Archilyzer · Source

archilyzer

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

commit 380d06cdc4db1594fd6fac1492aae476c48984a0
parent 718884c05c2ea59aa8637fd8d51233f619c30132
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 09:36:08 -0500

umtool: the workspace -- a report video's own address is one screen: top bar, live viewer, block strip, inspector (L7a)

/projects/<p> (no tab) opens components/projects/workspace/: WorkspaceTop (title, "Draft · from vN · N edits",
Versions ▾ with Play / Open in draft / Save version, Edit · Review pass · Present ⛶, Look Basic|Deck, Render ▾,
Share, Undo / Redo, Piece ▾), the viewer (playCore's PlayStage: the draft live, the intro included), BlockStrip
(intro, clips, posts, cards, +; select, ← →, Alt+← → and drag move through the timeline's `move`), and the
inspector chosen by the block: a clip's bench work column (ClipBench layout "inspector"), a post's L6 panel and
PostBench (layout "inspector", its data from the new GET /api/report/post-bench, shared with its page through
lib/report/postBenchData.ts), a card's teaser panel, the intro editor, else the project's panels. CutApp grows a
`home`: E opens the clip bench in place over the workspace, Back returns. The piece page's tabs stay at ?tab=
(projectHref writes `tab=overview` now; kinds.mjs opensWorkspace); a claimed project's own address is its
workspace too. Writes from the bench, the post bench and the intro editor announce MANIFEST_CHANGED.

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

Diffstat:
Aumtool/app/api/report/post-bench/route.ts | 20++++++++++++++++++++
Mumtool/app/projects/[...path]/page.tsx | 5++++-
Mumtool/components/projects/ClipBench.tsx | 1879+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Mumtool/components/projects/PostBench.tsx | 35++++++++++++++++++++++++++++-------
Mumtool/components/projects/PostBenchPage.tsx | 49++++++++++++-------------------------------------
Mumtool/components/projects/ProjectView.tsx | 5++++-
Mumtool/components/projects/cutApp/CutApp.tsx | 39+++++++++++++++++++++++++++++----------
Mumtool/components/projects/report/IntroEditor.tsx | 3+++
Aumtool/components/projects/workspace/BlockStrip.tsx | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/workspace/Workspace.tsx | 508+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/workspace/WorkspaceInspector.tsx | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/workspace/WorkspacePage.tsx | 33+++++++++++++++++++++++++++++++++
Aumtool/components/projects/workspace/WorkspaceTop.tsx | 311+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/hrefs.test.mjs | 6++++--
Mumtool/lib/hrefs.ts | 16+++++++++++++---
Mumtool/lib/projects/kinds.mjs | 12++++++++++++
Aumtool/lib/report/postBenchData.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 2369 insertions(+), 976 deletions(-)

diff --git a/umtool/app/api/report/post-bench/route.ts b/umtool/app/api/report/post-bench/route.ts @@ -0,0 +1,20 @@ +import { projectRef } from "@/lib/projects"; +import { postBenchData } from "@/lib/report/postBenchData"; + +export const dynamic = "force-dynamic"; + +// THE POST BENCH'S DATA as JSON, for the workspace's inspector (components/projects/workspace/): one post +// item of the draft as PostBench draws it. +// GET ?project=<id>&id=<post item id> +// +// The same function the bench's own page renders from (lib/report/postBenchData.ts), so the inspector and +// the page cannot disagree. An id that is not a post item of the cut is a 404, as the page's. +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const project = await projectRef(q.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const id = q.get("id") ?? ""; + const r = await postBenchData(project.dir, id); + if (!r) return Response.json({ error: `${id} is not a post item of the cut` }, { status: 404 }); + return Response.json(r, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/app/projects/[...path]/page.tsx b/umtool/app/projects/[...path]/page.tsx @@ -5,6 +5,7 @@ import ProjectView from "@/components/projects/ProjectView"; import ProjectGrid from "@/components/projects/ProjectGrid"; import { listProjects, resolveProjectPath } from "@/lib/projects"; import { claimedProjectRedirect } from "@/lib/pieces/article"; +import { opensWorkspace } from "@/lib/projects/kinds.mjs"; export const dynamic = "force-dynamic"; @@ -38,7 +39,9 @@ export default async function BrowsePathPage({ // A project an article claims IS that article's piece (P4a-2): its own // address lands there, on the same tab. The benches and kind views // (`clip/<id>`, `claim/<id>`, `review`, `narration`, `takes`) stay here. - if (resolved.rest.length === 0) { + // A report video's own address is its WORKSPACE (L7a), claimed or not: the article's piece page keeps its + // tabs (`?tab=`, a `note`), and the workspace is the video's one screen. + if (resolved.rest.length === 0 && !opensWorkspace(resolved.project.kind, search)) { const to = await claimedProjectRedirect(resolved.project, search); if (to) redirect(to); } diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -6,6 +6,7 @@ import { rejectionOf } from "@/lib/report/rejectReasons.mjs"; import AnchoredNotes, { notesOn } from "@/components/notes/AnchoredNotes"; import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { useSharedNotes, wroteNotes } from "@/components/notes/NotesProvider"; +import { announceManifestChanged } from "./timelineApi"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { LatestLine, type WorkingCut } from "./review/WhatPlays"; import { createPortal } from "react-dom"; @@ -543,9 +544,16 @@ type WindowPatch = { export default function ClipBench({ data, navigate, + layout = "bench", }: { data: ClipBenchData; /** + * `inspector`: the workspace's inspector (umtool redesign L7a) -- the work column alone (the window row, the + * instrument with its handles and gaps, the cue rail), no verdict bar, reader or answer, no walk keys; its own + * keys only while the focus is in it. Every save writes the draft, as the bench's. + */ + layout?: "bench" | "inspector"; + /** * Inside Play (components/projects/cutApp/CutApp.tsx): every move this bench makes -- p / n, * Confirm's advance, Back to the cut -- goes through here, so Play stays mounted and the * history is the app's. Absent, Next's router. @@ -555,6 +563,8 @@ export default function ClipBench({ // The project's notes: this clip's row notes, and the edit notes a save on a // generated manifest leaves (the save says so, and they are re-read). const notes = useSharedNotes({ project: data.project }); + const inspector = layout === "inspector"; + const inspectorRef = useRef<HTMLDivElement | null>(null); // Walking a take: every route is asked about the TAKE's clip, and every // save lands in the take's patch (see ClipBenchData.take). const takeId = data.take?.id ?? null; @@ -968,7 +978,7 @@ export default function ClipBench({ // racing it: a play() before `canplay` on a file being range-fetched is a // silent no-op, which reads as "the option does not work". useEffect(() => { - if (!playback.auto || !cached) return; + if (!playback.auto || !cached || inspector) return; const el = video.current; if (!el || autoPlayed.current === clip.id) return; const go = () => { @@ -991,7 +1001,7 @@ export default function ClipBench({ el.removeEventListener("loadedmetadata", go); el.removeEventListener("canplay", go); }; - }, [playback.auto, cached, clip.id, clip.start, clip.end, play]); + }, [playback.auto, cached, clip.id, clip.start, clip.end, play, inspector]); // ---- the selection ------------------------------------------------------ // @@ -1090,6 +1100,8 @@ export default function ClipBench({ })); } token.current = String(j.token ?? ""); + // The draft moved: whatever else on the page holds it (the workspace's viewer and strip) reads it again. + announceManifestChanged(data.project); setNote( followed?.cite ? `saved — the cite followed the edge: ${hms(followed.cite.from)} → ${hms(followed.cite.to)}${followed.citeUrl ? ", and the QR with it" : ""}` @@ -1296,6 +1308,8 @@ export default function ClipBench({ setMute(next.muteFrom); muteRef.current = next.muteFrom; token.current = String(j.token ?? ""); + // The draft moved: whatever else on the page holds it (the workspace's viewer and strip) reads it again. + announceManifestChanged(data.project); setNote("undone — not yet reviewed"); return; } @@ -1585,6 +1599,10 @@ export default function ClipBench({ const onKey = (e: KeyboardEvent) => { const el = e.target as HTMLElement | null; if (el && /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)) return; + // In the workspace's inspector the keys are the bench's only while the focus is in it, and the walk's + // (n / p, y, x, s) are not offered: the workspace walks the blocks. + if (inspector && !(el && inspectorRef.current?.contains(el))) return; + if (inspector && e.key.length === 1 && "nNpPyYxXsS".includes(e.key)) return; const step = e.shiftKey ? 0.5 : 0.05; // The zoom's and the gaps' keys leave the browser's own (Ctrl+F, Ctrl+Z …) alone. if ((e.ctrlKey || e.metaKey || e.altKey) && "zZfFgG".includes(e.key)) return; @@ -1740,6 +1758,7 @@ export default function ClipBench({ gap.pick, gap.cut, gap.removeAt, + inspector, ]); const refresh = useCallback(async (): Promise<ClipBenchData | null> => { @@ -1972,6 +1991,8 @@ export default function ClipBench({ // button writes only the cut, and an unsaved edge drag keeps its handles). if (!dirty) setSel(spanIn(cutNext, modeRef.current)); token.current = String(j.token ?? ""); + // The draft moved: whatever else on the page holds it (the workspace's viewer and strip) reads it again. + announceManifestChanged(data.project); if (wroteNotes(j)) void notes.reload(); setCutScore(j.score ?? null); setNote(`cut to the quote (match ${(j.score ?? 0).toFixed(2)})`); @@ -2941,964 +2962,992 @@ export default function ClipBench({ ) : null; - return ( - // ONE SCREEN, at a desk. - // - // Walking a cut is sixty clips in a row. A bench that scrolls puts the - // attribution fields -- the point of the walk -- below the fold on every - // one of them, and the answer to "did I check that" becomes a scroll - // position. So from lg up the bench owns exactly the space the page has - // left: the grid is the viewport minus the chrome, nothing outside a column - // scrolls, and what does not earn its height is folded rather than cut. - // Below lg it is a single scrolling column -- a phone cannot hold this and - // pretending otherwise would cost the desk case something. - <BenchBody verdict={verdictBar} reader={readerPane} workClassName="lg:overflow-hidden" phoneFlat> - <div - data-bench={clip.id} - data-verdict={verdict} - className="flex flex-col gap-2 lg:h-full lg:min-h-0 lg:overflow-hidden max-md:contents" - > - {/* On a phone the banner is one muted line under Notes (phoneNotesHead). - The wrapper only when there is a banner: an empty one would be a - flex item, and a gap, on the desk. */} - {data.generatedBy && !data.take && ( - <div className="max-md:hidden"> - <GeneratedBanner generatedBy={data.generatedBy} /> + // THE WORK COLUMN: the picture and everything that moves its edges -- the window row, the instrument + // (the waveform, its handles, the gaps), the cue rail. The bench draws it beside the claim and the + // answer; the workspace's inspector (layout "inspector", umtool redesign L7a) draws it alone. + const workColumn = ( + <div className="flex min-h-0 flex-col gap-2 lg:overflow-y-auto max-md:contents"> + {/* ---- the pin (a phone): the place bar over the picture ---- + On the desk this wrapper and the row inside it are `contents`: + the <video> is the column's flex item exactly as before. */} + <div + ref={pinRef} + data-walk-pin="" + data-compact={compact ? "" : undefined} + data-bar={barHidden ? "hidden" : "shown"} + className="md:contents max-md:sticky max-md:top-0 max-md:z-30 max-md:order-[10] max-md:-mx-4 max-md:bg-ground max-md:transition-transform max-md:duration-200" + style={ + isPhone + ? { + transform: barHidden ? `translateY(-${BAR_H}px)` : undefined, + // The strip keeps the full picture's footprint, so the page + // under it does not jump when it shrinks. + marginBottom: compact ? `calc(100vw * 9 / 16 - ${STRIP_H}px)` : undefined, + } + : undefined + } + > + {placeBar} + <div className="flex md:contents"> + {cached ? ( + <video + ref={video} + data-testid="clip-video" + src={media.src ?? undefined} + // object-contain, because the height is now whatever is left + // rather than whatever 16:9 asks for. + // The picture and the words SHARE what is left, 3:2, rather + // than either taking a fixed number of pixels: a laptop and a + // 1080p screen have very different amounts to give away, and a + // 130px player is not a player. + className={cn( + "aspect-video w-full rounded border border-[var(--color-line)] bg-black object-contain lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]", + // The workspace's viewer is the picture: the inspector keeps the element (the bench plays through it), unseen. + inspector && "hidden", + )} + preload="metadata" + controls + /> + ) : ( + <div data-walk-pin-empty="" className={cn("flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[12px] text-[var(--color-dim)] lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]", inspector && "aspect-auto py-3 lg:aspect-auto lg:min-h-0")}> + nothing fetched for this clip yet </div> )} - {/* A take's clip is never benched from the UI now (L3: Open in draft first); `umtool window --take` edits one. */} - {/* ---- where you are, where you can go, and what will be burned in ---- */} - <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] max-md:contents"> - {/* On a phone both counts are the place bar's `50/51` and its hairline. */} - <span className="micro max-md:hidden" data-review-progress=""> - {reviewed} reviewed - </span> - {/* What the WALK has left, which is not the same number: a clip nobody - has fetched still needs judgement and cannot get it today. */} - <span className="micro max-md:hidden" data-ready-count=""> - ready {data.ready} of {data.needing} needing judgement + {stripSide} + </div> + </div> + {phoneMiddle} + + {phoneSecHead("window", "max-md:order-[50]", "Window, cut, mute and speed", `${hms(sel.from)} – ${hms(sel.to)}`)} + {/* ---- the window, and everything that moves it, in one row ---- */} + <div data-walk-in="window" className={cn("flex flex-wrap items-center gap-x-3 gap-y-1.5 text-[12px]", secBody("window", "max-md:order-[51]"))}> + <span className="num text-[var(--color-meter)]"> + {hms(sel.from)} – {hms(sel.to)}{" "} + <span className="text-[var(--color-dim)]">({(sel.to - sel.from).toFixed(2)}s)</span> </span> - {/* The working cut's name: what this bench edits, and the latest take it was made into. */} - {data.working && !data.take && <LatestLine project={data.project} working={data.working} className="max-md:hidden" />} - {!data.fetched && ( - <span className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")} data-clip-unfetched=""> - not fetched yet + {dirty && ( + <span className="num text-[var(--color-dirty)]"> + unsaved — was {hms(savedSpan.from)} – {hms(savedSpan.to)} </span> )} - {/* A deliberate repeat (`repeatOf`): its overlap with that clip is the point. */} - {clip.repeatOf && ( + {muteMoved && ( + <span data-mute-unsaved="" className="num text-[var(--color-dirty)]"> + mute mark unsaved — was {clip.muteFrom == null ? "none" : hms(clip.muteFrom)} + </span> + )} + <span className="flex flex-wrap items-center gap-1.5"> + <button + type="button" + data-save-window="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!unsaved || !!busy} + onClick={saveWindow} + > + Save window + </button> + {windowUndo && !unsaved && ( + <button + type="button" + data-window-undo="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!!busy} + title={`undo: ${windowUndo.what}`} + onClick={() => void undoWindow()} + > + Undo save + </button> + )} + <button + type="button" + data-play-selection="" + className={buttonVariants({ size: "sm" })} + onClick={() => void play(sel.from, sel.to)} + > + Play selection + </button> + <button + type="button" + className={buttonVariants({ size: "sm" })} + data-reset="" + disabled={!unsaved && !extendedFrom} + title={!unsaved && extendedFrom ? `undo the extension: back to ${hms(extendedFrom.start)} – ${hms(extendedFrom.end)}` : undefined} + onClick={() => resetRef.current()} + > + Reset + </button> + {data.mixHref && ( + // Built SERVER-SIDE, because a mix link carries an absolute path + // and this component has no business constructing one. It also + // carries the SAVED window rather than the current selection: a + // mix of an unsaved edit is a mix of something not in the cut. + <Link + href={data.mixHref} + data-mix-link={clip.id} + className={buttonVariants({ size: "sm" })} + > + mix + </Link> + )} + </span> + {/* ---- how you listen ---- + Per browser, not per cut: `localStorage`, defaults on the + server, and nothing here reaches the manifest. */} + <span className="flex items-center gap-1.5"> + <span className="micro">speed</span> + <select + data-playback-rate="" + aria-label="playback speed" + value={playback.rate} + onChange={(e) => + choosePlayback((pb) => ({ ...pb, rate: Number(e.target.value) })) + } + className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-1 py-0.5 text-[11px]" + > + {RATES.map((r) => ( + <option key={r} value={r}> + {r}× + </option> + ))} + </select> + <button + type="button" + data-auto-audition={playback.auto ? "on" : "off"} + aria-pressed={playback.auto} + className={buttonVariants({ + variant: "outline", + size: "sm", + })} + onClick={() => choosePlayback((pb) => ({ ...pb, auto: !pb.auto }))} + > + Auto-audition {playback.auto ? "on" : "off"} + </button> + {/* What is playing, and what it measured. The attributes are the + bench's record of its last playback, on the audio clock -- + the claim is "stops where the selection ends", and this is + where it can be checked. */} <span - data-bench-repeat-of={clip.repeatOf} - title={`re-plays ${clip.repeatOf} on purpose (a callback, a flash-forward): their overlap is neither flagged nor trimmed`} - className={cn(badgeVariants({ variant: "info", size: "sm" }), "max-md:order-[21] max-md:self-start")} + data-playback="" + data-audio-state={audio.state} + data-play-engine={playInfo?.engine ?? ""} + data-play-state={playInfo?.state ?? ""} + data-play-from={playInfo?.from ?? ""} + data-play-to={playInfo?.to ?? ""} + data-play-rate={playInfo?.rate ?? ""} + data-play-stretched={playInfo ? String(playInfo.stretched) : ""} + data-play-ctx-start={playInfo?.ctxStart ?? ""} + data-play-ctx-stop={playInfo?.ctxStop ?? ""} + data-play-ended-at={playInfo?.endedAt ?? ""} + className="micro" + title={ + audio.state === "failed" + ? undefined + : "every bounded playback is the decoded audio, started and stopped on the audio clock: it ends where the selection ends, to the sample" + } > - repeats {clip.repeatOf} + {audio.state === "ready" + ? "exact playback" + : audio.state === "loading" + ? "decoding the audio…" + : null} </span> - )} - {clip.star && ( - <span data-bench-star="" title="starred on the walk: a trailer candidate" className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")}> - ★ trailer + </span> + {audio.state === "failed" && ( + <span data-playback-fallback="" className="text-[11px] text-[var(--color-dirty)]"> + exact playback unavailable — {audio.why}. The video plays instead, stopped by the + frame: up to half a frame either side of the end. </span> )} - {/* The renderer's own line, live. It used to sit four hundred pixels - down the page; it is the one string this bench exists to get right, - so it heads the screen. */} - <span - data-attrib-preview="" - title={previewLine} - className={cn( - "num ml-auto min-w-0 max-w-full truncate rounded bg-[var(--color-panel-2)] px-2 py-0.5 text-[12px] text-[var(--color-meter)]", - secBody("attribution", "max-md:order-[81] max-md:ml-0 max-md:whitespace-normal"), + {/* ---- EXTENT above, CUT here ---- + The window row says how much of the recording is worth having. + This says what will actually play, and offers to derive it + from the quote -- which is the whole reason the two are + different numbers. */} + <span data-cut={clip.cutStart != null ? `${clip.cutStart}-${clip.cutEnd}` : ""} className="flex flex-wrap items-center gap-1.5"> + {clip.cutStart != null && clip.cutEnd != null ? ( + <span className="num text-[var(--color-good)]"> + cut {hms(clip.cutStart)}–{hms(clip.cutEnd)}{" "} + <span className="text-[var(--color-dim)]"> + ({(clip.cutEnd - clip.cutStart).toFixed(2)}s + {cutScore != null ? `, quote match ${cutScore.toFixed(2)}` : ""} + ) + </span> + </span> + ) : ( + <span className="text-[var(--color-dim)]"> + no cut — the whole window plays + </span> + )} + <button + type="button" + data-cut-to-quote="" + className={buttonVariants({ size: "sm" })} + disabled={!!busy || !draft.quote.trim()} + title={ + draft.quote.trim() + ? "find the quote in the transcript and cut to it, inside this window" + : "there is no quote to match against" + } + onClick={() => void cutToQuote()} + > + Cut to quote + </button> + {clip.cutStart != null && ( + <button + type="button" + data-cut-clear="" + className={buttonVariants({ size: "sm" })} + disabled={!!busy} + onClick={takeWholeClip} + > + Clear cut + </button> + )} + {cutUndo && ( + <button + type="button" + data-cut-undo="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!!busy} + title={`undo: ${cutUndo.what}`} + onClick={() => void undoCut()} + > + Undo cut + </button> )} + </span> + {/* ---- the MUTE MARK ---- + Beside the cut because it is the same kind of decision -- what + the finished clip does with its seconds -- and drafted like the + edges: heard at once, written by `save window` or `y`. */} + <span + data-mute={mute ?? ""} + className="flex flex-wrap items-center gap-1.5" + title="From the mark to the end of the clip the sound fades out and the picture plays on. Set it at the last silence before the ending sound." > - {previewLine} + {mute != null ? ( + <span data-mute-from={mute} className="num text-[var(--color-text)]"> + mute from {hms(mute)}{" "} + <span className="text-[var(--color-dim)]"> + ({Math.max(0, sel.to - mute).toFixed(2)}s silent to the end) + </span> + </span> + ) : ( + <span className="text-[var(--color-dim)]">sound to the end</span> + )} + <button + type="button" + data-mute-set="" + className={buttonVariants({ size: "sm" })} + title="put the mute mark at the playhead" + onClick={muteAtPlayhead} + > + Mute from here + </button> + <button + type="button" + data-mute-pick={mutePick ? "armed" : ""} + aria-pressed={mutePick} + className={`${buttonVariants({ variant: "outline", size: "sm" })}${mutePick ? " bg-panel-2 border-muted" : ""}`} + title="the next click on the waveform places the mute mark (Esc cancels)" + onClick={() => setMutePick((v) => !v)} + > + {mutePick ? "Click the waveform…" : "Pick on waveform"} + </button> + {mute != null && ( + <button + type="button" + data-mute-clear="" + className={buttonVariants({ size: "sm" })} + onClick={clearMute} + > + Clear mute + </button> + )} </span> + <span className="micro max-md:hidden"> + <kbd>[</kbd> <kbd>]</kbd> start · <kbd>,</kbd> <kbd>.</kbd> end — each plays the edge + it moved · <kbd>space</kbd> the whole selection · <kbd>R</kbd> reset · <kbd>-</kbd>{" "} + <kbd>=</kbd> speed · <kbd>a</kbd> auto · <kbd>m</kbd> mute from the playhead,{" "} + <kbd>;</kbd> <kbd>&apos;</kbd> move it, <kbd>M</kbd> clear — shift for 0.5s + </span> + {busy && <span className="text-[var(--color-meter)]">{busy}</span>} + {note && ( + <span data-bench-note="" className="text-[var(--color-dirty)]"> + {note} + </span> + )} + {fixBox("bench")} </div> - <div className="grid min-h-0 flex-1 gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,23rem)] max-md:contents"> - {/* ================= the picture, and its edges ================= */} - {/* Since P4b the words are the bench's reader pane: this column is the - picture and everything that moves its edges, and it scrolls on its - own before the picture shrinks below a usable height. */} - <div className="flex min-h-0 flex-col gap-2 lg:overflow-y-auto max-md:contents"> - {/* ---- the pin (a phone): the place bar over the picture ---- - On the desk this wrapper and the row inside it are `contents`: - the <video> is the column's flex item exactly as before. */} - <div - ref={pinRef} - data-walk-pin="" - data-compact={compact ? "" : undefined} - data-bar={barHidden ? "hidden" : "shown"} - className="md:contents max-md:sticky max-md:top-0 max-md:z-30 max-md:order-[10] max-md:-mx-4 max-md:bg-ground max-md:transition-transform max-md:duration-200" - style={ - isPhone - ? { - transform: barHidden ? `translateY(-${BAR_H}px)` : undefined, - // The strip keeps the full picture's footprint, so the page - // under it does not jump when it shrinks. - marginBottom: compact ? `calc(100vw * 9 / 16 - ${STRIP_H}px)` : undefined, - } - : undefined - } + {/* ---- the instrument ---- + On a phone the edge strip is the instrument; this one is still + there, folded under Window, for the mute mark. */} + <div data-bench-sel={`${sel.from.toFixed(2)}-${sel.to.toFixed(2)}`} className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}> + {/* ---- the MODE: what the handles edit ---- + Cut (what plays; gaps live here) or Clip (the seconds reviewed), + and the line that reads the two in the mode's terms. */} + <div data-bench-mode={mode} className="flex flex-wrap items-center gap-2 text-[12px]"> + <span role="group" aria-label="what the handles edit" className="inline-flex overflow-hidden rounded border border-[var(--color-line)]"> + {(["cut", "clip"] as const).map((m) => ( + <button + key={m} + type="button" + data-bench-mode-set={m} + aria-pressed={mode === m} + disabled={!!busy || (dirty && mode !== m)} + title={ + dirty && mode !== m + ? `save or reset the ${editsCut ? "cut" : "window"} you moved first` + : m === "cut" + ? "the handles are what plays; gaps are cut here" + : "the handles are the seconds reviewed; what plays is the band inside" + } + onClick={() => setMode(m)} + className={ + mode === m + ? "bg-[var(--color-panel-2)] px-2.5 py-0.5 font-semibold text-[var(--color-text)] disabled:opacity-60" + : "px-2.5 py-0.5 text-[var(--color-dim)] hover:text-[var(--color-text)] disabled:opacity-50" + } + > + {m === "cut" ? "Cut" : "Clip"} + </button> + ))} + </span> + <span data-bench-plays={`${(after.cutStart ?? after.start).toFixed(2)}-${(after.cutEnd ?? after.end).toFixed(2)}`} className="num text-[var(--color-text)]"> + {mode === "cut" ? ( + <> + Plays {hms(after.cutStart ?? after.start)}–{hms(after.cutEnd ?? after.end)} + <span className="text-[var(--color-dim)]"> + {" "}· reviewed {hms(after.start)}–{hms(after.end)} + </span> + </> + ) : ( + <> + Reviewed {hms(after.start)}–{hms(after.end)} + <span className="text-[var(--color-dim)]"> + {" "}· plays {hms(after.cutStart ?? after.start)}–{hms(after.cutEnd ?? after.end)} + {after.cutStart != null ? " (edit it in Cut)" : ""} + </span> + </> + )} + </span> + {/* A cut narrower than what was reviewed: the rest back in one press. */} + {cutNarrower && !dirty && ( + <button + type="button" + data-cut-use-whole="" + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!!busy} + title="play everything reviewed: the cut is cleared, and gaps can go anywhere in the clip (Undo cut puts it back)" + onClick={takeWholeClip} > - {placeBar} - <div className="flex md:contents"> - {cached ? ( - <video - ref={video} - data-testid="clip-video" - src={media.src ?? undefined} - // object-contain, because the height is now whatever is left - // rather than whatever 16:9 asks for. - // The picture and the words SHARE what is left, 3:2, rather - // than either taking a fixed number of pixels: a laptop and a - // 1080p screen have very different amounts to give away, and a - // 130px player is not a player. - className="aspect-video w-full rounded border border-[var(--color-line)] bg-black object-contain lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]" - preload="metadata" - controls + Use the whole clip + </button> + )} + </div> + {/* Zoomed: round ticks over what is shown. */} + {zoom.zoomed && <ZoomRuler vis={zoom.vis} />} + <BenchWaveBox + zoom={zoom} + sel={sel} + cand={savedSpan} + cues={cues} + peaks={peaks} + playhead={playhead} + onSel={onSel} + gap={gap} + gaps={clip.gaps ?? []} + silences={renderEdges?.silences ?? null} + words={nearWords?.words ?? null} + busy={!!busy} + held={mutePick || mode === "clip"} + walls={mode === "cut" ? walls : null} + > + {/* The mute mark over the waveform: a line where the sound stops + and a hatch over what is silent to the end of the selection. + In the interaction colour, like the handles -- it is an edit, + not a reading -- and never in the way of a drag. */} + {mute != null && mute >= zoom.vis.from && mute <= zoom.vis.to && ( + <> + <div + data-mute-span="" + className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-dim)_22%,transparent)_0_3px,transparent_3px_7px)]" + style={{ + left: zpct(mute), + width: `calc(${zpct(Math.max(mute, Math.min(sel.to, zoom.vis.to)))} - ${zpct(mute)})`, + }} /> - ) : ( - <div data-walk-pin-empty="" className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] text-[12px] text-[var(--color-dim)] lg:aspect-auto lg:min-h-[200px] lg:flex-[3_1_0%]"> - nothing fetched for this clip yet + <div + data-mute-marker={mute} + className="pointer-events-none absolute top-0 h-full border-l-2 border-dashed border-[var(--color-sel)]" + style={{ left: zpct(mute) }} + > + <span className="absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-sel)]"> + mute + </span> </div> - )} - {stripSide} - </div> - </div> - {phoneMiddle} + </> + )} + {/* Clip mode: the cut as a band inside the extent (bench/CutEdges.tsx), passive. */} + {mode === "clip" && after.cutStart != null && after.cutEnd != null && ( + <CutEdges vis={zoom.vis} cut={{ from: after.cutStart, to: after.cutEnd }} extent={sel} busy={!!busy} fmt={hms} /> + )} + {/* Where the render will actually cut: each edge snapped to its silence, faint. */} + <RenderGhosts edges={renderEdges} view={zoom.vis} /> + {/* Armed: the next click places the mark rather than an edge. */} + {mutePick && ( + <div + data-mute-pick-layer="" + className="absolute inset-0 z-[8] cursor-crosshair rounded-md outline outline-1 outline-[var(--color-sel)]" + onPointerDown={(e) => { + const r = e.currentTarget.getBoundingClientRect(); + const frac = Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))); + placeMute(zoom.vis.from + frac * zspan, true); + }} + /> + )} + </BenchWaveBox> + {/* Zoomed: the whole cached window, what is shown of it -- drag to pan. */} + {zoom.zoomed && <ZoomOverview zoom={zoom} whole={view} peaks={peaks} sel={sel} gaps={clip.gaps ?? []} />} + {/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */} + <div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> + {/* ---- GAPS inside the clip (bench/BenchWave.tsx GapTools) ---- */} + {mode === "cut" ? ( + <GapTools gap={gap} gaps={clip.gaps ?? []} span={gapsSpan} sel={sel} busy={!!busy} fmt={hms} play={play} /> + ) : ( + <span data-gaps-clip-mode="" className="text-[var(--color-dim)]"> + {(clip.gaps ?? []).length ? `${(clip.gaps ?? []).length} gap${(clip.gaps ?? []).length === 1 ? "" : "s"} — ` : ""}gaps are cut in Cut mode + </span> + )} + <TightenButtons tools={edgeTools} busy={!!busy} /> + <span className="micro max-md:hidden"> + <kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "} + <kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead + </span> + <ZoomControls zoom={zoom} whole={view} selection={gap.sel ?? sel} playhead={playhead} /> + </div> + </div> - {phoneSecHead("window", "max-md:order-[50]", "Window, cut, mute and speed", `${hms(sel.from)} – ${hms(sel.to)}`)} - {/* ---- the window, and everything that moves it, in one row ---- */} - <div data-walk-in="window" className={cn("flex flex-wrap items-center gap-x-3 gap-y-1.5 text-[12px]", secBody("window", "max-md:order-[51]"))}> - <span className="num text-[var(--color-meter)]"> - {hms(sel.from)} – {hms(sel.to)}{" "} - <span className="text-[var(--color-dim)]">({(sel.to - sel.from).toFixed(2)}s)</span> + {/* Offered at the edge of the cache, as always -- and also whenever + the rail has something to read past it. Having just read the next + sentence is exactly when you want the seconds it is in, and + dragging to the edge first to be allowed to ask is a ritual. */} + {(atStartEdge || atEndEdge || peekOutside) && ( + <div data-walk-in="window" className={cn("flex flex-wrap items-center gap-2 text-[12px]", secBody("window", "max-md:order-[53]"))}> + {atStartEdge || atEndEdge ? ( + <span className="text-[var(--color-dirty)]"> + that is the edge of what is cached{cached ? ` (${cached.name})` : ""} </span> - {dirty && ( - <span className="num text-[var(--color-dirty)]"> - unsaved — was {hms(savedSpan.from)} – {hms(savedSpan.to)} - </span> - )} - {muteMoved && ( - <span data-mute-unsaved="" className="num text-[var(--color-dirty)]"> - mute mark unsaved — was {clip.muteFrom == null ? "none" : hms(clip.muteFrom)} - </span> - )} - <span className="flex flex-wrap items-center gap-1.5"> - <button - type="button" - data-save-window="" - className={buttonVariants({ variant: "outline", size: "sm" })} - disabled={!unsaved || !!busy} - onClick={saveWindow} - > - Save window - </button> - {windowUndo && !unsaved && ( - <button - type="button" - data-window-undo="" - className={buttonVariants({ variant: "outline", size: "sm" })} - disabled={!!busy} - title={`undo: ${windowUndo.what}`} - onClick={() => void undoWindow()} - > - Undo save - </button> - )} - <button - type="button" - data-play-selection="" - className={buttonVariants({ size: "sm" })} - onClick={() => void play(sel.from, sel.to)} - > - Play selection - </button> - <button - type="button" - className={buttonVariants({ size: "sm" })} - data-reset="" - disabled={!unsaved && !extendedFrom} - title={!unsaved && extendedFrom ? `undo the extension: back to ${hms(extendedFrom.start)} – ${hms(extendedFrom.end)}` : undefined} - onClick={() => resetRef.current()} - > - Reset - </button> - {data.mixHref && ( - // Built SERVER-SIDE, because a mix link carries an absolute path - // and this component has no business constructing one. It also - // carries the SAVED window rather than the current selection: a - // mix of an unsaved edit is a mix of something not in the cut. - <Link - href={data.mixHref} - data-mix-link={clip.id} - className={buttonVariants({ size: "sm" })} - > - mix - </Link> - )} + ) : ( + <span className="text-[var(--color-dim)]"> + cached to −{Math.floor(reachBefore)} s / +{Math.floor(reachAfter)} s around this + clip </span> - {/* ---- how you listen ---- - Per browser, not per cut: `localStorage`, defaults on the - server, and nothing here reaches the manifest. */} - <span className="flex items-center gap-1.5"> - <span className="micro">speed</span> - <select - data-playback-rate="" - aria-label="playback speed" - value={playback.rate} - onChange={(e) => - choosePlayback((pb) => ({ ...pb, rate: Number(e.target.value) })) - } - className="rounded border border-[var(--color-line)] bg-[var(--color-panel-2)] px-1 py-0.5 text-[11px]" - > - {RATES.map((r) => ( - <option key={r} value={r}> - {r}× - </option> - ))} - </select> - <button - type="button" - data-auto-audition={playback.auto ? "on" : "off"} - aria-pressed={playback.auto} - className={buttonVariants({ - variant: "outline", - size: "sm", - })} - onClick={() => choosePlayback((pb) => ({ ...pb, auto: !pb.auto }))} - > - Auto-audition {playback.auto ? "on" : "off"} - </button> - {/* What is playing, and what it measured. The attributes are the - bench's record of its last playback, on the audio clock -- - the claim is "stops where the selection ends", and this is - where it can be checked. */} - <span - data-playback="" - data-audio-state={audio.state} - data-play-engine={playInfo?.engine ?? ""} - data-play-state={playInfo?.state ?? ""} - data-play-from={playInfo?.from ?? ""} - data-play-to={playInfo?.to ?? ""} - data-play-rate={playInfo?.rate ?? ""} - data-play-stretched={playInfo ? String(playInfo.stretched) : ""} - data-play-ctx-start={playInfo?.ctxStart ?? ""} - data-play-ctx-stop={playInfo?.ctxStop ?? ""} - data-play-ended-at={playInfo?.endedAt ?? ""} - className="micro" - title={ - audio.state === "failed" - ? undefined - : "every bounded playback is the decoded audio, started and stopped on the audio clock: it ends where the selection ends, to the sample" - } - > - {audio.state === "ready" - ? "exact playback" - : audio.state === "loading" - ? "decoding the audio…" - : null} - </span> + )} + {beforeMaxed ? ( + <span data-fetch-before-maxed="" className="text-[var(--color-dim)]"> + {atStartOfSource + ? "the recording starts here" + : capSentence} </span> - {audio.state === "failed" && ( - <span data-playback-fallback="" className="text-[11px] text-[var(--color-dirty)]"> - exact playback unavailable — {audio.why}. The video plays instead, stopped by the - frame: up to half a frame either side of the end. - </span> - )} - {/* ---- EXTENT above, CUT here ---- - The window row says how much of the recording is worth having. - This says what will actually play, and offers to derive it - from the quote -- which is the whole reason the two are - different numbers. */} - <span data-cut={clip.cutStart != null ? `${clip.cutStart}-${clip.cutEnd}` : ""} className="flex flex-wrap items-center gap-1.5"> - {clip.cutStart != null && clip.cutEnd != null ? ( - <span className="num text-[var(--color-good)]"> - cut {hms(clip.cutStart)}–{hms(clip.cutEnd)}{" "} - <span className="text-[var(--color-dim)]"> - ({(clip.cutEnd - clip.cutStart).toFixed(2)}s - {cutScore != null ? `, quote match ${cutScore.toFixed(2)}` : ""} - ) - </span> - </span> - ) : ( - <span className="text-[var(--color-dim)]"> - no cut — the whole window plays - </span> - )} - <button - type="button" - data-cut-to-quote="" - className={buttonVariants({ size: "sm" })} - disabled={!!busy || !draft.quote.trim()} - title={ - draft.quote.trim() - ? "find the quote in the transcript and cut to it, inside this window" - : "there is no quote to match against" - } - onClick={() => void cutToQuote()} - > - Cut to quote - </button> - {clip.cutStart != null && ( - <button - type="button" - data-cut-clear="" - className={buttonVariants({ size: "sm" })} - disabled={!!busy} - onClick={takeWholeClip} - > - Clear cut - </button> - )} - {cutUndo && ( - <button - type="button" - data-cut-undo="" - className={buttonVariants({ variant: "outline", size: "sm" })} - disabled={!!busy} - title={`undo: ${cutUndo.what}`} - onClick={() => void undoCut()} - > - Undo cut - </button> - )} - </span> - {/* ---- the MUTE MARK ---- - Beside the cut because it is the same kind of decision -- what - the finished clip does with its seconds -- and drafted like the - edges: heard at once, written by `save window` or `y`. */} - <span - data-mute={mute ?? ""} - className="flex flex-wrap items-center gap-1.5" - title="From the mark to the end of the clip the sound fades out and the picture plays on. Set it at the last silence before the ending sound." + ) : ( + <button + type="button" + data-fetch-before={nextBefore} + className={buttonVariants({ size: "sm" })} + disabled={!!busy} + onClick={() => void fetchMore({ padBefore: nextBefore, padAfter: keepAfter })} > - {mute != null ? ( - <span data-mute-from={mute} className="num text-[var(--color-text)]"> - mute from {hms(mute)}{" "} - <span className="text-[var(--color-dim)]"> - ({Math.max(0, sel.to - mute).toFixed(2)}s silent to the end) - </span> - </span> - ) : ( - <span className="text-[var(--color-dim)]">sound to the end</span> - )} - <button - type="button" - data-mute-set="" - className={buttonVariants({ size: "sm" })} - title="put the mute mark at the playhead" - onClick={muteAtPlayhead} - > - Mute from here - </button> - <button - type="button" - data-mute-pick={mutePick ? "armed" : ""} - aria-pressed={mutePick} - className={`${buttonVariants({ variant: "outline", size: "sm" })}${mutePick ? " bg-panel-2 border-muted" : ""}`} - title="the next click on the waveform places the mute mark (Esc cancels)" - onClick={() => setMutePick((v) => !v)} - > - {mutePick ? "Click the waveform…" : "Pick on waveform"} - </button> - {mute != null && ( - <button - type="button" - data-mute-clear="" - className={buttonVariants({ size: "sm" })} - onClick={clearMute} - > - Clear mute - </button> - )} - </span> - <span className="micro max-md:hidden"> - <kbd>[</kbd> <kbd>]</kbd> start · <kbd>,</kbd> <kbd>.</kbd> end — each plays the edge - it moved · <kbd>space</kbd> the whole selection · <kbd>R</kbd> reset · <kbd>-</kbd>{" "} - <kbd>=</kbd> speed · <kbd>a</kbd> auto · <kbd>m</kbd> mute from the playhead,{" "} - <kbd>;</kbd> <kbd>&apos;</kbd> move it, <kbd>M</kbd> clear — shift for 0.5s + ← Fetch to −{nextBefore} s + </button> + )} + {afterMaxed ? ( + <span data-fetch-after-maxed="" className="text-[var(--color-dim)]"> + {atEndOfSource + ? "the recording ends here" + : capSentence} </span> - {busy && <span className="text-[var(--color-meter)]">{busy}</span>} - {note && ( - <span data-bench-note="" className="text-[var(--color-dirty)]"> - {note} - </span> - )} - {fixBox("bench")} - </div> + ) : ( + <button + type="button" + data-fetch-after={nextAfter} + className={buttonVariants({ variant: "outline", size: "sm" })} + disabled={!!busy} + onClick={() => void fetchMore({ padBefore: keepBefore, padAfter: nextAfter })} + > + Fetch to +{nextAfter} s → + </button> + )} + {/* THE WHOLE RECORDING, when neither edge is the answer. Last, + and plainly labelled: it can be gigabytes. */} + <button + type="button" + data-fetch-full="" + className={buttonVariants({ size: "sm" })} + disabled={!!busy} + onClick={() => void fetchWholeSource()} + > + Fetch whole source via editor + </button> + {/* A window known bad, evicted and fetched again: a queue step (lane/ui-simplify). */} + <RefetchButton project={data.project} clip={clip.id} take={takeId} disabled={!!busy} /> + {storedOffered && ( + <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact /> + )} + </div> + )} - {/* ---- the instrument ---- - On a phone the edge strip is the instrument; this one is still - there, folded under Window, for the mute mark. */} - <div data-bench-sel={`${sel.from.toFixed(2)}-${sel.to.toFixed(2)}`} className={cn("flex flex-col gap-1", secBody("window", "max-md:order-[52]"))}> - {/* ---- the MODE: what the handles edit ---- - Cut (what plays; gaps live here) or Clip (the seconds reviewed), - and the line that reads the two in the mode's terms. */} - <div data-bench-mode={mode} className="flex flex-wrap items-center gap-2 text-[12px]"> - <span role="group" aria-label="what the handles edit" className="inline-flex overflow-hidden rounded border border-[var(--color-line)]"> - {(["cut", "clip"] as const).map((m) => ( - <button - key={m} - type="button" - data-bench-mode-set={m} - aria-pressed={mode === m} - disabled={!!busy || (dirty && mode !== m)} - title={ - dirty && mode !== m - ? `save or reset the ${editsCut ? "cut" : "window"} you moved first` - : m === "cut" - ? "the handles are what plays; gaps are cut here" - : "the handles are the seconds reviewed; what plays is the band inside" - } - onClick={() => setMode(m)} - className={ - mode === m - ? "bg-[var(--color-panel-2)] px-2.5 py-0.5 font-semibold text-[var(--color-text)] disabled:opacity-60" - : "px-2.5 py-0.5 text-[var(--color-dim)] hover:text-[var(--color-text)] disabled:opacity-50" - } - > - {m === "cut" ? "Cut" : "Clip"} - </button> - ))} - </span> - <span data-bench-plays={`${(after.cutStart ?? after.start).toFixed(2)}-${(after.cutEnd ?? after.end).toFixed(2)}`} className="num text-[var(--color-text)]"> - {mode === "cut" ? ( - <> - Plays {hms(after.cutStart ?? after.start)}–{hms(after.cutEnd ?? after.end)} - <span className="text-[var(--color-dim)]"> - {" "}· reviewed {hms(after.start)}–{hms(after.end)} - </span> - </> - ) : ( - <> - Reviewed {hms(after.start)}–{hms(after.end)} - <span className="text-[var(--color-dim)]"> - {" "}· plays {hms(after.cutStart ?? after.start)}–{hms(after.cutEnd ?? after.end)} - {after.cutStart != null ? " (edit it in Cut)" : ""} - </span> - </> + {/* ---- the cue rail, and what is past the cache ---- */} + <div className={cn("relative h-14 w-full shrink-0 overflow-hidden rounded border border-[var(--color-line)] bg-[var(--color-panel-2)]", secBody("window", "max-md:order-[54]"))}> + {/* The cached span, shaded. The waveform above is exactly this + stretch; everything outside it is text and nothing else. */} + {peek.length > 0 && ( + <> + <div + data-cache-span="" + className="absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-meter)_7%,transparent)]" + style={{ left: rpct(view.from), width: `calc(${rpct(view.to)} - ${rpct(view.from)})` }} + /> + {[view.from, view.to].map((t) => ( + <div + key={t} + data-cache-edge={t} + className="absolute top-0 h-full border-l border-dashed border-[var(--color-meter)]" + style={{ left: rpct(t) }} + /> + ))} + </> + )} + {/* ---- what the CUT already covers ---- + A band per other clip from this recording, and a hatch where + one of them overlaps the selection: a window widened into the + next clip is a duplicate, and that is invisible from inside a + single clip. */} + {siblings.map((sb) => { + if (sb.end <= rail.from || sb.start >= rail.to) return null; + const from = Math.max(sb.start, rail.from); + const to = Math.min(sb.end, rail.to); + const clash = Math.min(to, sel.to) - Math.max(from, sel.from) > 0.02; + return ( + <div + key={`sib-${sb.id}`} + data-sibling-band={sb.id} + data-sibling-clash={clash ? "1" : "0"} + title={`${sb.id} · ${sb.where} · ${clock(sb.start)}–${clock(sb.end)}${ + clash ? " — this selection overlaps it" : "" + }`} + className={`absolute bottom-0 h-3 overflow-hidden whitespace-nowrap rounded-sm border px-1 text-[8px] leading-3 ${ + clash + ? "border-[var(--color-dirty)] text-[var(--color-dirty)] [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-dirty)_26%,transparent)_0_4px,transparent_4px_8px)]" + : "border-[var(--color-sel)] bg-[color-mix(in_srgb,var(--color-sel)_16%,transparent)] text-[var(--color-sel)]" + }`} + style={{ left: rpct(from), width: `calc(${rpct(to)} - ${rpct(from)})` }} + > + {sb.id} · {sb.where} + </div> + ); + })} + {/* The GAPS: cut out of the clip's middle. */} + {(clip.gaps ?? []).map((g) => ( + <div + key={`rail-gap-${g.from}`} + data-rail-gap={`${g.from}-${g.to}`} + aria-hidden + className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-dirty)_26%,transparent)_0_4px,transparent_4px_8px)]" + style={{ left: rpct(g.from), width: `calc(${rpct(g.to)} - ${rpct(g.from)})` }} + /> + ))} + {/* The CUT, as an inner pair of markers: what plays, inside what + was reviewed. */} + {clip.cutStart != null && clip.cutEnd != null && ( + <> + <div + data-cut-span="" + className="absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-good)_10%,transparent)]" + style={{ + left: rpct(clip.cutStart), + width: `calc(${rpct(clip.cutEnd)} - ${rpct(clip.cutStart)})`, + }} + /> + {[clip.cutStart, clip.cutEnd].map((t) => ( + <div + key={`cut-${t}`} + data-cut-edge={t} + title={`the cut ${hms(clip.cutStart!)}–${hms(clip.cutEnd!)}`} + className="absolute top-0 h-full border-l-2 border-[var(--color-good)]" + style={{ left: rpct(t) }} + /> + ))} + </> + )} + {railCues.map((c) => { + const inSel = c.end > sel.from && c.start < sel.to; + const owner = siblingAt(c); + // Outside the cached file: readable, dimmed, and a click offers + // to go and get it rather than pretending it is already here. + const outside = c.start < view.from - 0.02 || c.end > view.to + 0.02; + return ( + <button + type="button" + key={`${c.start}-${c.end}`} + data-cue={c.start} + data-ends-sentence={c.endsSentence ? "1" : "0"} + data-peek={outside ? "1" : "0"} + data-in-sibling={owner ? owner.id : ""} + title={ + [ + c.text, + // The whole point of reading ahead: these words may not + // be missing at all, they may be the next clip. + owner ? `already in the cut as ${owner.id} (${owner.where})` : null, + outside ? `not fetched — click to fetch to ${padLabelForCue(c)}` : null, + ] + .filter(Boolean) + .join("\n\n") + } + onClick={() => { + if (outside) { + if (!atMaxPad) void fetchMore(padsForCue(c)); + return; + } + // Snap the NEARER edge to this cue's nearer boundary. + const dStart = Math.abs(sel.from - c.start); + const dEnd = Math.abs(sel.to - c.end); + onSel( + dStart <= dEnd ? { ...sel, from: c.start } : { ...sel, to: c.end }, + false, + dStart <= dEnd ? "start" : "end", + ); + }} + className={`absolute top-0 h-full overflow-hidden border-l px-1 text-left text-[10px] leading-tight ${ + outside + ? "border-dashed border-[var(--color-line)] text-[var(--color-dim)] opacity-40 hover:opacity-70" + : inSel + ? "border-[var(--color-sel)] text-[var(--color-text)]" + : "border-[var(--color-line)] text-[var(--color-dim)] opacity-60" + }`} + style={{ left: rpct(c.start), width: `calc(${rpct(c.end)} - ${rpct(c.start)})` }} + > + {c.endsSentence && ( + <span className="mr-1 text-[var(--color-meter)]" aria-label="closes a sentence"> + ¶ + </span> )} - </span> - {/* A cut narrower than what was reviewed: the rest back in one press. */} - {cutNarrower && !dirty && ( - <button - type="button" - data-cut-use-whole="" - className={buttonVariants({ variant: "outline", size: "sm" })} - disabled={!!busy} - title="play everything reviewed: the cut is cleared, and gaps can go anywhere in the clip (Undo cut puts it back)" - onClick={takeWholeClip} - > - Use the whole clip - </button> - )} - </div> - {/* Zoomed: round ticks over what is shown. */} - {zoom.zoomed && <ZoomRuler vis={zoom.vis} />} - <BenchWaveBox - zoom={zoom} - sel={sel} - cand={savedSpan} - cues={cues} - peaks={peaks} - playhead={playhead} - onSel={onSel} - gap={gap} - gaps={clip.gaps ?? []} - silences={renderEdges?.silences ?? null} - words={nearWords?.words ?? null} - busy={!!busy} - held={mutePick || mode === "clip"} - walls={mode === "cut" ? walls : null} + {c.text} + </button> + ); + })} + </div> + {/* ---- the warnings ---- + Still unfolded, and deliberately: a warning behind a summary is a + warning nobody reads. They are one line each instead. */} + {midSentence && ( + <p + data-warn="mid-sentence" + className="shrink-0 max-md:order-[32] rounded border border-[var(--color-dirty)] bg-[color-mix(in_srgb,var(--color-dirty)_10%,transparent)] px-2 py-1 text-[11px] leading-snug text-[var(--color-dirty)]" + > + Ends mid-sentence — the cut lands inside &ldquo;… + {endCue?.text.trim().slice(-56)}&rdquo;. Run it to the end of the sentence, or set{" "} + <code className="font-mono">lockEnd</code> to say you meant to cut here. + </p> + )} + {data.noPunctuation && ( + <p + data-warn="no-punctuation" + className="shrink-0 max-md:order-[32] rounded border border-[var(--color-line)] px-2 py-1 text-[11px] leading-snug text-[var(--color-dim)]" + > + This upload&rsquo;s ASR carries no punctuation, so there are no sentence boundaries to + find and widening cannot help. Set these edges by ear and lock them. + </p> + )} + {wouldRevert && ( + <p + data-warn="would-revert" + data-walk-in="window" + className="max-md:order-[32] flex flex-wrap items-center gap-2 rounded border border-[var(--color-dirty)] px-2 py-1 text-[11px] leading-snug text-[var(--color-dirty)]" + > + <span> + <code className="font-mono">resolve-windows --write</code> would make this{" "} + {hms(proposed!.start)} – {hms(proposed!.end)}, reverting your edit. + </span> + <button + type="button" + className={buttonVariants({ variant: "outline", size: "sm" })} + onClick={() => + void save({ + ...edgePatch(sel), + start: after.start, + end: after.end, + lockStart: Math.abs(proposed!.start - after.start) > 0.05, + lockEnd: Math.abs(proposed!.end - after.end) > 0.05, + }) + } > - {/* The mute mark over the waveform: a line where the sound stops - and a hatch over what is silent to the end of the selection. - In the interaction colour, like the handles -- it is an edit, - not a reading -- and never in the way of a drag. */} - {mute != null && mute >= zoom.vis.from && mute <= zoom.vis.to && ( - <> - <div - data-mute-span="" - className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(135deg,color-mix(in_srgb,var(--color-dim)_22%,transparent)_0_3px,transparent_3px_7px)]" - style={{ - left: zpct(mute), - width: `calc(${zpct(Math.max(mute, Math.min(sel.to, zoom.vis.to)))} - ${zpct(mute)})`, - }} - /> - <div - data-mute-marker={mute} - className="pointer-events-none absolute top-0 h-full border-l-2 border-dashed border-[var(--color-sel)]" - style={{ left: zpct(mute) }} - > - <span className="absolute left-1 top-0.5 rounded bg-[var(--color-panel-2)] px-1 font-mono text-[9px] leading-tight text-[var(--color-sel)]"> - mute + Save and lock + </button> + </p> + )} + + {/* ---- the second 16:9 box, folded ---- + It was always on screen and it is the thing you look at LAST, once + per clip, after a render. Two stacked players is what made this + bench taller than a laptop. */} + <details + data-rendered-strip="" + onToggle={(e) => setRenderedOpen((e.currentTarget as HTMLDetailsElement).open)} + data-walk-in="window" + className={cn( + "shrink-0 rounded border border-[var(--color-line)] px-2 py-1 text-[12px] open:max-h-[55vh] open:overflow-y-auto max-md:open:max-h-none", + secBody("window", "max-md:order-[55]"), + )} + > + <summary className="cursor-pointer text-[11px] text-[var(--color-dim)]"> + this clip as rendered{" "} + <span className={segSrc ? "text-[var(--color-meter)]" : ""}> + {segSrc ? "· built" : "· nothing built yet"} + </span>{" "} + · what resolve-windows may touch + {windows.length > 1 && <span> · {windows.length} cached windows</span>} + </summary> + <div className="mt-2 grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,16rem)]"> + <div className="space-y-2"> + {segSrc && showOverlay ? ( + // The segment with the on-screen panel laid over it, where the + // build overlays it. The panel covers the bottom of the frame + // -- where native controls would be -- so the player's + // controls are a row of its own underneath. + <div className="space-y-1"> + <DeckFrame preview={deckPreview!} t={overlayT} texts={osTexts} testid="bench-deck-preview"> + <video + ref={segVideo} + data-testid="segment-video" + src={segSrc} + className="absolute inset-0 h-full w-full cursor-pointer object-contain" + preload="metadata" + onClick={(e) => { + const el = e.currentTarget; + if (el.paused) void el.play().catch(() => {}); + else el.pause(); + }} + /> + </DeckFrame> + <div className="flex items-center gap-2"> + <button + type="button" + data-testid="segment-play" + className={buttonVariants({ size: "sm" })} + onClick={() => { + const el = segVideo.current; + if (!el) return; + if (el.paused) void el.play().catch(() => {}); + else el.pause(); + }} + > + {segPaused ? "Play" : "Pause"} + </button> + <input + type="range" + data-testid="segment-scrub" + min={0} + max={segDur || 0} + step={0.01} + value={Math.min(segT ?? 0, segDur || 0)} + onChange={(e) => { + const el = segVideo.current; + if (el) el.currentTime = Number(e.target.value); + }} + className="min-w-0 flex-1" + /> + <span className="num font-mono text-[11px] text-[var(--color-dim)]"> + {(segT ?? 0).toFixed(1)} / {segDur.toFixed(1)}s </span> </div> - </> - )} - {/* Clip mode: the cut as a band inside the extent (bench/CutEdges.tsx), passive. */} - {mode === "clip" && after.cutStart != null && after.cutEnd != null && ( - <CutEdges vis={zoom.vis} cut={{ from: after.cutStart, to: after.cutEnd }} extent={sel} busy={!!busy} fmt={hms} /> - )} - {/* Where the render will actually cut: each edge snapped to its silence, faint. */} - <RenderGhosts edges={renderEdges} view={zoom.vis} /> - {/* Armed: the next click places the mark rather than an edge. */} - {mutePick && ( - <div - data-mute-pick-layer="" - className="absolute inset-0 z-[8] cursor-crosshair rounded-md outline outline-1 outline-[var(--color-sel)]" - onPointerDown={(e) => { - const r = e.currentTarget.getBoundingClientRect(); - const frac = Math.min(1, Math.max(0, (e.clientX - r.left) / Math.max(1, r.width))); - placeMute(zoom.vis.from + frac * zspan, true); - }} + </div> + ) : segSrc ? ( + <video + ref={segVideo} + data-testid="segment-video" + src={segSrc} + className="aspect-video w-full rounded border border-[var(--color-line)] bg-black" + preload="metadata" + controls /> - )} - </BenchWaveBox> - {/* Zoomed: the whole cached window, what is shown of it -- drag to pan. */} - {zoom.zoomed && <ZoomOverview zoom={zoom} whole={view} peaks={peaks} sel={sel} gaps={clip.gaps ?? []} />} - {/* Under the waveform: its zoom, and the clip's gaps (the waveform keeps its place on the page). */} - <div data-wave-tools="" className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px]"> - {/* ---- GAPS inside the clip (bench/BenchWave.tsx GapTools) ---- */} - {mode === "cut" ? ( - <GapTools gap={gap} gaps={clip.gaps ?? []} span={gapsSpan} sel={sel} busy={!!busy} fmt={hms} play={play} /> + ) : showOverlay ? ( + <div data-testid="no-segment"> + <DeckFrame + preview={deckPreview!} + t={deckSeg ? midOf(deckSeg) : 0} + texts={osTexts} + testid="bench-deck-preview" + > + <NeutralFrame geometry={deckPreview!.geometry} label="nothing rendered for this clip yet" /> + </DeckFrame> + </div> ) : ( - <span data-gaps-clip-mode="" className="text-[var(--color-dim)]"> - {(clip.gaps ?? []).length ? `${(clip.gaps ?? []).length} gap${(clip.gaps ?? []).length === 1 ? "" : "s"} — ` : ""}gaps are cut in Cut mode - </span> + <div + data-testid="no-segment" + className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] px-2 text-center text-[11px] text-[var(--color-dim)]" + > + nothing rendered for this clip yet + </div> )} - <TightenButtons tools={edgeTools} busy={!!busy} /> - <span className="micro max-md:hidden"> - <kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "} - <kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead - </span> - <ZoomControls zoom={zoom} whole={view} selection={gap.sel ?? sel} playhead={playhead} /> - </div> - </div> - - {/* Offered at the edge of the cache, as always -- and also whenever - the rail has something to read past it. Having just read the next - sentence is exactly when you want the seconds it is in, and - dragging to the edge first to be allowed to ask is a ritual. */} - {(atStartEdge || atEndEdge || peekOutside) && ( - <div data-walk-in="window" className={cn("flex flex-wrap items-center gap-2 text-[12px]", secBody("window", "max-md:order-[53]"))}> - {atStartEdge || atEndEdge ? ( - <span className="text-[var(--color-dirty)]"> - that is the edge of what is cached{cached ? ` (${cached.name})` : ""} - </span> - ) : ( - <span className="text-[var(--color-dim)]"> - cached to −{Math.floor(reachBefore)} s / +{Math.floor(reachAfter)} s around this - clip - </span> - )} - {beforeMaxed ? ( - <span data-fetch-before-maxed="" className="text-[var(--color-dim)]"> - {atStartOfSource - ? "the recording starts here" - : capSentence} - </span> - ) : ( - <button - type="button" - data-fetch-before={nextBefore} - className={buttonVariants({ size: "sm" })} - disabled={!!busy} - onClick={() => void fetchMore({ padBefore: nextBefore, padAfter: keepAfter })} - > - ← Fetch to −{nextBefore} s - </button> - )} - {afterMaxed ? ( - <span data-fetch-after-maxed="" className="text-[var(--color-dim)]"> - {atEndOfSource - ? "the recording ends here" - : capSentence} - </span> - ) : ( + {data.take ? ( + // The one-clip render builds the PROJECT's segment; a take is rendered whole. + <p data-take-no-rerender="" className="text-[11px] leading-snug text-[var(--color-dim)]"> + A take is rendered as a whole, from its own patch:{" "} + <Link href={data.take.takesHref} className="ink-link"> + Render on the Takes page + </Link>{" "} + or <code className="font-mono">umtool take {data.project} --id {data.take.id} --full</code>. + </p> + ) : ( + <> <button type="button" - data-fetch-after={nextAfter} + data-rerender="" className={buttonVariants({ variant: "outline", size: "sm" })} disabled={!!busy} - onClick={() => void fetchMore({ padBefore: keepBefore, padAfter: nextAfter })} + onClick={() => void rerender()} > - Fetch to +{nextAfter} s → + Re-render this clip </button> - )} - {/* THE WHOLE RECORDING, when neither edge is the answer. Last, - and plainly labelled: it can be gigabytes. */} - <button - type="button" - data-fetch-full="" - className={buttonVariants({ size: "sm" })} - disabled={!!busy} - onClick={() => void fetchWholeSource()} - > - Fetch whole source via editor - </button> - {/* A window known bad, evicted and fetched again: a queue step (lane/ui-simplify). */} - <RefetchButton project={data.project} clip={clip.id} take={takeId} disabled={!!busy} /> - {storedOffered && ( - <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact /> - )} - </div> - )} - - {/* ---- the cue rail, and what is past the cache ---- */} - <div className={cn("relative h-14 w-full shrink-0 overflow-hidden rounded border border-[var(--color-line)] bg-[var(--color-panel-2)]", secBody("window", "max-md:order-[54]"))}> - {/* The cached span, shaded. The waveform above is exactly this - stretch; everything outside it is text and nothing else. */} - {peek.length > 0 && ( - <> - <div - data-cache-span="" - className="absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-meter)_7%,transparent)]" - style={{ left: rpct(view.from), width: `calc(${rpct(view.to)} - ${rpct(view.from)})` }} - /> - {[view.from, view.to].map((t) => ( - <div - key={t} - data-cache-edge={t} - className="absolute top-0 h-full border-l border-dashed border-[var(--color-meter)]" - style={{ left: rpct(t) }} - /> - ))} + <p className="text-[11px] leading-snug text-[var(--color-dim)]"> + One clip, no crossfade, no chapters — it overwrites this clip&rsquo;s segment and + nothing else. The header is drawn by ffmpeg from a text file, so this is the only + place the line above can be checked rather than believed. + </p> </> )} - {/* ---- what the CUT already covers ---- - A band per other clip from this recording, and a hatch where - one of them overlaps the selection: a window widened into the - next clip is a duplicate, and that is invisible from inside a - single clip. */} - {siblings.map((sb) => { - if (sb.end <= rail.from || sb.start >= rail.to) return null; - const from = Math.max(sb.start, rail.from); - const to = Math.min(sb.end, rail.to); - const clash = Math.min(to, sel.to) - Math.max(from, sel.from) > 0.02; - return ( - <div - key={`sib-${sb.id}`} - data-sibling-band={sb.id} - data-sibling-clash={clash ? "1" : "0"} - title={`${sb.id} · ${sb.where} · ${clock(sb.start)}–${clock(sb.end)}${ - clash ? " — this selection overlaps it" : "" - }`} - className={`absolute bottom-0 h-3 overflow-hidden whitespace-nowrap rounded-sm border px-1 text-[8px] leading-3 ${ - clash - ? "border-[var(--color-dirty)] text-[var(--color-dirty)] [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-dirty)_26%,transparent)_0_4px,transparent_4px_8px)]" - : "border-[var(--color-sel)] bg-[color-mix(in_srgb,var(--color-sel)_16%,transparent)] text-[var(--color-sel)]" - }`} - style={{ left: rpct(from), width: `calc(${rpct(to)} - ${rpct(from)})` }} - > - {sb.id} · {sb.where} - </div> - ); - })} - {/* The GAPS: cut out of the clip's middle. */} - {(clip.gaps ?? []).map((g) => ( - <div - key={`rail-gap-${g.from}`} - data-rail-gap={`${g.from}-${g.to}`} - aria-hidden - className="pointer-events-none absolute top-0 h-full [background:repeating-linear-gradient(45deg,color-mix(in_srgb,var(--color-dirty)_26%,transparent)_0_4px,transparent_4px_8px)]" - style={{ left: rpct(g.from), width: `calc(${rpct(g.to)} - ${rpct(g.from)})` }} - /> - ))} - {/* The CUT, as an inner pair of markers: what plays, inside what - was reviewed. */} - {clip.cutStart != null && clip.cutEnd != null && ( - <> - <div - data-cut-span="" - className="absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-good)_10%,transparent)]" - style={{ - left: rpct(clip.cutStart), - width: `calc(${rpct(clip.cutEnd)} - ${rpct(clip.cutStart)})`, - }} + </div> + + {/* ---- lock, explained rather than labelled ---- */} + <div className="space-y-1"> + <div className="micro">what resolve-windows may touch</div> + {( + [ + ["lock", "leave this clip alone entirely — the window is deliberate"], + ["lockStart", "pin the start exactly where it is"], + ["lockEnd", "pin the end exactly where it is"], + ["lockCut", "keep the cut as it is — the resolver may not re-derive it"], + ] as const + ).map(([k, why]) => ( + <label key={k} className="flex items-start gap-2"> + <input + type="checkbox" + name={k} + checked={!!clip[k]} + disabled={!!busy} + onChange={(e) => void save({ [k]: e.target.checked } as Partial<Clip>)} /> - {[clip.cutStart, clip.cutEnd].map((t) => ( - <div - key={`cut-${t}`} - data-cut-edge={t} - title={`the cut ${hms(clip.cutStart!)}–${hms(clip.cutEnd!)}`} - className="absolute top-0 h-full border-l-2 border-[var(--color-good)]" - style={{ left: rpct(t) }} - /> - ))} - </> - )} - {railCues.map((c) => { - const inSel = c.end > sel.from && c.start < sel.to; - const owner = siblingAt(c); - // Outside the cached file: readable, dimmed, and a click offers - // to go and get it rather than pretending it is already here. - const outside = c.start < view.from - 0.02 || c.end > view.to + 0.02; - return ( - <button - type="button" - key={`${c.start}-${c.end}`} - data-cue={c.start} - data-ends-sentence={c.endsSentence ? "1" : "0"} - data-peek={outside ? "1" : "0"} - data-in-sibling={owner ? owner.id : ""} - title={ - [ - c.text, - // The whole point of reading ahead: these words may not - // be missing at all, they may be the next clip. - owner ? `already in the cut as ${owner.id} (${owner.where})` : null, - outside ? `not fetched — click to fetch to ${padLabelForCue(c)}` : null, - ] - .filter(Boolean) - .join("\n\n") - } - onClick={() => { - if (outside) { - if (!atMaxPad) void fetchMore(padsForCue(c)); - return; - } - // Snap the NEARER edge to this cue's nearer boundary. - const dStart = Math.abs(sel.from - c.start); - const dEnd = Math.abs(sel.to - c.end); - onSel( - dStart <= dEnd ? { ...sel, from: c.start } : { ...sel, to: c.end }, - false, - dStart <= dEnd ? "start" : "end", - ); - }} - className={`absolute top-0 h-full overflow-hidden border-l px-1 text-left text-[10px] leading-tight ${ - outside - ? "border-dashed border-[var(--color-line)] text-[var(--color-dim)] opacity-40 hover:opacity-70" - : inSel - ? "border-[var(--color-sel)] text-[var(--color-text)]" - : "border-[var(--color-line)] text-[var(--color-dim)] opacity-60" - }`} - style={{ left: rpct(c.start), width: `calc(${rpct(c.end)} - ${rpct(c.start)})` }} - > - {c.endsSentence && ( - <span className="mr-1 text-[var(--color-meter)]" aria-label="closes a sentence"> - ¶ - </span> - )} - {c.text} - </button> - ); - })} + <span> + <span className="font-mono text-[11px] text-[var(--color-text)]">{k}</span> + <span className="block text-[11px] text-[var(--color-dim)]">{why}</span> + </span> + </label> + ))} </div> - {/* ---- the warnings ---- - Still unfolded, and deliberately: a warning behind a summary is a - warning nobody reads. They are one line each instead. */} - {midSentence && ( - <p - data-warn="mid-sentence" - className="shrink-0 max-md:order-[32] rounded border border-[var(--color-dirty)] bg-[color-mix(in_srgb,var(--color-dirty)_10%,transparent)] px-2 py-1 text-[11px] leading-snug text-[var(--color-dirty)]" - > - Ends mid-sentence — the cut lands inside &ldquo;… - {endCue?.text.trim().slice(-56)}&rdquo;. Run it to the end of the sentence, or set{" "} - <code className="font-mono">lockEnd</code> to say you meant to cut here. - </p> - )} - {data.noPunctuation && ( - <p - data-warn="no-punctuation" - className="shrink-0 max-md:order-[32] rounded border border-[var(--color-line)] px-2 py-1 text-[11px] leading-snug text-[var(--color-dim)]" - > - This upload&rsquo;s ASR carries no punctuation, so there are no sentence boundaries to - find and widening cannot help. Set these edges by ear and lock them. - </p> - )} - {wouldRevert && ( - <p - data-warn="would-revert" - data-walk-in="window" - className="max-md:order-[32] flex flex-wrap items-center gap-2 rounded border border-[var(--color-dirty)] px-2 py-1 text-[11px] leading-snug text-[var(--color-dirty)]" - > - <span> - <code className="font-mono">resolve-windows --write</code> would make this{" "} - {hms(proposed!.start)} – {hms(proposed!.end)}, reverting your edit. - </span> - <button - type="button" - className={buttonVariants({ variant: "outline", size: "sm" })} - onClick={() => - void save({ - ...edgePatch(sel), - start: after.start, - end: after.end, - lockStart: Math.abs(proposed!.start - after.start) > 0.05, - lockEnd: Math.abs(proposed!.end - after.end) > 0.05, - }) - } - > - Save and lock - </button> - </p> - )} + </div> + </details> + </div> + ); - {/* ---- the second 16:9 box, folded ---- - It was always on screen and it is the thing you look at LAST, once - per clip, after a render. Two stacked players is what made this - bench taller than a laptop. */} - <details - data-rendered-strip="" - onToggle={(e) => setRenderedOpen((e.currentTarget as HTMLDetailsElement).open)} - data-walk-in="window" - className={cn( - "shrink-0 rounded border border-[var(--color-line)] px-2 py-1 text-[12px] open:max-h-[55vh] open:overflow-y-auto max-md:open:max-h-none", - secBody("window", "max-md:order-[55]"), - )} - > - <summary className="cursor-pointer text-[11px] text-[var(--color-dim)]"> - this clip as rendered{" "} - <span className={segSrc ? "text-[var(--color-meter)]" : ""}> - {segSrc ? "· built" : "· nothing built yet"} - </span>{" "} - · what resolve-windows may touch - {windows.length > 1 && <span> · {windows.length} cached windows</span>} - </summary> - <div className="mt-2 grid gap-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,16rem)]"> - <div className="space-y-2"> - {segSrc && showOverlay ? ( - // The segment with the on-screen panel laid over it, where the - // build overlays it. The panel covers the bottom of the frame - // -- where native controls would be -- so the player's - // controls are a row of its own underneath. - <div className="space-y-1"> - <DeckFrame preview={deckPreview!} t={overlayT} texts={osTexts} testid="bench-deck-preview"> - <video - ref={segVideo} - data-testid="segment-video" - src={segSrc} - className="absolute inset-0 h-full w-full cursor-pointer object-contain" - preload="metadata" - onClick={(e) => { - const el = e.currentTarget; - if (el.paused) void el.play().catch(() => {}); - else el.pause(); - }} - /> - </DeckFrame> - <div className="flex items-center gap-2"> - <button - type="button" - data-testid="segment-play" - className={buttonVariants({ size: "sm" })} - onClick={() => { - const el = segVideo.current; - if (!el) return; - if (el.paused) void el.play().catch(() => {}); - else el.pause(); - }} - > - {segPaused ? "Play" : "Pause"} - </button> - <input - type="range" - data-testid="segment-scrub" - min={0} - max={segDur || 0} - step={0.01} - value={Math.min(segT ?? 0, segDur || 0)} - onChange={(e) => { - const el = segVideo.current; - if (el) el.currentTime = Number(e.target.value); - }} - className="min-w-0 flex-1" - /> - <span className="num font-mono text-[11px] text-[var(--color-dim)]"> - {(segT ?? 0).toFixed(1)} / {segDur.toFixed(1)}s - </span> - </div> - </div> - ) : segSrc ? ( - <video - ref={segVideo} - data-testid="segment-video" - src={segSrc} - className="aspect-video w-full rounded border border-[var(--color-line)] bg-black" - preload="metadata" - controls - /> - ) : showOverlay ? ( - <div data-testid="no-segment"> - <DeckFrame - preview={deckPreview!} - t={deckSeg ? midOf(deckSeg) : 0} - texts={osTexts} - testid="bench-deck-preview" - > - <NeutralFrame geometry={deckPreview!.geometry} label="nothing rendered for this clip yet" /> - </DeckFrame> - </div> - ) : ( - <div - data-testid="no-segment" - className="flex aspect-video w-full items-center justify-center rounded border border-dashed border-[var(--color-line)] px-2 text-center text-[11px] text-[var(--color-dim)]" - > - nothing rendered for this clip yet - </div> - )} - {data.take ? ( - // The one-clip render builds the PROJECT's segment; a take is rendered whole. - <p data-take-no-rerender="" className="text-[11px] leading-snug text-[var(--color-dim)]"> - A take is rendered as a whole, from its own patch:{" "} - <Link href={data.take.takesHref} className="ink-link"> - Render on the Takes page - </Link>{" "} - or <code className="font-mono">umtool take {data.project} --id {data.take.id} --full</code>. - </p> - ) : ( - <> - <button - type="button" - data-rerender="" - className={buttonVariants({ variant: "outline", size: "sm" })} - disabled={!!busy} - onClick={() => void rerender()} - > - Re-render this clip - </button> - <p className="text-[11px] leading-snug text-[var(--color-dim)]"> - One clip, no crossfade, no chapters — it overwrites this clip&rsquo;s segment and - nothing else. The header is drawn by ffmpeg from a text file, so this is the only - place the line above can be checked rather than believed. - </p> - </> - )} - </div> + if (inspector) { + return ( + <div + ref={inspectorRef} + tabIndex={-1} + data-bench={clip.id} + data-bench-layout="inspector" + data-verdict={verdict} + // The bench's keys are its own only while the focus is in here (the workspace has its own). + data-ws-own-keys="" + className="flex min-w-0 flex-col gap-2 text-[12px] outline-none" + > + {workColumn} + </div> + ); + } - {/* ---- lock, explained rather than labelled ---- */} - <div className="space-y-1"> - <div className="micro">what resolve-windows may touch</div> - {( - [ - ["lock", "leave this clip alone entirely — the window is deliberate"], - ["lockStart", "pin the start exactly where it is"], - ["lockEnd", "pin the end exactly where it is"], - ["lockCut", "keep the cut as it is — the resolver may not re-derive it"], - ] as const - ).map(([k, why]) => ( - <label key={k} className="flex items-start gap-2"> - <input - type="checkbox" - name={k} - checked={!!clip[k]} - disabled={!!busy} - onChange={(e) => void save({ [k]: e.target.checked } as Partial<Clip>)} - /> - <span> - <span className="font-mono text-[11px] text-[var(--color-text)]">{k}</span> - <span className="block text-[11px] text-[var(--color-dim)]">{why}</span> - </span> - </label> - ))} - </div> - </div> - </details> + return ( + // ONE SCREEN, at a desk. + // + // Walking a cut is sixty clips in a row. A bench that scrolls puts the + // attribution fields -- the point of the walk -- below the fold on every + // one of them, and the answer to "did I check that" becomes a scroll + // position. So from lg up the bench owns exactly the space the page has + // left: the grid is the viewport minus the chrome, nothing outside a column + // scrolls, and what does not earn its height is folded rather than cut. + // Below lg it is a single scrolling column -- a phone cannot hold this and + // pretending otherwise would cost the desk case something. + <BenchBody verdict={verdictBar} reader={readerPane} workClassName="lg:overflow-hidden" phoneFlat> + <div + data-bench={clip.id} + data-verdict={verdict} + className="flex flex-col gap-2 lg:h-full lg:min-h-0 lg:overflow-hidden max-md:contents" + > + {/* On a phone the banner is one muted line under Notes (phoneNotesHead). + The wrapper only when there is a banner: an empty one would be a + flex item, and a gap, on the desk. */} + {data.generatedBy && !data.take && ( + <div className="max-md:hidden"> + <GeneratedBanner generatedBy={data.generatedBy} /> </div> + )} + {/* A take's clip is never benched from the UI now (L3: Open in draft first); `umtool window --take` edits one. */} + {/* ---- where you are, where you can go, and what will be burned in ---- */} + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] max-md:contents"> + {/* On a phone both counts are the place bar's `50/51` and its hairline. */} + <span className="micro max-md:hidden" data-review-progress=""> + {reviewed} reviewed + </span> + {/* What the WALK has left, which is not the same number: a clip nobody + has fetched still needs judgement and cannot get it today. */} + <span className="micro max-md:hidden" data-ready-count=""> + ready {data.ready} of {data.needing} needing judgement + </span> + {/* The working cut's name: what this bench edits, and the latest take it was made into. */} + {data.working && !data.take && <LatestLine project={data.project} working={data.working} className="max-md:hidden" />} + {!data.fetched && ( + <span className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")} data-clip-unfetched=""> + not fetched yet + </span> + )} + {/* A deliberate repeat (`repeatOf`): its overlap with that clip is the point. */} + {clip.repeatOf && ( + <span + data-bench-repeat-of={clip.repeatOf} + title={`re-plays ${clip.repeatOf} on purpose (a callback, a flash-forward): their overlap is neither flagged nor trimmed`} + className={cn(badgeVariants({ variant: "info", size: "sm" }), "max-md:order-[21] max-md:self-start")} + > + repeats {clip.repeatOf} + </span> + )} + {clip.star && ( + <span data-bench-star="" title="starred on the walk: a trailer candidate" className={cn(badgeVariants({ variant: "state", size: "sm" }), "max-md:order-[21] max-md:self-start")}> + ★ trailer + </span> + )} + {/* The renderer's own line, live. It used to sit four hundred pixels + down the page; it is the one string this bench exists to get right, + so it heads the screen. */} + <span + data-attrib-preview="" + title={previewLine} + className={cn( + "num ml-auto min-w-0 max-w-full truncate rounded bg-[var(--color-panel-2)] px-2 py-0.5 text-[12px] text-[var(--color-meter)]", + secBody("attribution", "max-md:order-[81] max-md:ml-0 max-md:whitespace-normal"), + )} + > + {previewLine} + </span> + </div> + + <div className="grid min-h-0 flex-1 gap-3 lg:grid-cols-[minmax(0,1fr)_minmax(20rem,23rem)] max-md:contents"> + {/* ================= the picture, and its edges ================= */} + {/* Since P4b the words are the bench's reader pane: this column is the + picture and everything that moves its edges, and it scrolls on its + own before the picture shrinks below a usable height. */} + {workColumn} {/* ============ what this clip IS, and what the header says ============ */} <div className="flex min-h-0 flex-col gap-2 overflow-y-auto text-[12px] max-md:contents"> diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -6,6 +6,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { postBenchHref } from "@/lib/hrefs"; +import { announceManifestChanged } from "./timelineApi"; import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, ownPictureOnly, postItemPlan, readingSeconds, refPictureOnly, ruleSeconds, panelEntry } from "umtool-report-to-video/post-item"; import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; @@ -91,7 +92,13 @@ type Scene = { key: string; n: number; of: number; ids: string[]; media: number export default function PostBench({ project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay, render = {}, combo = null, before = null, scene: savedScene = null, conversation = null, + layout = "bench", }: { + /** + * `inspector`: the workspace's inspector (umtool redesign L7a) -- one column, no way back or to the next post + * (the workspace walks the blocks), its keys its own only while the focus is in it. Every save writes the draft. + */ + layout?: "bench" | "inspector"; project: string; entry: Entry; token: string | null; @@ -113,6 +120,8 @@ export default function PostBench({ conversation?: Record<string, unknown> | null; }) { const router = useRouter(); + const inspector = layout === "inspector"; + const rootRef = useRef<HTMLDivElement | null>(null); const [entry, setEntry] = useState<Entry>(initial); const [saved, setSaved] = useState<Entry>(initial); const [token, setToken] = useState(initialToken); @@ -161,6 +170,7 @@ export default function PostBench({ const onKey = (ev: KeyboardEvent) => { const tgt = ev.target as HTMLElement | null; if (tgt?.closest("input, textarea, select")) return; + if (inspector && !(tgt && rootRef.current?.contains(tgt))) return; if (ev.key === " ") { ev.preventDefault(); setPlaying((p) => (s >= total ? (setS(0), true) : !p)); @@ -176,7 +186,7 @@ export default function PostBench({ }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); - }, [s, total, next, prev, project, fromPlay, router]); + }, [s, total, next, prev, project, fromPlay, router, inspector]); const dirty = JSON.stringify(entry) !== JSON.stringify(saved); const media = entry.media ?? []; @@ -253,6 +263,8 @@ export default function PostBench({ setSaved(j.entry); setToken(j.token ?? null); setStatus("saved"); + // The draft moved: whatever else on the page holds it (the workspace's viewer and strip) reads it again. + announceManifestChanged(project); // A scene knob changed: the page counts the scene again (its neighbours are read on the server). if ((saved.scene ?? null) !== (j.entry.scene ?? null)) router.refresh(); }, [entry, project, token, saved, router]); @@ -321,18 +333,27 @@ export default function PostBench({ const reading = readingSeconds(entry); return ( - <div className="mx-auto grid max-w-[1400px] grid-cols-1 gap-4 min-[1100px]:grid-cols-[minmax(0,1fr)_360px]" data-post-bench={entry.id}> + <div + ref={rootRef} + tabIndex={inspector ? -1 : undefined} + data-ws-own-keys={inspector ? "" : undefined} + className={cn("mx-auto grid max-w-[1400px] grid-cols-1 gap-4 outline-none", !inspector && "min-[1100px]:grid-cols-[minmax(0,1fr)_360px]")} + data-post-bench={entry.id} + data-post-bench-shape={layout} + > <section className="min-w-0 space-y-2"> <div className="flex flex-wrap items-center gap-2 text-[12px]"> - <Link href={back.href} className="ink-link" data-post-bench-back=""> - {back.label} - </Link> - {prev && ( + {!inspector && ( + <Link href={back.href} className="ink-link" data-post-bench-back=""> + {back.label} + </Link> + )} + {!inspector && prev && ( <Link href={postBenchHref(project, prev, fromPlay ? { play: { at: 0 } } : {})} className="ink-link" data-post-bench-prev={prev}> ‹ {prev} </Link> )} - {next && ( + {!inspector && next && ( <Link href={postBenchHref(project, next, fromPlay ? { play: { at: 0 } } : {})} className="ink-link" data-post-bench-next={next}> {next} › </Link> diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx @@ -1,18 +1,10 @@ import { notFound } from "next/navigation"; import AppShell from "@/components/shell/AppShell"; import PostBench from "./PostBench"; -import { channelsDirFor, readManifest } from "@/lib/projects/report.mjs"; -import { manifestToken } from "@/lib/report/manifest.mjs"; import { projectHref, playHref } from "@/lib/hrefs"; import PlayLink from "./PlayLink"; -import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; -import { postItemPlan, panelEntry } from "umtool-report-to-video/post-item"; -import { planContext } from "umtool-report-to-video/post-conversation"; -import { projectCombos } from "umtool-report-to-video/post-combo-prints"; -import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; +import { postBenchData } from "@/lib/report/postBenchData"; import type { ProjectRef } from "@/lib/project-types"; -import type { PostPlan } from "./review/PostItemPlayer"; -import type { ComboInfo } from "./review/ComboBadge"; // THE POST BENCH (report-to-video/post-item.mjs; knobs.md, "A post item"): one // post item of the cut on its own -- its card and attachments played on the @@ -29,27 +21,10 @@ export default async function PostBenchPage({ project, id, search = {} }: { proj } async function postBenchBody({ project, id, search }: { project: ProjectRef; id: string; search: Record<string, string | undefined> }) { - const m = (await readManifest(project.dir)) as Record<string, unknown> | null; - if (!m) notFound(); - const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Array<Record<string, unknown> & { id: string; type?: string }>; - const at = tl.findIndex((e) => e?.type === "post" && e.id === id); - if (at < 0) notFound(); - const entry = tl[at]; - const render = (m.render ?? {}) as Record<string, unknown>; - const box = deckOn(render) - ? (feedOn({ render, posts: (m.posts ?? []) as never[], entries: tl as never[] }) ? feedGeometry(render).footage : deckGeometry(render).footage) - : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) }; - const neighbours = tl.filter((e) => e?.type === "post").map((e) => e.id); - const k = neighbours.indexOf(id); - // What it opens on (post-conversation.mjs): the item before it and the scene its run leaves on screen. - const ctx = planContext(tl, at, render) as { prev: Record<string, unknown> | null; scene: Record<string, unknown> | null }; + const d = await postBenchData(project.dir, id); + if (!d) notFound(); + const { entry, neighbours, index: k } = d; const fromPlay = search.from === "play"; - // Its combo (post-combo.mjs): counted over the whole cut, as the build counts it. - const counted = await projectCombos(project.dir, m, { channelsDir: channelsDirFor(project.dir, m) }).catch(() => ({ combos: {}, groups: [] })); - const combos = counted.combos as Record<string, ComboInfo>; - const combo = combos[id] ?? null; - // Its media scene (post-media-scene.mjs): its neighbours with the same attachment, by the combo's groups. - const scene = mediaSceneOf(tl, at, counted.groups, render); const back = fromPlay ? playHref(project.id, { clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" }); return ( <div className="flex h-full flex-col"> @@ -68,14 +43,14 @@ async function postBenchBody({ project, id, search }: { project: ProjectRef; id: <PostBench project={project.id} entry={entry} - token={await manifestToken(project.dir)} - box={{ width: box.width, height: box.height }} - plan={postItemPlan(panelEntry(sceneEntry(entry, scene), render), render, { ...ctx, mediaScene: ctx.scene ? null : scene }) as unknown as PostPlan} - scene={scene} - render={render} - before={ctx.prev} - conversation={ctx.scene} - combo={combo} + token={d.token} + box={d.box} + plan={d.plan} + scene={d.scene as never} + render={d.render} + before={d.before} + conversation={d.conversation} + combo={d.combo} back={{ href: back, label: fromPlay ? "‹ Back to the cut" : "‹ The Cut tab" }} prev={k > 0 ? neighbours[k - 1] : null} next={k < neighbours.length - 1 ? neighbours[k + 1] : null} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -21,6 +21,8 @@ import ReelPlayPage from "./reel/ReelPlayPage"; import ReelWalkPage from "./reel/ReelWalkPage"; import TrailerPage from "./TrailerPage"; import { isTakeId } from "@/lib/report/takes.mjs"; +import { opensWorkspace } from "@/lib/projects/kinds.mjs"; +import WorkspacePage from "./workspace/WorkspacePage"; // --------------------------------------------------------------------------- // The one place a kind id is matched against a component. @@ -54,7 +56,8 @@ export default async function ProjectView({ return notFound(); } case "report-video": { - if (rest.length === 0) return <ReportProject project={project} search={search} />; + // Its own address is THE WORKSPACE (umtool redesign L7a); `?tab=` (a `note`, the Cut's `all`) the piece page. + if (rest.length === 0) return opensWorkspace(project.kind, search) ? <WorkspacePage project={project} search={search} /> : <ReportProject project={project} search={search} />; // `/browse/<project>/clip/<id>` -- the bench. A view the kind does not // declare is a 404 rather than a page that silently drops half its URL. // `/projects/<project>/post/<id>` -- a post item's bench (report-to-video/post-item.mjs). diff --git a/umtool/components/projects/cutApp/CutApp.tsx b/umtool/components/projects/cutApp/CutApp.tsx @@ -62,9 +62,28 @@ function benchOf(pathname: string, project: string): { id: string; take: string return null; } const clipOf = (pathname: string, project: string): string | null => benchOf(pathname, project)?.id ?? null; -const isPlay = (pathname: string, project: string) => pathname === `/projects/${project.split("/").map(encodeURIComponent).join("/")}/play`; +const playPath = (project: string) => `/projects/${project.split("/").map(encodeURIComponent).join("/")}/play`; -export default function CutApp({ project, playTop, children }: { project: string; playTop: React.ReactNode; children: React.ReactNode }) { +// THE WORKSPACE (umtool redesign L7a) is this app grown: its own address (`home`, the project's) is the +// screen that stays mounted, as Play's is here, and E opens the clip bench over it in place the same way. +export default function CutApp({ + project, + playTop, + children, + home: homeAt, + kind = "play", +}: { + project: string; + playTop: React.ReactNode; + children: React.ReactNode; + /** The address of the view that stays mounted (default: Play's, `/projects/<p>/play`). */ + home?: string; + /** Its frame's `data-bench-shell`. */ + kind?: string; +}) { + const home = homeAt ?? playPath(project); + // The bench's "Back to the cut" names Play's address: inside the workspace that is the workspace too. + const isPlay = useCallback((pathname: string) => pathname === home || pathname === playPath(project), [home, project]); const router = useRouter(); const [view, setView] = useState<View>({ kind: "play" }); const [bench, setBench] = useState<{ key: string; state: "loading" | "ready" | "error"; bench?: Bench; error?: string } | null>(null); @@ -150,16 +169,16 @@ export default function CutApp({ project, playTop, children }: { project: string return; } // Opened straight on a bench entry (a Forward into it): Play's own address. - window.history.pushState({ ...(window.history.state ?? {}), cutApp: 0 }, "", `/projects/${project}/play`); + window.history.pushState({ ...(window.history.state ?? {}), cutApp: 0 }, "", home); setView({ kind: "play" }); returned(); - }, [project, returned]); + }, [home, returned]); /** Every move the bench makes: within the app when it is this project's bench or Play, else a page. */ const navigate = useCallback( (href: string) => { const u = new URL(href, window.location.origin); - if (isPlay(u.pathname, project)) { + if (isPlay(u.pathname)) { backToPlay(); return; } @@ -170,7 +189,7 @@ export default function CutApp({ project, playTop, children }: { project: string } router.push(href); }, - [project, backToPlay, openClip, router], + [project, backToPlay, openClip, router, isPlay], ); // Back / Forward: the address says which view. @@ -178,7 +197,7 @@ export default function CutApp({ project, playTop, children }: { project: string const onPop = () => { const p = window.location.pathname; const st = (window.history.state ?? {}) as { cutApp?: number }; - if (isPlay(p, project)) { + if (isPlay(p)) { depth.current = 0; setView({ kind: "play" }); setBench(null); @@ -195,7 +214,7 @@ export default function CutApp({ project, playTop, children }: { project: string }; window.addEventListener("popstate", onPop); return () => window.removeEventListener("popstate", onPop); - }, [project, load, returned]); + }, [project, load, returned, isPlay]); // A click on an in-app link inside the bench (its head's ‹ prev / next ›, a sibling, Back to the cut): the app's. const onClickCapture = (e: React.MouseEvent) => { @@ -204,7 +223,7 @@ export default function CutApp({ project, playTop, children }: { project: string if (!a || a.target === "_blank") return; const u = new URL(a.href, window.location.origin); if (u.origin !== window.location.origin) return; - if (isPlay(u.pathname, project) || clipOf(u.pathname, project)) { + if (isPlay(u.pathname) || clipOf(u.pathname, project)) { e.preventDefault(); e.stopPropagation(); navigate(`${u.pathname}${u.search}`); @@ -217,7 +236,7 @@ export default function CutApp({ project, playTop, children }: { project: string <Ctx.Provider value={api}> {/* Play: mounted always, hidden (and paused) while the bench is up. */} <div className={view.kind === "play" ? "contents" : "hidden"} data-cut-app-play={view.kind === "play" ? "shown" : "hidden"}> - <BenchFrame kind="play" top={playTop}> + <BenchFrame kind={kind} top={playTop}> {children} </BenchFrame> </div> diff --git a/umtool/components/projects/report/IntroEditor.tsx b/umtool/components/projects/report/IntroEditor.tsx @@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Button } from "@/components/ui/button"; import { Field, Input, Select, Textarea } from "@/components/ui/field"; import IntroCardPlayer, { type IntroPage } from "../review/IntroCardPlayer"; +import { announceManifestChanged } from "../timelineApi"; // THE INTRO ROW of the Cut tab, and its editor (lane intro-play; operator, 8 Nov 2026: "more first-class intro support // (view in play the cut)"): the intro the cut opens on (`render.intro`) as the first row of the cut, and -- Edit -- its @@ -216,6 +217,8 @@ function IntroEditor({ project, state, reload }: { project: string; state: State const next = await reload(); if (next) setDraft(draftOf(next.intro, c.styleDefault)); setSaid({ ok: true, text: value === null ? "Saved: the cut opens on no intro." : "Saved to the manifest." }); + // The draft moved: the workspace's viewer and strip read it again (umtool redesign L7a). + announceManifestChanged(project); } finally { setBusy(false); } diff --git a/umtool/components/projects/workspace/BlockStrip.tsx b/umtool/components/projects/workspace/BlockStrip.tsx @@ -0,0 +1,161 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE STRIP (umtool redesign L7a): the cut as blocks, in the draft's order -- +// the intro, every clip, post item and card, and + at the end. A block's width +// is what it plays for (never under a readable minimum); the one on screen is +// marked, the selected one is the inspector's. +// +// click select it (the viewer goes to its start) +// ← → the block before / after (the workspace's keys) +// Alt+← → move the selected block one place: the timeline's `move`, +// the writer the Cut tab's TimelineList uses, one undo point +// drag a block onto another: it goes to that place (the same write) +// + Add a clip, Add posts, insert a card (the workspace's menu) +// +// The intro is not a timeline entry (render.intro: the build prepends it), so +// it is selected and played like any block but never moved. +// --------------------------------------------------------------------------- + +export type Block = { + id: string; + type: string; + heading: string; + /** Seconds it plays for (the plan's share), 0 when it is skipped. */ + seconds: number; + /** Its index in the manifest's timeline (null: the intro, which is not in it). */ + at: number | null; + rejected?: string | null; + missing?: boolean; +}; + +const TYPE_WORD: Record<string, string> = { clip: "clip", post: "post", teaser: "card", card: "card", intro: "intro", video: "video" }; +const TINT: Record<string, string> = { + clip: "border-[var(--color-line)] bg-[var(--color-panel)]", + post: "border-[color-mix(in_srgb,var(--color-meter)_45%,transparent)] bg-[color-mix(in_srgb,var(--color-meter)_10%,var(--color-panel))]", + teaser: "border-dashed border-[var(--color-line)] bg-[var(--color-panel-2)]", + card: "border-dashed border-[var(--color-line)] bg-[var(--color-panel-2)]", + intro: "border-dashed border-[var(--color-line)] bg-[var(--color-panel-2)]", + video: "border-[var(--color-line)] bg-[var(--color-panel-2)]", +}; + +/** Pixels per second of the strip, and the narrowest a block is drawn. */ +const PX_PER_S = 9; +const MIN_W = 64; +const MAX_W = 260; + +export default function BlockStrip({ + blocks, + selected, + playing, + busy, + onSelect, + onMove, + plus, +}: { + blocks: Block[]; + selected: string | null; + /** The block on screen now. */ + playing: string | null; + busy: boolean; + onSelect: (id: string) => void; + /** Move block `id` to timeline index `to`. */ + onMove: (id: string, at: number, to: number) => void; + /** The + at the end: what it opens. */ + plus: React.ReactNode; +}) { + const ref = useRef<HTMLDivElement | null>(null); + const [drag, setDrag] = useState<string | null>(null); + const [over, setOver] = useState<string | null>(null); + // The selected block kept in view (the keys walk past the strip's edge). + useEffect(() => { + if (!selected) return; + const el = ref.current?.querySelector(`[data-ws-block="${CSS.escape(selected)}"]`) as HTMLElement | null; + el?.scrollIntoView({ block: "nearest", inline: "nearest" }); + }, [selected]); + const byId = new Map(blocks.map((b) => [b.id, b])); + return ( + <div + ref={ref} + role="listbox" + aria-label="The cut's blocks" + aria-orientation="horizontal" + data-ws-strip="" + data-ws-strip-busy={busy ? "" : undefined} + className="flex min-h-0 shrink-0 items-stretch gap-1 overflow-x-auto overflow-y-hidden border-t border-seam bg-ground px-3 py-2" + > + {blocks.map((b, i) => { + const w = Math.round(Math.min(MAX_W, Math.max(MIN_W, b.seconds * PX_PER_S))); + const on = b.id === selected; + const movable = b.at !== null && !busy; + return ( + <button + key={`${b.id}@${i}`} + type="button" + role="option" + aria-selected={on} + data-ws-block={b.id} + data-ws-block-type={b.type} + data-ws-block-at={b.at ?? ""} + data-ws-block-now={b.id === playing ? "" : undefined} + data-ws-block-rejected={b.rejected ? "" : undefined} + draggable={movable} + onDragStart={(e) => { + if (!movable) return; + setDrag(b.id); + e.dataTransfer.effectAllowed = "move"; + e.dataTransfer.setData("text/plain", b.id); + }} + onDragEnd={() => { + setDrag(null); + setOver(null); + }} + onDragOver={(e) => { + if (!drag || drag === b.id || b.at === null) return; + e.preventDefault(); + setOver(b.id); + }} + onDragLeave={() => setOver((o) => (o === b.id ? null : o))} + onDrop={(e) => { + e.preventDefault(); + const from = drag ? byId.get(drag) : null; + setDrag(null); + setOver(null); + if (!from || from.at === null || b.at === null || from.id === b.id) return; + onMove(from.id, from.at, b.at); + }} + onClick={() => onSelect(b.id)} + title={`${b.id} · ${TYPE_WORD[b.type] ?? b.type}${b.seconds ? ` · ${b.seconds.toFixed(1)} s` : ""}${b.heading ? ` · ${b.heading}` : ""}${b.rejected ? ` · rejected: ${b.rejected}` : ""}${b.missing ? " · no media — fetch it" : ""}${b.at !== null ? " · Alt+← → moves it" : ""}`} + style={{ width: w, minWidth: w }} + className={cn( + "relative flex h-[60px] flex-col justify-between overflow-hidden rounded-[3px] border px-1.5 py-1 text-left outline-none transition-colors", + TINT[b.type] ?? TINT.clip, + on && "ring-2 ring-[var(--color-signal)] ring-offset-1 ring-offset-[var(--color-ground)]", + over === b.id && "border-[var(--color-signal)]", + drag === b.id && "opacity-50", + b.rejected && "opacity-60", + "focus-visible:ring-2 focus-visible:ring-[var(--color-signal)]", + )} + > + {b.id === playing && <span aria-hidden className="absolute inset-x-0 top-0 h-0.5 bg-[var(--color-signal)]" />} + <span className="flex items-baseline gap-1"> + <span className={cn("truncate font-mono text-[11.5px] font-medium text-text", b.rejected && "line-through")}>{b.id}</span> + <span className="ml-auto shrink-0 text-[10px] uppercase tracking-[0.06em] text-muted">{TYPE_WORD[b.type] ?? b.type}</span> + </span> + <span className="truncate text-[11px] leading-tight text-text-2">{b.heading || " "}</span> + <span className="flex items-baseline gap-1 font-mono text-[10.5px] text-muted"> + {b.seconds ? `${b.seconds.toFixed(1)} s` : b.rejected ? "skipped" : ""} + {b.missing && <span className="text-[var(--color-dirty)]">no media</span>} + </span> + </button> + ); + })} + <div className="flex shrink-0 items-stretch" data-ws-plus-slot=""> + {plus} + </div> + </div> + ); +} diff --git a/umtool/components/projects/workspace/Workspace.tsx b/umtool/components/projects/workspace/Workspace.tsx @@ -0,0 +1,508 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { clipBenchHref, postBenchHref } from "@/lib/hrefs"; +import { runningTime, startOf } from "@/lib/report/playCut.mjs"; +import { PlayStage, usePlayCore } from "../review/playCore"; +import type { PlayViewData } from "../review/PlayCut"; +import { useCutApp } from "../cutApp/CutApp"; +import { MANIFEST_CHANGED, refusalOf, timelineOp } from "../timelineApi"; +import { AddClipToggle } from "../AddClip"; +import AddPosts from "../AddPosts"; +import TeaserInspector from "../inspector/TeaserInspector"; +import BlockStrip, { type Block } from "./BlockStrip"; +import WorkspaceInspector from "./WorkspaceInspector"; +import WorkspaceTop, { type UndoState } from "./WorkspaceTop"; + +// --------------------------------------------------------------------------- +// THE WORKSPACE (umtool redesign L7a): a report video's ONE screen, at its own +// address (`/projects/<p>`). Fits 1366×768 with nothing scrolling but the +// inspector and the strip: +// +// top bar WorkspaceTop: the title, "Draft · from vN · N edits", the +// versions, the mode switch, Look, Render, Share, Undo / Redo +// viewer Play's player core (review/playCore.tsx, the same one Play +// draws -- no fork): the draft, live, the intro included +// strip the cut as blocks (BlockStrip): select one, move it +// inspector chosen by the selected block (WorkspaceInspector); under +// ~900 px wide a sheet at the bottom +// +// Every edit lands in THE DRAFT (video.manifest.json) with its own undo point; +// Undo takes back the newest whatever wrote it (`umtool timeline <p> undo`), +// Redo puts it back while nothing was edited since (`… redo`). The workspace +// reads the draft again (GET /api/report/play-view) whenever a panel announces +// a write (MANIFEST_CHANGED), and the deck recomposes when its token moved. +// +// THE CutApp SHELL, grown: E opens the clip bench IN PLACE over the workspace +// (cutApp/CutApp.tsx, `home` the workspace's address) -- the viewer stays +// mounted, paused, everything it composed kept -- and Back returns here. +// +// THE KEYS (the inspector's bench keeps its own while the focus is in it): +// Space play / pause · ← → the block before / after · Alt+← → move the +// selected block · E edit it in place · Esc nothing selected (the project's +// panels) · ⌘Z / Ctrl+Z undo · ⌘⇧Z / Ctrl+Y redo · ? the keys · ⌘K the +// palette (shell/JumpPalette.tsx), as everywhere. +// --------------------------------------------------------------------------- + +/** The + block: the inspector's add panels. */ +const ADD = "+"; + +const KEYS: { keys: string; what: string }[] = [ + { keys: "Space", what: "play / pause" }, + { keys: "← →", what: "the block before / after (selected; the viewer goes to it)" }, + { keys: "Alt+← →", what: "move the selected block one place" }, + { keys: "E", what: "edit the selected clip in place (the full bench; Back returns here)" }, + { keys: "Esc", what: "nothing selected: the project's panels" }, + { keys: "⌘Z Ctrl+Z", what: "undo the newest edit to the draft" }, + { keys: "⌘⇧Z Ctrl+Y", what: "redo" }, + { keys: "⌘K", what: "the command palette" }, + { keys: "?", what: "these keys" }, +]; + +type Timeline = { token: string | null; ids: string[] }; + +export default function Workspace({ view: served, initialBlock = null, introWritten = null, hasLedger = false }: { view: PlayViewData; initialBlock?: string | null; introWritten?: unknown; hasLedger?: boolean }) { + const router = useRouter(); + const [view, setView] = useState(served); + useEffect(() => setView(served), [served]); + const project = view.project; + const reloadSeq = useRef(0); + const reloadView = useCallback(async () => { + const mine = ++reloadSeq.current; + try { + const r = await fetch(`/api/report/play-view?${new URLSearchParams({ project }).toString()}`, { cache: "no-store" }); + const j = (await r.json()) as PlayViewData & { error?: string }; + if (mine === reloadSeq.current && r.ok && !j.error) setView(j); + } catch { + // The view stays as it was. + } + }, [project]); + + // The one app (CutApp): the bench opened in place over the workspace; the keys are the workspace's only while it shows. + const app = useCutApp(); + const shown = !app || app.view === "play"; + const shownRef = useRef(shown); + shownRef.current = shown; + useEffect(() => app?.onReturn(() => void reloadView()), [app, reloadView]); + + const core = usePlayCore(view); + const { engine, plan, planRef } = core; + const { ui } = engine; + const now = engine.now; + const setPlaying = engine.setPlaying; + useEffect(() => { + if (!shown) setPlaying(false); + }, [shown, setPlaying]); + + // ---- the timeline's order and token (TimelineList's: the writer the strip moves with) ---- + const tl = useRef<Timeline>({ token: null, ids: [] }); + const [tlIds, setTlIds] = useState<string[]>([]); + const loadTimeline = useCallback(async () => { + const r = await fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as { token?: string; timeline?: { id: string }[] }; + if (r.ok) { + tl.current = { token: typeof j.token === "string" ? j.token : null, ids: Array.isArray(j.timeline) ? j.timeline.map((e) => e.id) : [] }; + setTlIds(tl.current.ids); + } + return tl.current; + }, [project]); + useEffect(() => { + void loadTimeline(); + }, [loadTimeline, view.token]); + + // ---- what writes the draft from here: Undo, Redo, a move --------------------------- + const [undo, setUndo] = useState<UndoState>({ busy: false, said: null, error: false, canRedo: false }); + /** Bumped by the workspace's own structural writes: the inspector's panels are read afresh. */ + const [epoch, setEpoch] = useState(0); + const ownWrite = useRef(false); + const write = useCallback( + async (op: string, args: Record<string, unknown> = {}) => { + setUndo((u) => ({ ...u, busy: true, said: null, error: false })); + const token = tl.current.token ?? (await loadTimeline()).token; + const res = await timelineOp(project, token, op, args); + if (!res.ok) { + setUndo((u) => ({ ...u, busy: false, said: refusalOf(res), error: true, canRedo: op === "undo" ? u.canRedo : op === "redo" ? false : u.canRedo })); + if (res.json.stale) await loadTimeline(); + return null; + } + tl.current.token = typeof res.json.token === "string" ? res.json.token : null; + ownWrite.current = true; + setEpoch((n) => n + 1); + await Promise.all([reloadView(), loadTimeline()]); + return res.json; + }, + [project, loadTimeline, reloadView], + ); + const doUndo = useCallback(async () => { + const j = await write("undo"); + if (j) setUndo({ busy: false, said: `Undone: ${String(j.op ?? "the last edit")}`, error: false, canRedo: true }); + }, [write]); + const doRedo = useCallback(async () => { + const j = await write("redo"); + if (j) setUndo((u) => ({ busy: false, said: `Redone: ${String(j.op ?? "")}`, error: false, canRedo: u.canRedo })); + }, [write]); + // A write elsewhere on the page (an inspector panel, the bench, Add a clip): the draft read again, and a + // Redo is gone (an edit since the undo ends it). + useEffect(() => { + let t: ReturnType<typeof setTimeout> | null = null; + const on = (e: Event) => { + if ((e as CustomEvent).detail?.project !== project) return; + if (ownWrite.current) { + ownWrite.current = false; + return; + } + setUndo((u) => ({ ...u, canRedo: false, said: null })); + if (t) clearTimeout(t); + t = setTimeout(() => { + void reloadView(); + void loadTimeline(); + }, 120); + }; + window.addEventListener(MANIFEST_CHANGED, on); + return () => { + window.removeEventListener(MANIFEST_CHANGED, on); + if (t) clearTimeout(t); + }; + }, [project, reloadView, loadTimeline]); + + // ---- the blocks ------------------------------------------------------------------ + const itemOf = useMemo(() => new Map(plan.items.map((it, i) => [it.id, { it, i }])), [plan.items]); + const blocks = useMemo<Block[]>(() => { + const at = new Map(tlIds.map((id, i) => [id, i])); + return view.entries.map((e) => { + const p = itemOf.get(e.id); + return { + id: e.id, + type: e.type, + heading: e.type === "clip" ? (e.quote ?? e.heading ?? "") : (e.heading ?? ""), + seconds: p ? Math.max(0, p.it.to - p.it.from) : 0, + at: e.type === "intro" ? null : (at.get(e.id) ?? null), + rejected: e.rejected?.label ?? null, + missing: e.type === "clip" && !e.media, + }; + }); + }, [view.entries, itemOf, tlIds]); + const entryOf = core.entryOf; + + // ---- the selection (the inspector's block), kept in the URL (`?block=`) ---------------- + const [selected, setSelected] = useState<string | null>(initialBlock && (initialBlock === ADD || view.entries.some((e) => e.id === initialBlock)) ? initialBlock : null); + useEffect(() => { + if (!shownRef.current) return; + const u = new URL(window.location.href); + if (selected) u.searchParams.set("block", selected); + else u.searchParams.delete("block"); + const h = `${u.pathname}${u.search}${u.hash}`; + if (h !== `${window.location.pathname}${window.location.search}${window.location.hash}`) window.history.replaceState(window.history.state, "", h); + }, [selected]); + // A block that left the cut (an undo, a reject): nothing selected. + useEffect(() => { + if (selected && selected !== ADD && !view.entries.some((e) => e.id === selected)) setSelected(null); + }, [view.entries, selected]); + const select = useCallback( + (id: string | null) => { + setSelected(id); + if (!id || id === ADD) return; + const p = itemOf.get(id); + if (p) engine.seekTo(startOf(planRef.current, p.i)); + }, + [itemOf, engine, planRef], + ); + const step = useCallback( + (d: 1 | -1) => { + if (!blocks.length) return; + const i = selected ? blocks.findIndex((b) => b.id === selected) : -1; + const base = i >= 0 ? i : d > 0 ? -1 : blocks.length; + const to = Math.max(0, Math.min(blocks.length - 1, base + d)); + select(blocks[to].id); + }, + [blocks, selected, select], + ); + const move = useCallback( + async (id: string, at: number, to: number) => { + if (to < 0 || to >= tl.current.ids.length || to === at) return; + const j = await write("move", { id, at, toIndex: to }); + if (j) setUndo({ busy: false, said: `Moved ${id}`, error: false, canRedo: false }); + }, + [write], + ); + const moveSelected = useCallback( + (d: 1 | -1) => { + const b = blocks.find((x) => x.id === selected); + if (!b || b.at === null || undo.busy) return; + void move(b.id, b.at, b.at + d); + }, + [blocks, selected, move, undo.busy], + ); + + // ---- edit in place (E): the clip bench over the workspace, Back returns here ---------- + const editHere = useCallback(() => { + const id = selected && selected !== ADD ? selected : (core.item?.id ?? null); + const e = id ? entryOf.get(id) : null; + if (!e) return; + const p = itemOf.get(e.id); + const at = p ? Math.round(Math.max(0, now().t - p.it.from) * 100) / 100 : 0; + setPlaying(false); + if (e.type === "post") { + router.push(postBenchHref(project, e.id, { play: { at } })); + return; + } + if (e.type !== "clip") return; + const h = clipBenchHref(project, e.id, { play: { at, take: null } }); + if (app) app.openClip(e.id, h); + else router.push(h); + }, [selected, core.item, entryOf, itemOf, now, setPlaying, router, project, app]); + + // ---- the keys --------------------------------------------------------------------- + const [help, setHelp] = useState(false); + useEffect(() => { + const onKey = (ev: KeyboardEvent) => { + if (!shownRef.current) return; + const tgt = ev.target as HTMLElement | null; + if (ev.key === "Escape" && help) { + setHelp(false); + return; + } + if (tgt?.closest("input, textarea, select, [contenteditable=true], [data-ws-own-keys], [role=dialog]")) return; + const k = ev.key; + const mod = ev.metaKey || ev.ctrlKey; + if (mod && !ev.altKey && (k === "z" || k === "Z")) { + if (ev.shiftKey) void doRedo(); + else void doUndo(); + ev.preventDefault(); + return; + } + if (mod && !ev.altKey && (k === "y" || k === "Y") && ev.ctrlKey) { + void doRedo(); + ev.preventDefault(); + return; + } + if (mod) return; + if (ev.altKey) { + if (k === "ArrowLeft") moveSelected(-1); + else if (k === "ArrowRight") moveSelected(1); + else return; + ev.preventDefault(); + return; + } + if (k === " ") setPlaying(!now().playing); + else if (k === "ArrowLeft") step(-1); + else if (k === "ArrowRight") step(1); + else if (k === "e" || k === "E") editHere(); + else if (k === "Escape") setSelected(null); + else if (k === "?") setHelp((h) => !h); + else return; + ev.preventDefault(); + }; + // Space on a focused button would click it too on keyup: the key is the transport's here. + const onUp = (ev: KeyboardEvent) => { + if (!shownRef.current) return; + const tgt = ev.target as HTMLElement | null; + if (ev.key === " " && !tgt?.closest("input, textarea, select, [contenteditable=true], [data-ws-own-keys]")) ev.preventDefault(); + }; + window.addEventListener("keydown", onKey); + window.addEventListener("keyup", onUp); + return () => { + window.removeEventListener("keydown", onKey); + window.removeEventListener("keyup", onUp); + }; + }, [help, doUndo, doRedo, moveSelected, setPlaying, now, step, editHere]); + + // ---- the viewer's size: 16:9 in what the column leaves it -------------------------------- + const stageBox = useRef<HTMLDivElement | null>(null); + const [stageW, setStageW] = useState<number | null>(null); + useEffect(() => { + const el = stageBox.current; + if (!el) return; + const fit = () => { + const r = el.getBoundingClientRect(); + setStageW(Math.max(160, Math.floor(Math.min(r.width, (r.height * 16) / 9)))); + }; + fit(); + const ro = new ResizeObserver(fit); + ro.observe(el); + return () => ro.disconnect(); + }, []); + + // ---- the sheet (under ~900 px): the inspector folds to its head ------------------------- + const [sheetOpen, setSheetOpen] = useState(true); + + const selEntry = selected && selected !== ADD ? (entryOf.get(selected) ?? null) : null; + const firstClip = view.entries.find((e) => e.type === "clip" && !e.rejected)?.id ?? null; + const shareClip = selEntry?.type === "clip" ? selEntry.id : core.item?.clip ? core.item.id : firstClip; + const postChannels = useMemo( + () => [...new Set(view.entries.filter((e) => e.type === "post").map((e) => String((e.post as { post?: unknown } | undefined)?.post ?? "").split("/")[0]).filter(Boolean))], + [view.entries], + ); + const iconBtn = cn(buttonVariants({ variant: "outline", size: "sm" }), "min-w-9 font-mono"); + const t = core.t; + const item = core.item; + + return ( + <div + data-workspace={project} + data-ws-selected={selected ?? ""} + className="flex min-h-0 flex-1 flex-col overflow-hidden max-[899px]:pb-[44px]" + > + <WorkspaceTop + project={project} + title={view.title} + draftLine={view.draft?.line ?? "Draft"} + draftParent={view.draft?.parent ?? null} + draftEdits={view.draft?.edits ?? null} + versions={view.takes} + basic={!!view.basic} + firstClip={firstClip} + shareClip={shareClip} + undo={undo} + onUndo={() => void doUndo()} + onRedo={() => void doRedo()} + onChanged={() => void reloadView()} + help={() => setHelp(true)} + /> + <div className="grid min-h-0 flex-1 grid-cols-1 min-[900px]:grid-cols-[minmax(0,1fr)_minmax(340px,420px)]"> + {/* ---- the viewer, its transport, the strip ---- */} + <section className="flex min-h-0 min-w-0 flex-col" aria-label="The draft"> + <div + // What Play's root carries, for the same reads: the state, the second, the block on screen. + data-ws-viewer="" + data-play-state={ui.ended ? "ended" : ui.playing ? (ui.waiting ? "waiting" : "playing") : "paused"} + data-play-t={String(Math.round(t * 100) / 100)} + data-play-item={item?.id ?? ""} + data-play-compose={core.composeState} + data-play-edges={core.edges.state} + data-play-basic={view.basic ? "" : undefined} + ref={stageBox} + className="flex min-h-[120px] flex-1 items-center justify-center overflow-hidden px-3 pt-2" + > + <div className="relative w-full" style={stageW ? { width: stageW } : undefined}> + <PlayStage core={core} basic={!!view.basic} /> + </div> + </div> + <div className="flex flex-wrap items-center gap-1.5 px-3 py-1.5 text-[12px]" data-ws-transport=""> + <button type="button" className={iconBtn} onClick={() => step(-1)} title="the block before (←)" aria-label="previous block" data-ws-prev=""> + ‹ + </button> + <button type="button" className={cn(iconBtn, "min-w-20")} onClick={() => setPlaying(!ui.playing)} title="play / pause (Space)" data-ws-play=""> + {ui.playing ? "Pause" : ui.ended ? "Play again" : "Play"} + </button> + <button type="button" className={iconBtn} onClick={() => step(1)} title="the block after (→)" aria-label="next block" data-ws-next=""> + › + </button> + <span className="font-mono text-[12.5px] tabular-nums text-text" data-ws-clock=""> + {runningTime(t)} <span className="text-muted">/ {runningTime(plan.total)}</span> + </span> + {item && ( + <span className="min-w-0 truncate font-mono text-[11.5px] text-muted" data-ws-readout=""> + {ui.cur + 1}/{plan.items.length} · {item.id} + </span> + )} + <button + type="button" + className={cn(buttonVariants({ variant: "quiet", size: "sm" }))} + disabled={!(selEntry ?? (item ? entryOf.get(item.id) : null)) || !["clip", "post"].includes((selEntry ?? (item ? entryOf.get(item.id) : null))?.type ?? "")} + onClick={editHere} + data-ws-edit-here="" + title="the selected clip on the full bench, in place (E): Back returns here" + > + Edit in place + </button> + <span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted"> + {core.composeState === "composing" && <span>composing the chrome…</span>} + {core.composeState === "no-deck" && <span>{view.basic ? "basic: the footage alone" : "no on-screen deck"}</span>} + {core.composeState === "error" && <span className="text-reject-text">the chrome did not compose: {core.composeError}</span>} + {ui.waiting && <span data-ws-waiting="">loading…</span>} + </span> + </div> + <BlockStrip + blocks={blocks} + selected={selected} + playing={item?.id ?? null} + busy={undo.busy} + onSelect={(id) => select(id)} + onMove={(id, at, to) => void move(id, at, to)} + plus={ + <button + type="button" + onClick={() => setSelected(selected === ADD ? null : ADD)} + aria-pressed={selected === ADD} + data-ws-plus="" + title="add to the cut: a clip, posts, a teaser or closing card" + className={cn( + "flex h-[60px] w-[56px] items-center justify-center rounded-[3px] border border-dashed text-[20px]", + selected === ADD ? "border-[var(--color-signal)] text-text" : "border-seam-2 text-muted hover:text-text", + )} + > + + + </button> + } + /> + </section> + + {/* ---- the inspector (a sheet at the bottom under ~900 px) ---- */} + <aside + aria-label="Inspector" + data-ws-inspector={selected === ADD ? "add" : (selEntry?.type ?? "project")} + data-ws-sheet={sheetOpen ? "open" : "closed"} + className={cn( + "min-h-0 min-w-0 overflow-y-auto border-seam bg-panel min-[900px]:border-l", + "max-[899px]:fixed max-[899px]:inset-x-0 max-[899px]:bottom-0 max-[899px]:z-40 max-[899px]:border-t max-[899px]:shadow-[0_-6px_24px_rgba(0,0,0,0.25)]", + sheetOpen ? "max-[899px]:max-h-[55dvh]" : "max-[899px]:max-h-[44px] max-[899px]:overflow-hidden", + )} + > + <button type="button" className="flex w-full items-center gap-2 border-b border-seam px-3 py-2 text-left text-[12px] text-text-2 min-[900px]:hidden" onClick={() => setSheetOpen((o) => !o)} aria-expanded={sheetOpen} data-ws-sheet-toggle=""> + <span className="micro">Inspector</span> + <span className="font-mono">{selected === ADD ? "add" : (selected ?? "the project")}</span> + <span className="ml-auto">{sheetOpen ? "▾" : "▴"}</span> + </button> + <div key={`${selected ?? "-"}:${epoch}`}> + {selected === ADD ? ( + <AddPanels project={project} after={blocks.length ? blocks[blocks.length - 1].id : null} channels={postChannels} /> + ) : ( + <WorkspaceInspector project={project} entry={selEntry} hasLedger={hasLedger} hasClips={!!firstClip} introWritten={introWritten} /> + )} + </div> + </aside> + </div> + + {help && ( + <div role="dialog" aria-modal="true" aria-label="Keys" className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 p-4" onClick={() => setHelp(false)} data-ws-keys=""> + <div className="w-full max-w-[440px] rounded-[3px] border border-seam-2 bg-panel p-4 text-[12.5px] text-text-2" onClick={(e) => e.stopPropagation()}> + <div className="mb-2 flex items-center"> + <h2 className="micro m-0">Keys</h2> + <button type="button" autoFocus onClick={() => setHelp(false)} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}> + Close + </button> + </div> + <dl className="m-0 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1"> + {KEYS.map((k) => ( + <div key={k.keys} className="contents"> + <dt className="font-mono text-text">{k.keys}</dt> + <dd className="m-0">{k.what}</dd> + </div> + ))} + </dl> + </div> + </div> + )} + </div> + ); +} + +/** +: what is added to the cut -- a clip (found, in/out on its cues), posts, a teaser or closing card. */ +function AddPanels({ project, after, channels }: { project: string; after: string | null; channels: string[] }) { + return ( + <div className="space-y-3 px-3 py-2" data-ws-add=""> + <div className="flex items-baseline gap-2 border-b border-seam pb-1.5"> + <span className="micro">Add to the cut</span> + </div> + <div className="flex flex-wrap items-center gap-1.5 text-[12px]"> + <AddClipToggle project={project} after={after} where="workspace" label="+ Add a clip" open /> + </div> + <AddPosts project={project} channels={channels} /> + <TeaserInspector project={project} /> + </div> + ); +} diff --git a/umtool/components/projects/workspace/WorkspaceInspector.tsx b/umtool/components/projects/workspace/WorkspaceInspector.tsx @@ -0,0 +1,193 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useState } from "react"; +import { clipBenchHref, ingredientHref, postBenchHref } from "@/lib/hrefs"; +import ClipBench, { type ClipBenchData } from "../ClipBench"; +import PostBench from "../PostBench"; +import type { PostBenchData } from "@/lib/report/postBenchData"; +import IntroRow from "../report/IntroEditor"; +import TeaserInspector from "../inspector/TeaserInspector"; +import PostItemInspector from "../inspector/PostItemInspector"; +import TitleInspector from "../inspector/TitleInspector"; +import ProvenanceInspector from "../inspector/ProvenanceInspector"; +import LedgerInspector from "../inspector/LedgerInspector"; +import LinksInspector from "../inspector/LinksInspector"; +import StillInspector from "../inspector/StillInspector"; +import type { PlayEntry } from "../review/PlayCut"; + +// --------------------------------------------------------------------------- +// THE INSPECTOR (umtool redesign L7a): one column, chosen by the selected block. +// +// a clip the clip bench's work column (ClipBench, layout "inspector": the window row, the +// instrument -- the waveform, its handles, the gaps -- and the cue rail), its life cycle +// a post item the post item panel (L6: excerpt, media, recording) and the post bench (PostBench, +// layout "inspector": its attachments' trims, sound, crop, its hold) +// a card/teaser the teaser panel (L6) +// the intro the intro editor (L2) +// nothing the project's panels (L6): title, provenance, ledger, links, a still +// +// Every panel is the one its page draws, mounted here unchanged (no fork), and every write lands in the +// draft with its own undo point (the workspace's Undo takes it back). Each reads its own state from its +// own route; the workspace reads the draft again when one announces a write (MANIFEST_CHANGED). +// --------------------------------------------------------------------------- + +type Loaded<T> = { key: string; state: "loading" | "ready" | "error"; data?: T; error?: string }; + +function useJson<T>(url: string | null): Loaded<T> | null { + const [got, setGot] = useState<Loaded<T> | null>(null); + useEffect(() => { + if (!url) { + setGot(null); + return; + } + let live = true; + setGot({ key: url, state: "loading" }); + void (async () => { + try { + const r = await fetch(url, { cache: "no-store" }); + const j = (await r.json().catch(() => ({}))) as T & { error?: string }; + if (!live) return; + if (!r.ok) setGot({ key: url, state: "error", error: j.error ?? `HTTP ${r.status}` }); + else setGot({ key: url, state: "ready", data: j }); + } catch (e) { + if (live) setGot({ key: url, state: "error", error: e instanceof Error ? e.message : String(e) }); + } + })(); + return () => { + live = false; + }; + }, [url]); + return got && got.key === url ? got : url ? { key: url, state: "loading" } : null; +} + +function Head({ kind, id, children }: { kind: string; id?: string | null; children?: React.ReactNode }) { + return ( + <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1 border-b border-seam px-3 py-2"> + <span className="micro">{kind}</span> + {id ? <span className="font-mono text-[13px] font-medium text-text">{id}</span> : null} + <span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px]">{children}</span> + </div> + ); +} + +const Waiting = ({ what }: { what: string }) => <p className="m-0 px-3 py-2 text-[12px] text-muted" data-ws-inspector-loading="">reading {what}…</p>; +const Failed = ({ error }: { error: string }) => <p className="m-0 px-3 py-2 text-[12px] text-reject-text" role="alert">{error}</p>; + +function ClipInspector({ project, entry }: { project: string; entry: PlayEntry }) { + const url = `/api/report/bench?${new URLSearchParams({ project, clip: entry.id, order: "cut" }).toString()}`; + const got = useJson<{ data: ClipBenchData }>(url); + return ( + <> + <Head kind="Clip" id={entry.id}> + {/* The clip's recording across its life cycle (lane L5): found, downloaded, … published. */} + {entry.video && entry.sourceChannel && ( + <Link href={ingredientHref(entry.sourceChannel, entry.video)} prefetch={false} data-ws-life="" className="text-muted-2 hover:text-text" title="this clip's recording across its life cycle: found, downloaded, transcribed, its windows, every cut that uses it, checked, rendered, published"> + Life cycle + </Link> + )} + <Link href={clipBenchHref(project, entry.id)} prefetch={false} className="text-muted-2 hover:text-text" data-ws-full-bench="" title="the whole clip bench on its own page: the claim, the verdict, the attribution"> + Full bench + </Link> + </Head> + {entry.quote ? <p className="m-0 border-b border-seam px-3 py-1.5 font-serif text-[13px] leading-snug text-text-2">“{entry.quote}”</p> : null} + <div className="px-3 py-2"> + {!got || got.state === "loading" ? <Waiting what="the clip" /> : got.state === "error" ? <Failed error={got.error ?? ""} /> : <ClipBench key={entry.id} data={got.data!.data} layout="inspector" />} + </div> + </> + ); +} + +function PostInspector({ project, entry }: { project: string; entry: PlayEntry }) { + const url = `/api/report/post-bench?${new URLSearchParams({ project, id: entry.id }).toString()}`; + const got = useJson<PostBenchData>(url); + const d = got?.state === "ready" ? got.data! : null; + return ( + <> + <Head kind="Post" id={entry.id}> + <Link href={postBenchHref(project, entry.id)} prefetch={false} className="text-muted-2 hover:text-text" data-ws-full-bench="" title="the post bench on its own page"> + Full bench + </Link> + </Head> + <div className="space-y-2 px-3 py-2"> + {/* The excerpt picked by selection, media on/off, "use my recording" (L6). */} + <PostItemInspector project={project} block={entry.id} /> + {!got || got.state === "loading" ? ( + <Waiting what="the post bench" /> + ) : got.state === "error" ? ( + <Failed error={got.error ?? ""} /> + ) : ( + d && ( + <PostBench + key={`${entry.id}:${d.token ?? ""}`} + layout="inspector" + project={project} + entry={d.entry} + token={d.token} + box={d.box} + plan={d.plan} + scene={d.scene as never} + render={d.render} + before={d.before} + conversation={d.conversation} + combo={d.combo} + back={{ href: "", label: "" }} + prev={null} + next={null} + fromPlay={false} + /> + ) + )} + </div> + </> + ); +} + +export default function WorkspaceInspector({ project, entry, hasLedger, hasClips, introWritten }: { project: string; entry: PlayEntry | null; hasLedger: boolean; hasClips: boolean; introWritten: unknown }) { + if (entry?.type === "clip") return <ClipInspector project={project} entry={entry} />; + if (entry?.type === "post") return <PostInspector project={project} entry={entry} />; + if (entry?.type === "teaser") { + return ( + <> + <Head kind="Card" id={entry.id} /> + <div className="px-3 py-2"> + <TeaserInspector project={project} block={entry.id} /> + </div> + </> + ); + } + if (entry?.type === "intro") { + return ( + <> + <Head kind="Intro" id={null} /> + <div className="px-3 py-2"> + <IntroRow project={project} written={introWritten} open /> + </div> + </> + ); + } + if (entry) { + // A card the build draws (a chapter card, a video entry): nothing of its own to inspect here yet. + return ( + <> + <Head kind={entry.type} id={entry.id} /> + <p className="m-0 px-3 py-2 text-[12px] text-muted" data-ws-inspector-none={entry.type}> + {entry.heading ? `“${entry.heading}”. ` : ""}A {entry.type} is edited on the Cut tab. + </p> + </> + ); + } + // Nothing selected: the project's own panels. + return ( + <> + <Head kind="Project" /> + <div className="space-y-2 px-3 py-2" data-ws-project-panels=""> + <TitleInspector project={project} /> + <ProvenanceInspector project={project} /> + {hasClips && <LinksInspector project={project} />} + {hasLedger && <LedgerInspector project={project} />} + <StillInspector project={project} /> + </div> + </> + ); +} diff --git a/umtool/components/projects/workspace/WorkspacePage.tsx b/umtool/components/projects/workspace/WorkspacePage.tsx @@ -0,0 +1,33 @@ +import type { ProjectRef } from "@/lib/project-types"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { playView } from "@/lib/report/playView.mjs"; +import { workspaceHref } from "@/lib/hrefs"; +import { NotesProvider } from "@/components/notes/NotesProvider"; +import { RememberCut } from "@/components/shell/RecentCuts"; +import CutApp from "../cutApp/CutApp"; +import ReportProject from "../ReportProject"; +import type { PlayViewData } from "../review/PlayCut"; +import Workspace from "./Workspace"; + +// `/projects/<project>` for a report video -- THE WORKSPACE (umtool redesign L7a; components/projects/workspace/ +// Workspace.tsx): the draft playing, its blocks, the inspector, one screen. `?block=<id>` opens with that block +// selected. A project whose draft cannot be read is the piece page, which says why. The piece page's tabs stay +// at `?tab=` (lib/projects/kinds.mjs opensWorkspace). +export default async function WorkspacePage({ project, search }: { project: ProjectRef; search: Record<string, string | undefined> }) { + const [view, m] = await Promise.all([playView(project, {}), readManifest(project.dir).catch(() => null)]); + if ("error" in view) return <ReportProject project={project} search={{ ...search, tab: "overview" }} />; + const manifest = (m ?? {}) as { render?: { intro?: unknown }; ledger?: unknown; ledgerSchema?: unknown }; + return ( + <CutApp project={project.id} home={workspaceHref(project.id)} kind="workspace" playTop={null}> + <RememberCut project={project.id} title={(view as PlayViewData).title || project.name || project.id} /> + <NotesProvider target={{ project: project.id }}> + <Workspace + view={view as PlayViewData} + initialBlock={search.block ?? null} + introWritten={manifest.render?.intro ?? null} + hasLedger={Array.isArray(manifest.ledger) || !!manifest.ledgerSchema} + /> + </NotesProvider> + </CutApp> + ); +} diff --git a/umtool/components/projects/workspace/WorkspaceTop.tsx b/umtool/components/projects/workspace/WorkspaceTop.tsx @@ -0,0 +1,311 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { Mark } from "@/components/shell/Wordmark"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { clipBenchHref, openInDraftHref, playHref, presentHref, projectHref, projectsHref, takesHref } from "@/lib/hrefs"; +import { PIECE_TABS } from "@/lib/pieces/tabs.mjs"; +import CopyShareLine from "../CopyShareLine"; +import { startTakeJob } from "../NewTakePanel"; +import { announceManifestChanged } from "../timelineApi"; + +// --------------------------------------------------------------------------- +// THE WORKSPACE'S TOP BAR (umtool redesign L7a), one row: +// +// ← Projects / <title> · Draft · from vN · N edits · Versions ▾ · Edit | Review pass | Present ⛶ +// · Look Basic|Deck · Render ▾ · Share · Undo Redo · Piece ▾ +// +// Versions ▾ lists every saved version (and legacy take): Play it read-only, Open it in the draft (it asks +// first, and saves the draft as a version when it has edits -- OpenInDraftPage), and Save version (the +// draft frozen as the next vN: `umtool takes save`). The mode switch's Review pass and Present go to +// today's walk and present pages until L7b brings them in here. Look writes render.mode (`umtool look +// <p> mode=basic|deck`); Render queues a take of the draft (`umtool take`); Share copies the share line +// of the selected clip (`umtool share`). Piece ▾ is the piece page's tabs (Sources, Deliver, History …). +// --------------------------------------------------------------------------- + +type Version = { id: string; label: string; made: boolean }; + +const btn = (variant: "outline" | "quiet" | "pressed" = "quiet") => cn(buttonVariants({ variant, size: "sm" })); + +/** A <details> popover that closes on a click outside and on Escape. */ +function Menu({ label, testid, children, align = "left", title }: { label: React.ReactNode; testid: string; children: (close: () => void) => React.ReactNode; align?: "left" | "right"; title?: string }) { + const ref = useRef<HTMLDetailsElement | null>(null); + const [open, setOpen] = useState(false); + const close = useCallback(() => { + if (ref.current) ref.current.open = false; + setOpen(false); + }, []); + useEffect(() => { + if (!open) return; + const onDown = (e: MouseEvent) => { + if (ref.current && !ref.current.contains(e.target as Node)) close(); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") close(); + }; + window.addEventListener("mousedown", onDown); + window.addEventListener("keydown", onKey); + return () => { + window.removeEventListener("mousedown", onDown); + window.removeEventListener("keydown", onKey); + }; + }, [open, close]); + return ( + <details ref={ref} className="relative" {...{ [`data-ws-${testid}`]: open ? "open" : "" }} onToggle={(e) => setOpen((e.currentTarget as HTMLDetailsElement).open)}> + <summary className={cn(btn("quiet"), "cursor-pointer list-none")} title={title}> + {label} + </summary> + <div className={cn("absolute top-full z-50 mt-1 min-w-[260px] max-w-[min(420px,92vw)] rounded-[3px] border border-seam-2 bg-panel p-1.5 text-[12px] shadow-lg", align === "right" ? "right-0" : "left-0")}> + {open ? children(close) : null} + </div> + </details> + ); +} + +function VersionsMenu({ project, versions, onSaved }: { project: string; versions: Version[]; onSaved: () => void }) { + const [state, setState] = useState<{ busy: boolean; said: string | null; error: boolean }>({ busy: false, said: null, error: false }); + const save = async () => { + setState({ busy: true, said: null, error: false }); + const r = await fetch("/api/report/takes/save", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project }) }); + const j = (await r.json().catch(() => ({}))) as { saved?: boolean; id?: string; why?: string; error?: string }; + if (!r.ok) return setState({ busy: false, said: j.error ?? `HTTP ${r.status}`, error: true }); + setState({ busy: false, said: j.saved ? `saved as ${j.id}` : (j.why ?? "nothing to save"), error: false }); + onSaved(); + }; + return ( + <Menu label={<>Versions{versions.length ? ` (${versions.length})` : ""} ▾</>} testid="versions" title="saved versions of the draft: play one read-only, open one in the draft, save the draft as the next"> + {() => ( + <div className="flex flex-col gap-1"> + <div className="flex items-center gap-2 border-b border-seam px-1 pb-1.5"> + <button type="button" className={btn("outline")} disabled={state.busy} onClick={() => void save()} data-save-version="" title="freeze the working draft as the next version (v1, v2, …): it never changes after, and Open in draft brings it back (umtool takes save)"> + {state.busy ? "Saving…" : "Save version"} + </button> + {state.said && ( + <span role="status" className={cn("text-[11px]", state.error ? "text-reject-text" : "text-muted")} data-save-version-said={state.error ? "error" : "ok"}> + {state.said} + </span> + )} + </div> + {versions.length === 0 ? ( + <p className="m-0 px-1 py-1 text-muted">No saved version yet.</p> + ) : ( + <ul className="m-0 flex max-h-[50vh] list-none flex-col overflow-auto p-0" data-ws-version-list=""> + {versions + .slice() + .reverse() + .map((v) => ( + <li key={v.id} className="flex items-baseline gap-2 rounded-[2px] px-1 py-0.5 hover:bg-panel-2" data-ws-version={v.id}> + <span className={cn("font-mono text-text", !v.made && "italic")}>{v.id}</span> + <span className="min-w-0 flex-1 truncate text-muted" title={v.label}> + {v.label} + </span> + <Link href={playHref(project, { take: v.id })} prefetch={false} className="ink-link" data-ws-version-play={v.id} title="play it read-only"> + Play + </Link> + <Link href={openInDraftHref(project, v.id)} prefetch={false} className="ink-link" data-ws-version-open={v.id} title="copy it into the draft to edit it (it asks first; your draft is saved as a version when it has edits)"> + Open in draft + </Link> + </li> + ))} + </ul> + )} + </div> + )} + </Menu> + ); +} + +function LookSwitch({ project, basic, onChanged }: { project: string; basic: boolean; onChanged: () => void }) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const set = async (mode: "basic" | "deck") => { + if ((mode === "basic") === basic) return; + setBusy(true); + setError(null); + try { + const g = await fetch(`/api/report/render?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const v = (await g.json().catch(() => ({}))) as { token?: string | null; error?: string }; + if (!g.ok) throw new Error(v.error ?? `HTTP ${g.status}`); + const r = await fetch("/api/report/render", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, token: v.token ?? null, patch: { mode } }) }); + const j = (await r.json().catch(() => ({}))) as { error?: string; errors?: string[] }; + if (!r.ok) throw new Error((j.errors ?? [j.error ?? `HTTP ${r.status}`]).join("; ")); + announceManifestChanged(project); + onChanged(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + return ( + <span className="inline-flex items-center gap-1.5" data-ws-look={basic ? "basic" : "deck"}> + <span className="text-[11.5px] text-muted">Look</span> + <span role="group" aria-label="Output mode" className="inline-flex overflow-hidden rounded-[3px] border border-seam-2"> + {(["basic", "deck"] as const).map((m) => ( + <button + key={m} + type="button" + data-ws-look-mode={m} + aria-pressed={(m === "basic") === basic} + disabled={busy} + onClick={() => void set(m)} + title={m === "basic" ? "the footage alone: no deck, chrome, intro, QR, cards or brand (umtool look <p> mode=basic)" : "the deck and the look's chrome (umtool look <p> mode=deck)"} + className={(m === "basic") === basic ? "bg-[var(--color-text)] px-2 py-0.5 text-[11.5px] font-semibold text-[var(--color-ground)]" : "bg-transparent px-2 py-0.5 text-[11.5px] text-text-2 hover:text-text"} + > + {m === "basic" ? "Basic" : "Deck"} + </button> + ))} + </span> + {error && ( + <span role="alert" className="text-[11px] text-reject-text"> + {error} + </span> + )} + </span> + ); +} + +function RenderMenu({ project }: { project: string }) { + const [said, setSaid] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const go = async (window: "full" | { at: number; dur: number }) => { + setBusy(true); + setSaid(null); + const r = await startTakeJob({ project, take: { label: window === "full" ? "Draft, full" : "Draft, 60 s", window } }); + setBusy(false); + setSaid(r.error ?? "rendering — the job is on the jobs bar; the take lands under Versions"); + }; + return ( + <Menu label="Render ▾" testid="render" title="render the draft as a take (umtool take): a 60 s preview or the whole cut"> + {() => ( + <div className="flex flex-col gap-1.5 p-1"> + <div className="flex flex-wrap gap-1.5"> + <button type="button" className={btn("outline")} disabled={busy} onClick={() => void go({ at: 0, dur: 60 })} data-ws-render="60" title="umtool take <p> --at 0 --dur 60"> + Render 60 s + </button> + <button type="button" className={btn("outline")} disabled={busy} onClick={() => void go("full")} data-ws-render="full" title="umtool take <p> --full"> + Render full + </button> + </div> + {said && ( + <span role="status" className="text-[11px] text-muted" data-ws-render-said=""> + {said} + </span> + )} + <Link href={takesHref(project)} prefetch={false} className="ink-link text-[11.5px]"> + Takes and renders + </Link> + </div> + )} + </Menu> + ); +} + +export type UndoState = { busy: boolean; said: string | null; error: boolean; canRedo: boolean }; + +export default function WorkspaceTop({ + project, + title, + draftLine, + draftParent, + draftEdits, + versions, + basic, + firstClip, + shareClip, + undo, + onUndo, + onRedo, + onChanged, + help, +}: { + project: string; + title: string; + draftLine: string; + draftParent: string | null; + draftEdits: number | null; + versions: Version[]; + basic: boolean; + /** The walk starts here (Review pass, until L7b). */ + firstClip: string | null; + /** The clip whose share line Share copies: the selected one, else the one on screen. */ + shareClip: string | null; + undo: UndoState; + onUndo: () => void; + onRedo: () => void; + /** Something the bar wrote (a version, the look): the workspace reads the draft again. */ + onChanged: () => void; + help: () => void; +}) { + return ( + <header data-app-header="workspace" data-ws-top="" className="flex flex-wrap items-center gap-x-2.5 gap-y-1 border-b border-seam bg-panel px-3 py-1.5"> + <Link href="/" prefetch={false} aria-label="umtool home" className="shrink-0"> + <Mark size={18} /> + </Link> + <nav aria-label="Breadcrumb" className="flex min-w-0 items-center gap-1.5 text-[12.5px]"> + <Link href={projectsHref()} prefetch={false} className="hidden text-muted-2 hover:text-text xl:inline"> + Projects + </Link> + <span className="hidden text-seam-2 xl:inline">/</span> + <h1 className="m-0 min-w-0 max-w-[22vw] truncate font-display text-[14.5px] font-semibold text-text" title={`${title} — ${project}`} data-ws-title=""> + {title} + </h1> + </nav> + <span className="font-mono text-[11.5px] text-text-2" data-ws-draft={draftParent ?? ""} data-ws-draft-edits={draftEdits ?? ""} title="the working draft: every edit lands in it (video.manifest.json)"> + {draftLine} + </span> + <VersionsMenu project={project} versions={versions} onSaved={onChanged} /> + <nav aria-label="Mode" className="inline-flex items-center rounded-[3px] border border-seam-2 p-0.5 text-[12px]" data-ws-mode="edit"> + <span aria-current="page" className="rounded-[2px] bg-panel-2 px-2 py-0.5 font-medium text-text" data-ws-mode-edit=""> + Edit + </span> + {firstClip ? ( + <Link href={clipBenchHref(project, firstClip)} prefetch={false} className="rounded-[2px] px-2 py-0.5 text-muted-2 hover:text-text" data-ws-mode-review="" title="walk the draft's clips, a verdict each (the walk, until the review pass lands here)"> + Review pass + </Link> + ) : ( + <span className="px-2 py-0.5 text-seam-2" title="no clip to walk"> + Review pass + </span> + )} + <Link href={presentHref(project)} prefetch={false} className="rounded-[2px] px-2 py-0.5 text-muted-2 hover:text-text" data-ws-mode-present="" title="the cut as slides, full screen, navigated like a deck"> + Present ⛶ + </Link> + </nav> + <LookSwitch project={project} basic={basic} onChanged={onChanged} /> + <RenderMenu project={project} /> + {shareClip && <CopyShareLine key={shareClip} project={project} clip={shareClip} testid="ws" />} + <span className="ml-auto inline-flex items-center gap-1"> + <button type="button" className={btn("quiet")} disabled={undo.busy} onClick={onUndo} data-ws-undo="" title="take back the newest edit to the draft (⌘Z / Ctrl+Z; umtool timeline <p> undo)"> + Undo + </button> + <button type="button" className={btn("quiet")} disabled={undo.busy || !undo.canRedo} onClick={onRedo} data-ws-redo="" title="put back what Undo took back (⌘⇧Z / Ctrl+Y; umtool timeline <p> redo)"> + Redo + </button> + {undo.said && ( + <span role="status" className={cn("max-w-[220px] truncate text-[11px]", undo.error ? "text-reject-text" : "text-muted")} data-ws-undo-said={undo.error ? "error" : "ok"} title={undo.said}> + {undo.said} + </span> + )} + <Menu label="Piece ▾" testid="piece" align="right" title="the piece page's tabs"> + {(close) => ( + <ul className="m-0 flex list-none flex-col p-0"> + {PIECE_TABS.map((t) => ( + <li key={t.id}> + <Link href={projectHref(project, { tab: t.id })} prefetch={false} onClick={close} className="block rounded-[2px] px-2 py-1 text-text-2 hover:bg-panel-2 hover:text-text" data-ws-piece-tab={t.id}> + {t.label} + </Link> + </li> + ))} + </ul> + )} + </Menu> + <button type="button" onClick={help} className={cn(btn("outline"), "min-w-8 font-mono")} aria-label="keys" title="keys (?)" data-ws-help=""> + ? + </button> + </span> + </header> + ); +} diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs @@ -58,9 +58,11 @@ test("empty, null and false values are left out; true is 1", () => { assert.equal(H.workHref({}), "/work"); assert.equal(H.workHref({ kind: "", state: undefined, q: "x y" }), "/work?q=x+y"); assert.equal(H.projectHref("p", { all: false }), "/projects/p"); - // A piece page's tab: first, the Overview never written, a note still last. + // A piece page's tab: first, the Overview written out (the bare address is the workspace, L7a), a note still last. assert.equal(H.projectHref("a/b", { tab: "build" }), "/projects/a/b?tab=build"); - assert.equal(H.projectHref("a/b", { tab: "overview" }), "/projects/a/b"); + assert.equal(H.projectHref("a/b", { tab: "overview" }), "/projects/a/b?tab=overview"); + assert.equal(H.workspaceHref("a/b"), "/projects/a/b"); + assert.equal(H.workspaceHref("a/b", { block: "c01" }), "/projects/a/b?block=c01"); assert.equal(H.projectHref("a/b", { tab: "cut", all: true, note: "n1" }), "/projects/a/b?tab=cut&all=1&note=n1"); assert.equal(H.projectsHref({ kind: "k1", new: false }), "/projects?kind=k1"); assert.equal(H.projectsHref({ new: true }), "/projects?new=1"); diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -266,12 +266,22 @@ export function articleCompareHref(id: string, q: { a?: string; b?: string } = { // ── projects ──────────────────────────────────────────────────────────────── /** - * A project's page. `tab` opens one of the piece page's tabs (lib/pieces/tabs.mjs; - * absent, or `overview`, is the Overview); `all` shows every row of the cut's long list. + * A project's page. Its own address (no `tab`) is a report video's WORKSPACE (umtool redesign L7a: + * components/projects/workspace/) and any other kind's piece page; `tab` opens one of the piece page's tabs + * (lib/pieces/tabs.mjs) -- `overview` too, written out, since the bare address is the workspace's. + * `all` shows every row of the cut's long list. */ export function projectHref(id: string, q: { tab?: string; all?: boolean } & NoteOpt = {}): string { const { note, tab, ...rest } = q; - return withQuery(`/projects/${encodePath(id)}`, { ...(tab && tab !== "overview" ? { tab } : {}), ...rest }, note); + return withQuery(`/projects/${encodePath(id)}`, { ...(tab ? { tab } : {}), ...rest }, note); +} + +/** + * THE WORKSPACE (umtool redesign L7a): a report video's one screen -- the draft playing, its blocks, the + * inspector. `block`: open with that block (a timeline entry's id, or `intro`) selected. + */ +export function workspaceHref(id: string, q: { block?: string | null } = {}): string { + return withQuery(`/projects/${encodePath(id)}`, q.block ? { block: q.block } : {}); } /** A project by its path, for an id that a tool page shadows at its own URL. */ diff --git a/umtool/lib/projects/kinds.mjs b/umtool/lib/projects/kinds.mjs @@ -118,6 +118,9 @@ export const PROJECT_KINDS = [ // Takes are made of it (lib/report/takeMaker.mjs): its manifest patched // and rendered into takes/<id>/. makesTakes: true, + // Its own address opens THE WORKSPACE (umtool redesign L7a): one screen, viewer + strip + inspector; + // the piece page's tabs stay at `?tab=` (components/projects/workspace/). + workspace: true, }, { id: "song", @@ -211,6 +214,15 @@ export const kindPieceFlow = (id) => kindById(id)?.piece?.flow ?? null; /** Are takes made of a project of this kind (lib/report/takeMaker.mjs)? Declared on the kind. */ export const kindMakesTakes = (id) => kindById(id)?.makesTakes === true; +/** Does a project's bare address open the workspace (L7a) rather than its piece page's Overview? */ +export const kindHasWorkspace = (id) => kindById(id)?.workspace === true; +/** + * Does THIS address open the workspace: a kind that has one, its own address with nothing that names a tab of + * the piece page (`tab`, a `note` to find on a tab, the Cut's `all`). + * @param {string} kind + * @param {Record<string, string | string[] | undefined>} search + */ +export const opensWorkspace = (kind, search) => kindHasWorkspace(kind) && !search?.tab && !search?.note && search?.all !== "1"; /** Can a project of this kind be an article's video (lib/articles/links.mjs)? Declared on the kind. */ export const kindLinksArticles = (id) => kindById(id)?.linksArticles === true; diff --git a/umtool/lib/report/postBenchData.ts b/umtool/lib/report/postBenchData.ts @@ -0,0 +1,70 @@ +import { channelsDirFor, readManifest } from "@/lib/projects/report.mjs"; +import { manifestToken } from "@/lib/report/manifest.mjs"; +import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck"; +import { postItemPlan, panelEntry } from "umtool-report-to-video/post-item"; +import { planContext } from "umtool-report-to-video/post-conversation"; +import { projectCombos } from "umtool-report-to-video/post-combo-prints"; +import { mediaSceneOf, sceneEntry } from "umtool-report-to-video/post-media-scene"; +import type { PostPlan } from "@/components/projects/review/PostItemPlayer"; +import type { ComboInfo } from "@/components/projects/review/ComboBadge"; + +// --------------------------------------------------------------------------- +// THE POST BENCH'S DATA (report-to-video/post-item.mjs; knobs.md, "A post item"): what PostBench is drawn from +// for one post item of the draft -- its entry, the frame's box, its plan in the cut (the item before it, its +// conversation's scene, its media scene, its combo counted over the whole cut), its neighbours among the posts. +// One function, two callers: the bench's own page (PostBenchPage.tsx) and the workspace's inspector +// (GET /api/report/post-bench), so the two draw the same item the same way (umtool redesign L7a). +// --------------------------------------------------------------------------- + +type Entry = Record<string, unknown> & { id: string; type?: string }; + +export type PostBenchData = { + entry: Entry; + token: string | null; + box: { width: number; height: number }; + plan: PostPlan; + scene: ReturnType<typeof mediaSceneOf>; + render: Record<string, unknown>; + before: Record<string, unknown> | null; + conversation: Record<string, unknown> | null; + combo: ComboInfo | null; + /** The post items of the cut, in order (the bench's ‹ prev / next ›). */ + neighbours: string[]; + /** This item's place among them, 0-based. */ + index: number; +}; + +/** The post item `id` of the draft at `dir`, or null when the manifest has no such post item. */ +export async function postBenchData(dir: string, id: string): Promise<PostBenchData | null> { + const m = (await readManifest(dir)) as Record<string, unknown> | null; + if (!m) return null; + const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Entry[]; + const at = tl.findIndex((e) => e?.type === "post" && e.id === id); + if (at < 0) return null; + const entry = tl[at]; + const render = (m.render ?? {}) as Record<string, unknown>; + const box = deckOn(render) + ? (feedOn({ render, posts: (m.posts ?? []) as never[], entries: tl as never[] }) ? feedGeometry(render).footage : deckGeometry(render).footage) + : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) }; + const neighbours = tl.filter((e) => e?.type === "post").map((e) => e.id); + // What it opens on (post-conversation.mjs): the item before it and the scene its run leaves on screen. + const ctx = planContext(tl, at, render) as { prev: Record<string, unknown> | null; scene: Record<string, unknown> | null }; + // Its combo (post-combo.mjs): counted over the whole cut, as the build counts it. + const counted = await projectCombos(dir, m, { channelsDir: channelsDirFor(dir, m) }).catch(() => ({ combos: {}, groups: [] })); + const combos = counted.combos as Record<string, ComboInfo>; + // Its media scene (post-media-scene.mjs): its neighbours with the same attachment, by the combo's groups. + const scene = mediaSceneOf(tl, at, counted.groups, render); + return { + entry, + token: await manifestToken(dir), + box: { width: box.width, height: box.height }, + plan: postItemPlan(panelEntry(sceneEntry(entry, scene), render), render, { ...ctx, mediaScene: ctx.scene ? null : scene }) as unknown as PostPlan, + scene, + render, + before: ctx.prev, + conversation: ctx.scene, + combo: combos[id] ?? null, + neighbours, + index: neighbours.indexOf(id), + }; +}