-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1212 lines (1009 loc) · 38.9 KB
/
script.js
File metadata and controls
1212 lines (1009 loc) · 38.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
// ===== DOM Elements =====
const countdownEl = document.getElementById("countdown");
const hourInput = document.getElementById("hourInput");
const minuteInput = document.getElementById("minuteInput");
const startBtn = document.getElementById("startBtn");
const stopBtn = document.getElementById("stopBtn");
const alarmSound = document.getElementById("alarmSound");
const titleEl = document.getElementById("title");
const timeLine = document.getElementById("timeLine");
const dateLine = document.getElementById("dateLine");
const fullscreenBtn = document.getElementById("fullscreenBtn");
const quickBtnContainer = document.getElementById("quickBtnContainer");
const quickAddContainer = document.getElementById("quickAddContainer");
const quickTweakContainer = document.getElementById("quickTweakContainer");
const nowBtn = document.getElementById("nowBtn");
const tweakRow1 = document.getElementById("tweakRow1");
const tweakRow2 = document.getElementById("tweakRow2");
const countdownPreview = document.getElementById("countdownPreview");
const timerSelect = document.getElementById("timerSelect");
const addTimerBtn = document.getElementById("addTimerBtn");
const renameTimerBtn = document.getElementById("renameTimerBtn");
const additionalTimers = document.getElementById("additionalTimers");
const bottomRight = document.querySelector(".bottom-right");
const bottomLeft = document.querySelector(".bottom-left");
// ===== Constants =====
const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const increments = [2, 5, 10, 20, 30, 60, 120];
const tweakRow1Mins = [-5, -2, -1, 1, 2, 5];
const tweakRow2Mins = [-60, -30, -10, 10, 30, 60];
// ===== Local Storage Keys =====
const STORAGE_KEYS = {
TIMERS: 'countdown_timers',
TIMER_ORDER: 'countdown_timer_order',
CURRENT_TIMER: 'countdown_current_timer'
};
// ===== Local Storage Functions =====
function saveTimersToStorage() {
try {
// Save timers data
const timersData = {};
Object.keys(timers).forEach(timerId => {
const timer = timers[timerId];
// Convert Date objects to ISO strings for storage
timersData[timerId] = {
...timer,
target: timer.target ? timer.target.toISOString() : null
};
});
localStorage.setItem(STORAGE_KEYS.TIMERS, JSON.stringify(timersData));
localStorage.setItem(STORAGE_KEYS.TIMER_ORDER, JSON.stringify(timerOrder));
localStorage.setItem(STORAGE_KEYS.CURRENT_TIMER, currentTimerId);
console.log('Timers saved to local storage');
} catch (error) {
console.error('Failed to save timers to local storage:', error);
}
}
function loadTimersFromStorage() {
try {
// Load timers data
const savedTimers = localStorage.getItem(STORAGE_KEYS.TIMERS);
const savedTimerOrder = localStorage.getItem(STORAGE_KEYS.TIMER_ORDER);
const savedCurrentTimer = localStorage.getItem(STORAGE_KEYS.CURRENT_TIMER);
if (savedTimers) {
const timersData = JSON.parse(savedTimers);
// Restore timers with proper Date objects
Object.keys(timersData).forEach(timerId => {
const timerData = timersData[timerId];
timers[timerId] = {
...timerData,
target: timerData.target ? new Date(timerData.target) : null
};
});
// Clean up expired timers
cleanupExpiredTimers();
}
if (savedTimerOrder) {
timerOrder = JSON.parse(savedTimerOrder);
// Filter out any timer IDs that no longer exist
timerOrder = timerOrder.filter(id => timers[id]);
}
if (savedCurrentTimer && timers[savedCurrentTimer]) {
currentTimerId = savedCurrentTimer;
}
console.log('Timers loaded from local storage');
return true;
} catch (error) {
console.error('Failed to load timers from local storage:', error);
return false;
}
}
function cleanupExpiredTimers() {
const now = new Date();
const expiredTimerIds = [];
Object.keys(timers).forEach(timerId => {
const timer = timers[timerId];
if (timer.target && timer.target < now && timer.isRunning) {
// Timer has expired, mark it as stopped
timer.isRunning = false;
timer.remaining = 0;
expiredTimerIds.push(timerId);
}
});
if (expiredTimerIds.length > 0) {
console.log('Cleaned up expired timers:', expiredTimerIds);
saveTimersToStorage(); // Save the cleaned up state
}
}
function clearAllSavedTimers() {
try {
localStorage.removeItem(STORAGE_KEYS.TIMERS);
localStorage.removeItem(STORAGE_KEYS.TIMER_ORDER);
localStorage.removeItem(STORAGE_KEYS.CURRENT_TIMER);
console.log('All saved timers cleared from local storage');
// Reset to default state
timers = {
main: {
name: "Focus",
target: null,
remaining: 0,
isRunning: false
}
};
currentTimerId = "main";
timerOrder = ["main"];
// Update UI
updateTimerSelect();
updateAdditionalTimersDisplay();
setCurrentTimer("main");
} catch (error) {
console.error('Failed to clear saved timers:', error);
}
}
// ===== State =====
let mainTimer = null;
let wakeLock = null;
let timers = {
main: {
name: "Focus",
target: null,
remaining: 0,
isRunning: false
}
};
let currentTimerId = "main";
let timerOrder = ["main"];
// ===== Page Visibility API Support =====
let isPageVisible = true;
// Check if Page Visibility API is supported
function isPageVisibilitySupported() {
return typeof document.hidden !== "undefined" ||
typeof document.msHidden !== "undefined" ||
typeof document.webkitHidden !== "undefined";
}
// Get current page visibility state
function getPageVisibilityState() {
if (document.hidden !== undefined) return document.hidden;
if (document.msHidden !== undefined) return document.msHidden;
if (document.webkitHidden !== undefined) return document.webkitHidden;
return false;
}
// Handle page visibility changes
function handleVisibilityChange() {
const wasVisible = isPageVisible;
isPageVisible = !getPageVisibilityState();
// If page becomes visible and we have running timers, resync them
if (isPageVisible && !wasVisible) {
console.log("Page became visible, resyncing timers...");
resyncAllTimers();
}
}
// ===== Core Timer Functions =====
// Main timer function that runs every second
function updateAllTimers() {
const now = new Date();
// Update current time display
updateCurrentTimeDisplay(now);
// Update all running timers
Object.keys(timers).forEach(timerId => {
const timer = timers[timerId];
if (timer.isRunning && timer.target) {
updateTimer(timerId, now);
}
});
// Update additional timers display
updateAdditionalTimersDisplay();
}
// Update a specific timer
function updateTimer(timerId, now) {
const timer = timers[timerId];
if (!timer || !timer.target || !timer.isRunning) return;
// Calculate remaining time
const newRemaining = Math.floor((timer.target - now) / 1000);
if (newRemaining <= 0) {
// Timer completed
completeTimer(timerId);
} else {
// Update remaining time
timer.remaining = newRemaining;
// Update main timer display if this is the main timer
if (timerId === "main") {
countdownEl.textContent = formatTime(newRemaining);
updateDocumentTitle();
}
}
}
// Complete a timer
function completeTimer(timerId) {
const timer = timers[timerId];
if (!timer) return;
console.log(`Timer ${timerId} completed: ${timer.name}`);
// Stop the timer
timer.isRunning = false;
timer.remaining = 0;
if (timerId === "main") {
// Main timer completed
countdownEl.textContent = "TIME UP!";
document.body.style.background = "#009";
titleEl.textContent = "Countdown Timer";
updateDocumentTitle();
releaseWakeLock();
}
// Play notification sound for all completed timers
alarmSound.play();
}
// Resync all running timers based on current time
function resyncAllTimers() {
const now = new Date();
Object.keys(timers).forEach(timerId => {
const timer = timers[timerId];
if (timer.isRunning && timer.target) {
updateTimer(timerId, now);
}
});
}
// ===== Utility Functions =====
function showTimerSwitchAnimation() {
// Add a temporary highlight effect to show the switch
const titleEl = document.getElementById("title");
const additionalTimersEl = document.getElementById("additionalTimers");
const originalBackground = titleEl.style.background;
const originalColor = titleEl.style.color;
// Flash effect on title
titleEl.style.background = "#fd0";
titleEl.style.color = "#111";
titleEl.style.padding = "5px 10px";
titleEl.style.borderRadius = "5px";
titleEl.style.transition = "all 0.3s ease";
// Subtle highlight on additional timers
if (additionalTimersEl) {
additionalTimersEl.style.transform = "scale(1.02)";
additionalTimersEl.style.transition = "transform 0.3s ease";
}
setTimeout(() => {
titleEl.style.background = originalBackground;
titleEl.style.color = originalColor;
titleEl.style.padding = "";
titleEl.style.borderRadius = "";
if (additionalTimersEl) {
additionalTimersEl.style.transform = "scale(1)";
}
}, 300);
}
function formatTime(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}
function formatTimeForTitle(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}
function updateDocumentTitle() {
const mainTimer = timers.main;
if (mainTimer && mainTimer.isRunning && mainTimer.remaining > 0) {
document.title = formatTimeForTitle(mainTimer.remaining);
} else {
document.title = "Countdown Timer";
}
}
function updateCurrentTimeDisplay(now) {
const hh = String(now.getHours()).padStart(2, '0');
const mm = String(now.getMinutes()).padStart(2, '0');
const ss = String(now.getSeconds()).padStart(2, '0');
const dateStr = now.toISOString().split('T')[0];
const weekday = weekdays[now.getDay()];
timeLine.textContent = `${hh}:${mm}:${ss}`;
dateLine.textContent = `${dateStr} ${weekday}`;
}
function updateCountdownPreview() {
const h = parseInt(hourInput.value, 10);
const m = parseInt(minuteInput.value, 10);
if (isValidHourMinute(h, m)) {
const target = getTargetTime(h, m);
const now = new Date();
const remainingSeconds = Math.floor((target - now) / 1000);
if (remainingSeconds > 0) {
const hours = Math.floor(remainingSeconds / 3600);
const minutes = Math.ceil((remainingSeconds % 3600) / 60);
let previewText = "";
if (hours > 0) {
previewText += `${hours}h`;
}
if (minutes > 0 || hours === 0) {
previewText += `${minutes}min`;
}
countdownPreview.textContent = previewText.trim();
countdownPreview.style.color = "#fd0";
} else {
countdownPreview.textContent = "0min";
countdownPreview.style.color = "#666";
}
} else {
countdownPreview.textContent = "0min";
countdownPreview.style.color = "#666";
}
}
// ===== Timer Management Functions =====
function addNewTimer() {
const timerName = prompt("Enter timer name:");
if (timerName && timerName.trim()) {
const timerId = `timer_${Date.now()}`;
timers[timerId] = {
name: timerName.trim(),
target: null,
remaining: 0,
isRunning: false
};
timerOrder.push(timerId);
currentTimerId = timerId;
updateTimerSelect();
setCurrentTimer(timerId);
updateAdditionalTimersDisplay();
saveTimersToStorage(); // Save to local storage
}
}
function makeTimerMain(timerId) {
if (timerId === "main") return;
const additionalTimer = timers[timerId];
if (!additionalTimer) return;
// Store the current main timer data
const currentMainTimer = timers.main;
// Swap the timers
timers.main = {
name: additionalTimer.name,
target: additionalTimer.target,
remaining: additionalTimer.remaining,
isRunning: additionalTimer.isRunning
};
// Move the old main timer to additional timers
timers[timerId] = {
name: currentMainTimer.name,
target: currentMainTimer.target,
remaining: currentMainTimer.remaining,
isRunning: currentMainTimer.isRunning
};
// Update the timer order
const mainIndex = timerOrder.indexOf("main");
const additionalIndex = timerOrder.indexOf(timerId);
if (mainIndex !== -1 && additionalIndex !== -1) {
timerOrder[mainIndex] = timerId;
timerOrder[additionalIndex] = "main";
}
// Update current timer selection if needed
if (currentTimerId === timerId) {
currentTimerId = "main";
} else if (currentTimerId === "main") {
currentTimerId = timerId;
}
// Update UI
updateTimerSelect();
updateAdditionalTimersDisplay();
// If the new main timer is running, update the display
if (timers.main.isRunning && timers.main.target) {
const now = new Date();
timers.main.remaining = Math.floor((timers.main.target - now) / 1000);
countdownEl.textContent = formatTime(timers.main.remaining);
titleEl.textContent = `${timers.main.name} - Time until ${timers.main.target.toLocaleTimeString()}`;
updateDocumentTitle();
if (timers.main.isRunning) {
enableWakeLock();
document.body.style.background = "#111";
}
} else {
countdownEl.textContent = "00:00";
titleEl.textContent = "Countdown Timer";
updateDocumentTitle();
document.body.style.background = "#111";
releaseWakeLock();
}
// Update the current timer selection
setCurrentTimer(currentTimerId);
showTimerSwitchAnimation(); // Call the new animation function
saveTimersToStorage(); // Save to local storage
}
function deleteTimer(timerId) {
if (timerId === "main") {
alert("Cannot delete the main timer!");
return;
}
const timer = timers[timerId];
if (!timer) return;
if (timer.isRunning) {
timer.isRunning = false;
}
delete timers[timerId];
const orderIndex = timerOrder.indexOf(timerId);
if (orderIndex > -1) {
timerOrder.splice(orderIndex, 1);
}
if (currentTimerId === timerId) {
currentTimerId = "main";
setCurrentTimer("main");
}
updateTimerSelect();
updateAdditionalTimersDisplay();
saveTimersToStorage(); // Save to local storage
}
function renameCurrentTimer() {
const currentTimer = getCurrentTimer();
if (!currentTimer) return;
const newName = prompt("Enter new timer name:", currentTimer.name);
if (newName && newName.trim()) {
currentTimer.name = newName.trim();
updateTimerSelect();
updateAdditionalTimersDisplay();
updateTimerTitle();
saveTimersToStorage(); // Save to local storage
}
}
function updateTimerTitle() {
const currentTimer = getCurrentTimer();
if (currentTimer && currentTimer.isRunning && currentTimer.target) {
if (currentTimerId === "main") {
titleEl.textContent = `${currentTimer.name} - Time until ${currentTimer.target.toLocaleTimeString()}`;
}
}
}
function updateTimerSelect() {
timerSelect.innerHTML = "";
Object.keys(timers).forEach(timerId => {
const option = document.createElement("option");
option.value = timerId;
option.textContent = timers[timerId].name;
if (timerId === currentTimerId) {
option.selected = true;
}
timerSelect.appendChild(option);
});
}
function updateAdditionalTimersDisplay() {
if (!additionalTimers) return;
additionalTimers.innerHTML = "";
timerOrder.forEach(timerId => {
if (timerId !== "main" && timers[timerId]) {
const timer = timers[timerId];
const timerEl = document.createElement("div");
timerEl.className = "additional-timer";
timerEl.setAttribute("data-timer-id", timerId);
timerEl.draggable = true;
const endTime = timer.target ?
`${String(timer.target.getHours()).padStart(2, '0')}:${String(timer.target.getMinutes()).padStart(2, '0')}` : "";
const displayText = ` | ${formatTime(timer.remaining)}`;
timerEl.innerHTML = `
<span class="timer-name">${timer.name}</span>
<span class="timer-end-time">${endTime}</span>
<span class="timer-remaining">${displayText}</span>
<button class="delete-timer-btn" data-timer-id="${timerId}" title="Delete timer"><i class="fas fa-trash"></i></button>
<button class="make-main-btn" data-timer-id="${timerId}" title="Make Main"><i class="fas fa-crown"></i></button>
`;
const deleteBtn = timerEl.querySelector('.delete-timer-btn');
deleteBtn.addEventListener("click", (e) => {
e.stopPropagation();
deleteTimer(timerId);
});
// Add touch-specific event listeners for better iPad compatibility
deleteBtn.addEventListener("touchstart", (e) => {
e.stopPropagation();
e.preventDefault();
});
deleteBtn.addEventListener("touchend", (e) => {
e.stopPropagation();
e.preventDefault();
deleteTimer(timerId);
});
const makeMainBtn = timerEl.querySelector('.make-main-btn');
makeMainBtn.addEventListener("click", (e) => {
e.stopPropagation();
makeTimerMain(timerId);
});
// Add touch-specific event listeners for better iPad compatibility
makeMainBtn.addEventListener("touchstart", (e) => {
e.stopPropagation();
// Prevent default to avoid double-triggering on some devices
e.preventDefault();
});
makeMainBtn.addEventListener("touchend", (e) => {
e.stopPropagation();
e.preventDefault();
makeTimerMain(timerId);
});
timerEl.addEventListener("dragstart", handleDragStart);
timerEl.addEventListener("dragover", handleDragOver);
timerEl.addEventListener("drop", handleDrop);
timerEl.addEventListener("dragenter", handleDragEnter);
timerEl.addEventListener("dragleave", handleDragLeave);
timerEl.addEventListener("touchstart", handleTouchStart);
timerEl.addEventListener("touchmove", handleTouchMove);
timerEl.addEventListener("touchend", handleTouchEnd);
additionalTimers.appendChild(timerEl);
}
});
}
function getCurrentTimer() {
return timers[currentTimerId];
}
function setCurrentTimer(timerId) {
currentTimerId = timerId;
const timer = getCurrentTimer();
if (timer && timer.target) {
hourInput.value = timer.target.getHours();
minuteInput.value = String(timer.target.getMinutes()).padStart(2, '0');
updateCountdownPreview();
} else {
hourInput.value = "";
minuteInput.value = "";
updateCountdownPreview();
}
saveTimersToStorage(); // Save to local storage
}
// ===== Timer Control Functions =====
function startCountdown() {
const currentTimer = getCurrentTimer();
if (!currentTimer) return;
const target = targetTime();
if (!target) return;
currentTimer.target = target;
currentTimer.isRunning = true;
if (currentTimerId === "main") {
enableWakeLock();
document.body.style.background = "#111";
titleEl.textContent = `${timers.main.name} - Time until ${target.toLocaleTimeString()}`;
const now = new Date();
timers.main.remaining = Math.floor((target - now) / 1000);
countdownEl.textContent = formatTime(timers.main.remaining);
updateDocumentTitle();
}
updateAdditionalTimersDisplay();
saveTimersToStorage(); // Save to local storage
}
function stopCountdown() {
const currentTimer = getCurrentTimer();
if (!currentTimer) return;
if (currentTimerId === "main") {
releaseWakeLock();
countdownEl.textContent = "00:00";
titleEl.textContent = "Countdown Timer";
updateDocumentTitle();
document.body.style.background = "#111";
}
currentTimer.isRunning = false;
currentTimer.target = null;
currentTimer.remaining = 0;
updateAdditionalTimersDisplay();
saveTimersToStorage(); // Save to local storage
}
// ===== Helper Functions =====
function setVH() {
let vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
}
function targetTime() {
const h = parseInt(hourInput.value, 10);
let m = parseInt(minuteInput.value, 10);
if (isNaN(h) || isNaN(m) || !isValidHourMinute(h, m)) {
alert("Please enter a valid hour (0-23) and minute (0-59)!");
return;
}
minuteInput.value = String(m).padStart(2, '0');
return getTargetTime(h, m);
}
async function enableWakeLock() {
try {
// Try the standard wake lock API first
if ("wakeLock" in navigator) {
wakeLock = await navigator.wakeLock.request("screen");
console.log("Screen Wake Lock enabled");
return;
}
// Fallback for devices that don't support wake lock (like iPad)
console.log("Wake Lock API not supported, using fallback methods");
// For iPad and other devices, try to prevent sleep by keeping the page active
if (typeof window !== 'undefined') {
// Keep the page active by periodically updating
if (!window.fallbackWakeLockInterval) {
window.fallbackWakeLockInterval = setInterval(() => {
// This helps prevent some devices from sleeping
if (document.visibilityState === 'visible') {
// Keep the page active
window.focus();
// For iPad, try to keep the screen on by simulating user activity
if (navigator.userAgent.includes('iPad') || navigator.userAgent.includes('Macintosh')) {
// Create a subtle visual update to keep the screen active
const now = new Date();
if (timers.main && timers.main.isRunning) {
// Update the countdown display to keep the screen active
updateDocumentTitle();
}
}
}
}, 15000); // Every 15 seconds for better iPad compatibility
}
// Additional iPad-specific method: request animation frame to keep the screen active
if (navigator.userAgent.includes('iPad') || navigator.userAgent.includes('Macintosh')) {
if (!window.fallbackAnimationFrame) {
const keepAlive = () => {
if (timers.main && timers.main.isRunning) {
// Keep requesting animation frames to prevent sleep
window.fallbackAnimationFrame = requestAnimationFrame(keepAlive);
}
};
keepAlive();
}
}
}
} catch (err) {
console.error("Wake Lock failed:", err);
// Fallback for devices that don't support wake lock
console.log("Using fallback wake lock methods");
if (typeof window !== 'undefined') {
if (!window.fallbackWakeLockInterval) {
window.fallbackWakeLockInterval = setInterval(() => {
if (document.visibilityState === 'visible') {
window.focus();
}
}, 15000);
}
}
}
}
function releaseWakeLock() {
if (wakeLock !== null) {
wakeLock.release();
wakeLock = null;
console.log("Screen Wake Lock released");
}
// Clear fallback wake lock interval if it exists
if (window.fallbackWakeLockInterval) {
clearInterval(window.fallbackWakeLockInterval);
window.fallbackWakeLockInterval = null;
console.log("Fallback wake lock cleared");
}
}
function isValidHourMinute(h, m) {
return (
Number.isInteger(h) &&
Number.isInteger(m) &&
h >= 0 && h <= 23 &&
m >= 0 && m <= 59
);
}
function isValidTarget(h, m) {
return getTargetTime(h, m) > new Date();
}
function getTargetTime(h, m) {
const target = new Date();
target.setHours(h);
target.setMinutes(m);
target.setSeconds(0);
return target;
}
// ===== Quick Button Functions =====
function setupShortcutButtons() {
const morning = [[9, 0], [9, 30], [10, 0], [10, 30], [11, 0], [11, 30], [12, 0], [12, 30]];
const afternoon = [[13, 0], [13, 30], [14, 0], [14, 30], [15, 0], [15, 30], [16, 0], [16, 30], [17, 0], [17, 30], [18, 0]];
const night = [[19, 0], [20, 0], [21, 0], [22, 0]];
function createHourRow(arr) {
const row = document.createElement("div");
row.className = "quick-hour-row";
const now = new Date();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();
arr.forEach(([h, min]) => {
const btn = document.createElement("button");
btn.textContent = `${String(h).padStart(2, '0')}:${min === 0 ? '00' : '30'}`;
const isPastTime = (h < currentHour) || (h === currentHour && min <= currentMinute);
if (isPastTime) {
btn.disabled = true;
btn.style.opacity = "0.4";
btn.style.cursor = "not-allowed";
btn.title = "Time has passed";
} else {
btn.addEventListener("click", () => {
hourInput.value = h;
minuteInput.value = String(min).padStart(2, '0');
updateCountdownPreview();
startCountdown();
});
}
row.appendChild(btn);
});
return row;
}
quickBtnContainer.innerHTML = "";
quickBtnContainer.appendChild(createHourRow(morning));
quickBtnContainer.appendChild(createHourRow(afternoon));
quickBtnContainer.appendChild(createHourRow(night));
increments.forEach(min => {
const btn = document.createElement("button");
btn.textContent = min < 60 ? `${min}min` : `${min / 60}h`;
btn.addEventListener("click", () => {
const now = new Date();
const target = new Date(now.getTime() + min * 60000);
hourInput.value = target.getHours();
minuteInput.value = String(target.getMinutes()).padStart(2, '0');
updateCountdownPreview();
startCountdown();
});
quickAddContainer.appendChild(btn);
});
[...tweakRow1Mins].forEach(min => { createTweakButton(min, tweakRow1) });
[...tweakRow2Mins].forEach(min => { createTweakButton(min, tweakRow2) });
}
function createTweakButton(min, tweakRow) {
const tweakBtn = document.createElement("button");
tweakBtn.textContent = min < 0 ? `${min}min` : `+${min}min`;
tweakBtn.addEventListener("click", () => {
adjustInputTimeBy(min);
});
tweakRow.appendChild(tweakBtn);
}
function adjustInputTimeBy(min) {
let h = parseInt(hourInput.value, 10);
let m = parseInt(minuteInput.value, 10);
if (!isValidHourMinute(h, m)) {
const now = new Date();
h = now.getHours();
m = now.getMinutes();
}
let total = h * 60 + m + min;
if (total < 0) total = 0;
h = Math.floor(total / 60);
m = total % 60;
hourInput.value = h;
minuteInput.value = String(m).padStart(2, '0');
updateCountdownPreview();
if (isValidHourMinute(h, m) && isValidTarget(h, m)) {
startCountdown();
} else {
stopCountdown();
}
}
function updateQuickButtons() {
const now = new Date();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();
const timeButtons = quickBtnContainer.querySelectorAll('button');
timeButtons.forEach(btn => {
const timeText = btn.textContent;
const [hourStr, minuteStr] = timeText.split(':');
const h = parseInt(hourStr, 10);
const min = parseInt(minuteStr, 10);
if (!isNaN(h) && !isNaN(min)) {
const isPastTime = (h < currentHour) || (h === currentHour && min <= currentMinute);
if (isPastTime) {
btn.disabled = true;
btn.style.opacity = "0.4";
btn.style.cursor = "not-allowed";
btn.title = "Time has passed";
} else {
btn.disabled = false;
btn.style.opacity = "1";
btn.style.cursor = "pointer";
btn.title = "";
}
}
});
}
// ===== Event Listeners =====
function setupEventListeners() {
startBtn.addEventListener("click", startCountdown);
stopBtn.addEventListener("click", stopCountdown);
fullscreenBtn.addEventListener("click", () => {
if (isStandaloneMode()) {
location.reload();
return;
}
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen();
} else {
document.exitFullscreen();
}
});
document.addEventListener("fullscreenchange", () => {
if (!isStandaloneMode()) {
fullscreenBtn.innerHTML = document.fullscreenElement ? '<i class="fas fa-times"></i>' : '<i class="fas fa-expand"></i>';
}
});
window.addEventListener('resize', setVH);
nowBtn.addEventListener("click", () => {
const target = new Date();
hourInput.value = target.getHours();
minuteInput.value = String(target.getMinutes()).padStart(2, '0');
updateCountdownPreview();
});
hourInput.addEventListener("input", updateCountdownPreview);
minuteInput.addEventListener("input", updateCountdownPreview);
timerSelect.addEventListener("change", (e) => {
setCurrentTimer(e.target.value);
});
addTimerBtn.addEventListener("click", addNewTimer);
renameTimerBtn.addEventListener("click", renameCurrentTimer);
window.addEventListener('scroll', handleScroll);
document.addEventListener('scroll', handleScroll);
}
// ===== Scroll and UI Functions =====
function handleScroll() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const isScrolled = scrollTop > 50;
if (bottomRight && bottomLeft) {
if (isScrolled) {
bottomRight.classList.add("bottom-hidden");
bottomLeft.classList.add("bottom-hidden");
} else {
bottomRight.classList.remove("bottom-hidden");
bottomLeft.classList.remove("bottom-hidden");
}
}
}
// ===== Drag and Drop Functions =====
let draggedElement = null;
function handleDragStart(e) {
draggedElement = this;
this.style.opacity = '0.4';
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.outerHTML);
}
function handleDragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';