Archilyzer · Source

archilyzer

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

commit 03b34e2724e0a5a2d7f54f58713c7b46c37ca75a
parent 299f95183b275faa5ebc1b6d49cf19eabcb4970b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 19:34:59 -0500

umtool: the inspector panels, mounted in the Cut tab and Play (redesign L6)

components/projects/inspector/: TitleInspector, ProvenanceInspector (with the link policy), TeaserInspector
(insert a teaser or closing card; with a block, its lines and beat), LedgerInspector (date, scope, value,
basis, source), PostItemInspector (the excerpt picked by selecting the post's words -- excerptPick.mjs --,
media on/off and sound, Use my recording), LinksInspector (Use the published embed id, per row and for
every dead Rumble row), StillInspector + Play's Still button. Each takes {project, block?} and writes
through its route, so L7 mounts it unchanged. Cut tab: Options "Project", a post row's and a teaser row's
Edit, "Insert a teaser or closing card" beside the intro row.

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

Diffstat:
Aumtool/components/projects/inspector/LedgerInspector.tsx | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/LinksInspector.tsx | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/PostItemInspector.tsx | 247+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/ProvenanceInspector.tsx | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/StillInspector.tsx | 101+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/TeaserInspector.tsx | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/TitleInspector.tsx | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/inspector/shared.tsx | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/report/CutTab.tsx | 32++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PlayCut.tsx | 11+++++++++++
Aumtool/lib/report/excerptPick.mjs | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/excerptPick.test.mjs | 43+++++++++++++++++++++++++++++++++++++++++++
12 files changed, 1293 insertions(+), 0 deletions(-)

diff --git a/umtool/components/projects/inspector/LedgerInspector.tsx b/umtool/components/projects/inspector/LedgerInspector.tsx @@ -0,0 +1,248 @@ +"use client"; + +import { useCallback, useEffect, useMemo, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select, Textarea } from "@/components/ui/field"; +import { InspectorFrame, SaidLine, call, refusal, type InspectorProps, type Said } from "./shared"; + +// A MEASURE LEDGER's ROWS (umtool redesign L6, item 3; agents added and fixed them with jq this week): the rows the +// instruments draw from, each with its date, scope (a track), form, value (a number, or a regime and its event on +// a regime track), basis (the phrase that settles the scope) and source (src, channel/video, cite) -- added, +// changed or removed through POST /api/report/ledger, the ledger CLI's checks word for word, one undo point each. +// `umtool ledger <p> add|set|rm` is the twin. With `block` (a timeline entry's id): the rows pinned to it, and a +// new row pinned to it. + +type Track = { key: string; label: string; role: string; regimes: string[] | null }; +type Schema = { + unit: string; tracks: Track[]; forms: string[]; regimes: { key: string; label: string }[]; + fields: { key: string; label: string; kind: string; options: unknown[] | null }[]; + events: string[]; promiseForms: string[]; outcomes: string[]; scopeConfidence: string[]; valueKinds: string[]; +}; +type Row = Record<string, unknown> & { id: string }; +type View = { kind: "measure" | "headcount" | null; schema: Schema | null; schemaError: string | null; total: number; rows: Row[]; entries: string[]; token: string | null }; + +/** The keys the form shows, in order: what a row needs, then its source. */ +const BASE_KEYS = ["id", "date", "scope", "population", "value", "event", "scopeBasis", "label", "quote", "src", "channel", "video", "cite", "entryId"] as const; +const REQUIRED = new Set(["id", "date", "scope", "population", "scopeBasis"]); +const PAGE = 40; + +const textOf = (v: unknown) => (v === undefined || v === null ? "" : Array.isArray(v) ? v.join("|") : String(v)); + +export default function LedgerInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [editing, setEditing] = useState<string | null>(null); // a row id, or "" for a new row + const [form, setForm] = useState<Record<string, string>>({}); + const [filter, setFilter] = useState(""); + const [shown, setShown] = useState(PAGE); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const load = useCallback(async () => { + const q = new URLSearchParams({ project, ...(block ? { entry: block } : {}) }); + const { ok, j } = await call<View>(`/api/report/ledger?${q.toString()}`); + if (ok) setView(j); + return ok ? j : null; + }, [project, block]); + useEffect(() => { + void load(); + }, [load]); + const declared = view?.schema?.fields ?? []; + const keys = useMemo(() => [...BASE_KEYS, ...declared.map((f) => f.key)], [declared]); + const rows = useMemo(() => { + const all = [...(view?.rows ?? [])].sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")) || a.id.localeCompare(b.id)); + const f = filter.trim().toLowerCase(); + return f ? all.filter((r) => [r.id, r.date, r.scope, r.population, r.display, r.label, r.quote].some((v) => String(v ?? "").toLowerCase().includes(f))) : all; + }, [view, filter]); + if (!view || !view.kind) return null; + if (view.kind !== "measure" || !view.schema) { + return ( + <InspectorFrame kind="ledger" title={`Ledger — ${view.total} rows`}> + <p className="m-0 text-muted">{view.schemaError ?? "This ledger is not a measure ledger (ledgerSchema.kind \"measure\"): its rows are written by its own tools."}</p> + </InspectorFrame> + ); + } + const s = view.schema; + const track = s.tracks.find((t) => t.key === form.scope) ?? null; + const regimeTrack = track?.role === "regime"; + + const open = (id: string | null) => { + setSaid(null); + if (id === null) { + setEditing(null); + return; + } + if (id === "") { + const today = new Date().toISOString().slice(0, 10); + setForm({ id: "", date: today, scope: s.tracks[0]?.key ?? "", population: s.forms[0] ?? "", ...(block ? { entryId: block } : {}) }); + } else { + const r = view.rows.find((x) => x.id === id); + setForm(Object.fromEntries(keys.map((k) => [k, textOf(r?.[k])]))); + } + setEditing(id); + }; + const set = (k: string, v: string) => { + setSaid(null); + setForm((f) => ({ ...f, [k]: v })); + }; + const save = async () => { + setBusy(true); + setSaid(null); + try { + let body: Record<string, unknown>; + if (editing === "") { + const row = Object.fromEntries(Object.entries(form).filter(([, v]) => v.trim() !== "").map(([k, v]) => [k, v.trim()])); + body = { project, token: view.token, op: "add", row }; + } else { + const was = view.rows.find((x) => x.id === editing); + const patch: Record<string, string> = {}; + const unset: string[] = []; + for (const k of keys) { + if (k === "id") continue; + const now = (form[k] ?? "").trim(); + if (now === textOf(was?.[k])) continue; + if (now === "" && !REQUIRED.has(k)) unset.push(k); + else patch[k] = now; + } + if (!Object.keys(patch).length && !unset.length) { + setSaid({ ok: true, text: "Nothing changed." }); + return; + } + body = { project, token: view.token, op: "set", id: editing, patch, unset }; + } + const { ok, status, j } = await call<{ row?: Row }>("/api/report/ledger", { method: "POST", body: JSON.stringify(body) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setEditing(null); + setSaid({ ok: true, text: `${editing === "" ? "Added" : "Saved"} ${j.row?.id ?? ""}: ${String(j.row?.display ?? "")} — in the draft.` }); + router.refresh(); + } finally { + setBusy(false); + } + }; + const remove = async (id: string) => { + setBusy(true); + setSaid(null); + try { + const { ok, status, j } = await call("/api/report/ledger", { method: "POST", body: JSON.stringify({ project, token: view.token, op: "rm", id }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setEditing(null); + setSaid({ ok: true, text: `Removed ${id}.` }); + router.refresh(); + } finally { + setBusy(false); + } + }; + + const input = (k: string, label: string, hint?: string, extra?: React.ComponentProps<"input">) => ( + <Field key={k} label={label} hint={hint}> + <Input data-ledger-field={k} value={form[k] ?? ""} onChange={(e) => set(k, e.target.value)} {...extra} /> + </Field> + ); + const select = (k: string, label: string, options: { value: string; label: string }[], blank?: string) => ( + <Field key={k} label={label}> + <Select data-ledger-field={k} value={form[k] ?? ""} onChange={(e) => set(k, e.target.value)}> + {blank !== undefined && <option value="">{blank}</option>} + {options.map((o) => ( + <option key={o.value} value={o.value}> + {o.label} + </option> + ))} + </Select> + </Field> + ); + const regimes = regimeTrack ? (track?.regimes ?? s.regimes.map((r) => r.key)) : []; + const editor = editing !== null && ( + <div data-ledger-editor={editing || "new"} className="mt-2 rounded border border-[var(--color-line)] px-2 py-2"> + <div className="grid gap-2 sm:grid-cols-4"> + {editing === "" ? input("id", "Id", "a letter, then letters, digits . : - _") : <Field label="Id"><span className="font-mono text-[12.5px]">{editing}</span></Field>} + {input("date", "Date", "YYYY-MM-DD")} + {select("scope", "Scope", s.tracks.map((t) => ({ value: t.key, label: `${t.label} (${t.key})` })))} + {select("population", "Form", s.forms.map((f) => ({ value: f, label: f })))} + {regimeTrack + ? select("value", "Value", regimes.map((k) => ({ value: k, label: s.regimes.find((r) => r.key === k)?.label ?? k })), "—") + : input("value", "Value", s.unit ? `a number in ${s.unit}` : "a number")} + {regimeTrack ? select("event", "Event", s.events.map((e) => ({ value: e, label: e })), "—") : null} + {select("entryId", "Pinned to", view.entries.map((id) => ({ value: id, label: id })), "no entry")} + {input("cite", "Cite", "source second")} + {input("channel", "Channel", "source channel slug")} + {input("video", "Video", "source video id")} + <div className="sm:col-span-2">{input("src", "Source", "what it is: a title @ a time")}</div> + <div className="sm:col-span-4">{input("scopeBasis", "Basis", "the phrase that settles the scope (never defaulted)")}</div> + <div className="sm:col-span-2">{input("label", "Label")}</div> + <div className="sm:col-span-2"> + <Field label="Quote"> + <Textarea data-ledger-field="quote" rows={2} value={form.quote ?? ""} onChange={(e) => set("quote", e.target.value)} /> + </Field> + </div> + {declared.map((f) => + f.options ? select(f.key, f.label, f.options.map((o) => ({ value: String(o), label: String(o) })), "—") : input(f.key, f.label, `declared (${f.kind})`), + )} + </div> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="go" data-ledger-save={editing || "new"} disabled={busy} onClick={() => void save()}> + {editing === "" ? "Add row" : "Save row"} + </Button> + <Button type="button" size="sm" variant="quiet" data-ledger-cancel="" disabled={busy} onClick={() => open(null)}> + Cancel + </Button> + {editing !== "" && ( + <Button type="button" size="sm" variant="quiet" className="ml-auto" data-ledger-remove={editing} disabled={busy} onClick={() => void remove(editing)}> + Remove row + </Button> + )} + </div> + </div> + ); + return ( + <InspectorFrame + kind="ledger" + title={`Ledger — ${block ? `${view.rows.length} pinned to ${block} · ` : ""}${view.total} rows`} + aside={ + <> + <Input data-ledger-filter="" placeholder="filter" className="h-7 w-[12rem]" value={filter} onChange={(e) => { setFilter(e.target.value); setShown(PAGE); }} /> + <Button type="button" size="sm" variant="outline" data-ledger-add="" onClick={() => open("")}> + Add a row + </Button> + </> + } + > + {editing === "" && editor} + <ul className="flex max-h-[320px] flex-col gap-0.5 overflow-y-auto"> + {rows.slice(0, shown).map((r) => ( + <li key={r.id} data-ledger-row={r.id} className="flex flex-col"> + <div className="flex flex-wrap items-baseline gap-2 text-[12px]"> + <span className="w-[4.5rem] font-mono text-text">{r.id}</span> + <span className="num font-mono text-[11.5px] text-muted">{String(r.date ?? "")}</span> + <span className="text-[11.5px] text-text-2">{String(r.scope ?? "")} · {String(r.population ?? "")}</span> + <span className="font-mono text-[12px]">{String(r.display ?? r.value ?? "—")}</span> + {r.entryId ? <span className="text-[11px] text-muted">@{String(r.entryId)}</span> : null} + <span className="min-w-0 flex-1 truncate text-[11.5px] text-muted">{String(r.label ?? "")}</span> + <Button type="button" size="sm" variant={editing === r.id ? "pressed" : "quiet"} data-ledger-edit={r.id} onClick={() => open(editing === r.id ? null : r.id)}> + {editing === r.id ? "Close" : "Edit"} + </Button> + </div> + {editing === r.id && editor} + </li> + ))} + </ul> + {rows.length > shown && ( + <Button type="button" size="sm" variant="quiet" data-ledger-more="" onClick={() => setShown((n) => n + PAGE)}> + {rows.length - shown} more + </Button> + )} + <div className="mt-1.5"> + <SaidLine said={said} testid="ledger-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/LinksInspector.tsx b/umtool/components/projects/inspector/LinksInspector.tsx @@ -0,0 +1,91 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { InspectorFrame, SaidLine, call, refusal, type InspectorProps, type Said } from "./shared"; + +// THE RUMBLE CITE FIX (umtool redesign L6, item 5; 4 and 8 Nov: a Rumble clip's QR named the URL-slug folder the +// corpus keeps it under, and the archive serves the EMBED id -- 15/15 dead on quartering-midterms): each clip of +// the cut that cites such a folder, with its published embed id read from the folder's metadata through L1's one +// mapping, and "Use the published embed id" -- per row, and once for every dead Rumble row (every row when no +// check has run). It writes `siteVideo` (a citeUrl naming the folder moves with it): POST /api/report/embed-ids, +// one write, one undo point. No network; `umtool links <p>` checks the sites, `umtool links <p> --embed-ids` is +// this panel's twin. With `block`, only that clip's row. + +type Row = { clip: string; channel: string | null; video: string; siteVideo: string; url: string | null; fixedUrl: string | null; citeUrl: string | null; state: string }; +type View = { rows: Row[]; checkedAt: string | null; token: string | null }; + +export default function LinksInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const load = useCallback(async () => { + const { ok, j } = await call<View>(`/api/report/embed-ids?project=${encodeURIComponent(project)}`); + if (ok) setView(j); + return ok ? j : null; + }, [project]); + useEffect(() => { + void load(); + }, [load]); + if (!view) return null; + const rows = block ? view.rows.filter((r) => r.clip === block) : view.rows; + const dead = rows.filter((r) => r.state === "dead"); + const allOf = dead.length ? dead : rows; + const use = async (clips: string[]) => { + setBusy(true); + setSaid(null); + try { + const { ok, status, j } = await call<{ fixed?: { clip: string; siteVideo: string }[] }>("/api/report/embed-ids", { method: "POST", body: JSON.stringify({ project, token: view.token, clips }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + const fixed = j.fixed ?? []; + setSaid({ ok: true, text: `${fixed.map((f) => `${f.clip} → ${f.siteVideo}`).join(", ")}: saved to the draft — Check links on the Overview reads the site again.` }); + router.refresh(); + } finally { + setBusy(false); + } + }; + return ( + <InspectorFrame + kind="links" + title={`Rumble cites — ${rows.length} clip${rows.length === 1 ? "" : "s"} naming a folder id`} + aside={ + rows.length > 1 ? ( + <Button type="button" size="sm" variant="go" data-embed-use-all={allOf.length} disabled={busy} onClick={() => void use(allOf.map((r) => r.clip))}> + {dead.length ? `Use the published embed id for all ${dead.length} dead` : `Use the published embed id for all ${rows.length}`} + </Button> + ) : null + } + > + {rows.length === 0 ? ( + <p className="m-0 text-muted" data-embed-none=""> + Every clip names the id its archive serves{view.checkedAt ? ` (links last checked ${view.checkedAt.slice(0, 16).replace("T", " ")})` : ""}. + </p> + ) : ( + <ul className="flex flex-col gap-1"> + {rows.map((r) => ( + <li key={r.clip} data-embed-row={r.clip} data-embed-state={r.state} className="flex flex-wrap items-baseline gap-2"> + <span className="font-mono text-text">{r.clip}</span> + <span className="font-mono text-[11.5px] text-muted"> + {r.channel ?? "?"}/{r.video} → <span className="text-text-2">{r.siteVideo}</span> + </span> + <span className={r.state === "dead" ? "text-[11.5px] text-[var(--color-bad)]" : "text-[11.5px] text-muted"}>{r.state === "unchecked" ? "not checked" : r.state}</span> + <Button type="button" size="sm" variant="outline" className="ml-auto" data-embed-use={r.clip} disabled={busy} onClick={() => void use([r.clip])} title={r.fixedUrl ?? undefined}> + Use the published embed id + </Button> + </li> + ))} + </ul> + )} + <div className="mt-1.5"> + <SaidLine said={said} testid="embed-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/PostItemInspector.tsx b/umtool/components/projects/inspector/PostItemInspector.tsx @@ -0,0 +1,247 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "@/lib/report/excerptPick.mjs"; +import { InspectorFrame, SaidLine, call, refusal, type InspectorProps, type Said } from "./shared"; + +// A POST ITEM (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item excerpt=…` and `posts narrate +// --recording` by hand), with `block` the item's id: +// THE EXCERPT select words of the post and Add them: the selection snapped to whole words, merged with the +// spans already picked, settled where the build will find each one (excerptPick.mjs), saved as +// `entry.excerpt` -- verbatim spans in the post's order, read joined with " … ", the card still +// showing the whole post with the rest dimmed (POST /api/report/post-item {op: "set"}). +// ITS MEDIA each attachment shown or not (off removes it from the item, its file kept; a file of the post the +// item does not carry can be put back on) and a video's sound on or off. +// MY RECORDING a sound file of your own read of it, kept as a recorded take and picked (the multipart POST +// /api/report/post-narration: trimmed, levelled; `umtool posts narrate <p> <item> --recording <file> +// --no-clean --no-convert` is the twin). + +type Range = { start: number; end: number }; +type View = { + id: string; post: string | null; author: string | null; handle: string | null; text: string; + excerpt: string[] | null; ranges: Range[] | null; excerptErrors: string[]; + media: { i: number; src: string | null; kind: string | null; mute: boolean; seconds: number | null; audio: boolean }[]; + files: string[]; + narration: { takes: { i: number; file: string; engine: string | null; voice: string | null; seconds: number | null }[]; picked: number | null; off: boolean }; + token: string | null; +}; + +/** A (node, offset) of the selection as a character offset into `root`'s text. */ +function offsetIn(root: HTMLElement, node: Node, off: number): number | null { + if (!root.contains(node)) return null; + const r = document.createRange(); + r.selectNodeContents(root); + r.setEnd(node, off); + return r.toString().length; +} + +export default function PostItemInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [missing, setMissing] = useState<string | null>(null); + const [ranges, setRanges] = useState<Range[]>([]); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const [file, setFile] = useState<File | null>(null); + const textRef = useRef<HTMLDivElement>(null); + const fileRef = useRef<HTMLInputElement>(null); + const load = useCallback(async () => { + if (!block) return null; + const { ok, j } = await call<View>(`/api/report/post-item/inspector?${new URLSearchParams({ project, id: block }).toString()}`); + if (!ok) { + setMissing(j.error ?? "not a post item"); + return null; + } + setMissing(null); + setView(j); + setRanges(j.ranges ?? []); + return j; + }, [project, block]); + useEffect(() => { + void load(); + }, [load]); + if (!block) return null; + if (missing) return <InspectorFrame kind="post-item" title={`Post item ${block}`}><p className="m-0 text-muted">{missing}</p></InspectorFrame>; + if (!view) return null; + + const saved = view.ranges ?? []; + const dirty = JSON.stringify(ranges) !== JSON.stringify(saved); + const write = async (url: string, body: Record<string, unknown>, ok: string) => { + setBusy(true); + setSaid(null); + try { + const r = await call(url, { method: "POST", body: JSON.stringify({ project, token: view.token, id: view.id, ...body }) }); + if (!r.ok) { + setSaid({ ok: false, text: refusal(r.j, r.status) }); + if (r.j.stale) await load(); + return false; + } + await load(); + setSaid({ ok: true, text: ok }); + router.refresh(); + return true; + } finally { + setBusy(false); + } + }; + + const addSelection = () => { + const sel = window.getSelection(); + const root = textRef.current; + if (!sel || sel.rangeCount === 0 || !root) return; + const range = sel.getRangeAt(0); + const a = offsetIn(root, range.startContainer, range.startOffset); + const b = offsetIn(root, range.endContainer, range.endOffset); + if (a === null || b === null) { + setSaid({ ok: false, text: "select words inside the post's text first" }); + return; + } + const r = snapToWords(view.text, a, b); + if (!r) { + setSaid({ ok: false, text: "the selection holds no words" }); + return; + } + setSaid(null); + setRanges((rs) => settleRanges(view.text, addRange(rs, r))); + sel.removeAllRanges(); + }; + const saveExcerpt = () => { + const spans = spansOf(view.text, ranges); + // The build's own rule, checked before the write: each span found where it was picked. + const back = rangesOf(view.text, spans); + if (spans.length && JSON.stringify(back) !== JSON.stringify(ranges)) { + setSaid({ ok: false, text: "a span could not be placed where it was picked — clear and pick again" }); + return; + } + void write("/api/report/post-item", { op: "set", patch: { excerpt: spans.length ? spans : null } }, spans.length ? `Excerpt saved to the draft: ${spans.length} span${spans.length === 1 ? "" : "s"}, read joined with " … ".` : "Excerpt cleared: the whole post is read."); + }; + const keepMyRecording = async () => { + if (!file) return; + setBusy(true); + setSaid(null); + try { + const form = new FormData(); + form.set("project", project); + form.set("id", view.id); + form.set("label", "operator"); + form.append("part", file, file.name); + form.append("text", (view.excerpt?.length ? view.excerpt.join(" … ") : view.text).slice(0, 4000)); + form.append("para", "0"); + form.set("note", `my recording (${file.name})`); + const r = await fetch("/api/report/post-narration", { method: "POST", body: form }); + const j = (await r.json().catch(() => ({}))) as { take?: { file: string; seconds?: number }; gain?: number; error?: string }; + if (!r.ok || !j.take) { + setSaid({ ok: false, text: j.error ?? `HTTP ${r.status}` }); + return; + } + setFile(null); + if (fileRef.current) fileRef.current.value = ""; + await load(); + setSaid({ ok: true, text: `Kept as ${j.take.file}${typeof j.take.seconds === "number" ? ` (${j.take.seconds.toFixed(1)} s` : " ("}${typeof j.gain === "number" ? `, levelled ${j.gain >= 0 ? "+" : ""}${j.gain} dB)` : ")"} and picked.` }); + router.refresh(); + } finally { + setBusy(false); + } + }; + + const pieces = piecesOf(view.text, ranges); + const picked = view.narration.picked !== null ? view.narration.takes[view.narration.picked] : null; + return ( + <InspectorFrame kind="post-item" title={`Post item ${view.id}${view.author ? ` — ${view.author}` : ""}${view.handle ? ` @${view.handle}` : ""}`}> + <div className="grid gap-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]"> + <div className="flex min-w-0 flex-col gap-1.5" data-post-excerpt={view.excerpt?.length ?? 0}> + <span className="micro">excerpt — select words, then Add</span> + <div + ref={textRef} + data-post-text="" + className="max-h-[220px] overflow-y-auto whitespace-pre-wrap rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1.5 text-[12.5px] leading-relaxed text-text-2 select-text" + > + {pieces.map((p) => + p.picked ? ( + <mark key={p.start} data-excerpt-piece={p.start} className="rounded-[2px] bg-[color-mix(in_srgb,var(--signal)_30%,transparent)] text-text"> + {p.text} + </mark> + ) : ( + <span key={p.start} className={ranges.length ? "opacity-60" : undefined}> + {p.text} + </span> + ), + )} + </div> + {ranges.length > 0 && ( + <ol className="flex flex-col gap-0.5"> + {spansOf(view.text, ranges).map((s, i) => ( + <li key={`${ranges[i].start}`} data-excerpt-span={i} className="flex items-baseline gap-2 text-[11.5px]"> + <span className="min-w-0 flex-1 truncate">&ldquo;{s}&rdquo;</span> + <Button type="button" size="sm" variant="quiet" data-excerpt-span-remove={i} onClick={() => setRanges((rs) => rs.filter((_, k) => k !== i))}> + Remove + </Button> + </li> + ))} + </ol> + )} + {view.excerptErrors.length > 0 && <p className="m-0 text-[11.5px] text-[var(--color-bad)]">{view.excerptErrors.join("; ")}</p>} + <div className="flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="outline" data-excerpt-add="" onMouseDown={(e) => e.preventDefault()} onClick={addSelection}> + Add the selection + </Button> + <Button type="button" size="sm" variant="go" data-excerpt-save="" disabled={busy || !dirty} onClick={saveExcerpt}> + {ranges.length ? "Save excerpt" : "Save: read it whole"} + </Button> + <Button type="button" size="sm" variant="quiet" data-excerpt-clear="" disabled={busy || !ranges.length} onClick={() => setRanges([])}> + Clear + </Button> + <Button type="button" size="sm" variant="quiet" data-excerpt-revert="" disabled={busy || !dirty} onClick={() => setRanges(saved)}> + Revert + </Button> + </div> + </div> + <div className="flex min-w-0 flex-col gap-2"> + <div className="flex flex-col gap-1" data-post-media-list={view.media.length}> + <span className="micro">media</span> + {view.media.length === 0 && view.files.length === 0 && <span className="text-muted">no attachment</span>} + {view.media.map((m) => ( + <div key={`${m.i}:${m.src}`} data-post-media={m.i} className="flex flex-wrap items-center gap-x-3 gap-y-0.5"> + <label className="inline-flex min-w-0 items-center gap-1.5"> + <input type="checkbox" data-post-media-shown="" checked disabled={busy} onChange={() => void write("/api/report/post-item", { op: "set", patch: { media: { [m.i]: null } } }, `${m.src ?? `attachment ${m.i}`}: off the item (its file kept).`)} /> + <span className="truncate font-mono text-[11.5px]" title={m.src ?? ""}>{m.src?.split("/").pop() ?? `attachment ${m.i}`}</span> + <span className="text-[11px] text-muted">{m.kind}{m.seconds ? ` ${m.seconds.toFixed(1)} s` : ""}</span> + </label> + {m.kind === "video" && m.audio && ( + <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2"> + <input type="checkbox" data-post-media-sound="" checked={!m.mute} disabled={busy} onChange={(e) => void write("/api/report/post-item", { op: "set", patch: { media: { [m.i]: { mute: e.target.checked ? null : true } } } }, e.target.checked ? "Sound on." : "Sound off.")} /> + sound + </label> + )} + </div> + ))} + {view.files.map((f) => ( + <label key={f} data-post-file={f} className="inline-flex min-w-0 items-center gap-1.5 text-muted"> + <input type="checkbox" data-post-file-shown="" checked={false} disabled={busy} onChange={() => void write("/api/report/post-item/inspector", { op: "media-on", file: f }, `${f.split("/").pop()}: on the item.`)} /> + <span className="truncate font-mono text-[11.5px]" title={f}>{f.split("/").pop()}</span> + <span className="text-[11px]">not shown</span> + </label> + ))} + </div> + <div className="flex flex-col gap-1" data-post-recording={view.narration.takes.length}> + <span className="micro">my recording</span> + <span className="text-[11.5px] text-muted" data-post-takes=""> + {view.narration.takes.length ? `${view.narration.takes.length} take${view.narration.takes.length === 1 ? "" : "s"}; plays ${picked ? `${picked.file.split("/").pop()}${picked.engine ? ` (${picked.engine})` : ""}` : "none"}` : "not narrated yet"} + </span> + <input ref={fileRef} type="file" accept="audio/*,video/*" data-post-recording-file="" className="text-[11.5px]" onChange={(e) => setFile(e.target.files?.[0] ?? null)} /> + <div> + <Button type="button" size="sm" variant="outline" data-post-recording-use="" disabled={busy || !file} onClick={() => void keepMyRecording()} title="your read of it, trimmed and levelled, kept as a recorded take and picked"> + Use my recording + </Button> + </div> + </div> + </div> + </div> + <div className="mt-1.5"> + <SaidLine said={said} testid="post-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/ProvenanceInspector.tsx b/umtool/components/projects/inspector/ProvenanceInspector.tsx @@ -0,0 +1,107 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input } from "@/components/ui/field"; +import LinkPolicyPanel from "../report/LinkPolicyPanel"; +import { InspectorFrame, SaidLine, call, refusal, type InspectorProps, type Said } from "./shared"; + +// THE PROJECT'S PROVENANCE (umtool redesign L6, item 1; the owed provenance writer): where the cut's QRs open +// (provenance.siteOrigin), the channel a clip with no `channel` of its own is from (provenance.channelSlug -- +// `check` blocks without it), the sweep's display name (provenance.channel); and, under them, the link policy per +// channel (LinkPolicyPanel, its own writer). PUT /api/report/provenance; `umtool provenance <p> set` is the twin. + +type Prov = { siteOrigin: string | null; channelSlug: string | null; channel: string | null }; +type View = { + provenance: Prov; + channels: { slug: string; clips: number }[]; + corpusChannels: string[]; + sites: { origin: string; siteId: string; title: string | null }[]; + token: string | null; +}; +const KEYS = ["siteOrigin", "channelSlug", "channel"] as const; + +export default function ProvenanceInspector({ project }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [draft, setDraft] = useState<Record<(typeof KEYS)[number], string>>({ siteOrigin: "", channelSlug: "", channel: "" }); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const [policyKey, setPolicyKey] = useState(0); + const load = useCallback(async () => { + const { ok, j } = await call<View>(`/api/report/provenance?project=${encodeURIComponent(project)}`); + if (!ok) return null; + setView(j); + setDraft({ siteOrigin: j.provenance.siteOrigin ?? "", channelSlug: j.provenance.channelSlug ?? "", channel: j.provenance.channel ?? "" }); + return j; + }, [project]); + useEffect(() => { + void load(); + }, [load]); + if (!view) return null; + const changed = KEYS.filter((k) => draft[k].trim() !== (view.provenance[k] ?? "")); + const set = (k: (typeof KEYS)[number], v: string) => { + setSaid(null); + setDraft((d) => ({ ...d, [k]: v })); + }; + const save = async () => { + setBusy(true); + setSaid(null); + try { + const patch = Object.fromEntries(changed.map((k) => [k, draft[k].trim() || null])); + const { ok, status, j } = await call<{ changed?: Record<string, unknown> }>("/api/report/provenance", { method: "PUT", body: JSON.stringify({ project, token: view.token, patch }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setPolicyKey((n) => n + 1); + setSaid({ ok: true, text: `Saved to the draft: ${Object.keys(j.changed ?? {}).join(", ") || "nothing changed"}.` }); + router.refresh(); + } finally { + setBusy(false); + } + }; + const slugs = [...view.channels.map((c) => c.slug), ...view.corpusChannels.filter((s) => !view.channels.some((c) => c.slug === s))]; + return ( + <InspectorFrame kind="provenance" title="Provenance"> + <div className="grid gap-2 sm:grid-cols-3"> + <Field label="Site origin" hint="the archive its QRs open"> + <Input data-provenance-field="siteOrigin" list={`prov-sites-${project}`} placeholder="https://…" value={draft.siteOrigin} onChange={(e) => set("siteOrigin", e.target.value)} /> + </Field> + <Field label="Channel slug" hint={view.provenance.channelSlug ? "a clip with no channel is from it" : "empty: check blocks until it is set"}> + <Input data-provenance-field="channelSlug" list={`prov-channels-${project}`} value={draft.channelSlug} onChange={(e) => set("channelSlug", e.target.value)} /> + </Field> + <Field label="Channel name" hint="the sweep's display name"> + <Input data-provenance-field="channel" value={draft.channel} onChange={(e) => set("channel", e.target.value)} /> + </Field> + </div> + <datalist id={`prov-sites-${project}`}> + {view.sites.map((s) => ( + <option key={s.origin} value={s.origin}> + {s.title ?? s.siteId} + </option> + ))} + </datalist> + <datalist id={`prov-channels-${project}`}> + {slugs.map((s) => ( + <option key={s} value={s} /> + ))} + </datalist> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="go" data-provenance-save="" disabled={busy || !changed.length} onClick={() => void save()}> + Save provenance + </Button> + <Button type="button" size="sm" variant="quiet" data-provenance-revert="" disabled={busy || !changed.length} onClick={() => void load().then(() => setSaid(null))}> + Revert + </Button> + <SaidLine said={said} testid="provenance-said" /> + </div> + <div className="mt-2" data-provenance-link-policy=""> + <LinkPolicyPanel key={policyKey} project={project} /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/StillInspector.tsx b/umtool/components/projects/inspector/StillInspector.tsx @@ -0,0 +1,101 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { InspectorFrame, SaidLine, call, type InspectorProps, type Said } from "./shared"; + +// A STILL AT SECOND N (umtool redesign L6, item 6): one frame of the clip on screen at the playhead's SOURCE +// second, from its fetched window, saved in the project's shots/ (POST /api/report/still-frame; a single ffmpeg +// frame, nothing fetched, nothing in the cut written). `StillButton` sits by Play's controls; `StillInspector` +// lists the project's shots (with `block` a clip's id: that clip's stills). `umtool still` is the twin. + +type Shot = { rel: string; name: string; bytes: number; mtime: string; still: { clip: string; at: number } | null }; + +const shotUrl = (project: string, rel: string, v = "") => `/api/report/still-frame?${new URLSearchParams({ project, file: rel }).toString()}${v ? `&v=${encodeURIComponent(v)}` : ""}`; + +export default function StillInspector({ project, block = null }: InspectorProps) { + const [shots, setShots] = useState<Shot[] | null>(null); + const load = useCallback(async () => { + const { ok, j } = await call<{ shots: Shot[] }>(`/api/report/still-frame?project=${encodeURIComponent(project)}`); + if (ok) setShots(j.shots); + }, [project]); + useEffect(() => { + void load(); + // A still grabbed in Play (another component) is listed here once it lands. + const on = () => void load(); + window.addEventListener("umtool:still-grabbed", on); + return () => window.removeEventListener("umtool:still-grabbed", on); + }, [load]); + if (!shots) return null; + const list = block ? shots.filter((s) => s.still?.clip === block) : shots; + return ( + <InspectorFrame kind="still" title={`Shots — ${list.length}`} aside={<span className="font-mono text-[11px] text-muted">umtool still {project} &lt;clip&gt; --at &lt;s&gt;</span>}> + {list.length === 0 ? ( + <p className="m-0 text-muted">No pictures in shots/ yet — Play&rsquo;s Still button grabs the frame on screen.</p> + ) : ( + <ul className="flex flex-wrap gap-2"> + {list.map((s) => ( + <li key={s.rel} data-shot={s.rel} className="flex w-[160px] flex-col gap-0.5"> + <a href={shotUrl(project, s.rel, s.mtime)} target="_blank" rel="noreferrer"> + {/* eslint-disable-next-line @next/next/no-img-element */} + <img src={shotUrl(project, s.rel, s.mtime)} alt={s.name} className="h-[90px] w-[160px] rounded border border-[var(--color-line)] object-contain" loading="lazy" /> + </a> + <span className="truncate font-mono text-[10.5px] text-muted" title={s.rel}> + {s.still ? `${s.still.clip} @ ${s.still.at.toFixed(2)} s` : s.name} + </span> + </li> + ))} + </ul> + )} + </InspectorFrame> + ); +} + +/** + * Play's STILL button: the frame of the clip on screen at the playhead (`source()` -- the clip's id and the SOURCE + * second, or null on a card) grabbed into shots/. + */ +export function StillButton({ project, take = null, source, className }: { project: string; take?: string | null; source: () => { clip: string; at: number } | null; className?: string }) { + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const [last, setLast] = useState<string | null>(null); + const grab = async () => { + const s = source(); + if (!s) { + setSaid({ ok: false, text: "a card has no frame to keep: pause on a clip" }); + return; + } + setBusy(true); + setSaid(null); + try { + const { ok, j } = await call<{ rel?: string; at?: number }>("/api/report/still-frame", { method: "POST", body: JSON.stringify({ project, clip: s.clip, at: s.at, ...(take ? { take } : {}) }) }); + if (!ok || !j.rel) { + setSaid({ ok: false, text: j.error ?? "the frame could not be grabbed" }); + return; + } + setLast(j.rel); + setSaid({ ok: true, text: `${j.rel} (${s.clip} @ ${(j.at ?? s.at).toFixed(2)} s)` }); + window.dispatchEvent(new CustomEvent("umtool:still-grabbed", { detail: { rel: j.rel } })); + } finally { + setBusy(false); + } + }; + return ( + <span className={cn("inline-flex flex-wrap items-center gap-1.5", className)} data-play-still-box=""> + <Button type="button" size="sm" variant="outline" data-play-still="" disabled={busy} onClick={() => void grab()} title="keep the frame on screen as a picture in the project's shots/ (umtool still): from the clip's fetched window, at the playhead's source second"> + {busy ? "Grabbing…" : "Still"} + </Button> + {said && ( + <span className="inline-flex items-center gap-1.5"> + <SaidLine said={said} testid="play-still-said" /> + {said.ok && last && ( + <a className="ink-link text-[11.5px]" href={shotUrl(project, last, String(Date.now()))} target="_blank" rel="noreferrer" data-play-still-open=""> + open + </a> + )} + </span> + )} + </span> + ); +} diff --git a/umtool/components/projects/inspector/TeaserInspector.tsx b/umtool/components/projects/inspector/TeaserInspector.tsx @@ -0,0 +1,161 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select } from "@/components/ui/field"; +import { InspectorFrame, SaidLine, call, refusal, type InspectorProps, type Said } from "./shared"; + +// A TEASER OR CLOSING CARD (umtool redesign L6, item 2): with no `block`, a NEW card -- where it goes (the end: a +// closing card; the start: a cold open; after an entry), its lines (the first its title; each with the end of +// its words as a second tier, `break`, and a `hold`), its beat -- inserted; with `block` a teaser's id, its lines +// and beat changed. POST /api/report/teaser (op insert | set); the build's teaser rules refuse in their words. +// `umtool timeline <p> teaser-insert` / `timeline <p> teaser <id> <patch>` are the twins. + +type Line = { text: string; break: string; hold: string; keep?: Record<string, unknown> }; +type View = { + entries: { id: string; type: string; at: number; label: string | null }[]; + teasers: { id: string; at: number; lines: unknown[]; beat: number | null }[]; + limits: { lines: [number, number]; rows: number; chars: number; hold: number; beat: { min: number; max: number } }; + token: string | null; +}; + +const blank = (): Line => ({ text: "", break: "", hold: "" }); +/** A line as written into the editor's fields (keys it does not show kept as they are). */ +function lineOf(l: unknown): Line { + if (typeof l === "string") return { text: l, break: "", hold: "" }; + const o = (l && typeof l === "object" ? l : {}) as Record<string, unknown>; + const { text, break: brk, hold, ...keep } = o; + return { text: typeof text === "string" ? text : "", break: typeof brk === "string" ? brk : "", hold: typeof hold === "number" ? String(hold) : "", ...(Object.keys(keep).length ? { keep } : {}) }; +} +/** The line as the writer takes it: a string when it is only its words. */ +function valueOf(l: Line): unknown { + const o: Record<string, unknown> = { ...(l.keep ?? {}), text: l.text.trim() }; + if (l.break.trim()) o.break = l.break.trim(); + if (l.hold.trim()) o.hold = Number(l.hold); + return Object.keys(o).length === 1 ? o.text : o; +} + +export default function TeaserInspector({ project, block = null }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [lines, setLines] = useState<Line[]>([blank()]); + const [id, setId] = useState(""); + const [beat, setBeat] = useState(""); + const [position, setPosition] = useState("end"); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const editing = block ? view?.teasers.find((t) => t.id === block) ?? null : null; + const load = useCallback(async () => { + const { ok, j } = await call<View>(`/api/report/teaser?project=${encodeURIComponent(project)}`); + if (!ok) return null; + setView(j); + const t = block ? j.teasers.find((x) => x.id === block) : null; + if (t) { + setLines(t.lines.length ? t.lines.map(lineOf) : [blank()]); + setBeat(t.beat === null ? "" : String(t.beat)); + } + return j; + }, [project, block]); + useEffect(() => { + void load(); + }, [load]); + if (!view) return null; + if (block && !editing) return <InspectorFrame kind="teaser" title="Teaser"><p className="m-0 text-muted">No teaser {block} in the draft.</p></InspectorFrame>; + + const setLine = (i: number, patch: Partial<Line>) => { + setSaid(null); + setLines((ls) => ls.map((l, k) => (k === i ? { ...l, ...patch } : l))); + }; + const posValue = () => (position === "end" ? "end" : position === "start" ? "start" : { after: position.slice("after:".length) }); + const submit = async () => { + setBusy(true); + setSaid(null); + try { + const values = lines.filter((l) => l.text.trim()).map(valueOf); + const beatV = beat.trim() ? Number(beat) : null; + const body = editing + ? { project, token: view.token, op: "set", id: editing.id, patch: { lines: values, beat: beatV } } + : { project, token: view.token, op: "insert", position: posValue(), spec: { lines: values, ...(id.trim() ? { id: id.trim() } : {}), ...(beatV !== null ? { beat: beatV } : {}) } }; + const { ok, status, j } = await call<{ id?: string; at?: number }>("/api/report/teaser", { method: "POST", body: JSON.stringify(body) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + if (editing) { + await load(); + setSaid({ ok: true, text: `Saved ${j.id} to the draft.` }); + } else { + await load(); + setLines([blank()]); + setId(""); + setBeat(""); + setSaid({ ok: true, text: `Inserted ${j.id} at ${(j.at ?? 0) + 1} — Undo last edit takes it back.` }); + } + router.refresh(); + } finally { + setBusy(false); + } + }; + const lim = view.limits; + return ( + <InspectorFrame kind="teaser" title={editing ? `Teaser ${editing.id}` : "Insert a teaser or closing card"}> + {!editing && ( + <div className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,10rem)_minmax(0,7rem)]"> + <Field label="Where"> + <Select data-teaser-position="" value={position} onChange={(e) => { setPosition(e.target.value); setSaid(null); }}> + <option value="end">At the end (a closing card)</option> + <option value="start">At the start (a cold open)</option> + {view.entries.map((e) => ( + <option key={`${e.id}@${e.at}`} value={`after:${e.id}`}> + After {e.id} ({e.type}{e.label ? `: ${String(e.label).slice(0, 40)}` : ""}) + </option> + ))} + </Select> + </Field> + <Field label="Id" hint={position === "start" ? "blank: cold" : position === "end" ? "blank: close" : "blank: teaser"}> + <Input data-teaser-id="" value={id} onChange={(e) => setId(e.target.value)} /> + </Field> + <Field label="Beat" hint={`${lim.beat.min}–${lim.beat.max} s`}> + <Input data-teaser-beat="" type="number" step={0.1} min={lim.beat.min} max={lim.beat.max} value={beat} onChange={(e) => setBeat(e.target.value)} /> + </Field> + </div> + )} + {editing && ( + <div className="max-w-[10rem]"> + <Field label="Beat" hint={`${lim.beat.min}–${lim.beat.max} s`}> + <Input data-teaser-beat="" type="number" step={0.1} min={lim.beat.min} max={lim.beat.max} value={beat} onChange={(e) => setBeat(e.target.value)} /> + </Field> + </div> + )} + <ol className="mt-2 flex flex-col gap-1.5"> + {lines.map((l, i) => ( + <li key={i} data-teaser-line={i} className="grid items-end gap-1.5 sm:grid-cols-[minmax(0,1fr)_minmax(0,11rem)_minmax(0,5rem)_auto]"> + <Field label={i === 0 ? "Title line" : `Line ${i + 1}`} hint={i === 0 ? `at most ${lim.chars} characters a line` : undefined}> + <Input data-teaser-line-field="text" value={l.text} maxLength={lim.chars} onChange={(e) => setLine(i, { text: e.target.value })} /> + </Field> + <Field label="Break" hint="the end of its words, a second tier"> + <Input data-teaser-line-field="break" value={l.break} onChange={(e) => setLine(i, { break: e.target.value })} /> + </Field> + <Field label="Hold" hint={`0–${lim.hold} s`}> + <Input data-teaser-line-field="hold" type="number" step={0.1} min={0} max={lim.hold} value={l.hold} onChange={(e) => setLine(i, { hold: e.target.value })} /> + </Field> + <Button type="button" size="sm" variant="quiet" data-teaser-line-remove={i} disabled={lines.length === 1} onClick={() => setLines((ls) => ls.filter((_, k) => k !== i))}> + Remove + </Button> + </li> + ))} + </ol> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="outline" data-teaser-add-line="" disabled={lines.length >= lim.lines[1]} onClick={() => setLines((ls) => [...ls, blank()])}> + Add a line + </Button> + <Button type="button" size="sm" variant="go" data-teaser-insert={editing ? "set" : "insert"} disabled={busy || !lines.some((l) => l.text.trim())} onClick={() => void submit()}> + {editing ? "Save teaser" : "Insert card"} + </Button> + <SaidLine said={said} testid="teaser-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/TitleInspector.tsx b/umtool/components/projects/inspector/TitleInspector.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; +import { Button } from "@/components/ui/button"; +import { Field, Input } from "@/components/ui/field"; +import { InspectorFrame, SaidLine, call, refusal, type InspectorProps, type Said } from "./shared"; + +// THE PROJECT'S TITLE AND SUBTITLE (umtool redesign L6, item 7): the manifest's `title` and `subtitle`, through +// PUT /api/report/title (`umtool title <p> "<title>" [--subtitle "…"]`). An empty subtitle removes it. + +type View = { title: string | null; subtitle: string | null; limits: { title: number; subtitle: number }; token: string | null }; + +export default function TitleInspector({ project }: InspectorProps) { + const router = useRouter(); + const [view, setView] = useState<View | null>(null); + const [title, setTitle] = useState(""); + const [subtitle, setSubtitle] = useState(""); + const [busy, setBusy] = useState(false); + const [said, setSaid] = useState<Said>(null); + const load = useCallback(async () => { + const { ok, j } = await call<View>(`/api/report/title?project=${encodeURIComponent(project)}`); + if (!ok) return null; + setView(j); + setTitle(j.title ?? ""); + setSubtitle(j.subtitle ?? ""); + return j; + }, [project]); + useEffect(() => { + void load(); + }, [load]); + if (!view) return null; + const dirty = title.trim() !== (view.title ?? "") || subtitle.trim() !== (view.subtitle ?? ""); + const save = async () => { + setBusy(true); + setSaid(null); + try { + const { ok, status, j } = await call("/api/report/title", { method: "PUT", body: JSON.stringify({ project, token: view.token, title, subtitle }) }); + if (!ok) { + setSaid({ ok: false, text: refusal(j, status) }); + if (j.stale) await load(); + return; + } + await load(); + setSaid({ ok: true, text: "Saved to the draft." }); + router.refresh(); + } finally { + setBusy(false); + } + }; + return ( + <InspectorFrame kind="title" title="Title"> + <div className="grid gap-2 sm:grid-cols-2"> + <Field label="Title"> + <Input data-title-field="title" value={title} maxLength={view.limits.title} onChange={(e) => { setTitle(e.target.value); setSaid(null); }} /> + </Field> + <Field label="Subtitle" hint="blank: none"> + <Input data-title-field="subtitle" value={subtitle} maxLength={view.limits.subtitle} onChange={(e) => { setSubtitle(e.target.value); setSaid(null); }} /> + </Field> + </div> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <Button type="button" size="sm" variant="go" data-title-save="" disabled={busy || !dirty || !title.trim()} onClick={() => void save()}> + Save title + </Button> + <Button type="button" size="sm" variant="quiet" data-title-revert="" disabled={busy || !dirty} onClick={() => { setTitle(view.title ?? ""); setSubtitle(view.subtitle ?? ""); setSaid(null); }}> + Revert + </Button> + <SaidLine said={said} testid="title-said" /> + </div> + </InspectorFrame> + ); +} diff --git a/umtool/components/projects/inspector/shared.tsx b/umtool/components/projects/inspector/shared.tsx @@ -0,0 +1,68 @@ +"use client"; + +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE INSPECTOR PANELS' COMMON PARTS (umtool redesign L6). Every panel in this directory is self-contained: it +// takes `{ project, block? }` (the project id; the block -- a timeline entry's id -- it inspects, when it is about +// one), reads its own state from its API route and writes through it, so L7 can mount it in the workspace's +// inspector unchanged. Today they are mounted in the Cut tab (and Play's Still button). Every write lands in the +// working draft (video.manifest.json) with its own undo point; none touches a take's patch. No AI anywhere. +// --------------------------------------------------------------------------- + +export type InspectorProps = { project: string; block?: string | null }; + +/** What a write said: a sentence, good or bad. */ +export type Said = { ok: boolean; text: string } | null; + +/** A JSON request; the parsed body (or {}) and whether it was 2xx. A stale token says so. */ +export async function call<T = Record<string, unknown>>(url: string, init?: RequestInit): Promise<{ ok: boolean; status: number; j: T & { error?: string; errors?: string[]; stale?: boolean } }> { + const r = await fetch(url, { cache: "no-store", ...init, headers: init?.body && typeof init.body === "string" ? { "content-type": "application/json", ...(init.headers ?? {}) } : init?.headers }); + const j = (await r.json().catch(() => ({}))) as T & { error?: string; errors?: string[]; stale?: boolean }; + return { ok: r.ok, status: r.status, j }; +} + +/** The sentence for a refused write. */ +export const refusal = (j: { error?: string; errors?: string[]; stale?: boolean }, status: number) => + j.stale ? "The draft changed since this panel read it — it has been read again; check and save once more." : (j.errors?.length ? j.errors.join("; ") : j.error) ?? `HTTP ${status}`; + +/** A panel's frame: a heading, the body. */ +export function InspectorFrame({ kind, title, aside, className, children }: { kind: string; title: React.ReactNode; aside?: React.ReactNode; className?: string; children: React.ReactNode }) { + return ( + <section data-inspector={kind} className={cn("min-w-0 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]", className)}> + <div className="mb-1.5 flex flex-wrap items-baseline gap-2"> + <h3 className="micro">{title}</h3> + {aside ? <span className="ml-auto flex flex-wrap items-center gap-2">{aside}</span> : null} + </div> + {children} + </section> + ); +} + +/** The line under a panel's buttons. */ +export function SaidLine({ said, testid }: { said: Said; testid: string }) { + if (!said) return null; + return ( + <span role="status" {...{ [`data-${testid}`]: said.ok ? "ok" : "refused" }} className={cn("text-[11.5px]", said.ok ? "text-text-2" : "text-[var(--color-bad)]")}> + {said.text} + </span> + ); +} + +/** + * A row's "Edit" that opens a panel under it (the Cut tab's per-row inspector, until L7's workspace has one + * inspector for the selected block). + */ +export function InspectorToggle({ label = "Edit", testid, children, className }: { label?: string; testid: string; children: React.ReactNode; className?: string }) { + const [open, setOpen] = useState(false); + return ( + <> + <Button type="button" size="sm" variant={open ? "pressed" : "quiet"} className={className} aria-expanded={open} {...{ [`data-${testid}`]: open ? "open" : "" }} onClick={() => setOpen((o) => !o)}> + {open ? "Close" : label} + </Button> + {open ? <div className="basis-full pt-1.5">{children}</div> : null} + </> + ); +} diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -38,6 +38,15 @@ import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/ import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs"; import IntroRow from "./IntroEditor"; +// The inspector panels for this week's hand edits (umtool redesign L6), mounted here until L7's workspace inspector. +import { InspectorToggle } from "../inspector/shared"; +import TitleInspector from "../inspector/TitleInspector"; +import ProvenanceInspector from "../inspector/ProvenanceInspector"; +import TeaserInspector from "../inspector/TeaserInspector"; +import LedgerInspector from "../inspector/LedgerInspector"; +import PostItemInspector from "../inspector/PostItemInspector"; +import LinksInspector from "../inspector/LinksInspector"; +import StillInspector from "../inspector/StillInspector"; // The Cut tab: the timeline, read back -- the walk into it, its takes, every // entry with what is wrong with it, and the corrections the walk collected. @@ -219,6 +228,10 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <Link href={postBenchHref(project.id, e.id)} className="ink-link text-[11px]" data-post-bench-link={e.id}> bench </Link> + {/* Its excerpt by selection, its media on/off, my recording (the inspector, L6). */} + <InspectorToggle testid="post-edit" label="Edit"> + <PostItemInspector project={project.id} block={e.id} /> + </InspectorToggle> </div> {words && <div className="mt-0.5 text-[12px] text-[var(--color-dim)]">{words.length > 160 ? `${words.slice(0, 157)}…` : words}</div>} <div className="basis-full"> @@ -244,6 +257,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor </span> {e.seconds != null && <span className="num micro ml-auto">{e.seconds}s</span>} <PlayLink project={project.id} clip={e.id} where="row" variant="icon" className={e.seconds != null ? "" : "ml-auto"} /> + {e.kind === "teaser" && ( + <InspectorToggle testid="teaser-edit" label="Edit"> + <TeaserInspector project={project.id} block={e.id} /> + </InspectorToggle> + )} <div className="basis-full"> <RowNotes id={e.id} project={project.id} /> </div> @@ -498,6 +516,14 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor <PronunciationPanel project={project.id} /> </Options> )} + {/* The project's own facts, each an inspector panel (L6): what agents set by hand this week. */} + <Options id="cut-project" label="Project" hint="title · provenance · Rumble cites · ledger · shots" bodyClassName="w-[min(1100px,calc(100vw-3rem))] flex-col items-stretch"> + <TitleInspector project={project.id} /> + <ProvenanceInspector project={project.id} /> + {clips.length > 0 && <LinksInspector project={project.id} />} + {(Array.isArray(m?.ledger) || m?.ledgerSchema) && <LedgerInspector project={project.id} />} + <StillInspector project={project.id} /> + </Options> <Advanced id="cut" hint="voices · tight windows · bench prep"> {clips.length > 0 && ( <VoiceMatchPanel @@ -544,6 +570,12 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor )} {/* The intro the cut opens on (render.intro), first, and its editor with a live preview (lane intro-play). */} <IntroRow project={project.id} written={m?.render?.intro ?? null} open={search.intro === "1"} /> + {/* A teaser or closing card, inserted (the inspector, L6; `umtool timeline <p> teaser-insert`). */} + <div className="mb-1.5 flex flex-wrap items-center gap-2" data-cut-insert-card-row=""> + <InspectorToggle testid="cut-insert-card" label="Insert a teaser or closing card"> + <TeaserInspector project={project.id} /> + </InspectorToggle> + </div> <TimelineList project={project.id} count={entries.length} groupCount={groupBars.list.length}> {sectionBars.opening && <SectionBar section={sectionBars.opening} />} {entries.map((e, at) => ( diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -41,6 +41,7 @@ import { useIntroPage } from "./useIntroPage"; import { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs"; import ComboBadge, { type ComboInfo } from "./ComboBadge"; import CopyShareLine from "../CopyShareLine"; +import { StillButton } from "../inspector/StillInspector"; // --------------------------------------------------------------------------- // THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The @@ -710,6 +711,14 @@ export default function PlayCut({ if (take) return openInDraftHref(project, take, { clip: it.id, play: { at } }); return clipBenchHref(project, it.id, { play: { at, take: null } }); }, [project, take, now]); + // ---- a still at second N (the inspector, L6): the clip on screen at the playhead's SOURCE second ---- + const stillSource = useCallback(() => { + const e = now(); + const it = planRef.current.items[e.cur]; + if (!it?.clip) return null; + const src = sourceAt(it, e.t); + return src === null ? null : { clip: it.id, at: Math.round(src * 100) / 100 }; + }, [now]); /** Play's place as its own URL: the clip on screen, the offset into it, the cut second, the toggle. */ const placeHref = useCallback(() => { const e = now(); @@ -1390,6 +1399,8 @@ export default function PlayCut({ > {postNow ? "Edit this post" : "Edit this clip"} </button> + {/* The frame on screen kept as a picture in shots/ (umtool still): never a write to the cut. */} + {item?.clip && <StillButton project={project} take={take ?? null} source={stillSource} />} <span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted" data-play-hud=""> {tally.length > 0 && <span className="sr-only" data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")} />} {schedule?.factcheck && ( diff --git a/umtool/lib/report/excerptPick.mjs b/umtool/lib/report/excerptPick.mjs @@ -0,0 +1,112 @@ +// PICKING A POST ITEM's EXCERPT BY SELECTING ITS WORDS (umtool redesign L6, item 4): a selection in the post's +// text (character offsets into cardText, post-item.mjs) made into the excerpt's span format the build reads -- +// `entry.excerpt`, VERBATIM strings of the post's words in the post's order, each found by indexOf from the end +// of the one before (post-item.mjs excerptRanges). Pure, no imports: the inspector's client component runs it, +// and pnpm test:scripts checks it. + +const isWordChar = (c) => !!c && !/\s/.test(c); + +/** + * A selection snapped OUT to whole words and trimmed of the space at its ends: `[start, end)` in `text`, or null + * when it holds no word. + * @param {string} text + * @param {number} start + * @param {number} end + */ +export function snapToWords(text, start, end) { + let a = Math.max(0, Math.min(start, end)); + let b = Math.min(text.length, Math.max(start, end)); + while (a < b && /\s/.test(text[a])) a += 1; + while (b > a && /\s/.test(text[b - 1])) b -= 1; + if (a >= b) return null; + while (a > 0 && isWordChar(text[a - 1])) a -= 1; + while (b < text.length && isWordChar(text[b])) b += 1; + return { start: a, end: b }; +} + +/** + * The ranges with `r` added, in the post's order, overlapping or touching ranges merged. + * @param {Array<{ start: number, end: number }>} ranges + * @param {{ start: number, end: number }} r + */ +export function addRange(ranges, r) { + const all = [...ranges, r].sort((x, y) => x.start - y.start); + const out = []; + for (const x of all) { + const last = out.at(-1); + if (last && x.start <= last.end) last.end = Math.max(last.end, x.end); + else out.push({ ...x }); + } + return out; +} + +/** + * Where the build will FIND each span (indexOf from the end of the one before): a span whose words occur earlier + * in the post too would be read there, so it is widened a word to the left until it is found where it was + * picked. Returns the ranges (possibly widened) in order. + * @param {string} text + * @param {Array<{ start: number, end: number }>} ranges + */ +export function settleRanges(text, ranges) { + const out = []; + let from = 0; + for (const r0 of ranges) { + let r = { ...r0 }; + // Widen left, a word at a time, until the span is found where it stands (it always is at worst at `from`). + while (text.indexOf(text.slice(r.start, r.end), from) !== r.start && r.start > from) { + // The start of the word before: back over the space, then over its letters. + let a = r.start; + while (a > from && /\s/.test(text[a - 1])) a -= 1; + while (a > from && isWordChar(text[a - 1])) a -= 1; + if (a === r.start) break; + r = { start: a, end: r.end }; + } + const last = out.at(-1); + if (last && r.start <= last.end) last.end = Math.max(last.end, r.end); + else out.push(r); + from = r.end; + } + return out; +} + +/** + * The excerpt (the strings) the ranges spell. + * @param {string} text + * @param {Array<{ start: number, end: number }>} ranges + * @returns {string[]} + */ +export const spansOf = (text, ranges) => ranges.map((r) => text.slice(r.start, r.end)); + +/** + * The ranges an excerpt stands at (post-item.mjs excerptRanges' rule), or null when a span is not found. + * @param {string} text + * @param {string[]} spans + */ +export function rangesOf(text, spans) { + const out = []; + let from = 0; + for (const sp of spans) { + const at = text.indexOf(sp, from); + if (at < 0) return null; + out.push({ start: at, end: at + sp.length }); + from = at + sp.length; + } + return out; +} + +/** + * The text cut into pieces for drawing: each `{ text, start, end, picked }`, a picked piece one range. + * @param {string} text + * @param {Array<{ start: number, end: number }>} ranges + */ +export function piecesOf(text, ranges) { + const out = []; + let at = 0; + for (const r of ranges) { + if (r.start > at) out.push({ text: text.slice(at, r.start), start: at, end: r.start, picked: false }); + out.push({ text: text.slice(r.start, r.end), start: r.start, end: r.end, picked: true }); + at = r.end; + } + if (at < text.length) out.push({ text: text.slice(at), start: at, end: text.length, picked: false }); + return out; +} diff --git a/umtool/lib/report/excerptPick.test.mjs b/umtool/lib/report/excerptPick.test.mjs @@ -0,0 +1,43 @@ +// Picking a post item's excerpt by selecting its words (excerptPick.mjs): snapped to words, merged, settled +// where the build's indexOf will find each span. Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "./excerptPick.mjs"; +import { excerptRanges } from "umtool-report-to-video/post-item"; + +const T = "The scale said 291. I said the scale was broken. Then the scale said 290."; + +test("a selection snaps out to whole words, trimmed", () => { + const r = snapToWords(T, T.indexOf("cale said 2"), T.indexOf("291") + 2); + assert.deepEqual(spansOf(T, [r]), ["scale said 291."]); + assert.equal(snapToWords(T, 3, 4), null); + assert.deepEqual(snapToWords(T, 0, 1), { start: 0, end: 3 }); +}); + +test("ranges merge in the post's order", () => { + let rs = addRange([], { start: 20, end: 30 }); + rs = addRange(rs, { start: 0, end: 5 }); + rs = addRange(rs, { start: 28, end: 40 }); + assert.deepEqual(rs, [{ start: 0, end: 5 }, { start: 20, end: 40 }]); +}); + +test("a span whose words come earlier too is widened until the build finds it where it was picked", () => { + const W = "scale said"; + const second = T.lastIndexOf(W); + assert.ok(T.indexOf(W) < second); + const picked = [{ start: second, end: second + W.length }]; + const settled = settleRanges(T, picked); + const spans = spansOf(T, settled); + assert.deepEqual(excerptRanges(T, spans).map((r) => r.end), [second + W.length]); + assert.deepEqual(spans, ["the scale said"]); + // Two spans: the second found after the first. + const two = settleRanges(T, [{ start: 0, end: 9 }, picked[0]]); + assert.deepEqual(excerptRanges(T, spansOf(T, two)), two); + assert.deepEqual(rangesOf(T, spansOf(T, two)), two); +}); + +test("the pieces cover the text, the picked ones marked", () => { + const p = piecesOf(T, [{ start: 4, end: 9 }]); + assert.equal(p.map((x) => x.text).join(""), T); + assert.deepEqual(p.filter((x) => x.picked).map((x) => x.text), ["scale"]); +});