BlueGit

timfa questward

Files

questward / client / src / editor / questsModal.js

questsModal.js

questsModal.js 16.6 KiB Download Raw
1import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js";
2import { emptyConditionSet, EffectKind, normalizeEffects } from "/shared/quests/conditions.js";
3import { renderConditionSet } from "./conditionSetEditor.js";
4import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js";
5import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js";
6
7export function initQuestsModal ({
8 socket,
9 MessageType,
10 describeWorldTile = null,
11 centerEditorOnTile = null,
12 getDimensionOptions = null
13})
14{
15 const backdrop = document.getElementById("quests-backdrop");
16 const modal = document.getElementById("quests-modal");
17 const listEl = document.getElementById("quests-list");
18 const editorEl = document.getElementById("quests-editor");
19 const logEl = document.getElementById("quests-log");
20 const saveBtn = document.getElementById("quests-save");
21 const deleteBtn = document.getElementById("quests-delete");
22 let open = false;
23 /** @type {ReturnType<typeof normalizeQuestDef>[]} */
24 let quests = [];
25 /** @type {ReturnType<typeof normalizeDialogueTree>[]} */
26 let dialogues = [];
27 /** @type {ReturnType<typeof normalizeQuestDef>|null} */
28 let draft = null;
29 let selectedId = null;
30 /** @type {object[]} */
31 let changelog = [];
32
33 /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */
34 let itemPickContext = null;
35
36 function show (visible)
37 {
38 open = visible;
39 backdrop.hidden = !visible;
40 modal.hidden = !visible;
41 if (!visible)
42 {
43 draft = null;
44 selectedId = null;
45 closeInlineItemSearch();
46 }
47 }
48
49 function closeInlineItemSearch ()
50 {
51 if (itemPickContext?.resultsEl)
52 { itemPickContext.resultsEl.replaceChildren(); }
53 itemPickContext = null;
54 }
55
56 function openInlineItemSearch (inputEl, resultsEl)
57 {
58 itemPickContext = { inputEl, resultsEl };
59 inputEl.value = "";
60 renderInlineItemSearch("");
61 inputEl.focus();
62 }
63
64 function renderInlineItemSearch (query)
65 {
66 if (!itemPickContext || !draft)
67 { return; }
68 const { resultsEl } = itemPickContext;
69 resultsEl.replaceChildren();
70 const q = String(query ?? "").trim().toLowerCase();
71 const taken = new Set(
72 (draft.rewards ?? [])
73 .filter((row) => row.kind === EffectKind.giveItem)
74 .map((row) => row.itemId)
75 );
76 const matches = listAllItemPickerEntries().filter((item) =>
77 {
78 if (taken.has(item.itemId))
79 { return false; }
80 if (!q)
81 { return true; }
82 return item.displayName.toLowerCase().includes(q)
83 || item.key.toLowerCase().includes(q)
84 || String(item.itemId).includes(q);
85 }).slice(0, 40);
86 if (!matches.length)
87 {
88 resultsEl.textContent = "No matching items.";
89 return;
90 }
91 for (const item of matches)
92 {
93 const row = document.createElement("button");
94 row.type = "button";
95 row.className = "shop-item-search-row";
96 const name = document.createElement("span");
97 name.className = "shop-item-search-row-name";
98 name.textContent = item.displayName;
99 const key = document.createElement("span");
100 key.className = "shop-item-search-row-key";
101 key.textContent = `${item.key} · #${item.itemId}`;
102 row.append(name, key);
103 row.addEventListener("click", () =>
104 {
105 if (!Array.isArray(draft.rewards))
106 { draft.rewards = []; }
107 draft.rewards.push({
108 kind: EffectKind.giveItem,
109 itemId: item.itemId,
110 quantity: 1,
111 toBank: false
112 });
113 draft.rewards = normalizeEffects(draft.rewards);
114 closeInlineItemSearch();
115 renderEditor();
116 });
117 resultsEl.append(row);
118 }
119 }
120
121 function selectQuest (questId)
122 {
123 const found = quests.find((q) => q.questId === questId);
124 if (!found)
125 {
126 draft = null;
127 selectedId = null;
128 render();
129 return;
130 }
131 selectedId = found.questId;
132 draft = structuredClone(found);
133 render();
134 }
135
136 function renderList ()
137 {
138 listEl.replaceChildren();
139 for (const quest of quests)
140 {
141 const btn = document.createElement("button");
142 btn.type = "button";
143 btn.textContent = quest.title || quest.questId;
144 if (quest.questId === selectedId)
145 { btn.classList.add("active"); }
146 btn.addEventListener("click", () => selectQuest(quest.questId));
147 listEl.append(btn);
148 }
149 }
150
151 function addStep ()
152 {
153 draft.steps.push({
154 stepId: `step-${draft.steps.length + 1}`,
155 title: "New step",
156 description: "",
157 completionJournalText: "",
158 objectives: [{
159 objectiveId: "obj-1",
160 text: "Complete this step",
161 when: emptyConditionSet()
162 }],
163 onEnter: [],
164 onComplete: []
165 });
166 renderEditor();
167 }
168
169 function renderEditor ()
170 {
171 editorEl.replaceChildren();
172 saveBtn.disabled = !draft;
173 deleteBtn.disabled = !draft;
174 if (!draft)
175 {
176 const hint = document.createElement("p");
177 hint.className = "content-editor-hint";
178 hint.textContent = "Select a quest or create a new one.";
179 editorEl.append(hint);
180 return;
181 }
182
183 if (!Array.isArray(draft.rewards))
184 { draft.rewards = []; }
185
186 editorEl.append(
187 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
188 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
189 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
190 );
191
192 const stepsTitle = document.createElement("div");
193 stepsTitle.className = "content-editor-section-header";
194 const stepsStrong = document.createElement("strong");
195 stepsStrong.textContent = "Steps";
196 stepsTitle.append(stepsStrong);
197 editorEl.append(stepsTitle);
198
199 draft.steps.forEach((step, stepIndex) =>
200 {
201 const box = document.createElement("div");
202 box.className = "content-editor-section";
203 const head = sectionHeader(`Step ${stepIndex + 1}`, null, () =>
204 {
205 if (!window.confirm(`Delete quest step "${step.stepId || stepIndex + 1}"?`))
206 { return; }
207 draft.steps.splice(stepIndex, 1);
208 if (draft.steps.length === 0)
209 {
210 draft.steps.push(normalizeQuestDef({ questId: draft.questId }).steps[0]);
211 }
212 renderEditor();
213 });
214 box.append(head);
215 box.append(
216 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
217 field("Title", textInput(step.title, (v) => { step.title = v; })),
218 field("Description", textArea(step.description, (v) => { step.description = v; }, 2)),
219 field("Completion journal", textArea(step.completionJournalText, (v) =>
220 {
221 step.completionJournalText = v;
222 }, 2))
223 );
224
225 const objHead = sectionHeader("Objectives", () =>
226 {
227 step.objectives.push({
228 objectiveId: `obj-${step.objectives.length + 1}`,
229 text: "New objective",
230 when: emptyConditionSet()
231 });
232 renderEditor();
233 });
234 box.append(objHead);
235
236 step.objectives.forEach((obj, objIndex) =>
237 {
238 const objBox = document.createElement("div");
239 objBox.className = "content-editor-section";
240 objBox.append(
241 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
242 {
243 if (!window.confirm(`Delete objective "${obj.text || obj.objectiveId || objIndex + 1}"?`))
244 { return; }
245 step.objectives.splice(objIndex, 1);
246 if (step.objectives.length === 0)
247 {
248 step.objectives.push({
249 objectiveId: "obj-1",
250 text: "Complete this step",
251 when: emptyConditionSet()
252 });
253 }
254 renderEditor();
255 }),
256 field("Text", textInput(obj.text, (v) => { obj.text = v; }))
257 );
258 objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) =>
259 {
260 obj.when = next;
261 if (remount)
262 { renderEditor(); }
263 }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions }));
264 box.append(objBox);
265 });
266 editorEl.append(box);
267 });
268
269 const addStepBtn = document.createElement("button");
270 addStepBtn.type = "button";
271 addStepBtn.className = "content-editor-add-step";
272 addStepBtn.textContent = "(add step)";
273 addStepBtn.addEventListener("click", addStep);
274 editorEl.append(addStepBtn);
275
276 renderRewardsSection();
277 }
278
279 function renderRewardsSection ()
280 {
281 const box = document.createElement("div");
282 box.className = "content-editor-section";
283 const title = document.createElement("div");
284 title.className = "content-editor-section-header";
285 const strong = document.createElement("strong");
286 strong.textContent = "Completion rewards";
287 title.append(strong);
288 box.append(title);
289
290 const hint = document.createElement("p");
291 hint.className = "content-editor-hint";
292 hint.textContent = "Granted when the final step completes. Bank-checked items (or overflow) go to the bank with a Questward letter.";
293 box.append(hint);
294
295 const xpHead = sectionHeader("Skill XP", () =>
296 {
297 const skillId = ALL_SKILL_IDS.find((id) =>
298 !(draft.rewards ?? []).some((r) => r.kind === EffectKind.giveXp && r.skillId === id)
299 ) ?? ALL_SKILL_IDS[0];
300 draft.rewards.push({ kind: EffectKind.giveXp, skillId, amount: 15 });
301 draft.rewards = normalizeEffects(draft.rewards);
302 renderEditor();
303 });
304 box.append(xpHead);
305
306 const xpRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveXp);
307 if (!xpRows.length)
308 {
309 const empty = document.createElement("p");
310 empty.className = "content-editor-hint";
311 empty.textContent = "No skill XP rewards.";
312 box.append(empty);
313 }
314 xpRows.forEach((reward) =>
315 {
316 const rewardIndex = draft.rewards.indexOf(reward);
317 const row = document.createElement("div");
318 row.className = "content-editor-row";
319 const skill = document.createElement("select");
320 for (const skillId of ALL_SKILL_IDS)
321 {
322 const opt = document.createElement("option");
323 opt.value = skillId;
324 opt.textContent = SKILL_DEFINITIONS[skillId]?.displayName ?? skillId;
325 if (reward.skillId === skillId)
326 { opt.selected = true; }
327 skill.append(opt);
328 }
329 skill.addEventListener("change", () =>
330 {
331 draft.rewards[rewardIndex].skillId = skill.value;
332 });
333 const amount = document.createElement("input");
334 amount.type = "number";
335 amount.min = "1";
336 amount.step = "1";
337 amount.value = String(Math.max(1, reward.amount | 0 || 1));
338 amount.title = "XP amount";
339 amount.addEventListener("input", () =>
340 {
341 draft.rewards[rewardIndex].amount = Math.max(1, Number(amount.value) || 1) | 0;
342 });
343 row.append(skill, amount, removeButton(() =>
344 {
345 draft.rewards.splice(rewardIndex, 1);
346 renderEditor();
347 }));
348 box.append(row);
349 });
350
351 const searchWrap = document.createElement("div");
352 searchWrap.className = "dialogue-reward-item-search";
353 searchWrap.hidden = true;
354 const searchInput = document.createElement("input");
355 searchInput.type = "search";
356 searchInput.placeholder = "Search items…";
357 searchInput.autocomplete = "off";
358 searchInput.addEventListener("input", () => renderInlineItemSearch(searchInput.value));
359 const searchResults = document.createElement("div");
360 searchResults.className = "dialogue-reward-item-results";
361 searchWrap.append(searchInput, searchResults);
362
363 const itemHead = sectionHeader("Items", () =>
364 {
365 searchWrap.hidden = false;
366 openInlineItemSearch(searchInput, searchResults);
367 });
368 box.append(itemHead);
369
370 const itemRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveItem);
371 if (!itemRows.length)
372 {
373 const empty = document.createElement("p");
374 empty.className = "content-editor-hint";
375 empty.textContent = "No item rewards.";
376 box.append(empty);
377 }
378 itemRows.forEach((reward) =>
379 {
380 const rewardIndex = draft.rewards.indexOf(reward);
381 const def = itemDefinition(reward.itemId);
382 const row = document.createElement("div");
383 row.className = "spawner-drops-row";
384 const name = document.createElement("span");
385 name.className = "spawner-sells-name";
386 name.textContent = def?.displayName ?? `Item ${reward.itemId}`;
387 const qty = document.createElement("input");
388 qty.type = "number";
389 qty.min = "1";
390 qty.step = "1";
391 qty.value = String(Math.max(1, reward.quantity | 0 || 1));
392 qty.title = "Quantity";
393 qty.addEventListener("input", () =>
394 {
395 draft.rewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0;
396 });
397 const bankLabel = document.createElement("label");
398 bankLabel.className = "quest-reward-bank";
399 const bankBox = document.createElement("input");
400 bankBox.type = "checkbox";
401 bankBox.checked = !!reward.toBank;
402 bankBox.addEventListener("change", () =>
403 {
404 draft.rewards[rewardIndex].toBank = bankBox.checked;
405 });
406 bankLabel.append(bankBox, document.createTextNode(" Bank"));
407 row.append(name, qty, bankLabel, removeButton(() =>
408 {
409 draft.rewards.splice(rewardIndex, 1);
410 renderEditor();
411 }));
412 box.append(row);
413 });
414 box.append(searchWrap);
415 editorEl.append(box);
416 }
417
418 function render ()
419 {
420 renderList();
421 renderEditor();
422 renderLog();
423 }
424
425 function renderLog ()
426 {
427 if (!logEl)
428 { return; }
429 logEl.innerHTML = "";
430 const scopeId = draft?.questId ?? selectedId;
431 const entries = scopeId
432 ? changelog.filter((entry) => entry.questId === scopeId)
433 : changelog;
434 if (!entries.length)
435 {
436 logEl.innerHTML = scopeId
437 ? "<p class=\"hint\">No edits logged for this quest yet.</p>"
438 : "<p class=\"hint\">No quest edits logged yet.</p>";
439 return;
440 }
441 for (const entry of entries)
442 {
443 const item = document.createElement("article");
444 const who = entry.editorDisplayName || entry.editor_admin_id;
445 const scope = scopeId ? "" : ` · ${entry.questId}`;
446 item.innerHTML = `<header>${who}${scope} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
447 const list = document.createElement("ul");
448 for (const bullet of entry.diffEntries ?? [])
449 {
450 const li = document.createElement("li");
451 li.textContent = bullet;
452 list.append(li);
453 }
454 item.append(list);
455 logEl.append(item);
456 }
457 logEl.scrollTop = logEl.scrollHeight;
458 }
459
460 document.getElementById("open-quests").addEventListener("click", () =>
461 {
462 socket.send({ type: MessageType.editorLoadQuests });
463 socket.send({ type: MessageType.editorLoadDialogues });
464 show(true);
465 render();
466 });
467 document.getElementById("quests-close").addEventListener("click", () => show(false));
468 backdrop.addEventListener("click", () => show(false));
469 document.getElementById("quests-new").addEventListener("click", () =>
470 {
471 const base = normalizeQuestDef({
472 questId: `quest-${quests.length + 1}`,
473 title: "New quest",
474 description: ""
475 });
476 draft = structuredClone(base);
477 selectedId = null;
478 render();
479 });
480 saveBtn.addEventListener("click", () =>
481 {
482 if (!draft)
483 { return; }
484 draft.rewards = normalizeEffects(draft.rewards);
485 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
486 });
487 deleteBtn.addEventListener("click", () =>
488 {
489 if (!draft?.questId)
490 { return; }
491 if (!window.confirm(`Delete quest "${draft.questId}"?`))
492 { return; }
493 socket.send({ type: MessageType.editorDeleteQuest, questId: draft.questId });
494 });
495
496 return {
497 isOpen: () => open,
498 getQuests: () => quests,
499 handleMessage (message)
500 {
501 if (message.type === MessageType.editorDialogues)
502 {
503 dialogues = (message.dialogues ?? []).map((d) => normalizeDialogueTree(d));
504 if (open)
505 { render(); }
506 return;
507 }
508 if (message.type !== MessageType.editorQuests)
509 { return; }
510 quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
511 changelog = message.changelog ?? [];
512 if (draft)
513 {
514 const still = quests.find((q) => q.questId === draft.questId);
515 if (still)
516 {
517 selectedId = still.questId;
518 draft = structuredClone(still);
519 }
520 else if (selectedId)
521 {
522 draft = null;
523 selectedId = null;
524 }
525 }
526 if (open)
527 { render(); }
528 }
529 };
530}
531
532function removeButton (onClick)
533{
534 const remove = document.createElement("button");
535 remove.type = "button";
536 remove.className = "content-editor-remove";
537 remove.textContent = "×";
538 remove.title = "Remove";
539 remove.addEventListener("click", onClick);
540 return remove;
541}
542
543function field (label, input)
544{
545 const wrap = document.createElement("label");
546 wrap.append(document.createTextNode(label), input);
547 return wrap;
548}
549
550function textInput (value, onChange)
551{
552 const input = document.createElement("input");
553 input.type = "text";
554 input.value = value ?? "";
555 input.addEventListener("input", () => onChange(input.value));
556 return input;
557}
558
559function textArea (value, onChange, rows = 3)
560{
561 const input = document.createElement("textarea");
562 input.rows = rows;
563 input.value = value ?? "";
564 input.addEventListener("input", () => onChange(input.value));
565 return input;
566}
567
568function sectionHeader (title, onAdd, onRemove)
569{
570 const head = document.createElement("div");
571 head.className = "content-editor-section-header";
572 const strong = document.createElement("strong");
573 strong.textContent = title;
574 head.append(strong);
575 const actions = document.createElement("div");
576 actions.className = "content-editor-row";
577 if (onAdd)
578 {
579 const add = document.createElement("button");
580 add.type = "button";
581 add.textContent = "+";
582 add.title = "Add";
583 add.addEventListener("click", onAdd);
584 actions.append(add);
585 }
586 if (onRemove)
587 { actions.append(removeButton(onRemove)); }
588 head.append(actions);
589 return head;
590}