BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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