Repository navigation
Expand file tree
/
Copy pathrenderer.js
More file actions
4229 lines (3806 loc) · 155 KB
/
Copy pathrenderer.js
File metadata and controls
4229 lines (3806 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================
// 渲染进程主逻辑
// ============================================
let _electronAPI = window.electronAPI || null;
let codeMirrorEditor = null; // CodeMirror 实例
// DOM 元素
const fileTreeEl = document.getElementById('file-tree');
const editorContainer = document.getElementById('editor-textarea'); // 现在是一个 div 容器
const sourceEditor = document.getElementById('source-editor');
const visualEditor = document.getElementById('visual-editor');
const sourceModeBtn = document.getElementById('source-mode-btn');
const visualModeBtn = document.getElementById('visual-mode-btn');
const menuBar = document.getElementById('menu-bar');
const statusInfo = document.getElementById('status-info');
const filePathEl = document.getElementById('file-path');
const editorTabs = document.querySelector('.editor-tabs');
// 状态变量
let currentProjectPath = null;
let currentFile = null;
let files = [];
let openTabs = [];
let activeTab = null;
let isVisualMode = false;
let dirtyTabs = {}; // {filePath: true|false}
let autoSyncEnabled = false;
let autoSyncTimer = null;
// 文件夹树状态
let currentDirectoryPath = null;
let treeCache = {}; // (local|remote) 目录列表缓存: key = 模式前缀 + 路径
// 导航历史 (◀ 后退 / ▶ 前进): 条目为 {type:'file'|'directory', path}
let _navHistory = [];
let _navIndex = -1;
let _navSuppress = false; // 历史导航 / 恢复展开时跳过记录
const NAV_MAX = 100;
// 展开状态持久化: localStorage ceTreeExpanded = { [projectPath]: [path, ...] }
const EXPANDED_KEY = 'ceTreeExpanded';
function _loadExpandedPaths() {
try { return JSON.parse(localStorage.getItem(EXPANDED_KEY)) || {}; } catch (e) { return {}; }
}
function _saveExpandedPaths(map) {
try { localStorage.setItem(EXPANDED_KEY, JSON.stringify(map)); } catch (e) {}
}
function _addExpandedPath(path) {
if (!currentProjectPath) return;
const map = _loadExpandedPaths();
const arr = map[currentProjectPath] || (map[currentProjectPath] = []);
if (arr.indexOf(path) === -1) arr.push(path);
_saveExpandedPaths(map);
}
function _removeExpandedPath(path) {
if (!currentProjectPath) return;
const map = _loadExpandedPaths();
const arr = map[currentProjectPath];
if (!arr) return;
const i = arr.indexOf(path);
if (i >= 0) { arr.splice(i, 1); _saveExpandedPaths(map); }
}
function _treeCacheKey(path) {
return (_fmMode === 'remote' ? 'r:' : 'l:') + path;
}
// 远程文件管理
let _fmMode = 'local'; // 'local' | 'remote'
let _remoteFiles = [];
let _remoteDirPath = '';
let _otherEditingFiles = {}; // { filePath: true } 其他人正在编辑的文件
// ============================================
// 应用状态持久化
// ============================================
function saveAppState() {
try {
const state = {
currentProjectPath: currentProjectPath || null,
currentFile: currentFile || null,
openTabs: openTabs || [],
activeTab: activeTab || null,
};
localStorage.setItem('appState', JSON.stringify(state));
} catch (e) {
console.error('[RENDERER] 保存应用状态失败:', e);
}
}
function loadAutoSyncSetting() {
try {
const stored = localStorage.getItem('editorConfig');
if (stored) {
const config = JSON.parse(stored);
autoSyncEnabled = config.autoSync === true;
}
} catch (e) {
console.warn('[RENDERER] 加载自动同步设置失败:', e);
}
// 同步到全局标志供可视化编辑器使用
window.__keAutoSync = autoSyncEnabled;
}
async function restoreAppState() {
try {
const stored = localStorage.getItem('appState');
if (!stored) return;
const state = JSON.parse(stored);
if (!state.currentProjectPath) return;
currentProjectPath = state.currentProjectPath;
currentDirectoryPath = state.currentProjectPath;
const ok = await loadDirectory(state.currentProjectPath, true);
if (!ok) {
// 目录不可用,清除保存的状态
console.warn('[RENDERER] 保存的项目目录不可用,清除状态');
localStorage.removeItem('appState');
currentProjectPath = null;
currentDirectoryPath = null;
return;
}
// 检测项目类型
await _updateProjectTypeStatus(state.currentProjectPath);
// 恢复标签页
if (state.openTabs && state.openTabs.length > 0) {
// 先添加非活跃标签(只创建 tab DOM,不加载内容)
for (const tabPath of state.openTabs) {
if (tabPath !== state.activeTab && !openTabs.includes(tabPath)) {
openTabs.push(tabPath);
addTab(tabPath);
}
}
// 再打开活跃标签
if (state.activeTab && state.openTabs.includes(state.activeTab)) {
await openFile(state.activeTab);
}
}
} catch (e) {
console.warn('[RENDERER] 恢复应用状态失败:', e);
localStorage.removeItem('appState');
if (!currentProjectPath) {
currentProjectPath = null;
currentFile = null;
}
}
}
// ============================================
// 初始化 - 等待DOM和API就绪
// ============================================
document.addEventListener('DOMContentLoaded', async () => {
// 等待本地化字典就绪(首次启动时等待用户选择语言)
try { await I18N.ready; } catch (e) {}
setTimeout(async () => {
// 检查 electronAPI
if (!window.electronAPI) {
console.error('[RENDERER] electronAPI 不可用!');
showErrorDialog(
I18N.t('dialog.apiInitFailed'),
I18N.t('dialog.apiInitFailedMsg')
);
return;
}
_electronAPI = window.electronAPI;
init();
}, 300);
});
// ============================================
// CodeMirror 主题管理
// ============================================
function getCodeMirrorTheme() {
// 从 localStorage 读取配置
const stored = localStorage.getItem('editorConfig');
let editorTheme = 'dracula'; // 默认主题
if (stored) {
try {
const config = JSON.parse(stored);
// 优先使用用户选择的编辑器主题
if (config.editor && config.editor.theme) {
editorTheme = config.editor.theme;
} else {
// 根据应用主题选择默认主题
const appTheme = config.theme || 'dark';
editorTheme = appTheme === 'light' ? 'eclipse' : 'dracula';
}
} catch (e) {
console.error('[RENDERER] 解析 editorConfig 失败:', e);
}
}
return editorTheme;
}
function getEditorConfig() {
// 从 localStorage 读取配置
const stored = localStorage.getItem('editorConfig');
const defaultConfig = {
fontSize: '14',
tabSize: '4',
lineNumbers: true,
lineWrapping: true,
theme: 'dracula',
};
if (stored) {
try {
const config = JSON.parse(stored);
if (config.editor) {
return {
fontSize: config.editor.fontSize || defaultConfig.fontSize,
tabSize: config.editor.tabSize || defaultConfig.tabSize,
lineNumbers: config.editor.lineNumbers !== undefined ? config.editor.lineNumbers : defaultConfig.lineNumbers,
lineWrapping: config.editor.lineWrapping !== undefined ? config.editor.lineWrapping : defaultConfig.lineWrapping,
theme: config.editor.theme || defaultConfig.theme,
};
}
} catch (e) {
console.error('[RENDERER] 解析 editorConfig 失败:', e);
}
}
return defaultConfig;
}
function updateCodeMirrorTheme() {
if (!codeMirrorEditor) return;
const theme = getCodeMirrorTheme();
codeMirrorEditor.setOption('theme', theme);
}
// ============================================
// CodeMirror 初始化
// ============================================
function initCodeMirror() {
if (!editorContainer) {
console.error('[RENDERER] editorContainer 不存在');
return;
}
// 获取当前主题
const initialTheme = getCodeMirrorTheme();
// 创建 CodeMirror 实例
codeMirrorEditor = CodeMirror(editorContainer, {
lineNumbers: true,
lineWrapping: true,
theme: initialTheme,
mode: 'yaml',
indentUnit: 2,
tabSize: 2,
indentWithTabs: false,
extraKeys: {
'Tab': 'indentMore',
'Shift-Tab': 'indentLess',
},
placeholder: 'Open a file to start editing...',
autofocus: true,
});
// 暴露给 ChemdahInterpreter(可视化编辑器需要同步到源码)
window.codeMirrorEditor = codeMirrorEditor;
}
// ============================================
// 初始化函数
// ============================================
function init() {
initCodeMirror();
setupEventListeners();
// 应用已保存的配置(主题/字体/颜色/背景)
applyStoredConfig();
// 加载自动同步设置
loadAutoSyncSetting();
updateStatus(I18N.t('status.ready'));
// 从 desc/ 目录加载任务定义数据
loadQuestDefinitions();
// 启动预热(异步,不阻塞界面)
prewarmStartup();
// 监听 localStorage 变化,更新 CodeMirror 主题
window.addEventListener('storage', (e) => {
if (e.key === 'editorConfig') {
updateCodeMirrorTheme();
}
});
// 隐藏加载页面(从设置页返回时 inline script 已直接 display:none)
var splash = document.getElementById('splash-overlay');
if (splash && splash.style.display !== 'none') {
setTimeout(function() { splash.classList.add('hidden'); }, 400);
}
// 标题栏显示版本号(便于区分旧版/新版)
try {
if (window.electronAPI && window.electronAPI.appVersion) {
var tbt = document.querySelector('.title-bar-text');
if (tbt) tbt.textContent = 'Choten Editor v' + window.electronAPI.appVersion;
}
} catch (e) {}
// 恢复上次的会话
restoreAppState();
// CraftEngine 资源索引 / 预览 / 配置检查
try { initCETools(); } catch (e) { console.error('[CETools] init failed:', e); }
// Checks → Debug 窗口桥接 (重新扫描 / 打开并定位)
try { initChecksBridge(); } catch (e) { console.error('[Checks] init failed:', e); }
// 根据设置决定是否打开 DevTools
if (window.electronAPI && window.electronAPI.openDevTools) {
try {
var cfg = JSON.parse(localStorage.getItem('editorConfig') || '{}');
if (cfg.devTools === true) {
window.electronAPI.openDevTools();
}
} catch (_) {}
}
// 监听页面关闭/刷新,防止丢失未保存更改
window.addEventListener('beforeunload', function (e) {
if (window.__allowUnload) return;
var hasDirty = Object.values(dirtyTabs).some(function(v) { return v === true; });
if (hasDirty) {
e.preventDefault();
e.returnValue = '';
}
});
// 关闭窗口: 主进程拦下 close 后先问渲染进程, 这里跑未保存确认再放行。
// (否则 beforeunload 会静默吃掉关闭请求 → 标题栏/任务栏 ✕ 全部无反应)
if (_electronAPI.onBeforeClose) {
let closeConfirmPending = false;
_electronAPI.onBeforeClose(async function () {
if (closeConfirmPending) return; // 用户连点关闭: 只保留一个确认框
closeConfirmPending = true;
try {
if (window.__hasDirtyTabs && window.__showDirtyConfirm) {
const result = await window.__showDirtyConfirm('');
if (result === 'cancel') return; // 用户取消: 不关闭
if (result === 'save' && window.__saveAllDirtyFiles) {
await window.__saveAllDirtyFiles();
}
}
} catch (e) {
console.warn('[RENDERER] 关闭确认失败:', e);
} finally {
closeConfirmPending = false;
}
window.__allowUnload = true;
if (_electronAPI.confirmClose) _electronAPI.confirmClose();
else if (_electronAPI.close) _electronAPI.close();
});
}
}
// ============================================
// 事件监听设置
// ============================================
function setupEventListeners() {
// 检查元素是否存在
if (!sourceModeBtn) console.error('sourceModeBtn 不存在');
if (!visualModeBtn) console.error('visualModeBtn 不存在');
if (!codeMirrorEditor) console.error('codeMirrorEditor 不存在');
// 菜单栏初始化
initMenuBar();
// 编辑器模式按钮
if (sourceModeBtn) sourceModeBtn.addEventListener('click', async () => { playSound('click'); await switchEditorMode(false); });
if (visualModeBtn) visualModeBtn.addEventListener('click', async () => { playSound('click'); await switchEditorMode(true); });
// 编辑器文本框
if (codeMirrorEditor) codeMirrorEditor.on('change', handleEditorChange);
// 解释器类型选择器
const typeSelect = document.getElementById('interpreter-type-select');
if (typeSelect) {
typeSelect.addEventListener('change', function () {
playSound('click');
const val = this.value;
if (!currentFile || typeof ChemdahInterpreter === 'undefined') return;
if (val === 'auto') {
ChemdahInterpreter.removeTypeOverride(currentFile);
updateStatus(I18N.t('status.interpreterTypeAuto'));
} else {
ChemdahInterpreter.setTypeOverride(currentFile, val);
updateStatus(I18N.t('status.interpreterType', { type: typeLabel(val) }));
}
// 如果当前在可视化模式,重新渲染
if (isVisualMode && visualEditor) {
renderVisualEditor();
}
});
}
// 键盘快捷键 (从设置读取, 支持自定义组合键)
document.addEventListener('keydown', async function (e) {
const hit = (combo) => matchShortcut(e, combo);
if (hit(_ceShortcuts.save)) {
e.preventDefault();
playSound('save');
saveCurrentFile();
} else if (hit(_ceShortcuts.newFile)) {
e.preventDefault();
playSound('click');
createNewFile();
} else if (hit(_ceShortcuts.openProject)) {
e.preventDefault();
playSound('click');
openProject();
} else if (hit(_ceShortcuts.toggleMode)) {
e.preventDefault();
playSound('click');
// 检查是否可以对当前文件切换
if (currentFile && (currentFile.endsWith('.yml') || currentFile.endsWith('.yaml'))) {
await switchEditorMode(!isVisualMode);
}
} else if (hit(_ceShortcuts.previewWindow)) {
// Ctrl+Shift+P: 打开/聚焦预览独立窗口
e.preventDefault();
playSound('click');
if (window.CEPreviewPanel && window.CEPreviewPanel.detach) {
window.CEPreviewPanel.detach();
}
}
});
// 文件管理器选项卡切换
document.querySelectorAll('.fm-tab').forEach(function(tab) {
tab.addEventListener('click', function() {
var mode = this.dataset.fm;
if (mode === _fmMode) return;
_fmMode = mode;
document.querySelectorAll('.fm-tab').forEach(function(t) { t.classList.remove('active'); });
this.classList.add('active');
// 显示/隐藏删除按钮
document.getElementById('fm-delete').style.display = 'none';
if (mode === 'remote') {
// 切换到远程:清空树并请求远程根列表
renderTree(null, []);
if (window.electronAPI && window.electronAPI.remote) {
window.electronAPI.remote.getClientStatus().then(function(rs) {
if (rs && rs.connected) {
window.electronAPI.remote.requestFileList({ dirPath: _remoteDirPath || '/' });
}
}).catch(function() {});
}
} else {
// 切换到本地:重新加载当前目录
if (currentDirectoryPath) {
loadDirectory(currentDirectoryPath, true);
}
}
});
});
// 重新加载按钮
var reloadBtn = document.getElementById('fm-reload');
if (reloadBtn) {
reloadBtn.addEventListener('click', function() {
playSound('click');
refreshTree();
});
}
// 导航按钮: ◀ 后退 / ▶ 前进
var navBackBtn = document.getElementById('nav-back');
if (navBackBtn) {
navBackBtn.addEventListener('click', function() { playSound('click'); navBack(); });
}
var navForwardBtn = document.getElementById('nav-forward');
if (navForwardBtn) {
navForwardBtn.addEventListener('click', function() { playSound('click'); navForward(); });
}
// ▲ 上一个文件 / ▼ 下一个文件 (当前目录循环)
var navPrevBtn = document.getElementById('nav-prev');
if (navPrevBtn) {
navPrevBtn.addEventListener('click', function() { playSound('click'); navAdjacentFile(-1); });
}
var navNextBtn = document.getElementById('nav-next');
if (navNextBtn) {
navNextBtn.addEventListener('click', function() { playSound('click'); navAdjacentFile(1); });
}
// 删除按钮
var deleteBtn = document.getElementById('fm-delete');
if (deleteBtn) {
deleteBtn.addEventListener('click', async function() {
var selected = fileTreeEl.querySelector('.tree-row.selected');
if (!selected) return;
var path = selected.dataset.path;
if (!path) return;
if (!(await UI.confirm({ message: I18N.t('confirm.deleteFile', { name: getFileName(path) }) }))) return;
playSound('click');
if (_fmMode === 'remote') {
if (window.electronAPI && window.electronAPI.remote) {
window.electronAPI.remote.requestFileDelete({ filePath: path });
setRemoteStatus('rm-client-status', I18N.t('rm.requestingDelete'));
}
} else {
// 本地删除
try {
await _electronAPI.deleteFile(path);
refreshTree();
} catch (e) {
showErrorDialog(I18N.t('dialog.deleteFailed'), e.message);
}
}
});
}
// 文件树事件委托: 右键选中 + 点击选中/展开/打开
if (fileTreeEl) {
fileTreeEl.addEventListener('contextmenu', function(e) {
var row = e.target.closest('.tree-row');
if (row) {
fileTreeEl.querySelectorAll('.tree-row.selected').forEach(function(el) { el.classList.remove('selected'); });
row.classList.add('selected');
document.getElementById('fm-delete').style.display = '';
e.preventDefault();
var li = row.closest('li.tree-item');
var path = row.dataset.path;
var isDir = !!(li && li.classList.contains('directory'));
showTreeContextMenu(e, path, isDir);
}
});
fileTreeEl.addEventListener('click', async function(e) {
var row = e.target.closest('.tree-row');
fileTreeEl.querySelectorAll('.tree-row.selected').forEach(function(el) { el.classList.remove('selected'); });
if (!row) return;
row.classList.add('selected');
var li = row.closest('li.tree-item');
if (!li || !li._file) return;
playSound('click');
await handleFileClick(li._file, li);
});
}
}
// ============================================
// 菜单栏 (文件/编辑/调试/设置/帮助)
// ============================================
// 最近打开记录: localStorage ceRecentProjects / ceRecentFiles = [{path, name, time}]
const RECENT_PROJECTS_KEY = 'ceRecentProjects';
const RECENT_FILES_KEY = 'ceRecentFiles';
const RECENT_MAX = 10;
function _loadRecent(key) {
try { return JSON.parse(localStorage.getItem(key)) || []; } catch (e) { return []; }
}
function _saveRecent(key, list) {
try { localStorage.setItem(key, JSON.stringify(list)); } catch (e) {}
}
function _addRecent(key, filePath) {
const list = _loadRecent(key);
const entry = { path: filePath, name: getFileName(filePath), time: Date.now() };
const idx = list.findIndex((it) => it.path === filePath);
if (idx >= 0) list.splice(idx, 1);
list.unshift(entry);
if (list.length > RECENT_MAX) list.length = RECENT_MAX;
_saveRecent(key, list);
}
function addRecentProject(path) {
if (path) _addRecent(RECENT_PROJECTS_KEY, path);
}
function addRecentFile(path) {
if (path) _addRecent(RECENT_FILES_KEY, path);
}
function clearRecent() {
localStorage.removeItem(RECENT_PROJECTS_KEY);
localStorage.removeItem(RECENT_FILES_KEY);
}
// 渲染「最近打开」子菜单
function renderRecentMenu() {
const panel = document.getElementById('menu-recent-panel');
if (!panel) return;
panel.innerHTML = '';
const projects = _loadRecent(RECENT_PROJECTS_KEY);
const files = _loadRecent(RECENT_FILES_KEY);
function addGroup(title, list, isProject) {
const gt = document.createElement('div');
gt.className = 'menu-group-title';
gt.textContent = title;
panel.appendChild(gt);
if (!list.length) {
const empty = document.createElement('button');
empty.className = 'menu-entry';
empty.disabled = true;
empty.textContent = I18N.t('menu.empty');
panel.appendChild(empty);
return;
}
list.forEach((item) => {
const btn = document.createElement('button');
btn.className = 'menu-entry recent-item';
btn.dataset.recentType = isProject ? 'project' : 'file';
btn.dataset.recentPath = item.path;
btn.textContent = item.name;
btn.title = item.path;
btn.addEventListener('click', () => {
closeMenus();
if (isProject) {
playSound('click');
openProjectPath(item.path);
} else {
playSound('click');
openFile(item.path);
}
});
panel.appendChild(btn);
});
}
addGroup(I18N.t('menu.recentProjects'), projects, true);
addGroup(I18N.t('menu.recentFiles'), files, false);
const sep = document.createElement('div');
sep.className = 'menu-sep';
panel.appendChild(sep);
const clear = document.createElement('button');
clear.className = 'menu-entry';
clear.textContent = I18N.t('menu.clearRecent');
clear.addEventListener('click', () => {
clearRecent();
renderRecentMenu();
});
panel.appendChild(clear);
}
function closeMenus() {
if (!menuBar) return;
menuBar.querySelectorAll('.menu-item-wrap.open').forEach((w) => w.classList.remove('open'));
}
function cmExecCommand(cmd) {
if (codeMirrorEditor) {
codeMirrorEditor.focus();
codeMirrorEditor.execCommand(cmd);
}
}
// 文件 → 打开文件…: 对话框选择单个文件并打开
async function openFileDialog() {
if (!_electronAPI || !_electronAPI.openFile) {
showErrorDialog(I18N.t('dialog.apiError'), I18N.t('error.openDirectoryApi'));
return;
}
const result = await _electronAPI.openFile({
properties: ['openFile'],
filters: [
{ name: 'YAML', extensions: ['yml', 'yaml'] },
{ name: I18N.t('menu.allFiles'), extensions: ['*'] },
],
});
if (result && result.length > 0) {
await openFile(result[0]);
addRecentFile(result[0]);
}
}
async function closeAllTabs() {
const snapshot = openTabs.slice();
for (const p of snapshot) {
await closeTab(p, true);
}
}
// Help → 关于: 富内容弹窗 (反馈渠道 + 作者卡片), 原设置在设置页内, 已移至此处
function showAbout() {
let version = '1.0.0';
try {
if (window.electronAPI && window.electronAPI.appVersion) {
version = window.electronAPI.appVersion;
}
} catch (e) {}
const overlay = document.createElement('div');
overlay.className = 'ui-overlay';
const modal = document.createElement('div');
modal.className = 'ui-modal about-modal';
modal.setAttribute('role', 'dialog');
const title = document.createElement('div');
title.className = 'ui-modal-title';
title.textContent = 'Choten Editor v' + version;
const body = document.createElement('div');
body.className = 'ui-modal-body about-body';
body.style.whiteSpace = 'normal';
const feedback = document.createElement('div');
feedback.className = 'about-feedback';
const intro = document.createElement('div');
intro.className = 'about-intro';
intro.textContent = I18N.t('settings.feedbackIntro');
feedback.appendChild(intro);
const channels = [
{ label: I18N.t('settings.feedbackQqGroup') + ' 858827523', url: 'https://qm.qq.com/q/f7l7qPlY60', btn: I18N.t('settings.feedbackJoinQq') },
{ label: '🌐 Discord', url: 'https://discord.com/invite/VHs958jJXj', btn: I18N.t('settings.feedbackJoinDiscord') },
{ label: I18N.t('settings.feedbackQq') + ' 3631901756', url: 'https://qm.qq.com/q/f7l7qPlY60', btn: I18N.t('settings.feedbackAddFriend') },
];
channels.forEach((c) => {
const row = document.createElement('div');
row.className = 'about-feedback-row';
const label = document.createElement('span');
label.textContent = c.label;
const btn = document.createElement('button');
btn.className = 'ui-btn ui-btn-secondary';
btn.textContent = c.btn;
btn.addEventListener('click', () => {
if (window.electronAPI && window.electronAPI.openExternal) {
window.electronAPI.openExternal(c.url);
} else {
window.open(c.url, '_blank');
}
});
row.appendChild(label);
row.appendChild(btn);
feedback.appendChild(row);
});
body.appendChild(feedback);
const author = document.createElement('div');
author.className = 'about-author';
const authorTitle = document.createElement('div');
authorTitle.className = 'about-author-title';
authorTitle.textContent = I18N.t('settings.aboutAuthor');
const img = document.createElement('img');
img.src = 'images/author.png';
img.alt = 'Author';
author.appendChild(authorTitle);
author.appendChild(img);
body.appendChild(author);
const actions = document.createElement('div');
actions.className = 'ui-modal-actions';
const okBtn = document.createElement('button');
okBtn.className = 'ui-btn ui-btn-primary';
okBtn.textContent = I18N.t('ui.ok');
actions.appendChild(okBtn);
modal.appendChild(title);
modal.appendChild(body);
modal.appendChild(actions);
overlay.appendChild(modal);
document.body.appendChild(overlay);
requestAnimationFrame(() => overlay.classList.add('show'));
function close() {
overlay.classList.remove('show');
setTimeout(() => {
if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
}, 160);
}
okBtn.addEventListener('click', close);
overlay.addEventListener('mousedown', (e) => {
if (e.target === overlay) close();
});
overlay.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
e.stopPropagation();
close();
}
});
okBtn.focus();
}
function initMenuBar() {
if (!menuBar) return;
// 快捷键提示 (从设置读取的自定义组合键)
menuBar.querySelectorAll('.menu-entry[data-action]').forEach((btn) => {
const action = btn.dataset.action;
const combo = action === 'save' ? _ceShortcuts.save
: action === 'new-file' ? _ceShortcuts.newFile
: action === 'open-project' ? _ceShortcuts.openProject
: null;
if (combo) {
const key = document.createElement('span');
key.className = 'menu-key';
key.textContent = combo;
btn.appendChild(key);
}
});
// 点击触发器: 展开/折叠
menuBar.querySelectorAll('.menu-trigger').forEach((trigger) => {
trigger.addEventListener('click', (e) => {
e.stopPropagation();
const wrap = trigger.closest('.menu-item-wrap');
const isOpen = wrap.classList.contains('open');
closeMenus();
if (!isOpen) {
wrap.classList.add('open');
if (wrap.dataset.menu === 'file') renderRecentMenu();
}
});
});
// 展开状态下 hover 到其他菜单 → 切换 (先关后开, 避免多菜单同时展开)
menuBar.querySelectorAll('.menu-item-wrap').forEach((wrap) => {
wrap.addEventListener('mouseenter', () => {
if (menuBar.querySelector('.menu-item-wrap.open') && !wrap.classList.contains('open')) {
closeMenus();
wrap.classList.add('open');
if (wrap.dataset.menu === 'file') renderRecentMenu();
}
});
});
// 点击菜单外部关闭
document.addEventListener('mousedown', (e) => {
if (menuBar.contains(e.target)) return;
closeMenus();
});
// Esc 关闭
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && menuBar.querySelector('.menu-item-wrap.open')) {
closeMenus();
}
});
// 动作分发 (委托, 覆盖动态生成的最近打开条目)
menuBar.addEventListener('click', (e) => {
const entry = e.target.closest('.menu-entry');
if (!entry || entry.dataset.recentType) return; // 最近条目自绑监听
const action = entry.dataset.action;
if (!action || entry.disabled) return;
if (action !== 'recent') closeMenus();
switch (action) {
case 'new-file': playSound('click'); createNewFile(); break;
case 'new-folder': playSound('click'); createNewFolder(); break;
case 'open-file': playSound('click'); openFileDialog(); break;
case 'open-project': playSound('click'); openProject(); break;
case 'save': playSound('save'); saveCurrentFile(); break;
case 'close-tab': if (currentFile) closeTab(currentFile); break;
case 'close-all-tabs': closeAllTabs(); break;
case 'undo': cmExecCommand('undo'); break;
case 'redo': cmExecCommand('redo'); break;
case 'cut': cmExecCommand('cut'); break;
case 'copy': cmExecCommand('copy'); break;
case 'paste': cmExecCommand('paste'); break;
case 'select-all': cmExecCommand('selectAll'); break;
case 'settings': playSound('select'); openSettings(); break;
case 'checks-debug': playSound('select'); openChecksDebug(); break;
case 'remote': playSound('select'); openRemoteMode(); break;
case 'ai': playSound('select'); openAIPanel(); break;
case 'about': showAbout(); break;
case 'recent':
// 子菜单: 打开文件菜单时已渲染, 点击保持展开
renderRecentMenu();
break;
default: break;
}
});
}
// ============================================
// 打开项目
// ============================================
// 检测项目类型并更新状态栏消息
async function _updateProjectTypeStatus(path) {
if (typeof ChemdahInterpreter !== 'undefined') {
const types = await ChemdahInterpreter.detectProjectTypes(path);
let typeMsg = I18N.t('status.projectOpened', { name: getFileName(path) });
if (types.hasConversation && types.hasQuest) {
typeMsg += I18N.t('status.projectTypesConversationQuest');
} else if (types.hasConversation) {
typeMsg += I18N.t('status.projectTypesConversation');
} else if (types.hasQuest) {
typeMsg += I18N.t('status.projectTypesQuest');
}
// CraftEngine 工程级检测 (pack.yml namespace / config.yml 插件根特征)
if (typeof CraftEngineInterpreter !== 'undefined' && CraftEngineInterpreter.detectProjectTypes) {
try {
const ce = await CraftEngineInterpreter.detectProjectTypes(path);
if (ce && ce.isCraftEngine) {
typeMsg += I18N.t('status.ceProjectDetected');
}
} catch (e) {}
}
updateStatus(typeMsg);
} else {
updateStatus(I18N.t('status.projectOpened', { name: getFileName(path) }));
}
}
async function openProject() {
if (!_electronAPI || !_electronAPI.openDirectory) {
showErrorDialog(I18N.t('dialog.apiError'), I18N.t('error.openDirectoryApi'));
return;
}
try {
const result = await _electronAPI.openDirectory();
if (result && result.length > 0) {
await openProjectPath(result[0]);
}
} catch (error) {
console.error('[RENDERER] 打开项目错误:', error);
showErrorDialog(I18N.t('dialog.openProjectFailed'), error.message || error);
}
}
async function openProjectPath(path) {
currentProjectPath = path;
currentDirectoryPath = path;
await loadDirectory(path);
// 检测项目中的类型
await _updateProjectTypeStatus(path);
saveAppState();
// 记录最近打开项目
addRecentProject(path);
}
// ============================================
// 加载目录
// ============================================
async function loadDirectory(path, silent = false) {
if (!_electronAPI || !_electronAPI.readdir) {
if (!silent) showErrorDialog(I18N.t('dialog.apiError'), I18N.t('error.readdirApi'));
return false;
}
try {
const result = await _electronAPI.readdir(path);
if (result.success) {
files = result.files;
currentDirectoryPath = path;
renderTree(path, files);
updateStatus(I18N.t('status.directory', { path: path }));
if (!_navSuppress) _pushNav('directory', path);
return true;
} else {
if (!silent) showErrorDialog(I18N.t('dialog.loadDirFailed'), result.error);
return false;
}
} catch (error) {
console.error('[RENDERER] 加载目录错误:', error);
if (!silent) showErrorDialog(I18N.t('dialog.loadDirError'), error.message || error);
return false;
}
}
// ============================================
// 文件树渲染 (VSCode 风格可折叠树, 懒加载)
// ============================================
// 渲染树的根层; rootPath 为本地项目根时懒恢复持久化的展开状态
function renderTree(rootPath, files) {
if (!fileTreeEl) return;
fileTreeEl.innerHTML = '';
files.forEach((file) => {
fileTreeEl.appendChild(buildTreeItem(file));
});
if (_fmMode !== 'remote' && rootPath) {
restoreExpanded(rootPath);
}