refactor(web): extract ChicoryTV shell and routing #361

Merged
timothy merged 7 commits from feat/247-shell-routing into main 2026-07-16 13:42:20 +02:00
14 changed files with 3061 additions and 2529 deletions
+35
View File
@@ -55,6 +55,7 @@ keep append-only from accreting stale, contradictory, or unreadably-large histor
- [2026-07-11 — EntityLocker: atomic flags + single-owner release discipline, no owner tokens (#231)](#2026-07-11--entitylocker-atomic-flags--single-owner-release-discipline-no-owner-tokens-231)
- [2026-07-11 — Channels screen extraction (#244): single-file screen, no sibling helper dir (epic #243 phase 1)](#2026-07-11--channels-screen-extraction-244-single-file-screen-no-sibling-helper-dir-epic-243-phase-1)
- [2026-07-14 — Playouts screen extraction (#245): screen-owned route wrapper (epic #243 phase 2)](#2026-07-14--playouts-screen-extraction-245-screen-owned-route-wrapper-epic-243-phase-2)
- [2026-07-15 — App shell/routing extraction + explicit primary-action ownership (#247)](#2026-07-15--app-shellrouting-extraction--explicit-primary-action-ownership-247)
- [2026-07-11 — Media-source management REST write API + SPA (#202)](#2026-07-11--media-source-management-rest-write-api--spa-202)
- [2026-07-11 — Legacy→SPA redirect matcher: exact map + ordered segment-template patterns (#204)](#2026-07-11--legacyspa-redirect-matcher-exact-map--ordered-segment-template-patterns-204)
- [2026-07-11 — Blazor removal auth posture: no new exposure beyond phase (a); real auth deferred to #197 (#206)](#2026-07-11--blazor-removal-auth-posture-no-new-exposure-beyond-phase-a-real-auth-deferred-to-197-206)
@@ -1809,3 +1810,37 @@ guards to these pre-existing promise completions; changing those semantics belon
Detailed behavior tests now render `PlayoutsScreen` directly with a scoped fetch mock, including the
zero-playout Add Playout affordance, lock/409 handling, refresh/poll ownership, action and kind gates, and
dialog flows. Refs #245 #243.
## 2026-07-15 — App shell/routing extraction + explicit primary-action ownership (#247)
Final phase of the App.tsx modularization epic (#243). `web/src/App.tsx` is now only the composition
root: it owns `activeRoute`, `currentPathRef`, the `navigate`/`popstate` pair that consults the dirty
guard, the approved `librariesSubPath`, and the global theme/health inputs, then composes the shell with
the matched screen. Route metadata/matching/sidebar groups moved to `web/src/app/routes.tsx`; shell chrome
(Sidebar, TopBar, Connect menu, version and theme controls) moved to `app/AppShell.tsx`; exhaustive screen
dispatch plus the Media/Libraries wrappers moved to `app/ScreenContent.tsx`. No route, styling, API, or
dependency changed.
**Route identity is deliberate infrastructure.** `routes.tsx` contains the ONE stable module-level array
of shared `ScreenRoute` objects. `routeFromLocation()` returns those same references for an
`allowSubPaths` base path and every owned sub-path, so React's `Object.is` state bailout remains part of
the contract rather than an accidental implementation detail. The three existing sub-path mechanisms stay
distinct: Playouts and Media self-own `pathname`/`popstate`; guarded Libraries receives only the path App
approved after its dirty guard; the remaining route screens retain their established self-owned or keyed
remount behavior. The extraction does not unify them into a speculative router/framework. `ScreenContent`
uses an exhaustive `ScreenId` switch, so a future route added without a dispatch branch fails typecheck
instead of silently falling through to a placeholder.
**Primary actions are one explicit screen-owned registration, not a global event.** The old
`ctv:primary-action` window `CustomEvent` and string-keyed dispatcher are removed. `PrimaryActionProvider`
holds exactly one `{ routeId, handler, owner }` registration shared by the active screen and TopBar;
`usePrimaryAction` registers it, keeps the latest handler behind a ref without ownership churn, and clears
it only when the same opaque owner unmounts. A stale cleanup therefore cannot erase a newer screen's
action. TopBar renders the Plus action only when the route has a non-empty label AND that active route owns
a matching registration, so metadata alone can no longer create a dead button. This is intentionally not a
generic action bus: one declared action per screen is the whole contract.
Tests pin stable route-object identity (including sibling sub-paths and query-only URLs), composition-level
sub-path rendering and dirty-popstate restoration, and primary-action matching/latest-handler/route-change/
cleanup/stale-owner behavior. Detailed Builder and Settings behavior is colocated with those screens while
`App.test.tsx` remains shell/routing/composition coverage. Refs #247 #243 #238 #230.
+35 -18
View File
@@ -12,8 +12,14 @@ Companion to `api-conventions.md` (the API surface the SPA talks to) and `docs/c
Vite + React + TypeScript, builds to `ErsatzTV/wwwroot/app` (see `web/vite.config.ts`:
`base: '/app/'`, `build.outDir: '../ErsatzTV/wwwroot/app'`), served by the ASP.NET host at `/app`.
- **Routes + nav**: `web/src/App.tsx` — one big route table of `ScreenRoute` objects (`path`,
`label`, `title`, `kicker`, `icon`, etc.) plus an `allowSubPaths?: boolean` flag.
- **Composition root**: `web/src/App.tsx` — owns the active route, approved Libraries sub-path,
navigation guard integration, and theme; it composes the shell with the matched screen.
- **Routes + nav**: `web/src/app/routes.tsx` — the ONE stable module-level array of `ScreenRoute`
objects (`path`, `label`, `title`, `kicker`, `icon`, etc.) plus `allowSubPaths?: boolean`, the
matcher, and sidebar group definitions. Route objects must never be rebuilt per render.
- **Shell + screen dispatch**: `web/src/app/AppShell.tsx` owns Sidebar/TopBar/Connect/version/theme
chrome; `web/src/app/ScreenContent.tsx` exhaustively maps a matched route to its screen and owns
the Media/Libraries route wrappers.
- **Screens**: `web/src/screens/*.tsx`, one file per top-level screen, generally with a colocated
`*.test.tsx`.
- **API clients**: `web/src/api/<domain>.ts` (see §4).
@@ -25,9 +31,10 @@ Vite + React + TypeScript, builds to `ErsatzTV/wwwroot/app` (see `web/vite.confi
If a route sets `allowSubPaths: true` (e.g. so `/app/blocks/{id}` works under the `/app/blocks` nav
entry), **the screen component itself must track `window.location.pathname` and listen for
`popstate`** — do not rely on `App.tsx` re-rendering `ScreenContent` when the sub-path changes.
`popstate`** — do not rely on the composition root re-rendering `ScreenContent` when the sub-path
changes.
**Why**: `App.tsx`'s `routeFromLocation()` matches an `allowSubPaths` route by prefix
**Why**: `app/routes.tsx`'s `routeFromLocation()` matches an `allowSubPaths` route by prefix
(`pathname.startsWith(\`${route.path}/\`)`) and returns the **same `ScreenRoute` object reference**
for the base path and every sub-path under it. `App`'s state update is
`setActiveRoute(routeFromLocation())`; React's `useState` setter bails via `Object.is` when the new
@@ -46,8 +53,8 @@ Exemplars of screens that already do this correctly: `BlocksScreen.tsx`, `Templa
**Exception — a guarded sub-path route defers pathname ownership to App.** When a sub-path route's
screens ALSO register a dirty guard (§8), the wrapper must **not** self-listen for `popstate`; App
owns the pathname and passes the approved sub-path down as a prop. The `LibrariesRouteScreen` wrapper
in `App.tsx` is the exemplar (sub-path parsed by `parseLibrariesSubRoute`, dispatched via a flat
`switch`, sub-path supplied by App's `librariesSubPath` state). See §8 for why child-before-parent
in `app/ScreenContent.tsx` is the exemplar (sub-path parsed by `parseLibrariesSubRoute`, dispatched
via a flat `switch`, sub-path supplied by App's `librariesSubPath` state). See §8 for why child-before-parent
effect order makes the self-listening pattern unsafe here.
## 3. Data loading pattern
@@ -251,16 +258,17 @@ is gone. The SPA seams now are:
- **vitest**, colocated `*.test.ts` / `*.test.tsx` next to the source file.
- Every screen with meaningful logic gets a screen test; every API client module gets a
param-mapping / URL-building test (e.g. `logs.test.ts` next to `logs.ts`).
- `web/src/App.test.tsx` covers navigation + the route table, including regressions like the
sub-path bug in §2 (see the tests around `PlayoutsRouteScreen` that click into
`/app/playouts/{id}/...` sub-paths and assert the correct sub-screen rendered).
- `web/src/App.test.tsx` covers composition, navigation, shell behavior, and integration regressions
such as sub-path-to-sub-path rendering and guarded popstate restoration. Detailed screen behavior
belongs in the screen's colocated test. `web/src/app/routes.test.tsx` independently pins stable
route-object identity and query/path matching.
- **Nav-label test-selector care**: `getByRole('link'/'button', { name: /Regex/ })` matches by
substring by default — a loose regex can match more than one nav item. Verified example: the
System nav button is matched with an **anchored** regex (`name: /^System/`) rather than a bare
`/System/`, specifically to avoid ambiguous matches against other labels that start with or
contain "System". Anchor (`^`/`$`) or use exact strings in `getByRole` name matchers whenever a
new label could be a substring of (or share a substring with) an existing one — check
`App.tsx`'s nav `label:` list for collisions before picking a new label.
`app/routes.tsx`'s nav `label:` list for collisions before picking a new label.
- **Extracted-screen tests own their own fetch mock** (Schedules #207, Channels #244, Playouts
#245): when a
screen is pulled out of `App.tsx` into `web/src/screens/<Name>Screen.tsx`, its colocated
@@ -356,21 +364,30 @@ Keep the guard predicate reading a **ref** (`dirtyRef`), not the `dirty` state v
## 10. TopBar primary-action button (`usePrimaryAction`)
The shell TopBar (`App.tsx`) renders at most **one** primary-action button (top-right, Plus icon) for the
active screen. The TopBar has no reference to the screen component, so the click is delivered as a window
`CustomEvent` keyed on the active route id; the seam is `web/src/primaryAction.ts`:
The shell TopBar (`app/AppShell.tsx`) renders at most **one** primary-action button (top-right, Plus
icon) for the active screen. `App.tsx` wraps the shell and matched screen in the minimal
`PrimaryActionProvider` from `web/src/primaryAction.ts`: the active screen explicitly registers one
handler, and the TopBar reads that matching registration directly from React context. No window event,
string-keyed dispatcher, or generic screen-action framework participates in normal screen actions.
- **A screen opts in** by calling `usePrimaryAction(routeId, handler)` at the **top of the component, before
any early return** (it's a hook). The handler must be reachable there — a create/navigate handler or a
`useState` setter, not something defined below a loading/error `return`. Reference: `SchedulesScreen`
(`usePrimaryAction('schedules', () => setForm('create'))`).
- **The route must ALSO declare a matching non-empty `primaryAction` label** in the `routes` table. The
TopBar renders the button **only when `route.primaryAction` is non-empty** — so declaring a label without
subscribing renders a dead button, and subscribing without a label renders nothing. Keep the two in lockstep.
- **The provider owns exactly one registration.** Each mounted hook gets an opaque owner token; registering a
newer screen replaces the previous registration, and cleanup clears only the registration owned by that
hook. A stale unmount therefore cannot erase the newer screen's action. The hook keeps the latest handler in
a ref, so ordinary screen renders update behavior without reclaiming/churning ownership. Directly-rendered
screen tests outside the provider remain harmless; there is simply no shell action consumer.
- **The route must ALSO declare a matching non-empty `primaryAction` label** in the stable
`app/routes.tsx` table. The TopBar renders the button only when that label is non-empty **and** the active
route owns a matching registration — metadata alone can no longer produce a dead button, while a
registration without a label remains intentionally invisible. Keep the two in lockstep.
The `#238` tests in `App.test.tsx` guard this: a data-driven `it.each` asserts each URL-navigating create
screen's banner actually navigates (so a typo'd route id → a button that navigates nowhere → red), plus a
drop test that an action screen shows no banner button. The dialog/editor create screens (schedules, multi/
rerun collections, trakt) are exercised by their own create-flow tests.
drop test that an action screen shows no banner button. `primaryAction.test.tsx` separately pins matching,
latest-handler, route-change, cleanup, and stale-owner semantics. The dialog/editor create screens
(schedules, multi/rerun collections, trakt) are exercised by their own create-flow tests.
- **When to WIRE vs DROP (issue #238).** The Plus icon makes the button semantically a *"create new item"*
affordance. **Keep + wire it only on list screens with a single, unambiguous create flow** ("Add Channel",
"Add Schedule", "Add Multi-Collection", "Add Rerun Collection", "Add Trakt List", "Add Filler Preset", "Add
+74 -1311
View File
File diff suppressed because it is too large Load Diff
+35 -1150
View File
File diff suppressed because it is too large Load Diff
+364
View File
@@ -0,0 +1,364 @@
import {
Fragment,
useEffect,
useRef,
useState,
type KeyboardEvent,
type MouseEvent,
type ReactNode
} from 'react';
import {
Bell,
CalendarClock,
Cast,
Check,
ChevronDown,
CircleHelp,
ClipboardCopy,
Info,
ListVideo,
Plus,
Search
} from 'lucide-react';
import chicoryMarkUrl from '../../../design-system/assets/chicory-mark.svg';
import {
useChannelsQuery,
useDashboardVersionQuery,
type DashboardHealthQueryState
} from '../api';
import {
Button,
IconButton,
NavItem,
NavSection
} from '../components';
import {
designSystemThemes,
type DesignSystemThemeId
} from '../designSystem';
import { usePrimaryActionHandler } from '../primaryAction';
import { navigateToPath } from '../routing';
import { DashboardHealthSummary } from '../screens/DashboardScreen';
import { UnauthorizedBanner } from '../UnauthorizedBanner';
import { UserMenu } from '../UserMenu';
import {
routeById,
routeHref,
sidebarNavGroups,
type ScreenId,
type ScreenRoute
} from './routes';
type NavigateHandler = (route: ScreenRoute, event: MouseEvent) => void;
function SidebarNavGroup({
activeRoute,
ids,
onNavigate
}: {
activeRoute: ScreenRoute | null;
ids: readonly ScreenId[];
onNavigate: NavigateHandler;
}) {
return (
<>
{ids.map((id) => {
const route = routeById.get(id)!;
return (
<NavItem
key={route.id}
icon={route.icon}
label={route.label}
active={route.id === activeRoute?.id}
badge={route.badge}
badgeTone="warn"
href={routeHref(route)}
onClick={(event) => onNavigate(route, event)}
/>
);
})}
</>
);
}
function ThemeSwitcher({
theme,
onThemeChange
}: {
theme: DesignSystemThemeId;
onThemeChange: (theme: DesignSystemThemeId) => void;
}) {
return (
<section className="ctv-theme-switcher" aria-label="Theme">
<span>Theme</span>
<div>
{designSystemThemes.map(({ id, description, label }) => (
<button
key={id}
type="button"
className={`ctv-theme-swatch ctv-theme-swatch-${id}`}
aria-label={description}
aria-pressed={theme === id}
title={label}
onClick={() => onThemeChange(id)}
/>
))}
</div>
</section>
);
}
function Sidebar({
activeRoute,
healthState,
onNavigate
}: {
activeRoute: ScreenRoute | null;
healthState: DashboardHealthQueryState;
onNavigate: NavigateHandler;
}) {
return (
<aside className="ctv-sidebar">
<div className="ctv-brand">
<img src={chicoryMarkUrl} alt="ChicoryTV" />
<span className="ctv-brand-wordmark">
Chicory<span>TV</span>
</span>
</div>
<nav aria-label="Primary" className="ctv-nav">
{sidebarNavGroups.map(({ ids, label }) => (
<Fragment key={label ?? 'Primary'}>
{label ? <NavSection>{label}</NavSection> : null}
<SidebarNavGroup activeRoute={activeRoute} ids={ids} onNavigate={onNavigate} />
</Fragment>
))}
</nav>
<div className="ctv-sidebar-health">
<div>
<span>ChicoryTV</span>
<SidebarVersion />
</div>
<DashboardHealthSummary healthState={healthState} />
</div>
</aside>
);
}
function SidebarVersion() {
const versionQuery = useDashboardVersionQuery();
if (versionQuery.status === 'success') {
return <code>{versionQuery.version.appVersion ?? 'version unknown'}</code>;
}
if (versionQuery.status === 'error') {
return <code>version unavailable</code>;
}
return <code>loading version</code>;
}
function EndpointRow({ icon, label, url }: { icon: ReactNode; label: string; url: string }) {
const [copied, setCopied] = useState(false);
const copyUrl = () => {
void navigator.clipboard?.writeText(url);
setCopied(true);
window.setTimeout(() => setCopied(false), 1200);
};
return (
<div className="ctv-connect-endpoint">
<span className="ctv-connect-endpoint-icon">{icon}</span>
<div>
<strong>{label}</strong>
<code>{url}</code>
</div>
<button type="button" onClick={copyUrl}>
{copied ? <Check aria-hidden="true" size={13} /> : <ClipboardCopy aria-hidden="true" size={13} />}
{copied ? 'Copied' : 'Copy'}
</button>
</div>
);
}
function ConnectMenu() {
const [open, setOpen] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
const channelsQuery = useChannelsQuery();
const playlistUrl = `${window.location.origin}/iptv/channels.m3u`;
const guideUrl = `${window.location.origin}/iptv/xmltv.xml`;
useEffect(() => {
if (open) {
menuRef.current?.focus();
}
}, [open]);
const onMenuKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Escape') {
setOpen(false);
}
};
const channelCountLabel = (() => {
if (channelsQuery.status === 'loading') {
return 'Loading channels';
}
if (channelsQuery.status === 'error') {
return 'Channels unavailable';
}
const count = channelsQuery.channels.length;
return `${count} ${count === 1 ? 'channel' : 'channels'}`;
})();
return (
<div className="ctv-connect">
<button
type="button"
className="ctv-connect-button"
aria-expanded={open}
onClick={() => setOpen((current) => !current)}
>
<Cast aria-hidden="true" size={15} />
Connect
<ChevronDown aria-hidden="true" size={13} />
</button>
{open && (
<>
<button
type="button"
className="ctv-connect-dismiss"
aria-label="Close Connect menu"
onClick={() => setOpen(false)}
/>
<div
className="ctv-connect-menu"
role="dialog"
aria-label="Connect a player"
tabIndex={-1}
ref={menuRef}
onKeyDown={onMenuKeyDown}
>
<div className="ctv-connect-header">
<strong>Connect a player</strong>
<span>{channelCountLabel}</span>
</div>
<EndpointRow
icon={<ListVideo aria-hidden="true" size={15} />}
label="M3U playlist"
url={playlistUrl}
/>
<EndpointRow
icon={<CalendarClock aria-hidden="true" size={15} />}
label="XMLTV guide"
url={guideUrl}
/>
<p>
<Info aria-hidden="true" size={13} />
Works with any IPTV player.
</p>
</div>
</>
)}
</div>
);
}
function TopBar({ route }: { route: ScreenRoute | null }) {
const title = route?.title ?? 'Page not found';
const kicker = route?.kicker ?? 'Unknown route';
const primaryAction = route?.primaryAction ?? '';
const primaryActionHandler = usePrimaryActionHandler(route?.id ?? '');
const [searchValue, setSearchValue] = useState('');
return (
<header className="ctv-topbar">
<div className="ctv-topbar-title">
<p>{kicker}</p>
<h1>{title}</h1>
</div>
<form
className="ctv-topbar-search"
onSubmit={(event) => {
event.preventDefault();
const trimmed = searchValue.trim();
if (trimmed) {
navigateToPath(`/app/search?query=${encodeURIComponent(trimmed)}`);
}
}}
role="search"
>
<Search aria-hidden="true" size={15} />
<input
aria-label="Search"
onChange={(event) => setSearchValue(event.target.value)}
placeholder="Search movies, shows, music..."
type="search"
value={searchValue}
/>
</form>
<div className="ctv-topbar-spacer" />
<div className="ctv-topbar-tools">
<UserMenu />
<ConnectMenu />
<span className="ctv-topbar-divider" />
<IconButton title="Documentation" size="sm">
<CircleHelp aria-hidden="true" size={17} />
</IconButton>
<IconButton title="Notifications" size="sm">
<Bell aria-hidden="true" size={17} />
</IconButton>
<span className="ctv-avatar">TB</span>
</div>
{route && primaryAction && primaryActionHandler ? (
<Button
startIcon={<Plus aria-hidden="true" size={15} />}
onClick={primaryActionHandler}
>
{primaryAction}
</Button>
) : null}
</header>
);
}
export function AppShell({
children,
healthState,
onNavigate,
onThemeChange,
route,
theme
}: {
children: ReactNode;
healthState: DashboardHealthQueryState;
onNavigate: NavigateHandler;
onThemeChange: (theme: DesignSystemThemeId) => void;
route: ScreenRoute | null;
theme: DesignSystemThemeId;
}) {
return (
<div className="ctv-app-shell">
<Sidebar activeRoute={route} healthState={healthState} onNavigate={onNavigate} />
<div className="ctv-shell-body">
<TopBar route={route} />
<UnauthorizedBanner />
<main className="ctv-main">
<ThemeSwitcher theme={theme} onThemeChange={onThemeChange} />
{children}
</main>
</div>
</div>
);
}
+225
View File
@@ -0,0 +1,225 @@
import { useEffect, useState } from 'react';
import { Info } from 'lucide-react';
import type { DashboardHealthQueryState } from '../api';
import { ChannelBuilderScreen } from '../builder/ChannelBuilder';
import { Card } from '../components';
import {
parseLibrariesSubRoute,
parseMediaSubRoute
} from '../routing';
import { ApiKeyScreen } from '../screens/ApiKeyScreen';
import { BlockPlayoutTroubleshootingScreen } from '../screens/BlockPlayoutTroubleshootingScreen';
import { BlocksScreen } from '../screens/BlocksScreen';
import { ChannelEditScreen } from '../screens/ChannelEditScreen';
import { ChannelsScreen } from '../screens/ChannelsScreen';
import { CollectionsScreen } from '../screens/CollectionsScreen';
import { DashboardScreen } from '../screens/DashboardScreen';
import { DecoTemplatesScreen } from '../screens/DecoTemplatesScreen';
import { DecosScreen } from '../screens/DecosScreen';
import { FFmpegProfilesScreen } from '../screens/FFmpegProfilesScreen';
import { FillerPresetsScreen } from '../screens/FillerPresetsScreen';
import { GuideScreen } from '../screens/GuideScreen';
import { ImageBrowserScreen } from '../screens/ImageBrowserScreen';
import { LibrariesScreen } from '../screens/LibrariesScreen';
import { LocalLibraryEditScreen } from '../screens/LocalLibraryEditScreen';
import { LogsScreen } from '../screens/LogsScreen';
import { MediaBrowseScreen } from '../screens/MediaBrowseScreen';
import {
ArtistDetailScreen,
MovieDetailScreen,
SeasonDetailScreen,
ShowDetailScreen
} from '../screens/MediaDetailScreen';
import { MultiCollectionsScreen } from '../screens/MultiCollectionsScreen';
import { PathReplacementsEditScreen } from '../screens/PathReplacementsEditScreen';
import { PlaybackTroubleshootingScreen } from '../screens/PlaybackTroubleshootingScreen';
import { PlexSourceScreen } from '../screens/PlexSourceScreen';
import { PlaylistsScreen } from '../screens/PlaylistsScreen';
import { PlayoutsRouteScreen } from '../screens/PlayoutsScreen';
import { RemoteConnectionEditScreen } from '../screens/RemoteConnectionEditScreen';
import { RemoteLibrariesEditScreen } from '../screens/RemoteLibrariesEditScreen';
import { RemoteSourceScreen } from '../screens/RemoteSourceScreen';
import { RerunCollectionsScreen } from '../screens/RerunCollectionsScreen';
import { SchedulesScreen } from '../screens/SchedulesScreen';
import { SearchScreen } from '../screens/SearchScreen';
import { SettingsScreen } from '../screens/SettingsScreen';
import { TemplatesScreen } from '../screens/TemplatesScreen';
import { TraktListsScreen } from '../screens/TraktListsScreen';
import { TrashScreen } from '../screens/TrashScreen';
import { TroubleshootingScreen } from '../screens/TroubleshootingScreen';
import { WatermarksScreen } from '../screens/WatermarksScreen';
import { YamlValidatorScreen } from '../screens/YamlValidatorScreen';
import {
normalizeAppPath,
type ScreenId,
type ScreenRoute
} from './routes';
function NotFoundScreen() {
const pathname = normalizeAppPath(window.location.pathname);
return (
<div className="ctv-screen-stack">
<Card title={<h2>Unknown app route</h2>} subtitle="This URL does not match a ChicoryTV screen.">
<div className="ctv-placeholder-layout">
<div className="ctv-placeholder-icon"><Info aria-hidden="true" size={20} /></div>
<div>
<h3>Requested path</h3>
<p>{pathname}</p>
</div>
</div>
</Card>
</div>
);
}
// The Media nav entry owns detail sub-pages (/app/media/{movies|shows|seasons|artists}/{id}) and the
// image folder browser (/app/media/images/browser). Like PlayoutsRouteScreen, this wrapper tracks
// pathname locally + listens for popstate, because routeFromLocation() returns the SAME 'media'
// ScreenRoute object for the base grid and every sub-path (Object.is bails App's setActiveRoute).
export function MediaRouteScreen() {
const [pathname, setPathname] = useState(() => window.location.pathname);
const [search, setSearch] = useState(() => window.location.search);
useEffect(() => {
const onPopState = () => {
setPathname(window.location.pathname);
setSearch(window.location.search);
};
window.addEventListener('popstate', onPopState);
return () => window.removeEventListener('popstate', onPopState);
}, []);
const sub = parseMediaSubRoute(pathname);
if (sub?.kind === 'movie') {
return <MovieDetailScreen key={pathname} id={sub.id} />;
}
if (sub?.kind === 'show') {
return <ShowDetailScreen key={pathname} id={sub.id} />;
}
if (sub?.kind === 'season') {
return <SeasonDetailScreen key={pathname} id={sub.id} />;
}
if (sub?.kind === 'artist') {
return <ArtistDetailScreen key={pathname} id={sub.id} />;
}
if (sub?.kind === 'images') {
return <ImageBrowserScreen key={pathname} />;
}
return <MediaBrowseScreen key={search} />;
}
// The Libraries nav entry owns the media-source editor sub-paths. CRITICAL (design §D.2, finding 4):
// unlike PlayoutsRouteScreen/MediaRouteScreen this wrapper does NOT register its own `popstate`
// listener. Its editor sub-screens register a dirty guard, so App must approve the path first and
// pass it down. This wrapper never reads a raw navigation event.
export function LibrariesRouteScreen({ subPath }: { subPath: string }) {
const sub = parseLibrariesSubRoute(subPath);
if (sub === null) {
return <LibrariesScreen />;
}
switch (sub.kind) {
case 'local-new':
case 'local-edit':
return <LocalLibraryEditScreen key={subPath} />;
case 'remote-source':
return sub.family === 'plex'
? <PlexSourceScreen key={subPath} />
: <RemoteSourceScreen key={subPath} family={sub.family} />;
case 'remote-connection':
return <RemoteConnectionEditScreen key={subPath} family={sub.family} />;
case 'remote-libraries':
return <RemoteLibrariesEditScreen key={subPath} family={sub.family} sourceId={sub.id} />;
case 'remote-path-replacements':
return <PathReplacementsEditScreen key={subPath} family={sub.family} sourceId={sub.id} />;
}
}
function assertNeverScreen(screenId: never): never {
throw new Error(`Unhandled screen route: ${String(screenId)}`);
}
export function ScreenContent({
healthState,
librariesSubPath,
route
}: {
healthState: DashboardHealthQueryState;
librariesSubPath: string;
route: ScreenRoute | null;
}) {
if (route === null) {
return <NotFoundScreen />;
}
const routeId: ScreenId = route.id;
switch (routeId) {
case 'dashboard':
return <DashboardScreen healthState={healthState} />;
case 'channels':
return <ChannelsScreen />;
case 'builder':
return <ChannelBuilderScreen />;
case 'editChannel':
return <ChannelEditScreen key={window.location.pathname} />;
case 'guide':
return <GuideScreen />;
case 'schedules':
return <SchedulesScreen />;
case 'blocks':
return <BlocksScreen key={window.location.pathname} />;
case 'templates':
return <TemplatesScreen key={window.location.pathname} />;
case 'decos':
return <DecosScreen key={window.location.pathname} />;
case 'decoTemplates':
return <DecoTemplatesScreen key={window.location.pathname} />;
case 'playouts':
return <PlayoutsRouteScreen />;
case 'libraries':
return <LibrariesRouteScreen subPath={librariesSubPath} />;
case 'settings':
return <SettingsScreen />;
case 'apiKey':
return <ApiKeyScreen />;
case 'media':
return <MediaRouteScreen />;
case 'search':
return <SearchScreen key={window.location.search} />;
case 'trash':
return <TrashScreen />;
case 'collections':
return <CollectionsScreen />;
case 'multiCollections':
return <MultiCollectionsScreen />;
case 'rerunCollections':
return <RerunCollectionsScreen />;
case 'playlists':
return <PlaylistsScreen />;
case 'traktLists':
return <TraktListsScreen key={window.location.pathname} />;
case 'fillerPresets':
return <FillerPresetsScreen />;
case 'ffmpegProfiles':
return <FFmpegProfilesScreen />;
case 'watermarks':
return <WatermarksScreen />;
case 'logs':
return <LogsScreen />;
case 'troubleshooting':
return <TroubleshootingScreen />;
case 'blockPlayoutTroubleshooting':
return <BlockPlayoutTroubleshootingScreen />;
case 'playbackTroubleshooting':
return <PlaybackTroubleshootingScreen key={window.location.search} />;
case 'yamlValidator':
return <YamlValidatorScreen />;
default:
return assertNeverScreen(routeId);
}
}
+46
View File
@@ -0,0 +1,46 @@
import { afterEach, describe, expect, it } from 'vitest';
import {
routeById,
routeFromLocation
} from './routes';
describe('app route matching', () => {
afterEach(() => {
window.history.replaceState(null, '', '/app');
});
it('returns one stable route object across sibling allowSubPaths locations', () => {
const playoutsRoute = routeById.get('playouts');
window.history.replaceState(null, '', '/app/playouts/20/alternate-schedules');
const alternateSchedules = routeFromLocation();
window.history.replaceState(null, '', '/app/playouts/20/templates');
const templates = routeFromLocation();
expect(alternateSchedules).toBe(playoutsRoute);
expect(templates).toBe(playoutsRoute);
expect(templates).toBe(alternateSchedules);
});
it('ignores the query string while preserving the route object', () => {
const searchRoute = routeById.get('search');
window.history.replaceState(null, '', '/app/search?query=alpha');
const firstQuery = routeFromLocation();
window.history.replaceState(null, '', '/app/search?query=beta');
const secondQuery = routeFromLocation();
expect(firstQuery).toBe(searchRoute);
expect(secondQuery).toBe(searchRoute);
});
it('normalizes a trailing slash and rejects an unowned path', () => {
window.history.replaceState(null, '', '/app/channels/');
expect(routeFromLocation()).toBe(routeById.get('channels'));
window.history.replaceState(null, '', '/app/channels/42');
expect(routeFromLocation()).toBeNull();
});
});
+524
View File
@@ -0,0 +1,524 @@
import type { ReactNode } from 'react';
import {
Boxes,
Palette,
CalendarClock,
CalendarDays,
CalendarRange,
Clapperboard,
Film,
FolderTree,
KeyRound,
Layers,
LayoutDashboard,
LayoutGrid,
Library,
Link2,
ListChecks,
ListMusic,
ListVideo,
Plus,
Repeat,
ScrollText,
Search,
Settings,
SlidersHorizontal,
Stamp,
Stethoscope,
Trash2,
Tv
} from 'lucide-react';
export 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';
export 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;
}
// This is the one stable route-object table for the application. routeFromLocation returns
// references from this array so allowSubPaths navigations intentionally preserve object identity.
export const routes: ScreenRoute[] = [
{
id: 'dashboard',
path: '/app',
label: 'Dashboard',
title: 'Dashboard',
kicker: 'Overview',
description: 'On-air status, health checks, and recent server activity.',
icon: <LayoutDashboard aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Dashboard workspace'
},
{
id: 'channels',
path: '/app/channels',
label: 'Channels',
title: 'Channels',
kicker: 'Lineup',
description: 'Dense channel table, ordering tools, bulk actions, and playback status.',
icon: <Tv aria-hidden="true" size={16} />,
primaryAction: 'Add Channel',
placeholder: 'Channel list workspace'
},
{
id: 'builder',
path: '/app/new-channel',
label: 'New Channel',
title: 'New Channel',
kicker: 'Builder',
description: 'Library-to-lineup channel creation flow with template-backed defaults.',
icon: <Plus aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Channel builder workspace'
},
{
// Not in the sidebar nav; reached via the edit pencil on the channel table. The
// screen owns parsing the {id} suffix (see ChannelEditScreen), so it opts into
// sub-paths like /app/edit-channel/5.
id: 'editChannel',
path: '/app/edit-channel',
label: 'Edit Channel',
title: 'Edit Channel',
kicker: 'Channel',
description: 'Full channel editor: identity, playout, streaming, selection and branding.',
icon: <Tv aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Channel editor workspace',
allowSubPaths: true
},
{
id: 'guide',
path: '/app/guide',
label: 'Guide',
title: 'Guide',
kicker: 'EPG',
description: 'Timeline grid with channel rows, programme blocks, and a live now marker.',
icon: <LayoutGrid aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'EPG grid workspace'
},
{
id: 'schedules',
path: '/app/schedules',
label: 'Schedules',
title: 'Schedules',
kicker: 'Programming',
description: 'Two-pane schedule editor with drag ordering and progressive details.',
icon: <CalendarClock aria-hidden="true" size={16} />,
primaryAction: 'Add Schedule',
placeholder: 'Schedule editor workspace'
},
{
// The editor lives at a sub-path (/app/blocks/{id}); BlocksScreen owns parsing the id suffix.
id: 'blocks',
path: '/app/blocks',
label: 'Blocks',
title: 'Blocks',
kicker: 'Programming',
description: 'Group blocks and edit their items, durations, and playout preview.',
icon: <Boxes aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Blocks workspace',
allowSubPaths: true
},
{
// The editor lives at a sub-path (/app/templates/{id}); TemplatesScreen owns parsing the id suffix.
id: 'templates',
path: '/app/templates',
label: 'Templates',
title: 'Templates',
kicker: 'Programming',
description: 'Group templates and assign blocks to times of day.',
icon: <CalendarDays aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Templates workspace',
allowSubPaths: true
},
{
// The editor lives at a sub-path (/app/decos/{id}); DecosScreen owns parsing the id suffix.
id: 'decos',
path: '/app/decos',
label: 'Decos',
title: 'Decos',
kicker: 'Programming',
description: 'Group decos and configure watermark, graphics, break content, and filler overrides.',
icon: <Palette aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Decos workspace',
allowSubPaths: true
},
{
// The editor lives at a sub-path (/app/deco-templates/{id}); DecoTemplatesScreen owns parsing the id suffix.
id: 'decoTemplates',
path: '/app/deco-templates',
label: 'Deco Templates',
title: 'Deco Templates',
kicker: 'Programming',
description: 'Group deco templates and assign decos to times of day.',
icon: <CalendarRange aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Deco templates workspace',
allowSubPaths: true
},
{
// The alternate-schedules / templates editors live at sub-paths
// (/app/playouts/{id}/alternate-schedules, /app/playouts/{id}/templates).
id: 'playouts',
path: '/app/playouts',
label: 'Playouts',
title: 'Playouts',
kicker: 'Runtime',
description: 'Playout state, reset controls, timeline diagnostics, and build warnings.',
icon: <ListVideo aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Playouts workspace',
allowSubPaths: true
},
{
id: 'media',
path: '/app/media',
label: 'Browse',
title: 'Browse Media',
kicker: 'Media',
description: 'Browse indexed movies, shows, episodes, music and more by kind.',
icon: <Clapperboard aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Media browse workspace',
allowSubPaths: true
},
{
id: 'search',
path: '/app/search',
label: 'Search',
title: 'Search',
kicker: 'Media',
description: 'Search across every media kind at once.',
icon: <Search aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Search workspace',
allowSubPaths: true
},
{
id: 'trash',
path: '/app/trash',
label: 'Trash',
title: 'Trash',
kicker: 'Media',
description: 'Library items whose files have gone missing.',
icon: <Trash2 aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Trash workspace'
},
{
id: 'collections',
path: '/app/collections',
label: 'Collections',
title: 'Collections',
kicker: 'Media',
description: 'Manual, smart, multi, playlist, search, and rerun collection management.',
icon: <FolderTree aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Collections workspace'
},
{
id: 'multiCollections',
path: '/app/multi-collections',
label: 'Multi-Collections',
title: 'Multi-Collections',
kicker: 'Media',
description: 'Group manual and smart collections into a single schedulable collection.',
icon: <Layers aria-hidden="true" size={16} />,
primaryAction: 'Add Multi-Collection',
placeholder: 'Multi-collections workspace'
},
{
id: 'rerunCollections',
path: '/app/rerun-collections',
label: 'Rerun Collections',
title: 'Rerun Collections',
kicker: 'Media',
description: 'A collection with distinct first-run and rerun playback orders.',
icon: <Repeat aria-hidden="true" size={16} />,
primaryAction: 'Add Rerun Collection',
placeholder: 'Rerun collections workspace'
},
{
id: 'playlists',
path: '/app/playlists',
label: 'Playlists',
title: 'Playlists',
kicker: 'Media',
description: 'Group, order, and preview playlist items scheduled into channels.',
icon: <ListMusic aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Playlists workspace'
},
{
id: 'fillerPresets',
path: '/app/filler-presets',
label: 'Filler Presets',
title: 'Filler Presets',
kicker: 'Media',
description: 'Pre/mid/post-roll, tail and fallback filler presets used by schedules.',
icon: <Film aria-hidden="true" size={16} />,
primaryAction: 'Add Filler Preset',
placeholder: 'Filler presets workspace',
allowSubPaths: true
},
{
// The media-source editors live at sub-paths (/app/libraries/local/{id}, /app/libraries/plex,
// /app/libraries/{jellyfin|emby}/connection, .../{id}/sync, .../{id}/path-replacements).
// Unlike other allowSubPaths screens, the libraries wrapper does NOT self-listen for popstate:
// its editors register a dirty guard, so App owns pathname/popstate and passes the approved
// sub-path down (see LibrariesRouteScreen + spa-conventions §8, design §D.2).
id: 'libraries',
path: '/app/libraries',
label: 'Libraries',
title: 'Libraries',
kicker: 'Sources',
description: 'Local, Plex, Jellyfin, and Emby media source monitoring.',
icon: <Library aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Libraries workspace',
allowSubPaths: true
},
{
// The editor lives at a sub-path (/app/trakt-lists/{id}); the screen owns parsing the
// {id} suffix itself (see TraktListsScreen), same pattern as editChannel/settings.
id: 'traktLists',
path: '/app/trakt-lists',
label: 'Trakt Lists',
title: 'Trakt Lists',
kicker: 'Media',
description: 'Add, match, and manage Trakt list imports.',
icon: <Link2 aria-hidden="true" size={16} />,
primaryAction: 'Add Trakt List',
placeholder: 'Trakt lists workspace',
allowSubPaths: true
},
{
id: 'ffmpegProfiles',
path: '/app/ffmpeg-profiles',
label: 'FFmpeg Profiles',
title: 'FFmpeg Profiles',
kicker: 'System',
description: 'Transcoding profiles: resolution, video/audio formats, hardware acceleration.',
icon: <SlidersHorizontal aria-hidden="true" size={16} />,
primaryAction: 'Add Profile',
placeholder: 'FFmpeg profiles workspace',
allowSubPaths: true
},
{
id: 'watermarks',
path: '/app/watermarks',
label: 'Watermarks',
title: 'Watermarks',
kicker: 'System',
description: 'Channel watermark overlays: image, position, size and opacity.',
icon: <Stamp aria-hidden="true" size={16} />,
primaryAction: 'Add Watermark',
placeholder: 'Watermarks workspace',
allowSubPaths: true
},
{
id: 'settings',
path: '/app/settings',
label: 'Settings',
title: 'Settings',
kicker: 'System',
description: 'Server configuration, access keys, FFmpeg profiles, and UI preferences.',
icon: <Settings aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Settings workspace',
allowSubPaths: true
},
{
// Since #295 the browser authenticates by session cookie; this screen only *displays* the
// server machine key (for MCP / external REST clients) and, for local accounts, changes the
// admin password — there is no key to "save" here (see spa-conventions §5e).
id: 'apiKey',
path: '/app/api-key',
label: 'API Key',
title: 'API Key',
kicker: 'System',
description: 'View the machine key for MCP and external REST clients, and change the local admin password.',
icon: <KeyRound aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'API key workspace'
},
{
id: 'logs',
path: '/app/logs',
label: 'Logs',
title: 'Logs',
kicker: 'System',
description: 'Recent server log entries with level and free-text filtering.',
icon: <ScrollText aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Logs workspace'
},
{
id: 'troubleshooting',
path: '/app/troubleshooting',
label: 'Troubleshooting',
title: 'Troubleshooting',
kicker: 'System',
description: 'Version, environment, hardware and FFmpeg capability diagnostics.',
icon: <Stethoscope aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Troubleshooting workspace'
},
{
id: 'blockPlayoutTroubleshooting',
path: '/app/troubleshooting/blocks',
label: 'Block History',
title: 'Block Playout Troubleshooting',
kicker: 'System',
description: 'Inspect a block playout, its blocks, and each block’s scheduling history.',
icon: <Boxes aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Block playout troubleshooting workspace'
},
{
id: 'playbackTroubleshooting',
path: '/app/troubleshooting/playback',
label: 'Playback Troubleshooting',
title: 'Playback Troubleshooting',
kicker: 'System',
description: 'Preview channel or media-item playback with a chosen FFmpeg profile and inspect the transcode logs.',
icon: <Stethoscope aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Playback troubleshooting workspace'
},
{
id: 'yamlValidator',
path: '/app/troubleshooting/yaml',
label: 'Schedule Validator',
title: 'Sequential Schedule Validator',
kicker: 'System',
description: 'Validate a sequential-schedule YAML document against the schema.',
icon: <ListChecks aria-hidden="true" size={16} />,
primaryAction: '',
placeholder: 'Sequential schedule validator workspace'
}
];
export const routeById = new Map(routes.map((route) => [route.id, route]));
export interface SidebarNavGroupDefinition {
label?: string;
ids: readonly ScreenId[];
}
export const sidebarNavGroups: SidebarNavGroupDefinition[] = [
{
ids: [
'dashboard',
'channels',
'builder',
'guide',
'schedules',
'blocks',
'templates',
'decos',
'decoTemplates',
'playouts'
]
},
{
label: 'Media',
ids: [
'media',
'search',
'trash',
'collections',
'multiCollections',
'rerunCollections',
'playlists',
'fillerPresets',
'libraries',
'traktLists'
]
},
{
label: 'System',
ids: [
'settings',
'apiKey',
'logs',
'troubleshooting',
'blockPlayoutTroubleshooting',
'yamlValidator',
'ffmpegProfiles',
'watermarks'
]
}
];
export function normalizeAppPath(pathname: string): string {
return pathname.replace(/\/+$/, '') || '/app';
}
export function routeFromLocation(): ScreenRoute | null {
const pathname = normalizeAppPath(window.location.pathname);
const exactMatch = routes.find((route) => route.path === pathname);
if (exactMatch) {
return exactMatch;
}
// Fall back to a sub-path of a route that has explicitly opted into linkable
// sub-sections (e.g. /app/settings/streaming) - the screen owns parsing the
// suffix itself (see SettingsScreen).
const prefixMatches = routes
.filter((route) => route.allowSubPaths && pathname.startsWith(`${route.path}/`))
.sort((a, b) => b.path.length - a.path.length);
return prefixMatches[0] ?? null;
}
export function routeHref(route: ScreenRoute): string {
return route.id === 'dashboard' ? '/app' : route.path;
}
+796 -18
View File
@@ -1,5 +1,6 @@
import { cleanup, render, waitFor } from '@testing-library/react';
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { applyDesignSystemTheme } from '../designSystem';
import { ChannelBuilderScreen } from './ChannelBuilder';
function jsonResponse(body: unknown, status = 200): Response {
@@ -9,42 +10,208 @@ function jsonResponse(body: unknown, status = 200): Response {
});
}
// Mocks every endpoint the builder loads on mount so it can render its library
// browser, plus /api/v1/library/browse which the browse hook fans out across.
function mockBuilderApi() {
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL) => {
const url = input.toString();
// ---- Channel Builder (#89) fixtures ----------------------------------------
// The API serializes with Newtonsoft NullValueHandling.Ignore: null-valued
// members are omitted from the wire entirely. Fixtures mirror that by
// stripping null/undefined keys after overrides are applied.
function omitNullKeys(fixture: Record<string, unknown>): Record<string, unknown> {
return Object.fromEntries(Object.entries(fixture).filter(([, value]) => value != null));
}
if (url.startsWith('/api/v1/library/browse')) {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
// ChannelResponseModel
function channelSummary(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
categories: '',
ffmpegProfile: '1080p H.264',
group: 'ChicoryTV',
id: 1,
isEnabled: true,
language: 'English',
name: 'Movies',
number: '5',
showInEpg: true,
sortNumber: 5,
streamingMode: 'HttpLiveStreamingSegmenter',
...overrides
};
}
// ChannelTemplateResponseModel — nullable members (filler/watermark ids,
// preferred languages, streamSelector, musicVideoCreditsTemplate) are null on
// the Standard template and therefore absent from the serialized payload.
function channelTemplate(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return omitNullKeys({
description: 'General-purpose 1080p H.264.',
ffmpegProfileId: 100,
fixedStartTimeBehavior: 'Strict',
id: 10,
idleBehavior: 'StopOnDisconnect',
isDefault: true,
isSystem: true,
musicVideoCreditsMode: 'None',
name: 'Standard',
playoutMode: 'Continuous',
playoutSource: 'Generated',
randomStartPoint: false,
shuffleScheduleItems: false,
songVideoMode: 'Default',
streamSelectorMode: 'Default',
streamingMode: 'HttpLiveStreamingSegmenter',
subtitleMode: 'None',
transcodeMode: 'OnDemand',
...overrides
});
}
// LibraryBrowseItemResponseModel - Newtonsoft omits null fields, so exactly one
// typed id is populated and nullable metadata (duration/itemCount) is absent
// unless the caller supplies it.
function browseItem(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return omitNullKeys({
artwork: '',
collectionType: 'TelevisionShow',
id: 1,
libraryId: 31,
libraryName: 'Cartoons',
mediaItemId: 1,
mediaType: 'TelevisionShow',
title: 'Looney Tunes',
...overrides
});
}
// FFmpegFullProfileResponseModel (only id/name are read by the builder)
function ffmpegProfile(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return { id: 100, name: '1080p H.264', ...overrides };
}
// Read the JSON body captured for a mutating request to `path`.
function requestBodyFor(path: string): Record<string, unknown> {
const call = vi
.mocked(window.fetch)
.mock.calls.find(([input, init]) => input.toString() === path && init?.body != null);
if (!call) {
throw new Error(`no request captured for ${path}`);
}
return JSON.parse(call[1]?.body as string) as Record<string, unknown>;
}
function mockBuilderApi({
artworkUploadFailure = null,
browseHandler = null,
browseItems = [],
channels = [],
channelTemplates = [],
createTemplateResponse = null,
defaultChannelTemplate = null,
ffmpegProfiles = [],
fromLineupFailure = null,
fromLineupResponse = { channelId: 1, playlistId: null, playoutId: 3, programScheduleId: 2 }
}: {
artworkUploadFailure?: { status: number } | null;
browseHandler?: ((search: URLSearchParams) => { page: unknown[]; totalCount: number }) | null;
browseItems?: unknown[];
channels?: unknown[];
channelTemplates?: unknown[];
createTemplateResponse?: unknown;
defaultChannelTemplate?: unknown;
ffmpegProfiles?: unknown[];
fromLineupFailure?: { detail?: string; status?: number; title?: string } | null;
fromLineupResponse?: unknown;
} = {}) {
let currentChannelTemplates = channelTemplates;
return vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const path = input.toString();
if (path === '/api/v1/channels') {
return Promise.resolve(jsonResponse(channels));
}
if (url === '/api/v1/channel-templates/default') {
// Builder treats a 404 here as "no default template".
return Promise.resolve(jsonResponse({ status: 404, title: 'Not Found' }, 404));
if (path === '/api/v1/channels/from-lineup') {
if (fromLineupFailure) {
return Promise.resolve(jsonResponse(fromLineupFailure, fromLineupFailure.status ?? 422));
}
return Promise.resolve(jsonResponse(fromLineupResponse, 201));
}
// channels, channel-templates, ffmpeg/profiles, filler-presets, watermarks, media-sources
return Promise.resolve(jsonResponse([]));
if (path.startsWith('/api/v1/library/browse')) {
const search = new URL(path, window.location.origin).searchParams;
if (browseHandler) {
return Promise.resolve(jsonResponse(browseHandler(search)));
}
const mediaType = search.get('mediaType');
const page = mediaType
? browseItems.filter((item) => (item as { mediaType?: string }).mediaType === mediaType)
: browseItems;
return Promise.resolve(jsonResponse({ page, totalCount: page.length }));
}
if (path === '/api/v1/channel-templates') {
if ((init?.method ?? 'GET') === 'POST') {
const created = createTemplateResponse ?? channelTemplate();
currentChannelTemplates = [...currentChannelTemplates, created];
return Promise.resolve(jsonResponse(created, 201));
}
return Promise.resolve(jsonResponse(currentChannelTemplates));
}
if (path === '/api/v1/channel-templates/default') {
return Promise.resolve(
defaultChannelTemplate ? jsonResponse(defaultChannelTemplate) : jsonResponse(null, 404)
);
}
if (path === '/api/v1/ffmpeg/profiles') {
return Promise.resolve(jsonResponse(ffmpegProfiles));
}
if (path.startsWith('/api/v1/filler-presets')) {
return Promise.resolve(jsonResponse([]));
}
if (path === '/api/v1/watermarks' || path === '/api/v1/media-sources') {
return Promise.resolve(jsonResponse([]));
}
if (path === '/api/v1/artwork/uploads') {
if (artworkUploadFailure) {
return Promise.resolve(new Response(null, { status: artworkUploadFailure.status }));
}
return Promise.resolve(
jsonResponse({ contentType: 'image/png', path: '/artwork/logo/uploaded.png' }, 201)
);
}
return Promise.resolve(jsonResponse(null, 404));
});
}
function browseMediaTypes(fetchMock: ReturnType<typeof mockBuilderApi>): string[] {
return fetchMock.mock.calls
.map(([u]) => u.toString())
.filter((u) => u.startsWith('/api/v1/library/browse'))
.map((u) => new URL(u, 'http://localhost').searchParams.get('mediaType'))
.map(([url]) => url.toString())
.filter((url) => url.startsWith('/api/v1/library/browse'))
.map((url) => new URL(url, 'http://localhost').searchParams.get('mediaType'))
.filter((mediaType): mediaType is string => mediaType != null && mediaType !== '');
}
describe('ChannelBuilder library browse', () => {
describe('Channel Builder (#89)', () => {
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
window.history.replaceState(null, '', '/');
});
beforeEach(() => {
window.localStorage.clear();
document.documentElement.removeAttribute('data-theme');
window.history.replaceState(null, '', '/app/new-channel');
vi.restoreAllMocks();
});
it('fans out over movies/shows/artists and never requests TelevisionSeason', async () => {
@@ -52,7 +219,6 @@ describe('ChannelBuilder library browse', () => {
render(<ChannelBuilderScreen />);
// Wait until the initial library browse fan-out has fired.
await waitFor(() => {
expect(browseMediaTypes(fetchMock).length).toBeGreaterThan(0);
});
@@ -61,4 +227,616 @@ describe('ChannelBuilder library browse', () => {
expect(types).toEqual(new Set(['Movie', 'TelevisionShow', 'Artist']));
expect(types.has('TelevisionSeason')).toBe(false);
});
// ---- Channel Builder (#89) -----------------------------------------------
const renderBuilder = async () => {
window.history.replaceState(null, '', '/app/new-channel');
const utils = render(<ChannelBuilderScreen />);
await screen.findByPlaceholderText('Search shows & movies…');
return utils;
};
// The shell's nav link and top-bar primary action also read "New Channel" /
// "Create Channel"; scope these to the builder toolbar.
const createBtn = () =>
within(document.querySelector('.ctv-builder-toolbar') as HTMLElement).getByRole('button', {
name: 'Create Channel'
});
const builderTitle = () => screen.getByText('New Channel', { selector: '.ctv-builder-title' });
const numberField = () => screen.getByLabelText('Number', { exact: false }) as HTMLInputElement;
const builderDefaults = () => ({
channels: [channelSummary()],
channelTemplates: [channelTemplate()],
defaultChannelTemplate: channelTemplate(),
ffmpegProfiles: [ffmpegProfile()]
});
it('renders the builder three-column layout with library items and the default template', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })]
});
const { container } = await renderBuilder();
expect(builderTitle()).toBeInTheDocument();
expect(screen.getByText('Lineup')).toBeInTheDocument();
expect(screen.getByText('Channel Template')).toBeInTheDocument();
expect(screen.getByText('Standard')).toBeInTheDocument();
expect(await screen.findByText('Looney Tunes')).toBeInTheDocument();
expect(screen.getByText('Tom & Jerry')).toBeInTheDocument();
expect(container.querySelectorAll('.ctv-builder-col')).toHaveLength(3);
expect(screen.getByText('This channel has no content yet. Double-click or drag titles from the library to build the lineup.')).toBeInTheDocument();
});
it('computes the AUTO channel number from the max integer part of existing channels', async () => {
mockBuilderApi({
...builderDefaults(),
channels: [channelSummary({ id: 1, number: '5' }), channelSummary({ id: 2, number: '13.1' })],
browseItems: [browseItem()]
});
await renderBuilder();
const numberInput = numberField();
expect(numberInput.value).toBe('14');
expect(screen.getByText('AUTO')).toBeInTheDocument();
});
it('adds a library item to the lineup on double-click and dedupes repeats', async () => {
mockBuilderApi({ ...builderDefaults(), browseItems: [browseItem()] });
const { container } = await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
expect(container.querySelector('.ctv-builder-summary')?.textContent).toContain('1 in lineup');
expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1);
fireEvent.doubleClick(screen.getAllByText('Looney Tunes')[0]);
expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1);
});
it('removes a lineup item and clears the lineup through the confirm dialog', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })]
});
const { container } = await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.doubleClick(screen.getByText('Tom & Jerry'));
expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(2);
fireEvent.click(within(container.querySelectorAll('.ctv-builder-lineup-row')[0] as HTMLElement).getByRole('button', { name: 'Remove' }));
expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
fireEvent.click(await screen.findByRole('button', { name: 'Clear lineup' }));
await waitFor(() => expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(0));
});
it('filters library results through the debounced search query', async () => {
mockBuilderApi({
...builderDefaults(),
browseHandler: (search) => {
const query = (search.get('query') ?? '').toLowerCase();
const mediaType = search.get('mediaType');
const all = [
browseItem(),
browseItem({ id: 2, mediaItemId: 2, mediaType: 'Movie', collectionType: 'Movie', title: 'Blade Runner', libraryName: 'Movies' })
];
const page = all
.filter((item) => !mediaType || item.mediaType === mediaType)
.filter((item) => !query || String(item.title).toLowerCase().includes(query));
return { page, totalCount: page.length };
}
});
await renderBuilder();
expect(await screen.findByText('Blade Runner')).toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText('Search shows & movies…'), { target: { value: 'blade' } });
await waitFor(() => expect(screen.queryByText('Looney Tunes')).not.toBeInTheDocument());
expect(screen.getByText('Blade Runner')).toBeInTheDocument();
});
it('reorders lineup items with native drag and drop', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })]
});
const { container } = await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.doubleClick(screen.getByText('Tom & Jerry'));
let rows = container.querySelectorAll('.ctv-builder-lineup-row');
expect(rows[0].querySelector('.ctv-builder-row-title')?.textContent).toBe('Looney Tunes');
fireEvent.dragStart(rows[0]);
fireEvent.dragOver(rows[1]);
fireEvent.drop(rows[1]);
rows = container.querySelectorAll('.ctv-builder-lineup-row');
expect(rows[0].querySelector('.ctv-builder-row-title')?.textContent).toBe('Tom & Jerry');
expect(rows[1].querySelector('.ctv-builder-row-title')?.textContent).toBe('Looney Tunes');
});
it('validates the channel number for format and uniqueness', async () => {
mockBuilderApi({
...builderDefaults(),
channels: [channelSummary({ number: '5' })],
browseItems: [browseItem()]
});
await renderBuilder();
const numberInput = numberField();
fireEvent.change(numberInput, { target: { value: 'abc' } });
expect(await screen.findByText(/Use digits/)).toBeInTheDocument();
fireEvent.change(numberInput, { target: { value: '5' } });
expect(await screen.findByText(/already in use/)).toBeInTheDocument();
});
it('keeps Create disabled until a name and at least one lineup item exist', async () => {
mockBuilderApi({ ...builderDefaults(), browseItems: [browseItem()] });
await renderBuilder();
const createButton = createBtn();
expect(createButton).toBeDisabled();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Retro Cartoons' } });
expect(createButton).toBeEnabled();
});
it('preselects the default template and flags an override when the Shuffle toggle diverges', async () => {
mockBuilderApi({ ...builderDefaults(), browseItems: [browseItem()] });
const { container } = await renderBuilder();
// default template has shuffleScheduleItems=false -> no override tag yet
expect(screen.queryByText('overrides template')).not.toBeInTheDocument();
const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement;
fireEvent.click(shuffleRow);
expect(await screen.findByText('overrides template')).toBeInTheDocument();
});
it('applies a selected template shuffle default and clears the override', async () => {
mockBuilderApi({
...builderDefaults(),
channelTemplates: [
channelTemplate(),
channelTemplate({ id: 11, isDefault: false, name: 'Music videos', shuffleScheduleItems: true })
],
browseItems: [browseItem()]
});
const { container } = await renderBuilder();
const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement;
fireEvent.click(shuffleRow);
expect(await screen.findByText('overrides template')).toBeInTheDocument();
// open the template picker and select the shuffle-by-default template
fireEvent.click(screen.getByText('Standard'));
fireEvent.click(await screen.findByText('Music videos'));
await waitFor(() => expect(screen.queryByText('overrides template')).not.toBeInTheDocument());
});
it('marks a rerun-collection row invalid in a multi-item lineup and blocks Create', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [
browseItem(),
browseItem({ id: 9, title: 'Saturday Block', mediaType: 'RerunCollection', collectionType: 'RerunFirstRun', collectionKind: 'Rerun', rerunCollectionId: 9, mediaItemId: undefined })
]
});
await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
// RerunCollection is a collections kind, not one of the 4 library kinds —
// find it under the Collections tab.
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
fireEvent.doubleClick(await screen.findByText('Saturday Block'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Mixed' } });
expect(await screen.findByText('Only valid alone')).toBeInTheDocument();
expect(createBtn()).toBeDisabled();
});
it('clears a MultiCollection shuffle requirement when the Shuffle toggle is turned on', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [
browseItem({ id: 7, title: 'Prime Time', mediaType: 'MultiCollection', collectionType: 'MultiCollection', multiCollectionId: 7, mediaItemId: undefined })
]
});
const { container } = await renderBuilder();
// MultiCollection is a collections kind, not one of the 4 library kinds —
// find it under the Collections tab.
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
fireEvent.doubleClick(await screen.findByText('Prime Time'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Multi' } });
expect(await screen.findByText('Requires Shuffle')).toBeInTheDocument();
expect(createBtn()).toBeDisabled();
const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement;
fireEvent.click(shuffleRow);
await waitFor(() => expect(screen.queryByText('Requires Shuffle')).not.toBeInTheDocument());
expect(createBtn()).toBeEnabled();
});
it('posts a well-formed create request and navigates to channels on success', async () => {
mockBuilderApi({
...builderDefaults(),
channels: [channelSummary({ number: '5' })],
browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })]
});
await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.doubleClick(screen.getByText('Tom & Jerry'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: ' Retro Cartoons ' } });
fireEvent.click(createBtn());
await waitFor(() => expect(window.location.pathname).toBe('/app/channels'));
const body = requestBodyFor('/api/v1/channels/from-lineup');
expect(body.name).toBe('Retro Cartoons');
expect(body.number).toBe('6');
expect(body.group).toBe('ChicoryTV');
expect(body.templateId).toBe(10);
expect(body.logo).toEqual({ contentType: '', path: '' });
expect((body.advanced as Record<string, unknown>).playbackOrder).toBe('Chronological');
expect((body.advanced as Record<string, unknown>).playoutMode).toBe('Continuous');
const lineup = body.lineup as Array<Record<string, unknown>>;
expect(lineup).toHaveLength(2);
expect(lineup[0].mediaItemId).toBe(1);
expect(lineup[1].mediaItemId).toBe(2);
expect(lineup[0].mediaType).toBe('TelevisionShow');
});
it('highlights the offending lineup row and shows the detail on a 422 ProblemDetails', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })],
// Verbatim wire shape: ApiResults hard-codes the 422 title "Validation failed",
// and the handler's not-found detail is "lineup[i] <Label> <id> does not exist."
fromLineupFailure: { detail: 'lineup[1] TelevisionShow 999 does not exist.', status: 422, title: 'Validation failed' }
});
const { container } = await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.doubleClick(screen.getByText('Tom & Jerry'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Retro' } });
fireEvent.click(createBtn());
expect(await screen.findByText('lineup[1] TelevisionShow 999 does not exist.')).toBeInTheDocument();
await waitFor(() => {
const rows = container.querySelectorAll('.ctv-builder-lineup-row');
expect(rows[1].classList.contains('ctv-builder-lineup-row-error')).toBe(true);
});
expect(window.location.pathname).toBe('/app/new-channel');
});
it('uploads the channel image then references the returned path in the create body', async () => {
mockBuilderApi({ ...builderDefaults(), browseItems: [browseItem()] });
const { container } = await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Retro' } });
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['logo-bytes'], 'logo.png', { type: 'image/png' });
fireEvent.change(fileInput, { target: { files: [file] } });
fireEvent.click(createBtn());
await waitFor(() => expect(window.location.pathname).toBe('/app/channels'));
const uploadCall = vi
.mocked(window.fetch)
.mock.calls.find(([input]) => input.toString() === '/api/v1/artwork/uploads');
expect(uploadCall).toBeDefined();
const formData = uploadCall?.[1]?.body as FormData;
expect(formData).toBeInstanceOf(FormData);
expect(formData.get('target')).toBe('logo');
expect((formData.get('file') as File).name).toBe('logo.png');
const body = requestBodyFor('/api/v1/channels/from-lineup');
expect(body.logo).toEqual({ contentType: 'image/png', path: '/artwork/logo/uploaded.png' });
});
it('fans out 5 typed browse requests in Collections mode and renders the merged, title-sorted items', async () => {
const byType: Record<string, Record<string, unknown>> = {
Collection: browseItem({
id: 2,
title: 'Saturday Cartoons',
mediaType: 'Collection',
collectionType: 'Collection',
collectionKind: 'Manual',
collectionId: 2,
mediaItemId: undefined
}),
SmartCollection: browseItem({
id: 3,
title: 'Action Movies',
mediaType: 'SmartCollection',
collectionType: 'SmartCollection',
collectionKind: 'Smart',
smartCollectionId: 3,
mediaItemId: undefined
}),
MultiCollection: browseItem({
id: 7,
title: 'Prime Time',
mediaType: 'MultiCollection',
collectionType: 'MultiCollection',
collectionKind: 'Multi',
multiCollectionId: 7,
mediaItemId: undefined
}),
RerunCollection: browseItem({
id: 9,
title: 'Saturday Block',
mediaType: 'RerunCollection',
collectionType: 'RerunFirstRun',
collectionKind: 'Rerun',
rerunCollectionId: 9,
mediaItemId: undefined
}),
Playlist: browseItem({
id: 12,
title: 'Zzz Late Night',
mediaType: 'Playlist',
collectionType: 'Playlist',
playlistId: 12,
mediaItemId: undefined
})
};
mockBuilderApi({
...builderDefaults(),
browseItems: [browseItem()],
browseHandler: (search) => {
const mediaType = search.get('mediaType');
const item = mediaType ? byType[mediaType] : undefined;
return item ? { page: [item], totalCount: 1 } : { page: [], totalCount: 0 };
}
});
const { container } = await renderBuilder();
// Wait for the initial library fan-out (Movie/TelevisionShow/Artist) to be
// ISSUED before clearing the mock — renderBuilder only awaits the search
// box, and React flushes passive effects asynchronously, so on a slow
// machine the mount fan-out can otherwise leak past mockClear and pollute
// the post-click assertion below.
await waitFor(() => {
const browseCalls = vi
.mocked(window.fetch)
.mock.calls.filter(([input]) => input.toString().startsWith('/api/v1/library/browse'));
expect(browseCalls.length).toBeGreaterThanOrEqual(3);
});
// Only count requests made after switching to the Collections tab.
vi.mocked(window.fetch).mockClear();
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
expect(await screen.findByText('Action Movies')).toBeInTheDocument();
const browseTypes = vi
.mocked(window.fetch)
.mock.calls.map(([input]) => input.toString())
.filter((url) => url.startsWith('/api/v1/library/browse'))
.map((url) => new URL(url, window.location.origin).searchParams.get('mediaType'))
.filter((mediaType): mediaType is string => mediaType != null);
expect(browseTypes).toEqual(['Collection', 'SmartCollection', 'MultiCollection', 'RerunCollection', 'Playlist']);
const titles = Array.from(container.querySelectorAll('.ctv-builder-poster-title')).map((el) => el.textContent);
expect(titles).toEqual(['Action Movies', 'Prime Time', 'Saturday Block', 'Saturday Cartoons', 'Zzz Late Night']);
});
it('loads a second page of library results and preserves the first page', async () => {
const pages = [
[browseItem({ id: 1, mediaItemId: 1, title: 'Item A' }), browseItem({ id: 2, mediaItemId: 2, title: 'Item B' })],
[browseItem({ id: 3, mediaItemId: 3, title: 'Item C' })]
];
mockBuilderApi({
...builderDefaults(),
browseHandler: (search) => {
// The builder fans out per-kind (Movie/TelevisionShow/TelevisionSeason/Artist);
// only return real pages for the kind these fixtures use (TelevisionShow) so
// the other 3 kinds don't duplicate the same items.
if (search.get('mediaType') !== 'TelevisionShow') {
return { page: [], totalCount: 0 };
}
const pageNum = Number(search.get('pageNum') ?? '0');
return { page: pages[pageNum] ?? [], totalCount: 3 };
}
});
await renderBuilder();
expect(await screen.findByText('Item A')).toBeInTheDocument();
expect(screen.getByText('Item B')).toBeInTheDocument();
expect(screen.queryByText('Item C')).not.toBeInTheDocument();
const loadMoreButton = screen.getByRole('button', { name: 'Load more' });
fireEvent.click(loadMoreButton);
expect(await screen.findByText('Item C')).toBeInTheDocument();
expect(screen.getByText('Item A')).toBeInTheDocument();
expect(screen.getByText('Item B')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument();
});
it('saves the current settings as a new template and selects it', async () => {
const created = channelTemplate({
id: 55,
name: 'Saturday Special',
description: 'Custom mix.',
isDefault: false,
isSystem: false,
shuffleScheduleItems: true
});
mockBuilderApi({
...builderDefaults(),
browseItems: [browseItem()],
createTemplateResponse: created
});
const { container } = await renderBuilder();
const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement;
fireEvent.click(shuffleRow);
fireEvent.click(screen.getByText('Standard'));
fireEvent.click(await screen.findByText('Save current settings as template…'));
expect(await screen.findByText('Save as channel template')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('Template name'), { target: { value: 'Saturday Special' } });
fireEvent.change(screen.getByLabelText('Description'), { target: { value: 'Custom mix.' } });
fireEvent.click(screen.getByRole('button', { name: 'Save template' }));
await waitFor(() => expect(screen.queryByText('Save as channel template')).not.toBeInTheDocument());
const body = requestBodyFor('/api/v1/channel-templates');
expect(body.name).toBe('Saturday Special');
expect(body.description).toBe('Custom mix.');
expect(body.shuffleScheduleItems).toBe(true);
expect(body.playoutMode).toBe('Continuous');
expect(screen.getByText('Saturday Special')).toBeInTheDocument();
});
it('shows a friendly error and skips channel creation when the artwork upload returns a bare 413', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [browseItem()],
artworkUploadFailure: { status: 413 }
});
const { container } = await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Retro' } });
const fileInput = container.querySelector('input[type="file"]') as HTMLInputElement;
const file = new File(['logo-bytes'], 'logo.png', { type: 'image/png' });
fireEvent.change(fileInput, { target: { files: [file] } });
fireEvent.click(createBtn());
expect(await screen.findByText('Image is too large (max 30 MB).')).toBeInTheDocument();
expect(window.location.pathname).toBe('/app/new-channel');
expect(
vi.mocked(window.fetch).mock.calls.some(([input]) => input.toString() === '/api/v1/channels/from-lineup')
).toBe(false);
expect(createBtn()).toBeEnabled();
});
it('renders the empty-templates state and keeps Create disabled with no templates', async () => {
mockBuilderApi({
...builderDefaults(),
channelTemplates: [],
defaultChannelTemplate: null,
browseItems: [browseItem()]
});
await renderBuilder();
expect(
screen.getByText(/No channel templates exist yet\. Create one in Settings before building a channel/)
).toBeInTheDocument();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Retro Cartoons' } });
expect(createBtn()).toBeDisabled();
});
it('sends a Collection lineup item with only its typed id populated', async () => {
mockBuilderApi({
...builderDefaults(),
browseItems: [
browseItem({
id: 2,
title: 'Saturday Cartoons',
mediaType: 'Collection',
collectionType: 'Collection',
collectionKind: 'Manual',
collectionId: 2,
mediaItemId: undefined
})
]
});
await renderBuilder();
// Collection is a collections kind, not one of the 4 library kinds —
// find it under the Collections tab.
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
fireEvent.doubleClick(await screen.findByText('Saturday Cartoons'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Marathon' } });
fireEvent.click(createBtn());
await waitFor(() => expect(window.location.pathname).toBe('/app/channels'));
const body = requestBodyFor('/api/v1/channels/from-lineup');
const lineup = body.lineup as Array<Record<string, unknown>>;
expect(lineup).toHaveLength(1);
expect(lineup[0].mediaType).toBe('Collection');
expect(lineup[0].collectionType).toBe('Collection');
expect(lineup[0].collectionId).toBe(2);
expect(lineup[0].mediaItemId).toBeUndefined();
expect(lineup[0].multiCollectionId).toBeUndefined();
expect(lineup[0].smartCollectionId).toBeUndefined();
expect(lineup[0].rerunCollectionId).toBeUndefined();
expect(lineup[0].playlistId).toBeUndefined();
});
it('renders the builder under the cool and dual design themes', async () => {
mockBuilderApi({ ...builderDefaults(), browseItems: [browseItem()] });
await renderBuilder();
applyDesignSystemTheme('cool');
expect(document.documentElement).toHaveAttribute('data-theme', 'cool');
expect(builderTitle()).toBeInTheDocument();
applyDesignSystemTheme('dual');
expect(document.documentElement).toHaveAttribute('data-theme', 'dual');
expect(screen.getByPlaceholderText('Search shows & movies…')).toBeInTheDocument();
});
});
+68
View File
@@ -0,0 +1,68 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
Button,
Checkbox,
Input,
ProgressBar,
Switch,
Tabs,
Toast,
Tooltip
} from '.';
describe('component primitives', () => {
afterEach(cleanup);
it('exports typed primitives with expected interactions', () => {
const onSwitch = vi.fn();
const onCheckbox = vi.fn();
const onTab = vi.fn();
render(
<>
<Button variant="primary" loading>
Saving
</Button>
<Switch checked={false} onChange={onSwitch} label="Show disabled" />
<Checkbox indeterminate onChange={onCheckbox} label="Select all" />
<Input label="Channel number" value="5.1" error="Already in use" onChange={() => {}} />
<ProgressBar value={62} showLabel />
<Tabs
value="streaming"
onChange={onTab}
tabs={[{ value: 'streaming', label: 'Streaming' }]}
/>
<Tooltip label="Reset playout">
<button type="button">Reset</button>
</Tooltip>
</>
);
expect(screen.getByRole('button', { name: 'Saving' })).toBeDisabled();
fireEvent.click(screen.getByRole('switch', { name: 'Show disabled' }));
expect(onSwitch).toHaveBeenCalledWith(true);
expect(screen.getByRole('checkbox', { name: 'Select all' })).toHaveAttribute(
'aria-checked',
'mixed'
);
expect(screen.getByText('Already in use')).toBeInTheDocument();
expect(screen.getByText('62%')).toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Streaming' }));
expect(onTab).toHaveBeenCalledWith('streaming');
fireEvent.mouseEnter(screen.getByText('Reset'));
expect(screen.getByRole('tooltip')).toHaveTextContent('Reset playout');
});
it('uses distinct semantic icons for warning and error toasts', () => {
const { container } = render(
<>
<Toast tone="warn" title="Check settings" />
<Toast tone="error" title="Save failed" />
</>
);
expect(container.querySelector('.lucide-triangle-alert')).toBeInTheDocument();
expect(container.querySelector('.lucide-circle-x')).toBeInTheDocument();
});
});
+152
View File
@@ -0,0 +1,152 @@
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 (
<button type="button" disabled={!handler} onClick={handler}>
Run {routeId}
</button>
);
}
describe('primary actions', () => {
afterEach(() => {
cleanup();
});
it('invokes the active handler for a matching route', () => {
const handler = vi.fn();
render(
<PrimaryActionProvider>
<Registration routeId="schedules" handler={handler} />
<Action routeId="schedules" />
</PrimaryActionProvider>
);
fireEvent.click(screen.getByRole('button', { name: 'Run schedules' }));
expect(handler).toHaveBeenCalledOnce();
});
it('returns no handler for a nonmatching route', () => {
const handler = vi.fn();
render(
<PrimaryActionProvider>
<Registration routeId="schedules" handler={handler} />
<Action routeId="channels" />
</PrimaryActionProvider>
);
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(
<PrimaryActionProvider>
<Registration routeId="schedules" handler={firstHandler} />
<Action routeId="schedules" />
</PrimaryActionProvider>
);
view.rerender(
<PrimaryActionProvider>
<Registration routeId="schedules" handler={latestHandler} />
<Action routeId="schedules" />
</PrimaryActionProvider>
);
fireEvent.click(screen.getByRole('button', { name: 'Run schedules' }));
expect(firstHandler).not.toHaveBeenCalled();
expect(latestHandler).toHaveBeenCalledOnce();
});
it("moves the same owner's registration to a new route and clears it on unmount", () => {
const handler = vi.fn();
const view = render(
<PrimaryActionProvider>
<Registration routeId="schedules" handler={handler} />
<Action routeId="schedules" />
<Action routeId="channels" />
</PrimaryActionProvider>
);
view.rerender(
<PrimaryActionProvider>
<Registration routeId="channels" handler={handler} />
<Action routeId="schedules" />
<Action routeId="channels" />
</PrimaryActionProvider>
);
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(
<PrimaryActionProvider>
<Action routeId="schedules" />
<Action routeId="channels" />
</PrimaryActionProvider>
);
expect(screen.getByRole('button', { name: 'Run channels' })).toBeDisabled();
});
it('does not let an older owner rerender or cleanup reclaim a newer registration', () => {
const olderHandler = vi.fn();
const updatedOlderHandler = vi.fn();
const newerHandler = vi.fn();
const view = render(
<PrimaryActionProvider>
<Registration key="older" routeId="schedules" handler={olderHandler} />
<Action routeId="schedules" />
</PrimaryActionProvider>
);
view.rerender(
<PrimaryActionProvider>
<Registration key="older" routeId="schedules" handler={olderHandler} />
<Registration key="newer" routeId="schedules" handler={newerHandler} />
<Action routeId="schedules" />
</PrimaryActionProvider>
);
view.rerender(
<PrimaryActionProvider>
<Registration key="older" routeId="schedules" handler={updatedOlderHandler} />
<Registration key="newer" routeId="schedules" handler={newerHandler} />
<Action routeId="schedules" />
</PrimaryActionProvider>
);
fireEvent.click(screen.getByRole('button', { name: 'Run schedules' }));
expect(newerHandler).toHaveBeenCalledOnce();
view.rerender(
<PrimaryActionProvider>
<Registration key="newer" routeId="schedules" handler={newerHandler} />
<Action routeId="schedules" />
</PrimaryActionProvider>
);
fireEvent.click(screen.getByRole('button', { name: 'Run schedules' }));
expect(olderHandler).not.toHaveBeenCalled();
expect(updatedOlderHandler).not.toHaveBeenCalled();
expect(newerHandler).toHaveBeenCalledTimes(2);
});
it('lets screens render harmlessly without a provider', () => {
expect(() => render(<Registration routeId="schedules" handler={vi.fn()} />)).not.toThrow();
});
});
+57 -28
View File
@@ -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<PrimaryActionContextValue | undefined>(undefined);
/** Owns the single primary-action registration shared by the shell and active screen. */
export function PrimaryActionProvider({ children }: { children: ReactNode }) {
const [registration, setRegistration] = useState<PrimaryActionRegistration>();
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<string>).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;
}
+19 -4
View File
@@ -1,5 +1,6 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PrimaryActionProvider, usePrimaryActionHandler } from '../primaryAction';
import { SchedulesScreen } from './SchedulesScreen';
function jsonResponse(body: unknown, status = 200): Response {
@@ -157,6 +158,11 @@ async function renderReady(options: MockOptions = {}) {
return handle;
}
function SchedulesPrimaryActionButton() {
const handler = usePrimaryActionHandler('schedules');
return <button type="button" disabled={!handler} onClick={handler}>TopBar action</button>;
}
describe('SchedulesScreen — load', () => {
it('renders the lineup for the active schedule', async () => {
await renderReady();
@@ -438,10 +444,19 @@ describe('SchedulesScreen — schedule CRUD', () => {
await waitFor(() => expect(handle.requests.some((r) => r.url === '/api/v1/schedules/99/items')).toBe(true));
});
it('responds to the TopBar primary-action event by opening create', async () => {
await renderReady();
window.dispatchEvent(new CustomEvent('ctv:primary-action', { detail: 'schedules' }));
await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy());
it('registers the TopBar primary action to open create', async () => {
mockApi();
render(
<PrimaryActionProvider>
<SchedulesPrimaryActionButton />
<SchedulesScreen />
</PrimaryActionProvider>
);
await waitFor(() => expect(screen.getByLabelText('Schedule lineup')).toBeTruthy());
fireEvent.click(screen.getByRole('button', { name: 'TopBar action' }));
expect(screen.getByRole('dialog')).toBeTruthy();
expect(within(screen.getByRole('dialog')).getByLabelText('Name')).toBeTruthy();
});
+631
View File
@@ -0,0 +1,631 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SettingsScreen } from './SettingsScreen';
describe('Settings screen (#93)', () => {
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
window.history.replaceState(null, '', '/');
});
beforeEach(() => {
window.localStorage.clear();
document.documentElement.removeAttribute('data-theme');
window.history.replaceState(null, '', '/app/settings/general');
vi.restoreAllMocks();
});
const openSettings = async () => {
render(<SettingsScreen />);
expect(
await screen.findByText('Interface preferences. These apply to the legacy web UI; ChicoryTV theming lives in the theme switcher.')
).toBeInTheDocument();
};
it('renders each section on nav click', async () => {
mockSettingsApi();
render(<SettingsScreen />);
expect(await screen.findByText('Interface preferences. These apply to the legacy web UI; ChicoryTV theming lives in the theme switcher.')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Streaming/ }));
expect(await screen.findByText('FFmpeg engine, transcoding defaults and HLS session tuning.')).toBeInTheDocument();
expect(window.location.pathname).toBe('/app/settings/streaming');
fireEvent.click(screen.getByRole('button', { name: /Playout/ }));
expect(await screen.findByText('Defaults for how far ahead playouts are built and how gaps are handled.')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Guide \(XMLTV\)/ }));
expect(await screen.findByText('Shape of the XMLTV guide data served to Jellyfin and other clients.')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Scanner/ }));
expect(await screen.findByText('Background scanning of local libraries.')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Logging/ }));
expect(await screen.findByText('Minimum level written per category. Verbose and Debug are noisy — use for troubleshooting only.')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /^System/ }));
expect(await screen.findByText('HDHomeRun emulation, connected media sources and server info.')).toBeInTheDocument();
});
it('supports deep-linking directly to a section path', async () => {
mockSettingsApi();
window.history.replaceState(null, '', '/app/settings/scanner');
render(<SettingsScreen />);
expect(await screen.findByText('Background scanning of local libraries.')).toBeInTheDocument();
});
it('loads values from the API into the General pane', async () => {
mockSettingsApi({ uiSettings: defaultUiSettings({ isDarkMode: false, language: 'fr' }) });
await openSettings();
expect(await screen.findByDisplayValue('Light')).toBeInTheDocument();
expect(screen.getByDisplayValue('fr')).toBeInTheDocument();
});
it('shows the save bar with the correct dirty count when editing a field, and Discard restores', async () => {
mockSettingsApi();
await openSettings();
const languageInput = screen.getByPlaceholderText('en-US');
fireEvent.change(languageInput, { target: { value: 'de-DE' } });
expect(await screen.findByText('1 unsaved change')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Discard' }));
expect(screen.queryByText('1 unsaved change')).not.toBeInTheDocument();
expect(screen.getByDisplayValue('en-US')).toBeInTheDocument();
});
it('saves only the changed group(s) and shows a confirmation', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
mockSettingsApi();
await openSettings();
const languageInput = screen.getByPlaceholderText('en-US');
fireEvent.change(languageInput, { target: { value: 'de-DE' } });
await screen.findByText('1 unsaved change');
fireEvent.click(screen.getByRole('button', { name: /Save changes/ }));
expect(await screen.findByText('Settings saved')).toBeInTheDocument();
expect(requestBodyFor('/api/v1/settings/ui')).toMatchObject({ language: 'de-DE' });
expect(window.fetch).not.toHaveBeenCalledWith('/api/v1/settings/ffmpeg', expect.objectContaining({ method: 'PUT' }));
vi.advanceTimersByTime(2000);
await waitFor(() => expect(screen.queryByText('Settings saved')).not.toBeInTheDocument());
});
it('shows a warning callout when scanner refresh interval is 0', async () => {
mockSettingsApi({ scannerSettings: defaultScannerSettings({ libraryRefreshInterval: 0 }) });
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Scanner/ }));
expect(await screen.findByText('Automatic scanning is disabled — libraries only update when scanned manually.')).toBeInTheDocument();
});
it('adds and deletes a custom resolution (delete goes through a confirm dialog)', async () => {
mockSettingsApi();
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Streaming/ }));
await screen.findByText('Custom resolutions');
fireEvent.change(screen.getByPlaceholderText('width'), { target: { value: '2560' } });
fireEvent.change(screen.getByPlaceholderText('height'), { target: { value: '1080' } });
fireEvent.click(screen.getByRole('button', { name: 'Add resolution' }));
expect(await screen.findByText('2560 × 1080')).toBeInTheDocument();
expect(requestBodyFor('/api/v1/settings/resolutions')).toMatchObject({ height: 1080, width: 2560 });
const deleteButtons = screen.getAllByRole('button', { name: /Delete \d+×\d+/ });
fireEvent.click(deleteButtons[deleteButtons.length - 1]);
expect(await screen.findByRole('dialog')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Delete' }));
await waitFor(() => expect(screen.queryByText('2560 × 1080')).not.toBeInTheDocument());
});
it('does not show a delete button on non-custom resolutions', async () => {
mockSettingsApi();
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Streaming/ }));
await screen.findByText('1920 × 1080');
expect(screen.queryByRole('button', { name: 'Delete 1920×1080' })).not.toBeInTheDocument();
});
it('renders FFmpeg profiles read-only with a link to the FFmpeg Profiles editor, and media sources', async () => {
mockSettingsApi({
ffmpegProfiles: [ffmpegProfile({ id: 1, name: '1080p H.264' }), ffmpegProfile({ id: 2, name: '720p H.264' })],
mediaSources: [mediaSource({ id: 30, kind: 'Local', name: 'Local' })]
});
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Streaming/ }));
expect((await screen.findAllByText('1080p H.264')).length).toBeGreaterThan(0);
expect(screen.getAllByText('720p H.264').length).toBeGreaterThan(0);
expect(screen.getByRole('button', { name: /Manage FFmpeg profiles/ })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /^System/ }));
expect(await screen.findByText('Local')).toBeInTheDocument();
});
it('shows a Classic UI link to the legacy Blazor app in the System pane (#147)', async () => {
mockSettingsApi();
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /^System/ }));
const link = await screen.findByRole('link', { name: /Open Classic UI/ });
expect(link).toHaveAttribute('href', '/system/health');
});
it('renders and stays editable when media sources (tier-2 reference data) fail to load', async () => {
mockSettingsApi({ mediaSourcesFailuresBeforeSuccess: 99 });
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /^System/ }));
expect(await screen.findByText("Couldn't load media sources")).toBeInTheDocument();
// The rest of the screen is fully functional: edit + save still work.
fireEvent.click(screen.getByRole('button', { name: /General/ }));
fireEvent.change(await screen.findByPlaceholderText('en-US'), { target: { value: 'nl-BE' } });
await screen.findByText('1 unsaved change');
fireEvent.click(screen.getByRole('button', { name: /Save changes/ }));
expect(await screen.findByText('Settings saved')).toBeInTheDocument();
expect(requestBodyFor('/api/v1/settings/ui')).toMatchObject({ language: 'nl-BE' });
});
it('shows the error state with a working retry when a settings group (tier-1) fails', async () => {
mockSettingsApi({ settingsGetFailuresBeforeSuccess: { '/api/v1/settings/scanner': 1 } });
render(<SettingsScreen />);
const alert = await screen.findByRole('alert');
expect(alert).toBeInTheDocument();
expect(screen.queryByText('Loading settings…')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
expect(
await screen.findByText('Interface preferences. These apply to the legacy web UI; ChicoryTV theming lives in the theme switcher.')
).toBeInTheDocument();
});
it('saves exactly the dirty groups when multiple groups are edited', async () => {
mockSettingsApi();
await openSettings();
fireEvent.change(screen.getByPlaceholderText('en-US'), { target: { value: 'de-DE' } });
fireEvent.click(screen.getByRole('button', { name: /Playout/ }));
await screen.findByText('Defaults for how far ahead playouts are built and how gaps are handled.');
fireEvent.change(screen.getByDisplayValue('2'), { target: { value: '5' } });
await screen.findByText('2 unsaved changes');
fireEvent.click(screen.getByRole('button', { name: /Save changes/ }));
expect(await screen.findByText('Settings saved')).toBeInTheDocument();
expect(requestBodyFor('/api/v1/settings/ui')).toMatchObject({ language: 'de-DE' });
expect(requestBodyFor('/api/v1/settings/playout')).toMatchObject({ daysToBuild: 5 });
const putCallCount = (path: string) =>
vi.mocked(window.fetch).mock.calls.filter(([input, init]) => input.toString() === path && init?.method === 'PUT')
.length;
expect(putCallCount('/api/v1/settings/ui')).toBe(1);
expect(putCallCount('/api/v1/settings/playout')).toBe(1);
expect(putCallCount('/api/v1/settings/ffmpeg')).toBe(0);
expect(putCallCount('/api/v1/settings/xmltv')).toBe(0);
expect(putCallCount('/api/v1/settings/scanner')).toBe(0);
expect(putCallCount('/api/v1/settings/logging')).toBe(0);
expect(putCallCount('/api/v1/settings/hdhr')).toBe(0);
});
it('on partial save failure, keeps only the failed group dirty and surfaces its error', async () => {
mockSettingsApi({
settingsMutationFailures: { '/api/v1/settings/playout': { detail: 'Playout save failed', status: 500 } }
});
await openSettings();
fireEvent.change(screen.getByPlaceholderText('en-US'), { target: { value: 'de-DE' } });
fireEvent.click(screen.getByRole('button', { name: /Playout/ }));
await screen.findByText('Defaults for how far ahead playouts are built and how gaps are handled.');
fireEvent.change(screen.getByDisplayValue('2'), { target: { value: '5' } });
await screen.findByText('2 unsaved changes');
fireEvent.click(screen.getByRole('button', { name: /Save changes/ }));
expect(await screen.findByText('1 unsaved change')).toBeInTheDocument();
expect(screen.getByText(/Playout save failed/)).toBeInTheDocument();
expect(screen.queryByText('Settings saved')).not.toBeInTheDocument();
// The succeeded (ui) group's edit stuck even though the draft stayed on the Playout pane.
fireEvent.click(screen.getByRole('button', { name: /General/ }));
expect(await screen.findByDisplayValue('de-DE')).toBeInTheDocument();
});
it('surfaces an inline error (no unhandled rejection) when adding a duplicate resolution fails', async () => {
mockSettingsApi({ resolutionCreateFailure: { detail: 'Resolution already exists', status: 422 } });
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Streaming/ }));
await screen.findByText('Custom resolutions');
fireEvent.change(screen.getByPlaceholderText('width'), { target: { value: '2560' } });
fireEvent.change(screen.getByPlaceholderText('height'), { target: { value: '1080' } });
fireEvent.click(screen.getByRole('button', { name: 'Add resolution' }));
expect(await screen.findByText('Resolution already exists')).toBeInTheDocument();
});
it('surfaces a resolution-delete failure inside the still-open confirm dialog', async () => {
mockSettingsApi({ resolutionDeleteFailure: { detail: 'Resolution is in use', status: 409 } });
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Streaming/ }));
await screen.findByText('1920 × 1080');
fireEvent.change(screen.getByPlaceholderText('width'), { target: { value: '2560' } });
fireEvent.change(screen.getByPlaceholderText('height'), { target: { value: '1080' } });
fireEvent.click(screen.getByRole('button', { name: 'Add resolution' }));
await screen.findByText('2560 × 1080');
const deleteButtons = screen.getAllByRole('button', { name: /Delete \d+×\d+/ });
fireEvent.click(deleteButtons[deleteButtons.length - 1]);
const dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }));
expect(await within(dialog).findByText('Resolution is in use')).toBeInTheDocument();
// The dialog stays open with the resolution still present - a clean draft would
// otherwise show nothing at all, since saveError only renders inside the save bar.
expect(screen.getByText('2560 × 1080')).toBeInTheDocument();
});
it('disables Save and shows an inline error when a numeric field is cleared', async () => {
mockSettingsApi();
await openSettings();
fireEvent.click(screen.getByRole('button', { name: /Playout/ }));
await screen.findByText('Defaults for how far ahead playouts are built and how gaps are handled.');
fireEvent.change(screen.getByDisplayValue('2'), { target: { value: '' } });
await screen.findByText('1 unsaved change');
expect(screen.getByText('Must be a whole number ≥ 0')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Save changes/ })).toBeDisabled();
});
it('treats a tunerCount of 0 as invalid (backend rejects 0)', async () => {
mockSettingsApi();
await openSettings();
fireEvent.click(screen.getByRole('button', { name: /^System/ }));
await screen.findByText('HDHomeRun emulation, connected media sources and server info.');
fireEvent.change(screen.getByDisplayValue('2'), { target: { value: '0' } });
await screen.findByText('1 unsaved change');
expect(screen.getByText('Must be a whole number ≥ 1')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Save changes/ })).toBeDisabled();
});
it('shows the raw wire value as an extra HLS Direct option when it is outside the known set', async () => {
mockSettingsApi({ ffmpegSettings: defaultFfmpegSettings({ hlsDirectOutputFormat: 'Hls' }) });
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Streaming/ }));
expect(await screen.findByDisplayValue('Hls')).toBeInTheDocument();
});
it('sends a non-null globalWatermarkId through in the ffmpeg save PUT body', async () => {
mockSettingsApi({ watermarks: [{ id: 5, name: 'Bug' }] });
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /Streaming/ }));
await screen.findByText('Global defaults');
const watermarkSelect = screen
.getAllByRole('combobox')
.find((select) => within(select).queryByText('Bug')) as HTMLSelectElement;
fireEvent.change(watermarkSelect, { target: { value: '5' } });
await screen.findByText('1 unsaved change');
fireEvent.click(screen.getByRole('button', { name: /Save changes/ }));
expect(await screen.findByText('Settings saved')).toBeInTheDocument();
expect(requestBodyFor('/api/v1/settings/ffmpeg')).toMatchObject({ globalWatermarkId: 5 });
});
it('renders the most recent last-scan time per media source', async () => {
mockSettingsApi({
mediaSources: [
mediaSource({
id: 30,
kind: 'Local',
libraries: [
library({ id: 31, lastScan: '2026-07-01T00:00:00Z' }),
library({ id: 32, lastScan: '2026-07-05T14:30:00Z' })
],
name: 'Local'
}),
mediaSource({ id: 40, kind: 'Jellyfin', libraries: [], name: 'Jellyfin Server' })
]
});
await openSettings();
fireEvent.click(await screen.findByRole('button', { name: /^System/ }));
expect(await screen.findByText('Local')).toBeInTheDocument();
expect(await screen.findByText('Jellyfin Server')).toBeInTheDocument();
expect(screen.getByText(/Last scan/)).toBeInTheDocument();
});
});
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
function library(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
id: 31,
itemCount: 0,
lastScan: null,
mediaKind: 'Movies',
name: 'Movies',
...overrides
};
}
function mediaSource(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
connectionAddress: null,
id: 30,
kind: 'Local',
libraries: [],
name: 'Local',
...overrides
};
}
function ffmpegProfile(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return { id: 100, name: '1080p H.264', ...overrides };
}
// Read the JSON body captured for a mutating request to `path`.
function requestBodyFor(path: string): Record<string, unknown> {
const call = vi
.mocked(window.fetch)
.mock.calls.find(([input, init]) => input.toString() === path && init?.body != null);
if (!call) {
throw new Error(`no request captured for ${path}`);
}
return JSON.parse(call[1]?.body as string) as Record<string, unknown>;
}
function defaultFfmpegSettings(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
defaultFFmpegProfileId: 1,
defaultMpegTsScript: '',
extractEmbeddedSubtitles: false,
fFmpegPath: '/usr/bin/ffmpeg',
fFprobePath: '/usr/bin/ffprobe',
globalFallbackFillerId: null,
globalWatermarkId: null,
hlsDirectOutputFormat: 'MpegTs',
hlsSegmenterIdleTimeout: 60,
initialSegmentCount: 1,
preferredAudioLanguageCode: 'eng',
probeForInterlacedFrames: true,
saveReports: false,
useEmbeddedSubtitles: true,
workAheadSegmenterLimit: 1,
...overrides
};
}
function defaultPlayoutSettings(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
daysToBuild: 2,
scriptedScheduleTimeoutSeconds: 30,
skipMissingItems: true,
...overrides
};
}
function defaultXmltvSettings(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
blockBehavior: 'SplitTimeEvenly',
daysToBuild: 2,
timeZone: 'Local',
...overrides
};
}
function defaultScannerSettings(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
libraryRefreshInterval: 6,
...overrides
};
}
function defaultLoggingSettings(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
defaultMinimumLogLevel: 'Information',
httpMinimumLogLevel: 'Warning',
scanningMinimumLogLevel: 'Information',
schedulingMinimumLogLevel: 'Information',
searchingMinimumLogLevel: 'Information',
streamingMinimumLogLevel: 'Information',
...overrides
};
}
function defaultUiSettings(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
isDarkMode: true,
language: 'en-US',
...overrides
};
}
function defaultHdhrSettings(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
tunerCount: 2,
uuid: '6f1b0a2e-93c4-4d1e-b7aa-0e5f2c9d8a41',
...overrides
};
}
function defaultResolutions(): Array<Record<string, unknown>> {
return [
{ height: 1080, id: 1, isCustom: false, name: '1920x1080', width: 1920 },
{ height: 720, id: 2, isCustom: false, name: '1280x720', width: 1280 }
];
}
function mockSettingsApi({
ffmpegProfiles = [],
ffmpegSettings = defaultFfmpegSettings(),
hdhrSettings = defaultHdhrSettings(),
loggingSettings = defaultLoggingSettings(),
mediaSources = [],
mediaSourcesFailuresBeforeSuccess = 0,
playoutSettings = defaultPlayoutSettings(),
resolutionCreateFailure = null,
resolutionDeleteFailure = null,
resolutions = defaultResolutions(),
scannerSettings = defaultScannerSettings(),
settingsGetFailuresBeforeSuccess = {},
settingsMutationFailures = {},
uiSettings = defaultUiSettings(),
watermarks = [],
xmltvSettings = defaultXmltvSettings()
}: {
ffmpegProfiles?: unknown[];
ffmpegSettings?: Record<string, unknown>;
hdhrSettings?: Record<string, unknown>;
loggingSettings?: Record<string, unknown>;
mediaSources?: unknown[];
mediaSourcesFailuresBeforeSuccess?: number;
playoutSettings?: Record<string, unknown>;
resolutionCreateFailure?: { detail?: string; status?: number; title?: string } | null;
resolutionDeleteFailure?: { detail?: string; status?: number; title?: string } | null;
resolutions?: Array<Record<string, unknown>>;
scannerSettings?: Record<string, unknown>;
settingsGetFailuresBeforeSuccess?: Record<string, number>;
settingsMutationFailures?: Record<string, { detail?: string; status?: number; title?: string }>;
uiSettings?: Record<string, unknown>;
watermarks?: unknown[];
xmltvSettings?: Record<string, unknown>;
} = {}) {
let currentResolutions = resolutions;
let remainingMediaSourcesFailures = mediaSourcesFailuresBeforeSuccess;
const remainingSettingsGetFailures = { ...settingsGetFailuresBeforeSuccess };
const currentSettings: Record<string, Record<string, unknown>> = {
'/api/v1/settings/ffmpeg': ffmpegSettings,
'/api/v1/settings/hdhr': hdhrSettings,
'/api/v1/settings/logging': loggingSettings,
'/api/v1/settings/playout': playoutSettings,
'/api/v1/settings/scanner': scannerSettings,
'/api/v1/settings/ui': uiSettings,
'/api/v1/settings/xmltv': xmltvSettings
};
vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const path = input.toString();
const method = init?.method ?? 'GET';
if (path in currentSettings) {
if (method === 'GET' && (remainingSettingsGetFailures[path] ?? 0) > 0) {
remainingSettingsGetFailures[path] -= 1;
return Promise.resolve(new Response(null, { status: 500 }));
}
if (method === 'PUT') {
const failure = settingsMutationFailures[path];
if (failure) {
return Promise.resolve(jsonResponse(failure, failure.status ?? 422));
}
currentSettings[path] = {
...currentSettings[path],
...JSON.parse(String(init?.body ?? '{}')) as Record<string, unknown>
};
}
return Promise.resolve(jsonResponse(currentSettings[path]));
}
if (path === '/api/v1/settings/resolutions') {
if (method === 'POST') {
if (resolutionCreateFailure) {
return Promise.resolve(
jsonResponse(resolutionCreateFailure, resolutionCreateFailure.status ?? 422)
);
}
const body = JSON.parse(String(init?.body ?? '{}')) as { height: number; width: number };
const created = {
height: body.height,
id: Math.max(0, ...currentResolutions.map((resolution) => Number(resolution.id))) + 1,
isCustom: true,
name: `${body.width}x${body.height}`,
width: body.width
};
currentResolutions = [...currentResolutions, created];
return Promise.resolve(jsonResponse(created, 201));
}
return Promise.resolve(jsonResponse(currentResolutions));
}
if (path.match(/^\/api\/v1\/settings\/resolutions\/\d+$/)) {
if (resolutionDeleteFailure) {
return Promise.resolve(
jsonResponse(resolutionDeleteFailure, resolutionDeleteFailure.status ?? 422)
);
}
const id = Number(path.split('/').at(-1));
currentResolutions = currentResolutions.filter((resolution) => Number(resolution.id) !== id);
return Promise.resolve(new Response(null, { status: 204 }));
}
if (path === '/api/v1/media-sources') {
if (remainingMediaSourcesFailures > 0) {
remainingMediaSourcesFailures -= 1;
return Promise.resolve(new Response(null, { status: 500 }));
}
return Promise.resolve(jsonResponse(mediaSources));
}
if (path === '/api/v1/ffmpeg/profiles') {
return Promise.resolve(jsonResponse(ffmpegProfiles));
}
if (path === '/api/v1/watermarks') {
return Promise.resolve(jsonResponse(watermarks));
}
if (path.startsWith('/api/v1/filler-presets')) {
return Promise.resolve(jsonResponse([]));
}
if (path === '/api/v1/version') {
return Promise.resolve(jsonResponse({ apiVersion: 3, appVersion: '26.4.0' }));
}
if (path === '/api/v1/health') {
return Promise.resolve(jsonResponse([]));
}
return Promise.resolve(jsonResponse(null, 404));
});
}