Archilyzer · Source

archilyzer

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

commit 7e35ad60e8bb3ff65096edf22d9d7616eb0afe2e
parent 530fb5c0cdd694aa73a09e420e0a207b166f4930
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 17:19:16 -0500

umtool: a post's SCREENS -- text screenshots transcribed, drawn on the card and read as part of the post

A post item may carry `screens` (report-to-video/post-screens.mjs): the text screenshots
in its attachments (a DM exchange or an email in its video, an image that is a
screenshot), each transcribed once (lines: who, side, text, time, redact), checked by a
person, and read whole or in excerpts (`read`: all | none | [{line, text?}]).

- The data and its validation (validatePostItem); an e-mail, a phone number, an order or
  long number in a line is masked on the card and never said, whatever was marked.
- The read: each read line a piece of the thread read after his words, role
  screen:<id>:<n>, in its speaker's voice (her own lines in hers; a handle or a
  character's name); --no-screens; --line-take screen:<id>:<n>=<take> takes a line
  from an existing take as --post-take does his line; a short pause between lines.
- The card: a screen the take reads is a tile after his post (post-thread.mjs): his
  post gives way to a strip, each line a read-follow block lit while it is said, a
  finished screen collapses as the next comes in; a header "DMs shown in <shown
  name>'s video · transcribed" and a badge pinned to the card while a screen is up.
- The media (post-item.mjs planOf): its own attachments until the first screen is up,
  then each screen's span, its last frame held (post-render.mjs caps the span).
- The guard and lint: a part reading a line the screen does not read is refused; not
  checked, a masked shape, a read not made, a speaker blurred by the privacy rule
  are warnings; the anonymity pass covers screens' speakers and words.
- `umtool posts screen <p> <item> list|add|set|rm|check|read` through updatePostItem
  (an attachment a screen is in cannot go; the others' indices follow), and the post
  bench's Screens section (PostScreensPanel).

With no screens every page, plan and key is byte-identical (post-screens-pin.test.mjs).

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

Diffstat:
Mumtool/components/projects/PostBench.tsx | 6++++++
Aumtool/components/projects/PostScreensPanel.tsx | 333+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/castProject.mjs | 7+++++++
Mumtool/lib/report/manifest.mjs | 23++++++++++++++++++++---
Mumtool/lib/report/postNarrationCli.mjs | 20+++++++++++++++++---
Mumtool/lib/report/postPause.mjs | 2+-
Mumtool/lib/report/postSay.mjs | 3+++
Aumtool/lib/report/postScreens.test.mjs | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/postScreensCli.mjs | 385+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/postThreadCli.mjs | 5+++--
Mumtool/lib/report/postThreadRead.mjs | 86++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mumtool/lib/report/postsCli.mjs | 19++++++++++++++-----
Mumtool/report-to-video/package.json | 1+
Mumtool/report-to-video/post-anon.mjs | 37++++++++++++++++++++++++++++++++++++-
Mumtool/report-to-video/post-item.mjs | 79++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/report-to-video/post-narration.mjs | 2+-
Mumtool/report-to-video/post-redact.mjs | 10++++++++++
Mumtool/report-to-video/post-render.mjs | 11++++++++---
Aumtool/report-to-video/post-screens.mjs | 587+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-screens.test.mjs | 268+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/post-thread.mjs | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/read-follow.mjs | 41++++++++++++++++++++++++++++++++++++-----
22 files changed, 2132 insertions(+), 45 deletions(-)

diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx @@ -11,6 +11,7 @@ import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer"; import PostFollowPanel from "./PostFollowPanel"; import PostThreadPanel from "./PostThreadPanel"; +import PostScreensPanel from "./PostScreensPanel"; import BlurBoxPad, { type Band } from "./BlurBoxPad"; import PostNarrationPanel from "./PostNarrationPanel"; import PostComboPanel from "./PostComboPanel"; @@ -39,6 +40,8 @@ import { sceneEntry } from "umtool-report-to-video/post-media-scene"; // transcription (a job on a local worker), never ASR here // thread a read of the post it answers or quotes: what each is on // screen while it is read and after (PostThreadPanel) +// screens the text screenshots in its attachments, transcribed, drawn and +// read after its words (PostScreensPanel) // context the post it quotes, the posts it answers: a paraphrase of // a long one, drawn in place of its words with a // "paraphrased" label (its own text kept, shown beside) @@ -227,6 +230,8 @@ export default function PostBench({ ), // Picture-only (post-picture.mjs): true, false, or null (the rule). pictureOnly: typeof e.pictureOnly === "boolean" ? e.pictureOnly : null, + // Its screens (post-screens.mjs): the whole list as it stands (null: none). + screens: Array.isArray(e.screens) && e.screens.length ? e.screens : null, ...(e.quoted && typeof e.quoted === "object" ? { quoted: { paraphrase: e.quoted.paraphrase?.trim() ? e.quoted.paraphrase : null, pictureOnly: typeof e.quoted.pictureOnly === "boolean" ? e.quoted.pictureOnly : null } } : {}), ...(Array.isArray(e.parents) && e.parents.length ? { parents: Object.fromEntries(e.parents.map((p, i) => [i, { paraphrase: p?.paraphrase?.trim() ? p.paraphrase : null, pictureOnly: typeof p?.pictureOnly === "boolean" ? p.pictureOnly : null }])) } @@ -426,6 +431,7 @@ export default function PostBench({ /> <PostFollowPanel entry={entry} plan={plan} render={render} s={s} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> <PostThreadPanel project={project} entry={entry} plan={plan} render={render} before={before} scene={conversation} setS={setS} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> + <PostScreensPanel project={project} entry={entry} setEntry={(f) => setEntry((e) => f(e) as Entry)} /> <PostNarrationPanel project={project} entry={entry} diff --git a/umtool/components/projects/PostScreensPanel.tsx b/umtool/components/projects/PostScreensPanel.tsx @@ -0,0 +1,333 @@ +"use client"; + +import { useMemo, useRef, useState } from "react"; +import { SCREEN_KINDS, screenReadLines, screenWarnings, shapeSpans, validateScreens } from "umtool-report-to-video/post-screens"; +import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; +import { partRoles } from "umtool-report-to-video/post-thread"; +import { postFileUrl } from "./review/PostItemPlayer"; + +// --------------------------------------------------------------------------- +// A POST's SCREENS ON THE BENCH (report-to-video/post-screens.mjs; docs/report-video.md, "Screens"; operator, 12 Nov: +// "The 'read text screenshots as posts' ability in different variations should be first class"): the text screenshots +// the post carries -- each the attachment it is in (and, in a video, the seconds it is visible), what it is (DMs, an +// email, a post, text), its lines transcribed by hand (pasted as `who: words | time`), who says each and on which side, +// which lines are read (a line's excerpt trimmed to the words read), and whether a person checked the transcription. +// No model: everything here is typed. The bench's Save writes it (updatePostItem's `screens`); the read is made with +// `umtool posts screen <p> <item> read` (the line shown here). +// --------------------------------------------------------------------------- + +type Line = { who?: string; side?: "left" | "right"; text: string; time?: string; redact?: true }; +type Read = "all" | "none" | Array<{ line: number; text?: string }>; +type Screen = { id: string; media: number; at?: [number, number]; kind: string; title?: string; source?: string; checked?: { by: string; at: string }; ref?: string; unread?: "omit" | "dim"; lines: Line[]; read: Read }; +type Media = { src: string; kind: string; seconds?: number }; +type Entry = Record<string, unknown> & { id: string; media?: Media[]; screens?: Screen[] }; + +const r2 = (v: number) => Math.round(v * 100) / 100; + +/** One pasted line: `[right] who: words | time`, `- words`, `[redact] …` (postScreensCli.mjs lineOfText's rule). */ +function lineOfText(raw: string): Line | null { + let t = raw.trim(); + if (!t) return null; + const out: Line = { text: "" }; + for (;;) { + const m = /^\[(left|right|redact)\]\s*/i.exec(t); + if (!m) break; + if (m[1].toLowerCase() === "redact") out.redact = true; + else out.side = m[1].toLowerCase() as "left" | "right"; + t = t.slice(m[0].length); + } + const bar = t.lastIndexOf(" | "); + if (bar > 0) { + out.time = t.slice(bar + 3).trim(); + t = t.slice(0, bar).trim(); + } + if (t.startsWith("- ")) t = t.slice(2); + else { + const c = /^([^:]{1,64}?):\s+(.*)$/s.exec(t); + if (c && !/^https?$/i.test(c[1])) { + out.who = c[1].trim(); + t = c[2]; + } + } + out.text = t.trim(); + return out; +} + +/** The read as a list of `{ line, text? }` (all: every line not redacted; none: none). */ +const readList = (sc: Screen): Array<{ line: number; text?: string }> => (sc.read === "all" ? sc.lines.map((l, i) => (l.redact ? null : { line: i })).filter((x): x is { line: number } => !!x) : sc.read === "none" ? [] : sc.read); + +export default function PostScreensPanel({ project, entry, setEntry }: { project: string; entry: Entry; setEntry: (f: (e: Entry) => Entry) => void }) { + const screens = useMemo(() => (Array.isArray(entry.screens) ? entry.screens : []), [entry.screens]); + const media = Array.isArray(entry.media) ? entry.media : []; + const errors = useMemo(() => validateScreens(entry) as string[], [entry]); + const warnings = useMemo(() => screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? (partRoles(entry) as Array<{ role: string | null }>).map((r) => r.role) : [] }) as string[], [entry]); + const [paste, setPaste] = useState<Record<string, string>>({}); + const setScreens = (f: (list: Screen[]) => Screen[]) => + setEntry((e) => { + const next = f(Array.isArray(e.screens) ? (e.screens as Screen[]) : []); + const out = { ...e }; + if (next.length) out.screens = next; + else delete out.screens; + return out; + }); + const setScreen = (id: string, f: (s: Screen) => Screen) => setScreens((list) => list.map((s) => (s.id === id ? f(s) : s))); + // Lines or words changed: the check was for the words before. + const setLines = (id: string, f: (lines: Line[]) => Line[]) => setScreen(id, (s) => { + const { checked: _c, ...rest } = s; + void _c; + return { ...rest, lines: f(s.lines) }; + }); + const add = () => { + const have = new Set(screens.map((s) => s.id)); + let n = 1; + while (have.has(`s${n}`)) n += 1; + const m = media[0]; + const sc: Screen = { id: `s${n}`, media: 0, kind: "dm", source: "transcribed", lines: [], read: "all", ...(m && (m.kind === "video" || m.kind === "gif") ? { at: [0, r2(Math.min(5, m.seconds ?? 5))] as [number, number] } : {}) }; + setScreens((list) => [...list, sc]); + }; + if (!media.length) return null; + return ( + <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12px]" data-post-screens-panel="" data-screens={screens.length}> + <div className="mb-2 flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">screens</h2> + <span className="text-text-2">text screenshots in its attachments, transcribed, drawn on the card and read after its words</span> + <button type="button" className="ink-link ml-auto" onClick={add} data-post-screens-add=""> + Add a screen + </button> + </div> + {screens.map((sc) => ( + <ScreenEditor + key={sc.id} + project={project} + entry={entry} + sc={sc} + media={media} + paste={paste[sc.id] ?? ""} + setPaste={(v) => setPaste((p) => ({ ...p, [sc.id]: v }))} + setScreen={(f) => setScreen(sc.id, f)} + setLines={(f) => setLines(sc.id, f)} + remove={() => setScreens((list) => list.filter((s) => s.id !== sc.id))} + /> + ))} + {screens.length > 0 && ( + <p className="m-0 mt-2 font-mono text-text-2" data-post-screens-read-cmd=""> + umtool posts screen {project} {entry.id} read + </p> + )} + {errors.length > 0 && ( + <ul className="m-0 mt-1 list-disc pl-4 text-[var(--color-bad,#e5484d)]" data-post-screens-errors=""> + {errors.map((er, i) => ( + <li key={i}>{er}</li> + ))} + </ul> + )} + {warnings.length > 0 && ( + <ul className="m-0 mt-1 list-disc pl-4 text-text-2" data-post-screens-warnings=""> + {warnings.map((w, i) => ( + <li key={i}>{w}</li> + ))} + </ul> + )} + </section> + ); +} + +function ScreenEditor({ + project, entry, sc, media, paste, setPaste, setScreen, setLines, remove, +}: { + project: string; + entry: Entry; + sc: Screen; + media: Media[]; + paste: string; + setPaste: (v: string) => void; + setScreen: (f: (s: Screen) => Screen) => void; + setLines: (f: (lines: Line[]) => Line[]) => void; + remove: () => void; +}) { + const m = media[sc.media]; + const timed = m?.kind === "video" || m?.kind === "gif"; + const video = useRef<HTMLVideoElement | null>(null); + const reads = new Map(readList(sc).map((r) => [r.line, r])); + const drawnReads = new Map((screenReadLines(sc) as Array<{ n: number; cutBefore: boolean; cutAfter: boolean }>).map((r) => [r.n, r])); + const setRead = (list: Array<{ line: number; text?: string }>) => setScreen((s) => ({ ...s, read: list.length === s.lines.filter((l) => !l.redact).length && list.every((x) => !x.text) ? "all" : list.length ? [...list].sort((a, b) => a.line - b.line) : "none" })); + const toggleRead = (n: number, on: boolean) => { + const list = readList(sc).filter((x) => x.line !== n); + setRead(on ? [...list, { line: n }] : list); + }; + const setExcerpt = (n: number, text: string) => setRead([...readList(sc).filter((x) => x.line !== n), text.trim() ? { line: n, text } : { line: n }]); + const setLine = (n: number, patch: Partial<Line>) => + setLines((lines) => + lines.map((l, i) => { + if (i !== n) return l; + const out: Record<string, unknown> = { ...l, ...patch }; + for (const [k, v] of Object.entries(out)) if (v === undefined || v === "" || v === false) if (k !== "text") delete out[k]; + return out as Line; + }), + ); + const at = sc.at ?? [0, 0]; + return ( + <div className="mb-3 rounded border border-[var(--color-line)] p-2" data-post-screen={sc.id}> + <div className="mb-1 flex flex-wrap items-center gap-2"> + <span className="font-mono">{sc.id}</span> + <label className="flex items-center gap-1"> + what + <select value={sc.kind} onChange={(e) => setScreen((s) => ({ ...s, kind: e.target.value }))} data-post-screen-kind=""> + {SCREEN_KINDS.map((k: string) => ( + <option key={k} value={k}> + {k === "dm" ? "DMs" : k} + </option> + ))} + </select> + </label> + <label className="flex items-center gap-1"> + title + <input className="w-36" value={sc.title ?? ""} placeholder="(from what it is)" onChange={(e) => setScreen((s) => { const { title: _t, ...rest } = s; void _t; return e.target.value ? { ...rest, title: e.target.value } : rest; })} data-post-screen-title="" /> + </label> + <label className="flex items-center gap-1"> + in + <select + value={sc.media} + onChange={(e) => + setScreen((s) => { + const i = Number(e.target.value); + const mm = media[i]; + const { at: _a, ...rest } = s; + void _a; + return mm && (mm.kind === "video" || mm.kind === "gif") ? { ...rest, media: i, at: s.at ?? [0, r2(Math.min(5, mm.seconds ?? 5))] } : { ...rest, media: i }; + }) + } + data-post-screen-media="" + > + {media.map((mm, i) => ( + <option key={i} value={i}> + attachment {i + 1} ({mm.kind}) + </option> + ))} + </select> + </label> + {timed && ( + <span className="flex items-center gap-1" data-post-screen-at=""> + visible + <input type="number" step={0.1} min={0} className="w-16" value={at[0]} onChange={(e) => setScreen((s) => ({ ...s, at: [r2(Number(e.target.value)), at[1]] }))} data-post-screen-at-from="" aria-label="from (s)" /> + – + <input type="number" step={0.1} min={0} className="w-16" value={at[1]} onChange={(e) => setScreen((s) => ({ ...s, at: [at[0], r2(Number(e.target.value))] }))} data-post-screen-at-to="" aria-label="to (s)" /> + s + </span> + )} + <label className="flex items-center gap-1"> + lines not read + <select value={sc.unread ?? "omit"} onChange={(e) => setScreen((s) => { const { unread: _u, ...rest } = s; void _u; return e.target.value === "dim" ? { ...rest, unread: "dim" } : rest; })} data-post-screen-unread=""> + <option value="omit">left out</option> + <option value="dim">drawn dim</option> + </select> + </label> + <label className="flex items-center gap-1" title="the transcription read against the screenshot"> + <input + type="checkbox" + checked={!!sc.checked} + onChange={(e) => setScreen((s) => { const { checked: _c, ...rest } = s; void _c; return e.target.checked ? { ...rest, checked: { by: "operator", at: new Date().toISOString() } } : rest; })} + data-post-screen-checked="" + /> + checked + </label> + <button type="button" className="ink-link ml-auto" onClick={remove} data-post-screen-remove=""> + Remove + </button> + </div> + {timed && m && ( + <div className="mb-1 flex items-center gap-2" data-post-screen-scrub=""> + <video ref={video} src={postFileUrl(project, m.src)} className="h-28 rounded bg-black" controls muted preload="metadata" onLoadedMetadata={(e) => (e.currentTarget.currentTime = at[0])} /> + <div className="flex flex-col gap-1"> + <button type="button" className="ink-link text-left" onClick={() => video.current && setScreen((s) => ({ ...s, at: [r2(video.current!.currentTime), Math.max(r2(video.current!.currentTime) + 0.5, (s.at ?? at)[1])] }))} data-post-screen-from-here=""> + visible from here + </button> + <button type="button" className="ink-link text-left" onClick={() => video.current && setScreen((s) => ({ ...s, at: [(s.at ?? at)[0], r2(video.current!.currentTime)] }))} data-post-screen-to-here=""> + to here + </button> + </div> + </div> + )} + {sc.lines.length > 0 && ( + <table className="w-full border-collapse" data-post-screen-lines=""> + <thead> + <tr className="text-left text-text-2"> + <th className="w-6">#</th> + <th className="w-10">read</th> + <th className="w-28">who</th> + <th className="w-16">side</th> + <th>words (the excerpt read below, when trimmed)</th> + <th className="w-20">time</th> + <th className="w-14">redact</th> + </tr> + </thead> + <tbody> + {sc.lines.map((l, n) => { + const r = reads.get(n); + const d = drawnReads.get(n); + const shapes = (shapeSpans(l.text) as Array<{ kind: string }>).map((x) => x.kind); + return ( + <tr key={n} className="align-top" data-post-screen-line={n}> + <td className="font-mono">{n}</td> + <td> + <input type="checkbox" disabled={!!l.redact} checked={!!r && !l.redact} onChange={(e) => toggleRead(n, e.target.checked)} data-post-screen-read={n} aria-label={`read line ${n}`} /> + </td> + <td> + <input className="w-full" value={l.who ?? ""} placeholder="—" onChange={(e) => setLine(n, { who: e.target.value || undefined })} data-post-screen-who={n} /> + </td> + <td> + <select value={l.side ?? ""} onChange={(e) => setLine(n, { side: (e.target.value || undefined) as Line["side"] })} data-post-screen-side={n}> + <option value="">auto</option> + <option value="left">left</option> + <option value="right">right</option> + </select> + </td> + <td> + <input className="w-full" value={l.text} onChange={(e) => setLine(n, { text: e.target.value })} data-post-screen-text={n} /> + {r && !l.redact && ( + <input className="mt-0.5 w-full text-text-2" value={r.text ?? ""} placeholder="excerpt: the words read (all of them when empty)" onChange={(e) => setExcerpt(n, e.target.value)} data-post-screen-excerpt={n} /> + )} + {d && (d.cutBefore || d.cutAfter) && <span className="text-text-2">reads an excerpt</span>} + {shapes.length > 0 && !l.redact && <span className="text-text-2" data-post-screen-masked={n}> · masked: {shapes.join(", ")}</span>} + </td> + <td> + <input className="w-full" value={l.time ?? ""} onChange={(e) => setLine(n, { time: e.target.value || undefined })} data-post-screen-time={n} /> + </td> + <td> + <input type="checkbox" checked={!!l.redact} onChange={(e) => setLine(n, { redact: e.target.checked ? true : undefined })} data-post-screen-redact={n} aria-label={`redact line ${n}`} /> + <button type="button" className="ink-link ml-1" onClick={() => setLines((lines) => lines.filter((_, i) => i !== n))} title="remove the line" data-post-screen-line-remove={n}> + × + </button> + </td> + </tr> + ); + })} + </tbody> + </table> + )} + <div className="mt-1 flex items-start gap-2"> + <textarea + className="min-h-12 flex-1 font-mono" + value={paste} + placeholder={"paste the lines: who: words | time ([right] for her side, - words for none, [redact] never shown)"} + onChange={(e) => setPaste(e.target.value)} + data-post-screen-paste="" + /> + <button + type="button" + className="ink-link" + disabled={!paste.trim()} + onClick={() => { + const lines = paste.split(/\r?\n/).map(lineOfText).filter((x): x is Line => !!x); + setLines((old) => [...old, ...lines]); + setPaste(""); + }} + data-post-screen-paste-add="" + > + Add the lines + </button> + </div> + {entry.narration === undefined && <p className="m-0 mt-1 text-text-2">not narrated: a screen is drawn and read with the item&apos;s read</p>} + </div> + ); +} diff --git a/umtool/lib/report/castProject.mjs b/umtool/lib/report/castProject.mjs @@ -184,6 +184,13 @@ export function threadArgvOf(read, { handles = [], author = null, takes = null } const at = Array.isArray(takes) ? takes.findIndex((t) => t?.file === read.postTake.file) : -1; a.push("--post-take", String(at >= 0 ? at + 1 : read.postTake.n)); } + // Its screens (post-screens.mjs): left out, or lines from takes (found again by their files). + if (read.screens === false) a.push("--no-screens"); + for (const [r, x] of Object.entries(read.lineTakes ?? {})) { + if (typeof x?.file !== "string") continue; + const at = Array.isArray(takes) ? takes.findIndex((t) => t?.file === x.file) : -1; + a.push("--line-take", `${r}=${at >= 0 ? at + 1 : x.n}`); + } return a; } diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -2898,7 +2898,7 @@ export async function insertEntries(dir, afterId, specs, { token = null, op = "i } /** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */ -export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress", "pictureOnly", "excerpt"]); +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "panel", "redact", "follow", "thread", "scene", "progress", "pictureOnly", "excerpt", "screens"]); /** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript, its censoring blur. */ export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words", "blur", "enter"]); /** A context post's knobs (`quoted`, `parents[i]`): the operator's paraphrase of its words. */ @@ -2993,6 +2993,7 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { if (isObj(patch.media)) { const drop = new Set(Object.entries(patch.media).filter(([, v]) => v === null).map(([k2]) => Number(k2))); if (drop.size) { + remapScreens(e, drop, id); e.media = (e.media ?? []).filter((_, n) => !drop.has(n)); if (!e.media.length) delete e.media; } @@ -3012,6 +3013,7 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { const show = patch.mediaShow !== undefined ? idx(patch.mediaShow, "mediaShow") : new Set(); for (const n of hide) if (!isObj(on[n])) throw new Error(`${id} shows no attachment ${n}${on.length ? ` (0–${on.length - 1})` : ""}`); for (const n of show) if (!isObj(off[n])) throw new Error(`${id} has no attachment switched off at ${n}${off.length ? ` (0–${off.length - 1})` : ""}`); + remapScreens(e, hide, id); const media = [...on.filter((_, n) => !hide.has(n)), ...off.filter((_, n) => show.has(n))]; const mediaOff = [...off.filter((_, n) => !show.has(n)), ...on.filter((_, n) => hide.has(n))]; if (media.length) e.media = media; @@ -3099,19 +3101,34 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) { } // NEVER NARRATE HIDDEN TEXT (post-thread.mjs): a change to what the card shows that leaves a part of its read // off the screen is refused, with the fix (one it had before is the guard's, not this write's). - if ("thread" in patch || "follow" in patch || "parents" in patch || "links" in patch || "linksAdd" in patch) { + if ("thread" in patch || "follow" in patch || "parents" in patch || "links" in patch || "linksAdd" in patch || "screens" in patch || (isObj(patch.media) && Object.values(patch.media).includes(null)) || "mediaHide" in patch) { // With the item before it and the scene its run leaves on screen (post-conversation.mjs; a fresh list, so never // a context worked out before this write). const ctx = planContext(m.timeline.slice(), i, m.render); const guard = (x) => threadReadErrors(x, m.render, { ...ctx, followOn: followKnobs(x, m.render).on }); const had = new Set(guard(was)); - const now = guard(e).filter((x) => !had.has(x)); + // A SCREEN's line the picked take reads that the screen no longer reads (post-screens.mjs) is the build's to refuse, + // not this write's: the read is re-made FROM the screens (umtool posts screen <p> <item> read), so they change first. + const now = guard(e).filter((x) => !had.has(x) && !/ reads (?:line \d+ of )?screen [a-z0-9-]+,/.test(x)); if (now.length) throw new StructureRefused(now); } return { id, at: i, entry: e }; }); } +/** + * ITS SCREENS (post-screens.mjs) as attachments `drop` leave the item: a screen in one of them REFUSES the write (remove + * the screen first); the others' indices move down past the ones that go. In place. + */ +function remapScreens(e, drop, id) { + if (!Array.isArray(e.screens) || !drop.size) return; + for (const sc of e.screens) { + if (!isObj(sc) || !Number.isInteger(sc.media)) continue; + if (drop.has(sc.media)) throw new StructureRefused([`${id}: attachment ${sc.media} carries screen ${sc.id} -- remove the screen first (umtool posts screen <p> ${id} rm ${sc.id})`]); + } + for (const sc of e.screens) if (isObj(sc) && Number.isInteger(sc.media)) sc.media -= [...drop].filter((n) => n < sc.media).length; +} + // ---- the combo counter (report-to-video/post-combo.mjs) -------------------- /** diff --git a/umtool/lib/report/postNarrationCli.mjs b/umtool/lib/report/postNarrationCli.mjs @@ -54,7 +54,8 @@ export const NARRATE_USAGE = [ " umtool posts narrate <project> <item> --derive <n> --op enhance|convert [--engine e] [--voice v] [--as <character>]", " [--pitch target|source|contour] [--semitones <n>]", " umtool posts narrate <project> <item> --take --thread [--parents 0|all|none|<n>] [--skip-parent <id>]… [--no-quoted]", - " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--speed s] [--post-take <n>] [--force] [--dry-run]", + " [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--speed s] [--post-take <n>]", + " [--no-screens] [--line-take screen:<id>:<line>=<n>]… [--force] [--dry-run]", " umtool posts narrate <project> <item> … --in-take <take> any of these on a TAKE of the project: the pick, a new", " read (--take, --thread), the script, the mix -- written into the take's patch (umtool posts --help)", " umtool posts narrate <project> --all --draft-scripts [--force] | --all --take [--limit N]", @@ -230,7 +231,7 @@ export function normalizeParts(raw) { seconds: r3(p.seconds), ...(Number.isFinite(Number(p.gapBefore)) ? { gapBefore: r3(p.gapBefore) } : {}), // The text it reads (post-thread.mjs), the voice and the piece the batch read it in. - ...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role) ? { role: p.role } : {}), + ...(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role) ? { role: p.role } : {}), ...(typeof p.voice === "string" && /^[A-Za-z0-9][A-Za-z0-9_.+-]{0,63}$/.test(p.voice) ? { voice: p.voice } : {}), ...(typeof p.engine === "string" && /^(orpheus|kokoro|espeak-ng)$/.test(p.engine) ? { engine: p.engine } : {}), ...(Number.isInteger(p.piece) && p.piece >= 0 ? { piece: p.piece } : {}), @@ -695,9 +696,11 @@ export async function narrateCommand(project, words, flags, { json = false, dryR voice: str("--voice"), engine: str("--engine"), speed: speedFlag(str), note: str("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, // His own line from an existing take (its number as --list shows it), the context synthesized around it. postTake: str("--post-take"), + // ITS SCREENS (post-screens.mjs): read after his words unless --no-screens; a line from a take (--line-take). + screens: !flags.has("--no-screens"), lineTakes: lineTakesOf(multi("--line-take")), }); } - if (str("--post-take") !== null) throw new NarrateError("--post-take is a thread read's (umtool posts narrate <p> <item> --take --thread --post-take <n>)"); + if (str("--post-take") !== null || multi("--line-take").length) throw new NarrateError("--post-take and --line-take are a thread read's (umtool posts narrate <p> <item> --take --thread --post-take <n>)"); if (flags.has("--thread")) throw new NarrateError("--thread goes with --take (umtool posts narrate <p> <item> --take --thread)"); if (flags.has("--take")) { const r = await makeTake(project, e, { @@ -731,6 +734,17 @@ export async function narrateCommand(project, words, flags, { json = false, dryR return 0; } +/** `--line-take screen:<id>:<n>=<take n>` words as `{ <role>: <take n> }`; throws naming a bad one. */ +export function lineTakesOf(list) { + const out = {}; + for (const raw of (Array.isArray(list) ? list : []).flatMap((x) => String(x).split(",")).map((x) => x.trim()).filter(Boolean)) { + const m = /^(screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})=(\d{1,3})$/.exec(raw); + if (!m) throw new NarrateError(`--line-take takes screen:<id>:<line>=<take n> (got ${raw})`); + out[m[1]] = Number(m[2]); + } + return out; +} + export const CHARACTER_USAGE = [ "usage: umtool posts character <project> <item> [<character> | --clear] [--json]", " THE CHARACTER ONE POST ITEM's OWN READ IS MADE WITH (its `narration.character`): the id of one of this video's", diff --git a/umtool/lib/report/postPause.mjs b/umtool/lib/report/postPause.mjs @@ -62,7 +62,7 @@ export const PAUSE_CUT_BACK = 0.04; export const PAUSE_FADE = 0.01; /** How far either side of an @time pause the quietest cut is looked for, seconds. */ export const PAUSE_PIN_WINDOW = 0.15; -const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; /** A pause the plan cannot make (no word timings, the word not read, nothing to change): exit 1, not a usage error. */ export class PauseError extends Error { diff --git a/umtool/lib/report/postSay.mjs b/umtool/lib/report/postSay.mjs @@ -198,6 +198,9 @@ export function threadArgsOf(read) { if (read.seen === true) a.push("--read-seen"); for (const [h, v] of Object.entries(read.voiceFor ?? {})) a.push(`--voice-for ${q(`${h}=${v}`)}`); if (read.voice) a.push(`--voice ${q(read.voice)}`); + // Its screens (post-screens.mjs): left out, or lines from takes -- by their numbers then (the files are in the record). + if (read.screens === false) a.push("--no-screens"); + for (const [r, x] of Object.entries(read.lineTakes ?? {})) if (Number.isInteger(x?.n)) a.push(`--line-take ${q(`${r}=${x.n}`)}`); return a.length ? ` ${a.join(" ")}` : ""; } diff --git a/umtool/lib/report/postScreens.test.mjs b/umtool/lib/report/postScreens.test.mjs @@ -0,0 +1,183 @@ +// A post's SCREENS from the CLI and in the read (postScreensCli.mjs, postThreadRead.mjs; post-screens.mjs): the text +// lines a person pastes, the `set` keys, the writer (one write, refused in the build's words; an attachment a screen +// is in cannot go, the others' indices follow), check / rm / list, and the THREAD READ with screens -- each line in +// its speaker's voice, her own lines in hers, a line from an existing take (--line-take), her own line from the take +// that plays (never made again), the short pause between lines, --no-screens. No editor (a stub tts); temp dirs. +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { encodeWav16 } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; +import { VOICE_A, VOICE_B, syntheticVoice, withSilence } from "yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs"; +import { postsCommand } from "./postsCli.mjs"; +import { applyPairs, defaultPostTake, lineOfText, linesOfText } from "./postScreensCli.mjs"; +import { characterNames, joinTimes, readParts, threadReadPlan, threadTake } from "./postThreadRead.mjs"; +import { threadArgsOf } from "./postSay.mjs"; +import { threadArgvOf } from "./castProject.mjs"; +import { updatePostItem } from "./manifest.mjs"; +import { threadReadErrors } from "umtool-report-to-video/post-thread"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-screens-")); +after(() => rm(ROOT, { recursive: true, force: true })); +const wavOf = async (file, voice, seconds = 1.2) => { + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, encodeWav16(withSilence(syntheticVoice({ ...voice, seconds }), { before: 0.1, after: 0.1 }))); +}; +const stubAsk = (asked) => async (body) => { + asked.push(body); + await wavOf(body.out, VOICE_B, 0.6); + return { jobId: `job-${asked.length}`, result: { wav: body.out } }; +}; +const NO_RED = { terms: [], markup: {}, slurs: null }; +const VID = { src: "posts-media/savvy-x/2117/2117_1.mp4", kind: "video", width: 1920, height: 1080, seconds: 61.742, audio: true }; +const IMG = { src: "posts-media/savvy-x/2117/2117_2.jpg", kind: "image", width: 900, height: 1400 }; +const T1 = { file: "narration/posts/2117/take-1.recorded.wav", engine: "recorded", voice: "operator", seconds: 1.4, script: "Hey, you told me. Your turn.", source: { kind: "recorded", voice: "operator" } }; +const T2 = { file: "narration/posts/2117/take-2.recorded-tq.wav", engine: "recorded", voice: "tq", seconds: 1.0, script: "You can't be this dumb", source: { kind: "recorded", voice: "tq" } }; +const ITEM = { + type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", + text: "Hey, you told me. Your turn.", subjects: ["MadamSavvy"], media: [VID, IMG], + narration: { script: "Hey, you told me. Your turn.", takes: [T1, T2], pick: 0 }, +}; + +async function project(name, item = ITEM) { + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + for (const t of item.narration?.takes ?? []) await wavOf(path.join(dir, t.file), VOICE_A, 1); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: name, title: name, provenance: { channelsDir: "../channels", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, postNarration: { engine: "kokoro", voice: "af_heart" } }, + timeline: [item], + }, null, 2)); + await mkdir(path.join(dir, "narration"), { recursive: true }); + await writeFile(path.join(dir, "narration", "voices.json"), JSON.stringify({ thequartering: "kokoro:am_michael" })); + return { id: name, dir }; +} +const read = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8")); +const posts = async (args) => { + const lines = []; + const code = await postsCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(s) }); + return { code, text: lines.join("\n"), json: () => JSON.parse(lines.join("\n")) }; +}; + +test("text lines as a person pastes them: `[right] who: words | time`, `- words`, `[redact] …`", () => { + assert.deepEqual(lineOfText("TheQuartering: what's your email | 11:32 AM"), { who: "TheQuartering", text: "what's your email", time: "11:32 AM" }); + assert.deepEqual(lineOfText("[right] MadamSavvy: where is my scale video"), { who: "MadamSavvy", side: "right", text: "where is my scale video" }); + assert.deepEqual(lineOfText("- Total amount refunded: $99.95"), { text: "Total amount refunded: $99.95" }); + assert.deepEqual(lineOfText("[redact] Order #4419283"), { text: "Order #4419283", redact: true }); + assert.deepEqual(lineOfText("see https://x.com/a"), { text: "see https://x.com/a" }); + assert.equal(linesOfText("a: b\n\n \nc: d\n").length, 2); +}); + +test("set keys: kind, title, at, read, an excerpt, a line's who / side / redact, a line added and one removed (the read follows)", () => { + const sc = { id: "s1", media: 0, at: [1, 2], kind: "dm", read: "all", lines: [{ who: "a", text: "one two three" }, { who: "b", text: "four" }, { who: "a", text: "five six" }] }; + const x = applyPairs(sc, ["kind=text", "title=\"A note\"", "at=3.5,8", "read=0,2", "read.0=\"two three\"", "line.1.side=right", "line.1.redact=on", "line.add=\"c: seven\""]); + assert.deepEqual([x.kind, x.title, x.at], ["text", "A note", [3.5, 8]]); + assert.deepEqual(x.read, [{ line: 0, text: "two three" }, { line: 2 }]); + assert.deepEqual(x.lines[1], { who: "b", text: "four", side: "right", redact: true }); + assert.deepEqual(x.lines[3], { who: "c", text: "seven" }); + const y = applyPairs(x, ["line.0=off"]); + assert.deepEqual(y.read, [{ line: 1 }]); + assert.equal(y.lines[0].who, "b"); + assert.throws(() => applyPairs(sc, ["colour=red"]), /not a screen's knob/); + assert.throws(() => applyPairs(sc, ["line.9.who=x"]), /the screen has lines 0–2/); + assert.equal(sc.kind, "dm", "a copy"); +}); + +test("the CLI: add from a pasted file, list, set, check, rm -- one write each, refused in the build's words; the item's attachments guarded", async () => { + const p = await project("cli"); + const file = path.join(ROOT, "s1.txt"); + await writeFile(file, "TheQuartering: what's your email so I can refund your order | 11:32 AM\nMadamSavvy: where is my scale video | 11:53 AM\nTheQuartering: You can't be this dumb\n"); + let r = await posts(["screen", "cli", "p-2117", "add", "--media", "0", "--at", "3.5,8", "--kind", "dm", "--from", file, "--json"]); + assert.equal(r.code, 0, r.text); + const j = r.json(); + assert.equal(j.screens[0].id, "s1"); + assert.equal(j.screens[0].lines.length, 3); + assert.ok(j.warnings.some((w) => /transcription not checked/.test(w))); + assert.ok(j.warnings.some((w) => /does not read screen s1/.test(w))); + r = await posts(["screen", "cli", "p-2117", "add", "--media", "1", "--kind", "email", "--line", "coffee: Some items in your order have been refunded", "--line", "- Order number 4419283", "--read", "0"]); + assert.equal(r.code, 0, r.text); + assert.match(r.text, /added screen s2/); + assert.match(r.text, /NOT CHECKED/); + // Refused in the build's words: an excerpt not in the line. + r = await posts(["screen", "cli", "p-2117", "set", "s1", "read.0=\"refund my email\""]); + assert.equal(r.code, 1); + assert.match(r.text, /is not a run of line 0's words/); + r = await posts(["screen", "cli", "p-2117", "check", "s1", "--by", "op"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens[0].checked.by, "op"); + // A word changed: the check goes. + r = await posts(["screen", "cli", "p-2117", "set", "s1", "line.2.text=You cant be this dumb"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens[0].checked, undefined); + r = await posts(["screen", "cli", "p-2117", "list"]); + assert.match(r.text, /s1 {2}dm {2}attachment 0 \(video\) at 3\.5–8 s/); + assert.match(r.text, /\* {2}0 TheQuartering: what's your email/); + // The attachment a screen is in cannot go; one before it moves its index. + await assert.rejects(() => updatePostItem(p.dir, "p-2117", { media: { 1: null } }), /attachment 1 carries screen s2/); + r = await posts(["screen", "cli", "p-2117", "rm", "s2"]); + assert.equal(r.code, 0, r.text); + await updatePostItem(p.dir, "p-2117", { mediaAdd: [IMG] }); + await updatePostItem(p.dir, "p-2117", { media: { 0: null } }).catch((e) => assert.match(String(e.errors ?? e.message), /attachment 0 carries screen s1/)); + // --dry-run checks and writes nothing. + r = await posts(["screen", "cli", "p-2117", "add", "--media", "1", "--kind", "dm", "--line", "a: b", "--dry-run"]); + assert.equal(r.code, 0, r.text); + assert.equal((await read(p)).timeline[0].screens.length, 1); + r = await posts(["screen", "cli", "p-2117", "frob"]); + assert.equal(r.code, 2); +}); + +test("the read: after her words, each line in its speaker's voice (hers in hers), a character's name resolved, --no-screens, the pauses", async () => { + const e = { ...ITEM, screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order" }, + { who: "MadamSavvy", text: "where is my scale video" }, + { who: "Jeremy", text: "You can't be this dumb" }, + ] }] }; + const m = { render: { postNarration: { engine: "kokoro", voice: "af_heart" } }, timeline: [e] }; + const plan = threadReadPlan(m, e, { red: NO_RED, map: { thequartering: "kokoro:am_michael" }, names: characterNames({ cast: { characters: [{ id: "tq", name: "Jeremy", handles: ["TheQuartering"] }] } }) }); + assert.deepEqual(plan.pieces.map((p) => [p.role, p.voice]), [["post", "af_heart"], ["screen:s1:0", "am_michael"], ["screen:s1:1", "af_heart"], ["screen:s1:2", "am_michael"]]); + assert.equal(threadReadPlan(m, e, { red: NO_RED, screens: false }).pieces.length, 1); + const parts = readParts(plan); + const { meta } = joinTimes(parts, parts.map(() => 1)); + assert.deepEqual(meta.map((x) => x.gapBefore), [0, 0.8, 0.35, 0.35]); + assert.deepEqual(meta.map((x) => x.role), ["post", "screen:s1:0", "screen:s1:1", "screen:s1:2"]); +}); + +test("the read made: her line from the take that plays (not made again), a line from a recorded take (--line-take), each part's role stored; the guard is quiet", async () => { + const item = { ...ITEM, screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order" }, + { who: "MadamSavvy", text: "where is my scale video" }, + { who: "TheQuartering", text: "You can't be this dumb" }, + ] }] }; + const p = await project("made", item); + assert.equal(defaultPostTake(item), 1); + const asked = []; + const r = await threadTake(p, (await read(p)).timeline[0], { red: NO_RED, ask: stubAsk(asked), lanes: null, postTake: defaultPostTake(item), lineTakes: { "screen:s1:2": 2 } }); + assert.equal(asked.length, 2, "only the two lines no take reads are synthesized"); + const take = r.take; + assert.deepEqual(take.parts.map((x) => [x.role, x.take ?? null]), [["post", "take-1.recorded"], ["screen:s1:0", null], ["screen:s1:1", null], ["screen:s1:2", "take-2.recorded-tq"]]); + assert.equal(take.parts[3].text, "You can't be this dumb"); + assert.deepEqual(take.read.lineTakes, { "screen:s1:2": { n: 2, file: T2.file } }); + assert.equal(take.read.postTake.file, T1.file); + const after1 = (await read(p)).timeline[0]; + assert.deepEqual(threadReadErrors(after1, {}), []); + // Asked again: up to date (the same takes, the same words). + const again = await threadTake(p, after1, { red: NO_RED, ask: stubAsk(asked), lanes: null, postTake: defaultPostTake(after1), lineTakes: { "screen:s1:2": 2 } }); + assert.equal(again.upToDate, true); + // The flags that ask for it again carry the line take; the default for her own line is the take the thread read used. + assert.match(threadArgsOf(take.read), /--line-take screen:s1:2=2/); + assert.deepEqual(threadArgvOf(take.read, { takes: after1.narration.takes }).slice(-4), ["--post-take", "1", "--line-take", "screen:s1:2=2"]); + assert.equal(defaultPostTake(after1), 1); + // A line take that is a thread read, or out of range, is refused. + await assert.rejects(() => threadTake(p, after1, { red: NO_RED, ask: stubAsk(asked), lanes: null, lineTakes: { "screen:s1:2": 9 } }), /--line-take screen:s1:2=/); +}); + +test("the CLI's read: `posts screen <p> <item> read --dry-run` lists the pieces, her line from the take that plays", async () => { + const item = { ...ITEM, screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: [{ line: 0 }], lines: [{ who: "TheQuartering", text: "what's your email" }] }] }; + await project("dry", item); + const r = await posts(["screen", "dry", "p-2117", "read", "--dry-run", "--json"]); + assert.equal(r.code, 0, r.text); + const j = r.json(); + assert.deepEqual(j.pieces.map((x) => [x.role, x.take?.n ?? null]), [["post", 1], ["screen:s1:0", null]]); + assert.equal(j.pieces[1].voice, "am_michael"); +}); diff --git a/umtool/lib/report/postScreensCli.mjs b/umtool/lib/report/postScreensCli.mjs @@ -0,0 +1,385 @@ +// `umtool posts screen` -- A POST's SCREENS from the CLI (report-to-video/post-screens.mjs; docs/report-video.md, +// "Screens: text screenshots read as part of the post"): the text screenshots a post carries, transcribed once, drawn +// on its card and read -- whole or in excerpts -- in the voices of the people in them. +// +// umtool posts screen <p> <item> list [--json] +// umtool posts screen <p> <item> add --media <i> [--at <from>,<to>] --kind dm|email|post|text [--id <id>] [--title "…"] +// [--from <file>] [--line "who: words"]… [--read all|none|<n>,<n>…] [--unread omit|dim] +// [--ref <channel>/<postId>] [--json] +// umtool posts screen <p> <item> set <id> <key>=<value>… [--from <file>] [--json] +// umtool posts screen <p> <item> rm <id> [--json] +// umtool posts screen <p> <item> check <id> [--by <name>] [--undo] [--json] +// umtool posts screen <p> <item> read [--post-take <n>] [--line-take screen:<id>:<n>=<take n>]… [--force] [--dry-run] [--json] … +// +// Every write goes through the post item's one writer (manifest.mjs updatePostItem, `screens`: the whole list, under +// the manifest's token), refused in the build's words. `read` is the thread read (postThreadRead.mjs) with the screens: +// his own line from the take that plays when it is not a thread read (or the one the thread read used), so a recorded +// or picked read of his words is never made again. +// +// --from <file>: a JSON screen (or { lines: […] }, or a list of lines), or TEXT, one line per line: +// [right] who: words | time `[right]`/`[left]` the side; `who:` the speaker; `| time` the time shown +// - words a line with no speaker; [redact] … a line never drawn nor read +// Plain ESM: the CLI runs it under bare node. +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { manifestToken, updatePostItem } from "./manifest.mjs"; +import { SCREEN_KINDS, SCREEN_SIDES, SCREEN_UNREAD, screenReadLines, screenRows, screenWarnings, screensOf, validateScreens } from "umtool-report-to-video/post-screens"; + +export const SCREEN_USAGE = [ + "usage: umtool posts screen <project> <item> list [--json]", + " umtool posts screen <project> <item> add --media <i> [--at <from>,<to>] --kind dm|email|post|text [--id <id>] [--title \"…\"]", + " [--from <file>] [--line \"who: words\"]… [--read all|none|<n>,<n>…] [--unread omit|dim] [--ref <channel>/<postId>] [--json]", + " umtool posts screen <project> <item> set <id> <key>=<value>… [--from <file>] [--json]", + " umtool posts screen <project> <item> rm <id> [--json]", + " umtool posts screen <project> <item> check <id> [--by <name>] [--undo] [--json]", + " umtool posts screen <project> <item> read [--post-take <n>] [--line-take screen:<id>:<line>=<n>]… [--voice-for h=v]… [--force] [--dry-run] [--json]", + " A post's SCREENS: the text screenshots it carries (a DM exchange or an email in its video, a screenshot attached),", + " transcribed once, drawn on its card and read in the voices of the people in them, each line lit while it is said.", + " --media: the attachment it is in (its index); --at: the seconds of a video it is visible in. --read: the lines read", + " (all; none: transcribed only, not drawn); --unread: the lines not read left out (omit) or drawn dim. --from: a JSON", + " screen, or text lines `[right] who: words | time` (`- words`: no speaker; `[redact] …`: never drawn nor read).", + " set keys: kind= title=|off media= at=<a>,<b>|off unread= ref=|off read=all|none|<n>,… read.<n>=\"excerpt\"|on|off", + " line.add=\"who: words\" line.<n>=off line.<n>.who=|off line.<n>.side=left|right|auto line.<n>.text=", + " line.<n>.time=|off line.<n>.redact=on|off", + " check: the transcription read against the screenshot (by you, now); --undo takes it back. A screen not checked is a", + " lint WARNING. An e-mail address, a phone number, an order or reference number in a line is masked whatever you do.", + " read: the thread read with the screens (posts narrate <p> <item> --take --thread): his words from the take that plays", + " (--post-take n: another), each read line in its speaker's voice; --line-take: that line from the item's take n.", +].join("\n"); + +export class ScreenUsageError extends Error { + constructor(message) { + super(message); + this.name = "ScreenUsageError"; + } +} + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const unq = (v) => String(v).replace(/^"(.*)"$/s, "$1"); +const fail = (m) => { + throw new ScreenUsageError(m); +}; + +/** One line of TEXT as a screen line: `[right] who: words | time`, `- words`, `[redact] …`. Null: a blank line. */ +export function lineOfText(raw) { + let t = String(raw).trim(); + if (!t) return null; + const out = {}; + for (;;) { + const m = /^\[(left|right|redact)\]\s*/i.exec(t); + if (!m) break; + if (m[1].toLowerCase() === "redact") out.redact = true; + else out.side = m[1].toLowerCase(); + t = t.slice(m[0].length); + } + const bar = t.lastIndexOf(" | "); + if (bar > 0) { + out.time = t.slice(bar + 3).trim(); + t = t.slice(0, bar).trim(); + } + if (t.startsWith("- ")) t = t.slice(2); + else { + const c = /^([^:]{1,64}?):\s+(.*)$/s.exec(t); + if (c && !/^https?$/i.test(c[1])) { + out.who = c[1].trim(); + t = c[2]; + } + } + return { ...(out.who ? { who: out.who } : {}), ...(out.side ? { side: out.side } : {}), text: t.trim(), ...(out.time ? { time: out.time } : {}), ...(out.redact ? { redact: true } : {}) }; +} + +/** Lines of TEXT as screen lines. */ +export const linesOfText = (text) => String(text).split(/\r?\n/).map(lineOfText).filter(Boolean); + +/** What `--from <file>` holds: `{ screen?: {…}, lines?: […] }` (JSON: a screen, { lines }, or a list of lines; else text lines). */ +export async function readFrom(file) { + const raw = await readFile(file, "utf8").catch(() => fail(`--from ${file}: not there`)); + const t = raw.trim(); + if (t.startsWith("{") || t.startsWith("[")) { + let v; + try { + v = JSON.parse(t); + } catch (e) { + fail(`--from ${file}: not JSON (${e instanceof Error ? e.message : e})`); + } + if (Array.isArray(v)) return { lines: v.map((l) => (typeof l === "string" ? lineOfText(l) : l)).filter(Boolean) }; + if (isObj(v) && Array.isArray(v.lines) && Object.keys(v).length === 1) return { lines: v.lines }; + if (isObj(v)) return { screen: v }; + fail(`--from ${file}: a screen, { lines }, or a list of lines`); + } + return { lines: linesOfText(raw) }; +} + +const numList = (v, what) => { + const parts = String(v).split(",").map((x) => x.trim()).filter(Boolean); + if (!parts.length || !parts.every((x) => /^\d{1,2}$/.test(x))) fail(`${what} takes line numbers (0, 1, …) separated by commas`); + return parts.map(Number); +}; +const span = (v) => { + const m = /^\s*(\d+(?:\.\d+)?)\s*[,-]\s*(\d+(?:\.\d+)?)\s*$/.exec(String(v)); + if (!m) fail(`at takes <from>,<to> (seconds of the video: 3.5,8)`); + return [Math.round(Number(m[1]) * 100) / 100, Math.round(Number(m[2]) * 100) / 100]; +}; +const readOf = (v) => (v === "all" || v === "none" ? v : numList(v, "read").map((line) => ({ line }))); + +/** + * A screen with `key=value` pairs laid on (the `set` keys, SCREEN_USAGE), pure; a copy. Throws ScreenUsageError for a + * key it does not know or a value it cannot read; what the build refuses is the writer's to say. + */ +export function applyPairs(screen, pairs) { + const sc = JSON.parse(JSON.stringify(screen)); + sc.lines = Array.isArray(sc.lines) ? sc.lines : []; + const lineAt = (n) => { + if (!isObj(sc.lines[n])) fail(`line ${n}: the screen has lines 0–${sc.lines.length - 1}`); + return sc.lines[n]; + }; + const drops = []; + for (const pair of pairs) { + const eq = pair.indexOf("="); + if (eq < 1) fail(`${pair}: <key>=<value> (posts screen --help)`); + const key = pair.slice(0, eq); + const v = unq(pair.slice(eq + 1)); + const off = v === "off" || v === ""; + let m; + if (key === "kind") { + if (!SCREEN_KINDS.includes(v)) fail(`kind= takes ${SCREEN_KINDS.join(", ")}`); + sc.kind = v; + } else if (key === "title") { + if (off) delete sc.title; + else sc.title = v; + } else if (key === "media") { + if (!/^\d$/.test(v)) fail("media= takes the attachment's index (0, 1, …)"); + sc.media = Number(v); + } else if (key === "at") { + if (off) delete sc.at; + else sc.at = span(v); + } else if (key === "unread") { + if (!SCREEN_UNREAD.includes(v)) fail(`unread= takes ${SCREEN_UNREAD.join(" or ")}`); + sc.unread = v; + } else if (key === "ref") { + if (off) delete sc.ref; + else sc.ref = v; + } else if (key === "read") { + sc.read = readOf(v); + } else if ((m = /^read\.(\d{1,2})$/.exec(key))) { + const n = Number(m[1]); + lineAt(n); + const list = sc.read === "all" ? sc.lines.map((l, i) => (isObj(l) && l.redact !== true ? { line: i } : null)).filter(Boolean) : Array.isArray(sc.read) ? sc.read : []; + const rest = list.filter((x) => x?.line !== n); + if (v === "off") sc.read = rest; + else sc.read = [...rest, v === "on" ? { line: n } : { line: n, text: v }].sort((a, b) => a.line - b.line); + } else if (key === "line.add") { + const l = lineOfText(v); + if (!l) fail("line.add= takes a line (who: words)"); + sc.lines.push(l); + } else if ((m = /^line\.(\d{1,2})$/.exec(key))) { + if (v !== "off") fail(`${key}= takes off (the line removed; line.${m[1]}.text= to change its words)`); + lineAt(Number(m[1])); + drops.push(Number(m[1])); + } else if ((m = /^line\.(\d{1,2})\.(who|side|text|time|redact)$/.exec(key))) { + const l = lineAt(Number(m[1])); + const f = m[2]; + if (f === "side") { + if (v === "auto") delete l.side; + else if (!SCREEN_SIDES.includes(v)) fail(`${key}= takes left, right or auto`); + else l.side = v; + } else if (f === "redact") { + if (v === "on") l.redact = true; + else if (v === "off") delete l.redact; + else fail(`${key}= takes on or off`); + } else if (f === "text") l.text = v; + else if (off) delete l[f]; + else l[f] = v; + } else fail(`${key} is not a screen's knob (posts screen --help)`); + } + if (drops.length) { + // Lines removed: the read's line numbers follow them (a dropped line's read goes too). + const gone = new Set(drops); + const to = (n) => n - drops.filter((d) => d < n).length; + if (Array.isArray(sc.read)) sc.read = sc.read.filter((x) => !gone.has(x?.line)).map((x) => ({ ...x, line: to(x.line) })); + sc.lines = sc.lines.filter((_, n) => !gone.has(n)); + } + return sc; +} + +/** The next free screen id of an item: s1, s2, … */ +export function nextScreenId(e) { + const have = new Set(screensOf(e).map((s) => s.id)); + for (let n = 1; ; n += 1) if (!have.has(`s${n}`)) return `s${n}`; +} + +/** One screen as listing lines (text). */ +export function screenListing(e, sc) { + const reads = new Map(screenReadLines(sc).map((r) => [r.n, r])); + const m = (Array.isArray(e.media) ? e.media : [])[sc.media]; + const head = `${sc.id} ${sc.kind}${sc.title ? ` "${sc.title}"` : ""} attachment ${sc.media}${m ? ` (${m.kind})` : ""}${Array.isArray(sc.at) ? ` at ${sc.at[0]}–${sc.at[1]} s` : ""} read ${sc.read === "all" ? "all" : sc.read === "none" ? "none (transcribed only)" : `${reads.size} line(s)`}${sc.unread === "dim" ? ", the rest dim" : ""} ${sc.checked ? `checked by ${sc.checked.by} ${String(sc.checked.at).slice(0, 10)}` : "NOT CHECKED"}`; + const rows = sc.lines.map((l, n) => { + const r = reads.get(n); + const mark = l?.redact ? "x" : r ? (r.cutBefore || r.cutAfter ? "~" : "*") : " "; + const ex = r && (r.cutBefore || r.cutAfter) ? ` [reads: "${str(l.text).slice(r.start, r.end)}"]` : ""; + return ` ${mark} ${String(n).padStart(2)} ${(l?.side ? `[${l.side}] ` : "") + (l?.who ? `${l.who}: ` : "- ")}${l?.redact ? "(redacted)" : str(l?.text)}${l?.time ? ` | ${l.time}` : ""}${ex}`; + }); + return [head, ...rows]; +} + +/** + * `umtool posts screen <p> <item> <verb> …`. `project` is resolved; `rest` the words after the project + * (`<item> <verb> [<id>] [pairs…]`); `opt` the posts command's flags and helpers. + */ +export async function screenCommand(project, rest, { flags, str: flag, multi, json = false, out = (s) => console.log(s), dryRun = false }) { + const [ref, verb, ...words] = rest; + if (!ref || !verb || flags.has("--help")) { + out(SCREEN_USAGE); + return 2; + } + const manifest = await readManifest(project.dir); + if (!manifest) throw new ScreenUsageError(`${project.id} has no manifest`); + const tl = Array.isArray(manifest.timeline) ? manifest.timeline : []; + const e = tl.find((x) => x?.type === "post" && (x.id === ref || String(x.post ?? "").split("/")[1] === ref)); + if (!e) throw new ScreenUsageError(`no post item ${ref} in ${project.id} (its id, or the post's id)`); + const screens = screensOf(e); + const write = async (next, what) => { + const { result, editNotes } = await withEditNotes(project, async () => updatePostItem(project.dir, e.id, { screens: next.length ? next : null }, { token: await manifestToken(project.dir) })); + const entry = result.entry; + const { pickedTake, isNarrated } = await import("umtool-report-to-video/post-narration"); + const { partRoles } = await import("umtool-report-to-video/post-thread"); + const warnings = screenWarnings(entry, { narrated: isNarrated(entry), takeRoles: pickedTake(entry) ? partRoles(entry).map((r) => r.role) : [] }); + const { threadReadErrors } = await import("umtool-report-to-video/post-thread"); + const { followKnobs } = await import("umtool-report-to-video/read-follow"); + const { planContext } = await import("umtool-report-to-video/post-conversation"); + const m2 = await readManifest(project.dir); + const i = (m2?.timeline ?? []).findIndex((x) => x?.id === e.id); + const at = i >= 0 ? m2.timeline[i] : null; + const refused = at && isNarrated(at) ? threadReadErrors(at, m2.render ?? {}, { ...planContext(m2.timeline, i, m2.render ?? {}), followOn: followKnobs(at, m2.render ?? {}).on }) : []; + if (json) { + out(JSON.stringify({ ok: true, id: e.id, what, screens: entry.screens ?? [], warnings, refusedUntilRead: refused, token: result.token, editNotes }, null, 2)); + return 0; + } + out(`${e.id}: ${what}`); + for (const sc of screensOf(entry)) for (const l of screenListing(entry, sc)) out(` ${l}`); + for (const x of refused) out(` the build REFUSES the read as it is until it is re-made (umtool posts screen ${project.id} ${e.id} read): ${x}`); + for (const w of warnings) out(` warning: ${w}`); + if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel} (umtool timeline ${project.id} undo)`); + if (editNotes) out(` edit noted for ${editNotes.generatedBy}`); + return 0; + }; + const byId = (id) => { + if (!id) fail(`which screen? (${screens.map((s) => s.id).join(", ") || "it has none"})`); + const sc = screens.find((s) => s.id === id); + if (!sc) fail(`${e.id} has no screen ${id} (${screens.map((s) => s.id).join(", ") || "none"})`); + return sc; + }; + if (verb === "list") { + if (json) { + out(JSON.stringify({ ok: true, id: e.id, screens, rows: Object.fromEntries(screens.map((s) => [s.id, screenRows(s)])), errors: validateScreens(e), warnings: screenWarnings(e, { narrated: (await import("umtool-report-to-video/post-narration")).isNarrated(e), takeRoles: (await import("umtool-report-to-video/post-thread")).partRoles(e).map((r) => r.role) }) }, null, 2)); + return 0; + } + if (!screens.length) out(`${e.id}: no screens (umtool posts screen ${project.id} ${e.id} add --media <i> --kind dm --from <file>)`); + for (const sc of screens) for (const l of screenListing(e, sc)) out(l); + return 0; + } + if (verb === "add") { + const from = flag("--from") ? await readFrom(path.resolve(String(flag("--from")))) : {}; + const base = from.screen ?? {}; + const id = flag("--id") ?? base.id ?? nextScreenId(e); + if (screens.some((s) => s.id === id)) fail(`${e.id} has a screen ${id} already (set changes it)`); + const lines = [...(from.lines ?? base.lines ?? []), ...multi("--line").map(lineOfText).filter(Boolean)]; + const sc = { + ...base, + id, + ...(flag("--media") !== null ? { media: /^\d$/.test(String(flag("--media"))) ? Number(flag("--media")) : fail("--media takes the attachment's index") } : base.media === undefined ? { media: 0 } : {}), + ...(flag("--at") !== null ? { at: span(flag("--at")) } : {}), + ...(flag("--kind") !== null ? { kind: flag("--kind") } : {}), + ...(flag("--title") !== null ? { title: flag("--title") } : {}), + ...(flag("--ref") !== null ? { ref: flag("--ref") } : {}), + ...(flag("--unread") !== null ? { unread: flag("--unread") } : {}), + source: "transcribed", + lines, + read: flag("--read") !== null ? readOf(flag("--read")) : base.read ?? "all", + }; + if (!sc.kind) fail("--kind dm|email|post|text: what the screenshot is"); + if (dryRun) { + const errs = validateScreens({ ...e, screens: [...screens, sc] }); + out(json ? JSON.stringify({ ok: !errs.length, dryRun: true, screen: sc, errors: errs }, null, 2) : [`would add ${sc.id}:`, ...screenListing(e, sc).map((l) => ` ${l}`), ...errs.map((x) => ` refused: ${x}`)].join("\n")); + return errs.length ? 1 : 0; + } + return write([...screens, sc], `added screen ${sc.id}`); + } + if (verb === "set") { + const sc = byId(words[0]); + let next = sc; + if (flag("--from")) { + const from = await readFrom(path.resolve(String(flag("--from")))); + next = from.screen ? { ...from.screen, id: sc.id } : { ...sc, lines: from.lines ?? sc.lines }; + // New lines: the checked mark goes (it was for the words before). + delete next.checked; + } + const pairs = words.slice(1); + if (!pairs.length && !flag("--from")) fail("set <id> <key>=<value>… (posts screen --help)"); + next = applyPairs(next, pairs); + // Words changed: what was checked is not what is there now. + if (JSON.stringify(next.lines) !== JSON.stringify(sc.lines)) delete next.checked; + return write(screens.map((s) => (s.id === sc.id ? next : s)), `set screen ${sc.id}`); + } + if (verb === "rm") { + const sc = byId(words[0]); + return write(screens.filter((s) => s.id !== sc.id), `removed screen ${sc.id}`); + } + if (verb === "check") { + const sc = byId(words[0]); + const next = { ...sc }; + if (flags.has("--undo")) delete next.checked; + else next.checked = { by: flag("--by") ?? process.env.USER ?? "operator", at: new Date().toISOString() }; + return write(screens.map((s) => (s.id === sc.id ? next : s)), flags.has("--undo") ? `screen ${sc.id}: not checked` : `screen ${sc.id}: checked`); + } + if (verb === "read") { + if (!screens.length) fail(`${e.id} has no screens to read (add one first)`); + const { threadCommand, parentsSelector } = await import("./postThreadRead.mjs"); + const { lineTakesOf } = await import("./postNarrationCli.mjs"); + const { voiceOverridesOf } = await import("umtool-report-to-video/post-say"); + const postTake = flag("--post-take") ?? defaultPostTake(e); + return threadCommand(project, e, { + manifest, json, out, overrides: voiceOverridesOf(multi("--voice-for")), parents: parentsSelector(flag("--parents")), + skip: multi("--skip-parent"), quoted: !flags.has("--no-quoted"), linked: !flags.has("--no-linked"), readSeen: flags.has("--read-seen"), + voice: flag("--voice"), engine: flag("--engine"), note: flag("--note"), force: flags.has("--force"), hold: !flags.has("--no-hold"), dryRun, + postTake, lineTakes: { ...defaultLineTakes(e), ...lineTakesOf(multi("--line-take")) }, + }); + } + fail(`posts screen ${verb}: list, add, set, rm, check or read`); + return 2; +} + +/** + * HIS OWN LINE for a screens read (`read` with no --post-take): the take that plays when it is not a thread read (its + * number, from 1), else the take the thread read that plays used for it (`read.postTake.n`), else none (synthesized; + * from the parts cache when it was before). + */ +export function defaultPostTake(e) { + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + const k = Number.isInteger(e?.narration?.pick) && e.narration.pick >= 0 && e.narration.pick < takes.length ? e.narration.pick : 0; + const t = takes[k]; + if (!t || e?.narration?.off === true) return null; + const thread = /-thread\.wav$/.test(str(t.file)) || t.read?.kind === "thread"; + if (!thread) return k + 1; + const f = str(t.read?.postTake?.file); + // Its number then may have moved: found again by its file. + const at = takes.findIndex((x) => str(x?.file) === f); + return at >= 0 ? at + 1 : null; +} + +/** The lines the playing thread read took from takes (`read.lineTakes`), found again by their files: `{ <role>: n }`. */ +export function defaultLineTakes(e) { + const takes = Array.isArray(e?.narration?.takes) ? e.narration.takes : []; + const k = Number.isInteger(e?.narration?.pick) ? e.narration.pick : 0; + const lt = takes[k]?.read?.lineTakes; + if (!isObj(lt)) return {}; + const out = {}; + for (const [role, x] of Object.entries(lt)) { + const at = takes.findIndex((t) => str(t?.file) === str(x?.file)); + if (at >= 0) out[role] = at + 1; + } + return out; +} diff --git a/umtool/lib/report/postThreadCli.mjs b/umtool/lib/report/postThreadCli.mjs @@ -15,6 +15,7 @@ import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { partRoles, readPieces, threadLayout, threadReadErrors, threadReadWarnings } from "umtool-report-to-video/post-thread"; import { followKnobs } from "umtool-report-to-video/read-follow"; +import { tileOfRole } from "umtool-report-to-video/post-screens"; import { planContext } from "umtool-report-to-video/post-conversation"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; @@ -37,7 +38,7 @@ export class RolesError extends Error { } } -const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; /** * A narrated item's read, piece by piece: `{ id, take, pieces: [{ role, parts, source, mode }], errors, threaded }`. @@ -47,7 +48,7 @@ export function readListing(e, render, ctx) { const t = pickedTake(e); const roles = partRoles(e); const L = threadLayout(e, render, ctx ?? {}); - const mode = (role) => (!role ? null : role.startsWith("media:") ? "attachment" : L.tiles.find((x) => x.scope === role)?.mode ?? "absent"); + const mode = (role) => (!role ? null : role.startsWith("media:") ? "attachment" : L.tiles.find((x) => x.scope === tileOfRole(role))?.mode ?? "absent"); const pieces = readPieces(e, roles).map((p) => ({ role: p.role, parts: p.parts.map((k) => k + 1), diff --git a/umtool/lib/report/postThreadRead.mjs b/umtool/lib/report/postThreadRead.mjs @@ -63,6 +63,7 @@ import { cardText, parentsOf } from "umtool-report-to-video/post-item"; import { planContext } from "umtool-report-to-video/post-conversation"; import { spokenRead } from "umtool-report-to-video/post-redact"; import { readSpeedOf, resolvePieceVoice } from "umtool-report-to-video/post-say"; +import { SCREEN_LINE_GAP, parseScreenRole, screenWho } from "umtool-report-to-video/post-screens"; import { readManifest } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { manifestToken, updatePostNarration } from "./manifest.mjs"; @@ -102,6 +103,10 @@ export const THREAD_READ_USAGE = [ " --post-take <n>: his own line is the item's take n (as --list numbers them; a recording, or one converted to his", " character's voice), not synthesized -- the context pieces are, in their authors' voices; each part of the new take", " says where it came from. A thread take, or a take whose file is gone, is refused.", + " ITS SCREENS (umtool posts screen): each line a screen reads is read after his words, in the screens' order, in its", + " speaker's voice (`who`: the post's author in hers; a handle or a character's name in theirs) -- --no-screens leaves", + " them out. --line-take screen:<id>:<n>=<take n>: that LINE is the item's take n (a recording of that line, or one", + " converted to its speaker's character), not synthesized; repeatable.", ].join("\n"); /** @@ -161,7 +166,7 @@ export function seenIds(manifest, e) { * @param {{ red?: any, map?: Record<string, any>, cast?: Record<string, any>, item?: any, overrides?: Record<string, string>, parents?: string, * skip?: string[], quoted?: boolean, linked?: boolean, readSeen?: boolean, voice?: string | null, engine?: string | null, speed?: number | null }} [o] */ -export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, postTake = null } = {}) { +export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, item = null, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, postTake = null, screens = true, names = {}, lineTakes = {} } = {}) { const render = manifest?.render ?? {}; const k = postNarrationKnobs(e, render); const eng = engine ?? e.narration?.engine ?? k.engine; @@ -209,6 +214,31 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i skipped.push({ role: p.role, why: "--no-linked" }); continue; } + // A SCREEN's line (post-screens.mjs): its speaker's voice -- the post's author's own lines in hers. + if (parseScreenRole(p.role)) { + if (!screens) { + skipped.push({ role: p.role, why: "--no-screens" }); + continue; + } + const sw = screenWho(p.who, e, names); + const handle = sw.self ? str(e.handle) : sw.handle; + const written = draftScript(p.text).script; + const said = spokenRead(written, e, red, { voice: slurVoice }); + if (!norm(said.text)) { + skipped.push({ role: p.role, why: "nothing left to say (all of it redacted)" }); + continue; + } + const lt = lineTakes?.[p.role] ?? null; + if (lt) { + // THE LINE FROM A TAKE (--line-take): that take's file is the line's piece -- its words the line's, as drawn. + pieces.push({ role: p.role, handle, who: p.who, date: null, voice: takeVoiceOf(lt.take), from: "take", written, text: said.text.trim(), lexicon: [], slurs: lt.take.slurs ?? null, take: { n: lt.n, id: takeIdOf(lt.take), file: lt.take.file, ...(lt.take.engine ? { engine: lt.take.engine } : {}) } }); + continue; + } + const v = resolvePieceVoice({ handle, role: sw.self ? "post" : p.role }, { map, cast, item, overrides, self: str(e.handle), voice: null, narrator, engine: eng }); + const spd = readSpeedOf({ flag: speed, preset: v.speed ?? null, own: sw.self ? e.narration?.speed ?? null : null, engine: v.engine }); + pieces.push({ role: p.role, handle, who: p.who, date: null, voice: v.voice, engine: v.engine, from: v.from, ...(spd !== null ? { speed: spd } : {}), ...(v.character ? { character: v.character } : {}), written, text: said.text.trim(), lexicon: said.lexicon ?? [], slurs: said.slurs, ...(said.anonymised ? { anonymised: said.anonymised } : {}) }); + continue; + } const written = p.role === "post" ? own || script || "" : draftScript(p.text).script; if (!norm(written)) { skipped.push({ role: p.role, why: "no words to read" }); @@ -248,6 +278,27 @@ export function threadReadPlan(manifest, e, { red = null, map = {}, cast = {}, i }; } +/** + * The characters' NAMES -> their first handle (the project's own over the cast's), lower case: a screen line's `who` + * may be a name (post-screens.mjs screenWho). `{}` with no layers. + */ +export function characterNames(L) { + const out = {}; + const add = (c) => { + const n = str(c?.name).trim().toLowerCase(); + const h = Array.isArray(c?.handles) ? str(c.handles[0]) : ""; + if (n && h && !out[n] && c?.anonymous !== true) out[n] = h; + }; + for (const c of Array.isArray(L?.cast?.characters) ? L.cast.characters : []) add(c); + const own = Array.isArray(L?.project?.characters) ? L.project.characters : []; + for (const c of own) { + const n = str(c?.name).trim().toLowerCase(); + if (n) delete out[n]; + } + for (const c of own) add(c); + return out; +} + /** A take's voice as a thread read's label says it: its voice (or recorded label) without an engine ("am_michael", "operator"). */ export function takeVoiceOf(t) { const v = str(t?.voice) || str(t?.label) || (t?.engine === "recorded" ? "recorded" : "take"); @@ -290,7 +341,9 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : ` let t = 0; const meta = parts.map((p, i) => { const prev = i > 0 ? parts[i - 1] : null; - const gap = !prev ? 0 : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside; + // Two lines of one SCREEN (post-screens.mjs): a short pause, an exchange's. + const sameScreen = !!prev && p.piece !== prev.piece && parseScreenRole(p.role) !== null && parseScreenRole(p.role)?.id === parseScreenRole(prev.role)?.id; + const gap = !prev ? 0 : sameScreen ? SCREEN_LINE_GAP : p.piece !== prev.piece ? POST_PART_GAP.piece : p.para !== prev.para ? POST_PART_GAP.para : POST_PART_GAP.inside; t += gap; const s = Number(seconds[i]); // A part from a take (--post-take) says which (`take`: its id); a synthesized one its parts-cache file and voice. @@ -302,7 +355,7 @@ export function joinTimes(parts, seconds, { fileOf = (p) => (p.take ? p.file : ` } /** The `read` record of a take: how it was asked for (only what differs from the defaults). */ -export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null, postTake = null }) { +export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = true, readSeen = false, overrides = {}, voice = null, speed = null, postTake = null, screens = true, lineTakes = {} }) { return { kind: "thread", parents: parentsSelector(parents), ...(skip?.length ? { skip: [...skip] } : {}), ...(quoted ? {} : { quoted: false }), ...(linked ? {} : { linked: false }), @@ -311,6 +364,9 @@ export function readRecordOf({ parents = "0", skip = [], quoted = true, linked = ...(typeof speed === "number" && Number.isFinite(speed) ? { speed } : {}), // His line from a take (--post-take): its number then, and its file. ...(postTake ? { postTake: { n: postTake.n, file: postTake.take.file } } : {}), + // Its screens (post-screens.mjs): left out; lines from takes (--line-take). + ...(screens ? {} : { screens: false }), + ...(Object.keys(lineTakes ?? {}).length ? { lineTakes: Object.fromEntries(Object.entries(lineTakes).map(([r, lt]) => [r, { n: lt.n, file: lt.take.file }])) } : {}), }; } @@ -319,7 +375,11 @@ export function upToDate(e, plan) { const t = pickedTake(e); if (!t || norm(t.script) !== norm(plan.want) || str(t.voice) !== plan.voice || (t.engine ?? "orpheus") !== plan.engine) return false; // His line from a take: the same take's file, or not up to date. - if (str(t.read?.postTake?.file) !== str(plan.pieces.find((p) => p.take)?.take?.file)) return false; + if (str(t.read?.postTake?.file) !== str(plan.pieces.find((p) => p.take && p.role === "post")?.take?.file)) return false; + // A screen line from a take: the same takes' files, or not up to date. + const lines = Object.fromEntries(plan.pieces.filter((p) => p.take && p.role !== "post").map((p) => [p.role, p.take.file])); + const had = Object.fromEntries(Object.entries(t.read?.lineTakes ?? {}).map(([r, x]) => [r, str(x?.file)])); + if (JSON.stringify(Object.entries(lines).sort()) !== JSON.stringify(Object.entries(had).sort())) return false; // A take whose parts say their voices: each piece in the same engine and voice, at the same speed. const parts = Array.isArray(t.parts) ? t.parts.filter((p) => typeof p?.voice === "string") : []; if (!parts.length) return !plan.pieces.some((p) => typeof p.speed === "number"); @@ -347,6 +407,7 @@ export async function threadTake(project, e, opts = {}) { manifest: m0 = null, red: red0 = undefined, map: map0 = undefined, cast: cast0 = undefined, item: item0 = undefined, overrides = {}, parents = "0", skip = [], quoted = true, linked = true, readSeen = false, voice = null, engine = null, speed = null, note = null, force = false, hold = true, dryRun = false, ask = null, lanes: lanes0 = undefined, emit = () => {}, editor = null, signals = false, postTake: postTakeN = null, + screens = true, lineTakes: lineTakesN = {}, names: names0 = undefined, } = opts; const manifest = m0 ?? (await readManifest(project.dir)); if (!manifest) throw new ThreadReadError(`${project.id} has no manifest`); @@ -358,13 +419,24 @@ export async function threadTake(project, e, opts = {}) { const cast = cast0 !== undefined ? cast0 : L.castMap; const item = item0 !== undefined ? item0 : L?.itemOf(e) ?? null; const postTake = postTakeN === null || postTakeN === undefined ? null : postTakeOf(e, postTakeN); - const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake }); + // A screen line from a take (--line-take): checked as --post-take's is. + const lineTakes = Object.fromEntries(Object.entries(lineTakesN ?? {}).map(([role, n]) => { + if (!parseScreenRole(role)) throw new ThreadReadError(`--line-take names a screen's line as screen:<id>:<n> (got ${role})`); + try { + return [role, postTakeOf(e, n)]; + } catch (err) { + throw new ThreadReadError(String(err instanceof Error ? err.message : err).replace(/--post-take/g, `--line-take ${role}=`)); + } + })); + // The characters' names (a screen's `who` may be one), to their handles. + const names = names0 !== undefined ? names0 : characterNames(L); + const plan = threadReadPlan(manifest, e, { red, map, cast, item, overrides, parents, skip, quoted, linked, readSeen, voice, engine, speed, postTake, screens, names, lineTakes }); const parts = readParts(plan); const cacheDir = path.join(project.dir, ...PARTS_CACHE.split("/")); const wavOf = (p) => (p.take ? path.join(project.dir, ...p.file.split("/")) : path.join(cacheDir, `${p.key}.wav`)); const have = await Promise.all(parts.map((p) => fileThere(wavOf(p)))); const lost = parts.find((p, i) => p.take && !have[i]); - if (lost) throw new ThreadReadError(`--post-take ${postTake.n}: its file ${lost.file} is not there`); + if (lost) throw new ThreadReadError(`${lost.role === "post" ? `--post-take ${postTake?.n}` : `--line-take ${lost.role}`}: its file ${lost.file} is not there`); const base = { plan, parts: parts.map((p, i) => ({ ...p, cached: have[i] })), fresh: 0, cached: have.filter(Boolean).length, jobs: [], lane: null, dryRun }; if (!force && upToDate(e, plan)) return { ...base, upToDate: true }; if (dryRun) return { ...base, upToDate: false }; @@ -469,7 +541,7 @@ export async function threadTake(project, e, opts = {}) { ...(plan.lexicon.length ? { lexicon: plan.lexicon } : {}), // Where its parts' speeds came from: --speed (kept as asked), else their characters' presets / the item's own. ...(plan.pieces.some((p) => typeof p.speed === "number") ? { speedAsked: typeof speed === "number" ? true : "preset" } : {}), - read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake }), + read: readRecordOf({ parents, skip, quoted, linked, readSeen, overrides, voice, speed, postTake, screens, lineTakes }), }; const patch = { addTake: take, ...(plan.script ? { script: plan.script } : {}) }; const { result, editNotes } = await withEditNotes(project, async () => updatePostNarration(project.dir, e.id, patch, { token: await manifestToken(project.dir) })); diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs @@ -198,9 +198,9 @@ export const POSTS_USAGE = [ " none: the rule as it stands", ].join("\n"); -const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take"]); +const VALUED = new Set(["--in-take", "--set", "--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after", "--script", "--note", "--voice", "--engine", "--speed", "--pick", "--linger", "--derive", "--op", "--pitch", "--semitones", "--delete", "--match", "--target", "--occurrence", "--at", "--scale", "--hold", "--lead", "--ease", "--highlight", "--worker", "--without", "--drop-parts", "--text", "--place", "--rewind", "--zone", "--gap", "--from-scale", "--color", "--outline", "--outline-width", "--size", "--face", "--sfx", "--volume", "--bar", "--bar-style", "--tempo-for", "--tempo", "--parts", "--stretch", "--yell-gain", "--yell-style", "--pause", "--revoice", "--say", "--xfade", "--splice", "--parents", "--skip-parent", "--voice-for", "--item", "--recording", "--as", "--label", "--out", "--trim-span", "--post-take", "--line-take", "--from", "--media", "--kind", "--title", "--line", "--read", "--unread", "--by", "--ref"]); /** The valued flags that may be given more than once (each value kept, in order). */ -const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span"]); +const MULTI = new Set(["--skip-parent", "--voice-for", "--trim-span", "--line-take", "--line"]); const SLUG_RE = /^[A-Za-z0-9._-]+$/; const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; @@ -492,6 +492,15 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con try { const [verb, projectArg, ref] = words; if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }); + if (verb === "screen") { + // A POST's SCREENS (postScreensCli.mjs, post-screens.mjs): its text screenshots, transcribed, drawn and read. + const { SCREEN_USAGE, screenCommand } = await import("./postScreensCli.mjs"); + if (!projectArg || !ref || flags.has("--help")) { + err(SCREEN_USAGE); + return 2; + } + return await screenCommand(await projectOf(projectArg, root), words.slice(2), { flags, str, multi, json, out, dryRun }); + } if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out, reread: !flags.has("--no-reread") }); if (verb === "reread") { // A read re-joined without a piece (postReread.mjs): no TTS, a new take picked in one write. @@ -700,7 +709,7 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con return 1; } err(`umtool posts: ${e instanceof Error ? e.message : String(e)}`); - return e instanceof CliError || e?.constructor?.name === "NarrateError" || e?.constructor?.name === "FxError" ? 2 : 1; + return e instanceof CliError || e?.constructor?.name === "NarrateError" || e?.constructor?.name === "FxError" || e?.constructor?.name === "ScreenUsageError" ? 2 : 1; } } @@ -735,9 +744,9 @@ async function setCommand(projectArg, ref, pairs, { root, json, out }) { } /** The verbs `--in-take <take>` scopes (each writes a post item through manifest.mjs's structural writers). */ -export const IN_TAKE_VERBS = ["set-item", "roles", "narrate", "reread", "fx", "picture-reply"]; +export const IN_TAKE_VERBS = ["set-item", "roles", "narrate", "reread", "fx", "picture-reply", "screen"]; /** The verbs whose `--take <take>` is `--in-take <take>` (narrate's `--take` is its own: a new read). */ -const TAKE_ALIAS_VERBS = new Set(["set-item", "roles", "reread", "fx"]); +const TAKE_ALIAS_VERBS = new Set(["set-item", "roles", "reread", "fx", "screen"]); /** * `--in-take <take>` (or, on set-item/roles/reread/fx, `--take <take>`) taken out of a posts command line: diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -84,6 +84,7 @@ "./post-censor": "./post-censor.mjs", "./post-media-scene": "./post-media-scene.mjs", "./post-picture": "./post-picture.mjs", + "./post-screens": "./post-screens.mjs", "./post-redact": "./post-redact.mjs", "./post-say": "./post-say.mjs", "./cast": "./cast.mjs", diff --git a/umtool/report-to-video/post-anon.mjs b/umtool/report-to-video/post-anon.mjs @@ -254,6 +254,10 @@ function stripped(e) { out = { ...(out === e ? e : out), [k]: list.map(unflag) }; } for (const k of ["quoted", "repostedBy"]) if (isObj(out[k]) && "anonymous" in out[k]) out = { ...(out === e ? e : out), [k]: unflag(out[k]) }; + // A screen's lines (post-screens.mjs): the flag is this pass's alone there too. + if (Array.isArray(out.screens) && out.screens.some((sc) => isObj(sc) && Array.isArray(sc.lines) && sc.lines.some((l) => isObj(l) && "anonymous" in l))) { + out = { ...(out === e ? e : out), screens: out.screens.map((sc) => (isObj(sc) && Array.isArray(sc.lines) ? { ...sc, lines: sc.lines.map(unflag) } : sc)) }; + } return out; } @@ -310,6 +314,28 @@ export function anonymiseEntry(e0, set) { if (replyShown) edit().replyingTo = pseudonymOf(replyShown); // The subjects name handles: an anonymous one is its pseudonym there too (the card's subject accent still finds it). if (Array.isArray(e.subjects) && e.subjects.some((h) => of(h))) edit().subjects = e.subjects.map((h) => (of(h) ? pseudonymOf(of(h)) : h)); + // ITS SCREENS (post-screens.mjs): a speaker who is an anonymous handle under the shown name (flagged, drawn as it), every + // line's words and a title anonymised as the card's words are. + if (Array.isArray(e.screens)) { + let changed = false; + const screens = e.screens.map((sc) => { + if (!isObj(sc) || !Array.isArray(sc.lines)) return sc; + let mine = false; + const lines = sc.lines.map((l) => { + if (!isObj(l)) return l; + const s = typeof l.who === "string" ? of(l.who) : null; + const text = anonymiseWords(l.text, set); + if (!s && text === l.text) return l; + mine = true; + return { ...l, ...(s ? { who: s, anonymous: true } : {}), text }; + }); + const title = anonymiseWords(sc.title, set); + if (!mine && title === sc.title) return sc; + changed = true; + return { ...sc, lines, ...(title !== undefined ? { title } : {}) }; + }); + if (changed) edit().screens = screens; + } // The words the card draws. const w = withWords(out ?? e, set); if (w !== (out ?? e)) out = w; @@ -489,7 +515,16 @@ export function anonymityProblems(manifest, doc, { set: given = null } = {}) { if (!anonymousUrl(g.host, g.path.replace(/[.,;:!?)\]]+$/, ""), set)) warnings.push(`timeline ${e.id}: ${set.get(handleKey(e.handle))}'s words carry a link the pass cannot classify (${g.host}/…) -- drawn as written: check it does not lead to them`); } } - const drawn = whoOf(e).flatMap((w) => [str(w.text), str(w.paraphrase)]).join("\n"); + // ITS SCREENS (post-screens.mjs): a speaker written as an anonymous author's display name is drawn as written -- + // refused (write the handle: it is drawn under the shown name); their words are drawn as written, as a post's are. + const screens = (Array.isArray(e.screens) ? e.screens : []).filter((sc) => isObj(sc) && Array.isArray(sc.lines)); + for (const sc of screens) { + for (const l of sc.lines) { + if (!isObj(l) || typeof l.who !== "string") continue; + for (const [n, shown] of names) if (l.who.trim().toLowerCase() === n.toLowerCase()) errors.push(`timeline ${e.id}: screen ${str(sc.id)} names a speaker by ${shown}'s display name -- an anonymous author's: write their handle as the line's who (drawn as "${shown}")`); + } + } + const drawn = [...whoOf(e).flatMap((w) => [str(w.text), str(w.paraphrase)]), ...screens.flatMap((sc) => [str(sc.title), ...sc.lines.map((l) => str(l?.text))])].join("\n"); for (const [n, shown] of names) if (phraseRe(n).test(drawn)) warnings.push(`timeline ${e.id}: its words write out ${shown}'s display name -- the card draws words as written: edit them, or redact the name (umtool posts redact)`); if (typeof e.parentShot === "string") warnings.push(`timeline ${e.id}: its captured thread shot is not drawn -- this video has anonymous authors, and a shot may picture them (the card's "Replying to" line stands in)`); } diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -43,6 +43,7 @@ import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from ". import { progressErrors } from "./post-progress.mjs"; import { validatePostMapRender } from "./post-branch-map.mjs"; import { validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; +import { hasScreens, isScreenScope, screenBadgeHtml, screenCss, screenOf, screenShows, screenTileHtml, screenWho, validateScreens } from "./post-screens.mjs"; /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]); @@ -401,14 +402,18 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul const fitEnd = sch && isObj(w) && w.media === m.i && fin(w.end) && Math.abs(w.end - m.end) < 0.011; return fin(m.end) && !fitEnd ? s : { ...s, seconds: round3(Math.min(s.seconds, avail)) }; }); + // ITS SCREENS (post-screens.mjs) read: its own attachments until the first is up, then each screen's span. + const shows = !hasScreens(entry) || ownPictureOnly(entry) ? [] : screenShows(entry, follow, { lead: 0.4 }); + const ownUntil = shows.length ? Math.max(enter, shows[0].t0) : null; + const avail1 = ownUntil === null ? avail : round3(Math.max(0, ownUntil - enter)); const videos = all.filter((s) => s.kind === "video").reduce((n, s) => n + s.seconds, 0); const pics = all.filter((s) => s.kind !== "video"); - const share = pics.length ? Math.max(POST_PICTURE_MIN, (avail - videos) / pics.length) : 0; + const share = pics.length ? Math.max(POST_PICTURE_MIN, (avail1 - videos) / pics.length) : 0; const steps = all.map((s) => (s.kind === "video" ? s : { ...s, seconds: round3(share) })); const media = round3(steps.reduce((n, s) => n + s.seconds, 0)); // A LINK VISIT (post-link-visit.mjs) lit after the read runs on its hold: the item holds it. - const total = hold ?? round3(Math.max(span, enter + media, follow?.visits ? visitsEnd(follow.visits) : 0)); - const plan = planSteps(steps, enter, total); + const total = hold ?? round3(Math.max(span, ownUntil === null ? enter + media : 0, follow?.visits ? visitsEnd(follow.visits) : 0)); + const plan = ownUntil === null ? planSteps(steps, enter, total) : screenPlan(entry, steps, enter, ownUntil, shows, total); // A video shorter than the read: looped to the end, or (the default) its last frame held. const last = plan.steps[plan.steps.length - 1]; if (k.short === "loop" && last?.kind === "video" && plan.held > 0.05) { @@ -423,6 +428,46 @@ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = nul return { ...plan, reading: 0, total, ...extra, ...(panel ? { panel } : {}), ...(enter > 0 && plan.steps.length ? { enter } : {}), ...(inCard.length ? { pics: inCard } : {}) }; } +/** + * THE PLAN's STEPS with ITS SCREENS (post-screens.mjs): its own attachments from `enter`, cut at the first screen's + * show; then, for each screen, its attachment from its show to the next one's (the last to the item's end) -- a video + * or a GIF from its span's start (`at`), its last frame HELD when the read outlasts the span (a looped span would + * replay the overlay fading in and out); an image held. Each such step says `screen: <id>`. + */ +function screenPlan(entry, steps, enter, ownUntil, shows, total) { + const own = ownUntil > enter + 0.05 ? planSteps(steps, enter, ownUntil).steps : []; + // Its last own step runs on to the first screen, its last frame held (`hold`: the build plays no further than its span). + const lastOwn = own[own.length - 1]; + if (lastOwn && lastOwn.at + lastOwn.seconds < ownUntil - 0.01) { + lastOwn.seconds = round3(ownUntil - lastOwn.at); + if (lastOwn.kind === "video") lastOwn.hold = true; + } + const media = Array.isArray(entry?.media) ? entry.media : []; + const out = [...own]; + shows.forEach((sh, i) => { + const m = media[sh.media]; + const until = i + 1 < shows.length ? shows[i + 1].t0 : total; + if (!isObj(m) || until <= sh.t0 + 0.05) return; + const seconds = round3(until - sh.t0); + const timed = m.kind === "video" || m.kind === "gif"; + const from = timed && Array.isArray(sh.at) ? round3(sh.at[0]) : 0; + const to = timed && Array.isArray(sh.at) ? round3(sh.at[1]) : null; + out.push({ + kind: m.kind, + items: [{ ...m, i: sh.media, ...(timed ? { start: from, end: to } : {}) }], + at: round3(sh.t0), + seconds, + ...(timed ? { srcFrom: from, srcTo: to } : {}), + loop: m.kind === "gif", + sound: m.kind === "video" && m.mute !== true && m.audio !== false, + ...(m.kind === "video" ? { hold: true } : {}), + screen: sh.id, + }); + }); + const end = out.length ? out[out.length - 1].at + out[out.length - 1].seconds : enter; + return { steps: out, held: out.length ? round3(Math.max(0, total - end)) : 0 }; +} + /** Whether any context post of the item (a parent, the quoted post) is picture-only. */ const hasPictureContext = (entry) => parentsOf(entry).some(refPictureOnly) || (isObj(entry?.quoted) && refPictureOnly(entry.quoted)); @@ -737,6 +782,8 @@ export function validatePostItem(e) { errors.push(...progressErrors(e.progress, `timeline ${e?.id ?? "?"}.progress`)); // Picture-only (post-picture.mjs): its own, a parent's, the quoted post's -- true or false. errors.push(...validatePictureOnly(e)); + // Its screens (post-screens.mjs): the text screenshots it carries, transcribed, and what of them is read. + errors.push(...validateScreens(e)); return errors; } @@ -1267,6 +1314,16 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p return { media: post ? censorEntry({ post, media }, redaction).media : media }; }; const menSize = Math.round(22 * k); + // A SCREEN's speaker (post-screens.mjs): the post's author under the card's rule for her; an anonymous one (the pass + // flagged it) under the shown name; anyone else under the privacy rule -- a subject, or the item's redact: false. + const screenShown = (l) => { + const s = screenWho(l?.who, entry); + if (s.self) return !red("author"); + if (l?.anonymous === true) return true; + if (entry.redact === true) return false; + if (entry.redact === false) return true; + return !!s.handle && subjectsOf(entry).some((h) => String(h).replace(/^@/, "").toLowerCase() === String(s.handle).toLowerCase()); + }; const ownPicMax = Math.max(Math.round(140 * k), L.card.height - 2 * L.pad - Math.round(250 * k) - Math.min(2, parentsOf(entry).length) * Math.round(130 * k) - (isObj(entry.quoted) ? Math.round(170 * k) : 0)); const own = { author: entry.author, handle: entry.handle, ...(entry.anonymous === true ? { anonymous: true } : {}) }; const ownRed = red("author"); @@ -1414,9 +1471,21 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p `<div class="tslot" data-thread-slot="${esc(t.scope)}" data-thread-scene="${t.action === "keep" ? "keep" : "collapse"}"><div class="tile tparent tscene" data-thread-tile="${esc(t.scope)}" data-thread-mode="scene" data-post-scene="${esc(t.scope.slice(5))}"${r ? ' data-redacted=""' : ""}>${avatarHtml(ref, { redact: r, size: av, img: pic(ref) })}<div class="pbody">${relationHtml(t)}<div class="phead">${nameHtml(ref, { redact: r, cls: "big" })}<span class="pdate">${esc(cardDate(ref.date).split(" · ")[0])}</span>${ref.paraphrased ? '<span class="plabel" data-post-paraphrased="">paraphrased</span>' : ""}</div><div class="ptext tt${spic ? " pmen" : ""}" style="font-size:${tsize}px">${wordsHtml(text, r && ref.handle ? [...blurred, ref.handle] : blurred)}</div>${spic ? picIn(t.scope, spic, innerW - av - Math.round(16 * k), Math.round(innerH * 0.6)) : ""}</div></div></div>`, ); } + // ITS SCREENS (post-screens.mjs): each screen the take reads, typeset -- a tile after his post, its lines the + // read-follow's blocks (by role, never by words), with its badge pinned to the card's top while it is up. + const badges = []; + for (const t of tiles) { + if (!isScreenScope(t.scope)) continue; + const sc = screenOf(entry, t.scope.slice(7)); + if (!sc) continue; + const lines = new Map((fmap?.blocks ?? []).filter((b) => b.scope === t.scope && Number.isInteger(b.line)).map((b) => [b.line, b.k])); + tileHtml.push(screenTileHtml(entry, sc, { k, size: Math.max(followMin, Math.round(30 * k)), blocks: lines, shown: screenShown, authorHidden: ownRed, h: { esc } })); + badges.push(screenBadgeHtml(entry, sc, { esc, authorHidden: ownRed })); + } const order = [...tiles.map((t) => t.scope).filter((sc) => byScope.has(sc)), ...[...byScope.keys()].filter((sc) => !tiles.some((t) => t.scope === sc))]; return { - html: `<div class="card thread" data-post-card="${esc(entry.id)}" data-post-thread="${tiles.length}"${L.mode === "text" ? ' data-thread-fit=""' : ""} style="left:${box.x}px;top:${box.y}px;height:${box.height}px;width:${box.width}px"><div class="words" data-post-words="" style="font-size:${size}px"><div class="wflow" data-post-flow="">${order.map((sc) => byScope.get(sc)).join("")}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div></div></div>`, + html: `<div class="card thread" data-post-card="${esc(entry.id)}" data-post-thread="${tiles.length}"${L.mode === "text" ? ' data-thread-fit=""' : ""} style="left:${box.x}px;top:${box.y}px;height:${box.height}px;width:${box.width}px"><div class="words" data-post-words="" style="font-size:${size}px"><div class="wflow" data-post-flow="">${order.map((sc) => byScope.get(sc)).join("")}</div><div class="wfade" data-post-fade="top"></div><div class="wfade" data-post-fade="bottom"></div></div>${badges.join("")}</div>`, + screens: badges.length > 0, css: cutCss.length ? `\n${cutCss.join(", ")} { display: none; }` : "", }; }; @@ -1503,7 +1572,7 @@ ${tiles?.some((t) => t?.rel) ? `.rel { color: ${pal.muted}; font-size: ${Math.ro ` : ""}.tile .tt { display: block; -webkit-line-clamp: none; overflow: visible; line-height: ${LINE}; color: ${pal.fg}; margin-top: ${Math.round(6 * k)}px; } .twords { line-height: ${LINE}; overflow-wrap: anywhere; } .tile.quoted .tt { color: ${mixHex(pal.fg, pal.bg, 0.08)}; } -.tile.quoted.tabove .tt { color: ${pal.fg}; }${tc.css}` : ""}${highlight ? ` +.tile.quoted.tabove .tt { color: ${pal.fg}; }${tc.css}${tc.screens ? screenCss({ k, pal, mixHex, rgbaOf, pad: L.pad }) : ""}` : ""}${highlight ? ` [data-w-hl] { background: ${rgbaOf(highlight.color, WORD_ZOOM_HIGHLIGHT_ALPHA)}; box-shadow: inset 0 -0.12em 0 ${highlight.color}; border-radius: 0.16em; padding: 0 0.08em; margin: 0 -0.08em; -webkit-box-decoration-break: clone; box-decoration-break: clone; }` : ""} ${BAR_CSS(pal.fg)} </style></head> diff --git a/umtool/report-to-video/post-narration.mjs b/umtool/report-to-video/post-narration.mjs @@ -713,7 +713,7 @@ export function validatePostNarration(e) { if (p.text !== undefined && typeof p.text !== "string") errors.push(`${pw}.text must be the words it reads`); if (p.speed !== undefined && !numIn(p.speed, POST_NARRATION_LIMITS.speed)) errors.push(`${pw}.speed must be ${POST_NARRATION_LIMITS.speed.join("–")} (the speed it was synthesized at)`); if (p.tempo !== undefined && !numIn(p.tempo, POST_NARRATION_LIMITS.tempo)) errors.push(`${pw}.tempo must be ${POST_NARRATION_LIMITS.tempo.join("–")} (its reading speed in the take)`); - if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d)$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i> or media:<i> (the text it reads)`); + if (p.role !== undefined && !(typeof p.role === "string" && /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/.test(p.role))) errors.push(`${pw}.role must be post, quoted, parent:<i>, linked:<i>, media:<i> or screen:<id>:<line> (the text it reads)`); if (p.engine !== undefined && !POST_NARRATION_ENGINES.includes(p.engine)) errors.push(`${pw}.engine must be one of ${POST_NARRATION_ENGINES.join(", ")}`); if (p.take !== undefined && !(typeof p.take === "string" && n.takes.some((x) => x !== t && takeIdOf(x) === p.take))) errors.push(`${pw}.take must be the id of another of its takes (the take this part is)`); }); diff --git a/umtool/report-to-video/post-redact.mjs b/umtool/report-to-video/post-redact.mjs @@ -288,6 +288,8 @@ export function redactEntry(entry, red) { if (isObj(entry.quoted)) out.quoted = ref(entry.quoted, "quoted"); // A post its words link to (post-thread.mjs): marked by the project's terms, as a quoted post is. if (Array.isArray(entry.links)) out.links = entry.links.map((p) => ref(p, "quoted")); + // ITS SCREENS (post-screens.mjs): every line's words and its speaker marked by the project's terms. + if (Array.isArray(entry.screens)) out.screens = screensMarked(entry.screens, (v) => mark(v, all)); return slurEntry(out, red?.slurs); } @@ -336,9 +338,17 @@ export function slurEntry(entry, slurs) { if (Array.isArray(entry.parents)) out.parents = entry.parents.map(ref); if (isObj(entry.quoted)) out.quoted = ref(entry.quoted); if (Array.isArray(entry.links)) out.links = entry.links.map((r) => (isObj(r) && "transcript" in r ? { ...ref(r), transcript: m(r.transcript) } : ref(r))); + if (Array.isArray(entry.screens)) out.screens = screensMarked(entry.screens, m); return out; } +/** A screens list (post-screens.mjs) with each line's words, its speaker and the title passed through `m` (a copy). */ +function screensMarked(screens, m) { + return screens.map((sc) => (isObj(sc) && Array.isArray(sc.lines) + ? { ...sc, ...("title" in sc ? { title: m(sc.title) } : {}), lines: sc.lines.map((l) => (isObj(l) ? { ...l, ...("text" in l ? { text: m(l.text) } : {}), ...("who" in l ? { who: m(l.who) } : {}) } : l)) } + : sc)); +} + // --------------------------------------------------------------------------- // What is SAID and what a line of text SHOWS, the redaction and the slur filter together. // --------------------------------------------------------------------------- diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs @@ -32,6 +32,7 @@ import { POST_PROGRESS_DRAW_V, measureProgressPlace, mountProgress, progressCss, import { SLAM_BAR, SLAM_DUST, SLAM_FACE_STACK, SLAM_MOTION, mountSlams, slamBarOf, setSlamState, slamCss, slamCoverErrors, slamHits, slamLayout, slamListAt, slamPlan, slamShakeExpr, slamSize, slamVars } from "./post-slam.mjs"; import { TRAILER_AUDIO, TRAILER_HIT_TIERS, trailerHitsGraph } from "./trailer-hits.mjs"; import { panelReadErrors } from "./post-thread.mjs"; +import { POST_SCREEN_DRAW_V, hasScreens } from "./post-screens.mjs"; import { applyJoinState, endMediaOf, joinClockOf } from "./post-join.mjs"; import { applyVisitState } from "./post-link-visit.mjs"; import { applyMapState, mapPageHtml, mapPlace, mapSize, mapStateAt } from "./post-branch-map.mjs"; @@ -261,16 +262,18 @@ export function postSegmentArgs({ entry, box, plan, layout, cards, files, render parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}${fadeIn(shownFrom)}[${raw}]`); } } else { - // A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays. + // A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays. A step + // that HOLDS (post-item.mjs: a screen's span, post-screens.mjs) plays no further than its span: its last frame held. const len = until - step.at; - const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(len), "-i", file]); + const play = step.hold === true && Number.isFinite(step.srcTo) ? Math.min(len, Math.max(0.05, step.srcTo - step.srcFrom)) : len; + const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(play), "-i", file]); parts.push( `[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,` + `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}${fadeIn(shownFrom)}[${raw}]`, ); if (step.sound) { const ms = Math.round(step.at * 1000); - const dur = Math.min(step.seconds, len); + const dur = Math.min(step.seconds, play); audio.push({ label: `a${si}`, chain: `[${k}:a]aresample=${render.audioRate ?? 48000},aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS,atrim=0:${num(dur)},afade=t=in:d=0.04,afade=t=out:st=${num(Math.max(0, dur - 0.06))}:d=0.06,adelay=${ms}|${ms}[a${si}]` }); } } @@ -1362,6 +1365,8 @@ export function postSegmentKeyOf({ entry, redaction = null, box, place = [], ren ...(layout?.panel === "top" || layout?.panel === "bottom" ? { layout: { panel: layout.panel, card: layout.card, slot: layout.slot } } : {}), // A caption, the clock, the pace (post-caption.mjs, post-clock.mjs): nothing for an item with none of them. ...postFxKeyFields(entry, render, prev, { plan, layout }), + // ITS SCREENS (post-screens.mjs): their drawing's version -- only an item that carries screens. + ...(hasScreens(entry) ? { screens: POST_SCREEN_DRAW_V } : {}), ...(POST_SEGMENT_RV ? { rv: POST_SEGMENT_RV } : {}), }; } diff --git a/umtool/report-to-video/post-screens.mjs b/umtool/report-to-video/post-screens.mjs @@ -0,0 +1,587 @@ +// A POST's SCREENS: TEXT SCREENSHOTS READ AS PART OF THE POST (umtool/docs/report-video.md, "Screens"; operator, 12 Nov +// 2026, on quartering-diet rev9-a9: "the screenshots should be treated as extensions of the post rather than +// transparent, probably read and probably with excerpts because it's long text. You can show it alongside the video in +// the tweet slot as you read" -- "The 'read text screenshots as posts' ability in different variations should be first +// class, it's a very common pattern"). +// +// A post item may carry SCREENS: the text screenshots that belong to the post -- a DM exchange or an email shown in its +// video, an image attachment that is a screenshot of a chat, a letter, another post. Each is TRANSCRIBED once (data, a +// person checks it), DRAWN legibly on the card as part of the post, and READ -- whole or in excerpts -- in the voices of +// the people in it, each line lit while it is said. The standing rule holds: no hidden text is ever narrated, and every +// read piece is on screen in full and lit while it is read (post-thread.mjs). +// +// screens: [{ id: "s1", media: 0, at: [3.5, 8], kind: "dm", title?, source?: "transcribed", checked?: { by, at }, +// ref?: "<channel>/<postId>", unread?: "omit" | "dim", +// lines: [{ who?, side?: "left" | "right", text, time?, redact?: true }], +// read: "all" | "none" | [{ line, text? }] }] +// +// - `media` names the attachment (an index into the item's `media`); `at` the source span a video or GIF shows it. +// - `read`: every line ("all"), none ("none": transcribed only -- not drawn, not read), or the lines listed, each read +// whole or an EXCERPT (`text`: a contiguous run of that line's words; drawn "…excerpt…", the cut sides marked). +// - `unread`: the lines a read screen does not read are left out ("omit", the default: a "⋯" row where they were) or +// drawn dim ("dim"). A line marked `redact: true` is never drawn nor read. +// - THE SHAPES: an e-mail address, a phone number, a long run of digits, an order or confirmation number in a line are +// MASKED (a bar on the card, never said) whether or not anyone marked them -- the lint says which line held one. +// - `who`: a handle or a name; it is the post's author (her own lines, on the right), or another speaker, voiced through +// the project's characters and the cast as a thread read's pieces are (post-say.mjs) and drawn under the item's +// privacy rule (a subject, or `redact: false`, shown; else blurred), an anonymous one under its shown name. +// +// THE READ (lib/report/postThreadRead.mjs): each read line is a piece of the thread read, after the post's own words, in +// the screens' order, its ROLE `screen:<id>:<n>` (n the line's index). THE CARD (post-thread.mjs threadLayout): a screen +// the take reads is a tile `screen:<id>` after his post -- his post shrinks to a strip as it is revealed, it collapses as +// the next comes in. THE MEDIA (post-item.mjs planOf): while a screen is read the slot plays its span, its last frame held. +// +// PURE and dependency-free but for its siblings. +import { REDACT_MARK, dropMarks, redactText } from "./post-redact.mjs"; +import { handleKey } from "./post-say.mjs"; + +export const SCREEN_KINDS = Object.freeze(["dm", "email", "post", "text"]); +export const SCREEN_SIDES = Object.freeze(["left", "right"]); +export const SCREEN_UNREAD = Object.freeze(["omit", "dim"]); +export const SCREEN_ID_RE = /^[a-z0-9][a-z0-9-]{0,23}$/; +export const SCREENS_MAX = 8; +export const SCREEN_LINES_MAX = 60; +export const SCREEN_LINE_MAX = 600; +export const SCREEN_TITLE_MAX = 80; +export const SCREEN_WHO_MAX = 64; +export const SCREEN_TIME_MAX = 24; +/** The least span (s) a screen may name in a video. */ +export const SCREEN_MIN_SPAN = 0.5; +/** The pause between two lines of one screen in a joined read (a new piece is POST_PART_GAP.piece). */ +export const SCREEN_LINE_GAP = 0.35; +/** The drawing's version: a change to how a screen is drawn rebuilds the segments that draw one (post-render.mjs). */ +export const POST_SCREEN_DRAW_V = 1; +/** A screen line's role: `screen:<id>:<n>`. */ +export const SCREEN_ROLE_RE = /^screen:([a-z0-9][a-z0-9-]{0,23}):(\d{1,2})$/; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const str = (v) => (typeof v === "string" ? v : ""); +const r3 = (v) => Math.round(v * 1000) / 1000; + +/** A line's role. */ +export const screenRole = (id, n) => `screen:${id}:${n}`; +/** A screen's tile scope on the card. */ +export const screenScope = (id) => `screen:${id}`; +/** A role's screen and line, or null when it is not a screen line's. */ +export function parseScreenRole(role) { + const m = SCREEN_ROLE_RE.exec(str(role)); + return m ? { id: m[1], n: Number(m[2]) } : null; +} +/** Whether a scope or role is a screen's. */ +export const isScreenScope = (s) => str(s).startsWith("screen:"); +/** The TILE a role is read on: a screen line's is its screen's; any other role is its own. */ +export const tileOfRole = (role) => { + const p = parseScreenRole(role); + return p ? screenScope(p.id) : role; +}; + +/** An item's screens as drawn and read (each an object with an id and lines); [] when it has none. */ +export const screensOf = (entry) => + Array.isArray(entry?.screens) ? entry.screens.filter((s) => isObj(s) && SCREEN_ID_RE.test(str(s.id)) && Array.isArray(s.lines)).slice(0, SCREENS_MAX) : []; +/** Whether an item carries screens. */ +export const hasScreens = (entry) => screensOf(entry).length > 0; +/** One screen by id. */ +export const screenOf = (entry, id) => screensOf(entry).find((s) => s.id === id) ?? null; + +// --------------------------------------------------------------------------- +// THE SHAPES: what is never typeset nor read, marked or not. +// --------------------------------------------------------------------------- + +const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g; +const PHONE_RE = /(?<![\w$.])\+?\(?\d[\d\s().-]{8,}\d(?![\w])/g; +const ORDER_RE = /\b(?:order|confirmation|conf|invoice|tracking|reference|ref|account|acct)(?:\s+(?:number|no\.?|num|id|code))?\s*(?:#|:)?\s*([A-Za-z0-9-]*\d[A-Za-z0-9-]{2,})/gi; +const HASHNUM_RE = /#\s?[A-Za-z0-9-]*\d{4,}[A-Za-z0-9-]*/g; +// A token of six digits or more (separators inside it ignored), not an amount ("$1,000.00", "1,000,000"). +const TOKEN_RE = /[^\s]+/g; +const AMOUNT_RE = /^[($]*\$?\d{1,3}(?:,\d{3})+(?:\.\d+)?[).,;:!?]*$|^[($]*\$\d+(?:\.\d+)?[).,;:!?]*$|^\d+\.\d{1,2}[).,;:!?]*$/; + +/** + * THE SHAPES in a line, pure: `[{ start, end, kind }]` -- an e-mail address ("email"), a phone number of ten digits or + * more ("phone"), an order / confirmation / invoice / tracking number, or a "#1234" ("order"), a run of six digits or + * more that is not an amount ("number"). Merged, in order. + */ +export function shapeSpans(text) { + const t = str(text); + const out = []; + for (const m of t.matchAll(EMAIL_RE)) out.push({ start: m.index, end: m.index + m[0].length, kind: "email" }); + for (const m of t.matchAll(PHONE_RE)) if ([10, 11, 12, 13, 14, 15].includes((m[0].match(/\d/g) ?? []).length) && /[\s().+-]/.test(m[0])) out.push({ start: m.index, end: m.index + m[0].length, kind: "phone" }); + for (const m of t.matchAll(ORDER_RE)) { + const v = m[1]; + if ((v.match(/\d/g) ?? []).length < 3) continue; + const at = m.index + m[0].length - v.length; + out.push({ start: at, end: at + v.length, kind: "order" }); + } + for (const m of t.matchAll(HASHNUM_RE)) out.push({ start: m.index, end: m.index + m[0].length, kind: "order" }); + for (const m of t.matchAll(TOKEN_RE)) { + const tok = m[0]; + if ((tok.match(/\d/g) ?? []).length < 6 || AMOUNT_RE.test(tok)) continue; + const lead = tok.match(/^[("'“[]*/)[0].length; + const trail = tok.match(/[)"'”\].,;:!?]*$/)[0].length; + out.push({ start: m.index + lead, end: m.index + tok.length - trail, kind: "number" }); + } + out.sort((a, b) => a.start - b.start || b.end - a.end); + const merged = []; + for (const s of out) { + const last = merged[merged.length - 1]; + if (last && s.start <= last.end) last.end = Math.max(last.end, s.end); + else merged.push({ ...s }); + } + return merged; +} + +/** A line's words with its shapes MASKED (the redaction's marks: drawn as bars, dropped when said), and what was masked. */ +export function maskShapes(text) { + const spans = shapeSpans(text); + if (!spans.length) return { text: str(text), kinds: [] }; + return { text: redactText(str(text), [], { spans }).text, kinds: [...new Set(spans.map((s) => s.kind))] }; +} + +// --------------------------------------------------------------------------- +// WHAT IS READ AND WHAT IS DRAWN of a screen. +// --------------------------------------------------------------------------- + +const words = (t) => [...str(t).matchAll(/\S+/g)].map((m) => ({ w: m[0], start: m.index, end: m.index + m[0].length })); +const wkey = (w) => w.toLowerCase().replace(/^[^\p{L}\p{N}$#@]+|[^\p{L}\p{N}%]+$/gu, ""); + +/** + * Where an EXCERPT stands in its line, pure: `{ start, end }` (character offsets of the line's own words it names, a + * contiguous run; their edge punctuation need not match) -- or null when it is not a run of the line's words. + */ +export function excerptRun(line, excerpt) { + const L = words(line); + const E = words(excerpt).map((x) => wkey(x.w)); + if (!E.length || E.length > L.length) return null; + const keys = L.map((x) => wkey(x.w)); + for (let i = 0; i + E.length <= L.length; i += 1) { + let ok = true; + for (let j = 0; j < E.length; j += 1) { + if (keys[i + j] !== E[j]) { + ok = false; + break; + } + } + if (ok) return { start: L[i].start, end: L[i + E.length - 1].end }; + } + return null; +} + +/** Whether a line can be read or drawn at all: not marked redact, with words. */ +const lineOk = (l) => isObj(l) && l.redact !== true && !!str(l.text).trim(); + +/** + * A screen's READ LINES, pure, in the line order: `[{ n, start, end, cutBefore, cutAfter }]` -- each line read, the + * run of its words read (the whole line, or its excerpt), and whether words were cut before or after it. "none", a + * redacted line or a line with no words: none. An excerpt that is not in its line is read whole (the validation says so). + */ +export function screenReadLines(screen) { + const lines = Array.isArray(screen?.lines) ? screen.lines : []; + const r = screen?.read; + const asked = r === "all" ? lines.map((_, n) => ({ line: n })) : Array.isArray(r) ? r.filter((x) => isObj(x) && Number.isInteger(x.line)) : []; + const seen = new Set(); + const out = []; + for (const x of asked) { + const l = lines[x.line]; + if (!lineOk(l) || seen.has(x.line)) continue; + seen.add(x.line); + const t = str(l.text); + const run = str(x.text).trim() ? excerptRun(t, x.text) : null; + const all = { start: t.search(/\S/), end: t.trimEnd().length }; + const span = run ?? all; + out.push({ n: x.line, start: span.start, end: span.end, cutBefore: span.start > all.start, cutAfter: span.end < all.end }); + } + return out.sort((a, b) => a.n - b.n); +} + +/** The screens the DATA says are read (a read line or more), in order. */ +export const readScreens = (entry) => screensOf(entry).filter((s) => screenReadLines(s).length > 0); + +/** What a read line SAYS (before the thread read's spokenRead): its read run, its shapes left out. */ +export function screenLineSaid(screen, n) { + const r = screenReadLines(screen).find((x) => x.n === n); + if (!r) return ""; + const l = screen.lines[n]; + const masked = maskShapes(str(l.text)).text.slice(r.start, r.end); + return masked.includes(REDACT_MARK) ? dropMarks(masked) : masked.trim(); +} + +/** + * A screen's DRAWN ROWS, pure: `[{ n, text, read, cutBefore, cutAfter } | { gap: true, lines }]` -- each line drawn + * (masked; a read excerpt alone, its cut sides marked "…"), whether it is read; the lines not read left out (a gap row + * where they were) under `unread: "omit"`, drawn dim under "dim". A redacted line is never drawn (a gap row under omit). + */ +export function screenRows(screen) { + const lines = Array.isArray(screen?.lines) ? screen.lines : []; + const reads = new Map(screenReadLines(screen).map((r) => [r.n, r])); + const dim = screen?.unread === "dim"; + const out = []; + let gap = 0; + const flush = () => { + if (gap && out.length) out.push({ gap: true, lines: gap }); + gap = 0; + }; + lines.forEach((l, n) => { + const r = reads.get(n); + if (!r && !(dim && lineOk(l))) { + gap += 1; + return; + } + flush(); + const masked = maskShapes(str(l.text)).text; + out.push({ n, text: r ? masked.slice(r.start, r.end) : masked.trim(), read: !!r, cutBefore: !!r?.cutBefore, cutAfter: !!r?.cutAfter }); + }); + // A gap after the last row drawn: the screen goes on past what is shown. + if (gap && out.length) out.push({ gap: true, lines: gap }); + return out; +} + +/** Whether a screen's drawing leaves anything of it out (a line, or words of one): its header says "excerpt". */ +export const screenIsExcerpt = (screen) => screenRows(screen).some((r) => r.gap || r.cutBefore || r.cutAfter); + +// --------------------------------------------------------------------------- +// WHO SAYS IT. +// --------------------------------------------------------------------------- + +/** + * WHO a line is, pure: `{ self, handle, name }` -- `self` when it is the post's author (by handle or by name), else the + * handle it resolves to: written as a handle, or a character's name (`names`: lower-case name -> handle, the project's + * characters and the cast's) resolved to its handle; `name` as written. An empty `who`: the author's when the screen's + * kind is a letter, none else. + * + * @param {string | undefined} who + * @param {{ handle?: string, author?: string }} entry + * @param {Record<string, string> | Map<string, string>} [names] + */ +export function screenWho(who, entry, names = {}) { + const w = str(who).trim(); + const key = handleKey(w); + const self = !!w && ((!!key && key === handleKey(entry?.handle)) || w.toLowerCase() === str(entry?.author).trim().toLowerCase()); + if (!w) return { self: false, handle: null, name: "" }; + if (self) return { self: true, handle: str(entry?.handle).replace(/^@/, "") || null, name: w }; + const byName = names instanceof Map ? names.get(w.toLowerCase()) : names?.[w.toLowerCase()]; + if (byName) return { self: false, handle: str(byName).replace(/^@/, ""), name: w }; + return { self: false, handle: /^@?[A-Za-z0-9_]{1,30}$/.test(w) ? w.replace(/^@/, "") : null, name: w }; +} + +/** The side a line is drawn on: its own `side`, else the author's lines on the right and the others on the left. */ +export const screenSide = (line, entry) => (SCREEN_SIDES.includes(line?.side) ? line.side : screenWho(line?.who, entry).self ? "right" : "left"); + +// --------------------------------------------------------------------------- +// THE VALIDATION. +// --------------------------------------------------------------------------- + +/** Every reason an item's `screens` cannot be drawn or read (validatePostItem). */ +export function validateScreens(e) { + const s = e?.screens; + if (s === undefined) return []; + const w = `timeline ${e?.id ?? "?"}.screens`; + if (!Array.isArray(s)) return [`${w} must be a list of the text screenshots the post carries`]; + const errors = []; + if (s.length > SCREENS_MAX) errors.push(`${w}: at most ${SCREENS_MAX} screens`); + const media = Array.isArray(e?.media) ? e.media : []; + const ids = new Set(); + s.forEach((sc, i) => { + const at = `${w}[${i}]`; + if (!isObj(sc)) { + errors.push(`${at} must be an object`); + return; + } + const known = new Set(["id", "media", "at", "kind", "title", "source", "checked", "ref", "unread", "lines", "read"]); + for (const k of Object.keys(sc)) if (!known.has(k)) errors.push(`${at}.${k} is not a screen's field (${[...known].join(", ")})`); + if (!SCREEN_ID_RE.test(str(sc.id))) errors.push(`${at}.id must be a short name (lower-case letters, digits, -)`); + else if (ids.has(sc.id)) errors.push(`${at}.id "${sc.id}" is the id of another screen of the item`); + else ids.add(sc.id); + const m = Number.isInteger(sc.media) ? media[sc.media] : undefined; + if (!Number.isInteger(sc.media) || !isObj(m)) errors.push(`${at}.media must be the index of the attachment it is in (0–${Math.max(0, media.length - 1)}${media.length ? "" : ": the item has none"})`); + const timed = m?.kind === "video" || m?.kind === "gif"; + if (sc.at !== undefined) { + if (m && !timed) errors.push(`${at}.at: only a video or a GIF has a span (attachment ${sc.media} is ${m.kind === "image" ? "an image" : m.kind})`); + else if (!(Array.isArray(sc.at) && sc.at.length === 2 && sc.at.every((v) => fin(v) && v >= 0) && sc.at[1] - sc.at[0] >= SCREEN_MIN_SPAN - 1e-9 && (!fin(m?.seconds) || sc.at[1] <= m.seconds + 0.05))) { + errors.push(`${at}.at must be [from, to], the seconds of attachment ${sc.media} it is visible in (at least ${SCREEN_MIN_SPAN} s${fin(m?.seconds) ? `, inside 0–${m.seconds}` : ""})`); + } + } else if (timed) errors.push(`${at}.at must be [from, to]: the seconds of the ${m.kind} it is visible in`); + if (!SCREEN_KINDS.includes(sc.kind)) errors.push(`${at}.kind must be one of ${SCREEN_KINDS.join(", ")}`); + if (sc.title !== undefined && !(typeof sc.title === "string" && sc.title.trim() && sc.title.length <= SCREEN_TITLE_MAX)) errors.push(`${at}.title must be words (at most ${SCREEN_TITLE_MAX} characters)`); + if (sc.source !== undefined && sc.source !== "transcribed") errors.push(`${at}.source must be "transcribed"`); + if (sc.checked !== undefined && !(isObj(sc.checked) && typeof sc.checked.by === "string" && sc.checked.by.trim() && sc.checked.by.length <= 40 && typeof sc.checked.at === "string" && !Number.isNaN(Date.parse(sc.checked.at)))) { + errors.push(`${at}.checked must be { by, at }: who checked the transcription and when (ISO)`); + } + if (sc.ref !== undefined && !(sc.kind === "post" && typeof sc.ref === "string" && /^[A-Za-z0-9._-]+\/[A-Za-z0-9_-]+$/.test(sc.ref))) errors.push(`${at}.ref must be <channel>/<postId> (a screenshot of a post only)`); + if (sc.unread !== undefined && !SCREEN_UNREAD.includes(sc.unread)) errors.push(`${at}.unread must be ${SCREEN_UNREAD.join(" or ")}`); + const lines = Array.isArray(sc.lines) ? sc.lines : null; + if (!lines || !lines.length) errors.push(`${at}.lines must be the transcription: a list of { who?, side?, text, time?, redact? }`); + else { + if (lines.length > SCREEN_LINES_MAX) errors.push(`${at}.lines: at most ${SCREEN_LINES_MAX}`); + lines.forEach((l, n) => { + const lw = `${at}.lines[${n}]`; + if (!isObj(l)) { + errors.push(`${lw} must be { who?, side?, text, time?, redact? }`); + return; + } + for (const k of Object.keys(l)) if (!["who", "side", "text", "time", "redact", "anonymous"].includes(k)) errors.push(`${lw}.${k} is not a line's field (who, side, text, time, redact)`); + if (l.anonymous !== undefined && l.anonymous !== true) errors.push(`${lw}.anonymous is the anonymising pass's own flag (true, or absent)`); + if (typeof l.text !== "string" || l.text.length > SCREEN_LINE_MAX) errors.push(`${lw}.text must be the line's words (at most ${SCREEN_LINE_MAX} characters)`); + else if (!l.text.trim() && l.redact !== true) errors.push(`${lw}.text is empty (a line with no words: remove it, or mark it redact)`); + if (l.who !== undefined && !(typeof l.who === "string" && l.who.trim() && l.who.length <= SCREEN_WHO_MAX)) errors.push(`${lw}.who must be a handle or a name`); + if (l.side !== undefined && !SCREEN_SIDES.includes(l.side)) errors.push(`${lw}.side must be left or right`); + if (l.time !== undefined && !(typeof l.time === "string" && l.time.length <= SCREEN_TIME_MAX)) errors.push(`${lw}.time must be the time shown (at most ${SCREEN_TIME_MAX} characters)`); + if (l.redact !== undefined && l.redact !== true) errors.push(`${lw}.redact must be true (or absent)`); + }); + } + const r = sc.read; + if (r === "all" || r === "none") return; + if (!Array.isArray(r)) { + errors.push(`${at}.read must be "all", "none" or a list of { line, text? }`); + return; + } + const lines2 = lines ?? []; + const seen = new Set(); + r.forEach((x, j) => { + const rw = `${at}.read[${j}]`; + if (!isObj(x) || !Number.isInteger(x.line) || !isObj(lines2[x.line])) { + errors.push(`${rw} must be { line, text? } naming a line (0–${Math.max(0, lines2.length - 1)})`); + return; + } + if (seen.has(x.line)) errors.push(`${rw}: line ${x.line} is read twice`); + seen.add(x.line); + if (lines2[x.line].redact === true) errors.push(`${rw}: line ${x.line} is redacted -- it is never read`); + if (x.text !== undefined) { + if (typeof x.text !== "string" || !x.text.trim()) errors.push(`${rw}.text must be the words of the line to read (an excerpt)`); + else if (!excerptRun(str(lines2[x.line].text), x.text)) errors.push(`${rw}.text "${x.text.slice(0, 40)}" is not a run of line ${x.line}'s words (an excerpt is the line's own words, in a row)`); + } + for (const k of Object.keys(x)) if (!["line", "text"].includes(k)) errors.push(`${rw}.${k} is not a read's field (line, text)`); + }); + }); + return errors; +} + +/** + * A screen line the take reads, checked against the data: null when it is drawn and read, else why not (the guard, + * post-thread.mjs threadReadErrors). + */ +export function screenLineProblem(entry, role) { + const p = parseScreenRole(role); + if (!p) return "not a screen line"; + const sc = screenOf(entry, p.id); + if (!sc) return `screen ${p.id}, which the item does not carry`; + const l = sc.lines[p.n]; + if (!isObj(l)) return `line ${p.n} of screen ${p.id}, which it does not have`; + if (l.redact === true) return `line ${p.n} of screen ${p.id}, which is redacted (never drawn)`; + if (!screenReadLines(sc).some((r) => r.n === p.n)) return `line ${p.n} of screen ${p.id}, which the screen does not read (${sc.read === "none" ? 'read: "none" -- not drawn' : sc.unread === "dim" ? "drawn dim, never lit" : "left out of the card"})`; + return null; +} + +// --------------------------------------------------------------------------- +// THE PIECES a read reads (post-thread.mjs chronoPieces): after the post's own words. +// --------------------------------------------------------------------------- + +/** Each read line of the item's read screens, in order: `[{ role, who, text }]` (`text` what it says). */ +export function screenPieces(entry) { + const out = []; + for (const sc of readScreens(entry)) { + for (const r of screenReadLines(sc)) { + const text = screenLineSaid(sc, r.n); + if (text.trim()) out.push({ role: screenRole(sc.id, r.n), who: str(sc.lines[r.n].who) || null, text, screen: sc.id }); + } + } + return out; +} + +/** The read's order of a screen role: after every other text, by its screen's place and its line (null: not one). */ +export function screenOrder(entry, role) { + const p = parseScreenRole(role); + if (!p) return null; + const at = screensOf(entry).findIndex((s) => s.id === p.id); + return 100 + Math.max(0, at) + p.n / 1000; +} + +// --------------------------------------------------------------------------- +// THE MEDIA: what the slot plays while a screen is read (post-item.mjs planOf). +// --------------------------------------------------------------------------- + +/** + * WHEN EACH SCREEN IS UP, pure: `[{ id, media, t0 }]` -- each screen tile of the plan's thread from its first read + * line's start less the pan's lead (`lead`), in order. Empty: none read. + */ +export function screenShows(entry, follow, { lead = 0.4 } = {}) { + const tiles = (follow?.thread?.tiles ?? []).filter((t) => isScreenScope(t.scope)); + const out = []; + for (const t of tiles) { + const id = t.scope.slice(7); + const sc = screenOf(entry, id); + if (!sc) continue; + const ts = (follow.blocks ?? []).filter((b) => b.scope === t.scope && fin(b.start)).map((b) => b.start); + if (!ts.length) continue; + out.push({ id, media: sc.media, at: Array.isArray(sc.at) ? sc.at : null, t0: r3(Math.max(0, Math.min(...ts) - lead)) }); + } + return out.sort((a, b) => a.t0 - b.t0); +} + +// --------------------------------------------------------------------------- +// THE DRAWING (post-item.mjs postCardHtml's threaded card calls it). +// --------------------------------------------------------------------------- + +const KIND_WORD = { dm: "DMs", email: "An email", post: "A post", text: "Text" }; +const KIND_SHORT = { dm: "DMs", email: "Email", post: "Post", text: "Text" }; + +/** + * A screen's HEADER, pure: what it is and that it is transcribed -- "DMs shown in Savvy's video · transcribed" (its + * `title` for the kind's word; the author's SHOWN name, an anonymous one's; "the post's" for a blurred author). + */ +export function screenHeader(entry, screen, { authorHidden = false } = {}) { + const m = Array.isArray(entry?.media) ? entry.media[screen?.media] : null; + const where = m?.kind === "image" ? "picture" : "video"; + const who = authorHidden || !str(entry?.author).trim() ? "the post's" : `${str(entry.author).trim()}'s`; + const what = str(screen?.title).trim() || KIND_WORD[screen?.kind] || "Text"; + return { text: `${what} shown in ${who} ${where}`, badge: `${str(screen?.title).trim() || KIND_SHORT[screen?.kind] || "Text"} · transcribed` }; +} + +/** + * ONE SCREEN's TILE, as HTML (escaped; the redaction's marks drawn as bars by the page's barsHtml). `blocks`: line -> + * the read-follow block that reads it (`data-post-block`); `shown(lineWho)`: whether a speaker is drawn (the privacy + * rule), else blurred. `h`: the card's helpers (esc, mixHex, rgbaOf). The kinds: a DM as bubbles (the author's on the + * right in the accent, the others on the left), an email or text as a quiet letter block, a post as a post tile marked + * "screenshot". + * + * @param {Record<string, any>} entry + * @param {Record<string, any>} screen + * @param {{ k: number, size: number, blocks: Map<number, number>, shown: (line: Record<string, any>) => boolean, authorHidden?: boolean, h: { esc: (s: any) => string } }} o + */ +export function screenTileHtml(entry, screen, { k, size, blocks, shown, authorHidden = false, h }) { + const { esc } = h; + const id = screen.id; + const scope = screenScope(id); + const head = screenHeader(entry, screen, { authorHidden }); + const excerpt = screenIsExcerpt(screen) ? '<span class="plabel" data-screen-excerpt="">excerpt</span>' : ""; + const rows = screenRows(screen); + const blk = (n) => (blocks.has(n) ? ` data-post-block="${blocks.get(n)}"` : ""); + const words = (r) => `${r.cutBefore ? "…" : ""}${esc(r.text)}${r.cutAfter ? "…" : ""}`; + const nameOf = (l) => { + const w = str(l?.who).trim(); + if (!w) return ""; + return shown(l) ? `<span class="sname">${esc(w)}</span>` : '<span class="sname redact">xxxxxxxx</span>'; + }; + const time = (l) => (str(l?.time).trim() ? `<span class="stime">${esc(l.time.trim())}</span>` : ""); + let body; + if (screen.kind === "dm") { + const named = new Set(); + let last = null; + body = rows + .map((r) => { + if (r.gap) { + last = null; + return `<div class="sgap" data-screen-gap="${r.lines}">⋯</div>`; + } + const l = screen.lines[r.n]; + const side = screenSide(l, entry); + const who = str(l.who).trim(); + const key = who.toLowerCase(); + // The speaker's name on first use (and again after a gap or the other side). + const name = who && (!named.has(key) || last !== key) ? `<div class="swho">${nameOf(l)}</div>` : ""; + named.add(key); + last = key; + return `<div class="srow ${side}${r.read ? "" : " sdim"}" data-screen-line="${r.n}">${name}<div class="sbub"${blk(r.n)}>${words(r)}${time(l)}</div></div>`; + }) + .join(""); + } else if (screen.kind === "post") { + const first = screen.lines.find((l) => str(l?.who).trim()); + body = `<div class="spost">${first ? `<div class="sphead">${nameOf(first)}<span class="plabel" data-screen-shot="">screenshot</span></div>` : '<div class="sphead"><span class="plabel" data-screen-shot="">screenshot</span></div>'}${rows + .map((r) => (r.gap ? `<div class="sgap" data-screen-gap="${r.lines}">⋯</div>` : `<p class="sline${r.read ? "" : " sdim"}" data-screen-line="${r.n}"${blk(r.n)}>${words(r)}</p>`)) + .join("")}</div>`; + } else { + let lastWho = null; + body = `<div class="sletter">${rows + .map((r) => { + if (r.gap) return `<div class="sgap" data-screen-gap="${r.lines}">⋯</div>`; + const l = screen.lines[r.n]; + const who = str(l.who).trim(); + const from = who && who !== lastWho ? `<div class="sfrom">${nameOf(l)}${time(l)}</div>` : ""; + if (who) lastWho = who; + return `${from}<p class="sline${r.read ? "" : " sdim"}" data-screen-line="${r.n}"${blk(r.n)}>${words(r)}${from ? "" : time(l)}</p>`; + }) + .join("")}</div>`; + } + return `<div class="tslot" data-thread-slot="${esc(scope)}"><div class="tile tscreen" data-thread-tile="${esc(scope)}" data-thread-mode="full" data-post-screen="${esc(id)}" data-screen-kind="${esc(screen.kind)}" style="font-size:${size}px"><div class="shead" data-screen-head=""><span class="stitle">${esc(head.text)}</span><span class="strans" data-screen-transcribed=""> · transcribed</span>${excerpt}</div>${body}</div></div>`; +} + +/** A screen's BADGE: pinned to the card's top while that screen is up (followStateAt's `screen`) -- "· transcribed" never leaves the screen. */ +export const screenBadgeHtml = (entry, screen, { esc, authorHidden = false }) => + `<div class="sbadge" data-screen-badge="${esc(screen.id)}">${esc(screenHeader(entry, screen, { authorHidden }).badge)}</div>`; + +/** The CSS a page with screens adds (none without). */ +export function screenCss({ k, pal, mixHex, rgbaOf, pad }) { + const px = (v) => `${Math.round(v * k)}px`; + const bub = mixHex(pal.bg, pal.fg, 0.14); + return ` +.tscreen { display: flex; flex-direction: column; gap: ${px(10)}; line-height: 1.32; } +.shead { display: flex; align-items: baseline; gap: ${px(8)}; color: ${pal.muted}; font-size: ${px(20)}; letter-spacing: 0.01em; } +.shead .strans { color: ${pal.muted}; } +.shead .plabel { margin-left: auto; } +.srow { display: flex; flex-direction: column; max-width: 86%; } +.srow.left { align-self: flex-start; align-items: flex-start; } +.srow.right { align-self: flex-end; align-items: flex-end; } +.tscreen[data-screen-kind="dm"] { align-items: stretch; } +.tscreen[data-screen-kind="dm"] > .srow, .tscreen[data-screen-kind="dm"] > .sgap { } +.swho { color: ${pal.muted}; font-size: ${px(19)}; margin: ${px(4)} ${px(6)} ${px(2)}; } +.sbub { padding: ${px(8)} ${px(16)}; border-radius: ${px(20)}; background: ${bub}; color: ${pal.fg}; overflow-wrap: anywhere; } +.srow.right .sbub { background: ${rgbaOf(pal.accent, 0.42)}; } +.stime { color: ${pal.muted}; font-size: ${px(16)}; margin-left: ${px(10)}; white-space: nowrap; } +.sdim { opacity: 0.45; } +.sgap { align-self: center; color: ${pal.muted}; font-size: ${px(22)}; line-height: 1; letter-spacing: 0.2em; } +.sletter, .spost { border: 1px solid ${mixHex(pal.bg, pal.fg, 0.22)}; border-radius: ${px(12)}; padding: ${px(14)} ${px(18)}; display: flex; flex-direction: column; gap: ${px(8)}; } +.sfrom { color: ${pal.muted}; font-size: ${px(19)}; } +.sline { color: ${pal.fg}; overflow-wrap: anywhere; } +.sphead { display: flex; align-items: center; gap: ${px(10)}; font-size: ${px(22)}; } +.sname { font-family: 'PostSansBold', sans-serif; color: ${pal.fg}; } +.swho .sname { color: ${pal.muted}; } +.sbadge { position: absolute; top: ${Math.max(2, Math.round((pad - 22 * k) / 2))}px; right: ${pad}px; font-size: ${px(16)}; line-height: 1; padding: ${px(3)} ${px(9)}; border-radius: ${px(6)}; background: ${rgbaOf(pal.bg, 0.85)}; color: ${pal.muted}; border: 1px solid ${mixHex(pal.bg, pal.fg, 0.22)}; letter-spacing: 0.04em; text-transform: uppercase; opacity: 0; z-index: 3; }`; +} + +// --------------------------------------------------------------------------- +// THE LINT's WARNINGS (lint.mjs; never refused). +// --------------------------------------------------------------------------- + +/** + * Post item `entry`'s screens WARNINGS, pure: a transcription no one checked, a line holding a shape the card masks, a + * screen on an item not narrated (not drawn), a screenshot of a post naming an archived one, a speaker the privacy rule + * blurs, read lines the picked take does not read. `takeRoles`: the picked take's roles (post-thread.mjs partRoles), + * `narrated` whether it plays a take. + * + * @param {Record<string, any>} entry + * @param {{ narrated?: boolean, takeRoles?: Array<string | null> }} [o] + */ +export function screenWarnings(entry, { narrated = false, takeRoles = [] } = {}) { + const out = []; + const id = entry?.id ?? "?"; + const w = `timeline ${id}`; + const roles = new Set(takeRoles.filter(Boolean)); + const subjects = new Set((Array.isArray(entry?.subjects) ? entry.subjects : []).map((h) => handleKey(h))); + for (const sc of screensOf(entry)) { + if (!isObj(sc.checked)) out.push(`${w}: screen ${sc.id}'s transcription not checked -- read it against the screenshot, then umtool posts screen <p> ${id} check ${sc.id} (or tick it on the post bench)`); + sc.lines.forEach((l, n) => { + if (!isObj(l) || l.redact === true) return; + const kinds = [...new Set(shapeSpans(str(l.text)).map((s) => s.kind))]; + if (kinds.length) out.push(`${w}: screen ${sc.id} line ${n} holds ${kinds.map((k) => (k === "email" ? "an e-mail address" : k === "phone" ? "a phone number" : k === "order" ? "an order or reference number" : "a long number")).join(" and ")} -- masked on the card and never said; mark the line redact (umtool posts screen <p> ${id} set ${sc.id} line.${n}.redact=on) if the rest of it should go too`); + }); + if (sc.kind === "post" && sc.ref) out.push(`${w}: screen ${sc.id} pictures ${sc.ref} -- drawn from its transcription; umtool posts set-item <p> ${id} link.add=… draws the archived post itself`); + const reads = screenReadLines(sc); + if (!reads.length) continue; + if (!narrated) { + out.push(`${w}: screen ${sc.id} is drawn and read only on a narrated item -- make its read: umtool posts screen <p> ${id} read`); + continue; + } + const missing = reads.filter((r) => !roles.has(screenRole(sc.id, r.n))); + if (missing.length === reads.length) out.push(`${w}: its picked take does not read screen ${sc.id} (not drawn until it does) -- umtool posts screen <p> ${id} read`); + else if (missing.length) out.push(`${w}: its picked take does not read line${missing.length === 1 ? "" : "s"} ${missing.map((r) => r.n).join(", ")} of screen ${sc.id} -- umtool posts screen <p> ${id} read`); + const blurred = new Set(); + for (const r of reads) { + const who = str(sc.lines[r.n].who).trim(); + const s = screenWho(who, entry); + if (who && !s.self && entry?.redact !== false && !subjects.has(handleKey(s.handle ?? "")) && !blurred.has(who.toLowerCase())) { + blurred.add(who.toLowerCase()); + out.push(`${w}: screen ${sc.id}'s speaker ${who} is drawn blurred (the privacy rule: not a subject of the item) -- add them to its subjects or set redact: false to show the name`); + } + } + } + return out; +} diff --git a/umtool/report-to-video/post-screens.test.mjs b/umtool/report-to-video/post-screens.test.mjs @@ -0,0 +1,268 @@ +// post-screens.mjs: a post's SCREENS -- its text screenshots, transcribed, drawn on its card and read in the voices of +// the people in them. The data and its validation, the shapes masked (never drawn, never said), what is read and drawn +// of a screen, the read's roles and pieces, the card's tiles and its schedule, the plan's media, the anonymity pass, +// the lint's warnings. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { postCardHtml, postItemPlan, validatePostItem } from "./post-item.mjs"; +import { chronoPieces, partRoles, threadLayout, threadReadErrors, validateThreadReadWarnings } from "./post-thread.mjs"; +import { followBlocks, followStateAt, followStateKey, isDrawnState } from "./read-follow.mjs"; +import { anonymiseEntry, anonymityProblems } from "./post-anon.mjs"; +import { redactEntry } from "./post-redact.mjs"; +import { + excerptRun, maskShapes, parseScreenRole, screenHeader, screenLineSaid, screenReadLines, screenRows, screenWarnings, screenWho, shapeSpans, tileOfRole, validateScreens, +} from "./post-screens.mjs"; + +const VID = { src: "posts-media/savvy-x/2117/2117_1.mp4", kind: "video", width: 1920, height: 1080, seconds: 61.742, audio: true, start: 3.3, end: 8 }; +const IMG = { src: "posts-media/savvy-x/2117/2117_2.jpg", kind: "image", width: 900, height: 1400 }; +const S1 = { + id: "s1", media: 0, at: [3.5, 8], kind: "dm", read: "all", lines: [ + { who: "TheQuartering", text: "what's your email so I can refund your order", time: "11:32 AM" }, + { who: "MadamSavvy", text: "where is my scale video", time: "11:53 AM" }, + { who: "TheQuartering", text: "you HONESTLY believe that I have lied about weight loss?" }, + { who: "TheQuartering", text: "You can't be this dumb", time: "11:58 AM" }, + ], +}; +const S2 = { + id: "s2", media: 1, kind: "email", title: "Refund email", read: [{ line: 0 }, { line: 1, text: "Total amount refunded: $99.95" }], lines: [ + { who: "coffee brand coffee", text: "Some items in your order have been refunded" }, + { text: "Total amount refunded: $99.95 USD. It may take up to 10 days for this refund to appear in your account." }, + { text: "Order number 4419283 · reply to support@coffeebrand.com" }, + ], +}; +const POST = "Hey, @thequartering You told me your video was ready to go.\n\nYour turn."; +const base = (o = {}) => ({ type: "post", id: "p-2117", post: "savvy-x/2117", platform: "x", author: "Savvy", handle: "MadamSavvy", date: "2026-11-02T01:40:36.000Z", text: POST, subjects: ["MadamSavvy"], media: [VID, IMG], screens: [S1, S2], ...o }); +/** A thread read's take: his words, then each screen line (stored roles), timed by words. */ +function narrated(e, lines = [["s1", 0], ["s1", 1], ["s1", 2], ["s1", 3], ["s2", 0], ["s2", 1]]) { + const parts = []; + let t = 0; + const add = (text, role, piece, gap) => { + t += parts.length ? gap : 0; + const sec = Math.round((text.split(/\s+/).length / 3) * 100) / 100; + parts.push({ n: parts.length + 1, para: piece * 100, text, role, start: Math.round(t * 1000) / 1000, seconds: sec }); + t += sec; + }; + add("Hey, at thequartering You told me your video was ready to go.", "post", 0, 0); + add("Your turn.", "post", 0, 0.6); + lines.forEach(([id, n], i) => { + const sc = e.screens.find((s) => s.id === id); + add(screenLineSaid(sc, n), `screen:${id}:${n}`, 1 + i, i && lines[i - 1][0] === id ? 0.35 : 0.8); + }); + return { ...e, narration: { script: POST, pick: 0, takes: [{ file: "narration/posts/2117/take-1.orpheus-thread.wav", engine: "orpheus", voice: "tara+leo", seconds: Math.round(t * 1000) / 1000, script: "x", parts }] } }; +} + +test("the data: a well-formed item with screens is taken; each wrong field is named", () => { + assert.deepEqual(validatePostItem(narrated(base())), []); + const bad = (sc, re) => assert.ok(validateScreens(base({ screens: [sc] })).some((x) => re.test(x)), `${JSON.stringify(sc).slice(0, 80)} -> ${re}`); + bad({ ...S1, id: "S 1" }, /\.id must be a short name/); + bad({ ...S1, media: 7 }, /\.media must be the index/); + bad({ ...S1, at: undefined }, /\.at must be \[from, to\]: the seconds of the video/); + bad({ ...S1, at: [3, 70] }, /inside 0–61\.742/); + bad({ ...S2, at: [1, 2] }, /only a video or a GIF has a span/); + bad({ ...S1, kind: "chat" }, /\.kind must be one of dm, email, post, text/); + bad({ ...S1, read: [{ line: 0, text: "refund your email" }] }, /is not a run of line 0's words/); + bad({ ...S1, read: [{ line: 0 }, { line: 0 }] }, /line 0 is read twice/); + bad({ ...S1, lines: [{ text: "x", redact: true }, ...S1.lines], read: [{ line: 0 }] }, /line 0 is redacted -- it is never read/); + bad({ ...S1, ref: "a/b" }, /\.ref must be <channel>\/<postId> \(a screenshot of a post only\)/); + bad({ ...S1, checked: { by: "me" } }, /\.checked must be \{ by, at \}/); + bad({ ...S1, lines: [{ who: "x", text: "y", colour: "red" }] }, /\.colour is not a line's field/); + const two = validateScreens(base({ screens: [S1, { ...S2, id: "s1" }] })); + assert.ok(two.some((x) => /is the id of another screen/.test(x))); + // An excerpt names a run of the line's own words; its edge punctuation need not match. + assert.deepEqual(excerptRun("Total amount refunded: $99.95 USD. It may", "total amount refunded: $99.95."), { start: 0, end: 29 }); + assert.equal(excerptRun("hop on the scale fatso", "on scale"), null); +}); + +test("THE SHAPES: an e-mail, a phone number, an order or long number are masked -- absent from the card's page AND from what the part says", () => { + const kinds = (t) => shapeSpans(t).map((s) => s.kind); + assert.deepEqual(kinds("reply to support@coffeebrand.com"), ["email"]); + assert.deepEqual(kinds("call +1 (555) 201-4477 today"), ["phone"]); + assert.deepEqual(kinds("Order number 4419283 shipped"), ["order"]); + assert.deepEqual(kinds("your code #88213 is ready"), ["order"]); + assert.deepEqual(kinds("id 2117069332987425196"), ["number"]); + // Amounts, times and small numbers stay. + assert.deepEqual(kinds("Total $104.90 USD, $1,000,000 at 12:18 PM, 400 pounds, Oct 31, 290"), []); + assert.equal(maskShapes("a@b.co").text.includes("a@b.co"), false); + // A line that READS a shape: the card never draws it, the read never says it. + const sc = { ...S2, read: "all" }; + const e = narrated(base({ screens: [S1, sc] }), [["s1", 0], ["s2", 0], ["s2", 1], ["s2", 2]]); + assert.deepEqual(validatePostItem(e), []); + const said = screenLineSaid(sc, 2); + assert.ok(!said.includes("4419283") && !said.includes("support@") && !said.includes("coffeebrand"), said); + assert.ok(/reply to/.test(said)); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(html.includes('data-screen-line="2"'), "the line is drawn"); + for (const v of ["4419283", "support@coffeebrand.com", "coffeebrand"]) assert.ok(!html.includes(v), `${v} is not in the page`); + assert.ok(html.includes('data-post-blanked=""'), "a bar stands where it was"); + // The read's piece says it as the part does: the shape left out. + const piece = chronoPieces(e).find((p) => p.role === "screen:s2:2"); + assert.ok(piece && !/4419283|support@/.test(piece.text)); +}); + +test("what is read and drawn: all, a list with an excerpt, none; lines not read left out (a gap row) or drawn dim; a redacted line never", () => { + assert.deepEqual(screenReadLines(S1).map((r) => r.n), [0, 1, 2, 3]); + const r2 = screenReadLines(S2); + assert.deepEqual(r2.map((r) => [r.n, r.cutBefore, r.cutAfter]), [[0, false, false], [1, false, true]]); + assert.equal(screenLineSaid(S2, 1), "Total amount refunded: $99.95"); + const rows = screenRows(S2); + assert.deepEqual(rows.map((r) => (r.gap ? `gap${r.lines}` : `${r.n}:${r.read}`)), ["0:true", "1:true", "gap1"]); + assert.equal(rows[1].text, "Total amount refunded: $99.95"); + const dim = screenRows({ ...S2, unread: "dim" }); + assert.deepEqual(dim.map((r) => (r.gap ? "gap" : `${r.n}:${r.read}`)), ["0:true", "1:true", "2:false"]); + assert.ok(!dim[2].text.includes("4419283"), "a dim line is masked too"); + assert.deepEqual(screenReadLines({ ...S1, read: "none" }), []); + const red = { ...S1, lines: [S1.lines[0], { text: "my address is 12 High St", redact: true }, S1.lines[1]], read: "all" }; + assert.deepEqual(screenReadLines(red).map((r) => r.n), [0, 2]); + assert.ok(!JSON.stringify(screenRows({ ...red, unread: "dim" })).includes("High St"), "a redacted line is never drawn"); +}); + +test("who: the post's author by handle or name; another by handle, or a character's name resolved; the side follows", () => { + const e = base(); + assert.deepEqual(screenWho("MadamSavvy", e), { self: true, handle: "MadamSavvy", name: "MadamSavvy" }); + assert.equal(screenWho("savvy", e).self, true); + assert.deepEqual(screenWho("TheQuartering", e), { self: false, handle: "TheQuartering", name: "TheQuartering" }); + assert.deepEqual(screenWho("Jeremy Hambly", e, { "jeremy hambly": "TheQuartering" }), { self: false, handle: "TheQuartering", name: "Jeremy Hambly" }); + assert.equal(screenWho("coffee brand coffee", e).handle, null); +}); + +test("the read: roles screen:<id>:<n> stored on the take; the card threads -- his post, then each screen the take reads, a tile", () => { + const e = narrated(base()); + const roles = partRoles(e).map((r) => r.role); + assert.deepEqual(roles, ["post", "post", "screen:s1:0", "screen:s1:1", "screen:s1:2", "screen:s1:3", "screen:s2:0", "screen:s2:1"]); + assert.deepEqual(parseScreenRole("screen:s1:3"), { id: "s1", n: 3 }); + assert.equal(tileOfRole("screen:s1:3"), "screen:s1"); + const L = threadLayout(e, {}); + assert.equal(L.on, true); + assert.deepEqual(L.tiles.map((t) => t.scope), ["post", "screen:s1", "screen:s2"]); + // A screen the take does not read is not drawn (a warning says so). + const one = narrated(base(), [["s1", 0], ["s1", 1]]); + assert.deepEqual(threadLayout(one, {}).tiles.map((t) => t.scope), ["post", "screen:s1"]); + // The blocks: one a line, named by its role. + const b = followBlocks(e).blocks.filter((x) => String(x.scope).startsWith("screen:")); + assert.deepEqual(b.map((x) => [x.scope, x.line, x.part]), [["screen:s1", 0, 2], ["screen:s1", 1, 3], ["screen:s1", 2, 4], ["screen:s1", 3, 5], ["screen:s2", 0, 6], ["screen:s2", 1, 7]]); + // The pieces a thread read reads: after his words, in the screens' order. + assert.deepEqual(chronoPieces(e).map((p) => p.role), ["post", "screen:s1:0", "screen:s1:1", "screen:s1:2", "screen:s1:3", "screen:s2:0", "screen:s2:1"]); + assert.equal(chronoPieces(e)[1].who, "TheQuartering"); +}); + +test("the schedule: his post gives way to a strip as the first screen comes in; a screen read collapses as the next comes in; the last stays", () => { + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const rows = Object.fromEntries(plan.follow.thread.tiles.map((t) => [t.scope, t])); + const s1 = plan.follow.blocks.find((b) => b.scope === "screen:s1" && b.line === 0).start; + const s2 = plan.follow.blocks.find((b) => b.scope === "screen:s2" && b.line === 0).start; + assert.deepEqual(rows.post.to, [0.62, 0.5]); + assert.ok(Math.abs(rows.post.t0 - (s1 - 0.4)) < 0.01); + assert.deepEqual([rows["screen:s1"].from, rows["screen:s1"].to, rows["screen:s1"].then.to], [[1, 0], [1, 1], [0, 0]]); + assert.ok(Math.abs(rows["screen:s1"].then.t0 - (s2 - 0.4)) < 0.01); + assert.equal(rows["screen:s2"].then, undefined); + // The state says which screen is up (its badge); none before; part of the key; never "the page as drawn". + const path = { start: 0, segments: [], H: 600, C: 900, tiles: {} }; + assert.equal(followStateAt(plan.follow, path, 1).screen, null); + const mid = followStateAt(plan.follow, path, s1 + 1); + assert.equal(mid.screen, "s1"); + assert.equal(followStateAt(plan.follow, path, s2 + 1).screen, "s2"); + assert.ok(followStateKey(mid).includes('"screen":"s1"')); + assert.equal(isDrawnState({ op: {}, offset: 0, fadeTop: 0, fadeBottom: 0, screen: "s1" }), false); +}); + +test("the media: its own attachments until the first screen is up, then each screen's span -- a video's last frame HELD, an image held", () => { + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const st = plan.steps.map((s) => ({ kind: s.kind, at: s.at, sec: s.seconds, from: s.srcFrom, to: s.srcTo, screen: s.screen ?? null, hold: s.hold ?? false })); + const s1At = st.find((s) => s.screen === "s1"); + const s2At = st.find((s) => s.screen === "s2"); + assert.ok(s1At && s2At); + assert.deepEqual([s1At.kind, s1At.from, s1At.to, s1At.hold], ["video", 3.5, 8, true]); + assert.ok(s1At.sec > 8 - 3.5, "the read outlasts the span: held"); + assert.equal(s2At.kind, "image"); + assert.ok(Math.abs(s2At.at + s2At.sec - plan.total) < 0.01, "the last screen to the item's end"); + const own = st.filter((s) => !s.screen); + assert.ok(own.length >= 1 && Math.abs(own[own.length - 1].at + own[own.length - 1].sec - s1At.at) < 0.01, "its own run up to the first screen"); + assert.equal(plan.held, 0); + // A picture-only post: its picture is in its card, no slot -- no screen step. + const pic = narrated(base({ text: "@thequartering", media: [IMG], screens: [{ ...S2, media: 0 }] }), [["s2", 0]]); + assert.ok(postItemPlan(pic, {}).steps.every((s) => !s.screen)); +}); + +test("the card: the screen typeset -- its header names the author's shown name and says transcribed; a badge pins it; speakers by the privacy rule", () => { + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(html.includes("DMs shown in Savvy&#39;s video") || html.includes("DMs shown in Savvy's video")); + assert.ok(html.includes('data-screen-transcribed=""')); + assert.ok(html.includes('data-screen-badge="s1"') && html.includes("DMs · transcribed")); + assert.ok(html.includes("Refund email shown in Savvy") && html.includes("picture")); + assert.ok(html.includes('data-screen-excerpt=""'), "an excerpted screen says so"); + // Each read line is a block of the read-follow. + for (const n of [0, 1, 2, 3]) assert.ok(new RegExp(`data-screen-line="${n}"><div class="swho">|data-screen-line="${n}"><div class="sbub" data-post-block="\\d+"`).test(html) || html.includes(`data-screen-line="${n}"`)); + assert.equal((html.match(/class="sbub" data-post-block="/g) ?? []).length, 4); + // TheQuartering is not a subject of her item: blurred; hers shown. redact: false shows him. + assert.ok(html.includes('<span class="sname redact">')); + assert.ok(!html.includes(">TheQuartering<")); + const shown = postCardHtml({ ...e, redact: false }, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(shown.includes(">TheQuartering<")); + // The header: a blurred author is "the post's". + assert.equal(screenHeader(e, S1, { authorHidden: true }).text, "DMs shown in the post's video"); + assert.equal(screenHeader(e, S1).badge, "DMs · transcribed"); +}); + +test("anonymity: a speaker who is an anonymous handle is drawn under the shown name; the header the author's shown name; a display name refused", () => { + const set = new Map([["thequartering", "Anon 1"], ["madamsavvy", "Anon 2"]]); + const e = anonymiseEntry(narrated(base({ screens: [{ ...S1, lines: [...S1.lines, { who: "TheQuartering", text: "ask @TheQuartering yourself" }] }] }), [["s1", 0]]), set); + const lines = e.screens[0].lines; + assert.equal(lines[0].who, "Anon 1"); + assert.equal(lines[0].anonymous, true); + assert.equal(lines[4].text, "ask @Anon_1 yourself"); + assert.equal(e.author, "Anon 2"); + assert.equal(screenHeader(e, e.screens[0]).text, "DMs shown in Anon 2's video"); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread }); + assert.ok(!/TheQuartering|MadamSavvy|Savvy&#39;s|Savvy's/.test(html.replace(/Anon 2/g, "")), "no real name or handle in the page"); + assert.ok(html.includes(">Anon 1<")); + // A stray flag is the pass's alone: stripped on the way in. + const stray = anonymiseEntry(base({ screens: [{ ...S1, lines: [{ ...S1.lines[0], anonymous: true }] }] }), new Map([["someone", "Anon 9"]])); + assert.equal(stray.screens[0].lines[0].anonymous, undefined); + // The lint: a speaker written as an anonymous author's display name is an ERROR. + const doc = { characters: [{ id: "tq", name: "Jeremy", handles: ["TheQuartering"], anonymous: true, shown: "Anon 1" }] }; + const m = { timeline: [base({ screens: [{ ...S1, lines: [{ who: "Jeremy", text: "hi" }] }] }), { type: "post", id: "p-x", post: "tq-x/1", platform: "x", author: "Jeremy", handle: "TheQuartering", date: "2026-11-01T00:00:00Z", text: "x" }] }; + assert.ok(anonymityProblems(m, doc).errors.some((x) => /screen s1 names a speaker by Anon 1's display name/.test(x))); +}); + +test("the guard: a part reading a line the screen does not read, a redacted line, or a screen it does not carry is refused, with the fix", () => { + const e = narrated(base()); + assert.deepEqual(threadReadErrors(e, {}), []); + const unread = { ...e, screens: [{ ...S1, read: [{ line: 0 }, { line: 1 }, { line: 3 }] }, S2] }; + assert.ok(threadReadErrors(unread, {}).some((x) => /part 5 reads line 2 of screen s1, which the screen does not read/.test(x) && /posts screen <p> p-2117 read/.test(x))); + const gone = { ...e, screens: [S1] }; + assert.ok(threadReadErrors(gone, {}).some((x) => /reads screen s2, which the item does not carry/.test(x))); + const redacted = { ...e, screens: [{ ...S1, lines: S1.lines.map((l, n) => (n === 3 ? { ...l, redact: true } : l)) }, S2] }; + assert.ok(threadReadErrors(redacted, {}).some((x) => /line 3 of screen s1, which is redacted/.test(x))); +}); + +test("the redaction's terms mark a screen's words and speakers: the card draws bars, the read leaves them out", () => { + const red = { terms: [{ term: "dumb" }, { term: "TheQuartering" }] }; + const out = redactEntry(base(), red); + assert.ok(!out.screens[0].lines[3].text.includes("dumb")); + assert.ok(!out.screens[0].lines[0].who.includes("TheQuartering")); + const e = narrated(base()); + const plan = postItemPlan(e, {}); + const html = postCardHtml(e, { width: 1600, height: 900, follow: true, thread: plan.follow.thread, redaction: red }); + assert.ok(!html.includes("this dumb")); +}); + +test("the lint's warnings: not checked, a masked shape, a read not made, a speaker blurred; a checked screen read whole is quiet", () => { + const e = narrated(base(), [["s1", 0], ["s1", 1]]); + const w = screenWarnings(e, { narrated: true, takeRoles: partRoles(e).map((r) => r.role) }); + assert.ok(w.some((x) => /screen s1's transcription not checked/.test(x))); + assert.ok(w.some((x) => /screen s2 line 2 holds an e-mail address and an order or reference number/.test(x) || /screen s2 line 2 holds/.test(x))); + assert.ok(w.some((x) => /does not read lines 2, 3 of screen s1/.test(x))); + assert.ok(w.some((x) => /does not read screen s2/.test(x))); + assert.ok(w.some((x) => /speaker TheQuartering is drawn blurred/.test(x))); + const quiet = narrated(base({ redact: false, screens: [{ ...S1, checked: { by: "op", at: "2026-11-12T10:00:00Z" } }] }), [["s1", 0], ["s1", 1], ["s1", 2], ["s1", 3]]); + assert.deepEqual(screenWarnings(quiet, { narrated: true, takeRoles: partRoles(quiet).map((r) => r.role) }), []); + assert.ok(screenWarnings(base(), { narrated: false }).some((x) => /drawn and read only on a narrated item/.test(x))); + // Through the cut's lint warnings. + assert.ok(validateThreadReadWarnings({ timeline: [e] }).some((x) => /transcription not checked/.test(x))); +}); diff --git a/umtool/report-to-video/post-thread.mjs b/umtool/report-to-video/post-thread.mjs @@ -55,6 +55,7 @@ import { followKnobs } from "./read-follow.mjs"; import { planContext } from "./post-conversation.mjs"; import { branchMapOf, mapKnobs, mapTimes } from "./post-branch-map.mjs"; import { isPictureOnly, pictureBeatSeconds } from "./post-picture.mjs"; +import { isScreenScope, parseScreenRole, readScreens, screenLineProblem, screenLineSaid, screenOrder, screenPieces, screenReadLines, screenRole, screenScope, screenWarnings, tileOfRole } from "./post-screens.mjs"; /** What a context tile may be. */ export const THREAD_MODES = Object.freeze(["auto", "full", "excerpt", "context", "carry", "hidden"]); @@ -74,7 +75,7 @@ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const str = (v) => (typeof v === "string" ? v : ""); const r3 = (v) => Math.round(v * 1000) / 1000; -const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d)$/; +const ROLE_RE = /^(post|quoted|parent:\d|media:\d|linked:\d|screen:[a-z0-9][a-z0-9-]{0,23}:\d{1,2})$/; // --------------------------------------------------------------------------- // The knobs. @@ -164,6 +165,8 @@ export function readTexts(entry) { add(`linked:${i}`, [str(l.transcript), spoken(l.transcript)], true); }); add("post", [cardText(entry), str(entry?.narration?.script), spoken(cardText(entry))]); + // ITS SCREENS' read lines (post-screens.mjs): each its own text (a take's stored roles name them; a long line is matched). + for (const sc of readScreens(entry)) for (const r of screenReadLines(sc)) add(screenRole(sc.id, r.n), [screenLineSaid(sc, r.n)]); return out; } @@ -186,6 +189,12 @@ const kindOrder = (role) => (role.startsWith("parent:") ? 2 - Number(role.slice( * at theirs -- else by kind (kindOrder). An attachment's words come last. Ranks from 1. */ export function roleOrderOf(entry) { + const base = roleOrderByDate(entry); + // A SCREEN's line (post-screens.mjs) after every other text, in the screens' order and its lines'. + return readScreens(entry).length ? (role) => screenOrder(entry, role) ?? base(role) : base; +} + +function roleOrderByDate(entry) { const dates = new Map(); parentsOf(entry).forEach((p, i) => dates.set(`parent:${i}`, Date.parse(str(p?.date)))); if (isObj(entry?.quoted)) dates.set("quoted", Date.parse(str(entry.quoted.date))); @@ -346,6 +355,11 @@ export function threadLayout(entry, render = undefined, { prev = null, scene = n // THE READ's ORDER (operator, 4 Nov: "read the whole thread chronologically"): the tiles in the order the take // reads them -- a quote read before the post it answers sits above it -- one not read where it stood before the next. orderByRead(tiles, roles); + // ITS SCREENS (post-screens.mjs): each screen the take reads a line of, a tile after his post's, in the screens' order. + for (const sc of readScreens(entry)) { + if (!roles.some((r) => r?.role && parseScreenRole(r.role)?.id === sc.id)) continue; + tiles.push({ scope: screenScope(sc.id), mode: "full", read: true, screen: true }); + } const quotedAtOut = tiles.some((t) => t.above) ? "above" : "inside"; // THE SCENE (post-conversation.mjs): what the run had on screen, in the tree's order with this item's own tiles. const scened = withRelations(entry, isNarrated(entry) ? sceneTiles(entry, tiles, scene, k) : tiles, { group: !!scene?.group || !!groupOf(entry) }); @@ -538,7 +552,7 @@ export const tileModeOf = (layout, scope) => layout?.tiles?.find((t) => t.scope // THE GUARD: never narrate hidden text. // --------------------------------------------------------------------------- -const ROLE_NAME = (r) => (r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r.startsWith("linked:") ? "the post its words link to" : r.startsWith("parent:") ? (r === "parent:0" ? "the post it answers" : "the post that one answers") : `the words on attachment ${Number(r.slice(6)) + 1}`); +const ROLE_NAME = (r) => (parseScreenRole(r) ? `line ${parseScreenRole(r).n} of screen ${parseScreenRole(r).id}` : r === "post" ? "his words" : r === "quoted" ? "the post it quotes" : r.startsWith("linked:") ? "the post its words link to" : r.startsWith("parent:") ? (r === "parent:0" ? "the post it answers" : "the post that one answers") : `the words on attachment ${Number(r.slice(6)) + 1}`); /** * Every reason post item `entry`'s read narrates text the card does not show, @@ -562,6 +576,12 @@ export function threadReadErrors(entry, render = undefined, { prev = null, scene errors.push(`${w}: its take's part ${n} reads words the card does not show (no text on it holds them) -- set its role (umtool posts roles <p> ${entry?.id ?? "<item>"} --set ${n}=post|quoted|parent:0|media:0) ${remake}`); return; } + if (parseScreenRole(r.role)) { + // A SCREEN's line (post-screens.mjs): drawn and lit only when the screen reads it. + const why = screenLineProblem(entry, r.role); + if (why) errors.push(`${w}: its take's part ${n} reads ${why} -- read it (umtool posts screen <p> ${entry?.id ?? "<item>"} set <screen> read=…) or re-make the read without it (umtool posts screen <p> ${entry?.id ?? "<item>"} read)`); + return; + } if (r.role.startsWith("media:")) { const m = (entry?.media ?? [])[Number(r.role.slice(6))]; if (!m) errors.push(`${w}: its take's part ${n} reads attachment ${Number(r.role.slice(6)) + 1}, which it does not have -- set its role (umtool posts roles)`); @@ -601,7 +621,7 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat for (const b of blocks) if (b.part !== null && b.start !== null && !startOfPart.has(b.part)) startOfPart.set(b.part, b.start); // A PICTURE-ONLY context post's BEAT (pictureBeats) is a piece of its own, before the read's first. const beatOf = new Map((Array.isArray(beats) ? beats : []).map((b) => [b.scope, b])); - const pieces = [...beatOf.values()].map((b) => ({ role: b.scope, parts: [], start: b.t0, beat: b.scope !== "post" })).concat(readPieces(entry, roles).map((p) => { + const pieces = [...beatOf.values()].map((b) => ({ role: b.scope, parts: [], start: b.t0, beat: b.scope !== "post" })).concat(tilePieces(readPieces(entry, roles)).map((p) => { const ts = p.parts.map((n) => startOfPart.get(n)).filter(fin); return { ...p, start: ts.length ? Math.min(...ts) : null }; }).filter((p) => p.start !== null && p.role)); @@ -639,6 +659,15 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat row.from = [1, 0]; Object.assign(row, win(T)); } + // ITS SCREENS read after it (post-screens.mjs): his post gives way to a strip as the first comes in. + const S = pieces.find((p) => !p.beat && isScreenScope(p.role) && (T === null || p.start > T))?.start ?? null; + if (S !== null) { + if (row.t1 > row.t0) row.then = { to: small, ...win(S) }; + else { + row.to = small; + Object.assign(row, win(S)); + } + } } else if (t.mode === "scene") { // A post the run left on screen (post-conversation.mjs): it opens as the item before ended, and as the // read begins an ancestor of this item stays on top as context, any other post collapses away. @@ -681,16 +710,19 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat const T0 = firstRead(t.scope); // A quoted post above his: a top-level tile like a parent (revealed, shrunk); inside his: it only dims. const own = t.scope !== "quoted" || !!t.above; + // A SCREEN (post-screens.mjs) read and done COLLAPSES as the next one comes in: stacked, they would bury it. + const done = t.screen ? [0, 0] : small; if (own && revealed(t.scope, T0)) { // Revealed when its read comes (an older post read before it) -- from where the run had it, when it had it. row.from = t.fromScene ?? [1, 0]; row.to = [1, 1]; Object.assign(row, win(T0)); - if (T !== null) row.then = { to: small, ...win(T) }; + if (T !== null) row.then = { to: done, ...win(T) }; } else if (T !== null) { - row.to = own ? small : [1, k.dim]; + row.to = own ? done : [1, k.dim]; Object.assign(row, win(T)); } + if (t.screen) row.screen = true; } if (t.above) row.above = true; if (t.rel) row.rel = t.rel; @@ -702,6 +734,19 @@ export function threadSchedule(entry, render, { layout, blocks, lead = 0.4, beat return { shrink: k.shrink, dim: k.dim, seconds: k.seconds, pan: k.pan, contextRoom: THREAD_CONTEXT_ROOM, quotedAt: above ? "above" : "inside", tiles, ...(map ? { map } : {}) }; } +/** The read's pieces on their TILES: a screen's lines (post-screens.mjs) are one piece of its tile; any other role its own. */ +function tilePieces(pieces) { + if (!pieces.some((p) => p.role && isScreenScope(p.role))) return pieces; + const out = []; + for (const p of pieces) { + const role = p.role ? tileOfRole(p.role) : p.role; + const last = out[out.length - 1]; + if (last && last.role === role && role) last.parts = [...last.parts, ...p.parts]; + else out.push({ ...p, role }); + } + return out; +} + /** inOut cubic over [0, 1]. */ const ease = (x) => { const v = Math.min(1, Math.max(0, x)); @@ -767,7 +812,7 @@ export function threadGeoAt(geo, scales) { if (y >= t.top + t.height - 0.5) d += (1 - t.s) * t.height; else if (y > t.top) d += (1 - t.s) * (y - t.top); // A scene tile collapsing away (post-conversation.mjs) closes the gap above it too. - if (t.gap > 0 && t.scope.startsWith("conv:") && y >= t.top - 0.5) d += (1 - t.s) * t.gap; + if (t.gap > 0 && (t.scope.startsWith("conv:") || isScreenScope(t.scope)) && y >= t.top - 0.5) d += (1 - t.s) * t.gap; } return y - d; }; @@ -836,10 +881,13 @@ export function isTruncated(text) { return /…$/.test(t) || /\bshow more$/i.test(t); } -/** THE WARNINGS over a cut (the build's lint): every narrated post item's (threadReadWarnings). */ +/** THE WARNINGS over a cut (the build's lint): every narrated post item's (threadReadWarnings), and its screens' (post-screens.mjs). */ export function validateThreadReadWarnings(manifest) { const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; - return tl.filter((e) => e?.type === "post").flatMap((e) => threadReadWarnings(e)); + return tl.filter((e) => e?.type === "post").flatMap((e) => [ + ...threadReadWarnings(e), + ...(Array.isArray(e.screens) ? screenWarnings(e, { narrated: isNarrated(e), takeRoles: isNarrated(e) ? partRoles(e).map((r) => r.role) : [] }) : []), + ]); } /** @@ -1003,5 +1051,8 @@ export function chronoPieces(entry, { skip = [] } = {}) { if (isObj(entry?.quoted)) add("quoted", entry.quoted, contextText(entry.quoted)); linksOf(entry).forEach((l, i) => add(`linked:${i}`, l, [contextText(l), str(l.transcript)].filter((t) => t.trim()).join("\n\n"))); add("post", entry, cardText(entry)); - return out.sort((a, b) => order(a.role) - order(b.role)); + out.sort((a, b) => order(a.role) - order(b.role)); + // ITS SCREENS' read lines (post-screens.mjs), after everything else, in the screens' order: `who` as written. + for (const p of screenPieces(entry)) if (!skip.includes(p.role)) out.push({ role: p.role, date: null, author: null, handle: null, who: p.who, screen: p.screen, text: p.text }); + return out; } diff --git a/umtool/report-to-video/read-follow.mjs b/umtool/report-to-video/read-follow.mjs @@ -50,6 +50,7 @@ import { partRoles, threadGeoAt, threadKnobs, threadLayout, threadSchedule, thre import { sceneLayout, sceneRows, sceneSchedule } from "./post-media-scene.mjs"; import { linkVisits, visitRows, visitStateAt } from "./post-link-visit.mjs"; import { mapStateAt } from "./post-branch-map.mjs"; +import { isScreenScope, parseScreenRole, screenScope } from "./post-screens.mjs"; export const FOLLOW_DEFAULTS = Object.freeze({ on: true, dim: 0.65, ease: 0.25 }); export const FOLLOW_LIMITS = Object.freeze({ dim: [0.2, 1], ease: [0, 2] }); @@ -229,7 +230,16 @@ export function followBlocks(entry) { const byScope = new Map(scopes.map((sc) => [sc.scope, { sc, spans: [], cursor: 0 }])); // A part read off an attachment (a screenshot's words, post-thread.mjs): a block with no words on the card. const media = []; + // A SCREEN's line (post-screens.mjs): a block of its own -- the line, drawn by the screen's tile -- named by its role, + // never matched by words; a line read in several parts is one block (from its first part). + const screenLines = new Set(); parts.forEach((p, pi) => { + const sl = typeof p.scope === "string" ? parseScreenRole(p.scope) : null; + if (sl) { + if (!screenLines.has(p.scope)) media.push({ scope: screenScope(sl.id), line: sl.n, from: null, to: null, part: pi }); + screenLines.add(p.scope); + return; + } if (typeof p.scope === "string" && p.scope.startsWith("media:")) { media.push({ scope: p.scope, from: null, to: null, part: pi }); return; @@ -471,7 +481,7 @@ export function followPath(follow, geo) { } /** The tile a block's scope is drawn in (a quoted post is a tile inside his post's). */ -const tileScopeOf = (scope) => (scope === "quoted" || scope === "post" || String(scope).startsWith("parent:") || String(scope).startsWith("linked:") ? scope : null); +const tileScopeOf = (scope) => (scope === "quoted" || scope === "post" || String(scope).startsWith("parent:") || String(scope).startsWith("linked:") || isScreenScope(scope) ? scope : null); /** * A THREADED card's PAN (post-thread.mjs), pure: `{ thread: true, start, @@ -642,13 +652,15 @@ export function followStateAt(follow, path, s) { for (const [scope, [sc, o]] of Object.entries(ts)) { const h = path?.tiles?.[scope]?.height ?? 0; // A scene tile (post-conversation.mjs) collapsing away takes the gap above it with it. - const gap = scope.startsWith("conv:") ? path?.tiles?.[scope]?.gap ?? 0 : 0; + const gap = scope.startsWith("conv:") || isScreenScope(scope) ? path?.tiles?.[scope]?.gap ?? 0 : 0; tiles[scope] = gap > 0 ? [sc, o, Math.round(h * 100) / 100, Math.round(gap * 100) / 100] : [sc, o, Math.round(h * 100) / 100]; if (sc < 0.9995 && gap > 0) C -= (1 - sc) * gap; // A tile closes the flow up under it as it shrinks -- a quoted post inside his post never shrinks; one above it does. if (sc < 0.9995 && (scope !== "quoted" || follow.thread.quotedAt === "above")) C -= (1 - sc) * h; } const below = C - (path?.H ?? 0) - offset; + // A SCREEN up (post-screens.mjs): the one in full now -- its badge ("· transcribed") pinned to the card while it is. + const scr = screenUpAt(ts); return { op, offset, @@ -657,6 +669,7 @@ export function followStateAt(follow, path, s) { current, tiles, ...jp, + ...(scr !== undefined ? { screen: scr } : {}), }; } return { @@ -669,8 +682,21 @@ export function followStateAt(follow, path, s) { }; } +/** + * The SCREEN up at a thread state (post-screens.mjs): the id of the last screen tile at half its size and strength or + * more, null when none is -- undefined when the card has no screen tile (its state then carries no `screen`). + * @param {Record<string, number[]>} ts + */ +function screenUpAt(ts) { + const scopes = Object.keys(ts).filter(isScreenScope); + if (!scopes.length) return undefined; + let up = null; + for (const sc of scopes) if (ts[sc][0] >= 0.5 && ts[sc][1] >= 0.5) up = sc.slice(7); + return up; +} + /** A state's key: two frames with the same key draw the same card (the build shoots each key once). */ -export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom, ...(st.tiles ? [st.tiles] : []), ...(st.join !== undefined ? [st.join] : []), ...(st.visit ? [st.visit] : []), ...(st.map ? [st.map] : [])]); +export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom, ...(st.tiles ? [st.tiles] : []), ...(st.join !== undefined ? [st.join] : []), ...(st.visit ? [st.visit] : []), ...(st.map ? [st.map] : []), ...(st.screen !== undefined ? [{ screen: st.screen }] : [])]); /** * Whether a state draws the card PAGE AS DRAWN (no state applied): nothing @@ -683,7 +709,7 @@ export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeT */ export function isDrawnState(st) { if (!st) return true; - if (fin(st.join) || st.visit || st.map) return false; + if (fin(st.join) || st.visit || st.map || (typeof st.screen === "string" && st.screen)) return false; if (Object.values(st.op ?? {}).some((o) => fin(o) && o < 0.9995)) return false; if (fin(st.offset) && Math.abs(st.offset) >= 0.5) return false; if ((st.fadeTop ?? 0) > 0 || (st.fadeBottom ?? 0) > 0) return false; @@ -705,7 +731,7 @@ export function isDrawnState(st) { export const READ_IN_VIEW = Object.freeze({ tol: 2, slack: 0.25, share: 0.5, step: 0.05, size: 0.005 }); const pct = (v) => `${Math.round(v * 100)}%`; -const tileName = (scope) => (scope === "post" ? "his post" : scope === "quoted" ? "the quoted post" : String(scope).startsWith("parent:") ? `the post it answers (${scope})` : String(scope).startsWith("linked:") ? `the post it links (${scope})` : String(scope)); +const tileName = (scope) => (isScreenScope(scope) ? `screen ${String(scope).slice(7)}` : scope === "post" ? "his post" : scope === "quoted" ? "the quoted post" : String(scope).startsWith("parent:") ? `the post it answers (${scope})` : String(scope).startsWith("linked:") ? `the post it links (${scope})` : String(scope)); /** * THE READ IN VIEW, pure: every reason the words being read are not on screen, @@ -948,5 +974,10 @@ export function applyFollowState(state, doc = document) { const el = doc.querySelector(`[data-post-fade="${side}"]`); if (el) el.style.opacity = String(v || 0); } + // A SCREEN's badge (post-screens.mjs): shown while that screen is up. + for (const el of Array.from(doc.querySelectorAll("[data-screen-badge]"))) { + const v = state && state.screen === el.getAttribute("data-screen-badge") ? "1" : ""; + if (el.style.opacity !== v) el.style.opacity = v; + } if (doc.body) doc.body.setAttribute("data-post-follow-block", state && state.current !== null && state.current !== undefined ? String(state.current) : ""); }