import { normalizeQuestDef } from "/shared/quests/normalize.js"; import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js"; import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js"; const SIMPLE_KINDS = [ ConditionKind.hasItem, ConditionKind.questState, ConditionKind.dialogueHeard, ConditionKind.killCount, ConditionKind.atTile, ConditionKind.inDimension, ConditionKind.hasVisitedDimension ]; export function initQuestsModal ({ socket, MessageType }) { 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 saveBtn = document.getElementById("quests-save"); const deleteBtn = document.getElementById("quests-delete"); let open = false; /** @type {ReturnType[]} */ let quests = []; /** @type {ReturnType|null} */ let draft = null; let selectedId = null; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { draft = null; selectedId = null; } } 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 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; } 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 stepsHeader = sectionHeader("Steps", () => { 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(); }); editorEl.append(stepsHeader); draft.steps.forEach((step, stepIndex) => { const box = document.createElement("div"); box.className = "content-editor-section"; const head = sectionHeader(`Step ${stepIndex + 1}`, null, () => { 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, () => { 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 })); box.append(objBox); }); editorEl.append(box); }); } function render () { renderList(); renderEditor(); } document.getElementById("open-quests").addEventListener("click", () => { socket.send({ type: MessageType.editorLoadQuests }); 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; } 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, handleMessage (message) { if (message.type !== MessageType.editorQuests) { return; } quests = (message.quests ?? []).map((q) => normalizeQuestDef(q)); 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 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) { const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "×"; remove.title = "Remove"; remove.addEventListener("click", onRemove); actions.append(remove); } head.append(actions); return head; } function renderConditionSet (when, onChange, ctx = {}) { const wrap = document.createElement("div"); const set = normalizeConditionSet(when); const bump = (remount = true) => onChange(set, { remount }); const questList = Array.isArray(ctx.quests) ? ctx.quests : []; const title = document.createElement("strong"); title.textContent = "When (all of)"; wrap.append(title); set.all.forEach((clause, index) => { const row = document.createElement("div"); row.className = "content-editor-clause"; const notLabel = document.createElement("label"); const notBox = document.createElement("input"); notBox.type = "checkbox"; notBox.checked = !!clause.not; notBox.addEventListener("change", () => { set.all[index].not = notBox.checked; bump(false); }); notLabel.append(notBox, document.createTextNode(" NOT")); row.append(notLabel); const kind = document.createElement("select"); for (const k of SIMPLE_KINDS) { const opt = document.createElement("option"); opt.value = k; opt.textContent = k; if ((clause.condition?.kind ?? "") === k) { opt.selected = true; } kind.append(opt); } const otherOpt = document.createElement("option"); otherOpt.value = "__other__"; otherOpt.textContent = "(other / JSON)"; if (!SIMPLE_KINDS.includes(clause.condition?.kind)) { otherOpt.selected = true; } kind.append(otherOpt); kind.addEventListener("change", () => { if (kind.value === "__other__") { return; } set.all[index].condition = defaultCondition(kind.value); bump(true); }); row.append(kind); const cond = clause.condition ?? { kind: ConditionKind.hasItem }; if (cond.kind === ConditionKind.hasItem) { row.append(itemConditionPicker(cond, () => { set.all[index].condition = cond; bump(false); })); row.append(miniField("qty", cond.quantity ?? 1, (v) => { cond.quantity = Number(v) || 1; set.all[index].condition = cond; bump(false); })); } else if (cond.kind === ConditionKind.questState) { row.append(questStateConditionFields(cond, questList, () => { set.all[index].condition = cond; bump(false); })); } else if (cond.kind === ConditionKind.dialogueHeard) { row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) => { cond.dialogueId = v; set.all[index].condition = cond; bump(false); })); row.append(miniField("stepId", cond.stepId ?? "", (v) => { cond.stepId = v; set.all[index].condition = cond; bump(false); })); } else if (cond.kind === ConditionKind.killCount) { row.append(miniField("mobTypeId", cond.mobTypeId ?? "", (v) => { cond.mobTypeId = v || undefined; set.all[index].condition = cond; bump(false); })); row.append(miniField("count", cond.count ?? 1, (v) => { cond.count = Number(v) || 1; set.all[index].condition = cond; bump(false); })); } else if (cond.kind === ConditionKind.atTile) { row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) => { cond.dimensionId = String(v || "overworld"); set.all[index].condition = cond; bump(false); })); row.append(miniField("tileX", cond.tileX ?? 0, (v) => { cond.tileX = Number(v) | 0; set.all[index].condition = cond; bump(false); })); row.append(miniField("tileY", cond.tileY ?? 0, (v) => { cond.tileY = Number(v) | 0; set.all[index].condition = cond; bump(false); })); } else if ( cond.kind === ConditionKind.inDimension || cond.kind === ConditionKind.hasVisitedDimension ) { row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) => { cond.dimensionId = String(v || "overworld"); set.all[index].condition = cond; bump(false); })); } else { const json = document.createElement("textarea"); json.rows = 3; json.value = JSON.stringify(cond, null, 2); json.addEventListener("change", () => { try { set.all[index].condition = JSON.parse(json.value); bump(false); } catch { /* keep typing */ } }); row.append(json); } const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "×"; remove.addEventListener("click", () => { set.all.splice(index, 1); bump(true); }); row.append(remove); wrap.append(row); }); const add = document.createElement("button"); add.type = "button"; add.textContent = "Add clause"; add.addEventListener("click", () => { set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) }); bump(true); }); wrap.append(add); const jsonFallback = document.createElement("details"); const summary = document.createElement("summary"); summary.textContent = "Edit condition set as JSON"; const area = document.createElement("textarea"); area.rows = 5; area.value = JSON.stringify(set, null, 2); area.addEventListener("change", () => { try { onChange(normalizeConditionSet(JSON.parse(area.value)), { remount: true }); } catch { /* ignore */ } }); jsonFallback.append(summary, area); wrap.append(jsonFallback); return wrap; } /** Quest picker + state dropdown from that quest's steps. */ function questStateConditionFields (cond, questList, onChanged) { const wrap = document.createElement("div"); wrap.className = "quest-condition-pair"; const questSelect = document.createElement("select"); const blank = document.createElement("option"); blank.value = ""; blank.textContent = "Select quest…"; questSelect.append(blank); for (const quest of questList) { const opt = document.createElement("option"); opt.value = quest.questId; opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId; if (quest.questId === cond.questId) { opt.selected = true; } questSelect.append(opt); } if (cond.questId && !questList.some((q) => q.questId === cond.questId)) { const missing = document.createElement("option"); missing.value = cond.questId; missing.textContent = `${cond.questId} (missing)`; missing.selected = true; questSelect.append(missing); } const stateSelect = document.createElement("select"); const fillStates = () => { const quest = questList.find((q) => q.questId === cond.questId) ?? null; stateSelect.replaceChildren(); const options = [ { value: "not-started", label: "not-started" }, ...((quest?.steps ?? []).map((step, index) => ({ value: String(index + 1), label: `Step ${index + 1}: ${step.title || step.stepId}` }))), { value: "completed", label: "completed" } ]; let matched = false; for (const entry of options) { const opt = document.createElement("option"); opt.value = entry.value; opt.textContent = entry.label; const current = cond.state ?? "not-started"; const currentKey = current === "not-started" || current === "completed" ? current : String(Number(current) || current); if (entry.value === currentKey) { opt.selected = true; matched = true; } stateSelect.append(opt); } if (!matched) { const fallback = document.createElement("option"); fallback.value = String(cond.state ?? "not-started"); fallback.textContent = String(cond.state ?? "not-started"); fallback.selected = true; stateSelect.append(fallback); } }; fillStates(); questSelect.addEventListener("change", () => { cond.questId = questSelect.value; cond.state = "not-started"; fillStates(); onChanged(); }); stateSelect.addEventListener("change", () => { const raw = stateSelect.value; if (raw === "not-started" || raw === "completed") { cond.state = raw; } else { cond.state = Math.max(1, Number(raw) | 0); } onChanged(); }); wrap.append(questSelect, stateSelect); return wrap; } /** Compact searchable item picker for hasItem conditions. */ function itemConditionPicker (cond, onPicked) { const wrap = document.createElement("div"); wrap.className = "quest-condition-item-picker"; const pickBtn = document.createElement("button"); pickBtn.type = "button"; const refreshLabel = () => { const def = itemDefinition(cond.itemId); pickBtn.textContent = def?.displayName ?? (cond.itemId ? `Item #${cond.itemId}` : "Pick item…"); pickBtn.title = cond.itemId ? `${def?.key ?? "item"} · #${cond.itemId}` : "Choose an item"; }; refreshLabel(); 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"; const searchResults = document.createElement("div"); searchResults.className = "dialogue-reward-item-results"; const renderMatches = (query) => { searchResults.replaceChildren(); const q = String(query ?? "").trim().toLowerCase(); const matches = listAllItemPickerEntries().filter((item) => { 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) { searchResults.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", () => { cond.itemId = item.itemId; refreshLabel(); searchWrap.hidden = true; onPicked(); }); searchResults.append(row); } }; pickBtn.addEventListener("click", () => { searchWrap.hidden = !searchWrap.hidden; if (!searchWrap.hidden) { searchInput.value = ""; renderMatches(""); searchInput.focus(); } }); searchInput.addEventListener("input", () => renderMatches(searchInput.value)); searchWrap.append(searchInput, searchResults); wrap.append(pickBtn, searchWrap); return wrap; } function miniField (label, value, onChange) { const wrap = document.createElement("label"); wrap.textContent = `${label} `; const input = document.createElement("input"); input.type = "text"; input.value = String(value ?? ""); input.style.width = "7rem"; input.addEventListener("input", () => onChange(input.value)); wrap.append(input); return wrap; } function defaultCondition (kind) { switch (kind) { case ConditionKind.hasItem: return { kind, itemId: 1, quantity: 1 }; case ConditionKind.questState: return { kind, questId: "", state: "not-started" }; case ConditionKind.dialogueHeard: return { kind, dialogueId: "", stepId: "" }; case ConditionKind.killCount: return { kind, mobTypeId: "deer", count: 1 }; case ConditionKind.atTile: return { kind, dimensionId: "overworld", tileX: 0, tileY: 0 }; case ConditionKind.inDimension: case ConditionKind.hasVisitedDimension: return { kind, dimensionId: "overworld" }; default: return { kind }; } }