Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit eb5b8b2a5d5b67b532c2c8de806b3d8626a7f28a
parent 7fa0c551f949ceed803661bf77ea02b4808b3e6f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 18:12:15 -0500

umtool: a post as a timeline item -- the model, the duration rule, the privacy rule, validated by the writers and the build

`{type: "post", post: "<channel>/<postId>", …}` (report-to-video/post-item.mjs): an
archived post snapshotted into the cut as an entry of its own, beside clips. Pure and
shared by the build, Play, the writers and the lint: validatePostItem(s), the
duration rule (reading time 1 s + words / 3 wps clamped 3-15 s, each parent and the
quoted post 1.5-6 s, then the attachments in order -- a video its trimmed span, a GIF
looped to >= 3 s, an image 3.5 s, a grid 3.5 + 1 per extra; `hold` overrides), the
plan of what plays when, the layout (text / side / stack), the card's HTML, and the
privacy rule capture-posts applies to a thread parent, applied to every other author
a card draws (blurred unless the subject, gold/grey verified, or redact: false).

The deck: a post item's estimate is the rule, its title its day, its subtitle its
author and platform, its QR the post. A marker, a section and a claim group may hold
a post item as they hold a clip (sectionEdit, patchMarkers, claimGroups,
reanchorAfterRemove, insertIntoIn, validateDeckMarkers). The writers' structure check
and the lint refuse what validatePostItem refuses; insertEntries puts several entries
in in one undoable write; updatePostItem sets a post item's knobs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/lib/report/claimGroups.mjs | 3++-
Mumtool/lib/report/manifest.mjs | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/patchMarkers.mjs | 3++-
Mumtool/lib/report/sectionEdit.mjs | 3++-
Mumtool/lib/report/sections.mjs | 2+-
Mumtool/report-to-video/deck.mjs | 16+++++++++++++---
Mumtool/report-to-video/lint.mjs | 7+++++++
Mumtool/report-to-video/package.json | 2++
Aumtool/report-to-video/post-item.mjs | 693+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/post-item.test.mjs | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10 files changed, 947 insertions(+), 11 deletions(-)

diff --git a/umtool/lib/report/claimGroups.mjs b/umtool/lib/report/claimGroups.mjs @@ -52,7 +52,8 @@ export const GROUP_KEYS = Object.freeze(["id", "section", "claim", "ids"]); const GROUP_ID_RE = /^[A-Za-z0-9_-]{1,64}$/; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); -const isClip = (e) => !!e && (e.kind ?? e.type) === "clip"; +// A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows. +const isClip = (e) => !!e && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post"); const quoted = (s, n = 48) => { const t = String(s ?? ""); return `"${t.length > n ? `${t.slice(0, n - 1)}…` : t}"`; diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -57,6 +57,7 @@ import { variantsProblems, verdictOfInput, } from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; +import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item"; import { parseMuteFrom } from "./playback.mjs"; import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs"; import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources"; @@ -1864,6 +1865,8 @@ function structureErrors(manifest) { ...validateClipBlurEntries(manifest), // Claim groups (claimGroups.mjs): each one's clips together, in one section. ...validateGroups(manifest), + // Post items (post-item.mjs): an archived post as an entry of its own. + ...validatePostItems(manifest), ]; } @@ -1993,7 +1996,8 @@ export function reanchorAfterRemove(m, removed, i) { const chrome = m?.render?.chrome; if (!id || !chrome || typeof chrome !== "object") return notes; const tl = m.timeline ?? []; - const isClip = (e) => e && (e.kind ?? e.type) === "clip"; + // A footage entry: a clip or a post item (a marker may follow either). + const isClip = (e) => e && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post"); const prevClip = [...tl.slice(0, i)].reverse().find(isClip) ?? null; const nextInSection = tl.slice(i).find((e) => isClip(e) && (e.section ?? null) === (removed.section ?? null)) ?? null; const obj = (v) => v && typeof v === "object" && !Array.isArray(v); @@ -2309,6 +2313,90 @@ export async function insertEntry(dir, afterId, spec, { token = null, at = null }, { prepare: (m) => policyWebpage(dir, m, typeof spec === "string" ? parseClipSpec(spec) : spec) })); } +/** + * INSERT SEVERAL ENTRIES IN ONE WRITE (a posts reel, `umtool posts reel`): each + * spec as insertEntry takes it, in order, after `afterId` (null: at the end; + * "" or "-": at the start) -- one structural write, so one undo point and one + * check of what they break together. Returns `{ ids, at, entries }`. + * + * @param {string} dir + * @param {string | null} afterId + * @param {unknown[]} specs + * @param {{ token?: string | null, op?: string }} [opts] + */ +export async function insertEntries(dir, afterId, specs, { token = null, op = "insert" } = {}) { + if (!Array.isArray(specs) || !specs.length) throw new Error("nothing to insert"); + return prepAfter(dir, (r) => r.entries.filter((e) => e.type === "clip").map((e) => e.id), structural(dir, op, token, (m) => { + let i = afterId === null || afterId === undefined ? m.timeline.length : afterId === "" || afterId === "-" ? 0 : entryIndex(m.timeline, afterId) + 1; + const at = i; + const entries = []; + for (const spec of specs) { + const entry = entryFromSpec(m.timeline, spec); + if (entry.type === "post") { + const errors = validatePostItem(entry); + if (errors.length) throw new StructureRefused(errors); + } + m.timeline.splice(i, 0, entry); + entries.push(entry); + i += 1; + } + return { ids: entries.map((e) => e.id), at, entries }; + }, { snapshotEvery: 0 })); +} + +/** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */ +export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact"]); +/** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript. */ +export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words"]); + +/** + * SET A POST ITEM's KNOBS (the post bench, `umtool posts set-item`): `patch` + * is `{ hold?, mediaLayout?, redact?, media?: { <i>: { start?, end?, mute?, + * crop?, push?, words? } } }`; a null clears a knob (the default again). One + * structural write, refused in the build's words (validatePostItem). + * + * @param {string} dir + * @param {string} id + * @param {Record<string, any>} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updatePostItem(dir, id, patch, { token = null } = {}) { + if (!isObj(patch)) throw new Error("a post item's patch is an object"); + for (const k of Object.keys(patch)) { + if (k !== "media" && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media"].join(", ")})`); + } + return structural(dir, "post-item", token, (m) => { + const i = entryIndex(m.timeline, id); + const e = m.timeline[i]; + if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`); + const set = (o, k, v) => { + if (v === null || v === undefined) delete o[k]; + else o[k] = typeof v === "number" ? round2(v) : v; + }; + for (const k of POST_ITEM_KNOBS) if (k in patch) set(e, k, patch[k]); + if (isObj(patch.media)) { + const media = Array.isArray(e.media) ? e.media : []; + for (const [key, mp] of Object.entries(patch.media)) { + const n = Number(key); + if (!Number.isInteger(n) || !media[n]) throw new Error(`${id} has no attachment ${key} (0–${media.length - 1})`); + if (!isObj(mp)) throw new Error(`media.${key} is an object of knobs`); + for (const k of Object.keys(mp)) if (!POST_MEDIA_KNOBS.includes(k)) throw new Error(`media.${key}.${k} is not an attachment knob (${POST_MEDIA_KNOBS.join(", ")})`); + for (const k of POST_MEDIA_KNOBS) { + if (!(k in mp)) continue; + if (k === "crop" && Array.isArray(mp.crop)) media[n].crop = mp.crop.map((v) => Math.round(Number(v) * 10000) / 10000); + else set(media[n], k, mp[k]); + } + // A trim back to the whole file is no trim. + if (media[n].start === 0) delete media[n].start; + if (Number.isFinite(media[n].seconds) && Number.isFinite(media[n].end) && Math.abs(media[n].end - media[n].seconds) < 0.02) delete media[n].end; + } + } + const errors = validatePostItem(e); + if (errors.length) throw new StructureRefused(errors); + return { id, at: i, entry: e }; + }); +} + // ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) ----------- /** @@ -2391,10 +2479,10 @@ export function insertIntoIn(m, spec, { section = null, group = null } = {}) { if (!Array.isArray(m.timeline)) m.timeline = []; const tl = m.timeline; const entry = entryFromSpec(tl, spec); - if (entry.type !== "clip") throw new Error("only a clip goes into a section or a group"); + if (entry.type !== "clip" && entry.type !== "post") throw new Error("only a clip or a post item goes into a section or a group"); const hasDeck = isObj(m?.render?.chrome); const model = sectionModel(m); - const at = (id) => tl.findIndex((e) => e?.type === "clip" && e.id === id); + const at = (id) => tl.findIndex((e) => (e?.type === "clip" || e?.type === "post") && e.id === id); let target; let after; let g = null; @@ -2420,7 +2508,7 @@ export function insertIntoIn(m, spec, { section = null, group = null } = {}) { if (!after) throw new Error(`${sectionWords(model.sections[t])} has no clip to go after`); } else { if (!Number.isInteger(t) || t < 0) throw new Error("section is a section's number, 0 or more"); - const last = [...tl].reverse().find((e) => e?.type === "clip" && (Number.isInteger(e.section) ? e.section : 0) === t); + const last = [...tl].reverse().find((e) => (e?.type === "clip" || e?.type === "post") && (Number.isInteger(e.section) ? e.section : 0) === t); if (!last) throw new Error(`no clip of the cut is in section ${t} (this cut has no deck: its sections are the clips' \`section\` field)`); after = last.id; } diff --git a/umtool/lib/report/patchMarkers.mjs b/umtool/lib/report/patchMarkers.mjs @@ -27,7 +27,8 @@ import path from "node:path"; export const PATCH_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); -const isClip = (e) => isObj(e) && (e.kind ?? e.type) === "clip"; +// A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows. +const isClip = (e) => isObj(e) && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post"); /** The project's take patches: `*.patch.json` beside the manifest, by name. */ export async function patchFilesOf(dir) { diff --git a/umtool/lib/report/sectionEdit.mjs b/umtool/lib/report/sectionEdit.mjs @@ -30,7 +30,8 @@ // leave one first is refused in those words. const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); -const isClip = (e) => !!e && (e.kind ?? e.type) === "clip"; +// A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows. +const isClip = (e) => !!e && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post"); /** The deck's markers as written (an array, maybe empty), or null without a deck. */ function deckMarkers(m) { diff --git a/umtool/lib/report/sections.mjs b/umtool/lib/report/sections.mjs @@ -29,7 +29,7 @@ export function sectionEnterFlags(timeline) { let prev; return (timeline ?? []).map((e) => { - if (e?.type !== "clip") return false; + if (e?.type !== "clip" && e?.type !== "post") return false; const s = e.section; const enters = s !== undefined && s !== null && s !== prev; prev = s; diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -21,7 +21,8 @@ import { gappedLength, offsetIn, recordGaps, renderGaps } from "./gaps.mjs"; import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs"; import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs"; -import { attributionParts, deckSubtitle, deckSubtitleLines } from "./attribution.mjs"; +import { attributionParts, deckSubtitle, deckSubtitleLines, formatDeckDate } from "./attribution.mjs"; +import { postDeckText, postItemSeconds } from "./post-item.mjs"; import { claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck, } from "./factcheck.mjs"; @@ -230,13 +231,13 @@ export function validateDeckMarkers(manifest) { const hit = timeline.find((e) => e?.id === m.after.trim()); const where = `render.chrome.deck.markers[${i}].after`; if (!hit) errors.push(`${where} names ${m.after}, which is not in the timeline`); - else if (hit.type !== "clip") errors.push(`${where} names ${m.after}, a ${hit.type ?? "entry"}: a marker follows a clip`); + else if (hit.type !== "clip" && hit.type !== "post") errors.push(`${where} names ${m.after}, a ${hit.type ?? "entry"}: a marker follows a clip or a post item`); }); // A subsection (`level: 2`) sits inside the section before it, so the // first boundary of the cut -- by where it stands, not where it is listed // -- opens a section. One refusal, naming the marker. const pos = new Map(); - timeline.forEach((e, i) => { if (e?.type === "clip" && !pos.has(e.id)) pos.set(e.id, i); }); + timeline.forEach((e, i) => { if ((e?.type === "clip" || e?.type === "post") && !pos.has(e.id)) pos.set(e.id, i); }); const first = markers .map((m, i) => ({ m, i, p: isObj(m) && typeof m.after === "string" ? pos.get(m.after.trim()) : undefined })) .filter((x) => x.p !== undefined) @@ -960,6 +961,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render)) return Math.max(1, gappedLength(from, to, renderGaps(entry, render))); } if (entry.type === "image") return Number(entry.seconds ?? 4); + // A post item (post-item.mjs): its reading time and its attachments, or its `hold`. + if (entry.type === "post") return postItemSeconds(entry); // The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default). if (entry.type === "intro") return Number(entry.seconds ?? INTRO_SECONDS); // A teaser's dip makes its segment longer by the dissolve and the black (`teaserLead`). @@ -1051,6 +1054,11 @@ export function deckText(entry, meta, provenance, deck, multiChannel) { // the cut (umtool's On-screen rows, the schedule) names it by. if (!title) title = teaserTitle(entry); subtitle = ""; + } else if (entry.type === "post") { + // A post item: its day as the deck's date, its author and platform under it. + const t = postDeckText(entry, (d) => formatDeckDate(d, deck.subtitle?.dateFormat ?? "long")); + if (!title) title = t.title; + subtitle = t.subtitle; } else if (entry.type === "image") { const parts = { channel: "", title: String(entry.title ?? "").trim(), date: String(entry.date ?? "").trim(), at: null }; const opts = { ...deck.subtitle, parts: ["title", "date"] }; @@ -1088,6 +1096,8 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin return original ?? archiveMomentUrl(entry, provenance, entry.start); } if (entry.type === "image") return entry.citeUrl ?? null; + // A post item: the post's own page, or its archive's (postQrUrl, the posts' `links` rule). + if (entry.type === "post") return entry.citeUrl ?? (entry.url ? postQrUrl({ ...entry, postId: String(entry.post ?? "").split("/")[1] }, provenance, { links: links === "original" ? "original" : "archive" }) : null); return null; } diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs @@ -84,6 +84,7 @@ import { validateClaims } from "./factcheck.mjs"; import { validateClipAudioEntries } from "./clip-audio.mjs"; import { validateClipBlurEntries } from "./clip-blur.mjs"; import { validateGapEntries } from "./gaps.mjs"; +import { postItemFiles, validatePostItems } from "./post-item.mjs"; import { validateFinaleEntries } from "./finale.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; @@ -249,6 +250,10 @@ export function originQrsOf(manifest, { only = null, metaOf = null } = {}) { export function imageSrcsOf(manifest, { only = null } = {}) { const out = []; for (const e of manifest.timeline ?? []) { + if (e?.type === "post" && (!only || e.id === only)) { + out.push(...postItemFiles(e)); + continue; + } if (e?.type !== "image" || (only && e.id !== only)) continue; if (typeof e.src === "string") out.push({ where: `timeline ${e.id}`, src: e.src }); if (Array.isArray(e.panels)) { @@ -314,6 +319,8 @@ export function validatorErrors(whole) { ...validateClipBlurEntries(whole), // Seconds taken out of a clip's middle (gaps.mjs). ...validateGapEntries(whole), + // A post as a timeline item (post-item.mjs): its archived words, its attachments, its hold. + ...validatePostItems(whole), ]; if (deckOn(whole.render)) { errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`)); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -59,6 +59,8 @@ "./package.json": "./package.json", "./pauses": "./pauses.mjs", "./post-links": "./post-links.mjs", + "./post-item": "./post-item.mjs", + "./post-render": "./post-render.mjs", "./presets": "./presets.mjs", "./prune-frames": "./prune-frames.mjs", "./render-cards": "./render-cards.mjs", diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs @@ -0,0 +1,693 @@ +// 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: "<channel>/<postId>", +// platform, author, handle, date, text, url, engagement?, +// repostedBy?: { author, handle }, quoted?: <ref>, parents?: [<ref>, …], +// replyingTo?: "<handle>", parentShot?: "<file>", +// media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?, +// start?, end?, mute?, crop?: [x, y, w, h], push?, words? }], +// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen? } +// +// where a <ref> (a post it quotes, the posts it answers, nearest first) is +// `{ id?, author?, handle?, badge?, date?, text?, url? }`. 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. + +/** 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"]); + +/** + * 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) + * 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.5, max: 6 }); +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. */ +export const POST_PARENTS_MAX = 2; +/** 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) : []); + +/** Seconds to read the post itself (the rule above, its first line). */ +export function readSeconds(entry) { + return clamp(POST_READ.lead + wordCount(cardText(entry)) / POST_READ.wps, POST_READ.min, POST_READ.max); +} + +/** Seconds to read one post of its context (a parent, the quoted post). */ +export function contextReadSeconds(ref) { + return clamp(wordCount(ref?.text) / POST_READ.wps, POST_CONTEXT_READ.min, POST_CONTEXT_READ.max); +} + +/** The whole reading time: the post and its context. */ +export function readingSeconds(entry) { + let s = readSeconds(entry); + for (const p of parentsOf(entry)) s += contextReadSeconds(p); + if (isObj(entry?.quoted)) s += contextReadSeconds(entry.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. */ +export function mediaSteps(entry) { + const media = Array.isArray(entry?.media) ? 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 item's length by the rule, before `hold`. */ +export function ruleSeconds(entry) { + return round3(readingSeconds(entry) + mediaSteps(entry).reduce((n, s) => n + s.seconds, 0)); +} + +/** The item's length in the cut: `hold` when it is set, else the rule. */ +export function postItemSeconds(entry) { + return fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : ruleSeconds(entry); +} + +/** + * WHAT PLAYS WHEN inside a post item, in its own seconds (0 is its first + * frame): the reading span, then each step of the attachments. 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. With `hold` the plan + * is cut (or extended) to it: a step past the end is dropped, the last one + * cut at it; a longer hold holds the last step up (`held`). Both the render + * and Play the cut play this plan. + * + * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number }} + */ +export function postItemPlan(entry) { + const reading = readingSeconds(entry); + const total = postItemSeconds(entry); + const steps = []; + let at = reading; + for (const s of mediaSteps(entry)) { + 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; + } + // A text-only post reads for the whole; one with attachments holds its last up to `hold`. + const held = steps.length ? round3(Math.max(0, total - at)) : 0; + return { reading: round3(Math.min(reading, total)), total, steps, held }; +} + +/** 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") { + 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. + * + * @param {{ handle?: string|null, badge?: string|null }} who + * @param {{ subjects?: string[], redact?: boolean }} [o] + * @returns {{ redact: boolean, reason: "off"|"forced"|"subject"|"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 (!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: its own author and the account that reposted it. */ +export const subjectsOf = (entry) => [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 = []; + 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) }); + 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(", ")}`); + if (typeof r.text === "string" && r.text.length > TEXT_MAX) errors.push(`${where}.text is longer than ${TEXT_MAX} characters`); + 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 <channel>/<postId>, 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 (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`)); + 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 post it answers and its parent)`); + e.parents.forEach((p, i) => errors.push(...refErrors(p, `${w}.parents[${i}]`))); + } + } + 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.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.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}]`))); + } + } + 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.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); + } + 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)); + 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 }); + 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]); +/** 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); + const words = cardText(entry); + // What the card spends besides the words: its head (avatar, name, date), its counts, the context. + const context = 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) { + 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 }; + } + const cardW = Math.round((width - 3 * pad) * 0.42); + const side = fitSize(words, cardW - 2 * pad, height - 4 * pad - chrome, k); + if (side.fits && side.size >= POST_SIDE_MIN * k) { + 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", card, slot, strip: null, size: side.size, fits: true, 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 }; +} + +/** + * 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 }; + }); +} + +const esc = (s) => + String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;"); + +function rgb(hex) { + const h = String(hex ?? "#000").replace("#", ""); + const f = h.length === 3 ? h.split("").map((c) => c + c).join("") : h.padEnd(6, "0").slice(0, 6); + return [0, 2, 4].map((i) => parseInt(f.slice(i, i + 2), 16) || 0); +} +/** Palette colour `a` toward `b` by `t`. */ +export function mixHex(a, b, t) { + const x = rgb(a); + const y = rgb(b); + return `#${x.map((v, i) => Math.round(v + (y[i] - v) * t).toString(16).padStart(2, "0")).join("")}`; +} +const rgbaOf = (hex, a) => `rgba(${rgb(hex).join(", ")}, ${a})`; + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +/** The card's date line: "Oct 30, 2026 · 04:00 UTC" (UTC: the same card on every machine). */ +export function cardDate(iso) { + const d = new Date(String(iso ?? "")); + if (Number.isNaN(d.getTime())) return ""; + const hh = String(d.getUTCHours()).padStart(2, "0"); + const mm = String(d.getUTCMinutes()).padStart(2, "0"); + return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()} · ${hh}:${mm} UTC`; +} +/** The post's calendar day, `YYYY-MM-DD` (UTC), for the deck's date. */ +export const postDay = (iso) => { + const d = new Date(String(iso ?? "")); + return Number.isNaN(d.getTime()) ? "" : d.toISOString().slice(0, 10); +}; +/** A count as X prints it: 999, 1.2K, 34K, 1.1M. */ +export function countText(n) { + if (!fin(n)) return ""; + if (n < 1000) return String(n); + if (n < 10000) return `${(n / 1000).toFixed(1).replace(/\.0$/, "")}K`; + if (n < 1e6) return `${Math.round(n / 1000)}K`; + return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`; +} +const PLATFORM_NAME = { x: "X", bluesky: "Bluesky", web: "Web" }; + +/** The deck's title and subtitle for a post item (deck.mjs deckText). */ +export function postDeckText(entry, formatDate = (d) => d) { + const who = [str(entry?.author), entry?.handle ? `@${String(entry.handle).replace(/^@/, "")}` : ""].filter(Boolean).join(" "); + const verb = entry?.repostedBy ? "reposted on" : parentsOf(entry).length || entry?.replyingTo ? "replying on" : "on"; + return { + title: formatDate(postDay(entry?.date)), + subtitle: `${who} ${verb} ${PLATFORM_NAME[entry?.platform] ?? "the web"}`.trim(), + }; +} + +const hueOf = (s) => { + let h = 0; + for (const c of String(s ?? "")) h = (h * 31 + c.charCodeAt(0)) % 360; + return h; +}; + +/** The words with @mentions of the blurred authors blurred (their handle never in the page). */ +function wordsHtml(text, blurred) { + const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase())); + return esc(text) + .replace(/@([A-Za-z0-9_]{1,30})/g, (m, h) => (set.has(h.toLowerCase()) ? `<span class="redact">@${"x".repeat(Math.max(4, Math.min(12, h.length)))}</span>` : `<span class="mention">${m}</span>`)) + .replace(/https?:\/\/\S+/g, (u) => `<span class="link">${u.length > 48 ? `${u.slice(0, 46)}…` : u}</span>`) + .replace(/\n/g, "<br>"); +} + +function avatarHtml(who, { redact, size, accent }) { + const name = str(who?.author) || str(who?.handle) || "?"; + const initial = esc((name.replace(/^@/, "")[0] ?? "?").toUpperCase()); + const bg = accent ?? `hsl(${hueOf(who?.handle)}, 38%, 42%)`; + return `<div class="avatar${redact ? " redact" : ""}" style="width:${size}px;height:${size}px;font-size:${Math.round(size * 0.46)}px;background:${bg}">${redact ? "" : initial}</div>`; +} + +function nameHtml(who, { redact, cls = "" }) { + if (redact) return `<span class="who ${cls}"><span class="name redact">xxxxxxxxxxxx</span> <span class="handle redact">@xxxxxxxx</span></span>`; + const h = str(who?.handle).replace(/^@/, ""); + return `<span class="who ${cls}"><span class="name">${esc(str(who?.author) || h)}</span>${h ? ` <span class="handle">@${esc(h)}</span>` : ""}</span>`; +} + +/** + * The card's HTML: one page `width` × `height` (the box the item fills), the + * card drawn in the deck's palette and faces, the attachments' slot left as a + * well for the media to be laid into (the build overlays the files; Play the + * cut lays its elements over the same box). `phase` "read" draws the card; + * "media" in a stack layout the strip over the slot. `fonts` are urls for + * the regular and bold faces; with none, the page falls back to sans-serif. + * `parentShotUrl`: the capture's thread shot, drawn as the context when the + * post it answers is not archived. + * + * @param {Record<string, any>} entry + * @param {{ width: number, height: number, palette?: Record<string, string>, fonts?: { regular?: string, bold?: string }, + * phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean }} o + */ +export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false }) { + const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette }; + const L = postLayout(entry, { width, height }); + const k = height / 1080; + const size = L.size; + const authors = cardAuthors(entry); + 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 cardBg = mixHex(pal.bg, pal.fg, 0.07); + const line = mixHex(pal.bg, pal.fg, 0.18); + const own = { author: entry.author, handle: entry.handle }; + const strip = phase === "media" && L.mode === "stack"; + const e = entry.engagement ?? {}; + const counts = [["replies", e.replies], ["reposts", e.reposts], ["likes", e.likes], ["quotes", e.quotes]] + .filter(([, v]) => fin(v) && v > 0) + .map(([k2, v]) => `<span class="count"><b>${countText(v)}</b> ${k2 === "replies" && v === 1 ? "reply" : k2 === "reposts" && v === 1 ? "repost" : k2 === "likes" && v === 1 ? "like" : k2 === "quotes" && v === 1 ? "quote" : k2}</span>`) + .join(""); + const ctx = []; + // The posts it answers, oldest first, a thread line down to the post. + const parents = parentsOf(entry); + for (let i = parents.length - 1; i >= 0; i -= 1) { + const p = parents[i]; + const r = red(`parents[${i}]`); + ctx.push( + `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k) })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span></div><div class="ptext">${wordsHtml(str(p.text) || (p.url ? "(not archived)" : ""), blurred)}</div></div></div>`, + ); + } + if (!parents.length && parentShotUrl) ctx.push(`<div class="pshot" data-post-parent-shot=""><img src="${esc(parentShotUrl)}" alt=""></div>`); + else if (!parents.length && entry.replyingTo) { + ctx.push(`<div class="replying" data-post-replying="">Replying to ${red("replyingTo") ? '<span class="redact">@xxxxxxxx</span>' : `<span class="mention">@${esc(String(entry.replyingTo).replace(/^@/, ""))}</span>`}</div>`); + } + const q = isObj(entry.quoted) ? entry.quoted : null; + const quoted = q + ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span></div><div class="qtext">${wordsHtml(str(q.text), blurred)}</div></div>` + : ""; + const repost = entry.repostedBy + ? `<div class="repost" data-post-repost="">&#x21bb; ${esc(str(entry.repostedBy.author) || `@${entry.repostedBy.handle}`)} reposted</div>` + : ""; + const head = `<div class="head">${avatarHtml(own, { redact: false, size: Math.round(64 * k), accent: pal.accent })}<div class="hwho">${nameHtml(own, { redact: false, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`; + const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;top:${box.y}px;width:${box.width}px;height:${box.height}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words" data-post-words="" style="font-size:${size}px">${wordsHtml(cardText(entry), blurred)}</div>${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`; + const stripHtml = L.strip + ? `<div class="strip" data-post-strip="" style="left:${L.strip.x}px;top:${L.strip.y}px;width:${L.strip.width}px;height:${L.strip.height}px">${avatarHtml(own, { redact: false, size: Math.round(56 * k), accent: pal.accent })}<div class="hwho">${nameHtml(own, { redact: false, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="sline">${wordsHtml(cardText(entry).split("\n")[0].slice(0, 140) + (cardText(entry).length > 140 ? "…" : ""), blurred)}</div></div>` + : ""; + const slot = L.slot && (L.mode === "side" || strip) ? `<div class="slot" data-post-slot="" style="left:${L.slot.x}px;top:${L.slot.y}px;width:${L.slot.width}px;height:${L.slot.height}px"></div>` : ""; + const body = strip ? `${stripHtml}${slot}` : `${card(L.card)}${slot}`; + const minSize = Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k); + return `<!doctype html> +<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=${width}, height=${height}"> +<style> +@font-face { font-family: 'PostSans'; src: url('${esc(fonts.regular ?? "")}'); } +@font-face { font-family: 'PostSansBold'; src: url('${esc(fonts.bold ?? "")}'); } +* { margin: 0; padding: 0; box-sizing: border-box; } +html, body { width: ${width}px; height: ${height}px; overflow: hidden; background: ${transparent ? "transparent" : pal.bg}; } +body { position: relative; font-family: 'PostSans', sans-serif; color: ${pal.fg}; -webkit-font-smoothing: antialiased; font-synthesis: none; } +b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; } +.card, .strip, .slot { position: absolute; } +.card { display: flex; flex-direction: column; justify-content: center; gap: ${Math.round(18 * k)}px; padding: ${L.pad}px; background: ${cardBg}; border: 1px solid ${line}; border-radius: ${Math.round(18 * k)}px; overflow: hidden; } +.repost { color: ${pal.muted}; font-size: ${Math.round(22 * k)}px; } +.head, .strip { display: flex; align-items: center; gap: ${Math.round(16 * k)}px; } +.strip { padding: 0 ${Math.round(20 * k)}px; background: ${cardBg}; border: 1px solid ${line}; border-radius: ${Math.round(14 * k)}px; } +.hwho { display: flex; flex-direction: column; min-width: 0; } +.who.big .name { font-size: ${Math.round(30 * k)}px; } +.who.big .handle { font-size: ${Math.round(24 * k)}px; } +.who .name { font-size: ${Math.round(22 * k)}px; color: ${pal.fg}; } +.who .handle { font-size: ${Math.round(19 * k)}px; color: ${pal.muted}; } +.date { color: ${pal.muted}; font-size: ${Math.round(20 * k)}px; margin-top: ${Math.round(2 * k)}px; } +.mark { margin-left: auto; font-size: ${Math.round(30 * k)}px; color: ${pal.muted}; } +.avatar { flex: none; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-family: 'PostSansBold', sans-serif; } +.words { line-height: ${LINE}; overflow-wrap: anywhere; flex: 0 1 auto; min-height: 0; overflow: hidden; } +.sline { margin-left: ${Math.round(12 * k)}px; color: ${pal.fg}; font-size: ${Math.round(24 * k)}px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; } +.mention, .link { color: ${pal.accent}; } +.context { display: flex; flex-direction: column; gap: ${Math.round(10 * k)}px; } +.parent { display: flex; gap: ${Math.round(14 * k)}px; position: relative; padding-bottom: ${Math.round(6 * k)}px; } +.parent::after { content: ""; position: absolute; left: ${Math.round(21 * k)}px; top: ${Math.round(50 * k)}px; bottom: -${Math.round(6 * k)}px; width: 2px; background: ${line}; } +.pbody { min-width: 0; flex: 1; } +.phead { display: flex; align-items: baseline; gap: ${Math.round(10 * k)}px; } +.pdate { color: ${pal.muted}; font-size: ${Math.round(18 * k)}px; } +.ptext, .qtext { font-size: ${Math.round(22 * k)}px; line-height: 1.3; color: ${mixHex(pal.fg, pal.bg, 0.15)}; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; overflow-wrap: anywhere; } +.qtext { -webkit-line-clamp: 5; margin-top: ${Math.round(8 * k)}px; } +.quoted { border: 1px solid ${line}; border-radius: ${Math.round(14 * k)}px; padding: ${Math.round(16 * k)}px; } +.quoted .avatar { display: inline-flex; } +.pshot img { max-width: 100%; max-height: ${Math.round(240 * k)}px; border-radius: ${Math.round(10 * k)}px; display: block; } +.replying { color: ${pal.muted}; font-size: ${Math.round(21 * k)}px; } +.counts { display: flex; gap: ${Math.round(24 * k)}px; color: ${pal.muted}; font-size: ${Math.round(21 * k)}px; border-top: 1px solid ${line}; padding-top: ${Math.round(14 * k)}px; flex: none; } +.counts b { color: ${pal.fg}; } +.redact { filter: blur(${Math.round(9 * k)}px); color: ${pal.muted}; } +.avatar.redact { background: ${rgbaOf(pal.muted, 0.6)} !important; } +.slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; } +</style></head> +<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${body} +<script> +// The words at the layout's size, shrunk while they overflow (the browser +// knows how they wrap; the layout only estimated it). Then say so. +(function () { + var w = document.querySelector('[data-post-words]'); + var min = ${minSize}; + function fit() { + if (w) { var s = parseFloat(w.style.fontSize); while (w.scrollHeight > w.clientHeight + 1 && s > min) { s -= 1; w.style.fontSize = s + 'px'; } } + document.body.setAttribute('data-post-ready', '1'); + } + if (document.fonts && document.fonts.ready) document.fonts.ready.then(fit); else fit(); +})(); +</script></body></html>`; +} diff --git a/umtool/report-to-video/post-item.test.mjs b/umtool/report-to-video/post-item.test.mjs @@ -0,0 +1,133 @@ +// post-item.mjs: a post as a timeline item -- the validator, the duration +// rule, the plan of what plays when, the privacy rule and the layout. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + POST_GIF, POST_IMAGE_SECONDS, POST_READ, authorRedaction, cardAuthors, cardText, mediaSeconds, mediaTimeAt, postCardHtml, + postDeckText, postItemPlan, postItemSeconds, postLayout, readingSeconds, ruleSeconds, stepAt, stepBoxes, validatePostItem, wordCount, +} from "./post-item.mjs"; +import { deckText, estimatedDuration, deckQrUrl, resolveDeck, validateDeckMarkers } from "./deck.mjs"; + +const base = (o = {}) => ({ + type: "post", id: "p1", post: "someone-x/2116017249706225668", platform: "x", + author: "MR. OBVIOUS", handle: "ObviousRises", date: "2026-10-30T04:00:00.000Z", + text: "one two three four five six", url: "https://x.com/ObviousRises/status/2116017249706225668", ...o, +}); +const video = (o = {}) => ({ src: "posts-media/someone-x/1/1_1.mp4", kind: "video", seconds: 6.2, width: 1920, height: 1080, audio: true, ...o }); +const image = (o = {}) => ({ src: "posts-media/someone-x/1/1_1.jpg", kind: "image", width: 1200, height: 900, ...o }); + +test("a valid post item passes; each field is refused in words", () => { + assert.deepEqual(validatePostItem(base({ media: [video(), image()], engagement: { likes: 3 } })), []); + const bad = validatePostItem(base({ post: "nope", platform: "myspace", date: "soon", hold: 0.2, media: [video({ src: "/abs.mp4" }), image({ start: 1 }), { src: "a.png", kind: "sound" }] })); + assert.ok(bad.some((e) => e.includes(".post must be <channel>/<postId>"))); + assert.ok(bad.some((e) => e.includes(".platform must be one of"))); + assert.ok(bad.some((e) => e.includes(".date must be"))); + assert.ok(bad.some((e) => e.includes(".hold must be 1–120"))); + assert.ok(bad.some((e) => e.includes("media[0].src must be relative"))); + assert.ok(bad.some((e) => e.includes("media[1].start: only a video or a GIF is trimmed"))); + assert.ok(bad.some((e) => e.includes("media[2].kind must be one of"))); + assert.ok(validatePostItem(base({ media: [video({ start: 3, end: 3.2 })] })).some((e) => e.includes("at least 0.5 s after start"))); + assert.ok(validatePostItem(base({ media: [video({ end: 9 })] })).some((e) => e.includes("a second inside it"))); + assert.ok(validatePostItem(base({ media: [video({ crop: [0.5, 0, 0.6, 1] })] })).some((e) => e.includes(".crop must be"))); + assert.ok(validatePostItem(base({ parents: [{}, {}, {}] })).some((e) => e.includes("at most 2"))); + assert.ok(validatePostItem(base({ media: [video(), video(), video(), video(), video()] })).some((e) => e.includes("at most 4 attachments"))); +}); + +test("the duration rule: reading time (words / wps + lead, clamped) plus the attachments; hold overrides", () => { + assert.equal(wordCount(" a b\nc "), 3); + // Six words: 1 + 6/3 = 3 s (the floor). + assert.equal(readingSeconds(base()), POST_READ.min); + const long = base({ text: Array.from({ length: 30 }, () => "w").join(" ") }); + assert.equal(readingSeconds(long), POST_READ.lead + 30 / POST_READ.wps); + assert.equal(readingSeconds(base({ text: Array.from({ length: 900 }, () => "w").join(" ") })), POST_READ.max); + // A repost's "RT @x: " is its reposted line, not words to read. + assert.equal(cardText(base({ text: "RT @ObviousRises: hello there", repostedBy: { handle: "ObviousRises" } })), "hello there"); + // A parent and a quote add their own reading, clamped 1.5–6. + assert.equal(readingSeconds(base({ parents: [{ text: "a" }], quoted: { text: Array.from({ length: 60 }, () => "q").join(" ") } })), 3 + 1.5 + 6); + // Attachments in sequence. + assert.equal(mediaSeconds(video({ start: 1, end: 4 })), 3); + assert.equal(mediaSeconds(image()), POST_IMAGE_SECONDS); + assert.equal(mediaSeconds({ kind: "gif", seconds: 1.2 }), 3.6); // looped to ≥ 3 s: three passes + assert.equal(mediaSeconds({ kind: "gif", seconds: 25 }), POST_GIF.max); + assert.equal(ruleSeconds(base({ media: [video(), image()] })), 3 + 6.2 + 3.5); + assert.equal(postItemSeconds(base({ media: [video()], hold: 5 })), 5); + // A grid of images is one step: 3.5 + 1 per extra. + assert.equal(ruleSeconds(base({ mediaLayout: "grid", media: [image(), image(), image()] })), 3 + 5.5); + // The deck's estimate is the rule. + assert.equal(estimatedDuration(base({ media: [video()] })), 9.2); +}); + +test("the plan: the words first, then each attachment; a hold cuts it short or holds the last", () => { + const p = postItemPlan(base({ media: [video({ start: 1, end: 3 }), image()] })); + assert.equal(p.reading, 3); + assert.equal(p.total, 3 + 2 + 3.5); + assert.deepEqual(p.steps.map((s) => [s.kind, s.at, s.seconds]), [["video", 3, 2], ["image", 5, 3.5]]); + assert.equal(p.steps[0].srcFrom, 1); + assert.equal(p.steps[0].srcTo, 3); + assert.equal(p.steps[0].sound, true); + assert.equal(stepAt(p, 1), null); + assert.equal(stepAt(p, 4).kind, "video"); + assert.equal(mediaTimeAt(p.steps[0], 4), 2); + const cut = postItemPlan(base({ media: [video(), image()], hold: 5 })); + assert.deepEqual(cut.steps.map((s) => [s.kind, s.seconds]), [["video", 2]]); + assert.equal(cut.steps[0].srcTo, 2); + const held = postItemPlan(base({ media: [image()], hold: 12 })); + assert.equal(held.held, 12 - 6.5); + assert.equal(postItemPlan(base({ media: [video({ mute: true })] })).steps[0].sound, false); + const gif = postItemPlan(base({ media: [{ src: "g.mp4", kind: "gif", seconds: 1.2 }] })); + assert.equal(gif.steps[0].loop, true); + assert.equal(mediaTimeAt(gif.steps[0], 3 + 1.5), 0.3); +}); + +test("the privacy rule: another author is blurred unless the subject, gold/grey verified, or redact:false", () => { + assert.deepEqual(authorRedaction({ handle: "someone" }, { subjects: ["ObviousRises"] }), { redact: true, reason: "private" }); + assert.deepEqual(authorRedaction({ handle: "obviousrises" }, { subjects: ["ObviousRises"] }), { redact: false, reason: "subject" }); + assert.deepEqual(authorRedaction({ handle: "NASA", badge: "gold" }), { redact: false, reason: "verified" }); + assert.deepEqual(authorRedaction({ handle: "WhiteHouse", badge: "grey" }), { redact: false, reason: "verified" }); + assert.deepEqual(authorRedaction({ handle: "bought", badge: "blue" }), { redact: true, reason: "blue-check" }); + assert.deepEqual(authorRedaction({ handle: "x" }, { redact: false }), { redact: false, reason: "off" }); + assert.deepEqual(authorRedaction({ handle: "NASA", badge: "gold" }, { redact: true }), { redact: true, reason: "forced" }); + assert.deepEqual(authorRedaction({}), { redact: true, reason: "unknown" }); + const e = base({ text: "@KacamnGamesYT you are wrong", parents: [{ handle: "KacamnGamesYT", author: "Kacamn", text: "a question" }] }); + assert.deepEqual(cardAuthors(e).map((a) => [a.where, a.redact]), [["parents[0]", true]]); + const html = postCardHtml(e, { width: 1440, height: 810 }); + // The parent's name and handle are never in the page, and the mention of them is blurred. + assert.ok(!html.includes("KacamnGamesYT")); + assert.ok(!html.includes("Kacamn")); + assert.ok(html.includes("a question")); + assert.ok(html.includes('data-redacted=""')); + // A self-thread (his own parent) is drawn plainly. + const self = postCardHtml(base({ parents: [{ handle: "ObviousRises", author: "MR. OBVIOUS", text: "first" }] }), { width: 1440, height: 810 }); + assert.ok(!self.includes('data-redacted=""')); + // "Replying to" with no parent archived. + assert.ok(postCardHtml(base({ replyingTo: "private_person" }), { width: 1440, height: 810 }).includes("Replying to <span class=\"redact\">")); +}); + +test("the layout: text alone; the words beside the attachments when they fit; else read first, then the media large", () => { + const box = { width: 1440, height: 810 }; + assert.equal(postLayout(base(), box).mode, "text"); + const side = postLayout(base({ media: [video()] }), box); + assert.equal(side.mode, "side"); + assert.ok(side.slot.x > side.card.x + side.card.width); + const words = Array.from({ length: 480 }, () => "word").join(" "); + const stack = postLayout(base({ text: words, media: [video()] }), box); + assert.equal(stack.mode, "stack"); + assert.ok(stack.strip && stack.slot.y > stack.strip.y); + // A media box keeps its aspect inside the slot; a grid of two lays them side by side. + const [b] = stepBoxes({ items: [{ i: 0, width: 1920, height: 1080 }] }, side.slot); + assert.ok(Math.abs(b.width / b.height - 16 / 9) < 0.02); + const two = stepBoxes({ items: [{ i: 0, width: 100, height: 100 }, { i: 1, width: 100, height: 100 }] }, { x: 0, y: 0, width: 412, height: 200 }); + assert.ok(two[1].x > two[0].x + two[0].width); +}); + +test("the deck: a post item's date is its title, its author and platform the subtitle; its QR the post", () => { + const deck = resolveDeck({ chrome: { engine: "hyperframes", layout: "deck" } }); + const t = deckText(base(), null, {}, deck, false); + assert.equal(t.title, "Oct 30, 2026"); + assert.equal(t.subtitle, "MR. OBVIOUS @ObviousRises on X"); + assert.equal(postDeckText(base({ repostedBy: { handle: "ObviousRises" } })).subtitle, "MR. OBVIOUS @ObviousRises reposted on X"); + assert.equal(deckQrUrl(base(), {}, { links: "original" }), base().url); + // A marker may follow a post item. + const m = { render: { chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "p1", label: "Then" }] } } }, timeline: [base(), { ...base(), id: "p2" }] }; + assert.deepEqual(validateDeckMarkers(m), []); +});