Files
ersatztv/web/src/builder/ChannelBuilder.tsx
T
timothy ca99bedb1a fix(650): rewrite the pageSize guard on the TS compiler API; fix two append-ownership races
Second cold cross-family (Codex, BLOCKED) re-review of b90f8a3b found the
regex/bracket-tracking guard scanner still defeated in five ways, and two new
High-severity races introduced by the F3/F4 fixes. Addressed as a further
follow-up (b90f8a3b left untouched).

GUARD REWRITE (per the review's explicit direction — stop patching the regex,
use the compiler):

- New `web/src/api/pageSizeScan.ts`: `scanPageSizeSites` parses each file with
  `ts.createSourceFile` and walks the real AST for `pageSize`
  PropertyAssignment/ShorthandPropertyAssignment nodes inside an
  ObjectLiteralExpression. This eliminates categorically (not case-by-case):
    - M-3: comments and string/template CONTENTS are never revisited as code,
      so a `'https://...'` string can't be misread as an unterminated string
      that swallows the rest of the file.
    - M-4: an object literal nested in a ternary, `??`, or JSX expression
      container is still found — the walk visits every descendant node
      regardless of the syntactic context above the ObjectLiteralExpression.
    - M-5: template-literal interpolations are real AST children, not opaque
      text.
    - L-7: a type literal (`type P = { pageSize: 100 }`), an interface
      PropertySignature, and a destructuring ObjectBindingPattern (parameter
      or nested) are structurally different node kinds from
      ObjectLiteralExpression — excluded by kind, not by a
      preceding-character heuristic a stray `{`/`(`/`,` could fool.
  `getLineAndCharacterOfPosition` gives exact line+column (fixes M-6 identity
  granularity) instead of the prior line-only identity.
- `pageSizeCallSites.guard.test.ts` now imports the shared scanner; identity
  is `file:line:column:kind:value`, compared as a MULTISET (count, not
  membership) in both directions.
- Both directions (unregistered / stale) are computed and folded into ONE
  thrown Error so a failure always shows the complete picture in one run,
  addressing the line-churn "second direction never renders" concern.
- New `pageSizeScan.test.ts`: a FIXTURE test (inline source strings, no repo
  scan) pinning the exact discovered set for every case the review named —
  comment-in-string, string containing the literal text `pageSize: 100`,
  template interpolation, ternary, `??`, JSX container, same-line duplicates,
  parameter/nested destructuring, a type literal, an interface property, a
  forwarded call expression, a React dependency array. This is what actually
  protects the scanner going forward — the guard test alone only ever proved
  today's snapshot of real call sites, never the scanner's handling of input
  classes it hadn't happened to encounter yet.
- Re-verified both original plants (a duplicate at-cap call in an
  already-registered file, and a new file with both a literal and a
  shorthand site) against the rewritten scanner; both still fail with the
  new combined-direction message. Also verified a run with BOTH directions
  simultaneously non-empty renders both in one report.

HIGH-1 (ChannelBuilder.tsx useLibraryBrowse, now web/src/builder/libraryBrowse.ts):
`reqId` identifies a query GENERATION, not an individual fetch — a page-0
refresh and a "Load more" append can be outstanding simultaneously under the
same reqId (query changes while an append is in flight for the new
generation). Whichever settled first used to clear `loadingMore`, letting a
second click fire an out-of-order/duplicate page fetch. Fixed with a
per-fetch `fetchId` plus a `loadingFetchIdRef`/`loadingFetchReqIdRef` pair:
only the fetch that OWNS the currently-displayed spinner can clear it; a
same-generation page-0 refresh leaves a same-generation append's spinner
alone, while a page-0 refresh for a NEW generation still retires an
abandoned OLDER-generation append's spinner (preserving the original #650 F3
fix). Reproduced the exact interleaving from the review in a new test
(gate B's page-0 and page-1 fetches independently, click "Load more" while
B's page-0 is still in flight) and confirmed it fails without the fix
(button re-enables while the append is still pending).

HIGH-2 (same file): the append-failure rollback mutated whatever
`pageRef.current` currently held, rather than the specific page THIS fetch
requested — under an overlapping-append race, a later page's success
followed by an earlier page's failure could roll the cursor back past
already-appended progress, corrupting a retry into refetching a duplicate.
Fixed with a compare-and-set guard (`if (pageRef.current === pageNum)`) so
the rollback only fires when nothing has advanced the cursor since. Since
this overlap is UI-unreachable once HIGH-1's single-flight disabling is
wired up (verified empirically: two synchronous fireEvent.click calls in RTL
only produce one request, since act() flushes the disabling render between
them), the regression test drives `useLibraryBrowse` directly via
`renderHook` (now exported) to force the exact interleaving and confirms it
fails without the fix (page 2 gets duplicated, page 3 never requested).

Extracted `useLibraryBrowse` (plus `loadCollections`/`loadLibraryItems`/
`BrowseState`/the media-type const arrays) into a new non-JSX module
`web/src/builder/libraryBrowse.ts` — exporting a hook from a .tsx file
tripped `react-refresh/only-export-components`; this also makes the hook
importable by `renderHook` without pulling in the whole screen component.

No server-side/C# change. Full local gate: lint clean, tsc clean, full
vitest run 110 files / 1051 tests passed (one LibrariesScreen.test.tsx
flake reproduced under full-suite parallel load, confirmed pre-existing and
unrelated — passes in isolation, never touched that file).
2026-07-27 01:29:15 +02:00

2055 lines
77 KiB
TypeScript

import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type CSSProperties,
type ReactNode
} from 'react';
import {
Check,
ChevronDown,
ChevronRight,
ChevronUp,
Circle,
CircleCheck,
Eye,
Film,
FolderTree,
GripVertical,
Image as ImageIcon,
Info,
Library,
LayoutGrid,
ListOrdered,
ListVideo,
Plus,
Radio,
Rows3,
Save,
Search,
Shuffle,
SlidersHorizontal,
Sparkles,
SquarePen,
X
} from 'lucide-react';
import { navigateToPath } from '../routing';
import { TYPE_ICON, TYPE_LABEL, hueOf } from '../media/mediaKinds';
import {
ApiError,
createChannelFromLineup,
createChannelTemplate,
createSmartCollection,
getChannelTemplates,
getChannels,
getDefaultChannelTemplate,
getFFmpegProfiles,
getFillerPresets,
getLibraryBrowseItems,
getMediaSources,
getWatermarks,
messageFromError,
uploadArtwork,
type ChannelSummary,
type ChannelTemplate,
type CreateChannelFromLineupRequest,
type CreateChannelTemplateRequest,
type FFmpegProfile,
type FillerPreset,
type LibraryBrowseItem,
type MediaSource,
type Watermark
} from '../api';
import {
Badge,
Button,
ChannelLogo,
Dialog,
ConfirmDialog,
IconButton,
Input,
Select,
Spinner,
Switch,
Tooltip
} from '../components';
import {
ADVANCED_KEYS,
applyOverridesToRequest,
FIXED_START_TIME_BEHAVIORS,
IDLE_BEHAVIORS,
MUSIC_VIDEO_CREDITS_MODES,
PLAYBACK_ORDERS,
SONG_VIDEO_MODES,
STREAM_SELECTOR_MODES,
STREAMING_MODE_LABELS,
STREAMING_MODES,
SUBTITLE_MODES,
TRANSCODE_MODES,
effectiveValue,
fillerName,
inheritOption,
templatePlaybackOrder,
useAdvancedOverrides,
type AdvancedKey,
type FixedStartTimeBehavior,
type IdleBehavior,
type MusicVideoCreditsMode,
type Overrides,
type PlaybackOrder,
type PlayoutMode,
type SongVideoMode,
type StreamSelectorMode,
type StreamingMode,
type SubtitleMode,
type TranscodeMode
} from './advancedOptions';
import { useLibraryBrowse } from './libraryBrowse';
import { SmartCollectionDialog } from './SmartCollectionDialog';
// Advanced-options model (enum unions, INHERIT/omit semantics, the override hook)
// is shared with the Auto-Tune DetailPanel — see ./advancedOptions.
// ---- Media-type presentation ----------------------------------------------
// TYPE_ICON / TYPE_LABEL / hueOf are shared with the media browse/search/trash screens
// (see ../media/mediaKinds) so the per-kind icon+label map has a single source of truth.
// ---- Small pure helpers ----------------------------------------------------
const mono: CSSProperties = { fontFamily: 'var(--font-mono)', fontVariantNumeric: 'tabular-nums' };
// Parse a .NET TimeSpan (`[d.]hh:mm:ss[.fffffff]`) or ISO8601 duration to seconds.
function parseDurationSeconds(value: string | null | undefined): number | null {
if (!value) {
return null;
}
const timeSpan = /^(?:(\d+)\.)?(\d{1,2}):(\d{2}):(\d{2})(?:\.\d+)?$/.exec(value);
if (timeSpan) {
const [, days, hours, minutes, seconds] = timeSpan;
return (
(days ? Number(days) * 86400 : 0) + Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds)
);
}
const iso = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/.exec(value);
if (iso) {
const [, days, hours, minutes, seconds] = iso;
return (
(days ? Number(days) * 86400 : 0) +
(hours ? Number(hours) * 3600 : 0) +
(minutes ? Number(minutes) * 60 : 0) +
(seconds ? Number(seconds) : 0)
);
}
return null;
}
function formatDuration(totalSeconds: number): string {
const totalMinutes = Math.round(totalSeconds / 60);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
if (hours && minutes) {
return `${hours}h ${String(minutes).padStart(2, '0')}m`;
}
if (hours) {
return `${hours}h`;
}
return `${minutes}m`;
}
// Meta line for a browse item: duration and/or item count (both nullable -> omitted).
function itemMeta(item: LibraryBrowseItem): string {
const parts: string[] = [];
const durationSeconds = parseDurationSeconds(item.duration);
if (durationSeconds) {
parts.push(formatDuration(durationSeconds));
}
if (item.itemCount) {
parts.push(`${item.itemCount} items`);
}
return parts.join(' · ');
}
function lineupKey(item: LibraryBrowseItem): string {
return `${item.mediaType}:${item.id}`;
}
// The integer part of a channel number that parses; used for AUTO suggestion.
function suggestChannelNumber(channels: ChannelSummary[]): string {
let max = 0;
let seen = false;
for (const channel of channels) {
const parsed = Number.parseFloat(channel.number);
if (Number.isFinite(parsed)) {
seen = true;
max = Math.max(max, Math.floor(parsed));
}
}
return seen ? String(max + 1) : '1';
}
const NUMBER_PATTERN = /^[0-9]+(\.[0-9]{1,2})?$/;
// ---- Segmented control (builder-local, sliding highlight) ------------------
interface SegmentedOption<T extends string> {
value: T;
label?: string;
icon?: ReactNode;
title?: string;
}
function Segmented<T extends string>({
value,
options,
onChange
}: {
value: T;
options: SegmentedOption<T>[];
onChange: (next: T) => void;
}) {
const index = Math.max(
0,
options.findIndex((option) => option.value === value)
);
return (
<div className="ctv-builder-seg" role="group">
<div
className="ctv-builder-seg-thumb"
style={{
width: `calc((100% - 4px) / ${options.length})`,
transform: `translateX(${index * 100}%)`
}}
/>
{options.map((option) => {
const on = option.value === value;
return (
<button
key={option.value}
type="button"
aria-pressed={on}
title={option.title ?? option.label}
className={`ctv-builder-seg-btn ctv-press${on ? ' ctv-builder-seg-btn-on' : ''}`}
onClick={() => onChange(option.value)}
>
{option.icon}
{option.label}
</button>
);
})}
</div>
);
}
// ---- Poster placeholder ----------------------------------------------------
function Poster({ item, width, height, mini }: { item: LibraryBrowseItem; width: number | string; height: number; mini?: boolean }) {
const hue = hueOf(item.title);
const Icon = TYPE_ICON[item.mediaType] ?? Film;
return (
<div
className="ctv-builder-poster"
style={{
width,
height,
background: `linear-gradient(160deg, hsl(${hue} 24% 17%), hsl(${hue} 26% 12%))`
}}
>
{item.artwork ? (
<img src={item.artwork} alt="" loading="lazy" />
) : (
<div
style={{
position: 'absolute',
inset: 0,
backgroundImage: `repeating-linear-gradient(135deg, hsl(${hue} 22% 10% / .55) 0 1px, transparent 1px 9px)`
}}
/>
)}
<span
className="ctv-builder-poster-icon"
style={{ top: mini ? 4 : 7, left: mini ? 4 : 7, color: `hsl(${hue} 30% 68%)` }}
>
<Icon size={mini ? 12 : 15} aria-hidden="true" />
</span>
{!mini && (
<div className="ctv-builder-poster-scrim">
<div className="ctv-builder-poster-title">{item.title}</div>
{itemMeta(item) && <div className="ctv-builder-poster-meta">{itemMeta(item)}</div>}
</div>
)}
</div>
);
}
// ---- Library card ----------------------------------------------------------
function LibCard({
item,
added,
compact,
onAdd,
onSeasons,
onDragStart,
onDragEnd
}: {
item: LibraryBrowseItem;
added: boolean;
compact: boolean;
onAdd: () => void;
onSeasons?: () => void;
onDragStart: () => void;
onDragEnd: () => void;
}) {
const meta = itemMeta(item);
if (compact) {
return (
<div
draggable
onDragStart={onDragStart}
onDragEnd={onDragEnd}
onDoubleClick={onAdd}
title="Double-click or drag to add"
className="ctv-builder-libcard-compact ctv-press"
style={
added
? {
background: 'color-mix(in srgb, var(--action-primary) 14%, transparent)',
borderColor: 'color-mix(in srgb, var(--action-primary) 35%, transparent)'
}
: undefined
}
>
<Poster item={item} width={30} height={40} mini />
<div style={{ flex: 1, minWidth: 0 }}>
<div className="ctv-builder-compact-title">{item.title}</div>
<div className="ctv-builder-compact-meta">
{TYPE_LABEL[item.mediaType]}
{meta && (
<>
{' · '}
<span style={mono}>{meta}</span>
</>
)}
</div>
</div>
{onSeasons && (
<IconButton
size="sm"
title="Browse seasons"
onClick={(event) => {
event.stopPropagation();
onSeasons();
}}
>
<FolderTree size={15} aria-hidden="true" />
</IconButton>
)}
<IconButton size="sm" title={added ? 'Added' : 'Add to lineup'} onClick={onAdd}>
{added ? (
<Check size={15} color="var(--action-primary)" aria-hidden="true" />
) : (
<Plus size={15} aria-hidden="true" />
)}
</IconButton>
</div>
);
}
return (
<div
draggable
onDragStart={onDragStart}
onDragEnd={onDragEnd}
onDoubleClick={onAdd}
title="Double-click or drag to add"
className="ctv-builder-libcard ctv-lift"
>
<div
className="ctv-builder-libcard-poster"
style={added ? { boxShadow: '0 0 0 2px var(--action-primary)' } : undefined}
>
<Poster item={item} width="100%" height={150} />
{added && (
<div className="ctv-builder-added-check">
<Check size={14} aria-hidden="true" />
</div>
)}
{onSeasons && (
<button
type="button"
className="ctv-builder-seasons-btn ctv-press"
title="Browse seasons"
onClick={(event) => {
event.stopPropagation();
onSeasons();
}}
>
<FolderTree size={13} aria-hidden="true" />
Seasons
</button>
)}
</div>
</div>
);
}
// ---- Seasons drill-in ------------------------------------------------------
// Expands a TelevisionShow tile into its seasons so a specific season can be
// added to the lineup without flooding the main grid with per-season tiles
// (issue #180). Mounted fresh per show (keyed on show id) so initial state is
// 'loading' and the fetch effect only ever calls setState in its callbacks.
function SeasonsDialog({
show,
addedKeys,
onAdd,
onClose
}: {
show: LibraryBrowseItem;
addedKeys: Set<string>;
onAdd: (item: LibraryBrowseItem) => void;
onClose: () => void;
}) {
const [seasons, setSeasons] = useState<LibraryBrowseItem[]>([]);
const [totalCount, setTotalCount] = useState(0);
const [status, setStatus] = useState<'loading' | 'error' | 'success'>('loading');
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let active = true;
// Class B (media-library-scoped, spa-conventions §3b): a single bounded page at the
// server cap is intentional here — no real show has anywhere near 100 seasons, so this
// isn't paged to completeness — but #650 found the response's real `totalCount` went
// unread, so a show that somehow did exceed the cap would truncate silently. Read it and
// surface it below instead, same as the other Class B pickers.
getLibraryBrowseItems({ mediaType: 'TelevisionSeason', parentId: show.id, pageSize: 100 })
.then((result) => {
if (active) {
setSeasons(result.page ?? []);
setTotalCount(result.totalCount ?? (result.page ?? []).length);
setStatus('success');
}
})
.catch((loadError: unknown) => {
if (active) {
setError(messageFromError(loadError));
setStatus('error');
}
});
return () => {
active = false;
};
}, [show.id]);
return (
<Dialog
open
onClose={onClose}
title={`Seasons — ${show.title}`}
width={520}
footer={
<Button variant="secondary" onClick={onClose}>
Done
</Button>
}
>
{status === 'loading' ? (
<div className="ctv-builder-empty">
<Spinner size={18} tone="accent" />
</div>
) : status === 'error' ? (
<div className="ctv-builder-empty" role="alert">
{error}
</div>
) : seasons.length === 0 ? (
<div className="ctv-builder-empty">This show has no seasons.</div>
) : (
<>
{seasons.length < totalCount && (
<span className="ctv-field-help">
Showing the first {seasons.length} of {totalCount} seasons.
</span>
)}
<div className="ctv-builder-seasons-list">
{seasons.map((season) => {
const added = addedKeys.has(lineupKey(season));
return (
<div key={lineupKey(season)} className="ctv-builder-seasons-row">
<Poster item={season} width={40} height={54} mini />
<div className="ctv-builder-seasons-row-title">{season.title}</div>
<IconButton size="sm" title={added ? 'Added' : 'Add to lineup'} onClick={() => onAdd(season)}>
{added ? (
<Check size={15} color="var(--action-primary)" aria-hidden="true" />
) : (
<Plus size={15} aria-hidden="true" />
)}
</IconButton>
</div>
);
})}
</div>
</>
)}
</Dialog>
);
}
// ---- Builder support data (templates, pickers, channels) -------------------
interface BuilderData {
channels: ChannelSummary[];
templates: ChannelTemplate[];
defaultTemplate: ChannelTemplate | null;
ffmpegProfiles: FFmpegProfile[];
fillerPresets: FillerPreset[];
watermarks: Watermark[];
mediaSources: MediaSource[];
}
// ---- Main screen -----------------------------------------------------------
interface BuilderDataState {
status: 'loading' | 'error' | 'success';
data: BuilderData | null;
error: string | null;
}
export function ChannelBuilderScreen() {
const [state, setState] = useState<BuilderDataState>({ status: 'loading', data: null, error: null });
const mountedRef = useRef(true);
// Pure async loader: setState runs only in the .then/.catch callbacks, so the
// mount effect never triggers a synchronous state update ('loading' is the
// initial state). The Retry handler resets to loading itself (event handler).
const runLoad = useCallback(() => {
Promise.all([
getChannels(),
getChannelTemplates(),
getDefaultChannelTemplate(),
getFFmpegProfiles(),
getFillerPresets(),
getWatermarks(),
getMediaSources()
])
.then(([channels, templates, defaultTemplate, ffmpegProfiles, fillerPresets, watermarks, mediaSources]) => {
if (!mountedRef.current) {
return;
}
setState({
status: 'success',
data: { channels, templates, defaultTemplate, ffmpegProfiles, fillerPresets, watermarks, mediaSources },
error: null
});
})
.catch((error: unknown) => {
if (!mountedRef.current) {
return;
}
setState({ status: 'error', data: null, error: messageFromError(error) });
});
}, []);
useEffect(() => {
mountedRef.current = true;
runLoad();
return () => {
mountedRef.current = false;
};
}, [runLoad]);
const retry = () => {
setState({ status: 'loading', data: null, error: null });
runLoad();
};
const setData = useCallback((updater: (prev: BuilderData | null) => BuilderData | null) => {
setState((prev) => (prev.status === 'success' ? { ...prev, data: updater(prev.data) } : prev));
}, []);
if (state.status === 'loading') {
return (
<div className="ctv-builder">
<div className="ctv-dashboard-state" style={{ margin: 'auto' }}>
<Spinner size={20} tone="accent" />
<span>Loading channel builder</span>
</div>
</div>
);
}
if (state.status === 'error' || !state.data) {
return (
<div className="ctv-builder">
<div className="ctv-dashboard-error" style={{ margin: 'auto', textAlign: 'center' }}>
<span>Channel builder unavailable</span>
<strong>{state.error}</strong>
<div style={{ marginTop: 12 }}>
<Button variant="secondary" onClick={retry}>
Retry
</Button>
</div>
</div>
</div>
);
}
return <ChannelBuilder data={state.data} onDataChange={setData} />;
}
function ChannelBuilder({
data,
onDataChange
}: {
data: BuilderData;
onDataChange: (updater: (prev: BuilderData | null) => BuilderData | null) => void;
}) {
// ---- library browser state ----
const [source, setSource] = useState<'library' | 'collections'>('library');
const [searchInput, setSearchInput] = useState('');
const [query, setQuery] = useState('');
const [compact, setCompact] = useState(false);
const [libraryId, setLibraryId] = useState<number | null>(null);
// Show whose seasons are being browsed in the drill-in dialog (issue #180).
const [seasonsShow, setSeasonsShow] = useState<LibraryBrowseItem | null>(null);
// Inline "new smart query" authoring (#437): the shared SmartCollectionDialog persists the
// authored query as a real SmartCollection (the lineup references it by smartCollectionId), then
// it is added to the lineup like any browsed collection.
const [smartOpen, setSmartOpen] = useState(false);
const [smartBusy, setSmartBusy] = useState(false);
const [smartError, setSmartError] = useState<string | null>(null);
// debounce search input -> query
useEffect(() => {
const timer = window.setTimeout(() => setQuery(searchInput.trim()), 280);
return () => window.clearTimeout(timer);
}, [searchInput]);
const browse = useLibraryBrowse(source, query, libraryId);
// ---- lineup ----
const [lineup, setLineup] = useState<LibraryBrowseItem[]>([]);
const addedKeys = new Set(lineup.map(lineupKey));
// drag state
const [dragLib, setDragLib] = useState<string | null>(null);
const [dragRow, setDragRow] = useState<number | null>(null);
const [overRow, setOverRow] = useState<number | null>(null);
// ---- rail: identity ----
const [name, setName] = useState('');
// AUTO number: max integer part of existing channel numbers + 1 (empty -> "1").
const suggestion = suggestChannelNumber(data.channels);
const [number, setNumber] = useState(() => suggestion);
// ---- rail: image ----
const [logoFile, setLogoFile] = useState<File | null>(null);
const [logoPreview, setLogoPreview] = useState<string | null>(null);
const [imageError, setImageError] = useState<string | null>(null);
const [separateOpen, setSeparateOpen] = useState(false);
const [dropOver, setDropOver] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
// ---- rail: template + settings ----
const initialTemplate = data.defaultTemplate ?? data.templates.find((t) => t.isDefault) ?? data.templates[0] ?? null;
const [templateId, setTemplateId] = useState<number | null>(initialTemplate?.id ?? null);
const template = data.templates.find((t) => t.id === templateId) ?? initialTemplate;
const [tplOpen, setTplOpen] = useState(false);
const [playbackOrder, setPlaybackOrder] = useState<PlaybackOrder>(
template ? templatePlaybackOrder(template) : 'Chronological'
);
const [playoutMode, setPlayoutMode] = useState<PlayoutMode>((template?.playoutMode as PlayoutMode) ?? 'Continuous');
const [overrides, setOverrides] = useState<Overrides>({});
const [group, setGroup] = useState('ChicoryTV');
const [categories, setCategories] = useState('');
const [advMode, setAdvMode] = useState<'closed' | 'view' | 'override'>('closed');
// ---- create/save flow ----
const [creating, setCreating] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
const [errorRowIndex, setErrorRowIndex] = useState<number | null>(null);
const creatingRef = useRef(false);
// Cache a successful artwork upload keyed by the File object, so retrying a
// failed create with the same image doesn't orphan a fresh upload each attempt.
const uploadedLogoRef = useRef<{ file: File; logo: CreateChannelFromLineupRequest['logo'] } | null>(null);
const [confirmClear, setConfirmClear] = useState(false);
const [confirmCancel, setConfirmCancel] = useState(false);
const [saveOpen, setSaveOpen] = useState(false);
const [saveName, setSaveName] = useState('');
const [saveDesc, setSaveDesc] = useState('');
const [saveBusy, setSaveBusy] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
const railScrollRef = useRef<HTMLDivElement>(null);
// ---- derived ----
const shuffleOn = playbackOrder === 'Shuffle';
const alwaysOn = playoutMode === 'Continuous';
const applyTemplate = (next: ChannelTemplate) => {
setTemplateId(next.id);
setPlaybackOrder(templatePlaybackOrder(next));
setPlayoutMode(next.playoutMode as PlayoutMode);
setOverrides({});
setTplOpen(false);
};
// Any lineup mutation invalidates a server row-index highlight (it pointed at
// the pre-mutation array), so clear the stale create error whenever it changes.
const clearLineupError = () => {
setCreateError(null);
setErrorRowIndex(null);
};
const addItem = (item: LibraryBrowseItem) => {
clearLineupError();
setLineup((current) => (current.some((existing) => lineupKey(existing) === lineupKey(item)) ? current : [...current, item]));
};
// Create the authored query as a SmartCollection, then add it to the lineup as a
// SmartCollection browse item. The constructed item mirrors exactly what the library-browse
// endpoint returns for a smart collection (id = smartCollectionId, kind "Smart"; see
// GetLibraryBrowseItemsHandler.AppendSmartCollections), so lineupKey and the create-request
// mapping treat it identically to a browsed one — no refetch needed.
const handleCreateSmart = (values: { name: string; query: string }) => {
if (smartBusy) {
return;
}
setSmartBusy(true);
setSmartError(null);
createSmartCollection(values)
.then((created) => {
addItem({
id: created.id,
mediaType: 'SmartCollection',
title: created.name,
libraryId: null,
libraryName: null,
artwork: '',
duration: null,
itemCount: null,
collectionKind: 'Smart',
collectionType: 'SmartCollection',
collectionId: null,
multiCollectionId: null,
smartCollectionId: created.id,
rerunCollectionId: null,
mediaItemId: null,
playlistId: null
});
setSmartOpen(false);
})
.catch((error: unknown) => setSmartError(messageFromError(error)))
.finally(() => setSmartBusy(false));
};
const removeAt = (index: number) => {
clearLineupError();
setLineup((current) => current.filter((_, position) => position !== index));
};
// drop onto lineup container (append) or a row (insert at index)
const dropAt = (targetIndex: number | null) => {
clearLineupError();
setLineup((current) => {
if (dragRow != null) {
const next = current.slice();
const [moved] = next.splice(dragRow, 1);
next.splice(targetIndex ?? next.length, 0, moved);
return next;
}
if (dragLib != null) {
const item = browse.state.items.find((candidate) => lineupKey(candidate) === dragLib);
if (item && !current.some((existing) => lineupKey(existing) === dragLib)) {
const next = current.slice();
next.splice(targetIndex ?? next.length, 0, item);
return next;
}
}
return current;
});
setDragLib(null);
setDragRow(null);
setOverRow(null);
};
const totalDurationSeconds = lineup.reduce((sum, item) => sum + (parseDurationSeconds(item.duration) ?? 0), 0);
// ---- validation ----
const trimmedName = name.trim();
const numberValid = NUMBER_PATTERN.test(number.trim());
const numberUnique = !data.channels.some((channel) => channel.number === number.trim());
const numberError = !number.trim()
? null
: !numberValid
? 'Use digits, optionally with up to two decimals (e.g. 5 or 13.1).'
: !numberUnique
? 'That channel number is already in use.'
: null;
const rowErrorFor = (item: LibraryBrowseItem): string | null => {
if ((item.mediaType === 'RerunCollection' || item.mediaType === 'Playlist') && lineup.length > 1) {
return 'Only valid alone';
}
if (item.mediaType === 'MultiCollection' && !(playbackOrder === 'Shuffle' || playbackOrder === 'ShuffleInOrder')) {
return 'Requires Shuffle';
}
return null;
};
const rowErrors = lineup.map(rowErrorFor);
const firstRowErrorIndex = rowErrors.findIndex((error) => error != null);
const hasRowError = firstRowErrorIndex >= 0;
const createBlockedReason =
!trimmedName
? 'Name the channel and add at least one item'
: lineup.length === 0
? 'Add at least one item to the lineup'
: !group.trim()
? 'Channel group cannot be empty'
: numberError || !number.trim()
? 'Enter a valid, unique channel number'
: templateId == null
? 'Select a channel template'
: hasRowError
? `Fix lineup item ${firstRowErrorIndex + 1}: ${rowErrors[firstRowErrorIndex]}`
: null;
const canCreate = createBlockedReason == null;
// ---- image handling ----
const readImage = (file: File | undefined | null) => {
if (!file) {
return;
}
if (!file.type.startsWith('image/')) {
setImageError('Choose an image file.');
return;
}
if (file.size >= 30 * 1024 * 1024) {
setImageError('Image is too large (max 30 MB).');
return;
}
setImageError(null);
setLogoFile(file);
const reader = new FileReader();
reader.onload = () => setLogoPreview(typeof reader.result === 'string' ? reader.result : null);
reader.readAsDataURL(file);
};
// ---- advanced panel accordion height ----
const advFieldsRef = useRef<HTMLDivElement>(null);
const [advMaxHeight, setAdvMaxHeight] = useState(0);
// Measure the fields' natural height for the max-height accordion animation.
// Reading layout then writing state is the canonical useLayoutEffect use.
useLayoutEffect(() => {
const next = advMode === 'closed' ? 0 : (advFieldsRef.current?.scrollHeight ?? 0);
setAdvMaxHeight(next);
}, [advMode]);
// ---- create ----
const handleCreate = async () => {
if (creatingRef.current || !canCreate || templateId == null) {
return;
}
creatingRef.current = true;
setCreating(true);
setCreateError(null);
setErrorRowIndex(null);
try {
let logo: CreateChannelFromLineupRequest['logo'] = { path: '', contentType: '' };
if (logoFile) {
if (uploadedLogoRef.current?.file === logoFile) {
logo = uploadedLogoRef.current.logo;
} else {
const uploaded = await uploadArtwork(logoFile, 'logo');
logo = { path: uploaded.path, contentType: uploaded.contentType };
uploadedLogoRef.current = { file: logoFile, logo };
}
}
// advanced null/omitted = inherit template value (handler coalesces with ??); a field set to
// the CLEAR sentinel is translated into advanced.clear (force to none) — see #135.
// applyOverridesToRequest copies present set-values and attaches `clear`.
const advanced: CreateChannelFromLineupRequest['advanced'] = applyOverridesToRequest(
{ playbackOrder, playoutMode },
overrides
);
const body: CreateChannelFromLineupRequest = {
name: trimmedName,
number: number.trim(),
group: group.trim(),
categories: categories.trim(),
logo,
isEnabled: true,
showInEpg: true,
templateId,
advanced,
lineup: lineup.map((item) => ({
mediaType: item.mediaType,
collectionType: item.collectionType,
collectionId: item.collectionId,
multiCollectionId: item.multiCollectionId,
smartCollectionId: item.smartCollectionId,
rerunCollectionId: item.rerunCollectionId,
mediaItemId: item.mediaItemId,
playlistId: item.playlistId
}))
};
await createChannelFromLineup(body);
navigateToPath('/app/channels');
} catch (error: unknown) {
let message = messageFromError(error);
if (error instanceof ApiError) {
if (error.status === 413) {
message = 'Image is too large (max 30 MB).';
}
const detail = error.detail;
const match = detail ? /lineup\[(\d+)\]/.exec(detail) : null;
if (match) {
setErrorRowIndex(Number(match[1]));
}
}
setCreateError(message);
creatingRef.current = false;
setCreating(false);
}
};
// ---- save template ----
const openSaveTemplate = () => {
setSaveName('');
setSaveDesc('');
setSaveError(null);
setSaveOpen(true);
setTplOpen(false);
};
const handleSaveTemplate = async () => {
if (saveBusy || !template) {
return;
}
if (!saveName.trim()) {
setSaveError('Give the template a name.');
return;
}
setSaveBusy(true);
setSaveError(null);
// Compose from the same effective-value helper the panel renders with, so
// what's saved equals what's shown. Overrides never hold null/'' (inherited
// fields are absent), so effectiveValue is exactly the displayed value.
const eff = <T,>(key: AdvancedKey): T => effectiveValue(key, template, overrides) as T;
try {
const requestBody: CreateChannelTemplateRequest = {
name: saveName.trim(),
description: saveDesc.trim(),
ffmpegProfileId: eff('ffmpegProfileId'),
watermarkId: eff('watermarkId'),
fallbackFillerId: eff('fallbackFillerId'),
preRollFillerId: eff('preRollFillerId'),
midRollFillerId: eff('midRollFillerId'),
postRollFillerId: eff('postRollFillerId'),
streamSelectorMode: eff('streamSelectorMode'),
streamSelector: eff('streamSelector'),
preferredAudioLanguageCode: eff('preferredAudioLanguageCode'),
preferredAudioTitle: eff('preferredAudioTitle'),
playoutSource: template.playoutSource,
// toggles are the source of truth for these two:
playoutMode,
streamingMode: eff('streamingMode'),
preferredSubtitleLanguageCode: eff('preferredSubtitleLanguageCode'),
subtitleMode: eff('subtitleMode'),
musicVideoCreditsMode: eff('musicVideoCreditsMode'),
musicVideoCreditsTemplate: template.musicVideoCreditsTemplate,
songVideoMode: eff('songVideoMode'),
transcodeMode: eff('transcodeMode'),
idleBehavior: eff('idleBehavior'),
shuffleScheduleItems: shuffleOn,
randomStartPoint: eff('randomStartPoint'),
fixedStartTimeBehavior: eff('fixedStartTimeBehavior')
};
const created = await createChannelTemplate(requestBody);
const templates = await getChannelTemplates();
onDataChange((prev) => (prev ? { ...prev, templates } : prev));
applyTemplate(created);
setSaveOpen(false);
} catch (error: unknown) {
setSaveError(messageFromError(error));
} finally {
setSaveBusy(false);
}
};
// ---- cancel ----
const dirty = lineup.length > 0 || trimmedName.length > 0 || logoFile != null;
const handleCancel = () => {
if (dirty) {
setConfirmCancel(true);
} else {
navigateToPath('/app/channels');
}
};
// ---- filter chips (library mode) ----
const libraryChips = data.mediaSources.flatMap((mediaSource) =>
mediaSource.libraries.map((lib) => ({ id: lib.id, name: lib.name }))
);
const showAuto = number.trim() === suggestion;
const items = browse.state.items;
const serverRowIndex = errorRowIndex;
return (
<div className="ctv-builder">
{/* toolbar */}
<div className="ctv-builder-toolbar">
<span className="ctv-builder-toolbar-tile">
<Plus size={19} aria-hidden="true" />
</span>
<div className="ctv-builder-toolbar-titles">
<div className="ctv-builder-title">New Channel</div>
<div className="ctv-builder-summary">
Build from your library — <span style={mono}>{lineup.length}</span> in lineup ·{' '}
<span style={mono}>{formatDuration(totalDurationSeconds)}</span>
</div>
</div>
<Button variant="ghost" onClick={handleCancel} disabled={creating}>
Cancel
</Button>
<Tooltip placement="bottom" label={canCreate ? 'Creates the channel, schedule & playout' : createBlockedReason}>
<Button
variant="primary"
disabled={!canCreate || creating}
loading={creating}
startIcon={<Check size={15} aria-hidden="true" />}
onClick={handleCreate}
>
Create Channel
</Button>
</Tooltip>
</div>
{createError && (
<div className="ctv-builder-error" role="alert">
<span>{createError}</span>
</div>
)}
{/* body */}
<div className="ctv-builder-body">
{/* LEFT — library browser */}
<section className="ctv-builder-col">
<div className="ctv-builder-col-head">
<div className="ctv-builder-headrow">
<Segmented
value={source}
onChange={(next) => {
setSource(next);
setLibraryId(null);
}}
options={[
{ value: 'library', label: 'Library', icon: <Library size={13} aria-hidden="true" /> },
{ value: 'collections', label: 'Collections', icon: <FolderTree size={13} aria-hidden="true" /> }
]}
/>
<span style={{ flex: 1 }} />
<Segmented
value={compact ? 'list' : 'grid'}
onChange={(next) => setCompact(next === 'list')}
options={[
{ value: 'grid', icon: <LayoutGrid size={13} aria-hidden="true" />, title: 'Poster grid' },
{ value: 'list', icon: <Rows3 size={13} aria-hidden="true" />, title: 'Compact list' }
]}
/>
</div>
<Input
size="sm"
value={searchInput}
onChange={(event) => setSearchInput(event.target.value)}
leadingIcon={<Search size={15} aria-hidden="true" />}
placeholder={source === 'collections' ? 'Search collections…' : 'Search shows & movies…'}
/>
{source === 'library' && libraryChips.length > 0 && (
<div className="ctv-builder-chiprow">
<button
type="button"
className={`ctv-builder-chip ctv-press${libraryId == null ? ' ctv-builder-chip-on' : ''}`}
onClick={() => setLibraryId(null)}
>
All
</button>
{libraryChips.map((chip) => (
<button
key={chip.id}
type="button"
className={`ctv-builder-chip ctv-press${libraryId === chip.id ? ' ctv-builder-chip-on' : ''}`}
onClick={() => setLibraryId(chip.id)}
>
{chip.name}
</button>
))}
</div>
)}
{source === 'collections' && (
<div className="ctv-builder-chiprow">
<Button
size="sm"
variant="secondary"
startIcon={<Sparkles size={13} aria-hidden="true" />}
onClick={() => {
setSmartError(null);
setSmartOpen(true);
}}
>
New smart query
</Button>
</div>
)}
</div>
<div className="ctv-builder-scroll ctv-hide-sb">
<div className="ctv-builder-scroll-body">
{browse.state.status === 'loading' ? (
<div className="ctv-builder-empty">
<Spinner size={18} tone="accent" />
</div>
) : browse.state.status === 'error' ? (
<div className="ctv-builder-empty" role="alert">
{browse.state.error}
</div>
) : items.length === 0 ? (
<div className="ctv-builder-empty">No titles match.</div>
) : (
<>
<div className={compact ? 'ctv-builder-compact-list' : 'ctv-builder-grid'}>
{items.map((item) => (
<LibCard
key={lineupKey(item)}
item={item}
compact={compact}
added={addedKeys.has(lineupKey(item))}
onAdd={() => addItem(item)}
onSeasons={
item.mediaType === 'TelevisionShow' ? () => setSeasonsShow(item) : undefined
}
onDragStart={() => setDragLib(lineupKey(item))}
onDragEnd={() => {
if (dragLib != null) {
const dragged = items.find((candidate) => lineupKey(candidate) === dragLib);
if (dragged) {
addItem(dragged);
}
}
setDragLib(null);
setDragRow(null);
setOverRow(null);
}}
/>
))}
</div>
{browse.canLoadMore && (
<div className="ctv-builder-loadmore">
<Button variant="secondary" size="sm" loading={browse.loadingMore} onClick={browse.loadMore}>
Load more
</Button>
{browse.loadMoreError && (
<span className="ctv-field-error" role="alert">
{browse.loadMoreError}
</span>
)}
</div>
)}
</>
)}
</div>
</div>
</section>
{/* CENTER — lineup */}
<section
className="ctv-builder-col"
onDragOver={(event) => {
if (dragLib != null) {
event.preventDefault();
}
}}
onDrop={() => {
if (dragLib != null) {
dropAt(null);
}
}}
>
<div className="ctv-builder-col-head ctv-builder-col-head-row">
<span className="ctv-builder-eyebrow">Lineup</span>
<Badge tone={shuffleOn ? 'accent' : 'neutral'}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
{shuffleOn ? <Shuffle size={11} aria-hidden="true" /> : <ListOrdered size={11} aria-hidden="true" />}
{shuffleOn ? 'Shuffled' : 'Sequential'}
</span>
</Badge>
<span style={{ flex: 1 }} />
{lineup.length > 0 && (
<button
type="button"
className="ctv-builder-linkbtn"
onClick={() => setConfirmClear(true)}
>
Clear
</button>
)}
</div>
<div className="ctv-builder-scroll ctv-hide-sb">
<div className="ctv-builder-scroll-body">
{lineup.length === 0 ? (
<div className={`ctv-builder-lineup-empty${dragLib != null ? ' ctv-builder-lineup-empty-over' : ''}`}>
<ListVideo size={26} aria-hidden="true" />
<div style={{ font: 'var(--text-sm)/1.5 var(--font-sans)', maxWidth: 240 }}>
This channel has no content yet. Double-click or drag titles from the library to build the lineup.
</div>
</div>
) : (
<div className="ctv-builder-lineup-list">
{lineup.map((item, index) => {
const rowError = rowErrors[index];
const serverError = serverRowIndex === index;
return (
<div
key={`${lineupKey(item)}-${index}`}
className={`ctv-builder-lineup-row ctv-lift${rowError || serverError ? ' ctv-builder-lineup-row-error' : ''}`}
style={{
opacity: dragRow === index ? 0.35 : 1,
boxShadow: overRow === index && dragRow !== index ? '0 -2px 0 var(--action-primary)' : 'none'
}}
draggable
onDragStart={() => setDragRow(index)}
onDragEnd={() => {
setDragRow(null);
setOverRow(null);
}}
onDragOver={(event) => {
event.preventDefault();
setOverRow(index);
}}
onDrop={(event) => {
event.stopPropagation();
dropAt(index);
}}
>
<span className="ctv-builder-grip" title="Drag to reorder">
<GripVertical size={16} aria-hidden="true" />
</span>
<span className="ctv-builder-order">
{shuffleOn ? (
<Shuffle size={13} color="var(--text-disabled)" aria-hidden="true" />
) : (
index + 1
)}
</span>
<Poster item={item} width={34} height={46} mini />
<div className="ctv-builder-row-main">
<div className="ctv-builder-row-title">{item.title}</div>
<div className="ctv-builder-row-sub">
{TYPE_LABEL[item.mediaType]}
{item.libraryName ? ` · ${item.libraryName}` : ''}
</div>
</div>
{rowError && (
<Badge tone="error">
<span>{rowError}</span>
</Badge>
)}
<span className="ctv-builder-row-dur" style={mono}>
{parseDurationSeconds(item.duration)
? formatDuration(parseDurationSeconds(item.duration) as number)
: ''}
</span>
<IconButton size="sm" title="Remove" onClick={() => removeAt(index)}>
<X size={15} aria-hidden="true" />
</IconButton>
</div>
);
})}
<div className="ctv-builder-lineup-hint">
<Plus size={14} aria-hidden="true" />
Double-click or drag more titles to add
</div>
</div>
)}
</div>
</div>
</section>
{/* RIGHT — settings rail */}
<aside className="ctv-builder-col ctv-builder-col-rail">
<div className="ctv-builder-scroll ctv-builder-rail-scroll ctv-hide-sb" ref={railScrollRef}>
{/* identity */}
<div className="ctv-builder-rail-block">
<Input
label="Channel name"
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="e.g. Retro Cartoons"
/>
<Input
label="Number"
value={number}
onChange={(event) => setNumber(event.target.value)}
error={numberError}
trailing={showAuto ? <span className="ctv-builder-auto-chip">AUTO</span> : undefined}
/>
</div>
{/* image */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<div
className={`ctv-builder-dropzone${dropOver ? ' ctv-builder-dropzone-over' : ''}`}
onDragOver={(event) => {
event.preventDefault();
setDropOver(true);
}}
onDragLeave={() => setDropOver(false)}
onDrop={(event) => {
event.preventDefault();
setDropOver(false);
readImage(event.dataTransfer.files && event.dataTransfer.files[0]);
}}
onClick={() => fileInputRef.current?.click()}
>
<ChannelLogo name={name || 'New Channel'} src={logoPreview} size={52} radius="var(--radius-sm)" />
<div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 3 }}>
<div style={{ font: 'var(--weight-medium) var(--text-xs)/1 var(--font-sans)', color: 'var(--text-primary)' }}>
{logoPreview ? 'Channel image set' : 'Drop channel image'}
</div>
<div style={{ font: 'var(--text-2xs)/1.35 var(--font-sans)', color: 'var(--text-secondary)' }}>
Used as both the guide logo and the on-screen bug.
</div>
</div>
<input
ref={fileInputRef}
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={(event) => readImage(event.target.files && event.target.files[0])}
/>
</div>
{imageError && (
<div style={{ font: 'var(--text-2xs)/1.35 var(--font-sans)', color: 'var(--status-error)' }} role="alert">
{imageError}
</div>
)}
<div className="ctv-builder-preview-grid">
<div className="ctv-builder-preview-tile">
<div className="ctv-builder-eyebrow" style={{ marginBottom: 8 }}>
Guide logo
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
<ChannelLogo name={name || 'New Channel'} src={logoPreview} size={30} radius="var(--radius-xs)" />
<div style={{ minWidth: 0 }}>
<div
style={{
font: 'var(--weight-medium) var(--text-2xs)/1.1 var(--font-sans)',
color: 'var(--text-primary)',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
}}
>
{name || 'New Channel'}
</div>
<div style={{ ...mono, font: '9px/1 var(--font-mono)', color: 'var(--text-disabled)' }}>listing</div>
</div>
</div>
</div>
<div className="ctv-builder-preview-tile">
<div className="ctv-builder-eyebrow" style={{ marginBottom: 8 }}>
On-screen bug
</div>
<div
style={{
position: 'relative',
height: 42,
borderRadius: 'var(--radius-xs)',
overflow: 'hidden',
background: 'linear-gradient(160deg,#1a1d24,#0e1014)',
backgroundImage: 'repeating-linear-gradient(135deg, rgba(255,255,255,.03) 0 1px, transparent 1px 7px)'
}}
>
<div style={{ position: 'absolute', bottom: 5, right: 5, opacity: 0.9 }}>
<ChannelLogo name={name || 'New Channel'} src={logoPreview} size={22} radius="3px" />
</div>
</div>
</div>
</div>
<button type="button" className="ctv-builder-disclosure" onClick={() => setSeparateOpen((open) => !open)}>
{separateOpen ? <ChevronDown size={13} aria-hidden="true" /> : <ChevronRight size={13} aria-hidden="true" />}
Set logo &amp; bug separately
</button>
{separateOpen && (
<div className="ctv-builder-sep-grid">
<Button
size="sm"
variant="secondary"
startIcon={<ImageIcon size={14} aria-hidden="true" />}
onClick={() => fileInputRef.current?.click()}
>
Logo image
</Button>
<Tooltip label="Separate bug image coming with watermark upload support">
<Button size="sm" variant="secondary" disabled startIcon={<ImageIcon size={14} aria-hidden="true" />}>
Bug image
</Button>
</Tooltip>
</div>
)}
</div>
{/* friendly toggles */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{/* div, not label: the Switch is a labelable <button>, so a wrapping
label would forward its activation AND bubble the click, firing
the toggle twice. The row's onClick is the single toggle source. */}
<div
className="ctv-builder-toggle-row"
onClick={() => setPlaybackOrder(shuffleOn ? 'Chronological' : 'Shuffle')}
>
<div style={{ flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<span className="ctv-builder-toggle-label">Shuffle</span>
{template && playbackOrder !== templatePlaybackOrder(template) && (
<span className="ctv-builder-overrides-tag">overrides template</span>
)}
</div>
<div className="ctv-builder-toggle-help">
{shuffleOn ? 'Plays in a random order.' : 'Plays in sequence (chronological).'}
</div>
</div>
{/* presentational - the row's onClick is the single toggle source */}
<Switch checked={shuffleOn} />
</div>
<div className="ctv-builder-hairline" />
<div
className={`ctv-builder-toggle-row ctv-builder-toggle-live${alwaysOn ? ' ctv-builder-toggle-live-on' : ''}`}
onClick={() => setPlayoutMode(alwaysOn ? 'OnDemand' : 'Continuous')}
>
<span style={{ display: 'inline-flex', marginTop: 1, color: 'var(--ctv-live)', flex: '0 0 auto' }}>
<Radio size={16} aria-hidden="true" />
</span>
<div style={{ flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<span className="ctv-builder-toggle-label">Always playing</span>
{template && playoutMode !== template.playoutMode && (
<span className="ctv-builder-overrides-tag">overrides template</span>
)}
{alwaysOn && (
<span className="ctv-builder-live-pill">
<span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--ctv-live)' }} />
LIVE
</span>
)}
</div>
<div className="ctv-builder-toggle-help">
Like live TV — advances on schedule even when nobody is watching.
</div>
</div>
{/* presentational - the row's onClick is the single toggle source */}
<Switch checked={alwaysOn} />
</div>
</div>
{/* channel template */}
<div>
<div className="ctv-builder-eyebrow" style={{ marginBottom: 8 }}>
Channel Template
</div>
{data.templates.length === 0 ? (
<div className="ctv-builder-tpl-empty">
No channel templates exist yet. Create one in Settings before building a channel — a template supplies
the required technical configuration.
</div>
) : (
<>
<button type="button" className="ctv-builder-tpl-button ctv-press" onClick={() => setTplOpen((open) => !open)}>
<span className="ctv-builder-tpl-tile">
<SlidersHorizontal size={15} aria-hidden="true" />
</span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span className="ctv-builder-tpl-name">{template?.name}</span>
{template && !template.isSystem && (
<Badge tone="neutral">Custom</Badge>
)}
</div>
<div className="ctv-builder-tpl-desc">{template?.description}</div>
</div>
{tplOpen ? <ChevronUp size={15} color="var(--text-disabled)" aria-hidden="true" /> : <ChevronDown size={15} color="var(--text-disabled)" aria-hidden="true" />}
</button>
{tplOpen && (
<div className="ctv-builder-tpl-list">
{data.templates.map((option) => {
const on = option.id === templateId;
return (
<button
key={option.id}
type="button"
className={`ctv-builder-tpl-option ctv-press${on ? ' ctv-builder-tpl-option-on' : ''}`}
onClick={() => applyTemplate(option)}
>
{on ? (
<CircleCheck size={15} color="var(--action-primary)" aria-hidden="true" />
) : (
<Circle size={15} color="var(--text-disabled)" aria-hidden="true" />
)}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span className="ctv-builder-tpl-option-name">{option.name}</span>
{!option.isSystem && <Badge tone="neutral">Custom</Badge>}
</div>
<div className="ctv-builder-tpl-desc">{option.description}</div>
</div>
</button>
);
})}
<button type="button" className="ctv-builder-tpl-save" onClick={openSaveTemplate}>
<Save size={14} aria-hidden="true" />
Save current settings as template…
</button>
</div>
)}
{template && (
<div className="ctv-builder-config-chips">
{templateChips(template, data.ffmpegProfiles, playbackOrder, playoutMode).map((chip) => (
<span
key={chip}
className="ctv-builder-config-chip"
style={/\d/.test(chip) ? mono : undefined}
>
{chip}
</span>
))}
</div>
)}
</>
)}
</div>
{/* advanced */}
{template && (
<AdvancedPanel
template={template}
overrides={overrides}
setOverrides={setOverrides}
playbackOrder={playbackOrder}
setPlaybackOrder={setPlaybackOrder}
playoutMode={playoutMode}
setPlayoutMode={setPlayoutMode}
group={group}
setGroup={setGroup}
categories={categories}
setCategories={setCategories}
mode={advMode}
setMode={setAdvMode}
maxHeight={advMaxHeight}
fieldsRef={advFieldsRef}
scrollerRef={railScrollRef}
ffmpegProfiles={data.ffmpegProfiles}
fillerPresets={data.fillerPresets}
watermarks={data.watermarks}
/>
)}
</div>
</aside>
</div>
{seasonsShow && (
<SeasonsDialog
key={seasonsShow.id}
show={seasonsShow}
addedKeys={addedKeys}
onAdd={addItem}
onClose={() => setSeasonsShow(null)}
/>
)}
<SmartCollectionDialog
key={`smart-${smartOpen}`}
busy={smartBusy}
error={smartError}
initial={null}
onCancel={() => setSmartOpen(false)}
onSubmit={handleCreateSmart}
open={smartOpen}
/>
<ConfirmDialog
open={confirmClear}
title="Clear the lineup?"
message="This removes every item from the channel lineup."
confirmLabel="Clear lineup"
tone="danger"
onConfirm={() => {
clearLineupError();
setLineup([]);
setConfirmClear(false);
}}
onCancel={() => setConfirmClear(false)}
/>
<ConfirmDialog
open={confirmCancel}
title="Discard this channel?"
message="Your lineup and settings for this new channel will be discarded."
confirmLabel="Discard"
tone="danger"
onConfirm={() => {
setConfirmCancel(false);
navigateToPath('/app/channels');
}}
onCancel={() => setConfirmCancel(false)}
/>
<Dialog
open={saveOpen}
onClose={() => setSaveOpen(false)}
title="Save as channel template"
width={420}
footer={
<>
<Button variant="secondary" onClick={() => setSaveOpen(false)} disabled={saveBusy}>
Cancel
</Button>
<Button variant="primary" onClick={handleSaveTemplate} loading={saveBusy} disabled={saveBusy}>
Save template
</Button>
</>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<Input label="Template name" value={saveName} onChange={(event) => setSaveName(event.target.value)} placeholder="e.g. Retro Saturday AM" />
<Input label="Description" value={saveDesc} onChange={(event) => setSaveDesc(event.target.value)} placeholder="Optional one-line summary" />
{saveError && (
<div style={{ font: 'var(--text-xs)/1.4 var(--font-sans)', color: 'var(--status-error)' }} role="alert">
{saveError}
</div>
)}
</div>
</Dialog>
</div>
);
}
// Config chips derived from real template fields (4-6 chips).
function templateChips(
template: ChannelTemplate,
ffmpegProfiles: FFmpegProfile[],
playbackOrder: PlaybackOrder,
playoutMode: PlayoutMode
): string[] {
const chips: string[] = [];
chips.push(STREAMING_MODE_LABELS[template.streamingMode as StreamingMode] ?? template.streamingMode);
const profile = ffmpegProfiles.find((candidate) => candidate.id === template.ffmpegProfileId);
if (profile?.name) {
chips.push(profile.name);
}
chips.push(playbackOrder === 'Shuffle' || playbackOrder === 'ShuffleInOrder' ? 'Shuffle' : 'Sequential');
chips.push(playoutMode === 'Continuous' ? 'Always on' : 'On demand');
const fillers: string[] = [];
if (template.preRollFillerId != null) {
fillers.push('Pre');
}
if (template.midRollFillerId != null) {
fillers.push('Mid');
}
if (template.postRollFillerId != null) {
fillers.push('Post');
}
if (fillers.length > 0) {
chips.push(`${fillers.join('/')} filler`);
}
if (template.subtitleMode && template.subtitleMode !== 'None') {
chips.push(`Subtitles: ${template.subtitleMode}`);
}
return chips.slice(0, 6);
}
// ---- Advanced panel --------------------------------------------------------
function AdvancedPanel({
template,
overrides,
setOverrides,
playbackOrder,
setPlaybackOrder,
playoutMode,
setPlayoutMode,
group,
setGroup,
categories,
setCategories,
mode,
setMode,
maxHeight,
fieldsRef,
scrollerRef,
ffmpegProfiles,
fillerPresets,
watermarks
}: {
template: ChannelTemplate;
overrides: Overrides;
setOverrides: (updater: (prev: Overrides) => Overrides) => void;
playbackOrder: PlaybackOrder;
setPlaybackOrder: (next: PlaybackOrder) => void;
playoutMode: PlayoutMode;
setPlayoutMode: (next: PlayoutMode) => void;
group: string;
setGroup: (next: string) => void;
categories: string;
setCategories: (next: string) => void;
mode: 'closed' | 'view' | 'override';
setMode: (next: 'closed' | 'view' | 'override') => void;
maxHeight: number;
fieldsRef: React.RefObject<HTMLDivElement | null>;
scrollerRef: React.RefObject<HTMLDivElement | null>;
ffmpegProfiles: FFmpegProfile[];
fillerPresets: FillerPreset[];
watermarks: Watermark[];
}) {
const override = mode === 'override';
const overrideCount = Object.keys(overrides).length;
const fieldCount = ADVANCED_KEYS.length + 2; // + playbackOrder + playoutMode (toggled)
// Shared INHERIT/omit field adapters (see ./advancedOptions): a select set to
// INHERIT or a text input cleared to '' removes the override (field omitted).
const { setOverride, idSelectOptions, selValue, onSelect, textValue, onText, textPlaceholder, boolValue } =
useAdvancedOverrides(template, overrides, setOverrides);
// Opening a panel scrolls the rail so the Advanced header sits near the top
// (ported from the prototype ChannelBuilder.jsx toggle()).
const rootRef = useRef<HTMLDivElement>(null);
const toggleMode = (next: 'view' | 'override') => {
const nextMode = mode === next ? 'closed' : next;
setMode(nextMode);
if (nextMode !== 'closed' && scrollerRef.current && rootRef.current) {
const scroller = scrollerRef.current;
const root = rootRef.current;
requestAnimationFrame(() => {
const target = scroller.scrollTop + root.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 20;
scroller.scrollTo({ top: Math.max(0, target), behavior: 'smooth' });
});
}
};
return (
<div className="ctv-builder-adv" ref={rootRef}>
<div className="ctv-builder-adv-head">
<SlidersHorizontal size={16} color="var(--text-secondary)" aria-hidden="true" />
<span className="ctv-builder-adv-head-title">Advanced</span>
<span style={{ flex: 1 }} />
<span className="ctv-builder-adv-count">
{fieldCount} fields{overrideCount > 0 ? ` · ${overrideCount} overridden` : ''} · {template.name}
</span>
</div>
<div className="ctv-builder-adv-tabs">
<button
type="button"
className={`ctv-builder-adv-tab ctv-press${override ? ' ctv-builder-adv-tab-on' : ''}`}
onClick={() => toggleMode('override')}
>
<SquarePen size={14} aria-hidden="true" />
{override ? 'Overriding' : 'Override settings'}
</button>
<button
type="button"
className={`ctv-builder-adv-tab ctv-press${mode === 'view' ? ' ctv-builder-adv-tab-on' : ''}`}
onClick={() => toggleMode('view')}
>
<Eye size={14} aria-hidden="true" />
View defaults
</button>
</div>
<div className="ctv-builder-adv-panel" style={{ maxHeight }}>
<div className="ctv-builder-adv-fields" ref={fieldsRef}>
<div className="ctv-builder-adv-info">
<Info
size={13}
color={override ? 'var(--action-primary)' : 'var(--text-disabled)'}
aria-hidden="true"
/>
{override
? 'Editing these overrides the template for this channel only.'
: `Read-only — inherited from the ${template.name} template. Turn on Override to edit.`}
</div>
{override ? (
<>
<AdvGroup label="Streaming">
<Select
size="sm"
label="FFmpeg profile"
value={selValue('ffmpegProfileId')}
options={[
inheritOption(
ffmpegProfiles.find((p) => p.id === template.ffmpegProfileId)?.name ??
`#${template.ffmpegProfileId}`
),
...ffmpegProfiles.map((profile) => ({ value: String(profile.id), label: profile.name ?? `#${profile.id}` }))
]}
onChange={onSelect('ffmpegProfileId', Number)}
/>
<Select
size="sm"
label="Streaming mode"
value={selValue('streamingMode')}
options={[
inheritOption(STREAMING_MODE_LABELS[template.streamingMode as StreamingMode] ?? template.streamingMode),
...STREAMING_MODES.map((value) => ({ value, label: STREAMING_MODE_LABELS[value] }))
]}
onChange={onSelect('streamingMode', (raw) => raw as StreamingMode)}
/>
<Select
size="sm"
label="Transcode mode"
value={selValue('transcodeMode')}
options={[
inheritOption(template.transcodeMode),
...TRANSCODE_MODES.map((value) => ({ value, label: value }))
]}
onChange={onSelect('transcodeMode', (raw) => raw as TranscodeMode)}
/>
</AdvGroup>
<AdvGroup label="Filler">
<Select
size="sm"
label="Fallback filler"
value={selValue('fallbackFillerId')}
options={idSelectOptions('fallbackFillerId', fillerPresets)}
onChange={onSelect('fallbackFillerId', Number)}
/>
<Select
size="sm"
label="Pre-roll filler"
value={selValue('preRollFillerId')}
options={idSelectOptions('preRollFillerId', fillerPresets)}
onChange={onSelect('preRollFillerId', Number)}
/>
<Select
size="sm"
label="Mid-roll filler"
value={selValue('midRollFillerId')}
options={idSelectOptions('midRollFillerId', fillerPresets)}
onChange={onSelect('midRollFillerId', Number)}
/>
<Select
size="sm"
label="Post-roll filler"
value={selValue('postRollFillerId')}
options={idSelectOptions('postRollFillerId', fillerPresets)}
onChange={onSelect('postRollFillerId', Number)}
/>
<Select
size="sm"
label="Watermark"
value={selValue('watermarkId')}
options={idSelectOptions('watermarkId', watermarks)}
onChange={onSelect('watermarkId', Number)}
/>
</AdvGroup>
<AdvGroup label="Playback">
<Select
size="sm"
label="Playback order"
value={playbackOrder}
options={[...PLAYBACK_ORDERS]}
onChange={(event) => setPlaybackOrder(event.target.value as PlaybackOrder)}
/>
<Input
size="sm"
label="Preferred audio language"
value={textValue('preferredAudioLanguageCode')}
onChange={onText('preferredAudioLanguageCode')}
placeholder={textPlaceholder('preferredAudioLanguageCode', 'e.g. eng')}
/>
<Input
size="sm"
label="Preferred subtitle language"
value={textValue('preferredSubtitleLanguageCode')}
onChange={onText('preferredSubtitleLanguageCode')}
placeholder={textPlaceholder('preferredSubtitleLanguageCode', 'e.g. eng')}
/>
<Input
size="sm"
label="Preferred audio title"
value={textValue('preferredAudioTitle')}
onChange={onText('preferredAudioTitle')}
placeholder={textPlaceholder('preferredAudioTitle')}
/>
<Select
size="sm"
label="Subtitle mode"
value={selValue('subtitleMode')}
options={[
inheritOption(template.subtitleMode),
...SUBTITLE_MODES.map((value) => ({ value, label: value }))
]}
onChange={onSelect('subtitleMode', (raw) => raw as SubtitleMode)}
/>
<Select
size="sm"
label="Stream selector mode"
value={selValue('streamSelectorMode')}
options={[
inheritOption(template.streamSelectorMode),
...STREAM_SELECTOR_MODES.map((value) => ({ value, label: value }))
]}
onChange={onSelect('streamSelectorMode', (raw) => raw as StreamSelectorMode)}
/>
<Input
size="sm"
label="Stream selector"
value={textValue('streamSelector')}
onChange={onText('streamSelector')}
placeholder={textPlaceholder('streamSelector')}
/>
</AdvGroup>
<AdvGroup label="Behavior">
<Select
size="sm"
label="Playout mode"
value={playoutMode}
options={['Continuous', 'OnDemand']}
onChange={(event) => setPlayoutMode(event.target.value as PlayoutMode)}
/>
<Select
size="sm"
label="Music video credits"
value={selValue('musicVideoCreditsMode')}
options={[
inheritOption(template.musicVideoCreditsMode),
...MUSIC_VIDEO_CREDITS_MODES.map((value) => ({ value, label: value }))
]}
onChange={onSelect('musicVideoCreditsMode', (raw) => raw as MusicVideoCreditsMode)}
/>
<Select
size="sm"
label="Song video mode"
value={selValue('songVideoMode')}
options={[
inheritOption(template.songVideoMode),
...SONG_VIDEO_MODES.map((value) => ({ value, label: value }))
]}
onChange={onSelect('songVideoMode', (raw) => raw as SongVideoMode)}
/>
<Select
size="sm"
label="Idle behavior"
value={selValue('idleBehavior')}
options={[
inheritOption(template.idleBehavior),
...IDLE_BEHAVIORS.map((value) => ({ value, label: value }))
]}
onChange={onSelect('idleBehavior', (raw) => raw as IdleBehavior)}
/>
<Select
size="sm"
label="Fixed start time"
value={selValue('fixedStartTimeBehavior')}
options={[
inheritOption(template.fixedStartTimeBehavior),
...FIXED_START_TIME_BEHAVIORS.map((value) => ({ value, label: value }))
]}
onChange={onSelect('fixedStartTimeBehavior', (raw) => raw as FixedStartTimeBehavior)}
/>
<div className="ctv-builder-adv-switchrow">
<span>Random start point</span>
<Switch
checked={boolValue('randomStartPoint')}
onChange={(next) => setOverride('randomStartPoint', next)}
/>
</div>
<div className="ctv-builder-adv-switchrow">
<span>Shuffle schedule items</span>
<Switch
checked={boolValue('shuffleScheduleItems')}
onChange={(next) => setOverride('shuffleScheduleItems', next)}
/>
</div>
<Input size="sm" label="Group" value={group} onChange={(event) => setGroup(event.target.value)} error={group.trim() ? null : 'Required'} />
<Input size="sm" label="Categories" value={categories} onChange={(event) => setCategories(event.target.value)} placeholder="comma-separated" />
</AdvGroup>
</>
) : (
<>
<AdvGroup label="Streaming">
<ReadOnlyField label="FFmpeg profile" value={ffmpegProfiles.find((p) => p.id === template.ffmpegProfileId)?.name ?? `#${template.ffmpegProfileId}`} />
<ReadOnlyField label="Streaming mode" value={STREAMING_MODE_LABELS[template.streamingMode as StreamingMode] ?? template.streamingMode} />
<ReadOnlyField label="Transcode mode" value={template.transcodeMode} />
</AdvGroup>
<AdvGroup label="Filler">
<ReadOnlyField label="Fallback filler" value={fillerName(fillerPresets, template.fallbackFillerId)} />
<ReadOnlyField label="Pre-roll filler" value={fillerName(fillerPresets, template.preRollFillerId)} />
<ReadOnlyField label="Mid-roll filler" value={fillerName(fillerPresets, template.midRollFillerId)} />
<ReadOnlyField label="Post-roll filler" value={fillerName(fillerPresets, template.postRollFillerId)} />
<ReadOnlyField label="Watermark" value={fillerName(watermarks, template.watermarkId)} />
</AdvGroup>
<AdvGroup label="Playback">
<ReadOnlyField label="Playback order" value={playbackOrder} />
<ReadOnlyField label="Preferred audio language" value={template.preferredAudioLanguageCode ?? 'Not set'} />
<ReadOnlyField label="Preferred subtitle language" value={template.preferredSubtitleLanguageCode ?? 'Not set'} />
<ReadOnlyField label="Subtitle mode" value={template.subtitleMode} />
<ReadOnlyField label="Stream selector mode" value={template.streamSelectorMode} />
</AdvGroup>
<AdvGroup label="Behavior">
<ReadOnlyField label="Playout mode" value={playoutMode === 'Continuous' ? 'Always on' : 'On demand'} />
<ReadOnlyField label="Music video credits" value={template.musicVideoCreditsMode} />
<ReadOnlyField label="Song video mode" value={template.songVideoMode} />
<ReadOnlyField label="Idle behavior" value={template.idleBehavior} />
<ReadOnlyField label="Fixed start time" value={template.fixedStartTimeBehavior} />
<ReadOnlyField label="Group" value={group} />
</AdvGroup>
</>
)}
</div>
</div>
</div>
);
}
function AdvGroup({ label, children }: { label: string; children: ReactNode }) {
return (
<div>
<div className="ctv-builder-eyebrow" style={{ marginBottom: 8 }}>
{label}
</div>
<div className="ctv-builder-adv-grid">{children}</div>
</div>
);
}
function ReadOnlyField({ label, value }: { label: string; value: string }) {
return (
<div className="ctv-builder-adv-readonly">
<div className="ctv-builder-adv-readonly-key">{label}</div>
<div className="ctv-builder-adv-readonly-value" style={/\d/.test(value) ? mono : undefined}>
{value}
</div>
</div>
);
}