import { itemDefinition, itemDescription, itemAssetPathForStack, ItemId, EQUIPMENT_SLOT, LETTER_MAX_BODY_CHARS } from "/shared/definitions/items.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" }; export function initInventory ({ socket, MessageType, contextMenu, resolveSpriteUrl, getFriends, getLocalName }) { const bagPanel = document.getElementById("bag-panel"); const bagGrid = document.getElementById("bag-grid"); const equipGrid = document.getElementById("equip-grid"); const coins = document.getElementById("bag-coins"); const hint = document.getElementById("bag-hint"); const bankPanel = document.getElementById("bank-panel"); const vaultGrid = document.getElementById("vault-grid"); const vaultCoins = document.getElementById("vault-coins"); const inheritGrid = document.getElementById("inherit-grid"); const inheritCoins = document.getElementById("inherit-coins"); 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"); let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 }; let selected = null; let bankOpen = false; let sendState = null; let letterState = null; let pendingSearch = false; let localCharacterId = null; document.getElementById("bag-toggle").addEventListener("click", () => { bagPanel.hidden = !bagPanel.hidden; }); document.getElementById("bag-drop").addEventListener("click", () => { if (selected == null) { return; } socket.send({ type: MessageType.dropItem, slotIndex: selected }); }); document.getElementById("bag-equip").addEventListener("click", () => { if (selected == null) { return; } socket.send({ type: MessageType.equipItem, slotIndex: selected }); }); document.getElementById("bank-close").addEventListener("click", () => { bankOpen = false; bankPanel.hidden = true; }); document.getElementById("bank-claim").addEventListener("click", () => { socket.send({ type: MessageType.claimInheritance }); }); 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 render () { coins.textContent = `${bag.currency ?? 0} coins`; bagGrid.innerHTML = ""; (bag.inventory ?? []).forEach((slot, index) => { const button = document.createElement("button"); button.className = `item-slot${selected === index ? " selected" : ""}`; button.title = tooltip(slot); if (slot) { const def = itemDefinition(slot.itemId); const img = document.createElement("img"); img.src = itemAssetPathForStack(slot); img.alt = def?.displayName ?? ""; button.append(img); if (slot.quantity > 1) { const count = document.createElement("span"); count.className = "qty"; count.textContent = String(slot.quantity); button.append(count); } } button.addEventListener("click", () => { selected = index; hint.textContent = slot ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}: ${itemDescription(slot, { localCharacterId })}` : "Empty slot."; render(); }); button.addEventListener("contextmenu", (event) => { event.preventDefault(); event.stopPropagation(); if (!slot) { return; } selected = index; render(); 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.className = "item-slot"; button.title = worn ? tooltip(worn) : label; if (worn) { const def = itemDefinition(worn.itemId); const img = document.createElement("img"); img.src = itemAssetPathForStack(worn); img.alt = def?.displayName ?? label; button.append(img); } button.addEventListener("click", () => { if (worn) { socket.send({ type: MessageType.unequipItem, equipSlot: slot }); } }); equipGrid.append(button); } } 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.letter || isOwnLetter; 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 }) }); } } if (def?.equipment?.slot) { items.push({ label: "Equip", onSelect: () => socket.send({ type: MessageType.equipItem, slotIndex }) }); } if (canSend) { items.push({ label: "Send", onSelect: () => openSend(slotIndex, slot) }); } items.push({ label: "Drop", onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex }) }); contextMenu?.show(x, y, items); } function openSend (slotIndex, slot) { const def = itemDefinition(slot.itemId); sendState = { slotIndex, itemId: slot.itemId, maxQty: slot.quantity | 0, destination: null }; document.getElementById("send-item-img").src = itemAssetPathForStack(slot); document.getElementById("send-item-name").textContent = def?.displayName ?? "Item"; const qtyInput = document.getElementById("send-qty"); qtyInput.value = "1"; 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) { const wrap = document.createElement("div"); wrap.className = "char-preview"; for (const layer of layers ?? []) { const url = resolveSpriteUrl?.(layer.sprite); if (!url) { continue; } const img = document.createElement("img"); img.src = url; img.alt = ""; wrap.append(img); } return wrap; } 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 = 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 name = letterState?.instance?.authorDisplayName || getLocalName?.() || "Unknown"; letterSignature.textContent = `Signed:\n${name}`; } function closeLetter () { letterState = null; letterPanel.hidden = true; letterBackdrop.hidden = true; } function renderVault (grid, slots) { grid.innerHTML = ""; (slots ?? []).forEach((slot, index) => { const button = document.createElement("button"); button.className = "item-slot"; button.title = tooltip(slot); button.textContent = slot ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}` : ""; button.addEventListener("click", () => { if (!slot) { return; } socket.send({ type: MessageType.bankWithdraw, slotIndex: index }); }); grid.append(button); }); } function tooltip (slot) { if (!slot) { return ""; } const def = itemDefinition(slot.itemId); return `${def?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`; } return { isOpen () { return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden; }, isBlocking () { // Send/letter dialogs cover the view — keep world clicks blocked. if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden) { return true; } if (sendBackdrop && !sendBackdrop.hidden) { return true; } if (letterBackdrop && !letterBackdrop.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; }, handleInventory (message) { bag = { ...bag, ...message }; render(); 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; bag.vault = message.vault; bag.vaultCurrency = message.vaultCurrency; vaultCoins.textContent = `${message.vaultCurrency ?? 0} coins in vault · you carry ${message.currency ?? 0}`; inheritCoins.textContent = `${message.inheritance?.currency ?? 0} coins waiting`; renderVault(vaultGrid, message.vault); renderVault(inheritGrid, message.inheritance?.slots ?? []); inheritGrid.querySelectorAll("button").forEach((button) => { button.onclick = null; }); render(); }, depositSelected () { if (selected == null) { return; } socket.send({ type: MessageType.bankDeposit, slotIndex: selected }); }, 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; bankPanel.hidden = true; bankOpen = false; selected = null; closeSend(); closeLetter(); } }; }