refactor(spa): extract LibrariesScreen from App.tsx (#202 slice S4)

Move the Libraries domain verbatim out of web/src/App.tsx into
web/src/screens/LibrariesScreen.tsx (zero-prop, self-sufficient), mirroring the
ChannelsScreen extraction (#244). Pure structural move: no API, route, CSS, or
visual change. App.tsx retains only the import + the <LibrariesScreen /> dispatch.

- 10 symbols moved (LibrariesLoadingState -> sourceLastScanLabel); App.tsx's
  formatDateTime is inlined into the moved screen so it has no import back into
  App.tsx (behavior-identical), matching the Channels precedent.
- Libraries behavior tests moved to a colocated LibrariesScreen.test.tsx with its
  own scoped fetch mock (renders <LibrariesScreen /> directly); App.test.tsx keeps
  one nav-smoke test for the route.
- Pruned now-dead App.tsx imports (Server, MonitorPlay, Music, FileImage, Folder,
  HardDrive icons; useLibrariesScreenQuery, LibraryScanStatus/MediaSource/
  MediaSourceLibrary types) and the now-dead runPollTick test helper (its doc
  comment named it Libraries-specific).
- Disabled "Add Source"/gear/"Scan All" affordances are unchanged (wired in later
  S5/S6 slices, not here).

Verified: web vitest 584 passed, eslint clean, tsc/vite build clean, check:api no
drift.

refs #202
This commit is contained in:
2026-07-11 15:29:15 +02:00
parent d93bca653a
commit 99fab8e0bb
4 changed files with 686 additions and 749 deletions
+7 -479
View File
@@ -1,4 +1,4 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } 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 { App } from './App';
import { Button, Checkbox, Input, ProgressBar, Switch, Tabs, Toast, Tooltip } from './components';
@@ -590,44 +590,15 @@ describe('ChicoryTV SPA scaffold', () => {
expect(window.fetch).toHaveBeenCalledWith('/api/channels/state', expect.any(Object));
});
it('renders the Libraries screen from live media source and scan status APIs', async () => {
it('renders the extracted Libraries screen from live media source and scan status APIs (#202)', async () => {
// Thin route/composition smoke test: the full Libraries behavioral suite lives colocated in
// web/src/screens/LibrariesScreen.test.tsx. This only asserts the nav wires the extracted screen
// into the shell and it mounts + hits its own endpoints.
mockDashboardApi({
libraryScanStatuses: [{ libraryId: 31, percent: 0.625 }],
libraryScanStatuses: [{ libraryId: 31, percent: 0.5 }],
mediaSources: [
mediaSource({
connectionAddress: null,
id: 30,
kind: 'Local',
libraries: [
library({ id: 31, itemCount: 1250, lastScan: '2026-07-05T14:30:00Z', mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 14, lastScan: null, mediaKind: 'OtherVideos', name: 'Station IDs' })
],
name: 'Local'
}),
mediaSource({
connectionAddress: 'https://plex.example.test',
id: 40,
kind: 'Plex',
libraries: [
library({ id: 41, itemCount: 80, lastScan: '2026-07-04T08:00:00Z', mediaKind: 'Shows', name: 'TV Shows' })
],
name: 'Plex Server'
}),
mediaSource({
connectionAddress: 'https://jellyfin.example.test',
id: 50,
kind: 'Jellyfin',
libraries: [],
name: 'Jellyfin Home'
}),
mediaSource({
connectionAddress: 'https://emby.example.test',
id: 60,
kind: 'Emby',
libraries: [
library({ id: 61, itemCount: 22, lastScan: '2026-07-01T00:00:00Z', mediaKind: 'MusicVideos', name: 'Music Videos' })
],
name: 'Emby Archive'
libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })]
})
]
});
@@ -637,436 +608,11 @@ describe('ChicoryTV SPA scaffold', () => {
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument();
expect(screen.getByText('4 sources')).toBeInTheDocument();
expect(screen.getByText('1,366 items')).toBeInTheDocument();
expect(screen.getByRole('region', { name: 'Local media source' })).toBeInTheDocument();
expect(screen.getByText('Local connection')).toBeInTheDocument();
expect(screen.getByRole('region', { name: 'Plex Server media source' })).toBeInTheDocument();
expect(screen.getByText('https://plex.example.test')).toBeInTheDocument();
expect(screen.getAllByText('Movies').length).toBeGreaterThan(0);
expect(screen.getByText('Station IDs')).toBeInTheDocument();
expect(screen.getByText('TV Shows')).toBeInTheDocument();
expect(screen.getAllByText('Music Videos').length).toBeGreaterThan(0);
expect(screen.getByText('Other Videos')).toBeInTheDocument();
expect(screen.getAllByText('Music Videos').length).toBeGreaterThan(0);
// "Scanning" now appears twice: once as the source-header status label (paired with
// the StatusDot, not color alone) and once as the per-library scanning Badge.
expect(screen.getAllByText('Scanning').length).toBeGreaterThan(0);
// Wire contract: percent is a 0-1 fraction (0.625) - the UI must render it as 63%, not 0.625%.
expect(screen.getByText('63%')).toBeInTheDocument();
expect(screen.getAllByText('Synced').length).toBeGreaterThan(0);
expect(screen.getAllByText('Never scanned').length).toBeGreaterThan(0);
expect(screen.getByRole('button', { name: 'Add Source' })).toBeDisabled();
expect(screen.getByText('Adding sources is deferred to the existing server setup screens.')).toBeInTheDocument();
expect(window.fetch).toHaveBeenCalledWith('/api/media-sources', expect.any(Object));
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/scan-status', expect.any(Object));
});
it('converts 0 and 1 fractional scan-status percents to 0% and 100%', async () => {
mockDashboardApi({
libraryScanStatuses: [
{ libraryId: 31, percent: 0 },
{ libraryId: 32, percent: 1 }
],
mediaSources: [
mediaSource({
libraries: [
library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' })
]
})
]
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect(await screen.findByText('0%')).toBeInTheDocument();
expect(screen.getByText('100%')).toBeInTheDocument();
});
it('fetches Libraries data as a route delta and does not poll sources', async () => {
const intervalHandlers: Array<() => void> = [];
vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => {
if (typeof handler === 'function' && (timeout ?? 0) >= 10000) {
intervalHandlers.push(handler as () => void);
}
return intervalHandlers.length;
});
vi.spyOn(window, 'clearInterval').mockImplementation(() => undefined);
mockDashboardApi({
libraryScanStatuses: [{ libraryId: 31, percent: 0.1 }],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<App />);
await waitFor(() => {
expect(fetchCount('/api/media-sources')).toBeGreaterThan(0);
});
const sourceFetchesBeforeNavigation = fetchCount('/api/media-sources');
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument();
expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforeNavigation + 1);
expect(fetchCount('/api/libraries/scan-status')).toBe(1);
const sourceFetchesBeforePoll = fetchCount('/api/media-sources');
await runPollTick(intervalHandlers);
expect(fetchCount('/api/libraries/scan-status')).toBeGreaterThan(1);
expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforePoll);
});
it('stops Libraries scan polling and refreshes sources once when scans complete', async () => {
const intervalHandlers: Array<() => void> = [];
let clearCount = 0;
vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => {
if (typeof handler === 'function' && (timeout ?? 0) >= 10000) {
intervalHandlers.push(handler as () => void);
}
return intervalHandlers.length;
});
vi.spyOn(window, 'clearInterval').mockImplementation(() => {
clearCount += 1;
});
mockDashboardApi({
libraryScanStatusSequence: [
[{ libraryId: 31, percent: 0.75 }],
[]
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect(await screen.findByText('75%')).toBeInTheDocument();
const sourceFetchesBeforeCompletion = fetchCount('/api/media-sources');
await runPollTick(intervalHandlers);
expect(screen.queryByText('75%')).not.toBeInTheDocument();
expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforeCompletion + 1);
expect(clearCount).toBeGreaterThan(0);
});
it('triggers a library scan, disables that library while in flight, and starts polling scan status', async () => {
const scanStatusesAfterMutation = [{ libraryId: 31, percent: 0.05 }];
mockDashboardApi({
libraryScanStatuses: [],
libraryScanStatusesAfterMutation: scanStatusesAfterMutation,
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
await waitFor(() => {
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
expect(await screen.findByText('5%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
});
it('keeps the scan button disabled and polling armed through the queue-to-start race, then clears once the scan finishes', async () => {
const intervalHandlers: Array<() => void> = [];
let clearCount = 0;
vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => {
if (typeof handler === 'function' && (timeout ?? 0) >= 10000) {
intervalHandlers.push(handler as () => void);
}
return intervalHandlers.length;
});
vi.spyOn(window, 'clearInterval').mockImplementation(() => {
clearCount += 1;
});
mockDashboardApi({
libraryScanStatusSequence: [
[], // initial screen load
[], // trigger's immediate post-POST fetch: scanner hasn't started yet
[{ libraryId: 31, percent: 0.3 }], // first poll tick: now active
[] // second poll tick: scan finished
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
await waitFor(() => {
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
// The immediate post-trigger status fetch returned [] - without pending-id tracking
// the button would re-enable here and polling would never start. Both must hold.
await waitFor(() => {
expect(fetchCount('/api/libraries/scan-status')).toBe(2);
});
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
expect(intervalHandlers.length).toBeGreaterThan(0);
const sourceFetchesBeforeCompletion = fetchCount('/api/media-sources');
await runPollTick(intervalHandlers);
expect(screen.getByText('30%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
await runPollTick(intervalHandlers);
expect(screen.queryByText('30%')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled();
expect(fetchCount('/api/media-sources')).toBe(sourceFetchesBeforeCompletion + 1);
expect(clearCount).toBeGreaterThan(0);
});
it('reconciles a 409 "already scanning" against scan-status without an error toast (#232)', async () => {
// POST /scan now returns 409 when a scan is already in progress. That is benign - the SPA
// must NOT show an error; it reconciles against scan-status (which reports the active scan)
// and keeps the button disabled while that scan runs.
mockDashboardApi({
libraryScanStatusSequence: [
[], // initial screen load: nothing active yet
[{ libraryId: 31, percent: 0.3 }] // post-409 reconcile fetch: the in-progress scan
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { status: 409 }
}
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
await waitFor(() => {
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
// The reconcile fetch surfaces the already-running scan; the button stays disabled...
expect(await screen.findByText('30%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
// ...and no error toast is shown for the benign conflict.
expect(screen.queryByText(/Request failed/)).not.toBeInTheDocument();
expect(screen.queryByText(/Unable to scan/)).not.toBeInTheDocument();
});
it('surfaces a 422 "sync disabled" scan rejection and leaves the button enabled (#232)', async () => {
// POST /scan now returns 422 when item sync is disabled for the library. Nothing was queued,
// so the button must not be stuck disabled and the error must be surfaced.
mockDashboardApi({
libraryScanStatuses: [],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { detail: 'Item sync is disabled for library 31.', status: 422 }
}
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('Item sync is disabled for library 31.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled();
});
it('re-enables the scan button after the grace window if a 202 scan never appears active (#232)', async () => {
// A 202 genuinely queues a (forced) scan, but a short/empty library can finish before the next
// 10s poll ever observes it in scan-status - or the scanner may never register it. The optimistic
// "pending" flag must not wedge the button disabled forever: it expires after PENDING_GRACE_TICKS
// polls that never see the library active, then the button re-enables.
const intervalHandlers: Array<() => void> = [];
vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => {
if (typeof handler === 'function' && (timeout ?? 0) >= 10000) {
intervalHandlers.push(handler as () => void);
}
return intervalHandlers.length;
});
vi.spyOn(window, 'clearInterval').mockImplementation(() => 0);
mockDashboardApi({
// initial load, immediate post-POST fetch, then every poll: the scan never shows up
libraryScanStatusSequence: [[], [], [], [], []],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
await waitFor(() => {
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
// Optimistically disabled; the immediate post-POST fetch ([]) burned one grace tick but keeps it pending.
await waitFor(() => {
expect(fetchCount('/api/libraries/scan-status')).toBe(2);
});
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
// Grace is PENDING_GRACE_TICKS (3): the immediate fetch used one, two more unseen polls expire it.
await runPollTick(intervalHandlers);
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
await runPollTick(intervalHandlers);
expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled();
});
it('keeps the scan button disabled on a 409 even when scan-status has not yet caught up (#232)', async () => {
// 409 means the library is already scanning (a lock is held). The SPA must NOT re-enable the
// button just because scan-status has not yet listed the in-progress scan (the queue->active
// lag) - otherwise the user can fire repeated 409s. The pending flag is retained (button stays
// disabled, no error toast) and is reconciled/expired by the normal polling path.
mockDashboardApi({
libraryScanStatusSequence: [
[], // initial screen load
[] // post-409 reconcile fetch: the in-progress scan is not visible in scan-status yet
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { status: 409 }
}
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
await waitFor(() => {
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
// Reconcile fetch happened and returned nothing active, yet the button stays disabled...
await waitFor(() => {
expect(fetchCount('/api/libraries/scan-status')).toBe(2);
});
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
// ...and no error toast is shown for the benign conflict.
expect(screen.queryByText(/Request failed/)).not.toBeInTheDocument();
expect(screen.queryByText(/Unable to scan/)).not.toBeInTheDocument();
});
it('shows Libraries API errors and retries', async () => {
// The backend has no exception middleware, so a real failure is a bare 500 with no
// ProblemDetails body - do not invent one here (mirrors the scan-trigger-404 test below).
mockDashboardApi({
mediaSourcesFailuresBeforeSuccess: 2,
mediaSources: [mediaSource({ libraries: [] })]
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect(await screen.findByText('Request failed with status 500')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument();
});
it('shows scan trigger failures without inventing application ProblemDetails', async () => {
mockDashboardApi({
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': {
status: 404
}
}
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('Request failed with status 404')).toBeInTheDocument();
});
it('scans every library in a source when its Scan-all button is clicked', async () => {
mockDashboardApi({
mediaSources: [
mediaSource({
id: 30,
libraries: [
library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' })
],
name: 'Local'
})
]
});
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect(await screen.findByText('TV Shows')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Scan all libraries in Local' }));
await waitFor(() => {
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
await waitFor(() => {
expect(window.fetch).toHaveBeenCalledWith('/api/libraries/32/scan', expect.objectContaining({ method: 'POST' }));
});
expect(fetchCount('/api/libraries/31/scan')).toBe(1);
expect(fetchCount('/api/libraries/32/scan')).toBe(1);
});
it('shows an empty Libraries state when no media sources exist', async () => {
mockDashboardApi({ mediaSources: [] });
render(<App />);
fireEvent.click(screen.getByRole('link', { name: 'Libraries' }));
expect(await screen.findByText('No media sources returned')).toBeInTheDocument();
});
it('toggles Show filler to refetch playout items with showFiller=true and badge filler rows', async () => {
mockDashboardApi({
playoutItems: [
@@ -3810,24 +3356,6 @@ function mockDashboardApi({
});
}
// Deterministically fires one captured poll tick for the mocked-setInterval polling tests.
//
// The Libraries poll interval is registered in a passive useEffect that only runs after
// an out-of-act state commit (the async fetch that flips hasActiveScans), so `findBy*`
// queries - which resolve on the DOM mutation, via MutationObserver - can win the race
// against React's effect flush and observe an empty handler list (the #157 flake).
// The leading empty act() flushes those pending effects, the length assertion turns a
// still-missing registration into a clear failure instead of a silent no-op forEach,
// and the act() around the handlers applies the fetch microtasks + state updates before
// the caller asserts, so no assertion depends on wall-clock scheduling.
async function runPollTick(intervalHandlers: Array<() => void>): Promise<void> {
await act(async () => {});
expect(intervalHandlers.length).toBeGreaterThan(0);
await act(async () => {
intervalHandlers.forEach((handler) => handler());
});
}
function fetchCount(path: string): number {
return vi.mocked(window.fetch).mock.calls.filter(([input]) => input.toString() === path).length;
}
+1 -270
View File
@@ -23,11 +23,8 @@ import {
ClipboardCopy,
Crosshair,
Film,
FileImage,
Eraser,
Folder,
FolderTree,
HardDrive,
Info,
Layers,
LayoutDashboard,
@@ -37,8 +34,6 @@ import {
ListChecks,
ListMusic,
ListVideo,
MonitorPlay,
Music,
Plus,
Pencil,
Play,
@@ -47,7 +42,6 @@ import {
Repeat,
ScrollText,
Search,
Server,
Settings,
SlidersHorizontal,
Sparkles,
@@ -69,6 +63,7 @@ import { MultiCollectionsScreen } from './screens/MultiCollectionsScreen';
import { PlaylistsScreen } from './screens/PlaylistsScreen';
import { RerunCollectionsScreen } from './screens/RerunCollectionsScreen';
import { ChannelsScreen } from './screens/ChannelsScreen';
import { LibrariesScreen } from './screens/LibrariesScreen';
import { SchedulesScreen } from './screens/SchedulesScreen';
import { canLeaveCurrentScreen } from './navigationGuard';
import {
@@ -135,7 +130,6 @@ import {
defaultGuideWindowStart,
GUIDE_WINDOW_MS,
useGuideScreenQuery,
useLibrariesScreenQuery,
type ChannelState,
type ChannelGuideChannel,
type ChannelGuideProgramme,
@@ -144,9 +138,6 @@ import {
type DecoListItem,
type DashboardChannelState,
type DashboardHealthQueryState,
type LibraryScanStatus,
type MediaSource,
type MediaSourceLibrary,
type PlayoutDetail,
type PlayoutScheduleKind,
type ProgramSchedule,
@@ -1450,266 +1441,6 @@ function programmeMatchesNowPlaying(programme: ClippedProgramme, nowPlaying: Cha
programme.stop.getTime() === nowPlayingFinish.getTime();
}
function LibrariesLoadingState() {
return (
<Card title={<h2>Loading libraries</h2>} subtitle="Fetching media sources and active scan status.">
<div className="ctv-dashboard-state">
<Spinner tone="muted" />
<span>Loading libraries</span>
</div>
</Card>
);
}
function LibrariesErrorState({ error, refresh }: { error: string; refresh: () => void }) {
return (
<Card
title={<h2>Libraries unavailable</h2>}
subtitle="The API returned an error while loading media sources."
actions={<Button onClick={refresh} startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">Retry</Button>}
>
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
</Card>
);
}
function LibrariesEmptyState() {
return (
<Card title={<h2>No media sources</h2>} subtitle="Configure a source in the server setup screens before monitoring scans here.">
<div className="ctv-schedule-empty">No media sources returned</div>
</Card>
);
}
function LibrariesScreen() {
const query = useLibrariesScreenQuery();
if (query.status === 'loading') {
return <LibrariesLoadingState />;
}
if (query.status === 'error') {
return <LibrariesErrorState error={query.error} refresh={query.refresh} />;
}
if (query.data.sources.length === 0) {
return <LibrariesEmptyState />;
}
const totalItems = query.data.sources.reduce(
(sum, source) => sum + source.libraries.reduce((librarySum, library) => librarySum + library.itemCount, 0),
0
);
const scanStatusesByLibraryId = new Map(query.data.scanStatuses.map((status) => [status.libraryId, status]));
return (
<div className="ctv-libraries-screen">
<section className="ctv-libraries-header">
<div>
<span className="ctv-kicker">Sources</span>
<h2>Media Libraries</h2>
<p>Monitor connected media sources and trigger per-library scans.</p>
</div>
<div className="ctv-libraries-header-actions">
<Button disabled startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">Scan All</Button>
<Button disabled startIcon={<Plus aria-hidden="true" size={15} />}>Add Source</Button>
</div>
</section>
{query.error && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{query.error}</span>
</div>
)}
<div className="ctv-libraries-summary">
<span>{query.data.sources.length} source{query.data.sources.length === 1 ? '' : 's'}</span>
<span>{totalItems.toLocaleString()} items</span>
<span><StatusDot status={query.data.scanStatuses.length > 0 ? 'live' : 'ok'} size={7} />{query.data.scanStatuses.length} active scan{query.data.scanStatuses.length === 1 ? '' : 's'}</span>
</div>
<div className="ctv-libraries-grid">
{query.data.sources.map((source) => (
<MediaSourceCard
key={source.id}
onScanLibrary={query.scanLibrary}
scanStatusesByLibraryId={scanStatusesByLibraryId}
scanningLibraryIds={query.scanningLibraryIds}
source={source}
/>
))}
<section className="ctv-library-add-card" aria-label="Add media source">
<span className="ctv-library-kind-icon ctv-library-kind-local"><Plus aria-hidden="true" size={18} /></span>
<div>
<h3>Connect a media source</h3>
<p>Adding sources is deferred to the existing server setup screens.</p>
</div>
<div className="ctv-library-add-options" aria-hidden="true">
<span><HardDrive size={13} />Local folder</span>
<span><Server size={13} />Plex</span>
<span><Server size={13} />Jellyfin</span>
<span><Server size={13} />Emby</span>
</div>
</section>
</div>
</div>
);
}
function MediaSourceCard({
onScanLibrary,
scanStatusesByLibraryId,
scanningLibraryIds,
source
}: {
onScanLibrary: (libraryId: number) => Promise<void>;
scanStatusesByLibraryId: Map<number, LibraryScanStatus>;
scanningLibraryIds: Set<number>;
source: MediaSource;
}) {
const totalItems = source.libraries.reduce((sum, library) => sum + library.itemCount, 0);
const scanning = source.libraries.some((library) => scanningLibraryIds.has(library.id));
const scanSource = () => {
source.libraries.forEach((library) => {
void onScanLibrary(library.id);
});
};
return (
<section className="ctv-library-source-card" aria-label={`${source.name} media source`}>
<div className="ctv-library-source-head">
<span className={`ctv-library-kind-icon ctv-library-kind-${source.kind.toLowerCase()}`}>{sourceKindIcon(source.kind)}</span>
<div>
<div className="ctv-library-source-title">
<h3>{source.name}</h3>
<StatusDot status={scanning ? 'live' : 'ok'} label={scanning ? 'Scanning' : 'Synced'} size={7} />
</div>
<span>{source.connectionAddress ?? 'Local connection'}</span>
</div>
<div className="ctv-library-source-actions">
<IconButton disabled={scanning} onClick={scanSource} size="sm" title={`Scan all libraries in ${source.name}`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
<IconButton disabled size="sm" title={`Settings unavailable for ${source.name}`}>
<Settings aria-hidden="true" size={15} />
</IconButton>
</div>
</div>
<div className="ctv-library-list" role="list" aria-label={`${source.name} libraries`}>
{source.libraries.length === 0 ? (
<div className="ctv-library-empty">No synced libraries returned</div>
) : source.libraries.map((library) => (
<LibraryRow
key={library.id}
library={library}
onScanLibrary={onScanLibrary}
scanStatus={scanStatusesByLibraryId.get(library.id) ?? null}
scanning={scanningLibraryIds.has(library.id)}
/>
))}
</div>
<div className="ctv-library-source-foot">
<span><Clock aria-hidden="true" size={13} />{scanning ? 'Scanning now' : sourceLastScanLabel(source)}</span>
<span><code>{totalItems.toLocaleString()}</code> items · {source.libraries.length} librar{source.libraries.length === 1 ? 'y' : 'ies'}</span>
</div>
</section>
);
}
function LibraryRow({
library,
onScanLibrary,
scanStatus,
scanning
}: {
library: MediaSourceLibrary;
onScanLibrary: (libraryId: number) => Promise<void>;
scanStatus: LibraryScanStatus | null;
scanning: boolean;
}) {
const scanActive = scanStatus !== null;
const disabled = scanning || scanActive;
return (
<div className="ctv-library-row" role="listitem">
<span className="ctv-library-media-icon">{libraryMediaIcon(library.mediaKind)}</span>
<div className="ctv-library-row-main">
<strong>{library.name}</strong>
<span><span>{formatLibraryMediaKind(library.mediaKind)}</span> · <code>{library.itemCount.toLocaleString()}</code> items</span>
<small>{library.lastScan ? `Last scan ${formatDateTime(library.lastScan)}` : 'Never scanned'}</small>
</div>
<div className="ctv-library-row-status">
{scanStatus ? (
<div className="ctv-library-progress">
<ProgressBar value={scanStatus.percent} showLabel />
<Badge tone="accent" dot>Scanning</Badge>
</div>
) : (
<Badge tone="ok" dot>Synced</Badge>
)}
<IconButton disabled={disabled} onClick={() => void onScanLibrary(library.id)} size="sm" title={`Scan ${library.name}`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
</div>
</div>
);
}
function sourceKindIcon(kind: string): ReactNode {
return kind === 'Local'
? <HardDrive aria-hidden="true" size={18} />
: <Server aria-hidden="true" size={18} />;
}
function libraryMediaIcon(kind: string): ReactNode {
switch (kind) {
case 'Movies':
return <Clapperboard aria-hidden="true" size={14} />;
case 'Shows':
return <MonitorPlay aria-hidden="true" size={14} />;
case 'MusicVideos':
case 'Songs':
return <Music aria-hidden="true" size={14} />;
case 'Images':
return <FileImage aria-hidden="true" size={14} />;
case 'RemoteStreams':
return <Radio aria-hidden="true" size={14} />;
case 'OtherVideos':
return <Film aria-hidden="true" size={14} />;
default:
return <Folder aria-hidden="true" size={14} />;
}
}
function formatLibraryMediaKind(kind: string): string {
switch (kind) {
case 'MusicVideos':
return 'Music Videos';
case 'OtherVideos':
return 'Other Videos';
case 'RemoteStreams':
return 'Remote Streams';
default:
return kind;
}
}
function sourceLastScanLabel(source: MediaSource): string {
const scans = source.libraries
.map((library) => library.lastScan)
.filter((scan): scan is string => Boolean(scan))
.sort();
return scans.length > 0 ? `Last scan ${formatDateTime(scans[scans.length - 1])}` : 'Never scanned';
}
function PlayoutsLoadingState() {
return (
<Card title={<h2>Loading playouts</h2>} subtitle="Fetching playouts, channel state, and upcoming items.">
+369
View File
@@ -0,0 +1,369 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LibrariesScreen } from './LibrariesScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
// MediaSourceLibraryResponseModel row.
function library(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
id: 31,
itemCount: 0,
lastScan: null,
mediaKind: 'Movies',
name: 'Movies',
...overrides
};
}
// MediaSourceResponseModel row.
function mediaSource(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
connectionAddress: null,
id: 30,
kind: 'Local',
libraries: [],
name: 'Local',
...overrides
};
}
interface MockOptions {
mediaSources?: unknown[];
mediaSourcesFailuresBeforeSuccess?: number;
libraryScanStatuses?: unknown[];
libraryScanStatusSequence?: unknown[][] | null;
mutationFailures?: Record<string, { detail?: string; status?: number; title?: string }>;
}
interface MockHandle {
fetchSpy: ReturnType<typeof vi.spyOn>;
requests: Array<{ url: string; method: string; body: unknown }>;
}
function mockApi(options: MockOptions = {}): MockHandle {
const requests: Array<{ url: string; method: string; body: unknown }> = [];
const mediaSources = options.mediaSources ?? [mediaSource()];
const mutationFailures = options.mutationFailures ?? {};
let remainingMediaSourcesFailures = options.mediaSourcesFailuresBeforeSuccess ?? 0;
let scanStatusSequenceIndex = 0;
const fetchSpy = vi.spyOn(window, 'fetch').mockImplementation((input: RequestInfo | URL, init?: RequestInit) => {
const url = input.toString();
const method = (init?.method ?? 'GET').toUpperCase();
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
requests.push({ url, method, body });
if (url === '/api/media-sources' && method === 'GET') {
if (remainingMediaSourcesFailures > 0) {
remainingMediaSourcesFailures -= 1;
return Promise.resolve(new Response(null, { status: 500 }));
}
return Promise.resolve(jsonResponse(mediaSources));
}
if (url === '/api/libraries/scan-status' && method === 'GET') {
if (options.libraryScanStatusSequence) {
const sequenceValue =
options.libraryScanStatusSequence[Math.min(scanStatusSequenceIndex, options.libraryScanStatusSequence.length - 1)];
scanStatusSequenceIndex += 1;
return Promise.resolve(jsonResponse(sequenceValue));
}
return Promise.resolve(jsonResponse(options.libraryScanStatuses ?? []));
}
if (/^\/api\/libraries\/\d+\/scan$/.test(url) && method === 'POST') {
if (url in mutationFailures) {
return Promise.resolve(jsonResponse(mutationFailures[url], mutationFailures[url].status ?? 422));
}
return Promise.resolve(new Response(null, { status: 202 }));
}
return Promise.resolve(jsonResponse(null, 404));
});
return { fetchSpy, requests };
}
function fetchCount(handle: MockHandle, path: string): number {
return handle.requests.filter((r) => r.url === path).length;
}
async function runPollTick(intervalHandlers: Array<() => void>): Promise<void> {
await act(async () => {
intervalHandlers.forEach((handler) => handler());
});
}
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
vi.restoreAllMocks();
});
describe('LibrariesScreen', () => {
it('renders sources and libraries from live media source and scan status APIs', async () => {
const handle = mockApi({
libraryScanStatuses: [{ libraryId: 31, percent: 0.625 }],
mediaSources: [
mediaSource({
connectionAddress: null,
id: 30,
kind: 'Local',
libraries: [
library({ id: 31, itemCount: 1250, lastScan: '2026-07-05T14:30:00Z', mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 14, lastScan: null, mediaKind: 'OtherVideos', name: 'Station IDs' })
],
name: 'Local'
}),
mediaSource({
connectionAddress: 'https://plex.example.test',
id: 40,
kind: 'Plex',
libraries: [
library({ id: 41, itemCount: 80, lastScan: '2026-07-04T08:00:00Z', mediaKind: 'Shows', name: 'TV Shows' })
],
name: 'Plex Server'
}),
mediaSource({
connectionAddress: 'https://jellyfin.example.test',
id: 50,
kind: 'Jellyfin',
libraries: [],
name: 'Jellyfin Home'
}),
mediaSource({
connectionAddress: 'https://emby.example.test',
id: 60,
kind: 'Emby',
libraries: [
library({ id: 61, itemCount: 22, lastScan: '2026-07-01T00:00:00Z', mediaKind: 'MusicVideos', name: 'Music Videos' })
],
name: 'Emby Archive'
})
]
});
render(<LibrariesScreen />);
expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument();
expect(screen.getByText('4 sources')).toBeInTheDocument();
expect(screen.getByText('1,366 items')).toBeInTheDocument();
expect(screen.getByRole('region', { name: 'Local media source' })).toBeInTheDocument();
expect(screen.getByText('Local connection')).toBeInTheDocument();
expect(screen.getByRole('region', { name: 'Plex Server media source' })).toBeInTheDocument();
expect(screen.getByText('https://plex.example.test')).toBeInTheDocument();
expect(screen.getAllByText('Movies').length).toBeGreaterThan(0);
expect(screen.getByText('Station IDs')).toBeInTheDocument();
expect(screen.getByText('TV Shows')).toBeInTheDocument();
expect(screen.getAllByText('Music Videos').length).toBeGreaterThan(0);
expect(screen.getByText('Other Videos')).toBeInTheDocument();
// "Scanning" appears twice: once as the source-header status label (paired with the
// StatusDot, not color alone) and once as the per-library scanning Badge.
expect(screen.getAllByText('Scanning').length).toBeGreaterThan(0);
// Wire contract: percent is a 0-1 fraction (0.625) - the UI must render it as 63%, not 0.625%.
expect(screen.getByText('63%')).toBeInTheDocument();
expect(screen.getAllByText('Synced').length).toBeGreaterThan(0);
expect(screen.getAllByText('Never scanned').length).toBeGreaterThan(0);
expect(screen.getByRole('button', { name: 'Add Source' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Scan All' })).toBeDisabled();
expect(screen.getByText('Adding sources is deferred to the existing server setup screens.')).toBeInTheDocument();
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/media-sources', expect.any(Object));
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/scan-status', expect.any(Object));
});
it('converts 0 and 1 fractional scan-status percents to 0% and 100%', async () => {
mockApi({
libraryScanStatuses: [
{ libraryId: 31, percent: 0 },
{ libraryId: 32, percent: 1 }
],
mediaSources: [
mediaSource({
libraries: [
library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' })
]
})
]
});
render(<LibrariesScreen />);
expect(await screen.findByText('0%')).toBeInTheDocument();
expect(screen.getByText('100%')).toBeInTheDocument();
});
it('triggers a library scan via POST /api/libraries/{id}/scan, disables the button while in flight, and polls scan status', async () => {
const handle = mockApi({
libraryScanStatuses: [],
libraryScanStatusSequence: [[], [{ libraryId: 31, percent: 0.05 }]],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
expect(await screen.findByText('5%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
});
it('stops scan polling and refreshes sources once when scans complete', async () => {
const intervalHandlers: Array<() => void> = [];
vi.spyOn(window, 'setInterval').mockImplementation((handler: TimerHandler, timeout?: number) => {
if (typeof handler === 'function' && (timeout ?? 0) >= 10000) {
intervalHandlers.push(handler as () => void);
}
return intervalHandlers.length;
});
vi.spyOn(window, 'clearInterval').mockImplementation(() => undefined);
const handle = mockApi({
libraryScanStatusSequence: [
[{ libraryId: 31, percent: 0.75 }],
[]
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
]
});
render(<LibrariesScreen />);
expect(await screen.findByText('75%')).toBeInTheDocument();
const sourceFetchesBeforeCompletion = fetchCount(handle, '/api/media-sources');
await runPollTick(intervalHandlers);
expect(screen.queryByText('75%')).not.toBeInTheDocument();
expect(fetchCount(handle, '/api/media-sources')).toBe(sourceFetchesBeforeCompletion + 1);
});
it('reconciles a 409 "already scanning" against scan-status without an error toast (#232)', async () => {
mockApi({
libraryScanStatusSequence: [
[], // initial screen load: nothing active yet
[{ libraryId: 31, percent: 0.3 }] // post-409 reconcile fetch: the in-progress scan
],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { status: 409 }
}
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('30%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).toBeDisabled();
expect(screen.queryByText(/Request failed/)).not.toBeInTheDocument();
expect(screen.queryByText(/Unable to scan/)).not.toBeInTheDocument();
});
it('surfaces a 422 "sync disabled" scan rejection and leaves the button enabled (#232)', async () => {
mockApi({
libraryScanStatuses: [],
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { detail: 'Item sync is disabled for library 31.', status: 422 }
}
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('Item sync is disabled for library 31.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Scan Movies' })).not.toBeDisabled();
});
it('shows Libraries API errors and retries', async () => {
// 1 failure (the initial mount's load) then success on the Retry-triggered reload - unlike
// the App-level nav-smoke test, this standalone render has no earlier Dashboard fetch
// consuming a failure first.
mockApi({
mediaSourcesFailuresBeforeSuccess: 1,
mediaSources: [mediaSource({ libraries: [] })]
});
render(<LibrariesScreen />);
expect(await screen.findByText('Request failed with status 500')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
expect(await screen.findByRole('heading', { name: 'Media Libraries' })).toBeInTheDocument();
});
it('shows scan trigger failures without inventing application ProblemDetails', async () => {
mockApi({
mediaSources: [
mediaSource({ libraries: [library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' })] })
],
mutationFailures: {
'/api/libraries/31/scan': { status: 404 }
}
});
render(<LibrariesScreen />);
expect((await screen.findAllByText('Movies')).length).toBeGreaterThan(0);
fireEvent.click(screen.getByRole('button', { name: 'Scan Movies' }));
expect(await screen.findByText('Request failed with status 404')).toBeInTheDocument();
});
it('scans every library in a source when its Scan-all button is clicked', async () => {
const handle = mockApi({
mediaSources: [
mediaSource({
id: 30,
libraries: [
library({ id: 31, itemCount: 10, mediaKind: 'Movies', name: 'Movies' }),
library({ id: 32, itemCount: 5, mediaKind: 'Shows', name: 'TV Shows' })
],
name: 'Local'
})
]
});
render(<LibrariesScreen />);
expect(await screen.findByText('TV Shows')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Scan all libraries in Local' }));
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/31/scan', expect.objectContaining({ method: 'POST' }));
});
await waitFor(() => {
expect(handle.fetchSpy).toHaveBeenCalledWith('/api/libraries/32/scan', expect.objectContaining({ method: 'POST' }));
});
expect(fetchCount(handle, '/api/libraries/31/scan')).toBe(1);
expect(fetchCount(handle, '/api/libraries/32/scan')).toBe(1);
});
it('shows an empty state when no media sources exist', async () => {
mockApi({ mediaSources: [] });
render(<LibrariesScreen />);
expect(await screen.findByText('No media sources returned')).toBeInTheDocument();
});
});
+309
View File
@@ -0,0 +1,309 @@
import type { ReactNode } from 'react';
import {
Clapperboard,
Clock,
FileImage,
Film,
Folder,
HardDrive,
MonitorPlay,
Music,
Plus,
Radio,
RefreshCw,
Server,
Settings,
TriangleAlert
} from 'lucide-react';
import {
Badge,
Button,
Card,
IconButton,
ProgressBar,
Spinner,
StatusDot
} from '../components';
import {
useLibrariesScreenQuery,
type LibraryScanStatus,
type MediaSource,
type MediaSourceLibrary
} from '../api';
export function LibrariesScreen() {
const query = useLibrariesScreenQuery();
if (query.status === 'loading') {
return <LibrariesLoadingState />;
}
if (query.status === 'error') {
return <LibrariesErrorState error={query.error} refresh={query.refresh} />;
}
if (query.data.sources.length === 0) {
return <LibrariesEmptyState />;
}
const totalItems = query.data.sources.reduce(
(sum, source) => sum + source.libraries.reduce((librarySum, library) => librarySum + library.itemCount, 0),
0
);
const scanStatusesByLibraryId = new Map(query.data.scanStatuses.map((status) => [status.libraryId, status]));
return (
<div className="ctv-libraries-screen">
<section className="ctv-libraries-header">
<div>
<span className="ctv-kicker">Sources</span>
<h2>Media Libraries</h2>
<p>Monitor connected media sources and trigger per-library scans.</p>
</div>
<div className="ctv-libraries-header-actions">
<Button disabled startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">Scan All</Button>
<Button disabled startIcon={<Plus aria-hidden="true" size={15} />}>Add Source</Button>
</div>
</section>
{query.error && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{query.error}</span>
</div>
)}
<div className="ctv-libraries-summary">
<span>{query.data.sources.length} source{query.data.sources.length === 1 ? '' : 's'}</span>
<span>{totalItems.toLocaleString()} items</span>
<span><StatusDot status={query.data.scanStatuses.length > 0 ? 'live' : 'ok'} size={7} />{query.data.scanStatuses.length} active scan{query.data.scanStatuses.length === 1 ? '' : 's'}</span>
</div>
<div className="ctv-libraries-grid">
{query.data.sources.map((source) => (
<MediaSourceCard
key={source.id}
onScanLibrary={query.scanLibrary}
scanStatusesByLibraryId={scanStatusesByLibraryId}
scanningLibraryIds={query.scanningLibraryIds}
source={source}
/>
))}
<section className="ctv-library-add-card" aria-label="Add media source">
<span className="ctv-library-kind-icon ctv-library-kind-local"><Plus aria-hidden="true" size={18} /></span>
<div>
<h3>Connect a media source</h3>
<p>Adding sources is deferred to the existing server setup screens.</p>
</div>
<div className="ctv-library-add-options" aria-hidden="true">
<span><HardDrive size={13} />Local folder</span>
<span><Server size={13} />Plex</span>
<span><Server size={13} />Jellyfin</span>
<span><Server size={13} />Emby</span>
</div>
</section>
</div>
</div>
);
}
function LibrariesLoadingState() {
return (
<Card title={<h2>Loading libraries</h2>} subtitle="Fetching media sources and active scan status.">
<div className="ctv-dashboard-state">
<Spinner tone="muted" />
<span>Loading libraries</span>
</div>
</Card>
);
}
function LibrariesErrorState({ error, refresh }: { error: string; refresh: () => void }) {
return (
<Card
title={<h2>Libraries unavailable</h2>}
subtitle="The API returned an error while loading media sources."
actions={<Button onClick={refresh} startIcon={<RefreshCw aria-hidden="true" size={15} />} variant="secondary">Retry</Button>}
>
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
</Card>
);
}
function LibrariesEmptyState() {
return (
<Card title={<h2>No media sources</h2>} subtitle="Configure a source in the server setup screens before monitoring scans here.">
<div className="ctv-schedule-empty">No media sources returned</div>
</Card>
);
}
function MediaSourceCard({
onScanLibrary,
scanStatusesByLibraryId,
scanningLibraryIds,
source
}: {
onScanLibrary: (libraryId: number) => Promise<void>;
scanStatusesByLibraryId: Map<number, LibraryScanStatus>;
scanningLibraryIds: Set<number>;
source: MediaSource;
}) {
const totalItems = source.libraries.reduce((sum, library) => sum + library.itemCount, 0);
const scanning = source.libraries.some((library) => scanningLibraryIds.has(library.id));
const scanSource = () => {
source.libraries.forEach((library) => {
void onScanLibrary(library.id);
});
};
return (
<section className="ctv-library-source-card" aria-label={`${source.name} media source`}>
<div className="ctv-library-source-head">
<span className={`ctv-library-kind-icon ctv-library-kind-${source.kind.toLowerCase()}`}>{sourceKindIcon(source.kind)}</span>
<div>
<div className="ctv-library-source-title">
<h3>{source.name}</h3>
<StatusDot status={scanning ? 'live' : 'ok'} label={scanning ? 'Scanning' : 'Synced'} size={7} />
</div>
<span>{source.connectionAddress ?? 'Local connection'}</span>
</div>
<div className="ctv-library-source-actions">
<IconButton disabled={scanning} onClick={scanSource} size="sm" title={`Scan all libraries in ${source.name}`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
<IconButton disabled size="sm" title={`Settings unavailable for ${source.name}`}>
<Settings aria-hidden="true" size={15} />
</IconButton>
</div>
</div>
<div className="ctv-library-list" role="list" aria-label={`${source.name} libraries`}>
{source.libraries.length === 0 ? (
<div className="ctv-library-empty">No synced libraries returned</div>
) : source.libraries.map((library) => (
<LibraryRow
key={library.id}
library={library}
onScanLibrary={onScanLibrary}
scanStatus={scanStatusesByLibraryId.get(library.id) ?? null}
scanning={scanningLibraryIds.has(library.id)}
/>
))}
</div>
<div className="ctv-library-source-foot">
<span><Clock aria-hidden="true" size={13} />{scanning ? 'Scanning now' : sourceLastScanLabel(source)}</span>
<span><code>{totalItems.toLocaleString()}</code> items · {source.libraries.length} librar{source.libraries.length === 1 ? 'y' : 'ies'}</span>
</div>
</section>
);
}
function LibraryRow({
library,
onScanLibrary,
scanStatus,
scanning
}: {
library: MediaSourceLibrary;
onScanLibrary: (libraryId: number) => Promise<void>;
scanStatus: LibraryScanStatus | null;
scanning: boolean;
}) {
const scanActive = scanStatus !== null;
const disabled = scanning || scanActive;
return (
<div className="ctv-library-row" role="listitem">
<span className="ctv-library-media-icon">{libraryMediaIcon(library.mediaKind)}</span>
<div className="ctv-library-row-main">
<strong>{library.name}</strong>
<span><span>{formatLibraryMediaKind(library.mediaKind)}</span> · <code>{library.itemCount.toLocaleString()}</code> items</span>
<small>{library.lastScan ? `Last scan ${formatDateTime(library.lastScan)}` : 'Never scanned'}</small>
</div>
<div className="ctv-library-row-status">
{scanStatus ? (
<div className="ctv-library-progress">
<ProgressBar value={scanStatus.percent} showLabel />
<Badge tone="accent" dot>Scanning</Badge>
</div>
) : (
<Badge tone="ok" dot>Synced</Badge>
)}
<IconButton disabled={disabled} onClick={() => void onScanLibrary(library.id)} size="sm" title={`Scan ${library.name}`}>
<RefreshCw aria-hidden="true" size={15} />
</IconButton>
</div>
</div>
);
}
function sourceKindIcon(kind: string): ReactNode {
return kind === 'Local'
? <HardDrive aria-hidden="true" size={18} />
: <Server aria-hidden="true" size={18} />;
}
function libraryMediaIcon(kind: string): ReactNode {
switch (kind) {
case 'Movies':
return <Clapperboard aria-hidden="true" size={14} />;
case 'Shows':
return <MonitorPlay aria-hidden="true" size={14} />;
case 'MusicVideos':
case 'Songs':
return <Music aria-hidden="true" size={14} />;
case 'Images':
return <FileImage aria-hidden="true" size={14} />;
case 'RemoteStreams':
return <Radio aria-hidden="true" size={14} />;
case 'OtherVideos':
return <Film aria-hidden="true" size={14} />;
default:
return <Folder aria-hidden="true" size={14} />;
}
}
function formatLibraryMediaKind(kind: string): string {
switch (kind) {
case 'MusicVideos':
return 'Music Videos';
case 'OtherVideos':
return 'Other Videos';
case 'RemoteStreams':
return 'Remote Streams';
default:
return kind;
}
}
function sourceLastScanLabel(source: MediaSource): string {
const scans = source.libraries
.map((library) => library.lastScan)
.filter((scan): scan is string => Boolean(scan))
.sort();
return scans.length > 0 ? `Last scan ${formatDateTime(scans[scans.length - 1])}` : 'Never scanned';
}
// Inlined rather than imported back from App.tsx (mirrors the ChannelsScreen #244 extraction):
// App.tsx's formatDateTime is still used by other App.tsx-owned screens (Playouts, Guide), so
// keeping this screen self-sufficient means duplicating the tiny formatter here.
function formatDateTime(value: string | null | undefined): string {
if (!value) {
return 'unknown';
}
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) {
return value.slice(0, 5);
}
return parsed.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}