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
121 changes: 121 additions & 0 deletions apps/web/src/features/routines/routines-landing.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/** Verifies the routine page's registered-user and guest-facing states. */
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react';
import type { PropsWithChildren } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { ApplicationIdentityContext } from '../../app/application-identity';
import { createPublicUser } from '../../test/fixtures/public-user.fixture';
import { RoutinesLanding } from './routines-landing';

afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});

function createWrapper(identity: 'guest' | 'user' = 'user') {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const identityValue =
identity === 'guest'
? ({ kind: 'guest' } as const)
: ({ kind: 'user', user: createPublicUser() } as const);

return function Wrapper({ children }: PropsWithChildren) {
return (
<QueryClientProvider client={queryClient}>
<ApplicationIdentityContext.Provider value={identityValue}>
{children}
</ApplicationIdentityContext.Provider>
</QueryClientProvider>
);
};
}

describe('routines landing', () => {
it('shows a localized loading state', () => {
vi.stubGlobal(
'fetch',
vi.fn(() => new Promise(() => {})),
);

render(<RoutinesLanding />, { wrapper: createWrapper() });

expect(screen.getByLabelText('Loading routines')).toBeVisible();
});

it('shows the documented empty state', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(Response.json({ routines: [] })),
);

render(<RoutinesLanding />, { wrapper: createWrapper() });

expect(await screen.findByText('No routines yet.')).toBeVisible();
expect(
screen.getByText('Create your first routine to get ready for liftoff.'),
).toBeVisible();
});

it('shows routine summaries returned by the API', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
Response.json({
routines: [
{
id: '26d34dc0-8e4c-4bd0-9e3b-7b839b44e486',
name: 'Upper Body',
description: 'Monday strength session',
exerciseCount: 3,
scheduledDays: [1, 3, 5],
createdAt: '2026-08-26T10:00:00.000Z',
updatedAt: '2026-08-26T10:00:00.000Z',
},
],
}),
),
);

render(<RoutinesLanding />, { wrapper: createWrapper() });

expect(
await screen.findByRole('heading', { name: 'Upper Body' }),
).toBeVisible();
expect(screen.getByText('3 exercises')).toBeVisible();
expect(screen.getByText('Mon, Wed, Fri')).toBeVisible();
});

it('shows a retry action after an API failure', async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(null, { status: 500 }))
.mockResolvedValueOnce(Response.json({ routines: [] }));
vi.stubGlobal('fetch', fetchMock);

render(<RoutinesLanding />, { wrapper: createWrapper() });

fireEvent.click(await screen.findByRole('button', { name: 'Try again' }));

await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
expect(await screen.findByText('No routines yet.')).toBeVisible();
});

it('does not request persistent routines for a guest', () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);

render(<RoutinesLanding />, { wrapper: createWrapper('guest') });

expect(screen.getByText('Guest routines are coming later.')).toBeVisible();
expect(fetchMock).not.toHaveBeenCalled();
});
});
172 changes: 172 additions & 0 deletions apps/web/src/features/routines/routines-landing.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
/** Displays the routine collection with intentional guest, loading, error, and empty states. */
import type { RoutineSummary } from '@goforlift/contracts';
import { CalendarDays, Dumbbell } from 'lucide-react';
import type { ReactNode } from 'react';

import { useApplicationIdentity } from '../../app/application-identity';
import { useRoutines } from './routines.query';

const DAY_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

export function RoutinesLanding() {
const identity = useApplicationIdentity();

const routineContent =
identity.kind === 'guest' ? (
<GuestRoutinesMessage />
) : (
<RegisteredUserRoutines />
);

return (
<section>
<RoutinesHeader />
{routineContent}
</section>
);
}

function RoutinesHeader() {
return (
<header className="mb-6">
<p className="text-sm font-medium text-primary">Training plan</p>
<h1 className="mt-2 text-3xl font-semibold tracking-tight sm:text-4xl">
Routines
</h1>
</header>
);
}

function GuestRoutinesMessage() {
return (
<RoutineMessage
detail="Sign in with Google when you want to create routines that persist across devices."
title="Guest routines are coming later."
/>
);
}

function RegisteredUserRoutines() {
const routinesQuery = useRoutines();

if (routinesQuery.isPending) {
return <RoutineListSkeleton />;
}

if (routinesQuery.isError) {
return <RoutineLoadError onRetry={routinesQuery.refetch} />;
}

if (routinesQuery.data.routines.length === 0) {
return <EmptyRoutineList />;
}

return <RoutineList routines={routinesQuery.data.routines} />;
}

function RoutineLoadError({ onRetry }: { onRetry: () => unknown }) {
const retryButton = (
<button
className="rounded-md bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground"
onClick={() => void onRetry()}
type="button"
>
Try again
</button>
);

return (
<RoutineMessage
action={retryButton}
detail="Try again to reconnect to mission control."
title="We couldn't load your routines."
/>
);
}

function EmptyRoutineList() {
return (
<RoutineMessage
detail="Create your first routine to get ready for liftoff."
title="No routines yet."
/>
);
}

type RoutineListProps = {
routines: RoutineSummary[];
};

function RoutineList({ routines }: RoutineListProps) {
return (
<ul className="grid gap-4 md:grid-cols-2">
{routines.map((routine) => (
<RoutineCard key={routine.id} routine={routine} />
))}
</ul>
);
}

type RoutineCardProps = {
routine: RoutineSummary;
};

function RoutineCard({ routine }: RoutineCardProps) {
const schedule = routine.scheduledDays
.map((day) => DAY_LABELS[day])
.join(', ');
const exerciseLabel = routine.exerciseCount === 1 ? 'exercise' : 'exercises';

return (
<li className="rounded-xl border bg-surface p-5 shadow-sm">
<h2 className="text-lg font-semibold">{routine.name}</h2>
{routine.description && (
<p className="mt-1 text-sm text-muted-foreground">
{routine.description}
</p>
)}
<div className="mt-4 flex flex-wrap gap-4 text-sm text-muted-foreground">
<span className="flex items-center gap-2">
<Dumbbell aria-hidden="true" className="size-4" />
{routine.exerciseCount} {exerciseLabel}
</span>
{schedule && (
<span className="flex items-center gap-2">
<CalendarDays aria-hidden="true" className="size-4" />
{schedule}
</span>
)}
</div>
</li>
);
}

type RoutineMessageProps = {
detail: string;
title: string;
action?: ReactNode;
};

function RoutineMessage({ detail, title, action }: RoutineMessageProps) {
return (
<div className="rounded-xl border bg-surface px-6 py-12 text-center">
<Dumbbell aria-hidden="true" className="mx-auto size-10 text-primary" />
<h2 className="mt-4 text-xl font-semibold">{title}</h2>
<p className="mx-auto mt-2 max-w-md text-muted-foreground">{detail}</p>
{action && <div className="mt-5">{action}</div>}
</div>
);
}

function RoutineListSkeleton() {
return (
<div aria-label="Loading routines" className="grid gap-4 md:grid-cols-2">
{[0, 1].map((item) => (
<div
className="h-36 animate-pulse rounded-xl border bg-surface"
key={item}
/>
))}
</div>
);
}
56 changes: 56 additions & 0 deletions apps/web/src/features/routines/routines.api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/** Verifies routine requests include credentials and validate backend responses. */
import { afterEach, describe, expect, it, vi } from 'vitest';

import { fetchRoutines, RoutinesApiError } from './routines.api';

afterEach(() => vi.unstubAllGlobals());

describe('fetchRoutines', () => {
it('fetches and validates the authenticated user routines', async () => {
const response = {
routines: [
{
id: '26d34dc0-8e4c-4bd0-9e3b-7b839b44e486',
name: 'Upper Body',
description: null,
exerciseCount: 3,
scheduledDays: [1, 3, 5],
createdAt: '2026-08-26T10:00:00.000Z',
updatedAt: '2026-08-26T10:00:00.000Z',
},
],
};
const fetchMock = vi.fn().mockResolvedValue(Response.json(response));
vi.stubGlobal('fetch', fetchMock);

const abortController = new AbortController();

await expect(fetchRoutines(abortController.signal)).resolves.toEqual(
response,
);
expect(fetchMock).toHaveBeenCalledWith('/api/routines', {
credentials: 'include',
signal: abortController.signal,
});
});

it('rejects an unsuccessful response with its status', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(new Response(null, { status: 500 })),
);

await expect(fetchRoutines()).rejects.toEqual(new RoutinesApiError(500));
});

it('rejects a response that violates the shared contract', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValue(Response.json({ routines: [{ id: 'unsafe' }] })),
);

await expect(fetchRoutines()).rejects.toThrow();
});
});
28 changes: 28 additions & 0 deletions apps/web/src/features/routines/routines.api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/** Fetches and validates browser-safe routine data from the backend API. */
import {
routineListResponseSchema,
type RoutineListResponse,
} from '@goforlift/contracts';

export class RoutinesApiError extends Error {
constructor(public readonly status: number) {
super(`Routines API request failed with status ${status}`);
this.name = 'RoutinesApiError';
}
}

export async function fetchRoutines(
signal?: AbortSignal,
): Promise<RoutineListResponse> {
const response = await fetch('/api/routines', {
credentials: 'include',
signal,
});

if (!response.ok) {
throw new RoutinesApiError(response.status);
}

const data: unknown = await response.json();
return routineListResponseSchema.parse(data);
}
16 changes: 16 additions & 0 deletions apps/web/src/features/routines/routines.query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** Provides the TanStack Query source for the authenticated user's routines. */
import { queryOptions, useQuery } from '@tanstack/react-query';

import { fetchRoutines } from './routines.api';

export const routinesQueryKey = ['routines'] as const;

export const routinesQueryOptions = queryOptions({
queryKey: routinesQueryKey,
queryFn: ({ signal }) => fetchRoutines(signal),
retry: false,
});

export function useRoutines(enabled = true) {
return useQuery({ ...routinesQueryOptions, enabled });
}
Loading