"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, isWorkspaceMode, openInDraftHref, playHref, postBenchHref, workspaceHref, type WorkspaceMode } from "@/lib/hrefs";
import { runningTime, sourceAt, 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 type { BlockActions, BlockInfo } from "./BlockMenu";
import WorkspaceInspector from "./WorkspaceInspector";
import WorkspaceTop, { type UndoState } from "./WorkspaceTop";
import GeneratedBanner from "@/components/notes/GeneratedBanner";
import PresentView, { type PresentPayload } from "../present/PresentView";
import ReviewPass, { useReviewPass } from "./ReviewPass";
import ReadinessBar, { type Readiness } from "./ReadinessBar";
import { READ_ONLY_SAID, WorkspaceReadOnly, useWorkspaceReadOnly, workspaceReadOnly } from "./readOnly";
// ---------------------------------------------------------------------------
// THE WORKSPACE (umtool redesign L7a): a report video's ONE screen, at its own
// address (`/projects/
`). 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
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 MODES (L7b), in the address (`?mode=`; Edit is the bare one), each a history entry:
// Edit the above
// Review pass the inspector's column is the pass (ReviewPass.tsx): the viewer plays the block under review and
// stops at its end; Keep · Fix · Note (k f n) answer it and move on. A version (`?take=`) is
// reviewed read-only, its verdict at the end
// Present the viewer full screen as slides (present/PresentView.tsx, Present's own deck: arrows, the
// censor toggles), Esc back to Edit; a 9:16 cut presents tall
//
// 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 · Shift+F10 (or a
// right-click, or its ⋯) a block's menu (BlockMenu, lane L8b).
// ---------------------------------------------------------------------------
/** 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: "Shift+F10", what: "the focused block's menu (or right-click it, or its ⋯): its verbs, each a form filled in from it" },
{ keys: "?", what: "these keys" },
{ keys: "k f n", what: "review pass: keep, fix (say what), a note on the block" },
{ keys: "Esc", what: "present: back to Edit" },
];
type Timeline = { token: string | null; ids: string[] };
export default function Workspace({
view: served,
initialBlock = null,
initialAt = null,
initialMode = "edit",
presentInitial = null,
readiness = null,
introWritten = null,
hasLedger = false,
generatedBy = null,
}: {
view: PlayViewData;
initialBlock?: string | null;
/** `?at=`: seconds into the selected block (the bench's Back to the cut). */
initialAt?: number | null;
initialMode?: "edit" | WorkspaceMode;
/** Present mode's slides, when the page opened on it (else read when it is entered). */
presentInitial?: PresentPayload | null;
/** The readiness bar's pills as the page read them (ReadinessBar reads them again after a write). */
readiness?: Readiness | 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;
// A saved version reviewed or presented (`?take=`): read-only, its own view; Edit is the draft's page.
const take = view.take ? { id: view.take.id, label: view.take.label } : null;
const takeId = take?.id ?? null;
// THE read-only flag (readOnly.ts): derived here once, handed down; every draft writer below refuses on it.
const readOnly = workspaceReadOnly(view);
const readOnlyRef = useRef(readOnly);
readOnlyRef.current = readOnly;
const reloadSeq = useRef(0);
const reloadView = useCallback(async () => {
const mine = ++reloadSeq.current;
try {
const r = await fetch(`/api/report/play-view?${new URLSearchParams({ project, ...(takeId ? { take: takeId } : {}) }).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, takeId]);
// ---- the mode (L7b): Edit, Review pass, Present -- in the address, a history entry each ----------------------
const [mode, setModeState] = useState<"edit" | WorkspaceMode>(initialMode);
const modeRef = useRef(mode);
modeRef.current = mode;
const setMode = useCallback(
(next: "edit" | WorkspaceMode) => {
if (next === modeRef.current) return;
// Edit of a version is the draft's: its own page.
if (next === "edit" && takeId) {
router.push(workspaceHref(project));
return;
}
const u = new URL(window.location.href);
if (next === "edit") u.searchParams.delete("mode");
else u.searchParams.set("mode", next);
if (next !== "present") u.hash = "";
window.history.pushState(window.history.state, "", `${u.pathname}${u.search}${u.hash}`);
setModeState(next);
},
[router, project, takeId],
);
useEffect(() => {
const onPop = () => {
const m = new URL(window.location.href).searchParams.get("mode");
setModeState(isWorkspaceMode(m) ? m : "edit");
};
window.addEventListener("popstate", onPop);
return () => window.removeEventListener("popstate", onPop);
}, []);
// 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({ token: null, ids: [] });
const [tlIds, setTlIds] = useState([]);
const [tlToken, setTlToken] = useState(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({ 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 = {}) => {
// A version on screen: the draft is not what is shown, so nothing writes it (a move, an Undo, a Redo).
if (readOnlyRef.current) {
setUndo((u) => ({ ...u, busy: false, said: READ_ONLY_SAID, error: true }));
return null;
}
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, a ⌘K run): the draft read again,
// and a Redo is gone -- but only when the draft DID change (its token moved): a run that only read it (⌘K
// `show`, `check`) keeps the Redo and its word. The workspace's own writes (above) do not announce: they read
// the draft again themselves, and remount the inspector (`epoch`).
useEffect(() => {
let t: ReturnType | null = null;
let held: string | null = null;
const on = (e: Event) => {
if ((e as CustomEvent).detail?.project !== project) return;
if (t) clearTimeout(t);
else held = tl.current.token;
// The token first (the next Undo is asked on it), then the view.
t = setTimeout(() => {
t = null;
void loadTimeline().then((now) => {
if (now.token !== held) setUndo((u) => ({ ...u, canRedo: false, said: null }));
return 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(() => {
const fresh = !!tlToken && view.token === tlToken;
const count = new Map();
for (const id of tlIds) count.set(id, (count.get(id) ?? 0) + 1);
return view.entries.map((e) => {
const p = itemOf.get(e.id);
// ITS OWN place in the timeline (lane L8b): the one the view says (playView `timelineAt`), else the only entry
// with its id. A twin the view does not place is never guessed at: no index, and nothing moves or removes it.
// The view's word counts only when it was read at the token the timeline is held at now -- between an
// announce's two reads an old view's index checked against the new ids could land on the other twin.
const own = fresh && typeof e.timelineAt === "number" && tlIds[e.timelineAt] === e.id ? e.timelineAt : null;
const n = count.get(e.id) ?? 0;
// A version's (a take's) blocks are never moved (readOnly.ts: its timeline is not the draft's).
const at = e.type === "intro" || readOnly ? null : (own ?? (n === 1 ? tlIds.indexOf(e.id) : null));
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,
twin: e.type !== "intro" && !readOnly && at === null && n > 1,
rejected: e.rejected?.label ?? null,
missing: e.type === "clip" && !e.media,
};
});
}, [view.entries, view.token, itemOf, tlIds, tlToken, readOnly]);
const entryOf = core.entryOf;
// ---- the selection (the inspector's block), kept in the URL (`?block=`) ----------------
const [selected, setSelected] = useState(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;
const into = initialAt != null && initialAt > 0 ? Math.min(initialAt, Math.max(0, p.it.to - p.it.from - 0.05)) : 0;
engine.seekTo(startOf(planRef.current, p.i) + into);
}, [itemOf, selected, engine, planRef, initialAt]);
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],
);
// ---- the review pass (L7b): the selection is the block under review; past the last, the verdict ------------
const rv = useReviewPass(project, view.entries, mode === "review" && !takeId, readOnly);
const [atEnd, setAtEnd] = useState(false);
const reviewReady = mode === "review" && (takeId ? true : rv.loaded);
const reviewPlaced = useRef(false);
// A reload resumes on the block in its address; entering from Edit resumes on the first with no answer.
const reviewFromAddress = useRef(initialMode === "review");
useEffect(() => {
if (mode !== "review") {
reviewPlaced.current = false;
return;
}
if (!reviewReady || reviewPlaced.current) return;
reviewPlaced.current = true;
// Where it stopped: the block in the address (a reload), else the first with no answer, else the verdict.
const ids = rv.progress.ids;
const fromAddress = reviewFromAddress.current;
reviewFromAddress.current = false;
if (fromAddress && selected && ids.includes(selected)) return;
const at = takeId ? (ids[0] ?? null) : rv.progress.next;
if (at) {
setAtEnd(false);
select(at);
} else {
setAtEnd(true);
setSelected(null);
}
}, [mode, reviewReady, rv.progress, selected, select, takeId]);
const reviewStep = useCallback(
(d: 1 | -1, play = false) => {
const ids = rv.progress.ids;
if (!ids.length) {
setAtEnd(true);
return;
}
const i = atEnd ? ids.length : selected ? ids.indexOf(selected) : -1;
const to = i + d;
if (to >= ids.length) {
setAtEnd(true);
setSelected(null);
setPlaying(false);
return;
}
setAtEnd(false);
select(ids[Math.max(0, to)]);
if (play) setPlaying(true);
},
[rv.progress.ids, atEnd, selected, select, setPlaying],
);
// The viewer plays block by block: it stops where the block under review ends.
const lastItem = useRef(null);
const playingId = core.item?.id ?? null;
useEffect(() => {
const prev = lastItem.current;
lastItem.current = playingId;
if (mode !== "review" || !ui.playing) return;
if (prev && prev === selected && playingId !== selected) setPlaying(false);
}, [playingId, mode, ui.playing, selected, setPlaying]);
// ---- present (L7b): Present's own deck over the workspace, its slides read on the way in ------------------------
const [present, setPresent] = useState<{ state: "ready"; payload: PresentPayload } | { state: "loading" } | { state: "error"; error: string } | null>(
presentInitial ? { state: "ready", payload: presentInitial } : null,
);
const presentRead = useRef(!!presentInitial);
const presentSeq = useRef(0);
useEffect(() => {
if (mode !== "present") {
presentRead.current = false;
presentSeq.current += 1;
return;
}
setPlaying(false);
// Read once per entry (the draft may have changed since the last); a reading overtaken by a newer one is dropped.
if (presentRead.current) return;
presentRead.current = true;
const mine = ++presentSeq.current;
setPresent({ state: "loading" });
void (async () => {
try {
const r = await fetch(`/api/report/present?${new URLSearchParams({ project, ...(takeId ? { take: takeId } : {}) }).toString()}`, { cache: "no-store" });
const j = (await r.json().catch(() => ({}))) as PresentPayload & { error?: string };
if (mine !== presentSeq.current) return;
setPresent(r.ok && !j.error ? { state: "ready", payload: j } : { state: "error", error: j.error ?? `HTTP ${r.status}` });
} catch (e) {
if (mine === presentSeq.current) setPresent({ state: "error", error: e instanceof Error ? e.message : String(e) });
}
})();
}, [mode, project, takeId, setPlaying]);
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],
);
// A block moves by its own index (a twin with none does not move: the Cut tab names which).
const moveBlock = useCallback(
async (b: { id: string; at: number | null } | undefined, d: 1 | -1) => {
if (!b || b.at === null || undo.busy) return;
await move(b.id, b.at, b.at + d);
},
[move, undo.busy],
);
const moveSelected = useCallback((d: 1 | -1) => moveBlock(blocks.find((x) => x.id === selected), d), [moveBlock, blocks, selected]);
// ---- edit in place (E): the clip bench over the workspace, Back returns here ----------
const editHere = useCallback((which?: string) => {
if (readOnlyRef.current) return;
const id = which ?? (selected && selected !== ADD ? selected : (core.item?.id ?? null));
const e = id ? entryOf.get(id) : null;
if (!e) return;
const p = itemOf.get(e.id);
// The bench opens where the playhead is in the clip (at its start when the playhead is not in it: a block's menu).
const t0 = now().t;
const at = p && t0 >= p.it.from && t0 < p.it.to ? Math.round(Math.max(0, t0 - 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);
const reviewStepRef = useRef(reviewStep);
reviewStepRef.current = reviewStep;
useEffect(() => {
const onKey = (ev: KeyboardEvent) => {
if (!shownRef.current) return;
// Present's deck has the keys while it is up (present/PresentView.tsx; Esc is its way back to Edit).
if (modeRef.current === "present") 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], dialog")) return;
// A modal open over the workspace (⌘K, a form a block's menu opened) has the keys, wherever the focus fell: an
// Escape taken here would be preventDefault-ed, and the dialog would not close.
if (document.querySelector("dialog:modal")) return;
const k = ev.key;
const mod = ev.metaKey || ev.ctrlKey;
// The review pass: Space and ← → walk it (k f n are ReviewPass's); nothing here edits.
if (modeRef.current === "review") {
if (mod || ev.altKey) return;
if (k === " ") setPlaying(!now().playing);
else if (k === "ArrowLeft") reviewStepRef.current(-1);
else if (k === "ArrowRight") reviewStepRef.current(1);
else if (k === "?") setHelp((h) => !h);
else return;
ev.preventDefault();
return;
}
// A version on screen: no key here writes (undo, redo, a move, E).
if (readOnlyRef.current && (mod || ev.altKey || k === "e" || k === "E")) return;
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(null);
const [stageW, setStageW] = useState(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],
);
// ---- a block's menu (BlockMenu, lane L8b): the strip's own writers, and what fills a verb's form in ----
const nowRef = useRef(now);
nowRef.current = now;
const menu = useMemo(
() => ({
entries: tlIds.length,
busy: undo.busy,
// A block by its place in the strip (two blocks may share an id: a duplicate).
info: (i: number): BlockInfo | null => {
const e = view.entries[i];
const b = blocks[i];
if (!e || !b || b.id !== e.id) return null;
const id = e.id;
const p = itemOf.get(id);
const t = nowRef.current().t;
const cutStart = typeof e.cutStart === "number" ? e.cutStart : (e.start ?? null);
const cutEnd = typeof e.cutEnd === "number" ? e.cutEnd : (e.end ?? null);
// The second under the playhead when it is in this clip, else the start of its cut.
const it = p?.it ?? null;
const src = e.type === "clip" && it?.clip && t >= it.from && t < it.to ? sourceAt(it, t) : null;
const second = e.type !== "clip" ? null : typeof src === "number" ? Math.round(src * 100) / 100 : cutStart;
return { project, id, type: e.type, at: b.at, twin: !!b.twin, start: e.start ?? null, end: e.end ?? null, cutStart, cutEnd, second, video: e.video ?? null, channel: e.sourceChannel ?? e.channel ?? null };
},
edit: (b: BlockInfo) => {
select(b.id);
editHere(b.id);
},
play: (b: BlockInfo) => {
select(b.id);
setPlaying(true);
},
move: (b: BlockInfo, d: 1 | -1) => void moveBlock(b, d),
remove: (b: BlockInfo) => {
if (b.at === null) return;
void write("remove", { id: b.id, at: b.at }).then((j) => {
if (j) setUndo({ busy: false, said: `Removed ${b.id} — Undo puts it back`, error: false, canRedo: false });
});
},
}),
[tlIds.length, undo.busy, view.entries, blocks, itemOf, project, select, editHere, setPlaying, moveBlock, write],
);
const iconBtn = cn(buttonVariants({ variant: "outline", size: "sm" }), "min-w-9 font-mono");
const t = core.t;
const item = core.item;
return (
void doUndo()}
onRedo={() => void doRedo()}
onChanged={() => void reloadView()}
help={() => setHelp(true)}
/>
{/* The readiness bar (L7b): quote-check, links, captures, render, X jar -- what the Inbox would say of this
piece, each a click to its fix. Read-only. */}
{!takeId && b.missing).map((b) => b.id)} onSelect={(id) => select(id)} />}
{generatedBy && (
)}
{/* ---- the viewer, its transport, the strip ---- */}
{runningTime(t)} / {runningTime(plan.total)}
{item && (
{ui.cur + 1}/{plan.items.length} · {item.id}
)}
{core.composeState === "composing" && composing the chrome…}
{core.composeState === "no-deck" && {view.basic ? "basic: the footage alone" : "no on-screen deck"}}
{core.composeState === "error" && (
the chrome did not compose: {core.composeError}
)}
{ui.waiting && loading…}
{
if (mode === "review") setAtEnd(false);
select(id);
}}
// A block drags only in Edit on the draft: the review pass watches the cut, it never reorders it.
canMove={mode === "edit" && !readOnly}
onMove={(id, at, to) => {
if (mode === "edit" && !readOnly) void move(id, at, to);
}}
marks={mode === "review" ? rv.answers : null}
// A block's menu only in Edit on the draft: the workspace's one read-only flag (readOnly.ts) and the mode.
menu={mode === "edit" && !readOnly ? menu : undefined}
plus={mode !== "edit" || readOnly ? null : (
)}
/>
{/* ---- the inspector (a sheet at the bottom under ~900 px) ---- */}
);
}
/** +: 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[] }) {
// Every adder writes the draft: none while a version shows (readOnly.ts; the + is hidden then, but `?block=+`
// still selects it).
const readOnly = useWorkspaceReadOnly();
if (readOnly) {
return (