// A POST ITEM's CAPTION (umtool/docs/report-video.md, "A caption"; operator, 4 Nov: // a small explanatory chip tied to a phrase -- "不動心 · fudōshin — "immovable // mind"" on "Fudōshin" -- appearing as the phrase is read and held a beat). // // entry.fx = [{ kind: "caption", // target?: "post" | "parent:" | "quoted", // whose words (default: the post's own) // match: "", // occurrence?: n, // its n-th time in that text (default 1) // text: "", // ≤ CAPTION_TEXT_MAX characters, any script (CJK too) // at?: , // when; absent: the take's word timings, else the estimate // lead?: s, hold?: s, // in this long before the word; held this long from it // place?: "below" | "above" | "side" }] // where it sits by the phrase (default below) // // WHEN -- word-zoom's rule: `at` when it is set, else the matched word's start in // the picked take's word timings (the read's lead + start ÷ rate), else the // READING ESTIMATE: a narrated post's read spread over its script by characters, // an un-narrated one's 1 s + 3 words a second (word-zoom.mjs readingEstimate). // A caption never fights a word zoom: one that would be up while a zoom is (its // lead-in to back out) WAITS for the zoom to be out, then comes in. // // WHERE: a chip by the phrase (`place`; below by default), with a notch pointing // at it and an underline under it, inside the card. It never covers a word read // while it is up: a place that would is passed over for the next (below, above, // side), and the chip tracks the phrase while the card pans (read-follow.mjs). // It is drawn OVER the card, never in it: the read-follow geometry // (measureFollow, readInViewErrors) is measured without it, and it carries no // `data-w` / `data-post-block` -- it never counts as text, read or covering. // // THE LOOK: the card's palette (a panel of its background toward its accent, the // accent's border and notch), its faces, then the CJK faces this machine has // (CAPTION_FONT_STACK) so 不動心 is drawn, not boxes. Text before " — " is bold. // // Pure but for the DOM functions (mountCaptions, measureCaptionWords, // setCaptionState), which are SELF-CONTAINED: the build passes them to a page // (page.evaluate), Play calls them on its card frame's document. import { alignWords, cardWordsOf, findMatch, readingEstimate, scriptWordsOf, targetScope, targetTextOf } from "./word-zoom.mjs"; import { isNarrated, narrationSchedule, pickedTake } from "./post-narration.mjs"; import { esc, mixHex, rgbaOf } from "./post-item.mjs"; export const CAPTION_PLACES = Object.freeze(["below", "above", "side"]); export const CAPTION_DEFAULTS = Object.freeze({ target: "post", occurrence: 1, lead: 0.15, hold: 2.5, place: "below" }); export const CAPTION_LIMITS = Object.freeze({ at: [0, 600], lead: [0, 3], hold: [0.5, 10], occurrence: [1, 99] }); export const CAPTION_TEXT_MAX = 160; /** Its fade (and slide) in, and its fade out, seconds. */ export const CAPTION_IN = 0.3; export const CAPTION_OUT = 0.35; /** How far it slides in from, px at 1080. */ export const CAPTION_SLIDE = 16; /** The faces a chip is drawn in: the card's, then the CJK faces (Noto Sans CJK on this machine), then any sans. */ export const CAPTION_FONT_STACK = "'Noto Sans CJK JP', 'Noto Sans CJK SC', 'Source Han Sans JP', 'Source Han Sans CN', 'WenQuanYi Zen Hei', sans-serif"; const KEYS = new Set(["kind", "target", "match", "occurrence", "text", "at", "lead", "hold", "place"]); 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 MATCH_MAX = 120; /** * One caption with every default filled in. * @param {Record | null | undefined} fx * @returns {{ kind?: string, target: string, match: string, occurrence: number, text: string, at?: number, lead: number, hold: number, place: string }} */ export const resolveCaption = (fx) => ({ ...CAPTION_DEFAULTS, ...Object.fromEntries(Object.entries(fx ?? {}).filter(([, v]) => v !== undefined && v !== null)) }); 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})`); /** Every reason caption `fx` (entry `e`'s fx[i], named `fw`) cannot be built, as sentences. word-zoom.mjs validatePostFx calls it. */ export function captionErrors(e, fx, fw) { const errors = []; for (const k of Object.keys(fx)) if (!KEYS.has(k)) errors.push(`${fw}.${k} is not a caption 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 the caption explains, as the card shows it`); else if (fx.match.length > MATCH_MAX) errors.push(`${fw}.match is longer than ${MATCH_MAX} characters`); if (typeof fx.text !== "string" || !fx.text.trim()) errors.push(`${fw}.text must be what the caption says`); else if (fx.text.length > CAPTION_TEXT_MAX) errors.push(`${fw}.text is longer than ${CAPTION_TEXT_MAX} characters (a caption is a chip, not a paragraph)`); if (fx.occurrence !== undefined && !(Number.isInteger(fx.occurrence) && numIn(fx.occurrence, CAPTION_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"]) if (fx[k] !== undefined && !numIn(fx[k], CAPTION_LIMITS[k])) errors.push(`${fw}.${k} must be ${CAPTION_LIMITS[k][0]}–${CAPTION_LIMITS[k][1]} seconds`); if (fx.place !== undefined && !CAPTION_PLACES.includes(fx.place)) errors.push(`${fw}.place must be one of ${CAPTION_PLACES.join(", ")}`); return errors; } // --------------------------------------------------------------------------- // WHEN. // --------------------------------------------------------------------------- /** Fill each null in `times` between its known neighbours (an end with none: the nearest known). */ function fillTimes(times) { const out = times.slice(); const known = out.map((v, i) => (v === null ? -1 : i)).filter((i) => i >= 0); if (!known.length) return out; for (let i = 0; i < out.length; i += 1) { if (out[i] !== null) continue; const a = [...known].reverse().find((k) => k < i); const b = known.find((k) => k > i); if (a === undefined) out[i] = out[b]; else if (b === undefined) out[i] = out[a]; else out[i] = r3(out[a] + ((out[b] - out[a]) * (i - a)) / (b - a)); } return out; } /** * When each card word of `target` is read, item seconds: `{ times, source }` * -- "words" from the picked take's word timings, "estimate" otherwise (a * narrated post: its script's characters spread over the read; an un-narrated * one: readingEstimate). Null when the target draws no words. * @param {Record} entry * @param {Record} [render] * @param {string} [target] * @param {Record | null} [schedule] * @returns {{ times: Array, source: "words" | "estimate" } | null} */ export function cardWordTimes(entry, render = undefined, target = "post", schedule = undefined) { const text = targetTextOf(entry, target); if (text === null) return null; const words = cardWordsOf(text); if (!isNarrated(entry)) return { times: words.map((_, i) => readingEstimate(i)), source: "estimate" }; const sch = schedule ?? narrationSchedule(entry, render); const rate = sch.rate || 1; const take = pickedTake(entry); const timed = Array.isArray(take?.words) && take.words.length ? take.words : null; if (timed) { const map = alignWords(words, timed.map((x) => x.w)); return { times: fillTimes(map.map((k) => (k >= 0 && fin(timed[k].start) ? r3(sch.at + timed[k].start / rate) : null))), source: "words" }; } const script = typeof take?.script === "string" && take.script.trim() ? take.script : String(entry?.narration?.script ?? ""); const sw = scriptWordsOf(script); const map = alignWords(words, sw); const before = []; let n = 0; for (const w of sw) { before.push(n); n += w.length + 1; } const secs = fin(sch.seconds) && sch.seconds > 0 ? sch.seconds : (n / 15); return { times: fillTimes(map.map((k) => (k >= 0 && n > 0 ? r3(sch.at + (before[k] / n) * secs) : null))), source: "estimate" }; } /** * Each caption's moment, one per fx (a word zoom's row is `{ i, kind }`): * `{ i, t, source: "at"|"words"|"estimate" }` or `{ i, error }`. * @param {Record} entry * @param {Record} [render] * @param {Record | null} [schedule] * @returns {Array<{ i: number, t?: number, source?: string, error?: string, kind?: string | null }>} */ export function captionTimes(entry, render = undefined, schedule = undefined) { const list = Array.isArray(entry?.fx) ? entry.fx : []; const cache = new Map(); return list.map((fx0, i) => { if (!isObj(fx0) || fx0.kind !== "caption") return { i, kind: fx0?.kind ?? null }; const fx = resolveCaption(fx0); if (fin(fx0.at)) return { i, t: r3(fx0.at), source: "at" }; const text = targetTextOf(entry, fx.target); const m = findMatch(text, fx.match, fx.occurrence); if (m.error) return { i, error: `${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") is not on the card` }; if (!cache.has(fx.target)) cache.set(fx.target, cardWordTimes(entry, render, fx.target, schedule)); const wt = cache.get(fx.target); const t = wt?.times?.[m.from]; if (!fin(t)) return { i, t: readingEstimate(m.from), source: "estimate" }; return { i, t: r3(t), source: wt.source }; }); } /** * One caption's span on the item's clock: in from t0 (its lead before the * word) to t1, held to t2 (`hold` after the word), out by t3. It WAITS for a * word zoom (`zooms`: their spans, word-zoom.mjs zoomSpan) it would be up * with, and ends by `end` (the item's last second, or a stack card's media * phase). `{ t0, t1, t2, t3, at, waited }` or `{ error }`. * @param {Record} fx0 * @param {number} t * @param {{ zooms?: Array>, end?: number }} [o] * @returns {{ t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, error?: undefined } | { error: string, t0?: undefined, t1?: undefined, t2?: undefined, t3?: undefined, at?: undefined, waited?: undefined }} */ export function captionSpan(fx0, t, { zooms = [], end = Infinity } = {}) { const fx = resolveCaption(fx0); let t0 = Math.max(0, t - fx.lead); let dur = Math.max(CAPTION_IN, t + fx.hold - t0); /** @type {number | null} */ let waited = null; const sorted = zooms.map((z, k) => ({ ...z, k })).filter((z) => fin(z.t0) && fin(z.t3)).sort((a, b) => a.t0 - b.t0); for (const z of sorted) { if (t0 < z.t3 && t0 + dur + CAPTION_OUT > z.t0) { t0 = z.t3; waited = z.i ?? z.k; } } if (t0 >= end - CAPTION_IN - 0.05) return { error: `starts at ${r3(t0)} s, at or after the item's ${r3(end)} s${waited !== null ? " (it waits for a word zoom)" : ""}` }; let t2 = t0 + dur; if (t2 + CAPTION_OUT > end) t2 = Math.max(t0 + CAPTION_IN, end - CAPTION_OUT); const t1 = Math.min(t2, t0 + CAPTION_IN); return { t0: r3(t0), t1: r3(t1), t2: r3(t2), t3: r3(Math.min(end, t2 + CAPTION_OUT)), at: r3(t), waited }; } const easeOut = (x) => 1 - (1 - Math.min(1, Math.max(0, x))) ** 3; /** The chip's opacity at item second `s` (0–1). */ export function captionOpacityAt(span, s) { if (!span || span.error || s < span.t0 || s >= span.t3) return 0; if (s < span.t1) return span.t1 > span.t0 ? easeOut((s - span.t0) / (span.t1 - span.t0)) : 1; if (s < span.t2) return 1; return 1 - (s - span.t2) / (span.t3 - span.t2); } /** How much of its slide in is left at `s`, 1 → 0 (0 once in). */ export function captionSlideAt(span, s) { if (!span || span.error || s >= span.t1) return 0; if (s < span.t0) return 1; return 1 - easeOut((s - span.t0) / Math.max(1e-6, span.t1 - span.t0)); } /** The direction a placed chip slides in from (toward the phrase): a unit `{ x, y }`. */ export const slideDir = (place) => (place === "above" ? { x: 0, y: -1 } : place === "side-right" ? { x: 1, y: 0 } : place === "side-left" ? { x: -1, y: 0 } : { x: 0, y: 1 }); /** Two captions of one post up at once: their indices, or null (one at a time). */ export function overlappingCaptions(spans) { const s = spans.filter((x) => x && fin(x.t0)).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; } // --------------------------------------------------------------------------- // WHERE. // --------------------------------------------------------------------------- /** @typedef {{ x: number, y: number, width: number, height: number }} Rect */ /** @param {Rect} a @param {Rect} b */ const area = (a, b) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); /** @param {Rect} r @param {Rect} b */ const inside = (r, b) => r.x >= b.x - 0.5 && r.y >= b.y - 0.5 && r.x + r.width <= b.x + b.width + 0.5 && r.y + r.height <= b.y + b.height + 0.5; /** @param {Rect} r @param {number} m */ const grow = (r, m) => ({ x: r.x - m, y: r.y - m, width: r.width + 2 * m, height: r.height + 2 * m }); /** Whether segment a→b crosses rect r (sampled every 3 px). @param {number[]} a @param {number[]} b @param {Rect} r */ function crosses(a, b, r) { const n = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 3)); for (let k = 0; k <= n; k += 1) { const x = a[0] + ((b[0] - a[0]) * k) / n; const y = a[1] + ((b[1] - a[1]) * k) / n; if (x > r.x && x < r.x + r.width && y > r.y && y < r.y + r.height) return true; } return false; } /** * THE LEADER: a thin line from the phrase's underline to the chip, through free * space only -- straight when nothing is in the way, else an elbow out along the * underline (in the gap under the phrase's line) to the text column's gutter, * along the gutter, then across to the chip. `[[x, y], …]` or null (none clear). * @param {Rect} word @param {Rect} chip @param {Rect[]} obstacles @param {Rect | null} column */ export function leaderPath(word, chip, obstacles, column) { const uy = word.y + word.height; const cy = chip.y + chip.height / 2; const cx = chip.x + chip.width / 2; // The chip's edge facing the phrase. const end = chip.y >= uy ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y] : chip.y + chip.height <= word.y ? [Math.min(chip.x + chip.width - 8, Math.max(chip.x + 8, word.x + word.width / 2)), chip.y + chip.height] : chip.x >= word.x + word.width ? [chip.x, cy] : [chip.x + chip.width, cy]; const clear = (pts) => pts.slice(1).every((p, k) => obstacles.every((r) => !crosses(pts[k], p, grow(r, 1)))); const start = [Math.min(Math.max(end[0], word.x + 4), word.x + word.width - 4), uy]; const straight = [start, end]; if (clear(straight)) return straight; const tries = []; for (const side of [1, -1]) { const gx = column ? (side > 0 ? column.x + column.width + 10 : column.x - 10) : side > 0 ? word.x + word.width + 10 : word.x - 10; const s = [side > 0 ? word.x + word.width : word.x, uy]; const ey = chip.y <= uy && chip.y + chip.height >= uy ? uy : cy; const ex = gx >= chip.x + chip.width ? chip.x + chip.width : gx <= chip.x ? chip.x : cx; const pts = [s, [gx, uy], [gx, ey], [ex, ey]]; // The first leg runs in the gap under the phrase's line (not judged); the rest through free space. if (clear(pts.slice(1))) tries.push({ pts, len: Math.abs(gx - s[0]) + Math.abs(ey - uy) + Math.abs(ex - gx) }); } tries.sort((a, b) => a.len - b.len); return tries[0]?.pts ?? null; } /** * THE PLACE (operator, 4 Nov: "a caption chip never covers ANY of the card's * words -- read, unread or already read"): the chip in FREE SPACE -- over no * `obstacles` (every word drawn, the card's header and counts, the attachments, * the clock), inside `bounds` (the footage box) -- as near the phrase as it can * be, with a leader to it through free space. `sizes`: the chip laid out at * each width it may take (`{ width, height, max }`, widest first); `place` * (below | above | side) a preference, `card` the card's box (a place on the * card beats one off it). Every candidate is a grid of spots around the phrase * and down the box; the cheapest clear one wins (distance, plus a cost off the * card, against the preferred side, and without a clear leader). `{ x, y, * width, height, max, place, covers, leader }` -- `covers` 0 unless no spot is * free (then the least-covering, which the build warns about). * @param {{ word: Rect, sizes: Array<{ width: number, height: number, max?: number }>, bounds: Rect, card?: Rect | null, column?: Rect | null, place?: string, obstacles?: Rect[], gap?: number, step?: number }} o */ export function placeCaption({ word, sizes, bounds, card = null, column = null, place = "below", obstacles = [], gap = 10, step = 6 }) { const cx = word.x + word.width / 2; const cy = word.y + word.height / 2; const blocked = obstacles.map((r) => grow(r, gap / 2)).concat([grow(word, gap / 2)]); let best = null; let least = null; for (const [si, sz] of sizes.entries()) { const xs = new Set(); for (const x of [cx - sz.width / 2, word.x, word.x + word.width - sz.width, card ? card.x + 14 : bounds.x, card ? card.x + card.width + gap : bounds.x, column ? column.x : bounds.x]) xs.add(Math.round(x)); for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += Math.max(24, step * 4)) xs.add(Math.round(x)); for (const x0 of xs) { const x = Math.min(bounds.x + bounds.width - sz.width, Math.max(bounds.x, x0)); for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step) { const r = { x, y, width: sz.width, height: sz.height }; const covers = blocked.filter((b) => area(r, b) > 0).length; const mx = r.x + r.width / 2; const my = r.y + r.height / 2; let cost = Math.hypot(mx - cx, my - cy) + si * 40; const onCard = card && inside(r, card); if (!onCard) cost += 160; const below = r.y >= word.y + word.height; const above = r.y + r.height <= word.y; const side = !below && !above; if ((place === "below" && !below) || (place === "above" && !above) || (place === "side" && !side)) cost += 60; if (covers) { if (!least || covers < least.covers || (covers === least.covers && cost < least.cost)) least = { ...r, max: sz.max, covers, cost }; continue; } if (best && cost >= best.cost) continue; best = { ...r, max: sz.max, covers: 0, cost }; } } } // Its leader, through free space; a spot with none is passed over for the next clear one when there is one. const pick = best ?? least; if (!pick) return null; let leader = leaderPath(word, pick, obstacles, column); let out = pick; if (!leader && best) { // Search again, the ones with a clear leader only (fewer: the cost already ranked them). const ranked = []; for (const sz of sizes) { for (let y = bounds.y; y + sz.height <= bounds.y + bounds.height; y += step * 2) { for (let x = bounds.x; x + sz.width <= bounds.x + bounds.width; x += step * 4) { const r = { x, y, width: sz.width, height: sz.height }; if (blocked.some((b) => area(r, b) > 0)) continue; ranked.push({ ...r, max: sz.max, covers: 0, cost: Math.hypot(x + sz.width / 2 - cx, y + sz.height / 2 - cy) + (card && inside(r, card) ? 0 : 160) }); } } ranked.sort((a, b) => a.cost - b.cost); for (const r of ranked.slice(0, 200)) { const l = leaderPath(word, r, obstacles, column); if (l) { out = r; leader = l; break; } } if (leader) break; } } const where = card && inside(out, card) ? "card" : "off-card"; const { cost, ...rest } = out; return { ...rest, x: Math.round(rest.x), y: Math.round(rest.y), place: where, leader: leader ? leader.map(([x, y]) => [Math.round(x), Math.round(y)]) : null }; } // --------------------------------------------------------------------------- // THE PLAN. // --------------------------------------------------------------------------- /** * Post item `entry`'s captions, resolved: `[{ i, scope, from, to, text, * place, t, source, span, avoid }]` -- `avoid` the target's word indices read * while it is up (the chip covers none of them). `zooms`: the item's word * zooms' spans (each a caption waits for); `end`: the last second a caption * may be up. Throws in the build's words when one cannot be up, or two are up at once. * @param {Record} entry * @param {Record} [render] * @param {{ zooms?: Array>, end?: number, schedule?: Record }} [o] * @returns {Array<{ i: number, scope: string, from: number, to: number, text: string, place: string, t: number, source: string, span: { t0: number, t1: number, t2: number, t3: number, at: number, waited: number | null, i: number }, avoid: number[] }>} */ export function captionPlan(entry, render = undefined, { zooms = [], end = Infinity, schedule = undefined } = {}) { const list = Array.isArray(entry?.fx) ? entry.fx : []; if (!list.some((f) => f?.kind === "caption")) return []; const times = captionTimes(entry, render, schedule); const bad = times.filter((t) => t.error); if (bad.length) throw new Error(bad.map((t) => t.error).join("; ")); const wt = new Map(); /** @type {ReturnType} */ const out = []; for (const [i, fx0] of list.entries()) { if (fx0?.kind !== "caption") continue; const fx = resolveCaption(fx0); const m = findMatch(targetTextOf(entry, fx.target), fx.match, fx.occurrence); const span = captionSpan(fx0, times[i].t, { zooms, end }); if (span.error !== undefined) throw new Error(`${entry?.id ?? "?"}: caption ${i + 1} ("${fx.match}") ${span.error} (move its at, or shorten the zoom)`); if (!wt.has(fx.target)) wt.set(fx.target, cardWordTimes(entry, render, fx.target, schedule)); const read = wt.get(fx.target)?.times ?? []; const avoid = read.map((s, k) => (fin(s) && s >= span.t0 - 0.25 && s <= span.t3 + 0.25 && (k < m.from || k > m.to) ? k : -1)).filter((k) => k >= 0); out.push({ i, scope: targetScope(fx.target), from: m.from, to: m.to, text: fx.text, place: fx.place, t: Number(times[i].t), source: String(times[i].source), span: { ...span, i }, avoid }); } const clash = overlappingCaptions(out.map((c) => c.span)); if (clash) throw new Error(`${entry?.id ?? "?"}: captions ${clash[0] + 1} and ${clash[1] + 1} are up at once (one at a time: move one's at, or shorten its hold)`); return out; } // --------------------------------------------------------------------------- // THE LOOK. // --------------------------------------------------------------------------- /** The chip's inner HTML: the text, its part before " — " bold. */ export function captionInnerHtml(text) { const t = String(text ?? ""); const cut = t.indexOf(" — "); return cut > 0 ? `${esc(t.slice(0, cut))} — ${esc(t.slice(cut + 3))}` : esc(t); } /** * The chips' CSS, for a page `height` px tall (sizes at 1080), in the card's * palette (`palette`, the deck's) and faces (the card's @font-face PostSans / * PostSansBold, then CAPTION_FONT_STACK). */ /** @param {{ height?: number, palette?: Record }} [o] */ export function captionCss({ height = 1080, palette = {} } = {}) { const k = height / 1080; const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; const panel = mixHex(pal.bg, pal.accent, 0.16); const n = Math.round(16 * k); return ` [data-post-fx-captions] { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 60; } .pcap { position: absolute; left: 0; top: 0; max-width: ${Math.round(620 * k)}px; padding: ${Math.round(10 * k)}px ${Math.round(18 * k)}px ${Math.round(11 * k)}px; background: ${panel}; color: ${pal.fg}; border: ${Math.max(1, Math.round(2 * k))}px solid ${pal.accent}; border-radius: ${Math.round(12 * k)}px; box-shadow: 0 ${Math.round(8 * k)}px ${Math.round(26 * k)}px ${rgbaOf("#000000", 0.5)}; font-family: 'PostSans', ${CAPTION_FONT_STACK}; font-size: ${Math.round(27 * k)}px; line-height: 1.28; font-synthesis: none; opacity: 0; will-change: transform, opacity; overflow-wrap: anywhere; } .pcap b { font-family: 'PostSansBold', ${CAPTION_FONT_STACK}; font-weight: 700; color: ${pal.fg}; } .pcap .pcap-rest { color: ${mixHex(pal.fg, pal.muted, 0.25)}; } .pcap::before { content: ""; position: absolute; width: ${n}px; height: ${n}px; background: ${panel}; border: inherit; border-width: ${Math.max(1, Math.round(2 * k))}px; border-radius: ${Math.round(2 * k)}px; transform: rotate(45deg); } .pcap[data-place="below"]::before { top: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-right: none; border-bottom: none; } .pcap[data-place="above"]::before { bottom: -${Math.round(n / 2 + 1)}px; left: calc(var(--notch) - ${n / 2}px); border-left: none; border-top: none; } .pcap[data-place="side-right"]::before { left: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-right: none; border-top: none; } .pcap[data-place="side-left"]::before { right: -${Math.round(n / 2 + 1)}px; top: calc(var(--notch) - ${n / 2}px); border-left: none; border-bottom: none; } .pcap[data-place="free"]::before { display: none; } .pcap-leader-line { stroke: ${pal.accent}; } .pcap-leader-dot { fill: ${pal.accent}; } .pcap-mark { position: absolute; height: ${Math.max(2, Math.round(3 * k))}px; background: ${pal.accent}; border-radius: ${Math.max(1, Math.round(2 * k))}px; opacity: 0; } `; } // --------------------------------------------------------------------------- // THE DOM (self-contained: passed to page.evaluate by the build, called by Play). // --------------------------------------------------------------------------- /** The widths a chip is laid out at (px at 1080): the widest first; a narrower one fits a smaller space. */ export const CAPTION_WIDTHS = Object.freeze([620, 480, 380, 300]); /** * Mount the chips over the card page: `{ css, chips: [{ i, html }], k }`, each * laid out unplaced and hidden at every width of CAPTION_WIDTHS (× `k`). * Returns each one's sizes `[{ i, sizes: [{ width, height, max }] }]`. * @param {{ css?: string, chips?: Array<{ i: number, html: string }>, k?: number, widths?: number[] } | null} arg * @param {Document} [doc] * @returns {Array<{ i: number, sizes: Array<{ width: number, height: number, max: number }> }>} */ export function mountCaptions(arg, doc = document) { doc.querySelectorAll("[data-post-fx-captions], style[data-post-fx-captions-css]").forEach((el) => el.remove()); const chips = (arg && arg.chips) || []; if (!chips.length) return []; const style = doc.createElement("style"); style.setAttribute("data-post-fx-captions-css", ""); style.textContent = arg.css || ""; doc.head.appendChild(style); const layer = doc.createElement("div"); layer.setAttribute("data-post-fx-captions", ""); doc.body.appendChild(layer); const k = (arg && arg.k) || 1; const widths = (arg && arg.widths) || [620, 480, 380, 300]; return chips.map((c) => { const el = doc.createElement("div"); el.className = "pcap"; el.setAttribute("data-post-fx-caption", String(c.i)); el.innerHTML = c.html; layer.appendChild(el); const sizes = []; for (const w of widths) { const max = Math.round(w * k); el.style.maxWidth = `${max}px`; const b = el.getBoundingClientRect(); const s = { width: Math.ceil(b.width), height: Math.ceil(b.height), max }; if (!sizes.some((x) => x.width === s.width && x.height === s.height)) sizes.push(s); } el.style.maxWidth = ""; return { i: c.i, sizes }; }); } /** * The phrase's geometry as the card is drawn now: `{ scope, from, to, avoid: * [indices] }` → `{ card, word, lines, avoid, obstacles, column }` -- px boxes: * `lines` the phrase's box per line (its underline), `obstacles` everything * drawn a chip may not cover (every word in view, the card's header, its * counts, a quote's or a picture's frame -- the phrase itself apart), `column` * the phrase's text column; or `{ error }` when a word is not drawn or is cut * off the card. * @param {{ scope: string, from: number, to: number, avoid?: number[] }} arg * @param {Document} [doc] * @returns {{ error: string } | { error?: undefined, card: Rect, word: Rect, lines: Rect[], avoid: Rect[], obstacles: Rect[], column: Rect | null }} */ export function measureCaptionWords(arg, doc = document) { const rect = (el) => { const b = el.getBoundingClientRect(); return { x: b.left, y: b.top, width: b.width, height: b.height }; }; const card = doc.querySelector("[data-post-card]"); if (!card) return { error: "the card is not drawn" }; /** @type {Rect[]} */ const lines = []; let column = null; for (let i = arg.from; i <= arg.to; i += 1) { const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); if (!el) return { error: `word ${i} is not on the card` }; const clip = el.closest(".words, .ptext, .qtext, .twords, .tt"); if (clip && !column) column = rect(clip); const cb = (clip || card).getBoundingClientRect(); for (const r of Array.from(el.getClientRects())) { if (r.width === 0) continue; if (r.bottom > cb.bottom + 1 || r.top < cb.top - 1) return { error: "cut off the card (the text is longer than the card shows)" }; const same = lines.find((l) => Math.abs(l.y - r.top) < r.height / 2); if (same) { const x1 = Math.max(same.x + same.width, r.right); same.x = Math.min(same.x, r.left); same.width = x1 - same.x; same.height = Math.max(same.height, r.height); } else lines.push({ x: r.left, y: r.top, width: r.width, height: r.height }); } } if (!lines.length) return { error: "the words are not drawn" }; const x0 = Math.min(...lines.map((l) => l.x)); const y0 = Math.min(...lines.map((l) => l.y)); const x1 = Math.max(...lines.map((l) => l.x + l.width)); const y1 = Math.max(...lines.map((l) => l.y + l.height)); /** @type {Rect[]} */ const avoid = []; for (const i of arg.avoid || []) { const el = doc.querySelector(`[data-w="${arg.scope}:${i}"]`); if (el) for (const r of Array.from(el.getClientRects())) if (r.width > 0) avoid.push({ x: r.left, y: r.top, width: r.width, height: r.height }); } // Everything drawn a chip may not cover: each word in view (inside what clips it, not faded out), then the // card's furniture -- names, dates, the platform mark, avatars, counts, labels, a context shot or quote frame. /** @type {Rect[]} */ const obstacles = []; const mine = new Set(Array.from({ length: arg.to - arg.from + 1 }, (_, k) => `${arg.scope}:${arg.from + k}`)); const view = doc.defaultView; const shown = (el) => { for (let n = el; n && n !== doc.body; n = n.parentElement) { const st = view ? view.getComputedStyle(n) : null; if (st && (st.visibility === "hidden" || st.display === "none" || Number(st.opacity) < 0.05)) return false; } return true; }; for (const el of Array.from(doc.querySelectorAll("[data-w]"))) { if (mine.has(el.getAttribute("data-w") || "")) continue; const clip = el.closest(".words, .ptext, .qtext, .twords, .tt, [data-thread-tile]") || card; const cb = clip.getBoundingClientRect(); for (const r of Array.from(el.getClientRects())) { if (r.width <= 0 || r.bottom <= cb.top || r.top >= cb.bottom) continue; obstacles.push({ x: r.left, y: Math.max(r.top, cb.top), width: r.width, height: Math.min(r.bottom, cb.bottom) - Math.max(r.top, cb.top) }); } } for (const el of Array.from(card.querySelectorAll(".avatar, .name, .handle, .date, .pdate, .mark, .plabel, .repost, .replying, .counts > *, .pshot img, .sline, .strip"))) { if (!shown(el)) continue; for (const r of Array.from(el.getClientRects())) if (r.width > 0 && r.height > 0) obstacles.push({ x: r.left, y: r.top, width: r.width, height: r.height }); } return { card: rect(card), word: { x: x0, y: y0, width: x1 - x0, height: y1 - y0 }, lines, avoid, obstacles, column }; } /** * Set the chips: `[{ i, x, y, max, opacity, dx, dy, marks, mark, leader }]` * (`marks`: the underline's boxes under the phrase, `leader` its line to the * chip, `mark` their opacity); a chip not listed is hidden. `only`: "chip" | * "mark" draws just that layer (the build shoots them apart), absent both. * @param {{ list?: Array>, only?: string, stroke?: number } | null} arg * @param {Document} [doc] */ export function setCaptionState(arg, doc = document) { const list = (arg && arg.list) || []; const only = arg && arg.only; const layer = doc.querySelector("[data-post-fx-captions]"); if (!layer) return; layer.querySelectorAll(".pcap-mark, .pcap-leader").forEach((el) => el.remove()); for (const el of Array.from(layer.querySelectorAll(".pcap"))) { const c = list.find((x) => String(x.i) === el.getAttribute("data-post-fx-caption")); if (!c || only === "mark") { el.style.opacity = "0"; continue; } el.setAttribute("data-place", "free"); if (c.max) el.style.maxWidth = `${c.max}px`; el.style.transform = `translate(${Math.round(c.x + (c.dx || 0))}px, ${Math.round(c.y + (c.dy || 0))}px)`; el.style.opacity = String(c.opacity); } if (only === "chip") return; const sw = (arg && arg.stroke) || 2; for (const c of list) { for (const l of c.marks || []) { const m = doc.createElement("div"); m.className = "pcap-mark"; m.setAttribute("data-post-fx-caption-mark", String(c.i)); const h = Math.max(2, Math.round(l.height * 0.07)); m.style.left = `${Math.round(l.x)}px`; m.style.top = `${Math.round(l.y + l.height - h * 0.4)}px`; m.style.width = `${Math.round(l.width)}px`; m.style.opacity = String(c.mark ?? c.opacity); layer.appendChild(m); } if (Array.isArray(c.leader) && c.leader.length > 1) { const ns = "http://www.w3.org/2000/svg"; const svg = doc.createElementNS(ns, "svg"); svg.setAttribute("class", "pcap-leader"); svg.setAttribute("data-post-fx-caption-leader", String(c.i)); svg.setAttribute("width", "100%"); svg.setAttribute("height", "100%"); svg.style.position = "absolute"; svg.style.left = "0"; svg.style.top = "0"; svg.style.overflow = "visible"; svg.style.opacity = String(c.mark ?? c.opacity); const pl = doc.createElementNS(ns, "polyline"); pl.setAttribute("points", c.leader.map((p) => `${p[0] + (c.ldx || 0)},${p[1] + (c.ldy || 0)}`).join(" ")); pl.setAttribute("fill", "none"); pl.setAttribute("stroke-width", String(sw)); pl.setAttribute("stroke-linejoin", "round"); pl.setAttribute("class", "pcap-leader-line"); svg.appendChild(pl); const last = c.leader[c.leader.length - 1]; const dot = doc.createElementNS(ns, "circle"); dot.setAttribute("cx", String(last[0])); dot.setAttribute("cy", String(last[1])); dot.setAttribute("r", String(sw * 1.6)); dot.setAttribute("class", "pcap-leader-dot"); svg.appendChild(dot); layer.appendChild(svg); } } } /** * The card page's palette, read off its drawn styles (Play has the page, not the * deck's render): `{ bg, fg, muted, accent }` as #rrggbb. * @param {Document} [doc] * @returns {Record} */ export function paletteOfDoc(doc = document) { const hex = (c) => { const m = /rgba?\(([^)]+)\)/.exec(String(c || "")); if (!m) return null; const [r, g, b] = m[1].split(",").map((v) => Math.round(Number(v))); return `#${[r, g, b].map((v) => Math.max(0, Math.min(255, v || 0)).toString(16).padStart(2, "0")).join("")}`; }; const view = doc.defaultView; if (!view || !doc.body) return {}; const probe = (cls) => { const el = doc.createElement("span"); el.className = cls; doc.body.appendChild(el); const c = view.getComputedStyle(el).color; el.remove(); return hex(c); }; const st = view.getComputedStyle(doc.body); const out = { bg: hex(st.backgroundColor), fg: hex(st.color), accent: probe("mention"), muted: probe("pdate") }; return Object.fromEntries(Object.entries(out).filter(([, v]) => v)); }