BlueGit

timfa questward

Merge branch 'cursor/quest-graph-editor-fa7b' into 'master'

Quest graph editor: steps on the shared canvas

See merge request Timfa/questward!7

timfa Tim Falken · pushed by timfa

Authored 2026-10-14 · 4 weeks ago

Hash
b5646ac6b30c5655f8174dacf881450fed926d31
8 files changed +1530 −187
client/src/editor/dialogueCanvas.js +100 −60
@@ -1,10 +1,57 @@
1 1 /**
2 * Desktop node-graph canvas for dialogue steps.
2 * Desktop node-graph canvas for dialogue steps (and other graphs that pass a port adapter).
3 3 * Pan empty space, drag cards, wheel zoom, wire outputs → inputs.
4 *
5 * Dialogue calls use the built-in ports (continue / triggers / branches / end).
6 * Other hosts pass getPorts, cardLabel, cardMeta, isEntryStep, stepPosition, and cardFlags.
4 7 */
5 8
6 const CARD_W = 168;
7 const CARD_H = 72;
9 export const CARD_W = 168;
10 export const CARD_H = 72;
11
12 /** Default dialogue ports. Quest (and other) hosts replace this via getPorts. */
13 export function dialogueOutputPorts (step)
14 {
15 const exit = step?.exit ?? { kind: "end" };
16 if (exit.kind === "continue")
17 {
18 return [{
19 key: "continue",
20 label: "Continue",
21 nextStepId: exit.nextStepId ?? null,
22 setNext (id)
23 {
24 exit.nextStepId = id;
25 }
26 }];
27 }
28 if (exit.kind === "triggers")
29 {
30 return (exit.triggers ?? []).map((trig, i) => ({
31 key: `trigger:${i}`,
32 /** Player-facing button text (not the internal trigger id / legacy label). */
33 label: (trig.text ?? "").trim() || trig.trigger || `Trigger ${i + 1}`,
34 nextStepId: trig.nextStepId ?? null,
35 setNext (id)
36 {
37 trig.nextStepId = id;
38 }
39 }));
40 }
41 if (exit.kind === "branches")
42 {
43 return (exit.branches ?? []).map((branch, i) => ({
44 key: `branch:${i}`,
45 label: branch.label?.trim() ? branch.label : `Branch ${i + 1}`,
46 nextStepId: branch.nextStepId ?? null,
47 setNext (id)
48 {
49 branch.nextStepId = id;
50 }
51 }));
52 }
53 return [];
54 }
8 55 const PORT_R = 7;
9 56 const EDGE_PAD = 36;
10 57 const MIN_ZOOM = 0.35;
@@ -16,11 +63,40 @@ const AUTO_PAN = 14;
16 63 * getDraft: () => object | null,
17 64 * onOpenStep: (stepId: string) => void,
18 65 * onCreateStep: (worldX: number, worldY: number) => void,
19 * onChange: () => void
66 * onChange: () => void,
67 * getPorts?: (step: object) => { key: string, label: string, nextStepId: string | null, setNext: (id: string | null) => void }[],
68 * cardLabel?: (step: object) => string,
69 * cardMeta?: (step: object, isEntry: boolean) => string,
70 * isEntryStep?: (draft: object | null, step: object) => boolean,
71 * stepPosition?: (step: object, index: number, draft: object | null) => { x: number, y: number } | null,
72 * cardFlags?: (step: object, isEntry: boolean) => Record<string, boolean>,
73 * createStepLabel?: string
20 74 * }} options
21 75 */
22 export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onChange })
76 export function createDialogueCanvas ({
77 getDraft,
78 onOpenStep,
79 onCreateStep,
80 onChange,
81 getPorts = null,
82 cardLabel = null,
83 cardMeta = null,
84 isEntryStep = null,
85 stepPosition: stepPositionOverride = null,
86 cardFlags = null,
87 createStepLabel = "Create new step"
88 })
23 89 {
90 const resolvePorts = getPorts ?? dialogueOutputPorts;
91 const resolveLabel = cardLabel ?? ((step) => step.label || step.stepId);
92 const resolveMeta = cardMeta ?? ((step, isEntry) =>
93 {
94 const kind = step.exit?.kind ?? "end";
95 return isEntry ? `entry · ${kind}` : kind;
96 });
97 const resolveEntry = isEntryStep ?? ((draft, step) =>
98 !!(draft && (draft.entryStepId === step.stepId
99 || (!draft.entryStepId && draft.steps[0] === step))));
24 100 const wrap = document.createElement("div");
25 101 wrap.className = "dialogue-canvas-wrap";
26 102
@@ -47,7 +123,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
47 123 ctxMenu.hidden = true;
48 124 const createBtn = document.createElement("button");
49 125 createBtn.type = "button";
50 createBtn.textContent = "Create new step";
126 createBtn.textContent = createStepLabel;
51 127 ctxMenu.append(createBtn);
52 128
53 129 const tooltip = document.createElement("div");
@@ -123,54 +199,17 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
123 199
124 200 function stepPosition (step, index)
125 201 {
202 if (stepPositionOverride)
203 {
204 const laid = stepPositionOverride(step, index, getDraft());
205 if (laid && Number.isFinite(laid.x) && Number.isFinite(laid.y))
206 { return laid; }
207 }
126 208 const x = Number.isFinite(step.editorX) ? step.editorX : 40 + (index % 4) * (CARD_W + 48);
127 209 const y = Number.isFinite(step.editorY) ? step.editorY : 40 + Math.floor(index / 4) * (CARD_H + 64);
128 210 return { x, y };
129 211 }
130 212
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 213 function portWorldPos (step, index, portIndex, kind)
175 214 {
176 215 const pos = stepPosition(step, index);
@@ -178,7 +217,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
178 217 {
179 218 return { x: pos.x + CARD_W / 2, y: pos.y };
180 219 }
181 const ports = outputPorts(step);
220 const ports = resolvePorts(step);
182 221 const n = Math.max(1, ports.length);
183 222 const spacing = CARD_W / (n + 1);
184 223 return {
@@ -267,7 +306,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
267 306 { return; }
268 307 draft.steps.forEach((step, index) =>
269 308 {
270 const ports = outputPorts(step);
309 const ports = resolvePorts(step);
271 310 ports.forEach((port, portIndex) =>
272 311 {
273 312 if (!port.nextStepId)
@@ -349,7 +388,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
349 388 const from = draft?.steps?.find((s) => s.stepId === wiring.stepId);
350 389 if (!from)
351 390 { return; }
352 const ports = outputPorts(from);
391 const ports = resolvePorts(from);
353 392 const port = ports[wiring.portIndex];
354 393 if (!port)
355 394 { return; }
@@ -411,18 +450,19 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
411 450 {
412 451 card.setAttribute("data-step-id", step.stepId);
413 452 const draft = getDraft();
414 const isEntry = draft && (draft.entryStepId === step.stepId
415 || (!draft.entryStepId && draft.steps[0] === step));
453 const isEntry = resolveEntry(draft, step);
416 454 card.classList.toggle("is-entry", !!isEntry);
455 if (cardFlags)
456 {
457 for (const [name, on] of Object.entries(cardFlags(step, !!isEntry) ?? {}))
458 { card.classList.toggle(name, !!on); }
459 }
417 460 const label = card.querySelector(".dialogue-canvas-card-label");
418 461 if (label)
419 { label.textContent = step.label || step.stepId; }
462 { label.textContent = resolveLabel(step); }
420 463 const meta = card.querySelector(".dialogue-canvas-card-meta");
421 464 if (meta)
422 {
423 const kind = step.exit?.kind ?? "end";
424 meta.textContent = isEntry ? `entry · ${kind}` : kind;
425 }
465 { meta.textContent = resolveMeta(step, !!isEntry); }
426 466 const input = card.querySelector(".dialogue-canvas-input");
427 467 if (input)
428 468 {
@@ -433,7 +473,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
433 473 if (!portsRow)
434 474 { return; }
435 475 portsRow.replaceChildren();
436 const ports = outputPorts(step);
476 const ports = resolvePorts(step);
437 477 ports.forEach((port, portIndex) =>
438 478 {
439 479 const btn = document.createElement("button");
@@ -1,10 +1,57 @@
1/**
1/**
2 * Desktop node-graph canvas for dialogue steps.
2 * Desktop node-graph canvas for dialogue steps (and other graphs that pass a port adapter).
3 * Pan empty space, drag cards, wheel zoom, wire outputs → inputs.
3 * Pan empty space, drag cards, wheel zoom, wire outputs → inputs.
4 *
5 * Dialogue calls use the built-in ports (continue / triggers / branches / end).
6 * Other hosts pass getPorts, cardLabel, cardMeta, isEntryStep, stepPosition, and cardFlags.
4 */
7 */
5
8
6const CARD_W = 168;
9export const CARD_W = 168;
7const CARD_H = 72;
10export const CARD_H = 72;
11
12/** Default dialogue ports. Quest (and other) hosts replace this via getPorts. */
13export function dialogueOutputPorts (step)
14{
15 const exit = step?.exit ?? { kind: "end" };
16 if (exit.kind === "continue")
17 {
18 return [{
19 key: "continue",
20 label: "Continue",
21 nextStepId: exit.nextStepId ?? null,
22 setNext (id)
23 {
24 exit.nextStepId = id;
25 }
26 }];
27 }
28 if (exit.kind === "triggers")
29 {
30 return (exit.triggers ?? []).map((trig, i) => ({
31 key: `trigger:${i}`,
32 /** Player-facing button text (not the internal trigger id / legacy label). */
33 label: (trig.text ?? "").trim() || trig.trigger || `Trigger ${i + 1}`,
34 nextStepId: trig.nextStepId ?? null,
35 setNext (id)
36 {
37 trig.nextStepId = id;
38 }
39 }));
40 }
41 if (exit.kind === "branches")
42 {
43 return (exit.branches ?? []).map((branch, i) => ({
44 key: `branch:${i}`,
45 label: branch.label?.trim() ? branch.label : `Branch ${i + 1}`,
46 nextStepId: branch.nextStepId ?? null,
47 setNext (id)
48 {
49 branch.nextStepId = id;
50 }
51 }));
52 }
53 return [];
54}
8const PORT_R = 7;
55const PORT_R = 7;
9const EDGE_PAD = 36;
56const EDGE_PAD = 36;
10const MIN_ZOOM = 0.35;
57const MIN_ZOOM = 0.35;
@@ -16,11 +63,40 @@ const AUTO_PAN = 14;
16 * getDraft: () => object | null,
63 * getDraft: () => object | null,
17 * onOpenStep: (stepId: string) => void,
64 * onOpenStep: (stepId: string) => void,
18 * onCreateStep: (worldX: number, worldY: number) => void,
65 * onCreateStep: (worldX: number, worldY: number) => void,
19 * onChange: () => void
66 * onChange: () => void,
67 * getPorts?: (step: object) => { key: string, label: string, nextStepId: string | null, setNext: (id: string | null) => void }[],
68 * cardLabel?: (step: object) => string,
69 * cardMeta?: (step: object, isEntry: boolean) => string,
70 * isEntryStep?: (draft: object | null, step: object) => boolean,
71 * stepPosition?: (step: object, index: number, draft: object | null) => { x: number, y: number } | null,
72 * cardFlags?: (step: object, isEntry: boolean) => Record<string, boolean>,
73 * createStepLabel?: string
20 * }} options
74 * }} options
21 */
75 */
22export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onChange })
76export function createDialogueCanvas ({
77 getDraft,
78 onOpenStep,
79 onCreateStep,
80 onChange,
81 getPorts = null,
82 cardLabel = null,
83 cardMeta = null,
84 isEntryStep = null,
85 stepPosition: stepPositionOverride = null,
86 cardFlags = null,
87 createStepLabel = "Create new step"
88})
23{
89{
90 const resolvePorts = getPorts ?? dialogueOutputPorts;
91 const resolveLabel = cardLabel ?? ((step) => step.label || step.stepId);
92 const resolveMeta = cardMeta ?? ((step, isEntry) =>
93 {
94 const kind = step.exit?.kind ?? "end";
95 return isEntry ? `entry · ${kind}` : kind;
96 });
97 const resolveEntry = isEntryStep ?? ((draft, step) =>
98 !!(draft && (draft.entryStepId === step.stepId
99 || (!draft.entryStepId && draft.steps[0] === step))));
24 const wrap = document.createElement("div");
100 const wrap = document.createElement("div");
25 wrap.className = "dialogue-canvas-wrap";
101 wrap.className = "dialogue-canvas-wrap";
26
102
@@ -47,7 +123,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
47 ctxMenu.hidden = true;
123 ctxMenu.hidden = true;
48 const createBtn = document.createElement("button");
124 const createBtn = document.createElement("button");
49 createBtn.type = "button";
125 createBtn.type = "button";
50 createBtn.textContent = "Create new step";
126 createBtn.textContent = createStepLabel;
51 ctxMenu.append(createBtn);
127 ctxMenu.append(createBtn);
52
128
53 const tooltip = document.createElement("div");
129 const tooltip = document.createElement("div");
@@ -123,54 +199,17 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
123
199
124 function stepPosition (step, index)
200 function stepPosition (step, index)
125 {
201 {
202 if (stepPositionOverride)
203 {
204 const laid = stepPositionOverride(step, index, getDraft());
205 if (laid && Number.isFinite(laid.x) && Number.isFinite(laid.y))
206 { return laid; }
207 }
126 const x = Number.isFinite(step.editorX) ? step.editorX : 40 + (index % 4) * (CARD_W + 48);
208 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);
209 const y = Number.isFinite(step.editorY) ? step.editorY : 40 + Math.floor(index / 4) * (CARD_H + 64);
128 return { x, y };
210 return { x, y };
129 }
211 }
130
212
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)
213 function portWorldPos (step, index, portIndex, kind)
175 {
214 {
176 const pos = stepPosition(step, index);
215 const pos = stepPosition(step, index);
@@ -178,7 +217,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
178 {
217 {
179 return { x: pos.x + CARD_W / 2, y: pos.y };
218 return { x: pos.x + CARD_W / 2, y: pos.y };
180 }
219 }
181 const ports = outputPorts(step);
220 const ports = resolvePorts(step);
182 const n = Math.max(1, ports.length);
221 const n = Math.max(1, ports.length);
183 const spacing = CARD_W / (n + 1);
222 const spacing = CARD_W / (n + 1);
184 return {
223 return {
@@ -267,7 +306,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
267 { return; }
306 { return; }
268 draft.steps.forEach((step, index) =>
307 draft.steps.forEach((step, index) =>
269 {
308 {
270 const ports = outputPorts(step);
309 const ports = resolvePorts(step);
271 ports.forEach((port, portIndex) =>
310 ports.forEach((port, portIndex) =>
272 {
311 {
273 if (!port.nextStepId)
312 if (!port.nextStepId)
@@ -349,7 +388,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
349 const from = draft?.steps?.find((s) => s.stepId === wiring.stepId);
388 const from = draft?.steps?.find((s) => s.stepId === wiring.stepId);
350 if (!from)
389 if (!from)
351 { return; }
390 { return; }
352 const ports = outputPorts(from);
391 const ports = resolvePorts(from);
353 const port = ports[wiring.portIndex];
392 const port = ports[wiring.portIndex];
354 if (!port)
393 if (!port)
355 { return; }
394 { return; }
@@ -411,18 +450,19 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
411 {
450 {
412 card.setAttribute("data-step-id", step.stepId);
451 card.setAttribute("data-step-id", step.stepId);
413 const draft = getDraft();
452 const draft = getDraft();
414 const isEntry = draft && (draft.entryStepId === step.stepId
453 const isEntry = resolveEntry(draft, step);
415 || (!draft.entryStepId && draft.steps[0] === step));
416 card.classList.toggle("is-entry", !!isEntry);
454 card.classList.toggle("is-entry", !!isEntry);
455 if (cardFlags)
456 {
457 for (const [name, on] of Object.entries(cardFlags(step, !!isEntry) ?? {}))
458 { card.classList.toggle(name, !!on); }
459 }
417 const label = card.querySelector(".dialogue-canvas-card-label");
460 const label = card.querySelector(".dialogue-canvas-card-label");
418 if (label)
461 if (label)
419 { label.textContent = step.label || step.stepId; }
462 { label.textContent = resolveLabel(step); }
420 const meta = card.querySelector(".dialogue-canvas-card-meta");
463 const meta = card.querySelector(".dialogue-canvas-card-meta");
421 if (meta)
464 if (meta)
422 {
465 { meta.textContent = resolveMeta(step, !!isEntry); }
423 const kind = step.exit?.kind ?? "end";
424 meta.textContent = isEntry ? `entry · ${kind}` : kind;
425 }
426 const input = card.querySelector(".dialogue-canvas-input");
466 const input = card.querySelector(".dialogue-canvas-input");
427 if (input)
467 if (input)
428 {
468 {
@@ -433,7 +473,7 @@ export function createDialogueCanvas ({ getDraft, onOpenStep, onCreateStep, onCh
433 if (!portsRow)
473 if (!portsRow)
434 { return; }
474 { return; }
435 portsRow.replaceChildren();
475 portsRow.replaceChildren();
436 const ports = outputPorts(step);
476 const ports = resolvePorts(step);
437 ports.forEach((port, portIndex) =>
477 ports.forEach((port, portIndex) =>
438 {
478 {
439 const btn = document.createElement("button");
479 const btn = document.createElement("button");
client/src/editor/questStepModal.js added +713 −0
@@ -0,0 +1,713 @@
1 /**
2 * Step panel for the quest graph editor.
3 * Wires stay on the canvas; this panel edits text, exit kind, objectives, and branches.
4 */
5 import { emptyConditionSet, EffectKind } from "/shared/quests/conditions.js";
6 import { relinkImplicitQuestExits } from "/shared/quests/normalize.js";
7 import { blankQuestStep, branchShadowsLater } from "/shared/quests/questGraph.js";
8 import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
9 import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
10 import { renderConditionSet } from "./conditionSetEditor.js";
11 import { scrubDialogueStepLinks, stepHasEdges } from "./dialogueCanvas.js";
12
13 /**
14 * @param {{
15 * getDraft: () => object | null,
16 * conditionCtx: () => object,
17 * onChange: () => void,
18 * host?: HTMLElement | null
19 * }} options
20 */
21 export function initQuestStepModal ({
22 getDraft,
23 conditionCtx,
24 onChange,
25 host = null
26 })
27 {
28 const root = document.createElement("div");
29 root.className = "dialogue-step-overlay";
30 root.hidden = true;
31
32 const backdrop = document.createElement("div");
33 backdrop.className = "dialogue-step-backdrop";
34
35 const panel = document.createElement("div");
36 panel.className = "dialogue-step-panel quest-step-panel";
37
38 const header = document.createElement("header");
39 const title = document.createElement("h3");
40 title.textContent = "Step";
41 const closeBtn = document.createElement("button");
42 closeBtn.type = "button";
43 closeBtn.textContent = "Close";
44 header.append(title, closeBtn);
45
46 const body = document.createElement("div");
47 body.className = "dialogue-step-body";
48
49 root.append(backdrop, panel);
50 panel.append(header, body);
51 (host || document.body).append(root);
52
53 /** @type {string | null} */
54 let openStepId = null;
55
56 function show (visible)
57 {
58 root.hidden = !visible;
59 if (!visible)
60 {
61 openStepId = null;
62 body.replaceChildren();
63 }
64 }
65
66 function currentStep ()
67 {
68 const draft = getDraft();
69 if (!draft || !openStepId)
70 { return null; }
71 return draft.steps?.find((step) => step.stepId === openStepId) ?? null;
72 }
73
74 function uniqueStepId (draft, preferred)
75 {
76 const used = new Set((draft.steps ?? []).map((step) => step.stepId));
77 if (!used.has(preferred))
78 { return preferred; }
79 let n = (draft.steps?.length ?? 0) + 1;
80 let id = `step-${n}`;
81 while (used.has(id))
82 {
83 n += 1;
84 id = `step-${n}`;
85 }
86 return id;
87 }
88
89 function renameStep (step, nextId)
90 {
91 const draft = getDraft();
92 const previous = step.stepId;
93 if (!draft || !nextId || nextId === previous)
94 { return; }
95 if (draft.steps.some((other) => other !== step && other.stepId === nextId))
96 { return; }
97 for (const other of draft.steps)
98 {
99 const exit = other.exit;
100 if (!exit)
101 { continue; }
102 if (exit.kind === "continue" && exit.nextStepId === previous)
103 { exit.nextStepId = nextId; }
104 for (const branch of exit.branches ?? [])
105 {
106 if (branch.nextStepId === previous)
107 { branch.nextStepId = nextId; }
108 }
109 }
110 step.stepId = nextId;
111 openStepId = nextId;
112 onChange();
113 }
114
115 function setExitKind (step, kind)
116 {
117 const carried = step.exit?.kind === "continue"
118 ? (step.exit.nextStepId ?? null)
119 : (step.exit?.kind === "branches"
120 ? (step.exit.branches?.find((branch) => branch.nextStepId)?.nextStepId ?? null)
121 : null);
122 if (kind === "branches")
123 {
124 const existing = step.exit?.kind === "branches" ? (step.exit.branches ?? []) : [];
125 const branches = existing.length
126 ? existing
127 : [{
128 label: "",
129 text: "",
130 when: emptyConditionSet(),
131 nextStepId: carried,
132 effects: []
133 }];
134 step.exit = { kind: "branches", branches };
135 return;
136 }
137 if (kind === "continue")
138 {
139 const prev = step.exit?.kind === "continue"
140 ? (step.exit.nextStepId ?? null)
141 : carried;
142 step.exit = { kind: "continue", nextStepId: prev };
143 return;
144 }
145 step.exit = { kind: "complete" };
146 }
147
148 function deleteStep (step)
149 {
150 const draft = getDraft();
151 if (!draft)
152 { return; }
153 const removedId = step.stepId;
154 const index = draft.steps.indexOf(step);
155 if (index < 0)
156 { return; }
157 draft.steps.splice(index, 1);
158 scrubDialogueStepLinks(draft, removedId);
159 if (draft.steps.length === 0)
160 { draft.steps.push(blankQuestStep(uniqueStepId(draft, "step-1"), 80, 80)); }
161 else
162 { relinkImplicitQuestExits(draft.steps); }
163 show(false);
164 onChange();
165 }
166
167 function confirmDelete (step)
168 {
169 const draft = getDraft();
170 const linked = stepHasEdges(draft, step);
171 const message = linked
172 ? `Delete step "${step.title || step.stepId}"? Incoming and outgoing wires to it will be cleared.`
173 : `Delete step "${step.title || step.stepId}"?`;
174 if (!window.confirm(message))
175 { return; }
176 deleteStep(step);
177 }
178
179 function renderObjectives (step)
180 {
181 const head = sectionHeader("Objectives", () =>
182 {
183 step.objectives.push({
184 objectiveId: `obj-${step.objectives.length + 1}`,
185 text: "New objective",
186 when: emptyConditionSet()
187 });
188 onChange();
189 render();
190 });
191 body.append(head);
192 const note = document.createElement("p");
193 note.className = "content-editor-hint";
194 note.textContent = "All objectives must be done before this step advances.";
195 body.append(note);
196
197 step.objectives.forEach((obj, objIndex) =>
198 {
199 const objBox = document.createElement("div");
200 objBox.className = "content-editor-section";
201 objBox.append(
202 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
203 {
204 if (!window.confirm(`Delete objective "${obj.text || obj.objectiveId || objIndex + 1}"?`))
205 { return; }
206 step.objectives.splice(objIndex, 1);
207 if (step.objectives.length === 0)
208 {
209 step.objectives.push({
210 objectiveId: "obj-1",
211 text: "Complete this step",
212 when: emptyConditionSet()
213 });
214 }
215 onChange();
216 render();
217 }),
218 field("Text", textInput(obj.text, (value) =>
219 {
220 obj.text = value;
221 onChange();
222 }))
223 );
224 objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>
225 {
226 obj.when = next;
227 onChange();
228 if (remount)
229 { render(); }
230 }, conditionCtx()));
231 body.append(objBox);
232 });
233 }
234
235 function renderBranches (step)
236 {
237 if (!Array.isArray(step.exit.branches))
238 { step.exit.branches = []; }
239 const branches = step.exit.branches;
240 const head = sectionHeader("Branches", () =>
241 {
242 branches.push({
243 label: "",
244 text: "",
245 when: emptyConditionSet(),
246 nextStepId: null,
247 effects: []
248 });
249 onChange();
250 render();
251 });
252 body.append(head);
253 const note = document.createElement("p");
254 note.className = "content-editor-hint";
255 note.textContent = "First matching branch wins. The top of this list is checked first. Wire each branch from its port on the canvas. An empty next step completes the quest.";
256 body.append(note);
257
258 branches.forEach((branch, index) =>
259 {
260 const box = document.createElement("div");
261 box.className = "content-editor-section";
262 const titleText = document.createElement("span");
263 titleText.append(
264 Object.assign(document.createElement("span"), {
265 className: "quest-branch-order",
266 textContent: `${index + 1}. `
267 }),
268 document.createTextNode(branch.label?.trim() || branch.text?.trim() || "Branch")
269 );
270 const headerRow = document.createElement("div");
271 headerRow.className = "content-editor-section-header";
272 const strong = document.createElement("strong");
273 strong.append(titleText);
274 headerRow.append(strong);
275 const actions = document.createElement("div");
276 actions.className = "content-editor-row";
277 actions.append(
278 smallButton("Up", index === 0, () => moveBranch(branches, index, -1)),
279 smallButton("Down", index === branches.length - 1, () => moveBranch(branches, index, 1)),
280 removeButton(() =>
281 {
282 if (!window.confirm(`Delete branch ${index + 1}?`))
283 { return; }
284 branches.splice(index, 1);
285 onChange();
286 render();
287 })
288 );
289 headerRow.append(actions);
290 box.append(headerRow);
291
292 if (branchShadowsLater(branches, index))
293 {
294 const warn = document.createElement("p");
295 warn.className = "quest-branch-shadow-warn";
296 warn.textContent = "This condition is empty, so it always matches. Branches below it never run.";
297 box.append(warn);
298 }
299
300 box.append(
301 field("Label", textInput(branch.label ?? "", (value) =>
302 {
303 branch.label = value;
304 onChange();
305 })),
306 field("Log text", textArea(branch.text ?? "", (value) =>
307 {
308 branch.text = value;
309 onChange();
310 }, 2))
311 );
312 box.append(renderConditionSet(branch.when, (next, { remount = true } = {}) =>
313 {
314 branch.when = next;
315 onChange();
316 if (remount)
317 { render(); }
318 }, conditionCtx()));
319 box.append(renderEffects(branch));
320 body.append(box);
321 });
322
323 function moveBranch (list, index, delta)
324 {
325 const target = index + delta;
326 if (target < 0 || target >= list.length)
327 { return; }
328 const [row] = list.splice(index, 1);
329 list.splice(target, 0, row);
330 onChange();
331 render();
332 }
333 }
334
335 function renderEffects (branch)
336 {
337 if (!Array.isArray(branch.effects))
338 { branch.effects = []; }
339 const wrap = document.createElement("div");
340 wrap.append(sectionHeader("Effects", () =>
341 {
342 branch.effects.push(blankEffect(EffectKind.giveXp));
343 onChange();
344 render();
345 }));
346 if (!branch.effects.length)
347 {
348 const empty = document.createElement("p");
349 empty.className = "content-editor-hint";
350 empty.textContent = "No effects. They run when this branch is taken.";
351 wrap.append(empty);
352 return wrap;
353 }
354 branch.effects.forEach((effect, effectIndex) =>
355 {
356 const row = document.createElement("div");
357 row.className = "content-editor-section";
358 const kind = document.createElement("select");
359 for (const value of Object.values(EffectKind))
360 {
361 const opt = document.createElement("option");
362 opt.value = value;
363 opt.textContent = effectKindLabel(value);
364 if (effect.kind === value)
365 { opt.selected = true; }
366 kind.append(opt);
367 }
368 kind.addEventListener("change", () =>
369 {
370 branch.effects[effectIndex] = blankEffect(kind.value);
371 onChange();
372 render();
373 });
374 row.append(field("Effect", kind));
375 if (effect.kind === EffectKind.giveXp)
376 { row.append(xpFields(effect)); }
377 else if (effect.kind === EffectKind.giveItem || effect.kind === EffectKind.takeItem)
378 { row.append(itemFields(effect)); }
379 else if (effect.kind === EffectKind.startQuest)
380 { row.append(questFields(effect)); }
381 row.append(removeButton(() =>
382 {
383 branch.effects.splice(effectIndex, 1);
384 onChange();
385 render();
386 }));
387 wrap.append(row);
388 });
389 return wrap;
390
391 function xpFields (effect)
392 {
393 const line = document.createElement("div");
394 line.className = "content-editor-row";
395 const skill = document.createElement("select");
396 for (const skillId of ALL_SKILL_IDS)
397 {
398 const opt = document.createElement("option");
399 opt.value = skillId;
400 opt.textContent = SKILL_DEFINITIONS[skillId]?.displayName ?? skillId;
401 if (effect.skillId === skillId)
402 { opt.selected = true; }
403 skill.append(opt);
404 }
405 skill.addEventListener("change", () =>
406 {
407 effect.skillId = skill.value;
408 onChange();
409 });
410 const amount = document.createElement("input");
411 amount.type = "number";
412 amount.min = "1";
413 amount.step = "1";
414 amount.value = String(Math.max(1, effect.amount | 0 || 1));
415 amount.addEventListener("input", () =>
416 {
417 effect.amount = Math.max(1, Number(amount.value) || 1) | 0;
418 onChange();
419 });
420 line.append(skill, amount);
421 return line;
422 }
423
424 function itemFields (effect)
425 {
426 const line = document.createElement("div");
427 line.className = "content-editor-row";
428 const select = document.createElement("select");
429 for (const item of listAllItemPickerEntries())
430 {
431 const opt = document.createElement("option");
432 opt.value = String(item.itemId);
433 opt.textContent = item.displayName;
434 if (Number(effect.itemId) === item.itemId)
435 { opt.selected = true; }
436 select.append(opt);
437 }
438 if (effect.itemId && ![...select.options].some((opt) => opt.value === String(effect.itemId)))
439 {
440 const missing = document.createElement("option");
441 missing.value = String(effect.itemId);
442 missing.textContent = itemDefinition(effect.itemId)?.displayName ?? `Item ${effect.itemId}`;
443 missing.selected = true;
444 select.append(missing);
445 }
446 select.addEventListener("change", () =>
447 {
448 effect.itemId = Number(select.value) | 0;
449 onChange();
450 });
451 const qty = document.createElement("input");
452 qty.type = "number";
453 qty.min = "1";
454 qty.step = "1";
455 qty.value = String(Math.max(1, effect.quantity | 0 || 1));
456 qty.addEventListener("input", () =>
457 {
458 effect.quantity = Math.max(1, Number(qty.value) || 1) | 0;
459 onChange();
460 });
461 line.append(select, qty);
462 if (effect.kind === EffectKind.giveItem)
463 {
464 const bankLabel = document.createElement("label");
465 bankLabel.className = "quest-reward-bank";
466 const bankBox = document.createElement("input");
467 bankBox.type = "checkbox";
468 bankBox.checked = !!effect.toBank;
469 bankBox.addEventListener("change", () =>
470 {
471 effect.toBank = bankBox.checked;
472 onChange();
473 });
474 bankLabel.append(bankBox, document.createTextNode(" Bank"));
475 line.append(bankLabel);
476 }
477 return line;
478 }
479
480 function questFields (effect)
481 {
482 const select = document.createElement("select");
483 const quests = conditionCtx().quests ?? [];
484 const none = document.createElement("option");
485 none.value = "";
486 none.textContent = "Choose a quest";
487 select.append(none);
488 for (const quest of quests)
489 {
490 const opt = document.createElement("option");
491 opt.value = quest.questId;
492 opt.textContent = quest.title || quest.questId;
493 if (effect.questId === quest.questId)
494 { opt.selected = true; }
495 select.append(opt);
496 }
497 if (effect.questId && ![...select.options].some((opt) => opt.value === effect.questId))
498 {
499 const missing = document.createElement("option");
500 missing.value = effect.questId;
501 missing.textContent = effect.questId;
502 missing.selected = true;
503 select.append(missing);
504 }
505 select.addEventListener("change", () =>
506 {
507 effect.questId = select.value;
508 onChange();
509 });
510 return field("Quest", select);
511 }
512 }
513
514 function render ()
515 {
516 const step = currentStep();
517 body.replaceChildren();
518 if (!step)
519 {
520 show(false);
521 return;
522 }
523 title.textContent = step.title || step.stepId || "Step";
524 const stepIdInput = document.createElement("input");
525 stepIdInput.type = "text";
526 stepIdInput.value = step.stepId ?? "";
527 stepIdInput.addEventListener("change", () =>
528 {
529 const next = stepIdInput.value.trim();
530 const previous = step.stepId;
531 renameStep(step, next);
532 if (step.stepId === previous && next !== previous)
533 { stepIdInput.value = previous; }
534 });
535 body.append(
536 field("Step id", stepIdInput),
537 field("Title", textInput(step.title, (value) =>
538 {
539 step.title = value;
540 title.textContent = value || step.stepId;
541 onChange();
542 })),
543 field("Description", textArea(step.description, (value) =>
544 {
545 step.description = value;
546 onChange();
547 }, 2)),
548 field("Completion journal", textArea(step.completionJournalText, (value) =>
549 {
550 step.completionJournalText = value;
551 onChange();
552 }, 2))
553 );
554
555 const exitKind = document.createElement("select");
556 for (const option of [
557 { value: "continue", label: "Continue" },
558 { value: "branches", label: "Branches" },
559 { value: "complete", label: "Complete" }
560 ])
561 {
562 const opt = document.createElement("option");
563 opt.value = option.value;
564 opt.textContent = option.label;
565 if ((step.exit?.kind ?? "complete") === option.value)
566 { opt.selected = true; }
567 exitKind.append(opt);
568 }
569 exitKind.addEventListener("change", () =>
570 {
571 setExitKind(step, exitKind.value);
572 onChange();
573 render();
574 });
575 body.append(field("Exit", exitKind));
576
577 const exitNote = document.createElement("p");
578 exitNote.className = "content-editor-hint";
579 if (step.exit?.kind === "branches")
580 { exitNote.textContent = "Each branch has its own output port. A port with no wire completes the quest."; }
581 else if (step.exit?.kind === "continue")
582 { exitNote.textContent = "One output port. Wire it on the canvas. No wire completes the quest."; }
583 else
584 { exitNote.textContent = "Quest end. This card has no output port. Objectives still have to be finished first."; }
585 body.append(exitNote);
586
587 if (step.exit?.kind === "branches")
588 { renderBranches(step); }
589 else
590 { renderObjectives(step); }
591
592 const remove = document.createElement("button");
593 remove.type = "button";
594 remove.className = "content-editor-remove";
595 remove.textContent = "Delete step";
596 remove.addEventListener("click", () => confirmDelete(step));
597 body.append(remove);
598 }
599
600 closeBtn.addEventListener("click", () => show(false));
601 backdrop.addEventListener("click", () => show(false));
602
603 return {
604 open (stepId)
605 {
606 openStepId = stepId;
607 show(true);
608 render();
609 },
610 close: () => show(false),
611 isOpen: () => !!openStepId && !root.hidden,
612 refresh ()
613 {
614 if (openStepId)
615 { render(); }
616 }
617 };
618 }
619
620 function blankEffect (kind)
621 {
622 const item = listAllItemPickerEntries()[0];
623 if (kind === EffectKind.giveItem)
624 { return { kind, itemId: item?.itemId ?? 1, quantity: 1, toBank: false }; }
625 if (kind === EffectKind.takeItem)
626 { return { kind, itemId: item?.itemId ?? 1, quantity: 1 }; }
627 if (kind === EffectKind.startQuest)
628 { return { kind, questId: "" }; }
629 return { kind: EffectKind.giveXp, skillId: ALL_SKILL_IDS[0], amount: 10 };
630 }
631
632 function effectKindLabel (kind)
633 {
634 if (kind === EffectKind.giveXp)
635 { return "Give XP"; }
636 if (kind === EffectKind.giveItem)
637 { return "Give item"; }
638 if (kind === EffectKind.takeItem)
639 { return "Take item"; }
640 if (kind === EffectKind.startQuest)
641 { return "Start quest"; }
642 return kind;
643 }
644
645 function smallButton (label, disabled, onClick)
646 {
647 const button = document.createElement("button");
648 button.type = "button";
649 button.textContent = label;
650 button.disabled = disabled;
651 button.addEventListener("click", onClick);
652 return button;
653 }
654
655 function removeButton (onClick)
656 {
657 const remove = document.createElement("button");
658 remove.type = "button";
659 remove.className = "content-editor-remove";
660 remove.textContent = "×";
661 remove.title = "Remove";
662 remove.addEventListener("click", onClick);
663 return remove;
664 }
665
666 function field (label, input)
667 {
668 const wrap = document.createElement("label");
669 wrap.append(document.createTextNode(label), input);
670 return wrap;
671 }
672
673 function textInput (value, onChange, eventName = "input")
674 {
675 const input = document.createElement("input");
676 input.type = "text";
677 input.value = value ?? "";
678 input.addEventListener(eventName, () => onChange(input.value));
679 return input;
680 }
681
682 function textArea (value, onChange, rows = 3)
683 {
684 const input = document.createElement("textarea");
685 input.rows = rows;
686 input.value = value ?? "";
687 input.addEventListener("input", () => onChange(input.value));
688 return input;
689 }
690
691 function sectionHeader (titleText, onAdd, onRemove)
692 {
693 const head = document.createElement("div");
694 head.className = "content-editor-section-header";
695 const strong = document.createElement("strong");
696 strong.textContent = titleText;
697 head.append(strong);
698 const actions = document.createElement("div");
699 actions.className = "content-editor-row";
700 if (onAdd)
701 {
702 const add = document.createElement("button");
703 add.type = "button";
704 add.textContent = "+";
705 add.title = "Add";
706 add.addEventListener("click", onAdd);
707 actions.append(add);
708 }
709 if (onRemove)
710 { actions.append(removeButton(onRemove)); }
711 head.append(actions);
712 return head;
713 }
@@ -0,0 +1,713 @@
1/**
2 * Step panel for the quest graph editor.
3 * Wires stay on the canvas; this panel edits text, exit kind, objectives, and branches.
4 */
5import { emptyConditionSet, EffectKind } from "/shared/quests/conditions.js";
6import { relinkImplicitQuestExits } from "/shared/quests/normalize.js";
7import { blankQuestStep, branchShadowsLater } from "/shared/quests/questGraph.js";
8import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
9import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
10import { renderConditionSet } from "./conditionSetEditor.js";
11import { scrubDialogueStepLinks, stepHasEdges } from "./dialogueCanvas.js";
12
13/**
14 * @param {{
15 * getDraft: () => object | null,
16 * conditionCtx: () => object,
17 * onChange: () => void,
18 * host?: HTMLElement | null
19 * }} options
20 */
21export function initQuestStepModal ({
22 getDraft,
23 conditionCtx,
24 onChange,
25 host = null
26})
27{
28 const root = document.createElement("div");
29 root.className = "dialogue-step-overlay";
30 root.hidden = true;
31
32 const backdrop = document.createElement("div");
33 backdrop.className = "dialogue-step-backdrop";
34
35 const panel = document.createElement("div");
36 panel.className = "dialogue-step-panel quest-step-panel";
37
38 const header = document.createElement("header");
39 const title = document.createElement("h3");
40 title.textContent = "Step";
41 const closeBtn = document.createElement("button");
42 closeBtn.type = "button";
43 closeBtn.textContent = "Close";
44 header.append(title, closeBtn);
45
46 const body = document.createElement("div");
47 body.className = "dialogue-step-body";
48
49 root.append(backdrop, panel);
50 panel.append(header, body);
51 (host || document.body).append(root);
52
53 /** @type {string | null} */
54 let openStepId = null;
55
56 function show (visible)
57 {
58 root.hidden = !visible;
59 if (!visible)
60 {
61 openStepId = null;
62 body.replaceChildren();
63 }
64 }
65
66 function currentStep ()
67 {
68 const draft = getDraft();
69 if (!draft || !openStepId)
70 { return null; }
71 return draft.steps?.find((step) => step.stepId === openStepId) ?? null;
72 }
73
74 function uniqueStepId (draft, preferred)
75 {
76 const used = new Set((draft.steps ?? []).map((step) => step.stepId));
77 if (!used.has(preferred))
78 { return preferred; }
79 let n = (draft.steps?.length ?? 0) + 1;
80 let id = `step-${n}`;
81 while (used.has(id))
82 {
83 n += 1;
84 id = `step-${n}`;
85 }
86 return id;
87 }
88
89 function renameStep (step, nextId)
90 {
91 const draft = getDraft();
92 const previous = step.stepId;
93 if (!draft || !nextId || nextId === previous)
94 { return; }
95 if (draft.steps.some((other) => other !== step && other.stepId === nextId))
96 { return; }
97 for (const other of draft.steps)
98 {
99 const exit = other.exit;
100 if (!exit)
101 { continue; }
102 if (exit.kind === "continue" && exit.nextStepId === previous)
103 { exit.nextStepId = nextId; }
104 for (const branch of exit.branches ?? [])
105 {
106 if (branch.nextStepId === previous)
107 { branch.nextStepId = nextId; }
108 }
109 }
110 step.stepId = nextId;
111 openStepId = nextId;
112 onChange();
113 }
114
115 function setExitKind (step, kind)
116 {
117 const carried = step.exit?.kind === "continue"
118 ? (step.exit.nextStepId ?? null)
119 : (step.exit?.kind === "branches"
120 ? (step.exit.branches?.find((branch) => branch.nextStepId)?.nextStepId ?? null)
121 : null);
122 if (kind === "branches")
123 {
124 const existing = step.exit?.kind === "branches" ? (step.exit.branches ?? []) : [];
125 const branches = existing.length
126 ? existing
127 : [{
128 label: "",
129 text: "",
130 when: emptyConditionSet(),
131 nextStepId: carried,
132 effects: []
133 }];
134 step.exit = { kind: "branches", branches };
135 return;
136 }
137 if (kind === "continue")
138 {
139 const prev = step.exit?.kind === "continue"
140 ? (step.exit.nextStepId ?? null)
141 : carried;
142 step.exit = { kind: "continue", nextStepId: prev };
143 return;
144 }
145 step.exit = { kind: "complete" };
146 }
147
148 function deleteStep (step)
149 {
150 const draft = getDraft();
151 if (!draft)
152 { return; }
153 const removedId = step.stepId;
154 const index = draft.steps.indexOf(step);
155 if (index < 0)
156 { return; }
157 draft.steps.splice(index, 1);
158 scrubDialogueStepLinks(draft, removedId);
159 if (draft.steps.length === 0)
160 { draft.steps.push(blankQuestStep(uniqueStepId(draft, "step-1"), 80, 80)); }
161 else
162 { relinkImplicitQuestExits(draft.steps); }
163 show(false);
164 onChange();
165 }
166
167 function confirmDelete (step)
168 {
169 const draft = getDraft();
170 const linked = stepHasEdges(draft, step);
171 const message = linked
172 ? `Delete step "${step.title || step.stepId}"? Incoming and outgoing wires to it will be cleared.`
173 : `Delete step "${step.title || step.stepId}"?`;
174 if (!window.confirm(message))
175 { return; }
176 deleteStep(step);
177 }
178
179 function renderObjectives (step)
180 {
181 const head = sectionHeader("Objectives", () =>
182 {
183 step.objectives.push({
184 objectiveId: `obj-${step.objectives.length + 1}`,
185 text: "New objective",
186 when: emptyConditionSet()
187 });
188 onChange();
189 render();
190 });
191 body.append(head);
192 const note = document.createElement("p");
193 note.className = "content-editor-hint";
194 note.textContent = "All objectives must be done before this step advances.";
195 body.append(note);
196
197 step.objectives.forEach((obj, objIndex) =>
198 {
199 const objBox = document.createElement("div");
200 objBox.className = "content-editor-section";
201 objBox.append(
202 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
203 {
204 if (!window.confirm(`Delete objective "${obj.text || obj.objectiveId || objIndex + 1}"?`))
205 { return; }
206 step.objectives.splice(objIndex, 1);
207 if (step.objectives.length === 0)
208 {
209 step.objectives.push({
210 objectiveId: "obj-1",
211 text: "Complete this step",
212 when: emptyConditionSet()
213 });
214 }
215 onChange();
216 render();
217 }),
218 field("Text", textInput(obj.text, (value) =>
219 {
220 obj.text = value;
221 onChange();
222 }))
223 );
224 objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>
225 {
226 obj.when = next;
227 onChange();
228 if (remount)
229 { render(); }
230 }, conditionCtx()));
231 body.append(objBox);
232 });
233 }
234
235 function renderBranches (step)
236 {
237 if (!Array.isArray(step.exit.branches))
238 { step.exit.branches = []; }
239 const branches = step.exit.branches;
240 const head = sectionHeader("Branches", () =>
241 {
242 branches.push({
243 label: "",
244 text: "",
245 when: emptyConditionSet(),
246 nextStepId: null,
247 effects: []
248 });
249 onChange();
250 render();
251 });
252 body.append(head);
253 const note = document.createElement("p");
254 note.className = "content-editor-hint";
255 note.textContent = "First matching branch wins. The top of this list is checked first. Wire each branch from its port on the canvas. An empty next step completes the quest.";
256 body.append(note);
257
258 branches.forEach((branch, index) =>
259 {
260 const box = document.createElement("div");
261 box.className = "content-editor-section";
262 const titleText = document.createElement("span");
263 titleText.append(
264 Object.assign(document.createElement("span"), {
265 className: "quest-branch-order",
266 textContent: `${index + 1}. `
267 }),
268 document.createTextNode(branch.label?.trim() || branch.text?.trim() || "Branch")
269 );
270 const headerRow = document.createElement("div");
271 headerRow.className = "content-editor-section-header";
272 const strong = document.createElement("strong");
273 strong.append(titleText);
274 headerRow.append(strong);
275 const actions = document.createElement("div");
276 actions.className = "content-editor-row";
277 actions.append(
278 smallButton("Up", index === 0, () => moveBranch(branches, index, -1)),
279 smallButton("Down", index === branches.length - 1, () => moveBranch(branches, index, 1)),
280 removeButton(() =>
281 {
282 if (!window.confirm(`Delete branch ${index + 1}?`))
283 { return; }
284 branches.splice(index, 1);
285 onChange();
286 render();
287 })
288 );
289 headerRow.append(actions);
290 box.append(headerRow);
291
292 if (branchShadowsLater(branches, index))
293 {
294 const warn = document.createElement("p");
295 warn.className = "quest-branch-shadow-warn";
296 warn.textContent = "This condition is empty, so it always matches. Branches below it never run.";
297 box.append(warn);
298 }
299
300 box.append(
301 field("Label", textInput(branch.label ?? "", (value) =>
302 {
303 branch.label = value;
304 onChange();
305 })),
306 field("Log text", textArea(branch.text ?? "", (value) =>
307 {
308 branch.text = value;
309 onChange();
310 }, 2))
311 );
312 box.append(renderConditionSet(branch.when, (next, { remount = true } = {}) =>
313 {
314 branch.when = next;
315 onChange();
316 if (remount)
317 { render(); }
318 }, conditionCtx()));
319 box.append(renderEffects(branch));
320 body.append(box);
321 });
322
323 function moveBranch (list, index, delta)
324 {
325 const target = index + delta;
326 if (target < 0 || target >= list.length)
327 { return; }
328 const [row] = list.splice(index, 1);
329 list.splice(target, 0, row);
330 onChange();
331 render();
332 }
333 }
334
335 function renderEffects (branch)
336 {
337 if (!Array.isArray(branch.effects))
338 { branch.effects = []; }
339 const wrap = document.createElement("div");
340 wrap.append(sectionHeader("Effects", () =>
341 {
342 branch.effects.push(blankEffect(EffectKind.giveXp));
343 onChange();
344 render();
345 }));
346 if (!branch.effects.length)
347 {
348 const empty = document.createElement("p");
349 empty.className = "content-editor-hint";
350 empty.textContent = "No effects. They run when this branch is taken.";
351 wrap.append(empty);
352 return wrap;
353 }
354 branch.effects.forEach((effect, effectIndex) =>
355 {
356 const row = document.createElement("div");
357 row.className = "content-editor-section";
358 const kind = document.createElement("select");
359 for (const value of Object.values(EffectKind))
360 {
361 const opt = document.createElement("option");
362 opt.value = value;
363 opt.textContent = effectKindLabel(value);
364 if (effect.kind === value)
365 { opt.selected = true; }
366 kind.append(opt);
367 }
368 kind.addEventListener("change", () =>
369 {
370 branch.effects[effectIndex] = blankEffect(kind.value);
371 onChange();
372 render();
373 });
374 row.append(field("Effect", kind));
375 if (effect.kind === EffectKind.giveXp)
376 { row.append(xpFields(effect)); }
377 else if (effect.kind === EffectKind.giveItem || effect.kind === EffectKind.takeItem)
378 { row.append(itemFields(effect)); }
379 else if (effect.kind === EffectKind.startQuest)
380 { row.append(questFields(effect)); }
381 row.append(removeButton(() =>
382 {
383 branch.effects.splice(effectIndex, 1);
384 onChange();
385 render();
386 }));
387 wrap.append(row);
388 });
389 return wrap;
390
391 function xpFields (effect)
392 {
393 const line = document.createElement("div");
394 line.className = "content-editor-row";
395 const skill = document.createElement("select");
396 for (const skillId of ALL_SKILL_IDS)
397 {
398 const opt = document.createElement("option");
399 opt.value = skillId;
400 opt.textContent = SKILL_DEFINITIONS[skillId]?.displayName ?? skillId;
401 if (effect.skillId === skillId)
402 { opt.selected = true; }
403 skill.append(opt);
404 }
405 skill.addEventListener("change", () =>
406 {
407 effect.skillId = skill.value;
408 onChange();
409 });
410 const amount = document.createElement("input");
411 amount.type = "number";
412 amount.min = "1";
413 amount.step = "1";
414 amount.value = String(Math.max(1, effect.amount | 0 || 1));
415 amount.addEventListener("input", () =>
416 {
417 effect.amount = Math.max(1, Number(amount.value) || 1) | 0;
418 onChange();
419 });
420 line.append(skill, amount);
421 return line;
422 }
423
424 function itemFields (effect)
425 {
426 const line = document.createElement("div");
427 line.className = "content-editor-row";
428 const select = document.createElement("select");
429 for (const item of listAllItemPickerEntries())
430 {
431 const opt = document.createElement("option");
432 opt.value = String(item.itemId);
433 opt.textContent = item.displayName;
434 if (Number(effect.itemId) === item.itemId)
435 { opt.selected = true; }
436 select.append(opt);
437 }
438 if (effect.itemId && ![...select.options].some((opt) => opt.value === String(effect.itemId)))
439 {
440 const missing = document.createElement("option");
441 missing.value = String(effect.itemId);
442 missing.textContent = itemDefinition(effect.itemId)?.displayName ?? `Item ${effect.itemId}`;
443 missing.selected = true;
444 select.append(missing);
445 }
446 select.addEventListener("change", () =>
447 {
448 effect.itemId = Number(select.value) | 0;
449 onChange();
450 });
451 const qty = document.createElement("input");
452 qty.type = "number";
453 qty.min = "1";
454 qty.step = "1";
455 qty.value = String(Math.max(1, effect.quantity | 0 || 1));
456 qty.addEventListener("input", () =>
457 {
458 effect.quantity = Math.max(1, Number(qty.value) || 1) | 0;
459 onChange();
460 });
461 line.append(select, qty);
462 if (effect.kind === EffectKind.giveItem)
463 {
464 const bankLabel = document.createElement("label");
465 bankLabel.className = "quest-reward-bank";
466 const bankBox = document.createElement("input");
467 bankBox.type = "checkbox";
468 bankBox.checked = !!effect.toBank;
469 bankBox.addEventListener("change", () =>
470 {
471 effect.toBank = bankBox.checked;
472 onChange();
473 });
474 bankLabel.append(bankBox, document.createTextNode(" Bank"));
475 line.append(bankLabel);
476 }
477 return line;
478 }
479
480 function questFields (effect)
481 {
482 const select = document.createElement("select");
483 const quests = conditionCtx().quests ?? [];
484 const none = document.createElement("option");
485 none.value = "";
486 none.textContent = "Choose a quest";
487 select.append(none);
488 for (const quest of quests)
489 {
490 const opt = document.createElement("option");
491 opt.value = quest.questId;
492 opt.textContent = quest.title || quest.questId;
493 if (effect.questId === quest.questId)
494 { opt.selected = true; }
495 select.append(opt);
496 }
497 if (effect.questId && ![...select.options].some((opt) => opt.value === effect.questId))
498 {
499 const missing = document.createElement("option");
500 missing.value = effect.questId;
501 missing.textContent = effect.questId;
502 missing.selected = true;
503 select.append(missing);
504 }
505 select.addEventListener("change", () =>
506 {
507 effect.questId = select.value;
508 onChange();
509 });
510 return field("Quest", select);
511 }
512 }
513
514 function render ()
515 {
516 const step = currentStep();
517 body.replaceChildren();
518 if (!step)
519 {
520 show(false);
521 return;
522 }
523 title.textContent = step.title || step.stepId || "Step";
524 const stepIdInput = document.createElement("input");
525 stepIdInput.type = "text";
526 stepIdInput.value = step.stepId ?? "";
527 stepIdInput.addEventListener("change", () =>
528 {
529 const next = stepIdInput.value.trim();
530 const previous = step.stepId;
531 renameStep(step, next);
532 if (step.stepId === previous && next !== previous)
533 { stepIdInput.value = previous; }
534 });
535 body.append(
536 field("Step id", stepIdInput),
537 field("Title", textInput(step.title, (value) =>
538 {
539 step.title = value;
540 title.textContent = value || step.stepId;
541 onChange();
542 })),
543 field("Description", textArea(step.description, (value) =>
544 {
545 step.description = value;
546 onChange();
547 }, 2)),
548 field("Completion journal", textArea(step.completionJournalText, (value) =>
549 {
550 step.completionJournalText = value;
551 onChange();
552 }, 2))
553 );
554
555 const exitKind = document.createElement("select");
556 for (const option of [
557 { value: "continue", label: "Continue" },
558 { value: "branches", label: "Branches" },
559 { value: "complete", label: "Complete" }
560 ])
561 {
562 const opt = document.createElement("option");
563 opt.value = option.value;
564 opt.textContent = option.label;
565 if ((step.exit?.kind ?? "complete") === option.value)
566 { opt.selected = true; }
567 exitKind.append(opt);
568 }
569 exitKind.addEventListener("change", () =>
570 {
571 setExitKind(step, exitKind.value);
572 onChange();
573 render();
574 });
575 body.append(field("Exit", exitKind));
576
577 const exitNote = document.createElement("p");
578 exitNote.className = "content-editor-hint";
579 if (step.exit?.kind === "branches")
580 { exitNote.textContent = "Each branch has its own output port. A port with no wire completes the quest."; }
581 else if (step.exit?.kind === "continue")
582 { exitNote.textContent = "One output port. Wire it on the canvas. No wire completes the quest."; }
583 else
584 { exitNote.textContent = "Quest end. This card has no output port. Objectives still have to be finished first."; }
585 body.append(exitNote);
586
587 if (step.exit?.kind === "branches")
588 { renderBranches(step); }
589 else
590 { renderObjectives(step); }
591
592 const remove = document.createElement("button");
593 remove.type = "button";
594 remove.className = "content-editor-remove";
595 remove.textContent = "Delete step";
596 remove.addEventListener("click", () => confirmDelete(step));
597 body.append(remove);
598 }
599
600 closeBtn.addEventListener("click", () => show(false));
601 backdrop.addEventListener("click", () => show(false));
602
603 return {
604 open (stepId)
605 {
606 openStepId = stepId;
607 show(true);
608 render();
609 },
610 close: () => show(false),
611 isOpen: () => !!openStepId && !root.hidden,
612 refresh ()
613 {
614 if (openStepId)
615 { render(); }
616 }
617 };
618}
619
620function blankEffect (kind)
621{
622 const item = listAllItemPickerEntries()[0];
623 if (kind === EffectKind.giveItem)
624 { return { kind, itemId: item?.itemId ?? 1, quantity: 1, toBank: false }; }
625 if (kind === EffectKind.takeItem)
626 { return { kind, itemId: item?.itemId ?? 1, quantity: 1 }; }
627 if (kind === EffectKind.startQuest)
628 { return { kind, questId: "" }; }
629 return { kind: EffectKind.giveXp, skillId: ALL_SKILL_IDS[0], amount: 10 };
630}
631
632function effectKindLabel (kind)
633{
634 if (kind === EffectKind.giveXp)
635 { return "Give XP"; }
636 if (kind === EffectKind.giveItem)
637 { return "Give item"; }
638 if (kind === EffectKind.takeItem)
639 { return "Take item"; }
640 if (kind === EffectKind.startQuest)
641 { return "Start quest"; }
642 return kind;
643}
644
645function smallButton (label, disabled, onClick)
646{
647 const button = document.createElement("button");
648 button.type = "button";
649 button.textContent = label;
650 button.disabled = disabled;
651 button.addEventListener("click", onClick);
652 return button;
653}
654
655function removeButton (onClick)
656{
657 const remove = document.createElement("button");
658 remove.type = "button";
659 remove.className = "content-editor-remove";
660 remove.textContent = "×";
661 remove.title = "Remove";
662 remove.addEventListener("click", onClick);
663 return remove;
664}
665
666function field (label, input)
667{
668 const wrap = document.createElement("label");
669 wrap.append(document.createTextNode(label), input);
670 return wrap;
671}
672
673function textInput (value, onChange, eventName = "input")
674{
675 const input = document.createElement("input");
676 input.type = "text";
677 input.value = value ?? "";
678 input.addEventListener(eventName, () => onChange(input.value));
679 return input;
680}
681
682function textArea (value, onChange, rows = 3)
683{
684 const input = document.createElement("textarea");
685 input.rows = rows;
686 input.value = value ?? "";
687 input.addEventListener("input", () => onChange(input.value));
688 return input;
689}
690
691function sectionHeader (titleText, onAdd, onRemove)
692{
693 const head = document.createElement("div");
694 head.className = "content-editor-section-header";
695 const strong = document.createElement("strong");
696 strong.textContent = titleText;
697 head.append(strong);
698 const actions = document.createElement("div");
699 actions.className = "content-editor-row";
700 if (onAdd)
701 {
702 const add = document.createElement("button");
703 add.type = "button";
704 add.textContent = "+";
705 add.title = "Add";
706 add.addEventListener("click", onAdd);
707 actions.append(add);
708 }
709 if (onRemove)
710 { actions.append(removeButton(onRemove)); }
711 head.append(actions);
712 return head;
713}
client/src/editor/questsModal.js +195 −123
@@ -1,6 +1,13 @@
1 1 import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
2 import { emptyConditionSet, EffectKind, normalizeEffects } from "/shared/quests/conditions.js";
3 import { renderConditionSet } from "./conditionSetEditor.js";
2 import { EffectKind, normalizeEffects } from "/shared/quests/conditions.js";
3 import {
4 blankQuestStep,
5 layoutQuestSteps,
6 prepareQuestExitsForSave,
7 questCanvasPorts
8 } from "/shared/quests/questGraph.js";
9 import { createDialogueCanvas } from "./dialogueCanvas.js";
10 import { initQuestStepModal } from "./questStepModal.js";
4 11 import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
5 12 import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
6 13
@@ -32,12 +39,136 @@ export function initQuestsModal ({
32 39 let selectedId = null;
33 40 /** @type {object[]} */
34 41 let changelog = [];
42 /** JSON snapshot of the last loaded quest. null = never saved (new). */
43 let draftBaseline = null;
44
45 function conditionCtx ()
46 {
47 return {
48 quests,
49 dialogues,
50 describeWorldTile,
51 centerEditorOnTile,
52 getDimensionOptions,
53 getSpawnerOptions: (mobTypeId) =>
54 {
55 if (typeof getSpawnerOptions === "function")
56 { return getSpawnerOptions(mobTypeId) ?? []; }
57 return serverSpawners.filter((row) => !mobTypeId || String(row.mobTypeId) === String(mobTypeId));
58 }
59 };
60 }
61
62 const stepModal = initQuestStepModal({
63 getDraft: () => draft,
64 conditionCtx,
65 onChange ()
66 {
67 noteChange();
68 canvas?.refresh();
69 },
70 host: modal
71 });
72
73 const canvas = createDialogueCanvas({
74 getDraft: () => draft,
75 getPorts: questCanvasPorts,
76 cardLabel: (step) => step.title || step.stepId,
77 cardMeta (step, isEntry)
78 {
79 const kind = step.exit?.kind === "complete" ? "quest end" : (step.exit?.kind ?? "continue");
80 return isEntry ? `start · ${kind}` : kind;
81 },
82 isEntryStep: (tree, step) => tree?.steps?.[0] === step,
83 stepPosition (step)
84 {
85 const laid = layoutQuestSteps(draft?.steps ?? []);
86 return laid.get(step.stepId) ?? null;
87 },
88 cardFlags: (step) => ({ "is-quest-end": step.exit?.kind === "complete" }),
89 createStepLabel: "Create new step",
90 onOpenStep (stepId)
91 {
92 stepModal.open(stepId);
93 },
94 onCreateStep (worldX, worldY)
95 {
96 if (!draft)
97 { return; }
98 const stepId = uniqueStepId(draft);
99 draft.steps.push(blankQuestStep(stepId, worldX, worldY));
100 noteChange();
101 canvas.refresh();
102 stepModal.open(stepId);
103 },
104 onChange ()
105 {
106 noteChange();
107 stepModal.refresh();
108 }
109 });
110
111 function uniqueStepId (tree)
112 {
113 const used = new Set((tree.steps ?? []).map((step) => step.stepId));
114 let n = (tree.steps?.length ?? 0) + 1;
115 let id = `step-${n}`;
116 while (used.has(id))
117 {
118 n += 1;
119 id = `step-${n}`;
120 }
121 return id;
122 }
123
124 function persistableSnapshot (quest)
125 {
126 if (!quest)
127 { return null; }
128 return JSON.stringify(quest);
129 }
130
131 function captureBaseline ()
132 {
133 draftBaseline = draft ? persistableSnapshot(draft) : null;
134 syncSaveButton();
135 }
136
137 function isDraftDirty ()
138 {
139 if (!draft)
140 { return false; }
141 if (draftBaseline == null)
142 { return true; }
143 return persistableSnapshot(draft) !== draftBaseline;
144 }
145
146 function noteChange ()
147 {
148 syncSaveButton();
149 }
150
151 function syncSaveButton ()
152 {
153 const dirty = isDraftDirty();
154 saveBtn.disabled = !draft || !dirty;
155 saveBtn.classList.toggle("save-dirty", !!draft && dirty);
156 }
157
158 function confirmDiscard ()
159 {
160 if (!isDraftDirty())
161 { return true; }
162 return window.confirm("Discard unsaved quest changes?");
163 }
35 164
36 165 /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
37 166 let itemPickContext = null;
38 167
39 168 function show (visible)
40 169 {
170 if (!visible && !confirmDiscard())
171 { return; }
41 172 open = visible;
42 173 backdrop.hidden = !visible;
43 174 modal.hidden = !visible;
@@ -45,7 +176,11 @@ export function initQuestsModal ({
45 176 {
46 177 draft = null;
47 178 selectedId = null;
179 draftBaseline = null;
180 stepModal.close();
181 canvas.clearWiring();
48 182 closeInlineItemSearch();
183 syncSaveButton();
49 184 }
50 185 }
51 186
@@ -123,16 +258,25 @@ export function initQuestsModal ({
123 258
124 259 function selectQuest (questId)
125 260 {
261 if (questId === selectedId && draft)
262 { return; }
263 if (!confirmDiscard())
264 { return; }
126 265 const found = quests.find((q) => q.questId === questId);
127 266 if (!found)
128 267 {
129 268 draft = null;
130 269 selectedId = null;
270 draftBaseline = null;
271 stepModal.close();
131 272 render();
132 273 return;
133 274 }
134 275 selectedId = found.questId;
135 276 draft = structuredClone(found);
277 captureBaseline();
278 stepModal.close();
279 canvas.clearWiring();
136 280 render();
137 281 }
138 282
@@ -151,28 +295,11 @@ export function initQuestsModal ({
151 295 }
152 296 }
153 297
154 function addStep ()
155 {
156 draft.steps.push({
157 stepId: `step-${draft.steps.length + 1}`,
158 title: "New step",
159 description: "",
160 completionJournalText: "",
161 objectives: [{
162 objectiveId: "obj-1",
163 text: "Complete this step",
164 when: emptyConditionSet()
165 }],
166 onEnter: [],
167 onComplete: []
168 });
169 renderEditor();
170 }
171
172 298 function renderEditor ()
173 299 {
174 300 editorEl.replaceChildren();
175 saveBtn.disabled = !draft;
301 editorEl.classList.toggle("dialogues-editor-canvas-host", !!draft);
302 syncSaveButton();
176 303 deleteBtn.disabled = !draft;
177 304 if (!draft)
178 305 {
@@ -186,114 +313,45 @@ export function initQuestsModal ({
186 313 if (!Array.isArray(draft.rewards))
187 314 { draft.rewards = []; }
188 315
189 editorEl.append(
190 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
191 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
192 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
193 );
194
195 const stepsTitle = document.createElement("div");
196 stepsTitle.className = "content-editor-section-header";
197 const stepsStrong = document.createElement("strong");
198 stepsStrong.textContent = "Steps";
199 stepsTitle.append(stepsStrong);
200 editorEl.append(stepsTitle);
201
202 draft.steps.forEach((step, stepIndex) =>
203 {
204 const box = document.createElement("div");
205 box.className = "content-editor-section";
206 const head = sectionHeader(`Step ${stepIndex + 1}`, null, () =>
316 const meta = document.createElement("div");
317 meta.className = "dialogue-editor-meta";
318 meta.append(
319 field("Quest id", textInput(draft.questId, (value) =>
207 320 {
208 if (!window.confirm(`Delete quest step "${step.stepId || stepIndex + 1}"?`))
209 { return; }
210 draft.steps.splice(stepIndex, 1);
211 if (draft.steps.length === 0)
212 {
213 draft.steps.push(normalizeQuestDef({ questId: draft.questId }).steps[0]);
214 }
215 renderEditor();
216 });
217 box.append(head);
218 box.append(
219 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
220 field("Title", textInput(step.title, (v) => { step.title = v; })),
221 field("Description", textArea(step.description, (v) => { step.description = v; }, 2)),
222 field("Completion journal", textArea(step.completionJournalText, (v) =>
223 {
224 step.completionJournalText = v;
225 }, 2))
226 );
227
228 const objHead = sectionHeader("Objectives", () =>
229 {
230 step.objectives.push({
231 objectiveId: `obj-${step.objectives.length + 1}`,
232 text: "New objective",
233 when: emptyConditionSet()
234 });
235 renderEditor();
236 });
237 box.append(objHead);
238
239 step.objectives.forEach((obj, objIndex) =>
321 draft.questId = value;
322 noteChange();
323 })),
324 field("Title", textInput(draft.title, (value) =>
240 325 {
241 const objBox = document.createElement("div");
242 objBox.className = "content-editor-section";
243 objBox.append(
244 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
245 {
246 if (!window.confirm(`Delete objective "${obj.text || obj.objectiveId || objIndex + 1}"?`))
247 { return; }
248 step.objectives.splice(objIndex, 1);
249 if (step.objectives.length === 0)
250 {
251 step.objectives.push({
252 objectiveId: "obj-1",
253 text: "Complete this step",
254 when: emptyConditionSet()
255 });
256 }
257 renderEditor();
258 }),
259 field("Text", textInput(obj.text, (v) => { obj.text = v; }))
260 );
261 objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>
262 {
263 obj.when = next;
264 if (remount)
265 { renderEditor(); }
266 }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions, getSpawnerOptions: (mobTypeId) =>
326 draft.title = value;
327 noteChange();
328 })),
329 field("Description", textArea(draft.description, (value) =>
267 330 {
268 if (typeof getSpawnerOptions === "function")
269 { return getSpawnerOptions(mobTypeId) ?? []; }
270 return serverSpawners.filter((row) => !mobTypeId || String(row.mobTypeId) === String(mobTypeId));
271 } }));
272 box.append(objBox);
273 });
274 editorEl.append(box);
275 });
276
277 const addStepBtn = document.createElement("button");
278 addStepBtn.type = "button";
279 addStepBtn.className = "content-editor-add-step";
280 addStepBtn.textContent = "(add step)";
281 addStepBtn.addEventListener("click", addStep);
282 editorEl.append(addStepBtn);
283
284 renderRewardsSection();
331 draft.description = value;
332 noteChange();
333 }, 3))
334 );
335 const canvasHint = document.createElement("p");
336 canvasHint.className = "content-editor-hint dialogue-canvas-help";
337 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. The first card is the start. A quest-end card has no output.";
338 meta.append(canvasHint);
339 const rewards = document.createElement("details");
340 rewards.className = "quest-rewards-drawer";
341 rewards.open = true;
342 const summary = document.createElement("summary");
343 summary.textContent = "Completion rewards";
344 rewards.append(summary);
345 editorEl.append(meta, rewards);
346 renderRewardsSection(rewards);
347 editorEl.append(canvas.el);
348 canvas.refresh();
285 349 }
286 350
287 function renderRewardsSection ()
351 function renderRewardsSection (parent = editorEl)
288 352 {
289 353 const box = document.createElement("div");
290 354 box.className = "content-editor-section";
291 const title = document.createElement("div");
292 title.className = "content-editor-section-header";
293 const strong = document.createElement("strong");
294 strong.textContent = "Completion rewards";
295 title.append(strong);
296 box.append(title);
297 355
298 356 const hint = document.createElement("p");
299 357 hint.className = "content-editor-hint";
@@ -337,6 +395,7 @@ export function initQuestsModal ({
337 395 skill.addEventListener("change", () =>
338 396 {
339 397 draft.rewards[rewardIndex].skillId = skill.value;
398 noteChange();
340 399 });
341 400 const amount = document.createElement("input");
342 401 amount.type = "number";
@@ -347,6 +406,7 @@ export function initQuestsModal ({
347 406 amount.addEventListener("input", () =>
348 407 {
349 408 draft.rewards[rewardIndex].amount = Math.max(1, Number(amount.value) || 1) | 0;
409 noteChange();
350 410 });
351 411 row.append(skill, amount, removeButton(() =>
352 412 {
@@ -401,6 +461,7 @@ export function initQuestsModal ({
401 461 qty.addEventListener("input", () =>
402 462 {
403 463 draft.rewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
464 noteChange();
404 465 });
405 466 const bankLabel = document.createElement("label");
406 467 bankLabel.className = "quest-reward-bank";
@@ -410,6 +471,7 @@ export function initQuestsModal ({
410 471 bankBox.addEventListener("change", () =>
411 472 {
412 473 draft.rewards[rewardIndex].toBank = bankBox.checked;
474 noteChange();
413 475 });
414 476 bankLabel.append(bankBox, document.createTextNode(" Bank"));
415 477 row.append(name, qty, bankLabel, removeButton(() =>
@@ -420,7 +482,7 @@ export function initQuestsModal ({
420 482 box.append(row);
421 483 });
422 484 box.append(searchWrap);
423 editorEl.append(box);
485 parent.append(box);
424 486 }
425 487
426 488 function render ()
@@ -476,6 +538,8 @@ export function initQuestsModal ({
476 538 backdrop.addEventListener("click", () => show(false));
477 539 document.getElementById("quests-new").addEventListener("click", () =>
478 540 {
541 if (!confirmDiscard())
542 { return; }
479 543 const base = normalizeQuestDef({
480 544 questId: `quest-${quests.length + 1}`,
481 545 title: "New quest",
@@ -483,13 +547,17 @@ export function initQuestsModal ({
483 547 });
484 548 draft = structuredClone(base);
485 549 selectedId = null;
550 draftBaseline = null;
551 stepModal.close();
552 canvas.clearWiring();
486 553 render();
487 554 });
488 555 saveBtn.addEventListener("click", () =>
489 556 {
490 if (!draft)
557 if (!draft || !isDraftDirty())
491 558 { return; }
492 559 draft.rewards = normalizeEffects(draft.rewards);
560 prepareQuestExitsForSave(draft.steps);
493 561 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
494 562 });
495 563 deleteBtn.addEventListener("click", () =>
@@ -526,11 +594,15 @@ export function initQuestsModal ({
526 594 {
527 595 selectedId = still.questId;
528 596 draft = structuredClone(still);
597 captureBaseline();
598 stepModal.refresh();
529 599 }
530 600 else if (selectedId)
531 601 {
532 602 draft = null;
533 603 selectedId = null;
604 draftBaseline = null;
605 stepModal.close();
534 606 }
535 607 }
536 608 if (open)
@@ -1,6 +1,13 @@
1import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
1import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
2import { emptyConditionSet, EffectKind, normalizeEffects } from "/shared/quests/conditions.js";
2import { EffectKind, normalizeEffects } from "/shared/quests/conditions.js";
3import { renderConditionSet } from "./conditionSetEditor.js";
3import {
4 blankQuestStep,
5 layoutQuestSteps,
6 prepareQuestExitsForSave,
7 questCanvasPorts
8} from "/shared/quests/questGraph.js";
9import { createDialogueCanvas } from "./dialogueCanvas.js";
10import { initQuestStepModal } from "./questStepModal.js";
4import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
11import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
5import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
12import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
6
13
@@ -32,12 +39,136 @@ export function initQuestsModal ({
32 let selectedId = null;
39 let selectedId = null;
33 /** @type {object[]} */
40 /** @type {object[]} */
34 let changelog = [];
41 let changelog = [];
42 /** JSON snapshot of the last loaded quest. null = never saved (new). */
43 let draftBaseline = null;
44
45 function conditionCtx ()
46 {
47 return {
48 quests,
49 dialogues,
50 describeWorldTile,
51 centerEditorOnTile,
52 getDimensionOptions,
53 getSpawnerOptions: (mobTypeId) =>
54 {
55 if (typeof getSpawnerOptions === "function")
56 { return getSpawnerOptions(mobTypeId) ?? []; }
57 return serverSpawners.filter((row) => !mobTypeId || String(row.mobTypeId) === String(mobTypeId));
58 }
59 };
60 }
61
62 const stepModal = initQuestStepModal({
63 getDraft: () => draft,
64 conditionCtx,
65 onChange ()
66 {
67 noteChange();
68 canvas?.refresh();
69 },
70 host: modal
71 });
72
73 const canvas = createDialogueCanvas({
74 getDraft: () => draft,
75 getPorts: questCanvasPorts,
76 cardLabel: (step) => step.title || step.stepId,
77 cardMeta (step, isEntry)
78 {
79 const kind = step.exit?.kind === "complete" ? "quest end" : (step.exit?.kind ?? "continue");
80 return isEntry ? `start · ${kind}` : kind;
81 },
82 isEntryStep: (tree, step) => tree?.steps?.[0] === step,
83 stepPosition (step)
84 {
85 const laid = layoutQuestSteps(draft?.steps ?? []);
86 return laid.get(step.stepId) ?? null;
87 },
88 cardFlags: (step) => ({ "is-quest-end": step.exit?.kind === "complete" }),
89 createStepLabel: "Create new step",
90 onOpenStep (stepId)
91 {
92 stepModal.open(stepId);
93 },
94 onCreateStep (worldX, worldY)
95 {
96 if (!draft)
97 { return; }
98 const stepId = uniqueStepId(draft);
99 draft.steps.push(blankQuestStep(stepId, worldX, worldY));
100 noteChange();
101 canvas.refresh();
102 stepModal.open(stepId);
103 },
104 onChange ()
105 {
106 noteChange();
107 stepModal.refresh();
108 }
109 });
110
111 function uniqueStepId (tree)
112 {
113 const used = new Set((tree.steps ?? []).map((step) => step.stepId));
114 let n = (tree.steps?.length ?? 0) + 1;
115 let id = `step-${n}`;
116 while (used.has(id))
117 {
118 n += 1;
119 id = `step-${n}`;
120 }
121 return id;
122 }
123
124 function persistableSnapshot (quest)
125 {
126 if (!quest)
127 { return null; }
128 return JSON.stringify(quest);
129 }
130
131 function captureBaseline ()
132 {
133 draftBaseline = draft ? persistableSnapshot(draft) : null;
134 syncSaveButton();
135 }
136
137 function isDraftDirty ()
138 {
139 if (!draft)
140 { return false; }
141 if (draftBaseline == null)
142 { return true; }
143 return persistableSnapshot(draft) !== draftBaseline;
144 }
145
146 function noteChange ()
147 {
148 syncSaveButton();
149 }
150
151 function syncSaveButton ()
152 {
153 const dirty = isDraftDirty();
154 saveBtn.disabled = !draft || !dirty;
155 saveBtn.classList.toggle("save-dirty", !!draft && dirty);
156 }
157
158 function confirmDiscard ()
159 {
160 if (!isDraftDirty())
161 { return true; }
162 return window.confirm("Discard unsaved quest changes?");
163 }
35
164
36 /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
165 /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
37 let itemPickContext = null;
166 let itemPickContext = null;
38
167
39 function show (visible)
168 function show (visible)
40 {
169 {
170 if (!visible && !confirmDiscard())
171 { return; }
41 open = visible;
172 open = visible;
42 backdrop.hidden = !visible;
173 backdrop.hidden = !visible;
43 modal.hidden = !visible;
174 modal.hidden = !visible;
@@ -45,7 +176,11 @@ export function initQuestsModal ({
45 {
176 {
46 draft = null;
177 draft = null;
47 selectedId = null;
178 selectedId = null;
179 draftBaseline = null;
180 stepModal.close();
181 canvas.clearWiring();
48 closeInlineItemSearch();
182 closeInlineItemSearch();
183 syncSaveButton();
49 }
184 }
50 }
185 }
51
186
@@ -123,16 +258,25 @@ export function initQuestsModal ({
123
258
124 function selectQuest (questId)
259 function selectQuest (questId)
125 {
260 {
261 if (questId === selectedId && draft)
262 { return; }
263 if (!confirmDiscard())
264 { return; }
126 const found = quests.find((q) => q.questId === questId);
265 const found = quests.find((q) => q.questId === questId);
127 if (!found)
266 if (!found)
128 {
267 {
129 draft = null;
268 draft = null;
130 selectedId = null;
269 selectedId = null;
270 draftBaseline = null;
271 stepModal.close();
131 render();
272 render();
132 return;
273 return;
133 }
274 }
134 selectedId = found.questId;
275 selectedId = found.questId;
135 draft = structuredClone(found);
276 draft = structuredClone(found);
277 captureBaseline();
278 stepModal.close();
279 canvas.clearWiring();
136 render();
280 render();
137 }
281 }
138
282
@@ -151,28 +295,11 @@ export function initQuestsModal ({
151 }
295 }
152 }
296 }
153
297
154 function addStep ()
155 {
156 draft.steps.push({
157 stepId: `step-${draft.steps.length + 1}`,
158 title: "New step",
159 description: "",
160 completionJournalText: "",
161 objectives: [{
162 objectiveId: "obj-1",
163 text: "Complete this step",
164 when: emptyConditionSet()
165 }],
166 onEnter: [],
167 onComplete: []
168 });
169 renderEditor();
170 }
171
172 function renderEditor ()
298 function renderEditor ()
173 {
299 {
174 editorEl.replaceChildren();
300 editorEl.replaceChildren();
175 saveBtn.disabled = !draft;
301 editorEl.classList.toggle("dialogues-editor-canvas-host", !!draft);
302 syncSaveButton();
176 deleteBtn.disabled = !draft;
303 deleteBtn.disabled = !draft;
177 if (!draft)
304 if (!draft)
178 {
305 {
@@ -186,114 +313,45 @@ export function initQuestsModal ({
186 if (!Array.isArray(draft.rewards))
313 if (!Array.isArray(draft.rewards))
187 { draft.rewards = []; }
314 { draft.rewards = []; }
188
315
189 editorEl.append(
316 const meta = document.createElement("div");
190 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
317 meta.className = "dialogue-editor-meta";
191 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
318 meta.append(
192 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
319 field("Quest id", textInput(draft.questId, (value) =>
193 );
194
195 const stepsTitle = document.createElement("div");
196 stepsTitle.className = "content-editor-section-header";
197 const stepsStrong = document.createElement("strong");
198 stepsStrong.textContent = "Steps";
199 stepsTitle.append(stepsStrong);
200 editorEl.append(stepsTitle);
201
202 draft.steps.forEach((step, stepIndex) =>
203 {
204 const box = document.createElement("div");
205 box.className = "content-editor-section";
206 const head = sectionHeader(`Step ${stepIndex + 1}`, null, () =>
207 {
320 {
208 if (!window.confirm(`Delete quest step "${step.stepId || stepIndex + 1}"?`))
321 draft.questId = value;
209 { return; }
322 noteChange();
210 draft.steps.splice(stepIndex, 1);
323 })),
211 if (draft.steps.length === 0)
324 field("Title", textInput(draft.title, (value) =>
212 {
213 draft.steps.push(normalizeQuestDef({ questId: draft.questId }).steps[0]);
214 }
215 renderEditor();
216 });
217 box.append(head);
218 box.append(
219 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
220 field("Title", textInput(step.title, (v) => { step.title = v; })),
221 field("Description", textArea(step.description, (v) => { step.description = v; }, 2)),
222 field("Completion journal", textArea(step.completionJournalText, (v) =>
223 {
224 step.completionJournalText = v;
225 }, 2))
226 );
227
228 const objHead = sectionHeader("Objectives", () =>
229 {
230 step.objectives.push({
231 objectiveId: `obj-${step.objectives.length + 1}`,
232 text: "New objective",
233 when: emptyConditionSet()
234 });
235 renderEditor();
236 });
237 box.append(objHead);
238
239 step.objectives.forEach((obj, objIndex) =>
240 {
325 {
241 const objBox = document.createElement("div");
326 draft.title = value;
242 objBox.className = "content-editor-section";
327 noteChange();
243 objBox.append(
328 })),
244 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
329 field("Description", textArea(draft.description, (value) =>
245 {
246 if (!window.confirm(`Delete objective "${obj.text || obj.objectiveId || objIndex + 1}"?`))
247 { return; }
248 step.objectives.splice(objIndex, 1);
249 if (step.objectives.length === 0)
250 {
251 step.objectives.push({
252 objectiveId: "obj-1",
253 text: "Complete this step",
254 when: emptyConditionSet()
255 });
256 }
257 renderEditor();
258 }),
259 field("Text", textInput(obj.text, (v) => { obj.text = v; }))
260 );
261 objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>
262 {
263 obj.when = next;
264 if (remount)
265 { renderEditor(); }
266 }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions, getSpawnerOptions: (mobTypeId) =>
267 {
330 {
268 if (typeof getSpawnerOptions === "function")
331 draft.description = value;
269 { return getSpawnerOptions(mobTypeId) ?? []; }
332 noteChange();
270 return serverSpawners.filter((row) => !mobTypeId || String(row.mobTypeId) === String(mobTypeId));
333 }, 3))
271 } }));
334 );
272 box.append(objBox);
335 const canvasHint = document.createElement("p");
273 });
336 canvasHint.className = "content-editor-hint dialogue-canvas-help";
274 editorEl.append(box);
337 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. The first card is the start. A quest-end card has no output.";
275 });
338 meta.append(canvasHint);
276
339 const rewards = document.createElement("details");
277 const addStepBtn = document.createElement("button");
340 rewards.className = "quest-rewards-drawer";
278 addStepBtn.type = "button";
341 rewards.open = true;
279 addStepBtn.className = "content-editor-add-step";
342 const summary = document.createElement("summary");
280 addStepBtn.textContent = "(add step)";
343 summary.textContent = "Completion rewards";
281 addStepBtn.addEventListener("click", addStep);
344 rewards.append(summary);
282 editorEl.append(addStepBtn);
345 editorEl.append(meta, rewards);
283
346 renderRewardsSection(rewards);
284 renderRewardsSection();
347 editorEl.append(canvas.el);
348 canvas.refresh();
285 }
349 }
286
350
287 function renderRewardsSection ()
351 function renderRewardsSection (parent = editorEl)
288 {
352 {
289 const box = document.createElement("div");
353 const box = document.createElement("div");
290 box.className = "content-editor-section";
354 box.className = "content-editor-section";
291 const title = document.createElement("div");
292 title.className = "content-editor-section-header";
293 const strong = document.createElement("strong");
294 strong.textContent = "Completion rewards";
295 title.append(strong);
296 box.append(title);
297
355
298 const hint = document.createElement("p");
356 const hint = document.createElement("p");
299 hint.className = "content-editor-hint";
357 hint.className = "content-editor-hint";
@@ -337,6 +395,7 @@ export function initQuestsModal ({
337 skill.addEventListener("change", () =>
395 skill.addEventListener("change", () =>
338 {
396 {
339 draft.rewards[rewardIndex].skillId = skill.value;
397 draft.rewards[rewardIndex].skillId = skill.value;
398 noteChange();
340 });
399 });
341 const amount = document.createElement("input");
400 const amount = document.createElement("input");
342 amount.type = "number";
401 amount.type = "number";
@@ -347,6 +406,7 @@ export function initQuestsModal ({
347 amount.addEventListener("input", () =>
406 amount.addEventListener("input", () =>
348 {
407 {
349 draft.rewards[rewardIndex].amount = Math.max(1, Number(amount.value) || 1) | 0;
408 draft.rewards[rewardIndex].amount = Math.max(1, Number(amount.value) || 1) | 0;
409 noteChange();
350 });
410 });
351 row.append(skill, amount, removeButton(() =>
411 row.append(skill, amount, removeButton(() =>
352 {
412 {
@@ -401,6 +461,7 @@ export function initQuestsModal ({
401 qty.addEventListener("input", () =>
461 qty.addEventListener("input", () =>
402 {
462 {
403 draft.rewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
463 draft.rewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
464 noteChange();
404 });
465 });
405 const bankLabel = document.createElement("label");
466 const bankLabel = document.createElement("label");
406 bankLabel.className = "quest-reward-bank";
467 bankLabel.className = "quest-reward-bank";
@@ -410,6 +471,7 @@ export function initQuestsModal ({
410 bankBox.addEventListener("change", () =>
471 bankBox.addEventListener("change", () =>
411 {
472 {
412 draft.rewards[rewardIndex].toBank = bankBox.checked;
473 draft.rewards[rewardIndex].toBank = bankBox.checked;
474 noteChange();
413 });
475 });
414 bankLabel.append(bankBox, document.createTextNode(" Bank"));
476 bankLabel.append(bankBox, document.createTextNode(" Bank"));
415 row.append(name, qty, bankLabel, removeButton(() =>
477 row.append(name, qty, bankLabel, removeButton(() =>
@@ -420,7 +482,7 @@ export function initQuestsModal ({
420 box.append(row);
482 box.append(row);
421 });
483 });
422 box.append(searchWrap);
484 box.append(searchWrap);
423 editorEl.append(box);
485 parent.append(box);
424 }
486 }
425
487
426 function render ()
488 function render ()
@@ -476,6 +538,8 @@ export function initQuestsModal ({
476 backdrop.addEventListener("click", () => show(false));
538 backdrop.addEventListener("click", () => show(false));
477 document.getElementById("quests-new").addEventListener("click", () =>
539 document.getElementById("quests-new").addEventListener("click", () =>
478 {
540 {
541 if (!confirmDiscard())
542 { return; }
479 const base = normalizeQuestDef({
543 const base = normalizeQuestDef({
480 questId: `quest-${quests.length + 1}`,
544 questId: `quest-${quests.length + 1}`,
481 title: "New quest",
545 title: "New quest",
@@ -483,13 +547,17 @@ export function initQuestsModal ({
483 });
547 });
484 draft = structuredClone(base);
548 draft = structuredClone(base);
485 selectedId = null;
549 selectedId = null;
550 draftBaseline = null;
551 stepModal.close();
552 canvas.clearWiring();
486 render();
553 render();
487 });
554 });
488 saveBtn.addEventListener("click", () =>
555 saveBtn.addEventListener("click", () =>
489 {
556 {
490 if (!draft)
557 if (!draft || !isDraftDirty())
491 { return; }
558 { return; }
492 draft.rewards = normalizeEffects(draft.rewards);
559 draft.rewards = normalizeEffects(draft.rewards);
560 prepareQuestExitsForSave(draft.steps);
493 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
561 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
494 });
562 });
495 deleteBtn.addEventListener("click", () =>
563 deleteBtn.addEventListener("click", () =>
@@ -526,11 +594,15 @@ export function initQuestsModal ({
526 {
594 {
527 selectedId = still.questId;
595 selectedId = still.questId;
528 draft = structuredClone(still);
596 draft = structuredClone(still);
597 captureBaseline();
598 stepModal.refresh();
529 }
599 }
530 else if (selectedId)
600 else if (selectedId)
531 {
601 {
532 draft = null;
602 draft = null;
533 selectedId = null;
603 selectedId = null;
604 draftBaseline = null;
605 stepModal.close();
534 }
606 }
535 }
607 }
536 if (open)
608 if (open)
client/ui/editor.css +47 −2
@@ -512,7 +512,8 @@ button:disabled {
512 512 }
513 513
514 514 #save.save-dirty:not(:disabled),
515 #dialogues-save.save-dirty:not(:disabled) {
515 #dialogues-save.save-dirty:not(:disabled),
516 #quests-save.save-dirty:not(:disabled) {
516 517 animation: save-pulse 1.1s ease-in-out infinite;
517 518 border-color: #c9a227;
518 519 box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);
@@ -2199,7 +2200,8 @@ label {
2199 2200 }
2200 2201
2201 2202 /* Dialogue canvas graph editor */
2202 #dialogues-editor.dialogues-editor-canvas-host {
2203 #dialogues-editor.dialogues-editor-canvas-host,
2204 #quests-editor.dialogues-editor-canvas-host {
2203 2205 display: flex;
2204 2206 flex-direction: column;
2205 2207 overflow: hidden;
@@ -2241,6 +2243,21 @@ label {
2241 2243 margin: 0.35rem 0 0.15rem;
2242 2244 }
2243 2245
2246 .quest-rewards-drawer {
2247 flex-shrink: 0;
2248 max-height: 30%;
2249 overflow: auto;
2250 padding: 0.35rem 1rem 0.55rem;
2251 border-bottom: 1px solid #2c3340;
2252 background: #141820;
2253 }
2254
2255 .quest-rewards-drawer summary {
2256 cursor: pointer;
2257 font-weight: 650;
2258 margin-bottom: 0.35rem;
2259 }
2260
2244 2261 .dialogue-canvas-wrap {
2245 2262 position: relative;
2246 2263 flex: 1;
@@ -2339,6 +2356,15 @@ label {
2339 2356 box-shadow: 0 0 0 1px rgba(224, 168, 74, 0.35), 0 6px 18px rgba(0, 0, 0, 0.35);
2340 2357 }
2341 2358
2359 .dialogue-canvas-card.is-quest-end {
2360 border-color: #6a9a78;
2361 background: #18241e;
2362 }
2363
2364 .dialogue-canvas-card.is-quest-end .dialogue-canvas-card-meta {
2365 color: #9dccae;
2366 }
2367
2342 2368 .dialogue-canvas-card.dragging {
2343 2369 cursor: grabbing;
2344 2370 opacity: 0.92;
@@ -2467,6 +2493,25 @@ label {
2467 2493 background: rgba(0, 0, 0, 0.45);
2468 2494 }
2469 2495
2496 .dialogue-step-panel.quest-step-panel {
2497 width: min(520px, 96%);
2498 }
2499
2500 .quest-branch-order {
2501 color: #e0a84a;
2502 font-variant-numeric: tabular-nums;
2503 }
2504
2505 .quest-branch-shadow-warn {
2506 margin: 0.35rem 0;
2507 padding: 0.45rem 0.55rem;
2508 background: rgba(168, 120, 32, 0.22);
2509 border: 1px solid #c4a15a;
2510 border-radius: 4px;
2511 color: #f0e2c0;
2512 line-height: 1.35;
2513 }
2514
2470 2515 .dialogue-step-panel {
2471 2516 position: relative;
2472 2517 z-index: 1;
@@ -512,7 +512,8 @@ button:disabled {
512}
512}
513
513
514#save.save-dirty:not(:disabled),
514#save.save-dirty:not(:disabled),
515#dialogues-save.save-dirty:not(:disabled) {
515#dialogues-save.save-dirty:not(:disabled),
516#quests-save.save-dirty:not(:disabled) {
516 animation: save-pulse 1.1s ease-in-out infinite;
517 animation: save-pulse 1.1s ease-in-out infinite;
517 border-color: #c9a227;
518 border-color: #c9a227;
518 box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);
519 box-shadow: 0 0 0 1px rgba(201, 162, 39, 0.35);
@@ -2199,7 +2200,8 @@ label {
2199}
2200}
2200
2201
2201/* Dialogue canvas graph editor */
2202/* Dialogue canvas graph editor */
2202#dialogues-editor.dialogues-editor-canvas-host {
2203#dialogues-editor.dialogues-editor-canvas-host,
2204#quests-editor.dialogues-editor-canvas-host {
2203 display: flex;
2205 display: flex;
2204 flex-direction: column;
2206 flex-direction: column;
2205 overflow: hidden;
2207 overflow: hidden;
@@ -2241,6 +2243,21 @@ label {
2241 margin: 0.35rem 0 0.15rem;
2243 margin: 0.35rem 0 0.15rem;
2242}
2244}
2243
2245
2246.quest-rewards-drawer {
2247 flex-shrink: 0;
2248 max-height: 30%;
2249 overflow: auto;
2250 padding: 0.35rem 1rem 0.55rem;
2251 border-bottom: 1px solid #2c3340;
2252 background: #141820;
2253}
2254
2255.quest-rewards-drawer summary {
2256 cursor: pointer;
2257 font-weight: 650;
2258 margin-bottom: 0.35rem;
2259}
2260
2244.dialogue-canvas-wrap {
2261.dialogue-canvas-wrap {
2245 position: relative;
2262 position: relative;
2246 flex: 1;
2263 flex: 1;
@@ -2339,6 +2356,15 @@ label {
2339 box-shadow: 0 0 0 1px rgba(224, 168, 74, 0.35), 0 6px 18px rgba(0, 0, 0, 0.35);
2356 box-shadow: 0 0 0 1px rgba(224, 168, 74, 0.35), 0 6px 18px rgba(0, 0, 0, 0.35);
2340}
2357}
2341
2358
2359.dialogue-canvas-card.is-quest-end {
2360 border-color: #6a9a78;
2361 background: #18241e;
2362}
2363
2364.dialogue-canvas-card.is-quest-end .dialogue-canvas-card-meta {
2365 color: #9dccae;
2366}
2367
2342.dialogue-canvas-card.dragging {
2368.dialogue-canvas-card.dragging {
2343 cursor: grabbing;
2369 cursor: grabbing;
2344 opacity: 0.92;
2370 opacity: 0.92;
@@ -2467,6 +2493,25 @@ label {
2467 background: rgba(0, 0, 0, 0.45);
2493 background: rgba(0, 0, 0, 0.45);
2468}
2494}
2469
2495
2496.dialogue-step-panel.quest-step-panel {
2497 width: min(520px, 96%);
2498}
2499
2500.quest-branch-order {
2501 color: #e0a84a;
2502 font-variant-numeric: tabular-nums;
2503}
2504
2505.quest-branch-shadow-warn {
2506 margin: 0.35rem 0;
2507 padding: 0.45rem 0.55rem;
2508 background: rgba(168, 120, 32, 0.22);
2509 border: 1px solid #c4a15a;
2510 border-radius: 4px;
2511 color: #f0e2c0;
2512 line-height: 1.35;
2513}
2514
2470.dialogue-step-panel {
2515.dialogue-step-panel {
2471 position: relative;
2516 position: relative;
2472 z-index: 1;
2517 z-index: 1;
server/src/editor/service.js +23 −1
@@ -883,6 +883,11 @@ export function diffQuests (previous, next)
883 883 if (JSON.stringify(previous.rewards) !== JSON.stringify(next.rewards))
884 884 { bullets.push("Quest rewards changed."); }
885 885
886 const prevIds = (previous.steps ?? []).map((step) => step.stepId);
887 const nextIds = (next.steps ?? []).map((step) => step.stepId);
888 if (sameStepIdSet(prevIds, nextIds) && prevIds.join("\0") !== nextIds.join("\0"))
889 { bullets.push("Step order changed."); }
890
886 891 const prevSteps = new Map((previous.steps ?? []).map((step) => [step.stepId, step]));
887 892 const nextSteps = new Map((next.steps ?? []).map((step) => [step.stepId, step]));
888 893 for (const stepId of new Set([...prevSteps.keys(), ...nextSteps.keys()]))
@@ -893,8 +898,10 @@ export function diffQuests (previous, next)
893 898 { bullets.push(`Step "${cur.title}" (${stepId}) added.`); }
894 899 else if (prev && !cur)
895 900 { bullets.push(`Step "${prev.title}" (${stepId}) removed.`); }
896 else if (JSON.stringify(prev) !== JSON.stringify(cur))
901 else if (JSON.stringify(stepWithoutCanvasLayout(prev)) !== JSON.stringify(stepWithoutCanvasLayout(cur)))
897 902 { bullets.push(`Step "${cur.title}" (${stepId}) updated.`); }
903 else if (`${prev.editorX},${prev.editorY}` !== `${cur.editorX},${cur.editorY}`)
904 { bullets.push(`Step "${cur.title}" (${stepId}) moved on the canvas.`); }
898 905 }
899 906 if (bullets.length === 0)
900 907 { bullets.push(`Quest "${next.questId}" updated.`); }
@@ -933,6 +940,21 @@ export function diffDialogues (previous, next)
933 940 return bullets;
934 941 }
935 942
943 function stepWithoutCanvasLayout (step)
944 {
945 if (!step)
946 { return step; }
947 const { editorX, editorY, ...rest } = step;
948 return rest;
949 }
950
951 function sameStepIdSet (left, right)
952 {
953 if (left.length !== right.length)
954 { return false; }
955 return [...left].sort().join("\0") === [...right].sort().join("\0");
956 }
957
936 958 function indexSpawners (spawners)
937 959 {
938 960 const map = new Map();
@@ -883,6 +883,11 @@ export function diffQuests (previous, next)
883 if (JSON.stringify(previous.rewards) !== JSON.stringify(next.rewards))
883 if (JSON.stringify(previous.rewards) !== JSON.stringify(next.rewards))
884 { bullets.push("Quest rewards changed."); }
884 { bullets.push("Quest rewards changed."); }
885
885
886 const prevIds = (previous.steps ?? []).map((step) => step.stepId);
887 const nextIds = (next.steps ?? []).map((step) => step.stepId);
888 if (sameStepIdSet(prevIds, nextIds) && prevIds.join("\0") !== nextIds.join("\0"))
889 { bullets.push("Step order changed."); }
890
886 const prevSteps = new Map((previous.steps ?? []).map((step) => [step.stepId, step]));
891 const prevSteps = new Map((previous.steps ?? []).map((step) => [step.stepId, step]));
887 const nextSteps = new Map((next.steps ?? []).map((step) => [step.stepId, step]));
892 const nextSteps = new Map((next.steps ?? []).map((step) => [step.stepId, step]));
888 for (const stepId of new Set([...prevSteps.keys(), ...nextSteps.keys()]))
893 for (const stepId of new Set([...prevSteps.keys(), ...nextSteps.keys()]))
@@ -893,8 +898,10 @@ export function diffQuests (previous, next)
893 { bullets.push(`Step "${cur.title}" (${stepId}) added.`); }
898 { bullets.push(`Step "${cur.title}" (${stepId}) added.`); }
894 else if (prev && !cur)
899 else if (prev && !cur)
895 { bullets.push(`Step "${prev.title}" (${stepId}) removed.`); }
900 { bullets.push(`Step "${prev.title}" (${stepId}) removed.`); }
896 else if (JSON.stringify(prev) !== JSON.stringify(cur))
901 else if (JSON.stringify(stepWithoutCanvasLayout(prev)) !== JSON.stringify(stepWithoutCanvasLayout(cur)))
897 { bullets.push(`Step "${cur.title}" (${stepId}) updated.`); }
902 { bullets.push(`Step "${cur.title}" (${stepId}) updated.`); }
903 else if (`${prev.editorX},${prev.editorY}` !== `${cur.editorX},${cur.editorY}`)
904 { bullets.push(`Step "${cur.title}" (${stepId}) moved on the canvas.`); }
898 }
905 }
899 if (bullets.length === 0)
906 if (bullets.length === 0)
900 { bullets.push(`Quest "${next.questId}" updated.`); }
907 { bullets.push(`Quest "${next.questId}" updated.`); }
@@ -933,6 +940,21 @@ export function diffDialogues (previous, next)
933 return bullets;
940 return bullets;
934}
941}
935
942
943function stepWithoutCanvasLayout (step)
944{
945 if (!step)
946 { return step; }
947 const { editorX, editorY, ...rest } = step;
948 return rest;
949}
950
951function sameStepIdSet (left, right)
952{
953 if (left.length !== right.length)
954 { return false; }
955 return [...left].sort().join("\0") === [...right].sort().join("\0");
956}
957
936function indexSpawners (spawners)
958function indexSpawners (spawners)
937{
959{
938 const map = new Map();
960 const map = new Map();
server/tests/quest-graph.test.js added +205 −0
@@ -0,0 +1,205 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { CARD_W, CARD_H, dialogueOutputPorts } from "../../client/src/editor/dialogueCanvas.js";
4 import { diffQuests } from "../src/editor/service.js";
5 import { normalizeQuestDef, relinkImplicitQuestExits } from "../../shared/quests/normalize.js";
6 import { emptyConditionSet } from "../../shared/quests/conditions.js";
7 import {
8 QUEST_CARD_W,
9 QUEST_CARD_H,
10 blankQuestStep,
11 branchShadowsLater,
12 layoutQuestSteps,
13 prepareQuestExitsForSave,
14 questCanvasPorts
15 } from "../../shared/quests/questGraph.js";
16
17 test("dialogue canvas ports stay the default graph and match quest card size", () =>
18 {
19 assert.equal(QUEST_CARD_W, CARD_W);
20 assert.equal(QUEST_CARD_H, CARD_H);
21
22 const ended = { exit: { kind: "end" } };
23 assert.deepEqual(dialogueOutputPorts(ended), []);
24
25 const step = {
26 exit: {
27 kind: "triggers",
28 triggers: [{ trigger: "go", text: "Walk on", nextStepId: "next" }]
29 }
30 };
31 const ports = dialogueOutputPorts(step);
32 assert.equal(ports.length, 1);
33 assert.equal(ports[0].key, "trigger:0");
34 assert.equal(ports[0].label, "Walk on");
35 ports[0].setNext("other");
36 assert.equal(step.exit.triggers[0].nextStepId, "other");
37
38 const branched = {
39 exit: {
40 kind: "branches",
41 branches: [{ label: "", nextStepId: null }, { label: "Yes", nextStepId: "y" }]
42 }
43 };
44 const branchPorts = dialogueOutputPorts(branched);
45 assert.equal(branchPorts[0].label, "Branch 1");
46 assert.equal(branchPorts[1].label, "Yes");
47 });
48
49 test("quest steps keep editor positions and implicit chains", () =>
50 {
51 const quest = normalizeQuestDef({
52 questId: "placed",
53 steps: [
54 { stepId: "a", editorX: 12.5, editorY: 40 },
55 { stepId: "b" }
56 ]
57 });
58 assert.equal(quest.steps[0].editorX, 12.5);
59 assert.equal(quest.steps[0].editorY, 40);
60 assert.equal(quest.steps[0].exit.implicit, true);
61 assert.equal(quest.steps[0].exit.nextStepId, "b");
62 assert.equal(quest.steps[1].editorX, undefined);
63 });
64
65 test("saving keeps implicit exits unless the author changed the graph", () =>
66 {
67 const linear = normalizeQuestDef({
68 questId: "line",
69 steps: [{ stepId: "a" }, { stepId: "b" }, { stepId: "c" }]
70 });
71 prepareQuestExitsForSave(linear.steps);
72 assert.equal(linear.steps[0].exit.implicit, true);
73 assert.equal(linear.steps[0].exit.nextStepId, "b");
74 assert.equal(linear.steps[2].exit.kind, "complete");
75 assert.equal(linear.steps[2].exit.implicit, true);
76
77 linear.steps[0].exit = { kind: "continue", nextStepId: "c" };
78 prepareQuestExitsForSave(linear.steps);
79 const saved = normalizeQuestDef(linear);
80 assert.equal(saved.steps[0].exit.implicit, undefined);
81 assert.equal(saved.steps[0].exit.nextStepId, "c");
82 assert.equal(saved.steps[1].exit.implicit, true);
83 assert.equal(saved.steps[1].exit.nextStepId, "c");
84 assert.equal(saved.steps[2].exit.kind, "complete");
85
86 const extended = normalizeQuestDef({
87 questId: "line",
88 steps: [{ stepId: "a" }, { stepId: "b" }]
89 });
90 extended.steps.push(blankQuestStep("c", 30, 80));
91 prepareQuestExitsForSave(extended.steps);
92 const withExtra = normalizeQuestDef(extended);
93 assert.equal(withExtra.steps[0].exit.nextStepId, "b");
94 assert.equal(withExtra.steps[0].exit.implicit, true);
95 assert.equal(withExtra.steps[1].exit.kind, "complete");
96 assert.equal(withExtra.steps[1].exit.implicit, undefined);
97 assert.equal(withExtra.steps[2].exit.kind, "complete");
98 assert.equal(withExtra.steps[2].editorX, 30);
99 assert.equal(withExtra.steps[2].editorY, 80);
100 });
101
102 test("deleting a middle implicit step relinks the chain", () =>
103 {
104 const quest = normalizeQuestDef({
105 questId: "line",
106 steps: [{ stepId: "a" }, { stepId: "b" }, { stepId: "c" }]
107 });
108 quest.steps.splice(1, 1);
109 relinkImplicitQuestExits(quest.steps);
110 assert.equal(quest.steps[0].exit.kind, "continue");
111 assert.equal(quest.steps[0].exit.nextStepId, "c");
112 assert.equal(quest.steps[0].exit.implicit, true);
113 assert.equal(quest.steps[1].exit.kind, "complete");
114 });
115
116 test("quest canvas ports, first-match warning, and auto layout", () =>
117 {
118 const filled = {
119 all: [{ condition: { kind: "hasItem", itemId: 1, quantity: 1 } }]
120 };
121 const quest = normalizeQuestDef({
122 questId: "fork",
123 steps: [
124 {
125 stepId: "a",
126 title: "Fork",
127 exit: {
128 kind: "branches",
129 branches: [
130 { label: "Left", text: "Take the left path", when: emptyConditionSet(), nextStepId: "b" },
131 { label: "Right", text: "Take the right path", when: filled, nextStepId: "c" }
132 ]
133 }
134 },
135 { stepId: "b", title: "Left", exit: { kind: "continue", nextStepId: "d" } },
136 { stepId: "c", title: "Right", exit: { kind: "continue", nextStepId: "d" } },
137 { stepId: "d", title: "Join", exit: { kind: "complete" } }
138 ]
139 });
140 const fork = quest.steps[0];
141 assert.equal(fork.exit.implicit, undefined);
142 assert.equal(branchShadowsLater(fork.exit.branches, 0), true);
143 assert.equal(branchShadowsLater(fork.exit.branches, 1), false);
144
145 const ports = questCanvasPorts(fork);
146 assert.equal(ports.length, 2);
147 assert.equal(ports[0].label, "1. Left");
148 assert.equal(ports[1].key, "branch:1");
149 assert.equal(questCanvasPorts(quest.steps[1]).length, 1);
150 assert.equal(questCanvasPorts(quest.steps[3]).length, 0);
151
152 const placed = layoutQuestSteps(quest.steps);
153 assert.ok(placed.get("a").x < placed.get("b").x);
154 assert.equal(placed.get("b").x, placed.get("c").x);
155 assert.ok(placed.get("b").y < placed.get("c").y);
156 assert.ok(placed.get("d").x > placed.get("b").x);
157
158 quest.steps[0].editorX = 400;
159 quest.steps[0].editorY = 400;
160 const mixed = layoutQuestSteps(quest.steps);
161 assert.deepEqual(mixed.get("a"), { x: 400, y: 400 });
162 assert.equal(mixed.get("b").x, placed.get("b").x);
163 assert.equal(mixed.get("c").y, placed.get("c").y);
164
165 ports[0].setNext("d");
166 assert.equal(fork.exit.branches[0].nextStepId, "d");
167 assert.equal(fork.exit.branches[1].nextStepId, "c");
168
169 const linear = normalizeQuestDef({
170 questId: "line",
171 steps: [{ stepId: "a" }, { stepId: "b" }]
172 });
173 const same = questCanvasPorts(linear.steps[0]);
174 assert.equal(linear.steps[0].exit.implicit, true);
175 same[0].setNext("b");
176 assert.equal(linear.steps[0].exit.implicit, true);
177 same[0].setNext("elsewhere");
178 assert.equal(linear.steps[0].exit.implicit, undefined);
179 assert.equal(linear.steps[0].exit.nextStepId, "elsewhere");
180 });
181
182 test("quest changelog separates canvas moves from step edits", () =>
183 {
184 const previous = normalizeQuestDef({
185 questId: "q",
186 title: "Fetch",
187 steps: [{ stepId: "a", title: "Start" }, { stepId: "b", title: "End" }]
188 });
189 const moved = structuredClone(previous);
190 moved.steps[0].editorX = 80;
191 moved.steps[0].editorY = 40;
192 const movedBullets = diffQuests(previous, moved);
193 assert.deepEqual(movedBullets, ['Step "Start" (a) moved on the canvas.']);
194
195 const edited = structuredClone(previous);
196 edited.steps[1].title = "Finish";
197 const editedBullets = diffQuests(previous, edited);
198 assert.ok(editedBullets.some((line) => /updated/.test(line)));
199 assert.equal(editedBullets.some((line) => /moved/.test(line)), false);
200
201 const reordered = structuredClone(previous);
202 reordered.steps.reverse();
203 const orderBullets = diffQuests(previous, reordered);
204 assert.ok(orderBullets.some((line) => /Step order changed/.test(line)));
205 });
@@ -0,0 +1,205 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { CARD_W, CARD_H, dialogueOutputPorts } from "../../client/src/editor/dialogueCanvas.js";
4import { diffQuests } from "../src/editor/service.js";
5import { normalizeQuestDef, relinkImplicitQuestExits } from "../../shared/quests/normalize.js";
6import { emptyConditionSet } from "../../shared/quests/conditions.js";
7import {
8 QUEST_CARD_W,
9 QUEST_CARD_H,
10 blankQuestStep,
11 branchShadowsLater,
12 layoutQuestSteps,
13 prepareQuestExitsForSave,
14 questCanvasPorts
15} from "../../shared/quests/questGraph.js";
16
17test("dialogue canvas ports stay the default graph and match quest card size", () =>
18{
19 assert.equal(QUEST_CARD_W, CARD_W);
20 assert.equal(QUEST_CARD_H, CARD_H);
21
22 const ended = { exit: { kind: "end" } };
23 assert.deepEqual(dialogueOutputPorts(ended), []);
24
25 const step = {
26 exit: {
27 kind: "triggers",
28 triggers: [{ trigger: "go", text: "Walk on", nextStepId: "next" }]
29 }
30 };
31 const ports = dialogueOutputPorts(step);
32 assert.equal(ports.length, 1);
33 assert.equal(ports[0].key, "trigger:0");
34 assert.equal(ports[0].label, "Walk on");
35 ports[0].setNext("other");
36 assert.equal(step.exit.triggers[0].nextStepId, "other");
37
38 const branched = {
39 exit: {
40 kind: "branches",
41 branches: [{ label: "", nextStepId: null }, { label: "Yes", nextStepId: "y" }]
42 }
43 };
44 const branchPorts = dialogueOutputPorts(branched);
45 assert.equal(branchPorts[0].label, "Branch 1");
46 assert.equal(branchPorts[1].label, "Yes");
47});
48
49test("quest steps keep editor positions and implicit chains", () =>
50{
51 const quest = normalizeQuestDef({
52 questId: "placed",
53 steps: [
54 { stepId: "a", editorX: 12.5, editorY: 40 },
55 { stepId: "b" }
56 ]
57 });
58 assert.equal(quest.steps[0].editorX, 12.5);
59 assert.equal(quest.steps[0].editorY, 40);
60 assert.equal(quest.steps[0].exit.implicit, true);
61 assert.equal(quest.steps[0].exit.nextStepId, "b");
62 assert.equal(quest.steps[1].editorX, undefined);
63});
64
65test("saving keeps implicit exits unless the author changed the graph", () =>
66{
67 const linear = normalizeQuestDef({
68 questId: "line",
69 steps: [{ stepId: "a" }, { stepId: "b" }, { stepId: "c" }]
70 });
71 prepareQuestExitsForSave(linear.steps);
72 assert.equal(linear.steps[0].exit.implicit, true);
73 assert.equal(linear.steps[0].exit.nextStepId, "b");
74 assert.equal(linear.steps[2].exit.kind, "complete");
75 assert.equal(linear.steps[2].exit.implicit, true);
76
77 linear.steps[0].exit = { kind: "continue", nextStepId: "c" };
78 prepareQuestExitsForSave(linear.steps);
79 const saved = normalizeQuestDef(linear);
80 assert.equal(saved.steps[0].exit.implicit, undefined);
81 assert.equal(saved.steps[0].exit.nextStepId, "c");
82 assert.equal(saved.steps[1].exit.implicit, true);
83 assert.equal(saved.steps[1].exit.nextStepId, "c");
84 assert.equal(saved.steps[2].exit.kind, "complete");
85
86 const extended = normalizeQuestDef({
87 questId: "line",
88 steps: [{ stepId: "a" }, { stepId: "b" }]
89 });
90 extended.steps.push(blankQuestStep("c", 30, 80));
91 prepareQuestExitsForSave(extended.steps);
92 const withExtra = normalizeQuestDef(extended);
93 assert.equal(withExtra.steps[0].exit.nextStepId, "b");
94 assert.equal(withExtra.steps[0].exit.implicit, true);
95 assert.equal(withExtra.steps[1].exit.kind, "complete");
96 assert.equal(withExtra.steps[1].exit.implicit, undefined);
97 assert.equal(withExtra.steps[2].exit.kind, "complete");
98 assert.equal(withExtra.steps[2].editorX, 30);
99 assert.equal(withExtra.steps[2].editorY, 80);
100});
101
102test("deleting a middle implicit step relinks the chain", () =>
103{
104 const quest = normalizeQuestDef({
105 questId: "line",
106 steps: [{ stepId: "a" }, { stepId: "b" }, { stepId: "c" }]
107 });
108 quest.steps.splice(1, 1);
109 relinkImplicitQuestExits(quest.steps);
110 assert.equal(quest.steps[0].exit.kind, "continue");
111 assert.equal(quest.steps[0].exit.nextStepId, "c");
112 assert.equal(quest.steps[0].exit.implicit, true);
113 assert.equal(quest.steps[1].exit.kind, "complete");
114});
115
116test("quest canvas ports, first-match warning, and auto layout", () =>
117{
118 const filled = {
119 all: [{ condition: { kind: "hasItem", itemId: 1, quantity: 1 } }]
120 };
121 const quest = normalizeQuestDef({
122 questId: "fork",
123 steps: [
124 {
125 stepId: "a",
126 title: "Fork",
127 exit: {
128 kind: "branches",
129 branches: [
130 { label: "Left", text: "Take the left path", when: emptyConditionSet(), nextStepId: "b" },
131 { label: "Right", text: "Take the right path", when: filled, nextStepId: "c" }
132 ]
133 }
134 },
135 { stepId: "b", title: "Left", exit: { kind: "continue", nextStepId: "d" } },
136 { stepId: "c", title: "Right", exit: { kind: "continue", nextStepId: "d" } },
137 { stepId: "d", title: "Join", exit: { kind: "complete" } }
138 ]
139 });
140 const fork = quest.steps[0];
141 assert.equal(fork.exit.implicit, undefined);
142 assert.equal(branchShadowsLater(fork.exit.branches, 0), true);
143 assert.equal(branchShadowsLater(fork.exit.branches, 1), false);
144
145 const ports = questCanvasPorts(fork);
146 assert.equal(ports.length, 2);
147 assert.equal(ports[0].label, "1. Left");
148 assert.equal(ports[1].key, "branch:1");
149 assert.equal(questCanvasPorts(quest.steps[1]).length, 1);
150 assert.equal(questCanvasPorts(quest.steps[3]).length, 0);
151
152 const placed = layoutQuestSteps(quest.steps);
153 assert.ok(placed.get("a").x < placed.get("b").x);
154 assert.equal(placed.get("b").x, placed.get("c").x);
155 assert.ok(placed.get("b").y < placed.get("c").y);
156 assert.ok(placed.get("d").x > placed.get("b").x);
157
158 quest.steps[0].editorX = 400;
159 quest.steps[0].editorY = 400;
160 const mixed = layoutQuestSteps(quest.steps);
161 assert.deepEqual(mixed.get("a"), { x: 400, y: 400 });
162 assert.equal(mixed.get("b").x, placed.get("b").x);
163 assert.equal(mixed.get("c").y, placed.get("c").y);
164
165 ports[0].setNext("d");
166 assert.equal(fork.exit.branches[0].nextStepId, "d");
167 assert.equal(fork.exit.branches[1].nextStepId, "c");
168
169 const linear = normalizeQuestDef({
170 questId: "line",
171 steps: [{ stepId: "a" }, { stepId: "b" }]
172 });
173 const same = questCanvasPorts(linear.steps[0]);
174 assert.equal(linear.steps[0].exit.implicit, true);
175 same[0].setNext("b");
176 assert.equal(linear.steps[0].exit.implicit, true);
177 same[0].setNext("elsewhere");
178 assert.equal(linear.steps[0].exit.implicit, undefined);
179 assert.equal(linear.steps[0].exit.nextStepId, "elsewhere");
180});
181
182test("quest changelog separates canvas moves from step edits", () =>
183{
184 const previous = normalizeQuestDef({
185 questId: "q",
186 title: "Fetch",
187 steps: [{ stepId: "a", title: "Start" }, { stepId: "b", title: "End" }]
188 });
189 const moved = structuredClone(previous);
190 moved.steps[0].editorX = 80;
191 moved.steps[0].editorY = 40;
192 const movedBullets = diffQuests(previous, moved);
193 assert.deepEqual(movedBullets, ['Step "Start" (a) moved on the canvas.']);
194
195 const edited = structuredClone(previous);
196 edited.steps[1].title = "Finish";
197 const editedBullets = diffQuests(previous, edited);
198 assert.ok(editedBullets.some((line) => /updated/.test(line)));
199 assert.equal(editedBullets.some((line) => /moved/.test(line)), false);
200
201 const reordered = structuredClone(previous);
202 reordered.steps.reverse();
203 const orderBullets = diffQuests(previous, reordered);
204 assert.ok(orderBullets.some((line) => /Step order changed/.test(line)));
205});
shared/quests/normalize.js +23 −1
@@ -62,7 +62,7 @@ function normalizeQuestStep (raw, index, questLookup)
62 62 when: emptyConditionSet()
63 63 }, 0, questLookup)];
64 64 }
65 return {
65 const out = {
66 66 stepId,
67 67 title: String(raw?.title ?? stepId).trim().slice(0, 80) || stepId,
68 68 description: String(raw?.description ?? "").trim().slice(0, 500),
@@ -72,6 +72,13 @@ function normalizeQuestStep (raw, index, questLookup)
72 72 onComplete: normalizeEffects(raw?.onComplete),
73 73 exit: normalizeExplicitQuestExit(raw?.exit, questLookup)
74 74 };
75 const editorX = Number(raw?.editorX);
76 const editorY = Number(raw?.editorY);
77 if (Number.isFinite(editorX))
78 { out.editorX = editorX; }
79 if (Number.isFinite(editorY))
80 { out.editorY = editorY; }
81 return out;
75 82 }
76 83
77 84 /**
@@ -123,6 +130,21 @@ function linkImplicitQuestExits (steps)
123 130 }
124 131 }
125 132
133 /**
134 * Rebuild implicit exits from the current array order.
135 * Explicit exits (no implicit flag) keep their nextStepId.
136 */
137 export function relinkImplicitQuestExits (steps)
138 {
139 for (const step of steps ?? [])
140 {
141 if (step?.exit?.implicit === true)
142 { step.exit = null; }
143 }
144 linkImplicitQuestExits(steps ?? []);
145 return steps;
146 }
147
126 148 function normalizeQuestBranch (raw, questLookup)
127 149 {
128 150 if (!raw || typeof raw !== "object")
@@ -62,7 +62,7 @@ function normalizeQuestStep (raw, index, questLookup)
62 when: emptyConditionSet()
62 when: emptyConditionSet()
63 }, 0, questLookup)];
63 }, 0, questLookup)];
64 }
64 }
65 return {
65 const out = {
66 stepId,
66 stepId,
67 title: String(raw?.title ?? stepId).trim().slice(0, 80) || stepId,
67 title: String(raw?.title ?? stepId).trim().slice(0, 80) || stepId,
68 description: String(raw?.description ?? "").trim().slice(0, 500),
68 description: String(raw?.description ?? "").trim().slice(0, 500),
@@ -72,6 +72,13 @@ function normalizeQuestStep (raw, index, questLookup)
72 onComplete: normalizeEffects(raw?.onComplete),
72 onComplete: normalizeEffects(raw?.onComplete),
73 exit: normalizeExplicitQuestExit(raw?.exit, questLookup)
73 exit: normalizeExplicitQuestExit(raw?.exit, questLookup)
74 };
74 };
75 const editorX = Number(raw?.editorX);
76 const editorY = Number(raw?.editorY);
77 if (Number.isFinite(editorX))
78 { out.editorX = editorX; }
79 if (Number.isFinite(editorY))
80 { out.editorY = editorY; }
81 return out;
75}
82}
76
83
77/**
84/**
@@ -123,6 +130,21 @@ function linkImplicitQuestExits (steps)
123 }
130 }
124}
131}
125
132
133/**
134 * Rebuild implicit exits from the current array order.
135 * Explicit exits (no implicit flag) keep their nextStepId.
136 */
137export function relinkImplicitQuestExits (steps)
138{
139 for (const step of steps ?? [])
140 {
141 if (step?.exit?.implicit === true)
142 { step.exit = null; }
143 }
144 linkImplicitQuestExits(steps ?? []);
145 return steps;
146}
147
126function normalizeQuestBranch (raw, questLookup)
148function normalizeQuestBranch (raw, questLookup)
127{
149{
128 if (!raw || typeof raw !== "object")
150 if (!raw || typeof raw !== "object")
shared/quests/questGraph.js added +224 −0
@@ -0,0 +1,224 @@
1 /**
2 * Quest-graph helpers shared by the editor and tests.
3 * Card size matches client/src/editor/dialogueCanvas.js (CARD_W / CARD_H).
4 */
5 import { emptyConditionSet } from "./conditions.js";
6
7 export const QUEST_CARD_W = 168;
8 export const QUEST_CARD_H = 72;
9
10 const COL_GAP = 88;
11 const ROW_GAP = 56;
12 const ORIGIN = 48;
13
14 export function blankQuestStep (stepId, editorX, editorY)
15 {
16 const step = {
17 stepId,
18 title: "New step",
19 description: "",
20 completionJournalText: "",
21 objectives: [{
22 objectiveId: "obj-1",
23 text: "Complete this step",
24 when: emptyConditionSet()
25 }],
26 onEnter: [],
27 onComplete: [],
28 exit: { kind: "complete" }
29 };
30 if (Number.isFinite(editorX))
31 { step.editorX = editorX; }
32 if (Number.isFinite(editorY))
33 { step.editorY = editorY; }
34 return step;
35 }
36
37 /** An empty condition set always passes, so it shadows every later branch. */
38 export function conditionSetIsVacuous (set)
39 {
40 const all = set?.all;
41 return !Array.isArray(all) || all.length === 0;
42 }
43
44 export function branchShadowsLater (branches, index)
45 {
46 if (!Array.isArray(branches) || index < 0 || index >= branches.length - 1)
47 { return false; }
48 return conditionSetIsVacuous(branches[index]?.when);
49 }
50
51 /**
52 * True when this exit is the chain the loader would synthesise from array order.
53 * Branches are never implicit. A continue only matches the immediate next step.
54 */
55 export function questExitMatchesImplicit (steps, index)
56 {
57 const step = steps?.[index];
58 if (!step)
59 { return false; }
60 const exit = step.exit;
61 const last = index === steps.length - 1;
62 if (!exit)
63 { return true; }
64 if (exit.kind === "branches")
65 { return false; }
66 if (last)
67 { return exit.kind === "complete"; }
68 return exit.kind === "continue"
69 && (exit.nextStepId || null) === (steps[index + 1]?.stepId ?? null);
70 }
71
72 /**
73 * Keep implicit exits where the graph still matches array order.
74 * Anything the author changed (other target, branches, early complete) is explicit.
75 */
76 export function prepareQuestExitsForSave (steps)
77 {
78 for (let index = 0; index < (steps ?? []).length; index++)
79 {
80 const step = steps[index];
81 if (questExitMatchesImplicit(steps, index))
82 {
83 step.exit = index === steps.length - 1
84 ? { kind: "complete", implicit: true }
85 : {
86 kind: "continue",
87 nextStepId: steps[index + 1].stepId,
88 implicit: true
89 };
90 }
91 else if (step.exit)
92 { delete step.exit.implicit; }
93 }
94 return steps;
95 }
96
97 function outgoingStepIds (step)
98 {
99 const exit = step?.exit;
100 if (!exit)
101 { return []; }
102 if (exit.kind === "continue" && exit.nextStepId)
103 { return [exit.nextStepId]; }
104 if (exit.kind === "branches")
105 {
106 return (exit.branches ?? [])
107 .map((branch) => branch?.nextStepId)
108 .filter(Boolean);
109 }
110 return [];
111 }
112
113 function autoLayout (steps)
114 {
115 const depth = new Map();
116 const start = steps[0]?.stepId;
117 if (start)
118 {
119 const queue = [start];
120 depth.set(start, 0);
121 while (queue.length)
122 {
123 const id = queue.shift();
124 const step = steps.find((row) => row.stepId === id);
125 const column = depth.get(id) ?? 0;
126 for (const next of outgoingStepIds(step))
127 {
128 if (!steps.some((row) => row.stepId === next) || depth.has(next))
129 { continue; }
130 depth.set(next, column + 1);
131 queue.push(next);
132 }
133 }
134 }
135 let maxDepth = 0;
136 for (const column of depth.values())
137 { maxDepth = Math.max(maxDepth, column); }
138 const orphanColumn = steps.some((step) => !depth.has(step.stepId))
139 ? maxDepth + 1
140 : maxDepth;
141 const rows = new Map();
142 const positions = new Map();
143 for (const step of steps)
144 {
145 const column = depth.has(step.stepId) ? depth.get(step.stepId) : orphanColumn;
146 const row = rows.get(column) ?? 0;
147 rows.set(column, row + 1);
148 positions.set(step.stepId, {
149 x: ORIGIN + column * (QUEST_CARD_W + COL_GAP),
150 y: ORIGIN + row * (QUEST_CARD_H + ROW_GAP)
151 });
152 }
153 return positions;
154 }
155
156 /**
157 * Stored editorX/editorY win. Steps without a position use a left-to-right
158 * flow of the current wires, so a linear quest opens as a chain.
159 */
160 export function layoutQuestSteps (steps)
161 {
162 const list = steps ?? [];
163 const auto = autoLayout(list);
164 const out = new Map();
165 list.forEach((step, index) =>
166 {
167 const storedX = Number(step?.editorX);
168 const storedY = Number(step?.editorY);
169 if (Number.isFinite(storedX) && Number.isFinite(storedY))
170 { out.set(step.stepId, { x: storedX, y: storedY }); }
171 else
172 {
173 out.set(step.stepId, auto.get(step.stepId) ?? {
174 x: ORIGIN,
175 y: ORIGIN + index * (QUEST_CARD_H + ROW_GAP)
176 });
177 }
178 });
179 return out;
180 }
181
182 /**
183 * Canvas ports for a quest step. Wires call setNext, which only writes nextStepId.
184 * Rewiring a continue away from its current target drops the implicit flag.
185 */
186 export function questCanvasPorts (step)
187 {
188 const exit = step?.exit ?? { kind: "complete" };
189 if (exit.kind === "continue")
190 {
191 return [{
192 key: "continue",
193 label: "Continue",
194 nextStepId: exit.nextStepId ?? null,
195 setNext (id)
196 {
197 const next = id || null;
198 if ((exit.nextStepId ?? null) !== next)
199 { delete exit.implicit; }
200 exit.nextStepId = next;
201 }
202 }];
203 }
204 if (exit.kind === "branches")
205 {
206 return (exit.branches ?? []).map((branch, index) =>
207 {
208 const name = String(branch?.label ?? "").trim()
209 || String(branch?.text ?? "").trim()
210 || `Branch ${index + 1}`;
211 return {
212 key: `branch:${index}`,
213 label: `${index + 1}. ${name}`,
214 nextStepId: branch?.nextStepId ?? null,
215 setNext (id)
216 {
217 branch.nextStepId = id || null;
218 delete exit.implicit;
219 }
220 };
221 });
222 }
223 return [];
224 }
@@ -0,0 +1,224 @@
1/**
2 * Quest-graph helpers shared by the editor and tests.
3 * Card size matches client/src/editor/dialogueCanvas.js (CARD_W / CARD_H).
4 */
5import { emptyConditionSet } from "./conditions.js";
6
7export const QUEST_CARD_W = 168;
8export const QUEST_CARD_H = 72;
9
10const COL_GAP = 88;
11const ROW_GAP = 56;
12const ORIGIN = 48;
13
14export function blankQuestStep (stepId, editorX, editorY)
15{
16 const step = {
17 stepId,
18 title: "New step",
19 description: "",
20 completionJournalText: "",
21 objectives: [{
22 objectiveId: "obj-1",
23 text: "Complete this step",
24 when: emptyConditionSet()
25 }],
26 onEnter: [],
27 onComplete: [],
28 exit: { kind: "complete" }
29 };
30 if (Number.isFinite(editorX))
31 { step.editorX = editorX; }
32 if (Number.isFinite(editorY))
33 { step.editorY = editorY; }
34 return step;
35}
36
37/** An empty condition set always passes, so it shadows every later branch. */
38export function conditionSetIsVacuous (set)
39{
40 const all = set?.all;
41 return !Array.isArray(all) || all.length === 0;
42}
43
44export function branchShadowsLater (branches, index)
45{
46 if (!Array.isArray(branches) || index < 0 || index >= branches.length - 1)
47 { return false; }
48 return conditionSetIsVacuous(branches[index]?.when);
49}
50
51/**
52 * True when this exit is the chain the loader would synthesise from array order.
53 * Branches are never implicit. A continue only matches the immediate next step.
54 */
55export function questExitMatchesImplicit (steps, index)
56{
57 const step = steps?.[index];
58 if (!step)
59 { return false; }
60 const exit = step.exit;
61 const last = index === steps.length - 1;
62 if (!exit)
63 { return true; }
64 if (exit.kind === "branches")
65 { return false; }
66 if (last)
67 { return exit.kind === "complete"; }
68 return exit.kind === "continue"
69 && (exit.nextStepId || null) === (steps[index + 1]?.stepId ?? null);
70}
71
72/**
73 * Keep implicit exits where the graph still matches array order.
74 * Anything the author changed (other target, branches, early complete) is explicit.
75 */
76export function prepareQuestExitsForSave (steps)
77{
78 for (let index = 0; index < (steps ?? []).length; index++)
79 {
80 const step = steps[index];
81 if (questExitMatchesImplicit(steps, index))
82 {
83 step.exit = index === steps.length - 1
84 ? { kind: "complete", implicit: true }
85 : {
86 kind: "continue",
87 nextStepId: steps[index + 1].stepId,
88 implicit: true
89 };
90 }
91 else if (step.exit)
92 { delete step.exit.implicit; }
93 }
94 return steps;
95}
96
97function outgoingStepIds (step)
98{
99 const exit = step?.exit;
100 if (!exit)
101 { return []; }
102 if (exit.kind === "continue" && exit.nextStepId)
103 { return [exit.nextStepId]; }
104 if (exit.kind === "branches")
105 {
106 return (exit.branches ?? [])
107 .map((branch) => branch?.nextStepId)
108 .filter(Boolean);
109 }
110 return [];
111}
112
113function autoLayout (steps)
114{
115 const depth = new Map();
116 const start = steps[0]?.stepId;
117 if (start)
118 {
119 const queue = [start];
120 depth.set(start, 0);
121 while (queue.length)
122 {
123 const id = queue.shift();
124 const step = steps.find((row) => row.stepId === id);
125 const column = depth.get(id) ?? 0;
126 for (const next of outgoingStepIds(step))
127 {
128 if (!steps.some((row) => row.stepId === next) || depth.has(next))
129 { continue; }
130 depth.set(next, column + 1);
131 queue.push(next);
132 }
133 }
134 }
135 let maxDepth = 0;
136 for (const column of depth.values())
137 { maxDepth = Math.max(maxDepth, column); }
138 const orphanColumn = steps.some((step) => !depth.has(step.stepId))
139 ? maxDepth + 1
140 : maxDepth;
141 const rows = new Map();
142 const positions = new Map();
143 for (const step of steps)
144 {
145 const column = depth.has(step.stepId) ? depth.get(step.stepId) : orphanColumn;
146 const row = rows.get(column) ?? 0;
147 rows.set(column, row + 1);
148 positions.set(step.stepId, {
149 x: ORIGIN + column * (QUEST_CARD_W + COL_GAP),
150 y: ORIGIN + row * (QUEST_CARD_H + ROW_GAP)
151 });
152 }
153 return positions;
154}
155
156/**
157 * Stored editorX/editorY win. Steps without a position use a left-to-right
158 * flow of the current wires, so a linear quest opens as a chain.
159 */
160export function layoutQuestSteps (steps)
161{
162 const list = steps ?? [];
163 const auto = autoLayout(list);
164 const out = new Map();
165 list.forEach((step, index) =>
166 {
167 const storedX = Number(step?.editorX);
168 const storedY = Number(step?.editorY);
169 if (Number.isFinite(storedX) && Number.isFinite(storedY))
170 { out.set(step.stepId, { x: storedX, y: storedY }); }
171 else
172 {
173 out.set(step.stepId, auto.get(step.stepId) ?? {
174 x: ORIGIN,
175 y: ORIGIN + index * (QUEST_CARD_H + ROW_GAP)
176 });
177 }
178 });
179 return out;
180}
181
182/**
183 * Canvas ports for a quest step. Wires call setNext, which only writes nextStepId.
184 * Rewiring a continue away from its current target drops the implicit flag.
185 */
186export function questCanvasPorts (step)
187{
188 const exit = step?.exit ?? { kind: "complete" };
189 if (exit.kind === "continue")
190 {
191 return [{
192 key: "continue",
193 label: "Continue",
194 nextStepId: exit.nextStepId ?? null,
195 setNext (id)
196 {
197 const next = id || null;
198 if ((exit.nextStepId ?? null) !== next)
199 { delete exit.implicit; }
200 exit.nextStepId = next;
201 }
202 }];
203 }
204 if (exit.kind === "branches")
205 {
206 return (exit.branches ?? []).map((branch, index) =>
207 {
208 const name = String(branch?.label ?? "").trim()
209 || String(branch?.text ?? "").trim()
210 || `Branch ${index + 1}`;
211 return {
212 key: `branch:${index}`,
213 label: `${index + 1}. ${name}`,
214 nextStepId: branch?.nextStepId ?? null,
215 setNext (id)
216 {
217 branch.nextStepId = id || null;
218 delete exit.implicit;
219 }
220 };
221 });
222 }
223 return [];
224}