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