BlueGit

timfa questward

Files

questward / client / src / editor / dialoguesModal.js

dialoguesModal.js

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