BlueGit

timfa questward

Files

questward / client / src / editor / questsModal.js

questsModal.js

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