/** * 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, listAllItemPickerEntries } 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 { createDimensionCombobox } from "./dimensionCombobox.js"; import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js"; const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]); const ITEM_SEARCH_PAGE_SIZE = 40; /** 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 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 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; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { context = null; doorwayDimCombo = null; 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 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 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}`; row.append(name, key); 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 { 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 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()); 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 = "On death each line rolls its chance; if it hits, 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()); 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 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 = []; dropsDraft = []; 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("Respawn delay (seconds)", numberInput("respawnDelaySeconds", config.respawnDelaySeconds ?? 25, 0, 86_400)), 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 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); } 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 === "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: 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, 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; } onRemove?.(context); show(false); }); return { isOpen: () => open, openSpawner, openDoorway, openFishingSpot, 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; }