// A POST AS A TIMELINE ITEM (umtool/docs/report-video.md, "Post items"): an // archived post -- an X post, a Bluesky one -- played as an entry of the cut in // its own right, beside clips, rather than as a card laid over one (`posts[]`, // deck.mjs). A "posts reel" is a cut made of them (`umtool posts reel`); any // cut may mix them with clips. // // { type: "post", id, post: "/", // platform, author, handle, date, text, url, engagement?, // repostedBy?: { author, handle }, quoted?: , parents?: [, …], // replyingTo?: "", parentShot?: "", // media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?, // start?, end?, mute?, crop?: [x, y, w, h], push?, words?, // blur?: { on, strength?, boxes?, label? } }], (post-censor.mjs) // mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen?, scene?: false|"join", (post-media-scene.mjs) // fx?: [{ kind: "word-zoom", match, target?, occurrence?, at?, lead?, hold?, scale?, ease?, highlight? }] } // // (`fx`: the card pushed in on a word as it is read -- word-zoom.mjs.) // // where a (a post it quotes, the posts it answers, nearest first) is // `{ id?, author?, handle?, badge?, date?, text?, url?, paraphrase? }` -- // `paraphrase` the operator's short retelling of a long context post // (POST_PARAPHRASE_MAX characters), drawn in place of its words with a // "paraphrased" label (contextText); `text` is kept untouched. The archive row is // SNAPSHOTTED into the entry when it goes in (postReel.mjs): a cut renders the // words and counts it was made with, not whatever the archive says next week. // // PURE and dependency-free: the build (post-render.mjs), Play the cut (in the // browser), the writers and the lint all read the same rules from here -- // the validator, the duration rule, the plan of what plays when, the layout // and the card's HTML. import { draftScript, isNarrated, narrationSchedule, pickedTake, postNarrationFiles, postNarrationKnobs, validatePostNarration, } from "./post-narration.mjs"; import { BAR_CSS, barsHtml, hasMarks, projectRedactOf, redactEntry, redactSceneRef, redactionOn, validatePostsRender } from "./post-redact.mjs"; import { blurErrors, blurOn, censorEntry } from "./post-censor.mjs"; import { WORD_ZOOM_HIGHLIGHT_ALPHA, cardTokens, cardWordsOf, findMatch, targetTextOf, validatePostFx } from "./word-zoom.mjs"; import { FOLLOW_MIN_SIZE, followBlocks, followKnobs, followSchedule, scopeBlocks, validatePostFollow } from "./read-follow.mjs"; import { panelSchedule, pictureBeats, spokenSaysHiddenErrors, threadLayout, validatePostThread } from "./post-thread.mjs"; import { isPictureOnly, pictureBeatSeconds, pictureHasSound, pictureMediaOf, pictureRuleEntry, validatePictureOnly, validatePictureReplyRender } from "./post-picture.mjs"; import { joinLayerHtml, validatePostJoin, validatePostJoinRender } from "./post-join.mjs"; import { validatePostLinkVisit, validatePostLinkVisitRender, visitsEnd } from "./post-link-visit.mjs"; import { progressErrors } from "./post-progress.mjs"; import { validatePostMapRender } from "./post-branch-map.mjs"; import { validatePostScene, validatePostSceneRender } from "./post-media-scene.mjs"; import { hasScreens, isScreenScope, screenBadgeHtml, screenCss, screenOf, screenShows, screenTileHtml, screenWho, validateScreens } from "./post-screens.mjs"; /** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */ export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]); export const POST_MEDIA_KINDS = Object.freeze(["image", "video", "gif"]); export const POST_MEDIA_LAYOUTS = Object.freeze(["sequence", "grid"]); /** Where an item's attachments sit (`panel`): beside the card, above it or below it at full width. */ export const POST_PANELS = Object.freeze(["side", "top", "bottom"]); /** * THE DURATION RULE. A post item plays for the time it takes to read it, then * its attachments, one after another: * * reading = clamp(READ.lead + words / READ.wps, READ.min, READ.max) * + for each post it answers and the post it quotes: * clamp(words / READ.wps, CONTEXT_READ.min, CONTEXT_READ.max) -- 1-4 s: context, not the post * (the words its card shows: its paraphrase's, when it has one) * media = a video: its trimmed length (end - start), its sound on; * a GIF: looped to at least GIF.min s (one pass when longer, at most GIF.max); * an image: IMAGE_SECONDS; a grid of 2-4 images: GRID.base + GRID.per × (n - 1) * seconds = reading + the media, in order -- or `hold`, which overrides the * whole (a longer hold holds the last thing up; a shorter one cuts * the attachments short at it). * * Words are runs of non-space; a link is one word. 3 words a second is a * comfortable on-screen read (about 180 a minute), with a second to find the * text first; the cap keeps a 500-word post from stalling the reel -- a post * that long is shown at the size that fits, and `hold` gives it more. */ export const POST_READ = Object.freeze({ wps: 3, lead: 1, min: 3, max: 15 }); export const POST_CONTEXT_READ = Object.freeze({ min: 1, max: 4 }); export const POST_IMAGE_SECONDS = 3.5; export const POST_GIF = Object.freeze({ min: 3, max: 10 }); export const POST_GRID = Object.freeze({ base: 3.5, per: 1 }); export const POST_HOLD = Object.freeze({ min: 1, max: 120 }); export const POST_MEDIA_MAX = 4; /** * The posts it answers drawn above it (the reply chain), nearest first: at most this many (a WHOLE-THREAD read, * operator 4 Nov: "include the whole thread context" -- set by hand, `posts set-item

parent.=`). */ export const POST_PARENTS_MAX = 8; /** How many of them a reel or `posts context` fills from the archive by itself (the post it answers and its parent). */ export const POST_PARENTS_FILL = 2; /** The posts a post's words link to that it draws (`links[]`, post-thread.mjs: a link visit), at most this many. */ export const POST_LINKS_MAX = 4; /** A context post's paraphrase (`quoted.paraphrase`, `parents[i].paraphrase`): at most this many characters. */ export const POST_PARAPHRASE_MAX = 600; /** A video attachment's shortest trimmed span, in seconds. */ export const POST_MEDIA_MIN_SPAN = 0.5; /** An image's slow push-in (`push: true`): this much larger by the end of its span. */ export const POST_PUSH = 0.06; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const fin = (v) => typeof v === "number" && Number.isFinite(v); const round3 = (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 : ""); /** Words on the card: runs of non-space (a link is one). */ export function wordCount(text) { const t = str(text).trim(); return t ? t.split(/\s+/).length : 0; } /** The text a card shows: a repost's own "RT @x: " prefix is the card's "reposted" line, not its words. */ export function cardText(entry) { const t = str(entry?.text); return entry?.repostedBy ? t.replace(/^RT @[A-Za-z0-9_]+:\s*/, "") : t; } /** The posts it answers (nearest first), at most POST_PARENTS_MAX. */ export const parentsOf = (entry) => (Array.isArray(entry?.parents) ? entry.parents.filter(isObj).slice(0, POST_PARENTS_MAX) : []); /** The posts its words link to that it draws (`links[]`: a status link resolved by hand, `posts set-item … link.add=`). */ export const linksOf = (entry) => (Array.isArray(entry?.links) ? entry.links.filter(isObj).slice(0, POST_LINKS_MAX) : []); /** A context post's attachments (`ref.media`: a parent's picture, a linked post's -- project files). */ export const refMediaOf = (ref) => (Array.isArray(ref?.media) ? ref.media.filter((m) => isObj(m) && typeof m.src === "string") : []); /** Whether a context post is drawn at all: it has words, or an attachment (an image-only reply). */ export const refShown = (ref) => !!contextText(ref).trim() || refMediaOf(ref).length > 0; /** Whether the item's OWN post is picture-only (post-picture.mjs): its attachment drawn in its card, never in the slot. */ export const ownPictureOnly = (entry) => isPictureOnly(entry, { text: cardText(entry) }); /** Whether a context post (a parent, the quoted post) is picture-only (post-picture.mjs). */ export const refPictureOnly = (ref) => isPictureOnly(ref); // --------------------------------------------------------------------------- // THE EXCERPT (rev 9, 6 Nov): a long post read in part. `entry.excerpt` is one // or more VERBATIM spans of the post's words, in order; the read (the // narration script drafted for it, an un-narrated card's reading time) is // those spans joined with " … ", and the card still shows the WHOLE post -- // the spans read lit, the rest dimmed -- so it never hides that text was cut. // --------------------------------------------------------------------------- /** The excerpt's join: what stands between two spans in the read. */ export const POST_EXCERPT_JOIN = " … "; /** At most this many spans. */ export const POST_EXCERPT_MAX = 8; /** The excerpt's spans (`entry.excerpt`, the strings), or null when it has none. */ export const excerptSpansOf = (entry) => (Array.isArray(entry?.excerpt) && entry.excerpt.length && entry.excerpt.every((x) => typeof x === "string" && x.trim()) ? entry.excerpt : null); /** * Where each span stands in `text`, in order -- `[{ start, end }]` (character * offsets; each found at or after the end of the one before) -- or null when a * span is not in the text there. */ export function excerptRanges(text, spans) { const t = str(text); const out = []; let from = 0; for (const sp of spans) { const at = t.indexOf(sp, from); if (at < 0) return null; out.push({ start: at, end: at + sp.length }); from = at + sp.length; } return out; } /** What is READ of a post: its excerpt's spans joined with " … ", else the card's words whole. */ export function postReadText(entry) { const spans = excerptSpansOf(entry); return spans && excerptRanges(cardText(entry), spans) ? spans.map((x) => x.trim()).join(POST_EXCERPT_JOIN) : cardText(entry); } /** What a script says when nobody edited it: what is read of the post, drafted to be spoken (draftScript). */ export const shownDraftOf = (entry) => draftScript(postReadText(entry)).script; /** A script's words as compared: each paragraph's spacing collapsed, the paragraphs kept (a merge is an edit). */ const spacing = (t) => str(t).split(/\n\s*\n/).map((x) => x.replace(/\s+/g, " ").trim()).filter(Boolean).join("\n\n"); /** Whether `script` says his words as drafted (shownDraftOf), paragraph for paragraph: not an edit for reading. */ export const saysShownDraft = (entry, script) => spacing(script) === spacing(shownDraftOf(entry)); /** What an item whose playing take predates the rule is told (`posts narrate --list`, the bench), and what moves it. */ export const LEGACY_EDIT_TEXT = "its playing take was read before reads were kept apart from the card, so the card follows what that take says -- read it again to move it to the new rule"; /** * Whether a script is the post's words EDITED FOR READING (lane line-rerun; operator ruling 3, 15 Nov 2026: an edit * changes only what is spoken) -- `script` the one to judge (default: the item's own). What it decides is only an * item with NO playing take (a preview from the script); with one, the take decides (readEditOf): * null no script, no words on the card, or the script says the shown text as drafted * "reading" edited, and `narration.forReading` set by the writer * "legacy" edited, no marker */ export function scriptEditOf(entry, script = entry?.narration?.script) { const own = spacing(script); const shown = spacing(shownDraftOf(entry)); if (!own || !shown || own === shown) return null; return entry?.narration?.forReading === true ? "reading" : "legacy"; } /** * The post's words a take READ, as written (review 2, finding 1): a single read's `script` (the words before the * lexicon, the redaction or an anonymous handle changed what was said), else its parts -- his post's ("post") when * they store roles -- rebuilt into paragraphs (a paragraph over 60 words is read in several parts: they join with a * space; a thread read's part is in paragraph `para` % 100 of its piece). */ export function takePostWords(take) { const parts = Array.isArray(take?.parts) ? take.parts : []; const roled = parts.some((p) => typeof p?.role === "string"); if (!roled && str(take?.script).trim()) return str(take.script); const own = roled ? parts.filter((p) => p?.role === "post") : parts; if (!own.length) return str(take?.script); const paras = []; let last; for (const p of own) { const k = Number.isInteger(p?.para) ? (roled ? p.para % 100 : p.para) : null; if (paras.length && k !== null && k === last) paras[paras.length - 1] += ` ${str(p?.text).trim()}`; else paras.push(str(p?.text).trim()); last = k; } return paras.join("\n\n"); } /** * Whether a take is stamped FOR READING when it is made (the writer, postNarrationIn): the words it read are not the * post's as drafted. False with no shown text. A THREAD read decides its own when it is made, from the words its post * piece was WRITTEN as (postThreadRead.mjs: its parts hold the words as spoken) -- the writer leaves it as it comes. */ export const takeIsEditedRead = (entry, take) => !!spacing(shownDraftOf(entry)) && !!spacing(takePostWords(take)) && !saysShownDraft(entry, takePostWords(take)); /** * THE RULE FOR THE CARD's LAYOUT (lane line-rerun; review 1, finding 3, the orchestrator's ruling): the take that PLAYS * decides. `take` (default: the picked one): * "reading" stamped `forReading` when it was made: the card follows the SHOWN text (read-follow.mjs followParts, * post-thread.mjs partRoles), never the read's words * null it says the post's words as drafted: the card follows it, as ever (the same thing) * "legacy" made before the rule (no stamp) from other words: the card follows them, as it always did -- read it * again to move it to the rule * With no take playing, the script decides (scriptEditOf: `narration.forReading`). */ /** Whether the PLAYING take predates the rule and reads other words than the post's (`--list`, the bench say so). */ export const legacyReadOf = (entry) => !!pickedTake(entry) && readEditOf(entry) === "legacy"; export function readEditOf(entry, take = pickedTake(entry)) { if (!take) return scriptEditOf(entry); if (take.forReading === true) return "reading"; // An unstamped THREAD read's parts hold its words as SPOKEN (the lexicon, the redaction): it is legacy only when the // script it read from was edited too -- a lexicon word alone is not an edit. if (take.read?.kind === "thread" && (!str(entry?.narration?.script).trim() || saysShownDraft(entry, entry.narration.script))) return null; return takeIsEditedRead(entry, take) ? "legacy" : null; } /** The card's word indices (cardTokens') that the excerpt does NOT read (drawn dimmed), or null with no excerpt. */ export function excerptCutWords(entry) { const spans = excerptSpansOf(entry); const text = cardText(entry); const ranges = spans ? excerptRanges(text, spans) : null; if (!ranges) return null; const cut = new Set(); let at = 0; for (const t of cardTokens(text)) { const len = (t.space ?? t.tok).length; if (t.tok !== undefined && !ranges.some((r) => at < r.end && at + len > r.start)) cut.add(t.i); at += len; } return cut; } /** Every reason `entry.excerpt` cannot be read (empty: it can). */ export function excerptErrors(entry, where = `timeline ${entry?.id ?? "?"}.excerpt`) { const x = entry?.excerpt; if (x === undefined) return []; if (!Array.isArray(x) || !x.length) return [`${where} must be a list of the post's own words to read (one or more spans)`]; if (x.length > POST_EXCERPT_MAX) return [`${where}: at most ${POST_EXCERPT_MAX} spans`]; const errors = []; x.forEach((sp, i) => { if (typeof sp !== "string" || !sp.trim()) errors.push(`${where}[${i}] must be words of the post`); }); if (errors.length) return errors; const text = cardText(entry); let from = 0; x.forEach((sp, i) => { const at = str(text).indexOf(sp, from); if (at < 0) { errors.push(str(text).includes(sp) ? `${where}[${i}] "${sp.slice(0, 40)}" is in the post, but before the span ahead of it (the spans go in the post's order)` : `${where}[${i}] "${sp.slice(0, 40)}" is not in the post's words (an excerpt is verbatim)`); } else from = at + sp.length; }); return errors; } /** Seconds to read the post itself (the rule above, its first line): its excerpt when it has one. */ export function readSeconds(entry) { return clamp(POST_READ.lead + wordCount(postReadText(entry)) / POST_READ.wps, POST_READ.min, POST_READ.max); } /** Whether a context post (a parent, the quoted post) is drawn as the operator's paraphrase. */ export const isParaphrased = (ref) => !!str(ref?.paraphrase).trim(); /** * The words a context post's card shows: the operator's PARAPHRASE when it * has one (drawn with a "paraphrased" label -- never taken for the author's * words), else its own text. */ export function contextText(ref) { return isParaphrased(ref) ? str(ref.paraphrase).trim() : str(ref?.text); } /** Seconds to read one post of its context (a parent, the quoted post): the words its card shows. */ export function contextReadSeconds(ref) { return clamp(wordCount(contextText(ref)) / POST_READ.wps, POST_CONTEXT_READ.min, POST_CONTEXT_READ.max); } /** * The whole reading time: the post and its context. A PICTURE-ONLY post (post-picture.mjs) is its picture's beat * instead of its words' reading (`render`: the cut's rule). */ export function readingSeconds(entry, render = undefined) { const e = pictureRuleEntry(entry, render); const ctx = (p) => (refPictureOnly(p) ? pictureBeatSeconds(refMediaOf(p), render) : contextReadSeconds(p)); let s = ownPictureOnly(e) ? pictureBeatSeconds(pictureMediaOf(e), render) : readSeconds(e); for (const p of parentsOf(e)) s += ctx(p); if (isObj(e?.quoted)) s += ctx(e.quoted); return round3(s); } /** A media item's trimmed source span `[from, to]` (a video's or a GIF's own seconds). */ export function mediaSpan(m) { const len = fin(m?.seconds) && m.seconds > 0 ? m.seconds : null; const from = fin(m?.start) ? Math.max(0, m.start) : 0; const to = fin(m?.end) ? m.end : len ?? from + POST_IMAGE_SECONDS; return { from: round3(from), to: round3(len ? Math.min(to, len) : to) }; } /** How long one attachment plays in the item (the rule above). */ export function mediaSeconds(m) { if (m?.kind === "video") { const { from, to } = mediaSpan(m); return round3(Math.max(POST_MEDIA_MIN_SPAN, to - from)); } if (m?.kind === "gif") { const { from, to } = mediaSpan(m); const pass = Math.max(0.1, to - from); return round3(pass >= POST_GIF.min ? Math.min(pass, POST_GIF.max) : Math.ceil(POST_GIF.min / pass) * pass); } return POST_IMAGE_SECONDS; } /** The attachments as they play: a grid of the images (mediaLayout "grid", 2-4 of them) is one step. A picture-only post's are in its card (post-picture.mjs): none. */ export function mediaSteps(entry) { const media = Array.isArray(entry?.media) && !ownPictureOnly(entry) ? entry.media.filter(isObj).slice(0, POST_MEDIA_MAX) : []; const indexed = media.map((m, i) => ({ ...m, i })); const images = indexed.filter((m) => m.kind === "image"); if (entry?.mediaLayout === "grid" && images.length >= 2) { const rest = indexed.filter((m) => m.kind !== "image"); return [ { kind: "grid", items: images, seconds: round3(POST_GRID.base + POST_GRID.per * (images.length - 1)) }, ...rest.map((m) => ({ kind: m.kind, items: [m], seconds: mediaSeconds(m) })), ]; } return indexed.map((m) => ({ kind: m.kind, items: [m], seconds: mediaSeconds(m) })); } /** * THE ONE LAYOUT AND THE PACING RULE (operator, 2 Nov: "the gallery cycle * needs to be shown like a video and text stays on the screen the whole * time"; "read out every post, and not linger too long after finishing the * read"). Every post item is its card -- the full text, on screen for the * item's whole length -- and, beside it, its attachments played as ONE * sequence, like a video, WHILE the words are read: * * the read = narrated: lead + the take + tail + linger (post-narration.mjs); * not: the reading time (readingSeconds) * a video = from the item's first frame, from its in point (or the best * part `posts fit` chose) for the read -- cut to it; an out point * set is kept as the choice; `clip: "full"` plays it whole * pictures = the read's time left after the videos, shared out: a GIF * looped, the images cycling (crossfaded), each at least * POST_PICTURE_MIN s; a grid of 2-4 images is one picture * total = max(the read, the attachments) -- or `hold` * * A video shorter than the read holds its last frame (`short: "hold"`) or * loops (`short: "loop"`). Narrated with `attach: "after"`, the narration is * read over the card first and the attachments play after it, whole. */ export const POST_PICTURE_MIN = 1.5; /** The crossfade from one picture to the next, in seconds. */ export const POST_PICTURE_XFADE = 0.3; /** * The item's length by the rule, before `hold`. * @param {Record} entry * @param {Record} [render] */ export function ruleSeconds(entry, render = undefined) { return planOf(entry, render, null).total; } /** * The item's length in the cut: `hold` when it is set, else the rule. `render` the cut's (its `postNarration` knobs). * @param {Record} entry * @param {Record} [render] */ export function postItemSeconds(entry, render = undefined) { if (fin(entry?.hold) && entry.hold > 0) return round3(entry.hold); return ruleSeconds(entry, render); } /** * WHAT PLAYS WHEN inside a post item, in its own seconds (0 is its first * frame): each step of the attachments, from the first frame (the rule * above). A step is `{ kind, items, at, seconds, srcFrom, srcTo, loop, * sound }` -- a video's source span and whether its sound plays, a GIF's * loop. `reading` is 0 (the words are on screen throughout) but for a * narration read before the attachments (`attach: "after"`). With `hold` the * plan is cut (or extended) to it. A narrated item's plan carries its mix * (`narration`: narrationSchedule). The render and Play both play this plan. * * @param {Record} entry * @param {Record} [render] * `mediaScene` (post-media-scene.mjs mediaSceneOf): its media scene -- the * scene's earlier messages in its card's column (`follow.thread`). The entry * is the one the scene plays (sceneEntry: the shared attachment the * anchor's): the caller makes it, so a channel's markup is laid on first. * `scene` (post-conversation.mjs planContext): the posts its conversation's * run left on screen -- it wins the card over a media scene. * * @param {Record} entry * @param {Record} [render] * @param {{ prev?: Record | null, scene?: Record | null, mediaScene?: Record | null, join?: { seconds: number } | null }} [o] the item before it in the cut (post-thread.mjs carries a parent that is it); `join` (post-conversation.mjs planContext): it opens on the item before as it ended (post-join.mjs) * @returns {{ reading: number, total: number, steps: Array>, held: number, narration?: Record, follow?: Record }} */ export function postItemPlan(entry, render = undefined, { prev = null, scene = null, mediaScene = null, join = null } = {}) { const hold = fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : null; return planOf(entry, render, hold, prev, scene, mediaScene, join); } /** * @param {Record} entry * @param {Record | undefined} render * @param {number | null} hold * @param {Record | null} [prev] * @param {Record | null} [scene] * @param {Record | null} [mediaScene] */ function planOf(entry, render, hold, prev = null, scene = null, mediaScene = null, join = null) { // PICTURE-ONLY posts (post-picture.mjs): the cut's rule laid on (off: none is). entry = pictureRuleEntry(entry, render); const narrated = isNarrated(entry); const k = postNarrationKnobs(entry, render); // THE JOIN (post-join.mjs) comes first: the read starts after it (the item a join's seconds longer). const joinPre = join && fin(join.seconds) ? join.seconds : 0; // Then a PICTURE-ONLY context post's BEAT (post-thread.mjs pictureBeats): shown alone, the read after it -- its // start moved, the take never re-made. Looked for only when a context post is picture-only. const beats = narrated && followKnobs(entry, render).on && hasPictureContext(entry) ? pictureBeats(entry, render, threadLayout(entry, render, { prev, scene }), joinPre) : []; const pre = round3(joinPre + (beats.length ? beats[beats.length - 1].t1 - joinPre : 0)); const sch = narrated ? narrationSchedule(entry, render, { pre }) : null; // Its read-follow (read-follow.mjs): each block's start on the item's clock -- null when it is off. `prev`: the // item before it in the cut (post-thread.mjs: a parent that is that item is carried in, not cut to). const follow = followSchedule(entry, render, { hold, narration: sch, prev, scene, mediaScene, join, ...(beats.length ? { beats } : {}) }); const extra = { ...(sch ? { narration: sch } : {}), ...(follow ? { follow } : {}) }; if (sch && k.attach === "after") { const voiceOnly = round3(sch.at + sch.seconds + k.tail); const all = mediaSteps(entry); const media = all.reduce((n, s) => n + s.seconds, 0); const total = hold ?? round3(voiceOnly + media + (all.length ? 0 : k.linger)); const plan = planSteps(all, voiceOnly, total); const panel = follow ? panelSchedule(entry, follow, total) : null; const pics = picturesOf(entry, follow); return { ...plan, reading: round3(Math.min(voiceOnly, total)), total, ...extra, ...(panel ? { panel } : {}), ...(pics.length ? { pics } : {}) }; } const span = sch ? round3(sch.at + sch.seconds + k.tail + k.linger) : readingSeconds(entry, render); // ITS OWN ATTACHMENTS come in with ITS OWN POST (ownMediaEnterAt): a thread read's parents and quotes first, his // attachment when his words begin -- a video starts there, its sound too, its trim fitted to what is left. const enter = ownMediaEnterAt(entry, follow, { mediaScene }); const avail = round3(Math.max(0, span - enter)); const all = mediaSteps(entry).map((s) => { if (s.kind !== "video" || k.clip === "full") return s; // An out point the operator set is kept: that span is the choice. One `posts fit` set (it is the // window it recorded) was sized to the read, so it follows the read: a faster `rate` shortens it. const m = s.items[0]; const w = entry?.narration?.window; const fitEnd = sch && isObj(w) && w.media === m.i && fin(w.end) && Math.abs(w.end - m.end) < 0.011; return fin(m.end) && !fitEnd ? s : { ...s, seconds: round3(Math.min(s.seconds, avail)) }; }); // ITS SCREENS (post-screens.mjs) read: its own attachments until the first is up, then each screen's span. const shows = !hasScreens(entry) || ownPictureOnly(entry) ? [] : screenShows(entry, follow, { lead: 0.4 }); const ownUntil = shows.length ? Math.max(enter, shows[0].t0) : null; const avail1 = ownUntil === null ? avail : round3(Math.max(0, ownUntil - enter)); const videos = all.filter((s) => s.kind === "video").reduce((n, s) => n + s.seconds, 0); const pics = all.filter((s) => s.kind !== "video"); const share = pics.length ? Math.max(POST_PICTURE_MIN, (avail1 - videos) / pics.length) : 0; const steps = all.map((s) => (s.kind === "video" ? s : { ...s, seconds: round3(share) })); const media = round3(steps.reduce((n, s) => n + s.seconds, 0)); // A LINK VISIT (post-link-visit.mjs) lit after the read runs on its hold: the item holds it. const total = hold ?? round3(Math.max(span, ownUntil === null ? enter + media : 0, follow?.visits ? visitsEnd(follow.visits) : 0)); const plan = ownUntil === null ? planSteps(steps, enter, total) : screenPlan(entry, steps, enter, ownUntil, shows, total); // A video shorter than the read: looped to the end, or (the default) its last frame held. const last = plan.steps[plan.steps.length - 1]; if (k.short === "loop" && last?.kind === "video" && plan.held > 0.05) { last.seconds = round3(last.seconds + plan.held); last.loop = true; plan.held = 0; } // A CONTEXT POST's attachment (post-thread.mjs panelSchedule): over the slot while it is on screen. const panel = follow ? panelSchedule(entry, follow, total) : null; // A PICTURE-ONLY post's picture in its card (post-picture.mjs): the posts that have one, for the build's overlay. const inCard = picturesOf(entry, follow); return { ...plan, reading: 0, total, ...extra, ...(panel ? { panel } : {}), ...(enter > 0 && plan.steps.length ? { enter } : {}), ...(inCard.length ? { pics: inCard } : {}) }; } /** * THE PLAN's STEPS with ITS SCREENS (post-screens.mjs): its own attachments from `enter`, cut at the first screen's * show; then, for each screen, its attachment from its show to the next one's (the last to the item's end) -- a video * or a GIF from its span's start (`at`), its last frame HELD when the read outlasts the span (a looped span would * replay the overlay fading in and out); an image held. Each such step says `screen: `. */ function screenPlan(entry, steps, enter, ownUntil, shows, total) { const own = ownUntil > enter + 0.05 ? planSteps(steps, enter, ownUntil).steps : []; // Its last own step runs on to the first screen, its last frame held (`hold`: the build plays no further than its span). const lastOwn = own[own.length - 1]; if (lastOwn && lastOwn.at + lastOwn.seconds < ownUntil - 0.01) { lastOwn.seconds = round3(ownUntil - lastOwn.at); if (lastOwn.kind === "video") lastOwn.hold = true; } const media = Array.isArray(entry?.media) ? entry.media : []; const out = [...own]; shows.forEach((sh, i) => { const m = media[sh.media]; const until = i + 1 < shows.length ? shows[i + 1].t0 : total; if (!isObj(m) || until <= sh.t0 + 0.05) return; const seconds = round3(until - sh.t0); const timed = m.kind === "video" || m.kind === "gif"; const from = timed && Array.isArray(sh.at) ? round3(sh.at[0]) : 0; const to = timed && Array.isArray(sh.at) ? round3(sh.at[1]) : null; out.push({ kind: m.kind, items: [{ ...m, i: sh.media, ...(timed ? { start: from, end: to } : {}) }], at: round3(sh.t0), seconds, ...(timed ? { srcFrom: from, srcTo: to } : {}), loop: m.kind === "gif", sound: m.kind === "video" && m.mute !== true && m.audio !== false, ...(m.kind === "video" ? { hold: true } : {}), screen: sh.id, }); }); const end = out.length ? out[out.length - 1].at + out[out.length - 1].seconds : enter; return { steps: out, held: out.length ? round3(Math.max(0, total - end)) : 0 }; } /** Whether any context post of the item (a parent, the quoted post) is picture-only. */ const hasPictureContext = (entry) => parentsOf(entry).some(refPictureOnly) || (isObj(entry?.quoted) && refPictureOnly(entry.quoted)); /** * THE PICTURES IN CARDS (post-picture.mjs), pure: `[{ scope, media }]` -- each picture-only post the card draws * (his own: "post"; a parent: "parent:"; the quoted post: "quoted") with its attachments, the first drawn in its * card. The build plays a GIF's or a video's over its place while its card is at full size and still; Play plays it * in the card. A threaded card's hidden tile draws none. */ export function picturesOf(entry, follow = null) { const hidden = new Set((follow?.thread?.tiles ?? []).filter((t) => t.mode === "hidden").map((t) => t.scope)); const out = []; // A context post's BEAT with a video that has its sound: the sound plays through the beat (`sound`: its span). const soundOf = (scope, media) => { const b = (follow?.beats ?? []).find((x) => x.scope === scope); return b && pictureHasSound(media[0]) ? { sound: { t0: b.t0, t1: b.t1 } } : {}; }; if (ownPictureOnly(entry)) out.push({ scope: "post", media: pictureMediaOf(entry) }); parentsOf(entry).forEach((p, i) => { if (refPictureOnly(p) && !hidden.has(`parent:${i}`)) out.push({ scope: `parent:${i}`, media: pictureMediaOf(p), ...soundOf(`parent:${i}`, pictureMediaOf(p)) }); }); if (isObj(entry?.quoted) && refPictureOnly(entry.quoted) && !hidden.has("quoted")) out.push({ scope: "quoted", media: pictureMediaOf(entry.quoted), ...soundOf("quoted", pictureMediaOf(entry.quoted)) }); // A picture-only post the run left on screen (post-conversation.mjs sceneRefOf): its picture kept as context, in its // tile -- `post` names the archive post whose markup may censor it (its own attachment). for (const t of follow?.thread?.tiles ?? []) { if (t.mode !== "scene" || !t.ref?.pictureOnly || !pictureMediaOf(t.ref).length) continue; out.push({ scope: t.scope, media: pictureMediaOf(t.ref), ...(t.ref.src?.scope === "text" && str(t.ref.src.post) ? { post: str(t.ref.src.post) } : {}) }); } return out; } /** Where an item's own attachments may come in (`media[0].enter`): with its own post (the default), or with the item. */ export const POST_MEDIA_ENTERS = Object.freeze(["post", "item"]); /** Their crossfade in, seconds, from the moment his own words begin. */ export const POST_ENTER_FADE = 0.3; /** * WHEN AN ITEM's OWN ATTACHMENTS COME IN, pure (operator, 4 Nov, mid-11 at ~15:58: "the mr. obvious gif should come in * when his post does rather than during the strawb megathread reading"): the item second its OWN POST's read begins * (its first block of scope `post`) when a threaded read reads something else before it (a parent, a quote, a linked * post) -- else 0, as before: an item that reads only its post, one not threaded, one in a media scene after its * first (the item before ended on the same attachment: held through), or one whose first attachment says * `enter: "item"`. Until then the slot shows that * piece's context media (panelSchedule), or nothing. * @param {Record} entry * @param {{ thread?: any, blocks?: Array<{ scope?: string, start: number | null }> } | null} follow */ export function ownMediaEnterAt(entry, follow, { mediaScene = null } = {}) { const media = Array.isArray(entry?.media) ? entry.media : []; // In a media scene past its first item the item before ended on this same attachment: held through, as before. if (!media.length || !follow?.thread || (mediaScene && (mediaScene.n ?? 0) > 0)) return 0; if (media[0]?.enter === "item") return 0; const blocks = (follow.blocks ?? []).filter((b) => fin(b.start)); const post = blocks.filter((b) => b.scope === "post"); if (!post.length) return 0; const at = Math.min(...post.map((b) => b.start)); // A picture-only context post's BEAT before his words (post-picture.mjs) is a piece read before them too. const beat = (follow.beats ?? []).some((b) => fin(b.t0) && b.t0 < at - 1e-6); return beat || blocks.some((b) => b.scope !== "post" && b.start < at - 1e-6) ? round3(at) : 0; } /** Steps placed from `at0`, cut at `total` (postItemPlan's walk). */ function planSteps(stepsIn, at0, total) { const steps = []; let at = at0; for (const s of stepsIn) { if (at >= total - 0.05) break; const seconds = round3(Math.min(s.seconds, total - at)); const m = s.items[0]; const span = s.kind === "video" || s.kind === "gif" ? mediaSpan(m) : null; steps.push({ kind: s.kind, items: s.items, at: round3(at), seconds, ...(span ? { srcFrom: span.from, srcTo: s.kind === "video" ? round3(Math.min(span.to, span.from + seconds)) : span.to } : {}), loop: s.kind === "gif", sound: s.kind === "video" && m.mute !== true && m.audio !== false, }); at += seconds; } return { steps, held: steps.length ? round3(Math.max(0, total - at)) : 0 }; } /** The step on screen at item second `s` (null in the reading span). */ export function stepAt(plan, s) { let cur = null; for (const st of plan.steps) if (s >= st.at) cur = st; return cur; } /** Where a video/GIF step's media is at item second `s`: its source second. */ export function mediaTimeAt(step, s) { if (!step || (step.kind !== "video" && step.kind !== "gif")) return null; const local = Math.max(0, s - step.at); if (step.kind === "gif" || (step.loop && step.kind === "video")) { const pass = Math.max(0.1, step.srcTo - step.srcFrom); return round3(step.srcFrom + (local % pass)); } return round3(Math.min(step.srcTo, step.srcFrom + local)); } // --------------------------------------------------------------------------- // PRIVACY: whose name, face and handle a card may show. // --------------------------------------------------------------------------- /** * THE RULE capture-posts applies to a thread parent (common/social/ * xThreadShot.ts threadRedaction), applied to every OTHER author a post item * draws -- the post it answers (and its parent), the post it quotes, the * original of a repost: their avatar, display name and @handle are blurred * (and an @mention of them in the words), unless * * - the item says `redact: false` (the operator has judged them public), * - the author is the SUBJECT: the post's own author, or the account that * reposted it (a self-thread, his own post reposted), * - the archive says they carry an organisation's gold check or a * government's grey one (`badge`). X's blue check is bought, so a * blue-checked private person is blurred like any other; * * and `redact: true` blurs even those. An author the archive does not name * is blurred. The words of the post stay: what was said is the evidence; * who a private person is, is not. An ANONYMOUS author (post-anon.mjs: drawn * under a shown name, "Anon 1", with no handle or picture of theirs) is not * blurred by this rule -- the shown name says nothing of who they are; * `redact: true` still blurs them. * * @param {{ handle?: string|null, badge?: string|null, anonymous?: boolean }} who * @param {{ subjects?: string[], redact?: boolean }} [o] * @returns {{ redact: boolean, reason: "off"|"forced"|"subject"|"anonymous"|"verified"|"blue-check"|"private"|"unknown" }} */ export function authorRedaction(who, { subjects = [], redact = undefined } = {}) { const same = (a, b) => !!a && !!b && String(a).replace(/^@/, "").toLowerCase() === String(b).replace(/^@/, "").toLowerCase(); const handle = str(who?.handle); if (redact === false) return { redact: false, reason: "off" }; if (handle && subjects.some((s) => same(s, handle))) return { redact: redact === true, reason: redact === true ? "forced" : "subject" }; if (redact === true) return { redact: true, reason: "forced" }; if (who?.anonymous === true) return { redact: false, reason: "anonymous" }; if (!handle) return { redact: true, reason: "unknown" }; if (who?.badge === "gold" || who?.badge === "grey") return { redact: false, reason: "verified" }; if (who?.badge === "blue") return { redact: true, reason: "blue-check" }; return { redact: true, reason: "private" }; } /** * The subjects of an item: `subjects` when the item names them (a posts reel * names the accounts whose archive it was made from), else its own author and * the account that reposted it. */ export const subjectsOf = (entry) => Array.isArray(entry?.subjects) ? entry.subjects.filter((h) => typeof h === "string" && h) : [str(entry?.handle), str(entry?.repostedBy?.handle)].filter(Boolean); /** * Every author the card draws besides the subject, with the rule's answer: * `{ where, handle, redact, reason }` -- the parents, the quoted post, the * original of a repost, and a reply's "replying to" handle when its parent is * not archived. */ export function cardAuthors(entry) { const subjects = subjectsOf(entry); const o = { subjects, redact: typeof entry?.redact === "boolean" ? entry.redact : undefined }; const out = []; // The post's own author, when the item names its subjects and it is not one (a repost of somebody else's post). if (Array.isArray(entry?.subjects)) out.push({ where: "author", handle: str(entry.handle) || null, ...authorRedaction({ handle: entry.handle, badge: entry.badge, ...(entry.anonymous === true ? { anonymous: true } : {}) }, o) }); parentsOf(entry).forEach((p, i) => out.push({ where: `parents[${i}]`, handle: str(p.handle) || null, ...authorRedaction(p, o) })); if (isObj(entry?.quoted)) out.push({ where: "quoted", handle: str(entry.quoted.handle) || null, ...authorRedaction(entry.quoted, o) }); linksOf(entry).forEach((p, i) => out.push({ where: `links[${i}]`, handle: str(p.handle) || null, ...authorRedaction(p, o) })); if (!parentsOf(entry).length && str(entry?.replyingTo)) out.push({ where: "replyingTo", handle: entry.replyingTo, ...authorRedaction({ handle: entry.replyingTo }, o) }); return out; } // --------------------------------------------------------------------------- // The validator: the writers refuse with it and the build refuses with it. // --------------------------------------------------------------------------- const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; const NATIVE_ID_RE = /^[A-Za-z0-9_-]{1,128}$/; const HANDLE_RE = /^@?[A-Za-z0-9_.-]{1,64}$/; const BADGES = ["blue", "gold", "grey", "other"]; const TEXT_MAX = 25000; /** A project-relative file a post item names: inside the project, never absolute or `..`. */ export function relFileError(v, what) { if (typeof v !== "string" || !v.trim()) return `${what} must be a file path relative to the manifest`; if (v.startsWith("/") || v.startsWith("~") || /^[A-Za-z]:[\\/]/.test(v)) return `${what} must be relative to the manifest, not ${v}`; if (v.split(/[\\/]/).includes("..")) return `${what} must stay inside the project (no ..): ${v}`; return null; } function refErrors(r, where) { const errors = []; if (!isObj(r)) return [`${where} must be an object`]; for (const k of ["id", "author", "date", "text", "url"]) { if (r[k] !== undefined && typeof r[k] !== "string") errors.push(`${where}.${k} must be a string`); } if (r.handle !== undefined && (typeof r.handle !== "string" || !HANDLE_RE.test(r.handle))) errors.push(`${where}.handle must be a handle`); if (r.badge !== undefined && r.badge !== null && !BADGES.includes(r.badge)) errors.push(`${where}.badge must be one of ${BADGES.join(", ")}`); // How it was found: "link" -- a status link in the post's words, resolved to an archived post (postContext.mjs). if (r.via !== undefined && r.via !== "link") errors.push(`${where}.via must be "link" (a status link resolved to an archived post)`); if (typeof r.text === "string" && r.text.length > TEXT_MAX) errors.push(`${where}.text is longer than ${TEXT_MAX} characters`); // Its attachments (a parent's picture, shown in the slot while it is on screen): project files, as an item's. if (r.media !== undefined) { if (!Array.isArray(r.media)) errors.push(`${where}.media must be a list of attachments`); else { if (r.media.length > POST_MEDIA_MAX) errors.push(`${where}.media: at most ${POST_MEDIA_MAX} attachments`); r.media.forEach((m, i) => errors.push(...mediaErrors(m, `${where}.media[${i}]`))); } } // The words read off its picture (a linked post's screenshot, read in his voice): a block of the read with no card words. if (r.transcript !== undefined && !(typeof r.transcript === "string" && r.transcript.length <= TEXT_MAX)) errors.push(`${where}.transcript must be the words read off its picture (a string)`); if (r.paraphrase !== undefined) { if (typeof r.paraphrase !== "string") errors.push(`${where}.paraphrase must be a string (your retelling of its words; absent: its own words)`); else if (r.paraphrase.length > POST_PARAPHRASE_MAX) errors.push(`${where}.paraphrase is longer than ${POST_PARAPHRASE_MAX} characters (${r.paraphrase.length}): a paraphrase is short`); } return errors; } /** * Every reason post item `e` cannot be built, as sentences (empty: it can). * Unknown keys are left alone: a timeline entry carries the walk's and the * section's fields too. */ export function validatePostItem(e) { const w = `timeline ${e?.id ?? "?"}`; const errors = []; if (!isObj(e)) return [`${w} must be an object`]; if (typeof e.post !== "string" || !/^[^/]+\/[^/]+$/.test(e.post) || !SLUG_RE.test(e.post.split("/")[0]) || !NATIVE_ID_RE.test(e.post.split("/")[1])) { errors.push(`${w}.post must be /, the archive's post (got ${JSON.stringify(e.post)})`); } if (!POST_ITEM_PLATFORMS.includes(e.platform)) errors.push(`${w}.platform must be one of ${POST_ITEM_PLATFORMS.join(", ")}`); if (typeof e.text !== "string") errors.push(`${w}.text must be the post's words (a string; "" for none)`); else if (e.text.length > TEXT_MAX) errors.push(`${w}.text is longer than ${TEXT_MAX} characters`); if (typeof e.text === "string") errors.push(...excerptErrors(e, `${w}.excerpt`)); if (e.author !== undefined && typeof e.author !== "string") errors.push(`${w}.author must be a string`); if (e.handle !== undefined && (typeof e.handle !== "string" || !HANDLE_RE.test(e.handle))) errors.push(`${w}.handle must be a handle`); if (typeof e.date !== "string" || Number.isNaN(Date.parse(e.date))) errors.push(`${w}.date must be the post's date (ISO)`); if (e.url !== undefined && (typeof e.url !== "string" || !/^https?:\/\//.test(e.url))) errors.push(`${w}.url must be an http(s) link`); if (e.engagement !== undefined) { if (!isObj(e.engagement)) errors.push(`${w}.engagement must be an object of counts`); else for (const [k, v] of Object.entries(e.engagement)) if (!(Number.isInteger(v) && v >= 0)) errors.push(`${w}.engagement.${k} must be a whole number ≥ 0`); } if (e.repostedBy !== undefined) { if (!isObj(e.repostedBy) || typeof e.repostedBy.handle !== "string" || !HANDLE_RE.test(e.repostedBy.handle)) errors.push(`${w}.repostedBy must be { author?, handle }`); } if (e.quoted !== undefined) errors.push(...refErrors(e.quoted, `${w}.quoted`)); // The conversation it is part of (postContext.mjs: the archive row's threadId, snapshotted; post-conversation.mjs). if (e.conversation !== undefined && !(typeof e.conversation === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(e.conversation))) errors.push(`${w}.conversation must be the conversation's id (a string)`); if (e.parents !== undefined) { if (!Array.isArray(e.parents)) errors.push(`${w}.parents must be a list (the posts it answers, nearest first)`); else { if (e.parents.length > POST_PARENTS_MAX) errors.push(`${w}.parents: at most ${POST_PARENTS_MAX} (the posts it answers, nearest first)`); e.parents.forEach((p, i) => errors.push(...refErrors(p, `${w}.parents[${i}]`))); } } if (e.links !== undefined) { if (!Array.isArray(e.links)) errors.push(`${w}.links must be a list (the posts its words link to)`); else { if (e.links.length > POST_LINKS_MAX) errors.push(`${w}.links: at most ${POST_LINKS_MAX}`); e.links.forEach((p, i) => { errors.push(...refErrors(p, `${w}.links[${i}]`)); if (isObj(p) && !(typeof p.id === "string" && /^\d{1,25}$/.test(p.id))) errors.push(`${w}.links[${i}].id must be the linked post's id (its status number)`); }); } } if (e.replyingTo !== undefined && (typeof e.replyingTo !== "string" || !HANDLE_RE.test(e.replyingTo))) errors.push(`${w}.replyingTo must be a handle`); if (e.parentShot !== undefined) { const er = relFileError(e.parentShot, `${w}.parentShot`); if (er) errors.push(er); } if (e.redact !== undefined && typeof e.redact !== "boolean") errors.push(`${w}.redact must be true or false`); if (e.subjects !== undefined && !(Array.isArray(e.subjects) && e.subjects.length <= 8 && e.subjects.every((h) => typeof h === "string" && HANDLE_RE.test(h)))) { errors.push(`${w}.subjects must be a list of handles (at most 8): the accounts the cut is about`); } if (e.badge !== undefined && e.badge !== null && !BADGES.includes(e.badge)) errors.push(`${w}.badge must be one of ${BADGES.join(", ")}`); if (e.hold !== undefined && !(fin(e.hold) && e.hold >= POST_HOLD.min && e.hold <= POST_HOLD.max)) { errors.push(`${w}.hold must be ${POST_HOLD.min}–${POST_HOLD.max} seconds (absent: the duration rule)`); } if (e.panel !== undefined && !POST_PANELS.includes(e.panel)) errors.push(`${w}.panel must be one of ${POST_PANELS.join(", ")} (where its attachments sit; absent: beside the card, a wide one above it)`); if (e.mediaLayout !== undefined && !POST_MEDIA_LAYOUTS.includes(e.mediaLayout)) errors.push(`${w}.mediaLayout must be one of ${POST_MEDIA_LAYOUTS.join(", ")}`); if (e.media !== undefined) { if (!Array.isArray(e.media)) errors.push(`${w}.media must be a list of attachments`); else { if (e.media.length > POST_MEDIA_MAX) errors.push(`${w}.media: at most ${POST_MEDIA_MAX} attachments`); e.media.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.media[${i}]`))); } } // ITS ATTACHMENTS SWITCHED OFF (umtool redesign L6, the inspector's media on/off): each kept whole -- its crop, // blur, trim, sound -- in `mediaOff`, which nothing draws or plays (only `media` is read), so "on" puts it back as // it was. Checked as an attachment is. if (e.mediaOff !== undefined) { if (!Array.isArray(e.mediaOff) || !e.mediaOff.length) errors.push(`${w}.mediaOff must be a list of attachments switched off (absent: none)`); else { if (e.mediaOff.length > POST_MEDIA_MAX) errors.push(`${w}.mediaOff: at most ${POST_MEDIA_MAX} attachments`); e.mediaOff.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.mediaOff[${i}]`))); } } // Its narration (post-narration.mjs): the script, the takes, the mix's knobs. errors.push(...validatePostNarration(e)); // Its effects (word-zoom.mjs): a word zoomed on as it is read. errors.push(...validatePostFx(e)); // Its read-follow's knobs (read-follow.mjs): false, or { on, dim, ease }. errors.push(...validatePostFollow(e)); // Its thread read's knobs (post-thread.mjs): what each context post is on screen, the shrink and dim. errors.push(...validatePostThread(e)); // Its media scene (post-media-scene.mjs): false (never in one) or "join". errors.push(...validatePostScene(e)); // Its join with the item before (post-join.mjs): false (a cut) or { seconds }. errors.push(...validatePostJoin(e)); // Its link visit (post-link-visit.mjs): false (none). errors.push(...validatePostLinkVisit(e)); // Its progress bar (post-progress.mjs): auto, on or off (absent: the cut's). errors.push(...progressErrors(e.progress, `timeline ${e?.id ?? "?"}.progress`)); // Picture-only (post-picture.mjs): its own, a parent's, the quoted post's -- true or false. errors.push(...validatePictureOnly(e)); // Its screens (post-screens.mjs): the text screenshots it carries, transcribed, and what of them is read. errors.push(...validateScreens(e)); // A line's "said as" (saidAs) that says what another line masks or a redacted line holds: refused when written. for (const sc of Array.isArray(e?.screens) ? e.screens : []) { if (!isObj(sc?.saidAs)) continue; for (const [k, v] of Object.entries(sc.saidAs)) if (typeof v === "string") errors.push(...spokenSaysHiddenErrors(e, v, `line ${k} of screen ${sc.id}'s "said as"`)); } return errors; } function mediaErrors(m, where) { if (!isObj(m)) return [`${where} must be an object`]; const errors = []; const er = relFileError(m.src, `${where}.src`); if (er) errors.push(er); if (!POST_MEDIA_KINDS.includes(m.kind)) errors.push(`${where}.kind must be one of ${POST_MEDIA_KINDS.join(", ")}`); const timed = m.kind === "video" || m.kind === "gif"; if (timed && !(fin(m.seconds) && m.seconds > 0)) errors.push(`${where}.seconds must be its length (a ${m.kind} is measured when it goes in)`); for (const k of ["width", "height"]) if (m[k] !== undefined && !(Number.isInteger(m[k]) && m[k] > 0)) errors.push(`${where}.${k} must be a whole number of pixels`); for (const k of ["start", "end"]) { if (m[k] === undefined) continue; if (!timed) errors.push(`${where}.${k}: only a video or a GIF is trimmed`); else if (!(fin(m[k]) && m[k] >= 0 && (!fin(m.seconds) || m[k] <= m.seconds + 0.05))) errors.push(`${where}.${k} must be a second inside it (0–${m.seconds})`); } if (timed && fin(m.start) && fin(m.end) && m.end - m.start < POST_MEDIA_MIN_SPAN) errors.push(`${where}: end must be at least ${POST_MEDIA_MIN_SPAN} s after start`); for (const k of ["mute", "push", "audio"]) if (m[k] !== undefined && typeof m[k] !== "boolean") errors.push(`${where}.${k} must be true or false`); if (m.enter !== undefined && !POST_MEDIA_ENTERS.includes(m.enter)) errors.push(`${where}.enter must be ${POST_MEDIA_ENTERS.join(" or ")} (when it comes in: with his own post, or with the item)`); if (m.push !== undefined && m.kind !== "image") errors.push(`${where}.push: only an image is pushed in on`); if (m.crop !== undefined) { const c = m.crop; const ok = Array.isArray(c) && c.length === 4 && c.every((v) => fin(v) && v >= 0 && v <= 1) && c[2] > 0.05 && c[3] > 0.05 && c[0] + c[2] <= 1.0001 && c[1] + c[3] <= 1.0001; if (!ok) errors.push(`${where}.crop must be [x, y, w, h] as fractions of the picture (each 0–1, the box inside it)`); } if (m.words !== undefined) { const er2 = relFileError(m.words, `${where}.words`); if (er2) errors.push(er2); } errors.push(...blurErrors(m.blur, `${where}.blur`)); return errors; } /** Every post item's errors in a manifest (the writers' structure check and the build's lint). */ export function validatePostItems(manifest) { const errors = []; const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : []; for (const e of tl) if (e?.type === "post") errors.push(...validatePostItem(e)); errors.push(...validatePostsRender(manifest?.render), ...validatePostSceneRender(manifest?.render), ...validatePostPanelRender(manifest?.render), ...validatePostJoinRender(manifest?.render), ...validatePostLinkVisitRender(manifest?.render), ...validatePostMapRender(manifest?.render), ...validatePictureReplyRender(manifest?.render)); // A word zoom on a word the project's list blanks (the corpus's and a post's markup are checked by the build). const own = { terms: projectRedactOf(manifest?.render) }; for (const e of tl) if (e?.type === "post") errors.push(...fxRedactionErrors(e, own)); return errors; } /** * Every word zoom of post item `entry` whose words are (or hold) a REDACTED * word (post-redact.mjs): refused -- a published card never pushes in on a * blank. The match is found on the ORIGINAL text (its `occurrence` as the * manifest counts it); the redacted text keeps its spaces, so the same word * indices name the same words on the published card. * * @param {Record} entry * @param {{ terms: any[], markup?: Record } | null | undefined} red */ export function fxRedactionErrors(entry, red) { if (!Array.isArray(entry?.fx) || !entry.fx.length || !redactionOn(red)) return []; const shown = redactEntry(entry, red); const errors = []; entry.fx.forEach((fx, i) => { if (!isObj(fx) || fx.kind !== "word-zoom" || typeof fx.match !== "string") return; const target = fx.target ?? "post"; const text = targetTextOf(entry, target); const published = targetTextOf(shown, target); if (text === null || published === null) return; const m = findMatch(text, fx.match, fx.occurrence ?? 1); if (m.error) return; const words = cardWordsOf(published); for (let w = m.from; w <= m.to; w += 1) { if (hasMarks(words[w])) { errors.push(`timeline ${entry.id}.fx[${i}]: its match "${fx.match}" is a redacted word (render.posts.redact, the corpus's redactions.json or the post's markup) -- a published card never zooms on a blank; zoom on another word`); break; } } }); return errors; } /** Every file a post item reads beside the manifest, as `{ where, src }` (the lint checks each is there). */ export function postItemFiles(entry) { const out = []; const w = `timeline ${entry?.id ?? "?"}`; (Array.isArray(entry?.media) ? entry.media : []).forEach((m, i) => { if (typeof m?.src === "string") out.push({ where: `${w}.media[${i}]`, src: m.src }); }); if (typeof entry?.parentShot === "string") out.push({ where: `${w}.parentShot`, src: entry.parentShot }); // A context post's attachments (a parent's, a linked post's, the quoted post's). const refs = [...parentsOf(entry).map((p, i) => [`parents[${i}]`, p]), ...linksOf(entry).map((p, i) => [`links[${i}]`, p]), ...(isObj(entry?.quoted) ? [["quoted", entry.quoted]] : [])]; for (const [where, ref] of refs) refMediaOf(ref).forEach((m, i) => out.push({ where: `${w}.${where}.media[${i}]`, src: m.src })); out.push(...postNarrationFiles(entry)); return out; } // --------------------------------------------------------------------------- // The card: its layout in the footage box, and its HTML. // --------------------------------------------------------------------------- /** Fira Sans's average advance, as a fraction of the size, over running English. */ const CHAR_EM = 0.5; const LINE = 1.32; /** The text sizes tried, largest first, in px of a 1080-high frame (scaled to the box). */ export const POST_TEXT_SIZES = Object.freeze([46, 42, 38, 34, 30, 27, 24, 22, 20, 18]); /** * A LONG READ's words on a card ALONE (operator, 5 Nov, mid-15's "novel": "bigger text for the novel"): px of a * 1080-high landscape frame. Words that do not fit the card at any size of POST_TEXT_SIZES, read with read-follow (it * pans them), are drawn at this size -- never shrunk to fit; beside an attachment they keep FOLLOW_MIN_SIZE. */ export const POST_LONG_READ_SIZE = 36; /** The size a following card alone draws words that do not fit (POST_LONG_READ_SIZE scaled), else null. */ export function longReadSize(L, { width, height }, follow, fits = L.fits) { if (!follow || L.mode !== "text" || fits || width < height) return null; return Math.round(POST_LONG_READ_SIZE * (height / 1080)); } /** Below this size the words beside an attachment are too small: the card reads first, then the attachments play large. */ export const POST_SIDE_MIN = 26; /** Lines `text` takes in a column `width` px wide at `size` px (an estimate: wrapping by average advance). */ export function estimateLines(text, size, width) { const per = Math.max(8, Math.floor(width / (size * CHAR_EM))); return str(text).split("\n").reduce((n, para) => n + Math.max(1, Math.ceil(para.length / per)), 0); } /** The largest size in POST_TEXT_SIZES (scaled by `k`) at which `text` fits `width` × `height`; the smallest when none does. */ export function fitSize(text, width, height, k = 1) { for (const s0 of POST_TEXT_SIZES) { const s = s0 * k; if (estimateLines(text, s, width) * s * LINE <= height) return { size: Math.round(s), fits: true }; } return { size: Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k), fits: false }; } /** * THE LAYOUT, pure, in px of the box the item fills (the deck's footage box, * or the whole frame without the deck): * * text no attachment: the card alone, centred, as wide as reads well * side the card on the left, the attachments in a slot on the right, both * up the whole item -- when the words fit beside them at POST_SIDE_MIN * stack the words do not fit beside them: the card alone while it is read, * then the attachments large under a strip naming the post * * `card` is the card's box in the reading span, `slot` the attachments' box * in their span (`strip` the post's name over them, in a stack), `size` the * text size the card starts from (the page shrinks it further if it must). */ export function postLayout(entry, { width, height }) { const k = height / 1080; const pad = Math.round(36 * k); const steps = mediaSteps(entry); // The slot is laid out for its own attachments, else for a context post's (a parent's picture, post-thread.mjs panel). const shown = slotMediaOf(entry); const words = cardText(entry); // What the card spends besides the words: its head (avatar, name, date), its counts, the context. const context = Math.min(2, parentsOf(entry).length) * 130 * k + (isObj(entry?.quoted) ? 170 * k : 0) + (entry?.replyingTo || entry?.parentShot ? 40 * k : 0); const chrome = 150 * k + context + (entry?.repostedBy ? 34 * k : 0); const textCard = (w) => { const cw = Math.min(w, Math.round(1180 * k)); const box = { x: Math.round((width - cw) / 2), y: pad, width: cw, height: height - 2 * pad }; return { box, fit: fitSize(words, cw - 2 * pad, box.height - 2 * pad - chrome, k) }; }; if (!steps.length && !shown.length) { const t = textCard(width - 2 * pad); return { mode: "text", card: t.box, slot: null, strip: null, size: t.fit.size, fits: t.fit.fits, pad, panel: null }; } // A WIDE attachment (operator, 4 Nov: "for these super wide images a top-bottom layout would be better"): at full // width above (or below) the card, never a side panel -- `panel`, else the cut's rule (panelEntry). // A PORTRAIT box (a vertical cut, vertical.mjs) never lays the attachments beside the words: under them. const tall = height > width; const panel = tall && panelOf(entry) === "side" ? "bottom" : panelOf(entry); if (panel === "top" || panel === "bottom") { const first = shown[0] ?? {}; const crop = Array.isArray(first.crop) ? first.crop : null; const ar = ((first.width ?? 16) * (crop ? crop[2] : 1)) / Math.max(1, (first.height ?? 9) * (crop ? crop[3] : 1)); const fullW = width - 2 * pad; // A portrait box gives the panel its own share (`panelShare`, vertical.mjs's media-first layout) or POST_PANEL_SHARE_TALL. const share = tall ? (fin(entry?.panelShare) ? clamp(entry.panelShare, 0.2, 0.75) : POST_PANEL_SHARE_TALL) : POST_PANEL_SHARE; const slotH = Math.max(Math.round(120 * k), Math.min(Math.round(fullW / Math.max(0.2, ar)), Math.round(height * share))); const cw = Math.min(fullW, Math.round(1500 * k)); const cardH = height - 3 * pad - slotH; const slotY = panel === "top" ? pad : height - pad - slotH; const cardY = panel === "top" ? pad + slotH + pad : pad; const card = { x: Math.round((width - cw) / 2), y: cardY, width: cw, height: cardH }; const slot = { x: pad, y: slotY, width: fullW, height: slotH }; const fit = fitSize(words, cw - 2 * pad, cardH - 2 * pad - chrome, k); return { mode: "side", panel, card, slot, strip: null, size: fit.size, fits: fit.fits, pad }; } const cardW = Math.round((width - 3 * pad) * 0.42); const side = fitSize(words, cardW - 2 * pad, height - 4 * pad - chrome, k); // ONE LAYOUT (operator, 2 Nov): the words stay beside the attachments the whole time, at the size that fits // (the page shrinks them further if it must) -- never the card alone, then the attachments under a strip. if (side.fits || steps.length) { const card = { x: pad, y: pad, width: cardW, height: height - 2 * pad }; const slot = { x: 2 * pad + cardW, y: pad, width: width - 3 * pad - cardW, height: height - 2 * pad }; return { mode: "side", panel: "side", card, slot, strip: null, size: side.size, fits: side.fits, pad }; } const t = textCard(width - 2 * pad); const stripH = Math.round(92 * k); const strip = { x: pad, y: pad, width: width - 2 * pad, height: stripH }; const slot = { x: pad, y: pad + stripH + Math.round(pad / 2), width: width - 2 * pad, height: height - 2 * pad - stripH - Math.round(pad / 2) }; return { mode: "stack", card: t.box, slot, strip, size: t.fit.size, fits: t.fit.fits, pad, panel: null }; } /** A wide panel's height: at most this share of the box. */ export const POST_PANEL_SHARE = 0.42; /** In a portrait box (a vertical cut): at most this share. */ export const POST_PANEL_SHARE_TALL = 0.45; /** The cut's rule for a wide attachment (`render.posts.panel`): at this width ÷ height or more, laid at full width `place`. */ export const POST_PANEL_DEFAULTS = Object.freeze({ wide: 2.0, place: "top" }); /** What the slot shows over the item: its own attachments, else the context posts' (post-thread.mjs panelSchedule). */ export function slotMediaOf(entry) { // A picture-only post's attachment is drawn in its card (post-picture.mjs), never in the slot. const own = Array.isArray(entry?.media) && !ownPictureOnly(entry) ? entry.media.filter(isObj) : []; if (own.length) return own; const refs = [...[...parentsOf(entry)].reverse(), ...(isObj(entry?.quoted) ? [entry.quoted] : []), ...linksOf(entry)].filter((r) => !refPictureOnly(r)); return refs.flatMap(refMediaOf); } /** * Where an item's attachments sit: its `panel`, else top/bottom (the cut's `place`) when the first is WIDE (width ÷ * height ≥ `wide`; its crop counted), else beside the card. `rule`: the cut's (`render.posts.panel`), else the defaults. */ export function panelOf(entry, rule = null) { if (POST_PANELS.includes(entry?.panel)) return entry.panel; const r = { ...POST_PANEL_DEFAULTS, ...(isObj(rule) ? rule : {}) }; const m = slotMediaOf(entry)[0]; if (!m || !fin(m.width) || !fin(m.height) || r.place === "side") return "side"; const crop = Array.isArray(m.crop) ? m.crop : null; const ar = (m.width * (crop ? crop[2] : 1)) / Math.max(1, m.height * (crop ? crop[3] : 1)); return ar >= r.wide ? r.place : "side"; } /** The item with the CUT's wide-attachment rule laid on (`panel` set when the cut's rule differs from the defaults'). */ export function panelEntry(entry, render) { // PICTURE-ONLY posts (post-picture.mjs): the cut's rule laid on first (off: none is) -- the entry as it is, else. entry = pictureRuleEntry(entry, render); const rule = isObj(render?.posts?.panel) ? render.posts.panel : null; if (!rule || !isObj(entry) || POST_PANELS.includes(entry.panel)) return entry; const p = panelOf(entry, rule); return p === panelOf(entry) ? entry : { ...entry, panel: p }; } /** Every reason `render.posts.panel` cannot be built. */ export function validatePostPanelRender(render) { const v = render?.posts?.panel; if (v === undefined) return []; if (!isObj(v)) return ["render.posts.panel must be { wide?, place? } (where a wide attachment sits)"]; const errors = Object.keys(v).filter((k) => !(k in POST_PANEL_DEFAULTS)).map((k) => `render.posts.panel.${k} is not a panel knob (wide, place)`); if (v.wide !== undefined && !(fin(v.wide) && v.wide >= 1.2 && v.wide <= 10)) errors.push("render.posts.panel.wide must be 1.2–10 (width ÷ height from which an attachment is laid at full width)"); if (v.place !== undefined && !POST_PANELS.includes(v.place)) errors.push(`render.posts.panel.place must be one of ${POST_PANELS.join(", ")}`); return errors; } /** * Where each attachment of a step sits in the slot, in the box's px: one fills * the slot (fitted, its aspect kept); a grid lays 2 side by side, 3 as one * tall and two stacked, 4 as two by two -- each cell fitted. */ export function stepBoxes(step, slot, gap = 12) { const n = step.items.length; const cells = []; if (n <= 1) cells.push({ ...slot }); else if (n === 2) { const w = (slot.width - gap) / 2; cells.push({ x: slot.x, y: slot.y, width: w, height: slot.height }, { x: slot.x + w + gap, y: slot.y, width: w, height: slot.height }); } else if (n === 3) { const w = (slot.width - gap) / 2; const h = (slot.height - gap) / 2; cells.push({ x: slot.x, y: slot.y, width: w, height: slot.height }, { x: slot.x + w + gap, y: slot.y, width: w, height: h }, { x: slot.x + w + gap, y: slot.y + h + gap, width: w, height: h }); } else { const w = (slot.width - gap) / 2; const h = (slot.height - gap) / 2; for (const [cx, cy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) cells.push({ x: slot.x + cx * (w + gap), y: slot.y + cy * (h + gap), width: w, height: h }); } return step.items.map((m, j) => { const cell = cells[j]; const crop = Array.isArray(m.crop) ? m.crop : null; const iw = (m.width ?? 16) * (crop ? crop[2] : 1); const ih = (m.height ?? 9) * (crop ? crop[3] : 1); const s = Math.min(cell.width / iw, cell.height / ih); const w = Math.max(2, Math.floor((iw * s) / 2) * 2); const h = Math.max(2, Math.floor((ih * s) / 2) * 2); return { i: m.i, x: Math.round(cell.x + (cell.width - w) / 2), y: Math.round(cell.y + (cell.height - h) / 2), width: w, height: h, cell }; }); } /** A string inside a quoted CSS url(): a ${join?.A ? joinLayerHtml({ fromUrl: join.fromUrl ?? null, slotA: join.slotA ?? null, cardBg, line, radius: Math.round(18 * k) }) : ""}${barsHtml(body)} `); } /** * THE SIZE a card draws its post's words at (post-join.mjs: the post the next item carries is drawn alike): * threaded, the size that fits it alone in its tile; else the layout's (at least the follow minimum). The page may * shrink a plain card's further when it overflows -- the estimate's. * * @param {Record} entry * @param {{ width: number, height: number }} box * @param {{ follow?: boolean, threaded?: boolean }} [o] */ export function cardWordsSize(entry, { width, height }, { follow = false, threaded = false } = {}) { const L = postLayout(entry, { width, height }); const k = height / 1080; const followMin = Math.round(FOLLOW_MIN_SIZE * k); if (threaded) { const own = cardText(entry); const innerW = L.card.width - 2 * L.pad; const innerH = L.card.height - 2 * L.pad; const f = fitSize(own, innerW, innerH - 170 * k, k); return own.trim() ? Math.max(followMin, f.size, f.fits ? 0 : longReadSize(L, { width, height }, true, false) ?? 0) : Math.max(L.size, followMin); } return follow ? Math.max(L.size, longReadSize(L, { width, height }, true) ?? followMin) : L.size; } /** * HOW AN ITEM DRAWS ITS POST, for the join (post-join.mjs) -- what the item after it carries in is drawn alike, pure: * `{ size, plain, headSize }` -- its words' size (cardWordsSize; threaded when its plan is), whether its card is PLAIN * (no thread: its head the card's), else the size its head is drawn at (its words box's, cardWordsSize unthreaded). * `entry` as its segment draws it (its markup, its media scene, the panel rule laid on), `plan` its postItemPlan. * The build draws the item before's page with its OWN join this way (as its segment drew it); Play's route the same. * @param {Record} entry * @param {{ follow?: { thread?: any } | null }} plan * @param {{ width: number, height: number }} box * @param {Record} [render] */ export function joinCarryOf(entry, plan, box, render = undefined) { const follow = followKnobs(entry, render).on; const threaded = follow && !!plan?.follow?.thread; return { size: cardWordsSize(entry, box, { follow, threaded }), plain: !threaded, headSize: threaded ? cardWordsSize(entry, box, { follow }) : null }; } /** * A MEDIA SCENE's earlier message as a tile of a later item's column * (post-media-scene.mjs; postCardHtml's threaded card): drawn as its own post * tile was while it was read -- the repost line, its author (under its own * privacy rule), its words at the size that fits it alone, its counts -- * with its own redaction laid on. `t`: the tile (`scope`, `mode`, `entry`: * its card). * * @param {{ scope: string, mode: string, entry: Record }} t * @param {{ k: number, pal: Record, size: (text: string) => number, redaction?: any, avatars?: Record }} o */ export function sceneTileHtml(t, { k, pal, size, redaction = null, avatars = {} }) { const e = redactEntry(t.entry, redaction); const authors = cardAuthors(e); const blurred = authors.filter((a) => a.redact && a.handle).map((a) => a.handle); const red = (where) => authors.find((a) => a.where === where)?.redact ?? false; const ownRed = red("author"); const own = { author: e.author, handle: e.handle, ...(e.anonymous === true ? { anonymous: true } : {}) }; const words = cardText(e); const n = e.engagement ?? {}; const counts = [["replies", n.replies], ["reposts", n.reposts], ["likes", n.likes], ["quotes", n.quotes]] .filter(([, v]) => fin(v) && v > 0) .map(([k2, v]) => `${countText(v)} ${v === 1 ? String(k2).replace(/ies$/, "y").replace(/s$/, "") : k2}`) .join(""); const repost = e.repostedBy ? `

↻ ${esc(str(e.repostedBy.author) || `@${e.repostedBy.handle}`)} reposted
` : ""; const to = parentsOf(e)[0]?.handle ?? e.replyingTo; const replying = to ? `
Replying to ${red("parents[0]") || red("replyingTo") ? '@xxxxxxxx' : `@${esc(String(to).replace(/^@/, ""))}`}
` : ""; const head = `
${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent, img: avatarUrlOf(avatars, own.handle) })}
${nameHtml(own, { redact: ownRed, cls: "big" })}
${esc(cardDate(e.date))}
${esc(PLATFORM_NAME[e.platform] ?? "")}
`; return `
${repost}${replying}${head}
${wordsHtml(words, blurred)}
${counts ? `
${counts}
` : ""}
`; }