BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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