Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 16 additions & 16 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"axios": "^1.17.0",
"events": "^3.3.0",
"gd-eventlog": "^0.1.27",
"incyclist-services": "^1.9.27",
"incyclist-services": "^1.9.28",
"mqtt": "^5.15.2",
"path-browserify": "^1.0.1",
"process": "^0.11.10",
Expand Down
66 changes: 27 additions & 39 deletions src/hooks/workouts/useScheduledWorkoutPrompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,93 +4,81 @@ import { useScheduledWorkoutPrompt } from './useScheduledWorkoutPrompt';

const mockNavigate = jest.fn();

let appStateStore: Record<string, any>;
const mockGetState = jest.fn((key: string) => appStateStore[key]);
const mockSetState = jest.fn((key: string, value: any) => {
if (value === null) delete appStateStore[key];
else appStateStore[key] = value;
});

class FakeWorkoutCalendar extends EventEmitter {
getScheduledToday = jest.fn();
// Fake prompt page service: the once-per-session guard and the calendar lookup live in the
// service, so here `show` just returns what the service would decide.
class FakePromptService extends EventEmitter {
show = jest.fn();
onYes = jest.fn((prompt: any) => ({ page: 'workouts', autoOpenDetailsId: prompt.workoutId }));
onNo = jest.fn();
onCheckWorkouts = jest.fn(() => ({ page: 'workouts' }));
}
let mockCalendar: FakeWorkoutCalendar;
let mockService: FakePromptService;

jest.mock('incyclist-services', () => ({
useAppState: () => ({ getState: mockGetState, setState: mockSetState }),
useWorkoutCalendar: () => mockCalendar,
getScheduledWorkoutPromptPageService: () => mockService,
}));

jest.mock('../../services', () => ({
navigate: (...args: any[]) => mockNavigate(...args),
}));

jest.mock('../logging', () => ({
useLogging: () => ({ logEvent: jest.fn(), logError: jest.fn() }),
}));

const SCHEDULED = {
id: 'intervals:cal-entry-99', // calendar-entry composite id - must NOT be what's navigated with
name: 'VO2 Max Intervals',
type: 'scheduled',
workoutId: 'workout-42',
workout: { id: 'workout-42', name: 'VO2 Max Intervals' },
};
const PROMPT = { title: 'VO2 Max Intervals', workoutId: 'workout-42' };

describe('useScheduledWorkoutPrompt', () => {
beforeEach(() => {
jest.clearAllMocks();
appStateStore = {};
mockCalendar = new FakeWorkoutCalendar();
mockService = new FakePromptService();
});

it('shows nothing when no workout is scheduled today', () => {
mockCalendar.getScheduledToday.mockReturnValue(undefined);
mockService.show.mockReturnValue(null);
const { result } = renderHook(() => useScheduledWorkoutPrompt());
expect(result.current.prompt).toBeNull();
});

it('shows the prompt immediately when a workout is already scheduled at mount', () => {
mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
mockService.show.mockReturnValue(PROMPT);
const { result } = renderHook(() => useScheduledWorkoutPrompt());
expect(result.current.prompt).toEqual({ title: 'VO2 Max Intervals' });
});

it('sets the once-per-session guard as soon as the prompt is triggered', () => {
mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
// the guard is owned by the service: the hook must ask the service exactly once at mount
mockService.show.mockReturnValue(PROMPT);
renderHook(() => useScheduledWorkoutPrompt());
expect(mockSetState).toHaveBeenCalledWith('scheduledPromptShown', true);
expect(mockService.show).toHaveBeenCalledTimes(1);
});

it('does not show the prompt again once the guard is already set', () => {
appStateStore.scheduledPromptShown = true;
mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
// service returns null once its guard is set
mockService.show.mockReturnValue(null);
const { result } = renderHook(() => useScheduledWorkoutPrompt());
expect(result.current.prompt).toBeNull();
});

it('reacts to the calendar emitting "scheduled" after mount (async preload arrival)', () => {
mockCalendar.getScheduledToday.mockReturnValue(undefined);
mockService.show.mockReturnValue(null);
const { result } = renderHook(() => useScheduledWorkoutPrompt());
expect(result.current.prompt).toBeNull();

mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
mockService.show.mockReturnValue(PROMPT);
act(() => {
mockCalendar.emit('scheduled', SCHEDULED);
mockService.emit('scheduled', PROMPT);
});

expect(result.current.prompt).toEqual({ title: 'VO2 Max Intervals' });
});

it('does nothing while disabled (enabled=false), even with a workout scheduled and no guard', () => {
mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
mockService.show.mockReturnValue(PROMPT);
const { result } = renderHook(() => useScheduledWorkoutPrompt(false));
expect(result.current.prompt).toBeNull();
expect(mockSetState).not.toHaveBeenCalled();
expect(mockService.show).not.toHaveBeenCalled();
expect(mockService.listenerCount('scheduled')).toBe(0);
});

it('onYes navigates to workouts with the workout content id (not the calendar entry id) and clears the prompt', () => {
mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
mockService.show.mockReturnValue(PROMPT);
const { result } = renderHook(() => useScheduledWorkoutPrompt());

act(() => {
Expand All @@ -102,7 +90,7 @@ describe('useScheduledWorkoutPrompt', () => {
});

it('onNo just dismisses without navigating', () => {
mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
mockService.show.mockReturnValue(PROMPT);
const { result } = renderHook(() => useScheduledWorkoutPrompt());

act(() => {
Expand All @@ -114,7 +102,7 @@ describe('useScheduledWorkoutPrompt', () => {
});

it('onCheckWorkouts navigates to workouts with no auto-open param and dismisses', () => {
mockCalendar.getScheduledToday.mockReturnValue(SCHEDULED);
mockService.show.mockReturnValue(PROMPT);
const { result } = renderHook(() => useScheduledWorkoutPrompt());

act(() => {
Expand Down
98 changes: 34 additions & 64 deletions src/hooks/workouts/useScheduledWorkoutPrompt.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ScheduledWorkout, useAppState, useWorkoutCalendar } from 'incyclist-services';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { getScheduledWorkoutPromptPageService, ScheduledWorkoutPromptDisplayProps } from 'incyclist-services';
import { navigate } from '../../services';
import { useLogging } from '../logging';

// Once-per-app-session guard (workout-list-page-service-design.md §11.2). Deliberately kept in
// AppStateService's in-memory `state` (not `getPersistedState`/settings) - it must reset on every
// app launch, never survive to the next day, per the design's "no per-day persistence in Phase 1."
const SCHEDULED_PROMPT_GUARD_KEY = 'scheduledPromptShown';

export interface ScheduledWorkoutPromptState {
/** Workout name, for "You have <title> scheduled today - do you want to start it?" */
Expand All @@ -22,83 +16,59 @@ export interface UseScheduledWorkoutPromptResult {
}

/**
* Cross-cutting mobile-UI mechanism (workout-mobile-hld.md §3.1/§5,
* workout-list-page-service-design.md §11) - NOT owned by the Workouts feature. Meant to be
* called from every content page except `devices`/pairing (`routes`, `activities`, `workouts`,
* `search`, `main`).
* Cross-cutting mobile-UI mechanism - NOT owned by the Workouts feature. Meant to be called from
* every content page except `devices`/pairing (`routes`, `activities`, `workouts`, `search`, `main`).
*
* On first check per app session, if `WorkoutCalendarService.getScheduledToday()` returns a
* workout and the once-per-session guard hasn't fired yet, this surfaces a prompt: Yes navigates
* to the Workouts page with an auto-open param (consumed by `WorkoutsPage`'s
* `autoOpenDetailsId` -> `WorkoutDetailsDialog`), No just dismisses, Check workouts navigates to
* the Workouts page. `scheduledToday` is populated asynchronously by preload, so this also
* subscribes to the calendar service's `'scheduled'` event to catch it arriving after mount, not
* just what's already known at the moment this hook first runs.
* Thin wrapper around the scheduled-workout prompt page service, which decides whether a prompt is
* due (including the once-per-session guard). This hook only holds the visible prompt, re-checks
* when the service relays `'scheduled'` (calendar data arrives asynchronously) and performs the
* navigation intents: Yes opens the Workouts page with an auto-open param, Check workouts opens
* the Workouts page, No just dismisses.
*
* @param enabled Defaults to `true`. Pass `false` from a host that renders more than one
* navigation route (e.g. `NotImplementedPage` doubles as both `main`, which should trigger this,
* and `user`, which shouldn't) - keeps the hook call itself unconditional (Rules of Hooks) while
* suppressing its side effects (calendar check, guard, navigation) for the excluded route.
* suppressing its side effects (service call, subscription, navigation) for the excluded route.
*/
export const useScheduledWorkoutPrompt = (enabled: boolean = true): UseScheduledWorkoutPromptResult => {
const appState = useAppState();
const calendar = useWorkoutCalendar();
const { logEvent } = useLogging('ScheduledWorkoutPrompt');

const [prompt, setPrompt] = useState<ScheduledWorkoutPromptState | null>(null);

// Holds the id actually needed to re-open the details dialog. Deliberately NOT
// `scheduled.id` (WorkoutCalendarService.getScheduledWorkout()'s composite `source:workoutId`
// string) - `WorkoutListPageService.findWorkoutCard()`/`WorkoutCard.getId()` key cards by the
// plain `Workout.id` (same field `getUpcomingTrainingProps()`'s "Upcoming Training" rows
// already use for their own onOpenDetails calls). Passing the composite id through would
// silently fail the card lookup and leave `WorkoutDetailsDialog` unable to load anything.
const refWorkoutId = useRef<string | null>(null);

const checkAndShow = useCallback(() => {
if (!enabled) return;
if (appState.getState(SCHEDULED_PROMPT_GUARD_KEY)) return;

const scheduled: ScheduledWorkout | undefined = calendar.getScheduledToday();
if (!scheduled) return;

const workoutId = scheduled.workout?.id ?? scheduled.workoutId;
if (!workoutId) return;

refWorkoutId.current = workoutId;
// Set the guard the moment the prompt is triggered, not on a later per-action basis -
// matches workout-list-page-service-design.md §11.2 ("it triggers the popup and sets the
// guard") and is simpler/safer than three separate call sites all needing to remember it.
appState.setState(SCHEDULED_PROMPT_GUARD_KEY, true);
setPrompt({ title: scheduled.name });
logEvent({ message: 'scheduled workout prompt shown', workoutId });
}, [enabled, appState, calendar, logEvent]);
const [promptProps, setPromptProps] = useState<ScheduledWorkoutPromptDisplayProps | null>(null);

useEffect(() => {
if (!enabled) return;

const service = getScheduledWorkoutPromptPageService();
const checkAndShow = () => {
const props = service.show();
if (props) setPromptProps(props);
};

checkAndShow();

calendar.on('scheduled', checkAndShow);
service.on('scheduled', checkAndShow);
return () => {
calendar.off('scheduled', checkAndShow);
service.off('scheduled', checkAndShow);
};
}, [enabled, calendar, checkAndShow]);
}, [enabled]);

const onYes = useCallback(() => {
setPrompt(null);
const workoutId = refWorkoutId.current;
navigate('workouts', workoutId ? { autoOpenDetailsId: workoutId } : undefined);
}, []);
if (!promptProps) return;
const nav = getScheduledWorkoutPromptPageService().onYes(promptProps);
setPromptProps(null);
navigate(nav.page, nav.autoOpenDetailsId ? { autoOpenDetailsId: nav.autoOpenDetailsId } : undefined);
}, [promptProps]);

const onNo = useCallback(() => {
setPrompt(null);
}, []);
if (promptProps) getScheduledWorkoutPromptPageService().onNo(promptProps);
setPromptProps(null);
}, [promptProps]);

const onCheckWorkouts = useCallback(() => {
setPrompt(null);
navigate('workouts');
}, []);
const nav = promptProps ? getScheduledWorkoutPromptPageService().onCheckWorkouts(promptProps) : { page: 'workouts' as const };
setPromptProps(null);
navigate(nav.page);
}, [promptProps]);

const prompt = useMemo(() => (promptProps ? { title: promptProps.title } : null), [promptProps]);

return { prompt, onYes, onNo, onCheckWorkouts };
};
5 changes: 2 additions & 3 deletions src/pages/ActivitiesPage/ActivitiesPage.rideAgain.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ jest.mock('incyclist-services', () => ({
onCloseActivity: () => {},
onRideAgain: mockOnRideAgain,
}),
useAppState: () => ({ getState: jest.fn(), setState: jest.fn() }),
useWorkoutCalendar: () => ({
getScheduledToday: jest.fn(),
getScheduledWorkoutPromptPageService: () => ({
show: jest.fn(),
on: jest.fn(),
off: jest.fn(),
}),
Expand Down
9 changes: 4 additions & 5 deletions src/pages/ActivitiesPage/ActivitiesPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,10 @@ jest.mock('incyclist-services', () => ({
onCloseActivity: () => {},
onDeleteActivity: (id: string) => mockOnDeleteActivity(id),
}),
// Needed by useScheduledWorkoutPrompt (session 5.7), which every content page - including
// ActivitiesPage - now calls.
useAppState: () => ({ getState: jest.fn(), setState: jest.fn() }),
useWorkoutCalendar: () => ({
getScheduledToday: jest.fn(),
// Needed by useScheduledWorkoutPrompt, which every content page - including
// ActivitiesPage - calls.
getScheduledWorkoutPromptPageService: () => ({
show: jest.fn(),
on: jest.fn(),
off: jest.fn(),
}),
Expand Down
5 changes: 2 additions & 3 deletions src/pages/RoutesPage/RoutesPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,8 @@ jest.mock('incyclist-services', () => ({
onDownloadDelete: mockOnDownloadDelete,
onDownloadKeepInstead: mockOnDownloadKeepInstead,
}),
useAppState: () => ({ getState: jest.fn(), setState: jest.fn() }),
useWorkoutCalendar: () => ({
getScheduledToday: jest.fn(),
getScheduledWorkoutPromptPageService: () => ({
show: jest.fn(),
on: jest.fn(),
off: jest.fn(),
}),
Expand Down
Loading
Loading