BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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