Spaces:
Running
Composite the editor preview in the browser so edits show up live
Browse filesThe preview was a single <video> whose src was swapped per clip, so every cut
re-fetched from the CDN and stalled, and captions/titles/music existed only in
ffmpeg at export — you styled a caption and saw nothing until a multi-minute
round trip. Now the playhead (global timeline seconds) is the single source of
truth: one <video> per clip stays mounted and preloaded and only the active one
is shown, so playback is gapless; captions and titles are drawn as DOM boxes
using the export's own geometry (preview.ts mirrors _render_overlay_png and
_OVERLAY_Y, scaled by previewWidth/videoWidth); music previews through a synced
<audio>. The timeline scrubs on click/drag and space toggles playback.
Fixes three ways an edit could silently corrupt:
- Caption edits were keyed by array index, so reordering or trimming a clip
moved hand-edited text onto different words. Cues now carry a stable
clip-key#ordinal identity.
- Titles held absolute timeline seconds while trims moved the timeline under
them; they're now anchored to a clip + offset and resolved at export, and one
whose clip was deleted is dropped rather than exported at 0s.
- Closing the editor discarded every trim, caption and overlay. State autosaves
per render and is restored with a "start fresh" escape hatch.
Also: deleting a clip is undoable, the playhead no longer jumps backwards at a
clip boundary, and rAF drives the playhead at ~30fps instead of onTimeUpdate's
~4fps so captions track the video smoothly.
preview.check.ts covers the cue-key and geometry invariants (21 assertions); no
test runner is configured, so it documents its own esbuild+node one-liner.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Files changed (3)
12345678 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606147 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371382 unmodified lines1411421431441451461 unmodified line1481491501511521531545 unmodified lines1601611621631641651661674 unmodified lines1721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042057 unmodified lines2132142152162172181 unmodified line22022122222322422514 unmodified lines2402412422432442452462472482492508 unmodified lines2592602612622632642652662672682692702712722 unmodified lines2752762772782792802812822832842852862872882892902912922932942952962974 unmodified lines3023033043053063073082 unmodified lines3113123133143153163173183193203213223233243253263 unmodified lines3303313323333343354 unmodified lines34034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441518 unmodified lines43443543643743843944012 unmodified lines4534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925938 unmodified lines6026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676685 unmodified lines6746756766776786796806816826836846856865 unmodified lines69269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477530 unmodified lines80680780880981081181281381412 unmodified lines82782882983083183283383483583683783883984084153 unmodified lines89589689789889990090190290390490590690790890915 unmodified lines9259269279289299309311 unmodified line9339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310447 unmodified lines105210531054105510561057105821 unmodified lines10801081108210831084108510863 unmodified lines10901091109210931094109510967 unmodified lines11041105110611071108110911101111111211131114111514 unmodified lines1130113111321133113411351136import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { api, ApiError } from "../api/client";import type { CaptionCue, RenderClip, TextOverlay } from "../api/types";import { Loader } from "./Loader";type Track = {key: string;8 unmodified linesout: number;};type Overlay = TextOverlay & { key: string };type Stage = "loading" | "editing" | "exporting" | "done" | "empty";type Tab = "clips" | "captions" | "text" | "audio";type CaptionSource = "script" | "ai" | "none";const PX_PER_SEC = 46;const WORDS_PER_CUE = 4;/** Mirrors the backend's build_cues: chunk each clip's line into a few words and* split the clip's (trimmed) duration across chunks by character length. */function buildCues(clips: { spoken: string; duration: number }[]): CaptionCue[] {const cues: CaptionCue[] = [];let clock = 0;for (const c of clips) {const text = (c.spoken || "").trim();if (c.duration <= 0) continue;if (!text) {clock += c.duration;continue;}const words = text.split(/\s+/);const chunks: string[] = [];for (let i = 0; i < words.length; i += WORDS_PER_CUE) {chunks.push(words.slice(i, i + WORDS_PER_CUE).join(" "));}const totalChars = chunks.reduce((s, x) => s + x.length, 0) || 1;let t = clock;for (const chunk of chunks) {const span = c.duration * (chunk.length / totalChars);cues.push({text: chunk,start: Math.round(t * 100) / 100,end: Math.round((t + span) * 100) / 100,});t += span;}clock += c.duration;}return cues;}function TabBtn({active,47 unmodified linesconst [busyClip, setBusyClip] = useState(false);const [regenPrompt, setRegenPrompt] = useState("");const [regenSpoken, setRegenSpoken] = useState("");const [cueEdits, setCueEdits] = useState<Record<number, string>>({});const [music, setMusic] = useState<{ path: string; name: string } | null>(null);const [musicVolume, setMusicVolume] = useState(0.25);const [overlays, setOverlays] = useState<Overlay[]>([]);const [resultUrl, setResultUrl] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const dragKey = useRef<string | null>(null);const mounted = useRef(true);// --- preview playback -------------------------------------------------- //// The preview honours each clip's trim window, so dragging a handle shows the// frame you're cutting to and "play" runs the edit as it will export — no// round-trip to the backend.const videoRef = useRef<HTMLVideoElement | null>(null);const [cursor, setCursor] = useState(0); // playhead within the CURRENT clipconst [playingAll, setPlayingAll] = useState(false);/** Move the preview to `t` seconds within the selected clip. */const seek = useCallback((t: number) => {const v = videoRef.current;if (v && Number.isFinite(t)) v.currentTime = Math.max(0, t);}, []);useEffect(() => {mounted.current = true;2 unmodified lines};}, []);const load = useCallback(async () => {try {const clips: RenderClip[] = await api.getRenderClips(renderId);1 unmodified linesetStage("empty");return;}const next = clips.map((c, i) => ({key: `${c.index}-${i}`,index: c.index,url: c.url,5 unmodified linesin: 0,out: c.duration,}));setTracks(next);setSelected(next[0]?.key ?? null);try {setFonts(await api.listFonts());} catch {4 unmodified linessetError(err instanceof ApiError ? err.message : "Failed to load clips");setStage("editing");}}, [renderId]);useEffect(() => {load();}, [load]);// Prefill the regenerate fields from the selected clip so a blank submit means// "same again" and the stored prompt is visible/editable.useEffect(() => {const t = tracks.find((x) => x.key === selected);setRegenPrompt(t?.prompt ?? "");setRegenSpoken(t?.spoken ?? "");}, [selected, tracks]);const editable = stage === "editing";const total = tracks.reduce((s, t) => s + (t.out - t.in), 0);const cues = useMemo(() => buildCues(tracks.map((t) => ({ spoken: t.spoken, duration: t.out - t.in }))),[tracks],);const finalCues = cues.map((c, i) => ({ ...c, text: cueEdits[i] ?? c.text }));function patch(key: string, next: Partial<Track>) {setTracks((ts) => ts.map((t) => (t.key === key ? { ...t, ...next } : t)));}function remove(key: string) {setTracks((ts) => ts.filter((t) => t.key !== key));setSelected((s) => (s === key ? null : s));}function reorder(fromKey: string, toKey: string) {setTracks((ts) => {7 unmodified lines});}async function onMusicFile(e: React.ChangeEvent<HTMLInputElement>) {const file = e.target.files?.[0];e.target.value = "";1 unmodified linetry {const res = await api.uploadMedia(file);setMusic({ path: res.path, name: file.name });} catch (err) {setError(err instanceof ApiError ? err.message : "Failed to upload music");}14 unmodified lines}}async function regenerateSelected(sel: Track) {setBusyClip(true);setError(null);try {const { task_id } = await api.regenerateClip(renderId, sel.index, {prompt: regenPrompt.trim() || undefined,spoken: regenSpoken.trim() ? regenSpoken : undefined,use_reference: true, // seed b-roll with the clip being replaced8 unmodified lines}}async function uploadSelected(sel: Track, e: React.ChangeEvent<HTMLInputElement>) {const file = e.target.files?.[0];e.target.value = "";if (!file) return;setBusyClip(true);setError(null);try {await api.uploadClip(renderId, sel.index, file);await load();} catch (err) {setError(err instanceof ApiError ? err.message : "Failed to upload clip");2 unmodified lines}}function addOverlay() {setOverlays((o) => [...o,{key: `ov-${o.length}-${Math.random().toString(36).slice(2, 7)}`,text: "",position: "bottom",start: 0,end: null,color: "#39E508",size: 48,},]);}async function handleExport() {if (tracks.length === 0) return;setStage("exporting");setError(null);setResultUrl(null);4 unmodified lines{captions: captionSource !== "none",captionSource,captionCues: captionSource === "script" ? finalCues : [],captionColor,captionSize,captionPosition,2 unmodified linescaptionBgOpacity: captionBgOpacity,music: music?.path ?? null,musicVolume,overlays: overlays.filter((o) => o.text.trim()).map((o) => ({text: o.text,position: o.position,start: o.start,end: o.end,color: o.color,size: o.size,})),},);while (mounted.current) {3 unmodified linesif (s.status === "ready") {setResultUrl(s.video_url ?? null);setStage("done");onExported();return;}4 unmodified lines}}} catch (err) {setError(err instanceof ApiError ? err.message : "Failed to export");setStage("editing");}}const sel = tracks.find((t) => t.key === selected) ?? null;const selIdx = tracks.findIndex((t) => t.key === selected);const width = Math.max(total * PX_PER_SEC, 240);const ticks = Array.from({ length: Math.ceil(total) + 1 }, (_, i) => i);// Where the playhead sits on the timeline: every earlier clip's TRIMMED length,// plus how far into this clip's own trim window we are.const elapsedBefore = tracks.slice(0, Math.max(selIdx, 0)).reduce((s, t) => s + (t.out - t.in), 0);const playhead = sel ? elapsedBefore + Math.max(0, cursor - sel.in) : 0;// Selecting a clip parks the preview on its first kept frame. A brand-new src// isn't loaded yet, so onLoadedMetadata does the seek in that case.useEffect(() => {const v = videoRef.current;setCursor(sel?.in ?? 0);if (v && sel && v.readyState > 0) {v.currentTime = sel.in;if (playingAll) void v.play();}// playingAll/sel.in intentionally excluded: re-seeking on every handle drag// would fight the scrub below.// eslint-disable-next-line react-hooks/exhaustive-deps}, [selected]);function onLoadedMetadata(e: React.SyntheticEvent<HTMLVideoElement>) {const v = e.currentTarget;v.currentTime = sel?.in ?? 0;if (playingAll) void v.play();}/** Keep playback inside [in, out]; at `out`, roll on to the next clip. */function onTick(e: React.SyntheticEvent<HTMLVideoElement>) {const v = e.currentTarget;setCursor(v.currentTime);if (!sel) return;if (v.currentTime >= sel.out - 0.03) {if (playingAll && selIdx >= 0 && selIdx < tracks.length - 1) {setSelected(tracks[selIdx + 1].key);} else {v.pause();setPlayingAll(false);v.currentTime = sel.in;}} else if (v.currentTime < sel.in - 0.05) {v.currentTime = sel.in; // a trim-in moved past the playhead}}/** Play the whole edit from the top, respecting every trim. */function playTimeline() {const v = videoRef.current;if (!v || tracks.length === 0) return;if (playingAll) {v.pause();setPlayingAll(false);return;}setPlayingAll(true);if (selIdx === 0) {v.currentTime = tracks[0].in;void v.play();} else {setSelected(tracks[0].key); // the effect above seeks and starts playback}}18 unmodified lines</button><buttontype="button"onClick={onClose}className="border border-white/15 px-3 py-2 font-display text-xs tracking-wider text-chalk-dim uppercase hover:border-white/30 hover:text-chalk">← Renders12 unmodified lines{error && <p className="mb-3 text-sm text-tally">{error}</p>}{tracks.length > 0 && stage !== "loading" && stage !== "empty" && (<>{/* ---------- TIMELINE ---------- */}<div className="overflow-x-auto border border-white/10 bg-ink"><div style={{ width }} className="relative min-w-full">{/* playhead — spans every track so the preview position readsagainst the clips, captions and music at once */}<divclassName="pointer-events-none absolute top-0 bottom-0 z-10 w-px bg-tally"style={{ left: playhead * PX_PER_SEC }}><span className="absolute -top-0.5 -left-[3px] h-1.5 w-1.5 rotate-45 bg-tally" /></div>{/* ruler */}<div className="relative h-5 border-b border-white/10">{ticks.map((s) => (<spankey={s}className="absolute top-0 h-full border-l border-white/10 pl-1 font-script text-[9px] text-chalk-dim"style={{ left: s * PX_PER_SEC }}>{s}s</span>))}</div>{/* VIDEO track */}<div className="flex items-stretch gap-px border-b border-white/10">{tracks.map((t, i) => (<buttontype="button"key={t.key}draggable={editable}onDragStart={() => (dragKey.current = t.key)}onDragOver={(e) => e.preventDefault()}onDrop={() => {if (dragKey.current) reorder(dragKey.current, t.key);dragKey.current = null;}}onClick={() => setSelected(t.key)}style={{ width: Math.max((t.out - t.in) * PX_PER_SEC, 34) }}className={`group relative h-14 shrink-0 overflow-hidden border-l-2 px-1.5 py-1 text-left transition ${t.isBroll ? "border-l-gaffer bg-gaffer/10" : "border-l-print bg-print/10"} ${selected === t.key ? "ring-1 ring-chalk/60" : "hover:bg-white/5"}`}title={t.spoken || `Clip ${i + 1}`}><span className="block font-display text-[10px] tracking-wider text-chalk">{i + 1} {t.isBroll ? "B" : "P"}</span><span className="timecode block text-[9px] text-chalk-dim">{(t.out - t.in).toFixed(1)}s</span>{editable && (<span className="absolute right-0.5 bottom-0.5 cursor-grab text-[9px] text-chalk-dim opacity-0 group-hover:opacity-100">⠿</span>)}</button>))}</div>{/* VOICE track */}<div className="flex items-stretch gap-px border-b border-white/10">{tracks.map((t) => (<divkey={t.key}style={{ width: Math.max((t.out - t.in) * PX_PER_SEC, 34) }}className="h-9 shrink-0 overflow-hidden bg-viewfinder/10 px-1.5 py-1"title={t.spoken}><span className="block truncate font-script text-[9px] text-viewfinder">♪ {t.spoken || "—"}</span></div>))}</div>{/* CAPTIONS track */}<div className="relative h-7 border-b border-white/10">{captionSource === "none" ? (<span className="absolute left-1.5 top-1 font-script text-[9px] text-chalk-dim">captions off</span>) : captionSource === "ai" ? (<span className="absolute left-1.5 top-1 font-script text-[9px] text-clay">AI transcription (timing decided at export)</span>) : (finalCues.map((c, i) => (<spankey={i}className="absolute top-1 h-5 overflow-hidden border-l border-clay/60 bg-clay/20 px-1 font-script text-[9px] text-chalk"style={{left: c.start * PX_PER_SEC,width: Math.max((c.end - c.start) * PX_PER_SEC - 2, 12),}}title={`${c.start}s–${c.end}s · ${c.text}`}>{c.text}</span>)))}</div>{/* MUSIC track */}<div className="relative h-7">{music ? (<spanclassName="absolute top-1 h-5 overflow-hidden bg-gaffer/20 px-1.5 font-script text-[9px] text-gaffer"style={{ width: Math.max(total * PX_PER_SEC - 2, 40) }}>♫ {music.name} · {Math.round(musicVolume * 100)}%</span>) : (<span className="absolute left-1.5 top-1 font-script text-[9px] text-chalk-dim">no music — add one in the Audio tab</span>)}</div></div></div><p className="mt-1.5 font-script text-[10px] text-chalk-dim">Tracks: <span className="text-print">video</span> ·{" "}<span className="text-viewfinder">voice</span> · <span className="text-clay">captions</span> ·{" "}<span className="text-gaffer">music</span> — drag a clip to reorder, click to edit it.Trims apply to the preview live; “play all” runs the whole edit.</p>{/* ---------- TABS ---------- */}<div className="mt-5 flex flex-wrap gap-2"><TabBtn active={tab === "clips"} onClick={() => setTab("clips")}>Clip</TabBtn><TabBtn active={tab === "captions"} onClick={() => setTab("captions")} count={finalCues.length}>Captions</TabBtn><TabBtn active={tab === "text"} onClick={() => setTab("text")} count={overlays.length}>8 unmodified lines{/* --- CLIP --- */}{tab === "clips" &&(sel ? (<div className="flex flex-wrap gap-5"><div className="space-y-1.5"><videoref={videoRef}src={sel.url}onLoadedMetadata={onLoadedMetadata}onTimeUpdate={onTick}onPause={() => setPlayingAll(false)}playsInlineclassName="max-h-64 bg-black"/>{/* Position inside the trim window, not the source clip. */}<div className="h-1 w-full bg-white/10"><divclassName="h-full bg-print transition-[width] duration-100"style={{width: `${Math.min(100, Math.max(0, ((cursor - sel.in) / Math.max(0.1, sel.out - sel.in)) * 100))}%`,}}/></div><div className="flex items-center gap-2"><buttontype="button"onClick={() => {const v = videoRef.current;if (!v) return;if (v.paused) void v.play();else v.pause();}}className="border border-white/15 px-2 py-1 font-display text-[10px] tracking-wider text-chalk-dim uppercase hover:border-white/30 hover:text-chalk">play clip</button><buttontype="button"onClick={playTimeline}className="border border-print/50 px-2 py-1 font-display text-[10px] tracking-wider text-print uppercase hover:bg-print hover:text-ink">{playingAll ? "stop" : "play all"}</button><span className="timecode text-[10px] text-chalk-dim">{Math.max(0, cursor - sel.in).toFixed(1)}s /{" "}{(sel.out - sel.in).toFixed(1)}s</span></div></div><div className="min-w-[16rem] flex-1 space-y-3"><p className="font-script text-[11px] text-chalk-dim">Clip {tracks.findIndex((t) => t.key === sel.key) + 1} ·{" "}<span className={sel.isBroll ? "text-gaffer" : "text-print"}>{sel.isBroll ? "B-ROLL" : "PRESENTER"}</span>{" "}· source {sel.duration.toFixed(1)}s · keeping{" "}<span className="text-chalk">{(sel.out - sel.in).toFixed(1)}s</span></p>{sel.spoken && (<p className="border-l-2 border-viewfinder/40 pl-2 font-script text-[11px] text-chalk">“{sel.spoken}”</p>)}<label className="block font-script text-[11px] text-chalk-dim">trim in — {sel.in.toFixed(1)}s<inputtype="range"5 unmodified linesonChange={(e) => {const next = Math.min(Number(e.target.value), sel.out - 0.2);patch(sel.key, { in: next });videoRef.current?.pause();seek(next); // show the first frame you're keeping}}className="mt-1 w-full"/></label><label className="block font-script text-[11px] text-chalk-dim">trim out — {sel.out.toFixed(1)}s<inputtype="range"5 unmodified linesonChange={(e) => {const next = Math.max(Number(e.target.value), sel.in + 0.2);patch(sel.key, { out: next });videoRef.current?.pause();seek(next - 0.05); // show the last frame you're keeping}}className="mt-1 w-full"/></label><buttontype="button"onClick={() => remove(sel.key)}disabled={!editable}className="border border-tally/50 px-2.5 py-1 font-display text-[11px] tracking-wider text-tally uppercase hover:bg-tally hover:text-ink disabled:opacity-40">✕ Delete clip</button>{/* --- regenerate / replace this clip --- */}<div className="space-y-2 border-t border-white/10 pt-3"><p className="font-display text-[11px] tracking-wider text-chalk-dim uppercase">Regenerate or replace</p><textareavalue={regenPrompt}placeholder={sel.isBroll? "B-roll prompt — edit to change the shot…": "Scene prompt — edit to change the shot…"}onChange={(e) => setRegenPrompt(e.target.value)}disabled={!editable || busyClip}rows={2}className="w-full resize-y border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"/><inputvalue={regenSpoken}placeholder={sel.isBroll? "Spoken line for this cutaway (optional)…": "Spoken line — edit to re-record the voiceover…"}onChange={(e) => setRegenSpoken(e.target.value)}disabled={!editable || busyClip}className="w-full border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"/><div className="flex flex-wrap items-center gap-2"><buttontype="button"onClick={() => regenerateSelected(sel)}disabled={!editable || busyClip}className="border border-gaffer/60 px-2.5 py-1 font-display text-[11px] tracking-wider text-gaffer uppercase hover:bg-gaffer hover:text-ink disabled:opacity-40">⟳ Regenerate</button><label className="flex items-center gap-2"><spanclassName={`cursor-pointer border border-white/15 px-2.5 py-1 font-display text-[11px] tracking-wider uppercase ${editable && !busyClip? "text-chalk-dim hover:border-print/50 hover:text-chalk": "text-chalk-dim opacity-40"}`}>↑ Upload own clip</span><inputtype="file"accept="video/*"onChange={(e) => uploadSelected(sel, e)}disabled={!editable || busyClip}className="hidden"/></label>{busyClip && <Loader label="Working" />}</div><p className="font-script text-[10px] text-chalk-dim">{sel.isBroll? "The clip being replaced is passed to the model as a reference, so the new take continues from it.": "Changing the spoken line regenerates the voiceover and re-animates the presenter, keeping the same face."}</p></div></div></div>) : (30 unmodified lines</div><p className="font-script text-[11px] text-chalk-dim">{captionSource === "script"? "Cues come from the script we already generated — instant, free, and always spelled correctly. Edit any line below.": captionSource === "ai"? "Transcribes the audio with a Whisper model on Replicate (slower, costs a call, can mis-spell).": "No captions will be burned in."}</p>12 unmodified lines<label className="flex items-center gap-2 font-script text-[11px] text-chalk-dim">size<inputtype="number"min={20}max={110}step={2}value={captionSize}onChange={(e) => setCaptionSize(Number(e.target.value))}disabled={!editable}className="w-16 border border-white/15 bg-slate-2 px-1.5 py-1 text-chalk"/></label><label className="flex items-center gap-2 font-script text-[11px] text-chalk-dim">position53 unmodified lines{captionSource === "script" && (<div className="max-h-72 space-y-1.5 overflow-y-auto border-t border-white/10 pt-3">{finalCues.map((c, i) => (<div key={i} className="flex items-center gap-2"><span className="timecode w-24 shrink-0 font-script text-[10px] text-chalk-dim">{c.start.toFixed(1)}–{c.end.toFixed(1)}s</span><inputvalue={c.text}onChange={(e) =>setCueEdits((m) => ({ ...m, [i]: e.target.value }))}disabled={!editable}className="flex-1 border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"15 unmodified lines<div className="space-y-2"><div className="flex items-center justify-between"><p className="font-script text-[11px] text-chalk-dim">Titles / CTAs burned over the video (on top of captions).</p><buttontype="button"1 unmodified linedisabled={!editable}className="border border-print/50 px-2.5 py-1 font-display text-[11px] tracking-wider text-print uppercase hover:bg-print hover:text-ink disabled:opacity-40">+ Add text</button></div>{overlays.map((o) => (<div key={o.key} className="flex flex-wrap items-center gap-2 border border-white/10 px-2.5 py-2"><inputvalue={o.text}placeholder="Overlay text…"onChange={(e) =>setOverlays((os) =>os.map((x) => (x.key === o.key ? { ...x, text: e.target.value } : x)),)}disabled={!editable}className="min-w-[10rem] flex-1 border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"/><selectvalue={o.position}onChange={(e) =>setOverlays((os) =>os.map((x) =>x.key === o.key? { ...x, position: e.target.value as Overlay["position"] }: x,),)}disabled={!editable}className="border border-white/15 bg-slate-2 px-1.5 py-1 font-script text-[11px] text-chalk"><option value="top">top</option><option value="center">center</option><option value="bottom">bottom</option></select><label className="flex items-center gap-1 font-script text-[10px] text-chalk-dim">from<inputtype="number"min={0}max={total}step={0.5}value={o.start}onChange={(e) =>setOverlays((os) =>os.map((x) =>x.key === o.key ? { ...x, start: Number(e.target.value) } : x,),)}disabled={!editable}className="w-14 border border-white/15 bg-slate-2 px-1 py-1 text-chalk"/>to<inputtype="number"min={0}max={total}step={0.5}value={o.end ?? Math.round(total)}onChange={(e) =>setOverlays((os) =>os.map((x) =>x.key === o.key ? { ...x, end: Number(e.target.value) } : x,),)}disabled={!editable}className="w-14 border border-white/15 bg-slate-2 px-1 py-1 text-chalk"/>s</label><inputtype="color"value={o.color}onChange={(e) =>setOverlays((os) =>os.map((x) => (x.key === o.key ? { ...x, color: e.target.value } : x)),)}disabled={!editable}className="h-7 w-8 cursor-pointer border border-white/15 bg-slate-2"/><inputtype="number"min={16}max={120}step={2}value={o.size}onChange={(e) =>setOverlays((os) =>os.map((x) => (x.key === o.key ? { ...x, size: Number(e.target.value) } : x)),)}disabled={!editable}className="w-14 border border-white/15 bg-slate-2 px-1 py-1 font-script text-[11px] text-chalk"/><buttontype="button"onClick={() => setOverlays((os) => os.filter((x) => x.key !== o.key))}disabled={!editable}className="text-tally hover:text-tally/70 disabled:opacity-40">✕</button></div>))}{overlays.length === 0 && (<p className="font-script text-[11px] text-chalk-dim">No overlays yet — add a hook title or a CTA.7 unmodified lines<div className="space-y-4"><p className="font-script text-[11px] text-chalk-dim">Voiceover is generated per clip in one consistent system voice (shown on the voicetrack). Add a music bed to sit underneath it.</p><div className="flex flex-wrap items-center gap-4"><label className="flex items-center gap-2">21 unmodified linesmax={1}step={0.05}value={musicVolume}onChange={(e) => setMusicVolume(Number(e.target.value))}disabled={!editable}className="w-28"/>3 unmodified lines</label><buttontype="button"onClick={() => setMusic(null)}className="text-tally hover:text-tally/70">✕7 unmodified lines</p><div className="mt-1.5 space-y-1">{tracks.map((t, i) => (<p key={t.key} className="font-script text-[11px] text-chalk-dim"><span className="timecode mr-2 text-chalk">{i + 1} · {(t.out - t.in).toFixed(1)}s</span>{t.spoken || <span className="opacity-60">(silent b-roll)</span>}</p>))}</div></div>14 unmodified lines</p><div className="flex items-center gap-3"><video controls src={resultUrl} className="max-h-72 bg-black" /><a href={resultUrl} download className="font-script text-xs text-print hover:underline">Download</a></div>12345678910111213141516178 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676847 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501512 unmodified lines1541551561571581591601611621631641 unmodified line1661671681691701711725 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252264 unmodified lines2312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544557 unmodified lines4634644654664674684694704714724734744751 unmodified line47747847948048148248348448548614 unmodified lines5015025035045055065075085095105118 unmodified lines5205215225235245255265275285295305315325332 unmodified lines5365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685694 unmodified lines5745755765775785795805815825832 unmodified lines5865875885895905915925935945955965975985996006016026036046056066076083 unmodified lines6126136146156166176184 unmodified lines62362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366418 unmodified lines68368468568668768868969069169212 unmodified lines7057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809818 unmodified lines99099199299399499599699799899910001001100210031004100510061007100810091010101110125 unmodified lines101810191020102110221023102410251026102710281029103010315 unmodified lines1037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113430 unmodified lines11651166116711681169117011711172117312 unmodified lines118611871188118911901191119211931194119511961197119811991200120153 unmodified lines1255125612571258125912601261126212631264126512661267126812691270127112721273127415 unmodified lines129012911292129312941295129612971 unmodified line1299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714187 unmodified lines1426142714281429143014311432143321 unmodified lines145514561457145814591460146114621463146414653 unmodified lines14691470147114721473147414751476147714781479148014817 unmodified lines1489149014911492149314941495149614971498149915001501150215031504150514 unmodified lines15201521152215231524152515261527152815291530import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { api, ApiError } from "../api/client";import type { RenderClip, TextOverlay } from "../api/types";import { Loader } from "./Loader";import {buildCues,clipStart,locate,overlayStyle,totalLength,WORDS_PER_CUE,type Box,type Cue,} from "./editor/preview";type Track = {key: string;8 unmodified linesout: number;};/** A title/CTA. Anchored to a CLIP rather than to an absolute timeline second:* trimming or reordering moves the timeline underneath, and an absolute time* would silently drift off the moment it was placed on. */type Overlay = {key: string;text: string;position: "top" | "center" | "bottom";color: string;size: number;clipKey: string;offset: number; // seconds into that clip's trimmed spandur: number;};type Stage = "loading" | "editing" | "exporting" | "done" | "empty";type Tab = "clips" | "captions" | "text" | "audio";type CaptionSource = "script" | "ai" | "none";const PX_PER_SEC = 46;/** Everything the editor should survive a close/reopen with. The clip bytes live* in R2 and the manifest is reloaded, so only the user's decisions are stored. */type Saved = {order: number[];trims: Record<number, { in: number; out: number }>;captionSource: CaptionSource;captionColor: string;captionSize: number;captionPosition: string;captionFont: string;captionBg: string;captionBgOpacity: number;cueEdits: Record<string, string>;overlays: Overlay[];music: { path: string; name: string } | null;musicVolume: number;};function TabBtn({active,47 unmodified linesconst [busyClip, setBusyClip] = useState(false);const [regenPrompt, setRegenPrompt] = useState("");const [regenSpoken, setRegenSpoken] = useState("");const [cueEdits, setCueEdits] = useState<Record<string, string>>({});const [music, setMusic] = useState<{ path: string; name: string } | null>(null);const [musicUrl, setMusicUrl] = useState<string | null>(null); // local, for preview onlyconst [musicVolume, setMusicVolume] = useState(0.25);const [overlays, setOverlays] = useState<Overlay[]>([]);const [resultUrl, setResultUrl] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);const [restored, setRestored] = useState(false);const dragKey = useRef<string | null>(null);const mounted = useRef(true);const undoDelete = useRef<{ track: Track; at: number } | null>(null);// --- playback engine --------------------------------------------------- //// The playhead (global timeline seconds) is the single source of truth: which// clip is on screen, which captions are up and where the music is all derive// from it. One <video> per clip stays mounted and preloaded, and only the// active one is shown — swapping a single element's `src` re-fetches from the// CDN and stalls at every cut.const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);const musicRef = useRef<HTMLAudioElement | null>(null);const stageRef = useRef<HTMLDivElement | null>(null);const scrubRef = useRef<HTMLDivElement | null>(null);const scrubbing = useRef(false);const playheadRef = useRef(0);const [playhead, setPlayhead] = useState(0);const [playing, setPlaying] = useState(false);const [stageBox, setStageBox] = useState({ w: 0, h: 0 });const [videoBox, setVideoBox] = useState({ w: 1080, h: 1920 });useEffect(() => {mounted.current = true;2 unmodified lines};}, []);const setHead = useCallback((t: number) => {playheadRef.current = t;setPlayhead(t);}, []);const load = useCallback(async () => {try {const clips: RenderClip[] = await api.getRenderClips(renderId);1 unmodified linesetStage("empty");return;}const fresh: Track[] = clips.map((c, i) => ({key: `${c.index}-${i}`,index: c.index,url: c.url,5 unmodified linesin: 0,out: c.duration,}));// Re-apply anything from a previous session. Clips may have been// regenerated since, so only trims whose index still exists are restored.let next = fresh;const raw = localStorage.getItem(`cb-editor-${renderId}`);if (raw) {try {const s: Saved = JSON.parse(raw);const byIndex = new Map(fresh.map((t) => [t.index, t]));const ordered = s.order.map((i) => byIndex.get(i)).filter((t): t is Track => Boolean(t));const missing = fresh.filter((t) => !s.order.includes(t.index));next = [...ordered, ...missing].map((t) => {const trim = s.trims[t.index];if (!trim) return t;return {...t,in: Math.min(Math.max(0, trim.in), t.duration),out: Math.min(Math.max(0.2, trim.out), t.duration),};});setCaptionSource(s.captionSource ?? "script");setCaptionColor(s.captionColor ?? "#FFFFFF");setCaptionSize(s.captionSize ?? 52);setCaptionPosition(s.captionPosition ?? "bottom");setCaptionFont(s.captionFont ?? "");setCaptionBg(s.captionBg ?? "#000000");setCaptionBgOpacity(s.captionBgOpacity ?? 0.45);setCueEdits(s.cueEdits ?? {});setOverlays(s.overlays ?? []);setMusic(s.music ?? null);setMusicVolume(s.musicVolume ?? 0.25);setRestored(true);} catch {/* corrupt entry — start clean */}}videoRefs.current = new Array(next.length).fill(null);setTracks(next);setSelected(next[0]?.key ?? null);setHead(0);try {setFonts(await api.listFonts());} catch {4 unmodified linessetError(err instanceof ApiError ? err.message : "Failed to load clips");setStage("editing");}}, [renderId, setHead]);useEffect(() => {load();}, [load]);const editable = stage === "editing";const total = totalLength(tracks);const cues: Cue[] = useMemo(() =>buildCues(tracks.map((t) => ({ key: t.key, spoken: t.spoken, duration: t.out - t.in })),WORDS_PER_CUE,),[tracks],);// Keyed by cue.key, not array position: reordering or trimming a clip must not// move a hand-edited line onto different words.const finalCues = useMemo(() => cues.map((c) => ({ ...c, text: cueEdits[c.key] ?? c.text })),[cues, cueEdits],);const sel = tracks.find((t) => t.key === selected) ?? null;const playIdx = locate(tracks, playhead).idx;const width = Math.max(total * PX_PER_SEC, 240);const ticks = Array.from({ length: Math.ceil(total) + 1 }, (_, i) => i);/** A text overlay's absolute window, or null if its anchor clip is gone. */const overlayWindow = useCallback((o: Overlay): { start: number; end: number } | null => {const idx = tracks.findIndex((t) => t.key === o.clipKey);if (idx < 0) return null;const start = clipStart(tracks, idx) + o.offset;return { start, end: start + o.dur };},[tracks],);// --- persistence ------------------------------------------------------- //useEffect(() => {if (stage === "loading" || tracks.length === 0) return;const payload: Saved = {order: tracks.map((t) => t.index),trims: Object.fromEntries(tracks.map((t) => [t.index, { in: t.in, out: t.out }])),captionSource,captionColor,captionSize,captionPosition,captionFont,captionBg,captionBgOpacity,cueEdits,overlays,music,musicVolume,};try {localStorage.setItem(`cb-editor-${renderId}`, JSON.stringify(payload));} catch {/* quota — losing autosave is not worth breaking the editor over */}}, [stage, tracks, captionSource, captionColor, captionSize, captionPosition, captionFont,captionBg, captionBgOpacity, cueEdits, overlays, music, musicVolume, renderId,]);function resetEdits() {localStorage.removeItem(`cb-editor-${renderId}`);setOverlays([]);setCueEdits({});setMusic(null);setRestored(false);setStage("loading");void load();}// --- transport --------------------------------------------------------- //const syncMusic = useCallback((t: number, play: boolean) => {const a = musicRef.current;if (!a) return;a.volume = musicVolume;if (Number.isFinite(a.duration) && a.duration > 0) a.currentTime = t % a.duration;if (play) void a.play().catch(() => {});else a.pause();},[musicVolume],);const pauseAll = useCallback(() => {videoRefs.current.forEach((v) => v?.pause());musicRef.current?.pause();setPlaying(false);}, []);/** Show `t` without starting playback. */const seekTo = useCallback((t: number) => {const clamped = Math.max(0, Math.min(total, t));const { idx, local } = locate(tracks, clamped);setHead(clamped);if (idx < 0) return;const v = videoRefs.current[idx];if (v) v.currentTime = local;syncMusic(clamped, false);},[tracks, total, setHead, syncMusic],);/** Start (or resume) playback at `t`, gaplessly — the target clip is already* loaded, so this is a visibility switch plus a play() rather than a fetch. */const playFrom = useCallback((t: number) => {const clamped = Math.max(0, Math.min(total, t));const { idx, local } = locate(tracks, clamped);if (idx < 0) return;setHead(clamped);videoRefs.current.forEach((v, i) => {if (v && i !== idx) v.pause();});const v = videoRefs.current[idx];if (!v) return;v.currentTime = local;void v.play().catch(() => {});syncMusic(clamped, true);setPlaying(true);},[tracks, total, setHead, syncMusic],);function togglePlay() {if (playing) pauseAll();else playFrom(playheadRef.current >= total - 0.05 ? 0 : playheadRef.current);}// Drive the playhead off the active clip's real currentTime. rAF rather than// onTimeUpdate (which fires ~4x/sec) so captions and the playhead track the// video smoothly instead of stepping.useEffect(() => {if (!playing || tracks.length === 0) return;let raf = 0;const tick = () => {const { idx } = locate(tracks, playheadRef.current);const clip = tracks[idx];const v = videoRefs.current[idx];if (clip && v) {if (v.currentTime >= clip.out - 0.02) {if (idx < tracks.length - 1) {playFrom(clipStart(tracks, idx + 1));} else {pauseAll();setHead(total);return;}} else if (v.currentTime < clip.in - 0.05) {v.currentTime = clip.in;} else {// ~30fps is smooth to the eye; committing every frame would re-render// the whole timeline 60x/sec for no visible gain.const next = clipStart(tracks, idx) + (v.currentTime - clip.in);if (Math.abs(next - playheadRef.current) > 0.03) setHead(next);}}raf = requestAnimationFrame(tick);};raf = requestAnimationFrame(tick);return () => cancelAnimationFrame(raf);}, [playing, tracks, total, playFrom, pauseAll, setHead]);// Space toggles playback unless the user is typing.useEffect(() => {function onKey(e: KeyboardEvent) {const el = e.target as HTMLElement | null;if (el && /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) return;if (e.code !== "Space") return;e.preventDefault();togglePlay();}window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);// eslint-disable-next-line react-hooks/exhaustive-deps}, [playing, total, tracks]);// Keep the preview's on-screen size known so export pixels can be scaled to it.useEffect(() => {const el = stageRef.current;if (!el || typeof ResizeObserver === "undefined") return;const ro = new ResizeObserver(() => {setStageBox({ w: el.clientWidth, h: el.clientHeight });});ro.observe(el);setStageBox({ w: el.clientWidth, h: el.clientHeight });return () => ro.disconnect();}, [stage]);// --- edits ------------------------------------------------------------- //function patch(key: string, next: Partial<Track>) {setTracks((ts) => ts.map((t) => (t.key === key ? { ...t, ...next } : t)));}function remove(key: string) {setTracks((ts) => {const at = ts.findIndex((t) => t.key === key);if (at >= 0) undoDelete.current = { track: ts[at], at };return ts.filter((t) => t.key !== key);});setSelected((s) => (s === key ? null : s));pauseAll();}function restoreDeleted() {const saved = undoDelete.current;if (!saved) return;setTracks((ts) => {const copy = [...ts];copy.splice(Math.min(saved.at, copy.length), 0, saved.track);return copy;});setSelected(saved.track.key);undoDelete.current = null;}function reorder(fromKey: string, toKey: string) {setTracks((ts) => {7 unmodified lines});}function scrubAt(clientX: number) {const el = scrubRef.current;if (!el) return;const rect = el.getBoundingClientRect();seekTo((clientX - rect.left) / PX_PER_SEC);}async function onMusicFile(e: React.ChangeEvent<HTMLInputElement>) {const file = e.target.files?.[0];e.target.value = "";1 unmodified linetry {const res = await api.uploadMedia(file);setMusic({ path: res.path, name: file.name });setMusicUrl((prev) => {if (prev) URL.revokeObjectURL(prev);return URL.createObjectURL(file); // local copy so the mix previews});} catch (err) {setError(err instanceof ApiError ? err.message : "Failed to upload music");}14 unmodified lines}}async function regenerateSelected(clip: Track) {setBusyClip(true);setError(null);try {const { task_id } = await api.regenerateClip(renderId, clip.index, {prompt: regenPrompt.trim() || undefined,spoken: regenSpoken.trim() ? regenSpoken : undefined,use_reference: true, // seed b-roll with the clip being replaced8 unmodified lines}}async function uploadSelected(clip: Track, e: React.ChangeEvent<HTMLInputElement>) {const file = e.target.files?.[0];e.target.value = "";if (!file) return;setBusyClip(true);setError(null);try {await api.uploadClip(renderId, clip.index, file);await load();} catch (err) {setError(err instanceof ApiError ? err.message : "Failed to upload clip");2 unmodified lines}}/** New overlays land on the clip under the playhead, at the playhead. */function addOverlay() {const idx = Math.max(0, playIdx);const anchor = tracks[idx];if (!anchor) return;setOverlays((o) => [...o,{key: `ov-${o.length}-${Math.random().toString(36).slice(2, 7)}`,text: "",position: "bottom",color: "#39E508",size: 48,clipKey: anchor.key,offset: Math.max(0, playhead - clipStart(tracks, idx)),dur: Math.min(2.5, anchor.out - anchor.in),},]);setTab("text");}function patchOverlay(key: string, next: Partial<Overlay>) {setOverlays((os) => os.map((x) => (x.key === key ? { ...x, ...next } : x)));}async function handleExport() {if (tracks.length === 0) return;pauseAll();setStage("exporting");setError(null);setResultUrl(null);4 unmodified lines{captions: captionSource !== "none",captionSource,captionCues:captionSource === "script"? finalCues.map((c) => ({ text: c.text, start: c.start, end: c.end })): [],captionColor,captionSize,captionPosition,2 unmodified linescaptionBgOpacity: captionBgOpacity,music: music?.path ?? null,musicVolume,// Anchored windows resolved to absolute seconds for ffmpeg. Overlays// whose clip was deleted are dropped rather than exported at 0s.overlays: overlays.filter((o) => o.text.trim()).map((o): TextOverlay | null => {const w = overlayWindow(o);if (!w) return null;return {text: o.text,position: o.position,start: Math.round(w.start * 100) / 100,end: Math.round(w.end * 100) / 100,color: o.color,size: o.size,};}).filter((o): o is TextOverlay => o !== null),},);while (mounted.current) {3 unmodified linesif (s.status === "ready") {setResultUrl(s.video_url ?? null);setStage("done");localStorage.removeItem(`cb-editor-${renderId}`);onExported();return;}4 unmodified lines}}} catch (err) {setError(err instanceof ApiError ? err.message : "Export failed");setStage("editing");}}// --- what's burned in at the playhead, in preview pixels ---------------- //const displayW = Math.min(stageBox.w, stageBox.h * (videoBox.w / videoBox.h)) || stageBox.w;const scale = videoBox.w ? displayW / videoBox.w : 1;const liveBoxes: Box[] = [];if (captionSource === "script") {for (const c of finalCues) {if (playhead >= c.start && playhead <= c.end && c.text.trim()) {liveBoxes.push({text: c.text,position: captionPosition,color: captionColor,size: captionSize,font: captionFont || null,bgColor: captionBg,bgOpacity: captionBgOpacity,});}}}for (const o of overlays) {const w = overlayWindow(o);if (!w || !o.text.trim()) continue;if (playhead >= w.start && playhead <= w.end) {liveBoxes.push({text: o.text,position: o.position,color: o.color,size: o.size,bgColor: "#000000",bgOpacity: 0.45,});}}18 unmodified lines</button><buttontype="button"onClick={() => {pauseAll();onClose();}}className="border border-white/15 px-3 py-2 font-display text-xs tracking-wider text-chalk-dim uppercase hover:border-white/30 hover:text-chalk">← Renders12 unmodified lines{error && <p className="mb-3 text-sm text-tally">{error}</p>}{restored && stage !== "loading" && (<p className="mb-3 flex flex-wrap items-center gap-2 font-script text-[11px] text-viewfinder">Your unsaved edits from last time were restored.<buttontype="button"onClick={resetEdits}className="border border-white/15 px-2 py-0.5 font-display text-[10px] tracking-wider text-chalk-dim uppercase hover:border-tally/50 hover:text-tally">start fresh</button></p>)}{tracks.length > 0 && stage !== "loading" && stage !== "empty" && (<>{/* ---------- PREVIEW + TIMELINE ---------- */}<div className="flex flex-wrap gap-5">{/* live preview: every clip stays mounted, only the active one shows */}<div className="shrink-0"><divref={stageRef}className="relative aspect-[9/16] max-h-[58vh] w-[min(17rem,60vw)] overflow-hidden bg-black">{tracks.map((t, i) => (<videokey={t.key}ref={(el) => {videoRefs.current[i] = el;}}src={t.url}preload="auto"playsInlineonLoadedMetadata={(e) => {const v = e.currentTarget;if (i === 0 && v.videoWidth) {setVideoBox({ w: v.videoWidth, h: v.videoHeight });}if (i === playIdx) v.currentTime = locate(tracks, playhead).local;}}className={`absolute inset-0 h-full w-full object-contain ${i === playIdx ? "" : "invisible"}`}/>))}{/* burned-in text, drawn with the export's own geometry */}{liveBoxes.map((b, i) => (<div key={i} style={overlayStyle(b, displayW, scale)}>{b.text}</div>))}{!playing && (<buttontype="button"onClick={togglePlay}aria-label="Play"className="absolute inset-0 flex items-center justify-center bg-ink/20 text-3xl text-chalk/80 hover:bg-ink/10">▶</button>)}</div><div className="mt-1.5 flex items-center gap-2"><buttontype="button"onClick={togglePlay}className="border border-print/50 px-2.5 py-1 font-display text-[10px] tracking-wider text-print uppercase hover:bg-print hover:text-ink">{playing ? "❚❚ pause" : "▶ play"}</button><buttontype="button"onClick={() => seekTo(0)}className="border border-white/15 px-2 py-1 font-display text-[10px] tracking-wider text-chalk-dim uppercase hover:border-white/30 hover:text-chalk">⏮ start</button><span className="timecode text-[10px] text-chalk-dim">{playhead.toFixed(1)}s / {total.toFixed(1)}s</span></div><p className="mt-1 font-script text-[10px] text-chalk-dim">Captions, titles and music preview live. Grain is added on export.</p></div>{/* timeline */}<div className="min-w-[18rem] flex-1"><div className="overflow-x-auto border border-white/10 bg-ink"><divref={scrubRef}style={{ width }}className="relative min-w-full"onPointerDown={(e) => {scrubbing.current = true;e.currentTarget.setPointerCapture(e.pointerId);scrubAt(e.clientX);}}onPointerMove={(e) => {if (scrubbing.current) scrubAt(e.clientX);}}onPointerUp={(e) => {scrubbing.current = false;e.currentTarget.releasePointerCapture(e.pointerId);}}>{/* playhead */}<divclassName="pointer-events-none absolute top-0 bottom-0 z-10 w-px bg-tally"style={{ left: playhead * PX_PER_SEC }}><span className="absolute -top-0.5 -left-[3px] h-1.5 w-1.5 rotate-45 bg-tally" /></div>{/* ruler */}<div className="relative h-5 border-b border-white/10">{ticks.map((s) => (<spankey={s}className="absolute top-0 h-full border-l border-white/10 pl-1 font-script text-[9px] text-chalk-dim"style={{ left: s * PX_PER_SEC }}>{s}s</span>))}</div>{/* VIDEO track */}<div className="flex items-stretch gap-px border-b border-white/10">{tracks.map((t, i) => (<buttontype="button"key={t.key}draggable={editable}onDragStart={() => (dragKey.current = t.key)}onDragOver={(e) => e.preventDefault()}onDrop={() => {if (dragKey.current) reorder(dragKey.current, t.key);dragKey.current = null;}}onClick={() => setSelected(t.key)}style={{ width: Math.max((t.out - t.in) * PX_PER_SEC, 34) }}className={`group relative h-14 shrink-0 overflow-hidden border-l-2 px-1.5 py-1 text-left transition ${t.isBroll ? "border-l-gaffer bg-gaffer/10" : "border-l-print bg-print/10"} ${selected === t.key ? "ring-1 ring-chalk/60" : "hover:bg-white/5"}`}title={t.spoken || `Clip ${i + 1}`}><span className="block font-display text-[10px] tracking-wider text-chalk">{i + 1} {t.isBroll ? "B" : "P"}</span><span className="timecode block text-[9px] text-chalk-dim">{(t.out - t.in).toFixed(1)}s</span>{editable && (<span className="absolute right-0.5 bottom-0.5 cursor-grab text-[9px] text-chalk-dim opacity-0 group-hover:opacity-100">⠿</span>)}</button>))}</div>{/* VOICE track */}<div className="flex items-stretch gap-px border-b border-white/10">{tracks.map((t) => (<divkey={t.key}style={{ width: Math.max((t.out - t.in) * PX_PER_SEC, 34) }}className="h-9 shrink-0 overflow-hidden bg-viewfinder/10 px-1.5 py-1"title={t.spoken}><span className="block truncate font-script text-[9px] text-viewfinder">♪ {t.spoken || "—"}</span></div>))}</div>{/* CAPTIONS track */}<div className="relative h-7 border-b border-white/10">{captionSource === "none" ? (<span className="absolute top-1 left-1.5 font-script text-[9px] text-chalk-dim">captions off</span>) : captionSource === "ai" ? (<span className="absolute top-1 left-1.5 font-script text-[9px] text-clay">AI transcription (timing decided at export — no preview)</span>) : (finalCues.map((c) => (<spankey={c.key}className="absolute top-1 h-5 overflow-hidden border-l border-clay/60 bg-clay/20 px-1 font-script text-[9px] text-chalk"style={{left: c.start * PX_PER_SEC,width: Math.max((c.end - c.start) * PX_PER_SEC - 2, 12),}}title={`${c.start}s–${c.end}s · ${c.text}`}>{c.text}</span>)))}</div>{/* TEXT track */}<div className="relative h-7 border-b border-white/10">{overlays.length === 0 ? (<span className="absolute top-1 left-1.5 font-script text-[9px] text-chalk-dim">no titles — add one in the Text tab</span>) : (overlays.map((o) => {const w = overlayWindow(o);if (!w) return null;return (<spankey={o.key}className="absolute top-1 h-5 overflow-hidden border-l border-print/60 bg-print/20 px-1 font-script text-[9px] text-chalk"style={{left: w.start * PX_PER_SEC,width: Math.max(o.dur * PX_PER_SEC - 2, 12),}}title={`${w.start.toFixed(1)}s–${w.end.toFixed(1)}s · ${o.text}`}>{o.text || "(empty)"}</span>);}))}</div>{/* MUSIC track */}<div className="relative h-7">{music ? (<spanclassName="absolute top-1 h-5 overflow-hidden bg-gaffer/20 px-1.5 font-script text-[9px] text-gaffer"style={{ width: Math.max(total * PX_PER_SEC - 2, 40) }}>♫ {music.name} · {Math.round(musicVolume * 100)}%{!musicUrl && " (re-pick to preview)"}</span>) : (<span className="absolute top-1 left-1.5 font-script text-[9px] text-chalk-dim">no music — add one in the Audio tab</span>)}</div></div></div><p className="mt-1.5 font-script text-[10px] text-chalk-dim">Click or drag the timeline to scrub · space to play · drag a clip to reorder, clickto edit it.</p></div></div>{musicUrl && <audio ref={musicRef} src={musicUrl} loop preload="auto" className="hidden" />}{/* ---------- TABS ---------- */}<div className="mt-5 flex flex-wrap gap-2"><TabBtn active={tab === "clips"} onClick={() => setTab("clips")}>Clip</TabBtn><TabBtnactive={tab === "captions"}onClick={() => setTab("captions")}count={finalCues.length}>Captions</TabBtn><TabBtn active={tab === "text"} onClick={() => setTab("text")} count={overlays.length}>8 unmodified lines{/* --- CLIP --- */}{tab === "clips" &&(sel ? (<div className="space-y-3"><p className="font-script text-[11px] text-chalk-dim">Clip {tracks.findIndex((t) => t.key === sel.key) + 1} ·{" "}<span className={sel.isBroll ? "text-gaffer" : "text-print"}>{sel.isBroll ? "B-ROLL" : "PRESENTER"}</span>{" "}· source {sel.duration.toFixed(1)}s · keeping{" "}<span className="text-chalk">{(sel.out - sel.in).toFixed(1)}s</span></p>{sel.spoken && (<p className="border-l-2 border-viewfinder/40 pl-2 font-script text-[11px] text-chalk">“{sel.spoken}”</p>)}<div className="flex flex-wrap gap-5"><label className="block min-w-[13rem] flex-1 font-script text-[11px] text-chalk-dim">trim in — {sel.in.toFixed(1)}s<inputtype="range"5 unmodified linesonChange={(e) => {const next = Math.min(Number(e.target.value), sel.out - 0.2);patch(sel.key, { in: next });pauseAll();const idx = tracks.findIndex((t) => t.key === sel.key);seekTo(clipStart(tracks, idx)); // first frame you're keeping}}className="mt-1 w-full"/></label><label className="block min-w-[13rem] flex-1 font-script text-[11px] text-chalk-dim">trim out — {sel.out.toFixed(1)}s<inputtype="range"5 unmodified linesonChange={(e) => {const next = Math.max(Number(e.target.value), sel.in + 0.2);patch(sel.key, { out: next });pauseAll();const idx = tracks.findIndex((t) => t.key === sel.key);// last frame you're keepingseekTo(clipStart(tracks, idx) + (next - sel.in) - 0.05);}}className="mt-1 w-full"/></label></div><div className="flex flex-wrap items-center gap-2"><buttontype="button"onClick={() => remove(sel.key)}disabled={!editable || tracks.length <= 1}className="border border-tally/50 px-2.5 py-1 font-display text-[11px] tracking-wider text-tally uppercase hover:bg-tally hover:text-ink disabled:opacity-40">✕ Delete clip</button>{undoDelete.current && (<buttontype="button"onClick={restoreDeleted}className="border border-white/15 px-2.5 py-1 font-display text-[11px] tracking-wider text-chalk-dim uppercase hover:border-print/50 hover:text-chalk">↺ Restore last deleted</button>)}</div>{/* --- regenerate / replace this clip --- */}<div className="space-y-2 border-t border-white/10 pt-3"><p className="font-display text-[11px] tracking-wider text-chalk-dim uppercase">Regenerate or replace</p><textareavalue={regenPrompt}placeholder={sel.isBroll? "B-roll prompt — edit to change the shot…": "Scene prompt — edit to change the shot…"}onChange={(e) => setRegenPrompt(e.target.value)}disabled={!editable || busyClip}rows={2}className="w-full resize-y border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"/><inputvalue={regenSpoken}placeholder={sel.isBroll? "Spoken line for this cutaway (optional)…": "Spoken line — edit to re-record the voiceover…"}onChange={(e) => setRegenSpoken(e.target.value)}disabled={!editable || busyClip}className="w-full border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"/><div className="flex flex-wrap items-center gap-2"><buttontype="button"onClick={() => regenerateSelected(sel)}disabled={!editable || busyClip}className="border border-gaffer/60 px-2.5 py-1 font-display text-[11px] tracking-wider text-gaffer uppercase hover:bg-gaffer hover:text-ink disabled:opacity-40">⟳ Regenerate</button><label className="flex items-center gap-2"><spanclassName={`cursor-pointer border border-white/15 px-2.5 py-1 font-display text-[11px] tracking-wider uppercase ${editable && !busyClip? "text-chalk-dim hover:border-print/50 hover:text-chalk": "text-chalk-dim opacity-40"}`}>↑ Upload own clip</span><inputtype="file"accept="video/*"onChange={(e) => uploadSelected(sel, e)}disabled={!editable || busyClip}className="hidden"/></label>{busyClip && <Loader label="Working" />}</div><p className="font-script text-[10px] text-chalk-dim">{sel.isBroll? "The clip being replaced is passed to the model as a reference, so the new take continues from it.": "Changing the spoken line regenerates the voiceover and re-animates the presenter, keeping the same face."}</p></div></div>) : (30 unmodified lines</div><p className="font-script text-[11px] text-chalk-dim">{captionSource === "script"? "Cues come from the script we already generated — instant, free, always spelled correctly, and previewed live above. Edit any line below.": captionSource === "ai"? "Transcribes the audio with a Whisper model on Replicate (slower, costs a call, can mis-spell). Timing is decided at export, so this can't be previewed.": "No captions will be burned in."}</p>12 unmodified lines<label className="flex items-center gap-2 font-script text-[11px] text-chalk-dim">size<inputtype="range"min={20}max={110}step={2}value={captionSize}onChange={(e) => setCaptionSize(Number(e.target.value))}disabled={!editable}className="w-28"/><span className="timecode text-chalk">{captionSize}</span></label><label className="flex items-center gap-2 font-script text-[11px] text-chalk-dim">position53 unmodified lines{captionSource === "script" && (<div className="max-h-72 space-y-1.5 overflow-y-auto border-t border-white/10 pt-3">{finalCues.map((c) => (<div key={c.key} className="flex items-center gap-2"><buttontype="button"onClick={() => seekTo((c.start + c.end) / 2)}title="Jump the playhead here"className="timecode w-24 shrink-0 text-left font-script text-[10px] text-chalk-dim hover:text-print">{c.start.toFixed(1)}–{c.end.toFixed(1)}s</button><inputvalue={c.text}onChange={(e) =>setCueEdits((m) => ({ ...m, [c.key]: e.target.value }))}disabled={!editable}className="flex-1 border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"15 unmodified lines<div className="space-y-2"><div className="flex items-center justify-between"><p className="font-script text-[11px] text-chalk-dim">Titles / CTAs burned over the video. Each is pinned to a clip, so trims andreorders keep it on its moment.</p><buttontype="button"1 unmodified linedisabled={!editable}className="border border-print/50 px-2.5 py-1 font-display text-[11px] tracking-wider text-print uppercase hover:bg-print hover:text-ink disabled:opacity-40">+ Add at playhead</button></div>{overlays.map((o) => {const w = overlayWindow(o);const anchorNum = tracks.findIndex((t) => t.key === o.clipKey) + 1;return (<divkey={o.key}className="flex flex-wrap items-center gap-2 border border-white/10 px-2.5 py-2"><inputvalue={o.text}placeholder="Overlay text…"onChange={(e) => patchOverlay(o.key, { text: e.target.value })}disabled={!editable}className="min-w-[10rem] flex-1 border border-white/15 bg-slate-2 px-2 py-1 font-script text-xs text-chalk"/><selectvalue={o.position}onChange={(e) =>patchOverlay(o.key, { position: e.target.value as Overlay["position"] })}disabled={!editable}className="border border-white/15 bg-slate-2 px-1.5 py-1 font-script text-[11px] text-chalk"><option value="top">top</option><option value="center">center</option><option value="bottom">bottom</option></select><selectvalue={o.clipKey}onChange={(e) => patchOverlay(o.key, { clipKey: e.target.value })}disabled={!editable}title="Clip this title is pinned to"className="border border-white/15 bg-slate-2 px-1.5 py-1 font-script text-[11px] text-chalk">{tracks.map((t, i) => (<option key={t.key} value={t.key}>clip {i + 1}</option>))}</select><label className="flex items-center gap-1 font-script text-[10px] text-chalk-dim">at<inputtype="number"min={0}step={0.5}value={o.offset}onChange={(e) =>patchOverlay(o.key, { offset: Math.max(0, Number(e.target.value)) })}disabled={!editable}className="w-14 border border-white/15 bg-slate-2 px-1 py-1 text-chalk"/>for<inputtype="number"min={0.5}step={0.5}value={o.dur}onChange={(e) =>patchOverlay(o.key, { dur: Math.max(0.5, Number(e.target.value)) })}disabled={!editable}className="w-14 border border-white/15 bg-slate-2 px-1 py-1 text-chalk"/>s</label><inputtype="color"value={o.color}onChange={(e) => patchOverlay(o.key, { color: e.target.value })}disabled={!editable}className="h-7 w-8 cursor-pointer border border-white/15 bg-slate-2"/><inputtype="number"min={16}max={120}step={2}value={o.size}onChange={(e) => patchOverlay(o.key, { size: Number(e.target.value) })}disabled={!editable}className="w-14 border border-white/15 bg-slate-2 px-1 py-1 font-script text-[11px] text-chalk"/>{w && (<buttontype="button"onClick={() => seekTo(w.start + 0.05)}className="timecode font-script text-[10px] text-chalk-dim hover:text-print"title="Jump the playhead here">{w.start.toFixed(1)}s</button>)}{!w && (<span className="font-script text-[10px] text-tally">clip deleted</span>)}<span className="font-script text-[10px] text-chalk-dim">clip {anchorNum > 0 ? anchorNum : "—"}</span><buttontype="button"onClick={() => setOverlays((os) => os.filter((x) => x.key !== o.key))}disabled={!editable}className="text-tally hover:text-tally/70 disabled:opacity-40">✕</button></div>);})}{overlays.length === 0 && (<p className="font-script text-[11px] text-chalk-dim">No overlays yet — add a hook title or a CTA.7 unmodified lines<div className="space-y-4"><p className="font-script text-[11px] text-chalk-dim">Voiceover is generated per clip in one consistent system voice (shown on the voicetrack). Add a music bed to sit underneath it — it plays in the preview at thevolume you set.</p><div className="flex flex-wrap items-center gap-4"><label className="flex items-center gap-2">21 unmodified linesmax={1}step={0.05}value={musicVolume}onChange={(e) => {const v = Number(e.target.value);setMusicVolume(v);if (musicRef.current) musicRef.current.volume = v;}}disabled={!editable}className="w-28"/>3 unmodified lines</label><buttontype="button"onClick={() => {setMusic(null);setMusicUrl((prev) => {if (prev) URL.revokeObjectURL(prev);return null;});}}className="text-tally hover:text-tally/70">✕7 unmodified lines</p><div className="mt-1.5 space-y-1">{tracks.map((t, i) => (<buttonkey={t.key}type="button"onClick={() => seekTo(clipStart(tracks, i))}className="block w-full text-left font-script text-[11px] text-chalk-dim hover:text-chalk"><span className="timecode mr-2 text-chalk">{i + 1} · {(t.out - t.in).toFixed(1)}s</span>{t.spoken || <span className="opacity-60">(silent b-roll)</span>}</button>))}</div></div>14 unmodified lines</p><div className="flex items-center gap-3"><video controls src={resultUrl} className="max-h-72 bg-black" /><ahref={resultUrl}downloadclassName="font-script text-xs text-print hover:underline">Download</a></div>
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576/** Self-check for the preview maths. No test runner is configured, so run it with: * * npx esbuild --bundle --platform=node --format=cjs \ * --outfile=/tmp/pc.cjs src/components/editor/preview.check.ts && node /tmp/pc.cjs * * It guards the two things that silently corrupt an edit if they regress: cue * keys staying attached to their words across reorder/trim, and the overlay * geometry matching `_render_overlay_png` in app/services/video.py. */import { buildCues, locate, clipStart, totalLength, overlayStyle } from "./preview";
let fail = 0;const ok = (name: string, cond: boolean, extra = "") => { if (!cond) { fail++; console.log(` FAIL ${name} ${extra}`); } else console.log(` ok ${name}`);};
// --- locate / clipStart -------------------------------------------------- //const tracks = [ { in: 0.5, out: 3.5 }, // 3.0s -> timeline 0.0-3.0 { in: 0, out: 2.0 }, // 2.0s -> timeline 3.0-5.0 { in: 1.0, out: 5.0 }, // 4.0s -> timeline 5.0-9.0];ok("total", totalLength(tracks) === 9);ok("clipStart", clipStart(tracks, 2) === 5);ok("locate start of clip0", JSON.stringify(locate(tracks, 0)) === '{"idx":0,"local":0.5}');ok("locate mid clip1", JSON.stringify(locate(tracks, 4)) === '{"idx":1,"local":1}', JSON.stringify(locate(tracks, 4)));ok("locate boundary -> next clip", locate(tracks, 3).idx === 1);ok("locate into clip2 maps through trim-in", locate(tracks, 6).local === 2, String(locate(tracks, 6).local));ok("locate past end clamps", locate(tracks, 99).idx === 2);ok("locate empty", locate([], 3).idx === -1);
// --- cue keys survive reorder ------------------------------------------- //const a = { key: "10-0", spoken: "buy home insurance today right now", duration: 3 };const b = { key: "11-1", spoken: "save four hundred dollars a year", duration: 3 };const before = buildCues([a, b]);const after = buildCues([b, a]); // reorderedconst keysBefore = before.map(c => c.key).sort().join(",");const keysAfter = after.map(c => c.key).sort().join(",");ok("cue keys stable across reorder", keysBefore === keysAfter, `\n ${keysBefore}\n ${keysAfter}`);ok("cue text follows its key", (() => { const m = new Map(after.map(c => [c.key, c.text])); return before.every(c => m.get(c.key) === c.text);})());// trimming changes timing but not identityconst trimmed = buildCues([{ ...a, duration: 1.5 }, b]);ok("cue keys stable across trim", trimmed.map(c=>c.key).sort().join(",") === keysBefore);ok("cue timings shift on trim", trimmed[0].end < before[0].end + 0.001 && trimmed.length === before.length);ok("cues tile the timeline", Math.abs(before[before.length-1].end - 6) < 0.05, String(before[before.length-1].end));
// --- overlay geometry parity vs Pillow ---------------------------------- //// backend: size px on a video_w-wide frame; preview shows it at displayWconst videoW = 1080, displayW = 270; // scale 0.25const s = overlayStyle({ text: "x", position: "bottom", color: "#fff", size: 52, bgColor: "#000000", bgOpacity: 0.45 }, displayW, displayW / videoW);ok("fontSize scaled", s.fontSize === 13, String(s.fontSize)); // 52*0.25ok("padding = 0.45*size", s.padding === 13 * 0.45, String(s.padding));ok("radius = 0.28*size", s.borderRadius === 13 * 0.28, String(s.borderRadius));// content wraps at video_w*0.86 scaled == displayW*0.86, given border-boxok("wrap width matches Pillow", (s.maxWidth as number) - 2 * (s.padding as number) === displayW * 0.86, `${s.maxWidth} - 2*${s.padding}`);ok("line height 1.3", s.lineHeight === 1.3);ok("bottom = 10%", s.bottom === "10%");ok("top position = 8%", overlayStyle({ text:"x", position:"top", color:"#fff", size:40 }, displayW, 0.25).top === "8%");ok("bg rgba from hex+opacity", overlayStyle({ text:"x", position:"top", color:"#fff", size:40, bgColor:"#204080", bgOpacity:0.5 }, displayW, 1).background === "rgba(32,64,128,0.5)", String(overlayStyle({ text:"x", position:"top", color:"#fff", size:40, bgColor:"#204080", bgOpacity:0.5 }, displayW, 1).background));
console.log(fail ? `\n${fail} FAILED` : "\nall passed");// throw rather than process.exit so this file needs no node types in tsc -bif (fail) throw new Error(`${fail} preview check(s) failed`);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157/** Pure helpers shared by the editor's live preview. * * The export runs in ffmpeg/Pillow on the server, so anything drawn here has to * reproduce that geometry exactly or the preview lies. The numbers below mirror * `_render_overlay_png` and `_OVERLAY_Y` in app/services/video.py — keep them in * step if the backend ones change: * * text wraps at video_w * 0.86 * padding size * 0.45 * line height size * 1.30 * corner radius size * 0.28 * y: top H * 0.08 (box top edge) * center (H - h) / 2 * bottom H - h - H * 0.10 (i.e. 10% up from the bottom) */import type { CSSProperties } from "react";
export const WORDS_PER_CUE = 4;
export type Trim = { in: number; out: number };export type CueSource = { key: string; spoken: string; duration: number };
/** A caption cue. `key` is stable across reorder/trim/delete so a hand-edited * line stays attached to the words it belongs to — an array index does not. */export type Cue = { key: string; text: string; start: number; end: number };
/** Mirrors the backend's build_cues: chunk each clip's line into a few words and * split the clip's (trimmed) duration across chunks by character length. */export function buildCues(clips: CueSource[], wordsPerCue = WORDS_PER_CUE): Cue[] { const cues: Cue[] = []; let clock = 0; for (const clip of clips) { const text = (clip.spoken || "").trim(); if (clip.duration <= 0) continue; if (!text) { clock += clip.duration; continue; } const words = text.split(/\s+/); const chunks: string[] = []; for (let i = 0; i < words.length; i += wordsPerCue) { chunks.push(words.slice(i, i + wordsPerCue).join(" ")); } const totalChars = chunks.reduce((s, c) => s + c.length, 0) || 1; let t = clock; chunks.forEach((chunk, ordinal) => { const span = clip.duration * (chunk.length / totalChars); cues.push({ key: `${clip.key}#${ordinal}`, text: chunk, start: Math.round(t * 100) / 100, end: Math.round((t + span) * 100) / 100, }); t += span; }); clock += clip.duration; } return cues;}
/** Total length of the edit — every clip's trimmed span. */export function totalLength(tracks: Trim[]): number { return tracks.reduce((s, t) => s + (t.out - t.in), 0);}
/** Timeline offset at which clip `idx` starts. */export function clipStart(tracks: Trim[], idx: number): number { return totalLength(tracks.slice(0, Math.max(0, idx)));}
/** Global timeline seconds -> which clip is on screen and its own currentTime. * `idx` is -1 for an empty timeline. */export function locate(tracks: Trim[], t: number): { idx: number; local: number } { let acc = 0; for (let i = 0; i < tracks.length; i++) { const len = tracks[i].out - tracks[i].in; if (t < acc + len || i === tracks.length - 1) { return { idx: i, local: tracks[i].in + Math.min(Math.max(0, t - acc), len) }; } acc += len; } return { idx: -1, local: 0 };}
/** The backend picks fonts by family name from a fixed table; map those to the * nearest CSS family + weight so the preview letterforms match the export. */const FONT_CSS: Record<string, { fontFamily: string; fontWeight: number }> = { Impact: { fontFamily: "Impact, Haettenschweiler, sans-serif", fontWeight: 400 }, "Arial Black": { fontFamily: '"Arial Black", Gadget, sans-serif', fontWeight: 900 }, "Arial Bold": { fontFamily: "Arial, Helvetica, sans-serif", fontWeight: 700 }, Arial: { fontFamily: "Arial, Helvetica, sans-serif", fontWeight: 400 }, "Arial Narrow Bold": { fontFamily: '"Arial Narrow", Arial, sans-serif', fontWeight: 700 }, Helvetica: { fontFamily: "Helvetica, Arial, sans-serif", fontWeight: 400 }, "Verdana Bold": { fontFamily: "Verdana, Geneva, sans-serif", fontWeight: 700 }, "Georgia Bold": { fontFamily: "Georgia, serif", fontWeight: 700 }, "Courier New Bold": { fontFamily: '"Courier New", monospace', fontWeight: 700 }, Futura: { fontFamily: 'Futura, "Trebuchet MS", sans-serif', fontWeight: 400 },};
export function cssFont(name?: string | null) { return FONT_CSS[name || ""] ?? { fontFamily: "Arial, Helvetica, sans-serif", fontWeight: 700 };}
function rgba(hex: string, opacity: number): string { const h = (hex || "#000000").replace("#", ""); const n = parseInt(h.length === 3 ? h.replace(/./g, (c) => c + c) : h, 16); const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255]; return `rgba(${r},${g},${b},${Math.max(0, Math.min(1, opacity))})`;}
export type Box = { text: string; position: string; color: string; size: number; font?: string | null; bgColor?: string; bgOpacity?: number;};
/** * CSS for one burned-in text box, scaled from export pixels to the on-screen * preview. `scale` is previewWidth / video.videoWidth. * * maxWidth is the wrap width PLUS the padding because Tailwind's reset makes * every box border-box: content then wraps at exactly video_w * 0.86 * scale, * matching Pillow. */export function overlayStyle(box: Box, previewWidth: number, scale: number): CSSProperties { const size = Math.max(12, box.size || 48) * scale; const pad = size * 0.45; const { fontFamily, fontWeight } = cssFont(box.font); const vertical: CSSProperties = box.position === "top" ? { top: "8%" } : box.position === "center" ? { top: "50%", transform: "translate(-50%, -50%)" } : { bottom: "10%" }; return { position: "absolute", left: "50%", transform: box.position === "center" ? "translate(-50%, -50%)" : "translateX(-50%)", ...vertical, maxWidth: previewWidth * 0.86 + pad * 2, padding: pad, borderRadius: size * 0.28, background: rgba(box.bgColor ?? "#000000", box.bgOpacity ?? 0.45), color: box.color || "#FFFFFF", fontFamily, fontWeight, fontSize: size, lineHeight: 1.3, textAlign: "center", whiteSpace: "pre-wrap", pointerEvents: "none", };}