Merge branch 'feat/213-nits' into feat/210-211-playouts-collections

This commit is contained in:
2026-07-09 22:40:42 +02:00
8 changed files with 409 additions and 14 deletions
+37
View File
@@ -143,3 +143,40 @@ so the spec matches the wire format by construction. A contract test
the spec property sets to them. Decision: **the wire format is the source of truth; the spec follows it via the
real contract resolver.** This also fixed a latent SPA bug (the channel-list "FFmpeg profile" column read
`fFmpegProfile` and always showed "Unassigned"). Issue #198.
## 2026-07-09 — YAML playout validator: paste-textarea instead of a server file path
The legacy Blazor YAML playout validator took a **server-side file path** (read directly off the
container's filesystem). The SPA's `YamlValidatorScreen.tsx` instead uses a paste `<textarea>` — a
deliberate deviation, not an oversight. The SPA runs entirely client-side against `/api/*` and has
no access to the server's filesystem, so a file-path field would either need a new
filesystem-browsing endpoint or silently fail; pasting the YAML directly is simpler and matches how
every other SPA editor already round-trips content through the API instead of the disk.
## 2026-07-09 — Channel numbers: prompt-driven sequential renumber instead of drag-to-reorder
The legacy Blazor channel list let you drag-and-drop rows to reorder channel numbers. The SPA
(`App.tsx`) instead offers a "Renumber" action that walks the list and asks for each channel's new
number via a sequence of native `prompt()` calls. Deliberate deviation: drag-to-reorder needs a
dedicated drag library and a bespoke reorder-persistence endpoint; a sequential prompt reuses the
existing per-channel update call and needs no new UI dependency. Revisit only if channel counts grow
large enough that prompt-per-channel becomes tedious.
## 2026-07-09 — "Table, not calendar" convention also covers the deco-templates editor
Extends the 2026-07 "Templates editor in the SPA is a table, not Blazor's drag-calendar" entry
above (not editing that entry — this generalizes it): the deco-templates editor
(`DecoTemplatesScreen.tsx`) follows the same convention, rendering its day/deco assignment as a
table rather than reproducing Blazor's drag-and-drop calendar grid. Same rationale, same
accepted-deviation status — don't "fix" either editor to match Blazor's interaction model without
discussing it first.
## 2026-07-09 — Trash "see all" is capped at 100 items per kind; true paging deferred
`TrashScreen.tsx` requests `GET /api/search?query=state:FileNotFound&pageSize=100` — 100 is
`SearchController`'s `MaxPageSize`, and the endpoint has **no page-number parameter**, so a client
can't page past the first 100 matches of a given media kind. The SPA shows the first 100 per kind
(movies, shows, episodes, etc. are separate groups, so in practice most trash lists fit well within
that per-kind cap); this mirrors the legacy Blazor Trash page, which had the same underlying search
behavior and cap. True paging is deferred until the search API grows a page param — not attempted
here, since it would mean adding a paging contract server-side, out of scope for this pass.
+28
View File
@@ -79,6 +79,9 @@ function mockApi(options: MockOptions = {}) {
jsonResponse([{ title: 'Episode 1', start: '00:00:00', finish: '00:30:00', duration: '00:30:00' }])
);
}
if (url === '/api/blocks/4/copy' && method === 'POST') {
return Promise.resolve(jsonResponse({ id: 5, groupId: 2, groupName: 'Prime', name: 'Morning copy' }, 201));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
@@ -104,6 +107,31 @@ describe('BlocksScreen', () => {
expect(screen.getByText('Morning')).toBeInTheDocument();
});
it('opens the copy dialog and POSTs to the copy route, then refreshes the list', async () => {
mockApi();
render(<BlocksScreen />);
await screen.findByText('Morning');
fireEvent.click(screen.getByRole('button', { name: /Copy block/ }));
const dialog = await screen.findByText('Copy "Morning"');
expect(dialog).toBeInTheDocument();
const fetchMock = vi.spyOn(window, 'fetch');
fireEvent.click(screen.getByRole('button', { name: 'Copy' }));
await waitFor(() => {
const call = fetchMock.mock.calls.find(([u, init]) => u === '/api/blocks/4/copy' && init?.method === 'POST');
expect(call).toBeTruthy();
expect(JSON.parse(String(call?.[1]?.body))).toEqual({ blockGroupId: 2, name: 'Morning copy' });
});
await waitFor(() => {
const getCalls = fetchMock.mock.calls.filter(([u, init]) => u === '/api/blocks' && (init?.method ?? 'GET') === 'GET');
expect(getCalls.length).toBeGreaterThan(0);
});
});
it('loads the editor at a sub-path and hydrates duration from minutes', async () => {
window.history.pushState({}, '', '/app/blocks/4');
mockApi({ items: [blockItem({ id: 1, searchTitle: 'News', searchQuery: 'news' })] });
+59
View File
@@ -26,6 +26,7 @@ import {
Spinner
} from '../components';
import {
copyBlock,
createBlock,
createBlockGroup,
deleteBlock,
@@ -313,6 +314,9 @@ function BlockList() {
const [newGroupName, setNewGroupName] = useState('');
const [blockDialogGroup, setBlockDialogGroup] = useState<BlockGroup | null>(null);
const [newBlockName, setNewBlockName] = useState('');
const [copyTarget, setCopyTarget] = useState<Block | null>(null);
const [copyGroupId, setCopyGroupId] = useState('');
const [copyName, setCopyName] = useState('');
const [deleteGroupTarget, setDeleteGroupTarget] = useState<BlockGroup | null>(null);
const [deleteBlockTarget, setDeleteBlockTarget] = useState<Block | null>(null);
const [busy, setBusy] = useState(false);
@@ -376,6 +380,22 @@ function BlockList() {
}
};
const confirmCopy = async () => {
if (!copyTarget || !copyGroupId || !copyName.trim() || busy) {
return;
}
setBusy(true);
try {
await copyBlock(copyTarget.id, { blockGroupId: Number(copyGroupId), name: copyName.trim() });
setCopyTarget(null);
load();
} catch (copyError) {
setError(messageFromBlockError(copyError, 'Unable to copy block'));
} finally {
setBusy(false);
}
};
const confirmDeleteGroup = async () => {
if (!deleteGroupTarget) {
return;
@@ -433,6 +453,7 @@ function BlockList() {
}
const sortedGroups = [...groups].sort((a, b) => a.name.localeCompare(b.name));
const groupOptions = sortedGroups.map((group) => ({ label: group.name, value: String(group.id) }));
return (
<div className="ctv-collections">
@@ -514,6 +535,18 @@ function BlockList() {
{block.name}
</button>
<Badge tone="neutral">{block.minutes} min</Badge>
<IconButton
onClick={() => {
setCopyTarget(block);
setCopyGroupId(String(block.groupId));
setCopyName(`${block.name} copy`);
}}
size="sm"
title="Copy block"
variant="ghost"
>
<Copy aria-hidden="true" size={14} />
</IconButton>
<IconButton
onClick={() => setDeleteBlockTarget(block)}
size="sm"
@@ -581,6 +614,32 @@ function BlockList() {
/>
</Dialog>
<Dialog
footer={
<>
<Button onClick={() => setCopyTarget(null)} size="sm" variant="ghost">
Cancel
</Button>
<Button
disabled={!copyGroupId || !copyName.trim() || busy}
loading={busy}
onClick={() => void confirmCopy()}
size="sm"
>
Copy
</Button>
</>
}
onClose={() => setCopyTarget(null)}
open={copyTarget !== null}
title={copyTarget ? `Copy "${copyTarget.name}"` : 'Copy block'}
>
<Select label="Target group" onChange={(event) => setCopyGroupId(event.target.value)} options={groupOptions} value={copyGroupId} />
<div style={{ marginTop: 12 }}>
<Input label="New name" onChange={(event) => setCopyName(event.target.value)} value={copyName} />
</div>
</Dialog>
<ConfirmDialog
busy={busy}
confirmLabel="Delete"
+1 -1
View File
@@ -494,7 +494,7 @@ export function TraktListsScreen() {
<div className="ctv-settings-callout">
<Search aria-hidden="true" size={14} />
<span>
"View matched items" opens the Classic UI search page — the SPA doesn't have a search screen yet.
"View matched items" opens the SPA search screen, filtered to this list's matched items.
</span>
</div>
+132
View File
@@ -0,0 +1,132 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TrashScreen } from './TrashScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
function browseItem(id: number, mediaType: string, mediaItemId: number) {
return {
artwork: '',
collectionId: null,
collectionKind: null,
collectionType: 'Collection',
duration: null,
id,
itemCount: null,
libraryId: null,
libraryName: null,
mediaItemId,
mediaType,
multiCollectionId: null,
playlistId: null,
rerunCollectionId: null,
smartCollectionId: null,
title: `Item ${id}`
};
}
function emptyGroup() {
return { items: [], totalCount: 0 };
}
const searchResults = {
artists: emptyGroup(),
episodes: emptyGroup(),
images: emptyGroup(),
movies: { items: [browseItem(1, 'Movie', 101), browseItem(2, 'Movie', 102)], totalCount: 2 },
musicVideos: emptyGroup(),
otherVideos: emptyGroup(),
remoteStreams: emptyGroup(),
seasons: emptyGroup(),
shows: { items: [browseItem(3, 'TelevisionShow', 103)], totalCount: 1 },
songs: emptyGroup()
};
interface MockOptions {
onRequest?: (url: string, method: string, body: unknown) => Response | null;
}
function mockApi(options: MockOptions = {}) {
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/search') && method === 'GET') {
expect(url).toContain('pageSize=100');
return Promise.resolve(jsonResponse(searchResults));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
}
describe('TrashScreen', () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
beforeEach(() => {
window.localStorage.clear();
});
it('requests a pageSize of 100', async () => {
mockApi();
render(<TrashScreen />);
await screen.findByText('Item 1');
});
it('selects all items across kinds via Select all', async () => {
mockApi();
render(<TrashScreen />);
await screen.findByText('Item 1');
fireEvent.click(screen.getByRole('button', { name: 'Select all' }));
expect(await screen.findByText('Delete 3 selected')).toBeInTheDocument();
});
it('clears the selection via Clear selection', async () => {
mockApi();
render(<TrashScreen />);
await screen.findByText('Item 1');
fireEvent.click(screen.getByRole('button', { name: 'Select all' }));
await screen.findByText('Delete 3 selected');
fireEvent.click(screen.getByRole('button', { name: 'Clear selection' }));
await waitFor(() => {
expect(screen.queryByText(/Delete \d+ selected/)).not.toBeInTheDocument();
});
});
it('deletes all selected media item ids on confirm', async () => {
const fetchMock = mockApi();
render(<TrashScreen />);
await screen.findByText('Item 1');
fireEvent.click(screen.getByRole('button', { name: 'Select all' }));
fireEvent.click(await screen.findByText('Delete 3 selected'));
const dialogDeleteButton = await screen.findByRole('button', { name: 'Delete' });
fireEvent.click(dialogDeleteButton);
await waitFor(() => {
const call = fetchMock.mock.calls.find(([u, init]) => u === '/api/media-items' && init?.method === 'DELETE');
expect(call).toBeTruthy();
const sentBody = JSON.parse(String(call?.[1]?.body)) as { ids: number[] };
expect([...sentBody.ids].sort()).toEqual([101, 102, 103]);
});
});
});
+29 -1
View File
@@ -11,7 +11,9 @@ import {
} from '../api';
import { MediaPosterCard } from '../media/MediaPosterCard';
const PAGE_SIZE = 50;
// The search API's SearchController clamps pageSize to MaxPageSize=100 and has no page-number
// param, so this is the largest single request possible — see docs/decisions.md ("Trash see all").
const PAGE_SIZE = 100;
// Lucene state filter for items whose files have gone missing (matches the legacy Blazor Trash page).
const TRASH_QUERY = 'state:FileNotFound';
@@ -105,6 +107,24 @@ export function TrashScreen() {
? GROUPS.reduce((sum, group) => sum + state.results![group.key].totalCount, 0)
: 0;
const selectAll = () => {
if (state.status !== 'success' || !state.results) {
return;
}
const ids = new Set<number>();
for (const group of GROUPS) {
for (const item of state.results[group.key].items) {
const mediaItemId = mediaItemIdOf(item);
if (mediaItemId != null) {
ids.add(mediaItemId);
}
}
}
setSelected(ids);
};
const clearSelection = () => setSelected(new Set());
const runDelete = async () => {
setBusy(true);
setActionError(null);
@@ -133,6 +153,14 @@ export function TrashScreen() {
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Button disabled={totalMatches === 0} onClick={selectAll} size="sm" variant="secondary">
Select all
</Button>
{selected.size > 0 && (
<Button onClick={clearSelection} size="sm" variant="secondary">
Clear selection
</Button>
)}
{selected.size > 0 && (
<Button
onClick={() => setConfirm('selected')}
+98
View File
@@ -0,0 +1,98 @@
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { WatermarksScreen } from './WatermarksScreen';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), { headers: { 'Content-Type': 'application/json' }, status });
}
const watermarks = [{ id: 3, name: 'Logo' }];
const watermarkDetail = {
durationSeconds: 15,
frequencyMinutes: 15,
horizontalMargin: 5,
id: 3,
image: 'logo.png',
imageContentType: 'image/png',
imageSource: 'Custom',
location: 'BottomRight',
mode: 'Permanent',
name: 'Logo',
opacity: 100,
opacityExpression: null,
placeWithinSourceContent: false,
size: 'Scaled',
verticalMargin: 5,
width: 15,
zIndex: 0
};
interface MockOptions {
onRequest?: (url: string, method: string, body: unknown) => Response | null;
}
function mockApi(options: MockOptions = {}) {
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/watermarks' && method === 'GET') {
return Promise.resolve(jsonResponse(watermarks));
}
if (url === '/api/watermarks/3' && method === 'GET') {
return Promise.resolve(jsonResponse(watermarkDetail));
}
return Promise.resolve(new Response(null, { status: 204 }));
});
}
describe('WatermarksScreen', () => {
afterEach(() => {
cleanup();
vi.restoreAllMocks();
window.history.pushState({}, '', '/app/watermarks');
});
beforeEach(() => {
window.localStorage.clear();
window.history.pushState({}, '', '/app/watermarks');
});
it('renders watermarks', async () => {
mockApi();
render(<WatermarksScreen />);
expect(await screen.findByText('Logo')).toBeInTheDocument();
});
it('navigates to /add?from={id} when Copy is clicked', async () => {
mockApi();
render(<WatermarksScreen />);
await screen.findByText('Logo');
fireEvent.click(screen.getByRole('button', { name: /Copy Logo/ }));
await waitFor(() => {
expect(window.location.pathname + window.location.search).toBe('/app/watermarks/add?from=3');
});
});
it('prefills the editor from the source watermark with a "(copy)" name suffix', async () => {
window.history.pushState({}, '', '/app/watermarks/add?from=3');
mockApi();
render(<WatermarksScreen />);
await waitFor(() => expect(screen.getByDisplayValue('Logo (copy)')).toBeInTheDocument());
expect(screen.getByText('New watermark')).toBeInTheDocument();
});
});
+25 -12
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { ArrowLeft, Check, Image as ImageIcon, Plus, Trash2, TriangleAlert, Upload } from 'lucide-react';
import { ArrowLeft, Check, Copy, Image as ImageIcon, Plus, Trash2, TriangleAlert, Upload } from 'lucide-react';
import { navigateToPath } from '../routing';
import { Badge, Button, Card, Checkbox, ConfirmDialog, IconButton, Input, Select, Spinner } from '../components';
import {
@@ -156,7 +156,7 @@ function Row({
);
}
type Mode = { id: number; kind: 'edit' } | { kind: 'add' } | { kind: 'list' };
type Mode = { id: number; kind: 'edit' } | { kind: 'add'; from: null | number } | { kind: 'list' };
function modeFromPath(pathname: string): Mode {
const normalized = pathname.replace(/\/+$/, '');
@@ -168,7 +168,8 @@ function modeFromPath(pathname: string): Mode {
const suffix = normalized.slice(BASE_PATH.length + 1).split('/')[0];
if (suffix === 'add') {
return { kind: 'add' };
const from = new URLSearchParams(window.location.search).get('from');
return { from: from ? Number(from) : null, kind: 'add' };
}
const id = Number(suffix);
@@ -176,15 +177,15 @@ function modeFromPath(pathname: string): Mode {
}
export function WatermarksScreen() {
const [pathname, setPathname] = useState(() => window.location.pathname);
const [pathname, setPathname] = useState(() => window.location.pathname + window.location.search);
useEffect(() => {
const onPop = () => setPathname(window.location.pathname);
const onPop = () => setPathname(window.location.pathname + window.location.search);
window.addEventListener('popstate', onPop);
return () => window.removeEventListener('popstate', onPop);
}, []);
const mode = modeFromPath(pathname);
const mode = modeFromPath(window.location.pathname);
if (mode.kind === 'list') {
return <WatermarkList key={pathname} />;
@@ -306,6 +307,14 @@ function WatermarkList() {
>
{watermark.name}
</button>
<IconButton
onClick={() => navigateToPath(`${BASE_PATH}/add?from=${watermark.id}`)}
size="sm"
title={`Copy ${watermark.name}`}
variant="ghost"
>
<Copy aria-hidden="true" size={14} />
</IconButton>
<IconButton onClick={() => setDeleteTarget(watermark)} size="sm" title="Delete" variant="ghost">
<Trash2 aria-hidden="true" size={14} />
</IconButton>
@@ -328,8 +337,8 @@ function WatermarkList() {
);
}
function WatermarkEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: 'add' } }) {
const [draft, setDraft] = useState<Draft | null>(mode.kind === 'add' ? defaultDraft : null);
function WatermarkEditor({ mode }: { mode: { id: number; kind: 'edit' } | { from: null | number; kind: 'add' } }) {
const [draft, setDraft] = useState<Draft | null>(mode.kind === 'add' && mode.from == null ? defaultDraft : null);
const [loadError, setLoadError] = useState<null | string>(null);
const [saveError, setSaveError] = useState<null | string>(null);
const [uploadError, setUploadError] = useState<null | string>(null);
@@ -341,18 +350,22 @@ function WatermarkEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind
// Captured once at mount; the screen keys this editor by pathname (see ChannelEditScreen).
const [loadEditId] = useState(() => (mode.kind === 'edit' ? mode.id : null));
const [loadCopyFrom] = useState(() => (mode.kind === 'add' ? mode.from : null));
useEffect(() => {
if (loadEditId == null) {
if (loadEditId == null && loadCopyFrom == null) {
return;
}
let active = true;
getWatermark(loadEditId)
const sourceId = loadEditId ?? loadCopyFrom;
getWatermark(sourceId as number)
.then((watermark) => {
if (active) {
setDraft(draftFromWatermark(watermark as Watermark & Draft));
const source = draftFromWatermark(watermark as Watermark & Draft);
setDraft(loadEditId != null ? source : { ...source, name: `${source.name} (copy)` });
}
})
.catch((error: unknown) => {
@@ -364,7 +377,7 @@ function WatermarkEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind
return () => {
active = false;
};
}, [loadEditId]);
}, [loadEditId, loadCopyFrom]);
if (loadError) {
return (