/** * Right-click config modal for editor tiles that have configurable data (spawners, doorways). */ import { listSpawnableMobTypes, normalizeSpawnerConfig, MobId, isHumanoidMob, isCentralExchangeSpawner, spawnerEquipmentSlot, mobDefinition } from "/shared/definitions/mobs.js"; import { spellCastSuccessChancePercent } from "/shared/combat/magic.js"; import { SPELL_DEFINITIONS, spellMinMagicLevel } from "/shared/definitions/spells.js"; import { spellDifficultyFromTier } from "/shared/spells/constants.js"; import { centralExchangeStaffCount } from "/shared/market/exchange.js"; import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing, listAllItemPickerEntries, itemAssetPathForStack } from "/shared/definitions/items.js"; import { listRawFishPickerEntries, normalizeFishingSpotConfig, fishTierRankFromItemId } from "/shared/definitions/fishItems.js"; import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js"; import { normalizeRgb } from "/shared/render/tint.js"; import { applyItemIcon } from "/src/render/potionIcon.js"; import { createDimensionCombobox } from "./dimensionCombobox.js"; import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js"; import { renderConditionSet, emptyConditionSet, normalizeConditionSet } from "./conditionSetEditor.js"; import { DEFAULT_DOOR_BLOCKED_MESSAGE } from "/shared/world/doorRequirements.js"; import { isItemSpawnerConfig, normalizeItemSpawnerConfig, defaultItemSpawnerConfig, ItemSpawnerAppearance, ITEM_SPAWNER_APPEARANCES, ITEM_SPAWNER_CONTAINER_APPEARANCES, isItemSpawnerContainerAppearance, listItemSpawnerMaterials, ITEM_SPAWNER_LOCKED_MESSAGE } from "/shared/definitions/itemSpawners.js"; const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]); const ITEM_SEARCH_PAGE_SIZE = 40; function formatCastChancePercent (pct) { const n = Number(pct); if (!Number.isFinite(n)) { return "0"; } const rounded = Math.round(n * 10) / 10; return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1); } /** 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; } /** Stack shape for applyItemIcon, including optional clothing dye. */ function stackFromEquipDraft (draft) { const itemId = draft?.itemId; if (itemId == null) { return null; } const stack = { itemId, quantity: 1 }; if (draft.dyeColor && isDyeableClothing(itemId)) { stack.instance = { kind: "clothing", dyeColor: normalizeRgb(draft.dyeColor) }; } return stack; } function applyEquipIcon (img, draft) { if (!img) { return; } const stack = stackFromEquipDraft(draft); if (!stack) { img.removeAttribute("src"); img.alt = ""; img.hidden = true; return; } img.hidden = false; img.alt = itemDefinition(stack.itemId)?.displayName ?? ""; applyItemIcon(img, stack, itemAssetPathForStack(stack)); } 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, getQuests, getDimensionOptions, describeWorldTile = null, centerEditorOnTile = null }) { 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 itemSearchPrev = document.getElementById("shop-item-search-prev"); const itemSearchNext = document.getElementById("shop-item-search-next"); const itemSearchPageLabel = document.getElementById("shop-item-search-page"); 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 itemSpawnerItemsDraft = []; let itemSpawnerWhenDraft = emptyConditionSet(); let sellsDraft = []; /** @type {{ itemId: number, chancePercent: number, quantityMin: number, quantityMax: number }[]} */ let dropsDraft = []; /** @type {number[]} raw fish item ids for fishing spots */ let fishesDraft = []; /** @type {{ spellId: string, chance: number }[]} */ let spellsDraft = []; /** @type {Record} */ let equipmentDraft = {}; /** @type {{ kind: "sells" } | { kind: "drops" } | { kind: "fishes" } | { 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 {number} */ let itemSearchPage = 0; /** @type {{ itemId: number, displayName: string, key: string }[] | null} */ let itemSearchMatches = null; /** @type {ReturnType|null} */ let doorwayDimCombo = null; /** @type {{ all: object[] }} */ let doorWhenDraft = emptyConditionSet(); /** @type {string} */ let doorBlockedMessageDraft = ""; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { context = null; doorwayDimCombo = null; doorWhenDraft = emptyConditionSet(); doorBlockedMessageDraft = ""; closeItemSearch(); closeDyePicker(); } } function closeItemSearch () { itemSearchMode = null; itemSearchPage = 0; itemSearchMatches = null; if (itemSearchBackdrop) { itemSearchBackdrop.hidden = true; } if (itemSearchModal) { itemSearchModal.hidden = true; } } function openSellItemSearch () { itemSearchMode = { kind: "sells" }; openItemSearch("Add shop stock"); } function openDropItemSearch () { itemSearchMode = { kind: "drops" }; openItemSearch("Add drop"); } function openFishItemSearch () { itemSearchMode = { kind: "fishes" }; openItemSearch("Add fish to spot"); } function openItemSpawnerItemsSearch () { itemSearchMode = { kind: "item-spawner-items" }; openItemSearch("Add item to spawner"); } 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 = ""; itemSearchPage = 0; itemSearchMatches = null; itemSearchInput.placeholder = itemSearchMode?.kind === "equip" ? "Search equipment…" : itemSearchMode?.kind === "fishes" ? "Search raw fish…" : "Search all items…"; renderItemSearchResults(""); itemSearchBackdrop.hidden = false; itemSearchModal.hidden = false; itemSearchInput.focus(); } function candidateItems () { if (itemSearchMode?.kind === "equip") { return listEquippableItemsForSlot(itemSearchMode.slot); } if (itemSearchMode?.kind === "fishes") { return listRawFishPickerEntries(); } return listAllItemPickerEntries(); } function filterItemSearchMatches (query) { const q = String(query ?? "").trim().toLowerCase(); const taken = itemSearchMode?.kind === "sells" ? new Set(sellsDraft.map((line) => line.itemId)) : (itemSearchMode?.kind === "drops" ? new Set(dropsDraft.map((line) => line.itemId)) : null); return candidateItems().filter((item) => { if (taken?.has(item.itemId)) { return false; } if (!q) { return true; } const idText = String(item.itemId); return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q) || idText.includes(q); }); } function renderItemSearchResults (query) { if (!itemSearchResults) { return; } itemSearchResults.innerHTML = ""; itemSearchMatches = filterItemSearchMatches(query); const total = itemSearchMatches.length; const pageCount = Math.max(1, Math.ceil(total / ITEM_SEARCH_PAGE_SIZE)); if (itemSearchPage >= pageCount) { itemSearchPage = Math.max(0, pageCount - 1); } const start = itemSearchPage * ITEM_SEARCH_PAGE_SIZE; const pageItems = itemSearchMatches.slice(start, start + ITEM_SEARCH_PAGE_SIZE); if (itemSearchPageLabel) { itemSearchPageLabel.textContent = total ? `${start + 1}–${start + pageItems.length} of ${total}` : "No items"; } if (itemSearchPrev) { itemSearchPrev.disabled = itemSearchPage <= 0; } if (itemSearchNext) { itemSearchNext.disabled = itemSearchPage >= pageCount - 1; } if (!pageItems.length) { itemSearchResults.textContent = total ? "No items on this page." : "No matching items."; return; } for (const item of pageItems) { const row = document.createElement("button"); row.type = "button"; row.className = "shop-item-search-row"; const icon = document.createElement("img"); icon.className = "shop-item-search-row-icon equip-stats-icon"; icon.width = 16; icon.height = 16; icon.alt = ""; const stack = { itemId: item.itemId, quantity: 1 }; applyItemIcon(icon, stack, itemAssetPathForStack(stack)); const text = document.createElement("span"); text.className = "shop-item-search-row-text"; 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 = itemSearchMode?.kind === "fishes" ? `${item.key} · tier ${item.tier} · #${item.itemId}` : `${item.key} · #${item.itemId}`; text.append(name, key); row.append(icon, text); row.addEventListener("click", () => { if (itemSearchMode?.kind === "equip") { equipmentDraft[itemSearchMode.slot] = { itemId: item.itemId, dyeColor: null }; renderEquipmentRows(); } else if (itemSearchMode?.kind === "fishes") { if (!fishesDraft.includes(item.itemId)) { fishesDraft.push(item.itemId); } renderFishesList(); } else if (itemSearchMode?.kind === "drops") { dropsDraft.push({ itemId: item.itemId, chancePercent: 100, quantityMin: 1, quantityMax: 1 }); renderDropsList(); } else if (itemSearchMode?.kind === "item-spawner-items") { itemSpawnerItemsDraft.push({ itemId: item.itemId, quantity: 1 }); renderItemSpawnerItemsList(); syncItemSpawnerAppearanceGates(); } 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 renderFishesList () { const list = form.querySelector("[data-fishes-list]"); if (!list) { return; } list.innerHTML = ""; if (!fishesDraft.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No fish yet. Use + to choose species for this spot."; list.append(empty); return; } for (let index = 0; index < fishesDraft.length; index++) { const itemId = fishesDraft[index]; const def = itemDefinition(itemId); const row = document.createElement("div"); row.className = "spawner-sells-row"; const tier = fishTierRankFromItemId(itemId); const name = document.createElement("span"); name.className = "spawner-sells-name"; name.textContent = tier != null ? `${def?.displayName ?? `Item ${itemId}`} · tier ${tier}` : (def?.displayName ?? `Item ${itemId}`); const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Remove"; remove.addEventListener("click", () => { fishesDraft.splice(index, 1); renderFishesList(); }); row.append(name, remove); list.append(row); } } 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 renderDropsList () { const list = form.querySelector("[data-drops-list]"); if (!list) { return; } list.innerHTML = ""; if (!dropsDraft.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No drops yet. Use + to add loot."; list.append(empty); return; } for (let index = 0; index < dropsDraft.length; index++) { const line = dropsDraft[index]; const def = itemDefinition(line.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 ${line.itemId}`; const qtyMin = document.createElement("input"); qtyMin.type = "number"; qtyMin.min = "0"; qtyMin.step = "1"; qtyMin.value = String(line.quantityMin | 0); qtyMin.title = "Minimum quantity if this drop hits"; qtyMin.addEventListener("input", () => { const min = Math.max(0, Number(qtyMin.value) || 0) | 0; dropsDraft[index].quantityMin = min; if ((dropsDraft[index].quantityMax | 0) < min) { dropsDraft[index].quantityMax = min; qtyMax.value = String(min); } }); const qtyMax = document.createElement("input"); qtyMax.type = "number"; qtyMax.min = "0"; qtyMax.step = "1"; qtyMax.value = String(line.quantityMax | 0); qtyMax.title = "Maximum quantity if this drop hits"; qtyMax.addEventListener("input", () => { const max = Math.max(0, Number(qtyMax.value) || 0) | 0; const min = dropsDraft[index].quantityMin | 0; dropsDraft[index].quantityMax = Math.max(min, max); if (max < min) { qtyMax.value = String(min); } }); const chanceWrap = document.createElement("label"); chanceWrap.className = "spawner-drops-chance"; const chance = document.createElement("input"); chance.type = "number"; chance.min = "0"; chance.max = "100"; chance.step = "1"; chance.value = String(Math.round(line.chancePercent ?? 100)); chance.title = "Drop chance (0–100%)"; chance.addEventListener("input", () => { dropsDraft[index].chancePercent = Math.min( 100, Math.max(0, Number(chance.value) || 0) ); }); const suffix = document.createElement("span"); suffix.textContent = "%"; chanceWrap.append(chance, suffix); const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Remove"; remove.addEventListener("click", () => { dropsDraft.splice(index, 1); renderDropsList(); }); row.append(name, qtyMin, qtyMax, chanceWrap, 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 icon = document.createElement("img"); icon.className = "spawner-equip-icon equip-stats-icon"; icon.width = 16; icon.height = 16; icon.alt = ""; applyEquipIcon(icon, draft); 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, icon, name, pick, dyeBtn, clear); list.append(row); } } function renderCommonSpawnerFields (config) { const wrap = document.createElement("div"); wrap.className = "spawner-common-fields"; wrap.dataset.commonSpawner = "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 { const def = mobDefinition(config.mobTypeId); const placeholder = def?.displayName || "Name"; wrap.append( field("Display name", textInput("displayName", config.displayName || "")) ); const nameHint = document.createElement("p"); nameHint.className = "hint"; nameHint.textContent = `Optional. Empty uses the mob default (${placeholder}).`; wrap.append(nameHint); // Wildlife: Passive without Aggressive checkbox (Aggressive comes from mob def). if (!isHumanoidMob(config.mobTypeId) && !isCentralExchangeSpawner(config)) { const defAggressive = !!def?.aggressive; const passiveLabel = document.createElement("label"); passiveLabel.className = "spawner-buys-row"; const passive = document.createElement("input"); passive.type = "checkbox"; passive.name = "passive"; passive.checked = !!config.passive && !defAggressive; passive.disabled = defAggressive; passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)")); wrap.append(passiveLabel); const passiveHint = document.createElement("p"); passiveHint.className = "hint"; passiveHint.textContent = defAggressive ? "Unavailable: this mob type is Aggressive by definition." : "Passive mobs take hits but never retaliate when attacked."; wrap.append(passiveHint); } } const dropsHeader = document.createElement("div"); dropsHeader.className = "spawner-sells-header"; const dropsTitle = document.createElement("strong"); dropsTitle.textContent = "Drops"; const dropsAddBtn = document.createElement("button"); dropsAddBtn.type = "button"; dropsAddBtn.textContent = "+"; dropsAddBtn.title = "Add drop"; dropsAddBtn.addEventListener("click", () => openDropItemSearch()); dropsHeader.append(dropsTitle, dropsAddBtn); wrap.append(dropsHeader); const dropsList = document.createElement("div"); dropsList.className = "spawner-sells-list"; dropsList.dataset.dropsList = "1"; wrap.append(dropsList); const dropsHint = document.createElement("p"); dropsHint.className = "hint"; dropsHint.textContent = "Configured drops replace the mob's default loot table. Leave empty to keep defaults. Each line rolls its chance; quantity is random between min and max (inclusive)."; wrap.append(dropsHint); dropsDraft = (config.drops ?? []).map((line) => { if (!line || typeof line !== "object") { return null; } const itemId = line.itemId | 0; if (itemId <= 0) { return null; } let chancePercent = Number(line.chance); if (!Number.isFinite(chancePercent)) { chancePercent = 100; } else if (chancePercent <= 1) { chancePercent = chancePercent * 100; } let quantityMin = Math.max(0, Math.floor(Number(line.quantityMin ?? line.quantity ?? 1))); let quantityMax = Math.max(0, Math.floor(Number(line.quantityMax ?? quantityMin))); if (!Number.isFinite(quantityMin)) { quantityMin = 1; } if (!Number.isFinite(quantityMax) || quantityMax < quantityMin) { quantityMax = quantityMin; } return { itemId, chancePercent: Math.min(100, Math.max(0, chancePercent)), quantityMin, quantityMax }; }).filter(Boolean); queueMicrotask(() => renderDropsList()); return wrap; } function renderHumanoidFields (config) { const wrap = document.createElement("div"); wrap.className = "spawner-humanoid-fields"; wrap.dataset.humanoid = "1"; const exchange = isCentralExchangeSpawner(config); if (!exchange) { wrap.append(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", () => syncAggressivePassive()); 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 and Passive is unavailable."; wrap.append(aggressiveHint); const passiveLabel = document.createElement("label"); passiveLabel.className = "spawner-buys-row"; const passive = document.createElement("input"); passive.type = "checkbox"; passive.name = "passive"; passive.checked = !!config.passive && !config.aggressive; passive.disabled = !!config.aggressive; passiveLabel.append(passive, document.createTextNode(" Passive (takes hits, does not fight back)")); wrap.append(passiveLabel); const passiveHint = document.createElement("p"); passiveHint.className = "hint"; passiveHint.textContent = "Only available while Aggressive is off. Passive mobs never retaliate when attacked."; wrap.append(passiveHint); 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. Any item can be listed for sale. Buys items: pays 50% 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 syncCommonSpawnerSection (config) { form.querySelector("[data-common-spawner]")?.remove(); const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value || config?.mobTypeId || MobId.deer; const normalized = config ?? normalizeSpawnerConfig({ mobTypeId }, "spawner"); const anchor = form.querySelector("[data-humanoid]") || form.querySelector("[data-spells]"); const section = renderCommonSpawnerFields(normalized); if (anchor) { form.insertBefore(section, anchor); } else { form.append(section); } } 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) => !def.mobOnly && !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 success uses the mob Level as Magic vs the spell tier (same contest as players). 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; 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)) { if (spell.mobOnly) { continue; } const opt = document.createElement("option"); opt.value = spell.spellId; const minLv = spellMinMagicLevel(spell); 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 = spellMinMagicLevel(def); const tier = def?.tier | 0 || 1; const successPct = spellCastSuccessChancePercent(level, tier); const chanceLabel = document.createElement("span"); chanceLabel.className = "hint"; chanceLabel.title = `Channel success: Magic ${level} vs tier ${tier} (difficulty ${spellDifficultyFromTier(tier)})`; chanceLabel.textContent = level < minLv ? `needs Lv.${minLv}` : `cast ${formatCastChancePercent(successPct)}%`; 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 syncAggressivePassive () { const bountyInput = form.querySelector('[name="bounty"]'); const aggressiveInput = form.querySelector('[name="aggressive"]'); const passiveInput = form.querySelector('[name="passive"]'); const aggressive = !!aggressiveInput?.checked; if (bountyInput) { if (aggressive) { bountyInput.value = "0"; bountyInput.disabled = true; } else { bountyInput.disabled = false; } } if (passiveInput) { if (aggressive) { passiveInput.checked = false; passiveInput.disabled = true; } else { passiveInput.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("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)), field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 0, 32)), field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 0, 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 = Math.max(0, Number(spawnInput.value) || 0); 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(); syncCommonSpawnerSection(defaults); syncHumanoidSection(defaults); syncSpellsSection(defaults); syncAggressivePassive(); }); spellsDraft = (config.spells ?? []).map((line) => ({ spellId: String(line.spellId ?? "") })).filter((line) => line.spellId); syncCommonSpawnerSection(config); syncHumanoidSection(config); syncSpellsSection(config); syncAggressivePassive(); show(true); } function renderItemSpawnerItemsList () { const list = form.querySelector("[data-item-spawner-items]"); if (!list) { return; } list.innerHTML = ""; if (!itemSpawnerItemsDraft.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No items yet. Use + to choose what this spawner creates."; list.append(empty); return; } for (let index = 0; index < itemSpawnerItemsDraft.length; index++) { const line = itemSpawnerItemsDraft[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 = "1"; qty.step = "1"; qty.value = String(Math.max(1, line.quantity | 0)); qty.title = "Stack quantity"; qty.addEventListener("input", () => { itemSpawnerItemsDraft[index].quantity = Math.max(1, Number(qty.value) || 1) | 0; }); const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Remove"; remove.addEventListener("click", () => { itemSpawnerItemsDraft.splice(index, 1); renderItemSpawnerItemsList(); syncItemSpawnerAppearanceGates(); }); row.append(name, qty, remove); list.append(row); } } function syncItemSpawnerAppearanceGates () { const appearanceSelect = form.querySelector('[name="appearance"]'); const materialField = form.querySelector("[data-item-spawner-material]"); const conditionHost = form.querySelector("[data-item-spawner-condition]"); if (!appearanceSelect) { return; } const stackCount = itemSpawnerItemsDraft.length; const itemOpt = appearanceSelect.querySelector('option[value="item"]'); if (itemOpt) { itemOpt.disabled = stackCount !== 1; } if (appearanceSelect.value === "item" && stackCount !== 1) { appearanceSelect.value = ItemSpawnerAppearance.chest; } const appearance = appearanceSelect.value; const isContainer = isItemSpawnerContainerAppearance(appearance); if (materialField) { materialField.hidden = !isContainer; } if (conditionHost) { conditionHost.hidden = !isContainer; } } function openItemSpawner (ctx) { context = { kind: "item-spawner", ...ctx }; const config = normalizeItemSpawnerConfig(ctx.config, ctx.config?.spawnerId); itemSpawnerItemsDraft = (config.items ?? []).map((line) => ({ itemId: line.itemId, quantity: Math.max(1, line.quantity | 0) })); itemSpawnerWhenDraft = normalizeConditionSet(config.when ?? emptyConditionSet()); title.textContent = `Item Spawner · ${ctx.tileX}, ${ctx.tileY}`; if (socket && MessageType) { socket.send({ type: MessageType.editorLoadQuests }); socket.send({ type: MessageType.editorLoadDialogues }); } form.innerHTML = ""; const itemsHeader = document.createElement("div"); itemsHeader.className = "spawner-sells-header"; const itemsLabel = document.createElement("strong"); itemsLabel.textContent = "Items"; const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.textContent = "+"; addBtn.title = "Add item"; addBtn.addEventListener("click", () => openItemSpawnerItemsSearch()); itemsHeader.append(itemsLabel, addBtn); const itemsList = document.createElement("div"); itemsList.setAttribute("data-item-spawner-items", ""); form.append(itemsHeader, itemsList); form.append( field("Respawn time (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)), field("Range", numberInput("spawnRangeTiles", config.spawnRangeTiles ?? 0, 0, 32)), field("Spawner id", textInput("spawnerId", config.spawnerId, true)) ); const appearanceSelect = document.createElement("select"); appearanceSelect.name = "appearance"; const appearanceLabels = { [ItemSpawnerAppearance.item]: "Item", [ItemSpawnerAppearance.chest]: "Chest", [ItemSpawnerAppearance.barrel]: "Barrel", [ItemSpawnerAppearance.crate]: "Crate" }; for (const value of ITEM_SPAWNER_APPEARANCES) { const opt = document.createElement("option"); opt.value = value; opt.textContent = appearanceLabels[value] ?? value; if (value === config.appearance) { opt.selected = true; } appearanceSelect.append(opt); } appearanceSelect.addEventListener("change", () => syncItemSpawnerAppearanceGates()); form.append(field("Appearance", appearanceSelect)); const materialWrap = document.createElement("div"); materialWrap.setAttribute("data-item-spawner-material", ""); const materialSelect = document.createElement("select"); materialSelect.name = "material"; for (const row of listItemSpawnerMaterials()) { const opt = document.createElement("option"); opt.value = row.id; opt.textContent = row.displayName; if (row.id === config.material) { opt.selected = true; } materialSelect.append(opt); } materialWrap.append(field("Material", materialSelect)); form.append(materialWrap); const conditionHost = document.createElement("div"); conditionHost.setAttribute("data-item-spawner-condition", ""); conditionHost.className = "door-requirements-when"; const condHint = document.createElement("p"); condHint.className = "tile-config-hint"; condHint.textContent = `Condition gates opening. Fail toast: "${ITEM_SPAWNER_LOCKED_MESSAGE}"`; conditionHost.append(condHint); const whenHost = document.createElement("div"); conditionHost.append(whenHost); form.append(conditionHost); const remountWhen = () => { whenHost.replaceChildren(renderConditionSet(itemSpawnerWhenDraft, (next, { remount = true } = {}) => { itemSpawnerWhenDraft = normalizeConditionSet(next); if (remount) { remountWhen(); } }, { quests: typeof getQuests === "function" ? (getQuests() ?? []) : [], dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [], describeWorldTile, centerEditorOnTile, getDimensionOptions })); }; remountWhen(); renderItemSpawnerItemsList(); syncItemSpawnerAppearanceGates(); show(true); } function openFishingSpot (ctx) { context = { kind: "fishing-spot", ...ctx }; const normalized = normalizeFishingSpotConfig(ctx.config); fishesDraft = [...normalized.fishes]; title.textContent = `Fishing spot · ${ctx.tileX}, ${ctx.tileY}`; form.innerHTML = ""; const header = document.createElement("div"); header.className = "spawner-sells-header"; const label = document.createElement("strong"); label.textContent = "Fishes"; const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.textContent = "+"; addBtn.title = "Add fish"; addBtn.addEventListener("click", () => openFishItemSearch()); header.append(label, addBtn); const list = document.createElement("div"); list.setAttribute("data-fishes-list", ""); form.append(header, list); renderFishesList(); 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); } function renderDoorRequirementsForm () { form.innerHTML = ""; const hint = document.createElement("p"); hint.className = "tile-config-hint"; hint.textContent = "Players who fail these requirements cannot pass this door — even when it is held open."; form.append(hint); const whenHost = document.createElement("div"); whenHost.className = "door-requirements-when"; form.append(whenHost); const remountWhen = () => { whenHost.replaceChildren(renderConditionSet(doorWhenDraft, (next, { remount = true } = {}) => { doorWhenDraft = normalizeConditionSet(next); if (remount) { remountWhen(); } }, { quests: typeof getQuests === "function" ? (getQuests() ?? []) : [], dialogues: typeof getDialogues === "function" ? (getDialogues() ?? []) : [], describeWorldTile, centerEditorOnTile, getDimensionOptions })); }; remountWhen(); const msgLabel = document.createElement("label"); msgLabel.append(document.createTextNode("Blocked toast")); const msg = document.createElement("input"); msg.type = "text"; msg.name = "blockedMessage"; msg.maxLength = 200; msg.placeholder = DEFAULT_DOOR_BLOCKED_MESSAGE; msg.value = doorBlockedMessageDraft; msg.addEventListener("input", () => { doorBlockedMessageDraft = msg.value; }); msgLabel.append(msg); form.append(msgLabel); } function openDoor (ctx) { context = { kind: "door", ...ctx }; const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {}; doorWhenDraft = normalizeConditionSet(config.when ?? config.requirements ?? emptyConditionSet()); doorBlockedMessageDraft = String(config.blockedMessage ?? config.denyMessage ?? "").trim(); title.textContent = `Door · ${ctx.tileX}, ${ctx.tileY}`; if (socket && MessageType) { socket.send({ type: MessageType.editorLoadQuests }); socket.send({ type: MessageType.editorLoadDialogues }); } renderDoorRequirementsForm(); 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", () => { itemSearchPage = 0; renderItemSearchResults(itemSearchInput.value); }); itemSearchPrev?.addEventListener("click", () => { if (itemSearchPage <= 0) { return; } itemSearchPage -= 1; renderItemSearchResults(itemSearchInput?.value ?? ""); }); itemSearchNext?.addEventListener("click", () => { const pageCount = Math.max(1, Math.ceil((itemSearchMatches?.length ?? 0) / ITEM_SEARCH_PAGE_SIZE)); if (itemSearchPage >= pageCount - 1) { return; } itemSearchPage += 1; 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; } if (context.kind === "door") { onSave?.(context, { when: normalizeConditionSet(doorWhenDraft), blockedMessage: String(doorBlockedMessageDraft ?? "").trim() }); show(false); return; } if (context.kind === "item-spawner") { const data = new FormData(form); onSave?.(context, normalizeItemSpawnerConfig({ spawnerId: String(data.get("spawnerId") || context.config.spawnerId), items: itemSpawnerItemsDraft, respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25), spawnRangeTiles: (() => { const n = Number(data.get("spawnRangeTiles")); return Number.isFinite(n) ? n : 0; })(), appearance: String(data.get("appearance") || ItemSpawnerAppearance.chest), material: String(data.get("material") || "pine"), when: normalizeConditionSet(itemSpawnerWhenDraft) }, context.config.spawnerId)); show(false); return; } if (context.kind === "fishing-spot") { onSave?.(context, normalizeFishingSpotConfig({ fishes: fishesDraft })); 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), respawnDelaySeconds: Number(data.get("respawnDelaySeconds") ?? 25), spawnRangeTiles: (() => { const n = Number(data.get("spawnRangeTiles")); return Number.isFinite(n) ? n : 4; })(), maxWanderRangeTiles: (() => { const n = Number(data.get("maxWanderRangeTiles")); return Number.isFinite(n) ? n : 4; })(), level: Number(data.get("level") || 1), bounty: Number(data.get("bounty") || 0), aggressive: data.get("aggressive") === "on", passive: data.get("aggressive") === "on" ? false : data.get("passive") === "on", spawnerId: String(data.get("spawnerId") || context.config.spawnerId), sex: String(data.get("sex") || "male"), displayName: String(data.get("displayName") || ""), equipment, sells: sellsDraft, drops: dropsDraft.map((line) => { const quantityMin = Math.max(0, Number(line.quantityMin) || 0) | 0; const quantityMax = Math.max( quantityMin, Math.max(0, Number(line.quantityMax) || 0) | 0 ); return { itemId: line.itemId, chance: Math.min(100, Math.max(0, Number(line.chancePercent) || 0)) / 100, quantityMin, quantityMax }; }), 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; } if (context.kind === "spawner") { const label = context.config?.displayName || context.config?.mobTypeId || context.config?.spawnerId || "this spawner"; if (!window.confirm(`Delete mob spawner "${label}"?`)) { return; } } if (context.kind === "item-spawner") { const label = context.config?.spawnerId || "this item spawner"; if (!window.confirm(`Delete item spawner "${label}"?`)) { return; } } onRemove?.(context); show(false); }); return { isOpen: () => open, openSpawner, openItemSpawner, openDoorway, openDoor, openFishingSpot, close: () => show(false), handleMessage (message) { if (!MessageType) { return; } if (message.type === MessageType.editorDialogues) { 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)); } if (open && context?.kind === "door") { renderDoorRequirementsForm(); } return; } if (message.type === MessageType.editorQuests && open && context?.kind === "door") { renderDoorRequirementsForm(); } } }; } 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; }