Archilyzer · Source

archilyzer

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

commit 1f70f16412ba4f95ee619bde15fac0b0cd8e1316
parent 5d04480e69f66c3f6c31206c5ae070d02b98df3d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun,  8 Nov 2026 03:58:49 -0500

umtool: present mode -- the cut as slides, navigated like a deck

/projects/<p>/present (?take=, ?cut=1): lib/report/present.mjs cuts Play's
view (playView.mjs playViewWith, the take's patch as Play applies it, the
latest take by default) into slides -- a post slide per post item keyed by
its post's id, a clip slide per clip the walk kept (its spans, the deck's
words), teaser and text slides, section dividers from the markers or day
dividers for a chronological posts reel -- with each post's censor data by
kind; canUncensor false carries the censored posts and no reveal data.

The viewer draws posts with Play's own PostItemPlayer on a per-slide clock
(new optional props: a card view of censor toggles, narration and attachment
sound), keys/clicks/swipe, an outline strip, #<slide id> history, a settings
drawer kept in localStorage. The post-item route takes redact=0, authors=0
and blur=0 for the toggles. GET /api/report/present and `umtool present`
are its twins; Present links beside Play in the project head and take cards.

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

Diffstat:
Mumtool/app/api/report/post-item/route.ts | 26++++++++++++++++++++++++++
Aumtool/app/api/report/present/route.ts | 16++++++++++++++++
Mumtool/bin/umtool.mjs | 6++++++
Mumtool/components/projects/ProjectPrimary.tsx | 5++++-
Mumtool/components/projects/ProjectView.tsx | 3+++
Mumtool/components/projects/TakesBench.tsx | 11++++++++++-
Aumtool/components/projects/present/PresentPage.tsx | 36++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/present/PresentView.tsx | 743+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/PostItemPlayer.tsx | 53+++++++++++++++++++++++++++++++++++++++--------------
Mumtool/lib/hrefs.ts | 9+++++++++
Mumtool/lib/report/playView.mjs | 21+++++++++++++++++++--
Aumtool/lib/report/present.mjs | 415+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/presentCli.mjs | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
13 files changed, 1423 insertions(+), 18 deletions(-)

diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts @@ -34,6 +34,10 @@ export const dynamic = "force-dynamic"; // (post-redact.mjs), never in the page, its slurs // masked (post-slurs.mjs); &uncensored=1 the // slurs as posted (the redaction kept) +// PRESENT MODE's toggles (lib/report/present.mjs), each +// kind off on its own: &redact=0 the redacted words shown +// (the slurs as published says), &authors=0 no author +// blurred, &blur=0 no attachment censored // GET ?project&side=<clip>&w&h[&take][&published=1] a clip's SIDE POST's card page (side-card.mjs, // lane vertical): the post shown beside the clip, at w × h // GET ?project&file=posts-media/… an attachment (byte ranges): only a file @@ -91,6 +95,24 @@ const TYPES: Record<string, string> = { const wordsRelOf = (src: string) => `${src.replace(/\.[^./]+$/, "")}.words.json`; +/** The item with its own censors off (present mode): every author drawn as named, every attachment as captured. */ +function uncensoredItem(item: Entry, { authors, blur }: { authors: boolean; blur: boolean }): Entry { + const out: Entry = { ...item }; + if (authors) out.redact = false; + if (blur && Array.isArray(item.media)) out.media = item.media.map((m) => (m && typeof m === "object" && "blur" in m ? { ...m, blur: { ...(m.blur as object), on: false } } : m)); + return out; +} + +type Redaction = Awaited<ReturnType<typeof projectRedaction>>; + +/** A redaction with its terms (and its markup's spans) off, or its markup's attachment censors off. */ +function redactionWithout(red: Redaction, { terms, censor }: { terms: boolean; censor: boolean }): Redaction { + const markup = Object.fromEntries( + Object.entries((red.markup ?? {}) as Record<string, { redact?: unknown[]; censor?: unknown[] }>).map(([k, m]) => [k, { ...m, ...(terms ? { redact: [] } : {}), ...(censor ? { censor: [] } : {}) }]), + ); + return { ...red, ...(terms ? { terms: [] } : {}), markup } as Redaction; +} + export async function GET(request: Request) { const q = new URL(request.url).searchParams; const r = await resolveReport(q.get("project") ?? ""); @@ -160,6 +182,8 @@ export async function GET(request: Request) { return new Response(e instanceof Error ? e.message : String(e), { status: 400 }); } if (!found.item) return new Response(`no post item ${id}`, { status: 404 }); + // PRESENT MODE's toggles: the item's own censors off, kind by kind (the redaction's are below). + if (q.get("authors") === "0" || q.get("blur") === "0") found.item = uncensoredItem(found.item, { authors: q.get("authors") === "0", blur: q.get("blur") === "0" }); const tw = q.get("takeWords"); if (tw) { @@ -225,6 +249,8 @@ export async function GET(request: Request) { } catch (e) { return new Response(e instanceof Error ? e.message : String(e), { status: 500 }); } + // redact=0: the redaction's terms and markup spans off, its slur filter kept; blur=0: the markup's censors off too. + if (redaction && (q.get("redact") === "0" || q.get("blur") === "0")) redaction = redactionWithout(redaction, { terms: q.get("redact") === "0", censor: q.get("blur") === "0" }); const cutRender = (found.manifest.render ?? render) as Record<string, unknown>; const followOn = q.get("phase") !== "media" && followKnobs(found.item, cutRender).on; // Its MEDIA SCENE (post-media-scene.mjs): neighbours that carry the same attachment, by the combo counter's diff --git a/umtool/app/api/report/present/route.ts b/umtool/app/api/report/present/route.ts @@ -0,0 +1,16 @@ +import { projectRef } from "@/lib/projects"; +import { presentPayload } from "@/lib/report/present.mjs"; + +export const dynamic = "force-dynamic"; + +// PRESENT MODE's payload as JSON (lib/report/present.mjs; umtool/docs/knobs.md, "Present mode"): what +// `/projects/<p>/present` shows -- the cut as slides. GET ?project=<id>[&take=<id> | &cut=1][&public=1]; no take: +// the latest take, as Play. `public=1`: the payload a public page would carry (the posts censored, no reveal data). +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + const project = await projectRef(q.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + const payload = await presentPayload(project, { take: q.get("take") || null, bare: q.get("cut") === "1", canUncensor: q.get("public") !== "1" }); + if ("error" in payload) return Response.json(payload, { status: 400 }); + return Response.json(payload, { headers: { "cache-control": "no-store" } }); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -919,6 +919,10 @@ function usage() { " patch, an undo point first (`umtool timeline <p> --take <id> undo`); the manifest is untouched", " umtool walk <project> [--take <id>] [--all] [--json] the clip bench's walk: every clip in walk order,", " its verdict, fetched or not, and (→) the ones the walk visits; --take walks a take (a draft too)", + " umtool present <project> [--take <id> | --cut] [--json] [--public] [--open] PRESENT MODE: the cut as slides,", + " navigated like a deck (/projects/<p>/present); prints its address and its slides (#<slide id> opens", + " one); --json the payload (posts with their censor data by kind, clips' spans, section/day dividers);", + " --public the payload a public page would carry (censored, no reveal data); --open opens it", " umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):", " claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp", " claim.count claim.label (the first mark's, or --mark <id>'s) · marks: mark.add=<verdict>[@<sec>]", @@ -1146,6 +1150,8 @@ const COMMANDS = { window: cmdWindow, // The clip bench's walk, of the cut or of a take (walk a take): lib/report/walkCli.mjs. walk: async () => process.exit(await (await import("../lib/report/walkCli.mjs")).walkCommand(argv.slice(argv.indexOf("walk") + 1))), + // Present mode: the cut as slides (lib/report/presentCli.mjs). + present: async () => process.exit(await (await import("../lib/report/presentCli.mjs")).presentCommand(argv.slice(argv.indexOf("present") + 1))), link: cmdLink, // The video knobs (plans/video-knobs-ui.md): lib/report/knobsCli.mjs. set: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).setCommand(argv.slice(argv.indexOf("set") + 1))), diff --git a/umtool/components/projects/ProjectPrimary.tsx b/umtool/components/projects/ProjectPrimary.tsx @@ -1,6 +1,6 @@ import Link from "next/link"; import { buttonVariants } from "@/components/ui/button"; -import { clipBenchHref, projectHref, takeWalkHref } from "@/lib/hrefs"; +import { clipBenchHref, projectHref, takeWalkHref, presentHref } from "@/lib/hrefs"; import PlayLink from "./PlayLink"; import type { ClipDetail } from "./report/shared"; @@ -46,6 +46,9 @@ export default function ProjectPrimary({ project, detail, latest, words = null } return ( <> <PlayLink project={project} where="header" variant="header" label={latest ? `▶ Play ${latest}` : "▶ Play the cut"} /> + <Link href={presentHref(project)} prefetch={false} data-present-link="header" className={buttonVariants({ variant: "quiet", size: "md" })} title="the cut as slides, one at a time, navigated like a deck (present mode)"> + Present + </Link> {words && ( <span className="font-mono text-[11px] text-muted" data-primary-latest={latest ?? ""}> {words} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -15,6 +15,7 @@ import VoicesPage from "./VoicesPage"; import ReviewPage from "./ReviewPage"; import ClipDeckPage from "./ClipDeckPage"; import PlayCutPage from "./PlayCutPage"; +import PresentPage from "./present/PresentPage"; import TakeWalkPage from "./TakeWalkPage"; import ReelPlayPage from "./reel/ReelPlayPage"; import ReelWalkPage from "./reel/ReelWalkPage"; @@ -106,6 +107,8 @@ export default async function ProjectView({ if (rest.length === 2 && rest[0] === "trailer" && rest[1] === "walk") { return <ReelWalkPage project={project} reel={search.reel} take={search.take} beat={search.beat} changed={search.changed === "1"} />; } + // `/projects/<project>/present` (and `?take=<id>`) -- the cut as slides, navigated like a deck (present mode). + if (rest.length === 1 && rest[0] === "present") return <PresentPage project={project} take={search.take} bare={search.cut === "1"} />; if (rest.length === 1 && rest[0] === "play") return <PlayCutPage project={project} take={search.take} bare={search.cut === "1"} note={search.note} clip={search.clip} at={search.at} />; return notFound(); } diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx @@ -11,7 +11,7 @@ import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; import { buttonVariants } from "@/components/ui/button"; import { fmtAgo, fmtBytes } from "@/lib/format"; import { cn } from "@/lib/utils"; -import { playHref, takeWalkHref } from "@/lib/hrefs"; +import { playHref, takeWalkHref, presentHref } from "@/lib/hrefs"; import RenderRecord from "@/components/queue/RenderRecord"; import type { RenderView } from "@/lib/queue/view"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; @@ -768,6 +768,15 @@ function TakeCard({ > ▶ Play </Link> + <Link + href={presentHref(project, { take: t.id })} + data-present-link="take-card" + data-present-take={t.id} + className={buttonVariants({ variant: "quiet", size: "sm" })} + title="this take as slides, one at a time, navigated like a deck (present mode)" + > + Present + </Link> <button type="button" data-action="listen" diff --git a/umtool/components/projects/present/PresentPage.tsx b/umtool/components/projects/present/PresentPage.tsx @@ -0,0 +1,36 @@ +import Link from "next/link"; +import { playHref, presentHref } from "@/lib/hrefs"; +import { pieceHrefOfProject } from "@/lib/pieces/article"; +import type { ProjectRef } from "@/lib/project-types"; +import { presentPayload } from "@/lib/report/present.mjs"; +import PresentView, { type PresentPayload } from "./PresentView"; + +// `/projects/<project>/present` (and `?take=<id>`, `?cut=1`) -- PRESENT MODE (umtool/docs/knobs.md, "Present +// mode"): the cut as slides, one at a time, navigated like a deck. lib/report/present.mjs makes the payload (Play's +// view cut into slides); PresentView.tsx shows it. umtool is the operator's, so the payload carries what the build +// censors as data the viewer can toggle (`canUncensor`). + +export default async function PresentPage({ project, take, bare = false }: { project: ProjectRef; take?: string; bare?: boolean }) { + const [payload, back] = await Promise.all([presentPayload(project, { take: take || null, bare, canUncensor: true }), pieceHrefOfProject(project.id, { tab: "cut" })]); + if ("error" in payload) { + return ( + <main data-present-error="" className="flex h-full flex-col items-start gap-2 p-6 text-[13px]"> + <p className="text-reject-text">{String(payload.error)}</p> + <p className="flex gap-3"> + {take && ( + <Link href={presentHref(project.id)} className="ink-link"> + present the latest cut instead + </Link> + )} + <Link href={playHref(project.id)} className="ink-link"> + Play the cut + </Link> + <Link href={back} className="ink-link"> + ‹ {project.id} + </Link> + </p> + </main> + ); + } + return <PresentView payload={payload as unknown as PresentPayload} back={back} playHref={playHref(project.id, { take: take || null, bare })} />; +} diff --git a/umtool/components/projects/present/PresentView.tsx b/umtool/components/projects/present/PresentView.tsx @@ -0,0 +1,743 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import PostItemPlayer, { postItemAssets, type CardView, type PostPlan, type ProgressPlan } from "../review/PostItemPlayer"; +import ComboBadge, { type ComboInfo } from "../review/ComboBadge"; +import { postPreload } from "../review/playEngine/postPreload"; + +// --------------------------------------------------------------------------- +// PRESENT MODE, THE VIEWER (umtool/docs/knobs.md, "Present mode"; operator, 8 Nov 2026): the cut as slides, one at +// a time, full stage, navigated like a deck -- ← → PgUp PgDn Space Shift+Space Home End, a click on the stage's left +// or right third, a swipe; the outline strip under it (its sections or days, a cell per slide); `#<slide id>` in the +// address per slide, each move a history entry (Back returns to the slide before), a link opens on its slide. +// +// A POST slide is drawn by Play's own player (PostItemPlayer: the card page the build screenshots, its attachments, +// its narration's mix, its read-follow) on the slide's own clock from 0 as it arrives; a CLIP slide plays its spans +// (its cut minus its gaps) from the cached window Play plays; a section, a day, a teaser are text. +// +// THE SETTINGS (key s): what the card censors, kind by kind (only when the payload can uncensor), the narration, +// auto-advance after the read and a linger, the attachments' sound -- each viewer's own, in this browser +// (localStorage; the page works without it). +// --------------------------------------------------------------------------- + +type Box = { width: number; height: number }; +type Span = { from: number; to: number }; +type Section = { id: string; kind: "section" | "day" | "cut"; label: string; date?: string; level?: number; color?: string | null }; +type Censor = { marks: Array<{ kind: string; field: string; start: number; end: number; mask?: string }>; authors: unknown[]; media: unknown[]; counts: Record<CensorKind, number> } | null; +type SlideBase = { id: string; section: string; label: string; date: string | null; dateLabel: string | null; entry: string | null }; +type PostSlide = SlideBase & { + kind: "post"; + post: Record<string, unknown> & { id: string }; + plan: PostPlan; + progress: ProgressPlan | null; + clock: Parameters<typeof PostItemPlayer>[0]["clock"]; + scene: { key: string; n: number; of: number } | null; + combo: ComboInfo | null; + narration: { file: string; seconds: number } | null; + qrUrl: string | null; + censor: Censor; +}; +type ClipSlide = SlideBase & { + kind: "clip"; + media: { name: string; from: number; to: number; v?: string } | null; + spans: Span[]; + seconds: number; + title: string; + subtitle: string; + quote: string | null; + qrUrl: string | null; + blur: { strength: number; caption: string; from: number | null; to: number | null } | null; +}; +type TextSlide = SlideBase & { kind: "section" | "day" | "teaser" | "card"; lines?: string[]; tail?: string | null; seconds?: number | null; heading?: string; within?: string | null }; +type VideoSlide = SlideBase & { kind: "video"; src: string; from: number; to: number; seconds: number }; +export type Slide = PostSlide | ClipSlide | TextSlide | VideoSlide; +type CensorKind = "names" | "slurs" | "authors" | "pictures"; +export type PresentSettings = { censor: Record<CensorKind, boolean>; narration: boolean; autoAdvance: boolean; linger: number; sound: boolean }; +export type PresentPayload = { + version: number; + project: string; + take: { id: string; label: string; defaulted: boolean } | null; + title: string; + capabilities: { canUncensor: boolean }; + settings: PresentSettings; + box: Box; + zone: string; + blurRendered: boolean; + sections: Section[]; + slides: Slide[]; +}; + +const SETTINGS_KEY = "umtool.present.settings.v1"; +const CENSOR_WORDS: Record<CensorKind, string> = { + names: "Redacted names", + slurs: "Slurs masked", + authors: "Private authors blurred", + pictures: "Censored pictures", +}; +/** How long a text slide stands before it counts as read (auto-advance), seconds. */ +const TEXT_SECONDS = { section: 2.5, day: 2, teaser: 4, card: 3 } as const; + +/** A slide id in the address: readable (`#postchan-x/1`), never ambiguous. */ +const hashOf = (id: string) => `#${encodeURIComponent(id).replace(/%2F/g, "/").replace(/%40/g, "@")}`; +const idOfHash = (hash: string) => { + try { + return decodeURIComponent(hash.replace(/^#/, "")); + } catch { + return hash.replace(/^#/, ""); + } +}; + +function readSettings(defaults: PresentSettings): PresentSettings { + try { + const raw = window.localStorage.getItem(SETTINGS_KEY); + if (!raw) return defaults; + const v = JSON.parse(raw) as Partial<PresentSettings>; + const b = (x: unknown, d: boolean) => (typeof x === "boolean" ? x : d); + return { + censor: { + names: b(v.censor?.names, defaults.censor.names), + slurs: b(v.censor?.slurs, defaults.censor.slurs), + authors: b(v.censor?.authors, defaults.censor.authors), + pictures: b(v.censor?.pictures, defaults.censor.pictures), + }, + narration: b(v.narration, defaults.narration), + autoAdvance: b(v.autoAdvance, defaults.autoAdvance), + linger: typeof v.linger === "number" && Number.isFinite(v.linger) ? Math.min(30, Math.max(0, v.linger)) : defaults.linger, + sound: b(v.sound, defaults.sound), + }; + } catch { + return defaults; + } +} + +function writeSettings(s: PresentSettings) { + try { + window.localStorage.setItem(SETTINGS_KEY, JSON.stringify(s)); + } catch { + // A private window, blocked storage: the settings hold for this visit. + } +} + +/** The slide's own clock: seconds since it arrived, stopped while paused. Reset by `key`. */ +function useSlideClock(key: string, running: boolean) { + // Keyed: the frame a new slide arrives on reads 0, never the last slide's seconds. + const [st, setSt] = useState({ key, s: 0 }); + const base = useRef({ key, at: 0 }); + useEffect(() => { + if (!running) return; + if (base.current.key !== key) base.current = { key, at: 0 }; + let raf = 0; + const t0 = performance.now(); + const from = base.current.at; + const tick = () => { + const now = from + (performance.now() - t0) / 1000; + base.current.at = now; + setSt({ key, s: now }); + raf = requestAnimationFrame(tick); + }; + raf = requestAnimationFrame(tick); + return () => cancelAnimationFrame(raf); + }, [running, key]); + return st.key === key ? st.s : 0; +} + +/** The stage's box: the frame's aspect fitted into the space it has. */ +function useFitted(box: Box) { + const ref = useRef<HTMLDivElement | null>(null); + const [size, setSize] = useState<Box | null>(null); + useEffect(() => { + const node = ref.current; + if (!node) return; + const ro = new ResizeObserver(([e]) => { + const { width, height } = e.contentRect; + const k = Math.min(width / box.width, height / box.height); + setSize({ width: Math.floor(box.width * k), height: Math.floor(box.height * k) }); + }); + ro.observe(node); + return () => ro.disconnect(); + }, [box.width, box.height]); + return { ref, size }; +} + +export default function PresentView({ payload, back, playHref }: { payload: PresentPayload; back: string; playHref: string }) { + const { slides, sections, box } = payload; + const project = payload.project; + const take = payload.take?.id ?? null; + const n = slides.length; + const indexOfId = useMemo(() => new Map(slides.map((s, i) => [s.id, i])), [slides]); + const [index, setIndex] = useState(0); + const [paused, setPaused] = useState(false); + const [drawer, setDrawer] = useState(false); + const [settings, setSettings] = useState<PresentSettings>(payload.settings); + const [loaded, setLoaded] = useState(false); + const canUncensor = payload.capabilities.canUncensor; + const view: CardView = canUncensor ? settings.censor : { names: true, slurs: true, authors: true, pictures: true }; + + // ---- the settings: this viewer's own, read once mounted (the server drew the defaults) ---- + useEffect(() => { + setSettings(readSettings(payload.settings)); + setLoaded(true); + }, [payload.settings]); + const update = useCallback((patch: Partial<PresentSettings>) => { + setSettings((s) => { + const next = { ...s, ...patch, censor: { ...s.censor, ...(patch.censor ?? {}) } }; + writeSettings(next); + return next; + }); + }, []); + + // ---- the address: #<slide id>, a history entry per move ---- + useEffect(() => { + const fromHash = () => { + const i = indexOfId.get(idOfHash(window.location.hash)); + if (i !== undefined) setIndex(i); + return i; + }; + const first = fromHash(); + if (first === undefined && slides[0]) window.history.replaceState(window.history.state, "", hashOf(slides[0].id)); + const onPop = () => { + fromHash(); + }; + window.addEventListener("popstate", onPop); + window.addEventListener("hashchange", onPop); + return () => { + window.removeEventListener("popstate", onPop); + window.removeEventListener("hashchange", onPop); + }; + }, [indexOfId, slides]); + const indexRef = useRef(index); + indexRef.current = index; + const go = useCallback( + (i: number) => { + const to = Math.max(0, Math.min(n - 1, i)); + if (to === indexRef.current || !slides[to]) return; + indexRef.current = to; + window.history.pushState(window.history.state, "", hashOf(slides[to].id)); + setIndex(to); + setPaused(false); + }, + [n, slides], + ); + const next = useCallback(() => go(indexRef.current + 1), [go]); + const prev = useCallback(() => go(indexRef.current - 1), [go]); + + // ---- the keys ---- + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + const t = e.target as HTMLElement | null; + if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) { + if (e.key === "Escape") t.blur(); + return; + } + if (e.metaKey || e.ctrlKey || e.altKey) return; + const k = e.key; + let done = true; + if (k === "ArrowRight" || k === "PageDown" || (k === " " && !e.shiftKey)) next(); + else if (k === "ArrowLeft" || k === "PageUp" || (k === " " && e.shiftKey)) prev(); + else if (k === "Home") go(0); + else if (k === "End") go(n - 1); + else if (k === "s" || k === "S") setDrawer((d) => !d); + else if (k === "Escape") setDrawer(false); + else if (k === "p" || k === "k") setPaused((p) => !p); + else done = false; + if (done) e.preventDefault(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [next, prev, go, n]); + + // ---- the slide on stage, its clock and whether it is read ---- + const slide = slides[index] ?? null; + const clock = useSlideClock(slide?.id ?? "", !!slide && !paused); + const clockRef = useRef(0); + clockRef.current = clock; + const [clipDoneAt, setClipDoneAt] = useState<{ id: string; s: number } | null>(null); + const readEnd = useMemo(() => { + if (!slide) return null; + if (slide.kind === "post") return slide.plan.total; + if (slide.kind === "clip" || slide.kind === "video") return clipDoneAt?.id === slide.id ? clipDoneAt.s : null; + return slide.kind === "teaser" && slide.seconds ? slide.seconds : TEXT_SECONDS[slide.kind as keyof typeof TEXT_SECONDS] ?? 3; + }, [slide, clipDoneAt]); + const read = readEnd !== null && clock >= readEnd; + useEffect(() => { + if (!settings.autoAdvance || readEnd === null || paused || index >= n - 1) return; + if (clock >= readEnd + settings.linger) next(); + }, [clock, readEnd, settings.autoAdvance, settings.linger, paused, index, n, next]); + const onClipDone = useCallback((id: string) => setClipDoneAt((d) => (d?.id === id ? d : { id, s: clockRef.current })), []); + + // ---- the post items around it, fetched ahead (Play's preloader) ---- + useEffect(() => { + const assets = (i: number) => { + const sl = slides[i]; + if (!sl || sl.kind !== "post") return null; + return postItemAssets({ project, take, entry: sl.post, plan: sl.plan, box, view, joinFrom: joinOf(slides, i) }); + }; + const keep = [index - 1, index].map(assets).filter((x): x is NonNullable<typeof x> => !!x); + const ahead = [index + 1, index + 2, index + 3].map(assets).filter((x): x is NonNullable<typeof x> => !!x); + postPreload.want(ahead, keep); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [index, slides, project, take, box, view.names, view.slurs, view.authors, view.pictures]); + useEffect(() => () => postPreload.clear(), []); + + // ---- touch: a swipe ---- + const touch = useRef<{ x: number; y: number } | null>(null); + const onTouchStart = (e: React.TouchEvent) => { + const t = e.touches[0]; + touch.current = t ? { x: t.clientX, y: t.clientY } : null; + }; + const onTouchEnd = (e: React.TouchEvent) => { + const t0 = touch.current; + const t = e.changedTouches[0]; + touch.current = null; + if (!t0 || !t) return; + const dx = t.clientX - t0.x; + if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(t.clientY - t0.y)) { + if (dx < 0) next(); + else prev(); + } + }; + + const { ref: stageRef, size } = useFitted(box); + const sectionOf = useMemo(() => new Map(sections.map((s) => [s.id, s])), [sections]); + const progress = slide ? `${index + 1} / ${n}${slide.dateLabel ? ` · ${slide.dateLabel}` : ""}` : "0 / 0"; + + return ( + <div + data-present="" + data-present-slide={slide?.id ?? ""} + data-present-index={String(index)} + data-present-kind={slide?.kind ?? ""} + data-present-state={paused ? "paused" : "playing"} + data-present-read={read ? "1" : "0"} + data-present-settings-loaded={loaded ? "1" : "0"} + className="fixed inset-0 flex select-none flex-col overflow-hidden bg-black text-white" + onTouchStart={onTouchStart} + onTouchEnd={onTouchEnd} + > + <h1 className="sr-only">{payload.title} — present</h1> + {/* THE STAGE: one slide, the frame's aspect, as large as the window allows. */} + <div ref={stageRef} className="relative min-h-0 flex-1"> + {size && slide && ( + <div + data-present-stage="" + className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 overflow-hidden bg-black" + style={{ width: size.width, height: size.height }} + > + <SlideView + key={slide.id} + slide={slide} + slides={slides} + index={index} + project={project} + take={take} + box={box} + s={clock} + playing={!paused} + settings={settings} + view={view} + section={sectionOf.get(slide.section) ?? null} + sections={sections} + blurRendered={payload.blurRendered} + onDone={onClipDone} + /> + {/* The click zones: the left third back, the right third on, the middle pauses. */} + <div className="absolute inset-0 z-40 flex"> + <button type="button" aria-label="previous slide" data-present-zone="prev" className="h-full w-1/3 cursor-w-resize outline-none" onClick={() => prev()} /> + <button type="button" aria-label={paused ? "play" : "pause"} data-present-zone="pause" className="h-full w-1/3 outline-none" onClick={() => setPaused((p) => !p)} /> + <button type="button" aria-label="next slide" data-present-zone="next" className="h-full w-1/3 cursor-e-resize outline-none" onClick={() => next()} /> + </div> + {paused && ( + <div data-present-paused="" className="pointer-events-none absolute right-3 top-3 z-50 rounded bg-black/60 px-2 py-0.5 font-mono text-[11px] text-white/80"> + paused · p + </div> + )} + </div> + )} + {n === 0 && <p className="p-6 text-[13px] text-white/70">This cut has nothing to present.</p>} + </div> + <Outline slides={slides} sections={sections} index={index} onGo={go} /> + <div className="flex h-7 shrink-0 items-center gap-3 px-3 font-mono text-[11.5px] text-white/70"> + <span data-present-progress="">{progress}</span> + <span className="truncate text-white/40">{slide ? sectionOf.get(slide.section)?.label ?? "" : ""}</span> + {slide && (slide.kind === "clip" || slide.kind === "post") && slide.qrUrl && ( + <a href={slide.qrUrl} target="_blank" rel="noreferrer" data-present-source="" className="shrink-0 text-white/60 hover:text-white" title={slide.qrUrl}> + source ↗ + </a> + )} + <button type="button" data-present-settings-open="" aria-expanded={drawer} className="ml-auto rounded px-1.5 py-0.5 text-white/60 hover:bg-white/10 hover:text-white" onClick={() => setDrawer((d) => !d)}> + Settings · s + </button> + </div> + {drawer && ( + <SettingsDrawer + payload={payload} + settings={settings} + slide={slide} + onChange={update} + onClose={() => setDrawer(false)} + back={back} + playHref={playHref} + /> + )} + </div> + ); +} + +/** THE JOIN (post-join.mjs): the post item before it in the deck, when this one opens on it. */ +function joinOf(slides: Slide[], i: number) { + const sl = slides[i]; + const before = slides[i - 1]; + if (!sl || sl.kind !== "post" || !before || before.kind !== "post" || !sl.plan.follow?.join) return null; + return { entry: before.post, plan: before.plan, clock: before.clock }; +} + +function SlideView({ + slide, slides, index, project, take, box, s, playing, settings, view, section, sections, blurRendered, onDone, +}: { + slide: Slide; + slides: Slide[]; + index: number; + project: string; + take: string | null; + box: Box; + s: number; + playing: boolean; + settings: PresentSettings; + view: CardView; + section: Section | null; + sections: Section[]; + blurRendered: boolean; + onDone: (id: string) => void; +}) { + if (slide.kind === "post") { + const t = Math.min(s, slide.plan.total); + return ( + <div data-present-post={slide.id} data-present-entry={slide.entry ?? ""} className="absolute inset-0"> + <PostItemPlayer + project={project} + take={take} + entry={slide.post} + plan={slide.plan} + box={box} + s={t} + playing={playing && s < slide.plan.total} + view={view} + voiceOn={settings.narration} + sound={settings.sound} + scene={slide.scene} + clock={slide.clock ?? null} + progress={slide.progress} + joinFrom={joinOf(slides, index)} + /> + {slide.combo && <ComboBadge project={project} entry={slide.post} plan={slide.plan} combo={slide.combo} box={box} s={t} playing={playing} />} + </div> + ); + } + if (slide.kind === "clip") return <ClipView slide={slide} project={project} take={take} playing={playing} sound censor={view.pictures && blurRendered} onDone={onDone} />; + if (slide.kind === "video") return <VideoView slide={slide} project={project} playing={playing} onDone={onDone} />; + return <TextView slide={slide} section={section} sections={sections} slides={slides} />; +} + +/** A CLIP: its spans played from the cached window (Play's media route), the deck's words under it. */ +function ClipView({ slide, project, take, playing, sound, censor, onDone }: { slide: ClipSlide; project: string; take: string | null; playing: boolean; sound: boolean; censor: boolean; onDone: (id: string) => void }) { + const video = useRef<HTMLVideoElement | null>(null); + const [at, setAt] = useState<number | null>(null); + const [done, setDone] = useState(false); + const media = slide.media; + const src = media + ? `/api/report/raw?${new URLSearchParams({ project, clip: slide.entry ?? slide.id, ...(take ? { take } : {}), file: media.name, ...(media.v ? { v: media.v } : {}) }).toString()}` + : null; + // Where it is in its source, followed every frame; past a span's end, on to the next, past the last, done. + useEffect(() => { + const v = video.current; + if (!v || !media) return; + let raf = 0; + const tick = () => { + raf = requestAnimationFrame(tick); + const now = media.from + v.currentTime; + setAt(now); + const k = slide.spans.findIndex((sp) => now < sp.to - 0.02); + if (k < 0) { + if (!v.paused) v.pause(); + setDone(true); + return; + } + if (now < slide.spans[k].from - 0.05) v.currentTime = Math.max(0, slide.spans[k].from - media.from); + }; + raf = requestAnimationFrame(tick); + return () => cancelAnimationFrame(raf); + }, [media, slide.spans]); + useEffect(() => { + if (done) onDone(slide.id); + }, [done, onDone, slide.id]); + useEffect(() => { + const v = video.current; + if (!v) return; + if (playing && !done) void v.play().catch(() => {}); + else if (!v.paused) v.pause(); + }, [playing, done]); + useEffect(() => { + if (!media && slide.spans.length) { + // Not fetched: nothing plays, and the slide reads for its length. + const t = setTimeout(() => setDone(true), slide.seconds * 1000); + return () => clearTimeout(t); + } + }, [media, slide.spans.length, slide.seconds]); + const blurNow = censor && slide.blur && at !== null && (slide.blur.from === null || at >= slide.blur.from) && (slide.blur.to === null || at < slide.blur.to); + return ( + <div data-present-clip={slide.id} data-present-clip-at={at === null ? "" : at.toFixed(2)} data-present-clip-done={done ? "1" : "0"} className="absolute inset-0 flex flex-col bg-black" style={{ containerType: "size" }}> + <div className="relative min-h-0 flex-1"> + {src ? ( + <video + ref={video} + src={src} + preload="auto" + playsInline + muted={!sound} + data-present-clip-video="" + data-present-clip-blurred={blurNow ? "1" : "0"} + onLoadedMetadata={(e) => { + if (media && slide.spans[0]) e.currentTarget.currentTime = Math.max(0, slide.spans[0].from - media.from); + }} + className="absolute inset-0 h-full w-full object-contain" + style={{ filter: blurNow && slide.blur ? `blur(${slide.blur.strength}cqh)` : undefined }} + /> + ) : ( + <div data-present-clip-missing="" className="absolute inset-0 flex items-center justify-center text-[2.4cqh] text-white/50"> + not fetched yet — its words below + </div> + )} + {blurNow && slide.blur && ( + <div className="pointer-events-none absolute inset-x-0 top-[5%] text-center text-[3.2cqh] font-semibold text-white drop-shadow">{slide.blur.caption}</div> + )} + </div> + <div data-present-clip-band="" className="flex shrink-0 items-center gap-[2cqh] bg-neutral-950/95 px-[3cqh] py-[1.6cqh]"> + <div className="min-w-0 flex-1"> + <div data-present-clip-title="" className="truncate text-[3.4cqh] font-semibold leading-tight">{slide.title}</div> + {slide.subtitle && <div data-present-clip-subtitle="" className="truncate text-[2.4cqh] text-white/65">{slide.subtitle}</div>} + </div> + </div> + </div> + ); +} + +/** A VIDEO entry (a file of the project): its span, full frame. */ +function VideoView({ slide, project, playing, onDone }: { slide: VideoSlide; project: string; playing: boolean; onDone: (id: string) => void }) { + const v = useRef<HTMLVideoElement | null>(null); + useEffect(() => { + const el = v.current; + if (!el) return; + if (playing) void el.play().catch(() => {}); + else el.pause(); + }, [playing]); + return ( + <video + ref={v} + data-present-video={slide.id} + src={`/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(slide.src)}`} + playsInline + preload="auto" + onLoadedMetadata={(e) => { + e.currentTarget.currentTime = slide.from; + }} + onTimeUpdate={(e) => { + if (e.currentTarget.currentTime >= slide.to - 0.03) { + e.currentTarget.pause(); + onDone(slide.id); + } + }} + onEnded={() => onDone(slide.id)} + className="absolute inset-0 h-full w-full object-contain" + /> + ); +} + +/** A SECTION or a DAY divider, a TEASER's lines, a card's heading: words on the stage. */ +function TextView({ slide, section, sections, slides }: { slide: TextSlide; section: Section | null; sections: Section[]; slides: Slide[] }) { + const count = slides.filter((x) => x.section === slide.section && x.kind !== "section" && x.kind !== "day").length; + const ordinal = sections.findIndex((x) => x.id === slide.section); + return ( + <div data-present-text={slide.kind} className="absolute inset-0 flex flex-col items-center justify-center gap-[2.4cqh] px-[8cqw] text-center" style={{ containerType: "size" }}> + {slide.kind === "section" && ( + <> + <div className="font-mono text-[2.4cqh] uppercase tracking-[0.2em] text-white/50"> + {slide.within ? `${slide.within} ›` : ordinal > 0 ? `Part ${ordinal}` : "Opening"} + </div> + <div data-present-section-label="" className="font-display text-[8cqh] font-semibold leading-tight" style={{ color: section?.color ?? undefined }}> + {slide.label} + </div> + <div className="font-mono text-[2.4cqh] text-white/50"> + {count} slide{count === 1 ? "" : "s"} + {section?.date ? ` · from ${section.date}` : ""} + </div> + </> + )} + {slide.kind === "day" && ( + <> + <div className="font-mono text-[2.4cqh] uppercase tracking-[0.2em] text-white/50">{weekday(slide.date)}</div> + <div data-present-section-label="" className="font-display text-[10cqh] font-semibold leading-tight">{slide.label}</div> + <div className="font-mono text-[2.4cqh] text-white/50"> + {count} post{count === 1 ? "" : "s"} + </div> + </> + )} + {slide.kind === "teaser" && ( + <div data-present-teaser="" className="flex flex-col gap-[1.6cqh] font-display text-[6.4cqh] font-semibold leading-tight"> + {(slide.lines ?? []).map((l, i) => ( + <div key={i}>{l}{i === (slide.lines ?? []).length - 1 && slide.tail ? slide.tail : ""}</div> + ))} + </div> + )} + {slide.kind === "card" && <div className="font-display text-[6cqh] font-semibold leading-tight">{slide.heading ?? slide.label}</div>} + </div> + ); +} + +const weekday = (day: string | null) => { + const d = day ? new Date(`${day}T12:00:00Z`) : null; + return d && !Number.isNaN(d.getTime()) ? d.toLocaleDateString("en-US", { weekday: "long", timeZone: "UTC" }) : ""; +}; + +/** THE OUTLINE: the sections (or days) as bands, a cell per slide, the one on stage lit; a click jumps. */ +function Outline({ slides, sections, index, onGo }: { slides: Slide[]; sections: Section[]; index: number; onGo: (i: number) => void }) { + const groups = useMemo(() => { + const out: Array<{ section: Section; cells: Array<{ slide: Slide; i: number }> }> = []; + const at = new Map<string, number>(); + slides.forEach((slide, i) => { + let g = at.get(slide.section); + if (g === undefined) { + g = out.length; + at.set(slide.section, g); + out.push({ section: sections.find((x) => x.id === slide.section) ?? { id: slide.section, kind: "cut", label: slide.section }, cells: [] }); + } + out[g].cells.push({ slide, i }); + }); + return out; + }, [slides, sections]); + const cur = slides[index]?.section ?? null; + return ( + <nav aria-label="outline" data-present-outline="" className="flex h-[38px] shrink-0 gap-[3px] px-3 pt-1"> + {groups.map((g) => ( + <div key={g.section.id} data-present-group={g.section.id} className="flex min-w-[14px] flex-col gap-[2px] overflow-hidden" style={{ flexGrow: g.cells.length, flexBasis: 0 }}> + <button + type="button" + title={g.section.label} + data-present-group-label={g.section.id} + className={`truncate text-left font-mono text-[10px] leading-[14px] ${g.section.id === cur ? "text-white" : "text-white/45"} hover:text-white`} + onClick={() => onGo(g.cells[0].i)} + > + {g.section.label} + </button> + <div className="flex h-[14px] gap-[1px]"> + {g.cells.map(({ slide, i }) => ( + <button + key={slide.id} + type="button" + title={`${i + 1}. ${slide.label}`} + aria-label={`slide ${i + 1}: ${slide.label}`} + aria-current={i === index ? "true" : undefined} + data-present-cell={slide.id} + data-present-cell-kind={slide.kind} + className={`min-w-0 flex-1 rounded-[1px] ${i === index ? "bg-amber-400" : slide.kind === "section" || slide.kind === "day" ? "bg-white/45 hover:bg-white/70" : "bg-white/18 hover:bg-white/50"}`} + onClick={() => onGo(i)} + /> + ))} + </div> + </div> + ))} + </nav> + ); +} + +function SettingsDrawer({ + payload, settings, slide, onChange, onClose, back, playHref, +}: { + payload: PresentPayload; + settings: PresentSettings; + slide: Slide | null; + onChange: (p: Partial<PresentSettings>) => void; + onClose: () => void; + back: string; + playHref: string; +}) { + const counts = slide?.kind === "post" ? slide.censor?.counts ?? null : null; + const row = "flex items-center gap-2 py-1 text-[12.5px]"; + return ( + <aside + data-present-settings="" + aria-label="settings" + className="absolute bottom-[66px] right-3 top-3 z-[60] flex w-[300px] max-w-[calc(100vw-24px)] flex-col gap-3 overflow-y-auto rounded-md border border-white/15 bg-neutral-900/95 p-3 text-neutral-100 shadow-xl" + > + <div className="flex items-center"> + <span className="text-[13px] font-semibold">Settings</span> + <button type="button" data-present-settings-close="" className="ml-auto rounded px-1.5 text-[12px] text-white/60 hover:bg-white/10" onClick={onClose}> + close · Esc + </button> + </div> + {payload.capabilities.canUncensor && ( + <fieldset className="flex flex-col"> + <legend className="mb-1 font-mono text-[10.5px] uppercase tracking-wider text-white/50">Censor</legend> + {(Object.keys(CENSOR_WORDS) as CensorKind[]).map((k) => ( + <label key={k} className={row}> + <input type="checkbox" data-present-toggle={k} checked={settings.censor[k]} onChange={(e) => onChange({ censor: { ...settings.censor, [k]: e.target.checked } })} /> + <span>{CENSOR_WORDS[k]}</span> + {counts && counts[k] > 0 && ( + <span data-present-censor-count={k} className="ml-auto font-mono text-[11px] text-amber-300/90" title="on this slide"> + {counts[k]} here + </span> + )} + </label> + ))} + </fieldset> + )} + <fieldset className="flex flex-col"> + <legend className="mb-1 font-mono text-[10.5px] uppercase tracking-wider text-white/50">Play</legend> + <label className={row}> + <input type="checkbox" data-present-toggle="narration" checked={settings.narration} onChange={(e) => onChange({ narration: e.target.checked })} /> + <span>Narration</span> + </label> + <label className={row}> + <input type="checkbox" data-present-toggle="sound" checked={settings.sound} onChange={(e) => onChange({ sound: e.target.checked })} /> + <span>Attachment sound</span> + </label> + <label className={row}> + <input type="checkbox" data-present-toggle="autoAdvance" checked={settings.autoAdvance} onChange={(e) => onChange({ autoAdvance: e.target.checked })} /> + <span>Auto-advance after the read</span> + </label> + <label className={`${row} pl-6`}> + <span className="text-white/70">linger</span> + <input + type="number" + min={0} + max={30} + step={0.5} + data-present-linger="" + value={settings.linger} + onChange={(e) => { + const v = Number(e.target.value); + if (Number.isFinite(v)) onChange({ linger: Math.min(30, Math.max(0, v)) }); + }} + className="w-16 rounded border border-white/20 bg-black/40 px-1 py-0.5 font-mono text-[12px]" + /> + <span className="text-white/50">s</span> + </label> + </fieldset> + <div className="flex flex-col gap-1 border-t border-white/10 pt-2 text-[12px]"> + <span className="text-white/60"> + {payload.title} + {payload.take ? ` · ${payload.take.defaulted ? "latest " : "take "}${payload.take.id}` : " · the manifest"} + </span> + <Link href={playHref} className="text-amber-300 hover:underline" data-present-play-link=""> + ▶ Play the cut + </Link> + <Link href={back} className="text-amber-300 hover:underline" data-present-back=""> + ‹ Back to {payload.project} + </Link> + </div> + <div className="border-t border-white/10 pt-2 font-mono text-[10.5px] leading-[16px] text-white/50"> + → PgDn Space next · ← PgUp ⇧Space back · Home End · p pause · s settings · click the left or right third · swipe + </div> + </aside> + ); +} diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx @@ -184,11 +184,24 @@ export function takeFileUrl(project: string, rel: string) { return `/api/report/file?project=${encodeURIComponent(project)}&path=${encodeURIComponent(rel)}`; } -type PageOpts = { project: string; id: string; box: Box; phase: "read" | "media"; take?: string | null; cardKey?: string | null; published?: boolean; uncensored?: boolean }; +/** + * WHAT THE CARD CENSORS, kind by kind (present mode's toggles, lib/report/present.mjs): the redacted names, the + * slurs masked, the private authors blurred, the censored pictures. None given: Play's own `published`/`uncensored`. + */ +export type CardView = { names: boolean; slurs: boolean; authors: boolean; pictures: boolean }; + +type PageOpts = { project: string; id: string; box: Box; phase: "read" | "media"; take?: string | null; cardKey?: string | null; published?: boolean; uncensored?: boolean; view?: CardView | null }; + +/** A card view as the post-item route's query: published for names or slurs, and what is turned off. */ +function viewQuery(v: CardView) { + const pub = v.names || v.slurs; + return `${pub ? `&published=1${v.slurs ? "" : "&uncensored=1"}${v.names ? "" : "&redact=0"}` : ""}${v.authors ? "" : "&authors=0"}${v.pictures ? "" : "&blur=0"}`; +} /** A post item's card page (the post-item route), as the player draws it and Play fetches it ahead (postPreload.ts). */ -export function postPageUrl({ project, id, box, phase, take = null, cardKey = null, published = false, uncensored = false }: PageOpts) { - return `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}${published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""}`; +export function postPageUrl({ project, id, box, phase, take = null, cardKey = null, published = false, uncensored = false, view = null }: PageOpts) { + const censor = view ? viewQuery(view) : published ? `&published=1${uncensored ? "&uncensored=1" : ""}` : ""; + return `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}${cardKey ? `&v=${encodeURIComponent(cardKey)}` : ""}${censor}`; } /** @@ -197,11 +210,12 @@ export function postPageUrl({ project, id, box, phase, take = null, cardKey = nu * every attachment its plan shows (and a video's words), the panel's, what the join opens on. The same URLs the * player builds, so what was fetched is what it draws. */ -export function postItemAssets({ project, take = null, entry, plan, box, published = false, uncensored = false, joinFrom = null }: { +export function postItemAssets({ project, take = null, entry, plan, box, published = false, uncensored = false, view = null, joinFrom = null }: { project: string; take?: string | null; entry: Record<string, unknown> & { id: string }; plan: PostPlan; box: Box; published?: boolean; uncensored?: boolean; + view?: CardView | null; joinFrom?: { entry: Record<string, unknown> & { id: string }; plan: PostPlan } | null; }): PostAssets { - const page = (id: string, phase: "read" | "media") => postPageUrl({ project, id, box, phase, take, published, uncensored }); + const page = (id: string, phase: "read" | "media") => postPageUrl({ project, id, box, phase, take, published, uncensored, view }); const docs = [page(entry.id, "read")]; if (postLayout(entry, box).mode === "stack") docs.push(page(entry.id, "media")); if (joinFrom && (plan.follow?.join?.seconds ?? 0) > 0) docs.push(page(joinFrom.entry.id, "read")); @@ -390,8 +404,12 @@ function PixelLayer({ source, crop, censor }: { source: React.RefObject<HTMLVide } function MediaEl({ - project, m, box, b, step, s, playing, inStep, mix = null, speed = 1, joinOp = 1, + project, m, box, b, step, s, playing, inStep, mix = null, speed = 1, joinOp = 1, sound = true, censored = true, }: { + /** Its own sound (present mode's setting): off, the element stays muted. */ + sound?: boolean; + /** Its censor drawn (post-censor.mjs); off, the picture as captured (present mode's toggle). */ + censored?: boolean; /** THE JOIN (post-join.mjs): its strength while it fades in over the attachment the item before ended on. */ joinOp?: number; project: string; @@ -447,7 +465,7 @@ function MediaEl({ const progress = inStep ? Math.min(1, Math.max(0, (s - step.at) / Math.max(0.1, step.seconds))) : 0; // CENSORED (post-censor.mjs): the whole frame, or its regions (its boxes, its band) -- blurred, black or // pixelated, as the render draws them. - const blur = blurOf(m) as Censor | null; + const blur = censored ? (blurOf(m) as Censor | null) : null; const blurCss = blur && blur.style === "blur" ? `blur(${blurCqw(blur.strength)}cqw)` : undefined; const wholeBlur = blur && blur.style === "blur" && !blur.boxes.length ? blurCss : undefined; const at = blur ? labelBoxOf(blur) : null; @@ -471,7 +489,7 @@ function MediaEl({ preload="auto" playsInline loop={step.loop} - muted={!(step.sound && run)} + muted={!(step.sound && run && sound)} style={{ ...inner, objectFit: "fill", filter: wholeBlur }} /> ) : ( @@ -570,7 +588,14 @@ type ClockPlan = { to: number; from: number | null; mode: "forward" | "rewind" | export default function PostItemPlayer({ project, take = null, entry, plan, box, s, playing, cardKey = null, speed = 1, published = false, uncensored = false, scene = null, clock = null, joinFrom = null, progress = null, onReady, + view = null, voiceOn = true, sound = true, }: { + /** PRESENT MODE's card view (CardView): what the card censors, kind by kind -- in place of `published`/`uncensored`. */ + view?: CardView | null; + /** The narration heard (present mode's setting): off, the item keeps its clock and its voice is silent. */ + voiceOn?: boolean; + /** The attachments' own sound (present mode's setting). */ + sound?: boolean; /** * THIS player's readiness, for Play's clock (engine.ts `gate`): "ready" once its card is drawn and its voice and * first attachment can play (or failed: nothing to wait for) -- fetched ahead (postPreload.ts), as soon as its @@ -637,8 +662,8 @@ export default function PostItemPlayer({ return () => ro.disconnect(); }, [box.width]); const layout = useMemo(() => postLayout(entry, box), [entry, box]); - const pageUrlOf = (id: string, phase: "read" | "media") => postPageUrl({ project, id, box, phase, take, published, uncensored }); - const pageUrl = (phase: "read" | "media") => postPageUrl({ project, id: entry.id, box, phase, take, cardKey, published, uncensored }); + const pageUrlOf = (id: string, phase: "read" | "media") => postPageUrl({ project, id, box, phase, take, published, uncensored, view }); + const pageUrl = (phase: "read" | "media") => postPageUrl({ project, id: entry.id, box, phase, take, cardKey, published, uncensored, view }); // Fetched ahead by Play (postPreload.ts): drawn from those bytes, decided as each is first drawn. const docOf = useFirstDoc(); const fileOf = useFirstSrc(); @@ -953,7 +978,7 @@ export default function PostItemPlayer({ if (!p.sound) continue; const v = doc.querySelector(`[data-post-pic="${p.scope}"] video`) as HTMLVideoElement | null; if (!v) continue; - const on = picSound === p && playing; + const on = picSound === p && playing && sound; if (on) { const start = typeof p.media[0]?.start === "number" ? (p.media[0].start as number) : 0; const want = start + (s - p.sound.t0); @@ -967,7 +992,7 @@ export default function PostItemPlayer({ v.loop = true; } } - }, [picSound, playing, s, speed, plan.pics]); + }, [picSound, playing, s, speed, plan.pics, sound]); const live = zooms.find((z) => s >= z.span.t0 && s < z.span.t3) ?? null; const zf = live ? zoomAt(live.span, zoomProgressAt(live.span, s)) : 1; const hl = live ? highlightAt(live.span, s) : 0; @@ -1178,7 +1203,7 @@ export default function PostItemPlayer({ > {mix && voiceTake && ( // eslint-disable-next-line jsx-a11y/media-has-caption - <audio ref={voice} src={fileOf(takeFileUrl(project, voiceTake.file))} preload="auto" data-post-narration-audio={voiceTake.file} data-post-narration-rate={String(speed * readRate)} /> + <audio ref={voice} src={fileOf(takeFileUrl(project, voiceTake.file))} preload="auto" muted={!voiceOn} data-post-narration-audio={voiceTake.file} data-post-narration-rate={String(speed * readRate)} /> )} {scale > 0 && ( <div className="absolute left-0 top-0" style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}> @@ -1233,7 +1258,7 @@ export default function PostItemPlayer({ {shown && layout.slot && (layout.mode === "side" || mediaPhase) && ( <> {stepBoxes(shown, layout.slot).map((b: { x: number; y: number; width: number; height: number }, j: number) => ( - <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} joinOp={Math.min(enterOp, jframe && !(enterAt > 0) && !(joinEnds.length === 1 && joinEnds[0].m.src === shown.items[j]?.src) ? Math.min(1, Math.max(0, (jframe.e - 0.35) / 0.65)) : 1)} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} mix={mix} speed={speed} /> + <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} joinOp={Math.min(enterOp, jframe && !(enterAt > 0) && !(joinEnds.length === 1 && joinEnds[0].m.src === shown.items[j]?.src) ? Math.min(1, Math.max(0, (jframe.e - 0.35) / 0.65)) : 1)} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} mix={voiceOn ? mix : null} speed={speed} sound={sound} censored={view ? view.pictures : true} /> ))} {cue && ( <div diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts @@ -417,6 +417,15 @@ export function playHref( ); } +/** + * PRESENT MODE (umtool/docs/knobs.md, "Present mode"): the cut -- or `take` -- as slides, navigated like a deck; + * `slide` opens on that slide (its id: a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>`). + * With no take, the latest take (the working cut), as Play. + */ +export function presentHref(project: string, q: { take?: string | null; bare?: boolean; slide?: string | null } = {}): string { + return withQuery(`/projects/${encodePath(project)}/present`, { take: q.take, cut: !q.take && q.bare ? "1" : null }) + (q.slide ? `#${q.slide}` : ""); +} + /** The narration script, card by card. */ export function narrationHref(project: string, q: NoteOpt = {}): string { return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note); diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -121,6 +121,21 @@ export function videoPlayEntry(e, D) { * @param {{ take?: string | null, bare?: boolean }} [opts] */ export async function playView(project, { take = null, bare = false } = {}) { + const r = await playViewWith(project, { take, bare }); + return r.view ?? { error: String(r.error) }; +} + +/** + * THE PLAY VIEW AND WHAT IT WAS MADE FROM (present mode, lib/report/present.mjs): `{ view, manifest, base }` -- + * the view playView answers, the cut it played (the take's patch applied, the default variant selected) and the + * project's own manifest -- or `{ error }`. `postFor`, given the cut that plays, answers how each post item is + * turned before it is planned (present.mjs: the build's own `censorEntry`, the channel markup's censored + * attachments; Play draws the item as written). + * + * @param {{ id: string, dir: string }} project + * @param {{ take?: string | null, bare?: boolean, postFor?: ((manifest: Record<string, any>) => Promise<(e: Record<string, any>) => Record<string, any>>) | null }} [opts] + */ +export async function playViewWith(project, { take = null, bare = false, postFor = null } = {}) { const base = await readManifest(project.dir); if (!base) return { error: "this project has no video.manifest.json" }; const working = await readWorkingCut(project.dir, { @@ -153,6 +168,7 @@ export async function playView(project, { take = null, bare = false } = {}) { } const selected = selectVariant(manifest, DEFAULT_VARIANT); const render = selected.render ?? {}; + const post = postFor ? await postFor(selected) : null; const timeline = (selected.timeline ?? []).filter((e) => e && typeof e.id === "string"); const D = transitionOf(render); const durs = timeline.map((e) => estimatedDuration(e, render, D)); @@ -166,7 +182,7 @@ export async function playView(project, { take = null, bare = false } = {}) { : { combos: {}, groups: [] }; const entries = await Promise.all( timeline.map(async (e, i) => { - if (e.type === "post") return postPlayEntry(e, render, planContext(timeline, i, render), mediaSceneOf(timeline, i, repeatGroups, render)); + if (e.type === "post") return postPlayEntry(post ? post(e) : e, render, planContext(timeline, i, render), mediaSceneOf(timeline, i, repeatGroups, render)); if (e.type === "video") return videoPlayEntry(e, D); if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null }; const win = pickWindow(await windowsFor(project, e, cache), null); @@ -253,7 +269,7 @@ export async function playView(project, { take = null, bare = false } = {}) { const groups = (Array.isArray(selected.groups) ? selected.groups : []) .filter((g) => g && typeof g.id === "string" && Array.isArray(g.ids)) .map((g) => ({ id: g.id, claim: typeof g.claim === "string" ? g.claim : "", ids: g.ids.filter((x) => typeof x === "string") })); - return { + const view = { project: project.id, title: text(manifest.title) || project.id, groups, @@ -275,4 +291,5 @@ export async function playView(project, { take = null, bare = false } = {}) { segments, entries, }; + return { view, manifest: selected, base }; } diff --git a/umtool/lib/report/present.mjs b/umtool/lib/report/present.mjs @@ -0,0 +1,415 @@ +// PRESENT MODE (operator, 8 Nov 2026: "present X posts in a new UI mode ... navigated like a PowerPoint +// presentation including settings like toggled censors"; umtool/docs/knobs.md, "Present mode"): a cut -- or a +// take -- as SLIDES, one at a time, navigated like a deck. This file is its PAYLOAD: what the viewer +// (`/projects/<p>/present`, components/projects/present/) and `umtool present --json` read. Deterministic, no AI, +// nothing fetched, cut or rendered. +// +// It is Play's view (playView.mjs playViewWith) cut into slides, so what a slide shows is what Play plays: +// +// - the cut is the LATEST take by default (the working cut, workingCut.mjs), a named take, or the manifest +// alone (`bare`) -- the take's patch applied exactly as Play and the build apply it; +// - a POST slide per post item, keyed by the POST's id (`<channel>/<native id>`, never the entry's index: a +// story's depths and a viewer's "seen" -- steps 2 and 3 -- key on it), carrying the item as Play draws it +// (its plan, progress bar, clock, media scene, combo badge), its excerpt's spans, its picked narration take, +// and its CENSOR DATA -- every redacted span, masked slur, blurred author and censored attachment the build +// would apply, by kind, so the viewer can show what it hides and toggle it; +// - a CLIP slide per clip the walk did not reject: the spans it plays (its cut minus its gaps) from the cached +// window Play plays, the deck's title, source line and QR link, its quote and its picture's blur; +// - a TEASER slide (its lines), and any other entry as a text slide (its heading); +// - SECTION divider slides where the cut's markers open a section -- or, when the cut is a chronological reel of +// posts with no markers, a DAY divider per calendar day in the posts' clock zone (post-clock.mjs). +// +// THE CAPABILITY. `canUncensor: true` (umtool, the operator) carries the posts as written beside the censor data; +// `canUncensor: false` (a public export, step 4) carries the CENSORED posts only -- every redacted span already +// marked, every masked slur masked, every blurred author's name and handle gone from the data -- and no reveal +// data at all. A public page can add censoring, never remove it. +import { cardAuthors, cardText, excerptRanges, excerptSpansOf, postDay } from "umtool-report-to-video/post-item"; +import { REDACT_MARK, redactEntry, redactionOn } from "umtool-report-to-video/post-redact"; +import { maskFor, slurMatches, slursOn } from "umtool-report-to-video/post-slurs"; +import { blurOf, censorEntry } from "umtool-report-to-video/post-censor"; +import { clockZoneOf } from "umtool-report-to-video/post-clock"; +import { pickedTake } from "umtool-report-to-video/post-narration"; +import { estimateSchedule } from "umtool-report-to-video/deck"; +import { gapsOf, keptSpans } from "umtool-report-to-video/gaps"; +import { clipBlurOf } from "umtool-report-to-video/clip-blur"; +import { playViewWith } from "./playView.mjs"; +import { projectRedaction } from "./postRedaction.mjs"; +import { sectionModel } from "./sectionEdit.mjs"; + +export const PRESENT_VERSION = 1; + +/** + * The viewer's settings when a viewer has set none (each viewer's own are kept in its browser). Everything the build + * censors is censored; the narration plays; a slide waits for the viewer. + */ +export const PRESENT_DEFAULTS = Object.freeze({ + censor: Object.freeze({ names: true, slurs: true, authors: true, pictures: true }), + narration: true, + autoAdvance: false, + /** Seconds a slide stays up after its read ends, before auto-advance moves on. */ + linger: 1.5, + /** The attachments' own sound (a video's). */ + sound: true, +}); + +/** The censor kinds the viewer toggles, in its words. */ +export const CENSOR_KINDS = Object.freeze({ + names: "Redacted names", + slurs: "Slurs masked", + authors: "Private authors blurred", + pictures: "Censored pictures", +}); + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const str = (v) => (typeof v === "string" ? v : ""); +const fin = (v) => typeof v === "number" && Number.isFinite(v); +const text = (v) => str(v).replace(/\s+/g, " ").trim(); +const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** `YYYY-MM-DD` of a moment in `zone` (an IANA name), or null. */ +export function dayIn(iso, zone) { + const d = new Date(str(iso)); + if (Number.isNaN(d.getTime())) return null; + try { + // en-CA writes 2026-11-03. + return new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(d); + } catch { + return postDay(iso) || null; + } +} + +/** "Nov 3" for `YYYY-MM-DD` (the progress line's date). */ +export function dayLabel(day) { + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(str(day)); + if (!m || Number(m[2]) < 1 || Number(m[2]) > 12) return null; + return `${MON[Number(m[2]) - 1]} ${Number(m[3])}`; +} + +/** A clip's dateKey (YYYYMMDD, playView) as `YYYY-MM-DD`. */ +const dayOfKey = (k) => (fin(k) ? `${Math.floor(k / 10000)}-${String(Math.floor((k % 10000) / 100)).padStart(2, "0")}-${String(k % 100).padStart(2, "0")}` : null); + +// --------------------------------------------------------------------------- +// THE CENSOR DATA (post-redact.mjs, post-slurs.mjs, post-item.mjs authorRedaction, post-censor.mjs). +// --------------------------------------------------------------------------- + +/** Every string a card draws of a post item, by its path: `[path, value, slurs?]` (slurs: the filter masks it). */ +function drawnFields(entry) { + const out = []; + const add = (path, v, slurs) => { + if (typeof v === "string" && v) out.push([path, v, slurs]); + }; + add("author", entry.author, true); + add("handle", entry.handle, false); + add("replyingTo", entry.replyingTo, false); + add("text", entry.text, true); + if (isObj(entry.repostedBy)) { + add("repostedBy.author", entry.repostedBy.author, true); + add("repostedBy.handle", entry.repostedBy.handle, false); + } + const ref = (base, r) => { + if (!isObj(r)) return; + add(`${base}.author`, r.author, true); + add(`${base}.handle`, r.handle, false); + add(`${base}.text`, r.text, true); + add(`${base}.paraphrase`, r.paraphrase, true); + add(`${base}.transcript`, r.transcript, true); + }; + if (Array.isArray(entry.parents)) entry.parents.forEach((p, i) => ref(`parents.${i}`, p)); + if (isObj(entry.quoted)) ref("quoted", entry.quoted); + if (Array.isArray(entry.links)) entry.links.forEach((p, i) => ref(`links.${i}`, p)); + return out; +} + +const valueAt = (obj, path) => path.split(".").reduce((o, k) => (o == null ? undefined : o[k]), obj); + +/** The runs of REDACT_MARK in `marked`: `[{ start, end }]` (redactText keeps every offset). */ +function markRuns(marked) { + const out = []; + const re = new RegExp(`${REDACT_MARK}[${REDACT_MARK}\\s]*${REDACT_MARK}|${REDACT_MARK}`, "g"); + for (const m of str(marked).matchAll(re)) out.push({ start: m.index, end: m.index + m[0].length }); + return out; +} + +/** + * WHAT THE BUILD HIDES ON A POST ITEM, as data: `{ marks, authors, media, counts }` -- each redacted span and each + * masked slur of every string the card draws (`{ kind: "redact"|"slur", field, start, end, mask? }`, offsets in the + * string as written), each author the card blurs (`{ kind: "author", where, handle, reason }`), each censored + * attachment (`{ kind: "blur", i, style, boxes, band, strength, label }`) -- or null when it hides nothing. + * + * @param {Record<string, any>} entry the item as the card draws it (its censored attachments laid on) + * @param {import("umtool-report-to-video/post-redact").Redaction | null} red + */ +export function censorData(entry, red) { + const marks = []; + // The redaction alone (no slurs): its marks keep every offset of the string as written. + const termsOnly = red ? { ...red, slurs: null } : null; + if (redactionOn(termsOnly)) { + const marked = redactEntry(entry, termsOnly); + for (const [field, v] of drawnFields(entry)) { + const after = valueAt(marked, field); + if (typeof after !== "string" || after === v) continue; + for (const r of markRuns(after)) marks.push({ kind: "redact", field, start: r.start, end: r.end }); + } + } + if (slursOn(red?.slurs)) { + for (const [field, v, slurs] of drawnFields(entry)) { + if (!slurs) continue; + for (const h of slurMatches(v, red.slurs)) marks.push({ kind: "slur", field, start: h.start, end: h.end, mask: maskFor(red.slurs, h, v.slice(h.start, h.end)) }); + } + } + // Every author the card blurs (post-item.mjs cardAuthors: the parents, the quoted post, a linked post, a reply's + // "replying to", and the item's own author when it names its subjects and is not one). + const authors = cardAuthors(entry).filter((a) => a.redact).map((a) => ({ kind: "author", where: a.where, handle: a.handle, reason: a.reason })); + const media = (Array.isArray(entry.media) ? entry.media : []) + .map((m, i) => { + const b = blurOf(m); + return b ? { kind: "blur", i, style: b.style, boxes: b.boxes, band: b.band, strength: b.strength, label: b.label } : null; + }) + .filter(Boolean); + const counts = { + names: marks.filter((m) => m.kind === "redact").length, + slurs: marks.filter((m) => m.kind === "slur").length, + authors: authors.length, + pictures: media.length, + }; + return counts.names + counts.slurs + counts.authors + counts.pictures ? { marks, authors, media, counts } : null; +} + +/** + * A post item AS PUBLISHED, for a payload that cannot uncensor: its strings marked as the card draws them (the + * redaction's bars, the slurs' masks -- redactEntry), every author the card blurs left nameless (no name, handle or + * link in the data: the card draws "xxxx" for them either way), and its narration only as the take that plays + * (no script). + * + * @param {Record<string, any>} entry + * @param {import("umtool-report-to-video/post-redact").Redaction | null} red + */ +export function publicPostEntry(entry, red) { + const out = /** @type {Record<string, any>} */ (structuredClone(redactEntry(entry, red))); + for (const a of cardAuthors(entry)) { + if (!a.redact) continue; + const blank = (r) => { + if (!isObj(r)) return; + r.author = null; + r.handle = null; + delete r.url; + delete r.avatar; + }; + if (a.where === "author") { + out.author = null; + out.handle = null; + delete out.url; + } else if (a.where === "replyingTo") out.replyingTo = "xxxxxxxx"; + else if (a.where === "quoted") blank(out.quoted); + else { + const m = /^(parents|links)\[(\d+)\]$/.exec(a.where); + if (m) blank(out[m[1]]?.[Number(m[2])]); + } + } + const take = pickedTake(entry); + if (isObj(out.narration)) out.narration = take ? { takes: [{ file: take.file, seconds: take.seconds, ...(fin(take.rate) ? { rate: take.rate } : {}) }], pick: 0 } : { off: true }; + delete out.redact; + delete out.notes; + return out; +} + +// --------------------------------------------------------------------------- +// THE SLIDES. +// --------------------------------------------------------------------------- + +/** A chronological reel of posts: every played entry a post item, their dates in order. */ +export function isPostReel(entries) { + const posts = entries.filter((e) => e.type === "post"); + if (posts.length < 2 || posts.length !== entries.length) return false; + let last = -Infinity; + for (const e of posts) { + const t = new Date(str(e.post?.date)).getTime(); + if (Number.isNaN(t)) return false; + if (t < last) return false; + last = t; + } + return true; +} + +/** A post item's slide id: its post's (`<channel>/<native id>`), else the entry's -- made unique in the deck. */ +function postSlideId(e) { + const p = str(e.post?.post).trim(); + return p || `item:${e.id}`; +} + +/** + * THE PAYLOAD, pure (the tests' door): Play's view of the cut, the cut itself, the project's redaction and the + * deck's estimated schedule -> the presentation. + * + * @param {{ view: Record<string, any>, manifest: Record<string, any>, red: any, canUncensor?: boolean }} o + */ +export function presentFrom({ view, manifest, red, canUncensor = true }) { + const render = manifest.render ?? {}; + const timeline = (Array.isArray(manifest.timeline) ? manifest.timeline : []).filter((e) => e && typeof e.id === "string"); + const zone = clockZoneOf(render); + // The deck's words per entry (its title, source line and QR) on the estimate's schedule. + /** @type {Map<string, { title: string, subtitle: string, qrUrl: string | null }>} */ + const deck = new Map(); + try { + for (const s of estimateSchedule(manifest)?.segments ?? []) deck.set(s.id, { title: str(s.title), subtitle: str(s.subtitle), qrUrl: s.qrUrl ?? null }); + } catch { + // A cut the deck cannot schedule has no deck words: the slides carry their own. + } + const byId = new Map(timeline.map((e) => [e.id, e])); + // What plays: Play's entries, the walk's rejected clips left out (Play skips them). + const played = (view.entries ?? []).filter((e) => !(e.type === "clip" && e.rejected)); + + // ---- the sections: the markers', or the days of a posts reel, or the cut as one ---- + const model = sectionModel(manifest); + const indexOf = new Map(timeline.map((e, i) => [e.id, i])); + const marked = model.placed.length > 0; + const days = !marked && isPostReel(played); + /** @type {Array<{ id: string, kind: "section"|"day"|"cut", label: string, date?: string, level?: number, color?: string | null }>} */ + const sections = []; + const sectionIdOf = (e) => { + if (days) return `day-${dayIn(e.post?.date, zone)}`; + if (!marked) return "cut"; + return `section-${model.entrySection[indexOf.get(e.id) ?? 0] ?? 0}`; + }; + + const slides = []; + const used = new Set(); + const unique = (id) => { + let out = id; + for (let n = 2; used.has(out); n += 1) out = `${id}~${n}`; + used.add(out); + return out; + }; + let lastSection = null; + for (const e of played) { + const sec = sectionIdOf(e); + if (sec !== lastSection) { + lastSection = sec; + if (days) { + const day = sec.slice(4); + sections.push({ id: sec, kind: "day", label: dayLabel(day) ?? day, date: day }); + slides.push({ id: unique(sec), kind: "day", section: sec, label: dayLabel(day) ?? day, date: day, dateLabel: dayLabel(day), entry: null }); + } else if (marked) { + const k = Number(sec.slice(8)); + const s = model.sections[k]; + const label = s?.label ?? (k === 0 ? text(manifest.title) || view.title : `Section ${k}`); + sections.push({ id: sec, kind: "section", label, ...(s?.level === 2 ? { level: 2 } : {}), color: s?.color ?? null }); + slides.push({ id: unique(sec), kind: "section", section: sec, label, date: null, dateLabel: null, entry: null, ...(s?.level === 2 ? { level: 2, within: s.within ?? null } : {}) }); + } else { + sections.push({ id: "cut", kind: "cut", label: view.title }); + } + } + const src = byId.get(e.id) ?? {}; + const words = deck.get(e.id) ?? null; + if (e.type === "post" && e.post && e.postPlan) { + const post = /** @type {Record<string, any>} */ (e.post); + const day = dayIn(post.date, zone); + const take = pickedTake(post); + const spans = excerptSpansOf(post); + const excerpt = spans ? excerptRanges(cardText(post), spans) : null; + slides.push({ + id: unique(postSlideId(e)), + kind: "post", + section: sec, + entry: e.id, + label: e.heading, + date: day, + dateLabel: dayLabel(day), + post: canUncensor ? post : publicPostEntry(post, red), + plan: e.postPlan, + progress: e.postProgress ?? null, + clock: e.postClock ?? null, + scene: e.postScene ?? null, + combo: e.postCombo ?? null, + narration: take ? { file: take.file, seconds: take.seconds, ...(fin(take.rate) ? { rate: take.rate } : {}), ...(Array.isArray(take.words) && take.words.length ? { words: take.words } : {}) } : null, + excerpt, + qrUrl: words?.qrUrl ?? null, + censor: canUncensor ? censorData(post, red) : null, + }); + continue; + } + if (e.type === "clip") { + const from = fin(e.cutStart) ? e.cutStart : e.start; + const to = fin(e.cutEnd) ? e.cutEnd : e.end; + const spans = keptSpans(from, to, gapsOf(e)); + const day = dayOfKey(e.dateKey); + slides.push({ + id: unique(e.id), + kind: "clip", + section: sec, + entry: e.id, + label: words?.title || e.heading, + date: day, + dateLabel: dayLabel(day), + video: e.video, + channel: e.channel ?? null, + media: e.media ?? null, + spans, + seconds: Math.round(spans.reduce((n, s) => n + (s.to - s.from), 0) * 1000) / 1000, + title: words?.title || text(e.heading), + subtitle: words?.subtitle ?? "", + quote: e.quote ?? null, + qrUrl: words?.qrUrl ?? null, + blur: clipBlurOf(src, render), + }); + continue; + } + if (e.type === "teaser") { + const lines = (Array.isArray(src.lines) ? src.lines : []).map((l) => (typeof l === "string" ? l : text(l?.text))).filter(Boolean); + slides.push({ + id: unique(e.id), kind: "teaser", section: sec, entry: e.id, label: lines[0] ?? e.heading, date: null, dateLabel: null, + lines, tail: typeof src.tail === "string" ? src.tail : null, seconds: fin(src.seconds) ? src.seconds : null, + }); + continue; + } + if (e.type === "video" && e.videoEntry) { + slides.push({ + id: unique(e.id), kind: "video", section: sec, entry: e.id, label: e.heading, date: null, dateLabel: null, + src: e.videoEntry.src, from: e.videoEntry.from, to: e.videoEntry.to, seconds: e.videoEntry.seconds, + }); + continue; + } + slides.push({ id: unique(e.id), kind: "card", section: sec, entry: e.id, label: e.heading, date: null, dateLabel: null, heading: e.heading, type: e.type }); + } + // A section's date: its first dated slide's (the outline's hint). + for (const s of sections) { + if (s.kind !== "section") continue; + const d = slides.find((x) => x.section === s.id && x.date)?.date ?? null; + if (d) s.date = d; + } + return { + version: PRESENT_VERSION, + project: view.project, + take: view.take ? { id: view.take.id, label: view.take.label, defaulted: !!view.take.defaulted } : null, + title: view.title, + capabilities: { canUncensor: !!canUncensor }, + settings: PRESENT_DEFAULTS, + box: { width: fin(render.width) ? render.width : 1920, height: fin(render.height) ? render.height : 1080 }, + zone, + blurRendered: view.blurRendered !== false, + sections, + slides, + }; +} + +/** + * THE PAYLOAD of a project (or a take): Play's view, read with the build's own censored attachments (the channel + * markup's, post-censor.mjs censorEntry), and the project's redaction. + * + * @param {{ id: string, dir: string }} project + * @param {{ take?: string | null, bare?: boolean, canUncensor?: boolean }} [opts] + */ +export async function presentPayload(project, { take = null, bare = false, canUncensor = true } = {}) { + // The redaction is the cut's own (its terms, its channels' markup, its slur filter: a take's patch can switch it), + // read off the cut that plays; its censored attachments laid on each post item before it is planned. + let red = null; + const r = await playViewWith(project, { + take, bare, + postFor: async (manifest) => { + red = await projectRedaction(project.dir, manifest, { say: false }); + return (e) => censorEntry(e, red); + }, + }); + if ("error" in r) return r; + return presentFrom({ view: r.view, manifest: r.manifest, red, canUncensor }); +} diff --git a/umtool/lib/report/presentCli.mjs b/umtool/lib/report/presentCli.mjs @@ -0,0 +1,97 @@ +// `umtool present <project> [--take <id> | --cut] [--json] [--public] [--open] [--url <origin>]`: PRESENT MODE from a +// terminal (umtool/docs/knobs.md, "Present mode") -- the viewer's address (`/projects/<p>/present`), and with +// --json the payload it shows (lib/report/present.mjs presentPayload), so an agent can drive it: every slide's id +// (a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>`) opens it as `…/present#<id>`. +// +// Plain ESM: the CLI runs under bare node. +import { spawn } from "node:child_process"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { umtoolBase } from "./buildRun.mjs"; +import { presentPayload } from "./present.mjs"; + +export const PRESENT_USAGE = [ + "usage: umtool present <project> [--take <id> | --cut] [--json] [--public] [--open] [--url <origin>]", + "", + "PRESENT MODE: the cut as slides, one at a time, navigated like a deck (/projects/<p>/present). Prints the", + "viewer's address and the slides (each one's id, kind, section and date); --json the whole payload (its url", + "beside it): every slide in cut order -- a post item's card as Play draws it, its excerpt, its narration take", + "and its censor data by kind; a clip's spans from its cached window and the deck's words; section and day", + "dividers. With no --take the latest take (the working cut), as Play; --cut the manifest alone. --public: the", + "payload a public page would carry (the posts censored, no reveal data). --open opens the address (xdg-open).", + "A slide opens as <url>#<slide id>. UMTOOL_URL (else http://localhost:3050) or --url is the app's origin.", +].join("\n"); + +class CliError extends Error {} + +/** The viewer's path for a project (lib/hrefs.ts presentHref, in plain ESM). */ +export function presentPath(projectId, { take = null, bare = false, slide = null } = {}) { + const enc = String(projectId).split("/").filter(Boolean).map(encodeURIComponent).join("/"); + const q = new URLSearchParams(); + if (take) q.set("take", take); + else if (bare) q.set("cut", "1"); + const qs = q.toString(); + return `/projects/${enc}/present${qs ? `?${qs}` : ""}${slide ? `#${slide}` : ""}`; +} + +/** + * @param {string[]} args the words after `present` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, env?: Record<string, string | undefined>, open?: (url: string) => void }} [opts] + * @returns {Promise<number>} + */ +export async function presentCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), env = process.env, open = openUrl } = {}) { + try { + const words = []; + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--take" || a === "--url") { + if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); + flags.set(a, args[++i]); + } else if (a.startsWith("--")) flags.set(a, true); + else words.push(a); + } + if (!words[0] || flags.has("--help")) { + (flags.has("--help") ? out : err)(PRESENT_USAGE); + return flags.has("--help") ? 0 : 2; + } + for (const f of flags.keys()) if (!["--take", "--cut", "--json", "--public", "--open", "--url"].includes(f)) throw new CliError(`unknown flag ${f}\n\n${PRESENT_USAGE}`); + if (flags.has("--take") && flags.has("--cut")) throw new CliError("--take and --cut: one or the other"); + const r = await resolveProject(words[0], root); + if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${words[0]}"`); + const project = r.project; + const take = flags.has("--take") ? String(flags.get("--take")) : null; + const bare = flags.has("--cut"); + const payload = await presentPayload(project, { take, bare, canUncensor: !flags.has("--public") }); + if ("error" in payload) throw new CliError(String(payload.error)); + const url = `${umtoolBase(flags.get("--url"), env)}${presentPath(project.id, { take, bare })}`; + if (flags.has("--json")) out(JSON.stringify({ url, ...payload }, null, 2)); + else { + const what = payload.take ? `${payload.take.defaulted ? "latest take" : "take"} ${payload.take.id}` : "the manifest"; + const posts = payload.slides.filter((s) => s.kind === "post").length; + out(`${url}`); + out(`${project.id} · ${what} · ${payload.slides.length} slide(s), ${posts} post(s) · ${payload.sections.length} section(s)`); + for (const s of payload.slides) { + const censor = s.kind === "post" && s.censor ? ` [${Object.entries(s.censor.counts).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ")}]` : ""; + out(` ${s.kind.padEnd(7)} ${s.id}${s.dateLabel ? ` ${s.dateLabel}` : ""} ${String(s.label ?? "").slice(0, 70)}${censor}`); + } + } + if (flags.has("--open")) open(url); + return 0; + } catch (e) { + if (e instanceof CliError) { + err(`umtool present: ${e.message}`); + return 1; + } + throw e; + } +} + +function openUrl(url) { + const cmd = process.platform === "darwin" ? "open" : "xdg-open"; + try { + spawn(cmd, [url], { detached: true, stdio: "ignore" }).on("error", () => {}).unref(); + } catch { + // Nothing to open it with: the address is printed above. + } +}