fix(web): scope library/add-item pickers to their 4 media kinds (#168 review)
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 4m33s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m46s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped

GET /api/library/browse without mediaType now spans all 10 media kinds
(was 4: Movie/TelevisionShow/TelevisionSeason/Artist), which flooded two
pickers with episodes/songs/etc. mixed in with the intended top-level
items. Fan both consumers out per-kind and merge, restoring pre-#168
scoping without touching the API:

- ChannelBuilder's library browse tab now fans out Movie/TelevisionShow/
  TelevisionSeason/Artist per page (mirrors the existing loadCollections
  pattern) and sums per-kind totalCount so paging/load-more still works.
- CollectionsScreen's add-items search now fans out over the same 4
  addable kinds instead of filtering one unscoped page client-side.

Extended App.test.tsx and CollectionsScreen.test.tsx to assert the
per-kind requests and updated a few fixtures that relied on the old
unscoped browse call returning collection-kind items under the library
tab.
This commit is contained in:
2026-07-07 16:06:50 +02:00
parent 7083301ce6
commit 72b6d0a76a
4 changed files with 143 additions and 22 deletions
+34 -6
View File
@@ -2088,11 +2088,14 @@ describe('ChicoryTV SPA scaffold', () => {
...builderDefaults(),
browseHandler: (search) => {
const query = (search.get('query') ?? '').toLowerCase();
const mediaType = search.get('mediaType');
const all = [
browseItem(),
browseItem({ id: 2, mediaItemId: 2, mediaType: 'Movie', collectionType: 'Movie', title: 'Blade Runner', libraryName: 'Movies' })
];
const page = query ? all.filter((item) => String(item.title).toLowerCase().includes(query)) : all;
const page = all
.filter((item) => !mediaType || item.mediaType === mediaType)
.filter((item) => !query || String(item.title).toLowerCase().includes(query));
return { page, totalCount: page.length };
}
});
@@ -2210,7 +2213,11 @@ describe('ChicoryTV SPA scaffold', () => {
await renderBuilder();
fireEvent.doubleClick(await screen.findByText('Looney Tunes'));
fireEvent.doubleClick(screen.getByText('Saturday Block'));
// RerunCollection is a collections kind, not one of the 4 library kinds —
// find it under the Collections tab.
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
fireEvent.doubleClick(await screen.findByText('Saturday Block'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Mixed' } });
expect(await screen.findByText('Only valid alone')).toBeInTheDocument();
@@ -2227,6 +2234,9 @@ describe('ChicoryTV SPA scaffold', () => {
const { container } = await renderBuilder();
// MultiCollection is a collections kind, not one of the 4 library kinds —
// find it under the Collections tab.
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
fireEvent.doubleClick(await screen.findByText('Prime Time'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Multi' } });
@@ -2386,6 +2396,10 @@ describe('ChicoryTV SPA scaffold', () => {
const { container } = await renderBuilder();
// The initial render already fanned out over the 4 library kinds; only
// count requests made after switching to the Collections tab.
vi.mocked(window.fetch).mockClear();
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
expect(await screen.findByText('Action Movies')).toBeInTheDocument();
@@ -2412,6 +2426,12 @@ describe('ChicoryTV SPA scaffold', () => {
mockDashboardApi({
...builderDefaults(),
browseHandler: (search) => {
// The builder fans out per-kind (Movie/TelevisionShow/TelevisionSeason/Artist);
// only return real pages for the kind these fixtures use (TelevisionShow) so
// the other 3 kinds don't duplicate the same items.
if (search.get('mediaType') !== 'TelevisionShow') {
return { page: [], totalCount: 0 };
}
const pageNum = Number(search.get('pageNum') ?? '0');
return { page: pages[pageNum] ?? [], totalCount: 3 };
}
@@ -2538,6 +2558,9 @@ describe('ChicoryTV SPA scaffold', () => {
await renderBuilder();
// Collection is a collections kind, not one of the 4 library kinds —
// find it under the Collections tab.
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
fireEvent.doubleClick(await screen.findByText('Saturday Cartoons'));
fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Marathon' } });
@@ -3461,10 +3484,15 @@ function mockDashboardApi({
if (path.startsWith('/api/library/browse')) {
const search = new URL(path, window.location.origin).searchParams;
const result = browseHandler
? browseHandler(search)
: { page: browseItems, totalCount: browseItems.length };
return Promise.resolve(jsonResponse(result));
if (browseHandler) {
return Promise.resolve(jsonResponse(browseHandler(search)));
}
// Mirror the real API: an unfiltered request returns everything, a
// mediaType-scoped request (the builder now fans out per-kind) only
// returns items of that kind.
const mediaType = search.get('mediaType');
const page = mediaType ? browseItems.filter((item) => (item as { mediaType?: string }).mediaType === mediaType) : browseItems;
return Promise.resolve(jsonResponse({ page, totalCount: page.length }));
}
if (path === '/api/channel-templates') {
+41 -8
View File
@@ -140,6 +140,17 @@ const COLLECTION_MEDIA_TYPES: LibraryBrowseMediaType[] = [
'Playlist'
];
// The pre-#168 API default: browsing a library shows the "pickable" top-level
// kinds only (shows/seasons/movies/artists), not every episode/song/etc.
// nested underneath them. Kept explicit here since `GET /api/library/browse`
// now spans all 10 media kinds when `mediaType` is omitted.
const LIBRARY_MEDIA_TYPES: LibraryBrowseMediaType[] = [
'Movie',
'TelevisionShow',
'TelevisionSeason',
'Artist'
];
// ---- Small pure helpers ----------------------------------------------------
const mono: CSSProperties = { fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' };
@@ -411,6 +422,35 @@ async function loadCollections(query: string): Promise<{ page: LibraryBrowseItem
return { page: merged, totalCount: merged.length };
}
// Fan out across the four pickable library kinds (movies/shows/seasons/artists)
// instead of the unscoped browse, which now also returns episodes/songs/etc.
// Mirrors loadCollections's per-kind Promise.all pattern, but preserves real
// paging (each kind keeps its own pageNum/totalCount, summed across kinds) so
// canLoadMore stays meaningful for large libraries.
async function loadLibraryItems(
query: string,
libraryId: number | null,
pageNum: number,
pageSize: number
): Promise<{ page: LibraryBrowseItem[]; totalCount: number }> {
const results = await Promise.all(
LIBRARY_MEDIA_TYPES.map((mediaType) =>
getLibraryBrowseItems({
query: query || undefined,
libraryId: libraryId ?? undefined,
mediaType,
pageNum,
pageSize
})
)
);
const merged = results
.flatMap((result) => result.page)
.sort((left, right) => left.title.localeCompare(right.title, undefined, { sensitivity: 'base' }));
const totalCount = results.reduce((sum, result) => sum + result.totalCount, 0);
return { page: merged, totalCount };
}
function useLibraryBrowse(source: 'library' | 'collections', query: string, libraryId: number | null) {
const [state, setState] = useState<BrowseState>({ status: 'loading', items: [], totalCount: 0, error: null });
const [loadingMore, setLoadingMore] = useState(false);
@@ -420,14 +460,7 @@ function useLibraryBrowse(source: 'library' | 'collections', query: string, libr
const runFetch = useCallback(
(pageNum: number, reqId: number, append: boolean) => {
const promise =
source === 'collections'
? loadCollections(query)
: getLibraryBrowseItems({
query: query || undefined,
libraryId: libraryId ?? undefined,
pageNum,
pageSize: 100
});
source === 'collections' ? loadCollections(query) : loadLibraryItems(query, libraryId, pageNum, 100);
promise
.then((result) => {
@@ -265,4 +265,61 @@ describe('CollectionsScreen', () => {
);
expect(new URL(String(browseCall?.[0]), 'http://localhost').searchParams.get('query')).toBe('collection:"Favorites"');
});
it('fans the add-items search out over the 4 addable kinds and merges the results', async () => {
const byType: 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' }
};
const fetchMock = 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 ? byType[mediaType] : undefined;
return jsonResponse(item ? { page: [item], totalCount: 1 } : { page: [], totalCount: 0 });
}
return null;
}
});
render(<CollectionsScreen />);
await screen.findByText('Favorites');
fireEvent.click(screen.getByText('Favorites'));
await screen.findByText(/best-effort search preview/);
fireEvent.click(screen.getByRole('button', { name: 'Add items' }));
const dialog = screen.getByRole('dialog');
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('Melon Season 1')).toBeInTheDocument();
expect(within(dialog).getByText('Between Movie and Show')).toBeInTheDocument();
const browseTypes = 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);
expect(new Set(browseTypes)).toEqual(new Set(['Movie', 'TelevisionShow', 'TelevisionSeason', 'Artist']));
});
});
+11 -8
View File
@@ -46,12 +46,8 @@ import { TYPE_LABEL } from '../media/mediaKinds';
type Tab = 'manual' | 'smart';
const ADDABLE_TYPES = new Set<LibraryBrowseItem['mediaType']>([
'Movie',
'TelevisionShow',
'TelevisionSeason',
'Artist'
]);
const ADDABLE_TYPE_LIST: LibraryBrowseItem['mediaType'][] = ['Movie', 'TelevisionShow', 'TelevisionSeason', 'Artist'];
const ADDABLE_TYPES = new Set<LibraryBrowseItem['mediaType']>(ADDABLE_TYPE_LIST);
function sortByName<T extends { name?: null | string }>(items: T[]): T[] {
return [...items].sort((left, right) => (left.name ?? '').localeCompare(right.name ?? ''));
@@ -311,8 +307,15 @@ function AddItemsDialog({
setError(null);
try {
const result = await getLibraryBrowseItems({ pageSize: 50, query: query.trim() });
setResults((result.page ?? []).filter((item) => ADDABLE_TYPES.has(item.mediaType)));
const trimmed = query.trim();
const perKind = await Promise.all(
ADDABLE_TYPE_LIST.map((mediaType) => getLibraryBrowseItems({ pageSize: 50, query: trimmed, mediaType }))
);
const merged = perKind
.flatMap((result) => result.page ?? [])
.filter((item) => ADDABLE_TYPES.has(item.mediaType))
.sort((left, right) => left.title.localeCompare(right.title, undefined, { sensitivity: 'base' }));
setResults(merged.slice(0, 50));
} catch (searchError) {
setError(messageFromCollectionError(searchError, 'Unable to search library'));
} finally {