import { readFile } from "node:fs/promises"; import type { Page } from "puppeteer-core"; import { join } from "node:path"; import { AUDIT_SEEK_OPTIONS, openSettledCompositionPage, SCREENSHOT_SEEK_OPTIONS, type PrelaunchedBrowser, prelaunchCompositionBrowser, seekCompositionTimeline, } from "../capture/captureCompositionFrame.js"; import { bundleWithLocalizedFonts } from "../utils/bundleWithLocalizedFonts.js"; import { createPageDriver } from "../utils/checkBrowser.js"; type PageDriver = ReturnType; import type { AnchoredLayoutIssue } from "../utils/checkTypes.js"; import type { LayoutOverflow } from "../utils/layoutAudit.js"; import { serveStaticProjectHtml } from "../utils/staticProjectServer.js"; import { round } from "./json.js"; import { type FramedAt, framesInPage } from "./layoutFrame.js"; import { type Overlap, overlapsInPage } from "./layoutOverlap.js"; import { spillsInPage } from "./layoutSpill.js"; import { type Heard, shownInPage, shownWrong } from "./layoutShown.js"; import { recordCanvasText, wordsInPage, type WordsShown } from "./layoutWords.js"; const HELD_AT = 0.6; const TOLERANCE = 2; const SPILL_TOLERANCE = 4; const OCCLUDED = 0.15; // Words cover this share of the smaller of the two before they count as drawn over each other. const OVERLAP = 0.12; const OVERLAP_GAP = 16; // Effects whose words are set over each other or over their pictures by design. // Measured over the library rendered with filled slots, each looked at by eye. const LAYERED = new Set([ "3d-title-note", "flash-burst-sticker", "hands-reveal-text", "neon-price-counter", "pink-card-syringe", "predict-keys", "price-versus", "quote-neon-word", "rank-badge-title", "recolor-title-demo", "red-slab-title", "serif-overlap-stack", "two-side-typed-notes", ]); const READY_MS = 45_000; const OUT_OF_PLACE = new Set(["outside_safe_zone", "canvas_overflow", "container_overflow"]); const QUICK_SEEK = { ...AUDIT_SEEK_OPTIONS, waitForVideoFrames: false, waitForFontsMs: 0 }; // An effect whose words show at fewer of its moments than this is looked for every STEP seconds. const SHOWN_AT = 2; const STEP = 0.25; export type FindingCode = | "occluded" | "covered" | "out_of_place" | "over_captions" | "face" | "face_cut" | "overlap" | "sample" | "unsaid" | "blank"; export interface Finding { id: string; at: number; code: FindingCode; kind: string; text: string; /** The element to act on, as a selector inside the effect's own page; absent when it is outside it. */ selector?: string; fraction?: number; /** Pixels past the frame (`frame`) or past the box the text sits in, by side. */ over?: LayoutOverflow; frame?: boolean; /** For text past its box: whether it is still all in the frame, and its line's height. */ inFrame?: boolean; line?: number; /** CSS for the effect's page that puts it right, when code can. */ rules?: string[]; /** For words drawn over other words or a picture of the same effect, or covered by the person: the move that clears * them, if one fits. */ move?: { x: number; y: number }; /** For words the person covers: where the element moved is, in the frame's pixels. */ box?: { left: number; top: number; right: number; bottom: number }; } export interface Moment { id: string; start: number; end: number; matte: boolean; /** A picture is taken at the moment too, for the face check. */ pictured: boolean; /** The library effect it is, when known. */ effect?: string; /** What is said in its seconds, for an effect whose words the model wrote: what it shows is checked against it. */ heard?: Heard; } /** The moment an effect is fully in: past its entrance, before it leaves. */ export const heldAt = (p: { start: number; end: number }): number => round(p.start + Math.min(HELD_AT * (p.end - p.start), p.end - p.start - 0.1), 3); /** What is wrong with one effect at one moment; the face picture is taken at its held moment. */ type Spilled = Awaited>[number]; const spillFindings = (id: string, at: number, spills: Spilled[]): Finding[] => spills .filter((spill) => spill.id === id) .map((spill) => ({ id, at, code: "out_of_place", kind: `spills ${Object.entries(spill.overflow) .map(([side, by]) => `${by} px past the ${side}`) .join(", ")} of the box it sits in`, text: spill.text, selector: spill.selector, over: spill.overflow, inFrame: spill.inFrame, line: spill.line, })); interface Look { one: Moment; at: number; /** The moment its pictures are taken at. */ held: number; } /** Whether the effect's words were on screen at each moment it was looked at. */ type Words = Map; async function lookAt( page: Page, driver: PageDriver, look: Look, shots: string, frames: FramedAt[], painted: Set, words: Words, ): Promise { const { one, at } = look; const held = at === look.held; const picture = one.pictured && held; await seekCompositionTimeline( page, at, picture ? SCREENSHOT_SEEK_OPTIONS : one.matte ? AUDIT_SEEK_OPTIONS : QUICK_SEEK, ); if (picture) await pictured(page, one.id, shots); if (held) await page.screenshot({ path: join(shots, `${one.id}.held.jpg`), type: "jpeg", quality: 70 }); if (held) { const framed = await page.evaluate(framesInPage, `[data-composition-id="auto-${one.id}"]`); if (framed.length) frames.push({ id: one.id, at, start: one.start, framed }); } noted(words, one.id, at, await page.evaluate(wordsInPage, one.id)); const found = findingsOf(one.id, at, await driver.collectLayout(at, TOLERANCE), one.matte); if (one.heard) found.push(...(await shownFindings(page, one, at, painted))); found.push(...spillFindings(one.id, at, await page.evaluate(spillsInPage, SPILL_TOLERANCE))); if (!LAYERED.has(one.effect ?? "")) found.push( ...overlapFindings( one.id, at, await page.evaluate(overlapsInPage, one.id, OVERLAP, OVERLAP_GAP), ), ); return found; } function noted(words: Words, id: string, at: number, now: WordsShown): void { const seen = words.get(id) ?? { has: false, looked: [], shown: [] }; seen.has ||= now.has; seen.looked.push(at); if (now.shown) seen.shown.push(at); words.set(id, seen); } const byTime = (x: number, y: number) => x - y; /** The moments, in order, the effect's words are on screen, looked for every STEP seconds of its own. */ async function whenShown(page: Page, one: Moment, words: Words): Promise { const shown: number[] = []; for (let at = round(one.start + STEP / 2, 3); at < one.end; at = round(at + STEP, 3)) { await seekCompositionTimeline(page, at, QUICK_SEEK); const now = await page.evaluate(wordsInPage, one.id); const seen = words.get(one.id); if (seen) seen.has ||= now.has; if (now.shown) shown.push(at); } return shown; } /** Three moments over the seconds its words show: just in, held, and late, the middle one for its pictures. */ function shownMoments(shown: number[]): { at: number[]; held: number } { const pick = (share: number) => shown[Math.round(share * (shown.length - 1))] ?? 0; return { at: [...new Set([pick(0.2), pick(0.6), pick(1)])], held: pick(0.6) }; } /** What the effect shows at `at` that is not what is said; whether it shows anything is kept in `painted`. */ async function shownFindings( page: Page, one: Moment, at: number, painted: Set, ): Promise { if (!one.heard) return []; const shown = await page.evaluate(shownInPage, `[data-composition-id="auto-${one.id}"]`); if (shown.painted) painted.add(one.id); return shownWrong(shown, one.heard).map(([code, kind, text]) => ({ id: one.id, at, code, kind, text, })); } /** An effect whose words the model wrote and that showed nothing at any moment. */ const blanks = (moments: Moment[], painted: Set): Finding[] => moments .filter((one) => one.heard && !painted.has(one.id)) .map((one) => ({ id: one.id, at: heldAt(one), code: "blank" as const, kind: "shows nothing at any moment: its script may have stopped", text: "", })); // Words painted on a canvas carry no selector: no rule moves one line of it, so code leaves them to be taken off. export const overlapFindings = (id: string, at: number, overlaps: Overlap[]): Finding[] => overlaps .filter((o) => o.id === id && (o.selector || o.canvas)) .map((o) => ({ id, at, code: "overlap" as const, kind: `is drawn over ${o.picture ? "its picture" : "its words"} "${o.other}", ${Math.round(o.share * 100)}% of them${o.canvas ? ", both painted on its canvas" : ""}`, text: o.text, ...(o.selector ? { selector: o.selector } : {}), fraction: o.share, ...(o.move ? { move: o.move } : {}), })); /** Past the entrance, held, and before the exit: text that comes in or goes on its own is checked where it shows. */ export function momentsOf(p: { start: number; end: number }): number[] { const seconds = p.end - p.start; const held = heldAt(p); const early = round(p.start + Math.min(Math.max(0.5, 0.2 * seconds), seconds / 2), 3); const late = round(p.end - Math.min(Math.max(0.6, 0.15 * seconds), seconds / 2), 3); return [...new Set([early, held, late])].filter((at) => at > p.start && at < p.end).sort(); } const most = (one: Finding) => Math.max(100 * (one.fraction ?? 0), ...Object.values(one.over ?? {}).map(Number)); /** Words over words at one moment only are an entrance, an exit or a swap: kept when seen at two moments or more. */ export function lasting( found: Finding[], moments: { id: string; start: number; end: number }[], counts?: Map, ): Finding[] { const looks = new Map( moments.map((one) => [one.id, counts?.get(one.id) ?? momentsOf(one).length]), ); const times = new Map>(); const keyOf = (one: Finding) => `${one.id}\n${one.selector}`; for (const one of found.filter((f) => f.code === "overlap")) times.set(keyOf(one), (times.get(keyOf(one)) ?? new Set()).add(one.at)); return found.filter( (one) => one.code !== "overlap" || (times.get(keyOf(one))?.size ?? 0) >= Math.min(2, looks.get(one.id) ?? 1), ); } /** One finding for each thing wrong, from whichever moment showed it worst. */ export function worstOf(found: Finding[]): Finding[] { const kept = new Map(); for (const one of found) { const key = `${one.id}\n${one.code}\n${one.selector ?? one.text}`; const before = kept.get(key); if (!before || most(one) > most(before)) kept.set(key, one); } return [...kept.values()]; } const effectOf = (file: string | undefined) => /auto-(p\d+)\.html$/.exec(file ?? "")?.[1]; const isCaptions = (file: string | undefined) => /compositions\/auto-/.test(file ?? "") && !effectOf(file); const localTo = (selector: string | undefined) => selector && !selector.startsWith("#auto-") ? selector : undefined; // fallow-ignore-next-line complexity export function findingsOf( id: string, at: number, issues: AnchoredLayoutIssue[], behindPerson = false, ): Finding[] { const out: Finding[] = []; for (const issue of issues) { const own = effectOf(issue.sourceFile) === id; const text = (issue.text ?? "").trim(); const fraction = issue.coveredFraction ?? 0; const base = { id, at, kind: issue.code, text }; if ( own && issue.code === "text_occluded" && issue.severity === "error" && fraction > OCCLUDED && !behindPerson ) { const selector = localTo(issue.containerSelector); const { left, top, right, bottom } = issue.containerRect ?? issue.rect; out.push({ ...base, code: "occluded", fraction, box: { left, top, right, bottom }, ...(selector ? { selector } : {}), }); } else if (own && OUT_OF_PLACE.has(issue.code) && text) { const selector = localTo(issue.selector); const frame = issue.overflow && (issue.code === "canvas_overflow" || issue.code === "outside_safe_zone"); out.push({ ...base, code: "out_of_place", ...(selector ? { selector } : {}), ...(frame ? { over: issue.overflow, frame: true } : {}), }); } else if ( own && issue.code === "content_overlap" && isCaptionsSelector(issue.containerSelector) ) out.push({ ...base, code: "over_captions" }); else if ( isCaptions(issue.sourceFile) && (issue.code === "content_overlap" || issue.code === "text_occluded") && new RegExp(`^#auto-${id}(?![\\w-])`).test(issue.containerSelector ?? "") ) out.push({ ...base, code: "over_captions" }); } const seen = new Set(); return out.filter((one) => { const key = `${one.code}\n${one.kind}\n${one.text}\n${one.selector ?? ""}`; return !seen.has(key) && Boolean(seen.add(key)); }); } const isCaptionsSelector = (selector: string | undefined) => /^#auto-(?!p\d+(?:-wrap)?(?![\w-]))[\w-]+/.test(selector ?? ""); export interface Checked { found: Finding[]; /** The clip's videos each effect shows in a frame, at its held moment. */ frames?: FramedAt[]; /** The moments each effect was looked at, and those its words were on screen at. */ looked?: { [id: string]: { at: number[]; words: number[] } }; /** The moment each effect's pictures were taken at, where it is not its held moment. */ held?: { [id: string]: number }; /** Effects with words that were on screen at none of their moments: nothing about their words was checked. */ unseen?: string[]; ms: { bundle: number; open: number; look: number; face?: number }; } const BARE = "hf-layout-bare"; /** The frame as shown, and as it would be without the effect's graphics: its footage and cut-out stay. */ async function pictured(page: Page, id: string, shots: string): Promise { const shot = (name: string) => page.screenshot({ path: join(shots, name), type: "jpeg", quality: 80 }); await shot(`${id}.now.jpg`); await page.evaluate( (root: string, mark: string) => { const style = document.createElement("style"); style.id = mark; style.textContent = `${root} *:not(video) { visibility: hidden !important; } ${root} video { visibility: visible !important; }`; document.head.append(style); }, `[data-composition-id="auto-${id}"]`, BARE, ); await shot(`${id}.was.jpg`); await page.evaluate((mark: string) => document.getElementById(mark)?.remove(), BARE); } /** Starts the browser a check will want, while the run waits on something else. */ export async function browserFor(project: string): Promise { return prelaunchCompositionBrowser(await readFile(join(project, "index.html"), "utf8")); } /** Each effect's layout at the moment it is fully in: one page, one seek per effect, no contrast or motion checks. */ export async function checkLayout( project: string, moments: Moment[], shots: string, prelaunched?: PrelaunchedBrowser, ): Promise { const started = Date.now(); const html = await bundleWithLocalizedFonts(project); const bundled = Date.now(); const server = await serveStaticProjectHtml(project, html, "Failed to bind the layout check"); let browser: Awaited>["browser"] | undefined; try { const session = await openSettledCompositionPage(html, server.url, { renderReadyTimeoutMs: READY_MS, renderReadyWarningSuffix: "", beforeNavigate: async (page) => { await page.evaluateOnNewDocument(recordCanvasText); }, ...(prelaunched ? { prelaunched } : {}), }); browser = session.browser; if (session.renderReadyTimedOut) throw new Error("the page never became ready to check"); const opened = Date.now(); const driver = createPageDriver(session.page, undefined, undefined, project); await driver.initialize(false); const found: Finding[] = []; let frames: FramedAt[] = []; const painted = new Set(); const words: Words = new Map(); const look = async (looks: Look[]) => { for (const one of looks.sort((x, y) => x.at - y.at)) found.push(...(await lookAt(session.page, driver, one, shots, frames, painted, words))); }; await look( moments.flatMap((one) => momentsOf(one).map((at) => ({ one, at, held: heldAt(one) }))), ); // Words that come in late or leave early can miss the usual moments: looked at again where they show. const again: Look[] = []; const held: { [id: string]: number } = {}; for (const one of moments) { const seen = words.get(one.id); if (!seen?.has || seen.shown.length >= Math.min(SHOWN_AT, seen.looked.length)) continue; const shown = await whenShown(session.page, one, words); if (!shown.length) continue; const picked = shownMoments(shown); held[one.id] = picked.held; again.push(...picked.at.map((at) => ({ one, at, held: picked.held }))); } frames = frames.filter((one) => !(one.id in held)); await look(again); const looked = Object.fromEntries( [...words].map(([id, seen]) => [ id, { at: [...new Set(seen.looked)].sort(byTime), words: [...new Set(seen.shown)].sort(byTime), }, ]), ); const unseen = [...words] .filter(([, seen]) => seen.has && !seen.shown.length) .map(([id]) => id); const counts = new Map(Object.entries(looked).map(([id, one]) => [id, one.at.length])); return { found: [...worstOf(lasting(found, moments, counts)), ...blanks(moments, painted)], frames, looked, ...(Object.keys(held).length ? { held } : {}), ...(unseen.length ? { unseen } : {}), ms: { bundle: bundled - started, open: opened - bundled, look: Date.now() - opened }, }; } finally { await browser?.close().catch(() => undefined); await server.close().catch(() => undefined); await prelaunched?.discard(); } }