BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

inventory.js 35.4 KiB Download Raw
1import
2{
3 itemDefinition,
4 itemDescription,
5 itemOriginSummary,
6 itemAssetPathForStack,
7 itemDisplayName,
8 formatQuantity,
9 ItemId,
10 EQUIPMENT_SLOT,
11 LETTER_MAX_BODY_CHARS
12} from "/shared/definitions/items.js";
13import { stackQuantity } from "/shared/items/inventory.js";
14import { formatLetterSignature } from "/shared/courier/systemLetters.js";
15import { spellIdFromSpellbookStack } from "/shared/definitions/spellItems.js";
16import { spellDefinition } from "/shared/definitions/spells.js";
17import { bagMaxHitDisplay } from "/shared/combat/maxHit.js";
18import { applyItemIcon } from "../render/potionIcon.js";
19import { mountLayerPreview } from "./characterPreview.js";
20
21const EQUIP_LABELS = {
22 [EQUIPMENT_SLOT.head]: "Head",
23 [EQUIPMENT_SLOT.chest]: "Chest",
24 [EQUIPMENT_SLOT.legs]: "Legs",
25 [EQUIPMENT_SLOT.boots]: "Boots",
26 [EQUIPMENT_SLOT.weapon]: "Weapon",
27 [EQUIPMENT_SLOT.offhand]: "Off-hand",
28 [EQUIPMENT_SLOT.ring]: "Ring",
29 [EQUIPMENT_SLOT.bracelet]: "Bracelet",
30 [EQUIPMENT_SLOT.amulet]: "Amulet"
31};
32
33export function initInventory ({
34 socket,
35 MessageType,
36 contextMenu,
37 resolveSpriteUrl,
38 resolveImage = null,
39 getFriends,
40 getLocalName,
41 tipArrows = null,
42 getSoftClaims = null,
43 onBagSlotActivate = null,
44 bagClicksLocked = null,
45 knowsSpell = null,
46 getSkillLevels = null,
47 getSettings = null,
48 getKnownSpellIds = null,
49 onBagChanged = null
50})
51{
52 const bagPanel = document.getElementById("bag-panel");
53 const bagGrid = document.getElementById("bag-grid");
54 const equipGrid = document.getElementById("equip-grid");
55 const bagMaxHitEl = document.getElementById("bag-max-hit");
56 const hint = document.getElementById("bag-hint");
57 const bankPanel = document.getElementById("bank-panel");
58 const vaultGrid = document.getElementById("vault-grid");
59 const vaultReservedGrid = document.getElementById("vault-reserved-grid");
60 const inheritGrid = document.getElementById("inherit-grid");
61 const bankAvailablePane = document.getElementById("bank-available-pane");
62 const bankReservedPane = document.getElementById("bank-reserved-pane");
63 const bankInheritPane = document.getElementById("bank-inherit-pane");
64 const bankTabAvailable = document.getElementById("bank-tab-available");
65 const bankTabReserved = document.getElementById("bank-tab-reserved");
66 const bankTabInherit = document.getElementById("bank-tab-inherit");
67 const bankTabsRow = document.querySelector("#bank-panel .bank-tabs");
68
69 const sendPanel = document.getElementById("send-panel");
70 const sendBackdrop = document.getElementById("send-backdrop");
71 const sendTargetPanel = document.getElementById("send-target-panel");
72 const sendTargetList = document.getElementById("send-target-list");
73 const sendSearchResult = document.getElementById("send-search-result");
74 const letterPanel = document.getElementById("letter-panel");
75 const letterBackdrop = document.getElementById("letter-backdrop");
76 const letterBody = document.getElementById("letter-body");
77 const letterSignature = document.getElementById("letter-signature");
78 const letterSave = document.getElementById("letter-save");
79 const letterTitle = document.getElementById("letter-title");
80 const letterStatus = document.getElementById("letter-status");
81 const transferPanel = document.getElementById("transfer-panel");
82 const transferBackdrop = document.getElementById("transfer-backdrop");
83 const writeChequePanel = document.getElementById("write-cheque-panel");
84 const writeChequeBackdrop = document.getElementById("write-cheque-backdrop");
85 const writeChequeVault = document.getElementById("write-cheque-vault");
86
87 let bag = { inventory: [], equipment: { slots: {} }, vault: [], vaultReserved: [] };
88 let inheritance = { slots: [], currency: 0 };
89 let selected = null;
90 let bankOpen = false;
91 let bankTab = "available";
92 let sendState = null;
93 let letterState = null;
94 let transferState = null;
95 let writeChequeState = null;
96 let pendingSearch = false;
97 let localCharacterId = null;
98 let dragFromIndex = null;
99 let suppressSlotClick = false;
100
101 document.getElementById("bag-toggle").addEventListener("click", () =>
102 {
103 bagPanel.hidden = !bagPanel.hidden;
104 });
105 document.getElementById("bank-close").addEventListener("click", () => closeBank());
106 document.getElementById("bank-claim").addEventListener("click", () =>
107 {
108 socket.send({ type: MessageType.claimInheritance });
109 });
110 document.getElementById("bank-tab-available").addEventListener("click", () => setBankTab("available"));
111 document.getElementById("bank-tab-reserved").addEventListener("click", () => setBankTab("reserved"));
112 document.getElementById("bank-tab-inherit").addEventListener("click", () => setBankTab("inherit"));
113 document.getElementById("transfer-close").addEventListener("click", () => closeTransfer());
114 transferBackdrop.addEventListener("click", () => closeTransfer());
115 document.getElementById("transfer-confirm").addEventListener("click", () => confirmTransfer());
116 document.getElementById("write-cheque-close").addEventListener("click", () => closeWriteCheque());
117 writeChequeBackdrop.addEventListener("click", () => closeWriteCheque());
118 document.getElementById("write-cheque-confirm").addEventListener("click", () => confirmWriteCheque());
119
120 document.getElementById("send-close").addEventListener("click", () => closeSend());
121 sendBackdrop.addEventListener("click", () => closeSend());
122 document.getElementById("send-pick-target").addEventListener("click", () => openTargetPicker());
123 document.getElementById("send-target-close").addEventListener("click", () =>
124 {
125 sendTargetPanel.hidden = true;
126 });
127 document.getElementById("send-confirm").addEventListener("click", () => confirmSend());
128 document.getElementById("send-search").addEventListener("click", () =>
129 {
130 const firstName = document.getElementById("send-search-first").value.trim();
131 const lastName = document.getElementById("send-search-last").value.trim();
132 if (!firstName || !lastName)
133 {
134 sendSearchResult.textContent = "Enter a first and last name.";
135 return;
136 }
137 pendingSearch = true;
138 sendSearchResult.textContent = "Searching…";
139 socket.send({ type: MessageType.searchCharacter, firstName, lastName });
140 });
141
142 document.getElementById("letter-close").addEventListener("click", () => closeLetter());
143 letterBackdrop.addEventListener("click", () => closeLetter());
144 letterSave.addEventListener("click", () =>
145 {
146 if (!letterState || letterState.readOnly)
147 { return; }
148 const body = letterBody.value;
149 socket.send({
150 type: letterState.mode === "edit" ? MessageType.editLetter : MessageType.writeLetter,
151 slotIndex: letterState.slotIndex,
152 body
153 });
154 letterStatus.textContent = "Saving…";
155 });
156 letterBody.addEventListener("input", () =>
157 {
158 if (letterState?.readOnly)
159 { return; }
160 fitLetterBody();
161 refreshLetterSignature();
162 });
163
164 function sameClaimInstance (a, b)
165 {
166 return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
167 }
168
169 /** Bag view with cauldron soft-claims subtracted (presentation only). */
170 function displayInventorySlots ()
171 {
172 const source = bag.inventory ?? [];
173 const claims = getSoftClaims?.() ?? [];
174 if (!claims.length)
175 { return source; }
176 const slots = source.map((slot) => (slot
177 ? {
178 ...slot,
179 instance: slot.instance ? structuredClone(slot.instance) : null,
180 quantity: slot.quantity | 0
181 }
182 : null));
183 for (const claim of claims)
184 {
185 let need = claim.quantity | 0;
186 if (need <= 0)
187 { continue; }
188 for (let i = 0; i < slots.length && need > 0; i++)
189 {
190 const slot = slots[i];
191 if (!slot || (slot.itemId | 0) !== (claim.itemId | 0))
192 { continue; }
193 if ((claim.itemId | 0) === ItemId.flower
194 && !sameClaimInstance(slot.instance, claim.instance))
195 { continue; }
196 const take = Math.min(need, slot.quantity | 0);
197 slot.quantity -= take;
198 need -= take;
199 if (!(slot.quantity > 0))
200 { slots[i] = null; }
201 }
202 }
203 return slots;
204 }
205
206 function refreshMaxHit ()
207 {
208 if (!bagMaxHitEl)
209 { return; }
210 const display = bagMaxHitDisplay({
211 skillLevels: getSkillLevels?.() ?? {},
212 equipmentSlots: bag.equipment?.slots ?? {},
213 settings: getSettings?.() ?? null,
214 knownSpellIds: getKnownSpellIds?.() ?? []
215 });
216 const statSuffix = display.statLabel ? ` (${display.statLabel})` : "";
217 bagMaxHitEl.textContent = `Max hit: ${display.text}${statSuffix}`;
218 bagMaxHitEl.title = display.title ?? "";
219 bagMaxHitEl.hidden = false;
220 }
221
222 function render ()
223 {
224 bagGrid.innerHTML = "";
225 displayInventorySlots().forEach((slot, index) =>
226 {
227 const realSlot = bag.inventory?.[index] ?? null;
228 const button = document.createElement("button");
229 button.type = "button";
230 button.className = `item-slot${selected === index ? " selected" : ""}`;
231 button.dataset.slotIndex = String(index);
232 button.title = tooltip(slot ?? realSlot);
233 button.draggable = !!realSlot;
234 if (slot)
235 {
236 const img = document.createElement("img");
237 applyItemIcon(img, slot, itemAssetPathForStack(slot));
238 img.alt = itemDisplayName(slot);
239 img.draggable = false;
240 button.append(img);
241 if (slot.quantity > 1)
242 {
243 const count = document.createElement("span");
244 count.className = "qty";
245 count.textContent = formatQuantity(slot.quantity);
246 button.append(count);
247 }
248 }
249 else if (realSlot)
250 {
251 button.classList.add("soft-claimed");
252 button.title = `${itemDisplayName(realSlot)} (in use)`;
253 }
254 button.addEventListener("dragstart", (event) =>
255 {
256 if (!realSlot || !slot)
257 {
258 event.preventDefault();
259 return;
260 }
261 dragFromIndex = index;
262 suppressSlotClick = false;
263 event.dataTransfer.effectAllowed = "move";
264 event.dataTransfer.setData("text/plain", String(index));
265 button.classList.add("dragging");
266 });
267 button.addEventListener("dragend", () =>
268 {
269 button.classList.remove("dragging");
270 dragFromIndex = null;
271 for (const el of bagGrid.querySelectorAll(".item-slot.drag-over"))
272 { el.classList.remove("drag-over"); }
273 // Click fires after a completed drag in some browsers; ignore it.
274 suppressSlotClick = true;
275 queueMicrotask(() =>
276 { suppressSlotClick = false; });
277 });
278 button.addEventListener("dragover", (event) =>
279 {
280 if (dragFromIndex == null || dragFromIndex === index)
281 { return; }
282 event.preventDefault();
283 event.dataTransfer.dropEffect = "move";
284 button.classList.add("drag-over");
285 });
286 button.addEventListener("dragleave", () =>
287 { button.classList.remove("drag-over"); });
288 button.addEventListener("drop", (event) =>
289 {
290 event.preventDefault();
291 button.classList.remove("drag-over");
292 const raw = event.dataTransfer.getData("text/plain");
293 const from = raw === "" ? dragFromIndex : (raw | 0);
294 if (from == null || from === index)
295 { return; }
296 selected = index;
297 socket.send({
298 type: MessageType.moveInventorySlot,
299 fromSlotIndex: from,
300 toSlotIndex: index
301 });
302 });
303 button.addEventListener("click", () =>
304 {
305 if (suppressSlotClick)
306 {
307 suppressSlotClick = false;
308 return;
309 }
310 if (!slot)
311 { return; }
312 if (bagClicksLocked?.())
313 { return; }
314 if (onBagSlotActivate?.(index, slot))
315 { return; }
316 if (bankOpen)
317 {
318 transferSlot("inventory", index, null);
319 return;
320 }
321 selected = index;
322 hint.textContent = `${itemDisplayName(slot)}: ${itemDescription(slot, { localCharacterId })}`;
323 render();
324 });
325 button.addEventListener("contextmenu", (event) =>
326 {
327 event.preventDefault();
328 event.stopPropagation();
329 if (!slot)
330 { return; }
331 selected = index;
332 render();
333 if (bankOpen)
334 { showBankTransferMenu(event.clientX, event.clientY, "inventory", index, slot); }
335 else
336 { showItemMenu(event.clientX, event.clientY, index, slot); }
337 });
338 bagGrid.append(button);
339 });
340 equipGrid.innerHTML = "";
341 for (const [slot, label] of Object.entries(EQUIP_LABELS))
342 {
343 const worn = bag.equipment?.slots?.[slot];
344 const button = document.createElement("button");
345 button.type = "button";
346 button.className = "item-slot";
347 button.title = worn ? tooltip(worn) : label;
348 if (worn)
349 {
350 const img = document.createElement("img");
351 applyItemIcon(img, worn, itemAssetPathForStack(worn));
352 img.alt = itemDisplayName(worn);
353 button.append(img);
354 if (worn.quantity > 1)
355 {
356 const count = document.createElement("span");
357 count.className = "qty";
358 count.textContent = formatQuantity(worn.quantity);
359 button.append(count);
360 }
361 }
362 button.addEventListener("click", () =>
363 {
364 if (worn)
365 { socket.send({ type: MessageType.unequipItem, equipSlot: slot }); }
366 });
367 equipGrid.append(button);
368 }
369 refreshMaxHit();
370 }
371
372 function showItemMenu (x, y, slotIndex, slot)
373 {
374 const def = itemDefinition(slot.itemId);
375 const items = [];
376 const isOwnLetter = slot.itemId === ItemId.letter
377 && slot.instance?.kind === "letter"
378 && Number(slot.instance.authorCharacterId) === Number(localCharacterId);
379 const canSend = slot.itemId !== ItemId.blankCheque
380 && (slot.itemId !== ItemId.letter || isOwnLetter);
381 const canEquip = def?.equipment?.slot && slot.itemId !== ItemId.coins;
382
383 if (slot.itemId === ItemId.paper)
384 {
385 items.push({
386 label: "Write letter",
387 onSelect: () => openLetter({ mode: "write", slotIndex })
388 });
389 }
390 if (slot.itemId === ItemId.letter && slot.instance?.kind === "letter")
391 {
392 items.push({
393 label: "Read",
394 onSelect: () =>
395 {
396 if (slot.instance?.opened === false)
397 { socket.send({ type: MessageType.openLetter, slotIndex }); }
398 openLetter({
399 mode: "read",
400 slotIndex,
401 instance: { ...slot.instance, opened: true }
402 });
403 }
404 });
405 if (isOwnLetter)
406 {
407 items.push({
408 label: "Edit letter",
409 onSelect: () => openLetter({
410 mode: "edit",
411 slotIndex,
412 instance: slot.instance
413 })
414 });
415 }
416 }
417 const learnSpellId = spellIdFromSpellbookStack(slot, def);
418 if (learnSpellId && !knowsSpell?.(learnSpellId))
419 {
420 const spellName = spellDefinition(learnSpellId)?.displayName ?? "spell";
421 items.push({
422 label: `Learn ${spellName}`,
423 onSelect: () => socket.send({ type: MessageType.readSpellbook, slotIndex })
424 });
425 }
426 if (slot.itemId === ItemId.recipePaper && slot.instance?.kind === "recipe-paper")
427 {
428 const byYou = slot.instance.authorCharacterId != null
429 && Number(slot.instance.authorCharacterId) === Number(localCharacterId);
430 items.push({
431 label: "Read",
432 onSelect: () => openLetter({
433 mode: "read",
434 slotIndex,
435 instance: {
436 documentTitle: itemDisplayName(slot),
437 body: slot.instance.body ?? "",
438 authorDisplayName: (slot.instance.authorDisplayName ?? "Unknown")
439 }
440 })
441 });
442 }
443 if (slot.itemId === ItemId.blankCheque)
444 {
445 items.push({
446 label: "Write Cheque",
447 onSelect: () => openWriteCheque(slotIndex)
448 });
449 }
450 if (slot.itemId === ItemId.filledCheque && bankOpen)
451 {
452 items.push({
453 label: "Redeem Cheque",
454 onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
455 });
456 }
457 if (canEquip)
458 {
459 items.push({
460 label: "Equip",
461 onSelect: () => socket.send({ type: MessageType.equipItem, slotIndex })
462 });
463 }
464 if (canSend)
465 {
466 items.push({
467 label: "Send",
468 onSelect: () => openSend(slotIndex, slot)
469 });
470 }
471 const healing = itemDefinition(slot.itemId)?.healing ?? 0;
472 if (healing > 0)
473 {
474 items.push({
475 label: "Eat",
476 onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex })
477 });
478 }
479 if (slot.itemId === ItemId.potion && slot.instance?.kind === "potion")
480 {
481 if (tipArrows?.isArrowCoatingPotion?.(slot))
482 {
483 items.push({
484 label: "Apply to arrows",
485 onSelect: () => tipArrows.open(slotIndex)
486 });
487 }
488 else
489 {
490 items.push({
491 label: "Drink",
492 onSelect: () => socket.send({ type: MessageType.drinkItem, slotIndex })
493 });
494 }
495 }
496 const dropQty = stackQuantity(slot.quantity);
497 if (dropQty <= 1)
498 {
499 items.push({
500 label: "Drop",
501 onSelect: () => dropSlot(slotIndex, 1)
502 });
503 }
504 else
505 {
506 const name = itemDisplayName(slot);
507 items.push(
508 {
509 label: `Drop one ${name}`,
510 onSelect: () => dropSlot(slotIndex, 1)
511 },
512 {
513 label: `Drop half ${name}`,
514 onSelect: () => dropSlot(slotIndex, Math.max(1, Math.floor(dropQty / 2)))
515 },
516 {
517 label: `Drop all ${name}`,
518 onSelect: () => dropSlot(slotIndex, null)
519 },
520 {
521 label: `Drop X ${name}`,
522 onSelect: () => openDrop(slotIndex, slot)
523 }
524 );
525 }
526 contextMenu?.show(x, y, items);
527 }
528
529 function dropSlot (slotIndex, quantity)
530 {
531 const payload = { type: MessageType.dropItem, slotIndex };
532 if (quantity != null)
533 { payload.quantity = quantity; }
534 socket.send(payload);
535 }
536
537 function showBankTransferMenu (x, y, side, slotIndex, slot)
538 {
539 if (side === "inventory" && slot.itemId === ItemId.filledCheque)
540 {
541 contextMenu?.show(x, y, [{
542 label: "Redeem Cheque",
543 onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
544 }]);
545 return;
546 }
547 if (side === "inventory" && slot.itemId === ItemId.blankCheque)
548 {
549 contextMenu?.show(x, y, [
550 {
551 label: `Return ${slot.quantity | 0}`,
552 onSelect: () => socket.send({
553 type: MessageType.returnBlankCheques,
554 slotIndex,
555 quantity: slot.quantity | 0
556 })
557 },
558 {
559 label: "Write Cheque",
560 onSelect: () => openWriteCheque(slotIndex)
561 }
562 ]);
563 return;
564 }
565 const qty = slot.quantity | 0;
566 const name = itemDisplayName(slot);
567 if (qty <= 1)
568 {
569 contextMenu?.show(x, y, [{
570 label: `Transfer ${name}`,
571 onSelect: () => transferSlot(side, slotIndex, 1)
572 }]);
573 return;
574 }
575 contextMenu?.show(x, y, [
576 {
577 label: `Transfer all ${name}`,
578 onSelect: () => transferSlot(side, slotIndex, null)
579 },
580 {
581 label: `Transfer half ${name}`,
582 onSelect: () => transferSlot(side, slotIndex, Math.max(1, Math.floor(qty / 2)))
583 },
584 {
585 label: `Transfer one ${name}`,
586 onSelect: () => transferSlot(side, slotIndex, 1)
587 },
588 {
589 label: `Transfer X ${name}`,
590 onSelect: () => openTransfer(side, slotIndex, slot)
591 }
592 ]);
593 }
594
595 function transferSlot (side, slotIndex, quantity)
596 {
597 if (side === "inventory")
598 {
599 socket.send({
600 type: MessageType.bankDeposit,
601 slotIndex,
602 quantity
603 });
604 return;
605 }
606 socket.send({
607 type: MessageType.bankWithdraw,
608 slotIndex,
609 quantity
610 });
611 }
612
613 function openTransfer (side, slotIndex, slot)
614 {
615 transferState = { kind: "bank", side, slotIndex, maxQty: stackQuantity(slot.quantity) };
616 document.querySelector("#transfer-panel header h2").textContent = "Transfer";
617 document.getElementById("transfer-confirm").textContent = "Transfer";
618 document.getElementById("transfer-item-name").textContent = itemDisplayName(slot);
619 const input = document.getElementById("transfer-qty");
620 input.value = "1";
621 input.max = String(transferState.maxQty);
622 transferPanel.hidden = false;
623 transferBackdrop.hidden = false;
624 }
625
626 function openDrop (slotIndex, slot)
627 {
628 transferState = { kind: "drop", slotIndex, maxQty: stackQuantity(slot.quantity) };
629 document.querySelector("#transfer-panel header h2").textContent = "Drop";
630 document.getElementById("transfer-confirm").textContent = "Drop";
631 document.getElementById("transfer-item-name").textContent = itemDisplayName(slot);
632 const input = document.getElementById("transfer-qty");
633 input.value = "1";
634 input.max = String(transferState.maxQty);
635 transferPanel.hidden = false;
636 transferBackdrop.hidden = false;
637 }
638
639 function closeTransfer ()
640 {
641 transferState = null;
642 transferPanel.hidden = true;
643 transferBackdrop.hidden = true;
644 }
645
646 function confirmTransfer ()
647 {
648 if (!transferState)
649 { return; }
650 const quantity = Math.min(
651 transferState.maxQty,
652 Math.max(1, Number(document.getElementById("transfer-qty").value) | 0)
653 );
654 if (transferState.kind === "drop")
655 { dropSlot(transferState.slotIndex, quantity); }
656 else
657 { transferSlot(transferState.side, transferState.slotIndex, quantity); }
658 closeTransfer();
659 }
660
661 function openWriteCheque (slotIndex)
662 {
663 writeChequeState = { slotIndex, vaultSlotIndex: null, maxQty: 1 };
664 document.getElementById("write-cheque-item").textContent = "No vault item selected.";
665 document.getElementById("write-cheque-qty").value = "1";
666 document.getElementById("write-cheque-confirm").disabled = true;
667 document.getElementById("write-cheque-status").textContent = "";
668 writeChequePanel.hidden = false;
669 writeChequeBackdrop.hidden = false;
670 renderWriteChequeVault();
671 }
672
673 function closeWriteCheque ()
674 {
675 writeChequeState = null;
676 writeChequePanel.hidden = true;
677 writeChequeBackdrop.hidden = true;
678 if (bankOpen)
679 { renderBank(); }
680 }
681
682 function renderWriteChequeVault ()
683 {
684 if (!writeChequeVault)
685 { return; }
686 writeChequeVault.innerHTML = "";
687 const slots = bag.vault ?? [];
688 if (!slots.some(Boolean))
689 {
690 const empty = document.createElement("p");
691 empty.className = "hint";
692 empty.textContent = "Your vault is empty. Deposit goods at a bank first.";
693 writeChequeVault.append(empty);
694 return;
695 }
696 slots.forEach((slot, index) =>
697 {
698 if (!slot)
699 { return; }
700 const button = document.createElement("button");
701 button.className = "item-slot";
702 if (writeChequeState?.vaultSlotIndex === index)
703 { button.classList.add("selected"); }
704 button.title = tooltip(slot);
705 const def = itemDefinition(slot.itemId);
706 const img = document.createElement("img");
707 applyItemIcon(img, slot, itemAssetPathForStack(slot));
708 img.alt = itemDisplayName(slot);
709 button.append(img);
710 if (slot.quantity > 1)
711 {
712 const count = document.createElement("span");
713 count.className = "qty";
714 count.textContent = formatQuantity(slot.quantity);
715 button.append(count);
716 }
717 button.addEventListener("click", () =>
718 {
719 if (!writeChequeState)
720 { return; }
721 writeChequeState.vaultSlotIndex = index;
722 writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);
723 document.getElementById("write-cheque-item").textContent =
724 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
725 const qtyInput = document.getElementById("write-cheque-qty");
726 qtyInput.value = "1";
727 qtyInput.max = String(writeChequeState.maxQty);
728 qtyInput.disabled = writeChequeState.maxQty <= 1;
729 document.getElementById("write-cheque-confirm").disabled = false;
730 renderWriteChequeVault();
731 });
732 writeChequeVault.append(button);
733 });
734 }
735
736 function confirmWriteCheque ()
737 {
738 if (!writeChequeState || writeChequeState.vaultSlotIndex == null)
739 { return; }
740 const quantity = Math.max(1, Number(document.getElementById("write-cheque-qty").value) | 0);
741 socket.send({
742 type: MessageType.writeCheque,
743 slotIndex: writeChequeState.slotIndex,
744 vaultSlotIndex: writeChequeState.vaultSlotIndex,
745 quantity
746 });
747 document.getElementById("write-cheque-status").textContent = "Writing…";
748 closeWriteCheque();
749 }
750
751 function closeBank ()
752 {
753 bankOpen = false;
754 bankPanel.hidden = true;
755 closeWriteCheque();
756 closeTransfer();
757 }
758
759 function bankHasReserved ()
760 {
761 return (bag.vaultReserved ?? []).some((slot) => slot);
762 }
763
764 function bankHasInheritance ()
765 {
766 const slots = inheritance?.slots ?? [];
767 const hasSlots = slots.some((slot) => slot);
768 const hasCoins = (inheritance?.currency | 0) > 0;
769 return hasSlots || hasCoins;
770 }
771
772 function syncBankTabs ()
773 {
774 const showReserved = bankHasReserved();
775 const showInherit = bankHasInheritance();
776 if (bankTabReserved)
777 { bankTabReserved.hidden = !showReserved; }
778 if (bankTabInherit)
779 { bankTabInherit.hidden = !showInherit; }
780 if (bankTabsRow)
781 { bankTabsRow.hidden = !showReserved && !showInherit; }
782 if ((bankTab === "reserved" && !showReserved) || (bankTab === "inherit" && !showInherit))
783 { bankTab = "available"; }
784 }
785
786 function setBankTab (tab)
787 {
788 syncBankTabs();
789 if (tab === "reserved" && !bankHasReserved())
790 { tab = "available"; }
791 if (tab === "inherit" && !bankHasInheritance())
792 { tab = "available"; }
793 bankTab = tab;
794 bankTabAvailable?.classList.toggle("active", tab === "available");
795 bankTabReserved?.classList.toggle("active", tab === "reserved");
796 bankTabInherit?.classList.toggle("active", tab === "inherit");
797 if (bankAvailablePane)
798 { bankAvailablePane.hidden = tab !== "available"; }
799 if (bankReservedPane)
800 { bankReservedPane.hidden = tab !== "reserved"; }
801 if (bankInheritPane)
802 { bankInheritPane.hidden = tab !== "inherit"; }
803 }
804
805 function openSend (slotIndex, slot)
806 {
807 const def = itemDefinition(slot.itemId);
808 sendState = {
809 slotIndex,
810 itemId: slot.itemId,
811 maxQty: slot.quantity | 0,
812 destination: null
813 };
814 applyItemIcon(
815 document.getElementById("send-item-img"),
816 slot,
817 itemAssetPathForStack(slot)
818 );
819 document.getElementById("send-item-name").textContent = itemDisplayName(slot);
820 const qtyInput = document.getElementById("send-qty");
821 qtyInput.value = String(Math.max(1, sendState.maxQty));
822 qtyInput.max = String(sendState.maxQty);
823 qtyInput.disabled = sendState.maxQty <= 1;
824 document.getElementById("send-target-label").textContent = "No target selected.";
825 document.getElementById("send-confirm").disabled = true;
826 document.getElementById("send-status").textContent = "";
827 sendPanel.hidden = false;
828 sendBackdrop.hidden = false;
829 sendTargetPanel.hidden = true;
830 }
831
832 function closeSend ()
833 {
834 sendState = null;
835 sendPanel.hidden = true;
836 sendBackdrop.hidden = true;
837 sendTargetPanel.hidden = true;
838 }
839
840 function openTargetPicker ()
841 {
842 if (!sendState)
843 { return; }
844 sendTargetPanel.hidden = false;
845 sendSearchResult.replaceChildren();
846 document.getElementById("send-search-first").value = "";
847 document.getElementById("send-search-last").value = "";
848 renderTargetList();
849 }
850
851 function renderTargetList ()
852 {
853 sendTargetList.replaceChildren();
854 sendTargetList.append(targetRow({
855 kind: "bank",
856 label: "Bank",
857 hint: "Nearest bank → your vault"
858 }));
859 const friends = getFriends?.() ?? [];
860 if (!friends.length)
861 {
862 const empty = document.createElement("p");
863 empty.className = "hint";
864 empty.textContent = "No friends yet.";
865 sendTargetList.append(empty);
866 return;
867 }
868 for (const friend of friends)
869 { sendTargetList.append(characterTargetRow(friend)); }
870 }
871
872 function targetRow ({ kind, label, hint, onPick })
873 {
874 const row = document.createElement("button");
875 row.type = "button";
876 row.className = "send-target-row";
877 row.innerHTML = `<strong>${label}</strong>${hint ? `<span class="hint">${hint}</span>` : ""}`;
878 row.addEventListener("click", () =>
879 {
880 if (onPick)
881 { onPick(); }
882 else
883 { pickTarget({ kind: "bank" }, "Bank"); }
884 });
885 return row;
886 }
887
888 function characterTargetRow (entry)
889 {
890 const row = document.createElement("button");
891 row.type = "button";
892 row.className = "send-target-row";
893 const preview = characterPreview(entry.layers);
894 const text = document.createElement("div");
895 text.className = "send-target-text";
896 text.innerHTML = `<strong>${entry.firstName} ${entry.lastName}</strong>`;
897 row.append(preview, text);
898 row.addEventListener("click", () =>
899 {
900 pickTarget({
901 kind: "player",
902 firstName: entry.firstName,
903 lastName: entry.lastName,
904 characterId: entry.characterId
905 }, `${entry.firstName} ${entry.lastName}`);
906 });
907 return row;
908 }
909
910 function characterPreview (layers)
911 {
912 return mountLayerPreview(layers, {
913 resolveImage,
914 resolveSpriteUrl,
915 size: 48,
916 className: "char-preview"
917 });
918 }
919
920 function pickTarget (destination, label)
921 {
922 if (!sendState)
923 { return; }
924 sendState.destination = destination;
925 document.getElementById("send-target-label").textContent = `Target: ${label}`;
926 document.getElementById("send-confirm").disabled = false;
927 sendTargetPanel.hidden = true;
928 }
929
930 function confirmSend ()
931 {
932 if (!sendState?.destination)
933 { return; }
934 const quantity = Math.max(1, Math.min(sendState.maxQty, Number(document.getElementById("send-qty").value) | 0));
935 socket.send({
936 type: MessageType.sendPigeon,
937 destination: sendState.destination,
938 cargo: {
939 kind: "item",
940 slotIndex: sendState.slotIndex,
941 quantity
942 }
943 });
944 document.getElementById("send-status").textContent = "Pigeon dispatched…";
945 }
946
947 function openLetter ({ mode, slotIndex, instance })
948 {
949 letterState = { mode, slotIndex, readOnly: mode === "read", instance: instance ?? null };
950 letterTitle.textContent = instance?.documentTitle
951 ?? (mode === "write" ? "Write letter" : mode === "edit" ? "Edit letter" : "Letter");
952 letterBody.value = instance?.body ?? "";
953 letterBody.readOnly = letterState.readOnly;
954 letterBody.maxLength = LETTER_MAX_BODY_CHARS;
955 letterSave.hidden = letterState.readOnly;
956 letterStatus.textContent = "";
957 refreshLetterSignature();
958 letterPanel.hidden = false;
959 letterBackdrop.hidden = false;
960 fitLetterBody();
961 }
962
963 function fitLetterBody ()
964 {
965 letterBody.style.height = "auto";
966 letterBody.style.height = `${Math.max(letterBody.scrollHeight, 128)}px`;
967 }
968
969 function refreshLetterSignature ()
970 {
971 const fallback = getLocalName?.() || "Unknown";
972 letterSignature.textContent = formatLetterSignature(letterState?.instance, fallback);
973 }
974
975 function closeLetter ()
976 {
977 letterState = null;
978 letterPanel.hidden = true;
979 letterBackdrop.hidden = true;
980 }
981
982 function renderVault (grid, slots, { side = "vault", interactive = true } = {})
983 {
984 grid.innerHTML = "";
985 (slots ?? []).forEach((slot, index) =>
986 {
987 if (!slot)
988 { return; }
989 const button = document.createElement("button");
990 button.className = "item-slot";
991 if (writeChequeState && side === "vault" && writeChequeState.vaultSlotIndex === index)
992 { button.classList.add("selected"); }
993 button.title = tooltip(slot, { reserved: side === "reserved" });
994 const def = itemDefinition(slot.itemId);
995 const img = document.createElement("img");
996 applyItemIcon(img, slot, itemAssetPathForStack(slot));
997 img.alt = itemDisplayName(slot);
998 button.append(img);
999 if (slot.quantity > 1)
1000 {
1001 const count = document.createElement("span");
1002 count.className = "qty";
1003 count.textContent = formatQuantity(slot.quantity);
1004 button.append(count);
1005 }
1006 if (interactive && side === "vault")
1007 {
1008 button.addEventListener("click", () =>
1009 {
1010 if (writeChequeState)
1011 {
1012 writeChequeState.vaultSlotIndex = index;
1013 writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
1014 ? 1
1015 : availableOf(slot.itemId);
1016 document.getElementById("write-cheque-item").textContent =
1017 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
1018 const qtyInput = document.getElementById("write-cheque-qty");
1019 qtyInput.value = "1";
1020 qtyInput.max = String(writeChequeState.maxQty);
1021 qtyInput.disabled = writeChequeState.maxQty <= 1;
1022 document.getElementById("write-cheque-confirm").disabled = false;
1023 renderBank();
1024 return;
1025 }
1026 transferSlot("vault", index, null);
1027 });
1028 button.addEventListener("contextmenu", (event) =>
1029 {
1030 event.preventDefault();
1031 event.stopPropagation();
1032 if (writeChequeState)
1033 { return; }
1034 showBankTransferMenu(event.clientX, event.clientY, "vault", index, slot);
1035 });
1036 }
1037 grid.append(button);
1038 });
1039 }
1040
1041 function availableOf (itemId)
1042 {
1043 let total = 0;
1044 for (const slot of bag.vault ?? [])
1045 {
1046 if (slot?.itemId === itemId)
1047 { total += slot.quantity | 0; }
1048 }
1049 return total;
1050 }
1051
1052 function renderBank ()
1053 {
1054 renderVault(vaultGrid, bag.vault, { side: "vault", interactive: true });
1055 renderVault(vaultReservedGrid, bag.vaultReserved, { side: "reserved", interactive: false });
1056 setBankTab(bankTab);
1057 }
1058
1059 function tooltip (slot, { reserved = false } = {})
1060 {
1061 if (!slot)
1062 { return ""; }
1063 const base = `${itemDisplayName(slot)}${slot.quantity > 1 ? ` ×${formatQuantity(slot.quantity)}` : ""}`;
1064 const origin = itemOriginSummary(slot);
1065 const desc = itemDescription(slot, { localCharacterId });
1066 const lines = [base];
1067 if (reserved)
1068 {
1069 lines.push(slot.chequeId
1070 ? "Reserved against a written cheque."
1071 : "Reserved in the vault.");
1072 }
1073 if (origin)
1074 { lines.push(origin); }
1075 if (desc)
1076 { lines.push(desc); }
1077 return lines.join("\n");
1078 }
1079
1080 return {
1081 isOpen ()
1082 {
1083 return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden
1084 || !sendTargetPanel.hidden || !transferPanel.hidden || !writeChequePanel.hidden;
1085 },
1086 isBankOpen ()
1087 {
1088 return bankOpen;
1089 },
1090 closeBank,
1091 closeOverlays ()
1092 {
1093 closeBank();
1094 closeSend();
1095 closeLetter();
1096 closeTransfer();
1097 closeWriteCheque();
1098 },
1099 refreshBagDisplay ()
1100 {
1101 render();
1102 },
1103 refreshMaxHit,
1104 isBlocking ()
1105 {
1106 if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden
1107 || !transferPanel.hidden || !writeChequePanel.hidden)
1108 { return true; }
1109 if (sendBackdrop && !sendBackdrop.hidden)
1110 { return true; }
1111 if (letterBackdrop && !letterBackdrop.hidden)
1112 { return true; }
1113 if (transferBackdrop && !transferBackdrop.hidden)
1114 { return true; }
1115 if (writeChequeBackdrop && !writeChequeBackdrop.hidden)
1116 { return true; }
1117 const x = GameInput.mousePosition.x;
1118 const y = GameInput.mousePosition.y;
1119 for (const element of [bagPanel, bankPanel])
1120 {
1121 if (!element || element.hidden)
1122 { continue; }
1123 const box = element.getBoundingClientRect();
1124 if (x >= box.left && x < box.right && y >= box.top && y < box.bottom)
1125 { return true; }
1126 }
1127 return false;
1128 },
1129 setLocalCharacterId (characterId)
1130 {
1131 localCharacterId = characterId;
1132 },
1133 getLocalCharacterId ()
1134 {
1135 return localCharacterId;
1136 },
1137 getInventorySlots ()
1138 {
1139 return bag.inventory ?? [];
1140 },
1141 getBag ()
1142 {
1143 return {
1144 slots: bag.inventory ?? [],
1145 equipment: bag.equipment ?? null
1146 };
1147 },
1148 getEquipment ()
1149 {
1150 return bag.equipment?.slots ?? bag.equipment ?? {};
1151 },
1152 handleInventory (message)
1153 {
1154 bag = { ...bag, ...message };
1155 render();
1156 onBagChanged?.();
1157 if (bankOpen)
1158 {
1159 renderBank();
1160 syncBankTabs();
1161 }
1162 if (writeChequeState)
1163 { renderWriteChequeVault(); }
1164 if (letterState && letterStatus.textContent === "Saving…")
1165 {
1166 letterStatus.textContent = "Saved.";
1167 if (letterState.mode === "write")
1168 { closeLetter(); }
1169 else if (letterState.mode === "edit")
1170 {
1171 const slot = bag.inventory?.[letterState.slotIndex];
1172 if (slot?.instance)
1173 {
1174 letterState.instance = slot.instance;
1175 letterBody.value = slot.instance.body ?? "";
1176 refreshLetterSignature();
1177 fitLetterBody();
1178 }
1179 }
1180 }
1181 },
1182 handleBank (message)
1183 {
1184 bankOpen = true;
1185 bankPanel.hidden = false;
1186 bagPanel.hidden = false;
1187 bag.vault = message.vault ?? [];
1188 bag.vaultReserved = message.vaultReserved ?? [];
1189 inheritance = {
1190 slots: message.inheritance?.slots ?? [],
1191 currency: message.inheritance?.currency | 0 || 0
1192 };
1193 renderVault(inheritGrid, inheritance.slots, { interactive: false });
1194 inheritGrid.querySelectorAll("button").forEach((button) =>
1195 {
1196 button.onclick = null;
1197 });
1198 const inheritCoins = document.getElementById("inherit-coins");
1199 if (inheritCoins)
1200 {
1201 const coins = inheritance.currency | 0;
1202 inheritCoins.hidden = coins <= 0;
1203 inheritCoins.textContent = coins > 0 ? `${formatQuantity(coins)} coins` : "";
1204 }
1205 setBankTab("available");
1206 renderBank();
1207 render();
1208 },
1209 getBlankCheques ()
1210 {
1211 socket.send({ type: MessageType.getBlankCheques });
1212 },
1213 handlePigeonDispatched ()
1214 {
1215 document.getElementById("send-status").textContent = "Pigeon is in flight.";
1216 closeSend();
1217 },
1218 handlePigeonDelivered (message)
1219 {
1220 const kind = message.destinationKind === "bank" ? "bank vault" : "recipient";
1221 hint.textContent = `Pigeon delivered to ${kind}.`;
1222 },
1223 handleCharacterSearch (message)
1224 {
1225 if (!pendingSearch)
1226 { return; }
1227 pendingSearch = false;
1228 sendSearchResult.replaceChildren();
1229 if (!message.character)
1230 {
1231 sendSearchResult.textContent = "No character with that name.";
1232 return;
1233 }
1234 sendSearchResult.append(characterTargetRow(message.character));
1235 },
1236 reset ()
1237 {
1238 bagPanel.hidden = true;
1239 closeBank();
1240 selected = null;
1241 closeSend();
1242 closeLetter();
1243 }
1244 };
1245}