-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1837 lines (1660 loc) · 70.9 KB
/
Copy pathapp.js
File metadata and controls
1837 lines (1660 loc) · 70.9 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
'use strict';
/* =========================================================================
ENGINE — pure state functions. No DOM, no globals besides Date/Math/crypto.
Mutates the state object it's given and also returns it, for convenience.
========================================================================= */
/* ENGINE:START */
var Engine = (function () {
var MIN_BUDGET_MS = 10000;
var UNDO_CAP = 20;
function uid() {
if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
return 'id-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 10);
}
function clampBudget(ms) {
var n = Math.round(Number(ms));
if (!isFinite(n) || n < MIN_BUDGET_MS) return MIN_BUDGET_MS;
return n;
}
function shuffle(arr) {
var a = arr.slice();
for (var i = a.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
return a;
}
// ---- Profile -----------------------------------------------------------
function newProfile() {
var now = Date.now();
return {
id: uid(),
name: '',
createdAt: now,
lastPlayedAt: null,
mode: 'total',
incrementMs: 30000,
warningMs: 10000,
alertsEnabled: true,
players: [],
order: []
};
}
// Low-time warning defaults: a fixed 10s for modes with a whole-game
// budget, but half the per-turn allowance for "per turn" games, since a
// 10s warning would be meaningless (or the whole turn) on a short clock.
function defaultWarningMs(mode, turnBudgetMs) {
if (mode === 'per_turn') return Math.max(0, Math.round((turnBudgetMs || 0) / 2));
return 10000;
}
// Repeat cadence for the low-time warning (beep + screen pulse), given how
// much time the current player has left. null means "not in the warning
// zone" — either still above the threshold, or already in overdraft
// (negative), which has its own distinct always-on red/buzz treatment.
function warningCadenceMs(remainingMs, warningMs) {
if (remainingMs < 0 || remainingMs > warningMs) return null;
if (remainingMs > 30000) return 5000;
if (remainingMs > 10000) return 2000;
return 1000;
}
function newProfilePlayer(name, color, budgetMs, incrementMs) {
return {
id: uid(), name: name || 'Player', color: color || 'red', budgetMs: clampBudget(budgetMs),
incrementMs: Math.max(0, Math.round(Number(incrementMs) || 0))
};
}
// ---- GameState -----------------------------------------------------------
function createGameState(profile) {
var players = {};
profile.order.forEach(function (id) {
var src = profile.players.filter(function (p) { return p.id === id; })[0];
if (!src) return;
players[id] = {
id: src.id,
name: src.name,
color: src.color,
budgetMs: clampBudget(src.budgetMs),
committedRemainingMs: clampBudget(src.budgetMs),
incrementMs: src.incrementMs != null ? src.incrementMs : (profile.incrementMs || 0),
turnsTaken: 0,
totalUsedMs: 0,
longestTurnMs: 0,
overdraftMs: 0,
active: true,
removed: false
};
});
var now = Date.now();
return {
profileId: profile.id,
profileName: profile.name,
mode: profile.mode,
incrementMs: profile.incrementMs || 0,
warningMs: profile.warningMs != null ? profile.warningMs : 10000,
alertsEnabled: profile.alertsEnabled !== false,
players: players,
order: profile.order.slice(),
currentIndex: 0,
turnStartedAt: now,
pausedAt: null,
startedAt: now,
undoStack: []
};
}
// "now" respects an active pause so live values freeze while paused.
function effectiveNow(state) {
return state.pausedAt != null ? state.pausedAt : Date.now();
}
function currentPlayerId(state) {
return state.order[state.currentIndex];
}
// Display value, computed fresh — never stored, never decremented on tick.
function remainingMs(state, playerId) {
var p = state.players[playerId];
if (!p) return 0;
var isCurrent = currentPlayerId(state) === playerId;
if (!isCurrent || state.turnStartedAt === null) return p.committedRemainingMs;
return p.committedRemainingMs - (effectiveNow(state) - state.turnStartedAt);
}
function turnElapsedMs(state) {
if (state.turnStartedAt === null) return 0;
return effectiveNow(state) - state.turnStartedAt;
}
function isPaused(state) {
return state.pausedAt != null;
}
function isActivePlayer(state, playerId) {
var p = state.players[playerId];
return !!p && p.active && !p.removed;
}
function nextActiveIndex(state, fromIndex) {
var n = state.order.length;
for (var step = 1; step <= n; step++) {
var idx = (fromIndex + step) % n;
if (isActivePlayer(state, state.order[idx])) return idx;
}
return fromIndex;
}
function countActive(state) {
return state.order.reduce(function (n, id) {
return n + (isActivePlayer(state, id) ? 1 : 0);
}, 0);
}
// Commits the CURRENT player's elapsed time into committedRemainingMs and
// stats. Used by endTurn / jumpToPlayer / toggleActive(deactivating current).
// Does not touch currentIndex or turnStartedAt.
function commitCurrentPlayerTurn(state) {
if (state.turnStartedAt === null) return;
var id = currentPlayerId(state);
var p = state.players[id];
if (!p) return;
var elapsed = effectiveNow(state) - state.turnStartedAt;
var prevRemaining = p.committedRemainingMs;
p.committedRemainingMs = prevRemaining - elapsed;
p.totalUsedMs += elapsed;
p.longestTurnMs = Math.max(p.longestTurnMs, elapsed);
p.turnsTaken += 1;
var overdraftDelta = Math.max(0, elapsed - Math.max(0, prevRemaining));
p.overdraftMs += overdraftDelta;
if (state.mode === 'total_increment') {
p.committedRemainingMs += (p.incrementMs != null ? p.incrementMs : state.incrementMs) || 0;
}
}
function resetAllowanceIfPerTurn(state, playerId) {
if (state.mode !== 'per_turn') return;
var p = state.players[playerId];
if (p) p.committedRemainingMs = p.budgetMs;
}
function snapshot(state) {
var copy = JSON.parse(JSON.stringify(state));
delete copy.undoStack;
return copy;
}
function pushUndo(state) {
state.undoStack.push(snapshot(state));
if (state.undoStack.length > UNDO_CAP) state.undoStack.shift();
}
function endTurn(state) {
pushUndo(state);
commitCurrentPlayerTurn(state);
state.currentIndex = nextActiveIndex(state, state.currentIndex);
resetAllowanceIfPerTurn(state, currentPlayerId(state));
state.turnStartedAt = effectiveNow(state);
return state;
}
function jumpToPlayer(state, targetId) {
var idx = state.order.indexOf(targetId);
if (idx === -1 || idx === state.currentIndex) return state;
if (!isActivePlayer(state, targetId)) return state;
pushUndo(state);
commitCurrentPlayerTurn(state);
state.currentIndex = idx;
resetAllowanceIfPerTurn(state, targetId);
state.turnStartedAt = effectiveNow(state);
return state;
}
// Admin correction: like jumpToPlayer, but not part of the single-tap undo
// stack (admin has its own explicit controls to fix mistakes).
function adminSetCurrentPlayer(state, targetId) {
var idx = state.order.indexOf(targetId);
if (idx === -1 || idx === state.currentIndex) return state;
commitCurrentPlayerTurn(state);
state.currentIndex = idx;
resetAllowanceIfPerTurn(state, targetId);
state.turnStartedAt = effectiveNow(state);
return state;
}
function undo(state) {
if (!state.undoStack.length) return state;
var stack = state.undoStack;
var prev = stack[stack.length - 1];
prev.undoStack = stack.slice(0, -1);
return prev;
}
function pauseGame(state) {
if (state.pausedAt != null) return state;
state.pausedAt = Date.now();
return state;
}
function resumeGame(state) {
if (state.pausedAt == null) return state;
if (state.turnStartedAt != null) {
state.turnStartedAt += Date.now() - state.pausedAt;
}
state.pausedAt = null;
return state;
}
function adjustRemaining(state, playerId, deltaMs) {
var p = state.players[playerId];
if (!p) return state;
p.committedRemainingMs += deltaMs;
return state;
}
function setRemaining(state, playerId, ms) {
var p = state.players[playerId];
if (!p) return state;
p.committedRemainingMs = ms;
return state;
}
function renamePlayer(state, playerId, name) {
var p = state.players[playerId];
if (p) p.name = name;
return state;
}
function reorderPlayers(state, newOrder) {
var currentId = currentPlayerId(state);
state.order = newOrder.slice();
var idx = state.order.indexOf(currentId);
state.currentIndex = idx === -1 ? 0 : idx;
return state;
}
function toggleActive(state, playerId) {
var p = state.players[playerId];
if (!p || p.removed) return { ok: false, reason: 'not-found' };
if (p.active) {
var others = state.order.some(function (id) {
return id !== playerId && isActivePlayer(state, id);
});
if (!others) return { ok: false, reason: 'last-active' };
p.active = false;
if (currentPlayerId(state) === playerId) {
commitCurrentPlayerTurn(state);
state.currentIndex = nextActiveIndex(state, state.currentIndex);
resetAllowanceIfPerTurn(state, currentPlayerId(state));
state.turnStartedAt = effectiveNow(state);
}
} else {
p.active = true;
}
return { ok: true };
}
// Removed players keep their stats (state.players[id]) but are spliced out
// of the rotation entirely — unlike an inactive player, they never come back.
function removePlayer(state, playerId) {
var p = state.players[playerId];
if (!p || p.removed) return { ok: false, reason: 'not-found' };
var idx = state.order.indexOf(playerId);
if (idx === -1) return { ok: false, reason: 'not-found' };
var others = state.order.some(function (id) {
return id !== playerId && isActivePlayer(state, id);
});
if (p.active && !others) return { ok: false, reason: 'last-active' };
var wasCurrent = idx === state.currentIndex;
if (wasCurrent) commitCurrentPlayerTurn(state);
p.removed = true;
p.active = false;
state.order.splice(idx, 1);
if (state.order.length === 0) {
state.currentIndex = 0;
return { ok: true };
}
if (idx < state.currentIndex) {
state.currentIndex -= 1;
} else if (wasCurrent) {
var n = state.order.length;
var searchFrom = ((idx - 1) % n + n) % n;
state.currentIndex = nextActiveIndex(state, searchFrom);
resetAllowanceIfPerTurn(state, currentPlayerId(state));
state.turnStartedAt = effectiveNow(state);
}
return { ok: true };
}
function addPlayerMidGame(state, name, color, budgetMs, incrementMs) {
var id = uid();
var ms = clampBudget(budgetMs);
state.players[id] = {
id: id, name: name || 'Player', color: color || 'stone',
budgetMs: ms, committedRemainingMs: ms,
incrementMs: incrementMs != null ? Math.max(0, Math.round(Number(incrementMs) || 0)) : (state.incrementMs || 0),
turnsTaken: 0, totalUsedMs: 0, longestTurnMs: 0, overdraftMs: 0,
active: true, removed: false
};
var insertAt = state.currentIndex + 1;
state.order.splice(insertAt, 0, id);
if (insertAt <= state.currentIndex) state.currentIndex += 1;
return id;
}
function saveGameToProfile(state, profile) {
var players = state.order
.filter(function (id) { return !state.players[id].removed; })
.map(function (id) {
var p = state.players[id];
return { id: p.id, name: p.name, color: p.color, budgetMs: p.budgetMs, incrementMs: p.incrementMs || 0 };
});
profile.players = players;
profile.order = players.map(function (p) { return p.id; });
return profile;
}
return {
MIN_BUDGET_MS: MIN_BUDGET_MS,
uid: uid,
clampBudget: clampBudget,
shuffle: shuffle,
newProfile: newProfile,
newProfilePlayer: newProfilePlayer,
defaultWarningMs: defaultWarningMs,
warningCadenceMs: warningCadenceMs,
createGameState: createGameState,
remainingMs: remainingMs,
turnElapsedMs: turnElapsedMs,
isPaused: isPaused,
isActivePlayer: isActivePlayer,
currentPlayerId: currentPlayerId,
countActive: countActive,
endTurn: endTurn,
jumpToPlayer: jumpToPlayer,
adminSetCurrentPlayer: adminSetCurrentPlayer,
undo: undo,
pauseGame: pauseGame,
resumeGame: resumeGame,
adjustRemaining: adjustRemaining,
setRemaining: setRemaining,
renamePlayer: renamePlayer,
reorderPlayers: reorderPlayers,
toggleActive: toggleActive,
removePlayer: removePlayer,
addPlayerMidGame: addPlayerMidGame,
saveGameToProfile: saveGameToProfile
};
})();
/* ENGINE:END */
/* =========================================================================
STORAGE — localStorage read/write, JSON in/out.
========================================================================= */
var Storage = (function () {
var KEYS = {
profiles: 'gt:profiles', activeGame: 'gt:activeGame', lastProfileId: 'gt:lastProfileId',
history: 'gt:history', seededDefault: 'gt:seededDefault'
};
var MAX_HISTORY = 30;
function safeGet(key) {
try { return localStorage.getItem(key); } catch (e) { return null; }
}
function safeSet(key, value) {
try { localStorage.setItem(key, value); } catch (e) { /* storage unavailable/full — ignore */ }
}
function safeRemove(key) {
try { localStorage.removeItem(key); } catch (e) { /* ignore */ }
}
function loadProfiles() {
var raw = safeGet(KEYS.profiles);
if (!raw) return {};
try { return JSON.parse(raw) || {}; } catch (e) { return {}; }
}
function saveProfiles(profiles) { safeSet(KEYS.profiles, JSON.stringify(profiles)); }
function saveProfile(profile) {
var all = loadProfiles();
all[profile.id] = profile;
saveProfiles(all);
}
function deleteProfile(id) {
var all = loadProfiles();
delete all[id];
saveProfiles(all);
}
function loadActiveGame() {
var raw = safeGet(KEYS.activeGame);
if (!raw) return null;
try { return JSON.parse(raw); } catch (e) { return null; }
}
function saveActiveGame(state) { safeSet(KEYS.activeGame, JSON.stringify(state)); }
function clearActiveGame() { safeRemove(KEYS.activeGame); }
function getLastProfileId() { return safeGet(KEYS.lastProfileId); }
function setLastProfileId(id) { safeSet(KEYS.lastProfileId, id); }
function hasSeededDefault() { return safeGet(KEYS.seededDefault) === '1'; }
function markSeededDefault() { safeSet(KEYS.seededDefault, '1'); }
function loadHistory() {
var raw = safeGet(KEYS.history);
if (!raw) return [];
try { var arr = JSON.parse(raw); return Array.isArray(arr) ? arr : []; } catch (e) { return []; }
}
function saveHistory(list) { safeSet(KEYS.history, JSON.stringify(list)); }
function addHistoryEntry(entry) {
var list = loadHistory();
list.unshift(entry);
if (list.length > MAX_HISTORY) list.length = MAX_HISTORY;
saveHistory(list);
return entry;
}
function deleteHistoryEntry(id) {
saveHistory(loadHistory().filter(function (e) { return e.id !== id; }));
}
return {
loadProfiles: loadProfiles, saveProfiles: saveProfiles, saveProfile: saveProfile,
deleteProfile: deleteProfile, loadActiveGame: loadActiveGame, saveActiveGame: saveActiveGame,
clearActiveGame: clearActiveGame, getLastProfileId: getLastProfileId, setLastProfileId: setLastProfileId,
loadHistory: loadHistory, addHistoryEntry: addHistoryEntry, deleteHistoryEntry: deleteHistoryEntry,
hasSeededDefault: hasSeededDefault, markSeededDefault: markSeededDefault
};
})();
/* =========================================================================
PALETTE — player color tokens, matched to CSS custom properties.
========================================================================= */
var PALETTE = ['red', 'blue', 'amber', 'green', 'purple', 'orange', 'teal', 'stone', 'white', 'black'];
function colorVar(token) { return 'var(--c-' + (token || 'stone') + ')'; }
var MODE_LABEL = { total: 'Total time', per_turn: 'Per turn', total_increment: 'Total + increment' };
/* =========================================================================
TIME FORMATTING
========================================================================= */
function formatClock(ms, showTenths) {
var neg = ms < 0;
var abs = Math.abs(ms);
var m = Math.floor(abs / 60000);
var s = Math.floor((abs % 60000) / 1000);
var str = m + ':' + (s < 10 ? '0' : '') + s;
if (showTenths) {
var t = Math.floor((abs % 1000) / 100);
str += '.' + t;
}
return (neg ? '−' : '') + str;
}
function formatClockPlain(ms) {
// mm:ss for admin direct-entry fields; always non-negative display base, sign handled separately.
return formatClock(ms, false);
}
function formatMinSec(min, sec) { return (min * 60 + sec) * 1000; }
function parseClockToMs(str) {
str = String(str).trim();
var neg = str.charAt(0) === '-' || str.charAt(0) === '−';
if (neg) str = str.slice(1);
var parts = str.split(':');
var m = 0, s = 0;
if (parts.length === 2) { m = parseInt(parts[0], 10) || 0; s = parseInt(parts[1], 10) || 0; }
else { s = parseInt(parts[0], 10) || 0; }
var ms = (m * 60 + s) * 1000;
return neg ? -ms : ms;
}
function formatDuration(ms) {
var abs = Math.round(Math.abs(ms) / 1000);
var m = Math.floor(abs / 60), s = abs % 60;
return m + ':' + (s < 10 ? '0' : '') + s;
}
function formatDateShort(ts) {
if (!ts) return 'never played';
var d = new Date(ts);
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}
/* =========================================================================
AUDIO — synthesized alert tones, no bundled assets. Created lazily on the
first user gesture (Start game / Resume), per browser autoplay rules.
========================================================================= */
var AudioFx = (function () {
var ctx = null;
function ensureCtx() {
if (ctx) return ctx;
var Ctor = window.AudioContext || window.webkitAudioContext;
if (!Ctor) return null;
ctx = new Ctor();
return ctx;
}
function tone(freq, startAt, durationS, gainPeak, type) {
if (!ctx) return;
var osc = ctx.createOscillator();
var gain = ctx.createGain();
osc.type = type || 'sine';
osc.frequency.value = freq;
gain.gain.setValueAtTime(0, startAt);
gain.gain.linearRampToValueAtTime(gainPeak, startAt + 0.015);
gain.gain.exponentialRampToValueAtTime(0.0001, startAt + durationS);
osc.connect(gain).connect(ctx.destination);
osc.start(startAt);
osc.stop(startAt + durationS + 0.02);
}
function unlock() {
var c = ensureCtx();
if (c && c.state === 'suspended') c.resume();
}
// short, crisp beep — repeated at a ramping cadence by the low-time warning
// as a player's turn runs down toward zero.
function playWarningBeep() {
var c = ensureCtx(); if (!c) return;
var t = c.currentTime;
tone(740, t, 0.12, 0.16, 'triangle');
}
// distinct low descending buzz at zero
function playZero() {
var c = ensureCtx(); if (!c) return;
var t = c.currentTime;
var osc = c.createOscillator();
var gain = c.createGain();
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(300, t);
osc.frequency.exponentialRampToValueAtTime(120, t + 0.45);
gain.gain.setValueAtTime(0, t);
gain.gain.linearRampToValueAtTime(0.14, t + 0.02);
gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.5);
osc.connect(gain).connect(c.destination);
osc.start(t);
osc.stop(t + 0.52);
}
return { unlock: unlock, playZero: playZero, playWarningBeep: playWarningBeep };
})();
/* =========================================================================
WAKE LOCK
========================================================================= */
var WakeLockCtl = (function () {
var sentinel = null;
var wanted = false;
var hintShown = false;
function request() {
wanted = true;
if (!('wakeLock' in navigator)) {
if (!hintShown) {
hintShown = true;
toast('Tip: disable auto-lock in device settings for uninterrupted play.');
}
return;
}
navigator.wakeLock.request('screen').then(function (s) {
sentinel = s;
}).catch(function () { /* ignore — will retry on visibilitychange */ });
}
function release() {
wanted = false;
if (sentinel) { sentinel.release().catch(function () {}); sentinel = null; }
}
document.addEventListener('visibilitychange', function () {
if (wanted && document.visibilityState === 'visible') request();
});
return { request: request, release: release };
})();
/* =========================================================================
DRAG REORDER — generic pointer-based list reordering, touch + mouse.
Rows must have a `.drag-handle` child and a `data-id` attribute on the row.
========================================================================= */
function enableDragReorder(listEl, onReorder) {
var dragging = null;
var startY = 0;
var rowHeight = 0;
listEl.addEventListener('pointerdown', function (e) {
var handle = e.target.closest('.drag-handle');
if (!handle) return;
var row = handle.closest('[data-id]');
if (!row) return;
dragging = row;
startY = e.clientY;
rowHeight = row.offsetHeight;
row.classList.add('dragging');
handle.setPointerCapture(e.pointerId);
});
listEl.addEventListener('pointermove', function (e) {
if (!dragging) return;
var dy = e.clientY - startY;
if (Math.abs(dy) < rowHeight / 2) return;
var sibling = dy > 0 ? dragging.nextElementSibling : dragging.previousElementSibling;
if (!sibling) return;
if (dy > 0) listEl.insertBefore(sibling, dragging);
else listEl.insertBefore(dragging, sibling);
startY = e.clientY;
});
function finish() {
if (!dragging) return;
dragging.classList.remove('dragging');
dragging = null;
var ids = Array.prototype.map.call(listEl.querySelectorAll('[data-id]'), function (el) {
return el.getAttribute('data-id');
});
onReorder(ids);
}
listEl.addEventListener('pointerup', finish);
listEl.addEventListener('pointercancel', finish);
}
/* =========================================================================
MISC UI HELPERS
========================================================================= */
var toastTimer = null;
function toast(msg) {
var el = document.getElementById('toast');
el.textContent = msg;
el.classList.remove('hidden');
clearTimeout(toastTimer);
toastTimer = setTimeout(function () { el.classList.add('hidden'); }, 2200);
}
function debounce250() {
var last = 0;
return function () {
var now = Date.now();
if (now - last < 250) return false;
last = now;
return true;
};
}
/* =========================================================================
APP CONTROLLER
========================================================================= */
(function () {
var currentGame = null; // active GameState, or null
var soundOn = true;
var rafId = null;
var stripEls = {};
var prevDisplay = { current: null, elapsed: null };
var zeroFired = { key: null, fired: false };
var warningState = { key: null, lastFireAt: 0 };
var canEndTurn = debounce250();
var setupState = null;
var editingProfileId = null;
var colorPickerTargetId = null;
var pendingStartProfileId = null;
// ---- screen switching -------------------------------------------------
function showScreenRaw(name) {
document.querySelectorAll('.screen').forEach(function (s) {
s.classList.toggle('hidden', s.getAttribute('data-screen') !== name);
});
hideAllOverlaysAndSheets();
if (name !== 'play') leavePlayScreen();
}
function hideAllOverlaysAndSheets() {
document.getElementById('sheet-confirm-start').classList.add('hidden');
document.getElementById('popover-color').classList.add('hidden');
document.getElementById('overlay-pause').classList.add('hidden');
document.getElementById('overlay-admin').classList.add('hidden');
}
function persist() {
if (currentGame) Storage.saveActiveGame(currentGame);
}
// ---- HOME ---------------------------------------------------------------
var TRASH_SVG = '<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true">' +
'<path d="M5 7h14M10 7V5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v2m-7 0 1 13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1l1-13" ' +
'stroke="currentColor" stroke-width="1.8" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>';
function buildProfileRow(profile) {
var li = document.createElement('li');
li.className = 'profile-row';
var main = document.createElement('button');
main.type = 'button';
main.className = 'profile-row-main';
var name = document.createElement('p');
name.className = 'profile-row-name';
name.textContent = profile.name || 'Untitled timer';
var meta = document.createElement('p');
meta.className = 'profile-row-meta';
var firstBudget = profile.players[0] ? formatDuration(profile.players[0].budgetMs) : '';
meta.textContent = profile.players.length + ' players · ' + (MODE_LABEL[profile.mode] || profile.mode) +
' · ' + firstBudget + ' · ' + formatDateShort(profile.lastPlayedAt);
main.appendChild(name);
main.appendChild(meta);
main.addEventListener('click', function () { openConfirmStart(profile.id); });
var editBtn = document.createElement('button');
editBtn.type = 'button';
editBtn.className = 'profile-row-edit';
editBtn.setAttribute('aria-label', 'Edit ' + (profile.name || 'timer'));
editBtn.textContent = '✎';
editBtn.addEventListener('click', function (e) { e.stopPropagation(); openSetupEdit(profile.id); });
var deleteBtn = document.createElement('button');
deleteBtn.type = 'button';
deleteBtn.className = 'profile-row-delete';
deleteBtn.setAttribute('aria-label', 'Delete ' + (profile.name || 'timer'));
deleteBtn.innerHTML = TRASH_SVG;
deleteBtn.addEventListener('click', function (e) {
e.stopPropagation();
if (!confirm('Delete "' + (profile.name || 'Untitled timer') + '"? This cannot be undone.')) return;
Storage.deleteProfile(profile.id);
renderHome();
});
li.appendChild(main);
li.appendChild(editBtn);
li.appendChild(deleteBtn);
return li;
}
function buildActiveGameRow(activeGame) {
var li = document.createElement('li');
li.className = 'profile-row profile-row-active';
var main = document.createElement('button');
main.type = 'button';
main.className = 'profile-row-main';
var badge = document.createElement('p');
badge.className = 'profile-row-badge';
badge.textContent = 'Game in progress';
var name = document.createElement('p');
name.className = 'profile-row-name';
name.textContent = activeGame.profileName;
var meta = document.createElement('p');
meta.className = 'profile-row-meta';
var curId = Engine.currentPlayerId(activeGame);
var curName = (activeGame.players[curId] && activeGame.players[curId].name) || '';
meta.textContent = curName + '’s turn · started ' + formatDateShort(activeGame.startedAt);
main.appendChild(badge);
main.appendChild(name);
main.appendChild(meta);
function resumeActiveGame() {
currentGame = Storage.loadActiveGame();
if (!currentGame) return;
soundOn = currentGame.alertsEnabled !== false;
AudioFx.unlock();
showScreenRaw('play');
enterPlayScreen();
}
main.addEventListener('click', resumeActiveGame);
var resumeBtn = document.createElement('button');
resumeBtn.type = 'button';
resumeBtn.className = 'btn btn-accent';
resumeBtn.textContent = 'Resume';
resumeBtn.addEventListener('click', function (e) {
e.stopPropagation();
resumeActiveGame();
});
var deleteBtn = document.createElement('button');
deleteBtn.type = 'button';
deleteBtn.className = 'profile-row-delete';
deleteBtn.setAttribute('aria-label', 'Delete in-progress game');
deleteBtn.innerHTML = TRASH_SVG;
deleteBtn.addEventListener('click', function (e) {
e.stopPropagation();
if (!confirm('Delete this in-progress game? This cannot be undone.')) return;
Storage.clearActiveGame();
renderHome();
});
li.appendChild(main);
li.appendChild(resumeBtn);
li.appendChild(deleteBtn);
return li;
}
function buildHistoryRow(entry) {
var li = document.createElement('li');
li.className = 'profile-row';
var main = document.createElement('button');
main.type = 'button';
main.className = 'profile-row-main';
var name = document.createElement('p');
name.className = 'profile-row-name';
name.textContent = entry.state.profileName || 'Untitled timer';
var meta = document.createElement('p');
meta.className = 'profile-row-meta';
var playerCount = Object.keys(entry.state.players).length;
meta.textContent = playerCount + ' players · ' + (MODE_LABEL[entry.state.mode] || entry.state.mode) +
' · ' + formatDateShort(entry.endedAt);
main.appendChild(name);
main.appendChild(meta);
main.addEventListener('click', function () { openHistoryDetail(entry); });
var deleteBtn = document.createElement('button');
deleteBtn.type = 'button';
deleteBtn.className = 'profile-row-delete';
deleteBtn.setAttribute('aria-label', 'Delete ' + (entry.state.profileName || 'game') + ' from history');
deleteBtn.innerHTML = TRASH_SVG;
deleteBtn.addEventListener('click', function (e) {
e.stopPropagation();
if (!confirm('Delete "' + (entry.state.profileName || 'Untitled timer') + '" from your recent games? This cannot be undone.')) return;
Storage.deleteHistoryEntry(entry.id);
renderHome();
});
li.appendChild(main);
li.appendChild(deleteBtn);
return li;
}
function openHistoryDetail(entry) {
currentGame = entry.state;
renderSummary(currentGame);
showScreenRaw('summary');
}
function renderHome() {
var profiles = Storage.loadProfiles();
var all = Object.keys(profiles).map(function (id) { return profiles[id]; })
.sort(function (a, b) { return (b.lastPlayedAt || 0) - (a.lastPlayedAt || 0) || (b.createdAt || 0) - (a.createdAt || 0); });
var templatesEl = document.getElementById('profile-list-templates');
templatesEl.innerHTML = '';
all.forEach(function (profile) { templatesEl.appendChild(buildProfileRow(profile)); });
document.getElementById('heading-templates').classList.toggle('hidden', all.length === 0);
templatesEl.classList.toggle('hidden', all.length === 0);
var activeGame = Storage.loadActiveGame();
var history = Storage.loadHistory();
var recentEl = document.getElementById('profile-list-recent');
recentEl.innerHTML = '';
if (activeGame) recentEl.appendChild(buildActiveGameRow(activeGame));
history.forEach(function (entry) { recentEl.appendChild(buildHistoryRow(entry)); });
var hasRecent = !!activeGame || history.length > 0;
document.getElementById('heading-recent').classList.toggle('hidden', !hasRecent);
recentEl.classList.toggle('hidden', !hasRecent);
document.getElementById('empty-state').classList.toggle('hidden', all.length > 0);
}
document.getElementById('btn-new-profile').addEventListener('click', openSetupNew);
document.getElementById('btn-create-first').addEventListener('click', openSetupNew);
// ---- CONFIRM START SHEET -------------------------------------------------
function openConfirmStart(profileId) {
var profiles = Storage.loadProfiles();
var profile = profiles[profileId];
if (!profile) return;
pendingStartProfileId = profileId;
document.getElementById('confirm-profile-name').textContent = profile.name || 'Untitled timer';
document.getElementById('confirm-meta').textContent = MODE_LABEL[profile.mode] || profile.mode;
document.getElementById('input-game-name').value =
(profile.name || 'Untitled timer') + ': ' + formatDateShort(Date.now());
var rosterEl = document.getElementById('confirm-roster');
rosterEl.innerHTML = '';
profile.order.forEach(function (id) {
var p = profile.players.filter(function (pl) { return pl.id === id; })[0];
if (!p) return;
var li = document.createElement('li');
li.className = 'roster-row';
var dot = document.createElement('span');
dot.className = 'color-dot';
dot.style.background = colorVar(p.color);
li.appendChild(dot);
var rosterText = p.name + ' — ' + formatDuration(p.budgetMs);
if (profile.mode === 'total_increment') rosterText += ' +' + formatDuration(p.incrementMs || 0) + '/turn';
li.appendChild(document.createTextNode(rosterText));
rosterEl.appendChild(li);
});
document.getElementById('sheet-confirm-start').classList.remove('hidden');
}
function closeConfirmStart() { document.getElementById('sheet-confirm-start').classList.add('hidden'); }
document.getElementById('btn-confirm-cancel').addEventListener('click', closeConfirmStart);
document.querySelector('[data-close="confirm-start"]').addEventListener('click', closeConfirmStart);
document.getElementById('btn-confirm-start').addEventListener('click', function () {
var profiles = Storage.loadProfiles();
var profile = profiles[pendingStartProfileId];
if (!profile) return;
if (Storage.loadActiveGame() &&
!confirm('Starting this game will replace your current in-progress game. Press OK to continue.')) return;
currentGame = Engine.createGameState(profile);
var gameName = document.getElementById('input-game-name').value.trim();
currentGame.profileName = gameName || profile.name || 'Untitled timer';
soundOn = currentGame.alertsEnabled;
profile.lastPlayedAt = Date.now();
Storage.saveProfile(profile);
Storage.setLastProfileId(profile.id);
Storage.saveActiveGame(currentGame);
AudioFx.unlock();
closeConfirmStart();
showScreenRaw('play');
enterPlayScreen();
});
// ---- SETUP ---------------------------------------------------------------
function defaultBudgetMsForMode(mode) {
return mode === 'per_turn' ? 10000 : formatMinSec(10, 0);
}
function makeDefaultSetup() {
var defMs = formatMinSec(10, 0);
return {
id: null,
name: '',
mode: 'total',
incrementMs: 30000,
warningMs: 10000,
warningTouched: false,
warningLinked: true,
alertsEnabled: true,
defaultMs: defMs,
defaultMsTouched: false,
players: [
{ id: Engine.uid(), name: 'Player 1', color: 'red', budgetMs: defMs, incrementMs: 30000 },
{ id: Engine.uid(), name: 'Player 2', color: 'blue', budgetMs: defMs, incrementMs: 30000 }
]
};
}
function openSetupNew() {
editingProfileId = null;
setupState = makeDefaultSetup();
document.getElementById('setup-title').textContent = 'New timer';
document.getElementById('setup-existing-actions').hidden = true;
fillSetupForm();
showScreenRaw('setup');
}
function openSetupEdit(profileId) {
var profiles = Storage.loadProfiles();
var profile = profiles[profileId];
if (!profile) return;
editingProfileId = profileId;
var editDefaultMs = (profile.players[0] && profile.players[0].budgetMs) || formatMinSec(10, 0);
var editWarningMs = profile.warningMs != null ? profile.warningMs : Engine.defaultWarningMs(profile.mode, editDefaultMs);
setupState = {
id: profile.id,
name: profile.name,
mode: profile.mode,
incrementMs: profile.incrementMs || 30000,