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
407 changes: 403 additions & 4 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"next": "16.2.0",
"next-themes": "^0.4.6",
"react": "19.2.4",
"react-dom": "19.2.4"
"react-dom": "19.2.4",
"recharts": "^3.8.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
Expand Down
44 changes: 44 additions & 0 deletions src/app/api/championships/route.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { NextRequest } from 'next/server';
import { describe, expect, it } from 'vitest';

import { GET } from './route';

describe('GET /api/championships', () => {
it('returns championship data for valid year query', async () => {
const request = new NextRequest(
'http://localhost:3000/api/championships?year=2024',
);

const response = await GET(request);
const payload = await response.json();

expect(response.status).toBe(200);
expect(payload.data.year).toBe(2024);
expect(Array.isArray(payload.data.drivers)).toBe(true);
expect(payload.availableYears[0]).toBe(2024);
});

it('returns 400 for an invalid year value', async () => {
const request = new NextRequest(
'http://localhost:3000/api/championships?year=twenty-twenty-four',
);

const response = await GET(request);
const payload = await response.json();

expect(response.status).toBe(400);
expect(payload.message).toMatch(/invalid year/i);
});

it('uses 2024 as default year when year is omitted', async () => {
const request = new NextRequest(
'http://localhost:3000/api/championships',
);

const response = await GET(request);
const payload = await response.json();

expect(response.status).toBe(200);
expect(payload.data.year).toBe(2024);
});
});
44 changes: 44 additions & 0 deletions src/app/api/championships/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { NextRequest, NextResponse } from 'next/server';

import {
getChampionshipByYear,
isSupportedYear,
toServiceError,
} from '@/lib/server/championships';

export const dynamic = 'force-dynamic';

const defaultYear = 2024;

export async function GET(request: NextRequest) {
const yearParam = request.nextUrl.searchParams.get('year');

const year = yearParam ? Number(yearParam) : defaultYear;

if (Number.isNaN(year) || !Number.isInteger(year)) {
return NextResponse.json(
{ message: 'Invalid year query parameter.' },
{ status: 400 },
);
}

if (!isSupportedYear(year)) {
return NextResponse.json(
{ message: 'Unsupported championship year.' },
{ status: 400 },
);
}
Comment thread
dfloo marked this conversation as resolved.

try {
const response = await getChampionshipByYear({ year });
return NextResponse.json(response, { status: 200 });
} catch (error) {
const serviceError = toServiceError(error);
return NextResponse.json(
{
message: serviceError.message,
},
{ status: serviceError.status },
);
}
}
17 changes: 6 additions & 11 deletions src/app/championships/page.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
export default function ChampionshipPage() {
import ChampionshipsExplorer from '@/components/championships/ChampionshipsExplorer';

export default function ChampionshipsPage() {
return (
<div className="mx-auto w-full max-w-7xl px-6 py-12">
<div className="border-border mb-8 border-b pb-6">
<h1 className="text-foreground text-3xl font-bold">Championship</h1>
<p className="text-muted mt-2">
Drivers&apos; and Constructors&apos; standings, race calendar, and
historical season results.
</p>
</div>
<div className="border-border bg-surface text-muted flex items-center justify-center rounded-xl border py-32">
Championship data coming soon
<div className="flex h-full w-full overflow-hidden">
<div className="mx-auto h-full w-full max-w-7xl overflow-hidden px-6 py-6">
<ChampionshipsExplorer />
</div>
</div>
);
Expand Down
4 changes: 3 additions & 1 deletion src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ export default function RootLayout({
<body className="bg-background text-foreground flex h-full flex-col overflow-hidden">
<ThemeProvider>
<NavBar />
<main className="flex flex-1 flex-col">{children}</main>
<main className="flex flex-1 flex-col overflow-hidden">
{children}
</main>
</ThemeProvider>
</body>
</html>
Expand Down
44 changes: 44 additions & 0 deletions src/components/championships/CategoryTabs.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { ChampionshipCategory } from '@/types/championship';

interface CategoryTabsProps {
selectedCategory: ChampionshipCategory;
onChange: (nextCategory: ChampionshipCategory) => void;
disabled?: boolean;
}

const tabItems: Array<{ id: ChampionshipCategory; label: string }> = [
{ id: 'drivers', label: 'Drivers' },
{ id: 'constructors', label: 'Constructors' },
];

export default function CategoryTabs({
selectedCategory,
onChange,
disabled = false,
}: CategoryTabsProps) {
return (
<div className="bg-surface-hover inline-flex rounded-lg p-1">
{tabItems.map((item) => {
const isActive = selectedCategory === item.id;

return (
<button
key={item.id}
type="button"
aria-pressed={isActive}
disabled={disabled}
onClick={() => onChange(item.id)}
className={[
'rounded-md px-4 py-2 text-sm font-medium transition-colors disabled:opacity-60',
isActive
? 'bg-surface text-foreground'
: 'text-muted hover:text-foreground',
].join(' ')}
>
{item.label}
</button>
);
})}
</div>
);
}
206 changes: 206 additions & 0 deletions src/components/championships/ChampionshipsExplorer.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import ChampionshipsExplorer from './ChampionshipsExplorer';

vi.mock('./PointsProgressChart', () => ({
default: ({
progress,
}: {
progress: {
year: number;
category: string;
series: Array<{ name: string }>;
};
}) => (
<div>
Chart for {progress.year} {progress.category}: {progress.series[0]?.name}
</div>
),
}));

const yearPayload = {
availableYears: [2024, 2023, 2022],
data: {
year: 2024,
races: [
{ round: 1, name: 'Bahrain GP' },
{ round: 2, name: 'Saudi Arabian GP' },
],
drivers: [
{
id: '1',
name: 'Max Verstappen',
color: '#3671C6',
cumulativePoints: [25, 43],
raceResults: [
{
constructorId: '9',
constructorName: 'Red Bull',
constructorColor: '#3671C6',
racePoints: 25,
},
{
constructorId: '9',
constructorName: 'Red Bull',
constructorColor: '#3671C6',
racePoints: 18,
},
],
},
{
id: '2',
name: 'Sergio Perez',
color: '#3671C6',
cumulativePoints: [18, 33],
raceResults: [
{
constructorId: '9',
constructorName: 'Red Bull',
constructorColor: '#3671C6',
racePoints: 18,
},
{
constructorId: '9',
constructorName: 'Red Bull',
constructorColor: '#3671C6',
racePoints: 15,
},
],
},
{
id: '3',
name: 'Charles Leclerc',
color: '#DC0000',
cumulativePoints: [15, 30],
raceResults: [
{
constructorId: '6',
constructorName: 'Ferrari',
constructorColor: '#DC0000',
racePoints: 15,
},
{
constructorId: '6',
constructorName: 'Ferrari',
constructorColor: '#DC0000',
racePoints: 15,
},
],
},
],
},
};

describe('ChampionshipsExplorer', () => {
beforeEach(() => {
vi.restoreAllMocks();
});

it('loads 2024 drivers data by default', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => yearPayload,
});

vi.stubGlobal('fetch', fetchMock);

render(<ChampionshipsExplorer />);

await waitFor(() => {
expect(fetchMock).toHaveBeenCalledWith(
'/api/championships?year=2024',
expect.objectContaining({ cache: 'no-store', method: 'GET' }),
);
});

expect(
await screen.findByText(/chart for 2024 drivers: max verstappen/i),
).toBeInTheDocument();
});

it('does not refetch when switching to constructors tab', async () => {
const user = userEvent.setup();
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => yearPayload,
});

vi.stubGlobal('fetch', fetchMock);

render(<ChampionshipsExplorer />);

expect(
await screen.findByText(/chart for 2024 drivers: max verstappen/i),
).toBeInTheDocument();

const constructorsToggle = screen.getByRole('button', {
name: /constructors/i,
});

expect(constructorsToggle).toHaveAttribute('aria-pressed', 'false');

await user.click(constructorsToggle);

expect(constructorsToggle).toHaveAttribute('aria-pressed', 'true');

expect(
await screen.findByText(/chart for 2024 constructors: red bull/i),
).toBeInTheDocument();
expect(fetchMock).toHaveBeenCalledTimes(1);
});

it('refetches when year changes', async () => {
const user = userEvent.setup();
const fetchMock = vi
.fn()
.mockResolvedValueOnce({
ok: true,
json: async () => yearPayload,
})
.mockResolvedValueOnce({
ok: true,
json: async () => ({
...yearPayload,
data: {
...yearPayload.data,
year: 2023,
},
}),
});

vi.stubGlobal('fetch', fetchMock);

render(<ChampionshipsExplorer />);

expect(
await screen.findByText(/chart for 2024 drivers: max verstappen/i),
).toBeInTheDocument();

await user.selectOptions(screen.getByLabelText(/season/i), '2023');

expect(
await screen.findByText(/chart for 2023 drivers/i),
).toBeInTheDocument();
expect(fetchMock).toHaveBeenLastCalledWith(
'/api/championships?year=2023',
expect.objectContaining({ cache: 'no-store', method: 'GET' }),
);
});

it('shows an error state when request fails', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
json: async () => ({ message: 'Unsupported championship year.' }),
});

vi.stubGlobal('fetch', fetchMock);

render(<ChampionshipsExplorer />);

expect(await screen.findByRole('alert')).toHaveTextContent(
/unsupported championship year/i,
);
});
});
Loading
Loading