BlueGit

timfa questward

Files

questward / client / src / play / market.js

market.js

market.js 12.8 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6} from "/shared/definitions/items.js";
7import { INVENTORY_SLOTS } from "/shared/items/inventory.js";
8import { marketOrderListingFee } from "/shared/market/exchange.js";
9import { countMarketFunds, resolveMarketSellListing } from "/shared/market/funds.js";
10import { canSellOnMarketplace } from "/shared/items/marketplace.js";
11import { applyItemIcon } from "../render/potionIcon.js";
12
13export function initMarket ({
14 socket,
15 MessageType,
16 getInventorySlots,
17 getCoinCount,
18 getLocalCharacterId,
19 onSuppressWorldClick
20})
21{
22 const backdrop = document.getElementById("market-backdrop");
23 const panel = document.getElementById("market-panel");
24 const title = document.getElementById("market-title");
25 const ordersEl = document.getElementById("market-orders");
26 const catalogEl = document.getElementById("market-catalog");
27 const sellList = document.getElementById("market-sell-list");
28 const sellSelected = document.getElementById("market-sell-selected");
29 const buyItem = document.getElementById("market-buy-item");
30 const buySearch = document.getElementById("market-buy-search");
31 const buyQty = document.getElementById("market-buy-qty");
32 const buyMax = document.getElementById("market-buy-max");
33 const buyFee = document.getElementById("market-buy-fee");
34 const sellQty = document.getElementById("market-sell-qty");
35 const sellMin = document.getElementById("market-sell-min");
36 const sellFee = document.getElementById("market-sell-fee");
37 const sellSuggest = document.getElementById("market-sell-suggest");
38 const coinsEl = document.getElementById("market-coins");
39 const hintEl = document.getElementById("market-hint");
40 const tabs = [...document.querySelectorAll(".market-tab")];
41 const panes = [...document.querySelectorAll(".market-pane")];
42
43 let open = false;
44 let catalog = [];
45 let orders = [];
46 let searchHits = [];
47 let selectedSellSlot = null;
48 let selectedBuyItemId = null;
49 let selectedBuyListingKey = null;
50 let activeTab = "orders";
51 let sellQtyLocked = false;
52
53 function suppressWorldClick ()
54 {
55 onSuppressWorldClick?.();
56 }
57
58 function setTab (tab)
59 {
60 activeTab = tab;
61 for (const button of tabs)
62 { button.classList.toggle("active", button.dataset.tab === tab); }
63 for (const pane of panes)
64 { pane.hidden = pane.dataset.pane !== tab; }
65 if (tab === "sell")
66 {
67 renderSellables();
68 const slots = getInventorySlots?.() ?? [];
69 const slot = selectedSellSlot == null ? null : slots[selectedSellSlot];
70 const listing = slot ? resolveMarketSellListing(slot) : null;
71 updateSellSuggest(listing?.itemId ?? null, listing?.listingKey ?? null);
72 }
73 if (tab === "buy")
74 { updateBuyFee(); }
75 if (tab === "orders")
76 { renderOrders(); }
77 }
78
79 for (const button of tabs)
80 {
81 button.addEventListener("click", () => setTab(button.dataset.tab));
82 }
83
84 document.getElementById("market-close")?.addEventListener("click", () => close());
85 backdrop?.addEventListener("mousedown", (event) =>
86 {
87 event.preventDefault();
88 suppressWorldClick();
89 });
90 backdrop?.addEventListener("click", () => close());
91 panel?.addEventListener("mousedown", (event) =>
92 {
93 event.stopPropagation();
94 suppressWorldClick();
95 });
96
97 buySearch?.addEventListener("keydown", (event) =>
98 {
99 event.stopPropagation();
100 if (event.key !== "Enter")
101 { return; }
102 event.preventDefault();
103 runBuySearch(buySearch.value ?? "");
104 });
105 buySearch?.addEventListener("keyup", (event) => event.stopPropagation());
106
107 buyQty?.addEventListener("input", () => updateBuyFee());
108 buyMax?.addEventListener("input", () => updateBuyFee());
109 sellQty?.addEventListener("input", () => updateSellFee());
110 sellMin?.addEventListener("input", () => updateSellFee());
111
112 function catalogEntryMatches (entry)
113 {
114 return (entry.itemId | 0) === (selectedBuyItemId | 0)
115 && (entry.listingKey ?? null) === (selectedBuyListingKey ?? null);
116 }
117
118 function selectBuyEntry (entry)
119 {
120 selectedBuyItemId = entry.itemId;
121 selectedBuyListingKey = entry.listingKey ?? null;
122 if (buyItem)
123 { buyItem.textContent = entry.displayName; }
124 if (buyMax && !(buyMax.valueAsNumber > 0))
125 { buyMax.value = String(entry.hintPrice); }
126 renderCatalog();
127 updateBuyFee();
128 }
129
130 document.getElementById("market-buy-confirm")?.addEventListener("click", () =>
131 {
132 if (selectedBuyItemId == null)
133 { return; }
134 socket.send({
135 type: MessageType.placeMarketBuy,
136 itemId: selectedBuyItemId,
137 listingKey: selectedBuyListingKey,
138 quantity: Math.max(1, buyQty?.valueAsNumber || 1),
139 maxUnitPrice: Math.max(1, buyMax?.valueAsNumber || 1)
140 });
141 });
142
143 document.getElementById("market-sell-confirm")?.addEventListener("click", () =>
144 {
145 if (selectedSellSlot == null)
146 { return; }
147 socket.send({
148 type: MessageType.placeMarketSell,
149 slotIndex: selectedSellSlot,
150 quantity: Math.max(1, sellQty?.valueAsNumber || 1),
151 minUnitPrice: Math.max(1, sellMin?.valueAsNumber || 1)
152 });
153 });
154
155 sellSuggest?.addEventListener("click", () =>
156 {
157 const price = Number(sellSuggest.dataset.price);
158 if (!(price > 0) || !sellMin)
159 { return; }
160 sellMin.value = String(price);
161 updateSellFee();
162 });
163
164 function close ()
165 {
166 if (!open)
167 { return; }
168 open = false;
169 if (backdrop)
170 { backdrop.hidden = true; }
171 if (panel)
172 { panel.hidden = true; }
173 socket.send({ type: MessageType.closeMarket });
174 }
175
176 function runBuySearch (query)
177 {
178 const needle = String(query ?? "").trim().toLowerCase();
179 selectedBuyItemId = null;
180 selectedBuyListingKey = null;
181 if (buyItem)
182 { buyItem.textContent = needle ? "Select an item" : "Search and select an item"; }
183 if (!needle)
184 {
185 searchHits = [];
186 renderCatalog();
187 updateBuyFee();
188 return;
189 }
190 searchHits = catalog
191 .filter((entry) => entry.displayName.toLowerCase().includes(needle))
192 .slice(0, 10);
193 renderCatalog();
194 updateBuyFee();
195 }
196
197 function updateBuyFee ()
198 {
199 const qty = Math.max(1, buyQty?.valueAsNumber || 1);
200 const max = Math.max(1, buyMax?.valueAsNumber || 1);
201 const fee = selectedBuyItemId == null ? 0 : marketOrderListingFee(max, qty);
202 const escrow = selectedBuyItemId == null ? 0 : max * qty;
203 if (buyFee)
204 {
205 buyFee.textContent = selectedBuyItemId == null
206 ? ""
207 : `Escrow ${formatQuantity(escrow)} + listing fee ${formatQuantity(fee)}.`;
208 }
209 }
210
211 function updateSellFee ()
212 {
213 const qty = Math.max(1, sellQty?.valueAsNumber || 1);
214 const min = Math.max(1, sellMin?.valueAsNumber || 1);
215 const fee = selectedSellSlot == null ? 0 : marketOrderListingFee(min, qty);
216 if (sellFee)
217 {
218 sellFee.textContent = selectedSellSlot == null
219 ? ""
220 : `Listing fee ${formatQuantity(fee)}.`;
221 }
222 }
223
224 function hintPriceForItem (itemId, listingKey = null)
225 {
226 const entry = catalog.find((row) => (row.itemId | 0) === (itemId | 0)
227 && (row.listingKey ?? null) === (listingKey ?? null));
228 const price = entry?.hintPrice;
229 if (price == null || !(Number(price) > 0))
230 { return null; }
231 return Math.max(1, Math.ceil(Number(price)));
232 }
233
234 function updateSellSuggest (itemId = null, listingKey = null)
235 {
236 if (!sellSuggest)
237 { return; }
238 const price = itemId == null ? null : hintPriceForItem(itemId, listingKey);
239 if (price == null)
240 {
241 sellSuggest.hidden = true;
242 sellSuggest.dataset.price = "";
243 sellSuggest.textContent = "";
244 return;
245 }
246 sellSuggest.hidden = false;
247 sellSuggest.dataset.price = String(price);
248 sellSuggest.textContent = `Market ~${formatQuantity(price)}`;
249 sellSuggest.title = "Suggested price based on market value.";
250 }
251
252 function renderOrders ()
253 {
254 ordersEl.replaceChildren();
255 if (!orders.length)
256 {
257 const empty = document.createElement("p");
258 empty.className = "hint";
259 empty.textContent = "No open orders.";
260 ordersEl.append(empty);
261 return;
262 }
263 for (const order of orders)
264 {
265 const row = document.createElement("div");
266 row.className = "market-order-row";
267 const label = document.createElement("span");
268 const priceLabel = order.side === "buy"
269 ? `max ${order.limitUnitPrice}`
270 : `min ${order.limitUnitPrice}`;
271 label.textContent = `${order.side === "buy" ? "Buy" : "Sell"} ${order.quantity}× ${order.displayName} @ ${priceLabel}`;
272 const cancel = document.createElement("button");
273 cancel.type = "button";
274 cancel.textContent = "Cancel";
275 cancel.addEventListener("click", () =>
276 {
277 socket.send({
278 type: MessageType.cancelMarketOrder,
279 orderId: order.orderId
280 });
281 });
282 row.append(label, cancel);
283 ordersEl.append(row);
284 }
285 }
286
287 function renderCatalog ()
288 {
289 catalogEl.replaceChildren();
290 if (!searchHits.length)
291 {
292 const empty = document.createElement("p");
293 empty.className = "hint";
294 empty.textContent = (buySearch?.value ?? "").trim()
295 ? "No matching items."
296 : "Press Enter to search.";
297 catalogEl.append(empty);
298 return;
299 }
300 for (const entry of searchHits)
301 {
302 const row = document.createElement("button");
303 row.type = "button";
304 row.className = "market-catalog-row";
305 if (catalogEntryMatches(entry))
306 { row.classList.add("selected"); }
307 row.textContent = `${entry.displayName} (~${entry.hintPrice})`;
308 row.addEventListener("click", () => selectBuyEntry(entry));
309 catalogEl.append(row);
310 }
311 }
312
313 function selectSellSlot (slotIndex, slot, listing)
314 {
315 selectedSellSlot = slotIndex;
316 sellQtyLocked = !!listing.quantityLocked;
317 if (sellQty)
318 {
319 sellQty.value = String(listing.quantityLocked
320 ? listing.quantity
321 : Math.min(listing.quantity, Math.max(1, slot.quantity | 0)));
322 sellQty.readOnly = sellQtyLocked;
323 sellQty.disabled = sellQtyLocked;
324 if (!sellQtyLocked)
325 { sellQty.max = String(Math.max(1, slot.quantity | 0)); }
326 else
327 { sellQty.removeAttribute("max"); }
328 }
329 if (sellSelected)
330 {
331 sellSelected.textContent = listing.isCheque
332 ? `Selling cheque for ${listing.quantity}× ${listing.displayName}.`
333 : `Selling ${itemDisplayName(slot)}`;
334 }
335 updateSellSuggest(listing.itemId, listing.listingKey ?? null);
336 renderSellables();
337 updateSellFee();
338 }
339
340 function renderSellables ()
341 {
342 sellList.replaceChildren();
343 const slots = getInventorySlots?.() ?? [];
344 const count = Math.max(INVENTORY_SLOTS, slots.length);
345 for (let slotIndex = 0; slotIndex < count; slotIndex++)
346 {
347 const slot = slots[slotIndex] ?? null;
348 const button = document.createElement("button");
349 button.type = "button";
350 const listing = slot ? resolveMarketSellListing(slot) : null;
351 const sellable = !!listing && canSellOnMarketplace(slot, getLocalCharacterId?.() ?? null);
352 button.className = `item-slot${selectedSellSlot === slotIndex ? " selected" : ""}`;
353 if (slot && !sellable)
354 { button.classList.add("disabled"); }
355 button.title = slot
356 ? (sellable
357 ? (listing.isCheque
358 ? `Cheque: ${listing.displayName} ×${formatQuantity(listing.quantity)}`
359 : `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`)
360 : `${itemDisplayName(slot)} (cannot list)`)
361 : "";
362 if (slot)
363 {
364 const img = document.createElement("img");
365 img.alt = itemDisplayName(slot);
366 applyItemIcon(img, slot, itemAssetPathForStack(slot));
367 button.append(img);
368 if ((slot.quantity | 0) > 1)
369 {
370 const qty = document.createElement("span");
371 qty.className = "qty";
372 qty.textContent = formatQuantity(slot.quantity);
373 button.append(qty);
374 }
375 }
376 button.addEventListener("click", () =>
377 {
378 if (!sellable)
379 { return; }
380 selectSellSlot(slotIndex, slot, listing);
381 });
382 sellList.append(button);
383 }
384 }
385
386 function refreshChrome ()
387 {
388 const slots = getInventorySlots?.() ?? [];
389 const funds = countMarketFunds(slots);
390 const loose = getCoinCount?.() ?? 0;
391 if (coinsEl)
392 {
393 coinsEl.textContent = funds === loose
394 ? `Funds: ${formatQuantity(funds)}`
395 : `Funds: ${formatQuantity(funds)} (coins + cheques)`;
396 }
397 if (activeTab === "sell")
398 { renderSellables(); }
399 updateBuyFee();
400 updateSellFee();
401 }
402
403 return {
404 handleOpen (payload)
405 {
406 open = true;
407 orders = payload.orders ?? [];
408 catalog = payload.catalog ?? [];
409 searchHits = [];
410 selectedSellSlot = null;
411 selectedBuyItemId = null;
412 selectedBuyListingKey = null;
413 sellQtyLocked = false;
414 updateSellSuggest(null);
415 if (sellQty)
416 {
417 sellQty.readOnly = false;
418 sellQty.disabled = false;
419 sellQty.value = "1";
420 sellQty.removeAttribute("max");
421 }
422 if (buySearch)
423 { buySearch.value = ""; }
424 if (sellSelected)
425 { sellSelected.textContent = "Select an item from your bag"; }
426 if (title)
427 { title.textContent = payload.displayName || "Central Exchange"; }
428 if (hintEl)
429 {
430 hintEl.textContent = "Placing an order costs a 3% listing fee.";
431 }
432 if (backdrop)
433 { backdrop.hidden = false; }
434 if (panel)
435 { panel.hidden = false; }
436 setTab("orders");
437 renderOrders();
438 renderCatalog();
439 refreshChrome();
440 },
441 handleClosed ()
442 {
443 open = false;
444 if (backdrop)
445 { backdrop.hidden = true; }
446 if (panel)
447 { panel.hidden = true; }
448 },
449 handleTrade ()
450 {
451 if (open)
452 { refreshChrome(); }
453 },
454 refresh ()
455 {
456 if (open)
457 { refreshChrome(); }
458 },
459 isOpen ()
460 {
461 return open;
462 },
463 isBlocking ()
464 {
465 return open;
466 },
467 close
468 };
469}