BlueGit

timfa questward

Files

questward / client / src / editor / dialoguesModal.js

dialoguesModal.js

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