BlueGit

timfa questward

Files

questward / client / src / editor / dialoguesModal.js

dialoguesModal.js

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