BlueGit

timfa questward

Files

questward / client / src / play / main.js

main.js

main.js 76.4 KiB Download Raw
1import { MessageType, GAIT, CHUNK_SIZE, STATIC_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { validateCharacterNames } from "/shared/characters/names.js";
3import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
4import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
5import { OVERWORLD_ID } from "/shared/world/dimensions.js";
6import { findPathToNearestGoal } from "/shared/navigation/bfs.js";
7import { isAdjacentTile } from "/shared/navigation/adjacency.js";
8import { GameSocket, defaultSocketUrl } from "../net/socket.js";
9import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
10import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour, playImagesFromCatalog } from "../render/sprites.js";
11import { WorldView } from "../render/worldView.js";
12import { initSocial } from "./social.js";
13import { initChat } from "./chat.js";
14import { initInventory } from "./inventory.js";
15import { initSkills } from "./skills.js";
16import { initSpells } from "./spells.js";
17import { initCrafting } from "./crafting.js";
18import { initAlchemy } from "./alchemy.js";
19import { initTipArrows } from "./tipArrows.js";
20import { initStamina } from "./stamina.js";
21import { initHealth } from "./health.js";
22import { initStatusEffects } from "./statusEffects.js";
23import { initContextMenu } from "./contextMenu.js";
24import { initDeath } from "./death.js";
25import { initToasts } from "./toasts.js";
26import { skillLevelUpToastText, skillUnlockMessages } from "/shared/skills/levelUpUnlocks.js";
27import { mobDefinition, mobLevelDisplayName, MobId } from "/shared/definitions/mobs.js";
28import { canTeleportToBank, canTeleportToChurch } from "/shared/equipment/jewelryEffects.js";
29import { initQuests } from "./quests.js";
30import { initDialogue } from "./dialogue.js";
31import { initShop } from "./shop.js";
32import { initMarket } from "./market.js";
33import { initBounty } from "./bounty.js";
34import { initBarber } from "./barber.js";
35import { bindHairControls } from "./hairControls.js";
36import { bindCreateClothingControls } from "./createClothingControls.js";
37import { paintCharacterPreview } from "./characterPreview.js";
38import { initGraphicsSettings } from "./graphicsSettings.js";
39import { CraftingStationId } from "/shared/definitions/craftingStations.js";
40import { isOreBoulderState } from "/shared/definitions/materialTiers.js";
41import { formatQuantity } from "/shared/items/formatQuantity.js";
42import { ItemId, itemDefinition } from "/shared/definitions/items.js";
43import { CraftingItemId, TINDERBOX_MAX_CHARGES } from "/shared/definitions/craftingItems.js";
44import { ItemFamilyId } from "/shared/definitions/tierFamilies.js";
45import { EquipmentKind } from "/shared/definitions/equipmentKinds.js";
46import { countCoinsInSlots } from "/shared/items/inventory.js";
47
48const game = new Game();
49const hud = document.getElementById("hud");
50const overlay = document.getElementById("overlay");
51const statusEl = document.getElementById("status");
52const characterList = document.getElementById("character-list");
53const errorEl = document.getElementById("error");
54const assetLoadEl = document.getElementById("asset-load");
55const assetLoadBar = document.getElementById("asset-load-bar");
56const assetLoadLabel = document.getElementById("asset-load-label");
57const createCharacterOpen = document.getElementById("create-character-open");
58const worldTooltip = document.getElementById("world-tooltip");
59
60let socket;
61let session = null;
62let playing = false;
63let view = null;
64let graphicsSettingsUi = null;
65let scene = null;
66let gait = GAIT.walk;
67let catalog = { grounds: {}, blocks: {} };
68let social;
69let chat;
70let inventory;
71let skills;
72let spells;
73let crafting;
74let alchemy;
75let staminaUi;
76let healthUi;
77let statusEffectsUi;
78let contextMenu;
79let death;
80let toasts;
81let questsUi;
82let dialogueUi;
83let shop;
84let playZoomRaf = 0;
85let playZoomDelta = 0;
86let market;
87let bounty;
88let barber;
89let createHairControls;
90let createClothingControls;
91let createActiveTab = "appearance";
92let pendingPickup = null;
93/** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | { kind: "market" | "bounty" | "barber", tileX: number, tileY: number } | null } */
94let pendingInteract = null;
95/**
96 * Block/NPC the player currently has a station UI open for.
97 * Closed automatically when Chebyshev distance exceeds 1.
98 * @type {null | { kind: "bank" | "station" | "cauldron" | "market" | "bounty" | "barber", tileX: number, tileY: number } | { kind: "shop" | "dialogue", entityId: number }}
99 */
100let uiFocus = null;
101/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
102let approachMove = null;
103/** Client-tracked follow target; server follow owns gait while this is set. */
104let followTargetId = null;
105/** Destination of the active click/approach moveTo for autorun distance checks. */
106let moveDest = null;
107/** Entity / tile focus for server-driven approach (attack, cast) — no client moveTo. */
108let autorunFocusEntityId = null;
109let autorunFocusTile = null;
110/** After stamina hits 0 while autorunning, wait until ≥50% before running again. */
111let autorunWaitingStamina = false;
112/** Framework can report mousePressed for two frames; latch so one physical click is one command. */
113let leftClickConsumed = false;
114
115const AUTORUN_DISTANCE_TILES = 3;
116const AUTORUN_STAMINA_RESUME_RATIO = 0.5;
117
118function sendPlayerMoveTo (tileX, tileY)
119{
120 followTargetId = null;
121 clearAutorunFocus();
122 moveDest = { tileX: tileX | 0, tileY: tileY | 0 };
123 socket.send({ type: MessageType.moveTo, tileX: moveDest.tileX, tileY: moveDest.tileY });
124 syncAutorun();
125}
126
127function sendPlayerFollow (targetEntityId)
128{
129 followTargetId = targetEntityId | 0;
130 moveDest = null;
131 clearAutorunFocus();
132 autorunWaitingStamina = false;
133 socket.send({ type: MessageType.follow, targetEntityId: followTargetId });
134}
135
136function clearAutorunFocus ()
137{
138 autorunFocusEntityId = null;
139 autorunFocusTile = null;
140}
141
142function setAutorunFocusEntity (entityId)
143{
144 moveDest = null;
145 autorunFocusTile = null;
146 autorunFocusEntityId = entityId | 0;
147 syncAutorun();
148}
149
150function setAutorunFocusTile (tileX, tileY)
151{
152 moveDest = null;
153 autorunFocusEntityId = null;
154 autorunFocusTile = { tileX: tileX | 0, tileY: tileY | 0 };
155 syncAutorun();
156}
157
158function resolveAutorunDest ()
159{
160 if (moveDest)
161 { return moveDest; }
162 if (autorunFocusEntityId != null)
163 {
164 const target = view?.entities?.get(autorunFocusEntityId);
165 if (!target)
166 { return null; }
167 return { tileX: target.tileX | 0, tileY: target.tileY | 0 };
168 }
169 return autorunFocusTile;
170}
171
172function localEntityIsMoving (local)
173{
174 if (!local)
175 { return false; }
176 if (local.lerpStarted != null)
177 { return true; }
178 const dx = (local.visualX ?? 0) - (local.targetX ?? local.visualX ?? 0);
179 const dy = (local.visualY ?? 0) - (local.targetY ?? local.visualY ?? 0);
180 return (dx * dx + dy * dy) > 0.25;
181}
182
183function requestGaitIfNeeded (next)
184{
185 if (next !== GAIT.walk && next !== GAIT.run)
186 { return; }
187 if (next === gait)
188 { return; }
189 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 0) <= 0)
190 { return; }
191 socket.send({ type: MessageType.setGait, gait: next });
192 if (next === GAIT.walk)
193 {
194 gait = next;
195 const el = document.getElementById("gait");
196 if (el)
197 { el.textContent = gait; }
198 }
199}
200
201function syncAutorun ()
202{
203 if (!playing || followTargetId != null)
204 { return; }
205 const settings = graphicsSettingsUi?.getSettings?.() ?? {};
206 if (settings.autorun !== "on")
207 { return; }
208 const local = view?.entities?.get(view.localEntityId);
209 const dest = resolveAutorunDest();
210 if (!local || !dest)
211 { return; }
212 if (moveDest && local.tileX === moveDest.tileX && local.tileY === moveDest.tileY)
213 {
214 moveDest = null;
215 autorunWaitingStamina = false;
216 requestGaitIfNeeded(GAIT.walk);
217 return;
218 }
219 // Attack / cast approach is server-pathed — only run while tiles are changing.
220 if (!moveDest && !localEntityIsMoving(local))
221 {
222 requestGaitIfNeeded(GAIT.walk);
223 return;
224 }
225 const dist = chebyshev(local.tileX, local.tileY, dest.tileX, dest.tileY);
226 const wantRun = dist > AUTORUN_DISTANCE_TILES;
227 const current = staminaUi?.getCurrent?.() ?? 0;
228 const max = Math.max(1, staminaUi?.getMax?.() ?? 1);
229 if (gait === GAIT.run && current <= 0)
230 { autorunWaitingStamina = true; }
231 if (autorunWaitingStamina)
232 {
233 if (wantRun && current / max >= AUTORUN_STAMINA_RESUME_RATIO)
234 {
235 autorunWaitingStamina = false;
236 requestGaitIfNeeded(GAIT.run);
237 }
238 else
239 { requestGaitIfNeeded(GAIT.walk); }
240 return;
241 }
242 if (wantRun)
243 {
244 if (current <= 0)
245 {
246 autorunWaitingStamina = true;
247 requestGaitIfNeeded(GAIT.walk);
248 }
249 else
250 { requestGaitIfNeeded(GAIT.run); }
251 }
252 else
253 { requestGaitIfNeeded(GAIT.walk); }
254}
255
256function consumeWorldClick ()
257{
258 leftClickConsumed = true;
259}
260
261function showError (message)
262{
263 errorEl.textContent = message ?? "";
264}
265
266function setAssetLoading (active, { loaded = 0, total = 0, phase = "" } = {})
267{
268 if (assetLoadEl)
269 { assetLoadEl.hidden = !active; }
270 if (characterList)
271 { characterList.hidden = active; }
272 if (createCharacterOpen)
273 { createCharacterOpen.hidden = active; }
274 if (!active)
275 { return; }
276 if (assetLoadBar && total > 0)
277 { assetLoadBar.value = Math.round((loaded / total) * 100); }
278 if (assetLoadLabel)
279 {
280 assetLoadLabel.textContent = phase
281 || (total > 0 ? `Loading assets… ${loaded}/${total}` : "Loading assets…");
282 }
283}
284
285function renderCharacters (characters)
286{
287 characterList.innerHTML = "";
288 for (const character of characters)
289 {
290 const row = document.createElement("div");
291 row.className = "character-row";
292 const pending = character.deletionScheduledAt
293 ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})`
294 : "";
295 row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`;
296 const play = document.createElement("button");
297 play.textContent = "Play";
298 play.disabled = !!character.deletionScheduledAt;
299 play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId }));
300 const del = document.createElement("button");
301 del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete";
302 del.addEventListener("click", () =>
303 {
304 socket.send({
305 type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter,
306 characterId: character.characterId
307 });
308 });
309 row.append(play, del);
310 characterList.append(row);
311 }
312}
313
314function uiBlocked ()
315{
316 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
317 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
318 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
319 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
320 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
321 || graphicsSettingsUi?.isBlocking?.()
322 || pointerOverSpellUi());
323}
324
325function pointerOverSpellUi ()
326{
327 const el = document.elementFromPoint(GameInput.mousePosition.x, GameInput.mousePosition.y);
328 if (!el)
329 { return false; }
330 return !!el.closest("#spells-panel, #spell-favorites-bar, #spells-toggle");
331}
332
333function applyGraphicsSettings (settings)
334{
335 view?.setGraphicsPrefs(settings);
336 if (socket && playing)
337 {
338 socket.send({
339 type: MessageType.setGraphicsSettings,
340 viewDistance: settings.viewDistance
341 });
342 }
343 syncAutorun();
344}
345
346function clearPendingPickup ()
347{
348 pendingPickup = null;
349}
350
351function clearPendingInteract ()
352{
353 pendingInteract = null;
354 approachMove = null;
355}
356
357function clearAllPendingActions ()
358{
359 clearPendingPickup();
360 clearPendingInteract();
361}
362
363function approachAdjacentTile (tileX, tileY)
364{
365 const local = view.entities.get(view.localEntityId);
366 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
367 {
368 approachMove = null;
369 return true;
370 }
371 if (!local)
372 { return false; }
373
374 const radius = Math.max(1, STATIC_CHUNK_RADIUS | 0) * CHUNK_SIZE;
375 const path = findPathToNearestGoal(
376 local.tileX,
377 local.tileY,
378 (x, y) => chebyshev(x, y, tileX, tileY) === 1 && isClientApproachable(x, y),
379 (x, y) => isClientApproachable(x, y),
380 local.tileX - radius,
381 local.tileY - radius,
382 local.tileX + radius,
383 local.tileY + radius
384 );
385 let best = path.length ? path[path.length - 1] : null;
386 if (!best)
387 {
388 // Fallback if BFS finds nothing (incomplete client map): nearest adjacent guess.
389 let bestAny = null;
390 let bestAnyDist = Infinity;
391 for (let dy = -1; dy <= 1; dy++)
392 {
393 for (let dx = -1; dx <= 1; dx++)
394 {
395 if (dx === 0 && dy === 0)
396 { continue; }
397 const destX = tileX + dx;
398 const destY = tileY + dy;
399 const dist = chebyshev(local.tileX, local.tileY, destX, destY);
400 if (dist < bestAnyDist)
401 {
402 bestAnyDist = dist;
403 bestAny = { tileX: destX, tileY: destY };
404 }
405 }
406 }
407 best = bestAny ? { x: bestAny.tileX, y: bestAny.tileY } : null;
408 }
409 if (!best)
410 { return false; }
411 const destX = best.x ?? best.tileX;
412 const destY = best.y ?? best.tileY;
413 if (
414 approachMove
415 && approachMove.focusX === tileX
416 && approachMove.focusY === tileY
417 && approachMove.destX === destX
418 && approachMove.destY === destY
419 )
420 { return false; }
421 approachMove = {
422 focusX: tileX,
423 focusY: tileY,
424 destX,
425 destY
426 };
427 sendPlayerMoveTo(destX, destY);
428 return false;
429}
430
431function requestOpenBank (tileX, tileY, { getCheques = false } = {})
432{
433 clearAllPendingActions();
434 pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques };
435 const local = view?.entities.get(view.localEntityId);
436 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
437 { flushPendingInteract(); }
438 else
439 { approachAdjacentTile(tileX, tileY); }
440}
441
442function requestEnterDoorway (tileX, tileY)
443{
444 clearAllPendingActions();
445 pendingInteract = { kind: "doorway", tileX, tileY };
446 const local = view?.entities.get(view.localEntityId);
447 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
448 { flushPendingInteract(); }
449 else
450 { approachAdjacentTile(tileX, tileY); }
451}
452
453function requestOpenMarket (tileX, tileY)
454{
455 clearAllPendingActions();
456 pendingInteract = { kind: "market", tileX, tileY };
457 const local = view?.entities.get(view.localEntityId);
458 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
459 { flushPendingInteract(); }
460 else
461 { approachAdjacentTile(tileX, tileY); }
462}
463
464function requestOpenBounty (tileX, tileY)
465{
466 clearAllPendingActions();
467 pendingInteract = { kind: "bounty", tileX, tileY };
468 const local = view?.entities.get(view.localEntityId);
469 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
470 { flushPendingInteract(); }
471 else
472 { approachAdjacentTile(tileX, tileY); }
473}
474
475function requestOpenBarber (tileX, tileY)
476{
477 clearAllPendingActions();
478 pendingInteract = { kind: "barber", tileX, tileY };
479 const local = view?.entities.get(view.localEntityId);
480 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
481 { flushPendingInteract(); }
482 else
483 { approachAdjacentTile(tileX, tileY); }
484}
485
486function requestOpenCauldron (tileX, tileY)
487{
488 clearAllPendingActions();
489 pendingInteract = { kind: "cauldron", tileX, tileY };
490 const local = view?.entities.get(view.localEntityId);
491 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
492 { flushPendingInteract(); }
493 else
494 { approachAdjacentTile(tileX, tileY); }
495}
496
497function requestOpenFurnace (tileX, tileY)
498{
499 requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY);
500}
501
502function requestOpenCraftStation (stationId, tileX, tileY)
503{
504 clearAllPendingActions();
505 pendingInteract = { kind: "station", stationId, tileX, tileY };
506 const local = view?.entities.get(view.localEntityId);
507 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
508 { flushPendingInteract(); }
509 else
510 { approachAdjacentTile(tileX, tileY); }
511}
512
513function requestStartFire (ground)
514{
515 if (!ground)
516 { return; }
517 clearAllPendingActions();
518 pendingInteract = {
519 kind: "start-fire",
520 groundItemId: ground.groundItemId,
521 tileX: ground.tileX,
522 tileY: ground.tileY
523 };
524 const local = view?.entities.get(view.localEntityId);
525 if (local && isAdjacentTile(local.tileX, local.tileY, ground.tileX, ground.tileY))
526 { flushPendingInteract(); }
527 else
528 { approachAdjacentTile(ground.tileX, ground.tileY); }
529}
530
531function requestFish (tileX, tileY)
532{
533 clearAllPendingActions();
534 pendingInteract = { kind: "fish", tileX, tileY };
535 const local = view?.entities.get(view.localEntityId);
536 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
537 { flushPendingInteract(); }
538 else
539 { approachAdjacentTile(tileX, tileY); }
540}
541
542function requestMine (tileX, tileY)
543{
544 clearAllPendingActions();
545 pendingInteract = { kind: "mine", tileX, tileY };
546 const local = view?.entities.get(view.localEntityId);
547 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
548 { flushPendingInteract(); }
549 else
550 { approachAdjacentTile(tileX, tileY); }
551}
552
553function requestChop (tileX, tileY)
554{
555 clearAllPendingActions();
556 pendingInteract = { kind: "chop", tileX, tileY };
557 const local = view?.entities.get(view.localEntityId);
558 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
559 { flushPendingInteract(); }
560 else
561 { approachAdjacentTile(tileX, tileY); }
562}
563
564function requestPick (tileX, tileY)
565{
566 clearAllPendingActions();
567 pendingInteract = { kind: "pick", tileX, tileY };
568 const local = view?.entities.get(view.localEntityId);
569 if (local && isAdjacentTile(local.tileX, local.tileY, tileX, tileY))
570 { flushPendingInteract(); }
571 else
572 { approachAdjacentTile(tileX, tileY); }
573}
574
575function requestTalk (targetEntityId, purpose = null)
576{
577 clearAllPendingActions();
578 pendingInteract = { kind: "talk", targetEntityId, purpose };
579 const target = view?.entities.get(targetEntityId);
580 if (!target)
581 {
582 clearPendingInteract();
583 return;
584 }
585 if (approachAdjacentTile(target.tileX, target.tileY))
586 { flushPendingInteract(); }
587}
588
589function playerHasShears ()
590{
591 const slots = inventory?.getInventorySlots?.() ?? [];
592 const equipment = inventory?.getEquipment?.() ?? {};
593 for (const stack of [...slots, equipment.weapon])
594 {
595 if (!stack?.itemId)
596 { continue; }
597 if (itemDefinition(stack.itemId)?.equipment?.kind === EquipmentKind.shears)
598 { return true; }
599 }
600 return false;
601}
602
603function entityCanShear (entity)
604{
605 if (!entity?.mobTypeId)
606 { return false; }
607 const def = mobDefinition(entity.mobTypeId);
608 const shearable = def?.shearable;
609 if (!shearable)
610 { return false; }
611 const sprite = entity.layers?.[0]?.sprite ?? entity.sprite ?? "";
612 if (String(sprite).endsWith(`:${shearable.shornState}`))
613 { return false; }
614 return playerHasShears();
615}
616
617function requestShear (targetEntityId)
618{
619 clearAllPendingActions();
620 pendingInteract = { kind: "shear", targetEntityId };
621 const target = view?.entities.get(targetEntityId);
622 if (!target)
623 {
624 clearPendingInteract();
625 return;
626 }
627 if (approachAdjacentTile(target.tileX, target.tileY))
628 { flushPendingInteract(); }
629}
630
631function setUiFocus (focus)
632{
633 uiFocus = focus;
634}
635
636function clearUiFocus ()
637{
638 uiFocus = null;
639}
640
641/** Close stations, bank, dialogue, and other overlays when the local player dies. */
642function closeCloseablePlayUi ()
643{
644 clearUiFocus();
645 inventory?.closeBank?.();
646 inventory?.closeOverlays?.();
647 if (crafting?.isOpen?.())
648 { crafting.close(); }
649 if (alchemy?.isOpen?.())
650 { alchemy.close(); }
651 if (market?.isOpen?.())
652 { market.close(); }
653 if (bounty?.isOpen?.())
654 { bounty.close(); }
655 if (barber?.isOpen?.())
656 { barber.close(); }
657 if (shop?.isOpen?.())
658 { shop.close(); }
659 if (dialogueUi?.isOpen?.())
660 { dialogueUi.close(); }
661 questsUi?.hide?.();
662 chat?.close?.();
663 social?.closeOverlays?.();
664 contextMenu?.hide();
665 spells?.handleSpellDisarmed?.();
666 graphicsSettingsUi?.close?.();
667}
668
669/** Close bank / station / NPC UIs when the player walks out of adjacency. */
670function closeOpenUiIfTooFar ()
671{
672 if (!uiFocus || !view)
673 { return; }
674 const local = view.entities.get(view.localEntityId);
675 if (!local)
676 { return; }
677
678 let tooFar = false;
679 if (uiFocus.entityId != null)
680 {
681 const target = view.entities.get(uiFocus.entityId);
682 tooFar = !target
683 || !isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY);
684 }
685 else if (uiFocus.tileX != null && uiFocus.tileY != null)
686 {
687 tooFar = !isAdjacentTile(local.tileX, local.tileY, uiFocus.tileX, uiFocus.tileY);
688 }
689 if (!tooFar)
690 { return; }
691
692 const kind = uiFocus.kind;
693 clearUiFocus();
694 switch (kind)
695 {
696 case "bank":
697 if (inventory?.isBankOpen?.())
698 { inventory.closeBank(); }
699 break;
700 case "station":
701 if (crafting?.isOpen?.())
702 { crafting.close(); }
703 break;
704 case "cauldron":
705 if (alchemy?.isOpen?.())
706 { alchemy.close(); }
707 break;
708 case "market":
709 if (market?.isOpen?.())
710 { market.close(); }
711 break;
712 case "bounty":
713 if (bounty?.isOpen?.())
714 { bounty.close(); }
715 break;
716 case "barber":
717 if (barber?.isOpen?.())
718 { barber.close(); }
719 break;
720 case "shop":
721 if (shop?.isOpen?.())
722 { shop.close(); }
723 break;
724 case "dialogue":
725 if (dialogueUi?.isOpen?.())
726 { dialogueUi.close(); }
727 break;
728 default:
729 break;
730 }
731}
732
733function flushPendingInteract ()
734{
735 if (!pendingInteract || !view)
736 { return; }
737 const local = view.entities.get(view.localEntityId);
738 if (!local)
739 { return; }
740
741 if (pendingInteract.kind === "bank")
742 {
743 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
744 { return; }
745 setUiFocus({
746 kind: "bank",
747 tileX: pendingInteract.tileX,
748 tileY: pendingInteract.tileY
749 });
750 const getCheques = !!pendingInteract.getCheques;
751 socket.send({ type: MessageType.openBank });
752 if (getCheques)
753 { inventory?.getBlankCheques(); }
754 clearPendingInteract();
755 return;
756 }
757
758 if (pendingInteract.kind === "doorway")
759 {
760 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
761 { return; }
762 socket.send({
763 type: MessageType.enterDoorway,
764 tileX: pendingInteract.tileX,
765 tileY: pendingInteract.tileY
766 });
767 clearPendingInteract();
768 return;
769 }
770
771 if (pendingInteract.kind === "market")
772 {
773 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
774 { return; }
775 setUiFocus({
776 kind: "market",
777 tileX: pendingInteract.tileX,
778 tileY: pendingInteract.tileY
779 });
780 socket.send({ type: MessageType.openMarket });
781 clearPendingInteract();
782 return;
783 }
784
785 if (pendingInteract.kind === "bounty")
786 {
787 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
788 { return; }
789 setUiFocus({
790 kind: "bounty",
791 tileX: pendingInteract.tileX,
792 tileY: pendingInteract.tileY
793 });
794 socket.send({ type: MessageType.openBounty });
795 clearPendingInteract();
796 return;
797 }
798
799 if (pendingInteract.kind === "barber")
800 {
801 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
802 { return; }
803 setUiFocus({
804 kind: "barber",
805 tileX: pendingInteract.tileX,
806 tileY: pendingInteract.tileY
807 });
808 socket.send({ type: MessageType.openBarber });
809 clearPendingInteract();
810 return;
811 }
812
813 if (pendingInteract.kind === "cauldron")
814 {
815 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
816 { return; }
817 setUiFocus({
818 kind: "cauldron",
819 tileX: pendingInteract.tileX,
820 tileY: pendingInteract.tileY
821 });
822 socket.send({ type: MessageType.openCauldron });
823 clearPendingInteract();
824 return;
825 }
826
827 if (pendingInteract.kind === "station")
828 {
829 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
830 { return; }
831 setUiFocus({
832 kind: "station",
833 tileX: pendingInteract.tileX,
834 tileY: pendingInteract.tileY
835 });
836 socket.send({
837 type: MessageType.openStation,
838 stationId: pendingInteract.stationId
839 });
840 clearPendingInteract();
841 return;
842 }
843
844 if (pendingInteract.kind === "mine")
845 {
846 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
847 { return; }
848 socket.send({
849 type: MessageType.mine,
850 tileX: pendingInteract.tileX,
851 tileY: pendingInteract.tileY
852 });
853 clearPendingInteract();
854 return;
855 }
856
857 if (pendingInteract.kind === "start-fire")
858 {
859 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
860 { return; }
861 socket.send({
862 type: MessageType.startFire,
863 groundItemId: pendingInteract.groundItemId
864 });
865 clearPendingInteract();
866 return;
867 }
868
869 if (pendingInteract.kind === "fish")
870 {
871 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
872 { return; }
873 socket.send({
874 type: MessageType.startFish,
875 tileX: pendingInteract.tileX,
876 tileY: pendingInteract.tileY
877 });
878 clearPendingInteract();
879 return;
880 }
881
882 if (pendingInteract.kind === "chop")
883 {
884 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
885 { return; }
886 socket.send({
887 type: MessageType.chop,
888 tileX: pendingInteract.tileX,
889 tileY: pendingInteract.tileY
890 });
891 clearPendingInteract();
892 return;
893 }
894
895 if (pendingInteract.kind === "pick")
896 {
897 if (!isAdjacentTile(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY))
898 { return; }
899 socket.send({
900 type: MessageType.pick,
901 tileX: pendingInteract.tileX,
902 tileY: pendingInteract.tileY
903 });
904 clearPendingInteract();
905 return;
906 }
907
908 if (pendingInteract.kind === "talk")
909 {
910 const target = view.entities.get(pendingInteract.targetEntityId);
911 if (!target)
912 {
913 clearPendingInteract();
914 return;
915 }
916 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY))
917 {
918 // Target may have moved — keep chasing.
919 approachAdjacentTile(target.tileX, target.tileY);
920 return;
921 }
922 socket.send({
923 type: MessageType.interact,
924 targetEntityId: pendingInteract.targetEntityId,
925 purpose: pendingInteract.purpose || undefined
926 });
927 // Shop vs dialogue is decided server-side; both use NPC adjacency.
928 setUiFocus({
929 kind: pendingInteract.purpose === "shop" ? "shop" : "dialogue",
930 entityId: pendingInteract.targetEntityId
931 });
932 clearPendingInteract();
933 return;
934 }
935
936 if (pendingInteract.kind === "shear")
937 {
938 const target = view.entities.get(pendingInteract.targetEntityId);
939 if (!target)
940 {
941 clearPendingInteract();
942 return;
943 }
944 if (!isAdjacentTile(local.tileX, local.tileY, target.tileX, target.tileY))
945 {
946 approachAdjacentTile(target.tileX, target.tileY);
947 return;
948 }
949 socket.send({
950 type: MessageType.shear,
951 targetEntityId: pendingInteract.targetEntityId
952 });
953 clearPendingInteract();
954 }
955}
956
957function requestPickup (ground)
958{
959 if (!ground)
960 { return; }
961 clearPendingInteract();
962 pendingPickup = {
963 groundItemId: ground.groundItemId,
964 tileX: ground.tileX,
965 tileY: ground.tileY
966 };
967 const local = view.entities.get(view.localEntityId);
968 if (local && local.tileX === ground.tileX && local.tileY === ground.tileY)
969 {
970 flushPendingPickup();
971 return;
972 }
973 sendPlayerMoveTo(ground.tileX, ground.tileY);
974}
975
976function flushPendingPickup ()
977{
978 if (!pendingPickup || !view)
979 { return; }
980 const item = view.groundItems.get(pendingPickup.groundItemId);
981 if (!item)
982 {
983 clearPendingPickup();
984 return;
985 }
986 const local = view.entities.get(view.localEntityId);
987 if (!local)
988 { return; }
989 if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY)
990 { return; }
991 socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId });
992 clearPendingPickup();
993}
994
995function requestAttack (targetEntityId)
996{
997 clearAllPendingActions();
998 setAutorunFocusEntity(targetEntityId);
999 socket.send({ type: MessageType.attack, targetEntityId });
1000}
1001
1002function isAttackableEntity (entity)
1003{
1004 if (!entity || entity.untargetable)
1005 { return false; }
1006 if (entity.canFight)
1007 { return true; }
1008 // Snapshots can omit canFight; mobs are still attackable via LMB.
1009 return !!entity.mobTypeId && !entity.talkable;
1010}
1011
1012function canTalkToEntity (entity)
1013{
1014 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
1015}
1016
1017function isApproachingCombatOrCast ()
1018{
1019 return autorunFocusEntityId != null || autorunFocusTile != null;
1020}
1021
1022function handleLeftClick (mouseX, mouseY)
1023{
1024 const tile = view.screenToTile(mouseX, mouseY);
1025 const armed = spells?.getArmedSpell?.();
1026 const approaching = isApproachingCombatOrCast();
1027
1028 // Entity-armed: cast only when a valid target is under the cursor. Empty ground
1029 // must fall through so walk cancels cast/attack approach (server moveTo clears it).
1030 if (armed?.target === "entity" && armed.canCast)
1031 {
1032 const snap = nearestSpellEntityAtCursor(mouseX, mouseY);
1033 if (snap && spells.tryCastAtEntity(snap.entityId))
1034 {
1035 setAutorunFocusEntity(snap.entityId);
1036 return;
1037 }
1038 }
1039 // Tile-armed while approaching: prefer walk-cancel over re-targeting the cast.
1040 else if (
1041 !approaching
1042 && armed?.target === "tile"
1043 && armed.canCast
1044 && spells.tryCastAtTile(tile.tileX, tile.tileY)
1045 )
1046 {
1047 setAutorunFocusTile(tile.tileX, tile.tileY);
1048 return;
1049 }
1050
1051 const entity = view.entityAtScreen(mouseX, mouseY);
1052 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
1053 {
1054 clearPendingPickup();
1055 if (entity.characterId)
1056 {
1057 clearPendingInteract();
1058 social.inspect(entity);
1059 return;
1060 }
1061 // Dialogue (or shop/talkable) wins over attack as the default click.
1062 if (canTalkToEntity(entity))
1063 {
1064 // Same intent as context-menu Talk / Shop so dialogue pin matches.
1065 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
1066 ? "talk"
1067 : (entity.hasShop ? "shop" : "talk");
1068 requestTalk(entity.entityId, purpose);
1069 return;
1070 }
1071 if (isAttackableEntity(entity))
1072 {
1073 requestAttack(entity.entityId);
1074 return;
1075 }
1076 // Clicked an entity we don't act on — do not fall through to walk (that cancels combat).
1077 return;
1078 }
1079
1080 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
1081 if (ground)
1082 { requestPickup(ground); }
1083 else if (isBankTile(view, tile.tileX, tile.tileY))
1084 { requestOpenBank(tile.tileX, tile.tileY); }
1085 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
1086 { requestEnterDoorway(tile.tileX, tile.tileY); }
1087 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1088 { requestOpenMarket(tile.tileX, tile.tileY); }
1089 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1090 { requestOpenBounty(tile.tileX, tile.tileY); }
1091 else if (isBarberTile(view, tile.tileX, tile.tileY))
1092 { requestOpenBarber(tile.tileX, tile.tileY); }
1093 else if (isCauldronTile(view, tile.tileX, tile.tileY))
1094 { requestOpenCauldron(tile.tileX, tile.tileY); }
1095 else if (isFurnaceTile(view, tile.tileX, tile.tileY))
1096 { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); }
1097 else if (isOvenTile(view, tile.tileX, tile.tileY))
1098 { requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY); }
1099 else if (isCampfireTile(view, tile.tileX, tile.tileY))
1100 { requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY); }
1101 else if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1102 { requestFish(tile.tileX, tile.tileY); }
1103 else if (isAnvilTile(view, tile.tileX, tile.tileY))
1104 { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); }
1105 else if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1106 { requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY); }
1107 else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1108 { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); }
1109 else if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1110 { requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY); }
1111 else if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1112 { requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY); }
1113 else if (isLoomTile(view, tile.tileX, tile.tileY))
1114 { requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY); }
1115 else if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1116 { requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY); }
1117 else if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1118 { requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY); }
1119 else if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1120 { requestMine(tile.tileX, tile.tileY); }
1121 else if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1122 { requestChop(tile.tileX, tile.tileY); }
1123 else if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1124 { requestPick(tile.tileX, tile.tileY); }
1125 else
1126 {
1127 clearAllPendingActions();
1128 sendPlayerMoveTo(tile.tileX, tile.tileY);
1129 }
1130}
1131
1132function handleRightClick (event, mouseX, mouseY)
1133{
1134 event.preventDefault();
1135 if (spells?.isTargeting?.())
1136 {
1137 spells.cancelTargeting();
1138 view?.clearSpellTargetHighlight();
1139 return;
1140 }
1141 const tile = view.screenToTile(mouseX, mouseY);
1142 const items = [];
1143 const walkTileX = tile.tileX;
1144 const walkTileY = tile.tileY;
1145
1146 items.push({
1147 label: "Walk here",
1148 onSelect: () =>
1149 {
1150 clearAllPendingActions();
1151 sendPlayerMoveTo(walkTileX, walkTileY);
1152 }
1153 });
1154
1155 for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY, { includePrevious: true }))
1156 {
1157 if (entity.entityId === view.localEntityId)
1158 {
1159 const equipment = { slots: inventory?.getEquipment?.() ?? {} };
1160 if (canTeleportToChurch(equipment))
1161 {
1162 items.push({
1163 label: "Teleport to Church",
1164 onSelect: () =>
1165 {
1166 clearAllPendingActions();
1167 socket.send({
1168 type: MessageType.jewelryTeleport,
1169 destination: "church"
1170 });
1171 }
1172 });
1173 }
1174 if (canTeleportToBank(equipment))
1175 {
1176 items.push({
1177 label: "Teleport to bank",
1178 onSelect: () =>
1179 {
1180 clearAllPendingActions();
1181 socket.send({
1182 type: MessageType.jewelryTeleport,
1183 destination: "bank"
1184 });
1185 }
1186 });
1187 }
1188 continue;
1189 }
1190 const targetName = entityLabel(entity);
1191 items.push({
1192 label: `Follow ${targetName}`,
1193 onSelect: () =>
1194 {
1195 clearAllPendingActions();
1196 sendPlayerFollow(entity.entityId);
1197 }
1198 });
1199 if (entity.untargetable)
1200 { continue; }
1201 if (entity.hasShop)
1202 {
1203 items.push({
1204 label: `Shop ${targetName}`,
1205 onSelect: () => requestTalk(entity.entityId, "shop")
1206 });
1207 }
1208 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
1209 {
1210 items.push({
1211 label: `Talk to ${targetName}`,
1212 onSelect: () => requestTalk(entity.entityId, "talk")
1213 });
1214 }
1215 if (entityCanShear(entity))
1216 {
1217 items.push({
1218 label: `Shear ${targetName}`,
1219 onSelect: () => requestShear(entity.entityId)
1220 });
1221 }
1222 if (entity.characterId)
1223 {
1224 items.push({
1225 label: `${targetName} info`,
1226 onSelect: () =>
1227 {
1228 clearAllPendingActions();
1229 social.inspect(entity);
1230 }
1231 });
1232 }
1233 items.push({
1234 label: `Attack ${targetName}`,
1235 onSelect: () => requestAttack(entity.entityId)
1236 });
1237 }
1238
1239 for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY))
1240 {
1241 const name = groundLabel(ground);
1242 items.push({
1243 label: `Pick up ${name}`,
1244 onSelect: () => requestPickup(ground)
1245 });
1246 if (playerHasUsableTinderbox() && isGroundWoodLog(ground))
1247 {
1248 items.push({
1249 label: `Start Fire`,
1250 onSelect: () => requestStartFire(ground)
1251 });
1252 }
1253 }
1254
1255 if (isBankTile(view, tile.tileX, tile.tileY))
1256 {
1257 items.push({
1258 label: "Bank",
1259 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
1260 });
1261 items.push({
1262 label: "Get Blank Cheques",
1263 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
1264 });
1265 }
1266
1267 if (isDoorwayTile(view, tile.tileX, tile.tileY))
1268 {
1269 items.push({
1270 label: "Enter",
1271 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
1272 });
1273 }
1274
1275 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
1276 {
1277 items.push({
1278 label: "Central Exchange",
1279 onSelect: () => requestOpenMarket(tile.tileX, tile.tileY)
1280 });
1281 }
1282
1283 if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
1284 {
1285 items.push({
1286 label: "Bounty Office",
1287 onSelect: () => requestOpenBounty(tile.tileX, tile.tileY)
1288 });
1289 }
1290
1291 if (isBarberTile(view, tile.tileX, tile.tileY))
1292 {
1293 items.push({
1294 label: "Barber",
1295 onSelect: () => requestOpenBarber(tile.tileX, tile.tileY)
1296 });
1297 }
1298
1299 if (isCauldronTile(view, tile.tileX, tile.tileY))
1300 {
1301 items.push({
1302 label: "Alchemy",
1303 onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY)
1304 });
1305 }
1306
1307 if (isFurnaceTile(view, tile.tileX, tile.tileY))
1308 {
1309 items.push({
1310 label: "Smelt",
1311 onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY)
1312 });
1313 }
1314
1315 if (isOvenTile(view, tile.tileX, tile.tileY))
1316 {
1317 items.push({
1318 label: "Cook",
1319 onSelect: () => requestOpenCraftStation(CraftingStationId.oven, tile.tileX, tile.tileY)
1320 });
1321 }
1322
1323 if (isCampfireTile(view, tile.tileX, tile.tileY))
1324 {
1325 items.push({
1326 label: "Cook",
1327 onSelect: () => requestOpenCraftStation(CraftingStationId.fireplace, tile.tileX, tile.tileY)
1328 });
1329 }
1330
1331 if (isFishingSpotTile(view, tile.tileX, tile.tileY))
1332 {
1333 items.push({
1334 label: "Fish",
1335 onSelect: () => requestFish(tile.tileX, tile.tileY)
1336 });
1337 }
1338
1339 if (isAnvilTile(view, tile.tileX, tile.tileY))
1340 {
1341 items.push({
1342 label: "Smith",
1343 onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY)
1344 });
1345 }
1346
1347 if (isJeweleringStationTile(view, tile.tileX, tile.tileY))
1348 {
1349 items.push({
1350 label: "Jewel",
1351 onSelect: () => requestOpenCraftStation(CraftingStationId.jeweleringStation, tile.tileX, tile.tileY)
1352 });
1353 }
1354
1355 if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY))
1356 {
1357 items.push({
1358 label: "Woodwork",
1359 onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY)
1360 });
1361 }
1362
1363 if (isCraftingBenchTile(view, tile.tileX, tile.tileY))
1364 {
1365 items.push({
1366 label: "Craft",
1367 onSelect: () => requestOpenCraftStation(CraftingStationId.craftingBench, tile.tileX, tile.tileY)
1368 });
1369 }
1370
1371 if (isSpinningWheelTile(view, tile.tileX, tile.tileY))
1372 {
1373 items.push({
1374 label: "Spin",
1375 onSelect: () => requestOpenCraftStation(CraftingStationId.spinningWheel, tile.tileX, tile.tileY)
1376 });
1377 }
1378
1379 if (isLoomTile(view, tile.tileX, tile.tileY))
1380 {
1381 items.push({
1382 label: "Weave",
1383 onSelect: () => requestOpenCraftStation(CraftingStationId.loom, tile.tileX, tile.tileY)
1384 });
1385 }
1386
1387 if (isTailorBenchTile(view, tile.tileX, tile.tileY))
1388 {
1389 items.push({
1390 label: "Tailor",
1391 onSelect: () => requestOpenCraftStation(CraftingStationId.tailorBench, tile.tileX, tile.tileY)
1392 });
1393 }
1394
1395 if (isLeatherworkingTableTile(view, tile.tileX, tile.tileY))
1396 {
1397 items.push({
1398 label: "Leatherwork",
1399 onSelect: () => requestOpenCraftStation(CraftingStationId.leatherworkingStation, tile.tileX, tile.tileY)
1400 });
1401 }
1402
1403 if (isOreBoulderTile(view, tile.tileX, tile.tileY))
1404 {
1405 items.push({
1406 label: "Mine",
1407 onSelect: () => requestMine(tile.tileX, tile.tileY)
1408 });
1409 }
1410
1411 if (isChopableTreeTile(view, tile.tileX, tile.tileY))
1412 {
1413 items.push({
1414 label: "Chop",
1415 onSelect: () => requestChop(tile.tileX, tile.tileY)
1416 });
1417 }
1418
1419 if (isPickablePlantTile(view, tile.tileX, tile.tileY))
1420 {
1421 items.push({
1422 label: "Pick",
1423 onSelect: () => requestPick(tile.tileX, tile.tileY)
1424 });
1425 }
1426
1427 contextMenu.show(event.clientX, event.clientY, items);
1428}
1429
1430function entityLabel (entity)
1431{
1432 if (entity?.mobTypeId)
1433 {
1434 const def = mobDefinition(entity.mobTypeId);
1435 const first = (entity?.firstName ?? "").trim();
1436 const last = (entity?.lastName ?? "").trim();
1437 // Fairies keep type name in tooltips ("Lv.n Fairy") even when firstName is "Ada's Fairy".
1438 const name = first && last
1439 ? `${first} ${last}`
1440 : (entity.mobTypeId === MobId.fairy
1441 ? (def?.displayName || "Fairy")
1442 : (first || def?.displayName || "Creature"));
1443 const level = entity?.level ?? def?.attackSkill ?? 1;
1444 return mobLevelDisplayName(level, name);
1445 }
1446 const first = (entity?.firstName ?? "").trim();
1447 const last = (entity?.lastName ?? "").trim();
1448 return first && last ? `${first} ${last}` : (first || "target");
1449}
1450
1451function groundLabel (ground)
1452{
1453 const name = (ground?.displayName ?? "").trim() || "item";
1454 const qty = ground?.quantity ?? 1;
1455 if (qty <= 1)
1456 { return name; }
1457 return `${name} (${formatQuantity(qty)})`;
1458}
1459
1460function startPlay (payload)
1461{
1462 playing = true;
1463 overlay.hidden = true;
1464 hud.hidden = false;
1465 const settingsToggle = document.getElementById("settings-toggle");
1466 if (settingsToggle)
1467 { settingsToggle.hidden = false; }
1468 document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`;
1469 gait = payload.gait ?? GAIT.walk;
1470 document.getElementById("gait").textContent = gait;
1471 staminaUi?.show();
1472 healthUi?.show();
1473 statusEffectsUi?.show();
1474 if (payload.stamina != null)
1475 { staminaUi?.apply(payload.stamina); }
1476 if (payload.health != null || payload.maxHealth != null)
1477 {
1478 healthUi?.apply({
1479 current: payload.health ?? healthUi.getCurrent?.(),
1480 max: payload.maxHealth ?? healthUi.getMax?.()
1481 });
1482 }
1483 if (!scene)
1484 {
1485 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1486 game.loadScene(scene);
1487 useNearestNeighbour(scene, game.images);
1488 }
1489 if (!view)
1490 {
1491 view = new WorldView(game, scene, catalog);
1492 graphicsSettingsUi?.apply();
1493 const ticker = new GameObject(0, 0, null, 10);
1494 ticker.update = (dt) =>
1495 {
1496 const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left);
1497 const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left);
1498 if (!leftPressed && !leftHeld)
1499 { leftClickConsumed = false; }
1500 else if (!leftClickConsumed && playing && !uiBlocked())
1501 {
1502 leftClickConsumed = true;
1503 const canvas = scene.canvas;
1504 const rect = canvas.getBoundingClientRect();
1505 const mouseX = GameInput.mousePosition.x - rect.left;
1506 const mouseY = GameInput.mousePosition.y - rect.top;
1507 handleLeftClick(mouseX, mouseY);
1508 }
1509 if (GameInput.isPressed(82) && !uiBlocked())
1510 {
1511 const next = gait === GAIT.run ? GAIT.walk : GAIT.run;
1512 if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0)
1513 { return; }
1514 socket.send({ type: MessageType.setGait, gait: next });
1515 // Walk always applies; run waits for authoritative STAMINA (may reject if empty).
1516 if (next === GAIT.walk)
1517 {
1518 gait = next;
1519 document.getElementById("gait").textContent = gait;
1520 }
1521 }
1522 if (playing && !death?.isBlocking())
1523 {
1524 flushPendingPickup();
1525 flushPendingInteract();
1526 syncAutorun();
1527 social?.updateNametag(view, scene, view.localEntityId);
1528 chat?.update(view, scene);
1529 updateSpellTargetHighlight();
1530 updateWorldTooltip();
1531 }
1532 else
1533 {
1534 hideWorldTooltip();
1535 view?.clearSpellTargetHighlight();
1536 }
1537 view.update(dt);
1538 };
1539 scene.addObject(ticker);
1540 window.addEventListener("resize", () =>
1541 {
1542 scene.size.x = window.innerWidth;
1543 scene.size.y = window.innerHeight;
1544 scene.g_fixSize();
1545 useNearestNeighbour(scene, game.images);
1546 });
1547 window.addEventListener("wheel", (event) =>
1548 {
1549 if (!playing || uiBlocked())
1550 { return; }
1551 playZoomDelta += event.deltaY < 0 ? 0.25 : -0.25;
1552 if (playZoomRaf)
1553 { return; }
1554 playZoomRaf = requestAnimationFrame(() =>
1555 {
1556 playZoomRaf = 0;
1557 if (!view || !playZoomDelta)
1558 { return; }
1559 view.setZoom(view.zoom + playZoomDelta);
1560 playZoomDelta = 0;
1561 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
1562 });
1563 }, { passive: true });
1564 scene.canvas.addEventListener("contextmenu", (event) =>
1565 {
1566 if (!playing || uiBlocked())
1567 { return; }
1568 const rect = scene.canvas.getBoundingClientRect();
1569 handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top);
1570 });
1571 }
1572 view.setSettings(payload.settings ?? view.settings);
1573 chat?.syncSettings();
1574 view.worldHour = payload.worldTime?.hour ?? 12;
1575 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
1576 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
1577 view.setWorldSeason(payload.worldTime?.season);
1578 view.setLocalEntity(
1579 payload.entityId,
1580 payload.tileX,
1581 payload.tileY,
1582 payload.gait,
1583 payload.sex,
1584 payload.firstName,
1585 payload.lastName,
1586 payload.characterId,
1587 payload.layers,
1588 payload.health,
1589 payload.maxHealth,
1590 payload.skullValue
1591 );
1592 social?.setLocalIdentity?.({
1593 accountId: payload.accountId,
1594 characterId: payload.characterId
1595 });
1596 graphicsSettingsUi?.apply();
1597}
1598
1599async function main ()
1600{
1601 const authStatus = await fetchAuthStatus();
1602 updateAuthUi(authStatus);
1603 if (!authStatus.authenticated)
1604 {
1605 statusEl.textContent = "Sign in to play Questward.";
1606 showError("");
1607 return;
1608 }
1609
1610 setAssetLoading(true, { phase: "Loading catalog…" });
1611 catalog = await loadSpriteCatalog();
1612 const assetTotal = playImagesFromCatalog(catalog).length;
1613 setAssetLoading(true, { loaded: 0, total: assetTotal, phase: "Loading assets…" });
1614 await preloadCatalogImages(game, catalog, {
1615 onProgress ({ loaded, total })
1616 {
1617 setAssetLoading(true, { loaded, total });
1618 }
1619 });
1620 applySpriteSheets(game.images, catalog);
1621 if (!scene)
1622 {
1623 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
1624 game.loadScene(scene);
1625 }
1626 setAssetLoading(false);
1627 statusEl.textContent = "Connecting…";
1628 createHairControls = bindHairControls({
1629 root: document.getElementById("create-hair"),
1630 resolveSpriteUrl (name)
1631 {
1632 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1633 },
1634 getSex: () => document.getElementById("sex")?.value ?? "male",
1635 getBag: () => null,
1636 hideHeadgear: true,
1637 onChange ()
1638 {
1639 if (createActiveTab === "clothing")
1640 { void refreshCreateClothingPreview(); }
1641 }
1642 });
1643 createClothingControls = bindCreateClothingControls({
1644 root: document.getElementById("create-clothing"),
1645 onChange ()
1646 {
1647 if (createActiveTab === "clothing")
1648 { void refreshCreateClothingPreview(); }
1649 }
1650 });
1651 initCreateTabs();
1652 document.getElementById("sex")?.addEventListener("change", () =>
1653 {
1654 createHairControls?.fillStyles();
1655 void createHairControls?.refreshPreview();
1656 if (createActiveTab === "clothing")
1657 { void refreshCreateClothingPreview(); }
1658 });
1659 void createHairControls?.refreshPreview();
1660 void refreshCreateClothingPreview();
1661 graphicsSettingsUi = initGraphicsSettings({
1662 onChange: applyGraphicsSettings,
1663 onSuppressWorldClick: consumeWorldClick
1664 });
1665 social = initSocial({
1666 socket: { send (payload) { socket.send(payload); } },
1667 MessageType,
1668 resolveSpriteUrl (name)
1669 {
1670 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1671 },
1672 resolveImage (name)
1673 {
1674 return game?.images?.[name] ?? null;
1675 }
1676 });
1677 contextMenu = initContextMenu({ onSuppressWorldClick: consumeWorldClick });
1678 const tipArrows = initTipArrows({
1679 socket: { send (payload) { socket.send(payload); } },
1680 MessageType,
1681 getInventoryBag ()
1682 {
1683 return inventory?.getBag?.() ?? null;
1684 }
1685 });
1686 inventory = initInventory({
1687 socket: { send (payload) { socket.send(payload); } },
1688 MessageType,
1689 contextMenu,
1690 tipArrows,
1691 resolveSpriteUrl (name)
1692 {
1693 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1694 },
1695 resolveImage (name)
1696 {
1697 return game?.images?.[name] ?? null;
1698 },
1699 getFriends ()
1700 {
1701 return social?.getFriends?.() ?? [];
1702 },
1703 getLocalName ()
1704 {
1705 const you = document.getElementById("you")?.textContent ?? "";
1706 return you.split("(")[0].trim() || "Unknown";
1707 },
1708 getSoftClaims ()
1709 {
1710 return alchemy?.listSoftClaims?.() ?? [];
1711 },
1712 knowsSpell (spellId)
1713 {
1714 return !!spells?.knowsSpell?.(spellId);
1715 },
1716 getSkillLevels ()
1717 {
1718 return skills?.getSkillLevels?.() ?? {};
1719 },
1720 getSettings ()
1721 {
1722 return view?.settings ?? null;
1723 },
1724 getKnownSpellIds ()
1725 {
1726 return spells?.getKnownSpellIds?.() ?? [];
1727 },
1728 onBagChanged ()
1729 {
1730 spells?.refreshMaxHitDisplay?.();
1731 }
1732 });
1733 skills = initSkills({
1734 getEquipmentSlots ()
1735 {
1736 return inventory?.getEquipment?.() ?? {};
1737 },
1738 getSettings ()
1739 {
1740 return view?.settings ?? null;
1741 }
1742 });
1743 spells = initSpells({
1744 socket: { send (payload) { socket.send(payload); } },
1745 MessageType,
1746 getSkillLevel (skillId)
1747 {
1748 return skills?.skillLevel?.(skillId) ?? 1;
1749 },
1750 getSkillLevels ()
1751 {
1752 return skills?.getSkillLevels?.() ?? {};
1753 },
1754 getEquipmentSlots ()
1755 {
1756 return inventory?.getEquipment?.() ?? {};
1757 },
1758 getSettings ()
1759 {
1760 return view?.settings ?? null;
1761 }
1762 });
1763 crafting = initCrafting({
1764 socket: { send (payload) { socket.send(payload); } },
1765 MessageType,
1766 getInventorySlots ()
1767 {
1768 return inventory?.getInventorySlots?.() ?? [];
1769 },
1770 getEquipment ()
1771 {
1772 return inventory?.getEquipment?.() ?? {};
1773 },
1774 getSkillLevel (skillId)
1775 {
1776 return skills?.skillLevel?.(skillId) ?? 1;
1777 }
1778 });
1779 alchemy = initAlchemy({
1780 socket: { send (payload) { socket.send(payload); } },
1781 MessageType,
1782 getInventorySlots ()
1783 {
1784 return inventory?.getInventorySlots?.() ?? [];
1785 }
1786 });
1787 alchemy?.setOnSoftClaimsChanged?.(() => inventory?.refreshBagDisplay?.());
1788 staminaUi = initStamina();
1789 healthUi = initHealth();
1790 statusEffectsUi = initStatusEffects();
1791 toasts = initToasts();
1792 questsUi = initQuests({
1793 socket: { send (payload) { socket.send(payload); } },
1794 MessageType,
1795 toasts
1796 });
1797 dialogueUi = initDialogue({
1798 socket: { send (payload) { socket.send(payload); } },
1799 MessageType,
1800 getEntity (id)
1801 {
1802 if (id === "local")
1803 { return view?.entities.get(view.localEntityId) ?? null; }
1804 return view?.entities.get(id) ?? null;
1805 },
1806 captureSpeakerIcon (entityId, size = 64)
1807 {
1808 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1809 }
1810 });
1811 shop = initShop({
1812 socket: { send (payload) { socket.send(payload); } },
1813 MessageType,
1814 onSuppressWorldClick: consumeWorldClick,
1815 getCoinCount ()
1816 {
1817 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1818 },
1819 getInventorySlots ()
1820 {
1821 return inventory?.getInventorySlots?.() ?? [];
1822 }
1823 });
1824 market = initMarket({
1825 socket: { send (payload) { socket.send(payload); } },
1826 MessageType,
1827 onSuppressWorldClick: consumeWorldClick,
1828 getCoinCount ()
1829 {
1830 return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []);
1831 },
1832 getInventorySlots ()
1833 {
1834 return inventory?.getInventorySlots?.() ?? [];
1835 },
1836 getLocalCharacterId ()
1837 {
1838 return inventory?.getLocalCharacterId?.() ?? null;
1839 }
1840 });
1841 bounty = initBounty({
1842 socket: { send (payload) { socket.send(payload); } },
1843 MessageType,
1844 onSuppressWorldClick: consumeWorldClick,
1845 resolveSpriteUrl (name)
1846 {
1847 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1848 },
1849 resolveImage (name)
1850 {
1851 return game?.images?.[name] ?? null;
1852 }
1853 });
1854 barber = initBarber({
1855 socket: { send (payload) { socket.send(payload); } },
1856 MessageType,
1857 onSuppressWorldClick: consumeWorldClick,
1858 resolveSpriteUrl (name)
1859 {
1860 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
1861 },
1862 getInventoryBag ()
1863 {
1864 return {
1865 equipment: { slots: inventory?.getEquipment?.() ?? {} },
1866 inventory: inventory?.getInventorySlots?.() ?? []
1867 };
1868 }
1869 });
1870 chat = initChat({
1871 socket: { send (payload) { socket.send(payload); } },
1872 MessageType,
1873 getSettings: () => view?.settings
1874 });
1875 death = initDeath({
1876 socket: { send (payload) { socket.send(payload); } },
1877 MessageType
1878 });
1879 game.startGame();
1880 useNearestNeighbour(scene, game.images);
1881
1882 socket = new GameSocket(defaultSocketUrl(), (message) =>
1883 {
1884 switch (message.type)
1885 {
1886 case MessageType.session:
1887 session = message;
1888 statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1889 renderCharacters(message.characters);
1890 break;
1891 case MessageType.characterList:
1892 renderCharacters(message.characters);
1893 if (!playing)
1894 { overlay.hidden = false; }
1895 break;
1896 case MessageType.enterWorld:
1897 closeCreateModal();
1898 startPlay(message);
1899 inventory?.setLocalCharacterId(message.characterId);
1900 toasts?.applyRestartStatus?.(message.restartStatus);
1901 socket.send({ type: MessageType.requestQuests });
1902 break;
1903 case MessageType.chunkSnapshot:
1904 view?.applySnapshot(message);
1905 break;
1906 case MessageType.dimensionChanged:
1907 if (view)
1908 {
1909 view.setDimensionId(message.dimensionId);
1910 view.setDimensionModes(message.lightingMode, message.seasonMode);
1911 view.clearAllChunks();
1912 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1913 {
1914 view.moveEntity({
1915 entityId: view.localEntityId,
1916 tileX: message.tileX,
1917 tileY: message.tileY
1918 });
1919 }
1920 }
1921 closeOpenUiIfTooFar();
1922 break;
1923 case MessageType.chunkDelta:
1924 for (const tile of message.tiles ?? [])
1925 {
1926 view?.updateAuthoredTile(
1927 message.chunkX,
1928 message.chunkY,
1929 tile.localX,
1930 tile.localY,
1931 { ground: tile.ground, block: tile.block, light: tile.light }
1932 );
1933 }
1934 break;
1935 case MessageType.unsubscribeChunk:
1936 view?.removeChunk(message.chunkX, message.chunkY);
1937 break;
1938 case MessageType.entitySpawn:
1939 view?.spawnEntity(message);
1940 break;
1941 case MessageType.entityMove:
1942 view?.moveEntity(message);
1943 if (message.entityId === view?.localEntityId)
1944 {
1945 if (message.gait)
1946 {
1947 gait = message.gait;
1948 document.getElementById("gait").textContent = gait;
1949 }
1950 closeOpenUiIfTooFar();
1951 }
1952 else if (
1953 uiFocus?.entityId != null
1954 && message.entityId === uiFocus.entityId
1955 )
1956 { closeOpenUiIfTooFar(); }
1957 break;
1958 case MessageType.entityDespawn:
1959 if (message.entityId === autorunFocusEntityId)
1960 { clearAutorunFocus(); }
1961 view?.despawnEntity(message.entityId);
1962 break;
1963 case MessageType.entityAppearance:
1964 view?.setAppearance(message);
1965 break;
1966 case MessageType.entitySkull:
1967 view?.updateEntitySkull(message.entityId, message.skullValue);
1968 break;
1969 case MessageType.groundItemAppear:
1970 view?.upsertGroundItem(message);
1971 break;
1972 case MessageType.groundItemDespawn:
1973 view?.despawnGroundItem(message.groundItemId);
1974 break;
1975 case MessageType.inventory:
1976 inventory?.handleInventory(message);
1977 skills?.refresh?.();
1978 crafting?.refresh();
1979 alchemy?.refresh();
1980 shop?.refresh();
1981 market?.refresh();
1982 break;
1983 case MessageType.skills:
1984 skills?.render(message.skills, message.combatLevel);
1985 inventory?.refreshMaxHit?.();
1986 spells?.refreshMaxHitDisplay?.();
1987 crafting?.refresh();
1988 spells?.refreshCastGates?.();
1989 break;
1990 case MessageType.spells:
1991 case MessageType.spellsUpdated:
1992 spells?.render(message);
1993 inventory?.refreshMaxHit?.();
1994 break;
1995 case MessageType.spellArmed:
1996 spells?.handleSpellArmed(message);
1997 break;
1998 case MessageType.spellDisarmed:
1999 spells?.handleSpellDisarmed();
2000 break;
2001 case MessageType.spellProjectile:
2002 view?.spawnSpellProjectileFx(message);
2003 if (message.casterId === view?.localEntityId)
2004 { clearAutorunFocus(); }
2005 break;
2006 case MessageType.spellFizzle:
2007 view?.spawnSpellFizzleFx(message);
2008 if (message.casterId === view?.localEntityId)
2009 {
2010 clearAutorunFocus();
2011 toasts?.show("Failed to cast spell");
2012 }
2013 break;
2014 case MessageType.spellCastFlash:
2015 // Cast-flash dynamic lights skipped (lightmap rebake cost); Light spell uses spellLight*.
2016 if (message.casterId === view?.localEntityId)
2017 { clearAutorunFocus(); }
2018 break;
2019 case MessageType.spellLightAppear:
2020 case MessageType.spellLightUpdate:
2021 view?.setSpellLight(message);
2022 break;
2023 case MessageType.spellLightRemove:
2024 view?.removeSpellLight(message);
2025 break;
2026 case MessageType.spellDarkAppear:
2027 case MessageType.spellDarkUpdate:
2028 view?.setSpellDark(message);
2029 break;
2030 case MessageType.spellDarkRemove:
2031 view?.removeSpellDark(message);
2032 break;
2033 case MessageType.stamina:
2034 staminaUi?.apply(message);
2035 if (message.gait)
2036 {
2037 gait = message.gait;
2038 document.getElementById("gait").textContent = gait;
2039 if (gait === GAIT.walk && (staminaUi?.getCurrent?.() ?? 0) <= 0)
2040 { autorunWaitingStamina = true; }
2041 }
2042 syncAutorun();
2043 break;
2044 case MessageType.statusEffects:
2045 view?.setLocalBlind(!!message.blind);
2046 statusEffectsUi?.apply(message);
2047 break;
2048 case MessageType.bankSnapshot:
2049 inventory?.handleBank(message);
2050 break;
2051 case MessageType.cauldronSnapshot:
2052 if (message.open === false && uiFocus?.kind === "cauldron")
2053 { clearUiFocus(); }
2054 alchemy?.handleSnapshot(message);
2055 break;
2056 case MessageType.pigeonDispatched:
2057 inventory?.handlePigeonDispatched(message);
2058 break;
2059 case MessageType.pigeonDelivered:
2060 inventory?.handlePigeonDelivered(message);
2061 break;
2062 case MessageType.characterSearchResult:
2063 inventory?.handleCharacterSearch(message);
2064 break;
2065 case MessageType.craftResult:
2066 crafting?.handleCraftResult(message);
2067 break;
2068 case MessageType.worldStatus:
2069 if (view)
2070 {
2071 view.setSettings(message.settings ?? view.settings);
2072 view.worldHour = message.worldTime?.hour ?? view.worldHour;
2073 view.setWorldSeason(message.worldTime?.season);
2074 chat?.syncSettings();
2075 }
2076 skills?.refresh?.();
2077 toasts?.applyRestartStatus?.(message.restartStatus);
2078 break;
2079 case MessageType.restartStatus:
2080 toasts?.applyRestartStatus?.(message.restartStatus);
2081 break;
2082 case MessageType.chatBubble:
2083 chat?.showBubble(message);
2084 break;
2085 case MessageType.friends:
2086 social?.handleFriends(message);
2087 break;
2088 case MessageType.combatSwing:
2089 view?.spawnCombatSwing(message);
2090 break;
2091 case MessageType.combatProjectile:
2092 view?.spawnPhysicalProjectileFx({
2093 ...message,
2094 sprite: "fx:projectile:arrow"
2095 });
2096 break;
2097 case MessageType.combatNoArrows:
2098 toasts?.show("Out of arrows!");
2099 break;
2100 case MessageType.gatherSwing:
2101 case MessageType.tileShove:
2102 view?.spawnGatherSwing(message);
2103 break;
2104 case MessageType.stationOpen:
2105 if (message.stationId)
2106 { crafting?.openStation(message.stationId); }
2107 break;
2108 case MessageType.shopOpen:
2109 if (message.npcEntityId != null)
2110 { setUiFocus({ kind: "shop", entityId: message.npcEntityId | 0 }); }
2111 shop?.handleShopOpen(message);
2112 break;
2113 case MessageType.shopClosed:
2114 if (uiFocus?.kind === "shop")
2115 { clearUiFocus(); }
2116 shop?.handleShopClosed(message);
2117 break;
2118 case MessageType.marketOpen:
2119 market?.handleOpen(message);
2120 break;
2121 case MessageType.marketClosed:
2122 if (uiFocus?.kind === "market")
2123 { clearUiFocus(); }
2124 market?.handleClosed(message);
2125 break;
2126 case MessageType.marketTrade:
2127 market?.handleTrade(message);
2128 toasts?.show(`Trade: ${message.quantity} @ ${message.unitPrice} coins`);
2129 break;
2130 case MessageType.bountySnapshot:
2131 bounty?.handleSnapshot(message);
2132 break;
2133 case MessageType.closeBounty:
2134 if (uiFocus?.kind === "bounty")
2135 { clearUiFocus(); }
2136 bounty?.handleClosed(message);
2137 break;
2138 case MessageType.characterBounty:
2139 bounty?.handleCharacterBounty(message);
2140 social?.handleCharacterBounty(message);
2141 break;
2142 case MessageType.barberSnapshot:
2143 barber?.handleSnapshot(message);
2144 break;
2145 case MessageType.closeBarber:
2146 if (uiFocus?.kind === "barber")
2147 { clearUiFocus(); }
2148 barber?.handleClosed(message);
2149 break;
2150 case MessageType.itemBubble:
2151 chat?.showItemBubble(message);
2152 break;
2153 case MessageType.gatherComplete:
2154 crafting?.refresh();
2155 break;
2156 case MessageType.combatHit:
2157 {
2158 const applyHit = () =>
2159 {
2160 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
2161 view?.flashDamage(message.targetId);
2162 view?.spawnCombatKnockback?.(message);
2163 view?.spawnDamageNumber(message.targetId, message.damage);
2164 if (message.targetId === view?.localEntityId)
2165 {
2166 healthUi?.apply({
2167 current: message.health,
2168 max: message.maxHealth
2169 });
2170 }
2171 };
2172 if (!view?.deferCombatHit?.(message, applyHit))
2173 { applyHit(); }
2174 break;
2175 }
2176 case MessageType.combatMiss:
2177 view?.spawnCombatDodge?.(message);
2178 view?.markProjectileMiss?.(message);
2179 break;
2180 case MessageType.combatBlock:
2181 {
2182 const applyBlock = () =>
2183 {
2184 view?.flashBlock?.(message.targetId);
2185 if (message.health != null)
2186 { view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); }
2187 };
2188 if (!view?.deferCombatHit?.(message, applyBlock))
2189 { applyBlock(); }
2190 break;
2191 }
2192 case MessageType.entityHealth:
2193 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2194 if (message.entityId === view?.localEntityId)
2195 {
2196 healthUi?.apply({
2197 current: message.health,
2198 max: message.maxHealth
2199 });
2200 }
2201 break;
2202 case MessageType.skillLevelUp:
2203 view?.spawnSkillLevelUp(message.entityId, message);
2204 if (message.entityId === view?.localEntityId)
2205 {
2206 const level = message.level | 0;
2207 const previousLevel = message.previousLevel == null
2208 ? Math.max(0, level - 1)
2209 : message.previousLevel | 0;
2210 const unlockCount = skillUnlockMessages(message.skillId, previousLevel, level).length;
2211 toasts?.show(skillLevelUpToastText(message.skillId, level, previousLevel), {
2212 durationMs: 3500 + unlockCount * 1600
2213 });
2214 }
2215 break;
2216 case MessageType.playerDied:
2217 clearAllPendingActions();
2218 clearAutorunFocus();
2219 contextMenu?.hide();
2220 spells?.handleSpellDisarmed?.();
2221 closeCloseablePlayUi();
2222 death?.show();
2223 if (message.entityId === view?.localEntityId)
2224 {
2225 healthUi?.apply({ current: 0, max: healthUi.getMax?.() });
2226 view?.updateEntityHealth(message.entityId, 0, healthUi.getMax?.());
2227 }
2228 break;
2229 case MessageType.playerRespawned:
2230 death?.hide();
2231 // Drop deferred killing-blow health=0 that may still be queued on a projectile.
2232 view?.cancelDeferredCombatHits?.(message.entityId);
2233 view?.updateEntityHealth(message.entityId, message.health, message.maxHealth);
2234 if (message.skullValue != null)
2235 { view?.updateEntitySkull(message.entityId, message.skullValue); }
2236 if (message.entityId === view?.localEntityId)
2237 {
2238 healthUi?.apply({
2239 current: message.health,
2240 max: message.maxHealth
2241 });
2242 }
2243 if (message.stamina != null || message.maxStamina != null)
2244 {
2245 staminaUi?.apply({
2246 current: message.stamina ?? staminaUi.getCurrent?.(),
2247 max: message.maxStamina ?? staminaUi.getMax?.()
2248 });
2249 }
2250 break;
2251 case MessageType.error:
2252 if (playing)
2253 { toasts?.show(message.message); }
2254 else
2255 {
2256 const createPanel = document.getElementById("create-panel");
2257 const createError = document.getElementById("create-error");
2258 if (createPanel && !createPanel.hidden && createError)
2259 { createError.textContent = message.message ?? ""; }
2260 else
2261 { showError(message.message); }
2262 }
2263 social?.showError(message.message);
2264 break;
2265 case MessageType.toast:
2266 if (playing)
2267 { toasts?.show(message.message); }
2268 break;
2269 case MessageType.questsSnapshot:
2270 questsUi?.applySnapshot(message);
2271 break;
2272 case MessageType.questStepComplete:
2273 questsUi?.handleStepComplete(message);
2274 break;
2275 case MessageType.dialogueStep:
2276 if (message.npcEntityId != null)
2277 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2278 dialogueUi?.handleStep(message);
2279 break;
2280 case MessageType.dialogueItemRewards:
2281 if (message.npcEntityId != null)
2282 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2283 dialogueUi?.handleItemRewards(message);
2284 break;
2285 case MessageType.dialogueChoices:
2286 if (message.npcEntityId != null)
2287 { setUiFocus({ kind: "dialogue", entityId: message.npcEntityId | 0 }); }
2288 dialogueUi?.handleChoices(message);
2289 break;
2290 case MessageType.dialogueClose:
2291 if (uiFocus?.kind === "dialogue")
2292 { clearUiFocus(); }
2293 dialogueUi?.handleClose(message);
2294 break;
2295 case MessageType.forceLogout:
2296 returnToMenu(message.reason);
2297 break;
2298 }
2299 }, {
2300 onClose (event)
2301 {
2302 if (playing)
2303 { returnToMenu(event.reason || "Disconnected from server."); }
2304 }
2305 });
2306 await socket.connect();
2307 if (typeof window !== "undefined")
2308 {
2309 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
2310 {
2311 crafting?.openStation(stationId);
2312 };
2313 }
2314}
2315
2316function returnToMenu (reason = "")
2317{
2318 playing = false;
2319 followTargetId = null;
2320 moveDest = null;
2321 clearAutorunFocus();
2322 autorunWaitingStamina = false;
2323 clearAllPendingActions();
2324 clearUiFocus();
2325 social?.reset();
2326 chat?.reset();
2327 inventory?.reset();
2328 crafting?.reset();
2329 alchemy?.reset();
2330 staminaUi?.hide();
2331 healthUi?.hide();
2332 statusEffectsUi?.hide();
2333 skills?.hide();
2334 spells?.hide();
2335 contextMenu?.hide();
2336 death?.reset();
2337 shop?.close({ notifyServer: false });
2338 bounty?.close();
2339 barber?.close();
2340 questsUi?.reset();
2341 dialogueUi?.reset();
2342 hideWorldTooltip();
2343 if (view)
2344 { view.clearPlaySession(); }
2345 overlay.hidden = false;
2346 hud.hidden = true;
2347 const settingsToggle = document.getElementById("settings-toggle");
2348 if (settingsToggle)
2349 { settingsToggle.hidden = true; }
2350 graphicsSettingsUi?.close();
2351 if (reason)
2352 { statusEl.textContent = reason; }
2353}
2354
2355document.getElementById("create-character-open")?.addEventListener("click", () =>
2356{
2357 showError("");
2358 const createError = document.getElementById("create-error");
2359 if (createError)
2360 { createError.textContent = ""; }
2361 document.getElementById("create-backdrop").hidden = false;
2362 document.getElementById("create-panel").hidden = false;
2363 setCreateTab("appearance");
2364 void createHairControls?.refreshPreview();
2365});
2366
2367function closeCreateModal ()
2368{
2369 document.getElementById("create-backdrop").hidden = true;
2370 document.getElementById("create-panel").hidden = true;
2371}
2372
2373document.getElementById("create-close")?.addEventListener("click", closeCreateModal);
2374document.getElementById("create-backdrop")?.addEventListener("click", closeCreateModal);
2375
2376document.getElementById("create-form").addEventListener("submit", (event) =>
2377{
2378 event.preventDefault();
2379 showError("");
2380 const createError = document.getElementById("create-error");
2381 if (createError)
2382 { createError.textContent = ""; }
2383 const names = validateCharacterNames({
2384 firstName: document.getElementById("first-name").value,
2385 lastName: document.getElementById("last-name").value,
2386 isAdmin: !!session?.isAdmin
2387 });
2388 if (!names.ok)
2389 {
2390 if (createError)
2391 { createError.textContent = names.reason; }
2392 else
2393 { showError(names.reason); }
2394 return;
2395 }
2396 socket.send({
2397 type: MessageType.createCharacter,
2398 firstName: names.firstName,
2399 lastName: names.lastName,
2400 sex: document.getElementById("sex").value,
2401 hair: createHairControls?.currentHair?.() ?? null,
2402 clothing: createClothingControls?.currentClothing?.() ?? null
2403 });
2404});
2405
2406function initCreateTabs ()
2407{
2408 const tabs = document.querySelectorAll(".create-tab");
2409 for (const tab of tabs)
2410 {
2411 tab.addEventListener("click", () => setCreateTab(tab.dataset.createTab));
2412 }
2413 setCreateTab("appearance");
2414}
2415
2416function setCreateTab (name)
2417{
2418 createActiveTab = name === "clothing" ? "clothing" : "appearance";
2419 for (const tab of document.querySelectorAll(".create-tab"))
2420 {
2421 const on = tab.dataset.createTab === createActiveTab;
2422 tab.classList.toggle("active", on);
2423 tab.setAttribute("aria-selected", on ? "true" : "false");
2424 }
2425 for (const pane of document.querySelectorAll("[data-create-pane]"))
2426 { pane.hidden = pane.dataset.createPane !== createActiveTab; }
2427 if (createActiveTab === "clothing")
2428 { void refreshCreateClothingPreview(); }
2429 else
2430 { void createHairControls?.refreshPreview(); }
2431}
2432
2433async function refreshCreateClothingPreview ()
2434{
2435 const canvas = document.getElementById("create-clothing-preview");
2436 if (!canvas || !createClothingControls)
2437 { return; }
2438 try
2439 {
2440 await paintCharacterPreview(canvas, {
2441 sex: document.getElementById("sex")?.value ?? "male",
2442 bag: createClothingControls.previewBag(),
2443 hair: createHairControls?.currentHair?.() ?? null,
2444 hideHeadgear: true,
2445 resolveSpriteUrl (name)
2446 {
2447 return catalog?.images?.find((entry) => entry.name === name)?.url ?? null;
2448 },
2449 scale: 4
2450 });
2451 }
2452 catch (error)
2453 { console.warn(error); }
2454}
2455
2456document.getElementById("leave").addEventListener("click", () =>
2457{
2458 socket.send({ type: MessageType.leaveWorld });
2459 returnToMenu();
2460});
2461
2462main().catch((error) =>
2463{
2464 showError(error.message);
2465 console.error(error);
2466});
2467
2468function isBankTile (view, tileX, tileY)
2469{
2470 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
2471}
2472
2473function isDoorwayTile (view, tileX, tileY)
2474{
2475 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
2476}
2477
2478function isMarketplaceTile (view, tileX, tileY)
2479{
2480 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
2481}
2482
2483function isBountyOfficeTile (view, tileX, tileY)
2484{
2485 return blockTypeAt(view, tileX, tileY) === BlockType.bountyOffice;
2486}
2487
2488function isBarberTile (view, tileX, tileY)
2489{
2490 return blockTypeAt(view, tileX, tileY) === BlockType.barber;
2491}
2492
2493function isCauldronTile (view, tileX, tileY)
2494{
2495 return blockTypeAt(view, tileX, tileY) === BlockType.cauldron;
2496}
2497
2498function isFurnaceTile (view, tileX, tileY)
2499{
2500 return blockTypeAt(view, tileX, tileY) === BlockType.furnace;
2501}
2502
2503function isOvenTile (view, tileX, tileY)
2504{
2505 return blockTypeAt(view, tileX, tileY) === BlockType.oven;
2506}
2507
2508function isCampfireTile (view, tileX, tileY)
2509{
2510 return blockTypeAt(view, tileX, tileY) === BlockType.campfire;
2511}
2512
2513function isFishingSpotTile (view, tileX, tileY)
2514{
2515 const block = blockAt(view, tileX, tileY);
2516 if (!block || block.typeId !== BlockType.fishingSpot)
2517 { return false; }
2518 return block.state !== "exhausted";
2519}
2520
2521function isAnvilTile (view, tileX, tileY)
2522{
2523 return blockTypeAt(view, tileX, tileY) === BlockType.anvil;
2524}
2525
2526function isJeweleringStationTile (view, tileX, tileY)
2527{
2528 return blockTypeAt(view, tileX, tileY) === BlockType.jeweleringStation;
2529}
2530
2531function isGroundWoodLog (ground)
2532{
2533 const def = itemDefinition(ground?.itemId ?? ground?.stack?.itemId);
2534 return def?.familyId === ItemFamilyId.log;
2535}
2536
2537function playerHasUsableTinderbox ()
2538{
2539 const slots = inventory?.getInventorySlots?.() ?? [];
2540 for (const slot of slots)
2541 {
2542 if (!slot || slot.itemId !== CraftingItemId.tinderbox)
2543 { continue; }
2544 const charges = slot.instance?.kind === "tinderbox"
2545 ? (slot.instance.charges | 0)
2546 : TINDERBOX_MAX_CHARGES;
2547 if (charges > 0)
2548 { return true; }
2549 }
2550 return false;
2551}
2552
2553function isWoodworkingBenchTile (view, tileX, tileY)
2554{
2555 return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench;
2556}
2557
2558function isCraftingBenchTile (view, tileX, tileY)
2559{
2560 return blockTypeAt(view, tileX, tileY) === BlockType.craftingBench;
2561}
2562
2563function isSpinningWheelTile (view, tileX, tileY)
2564{
2565 return blockTypeAt(view, tileX, tileY) === BlockType.spinningWheel;
2566}
2567
2568function isLoomTile (view, tileX, tileY)
2569{
2570 return blockTypeAt(view, tileX, tileY) === BlockType.loom;
2571}
2572
2573function isTailorBenchTile (view, tileX, tileY)
2574{
2575 return blockTypeAt(view, tileX, tileY) === BlockType.tailorBench;
2576}
2577
2578function isLeatherworkingTableTile (view, tileX, tileY)
2579{
2580 return blockTypeAt(view, tileX, tileY) === BlockType.leatherworkingTable;
2581}
2582
2583function isOreBoulderTile (view, tileX, tileY)
2584{
2585 const block = blockAt(view, tileX, tileY);
2586 return block?.typeId === BlockType.boulder && isOreBoulderState(block.state);
2587}
2588
2589function isChopableTreeTile (view, tileX, tileY)
2590{
2591 return isChopableTreeBlock(blockAt(view, tileX, tileY));
2592}
2593
2594function isPickablePlantTile (view, tileX, tileY)
2595{
2596 return isPickablePlantBlock(blockAt(view, tileX, tileY));
2597}
2598
2599const SPELL_ENTITY_SNAP_TILES = 2;
2600
2601function updateSpellTargetHighlight ()
2602{
2603 if (!view || !playing || uiBlocked() || !spells?.isTargeting?.())
2604 {
2605 view?.clearSpellTargetHighlight();
2606 return;
2607 }
2608 const canvas = scene?.canvas;
2609 if (!canvas)
2610 { return; }
2611 const rect = canvas.getBoundingClientRect();
2612 const mouseX = GameInput.mousePosition.x - rect.left;
2613 const mouseY = GameInput.mousePosition.y - rect.top;
2614 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2615 {
2616 view.clearSpellTargetHighlight();
2617 return;
2618 }
2619 const armed = spells.getArmedSpell?.();
2620 const local = view.entities.get(view.localEntityId);
2621 if (armed?.target === "entity")
2622 {
2623 const target = nearestSpellEntityAtCursor(mouseX, mouseY);
2624 if (!target)
2625 {
2626 view.clearSpellTargetHighlight();
2627 return;
2628 }
2629 const inRange = !local
2630 || chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) <= COMBAT_RANGE_TILES;
2631 view.setSpellEntityTargetHighlight(target.entityId, inRange);
2632 return;
2633 }
2634 const tile = view.screenToTile(mouseX, mouseY);
2635 const inRange = !local
2636 || chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= COMBAT_RANGE_TILES;
2637 view.setSpellTargetHighlight(tile.tileX, tile.tileY, inRange);
2638}
2639
2640/**
2641 * Nearest spell-targetable entity within {@link SPELL_ENTITY_SNAP_TILES} of the
2642 * cursor tile (uses both authoritative and visual tile for moving mobs).
2643 */
2644function nearestSpellEntityAtCursor (mouseX, mouseY)
2645{
2646 if (!view)
2647 { return null; }
2648 const cursor = view.screenToTile(mouseX, mouseY);
2649 const tileSize = view.tileSize();
2650 let best = null;
2651 let bestDist = Infinity;
2652 let bestScreen = Infinity;
2653 for (const entity of view.entities.values())
2654 {
2655 if (!isSpellEntityTarget(entity))
2656 { continue; }
2657 const visualTileX = Math.floor((entity.visualX + (entity.stackOffsetX ?? 0)) / tileSize);
2658 const visualTileY = Math.floor((entity.visualY + (entity.stackOffsetY ?? 0)) / tileSize);
2659 const dist = Math.min(
2660 chebyshev(cursor.tileX, cursor.tileY, entity.tileX, entity.tileY),
2661 chebyshev(cursor.tileX, cursor.tileY, visualTileX, visualTileY)
2662 );
2663 if (dist > SPELL_ENTITY_SNAP_TILES)
2664 { continue; }
2665 const box = view.nametagAnchor?.(entity);
2666 const screenDist = box
2667 ? Math.hypot(box.x - mouseX, box.y - mouseY)
2668 : dist;
2669 if (dist < bestDist || (dist === bestDist && screenDist < bestScreen))
2670 {
2671 best = entity;
2672 bestDist = dist;
2673 bestScreen = screenDist;
2674 }
2675 }
2676 return best;
2677}
2678
2679function isSpellEntityTarget (entity)
2680{
2681 if (!entity || entity.entityId === view?.localEntityId)
2682 { return false; }
2683 if (entity.untargetable || entity.freeFlight)
2684 { return false; }
2685 return isAttackableEntity(entity);
2686}
2687
2688function hideWorldTooltip ()
2689{
2690 if (worldTooltip)
2691 {
2692 worldTooltip.hidden = true;
2693 worldTooltip.classList.remove("friend-name");
2694 worldTooltip.style.color = "";
2695 }
2696}
2697
2698/** Cursor tip for gatherable resource nodes (ores now; trees / fish / herbs later). */
2699function updateWorldTooltip ()
2700{
2701 if (!worldTooltip || !view || !scene || uiBlocked())
2702 {
2703 hideWorldTooltip();
2704 return;
2705 }
2706 const canvas = scene.canvas;
2707 const rect = canvas.getBoundingClientRect();
2708 const mouseX = GameInput.mousePosition.x - rect.left;
2709 const mouseY = GameInput.mousePosition.y - rect.top;
2710 if (mouseX < 0 || mouseY < 0 || mouseX >= rect.width || mouseY >= rect.height)
2711 {
2712 hideWorldTooltip();
2713 return;
2714 }
2715 const entity = view.entityAtScreen(mouseX, mouseY);
2716 if (entity && entity.entityId !== view.localEntityId)
2717 {
2718 const label = entityLabel(entity);
2719 worldTooltip.hidden = false;
2720 worldTooltip.textContent = label;
2721 const friend = entity.characterId && social?.isFriendCharacter?.(entity.characterId, entity.accountId);
2722 worldTooltip.classList.toggle("friend-name", !!friend);
2723 worldTooltip.style.color = friend ? "#e8c84a" : "";
2724 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2725 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2726 return;
2727 }
2728 const tile = view.screenToTile(mouseX, mouseY);
2729 const label = resourceNodeDisplayName(blockAt(view, tile.tileX, tile.tileY));
2730 if (!label)
2731 {
2732 hideWorldTooltip();
2733 return;
2734 }
2735 worldTooltip.hidden = false;
2736 worldTooltip.textContent = label;
2737 worldTooltip.style.left = `${GameInput.mousePosition.x + 14}px`;
2738 worldTooltip.style.top = `${GameInput.mousePosition.y + 16}px`;
2739}
2740
2741function blockTypeAt (view, tileX, tileY)
2742{
2743 return blockAt(view, tileX, tileY)?.typeId ?? null;
2744}
2745
2746function blockAt (view, tileX, tileY)
2747{
2748 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2749 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2750 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2751 if (!snapshot)
2752 { return null; }
2753 const localX = tileX - chunkX * CHUNK_SIZE;
2754 const localY = tileY - chunkY * CHUNK_SIZE;
2755 return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null;
2756}
2757
2758function groundTypeAt (view, tileX, tileY)
2759{
2760 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2761 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2762 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
2763 if (!snapshot)
2764 { return null; }
2765 const localX = tileX - chunkX * CHUNK_SIZE;
2766 const localY = tileY - chunkY * CHUNK_SIZE;
2767 return normalizeGround(snapshot.grounds?.[localY * CHUNK_SIZE + localX]).typeId;
2768}
2769
2770/** Best-effort client filter for approach destinations (server still authorizes paths). */
2771function isClientApproachable (tileX, tileY)
2772{
2773 if (!view)
2774 { return true; }
2775 const groundId = groundTypeAt(view, tileX, tileY);
2776 const groundDef = groundId != null ? GROUND_DEFINITIONS[groundId] : null;
2777 if (groundDef && !groundDef.passable)
2778 { return false; }
2779 const block = blockAt(view, tileX, tileY);
2780 if (block?.typeId != null)
2781 {
2782 const blockDef = BLOCK_DEFINITIONS[block.typeId];
2783 if (blockDef && !blockDef.passable)
2784 { return false; }
2785 }
2786 for (const entity of view.entitiesAtTile(tileX, tileY))
2787 {
2788 if (entity.entityId === view.localEntityId)
2789 { continue; }
2790 if (entity.untargetable || entity.freeFlight)
2791 { continue; }
2792 return false;
2793 }
2794 return true;
2795}
2796
2797function chebyshev (ax, ay, bx, by)
2798{
2799 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
2800}
2801
2802function updateAuthUi (authStatus)
2803{
2804 const signIn = document.getElementById("auth-sign-in");
2805 const signOut = document.getElementById("auth-sign-out");
2806 const exportLink = document.getElementById("auth-export");
2807 if (signIn)
2808 {
2809 signIn.hidden = !!authStatus?.authenticated;
2810 signIn.href = loginUrl("/");
2811 }
2812 if (signOut)
2813 {
2814 signOut.hidden = !authStatus?.authenticated;
2815 signOut.href = logoutUrl("/");
2816 }
2817 if (exportLink)
2818 { exportLink.hidden = !authStatus?.authenticated; }
2819 if (createCharacterOpen)
2820 { createCharacterOpen.hidden = !authStatus?.authenticated; }
2821 if (authStatus?.authenticated && !session)
2822 {
2823 statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
2824 }
2825}