"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { paperButtonVariants } from "@/components/ui/reader-pane"; import { useHydrated } from "@/components/ui/use-hydrated"; import { cn } from "@/lib/utils"; // --------------------------------------------------------------------------- // EXPORT ONE CLIP (operator, 2026-10-31: "an export button that maybe even // opens up the folder to let me grab a clean cropped export of any one clip"): // the clip as the cut plays it -- its edges, its gaps out as jump cuts, its // mute -- or its whole fetched window (raw), no deck chrome, written to the // project's exports/ (lib/report/clipExport.mjs, POST /api/report/clip-export). // // Then Download (everywhere -- a phone cannot open a folder: the file served // as an attachment by /api/report/exports) and Open folder (on the machine // umtool runs on: the file manager shows exports/ with the file selected; // the server says when it cannot, and why). The bench's reader footer and // Play the cut both use it; Play exports the clip at the playhead, or the one // a note points at, through one `useClipExport`. // // EXPORT ▾ (UI notes 2026-10-30, item 12): as cut (no chrome), with N s of // context, raw / full exchange (a span, fetched through the editor first when // it is not on disk). Every export is a umtool job (POST answers 202 and the // job; this polls it), in the machine's heavy slot. No "send to phone": no // share path exists in umtool -- Download is the phone's way. // --------------------------------------------------------------------------- export type ClipExportKind = "cut" | "context" | "raw"; export type ClipExportOpts = { context?: number; span?: { from: number; to: number } | null; fetch?: boolean }; type Done = { clip: string; kind: ClipExportKind; name: string; rel: string; size: number; seconds: number; summary: string; notes: string[]; download: string; canOpen: boolean; openWhy?: string; }; export type ClipExportState = | { k: "idle" } | { k: "exporting"; clip: string; kind: ClipExportKind; since: number; fetching?: boolean; line?: string | null } | { k: "ready"; done: Done; open: { k: "idle" } | { k: "opening" } | { k: "opened"; how: string } | { k: "failed"; error: string } } | { k: "failed"; clip: string; kind: ClipExportKind; error: string }; export type ClipExportHandle = { state: ClipExportState; busy: boolean; run: (clip: string, kind?: ClipExportKind, opts?: ClipExportOpts) => Promise; openFolder: () => Promise; dismiss: () => void; }; const mb = (n: number) => (n < 1e6 ? `${Math.max(1, Math.round(n / 1e3))} kB` : `${(n / 1e6).toFixed(n < 1e7 ? 1 : 0)} MB`); /** One project's (or take's) export: what is being made, what was, and Open folder. */ export function useClipExport(project: string, take: string | null = null): ClipExportHandle { const [state, setState] = useState({ k: "idle" }); const seq = useRef(0); const busy = state.k === "exporting"; const run = useCallback( async (clip: string, kind: ClipExportKind = "cut", opts: ClipExportOpts = {}) => { const mine = ++seq.current; const since = Date.now(); setState({ k: "exporting", clip, kind, since }); const fail = (error: string) => { if (mine === seq.current) setState({ k: "failed", clip, kind, error }); }; try { const r = await fetch("/api/report/clip-export", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip, kind, ...(take ? { take } : {}), ...(kind === "context" && opts.context != null ? { context: opts.context } : {}), ...(kind === "raw" && opts.span ? { span: opts.span } : {}), ...(opts.fetch ? { fetch: true } : {}), }), }); const j = (await r.json().catch(() => ({}))) as { error?: string; fetching?: boolean; job?: { id: string } }; if (mine !== seq.current) return; if (!r.ok || !j.job?.id) return fail(String(j.error ?? `HTTP ${r.status}`)); const job = j.job.id; setState({ k: "exporting", clip, kind, since, fetching: !!j.fetching }); // The job: polled until its export event (or its failure) is in. for (;;) { await new Promise((res) => setTimeout(res, 700)); if (mine !== seq.current) return; const g = await fetch(`/api/report/clip-export?job=${encodeURIComponent(job)}`, { cache: "no-store" }); const v = (await g.json().catch(() => ({}))) as { done?: Done; error?: string; job?: { state: string; stepIndex: number; steps: unknown[]; log: string[] } }; if (mine !== seq.current) return; if (v.done) { setState({ k: "ready", done: { ...v.done, clip, kind }, open: { k: "idle" } }); return; } if (v.error || !g.ok) return fail(String(v.error ?? `HTTP ${g.status}`)); if (v.job && v.job.state !== "running") return fail(v.job.state === "done" ? "the job ended without an export" : `the job ${v.job.state}`); const fetching = !!j.fetching && (v.job?.stepIndex ?? 0) < (v.job?.steps.length ?? 1) - 1; const line = v.job?.log.filter((l) => !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? null; setState({ k: "exporting", clip, kind, since, fetching, line }); } } catch (e) { fail(e instanceof Error ? e.message : String(e)); } }, [project, take], ); const openFolder = useCallback(async () => { if (state.k !== "ready") return; const done = state.done; setState({ k: "ready", done, open: { k: "opening" } }); try { const r = await fetch("/api/report/exports", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, name: done.name }), }); const j = (await r.json().catch(() => ({}))) as { ok?: boolean; how?: string; error?: string }; setState((s) => s.k === "ready" && s.done.name === done.name ? { ...s, open: r.ok && j.ok ? { k: "opened", how: String(j.how ?? "") } : { k: "failed", error: String(j.error ?? `HTTP ${r.status}`) } } : s, ); } catch (e) { setState((s) => (s.k === "ready" && s.done.name === done.name ? { ...s, open: { k: "failed", error: e instanceof Error ? e.message : String(e) } } : s)); } }, [project, state]); const dismiss = useCallback(() => { seq.current += 1; setState({ k: "idle" }); }, []); return { state, busy, run, openFolder, dismiss }; } type Surface = "paper" | "panel"; const btn = (surface: Surface, quiet = false) => surface === "paper" ? paperButtonVariants() : buttonVariants({ variant: quiet ? "quiet" : "outline", size: "sm" }); /** Export clip, its raw choice, and Export ▾, for `clip` (null: nothing to export here, `why` says so). */ export function ClipExportButtons({ exp, clip, surface = "panel", why = null, unsaved = false, around = null, align = "start", }: { exp: ClipExportHandle; clip: string | null; surface?: Surface; /** Why there is nothing to export (a card, a window not fetched): the cut and raw buttons are off and say so. */ why?: string | null; /** The bench has an edit not saved yet: the export is of the SAVED clip. */ unsaved?: boolean; /** The clip's extent (source seconds): the full exchange's span starts from it. */ around?: { start: number; end: number } | null; /** Which edge of Export ▾ its options open from: "end" on the bench's reader, at the screen's right edge. */ align?: "start" | "end"; }) { const hydrated = useHydrated(); const off = !hydrated || !clip || !!why || exp.busy; const saved = unsaved ? " — of the SAVED window: save first to export your edit" : ""; return ( <> ); } const CONTEXT_DEFAULT = 5; const r1 = (n: number) => Math.round(n * 10) / 10; /** * Export ▾: the three kinds (UI notes item 12) in one place -- as cut (no * chrome), with N s of context, raw / full exchange over a span. Context and * the full exchange are fetched through the editor first when what they need * is not on disk (`fetch: true`; the job says so while it fetches). */ function ExportMenu({ exp, clip, surface, around, saved, align, disabled, }: { exp: ClipExportHandle; clip: string | null; surface: Surface; around: { start: number; end: number } | null; saved: string; align: "start" | "end"; disabled: boolean; }) { const [open, setOpen] = useState(false); const [ctx, setCtx] = useState(String(CONTEXT_DEFAULT)); const [from, setFrom] = useState(""); const [to, setTo] = useState(""); const box = useRef(null); // A new clip: the span starts from its extent again. useEffect(() => { setFrom(around ? String(r1(Math.max(0, around.start - 30))) : ""); setTo(around ? String(r1(around.end + 30)) : ""); }, [clip, around?.start, around?.end]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!open) return; const away = (e: PointerEvent) => { if (box.current && !box.current.contains(e.target as Node)) setOpen(false); }; const esc = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); }; window.addEventListener("pointerdown", away); window.addEventListener("keydown", esc); return () => { window.removeEventListener("pointerdown", away); window.removeEventListener("keydown", esc); }; }, [open]); const n = Number(ctx); const ctxOk = Number.isFinite(n) && n >= 1 && n <= 120; const a = Number(from); const b = Number(to); const spanOk = from.trim() !== "" && to.trim() !== "" && Number.isFinite(a) && Number.isFinite(b) && a >= 0 && b - a >= 0.5; const go = (kind: ClipExportKind, opts: ClipExportOpts = {}) => { if (!clip) return; setOpen(false); void exp.run(clip, kind, opts); }; const input = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 font-mono text-[11px] text-[var(--color-text)]"; const item = buttonVariants({ variant: "outline", size: "sm" }); return (
{open && (
its edges, gaps out as jump cuts, its mute — no rail, subtitles, QR or cards
setCtx(e.target.value)} /> s either side what the cut plays and {ctxOk ? n : "N"} s around it, as recorded (1–120; fetched first if not on disk)
setFrom(e.target.value)} /> – setTo(e.target.value)} /> source seconds, as recorded (no gaps, no mute) — what is not on disk is fetched through the editor first
named <clip>-<kind>-<date>-<words>.mp4 in the project’s exports/ · Download for a phone
)}
); } /** Exporting… / the file, Download, Open folder / failed, with the reason. */ export function ClipExportStatus({ exp, surface = "panel", className }: { exp: ClipExportHandle; surface?: Surface; className?: string }) { const s = exp.state; const [, tick] = useState(0); useEffect(() => { if (s.k !== "exporting") return; const t = window.setInterval(() => tick((n) => n + 1), 1000); return () => window.clearInterval(t); }, [s.k]); if (s.k === "idle") return null; const muted = surface === "paper" ? "text-reader-dim" : "text-muted"; const link = surface === "paper" ? "font-medium text-reader-ink underline underline-offset-2" : "ink-link"; const base = cn("basis-full min-w-0 text-[11.5px]", surface === "paper" ? "text-reader-ink" : "text-text-2", className); if (s.k === "exporting") { return (

{s.fetching ? "Fetching what it needs through the editor, then exporting " : "Exporting "} {s.clip} {s.kind === "raw" ? " (raw)" : s.kind === "context" ? " (with context)" : ""}… {Math.max(0, Math.round((Date.now() - s.since) / 1000))} s {s.line ? {s.line.slice(0, 120)} : null}

); } if (s.k === "failed") { return (

Export of {s.clip} failed: {s.error}{" "}

); } const d = s.done; return (
{d.rel} {d.seconds.toFixed(1)} s · {mb(d.size)} Download {d.canOpen ? ( ) : ( (Open folder: on the machine umtool runs on) )} {s.open.k === "opened" && shown in the file manager} {s.open.k === "failed" && ( {s.open.error} )} {d.summary} {d.notes.length ? ` · ${d.notes.join(" · ")}` : ""}
); }