"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { cn } from "@/lib/utils"; import { counterAt, dateRamp, gapJoins, playPlan, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; import { rulerFor, tickLabel } from "@/lib/report/benchZoom.mjs"; import { dropSlot, edgeSpeed, itemSections, labelsThatFit, sectionName } from "@/lib/report/stripDrag.mjs"; import { ZoomOverview, type WaveZoom } from "../bench/GapsZoom"; type PlayItem = ReturnType["items"][number]; // --------------------------------------------------------------------------- // THE REEL STRIP (the Play view's signature): the whole cut as a strip of // film. One cell per entry, as wide as the page shows it; a clip's cell // tinted by its recording's date (older recedes toward the ground); a clip // with no media hatched; the sections' seams as hairlines with the section's // name and first date above; the deck's counter plotted across it as a // staircase in METER, its total at the right end and at the playhead; the // notes as SIGNAL pins at their cut second; the playhead a 1px SIGNAL line. // Click or drag on a cell's body to scrub; a cell's Enter jumps to its start. // // ZOOM (1 Nov 2026) is the bench waveform's (bench/GapsZoom.tsx useWaveZoom, // benchZoom.mjs), over cut seconds: Ctrl/⌘ + wheel at the pointer, − / + / // Fit / Zoom to clip / Zoom to section (z Z f F, in PlayCut), the wheel pans // while zoomed, an overview under the strip shows the whole cut and what is // shown (drag it), a ruler of round ticks. Zoomed, a cell shows its id and // date, the seams their section, and the view follows the playhead. // // REORDER (1 Nov 2026): grab a cell by its top band (the grip, ⠿) -- or // anywhere with Alt held -- and drag. An insertion bar in the section's // colour and the drop's words ("→ §3 Leaves it open, before o02") follow the // pointer; its left half lands before a cell, its right half after it, so at a // seam the two sides are the end of one section and the start of the next. At // a zoomed strip's edge it pans; Ctrl/⌘ + wheel zooms mid-drag; Esc cancels. // A drop is one write through `onEdit` (the place op: lib/report/sectionEdit.mjs // placeIn). The keyboard's: Alt+← / Alt+→ on a focused cell (crossing a seam // first changes its section, then moves it), and Move to… for a section. // --------------------------------------------------------------------------- export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown; rejected?: { why: string } | null }; export type StripCounter = { id: string; label: string; steps: Array<{ t: number; n: number }> }; export type StripPin = { id: string; t: number; text: string; open: boolean }; /** A seam: where a section opens, or (`kind: "group"`) a claim group -- drawn lighter. */ export type StripSeam = { before: string; index: number; date: string | null; label: string | null; kind?: "group"; group?: string }; export type StripSection = { index: number; label: string | null; color: string | null; count?: number; level?: 2; within?: string | null }; /** A structural edit the strip asks for: a drop, an Alt+arrow, or Move to…. */ export type StripEdit = | { op: "place"; ids: string[]; before: string | null; section: number | null; words: string } | { op: "section-move"; ids: string[]; section: number; position: "start" | "end"; words: string }; const CELLS_H = 56; /** The grip band at a cell's top: a press there drags the cell; below it scrubs. */ const GRIP_H = 18; /** How far a press moves before it is a drag (px). */ const DRAG_PX = 4; export default function ReelStrip({ items, total, entries, t, cur, seams, counters, pins, failed, timecode, onSeek, onSeekItem, skipped = [], zoom, sections = [], sectionOf = {}, editable = null, onEdit, busy = false, notice = null, }: { items: PlayItem[]; total: number; entries: Map; t: number; cur: number; seams: StripSeam[]; counters: StripCounter[]; pins: StripPin[]; failed: Record; timecode: (t: number) => string; onSeek: (t: number) => void; onSeekItem: (i: number) => void; /** Entries left out of the plan (clips the walk rejected): a struck-through marker at the seam, why on hover. */ skipped?: { id: string; at: number; why: string }[]; /** What is shown (the bench's zoom over cut seconds, owned by PlayCut for its keys). */ zoom: WaveZoom; /** The project's sections (the deck's markers) and each clip's: where a drop lands. */ sections?: StripSection[]; sectionOf?: Record; /** null: reordering is on; a string: why it is not (said under the strip). */ editable?: string | null; onEdit?: (e: StripEdit) => void; busy?: boolean; /** A word about what a move here does and does not change (a take with sections of its own). */ notice?: string | null; }) { const cells = useRef(null); const [hover, setHover] = useState(null); const scrubbing = useRef(false); const ramp = useMemo(() => dateRamp([...entries.values()]), [entries]); const max = Math.max(1, ...counters.map((c) => c.steps[c.steps.length - 1]?.n ?? 0)); const vis = zoom.vis; const span = Math.max(1e-6, vis.to - vis.from); const frac = (x: number) => (x - vis.from) / span; const pct = (x: number) => `${frac(x) * 100}%`; const wpct = (a: number, b: number) => `${((b - a) / span) * 100}%`; const inView = (a: number, b: number) => b >= vis.from && a <= vis.to; const { step, ticks } = useMemo(() => rulerFor(vis, 12), [vis]); // The strip's width in px: which labels fit, how wide a cell is. const [width, setWidth] = useState(1000); useEffect(() => { const el = cells.current; if (!el) return; const ro = new ResizeObserver(() => setWidth(el.clientWidth || 1000)); ro.observe(el); setWidth(el.clientWidth || 1000); return () => ro.disconnect(); }, []); const pxPerS = width / span; const tAt = (clientX: number) => { const r = cells.current?.getBoundingClientRect(); if (!r || r.width <= 0) return vis.from; return vis.from + Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * span; }; const counterNow = counters.map((c) => ({ ...c, now: counterAt(c.steps, t), end: c.steps[c.steps.length - 1]?.n ?? 0 })); const hovered = hover !== null ? items[hover] : null; const he = hovered ? entries.get(hovered.id) : null; const noMedia = (it: PlayItem) => !!it.clip && (!entries.get(it.id)?.media || !!failed[it.id]); const secs = useMemo(() => itemSections(items, sectionOf), [items, sectionOf]); const colorOf = (k: number) => sections.find((s) => s.index === k)?.color ?? "var(--muted)"; const named = sections.length > 1; // ---- the seams' labels: "27 Feb 2025 §3 Leaves it open" where they fit ---- const seamLabels = useMemo(() => { const list = seams .filter((s) => s.kind !== "group") .map((s) => { const it = items[s.index]; if (!it) return null; const sec = secs[s.index]; const text = named ? [s.date, sectionName(sections, sec)].filter(Boolean).join(" ") : (s.date ?? s.label ?? ""); return { s, sec, x: ((it.from - vis.from) / span) * width, w: text.length * 6.2 + 8 }; }) .filter((x): x is NonNullable => !!x && x.x >= -x.w && x.x <= width); const shown = new Set(labelsThatFit(list.map((l) => ({ x: l.x, w: l.w })))); return list.map((l, i) => ({ ...l, shown: shown.has(i) })); }, [seams, items, secs, sections, named, width, vis.from, span]); // ---- the drag ---- type Drag = { id: string; pointerId: number; x0: number; on: boolean; x: number; y: number }; const [drag, setDrag] = useState(null); const dragRef = useRef(null); dragRef.current = drag; const [refusal, setRefusal] = useState(null); const slot = drag?.on ? dropSlot(items, secs, sections, [drag.id], tAt(drag.x)) : null; const canDrag = editable === null && !!onEdit && !busy; // The edge: a zoomed strip pans while the pointer is near either end. const zoomRef = useRef(zoom); zoomRef.current = zoom; useEffect(() => { if (!drag?.on) return; let raf = 0; let last = performance.now(); const tick = (now: number) => { const d = dragRef.current; const z = zoomRef.current; const r = cells.current?.getBoundingClientRect(); if (d?.on && r && z.zoomed) { const v = edgeSpeed(d.x - r.left, r.width); if (v) z.pan(v * (z.vis.to - z.vis.from) * ((now - last) / 1000)); } last = now; raf = requestAnimationFrame(tick); }; raf = requestAnimationFrame(tick); return () => cancelAnimationFrame(raf); }, [drag?.on]); const cancelDrag = useCallback(() => setDrag(null), []); useEffect(() => { if (!drag) return; const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") { e.stopPropagation(); e.preventDefault(); cancelDrag(); } }; window.addEventListener("keydown", onKey, true); return () => window.removeEventListener("keydown", onKey, true); }, [drag, cancelDrag]); const finishDrag = () => { const d = dragRef.current; setDrag(null); if (!d) return; if (!d.on) { // A press on the grip that never moved: a click -- scrub there, as anywhere. onSeek(tAt(d.x)); return; } const s = dropSlot(items, secs, sections, [d.id], tAt(d.x)); if (!s || s.noop) return; if (s.refused) { setRefusal(`${d.id}: ${s.refused}`); return; } setRefusal(null); onEdit?.({ op: "place", ids: [d.id], before: s.before, section: named ? s.section : null, words: `${d.id} ${s.words}` }); }; // ---- the keyboard: Alt+← / Alt+→ one place, crossing a seam first into the next section ---- const nudge = (i: number, dir: -1 | 1) => { const it = items[i]; if (!it || !onEdit || editable !== null || busy) return; const s = secs[i]; const j = i + dir; if (j < 0 || j >= items.length) return; if (it.clip && named && secs[j] !== s) { // At a seam: the same slot, the next section. const alone = !items.some((x, k) => k !== i && x.clip && secs[k] === s); if (alone) { setRefusal(`${it.id}: ${sectionName(sections, s)} would have no clip left — remove its boundary first, or move another clip into it`); return; } onEdit({ op: "place", ids: [it.id], before: items[i + 1]?.id ?? null, section: secs[j], words: `${it.id} → ${sectionName(sections, secs[j])}` }); return; } const before = dir < 0 ? items[j].id : (items[j + 1]?.id ?? null); onEdit({ op: "place", ids: [it.id], before, section: it.clip && named ? s : null, words: `${it.id} ${dir < 0 ? `before ${items[j].id}` : `after ${items[j].id}`}` }); }; const [picker, setPicker] = useState<{ id: string } | null>(null); const ghostItem = drag?.on ? items.find((x) => x.id === drag.id) : null; const curItem = items[cur] ?? null; return (
{/* the seams' dates and sections, the counter's total at the right end */}
{seamLabels.map((l) => ( {named ? (l.s.date ?? "") : (l.s.date ?? l.s.label ?? "")} {named && {sectionName(sections, l.sec)}} ))} {counterNow.length > 0 && ( `${c.id}:${c.end}`).join(",")}> {counterNow.map((c) => `${c.label} ${c.end}`).join(" · ")} )}
{/* a hovered cell, named above it; the drop's words while dragging */}
{hovered && !drag?.on && inView(hovered.from, hovered.to) && ( 0.75 ? "-100%" : frac((hovered.from + hovered.to) / 2) < 0.25 ? "0" : "-50%"})`, }} > {hovered.id} {he?.dateLabel ? ` · ${he.dateLabel}` : hovered.clip ? "" : ` · ${hovered.type}`} · {shownSeconds(hovered).toFixed(1)} s {noMedia(hovered) ? " · no media — fetch it" : ""} )} {slot && ( 0.6 ? "-100%" : "0"})` }} > {slot.refused ? `refused: ${slot.refused}` : `${drag?.id} ${slot.words}`} )}
{/* the notes' pins */}
{pins .filter((p) => inView(p.t, p.t)) .map((p) => ( ))}
{/* the cells: click or drag the body to scrub; the grip band drags the cell */}
{ cells.current = node; zoom.ref(node); }} data-play-cells="" data-strip-dragging={drag?.on ? drag.id : undefined} className={cn("relative overflow-hidden rounded-[2px] border border-seam bg-ground touch-none", drag?.on ? "cursor-grabbing" : "cursor-col-resize")} style={{ height: CELLS_H }} onPointerDown={(e) => { if (e.button !== 0) return; const r = cells.current?.getBoundingClientRect(); const x = tAt(e.clientX); const i = items.findIndex((it) => x >= it.from && x < it.to); const onGrip = !!r && e.clientY - r.top < GRIP_H; if (i >= 0 && canDrag && (onGrip || e.altKey)) { e.currentTarget.setPointerCapture(e.pointerId); setDrag({ id: items[i].id, pointerId: e.pointerId, x0: e.clientX, on: false, x: e.clientX, y: e.clientY }); return; } scrubbing.current = true; e.currentTarget.setPointerCapture(e.pointerId); onSeek(x); }} onPointerMove={(e) => { const d = dragRef.current; if (d && d.pointerId === e.pointerId) { const on = d.on || Math.abs(e.clientX - d.x0) >= DRAG_PX; setDrag({ ...d, on, x: e.clientX, y: e.clientY }); return; } const x = tAt(e.clientX); const i = items.findIndex((it) => x >= it.from && x < it.to); setHover(i >= 0 ? i : null); if (scrubbing.current) onSeek(x); }} onPointerUp={(e) => { if (dragRef.current && dragRef.current.pointerId === e.pointerId) { finishDrag(); return; } scrubbing.current = false; }} onPointerCancel={() => { scrubbing.current = false; cancelDrag(); }} onPointerLeave={() => setHover(null)} > {items.map((it, i) => { if (!inView(it.from, it.to)) return null; const e = entries.get(it.id); const f = ramp.get(it.id); const missing = noMedia(it); const wrong = e?.rejected?.why ?? null; const base = it.clip ? `color-mix(in srgb, var(--seam-2) ${Math.round(30 + 60 * (f ?? 0.5))}%, var(--ground))` : "var(--panel)"; const px = (it.to - it.from) * pxPerS; const dragged = drag?.on && drag.id === it.id; return ( ); })} {/* a clip's gaps (gaps.mjs): a jump cut inside its cell, where the seconds it leaves out were */} {items.flatMap((it) => gapJoins(it) .filter((g) => inView(g.at, g.at)) .map((g) => ( )), )} {/* the entries skipped (rejected on the walk): a greyed, struck-through tag where they would play */} {skipped .filter((x) => inView(x.at, x.at)) .map((x) => ( {x.id} ))} {/* the sections' seams, in the new section's colour; a claim group's lighter: the lower half, fainter (solid: a dashed line is a gap's join) */} {seams.map((s) => { const it = items[s.index]; if (s.kind === "group") { return it && inView(it.from, it.from) ? ( ) : null; } return it && inView(it.from, it.from) ? ( ) : null; })} {/* the counter's staircase */} {counters.length > 0 && total > 0 && ( {counters.map((c, k) => { const y = (n: number) => 94 - (n / max) * 78; const X = (s: number) => frac(s) * 1000; let d = `M${X(0)},${y(0)}`; for (const s of c.steps) d += ` H${X(s.t)} V${y(s.n)}`; d += ` H${X(total)}`; return ; })} )} {/* the insertion bar while dragging, in the drop's section's colour */} {slot && !slot.noop && ( )} {/* the playhead */} {inView(t, t) && }
{/* the dragged cell, following the pointer */} {ghostItem && drag && ( ⠿ {ghostItem.id} {entries.get(ghostItem.id)?.dateLabel ? ` · ${entries.get(ghostItem.id)?.dateLabel}` : ""} · {shownSeconds(ghostItem).toFixed(1)} s )} {/* the playhead's timecode and the counter at it */}
{inView(t, t) && ( 0.8 ? "-100%" : frac(t) > 0.2 ? "-50%" : "0"})` }} data-play-strip-at="" > {timecode(t)} {counterNow.map((c) => ( {" "} · {c.label} {c.now} ))} )}
{/* the ruler: round ticks over what is shown */}
{ticks.map((s) => ( {s > vis.from + span * 0.02 && s < vis.to - span * 0.04 && {step >= 1 ? runningTime(s) : tickLabel(s, step)}} ))}
{/* the whole cut under a zoomed strip: drag to pan, click to centre */} {zoom.zoomed && (
{ items.forEach((it, i) => { g.fillStyle = named ? (sections.find((s) => s.index === secs[i])?.color ?? "#888") : "#888"; g.globalAlpha = it.clip ? 0.55 : 0.25; g.fillRect(toX(it.from), 3, Math.max(1, toX(it.to) - toX(it.from) - 0.5), h - 6); }); g.globalAlpha = 1; g.fillStyle = "#e5484d"; g.fillRect(Math.min(w - 1.5, toX(t)), 0, 1.5, h); }} />
)} {/* the strip's own row: how to move, Move to…, why reordering is off, a refused drop */}
{onEdit && editable === null ? ( drag a cell by its top band (or with Alt) to move it · Alt+← → on a focused cell ·{" "} ) : editable ? ( {editable} ) : null} {notice && ( {notice} )} {busy && moving…} {refusal && ( {refusal}{" "} )}
{picker && (
Move {picker.id} to
    {sections.map((s) => (
  • {sectionName(sections, s.index)} {(["start", "end"] as const).map((pos) => ( ))}
  • ))}
)}
); }