Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit ac0c878f636849b3ffc9c1f0759d44c8f76eaab1
parent 147392d48e6cfc212e1cc75f314f569060a61d41
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  1 Nov 2026 11:33:46 -0500

umtool: Play's reel strip zooms (the bench waveform's zoom, over cut seconds) and reorders by drag -- the drop's section said, one write per drop, an Undo after; Alt+← → and Move to… on the keyboard

- Zoom: useWaveZoom / ZoomControls / ZoomOverview from bench/GapsZoom.tsx (the
  controls take a label for their last button and children; the overview a
  painter in place of peaks) and benchZoom.mjs's arithmetic: Ctrl/⌘ + wheel at
  the pointer, − + Fit, Zoom to clip, Zoom to section, z Z f F, the wheel pans,
  an overview of the whole cut in the sections' colours, a ruler of round
  ticks. Zoomed, cells show id and date, seams their section ("§3 Leaves it
  open", only the labels that fit), and the view pages on with the playhead.
- Drag: a cell's top band (⠿, or Alt anywhere on it) drags; its body still
  scrubs. The insertion bar is in the drop's section's colour and the words say
  where ("o01 → §3 Leaves it open, after gn1"); a cell's left half lands before
  it, its right half after it, so a seam's two sides are two sections of one
  slot. A zoomed strip pans at its edge, Ctrl/⌘ + wheel zooms mid-drag, Esc
  cancels; a drop that would empty a section is refused in words before any
  write (lib/report/stripDrag.mjs, unit-tested).
- Write: the place op (placeEntries) with the view's token; the playhead held
  on its clip across the re-read; until the deck is composed again the
  estimate's segments play the new order. Undo is the structural undo with the
  drop's token, so an edit made since is never undone by mistake.
- The view carries the project's sections and each clip's (sectionModel) and
  the manifest's token; a take with its own timeline says reordering is its
  walk's.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/components/projects/bench/GapsZoom.tsx | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mumtool/components/projects/review/PlayCut.tsx | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/components/projects/review/ReelStrip.tsx | 577++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mumtool/lib/report/playView.mjs | 11+++++++++++
Aumtool/lib/report/stripDrag.mjs | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/stripDrag.test.mjs | 89+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 937 insertions(+), 134 deletions(-)

diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx @@ -100,8 +100,30 @@ export type WaveZoom = ReturnType<typeof useWaveZoom>; const btn = buttonVariants({ variant: "outline", size: "sm" }); -/** − / + / Fit / Zoom to selection, and how much is shown. */ -export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZoom; whole: Span; selection: Span | null; playhead: number | null }) { +/** + * − / + / 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 ( @@ -113,7 +135,7 @@ export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZ <button type="button" data-zoom-in="" className={btn} title="zoom in at the playhead, else the middle (z; Ctrl/⌘ + wheel at the pointer)" onClick={() => zoom.zoomIn(at)}> + </button> - <button type="button" data-zoom-fit="" className={btn} disabled={!zoom.zoomed} title="the whole cached window (f)" onClick={zoom.fit}> + <button type="button" data-zoom-fit="" className={btn} disabled={!zoom.zoomed} title={`the ${wholeLabel} (f)`} onClick={zoom.fit}> Fit </button> <button @@ -121,13 +143,14 @@ export function ZoomControls({ zoom, whole, selection, playhead }: { zoom: WaveZ data-zoom-selection="" className={btn} disabled={!selection} - title="zoom to the gap you are selecting, else the selection (F)" + title={selectionTitle} onClick={() => selection && zoom.to(selection)} > - Zoom to selection + {selectionLabel} </button> + {children} <span className="num text-[11px] text-[var(--color-dim)]" data-zoom-shown={shown.toFixed(2)}> - {zoom.zoomed ? `${shown < 10 ? shown.toFixed(2) : shown.toFixed(1)} s of ${(whole.to - whole.from).toFixed(0)} s` : "whole window"} + {zoom.zoomed ? `${shown < 10 ? shown.toFixed(2) : shown.toFixed(1)} s of ${(whole.to - whole.from).toFixed(0)} s` : wholeLabel} </span> </span> ); @@ -263,7 +286,22 @@ const OVERVIEW_H = 22; * 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, sel, gaps }: { zoom: WaveZoom; whole: Span; peaks: Peaks | null; sel: Span; gaps: Span[] }) { +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<HTMLDivElement | null>(null); const canvas = useRef<HTMLCanvasElement | null>(null); @@ -290,8 +328,14 @@ export function ZoomOverview({ zoom, whole, peaks, sel, gaps }: { zoom: WaveZoom g.clearRect(0, 0, width, OVERVIEW_H); const mid = OVERVIEW_H / 2; const toX = (t: number) => ((t - whole.from) / W) * width; - 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 (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); @@ -307,7 +351,7 @@ export function ZoomOverview({ zoom, whole, peaks, sel, gaps }: { zoom: WaveZoom } 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]); + }, [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) => { diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -19,7 +19,9 @@ import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type import { usePlayEngine } from "./playEngine/usePlayEngine"; import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts"; import type { EngineInfo, MediaRef } from "./playEngine/engine"; -import ReelStrip, { type StripCounter } from "./ReelStrip"; +import ReelStrip, { type StripCounter, type StripEdit } from "./ReelStrip"; +import { useWaveZoom, ZoomControls } from "../bench/GapsZoom"; +import { followVis, itemSections } from "@/lib/report/stripDrag.mjs"; import RejectClip from "./RejectClip"; import WhatPlays, { type WorkingCut } from "./WhatPlays"; import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport"; @@ -118,6 +120,11 @@ export type PlayViewData = { takes: { id: string; label: string; made: boolean }[]; /** The working cut's name: the latest whole-cut take, the edits since, the pick (lib/report/workingCut.mjs). */ working?: WorkingCut; + /** The project's sections (the deck's markers) and each clip's: where a drop on the strip lands. */ + sections?: { index: number; label: string | null; color: string | null; marker: number | null; count: number }[]; + sectionOf?: Record<string, number>; + /** The manifest's token when the view was read: a reorder from a stale view is refused, not lost. */ + token?: string; counter: { verdicts: { id: string; label: string }[]; stamps: { landed: number; verdict: string; count: number }[] }; markers: { after: string; label: string }[]; leadIn: number; @@ -168,6 +175,8 @@ const KEYS: { keys: string; what: string }[] = [ { keys: "[ ]", what: "previous / next note" }, { keys: "M", what: "note at the playhead" }, { keys: "E", what: "edit this clip on the bench (Back returns here)" }, + { keys: "z Z f F", what: "the strip: zoom in / out at the playhead, fit, zoom to this clip (Ctrl/⌘ + wheel at the pointer)" }, + { keys: "Alt+← →", what: "on a focused cell: move it one place (at a seam, into the next section first)" }, { keys: "X then 1–7", what: "reject this clip, and why (doesn't match, wrong speaker, irrelevant, repeats, weak, privacy, other)" }, { keys: "Alt+T C M F L O", what: "the note's kind, while writing" }, { keys: "Enter", what: "save the note (Shift+Enter: a new line)" }, @@ -271,7 +280,13 @@ export default function PlayCut({ }, [compose, view.deckOn]); // ---- the plan ---------------------------------------------------------------- - const schedule = doc?.schedule ?? null; + // The composed schedule, while it is the cut's ORDER: a reorder (the strip's drop) re-reads the + // view at once, and until the deck is composed again its segments would play the old order -- + // so the estimate's (the view's own, in the new order) stand in meanwhile. + const composedOrder = doc?.schedule?.segments?.map((x) => x.id).join("\n") ?? null; + const viewOrder = useMemo(() => view.segments.map((x) => x.id).join("\n"), [view.segments]); + const scheduleNow = composedOrder !== null && composedOrder === viewOrder; + const schedule = scheduleNow ? (doc?.schedule ?? null) : null; const segments = schedule?.segments ?? view.segments; const leadIn = doc?.leadIn ?? view.leadIn; // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change. @@ -518,6 +533,98 @@ export default function PlayCut({ return () => clearTimeout(id); }, [ui.t, ui.cur, ui.playing, showRejected, placeHref]); + // ---- the reel strip's zoom (the bench waveform's, over cut seconds) ------------------ + const zoom = useWaveZoom({ from: 0, to: Math.max(1, plan.total) }); + const stripSecs = useMemo(() => itemSections(plan.items, view.sectionOf ?? {}), [plan.items, view.sectionOf]); + /** The span of the clip on screen, and of its section: what Zoom to clip / to section show. */ + const curSpan = useCallback(() => { + const it = planRef.current.items[now().cur]; + return it ? { from: it.from, to: it.to } : null; + }, [now]); + const sectionSpan = useCallback(() => { + const items = planRef.current.items; + const i = now().cur; + if (!items[i]) return null; + let a = i; + let b = i; + while (a > 0 && stripSecs[a - 1] === stripSecs[i]) a -= 1; + while (b < items.length - 1 && stripSecs[b + 1] === stripSecs[i]) b += 1; + return { from: items[a].from, to: items[b].to }; + }, [now, stripSecs]); + // Zoomed and playing, the strip pages on with the playhead. + useEffect(() => { + if (!zoom.zoomed || !ui.playing) return; + const v = followVis(zoom.vis, { from: 0, to: plan.total }, ui.t); + if (v) zoom.set(v); + }, [ui.t, ui.playing, zoom, plan.total]); + + // ---- reorder (the strip's drop, Alt+arrows, Move to…): one write, an Undo after ------ + const [edit, setEdit] = useState<{ busy: boolean; error: string | null; done: { words: string; token: string | null; undone?: boolean } | null }>({ busy: false, error: null, done: null }); + const lastToken = useRef<string | null>(view.token ?? null); + useEffect(() => { + lastToken.current = view.token ?? null; + setEdit((x) => (x.busy ? { ...x, busy: false } : x)); + }, [view.token]); + /** Keep the playhead on the clip it is on, the same distance in, across the re-read. */ + const holdPlace = useCallback(() => { + const e = now(); + const it = planRef.current.items[e.cur]; + if (it) anchor.current = { clip: it.id, at: Math.max(0, e.t - it.from) }; + }, [now]); + const timelineWrite = useCallback( + async (body: Record<string, unknown>) => { + const r = await fetch("/api/report/timeline", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, token: lastToken.current, ...body }), + }); + const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[]; stale?: boolean; token?: string }; + return { r, j }; + }, + [project], + ); + const runEdit = useCallback( + async (e: StripEdit) => { + setEdit({ busy: true, error: null, done: null }); + const body = e.op === "place" ? { op: "place", ids: e.ids, before: e.before, section: e.section } : { op: "section-move", ids: e.ids, section: e.section, position: e.position }; + const { r, j } = await timelineWrite(body); + if (r.status === 409 && j.stale) { + setEdit({ busy: false, error: "The cut changed since this page read it — read again; drop it again", done: null }); + router.refresh(); + return; + } + if (!r.ok) { + setEdit({ busy: false, error: [j.error ?? `HTTP ${r.status}`, ...(j.errors ?? [])].join(" — "), done: null }); + return; + } + lastToken.current = j.token ?? null; + holdPlace(); + setEdit({ busy: true, error: null, done: { words: e.words, token: j.token ?? null } }); + router.refresh(); + if (view.deckOn) void compose(); + }, + [timelineWrite, holdPlace, router, view.deckOn, compose], + ); + const undoEdit = useCallback(async () => { + const d = edit.done; + if (!d) return; + setEdit({ busy: true, error: null, done: d }); + // The structural undo, guarded by the token the drop left: an edit made since is not undone by mistake. + const { r, j } = await timelineWrite({ op: "undo", token: d.token }); + if (!r.ok) { + setEdit({ busy: false, error: r.status === 409 ? "Not undone: the cut changed since that move (Undo last edit on the Cut tab takes back the newest edit)" : (j.error ?? `HTTP ${r.status}`), done: null }); + return; + } + lastToken.current = j.token ?? null; + holdPlace(); + setEdit({ busy: true, error: null, done: { ...d, undone: true } }); + router.refresh(); + if (view.deckOn) void compose(); + }, [edit.done, timelineWrite, holdPlace, router, view.deckOn, compose]); + const editableWhy = !editable + ? `take ${take} has its own timeline: reorder it on its walk (umtool timeline <p> --take ${take} move)` + : null; + // ---- the keys ---------------------------------------------------------------------- const [help, setHelp] = useState(false); useEffect(() => { @@ -541,7 +648,13 @@ export default function PlayCut({ else if (k === "]") stepNote(1); else if (k === "m" || k === "M") noteHere(); else if (k === "e" || k === "E") editHere(); - else if (k === "?") setHelp((h) => !h); + else if (k === "z") zoom.zoomIn(now().t); + else if (k === "Z") zoom.zoomOut(now().t); + else if (k === "f") zoom.fit(); + else if (k === "F") { + const c = curSpan(); + if (c) zoom.to(c); + } else if (k === "?") setHelp((h) => !h); else return; ev.preventDefault(); }; @@ -556,7 +669,7 @@ export default function PlayCut({ window.removeEventListener("keydown", onKey); window.removeEventListener("keyup", onUp); }; - }, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying, now]); + }, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying, now, zoom, curSpan]); // ---- what is on screen ------------------------------------------------------------- const t = ui.t; @@ -869,6 +982,31 @@ export default function PlayCut({ {doc?.finale?.error && <p className="m-0 text-[11.5px] text-reject-text">The finale did not compose: {doc.finale.error}</p>} {/* ---- the reel strip ---- */} + <div className="flex flex-wrap items-center gap-2 text-[11px]" data-strip-zoom-controls=""> + <ZoomControls + zoom={zoom} + whole={{ from: 0, to: Math.max(1, plan.total) }} + selection={item ? { from: item.from, to: item.to } : null} + playhead={t} + selectionLabel="Zoom to clip" + selectionTitle="the clip on screen fills the strip (F)" + wholeLabel="whole cut" + > + <button + type="button" + data-zoom-section="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!item} + title="the section the clip on screen is in fills the strip" + onClick={() => { + const sp = sectionSpan(); + if (sp) zoom.to(sp); + }} + > + Zoom to section + </button> + </ZoomControls> + </div> <ReelStrip items={plan.items} total={plan.total} @@ -883,7 +1021,26 @@ export default function PlayCut({ onSeek={seekTo} onSeekItem={(i) => seekTo(startOf(planRef.current, i))} skipped={plan.skipped.map((x) => ({ ...x, why: entryOf.get(x.id)?.rejected?.why ?? "" }))} + zoom={zoom} + sections={view.sections ?? []} + sectionOf={view.sectionOf ?? {}} + editable={editableWhy} + onEdit={(e) => void runEdit(e)} + busy={edit.busy} /> + {(edit.done || edit.error) && ( + <p role="status" data-strip-toast={edit.error ? "error" : edit.done?.undone ? "undone" : "done"} className={cn("m-0 flex flex-wrap items-center gap-2 text-[11.5px]", edit.error ? "text-reject-text" : "text-text-2")}> + {edit.error ? edit.error : edit.done?.undone ? `Undone: ${edit.done.words}` : `Moved: ${edit.done?.words}`} + {edit.done && !edit.done.undone && !edit.error && ( + <button type="button" className="ink-link" data-strip-undo="" disabled={edit.busy && !edit.done.token} onClick={() => void undoEdit()}> + Undo + </button> + )} + <button type="button" className="ink-link" onClick={() => setEdit((x) => ({ ...x, error: null, done: null }))}> + dismiss + </button> + </p> + )} {rejected.length > 0 && ( <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-muted" data-play-rejected={rejected.map((e) => e.id).join(" ")}> <span> diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx @@ -1,8 +1,11 @@ "use client"; -import { useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { cn } from "@/lib/utils"; -import { counterAt, dateRamp, gapJoins, playPlan, rulerTicks, runningTime, shownSeconds } from "@/lib/report/playCut.mjs"; +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<typeof playPlan>["items"][number]; @@ -11,20 +14,44 @@ type PlayItem = ReturnType<typeof playPlan>["items"][number]; // 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 -// 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 -// anywhere to scrub; a cell's Enter jumps to its start; the ruler under it -// counts the minutes. +// 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 }; export type StripSeam = { before: string; index: number; date: string | null; label: string | null }; +export type StripSection = { index: number; label: string | null; color: string | null; count?: number }; +/** 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; -const pctOf = (t: number, total: number) => `${total > 0 ? Math.max(0, Math.min(100, (t / total) * 100)) : 0}%`; +/** 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, @@ -40,6 +67,12 @@ export default function ReelStrip({ onSeek, onSeekItem, skipped = [], + zoom, + sections = [], + sectionOf = {}, + editable = null, + onEdit, + busy = false, }: { items: PlayItem[]; total: number; @@ -55,36 +88,169 @@ export default function ReelStrip({ 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<string, number>; + /** null: reordering is on; a string: why it is not (said under the strip). */ + editable?: string | null; + onEdit?: (e: StripEdit) => void; + busy?: boolean; }) { const cells = useRef<HTMLDivElement | null>(null); const [hover, setHover] = useState<number | null>(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 { ticks } = useMemo(() => rulerTicks(total), [total]); + 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 0; - return Math.max(0, Math.min(1, (clientX - r.left) / r.width)) * total; + 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 + .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<typeof x> => !!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<Drag | null>(null); + const dragRef = useRef<Drag | null>(null); + dragRef.current = drag; + const [refusal, setRefusal] = useState<string | null>(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 ( - <section data-play-strip="" aria-label="The cut as a reel" className="select-none"> - {/* the seams' dates, the counter's total at the right end */} - <div className="relative h-4 font-mono text-[10px] leading-4 text-muted"> - {seams.map((s) => { - const it = items[s.index]; - if (!it) return null; - return ( - <span key={s.before} data-play-seam-date={s.before} className="absolute top-0 -translate-x-px whitespace-nowrap pl-1" style={{ left: pctOf(it.from, total) }} title={s.label ?? undefined}> - {s.date ?? s.label ?? ""} - </span> - ); - })} + <section data-play-strip="" aria-label="The cut as a reel" className="select-none" data-strip-zoom={zoom.zoomed ? `${vis.from.toFixed(2)}-${vis.to.toFixed(2)}` : "fit"}> + {/* the seams' dates and sections, the counter's total at the right end */} + <div className="relative h-4 overflow-hidden font-mono text-[10px] leading-4 text-muted"> + {seamLabels.map((l) => ( + <span + key={l.s.before} + data-play-seam-section={l.sec} + className={cn("absolute top-0 -translate-x-px whitespace-nowrap pl-1", !l.shown && "invisible")} + style={{ left: l.x, borderLeft: named ? `2px solid ${colorOf(l.sec)}` : undefined }} + title={[l.s.date, named ? sectionName(sections, l.sec) : l.s.label].filter(Boolean).join(" · ")} + > + <span data-play-seam-date={l.s.before}>{named ? (l.s.date ?? "") : (l.s.date ?? l.s.label ?? "")}</span> + {named && <span className={cn("text-text-2", l.s.date && "ml-1")}>{sectionName(sections, l.sec)}</span>} + </span> + ))} {counterNow.length > 0 && ( <span className="absolute right-0 top-0 whitespace-nowrap bg-ground pl-1.5 text-meter" data-play-counter-end={counterNow.map((c) => `${c.id}:${c.end}`).join(",")}> {counterNow.map((c) => `${c.label} ${c.end}`).join(" · ")} @@ -92,15 +258,15 @@ export default function ReelStrip({ )} </div> - {/* a hovered cell, named above it */} + {/* a hovered cell, named above it; the drop's words while dragging */} <div className="relative h-0"> - {hovered && ( + {hovered && !drag?.on && inView(hovered.from, hovered.to) && ( <span data-play-strip-hover={hovered.id} className="pointer-events-none absolute -top-4 z-10 whitespace-nowrap rounded-[2px] border border-seam-2 bg-panel px-1.5 font-mono text-[10.5px] leading-4 text-text-2" style={{ - left: pctOf((hovered.from + hovered.to) / 2, total), - transform: `translateX(${(hovered.from + hovered.to) / 2 / Math.max(total, 1e-9) > 0.75 ? "-100%" : (hovered.from + hovered.to) / 2 / Math.max(total, 1e-9) < 0.25 ? "0" : "-50%"})`, + left: pct((hovered.from + hovered.to) / 2), + transform: `translateX(${frac((hovered.from + hovered.to) / 2) > 0.75 ? "-100%" : frac((hovered.from + hovered.to) / 2) < 0.25 ? "0" : "-50%"})`, }} > {hovered.id} @@ -108,69 +274,111 @@ export default function ReelStrip({ {noMedia(hovered) ? " · no media — fetch it" : ""} </span> )} + {slot && ( + <span + data-strip-drop={slot.noop ? "here" : (slot.before ?? "-")} + data-strip-drop-section={slot.section} + data-strip-drop-refused={slot.refused ? "" : undefined} + className={cn( + "pointer-events-none absolute -top-4 z-20 whitespace-nowrap rounded-[2px] border px-1.5 font-mono text-[10.5px] leading-4", + slot.refused ? "border-reject-text bg-panel text-reject-text" : "border-seam-2 bg-panel text-text", + )} + style={{ left: pct(slot.at), transform: `translateX(${frac(slot.at) > 0.6 ? "-100%" : "0"})` }} + > + {slot.refused ? `refused: ${slot.refused}` : `${drag?.id} ${slot.words}`} + </span> + )} </div> {/* the notes' pins */} - <div className="relative h-3"> - {pins.map((p) => ( - <button - key={p.id} - type="button" - data-play-pin={p.id} - title={`${timecode(p.t)} — ${p.text.split("\n")[0]}`} - aria-label={`note at ${timecode(p.t)}: ${p.text.split("\n")[0]}`} - onClick={() => onSeek(p.t)} - className={cn("absolute top-0 h-3 w-2 -translate-x-1/2 p-0", p.open ? "opacity-100" : "opacity-45")} - style={{ left: pctOf(p.t, total) }} - > - <span className="absolute left-1/2 top-0 h-2 w-2 -translate-x-1/2 rotate-45 bg-signal" /> - <span className="absolute left-1/2 top-1.5 h-1.5 w-px -translate-x-1/2 bg-signal" /> - </button> - ))} + <div className="relative h-3 overflow-hidden"> + {pins + .filter((p) => inView(p.t, p.t)) + .map((p) => ( + <button + key={p.id} + type="button" + data-play-pin={p.id} + title={`${timecode(p.t)} — ${p.text.split("\n")[0]}`} + aria-label={`note at ${timecode(p.t)}: ${p.text.split("\n")[0]}`} + onClick={() => onSeek(p.t)} + className={cn("absolute top-0 h-3 w-2 -translate-x-1/2 p-0", p.open ? "opacity-100" : "opacity-45")} + style={{ left: pct(p.t) }} + > + <span className="absolute left-1/2 top-0 h-2 w-2 -translate-x-1/2 rotate-45 bg-signal" /> + <span className="absolute left-1/2 top-1.5 h-1.5 w-px -translate-x-1/2 bg-signal" /> + </button> + ))} </div> - {/* the cells: click or drag to scrub */} + {/* the cells: click or drag the body to scrub; the grip band drags the cell */} <div - ref={cells} + ref={(node) => { + cells.current = node; + zoom.ref(node); + }} data-play-cells="" - className="relative cursor-col-resize overflow-hidden rounded-[2px] border border-seam bg-ground touch-none" + 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(tAt(e.clientX)); + onSeek(x); }} onPointerMove={(e) => { - const r = cells.current?.getBoundingClientRect(); - if (r) { - const x = tAt(e.clientX); - const i = items.findIndex((it) => x >= it.from && x < it.to); - setHover(i >= 0 ? i : null); + 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; } - if (scrubbing.current) onSeek(tAt(e.clientX)); + 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={() => { + 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 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 ( <button key={it.id} type="button" tabIndex={0} data-play-row={it.id} + data-play-row-section={secs[i]} aria-current={i === cur ? "true" : undefined} - aria-label={`${it.id}${e?.dateLabel ? `, ${e.dateLabel}` : ""}, ${shownSeconds(it).toFixed(1)} seconds${missing ? ", no media" : ""}`} + aria-label={`${it.id}${e?.dateLabel ? `, ${e.dateLabel}` : ""}, ${shownSeconds(it).toFixed(1)} seconds${missing ? ", no media" : ""}${named ? `, ${sectionName(sections, secs[i])}` : ""}`} title={wrong ? `${it.id}: rejected — ${wrong}` : missing ? `${it.id}: no media — fetch it` : undefined} data-play-row-missing={missing ? "" : undefined} data-play-row-rejected={wrong ? "" : undefined} @@ -178,57 +386,89 @@ export default function ReelStrip({ // A pointer's click scrubbed on pointerdown; a key's (Enter) jumps to the entry's start. if (ev.detail === 0) onSeekItem(i); }} + onKeyDown={(ev) => { + if (ev.altKey && (ev.key === "ArrowLeft" || ev.key === "ArrowRight")) { + ev.preventDefault(); + ev.stopPropagation(); + nudge(i, ev.key === "ArrowLeft" ? -1 : 1); + } + }} className={cn( - "absolute top-0 h-full overflow-hidden border-r border-ground px-1 pt-0.5 text-left font-mono text-[10px] leading-3", + "group absolute top-0 h-full overflow-hidden border-r border-ground px-1 text-left font-mono text-[10px] leading-3", it.clip ? "text-text-2" : "text-muted", wrong && "text-muted line-through opacity-60", i === cur && "shadow-[inset_0_-2px_0_var(--signal)]", + dragged && "opacity-35", )} style={{ - left: pctOf(it.from, total), - width: pctOf(it.to - it.from, total), - background: missing - ? `repeating-linear-gradient(135deg, var(--seam-2) 0 1px, transparent 1px 6px), ${base}` - : base, + left: pct(it.from), + width: wpct(it.from, it.to), + background: missing ? `repeating-linear-gradient(135deg, var(--seam-2) 0 1px, transparent 1px 6px), ${base}` : base, }} > - <span className="block whitespace-nowrap">{it.id}</span> - {!it.clip && <span className="block whitespace-nowrap text-[9px] uppercase tracking-wide opacity-80">{it.type}</span>} + {/* the grip band: the section's colour along its top, ⠿ where there is room */} + <span + aria-hidden + data-strip-grip={it.id} + className={cn("absolute inset-x-0 top-0 block", canDrag && "cursor-grab group-hover:bg-[color-mix(in_srgb,var(--signal)_14%,transparent)]")} + style={{ height: GRIP_H, borderTop: named ? `2px solid ${colorOf(secs[i])}` : undefined }} + title={canDrag ? `drag to move ${it.id} (Alt+← → on the keyboard)` : (editable ?? undefined)} + /> + {px >= 14 && ( + <span className={cn("pointer-events-none relative z-[5] mt-1 block w-fit max-w-full overflow-hidden whitespace-nowrap rounded-[2px]", px >= 40 && "bg-ground/70 px-0.5")}> + {px >= 40 && canDrag && <span className="mr-0.5 text-muted-2">⠿</span>} + {it.id} + </span> + )} + {px >= 70 && it.clip && e?.dateLabel && <span className="pointer-events-none relative z-[5] block w-fit whitespace-nowrap rounded-[2px] bg-ground/70 px-0.5 text-[9px] text-muted">{e.dateLabel}</span>} + {!it.clip && px >= 30 && <span className="pointer-events-none relative block whitespace-nowrap text-[9px] uppercase tracking-wide opacity-80">{it.type}</span>} </button> ); })} {/* a clip's gaps (gaps.mjs): a jump cut inside its cell, where the seconds it leaves out were */} {items.flatMap((it) => - gapJoins(it).map((g) => ( - <span - key={`gap:${it.id}:${g.from}`} - data-play-gap={`${it.id}@${g.at}`} - title={`${it.id}: ${(g.to - g.from).toFixed(2)} s cut out (${g.from.toFixed(2)}–${g.to.toFixed(2)}) — a jump cut`} - aria-hidden - className="pointer-events-none absolute top-0 z-[1] h-full w-0 border-l border-dashed border-[var(--color-dirty)]" - style={{ left: pctOf(g.at, total) }} - /> - )), + gapJoins(it) + .filter((g) => inView(g.at, g.at)) + .map((g) => ( + <span + key={`gap:${it.id}:${g.from}`} + data-play-gap={`${it.id}@${g.at}`} + title={`${it.id}: ${(g.to - g.from).toFixed(2)} s cut out (${g.from.toFixed(2)}–${g.to.toFixed(2)}) — a jump cut`} + aria-hidden + className="pointer-events-none absolute top-0 z-[1] h-full w-0 border-l border-dashed border-[var(--color-dirty)]" + style={{ left: pct(g.at) }} + /> + )), )} {/* the entries skipped (rejected on the walk): a greyed, struck-through tag where they would play */} - {skipped.map((x) => ( - <span - key={`skip:${x.id}`} - data-play-skipped={x.id} - title={`${x.id} skipped — rejected${x.why ? ` — ${x.why}` : ""}`} - className="absolute bottom-0 z-[1] -translate-x-1/2 rounded-[2px] bg-ground/90 px-0.5 font-mono text-[9px] leading-3 text-muted line-through opacity-80" - style={{ left: pctOf(x.at, total) }} - > - {x.id} - </span> - ))} + {skipped + .filter((x) => inView(x.at, x.at)) + .map((x) => ( + <span + key={`skip:${x.id}`} + data-play-skipped={x.id} + title={`${x.id} skipped — rejected${x.why ? ` — ${x.why}` : ""}`} + className="absolute bottom-0 z-[1] -translate-x-1/2 rounded-[2px] bg-ground/90 px-0.5 font-mono text-[9px] leading-3 text-muted line-through opacity-80" + style={{ left: pct(x.at) }} + > + {x.id} + </span> + ))} - {/* the sections' seams */} + {/* the sections' seams, in the new section's colour */} {seams.map((s) => { const it = items[s.index]; - return it ? <span key={s.before} aria-hidden className="pointer-events-none absolute top-0 h-full w-px bg-text-2 opacity-60" style={{ left: pctOf(it.from, total) }} /> : null; + return it && inView(it.from, it.from) ? ( + <span + key={s.before} + aria-hidden + data-strip-seam={s.before} + className="pointer-events-none absolute top-0 z-[2] h-full w-px opacity-80" + style={{ left: pct(it.from), background: named ? colorOf(secs[s.index]) : "var(--text-2)" }} + /> + ) : null; })} {/* the counter's staircase */} @@ -236,53 +476,150 @@ export default function ReelStrip({ <svg aria-hidden className="pointer-events-none absolute inset-0 h-full w-full" viewBox="0 0 1000 100" preserveAspectRatio="none" data-play-staircase=""> {counters.map((c, k) => { const y = (n: number) => 94 - (n / max) * 78; - let d = `M0,${y(0)}`; - for (const s of c.steps) d += ` H${(s.t / total) * 1000} V${y(s.n)}`; - d += " H1000"; - return ( - <path - key={c.id} - d={d} - fill="none" - stroke={k === 0 ? "var(--meter)" : k === 1 ? "var(--m3)" : "var(--m5)"} - strokeWidth={1.5} - vectorEffect="non-scaling-stroke" - strokeLinejoin="miter" - /> - ); + 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 <path key={c.id} d={d} fill="none" stroke={k === 0 ? "var(--meter)" : k === 1 ? "var(--m3)" : "var(--m5)"} strokeWidth={1.5} vectorEffect="non-scaling-stroke" strokeLinejoin="miter" />; })} </svg> )} + {/* the insertion bar while dragging, in the drop's section's colour */} + {slot && !slot.noop && ( + <span + aria-hidden + data-strip-insert={slot.before ?? "-"} + className="pointer-events-none absolute top-0 z-[7] h-full w-[3px] -translate-x-1/2 rounded-sm" + style={{ left: pct(slot.at), background: slot.refused ? "var(--reject-text)" : named ? colorOf(slot.section) : "var(--signal)", boxShadow: "0 0 0 1px var(--ground)" }} + /> + )} + {/* the playhead */} - <span aria-hidden data-play-playhead="" className="pointer-events-none absolute top-0 h-full w-px bg-signal" style={{ left: pctOf(t, total) }} /> + {inView(t, t) && <span aria-hidden data-play-playhead="" className="pointer-events-none absolute top-0 z-[6] h-full w-px bg-signal" style={{ left: pct(t) }} />} </div> - {/* the playhead's timecode and the counter at it; a hovered cell's line */} - <div className="relative h-4 font-mono text-[10.5px] leading-4"> + {/* the dragged cell, following the pointer */} + {ghostItem && drag && ( <span - className="absolute top-0 whitespace-nowrap text-signal-text" - style={{ left: pctOf(t, total), transform: `translateX(${t / Math.max(total, 1e-9) > 0.8 ? "-100%" : t / Math.max(total, 1e-9) > 0.2 ? "-50%" : "0"})` }} - data-play-strip-at="" + aria-hidden + data-strip-ghost={ghostItem.id} + className="pointer-events-none fixed z-50 -translate-x-1/2 rounded-[2px] border border-signal bg-panel px-1.5 py-0.5 font-mono text-[11px] text-text shadow-lg" + style={{ left: drag.x, top: drag.y + 18 }} > - {timecode(t)} - {counterNow.map((c) => ( - <span key={c.id} className="text-meter"> - {" "} - · {c.label} {c.now} - </span> - ))} + ⠿ {ghostItem.id} + {entries.get(ghostItem.id)?.dateLabel ? ` · ${entries.get(ghostItem.id)?.dateLabel}` : ""} · {shownSeconds(ghostItem).toFixed(1)} s </span> + )} + + {/* the playhead's timecode and the counter at it */} + <div className="relative h-4 overflow-hidden font-mono text-[10.5px] leading-4"> + {inView(t, t) && ( + <span + className="absolute top-0 whitespace-nowrap text-signal-text" + style={{ left: pct(t), transform: `translateX(${frac(t) > 0.8 ? "-100%" : frac(t) > 0.2 ? "-50%" : "0"})` }} + data-play-strip-at="" + > + {timecode(t)} + {counterNow.map((c) => ( + <span key={c.id} className="text-meter"> + {" "} + · {c.label} {c.now} + </span> + ))} + </span> + )} </div> - {/* the ruler */} - <div className="relative h-4 border-t border-seam font-mono text-[10px] leading-4 text-muted" aria-hidden data-play-ruler=""> + {/* the ruler: round ticks over what is shown */} + <div className="relative h-4 overflow-hidden border-t border-seam font-mono text-[10px] leading-4 text-muted" aria-hidden data-play-ruler={step}> {ticks.map((s) => ( - <span key={s} className="absolute top-0" style={{ left: pctOf(s, total) }}> + <span key={s} className="absolute top-0" style={{ left: pct(s) }}> <span className="absolute -top-px left-0 h-1.5 w-px bg-seam-2" /> - {s > 0 && s < total - total * 0.04 && <span className="absolute left-0 top-0.5 -translate-x-1/2 whitespace-nowrap">{runningTime(s)}</span>} + {s > vis.from + span * 0.02 && s < vis.to - span * 0.04 && <span className="absolute left-0 top-0.5 -translate-x-1/2 whitespace-nowrap">{step >= 1 ? runningTime(s) : tickLabel(s, step)}</span>} </span> ))} </div> + {/* the whole cut under a zoomed strip: drag to pan, click to centre */} + {zoom.zoomed && ( + <div className="mt-1" data-strip-overview=""> + <ZoomOverview + zoom={zoom} + whole={{ from: 0, to: total }} + paint={(g, toX, w, h) => { + 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); + }} + /> + </div> + )} + + {/* the strip's own row: how to move, Move to…, why reordering is off, a refused drop */} + <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted" data-strip-tools=""> + {onEdit && editable === null ? ( + <span> + drag a cell by its top band (or with Alt) to move it · Alt+← → on a focused cell ·{" "} + <button + type="button" + className="ink-link" + data-strip-move-to="" + disabled={!curItem?.clip || busy || sections.length < 2} + onClick={() => curItem?.clip && setPicker({ id: curItem.id })} + title={sections.length < 2 ? "the cut has one section" : "move the clip on screen to the start or end of a section"} + > + Move {curItem?.clip ? curItem.id : "this clip"} to… + </button> + </span> + ) : editable ? ( + <span data-strip-locked="">{editable}</span> + ) : null} + {busy && <span data-strip-busy="">moving…</span>} + {refusal && ( + <span role="alert" className="text-reject-text" data-strip-refusal=""> + {refusal}{" "} + <button type="button" className="ink-link" onClick={() => setRefusal(null)}> + dismiss + </button> + </span> + )} + </div> + {picker && ( + <div role="dialog" aria-label={`Move ${picker.id} to`} data-strip-picker={picker.id} className="mt-1 max-h-[40vh] overflow-auto rounded-[3px] border border-seam-2 bg-panel p-2 text-[12px]"> + <div className="mb-1 flex items-center gap-2"> + <span className="micro">Move {picker.id} to</span> + <button type="button" autoFocus className="ml-auto ink-link" onClick={() => setPicker(null)}> + close + </button> + </div> + <ul className="m-0 grid list-none gap-0.5 p-0 [grid-template-columns:repeat(auto-fill,minmax(260px,1fr))]"> + {sections.map((s) => ( + <li key={s.index} className="flex items-center gap-2" data-strip-picker-section={s.index}> + <span className="inline-block h-2.5 w-2.5 shrink-0 rounded-sm" style={{ background: s.color ?? "var(--muted)" }} /> + <span className="min-w-0 flex-1 truncate">{sectionName(sections, s.index)}</span> + {(["start", "end"] as const).map((pos) => ( + <button + key={pos} + type="button" + data-strip-picker-go={`${s.index}:${pos}`} + className="ink-link" + onClick={() => { + setPicker(null); + onEdit?.({ op: "section-move", ids: [picker.id], section: s.index, position: pos, words: `${picker.id} → the ${pos} of ${sectionName(sections, s.index)}` }); + }} + > + {pos} + </button> + ))} + </li> + ))} + </ul> + </div> + )} </section> ); } diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -17,6 +17,8 @@ import { dateKeyLabel } from "./playCut.mjs"; import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; import { readWorkingCut } from "./workingCut.mjs"; +import { sectionModel } from "./sectionEdit.mjs"; +import { manifestToken } from "./manifest.mjs"; const fin = (v) => typeof v === "number" && Number.isFinite(v); const text = (v) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim() : ""); @@ -140,9 +142,18 @@ export async function playView(project, { take = null, bare = false } = {}) { const markers = Array.isArray(render.chrome?.deck?.markers) ? render.chrome.deck.markers.filter((m) => m && typeof m.after === "string").map((m) => ({ after: m.after, label: typeof m.label === "string" ? m.label : "" })) : []; + // THE SECTIONS A DROP LANDS IN: the project's manifest's (what a reorder writes), each clip's + // section and each section's label and colour (sectionEdit.mjs sectionModel) -- as many as + // the markers make, no limit assumed here. + const model = sectionModel(base); + const sections = model.sections.map((x) => ({ index: x.index, label: x.label, color: x.color, marker: x.marker, count: x.clips.length })); return { project: project.id, title: text(manifest.title) || project.id, + sections, + sectionOf: Object.fromEntries(model.sectionOf), + // The manifest's token: a reorder written from a view older than the file is refused (409), not lost. + token: await manifestToken(project.dir), counter, markers, take: takeInfo, diff --git a/umtool/lib/report/stripDrag.mjs b/umtool/lib/report/stripDrag.mjs @@ -0,0 +1,165 @@ +// THE REEL STRIP'S DRAG AND ZOOM, as arithmetic (Play the cut, ReelStrip.tsx): +// where a dragged cell would land and in which section, which section labels +// fit at the zoom shown, how fast the strip pans at its edge while dragging, +// and when a zoomed strip follows the playhead. Pure: no DOM, no React, so it +// is unit-tested (stripDrag.test.mjs); the zoom itself is the bench's +// (benchZoom.mjs), on cut seconds instead of source seconds. +// +// Sections are the deck's markers (sectionEdit.mjs sectionModel), passed in +// as `sectionOf` (clip id -> section index) and `sections` ({index, label}); +// nothing here knows how many there may be. + +/** + * Each item's section: a clip's own, a card's that of the clip before it + * (else the one after), as sectionModel's entrySection stands a card. + * + * @param {Array<{ id: string, clip?: unknown }>} items + * @param {Record<string, number> | Map<string, number>} sectionOf + * @returns {number[]} + */ +export function itemSections(items, sectionOf) { + const get = (id) => (sectionOf instanceof Map ? sectionOf.get(id) : sectionOf?.[id]); + const out = items.map((it) => (it.clip ? get(it.id) : undefined)); + let last; + for (let i = 0; i < out.length; i += 1) { + if (out[i] !== undefined) last = out[i]; + else if (last !== undefined) out[i] = last; + } + let next; + for (let i = out.length - 1; i >= 0; i -= 1) { + if (items[i].clip && get(items[i].id) !== undefined) next = get(items[i].id); + else if (out[i] === undefined) out[i] = next ?? 0; + } + return out.map((s) => s ?? 0); +} + +/** "§3 Leaves it open" -- a section in the drop's words. */ +export const sectionName = (sections, k) => { + const s = (sections ?? []).find((x) => x.index === k); + return `§${k}${s?.label ? ` ${s.label}` : k === 0 ? " (the opening)" : ""}`; +}; + +/** + * Where a drag of `dragged` (ids) would land with the pointer at cut second + * `t`: next to the cell under the pointer -- its left half before it, its + * right half after it -- in that cell's section. So at a seam the two halves + * either side are the end of §k and the start of §k+1: the same slot, the + * section said. Null over the dragged cells themselves (nothing would move). + * + * `before` is the id the dragged entries land before (null: the end), what + * the place op takes; `at` the cut second of the insertion line; `refused` + * the words when the drop would leave a section with no clip. + * + * @param {Array<{ id: string, from: number, to: number, clip?: unknown }>} items + * @param {number[]} sectionsOfItems itemSections(items, …) + * @param {Array<{ index: number, label: string | null }>} sections + * @param {string[]} dragged + * @param {number} t + */ +export function dropSlot(items, sectionsOfItems, sections, dragged, t) { + if (!items.length) return null; + const moving = new Set(dragged); + let j = items.findIndex((it) => t >= it.from && t < it.to); + if (j < 0) j = t < items[0].from ? 0 : items.length - 1; + if (moving.has(items[j].id)) return null; + const it = items[j]; + const side = t < (it.from + it.to) / 2 ? "before" : "after"; + const section = sectionsOfItems[j]; + // The entry the dragged ones land before: this cell, or the next not being dragged. + let k = side === "before" ? j : j + 1; + while (k < items.length && moving.has(items[k].id)) k += 1; + const before = k < items.length ? items[k].id : null; + // Already there: the entry before the slot (skipping the dragged) is the last dragged one's + // predecessor, and the section is its own. + const draggedIdx = items.map((x, i) => (moving.has(x.id) ? i : -1)).filter((i) => i >= 0); + const firstDragged = draggedIdx[0] ?? -1; + let p = k - 1; + while (p >= 0 && moving.has(items[p].id)) p -= 1; + const prevId = p >= 0 ? items[p].id : null; + let q = firstDragged - 1; + while (q >= 0 && moving.has(items[q].id)) q -= 1; + const origPrev = q >= 0 ? items[q].id : null; + const sameSection = draggedIdx.every((i) => !items[i].clip || sectionsOfItems[i] === section); + const noop = firstDragged >= 0 && prevId === origPrev && sameSection && draggedIdx.every((i, n) => n === 0 || i === draggedIdx[n - 1] + 1); + // A section emptied: every clip of some section is being dragged out of it. + let refused = null; + const left = new Map(); + items.forEach((x, i) => { + if (!x.clip || moving.has(x.id)) return; + left.set(sectionsOfItems[i], (left.get(sectionsOfItems[i]) ?? 0) + 1); + }); + for (const i of draggedIdx) { + const s = sectionsOfItems[i]; + if (items[i].clip && s !== section && !left.get(s)) { + refused = `${sectionName(sections, s)} would have no clip left — remove its boundary first, or move another clip into it`; + break; + } + } + const at = side === "before" ? it.from : it.to; + const where = before ? `before ${before}` : "at the end"; + return { + over: it.id, + side, + before, + section, + at, + noop, + refused, + words: noop ? "already here" : `→ ${sectionName(sections, section)}, ${side === "after" ? `after ${it.id}` : where}`, + seam: side === "after" ? sectionsOfItems[j + 1] !== undefined && sectionsOfItems[j + 1] !== section : j > 0 && sectionsOfItems[j - 1] !== section, + prev: prevId, + }; +} + +/** + * Which labels fit, left to right: each `{x, w}` (px) is shown when it starts + * at least `gap` px after the last shown one ends. Returns the indexes shown. + * + * @param {Array<{ x: number, w: number }>} labels in x order + * @param {number} [gap] + */ +export function labelsThatFit(labels, gap = 6) { + const shown = []; + let end = -Infinity; + labels.forEach((l, i) => { + if (l.x >= end + gap) { + shown.push(i); + end = l.x + l.w; + } + }); + return shown; +} + +/** + * The pan speed while dragging near an edge, in widths of what is shown per + * second: 0 away from the edges, growing to `max` at (and past) the edge. + * + * @param {number} x the pointer, px from the strip's left + * @param {number} width the strip's width, px + * @param {{ edge?: number, max?: number }} [o] + */ +export function edgeSpeed(x, width, { edge = 48, max = 1.2 } = {}) { + if (!(width > 0)) return 0; + if (x < edge) return -max * Math.min(1, (edge - x) / edge); + if (x > width - edge) return max * Math.min(1, (x - (width - edge)) / edge); + return 0; +} + +/** + * A zoomed strip follows the playhead: once `t` leaves what is shown (or + * comes within `margin` of its right edge while playing), the view pages on + * so `t` sits a fifth of the way in. Null when it need not move. + * + * @param {{ from: number, to: number }} vis + * @param {{ from: number, to: number }} whole + * @param {number} t + * @param {{ margin?: number }} [o] fraction of the view + */ +export function followVis(vis, whole, t, { margin = 0.04 } = {}) { + const span = vis.to - vis.from; + if (!(span > 0) || span >= whole.to - whole.from - 1e-6) return null; + if (t >= vis.from && t <= vis.to - span * margin) return null; + let from = t - span * 0.2; + from = Math.max(whole.from, Math.min(whole.to - span, from)); + return { from, to: from + span }; +} diff --git a/umtool/lib/report/stripDrag.test.mjs b/umtool/lib/report/stripDrag.test.mjs @@ -0,0 +1,89 @@ +// The reel strip's drag and zoom arithmetic (stripDrag.mjs). +import assert from "node:assert/strict"; +import test from "node:test"; +import { dropSlot, edgeSpeed, followVis, itemSections, labelsThatFit, sectionName } from "./stripDrag.mjs"; +import { zoomAt, zoomTo } from "./benchZoom.mjs"; + +// a b | c d (k card) | e f, each 10 s. +const ids = ["a", "b", "c", "d", "k", "e", "f"]; +const items = ids.map((id, i) => ({ id, from: i * 10, to: i * 10 + 10, ...(id === "k" ? {} : { clip: {} }) })); +const sectionOf = { a: 0, b: 0, c: 1, d: 1, e: 2, f: 2 }; +const sections = [{ index: 0, label: null }, { index: 1, label: "Two" }, { index: 2, label: "Three" }]; +const secs = itemSections(items, sectionOf); + +test("itemSections: a card stands in the section of the clip before it", () => { + assert.deepEqual(secs, [0, 0, 1, 1, 1, 2, 2]); + assert.deepEqual(itemSections([{ id: "k" }, { id: "a", clip: {} }], { a: 3 }), [3, 3], "a card first takes the next clip's"); +}); + +test("dropSlot: the cell's halves; a seam's two sides are two sections of one slot", () => { + const d1 = dropSlot(items, secs, sections, ["a"], 52); // f? no: e is 50-60, left half + assert.equal(d1.over, "e"); + assert.equal(d1.side, "before"); + assert.equal(d1.before, "e"); + assert.equal(d1.section, 2); + assert.equal(d1.at, 50); + assert.equal(d1.words, "→ §2 Three, before e"); + // The right half of b (end of §0) and the left half of c (start of §1): both before c. + const end0 = dropSlot(items, secs, sections, ["f"], 18); + const start1 = dropSlot(items, secs, sections, ["f"], 21); + assert.equal(end0.before, "c"); + assert.equal(start1.before, "c"); + assert.equal(end0.section, 0); + assert.equal(start1.section, 1); + assert.equal(end0.words, "→ §0 (the opening), after b"); + assert.ok(end0.seam && start1.seam); + // Past the last cell: the end. + assert.equal(dropSlot(items, secs, sections, ["a"], 69).before, null); +}); + +test("dropSlot: over the dragged cell nothing; where it already is, a no-op", () => { + assert.equal(dropSlot(items, secs, sections, ["c"], 25), null); + const here = dropSlot(items, secs, sections, ["c"], 17); // right half of b: before c (skipping c itself)... after b, §0 + assert.equal(here.before, "d"); + assert.equal(here.noop, false, "§0 is not c's section: it would move into §0"); + const same = dropSlot(items, secs, sections, ["c"], 32); // left half of d: before d in §1, after b + assert.equal(same.noop, true); + assert.equal(same.words, "already here"); +}); + +test("dropSlot: dragging a section's only clip out of it is refused in words", () => { + const two = [items[0], items[1], items[2], items[5]]; + const s2 = itemSections(two, { a: 0, b: 0, c: 1, e: 2 }); + const r = dropSlot(two, s2, sections, ["c"], 5); + assert.equal(r.refused, "§1 Two would have no clip left — remove its boundary first, or move another clip into it"); + const ok = dropSlot(two, s2, sections, ["a"], 35); + assert.equal(ok.refused, null); +}); + +test("labelsThatFit: a label is shown when it clears the last one shown", () => { + assert.deepEqual(labelsThatFit([{ x: 0, w: 50 }, { x: 30, w: 40 }, { x: 60, w: 40 }, { x: 101, w: 10 }]), [0, 2]); + // 24 sections over 600 px with 80 px labels: one in four. + const many = Array.from({ length: 24 }, (_, i) => ({ x: i * 25, w: 80 })); + assert.deepEqual(labelsThatFit(many), [0, 4, 8, 12, 16, 20]); +}); + +test("edgeSpeed: zero in the middle, up to max at either edge", () => { + assert.equal(edgeSpeed(500, 1000), 0); + assert.equal(edgeSpeed(0, 1000), -1.2); + assert.equal(edgeSpeed(1000, 1000), 1.2); + assert.ok(edgeSpeed(980, 1000) > 0 && edgeSpeed(980, 1000) < 1.2); +}); + +test("followVis: a zoomed strip pages on when the playhead leaves it", () => { + const whole = { from: 0, to: 1680 }; + assert.equal(followVis(whole, whole, 900), null, "at fit nothing moves"); + const vis = { from: 100, to: 200 }; + assert.equal(followVis(vis, whole, 150), null); + assert.deepEqual(followVis(vis, whole, 199), { from: 179, to: 279 }); + assert.deepEqual(followVis(vis, whole, 1675), { from: 1580, to: 1680 }); +}); + +test("the bench's zoom on cut seconds: the pointer's second stays put, a clip fills the strip", () => { + const whole = { from: 0, to: 1680 }; + const v = zoomAt(null, whole, 420, 4); + assert.ok(Math.abs((420 - v.from) / (v.to - v.from) - 420 / 1680) < 1e-6); + const c = zoomTo({ from: 400, to: 412 }, whole); + assert.ok(c.from < 400 && c.to > 412 && c.to - c.from < 20); + assert.equal(sectionName(sections, 1), "§1 Two"); +});