"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import Link from "next/link"; import { useTranslations } from "next-intl"; import { AlertCircle, ArrowLeft, Check, ChevronDown, CloudOff, Download, Film, Keyboard, Layers, Loader2, MoreHorizontal, Redo2, RotateCcw, Undo2, } from "lucide-react"; import { toast } from "sonner"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { downloadBlob } from "@/lib/clip-actions"; import { clamp, outputTime, splitSegment, timecode, type CaptionStyle, } from "@/lib/editor/document"; import { cn } from "@/lib/utils"; import type { TextDraft } from "@/lib/editor/render"; import { editorRequest, useEditor } from "./use-editor"; import { Preview } from "./preview"; import { Timeline } from "./timeline"; import { Inspector, type InspectorTab } from "./inspector"; import { ExportPanel, readyEditor, type ClipSummary } from "./export-panel"; import { partTitle } from "@/components/app/clip-wall"; import { AIPrompt } from "./ai-prompt"; import { editorMessage, editorStatus, Keys, Panel, ToolButton } from "./studio-ui"; const SHORTCUTS: [string[], string][] = [ [["space"], "shortcuts.playPause"], [["←", "→"], "shortcuts.frames"], [["shift", "←", "→"], "shortcuts.jump"], [["I"], "shortcuts.setIn"], [["O"], "shortcuts.setOut"], [["S"], "shortcuts.split"], [["Delete"], "shortcuts.removeBroll"], [["mod", "J"], "shortcuts.aiPrompt"], [["mod", "Z"], "shortcuts.undo"], [["mod", "shift", "Z"], "shortcuts.redo"], [["mod", "S"], "shortcuts.save"], ]; // Widgets that own these keys natively; the editor shortcuts must not steal them. const WIDGET_KEYS: Record = { "[role=tab],[role=radio]": ["arrowleft", "arrowright", " "], "[role=switch],[role=checkbox]": [" "], }; /** "Part 2 · The bank calls back" for series parts, else the hook title, else "Clip n". */ export function clipPickerLabel(t: ReturnType>, clip: ClipSummary) { if (clip.workflow_role === "part" && clip.part_number) { const title = partTitle(clip); return title ? t("partClipLabel", { n: clip.part_number, title }) : t("partLabel", { n: clip.part_number }); } return clip.hook_title?.trim() || t("clipLabel", { order: clip.clip_order }); } interface Props { taskId: string; title: string; clips: ClipSummary[]; clip: ClipSummary; onSelect: (id: string) => void; refreshClips: (id?: string) => Promise; } export function EditorWorkspace({ taskId, title, clips, clip, onSelect, refreshClips, }: Props) { const t = useTranslations("editor"); const endpoint = `/api/tasks/${taskId}/clips/${clip.id}/editor`; const editor = useEditor(endpoint), doc = editor.document, asset = editor.asset; const [tab, setTab] = useState("captions"), [segmentIndex, setSegmentIndex] = useState(0), [time, setTime] = useState(0); // Paint timeline typing immediately without adding a history/save entry per key. const [timelineTextDraft, setTimelineTextDraft] = useState(); const [seekRequest, setSeekRequest] = useState({ time: 0, nonce: 0 }); const [exportOpen, setExportOpen] = useState(false), [helpOpen, setHelpOpen] = useState(false), [restoreOpen, setRestoreOpen] = useState(false), [reloadOpen, setReloadOpen] = useState(false); const [selected, setSelected] = useState([]), [combining, setCombining] = useState(false); const [brollId, setBrollId] = useState(null); const [clipsOpen, setClipsOpen] = useState(false); const videoRef = useRef(null); const index = doc ? Math.min(segmentIndex, doc.segments.length - 1) : 0; const seek = useCallback((value: number) => { setTime(value); setSeekRequest({ time: value, nonce: Date.now() }); }, []); // Jump to a source time from B-roll, playing it in the segment that contains it. const seekSource = useCallback( (value: number) => { if (doc && !(doc.segments[index]?.start <= value && value < doc.segments[index]?.end)) { const containing = doc.segments.findIndex((s) => s.start <= value && value < s.end); if (containing >= 0) setSegmentIndex(containing); } seek(value); }, [doc, index, seek], ); const selectBroll = useCallback((id: string | null) => { setBrollId(id); if (id) setTab("broll"); }, []); const switchClip = async (id: string) => { if (id === clip.id) return; try { await editor.save(); } catch { toast.error(t("workspace.keepLocal")); return; } onSelect(id); }; const applyAll = async (style: CaptionStyle) => { try { await editor.save(); for (const c of clips) { if (c.id === clip.id) continue; const url = `/api/tasks/${taskId}/clips/${c.id}/editor`, state = await readyEditor(url); await editorRequest(url, "PATCH", { basis: state.basis, revision: state.draft.revision, document: { ...state.draft.document, captions: style }, }); } toast.success(t("workspace.styleApplied")); } catch (e) { toast.error(editorMessage(t, (e as Error).message)); } }; const combine = async () => { setCombining(true); try { await editor.save(); for (const id of selected) await readyEditor(`/api/tasks/${taskId}/clips/${id}/editor`); const result = await editorRequest<{ id: string; anchor_clip_id: string; }>(`/api/tasks/${taskId}/editor/combine`, "POST", { clip_ids: selected }); const started = Date.now(); let combinedId = ""; while (!combinedId) { const job = await editorRequest<{ status: string; clip_id?: string; error?: string; }>( `/api/tasks/${taskId}/clips/${result.anchor_clip_id}/editor/exports/${result.id}`, ); if (job.status === "failed" || job.status === "cancelled") throw new Error(job.error || "Combine cancelled"); if (job.clip_id) combinedId = job.clip_id; else { if (Date.now() - started > 600_000) throw new Error( "The combine is still running in the export queue. Refresh your clips when it completes.", ); await new Promise((r) => setTimeout(r, 1500)); } } await refreshClips(combinedId); toast.success(t("workspace.combined")); } catch (e) { toast.error(editorMessage(t, (e as Error).message)); } finally { setCombining(false); } }; useEffect(() => { const handle = (event: KeyboardEvent) => { const target = event.target as HTMLElement; const key = event.key.toLowerCase(); if ( target.closest( "input,textarea,select,[contenteditable=true],[role=dialog],[role=slider],[role=listbox],[role=combobox]", ) || Object.entries(WIDGET_KEYS).some( ([selector, keys]) => target.closest(selector) && keys.includes(key), ) || helpOpen || exportOpen || restoreOpen || reloadOpen || !doc || !asset ) return; if (event.metaKey || event.ctrlKey) { if (key === "z") { event.preventDefault(); if (event.shiftKey) editor.redo(); else editor.undo(); } if (key === "y") { event.preventDefault(); editor.redo(); } if (key === "s") { event.preventDefault(); void editor.save().catch(() => {}); } return; } const segment = doc.segments[index]; if (event.code === "Space") { event.preventDefault(); document .querySelector( videoRef.current?.paused ? `button[aria-label="${CSS.escape(t("preview.play"))}"]` : `button[aria-label="${CSS.escape(t("preview.pause"))}"]`, ) ?.click(); } if (key === "arrowleft" || key === "arrowright") { event.preventDefault(); videoRef.current?.pause(); seek( clamp( time + (key === "arrowleft" ? -1 : 1) * (event.shiftKey ? 1 : 1 / asset.fps), 0, asset.duration, ), ); } if (key === "i") { event.preventDefault(); editor.update((d) => ({ ...d, segments: d.segments.map((s, i) => i === index ? { ...s, start: clamp(time, 0, segment.end - 0.04) } : s, ), })); } if (key === "o") { event.preventDefault(); editor.update((d) => ({ ...d, segments: d.segments.map((s, i) => i === index ? { ...s, end: clamp(time, segment.start + 0.04, asset.duration) } : s, ), })); } if (key === "s") { event.preventDefault(); editor.update((d) => splitSegment(d, index, time)); } if ((key === "delete" || key === "backspace") && brollId) { event.preventDefault(); editor.update((d) => ({ ...d, broll: (d.broll ?? []).filter((b) => b.id !== brollId) })); setBrollId(null); } if (key === "?") setHelpOpen(true); }; window.addEventListener("keydown", handle); return () => window.removeEventListener("keydown", handle); }, [ brollId, asset, doc, editor, index, time, seek, helpOpen, exportOpen, restoreOpen, reloadOpen, t, ]); const saved = editor.status === "All changes saved", saving = editor.status === "Saving…"; const shortcutKey = (key: string) => key === "space" ? t("keys.space") : key === "shift" ? t("keys.shift") : key === "mod" ? t("keys.mod") : key; return ( // data-editor-studio hides the app's floating feedback button, which would cover the timeline.

{title}

/
{t("workspace.clips")} {clips.length}
    {clips.map((c) => { const current = c.id === clip.id, order = selected.indexOf(c.id); return (
  • = 0} onCheckedChange={(checked) => setSelected((ids) => (checked ? [...ids, c.id] : ids.filter((id) => id !== c.id))) } className="relative z-10 bg-background" />
  • ); })}
{selected.length >= 2 ? ( ) : null}

{selected.length >= 2 ? t("workspace.combineHint") : selected.length === 1 ? t("workspace.combineOneMore") : t("workspace.combineEmpty")}

{saved ? ( ) : saving ? ( ) : editor.error ? ( ) : null} {editorStatus(t, editor.status)}
setHelpOpen(true)} > setRestoreOpen(true)}> {t("workspace.restore")}

{t("workspace.draftNote")}

{(editor.error || editor.storageError) && (
{editor.error && ( {editorMessage(t, editor.error)} {doc ? ( <> ) : ( )} )} {editor.storageError && ( {t("workspace.storageFull")} )}
)}
{doc && asset?.status === "ready" ? ( <>
) : null } />
) : (
{editor.error ? ( ) : ( )}

{editor.error ? t("workspace.previewBack") : t("workspace.preparingCanvas")}

{editor.error ? t("workspace.previewBackDetail") : t("workspace.preparingDetail")}

{!editor.error && ( )}
)}
{doc && asset?.status === "ready" && (
videoRef.current?.pause()} doc={doc} asset={asset} endpoint={endpoint} currentTime={time} onTextDraft={setTimelineTextDraft} index={index} select={setSegmentIndex} seek={seek} update={editor.update} brollId={brollId} selectBroll={selectBroll} seekBroll={seekSource} addBroll={() => setTab("broll")} />
)} {doc && asset && ( )} {t("workspace.shortcuts")} {t("workspace.shortcutsDescription")}
{SHORTCUTS.map(([keys, label]) => (
{t(label)}
))}
{t("workspace.restoreTitle")} {t("workspace.restoreDescription")} {t("workspace.reloadTitle")} {t("workspace.reloadDescription")}
); }