BlueGit

timfa questward

Files

questward / client / src / editor / questsModal.js

questsModal.js

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