Repository navigation
Expand file tree
/
Copy pathsettings.js
More file actions
1955 lines (1760 loc) · 70.6 KB
/
Copy pathsettings.js
File metadata and controls
1955 lines (1760 loc) · 70.6 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
// ============================================
// 弹窗模式(嵌入主窗口 iframe)
// ============================================
const IS_EMBEDDED = window.self !== window.top;
if (IS_EMBEDDED) {
document.body.classList.add('embedded');
// 父页面关闭弹窗前会通知保存(弹窗关闭不触发 beforeunload)
// 保存完成后回复父页面,等它关闭弹窗,避免异步操作(如密码哈希)未完成
window.addEventListener('message', (e) => {
if (e.data && e.data.type === 'saveSettings') {
Promise.resolve(saveSettings()).catch(() => {}).then(() => {
window.parent.postMessage({ type: 'settingsSaved' }, '*');
});
}
});
}
// ============================================
// 延迟初始化DOM元素
// ============================================
let themeSelect;
let backBtn;
let saveBtn;
let resetBtn;
let exportBtn;
let importBtn;
let importFile;
let colorInputs = {};
let presetBtns = [];
// 编辑器设置
let editorFontSize;
let editorTabSize;
let editorLineNumbers;
let editorLineWrapping;
let editorTheme;
let editorAutoSync;
let editorDevtools;
let itemKeyStyle;
let uiFont;
let editorFontFamily;
let prewarmFiles;
let prewarmFilesMax;
let prewarmKether;
let ceElementPickerEl;
let cePreviewEl;
let ceSwitchPreviewEl;
let cePreviewRefreshEl;
let cePreviewModeEl;
let ceDiagnosticsEl;
let mcAssetsPathEl;
let hidePremiumHintsEl;
let hideVersionHintsEl;
let mcAssetsBrowseBtn;
let mcAssetsDetectBtn;
let mcAssetsStatusEl;
// 个性化: 复选框标记
let checkboxMarkOnEl;
let checkboxMarkOffEl;
// 实验性功能开关
let experimentalRemoteEl;
let experimentalAiStudioEl;
// 积木块显示
let blockFontSize;
let catColorInputs = {};
// 快捷键设置
let shortcutInputs = {};
let resetShortcutsBtn;
let editShortcutsBtn;
// 远程设置
let remotePassword;
let remoteAllowDifferentVersions;
// AI 设置
let aiEndpoint;
let aiModel;
let aiCustomModel;
let aiCustomModelGroup;
let aiKeysList;
let aiNewKey;
let aiAddKeyBtn;
let aiSystemPrompt;
let aiCustomPrompt;
let aiMaxTokens;
let aiTemperature;
let aiPromptList;
let aiNewPromptName;
let aiNewPromptDesc;
let aiSavePromptBtn;
let aiPromptInfo;
// 背景图片
let bgGrid;
let bgOpacity;
let bgOpacityValue;
let bgUploadBtn;
let bgAppPath = '';
let bgImages = [];
// 默认配置
const defaultConfig = {
theme: 'dark',
itemKeyStyle: 'snake',
uiFont: '',
colors: {
primary: '#0098ff',
success: '#00c853',
warning: '#ffd600',
error: '#ff1744',
bgPrimary: '#000000',
bgSecondary: '#080808',
textPrimary: '#e0e0e0',
textSecondary: '#9e9e9e',
syntaxKeyword: '#569cd6',
syntaxString: '#ce9178',
syntaxNumber: '#b5cea8',
syntaxComment: '#6a9955',
syntaxFunction: '#dcdcaa',
syntaxOperator: '#d4d4d4',
syntaxPunctuation: '#d4d4d4',
syntaxProperty: '#9cdcfe',
checkboxOn: '#00c853',
checkboxOff: '#ff1744',
},
editor: {
fontSize: '14',
tabSize: '4',
lineNumbers: true,
lineWrapping: true,
theme: 'dracula',
fontFamily: '',
},
autoSync: false,
blockFontSize: '11',
categoryColors: {
'实体操作': '#c06262',
'数据与变量': '#5edf85',
'文本与运算': '#437a32',
'游戏机制': '#1566d1',
'系统管理': '#430000',
'逻辑判断': '#ddb271',
'世界与坐标': '#59745d',
'物品管理': '#615432',
'脚本控制': '#d115a8',
'界面与显示': '#3e5255',
'时间与日期': '#1a182c',
'基本': '#6b7475',
},
shortcuts: {
save: 'Ctrl+S',
newFile: 'Ctrl+N',
openProject: 'Ctrl+O',
toggleMode: 'F2',
find: 'Ctrl+F',
replace: 'Ctrl+H',
comment: 'Ctrl+/',
format: 'Shift+Alt+F',
},
background: {
filename: '',
opacity: 0.3,
},
remotePasswordHash: '',
allowDifferentVersions: false,
devTools: false,
prewarm: {
files: true,
filesMaxMb: 50,
kether: true,
},
// ---- CraftEngine 工具 ----
ceElementPicker: true, // 预载扫描 CE 元素 (补全按钮)
cePreview: true, // MC 场景预览
autoSwitchPreview: true, // 自动切换预览 (切条目时预览窗口跟着换)
previewRefresh: 'editor', // 预览刷新: editor (编辑器时刻刷新) / disk (从磁盘读取) / off (不刷新)
previewWindowMode: 'docked', // 预览窗口模式: docked (编辑器内浮动) / detached (独立系统窗口)
ceDiagnostics: true, // 配置错误检查 (ERROR/WARN/WEAK_WARN/INFO)
mcAssetsPath: '', // 原版 Minecraft assets 目录
hidePremiumHints: false, // 隐藏付费版提示
hideVersionHints: false, // 隐藏版本限制提示
// ---- 个性化: 复选框标记 (renderer 以 body class cb-mark-on/off 应用) ----
checkboxMarkOn: true, // 选中时显示 √ (缺省开启)
checkboxMarkOff: false, // 未选中时显示 ✕
// ---- 实验性功能 ----
experimental: {
remote: false, // 远程模式
aiStudio: false, // AI Studio (AI 面板)
},
ai: {
endpoint: 'https://api.openai.com/v1/chat/completions',
model: 'gpt-4o',
customModel: '',
keys: [],
systemPrompt: 'default',
customPrompt: '',
maxTokens: 4096,
temperature: 0.7,
},
};
// 预设主题配置
const presetThemes = {
'dark-default': {
theme: 'dark',
colors: {
primary: '#0098ff',
success: '#00c853',
warning: '#ffd600',
error: '#ff1744',
bgPrimary: '#000000',
bgSecondary: '#080808',
textPrimary: '#e0e0e0',
textSecondary: '#9e9e9e',
syntaxKeyword: '#569cd6',
syntaxString: '#ce9178',
syntaxNumber: '#b5cea8',
syntaxComment: '#6a9955',
syntaxFunction: '#dcdcaa',
syntaxOperator: '#d4d4d4',
syntaxPunctuation: '#d4d4d4',
syntaxProperty: '#9cdcfe',
},
},
'light-clean': {
theme: 'light',
colors: {
primary: '#0066cc',
success: '#107c10',
warning: '#ffb900',
error: '#e81123',
bgPrimary: '#ffffff',
bgSecondary: '#f3f3f3',
textPrimary: '#333333',
textSecondary: '#666666',
syntaxKeyword: '#569cd6',
syntaxString: '#ce9178',
syntaxNumber: '#b5cea8',
syntaxComment: '#6a9955',
syntaxFunction: '#dcdcaa',
syntaxOperator: '#d4d4d4',
syntaxPunctuation: '#d4d4d4',
syntaxProperty: '#9cdcfe',
},
},
dracula: {
theme: 'dark',
colors: {
primary: '#bd93f9',
success: '#50fa7b',
warning: '#f1fa8c',
error: '#ff5555',
bgPrimary: '#282a36',
bgSecondary: '#21222c',
textPrimary: '#f8f8f2',
textSecondary: '#6272a4',
syntaxKeyword: '#ff79c6',
syntaxString: '#f1fa8c',
syntaxNumber: '#bd93f9',
syntaxComment: '#6272a4',
syntaxFunction: '#50fa7b',
syntaxOperator: '#ff79c6',
syntaxPunctuation: '#f8f8f2',
syntaxProperty: '#8be9fd',
},
},
nord: {
theme: 'dark',
colors: {
primary: '#88c0d0',
success: '#a3be8c',
warning: '#ebcb8b',
error: '#bf616a',
bgPrimary: '#2e3440',
bgSecondary: '#3b4252',
textPrimary: '#eceff4',
textSecondary: '#d08770',
syntaxKeyword: '#81a1c1',
syntaxString: '#a3be8c',
syntaxNumber: '#b48ead',
syntaxComment: '#616e88',
syntaxFunction: '#88c0d0',
syntaxOperator: '#81a1c1',
syntaxPunctuation: '#d8dee9',
syntaxProperty: '#8fbcbb',
},
},
solarized: {
theme: 'dark',
colors: {
primary: '#268bd2',
success: '#859900',
warning: '#b58900',
error: '#dc322f',
bgPrimary: '#002b36',
bgSecondary: '#073642',
textPrimary: '#839496',
textSecondary: '#586e75',
syntaxKeyword: '#268bd2',
syntaxString: '#2aa198',
syntaxNumber: '#d33682',
syntaxComment: '#586e75',
syntaxFunction: '#b58900',
syntaxOperator: '#859900',
syntaxPunctuation: '#839496',
syntaxProperty: '#cb4b16',
},
},
};
// ============================================
// DOM加载完成后初始化
// ============================================
document.addEventListener('DOMContentLoaded', async () => {
console.log('[SETTINGS] DOMContentLoaded fired');
await I18N.ready;
// 初始化DOM元素
initializeDOMElements();
// 设置事件监听
setupEventListeners();
// 选项卡导航
initTabNavigation();
console.log('[SETTINGS] 初始化完成?');
});
// ============================================
// 初始化DOM元素
// ============================================
function initializeDOMElements() {
console.log('[SETTINGS] 初始化DOM元素');
themeSelect = document.getElementById('theme');
backBtn = document.getElementById('back-btn');
saveBtn = document.getElementById('save-settings');
resetBtn = document.getElementById('reset-settings');
exportBtn = document.getElementById('export-settings');
importBtn = document.getElementById('import-settings');
importFile = document.getElementById('import-file');
// 颜色输入
colorInputs = {
primary: document.getElementById('color-primary'),
success: document.getElementById('color-success'),
warning: document.getElementById('color-warning'),
error: document.getElementById('color-error'),
bgPrimary: document.getElementById('color-bg-primary'),
bgSecondary: document.getElementById('color-bg-secondary'),
textPrimary: document.getElementById('color-text-primary'),
textSecondary: document.getElementById('color-text-secondary'),
'syntax-keyword': document.getElementById('color-syntax-keyword'),
'syntax-string': document.getElementById('color-syntax-string'),
'syntax-number': document.getElementById('color-syntax-number'),
'syntax-comment': document.getElementById('color-syntax-comment'),
'syntax-function': document.getElementById('color-syntax-function'),
'syntax-operator': document.getElementById('color-syntax-operator'),
'syntax-punctuation': document.getElementById('color-syntax-punctuation'),
'syntax-property': document.getElementById('color-syntax-property'),
checkboxOn: document.getElementById('color-checkbox-on'),
checkboxOff: document.getElementById('color-checkbox-off'),
};
// 预设按钮
presetBtns = document.querySelectorAll('.preset-btn');
// 编辑器设置
editorFontSize = document.getElementById('editor-font-size');
editorTabSize = document.getElementById('editor-tab-size');
editorLineNumbers = document.getElementById('editor-line-numbers');
editorLineWrapping = document.getElementById('editor-line-wrapping');
editorTheme = document.getElementById('editor-theme');
editorAutoSync = document.getElementById('editor-auto-sync');
itemKeyStyle = document.getElementById('item-key-style');
uiFont = document.getElementById('ui-font');
editorFontFamily = document.getElementById('editor-font-family');
// 积木块显示
blockFontSize = document.getElementById('block-font-size');
catColorInputs = {};
document.querySelectorAll('.cat-color').forEach(el => {
catColorInputs[el.dataset.cat] = el;
});
// 快捷键输入
shortcutInputs = {
save: document.getElementById('shortcut-save'),
newFile: document.getElementById('shortcut-new-file'),
openProject: document.getElementById('shortcut-open-project'),
toggleMode: document.getElementById('shortcut-toggle-mode'),
find: document.getElementById('shortcut-find'),
replace: document.getElementById('shortcut-replace'),
comment: document.getElementById('shortcut-comment'),
format: document.getElementById('shortcut-format'),
};
// 背景图片
bgGrid = document.getElementById('bg-grid');
bgOpacity = document.getElementById('bg-opacity');
bgOpacityValue = document.getElementById('bg-opacity-value');
bgUploadBtn = document.getElementById('bg-upload-btn');
// 远程设置
remotePassword = document.getElementById('remote-password');
remoteAllowDifferentVersions = document.getElementById('remote-allow-different-versions');
// 开发者工具
editorDevtools = document.getElementById('editor-devtools');
// AI 设置
aiEndpoint = document.getElementById('ai-endpoint');
aiModel = document.getElementById('ai-model');
aiCustomModel = document.getElementById('ai-custom-model');
aiCustomModelGroup = document.getElementById('ai-custom-model-group');
aiKeysList = document.getElementById('ai-keys-list');
aiNewKey = document.getElementById('ai-new-key');
aiAddKeyBtn = document.getElementById('ai-add-key');
aiSystemPrompt = document.getElementById('ai-system-prompt');
aiCustomPrompt = document.getElementById('ai-custom-prompt');
aiMaxTokens = document.getElementById('ai-max-tokens');
aiTemperature = document.getElementById('ai-temperature');
aiPromptList = document.getElementById('ai-prompt-list');
aiNewPromptName = document.getElementById('ai-new-prompt-name');
aiNewPromptDesc = document.getElementById('ai-new-prompt-desc');
aiSavePromptBtn = document.getElementById('ai-save-prompt');
aiPromptInfo = document.getElementById('ai-prompt-info');
// 启动预热
prewarmFiles = document.getElementById('prewarm-files');
prewarmFilesMax = document.getElementById('prewarm-files-max');
prewarmKether = document.getElementById('prewarm-kether');
// CraftEngine 工具
ceElementPickerEl = document.getElementById('ce-element-picker');
cePreviewEl = document.getElementById('ce-preview');
ceSwitchPreviewEl = document.getElementById('ce-switch-preview');
cePreviewRefreshEl = document.getElementById('ce-preview-refresh');
cePreviewModeEl = document.getElementById('ce-preview-mode');
ceDiagnosticsEl = document.getElementById('ce-diagnostics');
mcAssetsPathEl = document.getElementById('mc-assets-path');
hidePremiumHintsEl = document.getElementById('hide-premium-hints');
hideVersionHintsEl = document.getElementById('hide-version-hints');
mcAssetsBrowseBtn = document.getElementById('mc-assets-browse');
mcAssetsDetectBtn = document.getElementById('mc-assets-detect');
mcAssetsStatusEl = document.getElementById('mc-assets-status');
// 个性化 / 实验性
checkboxMarkOnEl = document.getElementById('checkbox-mark-on');
checkboxMarkOffEl = document.getElementById('checkbox-mark-off');
experimentalRemoteEl = document.getElementById('experimental-remote');
experimentalAiStudioEl = document.getElementById('experimental-ai-studio');
bindCEToolEvents();
console.log(' - themeSelect:', !!themeSelect);
console.log(' - backBtn:', !!backBtn);
console.log(' - saveBtn:', !!saveBtn);
console.log(' - resetBtn:', !!resetBtn);
console.log(' - exportBtn:', !!exportBtn);
console.log(' - importBtn:', !!importBtn);
console.log(' - importFile:', !!importFile);
console.log(' - presetBtns count:', presetBtns.length);
console.log(' - colorInputs count:', Object.keys(colorInputs).length);
console.log(' - editorFontSize:', !!editorFontSize);
console.log(' - editorTabSize:', !!editorTabSize);
console.log(' - editorLineNumbers:', !!editorLineNumbers);
console.log(' - editorLineWrapping:', !!editorLineWrapping);
console.log(' - editorTheme:', !!editorTheme);
console.log(' - shortcutInputs count:', Object.keys(shortcutInputs).filter(key => shortcutInputs[key]).length);
}
// ============================================
// 选项卡导航
// ============================================
function initTabNavigation() {
const navItems = document.querySelectorAll('.settings-nav-item');
const panels = document.querySelectorAll('.settings-panel');
const panelsContainer = document.querySelector('.settings-panels');
if (!navItems.length || !panels.length) return;
function switchTab(tab) {
navItems.forEach((btn) => {
btn.classList.toggle('active', btn.dataset.tab === tab);
});
panels.forEach((panel) => {
panel.classList.toggle('active', panel.dataset.panel === tab);
});
if (panelsContainer) panelsContainer.scrollTop = 0;
sessionStorage.setItem('settingsActiveTab', tab);
}
navItems.forEach((btn) => {
btn.addEventListener('click', () => {
playSound('click');
switchTab(btn.dataset.tab);
});
});
// 恢复上次打开的选项卡
const saved = sessionStorage.getItem('settingsActiveTab');
if (saved && document.querySelector('.settings-nav-item[data-tab="' + CSS.escape(saved) + '"]')) {
switchTab(saved);
}
}
// ============================================
// 事件监听设置
// ============================================
function setupEventListeners() {
console.log('[SETTINGS] 设置事件监听');
// 主题选择
if (themeSelect) {
themeSelect.addEventListener('change', (e) => {
playSound('click');
console.log('[SETTINGS] 主题改变:', e.target.value);
applyTheme(e.target.value);
updateColorInputs();
});
}
// 字体选择(实时预览)
if (uiFont) {
uiFont.addEventListener('change', () => { playSound('click'); applyFonts(); });
}
if (editorFontFamily) {
editorFontFamily.addEventListener('change', () => { playSound('click'); applyFonts(); });
}
// 返回按钮
if (backBtn) {
backBtn.addEventListener('click', async () => {
playSound('back');
console.log('[SETTINGS] 返回到编辑器');
if (IS_EMBEDDED) {
// 弹窗模式:通知父页面关闭弹窗 (父页面会要求保存)
window.parent.postMessage({ type: 'closeSettings' }, '*');
} else {
// 独立页面:先落盘再导航,避免依赖 beforeunload (异步保存可能在卸载前没跑完)
try { await saveSettings(); } catch (e) { console.warn('[SETTINGS] 返回前保存失败:', e); }
window.location.href = 'index.html?fromSettings=1';
}
});
}
// 颜色输入
Object.values(colorInputs).forEach((input) => {
if (input) {
input.addEventListener('input', (e) => {
console.log('[SETTINGS] 颜色变更:', e.target.id, e.target.value);
updateCSSVariable(e.target.id, e.target.value);
updateColorValue(e.target.id);
});
input.addEventListener('change', () => { playSound('click'); });
}
});
// 分类颜色输入
Object.values(catColorInputs).forEach((input) => {
if (input) {
input.addEventListener('input', (e) => {
const valueEl = document.getElementById('cat-' + e.target.dataset.cat + '-value');
if (valueEl) valueEl.textContent = e.target.value.toUpperCase();
});
input.addEventListener('change', () => { playSound('click'); });
}
});
// 保存按钮
if (saveBtn) {
saveBtn.addEventListener('click', async () => {
playSound('save');
console.log('[SETTINGS] 保存设置');
await saveSettings();
});
}
// 重置按钮
if (resetBtn) {
resetBtn.addEventListener('click', () => {
playSound('update');
console.log('[SETTINGS] 重置设置');
resetSettings();
});
}
// 导出按钮
if (exportBtn) {
exportBtn.addEventListener('click', () => {
playSound('click');
console.log('[SETTINGS] 导出设置');
exportSettings();
});
}
// 导入按钮
if (importBtn) {
importBtn.addEventListener('click', () => {
playSound('click');
console.log('[SETTINGS] 导入设置');
if (importFile) {
importFile.click();
}
});
}
// 导入文件
if (importFile) {
importFile.addEventListener('change', importSettings);
}
// 预设主题
if (presetBtns && presetBtns.length > 0) {
presetBtns.forEach((btn) => {
btn.addEventListener('click', (e) => {
playSound('click');
const preset = e.target.dataset.preset;
console.log('[SETTINGS] 应用预设:', preset);
applyPreset(preset);
});
});
}
// 背景图片
if (bgOpacity) {
bgOpacity.addEventListener('input', (e) => {
const val = parseFloat(e.target.value);
if (bgOpacityValue) bgOpacityValue.textContent = val.toFixed(2);
applyBackgroundPreview();
});
}
if (bgUploadBtn) {
bgUploadBtn.addEventListener('click', () => { playSound('click'); uploadBackground(); });
}
// "无背景"点击
const noneItem = document.querySelector('.bg-none-item');
if (noneItem) {
noneItem.addEventListener('click', () => { playSound('close'); selectBackground(''); });
}
// 快捷键按钮
const resetShortcutBtn = document.getElementById('reset-shortcuts');
if (resetShortcutBtn) {
resetShortcutBtn.addEventListener('click', () => { playSound('update'); console.log('[SETTINGS] 重置快捷键'); });
}
const editShortcutBtn = document.getElementById('edit-shortcuts');
if (editShortcutBtn) {
editShortcutBtn.addEventListener('click', () => { playSound('click'); console.log('[SETTINGS] 编辑快捷键'); });
}
// AI 模型切换
if (aiModel) {
aiModel.addEventListener('change', function() {
if (aiCustomModelGroup) {
aiCustomModelGroup.style.display = this.value === 'custom' ? '' : 'none';
}
});
}
// AI 提示词切换
if (aiSystemPrompt) {
aiSystemPrompt.addEventListener('change', function() {
var val = this.value;
if (val === 'custom') {
if (aiCustomPromptGroup) aiCustomPromptGroup.style.display = '';
} else {
if (aiCustomPromptGroup) aiCustomPromptGroup.style.display = 'none';
// 从磁盘加载该提示词内容预览
if (window.electronAPI && window.electronAPI.ai && window.electronAPI.ai.loadPrompts) {
window.electronAPI.ai.loadPrompts().then(function(result) {
if (result.success && result.prompts[val]) {
if (aiCustomPrompt) aiCustomPrompt.value = result.prompts[val].content || '';
}
}).catch(function(err) { console.warn('Failed to load prompts:', err); });
}
}
updatePromptInfo(val, null, null);
// 重新获取 diskPrompts 更新信息
if (window.electronAPI && window.electronAPI.ai && window.electronAPI.ai.loadPrompts) {
window.electronAPI.ai.loadPrompts().then(function(result) {
if (result.success) {
var cfg2 = getFullConfig();
updatePromptInfo(val, result.prompts, (cfg2.ai && cfg2.ai.customPrompts) || {});
}
}).catch(function(err) { console.warn('Failed to load prompts:', err); });
}
});
}
// AI 保存自定义提示词
if (aiSavePromptBtn) {
aiSavePromptBtn.addEventListener('click', function() {
var name = aiNewPromptName ? aiNewPromptName.value.trim() : '';
var content = aiCustomPrompt ? aiCustomPrompt.value.trim() : '';
if (!name) { showNotification(I18N.t('settings.promptNameRequired'), 'error'); return; }
if (!content) { showNotification(I18N.t('settings.promptContentRequired'), 'error'); return; }
if (window.electronAPI && window.electronAPI.ai && window.electronAPI.ai.saveUserPrompt) {
window.electronAPI.ai.saveUserPrompt(name, content).then(function(result) {
if (result.success) {
showNotification(I18N.t('settings.promptSaved'), 'success');
loadAiPromptList();
} else {
showNotification(I18N.t('settings.promptSaveFailed', {msg: result.error || ''}), 'error');
}
}).catch(function(err) { console.warn('Failed to save user prompt:', err); });
} else {
// fallback: 保存到 localStorage
var cfg = getFullConfig();
if (!cfg.ai) cfg.ai = {};
cfg.ai.customPrompts = cfg.ai.customPrompts || {};
cfg.ai.customPrompts[name] = { desc: aiNewPromptDesc ? aiNewPromptDesc.value.trim() : '', content: content };
localStorage.setItem('editorConfig', JSON.stringify(cfg));
showNotification(I18N.t('settings.promptSavedLocal'), 'success');
loadAiPromptList();
}
});
}
// AI 添加密钥
if (aiAddKeyBtn) {
aiAddKeyBtn.addEventListener('click', function() {
var key = aiNewKey ? aiNewKey.value.trim() : '';
if (!key) { showNotification(I18N.t('settings.keyRequired'), 'error'); return; }
var config = getFullConfig();
var keys = config.ai && config.ai.keys ? config.ai.keys : [];
if (keys.includes(key)) { showNotification(I18N.t('settings.keyExists'), 'error'); return; }
keys.push(key);
if (!config.ai) config.ai = {};
config.ai.keys = keys;
localStorage.setItem('editorConfig', JSON.stringify(config));
if (aiNewKey) aiNewKey.value = '';
renderAiKeys(keys);
showNotification(I18N.t('settings.keyAdded'), 'success');
});
aiNewKey && aiNewKey.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && aiAddKeyBtn) aiAddKeyBtn.click();
});
}
// 语言切换:弹窗选择,只保存选择,重启后生效
// (热切换会造成设置页以外的界面残留旧语言、缓存失效,且刷新 iframe 会丢弃未保存的其他设置)
var langPickerBtn = document.getElementById('language-picker-btn');
var langOverlay = document.getElementById('lang-modal-overlay');
if (langPickerBtn && langOverlay) {
langPickerBtn.addEventListener('click', function() {
playSound('click');
openLangModal();
});
langOverlay.addEventListener('click', function(e) {
if (e.target === langOverlay) closeLangModal(); // 点击遮罩空白处关闭
});
document.getElementById('lang-modal-close').addEventListener('click', closeLangModal);
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape' && !langOverlay.hidden) closeLangModal();
});
document.getElementById('lang-modal-list').addEventListener('click', function(e) {
var opt = e.target.closest('.lang-option');
if (!opt) return;
playSound('click');
applyLanguageChoice(opt.dataset.lang);
});
syncLangModal();
updateLanguageRestartHint();
}
// 反馈按钮
document.querySelectorAll('.feedback-btn').forEach(function(btn) {
btn.addEventListener('click', function() {
playSound('click');
var url = this.dataset.url;
if (window.electronAPI && window.electronAPI.openExternal) {
window.electronAPI.openExternal(url);
} else {
window.open(url, '_blank');
}
});
});
console.log('[SETTINGS] 事件监听器设置完成?');
}
// 语言代码 → 显示名 (按当前界面语言表述, 避免英文界面里冒出"简体中文"这种混排)
var LANG_LABELS = {
zh_cn: { native: '简体中文', en: 'Chinese (Simplified)', zh: '简体中文' },
zh_tw: { native: '繁體中文', en: 'Chinese (Traditional)', zh: '繁體中文' },
en_us: { native: 'English', en: 'English', zh: '英语 (English)' },
de_de: { native: 'Deutsch', en: 'German', zh: '德语 (Deutsch)' },
es_es: { native: 'Español', en: 'Spanish', zh: '西班牙语 (Español)' },
fr_fr: { native: 'Français', en: 'French', zh: '法语 (Français)' },
ko_kr: { native: '한국어', en: 'Korean', zh: '韩语 (한국어)' },
ru_ru: { native: 'Русский', en: 'Russian', zh: '俄语 (Русский)' },
};
function languageLabel(code) {
var lb = LANG_LABELS[code];
if (!lb) return code;
if (I18N.lang === 'zh_cn') return lb.zh;
if (I18N.lang === 'zh_tw') return lb.native; // 繁中用户看得懂原文写法
return lb.en;
}
// ============================================
// 语言选择弹窗(旗帜列表)
// ============================================
function openLangModal() {
var overlay = document.getElementById('lang-modal-overlay');
if (!overlay) return;
syncLangModal();
overlay.hidden = false;
}
function closeLangModal() {
var overlay = document.getElementById('lang-modal-overlay');
if (overlay) overlay.hidden = true;
}
// 同步弹窗选中态与设置页按钮上的旗帜/名称
function syncLangModal() {
var overlay = document.getElementById('lang-modal-overlay');
if (!overlay) return;
var saved = getFullConfig().language;
var active = I18N.isSupported(saved) ? saved : I18N.lang;
var pending = active !== I18N.lang;
overlay.querySelectorAll('.lang-option').forEach(function(opt) {
opt.classList.toggle('active', opt.dataset.lang === active && !pending);
opt.classList.toggle('pending', opt.dataset.lang === active && pending);
});
// 设置页按钮: 显示当前生效语言(界面语言),与提示条分工一致
var btn = document.getElementById('language-picker-btn');
if (btn) {
var flagsEl = btn.querySelector('.lang-picker-flags');
var labelEl = btn.querySelector('.lang-picker-label');
if (flagsEl) flagsEl.innerHTML = langFlagsHtml(I18N.lang);
if (labelEl) labelEl.textContent = LANG_LABELS[I18N.lang] ? LANG_LABELS[I18N.lang].native : I18N.lang;
}
}
// 弹窗选项旗帜 HTML
function langFlagsHtml(code) {
var FLAG_FILES = { zh_cn: ['PRC'], zh_tw: ['HKN'], en_us: ['ENG', 'USA'], de_de: ['GER'], es_es: ['SPR'], fr_fr: ['FRA'], ko_kr: ['KOR'], ru_ru: ['SOV'] };
var files = FLAG_FILES[code] || [];
return files.map(function(f) {
return '<img src="images/flag/' + f + '.png" alt="">';
}).join('');
}
// 弹窗中选择语言: 选当前生效语言=关闭; 选其他=保存待重启
function applyLanguageChoice(next) {
if (next === I18N.lang) {
// 选当前界面语言 = 取消待重启的更改(若有)
var hadPending = I18N.isSupported(getFullConfig().language) && getFullConfig().language !== I18N.lang;
I18N.saveLang(next);
updateLanguageRestartHint();
syncLangModal();
closeLangModal();
if (hadPending) showNotification(I18N.t('settings.languageReverted'), 'info');
return;
}
I18N.saveLang(next);
updateLanguageRestartHint();
syncLangModal();
var msg = I18N.t('settings.languageRestartMessage', { lang: LANG_LABELS[next] ? LANG_LABELS[next].native : next });
if (window.UI && typeof UI.alert === 'function') {
UI.alert({ title: I18N.t('settings.languageRestartTitle'), message: msg });
} else {
showNotification(msg, 'info');
}
}
// 语言设置已保存但当前界面仍是旧语言(即等待重启)时,提示用户需要重启
function updateLanguageRestartHint() {
var hint = document.getElementById('language-restart-hint');
if (!hint) return;
var saved = getFullConfig().language;
var pending = I18N.isSupported(saved) && saved !== I18N.lang;
var key = pending ? 'settings.languageRestartPending' : 'settings.languageRestartHint';
// 待重启文案带 {lang} 参数: 去掉 data-i18n, 否则后续 applyDOM() 会用无参版本覆盖成 "{lang}"
if (pending) hint.removeAttribute('data-i18n');
else hint.setAttribute('data-i18n', key);
hint.classList.toggle('pending', pending);
hint.textContent = pending
? I18N.t(key, { lang: languageLabel(saved) })
: I18N.t(key);
if (!pending) return;
// 下拉框已回显当前生效语言, 无法靠"再选一次"取消, 这里给一个显式取消入口
var cancel = document.createElement('a');
cancel.href = 'javascript:void(0)';
cancel.textContent = ' ' + I18N.t('settings.languageCancelPending');
cancel.style.cssText = 'margin-left:6px;color:var(--color-primary);text-decoration:underline;';
cancel.addEventListener('click', function (e) {
e.preventDefault();
I18N.saveLang(I18N.lang);
updateLanguageRestartHint();
showNotification(I18N.t('settings.languageReverted'), 'info');
});
hint.appendChild(cancel);
}
// ============================================
// 主题应用
// ============================================
function applyTheme(theme) {
console.log('[SETTINGS] 应用主题:', theme);
document.body.setAttribute('data-theme', theme);
}
function applyPreset(presetName) {
console.log('[SETTINGS] 应用预设主题:', presetName);
const preset = presetThemes[presetName];
if (!preset) {
console.error('[SETTINGS] 预设不存在!', presetName);
return;
}
// 更新主题
if (themeSelect) {
themeSelect.value = preset.theme;
}
applyTheme(preset.theme);
// 更新颜色
Object.entries(preset.colors).forEach(([key, value]) => {
const inputId = `color-${camelToKebab(key)}`;
const input = document.getElementById(inputId);
if (input) {
input.value = value;
// 直接传入 inputId,不要再做转换
updateCSSVariable(inputId, value);
updateColorValue(inputId);
}
});
updatePresetButtonState(presetName);
}
function updatePresetButtonState(activePreset) {
presetBtns.forEach((btn) => {
if (btn.dataset.preset === activePreset) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
});
}
// ============================================
// 颜色管理
// ============================================
function updateCSSVariable(inputId, value) {
const cssVarName = `--color-${inputId.replace('color-', '')}`;
// 生成: --color-primary, --color-bg-primary 等
document.documentElement.style.setProperty(cssVarName, value);
}
function updateColorValue(inputId) {
const valueEl = document.getElementById(`${inputId}-value`);
const input = document.getElementById(inputId);
if (valueEl && input) {
valueEl.textContent = input.value.toUpperCase();
}
}
function updateColorValues() {
Object.keys(colorInputs).forEach((key) => {
const inputId = `color-${camelToKebab(key)}`;
updateColorValue(inputId);
});
}
function updateColorInputs() {
// 根据主题更新颜色输入框:清除自定义覆盖,恢复当前主题默认色,
// 避免保存的 colors 里残留旧主题色值(否则重启后被锁死导致主题切换失效)
var computedStyle = getComputedStyle(document.body);
Object.entries(colorInputs).forEach(([key, input]) => {
if (!input) return;
const cssVarName = `--color-${camelToKebab(key)}`;
document.documentElement.style.removeProperty(cssVarName);
const val = computedStyle.getPropertyValue(cssVarName).trim();
if (val) {
input.value = val;
updateColorValue(input.id);
}
});
console.log('[SETTINGS] 更新颜色输入,当前主题', themeSelect ? themeSelect.value : 'dark');