BlueGit

timfa questward

Files

questward / client / src / play / market.js

market.js

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