// A POST ITEM's READ-FOLLOW (umtool/docs/report-video.md, "Read-follow"; operator, // 3 Nov: "'I'm someone who has never watched Ember' goes on beyond the text but // the text doesn't scroll? That needs to be an effect, something like highlight // the current paragraph and panning down as needed" -- and "a subtle effect of // highlighting the block currently being read by making it brighter may be // good"): the card's words laid out in BLOCKS that match the read's parts, the // block being read drawn at full strength and the others dimmed a little, and a // card whose words are taller than their box PANNED so the block being read // stays in view -- where it used to shrink its words to 18 px and cut the rest. // // render.postNarration.follow = { on?: true, dim?: 0.65, ease?: 0.25 } the cut's // entry.follow = false | { on?, dim?, ease? } one post's (false: off) // // THE BLOCKS (followBlocks, from the entry alone): the read's parts -- a // narrated take's `parts` (its paragraphs, or a long paragraph's <=60-word // sentence runs; `para` = piece*100 + paragraph when a take reads the post it // answers first), else the script's parts, else (un-narrated) the card's own // paragraphs and sentence runs -- each matched BY ITS WORDS to the run of the // card's words it reads, in whichever of the card's texts it is (a parent's, // the post's, the quoted post's). The script is the post as a voice says it // ("this slash that", a shout lower-cased), so the match is by normalized // words, in order (a windowed longest common subsequence), never by index. // Words no part reads join the block before them up to a paragraph break; a // whole paragraph no part reads is a block that is never lit. // // THE SCHEDULE (followSchedule, the plan's `follow`): each block's start on the // item's clock -- a part's start in the take at the read's rate (lead + start ÷ // rate, post-narration.mjs partStartOnItem); without parts, the read's seconds // shared by words; un-narrated, the reading rule's seconds (post-item.mjs // readSeconds, contextReadSeconds) -- and the read's end, after which every // block is back at full strength. // // THE PAN (followPath, from the card page's geometry, measureFollow): the post's // words in a window of the card (`.words`); when a block to be read is not in // view, the words pan (eased, FOLLOW_PAN.seconds, starting FOLLOW_PAN.lead // before its read) so it sits a margin below the window's top; a block taller // than the window pans on through it as it is read. Short posts never move. // A fading edge says there is more text above or below. // // The build and Play draw the same thing: the card page carries the blocks // (`data-post-block`), its flow (`data-post-flow`) and fades; followStateAt(t) // is a pure function of the item's second (seek-safe), and applyFollowState // sets it on the page -- in the build per frame before a screenshot // (post-render.mjs), in Play per tick (PostItemPlayer). import { cardText, contextReadSeconds, contextText, linksOf, parentsOf, readEditOf, readSeconds, shownDraftOf } from "./post-item.mjs"; import { isNarrated, narrationSchedule, partStartOnItem, pickedTake, scriptParts } from "./post-narration.mjs"; import { cardTokens, easeOf, normWord, scriptWordsOf } from "./word-zoom.mjs"; import { partRoles, threadGeoAt, threadKnobs, threadLayout, threadSchedule, threadStateAt } from "./post-thread.mjs"; import { sceneLayout, sceneRows, sceneSchedule } from "./post-media-scene.mjs"; import { linkVisits, visitRows, visitStateAt } from "./post-link-visit.mjs"; import { mapStateAt } from "./post-branch-map.mjs"; import { isScreenScope, parseScreenRole, screenScope } from "./post-screens.mjs"; export const FOLLOW_DEFAULTS = Object.freeze({ on: true, dim: 0.65, ease: 0.25 }); export const FOLLOW_LIMITS = Object.freeze({ dim: [0.2, 1], ease: [0, 2] }); /** The pan: it starts `lead` s before the block's read and takes `seconds`, eased; the block sits `margin` (of the window) below its top. */ export const FOLLOW_PAN = Object.freeze({ lead: 0.4, seconds: 0.7, margin: 0.1 }); /** While follow is on, the words never shrink below this (px of a 1080-high frame) to fit: the card pans instead. */ export const FOLLOW_MIN_SIZE = 28; /** A block's words are matched if at least this share of a part's words are found. */ const MATCH_MIN = 0.35; const KEYS = new Set(["on", "dim", "ease"]); const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const r3 = (v) => Math.round(v * 1000) / 1000; const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)); const str = (v) => (typeof v === "string" ? v : ""); // --------------------------------------------------------------------------- // The knobs. // --------------------------------------------------------------------------- /** One follow knob's errors (`where`: its path in the manifest). `false` is off. */ export function followKnobErrors(v, where) { if (v === undefined || v === null || v === false) return []; if (!isObj(v)) return [`${where} must be false (off) or { on?, dim?, ease? }`]; const errors = []; for (const k of Object.keys(v)) if (!KEYS.has(k)) errors.push(`${where}.${k} is not a follow knob (on, dim, ease)`); if (v.on !== undefined && typeof v.on !== "boolean") errors.push(`${where}.on must be true or false`); for (const k of ["dim", "ease"]) { if (v[k] !== undefined && !(fin(v[k]) && v[k] >= FOLLOW_LIMITS[k][0] && v[k] <= FOLLOW_LIMITS[k][1])) { errors.push(`${where}.${k} must be ${FOLLOW_LIMITS[k][0]}–${FOLLOW_LIMITS[k][1]}${k === "dim" ? " (the other blocks' opacity)" : " seconds"}`); } } return errors; } /** A post item's `follow` errors (validatePostItem). */ export const validatePostFollow = (e) => followKnobErrors(e?.follow, `timeline ${e?.id ?? "?"}.follow`); const pick = (o) => (isObj(o) ? Object.fromEntries(Object.entries(o).filter(([k, v]) => KEYS.has(k) && v !== undefined && v !== null)) : {}); /** * One post's follow knobs: its own, else the cut's (`render.postNarration.follow`), else the defaults. * @param {Record | null | undefined} entry * @param {Record} [render] * @returns {{ on: boolean, dim: number, ease: number }} */ export function followKnobs(entry, render = undefined) { const r = isObj(render?.postNarration) ? render.postNarration.follow : undefined; const e = entry?.follow; return { ...FOLLOW_DEFAULTS, ...(r === false ? { on: false } : pick(r)), ...(e === false ? { on: false } : pick(e)), }; } // --------------------------------------------------------------------------- // THE BLOCKS: the read's parts matched to the card's words. // --------------------------------------------------------------------------- /** The card's texts in the order they are drawn: the posts it answers (oldest first), the post, the quoted post. */ export function cardScopes(entry) { const out = []; const parents = parentsOf(entry); for (let i = parents.length - 1; i >= 0; i -= 1) { const t = contextText(parents[i]); if (t.trim()) out.push({ scope: `parent:${i}`, text: t, ref: parents[i] }); } out.push({ scope: "post", text: cardText(entry), ref: null }); if (isObj(entry?.quoted) && contextText(entry.quoted).trim()) out.push({ scope: "quoted", text: contextText(entry.quoted), ref: entry.quoted }); // The posts its words link to (post-thread.mjs: a link visit; read in place when the take reads them). linksOf(entry).forEach((l, i) => { if (contextText(l).trim()) out.push({ scope: `linked:${i}`, text: contextText(l), ref: l }); }); return out; } /** A word as matching sees it: normalized, apostrophes gone. */ const keyOf = (w) => normWord(w).replace(/'/g, ""); /** A card text's match keys: `[{ key, ci }]` (ci its card word), a "this/that" word split at its slashes. */ function cardKeys(text) { const out = []; for (const t of cardTokens(text)) { if (t.tok === undefined) continue; for (const sub of t.tok.split("/")) { const key = keyOf(sub); if (key) out.push({ key, ci: t.i }); } } return out; } /** A part's words as keys ("slash" is the voice's reading of a "/": the card has none). */ const partKeys = (text) => scriptWordsOf(text).map(keyOf).filter((k) => k && k !== "slash"); /** The paragraph starts of a card text: the card word indices that begin a paragraph (after a blank line). */ function paragraphStarts(text) { const starts = new Set([0]); let seenWord = false; let next = 0; for (const t of cardTokens(text)) { if (t.tok !== undefined) { seenWord = true; next = t.i + 1; } else if (seenWord && /\n\s*\n/.test(t.space)) starts.add(next); } return starts; } /** * A FITTING ALIGNMENT of `a` (a part's keys) inside `b` (a card text's keys, * from `lo` to `hi`): all of `a`, a compact run of `b` -- a word in common * +2, a word skipped on either side -1, free before and after the run (so * a common word far away never stretches the span). Returns the matched b * indices, in order. */ function fitMatch(a, b, lo, hi) { const n = a.length; const m = hi - lo; if (!n || m <= 0) return []; const W = m + 1; const S = new Int32Array((n + 1) * W); for (let i = 1; i <= n; i += 1) S[i * W] = -i; for (let i = 1; i <= n; i += 1) { for (let j = 1; j <= m; j += 1) { const diag = S[(i - 1) * W + j - 1] + (a[i - 1] === b[lo + j - 1].key ? 2 : -1); S[i * W + j] = Math.max(diag, S[(i - 1) * W + j] - 1, S[i * W + j - 1] - 1); } } let j = 0; for (let x = 1; x <= m; x += 1) if (S[n * W + x] > S[n * W + j]) j = x; const hits = []; let i = n; while (i > 0 && j > 0) { const here = S[i * W + j]; const eq = a[i - 1] === b[lo + j - 1].key; if (here === S[(i - 1) * W + j - 1] + (eq ? 2 : -1)) { if (eq) hits.push(lo + j - 1); i -= 1; j -= 1; } else if (here === S[(i - 1) * W + j] - 1) i -= 1; else j -= 1; } return hits.reverse(); } /** The parts a block map is made from: `[{ text, scope? }]` -- the take's, the script's, or (un-narrated) the card's own. */ export function followParts(entry) { if (isNarrated(entry)) { const t = pickedTake(entry); // HIS WORDS EDITED FOR READING (post-item.mjs readEditOf: the playing take's stamp; ruling 3): the card follows // the SHOWN text -- his post's blocks are made from his words as drafted, never from the edited ones, so no edit // to what is said moves, dims for good or hides a drawn word. The edited read only times them. const forReading = readEditOf(entry, t) === "reading"; if (Array.isArray(t?.parts) && t.parts.length) { // Each part's ROLE (post-thread.mjs): the text it reads -- a context post, his words, an attachment's. const roles = partRoles(entry); const parts = t.parts.map((p, k) => ({ text: str(p.text), start: fin(p.start) ? p.start : null, ...(roles[k]?.role ? { scope: roles[k].role } : {}) })); return { source: "take", parts: forReading ? shownPostParts(entry, parts, t.parts) : parts }; } if (forReading) return { source: "script", parts: scriptParts(shownDraftOf(entry)).map((p) => ({ text: p.text, scope: "post" })) }; const script = str(t?.script).trim() ? t.script : str(entry?.narration?.script); const roles = partRoles(entry); return { source: "script", parts: scriptParts(script).map((p, k) => ({ text: p.text, ...(roles[k]?.role ? { scope: roles[k].role } : {}) })) }; } const parts = []; for (const sc of cardScopes(entry)) for (const p of scriptParts(sc.text)) parts.push({ text: p.text, scope: sc.scope }); return { source: "card", parts }; } /** * His post's parts of a take (scope "post", one run of them) REPLACED by his words as drafted (the shown text's * paragraphs), each `shown: true` and timed from the read: one for one when the read kept as many parts, else shared * by words over the span his parts were read in -- every block read in turn, none left unread by an edit. */ function shownPostParts(entry, parts, takeParts) { const at = parts.map((p, i) => (p.scope === "post" ? i : -1)).filter((i) => i >= 0); if (!at.length || at.some((i, j) => j && i !== at[j - 1] + 1)) return parts; // Each shown part keeps the take's part it stands for (`at`: one for one, else his first part for the first, his // last for the rest) -- the thread schedule finds a piece's start by the take's parts (review 1, finding 1). const shown = scriptParts(shownDraftOf(entry)).map((q, j) => ({ text: q.text, scope: "post", shown: true, at: at[Math.min(j, at.length - 1)] })); if (!shown.length) return parts; const own = at.map((i) => parts[i]); let timed; if (shown.length === own.length) timed = shown.map((q, j) => ({ ...q, start: own[j].start })); else { const last = takeParts[at[at.length - 1]]; const t0 = own[0].start; const t1 = fin(t0) && fin(last?.start) && fin(last?.seconds) ? last.start + last.seconds : null; const total = shown.reduce((n, q) => n + Math.max(1, wordsIn(q.text)), 0); let w = 0; timed = shown.map((q) => { const start = fin(t0) && fin(t1) ? Math.round((t0 + ((t1 - t0) * w) / total) * 1000) / 1000 : null; w += Math.max(1, wordsIn(q.text)); return { ...q, start }; }); } // Every other part keeps the take's part it is (`at`): the schedule times them by it. return [...parts.slice(0, at[0]).map((p, j) => ({ ...p, at: j })), ...timed, ...parts.slice(at[at.length - 1] + 1).map((p, j) => ({ ...p, at: at[at.length - 1] + 1 + j }))]; } /** * THE BLOCK MAP, pure, from the entry alone: `{ source, blocks: [{ k, scope, * from, to, part }], parts }` -- each block a run of one card text's words * (card word indices, inclusive), `part` the index of the part that reads it * (null: a paragraph no part reads). Blocks are in the card's order within a * scope; `k` is their id on the page (`data-post-block`). */ export function followBlocks(entry) { const { source, parts } = followParts(entry); const scopes = cardScopes(entry).map((sc) => ({ ...sc, keys: cardKeys(sc.text), starts: paragraphStarts(sc.text), words: cardTokens(sc.text).filter((t) => t.tok !== undefined).length })); const byScope = new Map(scopes.map((sc) => [sc.scope, { sc, spans: [], cursor: 0 }])); // A part read off an attachment (a screenshot's words, post-thread.mjs): a block with no words on the card. const media = []; // A SCREEN's line (post-screens.mjs): a block of its own -- the line, drawn by the screen's tile -- named by its role, // never matched by words; a line read in several parts is one block (from its first part). const screenLines = new Set(); parts.forEach((p, pi) => { const sl = typeof p.scope === "string" ? parseScreenRole(p.scope) : null; if (sl) { if (!screenLines.has(p.scope)) media.push({ scope: screenScope(sl.id), line: sl.n, from: null, to: null, part: pi }); screenLines.add(p.scope); return; } if (typeof p.scope === "string" && p.scope.startsWith("media:")) { media.push({ scope: p.scope, from: null, to: null, part: pi }); return; } const keys = partKeys(p.text); if (!keys.length) return; // A part read off a LINKED post's picture (its `transcript`, post-thread.mjs: the picture scrolls as it is read): // a block with no card words, its words counted for the scroll. if (typeof p.scope === "string" && p.scope.startsWith("linked:")) { const l = linksOf(entry)[Number(p.scope.slice(7))]; const onCard = new Set(partKeys(contextText(l))); const inPic = new Set(partKeys(l?.transcript ?? "")); const share = (set) => keys.filter((x) => set.has(x)).length / keys.length; if (inPic.size && share(inPic) > share(onCard)) { media.push({ scope: p.scope, from: null, to: null, part: pi, pic: true, words: keys.length }); return; } } // Which of the card's texts it reads: its own scope (the card's parts), else the one most of its words are in. let target = p.scope ? byScope.get(p.scope) : null; if (!target) { let best = 0; for (const s of byScope.values()) { const set = new Set(s.sc.keys.map((x) => x.key)); const share = keys.filter((k) => set.has(k)).length / keys.length; if (share > best + 1e-9 || (Math.abs(share - best) < 1e-9 && s.sc.scope === "post" && share > 0)) { best = share; target = s; } } if (best < 0.5) target = null; } if (!target) return; const ck = target.sc.keys; // In order: a window from where the last part ended, then (a part read out of order) the whole text. let hits = fitMatch(keys, ck, target.cursor, Math.min(ck.length, target.cursor + 2 * keys.length + 40)); if (hits.length < Math.max(1, Math.ceil(MATCH_MIN * keys.length))) hits = fitMatch(keys, ck, 0, ck.length); if (hits.length < Math.max(1, Math.ceil(MATCH_MIN * keys.length))) return; target.cursor = hits[hits.length - 1] + 1; target.spans.push({ part: pi, from: ck[hits[0]].ci, to: ck[hits[hits.length - 1]].ci }); }); const blocks = []; for (const { sc, spans } of byScope.values()) { if (!sc.words) continue; // Overlaps (a part re-read) are clipped to what the earlier part did not cover. const sorted = [...spans].sort((a, b) => a.from - b.from || a.part - b.part); const clean = []; for (const s of sorted) { const last = clean[clean.length - 1]; const from = last ? Math.max(s.from, last.to + 1) : s.from; if (from <= s.to) clean.push({ ...s, from }); } const segs = []; const gap = (from, to, prev, nextSpan) => { if (from > to) return; // The gap split at its paragraph starts: its first piece joins the block before (no break between), // its last piece the block after; a piece between breaks is a paragraph no part reads. const cuts = [from]; for (let i = from + 1; i <= to; i += 1) if (sc.starts.has(i)) cuts.push(i); const pieces = cuts.map((c, j) => ({ from: c, to: j + 1 < cuts.length ? cuts[j + 1] - 1 : to })); pieces.forEach((pc, j) => { if (j === 0 && prev && !sc.starts.has(pc.from)) prev.to = pc.to; else if (j === pieces.length - 1 && nextSpan && !sc.starts.has(to + 1)) nextSpan.from = pc.from; else segs.push({ scope: sc.scope, from: pc.from, to: pc.to, part: null }); }); }; let pos = 0; let prev = null; for (const s of clean) { const span = { scope: sc.scope, from: s.from, to: s.to, part: s.part }; gap(pos, s.from - 1, prev, span); segs.push(span); prev = span; pos = s.to + 1; } gap(pos, sc.words - 1, prev, null); segs.sort((a, b) => a.from - b.from); blocks.push(...segs); } blocks.push(...media); // A block read by a part that stands for a take's part (shownPostParts): that take part's index (`takePart`) -- // the thread schedule and the lint name a piece by the take's parts. const takeAt = (b) => (b.part !== null && Number.isInteger(parts[b.part]?.at) ? { takePart: parts[b.part].at } : {}); return { source, parts: parts.length, blocks: blocks.map((b, k) => ({ k, ...b, ...takeAt(b) })) }; } /** A block map's runs for one scope, as wordsHtml wraps them: `[{ from, to, k }]`. */ export const scopeBlocks = (map, scope) => (map?.blocks ?? []).filter((b) => b.scope === scope).map((b) => ({ from: b.from, to: b.to, k: b.k })); // --------------------------------------------------------------------------- // THE SCHEDULE: each block's start on the item's clock. // --------------------------------------------------------------------------- const wordsIn = (t) => scriptWordsOf(t).length; /** * THE FOLLOW SCHEDULE, pure (the plan's `follow`): `{ dim, ease, readEnd, * blocks: [{ k, scope, from, to, part, start, end }] }` -- `start` the * block's read on the item's clock (null: never read), `end` the next * block's start (the read's end for the last). Null when follow is off. * `o.total`/`o.hold`: the item's length, its hold (an un-narrated post with a * hold longer than its reading spreads the reading over it, less a second). * * @param {Record} entry * @param {Record} [render] * `o.mediaScene` (post-media-scene.mjs mediaSceneOf): the item's media scene -- * the scene's earlier messages drawn above the card as tiles of the column. * `o.scene` (post-conversation.mjs planContext): the posts its conversation's * run left on screen. A conversation scene WINS the card: with one, the media * scene is not drawn (it keeps only the attachment, sceneEntry). * * @param {{ hold?: number | null, narration?: Record | null, prev?: Record | null, scene?: Record | null, mediaScene?: Record | null, join?: { seconds: number } | null }} [o] */ export function followSchedule(entry, render = undefined, { hold = null, narration = undefined, prev = null, scene = null, mediaScene = null, join = null, beats = [] } = {}) { const k = followKnobs(entry, render); if (!k.on) return null; const map = followBlocks(entry); const { parts } = followParts(entry); const starts = new Array(parts.length).fill(null); let readEnd; if (isNarrated(entry)) { const sch = narration ?? narrationSchedule(entry, render); readEnd = r3(sch.at + sch.seconds); const take = pickedTake(entry); const timed = map.source === "take" && parts.every((p) => fin(p.start)); // A part of his words as drafted (shownPostParts) is timed by its own start; every other by the take's part. if (timed) parts.forEach((p, i) => (starts[i] = partStartOnItem(sch, p.shown ? p : take.parts[p.at ?? i]))); else { // No parts: the read's seconds shared by words. const total = parts.reduce((n, p) => n + wordsIn(p.text), 0) || 1; let w = 0; parts.forEach((p, i) => { starts[i] = r3(sch.at + (sch.seconds * w) / total); w += wordsIn(p.text); }); } } else { // The reading rule: each context post its context seconds, the post its reading seconds, shared by words. const spans = new Map(); for (const sc of cardScopes(entry)) spans.set(sc.scope, sc.ref ? contextReadSeconds(sc.ref) : readSeconds(entry)); const reading = [...spans.values()].reduce((n, v) => n + v, 0); const f = fin(hold) && hold > reading + 1 ? (hold - 1) / reading : 1; // THE JOIN (post-join.mjs) comes first: the reading after it. let t = join && fin(join.seconds) ? join.seconds : 0; for (const sc of cardScopes(entry)) { const mine = parts.map((p, i) => ({ p, i })).filter((x) => x.p.scope === sc.scope); const words = mine.reduce((n, x) => n + Math.max(1, wordsIn(x.p.text)), 0) || 1; const secs = spans.get(sc.scope) * f; for (const x of mine) { starts[x.i] = r3(t); t += (secs * Math.max(1, wordsIn(x.p.text))) / words; } if (!mine.length) t += secs; } readEnd = r3(t); } const blocks = map.blocks.map((b) => ({ ...b, start: b.part === null ? null : starts[b.part] })); // In the order they are read; each ends where the next starts. const lit = blocks.filter((b) => b.start !== null).sort((a, b) => a.start - b.start || a.k - b.k); lit.forEach((b, i) => (b.end = i + 1 < lit.length ? lit[i + 1].start : Math.max(b.start, readEnd))); for (const b of blocks) if (b.start === null) b.end = null; // THREADED (post-thread.mjs): a narrated read of the post it answers or quotes -- the card a column of tiles, // each shown in full while it is read, then shrunk and dimmed as the next piece comes in. // `scene` (post-conversation.mjs planContext): the posts its run left on screen, kept on top or collapsed away. // THE THREAD SCENE WINS (post-media-scene.mjs's header): with one, no media scene is drawn on the card. const ms = Array.isArray(scene?.tiles) && scene.tiles.length ? null : mediaScene; const base = isNarrated(entry) ? threadLayout(entry, render, { prev, scene }) : null; // A MEDIA SCENE (post-media-scene.mjs): the scene's earlier messages above the card's own tiles -- a narrated // item's on its thread read's schedule, an un-narrated one's on the scene's. const layout = ms ? sceneLayout(base, entry, ms) : base; // PICTURE-ONLY context posts' BEATS (post-thread.mjs pictureBeats, post-picture.mjs): pieces of their own before the read. const beatsOn = base && Array.isArray(beats) && beats.length ? beats : []; // A PICTURE-ONLY post of his own whose read reads its picture (the words on a screenshot: no block of the card's // words is timed) is read as a piece of its own from the read's start: its tile -- the picture -- framed whole. const picReads = base?.on && isNarrated(entry) && base.tiles.some((t) => t.scope === "post" && t.pic) && !blocks.some((b) => b.start !== null) ? [{ scope: "post", t0: r3((narration ?? narrationSchedule(entry, render)).at), t1: readEnd }] : []; const own = !layout?.on ? null : base ? threadSchedule(entry, render, { layout, blocks, lead: FOLLOW_PAN.lead, beats: [...beatsOn, ...picReads] }) : sceneSchedule(threadKnobs(entry, render), { layout, blocks, lead: FOLLOW_PAN.lead }); const thread0 = ms ? sceneRows(own, layout) : own; // LINK VISITS (post-link-visit.mjs): a link in the words visited -- the pointer, the click, the post opened. const visits = thread0 && isNarrated(entry) ? linkVisits(entry, thread0, blocks, render) : []; const thread = visits.length ? visitRows(thread0, visits) : thread0; // THE JOIN (post-join.mjs): its first seconds morph from the item before as it ended. return { dim: k.dim, ease: k.ease, readEnd, source: map.source, blocks, ...(thread ? { thread } : {}), ...(visits.length ? { visits } : {}), ...(join && fin(join.seconds) ? { join: { seconds: join.seconds } } : {}), ...(thread && beatsOn.length ? { beats: beatsOn } : {}), ...(thread && picReads.length ? { picReads } : {}) }; } /** The block being read at item second `s` (its k), or null (before the read's first block, or none). */ export function followBlockAt(follow, s) { let cur = null; for (const b of follow?.blocks ?? []) if (b.start !== null && s >= b.start - 0.05 && (cur === null || b.start >= cur.start)) cur = b; return cur ? cur.k : null; } // --------------------------------------------------------------------------- // THE PAN: the window over the post's words, from the page's geometry. // --------------------------------------------------------------------------- /** * THE PAN's PATH, pure: `{ max, segments: [{ t0, t1, from, to }] }` -- the * flow's offset (px, down) eased from `from` to `to` over each segment. `geo` * is measureFollow's: the window's height `H`, the flow's `C`, each post * block's `{ top, bottom }` in the flow. No overflow: no segments. */ export function followPath(follow, geo) { if (follow?.thread) return threadPath(follow, geo); const H = fin(geo?.H) ? geo.H : 0; const C = fin(geo?.C) ? geo.C : 0; const max = Math.max(0, Math.round((C - H) * 100) / 100); if (!follow || max < 1 || H <= 0) return { max, segments: [] }; const m = Math.round(H * FOLLOW_PAN.margin); const segments = []; let off = 0; let free = 0; const moveTo = (target, at) => { const to = Math.round(clamp(target, 0, max) * 100) / 100; if (Math.abs(to - off) < 1) return; const t0 = r3(Math.max(0, at, free)); const t1 = r3(t0 + FOLLOW_PAN.seconds); segments.push({ t0, t1, from: off, to }); off = to; free = t1; }; const read = (follow.blocks ?? []).filter((b) => b.scope === "post" && b.start !== null && geo.blocks?.[b.k]).sort((a, b) => a.start - b.start); for (const b of read) { const { top, bottom } = geo.blocks[b.k]; const h = bottom - top; // Not in view (above the window, or running past its foot): it pans to sit a margin below the top. if (top < off - 0.5 || bottom > off + H - m / 2 + 0.5) moveTo(top - m, b.start - FOLLOW_PAN.lead); // Taller than the window: on through it as it is read (the reading line taken as even through its words). const room = H - 2 * m; if (h > room && room > 0) { const over = h - room; const n = Math.ceil(over / (0.6 * room)); const span = Math.max(0.1, b.end - b.start); for (let i = 1; i <= n; i += 1) { const target = top - m + (over * i) / n; const line = target - (top - m) + room * 0.6; moveTo(target, Math.min(b.end - FOLLOW_PAN.seconds, b.start + (span * line) / h)); } } } return { max, segments }; } /** The tile a block's scope is drawn in (a quoted post is a tile inside his post's). */ const tileScopeOf = (scope) => (scope === "quoted" || scope === "post" || String(scope).startsWith("parent:") || String(scope).startsWith("linked:") || isScreenScope(scope) ? scope : null); /** * A THREADED card's PAN (post-thread.mjs), pure: `{ thread: true, start, * segments, H, C, tiles, max }` -- the column's offset at the first frame * (`start`; negative: a column shorter than the window, centred in it) and * its moves. The geometry is the page measured at every tile's full size * (measureFollow), worked out under the tiles' scales at each move's end * (threadGeoAt): the first block of each piece is brought in under a strip * (THREAD_CONTEXT_ROOM of the window) of the post it answers, eased over the * thread's `pan` seconds from the same moment the tile before it starts to * shrink; a later block not in view pans as read-follow pans a post's own. */ export function threadPath(follow, geo) { const th = follow.thread; const H = fin(geo?.H) ? geo.H : 0; const base = { thread: true, start: 0, segments: [], H, C: fin(geo?.C) ? geo.C : 0, tiles: geo?.tiles ?? {} }; if (!H) return { ...base, max: 0 }; const m = Math.round(H * FOLLOW_PAN.margin); const lead = FOLLOW_PAN.lead; const span = Math.max(th.seconds, th.pan); const scalesAt = (t) => Object.fromEntries(Object.entries(threadStateAt(th, t)).map(([sc, v]) => [sc, v[0]])); const at = (t) => threadGeoAt(geo, scalesAt(t)); const placed = (g, want) => { const max = g.C - H; if (max < 1) return Math.round((max / 2) * 100) / 100; return Math.round(clamp(want, 0, max) * 100) / 100; }; // A PICTURE-ONLY post's BEAT (post-picture.mjs) is framed as a piece read: its tile, for its beat. const beatBlocks = [...(Array.isArray(follow.beats) ? follow.beats : []), ...(Array.isArray(follow.picReads) ? follow.picReads : [])].filter((b) => geo?.tiles?.[b.scope]).map((b) => ({ scope: b.scope, start: b.t0, end: b.t1, k: null, beat: true })); const read = [...beatBlocks, ...(follow.blocks ?? []).filter((b) => b.start !== null && geo.blocks?.[b.k]).sort((a, b) => a.start - b.start || a.k - b.k)]; const boxOf = (g, b) => (b.beat ? g.tiles[b.scope] : g.blocks[b.k]); // The opening frame: a carried post (or the scene's post the item before ended on) framed as the item before // left it; else the first block's place. const carry = (th.tiles ?? []).find((t) => t.mode === "carry") ?? (th.tiles ?? []).find((t) => t.mode === "scene" && t.wasPost); const g0 = at(0); let off; if (carry && g0.tiles[carry.scope] && geo?.joinAnchor && fin(geo.joinAnchor.y)) { // THE JOIN (post-join.mjs): the post the item before ended on, framed where that item left it (the anchor // measured on both pages: its top this far down the window). off = Math.round((g0.tiles[carry.scope].top - geo.joinAnchor.y) * 100) / 100; } else if (carry && g0.tiles[carry.scope] && th.scene) { // A MEDIA SCENE (post-media-scene.mjs): framed as the item before ended -- what is on screen (the column down // to the carried message) centred, or its foot a margin above the window's when it runs past. const vis = g0.tiles[carry.scope].bottom; off = vis <= H ? Math.round(((vis - H) / 2) * 100) / 100 : placed(g0, vis - H + m); } else if (carry && g0.tiles[carry.scope]) off = placed(g0, g0.tiles[carry.scope].top - m); else if (read.length) { const g = at(read[0].start - lead + span); // The first post read, whole when it fits the window; else its first block a margin from the top. const tile = g.tiles[tileScopeOf(read[0].scope)]; off = placed(g, tile && tile.bottom - tile.top <= H - m ? tile.top - Math.min(m / 2, tile.top) : boxOf(g, read[0]).top - m); } else off = placed(g0, 0); const start = off; const segments = []; let free = 0; let maxSeen = Math.max(0, g0.C - H); const moveTo = (to, t0w, seconds) => { if (Math.abs(to - off) < 1) return; const t0 = r3(Math.max(0, t0w, free)); const t1 = r3(t0 + seconds); segments.push({ t0, t1, from: off, to }); off = to; free = t1; }; let prevScope = carry ? carry.scope : null; read.forEach((b, i) => { const first = b.scope !== prevScope; prevScope = b.scope; if (i === 0 && !carry) return; const g = at(b.start - lead + span); maxSeen = Math.max(maxSeen, g.C - H); const bb = boxOf(g, b); if (first) { // A new piece: its tile under a strip of the one it answers, the block itself in view. const tile = g.tiles[tileScopeOf(b.scope)]; const top = tile ? tile.top : bb.top; let want = top - Math.min(H * (th.contextRoom ?? 0.3), top); // THE POST BEING READ IN FULL (operator, 4 Nov, p-2117359906164814087: "it must be in full while read"): a // tile that fits the window is shown whole while it is read -- the strip of what it answers above giving way. if (tile && tile.bottom - tile.top <= H - m && tile.bottom > want + H - m / 2) want = Math.min(top, tile.bottom - H + m / 2); // Its first block whole in view, as much of what it answers kept above as that leaves. if (bb.bottom > want + H - m) want = Math.min(bb.top - m, bb.bottom - H + m); moveTo(placed(g, want), b.start - lead, th.pan); } else if (bb.top < off - 0.5) moveTo(placed(g, bb.top - m), b.start - lead, th.pan); // Running past the window's foot: up just enough to show it whole (what it follows kept in view above). else if (bb.bottom > off + H - m / 2 + 0.5) moveTo(placed(g, Math.min(bb.top - m, bb.bottom - H + m)), b.start - lead, th.pan); // A block taller than the window pans on through it as it is read. const h = bb.bottom - bb.top; const room = H - 2 * m; if (h > room && room > 0 && g.C - H >= 1) { const over = h - room; const n = Math.ceil(over / (0.6 * room)); const len = Math.max(0.1, (b.end ?? b.start) - b.start); for (let j = 1; j <= n; j += 1) { const target = bb.top - m + (over * j) / n; const line = target - (bb.top - m) + room * 0.6; moveTo(placed(g, target), Math.min((b.end ?? b.start) - th.pan, b.start + (len * line) / h), th.pan); } } }); return { ...base, start, segments, max: Math.round(maxSeen * 100) / 100 }; } /** The flow's offset at item second `s` on the path. */ export function followOffsetAt(path, s) { let off = fin(path?.start) ? path.start : 0; for (const g of path?.segments ?? []) { if (s >= g.t1) off = g.to; else if (s >= g.t0) return g.from + (g.to - g.from) * easeOf("inOut", (s - g.t0) / Math.max(1e-6, g.t1 - g.t0)); else break; } return off; } /** An eased ramp 0 -> 1 over [a, a + d]. */ const ramp = (s, a, d) => (d <= 0 ? (s >= a ? 1 : 0) : easeOf("inOut", (s - a) / d)); /** * THE STATE at item second `s`, pure and seek-safe: `{ op: { : opacity }, * offset, fadeTop, fadeBottom, current }`. The block being read rises to full * over `ease` (centred on its start) while the one before falls back to * `dim`; before the first block's start the first is lit; after the read's * end every block rises back to full. A map of fewer than two read blocks is * never dimmed. `path`: followPath's (null: no pan). */ /** * @param {Record | null} follow * @param {Record | null} path * @param {number} s * @returns {{ op: Record, offset: number, fadeTop: number, fadeBottom: number, current: any, tiles?: Record, join?: number, visit?: { i: number, move: number, click: number, ring: number }, map?: { op: number, p: number } }} */ export function followStateAt(follow, path, s) { const op = {}; if (!follow) return { op, offset: 0, fadeTop: 0, fadeBottom: 0, current: null }; const read = follow.blocks.filter((b) => b.start !== null).sort((a, b) => a.start - b.start); const e = follow.ease; const after = ramp(s, follow.readEnd, e); if (read.length >= 2) { const lit = new Map(); read.forEach((b, i) => { const up = i === 0 ? 1 : ramp(s, b.start - e / 2, e); const down = i + 1 < read.length ? ramp(s, read[i + 1].start - e / 2, e) : 0; lit.set(b.k, Math.min(up, 1 - down)); }); for (const b of follow.blocks) { const l = Math.max(lit.get(b.k) ?? 0, after); op[b.k] = Math.round((follow.dim + (1 - follow.dim) * l) * 1000) / 1000; } } const offset = Math.round(followOffsetAt(path, s) * 4) / 4; const max = path?.max ?? 0; const edge = 24; const current = read.length ? followBlockAt(follow, s) ?? read[0].k : null; // THE JOIN (post-join.mjs): its progress while the card morphs from the item before's. /** @type {Record} */ const jp = follow.join && fin(follow.join.seconds) && s < follow.join.seconds - 1e-6 ? { join: Math.round((Math.max(0, s) / follow.join.seconds) * 1000) / 1000 } : {}; // A LINK VISIT (post-link-visit.mjs): the pointer, its click, the linked post's ring. const vs = follow.visits?.length ? visitStateAt(follow.visits, s) : null; if (vs) jp.visit = vs; // THE BRANCH MAP (post-branch-map.mjs): shown as the scene changes branch, its light travelling. const ms = follow.thread?.map ? mapStateAt(follow.thread.map, s) : null; if (ms) jp.map = ms; if (follow.thread) { // THREADED (post-thread.mjs): each tile's scale and opacity, with its full height (the page sets its slot's). const ts = threadStateAt(follow.thread, s); const tiles = {}; let C = fin(path?.C) ? path.C : 0; for (const [scope, [sc, o]] of Object.entries(ts)) { const h = path?.tiles?.[scope]?.height ?? 0; // A scene tile (post-conversation.mjs) collapsing away takes the gap above it with it. const gap = scope.startsWith("conv:") || isScreenScope(scope) ? path?.tiles?.[scope]?.gap ?? 0 : 0; tiles[scope] = gap > 0 ? [sc, o, Math.round(h * 100) / 100, Math.round(gap * 100) / 100] : [sc, o, Math.round(h * 100) / 100]; if (sc < 0.9995 && gap > 0) C -= (1 - sc) * gap; // A tile closes the flow up under it as it shrinks -- a quoted post inside his post never shrinks; one above it does. if (sc < 0.9995 && (scope !== "quoted" || follow.thread.quotedAt === "above")) C -= (1 - sc) * h; } const below = C - (path?.H ?? 0) - offset; // A SCREEN up (post-screens.mjs): the one in full now -- its badge ("· transcribed") pinned to the card while it is. const scr = screenUpAt(ts); return { op, offset, fadeTop: offset > 0.5 ? Math.round(clamp(offset / edge, 0, 1) * 100) / 100 : 0, fadeBottom: path?.H && below > 0.5 ? Math.round(clamp(below / edge, 0, 1) * 100) / 100 : 0, current, tiles, ...jp, ...(scr !== undefined ? { screen: scr } : {}), }; } return { op, offset, fadeTop: max >= 1 ? Math.round(clamp(offset / edge, 0, 1) * 100) / 100 : 0, fadeBottom: max >= 1 ? Math.round(clamp((max - offset) / edge, 0, 1) * 100) / 100 : 0, current, ...jp, }; } /** * The SCREEN up at a thread state (post-screens.mjs): the id of the last screen tile at half its size and strength or * more, null when none is -- undefined when the card has no screen tile (its state then carries no `screen`). * @param {Record} ts */ function screenUpAt(ts) { const scopes = Object.keys(ts).filter(isScreenScope); if (!scopes.length) return undefined; let up = null; for (const sc of scopes) if (ts[sc][0] >= 0.5 && ts[sc][1] >= 0.5) up = sc.slice(7); return up; } /** A state's key: two frames with the same key draw the same card (the build shoots each key once). */ export const followStateKey = (st) => JSON.stringify([st.op, st.offset, st.fadeTop, st.fadeBottom, ...(st.tiles ? [st.tiles] : []), ...(st.join !== undefined ? [st.join] : []), ...(st.visit ? [st.visit] : []), ...(st.map ? [st.map] : []), ...(st.screen !== undefined ? [{ screen: st.screen }] : [])]); /** * Whether a state draws the card PAGE AS DRAWN (no state applied): nothing * dimmed, no pan, no fading edge, every tile full size and full strength. A * build whose every frame is in such a state needs no follow frames; one * frame that is not (a threaded card's context post small and dim, its column * placed) must be shot -- the page as drawn has every tile full and lit, the * column at the top (Mr. Obvious mid-5, p-2117259673917386879: one part read, * no pan, so no frames were shot and the parent drew full over his post). */ export function isDrawnState(st) { if (!st) return true; if (fin(st.join) || st.visit || st.map || (typeof st.screen === "string" && st.screen)) return false; if (Object.values(st.op ?? {}).some((o) => fin(o) && o < 0.9995)) return false; if (fin(st.offset) && Math.abs(st.offset) >= 0.5) return false; if ((st.fadeTop ?? 0) > 0 || (st.fadeBottom ?? 0) > 0) return false; return !Object.values(st.tiles ?? {}).some((v) => Array.isArray(v) && ((fin(v[0]) && v[0] < 0.9995) || (fin(v[1]) && v[1] < 0.9995))); } // --------------------------------------------------------------------------- // THE INVARIANT: what is being read is in view while it is read (operator, // 4 Nov: "no hidden text is ever narrated"). // --------------------------------------------------------------------------- /** * The tolerances of readInViewErrors: `tol` px a block may run past the * window's edge; `slack` s it may be out of view in all (a pan or a tile's * change in passing); `share` of the window a block taller than it must fill; * `step` s between the moments looked at; `size` the slack on a context * tile's size and strength. */ export const READ_IN_VIEW = Object.freeze({ tol: 2, slack: 0.25, share: 0.5, step: 0.05, size: 0.005 }); const pct = (v) => `${Math.round(v * 100)}%`; const tileName = (scope) => (isScreenScope(scope) ? `screen ${String(scope).slice(7)}` : scope === "post" ? "his post" : scope === "quoted" ? "the quoted post" : String(scope).startsWith("parent:") ? `the post it answers (${scope})` : String(scope).startsWith("linked:") ? `the post it links (${scope})` : String(scope)); /** * THE READ IN VIEW, pure: every reason the words being read are not on screen, * whole and lit, while they are said -- as sentences naming the item (empty: * they always are). `geo` is measureFollow's (the page at every tile's full * size); `stateAt(s)` the state the frames at item second `s` are DRAWN in * (null: the page as drawn, no state applied -- what a build that shoots no * follow frames shows). For each block a part reads, from the moment its pan * and its tile's change have settled until the next one's begin: * * - a tile that fits the window (less its margin) is in it WHOLE; a block of a * tile taller than that is in it whole, and one taller than the window fills * `share` of it (it pans on through); * - its tile (a quoted post inside his: his too) at full size and strength, * and the block itself lit; * * and, the whole item, a context tile never larger nor stronger than its * context size (a parent `shrink`×`dim`, a quoted post inside his `dim`), a * carried or scene tile at its own once it has given way. A part read off an * attachment lights no block and is not looked at. * * @param {Record | null} follow the plan's (followSchedule) * @param {Record | null} geo * @param {(s: number) => Record | null} stateAt * @param {{ total?: number | null, id?: string }} [o] * @returns {string[]} */ export function readInViewErrors(follow, geo, stateAt, { total = null, id = "?" } = {}) { if (!follow || !geo || !fin(geo.H) || geo.H <= 0) return []; const T = READ_IN_VIEW; const H = geo.H; const m = Math.round(H * FOLLOW_PAN.margin); const th = follow.thread ?? null; const lead = FOLLOW_PAN.lead; const settle = Math.max(0, (th ? Math.max(th.pan, th.seconds) : FOLLOW_PAN.seconds) - lead) + 0.05; const end = fin(total) && total > 0 ? total : follow.readEnd ?? 0; const errors = []; const memo = new Map(); const look = (s) => { const key = Math.round(s * 1000); if (memo.has(key)) return memo.get(key); const st = stateAt(s); const tiles = st?.tiles ?? {}; const scaleOf = (sc) => (Array.isArray(tiles[sc]) && fin(tiles[sc][0]) ? tiles[sc][0] : 1); const opOf = (sc) => (Array.isArray(tiles[sc]) && fin(tiles[sc][1]) ? tiles[sc][1] : 1); const g = th ? threadGeoAt(geo, Object.fromEntries(Object.keys(geo.tiles ?? {}).map((sc) => [sc, scaleOf(sc)]))) : { blocks: geo.blocks ?? {}, tiles: {} }; const v = { st, g, off: fin(st?.offset) ? st.offset : 0, scaleOf, opOf }; memo.set(key, v); return v; }; const read = (follow.blocks ?? []).filter((b) => b.start !== null && b.part !== null && geo.blocks?.[b.k] && !String(b.scope).startsWith("media:")); for (const b of read) { const bEnd = fin(b.end) ? b.end : b.start; const a = b.start + settle; const z = bEnd - lead; const times = []; if (z <= a) times.push(r3((b.start + bEnd) / 2)); else for (let s = a; s <= z + 1e-9; s += T.step) times.push(r3(s)); let bad = 0; let worst = null; for (const s of times) { const v = look(s); const bb = v.g.blocks[b.k]; if (!bb) continue; const why = []; const tile = th ? tileScopeOf(b.scope) : null; const tb = tile ? v.g.tiles[tile] : null; // In view: the tile whole when it fits, else the block whole, else (taller than the window) most of the window. const box = tb && tb.bottom - tb.top <= H - m ? tb : bb; const top = box.top - v.off; const bottom = box.bottom - v.off; const h = bottom - top; const seen = Math.max(0, Math.min(bottom, H) - Math.max(top, 0)); if (h <= H + T.tol ? top < -T.tol || bottom > H + T.tol : seen < T.share * H) { why.push(h <= H + T.tol ? `${box === tb ? "its tile" : "the block"} runs ${top < -T.tol ? `${Math.round(-top)} px above the window` : `${Math.round(bottom - H)} px past the window's foot`} (${pct(seen / Math.max(1, h))} of it in view)` : `only ${pct(seen / H)} of the window shows it`); } if (tile) { const sc = v.scaleOf(tile); const op = v.opOf(tile); if (sc < 0.99 || op < 0.99) why.push(`${tileName(tile)} is drawn at ${sc.toFixed(2)}× and ${op.toFixed(2)} strength`); if (tile === "quoted" && th.quotedAt !== "above" && (v.scaleOf("post") < 0.99 || v.opOf("post") < 0.99)) why.push(`his post, the quote's tile, is drawn at ${v.scaleOf("post").toFixed(2)}× and ${v.opOf("post").toFixed(2)} strength`); } const bop = v.st?.op?.[b.k]; if (fin(bop) && bop < 0.99) why.push(`the block is dimmed to ${bop}`); if (why.length) { bad += 1; worst ??= { s, why }; } } const secs = times.length > 1 ? bad * T.step : bad ? Math.max(0.1, bEnd - b.start) : 0; if (bad && secs > T.slack + 1e-9) { errors.push(`${id}: part ${(b.takePart ?? b.part) + 1} (${tileName(b.scope)}, block ${b.k}) is not in full view for ${secs.toFixed(2)} s of its read (${r3(b.start)}–${r3(bEnd)} s) -- at ${worst.s} s ${worst.why.join("; ")}`); } } // A CONTEXT tile is never larger nor stronger than its context size; a carried or scene tile, once it has given way. for (const row of th?.tiles ?? []) { const ctxMode = row.mode === "context"; const gave = (row.mode === "carry" || row.mode === "scene") && fin(row.t1) && row.t1 > row.t0 && !row.then; if (!ctxMode && !gave) continue; const lim = ctxMode ? (row.scope === "quoted" && th.quotedAt !== "above" ? [1, th.dim] : [th.shrink, th.dim]) : row.to; const from = ctxMode ? 0 : row.t1 + 0.05; for (let s = from; s <= end + 1e-9; s += 0.1) { // Lit again by a link visit (post-link-visit.mjs): its hold is the visit's, not a read's. if (row.pulse && s > row.pulse.t0 - 1e-6 && s < row.pulse.t3 + 1e-6) continue; const v = look(r3(s)); const sc = v.scaleOf(row.scope); const op = v.opOf(row.scope); if (sc > lim[0] + T.size || op > lim[1] + T.size) { errors.push(`${id}: ${tileName(row.scope)} (${ctxMode ? "context, never read" : `${row.mode}, given way`}) is drawn at ${sc.toFixed(2)}× and ${op.toFixed(2)} strength at ${r3(s)} s -- over its size there (${lim[0]}× and ${lim[1]})`); break; } } } return errors; } /** * The item's FRAMES as runs of one state, pure: `[{ key, st, n }]` -- frame i * at followStateAt(i / fps), `total` s at `fps`, consecutive frames of one * state one run (the build shoots each distinct state once). It needs no * frames shot only when every run is the page as drawn (isDrawnState). */ export function followRuns(follow, path, total, fps) { const frames = Math.max(1, Math.round(total * fps)); const runs = []; for (let i = 0; i < frames; i += 1) { const st = followStateAt(follow, path, i / fps); const key = followStateKey(st); const last = runs[runs.length - 1]; if (last && last.key === key) last.n += 1; else runs.push({ key, st, n: 1 }); } return runs; } /** * The frames' state at item second `s`, as the build shoots them: the state of * frame floor(s·fps) (followStateAt at i / fps); `shot` false (no follow * frames shot) the page as drawn, null. */ export const shotStateAt = (follow, path, fps, shot = true) => (s) => (shot ? followStateAt(follow, path, Math.floor(s * fps + 1e-6) / fps) : null); // --------------------------------------------------------------------------- // In the page: self-contained (the build passes them to page.evaluate; Play // calls them on its frame's document). They reach for nothing outside. // --------------------------------------------------------------------------- /** * The page's geometry for the pan: the window's height, the flow's, each * block's top and bottom in the flow -- and, a threaded card (post-thread.mjs), * each tile's top and height, all measured at every tile's full size. */ export function measureFollow(doc = document) { const words = doc.querySelector("[data-post-words]"); const flow = doc.querySelector("[data-post-flow]"); if (!words || !flow) return null; const had = flow.style.transform; flow.style.transform = "none"; // A threaded card's tiles at full size while it is measured (their state put back after). const slots = Array.from(flow.querySelectorAll("[data-thread-slot]")); const kept = slots.map((el) => { const tile = el.querySelector("[data-thread-tile]"); const k = { el, tile, h: el.style.height, mt: el.style.marginTop, t: tile ? tile.style.transform : "", o: tile ? tile.style.opacity : "" }; el.style.height = ""; el.style.marginTop = ""; if (tile) { tile.style.transform = ""; tile.style.opacity = ""; } return k; }); const fr = flow.getBoundingClientRect(); const blocks = {}; for (const el of Array.from(flow.querySelectorAll("[data-post-block]"))) { let top = Infinity; let bottom = -Infinity; for (const r of Array.from(el.getClientRects())) { if (r.width === 0 && r.height === 0) continue; top = Math.min(top, r.top); bottom = Math.max(bottom, r.bottom); } if (top < bottom) blocks[el.getAttribute("data-post-block")] = { top: Math.round((top - fr.top) * 100) / 100, bottom: Math.round((bottom - fr.top) * 100) / 100 }; } const out = { H: words.clientHeight, C: Math.round(fr.height * 100) / 100, blocks }; if (slots.length) { const tiles = {}; for (const el of slots) { const r = el.getBoundingClientRect(); const gap = parseFloat(getComputedStyle(el).marginTop) || 0; tiles[el.getAttribute("data-thread-slot")] = { top: Math.round((r.top - fr.top) * 100) / 100, height: Math.round(r.height * 100) / 100, ...(gap > 0 ? { gap: Math.round(gap * 100) / 100 } : {}) }; } out.tiles = tiles; } for (const k of kept) { k.el.style.height = k.h; k.el.style.marginTop = k.mt; if (k.tile) { k.tile.style.transform = k.t; k.tile.style.opacity = k.o; } } flow.style.transform = had; return out; } /** Set a follow state on the page: each block's opacity, the flow's offset, the fading edges. */ export function applyFollowState(state, doc = document) { const op = (state && state.op) || {}; for (const el of Array.from(doc.querySelectorAll("[data-post-block]"))) { const o = op[el.getAttribute("data-post-block")]; const v = typeof o === "number" && o < 0.9995 ? String(o) : ""; if (el.style.opacity !== v) el.style.opacity = v; } // A threaded card's tiles (post-thread.mjs): each scaled about its corner, its slot closed up to match, its strength. const tiles = (state && state.tiles) || {}; for (const el of Array.from(doc.querySelectorAll("[data-thread-slot]"))) { const v = tiles[el.getAttribute("data-thread-slot")]; const tile = el.querySelector("[data-thread-tile]"); const sc = v && typeof v[0] === "number" ? v[0] : 1; const o = v && typeof v[1] === "number" ? v[1] : 1; const h = sc < 0.9995 && v && v[2] > 0 ? `${Math.round(v[2] * sc * 100) / 100}px` : ""; if (el.style.height !== h) el.style.height = h; // A scene tile collapsing away (post-conversation.mjs): the gap above it closes with it. const mt = sc < 0.9995 && v && v[3] > 0 ? `${Math.round(v[3] * sc * 100) / 100}px` : ""; if (el.style.marginTop !== mt) el.style.marginTop = mt; if (tile) { const tf = sc < 0.9995 ? `scale(${sc})` : ""; if (tile.style.transform !== tf) tile.style.transform = tf; const ov = o < 0.9995 ? String(o) : ""; if (tile.style.opacity !== ov) tile.style.opacity = ov; } el.setAttribute("data-thread-state", sc < 0.9995 || o < 0.9995 ? (o < 0.02 ? "hidden" : "context") : "focus"); } const flow = doc.querySelector("[data-post-flow]"); if (flow) { const t = state && state.offset ? `translateY(${-state.offset}px)` : ""; if (flow.style.transform !== t) flow.style.transform = t; } for (const [side, v] of [["top", state ? state.fadeTop : 0], ["bottom", state ? state.fadeBottom : 0]]) { const el = doc.querySelector(`[data-post-fade="${side}"]`); if (el) el.style.opacity = String(v || 0); } // A SCREEN's badge (post-screens.mjs): shown while that screen is up. for (const el of Array.from(doc.querySelectorAll("[data-screen-badge]"))) { const v = state && state.screen === el.getAttribute("data-screen-badge") ? "1" : ""; if (el.style.opacity !== v) el.style.opacity = v; } if (doc.body) doc.body.setAttribute("data-post-follow-block", state && state.current !== null && state.current !== undefined ? String(state.current) : ""); }