-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2579 lines (2158 loc) · 99.8 KB
/
script.js
File metadata and controls
2579 lines (2158 loc) · 99.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
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 TimeTracker {
constructor() {
this.currentSession = null;
this.startTime = null;
this.endTime = null;
this.isRunning = false;
this.isPaused = false;
this.pausedTime = 0;
this.currentProject = 'general';
this.projects = this.loadProjects();
this.dailyData = this.loadDailyData();
this.streak = this.loadStreak();
this.dailyGoal = this.loadDailyGoal();
// Break reminder properties
this.breakSettings = this.loadBreakSettings();
this.lastBreakTime = this.loadLastBreakTime();
this.breakInterval = null;
this.breakCountdownInterval = null;
this.isOnBreak = false;
this.breakPostponeCount = 0;
// Calendar properties
this.currentCalendarMonth = new Date();
this.daySettings = this.loadDaySettings();
this.selectedDate = null;
// Section visibility state
this.sectionVisibility = this.loadSectionVisibility();
// Full focus mode properties
this.focusMode = false;
this.focusGoalTime = 90 * 60 * 1000; // Default 1.5 hours
this.wakeLock = null; // Add wake lock property for preventing sleep mode
this.initializeElements();
this.initializeEventListeners();
this.initializeDragAndDrop();
this.updateDisplay();
this.updateStats();
this.updateProjectSelector();
this.initializeBreakReminders();
this.loadTheme();
this.startDisplayTimer();
this.startRealTimeClock();
// Remove automatic notification permission request
// this.requestNotificationPermission();
this.renderCalendar();
this.initializeSectionVisibility();
}
initializeElements() {
// Timer elements
this.mainTimer = document.getElementById('mainTimer');
this.startBtn = document.getElementById('startBtn');
this.pauseBtn = document.getElementById('pauseBtn');
this.stopBtn = document.getElementById('stopBtn');
this.sessionStatus = document.getElementById('sessionStatus');
// Break reminder elements
this.breakReminder = document.getElementById('breakReminder');
this.breakCountdown = document.getElementById('breakCountdown');
this.breakActions = document.getElementById('breakActions');
this.takeBreakBtn = document.getElementById('takeBreakBtn');
this.postponeBreakBtn = document.getElementById('postponeBreakBtn');
// Project elements
this.currentProjectSelect = document.getElementById('currentProject');
this.addProjectBtn = document.getElementById('addProjectBtn');
this.projectsGrid = document.getElementById('projectsGrid');
// Modal elements
this.modalOverlay = document.getElementById('modalOverlay');
this.modalClose = document.getElementById('modalClose');
this.projectForm = document.getElementById('projectForm');
this.cancelBtn = document.getElementById('cancelBtn');
// Stats elements
this.todayTotal = document.getElementById('todayTotal');
this.projectCount = document.getElementById('projectCount');
this.streakCount = document.getElementById('streakCount');
// Historical elements
this.weekTotal = document.getElementById('weekTotal');
this.monthTotal = document.getElementById('monthTotal');
this.totalHours = document.getElementById('totalHours');
this.activeDays = document.getElementById('activeDays');
this.balanceValue = document.getElementById('balanceValue');
this.balanceDescription = document.getElementById('balanceDescription');
this.balanceFill = document.getElementById('balanceFill');
// Data management elements
this.exportDataBtn = document.getElementById('exportDataBtn');
this.importDataBtn = document.getElementById('importDataBtn');
this.importFileInput = document.getElementById('importFileInput');
// Project edit elements
this.projectEditModalOverlay = document.getElementById('projectEditModalOverlay');
this.projectEditModalClose = document.getElementById('projectEditModalClose');
this.projectEditForm = document.getElementById('projectEditForm');
this.editProjectName = document.getElementById('editProjectName');
this.editProjectColor = document.getElementById('editProjectColor');
this.editProjectGoalHours = document.getElementById('editProjectGoalHours');
this.editProjectGoalMinutes = document.getElementById('editProjectGoalMinutes');
this.editProjectTime = document.getElementById('editProjectTime');
this.editProjectSessions = document.getElementById('editProjectSessions');
this.deleteProjectBtn = document.getElementById('deleteProjectBtn');
this.editCancelBtn = document.getElementById('editCancelBtn');
this.currentEditingProjectId = null;
// Settings elements
this.settingsBtn = document.getElementById('settingsBtn');
this.settingsModalOverlay = document.getElementById('settingsModalOverlay');
this.settingsModalClose = document.getElementById('settingsModalClose');
this.natureThemeBtn = document.getElementById('natureThemeBtn');
this.spaceThemeBtn = document.getElementById('spaceThemeBtn');
this.breakRemindersEnabled = document.getElementById('breakRemindersEnabled');
this.breakIntervalHours = document.getElementById('breakIntervalHours');
this.breakIntervalMinutes = document.getElementById('breakIntervalMinutes');
this.breakNotificationsEnabled = document.getElementById('breakNotificationsEnabled');
this.autoStartEnabled = document.getElementById('autoStartEnabled');
// Clear data button
this.clearDataBtn = document.getElementById('clearDataBtn');
// Current time elements
this.currentTime = document.getElementById('currentTime');
this.currentDate = document.getElementById('currentDate');
// Goal elements
this.setDailyGoalBtn = document.getElementById('setDailyGoalBtn');
this.dailyGoalModalOverlay = document.getElementById('dailyGoalModalOverlay');
this.dailyGoalModalClose = document.getElementById('dailyGoalModalClose');
this.dailyGoalForm = document.getElementById('dailyGoalForm');
this.dailyGoalCancelBtn = document.getElementById('dailyGoalCancelBtn');
this.dailyGoalTime = document.getElementById('dailyGoalTime');
this.dailyProgressFill = document.getElementById('dailyProgressFill');
this.dailyProgressText = document.getElementById('dailyProgressText');
// Calendar elements
this.prevMonthBtn = document.getElementById('prevMonthBtn');
this.nextMonthBtn = document.getElementById('nextMonthBtn');
this.currentMonth = document.getElementById('currentMonth');
this.calendarDays = document.getElementById('calendarDays');
// Day settings modal elements
this.daySettingsModalOverlay = document.getElementById('daySettingsModalOverlay');
this.daySettingsModalClose = document.getElementById('daySettingsModalClose');
this.daySettingsTitle = document.getElementById('daySettingsTitle');
this.selectedDate = document.getElementById('selectedDate');
this.dayTrackedTime = document.getElementById('dayTrackedTime');
this.isWorkDay = document.getElementById('isWorkDay');
this.dayGoalHours = document.getElementById('dayGoalHours');
this.dayGoalMinutes = document.getElementById('dayGoalMinutes');
this.dayNote = document.getElementById('dayNote');
this.goalSettingGroup = document.getElementById('goalSettingGroup');
// Section toggle elements
this.currentSessionToggle = document.getElementById('currentSessionToggle');
this.dailySummaryToggle = document.getElementById('dailySummaryToggle');
this.projectsToggle = document.getElementById('projectsToggle');
this.historicalToggle = document.getElementById('historicalToggle');
this.calendarToggle = document.getElementById('calendarToggle');
// Section content elements
this.currentSessionContent = document.getElementById('currentSessionContent');
this.dailySummaryContent = document.getElementById('dailySummaryContent');
this.projectsContent = document.getElementById('projectsContent');
this.historicalContent = document.getElementById('historicalContent');
this.calendarContent = document.getElementById('calendarContent');
// Full focus mode elements
this.fullFocusBtn = document.getElementById('fullFocusBtn');
this.focusOverlay = document.getElementById('focusOverlay');
this.focusClose = document.getElementById('focusClose');
this.focusProjectName = document.getElementById('focusProjectName');
this.focusTimer = document.getElementById('focusTimer');
this.focusGoal = document.getElementById('focusGoal');
this.focusRemaining = document.getElementById('focusRemaining');
this.fuelFill = document.getElementById('fuelFill');
this.boosterFlames = document.getElementById('boosterFlames');
this.focusStartBtn = document.getElementById('focusStartBtn');
this.focusPauseBtn = document.getElementById('focusPauseBtn');
this.focusStopBtn = document.getElementById('focusStopBtn');
this.wakeLockStatus = document.getElementById('wakeLockStatus');
// Bulk edit elements
this.bulkEditBtn = document.getElementById('bulkEditBtn');
this.bulkEditModalOverlay = document.getElementById('bulkEditModalOverlay');
this.bulkEditModalClose = document.getElementById('bulkEditModalClose');
this.bulkStartDate = document.getElementById('bulkStartDate');
this.bulkEndDate = document.getElementById('bulkEndDate');
this.bulkMarkAsNoWork = document.getElementById('bulkMarkAsNoWork');
this.bulkNote = document.getElementById('bulkNote');
this.applyDateRangeBtn = document.getElementById('applyDateRangeBtn');
this.markWeekendsMonthBtn = document.getElementById('markWeekendsMonthBtn');
this.markWeekendsYearBtn = document.getElementById('markWeekendsYearBtn');
this.clearWeekendsMonthBtn = document.getElementById('clearWeekendsMonthBtn');
this.clearCurrentMonthBtn = document.getElementById('clearCurrentMonthBtn');
this.clearCurrentYearBtn = document.getElementById('clearCurrentYearBtn');
}
initializeEventListeners() {
// Timer controls
this.startBtn.addEventListener('click', () => this.startTimer());
this.pauseBtn.addEventListener('click', () => this.pauseTimer());
this.stopBtn.addEventListener('click', () => this.stopTimer());
// Break reminder controls
this.takeBreakBtn.addEventListener('click', () => this.startBreak());
this.postponeBreakBtn.addEventListener('click', () => this.postponeBreak());
// Project management
this.addProjectBtn.addEventListener('click', () => this.showAddProjectModal());
this.currentProjectSelect.addEventListener('change', (e) => {
this.currentProject = e.target.value;
});
// Modal controls
this.modalClose.addEventListener('click', () => this.hideAddProjectModal());
this.cancelBtn.addEventListener('click', () => this.hideAddProjectModal());
this.projectForm.addEventListener('submit', (e) => this.handleAddProject(e));
this.modalOverlay.addEventListener('click', (e) => {
if (e.target === this.modalOverlay) {
this.hideAddProjectModal();
}
});
// Settings controls
this.settingsBtn.addEventListener('click', () => this.showSettingsModal());
this.settingsModalClose.addEventListener('click', () => this.hideSettingsModal());
this.settingsModalOverlay.addEventListener('click', (e) => {
if (e.target === this.settingsModalOverlay) {
this.hideSettingsModal();
}
});
// Immediate settings event listeners
this.natureThemeBtn.addEventListener('click', () => {
this.selectTheme('nature');
this.applyTheme('nature');
});
this.spaceThemeBtn.addEventListener('click', () => {
this.selectTheme('space');
this.applyTheme('space');
});
this.breakRemindersEnabled.addEventListener('change', () => this.saveSettingsInstantly());
this.breakIntervalHours.addEventListener('change', () => this.saveSettingsInstantly());
this.breakIntervalMinutes.addEventListener('change', () => this.saveSettingsInstantly());
this.breakNotificationsEnabled.addEventListener('change', () => this.handleNotificationToggle());
this.autoStartEnabled.addEventListener('change', () => this.saveSettingsInstantly());
// Calendar controls
this.prevMonthBtn.addEventListener('click', () => this.previousMonth());
this.nextMonthBtn.addEventListener('click', () => this.nextMonth());
// Day settings modal
this.daySettingsModalClose.addEventListener('click', () => this.hideDaySettingsModal());
this.daySettingsModalOverlay.addEventListener('click', (e) => {
if (e.target === this.daySettingsModalOverlay) {
this.hideDaySettingsModal();
}
});
this.isWorkDay.addEventListener('change', () => this.toggleWorkDay());
this.dayGoalHours.addEventListener('change', () => this.saveDaySettings());
this.dayGoalMinutes.addEventListener('change', () => this.saveDaySettings());
this.dayNote.addEventListener('change', () => this.saveDaySettings());
// Section toggle controls
this.currentSessionToggle.addEventListener('click', () => this.toggleSection('currentSession'));
this.dailySummaryToggle.addEventListener('click', () => this.toggleSection('dailySummary'));
this.projectsToggle.addEventListener('click', () => this.toggleSection('projects'));
this.historicalToggle.addEventListener('click', () => this.toggleSection('historical'));
this.calendarToggle.addEventListener('click', () => this.toggleSection('calendar'));
// Clear data
this.clearDataBtn.addEventListener('click', () => this.clearAllData());
// Data management
this.exportDataBtn.addEventListener('click', () => this.exportData());
this.importDataBtn.addEventListener('click', () => this.importFileInput.click());
this.importFileInput.addEventListener('change', (e) => this.importData(e));
// Project editing
this.projectEditModalClose.addEventListener('click', () => this.hideProjectEditModal());
this.editCancelBtn.addEventListener('click', () => this.hideProjectEditModal());
this.projectEditForm.addEventListener('submit', (e) => this.handleEditProject(e));
this.deleteProjectBtn.addEventListener('click', () => this.handleDeleteProject());
this.projectEditModalOverlay.addEventListener('click', (e) => {
if (e.target === this.projectEditModalOverlay) {
this.hideProjectEditModal();
}
});
// Goal management
this.setDailyGoalBtn.addEventListener('click', () => this.showDailyGoalModal());
this.dailyGoalModalClose.addEventListener('click', () => this.hideDailyGoalModal());
this.dailyGoalCancelBtn.addEventListener('click', () => this.hideDailyGoalModal());
this.dailyGoalForm.addEventListener('submit', (e) => this.handleSetDailyGoal(e));
this.dailyGoalModalOverlay.addEventListener('click', (e) => {
if (e.target === this.dailyGoalModalOverlay) {
this.hideDailyGoalModal();
}
});
// Full focus mode controls
this.fullFocusBtn.addEventListener('click', () => this.showFocusMode());
this.focusClose.addEventListener('click', () => this.hideFocusMode());
this.focusOverlay.addEventListener('click', (e) => {
if (e.target === this.focusOverlay) {
this.hideFocusMode();
}
});
this.focusStartBtn.addEventListener('click', () => this.startTimer());
this.focusPauseBtn.addEventListener('click', () => this.pauseTimer());
this.focusStopBtn.addEventListener('click', () => this.stopTimer());
// Bulk edit calendar controls
this.bulkEditBtn.addEventListener('click', () => this.showBulkEditModal());
this.bulkEditModalClose.addEventListener('click', () => this.hideBulkEditModal());
this.bulkEditModalOverlay.addEventListener('click', (e) => {
if (e.target === this.bulkEditModalOverlay) {
this.hideBulkEditModal();
}
});
// Date range application
this.applyDateRangeBtn.addEventListener('click', () => this.applyDateRange());
// Weekend management
this.markWeekendsMonthBtn.addEventListener('click', () => this.markWeekends('month'));
this.markWeekendsYearBtn.addEventListener('click', () => this.markWeekends('year'));
this.clearWeekendsMonthBtn.addEventListener('click', () => this.clearWeekends('month'));
// Data clearing
this.clearCurrentMonthBtn.addEventListener('click', () => this.clearCalendarData('month'));
this.clearCurrentYearBtn.addEventListener('click', () => this.clearCalendarData('year'));
// Holiday presets
document.addEventListener('click', (e) => {
if (e.target.classList.contains('holiday-preset')) {
const holiday = e.target.dataset.holiday;
this.applyHolidayPreset(holiday);
}
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey) {
switch(e.key) {
case ' ':
e.preventDefault();
if (this.isRunning && !this.isPaused) {
this.pauseTimer();
} else {
this.startTimer();
}
break;
case 'Enter':
e.preventDefault();
this.stopTimer();
break;
}
}
// Focus mode shortcuts
if (e.key === 'Escape' && this.focusMode) {
e.preventDefault();
this.hideFocusMode();
}
if (e.key === 'F11') {
e.preventDefault();
if (this.focusMode) {
this.hideFocusMode();
} else {
this.showFocusMode();
}
}
});
// Handle page visibility change for wake lock re-acquisition
document.addEventListener('visibilitychange', () => {
if (this.focusMode && !document.hidden && !this.wakeLock) {
// Tab became visible again and we're in focus mode but don't have wake lock
this.requestWakeLock();
}
});
}
startTimer() {
if (!this.isRunning) {
this.startTime = Date.now();
this.isRunning = true;
this.isPaused = false;
this.pausedTime = 0;
// Reset break if coming back from break
if (this.isOnBreak) {
this.isOnBreak = false;
this.breakActions.style.display = 'none';
this.breakReminder.classList.remove('break-due');
this.lastBreakTime = Date.now();
this.saveLastBreakTime();
}
} else if (this.isPaused) {
this.startTime = Date.now() - this.pausedTime;
this.isPaused = false;
}
this.updateButtonStates();
this.updateSessionStatus('Running', '#10b981');
this.startBreakCountdown();
// Rebuild projects grid to show active indicator
this.buildProjectsGrid();
document.body.classList.add('timer-active');
}
pauseTimer() {
if (this.isRunning && !this.isPaused) {
this.pausedTime = Date.now() - this.startTime;
this.isPaused = true;
this.updateButtonStates();
this.updateSessionStatus('Paused', '#f59e0b');
this.stopBreakCountdown();
document.body.classList.remove('timer-active');
}
}
stopTimer() {
if (this.isRunning) {
const sessionTime = this.isPaused ? this.pausedTime : Date.now() - this.startTime;
this.saveSession(sessionTime);
this.resetTimer();
this.stopBreakCountdown();
// Rebuild projects grid to remove active indicator and show final times
this.buildProjectsGrid();
}
}
resetTimer() {
this.isRunning = false;
this.isPaused = false;
this.startTime = null;
this.pausedTime = 0;
this.updateButtonStates();
this.updateSessionStatus('Ready to work', '#10b981');
this.updateDisplay();
document.body.classList.remove('timer-active');
}
updateButtonStates() {
this.startBtn.disabled = this.isRunning && !this.isPaused;
this.pauseBtn.disabled = !this.isRunning || this.isPaused;
this.stopBtn.disabled = !this.isRunning;
// Update button text
if (this.isRunning && !this.isPaused) {
this.startBtn.innerHTML = '<i class="fas fa-play"></i> Running';
} else {
this.startBtn.innerHTML = '<i class="fas fa-play"></i> Start';
}
}
updateSessionStatus(text, color) {
this.sessionStatus.innerHTML = `<span class="status-indicator" style="background: ${color}"></span> ${text}`;
}
saveSession(duration) {
const session = {
project: this.currentProject,
duration: duration,
date: new Date().toDateString(),
timestamp: Date.now()
};
// Add to project data
if (!this.projects[this.currentProject]) {
this.projects[this.currentProject] = {
name: this.currentProject,
color: '#10b981',
totalTime: 0,
sessions: [],
goal: 0
};
}
this.projects[this.currentProject].totalTime += duration;
this.projects[this.currentProject].sessions.push(session);
// Add to daily data
const today = new Date().toDateString();
if (!this.dailyData[today]) {
this.dailyData[today] = 0;
}
this.dailyData[today] += duration;
// Update streak
this.updateStreak();
// Save to localStorage
this.saveData();
this.updateStats();
this.updateProjectsGrid();
this.renderCalendar();
this.initializeSectionVisibility();
}
updateStreak() {
const today = new Date().toDateString();
const yesterday = new Date(Date.now() - 86400000).toDateString();
if (this.dailyData[today] > 0) {
if (this.dailyData[yesterday] > 0 || this.streak === 0) {
this.streak++;
}
}
localStorage.setItem('timetracker_streak', this.streak.toString());
}
formatTime(milliseconds) {
const totalSeconds = Math.floor(milliseconds / 1000);
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
formatDuration(milliseconds) {
const totalMinutes = Math.floor(milliseconds / (1000 * 60));
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
if (hours > 0) {
return `${hours}h ${minutes}m`;
} else {
return `${minutes}m`;
}
}
updateDisplay() {
if (this.isRunning) {
const currentTime = this.isPaused ? this.pausedTime : Date.now() - this.startTime;
this.mainTimer.textContent = this.formatTime(currentTime);
// Update focus mode display
if (this.focusMode) {
this.updateFocusDisplay(currentTime);
}
// Update real-time daily progress during active session
this.updateRealTimeDailyProgress(currentTime);
// Update only the active project's time display (no rebuilding)
this.updateActiveProjectTime(currentTime);
} else {
this.mainTimer.textContent = '00:00:00';
// Update focus mode display
if (this.focusMode) {
this.updateFocusDisplay(0);
}
}
}
updateFocusDisplay(currentTime) {
const focusTime = currentTime - this.focusGoalTime;
const focusRemaining = this.focusGoalTime - focusTime;
if (focusRemaining > 0) {
this.focusRemaining.textContent = this.formatDuration(focusRemaining);
this.fuelFill.style.width = `${Math.min((focusRemaining / this.focusGoalTime) * 100, 100)}%`;
} else {
this.focusRemaining.textContent = 'Focus Time!';
this.fuelFill.style.width = '100%';
}
}
updateRealTimeDailyProgress(currentSessionTime = 0) {
// Get today's saved time
const today = new Date().toDateString();
const savedTodayTime = this.dailyData[today] || 0;
// Add current session time to get total time including active session
const totalTimeToday = savedTodayTime + currentSessionTime;
// Update today's total display
this.todayTotal.textContent = this.formatDuration(totalTimeToday);
// Update daily goal progress if goal is set
if (this.dailyGoal > 0) {
const progress = Math.min((totalTimeToday / this.dailyGoal) * 100, 100);
this.dailyProgressFill.style.width = `${progress}%`;
if (progress >= 100) {
this.dailyProgressText.textContent = '🎉 Goal Completed!';
this.dailyProgressFill.style.background = 'linear-gradient(90deg, #8fb68f 0%, #7ba87b 100%)';
} else {
this.dailyProgressText.textContent = `${Math.round(progress)}%`;
}
}
}
updateActiveProjectTime(currentSessionTime = 0) {
if (!this.isRunning || currentSessionTime <= 0) return;
// Find the active project card and update only its time-related elements
const projectCards = this.projectsGrid.querySelectorAll('.project-card');
projectCards.forEach((card, index) => {
const projectId = Object.keys(this.projects)[index];
const project = this.projects[projectId];
if (projectId === this.currentProject) {
// Update time display
const timeElement = card.querySelector('.project-time');
const sessionsElement = card.querySelector('.project-sessions');
const progressFill = card.querySelector('.project-progress-fill');
const progressText = card.querySelector('.project-progress-text');
if (timeElement) {
const displayTime = project.totalTime + currentSessionTime;
timeElement.textContent = this.formatDuration(displayTime);
}
if (sessionsElement) {
const sessionNote = ` (+${this.formatDuration(currentSessionTime)} current session)`;
sessionsElement.textContent = `${project.sessions.length} sessions${sessionNote}`;
}
// Update goal progress if exists
if (progressFill && progressText && project.goal > 0) {
const displayTime = project.totalTime + currentSessionTime;
const progress = Math.min((displayTime / project.goal) * 100, 100);
const progressTextContent = progress >= 100 ? '🎉 Complete!' : `${Math.round(progress)}%`;
progressFill.style.width = `${progress}%`;
progressText.textContent = progressTextContent;
}
}
});
}
startDisplayTimer() {
setInterval(() => {
this.updateDisplay();
}, 1000);
}
startRealTimeClock() {
// Update immediately
this.updateCurrentDateTime();
// Update every second
setInterval(() => {
this.updateCurrentDateTime();
}, 1000);
}
updateCurrentDateTime() {
const now = new Date();
// Format time (HH:MM:SS)
const timeString = now.toLocaleTimeString('en-US', {
hour12: false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
// Format date
const dateString = now.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
// Update DOM elements
if (this.currentTime) {
this.currentTime.textContent = timeString;
}
if (this.currentDate) {
this.currentDate.textContent = dateString;
}
}
updateStats() {
// Update real-time daily progress (this will handle today's total and goal progress)
this.updateRealTimeDailyProgress();
// Project count
this.projectCount.textContent = Object.keys(this.projects).length;
// Streak
this.streakCount.textContent = this.streak;
// Historical stats
this.updateHistoricalStats();
// Time balance
this.updateTimeBalance();
// Update goal displays
this.updateDailyGoalDisplay();
}
updateHistoricalStats() {
const now = new Date();
// Calculate week total (Monday to Sunday)
const startOfWeek = new Date(now);
const day = startOfWeek.getDay();
const diff = startOfWeek.getDate() - day + (day === 0 ? -6 : 1); // Adjust for Monday start
startOfWeek.setDate(diff);
startOfWeek.setHours(0, 0, 0, 0);
let weekTotal = 0;
for (let i = 0; i < 7; i++) {
const date = new Date(startOfWeek);
date.setDate(startOfWeek.getDate() + i);
const dateString = date.toDateString();
weekTotal += this.dailyData[dateString] || 0;
}
// Calculate month total
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
let monthTotal = 0;
const today = new Date();
for (let d = new Date(startOfMonth); d <= today; d.setDate(d.getDate() + 1)) {
const dateString = d.toDateString();
monthTotal += this.dailyData[dateString] || 0;
}
// Calculate all-time total
let allTimeTotal = 0;
let activeDaysCount = 0;
Object.values(this.dailyData).forEach(time => {
allTimeTotal += time;
if (time > 0) activeDaysCount++;
});
// Update displays
this.weekTotal.textContent = this.formatDuration(weekTotal);
this.monthTotal.textContent = this.formatDuration(monthTotal);
this.totalHours.textContent = this.formatDuration(allTimeTotal);
this.activeDays.textContent = activeDaysCount;
}
updateTimeBalance() {
if (this.dailyGoal <= 0) {
this.balanceValue.textContent = 'No goal set';
this.balanceDescription.textContent = 'Set a daily goal to track balance';
this.balanceFill.style.width = '0%';
this.balanceFill.className = 'balance-fill neutral';
return;
}
// Calculate balance over last 30 days
const now = new Date();
let totalWorked = 0;
let totalGoal = 0;
let daysWithGoal = 0;
for (let i = 0; i < 30; i++) {
const date = new Date(now);
date.setDate(now.getDate() - i);
const dateString = date.toDateString();
const dayWorked = this.dailyData[dateString] || 0;
totalWorked += dayWorked;
// Only count days with work toward goal calculation
if (dayWorked > 0) {
totalGoal += this.dailyGoal;
daysWithGoal++;
}
}
const balance = totalWorked - totalGoal;
const isPositive = balance >= 0;
const isNeutral = Math.abs(balance) < (30 * 60 * 1000); // Less than 30 minutes difference
// Update balance display
const balanceFormatted = this.formatDuration(Math.abs(balance));
this.balanceValue.textContent = `${isPositive ? '+' : '-'}${balanceFormatted}`;
// Update styling
this.balanceValue.className = `balance-value ${isNeutral ? 'neutral' : isPositive ? 'positive' : 'negative'}`;
this.balanceFill.className = `balance-fill ${isNeutral ? 'neutral' : isPositive ? 'positive' : 'negative'}`;
// Update description
if (isNeutral) {
this.balanceDescription.textContent = 'Perfectly balanced!';
} else if (isPositive) {
this.balanceDescription.textContent = 'Ahead of your goals! 🎉';
} else {
this.balanceDescription.textContent = 'Behind your goals. Keep going! 💪';
}
// Update progress bar
const maxBalance = this.dailyGoal * 7; // One week worth of goals
const balancePercent = Math.min(Math.abs(balance) / maxBalance * 50, 50); // 50% max width
this.balanceFill.style.width = `${balancePercent}%`;
}
updateProjectSelector() {
const currentValue = this.currentProjectSelect.value;
this.currentProjectSelect.innerHTML = '';
Object.keys(this.projects).forEach(projectId => {
const option = document.createElement('option');
option.value = projectId;
option.textContent = this.projects[projectId].name;
this.currentProjectSelect.appendChild(option);
});
// Restore selection or set to first project
if (currentValue && this.projects[currentValue]) {
this.currentProjectSelect.value = currentValue;
} else if (Object.keys(this.projects).length > 0) {
this.currentProjectSelect.value = Object.keys(this.projects)[0];
this.currentProject = Object.keys(this.projects)[0];
}
}
updateProjectsGrid() {
// Full rebuild of projects grid (only when needed)
this.buildProjectsGrid();
}
buildProjectsGrid() {
this.projectsGrid.innerHTML = '';
Object.keys(this.projects).forEach(projectId => {
const project = this.projects[projectId];
const projectCard = document.createElement('div');
projectCard.className = 'project-card';
projectCard.dataset.projectId = projectId; // Add data attribute for identification
let goalProgressHtml = '';
if (project.goal && project.goal > 0) {
const progress = Math.min((project.totalTime / project.goal) * 100, 100);
const progressText = progress >= 100 ? '🎉 Complete!' : `${Math.round(progress)}%`;
goalProgressHtml = `
<div class="project-goal-progress">
<div class="project-goal-info">
<span class="project-goal-label">Goal:</span>
<span class="project-goal-time">${this.formatDuration(project.goal)}</span>
</div>
<div class="project-progress-bar">
<div class="project-progress-fill" style="width: ${progress}%"></div>
</div>
<div class="project-progress-text">${progressText}</div>
</div>
`;
}
// Add active session indicator if this project is currently being worked on
const activeIndicator = (this.isRunning && this.currentProject === projectId)
? '<div class="project-active-indicator">🔥 Active</div>'
: '';
// Add edit buttons (don't show for general project or if it's the active project)
const canEdit = projectId !== 'general' && (!this.isRunning || this.currentProject !== projectId);
const editButtons = canEdit ? `
<div class="project-actions">
<button class="project-action-btn" onclick="timeTracker.showProjectEditModal('${projectId}')">
<i class="fas fa-edit"></i> Edit
</button>
</div>
` : '';
projectCard.innerHTML = `
<div class="project-header">
<div class="project-color" style="background: ${project.color}"></div>
<div class="project-name">${project.name}</div>
${editButtons}
</div>
${activeIndicator}
<div class="project-time">${this.formatDuration(project.totalTime)}</div>
<div class="project-sessions">${project.sessions.length} sessions</div>
${goalProgressHtml}
`;
this.projectsGrid.appendChild(projectCard);
});
}
showAddProjectModal() {
this.modalOverlay.classList.add('active');
document.getElementById('projectName').focus();
}
hideAddProjectModal() {
this.modalOverlay.classList.remove('active');
this.projectForm.reset();
}
handleAddProject(e) {
e.preventDefault();
const projectName = document.getElementById('projectName').value.trim();
const projectColor = document.getElementById('projectColor').value;
const goalHours = parseInt(document.getElementById('projectGoalHours').value) || 0;
const goalMinutes = parseInt(document.getElementById('projectGoalMinutes').value) || 0;
const goalTime = (goalHours * 60 + goalMinutes) * 60 * 1000; // Convert to milliseconds
if (projectName) {
const projectId = projectName.toLowerCase().replace(/\s+/g, '-');
this.projects[projectId] = {
name: projectName,
color: projectColor,
totalTime: 0,
sessions: [],
goal: goalTime
};
this.saveData();
this.updateProjectSelector();
this.updateProjectsGrid();
this.updateStats();
this.hideAddProjectModal();
}
}
toggleTheme() {
// This method is no longer used - theme switching is now handled in settings
}
clearAllData() {
if (confirm('Are you sure you want to clear all data? This cannot be undone.')) {
localStorage.removeItem('timetracker_projects');
localStorage.removeItem('timetracker_daily');
localStorage.removeItem('timetracker_streak');
localStorage.removeItem('timetracker_daily_goal');
localStorage.removeItem('timetracker_break_settings');
localStorage.removeItem('timetracker_last_break');
localStorage.removeItem('timetracker_day_settings');
localStorage.removeItem('timetracker_section_visibility');
this.projects = { general: { name: 'General Work', color: '#10b981', totalTime: 0, sessions: [], goal: 0 } };
this.dailyData = {};
this.streak = 0;
this.dailyGoal = 0;
this.daySettings = {};
this.breakSettings = this.loadBreakSettings();
this.lastBreakTime = Date.now();
this.sectionVisibility = this.loadSectionVisibility();
this.resetTimer();
this.updateProjectSelector();
this.updateProjectsGrid();
this.updateStats();
this.updateDailyGoalDisplay();
this.initializeBreakReminders();
this.renderCalendar();
this.initializeSectionVisibility();
}
}
saveData() {
localStorage.setItem('timetracker_projects', JSON.stringify(this.projects));
localStorage.setItem('timetracker_daily', JSON.stringify(this.dailyData));
localStorage.setItem('timetracker_streak', this.streak.toString());
localStorage.setItem('timetracker_daily_goal', this.dailyGoal.toString());
localStorage.setItem('timetracker_break_settings', JSON.stringify(this.breakSettings));
localStorage.setItem('timetracker_last_break', this.lastBreakTime.toString());
localStorage.setItem('timetracker_day_settings', JSON.stringify(this.daySettings));
}
loadProjects() {
const saved = localStorage.getItem('timetracker_projects');
if (saved) {
return JSON.parse(saved);
}
return {
general: {
name: 'General Work',
color: '#10b981',
totalTime: 0,
sessions: [],
goal: 0
}
};
}
loadDailyData() {
const saved = localStorage.getItem('timetracker_daily');
return saved ? JSON.parse(saved) : {};
}
loadStreak() {
const saved = localStorage.getItem('timetracker_streak');
return saved ? parseInt(saved) : 0;