"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { Peaks } from "@/components/Waveform"; import { usePalette } from "@/components/ui/use-palette"; import { cn } from "@/lib/utils"; import { ghostLabel, type RenderEdges } from "./RenderGhosts"; import { SNAP_RADIUS, sentenceBoundaries, snapToBoundary, stepBoundary, wordsAtEdge, } from "@/lib/report/sentenceEdges.mjs"; // --------------------------------------------------------------------------- // THE EDGE STRIP (the phone walk's signature; the design brief, "Signature: // the edge strip with sentence snap"). // // The desk moves an edge with a 10 px handle on a wide waveform and `[ ] , .`; // a thumb on a 358 px strip can do neither, and the standing complaint is cuts // that land mid-sentence anyway. So here THE SENTENCE IS THE UNIT OF AN EDGE: // // - the cached window's peaks across the full width, the selection lit in // Signal at 10%, every sentence boundary (lib/report/sentenceEdges.mjs, // the pre-cut's rule) a full-height seam tick; // - each edge a 28 px grab tab that hangs BELOW the waveform, so the thumb // holding it does not cover the line it is placing; // - a drag snaps to the nearest boundary within SNAP_RADIUS, and the tick it // lands on flashes; `Snap | Free` turns that off for an exact cut, and is // remembered per browser like the playback speed; // - per edge, `‹ sentence` / `sentence ›` step it to the previous / next // boundary. A step that would leave the cached window OFFERS the fetch // instead of clamping -- a button that silently stops short is the same // lie the desk's drag refuses to tell (ClipBench, "A DRAG NEVER DOWNLOADS"). // // It never saves. Like the desk's handles it moves the bench's draft selection // through `onSel` -- which auditions the moved edge on release, never during a // drag -- and Confirm (or Save) writes it through the one window writer. // --------------------------------------------------------------------------- type Cue = { start: number; end: number; text: string }; type Edge = "start" | "end"; const SNAP_KEY = "umtool.bench.edgeSnap"; /** The shortest selection an edge may make: an edge never crosses the other. */ const MIN_SPAN = 0.2; const WAVE_H = 72; export default function EdgeStrip({ view, sel, peaks, cues, playhead, limit, busy, fmt, onSel, onFetch, render = null, className, }: { /** The cached window, which the waveform spans. */ view: { from: number; to: number }; sel: { from: number; to: number }; peaks: Peaks | null; /** The cues the boundaries are read from: the cached window's and the peek past it. */ cues: Cue[]; playhead: number | null; /** How far an edge may go without a fetch (the cache, and the recording's own length). */ limit: { from: number; to: number }; busy: boolean; fmt: (t: number) => string; onSel: (next: { from: number; to: number }, dragging: boolean, edge: Edge) => void; /** Fetch far enough to put `t` inside the cache, on `edge`'s side. */ onFetch: (edge: Edge, t: number) => void; /** Where the render will cut (RenderGhosts.tsx useRenderEdges): a faint line on the waveform, its offset under each edge. */ render?: RenderEdges; className?: string; }) { const pal = usePalette(); const box = useRef(null); const canvas = useRef(null); const [width, setWidth] = useState(358); // Snap on until this browser said otherwise; read after mount, as the // bench's playback preference is, so the first paint matches the server's. const [snap, setSnap] = useState(true); useEffect(() => { try { if (localStorage.getItem(SNAP_KEY) === "free") setSnap(false); } catch { /* a private window: snapping stays on */ } }, []); const chooseSnap = (on: boolean) => { setSnap(on); try { localStorage.setItem(SNAP_KEY, on ? "snap" : "free"); } catch { /* the choice still holds for this page */ } }; const bounds = useMemo(() => sentenceBoundaries(cues), [cues]); // The boundary an edge last landed on, lit briefly. const [landed, setLanded] = useState(null); useEffect(() => { if (landed == null) return; const id = window.setTimeout(() => setLanded(null), 700); return () => window.clearTimeout(id); }, [landed]); // A step that would leave the cache: what to fetch, offered in place. const [offer, setOffer] = useState<{ edge: Edge; t: number } | null>(null); useEffect(() => setOffer(null), [limit.from, limit.to]); useEffect(() => { const el = box.current; if (!el) return; const ro = new ResizeObserver(() => setWidth(el.clientWidth || 358)); ro.observe(el); setWidth(el.clientWidth || 358); return () => ro.disconnect(); }, []); const span = Math.max(1e-6, view.to - view.from); const pct = (t: number) => `${((t - view.from) / span) * 100}%`; const inView = (t: number) => t >= view.from - 0.01 && t <= view.to + 0.01; // ---- the waveform ---- useEffect(() => { const cv = canvas.current; if (!cv) return; const dpr = window.devicePixelRatio || 1; cv.width = Math.max(1, Math.floor(width * dpr)); cv.height = Math.floor(WAVE_H * dpr); const g = cv.getContext("2d"); if (!g) return; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.clearRect(0, 0, width, WAVE_H); const mid = WAVE_H / 2; const toX = (t: number) => ((t - view.from) / span) * width; if (peaks && peaks.max.length) { const n = peaks.max.length; const pSpan = Math.max(1e-6, peaks.to - peaks.from); for (let i = 0; i < n; i += 1) { const t0 = peaks.from + (i / n) * pSpan; const x = toX(t0); if (x < -2 || x > width + 2) continue; g.fillStyle = t0 >= sel.from && t0 <= sel.to ? pal.text : pal["seam-2"]; const y0 = mid - peaks.max[i] * (mid - 4); const y1 = mid - peaks.min[i] * (mid - 4); g.fillRect(x, Math.min(y0, y1), Math.max(1, width / n), Math.max(1, Math.abs(y1 - y0))); } } else { g.fillStyle = pal.seam; g.fillRect(0, mid - 1, width, 2); } }, [peaks, width, view.from, span, sel.from, sel.to, pal]); // ---- moving an edge ---- const clampEdge = useCallback( (edge: Edge, t: number) => edge === "start" ? Math.max(limit.from, Math.min(t, sel.to - MIN_SPAN)) : Math.min(limit.to, Math.max(t, sel.from + MIN_SPAN)), [limit.from, limit.to, sel.from, sel.to], ); const listOf = (edge: Edge) => (edge === "start" ? bounds.starts : bounds.ends); // `dx`: how far from the edge line the thumb took hold. The tab sits beside // its line, so without it the edge would jump a tab's width on first move. const drag = useRef<{ edge: Edge; id: number; dx: number } | null>(null); const xOf = (t: number) => { const r = box.current?.getBoundingClientRect(); return r ? r.left + ((t - view.from) / span) * r.width : 0; }; const tAt = (clientX: number) => { const r = box.current?.getBoundingClientRect(); if (!r) return null; const frac = Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))); return view.from + frac * span; }; /** Where a drag at clientX puts `edge`, snapped when snapping is on. */ const place = (edge: Edge, clientX: number) => { const raw = tAt(clientX - (drag.current?.dx ?? 0)); if (raw == null) return null; const s = snap ? snapToBoundary(listOf(edge), raw, SNAP_RADIUS) : { t: raw, boundary: null }; const t = clampEdge(edge, s.t); return { t, boundary: s.boundary != null && Math.abs(t - s.boundary) < 0.01 ? s.boundary : null }; }; const move = (edge: Edge, t: number, dragging: boolean) => onSel(edge === "start" ? { from: t, to: sel.to } : { from: sel.from, to: t }, dragging, edge); const tabHandlers = (edge: Edge) => ({ onPointerDown: (e: React.PointerEvent) => { if (busy) return; e.preventDefault(); e.currentTarget.setPointerCapture(e.pointerId); drag.current = { edge, id: e.pointerId, dx: e.clientX - xOf(edge === "start" ? sel.from : sel.to) }; setOffer(null); }, onPointerMove: (e: React.PointerEvent) => { const d = drag.current; if (!d || d.id !== e.pointerId) return; const p = place(d.edge, e.clientX); if (p) move(d.edge, p.t, true); }, onPointerUp: (e: React.PointerEvent) => { const d = drag.current; if (!d || d.id !== e.pointerId) return; const p = place(d.edge, e.clientX); drag.current = null; if (!p) return; if (p.boundary != null) setLanded(p.boundary); // Release auditions the moved edge (ClipBench's onSel), as on the desk. move(d.edge, p.t, false); }, onPointerCancel: () => { drag.current = null; }, }); /** `‹ sentence` / `sentence ›`: the next boundary that way, or the fetch that reaches it. */ const stepTarget = (edge: Edge, dir: 1 | -1) => { const cur = edge === "start" ? sel.from : sel.to; const t = stepBoundary(listOf(edge), cur, dir); if (t == null) return null; // Never across the other edge. if (edge === "start" && t > sel.to - MIN_SPAN) return null; if (edge === "end" && t < sel.from + MIN_SPAN) return null; const outside = edge === "start" ? t < limit.from - 0.01 : t > limit.to + 0.01; return { t, outside }; }; const step = (edge: Edge, dir: 1 | -1) => { const s = stepTarget(edge, dir); if (!s) return; if (s.outside) { setOffer({ edge, t: s.t }); return; } setOffer(null); setLanded(s.t); move(edge, s.t, false); }; const words = { start: wordsAtEdge(cues, sel.from, "start"), end: wordsAtEdge(cues, sel.to, "end") }; const stepBtn = "inline-flex h-11 min-w-0 items-center justify-center rounded-[3px] border border-seam-2 px-2 text-[13px] text-text active:bg-panel-2 disabled:opacity-40"; return (
Edges {fmt(sel.from)} – {fmt(sel.to)} ({(sel.to - sel.from).toFixed(2)} s) {/* Snap | Free: a visible segmented control, never a long-press. */}
{([true, false] as const).map((on) => ( ))}
{/* The waveform, and the tabs hanging under it. pb is the tabs' reach; mx is a tab's width, so a tab at either end of the cache stays on the page instead of pushing it sideways. */}
{bounds.all.filter(inView).map((t) => (
))} {playhead != null && inView(playhead) && (
)} {render && (["start", "end"] as const).map((edge) => inView(render[edge].at) ? (
) : null, )}
{(["start", "end"] as const).map((edge) => { const t = edge === "start" ? sel.from : sel.to; if (!inView(t)) return null; return (
{/* The edge line over the waveform, then the grab tab under it. */} {edge === "start" ? "◖" : "◗"}
); })}
{/* Per edge: the sentence either way. */} {(["start", "end"] as const).map((edge) => { const back = stepTarget(edge, -1); const on = stepTarget(edge, 1); return (
{edge} {fmt(edge === "start" ? sel.from : sel.to)} {render && ( {ghostLabel(render[edge])} )}
); })} {offer && (

The {offer.edge === "start" ? "previous" : "next"} sentence {offer.edge === "start" ? "starts" : "ends"} at {fmt(offer.t)}, past what is fetched.

)} {/* The words at each edge, in the reader's serif. */}
{words.start &&

{words.start}

} {words.end &&

{words.end}

}
); }