diff --git a/docs/decisions.md b/docs/decisions.md index e03c628ac..40ea73f75 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -55,6 +55,7 @@ keep append-only from accreting stale, contradictory, or unreadably-large histor - [2026-07-11 — EntityLocker: atomic flags + single-owner release discipline, no owner tokens (#231)](#2026-07-11--entitylocker-atomic-flags--single-owner-release-discipline-no-owner-tokens-231) - [2026-07-11 — Channels screen extraction (#244): single-file screen, no sibling helper dir (epic #243 phase 1)](#2026-07-11--channels-screen-extraction-244-single-file-screen-no-sibling-helper-dir-epic-243-phase-1) - [2026-07-14 — Playouts screen extraction (#245): screen-owned route wrapper (epic #243 phase 2)](#2026-07-14--playouts-screen-extraction-245-screen-owned-route-wrapper-epic-243-phase-2) +- [2026-07-15 — App shell/routing extraction + explicit primary-action ownership (#247)](#2026-07-15--app-shellrouting-extraction--explicit-primary-action-ownership-247) - [2026-07-11 — Media-source management REST write API + SPA (#202)](#2026-07-11--media-source-management-rest-write-api--spa-202) - [2026-07-11 — Legacy→SPA redirect matcher: exact map + ordered segment-template patterns (#204)](#2026-07-11--legacyspa-redirect-matcher-exact-map--ordered-segment-template-patterns-204) - [2026-07-11 — Blazor removal auth posture: no new exposure beyond phase (a); real auth deferred to #197 (#206)](#2026-07-11--blazor-removal-auth-posture-no-new-exposure-beyond-phase-a-real-auth-deferred-to-197-206) @@ -1809,3 +1810,37 @@ guards to these pre-existing promise completions; changing those semantics belon Detailed behavior tests now render `PlayoutsScreen` directly with a scoped fetch mock, including the zero-playout Add Playout affordance, lock/409 handling, refresh/poll ownership, action and kind gates, and dialog flows. Refs #245 #243. + +## 2026-07-15 — App shell/routing extraction + explicit primary-action ownership (#247) + +Final phase of the App.tsx modularization epic (#243). `web/src/App.tsx` is now only the composition +root: it owns `activeRoute`, `currentPathRef`, the `navigate`/`popstate` pair that consults the dirty +guard, the approved `librariesSubPath`, and the global theme/health inputs, then composes the shell with +the matched screen. Route metadata/matching/sidebar groups moved to `web/src/app/routes.tsx`; shell chrome +(Sidebar, TopBar, Connect menu, version and theme controls) moved to `app/AppShell.tsx`; exhaustive screen +dispatch plus the Media/Libraries wrappers moved to `app/ScreenContent.tsx`. No route, styling, API, or +dependency changed. + +**Route identity is deliberate infrastructure.** `routes.tsx` contains the ONE stable module-level array +of shared `ScreenRoute` objects. `routeFromLocation()` returns those same references for an +`allowSubPaths` base path and every owned sub-path, so React's `Object.is` state bailout remains part of +the contract rather than an accidental implementation detail. The three existing sub-path mechanisms stay +distinct: Playouts and Media self-own `pathname`/`popstate`; guarded Libraries receives only the path App +approved after its dirty guard; the remaining route screens retain their established self-owned or keyed +remount behavior. The extraction does not unify them into a speculative router/framework. `ScreenContent` +uses an exhaustive `ScreenId` switch, so a future route added without a dispatch branch fails typecheck +instead of silently falling through to a placeholder. + +**Primary actions are one explicit screen-owned registration, not a global event.** The old +`ctv:primary-action` window `CustomEvent` and string-keyed dispatcher are removed. `PrimaryActionProvider` +holds exactly one `{ routeId, handler, owner }` registration shared by the active screen and TopBar; +`usePrimaryAction` registers it, keeps the latest handler behind a ref without ownership churn, and clears +it only when the same opaque owner unmounts. A stale cleanup therefore cannot erase a newer screen's +action. TopBar renders the Plus action only when the route has a non-empty label AND that active route owns +a matching registration, so metadata alone can no longer create a dead button. This is intentionally not a +generic action bus: one declared action per screen is the whole contract. + +Tests pin stable route-object identity (including sibling sub-paths and query-only URLs), composition-level +sub-path rendering and dirty-popstate restoration, and primary-action matching/latest-handler/route-change/ +cleanup/stale-owner behavior. Detailed Builder and Settings behavior is colocated with those screens while +`App.test.tsx` remains shell/routing/composition coverage. Refs #247 #243 #238 #230. diff --git a/docs/spa-conventions.md b/docs/spa-conventions.md index 3051be929..050dcb6a2 100644 --- a/docs/spa-conventions.md +++ b/docs/spa-conventions.md @@ -12,8 +12,14 @@ Companion to `api-conventions.md` (the API surface the SPA talks to) and `docs/c Vite + React + TypeScript, builds to `ErsatzTV/wwwroot/app` (see `web/vite.config.ts`: `base: '/app/'`, `build.outDir: '../ErsatzTV/wwwroot/app'`), served by the ASP.NET host at `/app`. -- **Routes + nav**: `web/src/App.tsx` — one big route table of `ScreenRoute` objects (`path`, - `label`, `title`, `kicker`, `icon`, etc.) plus an `allowSubPaths?: boolean` flag. +- **Composition root**: `web/src/App.tsx` — owns the active route, approved Libraries sub-path, + navigation guard integration, and theme; it composes the shell with the matched screen. +- **Routes + nav**: `web/src/app/routes.tsx` — the ONE stable module-level array of `ScreenRoute` + objects (`path`, `label`, `title`, `kicker`, `icon`, etc.) plus `allowSubPaths?: boolean`, the + matcher, and sidebar group definitions. Route objects must never be rebuilt per render. +- **Shell + screen dispatch**: `web/src/app/AppShell.tsx` owns Sidebar/TopBar/Connect/version/theme + chrome; `web/src/app/ScreenContent.tsx` exhaustively maps a matched route to its screen and owns + the Media/Libraries route wrappers. - **Screens**: `web/src/screens/*.tsx`, one file per top-level screen, generally with a colocated `*.test.tsx`. - **API clients**: `web/src/api/.ts` (see §4). @@ -25,9 +31,10 @@ Vite + React + TypeScript, builds to `ErsatzTV/wwwroot/app` (see `web/vite.confi If a route sets `allowSubPaths: true` (e.g. so `/app/blocks/{id}` works under the `/app/blocks` nav entry), **the screen component itself must track `window.location.pathname` and listen for -`popstate`** — do not rely on `App.tsx` re-rendering `ScreenContent` when the sub-path changes. +`popstate`** — do not rely on the composition root re-rendering `ScreenContent` when the sub-path +changes. -**Why**: `App.tsx`'s `routeFromLocation()` matches an `allowSubPaths` route by prefix +**Why**: `app/routes.tsx`'s `routeFromLocation()` matches an `allowSubPaths` route by prefix (`pathname.startsWith(\`${route.path}/\`)`) and returns the **same `ScreenRoute` object reference** for the base path and every sub-path under it. `App`'s state update is `setActiveRoute(routeFromLocation())`; React's `useState` setter bails via `Object.is` when the new @@ -46,8 +53,8 @@ Exemplars of screens that already do this correctly: `BlocksScreen.tsx`, `Templa **Exception — a guarded sub-path route defers pathname ownership to App.** When a sub-path route's screens ALSO register a dirty guard (§8), the wrapper must **not** self-listen for `popstate`; App owns the pathname and passes the approved sub-path down as a prop. The `LibrariesRouteScreen` wrapper -in `App.tsx` is the exemplar (sub-path parsed by `parseLibrariesSubRoute`, dispatched via a flat -`switch`, sub-path supplied by App's `librariesSubPath` state). See §8 for why child-before-parent +in `app/ScreenContent.tsx` is the exemplar (sub-path parsed by `parseLibrariesSubRoute`, dispatched +via a flat `switch`, sub-path supplied by App's `librariesSubPath` state). See §8 for why child-before-parent effect order makes the self-listening pattern unsafe here. ## 3. Data loading pattern @@ -251,16 +258,17 @@ is gone. The SPA seams now are: - **vitest**, colocated `*.test.ts` / `*.test.tsx` next to the source file. - Every screen with meaningful logic gets a screen test; every API client module gets a param-mapping / URL-building test (e.g. `logs.test.ts` next to `logs.ts`). -- `web/src/App.test.tsx` covers navigation + the route table, including regressions like the - sub-path bug in §2 (see the tests around `PlayoutsRouteScreen` that click into - `/app/playouts/{id}/...` sub-paths and assert the correct sub-screen rendered). +- `web/src/App.test.tsx` covers composition, navigation, shell behavior, and integration regressions + such as sub-path-to-sub-path rendering and guarded popstate restoration. Detailed screen behavior + belongs in the screen's colocated test. `web/src/app/routes.test.tsx` independently pins stable + route-object identity and query/path matching. - **Nav-label test-selector care**: `getByRole('link'/'button', { name: /Regex/ })` matches by substring by default — a loose regex can match more than one nav item. Verified example: the System nav button is matched with an **anchored** regex (`name: /^System/`) rather than a bare `/System/`, specifically to avoid ambiguous matches against other labels that start with or contain "System". Anchor (`^`/`$`) or use exact strings in `getByRole` name matchers whenever a new label could be a substring of (or share a substring with) an existing one — check - `App.tsx`'s nav `label:` list for collisions before picking a new label. + `app/routes.tsx`'s nav `label:` list for collisions before picking a new label. - **Extracted-screen tests own their own fetch mock** (Schedules #207, Channels #244, Playouts #245): when a screen is pulled out of `App.tsx` into `web/src/screens/Screen.tsx`, its colocated @@ -356,21 +364,30 @@ Keep the guard predicate reading a **ref** (`dirtyRef`), not the `dirty` state v ## 10. TopBar primary-action button (`usePrimaryAction`) -The shell TopBar (`App.tsx`) renders at most **one** primary-action button (top-right, Plus icon) for the -active screen. The TopBar has no reference to the screen component, so the click is delivered as a window -`CustomEvent` keyed on the active route id; the seam is `web/src/primaryAction.ts`: +The shell TopBar (`app/AppShell.tsx`) renders at most **one** primary-action button (top-right, Plus +icon) for the active screen. `App.tsx` wraps the shell and matched screen in the minimal +`PrimaryActionProvider` from `web/src/primaryAction.ts`: the active screen explicitly registers one +handler, and the TopBar reads that matching registration directly from React context. No window event, +string-keyed dispatcher, or generic screen-action framework participates in normal screen actions. - **A screen opts in** by calling `usePrimaryAction(routeId, handler)` at the **top of the component, before any early return** (it's a hook). The handler must be reachable there — a create/navigate handler or a `useState` setter, not something defined below a loading/error `return`. Reference: `SchedulesScreen` (`usePrimaryAction('schedules', () => setForm('create'))`). -- **The route must ALSO declare a matching non-empty `primaryAction` label** in the `routes` table. The - TopBar renders the button **only when `route.primaryAction` is non-empty** — so declaring a label without - subscribing renders a dead button, and subscribing without a label renders nothing. Keep the two in lockstep. +- **The provider owns exactly one registration.** Each mounted hook gets an opaque owner token; registering a + newer screen replaces the previous registration, and cleanup clears only the registration owned by that + hook. A stale unmount therefore cannot erase the newer screen's action. The hook keeps the latest handler in + a ref, so ordinary screen renders update behavior without reclaiming/churning ownership. Directly-rendered + screen tests outside the provider remain harmless; there is simply no shell action consumer. +- **The route must ALSO declare a matching non-empty `primaryAction` label** in the stable + `app/routes.tsx` table. The TopBar renders the button only when that label is non-empty **and** the active + route owns a matching registration — metadata alone can no longer produce a dead button, while a + registration without a label remains intentionally invisible. Keep the two in lockstep. The `#238` tests in `App.test.tsx` guard this: a data-driven `it.each` asserts each URL-navigating create screen's banner actually navigates (so a typo'd route id → a button that navigates nowhere → red), plus a - drop test that an action screen shows no banner button. The dialog/editor create screens (schedules, multi/ - rerun collections, trakt) are exercised by their own create-flow tests. + drop test that an action screen shows no banner button. `primaryAction.test.tsx` separately pins matching, + latest-handler, route-change, cleanup, and stale-owner semantics. The dialog/editor create screens + (schedules, multi/rerun collections, trakt) are exercised by their own create-flow tests. - **When to WIRE vs DROP (issue #238).** The Plus icon makes the button semantically a *"create new item"* affordance. **Keep + wire it only on list screens with a single, unambiguous create flow** ("Add Channel", "Add Schedule", "Add Multi-Collection", "Add Rerun Collection", "Add Trakt List", "Add Filler Preset", "Add diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index 896789727..45635ac8a 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -1,7 +1,6 @@ -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { App } from './App'; -import { Button, Checkbox, Input, ProgressBar, Switch, Tabs, Toast, Tooltip } from './components'; import { applyDesignSystemTheme, designSystemStylesheet, @@ -88,6 +87,18 @@ describe('ChicoryTV SPA scaffold', () => { expect(window.location.pathname).toBe('/app/schedules'); }); + it('dispatches the Channel Builder from its initial route', async () => { + window.history.replaceState(null, '', '/app/new-channel'); + + render(); + + expect( + await screen.findByText('New Channel', { selector: '.ctv-builder-title' }) + ).toBeInTheDocument(); + expect(screen.getByPlaceholderText('Search shows & movies…')).toBeInTheDocument(); + expect(window.fetch).toHaveBeenCalledWith('/api/v1/channel-templates', expect.any(Object)); + }); + it('registers the multi-collection and rerun-collection nav entries', async () => { render(); @@ -549,1032 +560,64 @@ describe('ChicoryTV SPA scaffold', () => { expect(window.location.pathname).toBe('/app/playouts'); }); - it('exports typed primitives with expected interactions', () => { - const onSwitch = vi.fn(); - const onCheckbox = vi.fn(); - const onTab = vi.fn(); - - render( - <> - - - - {}} /> - - - - - - - ); - - expect(screen.getByRole('button', { name: 'Saving' })).toBeDisabled(); - fireEvent.click(screen.getByRole('switch', { name: 'Show disabled' })); - expect(onSwitch).toHaveBeenCalledWith(true); - expect(screen.getByRole('checkbox', { name: 'Select all' })).toHaveAttribute( - 'aria-checked', - 'mixed' - ); - expect(screen.getByText('Already in use')).toBeInTheDocument(); - expect(screen.getByText('62%')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('tab', { name: 'Streaming' })); - expect(onTab).toHaveBeenCalledWith('streaming'); - fireEvent.mouseEnter(screen.getByText('Reset')); - expect(screen.getByRole('tooltip')).toHaveTextContent('Reset playout'); - }); - - it('uses distinct semantic icons for warning and error toasts', () => { - const { container } = render( - <> - - - - ); - - expect(container.querySelector('.lucide-triangle-alert')).toBeInTheDocument(); - expect(container.querySelector('.lucide-circle-x')).toBeInTheDocument(); - }); - - // ---- Channel Builder (#89) ----------------------------------------------- - const renderBuilder = async () => { - window.history.replaceState(null, '', '/app/new-channel'); - const utils = render(); - await screen.findByPlaceholderText('Search shows & movies…'); - return utils; - }; - - // The shell's nav link and top-bar primary action also read "New Channel" / - // "Create Channel"; scope these to the builder toolbar. - const createBtn = () => - within(document.querySelector('.ctv-builder-toolbar') as HTMLElement).getByRole('button', { - name: 'Create Channel' - }); - const builderTitle = () => screen.getByText('New Channel', { selector: '.ctv-builder-title' }); - const numberField = () => screen.getByLabelText('Number', { exact: false }) as HTMLInputElement; - - const builderDefaults = () => ({ - channels: [channelSummary()], - channelTemplates: [channelTemplate()], - defaultChannelTemplate: channelTemplate(), - ffmpegProfiles: [ffmpegProfile()] - }); - - it('renders the builder three-column layout with library items and the default template', async () => { + it('updates sibling Playouts editors on popstate while App retains the stable route object', async () => { mockDashboardApi({ - ...builderDefaults(), - browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] + playoutAlternateSchedules: [], + playoutDetails: playout({ id: 20, channelName: 'Retro Cartoons', channelNumber: '5.1' }), + playoutTemplateItems: [], + schedules: [], + templates: [] }); + window.history.replaceState(null, '', '/app/playouts/20/alternate-schedules'); - const { container } = await renderBuilder(); + render(); - expect(builderTitle()).toBeInTheDocument(); - expect(screen.getByText('Lineup')).toBeInTheDocument(); - expect(screen.getByText('Channel Template')).toBeInTheDocument(); - expect(screen.getByText('Standard')).toBeInTheDocument(); - expect(await screen.findByText('Looney Tunes')).toBeInTheDocument(); - expect(screen.getByText('Tom & Jerry')).toBeInTheDocument(); - expect(container.querySelectorAll('.ctv-builder-col')).toHaveLength(3); - expect(screen.getByText('This channel has no content yet. Double-click or drag titles from the library to build the lineup.')).toBeInTheDocument(); - }); - - it('computes the AUTO channel number from the max integer part of existing channels', async () => { - mockDashboardApi({ - ...builderDefaults(), - channels: [channelSummary({ id: 1, number: '5' }), channelSummary({ id: 2, number: '13.1' })], - browseItems: [browseItem()] - }); - - await renderBuilder(); - - const numberInput = numberField(); - expect(numberInput.value).toBe('14'); - expect(screen.getByText('AUTO')).toBeInTheDocument(); - }); - - it('adds a library item to the lineup on double-click and dedupes repeats', async () => { - mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem()] }); - - const { container } = await renderBuilder(); - - fireEvent.doubleClick(await screen.findByText('Looney Tunes')); - expect(container.querySelector('.ctv-builder-summary')?.textContent).toContain('1 in lineup'); - expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1); - - fireEvent.doubleClick(screen.getAllByText('Looney Tunes')[0]); - expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1); - }); - - it('removes a lineup item and clears the lineup through the confirm dialog', async () => { - mockDashboardApi({ - ...builderDefaults(), - browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] - }); - - const { container } = await renderBuilder(); - - fireEvent.doubleClick(await screen.findByText('Looney Tunes')); - fireEvent.doubleClick(screen.getByText('Tom & Jerry')); - expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(2); - - fireEvent.click(within(container.querySelectorAll('.ctv-builder-lineup-row')[0] as HTMLElement).getByRole('button', { name: 'Remove' })); - expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(1); - - fireEvent.click(screen.getByRole('button', { name: 'Clear' })); - fireEvent.click(await screen.findByRole('button', { name: 'Clear lineup' })); - await waitFor(() => expect(container.querySelectorAll('.ctv-builder-lineup-row')).toHaveLength(0)); - }); - - it('filters library results through the debounced search query', async () => { - mockDashboardApi({ - ...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 = all - .filter((item) => !mediaType || item.mediaType === mediaType) - .filter((item) => !query || String(item.title).toLowerCase().includes(query)); - return { page, totalCount: page.length }; - } - }); - - await renderBuilder(); - - expect(await screen.findByText('Blade Runner')).toBeInTheDocument(); - fireEvent.change(screen.getByPlaceholderText('Search shows & movies…'), { target: { value: 'blade' } }); - - await waitFor(() => expect(screen.queryByText('Looney Tunes')).not.toBeInTheDocument()); - expect(screen.getByText('Blade Runner')).toBeInTheDocument(); - }); - - it('reorders lineup items with native drag and drop', async () => { - mockDashboardApi({ - ...builderDefaults(), - browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] - }); - - const { container } = await renderBuilder(); - - fireEvent.doubleClick(await screen.findByText('Looney Tunes')); - fireEvent.doubleClick(screen.getByText('Tom & Jerry')); - - let rows = container.querySelectorAll('.ctv-builder-lineup-row'); - expect(rows[0].querySelector('.ctv-builder-row-title')?.textContent).toBe('Looney Tunes'); - - fireEvent.dragStart(rows[0]); - fireEvent.dragOver(rows[1]); - fireEvent.drop(rows[1]); - - rows = container.querySelectorAll('.ctv-builder-lineup-row'); - expect(rows[0].querySelector('.ctv-builder-row-title')?.textContent).toBe('Tom & Jerry'); - expect(rows[1].querySelector('.ctv-builder-row-title')?.textContent).toBe('Looney Tunes'); - }); - - it('validates the channel number for format and uniqueness', async () => { - mockDashboardApi({ - ...builderDefaults(), - channels: [channelSummary({ number: '5' })], - browseItems: [browseItem()] - }); - - await renderBuilder(); - - const numberInput = numberField(); - - fireEvent.change(numberInput, { target: { value: 'abc' } }); - expect(await screen.findByText(/Use digits/)).toBeInTheDocument(); - - fireEvent.change(numberInput, { target: { value: '5' } }); - expect(await screen.findByText(/already in use/)).toBeInTheDocument(); - }); - - it('keeps Create disabled until a name and at least one lineup item exist', async () => { - mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem()] }); - - await renderBuilder(); - - const createButton = createBtn(); - expect(createButton).toBeDisabled(); - - fireEvent.doubleClick(await screen.findByText('Looney Tunes')); - fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: 'Retro Cartoons' } }); - - expect(createButton).toBeEnabled(); - }); - - it('preselects the default template and flags an override when the Shuffle toggle diverges', async () => { - mockDashboardApi({ ...builderDefaults(), browseItems: [browseItem()] }); - - const { container } = await renderBuilder(); - - // default template has shuffleScheduleItems=false -> no override tag yet - expect(screen.queryByText('overrides template')).not.toBeInTheDocument(); - - const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement; - fireEvent.click(shuffleRow); - - expect(await screen.findByText('overrides template')).toBeInTheDocument(); - }); - - it('applies a selected template shuffle default and clears the override', async () => { - mockDashboardApi({ - ...builderDefaults(), - channelTemplates: [ - channelTemplate(), - channelTemplate({ id: 11, isDefault: false, name: 'Music videos', shuffleScheduleItems: true }) - ], - browseItems: [browseItem()] - }); - - const { container } = await renderBuilder(); - - const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement; - fireEvent.click(shuffleRow); - expect(await screen.findByText('overrides template')).toBeInTheDocument(); - - // open the template picker and select the shuffle-by-default template - fireEvent.click(screen.getByText('Standard')); - fireEvent.click(await screen.findByText('Music videos')); - - await waitFor(() => expect(screen.queryByText('overrides template')).not.toBeInTheDocument()); - }); - - it('marks a rerun-collection row invalid in a multi-item lineup and blocks Create', async () => { - mockDashboardApi({ - ...builderDefaults(), - browseItems: [ - browseItem(), - browseItem({ id: 9, title: 'Saturday Block', mediaType: 'RerunCollection', collectionType: 'RerunFirstRun', collectionKind: 'Rerun', rerunCollectionId: 9, mediaItemId: undefined }) - ] - }); - - await renderBuilder(); - - fireEvent.doubleClick(await screen.findByText('Looney Tunes')); - - // 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(); - expect(createBtn()).toBeDisabled(); - }); - - it('clears a MultiCollection shuffle requirement when the Shuffle toggle is turned on', async () => { - mockDashboardApi({ - ...builderDefaults(), - browseItems: [ - browseItem({ id: 7, title: 'Prime Time', mediaType: 'MultiCollection', collectionType: 'MultiCollection', multiCollectionId: 7, mediaItemId: undefined }) - ] - }); - - 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' } }); - - expect(await screen.findByText('Requires Shuffle')).toBeInTheDocument(); - expect(createBtn()).toBeDisabled(); - - const shuffleRow = container.querySelector('.ctv-builder-toggle-row:not(.ctv-builder-toggle-live)') as HTMLElement; - fireEvent.click(shuffleRow); - - await waitFor(() => expect(screen.queryByText('Requires Shuffle')).not.toBeInTheDocument()); - expect(createBtn()).toBeEnabled(); - }); - - it('posts a well-formed create request and navigates to channels on success', async () => { - mockDashboardApi({ - ...builderDefaults(), - channels: [channelSummary({ number: '5' })], - browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })] - }); - - await renderBuilder(); - - fireEvent.doubleClick(await screen.findByText('Looney Tunes')); - fireEvent.doubleClick(screen.getByText('Tom & Jerry')); - fireEvent.change(screen.getByLabelText('Channel name'), { target: { value: ' Retro Cartoons ' } }); - - fireEvent.click(createBtn()); - - await waitFor(() => expect(window.location.pathname).toBe('/app/channels')); - - const body = requestBodyFor('/api/v1/channels/from-lineup'); - expect(body.name).toBe('Retro Cartoons'); - expect(body.number).toBe('6'); - expect(body.group).toBe('ChicoryTV'); - expect(body.templateId).toBe(10); - expect(body.logo).toEqual({ contentType: '', path: '' }); - expect((body.advanced as Record).playbackOrder).toBe('Chronological'); - expect((body.advanced as Record).playoutMode).toBe('Continuous'); - const lineup = body.lineup as Array>; - expect(lineup).toHaveLength(2); - expect(lineup[0].mediaItemId).toBe(1); - expect(lineup[1].mediaItemId).toBe(2); - expect(lineup[0].mediaType).toBe('TelevisionShow'); - }); - - it('highlights the offending lineup row and shows the detail on a 422 ProblemDetails', async () => { - mockDashboardApi({ - ...builderDefaults(), - browseItems: [browseItem(), browseItem({ id: 2, mediaItemId: 2, title: 'Tom & Jerry' })], - // Verbatim wire shape: ApiResults hard-codes the 422 title "Validation failed", - // and the handler's not-found detail is "lineup[i]