Skip to content

Commit 7812924

Browse files
committed
refactor: streamline session data retrieval and initialization logic in navigation and main modules
1 parent 2d6cac5 commit 7812924

File tree

3 files changed

+83
-75
lines changed

3 files changed

+83
-75
lines changed

src/core/pomodoro-timer.js

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -507,7 +507,7 @@ export class PomodoroTimer {
507507
this.updateDisplay();
508508
this.updateButtons();
509509
this.updateTrayIcon();
510-
510+
511511
// Clear the resume flag after UI update
512512
this._justResumedFromAutoPause = false;
513513

@@ -534,7 +534,7 @@ export class PomodoroTimer {
534534
// Update display to remove (Auto-paused) status
535535
this.updateDisplay();
536536
this.updateButtons();
537-
537+
538538
console.log('🎯 Resume complete, timer should be running normally');
539539
}
540540

@@ -579,7 +579,7 @@ export class PomodoroTimer {
579579

580580
this.isRunning = true;
581581
this.isPaused = false;
582-
582+
583583
// Set flag to ensure status update when resuming from manual pause
584584
if (wasResuming) {
585585
this._justResumedFromPause = true;
@@ -603,12 +603,12 @@ export class PomodoroTimer {
603603

604604
this.updateButtons();
605605
this.updateDisplay();
606-
606+
607607
// Clear the resume flag after UI update
608608
if (wasResuming) {
609609
this._justResumedFromPause = false;
610610
}
611-
611+
612612
if (this.enableSoundNotifications) {
613613
NotificationUtils.playNotificationSound();
614614
}
@@ -773,13 +773,13 @@ export class PomodoroTimer {
773773
if (this.timeRemaining < 0 && this.allowContinuousSessions) {
774774
shouldSaveSession = true;
775775
this.sessionCompletedButNotSaved = false;
776-
776+
777777
// Save overtime focus session to SessionManager as individual session
778778
// Only save if session lasted at least 1 minute
779-
if (this.currentMode === 'focus' && this.lastCompletedSessionTime > 60) {
779+
if (this.currentMode === 'focus' && this.lastCompletedSessionTime > 3) {
780780
await this.saveCompletedFocusSession();
781781
}
782-
782+
783783
// Move to next mode as usual
784784
if (this.currentMode === 'focus') {
785785
if (this.completedPomodoros % 4 === 0) {
@@ -798,7 +798,6 @@ export class PomodoroTimer {
798798
this.updateButtons();
799799
if (shouldSaveSession) {
800800
this.saveSessionData();
801-
this.updateWeeklyStats();
802801
}
803802
const messages = {
804803
focus: 'Focus session skipped. Time for a break! 😌',
@@ -823,7 +822,7 @@ export class PomodoroTimer {
823822
const actualElapsedTime = this.currentSessionElapsedTime || (this.durations.focus - this.timeRemaining);
824823
this.totalFocusTime += actualElapsedTime;
825824
this.lastCompletedSessionTime = actualElapsedTime;
826-
825+
827826
// Save skipped focus session to SessionManager as individual session
828827
// Only save if session lasted at least 1 minute
829828
if (this.lastCompletedSessionTime > 60) {
@@ -854,7 +853,6 @@ export class PomodoroTimer {
854853
this.updateButtons();
855854
if (shouldSaveSession) {
856855
this.saveSessionData();
857-
this.updateWeeklyStats();
858856
}
859857
const messages = {
860858
focus: 'Focus session skipped. Time for a break! 😌',
@@ -949,14 +947,14 @@ export class PomodoroTimer {
949947
this.timeRemaining = this.durations[this.currentMode];
950948
this.updateDisplay();
951949
this.updateButtons();
952-
950+
953951
// Save completed focus session to SessionManager as individual session
954952
if (this.lastCompletedSessionTime > 0 && this.completedPomodoros > 0) {
955953
await this.saveCompletedFocusSession();
956954
}
957-
955+
956+
// Only save aggregated session data, individual sessions are handled by saveCompletedFocusSession
958957
await this.saveSessionData();
959-
await this.updateWeeklyStats();
960958
this.showNotification();
961959
if (this.enableSoundNotifications) {
962960
NotificationUtils.playNotificationSound();
@@ -1047,7 +1045,7 @@ export class PomodoroTimer {
10471045

10481046
// Mark session as completed but not saved yet (will be saved when user skips)
10491047
this.sessionCompletedButNotSaved = true;
1050-
1048+
10511049
// Save completed focus session to SessionManager immediately
10521050
await this.saveCompletedFocusSession();
10531051
}
@@ -1528,7 +1526,6 @@ export class PomodoroTimer {
15281526
this.updateProgressDots();
15291527
this.updateButtons();
15301528
await this.saveSessionData();
1531-
await this.updateWeeklyStats();
15321529
this.updateTrayIcon();
15331530

15341531
// Show undo notification
@@ -1839,7 +1836,7 @@ export class PomodoroTimer {
18391836

18401837
const now = new Date();
18411838
const durationMinutes = Math.round(this.lastCompletedSessionTime / 60);
1842-
1839+
18431840
// Calculate session end time (now) and start time (backwards from duration)
18441841
const endHour = now.getHours();
18451842
const endMinute = now.getMinutes();

src/main.js

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,8 +1065,7 @@ function setupAuthEventListeners() {
10651065
if (guestBtn) {
10661066
guestBtn.addEventListener('click', async () => {
10671067
window.authManager.continueAsGuest();
1068-
await hideAuthScreen();
1069-
initializeApplication(); // Continue with app initialization
1068+
// hideAuthScreen and initializeApplication will be handled by onAuthChange listener
10701069
});
10711070
}
10721071

@@ -1076,21 +1075,14 @@ function setupAuthEventListeners() {
10761075
guestLink.addEventListener('click', async (e) => {
10771076
e.preventDefault();
10781077
window.authManager.continueAsGuest();
1079-
await hideAuthScreen();
1080-
initializeApplication(); // Continue with app initialization
1078+
// hideAuthScreen and initializeApplication will be handled by onAuthChange listener
10811079
});
10821080
}
10831081

10841082
// Listen for auth state changes
10851083
if (window.authManager) {
10861084
window.authManager.onAuthChange(async (status, user) => {
1087-
if (status === 'authenticated') {
1088-
await hideAuthScreen();
1089-
// Only continue initialization if this is first run (app not yet initialized)
1090-
if (!window.pomodoroTimer) {
1091-
initializeApplication(); // Continue with app initialization
1092-
}
1093-
} else if (status === 'guest') {
1085+
if (status === 'authenticated' || status === 'guest') {
10941086
await hideAuthScreen();
10951087
// Only continue initialization if this is first run (app not yet initialized)
10961088
if (!window.pomodoroTimer) {
@@ -1437,8 +1429,15 @@ function setupUserAvatarEventListeners() {
14371429

14381430
// Initialize the application
14391431
async function initializeApplication() {
1432+
// Prevent double initialization
1433+
if (window._appInitialized) {
1434+
console.log('🚀 Application already initialized, skipping...');
1435+
return;
1436+
}
1437+
14401438
try {
14411439
console.log('🚀 Initializing Presto application...');
1440+
window._appInitialized = true;
14421441

14431442
// Initialize theme as early as possible
14441443
await initializeEarlyTheme();
@@ -1520,6 +1519,9 @@ async function initializeApplication() {
15201519
} catch (error) {
15211520
console.error('❌ Failed to initialize application:', error);
15221521
NotificationUtils.showNotificationPing('Failed to initialize app. Please refresh! 🔄', 'error');
1522+
1523+
// Reset initialization flag on error so user can retry
1524+
window._appInitialized = false;
15231525
}
15241526
}
15251527

src/managers/navigation-manager.js

Lines changed: 56 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// Navigation Manager for Sidebar
2-
const { invoke } = window.__TAURI__.core;
32
import { TimeUtils } from '../utils/common-utils.js';
43

54
export class NavigationManager {
@@ -183,7 +182,6 @@ export class NavigationManager {
183182
let previousWeeklySessions = 0;
184183

185184
try {
186-
const history = await invoke('get_stats_history');
187185
const weekStart = this.getWeekStart(this.currentDate);
188186
const previousWeekStart = new Date(weekStart);
189187
previousWeekStart.setDate(weekStart.getDate() - 7);
@@ -195,14 +193,25 @@ export class NavigationManager {
195193
for (let i = 0; i < 7; i++) {
196194
const date = new Date(weekStart);
197195
date.setDate(weekStart.getDate() + i);
198-
const dayData = history.find(h => h.date === date.toDateString());
199-
if (dayData) {
200-
weekTotal += dayData.total_focus_time;
201-
weeklyFocusTime += dayData.total_focus_time;
202-
weeklySessions += dayData.completed_pomodoros;
203-
if (dayData.total_focus_time > 0) {
204-
daysWithData++;
205-
}
196+
197+
let dayTotalTime = 0;
198+
let daySessions = 0;
199+
200+
// Get sessions from SessionManager for this date
201+
if (window.sessionManager) {
202+
const sessions = window.sessionManager.getSessionsForDate(date);
203+
const focusSessions = sessions.filter(s => s.session_type === 'focus' || s.session_type === 'custom');
204+
205+
// Calculate total time in seconds from session durations
206+
dayTotalTime = focusSessions.reduce((total, session) => total + ((session.duration || 0) * 60), 0);
207+
daySessions = focusSessions.length;
208+
}
209+
210+
if (dayTotalTime > 0) {
211+
weekTotal += dayTotalTime;
212+
weeklyFocusTime += dayTotalTime;
213+
weeklySessions += daySessions;
214+
daysWithData++;
206215
}
207216
}
208217

@@ -215,14 +224,25 @@ export class NavigationManager {
215224
for (let i = 0; i < 7; i++) {
216225
const date = new Date(previousWeekStart);
217226
date.setDate(previousWeekStart.getDate() + i);
218-
const dayData = history.find(h => h.date === date.toDateString());
219-
if (dayData) {
220-
previousWeekTotal += dayData.total_focus_time;
221-
previousWeekFocusTime += dayData.total_focus_time;
222-
previousWeeklySessions += dayData.completed_pomodoros;
223-
if (dayData.total_focus_time > 0) {
224-
previousDaysWithData++;
225-
}
227+
228+
let dayTotalTime = 0;
229+
let daySessions = 0;
230+
231+
// Get sessions from SessionManager for this date
232+
if (window.sessionManager) {
233+
const sessions = window.sessionManager.getSessionsForDate(date);
234+
const focusSessions = sessions.filter(s => s.session_type === 'focus' || s.session_type === 'custom');
235+
236+
// Calculate total time in seconds from session durations
237+
dayTotalTime = focusSessions.reduce((total, session) => total + ((session.duration || 0) * 60), 0);
238+
daySessions = focusSessions.length;
239+
}
240+
241+
if (dayTotalTime > 0) {
242+
previousWeekTotal += dayTotalTime;
243+
previousWeekFocusTime += dayTotalTime;
244+
previousWeeklySessions += daySessions;
245+
previousDaysWithData++;
226246
}
227247
}
228248

@@ -417,7 +437,6 @@ export class NavigationManager {
417437
const maxHeight = 70;
418438

419439
try {
420-
const history = await invoke('get_stats_history');
421440
const weekStart = this.getWeekStart(this.currentDate);
422441
const today = new Date();
423442

@@ -433,20 +452,17 @@ export class NavigationManager {
433452
const date = new Date(weekStart);
434453
date.setDate(weekStart.getDate() + index);
435454

436-
// Get data from both timer history and SessionManager
437-
const dayData = history.find(h => h.date === date.toDateString());
438-
let sessionsMinutes = dayData ? dayData.total_focus_time / 60 : 0; // Convert seconds to minutes
439-
let sessions = dayData ? dayData.completed_pomodoros : 0;
455+
let sessionsMinutes = 0;
456+
let sessions = 0;
440457

441-
// Add sessions from SessionManager for this date
458+
// Get sessions from SessionManager for this date
442459
if (window.sessionManager) {
443-
const manualSessions = window.sessionManager.getSessionsForDate(date);
444-
const focusSessions = manualSessions.filter(s => s.session_type === 'focus' || s.session_type === 'custom');
460+
const allSessions = window.sessionManager.getSessionsForDate(date);
461+
const focusSessions = allSessions.filter(s => s.session_type === 'focus' || s.session_type === 'custom');
445462

446-
// Add minutes from manual/timer sessions
447-
const manualMinutes = focusSessions.reduce((total, session) => total + (session.duration || 0), 0);
448-
sessionsMinutes += manualMinutes;
449-
sessions += focusSessions.length;
463+
// Calculate total minutes from session durations
464+
sessionsMinutes = focusSessions.reduce((total, session) => total + (session.duration || 0), 0);
465+
sessions = focusSessions.length;
450466
}
451467

452468
// Only consider days that have completely passed (exclude today) for average calculation
@@ -460,7 +476,6 @@ export class NavigationManager {
460476
weekData.push({
461477
day,
462478
date,
463-
dayData,
464479
sessionsMinutes,
465480
sessions,
466481
isPast: date <= today
@@ -530,7 +545,7 @@ export class NavigationManager {
530545
}
531546

532547
// Second pass: create the bars with proportional scaling
533-
weekData.forEach(({ day, sessionsMinutes, sessions, dayData, isPast }) => {
548+
weekData.forEach(({ day, sessionsMinutes, sessions, isPast }) => {
534549
const dayBar = document.createElement('div');
535550
dayBar.className = 'week-day-bar';
536551

@@ -708,15 +723,6 @@ export class NavigationManager {
708723
const daysInMonth = lastDay.getDate();
709724
const startingDay = firstDay.getDay();
710725

711-
// Load session history for the month
712-
let history = [];
713-
try {
714-
history = await invoke('get_stats_history');
715-
} catch (error) {
716-
console.error('Failed to load calendar data:', error);
717-
// Continue with empty history
718-
}
719-
720726
// Add empty cells for days before month starts
721727
for (let i = 0; i < startingDay; i++) {
722728
const emptyDay = document.createElement('div');
@@ -740,16 +746,19 @@ export class NavigationManager {
740746
dayEl.classList.add('today');
741747
}
742748

743-
// Add session dots based on real data (if available)
749+
// Add session dots based on SessionManager data
744750
const dots = document.createElement('div');
745751
dots.className = 'calendar-day-dots';
746752

747-
if (history.length > 0) {
748-
const dayData = history.find(h => h.date === dayDate.toDateString());
749-
if (dayData && dayData.completed_pomodoros > 0) {
753+
// Get sessions from SessionManager for this date
754+
if (window.sessionManager) {
755+
const sessions = window.sessionManager.getSessionsForDate(dayDate);
756+
const focusSessions = sessions.filter(s => s.session_type === 'focus' || s.session_type === 'custom');
757+
758+
if (focusSessions.length > 0) {
750759
dayEl.classList.add('has-sessions');
751-
// Create dots for completed pomodoros
752-
const numDots = Math.min(dayData.completed_pomodoros, 5); // Max 5 dots
760+
// Create dots for completed focus sessions
761+
const numDots = Math.min(focusSessions.length, 5); // Max 5 dots
753762
for (let i = 0; i < numDots; i++) {
754763
const dot = document.createElement('div');
755764
dot.className = 'calendar-dot';

0 commit comments

Comments
 (0)