// A POST ITEM's WORD ZOOM (umtool/docs/report-video.md, "A word zoom"; operator, // 3 Nov: "zoom in on the "barbecue" typo when it's being read out and make that // effect a standard thing we can use and tune in the UI"): the card pushed in on // one word (or a phrase) of its text as it is read, a highlight under it, then // back out. // // entry.fx = [{ kind: "word-zoom", // target?: "post" | "parent:" | "quoted", // whose words (default: the post's own) // match: "", // occurrence?: n, // its n-th time in that text (default 1) // at?: , // when; absent: from the take's word timings // lead?: s, hold?: s, scale?: 1.2–4, // in over lead before it, held, x scale // ease?: "out" | "inOut" | "snap", // highlight?: "#rrggbb" | false }] // the marker under it (default WORD_ZOOM_DEFAULTS) // // WHEN: `at` when it is set (the operator's nudge wins), else the matched // word's start in the picked take (`takes[i].words`, the editor's transcription // aligned to the script: `umtool posts narrate

--words`) on the // item's clock -- the read's lead + start ÷ the read's rate. An un-narrated // post has no read to time it by: its zoom needs `at`. // // THE CURVE (one function, the render's ffmpeg expressions and Play's CSS read // it): progress p 0 → 1 over [t - lead, t] on the ease, 1 for `hold`, back to 0 // over WORD_ZOOM_OUT on the same ease. The zoom is z = 1 + (scale - 1)·p; the // window is the card's region at 1/z of its size, moving toward the word so the // word's box is centred (clamped inside the region) when z = scale. // // PURE and dependency-free but for the post's text rules: the validator, the // card's word tokens (the card HTML wraps each in a span the build measures), // the match, the alignment of recognized words to a script, the time, the curve. import { cardText, contextText, parentsOf } from "./post-item.mjs"; import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; import { captionErrors } from "./post-caption.mjs"; import { clockErrors } from "./post-clock.mjs"; import { slamErrors } from "./post-slam.mjs"; // A post's effects: a word zoom, a CAPTION (post-caption.mjs: a chip explaining a phrase as it is read), and its // CLOCK (post-clock.mjs: the post's time on the card, running from the item before's), and a SLAM (post-slam.mjs: // a trailer-style title slam of a few glyphs over the word as it is read, one trailer hit per glyph). export const POST_FX_KINDS = Object.freeze(["word-zoom", "caption", "clock", "slam"]); export const POST_FX_MAX = 8; export const WORD_ZOOM_EASES = Object.freeze(["out", "inOut", "snap"]); export const WORD_ZOOM_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.5, hold: 1.2, scale: 2, ease: "inOut", highlight: "#ffd84d" }); export const WORD_ZOOM_LIMITS = Object.freeze({ lead: [0, 3], hold: [0, 10], scale: [1.2, 4], at: [0, 600], occurrence: [1, 99] }); /** The way back out, seconds, on the zoom's ease. */ export const WORD_ZOOM_OUT = 0.4; /** The highlight's fill: the colour at this opacity, under the words (the card's text stays on top, readable). */ export const WORD_ZOOM_HIGHLIGHT_ALPHA = 0.42; /** The longest match, in characters. */ export const WORD_ZOOM_MATCH_MAX = 120; const KEYS = new Set(["kind", "target", "match", "occurrence", "at", "lead", "hold", "scale", "ease", "highlight"]); const HEX_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const numIn = (v, [lo, hi]) => fin(v) && v >= lo && v <= hi; const r3 = (v) => Math.round(v * 1000) / 1000; const str = (v) => (typeof v === "string" ? v : ""); // --------------------------------------------------------------------------- // The card's words. // --------------------------------------------------------------------------- /** The text's tokens as the card draws them: `[{ tok, i }]` for each run of non-space (i from 0), `{ space }` between. */ export function cardTokens(text) { const out = []; let i = 0; for (const part of str(text).split(/(\s+)/)) { if (!part) continue; if (/^\s+$/.test(part)) out.push({ space: part }); else out.push({ tok: part, i: i++ }); } return out; } /** The card's words of `text` (cardTokens' words, in order). */ export const cardWordsOf = (text) => cardTokens(text).filter((t) => t.tok !== undefined).map((t) => t.tok); /** A word reduced for matching: lower case, its leading and trailing punctuation gone ("Barbecue," -> "barbecue"). */ export const normWord = (w) => str(w).toLowerCase().normalize("NFKC").replace(/[‘’]/g, "'").replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""); /** The text a target names on the card (the post's own words; a context post's: its paraphrase when it has one), or null. */ export function targetTextOf(entry, target = "post") { if (target === "post") return cardText(entry); if (target === "quoted") return isObj(entry?.quoted) ? contextText(entry.quoted) : null; const m = /^parent:(\d+)$/.exec(String(target)); if (m) { const p = parentsOf(entry)[Number(m[1])]; return p ? contextText(p) : null; } return null; } /** The scope a target's word spans carry on the card (`data-w=":"`). */ export const targetScope = (target = "post") => String(target ?? "post"); /** * Where `match` is in `text`: its `occurrence`-th run of words (1-based), as * `{ from, to, count }` card-word indices (inclusive), or `{ error, count }` * (from and to -1). * @param {string|null|undefined} text * @param {string} match * @param {number} [occurrence] * @returns {{ from: number, to: number, count: number, error?: string }} */ export function findMatch(text, match, occurrence = 1) { const want = str(match).split(/\s+/).map(normWord).filter(Boolean); if (!want.length) return { error: "match names no word", count: 0, from: -1, to: -1 }; const words = cardWordsOf(text).map(normWord); const hits = []; for (let i = 0; i + want.length <= words.length; i += 1) { if (want.every((w, k) => words[i + k] === w)) hits.push(i); } const n = Number.isInteger(occurrence) ? occurrence : 1; if (!hits.length) return { error: "not in", count: 0, from: -1, to: -1 }; if (n > hits.length) return { error: "occurrence", count: hits.length, from: -1, to: -1 }; return { from: hits[n - 1], to: hits[n - 1] + want.length - 1, count: hits.length }; } const TARGET_NAME = (t) => (t === "post" ? "the post's words" : t === "quoted" ? "the quoted post's words" : `the words of the post it answers (${t})`); // --------------------------------------------------------------------------- // The validator. // --------------------------------------------------------------------------- /** * One zoom with every default filled in. * @param {Record | null | undefined} fx * @returns {{ kind?: string, target: string, match: string, occurrence: number, at?: number, lead: number, hold: number, scale: number, ease: string, highlight: string | false }} */ export const resolveWordZoom = (fx) => ({ ...WORD_ZOOM_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) }); /** Every reason post item `e`'s `fx` cannot be built, as sentences (empty: it can). Time is the build's to judge (wordZoomTimes). */ export function validatePostFx(e) { if (e?.fx === undefined) return []; const w = `timeline ${e?.id ?? "?"}.fx`; if (!Array.isArray(e.fx)) return [`${w} must be a list of the post's effects ([{ kind: "word-zoom", match, … }])`]; const errors = []; if (e.fx.length > POST_FX_MAX) errors.push(`${w}: at most ${POST_FX_MAX} effects`); e.fx.forEach((fx, i) => { const fw = `${w}[${i}]`; if (!isObj(fx)) return errors.push(`${fw} must be an object`); if (!POST_FX_KINDS.includes(fx.kind)) return errors.push(`${fw}.kind must be one of ${POST_FX_KINDS.join(", ")}`); if (fx.kind === "caption") return errors.push(...captionErrors(e, fx, fw)); if (fx.kind === "clock") return errors.push(...clockErrors(e, fx, fw)); if (fx.kind === "slam") return errors.push(...slamErrors(e, fx, fw)); for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a word-zoom key (${[...KEYS].join(", ")})`); const target = fx.target ?? "post"; const text = typeof target === "string" ? targetTextOf(e, target) : null; if (fx.target !== undefined && !(typeof fx.target === "string" && /^(post|quoted|parent:\d+)$/.test(fx.target))) errors.push(`${fw}.target must be "post", "quoted" or "parent:"`); else if (text === null) errors.push(`${fw}.target ${target}: the card draws no such post (${target === "quoted" ? "it quotes none" : "it answers no post there"})`); if (typeof fx.match !== "string" || !fx.match.trim()) errors.push(`${fw}.match must be the word or phrase to zoom on, as the card shows it`); else if (fx.match.length > WORD_ZOOM_MATCH_MAX) errors.push(`${fw}.match is longer than ${WORD_ZOOM_MATCH_MAX} characters`); if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, WORD_ZOOM_LIMITS.occurrence))) errors.push(`${fw}.occurrence must be a whole number from 1 (its first time in the text)`); if (typeof fx.match === "string" && fx.match.trim() && text !== null) { const m = findMatch(text, fx.match, fx.occurrence ?? 1); if (m.error === "not in") errors.push(`${fw}.match "${fx.match}" is not in ${TARGET_NAME(target)}`); else if (m.error === "occurrence") errors.push(`${fw}.match "${fx.match}" is in ${TARGET_NAME(target)} ${m.count} time${m.count === 1 ? "" : "s"}: occurrence ${fx.occurrence} is not there`); else if (m.error) errors.push(`${fw}.match: ${m.error}`); } for (const k of ["at", "lead", "hold", "scale"]) { if (fx[k] !== undefined && !numIn(fx[k], WORD_ZOOM_LIMITS[k])) errors.push(`${fw}.${k} must be ${WORD_ZOOM_LIMITS[k][0]}–${WORD_ZOOM_LIMITS[k][1]}${k === "scale" ? " (times the card)" : " seconds"}`); } if (fx.ease !== undefined && !WORD_ZOOM_EASES.includes(fx.ease)) errors.push(`${fw}.ease must be one of ${WORD_ZOOM_EASES.join(", ")}`); if (fx.highlight !== undefined && fx.highlight !== false && !(typeof fx.highlight === "string" && HEX_RE.test(fx.highlight))) errors.push(`${fw}.highlight must be a colour (#rrggbb) or false (none)`); }); return errors; } // --------------------------------------------------------------------------- // Word timings: the editor's recognized words aligned to the script. // --------------------------------------------------------------------------- const NUMBERS = { 0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 20: "twenty", 100: "hundred" }; const spoken = (w) => { const n = normWord(w).replace(/'/g, ""); return /^\d+$/.test(n) && NUMBERS[Number(n)] ? NUMBERS[Number(n)] : n; }; function lev(a, b) { if (a === b) return 0; if (!a.length) return b.length; if (!b.length) return a.length; let prev = Array.from({ length: b.length + 1 }, (_, j) => j); for (let i = 1; i <= a.length; i += 1) { const cur = [i]; for (let j = 1; j <= b.length; j += 1) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); prev = cur; } return prev[b.length]; } /** How alike two words are, 0–1: 1 the same, else 1 - edit distance ÷ the longer (a typo read as the word it means scores high). */ export function wordSimilarity(a, b) { const x = spoken(a); const y = spoken(b); if (!x || !y) return 0; if (x === y) return 1; const max = Math.max(x.length, y.length); // The edit distance is at least the difference in length: past half the longer, no pair (skip the work). if (Math.abs(x.length - y.length) > max * (1 - ALIGN_MIN)) return 0; return Math.max(0, 1 - lev(x, y) / max); } /** Below this, two words are not the same word. */ export const ALIGN_MIN = 0.5; /** * THE ALIGNMENT, in order: each word of `a` paired with at most one of `b`, * never crossing, maximising the summed similarity (pairs under ALIGN_MIN are * not pairs). Returns `map[i]` = b's index for a's word i, or -1. * * @param {string[]} a * @param {string[]} b */ export function alignWords(a, b) { const n = a.length; const m = b.length; const map = new Array(n).fill(-1); if (!n || !m) return map; const W = m + 1; const D = new Float32Array((n + 1) * W); const sim = (i, j) => wordSimilarity(a[i], b[j]); for (let i = 1; i <= n; i += 1) { for (let j = 1; j <= m; j += 1) { const s = sim(i - 1, j - 1); const diag = s >= ALIGN_MIN ? D[(i - 1) * W + j - 1] + s : -1; D[i * W + j] = Math.max(D[(i - 1) * W + j], D[i * W + j - 1], diag); } } let i = n; let j = m; while (i > 0 && j > 0) { const here = D[i * W + j]; if (here === D[(i - 1) * W + j]) i -= 1; else if (here === D[i * W + j - 1]) j -= 1; else { map[i - 1] = j - 1; i -= 1; j -= 1; } } return map; } /** A script's spoken words: its runs of non-space, Orpheus's tags () dropped. */ export const scriptWordsOf = (script) => str(script).replace(/<[^<>]*>/g, " ").split(/\s+/).filter((w) => normWord(w)); /** * A TAKE's WORD TIMINGS from what the editor heard: `recognized` `[{ w, start, * end }]` (take seconds, in order) aligned to the script's words; each script * word gets the times of the word it was heard as, and a word not heard (or * heard as something else) is spread evenly between its heard neighbours. * Returns `[{ w, start, end }]`, one per script word, and how many were heard. * * @param {string} script * @param {Array<{ w: string, start: number, end: number }>} recognized */ export function scriptWordTimes(script, recognized) { const words = scriptWordsOf(script); const heard = (Array.isArray(recognized) ? recognized : []).filter((r) => r && typeof r.w === "string" && fin(r.start) && fin(r.end) && normWord(r.w)); const map = alignWords(words, heard.map((r) => r.w)); const out = words.map((w, i) => (map[i] >= 0 ? { w, start: r3(heard[map[i]].start), end: r3(Math.max(heard[map[i]].start, heard[map[i]].end)) } : { w, start: null, end: null })); const total = heard.length ? heard[heard.length - 1].end : 0; for (let i = 0; i < out.length; ) { if (out[i].start !== null) { i += 1; continue; } let k = i; while (k < out.length && out[k].start === null) k += 1; const from = i > 0 ? out[i - 1].end : heard[0]?.start ?? 0; const to = k < out.length ? out[k].start : Math.max(from, total); const step = (to - from) / (k - i); for (let x = i; x < k; x += 1) out[x] = { w: out[x].w, start: r3(from + step * (x - i)), end: r3(from + step * (x - i + 1)) }; i = k; } return { words: out, heard: map.filter((x) => x >= 0).length, of: words.length }; } // --------------------------------------------------------------------------- // WHEN: each zoom's second on the item's clock. // --------------------------------------------------------------------------- /** * Each zoom's moment, `[{ i, t, source: "at"|"words", word? } | { i, error }]`: * `at` when set; else the matched word in the picked take's words -- the card's * words aligned to the script it read -- at lead + start ÷ rate. * @param {Record} entry * @param {Record} [render] * @param {Record | null} [schedule] * @returns {Array<{ i: number, t?: number, kind?: string, source?: "at" | "words", word?: { w: string, start: number, end: number, index: number }, error?: string }>} */ export function wordZoomTimes(entry, render = undefined, schedule = undefined) { const list = Array.isArray(entry?.fx) ? entry.fx : []; const narrated = isNarrated(entry); const take = narrated ? pickedTake(entry) : null; // `schedule`: the item's narration schedule when the caller has it (Play: the plan's), else worked out here. const sch = narrated ? schedule ?? narrationSchedule(entry, render) : null; return list.map((fx0, i) => { // Another effect (a caption, post-caption.mjs) is timed by its own module: no time here, and no error. if (isObj(fx0) && fx0.kind !== "word-zoom" && POST_FX_KINDS.includes(fx0.kind)) return { i, kind: fx0.kind }; if (!isObj(fx0) || fx0.kind !== "word-zoom") return { i, error: "not a word zoom" }; const fx = resolveWordZoom(fx0); if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" }; const w = `${entry?.id ?? "?"}: word zoom ${i + 1} ("${fx.match}")`; if (!narrated) return { i, error: `${w} has no time: the post is not narrated, so set its second (at, item seconds)` }; const words = Array.isArray(take?.words) ? take.words : null; if (!words?.length) return { i, error: `${w} has no time: its take has no word timings yet (umtool posts narrate

${entry.id} --words, or the bench's Get word timings) -- or set at` }; const text = targetTextOf(entry, fx.target); const m = findMatch(text, fx.match, fx.occurrence); if (m.error) return { i, error: `${w} is not on the card` }; const map = alignWords(cardWordsOf(text), words.map((x) => x.w)); let hit = -1; for (let k = m.from; k <= m.to && hit < 0; k += 1) hit = map[k]; if (hit < 0) return { i, error: `${w} is not in the read (the script does not say it, or the take's words do not reach it) -- set at` }; return { i, t: r3(sch.at + words[hit].start / (sch.rate || 1)), source: "words", word: { ...words[hit], index: hit } }; }); } /** The reading estimate for an un-narrated post's word (the CLI's and the bench's first `at`): 1 s to find it, then 3 words a second. */ export const readingEstimate = (wordIndex) => Math.round((1 + Math.max(0, wordIndex) / 3) * 100) / 100; // --------------------------------------------------------------------------- // THE CURVE. // --------------------------------------------------------------------------- /** The ease, 0–1 → 0–1. */ export function easeOf(name, x) { const v = Math.min(1, Math.max(0, x)); if (name === "out") return 1 - (1 - v) ** 3; if (name === "snap") return v >= 1 ? 1 : 1 - 2 ** (-10 * v); return v < 0.5 ? 4 * v ** 3 : 1 - (-2 * v + 2) ** 3 / 2; } /** One zoom's span on the item's clock: in from t0 to t1 (= t), held to t2, out by t3. */ export function zoomSpan(fx0, t) { const fx = resolveWordZoom(fx0); const t1 = r3(t); const t0 = r3(Math.max(0, t1 - fx.lead)); const t2 = r3(t1 + fx.hold); return { t0, t1, t2, t3: r3(t2 + WORD_ZOOM_OUT), scale: fx.scale, ease: fx.ease }; } /** The zoom's progress at item second `s` (0 none, 1 all the way in). */ export function zoomProgressAt(span, s) { if (!span || s < span.t0 || s >= span.t3) return 0; if (s < span.t1) return span.t1 > span.t0 ? easeOf(span.ease, (s - span.t0) / (span.t1 - span.t0)) : 1; if (s < span.t2) return 1; return 1 - easeOf(span.ease, (s - span.t2) / (span.t3 - span.t2)); } /** The highlight's opacity at item second `s`, 0–1: linear in over the lead, out over the way back (the render's alpha fades). */ export function highlightAt(span, s) { if (!span || s < span.t0 || s >= span.t3) return 0; if (s < span.t1) return span.t1 > span.t0 ? (s - span.t0) / (span.t1 - span.t0) : 1; if (s < span.t2) return 1; return 1 - (s - span.t2) / (span.t3 - span.t2); } /** The zoom factor at progress p. */ export const zoomAt = (span, p) => 1 + (span.scale - 1) * p; /** * THE WINDOW at zoom z: the part of `region` (the card's box, px) shown * filling it -- 1/z of its size, moving from the whole region (z = 1) to the * one centred on `word` (its box, px; clamped inside the region) at z = scale. * @returns {{ x: number, y: number, width: number, height: number }} */ export function zoomWindow(region, word, scale, z) { const fw = region.width / scale; const fh = region.height / scale; const cx = word.x + word.width / 2; const cy = word.y + word.height / 2; const fx = Math.min(region.x + region.width - fw, Math.max(region.x, cx - fw / 2)); const fy = Math.min(region.y + region.height - fh, Math.max(region.y, cy - fh / 2)); // q runs 0 → 1 as z runs 1 → scale, so the window is exactly region / z. const q = scale > 1 ? (1 - 1 / z) / (1 - 1 / scale) : 0; return { x: region.x + (fx - region.x) * q, y: region.y + (fy - region.y) * q, width: region.width / z, height: region.height / z }; } /** The final window's offset in the region (zoomWindow at z = scale, relative to the region's corner). */ export function zoomTarget(region, word, scale) { const f = zoomWindow(region, word, scale, scale); return { x: f.x - region.x, y: f.y - region.y }; } const f4 = (v) => { const s = (Math.round(Number(v) * 1e4) / 1e4).toFixed(4).replace(/\.?0+$/, ""); return s === "-0" ? "0" : s; }; /** The ease as an ffmpeg expression of `X` (an expression clipped 0–1 by the caller). */ export function easeExpr(name, X) { if (name === "out") return `(1-pow(1-${X},3))`; if (name === "snap") return `if(gte(${X},1),1,1-pow(2,-10*${X}))`; return `if(lt(${X},0.5),4*pow(${X},3),1-pow(-2*${X}+2,3)/2)`; } /** zoomProgressAt as an ffmpeg expression of `S` (the item second). */ export function progressExpr(span, S) { const { t0, t1, t2, t3 } = span; const inX = t1 > t0 ? `clip((${S}-${f4(t0)})/${f4(t1 - t0)},0,1)` : "1"; const outX = `clip((${S}-${f4(t2)})/${f4(t3 - t2)},0,1)`; return `if(lt(${S},${f4(t0)}),0,if(lt(${S},${f4(t1)}),${t1 > t0 ? easeExpr(span.ease, inX) : "1"},if(lt(${S},${f4(t2)}),1,if(lt(${S},${f4(t3)}),1-${easeExpr(span.ease, outX)},0))))`; } /** * The zoompan expressions for one zoom over its region scaled by `k` (the * hi-res card's device scale): `z` from the item second `S`, and `x`, `y` -- * the window's corner in the region's px × k -- from zoompan's own `zoom`. */ export function zoompanExprs(span, target, k, S) { const p = progressExpr(span, S); const q = span.scale > 1 ? `(1-1/zoom)/${f4(1 - 1 / span.scale)}` : "0"; return { z: `1+${f4(span.scale - 1)}*${p}`, x: `${f4(target.x * k)}*${q}`, y: `${f4(target.y * k)}*${q}` }; } /** Two zooms of one post that are up at once (they would fight): their indices, or null. */ export function overlappingZooms(spans) { const s = spans.map((x, i) => ({ ...x, i })).filter((x) => x.t3 !== undefined).sort((a, b) => a.t0 - b.t0); for (let k = 1; k < s.length; k += 1) if (s[k].t0 < s[k - 1].t3) return [s[k - 1].i, s[k].i]; return null; }