-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
320 lines (258 loc) · 10.7 KB
/
script.js
File metadata and controls
320 lines (258 loc) · 10.7 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
// Pomodoro-Style Interval Timer
// State variables
let timerInterval = null;
let currentPhase = 1; // 1 for work phase, 2 for break phase
let remainingTimeMs = 0;
let isRunning = false;
// Audio context for sound alerts
let audioContext = null;
let audioEnabled = false;
// Initialize app on page load
window.addEventListener('DOMContentLoaded', function () {
initializeApp();
setupEventListeners();
requestNotificationPermission();
});
// Request notification permission
function requestNotificationPermission() {
if ("Notification" in window && Notification.permission === "default") {
Notification.requestPermission().then(function (permission) {
console.log("Notification permission:", permission);
});
}
}
// Initialize application
function initializeApp() {
// Load saved interval values from cookies
const savedWorkDuration = getCookie("workDuration");
const savedBreakDuration = getCookie("breakDuration");
const savedAudioEnabled = getCookie("audioEnabled");
// Set input values with validation
document.getElementById("workDuration").value = validateInterval(savedWorkDuration) || 25;
document.getElementById("breakDuration").value = validateInterval(savedBreakDuration) || 5;
// Set audio checkbox
audioEnabled = savedAudioEnabled === "true";
document.getElementById("audioAlert").checked = audioEnabled;
// Load timer state if it was running
const timerState = getCookie("timerState");
const savedPhase = getCookie("currentPhase");
const savedRemainingTime = getCookie("remainingTime");
const savedTimestamp = getCookie("lastUpdateTime");
if (timerState === "running" && savedPhase && savedRemainingTime && savedTimestamp) {
// Calculate time elapsed since last update
const now = Date.now();
const lastUpdate = parseInt(savedTimestamp, 10);
const elapsedTime = now - lastUpdate;
currentPhase = parseInt(savedPhase, 10);
remainingTimeMs = parseInt(savedRemainingTime, 10) - elapsedTime;
// If time ran out while page was closed, handle phase completion
const workDuration = validateInterval(document.getElementById("workDuration").value) || 25;
const breakDuration = validateInterval(document.getElementById("breakDuration").value) || 5;
while (remainingTimeMs <= 0) {
// Switch phases for any missed completions
currentPhase = currentPhase === 1 ? 2 : 1;
remainingTimeMs += (currentPhase === 1 ? workDuration : breakDuration) * 60 * 1000;
}
updatePhaseDisplay();
updateTimerDisplay(remainingTimeMs);
// Show brief notification that timer was resumed
console.log("Timer resumed from previous session");
// Auto-resume the timer
startTimer();
} else {
// Set initial time based on first phase
const workDuration = validateInterval(document.getElementById("workDuration").value);
remainingTimeMs = workDuration * 60 * 1000;
updateTimerDisplay(remainingTimeMs);
}
}
// Setup event listeners
function setupEventListeners() {
document.getElementById("startButton").addEventListener("click", startTimer);
document.getElementById("stopButton").addEventListener("click", stopTimer);
document.getElementById("resetButton").addEventListener("click", resetTimer);
document.getElementById("audioAlert").addEventListener("change", toggleAudio);
// Save preferences when intervals change
document.getElementById("workDuration").addEventListener("change", saveIntervalPreferences);
document.getElementById("breakDuration").addEventListener("change", saveIntervalPreferences);
// Save state before page unload
window.addEventListener('beforeunload', saveTimerState);
}
// Validate interval input
function validateInterval(value) {
const parsedValue = parseInt(value, 10);
return isNaN(parsedValue) || parsedValue < 1 ? null : parsedValue;
}
// Start timer
function startTimer() {
if (isRunning) return;
const workDuration = validateInterval(document.getElementById("workDuration").value) || 25;
const breakDuration = validateInterval(document.getElementById("breakDuration").value) || 5;
// If timer is at 0, reset to current phase duration
if (remainingTimeMs <= 0) {
remainingTimeMs = currentPhase === 1
? workDuration * 60 * 1000
: breakDuration * 60 * 1000;
}
isRunning = true;
timerInterval = setInterval(function () {
remainingTimeMs -= 1000;
updateTimerDisplay(remainingTimeMs);
if (remainingTimeMs <= 0) {
handlePhaseCompletion(workDuration, breakDuration);
}
// Save state every second while running
saveTimerState();
}, 1000);
updatePhaseDisplay();
saveTimerState(); // Save immediately when starting
}
// Stop timer
function stopTimer() {
if (!isRunning) return;
clearInterval(timerInterval);
timerInterval = null;
isRunning = false;
saveTimerState();
}
// Reset timer
function resetTimer() {
stopTimer();
const workDuration = validateInterval(document.getElementById("workDuration").value) || 25;
currentPhase = 1;
remainingTimeMs = workDuration * 60 * 1000;
updateTimerDisplay(remainingTimeMs);
updatePhaseDisplay();
// Clear saved state
deleteCookie("timerState");
deleteCookie("currentPhase");
deleteCookie("remainingTime");
}
// Handle phase completion
function handlePhaseCompletion(workDuration, breakDuration) {
const phaseName = currentPhase === 1 ? "Work Session" : "Break Time";
// Send notification
sendNotification(`${phaseName} Complete!`, `Time to ${currentPhase === 1 ? "take a break" : "get back to work"}!`);
// Play sound if enabled
if (audioEnabled) {
playAlertSound();
}
// Switch to next phase
currentPhase = currentPhase === 1 ? 2 : 1;
remainingTimeMs = currentPhase === 1
? workDuration * 60 * 1000
: breakDuration * 60 * 1000;
updatePhaseDisplay();
}
// Update timer display
function updateTimerDisplay(durationMs) {
const totalSeconds = Math.max(0, Math.floor(durationMs / 1000));
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const formattedTime = `${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
const timerElement = document.getElementById("timerDisplay");
timerElement.textContent = formattedTime;
// Add visual indicator when running
if (isRunning) {
timerElement.classList.add("running");
} else {
timerElement.classList.remove("running");
}
// Update page title for easy monitoring
document.title = `${formattedTime} - Focus Timer`;
}
// Pad numbers with leading zero
function padZero(num) {
return num < 10 ? `0${num}` : num;
}
// Update phase display
function updatePhaseDisplay() {
const phaseText = currentPhase === 1 ? "Work Session" : "Break Time";
const phaseEmoji = currentPhase === 1 ? "🎯" : "☕";
document.getElementById("intervalStatus").textContent = `${phaseEmoji} ${phaseText}`;
}
// Send notification
function sendNotification(title, body) {
if ("Notification" in window && Notification.permission === "granted") {
new Notification(title, {
body: body,
icon: "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='75' font-size='75'>⏰</text></svg>",
requireInteraction: false
});
}
}
// Toggle audio alerts
function toggleAudio() {
audioEnabled = document.getElementById("audioAlert").checked;
setCookie("audioEnabled", audioEnabled.toString());
}
// Play alert sound using Web Audio API
function playAlertSound() {
try {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
}
// Create a pleasant notification sound
const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.frequency.value = 800; // A5 note
oscillator.type = "sine";
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
oscillator.start(audioContext.currentTime);
oscillator.stop(audioContext.currentTime + 0.5);
// Play a second tone
setTimeout(() => {
const oscillator2 = audioContext.createOscillator();
const gainNode2 = audioContext.createGain();
oscillator2.connect(gainNode2);
gainNode2.connect(audioContext.destination);
oscillator2.frequency.value = 1000; // Higher note
oscillator2.type = "sine";
gainNode2.gain.setValueAtTime(0.3, audioContext.currentTime);
gainNode2.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.5);
oscillator2.start(audioContext.currentTime);
oscillator2.stop(audioContext.currentTime + 0.5);
}, 200);
} catch (error) {
console.error("Error playing sound:", error);
}
}
// Save interval preferences
function saveIntervalPreferences() {
const workDuration = document.getElementById("workDuration").value;
const breakDuration = document.getElementById("breakDuration").value;
setCookie("workDuration", workDuration);
setCookie("breakDuration", breakDuration);
}
// Save timer state
function saveTimerState() {
if (isRunning) {
setCookie("timerState", "running");
setCookie("currentPhase", currentPhase.toString());
setCookie("remainingTime", remainingTimeMs.toString());
setCookie("lastUpdateTime", Date.now().toString());
} else {
deleteCookie("timerState");
deleteCookie("currentPhase");
deleteCookie("remainingTime");
deleteCookie("lastUpdateTime");
}
}
// Cookie helper functions
function setCookie(name, value, days = 365) {
const expires = new Date();
expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
}
function getCookie(name) {
const cookies = document.cookie.split(';').map(cookie => cookie.trim());
const cookie = cookies.find(cookie => cookie.startsWith(`${name}=`));
return cookie ? cookie.split('=')[1] : null;
}
function deleteCookie(name) {
document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; SameSite=Lax`;
}