"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import type { Peaks } from "@/components/Waveform"; import { buttonVariants } from "@/components/ui/button"; import { alpha, usePalette } from "@/components/ui/use-palette"; import { cn } from "@/lib/utils"; import { pauseSpans } from "umtool-report-to-video/pauses"; import { DETAIL_SPAN, ZOOM_STEP, centreOn, clampVis, isFit, panBy, quietPoints, rulerFor, tickLabel, wheelFactor, zoomAt, zoomTo, } from "@/lib/report/benchZoom.mjs"; // --------------------------------------------------------------------------- // THE BENCH WAVEFORM, CLOSER (ClipBench.tsx's desk): a zoom on the waveform // where edges, the mute mark and a clip's GAPS (umtool-report-to-video // gaps.mjs: seconds cut out of its middle) are set. // // zoom Ctrl/⌘ + wheel (a trackpad's pinch is one) at the pointer, the // second under it staying there; − / + / Fit / Zoom to selection; // z in, Z out, f fit, F to the selection. The waveform, every mark // over it and the handles' drags all work on what is shown. // pan the wheel (either axis) while zoomed; a drag on the overview // strip under it, which shows the whole cached window, what is // shown in it, the selection and the gaps; a two-finger pinch on it. // closer a ruler of round ticks, and at DETAIL_SPAN seconds or less the // measured silences (the cut-points route's, the build's own), the // pauses (pauses.mjs pauseSpans: those silences and the gaps // between timed words, merged) as bands, and a box per WORD with // its text (a caption word's box runs to the next word's start), // so a gap's edge -- or a tightened edge -- goes between two words. // gaps each a hatched band over the waveform, `cut` on it; a click on // one picks it where a gap has settings of its own (a clip's: its // mark, why and Remove under the waveform), else puts it back (a // reel beat's). A span for a new one is dragged with Alt held // (or after `g` / Select a gap); Cut gap (or `g`) writes it. // // At fit -- the default, and on every clip's arrival -- the waveform is exactly // what it was: no ruler, no overview, nothing moved. // --------------------------------------------------------------------------- export type Span = { from: number; to: number }; /** * What the waveform shows (`vis`) and the zoom's moves, over `whole` (the * cached window). Null state is fit. `ref` goes on the element the wheel is * read over. */ export function useWaveZoom(whole: Span) { const [zv, setZv] = useState(null); // A different window (a fetch widened it, the next clip): what was shown, kept inside it. const wholeKey = `${whole.from}|${whole.to}`; const lastWhole = useRef(wholeKey); useEffect(() => { if (lastWhole.current === wholeKey) return; lastWhole.current = wholeKey; setZv((v) => (v ? (isFit(clampVis(v, whole), whole) ? null : clampVis(v, whole)) : null)); // `whole` is read through its key. // eslint-disable-next-line react-hooks/exhaustive-deps }, [wholeKey]); const vis = zv ?? whole; const zoomed = !isFit(zv, whole); const set = useCallback((v: Span) => setZv(isFit(v, whole) ? null : v), [whole]); const zoomIn = useCallback((at?: number | null) => set(zoomAt(zv, whole, at ?? (vis.from + vis.to) / 2, ZOOM_STEP)), [zv, whole, vis.from, vis.to, set]); const zoomOut = useCallback((at?: number | null) => set(zoomAt(zv, whole, at ?? (vis.from + vis.to) / 2, 1 / ZOOM_STEP)), [zv, whole, vis.from, vis.to, set]); const fit = useCallback(() => setZv(null), []); const to = useCallback((range: Span) => set(zoomTo(range, whole)), [whole, set]); const pan = useCallback((dt: number) => set(panBy(zv, whole, dt)), [zv, whole, set]); const centre = useCallback((t: number) => set(centreOn(zv, whole, t)), [zv, whole, set]); // The wheel, read natively: React's is passive, and a zoom must not also scroll the page. const el = useRef(null); const state = useRef({ zv, whole, vis, zoomed, set }); state.current = { zv, whole, vis, zoomed, set }; // Attached as the element mounts (a callback ref: the waveform is not on the page at the first render). const detach = useRef<(() => void) | null>(null); const ref = useCallback((node: HTMLDivElement | null) => { detach.current?.(); detach.current = null; el.current = node; if (!node) return; const on = (e: WheelEvent) => { const s = state.current; const r = node.getBoundingClientRect(); const at = s.vis.from + ((e.clientX - r.left) / Math.max(1, r.width)) * (s.vis.to - s.vis.from); if (e.ctrlKey || e.metaKey) { e.preventDefault(); s.set(zoomAt(s.zv, s.whole, at, wheelFactor(e.deltaY, e.deltaMode))); return; } if (!s.zoomed) return; // Zoomed: the wheel pans, either axis (shift turns a vertical wheel sideways on most systems already). const d = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY; if (!d) return; e.preventDefault(); const px = e.deltaMode === 1 ? d * 16 : e.deltaMode === 2 ? d * 400 : d; s.set(panBy(s.zv, s.whole, (px / Math.max(1, r.width)) * (s.vis.to - s.vis.from))); }; node.addEventListener("wheel", on, { passive: false }); detach.current = () => node.removeEventListener("wheel", on); }, []); return { vis, zoomed, ref, zoomIn, zoomOut, fit, to, pan, centre, set }; } export type WaveZoom = ReturnType; const btn = buttonVariants({ variant: "outline", size: "sm" }); /** * − / + / Fit / Zoom to selection, and how much is shown. The same controls zoom Play's reel strip * (ReelStrip.tsx), over cut seconds: `selectionLabel` / `selectionTitle` name what the last button * zooms to there ("Zoom to clip"), `wholeLabel` what fit shows ("whole cut"), `children` any more. */ export function ZoomControls({ zoom, whole, selection, playhead, selectionLabel = "Zoom to selection", selectionTitle = "zoom to the gap you are selecting, else the selection (F)", wholeLabel = "whole window", children, }: { zoom: WaveZoom; whole: Span; selection: Span | null; playhead: number | null; selectionLabel?: string; selectionTitle?: string; wholeLabel?: string; children?: React.ReactNode; }) { const at = playhead != null && playhead >= zoom.vis.from && playhead <= zoom.vis.to ? playhead : null; const shown = zoom.vis.to - zoom.vis.from; return ( zoom {children} {zoom.zoomed ? `${shown < 10 ? shown.toFixed(2) : shown.toFixed(1)} s of ${(whole.to - whole.from).toFixed(0)} s` : wholeLabel} ); } /** The ruler over the zoomed waveform: round ticks, labelled. */ export function ZoomRuler({ vis }: { vis: Span }) { const { step, ticks } = rulerFor(vis); const span = Math.max(1e-6, vis.to - vis.from); return (
{ticks.map((t) => ( {tickLabel(t, step)} ))}
); } /** * Over the waveform (absolutely placed, the waveform's box): the gaps, the * span being selected for one, and -- close in -- the silences and the pauses * between words. `onBand` on a gap's click (pick it, or put it back: useGapEditor's `band`); while `picking` (or with Alt * held over the waveform, the caller's capture handler) a drag selects a span. */ /** What GapLayer draws of the walls: gapWalls's shape, the zones' kinds open (a reel adds its master's gaps). */ export type GapWallsView = { span: Span; /** What the span is called in a sentence: "cut", "clip", "beat". */ whose: string; zones: Array<{ from: number; to: number; kind: string; why: string }>; marks: Array<{ at: number; kind: string; why: string }>; }; export function GapLayer({ vis, gaps, selection, picking, silences, words, busy, onBand, onSelect, live = null, walls = null, picked = null, pickable = false, }: { vis: Span; gaps: Array; /** The gap whose settings are shown (useGapEditor's `picked`): outlined. */ picked?: Span | null; /** A click on a band picks the gap (its settings) rather than putting it back (useGapEditor's `settings`). */ pickable?: boolean; selection: Span | null; /** What the selection would do, checked on every move (useGapEditor's GapLive). */ live?: { why: string | null; wall: string | null; merged: { from: number; to: number } | null; short: boolean } | null; /** * Where a gap cannot go, and why (gaps.mjs gapWalls, or a reel beat's own): * drawn so no wall a gap drag stops at is invisible -- outside the span and * the keep bands shaded (a strip along the foot always, the full height * while a gap is being picked), each mark a gap can't cover ticked, every * one with its sentence on hover. */ walls?: GapWallsView | null; picking: boolean; silences: Span[] | null; /** The recording's words (the clip-editor route's): timed (`end`), or a caption word's start only. */ words: { start: number; end?: number; w?: string }[] | null; busy: boolean; /** A click on a gap's band: useGapEditor's `band` (picks it with `settings`, else puts it back). */ onBand: (g: Span) => void; onSelect: (s: Span, done: boolean) => void; }) { const span = Math.max(1e-6, vis.to - vis.from); const pct = (t: number) => `${((Math.min(vis.to, Math.max(vis.from, t)) - vis.from) / span) * 100}%`; const width = (a: number, b: number) => `calc(${pct(b)} - ${pct(a)})`; const inView = (s: Span) => s.to > vis.from && s.from < vis.to; const close = vis.to - vis.from <= DETAIL_SPAN; const timed = (words ?? []).filter((w): w is { start: number; end: number; w?: string } => typeof w.end === "number"); const quiet = close ? quietPoints({ words: timed, silences }, vis.from, vis.to) : []; const pauses = close ? pauseSpans({ words: timed, silences }, { from: vis.from, to: vis.to }) : []; // A box per word in view: its own end, else (a caption's word) the next word's start, at most a second on. const sorted = close ? [...(words ?? [])].sort((a, b) => a.start - b.start) : []; const boxes = sorted .map((w, i) => ({ text: w.w ?? "", from: w.start, to: typeof w.end === "number" ? w.end : Math.min(w.start + 1, sorted[i + 1]?.start ?? w.start + 1) })) .filter((b) => b.to > b.from && inView(b)); const drag = useRef<{ id: number; at: number } | null>(null); const tAt = (el: HTMLElement, clientX: number) => { const r = el.getBoundingClientRect(); return vis.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * span; }; return ( <> {close && (silences ?? []).filter(inView).map((s) => (
))} {pauses.filter(inView).map((p) => (
))} {boxes.map((b) => (
{b.text}
))} {quiet.map((t) => (
))} {walls && } {gaps.filter(inView).map((g) => { const on = !!picked && picked.from === g.from && picked.to === g.to; return ( ); })} {selection && inView(selection) && (
)} {/* What the selection would do, said while it is dragged: the writer's refusal, the wall it stopped at, the gap it would merge into. */} {selection && live && (live.why || live.wall || live.merged) && (
{[ live.why ? (live.short ? live.why : `can't cut: ${live.why}`) : null, live.merged ? `touches a gap — cutting makes one gap ${live.merged.from.toFixed(2)}–${live.merged.to.toFixed(2)}` : null, live.wall, ] .filter(Boolean) .join(" · ")}
)} {picking && (
{ e.currentTarget.setPointerCapture(e.pointerId); const at = tAt(e.currentTarget, e.clientX); drag.current = { id: e.pointerId, at }; onSelect({ from: at, to: at }, false); }} onPointerMove={(e) => { const d = drag.current; if (!d || d.id !== e.pointerId) return; const t = tAt(e.currentTarget, e.clientX); onSelect({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, false); }} onPointerUp={(e) => { const d = drag.current; if (!d || d.id !== e.pointerId) return; drag.current = null; const t = tAt(e.currentTarget, e.clientX); onSelect({ from: Math.min(d.at, t), to: Math.max(d.at, t) }, true); }} onPointerCancel={() => { drag.current = null; }} /> )} ); } const OVERVIEW_H = 22; /** * The whole cached window under a zoomed waveform: its peaks small, the * selection, the gaps, and the stretch shown -- dragged to pan, clicked * elsewhere to centre there, pinched (two fingers) to zoom. */ export function ZoomOverview({ zoom, whole, peaks = null, sel = null, gaps = [], paint, }: { zoom: WaveZoom; whole: Span; peaks?: Peaks | null; sel?: Span | null; gaps?: Span[]; /** Draw the whole yourself (Play's reel strip: its cells and seams) in place of the peaks; `toX` maps a second. */ paint?: (g: CanvasRenderingContext2D, toX: (t: number) => number, width: number, height: number) => void; }) { const pal = usePalette(); const box = useRef(null); const canvas = useRef(null); const [width, setWidth] = useState(600); useEffect(() => { const el = box.current; if (!el) return; const ro = new ResizeObserver(() => setWidth(el.clientWidth || 600)); ro.observe(el); setWidth(el.clientWidth || 600); return () => ro.disconnect(); }, []); const W = Math.max(1e-6, whole.to - whole.from); const pct = (t: number) => `${((Math.min(whole.to, Math.max(whole.from, t)) - whole.from) / W) * 100}%`; 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(OVERVIEW_H * dpr); const g = cv.getContext("2d"); if (!g) return; g.setTransform(dpr, 0, 0, dpr, 0, 0); g.clearRect(0, 0, width, OVERVIEW_H); const mid = OVERVIEW_H / 2; const toX = (t: number) => ((t - whole.from) / W) * width; if (paint) { paint(g, toX, width, OVERVIEW_H); return; } if (sel) { g.fillStyle = alpha(pal.signal, 0.12); g.fillRect(toX(sel.from), 0, Math.max(1, toX(sel.to) - toX(sel.from)), OVERVIEW_H); } if (peaks && peaks.max.length) { const n = peaks.max.length; const pSpan = Math.max(1e-6, peaks.to - peaks.from); g.fillStyle = pal["seam-2"]; for (let i = 0; i < n; i += 1) { const t0 = peaks.from + (i / n) * pSpan; const x = toX(t0); if (x < -1 || x > width + 1) continue; const y0 = mid - peaks.max[i] * (mid - 2); const y1 = mid - peaks.min[i] * (mid - 2); g.fillRect(x, Math.min(y0, y1), Math.max(1, width / n), Math.max(1, Math.abs(y1 - y0))); } } g.fillStyle = alpha(pal.reject, 0.45); for (const gp of gaps) g.fillRect(toX(gp.from), 0, Math.max(1, toX(gp.to) - toX(gp.from)), OVERVIEW_H); }, [peaks, width, whole.from, W, sel?.from, sel?.to, gaps, pal, paint]); const drag = useRef<{ id: number; grab: number } | null>(null); const tAt = (clientX: number) => { const r = box.current?.getBoundingClientRect(); if (!r) return whole.from; return whole.from + Math.min(1, Math.max(0, (clientX - r.left) / Math.max(1, r.width))) * W; }; // Two fingers: the distance between them is the zoom, about their middle. const pinch = useRef<{ d: number; mid: number } | null>(null); useEffect(() => { const el = box.current; if (!el) return; const dist = (e: TouchEvent) => Math.abs(e.touches[0].clientX - e.touches[1].clientX); const midOf = (e: TouchEvent) => (e.touches[0].clientX + e.touches[1].clientX) / 2; const start = (e: TouchEvent) => { if (e.touches.length !== 2) return; e.preventDefault(); drag.current = null; pinch.current = { d: Math.max(8, dist(e)), mid: midOf(e) }; }; const move = (e: TouchEvent) => { const p = pinch.current; if (!p || e.touches.length !== 2) return; e.preventDefault(); const d = Math.max(8, dist(e)); const r = el.getBoundingClientRect(); const at = whole.from + ((midOf(e) - r.left) / Math.max(1, r.width)) * W; zoom.set(zoomAt(zoom.vis, whole, at, d / p.d)); pinch.current = { d, mid: midOf(e) }; }; const end = () => { pinch.current = null; }; el.addEventListener("touchstart", start, { passive: false }); el.addEventListener("touchmove", move, { passive: false }); el.addEventListener("touchend", end); return () => { el.removeEventListener("touchstart", start); el.removeEventListener("touchmove", move); el.removeEventListener("touchend", end); }; }, [zoom, whole, W]); return (
{ if (pinch.current) return; e.currentTarget.setPointerCapture(e.pointerId); const t = tAt(e.clientX); const inside = t >= zoom.vis.from && t <= zoom.vis.to; // On the shown stretch: grab it where it was taken. Elsewhere: centre there, then drag. if (!inside) zoom.centre(t); const from = inside ? zoom.vis.from : t - (zoom.vis.to - zoom.vis.from) / 2; drag.current = { id: e.pointerId, grab: t - from }; }} onPointerMove={(e) => { const d = drag.current; if (!d || d.id !== e.pointerId || pinch.current) return; const span = zoom.vis.to - zoom.vis.from; zoom.set(clampVis({ from: tAt(e.clientX) - d.grab, to: tAt(e.clientX) - d.grab + span }, whole)); }} onPointerUp={() => { drag.current = null; }} onPointerCancel={() => { drag.current = null; }} >
); } /** The walls (GapLayer's `walls`): no-cut zones and the marks a gap can't cover. */ function GapWallsLayer({ walls, vis, pct, width, full, }: { walls: GapWallsView; vis: Span; pct: (t: number) => string; width: (a: number, b: number) => string; /** A gap is being picked: shade the full height, not just the foot. */ full: boolean; }) { const inView = (a: number, b: number) => b > vis.from && a < vis.to; const zones: Array<{ from: number; to: number; kind: string; why: string }> = []; if (walls.span.from > vis.from) zones.push({ from: vis.from, to: walls.span.from, kind: "outside", why: `before the ${walls.whose}'s start: a gap goes inside the ${walls.whose}` }); if (walls.span.to < vis.to) zones.push({ from: walls.span.to, to: vis.to, kind: "outside", why: `after the ${walls.whose}'s end: a gap goes inside the ${walls.whose}` }); zones.push(...walls.zones.filter((z) => z.to > z.from)); return ( <> {zones .filter((z) => inView(z.from, z.to)) .map((z, k) => (
))} {/* The cut's own edges, labelled: where the span of gaps starts and ends. */} {(["start", "end"] as const).map((side) => { const t = side === "start" ? walls.span.from : walls.span.to; if (!(t >= vis.from && t <= vis.to)) return null; return (
{side === "start" ? `${walls.whose} ▸` : `◂ ${walls.whose}`}
); })} {walls.marks .filter((m) => m.at >= vis.from && m.at <= vis.to) .map((m) => (
{m.kind === "mute" ? "mute" : m.kind === "stamp" ? "stamp" : "mark"}
))} ); }