BlueGit

timfa questward

Files

questward / client / src / editor / dialoguesModal.js

dialoguesModal.js

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