"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"; import IntroCardPlayer, { type IntroPage } from "../review/IntroCardPlayer"; import CensorOverlay, { type CensorRegion } from "../review/CensorOverlay"; import { aModalIsOpen } from "@/components/ui/modalOpen"; // --------------------------------------------------------------------------- // 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); `#` 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; the INTRO plays the build's own page and its sound // (IntroCardPlayer, as Play does); 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 } | 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 & { id: string }; plan: PostPlan; progress: ProgressPlan | null; clock: Parameters[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; /** Its hidden regions (clip-censor.mjs): overlaid on the raw window on the operator's page -- no toggle lifts them. */ hidden?: CensorRegion[]; /** * A PUBLIC payload of a clip with hidden regions (no `media`: the raw window is never named): its built segment, * which hides them in the file (`segment` its version), or null -- the slide says the clip is not shown. */ censored?: { segment: number; seconds: number | null; take?: string } | 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 }; type IntroSlide = SlideBase & { kind: "intro"; style: string; seconds: number | null; title?: string; lines?: string[] }; export type Slide = PostSlide | ClipSlide | TextSlide | VideoSlide | IntroSlide; type CensorKind = "names" | "slurs" | "authors" | "pictures"; export type PresentSettings = { censor: Record; 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 = { 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, intro: 4.18 } 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; 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(null); const [size, setSize] = useState(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, onExit, }: { payload: PresentPayload; back: string; playHref: string; /** The workspace's present mode (umtool redesign L7b): Esc (the settings closed) and ‹ Edit go back to Edit. */ onExit?: () => void; }) { 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 drawerRef = useRef(drawer); drawerRef.current = drawer; const exitRef = useRef(onExit); exitRef.current = onExit; const [settings, setSettings] = useState(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) => { setSettings((s) => { const next = { ...s, ...patch, censor: { ...s.censor, ...(patch.censor ?? {}) } }; writeSettings(next); return next; }); }, []); // ---- the address: #, 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) => { // A modal is up (the ⌘K palette): its keys -- Esc closes IT, never present mode under it; no slide moves. if (aModalIsOpen()) return; const t = e.target as HTMLElement | null; // Typing in a field (the linger) is not a move; a checkbox is not typing. const typing = !!t && ((t.tagName === "INPUT" && !["checkbox", "radio", "button"].includes((t as HTMLInputElement).type)) || t.tagName === "TEXTAREA" || t.isContentEditable); if (e.key === "Escape") { if (t && t !== document.body) t.blur(); // The settings open: Esc closes them. Closed: back to the workspace's Edit, when presenting in it. if (drawerRef.current || !exitRef.current) setDrawer(false); else exitRef.current(); return; } if (typing) return; // In the settings, Space and Enter work the control that has the focus. if ((e.key === " " || e.key === "Enter") && t?.closest?.("[data-present-settings]")) 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 === "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; if (slide.kind === "intro" && slide.seconds) return slide.seconds; 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 => !!x); const ahead = [index + 1, index + 2, index + 3].map(assets).filter((x): x is NonNullable => !!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 (

{payload.title} — present

{/* THE STAGE: one slide, the frame's aspect, as large as the window allows. */}
{size && slide && (
{/* The click zones: the left third back, the right third on, the middle pauses. */}
{paused && (
paused · p
)}
)} {n === 0 &&

This cut has nothing to present.

}
{progress} {slide ? sectionOf.get(slide.section)?.label ?? "" : ""} {slide && (slide.kind === "clip" || slide.kind === "post") && slide.qrUrl && ( source ↗ )} {onExit && ( )}
{drawer && ( setDrawer(false)} back={back} playHref={playHref} /> )}
); } /** 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 (
{slide.combo && }
); } if (slide.kind === "clip") return ; if (slide.kind === "video") return ; if (slide.kind === "intro") return ; return ; } /** 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(null); const [at, setAt] = useState(null); const [done, setDone] = useState(false); const [aspect, setAspect] = useState(null); const media = slide.media; // A public page's clip with hidden regions plays its BUILT segment (the regions burned in), whole, or nothing. const built = !media && slide.censored ? slide.censored : null; const withheld = !media && slide.censored === null; 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()}` : built ? `/api/report/segment?${new URLSearchParams({ project, clip: slide.entry ?? slide.id, ...(built.take ? { take: built.take } : {}), public: "1", v: String(built.segment) }).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 && !built && 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, built, 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 (
{src ? (
{slide.title}
{slide.subtitle &&
{slide.subtitle}
}
); } /** 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(null); useEffect(() => { const el = v.current; if (!el) return; if (playing) void el.play().catch(() => {}); else el.pause(); }, [playing]); return (