import { normalizeQuestDef, normalizeDialogueTree } from "/shared/quests/normalize.js"; import { emptyConditionSet, EffectKind, normalizeEffects } from "/shared/quests/conditions.js"; import { renderConditionSet } from "./conditionSetEditor.js"; import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js"; import { ALL_SKILL_IDS, SKILL_DEFINITIONS } from "/shared/definitions/skills.js"; export function initQuestsModal ({ socket, MessageType, describeWorldTile = null, centerEditorOnTile = null, getDimensionOptions = null, getSpawnerOptions = null }) { const backdrop = document.getElementById("quests-backdrop"); const modal = document.getElementById("quests-modal"); const listEl = document.getElementById("quests-list"); const editorEl = document.getElementById("quests-editor"); const logEl = document.getElementById("quests-log"); const saveBtn = document.getElementById("quests-save"); const deleteBtn = document.getElementById("quests-delete"); let open = false; /** @type {ReturnType[]} */ let quests = []; /** @type {ReturnType[]} */ let dialogues = []; /** @type {{ spawnerId: string, mobTypeId?: string, dimensionId?: string, tileX?: number, tileY?: number }[]} */ let serverSpawners = []; /** @type {ReturnType|null} */ let draft = null; let selectedId = null; /** @type {object[]} */ let changelog = []; /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */ let itemPickContext = null; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { draft = null; selectedId = null; closeInlineItemSearch(); } } function closeInlineItemSearch () { if (itemPickContext?.resultsEl) { itemPickContext.resultsEl.replaceChildren(); } itemPickContext = null; } function openInlineItemSearch (inputEl, resultsEl) { itemPickContext = { inputEl, resultsEl }; inputEl.value = ""; renderInlineItemSearch(""); inputEl.focus(); } function renderInlineItemSearch (query) { if (!itemPickContext || !draft) { return; } const { resultsEl } = itemPickContext; resultsEl.replaceChildren(); const q = String(query ?? "").trim().toLowerCase(); const taken = new Set( (draft.rewards ?? []) .filter((row) => row.kind === EffectKind.giveItem) .map((row) => row.itemId) ); const matches = listAllItemPickerEntries().filter((item) => { if (taken.has(item.itemId)) { return false; } if (!q) { return true; } return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q) || String(item.itemId).includes(q); }).slice(0, 40); if (!matches.length) { resultsEl.textContent = "No matching items."; return; } for (const item of matches) { const row = document.createElement("button"); row.type = "button"; row.className = "shop-item-search-row"; const name = document.createElement("span"); name.className = "shop-item-search-row-name"; name.textContent = item.displayName; const key = document.createElement("span"); key.className = "shop-item-search-row-key"; key.textContent = `${item.key} · #${item.itemId}`; row.append(name, key); row.addEventListener("click", () => { if (!Array.isArray(draft.rewards)) { draft.rewards = []; } draft.rewards.push({ kind: EffectKind.giveItem, itemId: item.itemId, quantity: 1, toBank: false }); draft.rewards = normalizeEffects(draft.rewards); closeInlineItemSearch(); renderEditor(); }); resultsEl.append(row); } } function selectQuest (questId) { const found = quests.find((q) => q.questId === questId); if (!found) { draft = null; selectedId = null; render(); return; } selectedId = found.questId; draft = structuredClone(found); render(); } function renderList () { listEl.replaceChildren(); for (const quest of quests) { const btn = document.createElement("button"); btn.type = "button"; btn.textContent = quest.title || quest.questId; if (quest.questId === selectedId) { btn.classList.add("active"); } btn.addEventListener("click", () => selectQuest(quest.questId)); listEl.append(btn); } } function addStep () { draft.steps.push({ stepId: `step-${draft.steps.length + 1}`, title: "New step", description: "", completionJournalText: "", objectives: [{ objectiveId: "obj-1", text: "Complete this step", when: emptyConditionSet() }], onEnter: [], onComplete: [] }); renderEditor(); } function renderEditor () { editorEl.replaceChildren(); saveBtn.disabled = !draft; deleteBtn.disabled = !draft; if (!draft) { const hint = document.createElement("p"); hint.className = "content-editor-hint"; hint.textContent = "Select a quest or create a new one."; editorEl.append(hint); return; } if (!Array.isArray(draft.rewards)) { draft.rewards = []; } editorEl.append( field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })), field("Title", textInput(draft.title, (v) => { draft.title = v; })), field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3)) ); const stepsTitle = document.createElement("div"); stepsTitle.className = "content-editor-section-header"; const stepsStrong = document.createElement("strong"); stepsStrong.textContent = "Steps"; stepsTitle.append(stepsStrong); editorEl.append(stepsTitle); draft.steps.forEach((step, stepIndex) => { const box = document.createElement("div"); box.className = "content-editor-section"; const head = sectionHeader(`Step ${stepIndex + 1}`, null, () => { if (!window.confirm(`Delete quest step "${step.stepId || stepIndex + 1}"?`)) { return; } draft.steps.splice(stepIndex, 1); if (draft.steps.length === 0) { draft.steps.push(normalizeQuestDef({ questId: draft.questId }).steps[0]); } renderEditor(); }); box.append(head); box.append( field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })), field("Title", textInput(step.title, (v) => { step.title = v; })), field("Description", textArea(step.description, (v) => { step.description = v; }, 2)), field("Completion journal", textArea(step.completionJournalText, (v) => { step.completionJournalText = v; }, 2)) ); const objHead = sectionHeader("Objectives", () => { step.objectives.push({ objectiveId: `obj-${step.objectives.length + 1}`, text: "New objective", when: emptyConditionSet() }); renderEditor(); }); box.append(objHead); step.objectives.forEach((obj, objIndex) => { const objBox = document.createElement("div"); objBox.className = "content-editor-section"; objBox.append( sectionHeader(`Objective ${objIndex + 1}`, null, () => { if (!window.confirm(`Delete objective "${obj.text || obj.objectiveId || objIndex + 1}"?`)) { return; } step.objectives.splice(objIndex, 1); if (step.objectives.length === 0) { step.objectives.push({ objectiveId: "obj-1", text: "Complete this step", when: emptyConditionSet() }); } renderEditor(); }), field("Text", textInput(obj.text, (v) => { obj.text = v; })) ); objBox.append(renderConditionSet(obj.when, (next, { remount = true } = {}) => { obj.when = next; if (remount) { renderEditor(); } }, { quests, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions, getSpawnerOptions: (mobTypeId) => { if (typeof getSpawnerOptions === "function") { return getSpawnerOptions(mobTypeId) ?? []; } return serverSpawners.filter((row) => !mobTypeId || String(row.mobTypeId) === String(mobTypeId)); } })); box.append(objBox); }); editorEl.append(box); }); const addStepBtn = document.createElement("button"); addStepBtn.type = "button"; addStepBtn.className = "content-editor-add-step"; addStepBtn.textContent = "(add step)"; addStepBtn.addEventListener("click", addStep); editorEl.append(addStepBtn); renderRewardsSection(); } function renderRewardsSection () { const box = document.createElement("div"); box.className = "content-editor-section"; const title = document.createElement("div"); title.className = "content-editor-section-header"; const strong = document.createElement("strong"); strong.textContent = "Completion rewards"; title.append(strong); box.append(title); const hint = document.createElement("p"); hint.className = "content-editor-hint"; hint.textContent = "Granted when the final step completes. Bank-checked items (or overflow) go to the bank with a Questward letter."; box.append(hint); const xpHead = sectionHeader("Skill XP", () => { const skillId = ALL_SKILL_IDS.find((id) => !(draft.rewards ?? []).some((r) => r.kind === EffectKind.giveXp && r.skillId === id) ) ?? ALL_SKILL_IDS[0]; draft.rewards.push({ kind: EffectKind.giveXp, skillId, amount: 15 }); draft.rewards = normalizeEffects(draft.rewards); renderEditor(); }); box.append(xpHead); const xpRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveXp); if (!xpRows.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No skill XP rewards."; box.append(empty); } xpRows.forEach((reward) => { const rewardIndex = draft.rewards.indexOf(reward); const row = document.createElement("div"); row.className = "content-editor-row"; const skill = document.createElement("select"); for (const skillId of ALL_SKILL_IDS) { const opt = document.createElement("option"); opt.value = skillId; opt.textContent = SKILL_DEFINITIONS[skillId]?.displayName ?? skillId; if (reward.skillId === skillId) { opt.selected = true; } skill.append(opt); } skill.addEventListener("change", () => { draft.rewards[rewardIndex].skillId = skill.value; }); const amount = document.createElement("input"); amount.type = "number"; amount.min = "1"; amount.step = "1"; amount.value = String(Math.max(1, reward.amount | 0 || 1)); amount.title = "XP amount"; amount.addEventListener("input", () => { draft.rewards[rewardIndex].amount = Math.max(1, Number(amount.value) || 1) | 0; }); row.append(skill, amount, removeButton(() => { draft.rewards.splice(rewardIndex, 1); renderEditor(); })); box.append(row); }); const searchWrap = document.createElement("div"); searchWrap.className = "dialogue-reward-item-search"; searchWrap.hidden = true; const searchInput = document.createElement("input"); searchInput.type = "search"; searchInput.placeholder = "Search items…"; searchInput.autocomplete = "off"; searchInput.addEventListener("input", () => renderInlineItemSearch(searchInput.value)); const searchResults = document.createElement("div"); searchResults.className = "dialogue-reward-item-results"; searchWrap.append(searchInput, searchResults); const itemHead = sectionHeader("Items", () => { searchWrap.hidden = false; openInlineItemSearch(searchInput, searchResults); }); box.append(itemHead); const itemRows = (draft.rewards ?? []).filter((r) => r.kind === EffectKind.giveItem); if (!itemRows.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No item rewards."; box.append(empty); } itemRows.forEach((reward) => { const rewardIndex = draft.rewards.indexOf(reward); const def = itemDefinition(reward.itemId); const row = document.createElement("div"); row.className = "spawner-drops-row"; const name = document.createElement("span"); name.className = "spawner-sells-name"; name.textContent = def?.displayName ?? `Item ${reward.itemId}`; const qty = document.createElement("input"); qty.type = "number"; qty.min = "1"; qty.step = "1"; qty.value = String(Math.max(1, reward.quantity | 0 || 1)); qty.title = "Quantity"; qty.addEventListener("input", () => { draft.rewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0; }); const bankLabel = document.createElement("label"); bankLabel.className = "quest-reward-bank"; const bankBox = document.createElement("input"); bankBox.type = "checkbox"; bankBox.checked = !!reward.toBank; bankBox.addEventListener("change", () => { draft.rewards[rewardIndex].toBank = bankBox.checked; }); bankLabel.append(bankBox, document.createTextNode(" Bank")); row.append(name, qty, bankLabel, removeButton(() => { draft.rewards.splice(rewardIndex, 1); renderEditor(); })); box.append(row); }); box.append(searchWrap); editorEl.append(box); } function render () { renderList(); renderEditor(); renderLog(); } function renderLog () { if (!logEl) { return; } logEl.innerHTML = ""; const scopeId = draft?.questId ?? selectedId; const entries = scopeId ? changelog.filter((entry) => entry.questId === scopeId) : changelog; if (!entries.length) { logEl.innerHTML = scopeId ? "

No edits logged for this quest yet.

" : "

No quest edits logged yet.

"; return; } for (const entry of entries) { const item = document.createElement("article"); const who = entry.editorDisplayName || entry.editor_admin_id; const scope = scopeId ? "" : ` · ${entry.questId}`; item.innerHTML = `
${who}${scope} · ${new Date(entry.edited_at).toLocaleString()}
`; const list = document.createElement("ul"); for (const bullet of entry.diffEntries ?? []) { const li = document.createElement("li"); li.textContent = bullet; list.append(li); } item.append(list); logEl.append(item); } logEl.scrollTop = logEl.scrollHeight; } document.getElementById("open-quests").addEventListener("click", () => { socket.send({ type: MessageType.editorLoadQuests }); socket.send({ type: MessageType.editorLoadDialogues }); show(true); render(); }); document.getElementById("quests-close").addEventListener("click", () => show(false)); backdrop.addEventListener("click", () => show(false)); document.getElementById("quests-new").addEventListener("click", () => { const base = normalizeQuestDef({ questId: `quest-${quests.length + 1}`, title: "New quest", description: "" }); draft = structuredClone(base); selectedId = null; render(); }); saveBtn.addEventListener("click", () => { if (!draft) { return; } draft.rewards = normalizeEffects(draft.rewards); socket.send({ type: MessageType.editorSaveQuest, quest: draft }); }); deleteBtn.addEventListener("click", () => { if (!draft?.questId) { return; } if (!window.confirm(`Delete quest "${draft.questId}"?`)) { return; } socket.send({ type: MessageType.editorDeleteQuest, questId: draft.questId }); }); return { isOpen: () => open, getQuests: () => quests, getServerSpawners: () => serverSpawners.slice(), handleMessage (message) { if (message.type === MessageType.editorDialogues) { dialogues = (message.dialogues ?? []).map((d) => normalizeDialogueTree(d)); if (open) { render(); } return; } if (message.type !== MessageType.editorQuests) { return; } quests = (message.quests ?? []).map((q) => normalizeQuestDef(q)); serverSpawners = Array.isArray(message.spawners) ? message.spawners.slice() : []; changelog = message.changelog ?? []; if (draft) { const still = quests.find((q) => q.questId === draft.questId); if (still) { selectedId = still.questId; draft = structuredClone(still); } else if (selectedId) { draft = null; selectedId = null; } } if (open) { render(); } } }; } function removeButton (onClick) { const remove = document.createElement("button"); remove.type = "button"; remove.className = "content-editor-remove"; remove.textContent = "×"; remove.title = "Remove"; remove.addEventListener("click", onClick); return remove; } function field (label, input) { const wrap = document.createElement("label"); wrap.append(document.createTextNode(label), input); return wrap; } function textInput (value, onChange) { const input = document.createElement("input"); input.type = "text"; input.value = value ?? ""; input.addEventListener("input", () => onChange(input.value)); return input; } function textArea (value, onChange, rows = 3) { const input = document.createElement("textarea"); input.rows = rows; input.value = value ?? ""; input.addEventListener("input", () => onChange(input.value)); return input; } function sectionHeader (title, onAdd, onRemove) { const head = document.createElement("div"); head.className = "content-editor-section-header"; const strong = document.createElement("strong"); strong.textContent = title; head.append(strong); const actions = document.createElement("div"); actions.className = "content-editor-row"; if (onAdd) { const add = document.createElement("button"); add.type = "button"; add.textContent = "+"; add.title = "Add"; add.addEventListener("click", onAdd); actions.append(add); } if (onRemove) { actions.append(removeButton(onRemove)); } head.append(actions); return head; }