refactor(web): extract Guide screen #359

Merged
timothy merged 2 commits from codex/246-guide-screen into main 2026-07-15 21:59:16 +02:00
4 changed files with 548 additions and 499 deletions
+10 -209
View File
@@ -110,151 +110,16 @@ describe('ChicoryTV SPA scaffold', () => {
expect(window.location.pathname).toBe('/app');
});
it('selects the active screen from the current location', () => {
it('renders the extracted Guide screen at its route (#246)', async () => {
// Thin route/composition smoke test: detailed Guide behavior lives in GuideScreen.test.tsx.
window.history.replaceState(null, '', '/app/guide');
render(<App />);
expect(screen.getByRole('heading', { name: 'Guide' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Loading guide' })).toBeInTheDocument();
expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Guide' })).toHaveAttribute('aria-current', 'page');
});
it('renders the Guide screen from a bounded JSON guide window', async () => {
vi.setSystemTime(new Date('2026-07-05T20:30:00Z'));
mockDashboardApi({
channelStates: [
{
channelId: 1,
channelNumber: '5.1',
onAir: true,
nowPlaying: {
finishUtc: '2026-07-05T21:00:00Z',
startUtc: '2026-07-05T20:00:00Z',
title: 'Saturday Morning Cartoons - s01e01 - Pilot'
}
},
{ channelId: 2, channelNumber: '24', onAir: false, nowPlaying: null }
],
guide: guideFixture()
});
const { container } = render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Guide' }));
expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(screen.getByText('Retro Cartoons')).toBeInTheDocument();
expect(screen.getByText('News 24')).toBeInTheDocument();
expect(screen.getAllByText('Saturday Morning Cartoons').length).toBeGreaterThan(0);
expect(screen.getByText('Pilot')).toBeInTheDocument();
expect(screen.getAllByText('Kids').length).toBeGreaterThan(0);
expect(screen.getByText('Early Show')).toBeInTheDocument();
expect(screen.getByText('No programmes in this window')).toBeInTheDocument();
expect(screen.queryByText('Filler')).not.toBeInTheDocument();
expect(container.querySelectorAll('.ctv-epg-programme-live')).toHaveLength(1);
const guideCall = fetchCallsStartingWith('/api/v1/guide?')[0];
expect(guideCall).toBeDefined();
const guideUrl = new URL(guideCall, window.location.origin);
expect(guideUrl.searchParams.get('start')).toBe('2026-07-05T19:30:00.000Z');
expect(guideUrl.searchParams.get('end')).toBe('2026-07-06T08:30:00.000Z');
expect(window.fetch).toHaveBeenCalledWith('/api/v1/channels/state', expect.any(Object));
});
it('renders the Guide screen when an on-air channel omits nowPlaying', async () => {
mockDashboardApi({
channelStates: [
{
channelId: 1,
channelNumber: '5.1',
onAir: true
}
],
guide: guideFixture()
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Guide' }));
expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(screen.getByText('Retro Cartoons')).toBeInTheDocument();
});
it('moves the Guide now marker on timer ticks without polling the guide endpoint', async () => {
const intervalHandlers: Array<() => void> = [];
vi.setSystemTime(new Date('2026-07-05T20:30:00Z'));
vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler) => {
if (typeof handler === 'function') {
intervalHandlers.push(handler as () => void);
}
return intervalHandlers.length;
});
vi.spyOn(window, 'clearInterval').mockImplementation(() => undefined);
mockDashboardApi({ guide: guideFixture() });
const { container } = render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Guide' }));
expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
const guideFetchesBeforeTick = fetchCallsStartingWith('/api/v1/guide?').length;
const marker = container.querySelector('.ctv-epg-now-marker') as HTMLElement;
expect(marker.style.left).toBe('508px');
vi.setSystemTime(new Date('2026-07-05T21:00:00Z'));
intervalHandlers.forEach((handler) => handler());
await waitFor(() => {
expect(marker.style.left).toBe('664px');
});
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(guideFetchesBeforeTick);
});
it('fetches one Guide window per explicit navigation and jumps back to now', async () => {
vi.setSystemTime(new Date('2026-07-05T20:30:00Z'));
mockDashboardApi({ guide: guideFixture() });
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Guide' }));
expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Next guide window' }));
await waitFor(() => {
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(2);
});
const nextUrl = new URL(fetchCallsStartingWith('/api/v1/guide?')[1], window.location.origin);
expect(nextUrl.searchParams.get('start')).toBe('2026-07-06T08:30:00.000Z');
expect(nextUrl.searchParams.get('end')).toBe('2026-07-06T21:30:00.000Z');
fireEvent.click(screen.getByRole('button', { name: 'Jump to now' }));
await waitFor(() => {
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(3);
});
const nowUrl = new URL(fetchCallsStartingWith('/api/v1/guide?')[2], window.location.origin);
expect(nowUrl.searchParams.get('start')).toBe('2026-07-05T19:30:00.000Z');
expect(nowUrl.searchParams.get('end')).toBe('2026-07-06T08:30:00.000Z');
});
it('shows Guide API errors and retries', async () => {
mockDashboardApi({
guide: guideFixture(),
guideFailuresBeforeSuccess: 1
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Guide' }));
expect(await screen.findByText('Request failed with status 500')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
expect(await screen.findByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(vi.mocked(window.fetch).mock.calls.some(([input]) => input.toString().startsWith('/api/v1/guide?'))).toBe(true);
});
it('shows a not-found screen for unknown app routes', () => {
@@ -2048,8 +1913,6 @@ function mockDashboardApi({
collections = [],
confirm = false,
fillerPresets = [],
guide = null,
guideFailuresBeforeSuccess = 0,
health = [],
libraryScanStatusFailAfterTrigger = false,
libraryScanStatuses = [],
@@ -2120,8 +1983,6 @@ function mockDashboardApi({
collections?: unknown[];
confirm?: boolean;
fillerPresets?: unknown[];
guide?: unknown;
guideFailuresBeforeSuccess?: number;
health?: unknown[];
libraryScanStatusFailAfterTrigger?: boolean;
libraryScanStatuses?: unknown[];
@@ -2188,7 +2049,6 @@ function mockDashboardApi({
let currentHdhrSettings = hdhrSettings;
let currentResolutions = resolutions;
let remainingMediaSourcesFailures = mediaSourcesFailuresBeforeSuccess;
let remainingGuideFailures = guideFailuresBeforeSuccess;
let remainingScheduleItemFailures = scheduleItemFailuresBeforeSuccess;
let remainingPlayoutItemsFailures = playoutItemsFailuresBeforeSuccess;
let scanStatusSequenceIndex = 0;
@@ -2260,12 +2120,12 @@ function mockDashboardApi({
}
if (path.startsWith('/api/v1/guide?')) {
if (remainingGuideFailures > 0) {
remainingGuideFailures -= 1;
return Promise.resolve(new Response(null, { status: 500 }));
}
return Promise.resolve(jsonResponse(guide ?? guideFixture()));
const guideUrl = new URL(path, window.location.origin);
return Promise.resolve(jsonResponse({
channels: [],
end: guideUrl.searchParams.get('end'),
start: guideUrl.searchParams.get('start')
}));
}
if (path === '/api/v1/schedules') {
@@ -2682,62 +2542,3 @@ function mockDashboardApi({
return Promise.resolve(jsonResponse(null, 404));
});
}
function fetchCallsStartingWith(prefix: string): string[] {
return vi.mocked(window.fetch).mock.calls
.map(([input]) => input.toString())
.filter((path) => path.startsWith(prefix));
}
function guideFixture(overrides: Record<string, unknown> = {}) {
return {
channels: [
{
name: 'Retro Cartoons',
number: '5.1',
programmes: [
{
category: 'Kids',
fillerKind: 'None',
start: '2026-07-05T19:00:00Z',
stop: '2026-07-05T20:00:00Z',
subTitle: null,
title: 'Early Show'
},
{
category: 'Kids',
fillerKind: 'None',
start: '2026-07-05T20:00:00Z',
stop: '2026-07-05T21:00:00Z',
subTitle: 'Pilot',
title: 'Saturday Morning Cartoons'
},
{
category: null,
fillerKind: 'None',
start: '2026-07-05T22:00:00Z',
stop: '2026-07-05T23:00:00Z',
subTitle: null,
title: 'Saturday Morning Cartoons'
},
{
category: null,
fillerKind: 'None',
start: '2026-07-06T08:00:00Z',
stop: '2026-07-06T09:00:00Z',
subTitle: null,
title: 'Window Edge Special'
}
]
},
{
name: 'News 24',
number: '24',
programmes: []
}
],
end: '2026-07-06T08:30:00Z',
start: '2026-07-05T19:30:00Z',
...overrides
};
}
+3 -290
View File
@@ -20,7 +20,6 @@ import {
Clapperboard,
CircleHelp,
ClipboardCopy,
Crosshair,
Film,
FolderTree,
Info,
@@ -34,7 +33,6 @@ import {
ListMusic,
ListVideo,
Plus,
RefreshCw,
Repeat,
ScrollText,
Search,
@@ -43,7 +41,6 @@ import {
Stamp,
Stethoscope,
Trash2,
TriangleAlert,
Tv
} from 'lucide-react';
import chicoryMarkUrl from '../../design-system/assets/chicory-mark.svg';
@@ -93,6 +90,7 @@ import { DecoTemplatesScreen } from './screens/DecoTemplatesScreen';
import { TemplatesScreen } from './screens/TemplatesScreen';
import { PlayoutsRouteScreen } from './screens/PlayoutsScreen';
import { DashboardHealthSummary, DashboardScreen } from './screens/DashboardScreen';
import { GuideScreen } from './screens/GuideScreen';
import {
navigateToPath,
parseLibrariesSubRoute,
@@ -102,25 +100,15 @@ import {
Badge,
Button,
Card,
ChannelLogo,
IconButton,
NavItem,
NavSection,
Select,
Spinner,
StatusDot
NavSection
} from './components';
import {
useChannelsQuery,
useDashboardHealthQuery,
useDashboardVersionQuery,
defaultGuideWindowStart,
GUIDE_WINDOW_MS,
useGuideScreenQuery,
type ChannelState,
type ChannelGuideChannel,
type ChannelGuideProgramme,
type DashboardHealthQueryState,
type DashboardHealthQueryState
} from './api';
import {
applyDesignSystemTheme,
@@ -890,281 +878,6 @@ function TopBar({ route }: { route: ScreenRoute | null }) {
);
}
const EPG_SLOT_MINUTES = 30;
const EPG_SLOT_WIDTH = 156;
const EPG_RAIL_WIDTH = 196;
const EPG_ROW_HEIGHT = 82;
const EPG_HEADER_HEIGHT = 34;
function GuideLoadingState() {
return (
<Card title={<h2>Loading guide</h2>} subtitle="Fetching a bounded JSON guide window and live channel state.">
<div className="ctv-dashboard-state">
<Spinner tone="muted" />
<span>Loading guide</span>
</div>
</Card>
);
}
function GuideErrorState({ error, refresh }: { error: string; refresh: () => void }) {
return (
<Card
title={<h2>Guide unavailable</h2>}
subtitle="The API returned an error while loading the JSON guide."
actions={<Button onClick={refresh} startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">Retry</Button>}
>
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
</Card>
);
}
function GuideScreen() {
const query = useGuideScreenQuery();
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const intervalId = window.setInterval(() => {
setNow(new Date());
}, 60000);
return () => {
window.clearInterval(intervalId);
};
}, []);
if (query.status === 'loading') {
return <GuideLoadingState />;
}
if (query.status === 'error') {
return <GuideErrorState error={query.error} refresh={query.refresh} />;
}
const channels = query.data.guide.channels;
const channelStatesByNumber = new Map(query.data.channelStates.map((state) => [state.channelNumber, state]));
const windowStart = new Date(query.data.guide.start);
const windowEnd = new Date(query.data.guide.end);
const slots = guideSlots(windowStart, windowEnd);
const totalWidth = EPG_RAIL_WIDTH + slots.length * EPG_SLOT_WIDTH;
const nowOffset = offsetPx(now, windowStart);
const nowInWindow = now >= windowStart && now <= windowEnd;
const moveWindow = (delta: number) => {
query.setWindowStart(new Date(query.windowStart.getTime() + delta * GUIDE_WINDOW_MS));
};
const jumpToNow = () => {
query.setWindowStart(defaultGuideWindowStart(now));
};
return (
<div className="ctv-epg-screen">
<section className="ctv-epg-toolbar" aria-label="Guide controls">
<div className="ctv-epg-filter">
<Select disabled label="Channel group" options={['All channels']} size="sm" value="All channels" />
</div>
<div className="ctv-epg-window">
<span>{formatGuideTime(windowStart)}</span>
<input
aria-label="Guide window position"
disabled
max="100"
min="0"
type="range"
value={nowInWindow ? Math.round((now.getTime() - windowStart.getTime()) / (windowEnd.getTime() - windowStart.getTime()) * 100) : 0}
readOnly
/>
<span>{formatGuideTime(windowEnd)}</span>
</div>
<Badge tone={nowInWindow ? 'accent' : 'neutral'} dot={nowInWindow}>Now {formatGuideTime(now)}</Badge>
<Button onClick={() => moveWindow(-1)} variant="secondary">Previous</Button>
<Button onClick={() => moveWindow(1)} variant="secondary">Next guide window</Button>
<Button onClick={jumpToNow} startIcon={<Crosshair aria-hidden="true" size={15} />} variant="primary">Jump to now</Button>
</section>
<section className="ctv-epg-grid-shell" aria-label="Guide timeline">
<div className="ctv-epg-scroll">
<div
aria-label="Channel guide"
className="ctv-epg-grid"
role="grid"
style={{ minWidth: totalWidth }}
>
<div className="ctv-epg-time-head" role="row" style={{ height: EPG_HEADER_HEIGHT }}>
<div className="ctv-epg-rail-head" style={{ width: EPG_RAIL_WIDTH }} />
{slots.map((slot) => (
<div className="ctv-epg-time-slot" key={slot.toISOString()} role="columnheader" style={{ width: EPG_SLOT_WIDTH }}>
{formatGuideTime(slot)}
</div>
))}
</div>
{nowInWindow && (
<div
aria-hidden="true"
className="ctv-epg-now-marker"
style={{
bottom: 0,
left: EPG_RAIL_WIDTH + nowOffset,
top: EPG_HEADER_HEIGHT
}}
>
<span />
</div>
)}
{channels.map((channel, index) => (
<GuideChannelRow
channel={channel}
channelState={channelStatesByNumber.get(channel.number) ?? null}
index={index}
key={channel.number}
windowEnd={windowEnd}
windowStart={windowStart}
/>
))}
</div>
</div>
</section>
</div>
);
}
function GuideChannelRow({
channel,
channelState,
index,
windowEnd,
windowStart
}: {
channel: ChannelGuideChannel;
channelState: ChannelState | null;
index: number;
windowEnd: Date;
windowStart: Date;
}) {
const visibleProgrammes = channel.programmes
.map((programme) => clipProgramme(programme, windowStart, windowEnd))
.filter((programme): programme is ClippedProgramme => programme !== null);
return (
<div className="ctv-epg-row" role="row" style={{ height: EPG_ROW_HEIGHT }}>
<div className="ctv-epg-channel-rail" role="rowheader" style={{ width: EPG_RAIL_WIDTH }}>
<code>{channel.number}</code>
<ChannelLogo name={channel.name} size={30} />
<span>{channel.name}</span>
{channelState?.onAir && <StatusDot status="live" size={7} />}
</div>
<div className={`ctv-epg-track${index % 2 ? ' ctv-epg-track-alt' : ''}`} role="gridcell">
{visibleProgrammes.length === 0 ? (
<span className="ctv-epg-empty">No programmes in this window</span>
) : visibleProgrammes.map((programme) => (
<GuideProgrammeBlock
key={`${programme.title}-${programme.start.getTime()}-${programme.stop.getTime()}`}
programme={programme}
channelState={channelState}
windowStart={windowStart}
/>
))}
</div>
</div>
);
}
interface ClippedProgramme {
category: null | string;
fillerKind: string;
start: Date;
stop: Date;
subTitle: null | string;
title: string;
visibleStart: Date;
visibleStop: Date;
}
function GuideProgrammeBlock({
channelState,
programme,
windowStart
}: {
channelState: ChannelState | null;
programme: ClippedProgramme;
windowStart: Date;
}) {
const filler = programme.fillerKind !== 'None';
const live = Boolean(channelState?.onAir && programmeMatchesNowPlaying(programme, channelState.nowPlaying));
const left = offsetPx(programme.visibleStart, windowStart) + 3;
const width = Math.max(24, offsetPx(programme.visibleStop, programme.visibleStart) - 6);
return (
<article
className={`ctv-epg-programme${live ? ' ctv-epg-programme-live' : ''}${filler ? ' ctv-epg-programme-filler' : ''}`}
style={{ left, width }}
title={`${programme.title}${programme.subTitle ? ` - ${programme.subTitle}` : ''}`}
>
<div className="ctv-epg-programme-title">
{live && <StatusDot status="live" size={6} />}
<strong>{programme.title}</strong>
</div>
{programme.subTitle && <span>{programme.subTitle}</span>}
{filler ? <Badge tone="neutral">Filler</Badge> : programme.category && <small>{programme.category}</small>}
</article>
);
}
function guideSlots(start: Date, end: Date): Date[] {
const slots: Date[] = [];
const slotMs = EPG_SLOT_MINUTES * 60 * 1000;
for (let value = start.getTime(); value < end.getTime(); value += slotMs) {
slots.push(new Date(value));
}
return slots;
}
function formatGuideTime(value: Date): string {
return value.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function offsetPx(value: Date, start: Date): number {
return (value.getTime() - start.getTime()) / (EPG_SLOT_MINUTES * 60 * 1000) * EPG_SLOT_WIDTH;
}
function clipProgramme(programme: ChannelGuideProgramme, windowStart: Date, windowEnd: Date): ClippedProgramme | null {
const start = new Date(programme.start);
const stop = new Date(programme.stop);
if (Number.isNaN(start.getTime()) || Number.isNaN(stop.getTime()) || stop <= windowStart || start >= windowEnd) {
return null;
}
return {
category: programme.category,
fillerKind: programme.fillerKind,
start,
stop,
subTitle: programme.subTitle,
title: programme.title,
visibleStart: start < windowStart ? windowStart : start,
visibleStop: stop > windowEnd ? windowEnd : stop
};
}
function programmeMatchesNowPlaying(programme: ClippedProgramme, nowPlaying: ChannelState['nowPlaying'] | undefined): boolean {
if (!nowPlaying) {
return false;
}
const nowPlayingStart = new Date(nowPlaying.startUtc);
const nowPlayingFinish = new Date(nowPlaying.finishUtc);
return programme.start.getTime() === nowPlayingStart.getTime() &&
programme.stop.getTime() === nowPlayingFinish.getTime();
}
function PlaceholderScreen({ route }: { route: ScreenRoute }) {
return (
+240
View File
@@ -0,0 +1,240 @@
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GuideScreen } from './GuideScreen';
describe('GuideScreen', () => {
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
});
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-07-05T20:30:00Z'));
});
it('renders the Guide screen from a bounded JSON guide window', async () => {
mockGuideApi({
channelStates: [
{
channelId: 1,
channelNumber: '5.1',
onAir: true,
nowPlaying: {
finishUtc: '2026-07-05T21:00:00Z',
startUtc: '2026-07-05T20:00:00Z',
title: 'Saturday Morning Cartoons - s01e01 - Pilot'
}
},
{ channelId: 2, channelNumber: '24', onAir: false, nowPlaying: null }
],
guide: guideFixture()
});
const { container } = render(<GuideScreen />);
await flushGuideEffects();
expect(screen.getByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(screen.getByText('Retro Cartoons')).toBeInTheDocument();
expect(screen.getByText('News 24')).toBeInTheDocument();
expect(screen.getAllByText('Saturday Morning Cartoons').length).toBeGreaterThan(0);
expect(screen.getByText('Pilot')).toBeInTheDocument();
expect(screen.getAllByText('Kids').length).toBeGreaterThan(0);
expect(screen.getByText('Early Show')).toBeInTheDocument();
expect(screen.getByText('No programmes in this window')).toBeInTheDocument();
expect(screen.queryByText('Filler')).not.toBeInTheDocument();
expect(container.querySelectorAll('.ctv-epg-programme-live')).toHaveLength(1);
const guideCall = fetchCallsStartingWith('/api/v1/guide?')[0];
expect(guideCall).toBeDefined();
const guideUrl = new URL(guideCall, window.location.origin);
expect(guideUrl.searchParams.get('start')).toBe('2026-07-05T19:30:00.000Z');
expect(guideUrl.searchParams.get('end')).toBe('2026-07-06T08:30:00.000Z');
expect(window.fetch).toHaveBeenCalledWith('/api/v1/channels/state', expect.any(Object));
});
it('renders the Guide screen when an on-air channel omits nowPlaying', async () => {
mockGuideApi({
channelStates: [
{
channelId: 1,
channelNumber: '5.1',
onAir: true
}
],
guide: guideFixture()
});
render(<GuideScreen />);
await flushGuideEffects();
expect(screen.getByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(screen.getByText('Retro Cartoons')).toBeInTheDocument();
});
it('moves the Guide now marker on timer ticks without polling the guide endpoint', async () => {
mockGuideApi({ guide: guideFixture() });
const { container } = render(<GuideScreen />);
await flushGuideEffects();
expect(screen.getByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
const guideFetchesBeforeTick = fetchCallsStartingWith('/api/v1/guide?').length;
const marker = container.querySelector('.ctv-epg-now-marker') as HTMLElement;
expect(marker.style.left).toBe('508px');
vi.setSystemTime(new Date('2026-07-05T20:59:00Z'));
await act(async () => {
await vi.advanceTimersByTimeAsync(60000);
});
expect(marker.style.left).toBe('664px');
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(guideFetchesBeforeTick);
});
it('fetches one Guide window per explicit navigation and jumps back to now', async () => {
mockGuideApi({ guide: guideFixture() });
render(<GuideScreen />);
await flushGuideEffects();
expect(screen.getByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Next guide window' }));
await flushGuideEffects();
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(2);
const nextUrl = new URL(fetchCallsStartingWith('/api/v1/guide?')[1], window.location.origin);
expect(nextUrl.searchParams.get('start')).toBe('2026-07-06T08:30:00.000Z');
expect(nextUrl.searchParams.get('end')).toBe('2026-07-06T21:30:00.000Z');
fireEvent.click(screen.getByRole('button', { name: 'Jump to now' }));
await flushGuideEffects();
expect(fetchCallsStartingWith('/api/v1/guide?')).toHaveLength(3);
const nowUrl = new URL(fetchCallsStartingWith('/api/v1/guide?')[2], window.location.origin);
expect(nowUrl.searchParams.get('start')).toBe('2026-07-05T19:30:00.000Z');
expect(nowUrl.searchParams.get('end')).toBe('2026-07-06T08:30:00.000Z');
});
it('shows Guide API errors and retries', async () => {
mockGuideApi({
guide: guideFixture(),
guideFailuresBeforeSuccess: 1
});
render(<GuideScreen />);
await flushGuideEffects();
expect(screen.getByText('Request failed with status 500')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
await flushGuideEffects();
expect(screen.getByRole('grid', { name: 'Channel guide' })).toBeInTheDocument();
});
});
async function flushGuideEffects() {
await act(async () => {
await vi.advanceTimersByTimeAsync(0);
});
}
function mockGuideApi({
channelStates = [],
guide = guideFixture(),
guideFailuresBeforeSuccess = 0
}: {
channelStates?: unknown[];
guide?: unknown;
guideFailuresBeforeSuccess?: number;
} = {}) {
let remainingGuideFailures = guideFailuresBeforeSuccess;
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
const path = input.toString();
if (path.startsWith('/api/v1/guide?')) {
if (remainingGuideFailures > 0) {
remainingGuideFailures -= 1;
return Promise.resolve(new Response(null, { status: 500 }));
}
return Promise.resolve(jsonResponse(guide));
}
if (path === '/api/v1/channels/state') {
return Promise.resolve(jsonResponse(channelStates));
}
return Promise.resolve(jsonResponse(null, 404));
});
}
function fetchCallsStartingWith(prefix: string): string[] {
return vi.mocked(window.fetch).mock.calls
.map(([input]) => input.toString())
.filter((path) => path.startsWith(prefix));
}
function guideFixture(overrides: Record<string, unknown> = {}) {
return {
channels: [
{
name: 'Retro Cartoons',
number: '5.1',
programmes: [
{
category: 'Kids',
fillerKind: 'None',
start: '2026-07-05T19:00:00Z',
stop: '2026-07-05T20:00:00Z',
subTitle: null,
title: 'Early Show'
},
{
category: 'Kids',
fillerKind: 'None',
start: '2026-07-05T20:00:00Z',
stop: '2026-07-05T21:00:00Z',
subTitle: 'Pilot',
title: 'Saturday Morning Cartoons'
},
{
category: null,
fillerKind: 'None',
start: '2026-07-05T22:00:00Z',
stop: '2026-07-05T23:00:00Z',
subTitle: null,
title: 'Saturday Morning Cartoons'
},
{
category: null,
fillerKind: 'None',
start: '2026-07-06T08:00:00Z',
stop: '2026-07-06T09:00:00Z',
subTitle: null,
title: 'Window Edge Special'
}
]
},
{
name: 'News 24',
number: '24',
programmes: []
}
],
end: '2026-07-06T08:30:00Z',
start: '2026-07-05T19:30:00Z',
...overrides
};
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
+295
View File
@@ -0,0 +1,295 @@
import { useEffect, useState } from 'react';
import { Crosshair, RefreshCw, TriangleAlert } from 'lucide-react';
import {
defaultGuideWindowStart,
GUIDE_WINDOW_MS,
useGuideScreenQuery,
type ChannelState,
type ChannelGuideChannel,
type ChannelGuideProgramme
} from '../api';
import {
Badge,
Button,
Card,
ChannelLogo,
Select,
Spinner,
StatusDot
} from '../components';
const EPG_SLOT_MINUTES = 30;
const EPG_SLOT_WIDTH = 156;
const EPG_RAIL_WIDTH = 196;
const EPG_ROW_HEIGHT = 82;
const EPG_HEADER_HEIGHT = 34;
function GuideLoadingState() {
return (
<Card title={<h2>Loading guide</h2>} subtitle="Fetching a bounded JSON guide window and live channel state.">
<div className="ctv-dashboard-state">
<Spinner tone="muted" />
<span>Loading guide</span>
</div>
</Card>
);
}
function GuideErrorState({ error, refresh }: { error: string; refresh: () => void }) {
return (
<Card
title={<h2>Guide unavailable</h2>}
subtitle="The API returned an error while loading the JSON guide."
actions={<Button onClick={refresh} startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">Retry</Button>}
>
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
</Card>
);
}
export function GuideScreen() {
const query = useGuideScreenQuery();
const [now, setNow] = useState(() => new Date());
useEffect(() => {
const intervalId = window.setInterval(() => {
setNow(new Date());
}, 60000);
return () => {
window.clearInterval(intervalId);
};
}, []);
if (query.status === 'loading') {
return <GuideLoadingState />;
}
if (query.status === 'error') {
return <GuideErrorState error={query.error} refresh={query.refresh} />;
}
const channels = query.data.guide.channels;
const channelStatesByNumber = new Map(query.data.channelStates.map((state) => [state.channelNumber, state]));
const windowStart = new Date(query.data.guide.start);
const windowEnd = new Date(query.data.guide.end);
const slots = guideSlots(windowStart, windowEnd);
const totalWidth = EPG_RAIL_WIDTH + slots.length * EPG_SLOT_WIDTH;
const nowOffset = offsetPx(now, windowStart);
const nowInWindow = now >= windowStart && now <= windowEnd;
const moveWindow = (delta: number) => {
query.setWindowStart(new Date(query.windowStart.getTime() + delta * GUIDE_WINDOW_MS));
};
const jumpToNow = () => {
query.setWindowStart(defaultGuideWindowStart(now));
};
return (
<div className="ctv-epg-screen">
<section className="ctv-epg-toolbar" aria-label="Guide controls">
<div className="ctv-epg-filter">
<Select disabled label="Channel group" options={['All channels']} size="sm" value="All channels" />
</div>
<div className="ctv-epg-window">
<span>{formatGuideTime(windowStart)}</span>
<input
aria-label="Guide window position"
disabled
max="100"
min="0"
type="range"
value={nowInWindow ? Math.round((now.getTime() - windowStart.getTime()) / (windowEnd.getTime() - windowStart.getTime()) * 100) : 0}
readOnly
/>
<span>{formatGuideTime(windowEnd)}</span>
</div>
<Badge tone={nowInWindow ? 'accent' : 'neutral'} dot={nowInWindow}>Now {formatGuideTime(now)}</Badge>
<Button onClick={() => moveWindow(-1)} variant="secondary">Previous</Button>
<Button onClick={() => moveWindow(1)} variant="secondary">Next guide window</Button>
<Button onClick={jumpToNow} startIcon={<Crosshair aria-hidden="true" size={15} />} variant="primary">Jump to now</Button>
</section>
<section className="ctv-epg-grid-shell" aria-label="Guide timeline">
<div className="ctv-epg-scroll">
<div
aria-label="Channel guide"
className="ctv-epg-grid"
role="grid"
style={{ minWidth: totalWidth }}
>
<div className="ctv-epg-time-head" role="row" style={{ height: EPG_HEADER_HEIGHT }}>
<div className="ctv-epg-rail-head" style={{ width: EPG_RAIL_WIDTH }} />
{slots.map((slot) => (
<div className="ctv-epg-time-slot" key={slot.toISOString()} role="columnheader" style={{ width: EPG_SLOT_WIDTH }}>
{formatGuideTime(slot)}
</div>
))}
</div>
{nowInWindow && (
<div
aria-hidden="true"
className="ctv-epg-now-marker"
style={{
bottom: 0,
left: EPG_RAIL_WIDTH + nowOffset,
top: EPG_HEADER_HEIGHT
}}
>
<span />
</div>
)}
{channels.map((channel, index) => (
<GuideChannelRow
channel={channel}
channelState={channelStatesByNumber.get(channel.number) ?? null}
index={index}
key={channel.number}
windowEnd={windowEnd}
windowStart={windowStart}
/>
))}
</div>
</div>
</section>
</div>
);
}
function GuideChannelRow({
channel,
channelState,
index,
windowEnd,
windowStart
}: {
channel: ChannelGuideChannel;
channelState: ChannelState | null;
index: number;
windowEnd: Date;
windowStart: Date;
}) {
const visibleProgrammes = channel.programmes
.map((programme) => clipProgramme(programme, windowStart, windowEnd))
.filter((programme): programme is ClippedProgramme => programme !== null);
return (
<div className="ctv-epg-row" role="row" style={{ height: EPG_ROW_HEIGHT }}>
<div className="ctv-epg-channel-rail" role="rowheader" style={{ width: EPG_RAIL_WIDTH }}>
<code>{channel.number}</code>
<ChannelLogo name={channel.name} size={30} />
<span>{channel.name}</span>
{channelState?.onAir && <StatusDot status="live" size={7} />}
</div>
<div className={`ctv-epg-track${index % 2 ? ' ctv-epg-track-alt' : ''}`} role="gridcell">
{visibleProgrammes.length === 0 ? (
<span className="ctv-epg-empty">No programmes in this window</span>
) : visibleProgrammes.map((programme) => (
<GuideProgrammeBlock
key={`${programme.title}-${programme.start.getTime()}-${programme.stop.getTime()}`}
programme={programme}
channelState={channelState}
windowStart={windowStart}
/>
))}
</div>
</div>
);
}
interface ClippedProgramme {
category: null | string;
fillerKind: string;
start: Date;
stop: Date;
subTitle: null | string;
title: string;
visibleStart: Date;
visibleStop: Date;
}
function GuideProgrammeBlock({
channelState,
programme,
windowStart
}: {
channelState: ChannelState | null;
programme: ClippedProgramme;
windowStart: Date;
}) {
const filler = programme.fillerKind !== 'None';
const live = Boolean(channelState?.onAir && programmeMatchesNowPlaying(programme, channelState.nowPlaying));
const left = offsetPx(programme.visibleStart, windowStart) + 3;
const width = Math.max(24, offsetPx(programme.visibleStop, programme.visibleStart) - 6);
return (
<article
className={`ctv-epg-programme${live ? ' ctv-epg-programme-live' : ''}${filler ? ' ctv-epg-programme-filler' : ''}`}
style={{ left, width }}
title={`${programme.title}${programme.subTitle ? ` - ${programme.subTitle}` : ''}`}
>
<div className="ctv-epg-programme-title">
{live && <StatusDot status="live" size={6} />}
<strong>{programme.title}</strong>
</div>
{programme.subTitle && <span>{programme.subTitle}</span>}
{filler ? <Badge tone="neutral">Filler</Badge> : programme.category && <small>{programme.category}</small>}
</article>
);
}
function guideSlots(start: Date, end: Date): Date[] {
const slots: Date[] = [];
const slotMs = EPG_SLOT_MINUTES * 60 * 1000;
for (let value = start.getTime(); value < end.getTime(); value += slotMs) {
slots.push(new Date(value));
}
return slots;
}
function formatGuideTime(value: Date): string {
return value.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function offsetPx(value: Date, start: Date): number {
return (value.getTime() - start.getTime()) / (EPG_SLOT_MINUTES * 60 * 1000) * EPG_SLOT_WIDTH;
}
function clipProgramme(programme: ChannelGuideProgramme, windowStart: Date, windowEnd: Date): ClippedProgramme | null {
const start = new Date(programme.start);
const stop = new Date(programme.stop);
if (Number.isNaN(start.getTime()) || Number.isNaN(stop.getTime()) || stop <= windowStart || start >= windowEnd) {
return null;
}
return {
category: programme.category,
fillerKind: programme.fillerKind,
start,
stop,
subTitle: programme.subTitle,
title: programme.title,
visibleStart: start < windowStart ? windowStart : start,
visibleStop: stop > windowEnd ? windowEnd : stop
};
}
function programmeMatchesNowPlaying(programme: ClippedProgramme, nowPlaying: ChannelState['nowPlaying'] | undefined): boolean {
if (!nowPlaying) {
return false;
}
const nowPlayingStart = new Date(nowPlaying.startUtc);
const nowPlayingFinish = new Date(nowPlaying.finishUtc);
return programme.start.getTime() === nowPlayingStart.getTime() &&
programme.stop.getTime() === nowPlayingFinish.getTime();
}