"use client"; import { useCallback, useEffect, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { HOW_SAID, nearestPause, snapSaid, tightWindow } from "@/lib/report/tightWindow.mjs"; // --------------------------------------------------------------------------- // TIGHTEN TO THE SENTENCE, SNAP AN EDGE TO A PAUSE (UI notes 2026-10-30, item // 4), on the bench's waveform tools. lib/report/tightWindow.mjs decides where // the edges go -- the sentence from the cues (sentenceEdges.mjs), the pause // from the measured silences and the words (report-to-video/pauses.mjs) -- // and the edit is WRITTEN AT ONCE through the bench's one window writer // (`save`: PUT /api/report/window, the token, the cite that follows the edge), // like Extend and the gaps, with an Undo that writes back what was there. // --------------------------------------------------------------------------- export type BenchWord = { w?: string; start: number; end?: number }; type Span = { from: number; to: number }; type Cue = { start: number; end: number; text: string }; type ClipEdges = { id: string; start: number; end: number; cutStart: number | null; cutEnd: number | null; muteFrom: number | null; cite: number | null; citeUrl: string | null; }; /** The words of [from, to] on this clip's recording (the clip-editor route's, the bench's zoom asks the same). */ export async function benchWords(project: string, clip: string, video: string, from: number, to: number): Promise { const q = new URLSearchParams({ project, clip, video, from: String(Math.max(0, Math.floor(from))), to: String(Math.ceil(to)) }); try { const r = await fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" }); if (!r.ok) return null; const j = (await r.json()) as { words?: BenchWord[] | null }; return j.words ?? null; } catch { return null; } } const r2 = (n: number) => Number(n.toFixed(2)); const toWords = (ws: BenchWord[] | null) => (ws ?? []).map((w) => ({ start: w.start, ...(typeof w.end === "number" ? { end: w.end } : {}), text: w.w ?? "" })); /** * Tighten / snap / undo, over the bench's state. `save` is the bench's queued * writer (it re-syncs the clip, the selection and the token, and says when * the cite followed); `lastSaved` its last answer. */ export function useEdgeTools({ project, clip, video, sel, playhead, cues, silences, lo, hi, save, lastSaved, play, setNote, writes = null, }: { project: string; clip: ClipEdges; video: string; sel: Span; playhead: number | null; cues: Cue[]; silences: Span[] | null; lo: number; hi: number; save: (patch: Record) => Promise; lastSaved: React.MutableRefObject | null>; play: (from: number, to: number) => unknown; setNote: (s: string | null) => void; /** * What a span the tools settle on is written AS (the clip bench's cut mode, * lane/bench-modes: the cut, the extent grown past it): the patch, what else * it did in words, and the patch that puts the edges back. Absent: the * extent, the cut and the mute mark cleared when they no longer fit. */ writes?: { patchFor: (s: Span) => { patch: Record; also: string }; back: () => Record; anchorCut: boolean } | null; }) { const [undo, setUndo] = useState<{ patch: Record; what: string } | null>(null); const [working, setWorking] = useState(null); // Another clip: nothing to undo here. useEffect(() => setUndo(null), [clip.id]); /** Write new edges through the window writer, the cut and the mute mark cleared when they no longer fit -- as Save window does. */ const writeEdges = useCallback( async (next: Span, what: string, moved: "start" | "end" | "both") => { const start = r2(next.from); const end = r2(next.to); if (writes) { const { patch, also } = writes.patchFor({ from: start, to: end }); const backPatch = writes.back(); const ok = await save(patch); if (!ok) return false; setUndo({ patch: backPatch, what }); setNote(`${what}${also ? ` — ${also}` : ""} · Undo puts it back`); if (moved === "end") play(Math.max(start, end - 4), end); else play(start, Math.min(end, start + 4)); return true; } const patch: Record = { start, end }; const cleared: string[] = []; if (clip.cutStart != null && clip.cutEnd != null && (clip.cutStart < start - 0.02 || clip.cutEnd > end + 0.02)) { patch.cutStart = ""; patch.cutEnd = ""; cleared.push("the cut"); } if (clip.muteFrom != null && (clip.muteFrom < start - 0.02 || clip.muteFrom > end + 0.02)) { patch.muteFrom = ""; cleared.push("the mute mark"); } const before = clip; const ok = await save(patch); if (!ok) return false; const followed = (lastSaved.current?.citeFollowed ?? null) as { cite?: unknown; citeUrl?: unknown } | null; const back: Record = { start: before.start, end: before.end, ...(patch.cutStart !== undefined ? { cutStart: before.cutStart ?? "", cutEnd: before.cutEnd ?? "" } : {}), ...(patch.muteFrom !== undefined ? { muteFrom: before.muteFrom ?? "" } : {}), // The cite and the QR went with the edge: they come back with it. ...(followed?.cite ? { cite: before.cite ?? "" } : {}), ...(followed?.citeUrl ? { citeUrl: before.citeUrl ?? "" } : {}), }; setUndo({ patch: back, what }); setNote( `${what}${cleared.length ? ` — ${cleared.join(" and ")} no longer fitted and ${cleared.length > 1 ? "were" : "was"} cleared` : ""}` + `${followed?.cite ? " — the cite followed the edge" : followed?.citeUrl ? " — the QR's t= followed the edge" : ""} · Undo puts it back`, ); // Hear what moved. if (moved === "end") play(Math.max(start, end - 4), end); else play(start, Math.min(end, start + 4)); return true; }, [clip, save, lastSaved, play, setNote, writes], ); const tighten = useCallback(async () => { setWorking("tighten"); try { // tightWindow decides whether the playhead is a place (not parked on an edge). const at = playhead; const words = await benchWords(project, clip.id, video, sel.from - 12, sel.to + 12); const r = tightWindow({ // The handles' span is the cut itself in the bench's cut mode: nothing inside it anchors it. clip: { start: sel.from, end: sel.to, cutStart: writes && !writes.anchorCut ? null : clip.cutStart, cutEnd: writes && !writes.anchorCut ? null : clip.cutEnd }, cues, words: toWords(words), silences, at, lo, hi, }); if (!r.ok) { setNote(`not tightened: ${r.why}`); return; } const span = `${r.start.toFixed(2)}–${r.end.toFixed(2)} (${(r.end - r.start).toFixed(2)} s, was ${(sel.to - sel.from).toFixed(2)} s)`; if (!r.changed) { setNote(`already tight: ${HOW_SAID[r.how]} is ${span}`); return; } await writeEdges({ from: r.start, to: r.end }, `tightened to ${HOW_SAID[r.how]}: ${span}${r.said.length ? ` — ${r.said.join("; ")}` : ""}`, "both"); } finally { setWorking(null); } }, [playhead, sel, project, clip, video, cues, silences, lo, hi, writeEdges, setNote]); const snap = useCallback( async (edge: "start" | "end") => { setWorking(edge); try { const t = edge === "start" ? sel.from : sel.to; const words = await benchWords(project, clip.id, video, t - 3, t + 3); const other = edge === "start" ? sel.to : sel.from; const s = nearestPause(t, { words: toWords(words), silences, lo: edge === "start" ? lo : other + 0.5, hi: edge === "start" ? other - 0.5 : hi, }); const said = snapSaid(edge, s) ?? ""; if (!s.moved) { setNote(`not moved: ${said}${!silences?.length && !words?.length ? " — no silences measured and no words for this recording" : ""}`); return; } await writeEdges(edge === "start" ? { from: s.at, to: sel.to } : { from: sel.from, to: s.at }, said, edge); } finally { setWorking(null); } }, [sel, project, clip.id, video, silences, lo, hi, writeEdges, setNote], ); const undoEdges = useCallback(async () => { const u = undo; if (!u) return; const ok = await save(u.patch); if (!ok) return; setUndo(null); setNote(`undone — ${u.what.split(":")[0]} is reversed`); }, [undo, save, setNote]); return { tighten, snap, undoEdges, undo, working }; } const btn = buttonVariants({ variant: "outline", size: "sm" }); /** The buttons, in the waveform's tools row. */ export function TightenButtons({ tools, busy }: { tools: ReturnType; busy: boolean }) { const off = busy || !!tools.working; return ( snap edge to nearest pause {tools.undo && ( )} ); }