Merge branch 'feature/combat-ui-quest-tweaks'
Combat pathing, autorun, bow ammo UI, quest/dialogue editor pickers, initial quests, and dialogue simulate.
@@ -130,10 +130,21 @@
130
130
</div>
131
131
<footer>
132
132
<button id="dialogues-delete" type="button" disabled>Delete</button>
133
<button id="dialogues-simulate" type="button" disabled>Simulate</button>
133
134
<button id="dialogues-save" type="button" disabled>Save</button>
134
135
</footer>
135
136
</div>
136
137
138
<div id="dialogue-simulate-backdrop" hidden></div>
139
<aside id="dialogue-simulate-panel" hidden>
140
<header>
141
<strong id="dialogue-simulate-title">Simulate</strong>
142
<button id="dialogue-simulate-close" type="button">Close</button>
143
</header>
144
<div id="dialogue-simulate-lines"></div>
145
<div id="dialogue-simulate-actions"></div>
146
</aside>
147
137
148
<div id="gifts-backdrop" hidden></div>
138
149
<div id="gifts-modal" hidden>
139
150
<header>
@@ -130,10 +130,21 @@130
</div>130
</div>131
<footer>131
<footer>132
<button id="dialogues-delete" type="button" disabled>Delete</button>132
<button id="dialogues-delete" type="button" disabled>Delete</button>133
<button id="dialogues-simulate" type="button" disabled>Simulate</button>133
<button id="dialogues-save" type="button" disabled>Save</button>134
<button id="dialogues-save" type="button" disabled>Save</button>134
</footer>135
</footer>135
</div>136
</div>136
137
138
<div id="dialogue-simulate-backdrop" hidden></div>139
<aside id="dialogue-simulate-panel" hidden>140
<header>141
<strong id="dialogue-simulate-title">Simulate</strong>142
<button id="dialogue-simulate-close" type="button">Close</button>143
</header>144
<div id="dialogue-simulate-lines"></div>145
<div id="dialogue-simulate-actions"></div>146
</aside>147
137
<div id="gifts-backdrop" hidden></div>148
<div id="gifts-backdrop" hidden></div>138
<div id="gifts-modal" hidden>149
<div id="gifts-modal" hidden>139
<header>150
<header>@@ -162,7 +162,10 @@
162
162
</label>
163
163
<div id="spells-list" class="spells-grid"></div>
164
164
</aside>
165
<div id="spell-favorites-bar" hidden></div>
165
<div id="bottom-left-hud">
166
<div id="equipped-ammo-hud" hidden></div>
167
<div id="spell-favorites-bar" hidden></div>
168
</div>
166
169
167
170
<div id="send-backdrop" class="modal-backdrop" hidden></div>
168
171
<aside id="send-panel" hidden>
@@ -162,7 +162,10 @@162
</label>162
</label>163
<div id="spells-list" class="spells-grid"></div>163
<div id="spells-list" class="spells-grid"></div>164
</aside>164
</aside>165
<div id="spell-favorites-bar" hidden></div>165
<div id="bottom-left-hud">166
<div id="equipped-ammo-hud" hidden></div>167
<div id="spell-favorites-bar" hidden></div>168
</div>166
169
167
<div id="send-backdrop" class="modal-backdrop" hidden></div>170
<div id="send-backdrop" class="modal-backdrop" hidden></div>168
<aside id="send-panel" hidden>171
<aside id="send-panel" hidden>@@ -0,0 +1,776 @@
1
import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
2
import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
3
import { listSpawnableMobTypes } from "/shared/definitions/mobs.js";
4
import { createDimensionCombobox } from "./dimensionCombobox.js";
5
import { OVERWORLD_ID } from "/shared/world/dimensions.js";
6
7
/** All condition kinds available in the shared editor UI. */
8
export const CONDITION_EDITOR_KINDS = Object.freeze(Object.values(ConditionKind));
9
10
export { emptyConditionSet, normalizeConditionSet, ConditionKind };
11
12
export function renderConditionSet (when, onChange, ctx = {})
13
{
14
const wrap = document.createElement("div");
15
const set = normalizeConditionSet(when);
16
const bump = (remount = true) => onChange(set, { remount });
17
const questList = Array.isArray(ctx.quests) ? ctx.quests : [];
18
const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];
19
const title = document.createElement("strong");
20
title.textContent = "When (all of)";
21
wrap.append(title);
22
23
set.all.forEach((clause, index) =>
24
{
25
const row = document.createElement("div");
26
row.className = "content-editor-clause";
27
const notLabel = document.createElement("label");
28
const notBox = document.createElement("input");
29
notBox.type = "checkbox";
30
notBox.checked = !!clause.not;
31
notBox.addEventListener("change", () =>
32
{
33
set.all[index].not = notBox.checked;
34
bump(false);
35
});
36
notLabel.append(notBox, document.createTextNode(" NOT"));
37
row.append(notLabel);
38
39
const kind = document.createElement("select");
40
for (const k of CONDITION_EDITOR_KINDS)
41
{
42
const opt = document.createElement("option");
43
opt.value = k;
44
opt.textContent = k;
45
if ((clause.condition?.kind ?? "") === k)
46
{ opt.selected = true; }
47
kind.append(opt);
48
}
49
const otherOpt = document.createElement("option");
50
otherOpt.value = "__other__";
51
otherOpt.textContent = "(other / JSON)";
52
if (!CONDITION_EDITOR_KINDS.includes(clause.condition?.kind))
53
{ otherOpt.selected = true; }
54
kind.append(otherOpt);
55
kind.addEventListener("change", () =>
56
{
57
if (kind.value === "__other__")
58
{ return; }
59
set.all[index].condition = defaultCondition(kind.value);
60
bump(true);
61
});
62
row.append(kind);
63
64
const cond = clause.condition ?? { kind: ConditionKind.hasItem };
65
if (cond.kind === ConditionKind.hasItem)
66
{
67
row.append(itemConditionPicker(cond, () =>
68
{
69
set.all[index].condition = cond;
70
bump(false);
71
}));
72
row.append(miniField("qty", cond.quantity ?? 1, (v) =>
73
{
74
cond.quantity = Number(v) || 1;
75
set.all[index].condition = cond;
76
bump(false);
77
}));
78
}
79
else if (cond.kind === ConditionKind.questState)
80
{
81
row.append(questStateConditionFields(cond, questList, () =>
82
{
83
set.all[index].condition = cond;
84
bump(false);
85
}));
86
}
87
else if (cond.kind === ConditionKind.dialogueHeard)
88
{
89
row.append(dialogueHeardConditionFields(cond, dialogueList, () =>
90
{
91
set.all[index].condition = cond;
92
bump(false);
93
}));
94
}
95
else if (cond.kind === ConditionKind.killCount)
96
{
97
row.append(killCountConditionFields(cond, () =>
98
{
99
set.all[index].condition = cond;
100
bump(false);
101
}));
102
}
103
else if (cond.kind === ConditionKind.atTile)
104
{
105
row.append(atTileConditionFields(cond, ctx, () =>
106
{
107
set.all[index].condition = cond;
108
bump(false);
109
}));
110
}
111
else if (
112
cond.kind === ConditionKind.inDimension
113
|| cond.kind === ConditionKind.hasVisitedDimension
114
)
115
{
116
row.append(dimensionConditionField(cond, ctx, () =>
117
{
118
set.all[index].condition = cond;
119
bump(false);
120
}));
121
}
122
else if (cond.kind === ConditionKind.nearTile)
123
{
124
row.append(atTileConditionFields(cond, ctx, () =>
125
{
126
set.all[index].condition = cond;
127
bump(false);
128
}));
129
row.append(miniField("range", cond.range ?? 1, (v) =>
130
{
131
cond.range = Math.max(1, Number(v) || 1);
132
set.all[index].condition = cond;
133
bump(false);
134
}));
135
}
136
else if (cond.kind === ConditionKind.inRect)
137
{
138
row.append(dimensionConditionField(cond, ctx, () =>
139
{
140
set.all[index].condition = cond;
141
bump(false);
142
}));
143
for (const key of ["minTileX", "minTileY", "maxTileX", "maxTileY"])
144
{
145
row.append(miniField(key, cond[key] ?? 0, (v) =>
146
{
147
cond[key] = Number(v) | 0;
148
set.all[index].condition = cond;
149
bump(false);
150
}));
151
}
152
}
153
else if (cond.kind === ConditionKind.atChunk)
154
{
155
row.append(dimensionConditionField(cond, ctx, () =>
156
{
157
set.all[index].condition = cond;
158
bump(false);
159
}));
160
row.append(miniField("chunkX", cond.chunkX ?? 0, (v) =>
161
{
162
cond.chunkX = Number(v) | 0;
163
set.all[index].condition = cond;
164
bump(false);
165
}));
166
row.append(miniField("chunkY", cond.chunkY ?? 0, (v) =>
167
{
168
cond.chunkY = Number(v) | 0;
169
set.all[index].condition = cond;
170
bump(false);
171
}));
172
}
173
else if (cond.kind === ConditionKind.questStepAtLeast)
174
{
175
row.append(miniField("questId", cond.questId ?? "", (v) =>
176
{
177
cond.questId = v;
178
set.all[index].condition = cond;
179
bump(false);
180
}));
181
row.append(miniField("step", cond.step ?? 1, (v) =>
182
{
183
cond.step = Math.max(1, Number(v) || 1);
184
set.all[index].condition = cond;
185
bump(false);
186
}));
187
}
188
else if (cond.kind === ConditionKind.dialogueTrigger)
189
{
190
row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) =>
191
{
192
cond.dialogueId = v;
193
set.all[index].condition = cond;
194
bump(false);
195
}));
196
row.append(miniField("trigger", cond.trigger ?? "", (v) =>
197
{
198
cond.trigger = v;
199
set.all[index].condition = cond;
200
bump(false);
201
}));
202
}
203
else if (
204
cond.kind === ConditionKind.hpAtLeast
205
|| cond.kind === ConditionKind.staminaAtLeast
206
)
207
{
208
row.append(miniField("amount", cond.amount ?? 1, (v) =>
209
{
210
cond.amount = Math.max(0, Number(v) || 0);
211
set.all[index].condition = cond;
212
bump(false);
213
}));
214
}
215
else if (
216
cond.kind === ConditionKind.hpPercentAtLeast
217
|| cond.kind === ConditionKind.staminaPercentAtLeast
218
)
219
{
220
row.append(miniField("percent", cond.percent ?? 50, (v) =>
221
{
222
cond.percent = Math.min(100, Math.max(0, Number(v) || 0));
223
set.all[index].condition = cond;
224
bump(false);
225
}));
226
}
227
else if (cond.kind === ConditionKind.skillLevelAtLeast)
228
{
229
row.append(miniField("skillId", cond.skillId ?? "", (v) =>
230
{
231
cond.skillId = v;
232
set.all[index].condition = cond;
233
bump(false);
234
}));
235
row.append(miniField("level", cond.level ?? 1, (v) =>
236
{
237
cond.level = Math.max(1, Math.min(99, Number(v) || 1));
238
set.all[index].condition = cond;
239
bump(false);
240
}));
241
}
242
else if (cond.kind === ConditionKind.interactBlock)
243
{
244
row.append(atTileConditionFields(cond, ctx, () =>
245
{
246
set.all[index].condition = cond;
247
bump(false);
248
}));
249
row.append(miniField("blockTypeId", cond.blockTypeId ?? "", (v) =>
250
{
251
cond.blockTypeId = v === "" ? undefined : (Number(v) || v);
252
set.all[index].condition = cond;
253
bump(false);
254
}));
255
}
256
else
257
{
258
const json = document.createElement("textarea");
259
json.rows = 3;
260
json.value = JSON.stringify(cond, null, 2);
261
json.addEventListener("change", () =>
262
{
263
try
264
{
265
set.all[index].condition = JSON.parse(json.value);
266
bump(false);
267
}
268
catch
269
{ /* keep typing */ }
270
});
271
row.append(json);
272
}
273
274
const remove = document.createElement("button");
275
remove.type = "button";
276
remove.textContent = "×";
277
remove.addEventListener("click", () =>
278
{
279
set.all.splice(index, 1);
280
bump(true);
281
});
282
row.append(remove);
283
wrap.append(row);
284
});
285
286
const add = document.createElement("button");
287
add.type = "button";
288
add.textContent = "Add clause";
289
add.addEventListener("click", () =>
290
{
291
set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) });
292
bump(true);
293
});
294
wrap.append(add);
295
296
const jsonFallback = document.createElement("details");
297
const summary = document.createElement("summary");
298
summary.textContent = "Edit condition set as JSON";
299
const area = document.createElement("textarea");
300
area.rows = 5;
301
area.value = JSON.stringify(set, null, 2);
302
area.addEventListener("change", () =>
303
{
304
try
305
{
306
onChange(normalizeConditionSet(JSON.parse(area.value)), { remount: true });
307
}
308
catch
309
{ /* ignore */ }
310
});
311
jsonFallback.append(summary, area);
312
wrap.append(jsonFallback);
313
return wrap;
314
}
315
316
/** X/Y inputs, tile summary, and center-editor control for atTile. */
317
function atTileConditionFields (cond, ctx, onChanged)
318
{
319
const wrap = document.createElement("div");
320
wrap.className = "quest-condition-attile";
321
const dimField = dimensionConditionField(cond, ctx, () =>
322
{
323
refreshInfo();
324
onChanged();
325
});
326
const xInput = document.createElement("input");
327
xInput.type = "number";
328
xInput.step = "1";
329
xInput.style.width = "5rem";
330
xInput.value = String(cond.tileX ?? 0);
331
xInput.title = "Tile X";
332
const yInput = document.createElement("input");
333
yInput.type = "number";
334
yInput.step = "1";
335
yInput.style.width = "5rem";
336
yInput.value = String(cond.tileY ?? 0);
337
yInput.title = "Tile Y";
338
const xyRow = document.createElement("div");
339
xyRow.className = "quest-condition-pair";
340
const xLabel = document.createElement("label");
341
xLabel.append(document.createTextNode("X "), xInput);
342
const yLabel = document.createElement("label");
343
yLabel.append(document.createTextNode("Y "), yInput);
344
const centerBtn = document.createElement("button");
345
centerBtn.type = "button";
346
centerBtn.textContent = "Center editor";
347
centerBtn.title = "Pan the world editor to this tile (keeps this UI open)";
348
const info = document.createElement("pre");
349
info.className = "quest-condition-tile-info";
350
351
const refreshInfo = () =>
352
{
353
if (typeof ctx.describeWorldTile === "function")
354
{
355
info.textContent = ctx.describeWorldTile(
356
cond.tileX | 0,
357
cond.tileY | 0,
358
cond.dimensionId
359
);
360
}
361
else
362
{ info.textContent = "Tile inspection unavailable."; }
363
};
364
365
xInput.addEventListener("input", () =>
366
{
367
cond.tileX = Number(xInput.value) | 0;
368
refreshInfo();
369
onChanged();
370
});
371
yInput.addEventListener("input", () =>
372
{
373
cond.tileY = Number(yInput.value) | 0;
374
refreshInfo();
375
onChanged();
376
});
377
centerBtn.addEventListener("click", () =>
378
{
379
ctx.centerEditorOnTile?.(cond.tileX | 0, cond.tileY | 0, cond.dimensionId);
380
refreshInfo();
381
});
382
383
xyRow.append(xLabel, yLabel, centerBtn);
384
wrap.append(dimField, xyRow, info);
385
refreshInfo();
386
return wrap;
387
}
388
389
/** Searchable dimension combobox bound to condition.dimensionId. */
390
function dimensionConditionField (cond, ctx, onChanged)
391
{
392
const root = document.createElement("div");
393
root.className = "quest-condition-dim";
394
const combo = createDimensionCombobox({
395
root,
396
allowCreate: false,
397
placeholder: "Dimension…",
398
onSelect (id)
399
{
400
cond.dimensionId = id || OVERWORLD_ID;
401
onChanged();
402
}
403
});
404
const options = typeof ctx.getDimensionOptions === "function"
405
? ctx.getDimensionOptions()
406
: [{ id: OVERWORLD_ID, label: "Overworld" }];
407
combo.setOptions(options);
408
combo.setValue(cond.dimensionId || OVERWORLD_ID);
409
return root;
410
}
411
412
/** Mob selector + kill quantity for killCount conditions. */
413
function killCountConditionFields (cond, onChanged)
414
{
415
const wrap = document.createElement("div");
416
wrap.className = "quest-condition-pair";
417
const mobSelect = document.createElement("select");
418
for (const def of listSpawnableMobTypes())
419
{
420
const opt = document.createElement("option");
421
opt.value = def.mobTypeId;
422
opt.textContent = def.displayName ?? def.mobTypeId;
423
if (def.mobTypeId === cond.mobTypeId)
424
{ opt.selected = true; }
425
mobSelect.append(opt);
426
}
427
if (cond.mobTypeId && ![...mobSelect.options].some((o) => o.value === cond.mobTypeId))
428
{
429
const missing = document.createElement("option");
430
missing.value = cond.mobTypeId;
431
missing.textContent = `${cond.mobTypeId} (missing)`;
432
missing.selected = true;
433
mobSelect.append(missing);
434
}
435
if (!cond.mobTypeId && mobSelect.options.length)
436
{
437
cond.mobTypeId = mobSelect.options[0].value;
438
mobSelect.options[0].selected = true;
439
}
440
const qty = document.createElement("input");
441
qty.type = "number";
442
qty.min = "1";
443
qty.step = "1";
444
qty.style.width = "5rem";
445
qty.value = String(Math.max(1, Number(cond.count) || 1));
446
qty.title = "Kill count";
447
mobSelect.addEventListener("change", () =>
448
{
449
cond.mobTypeId = mobSelect.value || undefined;
450
onChanged();
451
});
452
qty.addEventListener("input", () =>
453
{
454
cond.count = Math.max(1, Number(qty.value) || 1);
455
onChanged();
456
});
457
wrap.append(mobSelect, qty);
458
return wrap;
459
}
460
461
/** Dialogue picker + step-id dropdown from that tree. */
462
function dialogueHeardConditionFields (cond, dialogueList, onChanged)
463
{
464
const wrap = document.createElement("div");
465
wrap.className = "quest-condition-pair";
466
const dialogueSelect = document.createElement("select");
467
const blank = document.createElement("option");
468
blank.value = "";
469
blank.textContent = "Select dialogue…";
470
dialogueSelect.append(blank);
471
for (const tree of dialogueList)
472
{
473
const opt = document.createElement("option");
474
opt.value = tree.dialogueId;
475
opt.textContent = tree.label ? `${tree.label} (${tree.dialogueId})` : tree.dialogueId;
476
if (tree.dialogueId === cond.dialogueId)
477
{ opt.selected = true; }
478
dialogueSelect.append(opt);
479
}
480
if (cond.dialogueId && !dialogueList.some((d) => d.dialogueId === cond.dialogueId))
481
{
482
const missing = document.createElement("option");
483
missing.value = cond.dialogueId;
484
missing.textContent = `${cond.dialogueId} (missing)`;
485
missing.selected = true;
486
dialogueSelect.append(missing);
487
}
488
489
const stepSelect = document.createElement("select");
490
const fillSteps = () =>
491
{
492
const tree = dialogueList.find((d) => d.dialogueId === cond.dialogueId) ?? null;
493
stepSelect.replaceChildren();
494
const steps = tree?.steps ?? [];
495
if (!steps.length)
496
{
497
const empty = document.createElement("option");
498
empty.value = cond.stepId ?? "";
499
empty.textContent = cond.stepId ? String(cond.stepId) : "No steps";
500
empty.selected = true;
501
stepSelect.append(empty);
502
return;
503
}
504
let matched = false;
505
for (const step of steps)
506
{
507
const opt = document.createElement("option");
508
opt.value = step.stepId;
509
opt.textContent = step.label
510
? `${step.label} (${step.stepId})`
511
: step.stepId;
512
if (step.stepId === cond.stepId)
513
{
514
opt.selected = true;
515
matched = true;
516
}
517
stepSelect.append(opt);
518
}
519
if (!matched && cond.stepId)
520
{
521
const fallback = document.createElement("option");
522
fallback.value = cond.stepId;
523
fallback.textContent = `${cond.stepId} (missing)`;
524
fallback.selected = true;
525
stepSelect.append(fallback);
526
}
527
else if (!matched)
528
{
529
cond.stepId = steps[0].stepId;
530
stepSelect.options[0].selected = true;
531
}
532
};
533
fillSteps();
534
535
dialogueSelect.addEventListener("change", () =>
536
{
537
cond.dialogueId = dialogueSelect.value;
538
const tree = dialogueList.find((d) => d.dialogueId === cond.dialogueId);
539
cond.stepId = tree?.steps?.[0]?.stepId ?? "";
540
fillSteps();
541
onChanged();
542
});
543
stepSelect.addEventListener("change", () =>
544
{
545
cond.stepId = stepSelect.value;
546
onChanged();
547
});
548
wrap.append(dialogueSelect, stepSelect);
549
return wrap;
550
}
551
552
/** Quest picker + state dropdown from that quest's steps. */
553
function questStateConditionFields (cond, questList, onChanged)
554
{
555
const wrap = document.createElement("div");
556
wrap.className = "quest-condition-pair";
557
const questSelect = document.createElement("select");
558
const blank = document.createElement("option");
559
blank.value = "";
560
blank.textContent = "Select quest…";
561
questSelect.append(blank);
562
for (const quest of questList)
563
{
564
const opt = document.createElement("option");
565
opt.value = quest.questId;
566
opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId;
567
if (quest.questId === cond.questId)
568
{ opt.selected = true; }
569
questSelect.append(opt);
570
}
571
if (cond.questId && !questList.some((q) => q.questId === cond.questId))
572
{
573
const missing = document.createElement("option");
574
missing.value = cond.questId;
575
missing.textContent = `${cond.questId} (missing)`;
576
missing.selected = true;
577
questSelect.append(missing);
578
}
579
580
const stateSelect = document.createElement("select");
581
const fillStates = () =>
582
{
583
const quest = questList.find((q) => q.questId === cond.questId) ?? null;
584
stateSelect.replaceChildren();
585
const options = [
586
{ value: "not-started", label: "not-started" },
587
...((quest?.steps ?? []).map((step, index) => ({
588
value: String(index + 1),
589
label: `Step ${index + 1}: ${step.title || step.stepId}`
590
}))),
591
{ value: "completed", label: "completed" }
592
];
593
let matched = false;
594
for (const entry of options)
595
{
596
const opt = document.createElement("option");
597
opt.value = entry.value;
598
opt.textContent = entry.label;
599
const current = cond.state ?? "not-started";
600
const currentKey = current === "not-started" || current === "completed"
601
? current
602
: String(Number(current) || current);
603
if (entry.value === currentKey)
604
{
605
opt.selected = true;
606
matched = true;
607
}
608
stateSelect.append(opt);
609
}
610
if (!matched)
611
{
612
const fallback = document.createElement("option");
613
fallback.value = String(cond.state ?? "not-started");
614
fallback.textContent = String(cond.state ?? "not-started");
615
fallback.selected = true;
616
stateSelect.append(fallback);
617
}
618
};
619
fillStates();
620
621
questSelect.addEventListener("change", () =>
622
{
623
cond.questId = questSelect.value;
624
cond.state = "not-started";
625
fillStates();
626
onChanged();
627
});
628
stateSelect.addEventListener("change", () =>
629
{
630
const raw = stateSelect.value;
631
if (raw === "not-started" || raw === "completed")
632
{ cond.state = raw; }
633
else
634
{ cond.state = Math.max(1, Number(raw) | 0); }
635
onChanged();
636
});
637
wrap.append(questSelect, stateSelect);
638
return wrap;
639
}
640
641
/** Compact searchable item picker for hasItem conditions. */
642
function itemConditionPicker (cond, onPicked)
643
{
644
const wrap = document.createElement("div");
645
wrap.className = "quest-condition-item-picker";
646
const pickBtn = document.createElement("button");
647
pickBtn.type = "button";
648
const refreshLabel = () =>
649
{
650
const def = itemDefinition(cond.itemId);
651
pickBtn.textContent = def?.displayName
652
?? (cond.itemId ? `Item #${cond.itemId}` : "Pick item…");
653
pickBtn.title = cond.itemId
654
? `${def?.key ?? "item"} · #${cond.itemId}`
655
: "Choose an item";
656
};
657
refreshLabel();
658
const searchWrap = document.createElement("div");
659
searchWrap.className = "dialogue-reward-item-search";
660
searchWrap.hidden = true;
661
const searchInput = document.createElement("input");
662
searchInput.type = "search";
663
searchInput.placeholder = "Search items…";
664
searchInput.autocomplete = "off";
665
const searchResults = document.createElement("div");
666
searchResults.className = "dialogue-reward-item-results";
667
668
const renderMatches = (query) =>
669
{
670
searchResults.replaceChildren();
671
const q = String(query ?? "").trim().toLowerCase();
672
const matches = listAllItemPickerEntries().filter((item) =>
673
{
674
if (!q)
675
{ return true; }
676
return item.displayName.toLowerCase().includes(q)
677
|| item.key.toLowerCase().includes(q)
678
|| String(item.itemId).includes(q);
679
}).slice(0, 40);
680
if (!matches.length)
681
{
682
searchResults.textContent = "No matching items.";
683
return;
684
}
685
for (const item of matches)
686
{
687
const row = document.createElement("button");
688
row.type = "button";
689
row.className = "shop-item-search-row";
690
const name = document.createElement("span");
691
name.className = "shop-item-search-row-name";
692
name.textContent = item.displayName;
693
const key = document.createElement("span");
694
key.className = "shop-item-search-row-key";
695
key.textContent = `${item.key} · #${item.itemId}`;
696
row.append(name, key);
697
row.addEventListener("click", () =>
698
{
699
cond.itemId = item.itemId;
700
refreshLabel();
701
searchWrap.hidden = true;
702
onPicked();
703
});
704
searchResults.append(row);
705
}
706
};
707
708
pickBtn.addEventListener("click", () =>
709
{
710
searchWrap.hidden = !searchWrap.hidden;
711
if (!searchWrap.hidden)
712
{
713
searchInput.value = "";
714
renderMatches("");
715
searchInput.focus();
716
}
717
});
718
searchInput.addEventListener("input", () => renderMatches(searchInput.value));
719
searchWrap.append(searchInput, searchResults);
720
wrap.append(pickBtn, searchWrap);
721
return wrap;
722
}
723
724
function miniField (label, value, onChange)
725
{
726
const wrap = document.createElement("label");
727
wrap.textContent = `${label} `;
728
const input = document.createElement("input");
729
input.type = "text";
730
input.value = String(value ?? "");
731
input.style.width = "7rem";
732
input.addEventListener("input", () => onChange(input.value));
733
wrap.append(input);
734
return wrap;
735
}
736
737
function defaultCondition (kind)
738
{
739
switch (kind)
740
{
741
case ConditionKind.hasItem:
742
return { kind, itemId: 1, quantity: 1 };
743
case ConditionKind.questState:
744
return { kind, questId: "", state: "not-started" };
745
case ConditionKind.dialogueHeard:
746
return { kind, dialogueId: "", stepId: "" };
747
case ConditionKind.dialogueTrigger:
748
return { kind, dialogueId: "", trigger: "" };
749
case ConditionKind.killCount:
750
return { kind, mobTypeId: "deer", count: 1 };
751
case ConditionKind.atTile:
752
case ConditionKind.nearTile:
753
return { kind, dimensionId: OVERWORLD_ID, tileX: 0, tileY: 0, ...(kind === ConditionKind.nearTile ? { range: 1 } : {}) };
754
case ConditionKind.inRect:
755
return { kind, dimensionId: OVERWORLD_ID, minTileX: 0, minTileY: 0, maxTileX: 0, maxTileY: 0 };
756
case ConditionKind.atChunk:
757
return { kind, dimensionId: OVERWORLD_ID, chunkX: 0, chunkY: 0 };
758
case ConditionKind.inDimension:
759
case ConditionKind.hasVisitedDimension:
760
return { kind, dimensionId: OVERWORLD_ID };
761
case ConditionKind.questStepAtLeast:
762
return { kind, questId: "", step: 1 };
763
case ConditionKind.hpAtLeast:
764
case ConditionKind.staminaAtLeast:
765
return { kind, amount: 1 };
766
case ConditionKind.hpPercentAtLeast:
767
case ConditionKind.staminaPercentAtLeast:
768
return { kind, percent: 50 };
769
case ConditionKind.skillLevelAtLeast:
770
return { kind, skillId: "attack", level: 1 };
771
case ConditionKind.interactBlock:
772
return { kind, dimensionId: OVERWORLD_ID, tileX: 0, tileY: 0 };
773
default:
774
return { kind };
775
}
776
}
@@ -0,0 +1,776 @@1
import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";2
import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";3
import { listSpawnableMobTypes } from "/shared/definitions/mobs.js";4
import { createDimensionCombobox } from "./dimensionCombobox.js";5
import { OVERWORLD_ID } from "/shared/world/dimensions.js";6
7
/** All condition kinds available in the shared editor UI. */8
export const CONDITION_EDITOR_KINDS = Object.freeze(Object.values(ConditionKind));9
10
export { emptyConditionSet, normalizeConditionSet, ConditionKind };11
12
export function renderConditionSet (when, onChange, ctx = {})13
{14
const wrap = document.createElement("div");15
const set = normalizeConditionSet(when);16
const bump = (remount = true) => onChange(set, { remount });17
const questList = Array.isArray(ctx.quests) ? ctx.quests : [];18
const dialogueList = Array.isArray(ctx.dialogues) ? ctx.dialogues : [];19
const title = document.createElement("strong");20
title.textContent = "When (all of)";21
wrap.append(title);22
23
set.all.forEach((clause, index) =>24
{25
const row = document.createElement("div");26
row.className = "content-editor-clause";27
const notLabel = document.createElement("label");28
const notBox = document.createElement("input");29
notBox.type = "checkbox";30
notBox.checked = !!clause.not;31
notBox.addEventListener("change", () =>32
{33
set.all[index].not = notBox.checked;34
bump(false);35
});36
notLabel.append(notBox, document.createTextNode(" NOT"));37
row.append(notLabel);38
39
const kind = document.createElement("select");40
for (const k of CONDITION_EDITOR_KINDS)41
{42
const opt = document.createElement("option");43
opt.value = k;44
opt.textContent = k;45
if ((clause.condition?.kind ?? "") === k)46
{ opt.selected = true; }47
kind.append(opt);48
}49
const otherOpt = document.createElement("option");50
otherOpt.value = "__other__";51
otherOpt.textContent = "(other / JSON)";52
if (!CONDITION_EDITOR_KINDS.includes(clause.condition?.kind))53
{ otherOpt.selected = true; }54
kind.append(otherOpt);55
kind.addEventListener("change", () =>56
{57
if (kind.value === "__other__")58
{ return; }59
set.all[index].condition = defaultCondition(kind.value);60
bump(true);61
});62
row.append(kind);63
64
const cond = clause.condition ?? { kind: ConditionKind.hasItem };65
if (cond.kind === ConditionKind.hasItem)66
{67
row.append(itemConditionPicker(cond, () =>68
{69
set.all[index].condition = cond;70
bump(false);71
}));72
row.append(miniField("qty", cond.quantity ?? 1, (v) =>73
{74
cond.quantity = Number(v) || 1;75
set.all[index].condition = cond;76
bump(false);77
}));78
}79
else if (cond.kind === ConditionKind.questState)80
{81
row.append(questStateConditionFields(cond, questList, () =>82
{83
set.all[index].condition = cond;84
bump(false);85
}));86
}87
else if (cond.kind === ConditionKind.dialogueHeard)88
{89
row.append(dialogueHeardConditionFields(cond, dialogueList, () =>90
{91
set.all[index].condition = cond;92
bump(false);93
}));94
}95
else if (cond.kind === ConditionKind.killCount)96
{97
row.append(killCountConditionFields(cond, () =>98
{99
set.all[index].condition = cond;100
bump(false);101
}));102
}103
else if (cond.kind === ConditionKind.atTile)104
{105
row.append(atTileConditionFields(cond, ctx, () =>106
{107
set.all[index].condition = cond;108
bump(false);109
}));110
}111
else if (112
cond.kind === ConditionKind.inDimension113
|| cond.kind === ConditionKind.hasVisitedDimension114
)115
{116
row.append(dimensionConditionField(cond, ctx, () =>117
{118
set.all[index].condition = cond;119
bump(false);120
}));121
}122
else if (cond.kind === ConditionKind.nearTile)123
{124
row.append(atTileConditionFields(cond, ctx, () =>125
{126
set.all[index].condition = cond;127
bump(false);128
}));129
row.append(miniField("range", cond.range ?? 1, (v) =>130
{131
cond.range = Math.max(1, Number(v) || 1);132
set.all[index].condition = cond;133
bump(false);134
}));135
}136
else if (cond.kind === ConditionKind.inRect)137
{138
row.append(dimensionConditionField(cond, ctx, () =>139
{140
set.all[index].condition = cond;141
bump(false);142
}));143
for (const key of ["minTileX", "minTileY", "maxTileX", "maxTileY"])144
{145
row.append(miniField(key, cond[key] ?? 0, (v) =>146
{147
cond[key] = Number(v) | 0;148
set.all[index].condition = cond;149
bump(false);150
}));151
}152
}153
else if (cond.kind === ConditionKind.atChunk)154
{155
row.append(dimensionConditionField(cond, ctx, () =>156
{157
set.all[index].condition = cond;158
bump(false);159
}));160
row.append(miniField("chunkX", cond.chunkX ?? 0, (v) =>161
{162
cond.chunkX = Number(v) | 0;163
set.all[index].condition = cond;164
bump(false);165
}));166
row.append(miniField("chunkY", cond.chunkY ?? 0, (v) =>167
{168
cond.chunkY = Number(v) | 0;169
set.all[index].condition = cond;170
bump(false);171
}));172
}173
else if (cond.kind === ConditionKind.questStepAtLeast)174
{175
row.append(miniField("questId", cond.questId ?? "", (v) =>176
{177
cond.questId = v;178
set.all[index].condition = cond;179
bump(false);180
}));181
row.append(miniField("step", cond.step ?? 1, (v) =>182
{183
cond.step = Math.max(1, Number(v) || 1);184
set.all[index].condition = cond;185
bump(false);186
}));187
}188
else if (cond.kind === ConditionKind.dialogueTrigger)189
{190
row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) =>191
{192
cond.dialogueId = v;193
set.all[index].condition = cond;194
bump(false);195
}));196
row.append(miniField("trigger", cond.trigger ?? "", (v) =>197
{198
cond.trigger = v;199
set.all[index].condition = cond;200
bump(false);201
}));202
}203
else if (204
cond.kind === ConditionKind.hpAtLeast205
|| cond.kind === ConditionKind.staminaAtLeast206
)207
{208
row.append(miniField("amount", cond.amount ?? 1, (v) =>209
{210
cond.amount = Math.max(0, Number(v) || 0);211
set.all[index].condition = cond;212
bump(false);213
}));214
}215
else if (216
cond.kind === ConditionKind.hpPercentAtLeast217
|| cond.kind === ConditionKind.staminaPercentAtLeast218
)219
{220
row.append(miniField("percent", cond.percent ?? 50, (v) =>221
{222
cond.percent = Math.min(100, Math.max(0, Number(v) || 0));223
set.all[index].condition = cond;224
bump(false);225
}));226
}227
else if (cond.kind === ConditionKind.skillLevelAtLeast)228
{229
row.append(miniField("skillId", cond.skillId ?? "", (v) =>230
{231
cond.skillId = v;232
set.all[index].condition = cond;233
bump(false);234
}));235
row.append(miniField("level", cond.level ?? 1, (v) =>236
{237
cond.level = Math.max(1, Math.min(99, Number(v) || 1));238
set.all[index].condition = cond;239
bump(false);240
}));241
}242
else if (cond.kind === ConditionKind.interactBlock)243
{244
row.append(atTileConditionFields(cond, ctx, () =>245
{246
set.all[index].condition = cond;247
bump(false);248
}));249
row.append(miniField("blockTypeId", cond.blockTypeId ?? "", (v) =>250
{251
cond.blockTypeId = v === "" ? undefined : (Number(v) || v);252
set.all[index].condition = cond;253
bump(false);254
}));255
}256
else257
{258
const json = document.createElement("textarea");259
json.rows = 3;260
json.value = JSON.stringify(cond, null, 2);261
json.addEventListener("change", () =>262
{263
try264
{265
set.all[index].condition = JSON.parse(json.value);266
bump(false);267
}268
catch269
{ /* keep typing */ }270
});271
row.append(json);272
}273
274
const remove = document.createElement("button");275
remove.type = "button";276
remove.textContent = "×";277
remove.addEventListener("click", () =>278
{279
set.all.splice(index, 1);280
bump(true);281
});282
row.append(remove);283
wrap.append(row);284
});285
286
const add = document.createElement("button");287
add.type = "button";288
add.textContent = "Add clause";289
add.addEventListener("click", () =>290
{291
set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) });292
bump(true);293
});294
wrap.append(add);295
296
const jsonFallback = document.createElement("details");297
const summary = document.createElement("summary");298
summary.textContent = "Edit condition set as JSON";299
const area = document.createElement("textarea");300
area.rows = 5;301
area.value = JSON.stringify(set, null, 2);302
area.addEventListener("change", () =>303
{304
try305
{306
onChange(normalizeConditionSet(JSON.parse(area.value)), { remount: true });307
}308
catch309
{ /* ignore */ }310
});311
jsonFallback.append(summary, area);312
wrap.append(jsonFallback);313
return wrap;314
}315
316
/** X/Y inputs, tile summary, and center-editor control for atTile. */317
function atTileConditionFields (cond, ctx, onChanged)318
{319
const wrap = document.createElement("div");320
wrap.className = "quest-condition-attile";321
const dimField = dimensionConditionField(cond, ctx, () =>322
{323
refreshInfo();324
onChanged();325
});326
const xInput = document.createElement("input");327
xInput.type = "number";328
xInput.step = "1";329
xInput.style.width = "5rem";330
xInput.value = String(cond.tileX ?? 0);331
xInput.title = "Tile X";332
const yInput = document.createElement("input");333
yInput.type = "number";334
yInput.step = "1";335
yInput.style.width = "5rem";336
yInput.value = String(cond.tileY ?? 0);337
yInput.title = "Tile Y";338
const xyRow = document.createElement("div");339
xyRow.className = "quest-condition-pair";340
const xLabel = document.createElement("label");341
xLabel.append(document.createTextNode("X "), xInput);342
const yLabel = document.createElement("label");343
yLabel.append(document.createTextNode("Y "), yInput);344
const centerBtn = document.createElement("button");345
centerBtn.type = "button";346
centerBtn.textContent = "Center editor";347
centerBtn.title = "Pan the world editor to this tile (keeps this UI open)";348
const info = document.createElement("pre");349
info.className = "quest-condition-tile-info";350
351
const refreshInfo = () =>352
{353
if (typeof ctx.describeWorldTile === "function")354
{355
info.textContent = ctx.describeWorldTile(356
cond.tileX | 0,357
cond.tileY | 0,358
cond.dimensionId359
);360
}361
else362
{ info.textContent = "Tile inspection unavailable."; }363
};364
365
xInput.addEventListener("input", () =>366
{367
cond.tileX = Number(xInput.value) | 0;368
refreshInfo();369
onChanged();370
});371
yInput.addEventListener("input", () =>372
{373
cond.tileY = Number(yInput.value) | 0;374
refreshInfo();375
onChanged();376
});377
centerBtn.addEventListener("click", () =>378
{379
ctx.centerEditorOnTile?.(cond.tileX | 0, cond.tileY | 0, cond.dimensionId);380
refreshInfo();381
});382
383
xyRow.append(xLabel, yLabel, centerBtn);384
wrap.append(dimField, xyRow, info);385
refreshInfo();386
return wrap;387
}388
389
/** Searchable dimension combobox bound to condition.dimensionId. */390
function dimensionConditionField (cond, ctx, onChanged)391
{392
const root = document.createElement("div");393
root.className = "quest-condition-dim";394
const combo = createDimensionCombobox({395
root,396
allowCreate: false,397
placeholder: "Dimension…",398
onSelect (id)399
{400
cond.dimensionId = id || OVERWORLD_ID;401
onChanged();402
}403
});404
const options = typeof ctx.getDimensionOptions === "function"405
? ctx.getDimensionOptions()406
: [{ id: OVERWORLD_ID, label: "Overworld" }];407
combo.setOptions(options);408
combo.setValue(cond.dimensionId || OVERWORLD_ID);409
return root;410
}411
412
/** Mob selector + kill quantity for killCount conditions. */413
function killCountConditionFields (cond, onChanged)414
{415
const wrap = document.createElement("div");416
wrap.className = "quest-condition-pair";417
const mobSelect = document.createElement("select");418
for (const def of listSpawnableMobTypes())419
{420
const opt = document.createElement("option");421
opt.value = def.mobTypeId;422
opt.textContent = def.displayName ?? def.mobTypeId;423
if (def.mobTypeId === cond.mobTypeId)424
{ opt.selected = true; }425
mobSelect.append(opt);426
}427
if (cond.mobTypeId && ![...mobSelect.options].some((o) => o.value === cond.mobTypeId))428
{429
const missing = document.createElement("option");430
missing.value = cond.mobTypeId;431
missing.textContent = `${cond.mobTypeId} (missing)`;432
missing.selected = true;433
mobSelect.append(missing);434
}435
if (!cond.mobTypeId && mobSelect.options.length)436
{437
cond.mobTypeId = mobSelect.options[0].value;438
mobSelect.options[0].selected = true;439
}440
const qty = document.createElement("input");441
qty.type = "number";442
qty.min = "1";443
qty.step = "1";444
qty.style.width = "5rem";445
qty.value = String(Math.max(1, Number(cond.count) || 1));446
qty.title = "Kill count";447
mobSelect.addEventListener("change", () =>448
{449
cond.mobTypeId = mobSelect.value || undefined;450
onChanged();451
});452
qty.addEventListener("input", () =>453
{454
cond.count = Math.max(1, Number(qty.value) || 1);455
onChanged();456
});457
wrap.append(mobSelect, qty);458
return wrap;459
}460
461
/** Dialogue picker + step-id dropdown from that tree. */462
function dialogueHeardConditionFields (cond, dialogueList, onChanged)463
{464
const wrap = document.createElement("div");465
wrap.className = "quest-condition-pair";466
const dialogueSelect = document.createElement("select");467
const blank = document.createElement("option");468
blank.value = "";469
blank.textContent = "Select dialogue…";470
dialogueSelect.append(blank);471
for (const tree of dialogueList)472
{473
const opt = document.createElement("option");474
opt.value = tree.dialogueId;475
opt.textContent = tree.label ? `${tree.label} (${tree.dialogueId})` : tree.dialogueId;476
if (tree.dialogueId === cond.dialogueId)477
{ opt.selected = true; }478
dialogueSelect.append(opt);479
}480
if (cond.dialogueId && !dialogueList.some((d) => d.dialogueId === cond.dialogueId))481
{482
const missing = document.createElement("option");483
missing.value = cond.dialogueId;484
missing.textContent = `${cond.dialogueId} (missing)`;485
missing.selected = true;486
dialogueSelect.append(missing);487
}488
489
const stepSelect = document.createElement("select");490
const fillSteps = () =>491
{492
const tree = dialogueList.find((d) => d.dialogueId === cond.dialogueId) ?? null;493
stepSelect.replaceChildren();494
const steps = tree?.steps ?? [];495
if (!steps.length)496
{497
const empty = document.createElement("option");498
empty.value = cond.stepId ?? "";499
empty.textContent = cond.stepId ? String(cond.stepId) : "No steps";500
empty.selected = true;501
stepSelect.append(empty);502
return;503
}504
let matched = false;505
for (const step of steps)506
{507
const opt = document.createElement("option");508
opt.value = step.stepId;509
opt.textContent = step.label510
? `${step.label} (${step.stepId})`511
: step.stepId;512
if (step.stepId === cond.stepId)513
{514
opt.selected = true;515
matched = true;516
}517
stepSelect.append(opt);518
}519
if (!matched && cond.stepId)520
{521
const fallback = document.createElement("option");522
fallback.value = cond.stepId;523
fallback.textContent = `${cond.stepId} (missing)`;524
fallback.selected = true;525
stepSelect.append(fallback);526
}527
else if (!matched)528
{529
cond.stepId = steps[0].stepId;530
stepSelect.options[0].selected = true;531
}532
};533
fillSteps();534
535
dialogueSelect.addEventListener("change", () =>536
{537
cond.dialogueId = dialogueSelect.value;538
const tree = dialogueList.find((d) => d.dialogueId === cond.dialogueId);539
cond.stepId = tree?.steps?.[0]?.stepId ?? "";540
fillSteps();541
onChanged();542
});543
stepSelect.addEventListener("change", () =>544
{545
cond.stepId = stepSelect.value;546
onChanged();547
});548
wrap.append(dialogueSelect, stepSelect);549
return wrap;550
}551
552
/** Quest picker + state dropdown from that quest's steps. */553
function questStateConditionFields (cond, questList, onChanged)554
{555
const wrap = document.createElement("div");556
wrap.className = "quest-condition-pair";557
const questSelect = document.createElement("select");558
const blank = document.createElement("option");559
blank.value = "";560
blank.textContent = "Select quest…";561
questSelect.append(blank);562
for (const quest of questList)563
{564
const opt = document.createElement("option");565
opt.value = quest.questId;566
opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId;567
if (quest.questId === cond.questId)568
{ opt.selected = true; }569
questSelect.append(opt);570
}571
if (cond.questId && !questList.some((q) => q.questId === cond.questId))572
{573
const missing = document.createElement("option");574
missing.value = cond.questId;575
missing.textContent = `${cond.questId} (missing)`;576
missing.selected = true;577
questSelect.append(missing);578
}579
580
const stateSelect = document.createElement("select");581
const fillStates = () =>582
{583
const quest = questList.find((q) => q.questId === cond.questId) ?? null;584
stateSelect.replaceChildren();585
const options = [586
{ value: "not-started", label: "not-started" },587
...((quest?.steps ?? []).map((step, index) => ({588
value: String(index + 1),589
label: `Step ${index + 1}: ${step.title || step.stepId}`590
}))),591
{ value: "completed", label: "completed" }592
];593
let matched = false;594
for (const entry of options)595
{596
const opt = document.createElement("option");597
opt.value = entry.value;598
opt.textContent = entry.label;599
const current = cond.state ?? "not-started";600
const currentKey = current === "not-started" || current === "completed"601
? current602
: String(Number(current) || current);603
if (entry.value === currentKey)604
{605
opt.selected = true;606
matched = true;607
}608
stateSelect.append(opt);609
}610
if (!matched)611
{612
const fallback = document.createElement("option");613
fallback.value = String(cond.state ?? "not-started");614
fallback.textContent = String(cond.state ?? "not-started");615
fallback.selected = true;616
stateSelect.append(fallback);617
}618
};619
fillStates();620
621
questSelect.addEventListener("change", () =>622
{623
cond.questId = questSelect.value;624
cond.state = "not-started";625
fillStates();626
onChanged();627
});628
stateSelect.addEventListener("change", () =>629
{630
const raw = stateSelect.value;631
if (raw === "not-started" || raw === "completed")632
{ cond.state = raw; }633
else634
{ cond.state = Math.max(1, Number(raw) | 0); }635
onChanged();636
});637
wrap.append(questSelect, stateSelect);638
return wrap;639
}640
641
/** Compact searchable item picker for hasItem conditions. */642
function itemConditionPicker (cond, onPicked)643
{644
const wrap = document.createElement("div");645
wrap.className = "quest-condition-item-picker";646
const pickBtn = document.createElement("button");647
pickBtn.type = "button";648
const refreshLabel = () =>649
{650
const def = itemDefinition(cond.itemId);651
pickBtn.textContent = def?.displayName652
?? (cond.itemId ? `Item #${cond.itemId}` : "Pick item…");653
pickBtn.title = cond.itemId654
? `${def?.key ?? "item"} · #${cond.itemId}`655
: "Choose an item";656
};657
refreshLabel();658
const searchWrap = document.createElement("div");659
searchWrap.className = "dialogue-reward-item-search";660
searchWrap.hidden = true;661
const searchInput = document.createElement("input");662
searchInput.type = "search";663
searchInput.placeholder = "Search items…";664
searchInput.autocomplete = "off";665
const searchResults = document.createElement("div");666
searchResults.className = "dialogue-reward-item-results";667
668
const renderMatches = (query) =>669
{670
searchResults.replaceChildren();671
const q = String(query ?? "").trim().toLowerCase();672
const matches = listAllItemPickerEntries().filter((item) =>673
{674
if (!q)675
{ return true; }676
return item.displayName.toLowerCase().includes(q)677
|| item.key.toLowerCase().includes(q)678
|| String(item.itemId).includes(q);679
}).slice(0, 40);680
if (!matches.length)681
{682
searchResults.textContent = "No matching items.";683
return;684
}685
for (const item of matches)686
{687
const row = document.createElement("button");688
row.type = "button";689
row.className = "shop-item-search-row";690
const name = document.createElement("span");691
name.className = "shop-item-search-row-name";692
name.textContent = item.displayName;693
const key = document.createElement("span");694
key.className = "shop-item-search-row-key";695
key.textContent = `${item.key} · #${item.itemId}`;696
row.append(name, key);697
row.addEventListener("click", () =>698
{699
cond.itemId = item.itemId;700
refreshLabel();701
searchWrap.hidden = true;702
onPicked();703
});704
searchResults.append(row);705
}706
};707
708
pickBtn.addEventListener("click", () =>709
{710
searchWrap.hidden = !searchWrap.hidden;711
if (!searchWrap.hidden)712
{713
searchInput.value = "";714
renderMatches("");715
searchInput.focus();716
}717
});718
searchInput.addEventListener("input", () => renderMatches(searchInput.value));719
searchWrap.append(searchInput, searchResults);720
wrap.append(pickBtn, searchWrap);721
return wrap;722
}723
724
function miniField (label, value, onChange)725
{726
const wrap = document.createElement("label");727
wrap.textContent = `${label} `;728
const input = document.createElement("input");729
input.type = "text";730
input.value = String(value ?? "");731
input.style.width = "7rem";732
input.addEventListener("input", () => onChange(input.value));733
wrap.append(input);734
return wrap;735
}736
737
function defaultCondition (kind)738
{739
switch (kind)740
{741
case ConditionKind.hasItem:742
return { kind, itemId: 1, quantity: 1 };743
case ConditionKind.questState:744
return { kind, questId: "", state: "not-started" };745
case ConditionKind.dialogueHeard:746
return { kind, dialogueId: "", stepId: "" };747
case ConditionKind.dialogueTrigger:748
return { kind, dialogueId: "", trigger: "" };749
case ConditionKind.killCount:750
return { kind, mobTypeId: "deer", count: 1 };751
case ConditionKind.atTile:752
case ConditionKind.nearTile:753
return { kind, dimensionId: OVERWORLD_ID, tileX: 0, tileY: 0, ...(kind === ConditionKind.nearTile ? { range: 1 } : {}) };754
case ConditionKind.inRect:755
return { kind, dimensionId: OVERWORLD_ID, minTileX: 0, minTileY: 0, maxTileX: 0, maxTileY: 0 };756
case ConditionKind.atChunk:757
return { kind, dimensionId: OVERWORLD_ID, chunkX: 0, chunkY: 0 };758
case ConditionKind.inDimension:759
case ConditionKind.hasVisitedDimension:760
return { kind, dimensionId: OVERWORLD_ID };761
case ConditionKind.questStepAtLeast:762
return { kind, questId: "", step: 1 };763
case ConditionKind.hpAtLeast:764
case ConditionKind.staminaAtLeast:765
return { kind, amount: 1 };766
case ConditionKind.hpPercentAtLeast:767
case ConditionKind.staminaPercentAtLeast:768
return { kind, percent: 50 };769
case ConditionKind.skillLevelAtLeast:770
return { kind, skillId: "attack", level: 1 };771
case ConditionKind.interactBlock:772
return { kind, dimensionId: OVERWORLD_ID, tileX: 0, tileY: 0 };773
default:774
return { kind };775
}776
}@@ -0,0 +1,344 @@
1
/**
2
* Client-only dialogue tree walk for the world editor.
3
* Default player look; triggers use the same choice flow; branches are freely selectable.
4
*/
5
import { itemDefinition } from "/shared/definitions/items.js";
6
import { evaluateConditionSet } from "/shared/quests/conditions.js";
7
import {
8
formatDialogueRewardMessage,
9
formatDialogueQuestRewardMessage
10
} from "/shared/quests/dialogueRewards.js";
11
12
const ICON = 48;
13
14
/**
15
* @param {{
16
* getTree: () => object | null,
17
* getQuestTitle?: (questId: string) => string
18
* }} options
19
*/
20
export function initDialogueSimulate ({ getTree, getQuestTitle = null } = {})
21
{
22
const backdrop = document.getElementById("dialogue-simulate-backdrop");
23
const panel = document.getElementById("dialogue-simulate-panel");
24
const titleEl = document.getElementById("dialogue-simulate-title");
25
const linesEl = document.getElementById("dialogue-simulate-lines");
26
const actionsEl = document.getElementById("dialogue-simulate-actions");
27
const closeBtn = document.getElementById("dialogue-simulate-close");
28
29
/** @type {null | {
30
* tree: object,
31
* stepId: string,
32
* lineIndex: number,
33
* rewardMessages: string[]|null,
34
* rewardIndex: number
35
* }} */
36
let session = null;
37
38
function show (visible)
39
{
40
if (backdrop)
41
{ backdrop.hidden = !visible; }
42
if (panel)
43
{ panel.hidden = !visible; }
44
if (!visible)
45
{ session = null; }
46
}
47
48
function speakerIcon (speaker)
49
{
50
const canvas = document.createElement("canvas");
51
canvas.className = "dialogue-simulate-icon";
52
canvas.width = ICON;
53
canvas.height = ICON;
54
const ctx = canvas.getContext("2d");
55
if (speaker === "player")
56
{
57
// Default player look stand-in (soft blue body + hair).
58
ctx.fillStyle = "#5b7ea6";
59
ctx.fillRect(8, 14, 32, 28);
60
ctx.fillStyle = "#c9a06a";
61
ctx.fillRect(12, 8, 24, 14);
62
ctx.fillStyle = "#2a3340";
63
ctx.fillRect(12, 6, 24, 8);
64
}
65
else
66
{
67
ctx.fillStyle = "#8a6a4a";
68
ctx.fillRect(8, 14, 32, 28);
69
ctx.fillStyle = "#d4b896";
70
ctx.fillRect(12, 8, 24, 14);
71
ctx.fillStyle = "#3a2a1a";
72
ctx.fillRect(12, 4, 24, 10);
73
}
74
return canvas;
75
}
76
77
/** Permissive snapshot so authored trigger gates can still be previewed. */
78
function simulateCtx ()
79
{
80
return {
81
countItem: () => 999,
82
tileX: 0,
83
tileY: 0,
84
chunkX: 0,
85
chunkY: 0,
86
dimensionId: "overworld",
87
hasVisitedDimension: () => true,
88
questState: () => "completed",
89
dialogueHeard: () => true,
90
dialogueTriggerLatched: () => true,
91
hp: 999,
92
maxHp: 999,
93
stamina: 999,
94
maxStamina: 999,
95
skillLevel: () => 99,
96
killCount: () => 999,
97
interactBlockDone: () => true
98
};
99
}
100
101
function rewardMessagesForStep (step)
102
{
103
const messages = [];
104
const bagParts = [];
105
for (const reward of step?.itemRewards ?? [])
106
{
107
const def = itemDefinition(reward.itemId);
108
bagParts.push({
109
displayName: def?.displayName ?? `Item ${reward.itemId}`,
110
quantity: Math.max(1, reward.quantity | 0 || 1)
111
});
112
}
113
const bagMsg = formatDialogueRewardMessage(bagParts, "bag");
114
if (bagMsg)
115
{ messages.push(bagMsg); }
116
const titles = [];
117
for (const questId of step?.questRewards ?? [])
118
{
119
titles.push(getQuestTitle?.(questId) || questId);
120
}
121
const questMsg = formatDialogueQuestRewardMessage(titles);
122
if (questMsg)
123
{ messages.push(questMsg); }
124
return messages;
125
}
126
127
function enterStep (stepId)
128
{
129
if (!session)
130
{ return; }
131
const step = session.tree.steps.find((s) => s.stepId === stepId);
132
if (!step)
133
{
134
show(false);
135
return;
136
}
137
session.stepId = stepId;
138
session.lineIndex = 0;
139
session.rewardMessages = null;
140
session.rewardIndex = 0;
141
render();
142
}
143
144
function resolveExit ()
145
{
146
if (!session)
147
{ return; }
148
const step = session.tree.steps.find((s) => s.stepId === session.stepId);
149
const exit = step?.exit ?? { kind: "end" };
150
if (exit.kind === "triggers")
151
{
152
const ctx = simulateCtx();
153
const triggers = (exit.triggers ?? []).filter((t) => evaluateConditionSet(t.when, ctx));
154
renderTriggerChoices(triggers);
155
return;
156
}
157
if (exit.kind === "branches")
158
{
159
renderBranchChoices(exit.branches ?? []);
160
return;
161
}
162
show(false);
163
}
164
165
function afterLines ()
166
{
167
const step = session.tree.steps.find((s) => s.stepId === session.stepId);
168
const messages = rewardMessagesForStep(step);
169
if (messages.length)
170
{
171
session.rewardMessages = messages;
172
session.rewardIndex = 0;
173
render();
174
return;
175
}
176
resolveExit();
177
}
178
179
function renderTriggerChoices (triggers)
180
{
181
if (titleEl)
182
{ titleEl.textContent = "Choices"; }
183
linesEl?.replaceChildren();
184
actionsEl?.replaceChildren();
185
if (!triggers.length)
186
{
187
const hint = document.createElement("p");
188
hint.className = "content-editor-hint";
189
hint.textContent = "No triggers matched (simulate uses a permissive player snapshot).";
190
linesEl?.append(hint);
191
const close = document.createElement("button");
192
close.type = "button";
193
close.textContent = "Close";
194
close.addEventListener("click", () => show(false));
195
actionsEl?.append(close);
196
return;
197
}
198
for (const trig of triggers)
199
{
200
const btn = document.createElement("button");
201
btn.type = "button";
202
btn.textContent = trig.text || trig.trigger || "…";
203
btn.addEventListener("click", () =>
204
{
205
if (trig.nextStepId)
206
{ enterStep(trig.nextStepId); }
207
else
208
{ show(false); }
209
});
210
actionsEl?.append(btn);
211
}
212
}
213
214
function renderBranchChoices (branches)
215
{
216
if (titleEl)
217
{ titleEl.textContent = "Branches (pick any)"; }
218
linesEl?.replaceChildren();
219
actionsEl?.replaceChildren();
220
const hint = document.createElement("p");
221
hint.className = "content-editor-hint";
222
hint.textContent = "Simulate ignores branch conditions so you can walk every path.";
223
linesEl?.append(hint);
224
if (!branches.length)
225
{
226
const close = document.createElement("button");
227
close.type = "button";
228
close.textContent = "Close";
229
close.addEventListener("click", () => show(false));
230
actionsEl?.append(close);
231
return;
232
}
233
branches.forEach((branch, index) =>
234
{
235
const btn = document.createElement("button");
236
btn.type = "button";
237
btn.textContent = branch.nextStepId
238
? `Branch ${index + 1} → ${branch.nextStepId}`
239
: `Branch ${index + 1} → end`;
240
btn.addEventListener("click", () =>
241
{
242
if (branch.nextStepId)
243
{ enterStep(branch.nextStepId); }
244
else
245
{ show(false); }
246
});
247
actionsEl?.append(btn);
248
});
249
}
250
251
function render ()
252
{
253
if (!session || !linesEl || !actionsEl)
254
{ return; }
255
linesEl.replaceChildren();
256
actionsEl.replaceChildren();
257
258
if (session.rewardMessages?.length)
259
{
260
if (titleEl)
261
{ titleEl.textContent = "Reward"; }
262
const row = document.createElement("div");
263
row.className = "dialogue-simulate-line dialogue-simulate-reward";
264
const text = document.createElement("span");
265
text.textContent = session.rewardMessages[session.rewardIndex] ?? "";
266
row.append(text);
267
linesEl.append(row);
268
const atLast = session.rewardIndex >= session.rewardMessages.length - 1;
269
const next = document.createElement("button");
270
next.type = "button";
271
next.textContent = atLast ? "Continue" : "Next";
272
next.addEventListener("click", () =>
273
{
274
if (!atLast)
275
{
276
session.rewardIndex += 1;
277
render();
278
return;
279
}
280
session.rewardMessages = null;
281
resolveExit();
282
});
283
actionsEl.append(next);
284
return;
285
}
286
287
const step = session.tree.steps.find((s) => s.stepId === session.stepId);
288
const line = step?.lines?.[session.lineIndex];
289
const speaker = line?.speaker === "player" ? "player" : "npc";
290
if (titleEl)
291
{ titleEl.textContent = speaker === "player" ? "You" : (session.tree.label || "NPC"); }
292
if (line)
293
{
294
const row = document.createElement("div");
295
row.className = `dialogue-simulate-line dialogue-simulate-${speaker}`;
296
row.append(speakerIcon(speaker));
297
const text = document.createElement("span");
298
text.textContent = line.text ?? "";
299
row.append(text);
300
linesEl.append(row);
301
}
302
const atLast = session.lineIndex >= (step?.lines?.length ?? 1) - 1;
303
const next = document.createElement("button");
304
next.type = "button";
305
next.textContent = atLast ? "Continue" : "Next";
306
next.addEventListener("click", () =>
307
{
308
if (!atLast)
309
{
310
session.lineIndex += 1;
311
render();
312
return;
313
}
314
afterLines();
315
});
316
actionsEl.append(next);
317
}
318
319
function start ()
320
{
321
const tree = getTree?.();
322
if (!tree?.steps?.length)
323
{ return false; }
324
session = {
325
tree,
326
stepId: tree.entryStepId || tree.steps[0].stepId,
327
lineIndex: 0,
328
rewardMessages: null,
329
rewardIndex: 0
330
};
331
show(true);
332
enterStep(session.stepId);
333
return true;
334
}
335
336
closeBtn?.addEventListener("click", () => show(false));
337
backdrop?.addEventListener("click", () => show(false));
338
339
return {
340
start,
341
close: () => show(false),
342
isOpen: () => !!session && panel && !panel.hidden
343
};
344
}
@@ -0,0 +1,344 @@1
/**2
* Client-only dialogue tree walk for the world editor.3
* Default player look; triggers use the same choice flow; branches are freely selectable.4
*/5
import { itemDefinition } from "/shared/definitions/items.js";6
import { evaluateConditionSet } from "/shared/quests/conditions.js";7
import {8
formatDialogueRewardMessage,9
formatDialogueQuestRewardMessage10
} from "/shared/quests/dialogueRewards.js";11
12
const ICON = 48;13
14
/**15
* @param {{16
* getTree: () => object | null,17
* getQuestTitle?: (questId: string) => string18
* }} options19
*/20
export function initDialogueSimulate ({ getTree, getQuestTitle = null } = {})21
{22
const backdrop = document.getElementById("dialogue-simulate-backdrop");23
const panel = document.getElementById("dialogue-simulate-panel");24
const titleEl = document.getElementById("dialogue-simulate-title");25
const linesEl = document.getElementById("dialogue-simulate-lines");26
const actionsEl = document.getElementById("dialogue-simulate-actions");27
const closeBtn = document.getElementById("dialogue-simulate-close");28
29
/** @type {null | {30
* tree: object,31
* stepId: string,32
* lineIndex: number,33
* rewardMessages: string[]|null,34
* rewardIndex: number35
* }} */36
let session = null;37
38
function show (visible)39
{40
if (backdrop)41
{ backdrop.hidden = !visible; }42
if (panel)43
{ panel.hidden = !visible; }44
if (!visible)45
{ session = null; }46
}47
48
function speakerIcon (speaker)49
{50
const canvas = document.createElement("canvas");51
canvas.className = "dialogue-simulate-icon";52
canvas.width = ICON;53
canvas.height = ICON;54
const ctx = canvas.getContext("2d");55
if (speaker === "player")56
{57
// Default player look stand-in (soft blue body + hair).58
ctx.fillStyle = "#5b7ea6";59
ctx.fillRect(8, 14, 32, 28);60
ctx.fillStyle = "#c9a06a";61
ctx.fillRect(12, 8, 24, 14);62
ctx.fillStyle = "#2a3340";63
ctx.fillRect(12, 6, 24, 8);64
}65
else66
{67
ctx.fillStyle = "#8a6a4a";68
ctx.fillRect(8, 14, 32, 28);69
ctx.fillStyle = "#d4b896";70
ctx.fillRect(12, 8, 24, 14);71
ctx.fillStyle = "#3a2a1a";72
ctx.fillRect(12, 4, 24, 10);73
}74
return canvas;75
}76
77
/** Permissive snapshot so authored trigger gates can still be previewed. */78
function simulateCtx ()79
{80
return {81
countItem: () => 999,82
tileX: 0,83
tileY: 0,84
chunkX: 0,85
chunkY: 0,86
dimensionId: "overworld",87
hasVisitedDimension: () => true,88
questState: () => "completed",89
dialogueHeard: () => true,90
dialogueTriggerLatched: () => true,91
hp: 999,92
maxHp: 999,93
stamina: 999,94
maxStamina: 999,95
skillLevel: () => 99,96
killCount: () => 999,97
interactBlockDone: () => true98
};99
}100
101
function rewardMessagesForStep (step)102
{103
const messages = [];104
const bagParts = [];105
for (const reward of step?.itemRewards ?? [])106
{107
const def = itemDefinition(reward.itemId);108
bagParts.push({109
displayName: def?.displayName ?? `Item ${reward.itemId}`,110
quantity: Math.max(1, reward.quantity | 0 || 1)111
});112
}113
const bagMsg = formatDialogueRewardMessage(bagParts, "bag");114
if (bagMsg)115
{ messages.push(bagMsg); }116
const titles = [];117
for (const questId of step?.questRewards ?? [])118
{119
titles.push(getQuestTitle?.(questId) || questId);120
}121
const questMsg = formatDialogueQuestRewardMessage(titles);122
if (questMsg)123
{ messages.push(questMsg); }124
return messages;125
}126
127
function enterStep (stepId)128
{129
if (!session)130
{ return; }131
const step = session.tree.steps.find((s) => s.stepId === stepId);132
if (!step)133
{134
show(false);135
return;136
}137
session.stepId = stepId;138
session.lineIndex = 0;139
session.rewardMessages = null;140
session.rewardIndex = 0;141
render();142
}143
144
function resolveExit ()145
{146
if (!session)147
{ return; }148
const step = session.tree.steps.find((s) => s.stepId === session.stepId);149
const exit = step?.exit ?? { kind: "end" };150
if (exit.kind === "triggers")151
{152
const ctx = simulateCtx();153
const triggers = (exit.triggers ?? []).filter((t) => evaluateConditionSet(t.when, ctx));154
renderTriggerChoices(triggers);155
return;156
}157
if (exit.kind === "branches")158
{159
renderBranchChoices(exit.branches ?? []);160
return;161
}162
show(false);163
}164
165
function afterLines ()166
{167
const step = session.tree.steps.find((s) => s.stepId === session.stepId);168
const messages = rewardMessagesForStep(step);169
if (messages.length)170
{171
session.rewardMessages = messages;172
session.rewardIndex = 0;173
render();174
return;175
}176
resolveExit();177
}178
179
function renderTriggerChoices (triggers)180
{181
if (titleEl)182
{ titleEl.textContent = "Choices"; }183
linesEl?.replaceChildren();184
actionsEl?.replaceChildren();185
if (!triggers.length)186
{187
const hint = document.createElement("p");188
hint.className = "content-editor-hint";189
hint.textContent = "No triggers matched (simulate uses a permissive player snapshot).";190
linesEl?.append(hint);191
const close = document.createElement("button");192
close.type = "button";193
close.textContent = "Close";194
close.addEventListener("click", () => show(false));195
actionsEl?.append(close);196
return;197
}198
for (const trig of triggers)199
{200
const btn = document.createElement("button");201
btn.type = "button";202
btn.textContent = trig.text || trig.trigger || "…";203
btn.addEventListener("click", () =>204
{205
if (trig.nextStepId)206
{ enterStep(trig.nextStepId); }207
else208
{ show(false); }209
});210
actionsEl?.append(btn);211
}212
}213
214
function renderBranchChoices (branches)215
{216
if (titleEl)217
{ titleEl.textContent = "Branches (pick any)"; }218
linesEl?.replaceChildren();219
actionsEl?.replaceChildren();220
const hint = document.createElement("p");221
hint.className = "content-editor-hint";222
hint.textContent = "Simulate ignores branch conditions so you can walk every path.";223
linesEl?.append(hint);224
if (!branches.length)225
{226
const close = document.createElement("button");227
close.type = "button";228
close.textContent = "Close";229
close.addEventListener("click", () => show(false));230
actionsEl?.append(close);231
return;232
}233
branches.forEach((branch, index) =>234
{235
const btn = document.createElement("button");236
btn.type = "button";237
btn.textContent = branch.nextStepId238
? `Branch ${index + 1} → ${branch.nextStepId}`239
: `Branch ${index + 1} → end`;240
btn.addEventListener("click", () =>241
{242
if (branch.nextStepId)243
{ enterStep(branch.nextStepId); }244
else245
{ show(false); }246
});247
actionsEl?.append(btn);248
});249
}250
251
function render ()252
{253
if (!session || !linesEl || !actionsEl)254
{ return; }255
linesEl.replaceChildren();256
actionsEl.replaceChildren();257
258
if (session.rewardMessages?.length)259
{260
if (titleEl)261
{ titleEl.textContent = "Reward"; }262
const row = document.createElement("div");263
row.className = "dialogue-simulate-line dialogue-simulate-reward";264
const text = document.createElement("span");265
text.textContent = session.rewardMessages[session.rewardIndex] ?? "";266
row.append(text);267
linesEl.append(row);268
const atLast = session.rewardIndex >= session.rewardMessages.length - 1;269
const next = document.createElement("button");270
next.type = "button";271
next.textContent = atLast ? "Continue" : "Next";272
next.addEventListener("click", () =>273
{274
if (!atLast)275
{276
session.rewardIndex += 1;277
render();278
return;279
}280
session.rewardMessages = null;281
resolveExit();282
});283
actionsEl.append(next);284
return;285
}286
287
const step = session.tree.steps.find((s) => s.stepId === session.stepId);288
const line = step?.lines?.[session.lineIndex];289
const speaker = line?.speaker === "player" ? "player" : "npc";290
if (titleEl)291
{ titleEl.textContent = speaker === "player" ? "You" : (session.tree.label || "NPC"); }292
if (line)293
{294
const row = document.createElement("div");295
row.className = `dialogue-simulate-line dialogue-simulate-${speaker}`;296
row.append(speakerIcon(speaker));297
const text = document.createElement("span");298
text.textContent = line.text ?? "";299
row.append(text);300
linesEl.append(row);301
}302
const atLast = session.lineIndex >= (step?.lines?.length ?? 1) - 1;303
const next = document.createElement("button");304
next.type = "button";305
next.textContent = atLast ? "Continue" : "Next";306
next.addEventListener("click", () =>307
{308
if (!atLast)309
{310
session.lineIndex += 1;311
render();312
return;313
}314
afterLines();315
});316
actionsEl.append(next);317
}318
319
function start ()320
{321
const tree = getTree?.();322
if (!tree?.steps?.length)323
{ return false; }324
session = {325
tree,326
stepId: tree.entryStepId || tree.steps[0].stepId,327
lineIndex: 0,328
rewardMessages: null,329
rewardIndex: 0330
};331
show(true);332
enterStep(session.stepId);333
return true;334
}335
336
closeBtn?.addEventListener("click", () => show(false));337
backdrop?.addEventListener("click", () => show(false));338
339
return {340
start,341
close: () => show(false),342
isOpen: () => !!session && panel && !panel.hidden343
};344
}@@ -1,8 +1,16 @@
1
import { normalizeDialogueTree } from "/shared/quests/normalize.js";
2
import { emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
1
import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";
2
import { emptyConditionSet } from "/shared/quests/conditions.js";
3
3
import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
4
import { renderConditionSet } from "./conditionSetEditor.js";
5
import { initDialogueSimulate } from "./dialogueSimulate.js";
4
6
5
export function initDialoguesModal ({ socket, MessageType })
7
export function initDialoguesModal ({
8
socket,
9
MessageType,
10
describeWorldTile = null,
11
centerEditorOnTile = null,
12
getDimensionOptions = null
13
})
6
14
{
7
15
const backdrop = document.getElementById("dialogues-backdrop");
8
16
const modal = document.getElementById("dialogues-modal");
@@ -10,13 +18,25 @@ export function initDialoguesModal ({ socket, MessageType })
10
18
const editorEl = document.getElementById("dialogues-editor");
11
19
const saveBtn = document.getElementById("dialogues-save");
12
20
const deleteBtn = document.getElementById("dialogues-delete");
21
const simulateBtn = document.getElementById("dialogues-simulate");
13
22
let open = false;
14
23
/** @type {any[]} */
15
24
let dialogues = [];
25
/** @type {ReturnType<typeof normalizeQuestDef>[]} */
26
let questCatalog = [];
16
27
/** @type {any|null} */
17
28
let draft = null;
18
29
let selectedId = null;
19
30
31
const simulate = initDialogueSimulate({
32
getTree: () => (draft ? normalizeDialogueTree(draft) : null),
33
getQuestTitle (questId)
34
{
35
const quest = questCatalog.find((q) => q.questId === questId);
36
return quest?.title || questId;
37
}
38
});
39
20
40
function show (visible)
21
41
{
22
42
open = visible;
@@ -27,6 +47,7 @@ export function initDialoguesModal ({ socket, MessageType })
27
47
draft = null;
28
48
selectedId = null;
29
49
closeInlineItemSearch();
50
simulate.close();
30
51
}
31
52
}
32
53
@@ -135,6 +156,7 @@ export function initDialoguesModal ({ socket, MessageType })
135
156
stepId: `step-${draft.steps.length + 1}`,
136
157
lines: [{ speaker: "npc", text: "…", effects: [] }],
137
158
itemRewards: [],
159
questRewards: [],
138
160
exit: { kind: "end" }
139
161
});
140
162
renderEditor();
@@ -145,6 +167,8 @@ export function initDialoguesModal ({ socket, MessageType })
145
167
editorEl.replaceChildren();
146
168
saveBtn.disabled = !draft;
147
169
deleteBtn.disabled = !draft;
170
if (simulateBtn)
171
{ simulateBtn.disabled = !draft; }
148
172
if (!draft)
149
173
{
150
174
const hint = document.createElement("p");
@@ -197,6 +221,7 @@ export function initDialoguesModal ({ socket, MessageType })
197
221
stepId: "greeting",
198
222
lines: [{ speaker: "npc", text: "…", effects: [] }],
199
223
itemRewards: [],
224
questRewards: [],
200
225
exit: { kind: "end" }
201
226
});
202
227
}
@@ -300,6 +325,69 @@ export function initDialoguesModal ({ socket, MessageType })
300
325
});
301
326
box.append(searchWrap);
302
327
328
if (!Array.isArray(step.questRewards))
329
{ step.questRewards = []; }
330
const questRewardsHead = sectionHeader("Quest rewards", () =>
331
{
332
const available = questCatalog.find((q) => !step.questRewards.includes(q.questId));
333
if (!available)
334
{ return; }
335
step.questRewards.push(available.questId);
336
renderEditor();
337
});
338
box.append(questRewardsHead);
339
const questHint = document.createElement("p");
340
questHint.className = "content-editor-hint";
341
questHint.textContent = "Started after all lines (with item rewards), before triggers/branches.";
342
box.append(questHint);
343
if (!step.questRewards.length)
344
{
345
const empty = document.createElement("p");
346
empty.className = "content-editor-hint";
347
empty.textContent = "No quest rewards.";
348
box.append(empty);
349
}
350
step.questRewards.forEach((questId, rewardIndex) =>
351
{
352
const row = document.createElement("div");
353
row.className = "spawner-drops-row";
354
const select = document.createElement("select");
355
const taken = new Set(step.questRewards);
356
const catalog = questCatalog.length
357
? questCatalog
358
: [{ questId, title: questId }];
359
for (const quest of catalog)
360
{
361
if (taken.has(quest.questId) && quest.questId !== questId)
362
{ continue; }
363
const opt = document.createElement("option");
364
opt.value = quest.questId;
365
opt.textContent = quest.title
366
? `${quest.title} (${quest.questId})`
367
: quest.questId;
368
select.append(opt);
369
}
370
if (![...select.options].some((o) => o.value === questId))
371
{
372
const missing = document.createElement("option");
373
missing.value = questId;
374
missing.textContent = `${questId} (missing)`;
375
select.append(missing);
376
}
377
select.value = questId;
378
select.addEventListener("change", () =>
379
{
380
step.questRewards[rewardIndex] = select.value;
381
renderEditor();
382
});
383
row.append(select, removeButton(() =>
384
{
385
step.questRewards.splice(rewardIndex, 1);
386
renderEditor();
387
}));
388
box.append(row);
389
});
390
303
391
const exitKind = document.createElement("select");
304
392
for (const k of ["end", "triggers", "branches"])
305
393
{
@@ -377,7 +465,12 @@ export function initDialoguesModal ({ socket, MessageType })
377
465
trig.nextStepId = v.trim() || null;
378
466
}))
379
467
);
380
tBox.append(whenJson(trig.when, (next) => { trig.when = next; }));
468
tBox.append(renderConditionSet(trig.when, (next, { remount = true } = {}) =>
469
{
470
trig.when = next;
471
if (remount)
472
{ renderEditor(); }
473
}, conditionCtx()));
381
474
box.append(tBox);
382
475
});
383
476
}
@@ -408,7 +501,12 @@ export function initDialoguesModal ({ socket, MessageType })
408
501
branch.nextStepId = v.trim() || null;
409
502
}))
410
503
);
411
bBox.append(whenJson(branch.when, (next) => { branch.when = next; }));
504
bBox.append(renderConditionSet(branch.when, (next, { remount = true } = {}) =>
505
{
506
branch.when = next;
507
if (remount)
508
{ renderEditor(); }
509
}, conditionCtx()));
412
510
box.append(bBox);
413
511
});
414
512
}
@@ -424,6 +522,17 @@ export function initDialoguesModal ({ socket, MessageType })
424
522
editorEl.append(addStepBtn);
425
523
}
426
524
525
function conditionCtx ()
526
{
527
return {
528
quests: questCatalog,
529
dialogues,
530
describeWorldTile,
531
centerEditorOnTile,
532
getDimensionOptions
533
};
534
}
535
427
536
function render ()
428
537
{
429
538
renderList();
@@ -433,11 +542,18 @@ export function initDialoguesModal ({ socket, MessageType })
433
542
document.getElementById("open-dialogues").addEventListener("click", () =>
434
543
{
435
544
socket.send({ type: MessageType.editorLoadDialogues });
545
socket.send({ type: MessageType.editorLoadQuests });
436
546
show(true);
437
547
render();
438
548
});
439
549
document.getElementById("dialogues-close").addEventListener("click", () => show(false));
440
550
backdrop.addEventListener("click", () => show(false));
551
simulateBtn?.addEventListener("click", () =>
552
{
553
if (!draft)
554
{ return; }
555
simulate.start();
556
});
441
557
document.getElementById("dialogues-new").addEventListener("click", () =>
442
558
{
443
559
const base = normalizeDialogueTree({
@@ -465,10 +581,17 @@ export function initDialoguesModal ({ socket, MessageType })
465
581
});
466
582
467
583
return {
468
isOpen: () => open,
584
isOpen: () => open || simulate.isOpen(),
469
585
getDialogues: () => dialogues,
470
586
handleMessage (message)
471
587
{
588
if (message.type === MessageType.editorQuests)
589
{
590
questCatalog = (message.quests ?? []).map((q) => normalizeQuestDef(q));
591
if (open)
592
{ render(); }
593
return;
594
}
472
595
if (message.type !== MessageType.editorDialogues)
473
596
{ return; }
474
597
dialogues = (message.dialogues ?? []).map((d) =>
@@ -550,23 +673,3 @@ function sectionHeader (title, onAdd, onRemove)
550
673
return head;
551
674
}
552
675
553
function whenJson (when, onChange)
554
{
555
const details = document.createElement("details");
556
const summary = document.createElement("summary");
557
summary.textContent = "when (condition JSON)";
558
const area = document.createElement("textarea");
559
area.rows = 4;
560
area.value = JSON.stringify(normalizeConditionSet(when), null, 2);
561
area.addEventListener("change", () =>
562
{
563
try
564
{
565
onChange(normalizeConditionSet(JSON.parse(area.value)));
566
}
567
catch
568
{ /* ignore invalid */ }
569
});
570
details.append(summary, area);
571
return details;
572
}
@@ -1,8 +1,16 @@1
import { normalizeDialogueTree } from "/shared/quests/normalize.js";1
import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js";2
import { emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";2
import { emptyConditionSet } from "/shared/quests/conditions.js";3
import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";3
import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";4
import { renderConditionSet } from "./conditionSetEditor.js";5
import { initDialogueSimulate } from "./dialogueSimulate.js";4
6
5
export function initDialoguesModal ({ socket, MessageType })7
export function initDialoguesModal ({8
socket,9
MessageType,10
describeWorldTile = null,11
centerEditorOnTile = null,12
getDimensionOptions = null13
})6
{14
{7
const backdrop = document.getElementById("dialogues-backdrop");15
const backdrop = document.getElementById("dialogues-backdrop");8
const modal = document.getElementById("dialogues-modal");16
const modal = document.getElementById("dialogues-modal");@@ -10,13 +18,25 @@ export function initDialoguesModal ({ socket, MessageType })10
const editorEl = document.getElementById("dialogues-editor");18
const editorEl = document.getElementById("dialogues-editor");11
const saveBtn = document.getElementById("dialogues-save");19
const saveBtn = document.getElementById("dialogues-save");12
const deleteBtn = document.getElementById("dialogues-delete");20
const deleteBtn = document.getElementById("dialogues-delete");21
const simulateBtn = document.getElementById("dialogues-simulate");13
let open = false;22
let open = false;14
/** @type {any[]} */23
/** @type {any[]} */15
let dialogues = [];24
let dialogues = [];25
/** @type {ReturnType<typeof normalizeQuestDef>[]} */26
let questCatalog = [];16
/** @type {any|null} */27
/** @type {any|null} */17
let draft = null;28
let draft = null;18
let selectedId = null;29
let selectedId = null;19
30
31
const simulate = initDialogueSimulate({32
getTree: () => (draft ? normalizeDialogueTree(draft) : null),33
getQuestTitle (questId)34
{35
const quest = questCatalog.find((q) => q.questId === questId);36
return quest?.title || questId;37
}38
});39
20
function show (visible)40
function show (visible)21
{41
{22
open = visible;42
open = visible;@@ -27,6 +47,7 @@ export function initDialoguesModal ({ socket, MessageType })27
draft = null;47
draft = null;28
selectedId = null;48
selectedId = null;29
closeInlineItemSearch();49
closeInlineItemSearch();50
simulate.close();30
}51
}31
}52
}32
53
@@ -135,6 +156,7 @@ export function initDialoguesModal ({ socket, MessageType })135
stepId: `step-${draft.steps.length + 1}`,156
stepId: `step-${draft.steps.length + 1}`,136
lines: [{ speaker: "npc", text: "…", effects: [] }],157
lines: [{ speaker: "npc", text: "…", effects: [] }],137
itemRewards: [],158
itemRewards: [],159
questRewards: [],138
exit: { kind: "end" }160
exit: { kind: "end" }139
});161
});140
renderEditor();162
renderEditor();@@ -145,6 +167,8 @@ export function initDialoguesModal ({ socket, MessageType })145
editorEl.replaceChildren();167
editorEl.replaceChildren();146
saveBtn.disabled = !draft;168
saveBtn.disabled = !draft;147
deleteBtn.disabled = !draft;169
deleteBtn.disabled = !draft;170
if (simulateBtn)171
{ simulateBtn.disabled = !draft; }148
if (!draft)172
if (!draft)149
{173
{150
const hint = document.createElement("p");174
const hint = document.createElement("p");@@ -197,6 +221,7 @@ export function initDialoguesModal ({ socket, MessageType })197
stepId: "greeting",221
stepId: "greeting",198
lines: [{ speaker: "npc", text: "…", effects: [] }],222
lines: [{ speaker: "npc", text: "…", effects: [] }],199
itemRewards: [],223
itemRewards: [],224
questRewards: [],200
exit: { kind: "end" }225
exit: { kind: "end" }201
});226
});202
}227
}@@ -300,6 +325,69 @@ export function initDialoguesModal ({ socket, MessageType })300
});325
});301
box.append(searchWrap);326
box.append(searchWrap);302
327
328
if (!Array.isArray(step.questRewards))329
{ step.questRewards = []; }330
const questRewardsHead = sectionHeader("Quest rewards", () =>331
{332
const available = questCatalog.find((q) => !step.questRewards.includes(q.questId));333
if (!available)334
{ return; }335
step.questRewards.push(available.questId);336
renderEditor();337
});338
box.append(questRewardsHead);339
const questHint = document.createElement("p");340
questHint.className = "content-editor-hint";341
questHint.textContent = "Started after all lines (with item rewards), before triggers/branches.";342
box.append(questHint);343
if (!step.questRewards.length)344
{345
const empty = document.createElement("p");346
empty.className = "content-editor-hint";347
empty.textContent = "No quest rewards.";348
box.append(empty);349
}350
step.questRewards.forEach((questId, rewardIndex) =>351
{352
const row = document.createElement("div");353
row.className = "spawner-drops-row";354
const select = document.createElement("select");355
const taken = new Set(step.questRewards);356
const catalog = questCatalog.length357
? questCatalog358
: [{ questId, title: questId }];359
for (const quest of catalog)360
{361
if (taken.has(quest.questId) && quest.questId !== questId)362
{ continue; }363
const opt = document.createElement("option");364
opt.value = quest.questId;365
opt.textContent = quest.title366
? `${quest.title} (${quest.questId})`367
: quest.questId;368
select.append(opt);369
}370
if (![...select.options].some((o) => o.value === questId))371
{372
const missing = document.createElement("option");373
missing.value = questId;374
missing.textContent = `${questId} (missing)`;375
select.append(missing);376
}377
select.value = questId;378
select.addEventListener("change", () =>379
{380
step.questRewards[rewardIndex] = select.value;381
renderEditor();382
});383
row.append(select, removeButton(() =>384
{385
step.questRewards.splice(rewardIndex, 1);386
renderEditor();387
}));388
box.append(row);389
});390
303
const exitKind = document.createElement("select");391
const exitKind = document.createElement("select");304
for (const k of ["end", "triggers", "branches"])392
for (const k of ["end", "triggers", "branches"])305
{393
{@@ -377,7 +465,12 @@ export function initDialoguesModal ({ socket, MessageType })377
trig.nextStepId = v.trim() || null;465
trig.nextStepId = v.trim() || null;378
}))466
}))379
);467
);380
tBox.append(whenJson(trig.when, (next) => { trig.when = next; }));468
tBox.append(renderConditionSet(trig.when, (next, { remount = true } = {}) =>469
{470
trig.when = next;471
if (remount)472
{ renderEditor(); }473
}, conditionCtx()));381
box.append(tBox);474
box.append(tBox);382
});475
});383
}476
}@@ -408,7 +501,12 @@ export function initDialoguesModal ({ socket, MessageType })408
branch.nextStepId = v.trim() || null;501
branch.nextStepId = v.trim() || null;409
}))502
}))410
);503
);411
bBox.append(whenJson(branch.when, (next) => { branch.when = next; }));504
bBox.append(renderConditionSet(branch.when, (next, { remount = true } = {}) =>505
{506
branch.when = next;507
if (remount)508
{ renderEditor(); }509
}, conditionCtx()));412
box.append(bBox);510
box.append(bBox);413
});511
});414
}512
}@@ -424,6 +522,17 @@ export function initDialoguesModal ({ socket, MessageType })424
editorEl.append(addStepBtn);522
editorEl.append(addStepBtn);425
}523
}426
524
525
function conditionCtx ()526
{527
return {528
quests: questCatalog,529
dialogues,530
describeWorldTile,531
centerEditorOnTile,532
getDimensionOptions533
};534
}535
427
function render ()536
function render ()428
{537
{429
renderList();538
renderList();@@ -433,11 +542,18 @@ export function initDialoguesModal ({ socket, MessageType })433
document.getElementById("open-dialogues").addEventListener("click", () =>542
document.getElementById("open-dialogues").addEventListener("click", () =>434
{543
{435
socket.send({ type: MessageType.editorLoadDialogues });544
socket.send({ type: MessageType.editorLoadDialogues });545
socket.send({ type: MessageType.editorLoadQuests });436
show(true);546
show(true);437
render();547
render();438
});548
});439
document.getElementById("dialogues-close").addEventListener("click", () => show(false));549
document.getElementById("dialogues-close").addEventListener("click", () => show(false));440
backdrop.addEventListener("click", () => show(false));550
backdrop.addEventListener("click", () => show(false));551
simulateBtn?.addEventListener("click", () =>552
{553
if (!draft)554
{ return; }555
simulate.start();556
});441
document.getElementById("dialogues-new").addEventListener("click", () =>557
document.getElementById("dialogues-new").addEventListener("click", () =>442
{558
{443
const base = normalizeDialogueTree({559
const base = normalizeDialogueTree({@@ -465,10 +581,17 @@ export function initDialoguesModal ({ socket, MessageType })465
});581
});466
582
467
return {583
return {468
isOpen: () => open,584
isOpen: () => open || simulate.isOpen(),469
getDialogues: () => dialogues,585
getDialogues: () => dialogues,470
handleMessage (message)586
handleMessage (message)471
{587
{588
if (message.type === MessageType.editorQuests)589
{590
questCatalog = (message.quests ?? []).map((q) => normalizeQuestDef(q));591
if (open)592
{ render(); }593
return;594
}472
if (message.type !== MessageType.editorDialogues)595
if (message.type !== MessageType.editorDialogues)473
{ return; }596
{ return; }474
dialogues = (message.dialogues ?? []).map((d) =>597
dialogues = (message.dialogues ?? []).map((d) =>@@ -550,23 +673,3 @@ function sectionHeader (title, onAdd, onRemove)550
return head;673
return head;551
}674
}552
675
553
function whenJson (when, onChange)554
{555
const details = document.createElement("details");556
const summary = document.createElement("summary");557
summary.textContent = "when (condition JSON)";558
const area = document.createElement("textarea");559
area.rows = 4;560
area.value = JSON.stringify(normalizeConditionSet(when), null, 2);561
area.addEventListener("change", () =>562
{563
try564
{565
onChange(normalizeConditionSet(JSON.parse(area.value)));566
}567
catch568
{ /* ignore invalid */ }569
});570
details.append(summary, area);571
return details;572
}@@ -339,6 +339,113 @@ function clearNeighborEditState ()
339
339
dirtyNeighborChunks.clear();
340
340
}
341
341
342
function groundAtWorld (tileX, tileY)
343
{
344
const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
345
const index = localY * CHUNK_SIZE + localX;
346
if (cx === chunkX && cy === chunkY && draft)
347
{ return draft.grounds[index] ?? null; }
348
const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
349
if (dirty)
350
{ return dirty.grounds[index] ?? null; }
351
const snapshot = view?.chunks.get(chunkKey(cx, cy));
352
return snapshot?.grounds?.[index] ?? null;
353
}
354
355
function spawnerAtWorld (tileX, tileY)
356
{
357
const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
358
if (cx === chunkX && cy === chunkY && draft)
359
{ return spawnerAt(localX, localY); }
360
const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));
361
if (dirty)
362
{ return dirty.spawners?.find((entry) => entry.localX === localX && entry.localY === localY) ?? null; }
363
return (neighborSpawnersByChunk.get(chunkKey(cx, cy)) ?? [])
364
.find((entry) => entry.localX === localX && entry.localY === localY) ?? null;
365
}
366
367
/** Human-readable summary of authored ground/block/spawner on a world tile. */
368
function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)
369
{
370
const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
371
if (dim !== selectedDimensionId)
372
{
373
return `Currently editing “${selectedDimensionId}”; switch to “${dim}” to inspect this tile.`;
374
}
375
const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
376
const key = chunkKey(cx, cy);
377
const loaded = (cx === chunkX && cy === chunkY && draft)
378
|| dirtyNeighborChunks.has(key)
379
|| view?.chunks?.has(key);
380
if (!loaded)
381
{ return `Chunk (${cx}, ${cy}) not loaded — center on this tile to load it.`; }
382
383
const lines = [];
384
const ground = normalizeGround(groundAtWorld(tileX, tileY));
385
const groundDef = GROUND_DEFINITIONS[ground?.typeId];
386
lines.push(`Ground: ${groundDef?.displayName ?? `type ${ground?.typeId ?? "?"}`}`);
387
const block = normalizeBlock(blockAtWorld(tileX, tileY));
388
if (block)
389
{
390
const blockDef = BLOCK_DEFINITIONS[block.typeId];
391
lines.push(`Block: ${blockDef?.displayName ?? `type ${block.typeId}`}${block.state ? ` (${block.state})` : ""}`);
392
if (block.config && Object.keys(block.config).length)
393
{
394
for (const [keyName, value] of Object.entries(block.config))
395
{ lines.push(` ${keyName}: ${value}`); }
396
}
397
}
398
else
399
{ lines.push("Block: (none)"); }
400
const spawner = spawnerAtWorld(tileX, tileY);
401
if (spawner)
402
{
403
const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);
404
const mob = mobDefinition(config.mobTypeId);
405
lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);
406
}
407
else
408
{ lines.push("Spawner: (none)"); }
409
return lines.join("\n");
410
}
411
412
/** Pan the editor to a world tile without closing other UI; loads its chunk neighborhood. */
413
function centerEditorOnTile (tileX, tileY, dimensionId = selectedDimensionId)
414
{
415
const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);
416
const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX | 0, tileY | 0, CHUNK_SIZE);
417
if (dim !== selectedDimensionId)
418
{
419
if (isDraftDirty())
420
{
421
showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: dim });
422
return false;
423
}
424
selectedDimensionId = dim;
425
syncDimensionUi();
426
clearNeighborhoodView();
427
doLoadNeighborhood(cx, cy);
428
}
429
else if (cx !== chunkX || cy !== chunkY)
430
{
431
if (isDraftDirty())
432
{
433
showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: selectedDimensionId });
434
return false;
435
}
436
doLoadNeighborhood(cx, cy);
437
}
438
if (!view?.scene)
439
{ return true; }
440
const size = view.tileSize();
441
view.followPlayer = false;
442
view.scene.cameraPosition.x = view.scene.real_size.x / 2 - ((tileX | 0) + 0.5) * size;
443
view.scene.cameraPosition.y = view.scene.real_size.y / 2 - ((tileY | 0) + 0.5) * size;
444
view.refreshViewport();
445
updateSelectionBorder();
446
return true;
447
}
448
342
449
function blockAtWorld (tileX, tileY)
343
450
{
344
451
const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);
@@ -1265,11 +1372,16 @@ async function main ()
1265
1372
applyDimensionsList(message);
1266
1373
}
1267
1374
else if (message.type === MessageType.editorQuests)
1268
{ questsModal?.handleMessage(message); }
1375
{
1376
questsModal?.handleMessage(message);
1377
settingsModal?.handleMessage(message);
1378
dialoguesModal?.handleMessage(message);
1379
}
1269
1380
else if (message.type === MessageType.editorDialogues)
1270
1381
{
1271
1382
dialoguesModal?.handleMessage(message);
1272
1383
tileConfigModal?.handleMessage(message);
1384
questsModal?.handleMessage(message);
1273
1385
}
1274
1386
else if (message.type === MessageType.editorGiftCharacters
1275
1387
|| message.type === MessageType.editorGiftSent)
@@ -1401,8 +1513,30 @@ async function main ()
1401
1513
getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1402
1514
isOverworld
1403
1515
});
1404
questsModal = initQuestsModal({ socket, MessageType });
1405
dialoguesModal = initDialoguesModal({ socket, MessageType });
1516
questsModal = initQuestsModal({
1517
socket,
1518
MessageType,
1519
describeWorldTile,
1520
centerEditorOnTile,
1521
getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1522
id: dim.dimensionId,
1523
label: dim.displayName || dim.dimensionId,
1524
disabled: dim.deletedAt != null,
1525
hint: dim.deletedAt != null ? "soft-deleted" : null
1526
}))
1527
});
1528
dialoguesModal = initDialoguesModal({
1529
socket,
1530
MessageType,
1531
describeWorldTile,
1532
centerEditorOnTile,
1533
getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
1534
id: dim.dimensionId,
1535
label: dim.displayName || dim.dimensionId,
1536
disabled: dim.deletedAt != null,
1537
hint: dim.deletedAt != null ? "soft-deleted" : null
1538
}))
1539
});
1406
1540
giftsModal = initGiftsModal({ socket, MessageType });
1407
1541
initSidePanelTabs();
1408
1542
game.startGame();
@@ -339,6 +339,113 @@ function clearNeighborEditState ()339
dirtyNeighborChunks.clear();339
dirtyNeighborChunks.clear();340
}340
}341
341
342
function groundAtWorld (tileX, tileY)343
{344
const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);345
const index = localY * CHUNK_SIZE + localX;346
if (cx === chunkX && cy === chunkY && draft)347
{ return draft.grounds[index] ?? null; }348
const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));349
if (dirty)350
{ return dirty.grounds[index] ?? null; }351
const snapshot = view?.chunks.get(chunkKey(cx, cy));352
return snapshot?.grounds?.[index] ?? null;353
}354
355
function spawnerAtWorld (tileX, tileY)356
{357
const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);358
if (cx === chunkX && cy === chunkY && draft)359
{ return spawnerAt(localX, localY); }360
const dirty = dirtyNeighborChunks.get(chunkKey(cx, cy));361
if (dirty)362
{ return dirty.spawners?.find((entry) => entry.localX === localX && entry.localY === localY) ?? null; }363
return (neighborSpawnersByChunk.get(chunkKey(cx, cy)) ?? [])364
.find((entry) => entry.localX === localX && entry.localY === localY) ?? null;365
}366
367
/** Human-readable summary of authored ground/block/spawner on a world tile. */368
function describeWorldTile (tileX, tileY, dimensionId = selectedDimensionId)369
{370
const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);371
if (dim !== selectedDimensionId)372
{373
return `Currently editing “${selectedDimensionId}”; switch to “${dim}” to inspect this tile.`;374
}375
const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);376
const key = chunkKey(cx, cy);377
const loaded = (cx === chunkX && cy === chunkY && draft)378
|| dirtyNeighborChunks.has(key)379
|| view?.chunks?.has(key);380
if (!loaded)381
{ return `Chunk (${cx}, ${cy}) not loaded — center on this tile to load it.`; }382
383
const lines = [];384
const ground = normalizeGround(groundAtWorld(tileX, tileY));385
const groundDef = GROUND_DEFINITIONS[ground?.typeId];386
lines.push(`Ground: ${groundDef?.displayName ?? `type ${ground?.typeId ?? "?"}`}`);387
const block = normalizeBlock(blockAtWorld(tileX, tileY));388
if (block)389
{390
const blockDef = BLOCK_DEFINITIONS[block.typeId];391
lines.push(`Block: ${blockDef?.displayName ?? `type ${block.typeId}`}${block.state ? ` (${block.state})` : ""}`);392
if (block.config && Object.keys(block.config).length)393
{394
for (const [keyName, value] of Object.entries(block.config))395
{ lines.push(` ${keyName}: ${value}`); }396
}397
}398
else399
{ lines.push("Block: (none)"); }400
const spawner = spawnerAtWorld(tileX, tileY);401
if (spawner)402
{403
const config = normalizeSpawnerConfig(spawner.config, spawner.config?.spawnerId);404
const mob = mobDefinition(config.mobTypeId);405
lines.push(`Spawner: ${mob?.displayName ?? config.mobTypeId} (${config.spawnerId})`);406
}407
else408
{ lines.push("Spawner: (none)"); }409
return lines.join("\n");410
}411
412
/** Pan the editor to a world tile without closing other UI; loads its chunk neighborhood. */413
function centerEditorOnTile (tileX, tileY, dimensionId = selectedDimensionId)414
{415
const dim = normalizeDimensionId(dimensionId ?? OVERWORLD_ID);416
const { chunkX: cx, chunkY: cy } = worldTileToChunkLocal(tileX | 0, tileY | 0, CHUNK_SIZE);417
if (dim !== selectedDimensionId)418
{419
if (isDraftDirty())420
{421
showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: dim });422
return false;423
}424
selectedDimensionId = dim;425
syncDimensionUi();426
clearNeighborhoodView();427
doLoadNeighborhood(cx, cy);428
}429
else if (cx !== chunkX || cy !== chunkY)430
{431
if (isDraftDirty())432
{433
showUnsavedModal({ chunkX: cx, chunkY: cy, dimensionId: selectedDimensionId });434
return false;435
}436
doLoadNeighborhood(cx, cy);437
}438
if (!view?.scene)439
{ return true; }440
const size = view.tileSize();441
view.followPlayer = false;442
view.scene.cameraPosition.x = view.scene.real_size.x / 2 - ((tileX | 0) + 0.5) * size;443
view.scene.cameraPosition.y = view.scene.real_size.y / 2 - ((tileY | 0) + 0.5) * size;444
view.refreshViewport();445
updateSelectionBorder();446
return true;447
}448
342
function blockAtWorld (tileX, tileY)449
function blockAtWorld (tileX, tileY)343
{450
{344
const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);451
const { chunkX: cx, chunkY: cy, localX, localY } = worldTileToChunkLocal(tileX, tileY, CHUNK_SIZE);@@ -1265,11 +1372,16 @@ async function main ()1265
applyDimensionsList(message);1372
applyDimensionsList(message);1266
}1373
}1267
else if (message.type === MessageType.editorQuests)1374
else if (message.type === MessageType.editorQuests)1268
{ questsModal?.handleMessage(message); }1375
{1376
questsModal?.handleMessage(message);1377
settingsModal?.handleMessage(message);1378
dialoguesModal?.handleMessage(message);1379
}1269
else if (message.type === MessageType.editorDialogues)1380
else if (message.type === MessageType.editorDialogues)1270
{1381
{1271
dialoguesModal?.handleMessage(message);1382
dialoguesModal?.handleMessage(message);1272
tileConfigModal?.handleMessage(message);1383
tileConfigModal?.handleMessage(message);1384
questsModal?.handleMessage(message);1273
}1385
}1274
else if (message.type === MessageType.editorGiftCharacters1386
else if (message.type === MessageType.editorGiftCharacters1275
|| message.type === MessageType.editorGiftSent)1387
|| message.type === MessageType.editorGiftSent)@@ -1401,8 +1513,30 @@ async function main ()1401
getDimensionRecord: (id) => dimensionsById.get(id) ?? null,1513
getDimensionRecord: (id) => dimensionsById.get(id) ?? null,1402
isOverworld1514
isOverworld1403
});1515
});1404
questsModal = initQuestsModal({ socket, MessageType });1516
questsModal = initQuestsModal({1405
dialoguesModal = initDialoguesModal({ socket, MessageType });1517
socket,1518
MessageType,1519
describeWorldTile,1520
centerEditorOnTile,1521
getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({1522
id: dim.dimensionId,1523
label: dim.displayName || dim.dimensionId,1524
disabled: dim.deletedAt != null,1525
hint: dim.deletedAt != null ? "soft-deleted" : null1526
}))1527
});1528
dialoguesModal = initDialoguesModal({1529
socket,1530
MessageType,1531
describeWorldTile,1532
centerEditorOnTile,1533
getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({1534
id: dim.dimensionId,1535
label: dim.displayName || dim.dimensionId,1536
disabled: dim.deletedAt != null,1537
hint: dim.deletedAt != null ? "soft-deleted" : null1538
}))1539
});1406
giftsModal = initGiftsModal({ socket, MessageType });1540
giftsModal = initGiftsModal({ socket, MessageType });1407
initSidePanelTabs();1541
initSidePanelTabs();1408
game.startGame();1542
game.startGame();@@ -1,17 +1,14 @@
1
import { normalizeQuestDef } from "/shared/quests/normalize.js";
2
import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
1
import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
2
import { emptyConditionSet } from "/shared/quests/conditions.js";
3
import { renderConditionSet } from "./conditionSetEditor.js";
3
4
4
const SIMPLE_KINDS = [
5
ConditionKind.hasItem,
6
ConditionKind.questState,
7
ConditionKind.dialogueHeard,
8
ConditionKind.killCount,
9
ConditionKind.atTile,
10
ConditionKind.inDimension,
11
ConditionKind.hasVisitedDimension
12
];
13
14
export function initQuestsModal ({ socket, MessageType })
5
export function initQuestsModal ({
6
socket,
7
MessageType,
8
describeWorldTile = null,
9
centerEditorOnTile = null,
10
getDimensionOptions = null
11
})
15
12
{
16
13
const backdrop = document.getElementById("quests-backdrop");
17
14
const modal = document.getElementById("quests-modal");
@@ -22,6 +19,8 @@ export function initQuestsModal ({ socket, MessageType })
22
19
let open = false;
23
20
/** @type {ReturnType<typeof normalizeQuestDef>[]} */
24
21
let quests = [];
22
/** @type {ReturnType<typeof normalizeDialogueTree>[]} */
23
let dialogues = [];
25
24
/** @type {ReturnType<typeof normalizeQuestDef>|null} */
26
25
let draft = null;
27
26
let selectedId = null;
@@ -162,11 +161,12 @@ export function initQuestsModal ({ socket, MessageType })
162
161
}),
163
162
field("Text", textInput(obj.text, (v) => { obj.text = v; }))
164
163
);
165
objBox.append(renderConditionSet(obj.when, (next) =>
164
objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>
166
165
{
167
166
obj.when = next;
168
renderEditor();
169
}));
167
if (remount)
168
{ renderEditor(); }
169
}, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions }));
170
170
box.append(objBox);
171
171
});
172
172
editorEl.append(box);
@@ -182,6 +182,7 @@ export function initQuestsModal ({ socket, MessageType })
182
182
document.getElementById("open-quests").addEventListener("click", () =>
183
183
{
184
184
socket.send({ type: MessageType.editorLoadQuests });
185
socket.send({ type: MessageType.editorLoadDialogues });
185
186
show(true);
186
187
render();
187
188
});
@@ -217,6 +218,13 @@ export function initQuestsModal ({ socket, MessageType })
217
218
isOpen: () => open,
218
219
handleMessage (message)
219
220
{
221
if (message.type === MessageType.editorDialogues)
222
{
223
dialogues = (message.dialogues ?? []).map((d) => normalizeDialogueTree(d));
224
if (open)
225
{ render(); }
226
return;
227
}
220
228
if (message.type !== MessageType.editorQuests)
221
229
{ return; }
222
230
quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
@@ -296,241 +304,4 @@ function sectionHeader (title, onAdd, onRemove)
296
304
return head;
297
305
}
298
306
299
function renderConditionSet (when, onChange)
300
{
301
const wrap = document.createElement("div");
302
const set = normalizeConditionSet(when);
303
const title = document.createElement("strong");
304
title.textContent = "When (all of)";
305
wrap.append(title);
306
307
set.all.forEach((clause, index) =>
308
{
309
const row = document.createElement("div");
310
row.className = "content-editor-clause";
311
const notLabel = document.createElement("label");
312
const notBox = document.createElement("input");
313
notBox.type = "checkbox";
314
notBox.checked = !!clause.not;
315
notBox.addEventListener("change", () =>
316
{
317
set.all[index].not = notBox.checked;
318
onChange(set);
319
});
320
notLabel.append(notBox, document.createTextNode(" NOT"));
321
row.append(notLabel);
322
323
const kind = document.createElement("select");
324
for (const k of SIMPLE_KINDS)
325
{
326
const opt = document.createElement("option");
327
opt.value = k;
328
opt.textContent = k;
329
if ((clause.condition?.kind ?? "") === k)
330
{ opt.selected = true; }
331
kind.append(opt);
332
}
333
const otherOpt = document.createElement("option");
334
otherOpt.value = "__other__";
335
otherOpt.textContent = "(other / JSON)";
336
if (!SIMPLE_KINDS.includes(clause.condition?.kind))
337
{ otherOpt.selected = true; }
338
kind.append(otherOpt);
339
kind.addEventListener("change", () =>
340
{
341
if (kind.value === "__other__")
342
{ return; }
343
set.all[index].condition = defaultCondition(kind.value);
344
onChange(set);
345
});
346
row.append(kind);
347
348
const cond = clause.condition ?? { kind: ConditionKind.hasItem };
349
if (cond.kind === ConditionKind.hasItem)
350
{
351
row.append(miniField("itemId", cond.itemId ?? "", (v) =>
352
{
353
cond.itemId = Number(v) || 0;
354
set.all[index].condition = cond;
355
onChange(set);
356
}));
357
row.append(miniField("qty", cond.quantity ?? 1, (v) =>
358
{
359
cond.quantity = Number(v) || 1;
360
set.all[index].condition = cond;
361
onChange(set);
362
}));
363
}
364
else if (cond.kind === ConditionKind.questState)
365
{
366
row.append(miniField("questId", cond.questId ?? "", (v) =>
367
{
368
cond.questId = v;
369
set.all[index].condition = cond;
370
onChange(set);
371
}));
372
row.append(miniField("state", cond.state ?? "not-started", (v) =>
373
{
374
const n = Number(v);
375
cond.state = Number.isFinite(n) && String(n) === String(v).trim() ? n : v;
376
set.all[index].condition = cond;
377
onChange(set);
378
}));
379
}
380
else if (cond.kind === ConditionKind.dialogueHeard)
381
{
382
row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) =>
383
{
384
cond.dialogueId = v;
385
set.all[index].condition = cond;
386
onChange(set);
387
}));
388
row.append(miniField("stepId", cond.stepId ?? "", (v) =>
389
{
390
cond.stepId = v;
391
set.all[index].condition = cond;
392
onChange(set);
393
}));
394
}
395
else if (cond.kind === ConditionKind.killCount)
396
{
397
row.append(miniField("mobTypeId", cond.mobTypeId ?? "", (v) =>
398
{
399
cond.mobTypeId = v || undefined;
400
set.all[index].condition = cond;
401
onChange(set);
402
}));
403
row.append(miniField("count", cond.count ?? 1, (v) =>
404
{
405
cond.count = Number(v) || 1;
406
set.all[index].condition = cond;
407
onChange(set);
408
}));
409
}
410
else if (cond.kind === ConditionKind.atTile)
411
{
412
row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
413
{
414
cond.dimensionId = String(v || "overworld");
415
set.all[index].condition = cond;
416
onChange(set);
417
}));
418
row.append(miniField("tileX", cond.tileX ?? 0, (v) =>
419
{
420
cond.tileX = Number(v) | 0;
421
set.all[index].condition = cond;
422
onChange(set);
423
}));
424
row.append(miniField("tileY", cond.tileY ?? 0, (v) =>
425
{
426
cond.tileY = Number(v) | 0;
427
set.all[index].condition = cond;
428
onChange(set);
429
}));
430
}
431
else if (
432
cond.kind === ConditionKind.inDimension
433
|| cond.kind === ConditionKind.hasVisitedDimension
434
)
435
{
436
row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
437
{
438
cond.dimensionId = String(v || "overworld");
439
set.all[index].condition = cond;
440
onChange(set);
441
}));
442
}
443
else
444
{
445
const json = document.createElement("textarea");
446
json.rows = 3;
447
json.value = JSON.stringify(cond, null, 2);
448
json.addEventListener("change", () =>
449
{
450
try
451
{
452
set.all[index].condition = JSON.parse(json.value);
453
onChange(set);
454
}
455
catch
456
{ /* keep typing */ }
457
});
458
row.append(json);
459
}
460
461
const remove = document.createElement("button");
462
remove.type = "button";
463
remove.textContent = "×";
464
remove.addEventListener("click", () =>
465
{
466
set.all.splice(index, 1);
467
onChange(set);
468
});
469
row.append(remove);
470
wrap.append(row);
471
});
472
473
const add = document.createElement("button");
474
add.type = "button";
475
add.textContent = "Add clause";
476
add.addEventListener("click", () =>
477
{
478
set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) });
479
onChange(set);
480
});
481
wrap.append(add);
482
483
const jsonFallback = document.createElement("details");
484
const summary = document.createElement("summary");
485
summary.textContent = "Edit condition set as JSON";
486
const area = document.createElement("textarea");
487
area.rows = 5;
488
area.value = JSON.stringify(set, null, 2);
489
area.addEventListener("change", () =>
490
{
491
try
492
{
493
onChange(normalizeConditionSet(JSON.parse(area.value)));
494
}
495
catch
496
{ /* ignore */ }
497
});
498
jsonFallback.append(summary, area);
499
wrap.append(jsonFallback);
500
return wrap;
501
}
502
503
function miniField (label, value, onChange)
504
{
505
const wrap = document.createElement("label");
506
wrap.textContent = `${label} `;
507
const input = document.createElement("input");
508
input.type = "text";
509
input.value = String(value ?? "");
510
input.style.width = "7rem";
511
input.addEventListener("input", () => onChange(input.value));
512
wrap.append(input);
513
return wrap;
514
}
515
307
516
function defaultCondition (kind)
517
{
518
switch (kind)
519
{
520
case ConditionKind.hasItem:
521
return { kind, itemId: 1, quantity: 1 };
522
case ConditionKind.questState:
523
return { kind, questId: "", state: "not-started" };
524
case ConditionKind.dialogueHeard:
525
return { kind, dialogueId: "", stepId: "" };
526
case ConditionKind.killCount:
527
return { kind, mobTypeId: "deer", count: 1 };
528
case ConditionKind.atTile:
529
return { kind, dimensionId: "overworld", tileX: 0, tileY: 0 };
530
case ConditionKind.inDimension:
531
case ConditionKind.hasVisitedDimension:
532
return { kind, dimensionId: "overworld" };
533
default:
534
return { kind };
535
}
536
}
@@ -1,17 +1,14 @@1
import { normalizeQuestDef } from "/shared/quests/normalize.js";1
import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";2
import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";2
import { emptyConditionSet } from "/shared/quests/conditions.js";3
import { renderConditionSet } from "./conditionSetEditor.js";3
4
4
const SIMPLE_KINDS = [5
export function initQuestsModal ({5
ConditionKind.hasItem,6
socket,6
ConditionKind.questState,7
MessageType,7
ConditionKind.dialogueHeard,8
describeWorldTile = null,8
ConditionKind.killCount,9
centerEditorOnTile = null,9
ConditionKind.atTile,10
getDimensionOptions = null10
ConditionKind.inDimension,11
})11
ConditionKind.hasVisitedDimension12
];13
14
export function initQuestsModal ({ socket, MessageType })15
{12
{16
const backdrop = document.getElementById("quests-backdrop");13
const backdrop = document.getElementById("quests-backdrop");17
const modal = document.getElementById("quests-modal");14
const modal = document.getElementById("quests-modal");@@ -22,6 +19,8 @@ export function initQuestsModal ({ socket, MessageType })22
let open = false;19
let open = false;23
/** @type {ReturnType<typeof normalizeQuestDef>[]} */20
/** @type {ReturnType<typeof normalizeQuestDef>[]} */24
let quests = [];21
let quests = [];22
/** @type {ReturnType<typeof normalizeDialogueTree>[]} */23
let dialogues = [];25
/** @type {ReturnType<typeof normalizeQuestDef>|null} */24
/** @type {ReturnType<typeof normalizeQuestDef>|null} */26
let draft = null;25
let draft = null;27
let selectedId = null;26
let selectedId = null;@@ -162,11 +161,12 @@ export function initQuestsModal ({ socket, MessageType })162
}),161
}),163
field("Text", textInput(obj.text, (v) => { obj.text = v; }))162
field("Text", textInput(obj.text, (v) => { obj.text = v; }))164
);163
);165
objBox.append(renderConditionSet(obj.when, (next) =>164
objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>166
{165
{167
obj.when = next;166
obj.when = next;168
renderEditor();167
if (remount)169
}));168
{ renderEditor(); }169
}, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions }));170
box.append(objBox);170
box.append(objBox);171
});171
});172
editorEl.append(box);172
editorEl.append(box);@@ -182,6 +182,7 @@ export function initQuestsModal ({ socket, MessageType })182
document.getElementById("open-quests").addEventListener("click", () =>182
document.getElementById("open-quests").addEventListener("click", () =>183
{183
{184
socket.send({ type: MessageType.editorLoadQuests });184
socket.send({ type: MessageType.editorLoadQuests });185
socket.send({ type: MessageType.editorLoadDialogues });185
show(true);186
show(true);186
render();187
render();187
});188
});@@ -217,6 +218,13 @@ export function initQuestsModal ({ socket, MessageType })217
isOpen: () => open,218
isOpen: () => open,218
handleMessage (message)219
handleMessage (message)219
{220
{221
if (message.type === MessageType.editorDialogues)222
{223
dialogues = (message.dialogues ?? []).map((d) => normalizeDialogueTree(d));224
if (open)225
{ render(); }226
return;227
}220
if (message.type !== MessageType.editorQuests)228
if (message.type !== MessageType.editorQuests)221
{ return; }229
{ return; }222
quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));230
quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));@@ -296,241 +304,4 @@ function sectionHeader (title, onAdd, onRemove)296
return head;304
return head;297
}305
}298
306
299
function renderConditionSet (when, onChange)300
{301
const wrap = document.createElement("div");302
const set = normalizeConditionSet(when);303
const title = document.createElement("strong");304
title.textContent = "When (all of)";305
wrap.append(title);306
307
set.all.forEach((clause, index) =>308
{309
const row = document.createElement("div");310
row.className = "content-editor-clause";311
const notLabel = document.createElement("label");312
const notBox = document.createElement("input");313
notBox.type = "checkbox";314
notBox.checked = !!clause.not;315
notBox.addEventListener("change", () =>316
{317
set.all[index].not = notBox.checked;318
onChange(set);319
});320
notLabel.append(notBox, document.createTextNode(" NOT"));321
row.append(notLabel);322
323
const kind = document.createElement("select");324
for (const k of SIMPLE_KINDS)325
{326
const opt = document.createElement("option");327
opt.value = k;328
opt.textContent = k;329
if ((clause.condition?.kind ?? "") === k)330
{ opt.selected = true; }331
kind.append(opt);332
}333
const otherOpt = document.createElement("option");334
otherOpt.value = "__other__";335
otherOpt.textContent = "(other / JSON)";336
if (!SIMPLE_KINDS.includes(clause.condition?.kind))337
{ otherOpt.selected = true; }338
kind.append(otherOpt);339
kind.addEventListener("change", () =>340
{341
if (kind.value === "__other__")342
{ return; }343
set.all[index].condition = defaultCondition(kind.value);344
onChange(set);345
});346
row.append(kind);347
348
const cond = clause.condition ?? { kind: ConditionKind.hasItem };349
if (cond.kind === ConditionKind.hasItem)350
{351
row.append(miniField("itemId", cond.itemId ?? "", (v) =>352
{353
cond.itemId = Number(v) || 0;354
set.all[index].condition = cond;355
onChange(set);356
}));357
row.append(miniField("qty", cond.quantity ?? 1, (v) =>358
{359
cond.quantity = Number(v) || 1;360
set.all[index].condition = cond;361
onChange(set);362
}));363
}364
else if (cond.kind === ConditionKind.questState)365
{366
row.append(miniField("questId", cond.questId ?? "", (v) =>367
{368
cond.questId = v;369
set.all[index].condition = cond;370
onChange(set);371
}));372
row.append(miniField("state", cond.state ?? "not-started", (v) =>373
{374
const n = Number(v);375
cond.state = Number.isFinite(n) && String(n) === String(v).trim() ? n : v;376
set.all[index].condition = cond;377
onChange(set);378
}));379
}380
else if (cond.kind === ConditionKind.dialogueHeard)381
{382
row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) =>383
{384
cond.dialogueId = v;385
set.all[index].condition = cond;386
onChange(set);387
}));388
row.append(miniField("stepId", cond.stepId ?? "", (v) =>389
{390
cond.stepId = v;391
set.all[index].condition = cond;392
onChange(set);393
}));394
}395
else if (cond.kind === ConditionKind.killCount)396
{397
row.append(miniField("mobTypeId", cond.mobTypeId ?? "", (v) =>398
{399
cond.mobTypeId = v || undefined;400
set.all[index].condition = cond;401
onChange(set);402
}));403
row.append(miniField("count", cond.count ?? 1, (v) =>404
{405
cond.count = Number(v) || 1;406
set.all[index].condition = cond;407
onChange(set);408
}));409
}410
else if (cond.kind === ConditionKind.atTile)411
{412
row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>413
{414
cond.dimensionId = String(v || "overworld");415
set.all[index].condition = cond;416
onChange(set);417
}));418
row.append(miniField("tileX", cond.tileX ?? 0, (v) =>419
{420
cond.tileX = Number(v) | 0;421
set.all[index].condition = cond;422
onChange(set);423
}));424
row.append(miniField("tileY", cond.tileY ?? 0, (v) =>425
{426
cond.tileY = Number(v) | 0;427
set.all[index].condition = cond;428
onChange(set);429
}));430
}431
else if (432
cond.kind === ConditionKind.inDimension433
|| cond.kind === ConditionKind.hasVisitedDimension434
)435
{436
row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>437
{438
cond.dimensionId = String(v || "overworld");439
set.all[index].condition = cond;440
onChange(set);441
}));442
}443
else444
{445
const json = document.createElement("textarea");446
json.rows = 3;447
json.value = JSON.stringify(cond, null, 2);448
json.addEventListener("change", () =>449
{450
try451
{452
set.all[index].condition = JSON.parse(json.value);453
onChange(set);454
}455
catch456
{ /* keep typing */ }457
});458
row.append(json);459
}460
461
const remove = document.createElement("button");462
remove.type = "button";463
remove.textContent = "×";464
remove.addEventListener("click", () =>465
{466
set.all.splice(index, 1);467
onChange(set);468
});469
row.append(remove);470
wrap.append(row);471
});472
473
const add = document.createElement("button");474
add.type = "button";475
add.textContent = "Add clause";476
add.addEventListener("click", () =>477
{478
set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) });479
onChange(set);480
});481
wrap.append(add);482
483
const jsonFallback = document.createElement("details");484
const summary = document.createElement("summary");485
summary.textContent = "Edit condition set as JSON";486
const area = document.createElement("textarea");487
area.rows = 5;488
area.value = JSON.stringify(set, null, 2);489
area.addEventListener("change", () =>490
{491
try492
{493
onChange(normalizeConditionSet(JSON.parse(area.value)));494
}495
catch496
{ /* ignore */ }497
});498
jsonFallback.append(summary, area);499
wrap.append(jsonFallback);500
return wrap;501
}502
503
function miniField (label, value, onChange)504
{505
const wrap = document.createElement("label");506
wrap.textContent = `${label} `;507
const input = document.createElement("input");508
input.type = "text";509
input.value = String(value ?? "");510
input.style.width = "7rem";511
input.addEventListener("input", () => onChange(input.value));512
wrap.append(input);513
return wrap;514
}515
307
516
function defaultCondition (kind)517
{518
switch (kind)519
{520
case ConditionKind.hasItem:521
return { kind, itemId: 1, quantity: 1 };522
case ConditionKind.questState:523
return { kind, questId: "", state: "not-started" };524
case ConditionKind.dialogueHeard:525
return { kind, dialogueId: "", stepId: "" };526
case ConditionKind.killCount:527
return { kind, mobTypeId: "deer", count: 1 };528
case ConditionKind.atTile:529
return { kind, dimensionId: "overworld", tileX: 0, tileY: 0 };530
case ConditionKind.inDimension:531
case ConditionKind.hasVisitedDimension:532
return { kind, dimensionId: "overworld" };533
default:534
return { kind };535
}536
}@@ -22,6 +22,12 @@ import
22
22
DEFAULT_STARTER_EQUIPMENT,
23
23
DEFAULT_STARTER_INVENTORY
24
24
} from "/shared/items/starterLoadout.js";
25
import
26
{
27
normalizeInitialQuests,
28
initialQuestsEqual
29
} from "/shared/quests/initialQuests.js";
30
import { normalizeQuestDef } from "/shared/quests/normalize.js";
25
31
import
26
32
{
27
33
EQUIPMENT_STAT_CATEGORIES,
@@ -70,6 +76,11 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
70
76
starterInventory: DEFAULT_STARTER_INVENTORY
71
77
});
72
78
let starterPanel = null;
79
/** @type {string[]} */
80
let draftInitialQuests = [];
81
/** @type {{ questId: string, title: string }[]} */
82
let questCatalog = [];
83
let initialQuestsPanel = null;
73
84
let draftEquipmentStats = normalizeEquipmentStatBonuses(null);
74
85
let equipmentStatsPanel = null;
75
86
let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;
@@ -87,6 +98,11 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
87
98
{ renderSeedPanel(); }
88
99
if (id === "starterEquipment")
89
100
{ renderStarterPanel(); }
101
if (id === "initialQuests")
102
{
103
socket.send({ type: MessageType.editorLoadQuests });
104
renderInitialQuestsPanel();
105
}
90
106
if (id === "equipmentStats")
91
107
{ renderEquipmentStatsPanel(); }
92
108
if (id === "gameAdmins")
@@ -108,6 +124,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
108
124
{
109
125
starterPanel = panel;
110
126
},
127
onInitialQuestsPanelReady (panel)
128
{
129
initialQuestsPanel = panel;
130
},
111
131
onEquipmentStatsPanelReady (panel)
112
132
{
113
133
equipmentStatsPanel = panel;
@@ -150,6 +170,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
150
170
refreshDirty();
151
171
});
152
172
form.addEventListener("starter-changed", () => refreshDirty());
173
form.addEventListener("initial-quests-changed", () => refreshDirty());
153
174
form.addEventListener("equipment-stats-changed", () => refreshDirty());
154
175
form.addEventListener("equip-stats-category", (event) =>
155
176
{
@@ -168,6 +189,15 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
168
189
renderStarterPanel();
169
190
form.dispatchEvent(new CustomEvent("starter-changed"));
170
191
});
192
form.addEventListener("initial-quests-add", () =>
193
{
194
const available = questCatalog.find((q) => !draftInitialQuests.includes(q.questId));
195
if (!available)
196
{ return; }
197
draftInitialQuests = normalizeInitialQuests([...draftInitialQuests, available.questId]);
198
renderInitialQuestsPanel();
199
form.dispatchEvent(new CustomEvent("initial-quests-changed"));
200
});
171
201
form.addEventListener("game-admin-grant", (event) =>
172
202
{
173
203
const username = String(event.detail?.username ?? "").trim();
@@ -244,6 +274,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
244
274
fillForm(form, baseline);
245
275
draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };
246
276
draftStarter = normalizeStarterLoadout(baseline);
277
draftInitialQuests = normalizeInitialQuests(baseline.initialQuests);
247
278
draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
248
279
seedQuery = "";
249
280
seedPage = 0;
@@ -251,6 +282,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
251
282
{ seedPanel.search.value = ""; }
252
283
renderSeedPanel();
253
284
renderStarterPanel();
285
renderInitialQuestsPanel();
254
286
renderEquipmentStatsPanel();
255
287
refreshDirty();
256
288
}
@@ -286,6 +318,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
286
318
itemSeedValues: draftSeeds,
287
319
starterEquipment: draftStarter.equipment,
288
320
starterInventory: draftStarter.inventory,
321
initialQuests: draftInitialQuests,
289
322
equipmentStatBonuses: draftEquipmentStats
290
323
};
291
324
}
@@ -306,6 +339,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
306
339
changed.starterEquipment = nextStarter.equipment;
307
340
changed.starterInventory = nextStarter.inventory;
308
341
}
342
const nextInitialQuests = normalizeInitialQuests(draftInitialQuests);
343
if (!initialQuestsEqual(baseline.initialQuests, nextInitialQuests))
344
{ changed.initialQuests = nextInitialQuests; }
309
345
const nextEquip = normalizeEquipmentStatBonuses(draftEquipmentStats);
310
346
if (!equipmentStatBonusMapsEqual(baseline.equipmentStatBonuses, nextEquip))
311
347
{ changed.equipmentStatBonuses = nextEquip; }
@@ -529,6 +565,72 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
529
565
refreshDirty();
530
566
}
531
567
568
function renderInitialQuestsPanel ()
569
{
570
if (!initialQuestsPanel)
571
{ return; }
572
const { listRoot, addBtn } = initialQuestsPanel;
573
listRoot.replaceChildren();
574
const taken = new Set(draftInitialQuests);
575
const available = questCatalog.filter((q) => !taken.has(q.questId));
576
addBtn.disabled = available.length === 0;
577
if (!draftInitialQuests.length)
578
{
579
const empty = document.createElement("p");
580
empty.className = "hint";
581
empty.textContent = "No initial quests.";
582
listRoot.append(empty);
583
}
584
draftInitialQuests.forEach((questId, index) =>
585
{
586
const row = document.createElement("div");
587
row.className = "initial-quest-row";
588
const select = document.createElement("select");
589
const catalog = questCatalog.length
590
? questCatalog
591
: [{ questId, title: questId }];
592
for (const quest of catalog)
593
{
594
if (taken.has(quest.questId) && quest.questId !== questId)
595
{ continue; }
596
const opt = document.createElement("option");
597
opt.value = quest.questId;
598
opt.textContent = quest.title
599
? `${quest.title} (${quest.questId})`
600
: quest.questId;
601
select.append(opt);
602
}
603
if (![...select.options].some((o) => o.value === questId))
604
{
605
const missing = document.createElement("option");
606
missing.value = questId;
607
missing.textContent = `${questId} (missing)`;
608
select.append(missing);
609
}
610
select.value = questId;
611
select.addEventListener("change", () =>
612
{
613
const next = draftInitialQuests.slice();
614
next[index] = select.value;
615
draftInitialQuests = normalizeInitialQuests(next);
616
renderInitialQuestsPanel();
617
form.dispatchEvent(new CustomEvent("initial-quests-changed"));
618
});
619
const remove = document.createElement("button");
620
remove.type = "button";
621
remove.textContent = "Remove";
622
remove.addEventListener("click", () =>
623
{
624
draftInitialQuests = draftInitialQuests.filter((_, i) => i !== index);
625
renderInitialQuestsPanel();
626
form.dispatchEvent(new CustomEvent("initial-quests-changed"));
627
});
628
row.append(select, remove);
629
listRoot.append(row);
630
});
631
refreshDirty();
632
}
633
532
634
function setRowIcon (img, itemId)
533
635
{
534
636
if (!img)
@@ -734,21 +836,34 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
734
836
renderGameAdminsPanel();
735
837
return;
736
838
}
839
if (message.type === MessageType.editorQuests)
840
{
841
questCatalog = (message.quests ?? []).map((q) =>
842
{
843
const def = normalizeQuestDef(q);
844
return { questId: def.questId, title: def.title };
845
});
846
renderInitialQuestsPanel();
847
return;
848
}
737
849
loaded = true;
738
850
baseline = {
739
851
...message.settings,
740
852
itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues),
741
equipmentStatBonuses: normalizeEquipmentStatBonuses(message.settings?.equipmentStatBonuses)
853
equipmentStatBonuses: normalizeEquipmentStatBonuses(message.settings?.equipmentStatBonuses),
854
initialQuests: normalizeInitialQuests(message.settings?.initialQuests)
742
855
};
743
856
itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"
744
857
? message.itemLastSales
745
858
: {};
746
859
draftSeeds = { ...baseline.itemSeedValues };
747
860
draftStarter = normalizeStarterLoadout(baseline);
861
draftInitialQuests = normalizeInitialQuests(baseline.initialQuests);
748
862
draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);
749
863
fillForm(form, baseline);
750
864
renderSeedPanel();
751
865
renderStarterPanel();
866
renderInitialQuestsPanel();
752
867
renderEquipmentStatsPanel();
753
868
refreshDirty();
754
869
renderLog(log, message.changelog ?? []);
@@ -763,6 +878,7 @@ function buildForm (form, {
763
878
onFieldInput,
764
879
onSeedPanelReady,
765
880
onStarterPanelReady,
881
onInitialQuestsPanelReady,
766
882
onEquipmentStatsPanelReady,
767
883
onGameAdminsPanelReady
768
884
})
@@ -810,6 +926,15 @@ function buildForm (form, {
810
926
section.append(panel.root);
811
927
onStarterPanelReady?.(panel);
812
928
}
929
else if (category.panel === "initialQuests")
930
{
931
const panel = buildInitialQuestsPanel({
932
onAdd ()
933
{ form.dispatchEvent(new CustomEvent("initial-quests-add")); }
934
});
935
section.append(panel.root);
936
onInitialQuestsPanelReady?.(panel);
937
}
813
938
else if (category.panel === "equipmentStats")
814
939
{
815
940
const panel = buildEquipmentStatsPanel({
@@ -1016,6 +1141,23 @@ function buildStarterEquipmentPanel ({ onAddInventory })
1016
1141
return { root, equipRoot, invRoot };
1017
1142
}
1018
1143
1144
function buildInitialQuestsPanel ({ onAdd })
1145
{
1146
const root = document.createElement("div");
1147
root.className = "initial-quests-panel";
1148
const hint = document.createElement("p");
1149
hint.className = "hint";
1150
hint.textContent = "These quests are granted to new characters. Existing characters also receive them on save or login unless the quest is already started or completed.";
1151
const listRoot = document.createElement("div");
1152
listRoot.className = "initial-quests-list";
1153
const addBtn = document.createElement("button");
1154
addBtn.type = "button";
1155
addBtn.textContent = "Add quest";
1156
addBtn.addEventListener("click", () => onAdd?.());
1157
root.append(hint, listRoot, addBtn);
1158
return { root, listRoot, addBtn };
1159
}
1160
1019
1161
function listAllItems ()
1020
1162
{
1021
1163
return Object.values(ITEM_DEFINITIONS)
@@ -22,6 +22,12 @@ import22
DEFAULT_STARTER_EQUIPMENT,22
DEFAULT_STARTER_EQUIPMENT,23
DEFAULT_STARTER_INVENTORY23
DEFAULT_STARTER_INVENTORY24
} from "/shared/items/starterLoadout.js";24
} from "/shared/items/starterLoadout.js";25
import26
{27
normalizeInitialQuests,28
initialQuestsEqual29
} from "/shared/quests/initialQuests.js";30
import { normalizeQuestDef } from "/shared/quests/normalize.js";25
import31
import26
{32
{27
EQUIPMENT_STAT_CATEGORIES,33
EQUIPMENT_STAT_CATEGORIES,@@ -70,6 +76,11 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi70
starterInventory: DEFAULT_STARTER_INVENTORY76
starterInventory: DEFAULT_STARTER_INVENTORY71
});77
});72
let starterPanel = null;78
let starterPanel = null;79
/** @type {string[]} */80
let draftInitialQuests = [];81
/** @type {{ questId: string, title: string }[]} */82
let questCatalog = [];83
let initialQuestsPanel = null;73
let draftEquipmentStats = normalizeEquipmentStatBonuses(null);84
let draftEquipmentStats = normalizeEquipmentStatBonuses(null);74
let equipmentStatsPanel = null;85
let equipmentStatsPanel = null;75
let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;86
let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;@@ -87,6 +98,11 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi87
{ renderSeedPanel(); }98
{ renderSeedPanel(); }88
if (id === "starterEquipment")99
if (id === "starterEquipment")89
{ renderStarterPanel(); }100
{ renderStarterPanel(); }101
if (id === "initialQuests")102
{103
socket.send({ type: MessageType.editorLoadQuests });104
renderInitialQuestsPanel();105
}90
if (id === "equipmentStats")106
if (id === "equipmentStats")91
{ renderEquipmentStatsPanel(); }107
{ renderEquipmentStatsPanel(); }92
if (id === "gameAdmins")108
if (id === "gameAdmins")@@ -108,6 +124,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi108
{124
{109
starterPanel = panel;125
starterPanel = panel;110
},126
},127
onInitialQuestsPanelReady (panel)128
{129
initialQuestsPanel = panel;130
},111
onEquipmentStatsPanelReady (panel)131
onEquipmentStatsPanelReady (panel)112
{132
{113
equipmentStatsPanel = panel;133
equipmentStatsPanel = panel;@@ -150,6 +170,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi150
refreshDirty();170
refreshDirty();151
});171
});152
form.addEventListener("starter-changed", () => refreshDirty());172
form.addEventListener("starter-changed", () => refreshDirty());173
form.addEventListener("initial-quests-changed", () => refreshDirty());153
form.addEventListener("equipment-stats-changed", () => refreshDirty());174
form.addEventListener("equipment-stats-changed", () => refreshDirty());154
form.addEventListener("equip-stats-category", (event) =>175
form.addEventListener("equip-stats-category", (event) =>155
{176
{@@ -168,6 +189,15 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi168
renderStarterPanel();189
renderStarterPanel();169
form.dispatchEvent(new CustomEvent("starter-changed"));190
form.dispatchEvent(new CustomEvent("starter-changed"));170
});191
});192
form.addEventListener("initial-quests-add", () =>193
{194
const available = questCatalog.find((q) => !draftInitialQuests.includes(q.questId));195
if (!available)196
{ return; }197
draftInitialQuests = normalizeInitialQuests([...draftInitialQuests, available.questId]);198
renderInitialQuestsPanel();199
form.dispatchEvent(new CustomEvent("initial-quests-changed"));200
});171
form.addEventListener("game-admin-grant", (event) =>201
form.addEventListener("game-admin-grant", (event) =>172
{202
{173
const username = String(event.detail?.username ?? "").trim();203
const username = String(event.detail?.username ?? "").trim();@@ -244,6 +274,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi244
fillForm(form, baseline);274
fillForm(form, baseline);245
draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };275
draftSeeds = { ...normalizeItemSeedValues(baseline.itemSeedValues) };246
draftStarter = normalizeStarterLoadout(baseline);276
draftStarter = normalizeStarterLoadout(baseline);277
draftInitialQuests = normalizeInitialQuests(baseline.initialQuests);247
draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);278
draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);248
seedQuery = "";279
seedQuery = "";249
seedPage = 0;280
seedPage = 0;@@ -251,6 +282,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi251
{ seedPanel.search.value = ""; }282
{ seedPanel.search.value = ""; }252
renderSeedPanel();283
renderSeedPanel();253
renderStarterPanel();284
renderStarterPanel();285
renderInitialQuestsPanel();254
renderEquipmentStatsPanel();286
renderEquipmentStatsPanel();255
refreshDirty();287
refreshDirty();256
}288
}@@ -286,6 +318,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi286
itemSeedValues: draftSeeds,318
itemSeedValues: draftSeeds,287
starterEquipment: draftStarter.equipment,319
starterEquipment: draftStarter.equipment,288
starterInventory: draftStarter.inventory,320
starterInventory: draftStarter.inventory,321
initialQuests: draftInitialQuests,289
equipmentStatBonuses: draftEquipmentStats322
equipmentStatBonuses: draftEquipmentStats290
};323
};291
}324
}@@ -306,6 +339,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi306
changed.starterEquipment = nextStarter.equipment;339
changed.starterEquipment = nextStarter.equipment;307
changed.starterInventory = nextStarter.inventory;340
changed.starterInventory = nextStarter.inventory;308
}341
}342
const nextInitialQuests = normalizeInitialQuests(draftInitialQuests);343
if (!initialQuestsEqual(baseline.initialQuests, nextInitialQuests))344
{ changed.initialQuests = nextInitialQuests; }309
const nextEquip = normalizeEquipmentStatBonuses(draftEquipmentStats);345
const nextEquip = normalizeEquipmentStatBonuses(draftEquipmentStats);310
if (!equipmentStatBonusMapsEqual(baseline.equipmentStatBonuses, nextEquip))346
if (!equipmentStatBonusMapsEqual(baseline.equipmentStatBonuses, nextEquip))311
{ changed.equipmentStatBonuses = nextEquip; }347
{ changed.equipmentStatBonuses = nextEquip; }@@ -529,6 +565,72 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi529
refreshDirty();565
refreshDirty();530
}566
}531
567
568
function renderInitialQuestsPanel ()569
{570
if (!initialQuestsPanel)571
{ return; }572
const { listRoot, addBtn } = initialQuestsPanel;573
listRoot.replaceChildren();574
const taken = new Set(draftInitialQuests);575
const available = questCatalog.filter((q) => !taken.has(q.questId));576
addBtn.disabled = available.length === 0;577
if (!draftInitialQuests.length)578
{579
const empty = document.createElement("p");580
empty.className = "hint";581
empty.textContent = "No initial quests.";582
listRoot.append(empty);583
}584
draftInitialQuests.forEach((questId, index) =>585
{586
const row = document.createElement("div");587
row.className = "initial-quest-row";588
const select = document.createElement("select");589
const catalog = questCatalog.length590
? questCatalog591
: [{ questId, title: questId }];592
for (const quest of catalog)593
{594
if (taken.has(quest.questId) && quest.questId !== questId)595
{ continue; }596
const opt = document.createElement("option");597
opt.value = quest.questId;598
opt.textContent = quest.title599
? `${quest.title} (${quest.questId})`600
: quest.questId;601
select.append(opt);602
}603
if (![...select.options].some((o) => o.value === questId))604
{605
const missing = document.createElement("option");606
missing.value = questId;607
missing.textContent = `${questId} (missing)`;608
select.append(missing);609
}610
select.value = questId;611
select.addEventListener("change", () =>612
{613
const next = draftInitialQuests.slice();614
next[index] = select.value;615
draftInitialQuests = normalizeInitialQuests(next);616
renderInitialQuestsPanel();617
form.dispatchEvent(new CustomEvent("initial-quests-changed"));618
});619
const remove = document.createElement("button");620
remove.type = "button";621
remove.textContent = "Remove";622
remove.addEventListener("click", () =>623
{624
draftInitialQuests = draftInitialQuests.filter((_, i) => i !== index);625
renderInitialQuestsPanel();626
form.dispatchEvent(new CustomEvent("initial-quests-changed"));627
});628
row.append(select, remove);629
listRoot.append(row);630
});631
refreshDirty();632
}633
532
function setRowIcon (img, itemId)634
function setRowIcon (img, itemId)533
{635
{534
if (!img)636
if (!img)@@ -734,21 +836,34 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi734
renderGameAdminsPanel();836
renderGameAdminsPanel();735
return;837
return;736
}838
}839
if (message.type === MessageType.editorQuests)840
{841
questCatalog = (message.quests ?? []).map((q) =>842
{843
const def = normalizeQuestDef(q);844
return { questId: def.questId, title: def.title };845
});846
renderInitialQuestsPanel();847
return;848
}737
loaded = true;849
loaded = true;738
baseline = {850
baseline = {739
...message.settings,851
...message.settings,740
itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues),852
itemSeedValues: normalizeItemSeedValues(message.settings?.itemSeedValues),741
equipmentStatBonuses: normalizeEquipmentStatBonuses(message.settings?.equipmentStatBonuses)853
equipmentStatBonuses: normalizeEquipmentStatBonuses(message.settings?.equipmentStatBonuses),854
initialQuests: normalizeInitialQuests(message.settings?.initialQuests)742
};855
};743
itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"856
itemLastSales = message.itemLastSales && typeof message.itemLastSales === "object"744
? message.itemLastSales857
? message.itemLastSales745
: {};858
: {};746
draftSeeds = { ...baseline.itemSeedValues };859
draftSeeds = { ...baseline.itemSeedValues };747
draftStarter = normalizeStarterLoadout(baseline);860
draftStarter = normalizeStarterLoadout(baseline);861
draftInitialQuests = normalizeInitialQuests(baseline.initialQuests);748
draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);862
draftEquipmentStats = normalizeEquipmentStatBonuses(baseline.equipmentStatBonuses);749
fillForm(form, baseline);863
fillForm(form, baseline);750
renderSeedPanel();864
renderSeedPanel();751
renderStarterPanel();865
renderStarterPanel();866
renderInitialQuestsPanel();752
renderEquipmentStatsPanel();867
renderEquipmentStatsPanel();753
refreshDirty();868
refreshDirty();754
renderLog(log, message.changelog ?? []);869
renderLog(log, message.changelog ?? []);@@ -763,6 +878,7 @@ function buildForm (form, {763
onFieldInput,878
onFieldInput,764
onSeedPanelReady,879
onSeedPanelReady,765
onStarterPanelReady,880
onStarterPanelReady,881
onInitialQuestsPanelReady,766
onEquipmentStatsPanelReady,882
onEquipmentStatsPanelReady,767
onGameAdminsPanelReady883
onGameAdminsPanelReady768
})884
})@@ -810,6 +926,15 @@ function buildForm (form, {810
section.append(panel.root);926
section.append(panel.root);811
onStarterPanelReady?.(panel);927
onStarterPanelReady?.(panel);812
}928
}929
else if (category.panel === "initialQuests")930
{931
const panel = buildInitialQuestsPanel({932
onAdd ()933
{ form.dispatchEvent(new CustomEvent("initial-quests-add")); }934
});935
section.append(panel.root);936
onInitialQuestsPanelReady?.(panel);937
}813
else if (category.panel === "equipmentStats")938
else if (category.panel === "equipmentStats")814
{939
{815
const panel = buildEquipmentStatsPanel({940
const panel = buildEquipmentStatsPanel({@@ -1016,6 +1141,23 @@ function buildStarterEquipmentPanel ({ onAddInventory })1016
return { root, equipRoot, invRoot };1141
return { root, equipRoot, invRoot };1017
}1142
}1018
1143
1144
function buildInitialQuestsPanel ({ onAdd })1145
{1146
const root = document.createElement("div");1147
root.className = "initial-quests-panel";1148
const hint = document.createElement("p");1149
hint.className = "hint";1150
hint.textContent = "These quests are granted to new characters. Existing characters also receive them on save or login unless the quest is already started or completed.";1151
const listRoot = document.createElement("div");1152
listRoot.className = "initial-quests-list";1153
const addBtn = document.createElement("button");1154
addBtn.type = "button";1155
addBtn.textContent = "Add quest";1156
addBtn.addEventListener("click", () => onAdd?.());1157
root.append(hint, listRoot, addBtn);1158
return { root, listRoot, addBtn };1159
}1160
1019
function listAllItems ()1161
function listAllItems ()1020
{1162
{1021
return Object.values(ITEM_DEFINITIONS)1163
return Object.values(ITEM_DEFINITIONS)@@ -10,6 +10,7 @@ import
10
10
EQUIPMENT_SLOT,
11
11
LETTER_MAX_BODY_CHARS
12
12
} from "/shared/definitions/items.js";
13
import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
13
14
import { stackQuantity } from "/shared/items/inventory.js";
14
15
import { formatLetterSignature } from "/shared/courier/systemLetters.js";
15
16
import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
@@ -52,6 +53,7 @@ export function initInventory ({
52
53
const bagPanel = document.getElementById("bag-panel");
53
54
const bagGrid = document.getElementById("bag-grid");
54
55
const equipGrid = document.getElementById("equip-grid");
56
const ammoHud = document.getElementById("equipped-ammo-hud");
55
57
const bagMaxHitEl = document.getElementById("bag-max-hit");
56
58
const hint = document.getElementById("bag-hint");
57
59
const bankPanel = document.getElementById("bank-panel");
@@ -219,6 +221,31 @@ export function initInventory ({
219
221
bagMaxHitEl.hidden = false;
220
222
}
221
223
224
function refreshEquippedAmmoHud ()
225
{
226
if (!ammoHud)
227
{ return; }
228
const worn = bag.equipment?.slots?.[EQUIPMENT_SLOT.offhand] ?? null;
229
const def = worn ? itemDefinition(worn.itemId) : null;
230
if (!worn || def?.equipment?.kind !== EquipmentKind.arrowAmmo)
231
{
232
ammoHud.hidden = true;
233
ammoHud.replaceChildren();
234
return;
235
}
236
ammoHud.hidden = false;
237
ammoHud.replaceChildren();
238
const img = document.createElement("img");
239
applyItemIcon(img, worn, itemAssetPathForStack(worn));
240
img.alt = itemDisplayName(worn);
241
ammoHud.append(img);
242
const count = document.createElement("span");
243
count.className = "qty";
244
count.textContent = formatQuantity(stackQuantity(worn.quantity));
245
ammoHud.append(count);
246
ammoHud.title = `${itemDisplayName(worn)} ×${formatQuantity(stackQuantity(worn.quantity))}`;
247
}
248
222
249
function render ()
223
250
{
224
251
bagGrid.innerHTML = "";
@@ -351,6 +378,13 @@ export function initInventory ({
351
378
applyItemIcon(img, worn, itemAssetPathForStack(worn));
352
379
img.alt = itemDisplayName(worn);
353
380
button.append(img);
381
if (worn.quantity > 1)
382
{
383
const count = document.createElement("span");
384
count.className = "qty";
385
count.textContent = formatQuantity(worn.quantity);
386
button.append(count);
387
}
354
388
}
355
389
button.addEventListener("click", () =>
356
390
{
@@ -359,6 +393,7 @@ export function initInventory ({
359
393
});
360
394
equipGrid.append(button);
361
395
}
396
refreshEquippedAmmoHud();
362
397
refreshMaxHit();
363
398
}
364
399
@@ -10,6 +10,7 @@ import10
EQUIPMENT_SLOT,10
EQUIPMENT_SLOT,11
LETTER_MAX_BODY_CHARS11
LETTER_MAX_BODY_CHARS12
} from "/shared/definitions/items.js";12
} from "/shared/definitions/items.js";13
import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";13
import { stackQuantity } from "/shared/items/inventory.js";14
import { stackQuantity } from "/shared/items/inventory.js";14
import { formatLetterSignature } from "/shared/courier/systemLetters.js";15
import { formatLetterSignature } from "/shared/courier/systemLetters.js";15
import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";16
import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";@@ -52,6 +53,7 @@ export function initInventory ({52
const bagPanel = document.getElementById("bag-panel");53
const bagPanel = document.getElementById("bag-panel");53
const bagGrid = document.getElementById("bag-grid");54
const bagGrid = document.getElementById("bag-grid");54
const equipGrid = document.getElementById("equip-grid");55
const equipGrid = document.getElementById("equip-grid");56
const ammoHud = document.getElementById("equipped-ammo-hud");55
const bagMaxHitEl = document.getElementById("bag-max-hit");57
const bagMaxHitEl = document.getElementById("bag-max-hit");56
const hint = document.getElementById("bag-hint");58
const hint = document.getElementById("bag-hint");57
const bankPanel = document.getElementById("bank-panel");59
const bankPanel = document.getElementById("bank-panel");@@ -219,6 +221,31 @@ export function initInventory ({219
bagMaxHitEl.hidden = false;221
bagMaxHitEl.hidden = false;220
}222
}221
223
224
function refreshEquippedAmmoHud ()225
{226
if (!ammoHud)227
{ return; }228
const worn = bag.equipment?.slots?.[EQUIPMENT_SLOT.offhand] ?? null;229
const def = worn ? itemDefinition(worn.itemId) : null;230
if (!worn || def?.equipment?.kind !== EquipmentKind.arrowAmmo)231
{232
ammoHud.hidden = true;233
ammoHud.replaceChildren();234
return;235
}236
ammoHud.hidden = false;237
ammoHud.replaceChildren();238
const img = document.createElement("img");239
applyItemIcon(img, worn, itemAssetPathForStack(worn));240
img.alt = itemDisplayName(worn);241
ammoHud.append(img);242
const count = document.createElement("span");243
count.className = "qty";244
count.textContent = formatQuantity(stackQuantity(worn.quantity));245
ammoHud.append(count);246
ammoHud.title = `${itemDisplayName(worn)} ×${formatQuantity(stackQuantity(worn.quantity))}`;247
}248
222
function render ()249
function render ()223
{250
{224
bagGrid.innerHTML = "";251
bagGrid.innerHTML = "";@@ -351,6 +378,13 @@ export function initInventory ({351
applyItemIcon(img, worn, itemAssetPathForStack(worn));378
applyItemIcon(img, worn, itemAssetPathForStack(worn));352
img.alt = itemDisplayName(worn);379
img.alt = itemDisplayName(worn);353
button.append(img);380
button.append(img);381
if (worn.quantity > 1)382
{383
const count = document.createElement("span");384
count.className = "qty";385
count.textContent = formatQuantity(worn.quantity);386
button.append(count);387
}354
}388
}355
button.addEventListener("click", () =>389
button.addEventListener("click", () =>356
{390
{@@ -359,6 +393,7 @@ export function initInventory ({359
});393
});360
equipGrid.append(button);394
equipGrid.append(button);361
}395
}396
refreshEquippedAmmoHud();362
refreshMaxHit();397
refreshMaxHit();363
}398
}364
399
@@ -118,7 +118,6 @@ let leftClickConsumed = false;
118
118
/** Mob/NPC entity ids recently trading blows with the local player (LMB prefers Attack). */
119
119
const combatWithLocalIds = new Set();
120
120
121
const AUTORUN_DISTANCE_TILES = 3;
122
121
const AUTORUN_STAMINA_RESUME_RATIO = 0.5;
123
122
124
123
function noteCombatWithLocal (attackerId, targetId)
@@ -264,7 +263,7 @@ function syncAutorun ()
264
263
return;
265
264
}
266
265
const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY);
267
const wantRun = dist > AUTORUN_DISTANCE_TILES;
266
const wantRun = dist > 0;
268
267
const current = staminaUi?.getCurrent?.() ?? 0;
269
268
const max = Math.max(1, staminaUi?.getMax?.() ?? 1);
270
269
if (gait === GAIT.run && current <= 0)
@@ -370,7 +369,7 @@ function pointerOverSpellUi ()
370
369
const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
371
370
if (!el)
372
371
{ return false; }
373
return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
372
return !!el.closest("#spells-panel, #spell-favorites-bar, #equipped-ammo-hud, #spells-toggle");
374
373
}
375
374
376
375
function pointerOverToastUi ()
@@ -118,7 +118,6 @@ let leftClickConsumed = false;118
/** Mob/NPC entity ids recently trading blows with the local player (LMB prefers Attack). */118
/** Mob/NPC entity ids recently trading blows with the local player (LMB prefers Attack). */119
const combatWithLocalIds = new Set();119
const combatWithLocalIds = new Set();120
120
121
const AUTORUN_DISTANCE_TILES = 3;122
const AUTORUN_STAMINA_RESUME_RATIO = 0.5;121
const AUTORUN_STAMINA_RESUME_RATIO = 0.5;123
122
124
function noteCombatWithLocal (attackerId, targetId)123
function noteCombatWithLocal (attackerId, targetId)@@ -264,7 +263,7 @@ function syncAutorun ()264
return;263
return;265
}264
}266
const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY);265
const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY);267
const wantRun = dist > AUTORUN_DISTANCE_TILES;266
const wantRun = dist > 0;268
const current = staminaUi?.getCurrent?.() ?? 0;267
const current = staminaUi?.getCurrent?.() ?? 0;269
const max = Math.max(1, staminaUi?.getMax?.() ?? 1);268
const max = Math.max(1, staminaUi?.getMax?.() ?? 1);270
if (gait === GAIT.run && current <= 0)269
if (gait === GAIT.run && current <= 0)@@ -370,7 +369,7 @@ function pointerOverSpellUi ()370
const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);369
const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);371
if (!el)370
if (!el)372
{ return false; }371
{ return false; }373
return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");372
return !!el.closest("#spells-panel, #spell-favorites-bar, #equipped-ammo-hud, #spells-toggle");374
}373
}375
374
376
function pointerOverToastUi ()375
function pointerOverToastUi ()@@ -728,6 +728,24 @@ label {
728
728
align-items: center;
729
729
}
730
730
731
.initial-quests-panel .hint {
732
margin: 0 0 0.6rem;
733
}
734
735
.initial-quests-list {
736
display: flex;
737
flex-direction: column;
738
gap: 0.4rem;
739
margin-bottom: 0.6rem;
740
}
741
742
.initial-quest-row {
743
display: grid;
744
grid-template-columns: 1fr auto;
745
gap: 0.4rem;
746
align-items: center;
747
}
748
731
749
.equip-stats-panel {
732
750
display: flex;
733
751
flex-direction: column;
@@ -1548,6 +1566,119 @@ label {
1548
1566
font-size: 0.85rem;
1549
1567
margin: 0.25rem 0 0.5rem;
1550
1568
}
1569
1570
#dialogue-simulate-backdrop {
1571
position: fixed;
1572
inset: 0;
1573
z-index: 80;
1574
background: rgba(0, 0, 0, 0.45);
1575
}
1576
1577
#dialogue-simulate-panel {
1578
position: fixed;
1579
z-index: 81;
1580
left: 50%;
1581
top: 50%;
1582
transform: translate(-50%, -50%);
1583
width: min(420px, calc(100vw - 2rem));
1584
max-height: min(70vh, 560px);
1585
display: flex;
1586
flex-direction: column;
1587
gap: 0.65rem;
1588
padding: 0.85rem 1rem 1rem;
1589
border-radius: 10px;
1590
background: #161a22;
1591
border: 1px solid #3a4250;
1592
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
1593
color: #e8ecf4;
1594
}
1595
1596
#dialogue-simulate-panel[hidden],
1597
#dialogue-simulate-backdrop[hidden] {
1598
display: none;
1599
}
1600
1601
#dialogue-simulate-panel > header {
1602
display: flex;
1603
align-items: center;
1604
justify-content: space-between;
1605
gap: 0.5rem;
1606
}
1607
1608
#dialogue-simulate-lines {
1609
min-height: 4rem;
1610
display: flex;
1611
flex-direction: column;
1612
gap: 0.5rem;
1613
overflow: auto;
1614
}
1615
1616
.dialogue-simulate-line {
1617
display: flex;
1618
gap: 0.55rem;
1619
align-items: flex-start;
1620
}
1621
1622
.dialogue-simulate-icon {
1623
flex: 0 0 auto;
1624
border-radius: 6px;
1625
image-rendering: pixelated;
1626
}
1627
1628
.dialogue-simulate-player {
1629
flex-direction: row-reverse;
1630
}
1631
1632
#dialogue-simulate-actions {
1633
display: flex;
1634
flex-wrap: wrap;
1635
gap: 0.4rem;
1636
}
1637
1638
.quest-condition-item-picker {
1639
display: flex;
1640
flex-direction: column;
1641
gap: 0.25rem;
1642
min-width: 12rem;
1643
}
1644
1645
.quest-condition-pair {
1646
display: flex;
1647
flex-wrap: wrap;
1648
gap: 0.35rem;
1649
align-items: center;
1650
}
1651
1652
.quest-condition-pair select {
1653
min-width: 10rem;
1654
max-width: 18rem;
1655
}
1656
1657
.quest-condition-attile {
1658
display: flex;
1659
flex-direction: column;
1660
gap: 0.35rem;
1661
min-width: 14rem;
1662
}
1663
1664
.quest-condition-tile-info {
1665
margin: 0;
1666
padding: 0.35rem 0.45rem;
1667
max-width: 28rem;
1668
white-space: pre-wrap;
1669
font-size: 0.8rem;
1670
line-height: 1.35;
1671
color: #c5d4e8;
1672
background: #12151c;
1673
border: 1px solid #3a4250;
1674
border-radius: 4px;
1675
}
1676
1677
.quest-condition-dim {
1678
min-width: 14rem;
1679
max-width: 22rem;
1680
}
1681
1551
1682
.dialogue-reward-item-search {
1552
1683
display: flex;
1553
1684
flex-direction: column;
@@ -728,6 +728,24 @@ label {728
align-items: center;728
align-items: center;729
}729
}730
730
731
.initial-quests-panel .hint {732
margin: 0 0 0.6rem;733
}734
735
.initial-quests-list {736
display: flex;737
flex-direction: column;738
gap: 0.4rem;739
margin-bottom: 0.6rem;740
}741
742
.initial-quest-row {743
display: grid;744
grid-template-columns: 1fr auto;745
gap: 0.4rem;746
align-items: center;747
}748
731
.equip-stats-panel {749
.equip-stats-panel {732
display: flex;750
display: flex;733
flex-direction: column;751
flex-direction: column;@@ -1548,6 +1566,119 @@ label {1548
font-size: 0.85rem;1566
font-size: 0.85rem;1549
margin: 0.25rem 0 0.5rem;1567
margin: 0.25rem 0 0.5rem;1550
}1568
}1569
1570
#dialogue-simulate-backdrop {1571
position: fixed;1572
inset: 0;1573
z-index: 80;1574
background: rgba(0, 0, 0, 0.45);1575
}1576
1577
#dialogue-simulate-panel {1578
position: fixed;1579
z-index: 81;1580
left: 50%;1581
top: 50%;1582
transform: translate(-50%, -50%);1583
width: min(420px, calc(100vw - 2rem));1584
max-height: min(70vh, 560px);1585
display: flex;1586
flex-direction: column;1587
gap: 0.65rem;1588
padding: 0.85rem 1rem 1rem;1589
border-radius: 10px;1590
background: #161a22;1591
border: 1px solid #3a4250;1592
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);1593
color: #e8ecf4;1594
}1595
1596
#dialogue-simulate-panel[hidden],1597
#dialogue-simulate-backdrop[hidden] {1598
display: none;1599
}1600
1601
#dialogue-simulate-panel > header {1602
display: flex;1603
align-items: center;1604
justify-content: space-between;1605
gap: 0.5rem;1606
}1607
1608
#dialogue-simulate-lines {1609
min-height: 4rem;1610
display: flex;1611
flex-direction: column;1612
gap: 0.5rem;1613
overflow: auto;1614
}1615
1616
.dialogue-simulate-line {1617
display: flex;1618
gap: 0.55rem;1619
align-items: flex-start;1620
}1621
1622
.dialogue-simulate-icon {1623
flex: 0 0 auto;1624
border-radius: 6px;1625
image-rendering: pixelated;1626
}1627
1628
.dialogue-simulate-player {1629
flex-direction: row-reverse;1630
}1631
1632
#dialogue-simulate-actions {1633
display: flex;1634
flex-wrap: wrap;1635
gap: 0.4rem;1636
}1637
1638
.quest-condition-item-picker {1639
display: flex;1640
flex-direction: column;1641
gap: 0.25rem;1642
min-width: 12rem;1643
}1644
1645
.quest-condition-pair {1646
display: flex;1647
flex-wrap: wrap;1648
gap: 0.35rem;1649
align-items: center;1650
}1651
1652
.quest-condition-pair select {1653
min-width: 10rem;1654
max-width: 18rem;1655
}1656
1657
.quest-condition-attile {1658
display: flex;1659
flex-direction: column;1660
gap: 0.35rem;1661
min-width: 14rem;1662
}1663
1664
.quest-condition-tile-info {1665
margin: 0;1666
padding: 0.35rem 0.45rem;1667
max-width: 28rem;1668
white-space: pre-wrap;1669
font-size: 0.8rem;1670
line-height: 1.35;1671
color: #c5d4e8;1672
background: #12151c;1673
border: 1px solid #3a4250;1674
border-radius: 4px;1675
}1676
1677
.quest-condition-dim {1678
min-width: 14rem;1679
max-width: 22rem;1680
}1681
1551
.dialogue-reward-item-search {1682
.dialogue-reward-item-search {1552
display: flex;1683
display: flex;1553
flex-direction: column;1684
flex-direction: column;@@ -1090,11 +1090,52 @@ button.friend-account-name:hover {
1090
1090
cursor: not-allowed;
1091
1091
}
1092
1092
1093
#spell-favorites-bar {
1093
#bottom-left-hud {
1094
1094
position: fixed;
1095
1095
z-index: 5;
1096
1096
left: 0.75rem;
1097
1097
bottom: 0.65rem;
1098
display: flex;
1099
flex-direction: column;
1100
align-items: flex-start;
1101
gap: 0.35rem;
1102
pointer-events: none;
1103
}
1104
1105
#bottom-left-hud > * {
1106
pointer-events: auto;
1107
}
1108
1109
#equipped-ammo-hud {
1110
display: flex;
1111
align-items: center;
1112
gap: 0.4rem;
1113
padding: 0.3rem 0.45rem 0.3rem 0.3rem;
1114
border-radius: 10px;
1115
background: rgba(18, 21, 27, 0.94);
1116
border: 1px solid #2c3340;
1117
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);
1118
color: #e8ecf4;
1119
font-size: 0.95rem;
1120
font-variant-numeric: tabular-nums;
1121
}
1122
1123
#equipped-ammo-hud[hidden] {
1124
display: none;
1125
}
1126
1127
#equipped-ammo-hud img {
1128
width: 36px;
1129
height: 36px;
1130
object-fit: contain;
1131
image-rendering: pixelated;
1132
}
1133
1134
#equipped-ammo-hud .qty {
1135
min-width: 1.25ch;
1136
}
1137
1138
#spell-favorites-bar {
1098
1139
display: flex;
1099
1140
gap: 0.35rem;
1100
1141
padding: 0.35rem;
@@ -1090,11 +1090,52 @@ button.friend-account-name:hover {1090
cursor: not-allowed;1090
cursor: not-allowed;1091
}1091
}1092
1092
1093
#spell-favorites-bar {1093
#bottom-left-hud {1094
position: fixed;1094
position: fixed;1095
z-index: 5;1095
z-index: 5;1096
left: 0.75rem;1096
left: 0.75rem;1097
bottom: 0.65rem;1097
bottom: 0.65rem;1098
display: flex;1099
flex-direction: column;1100
align-items: flex-start;1101
gap: 0.35rem;1102
pointer-events: none;1103
}1104
1105
#bottom-left-hud > * {1106
pointer-events: auto;1107
}1108
1109
#equipped-ammo-hud {1110
display: flex;1111
align-items: center;1112
gap: 0.4rem;1113
padding: 0.3rem 0.45rem 0.3rem 0.3rem;1114
border-radius: 10px;1115
background: rgba(18, 21, 27, 0.94);1116
border: 1px solid #2c3340;1117
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);1118
color: #e8ecf4;1119
font-size: 0.95rem;1120
font-variant-numeric: tabular-nums;1121
}1122
1123
#equipped-ammo-hud[hidden] {1124
display: none;1125
}1126
1127
#equipped-ammo-hud img {1128
width: 36px;1129
height: 36px;1130
object-fit: contain;1131
image-rendering: pixelated;1132
}1133
1134
#equipped-ammo-hud .qty {1135
min-width: 1.25ch;1136
}1137
1138
#spell-favorites-bar {1098
display: flex;1139
display: flex;1099
gap: 0.35rem;1140
gap: 0.35rem;1100
padding: 0.35rem;1141
padding: 0.35rem;@@ -65,6 +65,7 @@ import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlay
65
65
import { chunkBoundsAround, findPath } from "../navigation/astar.js";
66
66
import { tileToChunk } from "../world/coordinates.js";
67
67
import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";
68
import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
68
69
import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
69
70
import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";
70
71
import { placeOrMergeGroundStack, bagView } from "../items/bags.js";
@@ -1320,6 +1321,20 @@ function shouldSeekCoverApproach (world, handle)
1320
1321
return !mobHasRangedRetaliation(world, handle);
1321
1322
}
1322
1323
1324
/** Double cost for stepping back onto the tile just left while chasing. */
1325
function combatApproachStepCost (position, baseCost = null)
1326
{
1327
const prevX = position?.prevTileX;
1328
const prevY = position?.prevTileY;
1329
return (x, y) => withCombatBackstepCost(
1330
baseCost ? baseCost(x, y) : 1,
1331
x,
1332
y,
1333
prevX,
1334
prevY
1335
);
1336
}
1337
1323
1338
function coverStepCost (world, threatPos, goalX, goalY, x, y)
1324
1339
{
1325
1340
// Final adjacent step is always in LOS — don't punish the last lunge.
@@ -1401,7 +1416,10 @@ function findCoverMeleeApproachPath (world, entityId, handle, position, targetPo
1401
1416
bounds.maxY,
1402
1417
{
1403
1418
preferVertical,
1404
stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1419
stepCost: combatApproachStepCost(
1420
position,
1421
(x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)
1422
)
1405
1423
}
1406
1424
);
1407
1425
if (!tiles.length)
@@ -1604,7 +1622,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos
1604
1622
bounds.minY,
1605
1623
bounds.maxX,
1606
1624
bounds.maxY,
1607
{ preferVertical }
1625
{ preferVertical, stepCost: combatApproachStepCost(position) }
1608
1626
);
1609
1627
if (!tiles.length)
1610
1628
{
@@ -1677,7 +1695,8 @@ export function queueStandInRangeApproach (
1677
1695
bounds.minX,
1678
1696
bounds.minY,
1679
1697
bounds.maxX,
1680
bounds.maxY
1698
bounds.maxY,
1699
{ stepCost: combatApproachStepCost(position) }
1681
1700
);
1682
1701
if (!tiles.length)
1683
1702
{
@@ -1738,6 +1757,15 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D
1738
1757
})();
1739
1758
if (!isCreature && !consumeArrow(world.ecs, attackerHandle))
1740
1759
{ return events; }
1760
const character = world.ecs.get(attackerHandle, Component.character);
1761
if (character?.characterId != null)
1762
{
1763
events.push({
1764
type: "inventory",
1765
characterId: character.characterId,
1766
...bagView(world.ecs, attackerHandle)
1767
});
1768
}
1741
1769
1742
1770
const shotProfile = tipElement
1743
1771
? { ...profile, attackType: tipElement }
@@ -65,6 +65,7 @@ import { awardCombatHitXp, awardCombatAvoidanceXp, awardDamageHealthXp, syncPlay65
import { chunkBoundsAround, findPath } from "../navigation/astar.js";65
import { chunkBoundsAround, findPath } from "../navigation/astar.js";66
import { tileToChunk } from "../world/coordinates.js";66
import { tileToChunk } from "../world/coordinates.js";67
import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";67
import { findPathToNearestGoal } from "../../../shared/navigation/bfs.js";68
import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";68
import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";69
import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";69
import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";70
import { stackQuantity, insertStack } from "../../../shared/items/inventory.js";70
import { placeOrMergeGroundStack, bagView } from "../items/bags.js";71
import { placeOrMergeGroundStack, bagView } from "../items/bags.js";@@ -1320,6 +1321,20 @@ function shouldSeekCoverApproach (world, handle)1320
return !mobHasRangedRetaliation(world, handle);1321
return !mobHasRangedRetaliation(world, handle);1321
}1322
}1322
1323
1324
/** Double cost for stepping back onto the tile just left while chasing. */1325
function combatApproachStepCost (position, baseCost = null)1326
{1327
const prevX = position?.prevTileX;1328
const prevY = position?.prevTileY;1329
return (x, y) => withCombatBackstepCost(1330
baseCost ? baseCost(x, y) : 1,1331
x,1332
y,1333
prevX,1334
prevY1335
);1336
}1337
1323
function coverStepCost (world, threatPos, goalX, goalY, x, y)1338
function coverStepCost (world, threatPos, goalX, goalY, x, y)1324
{1339
{1325
// Final adjacent step is always in LOS — don't punish the last lunge.1340
// Final adjacent step is always in LOS — don't punish the last lunge.@@ -1401,7 +1416,10 @@ function findCoverMeleeApproachPath (world, entityId, handle, position, targetPo1401
bounds.maxY,1416
bounds.maxY,1402
{1417
{1403
preferVertical,1418
preferVertical,1404
stepCost: (x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)1419
stepCost: combatApproachStepCost(1420
position,1421
(x, y) => coverStepCost(world, targetPos, goal.x, goal.y, x, y)1422
)1405
}1423
}1406
);1424
);1407
if (!tiles.length)1425
if (!tiles.length)@@ -1604,7 +1622,7 @@ export function queueMeleeApproach (world, entityId, handle, position, targetPos1604
bounds.minY,1622
bounds.minY,1605
bounds.maxX,1623
bounds.maxX,1606
bounds.maxY,1624
bounds.maxY,1607
{ preferVertical }1625
{ preferVertical, stepCost: combatApproachStepCost(position) }1608
);1626
);1609
if (!tiles.length)1627
if (!tiles.length)1610
{1628
{@@ -1677,7 +1695,8 @@ export function queueStandInRangeApproach (1677
bounds.minX,1695
bounds.minX,1678
bounds.minY,1696
bounds.minY,1679
bounds.maxX,1697
bounds.maxX,1680
bounds.maxY1698
bounds.maxY,1699
{ stepCost: combatApproachStepCost(position) }1681
);1700
);1682
if (!tiles.length)1701
if (!tiles.length)1683
{1702
{@@ -1738,6 +1757,15 @@ export function resolveRangedShot (world, attackerId, targetId, profile, now = D1738
})();1757
})();1739
if (!isCreature && !consumeArrow(world.ecs, attackerHandle))1758
if (!isCreature && !consumeArrow(world.ecs, attackerHandle))1740
{ return events; }1759
{ return events; }1760
const character = world.ecs.get(attackerHandle, Component.character);1761
if (character?.characterId != null)1762
{1763
events.push({1764
type: "inventory",1765
characterId: character.characterId,1766
...bagView(world.ecs, attackerHandle)1767
});1768
}1741
1769
1742
const shotProfile = tipElement1770
const shotProfile = tipElement1743
? { ...profile, attackType: tipElement }1771
? { ...profile, attackType: tipElement }@@ -13,6 +13,11 @@ import {
13
13
starterLoadoutsEqual,
14
14
diffStarterLoadout
15
15
} from "../../../shared/items/starterLoadout.js";
16
import {
17
normalizeInitialQuests,
18
initialQuestsEqual,
19
diffInitialQuests
20
} from "../../../shared/quests/initialQuests.js";
16
21
import {
17
22
normalizeEquipmentStatBonuses,
18
23
diffEquipmentStatBonuses,
@@ -289,6 +294,10 @@ export class EditorService
289
294
{
290
295
next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);
291
296
}
297
if (Object.prototype.hasOwnProperty.call(partial, "initialQuests"))
298
{ next.initialQuests = normalizeInitialQuests(partial.initialQuests); }
299
else
300
{ next.initialQuests = normalizeInitialQuests(current.initialQuests); }
292
301
const { bullets: scalarBullets, changed } = diffSettings(current, next);
293
302
const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")
294
303
? diffItemSeedValues(
@@ -324,7 +333,20 @@ export class EditorService
324
333
(itemId) => itemDefinition(itemId)?.displayName ?? null
325
334
)
326
335
: [];
327
const bullets = [...scalarBullets, ...seedBullets, ...starterBullets, ...equipmentStatBullets];
336
const initialQuestsChanged = Object.prototype.hasOwnProperty.call(partial, "initialQuests")
337
&& !initialQuestsEqual(current.initialQuests, next.initialQuests);
338
if (initialQuestsChanged)
339
{ changed.initialQuests = next.initialQuests; }
340
const initialQuestBullets = initialQuestsChanged
341
? diffInitialQuests(current.initialQuests, next.initialQuests)
342
: [];
343
const bullets = [
344
...scalarBullets,
345
...seedBullets,
346
...starterBullets,
347
...equipmentStatBullets,
348
...initialQuestBullets
349
];
328
350
if (Object.keys(changed).length === 0)
329
351
{
330
352
return {
@@ -344,7 +366,9 @@ export class EditorService
344
366
starterInventory: changed.starterInventory ?? current.starterInventory
345
367
?? DEFAULT_WORLD_SETTINGS.starterInventory,
346
368
equipmentStatBonuses: changed.equipmentStatBonuses
347
?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses)
369
?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses),
370
initialQuests: changed.initialQuests
371
?? normalizeInitialQuests(current.initialQuests)
348
372
};
349
373
const normalized = normalizeStarterLoadout(settings);
350
374
settings.starterEquipment = normalized.equipment;
@@ -13,6 +13,11 @@ import {13
starterLoadoutsEqual,13
starterLoadoutsEqual,14
diffStarterLoadout14
diffStarterLoadout15
} from "../../../shared/items/starterLoadout.js";15
} from "../../../shared/items/starterLoadout.js";16
import {17
normalizeInitialQuests,18
initialQuestsEqual,19
diffInitialQuests20
} from "../../../shared/quests/initialQuests.js";16
import {21
import {17
normalizeEquipmentStatBonuses,22
normalizeEquipmentStatBonuses,18
diffEquipmentStatBonuses,23
diffEquipmentStatBonuses,@@ -289,6 +294,10 @@ export class EditorService289
{294
{290
next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);295
next.equipmentStatBonuses = normalizeEquipmentStatBonuses(current.equipmentStatBonuses);291
}296
}297
if (Object.prototype.hasOwnProperty.call(partial, "initialQuests"))298
{ next.initialQuests = normalizeInitialQuests(partial.initialQuests); }299
else300
{ next.initialQuests = normalizeInitialQuests(current.initialQuests); }292
const { bullets: scalarBullets, changed } = diffSettings(current, next);301
const { bullets: scalarBullets, changed } = diffSettings(current, next);293
const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")302
const seedBullets = Object.prototype.hasOwnProperty.call(partial, "itemSeedValues")294
? diffItemSeedValues(303
? diffItemSeedValues(@@ -324,7 +333,20 @@ export class EditorService324
(itemId) => itemDefinition(itemId)?.displayName ?? null333
(itemId) => itemDefinition(itemId)?.displayName ?? null325
)334
)326
: [];335
: [];327
const bullets = [...scalarBullets, ...seedBullets, ...starterBullets, ...equipmentStatBullets];336
const initialQuestsChanged = Object.prototype.hasOwnProperty.call(partial, "initialQuests")337
&& !initialQuestsEqual(current.initialQuests, next.initialQuests);338
if (initialQuestsChanged)339
{ changed.initialQuests = next.initialQuests; }340
const initialQuestBullets = initialQuestsChanged341
? diffInitialQuests(current.initialQuests, next.initialQuests)342
: [];343
const bullets = [344
...scalarBullets,345
...seedBullets,346
...starterBullets,347
...equipmentStatBullets,348
...initialQuestBullets349
];328
if (Object.keys(changed).length === 0)350
if (Object.keys(changed).length === 0)329
{351
{330
return {352
return {@@ -344,7 +366,9 @@ export class EditorService344
starterInventory: changed.starterInventory ?? current.starterInventory366
starterInventory: changed.starterInventory ?? current.starterInventory345
?? DEFAULT_WORLD_SETTINGS.starterInventory,367
?? DEFAULT_WORLD_SETTINGS.starterInventory,346
equipmentStatBonuses: changed.equipmentStatBonuses368
equipmentStatBonuses: changed.equipmentStatBonuses347
?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses)369
?? normalizeEquipmentStatBonuses(current.equipmentStatBonuses),370
initialQuests: changed.initialQuests371
?? normalizeInitialQuests(current.initialQuests)348
};372
};349
const normalized = normalizeStarterLoadout(settings);373
const normalized = normalizeStarterLoadout(settings);350
settings.starterEquipment = normalized.equipment;374
settings.starterEquipment = normalized.equipment;@@ -1048,7 +1048,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1048
1048
requireAdmin(session);
1049
1049
{
1050
1050
const saved = editor.saveSettings(message.settings ?? {}, session.authSubject);
1051
simulation.applySettings(saved.settings);
1051
simulation.applySettings(saved.settings, {
1052
grantInitialQuests: Object.prototype.hasOwnProperty.call(saved.changed ?? {}, "initialQuests")
1053
});
1052
1054
broadcastStatus();
1053
1055
broadcastSettings(saved);
1054
1056
}
@@ -1048,7 +1048,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1048
requireAdmin(session);1048
requireAdmin(session);1049
{1049
{1050
const saved = editor.saveSettings(message.settings ?? {}, session.authSubject);1050
const saved = editor.saveSettings(message.settings ?? {}, session.authSubject);1051
simulation.applySettings(saved.settings);1051
simulation.applySettings(saved.settings, {1052
grantInitialQuests: Object.prototype.hasOwnProperty.call(saved.changed ?? {}, "initialQuests")1053
});1052
broadcastStatus();1054
broadcastStatus();1053
broadcastSettings(saved);1055
broadcastSettings(saved);1054
}1056
}@@ -553,6 +553,14 @@ export class StateDatabase
553
553
return this.db.prepare("SELECT * FROM characters WHERE character_id = ?").get(characterId) ?? null;
554
554
}
555
555
556
/** All character ids (for world-settings fan-out such as initial quests). */
557
listAllCharacterIds ()
558
{
559
return this.db.prepare("SELECT character_id FROM characters").all()
560
.map((row) => row.character_id | 0)
561
.filter((id) => id > 0);
562
}
563
556
564
findSurnameClaim (surnameNormalized)
557
565
{
558
566
return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;
@@ -553,6 +553,14 @@ export class StateDatabase553
return this.db.prepare("SELECT * FROM characters WHERE character_id = ?").get(characterId) ?? null;553
return this.db.prepare("SELECT * FROM characters WHERE character_id = ?").get(characterId) ?? null;554
}554
}555
555
556
/** All character ids (for world-settings fan-out such as initial quests). */557
listAllCharacterIds ()558
{559
return this.db.prepare("SELECT character_id FROM characters").all()560
.map((row) => row.character_id | 0)561
.filter((id) => id > 0);562
}563
556
findSurnameClaim (surnameNormalized)564
findSurnameClaim (surnameNormalized)557
{565
{558
return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;566
return this.db.prepare("SELECT * FROM surname_claims WHERE surname_normalized = ?").get(surnameNormalized) ?? null;@@ -1,6 +1,7 @@
1
1
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2
2
import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
3
3
import { normalizeEquipmentStatBonuses } from "../../../shared/definitions/equipmentStatCategories.js";
4
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
4
5
import {
5
6
OVERWORLD_ID,
6
7
DIMENSION_PURGE_MS,
@@ -267,6 +268,7 @@ export class WorldDatabase
267
268
merged.starterEquipment = loadout.equipment;
268
269
merged.starterInventory = loadout.inventory;
269
270
merged.equipmentStatBonuses = normalizeEquipmentStatBonuses(merged.equipmentStatBonuses);
271
merged.initialQuests = normalizeInitialQuests(merged.initialQuests);
270
272
return merged;
271
273
}
272
274
@@ -1,6 +1,7 @@1
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";1
import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";2
import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";2
import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";3
import { normalizeEquipmentStatBonuses } from "../../../shared/definitions/equipmentStatCategories.js";3
import { normalizeEquipmentStatBonuses } from "../../../shared/definitions/equipmentStatCategories.js";4
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";4
import {5
import {5
OVERWORLD_ID,6
OVERWORLD_ID,6
DIMENSION_PURGE_MS,7
DIMENSION_PURGE_MS,@@ -267,6 +268,7 @@ export class WorldDatabase267
merged.starterEquipment = loadout.equipment;268
merged.starterEquipment = loadout.equipment;268
merged.starterInventory = loadout.inventory;269
merged.starterInventory = loadout.inventory;269
merged.equipmentStatBonuses = normalizeEquipmentStatBonuses(merged.equipmentStatBonuses);270
merged.equipmentStatBonuses = normalizeEquipmentStatBonuses(merged.equipmentStatBonuses);271
merged.initialQuests = normalizeInitialQuests(merged.initialQuests);270
return merged;272
return merged;271
}273
}272
274
@@ -1,10 +1,11 @@
1
1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
2
3
import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3
4
import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
4
5
import { itemDefinition } from "../../../shared/definitions/items.js";
5
6
import { applySkillXp } from "../../../shared/skills/state.js";
6
7
import { skillLevel } from "../../../shared/definitions/skills.js";
7
import { formatDialogueRewardMessage } from "../../../shared/quests/dialogueRewards.js";
8
import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
8
9
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9
10
import { floorDiv } from "../world/coordinates.js";
10
11
import { WorkerMessage } from "../simulation/protocol.js";
@@ -306,11 +307,10 @@ export class QuestRuntime
306
307
if (session.phase === "lines")
307
308
{
308
309
const step = tree.steps.find((s) => s.stepId === session.stepId);
309
const rewardMessages = this.#grantStepItemRewards(
310
characterId,
311
step,
312
events
313
);
310
const rewardMessages = [
311
...this.#grantStepItemRewards(characterId, step, events),
312
...this.#grantStepQuestRewards(characterId, step, playerView, events)
313
];
314
314
this.#reevaluateQuests(characterId, playerView, events);
315
315
if (rewardMessages.length > 0)
316
316
{
@@ -447,6 +447,28 @@ export class QuestRuntime
447
447
return messages;
448
448
}
449
449
450
/** Start step.questRewards; returns player-facing notices for newly started quests. */
451
#grantStepQuestRewards (characterId, step, playerView, events)
452
{
453
const rewards = step?.questRewards ?? [];
454
if (!rewards.length)
455
{ return []; }
456
const titles = [];
457
for (const questId of rewards)
458
{
459
const current = this.stateDb.getQuestState(characterId, questId);
460
if (current.state !== "not-started")
461
{ continue; }
462
const def = this.content.quest(questId);
463
if (!def)
464
{ continue; }
465
this.startQuest(characterId, questId, playerView, events);
466
titles.push(def.title || def.questId);
467
}
468
const message = formatDialogueQuestRewardMessage(titles);
469
return message ? [message] : [];
470
}
471
450
472
#loadBag (characterId)
451
473
{
452
474
const onlineId = this.simulation.characterEntities.get(characterId | 0);
@@ -555,6 +577,26 @@ export class QuestRuntime
555
577
this.#reevaluateQuests(characterId, playerView, events);
556
578
}
557
579
580
/**
581
* Grant world-settings initial quests when the character has not started or completed them.
582
*/
583
ensureInitialQuests (characterId, playerView = null, events = [])
584
{
585
const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
586
for (const questId of list)
587
{ this.startQuest(characterId, questId, playerView, events); }
588
return events;
589
}
590
591
/** Apply initial quests to every character in state (settings save / apply). */
592
grantInitialQuestsToAllCharacters ()
593
{
594
const events = [];
595
for (const characterId of this.stateDb.listAllCharacterIds())
596
{ this.ensureInitialQuests(characterId, null, events); }
597
return events;
598
}
599
558
600
#reevaluateQuests (characterId, playerView, events)
559
601
{
560
602
const states = this.stateDb.listQuestStates(characterId)
@@ -1,10 +1,11 @@1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
1
import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2
import { normalizeInitialQuests } from "../../../shared/quests/initialQuests.js";
2
import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3
import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3
import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
4
import { attachOrigins, godsOrigin } from "../../../shared/items/origin.js";
4
import { itemDefinition } from "../../../shared/definitions/items.js";
5
import { itemDefinition } from "../../../shared/definitions/items.js";
5
import { applySkillXp } from "../../../shared/skills/state.js";
6
import { applySkillXp } from "../../../shared/skills/state.js";
6
import { skillLevel } from "../../../shared/definitions/skills.js";
7
import { skillLevel } from "../../../shared/definitions/skills.js";
7
import { formatDialogueRewardMessage } from "../../../shared/quests/dialogueRewards.js";
8
import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../../shared/quests/dialogueRewards.js";
8
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
9
import { floorDiv } from "../world/coordinates.js";
10
import { floorDiv } from "../world/coordinates.js";
10
import { WorkerMessage } from "../simulation/protocol.js";
11
import { WorkerMessage } from "../simulation/protocol.js";
@@ -306,11 +307,10 @@ export class QuestRuntime306
if (session.phase === "lines")
307
if (session.phase === "lines")
307
{
308
{
308
const step = tree.steps.find((s) => s.stepId === session.stepId);
309
const step = tree.steps.find((s) => s.stepId === session.stepId);
309
const rewardMessages = this.#grantStepItemRewards(
310
const rewardMessages = [
310
characterId,
311
...this.#grantStepItemRewards(characterId, step, events),
311
step,
312
...this.#grantStepQuestRewards(characterId, step, playerView, events)
312
events
313
];
313
);
314
this.#reevaluateQuests(characterId, playerView, events);
314
this.#reevaluateQuests(characterId, playerView, events);
315
if (rewardMessages.length > 0)
315
if (rewardMessages.length > 0)
316
{
316
{
@@ -447,6 +447,28 @@ export class QuestRuntime447
return messages;
447
return messages;
448
}
448
}
449
449
450
/** Start step.questRewards; returns player-facing notices for newly started quests. */
451
#grantStepQuestRewards (characterId, step, playerView, events)
452
{
453
const rewards = step?.questRewards ?? [];
454
if (!rewards.length)
455
{ return []; }
456
const titles = [];
457
for (const questId of rewards)
458
{
459
const current = this.stateDb.getQuestState(characterId, questId);
460
if (current.state !== "not-started")
461
{ continue; }
462
const def = this.content.quest(questId);
463
if (!def)
464
{ continue; }
465
this.startQuest(characterId, questId, playerView, events);
466
titles.push(def.title || def.questId);
467
}
468
const message = formatDialogueQuestRewardMessage(titles);
469
return message ? [message] : [];
470
}
471
450
#loadBag (characterId)
472
#loadBag (characterId)
451
{
473
{
452
const onlineId = this.simulation.characterEntities.get(characterId | 0);
474
const onlineId = this.simulation.characterEntities.get(characterId | 0);
@@ -555,6 +577,26 @@ export class QuestRuntime555
this.#reevaluateQuests(characterId, playerView, events);
577
this.#reevaluateQuests(characterId, playerView, events);
556
}
578
}
557
579
580
/**
581
* Grant world-settings initial quests when the character has not started or completed them.
582
*/
583
ensureInitialQuests (characterId, playerView = null, events = [])
584
{
585
const list = normalizeInitialQuests(this.simulation?.settings?.initialQuests);
586
for (const questId of list)
587
{ this.startQuest(characterId, questId, playerView, events); }
588
return events;
589
}
590
591
/** Apply initial quests to every character in state (settings save / apply). */
592
grantInitialQuestsToAllCharacters ()
593
{
594
const events = [];
595
for (const characterId of this.stateDb.listAllCharacterIds())
596
{ this.ensureInitialQuests(characterId, null, events); }
597
return events;
598
}
599
558
#reevaluateQuests (characterId, playerView, events)
600
#reevaluateQuests (characterId, playerView, events)
559
{
601
{
560
const states = this.stateDb.listQuestStates(characterId)
602
const states = this.stateDb.listQuestStates(characterId)
@@ -150,10 +150,12 @@ export class Simulation
150
150
return this.nowFn();
151
151
}
152
152
153
applySettings (settings)
153
applySettings (settings, { grantInitialQuests = false } = {})
154
154
{
155
155
this.settings = { ...this.settings, ...settings };
156
156
this.#configureWorkers();
157
if (grantInitialQuests)
158
{ this.quests?.grantInitialQuestsToAllCharacters?.(); }
157
159
}
158
160
159
161
/** Sparse last-sale map for editor base-price readouts. */
@@ -539,6 +541,7 @@ export class Simulation
539
541
this.#recalculateActivation(this.now);
540
542
this.#syncGhosts();
541
543
this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);
544
this.quests?.ensureInitialQuests?.(character.character_id ?? row.character_id);
542
545
return entityId;
543
546
}
544
547
@@ -150,10 +150,12 @@ export class Simulation150
return this.nowFn();150
return this.nowFn();151
}151
}152
152
153
applySettings (settings)153
applySettings (settings, { grantInitialQuests = false } = {})154
{154
{155
this.settings = { ...this.settings, ...settings };155
this.settings = { ...this.settings, ...settings };156
this.#configureWorkers();156
this.#configureWorkers();157
if (grantInitialQuests)158
{ this.quests?.grantInitialQuestsToAllCharacters?.(); }157
}159
}158
160
159
/** Sparse last-sale map for editor base-price readouts. */161
/** Sparse last-sale map for editor base-price readouts. */@@ -539,6 +541,7 @@ export class Simulation539
this.#recalculateActivation(this.now);541
this.#recalculateActivation(this.now);540
this.#syncGhosts();542
this.#syncGhosts();541
this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);543
this.courier?.onCharacterEnteredWorld(character.character_id, tileX, tileY);544
this.quests?.ensureInitialQuests?.(character.character_id ?? row.character_id);542
return entityId;545
return entityId;543
}546
}544
547
@@ -95,6 +95,7 @@ import {
95
95
PATH_GROUND_STEP_COST,
96
96
SOFT_OCCUPIED_DWELL_MS
97
97
} from "../../../shared/navigation/pathGround.js";
98
import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";
98
99
import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";
99
100
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";
100
101
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";
@@ -1600,6 +1601,8 @@ export class WorkerWorld
1600
1601
const flying = this.#isFlying(handle);
1601
1602
if (!flying)
1602
1603
{ this.#vacate(entityId, fromTileX, fromTileY); }
1604
position.prevTileX = fromTileX;
1605
position.prevTileY = fromTileY;
1603
1606
position.tileX = next.x;
1604
1607
position.tileY = next.y;
1605
1608
tiles.shift();
@@ -1672,7 +1675,8 @@ export class WorkerWorld
1672
1675
this.pathfindOptions({
1673
1676
preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),
1674
1677
preferPaths: !inCombat,
1675
entityId
1678
entityId,
1679
penalizeCombatBackstep: inCombat
1676
1680
})
1677
1681
);
1678
1682
path.stuckSince = now;
@@ -2260,20 +2264,36 @@ export class WorkerWorld
2260
2264
}
2261
2265
2262
2266
/**
2263
* @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options]
2267
* @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null, penalizeCombatBackstep?: boolean }} [options]
2264
2268
*/
2265
pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {})
2269
pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null, penalizeCombatBackstep = false } = {})
2266
2270
{
2267
2271
const options = { preferVertical: !!preferVertical };
2268
2272
const now = Date.now();
2269
2273
const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;
2270
options.stepCost = (x, y) => stepCostForGround(
2271
this.groundTypeAt(x, y, dimensionId),
2274
let prevTileX = null;
2275
let prevTileY = null;
2276
if (penalizeCombatBackstep && entityId != null)
2277
{
2278
const handle = this.ecs.handleOf(entityId);
2279
const position = handle != null ? this.ecs.get(handle, Component.position) : null;
2280
if (position?.prevTileX != null && position?.prevTileY != null)
2272
2281
{
2273
preferPaths: !!preferPaths,
2274
softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2282
prevTileX = position.prevTileX | 0;
2283
prevTileY = position.prevTileY | 0;
2275
2284
}
2276
);
2285
}
2286
options.stepCost = (x, y) =>
2287
{
2288
const base = stepCostForGround(
2289
this.groundTypeAt(x, y, dimensionId),
2290
{
2291
preferPaths: !!preferPaths,
2292
softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)
2293
}
2294
);
2295
return withCombatBackstepCost(base, x, y, prevTileX, prevTileY);
2296
};
2277
2297
options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;
2278
2298
return options;
2279
2299
}
@@ -95,6 +95,7 @@ import {95
PATH_GROUND_STEP_COST,95
PATH_GROUND_STEP_COST,96
SOFT_OCCUPIED_DWELL_MS96
SOFT_OCCUPIED_DWELL_MS97
} from "../../../shared/navigation/pathGround.js";97
} from "../../../shared/navigation/pathGround.js";98
import { withCombatBackstepCost } from "../../../shared/navigation/combatPathCost.js";98
import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";99
import { GroundType, normalizeGround } from "../../../shared/definitions/tiles.js";99
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";100
import { clearFollow, setFollow, stepFollow, recordFollowTrail, consumeFollowTrail } from "./follow.js";100
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";101
import { ensureFlightComponent, stepFreeFlight } from "./freeFlight.js";@@ -1600,6 +1601,8 @@ export class WorkerWorld1600
const flying = this.#isFlying(handle);1601
const flying = this.#isFlying(handle);1601
if (!flying)1602
if (!flying)1602
{ this.#vacate(entityId, fromTileX, fromTileY); }1603
{ this.#vacate(entityId, fromTileX, fromTileY); }1604
position.prevTileX = fromTileX;1605
position.prevTileY = fromTileY;1603
position.tileX = next.x;1606
position.tileX = next.x;1604
position.tileY = next.y;1607
position.tileY = next.y;1605
tiles.shift();1608
tiles.shift();@@ -1672,7 +1675,8 @@ export class WorkerWorld1672
this.pathfindOptions({1675
this.pathfindOptions({1673
preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),1676
preferVertical: stuckHandle != null && this.ecs.has(stuckHandle, Component.character),1674
preferPaths: !inCombat,1677
preferPaths: !inCombat,1675
entityId1678
entityId,1679
penalizeCombatBackstep: inCombat1676
})1680
})1677
);1681
);1678
path.stuckSince = now;1682
path.stuckSince = now;@@ -2260,20 +2264,36 @@ export class WorkerWorld2260
}2264
}2261
2265
2262
/**2266
/**2263
* @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null }} [options]2267
* @param {{ preferVertical?: boolean, preferPaths?: boolean, entityId?: number | null, penalizeCombatBackstep?: boolean }} [options]2264
*/2268
*/2265
pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null } = {})2269
pathfindOptions ({ preferVertical = false, preferPaths = false, entityId = null, penalizeCombatBackstep = false } = {})2266
{2270
{2267
const options = { preferVertical: !!preferVertical };2271
const options = { preferVertical: !!preferVertical };2268
const now = Date.now();2272
const now = Date.now();2269
const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;2273
const dimensionId = entityId != null ? this.#entityDimensionId(entityId) : OVERWORLD_ID;2270
options.stepCost = (x, y) => stepCostForGround(2274
let prevTileX = null;2271
this.groundTypeAt(x, y, dimensionId),2275
let prevTileY = null;2276
if (penalizeCombatBackstep && entityId != null)2277
{2278
const handle = this.ecs.handleOf(entityId);2279
const position = handle != null ? this.ecs.get(handle, Component.position) : null;2280
if (position?.prevTileX != null && position?.prevTileY != null)2272
{2281
{2273
preferPaths: !!preferPaths,2282
prevTileX = position.prevTileX | 0;2274
softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)2283
prevTileY = position.prevTileY | 0;2275
}2284
}2276
);2285
}2286
options.stepCost = (x, y) =>2287
{2288
const base = stepCostForGround(2289
this.groundTypeAt(x, y, dimensionId),2290
{2291
preferPaths: !!preferPaths,2292
softOccupied: entityId != null && this.#isSoftOccupiedTile(x, y, dimensionId, entityId, now)2293
}2294
);2295
return withCombatBackstepCost(base, x, y, prevTileX, prevTileY);2296
};2277
options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;2297
options.minStepCost = preferPaths ? PATH_GROUND_STEP_COST : 1;2278
return options;2298
return options;2279
}2299
}@@ -2,6 +2,7 @@ import test from "node:test";
2
2
import assert from "node:assert/strict";
3
3
import { findPath, orderedCardinals } from "../src/navigation/astar.js";
4
4
import { PATH_GROUND_STEP_COST, SOFT_OCCUPIED_STEP_PENALTY, stepCostForGround } from "../../shared/navigation/pathGround.js";
5
import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";
5
6
import { GroundType } from "../../shared/definitions/tiles.js";
6
7
7
8
test("A* walks around an impassable tile", () =>
@@ -202,3 +203,28 @@ test("A* still crosses soft-occupied when the detour is much longer", () =>
202
203
);
203
204
assert.ok(path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));
204
205
});
206
207
test("A* combat backstep cost prefers not re-entering the previous tile", () =>
208
{
209
// Open field start (0,0) goal (1,1). Paths: (1,0)-(1,1) or (0,1)-(1,1).
210
// Prev tile (1,0) → first path costs 2+1=3, second costs 1+1=2 → prefer (0,1).
211
const prevX = 1;
212
const prevY = 0;
213
const path = findPath(
214
0,
215
0,
216
1,
217
1,
218
() => true,
219
-2,
220
-2,
221
4,
222
4,
223
{
224
stepCost: (x, y) => withCombatBackstepCost(1, x, y, prevX, prevY)
225
}
226
);
227
assert.ok(path.length > 0);
228
assert.deepEqual(path[0], { x: 0, y: 1 }, JSON.stringify(path));
229
assert.ok(!path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));
230
});
@@ -2,6 +2,7 @@ import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { findPath, orderedCardinals } from "../src/navigation/astar.js";3
import { findPath, orderedCardinals } from "../src/navigation/astar.js";4
import { PATH_GROUND_STEP_COST, SOFT_OCCUPIED_STEP_PENALTY, stepCostForGround } from "../../shared/navigation/pathGround.js";4
import { PATH_GROUND_STEP_COST, SOFT_OCCUPIED_STEP_PENALTY, stepCostForGround } from "../../shared/navigation/pathGround.js";5
import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";5
import { GroundType } from "../../shared/definitions/tiles.js";6
import { GroundType } from "../../shared/definitions/tiles.js";6
7
7
test("A* walks around an impassable tile", () =>8
test("A* walks around an impassable tile", () =>@@ -202,3 +203,28 @@ test("A* still crosses soft-occupied when the detour is much longer", () =>202
);203
);203
assert.ok(path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));204
assert.ok(path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));204
});205
});206
207
test("A* combat backstep cost prefers not re-entering the previous tile", () =>208
{209
// Open field start (0,0) goal (1,1). Paths: (1,0)-(1,1) or (0,1)-(1,1).210
// Prev tile (1,0) → first path costs 2+1=3, second costs 1+1=2 → prefer (0,1).211
const prevX = 1;212
const prevY = 0;213
const path = findPath(214
0,215
0,216
1,217
1,218
() => true,219
-2,220
-2,221
4,222
4,223
{224
stepCost: (x, y) => withCombatBackstepCost(1, x, y, prevX, prevY)225
}226
);227
assert.ok(path.length > 0);228
assert.deepEqual(path[0], { x: 0, y: 1 }, JSON.stringify(path));229
assert.ok(!path.some((step) => step.x === 1 && step.y === 0), JSON.stringify(path));230
});@@ -1,6 +1,7 @@
1
1
import test from "node:test";
2
2
import assert from "node:assert/strict";
3
3
import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";
4
import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";
4
5
5
6
test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>
6
7
{
@@ -38,3 +39,20 @@ test("BFS returns empty when already at a goal", () =>
38
39
);
39
40
assert.deepEqual(path, []);
40
41
});
42
43
test("weighted nearest-goal search avoids an expensive backstep tile", () =>
44
{
45
// Start (0,0); goals are (1,0) and (0,1). Prev is (1,0) so prefer (0,1).
46
const path = findPathToNearestGoal(
47
0,
48
0,
49
(x, y) => (x === 1 && y === 0) || (x === 0 && y === 1),
50
() => true,
51
-2,
52
-2,
53
4,
54
4,
55
{ stepCost: (x, y) => withCombatBackstepCost(1, x, y, 1, 0) }
56
);
57
assert.deepEqual(path, [{ x: 0, y: 1 }]);
58
});
@@ -1,6 +1,7 @@1
import test from "node:test";1
import test from "node:test";2
import assert from "node:assert/strict";2
import assert from "node:assert/strict";3
import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";3
import { findPathToNearestGoal } from "../../shared/navigation/bfs.js";4
import { withCombatBackstepCost } from "../../shared/navigation/combatPathCost.js";4
5
5
test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>6
test("BFS picks the nearest stand tile toward the target, not the top-left ring tile", () =>6
{7
{@@ -38,3 +39,20 @@ test("BFS returns empty when already at a goal", () =>38
);39
);39
assert.deepEqual(path, []);40
assert.deepEqual(path, []);40
});41
});42
43
test("weighted nearest-goal search avoids an expensive backstep tile", () =>44
{45
// Start (0,0); goals are (1,0) and (0,1). Prev is (1,0) so prefer (0,1).46
const path = findPathToNearestGoal(47
0,48
0,49
(x, y) => (x === 1 && y === 0) || (x === 0 && y === 1),50
() => true,51
-2,52
-2,53
4,54
4,55
{ stepCost: (x, y) => withCombatBackstepCost(1, x, y, 1, 0) }56
);57
assert.deepEqual(path, [{ x: 0, y: 1 }]);58
});@@ -6,7 +6,7 @@ import {
6
6
ConditionKind
7
7
} from "../../shared/quests/conditions.js";
8
8
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
9
import { formatDialogueRewardMessage } from "../../shared/quests/dialogueRewards.js";
9
import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../shared/quests/dialogueRewards.js";
10
10
11
11
test("ConditionSet AND + NOT", () =>
12
12
{
@@ -56,6 +56,7 @@ test("normalize quest and dialogue", () =>
56
56
assert.equal(tree.unique, true);
57
57
assert.equal(tree.steps[0].exit.kind, "end");
58
58
assert.deepEqual(tree.steps[0].itemRewards, [{ itemId: 10, quantity: 2 }]);
59
assert.deepEqual(tree.steps[0].questRewards, []);
59
60
});
60
61
61
62
test("dialogue reward messages bag vs bank and lists", () =>
@@ -83,4 +84,12 @@ test("dialogue reward messages bag vs bank and lists", () =>
83
84
], "bag"),
84
85
"A, B and C have been added to your bag."
85
86
);
87
assert.equal(
88
formatDialogueQuestRewardMessage(["Tin Delivery"]),
89
"The Tin Delivery quest has been added to your journal."
90
);
91
assert.equal(
92
formatDialogueQuestRewardMessage(["Alpha", "Beta"]),
93
"The Alpha and Beta quests have been added to your journal."
94
);
86
95
});
@@ -6,7 +6,7 @@ import {6
ConditionKind6
ConditionKind7
} from "../../shared/quests/conditions.js";7
} from "../../shared/quests/conditions.js";8
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";8
import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";9
import { formatDialogueRewardMessage } from "../../shared/quests/dialogueRewards.js";9
import { formatDialogueRewardMessage, formatDialogueQuestRewardMessage } from "../../shared/quests/dialogueRewards.js";10
10
11
test("ConditionSet AND + NOT", () =>11
test("ConditionSet AND + NOT", () =>12
{12
{@@ -56,6 +56,7 @@ test("normalize quest and dialogue", () =>56
assert.equal(tree.unique, true);56
assert.equal(tree.unique, true);57
assert.equal(tree.steps[0].exit.kind, "end");57
assert.equal(tree.steps[0].exit.kind, "end");58
assert.deepEqual(tree.steps[0].itemRewards, [{ itemId: 10, quantity: 2 }]);58
assert.deepEqual(tree.steps[0].itemRewards, [{ itemId: 10, quantity: 2 }]);59
assert.deepEqual(tree.steps[0].questRewards, []);59
});60
});60
61
61
test("dialogue reward messages bag vs bank and lists", () =>62
test("dialogue reward messages bag vs bank and lists", () =>@@ -83,4 +84,12 @@ test("dialogue reward messages bag vs bank and lists", () =>83
], "bag"),84
], "bag"),84
"A, B and C have been added to your bag."85
"A, B and C have been added to your bag."85
);86
);87
assert.equal(88
formatDialogueQuestRewardMessage(["Tin Delivery"]),89
"The Tin Delivery quest has been added to your journal."90
);91
assert.equal(92
formatDialogueQuestRewardMessage(["Alpha", "Beta"]),93
"The Alpha and Beta quests have been added to your journal."94
);86
});95
});