From e9fe12d1fd557259e65078e2c3e64454cc45713d Mon Sep 17 00:00:00 2001 From: Timothy Date: Wed, 15 Jul 2026 21:16:56 +0200 Subject: [PATCH 1/2] refactor(web): extract Guide screen Move Guide rendering, timer and clipping helpers, and detailed behavior tests into a screen-owned module while retaining only shell composition coverage in App. Refs #246 Co-Authored-By: OpenAI Codex --- web/src/App.test.tsx | 219 +------------------- web/src/App.tsx | 285 +------------------------- web/src/screens/GuideScreen.test.tsx | 240 ++++++++++++++++++++++ web/src/screens/GuideScreen.tsx | 295 +++++++++++++++++++++++++++ 4 files changed, 547 insertions(+), 492 deletions(-) create mode 100644 web/src/screens/GuideScreen.test.tsx create mode 100644 web/src/screens/GuideScreen.tsx diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index 02ba2eddf..896789727 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -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(); 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(); - - 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(); - - 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(); - - 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(); - - 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(); - - 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 = {}) { - 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 - }; -} diff --git a/web/src/App.tsx b/web/src/App.tsx index b15bc8e1c..ac96ea37f 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -20,7 +20,6 @@ import { Clapperboard, CircleHelp, ClipboardCopy, - Crosshair, Film, FolderTree, Info, @@ -93,6 +92,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, @@ -114,13 +114,7 @@ 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 +884,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 ( - Loading guide} subtitle="Fetching a bounded JSON guide window and live channel state."> -
- - Loading guide -
-
- ); -} - -function GuideErrorState({ error, refresh }: { error: string; refresh: () => void }) { - return ( - Guide unavailable} - subtitle="The API returned an error while loading the JSON guide." - actions={} - > -
-
-
- ); -} - -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 ; - } - - if (query.status === 'error') { - return ; - } - - 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 ( -
-
-
- - {formatGuideTime(windowEnd)} -
- Now {formatGuideTime(now)} - - - -
- -
-
-
-
-
- {slots.map((slot) => ( -
- {formatGuideTime(slot)} -
- ))} -
- - {nowInWindow && ( - - )} - - {channels.map((channel, index) => ( - - ))} -
-
-
-
- ); -} - -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 ( -
-
- {channel.number} - - {channel.name} - {channelState?.onAir && } -
-
- {visibleProgrammes.length === 0 ? ( - No programmes in this window - ) : visibleProgrammes.map((programme) => ( - - ))} -
-
- ); -} - -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 ( -
-
- {live && } - {programme.title} -
- {programme.subTitle && {programme.subTitle}} - {filler ? Filler : programme.category && {programme.category}} -
- ); -} - -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 ( diff --git a/web/src/screens/GuideScreen.test.tsx b/web/src/screens/GuideScreen.test.tsx new file mode 100644 index 000000000..da92661f2 --- /dev/null +++ b/web/src/screens/GuideScreen.test.tsx @@ -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(); + 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(); + 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(); + 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(); + 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(); + 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 = {}) { + 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 + }); +} diff --git a/web/src/screens/GuideScreen.tsx b/web/src/screens/GuideScreen.tsx new file mode 100644 index 000000000..5abbef7d8 --- /dev/null +++ b/web/src/screens/GuideScreen.tsx @@ -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 ( + Loading guide} subtitle="Fetching a bounded JSON guide window and live channel state."> +
+ + Loading guide +
+
+ ); +} + +function GuideErrorState({ error, refresh }: { error: string; refresh: () => void }) { + return ( + Guide unavailable} + subtitle="The API returned an error while loading the JSON guide." + actions={} + > +
+
+
+ ); +} + +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 ; + } + + if (query.status === 'error') { + return ; + } + + 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 ( +
+
+
+ + {formatGuideTime(windowEnd)} +
+ Now {formatGuideTime(now)} + + + +
+ +
+
+
+
+
+ {slots.map((slot) => ( +
+ {formatGuideTime(slot)} +
+ ))} +
+ + {nowInWindow && ( + + )} + + {channels.map((channel, index) => ( + + ))} +
+
+
+
+ ); +} + +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 ( +
+
+ {channel.number} + + {channel.name} + {channelState?.onAir && } +
+
+ {visibleProgrammes.length === 0 ? ( + No programmes in this window + ) : visibleProgrammes.map((programme) => ( + + ))} +
+
+ ); +} + +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 ( +
+
+ {live && } + {programme.title} +
+ {programme.subTitle && {programme.subTitle}} + {filler ? Filler : programme.category && {programme.category}} +
+ ); +} + +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(); +} -- 2.47.3 From 3876809a83088b5c6f3393cb56d00cd296cf5efe Mon Sep 17 00:00:00 2001 From: Timothy Date: Wed, 15 Jul 2026 21:51:42 +0200 Subject: [PATCH 2/2] chore(web): clean up App imports after screen extraction Refs #246 Co-Authored-By: OpenAI Codex --- web/src/App.tsx | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/web/src/App.tsx b/web/src/App.tsx index ac96ea37f..7d649f881 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -33,7 +33,6 @@ import { ListMusic, ListVideo, Plus, - RefreshCw, Repeat, ScrollText, Search, @@ -42,7 +41,6 @@ import { Stamp, Stethoscope, Trash2, - TriangleAlert, Tv } from 'lucide-react'; import chicoryMarkUrl from '../../design-system/assets/chicory-mark.svg'; @@ -102,13 +100,9 @@ import { Badge, Button, Card, - ChannelLogo, IconButton, NavItem, - NavSection, - Select, - Spinner, - StatusDot + NavSection } from './components'; import { useChannelsQuery, -- 2.47.3