"use client"; import { useEffect, useMemo, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import { isNarrated, pickedTake } from "umtool-report-to-video/post-narration"; import { WORD_ZOOM_DEFAULTS, WORD_ZOOM_EASES, WORD_ZOOM_LIMITS, cardTokens, normWord, readingEstimate, resolveWordZoom, targetTextOf, wordZoomTimes, zoomSpan, } from "umtool-report-to-video/word-zoom"; import { CAPTION_DEFAULTS, CAPTION_LIMITS, CAPTION_PLACES, captionTimes, resolveCaption } from "umtool-report-to-video/post-caption"; import { resolveSlam, slamLandings, slamTimes } from "umtool-report-to-video/post-slam"; // --------------------------------------------------------------------------- // A POST's WORD ZOOMS ON THE BENCH (report-to-video/word-zoom.mjs; knobs.md, "A // word zoom"): the card's words, each clickable (shift-click: a phrase) -- // Zoom here adds the zoom on them (its match and occurrence filled) -- then each // zoom's knobs: scale, lead, hold, ease, highlight, and its moment: from the // take's word timings (Get word timings: the EDITOR's transcription, a job) or // `at`, nudged. A CAPTION (post-caption.mjs) is added on the same words (Caption // here, its text typed), then its text, place, lead, hold and moment set. // Every change is one write (POST /api/report/post-item, op "fx"). // --------------------------------------------------------------------------- type Entry = Record & { id: string; fx?: Array> }; type Sel = { target: string; from: number; to: number } | null; const r2 = (v: number) => Math.round(v * 100) / 100; /** The word as the card shows it, its edge punctuation off (what `match` is written as). */ const bare = (tok: string) => tok.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "") || tok; export default function PostZoomPanel({ project, entry, token, render, s, setS, onEntry, }: { project: string; entry: Entry; token: string | null; render: Record; s: number; setS: (s: number) => void; onEntry: (e: Entry, token: string | null) => void; }) { const btn = cn(buttonVariants({ variant: "outline", size: "sm" })); const [error, setError] = useState(null); const [status, setStatus] = useState(null); const [sel, setSel] = useState(null); const targets = useMemo(() => { const out: Array<{ target: string; label: string; text: string }> = [{ target: "post", label: "the post", text: String(targetTextOf(entry, "post") ?? "") }]; const parents = Array.isArray(entry.parents) ? entry.parents : []; parents.slice(0, 2).forEach((_, i) => { const t = targetTextOf(entry, `parent:${i}`); if (t) out.push({ target: `parent:${i}`, label: i === 0 ? "the post it answers" : `the post ${i + 1} up`, text: t }); }); const q = targetTextOf(entry, "quoted"); if (q) out.push({ target: "quoted", label: "the post it quotes", text: q }); return out; }, [entry]); const [target, setTarget] = useState("post"); const text = targets.find((t) => t.target === target)?.text ?? ""; const tokens = useMemo(() => cardTokens(text).filter((t) => t.tok !== undefined) as Array<{ tok: string; i: number }>, [text]); const list = Array.isArray(entry.fx) ? entry.fx : []; const times = useMemo(() => wordZoomTimes(entry, render), [entry, render]); const ctimes = useMemo(() => captionTimes(entry, render), [entry, render]); const [capText, setCapText] = useState(""); const [slamText, setSlamText] = useState(""); const stimes = useMemo(() => slamTimes(entry, render), [entry, render]); const narrated = isNarrated(entry); const take = pickedTake(entry) as (Record & { words?: unknown[] }) | null; const send = async (fx: Record) => { setError(null); const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "fx", id: entry.id, fx, token }) }); const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] }; if (!res.ok || !j.entry) { setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`); return null; } onEntry(j.entry, j.token ?? null); return j.entry; }; const zoomHere = async (kind: "word-zoom" | "caption" | "slam" = "word-zoom") => { if (!sel) return; if (kind === "caption" && !capText.trim()) return setError("a caption needs its text"); if (kind === "slam" && !slamText.trim()) return setError("a slam needs its glyphs"); const words = tokens.slice(sel.from, sel.to + 1).map((t) => t.tok); const match = words.length === 1 ? bare(words[0]) : [bare(words[0]), ...words.slice(1, -1), bare(words[words.length - 1])].join(" "); // Its occurrence: how many times the same run of words came before it, plus one. const want = words.map(normWord); let occurrence = 1; for (let i = 0; i < sel.from; i += 1) if (want.every((w, k) => normWord(tokens[i + k]?.tok ?? "") === w)) occurrence += 1; const add: Record = { kind, match, ...(kind === "caption" ? { text: capText.trim() } : kind === "slam" ? { text: slamText.trim() } : {}), ...(occurrence > 1 ? { occurrence } : {}), ...(sel.target !== "post" ? { target: sel.target } : {}) }; // An un-narrated post has no read to time it by: the reading estimate, to nudge. // (A caption is timed by the reading estimate itself when it has no at.) if (!narrated && kind === "word-zoom") add.at = readingEstimate(sel.from); const e = await send({ add }); if (e) { setStatus(`${kind === "caption" ? "caption" : kind === "slam" ? "slam" : "zoom"} added on "${match}"`); setSel(null); if (kind === "caption") setCapText(""); if (kind === "slam") setSlamText(""); } }; // Get word timings: the editor's transcription of the picked take, a job (or one per part), followed. const [wordsJob, setWordsJob] = useState<{ jobs: string[]; state: string; error?: string } | null>(null); const getWords = async () => { setError(null); const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "take-words", id: entry.id }) }); const j = (await res.json().catch(() => ({}))) as { jobs?: string[]; error?: string }; if (!res.ok || !j.jobs?.length) { setWordsJob({ jobs: [], state: "failed", error: j.error ?? `HTTP ${res.status}` }); return; } setWordsJob({ jobs: j.jobs, state: "transcribing" }); }; useEffect(() => { if (wordsJob?.state !== "transcribing") return; const t = setTimeout(async () => { const res = await fetch(`/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&takeWords=${encodeURIComponent(wordsJob.jobs.join(","))}`); const j = (await res.json().catch(() => ({}))) as { state?: string; entry?: Entry; token?: string; error?: string; heard?: number; of?: number }; if (j.state === "done" && j.entry) { onEntry(j.entry, j.token ?? null); setStatus(`word timings: ${j.heard} of ${j.of} words heard`); setWordsJob(null); } else if (j.state !== "transcribing") setWordsJob({ ...wordsJob, state: "failed", error: j.error ?? "the transcription failed" }); else setWordsJob({ ...wordsJob }); }, 1500); return () => clearTimeout(t); }, [wordsJob, project, entry.id, onEntry]); const knob = (i: number, key: "scale" | "lead" | "hold", step: number) => { const fx = resolveWordZoom(list[i]); const [lo, hi] = WORD_ZOOM_LIMITS[key]; return ( ); }; return (

word zoom · caption

{targets.length > 1 && ( )} {narrated && ( {take?.words?.length ? `the take is timed (${take.words.length} words)` : "the take has no word timings"} {wordsJob?.state === "transcribing" ? ( transcribing on the editor… ) : ( )} )}
{wordsJob?.state === "failed" &&

{wordsJob.error}

}

Click a word (shift-click another: a phrase), then Zoom here.

{tokens.map((t) => { const on = sel && sel.target === target && t.i >= sel.from && t.i <= sel.to; return ( ); })}
setCapText(e.target.value)} placeholder="caption text" className="min-w-0 flex-1 rounded border border-seam bg-ground px-1 py-0.5" aria-label="caption text" data-post-caption-text="" /> setSlamText(e.target.value)} placeholder="slam glyphs (不動心)" className="w-28 rounded border border-seam bg-ground px-1 py-0.5" aria-label="slam glyphs" data-post-slam-text="" /> {sel && ( “{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}” )}
{list.map((fx0, i) => { // A SLAM (post-slam.mjs): its glyphs, its word, its hits; go to it, remove it (its knobs: umtool posts fx … set). if (fx0?.kind === "slam") { const sl = resolveSlam(fx0); const t = stimes[i] as { t?: number; end?: number | null; source?: string; error?: string }; const hits = typeof t?.t === "number" ? slamLandings(fx0, { t: t.t, end: t.end ?? null }) : []; const up = hits.length > 0 && s >= hits[0] - 0.2 && s < hits[hits.length - 1] + sl.hold + 0.35; return (
#{i + 1} slam {sl.text} {typeof fx0.match === "string" ? `on “${sl.match}” · ` : ""} {typeof fx0.bar === "string" ? `on a bar “${fx0.bar}” · ` : ""} {t?.error ? `no time: ${t.error}` : `hits at ${hits.map((x) => x.toFixed(2)).join(", ")} s (${t.source === "words" ? "over the spoken word" : t.source === "at" ? "its at" : "the estimate"})`}
); } // Its clock (post-clock.mjs): a row of its own, its rewind knob. if (fx0?.kind === "clock") { return (
#{i + 1} clock {fx0.on === false ? "off on this item" : "the post's own time, run from the item before"} {fx0.on !== false && ( )}
); } if (fx0?.kind === "caption") { const c = resolveCaption(fx0); const t = ctimes[i] as { t?: number; source?: string; error?: string }; const at = typeof t?.t === "number" ? t.t : null; const up = at !== null && s >= at - c.lead && s < at + c.hold + 0.35; const capKnob = (key: "lead" | "hold") => ( ); return (
#{i + 1} caption on “{c.match}” {at !== null ? ( at {at.toFixed(2)} s {t.source === "at" ? "(set by hand)" : t.source === "words" ? "(the take's words)" : "(the reading estimate)"} ) : ( {t?.error} )}
ev.target.value.trim() && ev.target.value !== c.text && void send({ set: i, patch: { text: ev.target.value } })} className="w-full rounded border border-seam bg-ground px-1 py-0.5" aria-label={`caption ${i + 1} text`} data-post-caption-knob="text" />
at {typeof fx0.at === "number" && ( )} {capKnob("lead")} {capKnob("hold")}
); } const fx = resolveWordZoom(fx0); const t = times[i] as { t?: number; source?: string; error?: string }; const at = typeof t?.t === "number" ? t.t : null; const span = at !== null ? zoomSpan(fx0, at) : null; const up = !!span && s >= span.t0 && s < span.t3; return (
#{i + 1} “{fx.match}” {fx.target !== "post" ? `${fx.target} · ` : ""} {fx.occurrence > 1 ? `its ${fx.occurrence}th time · ` : ""} {at !== null ? ( at {at.toFixed(2)} s {t.source === "words" ? "(the take's words)" : "(set by hand)"} ) : ( {t?.error} )}
at {typeof fx0.at === "number" && narrated && ( )}
{knob(i, "scale", 0.1)} {knob(i, "lead", 0.1)} {knob(i, "hold", 0.1)} {fx.highlight !== false && ( e.target.value !== String(fx.highlight) && void send({ set: i, patch: { highlight: e.target.value === WORD_ZOOM_DEFAULTS.highlight ? null : e.target.value } })} data-post-zoom-knob="color" /> )}
); })} {status &&

{status}

} {error && (

{error}

)}
); }