BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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