fix(cli): share one motion classifier between sweep guard and liveness

The frozen-sweep guard (sweep_static) and keepsMoving liveness (motion_frozen)
each owned their own definition of "what counts as motion": the sweep
fingerprint in layout-audit.browser.js read nine channels while
motion-sample.browser.js compared box + opacity only. They meet in one decision
in checkPipeline.ts, so a fixed-width attr() countdown was accepted by the
sweep guard and still reported frozen by liveness.

Move the classifier into motion-signature.browser.js, injected before both
samplers, and make it the single owner:

- Per-element channels (box, opacity, font-variation axes, clip-path, direct
  text, form-control state, ::before/::after content, media pixels) as a
  reader list so further channels (e.g. SVG dash) plug in.
- Liveness consumes the same signature with 2px / 0.08 bucketing; the sweep
  guard consumes it exact. motion-sample throws at install if the shared
  script is missing.
- Counter state is a composition-level channel over box-generating elements
  and root ancestors. display:none subtrees generate no boxes and are
  excluded, and only declarations naming a counter that some painted
  generated content (::before/::after/::marker on a non-ignored, paintable
  host) consumes are folded in, so a decoy hidden counter cannot make a
  frozen composition read as live.
- clip-path is a channel, replacing the fingerprint's former reliance on the
  clipped-away visibility probe, so a wipe over a static box still counts.
- data-layout-ignore layers are excluded from the signature but not from the
  per-selector `visible` bit reported for explicit motion assertions.
- Root resolution for the "*" liveness scope now matches the sweep guard and
  the root element is part of its own signature.

Tests: motion-signature.browser.test.ts (happy-dom, per-element fake computed
style so ancestor handling comes from the classifier) and
motion-signature.browser.chromium.test.ts (real Chromium via puppeteer-core;
skips without a system browser) pin every branch: attr() substitution,
display:none decoys, named-counter gating, ::marker, zero-box hosts, ancestor
counters, textarea/indeterminate, root text, clip-path, ignore layers, and
sweep/liveness agreement on the countdown fixture.

Co-Authored-By: Miguel Ángel <miguel.sierra@heygen.com>
This commit is contained in:
miga-heygen
2026-09-14 17:48:11 +00:00
co-authored by Miguel Ángel
parent a329d21eca
commit fbec4c6023
14 changed files with 1663 additions and 627 deletions
+5
View File
@@ -104,6 +104,11 @@ async function main() {
cpSync(contrastAuditScript, join(DIST, "commands", "contrast-audit.browser.js"));
}
const motionSignatureScript = join(CLI_ROOT, "src", "commands", "motion-signature.browser.js");
if (existsSync(motionSignatureScript)) {
cpSync(motionSignatureScript, join(DIST, "commands", "motion-signature.browser.js"));
}
const motionSampleScript = join(CLI_ROOT, "src", "commands", "motion-sample.browser.js");
if (existsSync(motionSampleScript)) {
cpSync(motionSampleScript, join(DIST, "commands", "motion-sample.browser.js"));
@@ -1629,163 +1629,10 @@
return contentOverlapIssues(root, time);
};
// Frozen-sweep guard (#U10, checkPipeline.ts): a compact per-sample
// fingerprint of every visible element's box, opacity, and rendered text
// state, in DOM order. Node
// calls this once per seeked grid point and compares the strings across the
// whole run — if every sample produces the identical string, the seek never
// actually moved anything and the whole audit run is unreliable. Deliberately
// a single opaque string (not a structured array) since Node only ever needs
// equality, not per-element diffing.
// Pixel-only media motion (a 2D/WebGL canvas repainting or a playing video
// without any element moving) is invisible to a DOM-state fingerprint
// and false-positives sweep_static. Downsample each visible canvas/video to
// 8x8 and fold its pixels into the fingerprint. Tainted, zero-sized, or
// unreadable media hashes to a constant — no worse than DOM-state-only
// detection and never a new false negative for DOM-motion compositions.
// Media inside iframes is intentionally outside this fingerprint: it lives
// in a separate document, and cross-origin frames are inaccessible under SOP.
function mediaPixelHash(element) {
try {
const rect = element.getBoundingClientRect();
const sourceWidth = element.videoWidth || element.width || rect.width;
const sourceHeight = element.videoHeight || element.height || rect.height;
if (!sourceWidth || !sourceHeight) return "x";
const off = document.createElement("canvas");
off.width = 8;
off.height = 8;
const ctx = off.getContext("2d");
if (!ctx) return "x";
ctx.drawImage(element, 0, 0, 8, 8);
const data = ctx.getImageData(0, 0, 8, 8).data;
let hash = 0;
for (let i = 0; i < data.length; i++) hash = (hash * 31 + data[i]) >>> 0;
return String(hash);
} catch {
return "x";
}
}
function foldFingerprintField(hash, value) {
hash ^= value.length;
hash = Math.imul(hash, 16777619);
for (let i = 0; i < value.length; i++) {
hash ^= value.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash;
}
function cssFingerprintValue(value) {
return value === "none" || value === "normal" ? "" : value || "";
}
function foldCounterState(hash, style) {
hash = foldFingerprintField(hash, cssFingerprintValue(style.counterReset));
hash = foldFingerprintField(hash, cssFingerprintValue(style.counterIncrement));
return foldFingerprintField(hash, cssFingerprintValue(style.counterSet));
}
function counterStateHash(style) {
const reset = cssFingerprintValue(style.counterReset);
const increment = cssFingerprintValue(style.counterIncrement);
const set = cssFingerprintValue(style.counterSet);
if (!reset && !increment && !set) return "";
let hash = 2166136261;
hash = foldCounterState(hash, style);
return (hash >>> 0).toString(36);
}
function foldLiveControlState(hash, element) {
if (element.tagName === "INPUT") {
hash = foldFingerprintField(hash, element.type || "");
hash = foldFingerprintField(hash, element.value || "");
hash = foldFingerprintField(hash, element.checked ? "1" : "0");
return foldFingerprintField(hash, element.indeterminate ? "1" : "0");
}
if (element.tagName === "TEXTAREA") {
return foldFingerprintField(hash, element.value || "");
}
if (element.tagName !== "SELECT") return foldFingerprintField(hash, "");
hash = foldFingerprintField(hash, String(element.selectedIndex));
hash = foldFingerprintField(hash, element.value || "");
for (let i = 0; i < element.options.length; i++) {
hash = foldFingerprintField(hash, element.options[i].selected ? "1" : "0");
}
return hash;
}
function textualStateHash(element, style) {
// Chromium resolves attr() here, so pseudo computed content is the
// platform-owned rendered value rather than a CSS expression to reparse.
const before = getComputedStyle(element, "::before");
const after = getComputedStyle(element, "::after");
// Visible descendants are fingerprinted separately; direct nodes prevent
// a hidden descendant's text mutation from masquerading as visible motion.
let directText = "";
for (const node of directTextNodes(element)) {
directText += node.textContent || "";
}
let hash = 2166136261;
hash = foldFingerprintField(hash, directText);
hash = foldLiveControlState(hash, element);
hash = foldFingerprintField(hash, cssFingerprintValue(before.content));
hash = foldFingerprintField(hash, cssFingerprintValue(after.content));
hash = foldCounterState(hash, style);
hash = foldCounterState(hash, before);
hash = foldCounterState(hash, after);
return (hash >>> 0).toString(36);
}
window.__hyperframesLayoutGeometry = function collectLayoutGeometry() {
const root =
document.querySelector("[data-composition-id][data-width][data-height]") ||
document.querySelector("[data-composition-id]") ||
document.body;
const allElements = [root, ...root.querySelectorAll("*")];
const elements = allElements.filter((element) => isVisibleElement(element));
const parts = elements.map((element) => {
const rect = toRect(element.getBoundingClientRect());
const opacity = round(opacityChain(element));
// Variable-font axis animation (font-variation-settings) is a real,
// visible motion channel that moves no geometry and no opacity, so a
// box+opacity+text fingerprint reads it as a frozen timeline. Worse in a
// DUPLEXED face (Recursive holds an identical advance width at every
// weight by design), where not even the line width shifts — the whole
// run then false-positives sweep_static. Fold the computed axis string
// in; it is "normal" for every element that does not use it, so this
// adds nothing to the fingerprint of an ordinary composition.
const style = getComputedStyle(element);
const axes = style.fontVariationSettings;
const textState = textualStateHash(element, style);
return `${rect.left},${rect.top},${rect.width},${rect.height},${opacity},${
axes && axes !== "normal" ? axes : ""
},${textState}`;
});
const visibleElements = new Set(elements);
for (let ancestor = root.parentElement; ancestor; ancestor = ancestor.parentElement) {
const state = counterStateHash(getComputedStyle(ancestor));
if (state) parts.push(`c:${state}`);
}
// Counter declarations can live on zero-box owners while a visible
// descendant's ::before/::after paints the resulting value.
for (const element of allElements) {
if (visibleElements.has(element)) continue;
const state = counterStateHash(getComputedStyle(element));
if (state) parts.push(`c:${state}`);
}
// img shares the same pixel-only-motion blind spot as canvas/video: an
// equal-size, equal-position opaque src/visibility swap moves no
// geometry and no opacity. mediaPixelHash already handles it generically
// (drawImage accepts any CanvasImageSource; width/height fall back to
// rect.width/height same as canvas/video), so only the element selector
// needed widening.
for (const media of root.querySelectorAll("canvas, video, img")) {
if (!isVisibleElement(media)) continue;
parts.push(`p:${mediaPixelHash(media)}`);
}
return parts.join("|");
};
// The frozen-sweep fingerprint (window.__hyperframesLayoutGeometry, #U10 in
// checkPipeline.ts) lives in motion-signature.browser.js, the single owner
// of "what counts as motion" shared with motion-sample.browser.js's
// liveness signature.
// Rotation-pivot sampling (rotation_pivot_drift). Per sample, report every
// rotatable candidate's bbox center, size, and current rotation angle. Node
@@ -31,400 +31,6 @@ describe("layout-audit.browser", () => {
clearGeometryCollector();
});
it("changes the sweep fingerprint when visible video pixels advance", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<video id="footage"></video>
</div>
`;
installGeometry({
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
footage: rect({ left: 0, top: 0, width: 640, height: 360 }),
});
let pixelValue = 20;
const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
mockReturnValue(value: CanvasRenderingContext2D): void;
};
getContextSpy.mockReturnValue({
drawImage() {},
getImageData() {
return { data: new Uint8ClampedArray(8 * 8 * 4).fill(pixelValue) };
},
} as unknown as CanvasRenderingContext2D);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
pixelValue = 220;
const after = collect();
expect(after).not.toBe(before);
});
// PRINFRA-666: an equal-size, equal-position opaque <img> src/visibility
// swap (the authoring pattern for a paused-GSAP-cursor-driven "reveal
// frame N of a still sequence" composition) moves no geometry and no
// opacity, so it was invisible to the fingerprint and false-positived
// sweep_static — mediaPixelHash already existed for exactly this pixel-only
// motion class, it just wasn't applied to img.
it("changes the sweep fingerprint when a same-size opaque img is swapped", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<img id="frame" />
</div>
`;
installGeometry({
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
frame: rect({ left: 0, top: 0, width: 640, height: 360 }),
});
let pixelValue = 20;
const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
mockReturnValue(value: CanvasRenderingContext2D): void;
};
getContextSpy.mockReturnValue({
drawImage() {},
getImageData() {
return { data: new Uint8ClampedArray(8 * 8 * 4).fill(pixelValue) };
},
} as unknown as CanvasRenderingContext2D);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
pixelValue = 220;
const after = collect();
expect(after).not.toBe(before);
});
// Opacity-reveal fixture (CLI feedback digest 2026-07-14): code-typing style
// scenes reveal pre-laid-out characters via opacity only — no geometry ever
// moves. The sweep fingerprint must treat that as motion, both while a glyph
// fades (opacity value changes) and when it crosses the 0.2 visibility floor
// (element enters the signature); otherwise `check` misfires `sweep_static`
// and authors reach for geometry hacks (a slow host y-drift) to pass.
it("changes the sweep fingerprint when text reveals via opacity alone", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="code"><span id="char">c</span></div>
</div>
`;
let charOpacity = "0";
installGeometry(
{
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
code: rect({ left: 40, top: 40, width: 560, height: 48 }),
char: rect({ left: 40, top: 40, width: 18, height: 48 }),
},
{
char: {
get opacity() {
return charOpacity;
},
} as Partial<CSSStyleDeclaration>,
},
);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const hidden = collect(); // below the 0.2 visibility floor — not in the signature
charOpacity = "0.5";
const fading = collect(); // mid-fade — present, opacity part of the signature
charOpacity = "1";
const revealed = collect(); // settled
expect(fading).not.toBe(hidden);
expect(revealed).not.toBe(fading);
});
// Variable-font axis animation (registry block `weight-wave`): a crest of
// weight travels along a headline by rewriting each character's
// font-variation-settings, and NOTHING else changes — no geometry, no
// opacity, no canvas. A duplexed face makes it total: Recursive holds one
// advance width at every weight by design, so not even the line width
// shifts and all six sweep samples hashed identically until the axis string
// joined the fingerprint. `check` then failed a working composition with
// sweep_static, and the documented remedies (spread the reveal, keep an
// element animating) cannot help — the motion is real, the fingerprint was
// just blind to it.
it("changes the sweep fingerprint when only font-variation-settings moves", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="line"><span id="char">P</span></div>
</div>
`;
let axes = '"wght" 400, "slnt" 0';
installGeometry(
{
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
line: rect({ left: 40, top: 40, width: 560, height: 48 }),
char: rect({ left: 40, top: 40, width: 18, height: 48 }),
},
{
char: {
get fontVariationSettings() {
return axes;
},
} as Partial<CSSStyleDeclaration>,
},
);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const rest = collect();
axes = '"wght" 1000, "slnt" -12'; // the crest arrives over this character
const crest = collect();
expect(crest).not.toBe(rest);
});
// The other direction, and it guards the more dangerous failure: a
// fingerprint that varies on its own would make sweep_static unfireable and
// every green layout verdict meaningless. Identical scene, axes included,
// must hash identically.
it("keeps the sweep fingerprint identical when nothing moves, font axes included", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="line"><span id="char">P</span></div>
</div>
`;
installGeometry(
{
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
line: rect({ left: 40, top: 40, width: 560, height: 48 }),
char: rect({ left: 40, top: 40, width: 18, height: 48 }),
},
{
char: { fontVariationSettings: '"wght" 400, "slnt" 0' } as Partial<CSSStyleDeclaration>,
},
);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
expect(collect()).toBe(collect());
});
it("changes the sweep fingerprint when fixed-width text content changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown">10</span>
</div>
`;
installGeometry({
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
countdown: rect({ left: 280, top: 140, width: 80, height: 48 }),
});
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
document.getElementById("countdown")!.textContent = "09";
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when an attr-backed data value changes", () => {
document.body.innerHTML = `
<style>#countdown::after { content: attr(data-txt); }</style>
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown" data-txt="10"></span>
</div>
`;
installGeometry(
{
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
countdown: rect({ left: 280, top: 140, width: 80, height: 48 }),
},
{},
{
countdown: {
after: {
get content() {
return JSON.stringify(document.getElementById("countdown")!.getAttribute("data-txt"));
},
} as Partial<CSSStyleDeclaration>,
},
},
);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
document.getElementById("countdown")!.setAttribute("data-txt", "09");
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when pseudo-element content changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown"></span>
</div>
`;
let generatedContent = '"10"';
installGeometry(
{
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
countdown: rect({ left: 280, top: 140, width: 80, height: 48 }),
},
{},
{
countdown: {
after: {
get content() {
return generatedContent;
},
} as Partial<CSSStyleDeclaration>,
},
},
);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
generatedContent = '"09"';
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when CSS counter state changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="counter-owner"><span id="countdown"></span></div>
</div>
`;
let counterReset = "countdown 10";
installGeometry(
{
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
"counter-owner": rect({ left: 0, top: 0, width: 0, height: 0 }),
countdown: rect({ left: 280, top: 140, width: 80, height: 48 }),
},
{
"counter-owner": {
get counterReset() {
return counterReset;
},
} as Partial<CSSStyleDeclaration>,
},
{
countdown: {
after: { content: "counter(countdown)" } as Partial<CSSStyleDeclaration>,
},
},
);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
counterReset = "countdown 9";
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when checkbox state changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<input id="toggle" type="checkbox" />
</div>
`;
installGeometry({
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
toggle: rect({ left: 280, top: 140, width: 24, height: 24 }),
});
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
(document.getElementById("toggle") as HTMLInputElement).checked = true;
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a secondary select option changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<select id="choices" multiple><option selected>A</option><option>B</option></select>
</div>
`;
installGeometry({
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
choices: rect({ left: 280, top: 140, width: 120, height: 48 }),
});
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
(document.getElementById("choices") as HTMLSelectElement).options[1]!.selected = true;
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a fixed-width form value changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<input id="countdown" value="10" />
</div>
`;
installGeometry({
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
countdown: rect({ left: 280, top: 140, width: 80, height: 48 }),
});
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const before = collect();
(document.getElementById("countdown") as HTMLInputElement).value = "09";
expect(collect()).not.toBe(before);
});
it("keeps textual sweep channels identical when the countdown is truly frozen", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown" data-txt="10">10</span>
</div>
`;
installGeometry(
{
root: rect({ left: 0, top: 0, width: 640, height: 360 }),
countdown: rect({ left: 280, top: 140, width: 80, height: 48 }),
},
{ countdown: { counterReset: "countdown 10" } as Partial<CSSStyleDeclaration> },
{
countdown: {
after: { content: '"10"' } as Partial<CSSStyleDeclaration>,
},
},
);
installAuditScript();
const collect = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
expect(collect()).toBe(collect());
});
it("uses authored canvas dimensions when the root bounding rect is degenerate", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
@@ -3324,23 +2930,13 @@ function rangeTextRect(selected: Node | null, rects: Record<string, DOMRect>): D
function installGeometry(
rects: Record<string, DOMRect>,
styleOverrides: Record<string, Partial<CSSStyleDeclaration>> = {},
pseudoStyleOverrides: Record<
string,
{ before?: Partial<CSSStyleDeclaration>; after?: Partial<CSSStyleDeclaration> }
> = {},
): void {
// Style-fixture branching mirrors the audit's per-property reads; splitting
// it would scatter one mock across helpers.
// fallow-ignore-next-line complexity
vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => {
vi.spyOn(window, "getComputedStyle").mockImplementation((element) => {
const el = element as Element;
const isBubble = el.id === "bubble";
const pseudoOverride =
pseudoElement === "::before"
? pseudoStyleOverrides[el.id]?.before
: pseudoElement === "::after"
? pseudoStyleOverrides[el.id]?.after
: undefined;
return {
display: "block",
visibility: "visible",
@@ -3364,7 +2960,6 @@ function installGeometry(
paddingLeft: isBubble ? "16px" : "0px",
fontSize: "36px",
...styleOverrides[el.id],
...pseudoOverride,
} as unknown as CSSStyleDeclaration;
});
+1
View File
@@ -390,6 +390,7 @@ async function runMotionPass(
width: window.innerWidth,
height: window.innerHeight,
}));
await page.addScriptTag({ content: loadBrowserScript("motion-signature.browser.js") });
await page.addScriptTag({ content: loadBrowserScript("motion-sample.browser.js") });
const frames = await collectMotionFrames(page, times, selectors, livenessScopes);
return { issues: evaluateMotion(frames, spec.assertions, canvas), sampleCount: frames.length };
@@ -4,7 +4,13 @@
// scope it returns a bucketed signature of all visible elements, so the Node-side
// evaluator can detect frozen windows by comparing signatures across frames.
(function () {
const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]);
// Visibility, opacity, and the liveness signature all come from the shared
// motion classifier so this sampler and the frozen-sweep guard can never
// disagree on what counts as motion (see motion-signature.browser.js).
const shared = window.__hyperframesMotionSignature;
if (!shared) {
throw new Error("motion-signature.browser.js must be injected before motion-sample.browser.js");
}
function round(value) {
return Math.round(value * 100) / 100;
@@ -21,71 +27,15 @@
};
}
function opacityChain(element) {
let opacity = 1;
for (let current = element; current; current = current.parentElement) {
const parsed = Number.parseFloat(getComputedStyle(current).opacity || "1");
if (Number.isFinite(parsed)) opacity *= parsed;
}
return opacity;
}
// Mirrors layout-audit.browser.js isVisibleElement.
// fallow-ignore-next-line complexity
function isVisibleElement(element) {
if (IGNORE_TAGS.has(element.tagName)) return false;
const style = getComputedStyle(element);
if (
style.display === "none" ||
style.visibility === "hidden" ||
style.visibility === "collapse"
) {
return false;
}
if (opacityChain(element) < 0.2) return false;
const rect = element.getBoundingClientRect();
return rect.width > 0.5 && rect.height > 0.5;
}
function sampleElement(element) {
const rect = element.getBoundingClientRect();
return {
rect: toRect(rect),
opacity: round(opacityChain(element)),
visible: isVisibleElement(element),
opacity: round(shared.opacityChain(element)),
visible: shared.isVisibleElement(element),
};
}
function compositionRoot() {
return document.querySelector("[data-composition-id]") || document.body;
}
// ponytail: bucket position to 2px and opacity to 0.08 so the RFC's "moves ≥2px /
// opacity ≥0.08" thresholds fall out of bucketing. Boundary-straddling moves are
// approximate — good enough for liveness; tighten only if false negatives show up.
function elementSignature(element) {
const rect = element.getBoundingClientRect();
const bx = Math.round(rect.left / 2);
const by = Math.round(rect.top / 2);
const bw = Math.round(rect.width / 2);
const bh = Math.round(rect.height / 2);
const bo = Math.round(opacityChain(element) / 0.08);
return bx + "," + by + "," + bw + "," + bh + "," + bo;
}
function livenessSignature(root) {
if (!root) return "";
const parts = [];
// ponytail: O(DOM) × MOTION_MAX_SAMPLES (300) — fine for typical compositions;
// narrow selector (e.g. "[id],[class]") if heavy-DOM compositions slow this down.
const all = root.querySelectorAll("*");
for (const element of all) {
if (!isVisibleElement(element)) continue;
parts.push(elementSignature(element));
}
return parts.join("|");
}
function safeQuery(selector) {
try {
return document.querySelector(selector);
@@ -108,8 +58,12 @@
function sampleLiveness(scopes) {
const liveness = {};
for (const scope of scopes) {
const root = scope === "*" ? compositionRoot() : safeQuery(scope);
liveness[scope] = livenessSignature(root);
const root = scope === "*" ? shared.compositionRoot() : safeQuery(scope);
// ponytail: O(DOM) × MOTION_MAX_SAMPLES (300), with three computed-style
// reads (element + ::before/::after) plus an ancestor walk per box-generating
// element — fine for typical compositions; narrow the scope if heavy-DOM
// compositions slow down.
liveness[scope] = shared.compositionSignature(root, { quantize: true });
}
return liveness;
}
@@ -6,6 +6,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const signatureScript = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8");
const script = readFileSync(join(__dirname, "motion-sample.browser.js"), "utf-8");
interface Geo {
@@ -13,6 +14,8 @@ interface Geo {
opacity?: string;
display?: string;
visibility?: string;
/** `::after` computed `content`; re-read on every call when a getter. */
afterContent?: string;
}
interface SampleResult {
@@ -24,8 +27,13 @@ interface SampleResult {
}
function installGeometry(byId: Record<string, Geo>): void {
vi.spyOn(window, "getComputedStyle").mockImplementation((element) => {
vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => {
const geo = byId[(element as Element).id] ?? {};
if (pseudoElement) {
return {
content: pseudoElement === "::after" ? (geo.afterContent ?? "none") : "none",
} as unknown as CSSStyleDeclaration;
}
return {
display: geo.display ?? "block",
visibility: geo.visibility ?? "visible",
@@ -47,6 +55,9 @@ function installGeometry(byId: Record<string, Geo>): void {
}
function installScript(): void {
// The sampler reads the shared motion classifier at install time.
// eslint-disable-next-line no-new-func
new Function(signatureScript)();
// eslint-disable-next-line no-new-func
new Function(script)();
}
@@ -62,6 +73,13 @@ describe("motion-sample.browser", () => {
vi.restoreAllMocks();
document.body.innerHTML = "";
delete (window as unknown as { __hyperframesMotionSample?: unknown }).__hyperframesMotionSample;
Reflect.deleteProperty(window, "__hyperframesMotionSignature");
Reflect.deleteProperty(window, "__hyperframesLayoutGeometry");
});
it("throws at install when the shared motion classifier is missing", () => {
// eslint-disable-next-line no-new-func
expect(() => new Function(script)()).toThrow(/motion-signature\.browser\.js/);
});
it("samples a present, visible selector and returns null for an absent one", () => {
@@ -79,6 +97,18 @@ describe("motion-sample.browser", () => {
expect(result.data["#missing"]).toBeNull();
});
it("reports an explicitly asserted data-layout-ignore element as visible", () => {
document.body.innerHTML = `
<div data-composition-id="main"><div id="glow" data-layout-ignore>x</div></div>
`;
installGeometry({ glow: { rect: { left: 100, top: 50, width: 300, height: 80 } } });
installScript();
// The layout-audit opt-out excludes the layer from liveness, not from an
// assertion that names it.
expect(sample({ selectors: ["#glow"] }).data["#glow"]?.visible).toBe(true);
});
it("reflects inherited ancestor opacity", () => {
document.body.innerHTML = `
<div data-composition-id="main"><div id="wrap"><div id="headline">Hi</div></div></div>
@@ -114,6 +144,46 @@ describe("motion-sample.browser", () => {
expect(moved).not.toBe(before);
});
// Liveness and the frozen-sweep guard share one classifier: a fixed-width
// attr()-backed countdown that the sweep guard accepts as motion must not be
// reported frozen by keepsMoving.
it("changes the liveness signature when attr-backed generated content changes, in step with the sweep fingerprint", () => {
document.body.innerHTML = `
<div data-composition-id="main"><span id="countdown" data-txt="10"></span></div>
`;
installGeometry({
countdown: {
rect: { left: 280, top: 140, width: 80, height: 48 },
get afterContent() {
return JSON.stringify(document.getElementById("countdown")!.getAttribute("data-txt"));
},
},
});
installScript();
const sweep = (window as unknown as { __hyperframesLayoutGeometry: () => string })
.__hyperframesLayoutGeometry;
const livenessBefore = sample({ livenessScopes: ["*"] }).liveness["*"];
const sweepBefore = sweep();
document.getElementById("countdown")!.setAttribute("data-txt", "09");
expect(sample({ livenessScopes: ["*"] }).liveness["*"]).not.toBe(livenessBefore);
expect(sweep()).not.toBe(sweepBefore);
});
it("signs a leaf withinSelector scope by the scope element itself", () => {
document.body.innerHTML = `
<div data-composition-id="main"><div id="logo">x</div></div>
`;
installGeometry({ logo: { rect: { left: 10, top: 10, width: 50, height: 50 } } });
installScript();
// The scope root is part of its own signature; a leaf scope is never "missing".
expect((sample({ livenessScopes: ["#logo"] }).liveness["#logo"] ?? "").length).toBeGreaterThan(
0,
);
});
it("scopes liveness to a withinSelector and returns empty for a missing scope", () => {
document.body.innerHTML = `
<div data-composition-id="main"><div id="scene"><div id="box">x</div></div></div>
@@ -0,0 +1,384 @@
// fallow-ignore-file code-duplication
// Real-Chromium pins for motion-signature.browser.js. The happy-dom suite
// (motion-signature.browser.test.ts) mocks getComputedStyle, so it asserts the
// classifier's control flow against a fake; this suite asserts the same
// branches against the platform — Blink's attr() substitution in computed
// pseudo content, unsubstituted counter(), display:none subtrees, clip-path,
// and form control state — using the exact scripts `hyperframes check` injects.
// Skipped when no Chrome/Chromium binary is available without downloading.
import { existsSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { Browser, Page } from "puppeteer-core";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { findSystemBrowser } from "../browser/manager.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const signatureScript = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8");
const motionSampleScript = readFileSync(join(__dirname, "motion-sample.browser.js"), "utf-8");
function resolveExecutable(): string | undefined {
for (const name of ["HYPERFRAMES_BROWSER_PATH", "PUPPETEER_EXECUTABLE_PATH"]) {
const candidate = process.env[name];
if (candidate && existsSync(candidate)) return candidate;
}
return findSystemBrowser()?.executablePath;
}
const executablePath = resolveExecutable();
interface Samples {
sweep: string;
liveness: string;
}
declare global {
interface Window {
__hyperframesLayoutGeometry: () => string;
__hyperframesMotionSample: (options: { livenessScopes: string[] }) => {
liveness: Record<string, string>;
};
}
}
function composition(css: string, body: string): string {
return `<!doctype html><html><head><style>
html, body { margin: 0; }
#root { position: relative; width: 640px; height: 360px; }
.fixed { display: inline-block; width: 80px; height: 48px; font: 32px/48px monospace; text-align: center; }
${css}
</style></head><body>
<div id="root" data-composition-id="main" data-width="640" data-height="360">${body}</div>
</body></html>`;
}
describe.skipIf(!executablePath)("motion-signature.browser in Chromium", () => {
let browser: Browser;
let page: Page;
beforeAll(async () => {
const puppeteer = await import("puppeteer-core");
browser = await puppeteer.default.launch({
headless: true,
executablePath,
args: ["--no-sandbox", "--disable-dev-shm-usage", "--disable-gpu"],
});
page = await browser.newPage();
await page.setViewport({ width: 640, height: 360 });
});
afterAll(async () => {
await browser?.close();
});
async function load(html: string): Promise<void> {
await page.setContent(html);
await page.addScriptTag({ content: signatureScript });
await page.addScriptTag({ content: motionSampleScript });
}
async function sample(): Promise<Samples> {
return page.evaluate(() => ({
sweep: window.__hyperframesLayoutGeometry(),
liveness: window.__hyperframesMotionSample({ livenessScopes: ["*"] }).liveness["*"] ?? "",
}));
}
async function mutate(script: string): Promise<void> {
await page.evaluate(script);
}
it("treats an attr()-backed fixed-width countdown as motion in both samplers", async () => {
await load(
composition(
"#countdown::after { content: attr(data-txt); }",
'<span id="countdown" class="fixed" data-txt="10"></span>',
),
);
const before = await sample();
await mutate('document.getElementById("countdown").setAttribute("data-txt", "09")');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
expect(after.liveness).not.toBe(before.liveness);
});
it("keeps both signatures identical when a countdown with every textual channel is frozen", async () => {
await load(
composition(
"body { counter-reset: countdown 10; } #countdown::after { content: attr(data-txt) counter(countdown); }",
'<span id="countdown" class="fixed" data-txt="10">10</span><textarea id="note">10</textarea>',
),
);
const first = await sample();
const second = await sample();
expect(second).toEqual(first);
});
it("ignores a display:none decoy counter owner in a frozen composition", async () => {
await load(
composition(
"#decoy { display: none; counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }",
'<div id="decoy"></div><span id="countdown" class="fixed"></span>',
),
);
const before = await sample();
await mutate('document.getElementById("decoy").style.counterReset = "countdown 9"');
const after = await sample();
expect(after).toEqual(before);
});
it("ignores a decoy counter owner nested inside a display:none subtree", async () => {
await load(
composition(
"#hidden-parent { display: none; } #decoy { display: block; counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }",
'<div id="hidden-parent"><div id="decoy"></div></div><span id="countdown" class="fixed"></span>',
),
);
const before = await sample();
await mutate('document.getElementById("decoy").style.counterReset = "countdown 9"');
const after = await sample();
expect(after).toEqual(before);
});
it("ignores counter state when nothing paints a counter", async () => {
await load(
composition(
"#owner { height: 0; counter-reset: countdown 10; }",
'<div id="owner"></div><span id="countdown" class="fixed">10</span>',
),
);
const before = await sample();
await mutate('document.getElementById("owner").style.counterReset = "countdown 9"');
const after = await sample();
expect(after).toEqual(before);
});
it("ignores a zero-box decoy whose counter name nothing paints even when a list marker exists", async () => {
await load(
composition(
"li { width: 80px; height: 48px; } #decoy { height: 0; counter-reset: decoy 10; }",
'<ul><li>item</li></ul><div id="decoy"></div>',
),
);
expect(await page.evaluate(() => getComputedStyle(document.querySelector("li")!).display)).toBe(
"list-item",
);
const before = await sample();
await mutate('document.getElementById("decoy").style.counterReset = "decoy 9"');
const after = await sample();
expect(after).toEqual(before);
});
it("ignores a counter consumed only by a pseudo-element under a data-layout-ignore layer", async () => {
await load(
composition(
"#owner { height: 0; counter-reset: countdown 10; } #a::after { content: counter(countdown); }",
'<div id="owner"></div><div data-layout-ignore><span id="a" class="fixed"></span></div>',
),
);
const before = await sample();
await mutate('document.getElementById("owner").style.counterReset = "countdown 9"');
const after = await sample();
expect(after).toEqual(before);
});
it("ignores a counter consumed only by a pseudo-element that inherits visibility:hidden", async () => {
await load(
composition(
"#owner { height: 0; counter-reset: countdown 10; } #a { visibility: hidden; } #a::after { content: counter(countdown); }",
'<div id="owner"></div><span id="a" class="fixed"></span>',
),
);
const before = await sample();
await mutate('document.getElementById("owner").style.counterReset = "countdown 9"');
const after = await sample();
expect(after).toEqual(before);
});
it("sees a counter painted by a visible pseudo-element on a visibility:hidden host", async () => {
await load(
composition(
"body { counter-reset: countdown 10; } #a { visibility: hidden; } #a::after { visibility: visible; content: counter(countdown); }",
'<span id="a" class="fixed"></span>',
),
);
const before = await sample();
await mutate('document.body.style.counterReset = "countdown 9"');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
});
it("sees a counter painted only through a ::marker", async () => {
await load(
composition(
"#owner { height: 0; counter-reset: countdown 10; } li { width: 80px; height: 48px; } li::marker { content: counter(countdown); }",
'<div id="owner"></div><ul><li>item</li></ul>',
),
);
const before = await sample();
await mutate('document.getElementById("owner").style.counterReset = "countdown 9"');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
});
it("sees counters(), styled counter(), and counter-set owners", async () => {
await load(
composition(
"#owner { height: 0; counter-reset: outer 1 inner 5; counter-set: styled 10; } #a::after { content: counters(outer, '.') ' ' counter(styled, upper-roman); }",
'<div id="owner"></div><span id="a" class="fixed"></span>',
),
);
const start = await sample();
await mutate('document.getElementById("owner").style.counterReset = "outer 2 inner 5"');
const afterCounters = await sample();
await mutate('document.getElementById("owner").style.counterSet = "styled 9"');
const afterSet = await sample();
expect(afterCounters.sweep).not.toBe(start.sweep);
expect(afterSet.sweep).not.toBe(afterCounters.sweep);
});
it("sees a zero-box owner's counter change when a visible pseudo-element paints it", async () => {
await load(
composition(
"#owner { counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }",
'<div id="owner"><span id="countdown" class="fixed"></span></div>',
),
);
// Blink leaves counter() unsubstituted in computed content, so the only
// signal is the owner's counter state.
expect(
await page.evaluate(
() => getComputedStyle(document.getElementById("countdown")!, "::after").content,
),
).toBe("counter(countdown)");
const before = await sample();
await mutate('document.getElementById("owner").style.counterReset = "countdown 9"');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
expect(after.liveness).not.toBe(before.liveness);
});
it("sees a counter painted by a zero-box host's absolutely positioned pseudo-element", async () => {
await load(
composition(
"body { counter-reset: countdown 10; } #host { width: 0; height: 0; } #host::after { position: absolute; left: 100px; top: 100px; content: counter(countdown); }",
'<div id="host"></div>',
),
);
const before = await sample();
await mutate('document.body.style.counterReset = "countdown 9"');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
});
it("sees a counter owned above the composition root change", async () => {
await load(
composition(
"body { counter-reset: countdown 10; } #countdown::after { content: counter(countdown); }",
'<span id="countdown" class="fixed"></span>',
),
);
const before = await sample();
await mutate('document.body.style.counterReset = "countdown 9"');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
});
it("sees a pseudo-element's own counter-increment change", async () => {
await load(
composition(
"#countdown::after { counter-increment: countdown 10; content: counter(countdown); } #countdown.next::after { counter-increment: countdown 9; }",
'<span id="countdown" class="fixed"></span>',
),
);
const before = await sample();
await mutate('document.getElementById("countdown").classList.add("next")');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
});
it("sees a clip-path wipe over a box that never moves", async () => {
await load(
composition(
"#panel { width: 200px; height: 100px; background: #f00; clip-path: inset(0 100% 0 0); }",
'<div id="panel"></div>',
),
);
const before = await sample();
await mutate('document.getElementById("panel").style.clipPath = "inset(0 50% 0 0)"');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
expect(after.liveness).not.toBe(before.liveness);
});
it("sees textarea value and checkbox indeterminate changes", async () => {
await load(
composition(
"",
'<textarea id="note" class="fixed">10</textarea><input id="toggle" type="checkbox" />',
),
);
const start = await sample();
await mutate('document.getElementById("note").value = "09"');
const afterText = await sample();
await mutate('document.getElementById("toggle").indeterminate = true');
const afterIndeterminate = await sample();
expect(afterText.sweep).not.toBe(start.sweep);
expect(afterIndeterminate.sweep).not.toBe(afterText.sweep);
});
it("sees the composition root's own text change", async () => {
await load(composition("", "10"));
const before = await sample();
await mutate('document.getElementById("root").firstChild.textContent = "09"');
const after = await sample();
expect(after.sweep).not.toBe(before.sweep);
expect(after.liveness).not.toBe(before.liveness);
});
it("ignores text mutations inside a display:none descendant", async () => {
await load(
composition(
"#hidden { display: none; }",
'<span id="countdown" class="fixed">10<span id="hidden">10</span></span>',
),
);
const before = await sample();
await mutate('document.getElementById("hidden").textContent = "09"');
const after = await sample();
expect(after).toEqual(before);
});
it("ignores motion on a data-layout-ignore layer", async () => {
await load(
composition(
"#glow { position: absolute; width: 100px; height: 100px; background: #0f0; }",
'<div id="glow" data-layout-ignore></div><span id="countdown" class="fixed">10</span>',
),
);
const before = await sample();
await mutate('document.getElementById("glow").style.left = "200px"');
const after = await sample();
expect(after).toEqual(before);
});
});
@@ -0,0 +1,361 @@
// Shared "what counts as motion" classifier for the two seek-time samplers.
// Injected via page.addScriptTag BEFORE layout-audit.browser.js and
// motion-sample.browser.js (see checkBrowser.ts injectAuditScripts and
// layout.ts); both consume it through window.__hyperframesMotionSignature.
//
// Two Node-side decisions compare per-sample signatures of the composition:
// - the frozen-sweep guard (#U10, checkPipeline.ts detectSweepStatic) reads
// window.__hyperframesLayoutGeometry once per layout-grid seek and fails
// the run with sweep_static when every sample is byte-identical;
// - keepsMoving liveness (motionAudit.ts) reads motion-sample's liveness
// signature per motion sample and reports motion_frozen on long runs of
// identical signatures.
// They meet in one decision (a motion_frozen finding suppresses sweep_static),
// so the set of channels that count as motion MUST be identical for both —
// otherwise a composition one sampler accepts as live is rejected as frozen
// by the other. This module is that single owner. The only sanctioned
// difference is quantization: liveness buckets position to 2px and opacity to
// 0.08 so the motion RFC's "moves ≥2px / opacity ≥0.08" thresholds fall out of
// bucketing, while the sweep guard wants exact (0.01) rounding because it asks
// whether the seek moved anything at all.
//
// Adding a channel (e.g. SVG stroke-dasharray/dashoffset): append one reader
// `(element, ctx) => string` to ELEMENT_CHANNELS. `ctx` carries the element's
// computed style, its ::before/::after styles, its inherited opacity, and the
// quantize flag. A reader returns a string that is equal between two samples
// iff that channel did not visibly change; return "" for elements the channel
// does not apply to so ordinary compositions gain no payload.
//
// Signatures are a single opaque string per sample (not a structured array):
// Node only ever needs equality, never per-element diffing. Textual channels
// are hashed (FNV-1a, length-delimited fields) so raw composition text never
// leaves the page and per-sample payloads stay compact.
(function () {
const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]);
const MEDIA_TAGS = new Set(["CANVAS", "VIDEO", "IMG"]);
const FNV_OFFSET_BASIS = 2166136261;
const FNV_PRIME = 16777619;
const LIVENESS_POSITION_BUCKET_PX = 2;
const LIVENESS_OPACITY_BUCKET = 0.08;
const IGNORE_SELECTOR = "[data-layout-ignore], [data-layout-check='ignore']";
// counter(name) / counters(name, sep) in generated content. A list-item box
// whose ::marker content is `normal` paints counter(list-item) implicitly.
const COUNTER_FUNCTION = /counters?\(\s*([^\s,)]+)/g;
const IMPLICIT_MARKER_CONTENT = "counter(list-item)";
const LIST_ITEM_DISPLAY = /\blist-item\b/;
function round(value) {
return Math.round(value * 100) / 100;
}
function opacityChain(element) {
let opacity = 1;
for (let current = element; current; current = current.parentElement) {
const parsed = Number.parseFloat(getComputedStyle(current).opacity || "1");
if (Number.isFinite(parsed)) opacity *= parsed;
}
return opacity;
}
function compositionRoot() {
return (
document.querySelector("[data-composition-id][data-width][data-height]") ||
document.querySelector("[data-composition-id]") ||
document.body
);
}
function isHiddenStyle(style) {
return (
style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse"
);
}
// Same visibility floor as layout-audit.browser.js isVisibleElement's default.
// The author opt-out (data-layout-ignore / data-layout-check=ignore) is NOT
// applied here: motion-sample reports this bit for explicitly asserted
// selectors, and an assertion naming an element outranks a layout-audit
// opt-out. compositionSignature applies the opt-out itself (see there).
// clip-path is not probed either; it is a channel, so a clip-path wipe over a
// static box counts as motion directly.
// fallow-ignore-next-line complexity
function isVisibleElement(element, style, opacity) {
if (IGNORE_TAGS.has(element.tagName)) return false;
if (isHiddenStyle(style || getComputedStyle(element))) return false;
if ((opacity === undefined ? opacityChain(element) : opacity) < 0.2) return false;
const rect = element.getBoundingClientRect();
return rect.width > 0.5 && rect.height > 0.5;
}
function foldField(hash, value) {
hash ^= value.length;
hash = Math.imul(hash, FNV_PRIME);
for (let i = 0; i < value.length; i++) {
hash ^= value.charCodeAt(i);
hash = Math.imul(hash, FNV_PRIME);
}
return hash;
}
function hashFields(fields) {
let hash = FNV_OFFSET_BASIS;
for (const field of fields) hash = foldField(hash, field);
return (hash >>> 0).toString(36);
}
// `none` / `normal` are the computed initial values of content, counter-*,
// clip-path, and font-variation-settings; collapse them so unused channels
// stay "".
function cssValue(value) {
return value === "none" || value === "normal" ? "" : value || "";
}
// --- Per-element channels: (element, ctx) => string --------------------------
function boxChannel(element, ctx) {
const rect = element.getBoundingClientRect();
const box = [rect.left, rect.top, rect.width, rect.height];
if (ctx.quantize) {
return box.map((value) => Math.round(value / LIVENESS_POSITION_BUCKET_PX)).join(",");
}
return box.map(round).join(",");
}
function opacityChannel(element, ctx) {
return String(
ctx.quantize ? Math.round(ctx.opacity / LIVENESS_OPACITY_BUCKET) : round(ctx.opacity),
);
}
// Variable-font axis animation moves no geometry and no opacity; in a
// DUPLEXED face (Recursive holds one advance width at every weight) not even
// the line width shifts, so without this channel the whole run reads frozen.
function fontAxesChannel(element, ctx) {
const axes = cssValue(ctx.style.fontVariationSettings);
return axes ? hashFields([axes]) : "";
}
// A clip-path wipe (inset(0 100% 0 0) → inset(0)) reveals a box that never
// moves; the computed clip-path string is the only thing that changes.
function clipPathChannel(element, ctx) {
const clip = cssValue(ctx.style.clipPath);
return clip ? hashFields([clip]) : "";
}
// Direct text nodes only: descendants are signed separately, and a hidden
// descendant's text mutation must not masquerade as visible motion.
function textChannel(element) {
const text = Array.from(element.childNodes)
.filter((node) => node.nodeType === 3)
.map((node) => node.textContent)
.join("");
return text && hashFields([text]);
}
function flag(value) {
return value ? "1" : "0";
}
function inputState(element) {
return [
element.type || "",
element.value || "",
flag(element.checked),
flag(element.indeterminate),
];
}
function selectState(element) {
const fields = [String(element.selectedIndex), element.value || ""];
for (const option of element.options) fields.push(flag(option.selected));
return fields;
}
const CONTROL_STATE = {
INPUT: inputState,
TEXTAREA: (element) => [element.value || ""],
SELECT: selectState,
};
// Form controls paint their value/checked state without changing the box.
function controlChannel(element) {
const read = CONTROL_STATE[element.tagName];
return read ? hashFields(read(element)) : "";
}
// Chromium substitutes attr() in computed pseudo content, so this is the
// platform-owned rendered string rather than a CSS expression to reparse.
// counter() is NOT substituted — that is what the counter channel is for.
function generatedContentChannel(element, ctx) {
const before = cssValue(ctx.pseudo.before.content);
const after = cssValue(ctx.pseudo.after.content);
return before || after ? hashFields([before, after]) : "";
}
// Pixel-only media motion (a 2D/WebGL canvas repainting, a playing video, or
// an equal-size opaque <img> src swap) moves no geometry and no opacity, so
// it is invisible to every DOM-state channel. Downsample each visible media
// element to 8x8 and fold its pixels in. Tainted, zero-sized, or unreadable
// media hashes to a constant — no worse than DOM-state-only detection and
// never a new false negative for DOM-motion compositions. Media inside
// iframes is intentionally outside this signature: it lives in a separate
// document, and cross-origin frames are inaccessible under SOP.
// fallow-ignore-next-line complexity
function mediaPixelChannel(element) {
if (!MEDIA_TAGS.has(element.tagName)) return "";
try {
const rect = element.getBoundingClientRect();
const sourceWidth = element.videoWidth || element.width || rect.width;
const sourceHeight = element.videoHeight || element.height || rect.height;
if (!sourceWidth || !sourceHeight) return "x";
const off = document.createElement("canvas");
off.width = 8;
off.height = 8;
const ctx2d = off.getContext("2d");
if (!ctx2d) return "x";
ctx2d.drawImage(element, 0, 0, 8, 8);
const data = ctx2d.getImageData(0, 0, 8, 8).data;
let hash = 0;
for (let i = 0; i < data.length; i++) hash = (hash * 31 + data[i]) >>> 0;
return String(hash);
} catch {
return "x";
}
}
const ELEMENT_CHANNELS = [
boxChannel,
opacityChannel,
fontAxesChannel,
clipPathChannel,
textChannel,
controlChannel,
generatedContentChannel,
mediaPixelChannel,
];
// --- Composition-level counter channel ------------------------------------
//
// Counter declarations often live on zero-box owners (or on ancestors of the
// composition root) while some pseudo-element paints the value, so counter
// state is a composition-level channel over every element that generates a
// box — not just the visible ones. Two guards keep a decoy counter from
// making a frozen composition read as live: a display:none subtree generates
// no boxes and therefore cannot feed any painted counter(), and only
// declarations that NAME a counter some generated content actually paints
// are folded in — a varying counter nobody renders is not motion. The gate
// is name-level, not scope-level: a same-named owner that cannot reach the
// consumer in the box tree still counts, which is accepted for a guard whose
// job is catching frozen timelines, not defeating deliberate authors.
// visibility:hidden and zero-box owners stay in as owners: they generate
// boxes, their counters propagate to visible descendants/siblings, and their
// own absolutely-positioned pseudo-elements can paint. <ol start> / <li
// value> are not surfaced in computed counter-* and stay invisible here.
// Generated content of one box owner that reaches the screen: the host is
// not under an author opt-out, has a paintable inherited opacity, and the
// pseudo box itself is not hidden. A list-item box also paints its ::marker
// (counter(list-item) when the marker content is `normal`).
function markerContent(element, style) {
if (isHiddenStyle(style) || !LIST_ITEM_DISPLAY.test(style.display)) return "";
return cssValue(getComputedStyle(element, "::marker").content) || IMPLICIT_MARKER_CONTENT;
}
function paintedContent(element, style, pseudo, opacity) {
if (opacity < 0.2 || element.closest(IGNORE_SELECTOR)) return [];
const boxes = [pseudo.before, pseudo.after].filter((box) => !isHiddenStyle(box));
return [...boxes.map((box) => cssValue(box.content)), markerContent(element, style)];
}
function consumedCounterNames(owners) {
const names = new Set();
for (const owner of owners) {
for (const content of owner.painted) {
for (const match of content.matchAll(COUNTER_FUNCTION)) names.add(match[1]);
}
}
return names;
}
// `counter-reset: a 10 b 3` → does any named counter get painted?
function namesConsumedCounter(declaration, consumed) {
return declaration.split(/\s+/).some((token) => consumed.has(token));
}
function counterState(style, consumed) {
const fields = [style.counterReset, style.counterIncrement, style.counterSet]
.map(cssValue)
.filter((declaration) => declaration && namesConsumedCounter(declaration, consumed));
return fields.length > 0 ? "c:" + hashFields(fields) : "";
}
function counterParts(root, owners) {
const consumed = consumedCounterNames(owners);
if (consumed.size === 0) return [];
const parts = [];
function push(style) {
const state = counterState(style, consumed);
if (state) parts.push(state);
}
for (let ancestor = root.parentElement; ancestor; ancestor = ancestor.parentElement) {
push(getComputedStyle(ancestor));
}
for (const owner of owners) {
push(owner.style);
push(owner.pseudo.before);
push(owner.pseudo.after);
}
return parts;
}
// One signature of everything under `root` (root included — a composition
// whose only textual motion is a direct text node of the root still moves)
// that a viewer could see change between two seeks. `options.quantize`
// selects liveness bucketing (see header). Elements under an author opt-out
// (data-layout-ignore / data-layout-check=ignore) — typically a decorative
// layer that may animate off the seeked timeline — are neither signed nor
// allowed to consume counters: they must not prove that the timeline
// advanced. They remain counter owners, since their boxes still propagate.
// fallow-ignore-next-line complexity
function compositionSignature(root, options) {
if (!root) return "";
const quantize = !!(options && options.quantize);
const parts = [];
const boxOwners = [];
const hiddenSubtree = new Set();
for (const element of [root, ...root.querySelectorAll("*")]) {
if (IGNORE_TAGS.has(element.tagName)) continue;
const style = getComputedStyle(element);
if (style.display === "none" || hiddenSubtree.has(element.parentElement)) {
hiddenSubtree.add(element);
continue;
}
const pseudo = {
before: getComputedStyle(element, "::before"),
after: getComputedStyle(element, "::after"),
};
const opacity = opacityChain(element);
boxOwners.push({ style, pseudo, painted: paintedContent(element, style, pseudo, opacity) });
if (element.closest(IGNORE_SELECTOR)) continue;
if (!isVisibleElement(element, style, opacity)) continue;
const ctx = { style, pseudo, opacity, quantize };
parts.push(ELEMENT_CHANNELS.map((channel) => channel(element, ctx)).join(","));
}
parts.push(...counterParts(root, boxOwners));
return parts.join("|");
}
window.__hyperframesMotionSignature = {
compositionRoot,
isVisibleElement,
opacityChain,
compositionSignature,
};
// Frozen-sweep guard entry point (checkBrowser.ts collectLayoutGeometry).
// The name predates the textual/media channels and is kept for driver
// compatibility.
window.__hyperframesLayoutGeometry = function collectLayoutGeometry() {
return compositionSignature(compositionRoot(), { quantize: false });
};
})();
@@ -0,0 +1,808 @@
// @vitest-environment happy-dom
// fallow-ignore-file code-duplication
import { afterEach, describe, expect, it, vi } from "vitest";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const script = readFileSync(join(__dirname, "motion-signature.browser.js"), "utf-8");
interface RectInput {
left: number;
top: number;
width: number;
height: number;
}
type StyleOverride = Partial<CSSStyleDeclaration>;
interface Fixture {
/** Bounding rects keyed by element id (or lower-case tag name for id-less elements). */
rects: Record<string, RectInput>;
/** Computed-style overrides keyed like `rects`; getters are re-read on every call. */
styles?: Record<string, StyleOverride>;
/** `::before` / `::after` computed-style overrides keyed like `rects`. */
pseudo?: Record<string, { before?: StyleOverride; after?: StyleOverride }>;
}
const BASE_STYLE: StyleOverride = {
display: "block",
visibility: "visible",
opacity: "1",
fontVariationSettings: "normal",
clipPath: "none",
counterReset: "none",
counterIncrement: "none",
counterSet: "none",
};
const BASE_PSEUDO_STYLE: StyleOverride = {
content: "none",
counterReset: "none",
counterIncrement: "none",
counterSet: "none",
};
function keyFor(element: Element): string {
return element.id || element.tagName.toLowerCase();
}
// A per-element fake `getComputedStyle`: each element reports ONLY its own
// declared style, exactly like the real platform (a child of a display:none
// parent still computes display:block). Any ancestor awareness — hidden
// subtrees, counter owners above the root — must therefore come from the
// classifier under test, which is what pins those branches.
function installFixture({ rects, styles = {}, pseudo = {} }: Fixture): void {
vi.spyOn(window, "getComputedStyle").mockImplementation((element, pseudoElement) => {
const key = keyFor(element as Element);
if (pseudoElement === "::before" || pseudoElement === "::after") {
const override = pseudoElement === "::before" ? pseudo[key]?.before : pseudo[key]?.after;
return { ...BASE_PSEUDO_STYLE, ...override } as CSSStyleDeclaration;
}
return { ...BASE_STYLE, ...styles[key] } as CSSStyleDeclaration;
});
for (const element of Array.from(document.querySelectorAll("*"))) {
const input = rects[keyFor(element)] ?? { left: 0, top: 0, width: 0, height: 0 };
vi.spyOn(element, "getBoundingClientRect").mockReturnValue(rect(input));
}
}
function rect({ left, top, width, height }: RectInput): DOMRect {
return {
left,
top,
right: left + width,
bottom: top + height,
width,
height,
x: left,
y: top,
toJSON() {
return this;
},
} as DOMRect;
}
interface SignatureWindow {
__hyperframesLayoutGeometry: () => string;
__hyperframesMotionSignature: {
compositionRoot(): Element;
compositionSignature(root: Element | null, options?: { quantize?: boolean }): string;
};
}
function signatureWindow(): SignatureWindow {
return window as unknown as SignatureWindow;
}
function installScript(): () => string {
window.eval(script);
return signatureWindow().__hyperframesLayoutGeometry;
}
function mockMediaPixels(read: () => number): void {
const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as {
mockReturnValue(value: CanvasRenderingContext2D): void;
};
getContextSpy.mockReturnValue({
drawImage() {},
getImageData() {
return { data: new Uint8ClampedArray(8 * 8 * 4).fill(read()) };
},
} as unknown as CanvasRenderingContext2D);
}
const ROOT = { left: 0, top: 0, width: 640, height: 360 };
const COUNTDOWN = { left: 280, top: 140, width: 80, height: 48 };
const ZERO_BOX = { left: 0, top: 0, width: 0, height: 0 };
const COUNTER_CONSUMER = { after: { content: "counter(countdown)" } };
afterEach(() => {
vi.restoreAllMocks();
document.body.innerHTML = "";
Reflect.deleteProperty(window, "__hyperframesLayoutGeometry");
Reflect.deleteProperty(window, "__hyperframesMotionSignature");
});
describe("motion-signature.browser media and geometry channels", () => {
it("changes the sweep fingerprint when visible video pixels advance", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<video id="footage"></video>
</div>
`;
installFixture({ rects: { root: ROOT, footage: ROOT } });
let pixelValue = 20;
mockMediaPixels(() => pixelValue);
const collect = installScript();
const before = collect();
pixelValue = 220;
expect(collect()).not.toBe(before);
});
// PRINFRA-666: an equal-size, equal-position opaque <img> src/visibility
// swap (the authoring pattern for a paused-GSAP-cursor-driven "reveal
// frame N of a still sequence" composition) moves no geometry and no
// opacity, so it was invisible to the fingerprint and false-positived
// sweep_static — mediaPixelHash already existed for exactly this pixel-only
// motion class, it just wasn't applied to img.
it("changes the sweep fingerprint when a same-size opaque img is swapped", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<img id="frame" />
</div>
`;
installFixture({ rects: { root: ROOT, frame: ROOT } });
let pixelValue = 20;
mockMediaPixels(() => pixelValue);
const collect = installScript();
const before = collect();
pixelValue = 220;
expect(collect()).not.toBe(before);
});
// Opacity-reveal fixture (CLI feedback digest 2026-07-14): code-typing style
// scenes reveal pre-laid-out characters via opacity only — no geometry ever
// moves. The sweep fingerprint must treat that as motion, both while a glyph
// fades (opacity value changes) and when it crosses the 0.2 visibility floor
// (element enters the signature); otherwise `check` misfires `sweep_static`
// and authors reach for geometry hacks (a slow host y-drift) to pass.
it("changes the sweep fingerprint when text reveals via opacity alone", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="code"><span id="char">c</span></div>
</div>
`;
let charOpacity = "0";
installFixture({
rects: {
root: ROOT,
code: { left: 40, top: 40, width: 560, height: 48 },
char: { left: 40, top: 40, width: 18, height: 48 },
},
styles: {
char: {
get opacity() {
return charOpacity;
},
} as StyleOverride,
},
});
const collect = installScript();
const hidden = collect(); // below the 0.2 visibility floor — not in the signature
charOpacity = "0.5";
const fading = collect(); // mid-fade — present, opacity part of the signature
charOpacity = "1";
const revealed = collect(); // settled
expect(fading).not.toBe(hidden);
expect(revealed).not.toBe(fading);
});
// Variable-font axis animation (registry block `weight-wave`): a crest of
// weight travels across a line of text. In a duplexed face nothing moves
// but the axis string — the fingerprint must still see it.
it("changes the sweep fingerprint when only font-variation-settings moves", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="line"><span id="char">P</span></div>
</div>
`;
let axes = '"wght" 400, "slnt" 0';
installFixture({
rects: {
root: ROOT,
line: { left: 40, top: 40, width: 560, height: 48 },
char: { left: 40, top: 40, width: 18, height: 48 },
},
styles: {
char: {
get fontVariationSettings() {
return axes;
},
} as StyleOverride,
},
});
const collect = installScript();
const rest = collect();
axes = '"wght" 1000, "slnt" -12'; // the crest arrives over this character
expect(collect()).not.toBe(rest);
});
// The other direction, and it guards the more dangerous failure: a
// fingerprint that varies on its own would make sweep_static unfireable and
// every green layout verdict meaningless. Identical scene, axes included,
// must hash identically.
it("keeps the sweep fingerprint identical when nothing moves, font axes included", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="line"><span id="char">P</span></div>
</div>
`;
installFixture({
rects: {
root: ROOT,
line: { left: 40, top: 40, width: 560, height: 48 },
char: { left: 40, top: 40, width: 18, height: 48 },
},
styles: { char: { fontVariationSettings: '"wght" 400, "slnt" 0' } },
});
const collect = installScript();
expect(collect()).toBe(collect());
});
it("changes the sweep fingerprint when only clip-path moves", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="panel"></div>
</div>
`;
let clipPath = "inset(0px 100% 0px 0px)";
installFixture({
rects: { root: ROOT, panel: { left: 40, top: 40, width: 200, height: 100 } },
styles: {
panel: {
get clipPath() {
return clipPath;
},
} as StyleOverride,
},
});
const collect = installScript();
const before = collect();
clipPath = "inset(0px 50% 0px 0px)";
expect(collect()).not.toBe(before);
});
it("ignores motion on a data-layout-ignore layer", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="glow" data-layout-ignore></div>
<span id="countdown">10</span>
</div>
`;
let left = 40;
installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } });
vi.spyOn(document.getElementById("glow")!, "getBoundingClientRect").mockImplementation(() =>
rect({ left, top: 40, width: 100, height: 100 }),
);
const collect = installScript();
const before = collect();
left = 200;
expect(collect()).toBe(before);
});
it("buckets sub-threshold moves out of the quantized liveness signature only", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="box"></div>
</div>
`;
let left = 100;
installFixture({ rects: { root: ROOT } });
vi.spyOn(document.getElementById("box")!, "getBoundingClientRect").mockImplementation(() =>
rect({ left, top: 100, width: 50, height: 50 }),
);
installScript();
const { compositionSignature, compositionRoot } =
signatureWindow().__hyperframesMotionSignature;
const root = compositionRoot();
const exactBefore = compositionSignature(root);
const bucketedBefore = compositionSignature(root, { quantize: true });
left = 100.6; // moves, but stays inside the 2px liveness bucket
expect(compositionSignature(root)).not.toBe(exactBefore);
expect(compositionSignature(root, { quantize: true })).toBe(bucketedBefore);
});
});
describe("motion-signature.browser textual channels", () => {
it("changes the sweep fingerprint when fixed-width text content changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown">10</span>
</div>
`;
installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } });
const collect = installScript();
const before = collect();
document.getElementById("countdown")!.textContent = "09";
expect(collect()).not.toBe(before);
});
it("ignores text mutations inside a display:none descendant", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown">10<span id="hidden">10</span></span>
</div>
`;
installFixture({
rects: { root: ROOT, countdown: COUNTDOWN, hidden: COUNTDOWN },
styles: { hidden: { display: "none" } },
});
const collect = installScript();
const before = collect();
document.getElementById("hidden")!.textContent = "09";
expect(collect()).toBe(before);
});
it("changes the sweep fingerprint when the composition root's own text changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">10</div>
`;
installFixture({ rects: { root: ROOT } });
const collect = installScript();
const before = collect();
document.getElementById("root")!.textContent = "09";
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when an attr-backed data value changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown" data-txt="10"></span>
</div>
`;
installFixture({
rects: { root: ROOT, countdown: COUNTDOWN },
pseudo: {
countdown: {
after: {
// Chromium substitutes attr() in computed pseudo content.
get content() {
return JSON.stringify(document.getElementById("countdown")!.getAttribute("data-txt"));
},
} as StyleOverride,
},
},
});
const collect = installScript();
const before = collect();
document.getElementById("countdown")!.setAttribute("data-txt", "09");
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when pseudo-element content changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown"></span>
</div>
`;
let generatedContent = '"10"';
installFixture({
rects: { root: ROOT, countdown: COUNTDOWN },
pseudo: {
countdown: {
after: {
get content() {
return generatedContent;
},
} as StyleOverride,
},
},
});
const collect = installScript();
const before = collect();
generatedContent = '"09"';
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when checkbox state changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<input id="toggle" type="checkbox" />
</div>
`;
installFixture({
rects: { root: ROOT, toggle: { left: 280, top: 140, width: 24, height: 24 } },
});
const collect = installScript();
const before = collect();
(document.getElementById("toggle") as HTMLInputElement).checked = true;
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a checkbox becomes indeterminate", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<input id="toggle" type="checkbox" />
</div>
`;
installFixture({
rects: { root: ROOT, toggle: { left: 280, top: 140, width: 24, height: 24 } },
});
const collect = installScript();
const before = collect();
(document.getElementById("toggle") as HTMLInputElement).indeterminate = true;
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a secondary select option changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<select id="choices" multiple><option selected>A</option><option>B</option></select>
</div>
`;
installFixture({
rects: { root: ROOT, choices: { left: 280, top: 140, width: 120, height: 48 } },
});
const collect = installScript();
const before = collect();
(document.getElementById("choices") as HTMLSelectElement).options[1]!.selected = true;
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a fixed-width form value changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<input id="countdown" value="10" />
</div>
`;
installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } });
const collect = installScript();
const before = collect();
(document.getElementById("countdown") as HTMLInputElement).value = "09";
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a textarea value changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<textarea id="countdown">10</textarea>
</div>
`;
installFixture({ rects: { root: ROOT, countdown: COUNTDOWN } });
const collect = installScript();
const before = collect();
(document.getElementById("countdown") as HTMLTextAreaElement).value = "09";
expect(collect()).not.toBe(before);
});
it("keeps textual sweep channels identical when the countdown is truly frozen", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown" data-txt="10">10</span>
</div>
`;
installFixture({
rects: { root: ROOT, countdown: COUNTDOWN },
styles: { countdown: { counterReset: "countdown 10" } },
pseudo: { countdown: { after: { content: '"10"' } } },
});
const collect = installScript();
expect(collect()).toBe(collect());
});
});
describe("motion-signature.browser counter channel", () => {
it("changes the sweep fingerprint when a zero-box owner's counter state changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="counter-owner"><span id="countdown"></span></div>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, "counter-owner": ZERO_BOX, countdown: COUNTDOWN },
styles: {
"counter-owner": {
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
pseudo: { countdown: COUNTER_CONSUMER },
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a counter owned above the composition root changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown"></span>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, countdown: COUNTDOWN },
styles: {
body: {
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
pseudo: { countdown: COUNTER_CONSUMER },
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a pseudo-element's own counter-increment changes", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<span id="countdown"></span>
</div>
`;
let counterIncrement = "countdown 10";
installFixture({
rects: { root: ROOT, countdown: COUNTDOWN },
pseudo: {
countdown: {
after: {
content: "counter(countdown)",
get counterIncrement() {
return counterIncrement;
},
} as StyleOverride,
},
},
});
const collect = installScript();
const before = collect();
counterIncrement = "countdown 9";
expect(collect()).not.toBe(before);
});
it("changes the sweep fingerprint when a zero-box host's own pseudo-element paints the counter", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="host"></div>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, host: ZERO_BOX },
styles: {
body: {
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
pseudo: { host: COUNTER_CONSUMER },
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).not.toBe(before);
});
it("ignores a zero-box decoy whose counter name nothing paints even when a list marker exists", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<ul><li id="item">item</li></ul>
<div id="decoy"></div>
</div>
`;
let counterReset = "decoy 10";
installFixture({
rects: { root: ROOT, item: COUNTDOWN, decoy: ZERO_BOX },
styles: {
item: { display: "list-item" },
decoy: {
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
});
const collect = installScript();
const before = collect();
counterReset = "decoy 9";
expect(collect()).toBe(before);
});
it("ignores a counter consumed only under a data-layout-ignore layer", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="counter-owner"></div>
<div data-layout-ignore><span id="countdown"></span></div>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, "counter-owner": ZERO_BOX, countdown: COUNTDOWN },
styles: {
"counter-owner": {
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
pseudo: { countdown: COUNTER_CONSUMER },
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).toBe(before);
});
it("keeps a visibility:hidden owner whose counter feeds a visible consumer", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="counter-owner"><span id="countdown"></span></div>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, "counter-owner": COUNTDOWN, countdown: COUNTDOWN },
styles: {
"counter-owner": {
visibility: "hidden",
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
pseudo: { countdown: COUNTER_CONSUMER },
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).not.toBe(before);
});
// A display:none element generates no box, so its counters cannot reach any
// painted counter() — a varying counter-reset there must not make a frozen
// composition read as live.
it("ignores a display:none decoy counter owner in a frozen composition", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="decoy"></div>
<span id="countdown"></span>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, decoy: ZERO_BOX, countdown: COUNTDOWN },
styles: {
decoy: {
display: "none",
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
pseudo: { countdown: COUNTER_CONSUMER },
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).toBe(before);
});
it("ignores a decoy counter owner nested inside a display:none subtree", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="hidden-parent"><div id="decoy"></div></div>
<span id="countdown"></span>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, "hidden-parent": ZERO_BOX, decoy: ZERO_BOX, countdown: COUNTDOWN },
styles: {
"hidden-parent": { display: "none" },
// The decoy itself computes display:block — only its ancestry hides it.
decoy: {
display: "block",
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
pseudo: { countdown: COUNTER_CONSUMER },
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).toBe(before);
});
it("ignores counter declarations when no visible generated content consumes a counter", () => {
document.body.innerHTML = `
<div id="root" data-composition-id="main" data-width="640" data-height="360">
<div id="counter-owner"></div>
<span id="countdown">10</span>
</div>
`;
let counterReset = "countdown 10";
installFixture({
rects: { root: ROOT, "counter-owner": ZERO_BOX, countdown: COUNTDOWN },
styles: {
"counter-owner": {
get counterReset() {
return counterReset;
},
} as StyleOverride,
},
});
const collect = installScript();
const before = collect();
counterReset = "countdown 9";
expect(collect()).toBe(before);
});
});
+2
View File
@@ -434,6 +434,8 @@ async function hasNoTimelineDeclaration(page: Page): Promise<boolean> {
}
async function injectAuditScripts(page: Page, contrast: boolean): Promise<void> {
// The shared motion classifier must land before both samplers that consume it.
await page.addScriptTag({ content: loadBrowserScript("motion-signature.browser.js") });
await page.addScriptTag({ content: loadBrowserScript("layout-audit.browser.js") });
await page.addScriptTag({ content: loadBrowserScript("motion-sample.browser.js") });
if (contrast) {
+1 -1
View File
@@ -500,7 +500,7 @@ const ZERO_LAYOUT_RECT: LayoutRect = {
/**
* Frozen-sweep guard (#U10): if every layout-grid sample produced the exact
* same visible-state fingerprint (see layout-audit.browser.js), the seek
* same visible-state fingerprint (see motion-signature.browser.js), the seek
* never actually advanced the composition's timeline — every other green
* verdict from this run is meaningless, not just a missed defect. Skips
* short (<3s) compositions, single-sample runs (nothing to compare), and
+3 -1
View File
@@ -196,7 +196,9 @@ export interface CheckAuditDriver {
collectOverlap(time: number): Promise<AnchoredLayoutIssue[]>;
/** Frozen-sweep guard (#U10): an opaque fingerprint of the current seeked
* visual state, for detecting a timeline that never advances under seek.
* The method keeps its legacy name for driver compatibility. */
* Produced by motion-signature.browser.js — the same classifier that feeds
* motion-sample's liveness signature. The method keeps its legacy name for
* driver compatibility. */
collectLayoutGeometry(): Promise<string>;
/** rotation_pivot_drift: every rotatable element's bbox center/size/angle at
* the current seeked state. Accumulated across the grid — see checkPipeline. */