refactor(frontend): extract logic to hooks, split inline components

Area 1 (tv/page.tsx 964→423 lines):
- hooks: use-fullscreen, use-idle, use-volume, use-quality, use-subtitles,
  use-channel-input, use-channel-passwords, use-tv-keyboard
- components: SubtitlePicker, VolumeControl, QualityPicker, TopControlBar,
  LogoWatermark, AutoplayPrompt, ChannelNumberOverlay, TvBaseLayer

Area 2 (edit-channel-sheet.tsx 1244→678 lines):
- hooks: use-channel-form (all form state + reset logic)
- lib/schemas.ts: extracted Zod schemas + extractErrors
- components: AlgorithmicFilterEditor, RecyclePolicyEditor, WebhookEditor,
  AccessSettingsEditor, LogoEditor

Area 3 (dashboard/page.tsx 406→261 lines):
- hooks: use-channel-order, use-import-channel, use-regenerate-all
- lib/channel-export.ts: pure export utility
- components: DashboardHeader
This commit is contained in:
2026-03-17 02:25:02 +01:00
parent ce92b43205
commit 8ed8da2d90
32 changed files with 2629 additions and 1689 deletions

View File

@@ -0,0 +1,57 @@
import type { AccessMode } from "@/lib/types";
interface AccessSettingsEditorProps {
accessMode: AccessMode;
accessPassword: string;
onAccessModeChange: (mode: AccessMode) => void;
onAccessPasswordChange: (pw: string) => void;
label?: string;
passwordLabel?: string;
passwordHint?: string;
}
export function AccessSettingsEditor({
accessMode,
accessPassword,
onAccessModeChange,
onAccessPasswordChange,
label = "Access",
passwordLabel = "Password",
passwordHint = "Leave blank to keep existing password",
}: AccessSettingsEditorProps) {
return (
<div className="space-y-2">
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
<select
value={accessMode}
onChange={(e) => {
onAccessModeChange(e.target.value as AccessMode);
onAccessPasswordChange("");
}}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:border-zinc-500 focus:outline-none"
>
<option value="public">Public</option>
<option value="password_protected">Password protected</option>
<option value="account_required">Account required</option>
<option value="owner_only">Owner only</option>
</select>
</div>
{accessMode === "password_protected" && (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
{passwordLabel}
</label>
<input
type="password"
placeholder={passwordHint}
value={accessPassword}
onChange={(e) => onAccessPasswordChange(e.target.value)}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,342 @@
"use client";
import { useState } from "react";
import { TagInput } from "./tag-input";
import { SeriesPicker } from "./series-picker";
import { FilterPreview } from "./filter-preview";
import { useCollections, useSeries, useGenres } from "@/hooks/use-library";
import type {
BlockContent,
ContentType,
FillStrategy,
MediaFilter,
ProviderInfo,
} from "@/lib/types";
import type { FieldErrors } from "@/lib/schemas";
function Field({
label,
hint,
error,
children,
}: {
label: string;
hint?: string;
error?: string;
children: React.ReactNode;
}) {
return (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
{children}
{error ? (
<p className="text-[11px] text-red-400">{error}</p>
) : hint ? (
<p className="text-[11px] text-zinc-600">{hint}</p>
) : null}
</div>
);
}
function NativeSelect({
value,
onChange,
children,
}: {
value: string;
onChange: (v: string) => void;
children: React.ReactNode;
}) {
return (
<select
value={value}
onChange={(e) => onChange(e.target.value)}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:border-zinc-500 focus:outline-none"
>
{children}
</select>
);
}
function NumberInput({
value,
onChange,
min,
placeholder,
error,
}: {
value: number | "";
onChange: (v: number | "") => void;
min?: number;
placeholder?: string;
error?: boolean;
}) {
return (
<input
type="number"
min={min}
value={value}
placeholder={placeholder}
onChange={(e) =>
onChange(e.target.value === "" ? "" : Number(e.target.value))
}
className={`w-full rounded-md border bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:outline-none ${error ? "border-red-500 focus:border-red-400" : "border-zinc-700 focus:border-zinc-500"}`}
/>
);
}
interface AlgorithmicFilterEditorProps {
content: Extract<BlockContent, { type: "algorithmic" }>;
pfx: string;
errors: FieldErrors;
providers: ProviderInfo[];
setFilter: (patch: Partial<MediaFilter>) => void;
setStrategy: (strategy: FillStrategy) => void;
setProviderId: (id: string) => void;
}
export function AlgorithmicFilterEditor({
content,
pfx,
errors,
providers,
setFilter,
setStrategy,
setProviderId,
}: AlgorithmicFilterEditorProps) {
const [showGenres, setShowGenres] = useState(false);
const providerId = content.provider_id ?? "";
const capabilities =
providers.find((p) => p.id === providerId)?.capabilities ??
providers[0]?.capabilities;
const { data: collections, isLoading: loadingCollections } = useCollections(
providerId || undefined,
);
const { data: series, isLoading: loadingSeries } = useSeries(undefined, {
enabled: capabilities?.series !== false,
provider: providerId || undefined,
});
const { data: genreOptions } = useGenres(
content.filter.content_type ?? undefined,
{
enabled: capabilities?.genres !== false,
provider: providerId || undefined,
},
);
const isEpisode = content.filter.content_type === "episode";
const collectionLabel =
capabilities?.collections && !capabilities?.series && !capabilities?.genres
? "Directory"
: "Library";
return (
<div className="space-y-3 rounded-md border border-zinc-700/50 bg-zinc-800 p-3">
<p className="text-[11px] font-medium uppercase tracking-wider text-zinc-500">
Filter
</p>
{providers.length > 1 && (
<Field label="Provider">
<NativeSelect value={providerId} onChange={setProviderId}>
{providers.map((p) => (
<option key={p.id} value={p.id}>
{p.id}
</option>
))}
</NativeSelect>
</Field>
)}
<div className="grid grid-cols-2 gap-3">
<Field label="Media type">
<NativeSelect
value={content.filter.content_type ?? ""}
onChange={(v) =>
setFilter({
content_type: v === "" ? null : (v as ContentType),
series_names:
v !== "episode" ? [] : content.filter.series_names,
})
}
>
<option value="">Any</option>
<option value="movie">Movie</option>
<option value="episode">Episode</option>
<option value="short">Short</option>
</NativeSelect>
</Field>
<Field label="Strategy">
<NativeSelect
value={content.strategy}
onChange={(v) => setStrategy(v as FillStrategy)}
>
<option value="random">Random</option>
<option value="best_fit">Best fit</option>
<option value="sequential">Sequential</option>
</NativeSelect>
</Field>
</div>
{isEpisode && capabilities?.series !== false && (
<Field
label="Series"
hint={
content.strategy === "sequential"
? "Episodes will play in chronological order"
: "Filter to specific shows, or leave empty for all"
}
>
<SeriesPicker
values={content.filter.series_names ?? []}
onChange={(v) => setFilter({ series_names: v })}
series={series ?? []}
isLoading={loadingSeries}
/>
</Field>
)}
<Field
label={collectionLabel}
hint={
loadingCollections
? `Loading ${collectionLabel.toLowerCase()}s…`
: collections
? `Scope this block to one ${collectionLabel.toLowerCase()}`
: `Enter a provider ${collectionLabel.toLowerCase()} ID`
}
>
{collections && collections.length > 0 ? (
<NativeSelect
value={content.filter.collections[0] ?? ""}
onChange={(v) => setFilter({ collections: v ? [v] : [] })}
>
<option value="">All libraries</option>
{collections.map((c) => (
<option key={c.id} value={c.id}>
{c.name}
{c.collection_type ? ` (${c.collection_type})` : ""}
</option>
))}
</NativeSelect>
) : (
<TagInput
values={content.filter.collections}
onChange={(v) => setFilter({ collections: v })}
placeholder="Library ID…"
/>
)}
</Field>
{capabilities?.genres !== false && (
<Field label="Genres" hint="Press Enter or comma to add">
<TagInput
values={content.filter.genres}
onChange={(v) => setFilter({ genres: v })}
placeholder="Comedy, Animation…"
/>
{genreOptions && genreOptions.length > 0 && (
<div className="mt-1.5">
<button
type="button"
onClick={() => setShowGenres((s) => !s)}
className="text-[11px] text-zinc-600 hover:text-zinc-400"
>
{showGenres ? "Hide" : "Browse"} available genres
</button>
{showGenres && (
<div className="mt-1.5 flex flex-wrap gap-1">
{genreOptions
.filter((g) => !content.filter.genres.includes(g))
.map((g) => (
<button
key={g}
type="button"
onClick={() =>
setFilter({ genres: [...content.filter.genres, g] })
}
className="rounded px-1.5 py-0.5 text-[11px] bg-zinc-700/50 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200"
>
+ {g}
</button>
))}
</div>
)}
</div>
)}
</Field>
)}
<Field label="Tags" hint="Press Enter or comma to add">
<TagInput
values={content.filter.tags}
onChange={(v) => setFilter({ tags: v })}
placeholder="classic, family…"
/>
</Field>
<div className="grid grid-cols-3 gap-3">
<Field
label="Decade"
hint="e.g. 1990"
error={errors[`${pfx}.content.filter.decade`]}
>
<NumberInput
value={content.filter.decade ?? ""}
onChange={(v) =>
setFilter({ decade: v === "" ? null : (v as number) })
}
placeholder="1990"
error={!!errors[`${pfx}.content.filter.decade`]}
/>
</Field>
<Field
label="Min duration (min)"
error={errors[`${pfx}.content.filter.min_duration_secs`]}
>
<NumberInput
value={
content.filter.min_duration_secs != null
? Math.round(content.filter.min_duration_secs / 60)
: ""
}
onChange={(v) =>
setFilter({
min_duration_secs: v === "" ? null : (v as number) * 60,
})
}
placeholder="30"
error={!!errors[`${pfx}.content.filter.min_duration_secs`]}
/>
</Field>
<Field
label="Max duration (min)"
error={errors[`${pfx}.content.filter.max_duration_secs`]}
>
<NumberInput
value={
content.filter.max_duration_secs != null
? Math.round(content.filter.max_duration_secs / 60)
: ""
}
onChange={(v) =>
setFilter({
max_duration_secs: v === "" ? null : (v as number) * 60,
})
}
placeholder="120"
error={!!errors[`${pfx}.content.filter.max_duration_secs`]}
/>
</Field>
</div>
<FilterPreview
filter={content.filter}
strategy={content.strategy}
provider={providerId || undefined}
/>
</div>
);
}

View File

@@ -0,0 +1,85 @@
import { Plus, Upload, RefreshCw, Antenna, Settings2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { ProviderCapabilities } from "@/lib/types";
interface DashboardHeaderProps {
hasChannels: boolean;
canTranscode: boolean;
canRescan: boolean;
isRegeneratingAll: boolean;
isRescanPending: boolean;
capabilities: ProviderCapabilities | undefined;
onTranscodeOpen: () => void;
onRescan: () => void;
onRegenerateAll: () => void;
onIptvOpen: () => void;
onImportOpen: () => void;
onCreateOpen: () => void;
}
export function DashboardHeader({
hasChannels,
canTranscode,
canRescan,
isRegeneratingAll,
isRescanPending,
onTranscodeOpen,
onRescan,
onRegenerateAll,
onIptvOpen,
onImportOpen,
onCreateOpen,
}: DashboardHeaderProps) {
return (
<div className="flex items-center justify-between">
<div>
<h1 className="text-xl font-semibold text-zinc-100">My Channels</h1>
<p className="mt-0.5 text-sm text-zinc-500">Build your broadcast lineup</p>
</div>
<div className="flex gap-2">
{canTranscode && (
<Button onClick={onTranscodeOpen} title="Transcode settings">
<Settings2 className="size-4" />
Transcode
</Button>
)}
{canRescan && (
<Button
onClick={onRescan}
disabled={isRescanPending}
title="Rescan local files directory"
>
<RefreshCw
className={`size-4 ${isRescanPending ? "animate-spin" : ""}`}
/>
Rescan library
</Button>
)}
{hasChannels && (
<Button
onClick={onRegenerateAll}
disabled={isRegeneratingAll}
title="Regenerate schedules for all channels"
>
<RefreshCw
className={`size-4 ${isRegeneratingAll ? "animate-spin" : ""}`}
/>
Regenerate all
</Button>
)}
<Button onClick={onIptvOpen}>
<Antenna className="size-4" />
IPTV
</Button>
<Button onClick={onImportOpen}>
<Upload className="size-4" />
Import
</Button>
<Button onClick={onCreateOpen}>
<Plus className="size-4" />
New channel
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,142 @@
import { useRef } from "react";
import { Button } from "@/components/ui/button";
import type { LogoPosition } from "@/lib/types";
const LOGO_POSITIONS: { value: LogoPosition; label: string }[] = [
{ value: "top_right", label: "Top right" },
{ value: "top_left", label: "Top left" },
{ value: "bottom_right", label: "Bottom right" },
{ value: "bottom_left", label: "Bottom left" },
];
interface LogoEditorProps {
logo: string | null;
logoPosition: LogoPosition;
logoOpacity: number;
onLogoChange: (logo: string | null) => void;
onPositionChange: (position: LogoPosition) => void;
onOpacityChange: (opacity: number) => void;
}
export function LogoEditor({
logo,
logoPosition,
logoOpacity,
onLogoChange,
onPositionChange,
onOpacityChange,
}: LogoEditorProps) {
const fileInputRef = useRef<HTMLInputElement>(null);
const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (ev) => {
const result = ev.target?.result;
if (typeof result === "string") onLogoChange(result);
};
reader.readAsDataURL(file);
e.target.value = "";
};
return (
<div className="space-y-3 rounded-md border border-zinc-700/50 bg-zinc-800/50 p-3">
<div className="flex gap-2">
<Button
type="button"
variant="outline"
size="xs"
className="border-zinc-700 text-zinc-300 hover:text-zinc-100"
onClick={() => fileInputRef.current?.click()}
>
Upload image
</Button>
{logo && (
<Button
type="button"
variant="ghost"
size="xs"
className="text-zinc-500 hover:text-red-400"
onClick={() => onLogoChange(null)}
>
Clear
</Button>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handleFile}
/>
</div>
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
URL or SVG
</label>
<textarea
rows={2}
value={logo ?? ""}
onChange={(e) => onLogoChange(e.target.value || null)}
placeholder="https://example.com/logo.png or <svg>…</svg>"
className="w-full resize-none rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-xs text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
Position
</label>
<select
value={logoPosition}
onChange={(e) => onPositionChange(e.target.value as LogoPosition)}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 focus:border-zinc-500 focus:outline-none"
>
{LOGO_POSITIONS.map((p) => (
<option key={p.value} value={p.value}>
{p.label}
</option>
))}
</select>
</div>
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">
Opacity ({logoOpacity}%)
</label>
<input
type="range"
min={0}
max={100}
value={logoOpacity}
onChange={(e) => onOpacityChange(Number(e.target.value))}
className="w-full accent-zinc-400"
/>
</div>
</div>
{logo && (
<div className="flex items-center justify-center rounded-md border border-zinc-700/50 bg-zinc-900 p-2">
{logo.trimStart().startsWith("<") ? (
<div
dangerouslySetInnerHTML={{ __html: logo }}
className="h-10 w-auto"
style={{ opacity: logoOpacity / 100 }}
/>
) : (
// eslint-disable-next-line @next/next/no-img-element
<img
src={logo}
alt="Logo preview"
className="h-10 w-auto object-contain"
style={{ opacity: logoOpacity / 100 }}
/>
)}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,115 @@
import type { RecyclePolicy } from "@/lib/types";
import type { FieldErrors } from "@/lib/schemas";
function NumberInput({
value,
onChange,
min,
max,
step,
placeholder,
error,
}: {
value: number | "";
onChange: (v: number | "") => void;
min?: number;
max?: number;
step?: number | "any";
placeholder?: string;
error?: boolean;
}) {
return (
<input
type="number"
min={min}
max={max}
step={step}
value={value}
placeholder={placeholder}
onChange={(e) =>
onChange(e.target.value === "" ? "" : Number(e.target.value))
}
className={`w-full rounded-md border bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:outline-none ${error ? "border-red-500 focus:border-red-400" : "border-zinc-700 focus:border-zinc-500"}`}
/>
);
}
function Field({
label,
hint,
error,
children,
}: {
label: string;
hint?: string;
error?: string;
children: React.ReactNode;
}) {
return (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
{children}
{error ? (
<p className="text-[11px] text-red-400">{error}</p>
) : hint ? (
<p className="text-[11px] text-zinc-600">{hint}</p>
) : null}
</div>
);
}
interface RecyclePolicyEditorProps {
policy: RecyclePolicy;
errors: FieldErrors;
onChange: (policy: RecyclePolicy) => void;
}
export function RecyclePolicyEditor({
policy,
errors,
onChange,
}: RecyclePolicyEditorProps) {
return (
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<Field label="Cooldown (days)" hint="Don't replay within N days">
<NumberInput
value={policy.cooldown_days ?? ""}
onChange={(v) =>
onChange({ ...policy, cooldown_days: v === "" ? null : (v as number) })
}
min={0}
placeholder="7"
/>
</Field>
<Field label="Cooldown (generations)" hint="Don't replay within N schedules">
<NumberInput
value={policy.cooldown_generations ?? ""}
onChange={(v) =>
onChange({ ...policy, cooldown_generations: v === "" ? null : (v as number) })
}
min={0}
placeholder="3"
/>
</Field>
</div>
<Field
label="Min available ratio"
hint="0.01.0 · Fraction of the pool kept selectable even if cooldown is active"
error={errors["recycle_policy.min_available_ratio"]}
>
<NumberInput
value={policy.min_available_ratio}
onChange={(v) =>
onChange({ ...policy, min_available_ratio: v === "" ? 0.1 : (v as number) })
}
min={0}
max={1}
step={0.01}
placeholder="0.1"
error={!!errors["recycle_policy.min_available_ratio"]}
/>
</Field>
</div>
);
}

View File

@@ -0,0 +1,141 @@
import type { WebhookFormat } from "@/hooks/use-channel-form";
import { WEBHOOK_PRESETS } from "@/hooks/use-channel-form";
function Field({
label,
hint,
children,
}: {
label: string;
hint?: string;
children: React.ReactNode;
}) {
return (
<div className="space-y-1.5">
<label className="block text-xs font-medium text-zinc-400">{label}</label>
{children}
{hint && <p className="text-[11px] text-zinc-600">{hint}</p>}
</div>
);
}
interface WebhookEditorProps {
webhookUrl: string;
webhookPollInterval: number | "";
webhookFormat: WebhookFormat;
webhookBodyTemplate: string;
webhookHeaders: string;
onWebhookUrlChange: (v: string) => void;
onWebhookPollIntervalChange: (v: number | "") => void;
onWebhookFormatChange: (fmt: WebhookFormat) => void;
onWebhookBodyTemplateChange: (v: string) => void;
onWebhookHeadersChange: (v: string) => void;
}
export function WebhookEditor({
webhookUrl,
webhookPollInterval,
webhookFormat,
webhookBodyTemplate,
webhookHeaders,
onWebhookUrlChange,
onWebhookPollIntervalChange,
onWebhookFormatChange,
onWebhookBodyTemplateChange,
onWebhookHeadersChange,
}: WebhookEditorProps) {
return (
<div className="space-y-3">
<Field label="Webhook URL" hint="POST events to this URL on broadcast changes">
<input
value={webhookUrl}
onChange={(e) => onWebhookUrlChange(e.target.value)}
placeholder="https://example.com/webhook"
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
{webhookUrl && (
<>
<Field
label="Poll interval (seconds)"
hint="How often to check for broadcast changes"
>
<input
type="number"
min={1}
value={webhookPollInterval}
placeholder="5"
onChange={(e) =>
onWebhookPollIntervalChange(
e.target.value === "" ? "" : Number(e.target.value),
)
}
className="w-full rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
<div className="space-y-2">
<p className="text-xs text-zinc-400">Payload format</p>
<div className="flex flex-wrap gap-1.5">
{(["default", "discord", "slack", "custom"] as WebhookFormat[]).map(
(fmt) => (
<button
key={fmt}
type="button"
onClick={() => {
onWebhookFormatChange(fmt);
if (fmt === "discord")
onWebhookBodyTemplateChange(WEBHOOK_PRESETS.discord);
else if (fmt === "slack")
onWebhookBodyTemplateChange(WEBHOOK_PRESETS.slack);
else if (fmt === "default") onWebhookBodyTemplateChange("");
}}
className={`rounded px-2.5 py-1 text-xs font-medium capitalize transition-colors ${
webhookFormat === fmt
? "bg-zinc-600 text-zinc-100"
: "bg-zinc-800 text-zinc-400 hover:bg-zinc-700 hover:text-zinc-200"
}`}
>
{fmt === "default" ? "K-TV default" : fmt}
</button>
),
)}
</div>
</div>
{webhookFormat !== "default" && (
<Field
label="Body template (Handlebars)"
hint="Context: event, timestamp, channel_id, data.item.title, data.item.duration_secs, …"
>
<textarea
rows={6}
value={webhookBodyTemplate}
onChange={(e) => {
onWebhookBodyTemplateChange(e.target.value);
onWebhookFormatChange("custom");
}}
placeholder={'{\n "text": "Now playing: {{data.item.title}}"\n}'}
className="w-full resize-y rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 font-mono text-xs text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
)}
<Field
label="Extra headers (JSON)"
hint={'e.g. {"Authorization": "Bearer token"}'}
>
<textarea
rows={2}
value={webhookHeaders}
onChange={(e) => onWebhookHeadersChange(e.target.value)}
placeholder={'{"Authorization": "Bearer xxx"}'}
className="w-full resize-none rounded-md border border-zinc-700 bg-zinc-800 px-3 py-2 font-mono text-xs text-zinc-100 placeholder:text-zinc-600 focus:border-zinc-500 focus:outline-none"
/>
</Field>
</>
)}
</div>
);
}