commit b31b4c56a1ed944d181f03fbb2089efcd6f0d7bc
parent 18c82af1500d8fb94d510d414259e76a8e8a5daa
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 10 Nov 2026 13:27:05 -0500
Merge lane/workspace: a report video's own address is one screen -- top bar, the live viewer playing the draft, the cut as a strip of blocks, an inspector chosen by the block; redo beside the one undo (redesign L7a)
- review/playCore.tsx: Play's player core, shared by Play and the workspace (no fork); 9:16 cuts and L10's post hero in the core
- components/projects/workspace/: WorkspaceTop (draft line, versions, Edit / Review pass / Present, Basic | Deck, Render, share), BlockStrip (select, keys, Alt+arrow reorder, +), WorkspaceInspector (ClipBench and PostBench in layout="inspector", L6's panels, L2's intro editor); a bottom sheet under ~900 px
- the bare /projects/<p> opens the workspace (a claimed project too; its ?tab= and ?note= still go to the article, whose More menu links back); projectHref(p, {tab}) writes ?tab=
- redo: umtool timeline <p> redo, the route op, the buttons and keys; an undo records the draft's hash and a redo refuses once anything wrote since (review blocker, fixed); undo-saved / redone-* pruned with the undo points
- GET /api/report/post-bench (memoised per draft token); the generated-manifest banner under the top bar
- the home's patch fixes are outlines until lit (visual-audit inbox green again)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
40 files changed, 3548 insertions(+), 1452 deletions(-)
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -137,6 +137,13 @@ source tree).
(`DisplaySummary` records), documented in `common/lib/corpus.ts:35-36` and served by
`common/components/summariesCache.ts`. Nothing to do with AI summaries. Use **`digest`**.
+**"Workspace" means two things in umtool.** THE WORKSPACE (umtool redesign L7a,
+`umtool/components/projects/workspace/`) is a report video's one screen at its own address
+`/projects/<p>` (`workspaceHref`, `kinds.mjs` `opensWorkspace`): viewer, block strip, inspector.
+An ARTICLE's "workspace files" are something else: the files of its research workspace, shown on the
+Article tab's `source` view (`umtool/lib/pieces/tabs.mjs` ARTICLE_SECTION_TAB `source`,
+`umtool/components/articles/WorkspacePanel.tsx`). Say which.
+
**Never name a sidecar `transcript.<x>.<y>`.** `common/lib/videoStatus.ts:88` —
`export const SUB_FILE_RE = /^transcript\.([^.]+)\.([^.]+)$/;` treats any such file as a
subtitle track. The exclusion list in `readSubTracks` is hardcoded. Use `ai-digest.json`,
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/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts
@@ -20,6 +20,7 @@ import {
removeWrongSpeaker,
removePost,
undoStructural,
+ redoStructural,
updateFactcheck,
updateSection,
updateTeaser,
@@ -60,6 +61,7 @@ export const dynamic = "force-dynamic";
// post-remove { id }
// factcheck { factcheck: { verdicts?, stamp?, tally? } | null }
// undo {} restore the newest auto snapshot
+// redo {} put back what the newest undo took back (no edit since)
// place { ids: [id…], before: id | null, section? } a drop on Play's reel strip: before that entry
// (null: the end), the clips joining that section; its own undo point
// section-move { ids: [id…], section, position?: "start" | "end" } clips into a section
@@ -180,6 +182,9 @@ export async function POST(request: Request) {
return updateFactcheck(dir, (body.factcheck ?? null) as Record<string, unknown> | null, { token });
case "undo":
return undoStructural(dir, { token });
+ case "redo":
+ // What the newest undo took back, put back (no edit since it): the workspace's Redo.
+ return redoStructural(dir, { token });
case "place":
return placeEntries(dir, Array.isArray(body.ids) ? body.ids.map(String) : [id], {
token,
@@ -223,7 +228,7 @@ export async function POST(request: Request) {
case "group-promote":
return promoteGroup(dir, String(body.group ?? ""), { label: typeof body.label === "string" ? body.label : null }, { token });
default:
- throw new Error("op must be move, place, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, section-move, section-add, section-boundary, section-remove, section-set, order, group-set, group-label, group-remove, group-move or group-promote");
+ throw new Error("op must be move, place, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, redo, section-move, section-add, section-boundary, section-remove, section-set, order, group-set, group-label, group-remove, group-move or group-promote");
}
};
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/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx
@@ -30,7 +30,7 @@ import { readArticleNotes, readReportFile, reportDirFor } from "@/lib/articles/s
import { sourceFor } from "@/lib/articles/sources.mjs";
import { readArticleProposals } from "@/lib/articles/verdicts";
import VerdictProposals from "@/components/articles/VerdictProposals";
-import { articleEvidenceHref, articleHref, projectHref } from "@/lib/hrefs";
+import { articleEvidenceHref, articleHref, projectHref, workspaceHref } from "@/lib/hrefs";
import { ARTICLES_KEY, corpusNotesFile } from "@/lib/paths";
import { readPieceGraph } from "@/lib/pieces";
import { articleVideo, projectNoteTab, readArticlePieceFrame, type ArticleVideo } from "@/lib/pieces/article";
@@ -212,6 +212,10 @@ export default async function ArticlePage({
<span className="px-2 pb-1 pt-1.5 font-mono text-[11px] text-muted" data-piece-more-project={videoRef.id}>
{videoRef.id}
</span>
+ {/* Its video's workspace (L7a): the project's own address -- the one way there from a claimed piece. */}
+ <Link href={workspaceHref(videoRef.id)} prefetch={false} data-primary-workspace={videoRef.id} className="block rounded-[2px] px-2 py-1 text-[12.5px] text-text-2 hover:bg-panel-2 hover:text-text">
+ Open the workspace
+ </Link>
<DeleteProject project={videoRef.id} />
</>
)}
diff --git a/umtool/components/inbox/InboxList.tsx b/umtool/components/inbox/InboxList.tsx
@@ -170,7 +170,7 @@ function Card({ card: c }: { card: InboxCard }) {
<LifecycleButton piece={c.piece} title={c.title} from={c.lifecycle} to="done" label="Mark done" variant="outline" size="md" className="lit-go max-md:min-h-11" />
) : oneClick && c.settle && c.project ? (
<span data-card-settle={c.settle.kind}>
- <DecisionSettle project={c.project} settle={c.settle} size="md" className="lit-go max-md:min-h-11" />
+ <DecisionSettle project={c.project} settle={c.settle} size="md" lit className="lit-go max-md:min-h-11" />
</span>
) : (
<Link href={c.action.href} prefetch={false} data-action-link="" className={cn(buttonVariants({ variant: "outline", size: "md" }), "lit-go max-md:min-h-11")}>
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";
@@ -515,9 +516,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.
@@ -527,6 +535,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);
// The DRAFT's clip, always (L3): a take's clip is never benched -- its old address is Open in draft.
// Export clip (ClipExport.tsx): this clip, clean, into the project's exports/.
const clipExport = useClipExport(data.project, null);
@@ -937,7 +947,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 = () => {
@@ -960,7 +970,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 ------------------------------------------------------
//
@@ -1059,6 +1069,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" : ""}`
@@ -1264,6 +1276,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;
}
@@ -1549,6 +1563,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;
@@ -1704,6 +1722,7 @@ export default function ClipBench({
gap.pick,
gap.cut,
gap.removeAt,
+ inspector,
]);
const refresh = useCallback(async (): Promise<ClipBenchData | null> => {
@@ -1935,6 +1954,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)})`);
@@ -2894,950 +2915,978 @@ 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 && (
- <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>
)}
- {/* ---- 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 && <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>'</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>'</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>
-
- {/* ---- 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>
- </>
- )}
+ ← Fetch to −{nextBefore} s
+ </button>
+ )}
+ {afterMaxed ? (
+ <span data-fetch-after-maxed="" className="text-[var(--color-dim)]">
+ {atEndOfSource
+ ? "the recording ends here"
+ : capSentence}
</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}
+ ) : (
+ <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()}
>
- {/* 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
- </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);
- }}
- />
- )}
- </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>
-
- {/* 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>
- ) : (
- <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={null} disabled={!!busy} />
- {storedOffered && (
- <StoredUrlCheckbox checked={fromStored} onChange={setFromStored} disabled={!!busy} compact />
- )}
- </div>
+ 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={null} 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) }}
- />
- ))}
- </>
- )}
- {/* ---- 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) => (
+ {/* ---- 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={`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)})` }}
+ key={t}
+ data-cache-edge={t}
+ className="absolute top-0 h-full border-l border-dashed border-[var(--color-meter)]"
+ style={{ left: rpct(t) }}
/>
))}
- {/* 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>
- )}
- {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 “…
- {endCue?.text.trim().slice(-56)}”. 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’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)]"
+ </>
+ )}
+ {/* ---- 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)})` }}
>
- <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,
- })
+ {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;
}
- >
- 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]"),
- )}
+ // 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>
+ );
+ })}
+ </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 “…
+ {endCue?.text.trim().slice(-56)}”. 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’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,
+ })
+ }
>
- <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 ? (
+ 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="aspect-video w-full rounded border border-[var(--color-line)] bg-black"
+ className="absolute inset-0 h-full w-full cursor-pointer object-contain"
preload="metadata"
- controls
+ onClick={(e) => {
+ const el = e.currentTarget;
+ if (el.paused) void el.play().catch(() => {});
+ else el.pause();
+ }}
/>
- ) : 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)]"
+ </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();
+ }}
>
- nothing rendered for this clip yet
- </div>
- )}
- <button
- type="button"
- data-rerender=""
- className={buttonVariants({ variant: "outline", size: "sm" })}
- disabled={!!busy}
- onClick={() => void rerender()}
+ {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"
>
- 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’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>
+ <NeutralFrame geometry={deckPreview!.geometry} label="nothing rendered for this clip yet" />
+ </DeckFrame>
</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
+ 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>
- </div>
- </details>
+ )}
+ <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’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>
+
+ {/* ---- 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>
+ </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>
+ );
+ }
+
+ 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 && (
+ <div className="max-md:hidden">
+ <GeneratedBanner generatedBy={data.generatedBy} />
+ </div>
+ )}
+ {/* ---- 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 && <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/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx
@@ -1,7 +1,8 @@
import AppShell from "@/components/shell/AppShell";
import PieceFrame from "@/components/piece/PieceFrame";
import { readPieceFrame } from "@/lib/pieces/frame";
-import { projectHref, projectsHref } from "@/lib/hrefs";
+import Link from "next/link";
+import { projectHref, projectsHref, workspaceHref } from "@/lib/hrefs";
import { projectNoteTab } from "@/lib/pieces/article";
import { PIECE_TABS, tabOf } from "@/lib/pieces/tabs.mjs";
import type { ProjectRef } from "@/lib/project-types";
@@ -80,6 +81,11 @@ export default async function ReportProject({
more={
<>
<span className="px-2 pb-1 pt-0.5 font-mono text-[11px] text-muted">{project.id}</span>
+ {/* The workspace (L7a): the project's own address -- the draft playing, its blocks, the inspector. Here, not in
+ the head's row: the head is sticky, and a wider row is a taller head over the Cut tab's drop targets. */}
+ <Link href={workspaceHref(project.id)} prefetch={false} data-primary-workspace="" className="block rounded-[2px] px-2 py-1 text-[12.5px] text-text-2 hover:bg-panel-2 hover:text-text">
+ Open the workspace
+ </Link>
<DeleteProject project={project.id} />
</>
}
diff --git a/umtool/components/projects/cutApp/CutApp.tsx b/umtool/components/projects/cutApp/CutApp.tsx
@@ -53,9 +53,28 @@ function clipOf(pathname: string, project: string): string | null {
const rest = pathname.slice(root.length).split("/");
return rest.length === 2 && rest[0] === "clip" && rest[1] ? decodeURIComponent(rest[1]) : 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);
@@ -138,16 +157,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;
}
@@ -158,7 +177,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.
@@ -166,7 +185,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);
@@ -183,7 +202,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) => {
@@ -192,7 +211,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}`);
@@ -205,7 +224,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/DecisionSettle.tsx b/umtool/components/projects/report/DecisionSettle.tsx
@@ -22,6 +22,7 @@ export default function DecisionSettle({
token = null,
size = "sm",
className,
+ lit = false,
}: {
project: string;
settle: NonNullable<Decision["settle"]>;
@@ -29,6 +30,11 @@ export default function DecisionSettle({
/** The Inbox's card draws it as its primary action: `md`, lit. */
size?: "sm" | "md";
className?: string;
+ /**
+ * A list line's action (the Inbox's card): an OUTLINE at rest, filled only on the lit line (`lit-go`) -- a page
+ * has ONE filled action (visual-audit.spec), so a patch's fix is not filled on every card that offers one.
+ */
+ lit?: boolean;
}) {
const router = useRouter();
const [busy, setBusy] = useState(false);
@@ -116,7 +122,7 @@ export default function DecisionSettle({
data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : settle.kind === "publish-site" ? `publish-${settle.siteId}` : settle.kind === "quote-check" ? "quote-check" : "links"}
disabled={busy}
onClick={() => void run()}
- className={cn(buttonVariants({ variant: settle.kind === "patch" ? "go" : "outline", size }), className)}
+ className={cn(buttonVariants({ variant: settle.kind === "patch" && !lit ? "go" : "outline", size }), className)}
title={
settle.kind === "patch"
? `writes ${Object.keys(settle.patch).join(", ")} on ${settle.clip} through the window writer`
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/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -9,18 +9,13 @@ import { NoteThread } from "@/components/notes/NoteThread";
import type { Anchor, CutAsk, Note } from "@/lib/annotations/types";
import { clipBenchHref, ingredientHref, openInDraftHref, postBenchHref } from "@/lib/hrefs";
import { cn } from "@/lib/utils";
-import { footageAt } from "@/lib/report/footage-move.mjs";
-import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
import {
- chromeTime, counterSteps, cutAtSource, cutNotesRequest, playPlan, playTimeOfChrome, runningTime, seamsOf, skipEntries, sourceAt, startOf,
+ counterSteps, cutAtSource, cutNotesRequest, playPlan, playTimeOfChrome, runningTime, seamsOf, sourceAt, startOf,
} from "@/lib/report/playCut.mjs";
-import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck";
import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from "../report/AssistBox";
-import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
-import { usePlayEngine } from "./playEngine/usePlayEngine";
-import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts";
-import type { EngineInfo, ItemGate, MediaRef } from "./playEngine/engine";
-import { postPreload } from "./playEngine/postPreload";
+import type { RenderCuts } from "./playEngine/useRenderCuts";
+import type { EngineInfo, MediaRef } from "./playEngine/engine";
+import { PlayStage, usePlayCore } from "./playCore";
import ReelStrip, { type StripCounter, type StripEdit } from "./ReelStrip";
import { useWaveZoom, ZoomControls } from "../bench/GapsZoom";
import { followVis, itemSections } from "@/lib/report/stripDrag.mjs";
@@ -32,14 +27,9 @@ import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExpor
import AddPost from "./AddPost";
import { AddClipToggle } from "../AddClip";
import { Options, PanelSlot } from "@/components/ui/disclosure";
-import PostItemPlayer, { postItemAssets, type PostPlan } from "./PostItemPlayer";
-import SidePostOverlay from "./SidePostOverlay";
-import VideoEntryPlayer from "./VideoEntryPlayer";
-import TeaserCardPlayer, { type TeaserPage } from "./TeaserCardPlayer";
-import IntroCardPlayer from "./IntroCardPlayer";
-import { useIntroPage } from "./useIntroPage";
-import { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs";
-import ComboBadge, { type ComboInfo } from "./ComboBadge";
+import type { PostPlan } from "./PostItemPlayer";
+import type { VideoEntryPlay } from "@/lib/report/playVideo.mjs";
+import type { ComboInfo } from "./ComboBadge";
import CopyShareLine from "../CopyShareLine";
import VersionVerdict from "./VersionVerdict";
import { StillButton } from "../inspector/StillInspector";
@@ -180,13 +170,6 @@ export type PlayViewData = {
entries: PlayEntry[];
};
-type LiveDoc = DeckPreviewDoc & {
- leadIn?: number;
- verdictLabels?: Record<string, string>;
- tallyOrder?: string[];
- tallyAlways?: string[];
- schedule: DeckPreviewDoc["schedule"] & { finale?: { from: number; to: number } };
-};
type Ui = { t: number; cur: number; playing: boolean; ended: boolean; waiting: boolean };
type CutAnchor = Extract<Anchor, { kind: "cut" }>;
@@ -203,10 +186,6 @@ const PAUSE_KEY = "umtool.play.pauseWhileWriting";
/** "on": play the clips the walk rejected too (for re-review); absent or "off": skip them. */
// The key keeps its old name: a browser that chose "show" before rejections had reasons still has.
const SHOW_REJECTED_KEY = "umtool.play.showIncorrect";
-/** Play's "As published": post cards drawn with their redacted words as bars (post-redact.mjs). Per browser. */
-const AS_PUBLISHED_KEY = "umtool.play.asPublished";
-/** And which cut: censored (the slur filter on, post-slurs.mjs) or the uncensored one. Per browser. */
-const UNCENSORED_KEY = "umtool.play.uncensored";
/** The dailies' kinds of note: what it asks for, and its key (with Alt, in the composer). */
const ASKS: { id: CutAsk; label: string; key: string }[] = [
@@ -267,16 +246,6 @@ function approximateLine(edges: RenderCuts, info: EngineInfo | null) {
].filter(Boolean).join(" ");
}
-/**
- * POST ITEMS FETCHED AHEAD (postPreload.ts; operator, 4 Nov: "the rapid sections ... don't load fast enough"):
- * the post items whose start is within this many cut seconds after the one on screen -- at least PRELOAD_MIN of
- * them, at most PRELOAD_MAX -- so a burst of short items has many ahead, a slow stretch a few.
- */
-const PRELOAD_AHEAD_S = 20;
-const PRELOAD_MIN = 3;
-const PRELOAD_MAX = 24;
-/** The clock never waits longer than this on one item (a page that never says it is ready). */
-const GATE_MAX_MS = 15_000;
/** The pinned player as a strip, once the transport is under it (a phone). */
const STRIP_H = 120;
@@ -331,102 +300,11 @@ export default function PlayCut({
// Export clip (ClipExport.tsx): the clip at the playhead -- or the one a note points at -- clean, into exports/.
const clipExport = useClipExport(project, take);
- // ---- the composition (the live preview's) ---------------------------------
- const [doc, setDoc] = useState<LiveDoc | null>(null);
- const [composeState, setComposeState] = useState<"composing" | "ready" | "no-deck" | "error">(view.deckOn ? "composing" : "no-deck");
- const [composeError, setComposeError] = useState<string | null>(null);
- const seq = useRef(0);
- const compose = useCallback(async () => {
- const mine = ++seq.current;
- setComposeState("composing");
- try {
- const r = await fetch("/api/report/chrome/preview", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, estimate: true, ...(take ? { take } : {}) }),
- });
- const j = (await r.json().catch(() => ({}))) as LiveDoc & { error?: string; deckOn?: boolean };
- if (mine !== seq.current) return;
- if (!r.ok) {
- setDoc(null);
- setComposeState(j.deckOn === false ? "no-deck" : "error");
- setComposeError(j.deckOn === false ? null : String(j.error ?? `HTTP ${r.status}`));
- } else {
- setDoc(j);
- setComposeState("ready");
- setComposeError(null);
- }
- } catch (e) {
- if (mine === seq.current) {
- setComposeState("error");
- setComposeError(e instanceof Error ? e.message : String(e));
- }
- }
- }, [project, take]);
- useEffect(() => {
- if (view.deckOn) void compose();
- }, [compose, view.deckOn]);
-
- // ---- the plan ----------------------------------------------------------------
- // The composed schedule, while it is the cut's ORDER: a reorder (the strip's drop) re-reads the
- // view at once, and until the deck is composed again its segments would play the old order --
- // so the estimate's (the view's own, in the new order) stand in meanwhile.
- const composedOrder = doc?.schedule?.segments?.map((x) => x.id).join("\n") ?? null;
- const viewOrder = useMemo(() => view.segments.map((x) => x.id).join("\n"), [view.segments]);
- const scheduleNow = composedOrder !== null && composedOrder === viewOrder;
- const schedule = scheduleNow ? (doc?.schedule ?? null) : null;
- const segments = schedule?.segments ?? view.segments;
- const leadIn = doc?.leadIn ?? view.leadIn;
- // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change.
- const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd, e.gaps ?? null])), [view.entries]);
- const edges = useRenderCuts(project, take, edgesKey);
+ // ---- the player core (playCore.tsx: the composition, the plan, the engine, what is on screen) ----
// Clips the walk REJECTED (a fact error, or irrelevant, weak, …) are SKIPPED
// unless asked for: the cut the operator means to ship does not hold them
// (umtool check blocks on a fact error and lists the rest). Remembered per browser.
const [showRejected, setShowRejected] = useState(false);
- const [asPublished, setAsPublished] = useState(false);
- const [uncensored, setUncensored] = useState(false);
- useEffect(() => {
- try {
- if (window.localStorage.getItem(AS_PUBLISHED_KEY) === "on") setAsPublished(true);
- if (window.localStorage.getItem(UNCENSORED_KEY) === "on") setUncensored(true);
- } catch {
- // A preference, not state.
- }
- }, []);
- const hasPosts = useMemo(() => view.entries.some((e) => e.type === "post"), [view.entries]);
- const hasVideoEntries = useMemo(() => view.entries.some((e) => e.type === "video" && !!e.videoEntry), [view.entries]);
- // THE TEASERS (lane leaflit-labels): each text card's own page, composed for preview (POST
- // /api/report/chrome/teasers) and laid full frame while it is on screen -- the build's card, not a placeholder.
- // Composed again whenever the manifest moved (its token), with or without a deck.
- const teaserKey = useMemo(() => view.entries.filter((e) => e.type === "teaser").map((e) => e.id).join("\n"), [view.entries]);
- // THE INTRO (lane intro-play): its page composed for preview (POST /api/report/chrome/intro), again when the manifest moved.
- const introPage = useIntroPage(project, take, view.entries.some((e) => e.type === "intro"), view.token);
- const [teaserPages, setTeaserPages] = useState<Record<string, TeaserPage | { id: string; error: string }>>({});
- useEffect(() => {
- if (!teaserKey) {
- setTeaserPages({});
- return;
- }
- let live = true;
- void (async () => {
- try {
- const r = await fetch("/api/report/chrome/teasers", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, ...(take ? { take } : {}) }),
- });
- const j = (await r.json().catch(() => ({}))) as { teasers?: (TeaserPage | { id: string; error: string })[]; error?: string };
- if (!live) return;
- setTeaserPages(Object.fromEntries((j.teasers ?? []).map((x) => [x.id, x])));
- } catch {
- if (live) setTeaserPages({});
- }
- })();
- return () => {
- live = false;
- };
- }, [project, take, teaserKey, view.token]);
useEffect(() => {
try {
// The URL first (Back from the bench lands on the URL Play left), then this browser's choice.
@@ -438,65 +316,9 @@ export default function PlayCut({
// No storage: skipped, the default.
}
}, []);
- const rejected = useMemo(() => view.entries.filter((e) => e.rejected), [view.entries]);
- const skipIds = useMemo(() => new Set(showRejected ? [] : rejected.map((e) => e.id)), [showRejected, rejected]);
- const plan = useMemo(
- () => skipEntries(playPlan(segments, view.entries, { leadIn, cuts: edges.cuts }), skipIds),
- [segments, view.entries, leadIn, edges.cuts, skipIds],
- );
- const entryOf = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
- const planRef = useRef(plan);
- planRef.current = plan;
-
- // ---- the engine (playEngine/: the sound on one Web Audio clock, the picture slaved to it) ----
- const bg = doc?.background ?? "#000";
- // `v` (the version of the window's bytes, playView): a window refetched under its old name is a new URL.
- const srcOf = useCallback(
- (id: string, m: MediaRef) =>
- `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file: m.name, ...(m.v ? { v: m.v } : {}) }).toString()}`,
- [project, take],
- );
- const audioOf = useCallback(
- (id: string, m: MediaRef, from: number, to: number) =>
- `/api/report/audio?${new URLSearchParams({
- project, clip: id, ...(take ? { take } : {}), file: m.name, from: String(from), to: String(to), ...(m.v ? { v: m.v } : {}),
- }).toString()}`,
- [project, take],
- );
- // THE GATE (engine.ts): a post item plays once its player is ready -- its card drawn, its voice and its first
- // attachment able to play -- and the clock waits on it, never cutting it short (a buffer stall's wait). Fetched
- // ahead (postPreload.ts), its player is ready the frame its card is drawn; the clock holds on the item before
- // while it is still fetching. `postReady`: what the MOUNTED player said (one at a time; "gone" as it unmounts).
- // `started`: the item on screen once it has played -- a player mounted again under it (the deck composed) is not
- // waited for (the clock runs on, as it always did).
- const entryOfRef = useRef(entryOf);
- entryOfRef.current = entryOf;
- const postReady = useRef<string | null>(null);
- const started = useRef<string | null>(null);
- const gateAsked = useRef(new Map<string, number>());
- const gate = useCallback<ItemGate>((id, next) => {
- const e = entryOfRef.current.get(id);
- if (!(e?.type === "post" && e.post && e.postPlan)) return "ready";
- const now = performance.now();
- const key = `${next ? "next" : "on"}:${id}`;
- let since = gateAsked.current.get(key);
- if (since === undefined) gateAsked.current.set(key, (since = now));
- if (now - since > GATE_MAX_MS) return "ready";
- if (next) return postPreload.itemState(id) === "loading" ? "fetching" : "ready";
- if (started.current === id) return "ready";
- if (postReady.current !== id) return "wait";
- started.current = id;
- return "ready";
- }, []);
- const onPostReady = useCallback((id: string, state: "ready" | "gone") => {
- if (state !== "gone") postReady.current = id;
- else if (postReady.current === id) postReady.current = null;
- }, []);
- const engine = usePlayEngine({
- plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", gate,
- });
+ const core = usePlayCore(view, { showRejected });
+ const { doc, composeState, composeError, compose, schedule, edges, plan, planRef, entryOf, rejected, skipIds, hasPosts, engine, asPublished, setAsPublished, uncensored, setUncensored } = core;
const { ui, rate, failed, now } = engine;
- const setDuck = engine.setDuck;
const setRate = engine.setRate;
// `?clip=&at=` (back from the clip bench): that clip, that far in -- the
@@ -591,14 +413,6 @@ export default function PlayCut({
setPlaying(false);
void reloadView();
}, [reloadView, setPlaying]);
- // The deck is composed again whenever the manifest moved (its token): a Reject, a reorder, an
- // Apply, the bench's save seen on the way back -- once, however the view came to be re-read.
- const composedFor = useRef(view.token);
- useEffect(() => {
- if (view.token === composedFor.current) return;
- composedFor.current = view.token;
- if (view.deckOn) void compose();
- }, [view.token, view.deckOn, compose]);
// Hidden under the bench (the one app), Play does not play on; shown again, it finds the clip it
// left by its id and the source second (an edit on the bench may have moved it in the cut).
const leftAt = useRef<{ clip: string; at: number; t: number } | null>(null);
@@ -921,88 +735,10 @@ export default function PlayCut({
};
}, [back, help, lPlay, next, prev, skip, stepNote, noteHere, editHere, setPlaying, now, zoom, curSpan]);
- // ---- what is on screen -------------------------------------------------------------
- const t = ui.t;
- // The chrome was composed on the estimate's clock: seeked by the source second playing.
- const tc = chromeTime(plan, t);
- const item = plan.items[ui.cur] ?? null;
- const entry = item ? entryOf.get(item.id) : null;
- const g = doc?.geometry ?? null;
+ // ---- what is on screen (the core's) ----------------------------------------------
+ const { t, item, entry, tally, stamp, finaleNow, broken, postNow, videoNow } = core;
// A 9:16 cut (the stacked vertical deck): its frame is tall, and the player is sized for it.
- const tall = !!g && g.H > g.W;
- const box: Rect | null = g ? (doc?.feed?.footage ?? g.footage) : null;
- const move = schedule ? footageAt(schedule, tc) : null;
- const rect: Rect | null = move?.rect ?? box;
- const order = useMemo(
- () => (schedule?.factcheck ? tallyCellsFrom(schedule.factcheck.stamps, doc?.tallyOrder ?? VERDICTS, doc?.tallyAlways ?? []) : []),
- [schedule, doc?.tallyOrder, doc?.tallyAlways],
- );
- const tally = schedule?.factcheck ? tallyAt(schedule, tc, order) : [];
- const stamp = schedule ? stampAt(schedule, tc) : null;
- const finaleNow = !!schedule && finaleUp(schedule, tc);
- const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, tc) : null;
- const missing = !!item?.clip && !entry?.media;
- const broken = !!item && !!failed[item.id];
- // A post item plays its card and attachments (PostItemPlayer), not a placeholder.
- const postNow = item && entry?.type === "post" && entry.post && entry.postPlan ? { item, entry } : null;
- // A VIDEO entry (lib/report/playVideo.mjs): its file, the whole frame -- and the item before it darkening into it.
- const vstage = hasVideoEntries ? videoStageAt(plan, entryOf, t) : null;
- const videoNow = vstage?.video ? { ...vstage, video: vstage.video } : null;
- // A teaser plays its own page (TeaserCardPlayer), once composed; until then -- or if it did not compose -- a placeholder.
- const teaserPage = item && entry?.type === "teaser" ? teaserPages[item.id] : undefined;
- const teaserNow = item && teaserPage && "src" in teaserPage ? { item, page: teaserPage } : null;
- // THE INTRO (lane intro-play): the build's own page and its sound (IntroCardPlayer), once composed; until then -- or if
- // it did not compose -- a placeholder that says so.
- const introNow = item && entry?.type === "intro" && introPage && "src" in introPage ? { item, page: introPage } : null;
- const placeholder = item && !postNow && !videoNow && !teaserNow && !introNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
- // The clips' sound fades with the picture into a video entry and is off over it (its element plays its own).
- const duck = vstage ? vstage.duck : 1;
- useEffect(() => {
- if (hasVideoEntries) setDuck(duck);
- }, [hasVideoEntries, duck, setDuck]);
- const pct = (n: number, of: number) => `${(n / of) * 100}%`;
- // A clip's side post (lane vertical): its card over the clip for the side's span (SidePostOverlay).
- const sideEntry = item && entry?.type === "clip" ? (entry as { side?: { from: number; to: number; place?: string | null } }).side : undefined;
- const sideNow = item && sideEntry ? <SidePostOverlay project={project} take={take} clipId={item.id} side={sideEntry} s={Math.max(0, t - item.start)} published={asPublished} /> : null;
-
- // ---- post items fetched ahead (postPreload.ts): from the one on screen, ~20 s on --------------------------
- const postBox = box ? { width: box.width, height: box.height } : { width: 1920, height: 1080 };
- const postBoxKey = `${Math.round(postBox.width)}x${Math.round(postBox.height)}`;
- useEffect(() => {
- // A new item on screen: its gate is asked afresh (a revisit waits as the first visit did).
- gateAsked.current.clear();
- }, [ui.cur, plan]);
- // Another item on screen: the one before is no longer "started" (a revisit waits as the first visit did).
- const curId = plan.items[ui.cur]?.id ?? null;
- useEffect(() => {
- if (started.current !== curId) started.current = null;
- }, [curId]);
- useEffect(() => {
- // Not while the deck composes: its pages would be fetched at the plain frame's size (the deck's box is
- // another URL), and the requests would queue ahead of the composition itself.
- if (composeState === "composing") return;
- const items = plan.items;
- const i = ui.cur;
- const [w, h] = postBoxKey.split("x").map(Number);
- const assetsOf = (k: number) => {
- const it = items[k];
- const e = it ? entryOf.get(it.id) : null;
- if (!e || e.type !== "post" || !e.post || !e.postPlan) return null;
- const before = k > 0 ? entryOf.get(items[k - 1]?.id ?? "") : null;
- const joinFrom = e.postPlan.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan } : null;
- return postItemAssets({ project, take, entry: e.post, plan: e.postPlan, box: { width: w, height: h }, published: asPublished, uncensored, joinFrom });
- };
- const keep = [i - 1, i].map(assetsOf).filter((x): x is NonNullable<typeof x> => !!x);
- const ahead: NonNullable<ReturnType<typeof assetsOf>>[] = [];
- const from = items[i]?.to ?? 0;
- for (let k = i + 1, n = 0; k < items.length && ahead.length < PRELOAD_MAX; k += 1, n += 1) {
- if (items[k].from - from > PRELOAD_AHEAD_S && n >= PRELOAD_MIN) break;
- const a = assetsOf(k);
- if (a) ahead.push(a);
- }
- postPreload.want(ahead, keep);
- }, [ui.cur, plan, entryOf, project, take, asPublished, uncensored, postBoxKey, composeState]);
- useEffect(() => () => postPreload.clear(), []);
+ const tall = !!core.g && core.g.H > core.g.W;
// The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's.
const counters = useMemo<StripCounter[]>(() => {
@@ -1017,99 +753,6 @@ export default function PlayCut({
const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: noteT(n.anchor as CutAnchor), text: n.text, open: n.status === "open" })), [mine, noteT, plan]);
const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
- const postPlayer = (box2: { width: number; height: number }) =>
- postNow ? (
- <PostItemPlayer
- key={postNow.item.id}
- project={project}
- take={take}
- entry={postNow.entry.post!}
- plan={postNow.entry.postPlan!}
- box={box2}
- s={Math.max(0, t - postNow.item.start)}
- playing={ui.playing && !ui.waiting}
- speed={rate}
- published={asPublished}
- uncensored={uncensored}
- scene={postNow.entry.postScene ?? null}
- clock={postNow.entry.postClock ?? null}
- onReady={onPostReady}
- progress={postNow.entry.postProgress ?? null}
- joinFrom={(() => {
- // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended.
- const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null;
- return postNow.entry.postPlan?.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan, clock: before.postClock ?? null } : null;
- })()}
- />
- ) : null;
- // A post item that repeats an earlier one's attachment: its combo badge, beside the player.
- const comboBadge = (box2: { width: number; height: number }) =>
- postNow?.entry.postCombo ? (
- <ComboBadge
- key={`combo-${postNow.item.id}`}
- project={project}
- entry={postNow.entry.post!}
- plan={postNow.entry.postPlan!}
- combo={postNow.entry.postCombo}
- box={box2}
- s={Math.max(0, t - postNow.item.start)}
- playing={ui.playing && !ui.waiting}
- />
- ) : null;
- // The video on screen: over EVERYTHING when the chrome is off over it (the default), else as the footage under it.
- const videoPlayer = videoNow ? (
- <VideoEntryPlayer
- key={videoNow.id}
- project={project}
- id={videoNow.id}
- video={videoNow.video}
- src={videoNow.src ?? videoNow.video.from}
- opacity={videoNow.opacity}
- run={ui.playing && !ui.waiting && videoNow.playing}
- speed={rate}
- />
- ) : null;
- const videoOver = videoNow?.video.noChrome ? <div className="pointer-events-none absolute inset-0 z-30">{videoPlayer}</div> : null;
- const videoUnder = videoNow && !videoNow.video.noChrome ? videoPlayer : null;
- // The item before a video entry, darkening into it: the whole stage, its chrome with it.
- const dipVeil = vstage && vstage.dark > 0 ? <div data-play-dip={vstage.id} className="pointer-events-none absolute inset-0 z-30 bg-black" style={{ opacity: vstage.dark }} /> : null;
- // A teaser on screen: its page, seeked to the seconds into the card (the item's own clock, as a post item's).
- const teaserCard = teaserNow ? <TeaserCardPlayer key={teaserNow.item.id} page={teaserNow.page} s={t - teaserNow.item.start} /> : null;
- // The intro on screen: its page seeked to the seconds into it, its sound on Play's clock.
- const introCard = introNow ? <IntroCardPlayer key={introNow.page.src} page={introNow.page} s={t - introNow.item.start} playing={ui.playing && !ui.waiting} speed={rate} /> : null;
- const placeholderCard = placeholder ? (
- <div
- data-play-placeholder={placeholder.kind}
- data-play-missing={placeholder.kind === "missing" ? placeholder.item.id : undefined}
- className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-1.5 p-6 text-center"
- style={{ background: placeholder.kind === "card" ? bg : "transparent" }}
- >
- {placeholder.kind === "card" ? (
- <>
- <span className="micro text-white/60">{placeholder.item.type}</span>
- <span className="max-w-[80%] font-display text-[clamp(15px,2.6vw,32px)] font-semibold text-white">{placeholder.entry?.heading ?? placeholder.item.id}</span>
- <span className="text-[11px] text-white/55">
- {teaserPage && "error" in teaserPage
- ? `the card did not compose: ${teaserPage.error}`
- : placeholder.item.type === "teaser"
- ? "composing the card…"
- : placeholder.item.type === "intro"
- ? introPage && "error" in introPage
- ? `the intro did not compose: ${introPage.error}`
- : "composing the intro…"
- : "a placeholder: the build draws it"}
- </span>
- </>
- ) : (
- <span className="rounded-[3px] bg-black/75 px-2.5 py-1 text-[12.5px] text-white">
- {broken ? `${failed[placeholder.item.id]} — ${placeholder.item.id} plays on as a placeholder` : `No media for ${placeholder.item.id} — fetch it`}
- <span className="mt-0.5 block font-mono text-[11px] text-white/60">
- {placeholder.entry?.video}@{placeholder.entry?.start}–{placeholder.entry?.end}
- </span>
- </span>
- )}
- </div>
- ) : null;
// ---- the phone: the pinned player --------------------------------------------------
// Pinned at full width; a strip (the picture left, where it is right) once
@@ -1157,9 +800,6 @@ export default function PlayCut({
}, [isPhone]);
const dockBtn = cn(buttonVariants({ variant: "outline", size: "md" }), "h-12 min-w-0 px-1 text-[13px]");
- const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => (
- <canvas ref={engine.canvasRef} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} />
- );
const iconBtn = cn(buttonVariants({ variant: "outline", size: "sm" }), "min-w-9 font-mono");
return (
@@ -1248,68 +888,7 @@ export default function PlayCut({
: tall ? { maxWidth: PLAYER_MAX_W_TALL, marginInline: "auto" } : { maxWidth: PLAYER_MAX_W }
}
>
- <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
- <video ref={engine.slotRef0} data-play-slot="0" preload="auto" playsInline muted onError={() => engine.onMediaError(0)} className="absolute inset-0 h-full w-full" />
- <video ref={engine.slotRef1} data-play-slot="1" preload="auto" playsInline muted onError={() => engine.onMediaError(1)} className="absolute inset-0 h-full w-full" />
- </div>
- <div className="relative">
- {doc && g && box ? (
- <DeckFrame preview={doc} t={tc} texts={{}} testid="play-deck">
- <div className="absolute inset-0" style={{ background: bg }} />
- {footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)}
- {videoUnder}
- {postNow && (g.post ?? rect) && (() => {
- // The stacked vertical deck lays a post item as its hero card (deck.mjs deckGeometry `post`).
- const pr = g.post ?? rect!;
- const pb = g.post ?? box;
- return (
- <div className="absolute" style={{ left: pct(pr.x, g.W), top: pct(pr.y, g.H), width: pct(pr.width, g.W), height: pct(pr.height, g.H), background: bg }}>
- {postPlayer({ width: pb.width, height: pb.height })}
- {comboBadge({ width: pb.width, height: pb.height })}
- </div>
- );
- })()}
- {teaserCard}
- {introCard}
- {placeholderCard}
- {sideNow && rect && <div className="pointer-events-none absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) }}>{sideNow}</div>}
- {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />}
- {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />}
- {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
- {/* Every module that declares `play` (chapters, then and now, the status ledger …), by z. */}
- <ModuleLayers layers={doc.layers} frame={g} t={tc} testid="play-layer" />
- {doc.finale && finaleNow && (
- <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale="">
- <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={tc} ready="finale:ready" testid="play-finale" name="finale" />
- </div>
- )}
- </DeckFrame>
- ) : (
- <div
- className="relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0"
- style={{ aspectRatio: "16 / 9" }}
- data-testid="play-plain"
- // A basic cut: the bare footage, as the basic render cuts it -- no card, no side post, nothing over it.
- data-play-bare={view.basic ? "" : undefined}
- >
- {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
- {!view.basic && postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>}
- {!view.basic && videoUnder}
- {!view.basic && teaserCard}
- {!view.basic && introCard}
- {!view.basic && placeholderCard}
- {!view.basic && sideNow}
- </div>
- )}
- {dipVeil}
- {videoOver}
- {ui.playing && ui.waiting && (
- // The clock held (engine.ts): a clip's sound decoding, a post item loading -- it plays in full once here.
- <span data-play-loading="" className="pointer-events-none absolute right-2 top-2 z-40 rounded-full bg-black/70 px-2 py-0.5 text-[11px] text-white">
- loading…
- </span>
- )}
- </div>
+ <PlayStage core={core} basic={!!view.basic} />
{/* The strip's right side (a phone): where you are. */}
{compact && (
<div data-play-strip-side="" className="absolute left-full top-0 flex h-full w-[calc(100vw-213px)] flex-col justify-center gap-0.5 bg-ground px-3 md:hidden">
@@ -1355,15 +934,7 @@ export default function PlayCut({
type="checkbox"
data-play-as-published=""
checked={asPublished}
- onChange={(ev) => {
- const on = ev.target.checked;
- setAsPublished(on);
- try {
- window.localStorage.setItem(AS_PUBLISHED_KEY, on ? "on" : "off");
- } catch {
- // A preference, not state.
- }
- }}
+ onChange={(ev) => setAsPublished(ev.target.checked)}
/>
{asPublished ? (uncensored ? "As published (uncensored)" : "As published (censored)") : "As published"}
</label>
@@ -1374,15 +945,7 @@ export default function PlayCut({
type="checkbox"
data-play-uncensored=""
checked={uncensored}
- onChange={(ev) => {
- const on = ev.target.checked;
- setUncensored(on);
- try {
- window.localStorage.setItem(UNCENSORED_KEY, on ? "on" : "off");
- } catch {
- // A preference, not state.
- }
- }}
+ onChange={(ev) => setUncensored(ev.target.checked)}
/>
Uncensored
</label>
diff --git a/umtool/components/projects/review/playCore.tsx b/umtool/components/projects/review/playCore.tsx
@@ -0,0 +1,525 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { footageAt } from "@/lib/report/footage-move.mjs";
+import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
+import { chromeTime, playPlan, skipEntries } from "@/lib/report/playCut.mjs";
+import { tallyCellsFrom, VERDICTS } from "umtool-report-to-video/factcheck";
+import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection";
+import { usePlayEngine } from "./playEngine/usePlayEngine";
+import { useRenderCuts } from "./playEngine/useRenderCuts";
+import type { ItemGate, MediaRef } from "./playEngine/engine";
+import { postPreload } from "./playEngine/postPreload";
+import PostItemPlayer, { postItemAssets } from "./PostItemPlayer";
+import SidePostOverlay from "./SidePostOverlay";
+import VideoEntryPlayer from "./VideoEntryPlayer";
+import TeaserCardPlayer, { type TeaserPage } from "./TeaserCardPlayer";
+import IntroCardPlayer from "./IntroCardPlayer";
+import { useIntroPage } from "./useIntroPage";
+import { videoStageAt } from "@/lib/report/playVideo.mjs";
+import ComboBadge from "./ComboBadge";
+import type { PlayEntry, PlayViewData } from "./PlayCut";
+
+// ---------------------------------------------------------------------------
+// THE PLAYER CORE, extracted from PlayCut (umtool redesign L7a): what plays the
+// draft -- or a version -- in the browser in its final look, with no render,
+// and nothing else. Play (PlayCut.tsx) and the workspace (workspace/Workspace.tsx)
+// both draw it; neither forks it.
+//
+// usePlayCore(view) the composition (the live preview's deck, POST
+// /api/report/chrome/preview), the plan (the estimate's
+// segments re-timed by the render's edges), the teasers'
+// and the intro's pages, the engine (one Web Audio clock,
+// the picture slaved to it), the post items' gate and
+// their fetching ahead -- and what is on screen now.
+// <PlayStage core/> the picture: the two <video> slots under the frame, the
+// deck (or the plain 16:9 frame), every card's player,
+// the overlays, the dip into a video entry.
+//
+// Everything a caller adds -- the transport, the notes, the strip, the keys,
+// the place in the URL -- is the caller's: the core does not know which page it
+// is on. PlayCut's own header comment is still the design of what plays.
+// ---------------------------------------------------------------------------
+
+export type LiveDoc = DeckPreviewDoc & {
+ leadIn?: number;
+ verdictLabels?: Record<string, string>;
+ tallyOrder?: string[];
+ tallyAlways?: string[];
+ schedule: DeckPreviewDoc["schedule"] & { finale?: { from: number; to: number } };
+};
+
+/** Play's "As published": post cards drawn with their redacted words as bars (post-redact.mjs). Per browser. */
+const AS_PUBLISHED_KEY = "umtool.play.asPublished";
+/** And which cut: censored (the slur filter on, post-slurs.mjs) or the uncensored one. Per browser. */
+const UNCENSORED_KEY = "umtool.play.uncensored";
+
+/**
+ * POST ITEMS FETCHED AHEAD (postPreload.ts; operator, 4 Nov: "the rapid sections ... don't load fast enough"):
+ * the post items whose start is within this many cut seconds after the one on screen -- at least PRELOAD_MIN of
+ * them, at most PRELOAD_MAX -- so a burst of short items has many ahead, a slow stretch a few.
+ */
+const PRELOAD_AHEAD_S = 20;
+const PRELOAD_MIN = 3;
+const PRELOAD_MAX = 24;
+/** The clock never waits longer than this on one item (a page that never says it is ready). */
+const GATE_MAX_MS = 15_000;
+
+const remember = (key: string, on: boolean) => {
+ try {
+ window.localStorage.setItem(key, on ? "on" : "off");
+ } catch {
+ // A preference, not state.
+ }
+};
+
+export function usePlayCore(view: PlayViewData, { showRejected = false }: { showRejected?: boolean } = {}) {
+ const project = view.project;
+ const take = view.take?.id ?? null;
+
+ // ---- the composition (the live preview's) ---------------------------------
+ const [doc, setDoc] = useState<LiveDoc | null>(null);
+ const [composeState, setComposeState] = useState<"composing" | "ready" | "no-deck" | "error">(view.deckOn ? "composing" : "no-deck");
+ const [composeError, setComposeError] = useState<string | null>(null);
+ const seq = useRef(0);
+ const compose = useCallback(async () => {
+ const mine = ++seq.current;
+ setComposeState("composing");
+ try {
+ const r = await fetch("/api/report/chrome/preview", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, estimate: true, ...(take ? { take } : {}) }),
+ });
+ const j = (await r.json().catch(() => ({}))) as LiveDoc & { error?: string; deckOn?: boolean };
+ if (mine !== seq.current) return;
+ if (!r.ok) {
+ setDoc(null);
+ setComposeState(j.deckOn === false ? "no-deck" : "error");
+ setComposeError(j.deckOn === false ? null : String(j.error ?? `HTTP ${r.status}`));
+ } else {
+ setDoc(j);
+ setComposeState("ready");
+ setComposeError(null);
+ }
+ } catch (e) {
+ if (mine === seq.current) {
+ setComposeState("error");
+ setComposeError(e instanceof Error ? e.message : String(e));
+ }
+ }
+ }, [project, take]);
+ useEffect(() => {
+ if (view.deckOn) void compose();
+ }, [compose, view.deckOn]);
+ // The deck is composed again whenever the manifest moved (its token): a Reject, a reorder, an
+ // Apply, the bench's save seen on the way back -- once, however the view came to be re-read.
+ const composedFor = useRef(view.token);
+ useEffect(() => {
+ if (view.token === composedFor.current) return;
+ composedFor.current = view.token;
+ if (view.deckOn) void compose();
+ }, [view.token, view.deckOn, compose]);
+ // A cut switched to Basic (or back) under the page: nothing composed for the deck that is no longer there.
+ useEffect(() => {
+ if (!view.deckOn) {
+ setDoc(null);
+ setComposeState("no-deck");
+ }
+ }, [view.deckOn]);
+
+ // ---- the plan ----------------------------------------------------------------
+ // The composed schedule, while it is the cut's ORDER: a reorder (the strip's drop) re-reads the
+ // view at once, and until the deck is composed again its segments would play the old order --
+ // so the estimate's (the view's own, in the new order) stand in meanwhile.
+ const composedOrder = doc?.schedule?.segments?.map((x) => x.id).join("\n") ?? null;
+ const viewOrder = useMemo(() => view.segments.map((x) => x.id).join("\n"), [view.segments]);
+ const scheduleNow = composedOrder !== null && composedOrder === viewOrder;
+ const schedule = scheduleNow ? (doc?.schedule ?? null) : null;
+ const segments = schedule?.segments ?? view.segments;
+ const leadIn = doc?.leadIn ?? view.leadIn;
+ // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change.
+ const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd, e.gaps ?? null])), [view.entries]);
+ const edges = useRenderCuts(project, take, edgesKey);
+ const [asPublished, setAsPublishedState] = useState(false);
+ const [uncensored, setUncensoredState] = useState(false);
+ useEffect(() => {
+ try {
+ if (window.localStorage.getItem(AS_PUBLISHED_KEY) === "on") setAsPublishedState(true);
+ if (window.localStorage.getItem(UNCENSORED_KEY) === "on") setUncensoredState(true);
+ } catch {
+ // A preference, not state.
+ }
+ }, []);
+ const setAsPublished = useCallback((on: boolean) => {
+ setAsPublishedState(on);
+ remember(AS_PUBLISHED_KEY, on);
+ }, []);
+ const setUncensored = useCallback((on: boolean) => {
+ setUncensoredState(on);
+ remember(UNCENSORED_KEY, on);
+ }, []);
+ const hasPosts = useMemo(() => view.entries.some((e) => e.type === "post"), [view.entries]);
+ const hasVideoEntries = useMemo(() => view.entries.some((e) => e.type === "video" && !!e.videoEntry), [view.entries]);
+ // THE TEASERS (lane leaflit-labels): each text card's own page, composed for preview (POST
+ // /api/report/chrome/teasers) and laid full frame while it is on screen -- the build's card, not a placeholder.
+ // Composed again whenever the manifest moved (its token), with or without a deck.
+ const teaserKey = useMemo(() => view.entries.filter((e) => e.type === "teaser").map((e) => e.id).join("\n"), [view.entries]);
+ // THE INTRO (lane intro-play): its page composed for preview (POST /api/report/chrome/intro), again when the manifest moved.
+ const introPage = useIntroPage(project, take, view.entries.some((e) => e.type === "intro"), view.token);
+ const [teaserPages, setTeaserPages] = useState<Record<string, TeaserPage | { id: string; error: string }>>({});
+ useEffect(() => {
+ if (!teaserKey) {
+ setTeaserPages({});
+ return;
+ }
+ let live = true;
+ void (async () => {
+ try {
+ const r = await fetch("/api/report/chrome/teasers", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, ...(take ? { take } : {}) }),
+ });
+ const j = (await r.json().catch(() => ({}))) as { teasers?: (TeaserPage | { id: string; error: string })[]; error?: string };
+ if (!live) return;
+ setTeaserPages(Object.fromEntries((j.teasers ?? []).map((x) => [x.id, x])));
+ } catch {
+ if (live) setTeaserPages({});
+ }
+ })();
+ return () => {
+ live = false;
+ };
+ }, [project, take, teaserKey, view.token]);
+ // Clips the walk REJECTED (a fact error, or irrelevant, weak, …) are SKIPPED unless the caller shows them.
+ const rejected = useMemo(() => view.entries.filter((e) => e.rejected), [view.entries]);
+ const skipIds = useMemo(() => new Set(showRejected ? [] : rejected.map((e) => e.id)), [showRejected, rejected]);
+ const plan = useMemo(
+ () => skipEntries(playPlan(segments, view.entries, { leadIn, cuts: edges.cuts }), skipIds),
+ [segments, view.entries, leadIn, edges.cuts, skipIds],
+ );
+ const entryOf = useMemo(() => new Map<string, PlayEntry>(view.entries.map((e) => [e.id, e])), [view.entries]);
+ const planRef = useRef(plan);
+ planRef.current = plan;
+
+ // ---- the engine (playEngine/: the sound on one Web Audio clock, the picture slaved to it) ----
+ const bg = doc?.background ?? "#000";
+ // `v` (the version of the window's bytes, playView): a window refetched under its old name is a new URL.
+ const srcOf = useCallback(
+ (id: string, m: MediaRef) =>
+ `/api/report/raw?${new URLSearchParams({ project, clip: id, ...(take ? { take } : {}), file: m.name, ...(m.v ? { v: m.v } : {}) }).toString()}`,
+ [project, take],
+ );
+ const audioOf = useCallback(
+ (id: string, m: MediaRef, from: number, to: number) =>
+ `/api/report/audio?${new URLSearchParams({
+ project, clip: id, ...(take ? { take } : {}), file: m.name, from: String(from), to: String(to), ...(m.v ? { v: m.v } : {}),
+ }).toString()}`,
+ [project, take],
+ );
+ // THE GATE (engine.ts): a post item plays once its player is ready -- its card drawn, its voice and its first
+ // attachment able to play -- and the clock waits on it, never cutting it short (a buffer stall's wait). Fetched
+ // ahead (postPreload.ts), its player is ready the frame its card is drawn; the clock holds on the item before
+ // while it is still fetching. `postReady`: what the MOUNTED player said (one at a time; "gone" as it unmounts).
+ // `started`: the item on screen once it has played -- a player mounted again under it (the deck composed) is not
+ // waited for (the clock runs on, as it always did).
+ const entryOfRef = useRef(entryOf);
+ entryOfRef.current = entryOf;
+ const postReady = useRef<string | null>(null);
+ const started = useRef<string | null>(null);
+ const gateAsked = useRef(new Map<string, number>());
+ const gate = useCallback<ItemGate>((id, next) => {
+ const e = entryOfRef.current.get(id);
+ if (!(e?.type === "post" && e.post && e.postPlan)) return "ready";
+ const now = performance.now();
+ const key = `${next ? "next" : "on"}:${id}`;
+ let since = gateAsked.current.get(key);
+ if (since === undefined) gateAsked.current.set(key, (since = now));
+ if (now - since > GATE_MAX_MS) return "ready";
+ if (next) return postPreload.itemState(id) === "loading" ? "fetching" : "ready";
+ if (started.current === id) return "ready";
+ if (postReady.current !== id) return "wait";
+ started.current = id;
+ return "ready";
+ }, []);
+ const onPostReady = useCallback((id: string, state: "ready" | "gone") => {
+ if (state !== "gone") postReady.current = id;
+ else if (postReady.current === id) postReady.current = null;
+ }, []);
+ const engine = usePlayEngine({
+ plan, entries: entryOf, srcOf, audioOf, blurRendered: view.blurRendered, bg, style: edges.style, edgesPending: edges.state === "measuring", gate,
+ });
+ const { ui, failed } = engine;
+ const setDuck = engine.setDuck;
+
+ // ---- what is on screen -------------------------------------------------------------
+ const t = ui.t;
+ // The chrome was composed on the estimate's clock: seeked by the source second playing.
+ const tc = chromeTime(plan, t);
+ const item = plan.items[ui.cur] ?? null;
+ const entry = item ? (entryOf.get(item.id) ?? null) : null;
+ const g = doc?.geometry ?? null;
+ const box: Rect | null = g ? (doc?.feed?.footage ?? g.footage) : null;
+ const move = schedule ? footageAt(schedule, tc) : null;
+ const rect: Rect | null = move?.rect ?? box;
+ const order = useMemo(
+ () => (schedule?.factcheck ? tallyCellsFrom(schedule.factcheck.stamps, doc?.tallyOrder ?? VERDICTS, doc?.tallyAlways ?? []) : []),
+ [schedule, doc?.tallyOrder, doc?.tallyAlways],
+ );
+ const tally = schedule?.factcheck ? tallyAt(schedule, tc, order) : [];
+ const stamp = schedule ? stampAt(schedule, tc) : null;
+ const finaleNow = !!schedule && finaleUp(schedule, tc);
+ const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, tc) : null;
+ const missing = !!item?.clip && !entry?.media;
+ const broken = !!item && !!failed[item.id];
+ // A post item plays its card and attachments (PostItemPlayer), not a placeholder.
+ const postNow = item && entry?.type === "post" && entry.post && entry.postPlan ? { item, entry } : null;
+ // A VIDEO entry (lib/report/playVideo.mjs): its file, the whole frame -- and the item before it darkening into it.
+ const vstage = hasVideoEntries ? videoStageAt(plan, entryOf, t) : null;
+ const videoNow = vstage?.video ? { ...vstage, video: vstage.video } : null;
+ // A teaser plays its own page (TeaserCardPlayer), once composed; until then -- or if it did not compose -- a placeholder.
+ const teaserPage = item && entry?.type === "teaser" ? teaserPages[item.id] : undefined;
+ const teaserNow = item && teaserPage && "src" in teaserPage ? { item, page: teaserPage } : null;
+ // THE INTRO (lane intro-play): the build's own page and its sound (IntroCardPlayer), once composed; until then -- or if
+ // it did not compose -- a placeholder that says so.
+ const introNow = item && entry?.type === "intro" && introPage && "src" in introPage ? { item, page: introPage } : null;
+ const placeholder = item && !postNow && !videoNow && !teaserNow && !introNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
+ // The clips' sound fades with the picture into a video entry and is off over it (its element plays its own).
+ const duck = vstage ? vstage.duck : 1;
+ useEffect(() => {
+ if (hasVideoEntries) setDuck(duck);
+ }, [hasVideoEntries, duck, setDuck]);
+ // A clip's side post (lane vertical): its card over the clip for the side's span (SidePostOverlay).
+ const sideEntry = item && entry?.type === "clip" ? (entry as { side?: { from: number; to: number; place?: string | null } }).side : undefined;
+
+ // ---- post items fetched ahead (postPreload.ts): from the one on screen, ~20 s on --------------------------
+ const postBox = box ? { width: box.width, height: box.height } : { width: 1920, height: 1080 };
+ const postBoxKey = `${Math.round(postBox.width)}x${Math.round(postBox.height)}`;
+ useEffect(() => {
+ // A new item on screen: its gate is asked afresh (a revisit waits as the first visit did).
+ gateAsked.current.clear();
+ }, [ui.cur, plan]);
+ // Another item on screen: the one before is no longer "started" (a revisit waits as the first visit did).
+ const curId = plan.items[ui.cur]?.id ?? null;
+ useEffect(() => {
+ if (started.current !== curId) started.current = null;
+ }, [curId]);
+ useEffect(() => {
+ // Not while the deck composes: its pages would be fetched at the plain frame's size (the deck's box is
+ // another URL), and the requests would queue ahead of the composition itself.
+ if (composeState === "composing") return;
+ const items = plan.items;
+ const i = ui.cur;
+ const [w, h] = postBoxKey.split("x").map(Number);
+ const assetsOf = (k: number) => {
+ const it = items[k];
+ const e = it ? entryOf.get(it.id) : null;
+ if (!e || e.type !== "post" || !e.post || !e.postPlan) return null;
+ const before = k > 0 ? entryOf.get(items[k - 1]?.id ?? "") : null;
+ const joinFrom = e.postPlan.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan } : null;
+ return postItemAssets({ project, take, entry: e.post, plan: e.postPlan, box: { width: w, height: h }, published: asPublished, uncensored, joinFrom });
+ };
+ const keep = [i - 1, i].map(assetsOf).filter((x): x is NonNullable<typeof x> => !!x);
+ const ahead: NonNullable<ReturnType<typeof assetsOf>>[] = [];
+ const from = items[i]?.to ?? 0;
+ for (let k = i + 1, n = 0; k < items.length && ahead.length < PRELOAD_MAX; k += 1, n += 1) {
+ if (items[k].from - from > PRELOAD_AHEAD_S && n >= PRELOAD_MIN) break;
+ const a = assetsOf(k);
+ if (a) ahead.push(a);
+ }
+ postPreload.want(ahead, keep);
+ }, [ui.cur, plan, entryOf, project, take, asPublished, uncensored, postBoxKey, composeState]);
+ useEffect(() => () => postPreload.clear(), []);
+
+ return {
+ view, project, take,
+ doc, composeState, composeError, compose,
+ schedule, edges, plan, planRef, entryOf, rejected, skipIds, hasPosts, hasVideoEntries,
+ teaserPages, introPage, engine, onPostReady, bg,
+ asPublished, setAsPublished, uncensored, setUncensored,
+ // what is on screen
+ t, tc, item, entry, g, box, move, rect, tally, stamp, finaleNow, postsWin, missing, broken,
+ postNow, vstage, videoNow, teaserPage, teaserNow, introNow, placeholder, sideEntry,
+ };
+}
+
+export type PlayCore = ReturnType<typeof usePlayCore>;
+
+const pct = (n: number, of: number) => `${(n / of) * 100}%`;
+
+/**
+ * THE PICTURE. The two <video>s sit full size UNDER the frame (which is opaque
+ * and drawn from them): an element the browser can see on the page loads and
+ * decodes a paused frame, where a hidden 1 px one was left at its metadata.
+ * They stay put while the frame above switches from plain to composed.
+ * `basic`: a basic cut -- the bare footage, as the basic render cuts it.
+ */
+export function PlayStage({ core, basic = false, plainClassName }: { core: PlayCore; basic?: boolean; plainClassName?: string }) {
+ const { project, take, doc, g, box, rect, move, tc, t, bg, engine, postNow, entryOf, plan, videoNow, vstage, teaserNow, introNow, placeholder, teaserPage, introPage, sideEntry, item, postsWin, finaleNow, asPublished, uncensored, onPostReady } = core;
+ const { ui, rate, failed } = engine;
+ const footageCanvas = (style: React.CSSProperties | undefined, w: number, h: number) => (
+ <canvas ref={engine.canvasRef} data-play-footage="" data-play-move={move ? move.segment : ""} width={w} height={h} className="absolute" style={style} />
+ );
+ const sideNow = item && sideEntry ? <SidePostOverlay project={project} take={take} clipId={item.id} side={sideEntry} s={Math.max(0, t - item.start)} published={asPublished} /> : null;
+ const postPlayer = (box2: { width: number; height: number }) =>
+ postNow ? (
+ <PostItemPlayer
+ key={postNow.item.id}
+ project={project}
+ take={take}
+ entry={postNow.entry.post!}
+ plan={postNow.entry.postPlan!}
+ box={box2}
+ s={Math.max(0, t - postNow.item.start)}
+ playing={ui.playing && !ui.waiting}
+ speed={rate}
+ published={asPublished}
+ uncensored={uncensored}
+ scene={postNow.entry.postScene ?? null}
+ clock={postNow.entry.postClock ?? null}
+ onReady={onPostReady}
+ progress={postNow.entry.postProgress ?? null}
+ joinFrom={(() => {
+ // THE JOIN (post-join.mjs): the item before, so this one opens on it as it ended.
+ const before = ui.cur > 0 ? entryOf.get(plan.items[ui.cur - 1]?.id ?? "") : null;
+ return postNow.entry.postPlan?.follow?.join && before?.type === "post" && before.post && before.postPlan ? { entry: before.post, plan: before.postPlan, clock: before.postClock ?? null } : null;
+ })()}
+ />
+ ) : null;
+ // A post item that repeats an earlier one's attachment: its combo badge, beside the player.
+ const comboBadge = (box2: { width: number; height: number }) =>
+ postNow?.entry.postCombo ? (
+ <ComboBadge
+ key={`combo-${postNow.item.id}`}
+ project={project}
+ entry={postNow.entry.post!}
+ plan={postNow.entry.postPlan!}
+ combo={postNow.entry.postCombo}
+ box={box2}
+ s={Math.max(0, t - postNow.item.start)}
+ playing={ui.playing && !ui.waiting}
+ />
+ ) : null;
+ // The video on screen: over EVERYTHING when the chrome is off over it (the default), else as the footage under it.
+ const videoPlayer = videoNow ? (
+ <VideoEntryPlayer
+ key={videoNow.id}
+ project={project}
+ id={videoNow.id}
+ video={videoNow.video}
+ src={videoNow.src ?? videoNow.video.from}
+ opacity={videoNow.opacity}
+ run={ui.playing && !ui.waiting && videoNow.playing}
+ speed={rate}
+ />
+ ) : null;
+ const videoOver = videoNow?.video.noChrome ? <div className="pointer-events-none absolute inset-0 z-30">{videoPlayer}</div> : null;
+ const videoUnder = videoNow && !videoNow.video.noChrome ? videoPlayer : null;
+ // The item before a video entry, darkening into it: the whole stage, its chrome with it.
+ const dipVeil = vstage && vstage.dark > 0 ? <div data-play-dip={vstage.id} className="pointer-events-none absolute inset-0 z-30 bg-black" style={{ opacity: vstage.dark }} /> : null;
+ // A teaser on screen: its page, seeked to the seconds into the card (the item's own clock, as a post item's).
+ const teaserCard = teaserNow ? <TeaserCardPlayer key={teaserNow.item.id} page={teaserNow.page} s={t - teaserNow.item.start} /> : null;
+ // The intro on screen: its page seeked to the seconds into it, its sound on Play's clock.
+ const introCard = introNow ? <IntroCardPlayer key={introNow.page.src} page={introNow.page} s={t - introNow.item.start} playing={ui.playing && !ui.waiting} speed={rate} /> : null;
+ const placeholderCard = placeholder ? (
+ <div
+ data-play-placeholder={placeholder.kind}
+ data-play-missing={placeholder.kind === "missing" ? placeholder.item.id : undefined}
+ className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-1.5 p-6 text-center"
+ style={{ background: placeholder.kind === "card" ? bg : "transparent" }}
+ >
+ {placeholder.kind === "card" ? (
+ <>
+ <span className="micro text-white/60">{placeholder.item.type}</span>
+ <span className="max-w-[80%] font-display text-[clamp(15px,2.6vw,32px)] font-semibold text-white">{placeholder.entry?.heading ?? placeholder.item.id}</span>
+ <span className="text-[11px] text-white/55">
+ {teaserPage && "error" in teaserPage
+ ? `the card did not compose: ${teaserPage.error}`
+ : placeholder.item.type === "teaser"
+ ? "composing the card…"
+ : placeholder.item.type === "intro"
+ ? introPage && "error" in introPage
+ ? `the intro did not compose: ${introPage.error}`
+ : "composing the intro…"
+ : "a placeholder: the build draws it"}
+ </span>
+ </>
+ ) : (
+ <span className="rounded-[3px] bg-black/75 px-2.5 py-1 text-[12.5px] text-white">
+ {core.broken ? `${failed[placeholder.item.id]} — ${placeholder.item.id} plays on as a placeholder` : `No media for ${placeholder.item.id} — fetch it`}
+ <span className="mt-0.5 block font-mono text-[11px] text-white/60">
+ {placeholder.entry?.video}@{placeholder.entry?.start}–{placeholder.entry?.end}
+ </span>
+ </span>
+ )}
+ </div>
+ ) : null;
+
+ return (
+ <>
+ <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
+ <video ref={engine.slotRef0} data-play-slot="0" preload="auto" playsInline muted onError={() => engine.onMediaError(0)} className="absolute inset-0 h-full w-full" />
+ <video ref={engine.slotRef1} data-play-slot="1" preload="auto" playsInline muted onError={() => engine.onMediaError(1)} className="absolute inset-0 h-full w-full" />
+ </div>
+ <div className="relative">
+ {doc && g && box ? (
+ <DeckFrame preview={doc} t={tc} texts={{}} testid="play-deck">
+ <div className="absolute inset-0" style={{ background: bg }} />
+ {footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)}
+ {videoUnder}
+ {postNow && (g.post ?? rect) && (() => {
+ // The stacked vertical deck lays a post item as its hero card (deck.mjs deckGeometry `post`).
+ const pr = g.post ?? rect!;
+ const pb = g.post ?? box;
+ return (
+ <div className="absolute" style={{ left: pct(pr.x, g.W), top: pct(pr.y, g.H), width: pct(pr.width, g.W), height: pct(pr.height, g.H), background: bg }}>
+ {postPlayer({ width: pb.width, height: pb.height })}
+ {comboBadge({ width: pb.width, height: pb.height })}
+ </div>
+ );
+ })()}
+ {teaserCard}
+ {introCard}
+ {placeholderCard}
+ {sideNow && rect && <div className="pointer-events-none absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) }}>{sideNow}</div>}
+ {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />}
+ {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />}
+ {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />}
+ {/* Every module that declares `play` (chapters, then and now, the status ledger …), by z. */}
+ <ModuleLayers layers={doc.layers} frame={g} t={tc} testid="play-layer" />
+ {doc.finale && finaleNow && (
+ <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale="">
+ <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={tc} ready="finale:ready" testid="play-finale" name="finale" />
+ </div>
+ )}
+ </DeckFrame>
+ ) : (
+ <div
+ className={plainClassName ?? "relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0"}
+ style={{ aspectRatio: "16 / 9" }}
+ data-testid="play-plain"
+ // A basic cut: the bare footage, as the basic render cuts it -- no card, no side post, nothing over it.
+ data-play-bare={basic ? "" : undefined}
+ >
+ {footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
+ {!basic && postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}{comboBadge({ width: 1920, height: 1080 })}</div>}
+ {!basic && videoUnder}
+ {!basic && teaserCard}
+ {!basic && introCard}
+ {!basic && placeholderCard}
+ {!basic && sideNow}
+ </div>
+ )}
+ {dipVeil}
+ {videoOver}
+ {ui.playing && ui.waiting && (
+ // The clock held (engine.ts): a clip's sound decoding, a post item loading -- it plays in full once here.
+ <span data-play-loading="" className="pointer-events-none absolute right-2 top-2 z-40 rounded-full bg-black/70 px-2 py-0.5 text-[11px] text-white">
+ loading…
+ </span>
+ )}
+ </div>
+ </>
+ );
+}
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 = 76;
+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 min-w-0 items-baseline gap-1 overflow-hidden whitespace-nowrap font-mono text-[10.5px] text-muted">
+ {b.seconds ? `${b.seconds.toFixed(1)} s` : b.rejected ? "skipped" : ""}
+ {b.missing && <span className="truncate 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,554 @@
+"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";
+import GeneratedBanner from "@/components/notes/GeneratedBanner";
+
+// ---------------------------------------------------------------------------
+// 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,
+ generatedBy = null,
+}: {
+ view: PlayViewData;
+ initialBlock?: string | null;
+ introWritten?: unknown;
+ hasLedger?: boolean;
+ /** The manifest's `generatedBy`: a rebuild overwrites edits made here, said under the top bar. */
+ generatedBy?: string | null;
+}) {
+ 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 [tlToken, setTlToken] = useState<string | null>(null);
+ 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);
+ setTlToken(tl.current.token);
+ }
+ 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 });
+ const undoRef = useRef(undo);
+ undoRef.current = undo;
+ /** Bumped by the workspace's own structural writes: the inspector's panels are read afresh. */
+ const [epoch, setEpoch] = useState(0);
+ 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;
+ let res = await timelineOp(project, token, op, args);
+ // The draft moved since the token was read -- a panel's save a moment ago, announced but not read back yet.
+ // A move names its index (refused if that is not it any more), so it is asked once more on the fresh token;
+ // an Undo or a Redo NEVER is: it would take back (or put back over) an edit this page has not seen. The
+ // refusal is said, and the token read again for the next press.
+ if (!res.ok && res.json.stale && op === "move") res = await timelineOp(project, (await loadTimeline()).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;
+ setTlToken(tl.current.token);
+ 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). The workspace's own writes (above) do not announce: they
+ // read the draft again themselves, and remount the inspector (`epoch`).
+ useEffect(() => {
+ let t: ReturnType<typeof setTimeout> | null = null;
+ const on = (e: Event) => {
+ if ((e as CustomEvent).detail?.project !== project) return;
+ setUndo((u) => ({ ...u, canRedo: false, said: null }));
+ if (t) clearTimeout(t);
+ // The token first (the next Undo is asked on it), then the view.
+ t = setTimeout(() => {
+ void loadTimeline().then(() => reloadView());
+ }, 60);
+ };
+ 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],
+ );
+ // `?block=` (an address, a reload): the viewer goes to that block once the plan has it, once.
+ const placed = useRef(false);
+ useEffect(() => {
+ if (placed.current || !selected || selected === ADD) return;
+ const p = itemOf.get(selected);
+ if (!p) return;
+ placed.current = true;
+ engine.seekTo(startOf(planRef.current, p.i));
+ }, [itemOf, selected, 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(
+ async (d: 1 | -1) => {
+ const b = blocks.find((x) => x.id === selected);
+ if (!b || b.type === "intro" || undo.busy) return;
+ // Its place in the manifest's timeline, read now if the strip has not had it yet.
+ const ids = tl.current.ids.length ? tl.current.ids : (await loadTimeline()).ids;
+ const at = ids.indexOf(b.id);
+ if (at < 0) return;
+ await move(b.id, at, at + d);
+ },
+ [blocks, selected, move, undo.busy, loadTimeline],
+ );
+
+ // ---- 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) {
+ if (undoRef.current.canRedo && !undoRef.current.busy) void doRedo();
+ } else if (!undoRef.current.busy) void doUndo();
+ ev.preventDefault();
+ return;
+ }
+ if (mod && !ev.altKey && (k === "y" || k === "Y") && ev.ctrlKey) {
+ if (undoRef.current.canRedo && !undoRef.current.busy) void doRedo();
+ ev.preventDefault();
+ return;
+ }
+ if (mod) return;
+ if (ev.altKey) {
+ if (k === "ArrowLeft") void moveSelected(-1);
+ else if (k === "ArrowRight") void 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 --------------------------------
+ // The frame's own shape: a 9:16 cut (the stacked vertical deck) is tall.
+ const aspect = core.g ? core.g.W / core.g.H : 16 / 9;
+ 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(120, Math.floor(Math.min(r.width, r.height * aspect))));
+ };
+ fit();
+ const ro = new ResizeObserver(fit);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [aspect]);
+
+ // ---- 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}
+ // The draft's token as this page last read it (a spec waits on it before pressing Undo after a save).
+ data-ws-token={tlToken ?? ""}
+ 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)}
+ />
+ {generatedBy && (
+ <div className="border-b border-seam px-3 py-1">
+ <GeneratedBanner generatedBy={generatedBy} />
+ </div>
+ )}
+ <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="max-w-[46ch] truncate text-reject-text" title={`the chrome did not compose: ${core.composeError}`} data-ws-compose-error="">
+ 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,34 @@
+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; generatedBy?: 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}
+ generatedBy={typeof manifest.generatedBy === "string" ? manifest.generatedBy : null}
+ />
+ </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/docs/cli.md b/umtool/docs/cli.md
@@ -319,6 +319,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `timeline <project> teaser <id> <patch>` | a teaser's lines, beat, dip, tail | form · *draft* |
| `timeline <project> teaser-insert [--at end\|start] [--after AFTER] [--before BEFORE] [--id ID] [--beat N] [--line LINE…] [--lines-json JSON]` | a teaser or closing card inserted (default at the end) | form · *draft* |
| `timeline <project> undo [--take TAKE]` | the newest automatic snapshot back | form · *draft* |
+| `timeline <project> redo` | what the newest undo took back, put back (no edit since it) | form · *draft* |
| `timeline <project> sections` | the deck's sections and their clips | form · *project* |
| `timeline <project> section-move <ids>… --to-section N [--start]` | clips to the end (or start) of section N | form · *draft* |
| `timeline <project> section-add --after AFTER [--label LABEL] [--color COLOR] [--level 1\|2]` | a new section after a clip | form · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -714,6 +714,47 @@ expected the cut). A take is a **saved version** — FROZEN:
the Open in draft page now — then the draft's bench. The take-scoped CLI (`--in-take`, `umtool timeline <p> --take`,
`umtool window --take`, `/api/report/takes/timeline`) stays for agents.
+## The workspace (one screen per report video)
+
+`/projects/<p>` — a report video's own address — is **the workspace** (umtool redesign L7a): one screen at 1366×768,
+nothing scrolling but the strip and the inspector. The piece page's tabs are `?tab=` (`?tab=overview` written out;
+the piece head's ⋯ **More → Open the workspace** comes back), and a claimed project's own address is its workspace too (its tabs still go
+to the article's piece). `?block=<id>` opens with that block selected.
+
+| Knob | UI | CLI twin |
+|---|---|---|
+| the draft's line, versions | the top bar: **Draft · from v2 · 3 edits**; **Versions ▾** — each version's **Play** (read-only) and **Open in draft**, and **Save version** | `umtool takes ls <p>` · `takes open <p> <t>` · `takes save <p>` |
+| mode | **Edit** · **Review pass** (the walk, until L7b brings it in) · **Present ⛶** | `umtool walk <p>` · `umtool present <p>` |
+| look | **Look Basic \| Deck** (`render.mode`) | `umtool look <p> mode=basic\|deck` |
+| render the draft | **Render ▾** — **Render 60 s**, **Render full** (a take of the draft, queued) | `umtool take <p> --at 0 --dur 60` · `umtool take <p> --full` |
+| share | **Copy share line** for the selected clip (else the one on screen) | `umtool share <p> <clip>` |
+| move a block | the strip: drag a block onto a place, or **Alt+← →** on the selected one (the timeline's `move`) | `umtool timeline <p> move <id> --to <index>` |
+| add | the strip's **+**: Add a clip, Add posts, insert a teaser or closing card | `umtool timeline <p> insert …` · `umtool posts add …` · `umtool timeline <p> teaser-insert …` |
+| undo / redo | **Undo**, **Redo** (⌘Z / Ctrl+Z, ⌘⇧Z / Ctrl+Y) | `umtool timeline <p> undo` · `umtool timeline <p> redo` |
+
+- **The viewer is Play's player core** (`components/projects/review/playCore.tsx`: `usePlayCore` + `PlayStage`, the same
+ code Play draws — not a copy): the draft live, the intro, the deck, the post items and the teasers as Play plays
+ them. Space plays and pauses; **‹ ›** (and **← →**) step the selected block, and the viewer goes to its start.
+- **The inspector is the selected block's**, each panel the one its own page draws, mounted unchanged: a **clip** —
+ the clip bench's work column (`ClipBench` `layout="inspector"`: the window row with **Save window**, the instrument
+ with its handles and gaps, the cue rail; its keys `[ ] , .` `g G` `z f` are its own while the focus is in it; the
+ verdict, the claim and the attribution stay on the **Full bench**) and its **Life cycle**; a **post item** — the post
+ item panel (excerpt, media, my recording) and the post bench (`PostBench` `layout="inspector"`); a **card** — the
+ teaser panel; the **intro** — the intro editor; **nothing** (Esc) — the project's panels (title, provenance, links,
+ ledger, a still).
+- **E edits in place**: the selected clip on the full bench over the workspace (the CutApp shell: the viewer stays
+ mounted, paused), and **Back to the cut** returns to it; a post item opens its own bench.
+- **Every edit lands in the draft.** What takes an undo point (`revisions/<stamp>-auto-before-<op>`): every structural
+ write (a move, a remove, an insert, a section, a group, a teaser, a reject, an open of a version, the inspector
+ panels' writes), a clip's moved edge (`trim`) and its gaps (`gaps`) — each its own in the app; from a terminal or
+ a step the app queues, one per op every two minutes. What does NOT: a clip's fields that move no edge (its title,
+ date, quote, attribution), a verdict, a saved version. **Undo** takes back the newest undo point. **Redo** puts back
+ what the newest Undo took back, and only while the draft is EXACTLY as that undo left it: an undo records a hash of
+ the manifest and `takes/draft.json` beside it (`<stamp>-undo-saved.redo.json`), and a redo refuses — *the draft
+ changed since the undo — nothing to redo* — after any write since, whichever writer and whether or not it took an
+ undo point. A redo renames the point back to `auto-before-<op>`, so the next Undo takes the redone edit back again
+ (`lib/report/manifest.mjs` redoStructural). `undo-saved` and `redone-*` keep their newest 200, as the undo points do.
+
## Play the cut (the whole cut, or a take, with no render)
`/projects/<p>/play` — the head's **▶ Play the draft**, or a version's **Play** on the takes page
diff --git a/umtool/e2e/add-clip.spec.ts b/umtool/e2e/add-clip.spec.ts
@@ -31,7 +31,7 @@ test.afterEach(() => {
test("Add a clip: find the words, in and out on the cues, after a row, added and fetched", async ({ page }) => {
test.setTimeout(120_000);
// The head's + Add a clip lands on the Cut tab with the panel open.
- await page.goto(urls.projectHref(P));
+ await page.goto(urls.projectHref(P, { tab: "overview" }));
await page.locator("[data-primary-add-clip]").click();
await expect(page.locator('[data-add-clip="cut"]')).toBeVisible();
diff --git a/umtool/e2e/article-delete.spec.ts b/umtool/e2e/article-delete.spec.ts
@@ -143,7 +143,7 @@ test("a take the project's manifest is, is refused until forced; another take an
expect(existsSync(path.join(PROJECT, "takes", "drop"))).toBe(false);
expect(existsSync(path.join(PROJECT, "takes", "keep", "take.json"))).toBe(true);
- await page.goto("/browse/reports/delete-fixture");
+ await page.goto(urls.projectHref("reports/delete-fixture", { tab: "overview" }));
// Delete is in the piece head's ⋯ menu (P4a-1).
await page.getByRole("button", { name: "More" }).click();
await page.getByRole("button", { name: "Delete project" }).click();
diff --git a/umtool/e2e/cut-integrity.spec.ts b/umtool/e2e/cut-integrity.spec.ts
@@ -91,7 +91,7 @@ test.afterAll(() => {
const row = (page: Page, kind: string, target: string) => page.locator(`[data-decision="${kind}"][data-target="${target}"]`);
test("the check rows: an overlap, a clock and QR off the clip, a stale take patch, links never checked — each with its settle and its fix", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
const overlap = row(page, "window-overlap", "c01");
await expect(overlap).toContainText("overlaps c02 by 2.0s");
await expect(overlap.locator('[data-settle-button="c02"]')).toHaveText("It's deliberate: c02 repeats c01");
@@ -111,7 +111,7 @@ test("the check rows: an overlap, a clock and QR off the clip, a stale take patc
});
test("#3 It's deliberate: repeatOf through the writer, the row gone, the chip on the Cut tab and the bench", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await row(page, "window-overlap", "c01").locator('[data-settle-button="c02"]').click();
await expect(row(page, "window-overlap", "c01")).toHaveCount(0);
expect(entry("c02")?.repeatOf).toBe("c01");
@@ -132,7 +132,7 @@ test("#3 It's deliberate: repeatOf through the writer, the row gone, the chip on
});
test("#5 Move to 0:06: the clock and the QR back on the clip, and the row gone", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await row(page, "clip-cite-off", "c03").locator('[data-settle-button="c03"]').click();
await expect(row(page, "clip-cite-off", "c03")).toHaveCount(0);
expect(entry("c03")?.cite).toBe(6);
@@ -176,7 +176,7 @@ test("#7 ★ (s) and the walk note on the bench: not a verdict, not a correction
});
test("#8 Check links: one link dead on the site blocks, naming the clip and why; offline they are not verified", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await row(page, "links-unchecked", "QR links").locator('[data-settle-button="links"]').click();
const host = new URL(origin).host;
const dead = row(page, "link-dead", host);
@@ -212,7 +212,7 @@ test("#6 removing a clip re-anchors the take patch's markers; the hand-made one
const patchMarkers = () =>
(JSON.parse(readFileSync(path.join(DIR, "draft-1.patch.json"), "utf8")) as { render: { chrome: { deck: { markers: { after: string; label: string }[] } } } }).render.chrome.deck.markers;
await expect.poll(patchMarkers).toEqual([{ after: "c02", label: "After four" }, { after: "gone", label: "Hand-made" }]);
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).toContainText('"Hand-made" after gone — a take made with --patch draft-1.patch.json is refused');
await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).not.toContainText("After four");
await shot(page, "6-patch-markers-stale");
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -2161,6 +2161,26 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out
rmSync(path.join(dvDir, "takes"), { recursive: true, force: true });
}
+// THE WORKSPACE (workspace.spec.ts, umtool redesign L7a, WRITES): play-cut-fixture's cut on vid1 (its cues: the
+// inspector's cue rail) with a text post item after c02 -- c01 c02 p-5 k01 c03 c04 -- and its made take
+// (takes/short/take.json), which no edit here may touch.
+{
+ const { dir: wsDir } = makePlayCutFixture({
+ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"),
+ name: "workspace-fixture", title: "The Workspace Fixture", video: "vid1",
+ });
+ const wsFile = path.join(wsDir, "video.manifest.json");
+ const wsM = JSON.parse(readFileSync(wsFile, "utf8"));
+ // The counter's cell word short enough for the tally's cell (play-cut-fixture's "Seizures" no longer fits since
+ // the tally's 72 px row): the deck COMPOSES here, so workspace.spec can say a composition failure is a regression.
+ wsM.render.chrome.factcheck.verdicts.CORROBORATED.tallyLabel = "Seized";
+ wsM.timeline.splice(2, 0, {
+ type: "post", id: "p-5", post: "postchan-x/5", platform: "x", author: "Post Subject", handle: "postsubject",
+ date: "2026-10-30T12:00:00.000Z", text: "The scale said 291 this morning. I said the scale was broken.", url: "https://x.com/postsubject/status/5", subjects: ["postsubject"],
+ });
+ writeFileSync(wsFile, JSON.stringify(wsM, null, 2) + "\n");
+}
+
// The inspector panels (inspector-*.spec.ts, umtool redesign L6, WRITE): one project per panel
// (inspector-fixture.mjs), each with a take the specs check is never written.
await makeInspectorFixtures({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture });
diff --git a/umtool/e2e/phone.spec.ts b/umtool/e2e/phone.spec.ts
@@ -98,7 +98,7 @@ test.describe("on a phone (390×844)", () => {
test.use({ viewport: PHONE, isMobile: true, hasTouch: true });
test("the shell: the place bar and the dock, the title in flow, no rail", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await hydrated(page);
await expect(page.locator("[data-app-rail]")).toBeHidden();
const bar = page.locator("[data-place-bar]");
@@ -213,7 +213,7 @@ test.describe("on a phone (390×844)", () => {
test("the piece's ⋯ → Done says what it did; Undo puts it back in Active", async ({ page, request }) => {
try {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await hydrated(page);
await page.locator("[data-place-more]").tap();
const sheet = page.getByRole("dialog", { name: "Page actions" });
@@ -339,7 +339,7 @@ test.describe("at 360×740", () => {
// ── the desk is unchanged ───────────────────────────────────────────────────
test("on the desk the head is as it was: the rail, the trail, the actions inline, the stepper; no phone chrome", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await expect(page.locator("[data-app-rail]")).toBeVisible();
await expect(page.locator("[data-place-bar]")).toBeHidden();
await expect(page.locator("[data-phone-dock]")).toBeHidden();
diff --git a/umtool/e2e/piece.spec.ts b/umtool/e2e/piece.spec.ts
@@ -22,7 +22,7 @@ const tab = (page: Page, id: string) => page.getByTestId(`piece-tab-${id}`);
const keysReady = (page: Page) => expect(page.locator("[data-piece-keys=ready]")).toBeAttached();
test("the frame: title, trail, stepper at Video, the Next card, seven tabs with the Overview lit", async ({ page }) => {
- const res = await page.goto(urls.projectHref(PROJECT));
+ const res = await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
expect(res?.status()).toBe(200);
const crumbs = page.getByRole("navigation", { name: "Breadcrumb" });
await expect(crumbs.locator("h1")).toHaveText("The Report Fixture");
@@ -66,7 +66,7 @@ test("the Next card is the piece's top Inbox call, and its one action goes where
const top = inbox.groups.filter((g) => g.id !== "quiet").flatMap((g) => g.cards).find((c) => c.piece === PIECE);
expect(top, "the fixture's report has a call waiting").toBeTruthy();
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
const next = page.locator("[data-next]:visible");
await expect(next.locator("[data-next-kind]")).toHaveAttribute("data-next-kind", top!.kind);
const action = next.locator("[data-next-action] > a:visible");
@@ -89,9 +89,12 @@ test("the tab is the URL: ?tab=, ?all=1 on the Cut, a bad tab the Overview, and
await page.goto(`${urls.projectHref(PROJECT)}?tab=nonsense`);
await expect(tab(page, "overview")).toHaveAttribute("aria-current", "page");
- // /browse/<project> (before P3) rides the redirect to the Overview.
+ // /browse/<project> (before P3) rides the redirect to the project's own address: its workspace (L7a);
+ // the Overview is written out.
await page.goto(`/browse/${PROJECT}`);
await expect(page).toHaveURL(new RegExp(`/projects/${PROJECT}$`));
+ await expect(page.locator(`[data-workspace="${PROJECT}"]`)).toBeVisible();
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await expect(tab(page, "overview")).toHaveAttribute("aria-current", "page");
// Clicking a tab is a link: the address changes, the section is there.
@@ -120,7 +123,7 @@ test("the lifecycle chip: Park, then Reactivate, each a round trip through the s
((await (await request.get("/api/pieces")).json()) as { pieces: { id: string; lifecycle: string }[] }).pieces.find((p) => p.id === PIECE)
?.lifecycle;
try {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
const chip = page.locator("[data-lifecycle-chip]");
await expect(chip).toHaveAttribute("data-lifecycle-chip", "active");
await chip.getByRole("button", { name: "Lifecycle: Active" }).click();
@@ -147,7 +150,7 @@ test("the lifecycle chip: Mark done says it hid the piece from Active, and Undo
((await (await request.get("/api/pieces")).json()) as { pieces: { id: string; lifecycle: string }[] }).pieces.find((p) => p.id === PIECE)
?.lifecycle;
try {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
const chip = page.locator("[data-lifecycle-chip]");
await chip.getByRole("button", { name: "Lifecycle: Active" }).click();
await chip.getByRole("button", { name: "Mark done" }).click();
@@ -165,7 +168,7 @@ test("the lifecycle chip: Mark done says it hid the piece from Active, and Undo
});
test("keys: 1–7 open the tabs, n runs the Next card's action; typing in a field is left alone", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await keysReady(page);
await page.keyboard.press("2");
await expect(page).toHaveURL(/\?tab=cut$/);
@@ -263,7 +266,9 @@ test("a claimed project's address redirects to its article piece on the same tab
return { status: r.status(), location: r.headers()["location"] ?? "" };
};
expect(await at(urls.projectHref(ZETA_CUT, { tab: "build" }))).toEqual({ status: 307, location: urls.articleHref(ZETA, { tab: "build" }) });
- expect(await at(urls.projectHref(ZETA_CUT))).toEqual({ status: 307, location: urls.articleHref(ZETA) });
+ expect(await at(urls.projectHref(ZETA_CUT, { tab: "overview" }))).toEqual({ status: 307, location: urls.articleHref(ZETA) });
+ // Its own address is its workspace (L7a): the video's one screen, claimed or not.
+ expect((await at(urls.projectHref(ZETA_CUT))).status).toBe(200);
expect(await at(urls.projectHref(ZETA_OTHER, { tab: "sources" }))).toEqual({
status: 307,
location: urls.articleHref(ZETA, { tab: "sources", project: ZETA_OTHER }),
@@ -276,6 +281,9 @@ test("a claimed project's address redirects to its article piece on the same tab
await page.goto(`/browse/${ZETA_CUT}?tab=history`);
await expect(page).toHaveURL(new RegExp(`/articles/zeta\\?tab=history$`));
await expect(tab(page, "history")).toHaveAttribute("aria-current", "page");
+ // The video's workspace is its own address: the article piece's ⋯ More leads there.
+ await page.getByRole("button", { name: "More" }).click();
+ await expect(page.locator(`[data-primary-workspace="${ZETA_CUT}"]`)).toHaveAttribute("href", urls.workspaceHref(ZETA_CUT));
// The benches and kind views stay at the project's address, and lead back to the piece.
expect((await at(urls.takesHref(ZETA_CUT))).status).toBe(200);
@@ -318,7 +326,7 @@ test("a note on the video lands on its tab inside the article piece", async ({ p
test("fits 1366×768: the head, the tabs and the Next card's action without a horizontal scroll", async ({ page }) => {
await page.setViewportSize({ width: 1366, height: 768 });
- for (const href of [urls.projectHref(PROJECT), urls.articleHref(ZETA)]) {
+ for (const href of [urls.projectHref(PROJECT, { tab: "overview" }), urls.articleHref(ZETA)]) {
await page.goto(href);
await expect(page.locator("[data-next-action] > :is(a, button):visible")).toBeInViewport();
await expect(tab(page, "history")).toBeInViewport();
@@ -341,7 +349,7 @@ test("a video started from a research board: Research done, Article not applicab
const done = await request.post(`/api/research/cases/${id}/handoff`, { data: { to: "video", slug, confirm: true } });
expect(done.ok(), await done.text()).toBe(true);
- await page.goto(urls.projectHref(slug));
+ await page.goto(urls.projectHref(slug, { tab: "overview" }));
const steps = page.getByRole("list", { name: "Stage" }).locator("li");
await expect(steps.nth(0)).toHaveAttribute("data-step", "done");
await expect(steps.nth(1)).toHaveAttribute("data-step", "na");
diff --git a/umtool/e2e/source-backlog.spec.ts b/umtool/e2e/source-backlog.spec.ts
@@ -48,7 +48,7 @@ test.afterAll(async ({ request }) => {
});
async function open(page: Page) {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
await expect(page.getByTestId("source-backlog")).toBeVisible({ timeout: 20_000 });
}
diff --git a/umtool/e2e/ui-ops.spec.ts b/umtool/e2e/ui-ops.spec.ts
@@ -85,7 +85,7 @@ test.beforeAll(async ({ playwright }) => {
// The site the QRs open, as transcripts/sites/<id>/site.json names it.
mkdirSync(SITE_DIR, { recursive: true });
writeFileSync(path.join(SITE_DIR, "site.json"), JSON.stringify({ siteId: "ui-ops-site", siteTitle: "UI Ops Site", siteUrl: origin, channels: [{ slug: "uiopschan", order: 0 }] }));
- await warm(playwright, [urls.projectHref(PROJECT), urls.takesHref(PROJECT), urls.clipBenchHref(SPEAKERS, "k04")]);
+ await warm(playwright, [urls.projectHref(PROJECT, { tab: "overview" }), urls.takesHref(PROJECT), urls.clipBenchHref(SPEAKERS, "k04")]);
});
test.afterAll(() => {
server?.close();
@@ -97,7 +97,7 @@ const row = (page: Page, kind: string, target: string) => page.locator(`[data-de
test("#9 the sites the links depend on: the deploy's date, the cited videos newer than it, and Publish <site>", async ({ page }) => {
const host = new URL(origin).host;
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
const site = page.locator(`[data-link-site="${host}"]`);
await expect(site).toHaveAttribute("data-link-site-id", "ui-ops-site");
await expect(site.locator("[data-link-site-deploy]")).toContainText("deploy date unknown · not checked yet");
@@ -120,7 +120,7 @@ test("#9 the sites the links depend on: the deploy's date, the cited videos newe
});
test("#10 the link policy: cite via ui-ops-site, uiopsdirect direct; the check's row and its fix; a new clip is written by it", async ({ page }) => {
- await page.goto(urls.projectHref(PROJECT));
+ await page.goto(urls.projectHref(PROJECT, { tab: "overview" }));
const panel = page.locator("[data-link-policy]");
await expect(panel).toHaveAttribute("data-link-policy", "none");
// "Cite via ui-ops-site; uiopsdirect direct."
diff --git a/umtool/e2e/workspace.spec.ts b/umtool/e2e/workspace.spec.ts
@@ -0,0 +1,210 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// THE WORKSPACE (umtool redesign L7a; components/projects/workspace/): a report video's own address is one
+// screen -- the top bar, the viewer (Play's player core), the strip of blocks, the inspector chosen by the
+// selected block -- and every edit made in it lands in THE DRAFT, never in a take, with one undo stack.
+//
+// workspace-fixture (WRITES; make-fixture.mjs): play-cut-fixture's cut on vid1 with a post item after c02 --
+// c01 c02 p-5 k01 c03 c04 -- and its made take, takes/short/take.json, which nothing here may touch. The tests
+// run in order, each leaving what the next reads.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial" });
+
+const P = "reports/workspace-fixture";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "workspace-fixture");
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const manifest = () => JSON.parse(manifestText()) as { timeline: { id: string; start?: number; end?: number }[] };
+const order = () => manifest().timeline.map((e) => e.id).join(" ");
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+const viewer = (page: Page) => page.locator("[data-ws-viewer]");
+const blocks = (page: Page) => page.locator("[data-ws-block]");
+const blockIds = (page: Page) => blocks(page).evaluateAll((els) => els.map((e) => e.getAttribute("data-ws-block")));
+
+test.beforeEach(async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 768 });
+});
+
+test("one screen at 1366×768: the top bar, the viewer plays the draft, the strip's blocks, no page scroll", async ({ page }) => {
+ expect(order()).toBe("c01 c02 p-5 k01 c03 c04");
+ await page.goto(urls.workspaceHref(P));
+ await expect(page.locator(`[data-workspace="${P}"]`)).toBeVisible();
+ await expect(page.locator("[data-ws-title]")).toHaveText("The Workspace Fixture");
+ await expect(page.locator("[data-ws-draft]")).toContainText("Draft");
+ await expect(page.locator("[data-ws-mode-edit]")).toHaveAttribute("aria-current", "page");
+ await expect(page.locator("[data-ws-mode-present]")).toHaveAttribute("href", urls.presentHref(P));
+ expect(await blockIds(page)).toEqual(["c01", "c02", "p-5", "k01", "c03", "c04"]);
+ await expect(page.locator('[data-ws-block="c03"]')).toContainText("no media");
+ // Nothing selected: the project's own panels (L6).
+ await expect(page.locator("[data-ws-inspector]")).toHaveAttribute("data-ws-inspector", "project");
+ await expect(page.locator('[data-ws-project-panels] [data-inspector="title"]')).toBeVisible();
+ // The page itself never scrolls: only the inspector and the strip do.
+ const fit = await page.evaluate(() => ({ h: document.documentElement.scrollHeight, w: document.documentElement.scrollWidth, ih: window.innerHeight, iw: window.innerWidth }));
+ expect(fit.h).toBeLessThanOrEqual(fit.ih);
+ expect(fit.w).toBeLessThanOrEqual(fit.iw);
+
+ // The viewer: the draft, on Play's clock, from the cached window.
+ await expect(viewer(page)).toHaveAttribute("data-play-state", "paused");
+ await expect(viewer(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ // The deck composes (the live preview's pages), as Play's does: no "the chrome did not compose".
+ await expect(viewer(page)).toHaveAttribute("data-play-compose", "ready", { timeout: 60_000 });
+ await expect(page.locator("[data-ws-compose-error]")).toHaveCount(0);
+ await expect(page.locator('[data-ws-viewer] [data-testid="play-deck"]')).toBeVisible();
+ await page.locator("[data-ws-play]").click();
+ await expect(viewer(page)).toHaveAttribute("data-play-item", "c01");
+ await expect.poll(async () => Number(await viewer(page).getAttribute("data-play-t")), { timeout: 20_000 }).toBeGreaterThan(0.5);
+ await expect(page.locator('[data-ws-block="c01"]')).toHaveAttribute("data-ws-block-now", "");
+ // Space pauses (the workspace's key).
+ await page.keyboard.press("Space");
+ await expect(viewer(page)).toHaveAttribute("data-play-state", "paused");
+ await page.screenshot({ path: path.join(process.env.WS_SHOTS ?? path.join(DIR, ".."), "ws-overview.png") }).catch(() => {});
+});
+
+test("a clip block: the inspector is the bench's window and word strip; a nudged edge lands in the draft, not the take; Undo and Redo", async ({ page }) => {
+ const original = manifestText();
+ const take = takeText();
+ await page.goto(urls.workspaceHref(P));
+ await page.locator('[data-ws-block="c01"]').click();
+ await expect(page.locator('[data-ws-block="c01"]')).toHaveAttribute("aria-selected", "true");
+ await expect(page).toHaveURL(/[?&]block=c01/);
+ await expect(page.locator("[data-ws-inspector]")).toHaveAttribute("data-ws-inspector", "clip");
+ const bench = page.locator('[data-bench-layout="inspector"][data-bench="c01"]');
+ await expect(bench).toBeVisible({ timeout: 20_000 });
+ // The window row and the word strip (the cue rail), and no verdict bar.
+ await expect(bench.locator("[data-save-window]")).toBeVisible();
+ await expect.poll(() => bench.locator("[data-cue]").count(), { timeout: 15_000 }).toBeGreaterThan(0);
+ await page.screenshot({ path: path.join(process.env.WS_SHOTS ?? path.join(DIR, ".."), "ws-clip.png") }).catch(() => {});
+
+ // Nudge the end on (the bench's own `.`, its focus inside it), save the window.
+ await bench.evaluate((el) => (el as HTMLElement).focus());
+ await page.keyboard.press(".");
+ await expect(bench.locator("[data-save-window]")).toBeEnabled();
+ await expect(page.locator("[data-workspace]")).toHaveAttribute("data-ws-token", /./);
+ const tokenBefore = await page.locator("[data-workspace]").getAttribute("data-ws-token");
+ await bench.locator("[data-save-window]").click();
+ await expect.poll(() => manifest().timeline.find((e) => e.id === "c01")?.end, { timeout: 15_000 }).not.toBe(3.0);
+ const nudged = manifestText();
+ // The workspace has read the draft's new token (the save announced itself) before Undo is pressed: an Undo on a
+ // stale token is refused, never retried.
+ await expect(page.locator("[data-workspace]")).not.toHaveAttribute("data-ws-token", tokenBefore ?? "");
+ expect(takeText()).toBe(take);
+
+ // One Undo restores the draft byte for byte; Redo puts the edit back; Undo again.
+ await page.locator("[data-ws-undo]").click();
+ await expect.poll(manifestText, { timeout: 15_000 }).toBe(original);
+ await expect(page.locator("[data-ws-undo-said]")).toContainText("Undone");
+ await expect(page.locator("[data-ws-redo]")).toBeEnabled();
+ await page.locator("[data-ws-redo]").click();
+ await expect.poll(manifestText, { timeout: 15_000 }).toBe(nudged);
+ await page.locator("body").press("Control+z");
+ await expect.poll(manifestText, { timeout: 15_000 }).toBe(original);
+ expect(takeText()).toBe(take);
+});
+
+test("a post block: the L6 post item panel and the post bench in the inspector", async ({ page }) => {
+ await page.goto(urls.workspaceHref(P, { block: "p-5" }));
+ await expect(page.locator('[data-ws-block="p-5"]')).toHaveAttribute("aria-selected", "true");
+ await expect(page.locator("[data-ws-inspector]")).toHaveAttribute("data-ws-inspector", "post");
+ // The address's block is where the viewer is, too.
+ await expect(viewer(page)).toHaveAttribute("data-play-item", "p-5", { timeout: 20_000 });
+ await expect(page.locator('[data-ws-inspector] [data-inspector="post-item"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator('[data-ws-inspector] [data-post-bench-shape="inspector"]')).toBeVisible({ timeout: 20_000 });
+ await page.screenshot({ path: path.join(process.env.WS_SHOTS ?? path.join(DIR, ".."), "ws-post.png") }).catch(() => {});
+ // ← → walk the blocks; Esc lets go of the block (the project's panels).
+ await page.locator("body").press("ArrowRight");
+ await expect(page.locator('[data-ws-block="k01"]')).toHaveAttribute("aria-selected", "true");
+ await page.locator("body").press("Escape");
+ await expect(page.locator("[data-ws-inspector]")).toHaveAttribute("data-ws-inspector", "project");
+});
+
+test("two blocks reordered by keys: one move in the draft, the take untouched", async ({ page }) => {
+ const take = takeText();
+ await page.goto(urls.workspaceHref(P));
+ await expect(page.locator('[data-ws-block="c02"]')).toHaveAttribute("data-ws-block-at", "1");
+ await page.locator('[data-ws-block="c02"]').click();
+ await page.keyboard.press("Alt+ArrowRight");
+ await expect(page.locator("[data-ws-undo-said]")).toContainText("Moved c02");
+ await expect.poll(order, { timeout: 15_000 }).toBe("c01 p-5 c02 k01 c03 c04");
+ await expect.poll(() => blockIds(page)).toEqual(["c01", "p-5", "c02", "k01", "c03", "c04"]);
+ await expect(page.locator('[data-ws-block="c02"]')).toHaveAttribute("aria-selected", "true");
+ expect(takeText()).toBe(take);
+});
+
+test("Save version: the versions menu lists it; E opens the bench in place and Back returns", async ({ page }) => {
+ await page.goto(urls.workspaceHref(P));
+ await page.locator("[data-ws-versions] > summary").click();
+ await expect(page.locator('[data-ws-version="v1"]')).toHaveCount(0);
+ await page.locator("[data-ws-versions] [data-save-version]").click();
+ await expect(page.locator("[data-ws-versions] [data-save-version-said]")).toContainText("saved as v1");
+ await expect(page.locator('[data-ws-version="v1"]')).toBeVisible({ timeout: 15_000 });
+ await expect(page.locator('[data-ws-version-open="v1"]')).toHaveAttribute("href", urls.openInDraftHref(P, "v1"));
+ await expect(page.locator("[data-ws-draft]")).toHaveAttribute("data-ws-draft", "v1");
+ await page.keyboard.press("Escape");
+
+ // E: the clip on the full bench, in place; the workspace stays mounted under it.
+ await page.locator('[data-ws-block="c01"]').click();
+ await page.locator("body").press("e");
+ await expect(page.locator('[data-cut-app-bench="c01"] [data-bench-shell="clip"]')).toBeVisible({ timeout: 20_000 });
+ await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "hidden");
+ await page.locator("[data-back-to-play]").click();
+ await expect(page.locator("[data-cut-app-play]")).toHaveAttribute("data-cut-app-play", "shown");
+ await expect(page).toHaveURL(new RegExp(`/projects/${P}(\\?|$)`));
+});
+
+test("the piece page's tabs stay at ?tab=; the Overview is written out", async ({ page }) => {
+ await page.goto(urls.projectHref(P, { tab: "overview" }));
+ await expect(page.locator("[data-workspace]")).toHaveCount(0);
+ await expect(page.locator("[data-piece-tabs]")).toHaveAttribute("data-piece-tabs", "overview");
+ // ...and the piece page's ⋯ More goes back to it.
+ await page.getByRole("button", { name: "More" }).click();
+ await expect(page.locator("[data-primary-workspace]")).toHaveAttribute("href", urls.workspaceHref(P));
+});
+
+test("under ~900 px the inspector is a sheet at the bottom, folded and unfolded by its head", async ({ page }) => {
+ await page.setViewportSize({ width: 820, height: 900 });
+ await page.goto(urls.workspaceHref(P, { block: "c02" }));
+ const sheet = page.locator("aside[data-ws-inspector]");
+ await expect(sheet).toHaveAttribute("data-ws-sheet", "open");
+ expect(await sheet.evaluate((el) => getComputedStyle(el).position)).toBe("fixed");
+ await expect(page.locator("[data-ws-sheet-toggle]")).toContainText("c02");
+ await page.screenshot({ path: path.join(process.env.WS_SHOTS ?? path.join(DIR, ".."), "ws-sheet.png") }).catch(() => {});
+ await page.locator("[data-ws-sheet-toggle]").click();
+ await expect(sheet).toHaveAttribute("data-ws-sheet", "closed");
+ const fit = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
+ expect(fit).toBeLessThanOrEqual(0);
+});
+
+test("a write since the undo ends the redo: Redo is refused and the write is kept", async ({ page, request }) => {
+ await page.goto(urls.workspaceHref(P));
+ await expect(page.locator('[data-ws-block="c04"]')).toHaveAttribute("data-ws-block-at", /\d/);
+ const before = order();
+ await page.locator('[data-ws-block="c04"]').click();
+ await page.keyboard.press("Alt+ArrowLeft");
+ await expect(page.locator("[data-ws-undo-said]")).toContainText("Moved c04");
+ await expect.poll(order).not.toBe(before);
+ await page.locator("[data-ws-undo]").click();
+ await expect.poll(order, { timeout: 15_000 }).toBe(before);
+ await expect(page.locator("[data-ws-redo]")).toBeEnabled();
+ // Another writer (an agent, the terminal) titles a clip -- a write that takes no undo point.
+ const r = await request.put("/api/report/window", { data: { project: P, clip: "c01", title: "Titled since the undo" } });
+ expect(r.ok(), await r.text()).toBe(true);
+ const titled = manifestText();
+ await page.locator("[data-ws-redo]").click();
+ // Refused: on the page's token (the draft moved since it was read), never retried on a fresh one...
+ await expect(page.locator("[data-ws-undo-said]")).toHaveAttribute("data-ws-undo-said", "error");
+ await expect(page.locator("[data-ws-undo-said]")).toContainText("changed since");
+ expect(manifestText()).toBe(titled);
+ // ...and by the redo itself, asked with no token at all (the CLI's way): the draft is not as the undo left it.
+ const again = await request.post("/api/report/timeline", { data: { project: P, op: "redo" } });
+ expect(again.ok()).toBe(false);
+ expect(await again.text()).toContain("the draft changed since the undo");
+ expect(manifestText()).toBe(titled);
+ expect(order()).toBe(before);
+ await expect(page.locator("[data-ws-redo]")).toBeDisabled();
+});
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -395,6 +395,7 @@ function timeline() {
opt("--lines-json", { type: "json", atFile: true, help: "the lines as JSON, each a string or {text, break?, hold?} (@file: from a terminal)" }),
]),
tl("undo", "draft", "the newest automatic snapshot back", [takeOpt({ help: "a take's own undo" })]),
+ tl("redo", "draft", "what the newest undo took back, put back (no edit since it)", []),
tl("sections", "project", "the deck's sections and their clips", []),
tl("section-move", "draft", "clips to the end (or start) of section N", [ids(), num("--to-section", { required: true }), bool("--start")]),
tl("section-add", "draft", "a new section after a clip", [opt("--after", { required: true }), opt("--label"), opt("--color"), pick("--level", ["1", "2"])]),
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¬e=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/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -20,6 +20,7 @@
// 4. GUARD ON THE FILE'S OWN MTIME. A PUT carrying a stale token is a 409, not
// a silent overwrite -- somebody may have run `resolve-windows --write` in
// between, and losing that is losing human judgement.
+import { createHash } from "node:crypto";
import { statSync } from "node:fs";
import { copyFile, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
@@ -2153,16 +2154,28 @@ export async function autoSnapshot(dir, op, { now = Date.now(), every = undoEver
/**
* Keep the newest `keep` undo points (`auto-before-*` snapshots in
* revisions/), removing the older ones and their draft-pointer sidecars
- * (versions.mjs openVersion). Named snapshots, `undo-saved` and `undone-*`
- * are never touched. Returns the names removed.
+ * (versions.mjs openVersion) -- and, by the same rule, the newest `keep` of
+ * `undo-saved` (with its `.redo.json` pairing and `.draft.json`) and of
+ * `redone-*`. Named snapshots and `undone-*` are never touched. Returns the
+ * names removed.
*/
export async function pruneAutoSnapshots(dir, keep = AUTO_SNAPSHOT_KEEP) {
- const auto = (await listSnapshots(dir)).filter((x) => !x.legacy && x.label?.startsWith(AUTO_SNAPSHOT_PREFIX));
+ const all = (await listSnapshots(dir)).filter((x) => !x.legacy);
+ // Each kind the undo stack makes keeps its newest `keep`: the undo points, what an undo replaced (`undo-saved`,
+ // its redo pairing and draft pointer beside it), and what a redo used up (`redone-*`).
+ const kinds = [
+ (x) => x.label?.startsWith(AUTO_SNAPSHOT_PREFIX),
+ (x) => x.label === "undo-saved",
+ (x) => x.label?.startsWith("redone-"),
+ ];
const gone = [];
- for (const x of auto.slice(Math.max(0, keep))) {
- await rm(path.join(dir, x.rel), { force: true });
- await rm(path.join(dir, x.rel.replace(/\.manifest\.json$/, ".draft.json")), { force: true });
- gone.push(x.name);
+ for (const kind of kinds) {
+ for (const x of all.filter(kind).slice(Math.max(0, keep))) {
+ await rm(path.join(dir, x.rel), { force: true });
+ await rm(path.join(dir, x.rel.replace(/\.manifest\.json$/, ".draft.json")), { force: true });
+ await rm(path.join(dir, x.rel.replace(/\.manifest\.json$/, ".redo.json")), { force: true });
+ gone.push(x.name);
+ }
}
return gone;
}
@@ -4889,6 +4902,11 @@ export async function undoStructural(dir, { token = null } = {}) {
let draft = undefined;
if (side !== undefined) {
const draftFile = path.join(dir, "takes", "draft.json");
+ // The pointer as it is now rides with `undo-saved`, so a Redo puts it back with the manifest (redoStructural).
+ if (saved) {
+ const now = await readFile(draftFile, "utf8").then((t) => JSON.parse(t), () => null);
+ await writeFile(path.join(dir, saved.replace(/\.manifest\.json$/, ".draft.json")), JSON.stringify(now, null, 2) + "\n", "utf8").catch(() => {});
+ }
if (side && typeof side === "object" && typeof side.from === "string" && side.from) {
const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
await writeFile(tmpD, JSON.stringify(side, null, 2) + "\n", "utf8");
@@ -4900,11 +4918,102 @@ export async function undoStructural(dir, { token = null } = {}) {
}
await rename(sidecar, path.join(dir, undone.replace(/\.manifest\.json$/, ".draft.json"))).catch(() => {});
}
+ // What a Redo pairs (redoStructural), beside the state this undo replaced: the undo point it took back, and the
+ // draft as this undo LEFT it (the manifest's bytes and the draft pointer's). A redo refuses unless both are
+ // still exactly that -- any writer since (a title, a throttled terminal edit, a saved version) ends it.
+ if (saved) await writeFile(path.join(dir, saved.replace(/\.manifest\.json$/, ".redo.json")), JSON.stringify({ undone, op, after: await draftStateHash(dir) }) + "\n", "utf8").catch(() => {});
return { restored: target.rel, op, saved, token: await manifestToken(dir), ...(draft !== undefined ? { draft } : {}) };
});
}
/**
+ * The draft's state, as one hash: the manifest's bytes and the draft pointer's (`takes/draft.json`, absent or not).
+ * What an undo records and a redo checks (redoStructural).
+ *
+ * @param {string} dir
+ */
+export async function draftStateHash(dir) {
+ const h = createHash("sha256");
+ h.update(await readFile(manifestFile(dir), "utf8"));
+ h.update("\0");
+ h.update(await readFile(path.join(dir, "takes", "draft.json"), "utf8").catch(() => "\u0001absent"));
+ return h.digest("hex");
+}
+
+/**
+ * Put back what the newest Undo took back (umtool redesign L7a: the workspace's Redo; `umtool timeline <p> redo`).
+ *
+ * An undo keeps the manifest it replaced as `undo-saved` and renames the undo point it restored `undone-<op>`
+ * (undoStructural), and beside it (`<undo-saved>.redo.json`) the undo point and a hash of the draft as the undo
+ * left it (draftStateHash: the manifest's bytes and takes/draft.json). A redo takes the newest undo not yet redone
+ * and refuses unless the draft is still exactly that -- ANY write since, whether or not it took an undo point
+ * (a title, a terminal edit under the throttle, a saved version, another process), ends the redo, as in every
+ * editor. It restores that `undo-saved` byte for byte, renames it `redone-<op>` (never used again), and
+ * renames the `undone-<op>` that undo took back (named beside it, `<undo-saved>.redo.json`) back to
+ * `auto-before-<op>`, so the next Undo takes the redone edit back again.
+ * Several undos redo in turn, newest first. The draft pointer an undo carried (`.draft.json`) comes back with it.
+ *
+ * @param {string} dir
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function redoStructural(dir, { token = null } = {}) {
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const all = (await listSnapshots(dir)).filter((s) => !s.legacy);
+ const pairOf = (s) => readFile(path.join(dir, s.rel.replace(/\.manifest\.json$/, ".redo.json")), "utf8").then((t) => JSON.parse(t), () => null);
+ // The newest undo not yet redone (a redone one's pairing is removed).
+ let head = null;
+ let pair = null;
+ for (const s of all) {
+ if (s.label !== "undo-saved") continue;
+ const p = await pairOf(s);
+ if (p) {
+ head = s;
+ pair = p;
+ break;
+ }
+ }
+ const undone = pair && typeof pair.undone === "string" ? all.find((s) => s.rel === pair.undone && s.label?.startsWith("undone-")) : null;
+ if (!head || !undone) throw new Error("nothing to redo: no undo since the last edit");
+ // The draft exactly as that undo left it, or no redo: whatever wrote it since -- a write that took no undo point
+ // (a title, a terminal edit under the throttle, a saved version), the CLI, another process -- would be lost.
+ if (typeof pair.after !== "string" || pair.after !== (await draftStateHash(dir))) throw new Error("the draft changed since the undo — nothing to redo");
+ const op = undone.label.slice("undone-".length);
+ const text = await readFile(path.join(dir, head.rel), "utf8");
+ JSON.parse(text);
+ const file = manifestFile(dir);
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, text, "utf8");
+ await rename(tmp, file);
+ const side = (rel) => path.join(dir, rel.replace(/\.manifest\.json$/, ".draft.json"));
+ const back = undone.rel.replace(`-${undone.label}.manifest.json`, `-${AUTO_SNAPSHOT_PREFIX}${op}.manifest.json`);
+ await rename(path.join(dir, undone.rel), path.join(dir, back)).catch(() => {});
+ await rename(side(undone.rel), side(back)).catch(() => {});
+ const done = head.rel.replace(/-undo-saved\.manifest\.json$/, `-redone-${op}.manifest.json`);
+ await rename(path.join(dir, head.rel), path.join(dir, done)).catch(() => {});
+ await rm(path.join(dir, head.rel.replace(/\.manifest\.json$/, ".redo.json")), { force: true });
+ // The draft pointer as it was before the undo (undoStructural kept it beside `undo-saved`).
+ const pointer = await readFile(side(head.rel), "utf8").then((t) => JSON.parse(t), () => undefined);
+ let draft = undefined;
+ if (pointer !== undefined) {
+ const draftFile = path.join(dir, "takes", "draft.json");
+ if (pointer && typeof pointer === "object" && typeof pointer.from === "string" && pointer.from) {
+ const tmpD = `${draftFile}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmpD, JSON.stringify(pointer, null, 2) + "\n", "utf8");
+ await rename(tmpD, draftFile);
+ draft = pointer;
+ } else {
+ await rm(draftFile, { force: true });
+ draft = null;
+ }
+ await rm(side(head.rel), { force: true });
+ }
+ return { restored: head.rel, op, token: await manifestToken(dir), ...(draft !== undefined ? { draft } : {}) };
+ });
+}
+
+/**
* THE ONE DOOR FOR A WRITER OUTSIDE THIS FILE (umtool redesign L6: inspectorEdits.mjs -- the
* provenance, the title, a teaser inserted, the published embed ids): `structural`'s write as it is --
* the token, the read inside the lock, `mutate` (which throws to refuse), the build's checks, the
diff --git a/umtool/lib/report/postBenchData.ts b/umtool/lib/report/postBenchData.ts
@@ -0,0 +1,83 @@
+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 combos counted per state of a draft (`<dir>\0<token>`), the newest few kept. */
+const combosByDraft = new Map<string, Promise<{ combos: unknown; groups: unknown }>>();
+const COMBOS_KEPT = 8;
+
+/** 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 -- once per state of the draft
+ // (its token): counting hashes every attachment, and the workspace asks again on each post block's click.
+ const token = await manifestToken(dir);
+ const key = `${dir}\0${token ?? ""}`;
+ let counting = combosByDraft.get(key);
+ if (!counting) {
+ counting = projectCombos(dir, m, { channelsDir: channelsDirFor(dir, m) }).catch(() => ({ combos: {}, groups: [] }));
+ combosByDraft.set(key, counting);
+ while (combosByDraft.size > COMBOS_KEPT) combosByDraft.delete(combosByDraft.keys().next().value as string);
+ }
+ const counted = (await counting) as { combos: unknown; groups: unknown };
+ 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 as never, render);
+ return {
+ entry,
+ token,
+ 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),
+ };
+}
diff --git a/umtool/lib/report/structure.test.mjs b/umtool/lib/report/structure.test.mjs
@@ -21,6 +21,9 @@ import {
moveEntry,
removeEntry,
removePost,
+ redoStructural,
+ updateClip,
+ setUndoEveryMs,
undoStructural,
updateFactcheck,
updateTeaser,
@@ -222,6 +225,134 @@ test("undoStructural restores the newest automatic snapshot, keeps the current s
}
});
+test("redoStructural puts back what each undo took back, newest first, and an edit since ends it", async () => {
+ const dir = await project();
+ setUndoEveryMs(0);
+ const pause = () => new Promise((r) => setTimeout(r, 25));
+ try {
+ const original = await readRaw(dir);
+ await assert.rejects(redoStructural(dir), /nothing to redo/);
+ await moveEntry(dir, "c03", 1);
+ const afterMove = await readRaw(dir);
+ await pause();
+ await removeEntry(dir, "c01");
+ const afterRemove = await readRaw(dir);
+ await pause();
+ await assert.rejects(redoStructural(dir), /nothing to redo/, "no undo yet");
+ await undoStructural(dir);
+ await pause();
+ await undoStructural(dir);
+ assert.equal(await readRaw(dir), original);
+ await pause();
+ const r1 = await redoStructural(dir);
+ assert.equal(r1.op, "move");
+ assert.equal(await readRaw(dir), afterMove, "the move, byte for byte");
+ await pause();
+ const r2 = await redoStructural(dir);
+ assert.equal(r2.op, "remove");
+ assert.equal(await readRaw(dir), afterRemove, "the remove, byte for byte");
+ await assert.rejects(redoStructural(dir), /nothing to redo/, "both redone");
+ // The redone edits undo again, in order.
+ await pause();
+ await undoStructural(dir);
+ assert.equal(await readRaw(dir), afterMove);
+ // A stale token is refused; an edit since the undo ends the redo.
+ await assert.rejects(redoStructural(dir, { token: "nope" }), StaleToken);
+ await pause();
+ await moveEntry(dir, "c02", 1);
+ await assert.rejects(redoStructural(dir), /nothing to redo/);
+ } finally {
+ setUndoEveryMs(null);
+ await rm(dir, { recursive: true });
+ }
+});
+
+test("redo refuses after ANY write since the undo -- one that took no undo point included -- and keeps it", async () => {
+ const pause = () => new Promise((r) => setTimeout(r, 25));
+ // (a) every edit its own undo point: move, undo, a title (no undo point), redo -> refused, the title kept.
+ {
+ const dir = await project();
+ setUndoEveryMs(0);
+ try {
+ await moveEntry(dir, "c03", 1);
+ await pause();
+ await undoStructural(dir);
+ await pause();
+ await updateClip(dir, "c02", { title: "A new title" });
+ const titled = await readRaw(dir);
+ await assert.rejects(redoStructural(dir), /the draft changed since the undo — nothing to redo/);
+ assert.equal(await readRaw(dir), titled, "the title is kept");
+ assert.equal((await read(dir)).timeline.find((e) => e.id === "c02").title, "A new title");
+ } finally {
+ setUndoEveryMs(null);
+ await rm(dir, { recursive: true });
+ }
+ }
+ // (b) the terminal's throttle: move, remove, undo, then a move within two minutes (no undo point) -> refused.
+ {
+ const dir = await project();
+ setUndoEveryMs(null);
+ try {
+ await moveEntry(dir, "c03", 1);
+ await pause();
+ await removeEntry(dir, "c01");
+ await pause();
+ await undoStructural(dir);
+ await pause();
+ const n = (await revisions(dir)).length;
+ await moveEntry(dir, "c02", 1);
+ assert.equal((await revisions(dir)).length, n, "the throttle took no undo point");
+ const moved = await readRaw(dir);
+ await assert.rejects(redoStructural(dir), /nothing to redo/);
+ assert.equal(await readRaw(dir), moved, "the move is kept");
+ } finally {
+ await rm(dir, { recursive: true });
+ }
+ }
+ // An older undo never becomes the head once a newer one is redone and the draft moved since.
+ {
+ const dir = await project();
+ setUndoEveryMs(0);
+ try {
+ await moveEntry(dir, "c03", 1);
+ await pause();
+ await removeEntry(dir, "c01");
+ await pause();
+ await undoStructural(dir);
+ await pause();
+ await undoStructural(dir);
+ await pause();
+ await redoStructural(dir); // the move again; the remove's undo is the head now
+ await pause();
+ await updateClip(dir, "c02", { title: "Since" });
+ const since = await readRaw(dir);
+ await assert.rejects(redoStructural(dir), /the draft changed since the undo/);
+ assert.equal(await readRaw(dir), since);
+ } finally {
+ setUndoEveryMs(null);
+ await rm(dir, { recursive: true });
+ }
+ }
+ // Nothing changed since the undo: the redo still works, byte for byte.
+ {
+ const dir = await project();
+ setUndoEveryMs(0);
+ try {
+ await updateClip(dir, "c02", { start: 31 });
+ const trimmed = await readRaw(dir);
+ await pause();
+ await undoStructural(dir);
+ await pause();
+ const r = await redoStructural(dir);
+ assert.equal(r.op, "trim");
+ assert.equal(await readRaw(dir), trimmed);
+ } finally {
+ setUndoEveryMs(null);
+ await rm(dir, { recursive: true });
+ }
+ }
+});
+
test("a manifest that already has a build problem can still be re-ordered", async () => {
const m = base();
m.posts[0].attachTo = "gone"; // already broken before the edit
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -89,6 +89,7 @@ import {
removeGroup,
setGroup,
undoStructural,
+ redoStructural,
updateClip,
updateTeaser,
updateVideoEntry,
@@ -145,6 +146,7 @@ export const TIMELINE_USAGE = [
" --line \"<text>\" [--break \"<its end>\"] [--hold S] [--line …] | --lines-json <json|@file>",
" a TEASER OR CLOSING CARD inserted (default at the end, id close; at the start, cold)",
" umtool timeline <project> undo restore the newest automatic snapshot",
+ " umtool timeline <project> redo put back what the newest undo took back (no edit since it)",
" umtool timeline <project> sections [--json] the deck's sections: §, label, colour, its marker, its clips",
" umtool timeline <project> section-move <id> [<id>…] --to-section N [--start]",
" clips to the end (--start: the start) of section N, every marker following",
@@ -198,7 +200,7 @@ export const TIMELINE_USAGE = [
].join("\n");
const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"];
-const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "removed", "restore", "import-item", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"];
+const VERBS = ["ls", "insert", "add-video", "set-video", "move", "place", "remove", "reject", "wrong-speaker", "removed", "restore", "import-item", "duplicate", "post", "post-remove", "teaser", "undo", "redo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups", "threads"];
const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"];
const VALUED = new Set(["--as", "--group", "--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim", "--conversation", "--from", "--fit", "--bass", "--gain", "--enter", "--hold"]);
/** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */
@@ -782,6 +784,10 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
({ result, editNotes } = await write((token) => undoStructural(project.dir, { token })));
break;
}
+ case "redo": {
+ ({ result, editNotes } = await write((token) => redoStructural(project.dir, { token })));
+ break;
+ }
case "section-move": {
if (!rest.length) throw new CliError("section-move needs one or more clip ids");
const section = intFlag(flags, "--to-section");