"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useTranslations } from "next-intl"; import { AlertCircle, Cloud, Download, Loader2, Monitor, X, } from "lucide-react"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Progress } from "@/components/ui/progress"; import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { editDuration, outputSize, timecode, type EditDocument, type EditorState, type ExportJob, } from "@/lib/editor/document"; import { useSession } from "@/lib/auth-client"; import { trackClipExport } from "@/lib/clip-export-tracking"; import { exportDraft } from "@/lib/editor/export-draft"; import { editorRequest } from "./use-editor"; import { editorMessage } from "./studio-ui"; import { toast } from "sonner"; import { cn } from "@/lib/utils"; import type { WorkflowMeta } from "@/lib/workflows"; export interface ClipSummary { id: string; filename: string; clip_order: number; duration: number; text: string; video_url: string; hook_title?: string | null; /** Series parts only. */ part_number?: number | null; workflow_role?: string | null; workflow_meta?: WorkflowMeta; } interface Job extends ExportJob { endpoint: string; clipOrder: number; } interface Props { open: boolean; setOpen: (open: boolean) => void; taskId: string; clip: ClipSummary; clips: ClipSummary[]; doc: EditDocument; asset: EditorState; save: () => Promise; } export async function readyEditor( endpoint: string, signal?: AbortSignal, ): Promise { let state = await editorRequest(endpoint); if (state.status === "unprepared" || state.status === "failed") await editorRequest(`${endpoint}/prepare`, "POST"); const started = Date.now(); while (state.status !== "ready") { signal?.throwIfAborted(); if (Date.now() - started > 600_000) throw new Error( "Source preparation is taking longer than expected. Reopen the editor to check its status.", ); await new Promise((r) => setTimeout(r, 1500)); state = await editorRequest(endpoint); if (state.status === "failed") throw new Error(state.error || "Could not prepare clip"); } return state; } export function ExportPanel({ open, setOpen, taskId, clip, clips, doc, asset, save, }: Props) { const t = useTranslations("editor"); const userId = useSession().data?.user?.id; const [preset, setPreset] = useState("tiktok"), [mode, setMode] = useState("server"), [progress, setProgress] = useState(null), [busy, setBusy] = useState(false), [message, setMessage] = useState(""); const [browserSupport, setBrowserSupport] = useState<{ supported: boolean; kind: "background" | "mp4" | "opus"; } | null>(null); const [jobs, setJobs] = useState([]), [error, setError] = useState(null); const controller = useRef(null); const endpoint = `/api/tasks/${taskId}/clips/${clip.id}/editor`; const size = outputSize(doc, asset.width, asset.height), duration = editDuration(doc); useEffect(() => { if (!open) return; let stopped = false; setBrowserSupport(null); void import("mediabunny") .then(async (m) => { const video = await m.canEncodeVideo("avc", { width: size.width, height: size.height, bitrate: preset === "reels" ? 12_000_000 : 10_000_000, }); const aac = !asset.hasAudio || (await m.canEncodeAudio("aac")); const audio = aac || (await m.canEncodeAudio("opus")); if (!stopped) setBrowserSupport({ supported: video && audio, kind: !video || !audio ? "background" : aac ? "mp4" : "opus", }); }) .catch(() => { if (!stopped) setBrowserSupport({ supported: false, kind: "background", }); }); return () => { stopped = true; }; }, [open, size.width, size.height, preset, asset.hasAudio]); const refresh = useCallback(async () => { const results = await Promise.allSettled( clips.map(async (c) => { const url = `/api/tasks/${taskId}/clips/${c.id}/editor`; const state = await editorRequest(url); return (state.jobs || []).map((job) => ({ ...job, endpoint: url, clipOrder: c.clip_order, })); }), ); const fulfilled = results.filter( (r): r is PromiseFulfilledResult => r.status === "fulfilled", ); if (fulfilled.length) setJobs(fulfilled.flatMap((r) => r.value)); }, [clips, taskId]); useEffect(() => { if (!open) return; void refresh(); const timer = setInterval(() => void refresh(), 3000); return () => clearInterval(timer); }, [open, refresh]); useEffect(() => () => controller.current?.abort(), []); useEffect(() => { if (!busy || mode !== "browser") return; const warn = (event: BeforeUnloadEvent) => event.preventDefault(); window.addEventListener("beforeunload", warn); return () => window.removeEventListener("beforeunload", warn); }, [busy, mode]); const start = async (batch: boolean) => { setBusy(true); setError(null); const control = new AbortController(); controller.current = control; try { await save(); if (mode === "browser" && !batch) { setProgress(0); await exportDraft( `${endpoint}/media/clean.mp4`, doc, asset, preset, control.signal, setProgress, ); if (userId) void trackClipExport({ userId, surface: "editor", format: preset }); toast.success(t("export.exported")); } else { for (const c of batch ? clips : [clip]) { control.signal.throwIfAborted(); setMessage(t("export.preparingClip", { order: c.clip_order })); const url = `/api/tasks/${taskId}/clips/${c.id}/editor`; const state = c.id === clip.id ? asset : await readyEditor(url, control.signal); control.signal.throwIfAborted(); await editorRequest(`${url}/exports`, "POST", { basis: state.basis, preset, document: c.id === clip.id ? doc : state.draft.document, }); } await refresh(); toast.success( batch ? t("export.queuedAll") : t("export.backgroundStarted"), ); } } catch (e) { if (!control.signal.aborted) setError(e instanceof Error ? editorMessage(t, e.message) : t("errors.exportFailed")); else toast.info(t("export.cancelled")); } finally { setBusy(false); setProgress(null); setMessage(""); controller.current = null; } }; const summary = [ [t("export.resolution"), `${size.width} × ${size.height}`], [t("export.duration"), timecode(duration)], [ t("export.audio"), !asset.hasAudio ? t("export.noAudio") : doc.muted ? t("export.muted") : t("export.volume", { volume: Math.round(doc.volume * 100) }), ], [ t("export.estimatedSize"), t("export.sizeValue", { size: (((preset === "reels" ? 12 : 10) * duration) / 8).toFixed(1), }), ], ]; const modes = [ { id: "server", Icon: Cloud, title: t("export.background"), detail: t("export.backgroundDetail"), disabled: busy, }, { id: "browser", Icon: Monitor, title: t("export.onDevice"), detail: browserSupport ? t(`export.browser.${browserSupport.kind}`) : t("export.checking"), disabled: busy || !browserSupport?.supported, }, ]; return ( {t("export.title")} {t("export.description")}

{t("export.platform")}

value && setPreset(value)} > {[ ["tiktok", "TikTok"], ["reels", "Reels"], ["shorts", "Shorts"], ].map(([id, label]) => ( {label} ))}
{summary.map(([label, value]) => (
{label}
{value}
))}

{t("export.renderOn")}

{modes.map(({ id, Icon, title, detail, disabled }) => ( ))}
{mode === "browser" && browserSupport?.kind === "opus" && (

{t("export.opusNote")}

)}
{error && ( {error} )} {busy ? (
{progress !== null ? t("export.exporting", { progress }) : message || t("export.savingDraft")}
{progress !== null && ( )}
) : (
{clips.length > 1 && ( )}
)} {jobs.length > 0 && (

{t("export.queue")}

    {jobs.map((job) => (
  • {t("clipLabel", { order: job.clipOrder })} {job.id.slice(0, 6)} {job.status === "rendering" ? `${job.progress}%` : job.status === "queued" || job.status === "completed" || job.status === "failed" || job.status === "cancelled" ? t(`export.jobStatus.${job.status}`) : job.status}

    {job.error && (

    {job.error}

    )} {job.status === "rendering" && ( )}
    {job.status === "completed" ? ( ) : ( (job.status === "queued" || job.status === "rendering") && ( ) )}
  • ))}
)}
); }