Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
5843 lines (5348 loc) · 235 KB
/
Copy pathmain.js
File metadata and controls
5843 lines (5348 loc) · 235 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Battlemap Screen and GM Streaming Tool
* Coordinate model:
* - "native" coords are image pixels (0..imageWidth, 0..imageHeight). Fog, rooms,
* tokens, pings and measures are all stored in native coords so they stay glued to
* the map regardless of zoom or the "Map image size" (map.scale) slider.
* - The render transform maps native -> world (x map.scale) -> screen (x view.scale,
* centered on view.cx/cy). Because the view is expressed as a centered map point +
* zoom, the GM and player windows frame the same thing even at different canvas sizes.
*/
import {
canvas, ctx, fogCanvas, fogCtx, liveCanvas, liveCtx, polyCanvas, polyCtx,
strokeCanvas, strokeCtx, losCanvas, losCtx, darkCanvas, darkCtx, lightCanvas, lightCtx,
exploredMasks, lightCache, shell, emptyState, channel, APP_NAME, LEGACY_APP_NAME, SAVE_FILE_VERSION,
DB_NAME, DB_VERSION, MAP_STORE, IMAGE_STORE, MODULE_STORE, SESSION_STORE, TOKEN_STORE, FOG_MAX_EDGE,
HISTORY_LIMIT, STAIRS_ICON_NEUTRAL, STAIRS_ICON_UP, STAIRS_ICON_DOWN, FEET_PER_CELL, MEASURE_UNITS, PING_DURATION, PLAYER_FRAME_REF, controls,
CONDITIONS,
MAP_LINK_ICONS, MAP_LINK_DEFAULT_ICON, MAP_KIND_CAPS,
isPlayer, isSandbox, DEFAULT_GM_FOG_OPACITY, INITIAL_FLOOR_ID, makeFloor, state, normalizeInput, uuid, escapeHtml,
playerCam, tools, cur, hooks, sel, fogBuf, peerWindow,
castCache, castFrameKeys, lightFrameKeys,
ui,
scene,
} from "./state.js";
import {
saveMapRecord, listMapRecords, deleteMapRecord, saveModuleRecord, listModuleRecords, getModuleRecord, deleteModuleRecord, saveSessionRecord,
listSessionRecords, getSessionRecord, deleteSessionRecord, saveTokenRecord, listTokenRecords, deleteTokenRecord, putImage,
getImage,
} from "./db.js";
import { readZip, parseDtt, importDtt } from "./dtt.js";
import { parseUvtt, importUvtt } from "./parse-uvtt.js";
import {
simplifyPolyline, distToSegment, pointInPolygon, gridCellNative, pxPerCellNative, cellsToNative, tokenRadius, snapToGrid,
snapNative, worldDims, activeView, fitScaleFor, viewTransform, clientToCanvasPoint, currentViewRotation, keepUpright,
screenToNative, nativeToScreen, followView, cellWorldPx,
} from "./geometry.js";
import {
drawAoeTemplate, drawMeasureLine, drawMeasureLabel, drawCalibrationDraft, updateCalibrationUI, updateMeasureCalibrateRow, hitAoe,
} from "./aoe-measure.js";
import {
drawNotes, hitNote, drawImages, hitImage, snapImage, getTokenImage, addPing, drawPings,
} from "./annotations.js";
import {
sortedCombatants, activeTurnTokenId, clampInitiativeTurn, updateInitiativeUI,
} from "./initiative.js";
import {
rebuildFog, compositeFog, roomPathFog, polygonCentroid, drawStampDraft, drawPolygon, stampPolygon, addInterpolatedStrokePoints,
} from "./fog.js";
import {
invalidateCast, rayHit, getVisibilityPolygon, hitLight, drawLights, compositeLoS, castVersion,
} from "./vision.js";
import {
tokenIsSquare, drawTokens,
} from "./tokens.js";
import {
drawRoomOutlines, drawObstacleOutlines, drawDraftObstacle, drawRoomNames, drawDraftRoom, obstacleDefaults, hitObstacle, moveSegments,
} from "./rooms-obstacles.js";
import {
ensureCameraLoop, stopCameraLoop, rotateMap,
} from "./view.js";
import {
hydrateFloorImages, mergeModuleSession, migrateMapsToModulesAndSessions, captureCurrentFloor, splitState, makeMapId, deriveCellGrid,
snapshotFromLiveState,
} from "./persistence.js";
import {
resolveSession, resolveModule, resolveImage,
trailActiveId, trailDepth, trailPush, trailPop, trailReset,
cacheHas, cacheGet, cacheSet,
} from "./content.js";
import {
relay, applyRemoteView, applyIncomingPlayerView, syncPlayerViewControls, snapPlayerViewToGM, broadcastAssets, broadcastState,
broadcastView, renderAndSync, renderAndSyncView, connectRelay, refitFramedView,
} from "./sync.js";
import {
render, playerFrameCorners,
} from "./render.js";
import {
apiFetch, isLoggedIn, getUsername, isAdmin, listRemoteModules, publishModule, putRemoteImage, publishSession, remoteModuleExists, fetchRemoteSession, deleteRemoteModule, refreshWhoami, adoptStoredGuest,
} from "./api.js";
import {
hitTokenStepArrow, arrowAnchorToken,
} from "./token-arrows.js";
import {
initNotesPanel, refreshNotesPanel,
} from "./notes-panel.js";
import {
initLibraryBackup, chooseBackupFolder, markLibraryDirty, onBackupStatus, buildLibraryPayload,
} from "./backup.js";
async function saveSession() {
captureCurrentFloor();
if (!state.floors.some((floor) => floor.imageData)) {
window.alert("Load a map image before saving.");
return;
}
const suggestedName = state.imageName ? state.imageName.replace(/\.[^.]+$/, "") : "battlemap";
const enteredName = window.prompt("Save map as:", suggestedName);
const mapName = enteredName?.trim();
if (!mapName) return;
// Make sure every floor that has an image carries a stable id (on the live state, so future
// saves reuse it and the image store stays deduped), then mirror the current one up.
state.floors.forEach((floor) => {
if (floor.imageData && !floor.imageId) floor.imageId = uuid();
});
const currentFloor = state.floors.find((f) => f.id === state.currentFloorId);
if (currentFloor && currentFloor.imageId) state.imageId = currentFloor.imageId;
try {
// De-embed: each floor's image into the image store (step 1), keyed by imageId.
for (const floor of state.floors) {
if (floor.imageData && floor.imageId) await putImage(floor.imageId, floor.imageData);
}
// Split the live state into an authored module + a session that references it. 1:1 for now:
// module and session share the name-derived id, which preserves overwrite-by-name, while the
// two-store + moduleId reference is already 1:many-ready.
const id = makeMapId(mapName);
const now = new Date().toISOString();
const { module, session } = splitState(state);
Object.assign(module, { id, app: APP_NAME, version: SAVE_FILE_VERSION, kind: "module", name: mapName, savedAt: now });
Object.assign(session, { id, moduleId: id, app: APP_NAME, version: SAVE_FILE_VERSION, kind: "session", name: mapName, savedAt: now });
await saveModuleRecord(module);
await saveSessionRecord(session);
markLibraryDirty(); // the next backup tick has something new to write
bindLibraryRecord(id); // the board now belongs to this record — autosave can safely aim at it
window.alert(`Saved "${mapName}" to the local map library.`);
refreshLibraryButtonState();
} catch (error) {
window.alert(`Could not save this map: ${error.message}`);
}
}
async function deleteLibraryMap(id, name) {
if (!window.confirm(`Delete "${name}" from the local map library?`)) return;
const session = await getSessionRecord(id);
await deleteSessionRecord(id);
// 1:1 — drop the referenced module too. (Its image blob is left in the image store; orphan
// cleanup is a separate backlog chunk so a shared image is never nuked out from under another
// map.)
await deleteModuleRecord(session?.moduleId || id);
const sessions = await listSessionRecords();
await renderLibraryGrid(sessions);
refreshLibraryButtonState(sessions);
}
function importLibrary(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = async () => {
try {
const parsed = JSON.parse(reader.result);
const images = Array.isArray(parsed?.images) ? parsed.images : [];
const modules = Array.isArray(parsed?.modules) ? parsed.modules : [];
const sessions = Array.isArray(parsed?.sessions) ? parsed.sessions : [];
// Legacy exports are a bare array, {maps:[...]}, or {maps, images} — single records.
const legacyMaps = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.maps) ? parsed.maps : []);
if (!modules.length && !sessions.length && !legacyMaps.length) {
throw new Error("no maps found in that file");
}
// Restore images first so module records can reference them.
for (const image of images) {
if (image?.id && image?.data) await putImage(image.id, image.data);
}
let imported = 0;
for (const module of modules) {
if (module?.id) await saveModuleRecord(module);
}
for (const session of sessions) {
if (session?.id) {
await saveSessionRecord(session);
imported += 1;
}
}
// Legacy single-record maps: store them, then split into module + session pairs.
for (const record of legacyMaps) {
if (!record?.id || !record?.state) continue;
await saveMapRecord(record);
}
if (legacyMaps.length) {
await migrateMapsToModulesAndSessions();
imported += legacyMaps.length;
}
markLibraryDirty(); // an import changes the library as much as a save does
window.alert(`Imported ${imported} map${imported === 1 ? "" : "s"}.`);
const updated = await listSessionRecords();
await renderLibraryGrid(updated);
refreshLibraryButtonState(updated);
} catch (error) {
window.alert(`Could not import that file: ${error.message}`);
} finally {
event.target.value = "";
}
};
reader.readAsText(file);
}
// Wire the orchestration hooks now that the render/sync/relay functions exist (all hoisted).
hooks.render = render;
hooks.renderAndSync = renderAndSync;
hooks.relay = relay;
hooks.pushHistory = pushHistory; // notes drawer: undo snapshot before a note edit
hooks.syncPanels = updateSelectionPanels; // notes drawer: keep the View-section note panel in sync
// Area of effect is a live "hover template" (not placed): the shape follows the cursor
// and is mirrored to the player display in real time.
let aoeSyncQueued = false;
const AOE_PRESETS = { circle: [5, 10, 15, 20], square: [10, 20, 30], cone: [15, 30] };
let tokenImageData = ""; // image applied to newly placed tokens (data URL), authoring default
// --- Token palette: a browsable library of reusable token templates (TOKEN_STORE) ---
let paletteEntries = []; // in-memory mirror of the persisted palette
let activePaletteId = null; // entry whose template is currently loaded into the token controls
let paletteThumbPx = 64; // browse size for palette thumbnails, persisted to localStorage
const PALETTE_THUMB_KEY = "vwag-table-palette-thumb";
let mapThumbPx = 220; // browse size for My-maps picker thumbnails, persisted to localStorage
const MAP_THUMB_KEY = "vwag-table-map-thumb";
const IMAGE_MAX_EDGE = 1024; // cap dropped map images so saves/syncs stay bounded
let isDragging = false;
let dragStart = { x: 0, y: 0 };
let viewStart = { cx: 0, cy: 0 };
let draggingToken = null;
let draggingImage = null;
let draggingNote = null;
let draggingStair = null;
let draggingMapLink = null;
let mapLinkIconChoice = MAP_LINK_DEFAULT_ICON; // current pick in the place-map-link dialog
let draggingFrame = false; // GM is dragging the player-view frame to pan the player display
let dragGrab = { dx: 0, dy: 0 }; // offset from cursor to object center while dragging images/notes/frame
let groupDragOffsets = null; // [{token,dx,dy}] formation captured at grab, for a player group-drag
let dragGrabbed = false; // a token-grab has been relayed for the current player pointer-drag
let lastTokenTap = { token: null, time: 0 }; // tracks the previous player token tap for double-tap traverse
const DOUBLE_TAP_MS = 350; // second tap on the same token within this window = traverse gesture
let dragMeasureStart = null; // the dragged token's pre-drag position; anchors the live drag-distance line
// Multitouch player-token drag. The IR touch frame reports true simultaneous contacts only on the
// Touch Events API (Pointer Events collapse it to one contact on this Chromium/X11 stack), so on the
// player display token movement is driven entirely by the touch* handlers below, not the pointer path.
// Each physical mini rides its own stable touch.identifier; this map holds one drag entry per finger.
// Mouse and pen keep the single-pointer path above (marquee, shift-select, formation group-drag).
const touchDrags = new Map(); // touch.identifier -> { token, grabbed, lastNative:{x,y}, lastMoveAt }
let touchMoveRaf = 0; // coalesces active touch-drag streaming to one relay batch per frame
let touchSettleTimer = 0; // idle sweep; runs only while at least one finger is actively dragging
// A physical mini rests on the glass the whole time it is in play, so a held contact is NOT a drag —
// only MOVEMENT is. A mini that stops moving settles: it commits + snaps and goes silent while still
// resting, and re-drags if pushed again. Without this, every resting mini would stream forever and peg
// the CPU. TOUCH_SETTLE_MS = stillness before a moving mini settles; TOUCH_JITTER_CELLS = sub-cell base
// wobble that must not count as movement (fraction of a cell). Both are feel-tunable.
const TOUCH_SETTLE_MS = 180;
const TOUCH_JITTER_CELLS = 0.15;
const undoStack = [];
const redoStack = [];
let seenMids = []; // recently handled message ids, for de-duplicating the two transports
// IRL play: keep one grid square a constant physical size on the player screen (TV). The
// target is screen px per square; the player zoom is re-derived per map from its grid size.
let lockPlayerSquare = false;
let lockedSquarePx = 0;
const SQUARE_LOCK_KEY = "lodestar.squareLock";
function handleMessage(message, source) {
if (!message || typeof message !== "object") return;
if (message.mid) {
if (seenMids.includes(message.mid)) return;
seenMids.push(message.mid);
if (seenMids.length > 60) seenMids.shift();
}
if (message.type === "assets" && isPlayer) applyAssets(message);
if (message.type === "sync" && isPlayer) loadSnapshot(message.state);
if (message.type === "view" && isPlayer) applyRemoteView(message);
if (message.type === "ping") addPing(message.x, message.y, message.color);
if (message.type === "measure" && isPlayer) {
tools.measureLine = message.line;
render();
}
if (message.type === "reset-explored" && isPlayer) {
resetExplored();
render();
}
if (message.type === "player-ready" && !isPlayer) {
if (source) peerWindow.ref = source;
broadcastAssets();
broadcastState();
}
if (message.type === "request-assets" && !isPlayer) broadcastAssets();
if (message.type === "token-grab" && !isPlayer) {
// Snapshot once at the start of a remote drag so the whole move is one undo step — but only when
// the table follows the GM's view. A drag on a floor the GM isn't viewing (table pinned
// elsewhere) shouldn't land on the GM's local undo stack.
if (state.activeFloorId === state.currentFloorId) pushHistory();
}
if (message.type === "token-move" && !isPlayer) {
// Live position during a drag: update and render locally, but do NOT broadcast — a full state
// sync mid-drag would replace the player's tokens and orphan its drag.
if (state.activeFloorId !== state.currentFloorId) {
// Table pinned to another floor: update the token in the active floor's record. No GM render
// (the GM isn't viewing it) and no broadcast (the player previews its own drag locally).
const active = state.floors.find((f) => f.id === state.activeFloorId);
const token = active && (active.tokens || []).find((t) => t.id === message.id);
if (token) { token.x = message.x; token.y = message.y; }
} else {
const token = state.tokens.find((t) => t.id === message.id);
if (token) {
token.x = message.x;
token.y = message.y;
render();
}
}
}
if (message.type === "token-drop" && !isPlayer) {
// Commit a player move: pick the target cell (nudged to the nearest free one so no two tokens
// share a cell), clamp the move to it so it can't cross a wall, then broadcast to all displays.
// The GM's own drags don't come through here, so the GM stays free to place anything anywhere.
const active = state.activeFloorId !== state.currentFloorId
? state.floors.find((f) => f.id === state.activeFloorId)
: null;
const tokens = active ? (active.tokens || []) : state.tokens;
const token = tokens.find((t) => t.id === message.id);
if (token) {
const commit = () => {
const snapped = snapNative({ x: message.x, y: message.y });
const free = nearestFreeCell(snapped, token);
const dest = resolveMove({ x: message.x, y: message.y }, free);
token.x = dest.x;
token.y = dest.y;
};
if (active) {
// Table pinned elsewhere: resolve collision and walls against the active floor, then
// broadcast (sanitizedState sources the active floor). The GM's canvas is untouched.
withActiveFloor(active, commit);
broadcastState();
} else {
commit();
renderAndSync();
}
}
}
if (message.type === "map-link-descend" && !isPlayer) {
// A player walked their token onto a map-link and pressed 'd'. The GM owns the map stack,
// so descend here — loads the child map, sets the table, and broadcasts it back so every
// screen travels together (the diegetic "party walks through the door" move).
if (message.targetMapId) descend(message.targetMapId);
}
if (message.type === "stair-traverse" && !isPlayer) {
// A player took a stair with a selection of tokens. They all live on the ACTIVE (table) floor —
// live state when the GM is viewing that floor, a stored record otherwise. What happens next keys
// off whether the table is DECOUPLED from the GM's view (pinned OR following initiative), not on
// whether the two floor pointers happen to coincide. Decoupled: only the token data and the table
// move while the GM's view stays put (the party walks floors independently of the GM) — pinned
// walks the table to the target, following points it at the active combatant's floor. Coupled
// (neither pinned nor following): the GM and party descend together (goToFloor, whose broadcast
// re-binds the players' selection by id). Branching on active!=current would strand the table for
// one traverse whenever the GM happened to be co-located on the table's floor.
const ids = Array.isArray(message.ids) ? message.ids : (message.id != null ? [message.id] : []);
const targetIdx = state.floors.findIndex((f) => f.id === message.targetFloorId);
const activeIsLive = state.activeFloorId === state.currentFloorId;
const sourceFloor = state.floors.find((f) => f.id === state.activeFloorId);
const sourceTokens = activeIsLive ? state.tokens : ((sourceFloor && sourceFloor.tokens) || []);
// The riders are every selected token that still lives on the source floor.
const riders = ids.map((id) => sourceTokens.find((t) => t.id === id)).filter(Boolean);
if (riders.length && sourceFloor && targetIdx !== -1) {
const targetFloor = state.floors[targetIdx];
const targetIsLive = targetFloor.id === state.currentFloorId; // the GM is viewing the target floor
const paired = (targetFloor.stairs || []).find((s) => s.targetFloorId === sourceFloor.id);
// Fan the group out around the paired stair (or each token's own cell if there is none), seeding
// occupancy with the target floor's existing tokens — live state when the GM is viewing it, the
// stored record otherwise — so nobody lands on an occupant or on another arriving teammate.
const occupied = [...(targetIsLive ? state.tokens : (targetFloor.tokens || []))];
const travelers = riders.map((token) => {
const traveler = JSON.parse(JSON.stringify(token));
const base = paired ? { x: paired.x, y: paired.y } : { x: traveler.x, y: traveler.y };
const landing = freeCellOnFloor(snapNative(base), occupied);
traveler.x = landing.x;
traveler.y = landing.y;
occupied.push(traveler); // the next rider nudges away from this one
return traveler;
});
const riderIds = new Set(riders.map((t) => t.id));
if (!ui.pinTable && !ui.followInitiative) {
// Coupled (neither pinned nor following): the GM and the party descend together (the
// long-standing behavior). goToFloor captures this floor (minus the riders), applies the
// target (with the travelers), and syncs the table to the GM's new floor.
targetFloor.tokens = [...(targetFloor.tokens || []), ...travelers]; // onto the next floor
state.tokens = state.tokens.filter((t) => !riderIds.has(t.id)); // off this floor
goToFloor(targetIdx);
} else {
// Decoupled (pinned or following): the GM's view stays put; only the token data and the
// table move. Pull the riders off the source floor and drop the travelers onto the target —
// live state when the GM is viewing that floor, the stored record otherwise.
if (activeIsLive) state.tokens = state.tokens.filter((t) => !riderIds.has(t.id)); // off the live floor
else sourceFloor.tokens = (sourceFloor.tokens || []).filter((t) => !riderIds.has(t.id)); // off the record
if (targetIsLive) state.tokens = [...state.tokens, ...travelers]; // target is the GM's live floor
else targetFloor.tokens = [...(targetFloor.tokens || []), ...travelers]; // target is a record
if (ui.followInitiative) {
// Following: the table tracks the active combatant — it lands on the target floor if the
// active combatant was among the travelers, and stays put otherwise (asset broadcast is
// handled inside the helper when the table floor actually changes).
if (!followTableToActiveTurn()) refreshFloorUI();
} else {
// Pinned: the table walks with the party to the target floor.
state.activeFloorId = targetFloor.id;
refreshFloorUI();
broadcastAssets();
}
render(); // the GM may have just watched the group leave or arrive on their own floor
broadcastState();
}
}
}
}
function setupStartScreen() {
const screen = document.getElementById("startScreen");
if (!screen) return;
// The player display never shows the opening menu.
if (isPlayer) {
screen.remove();
return;
}
const dismiss = () => {
screen.classList.add("hidden");
setTimeout(() => screen.remove(), 500);
window.removeEventListener("keydown", onStartKey);
};
const onStartKey = (event) => {
if (event.key === "Enter" || event.key === "Escape" || event.key === " ") {
event.preventDefault();
dismiss();
}
};
document.getElementById("startEnter")?.addEventListener("click", dismiss);
window.addEventListener("keydown", onStartKey);
}
// Make each GM panel section collapsible: a caret in the title toggles a slide-down
// body. The top action buttons (no heading) stay always visible.
function setupCollapsibleSections() {
document.querySelectorAll(".gm-panel .control-section").forEach((section) => {
const title = section.querySelector(":scope > .section-title");
const heading = title?.querySelector("h2");
if (!title || !heading) return;
// Wrap everything after the title in an animatable body (grid-rows 1fr -> 0fr).
const body = document.createElement("div");
body.className = "section-body";
const inner = document.createElement("div");
inner.className = "section-body-inner";
while (title.nextSibling) inner.appendChild(title.nextSibling);
body.appendChild(inner);
section.appendChild(body);
// Caret toggle at the start of the title.
const arrow = document.createElement("button");
arrow.type = "button";
arrow.className = "section-toggle";
arrow.setAttribute("aria-label", "Collapse or expand section");
arrow.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>';
title.insertBefore(arrow, title.firstChild);
section.classList.add("collapsed"); // start collapsed by default; click a title to open
const toggle = () => section.classList.toggle("collapsed");
arrow.addEventListener("click", toggle);
heading.style.cursor = "pointer";
heading.addEventListener("click", toggle);
});
}
// The player screen hides the cursor for a clean display, but that also hides the
// fullscreen button. Reveal both whenever the mouse moves, then fade out after a pause.
function setupPlayerCursor() {
let timer = 0;
const hide = () => shell.classList.remove("cursor-active");
window.addEventListener("mousemove", () => {
shell.classList.add("cursor-active");
clearTimeout(timer);
timer = setTimeout(hide, 2500);
});
}
function setup() {
shell.dataset.role = isPlayer ? "player" : "gm";
setupStartScreen();
if (isPlayer) {
document.title = "Player Battlemap";
adoptStoredGuest(); // seat the guest identity if redirected in from the join gate (no-op otherwise)
relay({ type: "player-ready" });
} else {
requestPersistentStorage(); // the library is irreplaceable; ask the browser not to evict it
setupBackupStatus(); // ...and persistence can still be denied, so keep a copy off-origin
initLibraryBackup();
bindControls();
loadSquareLock();
loadPaletteThumb();
if (controls.paletteSize) controls.paletteSize.value = paletteThumbPx;
loadMapThumb();
if (controls.mapSize) controls.mapSize.value = mapThumbPx;
if (controls.fallonMapSize) controls.fallonMapSize.value = mapThumbPx;
loadPalette();
syncControlsFromState();
updateSquareLockUI();
// One-time, idempotent: split any legacy single-record maps into module + session pairs,
// then give any pre-v6 modules a cell-space declaration.
migrateMapsToModulesAndSessions()
.then(() => backfillModuleCellGrids())
.finally(() => refreshLibraryButtonState());
updateUndoButtons();
setupCollapsibleSections();
updateInitiativeUI();
}
// Two transports so the link works whether or not BroadcastChannel delivers between
// windows (it is unreliable on file://): the BroadcastChannel and a direct
// window.postMessage to the opener / popup. Messages carry a "mid" so the receiver
// ignores the duplicate when both transports succeed.
channel.onmessage = (event) => handleMessage(event.data, null);
window.addEventListener("message", (event) => handleMessage(event.data, event.source));
connectRelay(handleMessage); // third transport: WebSocket to fallon (online tier)
watchCanvasSize();
window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
// Suppress the middle-click autoscroll widget so middle-drag can pan instead.
canvas.addEventListener("mousedown", (event) => {
if (event.button === 1) event.preventDefault();
});
canvas.addEventListener("pointerdown", onPointerDown);
canvas.addEventListener("pointermove", onPointerMove);
canvas.addEventListener("pointerup", onPointerUp);
canvas.addEventListener("pointercancel", onPointerUp);
canvas.addEventListener("pointerleave", () => {
if (ui.mode === "aoe" && !isPlayer && tools.aoe.template.visible) {
tools.aoe.template.visible = false;
renderAndSyncView();
}
});
// While any drag is in progress, block the browser's native touch scrolling/cancel so a
// finger drag isn't stolen after the first cell. This is the imperative backstop to the
// canvas `touch-action: none`, which some touch stacks (e.g. Chromium on Linux with IR
// touch panels) don't fully honor. Must be non-passive so preventDefault is allowed.
canvas.addEventListener("touchmove", (event) => {
if (isDragging) event.preventDefault();
}, { passive: false });
// Player display: true multitouch token movement rides the Touch Events API (Pointer Events collapse
// the IR frame to a single contact). Non-passive so the handlers can preventDefault the browser's
// native scroll/zoom/context gestures. Each handler no-ops unless isPlayer, so the GM tab is untouched.
canvas.addEventListener("touchstart", onTouchStart, { passive: false });
canvas.addEventListener("touchmove", onTouchMove, { passive: false });
canvas.addEventListener("touchend", onTouchEnd, { passive: false });
canvas.addEventListener("touchcancel", onTouchEnd, { passive: false });
canvas.addEventListener("dblclick", onDoubleClick);
canvas.addEventListener("contextmenu", onContextMenu);
canvas.addEventListener("wheel", onWheel, { passive: false });
// Drag-and-drop image files onto the map to place them (GM only).
if (!isPlayer) {
canvas.addEventListener("dragover", (event) => {
if (event.dataTransfer?.types?.includes("Files")) {
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
}
});
canvas.addEventListener("drop", (event) => {
const files = [...(event.dataTransfer?.files || [])].filter((f) => f.type.startsWith("image/"));
if (!files.length || !state.imageData) return;
event.preventDefault();
const n = toNativePoint(event);
files.forEach((file) => addImageFile(file, n.x, n.y));
});
}
if (isPlayer) {
controls.playerFullscreen?.addEventListener("click", toggleFullscreen);
controls.playerFollow?.addEventListener("click", toggleFollow);
controls.dpadUp?.addEventListener("click", () => dpadStep("ArrowUp"));
controls.dpadDown?.addEventListener("click", () => dpadStep("ArrowDown"));
controls.dpadLeft?.addEventListener("click", () => dpadStep("ArrowLeft"));
controls.dpadRight?.addEventListener("click", () => dpadStep("ArrowRight"));
setupPlayerCursor();
}
resizeCanvas();
refreshFloorUI();
render();
// Sandbox first-load: drop visitors onto a sample map instead of a blank canvas.
// GM client only, and only when nothing's already loaded (don't clobber a returning visitor).
if (isSandbox && !isPlayer && !state.imageData) loadSampleMap();
}
function bindControls() {
controls.mapUpload.addEventListener("change", loadMapFile);
controls.dttUpload.addEventListener("change", loadMapModuleFile);
controls.splashUpload.addEventListener("change", loadSplashFile);
controls.splashEnabled.addEventListener("input", () => {
state.splash.enabled = controls.splashEnabled.checked;
if (state.splash.enabled) {
state.blackout = false;
controls.blackoutEnabled.checked = false;
}
renderAndSync();
});
controls.blackoutEnabled.addEventListener("input", () => {
state.blackout = controls.blackoutEnabled.checked;
if (state.blackout) {
state.splash.enabled = false;
controls.splashEnabled.checked = false;
}
renderAndSync();
});
controls.losEnabled?.addEventListener("input", () => {
state.los.enabled = controls.losEnabled.checked;
controls.losOptions?.classList.toggle("hidden", !state.los.enabled);
renderAndSync();
});
controls.loadLibrary.addEventListener("click", openLibrary);
if (controls.mapUp) controls.mapUp.addEventListener("click", ascend);
if (controls.mapJump) {
controls.mapJump.addEventListener("focus", populateMapJump); // refresh in case maps were added/renamed
controls.mapJump.addEventListener("change", () => {
const id = controls.mapJump.value;
if (id) jumpToMap(id).catch((e) => window.alert(`Could not jump to that map: ${e.message}`));
});
}
controls.loadFallon?.addEventListener("click", openFallonDialog);
controls.fallonMapSize?.addEventListener("input", () => setMapThumb(Number(controls.fallonMapSize.value) || 220));
if (controls.publishFallon) {
controls.publishFallon.addEventListener("click", publishToFallon);
}
if (controls.pullFallon) {
controls.pullFallon.addEventListener("click", pullSessionFromFallon);
}
if (controls.inviteFallon) {
controls.inviteFallon.addEventListener("click", openInviteDialog);
}
// The Online session section (Import party + fallon controls) belongs to a
// logged-in GM only. api.js broadcasts "vwag:auth" from its auth chokepoint on
// login, logout, and init; reflect that here. The direct call covers the
// restored-token case (token loaded before this runs); the event covers later
// login/logout with no reload. Guests carry a _token too, so guard on isPlayer.
if (!isPlayer) {
const onlineSection = document.getElementById("onlineSection");
const applyOnlineVisibility = () => {
if (onlineSection) onlineSection.classList.toggle("hidden", !isLoggedIn());
};
document.addEventListener("vwag:auth", applyOnlineVisibility);
applyOnlineVisibility();
}
if (controls.inviteCopy) {
controls.inviteCopy.addEventListener("click", () => {
const code = controls.inviteCode ? controls.inviteCode.textContent : "";
const restore = controls.inviteCopy.textContent;
const flash = (msg) => {
controls.inviteCopy.textContent = msg;
setTimeout(() => { controls.inviteCopy.textContent = restore; }, 1200);
};
if (!navigator.clipboard && !document.queryCommandSupported?.("copy")) { flash("Copy unavailable"); return; }
_copyText(code, controls.inviteDialog).then(() => flash("Copied"), () => flash("Copy failed"));
});
}
// Flush autosave on the moments most likely to drop the last few changes: the
// tab going hidden (screen sleep, tab switch — fires more reliably than unload)
// and the page unloading. autosaveNow() self-guards player view + scratch maps.
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") flushAutosave();
});
window.addEventListener("beforeunload", flushAutosave);
updateMapNavUI();
controls.saveSession.addEventListener("click", saveSession);
controls.exportLibrary?.addEventListener("click", exportLibrary);
controls.importLibrary?.addEventListener("change", importLibrary);
controls.backupFolder?.addEventListener("click", chooseBackupFolder);
controls.openPlayer.addEventListener("click", openPlayerWindow);
const gridBindings = [
["gridEnabled", "enabled", "checked"],
["gridSnap", "snap", "checked"],
["gridSize", "size", "value"],
["gridOffsetX", "offsetX", "value"],
["gridOffsetY", "offsetY", "value"],
["gridColor", "color", "value"],
["gridOpacity", "opacity", "value"],
];
gridBindings.forEach(([controlName, stateKey, prop]) => {
controls[controlName].addEventListener("input", () => {
state.grid[stateKey] = prop === "checked" ? controls[controlName][prop] : normalizeInput(controls[controlName][prop]);
renderAndSync();
});
});
controls.gridEnabled.addEventListener("input", updateMeasureCalibrateRow);
controls.brushSize.addEventListener("input", () => {
state.fog.toolSize = Number(controls.brushSize.value);
render();
});
controls.fogTint.addEventListener("input", () => {
state.fog.gmColor = controls.fogTint.value;
fogBuf.dirty = true;
render();
});
controls.gmFogOpacity.addEventListener("input", () => {
state.fog.gmOpacity = Number(controls.gmFogOpacity.value);
render();
});
controls.losBrightness?.addEventListener("input", () => {
state.los.brightness = Number(controls.losBrightness.value);
renderAndSync();
});
controls.resetExplored?.addEventListener("click", () => {
resetExplored(); // clear any GM-side memory (none today, but keeps behavior local-safe)
relay({ type: "reset-explored" }); // the player window holds the real explored memory
});
controls.mapScale.addEventListener("input", () => {
const prev = state.map.scale || 1;
const next = Number(controls.mapScale.value) || 1;
const r = prev > 0 && next > 0 ? next / prev : 1;
if (r !== 1) {
// Keep the cell grid locked to the map as it resizes: scale the cell's world size by the
// same factor as the image, so obstacles/lights/notes anchored to the grid scale with it
// instead of detaching. Native px/cell (grid.size / map.scale) stays invariant.
if (state.grid.size > 0) state.grid.size *= r;
if (state.measure.cellSize > 0) state.measure.cellSize *= r;
if (controls.gridSize) controls.gridSize.value = state.grid.size;
}
state.map.scale = next;
renderAndSync();
});
controls.paletteAdd?.addEventListener("click", addCurrentToPalette);
controls.paletteSize?.addEventListener("input", () => setPaletteThumb(Number(controls.paletteSize.value) || 64));
controls.mapSize?.addEventListener("input", () => setMapThumb(Number(controls.mapSize.value) || 220));
controls.paletteImport?.addEventListener("change", (e) => {
importImageFiles(e.target.files);
e.target.value = "";
});
controls.paletteFolder?.addEventListener("change", (e) => {
importImageFiles(e.target.files);
e.target.value = "";
});
controls.paletteExport?.addEventListener("click", exportPalette);
controls.paletteJson?.addEventListener("change", (e) => {
importPaletteJson(e.target.files[0]);
e.target.value = "";
});
controls.paletteDelete?.addEventListener("click", () => {
if (activePaletteId) deletePaletteEntry(activePaletteId);
});
controls.paletteSelectedName?.addEventListener("change", (e) => renameSelectedEntry(e.target.value));
controls.panMode.addEventListener("click", () => setMode("pan"));
controls.fogToggle.addEventListener("click", toggleFogRibbon);
controls.polygonMode.addEventListener("click", () => setMode("polygon"));
controls.namedPolygonMode.addEventListener("click", () => setMode("namedPolygon"));
controls.brushMode.addEventListener("click", () => setMode("brush"));
controls.eraserMode.addEventListener("click", () => setMode("eraser"));
controls.stampMode?.addEventListener("click", () => setMode("stamp"));
controls.tokenMode.addEventListener("click", () => setMode("token"));
controls.aoeMode?.addEventListener("click", () => setMode("aoe"));
controls.measureMode.addEventListener("click", () => setMode("measure"));
controls.stairMode?.addEventListener("click", () => setMode("stair"));
controls.mapLinkMode?.addEventListener("click", () => setMode("mapLink"));
controls.mapKindSelect?.addEventListener("change", () => {
state.mapKind = controls.mapKindSelect.value;
applyMapKindCaps(state.mapKind); // live; persists on next save like any other map edit
});
controls.drawMode?.addEventListener("click", () => setMode("draw"));
controls.lightMode?.addEventListener("click", () => setMode("light"));
controls.obstacleKind?.addEventListener("change", () => { tools.obstacleKind = controls.obstacleKind.value; });
controls.showObstacles?.addEventListener("change", () => { tools.showObstacles = controls.showObstacles.checked; render(); });
controls.lightRadius?.addEventListener("input", () => {
tools.lightRadius = Number(controls.lightRadius.value) || 1;
if (controls.lightRadiusVal) controls.lightRadiusVal.textContent = tools.lightRadius;
});
controls.lightColor?.addEventListener("input", () => {
tools.lightColor = controls.lightColor.value || "#ffd9a0";
});
controls.tokenLight?.addEventListener("input", () => {
if (controls.tokenLightVal) controls.tokenLightVal.textContent = Number(controls.tokenLight.value) || 0;
});
controls.tokenSelLight?.addEventListener("input", () => {
if (!sel.token) return;
sel.token.light = Number(controls.tokenSelLight.value) || 0;
if (controls.tokenSelLightVal) controls.tokenSelLightVal.textContent = sel.token.light;
renderAndSync();
});
controls.darknessEnabled?.addEventListener("input", () => { state.los.darkness = controls.darknessEnabled.checked; renderAndSync(); });
controls.losSource?.addEventListener("change", () => { state.los.source = controls.losSource.value; renderAndSync(); });
controls.castDebug?.addEventListener("change", () => { ui.castDebug = controls.castDebug.checked; render(); });
// Floor navigation
controls.floorOverlay?.addEventListener("click", (event) => {
const act = event.target.closest("[data-act]")?.dataset.act;
if (act === "floor-up") { goToFloor(currentFloorIndex() + 1); return; }
if (act === "floor-down") { goToFloor(currentFloorIndex() - 1); return; }
if (act === "move-up" || act === "move-down") {
const li = event.target.closest("[data-idx]");
if (li) moveFloor(Number(li.dataset.idx), act === "move-up" ? 1 : -1);
return; // must return before the row-jump below, or reordering would also change floors
}
const row = event.target.closest("[data-idx]");
if (row) goToFloor(Number(row.dataset.idx)); // jump straight to any floor
});
controls.addFloorUp?.addEventListener("click", () => addFloor("up"));
controls.addFloorDown?.addEventListener("click", () => addFloor("down"));
controls.deleteFloor?.addEventListener("click", deleteCurrentFloor);
controls.floorName?.addEventListener("change", () => {
const floor = state.floors[currentFloorIndex()];
if (floor) {
floor.name = controls.floorName.value.trim();
refreshFloorUI();
broadcastState();
}
});
controls.stairSelFloor?.addEventListener("change", () => {
if (!sel.stair) return;
sel.stair.targetFloorId = controls.stairSelFloor.value;
renderAndSync(); // target changed → the stair's up/down arrow may flip
});
controls.stairSelLabel?.addEventListener("input", () => {
if (!sel.stair) return;
sel.stair.label = controls.stairSelLabel.value.trim();
renderAndSync();
});
controls.stairSelDelete?.addEventListener("click", () => {
if (!sel.stair) return;
pushHistory();
state.stairs = state.stairs.filter((s) => s !== sel.stair);
sel.stair = null;
updateSelectionPanels();
renderAndSync();
});
controls.mapLinkSelTarget?.addEventListener("change", () => {
if (!sel.mapLink) return;
sel.mapLink.targetMapId = controls.mapLinkSelTarget.value;
renderAndSync();
});
controls.mapLinkSelLabel?.addEventListener("input", () => {
if (!sel.mapLink) return;
sel.mapLink.label = controls.mapLinkSelLabel.value.trim();
renderAndSync();
});
controls.mapLinkSelDelete?.addEventListener("click", () => {
if (!sel.mapLink) return;
pushHistory();
state.mapLinks = state.mapLinks.filter((m) => m !== sel.mapLink);
sel.mapLink = null;
updateSelectionPanels();
renderAndSync();
});
controls.aoeSelRename?.addEventListener("click", () => {
if (!sel.aoe) return;
promptAoeName(sel.aoe, { isNew: false });
});
controls.aoeSelColor?.addEventListener("input", () => {
if (!sel.aoe) return;
sel.aoe.color = controls.aoeSelColor.value;
renderAndSync();
});
controls.aoeSelSize?.addEventListener("input", () => {
if (!sel.aoe) return;
const v = parseFloat(controls.aoeSelSize.value);
if (v > 0) { sel.aoe.sizeFt = v; renderAndSync(); } // resize any placed zone; mirrors to players
});
controls.aoeSelAngleSlider?.addEventListener("input", () => {
if (!sel.aoe) return;
sel.aoe.angle = parseFloat(controls.aoeSelAngleSlider.value) * Math.PI / 180; // re-aim a placed cone
renderAndSync();
});
controls.aoeSelDelete?.addEventListener("click", () => {
if (!sel.aoe) return;
pushHistory();
state.aoes = state.aoes.filter((a) => a !== sel.aoe);
sel.aoe = null;
updateSelectionPanels();
renderAndSync();
});
controls.pushToTable?.addEventListener("click", () => {
// Point the players' table at the floor the GM is currently viewing, and broadcast it.
state.activeFloorId = state.currentFloorId;
refreshFloorUI();
broadcastAssets();
broadcastState();
});
controls.pinTable?.addEventListener("change", () => {
ui.pinTable = controls.pinTable.checked;
// Pin and follow are mutually exclusive table drivers — turning pin on clears follow.
if (ui.pinTable && ui.followInitiative) {
ui.followInitiative = false;
if (controls.followInitiative) controls.followInitiative.checked = false;
}
// Unpinning re-couples the table to the GM's current view immediately.
if (!ui.pinTable && state.activeFloorId !== state.currentFloorId) {
state.activeFloorId = state.currentFloorId;
broadcastAssets();
broadcastState();
}
refreshFloorUI();
});
controls.followInitiative?.addEventListener("change", () => {
ui.followInitiative = controls.followInitiative.checked;
if (ui.followInitiative) {
// Mutually exclusive with pin; turning follow on clears pin and immediately points the
// table at the active combatant's floor.
if (ui.pinTable) {
ui.pinTable = false;
if (controls.pinTable) controls.pinTable.checked = false;
}
if (!followTableToActiveTurn()) refreshFloorUI();
broadcastState();
} else {
// Turning follow off re-couples the table to the GM's current view (like unpinning).
if (state.activeFloorId !== state.currentFloorId) {
state.activeFloorId = state.currentFloorId;
broadcastAssets();
}
refreshFloorUI();
broadcastState();
}
});
controls.roundShape.addEventListener("click", () => setToolShape("round"));
controls.squareShape.addEventListener("click", () => setToolShape("square"));
controls.stampRect?.addEventListener("click", () => setStampShape("rectangle"));
controls.stampSquare?.addEventListener("click", () => setStampShape("square"));
controls.stampEllipse?.addEventListener("click", () => setStampShape("ellipse"));
controls.stampCircle?.addEventListener("click", () => setStampShape("circle"));
controls.stampTriangle?.addEventListener("click", () => setStampShape("triangle"));
controls.tokenImage?.addEventListener("change", loadTokenImage);
controls.tokenImageClear?.addEventListener("click", clearTokenImage);
controls.measureUnit?.addEventListener("change", () => {
state.measure.unit = controls.measureUnit.value === "metric" ? "metric" : "imperial";
renderAndSync();
});
controls.aoeCircle?.addEventListener("click", () => setAoeShape("circle"));
controls.aoeSquare?.addEventListener("click", () => setAoeShape("square"));
controls.aoeCone?.addEventListener("click", () => setAoeShape("cone"));
controls.aoeColor?.addEventListener("input", () => {
tools.aoe.color = controls.aoeColor.value;
render();
});
controls.aoeCustomSize?.addEventListener("input", () => {
const v = parseFloat(controls.aoeCustomSize.value);
if (v > 0) { tools.aoe.sizeFt = v; updateAoePresets(); render(); }
});
controls.aoeAngleSlider?.addEventListener("input", () => {
tools.aoe.angle = parseFloat(controls.aoeAngleSlider.value) * Math.PI / 180;
renderAndSyncView(); // mirror the live template aim to the players (parity with the wheel)
});
controls.measureCalibrate?.addEventListener("click", () => armCalibration("measure"));
controls.calibrateScale?.addEventListener("click", () => armCalibration("scale"));
controls.gridCalibrate?.addEventListener("click", () => armCalibration("grid"));
controls.playerFrameToggle?.addEventListener("input", () => {
ui.showPlayerFrame = controls.playerFrameToggle.checked;
render();
});
controls.playerFrameColor?.addEventListener("input", () => {
ui.playerFrameColor = controls.playerFrameColor.value;
render();
});
controls.playerFrameOpacity?.addEventListener("input", () => {
ui.playerFrameOpacity = parseFloat(controls.playerFrameOpacity.value);
render();
});
controls.panelToggle?.addEventListener("click", togglePanelCollapsed);
// Initiative tracker
controls.initToggle?.addEventListener("click", toggleInitiative);
controls.notesToggle?.addEventListener("click", toggleNotes);
controls.notesClose?.addEventListener("click", closeNotes);
controls.notesAdd?.addEventListener("click", addNote);
controls.notesDelete?.addEventListener("click", deleteSelectedNote);
initNotesPanel();
controls.initClose?.addEventListener("click", () => setInitiativeActive(false));
controls.initPrev?.addEventListener("click", () => stepInitiative(-1));
controls.initNext?.addEventListener("click", () => stepInitiative(1));
controls.initReset?.addEventListener("click", resetInitiative);
controls.initShowPlayers?.addEventListener("input", () => {
state.initiative.showPlayers = controls.initShowPlayers.checked;
updateInitiativeUI();
broadcastState();
});
controls.initShowOverlay?.addEventListener("input", () => {