Files
ersatztv/web/src/screens/CollectionsScreen.test.tsx
T
timothy 606d50bb8d feat(spa): collection custom-order reorder UI + all-kind add picker (#211)
Adds PUT /api/collections/{id}/custom-order support (updateCollectionCustomOrder)
and a reorder mode in ManualItemsView: loads every page of a manual collection
(so the wholesale-replace PUT never drops items), lets the user move items with
up/down icon buttons, and saves/cancels. Reorder is offered for any manual
collection with useCustomPlaybackOrder on, not just movies-only (server/enumerator
already support any kind).

Widens the add-items picker (ADDABLE_TYPE_LIST, MEDIA_KIND_FILTERS,
toAddItemsRequest) from 4 to all 10 addable media kinds; the default "All" search
fan-out stays Movie/Show/Artist (seasons excluded per #180), with the new kinds
reachable via their specific filter, mirroring Blazor's per-kind list pages.
2026-07-09 22:35:43 +02:00

505 lines
19 KiB
TypeScript

import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CollectionsScreen } from './CollectionsScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
const manualCollections = [
{ collectionType: 'Collection', id: 1, name: 'Favorites', state: 'Normal', useCustomPlaybackOrder: false },
{ collectionType: 'Collection', id: 2, name: 'Kids', state: 'Normal', useCustomPlaybackOrder: true }
];
const smartCollections = [{ id: 10, name: 'Action', query: 'genre:action' }];
interface MockOptions {
manual?: unknown[];
smart?: unknown[];
onRequest?: (url: string, method: string, body: unknown) => Response | null;
}
function mockApi(options: MockOptions = {}) {
const manual = options.manual ?? manualCollections;
const smart = options.smart ?? smartCollections;
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 === '/api/collections' && method === 'GET') {
return Promise.resolve(jsonResponse(manual));
}
if (url === '/api/smart-collections' && method === 'GET') {
return Promise.resolve(jsonResponse(smart));
}
if (url.startsWith('/api/library/browse')) {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
if (/^\/api\/collections\/\d+\/items/.test(url) && method === 'GET') {
return Promise.resolve(jsonResponse({ page: [], totalCount: 0 }));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
}
describe('CollectionsScreen', () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
window.localStorage.clear();
});
it('renders both manual and smart collections', async () => {
mockApi();
render(<CollectionsScreen />);
expect(await screen.findByText('Favorites')).toBeInTheDocument();
expect(screen.getByText('Kids')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Smart/ }));
expect(await screen.findByText('Action')).toBeInTheDocument();
expect(screen.getByText('genre:action')).toBeInTheDocument();
});
it('shows an error state when loading fails', async () => {
mockApi({
onRequest: (url) => (url === '/api/collections' ? jsonResponse({ status: 500, title: 'Boom' }, 500) : null)
});
render(<CollectionsScreen />);
expect(await screen.findByText('Boom')).toBeInTheDocument();
});
it('creates a manual collection via POST', async () => {
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/collections' && method === 'POST'
? jsonResponse({ collectionType: 'Collection', id: 3, name: 'New One', state: 'Normal', useCustomPlaybackOrder: false }, 201)
: null
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByRole('button', { name: 'New collection' }));
const dialog = screen.getByRole('dialog');
fireEvent.change(within(dialog).getByPlaceholderText('Collection name'), { target: { value: 'New One' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));
await waitFor(() => {
expect(
fetchMock.mock.calls.some(
([u, init]) => u === '/api/collections' && (init?.method ?? '').toUpperCase() === 'POST'
)
).toBe(true);
});
const postCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections' && (init?.method ?? '').toUpperCase() === 'POST'
);
expect(JSON.parse(String(postCall?.[1]?.body))).toEqual({ name: 'New One' });
});
it('renames a manual collection via PUT', async () => {
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/collections/1' && method === 'PUT'
? jsonResponse({ collectionType: 'Collection', id: 1, name: 'Renamed', state: 'Normal', useCustomPlaybackOrder: false })
: null
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getAllByRole('button', { name: 'Rename' })[0]);
const dialog = screen.getByRole('dialog');
const input = within(dialog).getByPlaceholderText('Collection name') as HTMLInputElement;
expect(input.value).toBe('Favorites');
fireEvent.change(input, { target: { value: 'Renamed' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Save' }));
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections/1' && (init?.method ?? '').toUpperCase() === 'PUT'
);
expect(putCall).toBeDefined();
expect(JSON.parse(String(putCall?.[1]?.body))).toMatchObject({ name: 'Renamed' });
});
});
it('toggles custom playback order via PUT', async () => {
const fetchMock = mockApi({
onRequest: (url, method) =>
url === '/api/collections/1' && method === 'PUT'
? jsonResponse({ collectionType: 'Collection', id: 1, name: 'Favorites', state: 'Normal', useCustomPlaybackOrder: true })
: null
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
// First switch in the list belongs to "Favorites".
const switches = screen.getAllByRole('switch');
fireEvent.click(switches[0]);
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections/1' && (init?.method ?? '').toUpperCase() === 'PUT'
);
expect(putCall).toBeDefined();
expect(JSON.parse(String(putCall?.[1]?.body))).toMatchObject({ useCustomPlaybackOrder: true });
});
});
it('confirms and DELETEs a manual collection', async () => {
const fetchMock = mockApi();
render(<CollectionsScreen />);
await screen.findByText('Favorites');
const rows = screen.getAllByRole('button', { name: 'Delete' });
fireEvent.click(rows[0]);
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText(/Delete "Favorites"/)).toBeInTheDocument();
fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }));
await waitFor(() => {
expect(
fetchMock.mock.calls.some(
([u, init]) => u === '/api/collections/1' && (init?.method ?? '').toUpperCase() === 'DELETE'
)
).toBe(true);
});
});
it('creates a smart collection and previews the query against browse', async () => {
const fetchMock = mockApi({
onRequest: (url, method) => {
if (url.startsWith('/api/library/browse')) {
return jsonResponse({ page: [{ id: 1, mediaType: 'Movie', title: 'The Matrix' }], totalCount: 1 });
}
if (url === '/api/smart-collections' && method === 'POST') {
return jsonResponse({ id: 11, name: 'Sci-Fi', query: 'genre:scifi' }, 201);
}
return null;
}
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByRole('button', { name: /Smart/ }));
fireEvent.click(screen.getByRole('button', { name: 'New smart collection' }));
const dialog = screen.getByRole('dialog');
fireEvent.change(within(dialog).getByPlaceholderText('Smart collection name'), { target: { value: 'Sci-Fi' } });
fireEvent.change(within(dialog).getByPlaceholderText(/genre/), { target: { value: 'genre:scifi' } });
fireEvent.click(within(dialog).getByRole('button', { name: 'Preview results' }));
expect(await within(dialog).findByText('The Matrix')).toBeInTheDocument();
expect(within(dialog).getByText('1 matches')).toBeInTheDocument();
const browseCall = fetchMock.mock.calls.find(([u]) => u.toString().startsWith('/api/library/browse'));
expect(new URL(String(browseCall?.[0]), 'http://localhost').searchParams.get('query')).toBe('genre:scifi');
fireEvent.click(within(dialog).getByRole('button', { name: 'Create' }));
await waitFor(() => {
const postCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/smart-collections' && (init?.method ?? '').toUpperCase() === 'POST'
);
expect(postCall).toBeDefined();
expect(JSON.parse(String(postCall?.[1]?.body))).toEqual({ name: 'Sci-Fi', query: 'genre:scifi' });
});
});
it('opens a manual collection and lists its items via the collection-items endpoint', async () => {
const fetchMock = mockApi({
onRequest: (url, method) => {
if (/^\/api\/collections\/1\/items/.test(url) && method === 'GET') {
return jsonResponse({
page: [{ id: 5, mediaItemId: 5, mediaType: 'Movie', title: 'Inception' }],
totalCount: 1
});
}
return null;
}
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByText('Favorites'));
expect(await screen.findByText('Inception')).toBeInTheDocument();
// The lossy best-effort search-preview banner is gone now that a real endpoint exists.
expect(screen.queryByText(/best-effort search preview/)).not.toBeInTheDocument();
const itemsCall = fetchMock.mock.calls.find(([u]) => /\/api\/collections\/1\/items/.test(u.toString()));
expect(itemsCall).toBeDefined();
const itemsUrl = new URL(String(itemsCall?.[0]), 'http://localhost');
expect(itemsUrl.pathname).toBe('/api/collections/1/items');
expect(itemsUrl.searchParams.get('pageNum')).toBe('0');
expect(itemsUrl.searchParams.get('pageSize')).toBe('100');
});
const addItemsByType: Record<string, { id: number; mediaType: string; title: string }> = {
Movie: { id: 1, mediaType: 'Movie', title: 'Zathura' },
TelevisionShow: { id: 2, mediaType: 'TelevisionShow', title: 'Adventure Time' },
TelevisionSeason: { id: 3, mediaType: 'TelevisionSeason', title: 'Melon Season 1' },
Artist: { id: 4, mediaType: 'Artist', title: 'Between Movie and Show' },
Episode: { id: 5, mediaType: 'Episode', title: 'The Pilot Episode' },
MusicVideo: { id: 6, mediaType: 'MusicVideo', title: 'Music Video Reel' },
Song: { id: 7, mediaType: 'Song', title: 'Song of the Sea' },
OtherVideo: { id: 8, mediaType: 'OtherVideo', title: 'Home Video Clip' },
Image: { id: 9, mediaType: 'Image', title: 'Poster Art' },
RemoteStream: { id: 10, mediaType: 'RemoteStream', title: 'Live Feed' }
};
function mockAddItemsApi() {
return mockApi({
onRequest: (url) => {
if (url.startsWith('/api/library/browse')) {
const params = new URL(url, 'http://localhost').searchParams;
const query = params.get('query') ?? '';
// The manual-collection preview query (collection:"Favorites") should not
// reach the add-items search path.
if (query.startsWith('collection:')) {
return jsonResponse({ page: [], totalCount: 0 });
}
const mediaType = params.get('mediaType');
const item = mediaType ? addItemsByType[mediaType] : undefined;
return jsonResponse(item ? { page: [item], totalCount: 1 } : { page: [], totalCount: 0 });
}
return null;
}
});
}
async function openAddItemsDialog() {
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByText('Favorites'));
await screen.findByRole('button', { name: 'Add items' });
fireEvent.click(screen.getByRole('button', { name: 'Add items' }));
return screen.getByRole('dialog');
}
function addItemsBrowseTypes(fetchMock: ReturnType<typeof mockApi>): string[] {
return fetchMock.mock.calls
.map(([u]) => u.toString())
.filter((u) => u.startsWith('/api/library/browse'))
.map((u) => new URL(u, 'http://localhost').searchParams.get('mediaType'))
.filter((mediaType): mediaType is string => mediaType != null && mediaType !== '');
}
it('default add-items search excludes seasons and fans out over movies/shows/artists', async () => {
const fetchMock = mockAddItemsApi();
const dialog = await openAddItemsDialog();
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: 'a' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Search' }));
expect(await within(dialog).findByText('Adventure Time')).toBeInTheDocument();
expect(within(dialog).getByText('Zathura')).toBeInTheDocument();
expect(within(dialog).getByText('Between Movie and Show')).toBeInTheDocument();
// Seasons are excluded from the default fan-out (issue #180).
expect(within(dialog).queryByText('Melon Season 1')).not.toBeInTheDocument();
expect(new Set(addItemsBrowseTypes(fetchMock))).toEqual(new Set(['Movie', 'TelevisionShow', 'Artist']));
});
it('selecting the Seasons filter searches TelevisionSeason and surfaces seasons', async () => {
const fetchMock = mockAddItemsApi();
const dialog = await openAddItemsDialog();
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: 'a' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Seasons' }));
expect(await within(dialog).findByText('Melon Season 1')).toBeInTheDocument();
// The explicit filter narrows the fan-out to seasons only.
expect(within(dialog).queryByText('Zathura')).not.toBeInTheDocument();
const seasonCall = fetchMock.mock.calls
.map(([u]) => u.toString())
.filter((u) => u.startsWith('/api/library/browse'))
.some((u) => new URL(u, 'http://localhost').searchParams.get('mediaType') === 'TelevisionSeason');
expect(seasonCall).toBe(true);
});
it('the picker note explains the "All" fan-out and the reachable extra kinds (#211)', async () => {
mockAddItemsApi();
const dialog = await openAddItemsDialog();
expect(
within(dialog).getByText(
/searches movies, shows and artists; pick a specific kind to add seasons, episodes, music videos, songs, other videos, images or remote streams\./
)
).toBeInTheDocument();
});
it('selecting a newly-addable kind filter (Song) surfaces it and buckets it correctly on add', async () => {
const fetchMock = mockAddItemsApi();
const dialog = await openAddItemsDialog();
fireEvent.change(within(dialog).getByPlaceholderText('Search movies, shows, seasons, artists…'), {
target: { value: 'a' }
});
fireEvent.click(within(dialog).getByRole('button', { name: 'Song' }));
expect(await within(dialog).findByText('Song of the Sea')).toBeInTheDocument();
const songCall = fetchMock.mock.calls
.map(([u]) => u.toString())
.filter((u) => u.startsWith('/api/library/browse'))
.some((u) => new URL(u, 'http://localhost').searchParams.get('mediaType') === 'Song');
expect(songCall).toBe(true);
fireEvent.click(within(dialog).getByText('Song of the Sea'));
fireEvent.click(within(dialog).getByRole('button', { name: /Add 1 item/ }));
await waitFor(() => {
const addCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections/1/items' && (init?.method ?? '').toUpperCase() === 'POST'
);
expect(addCall).toBeDefined();
expect(JSON.parse(String(addCall?.[1]?.body)).songIds).toEqual([7]);
});
});
/* ---------- reorder mode (#211) ---------- */
function reorderPages(id: number) {
return {
[`/api/collections/${id}/items:0`]: {
page: [
{ id: 100, mediaItemId: 100, mediaType: 'Movie', title: 'Alpha' },
{ id: 200, mediaItemId: 200, mediaType: 'Movie', title: 'Bravo' }
],
totalCount: 3
},
[`/api/collections/${id}/items:1`]: {
page: [{ id: 300, mediaItemId: 300, mediaType: 'Movie', title: 'Charlie' }],
totalCount: 3
}
};
}
function mockReorderApi() {
const pages = reorderPages(2);
return mockApi({
onRequest: (url, method) => {
if (/^\/api\/collections\/2\/items/.test(url) && method === 'GET') {
const pageNum = new URL(url, 'http://localhost').searchParams.get('pageNum') ?? '0';
const key = `/api/collections/2/items:${pageNum}`;
return jsonResponse(pages[key] ?? { page: [], totalCount: 0 });
}
return null;
}
});
}
it('reorder mode loads every page, supports moving items, and saves the full ordered array', async () => {
const fetchMock = mockReorderApi();
render(<CollectionsScreen />);
await screen.findByText('Kids');
fireEvent.click(screen.getByText('Kids'));
expect(await screen.findByText('Alpha')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Reorder' }));
// Reorder mode fetches every page (0 then 1) before entering, so all three items render.
expect(await screen.findByRole('button', { name: 'Save order' })).toBeInTheDocument();
expect(screen.getByText('Charlie')).toBeInTheDocument();
const itemsCallCount = () =>
fetchMock.mock.calls.filter(([u]) => /^\/api\/collections\/2\/items/.test(u.toString())).length;
// Initial load (page 0) + enterReorder's page 0 + page 1 = 3 GETs minimum.
expect(itemsCallCount()).toBeGreaterThanOrEqual(3);
// Add/remove actions are disabled while reordering.
expect(screen.getByRole('button', { name: 'Add items' })).toBeDisabled();
// Move "Bravo" (index 1) down, so the order becomes Alpha, Charlie, Bravo.
fireEvent.click(screen.getByRole('button', { name: 'Move Bravo down' }));
fireEvent.click(screen.getByRole('button', { name: 'Save order' }));
await waitFor(() => {
const putCall = fetchMock.mock.calls.find(
([u, init]) => u === '/api/collections/2/custom-order' && (init?.method ?? '').toUpperCase() === 'PUT'
);
expect(putCall).toBeDefined();
expect(JSON.parse(String(putCall?.[1]?.body))).toEqual({ mediaItemIds: [100, 300, 200] });
});
// Exits reorder mode and refreshes the normal paged view.
await waitFor(() => {
expect(screen.queryByRole('button', { name: 'Save order' })).not.toBeInTheDocument();
});
expect(screen.getByRole('button', { name: 'Add items' })).not.toBeDisabled();
});
it('canceling reorder mode discards local moves without saving', async () => {
const fetchMock = mockReorderApi();
render(<CollectionsScreen />);
await screen.findByText('Kids');
fireEvent.click(screen.getByText('Kids'));
await screen.findByText('Alpha');
fireEvent.click(screen.getByRole('button', { name: 'Reorder' }));
await screen.findByRole('button', { name: 'Save order' });
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(screen.queryByRole('button', { name: 'Save order' })).not.toBeInTheDocument();
expect(
fetchMock.mock.calls.some(([u]) => u === '/api/collections/2/custom-order')
).toBe(false);
});
});