import { normalizeDialogueTree, normalizeQuestDef } from "/shared/quests/normalize.js"; import { emptyConditionSet } from "/shared/quests/conditions.js"; import { dialogueTakeIsUnguaranteed, unguaranteedDialogueTakes } from "/shared/quests/dialoguePathTakes.js"; import { applyDialogueTextReplacements, dialogueReplacementCatalog } from "/shared/speech/dialogueText.js"; import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js"; import { renderConditionSet } from "./conditionSetEditor.js"; import { initDialogueSimulate } from "./dialogueSimulate.js"; export function initDialoguesModal ({ socket, MessageType, describeWorldTile = null, centerEditorOnTile = null, getDimensionOptions = null }) { 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"); const simulateBtn = document.getElementById("dialogues-simulate"); const tokensBackdrop = document.getElementById("dialogue-tokens-backdrop"); const tokensModal = document.getElementById("dialogue-tokens-modal"); const tokensList = document.getElementById("dialogue-tokens-list"); const tokensPreviewInput = document.getElementById("dialogue-tokens-preview-input"); const tokensPreviewMale = document.getElementById("dialogue-tokens-preview-male"); const tokensPreviewFemale = document.getElementById("dialogue-tokens-preview-female"); let open = false; let tokensHelpOpen = false; /** @type {any[]} */ let dialogues = []; /** @type {ReturnType[]} */ let questCatalog = []; /** @type {any|null} */ let draft = null; let selectedId = null; const simulate = initDialogueSimulate({ getTree: () => (draft ? normalizeDialogueTree(draft) : null), getQuestTitle (questId) { const quest = questCatalog.find((q) => q.questId === questId); return quest?.title || questId; } }); function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { draft = null; selectedId = null; closeInlineItemSearch(); showTokensHelp(false); simulate.close(); } } function showTokensHelp (visible) { tokensHelpOpen = visible; if (tokensBackdrop) { tokensBackdrop.hidden = !visible; } if (tokensModal) { tokensModal.hidden = !visible; } if (visible) { renderTokensHelp(); tokensPreviewInput?.focus(); } } function renderTokensHelp () { if (tokensList) { tokensList.replaceChildren(); for (const entry of dialogueReplacementCatalog()) { const li = document.createElement("li"); const code = document.createElement("code"); code.textContent = entry.token; li.append(code, document.createTextNode(` — ${entry.meaning}`)); tokensList.append(li); } } updateTokensPreview(); } function updateTokensPreview () { const sample = tokensPreviewInput?.value || "Hello [Mr] [playername]. May [he] bring [his] [man]’s courage?"; if (tokensPreviewInput && !tokensPreviewInput.value) { tokensPreviewInput.placeholder = sample; } const text = tokensPreviewInput?.value || sample; const male = applyDialogueTextReplacements(text, { firstName: "Ada", lastName: "Worker", sex: "male" }); const female = applyDialogueTextReplacements(text, { firstName: "Ada", lastName: "Worker", sex: "female" }); if (tokensPreviewMale) { tokensPreviewMale.textContent = male; } if (tokensPreviewFemale) { tokensPreviewFemale.textContent = female; } } /** @type {null | { * step: object, * field: "itemRewards" | "itemTakes", * resultsEl: HTMLElement, * inputEl: HTMLInputElement * }} */ let itemPickContext = null; function closeInlineItemSearch () { if (itemPickContext?.resultsEl) { itemPickContext.resultsEl.replaceChildren(); } itemPickContext = null; } function openInlineItemSearch (step, field, inputEl, resultsEl) { itemPickContext = { step, field, inputEl, resultsEl }; inputEl.value = ""; renderInlineItemSearch(""); inputEl.focus(); } function renderInlineItemSearch (query) { if (!itemPickContext) { return; } const { step, field, resultsEl } = itemPickContext; resultsEl.replaceChildren(); const q = String(query ?? "").trim().toLowerCase(); const taken = new Set((step[field] ?? []).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[field])) { step[field] = []; } step[field].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: [], itemTakes: [], questRewards: [], exit: { kind: "end" } }); renderEditor(); } /** Update yellow take warnings without rebuilding the editor (keeps scroll + focus). */ function refreshDialogueTakeHighlights () { if (!draft || !editorEl) { return; } const warnings = unguaranteedDialogueTakes(draft); for (const row of editorEl.querySelectorAll("[data-take-step-id][data-take-item-id]")) { const stepId = row.getAttribute("data-take-step-id"); const itemId = Number(row.getAttribute("data-take-item-id")); const bad = dialogueTakeIsUnguaranteed(warnings, stepId, itemId); row.classList.toggle("dialogue-item-take-unguaranteed", bad); row.title = bad ? "Not guaranteed by every branch/trigger path to this step." : ""; } } function renderEditor () { editorEl.replaceChildren(); saveBtn.disabled = !draft; deleteBtn.disabled = !draft; if (simulateBtn) { simulateBtn.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); const takeWarnings = unguaranteedDialogueTakes(draft); 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: [], itemTakes: [], questRewards: [], 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, "itemRewards", 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); if (!Array.isArray(step.itemTakes)) { step.itemTakes = []; } const takeSearchWrap = document.createElement("div"); takeSearchWrap.className = "dialogue-reward-item-search"; takeSearchWrap.hidden = true; const takeSearchInput = document.createElement("input"); takeSearchInput.type = "search"; takeSearchInput.placeholder = "Search items…"; takeSearchInput.autocomplete = "off"; takeSearchInput.addEventListener("input", () => renderInlineItemSearch(takeSearchInput.value)); const takeSearchResults = document.createElement("div"); takeSearchResults.className = "dialogue-reward-item-results"; takeSearchWrap.append(takeSearchInput, takeSearchResults); const takesHead = sectionHeader("Item takes", () => { takeSearchWrap.hidden = false; openInlineItemSearch(step, "itemTakes", takeSearchInput, takeSearchResults); }); box.append(takesHead); const takesHint = document.createElement("p"); takesHint.className = "content-editor-hint"; takesHint.textContent = "Removed from the bag after all lines (soft: takes what the player has). Yellow = branch/trigger path does not guarantee the player has them."; box.append(takesHint); if (!step.itemTakes.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No item takes."; box.append(empty); } step.itemTakes.forEach((take, takeIndex) => { const def = itemDefinition(take.itemId); const row = document.createElement("div"); row.className = "spawner-drops-row"; row.setAttribute("data-take-step-id", step.stepId); row.setAttribute("data-take-item-id", String(take.itemId)); if (dialogueTakeIsUnguaranteed(takeWarnings, step.stepId, take.itemId)) { row.classList.add("dialogue-item-take-unguaranteed"); row.title = "Not guaranteed by every branch/trigger path to this step."; } const name = document.createElement("span"); name.className = "spawner-sells-name"; name.textContent = def?.displayName ?? `Item ${take.itemId}`; const qty = document.createElement("input"); qty.type = "number"; qty.min = "1"; qty.step = "1"; qty.value = String(Math.max(1, take.quantity | 0 || 1)); qty.title = "Quantity"; qty.addEventListener("input", () => { step.itemTakes[takeIndex].quantity = Math.max(1, Number(qty.value) || 1) | 0; refreshDialogueTakeHighlights(); }); row.append(name, qty, removeButton(() => { step.itemTakes.splice(takeIndex, 1); renderEditor(); })); box.append(row); }); box.append(takeSearchWrap); if (!Array.isArray(step.questRewards)) { step.questRewards = []; } const questRewardsHead = sectionHeader("Quest rewards", () => { const available = questCatalog.find((q) => !step.questRewards.includes(q.questId)); if (!available) { return; } step.questRewards.push(available.questId); renderEditor(); }); box.append(questRewardsHead); const questHint = document.createElement("p"); questHint.className = "content-editor-hint"; questHint.textContent = "Started after all lines (with item rewards), before triggers/branches."; box.append(questHint); if (!step.questRewards.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No quest rewards."; box.append(empty); } step.questRewards.forEach((questId, rewardIndex) => { const row = document.createElement("div"); row.className = "spawner-drops-row"; const select = document.createElement("select"); const taken = new Set(step.questRewards); const catalog = questCatalog.length ? questCatalog : [{ questId, title: questId }]; for (const quest of catalog) { if (taken.has(quest.questId) && quest.questId !== questId) { continue; } const opt = document.createElement("option"); opt.value = quest.questId; opt.textContent = quest.title ? `${quest.title} (${quest.questId})` : quest.questId; select.append(opt); } if (![...select.options].some((o) => o.value === questId)) { const missing = document.createElement("option"); missing.value = questId; missing.textContent = `${questId} (missing)`; select.append(missing); } select.value = questId; select.addEventListener("change", () => { step.questRewards[rewardIndex] = select.value; renderEditor(); }); row.append(select, removeButton(() => { step.questRewards.splice(rewardIndex, 1); renderEditor(); })); box.append(row); }); 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(renderConditionSet(trig.when, (next, { remount = true } = {}) => { trig.when = next; if (remount) { renderEditor(); } }, conditionCtx())); 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(renderConditionSet(branch.when, (next, { remount = true } = {}) => { branch.when = next; if (remount) { renderEditor(); } }, conditionCtx())); 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 conditionCtx () { return { quests: questCatalog, dialogues, describeWorldTile, centerEditorOnTile, getDimensionOptions }; } function render () { renderList(); renderEditor(); } document.getElementById("open-dialogues").addEventListener("click", () => { socket.send({ type: MessageType.editorLoadDialogues }); socket.send({ type: MessageType.editorLoadQuests }); show(true); render(); }); document.getElementById("dialogues-close").addEventListener("click", () => show(false)); backdrop.addEventListener("click", () => show(false)); document.getElementById("dialogues-tokens-help")?.addEventListener("click", () => { showTokensHelp(true); }); document.getElementById("dialogue-tokens-close")?.addEventListener("click", () => showTokensHelp(false)); tokensBackdrop?.addEventListener("click", () => showTokensHelp(false)); tokensPreviewInput?.addEventListener("input", () => updateTokensPreview()); simulateBtn?.addEventListener("click", () => { if (!draft) { return; } simulate.start(); }); 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 || tokensHelpOpen || simulate.isOpen(), getDialogues: () => dialogues, handleMessage (message) { if (message.type === MessageType.editorQuests) { questCatalog = (message.quests ?? []).map((q) => normalizeQuestDef(q)); if (open) { render(); } return; } 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; }