forked from AnujShrivastava01/AnimateItNow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpomodoro.js
More file actions
441 lines (377 loc) Β· 15.8 KB
/
Copy pathpomodoro.js
File metadata and controls
441 lines (377 loc) Β· 15.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
// π― Debug logging helper
const logDebug = (message, data = null) => {
console.log(`β° TimerDebug: ${message}`, data ? data : '');
};
// π― Performance monitoring helper
const trackPerformance = (operation, startTime) => {
const duration = performance.now() - startTime;
logDebug(`β±οΈ ${operation} Performance`, { duration: `${duration.toFixed(2)}ms` });
return duration;
};
document.addEventListener('DOMContentLoaded', () => {
const loadStartTime = performance.now();
logDebug('π Pomodoro timer initialized');
// π― DOM Elements with enhanced accessibility
const timeDisplay = document.querySelector('.time-display');
const startBtn = document.getElementById('start-btn');
const pauseBtn = document.getElementById('pause-btn');
const resetBtn = document.getElementById('reset-btn');
const pomodoroBtn = document.getElementById('pomodoro-btn');
const shortBreakBtn = document.getElementById('short-break-btn');
const longBreakBtn = document.getElementById('long-break-btn');
// π― Timer state with enhanced tracking
let timerInterval;
let isRunning = false;
let timeRemaining = 25 * 60; // Default Pomodoro time in seconds
let currentMode = 'pomodoro';
let sessionStats = {
pomodorosCompleted: 0,
totalFocusTime: 0,
sessions: [],
startTime: null
};
// Timer configurations
const timerConfig = {
pomodoro: 25 * 60,
'short-break': 5 * 60,
'long-break': 15 * 60
};
const modeNames = {
pomodoro: 'Pomodoro',
'short-break': 'Short Break',
'long-break': 'Long Break'
};
// π― Enhanced display update with accessibility
function updateDisplay() {
const minutes = Math.floor(timeRemaining / 60);
const seconds = timeRemaining % 60;
const displayText = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
timeDisplay.textContent = displayText;
// π― Update aria-live region for screen readers
timeDisplay.setAttribute('aria-live', 'polite');
timeDisplay.setAttribute('aria-label', `${minutes} minutes ${seconds} seconds remaining in ${modeNames[currentMode]}`);
logDebug('π Display updated', {
display: displayText,
mode: currentMode,
remaining: timeRemaining
});
}
// π― Enhanced timer start with state tracking
function startTimer() {
if (isRunning) {
logDebug('β οΈ Timer already running', { currentMode, timeRemaining });
return;
}
const startTime = performance.now();
isRunning = true;
// π― Track session start
if (!sessionStats.startTime) {
sessionStats.startTime = new Date();
logDebug('π¬ Session started', {
startTime: sessionStats.startTime.toISOString(),
mode: currentMode
});
}
// π― Update button states for accessibility
updateButtonStates();
timerInterval = setInterval(() => {
if (timeRemaining > 0) {
timeRemaining--;
updateDisplay();
// π― Log every minute for performance monitoring
if (timeRemaining % 60 === 0) {
logDebug('β²οΈ Timer tick', {
minutesRemaining: Math.floor(timeRemaining / 60),
mode: currentMode
});
}
} else {
clearInterval(timerInterval);
isRunning = false;
// π― Track session completion
trackSessionCompletion();
// π― Enhanced notification
const completionMessage = `${modeNames[currentMode]} session completed!`;
logDebug('β
Timer completed', {
mode: currentMode,
message: completionMessage
});
// π― Accessible notification
if ('Notification' in window && Notification.permission === 'granted') {
new Notification('Pomodoro Timer', {
body: completionMessage,
icon: '/timer-icon.png'
});
} else {
// Fallback alert with enhanced accessibility
const alertBox = document.createElement('div');
alertBox.setAttribute('role', 'alert');
alertBox.setAttribute('aria-live', 'assertive');
alertBox.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #4CAF50;
color: white;
padding: 1rem;
border-radius: 8px;
z-index: 1000;
`;
alertBox.textContent = completionMessage;
document.body.appendChild(alertBox);
setTimeout(() => {
document.body.removeChild(alertBox);
}, 5000);
}
updateButtonStates();
}
}, 1000);
const startDuration = trackPerformance('Timer Start', startTime);
logDebug('βΆοΈ Timer started', {
mode: currentMode,
duration: timeRemaining,
startPerformance: `${startDuration.toFixed(2)}ms`
});
}
// π― Enhanced pause function with state tracking
function pauseTimer() {
if (!isRunning) {
logDebug('β οΈ Timer not running, cannot pause');
return;
}
const pauseTime = performance.now();
clearInterval(timerInterval);
isRunning = false;
updateButtonStates();
const pauseDuration = trackPerformance('Timer Pause', pauseTime);
logDebug('βΈοΈ Timer paused', {
mode: currentMode,
remaining: timeRemaining,
pausePerformance: `${pauseDuration.toFixed(2)}ms`
});
}
// π― Enhanced reset function with session tracking
function resetTimer() {
const resetTime = performance.now();
pauseTimer();
timeRemaining = timerConfig[currentMode];
updateDisplay();
// π― Update active button state
updateActiveModeButton();
const resetDuration = trackPerformance('Timer Reset', resetTime);
logDebug('π Timer reset', {
mode: currentMode,
resetTo: timeRemaining,
resetPerformance: `${resetDuration.toFixed(2)}ms`
});
}
// π― Enhanced mode setting with validation
function setMode(mode) {
if (!timerConfig.hasOwnProperty(mode)) {
logDebug('β Invalid mode attempted', { attemptedMode: mode });
return;
}
const modeChangeTime = performance.now();
const previousMode = currentMode;
pauseTimer();
currentMode = mode;
timeRemaining = timerConfig[mode];
updateDisplay();
// π― Update active button with accessibility
updateActiveModeButton();
const modeChangeDuration = trackPerformance('Mode Change', modeChangeTime);
logDebug('π― Mode changed', {
from: previousMode,
to: mode,
duration: timeRemaining,
performance: `${modeChangeDuration.toFixed(2)}ms`
});
}
// π― Helper function to update active mode button
function updateActiveModeButton() {
const activeButton = document.querySelector('.modes .active');
if (activeButton) {
activeButton.classList.remove('active');
activeButton.setAttribute('aria-pressed', 'false');
}
const newActiveButton = document.getElementById(`${currentMode}-btn`);
if (newActiveButton) {
newActiveButton.classList.add('active');
newActiveButton.setAttribute('aria-pressed', 'true');
}
}
// π― Helper function to update control button states
function updateButtonStates() {
// Update Start/Pause button states
startBtn.disabled = isRunning;
startBtn.setAttribute('aria-disabled', isRunning.toString());
pauseBtn.disabled = !isRunning;
pauseBtn.setAttribute('aria-disabled', (!isRunning).toString());
// Update button labels for accessibility
startBtn.setAttribute('aria-label', isRunning ? 'Timer is running' : 'Start timer');
pauseBtn.setAttribute('aria-label', isRunning ? 'Pause timer' : 'Timer is paused');
logDebug('π Button states updated', {
isRunning: isRunning,
startDisabled: startBtn.disabled,
pauseDisabled: pauseBtn.disabled
});
}
// π― Session tracking and statistics
function trackSessionCompletion() {
const session = {
mode: currentMode,
duration: timerConfig[currentMode],
completedAt: new Date().toISOString(),
successful: true
};
sessionStats.sessions.push(session);
if (currentMode === 'pomodoro') {
sessionStats.pomodorosCompleted++;
sessionStats.totalFocusTime += timerConfig.pomodoro;
}
logDebug('π Session completed and tracked', {
session: session,
totalPomodoros: sessionStats.pomodorosCompleted,
totalFocusTime: sessionStats.totalFocusTime
});
// π― Log statistics periodically
if (sessionStats.pomodorosCompleted % 4 === 0) {
logDebug('π Milestone reached', {
pomodorosCompleted: sessionStats.pomodorosCompleted,
totalSessions: sessionStats.sessions.length,
totalFocusTime: sessionStats.totalFocusTime
});
}
}
// π― Enhanced event listeners with error handling
function setupEventListeners() {
try {
// Control buttons
startBtn.addEventListener('click', () => {
logDebug('π Start button clicked');
startTimer();
});
pauseBtn.addEventListener('click', () => {
logDebug('π Pause button clicked');
pauseTimer();
});
resetBtn.addEventListener('click', () => {
logDebug('π Reset button clicked');
resetTimer();
});
// Mode buttons
pomodoroBtn.addEventListener('click', () => {
logDebug('π Pomodoro mode selected');
setMode('pomodoro');
});
shortBreakBtn.addEventListener('click', () => {
logDebug('π Short break mode selected');
setMode('short-break');
});
longBreakBtn.addEventListener('click', () => {
logDebug('π Long break mode selected');
setMode('long-break');
});
// π― Keyboard navigation support
document.addEventListener('keydown', (event) => {
switch (event.key) {
case ' ':
case 'Enter':
if (document.activeElement === startBtn && !isRunning) {
event.preventDefault();
logDebug('β¨οΈ Start timer with keyboard');
startTimer();
} else if (document.activeElement === pauseBtn && isRunning) {
event.preventDefault();
logDebug('β¨οΈ Pause timer with keyboard');
pauseTimer();
}
break;
case 'r':
case 'R':
if (event.ctrlKey) {
event.preventDefault();
logDebug('β¨οΈ Reset timer with Ctrl+R');
resetTimer();
}
break;
case '1':
event.preventDefault();
logDebug('β¨οΈ Switch to Pomodoro with keyboard');
setMode('pomodoro');
break;
case '2':
event.preventDefault();
logDebug('β¨οΈ Switch to Short Break with keyboard');
setMode('short-break');
break;
case '3':
event.preventDefault();
logDebug('β¨οΈ Switch to Long Break with keyboard');
setMode('long-break');
break;
}
});
logDebug('π§ Event listeners setup completed');
} catch (error) {
logDebug('β Error setting up event listeners', {
error: error.message,
stack: error.stack
});
}
}
// π― Initialize accessibility attributes
function initializeAccessibility() {
// Time display
timeDisplay.setAttribute('role', 'timer');
timeDisplay.setAttribute('aria-live', 'polite');
timeDisplay.setAttribute('aria-atomic', 'true');
// Control buttons
startBtn.setAttribute('aria-label', 'Start the timer');
pauseBtn.setAttribute('aria-label', 'Pause the timer');
resetBtn.setAttribute('aria-label', 'Reset the timer to initial time');
// Mode buttons
pomodoroBtn.setAttribute('aria-label', 'Set Pomodoro mode - 25 minutes focus');
pomodoroBtn.setAttribute('aria-pressed', 'true');
shortBreakBtn.setAttribute('aria-label', 'Set Short Break mode - 5 minutes break');
shortBreakBtn.setAttribute('aria-pressed', 'false');
longBreakBtn.setAttribute('aria-label', 'Set Long Break mode - 15 minutes break');
longBreakBtn.setAttribute('aria-pressed', 'false');
logDebug('βΏ Accessibility features initialized');
}
// π― Request notification permission
function initializeNotifications() {
if ('Notification' in window && Notification.permission === 'default') {
Notification.requestPermission().then(permission => {
logDebug('π Notification permission status', { permission: permission });
});
}
}
// π― Initialize the application
function initializeApp() {
initializeAccessibility();
initializeNotifications();
setupEventListeners();
updateDisplay();
updateButtonStates();
const loadDuration = trackPerformance('App Initialization', loadStartTime);
logDebug('β
Pomodoro timer fully initialized', {
loadTime: `${loadDuration.toFixed(2)}ms`,
initialMode: currentMode,
initialTime: timeRemaining
});
}
// Start the application
initializeApp();
// π― Cleanup on page unload
window.addEventListener('beforeunload', () => {
if (timerInterval) {
clearInterval(timerInterval);
}
logDebug('π§Ή Timer cleanup performed', {
sessionsCompleted: sessionStats.pomodorosCompleted,
totalFocusTime: sessionStats.totalFocusTime,
totalSessions: sessionStats.sessions.length
});
});
});