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:
@@ -1,8 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Plus, Upload, RefreshCw, Antenna, Settings2 } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
useChannels,
|
||||
useCreateChannel,
|
||||
@@ -13,9 +12,11 @@ import {
|
||||
import { useAuthContext } from "@/context/auth-context";
|
||||
import { useConfig } from "@/hooks/use-config";
|
||||
import { useRescanLibrary } from "@/hooks/use-library";
|
||||
import { api } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useChannelOrder } from "@/hooks/use-channel-order";
|
||||
import { useImportChannel } from "@/hooks/use-import-channel";
|
||||
import { useRegenerateAllSchedules } from "@/hooks/use-regenerate-all";
|
||||
import { exportChannel } from "@/lib/channel-export";
|
||||
import { DashboardHeader } from "./components/dashboard-header";
|
||||
import { ChannelCard } from "./components/channel-card";
|
||||
import { CreateChannelDialog } from "./components/create-channel-dialog";
|
||||
import { DeleteChannelDialog } from "./components/delete-channel-dialog";
|
||||
@@ -35,7 +36,6 @@ import type {
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { token } = useAuthContext();
|
||||
const queryClient = useQueryClient();
|
||||
const { data: channels, isLoading, error } = useChannels();
|
||||
const { data: config } = useConfig();
|
||||
const capabilities = config?.provider_capabilities;
|
||||
@@ -46,84 +46,18 @@ export default function DashboardPage() {
|
||||
const generateSchedule = useGenerateSchedule();
|
||||
const rescanLibrary = useRescanLibrary();
|
||||
|
||||
// Channel ordering — persisted to localStorage
|
||||
const [channelOrder, setChannelOrder] = useState<string[]>([]);
|
||||
useEffect(() => {
|
||||
try {
|
||||
const stored = localStorage.getItem("k-tv-channel-order");
|
||||
if (stored) setChannelOrder(JSON.parse(stored));
|
||||
} catch {}
|
||||
}, []);
|
||||
|
||||
const saveOrder = (order: string[]) => {
|
||||
setChannelOrder(order);
|
||||
try {
|
||||
localStorage.setItem("k-tv-channel-order", JSON.stringify(order));
|
||||
} catch {}
|
||||
};
|
||||
|
||||
// Sort channels by stored order; new channels appear at the end
|
||||
const sortedChannels = channels
|
||||
? [...channels].sort((a, b) => {
|
||||
const ai = channelOrder.indexOf(a.id);
|
||||
const bi = channelOrder.indexOf(b.id);
|
||||
if (ai === -1 && bi === -1) return 0;
|
||||
if (ai === -1) return 1;
|
||||
if (bi === -1) return -1;
|
||||
return ai - bi;
|
||||
})
|
||||
: [];
|
||||
|
||||
const handleMoveUp = (channelId: string) => {
|
||||
const ids = sortedChannels.map((c) => c.id);
|
||||
const idx = ids.indexOf(channelId);
|
||||
if (idx <= 0) return;
|
||||
const next = [...ids];
|
||||
[next[idx - 1], next[idx]] = [next[idx], next[idx - 1]];
|
||||
saveOrder(next);
|
||||
};
|
||||
|
||||
const handleMoveDown = (channelId: string) => {
|
||||
const ids = sortedChannels.map((c) => c.id);
|
||||
const idx = ids.indexOf(channelId);
|
||||
if (idx === -1 || idx >= ids.length - 1) return;
|
||||
const next = [...ids];
|
||||
[next[idx], next[idx + 1]] = [next[idx + 1], next[idx]];
|
||||
saveOrder(next);
|
||||
};
|
||||
|
||||
// Regenerate all channels
|
||||
const [isRegeneratingAll, setIsRegeneratingAll] = useState(false);
|
||||
const handleRegenerateAll = async () => {
|
||||
if (!token || !channels || channels.length === 0) return;
|
||||
setIsRegeneratingAll(true);
|
||||
let failed = 0;
|
||||
for (const ch of channels) {
|
||||
try {
|
||||
await api.schedule.generate(ch.id, token);
|
||||
queryClient.invalidateQueries({ queryKey: ["schedule", ch.id] });
|
||||
} catch {
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
setIsRegeneratingAll(false);
|
||||
if (failed === 0)
|
||||
toast.success(`All ${channels.length} schedules regenerated`);
|
||||
else toast.error(`${failed} schedule(s) failed to generate`);
|
||||
};
|
||||
const { sortedChannels, handleMoveUp, handleMoveDown } = useChannelOrder(channels);
|
||||
const { isRegeneratingAll, handleRegenerateAll } = useRegenerateAllSchedules(channels, token);
|
||||
const importChannel = useImportChannel(token);
|
||||
|
||||
// Dialog state
|
||||
const [iptvOpen, setIptvOpen] = useState(false);
|
||||
const [transcodeOpen, setTranscodeOpen] = useState(false);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
const [importPending, setImportPending] = useState(false);
|
||||
const [importError, setImportError] = useState<string | null>(null);
|
||||
const [editChannel, setEditChannel] = useState<ChannelResponse | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<ChannelResponse | null>(
|
||||
null,
|
||||
);
|
||||
const [scheduleChannel, setScheduleChannel] =
|
||||
useState<ChannelResponse | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<ChannelResponse | null>(null);
|
||||
const [scheduleChannel, setScheduleChannel] = useState<ChannelResponse | null>(null);
|
||||
|
||||
const handleCreate = (data: {
|
||||
name: string;
|
||||
@@ -171,52 +105,8 @@ export default function DashboardPage() {
|
||||
};
|
||||
|
||||
const handleImport = async (data: ChannelImportData) => {
|
||||
if (!token) return;
|
||||
setImportPending(true);
|
||||
setImportError(null);
|
||||
try {
|
||||
const created = await api.channels.create(
|
||||
{
|
||||
name: data.name,
|
||||
timezone: data.timezone,
|
||||
description: data.description,
|
||||
},
|
||||
token,
|
||||
);
|
||||
await api.channels.update(
|
||||
created.id,
|
||||
{
|
||||
schedule_config: { blocks: data.blocks },
|
||||
recycle_policy: data.recycle_policy,
|
||||
},
|
||||
token,
|
||||
);
|
||||
await queryClient.invalidateQueries({ queryKey: ["channels"] });
|
||||
setImportOpen(false);
|
||||
} catch (e) {
|
||||
setImportError(e instanceof Error ? e.message : "Import failed");
|
||||
} finally {
|
||||
setImportPending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExport = (channel: ChannelResponse) => {
|
||||
const payload = {
|
||||
name: channel.name,
|
||||
description: channel.description ?? undefined,
|
||||
timezone: channel.timezone,
|
||||
blocks: channel.schedule_config.blocks,
|
||||
recycle_policy: channel.recycle_policy,
|
||||
};
|
||||
const blob = new Blob([JSON.stringify(payload, null, 2)], {
|
||||
type: "application/json",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `${channel.name.toLowerCase().replace(/\s+/g, "-")}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
const ok = await importChannel.handleImport(data);
|
||||
if (ok) setImportOpen(false);
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
@@ -226,69 +116,32 @@ export default function DashboardPage() {
|
||||
});
|
||||
};
|
||||
|
||||
const canTranscode = !!config?.providers?.some((p) => p.capabilities.transcode);
|
||||
const canRescan = !!capabilities?.rescan;
|
||||
|
||||
return (
|
||||
<div className="mx-auto w-full max-w-5xl space-y-6 px-6 py-8">
|
||||
{/* Header */}
|
||||
<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">
|
||||
{config?.providers?.some((p) => p.capabilities.transcode) && (
|
||||
<Button
|
||||
onClick={() => setTranscodeOpen(true)}
|
||||
title="Transcode settings"
|
||||
>
|
||||
<Settings2 className="size-4" />
|
||||
Transcode
|
||||
</Button>
|
||||
)}
|
||||
{capabilities?.rescan && (
|
||||
<Button
|
||||
onClick={() =>
|
||||
rescanLibrary.mutate(undefined, {
|
||||
onSuccess: (d) => toast.success(`Rescan complete: ${d.items_found} files found`),
|
||||
onError: () => toast.error("Rescan failed"),
|
||||
})
|
||||
}
|
||||
disabled={rescanLibrary.isPending}
|
||||
title="Rescan local files directory"
|
||||
>
|
||||
<RefreshCw className={`size-4 ${rescanLibrary.isPending ? "animate-spin" : ""}`} />
|
||||
Rescan library
|
||||
</Button>
|
||||
)}
|
||||
{channels && channels.length > 0 && (
|
||||
<Button
|
||||
onClick={handleRegenerateAll}
|
||||
disabled={isRegeneratingAll}
|
||||
title="Regenerate schedules for all channels"
|
||||
>
|
||||
<RefreshCw
|
||||
className={`size-4 ${isRegeneratingAll ? "animate-spin" : ""}`}
|
||||
/>
|
||||
Regenerate all
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={() => setIptvOpen(true)}>
|
||||
<Antenna className="size-4" />
|
||||
IPTV
|
||||
</Button>
|
||||
<Button onClick={() => setImportOpen(true)}>
|
||||
<Upload className="size-4" />
|
||||
Import
|
||||
</Button>
|
||||
<Button onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
New channel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<DashboardHeader
|
||||
hasChannels={!!channels && channels.length > 0}
|
||||
canTranscode={canTranscode}
|
||||
canRescan={canRescan}
|
||||
isRegeneratingAll={isRegeneratingAll}
|
||||
isRescanPending={rescanLibrary.isPending}
|
||||
capabilities={capabilities}
|
||||
onTranscodeOpen={() => setTranscodeOpen(true)}
|
||||
onRescan={() =>
|
||||
rescanLibrary.mutate(undefined, {
|
||||
onSuccess: (d) =>
|
||||
toast.success(`Rescan complete: ${d.items_found} files found`),
|
||||
onError: () => toast.error("Rescan failed"),
|
||||
})
|
||||
}
|
||||
onRegenerateAll={handleRegenerateAll}
|
||||
onIptvOpen={() => setIptvOpen(true)}
|
||||
onImportOpen={() => setImportOpen(true)}
|
||||
onCreateOpen={() => setCreateOpen(true)}
|
||||
/>
|
||||
|
||||
{/* Content */}
|
||||
{isLoading && (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-zinc-700 border-t-zinc-300" />
|
||||
@@ -304,10 +157,12 @@ export default function DashboardPage() {
|
||||
{!isLoading && channels && channels.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-zinc-800 py-20 text-center">
|
||||
<p className="text-sm text-zinc-500">No channels yet</p>
|
||||
<Button onClick={() => setCreateOpen(true)}>
|
||||
<Plus className="size-4" />
|
||||
<button
|
||||
onClick={() => setCreateOpen(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-zinc-700 bg-zinc-800 px-3 py-1.5 text-sm text-zinc-300 transition-colors hover:bg-zinc-700 hover:text-zinc-100"
|
||||
>
|
||||
Create your first channel
|
||||
</Button>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -327,7 +182,7 @@ export default function DashboardPage() {
|
||||
onDelete={() => setDeleteTarget(channel)}
|
||||
onGenerateSchedule={() => generateSchedule.mutate(channel.id)}
|
||||
onViewSchedule={() => setScheduleChannel(channel)}
|
||||
onExport={() => handleExport(channel)}
|
||||
onExport={() => exportChannel(channel)}
|
||||
onMoveUp={() => handleMoveUp(channel.id)}
|
||||
onMoveDown={() => handleMoveDown(channel.id)}
|
||||
/>
|
||||
@@ -354,12 +209,12 @@ export default function DashboardPage() {
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setImportOpen(false);
|
||||
setImportError(null);
|
||||
importChannel.clearError();
|
||||
}
|
||||
}}
|
||||
onSubmit={handleImport}
|
||||
isPending={importPending}
|
||||
error={importError}
|
||||
isPending={importChannel.isPending}
|
||||
error={importChannel.error}
|
||||
/>
|
||||
|
||||
<CreateChannelDialog
|
||||
|
||||
Reference in New Issue
Block a user