feat(spa): multi-collection & rerun-collection editor screens (#151, #152) #194

Merged
timothy merged 3 commits from feat/151-152-spa-editors into main 2026-07-08 20:22:01 +02:00
13 changed files with 1702 additions and 10 deletions
+9 -3
View File
@@ -73,6 +73,8 @@ been added to the redirect map yet.
| `/playouts/classic/{Id}`, `/playouts/block/{Id}`, `/playouts/scripted/{Id}`, `/playouts/sequential/{Id}` | `ClassicPlayoutEditor.razor`, `BlockPlayoutEditor.razor`, `ScriptedPlayoutEditor.razor`, `SequentialPlayoutEditor.razor` | `/app/playouts` | merged; #144 S5/S6 |
| `/playouts/{Id:int}/alternate-schedules` | `PlayoutAlternateSchedulesEditor.razor` | `/app/playouts/{id}/alternate-schedules` | allowSubPaths (`PlayoutsRouteScreen`); #144 S6/#162 |
| `/playouts/{Id:int}/templates` | `PlayoutTemplatesEditor.razor` | `/app/playouts/{id}/templates` | allowSubPaths (`PlayoutsRouteScreen`); #144 S6/#162 |
| `/media/multi-collections`(`/add`, `/{Id}/edit`) | `MultiCollections.razor`, `MultiCollectionEditor.razor` | `/app/multi-collections` | **SPA DONE** (`MultiCollectionsScreen`; in-screen list↔editor via local state, no sub-paths); #151 |
| `/media/rerun-collections`(`/add`, `/{Id}/edit`) | `RerunCollections.razor`, `RerunCollectionEditor.razor` | `/app/rerun-collections` | **SPA DONE** (`RerunCollectionsScreen`; in-screen list↔editor via local state, no sub-paths); #152 |
| `/schedules/{Id:int}`, `/schedules/add`, `/schedules/{Id:int}/items` | `ScheduleEditor.razor`, `ScheduleItemsEditor.razor` | `/app/schedules` | merged into schedules screen |
| `/media/filler/presets`(`/add`, `/{Id}/edit`) | `FillerPresets.razor`, `FillerPresetEditor.razor` | `/app/filler-presets` | allowSubPaths |
| `/media/collections`(`/add`, `/{Id}/edit`, `/{Id}`) | `ManualCollections.razor`, `CollectionEditor.razor`, `CollectionItems.razor` + `SmartCollections.razor`/`SmartCollectionEditor.razor` | `/app/collections` | allowSubPaths |
@@ -100,12 +102,16 @@ been added to the redirect map yet.
## Section 3 — BLAZOR-ONLY (blocking issues)
### Multi/rerun collections & playlist variants — API gaps #151/#152/#153
### Playlist variant management — API gap #153
**#151 (multi-collections) and #152 (rerun collections) are DONE** — both now have SPA editor screens
(`/app/multi-collections`, `/app/rerun-collections`; see Section 2). The rerun editor offers the
REST-supported selection types only (Collection, MultiCollection, SmartCollection, and the media-item
types TelevisionShow/TelevisionSeason/Artist/Movie/Episode/MusicVideo/OtherVideo/Song/Image/RemoteStream);
Playlist is intentionally excluded, matching `RerunCollectionRequestMapping.IsSupportedSelectionType`.
| Blazor route | File | Blocking issue |
|---|---|---|
| `/media/multi-collections`(`/add`, `/{Id}/edit`) | `MultiCollections.razor`, `MultiCollectionEditor.razor` | #151 — **REST API DONE** (`MultiCollectionController`, `/api/multi-collections` CRUD + `web/src/api/multiCollections.ts`); SPA editor screen still pending (follow-up) |
| `/media/rerun-collections`(`/add`, `/{Id}/edit`) | `RerunCollections.razor`, `RerunCollectionEditor.razor` | #152 — **REST API DONE** (`RerunCollectionController`, `/api/rerun-collections` CRUD + `web/src/api/rerunCollections.ts`); SPA editor screen still pending (follow-up) |
| `/media/playlists`(`/{Id}`) editing depth beyond what `/app/collections` covers | `Playlists.razor`, `PlaylistEditor.razor` | #153 (playlist variant management API) |
**#155 RESOLVED** (collection-items enumeration): `GET /api/collections/{id}/items` (paged) now returns a
+6 -5
View File
@@ -59,8 +59,8 @@ Channel (1) ──< Playout (0..N per channel; ChannelPlayoutSource distinguishe
| **Watermark** | `ChannelWatermark` image overlay; attached at channel, schedule-item, block-item, deco, or playout-item level with position/size/opacity. | `ChannelWatermark`, `DecoWatermark`, `BlockItemWatermark`, `ProgramScheduleItemWatermark` | `/app/watermarks` |
| **Collection** | Manual list of media items (`CollectionItem`). | `Collection` | `/app/collections` |
| **SmartCollection** | Saved search — a `Query` string, no static item list. | `SmartCollection` | `/app/collections` |
| **MultiCollection** | Combines multiple `Collection`s and/or `SmartCollection`s (with grouping via `MultiCollectionItem`/`MultiCollectionSmartItem`). | `MultiCollection` | `/app/collections` |
| **RerunCollection** | One source (collection/media item/multi/smart) with separate `FirstRunPlaybackOrder` vs `RerunPlaybackOrder`. | `RerunCollection` | `/app/collections` (blocked on API #152 per parity tracker) |
| **MultiCollection** | Combines multiple `Collection`s and/or `SmartCollection`s (with grouping via `MultiCollectionItem`/`MultiCollectionSmartItem`). | `MultiCollection` | `/app/multi-collections` (#151) |
| **RerunCollection** | One source (collection/media item/multi/smart) with separate `FirstRunPlaybackOrder` vs `RerunPlaybackOrder`. | `RerunCollection` | `/app/rerun-collections` (#152) |
| **Playlist** / **PlaylistGroup** | Ordered `PlaylistItem`s; `IsSystem` flag marks built-in/non-deletable playlists and groups. | `Playlist`, `PlaylistGroup`, `PlaylistItem` | `/app/collections` |
| **Media kinds** | `CollectionType` enum distinguishes container kinds (Collection/TelevisionShow/TelevisionSeason/Artist/MultiCollection/SmartCollection/Playlist/RerunFirstRun/RerunRerun/SearchQuery) from leaf media kinds (Movie/Episode/MusicVideo/OtherVideo/Song/Image/RemoteStream) plus synthetic `FakeCollection`/`FakePlaylistItem`. Concrete media entities: `Movie`, `Show`/`Season`/`Episode`, `Artist`/`MusicVideo`/`Song`, `OtherVideo`, `Image`, `RemoteStream` (`ErsatzTV.Core/Domain/MediaItem/`). | `MediaItem` subclasses | `/app/media?kind=...` |
| **Library / LibraryPath / LibraryFolder** | `Library` (abstract; Local/Plex/Jellyfin/Emby subclasses) owns one or more `LibraryPath`s (scan roots); each path has a `LibraryFolder` tree used for browsing and image-folder duration metadata. | `Library`, `LibraryPath`, `LibraryFolder` | `/app/libraries` |
@@ -81,7 +81,7 @@ Primary nav: `/app` (dashboard), `/app/channels`, `/app/new-channel`, `/app/guid
Media nav: `/app/media` (generic kind-filtered browse, `?kind=movies|shows|artists|music-videos|
other-videos|remote-streams|images`), `/app/search`, `/app/trash`, `/app/collections` (manual +
smart + multi + playlist; rerun-collection editing still gated on API #152),
smart), `/app/multi-collections` (#151), `/app/rerun-collections` (#152),
`/app/filler-presets`, `/app/libraries`, `/app/trakt-lists`.
System nav: `/app/settings` (sub-tabs: streaming/system/logging/playout/scanner/general/xmltv —
@@ -94,8 +94,9 @@ validator; playback troubleshooting still gated on API #145), `/app/ffmpeg-profi
Per-item media detail pages and the image-folder browser (`MediaDetailScreen`'s
`MovieDetailScreen`/`ShowDetailScreen`/`SeasonDetailScreen`/`ArtistDetailScreen`,
`ImageBrowserScreen`) landed via #141 (PR #183) at `/app/media/{movies|shows|seasons|artists}/{id}`
and `/app/media/images/browser`. Not yet in the SPA: multi/rerun-collection + playlist-variant
management (API gaps #151/#152/#153/#155). See `docs/blazor-route-parity.md` for the full
and `/app/media/images/browser`. Multi-collection (#151) and rerun-collection (#152) editors now
live in the SPA at `/app/multi-collections` and `/app/rerun-collections`. Not yet in the SPA:
playlist-variant management depth (API gap #153). See `docs/blazor-route-parity.md` for the full
route-by-route tracker.
## Key handler / file locations
+13
View File
@@ -56,6 +56,19 @@ describe('ChicoryTV SPA scaffold', () => {
expect(window.location.pathname).toBe('/app/schedules');
});
it('registers the multi-collection and rerun-collection nav entries', async () => {
render(<App />);
// Anchored exact names avoid matching the substring "Collections" nav entry (spa-conventions §6).
fireEvent.click(screen.getByRole('link', { name: 'Multi-Collections' }));
expect(screen.getByRole('heading', { name: 'Multi-Collections' })).toBeInTheDocument();
expect(window.location.pathname).toBe('/app/multi-collections');
fireEvent.click(screen.getByRole('link', { name: 'Rerun Collections' }));
expect(screen.getByRole('heading', { name: 'Rerun Collections' })).toBeInTheDocument();
expect(window.location.pathname).toBe('/app/rerun-collections');
});
it('preserves native browser behavior for modified nav link clicks', () => {
render(<App />);
+38
View File
@@ -34,6 +34,7 @@ import {
Hash,
HardDrive,
Info,
Layers,
LayoutDashboard,
LayoutGrid,
Library,
@@ -47,6 +48,7 @@ import {
Play,
Radio,
RefreshCw,
Repeat,
ScrollText,
Search,
Server,
@@ -69,6 +71,8 @@ import { FFmpegProfilesScreen } from './screens/FFmpegProfilesScreen';
import { FillerPresetsScreen } from './screens/FillerPresetsScreen';
import { LogsScreen } from './screens/LogsScreen';
import { MediaBrowseScreen } from './screens/MediaBrowseScreen';
import { MultiCollectionsScreen } from './screens/MultiCollectionsScreen';
import { RerunCollectionsScreen } from './screens/RerunCollectionsScreen';
import {
ArtistDetailScreen,
MovieDetailScreen,
@@ -183,6 +187,8 @@ type ScreenId =
| 'search'
| 'trash'
| 'collections'
| 'multiCollections'
| 'rerunCollections'
| 'fillerPresets'
| 'libraries'
| 'traktLists'
@@ -394,6 +400,28 @@ const routes: ScreenRoute[] = [
primaryAction: 'Add Collection',
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: 'fillerPresets',
path: '/app/filler-presets',
@@ -532,6 +560,8 @@ const mediaNavIds: ScreenId[] = [
'search',
'trash',
'collections',
'multiCollections',
'rerunCollections',
'fillerPresets',
'libraries',
'traktLists'
@@ -3691,6 +3721,14 @@ function ScreenContent({
return <CollectionsScreen />;
}
if (route.id === 'multiCollections') {
return <MultiCollectionsScreen />;
}
if (route.id === 'rerunCollections') {
return <RerunCollectionsScreen />;
}
if (route.id === 'traktLists') {
return <TraktListsScreen key={window.location.pathname} />;
}
+2
View File
@@ -18,10 +18,12 @@ export * from './logs';
export * from './maintenance';
export * from './mediaDetail';
export * from './mediaItems';
export * from './multiCollections';
export * from './pickers';
export * from './playlists';
export * from './playoutHistory';
export * from './playouts';
export * from './rerunCollections';
export * from './schedules';
export * from './search';
export * from './settings';
+100
View File
@@ -0,0 +1,100 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
createMultiCollection,
deleteMultiCollection,
getMultiCollection,
getMultiCollections,
messageFromMultiCollectionError,
updateMultiCollection
} from './multiCollections';
import { ApiError } from './client';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
function noContent(): Response {
return new Response(null, { status: 204 });
}
describe('multiCollections api client', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('getMultiCollections maps paging params into the query string', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));
await getMultiCollections({ pageNum: 2, pageSize: 25, query: 'kids' });
const url = new URL(String(fetchMock.mock.calls[0][0]), 'http://localhost');
expect(url.pathname).toBe('/api/multi-collections');
expect(url.searchParams.get('pageNum')).toBe('2');
expect(url.searchParams.get('pageSize')).toBe('25');
expect(url.searchParams.get('query')).toBe('kids');
});
it('getMultiCollections with no params hits the bare endpoint', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));
await getMultiCollections();
expect(fetchMock).toHaveBeenCalledWith('/api/multi-collections', expect.objectContaining({ method: 'GET' }));
});
it('getMultiCollection fetches a single multi-collection by id', async () => {
const fetchMock = vi
.spyOn(window, 'fetch')
.mockResolvedValue(jsonResponse({ id: 4, items: [], name: 'Bundle' }));
await expect(getMultiCollection(4)).resolves.toMatchObject({ id: 4 });
expect(fetchMock).toHaveBeenCalledWith('/api/multi-collections/4', expect.objectContaining({ method: 'GET' }));
});
it('createMultiCollection POSTs the name and items', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 9, items: [], name: 'New' }, 201));
const body = {
items: [{ collectionId: 3, playbackOrder: 'Chronological' as const, scheduleAsGroup: true, smartCollectionId: null }],
name: 'New'
};
await expect(createMultiCollection(body)).resolves.toMatchObject({ id: 9 });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/multi-collections');
expect(init).toMatchObject({ method: 'POST' });
expect(JSON.parse(String(init?.body))).toEqual(body);
});
it('updateMultiCollection PUTs to the id route', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 5, items: [], name: 'Renamed' }));
const body = {
items: [{ collectionId: null, playbackOrder: 'Chronological' as const, scheduleAsGroup: false, smartCollectionId: 7 }],
name: 'Renamed'
};
await updateMultiCollection(5, body);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/multi-collections/5');
expect(init).toMatchObject({ method: 'PUT' });
expect(JSON.parse(String(init?.body))).toEqual(body);
});
it('deleteMultiCollection issues a DELETE and resolves on 204', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await expect(deleteMultiCollection(6)).resolves.toBeUndefined();
expect(fetchMock).toHaveBeenCalledWith('/api/multi-collections/6', expect.objectContaining({ method: 'DELETE' }));
});
it('messageFromMultiCollectionError narrows ApiError, Error, and unknown', () => {
expect(messageFromMultiCollectionError(new ApiError(422, { detail: 'In use', title: 'Unprocessable' }))).toBe('In use');
expect(messageFromMultiCollectionError(new Error('boom'))).toBe('boom');
expect(messageFromMultiCollectionError('nope', 'fallback')).toBe('fallback');
});
});
+17 -1
View File
@@ -1,8 +1,9 @@
import { request } from './client';
import { ApiError, request } from './client';
import type { components } from './generated/v1';
export type MultiCollection = components['schemas']['MultiCollectionResponseModel'];
export type MultiCollectionItem = components['schemas']['MultiCollectionItemResponseModel'];
export type MultiCollectionItemRequest = components['schemas']['MultiCollectionItemRequest'];
export type PagedMultiCollections = components['schemas']['PagedMultiCollectionsResponseModel'];
export type CreateMultiCollectionRequest = components['schemas']['CreateMultiCollectionRequest'];
export type UpdateMultiCollectionRequest = components['schemas']['UpdateMultiCollectionRequest'];
@@ -48,3 +49,18 @@ export function updateMultiCollection(id: number, body: UpdateMultiCollectionReq
export function deleteMultiCollection(id: number): Promise<void> {
return request<void>(`/api/multi-collections/${id}`, { method: 'DELETE' });
}
export function messageFromMultiCollectionError(
error: unknown,
fallback = 'Unable to load multi-collections'
): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
}
if (error instanceof Error) {
return error.message;
}
return fallback;
}
+114
View File
@@ -0,0 +1,114 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
createRerunCollection,
deleteRerunCollection,
getRerunCollection,
getRerunCollections,
messageFromRerunCollectionError,
updateRerunCollection
} from './rerunCollections';
import { ApiError } from './client';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
function noContent(): Response {
return new Response(null, { status: 204 });
}
describe('rerunCollections api client', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('getRerunCollections maps paging params into the query string', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));
await getRerunCollections({ pageNum: 1, pageSize: 50, query: 'noir' });
const url = new URL(String(fetchMock.mock.calls[0][0]), 'http://localhost');
expect(url.pathname).toBe('/api/rerun-collections');
expect(url.searchParams.get('pageNum')).toBe('1');
expect(url.searchParams.get('pageSize')).toBe('50');
expect(url.searchParams.get('query')).toBe('noir');
});
it('getRerunCollections with no params hits the bare endpoint', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));
await getRerunCollections();
expect(fetchMock).toHaveBeenCalledWith('/api/rerun-collections', expect.objectContaining({ method: 'GET' }));
});
it('getRerunCollection fetches a single rerun collection by id', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(
jsonResponse({
collectionType: 'Collection',
firstRunPlaybackOrder: 'Chronological',
id: 3,
name: 'Reruns',
rerunPlaybackOrder: 'Shuffle',
selectedId: 8,
selectedName: 'Favorites'
})
);
await expect(getRerunCollection(3)).resolves.toMatchObject({ id: 3, selectedName: 'Favorites' });
expect(fetchMock).toHaveBeenCalledWith('/api/rerun-collections/3', expect.objectContaining({ method: 'GET' }));
});
it('createRerunCollection POSTs the full tagged-union body', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 12 }, 201));
const body = {
collectionType: 'TelevisionShow' as const,
firstRunPlaybackOrder: 'SeasonEpisode' as const,
name: 'Nightly',
rerunPlaybackOrder: 'Chronological' as const,
selectedId: 42
};
await expect(createRerunCollection(body)).resolves.toMatchObject({ id: 12 });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/rerun-collections');
expect(init).toMatchObject({ method: 'POST' });
expect(JSON.parse(String(init?.body))).toEqual(body);
});
it('updateRerunCollection PUTs to the id route', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 5 }));
const body = {
collectionType: 'MultiCollection' as const,
firstRunPlaybackOrder: 'Shuffle' as const,
name: 'Bundle Reruns',
rerunPlaybackOrder: 'Shuffle' as const,
selectedId: 99
};
await updateRerunCollection(5, body);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/rerun-collections/5');
expect(init).toMatchObject({ method: 'PUT' });
expect(JSON.parse(String(init?.body))).toEqual(body);
});
it('deleteRerunCollection issues a DELETE and resolves on 204', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await expect(deleteRerunCollection(7)).resolves.toBeUndefined();
expect(fetchMock).toHaveBeenCalledWith('/api/rerun-collections/7', expect.objectContaining({ method: 'DELETE' }));
});
it('messageFromRerunCollectionError narrows ApiError, Error, and unknown', () => {
expect(messageFromRerunCollectionError(new ApiError(422, { detail: 'In use', title: 'Unprocessable' }))).toBe('In use');
expect(messageFromRerunCollectionError(new Error('boom'))).toBe('boom');
expect(messageFromRerunCollectionError('nope', 'fallback')).toBe('fallback');
});
});
+16 -1
View File
@@ -1,4 +1,4 @@
import { request } from './client';
import { ApiError, request } from './client';
import type { components } from './generated/v1';
export type RerunCollection = components['schemas']['RerunCollectionResponseModel'];
@@ -47,3 +47,18 @@ export function updateRerunCollection(id: number, body: UpdateRerunCollectionReq
export function deleteRerunCollection(id: number): Promise<void> {
return request<void>(`/api/rerun-collections/${id}`, { method: 'DELETE' });
}
export function messageFromRerunCollectionError(
error: unknown,
fallback = 'Unable to load rerun collections'
): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
}
if (error instanceof Error) {
return error.message;
}
return fallback;
}
@@ -0,0 +1,176 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MultiCollectionsScreen } from './MultiCollectionsScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
const multiCollections = [
{
id: 1,
items: [
{ collectionId: 5, name: 'Favorites', playbackOrder: 'Chronological', scheduleAsGroup: false, smartCollectionId: null },
{ collectionId: null, name: 'Action', playbackOrder: 'Chronological', scheduleAsGroup: true, smartCollectionId: 9 }
],
name: 'Saturday Bundle'
},
{ id: 2, items: [], name: 'Empty Bundle' }
];
const manualCollections = [
{ collectionType: 'Collection', id: 5, name: 'Favorites', state: 'Normal', useCustomPlaybackOrder: false }
];
const smartCollections = [{ id: 9, name: 'Action', query: 'genre:action' }];
interface MockOptions {
multi?: unknown[];
onRequest?: (url: string, method: string, body: unknown) => Response | null;
}
function mockApi(options: MockOptions = {}) {
const multi = options.multi ?? multiCollections;
return 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;
if (options.onRequest) {
const override = options.onRequest(url, method, body);
if (override) {
return Promise.resolve(override);
}
}
if (url.startsWith('/api/multi-collections') && method === 'GET') {
return Promise.resolve(jsonResponse({ page: multi, totalCount: multi.length }));
}
if (url === '/api/collections' && method === 'GET') {
return Promise.resolve(jsonResponse(manualCollections));
}
if (url === '/api/smart-collections' && method === 'GET') {
return Promise.resolve(jsonResponse(smartCollections));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
}
describe('MultiCollectionsScreen', () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
window.localStorage.clear();
});
it('renders the multi-collections list with item counts', async () => {
mockApi();
render(<MultiCollectionsScreen />);
expect(await screen.findByText('Saturday Bundle')).toBeInTheDocument();
expect(screen.getByText('Empty Bundle')).toBeInTheDocument();
expect(screen.getByText('2 items')).toBeInTheDocument();
expect(screen.getByText('0 items')).toBeInTheDocument();
});
it('creates a multi-collection with an added manual collection', async () => {
const fetchMock = mockApi({
multi: [],
onRequest: (url, method) =>
url === '/api/multi-collections' && method === 'POST'
? jsonResponse({ id: 3, items: [], name: 'New Bundle' }, 201)
: null
});
render(<MultiCollectionsScreen />);
fireEvent.click(await screen.findByRole('button', { name: 'New multi-collection' }));
// Editor loads the collections list; select and add the manual collection.
const collectionSelect = (await screen.findAllByRole('combobox'))[0];
await within(collectionSelect).findByText('Favorites');
fireEvent.change(collectionSelect, { target: { value: '5' } });
fireEvent.click(screen.getByRole('button', { name: 'Add Collection' }));
// The added item appears in the items list.
expect(await screen.findByText('Favorites')).toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText('Multi-collection name'), { target: { value: 'New Bundle' } });
fireEvent.click(screen.getByRole('button', { name: 'Add multi-collection' }));
await waitFor(() => {
const postCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/multi-collections' && (init?.method ?? '').toUpperCase() === 'POST'
);
expect(postCall).toBeDefined();
expect(JSON.parse(String(postCall?.[1]?.body))).toEqual({
items: [{ collectionId: 5, playbackOrder: 'Chronological', scheduleAsGroup: false, smartCollectionId: null }],
name: 'New Bundle'
});
});
});
it('opens an existing multi-collection and PUTs its edits', async () => {
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/multi-collections/1' && method === 'PUT'
? jsonResponse({ id: 1, items: [], name: 'Saturday Bundle' })
: null
});
render(<MultiCollectionsScreen />);
fireEvent.click(await screen.findByText('Saturday Bundle'));
// Existing items are seeded from the response (manual + smart).
expect(await screen.findByText('Favorites')).toBeInTheDocument();
expect(screen.getByText('Action')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Save multi-collection' }));
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/multi-collections/1' && (init?.method ?? '').toUpperCase() === 'PUT'
);
expect(putCall).toBeDefined();
const parsed = JSON.parse(String(putCall?.[1]?.body));
expect(parsed.name).toBe('Saturday Bundle');
expect(parsed.items).toEqual(
expect.arrayContaining([
{ collectionId: 5, playbackOrder: 'Chronological', scheduleAsGroup: false, smartCollectionId: null },
{ collectionId: null, playbackOrder: 'Chronological', scheduleAsGroup: true, smartCollectionId: 9 }
])
);
});
});
it('confirms and DELETEs a multi-collection', async () => {
const fetchMock = mockApi();
render(<MultiCollectionsScreen />);
const row = (await screen.findByText('Saturday Bundle')).closest('.ctv-settings-flush-row') as HTMLElement;
fireEvent.click(within(row).getByRole('button', { name: 'Delete' }));
const dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }));
await waitFor(() => {
expect(
fetchMock.mock.calls.some(
([u, init]) => u === '/api/multi-collections/1' && (init?.method ?? '').toUpperCase() === 'DELETE'
)
).toBe(true);
});
});
});
+459
View File
@@ -0,0 +1,459 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowLeft, Check, Layers, Plus, Trash2, TriangleAlert } from 'lucide-react';
import { Badge, Button, Card, ConfirmDialog, IconButton, Input, Select, Spinner, Switch } from '../components';
import {
createMultiCollection,
deleteMultiCollection,
getCollections,
getMultiCollections,
getSmartCollections,
messageFromMultiCollectionError,
updateMultiCollection,
type MediaCollection,
type MultiCollection,
type MultiCollectionItemRequest,
type SmartCollection
} from '../api';
/* ---------- data hook ---------- */
type ListState =
| { data: MultiCollection[]; error: null; status: 'success' }
| { data: null; error: string; status: 'error' }
| { data: null; error: null; status: 'loading' };
function useMultiCollectionsData() {
const [state, setState] = useState<ListState>({ data: null, error: null, status: 'loading' });
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
return () => {
activeRef.current = false;
};
}, []);
const load = useCallback(() => {
getMultiCollections({ pageSize: 1000 })
.then((result) => {
if (activeRef.current) {
setState({ data: result.page ?? [], error: null, status: 'success' });
}
})
.catch((error: unknown) => {
if (activeRef.current) {
setState({ data: null, error: messageFromMultiCollectionError(error), status: 'error' });
}
});
}, []);
useEffect(() => {
load();
}, [load]);
const refresh = useCallback(
(quiet = false) => {
if (!quiet) {
setState({ data: null, error: null, status: 'loading' });
}
load();
},
[load]
);
return { refresh, state };
}
/* ---------- editor ---------- */
// One row in the editor: a manual collection or a smart collection, plus its
// schedule-as-group flag. Names are resolved from the fetched collection lists.
interface DraftItem {
id: number;
kind: 'manual' | 'smart';
name: string;
scheduleAsGroup: boolean;
}
function itemsFromMultiCollection(mc: MultiCollection): DraftItem[] {
return mc.items.map((item) =>
item.collectionId != null
? { id: item.collectionId, kind: 'manual', name: item.name, scheduleAsGroup: item.scheduleAsGroup }
: { id: item.smartCollectionId ?? 0, kind: 'smart', name: item.name, scheduleAsGroup: item.scheduleAsGroup }
);
}
function toItemRequest(item: DraftItem): MultiCollectionItemRequest {
return {
collectionId: item.kind === 'manual' ? item.id : null,
playbackOrder: 'Chronological',
scheduleAsGroup: item.scheduleAsGroup,
smartCollectionId: item.kind === 'smart' ? item.id : null
};
}
function MultiCollectionEditor({
initial,
onBack,
onSaved
}: {
initial: MultiCollection | null;
onBack: () => void;
onSaved: () => void;
}) {
const [name, setName] = useState(initial?.name ?? '');
const [items, setItems] = useState<DraftItem[]>(initial ? itemsFromMultiCollection(initial) : []);
const [collections, setCollections] = useState<MediaCollection[]>([]);
const [smartCollections, setSmartCollections] = useState<SmartCollection[]>([]);
const [selectedCollection, setSelectedCollection] = useState('');
const [selectedSmart, setSelectedSmart] = useState('');
const [loadError, setLoadError] = useState<string | null>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
Promise.all([getCollections(), getSmartCollections()])
.then(([manual, smart]) => {
if (activeRef.current) {
setCollections(manual);
setSmartCollections(smart);
setLoadError(null);
}
})
.catch((error: unknown) => {
if (activeRef.current) {
setLoadError(messageFromMultiCollectionError(error, 'Unable to load collections'));
}
});
return () => {
activeRef.current = false;
};
}, []);
const hasManual = (id: number) => items.some((item) => item.kind === 'manual' && item.id === id);
const hasSmart = (id: number) => items.some((item) => item.kind === 'smart' && item.id === id);
const addCollection = () => {
const id = Number(selectedCollection);
if (!id || hasManual(id)) {
return;
}
const collection = collections.find((entry) => entry.id === id);
setItems((current) => [...current, { id, kind: 'manual', name: collection?.name ?? `#${id}`, scheduleAsGroup: false }]);
setSelectedCollection('');
};
const addSmart = () => {
const id = Number(selectedSmart);
if (!id || hasSmart(id)) {
return;
}
const collection = smartCollections.find((entry) => entry.id === id);
setItems((current) => [...current, { id, kind: 'smart', name: collection?.name ?? `#${id}`, scheduleAsGroup: false }]);
setSelectedSmart('');
};
const removeItem = (target: DraftItem) => {
setItems((current) => current.filter((item) => !(item.kind === target.kind && item.id === target.id)));
};
const setScheduleAsGroup = (target: DraftItem, next: boolean) => {
setItems((current) =>
current.map((item) => (item.kind === target.kind && item.id === target.id ? { ...item, scheduleAsGroup: next } : item))
);
};
const trimmedName = name.trim();
const save = async () => {
if (trimmedName.length === 0 || saving) {
return;
}
setSaving(true);
setSaveError(null);
try {
const body = { items: items.map(toItemRequest), name: trimmedName };
if (initial) {
await updateMultiCollection(initial.id, body);
} else {
await createMultiCollection(body);
}
onSaved();
} catch (error) {
setSaveError(messageFromMultiCollectionError(error, 'Unable to save multi-collection'));
} finally {
setSaving(false);
}
};
const collectionOptions = [
{ label: 'Select a collection…', value: '' },
...collections
.filter((entry) => !hasManual(entry.id))
.map((entry) => ({ label: entry.name ?? `#${entry.id}`, value: String(entry.id) }))
];
const smartOptions = [
{ label: 'Select a smart collection…', value: '' },
...smartCollections
.filter((entry) => !hasSmart(entry.id))
.map((entry) => ({ label: entry.name ?? `#${entry.id}`, value: String(entry.id) }))
];
const sortedItems = [...items].sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Button onClick={onBack} size="sm" startIcon={<ArrowLeft aria-hidden="true" size={14} />} variant="ghost">
All multi-collections
</Button>
<span className="ctv-collections-detail-title">{initial ? 'Edit multi-collection' : 'New multi-collection'}</span>
<span className="ctv-channels-spacer" />
{saveError && <span className="ctv-settings-savebar-error">{saveError}</span>}
<Button
disabled={trimmedName.length === 0 || saving}
loading={saving}
onClick={() => void save()}
size="sm"
startIcon={<Check aria-hidden="true" size={14} />}
>
{initial ? 'Save multi-collection' : 'Add multi-collection'}
</Button>
</div>
{loadError && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{loadError}</span>
</div>
)}
<Card title="Multi-collection">
<Input
label="Name"
onChange={(event) => setName(event.target.value)}
placeholder="Multi-collection name"
value={name}
/>
<div style={{ alignItems: 'flex-end', display: 'flex', gap: 8, marginTop: 16 }}>
<Select
label="Collections"
onChange={(event) => setSelectedCollection(event.target.value)}
options={collectionOptions}
value={selectedCollection}
/>
<Button
disabled={selectedCollection === ''}
onClick={addCollection}
size="sm"
startIcon={<Plus aria-hidden="true" size={14} />}
variant="secondary"
>
Add Collection
</Button>
</div>
<div style={{ alignItems: 'flex-end', display: 'flex', gap: 8, marginTop: 12 }}>
<Select
label="Smart Collections"
onChange={(event) => setSelectedSmart(event.target.value)}
options={smartOptions}
value={selectedSmart}
/>
<Button
disabled={selectedSmart === ''}
onClick={addSmart}
size="sm"
startIcon={<Plus aria-hidden="true" size={14} />}
variant="secondary"
>
Add Smart Collection
</Button>
</div>
</Card>
<Card padded={false}>
{sortedItems.length === 0 ? (
<div className="ctv-collections-empty">No collections added yet.</div>
) : (
sortedItems.map((item, index) => (
<div
className="ctv-settings-flush-row"
key={`${item.kind}:${item.id}`}
style={index === 0 ? { borderTop: 'none' } : undefined}
>
<Layers aria-hidden="true" color="var(--ctv-accent)" size={15} />
<span className="ctv-settings-flush-row-main ctv-settings-flush-row-title">{item.name}</span>
<Badge tone="neutral">{item.kind === 'smart' ? 'Smart' : 'Manual'}</Badge>
<label className="ctv-collections-order-toggle" title="Schedule as group">
<Switch
checked={item.scheduleAsGroup}
onChange={(next) => setScheduleAsGroup(item, next)}
size="sm"
/>
<span>Schedule as group</span>
</label>
<IconButton
onClick={() => removeItem(item)}
size="sm"
title={`Remove ${item.name}`}
variant="ghost"
>
<Trash2 aria-hidden="true" size={14} />
</IconButton>
</div>
))
)}
</Card>
</div>
);
}
/* ---------- screen ---------- */
export function MultiCollectionsScreen() {
const { refresh, state } = useMultiCollectionsData();
const [editing, setEditing] = useState<{ kind: 'new' } | { kind: 'edit'; item: MultiCollection } | null>(null);
const [deleteTarget, setDeleteTarget] = useState<MultiCollection | null>(null);
const [deleteBusy, setDeleteBusy] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
if (editing) {
return (
<MultiCollectionEditor
initial={editing.kind === 'edit' ? editing.item : null}
onBack={() => setEditing(null)}
onSaved={() => {
setEditing(null);
refresh(true);
}}
/>
);
}
if (state.status === 'loading') {
return (
<div className="ctv-collections-loading" role="status">
<Spinner size={18} />
<span>Loading multi-collections…</span>
</div>
);
}
if (state.status === 'error') {
return (
<div className="ctv-collections">
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{state.error}</span>
<span className="ctv-channels-spacer" />
<Button onClick={() => refresh()} size="sm" variant="secondary">
Retry
</Button>
</div>
</div>
);
}
const multiCollections = [...state.data].sort((a, b) =>
(a.name ?? '').localeCompare(b.name ?? '', undefined, { sensitivity: 'base' })
);
const confirmDelete = async () => {
if (!deleteTarget) {
return;
}
setDeleteBusy(true);
setDeleteError(null);
try {
await deleteMultiCollection(deleteTarget.id);
setDeleteTarget(null);
refresh(true);
} catch (error) {
setDeleteError(messageFromMultiCollectionError(error, 'Unable to delete multi-collection'));
} finally {
setDeleteBusy(false);
}
};
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Badge tone="neutral">{multiCollections.length} multi-collections</Badge>
<span className="ctv-channels-spacer" />
<Button onClick={() => setEditing({ kind: 'new' })} size="sm" startIcon={<Plus aria-hidden="true" size={14} />}>
New multi-collection
</Button>
</div>
<Card padded={false}>
{multiCollections.length === 0 ? (
<div className="ctv-collections-empty">No multi-collections yet.</div>
) : (
multiCollections.map((collection, index) => (
<div
className="ctv-settings-flush-row"
key={collection.id}
style={index === 0 ? { borderTop: 'none' } : undefined}
>
<Layers aria-hidden="true" color="var(--ctv-accent)" size={15} />
<button
className="ctv-settings-flush-row-main ctv-settings-flush-row-title ctv-collections-linkbtn"
onClick={() => setEditing({ item: collection, kind: 'edit' })}
type="button"
>
{collection.name}
</button>
<Badge tone="neutral">
{collection.items.length} item{collection.items.length === 1 ? '' : 's'}
</Badge>
<IconButton onClick={() => setDeleteTarget(collection)} size="sm" title="Delete" variant="ghost">
<Trash2 aria-hidden="true" size={14} />
</IconButton>
</div>
))
)}
</Card>
<ConfirmDialog
busy={deleteBusy}
confirmLabel="Delete"
message={
deleteTarget ? (
<>
<span>{`Delete "${deleteTarget.name ?? 'this multi-collection'}"? This cannot be undone.`}</span>
{deleteError && (
<span className="ctv-field-error" role="alert">
{deleteError}
</span>
)}
</>
) : (
''
)
}
onCancel={() => {
setDeleteTarget(null);
setDeleteError(null);
}}
onConfirm={() => void confirmDelete()}
open={deleteTarget !== null}
title="Delete multi-collection"
tone="danger"
/>
</div>
);
}
@@ -0,0 +1,228 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { RerunCollectionsScreen } from './RerunCollectionsScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
const rerunCollections = [
{
collectionType: 'Collection',
firstRunPlaybackOrder: 'Chronological',
id: 1,
name: 'Nightly Reruns',
rerunPlaybackOrder: 'Shuffle',
selectedId: 5,
selectedName: 'Favorites'
}
];
const manualCollections = [
{ collectionType: 'Collection', id: 5, name: 'Favorites', state: 'Normal', useCustomPlaybackOrder: false }
];
const multiCollections = [{ id: 8, items: [], name: 'Bundle' }];
interface MockOptions {
list?: unknown[];
onRequest?: (url: string, method: string, body: unknown) => Response | null;
}
function mockApi(options: MockOptions = {}) {
const list = options.list ?? rerunCollections;
return 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;
if (options.onRequest) {
const override = options.onRequest(url, method, body);
if (override) {
return Promise.resolve(override);
}
}
if (url.startsWith('/api/rerun-collections') && method === 'GET') {
return Promise.resolve(jsonResponse({ page: list, totalCount: list.length }));
}
if (url === '/api/collections' && method === 'GET') {
return Promise.resolve(jsonResponse(manualCollections));
}
if (url.startsWith('/api/multi-collections') && method === 'GET') {
return Promise.resolve(jsonResponse({ page: multiCollections, totalCount: multiCollections.length }));
}
if (url === '/api/smart-collections' && method === 'GET') {
return Promise.resolve(jsonResponse([]));
}
if (url.startsWith('/api/library/browse')) {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
}
describe('RerunCollectionsScreen', () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
window.localStorage.clear();
});
it('renders the rerun-collections list with type + selection badge', async () => {
mockApi();
render(<RerunCollectionsScreen />);
expect(await screen.findByText('Nightly Reruns')).toBeInTheDocument();
expect(screen.getByText(/Collection · Favorites/)).toBeInTheDocument();
});
it('creates a rerun collection with a Collection selection', async () => {
const fetchMock = mockApi({
list: [],
onRequest: (url, method) =>
url === '/api/rerun-collections' && method === 'POST' ? jsonResponse({ id: 3 }, 201) : null
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByRole('button', { name: 'New rerun collection' }));
// combobox order: [0] Collection Type, [1] selection picker, [2] First Run, [3] Rerun.
const picker = (await screen.findAllByRole('combobox'))[1];
await within(picker).findByText('Favorites');
fireEvent.change(picker, { target: { value: '5' } });
fireEvent.change(screen.getByPlaceholderText('Rerun collection name'), { target: { value: 'My Reruns' } });
fireEvent.click(screen.getByRole('button', { name: 'Add rerun collection' }));
await waitFor(() => {
const postCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/rerun-collections' && (init?.method ?? '').toUpperCase() === 'POST'
);
expect(postCall).toBeDefined();
expect(JSON.parse(String(postCall?.[1]?.body))).toEqual({
collectionType: 'Collection',
firstRunPlaybackOrder: 'Chronological',
name: 'My Reruns',
rerunPlaybackOrder: 'Chronological',
selectedId: 5
});
});
});
it('switching the collection type swaps the picker and playback-order options', async () => {
const fetchMock = mockApi({ list: [] });
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByRole('button', { name: 'New rerun collection' }));
const comboboxes = await screen.findAllByRole('combobox');
const typeSelect = comboboxes[0];
const firstRunSelect = comboboxes[2];
// Collection: Chronological / Random / Shuffle.
expect(within(firstRunSelect).getAllByRole('option').map((o) => o.textContent)).toEqual([
'Chronological',
'Random',
'Shuffle'
]);
fireEvent.change(typeSelect, { target: { value: 'MultiCollection' } });
// MultiCollection picker loads the multi-collections list.
await waitFor(() => {
expect(fetchMock.mock.calls.some(([u]) => u.toString().startsWith('/api/multi-collections'))).toBe(true);
});
// MultiCollection restricts both orders to Shuffle only.
const refreshed = await screen.findAllByRole('combobox');
expect(within(refreshed[2]).getAllByRole('option').map((o) => o.textContent)).toEqual(['Shuffle']);
// The picker now offers the multi-collection.
expect(await within(refreshed[1]).findByText('Bundle')).toBeInTheDocument();
});
it('preserves an out-of-set stored playback order on edit-load and re-saves it unchanged', async () => {
const outOfSet = [
{
collectionType: 'Artist',
firstRunPlaybackOrder: 'SeasonEpisode',
id: 9,
name: 'Odd Order Reruns',
rerunPlaybackOrder: 'SeasonEpisode',
selectedId: 42,
selectedName: 'Some Artist'
}
];
const fetchMock = mockApi({
list: outOfSet,
onRequest: (url, method) =>
url === '/api/rerun-collections/9' && method === 'PUT' ? jsonResponse({ id: 9 }, 200) : null
});
render(<RerunCollectionsScreen />);
fireEvent.click(await screen.findByText('Odd Order Reruns'));
// combobox order: [0] Collection Type, [1] selection picker, [2] First Run, [3] Rerun.
const comboboxes = await screen.findAllByRole('combobox');
const firstRunSelect = comboboxes[2];
const rerunSelect = comboboxes[3];
// Artist's normal order set (Chronological / Random / Shuffle) does not include
// SeasonEpisode, but the stored value must still be present and selected.
expect(within(firstRunSelect).getByText('Season, Episode')).toBeInTheDocument();
expect((firstRunSelect as HTMLSelectElement).value).toBe('SeasonEpisode');
expect(within(rerunSelect).getByText('Season, Episode')).toBeInTheDocument();
expect((rerunSelect as HTMLSelectElement).value).toBe('SeasonEpisode');
fireEvent.click(screen.getByRole('button', { name: 'Save rerun collection' }));
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/rerun-collections/9' && (init?.method ?? '').toUpperCase() === 'PUT'
);
expect(putCall).toBeDefined();
expect(JSON.parse(String(putCall?.[1]?.body))).toEqual({
collectionType: 'Artist',
firstRunPlaybackOrder: 'SeasonEpisode',
name: 'Odd Order Reruns',
rerunPlaybackOrder: 'SeasonEpisode',
selectedId: 42
});
});
});
it('confirms and DELETEs a rerun collection', async () => {
const fetchMock = mockApi();
render(<RerunCollectionsScreen />);
const row = (await screen.findByText('Nightly Reruns')).closest('.ctv-settings-flush-row') as HTMLElement;
fireEvent.click(within(row).getByRole('button', { name: 'Delete' }));
const dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }));
await waitFor(() => {
expect(
fetchMock.mock.calls.some(
([u, init]) => u === '/api/rerun-collections/1' && (init?.method ?? '').toUpperCase() === 'DELETE'
)
).toBe(true);
});
});
});
+524
View File
@@ -0,0 +1,524 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowLeft, Check, Plus, Repeat, Trash2, TriangleAlert } from 'lucide-react';
import { Badge, Button, Card, ConfirmDialog, IconButton, Input, Select, Spinner } from '../components';
import type { SelectOption } from '../components';
import {
createRerunCollection,
deleteRerunCollection,
getCollections,
getLibraryBrowseItems,
getMultiCollections,
getRerunCollections,
getSmartCollections,
messageFromRerunCollectionError,
updateRerunCollection,
type CreateRerunCollectionRequest,
type LibraryBrowseMediaType,
type RerunCollection
} from '../api';
type RerunCollectionType = CreateRerunCollectionRequest['collectionType'];
type PlaybackOrder = CreateRerunCollectionRequest['firstRunPlaybackOrder'];
interface PickerOption {
id: number;
name: string;
}
// The REST-supported selection types (RerunCollectionRequestMapping.IsSupportedSelectionType).
// Playlist / RerunFirstRun / RerunRerun / SearchQuery / Fake* are intentionally excluded.
// Each entry knows how to load its picker options; every media-item type maps to a
// LibraryBrowseMediaType that GetLibraryBrowseItemsHandler.MediaTypesFor actually supports.
const COLLECTION_TYPES: Array<{
browse?: LibraryBrowseMediaType;
label: string;
source: 'browse' | 'collection' | 'multi' | 'smart';
value: RerunCollectionType;
}> = [
{ label: 'Collection', source: 'collection', value: 'Collection' },
{ label: 'Multi Collection', source: 'multi', value: 'MultiCollection' },
{ label: 'Smart Collection', source: 'smart', value: 'SmartCollection' },
{ browse: 'TelevisionShow', label: 'Television Show', source: 'browse', value: 'TelevisionShow' },
{ browse: 'TelevisionSeason', label: 'Television Season', source: 'browse', value: 'TelevisionSeason' },
{ browse: 'Artist', label: 'Artist', source: 'browse', value: 'Artist' },
{ browse: 'Movie', label: 'Movie', source: 'browse', value: 'Movie' },
{ browse: 'Episode', label: 'Episode', source: 'browse', value: 'Episode' },
{ browse: 'MusicVideo', label: 'Music Video', source: 'browse', value: 'MusicVideo' },
{ browse: 'OtherVideo', label: 'Other Video', source: 'browse', value: 'OtherVideo' },
{ browse: 'Song', label: 'Song', source: 'browse', value: 'Song' },
{ browse: 'Image', label: 'Image', source: 'browse', value: 'Image' },
{ browse: 'RemoteStream', label: 'Remote Stream', source: 'browse', value: 'RemoteStream' }
];
const ORDER_LABELS: Record<string, string> = {
Chronological: 'Chronological',
Random: 'Random',
SeasonEpisode: 'Season, Episode',
Shuffle: 'Shuffle'
};
function orderOption(order: PlaybackOrder): SelectOption {
return { label: ORDER_LABELS[order] ?? order, value: order };
}
// Mirrors the type-conditional option sets in RerunCollectionEditor.razor.
function orderOptionsFor(type: RerunCollectionType): SelectOption[] {
switch (type) {
case 'MultiCollection':
return [orderOption('Shuffle')];
case 'Collection':
case 'SmartCollection':
return ['Chronological', 'Random', 'Shuffle'].map((order) => orderOption(order as PlaybackOrder));
case 'TelevisionShow':
return ['Chronological', 'SeasonEpisode', 'Random', 'Shuffle'].map((order) => orderOption(order as PlaybackOrder));
default:
return ['Chronological', 'Random', 'Shuffle'].map((order) => orderOption(order as PlaybackOrder));
}
}
function defaultOrderFor(type: RerunCollectionType): PlaybackOrder {
return type === 'MultiCollection' ? 'Shuffle' : 'Chronological';
}
// The REST API accepts any PlaybackOrder for any collectionType (the per-type restriction
// enforced by orderOptionsFor is only a UI convention), so a rerun collection created via the
// API can carry a stored order outside the type's normal set. On edit-load, union that value in
// rather than letting the Select coerce it away (which would silently change what gets saved).
function orderOptionsWithCurrent(type: RerunCollectionType, current: PlaybackOrder): SelectOption[] {
const options = orderOptionsFor(type);
return options.some((option) => option.value === current) ? options : [...options, orderOption(current)];
}
function loadPickerOptions(type: RerunCollectionType): Promise<PickerOption[]> {
const config = COLLECTION_TYPES.find((entry) => entry.value === type);
if (!config) {
return Promise.resolve([]);
}
switch (config.source) {
case 'collection':
return getCollections().then((list) => list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` })));
case 'multi':
return getMultiCollections({ pageSize: 1000 }).then((result) =>
(result.page ?? []).map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` }))
);
case 'smart':
return getSmartCollections().then((list) => list.map((entry) => ({ id: entry.id, name: entry.name ?? `#${entry.id}` })));
default:
return getLibraryBrowseItems({ mediaType: config.browse, pageSize: 500 }).then((result) =>
(result.page ?? []).map((item) => ({ id: item.mediaItemId ?? item.id, name: item.title ?? `#${item.id}` }))
);
}
}
/* ---------- data hook ---------- */
type ListState =
| { data: RerunCollection[]; error: null; status: 'success' }
| { data: null; error: string; status: 'error' }
| { data: null; error: null; status: 'loading' };
function useRerunCollectionsData() {
const [state, setState] = useState<ListState>({ data: null, error: null, status: 'loading' });
const activeRef = useRef(true);
useEffect(() => {
activeRef.current = true;
return () => {
activeRef.current = false;
};
}, []);
const load = useCallback(() => {
getRerunCollections({ pageSize: 1000 })
.then((result) => {
if (activeRef.current) {
setState({ data: result.page ?? [], error: null, status: 'success' });
}
})
.catch((error: unknown) => {
if (activeRef.current) {
setState({ data: null, error: messageFromRerunCollectionError(error), status: 'error' });
}
});
}, []);
useEffect(() => {
load();
}, [load]);
const refresh = useCallback(
(quiet = false) => {
if (!quiet) {
setState({ data: null, error: null, status: 'loading' });
}
load();
},
[load]
);
return { refresh, state };
}
/* ---------- editor ---------- */
interface Draft {
collectionType: RerunCollectionType;
firstRunPlaybackOrder: PlaybackOrder;
name: string;
rerunPlaybackOrder: PlaybackOrder;
selectedId: number | null;
selectedName: string;
}
function draftFromRerun(rerun: RerunCollection): Draft {
return {
collectionType: rerun.collectionType,
firstRunPlaybackOrder: rerun.firstRunPlaybackOrder,
name: rerun.name ?? '',
rerunPlaybackOrder: rerun.rerunPlaybackOrder,
selectedId: rerun.selectedId ?? null,
selectedName: rerun.selectedName ?? ''
};
}
function RerunCollectionEditor({
initial,
onBack,
onSaved
}: {
initial: RerunCollection | null;
onBack: () => void;
onSaved: () => void;
}) {
const [draft, setDraft] = useState<Draft>(() =>
initial
? draftFromRerun(initial)
: {
collectionType: 'Collection',
firstRunPlaybackOrder: 'Chronological',
name: '',
rerunPlaybackOrder: 'Chronological',
selectedId: null,
selectedName: ''
}
);
const [pickerItems, setPickerItems] = useState<PickerOption[]>([]);
const [pickerError, setPickerError] = useState<string | null>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const { collectionType } = draft;
// Load the picker list for the active type. Resets only in the async callbacks (never
// synchronously in the effect body) per spa-conventions §3.
useEffect(() => {
let active = true;
loadPickerOptions(collectionType)
.then((items) => {
if (active) {
setPickerItems(items);
setPickerError(null);
}
})
.catch((error: unknown) => {
if (active) {
setPickerItems([]);
setPickerError(messageFromRerunCollectionError(error, 'Unable to load picker items'));
}
});
return () => {
active = false;
};
}, [collectionType]);
const setCollectionType = (type: RerunCollectionType) => {
setDraft((current) => ({
...current,
collectionType: type,
firstRunPlaybackOrder: defaultOrderFor(type),
rerunPlaybackOrder: defaultOrderFor(type),
selectedId: null,
selectedName: ''
}));
};
const setSelected = (value: string) => {
const id = value === '' ? null : Number(value);
const match = pickerItems.find((item) => item.id === id);
setDraft((current) => ({ ...current, selectedId: id, selectedName: match?.name ?? current.selectedName }));
};
const activeConfig = COLLECTION_TYPES.find((entry) => entry.value === collectionType);
const trimmedName = draft.name.trim();
const validationError =
trimmedName.length === 0 ? 'Name is required' : draft.selectedId == null ? 'A selection is required' : null;
const save = async () => {
if (validationError || saving || draft.selectedId == null) {
return;
}
setSaving(true);
setSaveError(null);
try {
const body = {
collectionType: draft.collectionType,
firstRunPlaybackOrder: draft.firstRunPlaybackOrder,
name: trimmedName,
rerunPlaybackOrder: draft.rerunPlaybackOrder,
selectedId: draft.selectedId
};
if (initial) {
await updateRerunCollection(initial.id, body);
} else {
await createRerunCollection(body);
}
onSaved();
} catch (error) {
setSaveError(messageFromRerunCollectionError(error, 'Unable to save rerun collection'));
} finally {
setSaving(false);
}
};
// Ensure the currently-selected item is always an option even if it isn't in the fetched
// page (e.g. a large library where browse returned a different slice).
const selectedInList = draft.selectedId != null && pickerItems.some((item) => item.id === draft.selectedId);
const pickerOptions: SelectOption[] = [
{ label: 'Select…', value: '' },
...(draft.selectedId != null && !selectedInList
? [{ label: draft.selectedName || `#${draft.selectedId}`, value: String(draft.selectedId) }]
: []),
...pickerItems.map((item) => ({ label: item.name, value: String(item.id) }))
];
const firstRunOrderOptions = orderOptionsWithCurrent(collectionType, draft.firstRunPlaybackOrder);
const rerunOrderOptions = orderOptionsWithCurrent(collectionType, draft.rerunPlaybackOrder);
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Button onClick={onBack} size="sm" startIcon={<ArrowLeft aria-hidden="true" size={14} />} variant="ghost">
All rerun collections
</Button>
<span className="ctv-collections-detail-title">
{initial ? 'Edit rerun collection' : 'New rerun collection'}
</span>
<span className="ctv-channels-spacer" />
{saveError && <span className="ctv-settings-savebar-error">{saveError}</span>}
{validationError && <Badge tone="neutral">{validationError}</Badge>}
<Button
disabled={validationError !== null || saving}
loading={saving}
onClick={() => void save()}
size="sm"
startIcon={<Check aria-hidden="true" size={14} />}
>
{initial ? 'Save rerun collection' : 'Add rerun collection'}
</Button>
</div>
<Card title="Rerun collection">
<Input
label="Name"
onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))}
placeholder="Rerun collection name"
value={draft.name}
/>
<div style={{ marginTop: 16 }}>
<Select
label="Collection Type"
onChange={(event) => setCollectionType(event.target.value as RerunCollectionType)}
options={COLLECTION_TYPES.map((entry) => ({ label: entry.label, value: entry.value }))}
value={draft.collectionType}
/>
</div>
<div style={{ marginTop: 12 }}>
<Select
label={activeConfig?.label ?? 'Selection'}
onChange={(event) => setSelected(event.target.value)}
options={pickerOptions}
value={draft.selectedId == null ? '' : String(draft.selectedId)}
/>
{pickerError && (
<span className="ctv-field-error" role="alert">
{pickerError}
</span>
)}
</div>
<div style={{ marginTop: 12 }}>
<Select
label="First Run Playback Order"
onChange={(event) =>
setDraft((current) => ({ ...current, firstRunPlaybackOrder: event.target.value as PlaybackOrder }))
}
options={firstRunOrderOptions}
value={draft.firstRunPlaybackOrder}
/>
</div>
<div style={{ marginTop: 12 }}>
<Select
label="Rerun Playback Order"
onChange={(event) =>
setDraft((current) => ({ ...current, rerunPlaybackOrder: event.target.value as PlaybackOrder }))
}
options={rerunOrderOptions}
value={draft.rerunPlaybackOrder}
/>
</div>
</Card>
</div>
);
}
/* ---------- screen ---------- */
export function RerunCollectionsScreen() {
const { refresh, state } = useRerunCollectionsData();
const [editing, setEditing] = useState<{ kind: 'new' } | { kind: 'edit'; item: RerunCollection } | null>(null);
const [deleteTarget, setDeleteTarget] = useState<RerunCollection | null>(null);
const [deleteBusy, setDeleteBusy] = useState(false);
const [deleteError, setDeleteError] = useState<string | null>(null);
if (editing) {
return (
<RerunCollectionEditor
initial={editing.kind === 'edit' ? editing.item : null}
onBack={() => setEditing(null)}
onSaved={() => {
setEditing(null);
refresh(true);
}}
/>
);
}
if (state.status === 'loading') {
return (
<div className="ctv-collections-loading" role="status">
<Spinner size={18} />
<span>Loading rerun collections…</span>
</div>
);
}
if (state.status === 'error') {
return (
<div className="ctv-collections">
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{state.error}</span>
<span className="ctv-channels-spacer" />
<Button onClick={() => refresh()} size="sm" variant="secondary">
Retry
</Button>
</div>
</div>
);
}
const rerunCollections = [...state.data].sort((a, b) =>
(a.name ?? '').localeCompare(b.name ?? '', undefined, { sensitivity: 'base' })
);
const typeLabel = (type: RerunCollectionType) => COLLECTION_TYPES.find((entry) => entry.value === type)?.label ?? type;
const confirmDelete = async () => {
if (!deleteTarget) {
return;
}
setDeleteBusy(true);
setDeleteError(null);
try {
await deleteRerunCollection(deleteTarget.id);
setDeleteTarget(null);
refresh(true);
} catch (error) {
setDeleteError(messageFromRerunCollectionError(error, 'Unable to delete rerun collection'));
} finally {
setDeleteBusy(false);
}
};
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Badge tone="neutral">{rerunCollections.length} rerun collections</Badge>
<span className="ctv-channels-spacer" />
<Button onClick={() => setEditing({ kind: 'new' })} size="sm" startIcon={<Plus aria-hidden="true" size={14} />}>
New rerun collection
</Button>
</div>
<Card padded={false}>
{rerunCollections.length === 0 ? (
<div className="ctv-collections-empty">No rerun collections yet.</div>
) : (
rerunCollections.map((collection, index) => (
<div
className="ctv-settings-flush-row"
key={collection.id}
style={index === 0 ? { borderTop: 'none' } : undefined}
>
<Repeat aria-hidden="true" color="var(--ctv-accent)" size={15} />
<button
className="ctv-settings-flush-row-main ctv-settings-flush-row-title ctv-collections-linkbtn"
onClick={() => setEditing({ item: collection, kind: 'edit' })}
type="button"
>
{collection.name}
</button>
<Badge tone="neutral">
{typeLabel(collection.collectionType)}
{collection.selectedName ? ` · ${collection.selectedName}` : ''}
</Badge>
<IconButton onClick={() => setDeleteTarget(collection)} size="sm" title="Delete" variant="ghost">
<Trash2 aria-hidden="true" size={14} />
</IconButton>
</div>
))
)}
</Card>
<ConfirmDialog
busy={deleteBusy}
confirmLabel="Delete"
message={
deleteTarget ? (
<>
<span>{`Delete "${deleteTarget.name ?? 'this rerun collection'}"? This cannot be undone.`}</span>
{deleteError && (
<span className="ctv-field-error" role="alert">
{deleteError}
</span>
)}
</>
) : (
''
)
}
onCancel={() => {
setDeleteTarget(null);
setDeleteError(null);
}}
onConfirm={() => void confirmDelete()}
open={deleteTarget !== null}
title="Delete rerun collection"
tone="danger"
/>
</div>
);
}