import { itemDefinition, itemDisplayName, itemAssetPathForStack, formatQuantity } from "/shared/definitions/items.js"; import { INVENTORY_SLOTS } from "/shared/items/inventory.js"; import { marketOrderListingFee } from "/shared/market/exchange.js"; import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js"; import { canSellOnMarketplace } from "/shared/items/marketplace.js"; import { applyItemIcon } from "../render/potionIcon.js"; export function initMarket ({ socket, MessageType, getInventorySlots, getCoinCount, getLocalCharacterId, onSuppressWorldClick }) { const backdrop = document.getElementById("market-backdrop"); const panel = document.getElementById("market-panel"); const title = document.getElementById("market-title"); const ordersEl = document.getElementById("market-orders"); const catalogEl = document.getElementById("market-catalog"); const sellList = document.getElementById("market-sell-list"); const sellSelected = document.getElementById("market-sell-selected"); const buyItem = document.getElementById("market-buy-item"); const buySearch = document.getElementById("market-buy-search"); const buyQty = document.getElementById("market-buy-qty"); const buyMax = document.getElementById("market-buy-max"); const buyFee = document.getElementById("market-buy-fee"); const sellQty = document.getElementById("market-sell-qty"); const sellMin = document.getElementById("market-sell-min"); const sellFee = document.getElementById("market-sell-fee"); const sellSuggest = document.getElementById("market-sell-suggest"); const coinsEl = document.getElementById("market-coins"); const hintEl = document.getElementById("market-hint"); const tabs = [...document.querySelectorAll(".market-tab")]; const panes = [...document.querySelectorAll(".market-pane")]; let open = false; let catalog = []; let orders = []; let searchHits = []; let selectedSellSlot = null; let selectedBuyItemId = null; let selectedBuyListingKey = null; let activeTab = "orders"; let sellQtyLocked = false; function suppressWorldClick () { onSuppressWorldClick?.(); } function setTab (tab) { activeTab = tab; for (const button of tabs) { button.classList.toggle("active", button.dataset.tab === tab); } for (const pane of panes) { pane.hidden = pane.dataset.pane !== tab; } if (tab === "sell") { renderSellables(); const slots = getInventorySlots?.() ?? []; const slot = selectedSellSlot == null ? null : slots[selectedSellSlot]; const listing = slot ? resolveMarketSellListing(slot) : null; updateSellSuggest(listing?.itemId ?? null, listing?.listingKey ?? null); } if (tab === "buy") { updateBuyFee(); } if (tab === "orders") { renderOrders(); } } for (const button of tabs) { button.addEventListener("click", () => setTab(button.dataset.tab)); } document.getElementById("market-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("mousedown", (event) => { event.preventDefault(); suppressWorldClick(); }); backdrop?.addEventListener("click", () => close()); panel?.addEventListener("mousedown", (event) => { event.stopPropagation(); suppressWorldClick(); }); buySearch?.addEventListener("keydown", (event) => { event.stopPropagation(); if (event.key !== "Enter") { return; } event.preventDefault(); runBuySearch(buySearch.value ?? ""); }); buySearch?.addEventListener("keyup", (event) => event.stopPropagation()); buyQty?.addEventListener("input", () => updateBuyFee()); buyMax?.addEventListener("input", () => updateBuyFee()); sellQty?.addEventListener("input", () => updateSellFee()); sellMin?.addEventListener("input", () => updateSellFee()); function catalogEntryMatches (entry) { return (entry.itemId | 0) === (selectedBuyItemId | 0) && (entry.listingKey ?? null) === (selectedBuyListingKey ?? null); } function selectBuyEntry (entry) { selectedBuyItemId = entry.itemId; selectedBuyListingKey = entry.listingKey ?? null; if (buyItem) { buyItem.textContent = entry.displayName; } if (buyMax && !(buyMax.valueAsNumber > 0)) { buyMax.value = String(entry.hintPrice); } renderCatalog(); updateBuyFee(); } document.getElementById("market-buy-confirm")?.addEventListener("click", () => { if (selectedBuyItemId == null) { return; } socket.send({ type: MessageType.placeMarketBuy, itemId: selectedBuyItemId, listingKey: selectedBuyListingKey, quantity: Math.max(1, buyQty?.valueAsNumber || 1), maxUnitPrice: Math.max(1, buyMax?.valueAsNumber || 1) }); }); document.getElementById("market-sell-confirm")?.addEventListener("click", () => { if (selectedSellSlot == null) { return; } socket.send({ type: MessageType.placeMarketSell, slotIndex: selectedSellSlot, quantity: Math.max(1, sellQty?.valueAsNumber || 1), minUnitPrice: Math.max(1, sellMin?.valueAsNumber || 1) }); }); sellSuggest?.addEventListener("click", () => { const price = Number(sellSuggest.dataset.price); if (!(price > 0) || !sellMin) { return; } sellMin.value = String(price); updateSellFee(); }); function close () { if (!open) { return; } open = false; if (backdrop) { backdrop.hidden = true; } if (panel) { panel.hidden = true; } socket.send({ type: MessageType.closeMarket }); } function runBuySearch (query) { const needle = String(query ?? "").trim().toLowerCase(); selectedBuyItemId = null; selectedBuyListingKey = null; if (buyItem) { buyItem.textContent = needle ? "Select an item" : "Search and select an item"; } if (!needle) { searchHits = []; renderCatalog(); updateBuyFee(); return; } searchHits = catalog .filter((entry) => entry.displayName.toLowerCase().includes(needle)) .slice(0, 10); renderCatalog(); updateBuyFee(); } function updateBuyFee () { const qty = Math.max(1, buyQty?.valueAsNumber || 1); const max = Math.max(1, buyMax?.valueAsNumber || 1); const fee = selectedBuyItemId == null ? 0 : marketOrderListingFee(max, qty); const escrow = selectedBuyItemId == null ? 0 : max * qty; if (buyFee) { buyFee.textContent = selectedBuyItemId == null ? "" : `Escrow ${formatQuantity(escrow)} + listing fee ${formatQuantity(fee)}.`; } } function updateSellFee () { const qty = Math.max(1, sellQty?.valueAsNumber || 1); const min = Math.max(1, sellMin?.valueAsNumber || 1); const fee = selectedSellSlot == null ? 0 : marketOrderListingFee(min, qty); if (sellFee) { sellFee.textContent = selectedSellSlot == null ? "" : `Listing fee ${formatQuantity(fee)}.`; } } function hintPriceForItem (itemId, listingKey = null) { const entry = catalog.find((row) => (row.itemId | 0) === (itemId | 0) && (row.listingKey ?? null) === (listingKey ?? null)); const price = entry?.hintPrice; if (price == null || !(Number(price) > 0)) { return null; } return Math.max(1, Math.ceil(Number(price))); } function updateSellSuggest (itemId = null, listingKey = null) { if (!sellSuggest) { return; } const price = itemId == null ? null : hintPriceForItem(itemId, listingKey); if (price == null) { sellSuggest.hidden = true; sellSuggest.dataset.price = ""; sellSuggest.textContent = ""; return; } sellSuggest.hidden = false; sellSuggest.dataset.price = String(price); sellSuggest.textContent = `Market ~${formatQuantity(price)}`; sellSuggest.title = "Suggested price based on market value."; } function renderOrders () { ordersEl.replaceChildren(); if (!orders.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No open orders."; ordersEl.append(empty); return; } for (const order of orders) { const row = document.createElement("div"); row.className = "market-order-row"; const label = document.createElement("span"); const priceLabel = order.side === "buy" ? `max ${order.limitUnitPrice}` : `min ${order.limitUnitPrice}`; label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${priceLabel}`; const cancel = document.createElement("button"); cancel.type = "button"; cancel.textContent = "Cancel"; cancel.addEventListener("click", () => { socket.send({ type: MessageType.cancelMarketOrder, orderId: order.orderId }); }); row.append(label, cancel); ordersEl.append(row); } } function renderCatalog () { catalogEl.replaceChildren(); if (!searchHits.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = (buySearch?.value ?? "").trim() ? "No matching items." : "Press Enter to search."; catalogEl.append(empty); return; } for (const entry of searchHits) { const row = document.createElement("button"); row.type = "button"; row.className = "market-catalog-row"; if (catalogEntryMatches(entry)) { row.classList.add("selected"); } row.textContent = `${entry.displayName} (~${entry.hintPrice})`; row.addEventListener("click", () => selectBuyEntry(entry)); catalogEl.append(row); } } function selectSellSlot (slotIndex, slot, listing) { selectedSellSlot = slotIndex; sellQtyLocked = !!listing.quantityLocked; if (sellQty) { sellQty.value = String(listing.quantityLocked ? listing.quantity : Math.min(listing.quantity, Math.max(1, slot.quantity | 0))); sellQty.readOnly = sellQtyLocked; sellQty.disabled = sellQtyLocked; if (!sellQtyLocked) { sellQty.max = String(Math.max(1, slot.quantity | 0)); } else { sellQty.removeAttribute("max"); } } if (sellSelected) { sellSelected.textContent = listing.isCheque ? `Selling cheque for ${listing.quantity}× ${listing.displayName}.` : `Selling ${itemDisplayName(slot)}`; } updateSellSuggest(listing.itemId, listing.listingKey ?? null); renderSellables(); updateSellFee(); } function renderSellables () { sellList.replaceChildren(); const slots = getInventorySlots?.() ?? []; const count = Math.max(INVENTORY_SLOTS, slots.length); for (let slotIndex = 0; slotIndex < count; slotIndex++) { const slot = slots[slotIndex] ?? null; const button = document.createElement("button"); button.type = "button"; const listing = slot ? resolveMarketSellListing(slot) : null; const sellable = !!listing && canSellOnMarketplace(slot, getLocalCharacterId?.() ?? null); button.className = `item-slot${selectedSellSlot === slotIndex ? " selected" : ""}`; if (slot && !sellable) { button.classList.add("disabled"); } button.title = slot ? (sellable ? (listing.isCheque ? `Cheque: ${listing.displayName} ×${formatQuantity(listing.quantity)}` : `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`) : `${itemDisplayName(slot)} (cannot list)`) : ""; if (slot) { const img = document.createElement("img"); img.alt = itemDisplayName(slot); applyItemIcon(img, slot, itemAssetPathForStack(slot)); button.append(img); if ((slot.quantity | 0) > 1) { const qty = document.createElement("span"); qty.className = "qty"; qty.textContent = formatQuantity(slot.quantity); button.append(qty); } } button.addEventListener("click", () => { if (!sellable) { return; } selectSellSlot(slotIndex, slot, listing); }); sellList.append(button); } } function refreshChrome () { const slots = getInventorySlots?.() ?? []; const funds = countMarketFunds(slots); const loose = getCoinCount?.() ?? 0; if (coinsEl) { coinsEl.textContent = funds === loose ? `Funds: ${formatQuantity(funds)}` : `Funds: ${formatQuantity(funds)} (coins + cheques)`; } if (activeTab === "sell") { renderSellables(); } updateBuyFee(); updateSellFee(); } return { handleOpen (payload) { open = true; orders = payload.orders ?? []; catalog = payload.catalog ?? []; searchHits = []; selectedSellSlot = null; selectedBuyItemId = null; selectedBuyListingKey = null; sellQtyLocked = false; updateSellSuggest(null); if (sellQty) { sellQty.readOnly = false; sellQty.disabled = false; sellQty.value = "1"; sellQty.removeAttribute("max"); } if (buySearch) { buySearch.value = ""; } if (sellSelected) { sellSelected.textContent = "Select an item from your bag"; } if (title) { title.textContent = payload.displayName || "Central Exchange"; } if (hintEl) { hintEl.textContent = "Placing an order costs a 3% listing fee."; } if (backdrop) { backdrop.hidden = false; } if (panel) { panel.hidden = false; } setTab("orders"); renderOrders(); renderCatalog(); refreshChrome(); }, handleClosed () { open = false; if (backdrop) { backdrop.hidden = true; } if (panel) { panel.hidden = true; } }, handleTrade () { if (open) { refreshChrome(); } }, refresh () { if (open) { refreshChrome(); } }, isOpen () { return open; }, isBlocking () { return open; }, close }; }