Archilyzer · Source

archilyzer

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

commit d6b96911cfa90cfe5fe3069dd0e303acd8d9a894
parent 0a901946ae7efc585f8c80732148510a39c0d4d9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 10 Nov 2026 16:24:21 -0500

Merge main (L8b block menus) into lane/review-present: a block's menu only in Edit on the draft (the workspace's one read-only flag and the mode); a version's blocks carry no timeline index (nothing drags, Alt-moves or menus them); the end verdict that saved a version announces it (the draft's line read again, its token unmoved so Redo and the Undo token stand); the click-through e2e covers Alt+→, a drag and the menu on a version

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Diffstat:
Mumtool/app/api/cli/route.ts | 15++++++++++-----
Mumtool/components/projects/review/PlayCut.tsx | 2++
Aumtool/components/projects/workspace/BlockMenu.tsx | 317+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/workspace/BlockStrip.tsx | 97++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/components/projects/workspace/ReviewPass.tsx | 3+++
Mumtool/components/projects/workspace/Workspace.tsx | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/components/shell/CommandForm.tsx | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/components/shell/JumpPalette.tsx | 81++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/docs/knobs.md | 24++++++++++++++++++++++++
Aumtool/e2e/block-menus.spec.ts | 402+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 28++++++++++++++++++++++++++++
Mumtool/e2e/review-pass.spec.ts | 6++++++
Mumtool/e2e/workspace.spec.ts | 3++-
Mumtool/lib/cli/verbs.mjs | 147++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mumtool/lib/cli/verbs.test.mjs | 74+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/playView.mjs | 6++++++
16 files changed, 1309 insertions(+), 81 deletions(-)

diff --git a/umtool/app/api/cli/route.ts b/umtool/app/api/cli/route.ts @@ -20,7 +20,9 @@ export const dynamic = "force-dynamic"; // pathname + search>, what the page is about -- { project, clip, post, take } // GET ?job=<id>[&since=N] { job }: the app job a form started (lib/jobs.ts jobView, its log from N) // GET ?qid=<qid> { step, log }: a queued form's step and its log's last lines -// POST { verb, values, confirm? } -> 202 { job, line } | 202 { queued: { qid }, line } +// POST { verb, values, confirm? } -> 202 { job, line, project } | 202 { queued: { qid }, line, project } +// (`project`: the resolved id of the project it names, or null -- the page announces a +// write to that project when the run ends done) // the row's args validated and built into argv HERE (lib/cli/argv.mjs); // a row with `queue` (it renders, or holds the heavy slot) is added to the // durable queue, any other runs as one job on the app's runner @@ -131,6 +133,8 @@ export async function POST(request: Request) { // A project arg is one the CLI will find: said here, not as the job's first line. let project: string | null = null; let projectDir: string | null = null; + // The project the run is about, for the page (the positional's, else a flag's: `cast audition --project`). + let named: string | null = null; for (const a of row.args) { const v = values[a.name]; if (a.type !== "project" || typeof v !== "string" || !v.trim()) continue; @@ -140,7 +144,7 @@ export async function POST(request: Request) { if (a.name === "project") { project = r.project.id; projectDir = r.project.dir; - } + } else named ??= r.project.id; } // A file a form names is a file of THE project, by its realpath; it runs as that absolute path // (a row whose CLI joins it to the project itself: as typed). @@ -153,6 +157,7 @@ export async function POST(request: Request) { } const built = buildArgv(row, run); if (!built.ok) return Response.json({ error: built.error, field: built.field ?? null }, { status: 400, headers }); + named = project ?? named; const take = row.args.filter((a) => a.context === "take").map((a) => values[a.name]).find((v): v is string => typeof v === "string" && !!v.trim()) ?? null; const line = cliLine(built.argv); const label = `⌘K: umtool ${built.argv.join(" ")}`.slice(0, 160); @@ -163,7 +168,7 @@ export async function POST(request: Request) { const recent = ((await listSteps(queueDir())) as Array<{ qid: string; argv: string[]; state: string; createdAt: string; by?: string }>).find( (s) => (s.state === "queued" || s.state === "running") && JSON.stringify(s.argv) === same && Date.now() - Date.parse(s.createdAt) < DEDUPE_MS, ); - if (recent) return Response.json({ ok: true, queued: { qid: recent.qid }, deduped: true, line, queue: queueRunnerStatus() }, { status: 200, headers }); + if (recent) return Response.json({ ok: true, queued: { qid: recent.qid }, deduped: true, line, project: named, queue: queueRunnerStatus() }, { status: 200, headers }); const step = (await addStep(queueDir(), { argv: built.argv, label, @@ -173,7 +178,7 @@ export async function POST(request: Request) { ...(row.timeoutMin ? { timeoutMin: row.timeoutMin } : {}), })) as { qid: string }; kickQueue(); - return Response.json({ ok: true, queued: { qid: step.qid }, line, queue: queueRunnerStatus() }, { status: 202, headers }); + return Response.json({ ok: true, queued: { qid: step.qid }, line, project: named, queue: queueRunnerStatus() }, { status: 202, headers }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers }); } @@ -181,5 +186,5 @@ export async function POST(request: Request) { const running = runningJob(); if (running) return Response.json({ error: `a job is already running (${running.kind}) — run this when it is done`, running: jobView(running, running.log.length) }, { status: 409, headers }); const job = startJob(`umtool ${verb}`, [{ cwd: UMTOOL_DIR, env: {}, label: `umtool ${built.argv.join(" ")}`.slice(0, 200), argv: [process.execPath, umtoolCli(), ...built.argv], timeoutMs: (row.timeoutMin ?? 15) * 60_000 }], { project }); - return Response.json({ ok: true, job: jobView(job), line }, { status: 202, headers }); + return Response.json({ ok: true, job: jobView(job), line, project: named }, { status: 202, headers }); } diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -137,6 +137,8 @@ export type PlayEntry = { postScene?: { key: string; n: number; of: number; ids: string[]; anchor: string }; /** A VIDEO entry (video-entry.mjs, lib/report/playView.mjs videoPlayEntry): a file of the project, full frame. */ videoEntry?: VideoEntryPlay; + /** Its index in the played manifest's own timeline (null: not one of its entries as written -- the intro, a turned variant). */ + timelineAt?: number | null; }; export type PlayViewData = { diff --git a/umtool/components/projects/workspace/BlockMenu.tsx b/umtool/components/projects/workspace/BlockMenu.tsx @@ -0,0 +1,317 @@ +"use client"; + +import Link from "next/link"; +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { blockVerbs, commandOf, fromBlockValues } from "@/lib/cli/verbs.mjs"; +import { clipBenchHref, ingredientHref, postBenchHref } from "@/lib/hrefs"; +import { openCommand } from "@/components/shell/JumpPalette"; +import type { CliVerb } from "@/components/shell/CommandForm"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// A BLOCK'S MENU (umtool redesign L8b): right-click a block of the workspace's +// strip, or its ⋯, or Shift+F10 / the context-menu key on it. On top, what needs +// no form -- Edit in place (E), Play from here, Move left / right (Alt+← →), +// Remove (the top bar's Undo takes it back), the full bench, the recording's +// life cycle -- the strip's own writers. Under them, every verb of the registry +// whose row names this block's kind (lib/cli/verbs.mjs `blocks`), grouped by its +// command; choosing one opens THE form ⌘K opens (shell/CommandForm, in the +// palette), filled in from the block by the row's own `fromBlock` rules. A row +// with `nav` is a page, not a run: it is a link here. +// +// Keys: ↑ ↓ (Home, End, a letter) move, Enter or Space chooses, Esc or Tab +// closes; the focus goes back to the block. +// --------------------------------------------------------------------------- + +/** What a block tells its menu: verbs.mjs BLOCK_FIELDS (the fromBlock templates read these). */ +export type BlockInfo = { + project: string; + id: string; + type: string; + /** Its own index in the timeline (null: the intro, or a twin the view did not place). */ + at: number | null; + /** Its id is in the timeline more than once and the view did not say which it is. */ + twin?: boolean; + start?: number | null; + end?: number | null; + cutStart?: number | null; + cutEnd?: number | null; + second?: number | null; + video?: string | null; + channel?: string | null; +}; + +/** The strip's own writers, as the workspace does them. */ +export type BlockActions = { + /** The block at this place in the strip (two blocks may share an id). */ + info: (place: number) => BlockInfo | null; + /** The timeline's length (Move right stops at its end). */ + entries: number; + busy: boolean; + edit: (b: BlockInfo) => void; + play: (b: BlockInfo) => void; + /** By the block's own index (`at`), never by its id. */ + move: (b: BlockInfo, d: 1 | -1) => void; + remove: (b: BlockInfo) => void; +}; + +/** Where it opens: at the pointer, or over the block (the keyboard, the ⋯). */ +export type MenuAnchor = { x: number; y: number } | { rect: { left: number; top: number; bottom: number } }; + +type Item = + | { key: string; label: string; hint?: string; kind: "action"; disabled?: boolean; why?: string; run: () => void } + | { key: string; label: string; hint?: string; kind: "link"; href: string } + | { key: string; label: string; hint?: string; kind: "verb"; row: CliVerb }; + +type Group = { key: string; label: string; items: Item[] }; + +const KIND_WORD: Record<string, string> = { clip: "Clip", post: "Post item", teaser: "Card", card: "Chapter card", intro: "Intro", video: "Video" }; +const COMMAND_WORD: Record<string, string> = { timeline: "The cut", posts: "Post item", "trailer-beats": "Trailer" }; + +/** A nav row's page, from what the block filled in. */ +function navHref(row: CliVerb, values: Record<string, string | boolean>): string | null { + if (row.nav === "ingredient") { + const [ch, id] = String(values.recording ?? "").split("/"); + return ch && id ? ingredientHref(ch, id) : null; + } + return null; +} + +/** Why a timeline entry with no index of its own is not moved or removed here. */ +export const TWIN_WHY = "this entry has a twin — use the Cut tab"; + +function groupsOf(info: BlockInfo, actions: BlockActions): Group[] { + const entry = info.type !== "intro"; + const placed = info.at !== null; + const why = placed ? undefined : TWIN_WHY; + const direct: Item[] = []; + if (info.type === "clip" || info.type === "post") direct.push({ key: "edit", label: "Edit in place", hint: "E", kind: "action", run: () => actions.edit(info) }); + direct.push({ key: "play", label: "Play from here", kind: "action", run: () => actions.play(info) }); + if (entry) { + // Each by the block's OWN index: a twin the view did not place is never guessed at. + direct.push({ key: "move-left", label: "Move left", hint: "Alt+←", kind: "action", disabled: actions.busy || !placed || info.at === 0, why, run: () => actions.move(info, -1) }); + direct.push({ key: "move-right", label: "Move right", hint: "Alt+→", kind: "action", disabled: actions.busy || !placed || (info.at ?? 0) >= actions.entries - 1, why, run: () => actions.move(info, 1) }); + direct.push({ key: "remove", label: "Remove", hint: placed ? "Undo takes it back" : "a twin", kind: "action", disabled: actions.busy || !placed, why, run: () => actions.remove(info) }); + } + if (info.type === "clip") direct.push({ key: "bench", label: "Full bench", kind: "link", href: clipBenchHref(info.project, info.id) }); + if (info.type === "post") direct.push({ key: "bench", label: "Full bench", kind: "link", href: postBenchHref(info.project, info.id) }); + + const rows = blockVerbs(info.type) as CliVerb[]; + for (const row of rows) { + if (!row.nav) continue; + const href = navHref(row, fromBlockValues(row, info)); + if (href) direct.push({ key: `nav:${row.verb}`, label: row.nav === "ingredient" ? "Life cycle" : row.verb, hint: `umtool ${row.verb}`, kind: "link", href }); + } + + // The verbs, by command: the kind's own verbs (one each) first, then each command's sub-verbs. + const byCmd = new Map<string, CliVerb[]>(); + for (const row of rows) { + if (row.nav) continue; + const c = commandOf(row.verb); + byCmd.set(c, [...(byCmd.get(c) ?? []), row]); + } + const own: CliVerb[] = []; + const multi: Group[] = []; + for (const [c, list] of byCmd) { + if (list.length === 1 && list[0].verb === c) own.push(list[0]); + else multi.push({ key: `cmd:${c}`, label: COMMAND_WORD[c] ?? c, items: list.map((row) => ({ key: `verb:${row.verb}`, label: row.verb, hint: row.summary, kind: "verb", row })) }); + } + const verbGroups: Group[] = []; + if (own.length) verbGroups.push({ key: "own", label: KIND_WORD[info.type] ?? info.type, items: own.map((row) => ({ key: `verb:${row.verb}`, label: row.verb, hint: row.summary, kind: "verb", row })) }); + // A group of one sub-verb (trailer-beats add) joins the kind's own. + for (const g of multi) { + if (g.items.length === 1 && verbGroups[0]?.key === "own") verbGroups[0].items.push(g.items[0]); + else verbGroups.push(g); + } + return [{ key: "direct", label: `${KIND_WORD[info.type] ?? info.type} ${info.id}`, items: direct }, ...verbGroups]; +} + +export default function BlockMenu({ + place, + info, + actions, + anchor, + onClose, +}: { + /** The block's place in the strip (its ⋯ toggles the menu: a press on it is not "outside"). */ + place: number; + info: BlockInfo; + actions: BlockActions; + anchor: MenuAnchor; + /** Closed: `refocus` -- the focus goes back to the block (Esc, Tab, a choice). */ + onClose: (refocus: boolean) => void; +}) { + const groups = useMemo(() => groupsOf(info, actions), [info, actions]); + const flat = useMemo(() => groups.flatMap((g) => g.items), [groups]); + const usable = (i: number) => !(flat[i]?.kind === "action" && flat[i].disabled); + const [at, setAt] = useState(() => Math.max(0, flat.findIndex((_, i) => usable(i)))); + const box = useRef<HTMLDivElement | null>(null); + const els = useRef<Array<HTMLElement | null>>([]); + const [pos, setPos] = useState<{ left: number; top: number } | null>(null); + + // Placed inside the window: at the pointer (flipped up when there is no room below), or above the block. + useLayoutEffect(() => { + const el = box.current; + if (!el) return; + const w = el.offsetWidth; + const h = el.offsetHeight; + const W = window.innerWidth; + const H = window.innerHeight; + let left: number; + let top: number; + if ("rect" in anchor) { + left = anchor.rect.left; + top = anchor.rect.top - h - 4 >= 8 ? anchor.rect.top - h - 4 : anchor.rect.bottom + 4 + h <= H - 8 ? anchor.rect.bottom + 4 : 8; + } else { + left = anchor.x; + top = anchor.y + h <= H - 8 ? anchor.y : Math.max(8, anchor.y - h); + } + setPos({ left: Math.max(8, Math.min(left, W - w - 8)), top: Math.max(8, top) }); + }, [anchor]); + + useEffect(() => { + if (pos) els.current[at]?.focus({ preventScroll: false }); + }, [at, pos]); + + // A press outside closes it (the focus stays where that press put it); so does the window moving under it. + useEffect(() => { + const down = (e: PointerEvent) => { + const t = e.target as Element | null; + if (t?.closest?.(`[data-ws-block-more-i="${place}"]`)) return; + if (box.current && !box.current.contains(t as Node)) onClose(false); + }; + const away = () => onClose(false); + document.addEventListener("pointerdown", down, true); + window.addEventListener("resize", away); + window.addEventListener("blur", away); + return () => { + document.removeEventListener("pointerdown", down, true); + window.removeEventListener("resize", away); + window.removeEventListener("blur", away); + }; + }, [onClose, place]); + + const choose = (it: Item) => { + if (it.kind === "action") { + if (it.disabled) return; + onClose(true); + it.run(); + } else if (it.kind === "verb") { + // The focus back on the block, then the palette's dialog opened at once -- in this same event, so no key typed + // in between reaches the workspace -- and closing it returns the focus to the block. + onClose(true); + openCommand({ row: it.row, values: fromBlockValues(it.row, info) }); + } else { + onClose(false); + } + }; + + const step = (d: 1 | -1, from = at) => { + for (let n = 1; n <= flat.length; n++) { + const i = (from + d * n + flat.length * 2) % flat.length; + if (usable(i)) return i; + } + return from; + }; + + const onKey = (e: React.KeyboardEvent) => { + const k = e.key; + // The menu's keys are its own: not the workspace's (data-ws-own-keys), not the page's. + e.stopPropagation(); + if (k === "ArrowDown") setAt((i) => step(1, i)); + else if (k === "ArrowUp") setAt((i) => step(-1, i)); + else if (k === "Home") setAt(step(1, -1)); + else if (k === "End") setAt(step(-1, flat.length)); + else if (k === "Escape") onClose(true); + else if (k === "Tab") onClose(true); + else if (k === "Enter" || k === " ") { + const it = flat[at]; + if (it?.kind === "link") { + els.current[at]?.click(); + } else if (it) choose(it); + } else if (k.length === 1 && /\S/.test(k) && !e.ctrlKey && !e.metaKey && !e.altKey) { + // A letter: the next item whose label starts with it. + const c = k.toLowerCase(); + for (let n = 1; n <= flat.length; n++) { + const i = (at + n) % flat.length; + if (usable(i) && flat[i].label.toLowerCase().startsWith(c)) { + setAt(i); + break; + } + } + } else return; + e.preventDefault(); + }; + + let n = -1; + const menu = ( + <div + ref={box} + role="menu" + aria-label={`${KIND_WORD[info.type] ?? info.type} ${info.id}`} + aria-orientation="vertical" + data-ws-menu={info.id} + data-ws-menu-type={info.type} + data-ws-own-keys="" + onKeyDown={onKey} + onContextMenu={(e) => e.preventDefault()} + style={pos ? { left: pos.left, top: pos.top } : { left: -9999, top: 0 }} + className="fixed z-50 max-h-[min(600px,calc(100dvh-16px))] w-[min(380px,calc(100vw-16px))] overflow-y-auto rounded-[3px] border border-seam-2 bg-panel py-1 text-[12.5px] text-text shadow-2xl" + > + {groups.map((g, gi) => ( + <div key={g.key} role="group" aria-labelledby={`ws-menu-${g.key}`} data-ws-menu-group={g.key}> + {gi > 0 && <div role="separator" className="my-1 border-t border-seam" />} + <div id={`ws-menu-${g.key}`} className={cn("micro px-3 pb-0.5 pt-1", gi === 0 && "font-mono normal-case tracking-normal text-text-2")}> + {g.label} + </div> + {g.items.map((it) => { + n += 1; + const i = n; + const on = i === at; + const cls = cn( + "flex w-full min-w-0 items-baseline gap-3 px-3 py-[5px] text-left outline-none", + on && "bg-panel-2 text-text", + it.kind === "action" && it.disabled && "cursor-default opacity-40", + ); + const body = ( + <> + <span className={cn("shrink-0", it.kind === "verb" && "font-mono text-[12px]")}>{it.label}</span> + {it.hint && <span className={cn("ml-auto min-w-0 truncate text-[11px]", it.kind === "verb" ? "text-muted-2" : "font-mono text-muted")}>{it.hint}</span>} + </> + ); + const common = { + ref: (el: HTMLElement | null) => void (els.current[i] = el), + role: "menuitem", + tabIndex: on ? 0 : -1, + onMouseMove: () => i !== at && usable(i) && setAt(i), + className: cls, + } as const; + if (it.kind === "link") { + return ( + <Link key={it.key} {...common} href={it.href} prefetch={false} data-ws-menu-link={it.key} onClick={() => onClose(false)}> + {body} + </Link> + ); + } + return ( + <button + key={it.key} + type="button" + {...common} + aria-disabled={it.kind === "action" && it.disabled ? true : undefined} + data-ws-menu-action={it.kind === "action" ? it.key : undefined} + data-ws-menu-verb={it.kind === "verb" ? it.row.verb : undefined} + title={it.kind === "verb" ? `umtool ${it.row.verb}: ${it.row.summary} -- its form, filled in from ${info.id}` : it.kind === "action" ? it.why : undefined} + onClick={() => choose(it)} + > + {body} + </button> + ); + })} + </div> + ))} + </div> + ); + return typeof document === "undefined" ? null : createPortal(menu, document.body); +} diff --git a/umtool/components/projects/workspace/BlockStrip.tsx b/umtool/components/projects/workspace/BlockStrip.tsx @@ -1,7 +1,8 @@ "use client"; -import { useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useRef, useState } from "react"; import { cn } from "@/lib/utils"; +import BlockMenu, { type BlockActions, type MenuAnchor } from "./BlockMenu"; // --------------------------------------------------------------------------- // THE STRIP (umtool redesign L7a): the cut as blocks, in the draft's order -- @@ -15,6 +16,9 @@ import { cn } from "@/lib/utils"; // 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) +// right-click, ⋯, Shift+F10 or the context-menu key +// its menu (BlockMenu, lane L8b): the strip's own writers and +// every registry verb for its kind, each the ⌘K form filled in // // 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. @@ -30,6 +34,8 @@ export type Block = { at: number | null; rejected?: string | null; missing?: boolean; + /** Its id is in the timeline more than once and the view did not say which it is: no index, nothing moves it. */ + twin?: boolean; }; const TYPE_WORD: Record<string, string> = { clip: "clip", post: "post", teaser: "card", card: "card", intro: "intro", video: "video" }; @@ -56,6 +62,7 @@ export default function BlockStrip({ onMove, plus, marks = null, + menu, }: { blocks: Block[]; selected: string | null; @@ -69,10 +76,49 @@ export default function BlockStrip({ plus: React.ReactNode; /** The review pass's answers (L7b): a block kept or to fix is marked. */ marks?: Map<string, { mark: "keep" | "fix" | "ruled"; note: string | null }> | null; + /** What a block's menu does (none: no menus). */ + menu?: BlockActions; }) { const ref = useRef<HTMLDivElement | null>(null); const [drag, setDrag] = useState<string | null>(null); const [over, setOver] = useState<string | null>(null); + // The open menu: its block -- by its place in the strip, two blocks may share an id -- and where it opens. A ref + // too, so the key's menu and the contextmenu event the browser may send after it open one menu. + const [open, setOpen] = useState<{ id: string; i: number; anchor: MenuAnchor; seq: number } | null>(null); + const seq = useRef(0); + const openRef = useRef<{ id: string; i: number } | null>(null); + const blockEl = (i: number) => ref.current?.querySelector(`[data-ws-block-i="${i}"]`) as HTMLElement | null; + const showMenu = (id: string, i: number, anchor: MenuAnchor | null) => { + if (!menu || openRef.current?.i === i) return; + const r = blockEl(i)?.getBoundingClientRect(); + const at: MenuAnchor = anchor ?? { rect: { left: r?.left ?? 8, top: r?.top ?? 8, bottom: r?.bottom ?? 8 } }; + openRef.current = { id, i }; + seq.current += 1; + setOpen({ id, i, anchor: at, seq: seq.current }); + }; + const closeMenu = useCallback((refocus: boolean) => { + const o = openRef.current; + openRef.current = null; + setOpen(null); + if (refocus && o) (ref.current?.querySelector(`[data-ws-block-i="${o.i}"]`) as HTMLElement | null)?.focus(); + }, []); + // Where its block is now: its place, or -- the strip re-read under it (an undo landing, another writer) -- the + // one block with its id. A block that left, or whose id is now on two blocks, takes the menu with it. + const openAt = (() => { + if (!open) return null; + if (blocks[open.i]?.id === open.id) return open.i; + const hits = blocks.flatMap((b, j) => (b.id === open.id ? [j] : [])); + return hits.length === 1 ? hits[0] : null; + })(); + const found = openAt !== null && menu ? menu.info(openAt) : null; + const openInfo = found && found.id === open?.id ? found : null; + useEffect(() => { + if (open && !openInfo) closeMenu(false); + else if (open && openAt !== null && openAt !== open.i) { + openRef.current = { id: open.id, i: openAt }; + setOpen({ ...open, i: openAt }); + } + }, [open, openInfo, openAt, closeMenu]); // The selected block kept in view (the keys walk past the strip's edge). useEffect(() => { if (!selected) return; @@ -94,13 +140,15 @@ export default function BlockStrip({ 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; + const menuOn = open?.i === i; return ( + <div key={`${b.id}@${i}`} className="group relative flex shrink-0"> <button - key={`${b.id}@${i}`} type="button" role="option" aria-selected={on} data-ws-block={b.id} + data-ws-block-i={i} data-ws-block-type={b.type} data-ws-block-at={b.at ?? ""} data-ws-block-now={b.id === playing ? "" : undefined} @@ -132,13 +180,31 @@ export default function BlockStrip({ 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" : ""}`} + onContextMenu={(e) => { + if (!menu) return; + e.preventDefault(); + // From the keyboard (Shift+F10, the context-menu key) the browser's event has no pointer: over the block. + const keyed = (e.nativeEvent as PointerEvent).pointerType === "" || (e.clientX === 0 && e.clientY === 0); + showMenu(b.id, i, keyed ? null : { x: e.clientX, y: e.clientY }); + }} + onKeyDown={(e) => { + if (!menu) return; + if ((e.shiftKey && e.key === "F10") || e.key === "ContextMenu") { + e.preventDefault(); + e.stopPropagation(); + showMenu(b.id, i, null); + } + }} + aria-haspopup={menu ? "menu" : undefined} + aria-keyshortcuts={menu ? "Shift+F10" : undefined} + 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" : ""}${menu ? " · right-click or Shift+F10: its menu" : ""}`} 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)]", + menuOn && "border-[var(--color-signal)]", drag === b.id && "opacity-50", b.rejected && "opacity-60", "focus-visible:ring-2 focus-visible:ring-[var(--color-signal)]", @@ -160,11 +226,36 @@ export default function BlockStrip({ {b.missing && <span className="truncate text-[var(--color-dirty)]">no media</span>} </span> </button> + {menu && ( + <button + type="button" + tabIndex={-1} + aria-label={`${b.id}: its menu`} + aria-haspopup="menu" + aria-expanded={menuOn} + data-ws-block-more={b.id} + data-ws-block-more-i={i} + onClick={(e) => { + e.stopPropagation(); + // A toggle: the menu's press-outside leaves its own ⋯ alone (BlockMenu), so this press closes it. + if (menuOn) closeMenu(true); + else showMenu(b.id, i, null); + }} + className={cn( + "absolute bottom-0.5 right-0.5 flex h-[18px] w-[22px] items-center justify-center rounded-[2px] font-mono text-[12px] leading-none text-muted hover:bg-panel-2 hover:text-text", + on || menuOn ? "opacity-100" : "opacity-0 group-hover:opacity-100 group-focus-within:opacity-100", + )} + > + ⋯ + </button> + )} + </div> ); })} <div className="flex shrink-0 items-stretch" data-ws-plus-slot=""> {plus} </div> + {open && openInfo && menu && <BlockMenu key={open.seq} place={openAt ?? open.i} info={openInfo} actions={menu} anchor={open.anchor} onClose={closeMenu} />} </div> ); } diff --git a/umtool/components/projects/workspace/ReviewPass.tsx b/umtool/components/projects/workspace/ReviewPass.tsx @@ -169,6 +169,9 @@ function DraftVerdict({ project, draft }: { project: string; draft: { line: stri const j = (await r.json().catch(() => ({}))) as { judged?: string; saved?: boolean; error?: string }; if (!r.ok || !j.judged) throw new Error(j.error ?? `HTTP ${r.status}`); setSaved({ id: j.judged, saved: !!j.saved }); + // A version saved for it: the draft's line ("from vN") is read again. Its token did not move (the manifest is + // as it was), so the workspace keeps its Redo and its Undo token (the MANIFEST_CHANGED rule, L8b). + if (j.saved) announceManifestChanged(project); } catch (e) { setErr(e instanceof Error ? e.message : String(e)); } finally { diff --git a/umtool/components/projects/workspace/Workspace.tsx b/umtool/components/projects/workspace/Workspace.tsx @@ -5,7 +5,7 @@ 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, startOf } from "@/lib/report/playCut.mjs"; +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"; @@ -14,6 +14,7 @@ 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"; @@ -57,7 +58,8 @@ import { READ_ONLY_SAID, WorkspaceReadOnly, workspaceReadOnly } from "./readOnly // 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. +// 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. */ @@ -72,6 +74,7 @@ const KEYS: { keys: string; what: string }[] = [ { 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" }, @@ -233,18 +236,24 @@ export default function Workspace({ 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`). + // 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<typeof setTimeout> | null = null; + let held: string | 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); + else held = tl.current.token; // The token first (the next Undo is asked on it), then the view. t = setTimeout(() => { - void loadTimeline().then(() => reloadView()); + 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); @@ -257,21 +266,31 @@ export default function Workspace({ // ---- 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])); + const fresh = !!tlToken && view.token === tlToken; + const count = new Map<string, number>(); + 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, - // A version's blocks are never moved (its timeline is not the draft's). - at: e.type === "intro" || readOnly ? null : (at.get(e.id) ?? null), + at, + twin: e.type !== "intro" && !readOnly && at === null && n > 1, rejected: e.rejected?.label ?? null, missing: e.type === "clip" && !e.media, }; }); - }, [view.entries, itemOf, tlIds, readOnly]); + }, [view.entries, view.token, itemOf, tlIds, tlToken, readOnly]); const entryOf = core.entryOf; // ---- the selection (the inspector's block), kept in the URL (`?block=`) ---------------- @@ -414,27 +433,26 @@ export default function Workspace({ }, [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); + // 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); }, - [blocks, selected, move, undo.busy, loadTimeline], + [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(() => { + const editHere = useCallback((which?: string) => { if (readOnlyRef.current) return; - const id = selected && selected !== ADD ? selected : (core.item?.id ?? null); + 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); - const at = p ? Math.round(Math.max(0, now().t - p.it.from) * 100) / 100 : 0; + // 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 } })); @@ -460,7 +478,10 @@ export default function Workspace({ setHelp(false); return; } - if (tgt?.closest("input, textarea, select, [contenteditable=true], [data-ws-own-keys], [role=dialog]")) 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. @@ -547,6 +568,48 @@ export default function Workspace({ () => [...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<BlockActions>( + () => ({ + 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; @@ -631,7 +694,7 @@ export default function Workspace({ 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} + onClick={() => editHere()} data-ws-edit-here="" title="the selected clip on the full bench, in place (E): Back returns here" > @@ -659,6 +722,8 @@ export default function Workspace({ }} onMove={(id, at, to) => 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 : ( <button type="button" diff --git a/umtool/components/shell/CommandForm.tsx b/umtool/components/shell/CommandForm.tsx @@ -14,14 +14,40 @@ import { cn } from "@/lib/utils"; // it deletes, evicts or kills) asks a second press, "Yes, <what it does>", // and the server wants that confirm too. What Run started is handed up // (onStarted), so the palette lists it under Runs after an Escape. +// +// A workspace block's menu (lane block-menus L8b) opens this same form with +// `prefill`: what the block filled in (verbs.mjs fromBlockValues), over the +// page's context; the focus goes to the first arg still to give. When a run +// ends the form says so (onEnded); the palette, which watches every run to its +// end even after this form is gone, announces a done run's write. // --------------------------------------------------------------------------- export type CliArg = { name: string; type: string; required?: boolean; choices?: string[]; default?: unknown; help?: string; repeat?: boolean; context?: string }; -export type CliVerb = { verb: string; summary: string; target: string; queue: boolean; confirm?: { what: string; when?: string[]; unless?: string[] } | null; args: CliArg[] }; +export type CliVerb = { + verb: string; + summary: string; + target: string; + queue: boolean; + confirm?: { what: string; when?: string[]; unless?: string[] } | null; + args: CliArg[]; + /** The block kinds whose menu offers it, what a block fills in, and a page it opens instead (lib/cli/verbs.mjs). */ + blocks?: string[]; + fromBlock?: Record<string, string | true>; + nav?: string; +}; export type CliContext = { project: string | null; clip: string | null; post: string | null; take: string | null }; export type Value = string | boolean; /** A run the palette keeps: its form's values and what it started. */ -export type CliRun = { verb: string; values: Record<string, Value>; kind: "job" | "queued"; id: string; line: string; at: number }; +export type CliRun = { + verb: string; + values: Record<string, Value>; + kind: "job" | "queued"; + id: string; + line: string; + at: number; + /** The project it names, resolved by the server (its id): a done run announces a write to it. */ + project: string | null; +}; type Run = | { kind: "job"; id: string; state: string; log: string[]; next: number; error: string | null; exitCode: number | null } @@ -31,7 +57,7 @@ const TEXTAREA = new Set(["pairs", "flagpairs", "list", "text", "json"]); const TERMINAL = new Set(["done", "failed", "cancelled", "blocked"]); /** What the page tells the form: the project for a project arg, the selection for one that asks. */ -function initialValues(row: CliVerb, ctx: CliContext): Record<string, Value> { +function initialValues(row: CliVerb, ctx: CliContext, prefill: Record<string, Value> | null): Record<string, Value> { const v: Record<string, Value> = {}; for (const a of row.args) { if (a.type === "project" && a.name === "project" && ctx.project) v[a.name] = ctx.project; @@ -40,7 +66,7 @@ function initialValues(row: CliVerb, ctx: CliContext): Record<string, Value> { else if (a.context === "take" && ctx.take && a.required) v[a.name] = ctx.take; else if (a.default !== undefined) v[a.name] = typeof a.default === "boolean" ? a.default : String(a.default); } - return v; + return prefill ? { ...v, ...prefill } : v; } export default function CommandForm({ @@ -48,16 +74,22 @@ export default function CommandForm({ ctx, onBack, resume = null, + prefill = null, onStarted, + onEnded, }: { row: CliVerb; ctx: CliContext; onBack: () => void; + /** Values a block's menu filled in (over the page's context). */ + prefill?: Record<string, Value> | null; /** A run started before (the palette's Runs): its values, and it is followed again. */ resume?: CliRun | null; onStarted?: (run: CliRun) => void; + /** What Run started ended (done, failed, cancelled, blocked): its id. */ + onEnded?: (id: string, state: string) => void; }) { - const [values, setValues] = useState<Record<string, Value>>(() => (resume ? resume.values : initialValues(row, ctx))); + const [values, setValues] = useState<Record<string, Value>>(() => (resume ? resume.values : initialValues(row, ctx, prefill))); const [run, setRun] = useState<Run | null>(() => resume ? resume.kind === "job" @@ -71,9 +103,21 @@ export default function CommandForm({ const [copied, setCopied] = useState(false); const first = useRef<HTMLElement | null>(null); const logRef = useRef<HTMLPreElement>(null); + // The field the focus starts in: the first required arg still empty when something was filled in for it, else the first. + const [focusAt] = useState(() => { + if (!prefill) return 0; + const i = row.args.findIndex((a) => a.required && (values[a.name] === undefined || values[a.name] === "")); + return i >= 0 ? i : 0; + }); useEffect(() => { first.current?.focus(); + // Opened with the palette in one go (a block's menu): the dialog's showModal runs after this and focuses its + // first button, so the field is focused again once it has. + const f = requestAnimationFrame(() => { + if (first.current && document.activeElement !== first.current && first.current.closest("dialog")?.contains(document.activeElement)) first.current.focus(); + }); + return () => cancelAnimationFrame(f); }, []); const built = useMemo(() => buildArgv(row, values), [row, values]); @@ -122,6 +166,13 @@ export default function CommandForm({ if (el) el.scrollTop = el.scrollHeight; }, [run?.log.length]); + // The run's end, told up at once (the palette also watches it, for after this form is gone). + const runId = run ? (run.kind === "job" ? run.id : run.qid) : null; + useEffect(() => { + if (runId && run && TERMINAL.has(run.state)) onEnded?.(runId, run.state); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [runId, run?.state]); + const set = (name: string, v: Value) => setValues((cur) => ({ ...cur, [name]: v })); const submit = async (confirmed = false) => { @@ -146,6 +197,7 @@ export default function CommandForm({ confirm?: string; job?: { id: string; state: string; log: string[]; next: number; error: string | null; exitCode: number | null }; queued?: { qid: string }; + project?: string | null; queue?: { armed: boolean }; }; if (!r.ok) { @@ -153,10 +205,10 @@ export default function CommandForm({ else setRefused(j.error ?? `HTTP ${r.status}`); } else if (j.job) { setRun({ kind: "job", id: j.job.id, state: j.job.state, log: j.job.log, next: j.job.next, error: j.job.error, exitCode: j.job.exitCode }); - onStarted?.({ verb: row.verb, values, kind: "job", id: j.job.id, line: j.line ?? line ?? "", at: Date.now() }); + onStarted?.({ verb: row.verb, values, kind: "job", id: j.job.id, line: j.line ?? line ?? "", at: Date.now(), project: j.project ?? null }); } else if (j.queued) { setRun({ kind: "queued", qid: j.queued.qid, state: "queued", log: [], error: null, exitCode: null, runnerUp: !!j.queue?.armed }); - onStarted?.({ verb: row.verb, values, kind: "queued", id: j.queued.qid, line: j.line ?? line ?? "", at: Date.now() }); + onStarted?.({ verb: row.verb, values, kind: "queued", id: j.queued.qid, line: j.line ?? line ?? "", at: Date.now(), project: j.project ?? null }); } } catch (e) { setRefused(e instanceof Error ? e.message : String(e)); @@ -179,7 +231,7 @@ export default function CommandForm({ const field = (a: CliArg, i: number) => { const id = `cli-arg-${i}`; const v = values[a.name]; - const ref = i === 0 ? (el: HTMLElement | null) => void (first.current = el) : undefined; + const ref = i === focusAt ? (el: HTMLElement | null) => void (first.current = el) : undefined; const bad = !built.ok && built.field === a.name; const control = a.type === "boolean" ? ( diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx @@ -22,8 +22,9 @@ import { phraseFinderHref, } from "@/lib/hrefs"; import { MODES } from "@/lib/types"; +import { announceManifestChanged } from "@/components/projects/timelineApi"; import { cn } from "@/lib/utils"; -import CommandForm, { type CliContext, type CliRun, type CliVerb } from "./CommandForm"; +import CommandForm, { type CliContext, type CliRun, type CliVerb, type Value } from "./CommandForm"; // --------------------------------------------------------------------------- // ⌘K: jump to any piece, place, tool or create action (plans/umtool-redesign.md, @@ -45,9 +46,27 @@ import CommandForm, { type CliContext, type CliRun, type CliVerb } from "./Comma // gets the last page's project: the form is keyed on the context and remounts when // it arrives). What a form's Run started stays under Runs (nothing typed) for // the page's life, so an Escape mid-run loses nothing. +// +// A WORKSPACE BLOCK'S MENU (lane block-menus L8b) opens a verb's form here, the +// same form, with `umtool:command` ({ row, values }: the row and what the +// block filled in) -- one form component, one Runs list, one POST /api/cli. +// +// EVERY RUN IS WATCHED TO ITS END here, open or closed (the palette is mounted +// once, for the page's life): a run that ends done and names a project +// announces a write to it (MANIFEST_CHANGED, by the id the server resolved), +// whatever its target -- `links --embed-ids` writes the draft too -- and a +// queued one that ends after an Escape still does. A re-read is cheap. // --------------------------------------------------------------------------- export const JUMP_EVENT = "umtool:jump"; +export const COMMAND_EVENT = "umtool:command"; +/** `umtool:command`'s detail: the row's form opened with these values over the page's context. */ +export type CommandRequest = { row: CliVerb; values: Record<string, Value> }; + +/** Open one verb's form in the palette, pre-filled (a block's menu). */ +export function openCommand(req: CommandRequest) { + window.dispatchEvent(new CustomEvent<CommandRequest>(COMMAND_EVENT, { detail: req })); +} type Item = { id: string; section: "Runs" | "Places" | "Tools" | "Create" | "Pieces" | "Commands"; label: string; hint: string; href: string; verb?: string; run?: CliRun }; @@ -127,12 +146,52 @@ export default function JumpPalette() { const [form, setForm] = useState<CliVerb | null>(null); const [resume, setResume] = useState<CliRun | null>(null); const [runs, setRuns] = useState<CliRun[]>([]); + const [prefill, setPrefill] = useState<Record<string, Value> | null>(null); + // The runs' ends: each told once (the form tells it at once; the watcher below for the rest). + const ended = useRef(new Set<string>()); + const runsRef = useRef(runs); + runsRef.current = runs; + const endRun = useCallback((id: string, state: string) => { + if (ended.current.has(id)) return; + ended.current.add(id); + const r = runsRef.current.find((x) => x.id === id); + if (state === "done" && r?.project) announceManifestChanged(r.project); + }, []); + const anyRunning = runs.some((r) => !ended.current.has(r.id)); + useEffect(() => { + if (!anyRunning) return; + let live = true; + const t = setInterval(async () => { + for (const r of runsRef.current) { + if (ended.current.has(r.id)) continue; + try { + const url = r.kind === "job" ? `/api/cli?job=${encodeURIComponent(r.id)}&since=1000000` : `/api/cli?qid=${encodeURIComponent(r.id)}`; + const res = await fetch(url, { cache: "no-store" }); + if (!live) return; + if (res.status === 404) { + endRun(r.id, "gone"); + continue; + } + const j = (await res.json()) as { job?: { state: string }; step?: { state: string } }; + const state = j.job?.state ?? j.step?.state ?? ""; + if (["done", "failed", "cancelled", "blocked"].includes(state)) endRun(r.id, state); + } catch { + /* the next turn asks again */ + } + } + }, 1500); + return () => { + live = false; + clearInterval(t); + }; + }, [anyRunning, runs, endRun]); const show = useCallback(() => { setQ(""); setAt(0); setForm(null); setResume(null); + setPrefill(null); setCtx(NO_CONTEXT); setOpen(true); }, []); @@ -148,12 +207,21 @@ export default function JumpPalette() { } }; const onJump = () => show(); + const onCommand = (e: Event) => { + const req = (e as CustomEvent<CommandRequest>).detail; + if (!req?.row?.verb) return; + show(); + setForm(req.row); + setPrefill(req.values ?? {}); + }; document.addEventListener("keydown", onKey); window.addEventListener(JUMP_EVENT, onJump); + window.addEventListener(COMMAND_EVENT, onCommand); setReady(true); return () => { document.removeEventListener("keydown", onKey); window.removeEventListener(JUMP_EVENT, onJump); + window.removeEventListener(COMMAND_EVENT, onCommand); }; }, [show]); @@ -252,6 +320,7 @@ export default function JumpPalette() { const v = verbs?.find((x) => x.verb === it.verb); if (v) { setResume(it.run ?? null); + setPrefill(null); setForm(v); } return; @@ -275,16 +344,22 @@ export default function JumpPalette() { {open && form && ( <div className="flex h-[76vh] max-h-[76vh] flex-col"> <CommandForm - key={`${form.verb}|${resume?.id ?? ""}|${ctx.project ?? ""}|${ctx.clip ?? ""}|${ctx.post ?? ""}|${ctx.take ?? ""}`} + // Remounted when the page's context arrives -- unless a block filled it in: the block is its context, and + // a remount then would drop what was typed meanwhile. + key={prefill && !resume ? `${form.verb}|block` : `${form.verb}|${resume?.id ?? ""}|${ctx.project ?? ""}|${ctx.clip ?? ""}|${ctx.post ?? ""}|${ctx.take ?? ""}`} row={form} ctx={ctx} resume={resume} + prefill={resume ? null : prefill} onStarted={(r) => { - setRuns((cur) => [r, ...cur.filter((x) => x.id !== r.id)].slice(0, 8)); + runsRef.current = [r, ...runsRef.current.filter((x) => x.id !== r.id)].slice(0, 8); + setRuns(runsRef.current); }} + onEnded={endRun} onBack={() => { setForm(null); setResume(null); + setPrefill(null); setTimeout(() => input.current?.focus(), 0); }} /> diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -759,6 +759,7 @@ fetched selects its block. Read-only; its terminal twins are `umtool check <p>` | 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` | +| a block's menu | right-click a block, its **⋯**, or **Shift+F10** / the context-menu key on it: **Edit in place**, **Play from here**, **Move left / right**, **Remove**, **Full bench**, **Life cycle**, then its kind's verbs (below) | each verb is its own `umtool …` line (the form's **Copy as CLI**); Remove is `umtool timeline <p> remove <id>` | - **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 @@ -770,6 +771,21 @@ fetched selects its block. Read-only; its terminal twins are `umtool check <p>` 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). +- **A block's menu** (`components/projects/workspace/BlockMenu.tsx`, lane L8b) lists, under the strip's own writers, + every verb of the registry whose row names the block's kind — `blocks: [...]` on the row in + `umtool/lib/cli/verbs.mjs` (clip, post, teaser, card — a chapter card —, intro, video); a verb with no `blocks` is + never in a block menu. Choosing one opens **the same form ⌘K opens** (below), filled in from the block by the row's + own `fromBlock` rules (`{id}`, `{at}`, `{second}` — the playhead's source second in the clip, else its cut's start —, + `{cutStart}-{cutEnd}`, `{channel}/{video}`): `timeline teaser-insert --after <this block>`, `still <clip> --at + <second>`, `timeline split <clip> <second>`, `quote-check --clips <clip>`, `links --embed-ids --clips <clip>` (the + one-clip Rumble cite fix), `posts set-item <item>`, `timeline move <id>` (its `--to` is yours) … Its Run is `POST + /api/cli`, as ⌘K's; a run that ends done makes the workspace read the draft again, and **Undo** takes it back. + **Move left / right** and **Remove** (and Alt+← →, a drag) name the block by its OWN timeline index, the one the + play view says (`timelineAt`) — never the first or last entry with its id; an id in the timeline twice that the + view does not place (an entry turned by `variants` beside a twin) is not moved or removed here: *this entry has a + twin — use the Cut tab*. No menu while the workspace shows a version or a take. A row with `nav` is a page, not a run (`ingredient`: the **Life cycle** link). Keys: ↑ ↓ Home End and a + letter move, Enter or Space chooses, Esc or Tab closes, and the focus goes back to the block. A new block verb is + `blocks` and `fromBlock` on its row; `verbs.test.mjs` fails until every arg that names a block has a rule. - **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 @@ -1993,6 +2009,14 @@ What a form may name, and what it asks first: a tailnet name) needs that name in `UMTOOL_ALLOWED_HOSTS`, or the app's own pages cannot save anything. - **Runs.** What a form started stays under **Runs** in the palette (nothing typed) for the page's life: an Escape mid-run loses nothing. The same queued command sent twice within 5 s is the one step. +- **From a block.** A workspace block's menu ([The workspace](#the-workspace-one-screen-per-report-video), "A block's + menu") opens these forms too, filled in from the block (`fromBlock` on the row), in this palette: one form, one + Runs list, one `POST /api/cli`. +- **A run's end is heard.** The palette watches every run it started to its end, open or closed (a queued narrate + that ends after an Escape too), and one that ends **done** and names a project announces a write to it + (MANIFEST_CHANGED, by the id `POST /api/cli` answers as `project`), whatever its target — `links --embed-ids` is + "project" and writes the draft — so the page under it reads its draft again and its next Undo is on the fresh + token. ## Reading them back diff --git a/umtool/e2e/block-menus.spec.ts b/umtool/e2e/block-menus.spec.ts @@ -0,0 +1,402 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// A BLOCK'S MENU (umtool redesign L8b; components/projects/workspace/BlockMenu.tsx): right-click a block of the +// workspace's strip (or its ⋯, or Shift+F10 on it) and its menu lists the strip's own writers, then the registry +// verbs whose row names that block's kind (lib/cli/verbs.mjs `blocks`) -- a clip's menu no post verb, a post's no +// clip verb. A verb opens THE ⌘K form (shell/CommandForm), filled in from the block by the row's `fromBlock`; +// Run is POST /api/cli as ⌘K's, the draft changes, and the workspace's Undo takes it back. +// +// block-menus-fixture (WRITES; make-fixture.mjs): the workspace fixture's cut, its own copy -- +// c01 c02 p-5 k01 c03 c04 (p-5 a post item, k01 a chapter card). Each test leaves the draft as it found it. +// E2E_BLOCK_MENUS_SHOTS=<dir>: screenshots there (1366×768). +// --------------------------------------------------------------------------- + +test.describe.configure({ mode: "serial" }); + +const P = "reports/block-menus-fixture"; +const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "block-menus-fixture"); +const SHOTS = process.env.E2E_BLOCK_MENUS_SHOTS ?? ""; +const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8"); +const manifest = () => JSON.parse(manifestText()) as { timeline: { id: string; type: string; lines?: unknown[] }[] }; +const order = () => manifest().timeline.map((e) => e.id).join(" "); +const ORIGINAL = "c01 c02 p-5 k01 c03 c04"; +const block = (page: Page, id: string) => page.locator(`[data-ws-block="${id}"]`); +const menuOf = (page: Page, id: string) => page.locator(`[role="menu"][data-ws-menu="${id}"]`); +const palette = (page: Page) => page.locator("dialog[data-jump]"); +const shot = async (page: Page, name: string) => { + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `${name}.png`) }); +}; + +async function open(page: Page) { + await page.goto(urls.workspaceHref(P)); + await expect(page.locator(`[data-workspace="${P}"]`)).toBeVisible(); + await expect(page.locator("[data-ws-strip] [data-ws-block]")).toHaveCount(6); + // The palette listens (the form opens in it) and the workspace has read the draft's token (its Undo asks on it). + await expect(page.locator("dialog[data-jump][data-ready]")).toBeAttached({ timeout: 60_000 }); + await expect(page.locator("[data-workspace]")).toHaveAttribute("data-ws-token", /./); +} + +test.beforeEach(async ({ page }) => { + test.setTimeout(150_000); + await page.setViewportSize({ width: 1366, height: 768 }); +}); + +test("a clip's menu: the clip's verbs, no post's; teaser-insert's form is filled in after this block; Copy as CLI; Run; Undo restores", async ({ page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + const original = manifestText(); + expect(order()).toBe(ORIGINAL); + await open(page); + + await block(page, "c01").click({ button: "right" }); + const menu = menuOf(page, "c01"); + await expect(menu).toBeVisible(); + await expect(menu).toHaveAttribute("aria-label", "Clip c01"); + // The direct items: no form needed. c01 is first: Move left has nowhere to go. + for (const a of ["edit", "play", "move-left", "move-right", "remove"]) await expect(menu.locator(`[data-ws-menu-action="${a}"]`)).toBeVisible(); + await expect(menu.locator('[data-ws-menu-action="move-left"]')).toHaveAttribute("aria-disabled", "true"); + await expect(menu.locator('[data-ws-menu-link="bench"]')).toHaveAttribute("href", urls.clipBenchHref(P, "c01")); + // `ingredient` is navigation: its life-cycle page, a link (not a run). + await expect(menu.locator('[data-ws-menu-link="nav:ingredient"]')).toHaveAttribute("href", urls.ingredientHref("testchan", "vid1")); + await expect(menu.locator('[data-ws-menu-verb="ingredient"]')).toHaveCount(0); + // The registry's clip verbs, and not a post's. + for (const v of ["window", "set", "still", "quote-check", "links", "timeline move", "timeline remove", "timeline teaser-insert", "timeline split"]) { + await expect(menu.locator(`[data-ws-menu-verb="${v}"]`)).toHaveCount(1); + } + await expect(menu.locator('[data-ws-menu-verb^="posts "]')).toHaveCount(0); + await expect(menu.locator('[data-ws-menu-verb="timeline teaser"]')).toHaveCount(0); + // It fits the window, and the first item has the focus. + const box = await menu.boundingBox(); + expect(box!.y).toBeGreaterThanOrEqual(0); + expect(box!.y + box!.height).toBeLessThanOrEqual(768); + await expect(menu.locator('[data-ws-menu-action="edit"]')).toBeFocused(); + await shot(page, "block-menu-clip"); + + // teaser-insert: THE ⌘K form, filled in from the block -- the project, and after this block. + await menu.locator('[data-ws-menu-verb="timeline teaser-insert"]').click(); + await expect(menu).toHaveCount(0); + const form = palette(page).locator('[data-cli-form="timeline teaser-insert"]'); + await expect(form).toBeVisible(); + await expect(form.locator('[data-cli-arg="project"] input')).toHaveValue(P); + await expect(form.locator('[data-cli-arg="--after"] input')).toHaveValue("c01"); + await form.locator('[data-cli-arg="--line"] textarea').fill("From the menu"); + const line = `node umtool/bin/umtool.mjs timeline ${P} teaser-insert --after c01 --line 'From the menu'`; + await expect(form.locator("[data-cli-line]")).toHaveText(line); + await form.locator("[data-cli-copy]").click(); + await expect(form.locator("[data-cli-copy]")).toHaveText("Copied"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(line); + const pbox = await palette(page).boundingBox(); + expect(pbox!.y + pbox!.height, "the form fits 1366×768").toBeLessThanOrEqual(768); + await shot(page, "block-menu-form"); + + // Run: POST /api/cli, as ⌘K's; the draft has the card after c01. + await form.locator("[data-cli-run]").click(); + await expect(form.locator("[data-cli-state]")).toHaveAttribute("data-cli-state", "done", { timeout: 90_000 }); + const tl = manifest().timeline; + expect(tl[0].id).toBe("c01"); + expect(tl[1].type).toBe("teaser"); + const card = tl[1].id; + expect(order()).toBe(`c01 ${card} c02 p-5 k01 c03 c04`); + // The run announced the write: the strip under the palette has the card already. + await expect(block(page, card)).toBeVisible({ timeout: 15_000 }); + // Esc: the palette closes and the focus is back on the block the menu was for. + await page.keyboard.press("Escape"); + await expect(palette(page)).toBeHidden(); + await expect(block(page, "c01")).toBeFocused(); + + // One Undo restores the draft byte for byte. + await page.locator("[data-ws-undo]").click(); + await expect.poll(manifestText, { timeout: 15_000 }).toBe(original); + await expect(block(page, card)).toHaveCount(0); +}); + +test("a post's menu and a chapter card's: their verbs; Move right, Remove and ⋯ from the menu, each undone", async ({ page }) => { + const original = manifestText(); + expect(order()).toBe(ORIGINAL); + await open(page); + + await block(page, "p-5").click({ button: "right" }); + const post = menuOf(page, "p-5"); + await expect(post).toBeVisible(); + await expect(post).toHaveAttribute("aria-label", "Post item p-5"); + for (const v of ["posts set-item", "posts narrate", "posts fx", "timeline teaser-insert", "timeline move"]) await expect(post.locator(`[data-ws-menu-verb="${v}"]`)).toHaveCount(1); + for (const v of ["window", "set", "still", "quote-check", "timeline split"]) await expect(post.locator(`[data-ws-menu-verb="${v}"]`)).toHaveCount(0); + await expect(post.locator('[data-ws-menu-link="bench"]')).toHaveAttribute("href", urls.postBenchHref(P, "p-5")); + await shot(page, "block-menu-post"); + + // Move right: the strip's writer (the timeline's move), one undo point. + await post.locator('[data-ws-menu-action="move-right"]').click(); + await expect.poll(order, { timeout: 15_000 }).toBe("c01 c02 k01 p-5 c03 c04"); + await expect(page.locator("[data-ws-undo-said]")).toContainText("Moved p-5"); + await page.locator("[data-ws-undo]").click(); + await expect.poll(manifestText, { timeout: 15_000 }).toBe(original); + + // The chapter card, from its ⋯: the cut's verbs, no clip's or post's; Remove, then Undo. + await block(page, "k01").hover(); + await page.locator('[data-ws-block-more="k01"]').click(); + const card = menuOf(page, "k01"); + await expect(card).toBeVisible(); + await expect(card).toHaveAttribute("aria-label", "Chapter card k01"); + await expect(card.locator('[data-ws-menu-verb="timeline teaser-insert"]')).toHaveCount(1); + await expect(card.locator('[data-ws-menu-verb="window"], [data-ws-menu-verb^="posts "]')).toHaveCount(0); + await expect(card.locator('[data-ws-menu-action="edit"]')).toHaveCount(0); + await card.locator('[data-ws-menu-action="remove"]').click(); + await expect.poll(order, { timeout: 15_000 }).toBe("c01 c02 p-5 c03 c04"); + await expect(page.locator("[data-ws-undo-said]")).toContainText("Removed k01"); + await expect(block(page, "k01")).toHaveCount(0); + await page.locator("[data-ws-undo]").click(); + await expect.poll(manifestText, { timeout: 15_000 }).toBe(original); + await expect(block(page, "k01")).toBeVisible(); + + // A press outside closes a menu and writes nothing. + await block(page, "c03").click({ button: "right" }); + await expect(menuOf(page, "c03")).toBeVisible(); + await page.locator("[data-ws-clock]").click(); + await expect(menuOf(page, "c03")).toHaveCount(0); + expect(manifestText()).toBe(original); +}); + +test("keyboard only: Shift+F10 opens it, the arrows move, Enter chooses, Esc closes; the focus goes back to the block", async ({ page }) => { + const original = manifestText(); + await open(page); + await block(page, "c02").focus(); + + await page.keyboard.press("Shift+F10"); + const menu = menuOf(page, "c02"); + await expect(menu).toBeVisible(); + const action = (a: string) => menu.locator(`[data-ws-menu-action="${a}"]`); + await expect(action("edit")).toBeFocused(); + await page.keyboard.press("ArrowDown"); + await expect(action("play")).toBeFocused(); + await page.keyboard.press("ArrowUp"); + await expect(action("edit")).toBeFocused(); + // Up from the first wraps to the last; Home goes back. + await page.keyboard.press("ArrowUp"); + await expect(menu.locator('[role="menuitem"]').last()).toBeFocused(); + await page.keyboard.press("Home"); + await expect(action("edit")).toBeFocused(); + await page.keyboard.press("Escape"); + await expect(menu).toHaveCount(0); + await expect(block(page, "c02")).toBeFocused(); + + // Play from here: ↓ Enter -- the block selected, the viewer playing it. + await page.keyboard.press("Shift+F10"); + await expect(action("play")).toBeVisible(); + await page.keyboard.press("ArrowDown"); + await expect(action("play")).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(menu).toHaveCount(0); + await expect(block(page, "c02")).toHaveAttribute("aria-selected", "true"); + await expect(page.locator("[data-ws-viewer]")).toHaveAttribute("data-play-item", "c02", { timeout: 20_000 }); + await expect(block(page, "c02")).toBeFocused(); + await page.keyboard.press("Space"); + await expect(page.locator("[data-ws-viewer]")).toHaveAttribute("data-play-state", "paused"); + + // A letter jumps to the item it starts: w is `window`; Enter opens its form, the clip filled in; Esc returns. + await page.keyboard.press("Shift+F10"); + await expect(menu).toBeVisible(); + await page.keyboard.press("w"); + await expect(menu.locator('[data-ws-menu-verb="window"]')).toBeFocused(); + await page.keyboard.press("Enter"); + const form = palette(page).locator('[data-cli-form="window"]'); + await expect(form).toBeVisible(); + await expect(form.locator('[data-cli-arg="project"] input')).toHaveValue(P); + await expect(form.locator('[data-cli-arg="clip"] input')).toHaveValue("c02"); + await expect(form.locator("[data-cli-line]")).toHaveText(`node umtool/bin/umtool.mjs window ${P} c02`); + await shot(page, "block-menu-keyboard-form"); + await page.keyboard.press("Escape"); + await expect(palette(page)).toBeHidden(); + await expect(block(page, "c02")).toBeFocused(); + + // The context-menu key opens it too; Tab closes it. + await page.keyboard.press("ContextMenu"); + await expect(menu).toBeVisible(); + await page.keyboard.press("Tab"); + await expect(menu).toHaveCount(0); + expect(manifestText()).toBe(original); +}); + +test("a variant twin: Remove takes the entry on screen, never its twin; a twin the view cannot place is not moved or removed", async ({ page }) => { + const original = manifestText(); + type Entry = Record<string, unknown> & { id: string }; + const m = JSON.parse(original) as { timeline: Entry[] }; + // c03's full-cut twin BEFORE it: the first entry with the id is not the one the default cut plays. + const i3 = m.timeline.findIndex((e) => e.id === "c03"); + m.timeline.splice(i3, 0, { ...m.timeline[i3], variant: "full", quote: "the full cut's twin" }); + // c04 turned by `variants` (the view makes it anew: it says no place for it) with a full-cut twin of its own. + const i4 = m.timeline.findIndex((e) => e.id === "c04"); + const c04 = m.timeline[i4]; + m.timeline.splice(i4, 1, { ...c04, variant: "full", quote: "c04's full twin" }, { ...c04, variants: { sourced: { quote: "turned" } } }); + const written = JSON.stringify(m, null, 2) + "\n"; + writeFileSync(path.join(DIR, "video.manifest.json"), written); + try { + expect(order()).toBe("c01 c02 p-5 k01 c03 c03 c04 c04"); + await open(page); + + await block(page, "c03").click({ button: "right" }); + const menu = menuOf(page, "c03"); + await expect(menu.locator('[data-ws-menu-action="remove"]')).not.toHaveAttribute("aria-disabled", "true"); + await menu.locator('[data-ws-menu-action="remove"]').click(); + // The one on screen left; its twin (the full cut's) stays. + await expect.poll(() => manifest().timeline.filter((e) => e.id === "c03").map((e) => (e as { variant?: string }).variant ?? "").join(","), { timeout: 15_000 }).toBe("full"); + await expect(page.locator("[data-ws-undo-said]")).toContainText("Removed c03"); + await page.locator("[data-ws-undo]").click(); + await expect.poll(manifestText, { timeout: 15_000 }).toBe(written); + // The strip has read the undo back (c03 is on it again) before c04's menu is asked for. + await expect(block(page, "c03")).toBeVisible(); + + // c04: no place of its own, its id twice -- never guessed at. + await block(page, "c04").click({ button: "right" }); + const twin = menuOf(page, "c04"); + for (const a of ["remove", "move-left", "move-right"]) { + await expect(twin.locator(`[data-ws-menu-action="${a}"]`)).toHaveAttribute("aria-disabled", "true"); + await expect(twin.locator(`[data-ws-menu-action="${a}"]`)).toHaveAttribute("title", "this entry has a twin — use the Cut tab"); + } + // Pressed anyway (past Playwright's own aria-disabled wait): nothing happens. + await twin.locator('[data-ws-menu-action="remove"]').click({ force: true }); + await page.keyboard.press("Escape"); + await expect(twin).toHaveCount(0); + expect(manifestText()).toBe(written); + } finally { + writeFileSync(path.join(DIR, "video.manifest.json"), original); + } +}); + +test("links from a Rumble clip's menu writes the draft (target project): the run's end is heard, and ONE Undo takes it back", async ({ page }) => { + const R = "reports/block-menus-rumble-fixture"; + const file = path.join(DIR, "..", "block-menus-rumble-fixture", "video.manifest.json"); + const before = readFileSync(file, "utf8"); + const siteVideo = () => (JSON.parse(readFileSync(file, "utf8")) as { timeline: { id: string; siteVideo?: string }[] }).timeline.find((e) => e.id === "r01")?.siteVideo ?? null; + await page.goto(urls.workspaceHref(R)); + await expect(page.locator("[data-ws-strip] [data-ws-block]")).toHaveCount(3); + await expect(page.locator("dialog[data-jump][data-ready]")).toBeAttached({ timeout: 60_000 }); + await expect(page.locator("[data-workspace]")).toHaveAttribute("data-ws-token", /./); + const token = await page.locator("[data-workspace]").getAttribute("data-ws-token"); + + await block(page, "r01").click({ button: "right" }); + await menuOf(page, "r01").locator('[data-ws-menu-verb="links"]').click(); + const form = palette(page).locator('[data-cli-form="links"]'); + await expect(form.locator('[data-cli-arg="--embed-ids"] input')).toBeChecked(); + await expect(form.locator('[data-cli-arg="--clips"] input')).toHaveValue("r01"); + await form.locator("[data-cli-run]").click(); + await expect(form.locator("[data-cli-state]")).toHaveAttribute("data-cli-state", "done", { timeout: 90_000 }); + expect(siteVideo()).toBe("v7emb01"); + await page.keyboard.press("Escape"); + await expect(palette(page)).toBeHidden(); + // The palette told the workspace (by the project's id): it has the draft's new token before Undo is pressed. + await expect(page.locator("[data-workspace]")).not.toHaveAttribute("data-ws-token", token ?? "", { timeout: 15_000 }); + await page.locator("[data-ws-undo]").click(); + await expect(page.locator("[data-ws-undo-said]")).toContainText("Undone"); + await expect.poll(() => readFileSync(file, "utf8"), { timeout: 15_000 }).toBe(before); +}); + +test("at phone width (390): the menu opens inside the window, its ⋯ toggles it, and it works", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 844 }); + await open(page); + // The inspector is a sheet at the bottom: folded, the strip is in reach. + await page.locator("[data-ws-sheet-toggle]").click(); + await expect(page.locator("[data-ws-inspector]")).toHaveAttribute("data-ws-sheet", "closed"); + await block(page, "c02").scrollIntoViewIfNeeded(); + const more = page.locator('[data-ws-block-more="c02"]'); + await more.click(); + const menu = menuOf(page, "c02"); + await expect(menu).toBeVisible(); + const box = await menu.boundingBox(); + expect(box!.x).toBeGreaterThanOrEqual(0); + expect(box!.x + box!.width).toBeLessThanOrEqual(390); + expect(box!.y).toBeGreaterThanOrEqual(0); + expect(box!.y + box!.height).toBeLessThanOrEqual(844); + await shot(page, "block-menu-phone"); + // Its ⋯ again closes it (a toggle), and opens it again. + await more.click(); + await expect(menu).toHaveCount(0); + await more.click(); + await expect(menu).toBeVisible(); + await menu.locator('[data-ws-menu-action="play"]').click(); + await expect(menu).toHaveCount(0); + await expect(page.locator("[data-workspace]")).toHaveAttribute("data-ws-selected", "c02"); +}); + +test("what is typed in a block's form survives the palette's page context arriving after it", async ({ page }) => { + await open(page); + let release: () => void = () => {}; + const gate = new Promise<void>((r) => (release = r)); + await page.route(/\/api\/cli\?path=/, async (route) => { + await gate; + await route.continue(); + }); + await block(page, "c01").click({ button: "right" }); + await menuOf(page, "c01").locator('[data-ws-menu-verb="timeline teaser-insert"]').click(); + const form = palette(page).locator('[data-cli-form="timeline teaser-insert"]'); + await expect(form).toBeVisible(); + await form.locator('[data-cli-arg="--line"] textarea').fill("Typed before the context"); + // Now the page's context answers. + const answered = page.waitForResponse(/\/api\/cli\?path=/); + release(); + await answered; + await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))); + await expect(form.locator('[data-cli-arg="--line"] textarea')).toHaveValue("Typed before the context"); + await expect(form.locator('[data-cli-arg="--after"] input')).toHaveValue("c01"); + await page.keyboard.press("Escape"); + await page.unroute(/\/api\/cli\?path=/); +}); + +test("a ⌘K run that only reads the draft keeps the workspace's Redo; one that writes it ends the Redo", async ({ page }) => { + const original = manifestText(); + await open(page); + const redo = page.locator("[data-ws-redo]"); + const said = page.locator("[data-ws-undo-said]"); + + // An edit, undone: the Redo is there. + await block(page, "p-5").click({ button: "right" }); + await menuOf(page, "p-5").locator('[data-ws-menu-action="move-right"]').click(); + await expect.poll(order, { timeout: 15_000 }).toBe("c01 c02 k01 p-5 c03 c04"); + await expect(said).toContainText("Moved p-5"); + await page.locator("[data-ws-undo]").click(); + await expect.poll(manifestText, { timeout: 15_000 }).toBe(original); + await expect(said).toContainText("Undone"); + await expect(redo).toBeEnabled(); + + // ⌘K `show` (it reads the project): its end is announced, the workspace reads the draft again -- unchanged -- + // and the Redo stays, with its word. + await page.keyboard.press("Control+k"); + await expect(palette(page)).toBeVisible(); + await page.keyboard.type(">show"); + await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "cmd:show", { timeout: 30_000 }); + await page.keyboard.press("Enter"); + const show = palette(page).locator('[data-cli-form="show"]'); + await expect(show.locator('[data-cli-arg="project"] input')).toHaveValue(P); + const reread = page.waitForResponse((r) => r.url().includes("/api/report/timeline?project=") && r.request().method() === "GET", { timeout: 60_000 }); + await show.locator("[data-cli-run]").click(); + await expect(show.locator("[data-cli-state]")).toHaveAttribute("data-cli-state", "done", { timeout: 90_000 }); + await reread; + await page.keyboard.press("Escape"); + await expect(palette(page)).toBeHidden(); + await expect(redo).toBeEnabled(); + await expect(said).toContainText("Undone"); + // …and it still works. + await redo.click(); + await expect.poll(order, { timeout: 15_000 }).toBe("c01 c02 k01 p-5 c03 c04"); + await expect(said).toContainText("Redone"); + await page.locator("[data-ws-undo]").click(); + await expect.poll(manifestText, { timeout: 15_000 }).toBe(original); + await expect(redo).toBeEnabled(); + + // A run that writes the draft (a card from c01's menu): the Redo is gone. + await block(page, "c01").click({ button: "right" }); + await menuOf(page, "c01").locator('[data-ws-menu-verb="timeline teaser-insert"]').click(); + const form = palette(page).locator('[data-cli-form="timeline teaser-insert"]'); + await form.locator('[data-cli-arg="--line"] textarea').fill("Ends the redo"); + await form.locator("[data-cli-run]").click(); + await expect(form.locator("[data-cli-state]")).toHaveAttribute("data-cli-state", "done", { timeout: 90_000 }); + await page.keyboard.press("Escape"); + await expect(palette(page)).toBeHidden(); + await expect(redo).toBeDisabled({ timeout: 15_000 }); + await expect(page.locator("[data-ws-strip] [data-ws-block]")).toHaveCount(7); + await page.locator("[data-ws-undo]").click(); + await expect.poll(manifestText, { timeout: 15_000 }).toBe(original); +}); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -2203,10 +2203,38 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out writeFileSync(rpFile, JSON.stringify(rpM, null, 2) + "\n"); } +// A BLOCK'S MENU (block-menus.spec.ts, umtool redesign L8b, WRITES): the workspace fixture's cut, its own copy -- +// c01 c02 p-5 k01 c03 c04 (k01 a chapter card) -- the spec inserts a card from c01's menu, moves and removes +// blocks, and undoes each. +{ + const { dir: bmDir } = makePlayCutFixture({ + reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), + name: "block-menus-fixture", title: "The Block Menus Fixture", video: "vid1", + }); + const bmFile = path.join(bmDir, "video.manifest.json"); + const bmM = JSON.parse(readFileSync(bmFile, "utf8")); + bmM.render.chrome.factcheck.verdicts.CORROBORATED.tallyLabel = "Seized"; + bmM.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(bmFile, JSON.stringify(bmM, 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 }); +// A BLOCK'S MENU on a Rumble cut (block-menus.spec.ts, L8b, WRITES): inspector-rumble-fixture copied whole -- r01 +// cites a URL-slug folder, so `links --embed-ids --clips r01` from its menu writes the draft (an undo point). +{ + const { cpSync } = await import("node:fs"); + const bmr = path.join(reports, "block-menus-rumble-fixture"); + cpSync(path.join(reports, "inspector-rumble-fixture"), bmr, { recursive: true }); + const f = path.join(bmr, "video.manifest.json"); + writeFileSync(f, JSON.stringify({ ...JSON.parse(readFileSync(f, "utf8")), slug: "block-menus-rumble-fixture", title: "The Block Menus Rumble Fixture" }, null, 2) + "\n"); +} + // One undo stack (undo.spec.ts, WRITES): two trims a moment apart, then two undos -- its own copy. { const { dir: unDir } = makePlayCutFixture({ diff --git a/umtool/e2e/review-pass.spec.ts b/umtool/e2e/review-pass.spec.ts @@ -193,6 +193,12 @@ test("by clicking, both ways: Versions ▾ → Review on v1 is v1's pass, where await page.locator("body").press("e"); await page.locator("body").press("Control+z"); await page.locator("body").press("k"); + // The strip's writers too (L8b's, gated on the same flag): Alt+→ on a block, a drag onto another, its menu. + await page.locator('[data-ws-block="c01"]').click(); + await page.locator("body").press("Alt+ArrowRight"); + await page.locator('[data-ws-block="c01"]').dragTo(page.locator('[data-ws-block="c02"]')); + await page.locator('[data-ws-block="c02"]').click({ button: "right" }); + await expect(page.locator('[role="menu"]')).toHaveCount(0); await page.waitForTimeout(600); await expect(page.locator("[data-cut-app-bench]")).toHaveCount(0); expect(disk()).toEqual(before); diff --git a/umtool/e2e/workspace.spec.ts b/umtool/e2e/workspace.spec.ts @@ -102,7 +102,8 @@ test("a clip block: the inspector is the bench's window and word strip; a nudged await expect(page.locator("[data-ws-redo]")).toBeEnabled(); await page.locator("[data-ws-redo]").click(); await expect.poll(manifestText, { timeout: 15_000 }).toBe(nudged); - // The redo's answer read back (the page is not busy any more): a key pressed while a write is in flight is dropped. + // The file is written before the page has read the redo back (it is busy until then, and a key pressed meanwhile is + // dropped): wait for its word first. await expect(page.locator("[data-ws-undo-said]")).toContainText("Redone"); await page.locator("body").press("Control+z"); await expect.poll(manifestText, { timeout: 15_000 }).toBe(original); diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -25,6 +25,14 @@ // confirm { what, when?, unless? }: it does something with no undo point (deletes, evicts, kills): // the form asks a second press ("Yes, <what>") and POST /api/cli wants `confirm: true`; // `when` the arg names that make it so (any given), `unless` those that make it a dry run +// blocks the workspace strip's block kinds whose menu offers it (lane block-menus L8b): BLOCK_KINDS below, +// the manifest's entry types plus the intro. A row with no `blocks` is never in a block menu. +// fromBlock { <arg name>: "<template>" | true }: what the block fills in when its menu opens the form -- +// a template of BLOCK_FIELDS (`"{id}"`, `"{cutStart}-{cutEnd}"`; any field the block lacks leaves the +// arg empty), or `true` for a boolean flag. The project arg is the block's project, always. +// verbs.test.mjs: every arg that names a block (`context` clip or post) has one. +// nav the block menu OPENS a page for it instead of a form ("ingredient": the life-cycle page), filled +// from the same fromBlock; ⌘K still offers its form // // An arg: { name, type, required?, choices?, default?, help?, repeat?, context? } // name "--flag" is a flag; anything else is a positional @@ -79,11 +87,16 @@ const window_ = () => [num("--at", { help: "the window's start, s" }), num("--du // ---- the rows ------------------------------------------------------------------- const form = (verb, target, summary, args, extra = {}) => ({ verb, summary, target, ui: "form", args, ...extra }); +/** A row's block menu (lane block-menus L8b): the block kinds that offer it, and what each fills in. */ +const B = (blocks, fromBlock, more = {}) => ({ blocks, fromBlock, ...more }); const none = (verb, target, summary, reason, extra = {}) => ({ verb, summary, target, ui: "none", reason, args: [], ...extra }); /** The heavy verbs' default time limit in the queue is its own (12 h); a job's is 15 min unless a row says. */ const Q = { queue: true }; +/** The block kinds that are timeline entries (the intro is not: the build prepends it). */ +const ENTRIES = ["clip", "post", "teaser", "card", "video"]; + const REJECT_WHYS = ["not-matching", "wrong-speaker", "irrelevant", "repeats", "weak", "privacy", "other"]; /** @type {ReadonlyArray<Record<string, any>>} */ @@ -99,7 +112,7 @@ export const VERBS = Object.freeze([ project(), bool("--fix", "rewrite the dead links it knows the fix for"), bool("--embed-ids", "no check: every clip citing a Rumble URL-slug folder gets the embed id the archive serves (siteVideo), one write to the draft"), opt("--clips", { help: "with --embed-ids: a,b (none: every such clip)" }), dry(), - ], { timeoutMin: 30 }), + ], { timeoutMin: 30, ...B(["clip"], { "--embed-ids": true, "--clips": "{id}" }) }), // The inspector's twins (umtool redesign L6): the project's provenance, its title, a still at second N. form("provenance ls", "project", "the project's provenance: site origin, channel slug, channel, link policy", [project()], { shape: "provenance <project> ls" }), form("provenance set", "draft", "the project's site origin, channel slug and channel name (\"\" removes one)", [ @@ -110,7 +123,7 @@ export const VERBS = Object.freeze([ ]), form("still", "project", "one frame of a clip's fetched window at a source second, into shots/", [ project(), clip(), num("--at", { required: true, help: "the SOURCE second" }), takeOpt({ help: "a take's (version's) clip" }), - ], { confirm: { what: "write the frame into shots/ (a file, no undo point; a still of the same second is replaced)" } }), + ], { confirm: { what: "write the frame into shots/ (a file, no undo point; a still of the same second is replaced)" }, ...B(["clip"], { clip: "{id}", "--at": "{second}" }) }), form("still ls", "project", "the pictures in the project's shots/", [project()], { shape: "still <project> ls" }), // ---- the cast ---- @@ -136,8 +149,8 @@ export const VERBS = Object.freeze([ form("speaker-check", "project", "which named voice each clip is (speaker-check.json)", [ project(), many("--clip", { repeat: true, help: "clip ids, one per line (none: every clip)" }), bool("--list", "list the named voices"), opt("--set", { help: "Name=<clip>,<channel>/<id>,channel:<slug>" }), opt("--remove", { help: "a voice's name" }), - ], { ...Q, confirm: { what: "remove that named voice from speakers.json", when: ["--remove"] } }), - form("quote-check", "project", "is each clip's quote in the seconds it plays", [project(), opt("--clips", { help: "a,b (none: every clip)" }), num("--pad"), bool("--status", "the rows as they stand")], Q), + ], { ...Q, confirm: { what: "remove that named voice from speakers.json", when: ["--remove"] }, ...B(["clip"], { "--clip": "{id}" }) }), + form("quote-check", "project", "is each clip's quote in the seconds it plays", [project(), opt("--clips", { help: "a,b (none: every clip)" }), num("--pad"), bool("--status", "the rows as they stand")], { ...Q, ...B(["clip"], { "--clips": "{id}" }) }), form("check-joins", "project", "do a rendered take's post joins carry on", [project(), takeOpt({ required: true, help: "the rendered take" }), bool("--all", "every post-to-post boundary"), num("--limit")], Q), form("link-policy", "draft", "cite via site X, these channels direct", [ project(), opt("--via", { help: "a site id or its https address" }), opt("--direct", { help: "channel slugs, a,b" }), bool("--clear"), bool("--fix", "rewrite the clips that break it"), @@ -162,7 +175,7 @@ export const VERBS = Object.freeze([ bool("--quote-ruled"), bool("--no-quote-ruled"), opt("--move-stamp", { help: "first | nearest | <s>" }), bool("--clear-stamp"), pick("--move-mute", ["nearest"]), bool("--clear-mute"), many("--gap", { repeat: true, help: "FROM-TO source seconds, one per line" }), num("--gap-remove"), opt("--gaps", { help: "A-B,C-D (the whole list)" }), takeOpt(), - ]), + ], B(["clip"], { clip: "{id}" })), form("walk", "project", "the clip bench's walk: clips in walk order, verdicts, fetched", [project(), takeOpt({ help: "walk a take (a draft too)" }), bool("--all", "every fetched clip")]), // The workspace's review pass (umtool redesign L7b, lib/report/reviewPass.mjs): a clip's Keep / Fix is its walk // verdict (`window --verdict`); a post's or a card's lives in review-pass.json. @@ -174,8 +187,8 @@ export const VERBS = Object.freeze([ project(), pick("verdict", ["like", "maybe", "no", "clear"], { required: true }), opt("--note", { type: "text", help: "the verdict's note" }), ], { shape: "review-pass <project> verdict <verdict>" }), form("present", "project", "present mode's address and slides", [project(), takeOpt({ help: "that take's cut (default the latest)" }), bool("--cut", "the manifest alone"), bool("--public", "as a public page would carry it")]), - form("set", "draft", "a clip's knobs: claim, marks, audio, blur, fx …", [project(), clip(), pairs({ help: "key=value, one per line (claim.at=190.2, audio.gain=-3, `key=` clears)" }), opt("--mark", { help: "the mark the claim.* keys set" }), takeOpt()]), - form("intro", "draft", "the intro the cut opens on (render.intro)", [project(), pairs({ required: false, help: "key=value, one per line (style=boot-dark, seconds=4); none: print it" }), bool("--off", "take the intro off"), takeOpt({ help: "a version: --off opens it on no intro, --on on the cut's" }), bool("--on")]), + form("set", "draft", "a clip's knobs: claim, marks, audio, blur, fx …", [project(), clip(), pairs({ help: "key=value, one per line (claim.at=190.2, audio.gain=-3, `key=` clears)" }), opt("--mark", { help: "the mark the claim.* keys set" }), takeOpt()], B(["clip"], { clip: "{id}" })), + form("intro", "draft", "the intro the cut opens on (render.intro)", [project(), pairs({ required: false, help: "key=value, one per line (style=boot-dark, seconds=4); none: print it" }), bool("--off", "take the intro off"), takeOpt({ help: "a version: --off opens it on no intro, --on on the cut's" }), bool("--on")], B(["intro"], {})), form("look", "draft", "the cut's knobs: mode, deck, fact-check stamps, variants …", [project(), pairs({ help: "key=value, one per line (mode=basic, deck.markerLayout=stagger)" }), many("--unset", { repeat: true, help: "render.<key>, a legacy key dropped" })]), form("migrate", "draft", "the manifest's settings into the video modules' homes", [project(), dry()]), form("variants", "project", "make the encode ladder of a build", [project(), takeOpt({ help: "a take's build" }), bool("--list", "what was made, and the sync report")], Q), @@ -201,7 +214,7 @@ export const VERBS = Object.freeze([ form("export", "project", "the posting artifacts, or one clip clean into exports/", [ project(), clip({ required: false, help: "one clip (none: --format)" }), pick("--format", ["toc-bbcode", "toc-markdown", "description", "chapters"]), opt("--variant"), opt("--first"), num("--context", { help: "± s, as recorded" }), bool("--raw", "the fetched window as recorded"), num("--from"), num("--to"), bool("--fetch", "ask the editor first for what is not on disk"), takeOpt(), - ], Q), + ], { ...Q, ...B(["clip"], { clip: "{id}" }) }), form("check-sources", "corpus", "the re-check chain, printed", [many("projects", { help: "one per line (none: the never-checked and > 30 d)" })]), // ---- notes ---- @@ -295,7 +308,7 @@ export const VERBS = Object.freeze([ project(), dry(), bool("--wait", "follow the editor's jobs"), bool("--status", "the last run's jobs"), bool("--body", "print the request body"), opt("--reason"), opt("--refetch", { help: "clipId,clipId: evict those windows first" }), opt("--refetch-video", { help: "<slug>/<id>" }), takeOpt({ help: "a take's clips" }), ], { timeoutMin: 60, confirm: { what: "evict those cached windows, then fetch them again", when: ["--refetch", "--refetch-video"], unless: ["--dry-run"] } }), - form("prep", "project", "the bench's excerpts and waveforms, before the walk", [project(), opt("--clips", { help: "a,b" }), bool("--wait", "here, until done"), bool("--status"), takeOpt()], Q), + form("prep", "project", "the bench's excerpts and waveforms, before the walk", [project(), opt("--clips", { help: "a,b" }), bool("--wait", "here, until done"), bool("--status"), takeOpt()], { ...Q, ...B(["clip"], { "--clips": "{id}" }) }), form("prune", "project", "takes' work files freed by policy (a dry run unless --yes)", [ project({ required: false, help: "one project (none: --all)" }), bool("--all"), opt("--take", { help: "X[,Y]" }), bool("--anyway"), num("--keep"), opt("--older-than", { help: "3d" }), opt("--idle-work", { help: "3d" }), bool("--versions", "whole superseded takes"), opt("--idle"), opt("--grace"), bool("--yes", "free them (else a dry run)"), @@ -315,12 +328,12 @@ export const VERBS = Object.freeze([ form("clips segments", "project", "the narrated-video spans auto-scope finds", [project()]), form("refresh", "corpus", "re-fetch an article's scope: the plan, and --yes starts it", [arg("article", { required: false }), num("--iteration"), bool("--no-fetch"), bool("--yes", "start it"), bool("--check", "the daily suggestion check, now"), bool("--force")], { confirm: { what: "start the refresh: an editor job that fetches the article's scope again", when: ["--yes"] } }), form("clip", "corpus", "quick clip: one moment to a basic-mode mp4 and its share line", [arg("spec", { help: "<channel>/<video>@<start>-<end>" }), pick("--snap", ["words"]), opt("--title"), name("--site"), name("--folder")], Q), - form("share", "project", "a clip's share line", [project(), clip({ required: false, help: "the clip (none: the first)" }), takeOpt({ help: "the take's cut" }), name("--site")]), + form("share", "project", "a clip's share line", [project(), clip({ required: false, help: "the clip (none: the first)" }), takeOpt({ help: "the take's cut" }), name("--site")], B(["clip"], { clip: "{id}" })), // ---- the cut's structure ---- ...timeline(), - form("scenes", "project", "scene cuts and black spans in a clip's fetched window", [project(), clip(), num("--black-min"), num("--threshold"), num("--pix-th"), num("--pad"), num("--from"), num("--to")]), + form("scenes", "project", "scene cuts and black spans in a clip's fetched window", [project(), clip(), num("--black-min"), num("--threshold"), num("--pix-th"), num("--pad"), num("--from"), num("--to")], B(["clip"], { clip: "{id}" })), // ---- posts ---- ...posts(), @@ -330,7 +343,7 @@ export const VERBS = Object.freeze([ form("candidates add", "project", "an agent's proposal(s) as candidates", [project(), arg("proposal", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })], { shape: "candidates <project> add <proposal>" }), form("ingredient", "corpus", "one recording's (or clip window's) life cycle: found to published", [ arg("recording", { type: "ref", help: "<channel>/<video> (a Rumble folder slug or its embed id)" }), opt("--window", { help: "<from>-<to>: one clip window" }), bool("--used-in", "every project clip that cuts from it, alone"), - ]), + ], B(["clip"], { recording: "{channel}/{video}" }, { nav: "ingredient" })), none("help", "corpus", "every command", "prints the command list: the palette's Commands are the same list"), ]); @@ -344,7 +357,7 @@ function trailerBeats() { const n = (o = {}) => num("n", { required: true, help: "the beat's number", ...o }); return [ tb("ls", "a reel's beats against its limit", []), - tb("add", "a clip beat", [clip(), arg("span", { required: false, help: "<from>-<to> source s (none: the whole cut)" }), num("--at", { help: "its place" }), opt("--label"), takeOpt({ help: "the take it is anchored to" })]), + tb("add", "a clip beat", [clip(), arg("span", { required: false, help: "<from>-<to> source s (none: the whole cut)" }), num("--at", { help: "its place" }), opt("--label"), takeOpt({ help: "the take it is anchored to" })], B(["clip"], { clip: "{id}" })), tb("add-raw", "a beat of master seconds", [num("at", { required: true }), num("dur", { required: true }), num("--at", { help: "its place" }), opt("--label")]), tb("set", "beat n's source seconds", [n(), arg("span", { help: "<from>-<to>" }), opt("--label")]), tb("gap", "seconds cut out of beat n's middle", [n(), pick("op", ["add", "remove", "clear"], { required: true }), arg("value", { required: false, help: "<from>-<to> (add), a second (remove)" })]), @@ -383,13 +396,13 @@ function timeline() { arg("spec", { help: "<channel>/<video>@<start>-<end>, post:<channel>/<postId> or post-json:<json>" }), opt("--after", { help: "an entry id, or - (the start)" }), num("--to-section"), opt("--group"), opt("--id"), num("--section"), bool("--lock"), bool("--lock-end"), opt("--title"), opt("--stream-title"), opt("--date", { help: "YYYY-MM-DD" }), opt("--quote", { type: "text" }), num("--cite"), opt("--cite-url"), takeOpt(), - ]), - tl("move", "draft", "an entry to an index", [id(), num("--to", { required: true, help: "its place after the move (0 first)" }), takeOpt()]), + ], B(ENTRIES, { "--after": "{id}" })), + tl("move", "draft", "an entry to an index", [id(), num("--to", { required: true, help: "its place after the move (0 first)" }), takeOpt()], B(ENTRIES, { id: "{id}" })), tl("place", "draft", "entries before another (Play's drag)", [ids(), opt("--before", { required: true, help: "an entry id, or - (the end)" }), num("--section")]), - tl("remove", "draft", "an entry out of the cut", [id(), num("--at", { help: "which of an id's twins" }), takeOpt()]), - tl("duplicate", "draft", "an entry twice", [id(), num("--at")]), - tl("reject", "draft", "an entry rejected and removed, on the record", [id(), pick("why", REJECT_WHYS, { required: true }), opt("--note", { type: "text" })]), - tl("wrong-speaker", "draft", "an entry removed: the wrong speaker", [id(), opt("--correction", { type: "text" })]), + tl("remove", "draft", "an entry out of the cut", [id(), num("--at", { help: "which of an id's twins" }), takeOpt()], B(ENTRIES, { id: "{id}" })), + tl("duplicate", "draft", "an entry twice", [id(), num("--at")], B(["clip", "post"], { id: "{id}" })), + tl("reject", "draft", "an entry rejected and removed, on the record", [id(), pick("why", REJECT_WHYS, { required: true }), opt("--note", { type: "text" })], B(["clip"], { id: "{id}" })), + tl("wrong-speaker", "draft", "an entry removed: the wrong speaker", [id(), opt("--correction", { type: "text" })], B(["clip"], { id: "{id}" })), tl("import-item", "draft", "items of another project into the draft, their files linked in", [ many("refs", { required: true, item: "ref", help: "<project>:<item>[,<item>…], one per line" }), opt("--after"), opt("--before"), opt("--as"), dry(), ]), @@ -397,22 +410,22 @@ function timeline() { tl("restore", "draft", "un-reject: a removed clip back as it was, at its old place", [arg("id", { help: "the removed clip's id (timeline removed lists them)" })]), tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })]), tl("post-remove", "draft", "a post out of the cut", [arg("id", { context: "post" })]), - tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })]), + tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })], B(["teaser"], { id: "{id}" })), tl("teaser-insert", "draft", "a teaser or closing card inserted (default at the end)", [ pick("--at", ["end", "start"]), opt("--after", { help: "an entry's id: after it" }), opt("--before", { help: "an entry's id: before it" }), opt("--id"), num("--beat"), many("--line", { repeat: true, help: "its lines, one per line (the first its title)" }), opt("--lines-json", { type: "json", atFile: true, help: "the lines as JSON, each a string or {text, break?, hold?} (@file: from a terminal)" }), - ]), + ], B(ENTRIES, { "--after": "{id}" })), 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"])]), + tl("section-add", "draft", "a new section after a clip", [opt("--after", { required: true }), opt("--label"), opt("--color"), pick("--level", ["1", "2"])], B(["clip"], { "--after": "{id}" })), tl("section-boundary", "draft", "a section boundary dragged", [marker(), opt("--after", { required: true })]), tl("section-remove", "draft", "a section's marker removed", [marker()]), tl("section-set", "draft", "a section's label, colour or level", [marker(), opt("--label"), opt("--color"), pick("--level", ["1", "2"])]), - tl("split", "draft", "a clip in two at a source second", [id(), num("second", { required: true })]), - tl("flash-forward", "draft", "a tight copy of a span elsewhere, as a repeat", [id(), arg("span", { help: "<from>-<to>" }), opt("--after"), num("--to-section"), bool("--start"), bool("--move", "the span leaves the clip"), opt("--quote"), opt("--id")]), + tl("split", "draft", "a clip in two at a source second", [id(), num("second", { required: true })], B(["clip"], { id: "{id}", second: "{second}" })), + tl("flash-forward", "draft", "a tight copy of a span elsewhere, as a repeat", [id(), arg("span", { help: "<from>-<to>" }), opt("--after"), num("--to-section"), bool("--start"), bool("--move", "the span leaves the clip"), opt("--quote"), opt("--id")], B(["clip"], { id: "{id}", span: "{cutStart}-{cutEnd}" })), tl("order", "draft", "the cut's order in one write", [many("order", { required: true, item: "id", help: "entry ids in order, one per line" })]), tl("threads", "draft", "the cut's conversations (and --write gathers them)", [bool("--write"), opt("--conversation")]), tl("groups", "project", "the claim groups, by section", []), @@ -426,13 +439,15 @@ function timeline() { file("src", { pass: "relative", help: "a video file of the project, relative to its directory" }), num("--from"), num("--to"), pick("--fit", ["contain", "cover"]), num("--bass"), num("--gain"), opt("--enter", { help: "cut | <out>,<in>" }), num("--hold"), opt("--title"), opt("--id"), opt("--after"), dry(), takeOpt(), ]), - tl("set-video", "draft", "a video entry's knobs", [id(), pairs({ help: "from= to= fit= audio.gain= …, one per line" }), takeOpt()]), + tl("set-video", "draft", "a video entry's knobs", [id(), pairs({ help: "from= to= fit= audio.gain= …, one per line" }), takeOpt()], B(["video"], { id: "{id}" })), ]; } function posts() { const p = (sub, target, summary, args, extra = {}) => form(`posts ${sub}`, target, summary, [project(), ...args], extra); const items = () => many("items", { help: "post item ids, one per line" }); + const POST_ITEM = B(["post"], { item: "{id}" }); + const POST_ITEMS = B(["post"], { items: "{id}" }); return [ p("add", "draft", "a post card from the posts archive", [arg("post", { help: "<archive-channel>/<postId>" }), opt("--attach", { help: "a clip id" }), opt("--flag"), opt("--author"), opt("--id"), bool("--thread"), num("--crop"), dry()]), p("set", "draft", "the Posts table's writer: thread, hide, attach, crop", [arg("post", { context: "post", help: "x-<postId> or the bare id" }), pairs({ help: "thread=on, hide=off, attach=<clip>|auto, crop=<px>|off" })]), @@ -440,21 +455,21 @@ function posts() { many("--channel", { repeat: true, required: true, item: "name", help: "posts channels, one per line" }), opt("--since"), opt("--until"), bool("--own"), bool("--with-media"), pick("--replies", ["include", "only", "exclude"]), pick("--order", ["chrono", "reverse"]), num("--limit"), opt("--after"), dry(), ]), - p("set-item", "draft", "a post item's knobs", [item(), pairs({ help: "hold=4, layout=grid, media.0.start=2 …" }), inTake()]), + p("set-item", "draft", "a post item's knobs", [item(), pairs({ help: "hold=4, layout=grid, media.0.start=2 …" }), inTake()], POST_ITEM), p("narrate", "draft", "a post item's narration: script, takes, pick, approve, mix", [ item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"), opt("--voice"), opt("--engine"), num("--speed"), num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"), bool("--thread", "with --take: a thread read"), opt("--parents"), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"), num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"), dry(), pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(), - ], Q), + ], { ...Q, ...POST_ITEM }), p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, allowAt: true, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }), p("voices", "draft", "the voice map a thread read uses", [pick("op", ["ls", "set", "remove"], { required: true }), arg("handle", { required: false, help: "a handle, or *" }), arg("voice", { required: false })], { shape: "posts voices <project> <op>" }), - p("fit", "draft", "narrated posts' videos cut to their best part", [items(), bool("--all"), num("--linger"), dry()], Q), + p("fit", "draft", "narrated posts' videos cut to their best part", [items(), bool("--all"), num("--linger"), dry()], { ...Q, ...POST_ITEMS }), p("fx", "draft", "a post item's word zooms, captions, clock, slams", [ item(), pick("op", ["ls", "add", "set", "remove"], { required: true }), arg("what", { required: false, help: "add: word-zoom | caption | clock | slam; set/remove: n" }), { name: "flags", type: "flagpairs", help: "match=…, text=…, at=…, one per line (each --key value)" }, inTake(), - ], { shape: "posts fx <project> <item> <op>" }), + ], { shape: "posts fx <project> <item> <op>", ...POST_ITEM }), p("clock", "draft", "the cut's clock default", [pick("mode", ["on", "off", "default"]), opt("--zone", { help: "an IANA zone" })]), p("progress", "draft", "the cut's progress bar default", [pick("mode", ["auto", "on", "off", "default"])]), p("avatar", "draft", "an author's picture on the cards", [arg("handle", { required: false, allowAt: true }), file("image", { required: false, literals: ["off"], help: "a picture file of the project, or off" })]), @@ -463,16 +478,16 @@ function posts() { p("slurs", "draft", "the slur filter", [pick("op", ["ls", "on", "off", "level", "visual", "voice", "add", "except", "remove", "edges"], { required: true }), arg("value", { required: false }), bool("--off")], { shape: "posts slurs <project> <op>" }), p("context", "draft", "each post item's context from its capture", [dry()]), p("repeats", "project", "the attachments played more than once", [pick("--match", ["id", "file", "audio"])]), - p("combo", "draft", "the combo badge's knobs (the cut's, or one item's)", [arg("item", { required: false, context: "post" }), pairs({ required: false, help: "on=on, label=COMBO … (an item: off | on | auto first)" })]), - p("attach", "draft", "a capture's media onto post items that carry none", [items(), bool("--all"), dry()]), + p("combo", "draft", "the combo badge's knobs (the cut's, or one item's)", [arg("item", { required: false, context: "post" }), pairs({ required: false, help: "on=on, label=COMBO … (an item: off | on | auto first)" })], POST_ITEM), + p("attach", "draft", "a capture's media onto post items that carry none", [items(), bool("--all"), dry()], POST_ITEMS), p("scenes", "draft", "the media scenes (and the cut's on/off)", [pick("mode", ["on", "off"])]), p("picture-reply", "draft", "the cut's picture-only rule", [pairs({ required: false, help: "on=on, image=2, min=1.5 …" }), inTake()]), - p("roles", "draft", "a read's pieces, stored or inferred", [items(), bool("--write"), opt("--set", { help: "<n>=<role>,…" }), inTake()]), + p("roles", "draft", "a read's pieces, stored or inferred", [items(), bool("--write"), opt("--set", { help: "<n>=<role>,…" }), inTake()], POST_ITEMS), p("reread", "draft", "a read re-joined, re-timed, paused or a phrase re-voiced", [ item(), opt("--without", { help: "parent:0,quoted …" }), opt("--drop-parts"), bool("--drop-urls"), opt("--tempo-for"), num("--tempo"), opt("--parts"), pick("--stretch", ["atempo", "rubberband"]), bool("--yell-caps"), num("--yell-gain"), pick("--yell-style", ["raise", "shout", "loud"]), opt("--pause"), opt("--target"), opt("--revoice"), opt("--say"), opt("--voice"), num("--xfade"), opt("--splice"), dry(), inTake(), - ], Q), - p("yell", "draft", "the caps he wrote, yelled in the read", [items(), bool("--all"), num("--yell-gain"), pick("--yell-style", ["raise", "shout", "loud"]), dry()], Q), + ], { ...Q, ...POST_ITEM }), + p("yell", "draft", "the caps he wrote, yelled in the read", [items(), bool("--all"), num("--yell-gain"), pick("--yell-style", ["raise", "shout", "loud"]), dry()], { ...Q, ...POST_ITEMS }), ]; } @@ -490,8 +505,72 @@ export function formVerbs() { queue: !!r.queue, confirm: r.confirm ?? null, args: r.args, + // Where the words and positionals go (`timeline <project> insert`): the page's Copy as CLI line is built with + // it, as the server's argv is -- without it the line named the project after the verb's words. + ...(r.shape ? { shape: r.shape } : {}), + ...(r.blocks ? { blocks: r.blocks, fromBlock: r.fromBlock ?? {} } : {}), + ...(r.nav ? { nav: r.nav } : {}), })); } +// ---- a block's menu (lane block-menus L8b) ---------------------------------------------- + +/** + * The block kinds of the workspace strip: the manifest's entry types a menu offers verbs for, and the intro + * (render.intro, which is not a timeline entry). A `card` is a chapter card (a section's card, the build's + * `type: "card"`), a `teaser` a teaser or closing card, a `video` a project file played full frame. + */ +export const BLOCK_KINDS = Object.freeze(["clip", "post", "teaser", "card", "intro", "video"]); + +/** + * What a block tells its menu, the fields a `fromBlock` template may name: + * project the project's id id the block's id (a timeline entry's, "intro") + * type its kind (BLOCK_KINDS) at its index in the timeline (none: the intro) + * start end the clip's extent, source s cutStart cutEnd the cut it renders, source s + * second the source second under the playhead when it is in this clip, else its cut's start + * video the clip's recording id channel the channel it cuts from + */ +export const BLOCK_FIELDS = Object.freeze(["project", "id", "type", "at", "start", "end", "cutStart", "cutEnd", "second", "video", "channel"]); + +/** The navigation rows: the page a block menu opens for one (lib/hrefs builds it from the filled values). */ +export const BLOCK_NAVS = Object.freeze(["ingredient"]); + +/** The rows a block of `kind` offers, in the registry's order (ui "form" only). */ +export const blockVerbs = (kind) => formVerbs().filter((r) => r.blocks?.includes(kind)); + +const TEMPLATE_FIELD = /\{([A-Za-z]+)\}/g; +const fieldWord = (v) => (typeof v === "number" ? (Number.isFinite(v) ? String(Math.round(v * 1000) / 1000) : null) : typeof v === "string" && v.trim() ? v : null); + +/** One fromBlock rule filled from a block: its value, or undefined when the block lacks a field it names. */ +export function fillFromBlock(rule, block) { + if (rule === true) return true; + if (typeof rule !== "string") return undefined; + let missing = false; + const out = rule.replace(TEMPLATE_FIELD, (_, f) => { + const w = fieldWord(block?.[f]); + if (w === null) missing = true; + return w ?? ""; + }); + return missing ? undefined : out; +} + +/** + * A row's form values from a block: the project, then every `fromBlock` rule the block can fill. A rule it + * cannot fill (a field the block lacks) leaves its arg to the person. + */ +export function fromBlockValues(row, block) { + /** @type {Record<string, string | boolean>} */ + const values = {}; + for (const a of row.args ?? []) if (a.type === "project" && a.name === "project" && fieldWord(block?.project)) values.project = block.project; + for (const [name, rule] of Object.entries(row.fromBlock ?? {})) { + const v = fillFromBlock(rule, block); + if (v !== undefined) values[name] = v; + } + return values; +} + +/** The fields a template names. */ +export const templateFields = (rule) => (typeof rule === "string" ? [...rule.matchAll(TEMPLATE_FIELD)].map((m) => m[1]) : []); + /** The top-level command a row belongs to: its first word. */ export const commandOf = (verb) => String(verb).split(" ")[0]; diff --git a/umtool/lib/cli/verbs.test.mjs b/umtool/lib/cli/verbs.test.mjs @@ -8,7 +8,7 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { VERBS, formVerbs, verbRow, commandOf } from "./verbs.mjs"; +import { VERBS, formVerbs, verbRow, commandOf, BLOCK_KINDS, BLOCK_FIELDS, BLOCK_NAVS, blockVerbs, fromBlockValues, templateFields } from "./verbs.mjs"; import { GROUPS } from "./groups.mjs"; import { CLI_MD, DOCS_BEGIN, DOCS_END, usageText, withVerbsSection } from "./docs.mjs"; import { buildArgv, cliLine, confirmOf, pathArgsOf, shellQuote, synopsis } from "./argv.mjs"; @@ -115,6 +115,15 @@ test("every row is a form or says why it is not, and its args make sense", () => } assert.ok(formVerbs().every((r) => !("usage" in r) && !("reason" in r)), "the page's list carries no prose"); assert.equal(formVerbs().length, VERBS.filter((r) => r.ui === "form").length); + // The page builds its Copy as CLI line from these rows: the same argv the server builds from the registry's. + const sample = { project: "reports/p", id: "c01", "--to": "2", "--after": "c01", item: "p-5", op: "ls", settings: "a=1", ruling: "keep", clip: "c01", marker: "m1", gid: "g1", n: "1", span: "1-2", second: "3" }; + for (const r of formVerbs()) { + // What the page builds the line from IS the registry's: its shape and its args, whole. + assert.deepEqual(r.shape, verbRow(r.verb).shape, `\`${r.verb}\`: the page's row has the registry's shape`); + assert.deepEqual(r.args, verbRow(r.verb).args, `\`${r.verb}\`: the page's row has the registry's args`); + const vals = Object.fromEntries(r.args.filter((a) => a.name in sample).map((a) => [a.name, sample[a.name]])); + assert.deepEqual(buildArgv(r, vals), buildArgv(verbRow(r.verb), vals), `\`${r.verb}\`: the page's line is the command that runs`); + } }); test("cli.md's generated section is current (node umtool/lib/cli/docs.mjs rewrites it)", () => { @@ -288,6 +297,69 @@ test("confirm: a row that deletes, evicts or kills asks, when its args make it s assert.ok(formVerbs().find((r) => r.verb === "prune")?.confirm, "the page knows to ask"); }); +// A BLOCK'S MENU (lane block-menus L8b): which verbs the workspace strip's block menus offer is data on the rows. +test("block menus: every `blocks` names a block kind, every block-naming arg has a fromBlock, the forms build", () => { + const kinds = new Set(BLOCK_KINDS); + const fields = new Set(BLOCK_FIELDS); + const withBlocks = VERBS.filter((r) => "blocks" in r || "fromBlock" in r || "nav" in r); + assert.ok(withBlocks.length >= 20, "the block menus offer the clip, post, card and intro verbs"); + for (const r of withBlocks) { + const at = `\`${r.verb}\``; + assert.equal(r.ui, "form", `${at}: a block menu opens a form -- a row with no form has no blocks`); + assert.ok(Array.isArray(r.blocks) && r.blocks.length, `${at}: blocks is a non-empty list`); + for (const k of r.blocks) assert.ok(kinds.has(k), `${at}: blocks names "${k}", not a block kind (${BLOCK_KINDS.join(", ")})`); + assert.ok(r.fromBlock && typeof r.fromBlock === "object", `${at}: blocks needs a fromBlock`); + const args = new Map(r.args.map((a) => [a.name, a])); + for (const [name, rule] of Object.entries(r.fromBlock)) { + const a = args.get(name); + assert.ok(a, `${at}: fromBlock fills ${name}, an arg it does not have`); + assert.ok(a.type !== "project", `${at}: the project is the block's, always -- not a fromBlock rule`); + if (rule === true) assert.equal(a.type, "boolean", `${at}: fromBlock ${name}: true is for a flag`); + else { + assert.equal(typeof rule, "string", `${at}: fromBlock ${name} is a template or true`); + assert.ok(templateFields(rule).length, `${at}: fromBlock ${name} names a field ({id} …)`); + for (const f of templateFields(rule)) assert.ok(fields.has(f), `${at}: fromBlock ${name} names {${f}}, not a block field (${BLOCK_FIELDS.join(", ")})`); + } + } + // Every id arg it needs: an arg that names a block (the clip, the post item) is filled from the block. + for (const a of r.args) { + if (a.context === "clip" || a.context === "post") assert.ok(a.name in r.fromBlock, `${at}: ${a.name} names a block -- give it a fromBlock rule`); + } + if (r.nav) assert.ok(BLOCK_NAVS.includes(r.nav), `${at}: nav "${r.nav}" is not a page the menu opens (${BLOCK_NAVS.join(", ")})`); + // What a block fills in is a form the server would take, but for what the person still has to give. + for (const k of r.blocks) { + const block = { project: "reports/p", id: k === "intro" ? "intro" : "x01", type: k, at: k === "intro" ? null : 2, start: 1, end: 9.5, cutStart: 2, cutEnd: 8.25, second: 3.5, video: "vid1", channel: "chan" }; + const values = fromBlockValues(r, block); + if (r.args.some((a) => a.type === "project" && a.name === "project")) assert.equal(values.project, "reports/p", `${at}: the block's project`); + const built = buildArgv(r, values); + if (!built.ok) { + const a = args.get(built.field); + assert.ok(a?.required && !(built.field in r.fromBlock), `${at} on a ${k}: ${built.error} (a value a block filled in is refused)`); + } + } + } + // Each kind's menu: the verbs that act on it, and none that do not. + const menu = (k) => blockVerbs(k).map((r) => r.verb); + for (const v of ["window", "set", "timeline remove", "timeline move", "quote-check", "links", "timeline teaser-insert", "still", "ingredient"]) assert.ok(menu("clip").includes(v), `a clip's menu offers ${v}`); + for (const v of ["posts set-item", "posts narrate", "timeline teaser-insert", "timeline move"]) assert.ok(menu("post").includes(v), `a post's menu offers ${v}`); + assert.ok(!menu("clip").some((v) => v.startsWith("posts ")), "a clip's menu has no post verbs"); + assert.ok(!menu("post").includes("window") && !menu("post").includes("set"), "a post's menu has no clip verbs"); + assert.deepEqual(menu("intro"), ["intro"]); + assert.ok(menu("teaser").includes("timeline teaser")); + // The fills, as the menu opens them. + assert.deepEqual(fromBlockValues(verbRow("timeline teaser-insert"), { project: "reports/p", id: "c01", at: 0 }), { project: "reports/p", "--after": "c01" }); + assert.deepEqual(fromBlockValues(verbRow("still"), { project: "reports/p", id: "c01", second: 12.3456 }), { project: "reports/p", clip: "c01", "--at": "12.346" }); + assert.deepEqual(fromBlockValues(verbRow("timeline flash-forward"), { project: "p", id: "c01", cutStart: 1.5 }), { project: "p", id: "c01" }, "a field the block lacks leaves the arg empty"); + assert.deepEqual(fromBlockValues(verbRow("ingredient"), { project: "p", id: "c01", channel: "chan", video: "vid1" }), { recording: "chan/vid1" }); + assert.deepEqual(fromBlockValues(verbRow("links"), { project: "p", id: "c01" }), { project: "p", "--embed-ids": true, "--clips": "c01" }); + // A move's place is the person's: its own index would be a no-op the CLI refuses ("already at N"). + assert.deepEqual(fromBlockValues(verbRow("timeline move"), { project: "p", id: "c01", at: 3 }), { project: "p", id: "c01" }); + // The page's list carries them (the palette and the menu read one table). + assert.deepEqual(formVerbs().find((r) => r.verb === "window")?.blocks, ["clip"]); + assert.equal(formVerbs().find((r) => r.verb === "ingredient")?.nav, "ingredient"); + assert.equal(formVerbs().find((r) => r.verb === "show")?.blocks, undefined); +}); + test("confineToProject: a file of the project by its realpath, symlinks followed", async () => { const tmp = mkdtempSync(path.join(os.tmpdir(), "umtool-confine-")); try { diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -175,6 +175,11 @@ export async function playViewWith(project, { take = null, bare = false, postFor return { error: e instanceof Error ? e.message : String(e) }; } } + // Each entry's place in the manifest's own timeline, by identity: the variant selection keeps an entry's object + // (one it turns -- `variants` -- and the intro it prepends are new, so they carry none). The workspace's writers + // name an entry by it, so a variant twin is never taken for the one on screen (lane block-menus L8b). + const sourceAt = new WeakMap(); + (manifest.timeline ?? []).forEach((e, i) => e && typeof e === "object" && sourceAt.set(e, i)); const selected = selectVariant(manifest, DEFAULT_VARIANT); const render = selected.render ?? {}; // THE BASIC OUTPUT MODE (render.mode, report-to-video basic.mjs): Play plays what the basic render cuts -- @@ -247,6 +252,7 @@ export async function playViewWith(project, { take = null, bare = false, postFor // The combo counter (post-combo.mjs): a post item that repeats an earlier one's attachment carries its badge // (`postCombo`: its count, which attachment, the knobs, whether it shows), counted over the cut played. for (const e of entries) if (e.type === "post" && combos[e.id]) Object.assign(e, { postCombo: combos[e.id] }); + entries.forEach((e, i) => Object.assign(e, { timelineAt: sourceAt.get(timeline[i]) ?? null })); // The counter (the deck's tally): each stamp's landing second and count on // the estimate's clock, and each verdict's word -- the reel strip's // staircase before (or without) the chrome's own schedule.