Repository navigation
Expand file tree
/
Copy pathchemdah-interpreter.js
More file actions
4764 lines (4292 loc) · 200 KB
/
Copy pathchemdah-interpreter.js
File metadata and controls
4764 lines (4292 loc) · 200 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
// ============================================
// Chemdah 插件解释器 — 核心模块 v1.0
// 功能:类型检测、对话解析、可视化渲染、双向同步
// ============================================
window.ChemdahInterpreter = (() => {
'use strict';
// ============================================
// 常量
// ============================================
const TYPES = {
CONVERSATION: 'conversation',
QUEST: 'quest',
UNKNOWN: 'unknown',
};
// 预设对话主题列表
const PRESET_THEMES = ['chat', 'chest', 'yosin-movie', 'bedrock'];
// 预设 flags
const PRESET_FLAGS = [
'FORCE_LOOK', 'FORCE_DISPLAY', 'LOOK_PLAYER',
'NO_EFFECT', 'NO_EFFECT:SLOW', 'NO_EFFECT:BLINDNESS',
'NO_EFFECT:SOUND', 'NO_EFFECT:PARTICLE', 'NO_MOVE', 'NO_SKIP',
];
// localStorage key
const STORAGE_KEY = 'chemdahTypeOverrides';
// ============================================
// 类型覆盖设置(持久化)
// ============================================
let _overrides = null;
function _loadOverrides() {
if (_overrides) return _overrides;
try {
const raw = localStorage.getItem(STORAGE_KEY);
_overrides = raw ? JSON.parse(raw) : {};
} catch { _overrides = {}; }
return _overrides;
}
function _saveOverrides() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(_overrides));
} catch {}
}
/** 设置类型覆盖 */
function setTypeOverride(path, type) {
const o = _loadOverrides();
if (type && type !== 'auto') {
o[path] = type;
} else {
delete o[path];
}
_saveOverrides();
}
/** 获取覆盖类型(没有则返回 null) */
function getTypeOverride(path) {
const o = _loadOverrides();
// 先检查精确路径匹配
if (o[path]) return o[path];
// 再检查父目录匹配
const parts = path.replace(/\\/g, '/').split('/');
for (let i = parts.length - 1; i > 0; i--) {
const dir = parts.slice(0, i).join('/');
if (o[dir]) return o[dir];
}
return null;
}
/** 获取所有覆盖 */
function getAllOverrides() {
return { ..._loadOverrides() };
}
/** 移除覆盖 */
function removeTypeOverride(path) {
const o = _loadOverrides();
delete o[path];
_saveOverrides();
}
// ============================================
// 项目类型检测
// ============================================
/**
* 检测项目目录下是否存在 conversation / quest 目录
* 返回 { hasConversation, hasQuest, types: [...] }
*/
async function detectProjectTypes(projectPath) {
const result = { hasConversation: false, hasQuest: false, types: [] };
if (!projectPath || !window.electronAPI) return result;
try {
const entries = await window.electronAPI.readdir(projectPath);
if (!entries.success) return result;
for (const f of entries.files) {
if (!f.isDirectory) continue;
const name = f.name.toLowerCase();
if (name === 'conversation') result.hasConversation = true;
if (name === 'quest') result.hasQuest = true;
}
} catch {}
if (result.hasConversation) result.types.push(TYPES.CONVERSATION);
if (result.hasQuest) result.types.push(TYPES.QUEST);
return result;
}
/**
* 检测单个文件的类型
* 优先检查用户覆盖 → 目录路径 → 内容启发式
*/
function detectFileType(filePath, content) {
// 1. 检查用户覆盖
const override = getTypeOverride(filePath);
if (override) return override;
// 2. 根据目录路径判断
const normalized = filePath.replace(/\\/g, '/').toLowerCase();
if (/\/conversation\//.test(normalized)) return TYPES.CONVERSATION;
if (/\/quest\//.test(normalized)) return TYPES.QUEST;
// 3. 内容启发式检测(需要 YAML 内容)
if (!content || content.trim().length === 0) return TYPES.UNKNOWN;
try {
const lines = content.split('\n');
const text = content;
// conversation 特征:有 __option__ 或 "npc id:" 或 "player:"
const hasOption = /__option__\s*:/.test(text);
const hasNpcId = /\n\s+npc\s+id\s*:/.test(text);
const hasPlayer = /\n\s+player\s*:/.test(text);
const hasNPC = /\n\s+npc\s*:[|>\s]/.test(text);
if (hasOption || hasNpcId || (hasPlayer && hasNPC)) {
return TYPES.CONVERSATION;
}
// quest 特征(常见字段)
const questPatterns = [
/\n\s*(quest|mission|task)_?(id|name|title)?\s*:/i,
/\n\s*(start|accept)_(npc|trigger)\s*:/i,
/\n\s*(objective|goal|stage)s?\s*:/i,
/\n\s*reward\s*:/i,
];
let questScore = 0;
for (const p of questPatterns) {
if (p.test(text)) questScore++;
}
if (questScore >= 2) return TYPES.QUEST;
} catch {}
return TYPES.UNKNOWN;
}
// ============================================
// 对话文件解析器
// ============================================
/**
* 解析对话 YAML 为结构化数据
* 返回 { options, dialogues }
*/
function parseConversation(content) {
const result = {
options: { theme: 'chat', title: '', flags: [] },
dialogues: [],
};
if (!content || !content.trim()) return result;
let data;
try {
data = jsyaml.load(content);
} catch (e) {
console.warn('[ChemdahInterpreter] YAML 解析失败,尝试容错解析:', e.message);
return { error: e.message, options: result.options, dialogues: [] };
}
if (!data || typeof data !== 'object') return result;
// 1. 解析 __option__
if (data.__option__) {
const opt = data.__option__;
if (opt.theme) result.options.theme = String(opt.theme);
if (opt.title) result.options.title = String(opt.title);
if (Array.isArray(opt.flags)) {
result.options.flags = opt.flags.map(String);
} else if (opt.flags) {
result.options.flags = [String(opt.flags)];
}
delete data.__option__;
}
// 2. 解析每个对话条目
for (const [name, entry] of Object.entries(data)) {
if (!entry || typeof entry !== 'object') continue;
if (name.startsWith('__') && name.endsWith('__')) continue; // skip YAML directives
const dialogue = {
name,
type: 'dialogue', // 'dialogue' | 'switch'
npcText: '',
npcId: '',
format: 'generic',
flags: [],
conditions: [], // for switch type
options: [], // for dialogue type (player replies)
_raw: {}, // 无法识别的字段, 编辑后原样写回
};
// 收集对话条目级未知字段 (npc/when/player 等已知字段之外的), 防止编辑后丢失
{
const knownKeys = ['npc', 'npcId', 'npc id', 'when', 'player', 'format', 'flags'];
for (const ek of Object.keys(entry)) {
if (!knownKeys.includes(ek)) dialogue._raw[ek] = entry[ek];
}
}
// 检测对话类型
if (entry.npcId || entry['npc id']) {
dialogue.type = 'switch';
dialogue.npcId = entry.npcId || entry['npc id'] || '';
}
if (entry.npc) {
dialogue.npcText = String(entry.npc);
// 已有 npc id 时保持 switch 类型(npc 是 switch 的默认文本), 否则是普通对话
if (!dialogue.npcId) dialogue.type = 'dialogue';
}
if (entry.format) dialogue.format = String(entry.format);
if (entry.flags) {
dialogue.flags = Array.isArray(entry.flags) ? entry.flags.map(String) : [String(entry.flags)];
}
// switch 类型的条件分支
if (entry.when && Array.isArray(entry.when)) {
for (const w of entry.when) {
if (w && typeof w === 'object') {
dialogue.conditions.push({
if: w.if !== undefined ? String(w.if) : 'true',
open: w.open !== undefined ? String(w.open) : '',
});
} else if (typeof w === 'string') {
dialogue.conditions.push({ if: 'true', open: w });
}
}
}
// dialogue 类型的玩家选项
if (entry.player && Array.isArray(entry.player)) {
for (const p of entry.player) {
if (p && typeof p === 'object') {
dialogue.options.push({
if: p.if !== undefined ? String(p.if) : null,
reply: p.reply !== undefined ? String(p.reply) : '',
then: p.then !== undefined ? String(p.then) : '',
});
}
}
}
// 也支持 switch 类型有 player(如带条件的 NPC 对话)
if (dialogue.type === 'switch' && entry.player && Array.isArray(entry.player)) {
for (const p of entry.player) {
if (p && typeof p === 'object') {
dialogue.options.push({
if: p.if !== undefined ? String(p.if) : null,
reply: p.reply !== undefined ? String(p.reply) : '',
then: p.then !== undefined ? String(p.then) : '',
});
}
}
}
result.dialogues.push(dialogue);
}
return result;
}
// ============================================
// 对话可视化渲染
// ============================================
function _escHtml(text) {
if (!text) return '';
const m = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
return String(text).replace(/[&<>"']/g, x => m[x]);
}
function _textToLines(text) {
if (!text) return [];
return String(text).split('\n');
}
/**
* 渲染对话文件的可视化编辑界面
*/
function renderConversationVisual(parsed, containerEl) {
if (!containerEl) return;
// 如果有解析错误
if (parsed.error) {
containerEl.innerHTML = `
<div class="cv-error-banner">
<span class="cv-error-icon">⚠️</span>
<div>
<strong>${I18N.t('chemdah.yamlError')}</strong>
<p>${_escHtml(parsed.error)}</p>
<p>${I18N.t('chemdah.yamlErrorHint')}</p>
</div>
</div>
`;
return;
}
const { options, dialogues } = parsed;
const viewMode = containerEl._cvViewMode || 'card';
// 卡片展开状态: 重渲染 (添加选项等操作) 后保留, 避免所有对话恢复折叠
if (!containerEl._cvOpenCards) containerEl._cvOpenCards = new Set();
else {
const cvNames = new Set(dialogues.map(d => d.name));
containerEl._cvOpenCards.forEach(n => { if (!cvNames.has(n)) containerEl._cvOpenCards.delete(n); });
}
let html = '<div class="cv-container">';
// === 左侧主内容区 ===
html += '<div class="cv-main-content">';
// === 文件选项面板 ===
html += _renderOptionsPanel(options);
// === 对话列表 / 思维导图 ===
if (viewMode === 'mindmap') {
html += '<div class="cv-mindmap-wrapper"><svg class="cv-mindmap-svg"></svg></div>';
} else {
html += '<div class="cv-dialogue-list">';
html += `<div class="cv-section-header">
<h3>${I18N.t('chemdah.dialoguesHeader')} <span class="cv-count">${dialogues.length}</span></h3>
<button class="cv-btn cv-btn-sm cv-btn-primary" data-action="add-dialogue">${I18N.t('chemdah.addDialogue')}</button>
</div>`;
if (dialogues.length === 0) {
html += '<div class="cv-empty">' + I18N.t('chemdah.noDialogues') + '</div>';
} else {
for (const d of dialogues) {
html += _renderDialogueCard(d, containerEl._cvOpenCards.has(d.name));
}
}
html += '</div>'; // cv-dialogue-list
}
// === 底部操作栏 ===
const toggleLabel = viewMode === 'mindmap' ? I18N.t('chemdah.cardView') : I18N.t('chemdah.mindmapView');
const toggleCls = viewMode === 'mindmap' ? 'cv-btn-primary' : 'cv-btn-secondary';
html += `<div class="cv-toolbar">
<button class="cv-btn cv-btn-primary" data-action="sync-to-source">${I18N.t('chemdah.syncToSource')}</button>
<label class="ke-auto-sync-toggle" style="font-size:12px;cursor:pointer;display:inline-flex;align-items:center;gap:4px;margin-left:8px;user-select:none;"><input type="checkbox" data-action="toggle-visual-autosync" ${window.__keAutoSync ? 'checked' : ''}> ${I18N.t('chemdah.autoSync')}</label>
<span class="cv-toolbar-hint">${I18N.t('chemdah.syncHint')}</span>
<button class="cv-btn cv-btn-sm ${toggleCls}" data-action="toggle-view" style="margin-left:auto">${toggleLabel}</button>
</div>`;
html += '</div>'; // cv-main-content
// === 右侧对话导航栏(思维导图模式下隐藏) ===
if (viewMode !== 'mindmap') {
html += '<div class="cv-sidebar">';
html += '<div class="cv-sidebar-header">' + I18N.t('chemdah.dialogueNav') + '</div>';
html += '<div class="cv-sidebar-list">';
for (const d of dialogues) {
const typeClass = d.type === 'switch' ? 'switch' : 'dialogue';
const typeLabel = d.type === 'switch' ? 'S' : 'D';
html += `<div class="cv-sidebar-item" data-action="sidebar-nav" data-sidebar-dialogue="${_escHtml(d.name)}" data-tip="${_escHtml(d.name)}">
<span class="cv-sidebar-type ${typeClass}">${typeLabel}</span>
<span class="cv-sidebar-name">${_escHtml(d.name)}</span>
</div>`;
}
html += '</div>'; // cv-sidebar-list
html += '</div>'; // cv-sidebar
}
html += '</div>'; // cv-container
containerEl.innerHTML = html;
// 如果是思维导图模式,初始化导图
if (viewMode === 'mindmap') {
const svgEl = containerEl.querySelector('.cv-mindmap-svg');
if (svgEl) _renderMindMapSVG(parsed, svgEl, containerEl);
}
// 绑定事件
_bindConversationEvents(containerEl, parsed);
}
function _renderOptionsPanel(options) {
let html = '<div class="cv-options-panel">';
html += '<div class="cv-section-header"><h3>' + I18N.t('chemdah.fileOptions') + '</h3></div>';
html += '<div class="cv-options-grid">';
// Theme
html += '<div class="cv-field">';
html += '<label>' + I18N.t('chemdah.theme') + '</label>';
const themeVal = _escHtml(options.theme || 'chat');
const isPreset = PRESET_THEMES.includes(themeVal);
html += `<div class="cv-select-wrapper">
<select class="cv-select" data-field="options.theme">
<option value="">${I18N.t('chemdah.customTheme')}</option>
${PRESET_THEMES.map(t =>
`<option value="${t}"${t === themeVal ? ' selected' : ''}>${t}</option>`
).join('')}
</select>
<input class="cv-input cv-theme-custom${isPreset ? ' hidden' : ''}"
data-field="options.theme.custom" value="${isPreset ? '' : themeVal}"
placeholder="${I18N.t('chemdah.customThemePlaceholder')}">
</div>`;
html += '</div>';
// Title
html += '<div class="cv-field">';
html += '<label>' + I18N.t('chemdah.title') + '</label>';
html += `<input class="cv-input" data-field="options.title" value="${_escHtml(options.title || '')}" placeholder="${I18N.t('chemdah.optionalTitle')}">`;
html += '</div>';
// Flags
html += '<div class="cv-field cv-field-wide">';
html += '<label>' + I18N.t('chemdah.flags') + '</label>';
html += '<div class="cv-flags-container">';
// 已有 flags
if (options.flags && options.flags.length > 0) {
for (const f of options.flags) {
html += `<span class="cv-flag" data-tag="${_escHtml(f)}">
${_escHtml(f)}
<span class="cv-flag-remove" data-action="remove-flag">×</span>
</span>`;
}
}
html += `<select class="cv-flag-add" data-action="add-flag">
<option value="">${I18N.t('chemdah.addFlag')}</option>
${PRESET_FLAGS.map(f =>
`<option value="${f}">${f}</option>`
).join('')}
<option value="__custom__">${I18N.t('chemdah.custom')}</option>
</select>`;
html += '</div></div>';
html += '</div></div>';
return html;
}
function _renderDialogueCard(d, isOpen) {
const isSwitch = d.type === 'switch';
const typeLabel = isSwitch ? I18N.t('chemdah.switch') : I18N.t('chemdah.dialogue');
const typeClass = isSwitch ? 'cv-type-switch' : 'cv-type-dialogue';
// 预览:显示简短信息
let preview = '';
if (isSwitch) {
const target = d.conditions.length > 0 ? d.conditions[0].open : '';
preview = target ? `→ ${target}` : I18N.t('chemdah.noCondition');
} else {
const optCount = d.options.length;
const npcFirst = d.npcText ? d.npcText.split('\n')[0].substring(0, 30) : '';
preview = npcFirst || I18N.t('chemdah.optionCount', {count: optCount});
}
let html = `<div class="cv-dialogue-card${isOpen ? ' expanded' : ' collapsed'}" data-dialogue="${_escHtml(d.name)}">`;
html += `<div class="cv-dialogue-header">
<span class="cv-header-toggle-area" data-action="toggle-card">
<span class="cv-toggle-arrow">▶</span>
<span class="cv-card-preview">${_escHtml(preview)}</span>
</span>
<span class="cv-dialogue-name">
<input class="cv-dialogue-name-input" value="${_escHtml(d.name)}"
data-field="dialogue.name" data-dialogue="${_escHtml(d.name)}">
</span>
<span class="cv-type-badge ${typeClass}">${typeLabel}</span>
<div class="cv-dialogue-actions">
<button class="cv-btn-icon" data-action="delete-dialogue" data-dialogue="${_escHtml(d.name)}"
data-tip="${I18N.t('chemdah.deleteDialogue')}">×</button>
</div>
</div>`;
if (isSwitch) {
// SWITCH 类型:NPC ID + 条件分支
html += '<div class="cv-dialogue-body">';
html += `<div class="cv-body-dialogue-id">${I18N.t('chemdah.dialogueIdPrefix', {id: _escHtml(d.name)})}</div>`;
html += '<div class="cv-field">';
html += '<label>' + I18N.t('chemdah.npcId') + '</label>';
html += `<input class="cv-input cv-input-mono" data-field="dialogue.npcId"
data-dialogue="${_escHtml(d.name)}" value="${_escHtml(d.npcId)}" placeholder="${I18N.t('chemdah.npcIdPlaceholder')}">`;
html += '</div>';
// 条件分支
html += `<div class="cv-conditions" data-dialogue="${_escHtml(d.name)}">`;
html += '<div class="cv-sub-header">';
html += '<label>' + I18N.t('chemdah.whenBranches') + '</label>';
html += `<button class="cv-btn cv-btn-xs cv-btn-secondary" data-action="add-condition"
data-dialogue="${_escHtml(d.name)}">${I18N.t('chemdah.addBranch')}</button>`;
html += '</div>';
if (d.conditions.length === 0) {
html += '<div class="cv-empty cv-empty-sm">' + I18N.t('chemdah.noWhenBranches') + '</div>';
} else {
for (let i = 0; i < d.conditions.length; i++) {
html += _renderConditionBranch(d.name, i, d.conditions[i]);
}
}
html += '</div>'; // cv-conditions
html += '</div>'; // cv-dialogue-body
// switch 类型也可能有 player 选项
if (d.options && d.options.length > 0) {
html += '<div class="cv-dialogue-section">';
html += _renderPlayerOptions(d.name, d.options);
html += '</div>';
}
} else {
// 普通对话类型
html += '<div class="cv-dialogue-body">';
html += `<div class="cv-body-dialogue-id">${I18N.t('chemdah.dialogueIdPrefix', {id: _escHtml(d.name)})}</div>`;
// NPC 对话文本
html += '<div class="cv-field cv-field-wide">';
html += '<label>' + I18N.t('chemdah.npcText') + '</label>';
const npcLines = _textToLines(d.npcText);
html += `<textarea class="cv-textarea" data-field="dialogue.npcText"
data-dialogue="${_escHtml(d.name)}" rows="${Math.max(3, npcLines.length)}"
placeholder="${I18N.t('chemdah.npcTextPlaceholder')}">${_escHtml(d.npcText)}</textarea>`;
html += '</div>';
// Format
html += '<div class="cv-field">';
html += '<label>' + I18N.t('chemdah.format') + '</label>';
html += `<input class="cv-input" data-field="dialogue.format"
data-dialogue="${_escHtml(d.name)}" value="${_escHtml(d.format)}" placeholder="generic">`;
html += '</div>';
// Flags per dialogue
if (d.flags && d.flags.length > 0) {
html += '<div class="cv-field">';
html += '<label>' + I18N.t('chemdah.tags') + '</label>';
html += `<span class="cv-tag-list">${d.flags.map(f =>
`<span class="cv-flag cv-flag-sm">${_escHtml(f)}</span>`
).join('')}</span>`;
html += '</div>';
}
html += '</div>'; // cv-dialogue-body
// 玩家选项
html += '<div class="cv-dialogue-section">';
html += _renderPlayerOptions(d.name, d.options);
html += '</div>';
}
html += '</div>'; // cv-dialogue-card
return html;
}
function _renderConditionBranch(dialogueName, index, cond) {
let html = `<div class="cv-condition" data-dialogue="${_escHtml(dialogueName)}" data-index="${index}">`;
html += '<div class="cv-condition-row">';
html += '<span class="cv-condition-label">' + I18N.t('chemdah.ifCondition') + '</span>';
html += `<input class="cv-input cv-input-mono" data-field="condition.if"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}"
value="${_escHtml(cond.if)}" placeholder="${I18N.t('chemdah.conditionPlaceholder')}">`;
html += '</div>';
html += '<div class="cv-condition-row">';
html += '<span class="cv-condition-label">' + I18N.t('chemdah.openJump') + '</span>';
html += `<input class="cv-input" data-field="condition.open"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}"
value="${_escHtml(cond.open)}" placeholder="${I18N.t('chemdah.targetDialoguePlaceholder')}">`;
html += `<button class="cv-btn-icon cv-btn-icon-danger" data-action="delete-condition"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}" data-tip="${I18N.t('chemdah.deleteBranch')}">×</button>`;
html += '</div>';
html += '</div>';
return html;
}
function _renderPlayerOptions(dialogueName, options) {
let html = '<div class="cv-player-options"';
html += ` data-dialogue="${_escHtml(dialogueName)}">`;
html += '<div class="cv-sub-header">';
html += '<label>' + I18N.t('chemdah.playerOptions') + '</label>';
html += `<button class="cv-btn cv-btn-xs cv-btn-secondary" data-action="add-option"
data-dialogue="${_escHtml(dialogueName)}">${I18N.t('chemdah.addOption')}</button>`;
html += '</div>';
if (!options || options.length === 0) {
html += '<div class="cv-empty cv-empty-sm">' + I18N.t('chemdah.noOptions') + '</div>';
} else {
for (let i = 0; i < options.length; i++) {
html += _renderPlayerOption(dialogueName, i, options[i]);
}
}
html += '</div>';
return html;
}
function _renderPlayerOption(dialogueName, index, opt) {
let html = `<div class="cv-player-option" data-dialogue="${_escHtml(dialogueName)}" data-index="${index}">`;
// 头部:条件和回复
html += '<div class="cv-option-header">';
if (opt.if) {
html += `<div class="cv-option-if-row">
<span class="cv-condition-label">${I18N.t('chemdah.condition')}</span>
<input class="cv-input cv-input-mono cv-input-sm" data-field="option.if"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}"
value="${_escHtml(opt.if)}">
</div>`;
}
html += `<div class="cv-option-reply-row">
<span class="cv-option-reply-icon">💬</span>
<input class="cv-input cv-option-reply-input" data-field="option.reply"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}"
value="${_escHtml(opt.reply)}" placeholder="${I18N.t('chemdah.optionTextPlaceholder')}">
</div>`;
html += '</div>';
// Then 脚本
const thenLines = _textToLines(opt.then);
html += `<div class="cv-option-then">
<label class="cv-label-sm">
<span class="cv-toggle-btn" data-action="toggle-then-vis"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}">▶</span>
${I18N.t('chemdah.thenScript')}
</label>
<textarea class="cv-textarea cv-textarea-code" data-field="option.then"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}"
rows="${Math.max(2, thenLines.length)}" placeholder="${I18N.t('chemdah.ketherScriptPlaceholder')}">${_escHtml(opt.then)}</textarea>
</div>`;
// 删除按钮
html += `<button class="cv-btn-icon cv-btn-icon-danger cv-option-delete"
data-action="delete-option"
data-dialogue="${_escHtml(dialogueName)}" data-index="${index}" data-tip="${I18N.t('chemdah.deleteOption')}">×</button>`;
html += '</div>';
return html;
}
// ============================================
// 对话编辑器事件绑定
// ============================================
function _bindConversationEvents(container, parsed) {
// 清除上次的点击事件代理(防止重复监听导致连点)
if (container._cvClickHandler) {
container.removeEventListener('click', container._cvClickHandler);
}
if (container._qvClickHandler) {
container.removeEventListener('click', container._qvClickHandler);
}
// 统一的点击事件代理
container._cvClickHandler = function (e) {
const btn = e.target.closest('[data-action]');
if (!btn) return;
const action = btn.dataset.action;
const dName = btn.dataset.dialogue;
switch (action) {
// ===== 卡片折叠/展开(点击箭头或预览区) =====
case 'toggle-card': {
const card = btn.closest('.cv-dialogue-card');
if (!card) break;
const isCollapsed = card.classList.contains('collapsed');
card.classList.toggle('collapsed', !isCollapsed);
card.classList.toggle('expanded', isCollapsed);
playSound('collapse');
// 更新侧栏高亮
const cardName = card.dataset.dialogue;
container.querySelectorAll('.cv-sidebar-item').forEach(el => {
el.classList.toggle('active', el.dataset.sidebarDialogue === cardName && isCollapsed);
});
// 记录展开状态, 重渲染后恢复
if (container._cvOpenCards && cardName) {
if (isCollapsed) container._cvOpenCards.add(cardName);
else container._cvOpenCards.delete(cardName);
}
break;
}
// ===== 侧栏导航点击 =====
case 'sidebar-nav': {
const targetName = btn.dataset.sidebarDialogue;
if (!targetName) break;
const targetCard = container.querySelector(`.cv-dialogue-card[data-dialogue="${_escHtml(targetName)}"]`);
if (targetCard) {
targetCard.classList.remove('collapsed');
targetCard.classList.add('expanded');
if (container._cvOpenCards && targetName) container._cvOpenCards.add(targetName);
targetCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
container.querySelectorAll('.cv-sidebar-item').forEach(el => {
el.classList.toggle('active', el.dataset.sidebarDialogue === targetName);
});
}
break;
}
// ===== 添加条件分支 =====
case 'add-condition':
if (dName) {
const d = parsed.dialogues.find(d => d.name === dName);
if (d) {
d.conditions.push({ if: 'true', open: '' });
if (window._cvRenderFn) window._cvRenderFn();
}
}
break;
// ===== 删除条件分支 =====
case 'delete-condition':
if (dName) {
const idx = parseInt(btn.dataset.index);
const d = parsed.dialogues.find(d => d.name === dName);
if (d && d.conditions[idx] !== undefined) {
d.conditions.splice(idx, 1);
if (window._cvRenderFn) window._cvRenderFn();
}
}
break;
// ===== 添加玩家选项 =====
case 'add-option':
if (dName) {
const d = parsed.dialogues.find(d => d.name === dName);
if (d) {
d.options.push({ if: null, reply: '', then: 'close' });
if (window._cvRenderFn) window._cvRenderFn();
}
}
break;
// ===== 删除玩家选项 =====
case 'delete-option':
if (dName) {
const idx = parseInt(btn.dataset.index);
const d = parsed.dialogues.find(d => d.name === dName);
if (d && d.options[idx] !== undefined) {
d.options.splice(idx, 1);
if (window._cvRenderFn) window._cvRenderFn();
}
}
break;
// ===== 添加对话 =====
case 'add-dialogue':
parsed.dialogues.push({
name: I18N.t('chemdah.newDialoguePrefix', {count: parsed.dialogues.length + 1}),
type: 'dialogue',
npcText: '',
npcId: '',
format: 'generic',
flags: [],
conditions: [{ if: 'true', open: '' }],
options: [{ if: null, reply: I18N.t('chemdah.defaultReply'), then: 'close' }],
});
if (window._cvRenderFn) window._cvRenderFn();
break;
// ===== 删除对话 =====
case 'delete-dialogue':
if (dName) {
const idx = parsed.dialogues.findIndex(d => d.name === dName);
if (idx !== -1) {
parsed.dialogues.splice(idx, 1);
if (window._cvRenderFn) window._cvRenderFn();
}
}
break;
// ===== 切换 then 脚本可见性 =====
case 'toggle-then-vis': {
const idx = parseInt(btn.dataset.index);
const textarea = container.querySelector(
`textarea[data-field="option.then"][data-dialogue="${_escHtml(dName)}"][data-index="${idx}"]`
);
if (textarea) {
textarea.classList.toggle('hidden');
btn.textContent = textarea.classList.contains('hidden') ? '▶' : '▼';
}
break;
}
// ===== 同步到源码 =====
case 'sync-to-source':
_syncConversationToSource(parsed);
break;
// ===== 切换自动同步 =====
case 'toggle-visual-autosync':
window.__keAutoSync = btn.checked;
// 更新本地存储配置
(function updateAutoSyncConfig(val) {
try {
var stored = localStorage.getItem('editorConfig');
var config = stored ? JSON.parse(stored) : {};
config.autoSync = val;
localStorage.setItem('editorConfig', JSON.stringify(config));
} catch (e) {}
})(window.__keAutoSync);
break;
// ===== 切换视图模式(卡片/思维导图) =====
case 'toggle-view':
container._cvViewMode = container._cvViewMode === 'mindmap' ? 'card' : 'mindmap';
if (window._cvRenderFn) window._cvRenderFn();
break;
// ===== 删除 flag =====
case 'remove-flag': {
const tag = btn.parentElement.dataset.tag;
if (tag) {
parsed.options.flags = parsed.options.flags.filter(f => f !== tag);
if (window._cvRenderFn) window._cvRenderFn();
}
break;
}
}
};
container.addEventListener('click', container._cvClickHandler);
// 音效包装:为所有 data-action 按钮添加点击音效
(function addCvSounds(c) {
var handler = c._cvClickHandler;
if (!handler) return;
var wrapped = function (e) {
var btn = e.target.closest('[data-action]');
if (btn) {
var action = btn.dataset.action;
if (action && action !== 'toggle-then-vis') {
if (action.indexOf('delete') >= 0 || action.indexOf('remove') >= 0) playSound('close');
else playSound('click');
}
}
handler(e);
};
c.removeEventListener('click', handler);
c._cvClickHandler = wrapped;
c.addEventListener('click', wrapped);
})(container);
// --- 文件选项 ---
// 主题选择
container.querySelectorAll('select[data-field="options.theme"]').forEach(el => {
el.addEventListener('change', function () {
const customInput = container.querySelector('.cv-theme-custom');
if (this.value === '') {
customInput.classList.remove('hidden');
customInput.focus();
} else {
customInput.classList.add('hidden');
parsed.options.theme = this.value;
}
});
});
container.querySelectorAll('.cv-theme-custom').forEach(el => {
el.addEventListener('change', function () {
parsed.options.theme = this.value;
});
el.addEventListener('input', function () {
parsed.options.theme = this.value;
});
});
// 标题
container.querySelectorAll('input[data-field="options.title"]').forEach(el => {
el.addEventListener('change', function () {
parsed.options.title = this.value;
});
});
// 添加 flag
container.querySelectorAll('select[data-action="add-flag"]').forEach(el => {
el.addEventListener('change', async function () {
let val = this.value;
if (!val) return;
if (val === '__custom__') {
val = await UI.prompt({ message: I18N.t('chemdah.customTagPrompt') });
if (!val) { this.value = ''; return; }
}
if (!parsed.options.flags.includes(val)) {
parsed.options.flags.push(val);
}
this.value = '';
// 重绘
if (window._cvRenderFn) window._cvRenderFn();
});
});
// --- 对话名称编辑 ---
if (container._cvCh1) container.removeEventListener('change', container._cvCh1);
container._cvCh1 = function (e) {
const input = e.target.closest('[data-field="dialogue.name"]');
if (input) {
const oldName = input.closest('[data-dialogue]').dataset.dialogue;
const newName = input.value.trim();
if (newName && newName !== oldName) {
const d = parsed.dialogues.find(d => d.name === oldName);
if (d) {
d.name = newName;
// 展开状态随重命名转移
if (container._cvOpenCards && container._cvOpenCards.has(oldName)) {
container._cvOpenCards.delete(oldName);
container._cvOpenCards.add(newName);
}
input.closest('[data-dialogue]').dataset.dialogue = newName;
// 更新所有关联的 data-dialogue 属性
const card = input.closest('.cv-dialogue-card');
card.querySelectorAll('[data-dialogue]').forEach(el => {
if (el !== input.closest('[data-dialogue]')) {
el.dataset.dialogue = newName;
}
});
card.dataset.dialogue = newName;
// 更新侧栏名称
const sidebarItem = container.querySelector(`.cv-sidebar-item[data-sidebar-dialogue="${_escHtml(oldName)}"]`);
if (sidebarItem) {
sidebarItem.dataset.sidebarDialogue = newName;
const nameSpan = sidebarItem.querySelector('.cv-sidebar-name');
if (nameSpan) nameSpan.textContent = newName;
sidebarItem.setAttribute('data-tip', newName);
}
}
}
}
};
container.addEventListener('change', container._cvCh1);
// --- NPC ID / NPC 文本 / Format 编辑 ---
if (container._cvCh2) container.removeEventListener('change', container._cvCh2);
container._cvCh2 = function (e) {
const input = e.target.closest('[data-field="dialogue.npcId"], [data-field="dialogue.format"]');
if (input) {
const field = input.dataset.field;
const dName = input.dataset.dialogue;
const d = parsed.dialogues.find(d => d.name === dName);
if (d) {
if (field === 'dialogue.npcId') d.npcId = input.value;
else if (field === 'dialogue.format') d.format = input.value;
}
}
};
container.addEventListener('change', container._cvCh2);
if (container._cvCh3) container.removeEventListener('change', container._cvCh3);
container._cvCh3 = function (e) {
const input = e.target.closest('[data-field="dialogue.npcText"]');
if (input) {
const dName = input.dataset.dialogue;
const d = parsed.dialogues.find(d => d.name === dName);
if (d) d.npcText = input.value;
}
};
container.addEventListener('change', container._cvCh3);
// --- 条件分支编辑 ---
if (container._cvCh4) container.removeEventListener('change', container._cvCh4);
container._cvCh4 = function (e) {
const input = e.target.closest('[data-field="condition.if"], [data-field="condition.open"]');
if (input) {
const field = input.dataset.field;
const dName = input.dataset.dialogue;
const idx = parseInt(input.dataset.index);
const d = parsed.dialogues.find(d => d.name === dName);
if (d && d.conditions[idx]) {
if (field === 'condition.if') d.conditions[idx].if = input.value;
else if (field === 'condition.open') d.conditions[idx].open = input.value;
}
}
};
container.addEventListener('change', container._cvCh4);
// --- 玩家选项编辑 ---
if (container._cvCh5) container.removeEventListener('change', container._cvCh5);
container._cvCh5 = function (e) {
const input = e.target.closest('[data-field^="option."]');
if (input) {
const field = input.dataset.field;
const dName = input.dataset.dialogue;
const idx = parseInt(input.dataset.index);