BlueGit

timfa questward

Files

questward / client / src / editor / questsModal.js

questsModal.js

questsModal.js 16.1 KiB Download Raw
1import { normalizeQuestDef } from "/shared/quests/normalize.js";
2import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
3import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
4
5const SIMPLE_KINDS = [
6 ConditionKind.hasItem,
7 ConditionKind.questState,
8 ConditionKind.dialogueHeard,
9 ConditionKind.killCount,
10 ConditionKind.atTile,
11 ConditionKind.inDimension,
12 ConditionKind.hasVisitedDimension
13];
14
15export function initQuestsModal ({ socket, MessageType })
16{
17 const backdrop = document.getElementById("quests-backdrop");
18 const modal = document.getElementById("quests-modal");
19 const listEl = document.getElementById("quests-list");
20 const editorEl = document.getElementById("quests-editor");
21 const saveBtn = document.getElementById("quests-save");
22 const deleteBtn = document.getElementById("quests-delete");
23 let open = false;
24 /** @type {ReturnType<typeof normalizeQuestDef>[]} */
25 let quests = [];
26 /** @type {ReturnType<typeof normalizeQuestDef>|null} */
27 let draft = null;
28 let selectedId = null;
29
30 function show (visible)
31 {
32 open = visible;
33 backdrop.hidden = !visible;
34 modal.hidden = !visible;
35 if (!visible)
36 {
37 draft = null;
38 selectedId = null;
39 }
40 }
41
42 function selectQuest (questId)
43 {
44 const found = quests.find((q) => q.questId === questId);
45 if (!found)
46 {
47 draft = null;
48 selectedId = null;
49 render();
50 return;
51 }
52 selectedId = found.questId;
53 draft = structuredClone(found);
54 render();
55 }
56
57 function renderList ()
58 {
59 listEl.replaceChildren();
60 for (const quest of quests)
61 {
62 const btn = document.createElement("button");
63 btn.type = "button";
64 btn.textContent = quest.title || quest.questId;
65 if (quest.questId === selectedId)
66 { btn.classList.add("active"); }
67 btn.addEventListener("click", () => selectQuest(quest.questId));
68 listEl.append(btn);
69 }
70 }
71
72 function renderEditor ()
73 {
74 editorEl.replaceChildren();
75 saveBtn.disabled = !draft;
76 deleteBtn.disabled = !draft;
77 if (!draft)
78 {
79 const hint = document.createElement("p");
80 hint.className = "content-editor-hint";
81 hint.textContent = "Select a quest or create a new one.";
82 editorEl.append(hint);
83 return;
84 }
85
86 editorEl.append(
87 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
88 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
89 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
90 );
91
92 const stepsHeader = sectionHeader("Steps", () =>
93 {
94 draft.steps.push({
95 stepId: `step-${draft.steps.length + 1}`,
96 title: "New step",
97 description: "",
98 completionJournalText: "",
99 objectives: [{
100 objectiveId: "obj-1",
101 text: "Complete this step",
102 when: emptyConditionSet()
103 }],
104 onEnter: [],
105 onComplete: []
106 });
107 renderEditor();
108 });
109 editorEl.append(stepsHeader);
110
111 draft.steps.forEach((step, stepIndex) =>
112 {
113 const box = document.createElement("div");
114 box.className = "content-editor-section";
115 const head = sectionHeader(`Step ${stepIndex + 1}`, null, () =>
116 {
117 draft.steps.splice(stepIndex, 1);
118 if (draft.steps.length === 0)
119 {
120 draft.steps.push(normalizeQuestDef({ questId: draft.questId }).steps[0]);
121 }
122 renderEditor();
123 });
124 box.append(head);
125 box.append(
126 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
127 field("Title", textInput(step.title, (v) => { step.title = v; })),
128 field("Description", textArea(step.description, (v) => { step.description = v; }, 2)),
129 field("Completion journal", textArea(step.completionJournalText, (v) =>
130 {
131 step.completionJournalText = v;
132 }, 2))
133 );
134
135 const objHead = sectionHeader("Objectives", () =>
136 {
137 step.objectives.push({
138 objectiveId: `obj-${step.objectives.length + 1}`,
139 text: "New objective",
140 when: emptyConditionSet()
141 });
142 renderEditor();
143 });
144 box.append(objHead);
145
146 step.objectives.forEach((obj, objIndex) =>
147 {
148 const objBox = document.createElement("div");
149 objBox.className = "content-editor-section";
150 objBox.append(
151 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
152 {
153 step.objectives.splice(objIndex, 1);
154 if (step.objectives.length === 0)
155 {
156 step.objectives.push({
157 objectiveId: "obj-1",
158 text: "Complete this step",
159 when: emptyConditionSet()
160 });
161 }
162 renderEditor();
163 }),
164 field("Text", textInput(obj.text, (v) => { obj.text = v; }))
165 );
166 objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>
167 {
168 obj.when = next;
169 if (remount)
170 { renderEditor(); }
171 }));
172 box.append(objBox);
173 });
174 editorEl.append(box);
175 });
176 }
177
178 function render ()
179 {
180 renderList();
181 renderEditor();
182 }
183
184 document.getElementById("open-quests").addEventListener("click", () =>
185 {
186 socket.send({ type: MessageType.editorLoadQuests });
187 show(true);
188 render();
189 });
190 document.getElementById("quests-close").addEventListener("click", () => show(false));
191 backdrop.addEventListener("click", () => show(false));
192 document.getElementById("quests-new").addEventListener("click", () =>
193 {
194 const base = normalizeQuestDef({
195 questId: `quest-${quests.length + 1}`,
196 title: "New quest",
197 description: ""
198 });
199 draft = structuredClone(base);
200 selectedId = null;
201 render();
202 });
203 saveBtn.addEventListener("click", () =>
204 {
205 if (!draft)
206 { return; }
207 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
208 });
209 deleteBtn.addEventListener("click", () =>
210 {
211 if (!draft?.questId)
212 { return; }
213 if (!window.confirm(`Delete quest "${draft.questId}"?`))
214 { return; }
215 socket.send({ type: MessageType.editorDeleteQuest, questId: draft.questId });
216 });
217
218 return {
219 isOpen: () => open,
220 handleMessage (message)
221 {
222 if (message.type !== MessageType.editorQuests)
223 { return; }
224 quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
225 if (draft)
226 {
227 const still = quests.find((q) => q.questId === draft.questId);
228 if (still)
229 {
230 selectedId = still.questId;
231 draft = structuredClone(still);
232 }
233 else if (selectedId)
234 {
235 draft = null;
236 selectedId = null;
237 }
238 }
239 if (open)
240 { render(); }
241 }
242 };
243}
244
245function field (label, input)
246{
247 const wrap = document.createElement("label");
248 wrap.append(document.createTextNode(label), input);
249 return wrap;
250}
251
252function textInput (value, onChange)
253{
254 const input = document.createElement("input");
255 input.type = "text";
256 input.value = value ?? "";
257 input.addEventListener("input", () => onChange(input.value));
258 return input;
259}
260
261function textArea (value, onChange, rows = 3)
262{
263 const input = document.createElement("textarea");
264 input.rows = rows;
265 input.value = value ?? "";
266 input.addEventListener("input", () => onChange(input.value));
267 return input;
268}
269
270function sectionHeader (title, onAdd, onRemove)
271{
272 const head = document.createElement("div");
273 head.className = "content-editor-section-header";
274 const strong = document.createElement("strong");
275 strong.textContent = title;
276 head.append(strong);
277 const actions = document.createElement("div");
278 actions.className = "content-editor-row";
279 if (onAdd)
280 {
281 const add = document.createElement("button");
282 add.type = "button";
283 add.textContent = "+";
284 add.title = "Add";
285 add.addEventListener("click", onAdd);
286 actions.append(add);
287 }
288 if (onRemove)
289 {
290 const remove = document.createElement("button");
291 remove.type = "button";
292 remove.textContent = "×";
293 remove.title = "Remove";
294 remove.addEventListener("click", onRemove);
295 actions.append(remove);
296 }
297 head.append(actions);
298 return head;
299}
300
301function renderConditionSet (when, onChange)
302{
303 const wrap = document.createElement("div");
304 const set = normalizeConditionSet(when);
305 const bump = (remount = true) => onChange(set, { remount });
306 const title = document.createElement("strong");
307 title.textContent = "When (all of)";
308 wrap.append(title);
309
310 set.all.forEach((clause, index) =>
311 {
312 const row = document.createElement("div");
313 row.className = "content-editor-clause";
314 const notLabel = document.createElement("label");
315 const notBox = document.createElement("input");
316 notBox.type = "checkbox";
317 notBox.checked = !!clause.not;
318 notBox.addEventListener("change", () =>
319 {
320 set.all[index].not = notBox.checked;
321 bump(false);
322 });
323 notLabel.append(notBox, document.createTextNode(" NOT"));
324 row.append(notLabel);
325
326 const kind = document.createElement("select");
327 for (const k of SIMPLE_KINDS)
328 {
329 const opt = document.createElement("option");
330 opt.value = k;
331 opt.textContent = k;
332 if ((clause.condition?.kind ?? "") === k)
333 { opt.selected = true; }
334 kind.append(opt);
335 }
336 const otherOpt = document.createElement("option");
337 otherOpt.value = "__other__";
338 otherOpt.textContent = "(other / JSON)";
339 if (!SIMPLE_KINDS.includes(clause.condition?.kind))
340 { otherOpt.selected = true; }
341 kind.append(otherOpt);
342 kind.addEventListener("change", () =>
343 {
344 if (kind.value === "__other__")
345 { return; }
346 set.all[index].condition = defaultCondition(kind.value);
347 bump(true);
348 });
349 row.append(kind);
350
351 const cond = clause.condition ?? { kind: ConditionKind.hasItem };
352 if (cond.kind === ConditionKind.hasItem)
353 {
354 row.append(itemConditionPicker(cond, () =>
355 {
356 set.all[index].condition = cond;
357 bump(false);
358 }));
359 row.append(miniField("qty", cond.quantity ?? 1, (v) =>
360 {
361 cond.quantity = Number(v) || 1;
362 set.all[index].condition = cond;
363 bump(false);
364 }));
365 }
366 else if (cond.kind === ConditionKind.questState)
367 {
368 row.append(miniField("questId", cond.questId ?? "", (v) =>
369 {
370 cond.questId = v;
371 set.all[index].condition = cond;
372 bump(false);
373 }));
374 row.append(miniField("state", cond.state ?? "not-started", (v) =>
375 {
376 const n = Number(v);
377 cond.state = Number.isFinite(n) && String(n) === String(v).trim() ? n : v;
378 set.all[index].condition = cond;
379 bump(false);
380 }));
381 }
382 else if (cond.kind === ConditionKind.dialogueHeard)
383 {
384 row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) =>
385 {
386 cond.dialogueId = v;
387 set.all[index].condition = cond;
388 bump(false);
389 }));
390 row.append(miniField("stepId", cond.stepId ?? "", (v) =>
391 {
392 cond.stepId = v;
393 set.all[index].condition = cond;
394 bump(false);
395 }));
396 }
397 else if (cond.kind === ConditionKind.killCount)
398 {
399 row.append(miniField("mobTypeId", cond.mobTypeId ?? "", (v) =>
400 {
401 cond.mobTypeId = v || undefined;
402 set.all[index].condition = cond;
403 bump(false);
404 }));
405 row.append(miniField("count", cond.count ?? 1, (v) =>
406 {
407 cond.count = Number(v) || 1;
408 set.all[index].condition = cond;
409 bump(false);
410 }));
411 }
412 else if (cond.kind === ConditionKind.atTile)
413 {
414 row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
415 {
416 cond.dimensionId = String(v || "overworld");
417 set.all[index].condition = cond;
418 bump(false);
419 }));
420 row.append(miniField("tileX", cond.tileX ?? 0, (v) =>
421 {
422 cond.tileX = Number(v) | 0;
423 set.all[index].condition = cond;
424 bump(false);
425 }));
426 row.append(miniField("tileY", cond.tileY ?? 0, (v) =>
427 {
428 cond.tileY = Number(v) | 0;
429 set.all[index].condition = cond;
430 bump(false);
431 }));
432 }
433 else if (
434 cond.kind === ConditionKind.inDimension
435 || cond.kind === ConditionKind.hasVisitedDimension
436 )
437 {
438 row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
439 {
440 cond.dimensionId = String(v || "overworld");
441 set.all[index].condition = cond;
442 bump(false);
443 }));
444 }
445 else
446 {
447 const json = document.createElement("textarea");
448 json.rows = 3;
449 json.value = JSON.stringify(cond, null, 2);
450 json.addEventListener("change", () =>
451 {
452 try
453 {
454 set.all[index].condition = JSON.parse(json.value);
455 bump(false);
456 }
457 catch
458 { /* keep typing */ }
459 });
460 row.append(json);
461 }
462
463 const remove = document.createElement("button");
464 remove.type = "button";
465 remove.textContent = "×";
466 remove.addEventListener("click", () =>
467 {
468 set.all.splice(index, 1);
469 bump(true);
470 });
471 row.append(remove);
472 wrap.append(row);
473 });
474
475 const add = document.createElement("button");
476 add.type = "button";
477 add.textContent = "Add clause";
478 add.addEventListener("click", () =>
479 {
480 set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) });
481 bump(true);
482 });
483 wrap.append(add);
484
485 const jsonFallback = document.createElement("details");
486 const summary = document.createElement("summary");
487 summary.textContent = "Edit condition set as JSON";
488 const area = document.createElement("textarea");
489 area.rows = 5;
490 area.value = JSON.stringify(set, null, 2);
491 area.addEventListener("change", () =>
492 {
493 try
494 {
495 onChange(normalizeConditionSet(JSON.parse(area.value)), { remount: true });
496 }
497 catch
498 { /* ignore */ }
499 });
500 jsonFallback.append(summary, area);
501 wrap.append(jsonFallback);
502 return wrap;
503}
504
505/** Compact searchable item picker for hasItem conditions. */
506function itemConditionPicker (cond, onPicked)
507{
508 const wrap = document.createElement("div");
509 wrap.className = "quest-condition-item-picker";
510 const pickBtn = document.createElement("button");
511 pickBtn.type = "button";
512 const refreshLabel = () =>
513 {
514 const def = itemDefinition(cond.itemId);
515 pickBtn.textContent = def?.displayName
516 ?? (cond.itemId ? `Item #${cond.itemId}` : "Pick item…");
517 pickBtn.title = cond.itemId
518 ? `${def?.key ?? "item"} · #${cond.itemId}`
519 : "Choose an item";
520 };
521 refreshLabel();
522 const searchWrap = document.createElement("div");
523 searchWrap.className = "dialogue-reward-item-search";
524 searchWrap.hidden = true;
525 const searchInput = document.createElement("input");
526 searchInput.type = "search";
527 searchInput.placeholder = "Search items…";
528 searchInput.autocomplete = "off";
529 const searchResults = document.createElement("div");
530 searchResults.className = "dialogue-reward-item-results";
531
532 const renderMatches = (query) =>
533 {
534 searchResults.replaceChildren();
535 const q = String(query ?? "").trim().toLowerCase();
536 const matches = listAllItemPickerEntries().filter((item) =>
537 {
538 if (!q)
539 { return true; }
540 return item.displayName.toLowerCase().includes(q)
541 || item.key.toLowerCase().includes(q)
542 || String(item.itemId).includes(q);
543 }).slice(0, 40);
544 if (!matches.length)
545 {
546 searchResults.textContent = "No matching items.";
547 return;
548 }
549 for (const item of matches)
550 {
551 const row = document.createElement("button");
552 row.type = "button";
553 row.className = "shop-item-search-row";
554 const name = document.createElement("span");
555 name.className = "shop-item-search-row-name";
556 name.textContent = item.displayName;
557 const key = document.createElement("span");
558 key.className = "shop-item-search-row-key";
559 key.textContent = `${item.key} · #${item.itemId}`;
560 row.append(name, key);
561 row.addEventListener("click", () =>
562 {
563 cond.itemId = item.itemId;
564 refreshLabel();
565 searchWrap.hidden = true;
566 onPicked();
567 });
568 searchResults.append(row);
569 }
570 };
571
572 pickBtn.addEventListener("click", () =>
573 {
574 searchWrap.hidden = !searchWrap.hidden;
575 if (!searchWrap.hidden)
576 {
577 searchInput.value = "";
578 renderMatches("");
579 searchInput.focus();
580 }
581 });
582 searchInput.addEventListener("input", () => renderMatches(searchInput.value));
583 searchWrap.append(searchInput, searchResults);
584 wrap.append(pickBtn, searchWrap);
585 return wrap;
586}
587
588function miniField (label, value, onChange)
589{
590 const wrap = document.createElement("label");
591 wrap.textContent = `${label} `;
592 const input = document.createElement("input");
593 input.type = "text";
594 input.value = String(value ?? "");
595 input.style.width = "7rem";
596 input.addEventListener("input", () => onChange(input.value));
597 wrap.append(input);
598 return wrap;
599}
600
601function defaultCondition (kind)
602{
603 switch (kind)
604 {
605 case ConditionKind.hasItem:
606 return { kind, itemId: 1, quantity: 1 };
607 case ConditionKind.questState:
608 return { kind, questId: "", state: "not-started" };
609 case ConditionKind.dialogueHeard:
610 return { kind, dialogueId: "", stepId: "" };
611 case ConditionKind.killCount:
612 return { kind, mobTypeId: "deer", count: 1 };
613 case ConditionKind.atTile:
614 return { kind, dimensionId: "overworld", tileX: 0, tileY: 0 };
615 case ConditionKind.inDimension:
616 case ConditionKind.hasVisitedDimension:
617 return { kind, dimensionId: "overworld" };
618 default:
619 return { kind };
620 }
621}