import { normalizeDialogueTree } from "/shared/quests/normalize.js"; import { emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js"; import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js"; export function initDialoguesModal ({ socket, MessageType }) { const backdrop = document.getElementById("dialogues-backdrop"); const modal = document.getElementById("dialogues-modal"); const listEl = document.getElementById("dialogues-list"); const editorEl = document.getElementById("dialogues-editor"); const saveBtn = document.getElementById("dialogues-save"); const deleteBtn = document.getElementById("dialogues-delete"); let open = false; /** @type {any[]} */ let dialogues = []; /** @type {any|null} */ let draft = null; let selectedId = null; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { draft = null; selectedId = null; closeInlineItemSearch(); } } /** @type {null | { step: object, resultsEl: HTMLElement, inputEl: HTMLInputElement }} */ let itemPickContext = null; function closeInlineItemSearch () { if (itemPickContext?.resultsEl) { itemPickContext.resultsEl.replaceChildren(); } itemPickContext = null; } function openInlineItemSearch (step, inputEl, resultsEl) { itemPickContext = { step, inputEl, resultsEl }; inputEl.value = ""; renderInlineItemSearch(""); inputEl.focus(); } function renderInlineItemSearch (query) { if (!itemPickContext) { return; } const { step, resultsEl } = itemPickContext; resultsEl.replaceChildren(); const q = String(query ?? "").trim().toLowerCase(); const taken = new Set((step.itemRewards ?? []).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(step.itemRewards)) { step.itemRewards = []; } step.itemRewards.push({ itemId: item.itemId, quantity: 1 }); closeInlineItemSearch(); renderEditor(); }); resultsEl.append(row); } } function selectDialogue (dialogueId) { const found = dialogues.find((d) => d.dialogueId === dialogueId); if (!found) { draft = null; selectedId = null; render(); return; } selectedId = found.dialogueId; draft = structuredClone(found); render(); } function renderList () { listEl.replaceChildren(); for (const tree of dialogues) { const btn = document.createElement("button"); btn.type = "button"; const unique = tree.unique ? " · unique" : ""; const assigned = tree.assignedSpawnerCount != null ? ` (${tree.assignedSpawnerCount})` : ""; btn.textContent = `${tree.label || tree.dialogueId}${unique}${assigned}`; if (tree.dialogueId === selectedId) { btn.classList.add("active"); } btn.addEventListener("click", () => selectDialogue(tree.dialogueId)); listEl.append(btn); } } function addStep () { draft.steps.push({ stepId: `step-${draft.steps.length + 1}`, lines: [{ speaker: "npc", text: "…", effects: [] }], itemRewards: [], exit: { kind: "end" } }); 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 dialogue or create a new one."; editorEl.append(hint); return; } editorEl.append( field("Dialogue id", textInput(draft.dialogueId, (v) => { draft.dialogueId = v; })), field("Label", textInput(draft.label, (v) => { draft.label = v; })) ); const uniqueLabel = document.createElement("label"); const uniqueBox = document.createElement("input"); uniqueBox.type = "checkbox"; uniqueBox.checked = !!draft.unique; uniqueBox.addEventListener("change", () => { draft.unique = uniqueBox.checked; }); uniqueLabel.append(uniqueBox, document.createTextNode(" Unique (at most one spawner)")); editorEl.append(uniqueLabel); const assigned = document.createElement("p"); assigned.className = "content-editor-hint"; assigned.textContent = `Assigned spawners: ${draft.assignedSpawnerCount ?? 0}`; editorEl.append(assigned); editorEl.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) => { draft.entryStepId = v; }))); 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"; box.append(sectionHeader(`Step ${stepIndex + 1}`, null, () => { draft.steps.splice(stepIndex, 1); if (draft.steps.length === 0) { draft.steps.push({ stepId: "greeting", lines: [{ speaker: "npc", text: "…", effects: [] }], itemRewards: [], exit: { kind: "end" } }); } renderEditor(); })); box.append(field("stepId", textInput(step.stepId, (v) => { step.stepId = v; }))); const linesHead = sectionHeader("Lines", () => { step.lines.push({ speaker: "npc", text: "…", effects: [] }); renderEditor(); }); box.append(linesHead); step.lines.forEach((line, lineIndex) => { const row = document.createElement("div"); row.className = "content-editor-row"; const speaker = document.createElement("select"); for (const s of ["npc", "player"]) { const opt = document.createElement("option"); opt.value = s; opt.textContent = s; if (line.speaker === s) { opt.selected = true; } speaker.append(opt); } speaker.addEventListener("change", () => { line.speaker = speaker.value; }); const text = document.createElement("input"); text.type = "text"; text.value = line.text ?? ""; text.style.flex = "1"; text.addEventListener("input", () => { line.text = text.value; }); row.append(speaker, text, removeButton(() => { step.lines.splice(lineIndex, 1); if (step.lines.length === 0) { step.lines.push({ speaker: "npc", text: "…", effects: [] }); } renderEditor(); })); box.append(row); }); if (!Array.isArray(step.itemRewards)) { step.itemRewards = []; } 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 rewardsHead = sectionHeader("Item rewards", () => { searchWrap.hidden = false; openInlineItemSearch(step, searchInput, searchResults); }); box.append(rewardsHead); const rewardsHint = document.createElement("p"); rewardsHint.className = "content-editor-hint"; rewardsHint.textContent = "Granted after all lines, before triggers/branches."; box.append(rewardsHint); if (!step.itemRewards.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No item rewards."; box.append(empty); } step.itemRewards.forEach((reward, rewardIndex) => { 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", () => { step.itemRewards[rewardIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0; }); row.append(name, qty, removeButton(() => { step.itemRewards.splice(rewardIndex, 1); renderEditor(); })); box.append(row); }); box.append(searchWrap); const exitKind = document.createElement("select"); for (const k of ["end", "triggers", "branches"]) { const opt = document.createElement("option"); opt.value = k; opt.textContent = k; if ((step.exit?.kind ?? "end") === k) { opt.selected = true; } exitKind.append(opt); } exitKind.addEventListener("change", () => { if (exitKind.value === "triggers") { step.exit = { kind: "triggers", triggers: step.exit?.triggers?.length ? step.exit.triggers : [{ trigger: "continue", text: "Continue", nextStepId: null, when: emptyConditionSet(), effects: [] }] }; } else if (exitKind.value === "branches") { step.exit = { kind: "branches", branches: step.exit?.branches?.length ? step.exit.branches : [{ when: emptyConditionSet(), nextStepId: null, effects: [] }] }; } else { step.exit = { kind: "end" }; } renderEditor(); }); box.append(field("Exit kind", exitKind)); if (step.exit?.kind === "triggers") { const trigHead = sectionHeader("Triggers", () => { step.exit.triggers.push({ trigger: `choice-${step.exit.triggers.length + 1}`, text: "Choice", nextStepId: null, when: emptyConditionSet(), effects: [] }); renderEditor(); }); box.append(trigHead); step.exit.triggers.forEach((trig, trigIndex) => { const tBox = document.createElement("div"); tBox.className = "content-editor-section"; tBox.append(sectionHeader(`Trigger ${trigIndex + 1}`, null, () => { step.exit.triggers.splice(trigIndex, 1); renderEditor(); })); tBox.append( field("trigger", textInput(trig.trigger, (v) => { trig.trigger = v; })), field("text (button)", textInput(trig.text, (v) => { trig.text = v; })), field("nextStepId (blank=end)", textInput(trig.nextStepId ?? "", (v) => { trig.nextStepId = v.trim() || null; })) ); tBox.append(whenJson(trig.when, (next) => { trig.when = next; })); box.append(tBox); }); } else if (step.exit?.kind === "branches") { const branchHead = sectionHeader("Branches", () => { step.exit.branches.push({ when: emptyConditionSet(), nextStepId: null, effects: [] }); renderEditor(); }); box.append(branchHead); step.exit.branches.forEach((branch, branchIndex) => { const bBox = document.createElement("div"); bBox.className = "content-editor-section"; bBox.append(sectionHeader(`Branch ${branchIndex + 1}`, null, () => { step.exit.branches.splice(branchIndex, 1); renderEditor(); })); bBox.append( field("nextStepId (blank=end)", textInput(branch.nextStepId ?? "", (v) => { branch.nextStepId = v.trim() || null; })) ); bBox.append(whenJson(branch.when, (next) => { branch.when = next; })); box.append(bBox); }); } 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); } function render () { renderList(); renderEditor(); } document.getElementById("open-dialogues").addEventListener("click", () => { socket.send({ type: MessageType.editorLoadDialogues }); show(true); render(); }); document.getElementById("dialogues-close").addEventListener("click", () => show(false)); backdrop.addEventListener("click", () => show(false)); document.getElementById("dialogues-new").addEventListener("click", () => { const base = normalizeDialogueTree({ dialogueId: `dialogue-${dialogues.length + 1}`, label: "New dialogue", unique: false }); draft = { ...structuredClone(base), assignedSpawnerCount: 0 }; selectedId = null; render(); }); saveBtn.addEventListener("click", () => { if (!draft) { return; } socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft }); }); deleteBtn.addEventListener("click", () => { if (!draft?.dialogueId) { return; } if (!window.confirm(`Delete dialogue "${draft.dialogueId}"?`)) { return; } socket.send({ type: MessageType.editorDeleteDialogue, dialogueId: draft.dialogueId }); }); return { isOpen: () => open, getDialogues: () => dialogues, handleMessage (message) { if (message.type !== MessageType.editorDialogues) { return; } dialogues = (message.dialogues ?? []).map((d) => { const tree = normalizeDialogueTree(d); return { ...tree, assignedSpawnerCount: d.assignedSpawnerCount ?? 0 }; }); if (draft) { const still = dialogues.find((d) => d.dialogueId === draft.dialogueId); if (still) { selectedId = still.dialogueId; 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 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 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; } function whenJson (when, onChange) { const details = document.createElement("details"); const summary = document.createElement("summary"); summary.textContent = "when (condition JSON)"; const area = document.createElement("textarea"); area.rows = 4; area.value = JSON.stringify(normalizeConditionSet(when), null, 2); area.addEventListener("change", () => { try { onChange(normalizeConditionSet(JSON.parse(area.value))); } catch { /* ignore invalid */ } }); details.append(summary, area); return details; }