import { itemDefinition, itemDescription, itemOriginSummary, itemExtraTooltipLines, itemAssetPathForStack, itemDisplayName, formatQuantity, ItemId, EQUIPMENT_SLOT, LETTER_MAX_BODY_CHARS } from "/shared/definitions/items.js"; import { EquipmentKind } from "/shared/definitions/equipmentKinds.js"; import { stackQuantity } from "/shared/items/inventory.js"; import { countIdenticalInSlots } from "/shared/items/cheque.js"; import { formatLetterSignature } from "/shared/courier/systemLetters.js"; import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js"; import { spellDefinition } from "/shared/definitions/spells.js"; import { bagMaxHitDisplay } from "/shared/combat/maxHit.js"; import { applyItemIcon } from "../render/potionIcon.js"; import { mountLayerPreview } from "./characterPreview.js"; const EQUIP_LABELS = { [EQUIPMENT_SLOT.head]: "Head", [EQUIPMENT_SLOT.chest]: "Chest", [EQUIPMENT_SLOT.legs]: "Legs", [EQUIPMENT_SLOT.boots]: "Boots", [EQUIPMENT_SLOT.weapon]: "Weapon", [EQUIPMENT_SLOT.offhand]: "Off-hand", [EQUIPMENT_SLOT.ring]: "Ring", [EQUIPMENT_SLOT.bracelet]: "Bracelet", [EQUIPMENT_SLOT.amulet]: "Amulet" }; export function initInventory ({ socket, MessageType, contextMenu, resolveSpriteUrl, resolveImage = null, getFriends, getLocalName, tipArrows = null, getSoftClaims = null, onBagSlotActivate = null, bagClicksLocked = null, knowsSpell = null, getSkillLevels = null, getSettings = null, getKnownSpellIds = null, onBagChanged = null }) { const bagPanel = document.getElementById("bag-panel"); const bagGrid = document.getElementById("bag-grid"); const equipGrid = document.getElementById("equip-grid"); const ammoHud = document.getElementById("equipped-ammo-hud"); const bagMaxHitEl = document.getElementById("bag-max-hit"); const hint = document.getElementById("bag-hint"); const bankPanel = document.getElementById("bank-panel"); const vaultGrid = document.getElementById("vault-grid"); const vaultReservedGrid = document.getElementById("vault-reserved-grid"); const inheritGrid = document.getElementById("inherit-grid"); const bankAvailablePane = document.getElementById("bank-available-pane"); const bankReservedPane = document.getElementById("bank-reserved-pane"); const bankInheritPane = document.getElementById("bank-inherit-pane"); const bankTabAvailable = document.getElementById("bank-tab-available"); const bankTabReserved = document.getElementById("bank-tab-reserved"); const bankTabInherit = document.getElementById("bank-tab-inherit"); const bankTabsRow = document.querySelector("#bank-panel .bank-tabs"); const sendPanel = document.getElementById("send-panel"); const sendBackdrop = document.getElementById("send-backdrop"); const sendTargetPanel = document.getElementById("send-target-panel"); const sendTargetList = document.getElementById("send-target-list"); const sendSearchResult = document.getElementById("send-search-result"); const letterPanel = document.getElementById("letter-panel"); const letterBackdrop = document.getElementById("letter-backdrop"); const letterBody = document.getElementById("letter-body"); const letterSignature = document.getElementById("letter-signature"); const letterSave = document.getElementById("letter-save"); const letterTitle = document.getElementById("letter-title"); const letterStatus = document.getElementById("letter-status"); const transferPanel = document.getElementById("transfer-panel"); const transferBackdrop = document.getElementById("transfer-backdrop"); const writeChequePanel = document.getElementById("write-cheque-panel"); const writeChequeBackdrop = document.getElementById("write-cheque-backdrop"); const writeChequeVault = document.getElementById("write-cheque-vault"); let bag = { inventory: [], equipment: { slots: {} }, vault: [], vaultReserved: [] }; let inheritance = { slots: [], currency: 0 }; let selected = null; let bankOpen = false; let bankTab = "available"; let sendState = null; let letterState = null; let transferState = null; let writeChequeState = null; let pendingSearch = false; let localCharacterId = null; let dragFromIndex = null; let suppressSlotClick = false; document.getElementById("bag-toggle").addEventListener("click", () => { bagPanel.hidden = !bagPanel.hidden; }); document.getElementById("bank-close").addEventListener("click", () => closeBank()); document.getElementById("bank-claim").addEventListener("click", () => { socket.send({ type: MessageType.claimInheritance }); }); document.getElementById("bank-tab-available").addEventListener("click", () => setBankTab("available")); document.getElementById("bank-tab-reserved").addEventListener("click", () => setBankTab("reserved")); document.getElementById("bank-tab-inherit").addEventListener("click", () => setBankTab("inherit")); document.getElementById("transfer-close").addEventListener("click", () => closeTransfer()); transferBackdrop.addEventListener("click", () => closeTransfer()); document.getElementById("transfer-confirm").addEventListener("click", () => confirmTransfer()); document.getElementById("write-cheque-close").addEventListener("click", () => closeWriteCheque()); writeChequeBackdrop.addEventListener("click", () => closeWriteCheque()); document.getElementById("write-cheque-confirm").addEventListener("click", () => confirmWriteCheque()); document.getElementById("send-close").addEventListener("click", () => closeSend()); sendBackdrop.addEventListener("click", () => closeSend()); document.getElementById("send-pick-target").addEventListener("click", () => openTargetPicker()); document.getElementById("send-target-close").addEventListener("click", () => { sendTargetPanel.hidden = true; }); document.getElementById("send-confirm").addEventListener("click", () => confirmSend()); document.getElementById("send-search").addEventListener("click", () => { const firstName = document.getElementById("send-search-first").value.trim(); const lastName = document.getElementById("send-search-last").value.trim(); if (!firstName || !lastName) { sendSearchResult.textContent = "Enter a first and last name."; return; } pendingSearch = true; sendSearchResult.textContent = "Searching…"; socket.send({ type: MessageType.searchCharacter, firstName, lastName }); }); document.getElementById("letter-close").addEventListener("click", () => closeLetter()); letterBackdrop.addEventListener("click", () => closeLetter()); letterSave.addEventListener("click", () => { if (!letterState || letterState.readOnly) { return; } const body = letterBody.value; socket.send({ type: letterState.mode === "edit" ? MessageType.editLetter : MessageType.writeLetter, slotIndex: letterState.slotIndex, body }); letterStatus.textContent = "Saving…"; }); letterBody.addEventListener("input", () => { if (letterState?.readOnly) { return; } fitLetterBody(); refreshLetterSignature(); }); function sameClaimInstance (a, b) { return JSON.stringify(a ?? null) === JSON.stringify(b ?? null); } /** Bag view with cauldron soft-claims subtracted (presentation only). */ function displayInventorySlots () { const source = bag.inventory ?? []; const claims = getSoftClaims?.() ?? []; if (!claims.length) { return source; } const slots = source.map((slot) => (slot ? { ...slot, instance: slot.instance ? structuredClone(slot.instance) : null, quantity: slot.quantity | 0 } : null)); for (const claim of claims) { let need = claim.quantity | 0; if (need <= 0) { continue; } for (let i = 0; i < slots.length && need > 0; i++) { const slot = slots[i]; if (!slot || (slot.itemId | 0) !== (claim.itemId | 0)) { continue; } if ((claim.itemId | 0) === ItemId.flower && !sameClaimInstance(slot.instance, claim.instance)) { continue; } const take = Math.min(need, slot.quantity | 0); slot.quantity -= take; need -= take; if (!(slot.quantity > 0)) { slots[i] = null; } } } return slots; } function refreshMaxHit () { if (!bagMaxHitEl) { return; } const display = bagMaxHitDisplay({ skillLevels: getSkillLevels?.() ?? {}, equipmentSlots: bag.equipment?.slots ?? {}, settings: getSettings?.() ?? null, knownSpellIds: getKnownSpellIds?.() ?? [] }); const statSuffix = display.statLabel ? ` (${display.statLabel})` : ""; bagMaxHitEl.textContent = `Max hit: ${display.text}${statSuffix}`; bagMaxHitEl.title = display.title ?? ""; bagMaxHitEl.hidden = false; } function refreshEquippedAmmoHud () { if (!ammoHud) { return; } const worn = bag.equipment?.slots?.[EQUIPMENT_SLOT.offhand] ?? null; const def = worn ? itemDefinition(worn.itemId) : null; if (!worn || def?.equipment?.kind !== EquipmentKind.arrowAmmo) { ammoHud.hidden = true; ammoHud.replaceChildren(); return; } ammoHud.hidden = false; ammoHud.replaceChildren(); const img = document.createElement("img"); applyItemIcon(img, worn, itemAssetPathForStack(worn)); img.alt = itemDisplayName(worn); ammoHud.append(img); const count = document.createElement("span"); count.className = "qty"; count.textContent = formatQuantity(stackQuantity(worn.quantity)); ammoHud.append(count); ammoHud.title = `${itemDisplayName(worn)} ×${formatQuantity(stackQuantity(worn.quantity))}`; } function render () { bagGrid.innerHTML = ""; displayInventorySlots().forEach((slot, index) => { const realSlot = bag.inventory?.[index] ?? null; const button = document.createElement("button"); button.type = "button"; button.className = `item-slot${selected === index ? " selected" : ""}`; button.dataset.slotIndex = String(index); button.title = tooltip(slot ?? realSlot); button.draggable = !!realSlot; if (slot) { const img = document.createElement("img"); applyItemIcon(img, slot, itemAssetPathForStack(slot)); img.alt = itemDisplayName(slot); img.draggable = false; button.append(img); if (slot.quantity > 1) { const count = document.createElement("span"); count.className = "qty"; count.textContent = formatQuantity(slot.quantity); button.append(count); } } else if (realSlot) { button.classList.add("soft-claimed"); button.title = `${itemDisplayName(realSlot)} (in use)`; } button.addEventListener("dragstart", (event) => { if (!realSlot || !slot) { event.preventDefault(); return; } dragFromIndex = index; suppressSlotClick = false; event.dataTransfer.effectAllowed = "move"; event.dataTransfer.setData("text/plain", String(index)); button.classList.add("dragging"); }); button.addEventListener("dragend", () => { button.classList.remove("dragging"); dragFromIndex = null; for (const el of bagGrid.querySelectorAll(".item-slot.drag-over")) { el.classList.remove("drag-over"); } // Click fires after a completed drag in some browsers; ignore it. suppressSlotClick = true; queueMicrotask(() => { suppressSlotClick = false; }); }); button.addEventListener("dragover", (event) => { if (dragFromIndex == null || dragFromIndex === index) { return; } event.preventDefault(); event.dataTransfer.dropEffect = "move"; button.classList.add("drag-over"); }); button.addEventListener("dragleave", () => { button.classList.remove("drag-over"); }); button.addEventListener("drop", (event) => { event.preventDefault(); button.classList.remove("drag-over"); const raw = event.dataTransfer.getData("text/plain"); const from = raw === "" ? dragFromIndex : (raw | 0); if (from == null || from === index) { return; } selected = index; socket.send({ type: MessageType.moveInventorySlot, fromSlotIndex: from, toSlotIndex: index }); }); button.addEventListener("click", () => { if (suppressSlotClick) { suppressSlotClick = false; return; } if (!slot) { return; } if (bagClicksLocked?.()) { return; } if (onBagSlotActivate?.(index, slot)) { return; } if (bankOpen) { transferSlot("inventory", index, null); return; } selected = index; hint.textContent = `${itemDisplayName(slot)}: ${itemDescription(slot, { localCharacterId })}`; render(); }); button.addEventListener("contextmenu", (event) => { event.preventDefault(); event.stopPropagation(); if (!slot) { return; } selected = index; render(); if (bankOpen) { showBankTransferMenu(event.clientX, event.clientY, "inventory", index, slot); } else { showItemMenu(event.clientX, event.clientY, index, slot); } }); bagGrid.append(button); }); equipGrid.innerHTML = ""; for (const [slot, label] of Object.entries(EQUIP_LABELS)) { const worn = bag.equipment?.slots?.[slot]; const button = document.createElement("button"); button.type = "button"; button.className = "item-slot"; button.title = worn ? tooltip(worn) : label; if (worn) { const img = document.createElement("img"); applyItemIcon(img, worn, itemAssetPathForStack(worn)); img.alt = itemDisplayName(worn); button.append(img); if (worn.quantity > 1) { const count = document.createElement("span"); count.className = "qty"; count.textContent = formatQuantity(worn.quantity); button.append(count); } } button.addEventListener("click", () => { if (worn) { socket.send({ type: MessageType.unequipItem, equipSlot: slot }); } }); equipGrid.append(button); } refreshEquippedAmmoHud(); refreshMaxHit(); } function showItemMenu (x, y, slotIndex, slot) { const def = itemDefinition(slot.itemId); const items = []; const isOwnLetter = slot.itemId === ItemId.letter && slot.instance?.kind === "letter" && Number(slot.instance.authorCharacterId) === Number(localCharacterId); const canSend = slot.itemId !== ItemId.blankCheque && (slot.itemId !== ItemId.letter || isOwnLetter); const canEquip = def?.equipment?.slot && slot.itemId !== ItemId.coins; if (slot.itemId === ItemId.paper) { items.push({ label: "Write letter", onSelect: () => openLetter({ mode: "write", slotIndex }) }); } if (slot.itemId === ItemId.letter && slot.instance?.kind === "letter") { items.push({ label: "Read", onSelect: () => { if (slot.instance?.opened === false) { socket.send({ type: MessageType.openLetter, slotIndex }); } openLetter({ mode: "read", slotIndex, instance: { ...slot.instance, opened: true } }); } }); if (isOwnLetter) { items.push({ label: "Edit letter", onSelect: () => openLetter({ mode: "edit", slotIndex, instance: slot.instance }) }); } } const learnSpellId = spellIdFromSpellbookStack(slot, def); if (learnSpellId && !knowsSpell?.(learnSpellId)) { const spellName = spellDefinition(learnSpellId)?.displayName ?? "spell"; items.push({ label: `Learn ${spellName}`, onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex }) }); } if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper") { const byYou = slot.instance.authorCharacterId != null && Number(slot.instance.authorCharacterId) === Number(localCharacterId); items.push({ label: "Read", onSelect: () => openLetter({ mode: "read", slotIndex, instance: { documentTitle: itemDisplayName(slot), body: slot.instance.body ?? "", authorDisplayName: (slot.instance.authorDisplayName ?? "Unknown") } }) }); } if (slot.itemId === ItemId.blankCheque) { items.push({ label: "Write Cheque", onSelect: () => openWriteCheque(slotIndex) }); } if (slot.itemId === ItemId.filledCheque && bankOpen) { items.push({ label: "Redeem Cheque", onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex }) }); } if (canEquip) { items.push({ label: "Equip", onSelect: () => socket.send({ type: MessageType.equipItem, slotIndex }) }); } if (canSend) { items.push({ label: "Send", onSelect: () => openSend(slotIndex, slot) }); } const healing = itemDefinition(slot.itemId)?.healing ?? 0; if (healing > 0) { items.push({ label: "Eat", onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex }) }); } if (slot.itemId === ItemId.potion && slot.instance?.kind === "potion") { if (tipArrows?.isArrowCoatingPotion?.(slot)) { items.push({ label: "Apply to arrows", onSelect: () => tipArrows.open(slotIndex) }); } else { items.push({ label: "Drink", onSelect: () => socket.send({ type: MessageType.drinkItem, slotIndex }) }); } } const dropQty = stackQuantity(slot.quantity); if (dropQty <= 1) { items.push({ label: "Drop", onSelect: () => dropSlot(slotIndex, 1) }); } else { const name = itemDisplayName(slot); items.push( { label: `Drop one ${name}`, onSelect: () => dropSlot(slotIndex, 1) }, { label: `Drop half ${name}`, onSelect: () => dropSlot(slotIndex, Math.max(1, Math.floor(dropQty / 2))) }, { label: `Drop all ${name}`, onSelect: () => dropSlot(slotIndex, null) }, { label: `Drop X ${name}`, onSelect: () => openDrop(slotIndex, slot) } ); } contextMenu?.show(x, y, items); } function dropSlot (slotIndex, quantity) { const payload = { type: MessageType.dropItem, slotIndex }; if (quantity != null) { payload.quantity = quantity; } socket.send(payload); } function showBankTransferMenu (x, y, side, slotIndex, slot) { if (side === "inventory" && slot.itemId === ItemId.filledCheque) { contextMenu?.show(x, y, [{ label: "Redeem Cheque", onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex }) }]); return; } if (side === "inventory" && slot.itemId === ItemId.blankCheque) { contextMenu?.show(x, y, [ { label: `Return ${slot.quantity | 0}`, onSelect: () => socket.send({ type: MessageType.returnBlankCheques, slotIndex, quantity: slot.quantity | 0 }) }, { label: "Write Cheque", onSelect: () => openWriteCheque(slotIndex) } ]); return; } const qty = slot.quantity | 0; const name = itemDisplayName(slot); if (qty <= 1) { contextMenu?.show(x, y, [{ label: `Transfer ${name}`, onSelect: () => transferSlot(side, slotIndex, 1) }]); return; } contextMenu?.show(x, y, [ { label: `Transfer all ${name}`, onSelect: () => transferSlot(side, slotIndex, null) }, { label: `Transfer half ${name}`, onSelect: () => transferSlot(side, slotIndex, Math.max(1, Math.floor(qty / 2))) }, { label: `Transfer one ${name}`, onSelect: () => transferSlot(side, slotIndex, 1) }, { label: `Transfer X ${name}`, onSelect: () => openTransfer(side, slotIndex, slot) } ]); } function transferSlot (side, slotIndex, quantity) { if (side === "inventory") { socket.send({ type: MessageType.bankDeposit, slotIndex, quantity }); return; } socket.send({ type: MessageType.bankWithdraw, slotIndex, quantity }); } function openTransfer (side, slotIndex, slot) { transferState = { kind: "bank", side, slotIndex, maxQty: stackQuantity(slot.quantity) }; document.querySelector("#transfer-panel header h2").textContent = "Transfer"; document.getElementById("transfer-confirm").textContent = "Transfer"; document.getElementById("transfer-item-name").textContent = itemDisplayName(slot); const input = document.getElementById("transfer-qty"); input.value = "1"; input.max = String(transferState.maxQty); transferPanel.hidden = false; transferBackdrop.hidden = false; } function openDrop (slotIndex, slot) { transferState = { kind: "drop", slotIndex, maxQty: stackQuantity(slot.quantity) }; document.querySelector("#transfer-panel header h2").textContent = "Drop"; document.getElementById("transfer-confirm").textContent = "Drop"; document.getElementById("transfer-item-name").textContent = itemDisplayName(slot); const input = document.getElementById("transfer-qty"); input.value = "1"; input.max = String(transferState.maxQty); transferPanel.hidden = false; transferBackdrop.hidden = false; } function closeTransfer () { transferState = null; transferPanel.hidden = true; transferBackdrop.hidden = true; } function confirmTransfer () { if (!transferState) { return; } const quantity = Math.min( transferState.maxQty, Math.max(1, Number(document.getElementById("transfer-qty").value) | 0) ); if (transferState.kind === "drop") { dropSlot(transferState.slotIndex, quantity); } else { transferSlot(transferState.side, transferState.slotIndex, quantity); } closeTransfer(); } function openWriteCheque (slotIndex) { writeChequeState = { slotIndex, vaultSlotIndex: null, maxQty: 1 }; document.getElementById("write-cheque-item").textContent = "No vault item selected."; document.getElementById("write-cheque-qty").value = "1"; document.getElementById("write-cheque-confirm").disabled = true; document.getElementById("write-cheque-status").textContent = ""; writeChequePanel.hidden = false; writeChequeBackdrop.hidden = false; renderWriteChequeVault(); } function closeWriteCheque () { writeChequeState = null; writeChequePanel.hidden = true; writeChequeBackdrop.hidden = true; if (bankOpen) { renderBank(); } } function renderWriteChequeVault () { if (!writeChequeVault) { return; } writeChequeVault.innerHTML = ""; const slots = bag.vault ?? []; if (!slots.some(Boolean)) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "Your vault is empty. Deposit goods at a bank first."; writeChequeVault.append(empty); return; } slots.forEach((slot, index) => { if (!slot) { return; } const button = document.createElement("button"); button.className = "item-slot"; if (writeChequeState?.vaultSlotIndex === index) { button.classList.add("selected"); } button.title = tooltip(slot); const def = itemDefinition(slot.itemId); const img = document.createElement("img"); applyItemIcon(img, slot, itemAssetPathForStack(slot)); img.alt = itemDisplayName(slot); button.append(img); if (slot.quantity > 1) { const count = document.createElement("span"); count.className = "qty"; count.textContent = formatQuantity(slot.quantity); button.append(count); } button.addEventListener("click", () => { if (!writeChequeState) { return; } writeChequeState.vaultSlotIndex = index; writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableMatching(slot); document.getElementById("write-cheque-item").textContent = `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`; const qtyInput = document.getElementById("write-cheque-qty"); qtyInput.value = "1"; qtyInput.max = String(writeChequeState.maxQty); qtyInput.disabled = writeChequeState.maxQty <= 1; document.getElementById("write-cheque-confirm").disabled = false; renderWriteChequeVault(); }); writeChequeVault.append(button); }); } function confirmWriteCheque () { if (!writeChequeState || writeChequeState.vaultSlotIndex == null) { return; } const quantity = Math.max(1, Number(document.getElementById("write-cheque-qty").value) | 0); socket.send({ type: MessageType.writeCheque, slotIndex: writeChequeState.slotIndex, vaultSlotIndex: writeChequeState.vaultSlotIndex, quantity }); document.getElementById("write-cheque-status").textContent = "Writing…"; closeWriteCheque(); } function closeBank () { bankOpen = false; bankPanel.hidden = true; closeWriteCheque(); closeTransfer(); } function bankHasReserved () { return (bag.vaultReserved ?? []).some((slot) => slot); } function bankHasInheritance () { const slots = inheritance?.slots ?? []; const hasSlots = slots.some((slot) => slot); const hasCoins = (inheritance?.currency | 0) > 0; return hasSlots || hasCoins; } function syncBankTabs () { const showReserved = bankHasReserved(); const showInherit = bankHasInheritance(); if (bankTabReserved) { bankTabReserved.hidden = !showReserved; } if (bankTabInherit) { bankTabInherit.hidden = !showInherit; } if (bankTabsRow) { bankTabsRow.hidden = !showReserved && !showInherit; } if ((bankTab === "reserved" && !showReserved) || (bankTab === "inherit" && !showInherit)) { bankTab = "available"; } } function setBankTab (tab) { syncBankTabs(); if (tab === "reserved" && !bankHasReserved()) { tab = "available"; } if (tab === "inherit" && !bankHasInheritance()) { tab = "available"; } bankTab = tab; bankTabAvailable?.classList.toggle("active", tab === "available"); bankTabReserved?.classList.toggle("active", tab === "reserved"); bankTabInherit?.classList.toggle("active", tab === "inherit"); if (bankAvailablePane) { bankAvailablePane.hidden = tab !== "available"; } if (bankReservedPane) { bankReservedPane.hidden = tab !== "reserved"; } if (bankInheritPane) { bankInheritPane.hidden = tab !== "inherit"; } } function openSend (slotIndex, slot) { const def = itemDefinition(slot.itemId); sendState = { slotIndex, itemId: slot.itemId, maxQty: slot.quantity | 0, destination: null }; applyItemIcon( document.getElementById("send-item-img"), slot, itemAssetPathForStack(slot) ); document.getElementById("send-item-name").textContent = itemDisplayName(slot); const qtyInput = document.getElementById("send-qty"); qtyInput.value = String(Math.max(1, sendState.maxQty)); qtyInput.max = String(sendState.maxQty); qtyInput.disabled = sendState.maxQty <= 1; document.getElementById("send-target-label").textContent = "No target selected."; document.getElementById("send-confirm").disabled = true; document.getElementById("send-status").textContent = ""; sendPanel.hidden = false; sendBackdrop.hidden = false; sendTargetPanel.hidden = true; } function closeSend () { sendState = null; sendPanel.hidden = true; sendBackdrop.hidden = true; sendTargetPanel.hidden = true; } function openTargetPicker () { if (!sendState) { return; } sendTargetPanel.hidden = false; sendSearchResult.replaceChildren(); document.getElementById("send-search-first").value = ""; document.getElementById("send-search-last").value = ""; renderTargetList(); } function renderTargetList () { sendTargetList.replaceChildren(); sendTargetList.append(targetRow({ kind: "bank", label: "Bank", hint: "Nearest bank → your vault" })); const friends = getFriends?.() ?? []; if (!friends.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No friends yet."; sendTargetList.append(empty); return; } for (const friend of friends) { sendTargetList.append(characterTargetRow(friend)); } } function targetRow ({ kind, label, hint, onPick }) { const row = document.createElement("button"); row.type = "button"; row.className = "send-target-row"; row.innerHTML = `${label}${hint ? `${hint}` : ""}`; row.addEventListener("click", () => { if (onPick) { onPick(); } else { pickTarget({ kind: "bank" }, "Bank"); } }); return row; } function characterTargetRow (entry) { const row = document.createElement("button"); row.type = "button"; row.className = "send-target-row"; const preview = characterPreview(entry.layers); const text = document.createElement("div"); text.className = "send-target-text"; text.innerHTML = `${entry.firstName} ${entry.lastName}`; row.append(preview, text); row.addEventListener("click", () => { pickTarget({ kind: "player", firstName: entry.firstName, lastName: entry.lastName, characterId: entry.characterId }, `${entry.firstName} ${entry.lastName}`); }); return row; } function characterPreview (layers) { return mountLayerPreview(layers, { resolveImage, resolveSpriteUrl, size: 48, className: "char-preview" }); } function pickTarget (destination, label) { if (!sendState) { return; } sendState.destination = destination; document.getElementById("send-target-label").textContent = `Target: ${label}`; document.getElementById("send-confirm").disabled = false; sendTargetPanel.hidden = true; } function confirmSend () { if (!sendState?.destination) { return; } const quantity = Math.max(1, Math.min(sendState.maxQty, Number(document.getElementById("send-qty").value) | 0)); socket.send({ type: MessageType.sendPigeon, destination: sendState.destination, cargo: { kind: "item", slotIndex: sendState.slotIndex, quantity } }); document.getElementById("send-status").textContent = "Pigeon dispatched…"; } function openLetter ({ mode, slotIndex, instance }) { letterState = { mode, slotIndex, readOnly: mode === "read", instance: instance ?? null }; letterTitle.textContent = instance?.documentTitle ?? (mode === "write" ? "Write letter" : mode === "edit" ? "Edit letter" : "Letter"); letterBody.value = instance?.body ?? ""; letterBody.readOnly = letterState.readOnly; letterBody.maxLength = LETTER_MAX_BODY_CHARS; letterSave.hidden = letterState.readOnly; letterStatus.textContent = ""; refreshLetterSignature(); letterPanel.hidden = false; letterBackdrop.hidden = false; fitLetterBody(); } function fitLetterBody () { letterBody.style.height = "auto"; letterBody.style.height = `${Math.max(letterBody.scrollHeight, 128)}px`; } function refreshLetterSignature () { const fallback = getLocalName?.() || "Unknown"; letterSignature.textContent = formatLetterSignature(letterState?.instance, fallback); } function closeLetter () { letterState = null; letterPanel.hidden = true; letterBackdrop.hidden = true; } function renderVault (grid, slots, { side = "vault", interactive = true } = {}) { grid.innerHTML = ""; (slots ?? []).forEach((slot, index) => { if (!slot) { return; } const button = document.createElement("button"); button.className = "item-slot"; if (writeChequeState && side === "vault" && writeChequeState.vaultSlotIndex === index) { button.classList.add("selected"); } button.title = tooltip(slot, { reserved: side === "reserved" }); const def = itemDefinition(slot.itemId); const img = document.createElement("img"); applyItemIcon(img, slot, itemAssetPathForStack(slot)); img.alt = itemDisplayName(slot); button.append(img); if (slot.quantity > 1) { const count = document.createElement("span"); count.className = "qty"; count.textContent = formatQuantity(slot.quantity); button.append(count); } if (interactive && side === "vault") { button.addEventListener("click", () => { if (writeChequeState) { writeChequeState.vaultSlotIndex = index; writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance ? 1 : availableMatching(slot); document.getElementById("write-cheque-item").textContent = `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`; const qtyInput = document.getElementById("write-cheque-qty"); qtyInput.value = "1"; qtyInput.max = String(writeChequeState.maxQty); qtyInput.disabled = writeChequeState.maxQty <= 1; document.getElementById("write-cheque-confirm").disabled = false; renderBank(); return; } transferSlot("vault", index, null); }); button.addEventListener("contextmenu", (event) => { event.preventDefault(); event.stopPropagation(); if (writeChequeState) { return; } showBankTransferMenu(event.clientX, event.clientY, "vault", index, slot); }); } grid.append(button); }); } function availableMatching (reference) { return countIdenticalInSlots(bag.vault ?? [], reference); } function availableOf (itemId) { let total = 0; for (const slot of bag.vault ?? []) { if (slot?.itemId === itemId) { total += slot.quantity | 0; } } return total; } function renderBank () { renderVault(vaultGrid, bag.vault, { side: "vault", interactive: true }); renderVault(vaultReservedGrid, bag.vaultReserved, { side: "reserved", interactive: false }); setBankTab(bankTab); } function tooltip (slot, { reserved = false } = {}) { if (!slot) { return ""; } const base = `${itemDisplayName(slot)}${slot.quantity > 1 ? ` ×${formatQuantity(slot.quantity)}` : ""}`; const origin = itemOriginSummary(slot); const desc = itemDescription(slot, { localCharacterId }); const lines = [base]; if (reserved) { lines.push(slot.chequeId ? "Reserved against a written cheque." : "Reserved in the vault."); } if (origin) { lines.push(origin); } if (desc) { lines.push(desc); } for (const extra of itemExtraTooltipLines(slot)) { lines.push(extra); } return lines.join("\n"); } return { isOpen () { return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden || !transferPanel.hidden || !writeChequePanel.hidden; }, isBankOpen () { return bankOpen; }, closeBank, closeOverlays () { closeBank(); closeSend(); closeLetter(); closeTransfer(); closeWriteCheque(); }, refreshBagDisplay () { render(); }, refreshMaxHit, isBlocking () { if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden || !transferPanel.hidden || !writeChequePanel.hidden) { return true; } if (sendBackdrop && !sendBackdrop.hidden) { return true; } if (letterBackdrop && !letterBackdrop.hidden) { return true; } if (transferBackdrop && !transferBackdrop.hidden) { return true; } if (writeChequeBackdrop && !writeChequeBackdrop.hidden) { return true; } const x = GameInput.mousePosition.x; const y = GameInput.mousePosition.y; for (const element of [bagPanel, bankPanel]) { if (!element || element.hidden) { continue; } const box = element.getBoundingClientRect(); if (x >= box.left && x < box.right && y >= box.top && y < box.bottom) { return true; } } return false; }, setLocalCharacterId (characterId) { localCharacterId = characterId; }, getLocalCharacterId () { return localCharacterId; }, getInventorySlots () { return bag.inventory ?? []; }, getBag () { return { slots: bag.inventory ?? [], equipment: bag.equipment ?? null }; }, getEquipment () { return bag.equipment?.slots ?? bag.equipment ?? {}; }, handleInventory (message) { bag = { ...bag, ...message }; render(); onBagChanged?.(); if (bankOpen) { renderBank(); syncBankTabs(); } if (writeChequeState) { renderWriteChequeVault(); } if (letterState && letterStatus.textContent === "Saving…") { letterStatus.textContent = "Saved."; if (letterState.mode === "write") { closeLetter(); } else if (letterState.mode === "edit") { const slot = bag.inventory?.[letterState.slotIndex]; if (slot?.instance) { letterState.instance = slot.instance; letterBody.value = slot.instance.body ?? ""; refreshLetterSignature(); fitLetterBody(); } } } }, handleBank (message) { bankOpen = true; bankPanel.hidden = false; bagPanel.hidden = false; bag.vault = message.vault ?? []; bag.vaultReserved = message.vaultReserved ?? []; inheritance = { slots: message.inheritance?.slots ?? [], currency: message.inheritance?.currency | 0 || 0 }; renderVault(inheritGrid, inheritance.slots, { interactive: false }); inheritGrid.querySelectorAll("button").forEach((button) => { button.onclick = null; }); const inheritCoins = document.getElementById("inherit-coins"); if (inheritCoins) { const coins = inheritance.currency | 0; inheritCoins.hidden = coins <= 0; inheritCoins.textContent = coins > 0 ? `${formatQuantity(coins)} coins` : ""; } setBankTab("available"); renderBank(); render(); }, getBlankCheques () { socket.send({ type: MessageType.getBlankCheques }); }, handlePigeonDispatched () { document.getElementById("send-status").textContent = "Pigeon is in flight."; closeSend(); }, handlePigeonDelivered (message) { const kind = message.destinationKind === "bank" ? "bank vault" : "recipient"; hint.textContent = `Pigeon delivered to ${kind}.`; }, handleCharacterSearch (message) { if (!pendingSearch) { return; } pendingSearch = false; sendSearchResult.replaceChildren(); if (!message.character) { sendSearchResult.textContent = "No character with that name."; return; } sendSearchResult.append(characterTargetRow(message.character)); }, reset () { bagPanel.hidden = true; closeBank(); selected = null; closeSend(); closeLetter(); } }; }