BlueGit

timfa questward

Files

questward / client / src / play / inventory.js

inventory.js

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