BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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