"use client"; import { ArrowLeft, ArrowRight, AudioLines, Captions, Clapperboard, CaptionsOff, Copy, Film, Scissors, Trash2, Type, Volume2, VolumeX, ZoomIn, ZoomOut, } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { useTranslations } from "next-intl"; import { Input } from "@/components/ui/input"; import { Slider } from "@/components/ui/slider"; import { Separator } from "@/components/ui/separator"; import { cn } from "@/lib/utils"; import { captionGroups, clamp, editDuration, hookRange, locate, mappedBroll, mappedWords, outputTime, placeBrollOnTimeline, replaceCaptionGroup, sequence, splitSegment, timecode, uid, type EditDocument, type EditorState, } from "@/lib/editor/document"; import { Panel, ToolButton } from "./studio-ui"; import { Filmstrip } from "./filmstrip"; import { InlineText } from "./inline-text"; import { HookTrack } from "./hook-track"; import { prepareTextDraft, type TextDraft } from "@/lib/editor/render"; interface Props { doc: EditDocument; asset: EditorState; endpoint: string; /** Playhead on the source timeline (the video element's time). */ currentTime: number; onTextDraft: (draft: TextDraft | undefined) => void; index: number; select: (index: number) => void; pause: () => void; seek: (time: number) => void; update: (change: (doc: EditDocument) => EditDocument, group?: string) => void; brollId: string | null; selectBroll: (id: string | null) => void; /** Open the B-roll panel to add footage. */ addBroll?: (time: number) => void; /** Seek for B-roll, which may sit in another segment. */ seekBroll?: (time: number) => void; } const MIN_SEGMENT = 0.04; const TRACK = { video: "h-12 [@media(max-height:780px)]:h-10", broll: "h-8", captions: "h-7", hook: "h-7", audio: "h-8", }; /** Ruler label: whole seconds as m:ss, half seconds with one decimal. */ function rulerLabel(seconds: number, step: number) { const minutes = Math.floor(seconds / 60), rest = seconds - minutes * 60; return `${minutes}:${step < 1 ? rest.toFixed(1).padStart(4, "0") : String(Math.round(rest)).padStart(2, "0")}`; } /** A readable ruler step for the visible duration. */ function rulerStep(visibleSeconds: number) { const steps = [0.5, 1, 2, 5, 10, 15, 30, 60, 120]; return steps.find((step) => visibleSeconds / step <= 10) ?? 300; } /** * Classic sequence timeline: the edit as clips laid end to end on V1, with * B-roll, caption and audio tracks underneath and one playhead through all of * them. Times here are edit (output) seconds; the document stores source seconds. */ export function Timeline({ doc, asset, endpoint, currentTime, onTextDraft, index, select, pause, seek, update, brollId, selectBroll, addBroll, }: Props) { const t = useTranslations("editor"); const [zoom, setZoom] = useState(1); const scroller = useRef(null); const lanes = useRef(null); const items = sequence(doc); const total = Math.max(0.01, editDuration(doc)); const hook = doc.hookTitle?.trim() ? hookRange(doc) : null; const active = doc.segments[index] ?? doc.segments[0]; const playhead = clamp( outputTime(doc, Math.min(index, doc.segments.length - 1), clamp(currentTime, active.start, active.end)), 0, total, ); const pct = (seconds: number) => `${(seconds / total) * 100}%`; const at = (clientX: number) => { const box = lanes.current?.getBoundingClientRect(); return box ? clamp((clientX - box.left) / box.width, 0, 1) * total : 0; }; const seekOut = (time: number) => { const target = locate(doc, time); select(target.index); seek(target.source); }; const secondsPerPixel = () => total / (lanes.current?.getBoundingClientRect().width || 1); // Keep the playhead in view while zoomed in. useEffect(() => { const box = scroller.current; if (!box || zoom === 1) return; const x = (playhead / total) * box.scrollWidth; if (x < box.scrollLeft + 40 || x > box.scrollLeft + box.clientWidth - 40) box.scrollLeft = Math.max(0, x - box.clientWidth / 3); }, [playhead, total, zoom]); const setRange = (start: number, end: number) => update( (d) => ({ ...d, segments: d.segments.map((s) => s.id === active.id ? { ...s, start: clamp(start, 0, end - MIN_SEGMENT), end: clamp(end, start + MIN_SEGMENT, asset.duration), } : s, ), }), "trim", ); const move = (direction: number) => { const target = index + direction; if (target < 0 || target >= doc.segments.length) return; update((d) => { const segments = [...d.segments]; [segments[index], segments[target]] = [segments[target], segments[index]]; return { ...d, segments }; }); select(target); }; const canSplit = currentTime > active.start + MIN_SEGMENT && currentTime < active.end - MIN_SEGMENT; // Scrub: press on the ruler or empty track space and drag. const scrub = useRef(false); const startScrub = (e: React.PointerEvent) => { if (e.target !== e.currentTarget) return; scrub.current = true; (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); seekOut(at(e.clientX)); }; const moveScrub = (e: React.PointerEvent) => { if (scrub.current) seekOut(at(e.clientX)); }; const endScrub = () => { scrub.current = false; }; const scrubbing = { onPointerDown: startScrub, onPointerMove: moveScrub, onPointerUp: endScrub, onPointerCancel: endScrub }; // Trim a clip by dragging its edge; the clips after it ripple. const trim = useRef<{ id: string; edge: "start" | "end"; x: number; start: number; end: number; scale: number } | null>(null); const beginTrim = (e: React.PointerEvent, segmentIndex: number, edge: "start" | "end") => { e.stopPropagation(); const segment = doc.segments[segmentIndex]; select(segmentIndex); trim.current = { id: segment.id, edge, x: e.clientX, start: segment.start, end: segment.end, scale: secondsPerPixel() }; (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId); }; const moveTrim = (e: React.PointerEvent) => { const d = trim.current; if (!d) return; const delta = (e.clientX - d.x) * d.scale; update( (current) => ({ ...current, segments: current.segments.map((s) => s.id !== d.id ? s : d.edge === "start" ? { ...s, start: clamp(d.start + delta, 0, d.end - MIN_SEGMENT) } : { ...s, end: clamp(d.end + delta, d.start + MIN_SEGMENT, asset.duration) }, ), }), "trim", ); }; const groups = captionGroups(mappedWords(doc), doc.captions.wordsPerLine); const pieces = mappedBroll(doc); const step = rulerStep(total / zoom); // Labels too close to the end would be clipped by the card edge. const ticks = Array.from({ length: Math.floor(total / step) + 1 }, (_, i) => i * step).filter( (tick) => tick === 0 || total - tick > step * 0.35, ); // Track headers are icons; the name is in the tooltip and accessible label. const header = (icon: React.ReactNode, label: string, height: string, control?: React.ReactNode) => (
{control ?? ( {icon} )}
); const minor = Array.from({ length: Math.ceil(total / (step / 4)) }, (_, i) => (i * step) / 4).filter( (time) => Math.abs(time / step - Math.round(time / step)) > 1e-6, ); return (
update((d) => splitSegment(d, index, currentTime))} > { update((d) => ({ ...d, segments: d.segments.filter((s) => s.id !== active.id) })); select(Math.max(0, index - 1)); }} > update((d) => ({ ...d, segments: [...d.segments.slice(0, index + 1), { ...active, id: uid() }, ...d.segments.slice(index + 1)], })) } > move(-1)}> = doc.segments.length - 1} onClick={() => move(1)} > {(["in", "out"] as const).map((edge) => ( ))} setRange(clamp(currentTime, 0, active.end - MIN_SEGMENT), active.end)} > {t("timeline.setIn")} setRange(active.start, clamp(currentTime, active.start + MIN_SEGMENT, asset.duration))} > {t("timeline.setOut")}
{t(doc.segments.length === 1 ? "timeline.summaryOne" : "timeline.summaryOther", { count: doc.segments.length, duration: timecode(total), })} setZoom((z) => Math.max(1, z / 1.5))}> setZoom(value)} /> = 12} onClick={() => setZoom((z) => Math.min(12, z * 1.5))}>
{header(, t("timeline.tracks.video"), TRACK.video)} {header(, t("timeline.tracks.broll"), TRACK.broll)} {hook && header(, t("captions.hookTitle"), TRACK.hook)} {header( null, t("timeline.tracks.captions"), TRACK.captions, , )} {header( , t("timeline.tracks.audio"), TRACK.audio, asset.hasAudio ? ( ) : undefined, )}
{ticks.map((tick) => ( {rulerLabel(tick, step)} ))} {minor.map((time) => ( ))}
{items.map((item) => { const length = item.end - item.start; const selected = item.index === index; return (
{ e.stopPropagation(); seekOut(at(e.clientX)); }} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); select(item.index); seek(item.segment.start); } }} > {t("timeline.segment", { n: item.index + 1 })} {(["start", "end"] as const).map((edge) => ( beginTrim(e, item.index, edge)} onPointerMove={moveTrim} onPointerUp={() => (trim.current = null)} onPointerCancel={() => (trim.current = null)} > ))}
); })}
{hook && }
{groups.map((group) => ( w.text).join(" ")} label={t("timeline.tracks.captions")} maxLength={960} className="absolute inset-y-0 overflow-hidden rounded-md bg-stone-100 px-1.5 text-left text-[11px] leading-7 text-stone-600 transition-colors hover:bg-stone-200 dark:bg-stone-800 dark:text-stone-300" style={{ left: pct(group[0].start), width: pct(Math.max(0.05, group[group.length - 1].end - group[0].start)) }} title={group.map((w) => w.text).join(" ")} onBegin={() => { pause(); seekOut(group[0].start + 0.001); }} onDraft={text => onTextDraft(text === null ? undefined : prepareTextDraft(doc, group[0].start, "captions", text))} onCommit={text => update(current => replaceCaptionGroup(current, group.map(word => word.id), text, asset.duration))} > {group.map((w) => w.text).join(" ")} ))}
{asset.hasAudio && items.map((item) => { const n = asset.waveform.length; const from = Math.floor((item.segment.start / asset.duration) * n); const to = Math.max(from + 1, Math.ceil((item.segment.end / asset.duration) * n)); const slice = asset.waveform.slice(from, to); return ( {slice.map((v, i) => ( ))} ); })}
seekOut(Number(e.target.value))} /> ); } function BRollTrack({ doc, total, pieces, selected, select, seekOut, update, add, at, secondsPerPixel, duration, }: { doc: EditDocument; total: number; pieces: ReturnType; selected: string | null; select: (id: string | null) => void; seekOut: (time: number) => void; update: Props["update"]; add?: (time: number) => void; at: (clientX: number) => number; secondsPerPixel: () => number; duration: number; }) { const t = useTranslations("editor"); const drag = useRef<{ id: string; mode: "move" | "start" | "end"; x: number; document: EditDocument; piece: ReturnType[number]; group: string; scale: number; moved: boolean; } | null>(null); const laneRef = useRef(null); const ignoreClick = useRef(false); const pct = (seconds: number) => `${(seconds / total) * 100}%`; const begin = (e: React.PointerEvent, piece: ReturnType[number], mode: "move" | "start" | "end") => { const clip = piece.clip; e.stopPropagation(); select(clip.id); ignoreClick.current = true; drag.current = { id: clip.id, mode, x: e.clientX, document: doc, piece, group: `gesture:${uid()}`, scale: secondsPerPixel(), moved: false }; // Crossing a cut changes the piece's segment/key. Capture on the stable lane. laneRef.current?.setPointerCapture(e.pointerId); }; const move = (e: React.PointerEvent) => { const d = drag.current; if (!d) return; if (!(e.buttons & 1)) { drag.current = null; return; } if (Math.abs(e.clientX - d.x) > 2) d.moved = true; if (!d.moved) return; const delta = (e.clientX - d.x) * d.scale; const placed = placeBrollOnTimeline(d.document, d.id, d.piece, d.mode, delta, duration); update(current => ({ ...current, broll: placed.broll }), d.group); }; const end = (e: React.PointerEvent) => { const d = drag.current; drag.current = null; if (d && !d.moved) seekOut(at(e.clientX)); }; return (
{ if (e.target === e.currentTarget) ignoreClick.current = false; }} onPointerMove={move} onPointerUp={end} onPointerCancel={() => (drag.current = null)} onLostPointerCapture={() => (drag.current = null)} className={cn("relative cursor-copy rounded-lg", TRACK.broll, pieces.length === 0 && "bg-stone-50 dark:bg-stone-900/50")} onClick={(e) => { if (ignoreClick.current) { ignoreClick.current = false; return; } if (e.target !== e.currentTarget) return; const time = at(e.clientX); select(null); seekOut(time); add?.(time); }} > {pieces.map((piece) => { const clip = piece.clip; return (
begin(e, piece, "move")} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); select(clip.id); seekOut(piece.start + 0.001); } }} > {clip.query || t("broll.untitled")} {(["start", "end"] as const).map((edge) => ( begin(e, piece, edge)} /> ))}
); })} {pieces.length === 0 && ( {t("broll.laneEmpty")} )}
); }