BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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