-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1113 lines (927 loc) Β· 40.4 KB
/
script.js
File metadata and controls
1113 lines (927 loc) Β· 40.4 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
class BarbecueTimer {
constructor() {
this.totalSeconds = 0;
this.remainingSeconds = 0;
this.originalTime = 0;
this.addedSeconds = 0;
this.isRunning = false;
this.isPaused = false;
this.timerInterval = null;
this.alarmAudio = null;
this.alarmInterval = null;
this.lastUsedTime = null;
// Timestamp-based timer tracking
this.timerEndTime = null;
this.pausedTime = null;
// Program-related variables
this.programs = [];
this.currentProgram = null;
this.currentProgramStep = 0;
this.isRunningProgram = false;
this.isProgramPaused = false;
this.originalTimerComplete = null;
this.initializeElements();
this.setupEventListeners();
this.setupVisibilityHandling();
this.createAlarmSound();
this.loadPrograms();
}
initializeElements() {
this.elements = {
originalTime: document.getElementById('originalTime'),
addedTime: document.getElementById('addedTime'),
countdown: document.getElementById('countdown'),
quickTimers: document.getElementById('quickTimers'),
customTimer: document.getElementById('customTimer'),
timerControls: document.getElementById('timerControls'),
alarmSection: document.getElementById('alarmSection'),
tempModal: document.getElementById('tempModal'),
minutes: document.getElementById('minutes'),
seconds: document.getElementById('seconds'),
setCustomTimer: document.getElementById('setCustomTimer'),
addTime: document.getElementById('addTime'),
pauseTimer: document.getElementById('pauseTimer'),
stopTimer: document.getElementById('stopTimer'),
dismissAlarm: document.getElementById('dismissAlarm'),
tempGuideBtn: document.getElementById('tempGuideBtn'),
closeTempModal: document.getElementById('closeTempModal'),
volumeWarning: document.getElementById('volumeWarning'),
// Programs elements
programsSection: document.getElementById('programsSection'),
programsList: document.getElementById('programsList'),
createProgram: document.getElementById('createProgram'),
programModal: document.getElementById('programModal'),
closeProgramModal: document.getElementById('closeProgramModal'),
programName: document.getElementById('programName'),
programSteps: document.getElementById('programSteps'),
addStep: document.getElementById('addStep'),
saveProgram: document.getElementById('saveProgram'),
cancelProgram: document.getElementById('cancelProgram'),
programExecution: document.getElementById('programExecution'),
programExecutionTitle: document.getElementById('programExecutionTitle'),
currentStep: document.getElementById('currentStep'),
stepDescription: document.getElementById('stepDescription'),
// Program step completion elements
programStepAlarmSection: document.getElementById('programStepAlarmSection'),
programStepTitle: document.getElementById('programStepTitle'),
programStepMessage: document.getElementById('programStepMessage'),
programNextStepInfo: document.getElementById('programNextStepInfo'),
nextStepDescription: document.getElementById('nextStepDescription'),
pauseProgram: document.getElementById('pauseProgram'),
continueToNextStep: document.getElementById('continueToNextStep'),
// Program completion elements
programCompleteAlarmSection: document.getElementById('programCompleteAlarmSection'),
programCompleteTitle: document.getElementById('programCompleteTitle'),
programCompleteMessage: document.getElementById('programCompleteMessage'),
dismissProgramComplete: document.getElementById('dismissProgramComplete')
};
}
setupEventListeners() {
// Quick timer buttons
document.querySelectorAll('.quick-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
this.playButtonBeep();
const seconds = parseInt(e.target.dataset.seconds);
this.setTimer(seconds);
});
});
// Custom timer
this.elements.setCustomTimer.addEventListener('click', () => {
this.playButtonBeep();
this.setCustomTimer();
});
// Timer controls
this.elements.addTime.addEventListener('click', () => {
this.playButtonBeep();
this.addTime(30);
});
this.elements.pauseTimer.addEventListener('click', () => {
this.playButtonBeep();
this.togglePause();
});
this.elements.stopTimer.addEventListener('click', () => {
this.playButtonBeep();
this.stopTimer();
});
// Alarm dismissal
this.elements.dismissAlarm.addEventListener('click', () => {
this.playButtonBeep();
this.dismissAlarm();
});
// Temperature guide modal
this.elements.tempGuideBtn.addEventListener('click', () => {
this.playButtonBeep();
this.showTempModal();
});
this.elements.closeTempModal.addEventListener('click', () => {
this.playButtonBeep();
this.hideTempModal();
});
// Close modal when clicking outside
this.elements.tempModal.addEventListener('click', (e) => {
if (e.target === this.elements.tempModal) {
this.hideTempModal();
}
});
// Close modal with Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.elements.tempModal.style.display === 'flex') {
this.hideTempModal();
}
});
// Volume warning click to dismiss
this.elements.volumeWarning.addEventListener('click', () => {
this.hideVolumeWarning();
});
// Enter key for custom timer
[this.elements.minutes, this.elements.seconds].forEach(input => {
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.playButtonBeep();
this.setCustomTimer();
}
});
});
// Programs event listeners
this.elements.createProgram.addEventListener('click', () => {
this.playButtonBeep();
this.showProgramModal();
});
this.elements.closeProgramModal.addEventListener('click', () => {
this.playButtonBeep();
this.hideProgramModal();
});
this.elements.cancelProgram.addEventListener('click', () => {
this.playButtonBeep();
this.hideProgramModal();
});
this.elements.saveProgram.addEventListener('click', () => {
this.playButtonBeep();
this.saveProgram();
});
this.elements.addStep.addEventListener('click', () => {
this.playButtonBeep();
this.addProgramStep();
});
// Close program modal when clicking outside
this.elements.programModal.addEventListener('click', (e) => {
if (e.target === this.elements.programModal) {
this.hideProgramModal();
}
});
// Handle Escape key for program modal
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.elements.programModal.style.display === 'flex') {
this.hideProgramModal();
}
});
// Program step completion event listeners
this.elements.pauseProgram.addEventListener('click', () => {
this.playButtonBeep();
this.pauseProgramExecution();
});
this.elements.continueToNextStep.addEventListener('click', () => {
this.playButtonBeep();
this.continueToNextProgramStep();
});
// Program completion event listener
this.elements.dismissProgramComplete.addEventListener('click', () => {
this.playButtonBeep();
this.dismissProgramComplete();
});
}
setupVisibilityHandling() {
// Handle page visibility changes to recalculate timer when screen turns back on
document.addEventListener('visibilitychange', () => {
if (!document.hidden && this.isRunning && !this.isPaused) {
// Page became visible again, recalculate remaining time
this.recalculateRemainingTime();
}
});
// Also handle when the page gains focus
window.addEventListener('focus', () => {
if (this.isRunning && !this.isPaused) {
this.recalculateRemainingTime();
}
});
}
recalculateRemainingTime() {
if (!this.timerEndTime) return;
const now = Date.now();
const remaining = Math.max(0, Math.ceil((this.timerEndTime - now) / 1000));
if (remaining <= 0) {
// Timer has completed while we were away
this.remainingSeconds = 0;
this.updateDisplay();
this.timerComplete();
} else {
this.remainingSeconds = remaining;
this.updateDisplay();
// Update low-time warning
if (this.remainingSeconds <= 30) {
document.body.classList.add('low-time');
} else {
document.body.classList.remove('low-time');
}
}
}
createAlarmSound() {
// Create alarm sound using Web Audio API
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
this.createBeepSound();
this.checkVolumeLevel();
}
async checkVolumeLevel() {
// Check if we can detect volume level
// Note: Web browsers don't provide direct access to system volume
// We'll use a heuristic approach by checking if audio output is available
try {
if (this.audioContext) {
// Check if audio context is working
const destination = this.audioContext.destination;
// If destination maxChannelCount is 0, audio might be unavailable
if (destination.maxChannelCount === 0) {
this.showVolumeWarning();
return;
}
}
// Always show the warning when timer starts to remind users to check volume
// This is a best practice since we can't detect actual system volume
this.volumeWarningDismissed = false;
} catch (error) {
console.log('Could not check volume level:', error);
}
}
showVolumeWarning() {
if (!this.volumeWarningDismissed && this.elements.volumeWarning) {
this.elements.volumeWarning.style.display = 'flex';
// Auto-hide after 10 seconds
if (this.volumeWarningTimeout) {
clearTimeout(this.volumeWarningTimeout);
}
this.volumeWarningTimeout = setTimeout(() => {
this.hideVolumeWarning();
}, 10000);
}
}
hideVolumeWarning() {
if (this.elements.volumeWarning) {
this.elements.volumeWarning.style.display = 'none';
this.volumeWarningDismissed = true;
}
}
createBeepSound() {
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.audioContext.destination);
oscillator.frequency.setValueAtTime(800, this.audioContext.currentTime);
gainNode.gain.setValueAtTime(0.1, this.audioContext.currentTime);
this.alarmOscillator = oscillator;
this.alarmGain = gainNode;
}
playButtonBeep() {
// Play a short beep sound for button clicks
if (!this.audioContext) return;
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.audioContext.destination);
// Shorter, higher pitched beep for button clicks
oscillator.frequency.setValueAtTime(1000, this.audioContext.currentTime);
gainNode.gain.setValueAtTime(0.05, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.001, this.audioContext.currentTime + 0.1);
oscillator.start();
oscillator.stop(this.audioContext.currentTime + 0.1);
}
playAlarm() {
let isPlaying = true;
this.alarmInterval = setInterval(() => {
if (isPlaying) {
const oscillator = this.audioContext.createOscillator();
const gainNode = this.audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this.audioContext.destination);
oscillator.frequency.setValueAtTime(800, this.audioContext.currentTime);
gainNode.gain.setValueAtTime(0.1, this.audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + 0.5);
oscillator.start();
oscillator.stop(this.audioContext.currentTime + 0.5);
// Vibrate if supported
if ('vibrate' in navigator) {
navigator.vibrate([500, 200, 500, 200, 500]);
}
}
}, 1000);
}
stopAlarm() {
if (this.alarmInterval) {
clearInterval(this.alarmInterval);
this.alarmInterval = null;
}
if ('vibrate' in navigator) {
navigator.vibrate(0); // Stop vibration
}
}
setTimer(seconds) {
if (this.isRunning) return;
this.totalSeconds = seconds;
this.remainingSeconds = seconds;
this.originalTime = seconds;
this.addedSeconds = 0;
this.lastUsedTime = seconds;
this.updateDisplay();
this.startTimer();
}
setCustomTimer() {
if (this.isRunning) return;
const minutes = parseInt(this.elements.minutes.value) || 0;
const seconds = parseInt(this.elements.seconds.value) || 0;
const totalSeconds = (minutes * 60) + seconds;
if (totalSeconds <= 0) {
alert('Please enter a valid time');
return;
}
this.setTimer(totalSeconds);
// Clear inputs
this.elements.minutes.value = '';
this.elements.seconds.value = '';
// Scroll to top to show the timer display
window.scrollTo({ top: 0, behavior: 'smooth' });
}
startTimer() {
this.isRunning = true;
this.isPaused = false;
// Clear any previous last-used highlight
this.clearLastUsedHighlight();
// Calculate the end time based on remaining seconds
this.timerEndTime = Date.now() + (this.remainingSeconds * 1000);
// Show volume warning
this.showVolumeWarning();
// Show controls, hide setup
this.elements.timerControls.style.display = 'flex';
document.body.classList.add('timer-running');
this.elements.originalTime.textContent = `Original: ${this.formatTime(this.originalTime)}`;
this.elements.addedTime.style.display = 'none'; // Hide initially
this.timerInterval = setInterval(() => {
if (!this.isPaused) {
// Calculate remaining time based on actual elapsed time
const now = Date.now();
const remaining = Math.max(0, Math.ceil((this.timerEndTime - now) / 1000));
this.remainingSeconds = remaining;
// Prevent negative values from being displayed
if (this.remainingSeconds <= 0) {
this.remainingSeconds = 0;
this.updateDisplay();
this.timerComplete();
return;
}
this.updateDisplay();
// Warning for last 30 seconds
if (this.remainingSeconds <= 30) {
document.body.classList.add('low-time');
} else {
document.body.classList.remove('low-time');
}
}
}, 1000);
}
updateDisplay() {
this.elements.countdown.textContent = this.formatTime(this.remainingSeconds);
}
formatTime(totalSeconds) {
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
addTime(seconds) {
if (!this.isRunning) return;
this.remainingSeconds += seconds;
this.totalSeconds += seconds;
this.addedSeconds += seconds; // Track added time separately
// Update the end time to reflect added seconds
if (this.timerEndTime) {
this.timerEndTime += (seconds * 1000);
}
this.updateDisplay();
// Keep original time display unchanged, show added time below
if (this.addedSeconds > 0) {
this.elements.addedTime.textContent = `Plus ${this.formatTime(this.addedSeconds)} added`;
this.elements.addedTime.style.display = 'block';
}
// Remove low-time warning if we're above 30 seconds
if (this.remainingSeconds > 30) {
document.body.classList.remove('low-time');
}
// Show feedback
this.showAddTimeAnimation();
}
showAddTimeAnimation() {
const addBtn = this.elements.addTime;
const originalText = addBtn.textContent;
addBtn.textContent = '+30s Added!';
addBtn.style.background = '#4CAF50';
setTimeout(() => {
addBtn.textContent = originalText;
addBtn.style.background = '#2196F3';
}, 1000);
}
togglePause() {
if (!this.isRunning) return;
this.isPaused = !this.isPaused;
this.elements.pauseTimer.textContent = this.isPaused ? 'Resume' : 'Pause';
if (this.isPaused) {
// Store the paused time
this.pausedTime = Date.now();
document.body.classList.remove('timer-running');
} else {
// Resume: adjust end time to account for pause duration
if (this.pausedTime && this.timerEndTime) {
const pauseDuration = Date.now() - this.pausedTime;
this.timerEndTime += pauseDuration;
this.pausedTime = null;
}
document.body.classList.add('timer-running');
}
}
stopTimer() {
this.isRunning = false;
this.isPaused = false;
// Reset timestamp tracking
this.timerEndTime = null;
this.pausedTime = null;
// Hide volume warning
this.hideVolumeWarning();
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
// If a program is running, stop it completely
if (this.isRunningProgram) {
this.isRunningProgram = false;
this.currentProgram = null;
this.currentProgramStep = 0;
if (this.originalTimerComplete) {
this.timerComplete = this.originalTimerComplete; // Restore original
}
// Show regular sections again
this.elements.quickTimers.style.display = 'block';
this.elements.customTimer.style.display = 'block';
this.elements.programsSection.style.display = 'block';
this.elements.programExecution.style.display = 'none';
}
// Reset display
this.elements.originalTime.textContent = 'Set a timer';
this.elements.addedTime.style.display = 'none'; // Hide added time
this.elements.countdown.textContent = '00:00';
this.elements.pauseTimer.textContent = 'Pause';
// Hide controls, show setup
this.elements.timerControls.style.display = 'none';
document.body.classList.remove('timer-running', 'low-time');
this.remainingSeconds = 0;
this.totalSeconds = 0;
this.originalTime = 0;
this.addedSeconds = 0; // Reset added time
}
timerComplete() {
this.stopTimer();
this.showAlarm();
this.playAlarm();
// Send notification if the page is in the background
if (document.hidden && 'Notification' in window && Notification.permission === 'granted') {
new Notification('π Time to flip!', {
body: 'Your Barbecue Timer has finished!',
icon: '/android-chrome-192x192.png',
badge: '/favicon-48x48.png',
vibrate: [500, 200, 500, 200, 500],
tag: 'timer-complete',
requireInteraction: true
});
}
}
showAlarm() {
this.elements.alarmSection.style.display = 'flex';
// Change the page title to draw attention
document.title = 'π₯ TIME TO FLIP! - Barbecue Timer';
}
dismissAlarm() {
this.elements.alarmSection.style.display = 'none';
this.stopAlarm();
document.title = 'Barbecue Timer';
this.highlightLastUsedTime();
}
clearLastUsedHighlight() {
document.querySelectorAll('.quick-btn').forEach(btn => {
btn.classList.remove('last-used');
});
}
highlightLastUsedTime() {
this.clearLastUsedHighlight();
// Highlight the matching quick button if there is one
if (this.lastUsedTime !== null) {
const matchingButton = document.querySelector(`.quick-btn[data-seconds="${this.lastUsedTime}"]`);
if (matchingButton) {
matchingButton.classList.add('last-used');
}
}
}
showTempModal() {
this.elements.tempModal.style.display = 'flex';
}
hideTempModal() {
this.elements.tempModal.style.display = 'none';
}
// Program Management Methods
loadPrograms() {
try {
const saved = localStorage.getItem('barbecue-programs');
this.programs = saved ? JSON.parse(saved) : [];
this.displayPrograms();
} catch (error) {
console.error('Error loading programs:', error);
this.programs = [];
}
}
savePrograms() {
try {
localStorage.setItem('barbecue-programs', JSON.stringify(this.programs));
} catch (error) {
console.error('Error saving programs:', error);
}
}
displayPrograms() {
const container = this.elements.programsList;
container.innerHTML = '';
// Show resume option if a program is paused
if (this.isProgramPaused && this.currentProgram) {
const resumeElement = document.createElement('div');
resumeElement.className = 'program-item paused-program';
resumeElement.innerHTML = `
<div class="program-info">
<h4>βΈοΈ ${this.currentProgram.name} (Paused)</h4>
<p>Step ${this.currentProgramStep + 1} of ${this.currentProgram.steps.length} β’ Paused</p>
</div>
<div class="program-actions">
<button class="program-btn resume-program">Resume</button>
<button class="program-btn stop-program">Stop Program</button>
</div>
`;
container.appendChild(resumeElement);
// Add event listeners for resume and stop
resumeElement.querySelector('.resume-program').addEventListener('click', () => {
this.playButtonBeep();
this.resumeProgramExecution();
});
resumeElement.querySelector('.stop-program').addEventListener('click', () => {
this.playButtonBeep();
this.completeProgramExecution();
});
}
if (this.programs.length === 0 && !this.isProgramPaused) {
container.innerHTML = '<p style="color: #666; font-style: italic;">No programs saved yet. Create your first program!</p>';
return;
}
this.programs.forEach((program, index) => {
const programElement = document.createElement('div');
programElement.className = 'program-item';
const totalTime = program.steps.reduce((total, step) => {
return total + (step.minutes * 60) + step.seconds;
}, 0);
programElement.innerHTML = `
<div class="program-info">
<h4>${program.name}</h4>
<p>${program.steps.length} steps β’ Total: ${this.formatTime(totalTime)}</p>
</div>
<div class="program-actions">
<button class="program-btn run-program" data-index="${index}">Run</button>
<button class="program-btn delete-program" data-index="${index}">Delete</button>
</div>
`;
container.appendChild(programElement);
});
// Add event listeners for run and delete buttons
container.querySelectorAll('.run-program').forEach(btn => {
btn.addEventListener('click', (e) => {
this.playButtonBeep();
const index = parseInt(e.target.dataset.index);
this.runProgram(index);
});
});
container.querySelectorAll('.delete-program').forEach(btn => {
btn.addEventListener('click', (e) => {
this.playButtonBeep();
const index = parseInt(e.target.dataset.index);
this.deleteProgram(index);
});
});
}
showProgramModal() {
this.elements.programModal.style.display = 'flex';
this.elements.programName.value = '';
this.resetProgramSteps();
}
hideProgramModal() {
this.elements.programModal.style.display = 'none';
}
resetProgramSteps() {
this.elements.programSteps.innerHTML = `
<div class="step-input">
<input type="number" min="0" max="59" placeholder="0" class="step-minutes">
<span>minutes</span>
<input type="number" min="0" max="59" placeholder="0" class="step-seconds">
<span>seconds</span>
<input type="text" placeholder="Step description (optional)" class="step-description">
<button type="button" class="remove-step" style="display: none;">×</button>
</div>
`;
}
addProgramStep() {
const stepDiv = document.createElement('div');
stepDiv.className = 'step-input';
stepDiv.innerHTML = `
<input type="number" min="0" max="59" placeholder="0" class="step-minutes">
<span>minutes</span>
<input type="number" min="0" max="59" placeholder="0" class="step-seconds">
<span>seconds</span>
<input type="text" placeholder="Step description (optional)" class="step-description">
<button type="button" class="remove-step">×</button>
`;
this.elements.programSteps.appendChild(stepDiv);
// Add event listener for remove button
stepDiv.querySelector('.remove-step').addEventListener('click', () => {
this.playButtonBeep();
stepDiv.remove();
this.updateRemoveButtons();
});
this.updateRemoveButtons();
}
updateRemoveButtons() {
const steps = this.elements.programSteps.querySelectorAll('.step-input');
steps.forEach((step, index) => {
const removeBtn = step.querySelector('.remove-step');
removeBtn.style.display = steps.length > 1 ? 'flex' : 'none';
});
}
saveProgram() {
const name = this.elements.programName.value.trim();
if (!name) {
alert('Please enter a program name');
return;
}
const stepInputs = this.elements.programSteps.querySelectorAll('.step-input');
const steps = [];
for (let stepInput of stepInputs) {
const minutes = parseInt(stepInput.querySelector('.step-minutes').value) || 0;
const seconds = parseInt(stepInput.querySelector('.step-seconds').value) || 0;
const description = stepInput.querySelector('.step-description').value.trim();
if (minutes === 0 && seconds === 0) {
alert('Each step must have at least 1 second');
return;
}
steps.push({
minutes,
seconds,
description: description || `${minutes}m ${seconds}s`
});
}
if (steps.length === 0) {
alert('Please add at least one step');
return;
}
const program = { name, steps };
this.programs.push(program);
this.savePrograms();
this.displayPrograms();
this.hideProgramModal();
}
deleteProgram(index) {
const program = this.programs[index];
if (confirm(`Delete program "${program.name}"?`)) {
this.programs.splice(index, 1);
this.savePrograms();
this.displayPrograms();
}
}
runProgram(index) {
if (this.isRunning || this.isRunningProgram) {
alert('A timer is already running. Stop it first.');
return;
}
// Scroll to top of the page when starting a program
window.scrollTo({ top: 0, behavior: 'smooth' });
this.currentProgram = this.programs[index];
this.currentProgramStep = 0;
this.isRunningProgram = true;
// Hide other sections and show program execution
this.elements.quickTimers.style.display = 'none';
this.elements.customTimer.style.display = 'none';
this.elements.programsSection.style.display = 'none';
this.elements.programExecution.style.display = 'block';
this.elements.programExecutionTitle.textContent = `Running: ${this.currentProgram.name}`;
this.runNextProgramStep();
}
runNextProgramStep() {
if (this.currentProgramStep >= this.currentProgram.steps.length) {
this.completeProgramExecution();
return;
}
const step = this.currentProgram.steps[this.currentProgramStep];
const stepTime = (step.minutes * 60) + step.seconds;
// Update program progress display
this.elements.currentStep.textContent = `Step ${this.currentProgramStep + 1} of ${this.currentProgram.steps.length}`;
this.elements.stepDescription.textContent = step.description;
// Start the timer for this step
this.setTimer(stepTime);
// Override the timer complete method to handle program flow
this.originalTimerComplete = this.timerComplete.bind(this);
this.timerComplete = () => {
// Stop the timer but keep program running
this.isRunning = false;
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
this.stopAlarm();
this.showProgramStepComplete();
};
}
showProgramStepComplete() {
// Check if this was the last step before incrementing
if (this.currentProgramStep + 1 >= this.currentProgram.steps.length) {
this.currentProgramStep++;
this.completeProgramExecution();
} else {
// Show enhanced alarm modal for step completion
const nextStep = this.currentProgram.steps[this.currentProgramStep + 1];
// Update modal content
this.elements.programStepTitle.textContent = `π Step ${this.currentProgramStep + 1} Complete!`;
this.elements.programStepMessage.textContent = `Great progress! You've completed another step.`;
this.elements.nextStepDescription.textContent = nextStep.description || `Step ${this.currentProgramStep + 2}`;
// Show the program step completion modal
this.elements.programStepAlarmSection.style.display = 'flex';
// Change the page title to draw attention
document.title = 'π₯ STEP COMPLETE! - Barbecue Timer';
// Play alarm sound and vibrate
this.playAlarm();
// Send notification if the page is in the background
if (document.hidden && 'Notification' in window && Notification.permission === 'granted') {
new Notification(`π Step ${this.currentProgramStep + 1} Complete!`, {
body: `Next: ${nextStep.description || `Step ${this.currentProgramStep + 2}`}`,
icon: '/android-chrome-192x192.png',
badge: '/favicon-48x48.png',
vibrate: [500, 200, 500, 200, 500],
tag: 'program-step-complete',
requireInteraction: true
});
}
}
}
completeProgramExecution() {
// Show styled program completion modal instead of basic alert
this.elements.programCompleteTitle.textContent = `π Program Complete!`;
this.elements.programCompleteMessage.textContent = `Congratulations! You've completed "${this.currentProgram.name}"! π`;
// Show the program completion modal
this.elements.programCompleteAlarmSection.style.display = 'flex';
// Change the page title to draw attention
document.title = 'π PROGRAM COMPLETE! - Barbecue Timer';
// Play alarm sound and vibrate
this.playAlarm();
// Send notification if the page is in the background
if (document.hidden && 'Notification' in window && Notification.permission === 'granted') {
new Notification('π Program Complete!', {
body: `You've finished "${this.currentProgram.name}"!`,
icon: '/android-chrome-192x192.png',
badge: '/favicon-48x48.png',
vibrate: [500, 200, 500, 200, 500],
tag: 'program-complete',
requireInteraction: true
});
}
// Reset program state
this.isRunningProgram = false;
this.isProgramPaused = false;
this.currentProgram = null;
this.currentProgramStep = 0;
this.timerComplete = this.originalTimerComplete; // Restore original
// Show regular sections again
this.elements.quickTimers.style.display = 'block';
this.elements.customTimer.style.display = 'block';
this.elements.programsSection.style.display = 'block';
this.elements.programExecution.style.display = 'none';
// Reset timer display
this.stopTimer();
}
pauseProgramExecution() {
// Hide the step completion modal
this.elements.programStepAlarmSection.style.display = 'none';
this.stopAlarm();
document.title = 'Barbecue Timer';
// Increment step counter since we completed the current step
this.currentProgramStep++;
// Set program as paused
this.isProgramPaused = true;
// Show regular sections for user to interact with other features
this.elements.quickTimers.style.display = 'block';
this.elements.customTimer.style.display = 'block';
this.elements.programsSection.style.display = 'block';
this.elements.programExecution.style.display = 'none';
// Reset timer display
this.stopTimer();
// Add resume button to programs section (we'll need to update displayPrograms for this)
this.displayPrograms();