diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 62faa4eaa0..fad6ea4bd2 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -1288,6 +1288,7 @@ cover every finding from the full check. | `--no-craft` | Skip the craft pass (dead stretches, unread lines, silent film), the longest part of a full check. The report marks it skipped. Use it for a render preflight; keep it on for the full check before a release. | | `--strict` | Exit non-zero on warnings too (default: errors only) | | `--caption-zone ""` | Opt-in band gate. Flags a text element's DOM box that overlaps the fractional band. Optional `severity` and `seek`. | +| `--safe-zone ` | Warn when text, captions included, leaves a safe area: a platform's on 9:16 compositions (default: all three), or `standard` title-safe margins (10% from each edge) on any frame. Never fails `--strict` | | `--frame-check` | Opt-in out-of-frame detection for `img`, `svg`, `video`, and `canvas` | | `--layout` | Layout knobs, currently `proseCoverageFloor=0.05` (0–1, default 0.15) | | `--browser-gpu` / `--no-browser-gpu` | Hardware GPU capture, or deterministic SwiftShader (default: auto-detect) | @@ -1424,6 +1425,16 @@ For deliberate lower-third copy under `--caption-zone`, use nothing else — overflow, overlap, occlusion, and contrast still apply. Put it on the narrowest wrapper that owns the band copy. +On a 9:16 composition, check samples every text block and caption line against the +areas TikTok, Instagram Reels and YouTube Shorts leave clear of their buttons and +captions. Each block that leaves one is an `outside_safe_zone` warning naming the +platforms and the edges it crosses, at the first time it is seen. The areas are +reference guides from each platform's vertical ad specs: TikTok 720x1280 with a +stepped right edge, Reels with the bottom 35%, top 14% and 6% sides excluded, Shorts +1080x1920 excluding 48px left, 192px right, 288px top and 672px bottom. `--safe-zone standard` checks the title-safe margins instead, 10% in from each +edge, on any aspect ratio. Mark text that may sit outside them with +`data-layout-allow-safe-zone`. + #### Verify motion, not just layout Layout sampling cannot catch a render-≠-preview bug: an entrance the seek lands diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts index afc7e7ee66..e9fddf6c2f 100644 --- a/packages/cli/src/commands/check.test.ts +++ b/packages/cli/src/commands/check.test.ts @@ -22,7 +22,7 @@ vi.mock("../telemetry/events.js", () => ({ })); import { contrastRatio, parseColorRGBA } from "./contrast-bg.js"; -import { createCheckCommand, parseCheckRange } from "./check.js"; +import { createCheckCommand, parseCheckRange, parseSafeZone } from "./check.js"; import { assertKnownFlags } from "../utils/reject-unknown-flags.js"; import { readConfig } from "../telemetry/config.js"; import { @@ -234,7 +234,7 @@ function fakeDriver(overrides: Partial = {}): CheckAuditDriver } interface GeometryFixture { - kind: "text" | "media"; + kind: "text" | "media" | "block"; tag: string; text: string; selector: string; @@ -1035,6 +1035,7 @@ it("flags text whose DOM box overlaps the caption band at the default end seek", expect(collectGeometryCandidates).toHaveBeenCalledWith(10, { text: true, media: false, + blocks: false, tolerance: 2, }); expect(report.layout.samples).toEqual([5, 10]); @@ -1210,6 +1211,7 @@ it("checks media overflow at the default midpoint and applies warning severity", expect(collectGeometryCandidates).toHaveBeenCalledWith(5, { text: false, media: true, + blocks: false, tolerance: 2, }); expect(report.layout.findings[0]).toMatchObject({ @@ -1245,9 +1247,9 @@ it("converts progress seeks to time, gates each collector, and keeps distinct ca expect(report.layout.samples).toEqual([2, 4, 6]); expect(collectGeometryCandidates.mock.calls).toEqual([ - [2, { text: true, media: false, tolerance: 2 }], - [4, { text: false, media: true, tolerance: 2 }], - [6, { text: true, media: false, tolerance: 2 }], + [2, { text: true, media: false, blocks: false, tolerance: 2 }], + [4, { text: false, media: true, blocks: false, tolerance: 2 }], + [6, { text: true, media: false, blocks: false, tolerance: 2 }], ]); expect(report.layout.findings).toEqual([ expect.objectContaining({ @@ -1289,6 +1291,150 @@ it("does not collect or emit opt-in geometry findings when both flags are off", expect(JSON.stringify(report)).not.toContain("frame_out_of_frame"); }); +describe("social safe zones", () => { + const portrait = { width: 1080, height: 1920 }; + const block = (selector: string, text: string, rect: LayoutRect, time: number) => + geometryCandidate({ kind: "block", tag: "p", text, selector, rect, time }); + // A caption in the bottom 30% and a title centred in the upper half. + const captionAndTitle = (time: number) => [ + block("#caption", "Follow for part two", fixtureRect(140, 1400, 800, 120), time), + block("#title", "Centred title", fixtureRect(216, 600, 648, 120), time), + ]; + + async function safeZoneScenario( + candidates: (time: number) => ReturnType[], + options: Partial = {}, + canvas = portrait, + ) { + const collectGeometryCandidates = vi.fn(async (time: number) => candidates(time)); + const { report } = await runScenario( + fakeDriver({ + getDuration: vi.fn(async () => 4), + getCanvas: vi.fn(async () => canvas), + collectGeometryCandidates, + }), + { samples: 2, contrast: false, safeZones: ["tiktok", "reels", "shorts"], ...options }, + ); + return { report, collectGeometryCandidates }; + } + + it("warns once, at the first time, for a caption below every platform's safe area", async () => { + const { report, collectGeometryCandidates } = await safeZoneScenario(captionAndTitle, { + strict: true, + }); + + expect(collectGeometryCandidates).toHaveBeenCalledWith( + expect.any(Number), + expect.objectContaining({ blocks: true }), + ); + expect(report.layout.findings).toEqual([ + expect.objectContaining({ + code: "outside_safe_zone", + severity: "warning", + selector: "#caption", + time: report.layout.samples[0], + message: + '

"Follow for part two" is outside the safe area: TikTok (bottom edge), Instagram Reels (bottom edge), YouTube Shorts (bottom edge).', + }), + ]); + expect(report.ok).toBe(true); + }); + + it("follows TikTok's stepped right edge", async () => { + const { report } = await safeZoneScenario((time) => [ + block("#under-step", "Under the buttons", fixtureRect(756, 960, 108, 96), time), + block("#above-step", "Above the buttons", fixtureRect(756, 384, 108, 96), time), + ]); + + expect(report.layout.findings).toEqual([ + expect.objectContaining({ + selector: "#under-step", + message: '

"Under the buttons" is outside the safe area: TikTok (right edge).', + }), + ]); + }); + + it("narrows to one platform", async () => { + const { report } = await safeZoneScenario(captionAndTitle, { safeZones: ["shorts"] }); + + expect(report.layout.findings.map((finding) => finding.message)).toEqual([ + '

"Follow for part two" is outside the safe area: YouTube Shorts (bottom edge).', + ]); + }); + + it("skips text marked data-layout-allow-safe-zone", async () => { + const { report } = await safeZoneScenario((time) => [ + geometryCandidate({ + kind: "block", + tag: "p", + text: "Sticker", + selector: "#sticker", + rect: fixtureRect(140, 1400, 800, 120), + time, + dataAttributes: { "data-layout-allow-safe-zone": "" }, + }), + ]); + + expect(report.layout.findings).toEqual([]); + }); + + it("reports nothing when off or when the frame is not 9:16", async () => { + const off = await safeZoneScenario(captionAndTitle, { safeZones: [] }); + const landscape = await safeZoneScenario(captionAndTitle, {}, { width: 1920, height: 1080 }); + + expect(off.collectGeometryCandidates).not.toHaveBeenCalled(); + expect(landscape.collectGeometryCandidates).not.toHaveBeenCalled(); + expect(off.report.layout.findings).toEqual([]); + expect(landscape.report.layout.findings).toEqual([]); + }); + + it("never lets a safe-zone warning push a defect warning past --max-issues", async () => { + const { report } = await safeZoneScenario( + (time) => [ + ...captionAndTitle(time), + geometryCandidate({ + kind: "text", + tag: "p", + text: "Lower third", + selector: "#lower-third", + rect: fixtureRect(140, 1700, 800, 80), + time, + }), + ], + { maxIssues: 1, strict: true, captionZone: { x0: 0, y0: 0.85, x1: 1, y1: 1 } }, + ); + + expect(report.layout.findings).toEqual([ + expect.objectContaining({ code: "caption_zone_collision", selector: "#lower-third" }), + ]); + expect(report.ok).toBe(false); + }); + + it("checks title-safe margins on any frame when asked for standard", async () => { + const landscape = { width: 1920, height: 1080 }; + const { report } = await safeZoneScenario( + (time) => [ + block("#edge-title", "Near the edge", fixtureRect(96, 400, 600, 100), time), + block("#centred", "Centred", fixtureRect(660, 490, 600, 100), time), + ], + { safeZones: ["standard"] }, + landscape, + ); + + expect(report.layout.findings.map((finding) => finding.message)).toEqual([ + '

"Near the edge" is outside the safe area: title-safe margins (left edge).', + ]); + }); + + it("parses --safe-zone", () => { + expect(parseSafeZone(undefined)).toEqual(["tiktok", "reels", "shorts"]); + expect(parseSafeZone("reels")).toEqual(["reels"]); + expect(parseSafeZone("standard")).toEqual(["standard"]); + expect(parseSafeZone("off")).toEqual([]); + expect(() => parseSafeZone("instagram")).toThrow(CliUsageError); + }); +}); + it("computes caption bands from a portrait composition viewport", async () => { const viewport = resolveCompositionViewportFromHtml( '

', diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index 8ee2a67593..009a5226ce 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -39,6 +39,8 @@ import { } from "../utils/checkPipeline.js"; import type { CaptionZoneOptions, FrameCheckOptions, LayoutOptions } from "../utils/checkTypes.js"; import { resolveLocalBrowserGpuMode } from "../browser/gpuPolicy.js"; +import { SOCIAL_SAFE_AREA_NAMES } from "@hyperframes/core/safe-areas"; +import type { SafeZone } from "../utils/safeZones.js"; import { preResolveHostileMediaProxies, type PreparedMediaFile } from "../utils/checkBrowser.js"; import { parseTimeoutMs } from "../utils/timeoutArg.js"; import { failureMessage, jsonFailure } from "../utils/jsonError.js"; @@ -297,6 +299,11 @@ const CHECK_COMMAND_ARGS = { description: 'Caption band "x0=0;y0=.82;x1=1;y1=1[;severity=warning|error][;seek=.5,1]" (fractions 0-1; defaults: warning, seek=1)', }, + "safe-zone": { + type: "string", + description: + "Warn when text leaves a safe area: tiktok, reels or shorts on 9:16 (default: all three), standard (title-safe margins, any frame), or off", + }, "frame-check": { type: "string", description: @@ -499,6 +506,7 @@ function parseCheckOptions(args: Record): CheckOptions { ...(checkReview()?.findingFrames ? { findingFrames: true } : {}), ...(checkReview()?.inspect ? { inspect: true } : {}), captionZone: parseCaptionZone(args["caption-zone"]), + safeZones: parseSafeZone(args["safe-zone"]), frameCheck: parseFrameCheck(args["frame-check"]), layout: parseLayout(args.layout), autoProxy: args.proxy as boolean | undefined, @@ -623,6 +631,15 @@ function parseNumberStrict(raw: string): number | null { return Number.isFinite(value) ? value : null; } +export function parseSafeZone(value: unknown): SafeZone[] { + if (value === undefined) return [...SOCIAL_SAFE_AREA_NAMES]; + if (value === "off") return []; + const zone = [...SOCIAL_SAFE_AREA_NAMES, "standard" as const].find((name) => name === value); + if (!zone) + throw new CliUsageError("Invalid --safe-zone; use tiktok, reels, shorts, standard or off."); + return [zone]; +} + function parseCaptionZone(value: unknown): CaptionZoneOptions | undefined { if (value === undefined || value === null) return undefined; const fields = parseCaptionFields(captionZoneString(value)); diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js index aec3f34a2f..332fb480f3 100644 --- a/packages/cli/src/commands/layout-audit.browser.js +++ b/packages/cli/src/commands/layout-audit.browser.js @@ -126,6 +126,10 @@ return !!authoredElement(element).closest("[data-layout-allow-caption-zone]"); } + function hasAllowSafeZoneFlag(element) { + return !!authoredElement(element).closest("[data-layout-allow-safe-zone]"); + } + function hasTextClipOptOut(element) { return ( hasAllowOverflowFlag(element) || authoredElement(element).hasAttribute("data-layout-bleed") @@ -2813,10 +2817,34 @@ }; } + const CAPTION_STAGES = '[data-composition-id="captions"], .caption-layer, #caption-stage'; + + // One box per reading block (a caption stage counts as one), so a line split into word spans is one finding. + function addTextToBlock(blocks, block, element) { + const rect = textRectFor(element, true); + if (!rect) return; + const entry = blocks.get(block) ?? { rects: [], texts: [] }; + entry.rects.push(rect); + entry.texts.push(textContentFor(element, true)); + blocks.set(block, entry); + } + + function blockCandidates(blocks) { + return Array.from(blocks, ([block, entry]) => ({ + kind: "block", + tag: block.tagName.toLowerCase(), + text: entry.texts.join(" "), + rect: unionRects(entry.rects), + elementRect: toRect(block.getBoundingClientRect()), + ...candidateAnchor(block), + })); + } + window.__hyperframesGeometryCandidates = function collectGeometryCandidates(options) { const includeText = options?.text === true; const includeMedia = options?.media === true; - if (!includeText && !includeMedia) return []; + const includeBlocks = options?.blocks === true; + if (!includeText && !includeMedia && !includeBlocks) return []; const tolerance = typeof options?.tolerance === "number" ? options.tolerance : 2; const root = document.querySelector("[data-composition-id][data-width][data-height]") || @@ -2824,11 +2852,15 @@ document.body; const rootRect = rootRectFor(root); const candidates = []; + const blocks = new Map(); for (const element of Array.from(document.querySelectorAll("body *"))) { - if (element.closest('[data-composition-id="captions"], .caption-layer, #caption-stage')) { - continue; - } + const captionStage = element.closest(CAPTION_STAGES); + if (captionStage && !includeBlocks) continue; if (!isVisibleElement(element, 0.05, false)) continue; + if (includeBlocks && hasOwnTextCandidate(element, true) && !hasAllowSafeZoneFlag(element)) { + addTextToBlock(blocks, captionStage || readingBlock(element, root), element); + } + if (captionStage) continue; const elementRect = toRect(element.getBoundingClientRect()); if (includeText && hasOwnTextCandidate(element, true) && !hasAllowCaptionZoneFlag(element)) { const rect = textRectFor(element, true); @@ -2844,7 +2876,7 @@ ); } } - return candidates; + return candidates.concat(blockCandidates(blocks)); }; window.__hyperframesLayoutAudit = function auditLayout(options) { diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts index 69a6b02d78..8d17357e83 100644 --- a/packages/cli/src/commands/layout-audit.browser.test.ts +++ b/packages/cli/src/commands/layout-audit.browser.test.ts @@ -731,6 +731,36 @@ it("excludes text marked data-layout-allow-caption-zone from geometry candidates expect(candidates.map((candidate) => candidate.selector)).toEqual(["#copy"]); }); +it("groups text into reading blocks, caption layers included, for the safe-zone check", () => { + document.body.innerHTML = ` +
+

Big title

+

Follow

+
Helloworld
+
+ `; + installGeometry( + { + root: rect({ left: 0, top: 0, width: 1080, height: 1920 }), + text: rect({ left: 100, top: 1500, width: 300, height: 80 }), + }, + { word: { display: "inline" } }, + ); + installAuditScript(); + + const candidates = runGeometryCandidates({ + text: false, + media: false, + blocks: true, + tolerance: 2, + }); + + expect(candidates.map(({ kind, selector, text }) => ({ kind, selector, text }))).toEqual([ + { kind: "block", selector: "#title", text: "Big title" }, + { kind: "block", selector: "#captions", text: "Hello world" }, + ]); +}); + it("scans body-level composition siblings and includes a media boundary root", () => { document.body.innerHTML = ` @@ -4160,6 +4190,7 @@ declare global { __hyperframesGeometryCandidates?: (options: { text: boolean; media: boolean; + blocks?: boolean; tolerance: number; }) => GeometryCandidateResult[]; } @@ -4168,6 +4199,7 @@ declare global { function runGeometryCandidates(options: { text: boolean; media: boolean; + blocks?: boolean; tolerance: number; }): GeometryCandidateResult[] { const collector = window.__hyperframesGeometryCandidates; diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.ts index 549bf0fa93..c20fd906af 100644 --- a/packages/cli/src/utils/checkBrowser.ts +++ b/packages/cli/src/utils/checkBrowser.ts @@ -2121,7 +2121,8 @@ function parseGeometryIdentity( value: Record, ): Pick | null { const kindValue = Reflect.get(value, "kind"); - const kind = kindValue === "text" || kindValue === "media" ? kindValue : null; + const kind = + kindValue === "text" || kindValue === "media" || kindValue === "block" ? kindValue : null; if (!kind) return null; const tag = stringValue(value, "tag"); if (!tag) return null; @@ -2291,6 +2292,7 @@ const LAYOUT_ISSUE_CODES: readonly LayoutIssueCode[] = [ "video_alpha_unread", "text_not_painted", "caption_zone_collision", + "outside_safe_zone", "frame_out_of_frame", "escaped_container", "panel_out_of_canvas", diff --git a/packages/cli/src/utils/checkPipeline.ts b/packages/cli/src/utils/checkPipeline.ts index e77aec7e80..2cd66b352a 100644 --- a/packages/cli/src/utils/checkPipeline.ts +++ b/packages/cli/src/utils/checkPipeline.ts @@ -16,6 +16,7 @@ import { finishCheckSnapshots, } from "./checkSnapshotDirectory.js"; import { findingAtRoot, findingElementKey, groupSampledFindings } from "./checkFindings.js"; +import { safeZoneEdgesCrossed, safeZoneLabel, safeZonesFor, type SafeZone } from "./safeZones.js"; import { MAX_FINDING_FRAME_TIMES, selectFindingFrames, @@ -40,6 +41,7 @@ import { CONTENT_OVERLAP_HELD_ERROR_MS, longestContiguousRunMs, dedupeLayoutIssues, + isGuidanceIssue, limitLayoutIssues, mergeSampleTimes, type LayoutIssue, @@ -317,13 +319,15 @@ function geometryRequest( time: number, grid: SampleGrid, options: CheckOptions, + sets: SampleSets, ): GeometryCandidateRequest | null { const text = grid.captionSamples.includes(time); const media = grid.frameSamples.includes(time); - if (!text && !media) return null; + const blocks = sets.safeZones.length > 0 && sets.layout.has(time); + if (!text && !media && !blocks) return null; const configuredTolerance = options.frameCheck?.tol; const tolerance = typeof configuredTolerance === "number" ? configuredTolerance : 2; - return { text, media, tolerance }; + return { text, media, blocks, tolerance }; } function candidateIsSized(candidate: CheckGeometryCandidate, canvas: Canvas): boolean { @@ -385,6 +389,35 @@ function captionFinding( }; } +function safeZoneFinding( + candidate: CheckGeometryCandidate, + zones: SafeZone[], + canvas: Canvas, + time: number, +): AnchoredLayoutIssue | null { + if (candidate.kind !== "block" || candidate.rect.width < 4 || candidate.rect.height < 4) { + return null; + } + // Backstop for mocks/non-browser sources; the browser already drops opted-out text. + if ("data-layout-allow-safe-zone" in candidate.dataAttributes) return null; + const crossed = zones.flatMap((zone) => { + const edges = safeZoneEdgesCrossed(candidate.rect, canvas, zone); + if (edges.length === 0) return []; + return [`${safeZoneLabel(zone)} (${edges.join(" and ")} edge${edges.length > 1 ? "s" : ""})`]; + }); + if (crossed.length === 0) return null; + const text = candidate.text.slice(0, 48); + return { + ...geometryIssueAnchor(candidate, time), + code: "outside_safe_zone", + severity: "warning", + text, + message: `<${candidate.tag}> "${text}" is outside the safe area: ${crossed.join(", ")}.`, + fixHint: + "Move the text inside the safe area, or mark text meant to sit there with data-layout-allow-safe-zone.", + }; +} + function maxOverflow(candidate: CheckGeometryCandidate): number { if (!candidate.overflow) return 0; return Math.max( @@ -435,24 +468,20 @@ async function collectGeometryAt( driver: CheckAuditDriver, options: CheckOptions, grid: SampleGrid, + sets: SampleSets, canvas: Canvas, time: number, ): Promise { - const request = geometryRequest(time, grid, options); + const request = geometryRequest(time, grid, options, sets); if (!request) return []; const candidates = await driver.collectGeometryCandidates(time, request); - const issues: AnchoredLayoutIssue[] = []; - for (const candidate of candidates) { - if (request.text) { - const finding = captionFinding(candidate, options, canvas, time); - if (finding) issues.push(finding); - } - if (request.media) { - const finding = frameFinding(candidate, options, canvas, time); - if (finding) issues.push(finding); - } - } - return issues; + return candidates + .flatMap((candidate) => [ + request.blocks ? safeZoneFinding(candidate, sets.safeZones, canvas, time) : null, + request.text ? captionFinding(candidate, options, canvas, time) : null, + request.media ? frameFinding(candidate, options, canvas, time) : null, + ]) + .filter((finding): finding is AnchoredLayoutIssue => finding !== null); } function emptyGridSamples(): GridSamples { @@ -490,6 +519,8 @@ interface SampleSets { motion: Set; contrast: Set; canvas: Canvas | null; + /** Platforms to judge text against; empty unless the frame is 9:16. */ + safeZones: SafeZone[]; } async function collectSampleAt( @@ -519,7 +550,7 @@ async function collectSampleAt( collected.indicatorFrames.push(await driver.collectOffPivotRotationSample(time)); } if (sets.canvas) { - const geometryIssues = await collectGeometryAt(driver, options, grid, sets.canvas, time); + const geometryIssues = await collectGeometryAt(driver, options, grid, sets, sets.canvas, time); collected.layoutIssues.push(...geometryIssues); issuesAtTime.push(...geometryIssues); } @@ -533,6 +564,25 @@ async function collectSampleAt( return collected; } +async function buildSampleSets( + driver: CheckAuditDriver, + options: CheckOptions, + grid: SampleGrid, + motion: MotionPlan, +): Promise { + const safeZones = options.safeZones ?? []; + const geometryEnabled = + grid.captionSamples.length > 0 || grid.frameSamples.length > 0 || safeZones.length > 0; + const canvas = geometryEnabled ? await driver.getCanvas() : null; + return { + layout: new Set(grid.layoutSamples), + motion: new Set(motion.times), + contrast: new Set(grid.contrastSamples), + canvas, + safeZones: canvas ? safeZonesFor(safeZones, canvas) : [], + }; +} + // Frames are a function of time, so a helper page that is ready takes the next unclaimed sample // and the merge keeps the serial order. A helper only adds speed: one that fails hands its samples back. async function collectGridSamples( @@ -545,13 +595,7 @@ async function collectGridSamples( report: CheckProgress, keep: (read: () => Partial) => void, ): Promise { - const geometryEnabled = grid.captionSamples.length > 0 || grid.frameSamples.length > 0; - const sets: SampleSets = { - layout: new Set(grid.layoutSamples), - motion: new Set(motion.times), - contrast: new Set(grid.contrastSamples), - canvas: geometryEnabled ? await driver.getCanvas() : null, - }; + const sets = await buildSampleSets(driver, options, grid, motion); const gridStart = performance.now(); const times = mergeSampleTimes(grid.layoutSamples, motion.times); const pending = times.map((_, index) => index); @@ -2073,7 +2117,10 @@ function buildReport( contrastSection.errorCount + craftSection.errorCount; // Craft findings are judgment calls a film may break on purpose, so --strict gates defects only. - const strictWarningCount = warningCount - craftSection.warningCount; + const guidanceWarnings = layout.findings.filter( + (finding) => finding.severity === "warning" && isGuidanceIssue(finding), + ).length; + const strictWarningCount = warningCount - craftSection.warningCount - guidanceWarnings; const report: CheckReport = { ok: errorCount === 0 && (!options.strict || strictWarningCount === 0), strict: options.strict, diff --git a/packages/cli/src/utils/checkTypes.ts b/packages/cli/src/utils/checkTypes.ts index 8a4580fcd1..4c15fad2c3 100644 --- a/packages/cli/src/utils/checkTypes.ts +++ b/packages/cli/src/utils/checkTypes.ts @@ -11,6 +11,7 @@ import type { HdrAutoPromotion } from "@hyperframes/engine"; import type { ComponentReport } from "@hyperframes/inspector/live"; import type { PrelaunchedBrowser } from "../capture/captureCompositionFrame.js"; import type { CheckPhase } from "./checkDeadline.js"; +import type { SafeZone } from "./safeZones.js"; export interface CheckOptions { samples: number; @@ -31,6 +32,7 @@ export interface CheckOptions { findingFrames?: boolean; inspect?: boolean; captionZone?: CaptionZoneOptions; + safeZones?: SafeZone[]; frameCheck?: FrameCheckOptions; /** Opt-in layout-audit knobs (`--layout "proseCoverageFloor=0.05"`). Defaults stay in the browser audit. */ layout?: LayoutOptions; @@ -135,6 +137,7 @@ export interface ContrastCapture { export interface GeometryCandidateRequest { text: boolean; media: boolean; + blocks: boolean; tolerance: number; } @@ -172,7 +175,7 @@ export interface CheckFindingInspection { } export interface CheckGeometryCandidate extends CheckAnchor { - kind: "text" | "media"; + kind: "text" | "media" | "block"; tag: string; text: string; rect: LayoutRect; diff --git a/packages/cli/src/utils/layoutAudit.ts b/packages/cli/src/utils/layoutAudit.ts index 106557ddd9..6e04a2adb7 100644 --- a/packages/cli/src/utils/layoutAudit.ts +++ b/packages/cli/src/utils/layoutAudit.ts @@ -22,6 +22,7 @@ export type LayoutIssueCode = | "video_alpha_unread" | "text_not_painted" | "caption_zone_collision" + | "outside_safe_zone" | "frame_out_of_frame" // Coordinate-frame findings — geometry computed in one frame, rendered in another. | "escaped_container" @@ -344,8 +345,7 @@ function applyPersistenceTier( multiSampleRun: boolean, sampleTimes?: readonly number[], ): LayoutIssue { - if (!multiSampleRun) return issue; - if (!PERSISTENCE_TIERED_CODES.has(issue.code)) return issue; + if (!multiSampleRun || !PERSISTENCE_TIERED_CODES.has(issue.code)) return issue; const occurrences = issue.occurrences ?? 1; // A single collapsed occurrence is held 0ms by construction (firstSeen === @@ -354,13 +354,18 @@ function applyPersistenceTier( if (occurrences <= 1) { return caughtForWholeLifetime(issue, sampleTimes) ? issue : { ...issue, severity: "info" }; } + const promoted = heldPromotion(issue, occurrences); + return promoted ? { ...issue, severity: promoted } : issue; +} + +function heldPromotion(issue: LayoutIssue, occurrences: number): LayoutIssueSeverity | null { if (issue.code === "content_overlap" && isContentOverlapHeldLongEnough(issue, occurrences)) { - return { ...issue, severity: "error" }; + return "error"; } if (issue.code === "canvas_overflow" && isCanvasBreachHeldLarge(issue, occurrences)) { - return { ...issue, severity: "warning" }; + return "warning"; } - return issue; + return null; } // A held, canvas-scale, PARTIALLY visible breach is drift; a fully off-canvas rect is a parked entrance. @@ -394,6 +399,11 @@ function isContentOverlapHeldLongEnough(issue: LayoutIssue, occurrences: number) return heldMs >= CONTENT_OVERLAP_HELD_ERROR_MS; } +// Platform guidance, not a defect: it never fails --strict and is the first to go past --max-issues. +export function isGuidanceIssue(issue: Pick): boolean { + return issue.code === "outside_safe_zone"; +} + export function limitLayoutIssues( issues: LayoutIssue[], maxIssues: number, @@ -402,7 +412,8 @@ export function limitLayoutIssues( const sortedIssues = [...issues].sort((a, b) => { const severityDelta = severityRank(a.severity) - severityRank(b.severity); if (severityDelta !== 0) return severityDelta; - return a.time - b.time; + const guidanceDelta = Number(isGuidanceIssue(a)) - Number(isGuidanceIssue(b)); + return guidanceDelta !== 0 ? guidanceDelta : a.time - b.time; }); return { issues: sortedIssues.slice(0, limit), diff --git a/packages/cli/src/utils/safeZones.ts b/packages/cli/src/utils/safeZones.ts new file mode 100644 index 0000000000..4ced471b9f --- /dev/null +++ b/packages/cli/src/utils/safeZones.ts @@ -0,0 +1,53 @@ +import { + SOCIAL_SAFE_AREAS, + TITLE_SAFE_PERCENT, + safeBoxInsetPercent, + type SafeArea, + type SocialSafeArea, +} from "@hyperframes/core/safe-areas"; +import type { LayoutRect } from "./layoutAudit.js"; + +export type SafeZone = SocialSafeArea | "standard"; +export type SafeZoneEdge = "left" | "top" | "right" | "bottom"; + +const TITLE_INSET = safeBoxInsetPercent(TITLE_SAFE_PERCENT); +const SAFE_AREAS: Record = { + ...SOCIAL_SAFE_AREAS, + standard: { + label: "title-safe margins", + width: 100, + height: 100, + clearBandsTopToBottom: [[TITLE_INSET, 100 - TITLE_INSET, TITLE_INSET, 100 - TITLE_INSET]], + }, +}; + +export function safeZoneLabel(zone: SafeZone): string { + return SAFE_AREAS[zone].label; +} + +/** The social areas only describe 9:16 frames; title-safe margins fit any frame. */ +export function safeZonesFor(zones: SafeZone[], canvas: { width: number; height: number }) { + const nineBySixteen = canvas.height > 0 && Math.abs(canvas.width / canvas.height - 9 / 16) < 0.01; + return zones.filter((zone) => zone === "standard" || nineBySixteen); +} + +export function safeZoneEdgesCrossed( + box: LayoutRect, + canvas: { width: number; height: number }, + zone: SafeZone, +): SafeZoneEdge[] { + const area = SAFE_AREAS[zone]; + const x = (value: number) => (value / area.width) * canvas.width; + const y = (value: number) => (value / area.height) * canvas.height; + const edges = new Set(); + const first = area.clearBandsTopToBottom[0]; + const last = area.clearBandsTopToBottom.at(-1); + if (first && box.top < y(first[0])) edges.add("top"); + if (last && box.bottom > y(last[1])) edges.add("bottom"); + for (const [top, bottom, left, right] of area.clearBandsTopToBottom) { + if (box.bottom <= y(top) || box.top >= y(bottom)) continue; + if (box.left < x(left)) edges.add("left"); + if (box.right > x(right)) edges.add("right"); + } + return (["left", "top", "right", "bottom"] as const).filter((edge) => edges.has(edge)); +} diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json index 1e3e4f2d6f..29aa4f794a 100644 --- a/packages/core/package-subpaths.json +++ b/packages/core/package-subpaths.json @@ -56,6 +56,12 @@ "types": "./dist/safePath.d.ts", "environments": ["bun", "node"] }, + "./safe-areas": { + "source": "./src/safeAreas.ts", + "runtime": "./dist/safeAreas.js", + "types": "./dist/safeAreas.d.ts", + "environments": ["browser", "bun", "node"] + }, "./browser-marker": { "source": "./src/browserMarker.ts", "runtime": "./dist/browserMarker.js", diff --git a/packages/core/package.json b/packages/core/package.json index c9bef6f003..ab35a8d182 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -68,6 +68,12 @@ "import": "./src/safePath.ts", "types": "./src/safePath.ts" }, + "./safe-areas": { + "bun": "./src/safeAreas.ts", + "node": "./dist/safeAreas.js", + "import": "./src/safeAreas.ts", + "types": "./src/safeAreas.ts" + }, "./browser-marker": { "bun": "./src/browserMarker.ts", "node": "./dist/browserMarker.js", @@ -678,6 +684,10 @@ "import": "./dist/safePath.js", "types": "./dist/safePath.d.ts" }, + "./safe-areas": { + "import": "./dist/safeAreas.js", + "types": "./dist/safeAreas.d.ts" + }, "./browser-marker": { "import": "./dist/browserMarker.js", "types": "./dist/browserMarker.d.ts" diff --git a/packages/core/src/lightEntries.test.ts b/packages/core/src/lightEntries.test.ts index 33c6827550..14ef99b736 100644 --- a/packages/core/src/lightEntries.test.ts +++ b/packages/core/src/lightEntries.test.ts @@ -22,7 +22,7 @@ function loadedModules(entry: string): string[] { } describe("entries a host imports for one helper", () => { - it.each(["./safe-path", "./asset-paths", "./preview-quality"])( + it.each(["./safe-path", "./safe-areas", "./asset-paths", "./preview-quality"])( "%s loads none of the parsers", (entry) => { expect(loadedModules(entry).filter((path) => HEAVY.test(path))).toEqual([]); diff --git a/packages/core/src/safeAreas.ts b/packages/core/src/safeAreas.ts new file mode 100644 index 0000000000..e3eec98eea --- /dev/null +++ b/packages/core/src/safeAreas.ts @@ -0,0 +1,46 @@ +export interface SafeArea { + label: string; + width: number; + height: number; + clearBandsTopToBottom: [top: number, bottom: number, left: number, right: number][]; +} + +// Vertical-ad guides checked 2026-10-13: TikTok in-feed ads template (720x1280, stepped right edge +// for the action buttons), Meta's Reels ads guide (bottom 35%; top 14% and sides 6% are a conservative +// pick), Google's YouTube Shorts video ad specs (1080x1920). Platform UI varies by caption and device. +export const SOCIAL_SAFE_AREAS = { + tiktok: { + label: "TikTok", + width: 720, + height: 1280, + clearBandsTopToBottom: [ + [160, 560, 80, 640], + [560, 840, 80, 520], + ], + }, + reels: { + label: "Instagram Reels", + width: 100, + height: 100, + clearBandsTopToBottom: [[14, 65, 6, 94]], + }, + shorts: { + label: "YouTube Shorts", + width: 1080, + height: 1920, + clearBandsTopToBottom: [[288, 1248, 48, 888]], + }, +} satisfies Record; + +export type SocialSafeArea = keyof typeof SOCIAL_SAFE_AREAS; +export const SOCIAL_SAFE_AREA_NAMES: SocialSafeArea[] = ["tiktok", "reels", "shorts"]; + +// Adobe Premiere default: action-safe and title-safe margins are 10% and 20% total (5% and 10% per edge). +export const ACTION_SAFE_PERCENT = 90; +export const TITLE_SAFE_PERCENT = 80; + +export const SAFE_BOX_PERCENTS = [ACTION_SAFE_PERCENT, TITLE_SAFE_PERCENT] as const; + +export function safeBoxInsetPercent(boxPercent: number): number { + return (100 - boxPercent) / 2; +} diff --git a/packages/studio/src/utils/previewSafeMargins.ts b/packages/studio/src/utils/previewSafeMargins.ts index 957786499f..1f60b16316 100644 --- a/packages/studio/src/utils/previewSafeMargins.ts +++ b/packages/studio/src/utils/previewSafeMargins.ts @@ -1,10 +1,6 @@ -// Adobe Premiere default: action-safe and title-safe margins are 10% and 20% total (5% and 10% per edge). -export const ACTION_SAFE_PERCENT = 90; -export const TITLE_SAFE_PERCENT = 80; - -export const SAFE_BOX_PERCENTS = [ACTION_SAFE_PERCENT, TITLE_SAFE_PERCENT] as const; - -/** Inset from each frame edge, as a percent of the frame. */ -export function safeBoxInsetPercent(boxPercent: number): number { - return (100 - boxPercent) / 2; -} +export { + ACTION_SAFE_PERCENT, + SAFE_BOX_PERCENTS, + TITLE_SAFE_PERCENT, + safeBoxInsetPercent, +} from "@hyperframes/core/safe-areas"; diff --git a/scripts/creator-editing-recipes.test.mjs b/scripts/creator-editing-recipes.test.mjs index 915742eaff..0dcc4aea59 100644 --- a/scripts/creator-editing-recipes.test.mjs +++ b/scripts/creator-editing-recipes.test.mjs @@ -60,7 +60,7 @@ test("the Remotion translation docs do not claim volume ramps are unsupported", }); test("the entry skill's safe boxes equal the preview's", async () => { - const src = await read("packages/studio/src/utils/previewSafeMargins.ts"); + const src = await read("packages/core/src/safeAreas.ts"); const action = src.match(/ACTION_SAFE_PERCENT = (\d+)/)?.[1]; const title = src.match(/TITLE_SAFE_PERCENT = (\d+)/)?.[1]; const skill = await read(ENTRY_SKILL);