/** * Right-click config modal for editor tiles that have configurable data (spawners, doorways). */ import { listSpawnableMobTypes, normalizeSpawnerConfig, MobId, isHumanoidMob, isCentralExchangeSpawner, spawnerEquipmentSlot } from "/shared/definitions/mobs.js"; import { mobSpellCastChancePercent } from "/shared/definitions/mobCombat.js"; import { SPELL_DEFINITIONS } from "/shared/definitions/spells.js"; import { centralExchangeStaffCount } from "/shared/market/exchange.js"; import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/definitions/items.js"; import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js"; import { listNpcShopSellableItems } from "/shared/shop/pricing.js"; import { normalizeRgb } from "/shared/render/tint.js"; import { createDimensionCombobox } from "./dimensionCombobox.js"; import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js"; const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]); /** Items that can be worn in a given equipment slot. */ export function listEquippableItemsForSlot (slot) { const out = []; for (const def of Object.values(ITEM_DEFINITIONS)) { if (!def?.equipment || def.equipment.slot !== slot) { continue; } out.push({ itemId: def.itemId, key: def.key ?? String(def.itemId), displayName: def.displayName ?? `Item ${def.itemId}` }); } out.sort((a, b) => a.displayName.localeCompare(b.displayName)); return out; } function emptyEquipDraft () { return { itemId: null, dyeColor: null }; } function equipDraftFromConfig (raw) { const { itemId, dyeColor } = spawnerEquipmentSlot(raw); return { itemId: itemId > 0 ? itemId : null, dyeColor: dyeColor ? normalizeRgb(dyeColor) : null }; } function equipConfigFromDraft (draft) { const itemId = draft?.itemId; if (itemId == null || itemId === "") { return null; } const id = Number(itemId) || null; if (!id) { return null; } if (draft.dyeColor && isDyeableClothing(id)) { return { itemId: id, dyeColor: normalizeRgb(draft.dyeColor) }; } return id; } function rgbToCss (color) { const c = normalizeRgb(color, { r: 0.78, g: 0.31, b: 0.47 }); return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`; } export function initTileConfigModal ({ onSave, onRemove, socket, MessageType, getDialogues, getDimensionOptions }) { const backdrop = document.getElementById("tile-config-backdrop"); const modal = document.getElementById("tile-config-modal"); const form = document.getElementById("tile-config-form"); const title = document.getElementById("tile-config-title"); const itemSearchBackdrop = document.getElementById("shop-item-search-backdrop"); const itemSearchModal = document.getElementById("shop-item-search-modal"); const itemSearchTitle = itemSearchModal?.querySelector("h2") ?? null; const itemSearchInput = document.getElementById("shop-item-search-input"); const itemSearchResults = document.getElementById("shop-item-search-results"); const dyeBackdrop = document.getElementById("equip-dye-backdrop"); const dyeModal = document.getElementById("equip-dye-modal"); const dyeTitle = document.getElementById("equip-dye-title"); const dyePreview = document.getElementById("equip-dye-preview"); const dyeR = document.getElementById("equip-dye-r"); const dyeG = document.getElementById("equip-dye-g"); const dyeB = document.getElementById("equip-dye-b"); const dyeRNum = document.getElementById("equip-dye-r-num"); const dyeGNum = document.getElementById("equip-dye-g-num"); const dyeBNum = document.getElementById("equip-dye-b-num"); let open = false; let context = null; /** @type {{ itemId: number, quantity: number }[]} */ let sellsDraft = []; /** @type {{ spellId: string, chance: number }[]} */ let spellsDraft = []; /** @type {Record} */ let equipmentDraft = {}; /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | { kind: "spells" } | null} */ let itemSearchMode = null; /** @type {string|null} */ let dyeEditSlot = null; /** @type {{ dialogueId: string, label: string, unique?: boolean }[]} */ let dialogueOptions = []; let pendingDialogueId = null; /** @type {ReturnType|null} */ let doorwayDimCombo = null; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { context = null; doorwayDimCombo = null; closeItemSearch(); closeDyePicker(); } } function closeItemSearch () { itemSearchMode = null; if (itemSearchBackdrop) { itemSearchBackdrop.hidden = true; } if (itemSearchModal) { itemSearchModal.hidden = true; } } function openSellItemSearch () { itemSearchMode = { kind: "sells" }; openItemSearch("Add shop stock"); } function openEquipItemSearch (slot) { itemSearchMode = { kind: "equip", slot }; openItemSearch(`Equip ${slot}`); } function openItemSearch (heading) { if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput) { return; } if (itemSearchTitle) { itemSearchTitle.textContent = heading ?? "Choose item"; } itemSearchInput.value = ""; itemSearchInput.placeholder = itemSearchMode?.kind === "equip" ? "Search equipment…" : "Search items…"; renderItemSearchResults(""); itemSearchBackdrop.hidden = false; itemSearchModal.hidden = false; itemSearchInput.focus(); } function candidateItems () { if (itemSearchMode?.kind === "equip") { return listEquippableItemsForSlot(itemSearchMode.slot); } return listNpcShopSellableItems(); } function renderItemSearchResults (query) { if (!itemSearchResults) { return; } itemSearchResults.innerHTML = ""; const q = String(query ?? "").trim().toLowerCase(); const taken = itemSearchMode?.kind === "sells" ? new Set(sellsDraft.map((line) => line.itemId)) : null; const matches = candidateItems().filter((item) => { if (taken?.has(item.itemId)) { return false; } if (!q) { return true; } return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q); }).slice(0, 120); if (!matches.length) { itemSearchResults.textContent = "No matching items."; return; } for (const item of matches) { const row = document.createElement("button"); row.type = "button"; row.className = "shop-item-search-row"; row.textContent = item.displayName; row.addEventListener("click", () => { if (itemSearchMode?.kind === "equip") { equipmentDraft[itemSearchMode.slot] = { itemId: item.itemId, dyeColor: null }; renderEquipmentRows(); } else { sellsDraft.push({ itemId: item.itemId, quantity: 0 }); renderSellsList(); } closeItemSearch(); }); itemSearchResults.append(row); } } function closeDyePicker () { dyeEditSlot = null; if (dyeBackdrop) { dyeBackdrop.hidden = true; } if (dyeModal) { dyeModal.hidden = true; } } function readDyeSliders () { return { r: Math.min(255, Math.max(0, Number(dyeR?.value) || 0)) / 255, g: Math.min(255, Math.max(0, Number(dyeG?.value) || 0)) / 255, b: Math.min(255, Math.max(0, Number(dyeB?.value) || 0)) / 255 }; } function syncDyePreview () { const color = readDyeSliders(); if (dyePreview) { dyePreview.style.background = rgbToCss(color); } if (dyeRNum) { dyeRNum.value = String(Math.round(color.r * 255)); } if (dyeGNum) { dyeGNum.value = String(Math.round(color.g * 255)); } if (dyeBNum) { dyeBNum.value = String(Math.round(color.b * 255)); } } function setDyeSliders (color) { const c = normalizeRgb(color, { r: 200 / 255, g: 80 / 255, b: 120 / 255 }); const r = Math.round(c.r * 255); const g = Math.round(c.g * 255); const b = Math.round(c.b * 255); if (dyeR) { dyeR.value = String(r); } if (dyeG) { dyeG.value = String(g); } if (dyeB) { dyeB.value = String(b); } syncDyePreview(); } function openDyePicker (slot) { const draft = equipmentDraft[slot]; if (!draft?.itemId || !isDyeableClothing(draft.itemId) || !dyeModal || !dyeBackdrop) { return; } dyeEditSlot = slot; const def = itemDefinition(draft.itemId); if (dyeTitle) { dyeTitle.textContent = `Dye — ${def?.displayName ?? slot}`; } setDyeSliders(draft.dyeColor ?? { r: 200 / 255, g: 80 / 255, b: 120 / 255 }); dyeBackdrop.hidden = false; dyeModal.hidden = false; } function bindDyeChannel (range, num) { range?.addEventListener("input", () => { if (num) { num.value = range.value; } syncDyePreview(); }); num?.addEventListener("input", () => { const v = Math.min(255, Math.max(0, Number(num.value) || 0)); num.value = String(v); if (range) { range.value = String(v); } syncDyePreview(); }); } bindDyeChannel(dyeR, dyeRNum); bindDyeChannel(dyeG, dyeGNum); bindDyeChannel(dyeB, dyeBNum); function renderSellsList () { const list = form.querySelector("[data-sells-list]"); if (!list) { return; } list.innerHTML = ""; if (!sellsDraft.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No items yet. Use + to add stock."; list.append(empty); return; } for (let index = 0; index < sellsDraft.length; index++) { const line = sellsDraft[index]; const def = itemDefinition(line.itemId); const row = document.createElement("div"); row.className = "spawner-sells-row"; const name = document.createElement("span"); name.className = "spawner-sells-name"; name.textContent = def?.displayName ?? `Item ${line.itemId}`; const qty = document.createElement("input"); qty.type = "number"; qty.min = "0"; qty.step = "1"; qty.value = String(line.quantity | 0); qty.title = "0 = infinite; otherwise restocks this many at 00:00 server time"; qty.addEventListener("input", () => { sellsDraft[index].quantity = Math.max(0, Number(qty.value) || 0) | 0; }); const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Remove"; remove.addEventListener("click", () => { sellsDraft.splice(index, 1); renderSellsList(); }); row.append(name, qty, remove); list.append(row); } } function renderEquipmentRows () { const list = form.querySelector("[data-equipment-list]"); if (!list) { return; } list.innerHTML = ""; for (const slot of EQUIPMENT_SLOTS) { const draft = equipmentDraft[slot] ?? emptyEquipDraft(); const itemId = draft.itemId ?? null; const def = itemId ? itemDefinition(itemId) : null; const dyeable = itemId != null && isDyeableClothing(itemId); const row = document.createElement("div"); row.className = "spawner-equip-row"; const label = document.createElement("span"); label.className = "spawner-equip-slot"; label.textContent = slot; const name = document.createElement("span"); name.className = "spawner-equip-name"; if (def && draft.dyeColor) { const swatch = document.createElement("span"); swatch.className = "spawner-equip-dye-swatch"; swatch.style.background = rgbToCss(draft.dyeColor); name.append(swatch, document.createTextNode(def.displayName)); } else { name.textContent = def?.displayName ?? "(none)"; } const pick = document.createElement("button"); pick.type = "button"; pick.textContent = "Choose…"; pick.addEventListener("click", () => openEquipItemSearch(slot)); const dyeBtn = document.createElement("button"); dyeBtn.type = "button"; dyeBtn.textContent = "Dye…"; dyeBtn.disabled = !dyeable; dyeBtn.title = dyeable ? "Set clothing dye colour" : "Only tailor clothing can be dyed"; dyeBtn.addEventListener("click", () => openDyePicker(slot)); const clear = document.createElement("button"); clear.type = "button"; clear.textContent = "Clear"; clear.disabled = itemId == null; clear.addEventListener("click", () => { equipmentDraft[slot] = emptyEquipDraft(); renderEquipmentRows(); }); row.append(label, name, pick, dyeBtn, clear); list.append(row); } } function renderHumanoidFields (config) { const wrap = document.createElement("div"); wrap.className = "spawner-humanoid-fields"; wrap.dataset.humanoid = "1"; const exchange = isCentralExchangeSpawner(config); if (exchange) { const note = document.createElement("p"); note.className = "hint"; note.textContent = `Spawns all ${centralExchangeStaffCount()} Central Exchange clerks (names & sex fixed). Equipment below is shared. No shop interaction.`; wrap.append(note); } else { wrap.append( field("Display name", textInput("displayName", config.displayName || "Shopkeeper")), field("Sex", sexSelect("sex", config.sex)) ); } const aggressiveLabel = document.createElement("label"); aggressiveLabel.className = "spawner-buys-row"; const aggressive = document.createElement("input"); aggressive.type = "checkbox"; aggressive.name = "aggressive"; aggressive.checked = !!config.aggressive; aggressive.addEventListener("change", () => syncBountyForAggressive()); aggressiveLabel.append(aggressive, document.createTextNode(" Aggressive (attacks players in range)")); wrap.append(aggressiveLabel); const aggressiveHint = document.createElement("p"); aggressiveHint.className = "hint"; aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0."; wrap.append(aggressiveHint); wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions))); const equipHeader = document.createElement("div"); equipHeader.className = "spawner-sells-header"; const equipTitle = document.createElement("strong"); equipTitle.textContent = "Equipment"; equipHeader.append(equipTitle); wrap.append(equipHeader); const equipList = document.createElement("div"); equipList.className = "spawner-equip-list"; equipList.dataset.equipmentList = "1"; wrap.append(equipList); equipmentDraft = {}; for (const slot of EQUIPMENT_SLOTS) { equipmentDraft[slot] = equipDraftFromConfig(config.equipment?.[slot]); } queueMicrotask(() => renderEquipmentRows()); if (!exchange) { wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01))); const sellsHeader = document.createElement("div"); sellsHeader.className = "spawner-sells-header"; const sellsTitle = document.createElement("strong"); sellsTitle.textContent = "Sells"; const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.textContent = "+"; addBtn.title = "Add item"; addBtn.addEventListener("click", () => openSellItemSearch()); sellsHeader.append(sellsTitle, addBtn); wrap.append(sellsHeader); const list = document.createElement("div"); list.className = "spawner-sells-list"; list.dataset.sellsList = "1"; wrap.append(list); const buysLabel = document.createElement("label"); buysLabel.className = "spawner-buys-row"; const buys = document.createElement("input"); buys.type = "checkbox"; buys.name = "buysItems"; buys.checked = !!config.buysItems; buysLabel.append(buys, document.createTextNode(" Buys items")); wrap.append(buysLabel); const hint = document.createElement("p"); hint.className = "hint"; hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock."; wrap.append(hint); sellsDraft = (config.sells ?? []).map((line) => { if (line && typeof line === "object") { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; } return { itemId: line | 0, quantity: 0 }; }).filter((line) => line.itemId > 0); queueMicrotask(() => renderSellsList()); } else { sellsDraft = []; } return wrap; } function syncHumanoidSection (config) { form.querySelector("[data-humanoid]")?.remove(); const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value; if (!isHumanoidMob(mobTypeId)) { sellsDraft = []; equipmentDraft = {}; return; } form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({ mobTypeId: mobTypeId || MobId.humanoid }, "spawner"))); const maxAlive = form.querySelector('[name="maxAlive"]'); if (maxAlive && isCentralExchangeSpawner({ mobTypeId })) { maxAlive.value = String(centralExchangeStaffCount()); maxAlive.disabled = true; } else if (maxAlive) { maxAlive.disabled = false; } } function syncSpellsSection (config) { form.querySelector("[data-spells]")?.remove(); form.append(renderSpellsFields(config)); } function renderSpellsFields (config) { const wrap = document.createElement("div"); wrap.className = "spawner-spells-fields"; wrap.dataset.spells = "1"; const header = document.createElement("div"); header.className = "spawner-sells-header"; const titleEl = document.createElement("strong"); titleEl.textContent = "Spells"; const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.textContent = "+"; addBtn.title = "Add spell"; addBtn.addEventListener("click", () => { const available = Object.values(SPELL_DEFINITIONS).find((def) => !spellsDraft.some((line) => line.spellId === def.spellId)); if (!available) { return; } spellsDraft.push({ spellId: available.spellId }); renderSpellsList(); }); header.append(titleEl, addBtn); wrap.append(header); const list = document.createElement("div"); list.className = "spawner-sells-list"; list.dataset.spellsList = "1"; wrap.append(list); const hint = document.createElement("p"); hint.className = "hint"; hint.textContent = "Cast chance is derived from the mob Level (shown as a label). Only Attack (entity) spells are used in combat. Mobs only learn spells their Level can cast."; wrap.append(hint); if (!Array.isArray(spellsDraft) || !spellsDraft.length) { spellsDraft = (config?.spells ?? []).map((line) => ({ spellId: String(line.spellId ?? "") })).filter((line) => line.spellId); } queueMicrotask(() => renderSpellsList()); return wrap; } function renderSpellsList () { const list = form.querySelector("[data-spells-list]"); if (!list) { return; } list.replaceChildren(); if (!spellsDraft.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No spells."; list.append(empty); return; } const level = Math.max(1, Number(form.querySelector('[name="level"]')?.value) || 1) | 0; const castChance = mobSpellCastChancePercent(level); for (let index = 0; index < spellsDraft.length; index++) { const line = spellsDraft[index]; const def = SPELL_DEFINITIONS[line.spellId]; const row = document.createElement("div"); row.className = "spawner-sell-row"; const select = document.createElement("select"); for (const spell of Object.values(SPELL_DEFINITIONS)) { const opt = document.createElement("option"); opt.value = spell.spellId; const minLv = spell.minMagicLevel | 0 || 1; opt.textContent = `${spell.displayName} (Magic ${minLv}+)`; if (spell.spellId === line.spellId) { opt.selected = true; } select.append(opt); } select.addEventListener("change", () => { spellsDraft[index].spellId = select.value; renderSpellsList(); }); const minLv = def?.minMagicLevel | 0 || 1; const chanceLabel = document.createElement("span"); chanceLabel.className = "hint"; chanceLabel.title = "Cast chance from mob Level"; chanceLabel.textContent = level < minLv ? `needs Lv.${minLv}` : `cast ${castChance}%`; const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "×"; remove.addEventListener("click", () => { spellsDraft.splice(index, 1); renderSpellsList(); }); row.append(select, chanceLabel, remove); list.append(row); } } function syncBountyForAggressive () { const bountyInput = form.querySelector('[name="bounty"]'); const aggressiveInput = form.querySelector('[name="aggressive"]'); if (!bountyInput) { return; } const aggressive = !!aggressiveInput?.checked; if (aggressive) { bountyInput.value = "0"; bountyInput.disabled = true; } else { bountyInput.disabled = false; } } function openSpawner (ctx) { context = { kind: "spawner", ...ctx }; const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId); pendingDialogueId = config.dialogueId ?? null; dialogueOptions = typeof getDialogues === "function" ? (getDialogues() ?? []) : dialogueOptions; if (socket && MessageType) { socket.send({ type: MessageType.editorLoadDialogues }); } title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`; form.innerHTML = ""; const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId)); form.append( mobField, field("Level", numberInput("level", config.level ?? 1, 1, 99)), field("Bounty", numberInput("bounty", config.bounty ?? 0, 0, 1_000_000)), field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)), field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)), field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)), field("Spawner id", textInput("spawnerId", config.spawnerId, true)) ); const spawnInput = form.querySelector('[name="spawnRangeTiles"]'); const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]'); const syncWanderMin = () => { const spawn = Number(spawnInput.value) || 1; wanderInput.min = String(spawn); if (Number(wanderInput.value) < spawn) { wanderInput.value = String(spawn); } }; spawnInput.addEventListener("input", syncWanderMin); syncWanderMin(); form.querySelector('[name="level"]')?.addEventListener("input", () => renderSpellsList()); form.querySelector('[name="mobTypeId"]').addEventListener("change", () => { const nextType = form.querySelector('[name="mobTypeId"]').value; const defaults = normalizeSpawnerConfig({ mobTypeId: nextType }, config.spawnerId); form.querySelector('[name="maxAlive"]').value = String(defaults.maxAlive); form.querySelector('[name="spawnRangeTiles"]').value = String(defaults.spawnRangeTiles); form.querySelector('[name="maxWanderRangeTiles"]').value = String(defaults.maxWanderRangeTiles); form.querySelector('[name="level"]').value = String(defaults.level ?? 1); form.querySelector('[name="bounty"]').value = String(defaults.bounty ?? 0); syncWanderMin(); syncHumanoidSection(defaults); syncSpellsSection(defaults); syncBountyForAggressive(); }); spellsDraft = (config.spells ?? []).map((line) => ({ spellId: String(line.spellId ?? "") })).filter((line) => line.spellId); syncHumanoidSection(config); syncSpellsSection(config); syncBountyForAggressive(); show(true); } function openDoorway (ctx) { context = { kind: "doorway", ...ctx }; const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {}; const state = DOORWAY_STATES.includes(ctx.state) ? ctx.state : "door"; title.textContent = `Doorway · ${ctx.tileX}, ${ctx.tileY}`; form.innerHTML = ""; form.append( field("Appearance", doorwayStateSelect("state", state)), field("Target tile X", numberInput("tileX", Number.isFinite(Number(config.tileX)) ? Number(config.tileX) : 0, -1_000_000, 1_000_000)), field("Target tile Y", numberInput("tileY", Number.isFinite(Number(config.tileY)) ? Number(config.tileY) : 0, -1_000_000, 1_000_000)) ); const dimWrap = document.createElement("label"); dimWrap.append(document.createTextNode("Target dimension")); const dimRoot = document.createElement("div"); dimRoot.className = "doorway-dim-combo"; dimWrap.append(dimRoot); form.append(dimWrap); const options = typeof getDimensionOptions === "function" ? (getDimensionOptions() ?? []) : []; doorwayDimCombo = createDimensionCombobox({ root: dimRoot, placeholder: "Target dimension…", onSelect () {} }); doorwayDimCombo.setOptions(options); doorwayDimCombo.setValue(normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID)); show(true); } document.getElementById("tile-config-close").addEventListener("click", () => show(false)); document.getElementById("tile-config-cancel").addEventListener("click", () => show(false)); backdrop.addEventListener("click", () => show(false)); document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch()); itemSearchBackdrop?.addEventListener("click", () => closeItemSearch()); itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value)); document.getElementById("equip-dye-close")?.addEventListener("click", () => closeDyePicker()); dyeBackdrop?.addEventListener("click", () => closeDyePicker()); document.getElementById("equip-dye-apply")?.addEventListener("click", () => { if (!dyeEditSlot || !equipmentDraft[dyeEditSlot]) { return; } equipmentDraft[dyeEditSlot].dyeColor = readDyeSliders(); closeDyePicker(); renderEquipmentRows(); }); document.getElementById("equip-dye-clear")?.addEventListener("click", () => { if (!dyeEditSlot || !equipmentDraft[dyeEditSlot]) { return; } equipmentDraft[dyeEditSlot].dyeColor = null; closeDyePicker(); renderEquipmentRows(); }); document.getElementById("tile-config-save").addEventListener("click", () => { if (!context) { return; } if (context.kind === "doorway") { const data = new FormData(form); const stateRaw = String(data.get("state") || "door"); onSave?.(context, { state: DOORWAY_STATES.includes(stateRaw) ? stateRaw : "door", targetDimensionId: normalizeDimensionId(doorwayDimCombo?.getValue() ?? OVERWORLD_ID), tileX: Number(data.get("tileX")) || 0, tileY: Number(data.get("tileY")) || 0 }); show(false); return; } const data = new FormData(form); const equipment = {}; for (const slot of EQUIPMENT_SLOTS) { equipment[slot] = equipConfigFromDraft(equipmentDraft[slot]); } onSave?.(context, normalizeSpawnerConfig({ mobTypeId: String(data.get("mobTypeId") || "deer"), maxAlive: Number(data.get("maxAlive") || 3), spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4), maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4), level: Number(data.get("level") || 1), bounty: Number(data.get("bounty") || 0), aggressive: data.get("aggressive") === "on", spawnerId: String(data.get("spawnerId") || context.config.spawnerId), sex: String(data.get("sex") || "male"), displayName: String(data.get("displayName") || ""), equipment, sells: sellsDraft, spells: spellsDraft, buysItems: data.get("buysItems") === "on", hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9), centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")), dialogueId: String(data.get("dialogueId") || "").trim() || null }, context.config.spawnerId)); show(false); }); document.getElementById("tile-config-remove").addEventListener("click", () => { if (!context) { return; } onRemove?.(context); show(false); }); return { isOpen: () => open, openSpawner, openDoorway, close: () => show(false), handleMessage (message) { if (!MessageType || message.type !== MessageType.editorDialogues) { return; } dialogueOptions = (message.dialogues ?? []).map((d) => ({ dialogueId: String(d.dialogueId ?? ""), label: String(d.label ?? d.dialogueId ?? ""), unique: !!d.unique })).filter((d) => d.dialogueId); const select = form.querySelector('[name="dialogueId"]'); if (select && open) { const current = select.value || pendingDialogueId || ""; select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions)); } } }; } function doorwayStateSelect (name, value) { const select = document.createElement("select"); select.name = name; for (const state of DOORWAY_STATES) { const opt = document.createElement("option"); opt.value = state; opt.textContent = state.charAt(0).toUpperCase() + state.slice(1); if (state === value) { opt.selected = true; } select.append(opt); } return select; } function field (label, input) { const wrap = document.createElement("label"); wrap.append(document.createTextNode(label), input); return wrap; } function numberInput (name, value, min, max, step = 1) { const input = document.createElement("input"); input.type = "number"; input.name = name; input.min = String(min); input.max = String(max); input.step = String(step); input.value = String(value); return input; } function textInput (name, value, readOnly = false) { const input = document.createElement("input"); input.type = "text"; input.name = name; input.value = String(value ?? ""); input.readOnly = readOnly; return input; } function sexSelect (name, value) { const select = document.createElement("select"); select.name = name; for (const sex of ["male", "female"]) { const option = document.createElement("option"); option.value = sex; option.textContent = sex; if (sex === value) { option.selected = true; } select.append(option); } return select; } function mobSelect (name, value) { const select = document.createElement("select"); select.name = name; for (const def of listSpawnableMobTypes()) { const option = document.createElement("option"); option.value = def.mobTypeId; option.textContent = def.displayName; if (def.mobTypeId === value) { option.selected = true; } select.append(option); } return select; } function dialogueSelect (name, value, options = []) { const select = document.createElement("select"); select.name = name; const none = document.createElement("option"); none.value = ""; none.textContent = "(none)"; select.append(none); const selected = String(value ?? ""); let found = !selected; for (const entry of options) { const option = document.createElement("option"); option.value = entry.dialogueId; option.textContent = entry.unique ? `${entry.label} [${entry.dialogueId}] · unique` : `${entry.label} [${entry.dialogueId}]`; if (entry.dialogueId === selected) { option.selected = true; found = true; } select.append(option); } if (selected && !found) { const orphan = document.createElement("option"); orphan.value = selected; orphan.textContent = `${selected} (missing)`; orphan.selected = true; select.append(orphan); } return select; }