BlueGit

timfa questward

Files

questward / client / src / play / shop.js

shop.js

shop.js 11.2 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6} from "/shared/definitions/items.js";
7import { insertStack } 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 grid = document.getElementById("shop-grid");
27 const detail = document.getElementById("shop-detail");
28 const detailIcon = document.getElementById("shop-detail-icon");
29 const detailName = document.getElementById("shop-detail-name");
30 const detailPrice = document.getElementById("shop-detail-price");
31 const detailStock = document.getElementById("shop-detail-stock");
32 const bagWarn = document.getElementById("shop-bag-warn");
33 const coinsEl = document.getElementById("shop-coins");
34 const sellSection = document.getElementById("shop-sell-section");
35 const sellList = document.getElementById("shop-sell-list");
36 const sellDetail = document.getElementById("shop-sell-detail");
37 const sellPrice = document.getElementById("shop-sell-price");
38 const sellFee = document.getElementById("shop-sell-fee");
39 const sellConfirm = document.getElementById("shop-sell-confirm");
40 const qtyBackdrop = document.getElementById("shop-qty-backdrop");
41 const qtyPanel = document.getElementById("shop-qty-panel");
42 const qtyInput = document.getElementById("shop-qty-input");
43 const qtyHint = document.getElementById("shop-qty-hint");
44
45 let npcEntityId = null;
46 let stock = [];
47 let selectedListingId = null;
48 let selectedSellSlotIndex = null;
49 let buysItems = false;
50 let displayName = "Shop";
51 let sex = "male";
52
53 function suppressWorldClick ()
54 {
55 onSuppressWorldClick?.();
56 }
57
58 document.getElementById("shop-close")?.addEventListener("click", () => close());
59 backdrop?.addEventListener("mousedown", (event) =>
60 {
61 event.preventDefault();
62 suppressWorldClick();
63 });
64 backdrop?.addEventListener("click", () => close());
65 panel?.addEventListener("mousedown", (event) =>
66 {
67 event.stopPropagation();
68 suppressWorldClick();
69 });
70 qtyBackdrop?.addEventListener("mousedown", (event) =>
71 {
72 event.preventDefault();
73 suppressWorldClick();
74 });
75 qtyPanel?.addEventListener("mousedown", (event) =>
76 {
77 event.stopPropagation();
78 suppressWorldClick();
79 });
80 document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1));
81 document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5));
82 document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10));
83 document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal());
84 document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal());
85 document.getElementById("shop-qty-confirm")?.addEventListener("click", () => confirmQtyBuy());
86 qtyBackdrop?.addEventListener("click", () => closeQtyModal());
87 qtyInput?.addEventListener("keydown", (event) =>
88 {
89 if (event.key === "Enter")
90 { confirmQtyBuy(); }
91 });
92 sellConfirm?.addEventListener("click", () => sellSelected());
93
94 function open (payload)
95 {
96 npcEntityId = payload.npcEntityId | 0;
97 displayName = payload.displayName || "Shop";
98 sex = payload.sex === "female" ? "female" : "male";
99 title.textContent = displayName;
100 buysItems = !!payload.buysItems;
101 stock = Array.isArray(payload.stock) ? payload.stock : [];
102 if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId))
103 { selectedListingId = stock[0]?.listingId ?? null; }
104 closeQtyModal();
105 render();
106 backdrop.hidden = false;
107 panel.hidden = false;
108 suppressWorldClick();
109 }
110
111 function close ({ notifyServer = true } = {})
112 {
113 const closingNpcId = npcEntityId;
114 closeQtyModal();
115 backdrop.hidden = true;
116 panel.hidden = true;
117 npcEntityId = null;
118 stock = [];
119 selectedListingId = null;
120 selectedSellSlotIndex = null;
121 buysItems = false;
122 sex = "male";
123 suppressWorldClick();
124 if (notifyServer && closingNpcId)
125 {
126 socket.send({
127 type: MessageType.closeShop,
128 npcEntityId: closingNpcId
129 });
130 }
131 }
132
133 function selectedEntry ()
134 {
135 return stock.find((row) => row.listingId === selectedListingId) ?? null;
136 }
137
138 function maxBuyable (entry)
139 {
140 const price = Math.max(1, entry?.unitPrice | 0 || 1);
141 const coins = getCoinCount?.() ?? 0;
142 const affordable = Math.max(0, Math.floor(coins / price));
143 const available = entry?.available == null ? affordable : Math.max(0, entry.available | 0);
144 return Math.min(affordable, available);
145 }
146
147 function inventoryFits (itemId, quantity)
148 {
149 const def = itemDefinition(itemId);
150 if (!def)
151 { return false; }
152 const slots = getInventorySlots?.() ?? [];
153 const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), {
154 itemId,
155 quantity: Math.max(1, quantity | 0 || 1)
156 }, def);
157 return added.ok && added.remainder === 0;
158 }
159
160 function buy (quantity)
161 {
162 const entry = selectedEntry();
163 if (!npcEntityId || !entry)
164 { return; }
165 const qty = Math.max(1, quantity | 0 || 1);
166 const max = maxBuyable(entry);
167 if (qty > max)
168 { return; }
169 socket.send({
170 type: MessageType.buyFromShop,
171 npcEntityId,
172 itemId: entry.itemId,
173 quantity: qty,
174 listingId: entry.listingId,
175 source: entry.source
176 });
177 }
178
179 function openQtyModal ()
180 {
181 const entry = selectedEntry();
182 if (!entry)
183 { return; }
184 const max = maxBuyable(entry);
185 if (max < 1)
186 { return; }
187 qtyInput.value = String(Math.min(max, 1));
188 qtyHint.textContent = `Max ${max}`;
189 qtyBackdrop.hidden = false;
190 qtyPanel.hidden = false;
191 suppressWorldClick();
192 qtyInput.focus();
193 qtyInput.select();
194 }
195
196 function closeQtyModal ()
197 {
198 qtyBackdrop.hidden = true;
199 qtyPanel.hidden = true;
200 }
201
202 function confirmQtyBuy ()
203 {
204 const entry = selectedEntry();
205 if (!entry)
206 {
207 closeQtyModal();
208 return;
209 }
210 const max = maxBuyable(entry);
211 const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1));
212 closeQtyModal();
213 buy(qty);
214 }
215
216 function selectedSellSlot ()
217 {
218 if (selectedSellSlotIndex == null)
219 { return null; }
220 const slots = getInventorySlots?.() ?? [];
221 const slot = slots[selectedSellSlotIndex];
222 if (!slot?.itemId || !canPlayerSellToNpc(slot))
223 { return null; }
224 return slot;
225 }
226
227 function sellSelected ()
228 {
229 if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot())
230 { return; }
231 socket.send({
232 type: MessageType.sellToShop,
233 npcEntityId,
234 slotIndex: selectedSellSlotIndex,
235 quantity: 1
236 });
237 }
238
239 function renderSellDetail ()
240 {
241 if (!sellDetail || !sellPrice || !sellFee || !sellConfirm)
242 { return; }
243 const slot = selectedSellSlot();
244 if (!slot)
245 {
246 sellDetail.hidden = true;
247 sellFee.hidden = true;
248 return;
249 }
250 const quote = resolveShopSellQuote(slot, { quantity: 1 });
251 if (!quote)
252 {
253 sellDetail.hidden = true;
254 sellFee.hidden = true;
255 return;
256 }
257 sellDetail.hidden = false;
258 sellPrice.textContent = quote.isCheque
259 ? `You receive ${formatQuantity(quote.payout)} coins`
260 : `${formatQuantity(quote.unitPrice)} coins each`;
261 if (quote.isCheque)
262 {
263 sellFee.hidden = false;
264 sellFee.textContent = `${formatQuantity(quote.adminFee)} coins charged as administrative fee`;
265 }
266 else
267 {
268 sellFee.hidden = true;
269 sellFee.textContent = "";
270 }
271 sellConfirm.disabled = false;
272 }
273
274 function renderSellList ()
275 {
276 if (!sellSection || !sellList)
277 { return; }
278 if (!buysItems)
279 {
280 sellSection.hidden = true;
281 selectedSellSlotIndex = null;
282 if (sellDetail)
283 { sellDetail.hidden = true; }
284 return;
285 }
286 sellSection.hidden = false;
287 sellList.innerHTML = "";
288 const slots = getInventorySlots?.() ?? [];
289 const sellableIndexes = [];
290 slots.forEach((slot, slotIndex) =>
291 {
292 if (!slot?.itemId || !canPlayerSellToNpc(slot))
293 { return; }
294 sellableIndexes.push(slotIndex);
295 });
296 if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex))
297 { selectedSellSlotIndex = null; }
298 if (selectedSellSlotIndex == null && sellableIndexes.length)
299 { selectedSellSlotIndex = sellableIndexes[0]; }
300 if (!sellableIndexes.length)
301 {
302 sellList.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`;
303 selectedSellSlotIndex = null;
304 renderSellDetail();
305 return;
306 }
307 for (const slotIndex of sellableIndexes)
308 {
309 const slot = slots[slotIndex];
310 const row = document.createElement("button");
311 row.type = "button";
312 row.className = "shop-sell-row";
313 if (slotIndex === selectedSellSlotIndex)
314 { row.classList.add("selected"); }
315 row.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`;
316 row.addEventListener("click", () =>
317 {
318 selectedSellSlotIndex = slotIndex;
319 renderSellList();
320 });
321 sellList.append(row);
322 }
323 renderSellDetail();
324 }
325
326 function render ()
327 {
328 grid.innerHTML = "";
329 const coins = getCoinCount?.() ?? 0;
330 coinsEl.textContent = `Coins: ${formatQuantity(coins)}`;
331
332 if (!stock.length)
333 {
334 grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale.";
335 detail.hidden = true;
336 bagWarn.hidden = true;
337 renderSellList();
338 return;
339 }
340
341 for (const entry of stock)
342 {
343 const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
344 const btn = document.createElement("button");
345 btn.type = "button";
346 btn.className = "shop-cell";
347 if (entry.listingId === selectedListingId)
348 { btn.classList.add("selected"); }
349 btn.title = name;
350 const img = document.createElement("img");
351 img.alt = name;
352 applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
353 btn.append(img);
354 btn.addEventListener("click", () =>
355 {
356 selectedListingId = entry.listingId;
357 render();
358 });
359 grid.append(btn);
360 }
361
362 const entry = selectedEntry();
363 if (!entry)
364 {
365 detail.hidden = true;
366 bagWarn.hidden = true;
367 renderSellList();
368 return;
369 }
370
371 detail.hidden = false;
372 const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId });
373 detailName.textContent = name;
374 detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`;
375 detailStock.textContent = entry.available == null
376 ? "In stock"
377 : `Stock: ${formatQuantity(entry.available)}`;
378 applyItemIcon(detailIcon, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId }));
379
380 const max = maxBuyable(entry);
381 const setBuy = (id, qty) =>
382 {
383 const el = document.getElementById(id);
384 if (!el)
385 { return; }
386 el.disabled = max < qty;
387 };
388 setBuy("shop-buy-1", 1);
389 setBuy("shop-buy-5", 5);
390 setBuy("shop-buy-10", 10);
391 const buyX = document.getElementById("shop-buy-x");
392 if (buyX)
393 { buyX.disabled = max < 1; }
394
395 bagWarn.hidden = inventoryFits(entry.itemId, 1);
396 renderSellList();
397 }
398
399 function handleShopOpen (message)
400 {
401 open(message);
402 }
403
404 function handleShopClosed (message)
405 {
406 if ((message?.npcEntityId | 0) === npcEntityId)
407 { close({ notifyServer: false }); }
408 }
409
410 function refresh ()
411 {
412 if (npcEntityId != null && !panel.hidden)
413 { render(); }
414 }
415
416 return {
417 handleShopOpen,
418 handleShopClosed,
419 refresh,
420 close,
421 isBlocking: () => !panel.hidden || !qtyPanel.hidden,
422 isOpen: () => !panel.hidden
423 };
424}