BlueGit

timfa questward

Files

questward / client / src / play / shop.js

shop.js

shop.js 15.8 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6} from "/shared/definitions/items.js";
7import { insertStack, stackQuantity } from "/shared/items/inventory.js";
8import {
9 canPlayerSellToNpc,
10 resolveShopSellQuote
11} from "/shared/shop/pricing.js";
12import { subjectPronoun } from "/shared/speech/pronouns.js";
13import { applyItemIcon } from "../render/potionIcon.js";
14
15export function initShop ({
16 socket,
17 MessageType,
18 getCoinCount,
19 getInventorySlots,
20 onSuppressWorldClick
21})
22{
23 const backdrop = document.getElementById("shop-backdrop");
24 const panel = document.getElementById("shop-panel");
25 const title = document.getElementById("shop-title");
26 const tabBuy = document.getElementById("shop-tab-buy");
27 const tabSell = document.getElementById("shop-tab-sell");
28 const paneBuy = document.getElementById("shop-pane-buy");
29 const paneSell = document.getElementById("shop-pane-sell");
30 const grid = document.getElementById("shop-grid");
31 const detail = document.getElementById("shop-detail");
32 const detailIcon = document.getElementById("shop-detail-icon");
33 const detailName = document.getElementById("shop-detail-name");
34 const detailPrice = document.getElementById("shop-detail-price");
35 const detailStock = document.getElementById("shop-detail-stock");
36 const bagWarn = document.getElementById("shop-bag-warn");
37 const coinsEl = document.getElementById("shop-coins");
38 const sellGrid = document.getElementById("shop-sell-grid");
39 const sellDetail = document.getElementById("shop-sell-detail");
40 const sellIcon = document.getElementById("shop-sell-icon");
41 const sellName = document.getElementById("shop-sell-name");
42 const sellPrice = document.getElementById("shop-sell-price");
43 const sellFee = document.getElementById("shop-sell-fee");
44 const sellActions = document.getElementById("shop-sell-actions");
45 const sellEmpty = document.getElementById("shop-sell-empty");
46 const qtyBackdrop = document.getElementById("shop-qty-backdrop");
47 const qtyPanel = document.getElementById("shop-qty-panel");
48 const qtyTitle = document.getElementById("shop-qty-title");
49 const qtyConfirm = document.getElementById("shop-qty-confirm");
50 const qtyInput = document.getElementById("shop-qty-input");
51 const qtyHint = document.getElementById("shop-qty-hint");
52
53 let npcEntityId = null;
54 let stock = [];
55 let selectedListingId = null;
56 let selectedSellSlotIndex = null;
57 let buysItems = false;
58 let displayName = "Shop";
59 let sex = "male";
60 /** @type {"buy"|"sell"} */
61 let activeTab = "buy";
62 /** @type {"buy"|"sell"|null} */
63 let qtyMode = null;
64
65 function suppressWorldClick ()
66 {
67 onSuppressWorldClick?.();
68 }
69
70 document.getElementById("shop-close")?.addEventListener("click", () => close());
71 backdrop?.addEventListener("mousedown", (event) =>
72 {
73 event.preventDefault();
74 suppressWorldClick();
75 });
76 backdrop?.addEventListener("click", () => close());
77 panel?.addEventListener("mousedown", (event) =>
78 {
79 event.stopPropagation();
80 suppressWorldClick();
81 });
82 qtyBackdrop?.addEventListener("mousedown", (event) =>
83 {
84 event.preventDefault();
85 suppressWorldClick();
86 });
87 qtyPanel?.addEventListener("mousedown", (event) =>
88 {
89 event.stopPropagation();
90 suppressWorldClick();
91 });
92 tabBuy?.addEventListener("click", () => setTab("buy"));
93 tabSell?.addEventListener("click", () => setTab("sell"));
94 document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1));
95 document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5));
96 document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10));
97 document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal("buy"));
98 document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal());
99 qtyConfirm?.addEventListener("click", () => confirmQtyModal());
100 qtyBackdrop?.addEventListener("click", () => closeQtyModal());
101 qtyInput?.addEventListener("keydown", (event) =>
102 {
103 if (event.key === "Enter")
104 { confirmQtyModal(); }
105 });
106
107 function setTab (tab)
108 {
109 if (tab === "sell" && !buysItems)
110 { tab = "buy"; }
111 activeTab = tab;
112 const buyActive = tab === "buy";
113 if (tabBuy)
114 {
115 tabBuy.classList.toggle("active", buyActive);
116 tabBuy.setAttribute("aria-selected", buyActive ? "true" : "false");
117 }
118 if (tabSell)
119 {
120 tabSell.classList.toggle("active", !buyActive);
121 tabSell.setAttribute("aria-selected", buyActive ? "false" : "true");
122 }
123 if (paneBuy)
124 { paneBuy.hidden = !buyActive; }
125 if (paneSell)
126 { paneSell.hidden = buyActive; }
127 render();
128 }
129
130 function open (payload)
131 {
132 npcEntityId = payload.npcEntityId | 0;
133 displayName = payload.displayName || "Shop";
134 sex = payload.sex === "female" ? "female" : "male";
135 title.textContent = displayName;
136 buysItems = !!payload.buysItems;
137 stock = Array.isArray(payload.stock) ? payload.stock : [];
138 if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId))
139 { selectedListingId = stock[0]?.listingId ?? null; }
140 if (tabSell)
141 { tabSell.hidden = !buysItems; }
142 closeQtyModal();
143 setTab(buysItems && activeTab === "sell" ? "sell" : "buy");
144 backdrop.hidden = false;
145 panel.hidden = false;
146 suppressWorldClick();
147 }
148
149 function close ({ notifyServer = true } = {})
150 {
151 const closingNpcId = npcEntityId;
152 closeQtyModal();
153 backdrop.hidden = true;
154 panel.hidden = true;
155 npcEntityId = null;
156 stock = [];
157 selectedListingId = null;
158 selectedSellSlotIndex = null;
159 buysItems = false;
160 sex = "male";
161 activeTab = "buy";
162 suppressWorldClick();
163 if (notifyServer && closingNpcId)
164 {
165 socket.send({
166 type: MessageType.closeShop,
167 npcEntityId: closingNpcId
168 });
169 }
170 }
171
172 function selectedEntry ()
173 {
174 return stock.find((row) => row.listingId === selectedListingId) ?? null;
175 }
176
177 function maxBuyable (entry)
178 {
179 const price = Math.max(1, entry?.unitPrice | 0 || 1);
180 const coins = getCoinCount?.() ?? 0;
181 const affordable = Math.max(0, Math.floor(coins / price));
182 const available = entry?.available == null ? affordable : Math.max(0, entry.available | 0);
183 return Math.min(affordable, available);
184 }
185
186 function inventoryFits (itemId, quantity)
187 {
188 const def = itemDefinition(itemId);
189 if (!def)
190 { return false; }
191 const slots = getInventorySlots?.() ?? [];
192 const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), {
193 itemId,
194 quantity: Math.max(1, quantity | 0 || 1)
195 }, def);
196 return added.ok && added.remainder === 0;
197 }
198
199 function buy (quantity)
200 {
201 const entry = selectedEntry();
202 if (!npcEntityId || !entry)
203 { return; }
204 const qty = Math.max(1, quantity | 0 || 1);
205 const max = maxBuyable(entry);
206 if (qty > max)
207 { return; }
208 socket.send({
209 type: MessageType.buyFromShop,
210 npcEntityId,
211 itemId: entry.itemId,
212 quantity: qty,
213 listingId: entry.listingId,
214 source: entry.source
215 });
216 }
217
218 function openQtyModal (mode)
219 {
220 qtyMode = mode;
221 if (mode === "buy")
222 {
223 const entry = selectedEntry();
224 if (!entry)
225 { return; }
226 const max = maxBuyable(entry);
227 if (max < 1)
228 { return; }
229 if (qtyTitle)
230 { qtyTitle.textContent = "Buy quantity"; }
231 if (qtyConfirm)
232 { qtyConfirm.textContent = "Buy"; }
233 qtyInput.min = "1";
234 qtyInput.max = String(max);
235 qtyInput.value = String(Math.min(max, 1));
236 qtyHint.textContent = `Max ${max}`;
237 }
238 else
239 {
240 const slot = selectedSellSlot();
241 if (!slot)
242 { return; }
243 const max = Math.max(1, stackQuantity(slot.quantity));
244 if (max < 4)
245 { return; }
246 if (qtyTitle)
247 { qtyTitle.textContent = "Sell quantity"; }
248 if (qtyConfirm)
249 { qtyConfirm.textContent = "Sell"; }
250 qtyInput.min = "1";
251 qtyInput.max = String(max);
252 qtyInput.value = "1";
253 qtyHint.textContent = `Max ${max}`;
254 }
255 qtyBackdrop.hidden = false;
256 qtyPanel.hidden = false;
257 suppressWorldClick();
258 qtyInput.focus();
259 qtyInput.select();
260 }
261
262 function closeQtyModal ()
263 {
264 qtyMode = null;
265 qtyBackdrop.hidden = true;
266 qtyPanel.hidden = true;
267 }
268
269 function confirmQtyModal ()
270 {
271 if (qtyMode === "sell")
272 {
273 const slot = selectedSellSlot();
274 if (!slot)
275 {
276 closeQtyModal();
277 return;
278 }
279 const max = Math.max(1, stackQuantity(slot.quantity));
280 const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1));
281 closeQtyModal();
282 sellQuantity(qty);
283 return;
284 }
285 const entry = selectedEntry();
286 if (!entry)
287 {
288 closeQtyModal();
289 return;
290 }
291 const max = maxBuyable(entry);
292 const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1));
293 closeQtyModal();
294 buy(qty);
295 }
296
297 function selectedSellSlot ()
298 {
299 if (selectedSellSlotIndex == null)
300 { return null; }
301 const slots = getInventorySlots?.() ?? [];
302 const slot = slots[selectedSellSlotIndex];
303 if (!slot?.itemId || !canPlayerSellToNpc(slot))
304 { return null; }
305 return slot;
306 }
307
308 function sellQuantity (quantity)
309 {
310 if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot())
311 { return; }
312 const slot = selectedSellSlot();
313 const max = Math.max(1, stackQuantity(slot.quantity));
314 const qty = Math.min(max, Math.max(1, quantity | 0 || 1));
315 socket.send({
316 type: MessageType.sellToShop,
317 npcEntityId,
318 slotIndex: selectedSellSlotIndex,
319 quantity: qty
320 });
321 }
322
323 function renderSellActions (slot)
324 {
325 if (!sellActions)
326 { return; }
327 sellActions.replaceChildren();
328 const qty = Math.max(1, stackQuantity(slot.quantity));
329 const addBtn = (label, onClick) =>
330 {
331 const btn = document.createElement("button");
332 btn.type = "button";
333 btn.textContent = label;
334 btn.addEventListener("click", onClick);
335 sellActions.append(btn);
336 };
337 if (qty <= 1)
338 {
339 addBtn("Sell", () => sellQuantity(1));
340 return;
341 }
342 addBtn("Sell 1", () => sellQuantity(1));
343 if (qty === 2)
344 {
345 addBtn("Sell all", () => sellQuantity(qty));
346 return;
347 }
348 if (qty === 3)
349 {
350 addBtn("Sell 2", () => sellQuantity(2));
351 addBtn("Sell all", () => sellQuantity(qty));
352 return;
353 }
354 addBtn("Sell x", () => openQtyModal("sell"));
355 addBtn("Sell all", () => sellQuantity(qty));
356 }
357
358 function renderSellDetail ()
359 {
360 if (!sellDetail || !sellPrice || !sellFee)
361 { return; }
362 const slot = selectedSellSlot();
363 if (!slot)
364 {
365 sellDetail.hidden = true;
366 sellFee.hidden = true;
367 if (sellActions)
368 { sellActions.replaceChildren(); }
369 return;
370 }
371 const quote = resolveShopSellQuote(slot, {
372 quantity: Math.max(1, stackQuantity(slot.quantity))
373 });
374 const unitQuote = resolveShopSellQuote(slot, { quantity: 1 });
375 if (!quote || !unitQuote)
376 {
377 sellDetail.hidden = true;
378 sellFee.hidden = true;
379 return;
380 }
381 sellDetail.hidden = false;
382 if (sellEmpty)
383 { sellEmpty.hidden = true; }
384 const name = itemDisplayName(slot);
385 if (sellName)
386 { sellName.textContent = name; }
387 if (sellIcon)
388 { applyItemIcon(sellIcon, slot, itemAssetPathForStack(slot)); }
389 sellPrice.textContent = quote.isCheque
390 ? `You receive ${formatQuantity(quote.payout)} coins`
391 : `${formatQuantity(unitQuote.unitPrice)} coins each`;
392 if (quote.isCheque)
393 {
394 sellFee.hidden = false;
395 sellFee.textContent = `${formatQuantity(quote.adminFee)} coins charged as administrative fee`;
396 }
397 else
398 {
399 sellFee.hidden = true;
400 sellFee.textContent = "";
401 }
402 renderSellActions(slot);
403 }
404
405 function renderSellPane ()
406 {
407 if (!sellGrid)
408 { return; }
409 sellGrid.replaceChildren();
410 if (!buysItems)
411 { return; }
412 const slots = getInventorySlots?.() ?? [];
413 const sellableIndexes = [];
414 slots.forEach((slot, slotIndex) =>
415 {
416 if (slot?.itemId && canPlayerSellToNpc(slot))
417 { sellableIndexes.push(slotIndex); }
418 });
419 if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex))
420 { selectedSellSlotIndex = null; }
421 if (!sellableIndexes.length)
422 {
423 selectedSellSlotIndex = null;
424 if (sellDetail)
425 { sellDetail.hidden = true; }
426 if (sellEmpty)
427 { sellEmpty.hidden = true; }
428 const note = document.createElement("p");
429 note.className = "hint";
430 note.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;
431 sellGrid.append(note);
432 return;
433 }
434 if (sellEmpty)
435 { sellEmpty.hidden = true; }
436 if (selectedSellSlotIndex == null)
437 {
438 if (sellDetail)
439 {
440 sellDetail.hidden = false;
441 if (sellName)
442 { sellName.textContent = "Select an item"; }
443 if (sellIcon)
444 {
445 sellIcon.removeAttribute("src");
446 sellIcon.alt = "";
447 }
448 if (sellPrice)
449 { sellPrice.textContent = ""; }
450 if (sellFee)
451 { sellFee.hidden = true; }
452 if (sellActions)
453 { sellActions.replaceChildren(); }
454 }
455 }
456 slots.forEach((slot, slotIndex) =>
457 {
458 const button = document.createElement("button");
459 button.type = "button";
460 button.className = "item-slot";
461 const sellable = !!slot?.itemId && canPlayerSellToNpc(slot);
462 if (!slot)
463 {
464 button.disabled = true;
465 sellGrid.append(button);
466 return;
467 }
468 if (!sellable)
469 { button.classList.add("disabled"); }
470 if (slotIndex === selectedSellSlotIndex)
471 { button.classList.add("selected"); }
472 const img = document.createElement("img");
473 img.alt = itemDisplayName(slot);
474 applyItemIcon(img, slot, itemAssetPathForStack(slot));
475 button.append(img);
476 const qty = stackQuantity(slot.quantity);
477 if (qty > 1)
478 {
479 const count = document.createElement("span");
480 count.className = "qty";
481 count.textContent = formatQuantity(qty);
482 button.append(count);
483 }
484 button.title = itemDisplayName(slot);
485 button.addEventListener("click", () =>
486 {
487 if (!sellable)
488 { return; }
489 selectedSellSlotIndex = slotIndex;
490 render();
491 });
492 sellGrid.append(button);
493 });
494 if (selectedSellSlotIndex != null)
495 { renderSellDetail(); }
496 }
497
498 function renderBuyPane ()
499 {
500 grid.innerHTML = "";
501 if (!stock.length)
502 {
503 grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale.";
504 detail.hidden = true;
505 bagWarn.hidden = true;
506 return;
507 }
508
509 for (const entry of stock)
510 {
511 const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
512 const btn = document.createElement("button");
513 btn.type = "button";
514 btn.className = "shop-cell";
515 if (entry.listingId === selectedListingId)
516 { btn.classList.add("selected"); }
517 btn.title = name;
518 const img = document.createElement("img");
519 img.alt = name;
520 applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
521 btn.append(img);
522 btn.addEventListener("click", () =>
523 {
524 selectedListingId = entry.listingId;
525 render();
526 });
527 grid.append(btn);
528 }
529
530 const entry = selectedEntry();
531 if (!entry)
532 {
533 detail.hidden = true;
534 bagWarn.hidden = true;
535 return;
536 }
537
538 detail.hidden = false;
539 const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
540 detailName.textContent = name;
541 detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`;
542 detailStock.textContent = entry.available == null
543 ? "In stock"
544 : `Stock: ${formatQuantity(entry.available)}`;
545 applyItemIcon(detailIcon, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
546
547 const max = maxBuyable(entry);
548 const setBuy = (id, qty) =>
549 {
550 const el = document.getElementById(id);
551 if (!el)
552 { return; }
553 el.disabled = max < qty;
554 };
555 setBuy("shop-buy-1", 1);
556 setBuy("shop-buy-5", 5);
557 setBuy("shop-buy-10", 10);
558 const buyX = document.getElementById("shop-buy-x");
559 if (buyX)
560 { buyX.disabled = max < 1; }
561
562 bagWarn.hidden = inventoryFits(entry.itemId, 1);
563 }
564
565 function render ()
566 {
567 const coins = getCoinCount?.() ?? 0;
568 coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;
569 if (tabSell)
570 { tabSell.hidden = !buysItems; }
571 if (activeTab === "sell" && buysItems)
572 { renderSellPane(); }
573 else
574 { renderBuyPane(); }
575 }
576
577 function handleShopOpen (message)
578 {
579 open(message);
580 }
581
582 function handleShopClosed (message)
583 {
584 if ((message?.npcEntityId | 0) === npcEntityId)
585 { close({ notifyServer: false }); }
586 }
587
588 function refresh ()
589 {
590 if (npcEntityId != null && !panel.hidden)
591 { render(); }
592 }
593
594 return {
595 handleShopOpen,
596 handleShopClosed,
597 refresh,
598 close,
599 isBlocking: () => !panel.hidden || !qtyPanel.hidden,
600 isOpen: () => !panel.hidden
601 };
602}