BlueGit

timfa questward

Files

questward / client / src / editor / dialoguesModal.js

dialoguesModal.js

dialoguesModal.js 24.7 KiB Download Raw
1import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";
2import { emptyConditionSet } from "/shared/quests/conditions.js";
3import {
4 dialogueTakeIsUnguaranteed,
5 unguaranteedDialogueTakes
6} from "/shared/quests/dialoguePathTakes.js";
7import {
8 applyDialogueTextReplacements,
9 dialogueReplacementCatalog
10} from "/shared/speech/dialogueText.js";
11import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
12import { renderConditionSet } from "./conditionSetEditor.js";
13import { initDialogueSimulate } from "./dialogueSimulate.js";
14
15export function initDialoguesModal ({
16 socket,
17 MessageType,
18 describeWorldTile = null,
19 centerEditorOnTile = null,
20 getDimensionOptions = null
21})
22{
23 const backdrop = document.getElementById("dialogues-backdrop");
24 const modal = document.getElementById("dialogues-modal");
25 const listEl = document.getElementById("dialogues-list");
26 const editorEl = document.getElementById("dialogues-editor");
27 const saveBtn = document.getElementById("dialogues-save");
28 const deleteBtn = document.getElementById("dialogues-delete");
29 const simulateBtn = document.getElementById("dialogues-simulate");
30 const tokensBackdrop = document.getElementById("dialogue-tokens-backdrop");
31 const tokensModal = document.getElementById("dialogue-tokens-modal");
32 const tokensList = document.getElementById("dialogue-tokens-list");
33 const tokensPreviewInput = document.getElementById("dialogue-tokens-preview-input");
34 const tokensPreviewMale = document.getElementById("dialogue-tokens-preview-male");
35 const tokensPreviewFemale = document.getElementById("dialogue-tokens-preview-female");
36 let open = false;
37 let tokensHelpOpen = false;
38 /** @type {any[]} */
39 let dialogues = [];
40 /** @type {ReturnType<typeof normalizeQuestDef>[]} */
41 let questCatalog = [];
42 /** @type {any|null} */
43 let draft = null;
44 let selectedId = null;
45
46 const simulate = initDialogueSimulate({
47 getTree: () => (draft ? normalizeDialogueTree(draft) : null),
48 getQuestTitle (questId)
49 {
50 const quest = questCatalog.find((q) => q.questId === questId);
51 return quest?.title || questId;
52 }
53 });
54
55 function show (visible)
56 {
57 open = visible;
58 backdrop.hidden = !visible;
59 modal.hidden = !visible;
60 if (!visible)
61 {
62 draft = null;
63 selectedId = null;
64 closeInlineItemSearch();
65 showTokensHelp(false);
66 simulate.close();
67 }
68 }
69
70 function showTokensHelp (visible)
71 {
72 tokensHelpOpen = visible;
73 if (tokensBackdrop)
74 { tokensBackdrop.hidden = !visible; }
75 if (tokensModal)
76 { tokensModal.hidden = !visible; }
77 if (visible)
78 {
79 renderTokensHelp();
80 tokensPreviewInput?.focus();
81 }
82 }
83
84 function renderTokensHelp ()
85 {
86 if (tokensList)
87 {
88 tokensList.replaceChildren();
89 for (const entry of dialogueReplacementCatalog())
90 {
91 const li = document.createElement("li");
92 const code = document.createElement("code");
93 code.textContent = entry.token;
94 li.append(code, document.createTextNode(` — ${entry.meaning}`));
95 tokensList.append(li);
96 }
97 }
98 updateTokensPreview();
99 }
100
101 function updateTokensPreview ()
102 {
103 const sample = tokensPreviewInput?.value
104 || "Hello [Mr] [playername]. May [he] bring [his] [man]’s courage?";
105 if (tokensPreviewInput && !tokensPreviewInput.value)
106 { tokensPreviewInput.placeholder = sample; }
107 const text = tokensPreviewInput?.value || sample;
108 const male = applyDialogueTextReplacements(text, {
109 firstName: "Ada",
110 lastName: "Worker",
111 sex: "male"
112 });
113 const female = applyDialogueTextReplacements(text, {
114 firstName: "Ada",
115 lastName: "Worker",
116 sex: "female"
117 });
118 if (tokensPreviewMale)
119 { tokensPreviewMale.textContent = male; }
120 if (tokensPreviewFemale)
121 { tokensPreviewFemale.textContent = female; }
122 }
123
124 /** @type {null | {
125 * step: object,
126 * field: "itemRewards" | "itemTakes",
127 * resultsEl: HTMLElement,
128 * inputEl: HTMLInputElement
129 * }} */
130 let itemPickContext = null;
131
132 function closeInlineItemSearch ()
133 {
134 if (itemPickContext?.resultsEl)
135 { itemPickContext.resultsEl.replaceChildren(); }
136 itemPickContext = null;
137 }
138
139 function openInlineItemSearch (step, field, inputEl, resultsEl)
140 {
141 itemPickContext = { step, field, inputEl, resultsEl };
142 inputEl.value = "";
143 renderInlineItemSearch("");
144 inputEl.focus();
145 }
146
147 function renderInlineItemSearch (query)
148 {
149 if (!itemPickContext)
150 { return; }
151 const { step, field, resultsEl } = itemPickContext;
152 resultsEl.replaceChildren();
153 const q = String(query ?? "").trim().toLowerCase();
154 const taken = new Set((step[field] ?? []).map((row) => row.itemId));
155 const matches = listAllItemPickerEntries().filter((item) =>
156 {
157 if (taken.has(item.itemId))
158 { return false; }
159 if (!q)
160 { return true; }
161 return item.displayName.toLowerCase().includes(q)
162 || item.key.toLowerCase().includes(q)
163 || String(item.itemId).includes(q);
164 }).slice(0, 40);
165 if (!matches.length)
166 {
167 resultsEl.textContent = "No matching items.";
168 return;
169 }
170 for (const item of matches)
171 {
172 const row = document.createElement("button");
173 row.type = "button";
174 row.className = "shop-item-search-row";
175 const name = document.createElement("span");
176 name.className = "shop-item-search-row-name";
177 name.textContent = item.displayName;
178 const key = document.createElement("span");
179 key.className = "shop-item-search-row-key";
180 key.textContent = `${item.key} · #${item.itemId}`;
181 row.append(name, key);
182 row.addEventListener("click", () =>
183 {
184 if (!Array.isArray(step[field]))
185 { step[field] = []; }
186 step[field].push({ itemId: item.itemId, quantity: 1 });
187 closeInlineItemSearch();
188 renderEditor();
189 });
190 resultsEl.append(row);
191 }
192 }
193
194 function selectDialogue (dialogueId)
195 {
196 const found = dialogues.find((d) => d.dialogueId === dialogueId);
197 if (!found)
198 {
199 draft = null;
200 selectedId = null;
201 render();
202 return;
203 }
204 selectedId = found.dialogueId;
205 draft = structuredClone(found);
206 render();
207 }
208
209 function renderList ()
210 {
211 listEl.replaceChildren();
212 for (const tree of dialogues)
213 {
214 const btn = document.createElement("button");
215 btn.type = "button";
216 const unique = tree.unique ? " · unique" : "";
217 const assigned = tree.assignedSpawnerCount != null
218 ? ` (${tree.assignedSpawnerCount})`
219 : "";
220 btn.textContent = `${tree.label || tree.dialogueId}${unique}${assigned}`;
221 if (tree.dialogueId === selectedId)
222 { btn.classList.add("active"); }
223 btn.addEventListener("click", () => selectDialogue(tree.dialogueId));
224 listEl.append(btn);
225 }
226 }
227
228 function addStep ()
229 {
230 draft.steps.push({
231 stepId: `step-${draft.steps.length + 1}`,
232 lines: [{ speaker: "npc", text: "…", effects: [] }],
233 itemRewards: [],
234 itemTakes: [],
235 questRewards: [],
236 exit: { kind: "end" }
237 });
238 renderEditor();
239 }
240
241 /** Update yellow take warnings without rebuilding the editor (keeps scroll + focus). */
242 function refreshDialogueTakeHighlights ()
243 {
244 if (!draft || !editorEl)
245 { return; }
246 const warnings = unguaranteedDialogueTakes(draft);
247 for (const row of editorEl.querySelectorAll("[data-take-step-id][data-take-item-id]"))
248 {
249 const stepId = row.getAttribute("data-take-step-id");
250 const itemId = Number(row.getAttribute("data-take-item-id"));
251 const bad = dialogueTakeIsUnguaranteed(warnings, stepId, itemId);
252 row.classList.toggle("dialogue-item-take-unguaranteed", bad);
253 row.title = bad
254 ? "Not guaranteed by every branch/trigger path to this step."
255 : "";
256 }
257 }
258
259 function renderEditor ()
260 {
261 editorEl.replaceChildren();
262 saveBtn.disabled = !draft;
263 deleteBtn.disabled = !draft;
264 if (simulateBtn)
265 { simulateBtn.disabled = !draft; }
266 if (!draft)
267 {
268 const hint = document.createElement("p");
269 hint.className = "content-editor-hint";
270 hint.textContent = "Select a dialogue or create a new one.";
271 editorEl.append(hint);
272 return;
273 }
274
275 editorEl.append(
276 field("Dialogue id", textInput(draft.dialogueId, (v) => { draft.dialogueId = v; })),
277 field("Label", textInput(draft.label, (v) => { draft.label = v; }))
278 );
279
280 const uniqueLabel = document.createElement("label");
281 const uniqueBox = document.createElement("input");
282 uniqueBox.type = "checkbox";
283 uniqueBox.checked = !!draft.unique;
284 uniqueBox.addEventListener("change", () => { draft.unique = uniqueBox.checked; });
285 uniqueLabel.append(uniqueBox, document.createTextNode(" Unique (at most one spawner)"));
286 editorEl.append(uniqueLabel);
287
288 const assigned = document.createElement("p");
289 assigned.className = "content-editor-hint";
290 assigned.textContent = `Assigned spawners: ${draft.assignedSpawnerCount ?? 0}`;
291 editorEl.append(assigned);
292
293 editorEl.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) =>
294 {
295 draft.entryStepId = v;
296 })));
297
298 const stepsTitle = document.createElement("div");
299 stepsTitle.className = "content-editor-section-header";
300 const stepsStrong = document.createElement("strong");
301 stepsStrong.textContent = "Steps";
302 stepsTitle.append(stepsStrong);
303 editorEl.append(stepsTitle);
304
305 const takeWarnings = unguaranteedDialogueTakes(draft);
306
307 draft.steps.forEach((step, stepIndex) =>
308 {
309 const box = document.createElement("div");
310 box.className = "content-editor-section";
311 box.append(sectionHeader(`Step ${stepIndex + 1}`, null, () =>
312 {
313 draft.steps.splice(stepIndex, 1);
314 if (draft.steps.length === 0)
315 {
316 draft.steps.push({
317 stepId: "greeting",
318 lines: [{ speaker: "npc", text: "…", effects: [] }],
319 itemRewards: [],
320 itemTakes: [],
321 questRewards: [],
322 exit: { kind: "end" }
323 });
324 }
325 renderEditor();
326 }));
327 box.append(field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })));
328
329 const linesHead = sectionHeader("Lines", () =>
330 {
331 step.lines.push({ speaker: "npc", text: "…", effects: [] });
332 renderEditor();
333 });
334 box.append(linesHead);
335 step.lines.forEach((line, lineIndex) =>
336 {
337 const row = document.createElement("div");
338 row.className = "content-editor-row";
339 const speaker = document.createElement("select");
340 for (const s of ["npc", "player"])
341 {
342 const opt = document.createElement("option");
343 opt.value = s;
344 opt.textContent = s;
345 if (line.speaker === s)
346 { opt.selected = true; }
347 speaker.append(opt);
348 }
349 speaker.addEventListener("change", () =>
350 {
351 line.speaker = speaker.value;
352 });
353 const text = document.createElement("input");
354 text.type = "text";
355 text.value = line.text ?? "";
356 text.style.flex = "1";
357 text.addEventListener("input", () => { line.text = text.value; });
358 row.append(speaker, text, removeButton(() =>
359 {
360 step.lines.splice(lineIndex, 1);
361 if (step.lines.length === 0)
362 { step.lines.push({ speaker: "npc", text: "…", effects: [] }); }
363 renderEditor();
364 }));
365 box.append(row);
366 });
367
368 if (!Array.isArray(step.itemRewards))
369 { step.itemRewards = []; }
370 const searchWrap = document.createElement("div");
371 searchWrap.className = "dialogue-reward-item-search";
372 searchWrap.hidden = true;
373 const searchInput = document.createElement("input");
374 searchInput.type = "search";
375 searchInput.placeholder = "Search items…";
376 searchInput.autocomplete = "off";
377 searchInput.addEventListener("input", () => renderInlineItemSearch(searchInput.value));
378 const searchResults = document.createElement("div");
379 searchResults.className = "dialogue-reward-item-results";
380 searchWrap.append(searchInput, searchResults);
381 const rewardsHead = sectionHeader("Item rewards", () =>
382 {
383 searchWrap.hidden = false;
384 openInlineItemSearch(step, "itemRewards", searchInput, searchResults);
385 });
386 box.append(rewardsHead);
387 const rewardsHint = document.createElement("p");
388 rewardsHint.className = "content-editor-hint";
389 rewardsHint.textContent = "Granted after all lines, before triggers/branches.";
390 box.append(rewardsHint);
391 if (!step.itemRewards.length)
392 {
393 const empty = document.createElement("p");
394 empty.className = "content-editor-hint";
395 empty.textContent = "No item rewards.";
396 box.append(empty);
397 }
398 step.itemRewards.forEach((reward, rewardIndex) =>
399 {
400 const def = itemDefinition(reward.itemId);
401 const row = document.createElement("div");
402 row.className = "spawner-drops-row";
403 const name = document.createElement("span");
404 name.className = "spawner-sells-name";
405 name.textContent = def?.displayName ?? `Item ${reward.itemId}`;
406 const qty = document.createElement("input");
407 qty.type = "number";
408 qty.min = "1";
409 qty.step = "1";
410 qty.value = String(Math.max(1, reward.quantity | 0 || 1));
411 qty.title = "Quantity";
412 qty.addEventListener("input", () =>
413 {
414 step.itemRewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
415 });
416 row.append(name, qty, removeButton(() =>
417 {
418 step.itemRewards.splice(rewardIndex, 1);
419 renderEditor();
420 }));
421 box.append(row);
422 });
423 box.append(searchWrap);
424
425 if (!Array.isArray(step.itemTakes))
426 { step.itemTakes = []; }
427 const takeSearchWrap = document.createElement("div");
428 takeSearchWrap.className = "dialogue-reward-item-search";
429 takeSearchWrap.hidden = true;
430 const takeSearchInput = document.createElement("input");
431 takeSearchInput.type = "search";
432 takeSearchInput.placeholder = "Search items…";
433 takeSearchInput.autocomplete = "off";
434 takeSearchInput.addEventListener("input", () => renderInlineItemSearch(takeSearchInput.value));
435 const takeSearchResults = document.createElement("div");
436 takeSearchResults.className = "dialogue-reward-item-results";
437 takeSearchWrap.append(takeSearchInput, takeSearchResults);
438 const takesHead = sectionHeader("Item takes", () =>
439 {
440 takeSearchWrap.hidden = false;
441 openInlineItemSearch(step, "itemTakes", takeSearchInput, takeSearchResults);
442 });
443 box.append(takesHead);
444 const takesHint = document.createElement("p");
445 takesHint.className = "content-editor-hint";
446 takesHint.textContent = "Removed from the bag after all lines (soft: takes what the player has). Yellow = branch/trigger path does not guarantee the player has them.";
447 box.append(takesHint);
448 if (!step.itemTakes.length)
449 {
450 const empty = document.createElement("p");
451 empty.className = "content-editor-hint";
452 empty.textContent = "No item takes.";
453 box.append(empty);
454 }
455 step.itemTakes.forEach((take, takeIndex) =>
456 {
457 const def = itemDefinition(take.itemId);
458 const row = document.createElement("div");
459 row.className = "spawner-drops-row";
460 row.setAttribute("data-take-step-id", step.stepId);
461 row.setAttribute("data-take-item-id", String(take.itemId));
462 if (dialogueTakeIsUnguaranteed(takeWarnings, step.stepId, take.itemId))
463 {
464 row.classList.add("dialogue-item-take-unguaranteed");
465 row.title = "Not guaranteed by every branch/trigger path to this step.";
466 }
467 const name = document.createElement("span");
468 name.className = "spawner-sells-name";
469 name.textContent = def?.displayName ?? `Item ${take.itemId}`;
470 const qty = document.createElement("input");
471 qty.type = "number";
472 qty.min = "1";
473 qty.step = "1";
474 qty.value = String(Math.max(1, take.quantity | 0 || 1));
475 qty.title = "Quantity";
476 qty.addEventListener("input", () =>
477 {
478 step.itemTakes[takeIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
479 refreshDialogueTakeHighlights();
480 });
481 row.append(name, qty, removeButton(() =>
482 {
483 step.itemTakes.splice(takeIndex, 1);
484 renderEditor();
485 }));
486 box.append(row);
487 });
488 box.append(takeSearchWrap);
489
490 if (!Array.isArray(step.questRewards))
491 { step.questRewards = []; }
492 const questRewardsHead = sectionHeader("Quest rewards", () =>
493 {
494 const available = questCatalog.find((q) => !step.questRewards.includes(q.questId));
495 if (!available)
496 { return; }
497 step.questRewards.push(available.questId);
498 renderEditor();
499 });
500 box.append(questRewardsHead);
501 const questHint = document.createElement("p");
502 questHint.className = "content-editor-hint";
503 questHint.textContent = "Started after all lines (with item rewards), before triggers/branches.";
504 box.append(questHint);
505 if (!step.questRewards.length)
506 {
507 const empty = document.createElement("p");
508 empty.className = "content-editor-hint";
509 empty.textContent = "No quest rewards.";
510 box.append(empty);
511 }
512 step.questRewards.forEach((questId, rewardIndex) =>
513 {
514 const row = document.createElement("div");
515 row.className = "spawner-drops-row";
516 const select = document.createElement("select");
517 const taken = new Set(step.questRewards);
518 const catalog = questCatalog.length
519 ? questCatalog
520 : [{ questId, title: questId }];
521 for (const quest of catalog)
522 {
523 if (taken.has(quest.questId) && quest.questId !== questId)
524 { continue; }
525 const opt = document.createElement("option");
526 opt.value = quest.questId;
527 opt.textContent = quest.title
528 ? `${quest.title} (${quest.questId})`
529 : quest.questId;
530 select.append(opt);
531 }
532 if (![...select.options].some((o) => o.value === questId))
533 {
534 const missing = document.createElement("option");
535 missing.value = questId;
536 missing.textContent = `${questId} (missing)`;
537 select.append(missing);
538 }
539 select.value = questId;
540 select.addEventListener("change", () =>
541 {
542 step.questRewards[rewardIndex] = select.value;
543 renderEditor();
544 });
545 row.append(select, removeButton(() =>
546 {
547 step.questRewards.splice(rewardIndex, 1);
548 renderEditor();
549 }));
550 box.append(row);
551 });
552
553 const exitKind = document.createElement("select");
554 for (const k of ["end", "triggers", "branches"])
555 {
556 const opt = document.createElement("option");
557 opt.value = k;
558 opt.textContent = k;
559 if ((step.exit?.kind ?? "end") === k)
560 { opt.selected = true; }
561 exitKind.append(opt);
562 }
563 exitKind.addEventListener("change", () =>
564 {
565 if (exitKind.value === "triggers")
566 {
567 step.exit = {
568 kind: "triggers",
569 triggers: step.exit?.triggers?.length
570 ? step.exit.triggers
571 : [{
572 trigger: "continue",
573 text: "Continue",
574 nextStepId: null,
575 when: emptyConditionSet(),
576 effects: []
577 }]
578 };
579 }
580 else if (exitKind.value === "branches")
581 {
582 step.exit = {
583 kind: "branches",
584 branches: step.exit?.branches?.length
585 ? step.exit.branches
586 : [{
587 when: emptyConditionSet(),
588 nextStepId: null,
589 effects: []
590 }]
591 };
592 }
593 else
594 { step.exit = { kind: "end" }; }
595 renderEditor();
596 });
597 box.append(field("Exit kind", exitKind));
598
599 if (step.exit?.kind === "triggers")
600 {
601 const trigHead = sectionHeader("Triggers", () =>
602 {
603 step.exit.triggers.push({
604 trigger: `choice-${step.exit.triggers.length + 1}`,
605 text: "Choice",
606 nextStepId: null,
607 when: emptyConditionSet(),
608 effects: []
609 });
610 renderEditor();
611 });
612 box.append(trigHead);
613 step.exit.triggers.forEach((trig, trigIndex) =>
614 {
615 const tBox = document.createElement("div");
616 tBox.className = "content-editor-section";
617 tBox.append(sectionHeader(`Trigger ${trigIndex + 1}`, null, () =>
618 {
619 step.exit.triggers.splice(trigIndex, 1);
620 renderEditor();
621 }));
622 tBox.append(
623 field("trigger", textInput(trig.trigger, (v) => { trig.trigger = v; })),
624 field("text (button)", textInput(trig.text, (v) => { trig.text = v; })),
625 field("nextStepId (blank=end)", textInput(trig.nextStepId ?? "", (v) =>
626 {
627 trig.nextStepId = v.trim() || null;
628 }))
629 );
630 tBox.append(renderConditionSet(trig.when, (next, { remount = true } = {}) =>
631 {
632 trig.when = next;
633 if (remount)
634 { renderEditor(); }
635 }, conditionCtx()));
636 box.append(tBox);
637 });
638 }
639 else if (step.exit?.kind === "branches")
640 {
641 const branchHead = sectionHeader("Branches", () =>
642 {
643 step.exit.branches.push({
644 when: emptyConditionSet(),
645 nextStepId: null,
646 effects: []
647 });
648 renderEditor();
649 });
650 box.append(branchHead);
651 step.exit.branches.forEach((branch, branchIndex) =>
652 {
653 const bBox = document.createElement("div");
654 bBox.className = "content-editor-section";
655 bBox.append(sectionHeader(`Branch ${branchIndex + 1}`, null, () =>
656 {
657 step.exit.branches.splice(branchIndex, 1);
658 renderEditor();
659 }));
660 bBox.append(
661 field("nextStepId (blank=end)", textInput(branch.nextStepId ?? "", (v) =>
662 {
663 branch.nextStepId = v.trim() || null;
664 }))
665 );
666 bBox.append(renderConditionSet(branch.when, (next, { remount = true } = {}) =>
667 {
668 branch.when = next;
669 if (remount)
670 { renderEditor(); }
671 }, conditionCtx()));
672 box.append(bBox);
673 });
674 }
675
676 editorEl.append(box);
677 });
678
679 const addStepBtn = document.createElement("button");
680 addStepBtn.type = "button";
681 addStepBtn.className = "content-editor-add-step";
682 addStepBtn.textContent = "(add step)";
683 addStepBtn.addEventListener("click", addStep);
684 editorEl.append(addStepBtn);
685 }
686
687 function conditionCtx ()
688 {
689 return {
690 quests: questCatalog,
691 dialogues,
692 describeWorldTile,
693 centerEditorOnTile,
694 getDimensionOptions
695 };
696 }
697
698 function render ()
699 {
700 renderList();
701 renderEditor();
702 }
703
704 document.getElementById("open-dialogues").addEventListener("click", () =>
705 {
706 socket.send({ type: MessageType.editorLoadDialogues });
707 socket.send({ type: MessageType.editorLoadQuests });
708 show(true);
709 render();
710 });
711 document.getElementById("dialogues-close").addEventListener("click", () => show(false));
712 backdrop.addEventListener("click", () => show(false));
713 document.getElementById("dialogues-tokens-help")?.addEventListener("click", () =>
714 {
715 showTokensHelp(true);
716 });
717 document.getElementById("dialogue-tokens-close")?.addEventListener("click", () => showTokensHelp(false));
718 tokensBackdrop?.addEventListener("click", () => showTokensHelp(false));
719 tokensPreviewInput?.addEventListener("input", () => updateTokensPreview());
720 simulateBtn?.addEventListener("click", () =>
721 {
722 if (!draft)
723 { return; }
724 simulate.start();
725 });
726 document.getElementById("dialogues-new").addEventListener("click", () =>
727 {
728 const base = normalizeDialogueTree({
729 dialogueId: `dialogue-${dialogues.length + 1}`,
730 label: "New dialogue",
731 unique: false
732 });
733 draft = { ...structuredClone(base), assignedSpawnerCount: 0 };
734 selectedId = null;
735 render();
736 });
737 saveBtn.addEventListener("click", () =>
738 {
739 if (!draft)
740 { return; }
741 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
742 });
743 deleteBtn.addEventListener("click", () =>
744 {
745 if (!draft?.dialogueId)
746 { return; }
747 if (!window.confirm(`Delete dialogue "${draft.dialogueId}"?`))
748 { return; }
749 socket.send({ type: MessageType.editorDeleteDialogue, dialogueId: draft.dialogueId });
750 });
751
752 return {
753 isOpen: () => open || tokensHelpOpen || simulate.isOpen(),
754 getDialogues: () => dialogues,
755 handleMessage (message)
756 {
757 if (message.type === MessageType.editorQuests)
758 {
759 questCatalog = (message.quests ?? []).map((q) => normalizeQuestDef(q));
760 if (open)
761 { render(); }
762 return;
763 }
764 if (message.type !== MessageType.editorDialogues)
765 { return; }
766 dialogues = (message.dialogues ?? []).map((d) =>
767 {
768 const tree = normalizeDialogueTree(d);
769 return {
770 ...tree,
771 assignedSpawnerCount: d.assignedSpawnerCount ?? 0
772 };
773 });
774 if (draft)
775 {
776 const still = dialogues.find((d) => d.dialogueId === draft.dialogueId);
777 if (still)
778 {
779 selectedId = still.dialogueId;
780 draft = structuredClone(still);
781 }
782 else if (selectedId)
783 {
784 draft = null;
785 selectedId = null;
786 }
787 }
788 if (open)
789 { render(); }
790 }
791 };
792}
793
794function field (label, input)
795{
796 const wrap = document.createElement("label");
797 wrap.append(document.createTextNode(label), input);
798 return wrap;
799}
800
801function textInput (value, onChange)
802{
803 const input = document.createElement("input");
804 input.type = "text";
805 input.value = value ?? "";
806 input.addEventListener("input", () => onChange(input.value));
807 return input;
808}
809
810function removeButton (onClick)
811{
812 const remove = document.createElement("button");
813 remove.type = "button";
814 remove.className = "content-editor-remove";
815 remove.textContent = "×";
816 remove.title = "Remove";
817 remove.addEventListener("click", onClick);
818 return remove;
819}
820
821function sectionHeader (title, onAdd, onRemove)
822{
823 const head = document.createElement("div");
824 head.className = "content-editor-section-header";
825 const strong = document.createElement("strong");
826 strong.textContent = title;
827 head.append(strong);
828 const actions = document.createElement("div");
829 actions.className = "content-editor-row";
830 if (onAdd)
831 {
832 const add = document.createElement("button");
833 add.type = "button";
834 add.textContent = "+";
835 add.title = "Add";
836 add.addEventListener("click", onAdd);
837 actions.append(add);
838 }
839 if (onRemove)
840 { actions.append(removeButton(onRemove)); }
841 head.append(actions);
842 return head;
843}
844