-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimer-template.html
More file actions
843 lines (796 loc) · 25.8 KB
/
Copy pathtimer-template.html
File metadata and controls
843 lines (796 loc) · 25.8 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>__LABEL__</title>
<style>
:root {
--bg: __BG__;
--fg: #e2e8f0;
--muted: #94a3b8;
--accent: __ACCENT__;
--warn: __WARN__;
--break: __BREAK__;
--done: __DONE__;
--surface-bg: rgba(255, 255, 255, 0.06);
--surface-border: rgba(255, 255, 255, 0.12);
--done-bg: #0a0a0a;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
height: 100%;
background: var(--bg);
color: var(--fg);
font-family: __FONT__, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
transition: background 600ms ease, color 600ms ease;
}
body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 1.5rem;
padding: 2rem;
text-align: center;
user-select: none;
}
.goal {
font-size: clamp(0.9rem, 1.6vw, 1.2rem);
text-transform: uppercase;
letter-spacing: 0.2em;
color: var(--muted);
max-width: 80vw;
word-break: break-word;
}
.time {
font-size: clamp(5rem, 18vw, 14rem);
font-weight: 200;
font-variant-numeric: tabular-nums;
line-height: 1;
color: var(--accent);
transition: color 600ms ease;
}
.bar-wrap {
width: min(70vw, 720px);
height: 10px;
background: var(--surface-bg);
border-radius: 999px;
overflow: hidden;
}
.bar {
height: 100%;
width: 0%;
background: var(--accent);
border-radius: 999px;
transition: width 1s linear, background 600ms ease;
}
.controls {
display: flex;
gap: 0.75rem;
align-items: center;
}
.ctrl {
background: var(--surface-bg);
color: var(--fg);
border: 1px solid var(--surface-border);
border-radius: 999px;
width: 3rem;
height: 3rem;
font-size: 1.2rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: background 200ms ease, transform 100ms ease, color 400ms ease, border-color 400ms ease;
}
.ctrl:hover { background: var(--surface-border); }
.ctrl:active { transform: scale(0.95); }
.ctrl.primary {
width: 3.5rem;
height: 3.5rem;
font-size: 1.4rem;
background: var(--accent);
color: var(--bg);
border-color: transparent;
}
.ctrl.primary:hover { filter: brightness(1.1); }
.meta {
display: flex;
gap: 1.5rem;
color: var(--muted);
font-size: clamp(0.85rem, 1.4vw, 1.05rem);
}
.meta span strong { color: var(--fg); font-weight: 500; }
.gear {
position: fixed;
top: 1rem;
right: 1rem;
width: 2.25rem;
height: 2.25rem;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 50%;
color: var(--fg);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 1rem;
transition: background 200ms ease, transform 400ms ease, color 400ms ease, border-color 400ms ease;
}
.gear:hover { background: var(--surface-border); transform: rotate(60deg); }
.panel {
position: fixed;
top: 0;
right: 0;
height: 100%;
width: min(360px, 90vw);
background: var(--bg);
border-left: 1px solid var(--surface-border);
padding: 4rem 1.5rem 1.5rem;
overflow-y: auto;
transform: translateX(100%);
transition: transform 300ms ease, background 600ms ease;
z-index: 10;
text-align: left;
box-shadow: -10px 0 30px rgba(0, 0, 0, 0.18);
}
.panel.open { transform: translateX(0); }
.panel-close {
position: absolute;
top: 1rem;
right: 1rem;
width: 2rem;
height: 2rem;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 50%;
color: var(--fg);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.95rem;
line-height: 1;
transition: background 200ms ease, transform 150ms ease, color 400ms ease, border-color 400ms ease;
}
.panel-close:hover { background: var(--surface-border); transform: scale(1.05); }
.panel-close:active { transform: scale(0.95); }
.panel h2 {
font-size: 1rem;
font-weight: 500;
margin-bottom: 0.4rem;
color: var(--fg);
}
.panel p.lede {
font-size: 0.8rem;
color: var(--muted);
margin-bottom: 1rem;
}
.panel h3 {
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.16em;
color: var(--muted);
margin: 1.25rem 0 0.5rem;
font-weight: 500;
}
.presets {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.preset {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.55rem 0.75rem;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
border-radius: 8px;
cursor: pointer;
transition: background 200ms ease, transform 100ms ease, border-color 200ms ease;
}
.preset:hover { background: var(--surface-border); }
.preset:active { transform: scale(0.98); }
.preset-name {
font-size: 0.85rem;
color: var(--fg);
}
.preset-swatches {
display: flex;
gap: 4px;
}
.preset-swatches span {
width: 14px;
height: 14px;
border-radius: 50%;
border: 1px solid var(--surface-border);
display: inline-block;
}
.color-row {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 0.5rem;
}
.color-row label {
flex: 0 0 5.5rem;
font-size: 0.85rem;
color: var(--muted);
text-transform: capitalize;
}
.color-row input[type="color"] {
width: 2rem;
height: 2rem;
border: 1px solid var(--surface-border);
border-radius: 6px;
background: transparent;
cursor: pointer;
padding: 0;
}
.color-row input[type="text"] {
flex: 1;
background: var(--surface-bg);
border: 1px solid var(--surface-border);
color: var(--fg);
padding: 0.45rem 0.6rem;
border-radius: 6px;
font-family: ui-monospace, "SF Mono", Menlo, monospace;
font-size: 0.85rem;
}
.panel-actions {
display: flex;
gap: 0.5rem;
margin-top: 1.5rem;
}
.panel-actions button {
flex: 1;
background: var(--surface-bg);
color: var(--fg);
border: 1px solid var(--surface-border);
padding: 0.6rem;
border-radius: 8px;
font-size: 0.85rem;
cursor: pointer;
transition: filter 150ms ease;
}
.panel-actions button.primary {
background: var(--accent);
color: var(--bg);
border-color: transparent;
font-weight: 500;
}
.panel-actions button:hover { filter: brightness(1.15); }
.panel-msg {
margin-top: 0.75rem;
font-size: 0.8rem;
color: var(--muted);
min-height: 1rem;
}
body.warn { background: color-mix(in srgb, var(--warn) 18%, var(--bg)); }
body.warn .time { color: var(--warn); }
body.warn .bar { background: var(--warn); }
body.warn .ctrl.primary { background: var(--warn); }
body.break { background: color-mix(in srgb, var(--break) 14%, var(--bg)); }
body.break .time { color: var(--break); }
body.break .bar { background: var(--break); }
body.break .ctrl.primary { background: var(--break); }
body.done { background: var(--done-bg); }
body.done .time { font-size: clamp(2rem, 5vw, 4rem); color: var(--done); }
body.done .bar-wrap, body.done .controls { display: none; }
.pulse { animation: pulse 4s ease-in-out infinite; }
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.88; }
}
</style>
<script>
// Pre-paint luminance derivation: keeps light themes from flashing dark.
(function() {
var bg = "__BG__";
function hexToRgb(h) {
h = h.replace("#", "");
if (h.length === 3) h = h.split("").map(c => c + c).join("");
var n = parseInt(h, 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function luminance(hex) {
try {
var rgb = hexToRgb(hex).map(function(v) {
v = v / 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
} catch (e) { return 0; }
}
var isLight = luminance(bg) > 0.55;
var r = document.documentElement;
if (isLight) {
r.style.setProperty("--fg", "#2a1f15");
r.style.setProperty("--muted", "rgba(40, 30, 20, 0.55)");
r.style.setProperty("--surface-bg", "rgba(40, 30, 20, 0.06)");
r.style.setProperty("--surface-border", "rgba(40, 30, 20, 0.14)");
r.style.setProperty("--done-bg", "#231a14");
} else {
r.style.setProperty("--fg", "#e2e8f0");
r.style.setProperty("--muted", "#94a3b8");
r.style.setProperty("--surface-bg", "rgba(255, 255, 255, 0.06)");
r.style.setProperty("--surface-border", "rgba(255, 255, 255, 0.12)");
r.style.setProperty("--done-bg", "#0a0a0a");
}
})();
</script>
</head>
<body class="pulse">
<button class="gear" id="gear" title="Theme settings">⚙</button>
<div class="goal" id="goal">__GOAL__</div>
<div class="time" id="time">--:--</div>
<div class="bar-wrap"><div class="bar" id="bar"></div></div>
<div class="controls">
<button class="ctrl" id="rewindBtn" title="Rewind">⏮</button>
<button class="ctrl primary" id="pauseBtn" title="Pause / Resume">⏸</button>
<button class="ctrl" id="skipBtn" title="Skip to end">⏭</button>
</div>
<div class="meta">
<span><strong id="label">__LABEL__</strong></span>
<span>Started <strong id="start">__START_HHMM__</strong></span>
</div>
<aside class="panel" id="panel">
<button class="panel-close" id="panelClose" title="Close (Esc)" aria-label="Close theme settings">✕</button>
<h2>Theme</h2>
<p class="lede">Pick a vibe, or tweak your own. "Save as default" writes it back to your config.</p>
<h3>Presets</h3>
<div class="presets" id="presets"></div>
<h3>Colors</h3>
<div id="colorRows"></div>
<div class="panel-actions">
<button id="saveBtn" class="primary">Save as default</button>
<button id="resetBtn">Reset</button>
</div>
<div class="panel-msg" id="panelMsg"></div>
</aside>
<script>
const START_TS = __START_TS__;
const INITIAL_END_TS = __END_TS__;
const MODE = "__MODE__";
const LABEL = "__LABEL__";
const REWIND_SECONDS = __REWIND_SECONDS__;
const TEMPLATE_THEME = {
accent: "__ACCENT__",
background: "__BG__",
warn: "__WARN__",
break: "__BREAK__",
done: "__DONE__"
};
const SAVE_URL = "__SAVE_URL__";
const PRESETS = [
{
name: "Dark Academia",
theme: { accent: "#8b2e3b", background: "#1c1410", warn: "#c9933b", break: "#6b7e5c", done: "#a8895d" }
},
{
name: "Light Academia",
theme: { accent: "#5c3a1e", background: "#efe4ce", warn: "#b07d2f", break: "#8e9b81", done: "#a47358" }
},
{
name: "Forest Cottagecore",
theme: { accent: "#6b8e5a", background: "#1a201a", warn: "#c98a3f", break: "#a8b89f", done: "#a86b4f" }
},
{
name: "Candlelit Nocturne",
theme: { accent: "#d4a755", background: "#0c1424", warn: "#cc6633", break: "#6a89a8", done: "#b8a888" }
},
{
name: "Linen & Latte",
theme: { accent: "#4a2e1f", background: "#ede2cf", warn: "#c47b3d", break: "#9aa490", done: "#b08374" }
}
];
// ---- state machine ----
const state = {
mode: MODE,
endTs: INITIAL_END_TS,
pausedRemainingMs: null,
isPaused: false,
isComplete: false,
userTookControl: false,
chimeFired: { halfway: false, lastminute: false, complete: false }
};
const timeEl = document.getElementById("time");
const barEl = document.getElementById("bar");
const body = document.body;
const rewindBtn = document.getElementById("rewindBtn");
const pauseBtn = document.getElementById("pauseBtn");
const skipBtn = document.getElementById("skipBtn");
if (MODE === "break") body.classList.add("break");
function pad(n) { return n < 10 ? "0" + n : "" + n; }
function remaining() {
if (state.isPaused) return state.pausedRemainingMs;
return Math.max(0, state.endTs - Date.now());
}
function totalMs() { return INITIAL_END_TS - START_TS; }
function render() {
const rem = remaining();
const tot = totalMs();
const elapsed = tot - rem;
const pct = Math.min(100, Math.max(0, (elapsed / tot) * 100));
const mins = Math.floor(rem / 60000);
const secs = Math.floor((rem % 60000) / 1000);
const display = pad(mins) + ":" + pad(secs);
timeEl.textContent = display;
barEl.style.width = pct + "%";
document.title = (state.isPaused ? "(paused) " : "") + display + " • " + LABEL;
if (state.mode === "focus" && !state.chimeFired.halfway && elapsed >= tot / 2 && rem > 0) {
state.chimeFired.halfway = true;
playChime("halfway");
}
if (state.mode === "focus" && rem <= 60000 && rem > 0) {
body.classList.add("warn");
if (!state.chimeFired.lastminute) {
state.chimeFired.lastminute = true;
playChime("lastminute");
}
} else if (rem > 60000) {
body.classList.remove("warn");
}
if (rem <= 0 && !state.isComplete) {
triggerComplete();
}
}
function triggerComplete() {
state.isComplete = true;
state.isPaused = false;
stopTicking();
body.className = "done";
timeEl.textContent = state.mode === "focus" ? "Block complete." : "Break complete.";
document.title = "Done • " + LABEL;
if (!state.chimeFired.complete) {
state.chimeFired.complete = true;
playChime("complete");
}
}
// ---- chime ----
let audioCtx = null;
function playChime(kind) {
try {
const Ctx = window.AudioContext || window.webkitAudioContext;
if (!Ctx) return;
if (!audioCtx) audioCtx = new Ctx();
if (audioCtx.state === "suspended") audioCtx.resume();
const now = audioCtx.currentTime;
const notes = ({
halfway: [523.25, 659.25],
lastminute: [659.25, 783.99],
complete: [523.25, 659.25, 783.99]
})[kind] || [523.25];
notes.forEach((freq, i) => {
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.type = "sine";
osc.frequency.value = freq;
osc.connect(gain);
gain.connect(audioCtx.destination);
const start = now + i * 0.16;
const dur = 0.5;
gain.gain.setValueAtTime(0, start);
gain.gain.linearRampToValueAtTime(0.18, start + 0.03);
gain.gain.exponentialRampToValueAtTime(0.001, start + dur);
osc.start(start);
osc.stop(start + dur);
});
} catch (e) {}
}
// ---- ticking ----
let tickId = null;
function startTicking() {
if (tickId) return;
tickId = setInterval(render, 1000);
}
function stopTicking() {
if (tickId) { clearInterval(tickId); tickId = null; }
}
// ---- controls ----
function togglePause() {
if (state.isComplete) return;
if (state.isPaused) {
state.endTs = Date.now() + state.pausedRemainingMs;
state.isPaused = false;
state.pausedRemainingMs = null;
pauseBtn.textContent = "⏸";
startTicking();
} else {
state.pausedRemainingMs = Math.max(0, state.endTs - Date.now());
state.isPaused = true;
pauseBtn.textContent = "▶";
stopTicking();
}
state.userTookControl = true;
render();
}
function rewind() {
if (state.isComplete) return;
const ms = REWIND_SECONDS * 1000;
if (state.isPaused) state.pausedRemainingMs += ms;
else state.endTs += ms;
state.userTookControl = true;
render();
}
function skip() {
if (state.isComplete) return;
state.endTs = Date.now();
state.pausedRemainingMs = 0;
state.userTookControl = true;
triggerComplete();
}
rewindBtn.addEventListener("click", rewind);
pauseBtn.addEventListener("click", togglePause);
skipBtn.addEventListener("click", skip);
document.addEventListener("keydown", (e) => {
if (e.code === "Escape") {
const panel = document.getElementById("panel");
if (panel && panel.classList.contains("open")) {
panel.classList.remove("open");
e.preventDefault();
return;
}
}
if (e.target.tagName === "INPUT") return;
if (e.code === "Space") { e.preventDefault(); togglePause(); }
else if (e.code === "ArrowLeft") { rewind(); }
else if (e.code === "ArrowRight") { skip(); }
});
// ---- theme ----
const COLOR_KEYS = ["accent", "background", "warn", "break", "done"];
const VAR_MAP = { accent: "--accent", background: "--bg", warn: "--warn", break: "--break", done: "--done" };
const LS_KEY = "loft-hours-theme";
function hexToRgb(h) {
h = h.replace("#", "");
if (h.length === 3) h = h.split("").map(c => c + c).join("");
const n = parseInt(h, 16);
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
}
function relativeLuminance(hex) {
try {
const rgb = hexToRgb(hex).map(v => {
v = v / 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
} catch (e) { return 0; }
}
function setLuminanceVars(bgHex) {
const r = document.documentElement;
const isLight = relativeLuminance(bgHex) > 0.55;
if (isLight) {
r.style.setProperty("--fg", "#2a1f15");
r.style.setProperty("--muted", "rgba(40, 30, 20, 0.55)");
r.style.setProperty("--surface-bg", "rgba(40, 30, 20, 0.06)");
r.style.setProperty("--surface-border", "rgba(40, 30, 20, 0.14)");
r.style.setProperty("--done-bg", "#231a14");
} else {
r.style.setProperty("--fg", "#e2e8f0");
r.style.setProperty("--muted", "#94a3b8");
r.style.setProperty("--surface-bg", "rgba(255, 255, 255, 0.06)");
r.style.setProperty("--surface-border", "rgba(255, 255, 255, 0.12)");
r.style.setProperty("--done-bg", "#0a0a0a");
}
}
function loadTheme() {
try {
const saved = localStorage.getItem(LS_KEY);
if (saved) return Object.assign({}, TEMPLATE_THEME, JSON.parse(saved));
} catch (e) {}
return Object.assign({}, TEMPLATE_THEME);
}
function applyTheme(theme) {
COLOR_KEYS.forEach(k => {
document.documentElement.style.setProperty(VAR_MAP[k], theme[k]);
});
setLuminanceVars(theme.background);
}
function persistTheme(theme) {
try { localStorage.setItem(LS_KEY, JSON.stringify(theme)); } catch (e) {}
}
function refreshPickerInputs() {
document.querySelectorAll("#colorRows input").forEach(inp => {
inp.value = currentTheme[inp.dataset.key];
});
}
function applyPreset(theme) {
COLOR_KEYS.forEach(k => { currentTheme[k] = theme[k]; });
applyTheme(currentTheme);
persistTheme(currentTheme);
refreshPickerInputs();
}
const currentTheme = loadTheme();
applyTheme(currentTheme);
// ---- preset pills ----
const presetsEl = document.getElementById("presets");
PRESETS.forEach((p, idx) => {
const pill = document.createElement("div");
pill.className = "preset";
pill.dataset.idx = idx;
const swatches = COLOR_KEYS.map(k =>
`<span style="background:${p.theme[k]}"></span>`
).join("");
pill.innerHTML =
`<span class="preset-name">${p.name}</span>` +
`<div class="preset-swatches">${swatches}</div>`;
pill.addEventListener("click", () => applyPreset(p.theme));
presetsEl.appendChild(pill);
});
// ---- color picker rows ----
const colorRowsEl = document.getElementById("colorRows");
COLOR_KEYS.forEach(k => {
const row = document.createElement("div");
row.className = "color-row";
row.innerHTML =
`<label>${k}</label>` +
`<input type="color" data-key="${k}" value="${currentTheme[k]}" />` +
`<input type="text" data-key="${k}" value="${currentTheme[k]}" maxlength="7" />`;
colorRowsEl.appendChild(row);
});
function isValidHex(s) { return /^#[0-9a-fA-F]{6}$/.test(s); }
colorRowsEl.addEventListener("input", (e) => {
const key = e.target.dataset.key;
if (!key) return;
let val = e.target.value;
if (e.target.type === "text" && !isValidHex(val)) return;
currentTheme[key] = val;
const siblings = colorRowsEl.querySelectorAll(`[data-key="${key}"]`);
siblings.forEach(s => { if (s !== e.target) s.value = val; });
applyTheme(currentTheme);
persistTheme(currentTheme);
});
// ---- save / reset ----
const saveBtn = document.getElementById("saveBtn");
const resetBtn = document.getElementById("resetBtn");
const panelMsg = document.getElementById("panelMsg");
// ---- persisted config.json handle (so future saves are silent) ----
const IDB_NAME = "loft-hours-db";
const IDB_STORE = "handles";
const IDB_KEY = "config-handle";
function idbOpen() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(IDB_NAME, 1);
req.onupgradeneeded = () => req.result.createObjectStore(IDB_STORE);
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function idbGet(key) {
const db = await idbOpen();
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_STORE, "readonly");
const r = tx.objectStore(IDB_STORE).get(key);
r.onsuccess = () => resolve(r.result);
r.onerror = () => reject(r.error);
});
}
async function idbSet(key, val) {
const db = await idbOpen();
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_STORE, "readwrite");
tx.objectStore(IDB_STORE).put(val, key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function idbDel(key) {
const db = await idbOpen();
return new Promise((resolve, reject) => {
const tx = db.transaction(IDB_STORE, "readwrite");
tx.objectStore(IDB_STORE).delete(key);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function ensureRW(handle) {
if (!handle || !handle.queryPermission) return false;
const opts = { mode: "readwrite" };
if ((await handle.queryPermission(opts)) === "granted") return true;
return (await handle.requestPermission(opts)) === "granted";
}
async function writeThemeToHandle(handle) {
const file = await handle.getFile();
const text = await file.text();
const cfg = JSON.parse(text);
cfg.timer_ui = cfg.timer_ui || {};
cfg.timer_ui.theme = Object.assign({}, currentTheme);
const writable = await handle.createWritable();
await writable.write(JSON.stringify(cfg, null, 2) + "\n");
await writable.close();
}
async function saveToConfig() {
panelMsg.textContent = "Saving...";
// 1. Silent path: POST to the local save server started by render-timer.sh.
// Bound to 127.0.0.1, per-session token, writes config.json directly.
if (SAVE_URL && !SAVE_URL.startsWith("__")) {
try {
const res = await fetch(SAVE_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(currentTheme)
});
if (res.ok) {
panelMsg.textContent = "Saved.";
return;
}
const err = await res.json().catch(() => ({}));
panelMsg.textContent = "Save server rejected: " + (err.error || res.status);
return;
} catch (e) {
// Server unreachable (died, port closed, PNA blocked, etc). Fall through.
console.warn("save server fetch failed:", e);
panelMsg.textContent = "Save server unreachable (" + (e.message || e) + "), trying file picker...";
}
}
// 2. Legacy fallback: File System Access API with persisted handle.
let handle = null;
try { handle = await idbGet(IDB_KEY); } catch (e) {}
if (handle) {
try {
if (await ensureRW(handle)) {
await writeThemeToHandle(handle);
panelMsg.textContent = "Saved.";
return;
}
} catch (err) {
try { await idbDel(IDB_KEY); } catch (e) {}
handle = null;
}
}
if (window.showOpenFilePicker) {
try {
const [picked] = await window.showOpenFilePicker({
types: [{ description: "JSON", accept: { "application/json": [".json"] } }]
});
if (!(await ensureRW(picked))) {
panelMsg.textContent = "Permission denied. Save cancelled.";
return;
}
await writeThemeToHandle(picked);
try { await idbSet(IDB_KEY, picked); } catch (e) {}
panelMsg.textContent = "Saved.";
return;
} catch (err) {
if (err && err.name === "AbortError") { panelMsg.textContent = "Save cancelled."; return; }
panelMsg.textContent = "FS access failed, downloading theme.json instead.";
}
}
// 3. Last-resort: download the theme JSON.
const blob = new Blob([JSON.stringify({ timer_ui: { theme: currentTheme } }, null, 2)],
{ type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url; a.download = "theme.json"; a.click();
URL.revokeObjectURL(url);
panelMsg.textContent = "Downloaded theme.json. Merge timer_ui.theme into your config.";
}
function resetTheme() {
Object.assign(currentTheme, TEMPLATE_THEME);
applyTheme(currentTheme);
persistTheme(currentTheme);
refreshPickerInputs();
panelMsg.textContent = "Reset to current defaults.";
}
saveBtn.addEventListener("click", saveToConfig);
resetBtn.addEventListener("click", resetTheme);
// gear / close toggle
const panelEl = document.getElementById("panel");
document.getElementById("gear").addEventListener("click", () => {
panelEl.classList.toggle("open");
});
document.getElementById("panelClose").addEventListener("click", () => {
panelEl.classList.remove("open");
});
// ---- boot ----
render();
startTicking();
document.addEventListener("visibilitychange", () => {
if (!document.hidden && !state.isPaused && !state.isComplete) render();
});
</script>
</body>
</html>