BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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