commit e0b3cab1e620ba6ad82d0c01bc86f5169c78a456
parent 261f017798da793268934f7b70875253037d4873
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 3 Nov 2026 13:57:15 -0500
umtool: the word zoom in Play and on the post bench -- Play zooms the card live on the render's curve; the bench's words are clickable (Zoom here), each zoom's knobs, Get word timings, a nudge of at; the plan strip and the read lane mark it
PostItemPlayer measures the zoom's word in the card page (its data-w spans) and
transforms the card's children about the same window the render crops, the
highlight fading under the word (data-post-zoom on the player). PostZoomPanel:
the card's words (shift-click a phrase), Zoom here (match and occurrence filled;
an un-narrated post gets the reading estimate as at), scale / lead / hold /
ease / highlight, at -0.1 / +0.1 / at playhead / from the words, and Get word
timings -- the editor's transcribe op on the picked take as a job (POST
/api/report/post-item op "take-words", followed by GET ?takeWords=), aligned and
kept on the take. op "fx" is updatePostFx.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
5 files changed, 507 insertions(+), 3 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts
@@ -4,7 +4,10 @@ import { postCardHtml } from "umtool-report-to-video/post-item";
import { avatarUrls } from "umtool-report-to-video/post-avatars";
import { jobState, startJob } from "@/lib/research/case-editor";
import { withEditNotes } from "@/lib/report/guard";
-import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs";
+import { StaleToken, StructureRefused, manifestToken, updatePostFx, updatePostItem, updatePostNarration } from "@/lib/report/manifest.mjs";
+import { pickedTake } from "umtool-report-to-video/post-narration";
+import { scriptWordTimes } from "umtool-report-to-video/word-zoom";
+import { recognizedOf, takeWordSources, wordsFileOf } from "@/lib/report/postFxCli.mjs";
import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs";
import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
import { refuseCaller } from "@/lib/report/caller";
@@ -25,6 +28,12 @@ export const dynamic = "force-dynamic";
// POST {project, op: "set", id, patch, token} updatePostItem (hold, layout, redact, media.<i>.…)
// POST {project, op: "transcribe", id, media} the editor's transcribe op on the attachment
// (a local file, a job), its words beside it
+// POST {project, op: "fx", id, fx, token} updatePostFx: a word zoom added ({add}), changed
+// ({set, patch}), removed ({remove}) (word-zoom.mjs)
+// POST {project, op: "take-words", id, worker?} the picked take's WORD TIMINGS: the editor's transcribe
+// op on it (or each of its parts), jobs -> {jobs}
+// GET ?project&id&takeWords=<job>,<job>… those jobs' state; once all are done, the words heard
+// aligned to the script and kept on the take
const noStore = { "cache-control": "no-store" };
@@ -91,6 +100,34 @@ export async function GET(request: Request) {
}
if (!found.item) return new Response(`no post item ${id}`, { status: 404 });
+ const tw = q.get("takeWords");
+ if (tw) {
+ const jobs = tw.split(",").filter(Boolean);
+ const take = pickedTake(found.item) as (Record<string, unknown> & { file: string; index: number; script?: string; parts?: unknown[] }) | null;
+ if (!take) return Response.json({ state: "failed", error: `${id} has no take` }, { status: 404 });
+ try {
+ const states = await Promise.all(jobs.map((j) => jobState(j)));
+ if (states.some((st) => !st.done)) return Response.json({ state: "transcribing", done: states.filter((st) => st.done).length, of: jobs.length }, { headers: noStore });
+ const bad = states.find((st) => st.status !== "done");
+ if (bad) return Response.json({ state: "failed", status: bad.status, error: bad.tail.slice(-3).join(" / ") }, { headers: noStore });
+ const sources = await takeWordSources(r.project.dir, take);
+ const heard: Array<{ w: string; start: number; end: number }> = [];
+ for (const src of sources) {
+ const doc = JSON.parse(await readFile(path.join(r.project.dir, ...wordsFileOf(src.file).split("/")), "utf8"));
+ heard.push(...recognizedOf(doc, src.offset));
+ }
+ if (!heard.length) return Response.json({ state: "failed", error: "the editor's transcription came back with no word timings (a parakeet worker keeps them)" }, { headers: noStore });
+ const n = (found.item as { narration?: { script?: string } }).narration;
+ const script = typeof take.script === "string" && take.script.trim() ? take.script : String(n?.script ?? "");
+ const t = scriptWordTimes(script, heard);
+ const { result } = await withEditNotes(r.project, async () =>
+ updatePostNarration(r.project.dir, id, { takeWords: { take: take.index, words: t.words } }, { token: await manifestToken(r.project.dir) }));
+ return Response.json({ state: "done", heard: t.heard, of: t.of, entry: result.entry, token: result.token }, { headers: noStore });
+ } catch (e) {
+ return Response.json({ state: "failed", error: e instanceof Error ? e.message : String(e) }, { status: 502 });
+ }
+ }
+
const job = q.get("job");
if (job) {
const i = Number(q.get("media"));
@@ -154,6 +191,36 @@ export async function POST(request: Request) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
}
+ if (body.op === "fx") {
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, () =>
+ updatePostFx(r.project.dir, id, (body.fx ?? {}) as Record<string, unknown>, { token: body.token === undefined || body.token === null ? null : String(body.token) }),
+ );
+ return Response.json({ ok: true, entry: result.entry, index: result.index, token: result.token, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+ }
+ if (body.op === "take-words") {
+ const found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, null);
+ const take = found.item ? (pickedTake(found.item) as (Record<string, unknown> & { file: string }) | null) : null;
+ if (!take) return Response.json({ error: `${id} has no take to time` }, { status: 404 });
+ try {
+ const sources = await takeWordSources(r.project.dir, take);
+ const worker = typeof body.worker === "string" && body.worker ? { workerId: body.worker } : {};
+ // The editor's transcription door, as for an attachment: a local file, a job -- never ASR here.
+ const jobs = [];
+ for (const src of sources) {
+ jobs.push(await startJob("/api/ops/transcribe", { path: path.join(r.project.dir, ...src.file.split("/")), words: true, out: path.join(r.project.dir, ...wordsFileOf(src.file).split("/")), ...worker }));
+ }
+ return Response.json({ ok: true, jobs }, { headers: noStore });
+ } catch (e) {
+ const status = (e as { status?: number }).status ?? 502;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
+ }
+ }
if (body.op === "transcribe") {
const found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, null);
const i = Number(body.media);
@@ -172,5 +239,5 @@ export async function POST(request: Request) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
}
}
- return Response.json({ error: "op is set or transcribe" }, { status: 400 });
+ return Response.json({ error: "op is set, fx, take-words or transcribe" }, { status: 400 });
}
diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx
@@ -9,6 +9,8 @@ import { postBenchHref } from "@/lib/hrefs";
import { POST_HOLD, POST_MEDIA_MIN_SPAN, POST_PARAPHRASE_MAX, contextReadSeconds, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item";
import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer";
import PostNarrationPanel from "./PostNarrationPanel";
+import PostZoomPanel from "./PostZoomPanel";
+import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
// THE POST BENCH, the client half (PostBenchPage.tsx): the item played on its
@@ -208,6 +210,13 @@ export default function PostBench({
return () => clearTimeout(t);
});
+ const zoomMarks = useMemo(
+ () =>
+ (wordZoomTimes(entry, render) as Array<{ i: number; t?: number }>)
+ .filter((z) => typeof z.t === "number")
+ .map((z) => ({ i: z.i, ...zoomSpan((entry.fx as Array<Record<string, unknown>>)[z.i], z.t as number) })),
+ [entry, render],
+ );
const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null;
const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
const reading = readingSeconds(entry);
@@ -264,8 +273,25 @@ export default function PostBench({
{st.kind} {st.seconds.toFixed(1)} s
</div>
))}
+ {/* Its word zooms (word-zoom.mjs): each from its lead-in to back out. */}
+ {zoomMarks.map((z) => (
+ <div key={z.i} className="absolute inset-y-0 border-x border-amber-400/80 bg-amber-400/25" style={{ left: `${(z.t0 / total) * 100}%`, width: `${((z.t3 - z.t0) / total) * 100}%` }} title={`word zoom ${z.i + 1}`} data-post-bench-zoom-mark={z.i} />
+ ))}
<div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} />
</div>
+ <PostZoomPanel
+ project={project}
+ entry={entry}
+ token={token}
+ render={render}
+ s={s}
+ setS={setS}
+ onEntry={(e, t) => {
+ setEntry(e as Entry);
+ setSaved(e as Entry);
+ setToken(t);
+ }}
+ />
<PostNarrationPanel
project={project}
entry={entry}
diff --git a/umtool/components/projects/PostNarrationPanel.tsx b/umtool/components/projects/PostNarrationPanel.tsx
@@ -12,6 +12,7 @@ import { usePeaks } from "./bench/usePeaks";
import { useNotes } from "@/lib/annotations/useNotes";
import { MIC_KEY, ls, useMic } from "./useMic";
import type { PostPlan } from "./review/PostItemPlayer";
+import { wordZoomTimes, zoomSpan } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
// A POST's NARRATION ON THE BENCH (report-to-video/post-narration.mjs;
@@ -463,6 +464,11 @@ export default function PostNarrationPanel({
<span key={p.n} className="absolute inset-y-0 w-px bg-amber-200/70" style={{ left: `${(p.start / picked.seconds) * 100}%` }} title={`part ${p.n}`} />
))}
</div>
+ {/* The word zooms on the read: from the lead-in to back out (word-zoom.mjs). */}
+ {(wordZoomTimes(entry, render) as Array<{ i: number; t?: number }>).filter((z) => typeof z.t === "number").map((z) => {
+ const sp = zoomSpan((entry.fx as Array<Record<string, unknown>>)[z.i], z.t as number);
+ return <div key={`z${z.i}`} className="pointer-events-none absolute inset-y-0 border-x-2 border-amber-300 bg-amber-300/10" style={{ left: pct(sp.t0), width: pct(sp.t3 - sp.t0) }} title={`word zoom ${z.i + 1}`} data-post-lane-zoom={z.i} />;
+ })}
<div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: pct(s) }} />
</div>
</div>
diff --git a/umtool/components/projects/PostZoomPanel.tsx b/umtool/components/projects/PostZoomPanel.tsx
@@ -0,0 +1,290 @@
+"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";
+
+// ---------------------------------------------------------------------------
+// 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. Every change is one write (POST /api/report/post-item, op "fx").
+// ---------------------------------------------------------------------------
+
+type Entry = Record<string, unknown> & { id: string; fx?: Array<Record<string, unknown>> };
+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<string, unknown>;
+ 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<string | null>(null);
+ const [status, setStatus] = useState<string | null>(null);
+ const [sel, setSel] = useState<Sel>(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 narrated = isNarrated(entry);
+ const take = pickedTake(entry) as (Record<string, unknown> & { words?: unknown[] }) | null;
+
+ const send = async (fx: Record<string, unknown>) => {
+ 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 () => {
+ if (!sel) return;
+ 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<string, unknown> = { kind: "word-zoom", match, ...(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.
+ if (!narrated) add.at = readingEstimate(sel.from);
+ const e = await send({ add });
+ if (e) {
+ setStatus(`zoom added on "${match}"`);
+ setSel(null);
+ }
+ };
+
+ // 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 (
+ <label className="flex items-center gap-1" key={key}>
+ {key}
+ <input
+ type="number"
+ step={step}
+ min={lo}
+ max={hi}
+ defaultValue={Number(fx[key])}
+ key={`${entry.id}:${i}:${key}:${String(fx[key])}`}
+ onBlur={(ev) => {
+ const v = Number(ev.target.value);
+ if (Number.isFinite(v) && v !== Number(fx[key])) void send({ set: i, patch: { [key]: v === WORD_ZOOM_DEFAULTS[key] ? null : v } });
+ }}
+ className="w-14 rounded border border-seam bg-ground px-1 py-0.5"
+ data-post-zoom-knob={key}
+ />
+ </label>
+ );
+ };
+
+ return (
+ <section className="space-y-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3 text-[12.5px]" data-post-zoom-panel={entry.id}>
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="micro m-0">word zoom</h2>
+ {targets.length > 1 && (
+ <select value={target} onChange={(e) => (setTarget(e.target.value), setSel(null))} data-post-zoom-target="">
+ {targets.map((t) => (
+ <option key={t.target} value={t.target}>
+ {t.label}
+ </option>
+ ))}
+ </select>
+ )}
+ {narrated && (
+ <span className="ml-auto flex items-center gap-2">
+ <span className="text-text-2" data-post-zoom-words-state="">
+ {take?.words?.length ? `the take is timed (${take.words.length} words)` : "the take has no word timings"}
+ </span>
+ {wordsJob?.state === "transcribing" ? (
+ <span data-post-zoom-words-running="">transcribing on the editor…</span>
+ ) : (
+ <button type="button" className={btn} onClick={() => void getWords()} data-post-zoom-get-words="">
+ Get word timings
+ </button>
+ )}
+ </span>
+ )}
+ </div>
+ {wordsJob?.state === "failed" && <p className="m-0 text-[var(--color-blocking,#c33)]">{wordsJob.error}</p>}
+ <p className="m-0 text-text-2">Click a word (shift-click another: a phrase), then Zoom here.</p>
+ <div className="max-h-40 overflow-y-auto rounded border border-seam bg-ground p-2 leading-7" data-post-zoom-words={target}>
+ {tokens.map((t) => {
+ const on = sel && sel.target === target && t.i >= sel.from && t.i <= sel.to;
+ return (
+ <button
+ key={t.i}
+ type="button"
+ className={cn("mr-1 rounded px-0.5", on ? "bg-amber-400/40 ring-1 ring-amber-400" : "hover:bg-white/10")}
+ onClick={(ev) => {
+ if (ev.shiftKey && sel && sel.target === target) setSel({ target, from: Math.min(sel.from, t.i), to: Math.max(sel.to, t.i) });
+ else setSel({ target, from: t.i, to: t.i });
+ }}
+ data-post-zoom-word={t.i}
+ >
+ {t.tok}
+ </button>
+ );
+ })}
+ </div>
+ <div className="flex items-center gap-2">
+ <button type="button" className={btn} disabled={!sel} onClick={() => void zoomHere()} data-post-zoom-here="">
+ Zoom here
+ </button>
+ {sel && (
+ <span className="text-text-2" data-post-zoom-sel="">
+ “{tokens.slice(sel.from, sel.to + 1).map((t) => t.tok).join(" ")}”
+ </span>
+ )}
+ </div>
+ {list.map((fx0, i) => {
+ 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 (
+ <div key={i} className={cn("space-y-1.5 rounded border p-2", up ? "border-amber-400/70" : "border-seam")} data-post-zoom-fx={i}>
+ <div className="flex flex-wrap items-center gap-2">
+ <b>
+ #{i + 1} “{fx.match}”
+ </b>
+ <span className="text-text-2">
+ {fx.target !== "post" ? `${fx.target} · ` : ""}
+ {fx.occurrence > 1 ? `its ${fx.occurrence}th time · ` : ""}
+ </span>
+ {at !== null ? (
+ <span data-post-zoom-at={String(at)}>
+ at {at.toFixed(2)} s {t.source === "words" ? "(the take's words)" : "(set by hand)"}
+ </span>
+ ) : (
+ <span className="text-[var(--color-blocking,#c33)]" data-post-zoom-no-time="">
+ {t?.error}
+ </span>
+ )}
+ <button type="button" className="ink-link ml-auto" onClick={() => setS(Math.max(0, (span?.t0 ?? 0) - 0.3))} disabled={!span} data-post-zoom-go={i}>
+ play it
+ </button>
+ <button type="button" className="ink-link" onClick={() => void send({ remove: i })} data-post-zoom-remove={i}>
+ remove
+ </button>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ at
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(Math.max(0, (at ?? 0) - 0.1)) } })} data-post-zoom-nudge="-">
+ −0.1
+ </button>
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2((at ?? 0) + 0.1) } })} data-post-zoom-nudge="+">
+ +0.1
+ </button>
+ <button type="button" className={btn} onClick={() => void send({ set: i, patch: { at: r2(s) } })} data-post-zoom-at-playhead="">
+ at playhead
+ </button>
+ {typeof fx0.at === "number" && narrated && (
+ <button type="button" className="ink-link" onClick={() => void send({ set: i, patch: { at: null } })} data-post-zoom-from-words="">
+ from the words
+ </button>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {knob(i, "scale", 0.1)}
+ {knob(i, "lead", 0.1)}
+ {knob(i, "hold", 0.1)}
+ <label className="flex items-center gap-1">
+ ease
+ <select value={fx.ease} onChange={(e) => void send({ set: i, patch: { ease: e.target.value === WORD_ZOOM_DEFAULTS.ease ? null : e.target.value } })} data-post-zoom-knob="ease">
+ {WORD_ZOOM_EASES.map((x) => (
+ <option key={x} value={x}>
+ {x}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-1">
+ <input type="checkbox" checked={fx.highlight !== false} onChange={(e) => void send({ set: i, patch: { highlight: e.target.checked ? null : false } })} data-post-zoom-knob="highlight" />
+ highlight
+ </label>
+ {fx.highlight !== false && (
+ <input
+ type="color"
+ defaultValue={String(fx.highlight).length === 7 ? String(fx.highlight) : WORD_ZOOM_DEFAULTS.highlight}
+ key={`${entry.id}:${i}:hl:${String(fx.highlight)}`}
+ onBlur={(e) => 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"
+ />
+ )}
+ </div>
+ </div>
+ );
+ })}
+ {status && <p className="m-0 text-text-2" data-post-zoom-status="">{status}</p>}
+ {error && (
+ <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-zoom-error="">
+ {error}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item";
import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-video/post-narration";
+import { WORD_ZOOM_HIGHLIGHT_ALPHA, findMatch, highlightAt, resolveWordZoom, targetScope, targetTextOf, wordZoomTimes, zoomAt, zoomProgressAt, zoomSpan, zoomWindow } from "umtool-report-to-video/word-zoom";
// ---------------------------------------------------------------------------
// A POST ITEM PLAYED (report-to-video/post-item.mjs; knobs.md, "Play the cut"):
@@ -17,8 +18,54 @@ import { dryGainAt, mixPhaseAt, pickedTake, wetGainAt } from "umtool-report-to-v
// the pitch kept), so a fast-forward SPEEDS the item up rather than seeking
// it forward every few frames. The voice plays at that times the read's own
// `rate` (post-narration.mjs). A video's words show at the slot's foot.
+//
+// A WORD ZOOM (word-zoom.mjs) plays live on the same curve as the render's: the
+// card's contents scaled toward the word's box (measured in the card page: its
+// `data-w` spans) inside the card, which clips them, its highlight fading in
+// under the word -- the card page's own elements transformed, nothing redrawn.
// ---------------------------------------------------------------------------
+type Rect = { x: number; y: number; width: number; height: number };
+/** A zoom of the item, measured in its card page: its span on the item's clock, the card's region, the word's box. */
+type LiveZoom = { i: number; span: ReturnType<typeof zoomSpan>; scope: string; from: number; to: number; color: string | null; region: Rect; word: Rect };
+
+/** The card's children placed so the region shows `win` (zoomWindow) at z; their layout boxes measured before any transform. */
+function applyZoom(doc: Document, z: LiveZoom | null, zf: number, hl: number, boxes: Map<Element, Rect>) {
+ const card = doc.querySelector("[data-post-card]");
+ if (!card) return;
+ const kids = Array.from(card.children) as HTMLElement[];
+ if (!z || zf <= 1.0005) {
+ for (const k of kids) if (k.style.transform) k.style.transform = "";
+ } else {
+ const win = zoomWindow(z.region, z.word, z.span.scale, zf);
+ for (const k of kids) {
+ const c = boxes.get(k);
+ if (!c) continue;
+ // Window point P is drawn at R + (P - W)·z: a child's corner C moves by R - z·W + (z - 1)·C, scaled about it.
+ const tx = z.region.x - zf * win.x + (zf - 1) * c.x;
+ const ty = z.region.y - zf * win.y + (zf - 1) * c.y;
+ k.style.transformOrigin = "0 0";
+ k.style.transform = `translate(${tx}px, ${ty}px) scale(${zf})`;
+ }
+ }
+ doc.querySelectorAll("[data-w-live-hl]").forEach((el) => {
+ (el as HTMLElement).style.background = "";
+ (el as HTMLElement).style.boxShadow = "";
+ el.removeAttribute("data-w-live-hl");
+ });
+ if (z && z.color && hl > 0) {
+ const [r, g, b] = [1, 3, 5].map((o) => parseInt((z.color!.length === 4 ? z.color!.replace(/^#(.)(.)(.)$/, "#$1$1$2$2$3$3") : z.color!).slice(o, o + 2), 16));
+ for (let i = z.from; i <= z.to; i += 1) {
+ const el = doc.querySelector(`[data-w="${z.scope}:${i}"]`) as HTMLElement | null;
+ if (!el) continue;
+ el.setAttribute("data-w-live-hl", "");
+ el.style.background = `rgba(${r}, ${g}, ${b}, ${WORD_ZOOM_HIGHLIGHT_ALPHA * hl})`;
+ el.style.boxShadow = `inset 0 -0.12em 0 rgba(${r}, ${g}, ${b}, ${hl})`;
+ el.style.borderRadius = "0.16em";
+ }
+ }
+}
+
/** A narrated item's mix on its clock (post-narration.mjs narrationSchedule). */
export type NarrationSchedule = { at: number; seconds: number; takeSeconds?: number; rate?: number; voiceEnd: number; rampEnd: number; wet: number; lowpassHz: number; duck: boolean; attach?: string; lufs?: number };
@@ -271,6 +318,69 @@ export default function PostItemPlayer({
gone = true;
};
}, [wordsRel, project, cues]);
+ // ---- the word zooms, live: measured in the card page once it is drawn, applied on the item's clock ----
+ const readFrame = useRef<HTMLIFrameElement | null>(null);
+ const [zooms, setZooms] = useState<LiveZoom[]>([]);
+ const boxes = useRef<Map<Element, Rect>>(new Map());
+ const zoomTimes = useMemo(() => (Array.isArray(entry.fx) && entry.fx.length ? wordZoomTimes(entry, undefined, plan.narration as never) : []), [entry, plan.narration]);
+ const measure = useCallback(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (!doc || doc.body?.getAttribute("data-post-ready") !== "1") return false;
+ const card = doc.querySelector("[data-post-card]") as HTMLElement | null;
+ const list = Array.isArray(entry.fx) ? (entry.fx as Array<Record<string, unknown>>) : [];
+ if (!card || !list.length) {
+ setZooms([]);
+ return true;
+ }
+ const rect = (el: Element): Rect => {
+ const b = el.getBoundingClientRect();
+ return { x: b.left, y: b.top, width: b.width, height: b.height };
+ };
+ // Laid out untransformed first: the boxes every zoom is placed from.
+ for (const k of Array.from(card.children) as HTMLElement[]) k.style.transform = "";
+ boxes.current = new Map(Array.from(card.children).map((k) => [k, rect(k)]));
+ const c = rect(card);
+ const r = Math.round(18 * (box.height / 1080)) + 1;
+ const region = { x: c.x + r, y: c.y + r, width: c.width - 2 * r, height: c.height - 2 * r };
+ const out: LiveZoom[] = [];
+ list.forEach((fx0, i) => {
+ const t = zoomTimes[i] as { t?: number } | undefined;
+ if (typeof t?.t !== "number") return;
+ const fx = resolveWordZoom(fx0);
+ const m = findMatch(targetTextOf(entry, fx.target) ?? "", fx.match, fx.occurrence);
+ if (m.error) return;
+ const scope = targetScope(fx.target);
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (let w = m.from; w <= m.to; w += 1) {
+ const el = doc.querySelector(`[data-w="${scope}:${w}"]`);
+ if (!el) return;
+ const b = rect(el);
+ x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y); x1 = Math.max(x1, b.x + b.width); y1 = Math.max(y1, b.y + b.height);
+ }
+ out.push({ i, span: zoomSpan(fx0, t.t), scope, from: m.from, to: m.to, color: fx.highlight === false ? null : String(fx.highlight), region, word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 } });
+ });
+ setZooms(out);
+ return true;
+ }, [entry, zoomTimes, box.height]);
+ const onFrameLoad = useCallback(() => {
+ let tries = 0;
+ const tick = () => {
+ if (measure() || tries++ > 50) return;
+ setTimeout(tick, 100);
+ };
+ tick();
+ }, [measure]);
+ useEffect(() => {
+ // The item changed under a loaded page (a knob, a zoom added): measure again.
+ onFrameLoad();
+ }, [onFrameLoad]);
+ 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;
+ useEffect(() => {
+ const doc = readFrame.current?.contentDocument;
+ if (doc) applyZoom(doc, live, zf, hl, boxes.current);
+ }, [live, zf, hl]);
const src = shown && inStep ? mediaTimeAt(shown, s) : null;
const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null;
return (
@@ -285,6 +395,9 @@ export default function PostItemPlayer({
data-post-wet={mix ? String(Math.round(wetGainAt(mix, s) * 100) / 100) : undefined}
data-post-dry={mix ? String(Math.round(dryGainAt(mix, s) * 100) / 100) : undefined}
data-post-narration-playing={mix ? (playing && speaking ? "1" : "0") : undefined}
+ data-post-zooms={zooms.length ? String(zooms.length) : undefined}
+ data-post-zoom={zooms.length ? String(Math.round(zf * 100) / 100) : undefined}
+ data-post-zoom-fx={live ? String(live.i) : undefined}
className="pointer-events-none absolute inset-0 overflow-hidden"
>
{mix && voiceTake && (
@@ -295,6 +408,8 @@ export default function PostItemPlayer({
<div className="absolute left-0 top-0" style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}>
<iframe
title={`post ${entry.id}`}
+ ref={readFrame}
+ onLoad={onFrameLoad}
src={pageUrl("read")}
data-post-card-frame="read"
className="absolute inset-0 border-0"