/** * Right-click config modal for editor tiles that have configurable data (spawners). */ import { listSpawnableMobTypes, normalizeSpawnerConfig, MobId, isHumanoidMob, isCentralExchangeSpawner } from "/shared/definitions/mobs.js"; import { centralExchangeStaffCount } from "/shared/market/exchange.js"; import { ITEM_DEFINITIONS, itemDefinition } from "/shared/definitions/items.js"; import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js"; import { listNpcShopSellableItems } from "/shared/shop/pricing.js"; /** 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; } export function initTileConfigModal ({ onSave, onRemove }) { 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"); let open = false; let context = null; /** @type {{ itemId: number, quantity: number }[]} */ let sellsDraft = []; /** @type {Record} */ let equipmentDraft = {}; /** @type {{ kind: "sells" } | { kind: "equip", slot: string } | null} */ let itemSearchMode = null; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { context = null; closeItemSearch(); } } function closeItemSearch () { itemSearchMode = null; if (itemSearchBackdrop) { itemSearchBackdrop.hidden = true; } if (itemSearchModal) { itemSearchModal.hidden = true; } } function openSellItemSearch () { itemSearchMode = { kind: "sells" }; openItemSearch("Add shop stock"); } function openEquipItemSearch (slot) { itemSearchMode = { kind: "equip", slot }; openItemSearch(`Equip ${slot}`); } function openItemSearch (heading) { if (!itemSearchBackdrop || !itemSearchModal || !itemSearchInput) { return; } if (itemSearchTitle) { itemSearchTitle.textContent = heading ?? "Choose item"; } itemSearchInput.value = ""; itemSearchInput.placeholder = itemSearchMode?.kind === "equip" ? "Search equipment…" : "Search items…"; renderItemSearchResults(""); itemSearchBackdrop.hidden = false; itemSearchModal.hidden = false; itemSearchInput.focus(); } function candidateItems () { if (itemSearchMode?.kind === "equip") { return listEquippableItemsForSlot(itemSearchMode.slot); } return listNpcShopSellableItems(); } function renderItemSearchResults (query) { if (!itemSearchResults) { return; } itemSearchResults.innerHTML = ""; const q = String(query ?? "").trim().toLowerCase(); const taken = itemSearchMode?.kind === "sells" ? new Set(sellsDraft.map((line) => line.itemId)) : null; const matches = candidateItems().filter((item) => { if (taken?.has(item.itemId)) { return false; } if (!q) { return true; } return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q); }).slice(0, 120); if (!matches.length) { itemSearchResults.textContent = "No matching items."; return; } for (const item of matches) { const row = document.createElement("button"); row.type = "button"; row.className = "shop-item-search-row"; row.textContent = item.displayName; row.addEventListener("click", () => { if (itemSearchMode?.kind === "equip") { equipmentDraft[itemSearchMode.slot] = item.itemId; renderEquipmentRows(); } else { sellsDraft.push({ itemId: item.itemId, quantity: 0 }); renderSellsList(); } closeItemSearch(); }); itemSearchResults.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 renderEquipmentRows () { const list = form.querySelector("[data-equipment-list]"); if (!list) { return; } list.innerHTML = ""; for (const slot of EQUIPMENT_SLOTS) { const itemId = equipmentDraft[slot] ?? null; const def = itemId ? itemDefinition(itemId) : null; 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"; name.textContent = def?.displayName ?? "(none)"; const pick = document.createElement("button"); pick.type = "button"; pick.textContent = "Choose…"; pick.addEventListener("click", () => openEquipItemSearch(slot)); const clear = document.createElement("button"); clear.type = "button"; clear.textContent = "Clear"; clear.disabled = itemId == null; clear.addEventListener("click", () => { equipmentDraft[slot] = null; renderEquipmentRows(); }); row.append(label, name, pick, 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 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) { const raw = config.equipment?.[slot]; equipmentDraft[slot] = raw != null && raw !== "" ? Number(raw) || null : null; } queueMicrotask(() => renderEquipmentRows()); if (!exchange) { wrap.append(field("Hidden discount (0–1)", numberInput("hiddenDiscount", config.hiddenDiscount ?? 0.9, 0.01, 1, 0.01))); const sellsHeader = document.createElement("div"); sellsHeader.className = "spawner-sells-header"; const sellsTitle = document.createElement("strong"); sellsTitle.textContent = "Sells"; const addBtn = document.createElement("button"); addBtn.type = "button"; addBtn.textContent = "+"; addBtn.title = "Add item"; addBtn.addEventListener("click", () => openSellItemSearch()); sellsHeader.append(sellsTitle, addBtn); wrap.append(sellsHeader); const list = document.createElement("div"); list.className = "spawner-sells-list"; list.dataset.sellsList = "1"; wrap.append(list); const buysLabel = document.createElement("label"); buysLabel.className = "spawner-buys-row"; const buys = document.createElement("input"); buys.type = "checkbox"; buys.name = "buysItems"; buys.checked = !!config.buysItems; buysLabel.append(buys, document.createTextNode(" Buys items")); wrap.append(buysLabel); const hint = document.createElement("p"); hint.className = "hint"; hint.textContent = "Quantity 0 = infinite stock. Limited stock restocks daily at 00:00 server time. Buys items: pays 80% market for transferable bag goods (not blank cheques); filled cheques sell as reserved goods with a 5% admin fee; extras resell at 120% until restock."; wrap.append(hint); sellsDraft = (config.sells ?? []).map((line) => { if (line && typeof line === "object") { return { itemId: line.itemId | 0, quantity: Math.max(0, line.quantity | 0 || 0) }; } return { itemId: line | 0, quantity: 0 }; }).filter((line) => line.itemId > 0); queueMicrotask(() => renderSellsList()); } else { sellsDraft = []; } return wrap; } function syncHumanoidSection (config) { form.querySelector("[data-humanoid]")?.remove(); const mobTypeId = form.querySelector('[name="mobTypeId"]')?.value; if (!isHumanoidMob(mobTypeId)) { sellsDraft = []; equipmentDraft = {}; return; } form.append(renderHumanoidFields(config ?? normalizeSpawnerConfig({ mobTypeId: mobTypeId || MobId.humanoid }, "spawner"))); const maxAlive = form.querySelector('[name="maxAlive"]'); if (maxAlive && isCentralExchangeSpawner({ mobTypeId })) { maxAlive.value = String(centralExchangeStaffCount()); maxAlive.disabled = true; } else if (maxAlive) { maxAlive.disabled = false; } } function openSpawner (ctx) { context = { kind: "spawner", ...ctx }; const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId); title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`; form.innerHTML = ""; const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId)); form.append( mobField, field("Max alive", numberInput("maxAlive", config.maxAlive, 1, 20)), field("Spawn range", numberInput("spawnRangeTiles", config.spawnRangeTiles, 1, 32)), field("Max wander range", numberInput("maxWanderRangeTiles", config.maxWanderRangeTiles, 1, 64)), field("Spawner id", textInput("spawnerId", config.spawnerId, true)) ); const spawnInput = form.querySelector('[name="spawnRangeTiles"]'); const wanderInput = form.querySelector('[name="maxWanderRangeTiles"]'); const syncWanderMin = () => { const spawn = Number(spawnInput.value) || 1; wanderInput.min = String(spawn); if (Number(wanderInput.value) < spawn) { wanderInput.value = String(spawn); } }; spawnInput.addEventListener("input", syncWanderMin); syncWanderMin(); form.querySelector('[name="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); syncWanderMin(); syncHumanoidSection(defaults); }); syncHumanoidSection(config); show(true); } document.getElementById("tile-config-close").addEventListener("click", () => show(false)); document.getElementById("tile-config-cancel").addEventListener("click", () => show(false)); backdrop.addEventListener("click", () => show(false)); document.getElementById("shop-item-search-close")?.addEventListener("click", () => closeItemSearch()); itemSearchBackdrop?.addEventListener("click", () => closeItemSearch()); itemSearchInput?.addEventListener("input", () => renderItemSearchResults(itemSearchInput.value)); document.getElementById("tile-config-save").addEventListener("click", () => { if (!context) { return; } const data = new FormData(form); const equipment = {}; for (const slot of EQUIPMENT_SLOTS) { const raw = equipmentDraft[slot]; equipment[slot] = raw != null && raw !== "" ? Number(raw) || null : null; } onSave?.(context, normalizeSpawnerConfig({ mobTypeId: String(data.get("mobTypeId") || "deer"), maxAlive: Number(data.get("maxAlive") || 3), spawnRangeTiles: Number(data.get("spawnRangeTiles") || 4), maxWanderRangeTiles: Number(data.get("maxWanderRangeTiles") || 4), spawnerId: String(data.get("spawnerId") || context.config.spawnerId), sex: String(data.get("sex") || "male"), displayName: String(data.get("displayName") || ""), equipment, sells: sellsDraft, buysItems: data.get("buysItems") === "on", hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9), centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")) }, context.config.spawnerId)); show(false); }); document.getElementById("tile-config-remove").addEventListener("click", () => { if (!context) { return; } onRemove?.(context); show(false); }); return { isOpen: () => open, openSpawner, close: () => show(false) }; } 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; }