From 0416c00f96c8d034b24f7feea329bd7f86385541 Mon Sep 17 00:00:00 2001 From: Timothy Date: Wed, 15 Jul 2026 22:31:31 +0200 Subject: [PATCH 1/7] refactor(web): replace primary-action events with context Refs #247 Co-Authored-By: OpenAI Codex --- web/src/primaryAction.test.tsx | 149 +++++++++++++++++++++++++++++++++ web/src/primaryAction.ts | 85 ++++++++++++------- 2 files changed, 206 insertions(+), 28 deletions(-) create mode 100644 web/src/primaryAction.test.tsx diff --git a/web/src/primaryAction.test.tsx b/web/src/primaryAction.test.tsx new file mode 100644 index 000000000..b6de3aa0a --- /dev/null +++ b/web/src/primaryAction.test.tsx @@ -0,0 +1,149 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { PrimaryActionProvider, usePrimaryAction, usePrimaryActionHandler } from './primaryAction'; + +function Registration({ routeId, handler }: { routeId: string; handler: () => void }) { + usePrimaryAction(routeId, handler); + return null; +} + +function Action({ routeId }: { routeId: string }) { + const handler = usePrimaryActionHandler(routeId); + return ( + + ); +} + +describe('primary actions', () => { + afterEach(() => { + cleanup(); + }); + + it('invokes the active handler for a matching route', () => { + const handler = vi.fn(); + render( + + + + + ); + + fireEvent.click(screen.getByRole('button', { name: 'Run schedules' })); + + expect(handler).toHaveBeenCalledOnce(); + }); + + it('returns no handler for a nonmatching route', () => { + const handler = vi.fn(); + render( + + + + + ); + + const action = screen.getByRole('button', { name: 'Run channels' }); + expect(action).toBeDisabled(); + fireEvent.click(action); + expect(handler).not.toHaveBeenCalled(); + }); + + it('invokes the latest handler without replacing the registration', () => { + const firstHandler = vi.fn(); + const latestHandler = vi.fn(); + const view = render( + + + + + ); + + view.rerender( + + + + + ); + fireEvent.click(screen.getByRole('button', { name: 'Run schedules' })); + + expect(firstHandler).not.toHaveBeenCalled(); + expect(latestHandler).toHaveBeenCalledOnce(); + }); + + it('cleans up the old route and clears the registration on unmount', () => { + const handler = vi.fn(); + const view = render( + + + + + + ); + + view.rerender( + + + + + + ); + + expect(screen.getByRole('button', { name: 'Run schedules' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Run channels' })).toBeEnabled(); + fireEvent.click(screen.getByRole('button', { name: 'Run channels' })); + expect(handler).toHaveBeenCalledOnce(); + + view.rerender( + + + + + ); + + expect(screen.getByRole('button', { name: 'Run channels' })).toBeDisabled(); + }); + + it('does not let an older owner clear a newer registration', () => { + const olderHandler = vi.fn(); + const updatedOlderHandler = vi.fn(); + const newerHandler = vi.fn(); + const view = render( + + + + + ); + + view.rerender( + + + + + + ); + view.rerender( + + + + + + ); + view.rerender( + + + + + ); + fireEvent.click(screen.getByRole('button', { name: 'Run schedules' })); + + expect(olderHandler).not.toHaveBeenCalled(); + expect(updatedOlderHandler).not.toHaveBeenCalled(); + expect(newerHandler).toHaveBeenCalledOnce(); + }); + + it('lets screens render harmlessly without a provider', () => { + expect(() => render()).not.toThrow(); + }); +}); diff --git a/web/src/primaryAction.ts b/web/src/primaryAction.ts index b3b1eb06f..158a94b5e 100644 --- a/web/src/primaryAction.ts +++ b/web/src/primaryAction.ts @@ -1,39 +1,68 @@ -import { useEffect, useRef } from 'react'; +import { + createContext, + createElement, + type ReactNode, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState +} from 'react'; -// The TopBar renders one "primary action" button per screen (top-right). Because the -// TopBar and the screens are decoupled (the TopBar has no reference to the active -// screen component), the click is delivered as a window CustomEvent keyed on the -// active route id; a screen opts in with `usePrimaryAction(routeId, handler)`. -// -// A screen that does NOT call usePrimaryAction gets NO button — App.tsx's route table -// declares an empty `primaryAction` for such screens and the TopBar suppresses the -// button (see issue #238: the old code rendered a dead button for every unwired route). -export const PRIMARY_ACTION_EVENT = 'ctv:primary-action'; +type PrimaryActionHandler = () => void; -export function dispatchPrimaryAction(routeId: string): void { - window.dispatchEvent(new CustomEvent(PRIMARY_ACTION_EVENT, { detail: routeId })); +interface PrimaryActionRegistration { + owner: symbol; + routeId: string; + handler: PrimaryActionHandler; } -/** - * Subscribe a screen to its TopBar primary-action button. The handler runs whenever the - * TopBar dispatches `ctv:primary-action` with a detail matching `routeId`. The latest - * handler is held in a ref so re-renders don't churn the window listener. - */ -export function usePrimaryAction(routeId: string, handler: () => void): void { +interface PrimaryActionContextValue { + registration: PrimaryActionRegistration | undefined; + register: (owner: symbol, routeId: string, handler: PrimaryActionHandler) => () => void; +} + +const PrimaryActionContext = createContext(undefined); + +/** Owns the single primary-action registration shared by the shell and active screen. */ +export function PrimaryActionProvider({ children }: { children: ReactNode }) { + const [registration, setRegistration] = useState(); + + const register = useCallback((owner: symbol, routeId: string, handler: PrimaryActionHandler) => { + setRegistration({ owner, routeId, handler }); + + return () => { + setRegistration((current) => (current?.owner === owner ? undefined : current)); + }; + }, []); + + const value = useMemo(() => ({ registration, register }), [register, registration]); + + return createElement(PrimaryActionContext.Provider, { value }, children); +} + +/** Register a screen's primary action. Rendering outside the provider is intentionally harmless. */ +export function usePrimaryAction(routeId: string, handler: PrimaryActionHandler): void { const handlerRef = useRef(handler); - // Keep the ref pointing at the latest handler without re-subscribing the window listener - // on every render. Updating a ref during render trips react-hooks/refs, so do it in an effect. + const [owner] = useState(() => Symbol('primary-action-owner')); + const register = useContext(PrimaryActionContext)?.register; + useEffect(() => { handlerRef.current = handler; }); useEffect(() => { - const listener = (event: Event) => { - if ((event as CustomEvent).detail === routeId) { - handlerRef.current(); - } - }; - window.addEventListener(PRIMARY_ACTION_EVENT, listener); - return () => window.removeEventListener(PRIMARY_ACTION_EVENT, listener); - }, [routeId]); + if (!register) { + return; + } + + return register(owner, routeId, () => handlerRef.current()); + }, [owner, register, routeId]); +} + +/** Return the active handler only when its registration belongs to the requested route. */ +export function usePrimaryActionHandler(routeId: string): PrimaryActionHandler | undefined { + const registration = useContext(PrimaryActionContext)?.registration; + return registration?.routeId === routeId ? registration.handler : undefined; } -- 2.47.3 From ce5aaa8706516eeddef2504fbb221fc00e62cdf1 Mon Sep 17 00:00:00 2001 From: Timothy Date: Wed, 15 Jul 2026 22:34:19 +0200 Subject: [PATCH 2/7] refactor(web): extract app shell and routing Refs #247 Co-Authored-By: OpenAI Codex --- web/src/App.tsx | 1185 +-------------------------------- web/src/app/AppShell.tsx | 364 ++++++++++ web/src/app/ScreenContent.tsx | 225 +++++++ web/src/app/routes.tsx | 524 +++++++++++++++ 4 files changed, 1148 insertions(+), 1150 deletions(-) create mode 100644 web/src/app/AppShell.tsx create mode 100644 web/src/app/ScreenContent.tsx create mode 100644 web/src/app/routes.tsx diff --git a/web/src/App.tsx b/web/src/App.tsx index 7d649f881..e2df509a9 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -3,1137 +3,23 @@ import { useMemo, useRef, useState, - type KeyboardEvent, - type MouseEvent, - type ReactNode + type MouseEvent } from 'react'; +import { useDashboardHealthQuery } from './api'; +import { AppShell } from './app/AppShell'; +import { ScreenContent } from './app/ScreenContent'; import { - Bell, - Boxes, - Palette, - CalendarClock, - CalendarDays, - CalendarRange, - Cast, - Check, - ChevronDown, - Clapperboard, - CircleHelp, - ClipboardCopy, - Film, - FolderTree, - Info, - Layers, - KeyRound, - LayoutDashboard, - LayoutGrid, - Library, - Link2, - ListChecks, - ListMusic, - ListVideo, - Plus, - Repeat, - ScrollText, - Search, - Settings, - SlidersHorizontal, - Stamp, - Stethoscope, - Trash2, - Tv -} from 'lucide-react'; -import chicoryMarkUrl from '../../design-system/assets/chicory-mark.svg'; -import { ChannelBuilderScreen } from './builder/ChannelBuilder'; -import { ChannelEditScreen } from './screens/ChannelEditScreen'; -import { CollectionsScreen } from './screens/CollectionsScreen'; -import { FFmpegProfilesScreen } from './screens/FFmpegProfilesScreen'; -import { FillerPresetsScreen } from './screens/FillerPresetsScreen'; -import { LogsScreen } from './screens/LogsScreen'; -import { MediaBrowseScreen } from './screens/MediaBrowseScreen'; -import { MultiCollectionsScreen } from './screens/MultiCollectionsScreen'; -import { PlaylistsScreen } from './screens/PlaylistsScreen'; -import { RerunCollectionsScreen } from './screens/RerunCollectionsScreen'; -import { ChannelsScreen } from './screens/ChannelsScreen'; -import { LibrariesScreen } from './screens/LibrariesScreen'; -import { LocalLibraryEditScreen } from './screens/LocalLibraryEditScreen'; -import { PlexSourceScreen } from './screens/PlexSourceScreen'; -import { RemoteSourceScreen } from './screens/RemoteSourceScreen'; -import { RemoteConnectionEditScreen } from './screens/RemoteConnectionEditScreen'; -import { RemoteLibrariesEditScreen } from './screens/RemoteLibrariesEditScreen'; -import { PathReplacementsEditScreen } from './screens/PathReplacementsEditScreen'; -import { SchedulesScreen } from './screens/SchedulesScreen'; -import { canLeaveCurrentScreen } from './navigationGuard'; -import { dispatchPrimaryAction } from './primaryAction'; -import { - ArtistDetailScreen, - MovieDetailScreen, - SeasonDetailScreen, - ShowDetailScreen -} from './screens/MediaDetailScreen'; -import { ImageBrowserScreen } from './screens/ImageBrowserScreen'; -import { SearchScreen } from './screens/SearchScreen'; -import { SettingsScreen } from './screens/SettingsScreen'; -import { ApiKeyScreen } from './screens/ApiKeyScreen'; -import { UnauthorizedBanner } from './UnauthorizedBanner'; -import { UserMenu } from './UserMenu'; -import { TraktListsScreen } from './screens/TraktListsScreen'; -import { TrashScreen } from './screens/TrashScreen'; -import { TroubleshootingScreen } from './screens/TroubleshootingScreen'; -import { BlockPlayoutTroubleshootingScreen } from './screens/BlockPlayoutTroubleshootingScreen'; -import { PlaybackTroubleshootingScreen } from './screens/PlaybackTroubleshootingScreen'; -import { YamlValidatorScreen } from './screens/YamlValidatorScreen'; -import { WatermarksScreen } from './screens/WatermarksScreen'; -import { BlocksScreen } from './screens/BlocksScreen'; -import { DecosScreen } from './screens/DecosScreen'; -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, - parseMediaSubRoute -} from './routing'; -import { - Badge, - Button, - Card, - IconButton, - NavItem, - NavSection -} from './components'; -import { - useChannelsQuery, - useDashboardHealthQuery, - useDashboardVersionQuery, - type DashboardHealthQueryState -} from './api'; + routeFromLocation, + routeHref, + type ScreenRoute +} from './app/routes'; import { applyDesignSystemTheme, - designSystemThemes, getStoredDesignSystemTheme, type DesignSystemThemeId } from './designSystem'; - -type ScreenId = - | 'dashboard' - | 'channels' - | 'builder' - | 'editChannel' - | 'guide' - | 'schedules' - | 'blocks' - | 'templates' - | 'decos' - | 'decoTemplates' - | 'playouts' - | 'media' - | 'search' - | 'trash' - | 'collections' - | 'multiCollections' - | 'rerunCollections' - | 'playlists' - | 'fillerPresets' - | 'libraries' - | 'traktLists' - | 'ffmpegProfiles' - | 'watermarks' - | 'settings' - | 'apiKey' - | 'logs' - | 'troubleshooting' - | 'blockPlayoutTroubleshooting' - | 'playbackTroubleshooting' - | 'yamlValidator'; - -interface ScreenRoute { - id: ScreenId; - path: string; - label: string; - title: string; - kicker: string; - description: string; - icon: ReactNode; - primaryAction: string; - placeholder: string; - badge?: number; - // Screens that own linkable sub-sections (e.g. /app/settings/streaming) opt in here; - // the sub-path is otherwise unowned and 404s (see routeFromLocation). - allowSubPaths?: boolean; -} - -const routes: ScreenRoute[] = [ - { - id: 'dashboard', - path: '/app', - label: 'Dashboard', - title: 'Dashboard', - kicker: 'Overview', - description: 'On-air status, health checks, and recent server activity.', - icon: