/** * Step detail modal for the dialogue canvas editor. */ import { emptyConditionSet } from "/shared/quests/conditions.js"; import { dialogueTakeIsUnguaranteed, unguaranteedDialogueTakes } from "/shared/quests/dialoguePathTakes.js"; import { itemDefinition, listAllItemPickerEntries } from "/shared/definitions/items.js"; import { renderConditionSet } from "./conditionSetEditor.js"; import { scrubDialogueStepLinks, stepHasEdges } from "./dialogueCanvas.js"; /** * @param {{ * getDraft: () => object | null, * getQuestCatalog: () => object[], * getDialogues: () => object[], * conditionCtx: () => object, * onChange: () => void, * host?: HTMLElement | null * }} options */ export function initDialogueStepModal ({ getDraft, getQuestCatalog, getDialogues, conditionCtx, onChange, host = null }) { const root = document.createElement("div"); root.className = "dialogue-step-overlay"; root.hidden = true; const backdrop = document.createElement("div"); backdrop.className = "dialogue-step-backdrop"; const panel = document.createElement("div"); panel.className = "dialogue-step-panel"; const header = document.createElement("header"); const title = document.createElement("h3"); title.textContent = "Step"; const closeBtn = document.createElement("button"); closeBtn.type = "button"; closeBtn.textContent = "Close"; header.append(title, closeBtn); const body = document.createElement("div"); body.className = "dialogue-step-body"; root.append(backdrop, panel); panel.append(header, body); (host || document.body).append(root); /** @type {string | null} */ let openStepId = null; /** @type {null | { * step: object, * field: "itemRewards" | "itemTakes", * resultsEl: HTMLElement, * inputEl: HTMLInputElement * }} */ let itemPickContext = null; function show (visible) { root.hidden = !visible; if (!visible) { openStepId = null; itemPickContext = null; body.replaceChildren(); } } function currentStep () { const draft = getDraft(); if (!draft || !openStepId) { return null; } return draft.steps.find((s) => s.stepId === openStepId) ?? 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(); onChange(); render(); }); resultsEl.append(row); } } function refreshTakeHighlights () { const draft = getDraft(); if (!draft) { return; } const warnings = unguaranteedDialogueTakes(draft); for (const row of body.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 openSubModal (titleText, build) { const sub = document.createElement("div"); sub.className = "dialogue-step-submodal"; const subPanel = document.createElement("div"); subPanel.className = "dialogue-step-subpanel"; const subHead = document.createElement("header"); const h = document.createElement("h4"); h.textContent = titleText; const done = document.createElement("button"); done.type = "button"; done.textContent = "Done"; subHead.append(h, done); const subBody = document.createElement("div"); subBody.className = "dialogue-step-subbody"; subPanel.append(subHead, subBody); sub.append(subPanel); panel.append(sub); const close = () => sub.remove(); done.addEventListener("click", close); sub.addEventListener("click", (event) => { if (event.target === sub) { close(); } }); build(subBody, close); return close; } function openRewardsUi (step) { openSubModal("Rewards & takes", (subBody) => { if (!Array.isArray(step.itemRewards)) { step.itemRewards = []; } if (!Array.isArray(step.itemTakes)) { step.itemTakes = []; } const rewardsHead = sectionHeader("Item rewards", () => { searchWrap.hidden = false; openInlineItemSearch(step, "itemRewards", searchInput, searchResults); }); subBody.append(rewardsHead); const rewardsHint = document.createElement("p"); rewardsHint.className = "content-editor-hint"; rewardsHint.textContent = "Granted after all lines, before triggers/branches."; subBody.append(rewardsHint); 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 rewardsList = document.createElement("div"); function renderRewards () { rewardsList.replaceChildren(); if (!step.itemRewards.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No item rewards."; rewardsList.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; onChange(); }); row.append(name, qty, removeButton(() => { step.itemRewards.splice(rewardIndex, 1); onChange(); renderRewards(); render(); })); rewardsList.append(row); }); } renderRewards(); subBody.append(rewardsList, searchWrap); const takesHead = sectionHeader("Item takes", () => { takeSearchWrap.hidden = false; openInlineItemSearch(step, "itemTakes", takeSearchInput, takeSearchResults); }); subBody.append(takesHead); const takesHint = document.createElement("p"); takesHint.className = "content-editor-hint"; takesHint.textContent = "Removed from the bag after all lines (soft). Yellow = not guaranteed on every path."; subBody.append(takesHint); 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 takesList = document.createElement("div"); const draft = getDraft(); const takeWarnings = draft ? unguaranteedDialogueTakes(draft) : new Map(); function renderTakes () { takesList.replaceChildren(); if (!step.itemTakes.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No item takes."; takesList.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; onChange(); refreshTakeHighlights(); }); row.append(name, qty, removeButton(() => { step.itemTakes.splice(takeIndex, 1); onChange(); renderTakes(); render(); })); takesList.append(row); }); } renderTakes(); subBody.append(takesList, takeSearchWrap); }); } function openQuestsUi (step) { openSubModal("Quest rewards", (subBody) => { if (!Array.isArray(step.questRewards)) { step.questRewards = []; } const questCatalog = getQuestCatalog(); const head = sectionHeader("Quest rewards", () => { const available = questCatalog.find((q) => !step.questRewards.includes(q.questId)); if (!available) { return; } step.questRewards.push(available.questId); onChange(); renderQuests(); render(); }); subBody.append(head); const hint = document.createElement("p"); hint.className = "content-editor-hint"; hint.textContent = "Started after all lines (with item rewards), before triggers/branches."; subBody.append(hint); const list = document.createElement("div"); function renderQuests () { list.replaceChildren(); if (!step.questRewards.length) { const empty = document.createElement("p"); empty.className = "content-editor-hint"; empty.textContent = "No quest rewards."; list.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; onChange(); render(); }); row.append(select, removeButton(() => { step.questRewards.splice(rewardIndex, 1); onChange(); renderQuests(); render(); })); list.append(row); }); } renderQuests(); subBody.append(list); }); } function openExitConfigure (step) { const kind = step.exit?.kind; if (kind !== "branches" && kind !== "triggers") { return; } openSubModal(kind === "triggers" ? "Configure triggers" : "Configure branches", (subBody) => { const hint = document.createElement("p"); hint.className = "content-editor-hint"; hint.textContent = "Wire next steps on the canvas. Here you edit labels, text, conditions, and effects."; subBody.append(hint); if (kind === "triggers") { if (!Array.isArray(step.exit.triggers)) { step.exit.triggers = []; } const head = sectionHeader("Triggers", () => { step.exit.triggers.push({ trigger: `choice-${step.exit.triggers.length + 1}`, label: `choice-${step.exit.triggers.length + 1}`, text: "Choice", nextStepId: null, when: emptyConditionSet(), effects: [] }); onChange(); renderTriggers(); render(); }); subBody.append(head); const list = document.createElement("div"); function renderTriggers () { list.replaceChildren(); 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); onChange(); renderTriggers(); render(); })); tBox.append( field("trigger", textInput(trig.trigger, (v) => { trig.trigger = v; onChange(); })), field("label", textInput(trig.label ?? "", (v) => { trig.label = v; onChange(); })), field("text (button)", textInput(trig.text, (v) => { trig.text = v; onChange(); })) ); tBox.append(renderConditionSet(trig.when, (next, { remount = true } = {}) => { trig.when = next; onChange(); if (remount) { renderTriggers(); } }, conditionCtx())); list.append(tBox); }); } renderTriggers(); subBody.append(list); return; } if (!Array.isArray(step.exit.branches)) { step.exit.branches = []; } const head = sectionHeader("Branches", () => { step.exit.branches.push({ label: "", when: emptyConditionSet(), nextStepId: null, effects: [] }); onChange(); renderBranches(); render(); }); subBody.append(head); const list = document.createElement("div"); function renderBranches () { list.replaceChildren(); 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); onChange(); renderBranches(); render(); })); bBox.append(field("label", textInput(branch.label ?? "", (v) => { branch.label = v; onChange(); }))); bBox.append(renderConditionSet(branch.when, (next, { remount = true } = {}) => { branch.when = next; onChange(); if (remount) { renderBranches(); } }, conditionCtx())); list.append(bBox); }); } renderBranches(); subBody.append(list); }); } function confirmDeleteStep (step) { const draft = getDraft(); if (!draft) { return; } const linked = stepHasEdges(draft, step); if (!linked) { if (!window.confirm(`Delete dialogue step "${step.label || step.stepId}"?`)) { return; } deleteStep(step); return; } openSubModal("Delete step?", (subBody, close) => { subBody.classList.add("dialogue-step-delete-warn"); const warn = document.createElement("p"); warn.className = "dialogue-step-delete-warn-text"; warn.textContent = `“${step.label || step.stepId}” has incoming or outgoing connections. Deleting it will remove those links.`; const actions = document.createElement("div"); actions.className = "dialogue-step-delete-actions"; const cancel = document.createElement("button"); cancel.type = "button"; cancel.textContent = "Cancel"; cancel.addEventListener("click", close); const confirm = document.createElement("button"); confirm.type = "button"; confirm.className = "dialogue-step-delete-confirm"; confirm.textContent = "Delete step"; confirm.addEventListener("click", () => { close(); deleteStep(step); }); actions.append(cancel, confirm); subBody.append(warn, actions); }); } function deleteStep (step) { const draft = getDraft(); if (!draft) { return; } const index = draft.steps.indexOf(step); if (index < 0) { return; } const removedId = step.stepId; draft.steps.splice(index, 1); scrubDialogueStepLinks(draft, removedId); if (draft.entryStepId === removedId) { draft.entryStepId = draft.steps[0]?.stepId ?? ""; } if (draft.steps.length === 0) { draft.steps.push({ stepId: "greeting", label: "Greeting", lines: [{ speaker: "npc", text: "…", effects: [] }], itemRewards: [], itemTakes: [], questRewards: [], exit: { kind: "end" }, editorX: 80, editorY: 80 }); draft.entryStepId = "greeting"; } show(false); onChange(); } function setExitKind (step, kind) { if (kind === "triggers") { step.exit = { kind: "triggers", triggers: step.exit?.triggers?.length ? step.exit.triggers : [{ trigger: "continue", label: "continue", text: "Continue", nextStepId: null, when: emptyConditionSet(), effects: [] }] }; } else if (kind === "branches") { step.exit = { kind: "branches", branches: step.exit?.branches?.length ? step.exit.branches : [{ label: "", when: emptyConditionSet(), nextStepId: null, effects: [] }] }; } else if (kind === "continue") { const prevNext = step.exit?.kind === "continue" ? step.exit.nextStepId : null; step.exit = { kind: "continue", nextStepId: prevNext ?? null }; } else { step.exit = { kind: "end" }; } } function render () { const step = currentStep(); body.replaceChildren(); if (!step) { show(false); return; } title.textContent = step.label || step.stepId || "Step"; body.append( field("stepId", textInput(step.stepId, (v) => { const draft = getDraft(); const oldId = step.stepId; step.stepId = v; if (draft?.entryStepId === oldId) { draft.entryStepId = v; } scrubRename(draft, oldId, v); openStepId = v; onChange(); })), field("Label", textInput(step.label ?? "", (v) => { step.label = v; title.textContent = v || step.stepId || "Step"; onChange(); })) ); const linesHead = sectionHeader("Lines", () => { step.lines.push({ speaker: "npc", text: "…", effects: [] }); onChange(); render(); }); body.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; onChange(); }); const text = document.createElement("input"); text.type = "text"; text.value = line.text ?? ""; text.style.flex = "1"; text.addEventListener("input", () => { line.text = text.value; onChange(); }); row.append(speaker, text, removeButton(() => { if (!window.confirm("Delete this dialogue line?")) { return; } step.lines.splice(lineIndex, 1); if (step.lines.length === 0) { step.lines.push({ speaker: "npc", text: "…", effects: [] }); } onChange(); render(); })); body.append(row); }); const actions = document.createElement("div"); actions.className = "dialogue-step-actions"; const rewardCount = (step.itemRewards?.length ?? 0) + (step.itemTakes?.length ?? 0); const rewardsBtn = document.createElement("button"); rewardsBtn.type = "button"; rewardsBtn.textContent = rewardCount > 0 ? `Rewards (${rewardCount})` : "Rewards"; rewardsBtn.addEventListener("click", () => openRewardsUi(step)); const questsBtn = document.createElement("button"); questsBtn.type = "button"; questsBtn.textContent = (step.questRewards?.length ?? 0) > 0 ? `Quests (${step.questRewards.length})` : "Quests"; questsBtn.addEventListener("click", () => openQuestsUi(step)); const deleteBtn = document.createElement("button"); deleteBtn.type = "button"; deleteBtn.className = "content-editor-remove"; deleteBtn.textContent = "Delete Step"; deleteBtn.addEventListener("click", () => confirmDeleteStep(step)); actions.append(rewardsBtn, questsBtn, deleteBtn); body.append(actions); const exitKind = document.createElement("select"); for (const k of [ { value: "end", label: "End" }, { value: "branches", label: "Branches" }, { value: "triggers", label: "Triggers" }, { value: "continue", label: "Continue" } ]) { const opt = document.createElement("option"); opt.value = k.value; opt.textContent = k.label; if ((step.exit?.kind ?? "end") === k.value) { opt.selected = true; } exitKind.append(opt); } exitKind.addEventListener("change", () => { setExitKind(step, exitKind.value); onChange(); render(); }); body.append(field("Exit", exitKind)); const configure = document.createElement("button"); configure.type = "button"; configure.textContent = "Configure"; const canConfigure = step.exit?.kind === "branches" || step.exit?.kind === "triggers"; configure.disabled = !canConfigure; configure.addEventListener("click", () => openExitConfigure(step)); body.append(configure); if (step.exit?.kind === "continue") { const note = document.createElement("p"); note.className = "content-editor-hint"; note.textContent = "Continue uses a single outgoing port on the canvas."; body.append(note); } } function scrubRename (draft, oldId, newId) { if (!draft || !oldId || oldId === newId) { return; } for (const other of draft.steps) { const exit = other.exit; if (!exit) { continue; } if (exit.kind === "continue" && exit.nextStepId === oldId) { exit.nextStepId = newId; } if (exit.kind === "triggers") { for (const trig of exit.triggers ?? []) { if (trig.nextStepId === oldId) { trig.nextStepId = newId; } } } if (exit.kind === "branches") { for (const branch of exit.branches ?? []) { if (branch.nextStepId === oldId) { branch.nextStepId = newId; } } } } } closeBtn.addEventListener("click", () => show(false)); backdrop.addEventListener("click", () => show(false)); return { open (stepId) { openStepId = stepId; show(true); render(); }, close: () => show(false), isOpen: () => !!openStepId && !root.hidden, refresh () { if (openStepId) { render(); } }, el: root }; } 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; }