BlueGit

timfa questward

Files

questward / client / src / editor / dialoguesModal.js

dialoguesModal.js

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