BlueGit

timfa questward

Merge branch 'feature/dialogue-editor-canvas'

timfa Tim Falken · pushed by timfa

Authored 2026-09-13 · 2 months ago

Hash
80d766499af3b7ae412cbd9196e53966455f0831
10 files changed +2455 −585
client/editor.html +13 −0
@@ -158,6 +158,19 @@
158 158 </aside>
159 159 </div>
160 160
161 <div id="unsaved-dialogue-backdrop" hidden></div>
162 <div id="unsaved-dialogue-modal" hidden role="dialog" aria-modal="true" aria-labelledby="unsaved-dialogue-title">
163 <header>
164 <h2 id="unsaved-dialogue-title">Unsaved changes</h2>
165 </header>
166 <p>You have unsaved dialogue changes. Leave without saving?</p>
167 <footer class="unsaved-chunk-actions">
168 <button id="unsaved-dialogue-cancel" type="button">Cancel</button>
169 <button id="unsaved-dialogue-discard" type="button">Discard</button>
170 <button id="unsaved-dialogue-save" type="button">Save</button>
171 </footer>
172 </div>
173
161 174 <div id="global-changelog-backdrop" hidden></div>
162 175 <div id="global-changelog-modal" hidden>
163 176 <header>
@@ -158,6 +158,19 @@
158 </aside>
158 </aside>
159 </div>
159 </div>
160
160
161 <div id="unsaved-dialogue-backdrop" hidden></div>
162 <div id="unsaved-dialogue-modal" hidden role="dialog" aria-modal="true" aria-labelledby="unsaved-dialogue-title">
163 <header>
164 <h2 id="unsaved-dialogue-title">Unsaved changes</h2>
165 </header>
166 <p>You have unsaved dialogue changes. Leave without saving?</p>
167 <footer class="unsaved-chunk-actions">
168 <button id="unsaved-dialogue-cancel" type="button">Cancel</button>
169 <button id="unsaved-dialogue-discard" type="button">Discard</button>
170 <button id="unsaved-dialogue-save" type="button">Save</button>
171 </footer>
172 </div>
173
161 <div id="global-changelog-backdrop" hidden></div>
174 <div id="global-changelog-backdrop" hidden></div>
162 <div id="global-changelog-modal" hidden>
175 <div id="global-changelog-modal" hidden>
163 <header>
176 <header>
client/src/editor/dialogueCanvas.js added +746 −0
@@ -0,0 +1,746 @@
1 /**
2 * Desktop node-graph canvas for dialogue steps.
3 * Pan empty space, drag cards, wheel zoom, wire outputs → inputs.
4 */
5
6 const CARD_W = 168;
7 const CARD_H = 72;
8 const PORT_R = 7;
9 const EDGE_PAD = 36;
10 const MIN_ZOOM = 0.35;
11 const MAX_ZOOM = 2.25;
12 const AUTO_PAN = 14;
13
14 /**
15 * @param {{
16 * getDraft: () => object | null,
17 * onOpenStep: (stepId: string) => void,
18 * onCreateStep: (worldX: number, worldY: number) => void,
19 * onChange: () => void
20 * }} options
21 */
22 export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onChange })
23 {
24 const wrap = document.createElement("div");
25 wrap.className = "dialogue-canvas-wrap";
26
27 const viewport = document.createElement("div");
28 viewport.className = "dialogue-canvas-viewport";
29 viewport.tabIndex = 0;
30
31 const world = document.createElement("div");
32 world.className = "dialogue-canvas-world";
33
34 const edgesSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
35 edgesSvg.classList.add("dialogue-canvas-edges");
36 edgesSvg.setAttribute("overflow", "visible");
37
38 const cardsLayer = document.createElement("div");
39 cardsLayer.className = "dialogue-canvas-cards";
40
41 const rubberPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
42 rubberPath.classList.add("dialogue-canvas-rubber");
43 rubberPath.setAttribute("fill", "none");
44
45 const ctxMenu = document.createElement("div");
46 ctxMenu.className = "dialogue-canvas-context";
47 ctxMenu.hidden = true;
48 const createBtn = document.createElement("button");
49 createBtn.type = "button";
50 createBtn.textContent = "Create new step";
51 ctxMenu.append(createBtn);
52
53 const tooltip = document.createElement("div");
54 tooltip.className = "dialogue-canvas-tooltip";
55 tooltip.hidden = true;
56
57 world.append(edgesSvg, cardsLayer);
58 edgesSvg.append(rubberPath);
59 viewport.append(world);
60 wrap.append(viewport, ctxMenu, tooltip);
61
62 /** @type {{ x: number, y: number, zoom: number }} */
63 let view = { x: 40, y: 40, zoom: 1 };
64 /** @type {null | {
65 * mode: "pan" | "card" | "wire",
66 * startClientX: number,
67 * startClientY: number,
68 * originViewX?: number,
69 * originViewY?: number,
70 * step?: object,
71 * originEditorX?: number,
72 * originEditorY?: number,
73 * moved: boolean,
74 * portKey?: string,
75 * fromStepId?: string,
76 * portIndex?: number
77 * }} */
78 let drag = null;
79 /** @type {null | { stepId: string, portIndex: number, portKey: string }} */
80 let wiring = null;
81 let ctxWorld = { x: 0, y: 0 };
82 /** @type {number | null} */
83 let autoPanRaf = null;
84 let lastPointer = { x: 0, y: 0 };
85
86 function applyTransform ()
87 {
88 world.style.transform = `translate(${view.x}px, ${view.y}px) scale(${view.zoom})`;
89 }
90
91 function clientToWorld (clientX, clientY)
92 {
93 const rect = viewport.getBoundingClientRect();
94 return {
95 x: (clientX - rect.left - view.x) / view.zoom,
96 y: (clientY - rect.top - view.y) / view.zoom
97 };
98 }
99
100 function hideContext ()
101 {
102 ctxMenu.hidden = true;
103 }
104
105 function hideTooltip ()
106 {
107 tooltip.hidden = true;
108 }
109
110 function showTooltip (text, clientX, clientY)
111 {
112 if (!text)
113 {
114 hideTooltip();
115 return;
116 }
117 tooltip.hidden = false;
118 tooltip.textContent = text;
119 const rect = wrap.getBoundingClientRect();
120 tooltip.style.left = `${clientX - rect.left + 12}px`;
121 tooltip.style.top = `${clientY - rect.top + 12}px`;
122 }
123
124 function stepPosition (step, index)
125 {
126 const x = Number.isFinite(step.editorX) ? step.editorX : 40 + (index % 4) * (CARD_W + 48);
127 const y = Number.isFinite(step.editorY) ? step.editorY : 40 + Math.floor(index / 4) * (CARD_H + 64);
128 return { x, y };
129 }
130
131 function outputPorts (step)
132 {
133 const exit = step?.exit ?? { kind: "end" };
134 if (exit.kind === "continue")
135 {
136 return [{
137 key: "continue",
138 label: "Continue",
139 nextStepId: exit.nextStepId ?? null,
140 setNext (id)
141 {
142 exit.nextStepId = id;
143 }
144 }];
145 }
146 if (exit.kind === "triggers")
147 {
148 return (exit.triggers ?? []).map((trig, i) => ({
149 key: `trigger:${i}`,
150 /** Player-facing button text (not the internal trigger id / legacy label). */
151 label: (trig.text ?? "").trim() || trig.trigger || `Trigger ${i + 1}`,
152 nextStepId: trig.nextStepId ?? null,
153 setNext (id)
154 {
155 trig.nextStepId = id;
156 }
157 }));
158 }
159 if (exit.kind === "branches")
160 {
161 return (exit.branches ?? []).map((branch, i) => ({
162 key: `branch:${i}`,
163 label: branch.label?.trim() ? branch.label : `Branch ${i + 1}`,
164 nextStepId: branch.nextStepId ?? null,
165 setNext (id)
166 {
167 branch.nextStepId = id;
168 }
169 }));
170 }
171 return [];
172 }
173
174 function portWorldPos (step, index, portIndex, kind)
175 {
176 const pos = stepPosition(step, index);
177 if (kind === "in")
178 {
179 return { x: pos.x + CARD_W / 2, y: pos.y };
180 }
181 const ports = outputPorts(step);
182 const n = Math.max(1, ports.length);
183 const spacing = CARD_W / (n + 1);
184 return {
185 x: pos.x + spacing * (portIndex + 1),
186 y: pos.y + CARD_H
187 };
188 }
189
190 function bezier (x1, y1, x2, y2)
191 {
192 const dy = Math.max(40, Math.abs(y2 - y1) * 0.45);
193 return `M ${x1} ${y1} C ${x1} ${y1 + dy}, ${x2} ${y2 - dy}, ${x2} ${y2}`;
194 }
195
196 function clearWiring ()
197 {
198 wiring = null;
199 rubberPath.setAttribute("d", "");
200 rubberPath.classList.remove("active");
201 wrap.classList.remove("dialogue-canvas-wiring");
202 for (const el of cardsLayer.querySelectorAll(".dialogue-canvas-input.show"))
203 { el.classList.remove("show"); }
204 }
205
206 function setWiring (stepId, portIndex, portKey)
207 {
208 wiring = { stepId, portIndex, portKey };
209 wrap.classList.add("dialogue-canvas-wiring");
210 for (const el of cardsLayer.querySelectorAll(".dialogue-canvas-input"))
211 {
212 if (el.getAttribute("data-step-id") !== stepId)
213 { el.classList.add("show"); }
214 }
215 }
216
217 function stopAutoPan ()
218 {
219 if (autoPanRaf != null)
220 {
221 cancelAnimationFrame(autoPanRaf);
222 autoPanRaf = null;
223 }
224 }
225
226 function tickAutoPan ()
227 {
228 autoPanRaf = null;
229 if (!drag || drag.mode !== "card")
230 { return; }
231 const rect = viewport.getBoundingClientRect();
232 let dx = 0;
233 let dy = 0;
234 if (lastPointer.x < rect.left + EDGE_PAD)
235 { dx = AUTO_PAN; }
236 else if (lastPointer.x > rect.right - EDGE_PAD)
237 { dx = -AUTO_PAN; }
238 if (lastPointer.y < rect.top + EDGE_PAD)
239 { dy = AUTO_PAN; }
240 else if (lastPointer.y > rect.bottom - EDGE_PAD)
241 { dy = -AUTO_PAN; }
242 if (dx || dy)
243 {
244 view.x += dx;
245 view.y += dy;
246 applyTransform();
247 const worldPt = clientToWorld(lastPointer.x, lastPointer.y);
248 drag.step.editorX = worldPt.x - CARD_W / 2;
249 drag.step.editorY = worldPt.y - CARD_H / 2;
250 refreshCardsOnly();
251 redrawEdges();
252 }
253 autoPanRaf = requestAnimationFrame(tickAutoPan);
254 }
255
256 function redrawEdges ()
257 {
258 const draft = getDraft();
259 for (const el of [...edgesSvg.children])
260 {
261 if (el !== rubberPath)
262 { el.remove(); }
263 }
264 if (rubberPath.parentNode !== edgesSvg)
265 { edgesSvg.append(rubberPath); }
266 if (!draft?.steps?.length)
267 { return; }
268 draft.steps.forEach((step, index) =>
269 {
270 const ports = outputPorts(step);
271 ports.forEach((port, portIndex) =>
272 {
273 if (!port.nextStepId)
274 { return; }
275 const targetIndex = draft.steps.findIndex((s) => s.stepId === port.nextStepId);
276 if (targetIndex < 0)
277 { return; }
278 const from = portWorldPos(step, index, portIndex, "out");
279 const to = portWorldPos(draft.steps[targetIndex], targetIndex, 0, "in");
280 const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
281 path.classList.add("dialogue-canvas-edge");
282 const rewiring = !!wiring
283 && wiring.stepId === step.stepId
284 && wiring.portIndex === portIndex;
285 if (rewiring)
286 { path.classList.add("is-rewiring"); }
287 path.setAttribute("d", bezier(from.x, from.y, to.x, to.y));
288 path.setAttribute("fill", "none");
289 edgesSvg.insertBefore(path, rubberPath);
290 });
291 });
292 }
293
294 function refreshCardsOnly ()
295 {
296 const draft = getDraft();
297 if (!draft)
298 {
299 cardsLayer.replaceChildren();
300 return;
301 }
302 const existing = new Map(
303 [...cardsLayer.querySelectorAll(".dialogue-canvas-card")]
304 .map((el) => [el.getAttribute("data-step-id"), el])
305 );
306 const keep = new Set();
307 draft.steps.forEach((step, index) =>
308 {
309 keep.add(step.stepId);
310 let card = existing.get(step.stepId);
311 if (!card)
312 {
313 card = buildCard(step, index);
314 cardsLayer.append(card);
315 }
316 else
317 { updateCard(card, step, index); }
318 const pos = stepPosition(step, index);
319 card.style.left = `${pos.x}px`;
320 card.style.top = `${pos.y}px`;
321 });
322 for (const [id, el] of existing)
323 {
324 if (!keep.has(id))
325 { el.remove(); }
326 }
327 }
328
329 function buildCard (step, index)
330 {
331 const card = document.createElement("div");
332 card.className = "dialogue-canvas-card";
333 card.setAttribute("data-step-id", step.stepId);
334
335 const input = document.createElement("button");
336 input.type = "button";
337 input.className = "dialogue-canvas-input";
338 input.title = "Connect here";
339 input.setAttribute("data-step-id", step.stepId);
340 input.addEventListener("pointerdown", (event) =>
341 {
342 event.stopPropagation();
343 event.preventDefault();
344 if (!wiring)
345 { return; }
346 if (wiring.stepId === step.stepId)
347 { return; }
348 const draft = getDraft();
349 const from = draft?.steps?.find((s) => s.stepId === wiring.stepId);
350 if (!from)
351 { return; }
352 const ports = outputPorts(from);
353 const port = ports[wiring.portIndex];
354 if (!port)
355 { return; }
356 port.setNext(step.stepId);
357 clearWiring();
358 onChange();
359 refresh();
360 });
361
362 const label = document.createElement("div");
363 label.className = "dialogue-canvas-card-label";
364
365 const meta = document.createElement("div");
366 meta.className = "dialogue-canvas-card-meta";
367
368 const portsRow = document.createElement("div");
369 portsRow.className = "dialogue-canvas-ports";
370
371 card.append(input, label, meta, portsRow);
372
373 card.addEventListener("pointerdown", (event) =>
374 {
375 if (event.button !== 0)
376 { return; }
377 if (event.target.closest(".dialogue-canvas-port, .dialogue-canvas-input"))
378 { return; }
379 event.preventDefault();
380 hideContext();
381 const draft = getDraft();
382 const live = draft?.steps?.find((s) => s.stepId === step.stepId);
383 if (!live)
384 { return; }
385 const pos = stepPosition(live, draft.steps.indexOf(live));
386 if (!Number.isFinite(live.editorX))
387 { live.editorX = pos.x; }
388 if (!Number.isFinite(live.editorY))
389 { live.editorY = pos.y; }
390 drag = {
391 mode: "card",
392 startClientX: event.clientX,
393 startClientY: event.clientY,
394 step: live,
395 originEditorX: live.editorX,
396 originEditorY: live.editorY,
397 moved: false
398 };
399 lastPointer = { x: event.clientX, y: event.clientY };
400 card.classList.add("dragging");
401 card.setPointerCapture(event.pointerId);
402 stopAutoPan();
403 autoPanRaf = requestAnimationFrame(tickAutoPan);
404 });
405
406 updateCard(card, step, index);
407 return card;
408 }
409
410 function updateCard (card, step, index)
411 {
412 card.setAttribute("data-step-id", step.stepId);
413 const draft = getDraft();
414 const isEntry = draft && (draft.entryStepId === step.stepId
415 || (!draft.entryStepId && draft.steps[0] === step));
416 card.classList.toggle("is-entry", !!isEntry);
417 const label = card.querySelector(".dialogue-canvas-card-label");
418 if (label)
419 { label.textContent = step.label || step.stepId; }
420 const meta = card.querySelector(".dialogue-canvas-card-meta");
421 if (meta)
422 {
423 const kind = step.exit?.kind ?? "end";
424 meta.textContent = isEntry ? `entry · ${kind}` : kind;
425 }
426 const input = card.querySelector(".dialogue-canvas-input");
427 if (input)
428 {
429 input.setAttribute("data-step-id", step.stepId);
430 input.classList.toggle("show", !!wiring && wiring.stepId !== step.stepId);
431 }
432 const portsRow = card.querySelector(".dialogue-canvas-ports");
433 if (!portsRow)
434 { return; }
435 portsRow.replaceChildren();
436 const ports = outputPorts(step);
437 ports.forEach((port, portIndex) =>
438 {
439 const btn = document.createElement("button");
440 btn.type = "button";
441 btn.className = "dialogue-canvas-port";
442 btn.title = port.label;
443 btn.classList.toggle("linked", !!port.nextStepId);
444 btn.classList.toggle("selected",
445 !!wiring && wiring.stepId === step.stepId && wiring.portIndex === portIndex);
446 btn.addEventListener("pointerdown", (event) =>
447 {
448 event.stopPropagation();
449 event.preventDefault();
450 hideContext();
451 // Clicking an output always starts/continues wire mode (existing link stays until
452 // a new input is chosen; that edge is drawn red via is-rewiring).
453 setWiring(step.stepId, portIndex, port.key);
454 drag = {
455 mode: "wire",
456 startClientX: event.clientX,
457 startClientY: event.clientY,
458 moved: false,
459 fromStepId: step.stepId,
460 portIndex,
461 portKey: port.key
462 };
463 const from = portWorldPos(step, index, portIndex, "out");
464 const worldPt = clientToWorld(event.clientX, event.clientY);
465 rubberPath.classList.add("active");
466 rubberPath.setAttribute("d", bezier(from.x, from.y, worldPt.x, worldPt.y));
467 refreshCardsOnly();
468 redrawEdges();
469 });
470 btn.addEventListener("pointerenter", (event) =>
471 {
472 showTooltip(port.label, event.clientX, event.clientY);
473 });
474 btn.addEventListener("pointerleave", () => hideTooltip());
475 btn.addEventListener("pointermove", (event) =>
476 {
477 showTooltip(port.label, event.clientX, event.clientY);
478 });
479 portsRow.append(btn);
480 });
481 }
482
483 function refresh ()
484 {
485 applyTransform();
486 refreshCardsOnly();
487 redrawEdges();
488 }
489
490 function onPointerMove (event)
491 {
492 lastPointer = { x: event.clientX, y: event.clientY };
493 if (!drag)
494 {
495 if (wiring)
496 {
497 const draft = getDraft();
498 const fromStep = draft?.steps?.find((s) => s.stepId === wiring.stepId);
499 if (!fromStep)
500 { return; }
501 const index = draft.steps.indexOf(fromStep);
502 const from = portWorldPos(fromStep, index, wiring.portIndex, "out");
503 const worldPt = clientToWorld(event.clientX, event.clientY);
504 rubberPath.setAttribute("d", bezier(from.x, from.y, worldPt.x, worldPt.y));
505 }
506 return;
507 }
508 const dx = event.clientX - drag.startClientX;
509 const dy = event.clientY - drag.startClientY;
510 if (Math.hypot(dx, dy) > 4)
511 { drag.moved = true; }
512 if (drag.mode === "pan")
513 {
514 view.x = drag.originViewX + dx;
515 view.y = drag.originViewY + dy;
516 applyTransform();
517 return;
518 }
519 if (drag.mode === "card")
520 {
521 drag.step.editorX = drag.originEditorX + dx / view.zoom;
522 drag.step.editorY = drag.originEditorY + dy / view.zoom;
523 refreshCardsOnly();
524 redrawEdges();
525 return;
526 }
527 if (drag.mode === "wire")
528 {
529 const draft = getDraft();
530 const fromStep = draft?.steps?.find((s) => s.stepId === drag.fromStepId);
531 if (!fromStep)
532 { return; }
533 const index = draft.steps.indexOf(fromStep);
534 const from = portWorldPos(fromStep, index, drag.portIndex, "out");
535 const worldPt = clientToWorld(event.clientX, event.clientY);
536 rubberPath.setAttribute("d", bezier(from.x, from.y, worldPt.x, worldPt.y));
537 }
538 }
539
540 function onPointerUp (event)
541 {
542 if (!drag)
543 { return; }
544 const finished = drag;
545 drag = null;
546 stopAutoPan();
547 for (const el of cardsLayer.querySelectorAll(".dragging"))
548 { el.classList.remove("dragging"); }
549 if (finished.mode === "card")
550 {
551 if (!finished.moved)
552 { onOpenStep(finished.step.stepId); }
553 else
554 { onChange(); }
555 refresh();
556 return;
557 }
558 if (finished.mode === "wire")
559 {
560 // Keep wiring selected until input click or cancel
561 if (!wiring)
562 { clearWiring(); }
563 refresh();
564 return;
565 }
566 if (finished.mode === "pan" && !finished.moved && event.button === 0)
567 {
568 clearWiring();
569 refresh();
570 }
571 }
572
573 viewport.addEventListener("pointerdown", (event) =>
574 {
575 if (event.button === 2)
576 { return; }
577 if (event.button !== 0)
578 { return; }
579 if (event.target.closest(".dialogue-canvas-card, .dialogue-canvas-context"))
580 { return; }
581 hideContext();
582 drag = {
583 mode: "pan",
584 startClientX: event.clientX,
585 startClientY: event.clientY,
586 originViewX: view.x,
587 originViewY: view.y,
588 moved: false
589 };
590 viewport.setPointerCapture(event.pointerId);
591 });
592
593 viewport.addEventListener("contextmenu", (event) =>
594 {
595 event.preventDefault();
596 // RMB cancels an in-progress wire/rewire.
597 if (wiring)
598 {
599 clearWiring();
600 hideContext();
601 refresh();
602 return;
603 }
604 if (event.target.closest(".dialogue-canvas-card"))
605 { return; }
606 const worldPt = clientToWorld(event.clientX, event.clientY);
607 ctxWorld = worldPt;
608 const rect = wrap.getBoundingClientRect();
609 ctxMenu.hidden = false;
610 ctxMenu.style.left = `${event.clientX - rect.left}px`;
611 ctxMenu.style.top = `${event.clientY - rect.top}px`;
612 });
613
614 createBtn.addEventListener("click", () =>
615 {
616 hideContext();
617 onCreateStep(ctxWorld.x, ctxWorld.y);
618 });
619
620 viewport.addEventListener("wheel", (event) =>
621 {
622 event.preventDefault();
623 const rect = viewport.getBoundingClientRect();
624 const mx = event.clientX - rect.left;
625 const my = event.clientY - rect.top;
626 const before = {
627 x: (mx - view.x) / view.zoom,
628 y: (my - view.y) / view.zoom
629 };
630 const factor = event.deltaY < 0 ? 1.08 : 1 / 1.08;
631 view.zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, view.zoom * factor));
632 view.x = mx - before.x * view.zoom;
633 view.y = my - before.y * view.zoom;
634 applyTransform();
635 }, { passive: false });
636
637 window.addEventListener("pointermove", onPointerMove);
638 window.addEventListener("pointerup", onPointerUp);
639 window.addEventListener("pointercancel", onPointerUp);
640 window.addEventListener("keydown", (event) =>
641 {
642 if (event.key === "Escape")
643 {
644 clearWiring();
645 hideContext();
646 refresh();
647 }
648 });
649
650 applyTransform();
651
652 return {
653 el: wrap,
654 refresh,
655 clearWiring: () =>
656 {
657 clearWiring();
658 refresh();
659 },
660 destroy ()
661 {
662 stopAutoPan();
663 window.removeEventListener("pointermove", onPointerMove);
664 window.removeEventListener("pointerup", onPointerUp);
665 window.removeEventListener("pointercancel", onPointerUp);
666 wrap.remove();
667 }
668 };
669 }
670
671 export function blankDialogueStep (stepId, editorX, editorY)
672 {
673 const step = {
674 stepId,
675 label: stepId,
676 lines: [{ speaker: "npc", text: "…", effects: [] }],
677 itemRewards: [],
678 itemTakes: [],
679 questRewards: [],
680 exit: { kind: "end" }
681 };
682 if (Number.isFinite(editorX))
683 { step.editorX = editorX; }
684 if (Number.isFinite(editorY))
685 { step.editorY = editorY; }
686 return step;
687 }
688
689 /** Clear nextStepId references to a deleted step. */
690 export function scrubDialogueStepLinks (draft, removedStepId)
691 {
692 if (!draft?.steps)
693 { return; }
694 for (const step of draft.steps)
695 {
696 const exit = step.exit;
697 if (!exit)
698 { continue; }
699 if (exit.kind === "continue" && exit.nextStepId === removedStepId)
700 { exit.nextStepId = null; }
701 if (exit.kind === "triggers")
702 {
703 for (const trig of exit.triggers ?? [])
704 {
705 if (trig.nextStepId === removedStepId)
706 { trig.nextStepId = null; }
707 }
708 }
709 if (exit.kind === "branches")
710 {
711 for (const branch of exit.branches ?? [])
712 {
713 if (branch.nextStepId === removedStepId)
714 { branch.nextStepId = null; }
715 }
716 }
717 }
718 }
719
720 export function stepHasEdges (draft, step)
721 {
722 const exit = step?.exit ?? { kind: "end" };
723 let outgoing = false;
724 if (exit.kind === "continue")
725 { outgoing = !!exit.nextStepId; }
726 else if (exit.kind === "triggers")
727 { outgoing = (exit.triggers ?? []).some((t) => !!t.nextStepId); }
728 else if (exit.kind === "branches")
729 { outgoing = (exit.branches ?? []).some((b) => !!b.nextStepId); }
730 const incoming = (draft?.steps ?? []).some((other) =>
731 {
732 if (other === step)
733 { return false; }
734 const e = other.exit;
735 if (!e)
736 { return false; }
737 if (e.kind === "continue")
738 { return e.nextStepId === step.stepId; }
739 if (e.kind === "triggers")
740 { return (e.triggers ?? []).some((t) => t.nextStepId === step.stepId); }
741 if (e.kind === "branches")
742 { return (e.branches ?? []).some((b) => b.nextStepId === step.stepId); }
743 return false;
744 });
745 return incoming || outgoing;
746 }
@@ -0,0 +1,746 @@
1/**
2 * Desktop node-graph canvas for dialogue steps.
3 * Pan empty space, drag cards, wheel zoom, wire outputs → inputs.
4 */
5
6const CARD_W = 168;
7const CARD_H = 72;
8const PORT_R = 7;
9const EDGE_PAD = 36;
10const MIN_ZOOM = 0.35;
11const MAX_ZOOM = 2.25;
12const AUTO_PAN = 14;
13
14/**
15 * @param {{
16 * getDraft: () => object | null,
17 * onOpenStep: (stepId: string) => void,
18 * onCreateStep: (worldX: number, worldY: number) => void,
19 * onChange: () => void
20 * }} options
21 */
22export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onChange })
23{
24 const wrap = document.createElement("div");
25 wrap.className = "dialogue-canvas-wrap";
26
27 const viewport = document.createElement("div");
28 viewport.className = "dialogue-canvas-viewport";
29 viewport.tabIndex = 0;
30
31 const world = document.createElement("div");
32 world.className = "dialogue-canvas-world";
33
34 const edgesSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
35 edgesSvg.classList.add("dialogue-canvas-edges");
36 edgesSvg.setAttribute("overflow", "visible");
37
38 const cardsLayer = document.createElement("div");
39 cardsLayer.className = "dialogue-canvas-cards";
40
41 const rubberPath = document.createElementNS("http://www.w3.org/2000/svg", "path");
42 rubberPath.classList.add("dialogue-canvas-rubber");
43 rubberPath.setAttribute("fill", "none");
44
45 const ctxMenu = document.createElement("div");
46 ctxMenu.className = "dialogue-canvas-context";
47 ctxMenu.hidden = true;
48 const createBtn = document.createElement("button");
49 createBtn.type = "button";
50 createBtn.textContent = "Create new step";
51 ctxMenu.append(createBtn);
52
53 const tooltip = document.createElement("div");
54 tooltip.className = "dialogue-canvas-tooltip";
55 tooltip.hidden = true;
56
57 world.append(edgesSvg, cardsLayer);
58 edgesSvg.append(rubberPath);
59 viewport.append(world);
60 wrap.append(viewport, ctxMenu, tooltip);
61
62 /** @type {{ x: number, y: number, zoom: number }} */
63 let view = { x: 40, y: 40, zoom: 1 };
64 /** @type {null | {
65 * mode: "pan" | "card" | "wire",
66 * startClientX: number,
67 * startClientY: number,
68 * originViewX?: number,
69 * originViewY?: number,
70 * step?: object,
71 * originEditorX?: number,
72 * originEditorY?: number,
73 * moved: boolean,
74 * portKey?: string,
75 * fromStepId?: string,
76 * portIndex?: number
77 * }} */
78 let drag = null;
79 /** @type {null | { stepId: string, portIndex: number, portKey: string }} */
80 let wiring = null;
81 let ctxWorld = { x: 0, y: 0 };
82 /** @type {number | null} */
83 let autoPanRaf = null;
84 let lastPointer = { x: 0, y: 0 };
85
86 function applyTransform ()
87 {
88 world.style.transform = `translate(${view.x}px, ${view.y}px) scale(${view.zoom})`;
89 }
90
91 function clientToWorld (clientX, clientY)
92 {
93 const rect = viewport.getBoundingClientRect();
94 return {
95 x: (clientX - rect.left - view.x) / view.zoom,
96 y: (clientY - rect.top - view.y) / view.zoom
97 };
98 }
99
100 function hideContext ()
101 {
102 ctxMenu.hidden = true;
103 }
104
105 function hideTooltip ()
106 {
107 tooltip.hidden = true;
108 }
109
110 function showTooltip (text, clientX, clientY)
111 {
112 if (!text)
113 {
114 hideTooltip();
115 return;
116 }
117 tooltip.hidden = false;
118 tooltip.textContent = text;
119 const rect = wrap.getBoundingClientRect();
120 tooltip.style.left = `${clientX - rect.left + 12}px`;
121 tooltip.style.top = `${clientY - rect.top + 12}px`;
122 }
123
124 function stepPosition (step, index)
125 {
126 const x = Number.isFinite(step.editorX) ? step.editorX : 40 + (index % 4) * (CARD_W + 48);
127 const y = Number.isFinite(step.editorY) ? step.editorY : 40 + Math.floor(index / 4) * (CARD_H + 64);
128 return { x, y };
129 }
130
131 function outputPorts (step)
132 {
133 const exit = step?.exit ?? { kind: "end" };
134 if (exit.kind === "continue")
135 {
136 return [{
137 key: "continue",
138 label: "Continue",
139 nextStepId: exit.nextStepId ?? null,
140 setNext (id)
141 {
142 exit.nextStepId = id;
143 }
144 }];
145 }
146 if (exit.kind === "triggers")
147 {
148 return (exit.triggers ?? []).map((trig, i) => ({
149 key: `trigger:${i}`,
150 /** Player-facing button text (not the internal trigger id / legacy label). */
151 label: (trig.text ?? "").trim() || trig.trigger || `Trigger ${i + 1}`,
152 nextStepId: trig.nextStepId ?? null,
153 setNext (id)
154 {
155 trig.nextStepId = id;
156 }
157 }));
158 }
159 if (exit.kind === "branches")
160 {
161 return (exit.branches ?? []).map((branch, i) => ({
162 key: `branch:${i}`,
163 label: branch.label?.trim() ? branch.label : `Branch ${i + 1}`,
164 nextStepId: branch.nextStepId ?? null,
165 setNext (id)
166 {
167 branch.nextStepId = id;
168 }
169 }));
170 }
171 return [];
172 }
173
174 function portWorldPos (step, index, portIndex, kind)
175 {
176 const pos = stepPosition(step, index);
177 if (kind === "in")
178 {
179 return { x: pos.x + CARD_W / 2, y: pos.y };
180 }
181 const ports = outputPorts(step);
182 const n = Math.max(1, ports.length);
183 const spacing = CARD_W / (n + 1);
184 return {
185 x: pos.x + spacing * (portIndex + 1),
186 y: pos.y + CARD_H
187 };
188 }
189
190 function bezier (x1, y1, x2, y2)
191 {
192 const dy = Math.max(40, Math.abs(y2 - y1) * 0.45);
193 return `M ${x1} ${y1} C ${x1} ${y1 + dy}, ${x2} ${y2 - dy}, ${x2} ${y2}`;
194 }
195
196 function clearWiring ()
197 {
198 wiring = null;
199 rubberPath.setAttribute("d", "");
200 rubberPath.classList.remove("active");
201 wrap.classList.remove("dialogue-canvas-wiring");
202 for (const el of cardsLayer.querySelectorAll(".dialogue-canvas-input.show"))
203 { el.classList.remove("show"); }
204 }
205
206 function setWiring (stepId, portIndex, portKey)
207 {
208 wiring = { stepId, portIndex, portKey };
209 wrap.classList.add("dialogue-canvas-wiring");
210 for (const el of cardsLayer.querySelectorAll(".dialogue-canvas-input"))
211 {
212 if (el.getAttribute("data-step-id") !== stepId)
213 { el.classList.add("show"); }
214 }
215 }
216
217 function stopAutoPan ()
218 {
219 if (autoPanRaf != null)
220 {
221 cancelAnimationFrame(autoPanRaf);
222 autoPanRaf = null;
223 }
224 }
225
226 function tickAutoPan ()
227 {
228 autoPanRaf = null;
229 if (!drag || drag.mode !== "card")
230 { return; }
231 const rect = viewport.getBoundingClientRect();
232 let dx = 0;
233 let dy = 0;
234 if (lastPointer.x < rect.left + EDGE_PAD)
235 { dx = AUTO_PAN; }
236 else if (lastPointer.x > rect.right - EDGE_PAD)
237 { dx = -AUTO_PAN; }
238 if (lastPointer.y < rect.top + EDGE_PAD)
239 { dy = AUTO_PAN; }
240 else if (lastPointer.y > rect.bottom - EDGE_PAD)
241 { dy = -AUTO_PAN; }
242 if (dx || dy)
243 {
244 view.x += dx;
245 view.y += dy;
246 applyTransform();
247 const worldPt = clientToWorld(lastPointer.x, lastPointer.y);
248 drag.step.editorX = worldPt.x - CARD_W / 2;
249 drag.step.editorY = worldPt.y - CARD_H / 2;
250 refreshCardsOnly();
251 redrawEdges();
252 }
253 autoPanRaf = requestAnimationFrame(tickAutoPan);
254 }
255
256 function redrawEdges ()
257 {
258 const draft = getDraft();
259 for (const el of [...edgesSvg.children])
260 {
261 if (el !== rubberPath)
262 { el.remove(); }
263 }
264 if (rubberPath.parentNode !== edgesSvg)
265 { edgesSvg.append(rubberPath); }
266 if (!draft?.steps?.length)
267 { return; }
268 draft.steps.forEach((step, index) =>
269 {
270 const ports = outputPorts(step);
271 ports.forEach((port, portIndex) =>
272 {
273 if (!port.nextStepId)
274 { return; }
275 const targetIndex = draft.steps.findIndex((s) => s.stepId === port.nextStepId);
276 if (targetIndex < 0)
277 { return; }
278 const from = portWorldPos(step, index, portIndex, "out");
279 const to = portWorldPos(draft.steps[targetIndex], targetIndex, 0, "in");
280 const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
281 path.classList.add("dialogue-canvas-edge");
282 const rewiring = !!wiring
283 && wiring.stepId === step.stepId
284 && wiring.portIndex === portIndex;
285 if (rewiring)
286 { path.classList.add("is-rewiring"); }
287 path.setAttribute("d", bezier(from.x, from.y, to.x, to.y));
288 path.setAttribute("fill", "none");
289 edgesSvg.insertBefore(path, rubberPath);
290 });
291 });
292 }
293
294 function refreshCardsOnly ()
295 {
296 const draft = getDraft();
297 if (!draft)
298 {
299 cardsLayer.replaceChildren();
300 return;
301 }
302 const existing = new Map(
303 [...cardsLayer.querySelectorAll(".dialogue-canvas-card")]
304 .map((el) => [el.getAttribute("data-step-id"), el])
305 );
306 const keep = new Set();
307 draft.steps.forEach((step, index) =>
308 {
309 keep.add(step.stepId);
310 let card = existing.get(step.stepId);
311 if (!card)
312 {
313 card = buildCard(step, index);
314 cardsLayer.append(card);
315 }
316 else
317 { updateCard(card, step, index); }
318 const pos = stepPosition(step, index);
319 card.style.left = `${pos.x}px`;
320 card.style.top = `${pos.y}px`;
321 });
322 for (const [id, el] of existing)
323 {
324 if (!keep.has(id))
325 { el.remove(); }
326 }
327 }
328
329 function buildCard (step, index)
330 {
331 const card = document.createElement("div");
332 card.className = "dialogue-canvas-card";
333 card.setAttribute("data-step-id", step.stepId);
334
335 const input = document.createElement("button");
336 input.type = "button";
337 input.className = "dialogue-canvas-input";
338 input.title = "Connect here";
339 input.setAttribute("data-step-id", step.stepId);
340 input.addEventListener("pointerdown", (event) =>
341 {
342 event.stopPropagation();
343 event.preventDefault();
344 if (!wiring)
345 { return; }
346 if (wiring.stepId === step.stepId)
347 { return; }
348 const draft = getDraft();
349 const from = draft?.steps?.find((s) => s.stepId === wiring.stepId);
350 if (!from)
351 { return; }
352 const ports = outputPorts(from);
353 const port = ports[wiring.portIndex];
354 if (!port)
355 { return; }
356 port.setNext(step.stepId);
357 clearWiring();
358 onChange();
359 refresh();
360 });
361
362 const label = document.createElement("div");
363 label.className = "dialogue-canvas-card-label";
364
365 const meta = document.createElement("div");
366 meta.className = "dialogue-canvas-card-meta";
367
368 const portsRow = document.createElement("div");
369 portsRow.className = "dialogue-canvas-ports";
370
371 card.append(input, label, meta, portsRow);
372
373 card.addEventListener("pointerdown", (event) =>
374 {
375 if (event.button !== 0)
376 { return; }
377 if (event.target.closest(".dialogue-canvas-port, .dialogue-canvas-input"))
378 { return; }
379 event.preventDefault();
380 hideContext();
381 const draft = getDraft();
382 const live = draft?.steps?.find((s) => s.stepId === step.stepId);
383 if (!live)
384 { return; }
385 const pos = stepPosition(live, draft.steps.indexOf(live));
386 if (!Number.isFinite(live.editorX))
387 { live.editorX = pos.x; }
388 if (!Number.isFinite(live.editorY))
389 { live.editorY = pos.y; }
390 drag = {
391 mode: "card",
392 startClientX: event.clientX,
393 startClientY: event.clientY,
394 step: live,
395 originEditorX: live.editorX,
396 originEditorY: live.editorY,
397 moved: false
398 };
399 lastPointer = { x: event.clientX, y: event.clientY };
400 card.classList.add("dragging");
401 card.setPointerCapture(event.pointerId);
402 stopAutoPan();
403 autoPanRaf = requestAnimationFrame(tickAutoPan);
404 });
405
406 updateCard(card, step, index);
407 return card;
408 }
409
410 function updateCard (card, step, index)
411 {
412 card.setAttribute("data-step-id", step.stepId);
413 const draft = getDraft();
414 const isEntry = draft && (draft.entryStepId === step.stepId
415 || (!draft.entryStepId && draft.steps[0] === step));
416 card.classList.toggle("is-entry", !!isEntry);
417 const label = card.querySelector(".dialogue-canvas-card-label");
418 if (label)
419 { label.textContent = step.label || step.stepId; }
420 const meta = card.querySelector(".dialogue-canvas-card-meta");
421 if (meta)
422 {
423 const kind = step.exit?.kind ?? "end";
424 meta.textContent = isEntry ? `entry · ${kind}` : kind;
425 }
426 const input = card.querySelector(".dialogue-canvas-input");
427 if (input)
428 {
429 input.setAttribute("data-step-id", step.stepId);
430 input.classList.toggle("show", !!wiring && wiring.stepId !== step.stepId);
431 }
432 const portsRow = card.querySelector(".dialogue-canvas-ports");
433 if (!portsRow)
434 { return; }
435 portsRow.replaceChildren();
436 const ports = outputPorts(step);
437 ports.forEach((port, portIndex) =>
438 {
439 const btn = document.createElement("button");
440 btn.type = "button";
441 btn.className = "dialogue-canvas-port";
442 btn.title = port.label;
443 btn.classList.toggle("linked", !!port.nextStepId);
444 btn.classList.toggle("selected",
445 !!wiring && wiring.stepId === step.stepId && wiring.portIndex === portIndex);
446 btn.addEventListener("pointerdown", (event) =>
447 {
448 event.stopPropagation();
449 event.preventDefault();
450 hideContext();
451 // Clicking an output always starts/continues wire mode (existing link stays until
452 // a new input is chosen; that edge is drawn red via is-rewiring).
453 setWiring(step.stepId, portIndex, port.key);
454 drag = {
455 mode: "wire",
456 startClientX: event.clientX,
457 startClientY: event.clientY,
458 moved: false,
459 fromStepId: step.stepId,
460 portIndex,
461 portKey: port.key
462 };
463 const from = portWorldPos(step, index, portIndex, "out");
464 const worldPt = clientToWorld(event.clientX, event.clientY);
465 rubberPath.classList.add("active");
466 rubberPath.setAttribute("d", bezier(from.x, from.y, worldPt.x, worldPt.y));
467 refreshCardsOnly();
468 redrawEdges();
469 });
470 btn.addEventListener("pointerenter", (event) =>
471 {
472 showTooltip(port.label, event.clientX, event.clientY);
473 });
474 btn.addEventListener("pointerleave", () => hideTooltip());
475 btn.addEventListener("pointermove", (event) =>
476 {
477 showTooltip(port.label, event.clientX, event.clientY);
478 });
479 portsRow.append(btn);
480 });
481 }
482
483 function refresh ()
484 {
485 applyTransform();
486 refreshCardsOnly();
487 redrawEdges();
488 }
489
490 function onPointerMove (event)
491 {
492 lastPointer = { x: event.clientX, y: event.clientY };
493 if (!drag)
494 {
495 if (wiring)
496 {
497 const draft = getDraft();
498 const fromStep = draft?.steps?.find((s) => s.stepId === wiring.stepId);
499 if (!fromStep)
500 { return; }
501 const index = draft.steps.indexOf(fromStep);
502 const from = portWorldPos(fromStep, index, wiring.portIndex, "out");
503 const worldPt = clientToWorld(event.clientX, event.clientY);
504 rubberPath.setAttribute("d", bezier(from.x, from.y, worldPt.x, worldPt.y));
505 }
506 return;
507 }
508 const dx = event.clientX - drag.startClientX;
509 const dy = event.clientY - drag.startClientY;
510 if (Math.hypot(dx, dy) > 4)
511 { drag.moved = true; }
512 if (drag.mode === "pan")
513 {
514 view.x = drag.originViewX + dx;
515 view.y = drag.originViewY + dy;
516 applyTransform();
517 return;
518 }
519 if (drag.mode === "card")
520 {
521 drag.step.editorX = drag.originEditorX + dx / view.zoom;
522 drag.step.editorY = drag.originEditorY + dy / view.zoom;
523 refreshCardsOnly();
524 redrawEdges();
525 return;
526 }
527 if (drag.mode === "wire")
528 {
529 const draft = getDraft();
530 const fromStep = draft?.steps?.find((s) => s.stepId === drag.fromStepId);
531 if (!fromStep)
532 { return; }
533 const index = draft.steps.indexOf(fromStep);
534 const from = portWorldPos(fromStep, index, drag.portIndex, "out");
535 const worldPt = clientToWorld(event.clientX, event.clientY);
536 rubberPath.setAttribute("d", bezier(from.x, from.y, worldPt.x, worldPt.y));
537 }
538 }
539
540 function onPointerUp (event)
541 {
542 if (!drag)
543 { return; }
544 const finished = drag;
545 drag = null;
546 stopAutoPan();
547 for (const el of cardsLayer.querySelectorAll(".dragging"))
548 { el.classList.remove("dragging"); }
549 if (finished.mode === "card")
550 {
551 if (!finished.moved)
552 { onOpenStep(finished.step.stepId); }
553 else
554 { onChange(); }
555 refresh();
556 return;
557 }
558 if (finished.mode === "wire")
559 {
560 // Keep wiring selected until input click or cancel
561 if (!wiring)
562 { clearWiring(); }
563 refresh();
564 return;
565 }
566 if (finished.mode === "pan" && !finished.moved && event.button === 0)
567 {
568 clearWiring();
569 refresh();
570 }
571 }
572
573 viewport.addEventListener("pointerdown", (event) =>
574 {
575 if (event.button === 2)
576 { return; }
577 if (event.button !== 0)
578 { return; }
579 if (event.target.closest(".dialogue-canvas-card, .dialogue-canvas-context"))
580 { return; }
581 hideContext();
582 drag = {
583 mode: "pan",
584 startClientX: event.clientX,
585 startClientY: event.clientY,
586 originViewX: view.x,
587 originViewY: view.y,
588 moved: false
589 };
590 viewport.setPointerCapture(event.pointerId);
591 });
592
593 viewport.addEventListener("contextmenu", (event) =>
594 {
595 event.preventDefault();
596 // RMB cancels an in-progress wire/rewire.
597 if (wiring)
598 {
599 clearWiring();
600 hideContext();
601 refresh();
602 return;
603 }
604 if (event.target.closest(".dialogue-canvas-card"))
605 { return; }
606 const worldPt = clientToWorld(event.clientX, event.clientY);
607 ctxWorld = worldPt;
608 const rect = wrap.getBoundingClientRect();
609 ctxMenu.hidden = false;
610 ctxMenu.style.left = `${event.clientX - rect.left}px`;
611 ctxMenu.style.top = `${event.clientY - rect.top}px`;
612 });
613
614 createBtn.addEventListener("click", () =>
615 {
616 hideContext();
617 onCreateStep(ctxWorld.x, ctxWorld.y);
618 });
619
620 viewport.addEventListener("wheel", (event) =>
621 {
622 event.preventDefault();
623 const rect = viewport.getBoundingClientRect();
624 const mx = event.clientX - rect.left;
625 const my = event.clientY - rect.top;
626 const before = {
627 x: (mx - view.x) / view.zoom,
628 y: (my - view.y) / view.zoom
629 };
630 const factor = event.deltaY < 0 ? 1.08 : 1 / 1.08;
631 view.zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, view.zoom * factor));
632 view.x = mx - before.x * view.zoom;
633 view.y = my - before.y * view.zoom;
634 applyTransform();
635 }, { passive: false });
636
637 window.addEventListener("pointermove", onPointerMove);
638 window.addEventListener("pointerup", onPointerUp);
639 window.addEventListener("pointercancel", onPointerUp);
640 window.addEventListener("keydown", (event) =>
641 {
642 if (event.key === "Escape")
643 {
644 clearWiring();
645 hideContext();
646 refresh();
647 }
648 });
649
650 applyTransform();
651
652 return {
653 el: wrap,
654 refresh,
655 clearWiring: () =>
656 {
657 clearWiring();
658 refresh();
659 },
660 destroy ()
661 {
662 stopAutoPan();
663 window.removeEventListener("pointermove", onPointerMove);
664 window.removeEventListener("pointerup", onPointerUp);
665 window.removeEventListener("pointercancel", onPointerUp);
666 wrap.remove();
667 }
668 };
669}
670
671export function blankDialogueStep (stepId, editorX, editorY)
672{
673 const step = {
674 stepId,
675 label: stepId,
676 lines: [{ speaker: "npc", text: "…", effects: [] }],
677 itemRewards: [],
678 itemTakes: [],
679 questRewards: [],
680 exit: { kind: "end" }
681 };
682 if (Number.isFinite(editorX))
683 { step.editorX = editorX; }
684 if (Number.isFinite(editorY))
685 { step.editorY = editorY; }
686 return step;
687}
688
689/** Clear nextStepId references to a deleted step. */
690export function scrubDialogueStepLinks (draft, removedStepId)
691{
692 if (!draft?.steps)
693 { return; }
694 for (const step of draft.steps)
695 {
696 const exit = step.exit;
697 if (!exit)
698 { continue; }
699 if (exit.kind === "continue" && exit.nextStepId === removedStepId)
700 { exit.nextStepId = null; }
701 if (exit.kind === "triggers")
702 {
703 for (const trig of exit.triggers ?? [])
704 {
705 if (trig.nextStepId === removedStepId)
706 { trig.nextStepId = null; }
707 }
708 }
709 if (exit.kind === "branches")
710 {
711 for (const branch of exit.branches ?? [])
712 {
713 if (branch.nextStepId === removedStepId)
714 { branch.nextStepId = null; }
715 }
716 }
717 }
718}
719
720export function stepHasEdges (draft, step)
721{
722 const exit = step?.exit ?? { kind: "end" };
723 let outgoing = false;
724 if (exit.kind === "continue")
725 { outgoing = !!exit.nextStepId; }
726 else if (exit.kind === "triggers")
727 { outgoing = (exit.triggers ?? []).some((t) => !!t.nextStepId); }
728 else if (exit.kind === "branches")
729 { outgoing = (exit.branches ?? []).some((b) => !!b.nextStepId); }
730 const incoming = (draft?.steps ?? []).some((other) =>
731 {
732 if (other === step)
733 { return false; }
734 const e = other.exit;
735 if (!e)
736 { return false; }
737 if (e.kind === "continue")
738 { return e.nextStepId === step.stepId; }
739 if (e.kind === "triggers")
740 { return (e.triggers ?? []).some((t) => t.nextStepId === step.stepId); }
741 if (e.kind === "branches")
742 { return (e.branches ?? []).some((b) => b.nextStepId === step.stepId); }
743 return false;
744 });
745 return incoming || outgoing;
746}
client/src/editor/dialogueSimulate.js +8 −0
@@ -178,6 +178,14 @@ export function initDialogueSimulate ({ getTree, getQuestTitle = null } = {})
178 178 renderBranchChoices(exit.branches ?? []);
179 179 return;
180 180 }
181 if (exit.kind === "continue")
182 {
183 if (exit.nextStepId)
184 { enterStep(exit.nextStepId); }
185 else
186 { show(false); }
187 return;
188 }
181 189 show(false);
182 190 }
183 191
@@ -178,6 +178,14 @@ export function initDialogueSimulate ({ getTree, getQuestTitle = null } = {})
178 renderBranchChoices(exit.branches ?? []);
178 renderBranchChoices(exit.branches ?? []);
179 return;
179 return;
180 }
180 }
181 if (exit.kind === "continue")
182 {
183 if (exit.nextStepId)
184 { enterStep(exit.nextStepId); }
185 else
186 { show(false); }
187 return;
188 }
181 show(false);
189 show(false);
182 }
190 }
183
191
client/src/editor/dialogueStepModal.js added +913 −0
@@ -0,0 +1,913 @@
1 /**
2 * Step detail modal for the dialogue canvas editor.
3 */
4 import { emptyConditionSet } from "/shared/quests/conditions.js";
5 import {
6 dialogueTakeIsUnguaranteed,
7 unguaranteedDialogueTakes
8 } from "/shared/quests/dialoguePathTakes.js";
9 import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
10 import { renderConditionSet } from "./conditionSetEditor.js";
11 import { scrubDialogueStepLinks, stepHasEdges } from "./dialogueCanvas.js";
12
13 /**
14 * @param {{
15 * getDraft: () => object | null,
16 * getQuestCatalog: () => object[],
17 * getDialogues: () => object[],
18 * conditionCtx: () => object,
19 * onChange: () => void,
20 * host?: HTMLElement | null
21 * }} options
22 */
23 export function initDialogueStepModal ({
24 getDraft,
25 getQuestCatalog,
26 getDialogues,
27 conditionCtx,
28 onChange,
29 host = null
30 })
31 {
32 const root = document.createElement("div");
33 root.className = "dialogue-step-overlay";
34 root.hidden = true;
35
36 const backdrop = document.createElement("div");
37 backdrop.className = "dialogue-step-backdrop";
38
39 const panel = document.createElement("div");
40 panel.className = "dialogue-step-panel";
41
42 const header = document.createElement("header");
43 const title = document.createElement("h3");
44 title.textContent = "Step";
45 const closeBtn = document.createElement("button");
46 closeBtn.type = "button";
47 closeBtn.textContent = "Close";
48 header.append(title, closeBtn);
49
50 const body = document.createElement("div");
51 body.className = "dialogue-step-body";
52
53 root.append(backdrop, panel);
54 panel.append(header, body);
55 (host || document.body).append(root);
56
57 /** @type {string | null} */
58 let openStepId = null;
59 /** @type {null | {
60 * step: object,
61 * field: "itemRewards" | "itemTakes",
62 * resultsEl: HTMLElement,
63 * inputEl: HTMLInputElement
64 * }} */
65 let itemPickContext = null;
66
67 function show (visible)
68 {
69 root.hidden = !visible;
70 if (!visible)
71 {
72 openStepId = null;
73 itemPickContext = null;
74 body.replaceChildren();
75 }
76 }
77
78 function currentStep ()
79 {
80 const draft = getDraft();
81 if (!draft || !openStepId)
82 { return null; }
83 return draft.steps.find((s) => s.stepId === openStepId) ?? null;
84 }
85
86 function closeInlineItemSearch ()
87 {
88 if (itemPickContext?.resultsEl)
89 { itemPickContext.resultsEl.replaceChildren(); }
90 itemPickContext = null;
91 }
92
93 function openInlineItemSearch (step, field, inputEl, resultsEl)
94 {
95 itemPickContext = { step, field, inputEl, resultsEl };
96 inputEl.value = "";
97 renderInlineItemSearch("");
98 inputEl.focus();
99 }
100
101 function renderInlineItemSearch (query)
102 {
103 if (!itemPickContext)
104 { return; }
105 const { step, field, resultsEl } = itemPickContext;
106 resultsEl.replaceChildren();
107 const q = String(query ?? "").trim().toLowerCase();
108 const taken = new Set((step[field] ?? []).map((row) => row.itemId));
109 const matches = listAllItemPickerEntries().filter((item) =>
110 {
111 if (taken.has(item.itemId))
112 { return false; }
113 if (!q)
114 { return true; }
115 return item.displayName.toLowerCase().includes(q)
116 || item.key.toLowerCase().includes(q)
117 || String(item.itemId).includes(q);
118 }).slice(0, 40);
119 if (!matches.length)
120 {
121 resultsEl.textContent = "No matching items.";
122 return;
123 }
124 for (const item of matches)
125 {
126 const row = document.createElement("button");
127 row.type = "button";
128 row.className = "shop-item-search-row";
129 const name = document.createElement("span");
130 name.className = "shop-item-search-row-name";
131 name.textContent = item.displayName;
132 const key = document.createElement("span");
133 key.className = "shop-item-search-row-key";
134 key.textContent = `${item.key} · #${item.itemId}`;
135 row.append(name, key);
136 row.addEventListener("click", () =>
137 {
138 if (!Array.isArray(step[field]))
139 { step[field] = []; }
140 step[field].push({ itemId: item.itemId, quantity: 1 });
141 closeInlineItemSearch();
142 onChange();
143 render();
144 });
145 resultsEl.append(row);
146 }
147 }
148
149 function refreshTakeHighlights ()
150 {
151 const draft = getDraft();
152 if (!draft)
153 { return; }
154 const warnings = unguaranteedDialogueTakes(draft);
155 for (const row of body.querySelectorAll("[data-take-step-id][data-take-item-id]"))
156 {
157 const stepId = row.getAttribute("data-take-step-id");
158 const itemId = Number(row.getAttribute("data-take-item-id"));
159 const bad = dialogueTakeIsUnguaranteed(warnings, stepId, itemId);
160 row.classList.toggle("dialogue-item-take-unguaranteed", bad);
161 row.title = bad
162 ? "Not guaranteed by every branch/trigger path to this step."
163 : "";
164 }
165 }
166
167 function openSubModal (titleText, build)
168 {
169 const sub = document.createElement("div");
170 sub.className = "dialogue-step-submodal";
171 const subPanel = document.createElement("div");
172 subPanel.className = "dialogue-step-subpanel";
173 const subHead = document.createElement("header");
174 const h = document.createElement("h4");
175 h.textContent = titleText;
176 const done = document.createElement("button");
177 done.type = "button";
178 done.textContent = "Done";
179 subHead.append(h, done);
180 const subBody = document.createElement("div");
181 subBody.className = "dialogue-step-subbody";
182 subPanel.append(subHead, subBody);
183 sub.append(subPanel);
184 panel.append(sub);
185 const close = () => sub.remove();
186 done.addEventListener("click", close);
187 sub.addEventListener("click", (event) =>
188 {
189 if (event.target === sub)
190 { close(); }
191 });
192 build(subBody, close);
193 return close;
194 }
195
196 function openRewardsUi (step)
197 {
198 openSubModal("Rewards & takes", (subBody) =>
199 {
200 if (!Array.isArray(step.itemRewards))
201 { step.itemRewards = []; }
202 if (!Array.isArray(step.itemTakes))
203 { step.itemTakes = []; }
204
205 const rewardsHead = sectionHeader("Item rewards", () =>
206 {
207 searchWrap.hidden = false;
208 openInlineItemSearch(step, "itemRewards", searchInput, searchResults);
209 });
210 subBody.append(rewardsHead);
211 const rewardsHint = document.createElement("p");
212 rewardsHint.className = "content-editor-hint";
213 rewardsHint.textContent = "Granted after all lines, before triggers/branches.";
214 subBody.append(rewardsHint);
215
216 const searchWrap = document.createElement("div");
217 searchWrap.className = "dialogue-reward-item-search";
218 searchWrap.hidden = true;
219 const searchInput = document.createElement("input");
220 searchInput.type = "search";
221 searchInput.placeholder = "Search items…";
222 searchInput.autocomplete = "off";
223 searchInput.addEventListener("input", () => renderInlineItemSearch(searchInput.value));
224 const searchResults = document.createElement("div");
225 searchResults.className = "dialogue-reward-item-results";
226 searchWrap.append(searchInput, searchResults);
227
228 const rewardsList = document.createElement("div");
229 function renderRewards ()
230 {
231 rewardsList.replaceChildren();
232 if (!step.itemRewards.length)
233 {
234 const empty = document.createElement("p");
235 empty.className = "content-editor-hint";
236 empty.textContent = "No item rewards.";
237 rewardsList.append(empty);
238 }
239 step.itemRewards.forEach((reward, rewardIndex) =>
240 {
241 const def = itemDefinition(reward.itemId);
242 const row = document.createElement("div");
243 row.className = "spawner-drops-row";
244 const name = document.createElement("span");
245 name.className = "spawner-sells-name";
246 name.textContent = def?.displayName ?? `Item ${reward.itemId}`;
247 const qty = document.createElement("input");
248 qty.type = "number";
249 qty.min = "1";
250 qty.step = "1";
251 qty.value = String(Math.max(1, reward.quantity | 0 || 1));
252 qty.title = "Quantity";
253 qty.addEventListener("input", () =>
254 {
255 step.itemRewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
256 onChange();
257 });
258 row.append(name, qty, removeButton(() =>
259 {
260 step.itemRewards.splice(rewardIndex, 1);
261 onChange();
262 renderRewards();
263 render();
264 }));
265 rewardsList.append(row);
266 });
267 }
268 renderRewards();
269 subBody.append(rewardsList, searchWrap);
270
271 const takesHead = sectionHeader("Item takes", () =>
272 {
273 takeSearchWrap.hidden = false;
274 openInlineItemSearch(step, "itemTakes", takeSearchInput, takeSearchResults);
275 });
276 subBody.append(takesHead);
277 const takesHint = document.createElement("p");
278 takesHint.className = "content-editor-hint";
279 takesHint.textContent = "Removed from the bag after all lines (soft). Yellow = not guaranteed on every path.";
280 subBody.append(takesHint);
281
282 const takeSearchWrap = document.createElement("div");
283 takeSearchWrap.className = "dialogue-reward-item-search";
284 takeSearchWrap.hidden = true;
285 const takeSearchInput = document.createElement("input");
286 takeSearchInput.type = "search";
287 takeSearchInput.placeholder = "Search items…";
288 takeSearchInput.autocomplete = "off";
289 takeSearchInput.addEventListener("input", () => renderInlineItemSearch(takeSearchInput.value));
290 const takeSearchResults = document.createElement("div");
291 takeSearchResults.className = "dialogue-reward-item-results";
292 takeSearchWrap.append(takeSearchInput, takeSearchResults);
293
294 const takesList = document.createElement("div");
295 const draft = getDraft();
296 const takeWarnings = draft ? unguaranteedDialogueTakes(draft) : new Map();
297 function renderTakes ()
298 {
299 takesList.replaceChildren();
300 if (!step.itemTakes.length)
301 {
302 const empty = document.createElement("p");
303 empty.className = "content-editor-hint";
304 empty.textContent = "No item takes.";
305 takesList.append(empty);
306 }
307 step.itemTakes.forEach((take, takeIndex) =>
308 {
309 const def = itemDefinition(take.itemId);
310 const row = document.createElement("div");
311 row.className = "spawner-drops-row";
312 row.setAttribute("data-take-step-id", step.stepId);
313 row.setAttribute("data-take-item-id", String(take.itemId));
314 if (dialogueTakeIsUnguaranteed(takeWarnings, step.stepId, take.itemId))
315 {
316 row.classList.add("dialogue-item-take-unguaranteed");
317 row.title = "Not guaranteed by every branch/trigger path to this step.";
318 }
319 const name = document.createElement("span");
320 name.className = "spawner-sells-name";
321 name.textContent = def?.displayName ?? `Item ${take.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, take.quantity | 0 || 1));
327 qty.title = "Quantity";
328 qty.addEventListener("input", () =>
329 {
330 step.itemTakes[takeIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
331 onChange();
332 refreshTakeHighlights();
333 });
334 row.append(name, qty, removeButton(() =>
335 {
336 step.itemTakes.splice(takeIndex, 1);
337 onChange();
338 renderTakes();
339 render();
340 }));
341 takesList.append(row);
342 });
343 }
344 renderTakes();
345 subBody.append(takesList, takeSearchWrap);
346 });
347 }
348
349 function openQuestsUi (step)
350 {
351 openSubModal("Quest rewards", (subBody) =>
352 {
353 if (!Array.isArray(step.questRewards))
354 { step.questRewards = []; }
355 const questCatalog = getQuestCatalog();
356 const head = sectionHeader("Quest rewards", () =>
357 {
358 const available = questCatalog.find((q) => !step.questRewards.includes(q.questId));
359 if (!available)
360 { return; }
361 step.questRewards.push(available.questId);
362 onChange();
363 renderQuests();
364 render();
365 });
366 subBody.append(head);
367 const hint = document.createElement("p");
368 hint.className = "content-editor-hint";
369 hint.textContent = "Started after all lines (with item rewards), before triggers/branches.";
370 subBody.append(hint);
371 const list = document.createElement("div");
372 function renderQuests ()
373 {
374 list.replaceChildren();
375 if (!step.questRewards.length)
376 {
377 const empty = document.createElement("p");
378 empty.className = "content-editor-hint";
379 empty.textContent = "No quest rewards.";
380 list.append(empty);
381 }
382 step.questRewards.forEach((questId, rewardIndex) =>
383 {
384 const row = document.createElement("div");
385 row.className = "spawner-drops-row";
386 const select = document.createElement("select");
387 const taken = new Set(step.questRewards);
388 const catalog = questCatalog.length
389 ? questCatalog
390 : [{ questId, title: questId }];
391 for (const quest of catalog)
392 {
393 if (taken.has(quest.questId) && quest.questId !== questId)
394 { continue; }
395 const opt = document.createElement("option");
396 opt.value = quest.questId;
397 opt.textContent = quest.title
398 ? `${quest.title} (${quest.questId})`
399 : quest.questId;
400 select.append(opt);
401 }
402 if (![...select.options].some((o) => o.value === questId))
403 {
404 const missing = document.createElement("option");
405 missing.value = questId;
406 missing.textContent = `${questId} (missing)`;
407 select.append(missing);
408 }
409 select.value = questId;
410 select.addEventListener("change", () =>
411 {
412 step.questRewards[rewardIndex] = select.value;
413 onChange();
414 render();
415 });
416 row.append(select, removeButton(() =>
417 {
418 step.questRewards.splice(rewardIndex, 1);
419 onChange();
420 renderQuests();
421 render();
422 }));
423 list.append(row);
424 });
425 }
426 renderQuests();
427 subBody.append(list);
428 });
429 }
430
431 function openExitConfigure (step)
432 {
433 const kind = step.exit?.kind;
434 if (kind !== "branches" && kind !== "triggers")
435 { return; }
436 openSubModal(kind === "triggers" ? "Configure triggers" : "Configure branches", (subBody) =>
437 {
438 const hint = document.createElement("p");
439 hint.className = "content-editor-hint";
440 hint.textContent = kind === "triggers"
441 ? "Wire next steps on the canvas. Here you edit button text and conditions."
442 : "Wire next steps on the canvas. Here you edit labels and conditions.";
443 subBody.append(hint);
444
445 if (kind === "triggers")
446 {
447 if (!Array.isArray(step.exit.triggers))
448 { step.exit.triggers = []; }
449 const head = sectionHeader("Triggers", () =>
450 {
451 step.exit.triggers.push({
452 trigger: `choice-${step.exit.triggers.length + 1}`,
453 text: "Choice",
454 nextStepId: null,
455 when: emptyConditionSet(),
456 effects: []
457 });
458 onChange();
459 renderTriggers();
460 render();
461 });
462 subBody.append(head);
463 const list = document.createElement("div");
464 function renderTriggers ()
465 {
466 list.replaceChildren();
467 step.exit.triggers.forEach((trig, trigIndex) =>
468 {
469 const tBox = document.createElement("div");
470 tBox.className = "content-editor-section";
471 tBox.append(sectionHeader(`Trigger ${trigIndex + 1}`, null, () =>
472 {
473 step.exit.triggers.splice(trigIndex, 1);
474 onChange();
475 renderTriggers();
476 render();
477 }));
478 tBox.append(
479 field("trigger", textInput(trig.trigger, (v) =>
480 {
481 trig.trigger = v;
482 onChange();
483 })),
484 field("Button", textInput(trig.text ?? "", (v) =>
485 {
486 trig.text = v;
487 onChange();
488 render();
489 }))
490 );
491 tBox.append(renderConditionSet(trig.when, (next, { remount = true } = {}) =>
492 {
493 trig.when = next;
494 onChange();
495 if (remount)
496 { renderTriggers(); }
497 }, conditionCtx()));
498 list.append(tBox);
499 });
500 }
501 renderTriggers();
502 subBody.append(list);
503 return;
504 }
505
506 if (!Array.isArray(step.exit.branches))
507 { step.exit.branches = []; }
508 const head = sectionHeader("Branches", () =>
509 {
510 step.exit.branches.push({
511 label: "",
512 when: emptyConditionSet(),
513 nextStepId: null,
514 effects: []
515 });
516 onChange();
517 renderBranches();
518 render();
519 });
520 subBody.append(head);
521 const list = document.createElement("div");
522 function renderBranches ()
523 {
524 list.replaceChildren();
525 step.exit.branches.forEach((branch, branchIndex) =>
526 {
527 const bBox = document.createElement("div");
528 bBox.className = "content-editor-section";
529 bBox.append(sectionHeader(`Branch ${branchIndex + 1}`, null, () =>
530 {
531 step.exit.branches.splice(branchIndex, 1);
532 onChange();
533 renderBranches();
534 render();
535 }));
536 bBox.append(field("label", textInput(branch.label ?? "", (v) =>
537 {
538 branch.label = v;
539 onChange();
540 })));
541 bBox.append(renderConditionSet(branch.when, (next, { remount = true } = {}) =>
542 {
543 branch.when = next;
544 onChange();
545 if (remount)
546 { renderBranches(); }
547 }, conditionCtx()));
548 list.append(bBox);
549 });
550 }
551 renderBranches();
552 subBody.append(list);
553 });
554 }
555
556 function confirmDeleteStep (step)
557 {
558 const draft = getDraft();
559 if (!draft)
560 { return; }
561 const linked = stepHasEdges(draft, step);
562 if (!linked)
563 {
564 if (!window.confirm(`Delete dialogue step "${step.label || step.stepId}"?`))
565 { return; }
566 deleteStep(step);
567 return;
568 }
569 openSubModal("Delete step?", (subBody, close) =>
570 {
571 subBody.classList.add("dialogue-step-delete-warn");
572 const warn = document.createElement("p");
573 warn.className = "dialogue-step-delete-warn-text";
574 warn.textContent = `“${step.label || step.stepId}” has incoming or outgoing connections. Deleting it will remove those links.`;
575 const actions = document.createElement("div");
576 actions.className = "dialogue-step-delete-actions";
577 const cancel = document.createElement("button");
578 cancel.type = "button";
579 cancel.textContent = "Cancel";
580 cancel.addEventListener("click", close);
581 const confirm = document.createElement("button");
582 confirm.type = "button";
583 confirm.className = "dialogue-step-delete-confirm";
584 confirm.textContent = "Delete step";
585 confirm.addEventListener("click", () =>
586 {
587 close();
588 deleteStep(step);
589 });
590 actions.append(cancel, confirm);
591 subBody.append(warn, actions);
592 });
593 }
594
595 function deleteStep (step)
596 {
597 const draft = getDraft();
598 if (!draft)
599 { return; }
600 const index = draft.steps.indexOf(step);
601 if (index < 0)
602 { return; }
603 const removedId = step.stepId;
604 draft.steps.splice(index, 1);
605 scrubDialogueStepLinks(draft, removedId);
606 if (draft.entryStepId === removedId)
607 { draft.entryStepId = draft.steps[0]?.stepId ?? ""; }
608 if (draft.steps.length === 0)
609 {
610 draft.steps.push({
611 stepId: "greeting",
612 label: "Greeting",
613 lines: [{ speaker: "npc", text: "…", effects: [] }],
614 itemRewards: [],
615 itemTakes: [],
616 questRewards: [],
617 exit: { kind: "end" },
618 editorX: 80,
619 editorY: 80
620 });
621 draft.entryStepId = "greeting";
622 }
623 show(false);
624 onChange();
625 }
626
627 function setExitKind (step, kind)
628 {
629 if (kind === "triggers")
630 {
631 step.exit = {
632 kind: "triggers",
633 triggers: step.exit?.triggers?.length
634 ? step.exit.triggers
635 : [{
636 trigger: "continue",
637 text: "Continue",
638 nextStepId: null,
639 when: emptyConditionSet(),
640 effects: []
641 }]
642 };
643 }
644 else if (kind === "branches")
645 {
646 step.exit = {
647 kind: "branches",
648 branches: step.exit?.branches?.length
649 ? step.exit.branches
650 : [{
651 label: "",
652 when: emptyConditionSet(),
653 nextStepId: null,
654 effects: []
655 }]
656 };
657 }
658 else if (kind === "continue")
659 {
660 const prevNext = step.exit?.kind === "continue"
661 ? step.exit.nextStepId
662 : null;
663 step.exit = { kind: "continue", nextStepId: prevNext ?? null };
664 }
665 else
666 { step.exit = { kind: "end" }; }
667 }
668
669 function render ()
670 {
671 const step = currentStep();
672 body.replaceChildren();
673 if (!step)
674 {
675 show(false);
676 return;
677 }
678 title.textContent = step.label || step.stepId || "Step";
679
680 body.append(
681 field("stepId", textInput(step.stepId, (v) =>
682 {
683 const draft = getDraft();
684 const oldId = step.stepId;
685 step.stepId = v;
686 if (draft?.entryStepId === oldId)
687 { draft.entryStepId = v; }
688 scrubRename(draft, oldId, v);
689 openStepId = v;
690 onChange();
691 })),
692 field("Label", textInput(step.label ?? "", (v) =>
693 {
694 step.label = v;
695 title.textContent = v || step.stepId || "Step";
696 onChange();
697 }))
698 );
699
700 const linesHead = sectionHeader("Lines", () =>
701 {
702 step.lines.push({ speaker: "npc", text: "…", effects: [] });
703 onChange();
704 render();
705 });
706 body.append(linesHead);
707 step.lines.forEach((line, lineIndex) =>
708 {
709 const row = document.createElement("div");
710 row.className = "content-editor-row";
711 const speaker = document.createElement("select");
712 for (const s of ["npc", "player"])
713 {
714 const opt = document.createElement("option");
715 opt.value = s;
716 opt.textContent = s;
717 if (line.speaker === s)
718 { opt.selected = true; }
719 speaker.append(opt);
720 }
721 speaker.addEventListener("change", () =>
722 {
723 line.speaker = speaker.value;
724 onChange();
725 });
726 const text = document.createElement("input");
727 text.type = "text";
728 text.value = line.text ?? "";
729 text.style.flex = "1";
730 text.addEventListener("input", () =>
731 {
732 line.text = text.value;
733 onChange();
734 });
735 row.append(speaker, text, removeButton(() =>
736 {
737 if (!window.confirm("Delete this dialogue line?"))
738 { return; }
739 step.lines.splice(lineIndex, 1);
740 if (step.lines.length === 0)
741 { step.lines.push({ speaker: "npc", text: "…", effects: [] }); }
742 onChange();
743 render();
744 }));
745 body.append(row);
746 });
747
748 const actions = document.createElement("div");
749 actions.className = "dialogue-step-actions";
750
751 const rewardCount = (step.itemRewards?.length ?? 0) + (step.itemTakes?.length ?? 0);
752 const rewardsBtn = document.createElement("button");
753 rewardsBtn.type = "button";
754 rewardsBtn.textContent = rewardCount > 0 ? `Rewards (${rewardCount})` : "Rewards";
755 rewardsBtn.addEventListener("click", () => openRewardsUi(step));
756
757 const questsBtn = document.createElement("button");
758 questsBtn.type = "button";
759 questsBtn.textContent = (step.questRewards?.length ?? 0) > 0
760 ? `Quests (${step.questRewards.length})`
761 : "Quests";
762 questsBtn.addEventListener("click", () => openQuestsUi(step));
763
764 const deleteBtn = document.createElement("button");
765 deleteBtn.type = "button";
766 deleteBtn.className = "content-editor-remove";
767 deleteBtn.textContent = "Delete Step";
768 deleteBtn.addEventListener("click", () => confirmDeleteStep(step));
769
770 actions.append(rewardsBtn, questsBtn, deleteBtn);
771 body.append(actions);
772
773 const exitKind = document.createElement("select");
774 for (const k of [
775 { value: "end", label: "End" },
776 { value: "branches", label: "Branches" },
777 { value: "triggers", label: "Triggers" },
778 { value: "continue", label: "Continue" }
779 ])
780 {
781 const opt = document.createElement("option");
782 opt.value = k.value;
783 opt.textContent = k.label;
784 if ((step.exit?.kind ?? "end") === k.value)
785 { opt.selected = true; }
786 exitKind.append(opt);
787 }
788 exitKind.addEventListener("change", () =>
789 {
790 setExitKind(step, exitKind.value);
791 onChange();
792 render();
793 });
794 body.append(field("Exit", exitKind));
795
796 const configure = document.createElement("button");
797 configure.type = "button";
798 configure.textContent = "Configure";
799 const canConfigure = step.exit?.kind === "branches" || step.exit?.kind === "triggers";
800 configure.disabled = !canConfigure;
801 configure.addEventListener("click", () => openExitConfigure(step));
802 body.append(configure);
803
804 if (step.exit?.kind === "continue")
805 {
806 const note = document.createElement("p");
807 note.className = "content-editor-hint";
808 note.textContent = "Continue uses a single outgoing port on the canvas.";
809 body.append(note);
810 }
811 }
812
813 function scrubRename (draft, oldId, newId)
814 {
815 if (!draft || !oldId || oldId === newId)
816 { return; }
817 for (const other of draft.steps)
818 {
819 const exit = other.exit;
820 if (!exit)
821 { continue; }
822 if (exit.kind === "continue" && exit.nextStepId === oldId)
823 { exit.nextStepId = newId; }
824 if (exit.kind === "triggers")
825 {
826 for (const trig of exit.triggers ?? [])
827 {
828 if (trig.nextStepId === oldId)
829 { trig.nextStepId = newId; }
830 }
831 }
832 if (exit.kind === "branches")
833 {
834 for (const branch of exit.branches ?? [])
835 {
836 if (branch.nextStepId === oldId)
837 { branch.nextStepId = newId; }
838 }
839 }
840 }
841 }
842
843 closeBtn.addEventListener("click", () => show(false));
844 backdrop.addEventListener("click", () => show(false));
845
846 return {
847 open (stepId)
848 {
849 openStepId = stepId;
850 show(true);
851 render();
852 },
853 close: () => show(false),
854 isOpen: () => !!openStepId && !root.hidden,
855 refresh ()
856 {
857 if (openStepId)
858 { render(); }
859 },
860 el: root
861 };
862 }
863
864 function field (label, input)
865 {
866 const wrap = document.createElement("label");
867 wrap.append(document.createTextNode(label), input);
868 return wrap;
869 }
870
871 function textInput (value, onChange)
872 {
873 const input = document.createElement("input");
874 input.type = "text";
875 input.value = value ?? "";
876 input.addEventListener("input", () => onChange(input.value));
877 return input;
878 }
879
880 function removeButton (onClick)
881 {
882 const remove = document.createElement("button");
883 remove.type = "button";
884 remove.className = "content-editor-remove";
885 remove.textContent = "×";
886 remove.title = "Remove";
887 remove.addEventListener("click", onClick);
888 return remove;
889 }
890
891 function sectionHeader (title, onAdd, onRemove)
892 {
893 const head = document.createElement("div");
894 head.className = "content-editor-section-header";
895 const strong = document.createElement("strong");
896 strong.textContent = title;
897 head.append(strong);
898 const actions = document.createElement("div");
899 actions.className = "content-editor-row";
900 if (onAdd)
901 {
902 const add = document.createElement("button");
903 add.type = "button";
904 add.textContent = "+";
905 add.title = "Add";
906 add.addEventListener("click", onAdd);
907 actions.append(add);
908 }
909 if (onRemove)
910 { actions.append(removeButton(onRemove)); }
911 head.append(actions);
912 return head;
913 }
@@ -0,0 +1,913 @@
1/**
2 * Step detail modal for the dialogue canvas editor.
3 */
4import { emptyConditionSet } from "/shared/quests/conditions.js";
5import {
6 dialogueTakeIsUnguaranteed,
7 unguaranteedDialogueTakes
8} from "/shared/quests/dialoguePathTakes.js";
9import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
10import { renderConditionSet } from "./conditionSetEditor.js";
11import { scrubDialogueStepLinks, stepHasEdges } from "./dialogueCanvas.js";
12
13/**
14 * @param {{
15 * getDraft: () => object | null,
16 * getQuestCatalog: () => object[],
17 * getDialogues: () => object[],
18 * conditionCtx: () => object,
19 * onChange: () => void,
20 * host?: HTMLElement | null
21 * }} options
22 */
23export function initDialogueStepModal ({
24 getDraft,
25 getQuestCatalog,
26 getDialogues,
27 conditionCtx,
28 onChange,
29 host = null
30})
31{
32 const root = document.createElement("div");
33 root.className = "dialogue-step-overlay";
34 root.hidden = true;
35
36 const backdrop = document.createElement("div");
37 backdrop.className = "dialogue-step-backdrop";
38
39 const panel = document.createElement("div");
40 panel.className = "dialogue-step-panel";
41
42 const header = document.createElement("header");
43 const title = document.createElement("h3");
44 title.textContent = "Step";
45 const closeBtn = document.createElement("button");
46 closeBtn.type = "button";
47 closeBtn.textContent = "Close";
48 header.append(title, closeBtn);
49
50 const body = document.createElement("div");
51 body.className = "dialogue-step-body";
52
53 root.append(backdrop, panel);
54 panel.append(header, body);
55 (host || document.body).append(root);
56
57 /** @type {string | null} */
58 let openStepId = null;
59 /** @type {null | {
60 * step: object,
61 * field: "itemRewards" | "itemTakes",
62 * resultsEl: HTMLElement,
63 * inputEl: HTMLInputElement
64 * }} */
65 let itemPickContext = null;
66
67 function show (visible)
68 {
69 root.hidden = !visible;
70 if (!visible)
71 {
72 openStepId = null;
73 itemPickContext = null;
74 body.replaceChildren();
75 }
76 }
77
78 function currentStep ()
79 {
80 const draft = getDraft();
81 if (!draft || !openStepId)
82 { return null; }
83 return draft.steps.find((s) => s.stepId === openStepId) ?? null;
84 }
85
86 function closeInlineItemSearch ()
87 {
88 if (itemPickContext?.resultsEl)
89 { itemPickContext.resultsEl.replaceChildren(); }
90 itemPickContext = null;
91 }
92
93 function openInlineItemSearch (step, field, inputEl, resultsEl)
94 {
95 itemPickContext = { step, field, inputEl, resultsEl };
96 inputEl.value = "";
97 renderInlineItemSearch("");
98 inputEl.focus();
99 }
100
101 function renderInlineItemSearch (query)
102 {
103 if (!itemPickContext)
104 { return; }
105 const { step, field, resultsEl } = itemPickContext;
106 resultsEl.replaceChildren();
107 const q = String(query ?? "").trim().toLowerCase();
108 const taken = new Set((step[field] ?? []).map((row) => row.itemId));
109 const matches = listAllItemPickerEntries().filter((item) =>
110 {
111 if (taken.has(item.itemId))
112 { return false; }
113 if (!q)
114 { return true; }
115 return item.displayName.toLowerCase().includes(q)
116 || item.key.toLowerCase().includes(q)
117 || String(item.itemId).includes(q);
118 }).slice(0, 40);
119 if (!matches.length)
120 {
121 resultsEl.textContent = "No matching items.";
122 return;
123 }
124 for (const item of matches)
125 {
126 const row = document.createElement("button");
127 row.type = "button";
128 row.className = "shop-item-search-row";
129 const name = document.createElement("span");
130 name.className = "shop-item-search-row-name";
131 name.textContent = item.displayName;
132 const key = document.createElement("span");
133 key.className = "shop-item-search-row-key";
134 key.textContent = `${item.key} · #${item.itemId}`;
135 row.append(name, key);
136 row.addEventListener("click", () =>
137 {
138 if (!Array.isArray(step[field]))
139 { step[field] = []; }
140 step[field].push({ itemId: item.itemId, quantity: 1 });
141 closeInlineItemSearch();
142 onChange();
143 render();
144 });
145 resultsEl.append(row);
146 }
147 }
148
149 function refreshTakeHighlights ()
150 {
151 const draft = getDraft();
152 if (!draft)
153 { return; }
154 const warnings = unguaranteedDialogueTakes(draft);
155 for (const row of body.querySelectorAll("[data-take-step-id][data-take-item-id]"))
156 {
157 const stepId = row.getAttribute("data-take-step-id");
158 const itemId = Number(row.getAttribute("data-take-item-id"));
159 const bad = dialogueTakeIsUnguaranteed(warnings, stepId, itemId);
160 row.classList.toggle("dialogue-item-take-unguaranteed", bad);
161 row.title = bad
162 ? "Not guaranteed by every branch/trigger path to this step."
163 : "";
164 }
165 }
166
167 function openSubModal (titleText, build)
168 {
169 const sub = document.createElement("div");
170 sub.className = "dialogue-step-submodal";
171 const subPanel = document.createElement("div");
172 subPanel.className = "dialogue-step-subpanel";
173 const subHead = document.createElement("header");
174 const h = document.createElement("h4");
175 h.textContent = titleText;
176 const done = document.createElement("button");
177 done.type = "button";
178 done.textContent = "Done";
179 subHead.append(h, done);
180 const subBody = document.createElement("div");
181 subBody.className = "dialogue-step-subbody";
182 subPanel.append(subHead, subBody);
183 sub.append(subPanel);
184 panel.append(sub);
185 const close = () => sub.remove();
186 done.addEventListener("click", close);
187 sub.addEventListener("click", (event) =>
188 {
189 if (event.target === sub)
190 { close(); }
191 });
192 build(subBody, close);
193 return close;
194 }
195
196 function openRewardsUi (step)
197 {
198 openSubModal("Rewards & takes", (subBody) =>
199 {
200 if (!Array.isArray(step.itemRewards))
201 { step.itemRewards = []; }
202 if (!Array.isArray(step.itemTakes))
203 { step.itemTakes = []; }
204
205 const rewardsHead = sectionHeader("Item rewards", () =>
206 {
207 searchWrap.hidden = false;
208 openInlineItemSearch(step, "itemRewards", searchInput, searchResults);
209 });
210 subBody.append(rewardsHead);
211 const rewardsHint = document.createElement("p");
212 rewardsHint.className = "content-editor-hint";
213 rewardsHint.textContent = "Granted after all lines, before triggers/branches.";
214 subBody.append(rewardsHint);
215
216 const searchWrap = document.createElement("div");
217 searchWrap.className = "dialogue-reward-item-search";
218 searchWrap.hidden = true;
219 const searchInput = document.createElement("input");
220 searchInput.type = "search";
221 searchInput.placeholder = "Search items…";
222 searchInput.autocomplete = "off";
223 searchInput.addEventListener("input", () => renderInlineItemSearch(searchInput.value));
224 const searchResults = document.createElement("div");
225 searchResults.className = "dialogue-reward-item-results";
226 searchWrap.append(searchInput, searchResults);
227
228 const rewardsList = document.createElement("div");
229 function renderRewards ()
230 {
231 rewardsList.replaceChildren();
232 if (!step.itemRewards.length)
233 {
234 const empty = document.createElement("p");
235 empty.className = "content-editor-hint";
236 empty.textContent = "No item rewards.";
237 rewardsList.append(empty);
238 }
239 step.itemRewards.forEach((reward, rewardIndex) =>
240 {
241 const def = itemDefinition(reward.itemId);
242 const row = document.createElement("div");
243 row.className = "spawner-drops-row";
244 const name = document.createElement("span");
245 name.className = "spawner-sells-name";
246 name.textContent = def?.displayName ?? `Item ${reward.itemId}`;
247 const qty = document.createElement("input");
248 qty.type = "number";
249 qty.min = "1";
250 qty.step = "1";
251 qty.value = String(Math.max(1, reward.quantity | 0 || 1));
252 qty.title = "Quantity";
253 qty.addEventListener("input", () =>
254 {
255 step.itemRewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
256 onChange();
257 });
258 row.append(name, qty, removeButton(() =>
259 {
260 step.itemRewards.splice(rewardIndex, 1);
261 onChange();
262 renderRewards();
263 render();
264 }));
265 rewardsList.append(row);
266 });
267 }
268 renderRewards();
269 subBody.append(rewardsList, searchWrap);
270
271 const takesHead = sectionHeader("Item takes", () =>
272 {
273 takeSearchWrap.hidden = false;
274 openInlineItemSearch(step, "itemTakes", takeSearchInput, takeSearchResults);
275 });
276 subBody.append(takesHead);
277 const takesHint = document.createElement("p");
278 takesHint.className = "content-editor-hint";
279 takesHint.textContent = "Removed from the bag after all lines (soft). Yellow = not guaranteed on every path.";
280 subBody.append(takesHint);
281
282 const takeSearchWrap = document.createElement("div");
283 takeSearchWrap.className = "dialogue-reward-item-search";
284 takeSearchWrap.hidden = true;
285 const takeSearchInput = document.createElement("input");
286 takeSearchInput.type = "search";
287 takeSearchInput.placeholder = "Search items…";
288 takeSearchInput.autocomplete = "off";
289 takeSearchInput.addEventListener("input", () => renderInlineItemSearch(takeSearchInput.value));
290 const takeSearchResults = document.createElement("div");
291 takeSearchResults.className = "dialogue-reward-item-results";
292 takeSearchWrap.append(takeSearchInput, takeSearchResults);
293
294 const takesList = document.createElement("div");
295 const draft = getDraft();
296 const takeWarnings = draft ? unguaranteedDialogueTakes(draft) : new Map();
297 function renderTakes ()
298 {
299 takesList.replaceChildren();
300 if (!step.itemTakes.length)
301 {
302 const empty = document.createElement("p");
303 empty.className = "content-editor-hint";
304 empty.textContent = "No item takes.";
305 takesList.append(empty);
306 }
307 step.itemTakes.forEach((take, takeIndex) =>
308 {
309 const def = itemDefinition(take.itemId);
310 const row = document.createElement("div");
311 row.className = "spawner-drops-row";
312 row.setAttribute("data-take-step-id", step.stepId);
313 row.setAttribute("data-take-item-id", String(take.itemId));
314 if (dialogueTakeIsUnguaranteed(takeWarnings, step.stepId, take.itemId))
315 {
316 row.classList.add("dialogue-item-take-unguaranteed");
317 row.title = "Not guaranteed by every branch/trigger path to this step.";
318 }
319 const name = document.createElement("span");
320 name.className = "spawner-sells-name";
321 name.textContent = def?.displayName ?? `Item ${take.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, take.quantity | 0 || 1));
327 qty.title = "Quantity";
328 qty.addEventListener("input", () =>
329 {
330 step.itemTakes[takeIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
331 onChange();
332 refreshTakeHighlights();
333 });
334 row.append(name, qty, removeButton(() =>
335 {
336 step.itemTakes.splice(takeIndex, 1);
337 onChange();
338 renderTakes();
339 render();
340 }));
341 takesList.append(row);
342 });
343 }
344 renderTakes();
345 subBody.append(takesList, takeSearchWrap);
346 });
347 }
348
349 function openQuestsUi (step)
350 {
351 openSubModal("Quest rewards", (subBody) =>
352 {
353 if (!Array.isArray(step.questRewards))
354 { step.questRewards = []; }
355 const questCatalog = getQuestCatalog();
356 const head = sectionHeader("Quest rewards", () =>
357 {
358 const available = questCatalog.find((q) => !step.questRewards.includes(q.questId));
359 if (!available)
360 { return; }
361 step.questRewards.push(available.questId);
362 onChange();
363 renderQuests();
364 render();
365 });
366 subBody.append(head);
367 const hint = document.createElement("p");
368 hint.className = "content-editor-hint";
369 hint.textContent = "Started after all lines (with item rewards), before triggers/branches.";
370 subBody.append(hint);
371 const list = document.createElement("div");
372 function renderQuests ()
373 {
374 list.replaceChildren();
375 if (!step.questRewards.length)
376 {
377 const empty = document.createElement("p");
378 empty.className = "content-editor-hint";
379 empty.textContent = "No quest rewards.";
380 list.append(empty);
381 }
382 step.questRewards.forEach((questId, rewardIndex) =>
383 {
384 const row = document.createElement("div");
385 row.className = "spawner-drops-row";
386 const select = document.createElement("select");
387 const taken = new Set(step.questRewards);
388 const catalog = questCatalog.length
389 ? questCatalog
390 : [{ questId, title: questId }];
391 for (const quest of catalog)
392 {
393 if (taken.has(quest.questId) && quest.questId !== questId)
394 { continue; }
395 const opt = document.createElement("option");
396 opt.value = quest.questId;
397 opt.textContent = quest.title
398 ? `${quest.title} (${quest.questId})`
399 : quest.questId;
400 select.append(opt);
401 }
402 if (![...select.options].some((o) => o.value === questId))
403 {
404 const missing = document.createElement("option");
405 missing.value = questId;
406 missing.textContent = `${questId} (missing)`;
407 select.append(missing);
408 }
409 select.value = questId;
410 select.addEventListener("change", () =>
411 {
412 step.questRewards[rewardIndex] = select.value;
413 onChange();
414 render();
415 });
416 row.append(select, removeButton(() =>
417 {
418 step.questRewards.splice(rewardIndex, 1);
419 onChange();
420 renderQuests();
421 render();
422 }));
423 list.append(row);
424 });
425 }
426 renderQuests();
427 subBody.append(list);
428 });
429 }
430
431 function openExitConfigure (step)
432 {
433 const kind = step.exit?.kind;
434 if (kind !== "branches" && kind !== "triggers")
435 { return; }
436 openSubModal(kind === "triggers" ? "Configure triggers" : "Configure branches", (subBody) =>
437 {
438 const hint = document.createElement("p");
439 hint.className = "content-editor-hint";
440 hint.textContent = kind === "triggers"
441 ? "Wire next steps on the canvas. Here you edit button text and conditions."
442 : "Wire next steps on the canvas. Here you edit labels and conditions.";
443 subBody.append(hint);
444
445 if (kind === "triggers")
446 {
447 if (!Array.isArray(step.exit.triggers))
448 { step.exit.triggers = []; }
449 const head = sectionHeader("Triggers", () =>
450 {
451 step.exit.triggers.push({
452 trigger: `choice-${step.exit.triggers.length + 1}`,
453 text: "Choice",
454 nextStepId: null,
455 when: emptyConditionSet(),
456 effects: []
457 });
458 onChange();
459 renderTriggers();
460 render();
461 });
462 subBody.append(head);
463 const list = document.createElement("div");
464 function renderTriggers ()
465 {
466 list.replaceChildren();
467 step.exit.triggers.forEach((trig, trigIndex) =>
468 {
469 const tBox = document.createElement("div");
470 tBox.className = "content-editor-section";
471 tBox.append(sectionHeader(`Trigger ${trigIndex + 1}`, null, () =>
472 {
473 step.exit.triggers.splice(trigIndex, 1);
474 onChange();
475 renderTriggers();
476 render();
477 }));
478 tBox.append(
479 field("trigger", textInput(trig.trigger, (v) =>
480 {
481 trig.trigger = v;
482 onChange();
483 })),
484 field("Button", textInput(trig.text ?? "", (v) =>
485 {
486 trig.text = v;
487 onChange();
488 render();
489 }))
490 );
491 tBox.append(renderConditionSet(trig.when, (next, { remount = true } = {}) =>
492 {
493 trig.when = next;
494 onChange();
495 if (remount)
496 { renderTriggers(); }
497 }, conditionCtx()));
498 list.append(tBox);
499 });
500 }
501 renderTriggers();
502 subBody.append(list);
503 return;
504 }
505
506 if (!Array.isArray(step.exit.branches))
507 { step.exit.branches = []; }
508 const head = sectionHeader("Branches", () =>
509 {
510 step.exit.branches.push({
511 label: "",
512 when: emptyConditionSet(),
513 nextStepId: null,
514 effects: []
515 });
516 onChange();
517 renderBranches();
518 render();
519 });
520 subBody.append(head);
521 const list = document.createElement("div");
522 function renderBranches ()
523 {
524 list.replaceChildren();
525 step.exit.branches.forEach((branch, branchIndex) =>
526 {
527 const bBox = document.createElement("div");
528 bBox.className = "content-editor-section";
529 bBox.append(sectionHeader(`Branch ${branchIndex + 1}`, null, () =>
530 {
531 step.exit.branches.splice(branchIndex, 1);
532 onChange();
533 renderBranches();
534 render();
535 }));
536 bBox.append(field("label", textInput(branch.label ?? "", (v) =>
537 {
538 branch.label = v;
539 onChange();
540 })));
541 bBox.append(renderConditionSet(branch.when, (next, { remount = true } = {}) =>
542 {
543 branch.when = next;
544 onChange();
545 if (remount)
546 { renderBranches(); }
547 }, conditionCtx()));
548 list.append(bBox);
549 });
550 }
551 renderBranches();
552 subBody.append(list);
553 });
554 }
555
556 function confirmDeleteStep (step)
557 {
558 const draft = getDraft();
559 if (!draft)
560 { return; }
561 const linked = stepHasEdges(draft, step);
562 if (!linked)
563 {
564 if (!window.confirm(`Delete dialogue step "${step.label || step.stepId}"?`))
565 { return; }
566 deleteStep(step);
567 return;
568 }
569 openSubModal("Delete step?", (subBody, close) =>
570 {
571 subBody.classList.add("dialogue-step-delete-warn");
572 const warn = document.createElement("p");
573 warn.className = "dialogue-step-delete-warn-text";
574 warn.textContent = `“${step.label || step.stepId}” has incoming or outgoing connections. Deleting it will remove those links.`;
575 const actions = document.createElement("div");
576 actions.className = "dialogue-step-delete-actions";
577 const cancel = document.createElement("button");
578 cancel.type = "button";
579 cancel.textContent = "Cancel";
580 cancel.addEventListener("click", close);
581 const confirm = document.createElement("button");
582 confirm.type = "button";
583 confirm.className = "dialogue-step-delete-confirm";
584 confirm.textContent = "Delete step";
585 confirm.addEventListener("click", () =>
586 {
587 close();
588 deleteStep(step);
589 });
590 actions.append(cancel, confirm);
591 subBody.append(warn, actions);
592 });
593 }
594
595 function deleteStep (step)
596 {
597 const draft = getDraft();
598 if (!draft)
599 { return; }
600 const index = draft.steps.indexOf(step);
601 if (index < 0)
602 { return; }
603 const removedId = step.stepId;
604 draft.steps.splice(index, 1);
605 scrubDialogueStepLinks(draft, removedId);
606 if (draft.entryStepId === removedId)
607 { draft.entryStepId = draft.steps[0]?.stepId ?? ""; }
608 if (draft.steps.length === 0)
609 {
610 draft.steps.push({
611 stepId: "greeting",
612 label: "Greeting",
613 lines: [{ speaker: "npc", text: "…", effects: [] }],
614 itemRewards: [],
615 itemTakes: [],
616 questRewards: [],
617 exit: { kind: "end" },
618 editorX: 80,
619 editorY: 80
620 });
621 draft.entryStepId = "greeting";
622 }
623 show(false);
624 onChange();
625 }
626
627 function setExitKind (step, kind)
628 {
629 if (kind === "triggers")
630 {
631 step.exit = {
632 kind: "triggers",
633 triggers: step.exit?.triggers?.length
634 ? step.exit.triggers
635 : [{
636 trigger: "continue",
637 text: "Continue",
638 nextStepId: null,
639 when: emptyConditionSet(),
640 effects: []
641 }]
642 };
643 }
644 else if (kind === "branches")
645 {
646 step.exit = {
647 kind: "branches",
648 branches: step.exit?.branches?.length
649 ? step.exit.branches
650 : [{
651 label: "",
652 when: emptyConditionSet(),
653 nextStepId: null,
654 effects: []
655 }]
656 };
657 }
658 else if (kind === "continue")
659 {
660 const prevNext = step.exit?.kind === "continue"
661 ? step.exit.nextStepId
662 : null;
663 step.exit = { kind: "continue", nextStepId: prevNext ?? null };
664 }
665 else
666 { step.exit = { kind: "end" }; }
667 }
668
669 function render ()
670 {
671 const step = currentStep();
672 body.replaceChildren();
673 if (!step)
674 {
675 show(false);
676 return;
677 }
678 title.textContent = step.label || step.stepId || "Step";
679
680 body.append(
681 field("stepId", textInput(step.stepId, (v) =>
682 {
683 const draft = getDraft();
684 const oldId = step.stepId;
685 step.stepId = v;
686 if (draft?.entryStepId === oldId)
687 { draft.entryStepId = v; }
688 scrubRename(draft, oldId, v);
689 openStepId = v;
690 onChange();
691 })),
692 field("Label", textInput(step.label ?? "", (v) =>
693 {
694 step.label = v;
695 title.textContent = v || step.stepId || "Step";
696 onChange();
697 }))
698 );
699
700 const linesHead = sectionHeader("Lines", () =>
701 {
702 step.lines.push({ speaker: "npc", text: "…", effects: [] });
703 onChange();
704 render();
705 });
706 body.append(linesHead);
707 step.lines.forEach((line, lineIndex) =>
708 {
709 const row = document.createElement("div");
710 row.className = "content-editor-row";
711 const speaker = document.createElement("select");
712 for (const s of ["npc", "player"])
713 {
714 const opt = document.createElement("option");
715 opt.value = s;
716 opt.textContent = s;
717 if (line.speaker === s)
718 { opt.selected = true; }
719 speaker.append(opt);
720 }
721 speaker.addEventListener("change", () =>
722 {
723 line.speaker = speaker.value;
724 onChange();
725 });
726 const text = document.createElement("input");
727 text.type = "text";
728 text.value = line.text ?? "";
729 text.style.flex = "1";
730 text.addEventListener("input", () =>
731 {
732 line.text = text.value;
733 onChange();
734 });
735 row.append(speaker, text, removeButton(() =>
736 {
737 if (!window.confirm("Delete this dialogue line?"))
738 { return; }
739 step.lines.splice(lineIndex, 1);
740 if (step.lines.length === 0)
741 { step.lines.push({ speaker: "npc", text: "…", effects: [] }); }
742 onChange();
743 render();
744 }));
745 body.append(row);
746 });
747
748 const actions = document.createElement("div");
749 actions.className = "dialogue-step-actions";
750
751 const rewardCount = (step.itemRewards?.length ?? 0) + (step.itemTakes?.length ?? 0);
752 const rewardsBtn = document.createElement("button");
753 rewardsBtn.type = "button";
754 rewardsBtn.textContent = rewardCount > 0 ? `Rewards (${rewardCount})` : "Rewards";
755 rewardsBtn.addEventListener("click", () => openRewardsUi(step));
756
757 const questsBtn = document.createElement("button");
758 questsBtn.type = "button";
759 questsBtn.textContent = (step.questRewards?.length ?? 0) > 0
760 ? `Quests (${step.questRewards.length})`
761 : "Quests";
762 questsBtn.addEventListener("click", () => openQuestsUi(step));
763
764 const deleteBtn = document.createElement("button");
765 deleteBtn.type = "button";
766 deleteBtn.className = "content-editor-remove";
767 deleteBtn.textContent = "Delete Step";
768 deleteBtn.addEventListener("click", () => confirmDeleteStep(step));
769
770 actions.append(rewardsBtn, questsBtn, deleteBtn);
771 body.append(actions);
772
773 const exitKind = document.createElement("select");
774 for (const k of [
775 { value: "end", label: "End" },
776 { value: "branches", label: "Branches" },
777 { value: "triggers", label: "Triggers" },
778 { value: "continue", label: "Continue" }
779 ])
780 {
781 const opt = document.createElement("option");
782 opt.value = k.value;
783 opt.textContent = k.label;
784 if ((step.exit?.kind ?? "end") === k.value)
785 { opt.selected = true; }
786 exitKind.append(opt);
787 }
788 exitKind.addEventListener("change", () =>
789 {
790 setExitKind(step, exitKind.value);
791 onChange();
792 render();
793 });
794 body.append(field("Exit", exitKind));
795
796 const configure = document.createElement("button");
797 configure.type = "button";
798 configure.textContent = "Configure";
799 const canConfigure = step.exit?.kind === "branches" || step.exit?.kind === "triggers";
800 configure.disabled = !canConfigure;
801 configure.addEventListener("click", () => openExitConfigure(step));
802 body.append(configure);
803
804 if (step.exit?.kind === "continue")
805 {
806 const note = document.createElement("p");
807 note.className = "content-editor-hint";
808 note.textContent = "Continue uses a single outgoing port on the canvas.";
809 body.append(note);
810 }
811 }
812
813 function scrubRename (draft, oldId, newId)
814 {
815 if (!draft || !oldId || oldId === newId)
816 { return; }
817 for (const other of draft.steps)
818 {
819 const exit = other.exit;
820 if (!exit)
821 { continue; }
822 if (exit.kind === "continue" && exit.nextStepId === oldId)
823 { exit.nextStepId = newId; }
824 if (exit.kind === "triggers")
825 {
826 for (const trig of exit.triggers ?? [])
827 {
828 if (trig.nextStepId === oldId)
829 { trig.nextStepId = newId; }
830 }
831 }
832 if (exit.kind === "branches")
833 {
834 for (const branch of exit.branches ?? [])
835 {
836 if (branch.nextStepId === oldId)
837 { branch.nextStepId = newId; }
838 }
839 }
840 }
841 }
842
843 closeBtn.addEventListener("click", () => show(false));
844 backdrop.addEventListener("click", () => show(false));
845
846 return {
847 open (stepId)
848 {
849 openStepId = stepId;
850 show(true);
851 render();
852 },
853 close: () => show(false),
854 isOpen: () => !!openStepId && !root.hidden,
855 refresh ()
856 {
857 if (openStepId)
858 { render(); }
859 },
860 el: root
861 };
862}
863
864function field (label, input)
865{
866 const wrap = document.createElement("label");
867 wrap.append(document.createTextNode(label), input);
868 return wrap;
869}
870
871function textInput (value, onChange)
872{
873 const input = document.createElement("input");
874 input.type = "text";
875 input.value = value ?? "";
876 input.addEventListener("input", () => onChange(input.value));
877 return input;
878}
879
880function removeButton (onClick)
881{
882 const remove = document.createElement("button");
883 remove.type = "button";
884 remove.className = "content-editor-remove";
885 remove.textContent = "×";
886 remove.title = "Remove";
887 remove.addEventListener("click", onClick);
888 return remove;
889}
890
891function sectionHeader (title, onAdd, onRemove)
892{
893 const head = document.createElement("div");
894 head.className = "content-editor-section-header";
895 const strong = document.createElement("strong");
896 strong.textContent = title;
897 head.append(strong);
898 const actions = document.createElement("div");
899 actions.className = "content-editor-row";
900 if (onAdd)
901 {
902 const add = document.createElement("button");
903 add.type = "button";
904 add.textContent = "+";
905 add.title = "Add";
906 add.addEventListener("click", onAdd);
907 actions.append(add);
908 }
909 if (onRemove)
910 { actions.append(removeButton(onRemove)); }
911 head.append(actions);
912 return head;
913}
client/src/editor/dialoguesModal.js +293 −582
@@ -1,16 +1,14 @@
1 1 import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";
2 import { emptyConditionSet } from "/shared/quests/conditions.js";
3 import {
4 dialogueTakeIsUnguaranteed,
5 unguaranteedDialogueTakes
6 } from "/shared/quests/dialoguePathTakes.js";
7 2 import {
8 3 applyDialogueTextReplacements,
9 4 dialogueReplacementCatalog
10 5 } from "/shared/speech/dialogueText.js";
11 import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
12 import { renderConditionSet } from "./conditionSetEditor.js";
13 6 import { initDialogueSimulate } from "./dialogueSimulate.js";
7 import {
8 blankDialogueStep,
9 createDialogueCanvas
10 } from "./dialogueCanvas.js";
11 import { initDialogueStepModal } from "./dialogueStepModal.js";
14 12
15 13 export function initDialoguesModal ({
16 14 socket,
@@ -45,6 +43,16 @@ export function initDialoguesModal ({
45 43 let selectedId = null;
46 44 /** @type {object[]} */
47 45 let changelog = [];
46 /** JSON snapshot of last loaded/saved dialogue (normalized). null = never saved (new). */
47 let draftBaseline = null;
48 /** @type {null | { type: "close" } | { type: "select", dialogueId: string } | { type: "new" }} */
49 let pendingLeave = null;
50 /** After a successful save, run pendingLeave. */
51 let leaveAfterSave = false;
52 let unsavedPromptOpen = false;
53
54 const unsavedBackdrop = document.getElementById("unsaved-dialogue-backdrop");
55 const unsavedModal = document.getElementById("unsaved-dialogue-modal");
48 56
49 57 const simulate = initDialogueSimulate({
50 58 getTree: () => (draft ? normalizeDialogueTree(draft) : null),
@@ -55,19 +63,215 @@ export function initDialoguesModal ({
55 63 }
56 64 });
57 65
58 function show (visible)
66 function conditionCtx ()
59 67 {
60 open = visible;
61 backdrop.hidden = !visible;
62 modal.hidden = !visible;
63 if (!visible)
68 return {
69 quests: questCatalog,
70 dialogues,
71 describeWorldTile,
72 centerEditorOnTile,
73 getDimensionOptions
74 };
75 }
76
77 const stepModal = initDialogueStepModal({
78 getDraft: () => draft,
79 getQuestCatalog: () => questCatalog,
80 getDialogues: () => dialogues,
81 conditionCtx,
82 onChange ()
83 {
84 noteChange();
85 canvas?.refresh();
86 },
87 host: modal
88 });
89
90 const canvas = createDialogueCanvas({
91 getDraft: () => draft,
92 onOpenStep (stepId)
93 {
94 stepModal.open(stepId);
95 },
96 onCreateStep (worldX, worldY)
97 {
98 if (!draft)
99 { return; }
100 const stepId = uniqueStepId(draft);
101 draft.steps.push(blankDialogueStep(stepId, worldX, worldY));
102 noteChange();
103 canvas.refresh();
104 stepModal.open(stepId);
105 },
106 onChange ()
107 {
108 noteChange();
109 stepModal.refresh();
110 }
111 });
112
113 function uniqueStepId (tree)
114 {
115 const used = new Set((tree.steps ?? []).map((s) => s.stepId));
116 let n = (tree.steps?.length ?? 0) + 1;
117 let id = `step-${n}`;
118 while (used.has(id))
119 {
120 n += 1;
121 id = `step-${n}`;
122 }
123 return id;
124 }
125
126 function persistableSnapshot (tree)
127 {
128 if (!tree)
129 { return null; }
130 return JSON.stringify(normalizeDialogueTree(tree));
131 }
132
133 function captureBaseline ()
134 {
135 draftBaseline = draft ? persistableSnapshot(draft) : null;
136 syncSaveButton();
137 }
138
139 function isDraftDirty ()
140 {
141 if (!draft)
142 { return false; }
143 if (draftBaseline == null)
144 { return true; }
145 return persistableSnapshot(draft) !== draftBaseline;
146 }
147
148 function noteChange ()
149 {
150 syncSaveButton();
151 }
152
153 function syncSaveButton ()
154 {
155 const dirty = isDraftDirty();
156 saveBtn.disabled = !draft || !dirty;
157 saveBtn.classList.toggle("save-dirty", !!draft && dirty);
158 }
159
160 function hideUnsavedPrompt ()
161 {
162 unsavedPromptOpen = false;
163 if (unsavedBackdrop)
164 { unsavedBackdrop.hidden = true; }
165 if (unsavedModal)
166 { unsavedModal.hidden = true; }
167 }
168
169 function showUnsavedPrompt (leave)
170 {
171 pendingLeave = leave;
172 unsavedPromptOpen = true;
173 if (unsavedBackdrop)
174 { unsavedBackdrop.hidden = false; }
175 if (unsavedModal)
176 { unsavedModal.hidden = false; }
177 }
178
179 function requestLeave (leave)
180 {
181 if (!isDraftDirty())
182 {
183 performLeave(leave);
184 return;
185 }
186 showUnsavedPrompt(leave);
187 }
188
189 function performLeave (leave)
190 {
191 hideUnsavedPrompt();
192 pendingLeave = null;
193 leaveAfterSave = false;
194 if (!leave)
195 { return; }
196 if (leave.type === "close")
197 {
198 forceClose();
199 return;
200 }
201 if (leave.type === "select")
202 {
203 loadDialogue(leave.dialogueId);
204 return;
205 }
206 if (leave.type === "new")
207 { createNewDialogue(); }
208 }
209
210 function forceClose ()
211 {
212 open = false;
213 backdrop.hidden = true;
214 modal.hidden = true;
215 draft = null;
216 selectedId = null;
217 draftBaseline = null;
218 stepModal.close();
219 showTokensHelp(false);
220 simulate.close();
221 canvas.clearWiring();
222 syncSaveButton();
223 }
224
225 function loadDialogue (dialogueId)
226 {
227 const found = dialogues.find((d) => d.dialogueId === dialogueId);
228 if (!found)
64 229 {
65 230 draft = null;
66 231 selectedId = null;
67 closeInlineItemSearch();
68 showTokensHelp(false);
69 simulate.close();
232 draftBaseline = null;
233 stepModal.close();
234 render();
235 return;
70 236 }
237 selectedId = found.dialogueId;
238 draft = structuredClone(found);
239 captureBaseline();
240 stepModal.close();
241 canvas.clearWiring();
242 render();
243 }
244
245 function createNewDialogue ()
246 {
247 const base = normalizeDialogueTree({
248 dialogueId: `dialogue-${dialogues.length + 1}`,
249 label: "New dialogue",
250 unique: false
251 });
252 if (base.steps[0])
253 {
254 base.steps[0].editorX = 80;
255 base.steps[0].editorY = 80;
256 }
257 draft = { ...structuredClone(base), assignedSpawnerCount: 0 };
258 selectedId = null;
259 draftBaseline = null;
260 stepModal.close();
261 canvas.clearWiring();
262 render();
263 }
264
265 function show (visible)
266 {
267 if (!visible)
268 {
269 requestLeave({ type: "close" });
270 return;
271 }
272 open = true;
273 backdrop.hidden = false;
274 modal.hidden = false;
71 275 }
72 276
73 277 function showTokensHelp (visible)
@@ -124,89 +328,11 @@ export function initDialoguesModal ({
124 328 { tokensPreviewFemale.textContent = female; }
125 329 }
126 330
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 331 function selectDialogue (dialogueId)
198 332 {
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();
333 if (dialogueId === selectedId && draft)
334 { return; }
335 requestLeave({ type: "select", dialogueId });
210 336 }
211 337
212 338 function renderList ()
@@ -228,41 +354,11 @@ export function initDialoguesModal ({
228 354 }
229 355 }
230 356
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 357 function renderEditor ()
263 358 {
264 359 editorEl.replaceChildren();
265 saveBtn.disabled = !draft;
360 editorEl.classList.add("dialogues-editor-canvas-host");
361 syncSaveButton();
266 362 deleteBtn.disabled = !draft;
267 363 if (simulateBtn)
268 364 { simulateBtn.disabled = !draft; }
@@ -275,431 +371,53 @@ export function initDialoguesModal ({
275 371 return;
276 372 }
277 373
278 editorEl.append(
279 field("Dialogue id", textInput(draft.dialogueId, (v) => { draft.dialogueId = v; })),
280 field("Label", textInput(draft.label, (v) => { draft.label = v; }))
374 const meta = document.createElement("div");
375 meta.className = "dialogue-editor-meta";
376 meta.append(
377 field("Dialogue id", textInput(draft.dialogueId, (v) =>
378 {
379 draft.dialogueId = v;
380 noteChange();
381 })),
382 field("Label", textInput(draft.label, (v) =>
383 {
384 draft.label = v;
385 noteChange();
386 }))
281 387 );
282 388
283 389 const uniqueLabel = document.createElement("label");
390 uniqueLabel.className = "dialogue-editor-unique";
284 391 const uniqueBox = document.createElement("input");
285 392 uniqueBox.type = "checkbox";
286 393 uniqueBox.checked = !!draft.unique;
287 uniqueBox.addEventListener("change", () => { draft.unique = uniqueBox.checked; });
394 uniqueBox.addEventListener("change", () =>
395 {
396 draft.unique = uniqueBox.checked;
397 noteChange();
398 });
288 399 uniqueLabel.append(uniqueBox, document.createTextNode(" Unique (at most one spawner)"));
289 editorEl.append(uniqueLabel);
400 meta.append(uniqueLabel);
290 401
291 402 const assigned = document.createElement("p");
292 403 assigned.className = "content-editor-hint";
293 404 assigned.textContent = `Assigned spawners: ${draft.assignedSpawnerCount ?? 0}`;
294 editorEl.append(assigned);
405 meta.append(assigned);
295 406
296 editorEl.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) =>
407 meta.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) =>
297 408 {
298 409 draft.entryStepId = v;
410 noteChange();
411 canvas.refresh();
299 412 })));
300 413
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));
414 const canvasHint = document.createElement("p");
415 canvasHint.className = "content-editor-hint dialogue-canvas-help";
416 canvasHint.textContent = "Drag empty space to pan · wheel to zoom · drag cards to move · click a card to edit · right-click empty canvas to create a step · click an output port then an input to wire.";
417 meta.append(canvasHint);
605 418
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 };
419 editorEl.append(meta, canvas.el);
420 canvas.refresh();
703 421 }
704 422
705 423 function render ()
@@ -753,6 +471,31 @@ export function initDialoguesModal ({
753 471 });
754 472 document.getElementById("dialogues-close").addEventListener("click", () => show(false));
755 473 backdrop.addEventListener("click", () => show(false));
474 document.getElementById("unsaved-dialogue-cancel")?.addEventListener("click", () =>
475 {
476 pendingLeave = null;
477 leaveAfterSave = false;
478 hideUnsavedPrompt();
479 });
480 unsavedBackdrop?.addEventListener("click", () =>
481 {
482 pendingLeave = null;
483 leaveAfterSave = false;
484 hideUnsavedPrompt();
485 });
486 document.getElementById("unsaved-dialogue-discard")?.addEventListener("click", () =>
487 {
488 const leave = pendingLeave;
489 performLeave(leave);
490 });
491 document.getElementById("unsaved-dialogue-save")?.addEventListener("click", () =>
492 {
493 if (!draft)
494 { return; }
495 leaveAfterSave = true;
496 hideUnsavedPrompt();
497 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
498 });
756 499 document.getElementById("dialogues-tokens-help")?.addEventListener("click", () =>
757 500 {
758 501 showTokensHelp(true);
@@ -768,18 +511,11 @@ export function initDialoguesModal ({
768 511 });
769 512 document.getElementById("dialogues-new").addEventListener("click", () =>
770 513 {
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();
514 requestLeave({ type: "new" });
779 515 });
780 516 saveBtn.addEventListener("click", () =>
781 517 {
782 if (!draft)
518 if (!draft || !isDraftDirty())
783 519 { return; }
784 520 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
785 521 });
@@ -793,7 +529,7 @@ export function initDialoguesModal ({
793 529 });
794 530
795 531 return {
796 isOpen: () => open || tokensHelpOpen || simulate.isOpen(),
532 isOpen: () => open || tokensHelpOpen || unsavedPromptOpen || simulate.isOpen() || stepModal.isOpen(),
797 533 getDialogues: () => dialogues,
798 534 handleMessage (message)
799 535 {
@@ -822,11 +558,22 @@ export function initDialoguesModal ({
822 558 {
823 559 selectedId = still.dialogueId;
824 560 draft = structuredClone(still);
561 captureBaseline();
562 if (leaveAfterSave)
563 {
564 const leave = pendingLeave;
565 leaveAfterSave = false;
566 performLeave(leave);
567 return;
568 }
825 569 }
826 570 else if (selectedId)
827 571 {
828 572 draft = null;
829 573 selectedId = null;
574 draftBaseline = null;
575 leaveAfterSave = false;
576 pendingLeave = null;
830 577 }
831 578 }
832 579 if (open)
@@ -850,39 +597,3 @@ function textInput (value, onChange)
850 597 input.addEventListener("input", () => onChange(input.value));
851 598 return input;
852 599 }
853
854 function 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
865 function 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
@@ -1,16 +1,14 @@
1import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";
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 {
2import {
8 applyDialogueTextReplacements,
3 applyDialogueTextReplacements,
9 dialogueReplacementCatalog
4 dialogueReplacementCatalog
10} from "/shared/speech/dialogueText.js";
5} from "/shared/speech/dialogueText.js";
11import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
12import { renderConditionSet } from "./conditionSetEditor.js";
13import { initDialogueSimulate } from "./dialogueSimulate.js";
6import { initDialogueSimulate } from "./dialogueSimulate.js";
7import {
8 blankDialogueStep,
9 createDialogueCanvas
10} from "./dialogueCanvas.js";
11import { initDialogueStepModal } from "./dialogueStepModal.js";
14
12
15export function initDialoguesModal ({
13export function initDialoguesModal ({
16 socket,
14 socket,
@@ -45,6 +43,16 @@ export function initDialoguesModal ({
45 let selectedId = null;
43 let selectedId = null;
46 /** @type {object[]} */
44 /** @type {object[]} */
47 let changelog = [];
45 let changelog = [];
46 /** JSON snapshot of last loaded/saved dialogue (normalized). null = never saved (new). */
47 let draftBaseline = null;
48 /** @type {null | { type: "close" } | { type: "select", dialogueId: string } | { type: "new" }} */
49 let pendingLeave = null;
50 /** After a successful save, run pendingLeave. */
51 let leaveAfterSave = false;
52 let unsavedPromptOpen = false;
53
54 const unsavedBackdrop = document.getElementById("unsaved-dialogue-backdrop");
55 const unsavedModal = document.getElementById("unsaved-dialogue-modal");
48
56
49 const simulate = initDialogueSimulate({
57 const simulate = initDialogueSimulate({
50 getTree: () => (draft ? normalizeDialogueTree(draft) : null),
58 getTree: () => (draft ? normalizeDialogueTree(draft) : null),
@@ -55,19 +63,215 @@ export function initDialoguesModal ({
55 }
63 }
56 });
64 });
57
65
58 function show (visible)
66 function conditionCtx ()
59 {
67 {
60 open = visible;
68 return {
61 backdrop.hidden = !visible;
69 quests: questCatalog,
62 modal.hidden = !visible;
70 dialogues,
63 if (!visible)
71 describeWorldTile,
72 centerEditorOnTile,
73 getDimensionOptions
74 };
75 }
76
77 const stepModal = initDialogueStepModal({
78 getDraft: () => draft,
79 getQuestCatalog: () => questCatalog,
80 getDialogues: () => dialogues,
81 conditionCtx,
82 onChange ()
83 {
84 noteChange();
85 canvas?.refresh();
86 },
87 host: modal
88 });
89
90 const canvas = createDialogueCanvas({
91 getDraft: () => draft,
92 onOpenStep (stepId)
93 {
94 stepModal.open(stepId);
95 },
96 onCreateStep (worldX, worldY)
97 {
98 if (!draft)
99 { return; }
100 const stepId = uniqueStepId(draft);
101 draft.steps.push(blankDialogueStep(stepId, worldX, worldY));
102 noteChange();
103 canvas.refresh();
104 stepModal.open(stepId);
105 },
106 onChange ()
107 {
108 noteChange();
109 stepModal.refresh();
110 }
111 });
112
113 function uniqueStepId (tree)
114 {
115 const used = new Set((tree.steps ?? []).map((s) => s.stepId));
116 let n = (tree.steps?.length ?? 0) + 1;
117 let id = `step-${n}`;
118 while (used.has(id))
119 {
120 n += 1;
121 id = `step-${n}`;
122 }
123 return id;
124 }
125
126 function persistableSnapshot (tree)
127 {
128 if (!tree)
129 { return null; }
130 return JSON.stringify(normalizeDialogueTree(tree));
131 }
132
133 function captureBaseline ()
134 {
135 draftBaseline = draft ? persistableSnapshot(draft) : null;
136 syncSaveButton();
137 }
138
139 function isDraftDirty ()
140 {
141 if (!draft)
142 { return false; }
143 if (draftBaseline == null)
144 { return true; }
145 return persistableSnapshot(draft) !== draftBaseline;
146 }
147
148 function noteChange ()
149 {
150 syncSaveButton();
151 }
152
153 function syncSaveButton ()
154 {
155 const dirty = isDraftDirty();
156 saveBtn.disabled = !draft || !dirty;
157 saveBtn.classList.toggle("save-dirty", !!draft && dirty);
158 }
159
160 function hideUnsavedPrompt ()
161 {
162 unsavedPromptOpen = false;
163 if (unsavedBackdrop)
164 { unsavedBackdrop.hidden = true; }
165 if (unsavedModal)
166 { unsavedModal.hidden = true; }
167 }
168
169 function showUnsavedPrompt (leave)
170 {
171 pendingLeave = leave;
172 unsavedPromptOpen = true;
173 if (unsavedBackdrop)
174 { unsavedBackdrop.hidden = false; }
175 if (unsavedModal)
176 { unsavedModal.hidden = false; }
177 }
178
179 function requestLeave (leave)
180 {
181 if (!isDraftDirty())
182 {
183 performLeave(leave);
184 return;
185 }
186 showUnsavedPrompt(leave);
187 }
188
189 function performLeave (leave)
190 {
191 hideUnsavedPrompt();
192 pendingLeave = null;
193 leaveAfterSave = false;
194 if (!leave)
195 { return; }
196 if (leave.type === "close")
197 {
198 forceClose();
199 return;
200 }
201 if (leave.type === "select")
202 {
203 loadDialogue(leave.dialogueId);
204 return;
205 }
206 if (leave.type === "new")
207 { createNewDialogue(); }
208 }
209
210 function forceClose ()
211 {
212 open = false;
213 backdrop.hidden = true;
214 modal.hidden = true;
215 draft = null;
216 selectedId = null;
217 draftBaseline = null;
218 stepModal.close();
219 showTokensHelp(false);
220 simulate.close();
221 canvas.clearWiring();
222 syncSaveButton();
223 }
224
225 function loadDialogue (dialogueId)
226 {
227 const found = dialogues.find((d) => d.dialogueId === dialogueId);
228 if (!found)
64 {
229 {
65 draft = null;
230 draft = null;
66 selectedId = null;
231 selectedId = null;
67 closeInlineItemSearch();
232 draftBaseline = null;
68 showTokensHelp(false);
233 stepModal.close();
69 simulate.close();
234 render();
235 return;
70 }
236 }
237 selectedId = found.dialogueId;
238 draft = structuredClone(found);
239 captureBaseline();
240 stepModal.close();
241 canvas.clearWiring();
242 render();
243 }
244
245 function createNewDialogue ()
246 {
247 const base = normalizeDialogueTree({
248 dialogueId: `dialogue-${dialogues.length + 1}`,
249 label: "New dialogue",
250 unique: false
251 });
252 if (base.steps[0])
253 {
254 base.steps[0].editorX = 80;
255 base.steps[0].editorY = 80;
256 }
257 draft = { ...structuredClone(base), assignedSpawnerCount: 0 };
258 selectedId = null;
259 draftBaseline = null;
260 stepModal.close();
261 canvas.clearWiring();
262 render();
263 }
264
265 function show (visible)
266 {
267 if (!visible)
268 {
269 requestLeave({ type: "close" });
270 return;
271 }
272 open = true;
273 backdrop.hidden = false;
274 modal.hidden = false;
71 }
275 }
72
276
73 function showTokensHelp (visible)
277 function showTokensHelp (visible)
@@ -124,89 +328,11 @@ export function initDialoguesModal ({
124 { tokensPreviewFemale.textContent = female; }
328 { tokensPreviewFemale.textContent = female; }
125 }
329 }
126
330
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)
331 function selectDialogue (dialogueId)
198 {
332 {
199 const found = dialogues.find((d) => d.dialogueId === dialogueId);
333 if (dialogueId === selectedId && draft)
200 if (!found)
334 { return; }
201 {
335 requestLeave({ type: "select", dialogueId });
202 draft = null;
203 selectedId = null;
204 render();
205 return;
206 }
207 selectedId = found.dialogueId;
208 draft = structuredClone(found);
209 render();
210 }
336 }
211
337
212 function renderList ()
338 function renderList ()
@@ -228,41 +354,11 @@ export function initDialoguesModal ({
228 }
354 }
229 }
355 }
230
356
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 ()
357 function renderEditor ()
263 {
358 {
264 editorEl.replaceChildren();
359 editorEl.replaceChildren();
265 saveBtn.disabled = !draft;
360 editorEl.classList.add("dialogues-editor-canvas-host");
361 syncSaveButton();
266 deleteBtn.disabled = !draft;
362 deleteBtn.disabled = !draft;
267 if (simulateBtn)
363 if (simulateBtn)
268 { simulateBtn.disabled = !draft; }
364 { simulateBtn.disabled = !draft; }
@@ -275,431 +371,53 @@ export function initDialoguesModal ({
275 return;
371 return;
276 }
372 }
277
373
278 editorEl.append(
374 const meta = document.createElement("div");
279 field("Dialogue id", textInput(draft.dialogueId, (v) => { draft.dialogueId = v; })),
375 meta.className = "dialogue-editor-meta";
280 field("Label", textInput(draft.label, (v) => { draft.label = v; }))
376 meta.append(
377 field("Dialogue id", textInput(draft.dialogueId, (v) =>
378 {
379 draft.dialogueId = v;
380 noteChange();
381 })),
382 field("Label", textInput(draft.label, (v) =>
383 {
384 draft.label = v;
385 noteChange();
386 }))
281 );
387 );
282
388
283 const uniqueLabel = document.createElement("label");
389 const uniqueLabel = document.createElement("label");
390 uniqueLabel.className = "dialogue-editor-unique";
284 const uniqueBox = document.createElement("input");
391 const uniqueBox = document.createElement("input");
285 uniqueBox.type = "checkbox";
392 uniqueBox.type = "checkbox";
286 uniqueBox.checked = !!draft.unique;
393 uniqueBox.checked = !!draft.unique;
287 uniqueBox.addEventListener("change", () => { draft.unique = uniqueBox.checked; });
394 uniqueBox.addEventListener("change", () =>
395 {
396 draft.unique = uniqueBox.checked;
397 noteChange();
398 });
288 uniqueLabel.append(uniqueBox, document.createTextNode(" Unique (at most one spawner)"));
399 uniqueLabel.append(uniqueBox, document.createTextNode(" Unique (at most one spawner)"));
289 editorEl.append(uniqueLabel);
400 meta.append(uniqueLabel);
290
401
291 const assigned = document.createElement("p");
402 const assigned = document.createElement("p");
292 assigned.className = "content-editor-hint";
403 assigned.className = "content-editor-hint";
293 assigned.textContent = `Assigned spawners: ${draft.assignedSpawnerCount ?? 0}`;
404 assigned.textContent = `Assigned spawners: ${draft.assignedSpawnerCount ?? 0}`;
294 editorEl.append(assigned);
405 meta.append(assigned);
295
406
296 editorEl.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) =>
407 meta.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) =>
297 {
408 {
298 draft.entryStepId = v;
409 draft.entryStepId = v;
410 noteChange();
411 canvas.refresh();
299 })));
412 })));
300
413
301 const stepsTitle = document.createElement("div");
414 const canvasHint = document.createElement("p");
302 stepsTitle.className = "content-editor-section-header";
415 canvasHint.className = "content-editor-hint dialogue-canvas-help";
303 const stepsStrong = document.createElement("strong");
416 canvasHint.textContent = "Drag empty space to pan · wheel to zoom · drag cards to move · click a card to edit · right-click empty canvas to create a step · click an output port then an input to wire.";
304 stepsStrong.textContent = "Steps";
417 meta.append(canvasHint);
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
418
606 if (step.exit?.kind === "triggers")
419 editorEl.append(meta, canvas.el);
607 {
420 canvas.refresh();
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 }
421 }
704
422
705 function render ()
423 function render ()
@@ -753,6 +471,31 @@ export function initDialoguesModal ({
753 });
471 });
754 document.getElementById("dialogues-close").addEventListener("click", () => show(false));
472 document.getElementById("dialogues-close").addEventListener("click", () => show(false));
755 backdrop.addEventListener("click", () => show(false));
473 backdrop.addEventListener("click", () => show(false));
474 document.getElementById("unsaved-dialogue-cancel")?.addEventListener("click", () =>
475 {
476 pendingLeave = null;
477 leaveAfterSave = false;
478 hideUnsavedPrompt();
479 });
480 unsavedBackdrop?.addEventListener("click", () =>
481 {
482 pendingLeave = null;
483 leaveAfterSave = false;
484 hideUnsavedPrompt();
485 });
486 document.getElementById("unsaved-dialogue-discard")?.addEventListener("click", () =>
487 {
488 const leave = pendingLeave;
489 performLeave(leave);
490 });
491 document.getElementById("unsaved-dialogue-save")?.addEventListener("click", () =>
492 {
493 if (!draft)
494 { return; }
495 leaveAfterSave = true;
496 hideUnsavedPrompt();
497 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
498 });
756 document.getElementById("dialogues-tokens-help")?.addEventListener("click", () =>
499 document.getElementById("dialogues-tokens-help")?.addEventListener("click", () =>
757 {
500 {
758 showTokensHelp(true);
501 showTokensHelp(true);
@@ -768,18 +511,11 @@ export function initDialoguesModal ({
768 });
511 });
769 document.getElementById("dialogues-new").addEventListener("click", () =>
512 document.getElementById("dialogues-new").addEventListener("click", () =>
770 {
513 {
771 const base = normalizeDialogueTree({
514 requestLeave({ type: "new" });
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 });
515 });
780 saveBtn.addEventListener("click", () =>
516 saveBtn.addEventListener("click", () =>
781 {
517 {
782 if (!draft)
518 if (!draft || !isDraftDirty())
783 { return; }
519 { return; }
784 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
520 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
785 });
521 });
@@ -793,7 +529,7 @@ export function initDialoguesModal ({
793 });
529 });
794
530
795 return {
531 return {
796 isOpen: () => open || tokensHelpOpen || simulate.isOpen(),
532 isOpen: () => open || tokensHelpOpen || unsavedPromptOpen || simulate.isOpen() || stepModal.isOpen(),
797 getDialogues: () => dialogues,
533 getDialogues: () => dialogues,
798 handleMessage (message)
534 handleMessage (message)
799 {
535 {
@@ -822,11 +558,22 @@ export function initDialoguesModal ({
822 {
558 {
823 selectedId = still.dialogueId;
559 selectedId = still.dialogueId;
824 draft = structuredClone(still);
560 draft = structuredClone(still);
561 captureBaseline();
562 if (leaveAfterSave)
563 {
564 const leave = pendingLeave;
565 leaveAfterSave = false;
566 performLeave(leave);
567 return;
568 }
825 }
569 }
826 else if (selectedId)
570 else if (selectedId)
827 {
571 {
828 draft = null;
572 draft = null;
829 selectedId = null;
573 selectedId = null;
574 draftBaseline = null;
575 leaveAfterSave = false;
576 pendingLeave = null;
830 }
577 }
831 }
578 }
832 if (open)
579 if (open)
@@ -850,39 +597,3 @@ function textInput (value, onChange)
850 input.addEventListener("input", () => onChange(input.value));
597 input.addEventListener("input", () => onChange(input.value));
851 return input;
598 return input;
852}
599}
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
client/ui/editor.css +385 −1
@@ -418,7 +418,8 @@ button:disabled {
418 418 cursor: not-allowed;
419 419 }
420 420
421 #save.save-dirty:not(:disabled) {
421 #save.save-dirty:not(:disabled),
422 #dialogues-save.save-dirty:not(:disabled) {
422 423 animation: save-pulse 1.1s ease-in-out infinite;
423 424 border-color: #c9a227;
424 425 box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);
@@ -436,6 +437,7 @@ button:disabled {
436 437 }
437 438 }
438 439
440 #unsaved-dialogue-backdrop,
439 441 #unsaved-chunk-backdrop {
440 442 position: fixed;
441 443 inset: 0;
@@ -443,6 +445,7 @@ button:disabled {
443 445 z-index: 29;
444 446 }
445 447
448 #unsaved-dialogue-modal,
446 449 #unsaved-chunk-modal {
447 450 position: fixed;
448 451 left: 50%;
@@ -456,12 +459,14 @@ button:disabled {
456 459 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
457 460 }
458 461
462 #unsaved-dialogue-modal header,
459 463 #unsaved-chunk-modal header {
460 464 margin: 0 0 0.5rem;
461 465 padding: 0;
462 466 border: 0;
463 467 }
464 468
469 #unsaved-dialogue-modal h2,
465 470 #unsaved-chunk-modal h2 {
466 471 margin: 0;
467 472 font-size: 1.1rem;
@@ -2087,3 +2092,382 @@ label {
2087 2092 white-space: pre-wrap;
2088 2093 word-break: break-word;
2089 2094 }
2095
2096 /* Dialogue canvas graph editor */
2097 #dialogues-editor.dialogues-editor-canvas-host {
2098 display: flex;
2099 flex-direction: column;
2100 overflow: hidden;
2101 padding: 0;
2102 }
2103
2104 .dialogue-editor-meta {
2105 flex-shrink: 0;
2106 padding: 0.65rem 1rem 0.45rem;
2107 border-bottom: 1px solid #2c3340;
2108 background: #141820;
2109 max-height: 42%;
2110 overflow: auto;
2111 }
2112
2113 .dialogue-editor-meta label {
2114 display: inline-block;
2115 margin: 0.25rem 0.75rem 0.25rem 0;
2116 min-width: 11rem;
2117 vertical-align: top;
2118 }
2119
2120 .dialogue-editor-meta input[type="text"] {
2121 display: block;
2122 width: 100%;
2123 margin-top: 0.2rem;
2124 box-sizing: border-box;
2125 }
2126
2127 .dialogue-editor-unique {
2128 display: inline-flex !important;
2129 align-items: center;
2130 gap: 0.4rem;
2131 min-width: auto !important;
2132 margin-top: 0.55rem !important;
2133 }
2134
2135 .dialogue-canvas-help {
2136 margin: 0.35rem 0 0.15rem;
2137 }
2138
2139 .dialogue-canvas-wrap {
2140 position: relative;
2141 flex: 1;
2142 min-height: 220px;
2143 background:
2144 radial-gradient(circle at 1px 1px, #2a3140 1px, transparent 0) 0 0 / 18px 18px,
2145 #0f1218;
2146 overflow: hidden;
2147 }
2148
2149 .dialogue-canvas-viewport {
2150 position: absolute;
2151 inset: 0;
2152 outline: none;
2153 cursor: grab;
2154 touch-action: none;
2155 }
2156
2157 .dialogue-canvas-viewport:active {
2158 cursor: grabbing;
2159 }
2160
2161 .dialogue-canvas-world {
2162 position: absolute;
2163 left: 0;
2164 top: 0;
2165 transform-origin: 0 0;
2166 will-change: transform;
2167 }
2168
2169 .dialogue-canvas-edges {
2170 position: absolute;
2171 left: 0;
2172 top: 0;
2173 overflow: visible;
2174 width: 1px;
2175 height: 1px;
2176 pointer-events: none;
2177 }
2178
2179 .dialogue-canvas-edge {
2180 stroke: #6b8cae;
2181 stroke-width: 2.25;
2182 stroke-dasharray: 8 6;
2183 animation: dialogue-edge-dash 0.9s linear infinite;
2184 }
2185
2186 .dialogue-canvas-edge.is-rewiring {
2187 stroke: #e05050;
2188 stroke-width: 2.75;
2189 animation: none;
2190 stroke-dasharray: none;
2191 }
2192
2193 .dialogue-canvas-rubber {
2194 stroke: #e0a84a;
2195 stroke-width: 2;
2196 stroke-dasharray: 6 5;
2197 opacity: 0;
2198 pointer-events: none;
2199 }
2200
2201 .dialogue-canvas-rubber.active {
2202 opacity: 1;
2203 }
2204
2205 @keyframes dialogue-edge-dash {
2206 to {
2207 stroke-dashoffset: -28;
2208 }
2209 }
2210
2211 .dialogue-canvas-cards {
2212 position: absolute;
2213 left: 0;
2214 top: 0;
2215 }
2216
2217 .dialogue-canvas-card {
2218 position: absolute;
2219 width: 168px;
2220 min-height: 72px;
2221 box-sizing: border-box;
2222 padding: 0.45rem 0.55rem 1.35rem;
2223 background: #1a2130;
2224 border: 1px solid #3a4558;
2225 border-radius: 8px;
2226 box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35);
2227 color: #e8e4d8;
2228 cursor: grab;
2229 user-select: none;
2230 }
2231
2232 .dialogue-canvas-card.is-entry {
2233 border-color: #e0a84a;
2234 box-shadow: 0 0 0 1px rgba(224, 168, 74, 0.35), 0 6px 18px rgba(0, 0, 0, 0.35);
2235 }
2236
2237 .dialogue-canvas-card.dragging {
2238 cursor: grabbing;
2239 opacity: 0.92;
2240 z-index: 5;
2241 }
2242
2243 .dialogue-canvas-card-label {
2244 font-weight: 650;
2245 font-size: 0.92rem;
2246 line-height: 1.25;
2247 word-break: break-word;
2248 }
2249
2250 .dialogue-canvas-card-meta {
2251 margin-top: 0.2rem;
2252 font-size: 0.72rem;
2253 color: #9eb0c8;
2254 text-transform: lowercase;
2255 }
2256
2257 .dialogue-canvas-ports {
2258 position: absolute;
2259 left: 0;
2260 right: 0;
2261 bottom: -8px;
2262 display: flex;
2263 justify-content: space-evenly;
2264 pointer-events: none;
2265 }
2266
2267 .dialogue-canvas-port,
2268 .dialogue-canvas-input {
2269 width: 14px;
2270 height: 14px;
2271 border-radius: 999px;
2272 border: 2px solid #8ab0d4;
2273 background: #12151c;
2274 padding: 0;
2275 pointer-events: auto;
2276 cursor: crosshair;
2277 }
2278
2279 .dialogue-canvas-port.linked {
2280 background: #6b8cae;
2281 }
2282
2283 .dialogue-canvas-port.selected {
2284 border-color: #e0a84a;
2285 background: #e0a84a;
2286 box-shadow: 0 0 0 3px rgba(224, 168, 74, 0.28);
2287 }
2288
2289 .dialogue-canvas-input {
2290 position: absolute;
2291 left: 50%;
2292 top: -8px;
2293 transform: translateX(-50%);
2294 opacity: 0;
2295 pointer-events: none;
2296 border-color: #74c08a;
2297 }
2298
2299 .dialogue-canvas-input.show,
2300 .dialogue-canvas-wiring .dialogue-canvas-input.show {
2301 opacity: 1;
2302 pointer-events: auto;
2303 }
2304
2305 .dialogue-canvas-context {
2306 position: absolute;
2307 z-index: 8;
2308 min-width: 160px;
2309 padding: 0.25rem;
2310 background: #1a1e26;
2311 border: 1px solid #3a4250;
2312 border-radius: 6px;
2313 box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
2314 }
2315
2316 .dialogue-canvas-context button {
2317 display: block;
2318 width: 100%;
2319 text-align: left;
2320 background: transparent;
2321 border: 0;
2322 color: #e8e4d8;
2323 padding: 0.45rem 0.55rem;
2324 cursor: pointer;
2325 border-radius: 4px;
2326 }
2327
2328 .dialogue-canvas-context button:hover {
2329 background: #243044;
2330 }
2331
2332 .dialogue-canvas-tooltip {
2333 position: absolute;
2334 z-index: 9;
2335 max-width: 220px;
2336 padding: 0.3rem 0.45rem;
2337 background: #12151c;
2338 border: 1px solid #3a4250;
2339 border-radius: 4px;
2340 color: #d6d1c4;
2341 font-size: 0.78rem;
2342 pointer-events: none;
2343 box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
2344 }
2345
2346 .dialogue-step-overlay {
2347 position: absolute;
2348 inset: 0;
2349 z-index: 30;
2350 display: flex;
2351 align-items: stretch;
2352 justify-content: flex-end;
2353 }
2354
2355 .dialogue-step-overlay[hidden] {
2356 display: none !important;
2357 }
2358
2359 .dialogue-step-backdrop {
2360 position: absolute;
2361 inset: 0;
2362 background: rgba(0, 0, 0, 0.45);
2363 }
2364
2365 .dialogue-step-panel {
2366 position: relative;
2367 z-index: 1;
2368 width: min(420px, 92%);
2369 max-width: 100%;
2370 height: 100%;
2371 display: flex;
2372 flex-direction: column;
2373 background: #161a22;
2374 border-left: 1px solid #3a4250;
2375 box-shadow: -12px 0 40px rgba(0, 0, 0, 0.4);
2376 }
2377
2378 .dialogue-step-panel > header {
2379 display: flex;
2380 align-items: center;
2381 justify-content: space-between;
2382 gap: 0.75rem;
2383 padding: 0.75rem 1rem;
2384 border-bottom: 1px solid #2c3340;
2385 }
2386
2387 .dialogue-step-panel > header h3 {
2388 margin: 0;
2389 font-size: 1.05rem;
2390 }
2391
2392 .dialogue-step-body {
2393 flex: 1;
2394 min-height: 0;
2395 overflow: auto;
2396 padding: 0.75rem 1rem 1.1rem;
2397 }
2398
2399 .dialogue-step-actions {
2400 display: flex;
2401 flex-wrap: wrap;
2402 gap: 0.45rem;
2403 margin: 0.75rem 0;
2404 }
2405
2406 .dialogue-step-submodal {
2407 position: absolute;
2408 inset: 0;
2409 z-index: 2;
2410 display: flex;
2411 align-items: center;
2412 justify-content: center;
2413 background: rgba(0, 0, 0, 0.5);
2414 padding: 1rem;
2415 }
2416
2417 .dialogue-step-subpanel {
2418 width: min(420px, 100%);
2419 max-height: min(80vh, 640px);
2420 display: flex;
2421 flex-direction: column;
2422 background: #161a22;
2423 border: 1px solid #3a4250;
2424 border-radius: 8px;
2425 box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
2426 }
2427
2428 .dialogue-step-subpanel > header {
2429 display: flex;
2430 align-items: center;
2431 justify-content: space-between;
2432 gap: 0.75rem;
2433 padding: 0.65rem 0.85rem;
2434 border-bottom: 1px solid #2c3340;
2435 }
2436
2437 .dialogue-step-subpanel > header h4 {
2438 margin: 0;
2439 }
2440
2441 .dialogue-step-subbody {
2442 flex: 1;
2443 min-height: 0;
2444 overflow: auto;
2445 padding: 0.75rem 0.85rem 1rem;
2446 }
2447
2448 .dialogue-step-delete-warn-text {
2449 margin: 0 0 1rem;
2450 padding: 0.75rem 0.85rem;
2451 background: rgba(168, 48, 48, 0.22);
2452 border: 1px solid #a84848;
2453 border-radius: 6px;
2454 color: #f0d0d0;
2455 line-height: 1.4;
2456 }
2457
2458 .dialogue-step-delete-actions {
2459 display: flex;
2460 justify-content: flex-end;
2461 gap: 0.5rem;
2462 }
2463
2464 .dialogue-step-delete-confirm {
2465 background: #8a3030;
2466 border-color: #a84848;
2467 color: #f0e8e8;
2468 }
2469
2470 .dialogue-step-delete-confirm:hover {
2471 background: #a83838;
2472 border-color: #c06060;
2473 }
@@ -418,7 +418,8 @@ button:disabled {
418 cursor: not-allowed;
418 cursor: not-allowed;
419}
419}
420
420
421#save.save-dirty:not(:disabled) {
421#save.save-dirty:not(:disabled),
422#dialogues-save.save-dirty:not(:disabled) {
422 animation: save-pulse 1.1s ease-in-out infinite;
423 animation: save-pulse 1.1s ease-in-out infinite;
423 border-color: #c9a227;
424 border-color: #c9a227;
424 box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);
425 box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);
@@ -436,6 +437,7 @@ button:disabled {
436 }
437 }
437}
438}
438
439
440#unsaved-dialogue-backdrop,
439#unsaved-chunk-backdrop {
441#unsaved-chunk-backdrop {
440 position: fixed;
442 position: fixed;
441 inset: 0;
443 inset: 0;
@@ -443,6 +445,7 @@ button:disabled {
443 z-index: 29;
445 z-index: 29;
444}
446}
445
447
448#unsaved-dialogue-modal,
446#unsaved-chunk-modal {
449#unsaved-chunk-modal {
447 position: fixed;
450 position: fixed;
448 left: 50%;
451 left: 50%;
@@ -456,12 +459,14 @@ button:disabled {
456 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
459 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
457}
460}
458
461
462#unsaved-dialogue-modal header,
459#unsaved-chunk-modal header {
463#unsaved-chunk-modal header {
460 margin: 0 0 0.5rem;
464 margin: 0 0 0.5rem;
461 padding: 0;
465 padding: 0;
462 border: 0;
466 border: 0;
463}
467}
464
468
469#unsaved-dialogue-modal h2,
465#unsaved-chunk-modal h2 {
470#unsaved-chunk-modal h2 {
466 margin: 0;
471 margin: 0;
467 font-size: 1.1rem;
472 font-size: 1.1rem;
@@ -2087,3 +2092,382 @@ label {
2087 white-space: pre-wrap;
2092 white-space: pre-wrap;
2088 word-break: break-word;
2093 word-break: break-word;
2089}
2094}
2095
2096/* Dialogue canvas graph editor */
2097#dialogues-editor.dialogues-editor-canvas-host {
2098 display: flex;
2099 flex-direction: column;
2100 overflow: hidden;
2101 padding: 0;
2102}
2103
2104.dialogue-editor-meta {
2105 flex-shrink: 0;
2106 padding: 0.65rem 1rem 0.45rem;
2107 border-bottom: 1px solid #2c3340;
2108 background: #141820;
2109 max-height: 42%;
2110 overflow: auto;
2111}
2112
2113.dialogue-editor-meta label {
2114 display: inline-block;
2115 margin: 0.25rem 0.75rem 0.25rem 0;
2116 min-width: 11rem;
2117 vertical-align: top;
2118}
2119
2120.dialogue-editor-meta input[type="text"] {
2121 display: block;
2122 width: 100%;
2123 margin-top: 0.2rem;
2124 box-sizing: border-box;
2125}
2126
2127.dialogue-editor-unique {
2128 display: inline-flex !important;
2129 align-items: center;
2130 gap: 0.4rem;
2131 min-width: auto !important;
2132 margin-top: 0.55rem !important;
2133}
2134
2135.dialogue-canvas-help {
2136 margin: 0.35rem 0 0.15rem;
2137}
2138
2139.dialogue-canvas-wrap {
2140 position: relative;
2141 flex: 1;
2142 min-height: 220px;
2143 background:
2144 radial-gradient(circle at 1px 1px, #2a3140 1px, transparent 0) 0 0 / 18px 18px,
2145 #0f1218;
2146 overflow: hidden;
2147}
2148
2149.dialogue-canvas-viewport {
2150 position: absolute;
2151 inset: 0;
2152 outline: none;
2153 cursor: grab;
2154 touch-action: none;
2155}
2156
2157.dialogue-canvas-viewport:active {
2158 cursor: grabbing;
2159}
2160
2161.dialogue-canvas-world {
2162 position: absolute;
2163 left: 0;
2164 top: 0;
2165 transform-origin: 0 0;
2166 will-change: transform;
2167}
2168
2169.dialogue-canvas-edges {
2170 position: absolute;
2171 left: 0;
2172 top: 0;
2173 overflow: visible;
2174 width: 1px;
2175 height: 1px;
2176 pointer-events: none;
2177}
2178
2179.dialogue-canvas-edge {
2180 stroke: #6b8cae;
2181 stroke-width: 2.25;
2182 stroke-dasharray: 8 6;
2183 animation: dialogue-edge-dash 0.9s linear infinite;
2184}
2185
2186.dialogue-canvas-edge.is-rewiring {
2187 stroke: #e05050;
2188 stroke-width: 2.75;
2189 animation: none;
2190 stroke-dasharray: none;
2191}
2192
2193.dialogue-canvas-rubber {
2194 stroke: #e0a84a;
2195 stroke-width: 2;
2196 stroke-dasharray: 6 5;
2197 opacity: 0;
2198 pointer-events: none;
2199}
2200
2201.dialogue-canvas-rubber.active {
2202 opacity: 1;
2203}
2204
2205@keyframes dialogue-edge-dash {
2206 to {
2207 stroke-dashoffset: -28;
2208 }
2209}
2210
2211.dialogue-canvas-cards {
2212 position: absolute;
2213 left: 0;
2214 top: 0;
2215}
2216
2217.dialogue-canvas-card {
2218 position: absolute;
2219 width: 168px;
2220 min-height: 72px;
2221 box-sizing: border-box;
2222 padding: 0.45rem 0.55rem 1.35rem;
2223 background: #1a2130;
2224 border: 1px solid #3a4558;
2225 border-radius: 8px;
2226 box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35);
2227 color: #e8e4d8;
2228 cursor: grab;
2229 user-select: none;
2230}
2231
2232.dialogue-canvas-card.is-entry {
2233 border-color: #e0a84a;
2234 box-shadow: 0 0 0 1px rgba(224, 168, 74, 0.35), 0 6px 18px rgba(0, 0, 0, 0.35);
2235}
2236
2237.dialogue-canvas-card.dragging {
2238 cursor: grabbing;
2239 opacity: 0.92;
2240 z-index: 5;
2241}
2242
2243.dialogue-canvas-card-label {
2244 font-weight: 650;
2245 font-size: 0.92rem;
2246 line-height: 1.25;
2247 word-break: break-word;
2248}
2249
2250.dialogue-canvas-card-meta {
2251 margin-top: 0.2rem;
2252 font-size: 0.72rem;
2253 color: #9eb0c8;
2254 text-transform: lowercase;
2255}
2256
2257.dialogue-canvas-ports {
2258 position: absolute;
2259 left: 0;
2260 right: 0;
2261 bottom: -8px;
2262 display: flex;
2263 justify-content: space-evenly;
2264 pointer-events: none;
2265}
2266
2267.dialogue-canvas-port,
2268.dialogue-canvas-input {
2269 width: 14px;
2270 height: 14px;
2271 border-radius: 999px;
2272 border: 2px solid #8ab0d4;
2273 background: #12151c;
2274 padding: 0;
2275 pointer-events: auto;
2276 cursor: crosshair;
2277}
2278
2279.dialogue-canvas-port.linked {
2280 background: #6b8cae;
2281}
2282
2283.dialogue-canvas-port.selected {
2284 border-color: #e0a84a;
2285 background: #e0a84a;
2286 box-shadow: 0 0 0 3px rgba(224, 168, 74, 0.28);
2287}
2288
2289.dialogue-canvas-input {
2290 position: absolute;
2291 left: 50%;
2292 top: -8px;
2293 transform: translateX(-50%);
2294 opacity: 0;
2295 pointer-events: none;
2296 border-color: #74c08a;
2297}
2298
2299.dialogue-canvas-input.show,
2300.dialogue-canvas-wiring .dialogue-canvas-input.show {
2301 opacity: 1;
2302 pointer-events: auto;
2303}
2304
2305.dialogue-canvas-context {
2306 position: absolute;
2307 z-index: 8;
2308 min-width: 160px;
2309 padding: 0.25rem;
2310 background: #1a1e26;
2311 border: 1px solid #3a4250;
2312 border-radius: 6px;
2313 box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
2314}
2315
2316.dialogue-canvas-context button {
2317 display: block;
2318 width: 100%;
2319 text-align: left;
2320 background: transparent;
2321 border: 0;
2322 color: #e8e4d8;
2323 padding: 0.45rem 0.55rem;
2324 cursor: pointer;
2325 border-radius: 4px;
2326}
2327
2328.dialogue-canvas-context button:hover {
2329 background: #243044;
2330}
2331
2332.dialogue-canvas-tooltip {
2333 position: absolute;
2334 z-index: 9;
2335 max-width: 220px;
2336 padding: 0.3rem 0.45rem;
2337 background: #12151c;
2338 border: 1px solid #3a4250;
2339 border-radius: 4px;
2340 color: #d6d1c4;
2341 font-size: 0.78rem;
2342 pointer-events: none;
2343 box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
2344}
2345
2346.dialogue-step-overlay {
2347 position: absolute;
2348 inset: 0;
2349 z-index: 30;
2350 display: flex;
2351 align-items: stretch;
2352 justify-content: flex-end;
2353}
2354
2355.dialogue-step-overlay[hidden] {
2356 display: none !important;
2357}
2358
2359.dialogue-step-backdrop {
2360 position: absolute;
2361 inset: 0;
2362 background: rgba(0, 0, 0, 0.45);
2363}
2364
2365.dialogue-step-panel {
2366 position: relative;
2367 z-index: 1;
2368 width: min(420px, 92%);
2369 max-width: 100%;
2370 height: 100%;
2371 display: flex;
2372 flex-direction: column;
2373 background: #161a22;
2374 border-left: 1px solid #3a4250;
2375 box-shadow: -12px 0 40px rgba(0, 0, 0, 0.4);
2376}
2377
2378.dialogue-step-panel > header {
2379 display: flex;
2380 align-items: center;
2381 justify-content: space-between;
2382 gap: 0.75rem;
2383 padding: 0.75rem 1rem;
2384 border-bottom: 1px solid #2c3340;
2385}
2386
2387.dialogue-step-panel > header h3 {
2388 margin: 0;
2389 font-size: 1.05rem;
2390}
2391
2392.dialogue-step-body {
2393 flex: 1;
2394 min-height: 0;
2395 overflow: auto;
2396 padding: 0.75rem 1rem 1.1rem;
2397}
2398
2399.dialogue-step-actions {
2400 display: flex;
2401 flex-wrap: wrap;
2402 gap: 0.45rem;
2403 margin: 0.75rem 0;
2404}
2405
2406.dialogue-step-submodal {
2407 position: absolute;
2408 inset: 0;
2409 z-index: 2;
2410 display: flex;
2411 align-items: center;
2412 justify-content: center;
2413 background: rgba(0, 0, 0, 0.5);
2414 padding: 1rem;
2415}
2416
2417.dialogue-step-subpanel {
2418 width: min(420px, 100%);
2419 max-height: min(80vh, 640px);
2420 display: flex;
2421 flex-direction: column;
2422 background: #161a22;
2423 border: 1px solid #3a4250;
2424 border-radius: 8px;
2425 box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);
2426}
2427
2428.dialogue-step-subpanel > header {
2429 display: flex;
2430 align-items: center;
2431 justify-content: space-between;
2432 gap: 0.75rem;
2433 padding: 0.65rem 0.85rem;
2434 border-bottom: 1px solid #2c3340;
2435}
2436
2437.dialogue-step-subpanel > header h4 {
2438 margin: 0;
2439}
2440
2441.dialogue-step-subbody {
2442 flex: 1;
2443 min-height: 0;
2444 overflow: auto;
2445 padding: 0.75rem 0.85rem 1rem;
2446}
2447
2448.dialogue-step-delete-warn-text {
2449 margin: 0 0 1rem;
2450 padding: 0.75rem 0.85rem;
2451 background: rgba(168, 48, 48, 0.22);
2452 border: 1px solid #a84848;
2453 border-radius: 6px;
2454 color: #f0d0d0;
2455 line-height: 1.4;
2456}
2457
2458.dialogue-step-delete-actions {
2459 display: flex;
2460 justify-content: flex-end;
2461 gap: 0.5rem;
2462}
2463
2464.dialogue-step-delete-confirm {
2465 background: #8a3030;
2466 border-color: #a84848;
2467 color: #f0e8e8;
2468}
2469
2470.dialogue-step-delete-confirm:hover {
2471 background: #a83838;
2472 border-color: #c06060;
2473}
server/src/quests/runtime.js +12 −0
@@ -421,6 +421,18 @@ export class QuestRuntime
421 421 return { ok: true, events };
422 422 }
423 423
424 if (exit.kind === "continue")
425 {
426 if (!exit.nextStepId)
427 {
428 const npcEntityId = session.entityId;
429 this.sessions.delete(characterId | 0);
430 events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431 return { ok: true, events };
432 }
433 return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434 }
435
424 436 const npcEntityId = session.entityId;
425 437 this.sessions.delete(characterId | 0);
426 438 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
@@ -421,6 +421,18 @@ export class QuestRuntime
421 return { ok: true, events };
421 return { ok: true, events };
422 }
422 }
423
423
424 if (exit.kind === "continue")
425 {
426 if (!exit.nextStepId)
427 {
428 const npcEntityId = session.entityId;
429 this.sessions.delete(characterId | 0);
430 events.push({ type: "dialogueClose", reason: "continue-end", npcEntityId });
431 return { ok: true, events };
432 }
433 return this.#enterStep(characterId, session.entityId, tree, exit.nextStepId, playerView, events);
434 }
435
424 const npcEntityId = session.entityId;
436 const npcEntityId = session.entityId;
425 this.sessions.delete(characterId | 0);
437 this.sessions.delete(characterId | 0);
426 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
438 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
server/tests/dialogue-takes.test.js +62 −1
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3 3 import { normalizeDialogueTree } from "../../shared/quests/normalize.js";
4 4 import { ConditionKind } from "../../shared/quests/conditions.js";
5 5 import { formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
6 import { unguaranteedDialogueTakes } from "../../shared/quests/dialoguePathTakes.js";
6 import { dialogueExitEdges, unguaranteedDialogueTakes } from "../../shared/quests/dialoguePathTakes.js";
7 7 import {
8 8 countItemInSlots,
9 9 emptyEquipment,
@@ -221,3 +221,64 @@ test("dialogueHeard is set only after the step fully completes", () =>
221 221 finally
222 222 { harness.close(); }
223 223 });
224
225 test("normalizeDialogueTree supports continue exits and editor coordinates", () =>
226 {
227 const tree = normalizeDialogueTree({
228 dialogueId: "chain",
229 entryStepId: "a",
230 steps: [
231 {
232 stepId: "a",
233 label: "Start",
234 lines: [{ text: "Go on." }],
235 editorX: 120.5,
236 editorY: 40,
237 exit: { kind: "continue", nextStepId: "b" }
238 },
239 {
240 stepId: "b",
241 lines: [{ text: "Done." }],
242 editorX: 300,
243 editorY: 80,
244 exit: { kind: "end" }
245 }
246 ]
247 });
248 assert.equal(tree.steps[0].exit.kind, "continue");
249 assert.equal(tree.steps[0].exit.nextStepId, "b");
250 assert.equal(tree.steps[0].editorX, 120.5);
251 assert.equal(tree.steps[0].editorY, 40);
252 assert.equal(tree.steps[1].editorX, 300);
253 assert.equal(tree.steps[1].editorY, 80);
254 });
255
256 test("dialogueExitEdges treats continue as a single edge", () =>
257 {
258 const edges = dialogueExitEdges({ kind: "continue", nextStepId: "next" });
259 assert.deepEqual(edges, [{ nextStepId: "next", when: { all: [] } }]);
260 assert.deepEqual(dialogueExitEdges({ kind: "continue", nextStepId: null }), []);
261 assert.deepEqual(dialogueExitEdges({ kind: "end" }), []);
262 });
263
264 test("unguaranteedDialogueTakes follows continue edges", () =>
265 {
266 const tree = normalizeDialogueTree({
267 dialogueId: "continue-take",
268 entryStepId: "start",
269 steps: [
270 {
271 stepId: "start",
272 lines: [{ text: "Hi" }],
273 exit: { kind: "continue", nextStepId: "pay" }
274 },
275 {
276 stepId: "pay",
277 lines: [{ text: "Hand it over." }],
278 itemTakes: [{ itemId: ItemId.bones, quantity: 1 }]
279 }
280 ]
281 });
282 const warn = unguaranteedDialogueTakes(tree);
283 assert.equal(warn.get("pay")?.has(ItemId.bones), true);
284 });
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3import { normalizeDialogueTree } from "../../shared/quests/normalize.js";
3import { normalizeDialogueTree } from "../../shared/quests/normalize.js";
4import { ConditionKind } from "../../shared/quests/conditions.js";
4import { ConditionKind } from "../../shared/quests/conditions.js";
5import { formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
5import { formatDialogueTakeMessage } from "../../shared/quests/dialogueRewards.js";
6import { unguaranteedDialogueTakes } from "../../shared/quests/dialoguePathTakes.js";
6import { dialogueExitEdges, unguaranteedDialogueTakes } from "../../shared/quests/dialoguePathTakes.js";
7import {
7import {
8 countItemInSlots,
8 countItemInSlots,
9 emptyEquipment,
9 emptyEquipment,
@@ -221,3 +221,64 @@ test("dialogueHeard is set only after the step fully completes", () =>
221 finally
221 finally
222 { harness.close(); }
222 { harness.close(); }
223});
223});
224
225test("normalizeDialogueTree supports continue exits and editor coordinates", () =>
226{
227 const tree = normalizeDialogueTree({
228 dialogueId: "chain",
229 entryStepId: "a",
230 steps: [
231 {
232 stepId: "a",
233 label: "Start",
234 lines: [{ text: "Go on." }],
235 editorX: 120.5,
236 editorY: 40,
237 exit: { kind: "continue", nextStepId: "b" }
238 },
239 {
240 stepId: "b",
241 lines: [{ text: "Done." }],
242 editorX: 300,
243 editorY: 80,
244 exit: { kind: "end" }
245 }
246 ]
247 });
248 assert.equal(tree.steps[0].exit.kind, "continue");
249 assert.equal(tree.steps[0].exit.nextStepId, "b");
250 assert.equal(tree.steps[0].editorX, 120.5);
251 assert.equal(tree.steps[0].editorY, 40);
252 assert.equal(tree.steps[1].editorX, 300);
253 assert.equal(tree.steps[1].editorY, 80);
254});
255
256test("dialogueExitEdges treats continue as a single edge", () =>
257{
258 const edges = dialogueExitEdges({ kind: "continue", nextStepId: "next" });
259 assert.deepEqual(edges, [{ nextStepId: "next", when: { all: [] } }]);
260 assert.deepEqual(dialogueExitEdges({ kind: "continue", nextStepId: null }), []);
261 assert.deepEqual(dialogueExitEdges({ kind: "end" }), []);
262});
263
264test("unguaranteedDialogueTakes follows continue edges", () =>
265{
266 const tree = normalizeDialogueTree({
267 dialogueId: "continue-take",
268 entryStepId: "start",
269 steps: [
270 {
271 stepId: "start",
272 lines: [{ text: "Hi" }],
273 exit: { kind: "continue", nextStepId: "pay" }
274 },
275 {
276 stepId: "pay",
277 lines: [{ text: "Hand it over." }],
278 itemTakes: [{ itemId: ItemId.bones, quantity: 1 }]
279 }
280 ]
281 });
282 const warn = unguaranteedDialogueTakes(tree);
283 assert.equal(warn.get("pay")?.has(ItemId.bones), true);
284});
shared/quests/dialoguePathTakes.js +5 −0
@@ -49,6 +49,11 @@ export function dialogueExitEdges (exit)
49 49 edges.push({ nextStepId: trigger.nextStepId, when: trigger.when ?? { all: [] } });
50 50 }
51 51 }
52 else if (exit?.kind === "continue")
53 {
54 if (exit.nextStepId)
55 { edges.push({ nextStepId: exit.nextStepId, when: { all: [] } }); }
56 }
52 57 return edges;
53 58 }
54 59
@@ -49,6 +49,11 @@ export function dialogueExitEdges (exit)
49 edges.push({ nextStepId: trigger.nextStepId, when: trigger.when ?? { all: [] } });
49 edges.push({ nextStepId: trigger.nextStepId, when: trigger.when ?? { all: [] } });
50 }
50 }
51 }
51 }
52 else if (exit?.kind === "continue")
53 {
54 if (exit.nextStepId)
55 { edges.push({ nextStepId: exit.nextStepId, when: { all: [] } }); }
56 }
52 return edges;
57 return edges;
53}
58}
54
59
shared/quests/normalize.js +18 −1
@@ -80,7 +80,7 @@ function normalizeDialogueStep (raw, index)
80 80 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
81 81 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
82 82 const exit = normalizeExit(raw?.exit, raw);
83 return {
83 const out = {
84 84 stepId,
85 85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
86 86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
@@ -89,6 +89,13 @@ function normalizeDialogueStep (raw, index)
89 89 questRewards: normalizeQuestRewards(raw?.questRewards),
90 90 exit
91 91 };
92 const editorX = Number(raw?.editorX);
93 const editorY = Number(raw?.editorY);
94 if (Number.isFinite(editorX))
95 { out.editorX = editorX; }
96 if (Number.isFinite(editorY))
97 { out.editorY = editorY; }
98 return out;
92 99 }
93 100
94 101 /** Step-level gifts granted after all lines are read, before exit triggers/branches. */
@@ -165,6 +172,16 @@ function normalizeExit (exit, legacy)
165 172 .filter(Boolean)
166 173 };
167 174 }
175 if (exit.kind === "continue")
176 {
177 const next = exit.nextStepId == null || exit.nextStepId === ""
178 ? null
179 : slugId(exit.nextStepId, "");
180 return {
181 kind: "continue",
182 nextStepId: next || null
183 };
184 }
168 185 return { kind: "end" };
169 186 }
170 187 if (Array.isArray(legacy?.triggers) && legacy.triggers.length > 0)
@@ -80,7 +80,7 @@ function normalizeDialogueStep (raw, index)
80 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
80 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
81 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
81 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
82 const exit = normalizeExit(raw?.exit, raw);
82 const exit = normalizeExit(raw?.exit, raw);
83 return {
83 const out = {
84 stepId,
84 stepId,
85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
@@ -89,6 +89,13 @@ function normalizeDialogueStep (raw, index)
89 questRewards: normalizeQuestRewards(raw?.questRewards),
89 questRewards: normalizeQuestRewards(raw?.questRewards),
90 exit
90 exit
91 };
91 };
92 const editorX = Number(raw?.editorX);
93 const editorY = Number(raw?.editorY);
94 if (Number.isFinite(editorX))
95 { out.editorX = editorX; }
96 if (Number.isFinite(editorY))
97 { out.editorY = editorY; }
98 return out;
92}
99}
93
100
94/** Step-level gifts granted after all lines are read, before exit triggers/branches. */
101/** Step-level gifts granted after all lines are read, before exit triggers/branches. */
@@ -165,6 +172,16 @@ function normalizeExit (exit, legacy)
165 .filter(Boolean)
172 .filter(Boolean)
166 };
173 };
167 }
174 }
175 if (exit.kind === "continue")
176 {
177 const next = exit.nextStepId == null || exit.nextStepId === ""
178 ? null
179 : slugId(exit.nextStepId, "");
180 return {
181 kind: "continue",
182 nextStepId: next || null
183 };
184 }
168 return { kind: "end" };
185 return { kind: "end" };
169 }
186 }
170 if (Array.isArray(legacy?.triggers) && legacy.triggers.length > 0)
187 if (Array.isArray(legacy?.triggers) && legacy.triggers.length > 0)