Skip to content

Write HTML. Render video. Built for agents.

feat(cli): keyframes command (surface GSAP/CSS/Anime keyframes + 3D onion-skin --shot) (#1603)

Miguel Ángela908af11a814
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index 014e90809b..f384a14b44 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -331,6 +331,11 @@
// pre-existing per-rule scaffold; adding a clip-path case shifts lines and
// re-flags it. Collapsing the per-rule installers would obscure each case.
"packages/cli/src/commands/layout-audit.browser.test.ts",
+ // gsapParserAcorn.motionEval.test.ts: parallel arrange/act/assert cases for
+ // the staggered-collection honesty pass (.from reveal vs .to landing on the
+ // rest pose). Each asserts a distinct keyframe shape; collapsing the shared
+ // parse/keyframes-extraction scaffold would obscure what each case verifies.
+ "packages/core/src/parsers/gsapParserAcorn.motionEval.test.ts",
],
},
"health": {
@@ -430,6 +435,18 @@
// breaking fallow's inherited-detection fingerprint. File-level
// exemption avoids the line-shift problem for this inherited finding.
"packages/core/src/runtime/adapters/lottie.ts",
+ // info.ts: the flagged `run` command handler pre-dates the keyframes-cli
+ // PR; that PR only added the orientation()/durationFromHtml() helpers and
+ // swapped a few `maxEnd` reads for the new `duration` variable, without
+ // adding branches. The line-shift fingerprint re-flags the inherited
+ // complexity even though the logic is unchanged.
+ "packages/cli/src/commands/info.ts",
+ // gsapParserAcorn.ts: the flagged `sameMemberAccess` (structural equality
+ // of two member-access nodes) pre-dates this PR's motion-eval work
+ // (added in #1760, unchanged since). The new const-folding / set-seeding /
+ // label-position code added earlier in the file shifted its line number,
+ // so the line-shift fingerprint re-flags this inherited finding.
+ "packages/parsers/src/gsapParserAcorn.ts",
],
},
}
diff --git a/CLAUDE.md b/CLAUDE.md
index d7a318de8a..948707a14f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,11 +4,11 @@ Open-source video rendering framework: write HTML, render video.
## Skills
-This repo ships 19 AI agent skills via [vercel-labs/skills](https://github.com/vercel-labs/skills). Install them before writing compositions — they encode framework-specific patterns that generic docs don't cover.
+This repo ships 20 AI agent skills via [vercel-labs/skills](https://github.com/vercel-labs/skills). Install them before writing compositions — they encode framework-specific patterns that generic docs don't cover.
```bash
npx skills add heygen-com/hyperframes # interactive picker
-npx skills add heygen-com/hyperframes --all # install all 19 (skips picker)
+npx skills add heygen-com/hyperframes --all # install all 20 (skips picker)
npx skills add heygen-com/hyperframes --skill <name> # just one (bare name, no leading slash)
```
@@ -34,6 +34,7 @@ Atomic capabilities the creation workflows compose against — pull one when you
- `/hyperframes-core` — the composition contract: `data-*` timing attributes, `class="clip"`, tracks, sub-compositions, variables, framework-owned media playback, determinism rules. Read before writing composition HTML.
- `/hyperframes-animation` — all animation knowledge: atomic motion rules, scene blueprints, transitions, runtime adapters (GSAP default, plus Lottie / Three.js / Anime.js / CSS / WAAPI / TypeGPU).
+- `/hyperframes-keyframes` — seek-safe keyframe authoring across runtimes: GSAP timelines, CSS keyframes, Anime.js, WAAPI, FLIP, paths, masks, SVG morph/draw, text trails, cursor demos, 3D depth; plus `hyperframes keyframes` diagnostics for surfacing and verifying rendered motion.
- `/hyperframes-creative` — non-animation creative direction: `frame.md` / `design.md` handling, palettes, typography, narration, beat planning, audio-reactive visuals, composition patterns.
- `/hyperframes-media` — audio + media: TTS voiceover, background music, sound effects, Whisper transcription, background removal, caption authoring (one shared `scripts/audio.mjs` engine, multi-provider).
- `/media-use` — resolve any media need (BGM, SFX, image, icon) into a frozen local file + ledger record. One verb (`resolve`) over the HeyGen catalog with manifest tracking; keeps search noise on disk.
@@ -47,7 +48,7 @@ When adding a new skill, or substantially renaming / repurposing an existing one
1. The skill list above (CLAUDE.md) AND the `## Skills` section in `README.md` AND `docs/guides/skills.mdx` (rendered at [hyperframes.heygen.com/guides/skills](https://hyperframes.heygen.com/guides/skills)). Out-of-date entries silently kill discovery.
2. If the skill changes the routing surface for "make a video" requests, also update the capability map and intent router in `skills/hyperframes/SKILL.md` — that's the canonical router agents read first.
3. Mirror the Router / Creation workflows / Domain skills grouping across all three surfaces so a skill always lives in the same column.
-4. Skill count appears in the README and CLAUDE.md intro lines ("19 AI agent skills…") — update on add/remove. The `docs/guides/skills.mdx` page deliberately omits a count to avoid drift; keep it count-free.
+4. Skill count appears in the README and CLAUDE.md intro lines ("20 AI agent skills…") — update on add/remove. The `docs/guides/skills.mdx` page deliberately omits a count to avoid drift; keep it count-free.
The skill's own `SKILL.md` frontmatter `description:` is the source of truth for the one-line "use when" blurb; copy from there into the catalog rather than paraphrasing.
diff --git a/README.md b/README.md
index 6d48f020d1..321d06f404 100644
--- a/README.md
+++ b/README.md
@@ -49,9 +49,9 @@ The skills teach agents the HyperFrames production loop: plan the video, write v
## Skills
-HyperFrames ships 19 skills agents load on demand. Read `/hyperframes` first — it's the router and capability map; it picks a workflow for any "make me a video" request and points to the domain skills below.
+HyperFrames ships 20 skills agents load on demand. Read `/hyperframes` first — it's the router and capability map; it picks a workflow for any "make me a video" request and points to the domain skills below.
-Run `npx skills add heygen-com/hyperframes` for the interactive picker, `npx skills add heygen-com/hyperframes --all` to install all 19 at once (skips the picker), or `npx skills add heygen-com/hyperframes --skill <name>` for just one (bare name, no leading `/`).
+Run `npx skills add heygen-com/hyperframes` for the interactive picker, `npx skills add heygen-com/hyperframes --all` to install all 20 at once (skips the picker), or `npx skills add heygen-com/hyperframes --skill <name>` for just one (bare name, no leading `/`).
### Router
@@ -79,15 +79,16 @@ Run `npx skills add heygen-com/hyperframes` for the interactive picker, `npx ski
Atomic capabilities the creation workflows compose against — pull one when you need that specific layer.
-| Skill | Covers |
-| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `/hyperframes-core` | The composition contract — `data-*` timing attributes, `class="clip"`, tracks, sub-compositions, variables, framework-owned media playback, determinism rules. |
-| `/hyperframes-animation` | All animation knowledge — atomic motion rules, scene blueprints, transitions, runtime adapters (GSAP / Lottie / Three.js / Anime.js / CSS / WAAPI / TypeGPU). |
-| `/hyperframes-creative` | Non-animation creative direction — `frame.md` / `design.md`, palettes, typography, narration, beat planning, audio-reactive visuals, composition patterns. |
-| `/hyperframes-media` | Audio + media — TTS voiceover, background music, sound effects, Whisper transcription, background removal, caption authoring (one shared audio engine). |
-| `/media-use` | Resolve any media need (BGM, SFX, image, icon) into a frozen local file + ledger record. One verb (`resolve`) over the HeyGen catalog with manifest tracking. |
-| `/hyperframes-cli` | CLI dev loop — `init`, `lint`, `validate`, `inspect`, `preview`, `render`, `publish`, `doctor`, plus AWS Lambda cloud rendering (`lambda deploy / render / progress`). |
-| `/hyperframes-registry` | Install and wire registry blocks and components into compositions via `hyperframes add`. Authoring a new block or component to contribute upstream. |
+| Skill | Covers |
+| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `/hyperframes-core` | The composition contract — `data-*` timing attributes, `class="clip"`, tracks, sub-compositions, variables, framework-owned media playback, determinism rules. |
+| `/hyperframes-animation` | All animation knowledge — atomic motion rules, scene blueprints, transitions, runtime adapters (GSAP / Lottie / Three.js / Anime.js / CSS / WAAPI / TypeGPU). |
+| `/hyperframes-keyframes` | Seek-safe keyframe authoring across runtimes — GSAP timelines, CSS keyframes, Anime.js, WAAPI, FLIP, paths, masks, SVG morph/draw, 3D depth — plus `hyperframes keyframes` diagnostics for rendered motion. |
+| `/hyperframes-creative` | Non-animation creative direction — `frame.md` / `design.md`, palettes, typography, narration, beat planning, audio-reactive visuals, composition patterns. |
+| `/hyperframes-media` | Audio + media — TTS voiceover, background music, sound effects, Whisper transcription, background removal, caption authoring (one shared audio engine). |
+| `/media-use` | Resolve any media need (BGM, SFX, image, icon) into a frozen local file + ledger record. One verb (`resolve`) over the HeyGen catalog with manifest tracking. |
+| `/hyperframes-cli` | CLI dev loop — `init`, `lint`, `validate`, `inspect`, `preview`, `render`, `publish`, `doctor`, plus AWS Lambda cloud rendering (`lambda deploy / render / progress`). |
+| `/hyperframes-registry` | Install and wire registry blocks and components into compositions via `hyperframes add`. Authoring a new block or component to contribute upstream. |
For visual design handoff workflows, see the [Claude Design guide](https://hyperframes.heygen.com/guides/claude-design) and [Open Design guide](https://hyperframes.heygen.com/guides/open-design).
diff --git a/docs/guides/skills.mdx b/docs/guides/skills.mdx
index 5ac8423573..4d592463b4 100644
--- a/docs/guides/skills.mdx
+++ b/docs/guides/skills.mdx
@@ -21,7 +21,7 @@ The skills split into three groups:
Opens a picker so you can choose which skills to add. Works with [Claude Code](https://claude.ai/claude-code), [Cursor](https://cursor.sh), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [Codex CLI](https://github.com/openai/codex), [GitHub Copilot CLI](/guides/copilot-cli), and [Google Antigravity](/guides/antigravity).
</Step>
- <Step title="Or install all 19 at once (skip the picker)">
+ <Step title="Or install all 20 at once (skip the picker)">
```bash
npx skills add heygen-com/hyperframes --all
```
@@ -78,6 +78,7 @@ Atomic capabilities the creation workflows compose against — pull one when you
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/hyperframes-core` | The composition contract — `data-*` timing attributes, `class="clip"`, tracks, sub-compositions, variables, framework-owned media playback, determinism rules. |
| `/hyperframes-animation` | All animation knowledge — atomic motion rules, scene blueprints, transitions, runtime adapters (GSAP / Lottie / Three.js / Anime.js / CSS / WAAPI / TypeGPU). |
+| `/hyperframes-keyframes` | Seek-safe keyframe authoring across runtimes — GSAP timelines, CSS keyframes, Anime.js, WAAPI, FLIP, paths, masks, SVG morph/draw, 3D depth — plus `hyperframes keyframes` diagnostics for rendered motion. |
| `/hyperframes-creative` | Non-animation creative direction — `frame.md` / `design.md`, palettes, typography, narration, beat planning, audio-reactive visuals, composition patterns. |
| `/hyperframes-media` | Audio + media — TTS voiceover, background music, sound effects, Whisper transcription, background removal, caption authoring (one shared audio engine). |
| `/media-use` | Resolve any media need (BGM, SFX, image, icon) into a frozen local file + ledger record. One verb (`resolve`) over the HeyGen catalog with manifest tracking. |
diff --git a/packages/cli/src/cli.commands.test.ts b/packages/cli/src/cli.commands.test.ts
new file mode 100644
index 0000000000..4a533eeb5b
--- /dev/null
+++ b/packages/cli/src/cli.commands.test.ts
@@ -0,0 +1,29 @@
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const cliSource = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "cli.ts"), "utf8");
+const helpSource = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "help.ts"), "utf8");
+
+function commandLoaderBlock(): string {
+ const match = cliSource.match(/const commandLoaders = \{([\s\S]*?)\n\};/);
+ expect(match).toBeTruthy();
+ return match![1]!;
+}
+
+describe("CLI command registration", () => {
+ it("registers keyframes as the only keyframe inspection command", () => {
+ const loaders = commandLoaderBlock();
+
+ expect(loaders).toMatch(/\bkeyframes:\s*\(\)\s*=>\s*import\("\.\/commands\/keyframes\.js"\)/);
+ expect(loaders).not.toMatch(/\bmotion:\s*\(\)\s*=>/);
+ expect(loaders).not.toContain("./commands/motion.js");
+ });
+
+ it("shows keyframes in root help", () => {
+ expect(helpSource).toContain(
+ '["keyframes", "Inspect keyframes and render onion-shot diagnostics"]',
+ );
+ });
+});
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 2316977ec4..20ec2a427d 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -121,6 +121,7 @@ const commandLoaders = {
lint: () => import("./commands/lint.js").then((m) => m.default),
beats: () => import("./commands/beats.js").then((m) => m.default),
inspect: () => import("./commands/inspect.js").then((m) => m.default),
+ keyframes: () => import("./commands/keyframes.js").then((m) => m.default),
layout: () => import("./commands/layout.js").then((m) => m.default),
info: () => import("./commands/info.js").then((m) => m.default),
compositions: () => import("./commands/compositions.js").then((m) => m.default),
diff --git a/packages/cli/src/commands/info.test.ts b/packages/cli/src/commands/info.test.ts
new file mode 100644
index 0000000000..1386216100
--- /dev/null
+++ b/packages/cli/src/commands/info.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import { orientation, durationFromHtml } from "./info.js";
+
+describe("orientation", () => {
+ it("is landscape when width > height", () => {
+ expect(orientation(1920, 1080)).toBe("landscape");
+ });
+
+ it("is portrait when height > width", () => {
+ expect(orientation(1080, 1920)).toBe("portrait");
+ });
+
+ it("is square when width === height", () => {
+ expect(orientation(1080, 1080)).toBe("square");
+ });
+});
+
+describe("durationFromHtml", () => {
+ it("reads data-duration from the root composition element", () => {
+ const html = `<div data-composition-id="comp" data-width="1920" data-height="1080" data-start="0" data-duration="6"></div>`;
+ expect(durationFromHtml(html, 5)).toBe(6);
+ });
+
+ it("reads data-duration regardless of attribute order", () => {
+ const html = `<div data-duration="8" data-composition-id="comp"></div>`;
+ expect(durationFromHtml(html, 5)).toBe(8);
+ });
+
+ it("falls back to the computed timeline duration when no data-duration", () => {
+ const html = `<div data-composition-id="comp"></div>`;
+ expect(durationFromHtml(html, 5)).toBe(5);
+ });
+});
diff --git a/packages/cli/src/commands/info.ts b/packages/cli/src/commands/info.ts
index f5074d3757..f57d40f2a1 100644
--- a/packages/cli/src/commands/info.ts
+++ b/packages/cli/src/commands/info.ts
@@ -14,6 +14,25 @@ import { ensureDOMParser } from "../utils/dom.js";
import { resolveProject } from "../utils/project.js";
import { withMeta } from "../utils/updateCheck.js";
+/** Derive orientation label from actual pixel dimensions. */
+export function orientation(width: number, height: number): "landscape" | "portrait" | "square" {
+ if (width > height) return "landscape";
+ if (height > width) return "portrait";
+ return "square";
+}
+
+/**
+ * Duration of the composition: prefer the root element's data-duration,
+ * fall back to the computed timeline end.
+ */
+export function durationFromHtml(html: string, fallback: number): number {
+ const match =
+ html.match(/data-composition-id[^>]*data-duration=["']([\d.]+)["']/) ||
+ html.match(/data-duration=["']([\d.]+)["'][^>]*data-composition-id/);
+ const value = match?.[1] ? parseFloat(match[1]) : NaN;
+ return Number.isFinite(value) ? value : fallback;
+}
+
function totalSize(dir: string): number {
let total = 0;
for (const entry of readdirSync(dir, { withFileTypes: true })) {
@@ -56,6 +75,7 @@ export default defineCommand({
const width = widthMatch?.[1] ? parseInt(widthMatch[1], 10) : fallback.width;
const height = heightMatch?.[1] ? parseInt(heightMatch[1], 10) : fallback.height;
const resolution = `${width}x${height}`;
+ const duration = durationFromHtml(html, maxEnd);
const size = totalSize(project.dir);
const typeCounts: Record<string, number> = {};
@@ -71,10 +91,10 @@ export default defineCommand({
JSON.stringify(
withMeta({
name: project.name,
- resolution: parsed.resolution,
+ resolution: orientation(width, height),
width,
height,
- duration: maxEnd,
+ duration,
elements: parsed.elements.length,
tracks: tracks.size,
types: typeCounts,
@@ -89,7 +109,7 @@ export default defineCommand({
console.log(`${c.success("◇")} ${c.accent(project.name)}`);
console.log(label("Resolution", resolution));
- console.log(label("Duration", `${maxEnd.toFixed(1)}s`));
+ console.log(label("Duration", `${duration.toFixed(1)}s`));
console.log(label("Elements", `${parsed.elements.length}${typeStr ? ` (${typeStr})` : ""}`));
console.log(label("Tracks", `${tracks.size}`));
console.log(label("Size", formatBytes(size)));
diff --git a/packages/cli/src/commands/keyframes.test.ts b/packages/cli/src/commands/keyframes.test.ts
new file mode 100644
index 0000000000..39e5c3281f
--- /dev/null
+++ b/packages/cli/src/commands/keyframes.test.ts
@@ -0,0 +1,143 @@
+import { beforeAll, describe, expect, it } from "vitest";
+import { ensureDOMParser } from "../utils/dom.js";
+import { collectShotSelectors, surfaceComposition } from "./keyframes.js";
+
+beforeAll(() => ensureDOMParser());
+
+const wrap = (script: string) =>
+ `<!doctype html><html><body><div id="root" data-composition-id="main" data-duration="4"><div id="dot" class="clip"></div></div><script>${script}</script></body></html>`;
+
+describe("keyframes multi-stroke traces", () => {
+ it("composites ≥2 position strokes on one element into a single trace", () => {
+ const html = wrap(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#dot", { keyframes: { "0%": { x: -100, y: -150 }, "100%": { x: 80, y: -120 } }, duration: 1 });
+ tl.to("#dot", { keyframes: { "0%": { x: 80, y: 120 }, "100%": { x: 85, y: 140 } }, duration: 1 });
+ window.__timelines = [tl];
+ `);
+ const { traces } = surfaceComposition(html, "index.html", "index.html");
+ expect(traces).toHaveLength(1);
+ expect(traces[0]!.target).toBe("#dot");
+ expect(traces[0]!.strokes).toHaveLength(2);
+ });
+
+ it("treats a 0-duration set() between strokes as a pen-up jump, not a drawn stroke", () => {
+ const html = wrap(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#dot", { keyframes: { "0%": { x: 0, y: 0 }, "100%": { x: 100, y: 0 } }, duration: 1 });
+ tl.set("#dot", { x: 200, y: 200 });
+ tl.to("#dot", { keyframes: { "0%": { x: 200, y: 200 }, "100%": { x: 250, y: 250 } }, duration: 1 });
+ window.__timelines = [tl];
+ `);
+ const { traces } = surfaceComposition(html, "index.html", "index.html");
+ expect(traces).toHaveLength(1);
+ // two DRAWN strokes; the set() is the pen-up gap and is excluded
+ expect(traces[0]!.strokes).toHaveLength(2);
+ });
+
+ it("leaves a single-stroke element untraced (normal per-tween output)", () => {
+ const html = wrap(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#dot", { keyframes: { "0%": { x: 0, y: 0 }, "50%": { x: 200, y: -100 }, "100%": { x: 0, y: 0 } }, duration: 3 });
+ window.__timelines = [tl];
+ `);
+ const { traces, tweens } = surfaceComposition(html, "index.html", "index.html");
+ expect(traces).toHaveLength(0);
+ expect(tweens.length).toBeGreaterThan(0);
+ });
+});
+
+describe("keyframes composed-ancestor surfacing (nested elements)", () => {
+ const nested = (script: string) =>
+ `<!doctype html><html><body><div id="root" data-composition-id="main" data-duration="4"><div id="stage"><div id="hero"><div id="core" class="clip"></div></div></div></div><script>${script}</script></body></html>`;
+
+ it("annotates a child tween with its animated ANCESTOR's motion", () => {
+ const html = nested(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#hero", { keyframes: { "0%": { x: -300, y: 0 }, "100%": { x: 300, y: 0 } }, duration: 4 }, 0);
+ tl.to("#core", { keyframes: { "0%": { scale: 1 }, "100%": { scale: 1.5 } }, duration: 4 }, 0);
+ window.__timelines = [tl];
+ `);
+ const { tweens } = surfaceComposition(html, "index.html", "index.html");
+ const core = tweens.find((t) => t.target === "#core");
+ expect(core?.composedWith?.map((a) => a.selector)).toContain("#hero");
+ // and the ancestor's path EXTENT is summarised (range, not endpoints — so a
+ // closed loop still reveals its travel)
+ expect(core?.composedWith?.[0]!.summary).toMatch(/x -300\.\.300/);
+ });
+
+ it("does not annotate when the parent isn't animated", () => {
+ const html = nested(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#core", { keyframes: { "0%": { scale: 1 }, "100%": { scale: 1.5 } }, duration: 4 }, 0);
+ window.__timelines = [tl];
+ `);
+ const { tweens } = surfaceComposition(html, "index.html", "index.html");
+ expect(tweens.find((t) => t.target === "#core")?.composedWith).toBeUndefined();
+ });
+});
+
+describe("keyframes runtime surfacing", () => {
+ it("surfaces CSS @keyframes and their animated selectors", () => {
+ const html = `<!doctype html><html><head><style>
+ .dot { animation: rise 1200ms ease-out both; }
+ @keyframes rise {
+ 0% { opacity: 0; transform: translateY(40px); }
+ 100% { opacity: 1; transform: translateY(0); }
+ }
+ </style></head><body><div class="dot"></div></body></html>`;
+ const { cssKeyframes } = surfaceComposition(html, "index.html", "index.html");
+ expect(cssKeyframes).toHaveLength(1);
+ expect(cssKeyframes[0]!.name).toBe("rise");
+ expect(cssKeyframes[0]!.selectors).toContain(".dot");
+ expect(cssKeyframes[0]!.keyframes.map((kf) => kf.selector)).toEqual(["0%", "100%"]);
+ });
+
+ it("does not let a CSS comment before @keyframes leak into the next rule's selector", () => {
+ const html = `<!doctype html><html><head><style>
+ /* Grain animation */
+ @keyframes rise { 0% { opacity: 0; } 100% { opacity: 1; } }
+ .dot { animation: rise 1s both; }
+ </style></head><body><div class="dot"></div></body></html>`;
+ const { cssKeyframes } = surfaceComposition(html, "index.html", "index.html");
+ expect(cssKeyframes[0]!.selectors).toEqual([".dot"]);
+ });
+
+ it("surfaces Anime.js calls and explicit HyperFrames registration", () => {
+ const html = wrap(`
+ const tl = anime.createTimeline({ autoplay: false });
+ tl.add(".chip", { translateX: [0, 240], duration: 900 });
+ window.__hfAnime = window.__hfAnime || [];
+ window.__hfAnime.push(tl);
+ `);
+ const { anime } = surfaceComposition(html, "index.html", "index.html");
+ expect(anime).toHaveLength(1);
+ expect(anime[0]!.kind).toBe("timeline");
+ expect(anime[0]!.registered).toBe(true);
+ expect(anime[0]!.targets).toContain(".chip");
+ expect(anime[0]!.durations).toContain(900);
+ });
+
+ it("uses CSS and Anime targets as onion-shot candidates", () => {
+ const cssHtml = `<!doctype html><html><head><style>
+ .dot { animation: rise 1200ms ease-out both; }
+ @keyframes rise {
+ 0% { transform: translateY(40px); }
+ 100% { transform: translateY(0); }
+ }
+ </style></head><body><div class="dot"></div></body></html>`;
+ const animeHtml = wrap(`
+ const tl = anime.createTimeline({ autoplay: false });
+ tl.add(".chip", { translateX: [0, 240], duration: 900 });
+ window.__hfAnime = window.__hfAnime || [];
+ window.__hfAnime.push(tl);
+ `);
+
+ const selectors = collectShotSelectors([
+ surfaceComposition(cssHtml, "css.html", "css.html"),
+ surfaceComposition(animeHtml, "anime.html", "anime.html"),
+ ]).map((item) => item.selector);
+
+ expect(selectors).toEqual(expect.arrayContaining([".dot", ".chip"]));
+ });
+});
diff --git a/packages/cli/src/commands/keyframes.ts b/packages/cli/src/commands/keyframes.ts
new file mode 100644
index 0000000000..48fc4971e8
--- /dev/null
+++ b/packages/cli/src/commands/keyframes.ts
@@ -0,0 +1,983 @@
+import { defineCommand } from "citty";
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { resolve, dirname, basename } from "node:path";
+import { parseGsapScript, type GsapAnimation } from "@hyperframes/core/gsap-parser";
+import type { Example } from "./_examples.js";
+import { c } from "../ui/colors.js";
+import { ensureDOMParser } from "../utils/dom.js";
+import { resolveProject } from "../utils/project.js";
+import { withMeta } from "../utils/updateCheck.js";
+
+export const examples: Example[] = [
+ ["Surface every keyframe + motion path in the project", "hyperframes keyframes"],
+ ["Inspect one composition file", "hyperframes keyframes compositions/scene.html"],
+ ["Machine-readable output for an agent", "hyperframes keyframes --json"],
+ ["Only one element's keyframes", "hyperframes keyframes --selector '#puck-a'"],
+ ["Runtime-aware hint for CSS/Anime compositions", "hyperframes keyframes --runtime all"],
+];
+
+// ── Surfaced shapes ──────────────────────────────────────────────────────────
+
+interface KeyframePoint {
+ /** Tween-relative percentage (0–100). */
+ pct: number;
+ /** Absolute timeline time (seconds) = tweenStart + pct/100 * duration. */
+ time: number;
+ properties: Record<string, number | string>;
+}
+
+interface SurfacedTween {
+ id: string;
+ target: string;
+ method: string;
+ group?: string;
+ start: number;
+ duration: number;
+ end: number;
+ /** "keyframes" (array/object form), "flat" (to/from), or "motionPath". */
+ shape: "keyframes" | "flat" | "motionPath";
+ keyframes: KeyframePoint[];
+ /** x/y position points (gsap offsets) when this tween animates position. */
+ path: Array<{ x: number; y: number }> | null;
+ /** Animated ANCESTOR elements (nested composition): this element's rendered
+ * motion is composed with theirs. Surfaced so a reader of the text/JSON
+ * doesn't miss a parent's path/trajectory that lives on another element. */
+ composedWith?: Array<{ selector: string; summary: string }>;
+}
+
+/** One drawn stroke of a multi-stroke trace — a single position tween. */
+interface TraceStroke {
+ id: string;
+ start: number;
+ end: number;
+ keyframes: KeyframePoint[];
+ points: Array<{ x: number; y: number }>;
+}
+
+/** An element's position motion composited into ordered strokes. The gaps
+ * between strokes are pen-up jumps (a 0-duration `set`, or a discontinuity)
+ * and are NOT drawn — this is how one element traces shapes with holes or
+ * detached parts (a `?` dot, an icon counter, multi-letter words). */
+interface SurfacedTrace {
+ target: string;
+ strokes: TraceStroke[];
+}
+
+interface CssKeyframeStop {
+ selector: string;
+ declarations: string[];
+}
+
+interface SurfacedCssKeyframes {
+ name: string;
+ selectors: string[];
+ keyframes: CssKeyframeStop[];
+}
+
+interface SurfacedAnimeAnimation {
+ kind: "animation" | "timeline";
+ targets: string[];
+ durations: Array<number | string>;
+ registered: boolean;
+}
+
+interface SurfacedComposition {
+ composition: string;
+ source: string;
+ tweens: SurfacedTween[];
+ /** Multi-stroke traces: targets with ≥2 drawn position strokes, composited. */
+ traces: SurfacedTrace[];
+ cssKeyframes: SurfacedCssKeyframes[];
+ anime: SurfacedAnimeAnimation[];
+}
+
+// ── GSAP extraction ──────────────────────────────────────────────────────────
+
+function inlineScriptText(html: string): string {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ return Array.from(doc.querySelectorAll("script"))
+ .filter((s) => !s.getAttribute("src"))
+ .map((s) => s.textContent ?? "")
+ .join("\n");
+}
+
+function inlineStyleText(html: string): string {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ return Array.from(doc.querySelectorAll("style"))
+ .map((s) => s.textContent ?? "")
+ .join("\n");
+}
+
+function num(v: number | string | undefined): number | null {
+ if (typeof v === "number") return v;
+ if (typeof v === "string") {
+ const n = Number.parseFloat(v);
+ return Number.isFinite(n) ? n : null;
+ }
+ return null;
+}
+
+function isPositionTween(anim: GsapAnimation): boolean {
+ if (anim.propertyGroup === "position") return true;
+ const has = (p: Record<string, number | string> | undefined) => !!p && ("x" in p || "y" in p);
+ if (has(anim.properties) || has(anim.fromProperties)) return true;
+ return (anim.keyframes?.keyframes ?? []).some(
+ (kf) => "x" in kf.properties || "y" in kf.properties,
+ );
+}
+
+// The rest-state value for an animated property (what GSAP animates to/from when
+// the other endpoint is the element's natural pose): 1 for scale/opacity, 0 for
+// translate/rotation.
+function baseProps(props: Record<string, number | string>): Record<string, number | string> {
+ const base: Record<string, number | string> = {};
+ for (const k of Object.keys(props)) {
+ if (k === "ease") continue;
+ base[k] = k === "opacity" || k.startsWith("scale") ? 1 : 0;
+ }
+ return base;
+}
+
+// Flat tweens carry no explicit keyframes — synthesize a 0%/100% pair against the
+// element's rest pose so the surfaced keyframes are uniform. `from()` goes
+// fromProperties → base; `to()` goes base → properties.
+function flatKeyframes(anim: GsapAnimation): KeyframePoint[] {
+ if (anim.method === "fromTo") {
+ return [
+ { pct: 0, time: 0, properties: anim.fromProperties ?? {} },
+ { pct: 100, time: 0, properties: anim.properties ?? {} },
+ ];
+ }
+ // to()/from() vars both live in anim.properties; from() plays them in reverse
+ // against the element's rest pose.
+ const vars = anim.properties ?? {};
+ const base = baseProps(vars);
+ return anim.method === "from"
+ ? [
+ { pct: 0, time: 0, properties: vars },
+ { pct: 100, time: 0, properties: base },
+ ]
+ : [
+ { pct: 0, time: 0, properties: base },
+ { pct: 100, time: 0, properties: vars },
+ ];
+}
+
+// Studio-internal markers that aren't user motion: the position-hold `set` GSAP
+// runs before a keyframed position tween (`data: "hf-hold"`).
+function isHoldMarker(anim: GsapAnimation): boolean {
+ return anim.properties?.data === "hf-hold" || anim.fromProperties?.data === "hf-hold";
+}
+
+// Drop internal / non-visual keys so they don't pollute the surfaced keyframes.
+function cleanProps(props: Record<string, number | string>): Record<string, number | string> {
+ const out: Record<string, number | string> = {};
+ for (const [k, v] of Object.entries(props)) {
+ if (k === "data" || k === "ease") continue;
+ out[k] = v;
+ }
+ return out;
+}
+
+function surfaceTween(anim: GsapAnimation): SurfacedTween {
+ const start =
+ typeof anim.resolvedStart === "number" ? anim.resolvedStart : (num(anim.position) ?? 0);
+ const duration = anim.duration ?? 0;
+
+ let shape: SurfacedTween["shape"];
+ let rawKfs: Array<{ percentage: number; properties: Record<string, number | string> }>;
+ if (anim.keyframes?.keyframes?.length) {
+ shape = "keyframes";
+ rawKfs = anim.keyframes.keyframes;
+ } else if (anim.arcPath?.enabled) {
+ shape = "motionPath";
+ rawKfs = [];
+ } else {
+ shape = "flat";
+ rawKfs = flatKeyframes(anim).map((k) => ({ percentage: k.pct, properties: k.properties }));
+ }
+
+ const keyframes: KeyframePoint[] = rawKfs.map((kf) => ({
+ pct: kf.percentage,
+ time: Math.round((start + (kf.percentage / 100) * duration) * 1000) / 1000,
+ properties: cleanProps(kf.properties),
+ }));
+
+ return {
+ id: anim.id,
+ target: anim.targetSelector,
+ method: anim.method,
+ group: anim.propertyGroup,
+ start: Math.round(start * 1000) / 1000,
+ duration,
+ end: Math.round((start + duration) * 1000) / 1000,
+ shape,
+ keyframes,
+ path: isPositionTween(anim) ? positionPath(keyframes) : null,
+ };
+}
+
+// Carry x/y forward across keyframes that only set one axis, so the path is
+// continuous (GSAP holds the last value for an unspecified property).
+function positionPath(keyframes: KeyframePoint[]): Array<{ x: number; y: number }> | null {
+ if (keyframes.length === 0) return null;
+ let lastX = 0;
+ let lastY = 0;
+ return keyframes.map((kf) => {
+ const x = num(kf.properties.x);
+ const y = num(kf.properties.y);
+ if (x !== null) lastX = x;
+ if (y !== null) lastY = y;
+ return { x: lastX, y: lastY };
+ });
+}
+
+// ── Composition surfacing ────────────────────────────────────────────────────
+
+export function surfaceComposition(
+ html: string,
+ label: string,
+ source: string,
+): SurfacedComposition {
+ const script = inlineScriptText(html);
+ let animations: GsapAnimation[] = [];
+ try {
+ animations = parseGsapScript(script).animations;
+ } catch {
+ animations = [];
+ }
+ const tweens = animations.filter((a) => !isHoldMarker(a)).map(surfaceTween);
+ attachComposedAncestors(tweens, html);
+ return {
+ composition: label,
+ source,
+ tweens,
+ traces: groupTraces(tweens),
+ cssKeyframes: surfaceCssKeyframes(inlineStyleText(html)),
+ anime: surfaceAnime(inlineScriptText(html)),
+ };
+}
+
+// ── CSS / Anime extraction ───────────────────────────────────────────────────
+
+function readBalancedBlock(text: string, openBrace: number): { body: string; end: number } | null {
+ if (text[openBrace] !== "{") return null;
+ let depth = 0;
+ for (let i = openBrace; i < text.length; i++) {
+ const ch = text[i];
+ if (ch === "{") depth++;
+ else if (ch === "}") {
+ depth--;
+ if (depth === 0) {
+ return { body: text.slice(openBrace + 1, i), end: i + 1 };
+ }
+ }
+ }
+ return null;
+}
+
+function parseDeclarations(body: string): string[] {
+ return body
+ .split(";")
+ .map((part) => part.trim())
+ .filter(Boolean);
+}
+
+function stripRanges(text: string, ranges: Array<{ start: number; end: number }>): string {
+ let out = "";
+ let cursor = 0;
+ for (const range of [...ranges].sort((a, b) => a.start - b.start)) {
+ out += text.slice(cursor, range.start);
+ cursor = range.end;
+ }
+ return out + text.slice(cursor);
+}
+
+function collectKeyframeBlocks(css: string): {
+ keyframes: Array<{ name: string; stops: CssKeyframeStop[] }>;
+ ranges: Array<{ start: number; end: number }>;
+} {
+ const keyframes: Array<{ name: string; stops: CssKeyframeStop[] }> = [];
+ const ranges: Array<{ start: number; end: number }> = [];
+ const re = /@keyframes\s+([a-zA-Z0-9_-]+)/g;
+ let match: RegExpExecArray | null;
+ while ((match = re.exec(css))) {
+ const open = css.indexOf("{", re.lastIndex);
+ const block = open >= 0 ? readBalancedBlock(css, open) : null;
+ if (!block) continue;
+ ranges.push({ start: match.index, end: block.end });
+ const stops: CssKeyframeStop[] = [];
+ const stopRe = /([^{}]+)\{([^{}]*)\}/g;
+ let stop: RegExpExecArray | null;
+ while ((stop = stopRe.exec(block.body))) {
+ stops.push({
+ selector: stop[1]!.trim().replace(/\s+/g, " "),
+ declarations: parseDeclarations(stop[2]!),
+ });
+ }
+ keyframes.push({ name: match[1]!, stops });
+ }
+ return { keyframes, ranges };
+}
+
+function stripQuotes(raw: string): string {
+ return raw.trim().replace(/^["']|["']$/g, "");
+}
+
+// `animation-name: foo, bar;` — each comma-separated part is a full keyframes name.
+function addAnimationNameDeclNames(body: string, knownNames: Set<string>, out: Set<string>): void {
+ const nameRe = /animation-name\s*:\s*([^;]+)/g;
+ let nameMatch: RegExpExecArray | null;
+ while ((nameMatch = nameRe.exec(body))) {
+ for (const raw of nameMatch[1]!.split(",")) {
+ const name = stripQuotes(raw);
+ if (knownNames.has(name)) out.add(name);
+ }
+ }
+}
+
+// `animation: foo 2s ease, bar 1s;` shorthand — the name is one whitespace-separated
+// token among duration/timing-function/etc, so every token has to be checked.
+function addAnimationShorthandNames(body: string, knownNames: Set<string>, out: Set<string>): void {
+ const animationRe = /animation\s*:\s*([^;]+)/g;
+ let animationMatch: RegExpExecArray | null;
+ while ((animationMatch = animationRe.exec(body))) {
+ for (const raw of animationMatch[1]!.split(",")) {
+ for (const token of raw.trim().split(/\s+/)) {
+ const normalized = stripQuotes(token);
+ if (knownNames.has(normalized)) out.add(normalized);
+ }
+ }
+ }
+}
+
+function animationNamesFromDeclarations(body: string, knownNames: Set<string>): string[] {
+ const out = new Set<string>();
+ addAnimationNameDeclNames(body, knownNames, out);
+ addAnimationShorthandNames(body, knownNames, out);
+ return [...out];
+}
+
+// CSS comments would otherwise glue onto the next rule's selector: once the
+// @keyframes blocks between them are stripped, a `/* note */` sitting above an
+// @keyframes reattaches to the following rule (and corrupts both the printed
+// selector and the --shot querySelector). Drop comments up front.
+function stripCssComments(css: string): string {
+ return css.replace(/\/\*[\s\S]*?\*\//g, " ");
+}
+
+function surfaceCssKeyframes(rawCss: string): SurfacedCssKeyframes[] {
+ const css = stripCssComments(rawCss);
+ if (!css.trim()) return [];
+ const { keyframes, ranges } = collectKeyframeBlocks(css);
+ if (keyframes.length === 0) return [];
+
+ const selectorsByName = new Map<string, Set<string>>();
+ for (const kf of keyframes) selectorsByName.set(kf.name, new Set());
+ const knownNames = new Set(keyframes.map((kf) => kf.name));
+ const cssWithoutKeyframes = stripRanges(css, ranges);
+ const ruleRe = /([^{}@]+)\{([^{}]*animation[^{}]*)\}/g;
+ let rule: RegExpExecArray | null;
+ while ((rule = ruleRe.exec(cssWithoutKeyframes))) {
+ const selector = rule[1]!.trim().replace(/\s+/g, " ");
+ if (!selector) continue;
+ for (const name of animationNamesFromDeclarations(rule[2]!, knownNames)) {
+ selectorsByName.get(name)?.add(selector);
+ }
+ }
+
+ return keyframes.map((kf) => ({
+ name: kf.name,
+ selectors: [...(selectorsByName.get(kf.name) ?? new Set<string>())],
+ keyframes: kf.stops,
+ }));
+}
+
+function valuesFromProperty(
+ script: string,
+ property: "targets" | "duration",
+): Array<string | number> {
+ const values: Array<string | number> = [];
+ const quoted = property + "\\s*:\\s*([\"'`])([^\"'`]+)\\1";
+ const numeric = property + "\\s*:\\s*([0-9]+(?:\\.[0-9]+)?)";
+ const re = new RegExp(`${quoted}|${numeric}`, "g");
+ let match: RegExpExecArray | null;
+ while ((match = re.exec(script))) {
+ if (match[2] !== undefined) values.push(match[2]);
+ else if (match[3] !== undefined) values.push(Number(match[3]));
+ }
+ return values;
+}
+
+function animeAddTargets(script: string): string[] {
+ const values: string[] = [];
+ const re = /\.add\s*\(\s*(["'`])([^"'`]+)\1/g;
+ let match: RegExpExecArray | null;
+ while ((match = re.exec(script))) values.push(match[2]!);
+ return values;
+}
+
+function surfaceAnime(script: string): SurfacedAnimeAnimation[] {
+ if (!/\banime\s*(?:\.(?:timeline|createTimeline))?\s*\(/.test(script)) return [];
+ const registered = /__hfAnime[\s\S]*?\.push\s*\(/.test(script) || /__hfAnime\s*=/.test(script);
+ const timelineCount = (script.match(/\banime\.(?:timeline|createTimeline)\s*\(/g) ?? []).length;
+ const animationCount = (script.match(/\banime\s*\(/g) ?? []).length;
+ const targets = [
+ ...valuesFromProperty(script, "targets").filter(
+ (value): value is string => typeof value === "string",
+ ),
+ ...animeAddTargets(script),
+ ];
+ const durations = valuesFromProperty(script, "duration");
+ const out: SurfacedAnimeAnimation[] = [];
+ for (let i = 0; i < timelineCount; i++) {
+ out.push({ kind: "timeline", targets, durations, registered });
+ }
+ for (let i = 0; i < animationCount; i++) {
+ out.push({ kind: "animation", targets, durations, registered });
+ }
+ return out;
+}
+
+// A nested element's rendered motion is the COMPOSITION of its own tween and any
+// animated ancestor's. The per-element surface would otherwise hide the parent's
+// trajectory (e.g. a child carries a flap while the parent carries the path), so
+// annotate each tween with the animated ancestor elements above it in the DOM.
+function attachComposedAncestors(tweens: SurfacedTween[], html: string): void {
+ const animated = [...new Set(tweens.filter((t) => t.method !== "set").map((t) => t.target))];
+ if (animated.length < 2) return; // need ≥2 distinct animated elements to compose
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ for (const t of tweens) {
+ const ancestors = animatedAncestors(doc, t.target, animated);
+ if (ancestors.length) {
+ t.composedWith = ancestors.map((sel) => ({
+ selector: sel,
+ summary: summarizeMotion(tweens, sel),
+ }));
+ }
+ }
+}
+
+const safeMatches = (el: Element, sel: string): boolean => {
+ try {
+ return el.matches(sel);
+ } catch {
+ return false;
+ }
+};
+
+// Animated-target selectors of `target`'s DOM ancestors (in order, parent-first).
+function animatedAncestors(doc: Document, target: string, animated: string[]): string[] {
+ let el: Element | null = null;
+ try {
+ el = doc.querySelector(target);
+ } catch {
+ return [];
+ }
+ const out: string[] = [];
+ for (let n = el?.parentElement ?? null; n; n = n.parentElement) {
+ for (const sel of animated) {
+ if (sel !== target && !out.includes(sel) && safeMatches(n, sel)) out.push(sel);
+ }
+ }
+ return out;
+}
+
+// Compact extent summary of an element's motion: each animated property's min..max
+// across all its keyframes. Ranges (not endpoints) so a CLOSED loop — a figure-8
+// or orbit returning to its start — still reveals its travel instead of reading
+// static (0→0).
+function summarizeMotion(tweens: SurfacedTween[], sel: string): string {
+ const ranges = new Map<string, { min: number; max: number }>();
+ const kfs = tweens
+ .filter((t) => t.target === sel && t.method !== "set")
+ .flatMap((t) => t.keyframes);
+ for (const kf of kfs) {
+ for (const [k, v] of Object.entries(kf.properties)) {
+ const n = num(v);
+ if (n !== null) bumpRange(ranges, k, n);
+ }
+ }
+ const varying = [...ranges.entries()]
+ .filter(([, r]) => r.max - r.min > 0.5)
+ .map(([k, r]) => `${k} ${Math.round(r.min)}..${Math.round(r.max)}`);
+ return varying.length ? varying.join(", ") : "(static)";
+}
+
+function bumpRange(ranges: Map<string, { min: number; max: number }>, k: string, n: number): void {
+ const r = ranges.get(k);
+ if (r) {
+ r.min = Math.min(r.min, n);
+ r.max = Math.max(r.max, n);
+ } else ranges.set(k, { min: n, max: n });
+}
+
+// A drawn stroke must actually move across the canvas. A position tween whose
+// points never leave the start (an opacity/scale tween merely carrying a static
+// y) is not a pen stroke — exclude it so repeated in-place tweens don't
+// masquerade as a multi-stroke trace.
+function pathTravels(points: Array<{ x: number; y: number }>): boolean {
+ const first = points[0];
+ if (!first) return false;
+ return points.some((p) => Math.abs(p.x - first.x) > 0.5 || Math.abs(p.y - first.y) > 0.5);
+}
+
+// Group an element's DRAWN position strokes (to/from/fromTo/keyframes that carry
+// a path) into one ordered trace. A `set` with x/y is a pen-up jump — excluded
+// (not drawn). Only targets with ≥2 strokes become a composited trace; a single
+// stroke stays on the normal per-tween path so existing output is unchanged.
+function groupTraces(tweens: SurfacedTween[]): SurfacedTrace[] {
+ const byTarget = new Map<string, SurfacedTween[]>();
+ for (const t of tweens) {
+ if (t.method === "set") continue;
+ if (!t.path || t.path.length < 2) continue;
+ if (!pathTravels(t.path)) continue; // in-place tween (e.g. opacity carrying a static y) is not a drawn stroke
+ const list = byTarget.get(t.target);
+ if (list) list.push(t);
+ else byTarget.set(t.target, [t]);
+ }
+ const traces: SurfacedTrace[] = [];
+ for (const [target, list] of byTarget) {
+ if (list.length < 2) continue;
+ const strokes = [...list]
+ .sort((a, b) => a.start - b.start)
+ .map((t) => ({
+ id: t.id,
+ start: t.start,
+ end: t.end,
+ keyframes: t.keyframes,
+ points: t.path!,
+ }));
+ traces.push({ target, strokes });
+ }
+ return traces;
+}
+
+function collectCompositions(indexPath: string): SurfacedComposition[] {
+ const html = readFileSync(indexPath, "utf-8");
+ const baseDir = dirname(indexPath);
+ const out: SurfacedComposition[] = [
+ surfaceComposition(html, basename(indexPath), basename(indexPath)),
+ ];
+
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ for (const div of Array.from(doc.querySelectorAll("[data-composition-src]"))) {
+ const src = div.getAttribute("data-composition-src");
+ if (!src) continue;
+ const subPath = resolve(baseDir, src);
+ if (!existsSync(subPath)) continue;
+ const id = div.getAttribute("data-composition-id") ?? src;
+ out.push(surfaceComposition(readFileSync(subPath, "utf-8"), id, src));
+ }
+ return out;
+}
+
+// ── Render (human) ───────────────────────────────────────────────────────────
+
+function fmtProps(props: Record<string, number | string>): string {
+ return Object.entries(props)
+ .filter(([k]) => k !== "ease")
+ .map(([k, v]) => `${k}:${v}`)
+ .join(" ");
+}
+
+function printTween(t: SurfacedTween): void {
+ const timing = c.dim(`@${t.start}s→${t.end}s (${t.duration}s)`);
+ const group = t.group ? c.dim(` ${t.group}`) : "";
+ console.log(` ${c.accent(t.target)}${group} ${c.dim(t.method)}/${t.shape} ${timing}`);
+ if (t.shape === "motionPath") {
+ console.log(c.dim(` motionPath arc (${t.keyframes.length} stops)`));
+ } else {
+ const kfLine = t.keyframes.map((k) => `${k.pct}% {${fmtProps(k.properties)}}`).join(" ");
+ console.log(` ${c.dim(kfLine)}`);
+ }
+ if (t.composedWith?.length) {
+ for (const a of t.composedWith) {
+ console.log(c.dim(` ↑ composed with ${c.accent(a.selector)}${c.dim(": " + a.summary)}`));
+ }
+ }
+ console.log();
+}
+
+function printTrace(tr: SurfacedTrace): void {
+ const start = Math.min(...tr.strokes.map((s) => s.start));
+ const end = Math.max(...tr.strokes.map((s) => s.end));
+ const n = tr.strokes.length;
+ console.log(
+ ` ${c.accent(tr.target)}${c.dim(" position")} ${c.dim("trace")} ${c.dim(`${n} strokes`)} ${c.dim(`@${start}s→${end}s`)}`,
+ );
+ tr.strokes.forEach((s, i) => {
+ const kfLine = s.keyframes.map((k) => `${k.pct}% {${fmtProps(k.properties)}}`).join(" ");
+ console.log(` ${c.dim(`stroke ${i + 1}:`)} ${c.dim(kfLine)}`);
+ });
+ console.log();
+}
+
+// ── Onion-skin self-verify shot ──────────────────────────────────────────────
+
+interface ShotArgs {
+ shot?: string;
+ samples?: string;
+ layout?: string;
+ from?: string;
+ to?: string;
+ fit?: boolean;
+ angle?: string;
+ ghost?: boolean;
+}
+
+// Every animated element qualifies — the onion samples the live element and shows
+// every channel (rotation / scale / opacity / colour / 3D), not just x/y. A
+// 0-duration `set` is a pen-up marker, not motion.
+function addTraceSelectors(selectors: Set<string>, cmp: SurfacedComposition): void {
+ for (const tr of cmp.traces) selectors.add(tr.target);
+}
+
+function addTweenSelectors(selectors: Set<string>, cmp: SurfacedComposition): void {
+ for (const t of cmp.tweens) {
+ if (t.method !== "set") selectors.add(t.target);
+ }
+}
+
+function addCssKeyframeSelectors(selectors: Set<string>, cmp: SurfacedComposition): void {
+ for (const css of cmp.cssKeyframes) {
+ for (const selector of css.selectors) {
+ if (selector) selectors.add(selector);
+ }
+ }
+}
+
+function addAnimeSelectors(selectors: Set<string>, cmp: SurfacedComposition): void {
+ for (const anime of cmp.anime) {
+ for (const selector of anime.targets) {
+ if (selector) selectors.add(selector);
+ }
+ }
+}
+
+export function collectShotSelectors(comps: SurfacedComposition[]): Array<{ selector: string }> {
+ const selectors = new Set<string>();
+ for (const cmp of comps) {
+ addTraceSelectors(selectors, cmp);
+ addTweenSelectors(selectors, cmp);
+ addCssKeyframeSelectors(selectors, cmp);
+ addAnimeSelectors(selectors, cmp);
+ }
+ return [...selectors].map((selector) => ({ selector }));
+}
+
+// Guard checks that must pass before capturing the onion-skin shot. Returns the
+// message to print when a guard fails, or null when clear to proceed.
+function onionShotGuardError(
+ projectDir: string | undefined,
+ requests: Array<{ selector: string }>,
+ ghost: boolean,
+): string | null {
+ if (!projectDir) return "--shot needs a project directory (not a single .html file).";
+ // The rendered onion (--ghost) screenshots the whole painted stage, so it does
+ // not need an animated DOM element to sample — only the marker onion does.
+ if (requests.length === 0 && !ghost)
+ return "--shot: no animated element to sample for the selection.";
+ return null;
+}
+
+function onionShotOptions(args: ShotArgs & { selector?: string }) {
+ return {
+ samples: num(args.samples) ?? 9,
+ layout: (args.layout === "strip" ? "strip" : "path") as "strip" | "path",
+ fit: args.fit ?? true,
+ from: num(args.from),
+ to: num(args.to),
+ angle: args.angle,
+ scopeSelector: args.selector ?? null,
+ ghost: args.ghost ?? false,
+ };
+}
+
+function printOnionShotSaved(saved: string, elementCount: number): void {
+ console.log(`${c.success("◇")} onion-skin screenshot saved ${c.accent(saved)}`);
+ console.log(
+ c.dim(
+ ` ${elementCount} element${elementCount === 1 ? "" : "s"} · open it to verify the motion matches your target, then read the keyframes below.`,
+ ),
+ );
+ console.log();
+}
+
+/** Render the 3D onion-skin screenshot for every animated element. Returns true
+ * when the command should early-return (a guard failed). */
+async function runOnionShot(
+ comps: SurfacedComposition[],
+ allComps: SurfacedComposition[],
+ projectDir: string | undefined,
+ args: ShotArgs & { selector?: string },
+): Promise<boolean> {
+ const { captureMotionPathShot } = await import("./motionShot.js");
+ // With --selector, sample from the FULL animated set and let the browser scope
+ // to the selector (or its animated descendants when the selector is a static
+ // wrapper like `.clip`). Without it, only the (already-filtered) comps qualify.
+ const requests = collectShotSelectors(args.selector ? allComps : comps);
+ const guardError = onionShotGuardError(projectDir, requests, args.ghost ?? false);
+ if (guardError) {
+ console.log(c.dim(guardError));
+ return true;
+ }
+ const saved = await captureMotionPathShot(
+ projectDir!,
+ requests,
+ resolve(args.shot!),
+ onionShotOptions(args),
+ );
+ printOnionShotSaved(saved, requests.length);
+ return false;
+}
+
+// Resolve the command target (a project dir or a single .html) into surfaced
+// compositions, applying the optional --selector filter.
+function resolveScope(args: { target?: string; selector?: string }): {
+ comps: SurfacedComposition[];
+ allComps: SurfacedComposition[];
+ projectName: string;
+ projectDir: string | undefined;
+} {
+ const raw = args.target?.trim();
+ let comps: SurfacedComposition[];
+ let projectName: string;
+ let projectDir: string | undefined;
+ if (raw && raw.endsWith(".html") && existsSync(raw) && statSync(raw).isFile()) {
+ comps = [surfaceComposition(readFileSync(raw, "utf-8"), basename(raw), raw)];
+ projectName = basename(raw);
+ projectDir = dirname(raw);
+ } else {
+ const project = resolveProject(raw);
+ comps = collectCompositions(project.indexPath);
+ projectName = project.name;
+ projectDir = project.dir;
+ }
+ // allComps keeps the unfiltered set so --shot --selector can resolve a STATIC
+ // wrapper (e.g. `.clip`) to its animated descendants in the live DOM, even
+ // though the literal selector filter (for print/json) drops it to empty.
+ const allComps = comps;
+ if (args.selector) {
+ const sel = args.selector;
+ const matches = (target: string) => target.split(",").some((s) => s.trim() === sel);
+ comps = comps
+ .map((cmp) => ({
+ ...cmp,
+ tweens: cmp.tweens.filter((t) => matches(t.target)),
+ traces: cmp.traces.filter((tr) => matches(tr.target)),
+ cssKeyframes: cmp.cssKeyframes.filter((kf) => kf.selectors.some(matches)),
+ anime: cmp.anime.filter((a) => a.targets.some(matches)),
+ }))
+ .filter(
+ (cmp) =>
+ cmp.tweens.length > 0 ||
+ cmp.traces.length > 0 ||
+ cmp.cssKeyframes.length > 0 ||
+ cmp.anime.length > 0,
+ );
+ }
+ return { comps, allComps, projectName, projectDir };
+}
+
+function isEmptyComposition(cmp: SurfacedComposition): boolean {
+ return (
+ cmp.tweens.length === 0 &&
+ cmp.traces.length === 0 &&
+ cmp.cssKeyframes.length === 0 &&
+ cmp.anime.length === 0
+ );
+}
+
+// Print tweens not already shown as part of a trace (a drawn stroke, or its
+// internal pen-up jump).
+function printCompositionTweens(cmp: SurfacedComposition): void {
+ const tracedIds = new Set(cmp.traces.flatMap((tr) => tr.strokes.map((s) => s.id)));
+ const tracedTargets = new Set(cmp.traces.map((tr) => tr.target));
+ for (const t of cmp.tweens) {
+ if (tracedIds.has(t.id)) continue; // already shown as part of its trace
+ if (t.method === "set" && tracedTargets.has(t.target)) continue; // internal pen-up jump
+ printTween(t);
+ }
+}
+
+// Print one composition's traces + tweens (skipping strokes already shown in a trace).
+function printComposition(cmp: SurfacedComposition): void {
+ if (isEmptyComposition(cmp)) return;
+ console.log(c.bold(`${cmp.composition}`) + c.dim(` (${cmp.source})`));
+ for (const tr of cmp.traces) printTrace(tr);
+ printCompositionTweens(cmp);
+ for (const cssKeyframes of cmp.cssKeyframes) printCssKeyframes(cssKeyframes);
+ for (const anime of cmp.anime) printAnime(anime);
+}
+
+function printCssKeyframes(cssKeyframes: SurfacedCssKeyframes): void {
+ const selectors = cssKeyframes.selectors.length
+ ? cssKeyframes.selectors.join(", ")
+ : "(no selector found)";
+ console.log(
+ ` ${c.accent(`@keyframes ${cssKeyframes.name}`)}${c.dim(" css")} ${c.dim(selectors)}`,
+ );
+ for (const stop of cssKeyframes.keyframes) {
+ console.log(` ${c.dim(`${stop.selector} {${stop.declarations.join("; ")}}`)}`);
+ }
+ console.log();
+}
+
+function printAnime(anime: SurfacedAnimeAnimation): void {
+ const targets = anime.targets.length ? anime.targets.join(", ") : "(targets not parsed)";
+ const durations = anime.durations.length ? ` duration ${anime.durations.join(",")}` : "";
+ const registered = anime.registered ? "registered" : "not registered";
+ console.log(
+ ` ${c.accent(`anime.${anime.kind}`)}${c.dim(` ${registered}`)} ${c.dim(`${targets}${durations}`)}`,
+ );
+ console.log();
+}
+
+// ── Command ──────────────────────────────────────────────────────────────────
+
+interface KeyframesCommandOptions {
+ name: string;
+ description: string;
+ invocation: string;
+ defaultRuntime: "gsap" | "css" | "anime" | "all";
+}
+
+const defaultKeyframesCommand: KeyframesCommandOptions = {
+ name: "keyframes",
+ description:
+ "See, debug, and refine keyframes — surface GSAP, CSS @keyframes, Anime.js, paths, and onion-shot diagnostics",
+ invocation: "hyperframes keyframes",
+ defaultRuntime: "all",
+};
+
+function createKeyframesCommand(options: Partial<KeyframesCommandOptions> = {}) {
+ const commandOptions = { ...defaultKeyframesCommand, ...options };
+
+ return defineCommand({
+ meta: {
+ name: commandOptions.name,
+ description: commandOptions.description,
+ },
+ args: {
+ target: {
+ type: "positional",
+ description: "Project dir or composition .html",
+ required: false,
+ },
+ selector: { type: "string", description: "Only keyframes matching this CSS selector" },
+ runtime: {
+ type: "string",
+ description:
+ "Runtime filter hint: gsap|css|anime|all. Surfaces GSAP tweens, CSS @keyframes, and Anime.js timelines when detectable.",
+ },
+ json: { type: "boolean", description: "Machine-readable JSON (for agents)", default: false },
+ shot: {
+ type: "string",
+ description:
+ "Onion-skin screenshot to PNG: the real element sampled over the timeline (true 3D, every channel) for visual self-verify. Pair with --selector to focus one element.",
+ },
+ samples: {
+ type: "string",
+ description: "Onion samples (equal-time steps) for --shot. Default 9.",
+ },
+ layout: {
+ type: "string",
+ description:
+ "--shot layout: 'path' (ghosts at real positions + path, default) or 'strip' (filmstrip by time — for in-place/overlapping motion).",
+ },
+ from: { type: "string", description: "--shot: sample only from this time (seconds)." },
+ to: { type: "string", description: "--shot: sample only up to this time (seconds)." },
+ angle: {
+ type: "string",
+ description:
+ "--shot orbit camera: a preset (front|iso|top|side|rear-iso) or 'yaw,pitch' degrees — view 3D motion from the angle that reveals it.",
+ },
+ fit: {
+ type: "boolean",
+ description:
+ "--shot: zoom the motion to fill the frame (default true; --no-fit to disable).",
+ default: true,
+ },
+ ghost: {
+ type: "boolean",
+ description:
+ "--shot: rendered onion-skin — composite the real canvas/WebGL frames as translucent ghosts (older fainter), instead of bbox markers. For the canvas-internal 3D motion the marker onion can't see (requires a <canvas>).",
+ default: false,
+ },
+ },
+ async run({ args }) {
+ ensureDOMParser();
+ const runtime = normalizeRuntime(args.runtime, commandOptions.defaultRuntime);
+ if (runtime === "css" || runtime === "anime") {
+ console.log(
+ c.dim(
+ `${commandOptions.name}: ${runtime} output is a static authoring surface; use validate/render/snapshot to verify runtime adapter seekability.`,
+ ),
+ );
+ console.log();
+ }
+ const { comps: rawComps, allComps, projectName, projectDir } = resolveScope(args);
+ const comps = filterCompositionsByRuntime(rawComps, runtime);
+
+ // --shot: 3D onion-skin self-verify screenshot. Returns true when the command
+ // should stop (guard failure) so run() stays small.
+ if (args.shot && (await runOnionShot(comps, allComps, projectDir, args))) return;
+
+ if (args.json) {
+ console.log(
+ JSON.stringify(withMeta({ project: projectName, runtime, compositions: comps }), null, 2),
+ );
+ return;
+ }
+
+ const total = comps.reduce(
+ (n, cmp) => n + cmp.tweens.length + cmp.cssKeyframes.length + cmp.anime.length,
+ 0,
+ );
+ if (total === 0) {
+ console.log(`${c.success("◇")} ${c.accent(projectName)} ${c.dim("— no keyframes found")}`);
+ return;
+ }
+ console.log(
+ `${c.success("◇")} ${c.accent(projectName)} ${c.dim("—")} ${c.dim(`${total} item${total === 1 ? "" : "s"}`)}`,
+ );
+ console.log();
+ for (const cmp of comps) printComposition(cmp);
+ console.log(
+ c.dim(
+ `Tip: edit the keyframes in source, then \`${commandOptions.invocation} --shot out.png\` to see the rendered motion.`,
+ ),
+ );
+ },
+ });
+}
+
+function normalizeRuntime(
+ runtime: unknown,
+ fallback: KeyframesCommandOptions["defaultRuntime"],
+): KeyframesCommandOptions["defaultRuntime"] {
+ if (typeof runtime !== "string") return fallback;
+ const normalized = runtime.toLowerCase();
+ return normalized === "gsap" ||
+ normalized === "css" ||
+ normalized === "anime" ||
+ normalized === "all"
+ ? normalized
+ : fallback;
+}
+
+function filterCompositionsByRuntime(
+ comps: SurfacedComposition[],
+ runtime: KeyframesCommandOptions["defaultRuntime"],
+): SurfacedComposition[] {
+ return comps.map((cmp) => ({
+ ...cmp,
+ tweens: runtime === "gsap" || runtime === "all" ? cmp.tweens : [],
+ traces: runtime === "gsap" || runtime === "all" ? cmp.traces : [],
+ cssKeyframes: runtime === "css" || runtime === "all" ? cmp.cssKeyframes : [],
+ anime: runtime === "anime" || runtime === "all" ? cmp.anime : [],
+ }));
+}
+
+export default createKeyframesCommand();
diff --git a/packages/cli/src/commands/layout-audit.browser.js b/packages/cli/src/commands/layout-audit.browser.js
index 7a1e011b5d..c67ed809e3 100644
--- a/packages/cli/src/commands/layout-audit.browser.js
+++ b/packages/cli/src/commands/layout-audit.browser.js
@@ -359,6 +359,17 @@
};
}
+ // An ancestor (up to and including `stopAt`) that clips its overflow makes any
+ // text spilling past it invisible — that clipping IS the layout mechanism
+ // (odometer/ticker reels, masked windows), not a defect to report.
+ function clippedByAncestor(element, stopAt) {
+ for (let current = element; current; current = current.parentElement) {
+ if (current !== element && clipsOverflow(getComputedStyle(current))) return true;
+ if (current === stopAt) break;
+ }
+ return false;
+ }
+
function textOverflowIssues(element, root, rootRect, time, tolerance) {
const textRect = textRectFor(element);
if (!textRect) return [];
@@ -382,7 +393,11 @@
? tolerance
: Math.max(tolerance, parsePx(elementStyle.fontSize) * 0.2);
const containerOverflow = overflowFor(textRect, containerRect, tolerance, verticalTolerance);
- if (containerOverflow && !hasAllowOverflowFlag(element)) {
+ if (
+ containerOverflow &&
+ !hasAllowOverflowFlag(element) &&
+ !clippedByAncestor(element, container)
+ ) {
const style = elementStyle;
issues.push({
code: "text_box_overflow",
@@ -622,13 +637,31 @@
return Math.min(opacityChain(textScene), opacityChain(occluderScene)) < 0.999;
}
+ // The nearest ancestor establishing a 3D rendering context, or null. Elements
+ // sharing one are depth-sorted in 3D, so a "covering" hit is legitimate
+ // perspective (e.g. the back face of a preserve-3d cube), not a 2D overlap.
+ function preserve3dContext(element) {
+ for (let current = element; current; current = current.parentElement) {
+ const ts = getComputedStyle(current).transformStyle;
+ if (ts === "preserve-3d") return current;
+ }
+ return null;
+ }
+
+ function sharedPreserve3d(a, b) {
+ const ctx = preserve3dContext(a);
+ return !!ctx && ctx === preserve3dContext(b);
+ }
+
// The opaque element painted over (x, y), or null when the topmost element
- // there is related to the text, non-opaque, or a transient crossfade overlap.
+ // there is related to the text, non-opaque, sharing a 3D context with it, or
+ // part of a transient crossfade overlap.
// fallow-ignore-next-line complexity
function occluderAt(element, x, y) {
if (typeof document.elementFromPoint !== "function") return null;
const hit = document.elementFromPoint(x, y);
if (!isForeignElement(element, hit)) return null;
+ if (sharedPreserve3d(element, hit)) return null;
if (!isOpaqueOccluder(hit)) return null;
if (isCrossSceneTransitionOverlap(element, hit)) return null;
return hit;
diff --git a/packages/cli/src/commands/motionShot.ts b/packages/cli/src/commands/motionShot.ts
new file mode 100644
index 0000000000..5db13f6b22
--- /dev/null
+++ b/packages/cli/src/commands/motionShot.ts
@@ -0,0 +1,663 @@
+// Onion-skin motion screenshot: seek the LIVE timeline at N equal-time steps and
+// project the REAL element at each step, so an agent can SELF-VERIFY motion (the
+// rendered result — every channel: position, rotation, scale, opacity, colour),
+// not just the authored x/y numbers. Reuses the headless-Chrome + static-server
+// pattern from layout.ts.
+//
+// 3D is captured for free: zero-size marker children at the element's corners are
+// projected by the browser, so a tilted/edge-on element renders as a real quad.
+// Framing controls (samples / time window / fit / filmstrip) let the agent frame
+// exactly what it's editing. All geometry + SVG live in ./motionShotLayout.ts
+// (pure, tested); this file only drives the browser and SAMPLES.
+
+import { writeFileSync } from "node:fs";
+import {
+ buildOnionSvg,
+ ghostAlphas,
+ parseAngle,
+ resolveShotSelectors,
+ sampleTimes,
+ type OnionElement,
+} from "./motionShotLayout.js";
+
+export interface ShotRequest {
+ /** CSS selector of the moving element to sample (e.g. "#dot"). */
+ selector: string;
+}
+
+/** Returned by the in-browser selector resolver: which animated selectors a
+ * `--selector SCOPE` actually resolves to (scope itself, or its descendants),
+ * plus diagnostic context when nothing under the scope animates. */
+interface ScopeResolution {
+ /** Animated selectors to sample (subset of `requests`). */
+ selectors: string[];
+ /** True when the scope selector matched a real element in the DOM. */
+ scopeExists: boolean;
+}
+
+export interface ShotOptions {
+ /** Equal-time samples across the (windowed) timeline. Default 9. */
+ samples?: number;
+ /** "path" = ghosts at real positions + path; "strip" = filmstrip by time. */
+ layout?: "path" | "strip";
+ /** Zoom the motion to fill the frame. Default true. */
+ fit?: boolean;
+ /** Sample only this time window (seconds) — dense inspection of one phase. */
+ from?: number | null;
+ to?: number | null;
+ /** Orbit camera: a preset (front|iso|top|side) or "yaw,pitch" degrees. */
+ angle?: string;
+ /** `--selector` scope: when the user focused one element, narrow `requests`
+ * to that element if it animates, else to its animated descendants (so a
+ * static `.clip` wrapper resolves to the animated children under it). */
+ scopeSelector?: string | null;
+ /** Rendered ("ghost") onion-skin: capture the canvas pixels at each sample and
+ * composite them as translucent ghosts (older fainter → newest solid) — the
+ * canvas/WebGL motion the bbox-marker onion can't see. Requires a <canvas>. */
+ ghost?: boolean;
+}
+
+interface PageSample {
+ t: number;
+ q: Array<{ x: number; y: number }>;
+ c: { x: number; y: number };
+ color: string;
+ opacity: number;
+}
+
+type OrbitCamera = { yaw: number; pitch: number };
+type FrameSize = { width: number; height: number };
+
+// Runs IN THE BROWSER (serialized by page.evaluate). Make the element's ancestor
+// chain preserve-3d, strip intermediate perspective, put one perspective on the
+// composition root's parent (the lens) and rotate the root — so the element's own
+// 3D is viewed from the requested angle on any composition shape (no #stage assumption).
+function applyOrbitCamera(selectors: string[], cam: OrbitCamera): void {
+ const first = document.querySelector(selectors[0] ?? "");
+ const root =
+ (first?.closest("[data-composition-id]") as HTMLElement | null) ??
+ (document.querySelector("#stage") as HTMLElement | null) ??
+ (document.body.firstElementChild as HTMLElement | null) ??
+ document.body;
+ for (const sel of selectors) {
+ let n = document.querySelector(sel) as HTMLElement | null;
+ while (n && n !== root) {
+ n.style.transformStyle = "preserve-3d";
+ n.style.perspective = "none";
+ n = n.parentElement;
+ }
+ }
+ root.style.transformStyle = "preserve-3d";
+ root.style.perspective = "none";
+ root.style.transformOrigin = "50% 50%";
+ root.style.transform = `rotateX(${cam.pitch}deg) rotateY(${cam.yaw}deg)`;
+ const lens = root.parentElement ?? document.body;
+ lens.style.perspective = "1600px";
+ lens.style.perspectiveOrigin = "50% 50%";
+}
+
+// Runs IN THE BROWSER. Composite N real painted frames (data URLs) onto a black
+// canvas with per-frame opacity (older fainter → newest solid) so canvas/WebGL
+// motion reads as a rendered onion-skin trail. Returns the composite as a PNG
+// data URL. Used by the `--ghost` mode.
+function compositeGhostFrames(
+ frames: string[],
+ alphas: number[],
+ W: number,
+ H: number,
+ label: string,
+): Promise<string> {
+ return new Promise((resolve) => {
+ const cv = document.createElement("canvas");
+ cv.width = W;
+ cv.height = H;
+ const ctx = cv.getContext("2d");
+ if (!ctx) {
+ resolve("");
+ return;
+ }
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, W, H);
+ let i = 0;
+ const step = () => {
+ if (i >= frames.length) {
+ ctx.globalAlpha = 1;
+ ctx.font = "600 22px ui-monospace, SFMono-Regular, Menlo, monospace";
+ ctx.fillStyle = "#86c2ff";
+ ctx.fillText(label, 24, 38);
+ resolve(cv.toDataURL("image/png"));
+ return;
+ }
+ const img = new Image();
+ img.onload = () => {
+ ctx.globalAlpha = alphas[i] ?? 1;
+ ctx.drawImage(img, 0, 0, W, H);
+ i += 1;
+ step();
+ };
+ img.onerror = () => {
+ i += 1;
+ step();
+ };
+ img.src = frames[i] ?? "";
+ };
+ step();
+ });
+}
+
+// Runs IN THE BROWSER. Self-contained (only `tt` + window/document — never a
+// Node-side closure variable), pauses/seeks every adapter to time `tt`: GSAP
+// `__timelines`, the Web Animations API, `__hfAnime` instances, then dispatches
+// `hf-seek` and nudges the three/GSAP render hooks. This one routine backs BOTH
+// the ghost-frame capture and the marker sampler below — see installSeekHelper
+// for why it's installed as a page global instead of being duplicated inline
+// (Puppeteer's page.evaluate only serializes the single function passed to it,
+// so a Node-side function can't be *called* from inside another evaluate
+// callback; it can only be reused by installing its source as a real page
+// global once, up front).
+function seekAllAdaptersInBrowser(tt: number): void {
+ const tryCall = (fn: () => void): void => {
+ try {
+ fn();
+ } catch {
+ /* best-effort */
+ }
+ };
+ const w = window as unknown as {
+ __player?: { renderSeek?: (t: number) => void; seek?: (t: number) => void };
+ __hfThreeTime?: number;
+ __hfThreeRender?: () => void;
+ __hfAnime?: Array<{ pause?: () => void; seek?: (timeMs: number) => void }>;
+ gsap?: { ticker?: { tick?: () => void } };
+ __timelines?: Record<
+ string,
+ {
+ pause?: () => void;
+ seek?: (t: number) => void;
+ totalTime?: (t: number, s: boolean) => void;
+ }
+ >;
+ };
+ const timeMs = Math.max(0, tt * 1000);
+
+ tryCall(() => {
+ if (typeof w.__player?.renderSeek === "function") w.__player.renderSeek(tt);
+ else if (typeof w.__player?.seek === "function") w.__player.seek(tt);
+ });
+
+ Object.values(w.__timelines ?? {}).forEach((tl) => {
+ tryCall(() => {
+ tl.pause?.();
+ if (typeof tl.totalTime === "function") {
+ tl.totalTime(tt + 0.001, true);
+ tl.totalTime(tt, false);
+ } else {
+ tl.seek?.(tt);
+ }
+ });
+ });
+
+ tryCall(() => {
+ if (typeof document.getAnimations === "function") {
+ for (const animation of document.getAnimations()) {
+ tryCall(() => {
+ animation.currentTime = timeMs;
+ });
+ tryCall(() => animation.pause());
+ }
+ }
+ });
+
+ for (const instance of w.__hfAnime ?? []) {
+ tryCall(() => {
+ instance.pause?.();
+ instance.seek?.(timeMs);
+ });
+ }
+
+ tryCall(() => {
+ w.__hfThreeTime = tt;
+ window.dispatchEvent(new CustomEvent("hf-seek", { detail: { time: tt } }));
+ w.__hfThreeRender?.();
+ w.gsap?.ticker?.tick?.();
+ });
+}
+
+// Installs seekAllAdaptersInBrowser as a real `window` global, once per page
+// load. Both the ghost-frame capture and the marker sampler then call it via a
+// plain property access instead of re-declaring its body — see the function's
+// own doc comment for why a page global (rather than a Node-side reference) is
+// required here.
+async function installSeekHelper(page: import("puppeteer-core").Page): Promise<void> {
+ await page.evaluate(`window.__hfSeekAllAdapters = ${seekAllAdaptersInBrowser.toString()};`);
+}
+
+// Launch headless Chrome, load the composition sized to its canvas, wait for the
+// timelines + fonts to be ready. Returns the browser (caller closes it), page, size.
+async function openCompositionPage(
+ url: string,
+ executablePath: string,
+): Promise<{
+ browser: import("puppeteer-core").Browser;
+ page: import("puppeteer-core").Page;
+ size: FrameSize;
+}> {
+ const puppeteer = await import("puppeteer-core");
+ const browser = await puppeteer.default.launch({
+ headless: true,
+ executablePath,
+ args: [
+ "--no-sandbox",
+ "--disable-gpu",
+ "--disable-dev-shm-usage",
+ "--enable-webgl",
+ "--use-gl=angle",
+ "--use-angle=swiftshader",
+ ],
+ });
+ const page = await browser.newPage();
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 10000 });
+ const size = await page.evaluate(() => {
+ const root = document.querySelector("[data-composition-id][data-width][data-height]");
+ const w = root ? parseInt(root.getAttribute("data-width") ?? "", 10) : 0;
+ const h = root ? parseInt(root.getAttribute("data-height") ?? "", 10) : 0;
+ return {
+ width: Number.isFinite(w) && w > 0 ? Math.min(w, 4096) : 1920,
+ height: Number.isFinite(h) && h > 0 ? Math.min(h, 4096) : 1080,
+ };
+ });
+ await page.setViewport(size);
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 10000 });
+ await page
+ .waitForFunction(() => !!(window as unknown as { __timelines?: unknown }).__timelines, {
+ timeout: 10000,
+ })
+ .catch(() => {});
+ await page
+ .evaluate(async () => {
+ const d = document as unknown as { fonts?: { ready?: Promise<unknown> } };
+ if (d.fonts?.ready) await d.fonts.ready;
+ })
+ .catch(() => {});
+ await installSeekHelper(page);
+ return { browser, page, size };
+}
+
+// Longest seekable duration (seconds) across registered timelines, player/root
+// duration, CSS/WAAPI animations, and Anime.js instances.
+function timelineDuration(page: import("puppeteer-core").Page): Promise<number> {
+ return page.evaluate(() => {
+ const finiteSeconds = (value: unknown): number => {
+ const n = typeof value === "number" ? value : Number(value);
+ return Number.isFinite(n) && n > 0 ? n : 0;
+ };
+ const finiteMsToSeconds = (value: unknown): number => {
+ const n = typeof value === "number" ? value : Number(value);
+ return Number.isFinite(n) && n > 0 ? n / 1000 : 0;
+ };
+ const w = window as unknown as {
+ __player?: { getDuration?: () => number };
+ __timelines?: Record<string, { duration?: () => number; totalDuration?: () => number }>;
+ __hfAnime?: Array<{ duration?: number | string; totalDuration?: number | string }>;
+ };
+
+ const timelinesDuration = (): number => {
+ let d = 0;
+ for (const tl of Object.values(w.__timelines ?? {})) {
+ try {
+ d = Math.max(d, (tl.totalDuration?.() ?? tl.duration?.() ?? 0) as number);
+ } catch {
+ // skip
+ }
+ }
+ return d;
+ };
+
+ const animationDurationSeconds = (animation: Animation): number => {
+ const timing = animation.effect?.getTiming?.();
+ if (!timing) return 0;
+ const durationMs = Number(timing.duration);
+ const iterations = Number(timing.iterations ?? 1);
+ if (!Number.isFinite(durationMs) || !Number.isFinite(iterations)) return 0;
+ const delayMs = Number(timing.delay ?? 0);
+ const endDelayMs = Number(timing.endDelay ?? 0);
+ return finiteMsToSeconds(Math.max(0, delayMs) + durationMs * iterations + endDelayMs);
+ };
+
+ const waapiDuration = (): number => {
+ if (typeof document.getAnimations !== "function") return 0;
+ let d = 0;
+ try {
+ for (const animation of document.getAnimations()) {
+ d = Math.max(d, animationDurationSeconds(animation));
+ }
+ } catch {
+ // skip
+ }
+ return d;
+ };
+
+ const animeDuration = (): number => {
+ let d = 0;
+ for (const instance of w.__hfAnime ?? []) {
+ d = Math.max(d, finiteMsToSeconds(instance.totalDuration ?? instance.duration));
+ }
+ return d;
+ };
+
+ let d = finiteSeconds(w.__player?.getDuration?.());
+ const root = document.querySelector("[data-composition-id][data-duration]");
+ if (root) d = Math.max(d, finiteSeconds(root.getAttribute("data-duration")));
+ return Math.max(d, timelinesDuration(), waapiDuration(), animeDuration());
+ });
+}
+
+// In the live DOM, decide which animated selectors fall under `scope`: read
+// whether the scope exists and, for each candidate, whether it is the scope or a
+// descendant of it. The pure decision (motionShotLayout.resolveShotSelectors)
+// runs Node-side on the booleans this returns, so it stays unit-testable.
+async function resolveScopeInBrowser(
+ page: import("puppeteer-core").Page,
+ scope: string,
+ candidates: string[],
+): Promise<ScopeResolution> {
+ const probe = await page.evaluate(
+ (scopeSel: string, cands: string[]) => {
+ let root: Element | null = null;
+ try {
+ root = document.querySelector(scopeSel);
+ } catch {
+ root = null;
+ }
+ const descendant = cands.map((sel) => {
+ if (!root) return false;
+ let el: Element | null = null;
+ try {
+ el = document.querySelector(sel);
+ } catch {
+ return false;
+ }
+ return !!el && (el === root || root.contains(el));
+ });
+ return { scopeExists: !!root, descendant };
+ },
+ scope,
+ candidates,
+ );
+ const selectors = resolveShotSelectors(
+ scope,
+ candidates,
+ (_s, target) => probe.descendant[candidates.indexOf(target)] === true,
+ );
+ return { selectors, scopeExists: probe.scopeExists };
+}
+
+// --selector scope: the focused element is often a STATIC wrapper (`.clip`)
+// whose animated children carry the tweens. Resolve, in the live DOM, to the
+// scope itself if it animates, else its animated descendants — so the shot
+// works on the standard composition shape instead of erroring.
+async function resolveScopedRequests(
+ page: import("puppeteer-core").Page,
+ requests: ShotRequest[],
+ scopeSelector: string,
+): Promise<ShotRequest[]> {
+ const resolved = await resolveScopeInBrowser(
+ page,
+ scopeSelector,
+ requests.map((r) => r.selector),
+ );
+ if (!resolved.scopeExists) {
+ throw new Error(`--shot: --selector '${scopeSelector}' matched no element.`);
+ }
+ if (resolved.selectors.length === 0) {
+ const nearest = requests
+ .slice(0, 5)
+ .map((r) => r.selector)
+ .join(", ");
+ throw new Error(
+ `--shot: nothing animates under '${scopeSelector}'. Nearest animated elements: ${nearest || "(none)"}.`,
+ );
+ }
+ return resolved.selectors.map((selector) => ({ selector }));
+}
+
+// In-tick capture: seek the timeline (fires the composition's onUpdate render
+// synchronously via the shared window.__hfSeekAllAdapters) + nudge the
+// three-adapter, then drawImage every <canvas> onto an offscreen canvas in the
+// SAME tick — before the browser clears the GL drawing buffer (works without
+// preserveDrawingBuffer; page.screenshot can't see the GL buffer here).
+function captureGhostFrame(page: import("puppeteer-core").Page, t: number): Promise<string> {
+ return page.evaluate((tt: number) => {
+ (window as unknown as { __hfSeekAllAdapters?: (time: number) => void }).__hfSeekAllAdapters?.(
+ tt,
+ );
+ const root = (document.querySelector("[data-composition-id]") ?? document.body) as HTMLElement;
+ const rb = root.getBoundingClientRect();
+ const off = document.createElement("canvas");
+ off.width = Math.max(1, Math.round(rb.width));
+ off.height = Math.max(1, Math.round(rb.height));
+ const octx = off.getContext("2d");
+ for (const cv of Array.from(document.querySelectorAll("canvas"))) {
+ const r = cv.getBoundingClientRect();
+ try {
+ octx?.drawImage(cv, r.left - rb.left, r.top - rb.top, r.width, r.height);
+ } catch {
+ /* tainted / not ready — skip */
+ }
+ }
+ return off.toDataURL("image/png");
+ }, t);
+}
+
+// Shared by both onion-skin modes: rotate the composition to the requested
+// orbit angle (a no-op at the front angle), and format that angle for the
+// frame's caption label.
+async function applyOrbitCameraIfAngled(
+ page: import("puppeteer-core").Page,
+ requests: ShotRequest[],
+ camera: OrbitCamera,
+): Promise<void> {
+ if (camera.yaw === 0 && camera.pitch === 0) return;
+ await page.evaluate(
+ applyOrbitCamera,
+ requests.map((r) => r.selector),
+ camera,
+ );
+}
+
+function cameraLabel(camera: OrbitCamera): string {
+ return camera.yaw === 0 && camera.pitch === 0
+ ? "front"
+ : `yaw ${camera.yaw}° pitch ${camera.pitch}°`;
+}
+
+// Rendered ("ghost") onion-skin: screenshot the REAL painted stage at each
+// sample and composite them as translucent ghosts. This is the onion-skin for
+// canvas/WebGL motion the marker sampler is blind to (the markers project a
+// bbox; the pixels are the motion). Works for any visual composition, but
+// requires a <canvas> (DOM/SVG transform motion already shows up in the
+// default marker onion).
+async function captureGhostOnionSkin(
+ page: import("puppeteer-core").Page,
+ requests: ShotRequest[],
+ times: number[],
+ size: FrameSize,
+ camera: OrbitCamera,
+ outPath: string,
+): Promise<string> {
+ await applyOrbitCameraIfAngled(page, requests, camera);
+ const hasCanvas = await page.evaluate(() => document.querySelectorAll("canvas").length > 0);
+ if (!hasCanvas) {
+ throw new Error(
+ "--ghost renders a canvas/WebGL motion trail, but this composition has no <canvas>. Use the default --shot onion for DOM/SVG transform motion.",
+ );
+ }
+ const frames: string[] = [];
+ for (const t of times) {
+ frames.push(await captureGhostFrame(page, t));
+ }
+ const label = `${cameraLabel(camera)} · rendered onion · ${times.length} frames · t ${times[0]}–${times[times.length - 1]}s`;
+ const dataUrl = (await page.evaluate(
+ compositeGhostFrames,
+ frames,
+ ghostAlphas(frames.length),
+ size.width,
+ size.height,
+ label,
+ )) as string;
+ const b64 = String(dataUrl).replace(/^data:image\/png;base64,/, "");
+ if (!b64) throw new Error("ghost composite returned no data");
+ writeFileSync(outPath, Buffer.from(b64, "base64"));
+ return outPath;
+}
+
+// Default (marker) onion-skin: seek to each sample time, read every element's
+// projected corners. Marker children (zero-size) inherit the element's full
+// transform chain, so their screen positions ARE the 3D projection of each
+// corner — this is how 3D comes "for free" without an #stage assumption.
+async function captureMarkerOnionSkin(
+ page: import("puppeteer-core").Page,
+ requests: ShotRequest[],
+ times: number[],
+ size: FrameSize,
+ camera: OrbitCamera,
+ frame: { layout: "path" | "strip"; fit: boolean; hasWindow: boolean },
+ outPath: string,
+): Promise<string> {
+ // Orbit camera as its own step (keeps the sampler simple), only when angled.
+ await applyOrbitCameraIfAngled(page, requests, camera);
+
+ const elements = (await page.evaluate(
+ (selectors: string[], ts: number[]) => {
+ const seek = (window as unknown as { __hfSeekAllAdapters?: (t: number) => void })
+ .__hfSeekAllAdapters;
+
+ const rigs = selectors.map((sel) => {
+ const el = document.querySelector(sel) as HTMLElement | null;
+ if (!el) return null;
+ const w = el.offsetWidth;
+ const h = el.offsetHeight;
+ const local: Array<[number, number]> = [
+ [0, 0],
+ [w, 0],
+ [w, h],
+ [0, h],
+ [w / 2, h / 2],
+ ];
+ const markers = local.map(([lx, ly]) => {
+ const m = document.createElement("div");
+ m.style.cssText = `position:absolute;left:${lx}px;top:${ly}px;width:0;height:0;pointer-events:none`;
+ el.appendChild(m);
+ return m;
+ });
+ return { el, markers };
+ });
+ const out = selectors.map((selector) => ({ selector, samples: [] as PageSample[] }));
+ for (const t of ts) {
+ seek?.(t);
+ rigs.forEach((rig, i) => {
+ if (!rig) return;
+ const pts = rig.markers.map((m) => {
+ const r = m.getBoundingClientRect();
+ return { x: r.left, y: r.top };
+ });
+ const cs = getComputedStyle(rig.el);
+ out[i]!.samples.push({
+ t: Math.round(t * 1000) / 1000,
+ q: pts.slice(0, 4),
+ c: pts[4]!,
+ color: cs.backgroundColor,
+ opacity: parseFloat(cs.opacity) || 0,
+ });
+ });
+ }
+ rigs.forEach((rig) => {
+ if (rig) rig.el.style.visibility = "hidden";
+ });
+ return out.filter((o) => o.samples.length > 0);
+ },
+ requests.map((r) => r.selector),
+ times,
+ )) as OnionElement[];
+
+ const windowStr = frame.hasWindow ? ` · t ${times[0]}–${times[times.length - 1]}s` : "";
+ const label = `${cameraLabel(camera)} · ${frame.layout === "strip" ? "filmstrip" : frame.fit ? "zoom-fit" : "1:1"} · ${times.length} frames${windowStr}`;
+ const svg = buildOnionSvg(elements, {
+ layout: frame.layout,
+ fit: frame.fit,
+ width: size.width,
+ height: size.height,
+ label,
+ });
+
+ await page.evaluate((markup: string) => {
+ document.body.insertAdjacentHTML("beforeend", markup);
+ }, svg);
+ await new Promise((r) => setTimeout(r, 60));
+
+ const buf = await page.screenshot({ type: "png" });
+ if (!buf) throw new Error("screenshot returned no data");
+ writeFileSync(outPath, buf as Uint8Array);
+ return outPath;
+}
+
+/** Render `projectDir`'s index headless, sample each element's motion as a 3D
+ * onion-skin, screenshot to `outPath` (PNG). Returns the saved path. */
+export async function captureMotionPathShot(
+ projectDir: string,
+ requestsIn: ShotRequest[],
+ outPath: string,
+ opts: ShotOptions = {},
+): Promise<string> {
+ let requests = requestsIn;
+ const samples = Math.max(1, Math.min(60, opts.samples ?? 9));
+ const layout = opts.layout ?? "path";
+ const fit = opts.fit ?? true;
+ const camera = parseAngle(opts.angle);
+
+ const { ensureBrowser } = await import("../browser/manager.js");
+ const { serveStaticProjectHtml } = await import("../utils/staticProjectServer.js");
+ const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
+
+ const html = await bundleToSingleHtml(projectDir);
+ const server = await serveStaticProjectHtml(
+ projectDir,
+ html,
+ "Failed to bind motion shot server",
+ );
+ let browserInstance: import("puppeteer-core").Browser | undefined;
+ try {
+ const browser = await ensureBrowser();
+ const opened = await openCompositionPage(server.url, browser.executablePath);
+ browserInstance = opened.browser;
+ const { page, size } = opened;
+
+ if (opts.scopeSelector && !opts.ghost) {
+ requests = await resolveScopedRequests(page, requests, opts.scopeSelector);
+ }
+
+ const times = sampleTimes(
+ await timelineDuration(page),
+ samples,
+ opts.from ?? null,
+ opts.to ?? null,
+ );
+
+ if (opts.ghost) {
+ return await captureGhostOnionSkin(page, requests, times, size, camera, outPath);
+ }
+
+ return await captureMarkerOnionSkin(
+ page,
+ requests,
+ times,
+ size,
+ camera,
+ { layout, fit, hasWindow: opts.from != null || opts.to != null },
+ outPath,
+ );
+ } finally {
+ await browserInstance?.close().catch(() => {});
+ await server.close().catch(() => {});
+ }
+}
diff --git a/packages/cli/src/commands/motionShotLayout.test.ts b/packages/cli/src/commands/motionShotLayout.test.ts
new file mode 100644
index 0000000000..3924c85da9
--- /dev/null
+++ b/packages/cli/src/commands/motionShotLayout.test.ts
@@ -0,0 +1,184 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildOnionSvg,
+ fitTransform,
+ ghostAlphas,
+ parseAngle,
+ resolveShotSelectors,
+ sampleTimes,
+ stripCells,
+ type OnionElement,
+} from "./motionShotLayout.js";
+
+describe("ghostAlphas", () => {
+ it("ramps older→fainter, newest solid, monotonic increasing", () => {
+ expect(ghostAlphas(0)).toEqual([]);
+ expect(ghostAlphas(1)).toEqual([1]);
+ const a = ghostAlphas(5);
+ expect(a).toHaveLength(5);
+ expect(a[0]).toBeCloseTo(0.14, 3); // oldest faintest
+ expect(a[4]).toBe(1); // newest solid
+ for (let i = 1; i < a.length; i++) expect(a[i]).toBeGreaterThan(a[i - 1]!);
+ });
+});
+
+describe("resolveShotSelectors", () => {
+ const animated = [".title", ".cube", ".floor"];
+
+ it("samples the scope itself when the scope animates", () => {
+ // .cube has its own tween → exact selection, no descendant fallback.
+ const got = resolveShotSelectors(".cube", animated, () => {
+ throw new Error("descendant check should not run when scope animates");
+ });
+ expect(got).toEqual([".cube"]);
+ });
+
+ it("falls back to animated descendants when the scope is a static wrapper", () => {
+ // .clip is the standard composition root: static, but every animated element
+ // lives under it → resolve to all of them (this is VERIFIED BUG #9).
+ const got = resolveShotSelectors(".clip", animated, () => true);
+ expect(got).toEqual([".title", ".cube", ".floor"]);
+ });
+
+ it("keeps only the descendants that are actually under the scope", () => {
+ const underPanel = new Set([".title", ".floor"]);
+ const got = resolveShotSelectors(".panel", animated, (_scope, target) =>
+ underPanel.has(target),
+ );
+ expect(got).toEqual([".title", ".floor"]);
+ });
+
+ it("returns [] when nothing animates under the scope (caller errors)", () => {
+ expect(resolveShotSelectors(".empty", animated, () => false)).toEqual([]);
+ });
+});
+
+describe("sampleTimes", () => {
+ it("spreads N equal-time steps across the full duration", () => {
+ expect(sampleTimes(4, 5, null, null)).toEqual([0, 1, 2, 3, 4]);
+ });
+ it("samples only the requested window", () => {
+ expect(sampleTimes(4, 3, 2, 3)).toEqual([2, 2.5, 3]);
+ });
+ it("returns a single point at the window start when n=1", () => {
+ expect(sampleTimes(4, 1, 1.5, 3)).toEqual([1.5]);
+ });
+ it("clamps the window to [0, dur]", () => {
+ expect(sampleTimes(4, 2, -5, 99)).toEqual([0, 4]);
+ });
+});
+
+describe("fitTransform", () => {
+ it("centres on the bbox midpoint", () => {
+ const { cx, cy } = fitTransform(
+ [
+ { x: 100, y: 200 },
+ { x: 300, y: 400 },
+ ],
+ 1000,
+ 1000,
+ );
+ expect(cx).toBe(200);
+ expect(cy).toBe(300);
+ });
+ it("zooms a tiny cluster up (k > 1) but clamps the factor", () => {
+ const { k } = fitTransform(
+ [
+ { x: 0, y: 0 },
+ { x: 10, y: 10 },
+ ],
+ 1000,
+ 1000,
+ );
+ expect(k).toBeGreaterThan(1);
+ expect(k).toBeLessThanOrEqual(7);
+ });
+ it("shrinks an oversized span (k < 1)", () => {
+ const { k } = fitTransform(
+ [
+ { x: 0, y: 0 },
+ { x: 5000, y: 0 },
+ ],
+ 1000,
+ 1000,
+ );
+ expect(k).toBeLessThan(1);
+ expect(k).toBeGreaterThanOrEqual(0.3);
+ });
+ it("is safe on empty input", () => {
+ expect(fitTransform([], 800, 600)).toEqual({ k: 1, cx: 400, cy: 300 });
+ });
+});
+
+describe("stripCells", () => {
+ it("uses a single row for few samples", () => {
+ expect(stripCells(3, 900, 900)).toMatchObject({ cols: 3, rows: 1 });
+ });
+ it("uses a roughly square grid for many samples", () => {
+ expect(stripCells(9, 900, 900)).toMatchObject({ cols: 3, rows: 3 });
+ expect(stripCells(13, 1080, 1080)).toMatchObject({ cols: 4, rows: 4 });
+ });
+});
+
+describe("parseAngle", () => {
+ it("resolves named presets", () => {
+ expect(parseAngle("iso")).toEqual({ yaw: 30, pitch: -22 });
+ expect(parseAngle("top")).toEqual({ yaw: 0, pitch: -68 });
+ });
+ it("parses yaw,pitch pairs", () => {
+ expect(parseAngle("45,-30")).toEqual({ yaw: 45, pitch: -30 });
+ });
+ it("falls back to front on missing or garbage input", () => {
+ expect(parseAngle()).toEqual({ yaw: 0, pitch: 0 });
+ expect(parseAngle("nonsense")).toEqual({ yaw: 0, pitch: 0 });
+ });
+});
+
+const sample = (t: number) => ({
+ t,
+ q: [
+ { x: 0, y: 0 },
+ { x: 10, y: 0 },
+ { x: 10, y: 10 },
+ { x: 0, y: 10 },
+ ],
+ c: { x: 5, y: 5 },
+ color: "rgb(34, 211, 238)",
+ opacity: 1,
+});
+const oneElement: OnionElement[] = [{ selector: "#hero", samples: [sample(0), sample(2)] }];
+
+describe("buildOnionSvg", () => {
+ it("path layout: one ghost per sample, a connecting path, and centre dots", () => {
+ const svg = buildOnionSvg(oneElement, { layout: "path", fit: true, width: 1000, height: 1000 });
+ expect(svg.startsWith("<svg")).toBe(true);
+ expect((svg.match(/<polygon/g) ?? []).length).toBe(2); // 2 ghosts
+ expect((svg.match(/<line/g) ?? []).length).toBe(3); // 2 ticks + 1 path segment
+ expect((svg.match(/<circle/g) ?? []).length).toBe(2); // 2 centre dots
+ });
+ it("strip layout: one framed cell per sample", () => {
+ const svg = buildOnionSvg(oneElement, {
+ layout: "strip",
+ fit: true,
+ width: 1000,
+ height: 1000,
+ });
+ expect((svg.match(/<rect/g) ?? []).length).toBe(2); // 2 cells
+ expect((svg.match(/<polygon/g) ?? []).length).toBe(2);
+ });
+ it("renders the caption label when provided", () => {
+ const svg = buildOnionSvg(oneElement, {
+ layout: "path",
+ fit: true,
+ width: 800,
+ height: 800,
+ label: "front · zoom-fit",
+ });
+ expect(svg).toContain("front");
+ });
+ it("is safe on empty input", () => {
+ const svg = buildOnionSvg([], { layout: "path", fit: true, width: 800, height: 800 });
+ expect(svg.startsWith("<svg")).toBe(true);
+ expect(svg.match(/<polygon/g)).toBeNull();
+ });
+});
diff --git a/packages/cli/src/commands/motionShotLayout.ts b/packages/cli/src/commands/motionShotLayout.ts
new file mode 100644
index 0000000000..fa88d84506
--- /dev/null
+++ b/packages/cli/src/commands/motionShotLayout.ts
@@ -0,0 +1,245 @@
+// Pure, Node-side geometry + SVG generation for the onion-skin motion shot.
+//
+// The headless step (motionShot.ts) only SAMPLES — it seeks the live timeline
+// and reads each element's projected corners. Everything else (which times to
+// sample, how to fit/lay them out, and the SVG markup) lives here as pure
+// functions so it can be unit-tested without a browser.
+
+export interface Pt {
+ x: number;
+ y: number;
+}
+
+/** One time-sample of one element: its 4 projected corners, centre, colour, opacity. */
+export interface OnionSample {
+ t: number;
+ q: Pt[];
+ c: Pt;
+ color: string;
+ opacity: number;
+}
+
+export interface OnionElement {
+ selector: string;
+ samples: OnionSample[];
+}
+
+export type ShotLayout = "path" | "strip";
+
+export interface ShotLayoutOptions {
+ layout: ShotLayout;
+ fit: boolean;
+ width: number;
+ height: number;
+ /** Caption drawn top-left (camera / framing / window info). */
+ label?: string;
+}
+
+export interface Camera {
+ yaw: number;
+ pitch: number;
+}
+
+const ANGLE_PRESETS: Record<string, [number, number]> = {
+ front: [0, 0],
+ iso: [30, -22],
+ top: [0, -68],
+ side: [78, 0],
+ "rear-iso": [205, -22],
+};
+
+/** Parse an angle preset name or "yaw,pitch" degrees into a Camera. */
+export function parseAngle(a?: string): Camera {
+ if (!a) return { yaw: 0, pitch: 0 };
+ const preset = ANGLE_PRESETS[a];
+ if (preset) return { yaw: preset[0], pitch: preset[1] };
+ const [y, p] = a.split(",").map((n) => Number.parseFloat(n));
+ return { yaw: Number.isFinite(y) ? y! : 0, pitch: Number.isFinite(p) ? p! : 0 };
+}
+
+/** Resolve which animated selectors a `--shot --selector SCOPE` should sample.
+ *
+ * The scope element is often a STATIC wrapper (the standard `.clip` root) whose
+ * animated CHILDREN carry the tweens — so a literal match against animated
+ * targets finds nothing. We fall back to the animated descendants of the scope:
+ *
+ * 1. scope itself is animated → sample just scope (exact selection)
+ * 2. scope is static but has animated → sample those descendants
+ * descendants (e.g. `.clip` wrapper)
+ * 3. scope contains nothing animated → sample [] (caller errors, naming
+ * the nearest animated elements)
+ *
+ * `isDescendant(scope, target)` is supplied by the caller (DOM-aware in the
+ * browser); kept as a param so this decision is pure and unit-testable.
+ */
+export function resolveShotSelectors(
+ scope: string,
+ animated: string[],
+ isDescendant: (scope: string, target: string) => boolean,
+): string[] {
+ if (animated.includes(scope)) return [scope];
+ return animated.filter((target) => isDescendant(scope, target));
+}
+
+/** N equal-time sample points across [from?, to?] within [0, dur]. */
+export function sampleTimes(
+ dur: number,
+ n: number,
+ from: number | null,
+ to: number | null,
+): number[] {
+ const t0 = from != null ? Math.max(0, Math.min(from, dur)) : 0;
+ const t1 = to != null ? Math.max(0, Math.min(to, dur)) : dur;
+ const count = Math.max(1, Math.floor(n));
+ if (count === 1) return [t0];
+ return Array.from({ length: count }, (_, i) => {
+ const t = t0 + (i / (count - 1)) * (t1 - t0);
+ return Math.round(t * 1000) / 1000;
+ });
+}
+
+/** Opacity ramp for the rendered ("ghost") onion-skin: older frames fainter,
+ * the newest frame solid, so the composite of real painted frames reads as a
+ * motion trail leading to the final pose. One alpha in [0,1] per sample. */
+export function ghostAlphas(n: number): number[] {
+ if (n <= 0) return [];
+ if (n === 1) return [1];
+ const lo = 0.14;
+ return Array.from(
+ { length: n },
+ (_, i) => Math.round((lo + (1 - lo) * (i / (n - 1))) * 1000) / 1000,
+ );
+}
+
+/** Scale+centre transform that fits `pts` into a W×H frame (with padding). */
+export function fitTransform(
+ pts: Pt[],
+ width: number,
+ height: number,
+): { k: number; cx: number; cy: number } {
+ if (pts.length === 0) return { k: 1, cx: width / 2, cy: height / 2 };
+ const xs = pts.map((p) => p.x);
+ const ys = pts.map((p) => p.y);
+ const minX = Math.min(...xs);
+ const maxX = Math.max(...xs);
+ const minY = Math.min(...ys);
+ const maxY = Math.max(...ys);
+ const cx = (minX + maxX) / 2;
+ const cy = (minY + maxY) / 2;
+ const span = Math.max(maxX - minX, maxY - minY, 1);
+ const k = Math.max(0.3, Math.min(7, (Math.min(width, height) * 0.8) / span));
+ return { k, cx, cy };
+}
+
+/** Grid geometry for the filmstrip layout. */
+export function stripCells(n: number, width: number, height: number) {
+ const cols = n <= 5 ? Math.max(1, n) : Math.ceil(Math.sqrt(n));
+ const rows = Math.ceil(n / cols);
+ return { cols, rows, cellW: width / cols, cellH: height / rows };
+}
+
+const timeColor = (f: number) => `hsl(${190 + f * 150} 90% 65%)`;
+
+const attrs = (o: Record<string, string | number>) =>
+ Object.entries(o)
+ .map(([k, v]) => `${k}="${v}"`)
+ .join(" ");
+
+const polygon = (corners: Pt[], fill: string, fillOpacity: number, stroke: string) =>
+ `<polygon ${attrs({
+ points: corners.map((p) => `${round(p.x)},${round(p.y)}`).join(" "),
+ fill,
+ "fill-opacity": fillOpacity.toFixed(2),
+ stroke,
+ "stroke-width": 2.5,
+ "stroke-linejoin": "round",
+ })}/>`;
+
+const line = (a: Pt, b: Pt, stroke: string, w: number, o: number) =>
+ `<line ${attrs({ x1: round(a.x), y1: round(a.y), x2: round(b.x), y2: round(b.y), stroke, "stroke-width": w, opacity: o, "stroke-linecap": "round" })}/>`;
+
+const circle = (p: Pt, r: number, fill: string) =>
+ `<circle ${attrs({ cx: round(p.x), cy: round(p.y), r, fill })}/>`;
+
+const text = (p: Pt, s: string, fill: string, size = 15) =>
+ `<text ${attrs({ x: round(p.x), y: round(p.y), fill, "font-family": "ui-monospace,monospace", "font-size": size, "font-weight": 600 })}>${escapeXml(s)}</text>`;
+
+const round = (n: number) => Math.round(n * 100) / 100;
+const escapeXml = (s: string) =>
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+
+const ghost = (corners: Pt[], center: Pt, color: string, opacity: number, f: number): string => {
+ const tickEnd = {
+ x: (corners[0]!.x + corners[1]!.x) / 2,
+ y: (corners[0]!.y + corners[1]!.y) / 2,
+ };
+ return (
+ polygon(corners, color, Math.max(0.08, opacity * 0.42), timeColor(f)) +
+ line(center, tickEnd, timeColor(f), 3, 0.9)
+ );
+};
+
+/** Build the full onion-skin SVG overlay markup from sampled elements. */
+export function buildOnionSvg(elements: OnionElement[], opt: ShotLayoutOptions): string {
+ const { width: W, height: H } = opt;
+ let body = "";
+
+ if (opt.layout === "strip") {
+ body = stripBody(elements[0]?.samples ?? [], W, H);
+ } else {
+ body = pathBody(elements, opt.fit, W, H);
+ }
+
+ if (opt.label) body += text({ x: 28, y: 40 }, opt.label, timeColor(0), 18);
+
+ return `<svg ${attrs({
+ xmlns: "http://www.w3.org/2000/svg",
+ style: "position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483647",
+ viewBox: `0 0 ${W} ${H}`,
+ })}>${body}</svg>`;
+}
+
+function pathBody(elements: OnionElement[], fit: boolean, W: number, H: number): string {
+ const all = elements.flatMap((e) => e.samples.flatMap((s) => [...s.q, s.c]));
+ const { k, cx, cy } = fit ? fitTransform(all, W, H) : { k: 1, cx: W / 2, cy: H / 2 };
+ const M = (p: Pt): Pt => ({ x: (p.x - cx) * k + W / 2, y: (p.y - cy) * k + H / 2 });
+ let out = "";
+ for (const el of elements) {
+ const last = el.samples.length - 1;
+ const fOf = (i: number) => (last <= 0 ? 0 : i / last);
+ el.samples.forEach((s, i) => (out += ghost(s.q.map(M), M(s.c), s.color, s.opacity, fOf(i))));
+ for (let i = 0; i < last; i++)
+ out += line(M(el.samples[i]!.c), M(el.samples[i + 1]!.c), timeColor(fOf(i)), 3.5, 0.85);
+ el.samples.forEach((s, i) => {
+ const c = M(s.c);
+ out += circle(c, 4, timeColor(fOf(i)));
+ out += text({ x: c.x + 10, y: c.y + (i % 2 === 0 ? -10 : 18) }, `${s.t}s`, timeColor(fOf(i)));
+ });
+ }
+ return out;
+}
+
+function stripBody(samples: OnionSample[], W: number, H: number): string {
+ if (samples.length === 0) return "";
+ const { cols, cellW, cellH } = stripCells(samples.length, W, H);
+ let maxExt = 1;
+ for (const s of samples)
+ for (const p of s.q) maxExt = Math.max(maxExt, Math.hypot(p.x - s.c.x, p.y - s.c.y));
+ const cellScale = (Math.min(cellW, cellH) * 0.62) / maxExt;
+ const last = samples.length - 1;
+ let out = "";
+ samples.forEach((s, i) => {
+ const col = i % cols;
+ const row = Math.floor(i / cols);
+ const cc = { x: cellW * (col + 0.5), y: cellH * (row + 0.5) };
+ const f = last <= 0 ? 0 : i / last;
+ out += `<rect ${attrs({ x: round(col * cellW + 3), y: round(row * cellH + 3), width: round(cellW - 6), height: round(cellH - 6), fill: "none", stroke: "#1c2531", "stroke-width": 1, rx: 8 })}/>`;
+ const corners = s.q.map((p) => ({
+ x: cc.x + (p.x - s.c.x) * cellScale,
+ y: cc.y + (p.y - s.c.y) * cellScale,
+ }));
+ out += ghost(corners, cc, s.color, s.opacity, f);
+ out += text({ x: col * cellW + 12, y: row * cellH + 24 }, `${s.t}s`, timeColor(f), 16);
+ });
+ return out;
+}
diff --git a/packages/cli/src/commands/snapshot.test.ts b/packages/cli/src/commands/snapshot.test.ts
new file mode 100644
index 0000000000..0537f1705d
--- /dev/null
+++ b/packages/cli/src/commands/snapshot.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from "vitest";
+import { computeSnapshotTimes, tailFrameTime } from "./snapshot.js";
+
+describe("tailFrameTime", () => {
+ it("backs off ~3% of duration so the final frame isn't the blank exact-end", () => {
+ // Verified on the V4 3D artifact: t=8.0 of an 8s clip rendered blank white,
+ // t=7.76 rendered the final hero. 8 - 8*0.03 = 7.76.
+ expect(tailFrameTime(8)).toBeCloseTo(7.76, 5);
+ });
+
+ it("uses a 50ms floor for short clips", () => {
+ expect(tailFrameTime(1)).toBeCloseTo(0.95, 5); // 1 - 0.05 (floor beats 3%)
+ });
+
+ it("never goes negative", () => {
+ expect(tailFrameTime(0)).toBe(0);
+ });
+});
+
+describe("computeSnapshotTimes (FINDING [7]: tail is always captured)", () => {
+ it("default frames: last point is the readable tail, never exact duration", () => {
+ const { times, appendedTail } = computeSnapshotTimes(8, { frames: 5 });
+ expect(times).toHaveLength(5);
+ expect(times[0]).toBe(0);
+ expect(times[times.length - 1]).toBeCloseTo(7.76, 5);
+ expect(times[times.length - 1]).toBeLessThan(8); // not the blank exact-end
+ expect(appendedTail).toBe(false);
+ });
+
+ it("single frame samples the midpoint", () => {
+ expect(computeSnapshotTimes(8, { frames: 1 }).times).toEqual([4]);
+ });
+
+ it("explicit --at: keeps the user's times AND appends an end-of-timeline frame", () => {
+ const { times, appendedTail } = computeSnapshotTimes(8, { frames: 5, at: [1, 2, 3] });
+ expect(times.slice(0, 3)).toEqual([1, 2, 3]);
+ expect(times[times.length - 1]).toBeCloseTo(7.76, 5);
+ expect(appendedTail).toBe(true);
+ });
+
+ it("explicit --at: does not double-add when the user already sampled the tail", () => {
+ const { times, appendedTail } = computeSnapshotTimes(8, { frames: 5, at: [1, 7.76] });
+ expect(times).toEqual([1, 7.76]);
+ expect(appendedTail).toBe(false);
+ });
+
+ it("explicit --at: a sample at exact duration counts as the tail (no append)", () => {
+ const { appendedTail } = computeSnapshotTimes(8, { frames: 5, at: [1, 8] });
+ expect(appendedTail).toBe(false);
+ });
+
+ it("respects includeEnd:false opt-out for --at", () => {
+ const { times, appendedTail } = computeSnapshotTimes(8, {
+ frames: 5,
+ at: [1, 2],
+ includeEnd: false,
+ });
+ expect(times).toEqual([1, 2]);
+ expect(appendedTail).toBe(false);
+ });
+});
diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.ts
index ee6bfcfda5..42d408659f 100644
--- a/packages/cli/src/commands/snapshot.ts
+++ b/packages/cli/src/commands/snapshot.ts
@@ -10,8 +10,42 @@ import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
import { c } from "../ui/colors.js";
import { findFFmpeg } from "../browser/ffmpeg.js";
+import { parseAngle, type Camera } from "./motionShotLayout.js";
import type { Example } from "./_examples.js";
+// Runs IN THE BROWSER (serialized into page.evaluate). Tilt the whole stage so
+// the REAL painted pixels are viewed from an orthogonal angle (FINDING [10]:
+// snapshot only captured the composition's own head-on camera, so 3D depth /
+// occlusion couldn't be verified). Same approach as motionShot's orbit camera:
+// make the composition root + its ancestor chain preserve-3d, strip intermediate
+// perspective, put one perspective on the root's parent (the lens) and rotate
+// the root — works on any composition shape (no #stage assumption).
+//
+// Kept as a self-contained copy of motionShot.ts's `applyOrbitCamera` because
+// that one is module-private; this is ~15 lines and sharing it would mean
+// touching motionShot.ts (out of scope for this change).
+function orbitStageSource(): string {
+ return `function(cam) {
+ var root = document.querySelector("[data-composition-id]")
+ || document.querySelector("#stage")
+ || document.body.firstElementChild
+ || document.body;
+ var n = root;
+ while (n && n !== document.body) {
+ n.style.transformStyle = "preserve-3d";
+ n.style.perspective = "none";
+ n = n.parentElement;
+ }
+ root.style.transformStyle = "preserve-3d";
+ root.style.perspective = "none";
+ root.style.transformOrigin = "50% 50%";
+ root.style.transform = "rotateX(" + cam.pitch + "deg) rotateY(" + cam.yaw + "deg)";
+ var lens = root.parentElement || document.body;
+ lens.style.perspective = "1600px";
+ lens.style.perspectiveOrigin = "50% 50%";
+ }`;
+}
+
/** Maximum time a single-frame FFmpeg extract is allowed to run. Mirrors the
* default applied by `@hyperframes/engine`'s `runFfmpeg` so a pathological
* clip (corrupt media, stalled network mount, codec edge case) cannot wedge
@@ -87,15 +121,76 @@ async function extractVideoFrameToBuffer(
export const examples: Example[] = [
["Capture 5 key frames from a composition", "snapshot capture"],
["Capture 10 evenly-spaced frames", "snapshot capture --frames 10"],
+ ["View the 3D stage from an isometric angle", "snapshot capture --angle iso"],
];
+/**
+ * Seeking the timeline to EXACTLY `data-duration` renders blank — the runtime
+ * treats t >= clip-end as past-end and unmounts the clip (verified on a V4 3D
+ * artifact: t=8.0 of an 8s clip was pure white, t=7.76 showed the final hero).
+ * So the "final frame" must be sampled just-before-end. The blank tail observed
+ * spanned the last ~2.5% of the timeline, hence a 3%-of-duration nudge (floored
+ * at 50ms so very short clips still back off a readable amount).
+ */
+export function tailFrameTime(duration: number): number {
+ return Math.max(0, duration - Math.max(0.05, duration * 0.03));
+}
+
+/**
+ * Pick the seek positions to screenshot. Pure so the "tail is always captured"
+ * guarantee is unit-testable (FINDING [7]: evenly-spaced --at times skipped the
+ * final beat and short hero beats with no signal).
+ *
+ * - No --at: evenly-spaced frames, but the LAST point is moved off the exact
+ * duration to `tailFrameTime` so it isn't blank.
+ * - With --at: the user's exact times are honoured, plus a guaranteed
+ * end-of-timeline frame appended (unless `includeEnd` is false), so the tail
+ * is never silently skipped. A near-duplicate of the tail is not added twice.
+ *
+ * `appendedTail` flags that the readable-tail frame was added on top of the
+ * caller's request — used to warn that short sub-interval beats between samples
+ * may still be missed and need explicit --at.
+ */
+export function computeSnapshotTimes(
+ duration: number,
+ opts: { frames: number; at?: number[]; includeEnd?: boolean },
+): { times: number[]; appendedTail: boolean } {
+ const includeEnd = opts.includeEnd !== false;
+ const tail = tailFrameTime(duration);
+ const round = (t: number) => Math.round(t * 1000) / 1000;
+
+ if (opts.at?.length) {
+ const times = opts.at.map(round);
+ // Only append if the user didn't already sample at/near the readable tail.
+ const hasTail = times.some((t) => Math.abs(t - tail) < 0.05 || t >= duration);
+ if (includeEnd && duration > 0 && !hasTail) {
+ return { times: [...times, round(tail)], appendedTail: true };
+ }
+ return { times, appendedTail: false };
+ }
+
+ const n = opts.frames;
+ if (n <= 1) return { times: [round(duration / 2)], appendedTail: false };
+ const times = Array.from({ length: n }, (_, i) => (i / (n - 1)) * duration);
+ // Replace the final (exact-duration, blank) point with the readable tail.
+ if (includeEnd) times[times.length - 1] = tail;
+ return { times: times.map(round), appendedTail: false };
+}
+
/**
* Render key frames from a composition as PNG screenshots.
* The agent can Read these to verify its output visually.
*/
async function captureSnapshots(
projectDir: string,
- opts: { frames?: number; timeout?: number; at?: number[]; outputDir?: string },
+ opts: {
+ frames?: number;
+ timeout?: number;
+ at?: number[];
+ outputDir?: string;
+ angle?: Camera;
+ includeEnd?: boolean;
+ },
): Promise<string[]> {
const { bundleToSingleHtml } = await import("@hyperframes/core/compiler");
const { ensureBrowser } = await import("../browser/manager.js");
@@ -226,12 +321,25 @@ async function captureSnapshots(
return [];
}
- // Calculate seek positions — explicit timestamps or evenly spaced
- const positions: number[] = opts.at?.length
- ? opts.at
- : numFrames === 1
- ? [duration / 2]
- : Array.from({ length: numFrames }, (_, i) => (i / (numFrames - 1)) * duration);
+ // Calculate seek positions — explicit timestamps or evenly spaced, always
+ // including a readable end-of-timeline frame (FINDING [7]).
+ const { times: positions, appendedTail } = computeSnapshotTimes(duration, {
+ frames: numFrames,
+ at: opts.at,
+ includeEnd: opts.includeEnd,
+ });
+ if (appendedTail) {
+ console.log(
+ ` ${c.dim(`Note: added an end-of-timeline frame at ${positions[positions.length - 1]!.toFixed(2)}s. Short beats between your --at times may still be skipped — pass them explicitly.`)}`,
+ );
+ }
+
+ // Orthogonal camera (FINDING [10]) — re-applied after each seek inside the
+ // loop, since renderSeek may touch the stage's inline transform.
+ const cameraExpr =
+ opts.angle && (opts.angle.yaw !== 0 || opts.angle.pitch !== 0)
+ ? `(${orbitStageSource()})(${JSON.stringify(opts.angle)})`
+ : null;
const snapshotDir = opts.outputDir ?? join(projectDir, "snapshots");
mkdirSync(snapshotDir, { recursive: true });
@@ -319,6 +427,8 @@ async function captureSnapshots(
requestAnimationFrame(function() { requestAnimationFrame(finish); });
})`);
+ if (cameraExpr) await page.evaluate(cameraExpr);
+
if (injectVideoFramesBatch && syncVideoFrameVisibility) {
const active = await page.evaluate((t: number) => {
return Array.from(document.querySelectorAll("video[data-start]"))
@@ -460,6 +570,17 @@ export default defineCommand({
description: "Ms to wait for runtime to initialize (default: 5000)",
default: "5000",
},
+ angle: {
+ type: "string",
+ description:
+ "Orthogonal 3D camera for depth/occlusion checks: a preset (front|iso|top|side) or 'yaw,pitch' degrees. Tilts the whole stage before screenshotting (real pixels, not bbox markers).",
+ },
+ end: {
+ type: "boolean",
+ description:
+ "Always include a readable end-of-timeline frame (default: true). Pass --no-end to capture only your exact --at times.",
+ default: true,
+ },
describe: {
type: "string",
description:
@@ -487,10 +608,16 @@ export default defineCommand({
? null
: String(args.describe);
+ const camera = args.angle ? parseAngle(String(args.angle)) : undefined;
+
const label = atTimestamps
? `${atTimestamps.length} frames at [${atTimestamps.map((t) => t.toFixed(1) + "s").join(", ")}]`
: `${frames} frames`;
- console.log(`${c.accent("◆")} Capturing ${label} from ${c.accent(project.name)}`);
+ const angleLabel =
+ camera && (camera.yaw !== 0 || camera.pitch !== 0)
+ ? ` ${c.dim(`(angle yaw ${camera.yaw}° pitch ${camera.pitch}°)`)}`
+ : "";
+ console.log(`${c.accent("◆")} Capturing ${label} from ${c.accent(project.name)}${angleLabel}`);
try {
const snapshotDir = args.output
@@ -501,6 +628,8 @@ export default defineCommand({
timeout,
at: atTimestamps,
outputDir: snapshotDir,
+ angle: camera,
+ includeEnd: args.end !== false,
});
if (paths.length === 0) {
diff --git a/packages/cli/src/help.ts b/packages/cli/src/help.ts
index a44796da07..41f22a6acf 100644
--- a/packages/cli/src/help.ts
+++ b/packages/cli/src/help.ts
@@ -39,6 +39,7 @@ const GROUPS: Group[] = [
],
["beats", "Detect beats in the music track and write beats/<audio>.json"],
["inspect", "Inspect rendered visual layout across the timeline"],
+ ["keyframes", "Inspect keyframes and render onion-shot diagnostics"],
["snapshot", "Capture key frames as PNG screenshots for visual verification"],
["info", "Print project metadata"],
["compositions", "List all compositions in a project"],
diff --git a/packages/cli/src/utils/layoutAudit.test.ts b/packages/cli/src/utils/layoutAudit.test.ts
index f748992053..6c4ffc9704 100644
--- a/packages/cli/src/utils/layoutAudit.test.ts
+++ b/packages/cli/src/utils/layoutAudit.test.ts
@@ -3,6 +3,7 @@ import {
buildLayoutSampleTimes,
buildTransitionSampleTimes,
computeOverflow,
+ overflowValueClips,
collapseStaticLayoutIssues,
limitLayoutIssues,
mergeSampleTimes,
@@ -165,6 +166,22 @@ describe("layoutAudit helpers", () => {
expect(formatted).toContain("t=1-5s (3 samples)");
});
+ // The clip rule that suppresses the odometer/ticker false positive: text
+ // spilling past an `overflow:hidden` reel window is the mechanism, not a bug.
+ it("treats clipping overflow values as masking (suppress) and visible as not (still report)", () => {
+ // Intended clipping — the queued digit rows of a reel are masked here.
+ expect(overflowValueClips("hidden")).toBe(true);
+ expect(overflowValueClips("clip")).toBe(true);
+ expect(overflowValueClips("auto")).toBe(true);
+ expect(overflowValueClips("scroll")).toBe(true);
+ // Genuine overflow — nothing masks the text, so it must STILL be reported.
+ expect(overflowValueClips("visible")).toBe(false);
+ expect(overflowValueClips("clip visible")).toBe(false);
+ expect(overflowValueClips("")).toBe(false);
+ expect(overflowValueClips(null)).toBe(false);
+ expect(overflowValueClips(undefined)).toBe(false);
+ });
+
it("limits returned issues by severity before truncating", () => {
const limited = limitLayoutIssues(
[
diff --git a/packages/cli/src/utils/layoutAudit.ts b/packages/cli/src/utils/layoutAudit.ts
index 2826c1dcf5..70b00deb9c 100644
--- a/packages/cli/src/utils/layoutAudit.ts
+++ b/packages/cli/src/utils/layoutAudit.ts
@@ -95,6 +95,18 @@ export function computeOverflow(
return Object.keys(overflow).length > 0 ? overflow : null;
}
+/**
+ * Whether a computed `overflow*` value clips its box. Mirrors the rule the
+ * browser audit (layout-audit.browser.js) uses to decide that text spilling
+ * past such an ancestor is intentionally masked (odometer/ticker reels) rather
+ * than a `text_box_overflow` defect. Kept here as the one unit-testable seam of
+ * that suppression: only `visible` (and the `clip visible` no-op) must NOT clip
+ * — every clipping value must, or real masked overflow gets reported as a bug.
+ */
+export function overflowValueClips(value: string | null | undefined): boolean {
+ return !!value && value !== "visible" && value !== "clip visible";
+}
+
export function summarizeLayoutIssues(issues: LayoutIssue[]): LayoutSummary {
const errorCount = issues.filter((issue) => issue.severity === "error").length;
const warningCount = issues.filter((issue) => issue.severity === "warning").length;
diff --git a/packages/core/src/parsers/gsapParserAcorn.motionEval.test.ts b/packages/core/src/parsers/gsapParserAcorn.motionEval.test.ts
new file mode 100644
index 0000000000..db2e9ac9bb
--- /dev/null
+++ b/packages/core/src/parsers/gsapParserAcorn.motionEval.test.ts
@@ -0,0 +1,194 @@
+/**
+ * Motion-introspection eval regressions (the `hyperframes motion` read path).
+ *
+ * Each block targets one bug the tooling eval surfaced where the parser was
+ * blind to authored motion. Minimal inline scripts reproduce the wrong output,
+ * then assert the fixed behavior.
+ */
+import { describe, it, expect } from "vitest";
+import { parseGsapScriptAcorn } from "./gsapParserAcorn.js";
+
+const start = (a: { resolvedStart?: number }): number | undefined => a.resolvedStart;
+
+// ── Bug #2: constant expression folding (member / array-index / Math.*) ───────
+
+describe("motion eval — constant expression folding (#2)", () => {
+ it("folds object-member access (H.bar0 / 200)", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const H = { bar0: 100, bar1: 50 };
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#bar0", { scaleY: H.bar0 / 200, duration: 0.7 }, 0.3);
+ `);
+ expect(animations[0]!.properties.scaleY).toBe(0.5);
+ });
+
+ it("folds nested array index (SPARK[0][1])", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const SPARK = [[10, 20], [30, 40]];
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#m", { x: SPARK[0][1], y: SPARK[1][0], duration: 0.3 }, 0);
+ `);
+ expect(animations[0]!.properties.x).toBe(20);
+ expect(animations[0]!.properties.y).toBe(30);
+ });
+
+ it("folds whitelisted Math.* over constant args", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#m", { x: Math.round(2.6), y: Math.max(3, 7), r: Math.PI, duration: 0.3 }, 0);
+ `);
+ expect(animations[0]!.properties.x).toBe(3);
+ expect(animations[0]!.properties.y).toBe(7);
+ expect(animations[0]!.properties.r).toBeCloseTo(Math.PI);
+ });
+
+ it("leaves genuinely runtime-dynamic values as __raw", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#m", { x: someFn(), duration: 0.3 }, 0);
+ `);
+ expect(String(animations[0]!.properties.x)).toMatch(/^__raw:/);
+ });
+});
+
+// ── Bug #1: gsap.set() pre-state seeds the next tween's from-keyframe ──────────
+
+describe("motion eval — set() seeds tween start (#1)", () => {
+ it("seeds scaleY:0 from gsap.set before a .to(scaleY:1)", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ gsap.set("#bar", { scaleY: 0 });
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#bar", { scaleY: 1, duration: 0.7 }, 0.3);
+ `);
+ const grow = animations.find((a) => a.targetSelector === "#bar" && a.method === "to")!;
+ expect(grow.fromProperties?.scaleY).toBe(0);
+ });
+
+ it("uses the most recent set() value and only for omitted from-props", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ gsap.set("#x", { opacity: 0, y: 8 });
+ const tl = gsap.timeline({ paused: true });
+ tl.set("#x", { opacity: 0.2 }, 0);
+ tl.to("#x", { opacity: 1, y: 0, duration: 0.5 }, 0.3);
+ `);
+ const t = animations.find((a) => a.method === "to")!;
+ expect(t.fromProperties?.opacity).toBe(0.2); // most recent set wins
+ expect(t.fromProperties?.y).toBe(8);
+ });
+});
+
+// ── Bug #3: labels & label-relative positions ─────────────────────────────────
+
+describe("motion eval — label-relative positions (#3)", () => {
+ it("resolves numeric-label and label+=n positions to absolute times", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#c", { x: 10, duration: 1.1 }, 0);
+ tl.addLabel("press", 1.1);
+ tl.to("#c", { x: 20, duration: 0.12 }, "press");
+ tl.to("#b", { scale: 1, duration: 0.32 }, "press+=0.12");
+ tl.addLabel("loading", "press+=0.18");
+ tl.to("#l", { opacity: 1, duration: 0.2 }, "loading");
+ `);
+ const bySel = (s: string, i = 0) => animations.filter((a) => a.targetSelector === s)[i]!;
+ expect(start(bySel("#c", 1))).toBeCloseTo(1.1);
+ expect(start(bySel("#b"))).toBeCloseTo(1.22);
+ expect(start(bySel("#l"))).toBeCloseTo(1.28); // press(1.1)+0.18
+ });
+});
+
+// ── Bug #4: collection aliases (slice / index) keep the selector ──────────────
+
+describe("motion eval — collection aliases (#4)", () => {
+ it("resolves selector for glyphs.slice() / glyphs[0] aliases of toArray()", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const glyphs = gsap.utils.toArray(".glyph");
+ const lead = glyphs[0];
+ const rest = glyphs.slice(1);
+ const tl = gsap.timeline({ paused: true });
+ tl.to(lead, { y: 0, duration: 0.5 }, 0.2);
+ tl.to(rest, { y: 0, duration: 0.6, stagger: 0.085 }, 0.5);
+ `);
+ expect(animations[0]!.targetSelector).toBe(".glyph");
+ expect(animations[1]!.targetSelector).toBe(".glyph");
+ expect(animations[1]!.hasUnresolvedSelector).toBeUndefined();
+ // stagger still preserved in extras
+ expect(animations[1]!.extras?.stagger).toBeDefined();
+ });
+});
+
+// ── Bug: staggered collection tweens read as flat no-ops ──────────────────────
+
+describe("motion eval — staggered collection tweens are honest", () => {
+ it("surfaces real from/to + stagger for a staggered .from reveal (not a flat no-op)", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ tl.from(".glyph", { yPercent: 120, stagger: 0.08, duration: 0.5 }, 0);
+ `);
+ const a = animations[0]!;
+ // Surfaced as keyframes so the `motion` text shows real per-element motion.
+ const kfs = a.keyframes?.keyframes ?? [];
+ expect(kfs.length).toBeGreaterThan(0);
+ // from() plays vars → rest: 120 → 0, a real non-no-op move.
+ expect(kfs[0]!.properties.yPercent).toBe(120);
+ expect(kfs.at(-1)!.properties.yPercent).toBe(0);
+ // The per-element stagger is noted on the surfaced keyframes.
+ expect(kfs.every((k) => k.properties.stagger === 0.08)).toBe(true);
+ // Per-element duration preserved; selector + extras untouched (round-trip safe).
+ expect(a.duration).toBe(0.5);
+ expect(a.targetSelector).toBe(".glyph");
+ expect(a.extras?.stagger).toBeDefined();
+ });
+
+ it("notes the stagger even when a .to lands on the rest pose (1→1 case)", () => {
+ // to(rest-pose) reads as 1→1; without the stagger note it looks like a no-op.
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to(".glyph", { scaleY: 1, scaleX: 1, yPercent: 0, duration: 0.18,
+ stagger: { each: 0.012, from: "center" } }, 0);
+ `);
+ const a = animations[0]!;
+ const kfs = a.keyframes?.keyframes ?? [];
+ expect(kfs.length).toBeGreaterThan(0);
+ // The collection still reads as animating: the per-element stagger is shown.
+ expect(kfs.every((k) => k.properties.stagger === 0.012)).toBe(true);
+ expect(a.duration).toBe(0.18);
+ });
+
+ it("leaves a non-staggered single tween untouched (no synthetic keyframes)", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to("#hero", { x: 100, duration: 0.4 }, 0);
+ `);
+ expect(animations[0]!.targetSelector).toBe("#hero");
+ expect(animations[0]!.keyframes).toBeUndefined();
+ });
+});
+
+// ── Bug #11 / #5: dwell tweens & onUpdate proxy clarity ───────────────────────
+
+describe("motion eval — dwell / proxy targets (#11, #5)", () => {
+ it("labels empty-target dwell tweens instead of __unresolved__", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ tl.to({}, { duration: 2.8 }, 2.2);
+ `);
+ const dwell = animations[0]!;
+ expect(dwell.targetSelector).not.toBe("__unresolved__");
+ expect(dwell.targetSelector).toContain("dwell");
+ expect(dwell.duration).toBe(2.8);
+ });
+
+ it("labels an onUpdate proxy tween with its driven DOM property", () => {
+ const { animations } = parseGsapScriptAcorn(`
+ const tl = gsap.timeline({ paused: true });
+ const s = { u: 0 };
+ tl.to(s, { u: 1, duration: 2.2, onUpdate: function () {
+ document.querySelector("#trace").setAttribute("stroke-dashoffset", s.u);
+ } }, 0.2);
+ `);
+ const drv = animations[0]!;
+ expect(drv.targetSelector).not.toBe("__unresolved__");
+ expect(drv.targetSelector).toContain("stroke-dashoffset");
+ });
+});
diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.ts
index 515a4a0874..d1104ca03d 100644
--- a/packages/core/src/runtime/init.test.ts
+++ b/packages/core/src/runtime/init.test.ts
@@ -271,6 +271,28 @@ describe("initSandboxRuntimeModular", () => {
expect(child.style.visibility).toBe("hidden");
});
+ it("binds the sole registered timeline even when the root id is missing", () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ // Root is MISSING data-composition-id, but there is exactly one usable
+ // timeline registered. The DX fallback can bind it unambiguously instead of
+ // letting the render freeze at t=0.
+ const root = document.createElement("div");
+ root.className = "clip";
+ root.setAttribute("data-root", "true");
+ root.setAttribute("data-start", "0");
+ root.setAttribute("data-width", "1920");
+ root.setAttribute("data-height", "1080");
+ document.body.appendChild(root);
+
+ window.__timelines = { main: createMockTimeline(6) };
+
+ initSandboxRuntimeModular();
+
+ const warned = warnSpy.mock.calls.map((c) => String(c[0])).join("\n");
+ expect(window.__player?.getDuration()).toBe(6);
+ expect(warned).not.toContain("Root timeline not bound");
+ });
+
it("uses the shorter authored host window when the child timeline is longer", () => {
const root = document.createElement("div");
root.setAttribute("data-composition-id", "main");
@@ -487,9 +509,10 @@ describe("initSandboxRuntimeModular", () => {
expect(window.__player?.getDuration()).toBe(7);
});
- // #6: when the root id is missing AND two timelines are registered, the
- // fallback is ambiguous, so nothing is bound (the loud warning fires instead).
+ // #6: when the root id is unmatched AND two timelines are registered, the
+ // fallback is ambiguous, so nothing is bound and the loud warning fires.
it("does not bind any timeline when the root id is unmatched and multiple are registered", () => {
+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const root = document.createElement("div");
root.setAttribute("data-composition-id", "main");
root.setAttribute("data-root", "true");
@@ -505,7 +528,12 @@ describe("initSandboxRuntimeModular", () => {
initSandboxRuntimeModular();
+ const warned = warnSpy.mock.calls.map((c) => String(c[0])).join("\n");
expect(window.__player?.getDuration()).toBe(0);
+ expect(warned).toContain("[hyperframes]");
+ expect(warned).toContain("Root timeline not bound");
+ expect(warned).toContain("wrong-key-a");
+ expect(warned).toContain("wrong-key-b");
});
it("pauses nested media that is outside the timed-media cache after a seek", () => {
diff --git a/packages/lint/src/rules/core.test.ts b/packages/lint/src/rules/core.test.ts
index 5f601e8583..dfe9a28b18 100644
--- a/packages/lint/src/rules/core.test.ts
+++ b/packages/lint/src/rules/core.test.ts
@@ -666,6 +666,38 @@ body {
const finding = result.findings.find((f) => f.code === "timeline_id_mismatch");
expect(finding).toBeUndefined();
});
+
+ it("accepts object-literal timeline registration and extracts its keys", async () => {
+ const html = `
+<html><body>
+ <div data-composition-id="comp-1" data-width="1920" data-height="1080"></div>
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines = { "comp-1": tl };
+ </script>
+</body></html>`;
+ const result = await lintHyperframeHtml(html);
+ expect(result.findings.find((f) => f.code === "missing_timeline_registry")).toBeUndefined();
+ expect(
+ result.findings.find((f) => f.code === "timeline_registry_missing_init"),
+ ).toBeUndefined();
+ expect(result.findings.find((f) => f.code === "timeline_id_mismatch")).toBeUndefined();
+ });
+
+ it("reports mismatched object-literal timeline registration keys", async () => {
+ const html = `
+<html><body>
+ <div data-composition-id="comp-1" data-width="1920" data-height="1080"></div>
+ <script>
+ const tl = gsap.timeline({ paused: true });
+ window.__timelines = { main: tl };
+ </script>
+</body></html>`;
+ const result = await lintHyperframeHtml(html);
+ const finding = result.findings.find((f) => f.code === "timeline_id_mismatch");
+ expect(finding).toBeDefined();
+ expect(finding?.message).toContain('Timeline registered as "main"');
+ });
});
it("warns when a timeline-visible element has no stable id for Studio editing", async () => {
diff --git a/packages/lint/src/rules/core.ts b/packages/lint/src/rules/core.ts
index fec78abee4..016fa25845 100644
--- a/packages/lint/src/rules/core.ts
+++ b/packages/lint/src/rules/core.ts
@@ -9,6 +9,7 @@ import {
getInlineScriptSyntaxError,
TIMELINE_REGISTRY_INIT_PATTERN,
TIMELINE_REGISTRY_ASSIGN_PATTERN,
+ TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN,
INVALID_SCRIPT_CLOSE_PATTERN,
} from "../utils";
@@ -252,7 +253,8 @@ export const coreRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
const findings: HyperframeLintFinding[] = [];
if (
!TIMELINE_REGISTRY_INIT_PATTERN.test(source) &&
- !TIMELINE_REGISTRY_ASSIGN_PATTERN.test(source)
+ !TIMELINE_REGISTRY_ASSIGN_PATTERN.test(source) &&
+ !TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN.test(source)
) {
findings.push({
code: "missing_timeline_registry",
diff --git a/packages/lint/src/rules/gsap.ts b/packages/lint/src/rules/gsap.ts
index 03fd0e6219..010c7a5e14 100644
--- a/packages/lint/src/rules/gsap.ts
+++ b/packages/lint/src/rules/gsap.ts
@@ -26,7 +26,9 @@ import {
readAttr,
truncateSnippet,
stripJsComments,
+ hasCaptionStyles,
WINDOW_TIMELINE_ASSIGN_PATTERN,
+ TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN,
} from "../utils";
// ── GSAP-specific types ────────────────────────────────────────────────────
@@ -274,6 +276,17 @@ function findContainingCompositionId(tag: OpenTag, ranges: CompositionRange[]):
return match?.id || null;
}
+// A tag's `class` attribute, split into tokens, but only when it carries the
+// `clip` marker class — the common "is this a clip element?" filter used by
+// several rules that walk every tag looking for clips.
+type ClipTagClasses = { classAttr: string; classes: string[] };
+
+function getClipTagClasses(tag: OpenTag): ClipTagClasses | null {
+ const classAttr = readAttr(tag.raw, "class") || "";
+ const classes = classAttr.split(/\s+/).filter(Boolean);
+ return classes.includes("clip") ? { classAttr, classes } : null;
+}
+
function collectClipStartBoundariesByComposition(
source: string,
tags: OpenTag[],
@@ -282,9 +295,7 @@ function collectClipStartBoundariesByComposition(
const boundaries = new Map<string, Set<number>>();
for (const tag of tags) {
- const classAttr = readAttr(tag.raw, "class") || "";
- const classes = classAttr.split(/\s+/).filter(Boolean);
- if (!classes.includes("clip")) continue;
+ if (!getClipTagClasses(tag)) continue;
const compositionId = findContainingCompositionId(tag, ranges);
if (!compositionId) continue;
const start = numberValue(readAttr(tag.raw, "data-start") ?? undefined);
@@ -507,6 +518,32 @@ function extractStandaloneGsapTransformCalls(script: string): GsapTransformCall[
return calls;
}
+// Run a global regex over every script's content, yielding each match plus a
+// context-padded snippet around it. Shared by the repeat-count and
+// group-selector-keyframes rules below, which differ only in the pattern,
+// whether comments are stripped first, and the context window size.
+function scanScriptsForRegexMatches(
+ scripts: LintContext["scripts"],
+ pattern: RegExp,
+ options: { stripComments: boolean; contextBefore: number; contextAfter: number },
+): Array<{ match: RegExpExecArray; snippet: string }> {
+ const hits: Array<{ match: RegExpExecArray; snippet: string }> = [];
+ for (const script of scripts) {
+ const content = options.stripComments ? stripJsComments(script.content) : script.content;
+ const regex = new RegExp(pattern.source, pattern.flags);
+ let match: RegExpExecArray | null;
+ while ((match = regex.exec(content)) !== null) {
+ const contextStart = Math.max(0, match.index - options.contextBefore);
+ const contextEnd = Math.min(
+ content.length,
+ match.index + match[0].length + options.contextAfter,
+ );
+ hits.push({ match, snippet: content.slice(contextStart, contextEnd) });
+ }
+ }
+ return hits;
+}
+
// ── GSAP rules ─────────────────────────────────────────────────────────────
// fallow-ignore-next-line complexity
@@ -521,17 +558,16 @@ export const gsapRules: LintRule<LintContext>[] = [
const clipIds = new Map<string, ClipInfo>();
const clipClasses = new Map<string, ClipInfo>();
for (const tag of tags) {
- const classAttr = readAttr(tag.raw, "class") || "";
- const classes = classAttr.split(/\s+/).filter(Boolean);
- if (!classes.includes("clip")) continue;
+ const clipTag = getClipTagClasses(tag);
+ if (!clipTag) continue;
const id = readAttr(tag.raw, "id");
const info: ClipInfo = {
tag: tag.name,
id: id || "",
- classes: classAttr,
+ classes: clipTag.classAttr,
};
if (id) clipIds.set(`#${id}`, info);
- for (const cls of classes) {
+ for (const cls of clipTag.classes) {
if (cls !== "clip") clipClasses.set(`.${cls}`, info);
}
}
@@ -859,8 +895,7 @@ export const gsapRules: LintRule<LintContext>[] = [
// fallow-ignore-next-line complexity
({ scripts, styles }) => {
const findings: HyperframeLintFinding[] = [];
- const isCaptionFile = styles.some((s) => /\.caption[-_]?(?:group|word)/i.test(s.content));
- if (!isCaptionFile) return findings;
+ if (!hasCaptionStyles(styles)) return findings;
for (const script of scripts) {
const content = script.content;
@@ -904,28 +939,25 @@ export const gsapRules: LintRule<LintContext>[] = [
// gsap_infinite_repeat
({ scripts }) => {
const findings: HyperframeLintFinding[] = [];
- for (const script of scripts) {
- const content = stripJsComments(script.content);
- // Match repeat: -1 in GSAP tweens or timeline configs
- const pattern = /repeat\s*:\s*-1(?!\d)/g;
- let match: RegExpExecArray | null;
- while ((match = pattern.exec(content)) !== null) {
- const contextStart = Math.max(0, match.index - 60);
- const contextEnd = Math.min(content.length, match.index + match[0].length + 60);
- const snippet = content.slice(contextStart, contextEnd).trim();
- findings.push({
- code: "gsap_infinite_repeat",
- severity: "error",
- message:
- "GSAP tween uses `repeat: -1` (infinite). Infinite repeats break the deterministic " +
- "capture engine which seeks to exact frame times. Use a finite repeat count calculated " +
- "from the composition duration: `repeat: Math.floor(duration / cycleDuration) - 1`.",
- fixHint:
- "Replace `repeat: -1` with a finite count, e.g. `repeat: Math.floor(totalDuration / singleCycleDuration) - 1`. " +
- "Use Math.floor (not Math.ceil) to ensure the animation fits within the total duration.",
- snippet: truncateSnippet(snippet),
- });
- }
+ // Match repeat: -1 in GSAP tweens or timeline configs
+ const pattern = /repeat\s*:\s*-1(?!\d)/g;
+ for (const { snippet } of scanScriptsForRegexMatches(scripts, pattern, {
+ stripComments: true,
+ contextBefore: 60,
+ contextAfter: 60,
+ })) {
+ findings.push({
+ code: "gsap_infinite_repeat",
+ severity: "error",
+ message:
+ "GSAP tween uses `repeat: -1` (infinite). Infinite repeats break the deterministic " +
+ "capture engine which seeks to exact frame times. Use a finite repeat count calculated " +
+ "from the composition duration: `repeat: Math.floor(duration / cycleDuration) - 1`.",
+ fixHint:
+ "Replace `repeat: -1` with a finite count, e.g. `repeat: Math.floor(totalDuration / singleCycleDuration) - 1`. " +
+ "Use Math.floor (not Math.ceil) to ensure the animation fits within the total duration.",
+ snippet: truncateSnippet(snippet),
+ });
}
return findings;
},
@@ -933,29 +965,26 @@ export const gsapRules: LintRule<LintContext>[] = [
// gsap_repeat_ceil_overshoot
({ scripts }) => {
const findings: HyperframeLintFinding[] = [];
- for (const script of scripts) {
- const content = script.content;
- // Match patterns like: repeat: Math.ceil(duration / X) - 1
- // or repeat: Math.ceil(totalDuration / cycleDuration) - 1
- const pattern = /repeat\s*:\s*Math\.ceil\s*\([^)]+\)\s*-\s*1/g;
- let match: RegExpExecArray | null;
- while ((match = pattern.exec(content)) !== null) {
- const contextStart = Math.max(0, match.index - 40);
- const contextEnd = Math.min(content.length, match.index + match[0].length + 40);
- const snippet = content.slice(contextStart, contextEnd).trim();
- findings.push({
- code: "gsap_repeat_ceil_overshoot",
- severity: "warning",
- message:
- "GSAP repeat calculation uses `Math.ceil` which can overshoot the composition duration. " +
- "For example, Math.ceil(10.5 / 2) - 1 = 5 repeats → 6 cycles × 2s = 12s, exceeding 10.5s.",
- fixHint:
- "Use `Math.floor` instead of `Math.ceil` to ensure the animation fits within the duration: " +
- "`repeat: Math.floor(totalDuration / cycleDuration) - 1`. " +
- "Math.floor(10.5 / 2) - 1 = 4 repeats → 5 cycles × 2s = 10s ✓",
- snippet: truncateSnippet(snippet),
- });
- }
+ // Match patterns like: repeat: Math.ceil(duration / X) - 1
+ // or repeat: Math.ceil(totalDuration / cycleDuration) - 1
+ const pattern = /repeat\s*:\s*Math\.ceil\s*\([^)]+\)\s*-\s*1/g;
+ for (const { snippet } of scanScriptsForRegexMatches(scripts, pattern, {
+ stripComments: false,
+ contextBefore: 40,
+ contextAfter: 40,
+ })) {
+ findings.push({
+ code: "gsap_repeat_ceil_overshoot",
+ severity: "warning",
+ message:
+ "GSAP repeat calculation uses `Math.ceil` which can overshoot the composition duration. " +
+ "For example, Math.ceil(10.5 / 2) - 1 = 5 repeats → 6 cycles × 2s = 12s, exceeding 10.5s.",
+ fixHint:
+ "Use `Math.floor` instead of `Math.ceil` to ensure the animation fits within the duration: " +
+ "`repeat: Math.floor(totalDuration / cycleDuration) - 1`. " +
+ "Math.floor(10.5 / 2) - 1 = 4 repeats → 5 cycles × 2s = 10s ✓",
+ snippet: truncateSnippet(snippet),
+ });
}
return findings;
},
@@ -1009,7 +1038,9 @@ export const gsapRules: LintRule<LintContext>[] = [
for (const script of scripts) {
const content = script.content;
if (!/gsap\.timeline/.test(content)) continue;
- const hasRegistration = WINDOW_TIMELINE_ASSIGN_PATTERN.test(content);
+ const hasRegistration =
+ WINDOW_TIMELINE_ASSIGN_PATTERN.test(content) ||
+ TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN.test(content);
if (hasRegistration || canInheritFromHost) continue;
findings.push({
code: "gsap_timeline_not_registered",
@@ -1126,28 +1157,26 @@ export const gsapRules: LintRule<LintContext>[] = [
// gsap_group_selector_keyframes
({ scripts }) => {
const findings: HyperframeLintFinding[] = [];
- for (const script of scripts) {
- const content = stripJsComments(script.content);
- const pattern = /\.(?:to|from|fromTo)\(\s*["']([^"']+,\s*[^"']+)["']\s*,\s*\{[^}]*keyframes/g;
- let match: RegExpExecArray | null;
- while ((match = pattern.exec(content)) !== null) {
- const selector = match[1]!;
- const count = selector.split(",").length;
- const contextStart = Math.max(0, match.index - 20);
- const contextEnd = Math.min(content.length, match.index + match[0].length + 40);
- findings.push({
- code: "gsap_group_selector_keyframes",
- severity: "warning",
- message:
- `GSAP tween targets ${count} elements with shared keyframes ("${truncateSnippet(selector, 60)}"). ` +
- `Editing one element's keyframes in Studio will affect all ${count} elements. ` +
- `Split into individual tweens for per-element keyframe control.`,
- fixHint:
- `Replace the group selector with individual tl.to() calls per element, ` +
- `each with their own keyframes object.`,
- snippet: truncateSnippet(content.slice(contextStart, contextEnd)),
- });
- }
+ const pattern = /\.(?:to|from|fromTo)\(\s*["']([^"']+,\s*[^"']+)["']\s*,\s*\{[^}]*keyframes/g;
+ for (const { match, snippet } of scanScriptsForRegexMatches(scripts, pattern, {
+ stripComments: true,
+ contextBefore: 20,
+ contextAfter: 40,
+ })) {
+ const selector = match[1]!;
+ const count = selector.split(",").length;
+ findings.push({
+ code: "gsap_group_selector_keyframes",
+ severity: "warning",
+ message:
+ `GSAP tween targets ${count} elements with shared keyframes ("${truncateSnippet(selector, 60)}"). ` +
+ `Editing one element's keyframes in Studio will affect all ${count} elements. ` +
+ `Split into individual tweens for per-element keyframe control.`,
+ fixHint:
+ `Replace the group selector with individual tl.to() calls per element, ` +
+ `each with their own keyframes object.`,
+ snippet: truncateSnippet(snippet),
+ });
}
return findings;
},
diff --git a/packages/lint/src/utils.ts b/packages/lint/src/utils.ts
index 65362db2e9..60296d2f08 100644
--- a/packages/lint/src/utils.ts
+++ b/packages/lint/src/utils.ts
@@ -21,6 +21,11 @@ export const SCRIPT_BLOCK_PATTERN = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
const COMPOSITION_ID_IN_CSS_PATTERN = /\[data-composition-id=["']([^"']+)["']\]/g;
export const TIMELINE_REGISTRY_INIT_PATTERN =
/window\.__timelines\s*=\s*window\.__timelines\s*\|\|\s*\{\}|window\.__timelines\s*=\s*\{\}|window\.__timelines\s*\?\?=\s*\{\}/i;
+// Object-literal registration that assigns at least one `key: value` entry inline,
+// e.g. `window.__timelines = { main: tl }` or `window.__timelines = { "comp-1": tl }`.
+// Distinct from the empty-init form (`= {}`) — requires a key followed by `:`.
+export const TIMELINE_REGISTRY_OBJECT_LITERAL_PATTERN =
+ /window\.__timelines\s*=\s*\{\s*(?:["'][^"']+["']|[A-Za-z_$][\w$]*)\s*:/i;
export const TIMELINE_REGISTRY_ASSIGN_PATTERN =
/window\.__timelines(?:\[[^\]]+\]|\.[A-Za-z_$][\w$]*)\s*=/i;
export const WINDOW_TIMELINE_ASSIGN_PATTERN =
@@ -30,6 +35,14 @@ export const INVALID_SCRIPT_CLOSE_PATTERN = /<script[^>]*>[\s\S]*?<\s*\/\s*scrip
const TIMELINE_REGISTRY_KEY_PATTERN =
/window\.__timelines(?:\[\s*["']([^"']+)["']\s*\]|\.\s*([A-Za-z_$][\w$]*))\s*=/g;
+// The `window.__timelines = { ... }` object-literal body (group 1), captured so its
+// `key: value` entries can be scanned for registered keys.
+const TIMELINE_REGISTRY_OBJECT_BODY_PATTERN = /window\.__timelines\s*=\s*\{([\s\S]*?)\}/i;
+// A single object-literal entry whose value is an identifier (real timeline registration),
+// e.g. `main: tl` or `"comp-1": tl`. Captures the key in group 1 (quoted) or 2 (bare).
+const TIMELINE_REGISTRY_OBJECT_ENTRY_PATTERN =
+ /(?:["']([^"']+)["']|([A-Za-z_$][\w$]*))\s*:\s*[A-Za-z_$][\w$]*/g;
+
export function extractOpenTags(source: string): OpenTag[] {
const tags: OpenTag[] = [];
let match: RegExpExecArray | null;
@@ -177,6 +190,17 @@ export function extractTimelineRegistryKeys(source: string): string[] {
const key = match[1] ?? match[2];
if (key) keys.add(key);
}
+ const objectBody = TIMELINE_REGISTRY_OBJECT_BODY_PATTERN.exec(source)?.[1];
+ if (objectBody) {
+ const entryPattern = new RegExp(
+ TIMELINE_REGISTRY_OBJECT_ENTRY_PATTERN.source,
+ TIMELINE_REGISTRY_OBJECT_ENTRY_PATTERN.flags,
+ );
+ while ((match = entryPattern.exec(objectBody)) !== null) {
+ const key = match[1] ?? match[2];
+ if (key) keys.add(key);
+ }
+ }
return [...keys];
}
@@ -300,6 +324,13 @@ export function isMediaTag(tagName: string): boolean {
return tagName === "video" || tagName === "audio" || tagName === "img";
}
+// Whether any <style> block in the composition defines caption group/word
+// classes (`.caption-group`, `.caption_word`, etc.) — the signal several
+// caption-specific rules use to skip non-caption compositions entirely.
+export function hasCaptionStyles(styles: ExtractedBlock[]): boolean {
+ return styles.some((s) => /\.caption[-_]?(?:group|word)/i.test(s.content));
+}
+
export function truncateSnippet(value: string, maxLength = 220): string | undefined {
const normalized = value.replace(/\s+/g, " ").trim();
if (!normalized) return undefined;
diff --git a/packages/parsers/src/__goldens__/complex.parsed.json b/packages/parsers/src/__goldens__/complex.parsed.json
index af592ef9dd..d1032f39b9 100644
--- a/packages/parsers/src/__goldens__/complex.parsed.json
+++ b/packages/parsers/src/__goldens__/complex.parsed.json
@@ -14,6 +14,27 @@
"stagger": "__raw:0.055"
},
"resolvedStart": 0.05,
+ "keyframes": {
+ "format": "percentage",
+ "keyframes": [
+ {
+ "percentage": 0,
+ "properties": {
+ "y": 46,
+ "opacity": 0,
+ "stagger": 0.055
+ }
+ },
+ {
+ "percentage": 100,
+ "properties": {
+ "y": 0,
+ "opacity": 1,
+ "stagger": 0.055
+ }
+ }
+ ]
+ },
"id": ".headline span-from-50"
},
{
@@ -56,6 +77,27 @@
"stagger": "__raw:0.08"
},
"resolvedStart": 0.16,
+ "keyframes": {
+ "format": "percentage",
+ "keyframes": [
+ {
+ "percentage": 0,
+ "properties": {
+ "scaleX": 0,
+ "opacity": 0,
+ "stagger": 0.08
+ }
+ },
+ {
+ "percentage": 100,
+ "properties": {
+ "scaleX": 1,
+ "opacity": 1,
+ "stagger": 0.08
+ }
+ }
+ ]
+ },
"id": ".ambient-line-from-160"
}
],
diff --git a/packages/parsers/src/__goldens__/minimal.parsed.json b/packages/parsers/src/__goldens__/minimal.parsed.json
index cbfa33de9a..6daf5e7fb1 100644
--- a/packages/parsers/src/__goldens__/minimal.parsed.json
+++ b/packages/parsers/src/__goldens__/minimal.parsed.json
@@ -8,6 +8,10 @@
"x": 0,
"opacity": 1
},
+ "fromProperties": {
+ "x": 420,
+ "opacity": 0
+ },
"duration": 0.5,
"ease": "power3.out",
"resolvedStart": 0.2,
@@ -21,6 +25,10 @@
"x": 420,
"opacity": 0
},
+ "fromProperties": {
+ "x": 0,
+ "opacity": 1
+ },
"duration": 0.3,
"ease": "power3.in",
"resolvedStart": 4.2,
diff --git a/packages/parsers/src/__goldens__/moderate.parsed.json b/packages/parsers/src/__goldens__/moderate.parsed.json
index 8edb3f3506..8d269daf0f 100644
--- a/packages/parsers/src/__goldens__/moderate.parsed.json
+++ b/packages/parsers/src/__goldens__/moderate.parsed.json
@@ -8,6 +8,10 @@
"y": 0,
"opacity": 1
},
+ "fromProperties": {
+ "y": 300,
+ "opacity": 0
+ },
"duration": 0.5,
"ease": "power3.out",
"resolvedStart": 0.1,
@@ -33,6 +37,9 @@
"properties": {
"scale": 1
},
+ "fromProperties": {
+ "scale": 0.92
+ },
"duration": 0.4,
"ease": "elastic.out(1, 0.4)",
"propertyGroup": "scale",
@@ -73,6 +80,10 @@
"y": 300,
"opacity": 0
},
+ "fromProperties": {
+ "y": 0,
+ "opacity": 1
+ },
"duration": 0.25,
"ease": "power3.in",
"resolvedStart": 3.8,
diff --git a/packages/parsers/src/gsapParserAcorn.ts b/packages/parsers/src/gsapParserAcorn.ts
index 94c88e887c..a8536132bf 100644
--- a/packages/parsers/src/gsapParserAcorn.ts
+++ b/packages/parsers/src/gsapParserAcorn.ts
@@ -50,6 +50,93 @@ type ScopeBindings = ReadonlyMap<string, number | string | boolean>;
/** Per-scope element bindings: scopeNode → (variable name → selector). */
type TargetBindings = Map<any, Map<string, string>>;
+/**
+ * Side-table of top-level const/let ARRAY and OBJECT literals (of literals),
+ * captured by `collectScopeBindings` and stashed on the scope Map so that
+ * `resolveNode` can fold member access (`H.bar0`) and computed array index
+ * (`SPARK[0][1]`) without changing the resolveNode signature at its ~15 call
+ * sites. ponytail: hidden prop on the Map beats threading a new param everywhere.
+ */
+const CONST_NODES = Symbol("hf.constNodes");
+type ConstNodes = Map<string, any>;
+
+function constNodesOf(
+ scope: ReadonlyMap<string, number | string | boolean>,
+): ConstNodes | undefined {
+ return (scope as any)[CONST_NODES];
+}
+
+/** Whitelisted Math members we fold over constant args (deterministic, no I/O). */
+const MATH_FNS = new Set(["min", "max", "round", "floor", "ceil", "abs", "sqrt", "sign", "trunc"]);
+const MATH_CONSTS: Record<string, number> = { PI: Math.PI, E: Math.E, SQRT2: Math.SQRT2 };
+
+/**
+ * Fold a MemberExpression (`obj.prop`, `arr[i]`, `Math.PI`, `Math.round(x)`)
+ * against the const-node side-table. Returns undefined when not statically
+ * resolvable (genuinely runtime-dynamic) so the caller falls back to __raw.
+ */
+// fallow-ignore-next-line complexity
+function resolveMemberNode(
+ node: any,
+ scope: ReadonlyMap<string, number | string | boolean>,
+): number | string | boolean | undefined {
+ // Math.PI / Math.E
+ if (node.object?.type === "Identifier" && node.object.name === "Math") {
+ const key = node.property?.name;
+ return typeof key === "string" ? MATH_CONSTS[key] : undefined;
+ }
+ // Resolve the object to a const AST node (array/object literal), descending
+ // through chained member/index access (SPARK[0][1], H.bar0).
+ const objNode = resolveConstNode(node.object, scope);
+ if (!objNode) return undefined;
+ let valueNode: any;
+ if (node.computed) {
+ const idx = resolveNode(node.property, scope);
+ if (objNode.type === "ArrayExpression" && typeof idx === "number") {
+ valueNode = objNode.elements?.[idx];
+ } else if (
+ objNode.type === "ObjectExpression" &&
+ (typeof idx === "string" || typeof idx === "number")
+ ) {
+ valueNode = findPropertyNode(objNode, String(idx));
+ }
+ } else if (objNode.type === "ObjectExpression") {
+ valueNode = findPropertyNode(objNode, node.property?.name ?? node.property?.value);
+ }
+ return valueNode ? resolveNode(valueNode, scope) : undefined;
+}
+
+/**
+ * Descend one MemberExpression step into an already-resolved const ARRAY/OBJECT
+ * node (`objNode[idx]` / `objNode.prop`). Split out of resolveConstNode so the
+ * recursive walk stays flat/low-branch.
+ */
+function resolveConstMember(
+ objNode: any,
+ node: any,
+ scope: ReadonlyMap<string, number | string | boolean>,
+): any {
+ if (!node.computed) {
+ return objNode.type === "ObjectExpression"
+ ? findPropertyNode(objNode, node.property?.name ?? node.property?.value)
+ : undefined;
+ }
+ const idx = resolveNode(node.property, scope);
+ if (objNode.type === "ArrayExpression" && typeof idx === "number") return objNode.elements?.[idx];
+ if (objNode.type === "ObjectExpression") return findPropertyNode(objNode, String(idx));
+ return undefined;
+}
+
+/** Resolve an expression to a const ARRAY/OBJECT AST node (for nested access). */
+function resolveConstNode(node: any, scope: ReadonlyMap<string, number | string | boolean>): any {
+ if (!node) return undefined;
+ if (node.type === "ArrayExpression" || node.type === "ObjectExpression") return node;
+ if (node.type === "Identifier") return constNodesOf(scope)?.get(node.name);
+ if (node.type !== "MemberExpression") return undefined;
+ const objNode = resolveConstNode(node.object, scope);
+ return objNode ? resolveConstMember(objNode, node, scope) : undefined;
+}
+
// ── Value resolution ─────────────────────────────────────────────────────────
// fallow-ignore-next-line complexity
@@ -95,6 +182,22 @@ function resolveNode(
if (node.type === "TemplateLiteral" && node.expressions?.length === 0) {
return node.quasis?.[0]?.value?.cooked ?? undefined;
}
+ if (node.type === "MemberExpression") {
+ return resolveMemberNode(node, scope);
+ }
+ // Whitelisted Math.fn(...) over constant args (Math.round/min/max/...).
+ if (
+ node.type === "CallExpression" &&
+ node.callee?.type === "MemberExpression" &&
+ node.callee.object?.type === "Identifier" &&
+ node.callee.object.name === "Math" &&
+ MATH_FNS.has(node.callee.property?.name)
+ ) {
+ const args = (node.arguments ?? []).map((a: any) => resolveNode(a, scope));
+ if (args.every((a: unknown) => typeof a === "number")) {
+ return (Math as any)[node.callee.property.name](...(args as number[]));
+ }
+ }
return undefined;
}
@@ -193,14 +296,21 @@ function resolveCollectionSelector(
function collectScopeBindings(ast: any): ScopeBindings {
const bindings = new Map<string, number | string | boolean>();
+ // Const ARRAY/OBJECT literals are kept as AST nodes for member/index folding
+ // (resolveMemberNode), exposed to resolveNode via the CONST_NODES side-table.
+ const constNodes: ConstNodes = new Map();
+ Object.defineProperty(bindings, CONST_NODES, { value: constNodes, enumerable: false });
acornWalk.simple(ast, {
VariableDeclarator(node: any) {
const name = node.id?.name;
const init = node.init;
- if (name && init) {
- const val = resolveNode(init, bindings);
- if (val !== undefined) bindings.set(name, val);
+ if (!name || !init) return;
+ if (init.type === "ArrayExpression" || init.type === "ObjectExpression") {
+ constNodes.set(name, init);
+ return;
}
+ const val = resolveNode(init, bindings);
+ if (val !== undefined) bindings.set(name, val);
},
});
return bindings;
@@ -256,6 +366,40 @@ function collectTargetBindings(ast: any, scope: ScopeBindings): TargetBindings {
},
} as any);
+ // Pass 3: collection ALIASES inherit their source collection's selector.
+ // `const lead = glyphs[0]`, `const rest = glyphs.slice(1)`,
+ // `const some = glyphs.filter(...)` all still target the same selector
+ // (`.glyph`). Per-element identity isn't statically recoverable (DOM-sized
+ // collection), but the selector + stagger should not read as __unresolved__.
+ const COLLECTION_ALIAS_METHODS = new Set(["slice", "filter", "concat", "reverse"]);
+ acornWalk.ancestor(ast, {
+ // fallow-ignore-next-line complexity
+ VariableDeclarator(node: any, _: unknown, ancestors: any[]) {
+ const name = node.id?.name;
+ const init = node.init;
+ if (!name || !init) return;
+ let sourceVar: string | undefined;
+ // x = coll[i]
+ if (init.type === "MemberExpression" && init.object?.type === "Identifier") {
+ sourceVar = init.object.name;
+ }
+ // x = coll.slice(...) / coll.filter(...)
+ else if (
+ init.type === "CallExpression" &&
+ init.callee?.type === "MemberExpression" &&
+ init.callee.object?.type === "Identifier" &&
+ init.callee.property?.type === "Identifier" &&
+ COLLECTION_ALIAS_METHODS.has(init.callee.property.name)
+ ) {
+ sourceVar = init.callee.object.name;
+ }
+ if (!sourceVar) return;
+ const selector = lookupBindingFromAncestors(sourceVar, ancestors, bindings);
+ if (selector)
+ addBinding(bindings, enclosingScopeNodeFromAncestors(ancestors), name, selector);
+ },
+ } as any);
+
return bindings;
}
@@ -288,6 +432,66 @@ function resolveTargetSelector(
return null;
}
+/**
+ * Classify an otherwise-unresolved tween target that is a plain object literal
+ * (`tl.to({}, …)`) or a proxy object (`tl.to(s, {onUpdate})`). Returns a
+ * descriptive pseudo-selector or null when the target isn't an object proxy.
+ *
+ * - Empty object literal → "dwell/hold" (a timing-only spacer tween, #11).
+ * - Proxy with onUpdate that writes a DOM attribute/style → "proxy → <attr>"
+ * (best-effort #5; the channel name is parsed from the onUpdate body).
+ */
+function describeProxyTarget(targetNode: any, varsNode: any, scope: ScopeBindings): string | null {
+ // Resolve an Identifier proxy (const s = {u:0}) to its object literal.
+ const objNode =
+ targetNode?.type === "ObjectExpression"
+ ? targetNode
+ : targetNode?.type === "Identifier"
+ ? resolveConstNode(targetNode, scope)
+ : undefined;
+ if (objNode?.type !== "ObjectExpression") return null;
+
+ const onUpdate = findPropertyNode(varsNode, "onUpdate");
+ const driven = onUpdate ? drivenDomChannel(onUpdate) : undefined;
+ if (driven) return `proxy → ${driven}`;
+ // Empty / proxy object with no resolvable DOM write ⇒ a timing spacer.
+ return "dwell/hold";
+}
+
+/** True for `el.style.foo = …` (nested-member style write). */
+function isStyleAssignmentTarget(left: any): boolean {
+ return (
+ left?.type === "MemberExpression" &&
+ left.object?.type === "MemberExpression" &&
+ left.object.property?.name === "style" &&
+ !!left.property?.name
+ );
+}
+
+/** Best-effort: find the DOM attribute/style channel an onUpdate body writes. */
+// fallow-ignore-next-line complexity
+function drivenDomChannel(fnNode: any): string | undefined {
+ let found: string | undefined;
+ acornWalk.simple(fnNode, {
+ CallExpression(node: any) {
+ // setAttribute("d" | "points" | "stroke-dashoffset", …)
+ if (
+ node.callee?.type === "MemberExpression" &&
+ node.callee.property?.name === "setAttribute" &&
+ typeof node.arguments?.[0]?.value === "string"
+ ) {
+ found ??= node.arguments[0].value;
+ }
+ },
+ AssignmentExpression(node: any) {
+ // el.style.foo = … / el.setAttribute-less style writes
+ const left = node.left;
+ if (isStyleAssignmentTarget(left)) found ??= `style.${left.property.name}`;
+ },
+ });
+ return found;
+}
+
// ── ObjectExpression utilities ────────────────────────────────────────────────
function isObjectProperty(prop: any): boolean {
@@ -359,26 +563,27 @@ interface TimelineDefaults {
}
// How the timeline is referred to in source. `identifier` is the canonical
-// `const tl = …` form; `member` is the inline `window.__timelines["scene"] = …`
-// form, where the timeline IS the member expression (no variable name).
+// `const tl = ...` form; `member` is the inline
+// `window.__timelines["scene"] = ...` form, where the timeline is the member
+// expression itself.
type TimelineRef = { kind: "identifier"; name: string } | { kind: "member"; node: any };
interface TimelineDetection {
- /** Identifier name for the canonical form, else null (member or none). */
+ /** Identifier name for the canonical form, else null for member/none. */
timelineVar: string | null;
- /** Structural reference: identifier OR member expression. Null when none found. */
+ /** Structural reference: identifier or member expression. Null when none found. */
ref: TimelineRef | null;
timelineCount: number;
defaults?: TimelineDefaults;
}
-/** The static string key of a member access (`window.__timelines["scene"]` → "scene"), else null. */
+/** The static string key of a member access (`window.__timelines["scene"]` -> "scene"), else null. */
function staticMemberKey(node: any): string | null {
if (!node || node.type !== "MemberExpression") return null;
if (node.computed) {
const p = node.property;
if (p?.type === "Literal" && typeof p.value === "string") return p.value;
- return null; // computed non-string-literal key → not statically resolvable
+ return null;
}
return node.property?.type === "Identifier" ? node.property.name : null;
}
@@ -534,9 +739,9 @@ function findAllTweenCalls(
// Fire BEFORE children (pre-order) so chained outer calls come first.
if (node.type === "CallExpression") {
const callee = node.callee;
- // A base `gsap.set("#sel", props)` is an off-timeline static hold — parse it as
- // an editable global `set` so a static value round-trips and re-edits in place.
- // STRING-LITERAL selectors only: variable-target holds stay surrounding source.
+ // A base `gsap.set("#sel", props)` is an off-timeline static hold. Parse
+ // it as an editable global `set` so static values round-trip and re-edit
+ // in place. Variable-target holds stay surrounding source.
const gsapSetArg = node.arguments?.[0];
const isGlobalSet =
callee?.type === "MemberExpression" &&
@@ -974,8 +1179,16 @@ function tweenCallToAnimation(
duration = computeKeyframesTotalDuration(call.varsArg, scope, source);
}
+ // Relabel object-proxy / empty-target tweens so they don't read as bare
+ // __unresolved__: a dwell/hold spacer or an onUpdate-driven DOM channel (#5/#11).
+ let selector = call.selector;
+ if (selector === "__unresolved__") {
+ const proxyLabel = describeProxyTarget(call.node.arguments?.[0], call.varsArg, scope);
+ if (proxyLabel) selector = proxyLabel;
+ }
+
const anim: Omit<GsapAnimation, "id"> = {
- targetSelector: call.selector,
+ targetSelector: selector,
method: call.method,
position,
properties,
@@ -998,12 +1211,88 @@ function tweenCallToAnimation(
if (keyframesData) anim.keyframes = keyframesData;
if (motionPathResult) anim.arcPath = motionPathResult.arcPath;
if (hasUnresolvedKeyframes) anim.hasUnresolvedKeyframes = true;
- if (call.selector === "__unresolved__") anim.hasUnresolvedSelector = true;
+ if (selector === "__unresolved__") anim.hasUnresolvedSelector = true;
const provenance = readProvenance(call.node);
if (provenance) anim.provenance = provenance;
return anim;
}
+// ── Stagger annotation (read path) ────────────────────────────────────────────
+
+/**
+ * Pull the per-element stagger amount out of a captured `extras.stagger` value.
+ * GSAP staggers are either a number (`0.08`) or an object (`{ each: 0.012, ... }`).
+ * The value arrives here as the round-trip form `__raw:<source>`; we only need
+ * the leading numeric / `each:` figure for the annotation. Returns undefined for
+ * non-numeric (function) staggers — there's nothing honest to print.
+ */
+function staggerAmount(raw: unknown): number | undefined {
+ if (typeof raw === "number") return raw;
+ if (typeof raw !== "string") return undefined;
+ const src = raw.startsWith("__raw:") ? raw.slice(6) : raw;
+ const m = /(?:each\s*:\s*)?(-?\d+(?:\.\d+)?)/.exec(src);
+ if (!m) return undefined;
+ const n = Number.parseFloat(m[1]!);
+ return Number.isFinite(n) ? n : undefined;
+}
+
+/** Rest-pose value GSAP animates to/from for an unspecified endpoint. */
+function restValue(prop: string): number {
+ return prop === "opacity" || prop.startsWith("scale") ? 1 : 0;
+}
+
+/**
+ * Honest from/to keyframes for a flat staggered tween, mirroring how a flat
+ * tween renders: `from()` plays vars -> rest, `to()` plays rest -> vars, `fromTo`
+ * plays its authored endpoints. A synthetic `stagger` channel rides on both
+ * keyframes so the per-element cascade is visible even when the tween lands on
+ * the rest pose (a 1->1 collection that would otherwise read as a no-op).
+ */
+function staggeredKeyframes(
+ anim: Omit<GsapAnimation, "id">,
+ each: number,
+): GsapPercentageKeyframe[] {
+ const vars = { ...anim.properties };
+ let from: Record<string, number | string>;
+ let to: Record<string, number | string>;
+ if (anim.method === "fromTo") {
+ from = { ...(anim.fromProperties ?? {}) };
+ to = vars;
+ } else if (anim.method === "from") {
+ from = vars;
+ to = {};
+ for (const k of Object.keys(vars)) to[k] = restValue(k);
+ } else {
+ from = { ...(anim.fromProperties ?? {}) };
+ for (const k of Object.keys(vars)) if (from[k] === undefined) from[k] = restValue(k);
+ to = vars;
+ }
+ return [
+ { percentage: 0, properties: { ...from, stagger: each } },
+ { percentage: 100, properties: { ...to, stagger: each } },
+ ];
+}
+
+/**
+ * Read-path honesty pass: a tween with a `stagger` targets a per-element
+ * collection that animates one element at a time. A flat staggered tween that
+ * lands on (or starts from) the rest pose otherwise renders as a misleading
+ * X->X no-op. Surface real from/to keyframes plus the per-element `stagger`
+ * amount so the reader can tell the collection DOES animate and roughly how.
+ *
+ * Read path only — the write/serialize path ignores `keyframes` and keeps the
+ * literal `extras.stagger` source, so round-trips are untouched. Keyframed /
+ * motionPath tweens already surface their motion, so they're left alone.
+ */
+function annotateStaggeredCollections(anims: Omit<GsapAnimation, "id">[]): void {
+ for (const anim of anims) {
+ if (anim.keyframes || anim.arcPath) continue;
+ const each = staggerAmount(anim.extras?.stagger);
+ if (each === undefined) continue;
+ anim.keyframes = { format: "percentage", keyframes: staggeredKeyframes(anim, each) };
+ }
+}
+
// ── Timeline position resolution ─────────────────────────────────────────────
const GSAP_DEFAULT_DURATION = 0.5;
@@ -1034,6 +1323,104 @@ function resolvePositionString(pos: string, cursor: number, prevStart: number):
return Number.isFinite(n) ? n : null;
}
+// ── set() pre-state seeding (#3 in eval) ──────────────────────────────────────
+
+/**
+ * Collect `gsap.set(target, {prop: v})` calls into selector → {prop: value}.
+ * These run before the (paused) timeline builds, establishing the initial DOM
+ * state. tl.set(...) calls are already in the animation list, so they're folded
+ * in during the seeding walk instead.
+ */
+function collectGsapSetStates(
+ ast: any,
+ scope: ScopeBindings,
+ bindings: TargetBindings,
+ source: string,
+): Map<string, Record<string, number | string>> {
+ const states = new Map<string, Record<string, number | string>>();
+ acornWalk.ancestor(ast, {
+ // fallow-ignore-next-line complexity
+ CallExpression(node: any, _: unknown, ancestors: any[]) {
+ const callee = node.callee;
+ if (
+ callee?.type !== "MemberExpression" ||
+ callee.object?.name !== "gsap" ||
+ callee.property?.name !== "set"
+ )
+ return;
+ const selector = resolveTargetSelector(node.arguments?.[0], ancestors, scope, bindings);
+ if (!selector) return;
+ const rec = objectExpressionToRecord(node.arguments?.[1], scope, source);
+ const props: Record<string, number | string> = states.get(selector) ?? {};
+ for (const [k, v] of Object.entries(rec)) {
+ if (typeof v === "number" || typeof v === "string") props[k] = v;
+ }
+ states.set(selector, props);
+ },
+ } as any);
+ return states;
+}
+
+/**
+ * Seed each tween's start keyframe from the most recent set() value on the same
+ * target. Without this, `set(scaleY:0)` then `.to(scaleY:1)` reports the CSS
+ * default as the start, so a grow/fold/fade-from reads as a flat no-op.
+ *
+ * Walks animations in timeline order, tracking per-target current state from
+ * gsap.set() (pre-seeded) and tl.set() tweens. For a later to/from tween that
+ * lacks an explicit from-value for an animated prop, the tracked set() value
+ * becomes its from-keyframe.
+ */
+/** Overwrite `target` in place with `props`, returning it (for Map.set chaining). */
+function mergeProps(
+ target: Record<string, number | string>,
+ props: Record<string, number | string>,
+): Record<string, number | string> {
+ for (const [k, v] of Object.entries(props)) target[k] = v;
+ return target;
+}
+
+/**
+ * Fill in `anim.fromProperties` for a `.to()` tween's props that lack an
+ * explicit start, from the tracked pre-tween state. Mutates `anim` only when
+ * at least one prop is actually seeded.
+ */
+function seedFromPreState(
+ anim: Omit<GsapAnimation, "id">,
+ cur: Record<string, number | string>,
+): void {
+ const from = { ...(anim.fromProperties ?? {}) };
+ let seeded = false;
+ for (const prop of Object.keys(anim.properties)) {
+ if (from[prop] === undefined && cur[prop] !== undefined) {
+ from[prop] = cur[prop];
+ seeded = true;
+ }
+ }
+ if (seeded) anim.fromProperties = from;
+}
+
+function seedSetStates(
+ anims: Omit<GsapAnimation, "id">[],
+ initial: Map<string, Record<string, number | string>>,
+): void {
+ const state = new Map<string, Record<string, number | string>>();
+ for (const [sel, props] of initial) state.set(sel, { ...props });
+
+ for (const anim of anims) {
+ const sel = anim.targetSelector;
+ if (anim.method === "set") {
+ state.set(sel, mergeProps(state.get(sel) ?? {}, anim.properties));
+ continue;
+ }
+ // fromTo authors its own start explicitly — don't override it.
+ const cur = state.get(sel);
+ if (anim.method === "to" && cur) seedFromPreState(anim, cur);
+ // After a to/from tween, the target's state is the tween's END values.
+ state.set(sel, mergeProps(state.get(sel) ?? {}, anim.properties));
+ }
+}
+
function applyTimelineDefaults(
anims: Omit<GsapAnimation, "id">[],
defaults?: TimelineDefaults,
@@ -1050,38 +1437,157 @@ function applyTimelineDefaults(
}
}
-// fallow-ignore-next-line complexity
-function resolveTimelinePositions(anims: Omit<GsapAnimation, "id">[]): void {
+/** A source-ordered addLabel(name, position) definition. */
+interface AddLabelDef {
+ name: string;
+ /** Raw position string/number, or undefined ⇒ label sits at current end. */
+ position: string | number | undefined;
+ /** Source-order key (parallel to anims), for interleaving. */
+ order: number;
+}
+
+/**
+ * Resolve a label-relative position string against a live label table.
+ * Handles "label", "label+=n", "label-=n". Unknown labels auto-create at the
+ * current playhead (cursor) — GSAP's behavior when a tween references a label
+ * that hasn't been added yet. Returns null when not a label form.
+ */
+function resolveLabelPosition(
+ pos: string,
+ labels: Map<string, number>,
+ cursor: number,
+): number | null {
+ const m = /^([A-Za-z_$][\w$]*)\s*(?:([+-])=\s*([\d.]+))?$/.exec(pos.trim());
+ if (!m) return null;
+ const name = m[1]!;
+ let base = labels.get(name);
+ if (base === undefined) {
+ base = cursor; // auto-create label at the current end-of-timeline
+ labels.set(name, base);
+ }
+ if (m[2] && m[3]) {
+ const n = Number.parseFloat(m[3]);
+ if (Number.isFinite(n)) return m[2] === "+" ? base + n : base - n;
+ }
+ return base;
+}
+
+/** Resolve a single tween's unresolved start time against the live cursor/labels. */
+function resolveAnimStart(
+ anim: Omit<GsapAnimation, "id">,
+ cursor: number,
+ prevStart: number,
+ labels: Map<string, number>,
+): number | null {
+ if (anim.implicitPosition) return cursor;
+ if (typeof anim.position === "number") return anim.position;
+ if (typeof anim.position === "string") {
+ return (
+ resolveLabelPosition(anim.position, labels, cursor) ??
+ resolvePositionString(anim.position, cursor, prevStart)
+ );
+ }
+ return cursor;
+}
+
+function resolveTimelinePositions(
+ anims: Omit<GsapAnimation, "id">[],
+ labelDefs: AddLabelDef[] = [],
+): void {
let cursor = 0;
let prevStart = 0;
- for (const anim of anims) {
- // A global `gsap.set(...)` is off-timeline — applied once at load, not
- // sequenced on the master timeline. It carries no position arg, so the
- // cursor fallback would otherwise hand it the comp-end time. Pin it to 0
- // (its load-time start) and don't advance the cursor/prevStart.
+ const labels = new Map<string, number>();
+ // Interleave addLabel definitions with tweens by source order so labels are
+ // available exactly when later tweens reference them.
+ let labelIdx = 0;
+ const sortedLabels = [...labelDefs].sort((a, b) => a.order - b.order);
+
+ const defineLabel = (def: AddLabelDef): void => {
+ let value: number;
+ if (typeof def.position === "number") value = def.position;
+ else if (typeof def.position === "string") {
+ value = resolveLabelPosition(def.position, labels, cursor) ?? cursor;
+ } else value = cursor; // no position ⇒ end of timeline
+ labels.set(def.name, Math.max(0, value));
+ };
+
+ anims.forEach((anim, i) => {
+ // Apply any addLabel calls authored before this tween.
+ while (labelIdx < sortedLabels.length && sortedLabels[labelIdx]!.order <= i) {
+ defineLabel(sortedLabels[labelIdx]!);
+ labelIdx++;
+ }
+
+ // A global `gsap.set(...)` is off-timeline: applied once at load, not
+ // sequenced on the master timeline. It has no position arg, so pin it to 0
+ // and do not advance the cursor.
if (anim.method === "set" && anim.global) {
anim.resolvedStart = 0;
- continue;
+ return;
}
+
const duration = anim.method === "set" ? 0 : (anim.duration ?? GSAP_DEFAULT_DURATION);
- let start: number | null;
-
- if (anim.implicitPosition) {
- start = cursor;
- } else if (typeof anim.position === "number") {
- start = anim.position;
- } else if (typeof anim.position === "string") {
- start = resolvePositionString(anim.position, cursor, prevStart);
- } else {
- start = cursor;
- }
+ const start = resolveAnimStart(anim, cursor, prevStart, labels);
if (start != null) {
anim.resolvedStart = Math.max(0, start);
prevStart = anim.resolvedStart;
cursor = Math.max(cursor, anim.resolvedStart + duration);
}
- }
+ });
+
+ // Any trailing addLabel calls (define for completeness; no tweens follow).
+ while (labelIdx < sortedLabels.length) defineLabel(sortedLabels[labelIdx++]!);
+}
+
+/**
+ * Collect `tl.addLabel(name, position)` calls and compute each one's `order` —
+ * the count of tween calls that precede it in source order — so positions can
+ * be interleaved against the sorted animation list in resolveTimelinePositions.
+ */
+function collectAddLabelDefs(
+ ast: any,
+ ref: TimelineRef,
+ scope: ScopeBindings,
+ sortedCalls: TweenCallInfo[],
+): AddLabelDef[] {
+ const callLocs = sortedCalls.map((c) => c.node.callee?.property?.loc?.start);
+ const defs: AddLabelDef[] = [];
+ acornWalk.simple(ast, {
+ // fallow-ignore-next-line complexity
+ CallExpression(node: any) {
+ const callee = node.callee;
+ const objMatches =
+ ref.kind === "identifier"
+ ? callee.object?.type === "Identifier" && callee.object.name === ref.name
+ : sameMemberAccess(callee.object, ref.node);
+ if (
+ callee?.type !== "MemberExpression" ||
+ !objMatches ||
+ callee.property?.name !== "addLabel"
+ )
+ return;
+ const nameNode = node.arguments?.[0];
+ const name = typeof nameNode?.value === "string" ? nameNode.value : undefined;
+ if (!name) return;
+ // position may be numeric, a label-relative string, or omitted.
+ const posVal = resolveNode(node.arguments?.[1], scope);
+ const position =
+ typeof posVal === "number" || typeof posVal === "string" ? posVal : undefined;
+ const labelLoc = callee.property?.loc?.start;
+ let order = sortedCalls.length;
+ if (labelLoc) {
+ order = callLocs.findIndex(
+ (l) =>
+ l &&
+ (l.line > labelLoc.line || (l.line === labelLoc.line && l.column > labelLoc.column)),
+ );
+ if (order === -1) order = sortedCalls.length;
+ }
+ defs.push({ name, position, order });
+ },
+ });
+ return defs;
}
function compareByLoc(a: TweenCallInfo, b: TweenCallInfo): number {
@@ -1186,8 +1692,8 @@ export function parseGsapScriptAcorn(script: string): ParsedGsap {
// Expand helper-built / bounded-loop timelines before analysis so their
// tweens resolve at true positions (read path only — the write path keeps
// original source nodes). Degrades to the un-inlined AST on any failure.
- // Only the identifier form uses the helper-built pattern; inline member
- // timelines have nothing to inline, so skip (avoids mis-rooting on the member).
+ // Only identifier timelines use the helper-built pattern; inline member
+ // timelines have nothing to inline, so skip to avoid mis-rooting on member refs.
if (ref.kind === "identifier") {
try {
inlineComputedTimelines(ast, timelineVar, (node) => resolveNode(node, scope));
@@ -1200,12 +1706,17 @@ export function parseGsapScriptAcorn(script: string): ParsedGsap {
sortBySourcePosition(calls);
const rawAnims = calls.map((call) => tweenCallToAnimation(call, scope, script));
applyTimelineDefaults(rawAnims, detection.defaults);
- resolveTimelinePositions(rawAnims);
+ // Seed tween start-keyframes from gsap.set()/tl.set() pre-states (read-only
+ // enrichment; the write path keeps source untouched for round-trip parity).
+ seedSetStates(rawAnims, collectGsapSetStates(ast, scope, targetBindings, script));
+ const labelDefs = collectAddLabelDefs(ast, ref, scope, calls);
+ resolveTimelinePositions(rawAnims, labelDefs);
+ // Honesty pass (read path only): make staggered collection tweens read as
+ // real per-element motion instead of a flat no-op. Done after positions so
+ // duration is settled; before ids so the annotation is part of the id.
+ annotateStaggeredCollections(rawAnims);
const animations = assignStableIds(rawAnims);
- // Preamble = source up to and including the timeline declaration/assignment.
- // Identifier keeps the original `const|let|var <name> = …` regex (byte-stable);
- // member matches `<member source> = …`.
const declPattern =
ref.kind === "identifier"
? `(?:const|let|var)\\s+${timelineVar}\\s*=\\s*gsap\\.timeline\\s*\\([^)]*\\)\\s*;?`
diff --git a/skills-manifest.json b/skills-manifest.json
index 8548b4f989..2d9160c91b 100644
--- a/skills-manifest.json
+++ b/skills-manifest.json
@@ -14,7 +14,7 @@
"files": 1
},
"hyperframes": {
- "hash": "e0cf1bb2843bc834",
+ "hash": "6cff4ef2b582b81b",
"files": 1
},
"hyperframes-animation": {
@@ -33,6 +33,10 @@
"hash": "18a14a79da6cbc06",
"files": 68
},
+ "hyperframes-keyframes": {
+ "hash": "47f20312033792c3",
+ "files": 3
+ },
"hyperframes-media": {
"hash": "096b2ab0a43b05dd",
"files": 40
diff --git a/skills/hyperframes-keyframes/SKILL.md b/skills/hyperframes-keyframes/SKILL.md
new file mode 100644
index 0000000000..1d9af6bc95
--- /dev/null
+++ b/skills/hyperframes-keyframes/SKILL.md
@@ -0,0 +1,237 @@
+---
+name: hyperframes-keyframes
+description: >
+ Use when a HyperFrames composition needs seek-safe 2D/3D keyframes, GSAP
+ timelines, CSS keyframes, Anime.js, WAAPI, FLIP, paths, masks, SVG morph/draw,
+ text trails, cursor demos, 3D depth, or `hyperframes keyframes` diagnostics.
+ Don't use for broad scene strategy, brand design, media sourcing, captions, or
+ general video planning.
+---
+
+# HyperFrames Keyframes
+
+Keyframes are a pose contract: visible states, continuous subject identity, seek-safe runtime, verified pixels.
+
+Use `hyperframes-animation` for broad scene recipes.
+Use `hyperframes-cli` for full command docs.
+Use `references/keyframe-patterns.md` only when choosing implementation mechanisms, not visual style.
+
+## Procedure
+
+1. Identify the animated subject, visible states, final state, and runtime.
+2. Choose the smallest mechanism that proves the prompt. Read `references/keyframe-patterns.md` only if the mechanism is unclear.
+3. Author seek-safe keyframes in the declared runtime. Build synchronously and register the runtime instance.
+4. Verify with lint, validate, `hyperframes keyframes`, one focused `--shot`, and snapshots at proof times.
+5. If proof fails, fix the source keyframes and rerun the smallest failing diagnostic before rendering.
+
+## Contract
+
+- Name the moving subject.
+- Name the poses needed to prove the intended motion, including the final state.
+- Keyframe visible channels, not hidden helper state.
+- Preserve object identity when continuity matters.
+- Crossfade only when the intended motion is replacement or dissolve.
+- Hold readable or semantic states long enough to see.
+- Final frame is part of the animation, not cleanup.
+- Do not reset to rest unless requested.
+- Do not end on black unless requested.
+- If editing a starter scene, preserve layout, copy, assets, colors, and final state unless asked to redesign.
+
+## Runtime Rules
+
+GSAP:
+
+- build synchronously at page load
+- use `gsap.timeline({ paused: true })`
+- register as `window.__timelines[compositionId]`
+- registry key must match `data-composition-id`
+- do not call `tl.play()` for render-critical motion
+- keep repeats finite
+
+CSS keyframes:
+
+- finite duration and iteration count
+- deterministic delay
+- `animation-fill-mode: both`
+- use `data-start` when timing belongs to a clip
+
+Anime.js:
+
+- create synchronously
+- `autoplay: false`
+- finite duration and loops
+- push every instance to `window.__hfAnime`
+
+WAAPI:
+
+- finite `duration`
+- `fill: "both"`
+- deterministic construction
+- the text surface does not list WAAPI; verify with `--shot` (it seeks WAAPI) and snapshots
+
+Never use for render-critical motion:
+
+- `Date.now()`
+- `performance.now()`
+- unseeded `Math.random()`
+- hover/scroll triggers
+- timers
+- async-created timelines
+- unregistered `requestAnimationFrame`
+- infinite loops
+
+## GSAP Skeleton
+
+```js
+const root = document.querySelector("[data-composition-id]");
+const compositionId = root.dataset.compositionId;
+const tl = gsap.timeline({ paused: true });
+
+tl.addLabel("state-a", 0);
+tl.to(".subject", {
+ keyframes: [
+ { x: 0, opacity: 1, duration: 0.2 },
+ { x: 120, opacity: 1, duration: 0.4, ease: "power2.out" },
+ { x: 100, opacity: 1, duration: 0.2, ease: "power2.inOut" },
+ ],
+ ease: "none",
+});
+
+window.__timelines = window.__timelines || {};
+window.__timelines[compositionId] = tl;
+```
+
+Use labels for semantic states.
+Use position parameters instead of chained delays.
+Use `immediateRender: false` for later `from()`/`fromTo()` tweens touching the same property.
+
+## Keyframe Forms
+
+- Array keyframes: pose ladder with per-step duration/ease.
+- Percentage keyframes: exact timing inside one tween.
+- Property arrays: compact multi-stop changes.
+- `ease: "none"` on the parent when each stop carries its own easing.
+- `easeEach` when every segment should share the same feel.
+
+Do not copy numeric distances or timing from examples. Derive them from the actual composition geometry and duration.
+
+For one subject moving between two boxes, prefer one continuous transform tween or FLIP. Split `x/y/scale` into multiple eased keyframes only when the viewer should feel distinct beats; every segment changes velocity and can read as a hitch.
+
+## Channels
+
+Prefer compositor/visual channels:
+`x/y/z`, `xPercent/yPercent`, `scale`, `rotationX/Y/Z`, `skew`, `transformOrigin`, `svgOrigin`, `opacity`, `autoAlpha`, `clip-path`, masks, CSS vars, SVG path/dash values, camera transforms, shader uniforms.
+
+Avoid layout/lifecycle channels:
+`top/left/right/bottom`, `width/height`, `margin/padding`, `display`, `visibility`, late DOM creation, helper overlays doing subject motion.
+
+## Mechanism Choice
+
+Choose the smallest mechanism that proves the prompt:
+
+| Need | Mechanism |
+| ------------------------------------- | -------------------------------------------------- |
+| Same subject changes box or hierarchy | shared element / FLIP |
+| Subject travels a visible route | path travel |
+| Stroke grows or traces | stroke draw |
+| Shape becomes another shape | shape interpolation |
+| Reveal boundary is visible | clip, mask, or shader uniform |
+| Many items move with order | stagger / indexed delay |
+| Text itself moves | line, word, character, or band subdivision |
+| Surface bends, stretches, or crops | parent/child counter-transform |
+| UI has states | explicit state machine |
+| Scene has depth | DOM 3D, Three.js, or WebGL camera/object keyframes |
+
+Mechanisms can combine, but each one must clarify the idea. Decoration is not proof.
+
+## Timing
+
+- Anticipation only when it clarifies cause or direction.
+- Acceleration leaves rest.
+- Peak proof shows the mechanism unmistakably.
+- Follow-through sells energy and direction.
+- Overshoot only when the subject should feel elastic or tactile.
+- Constant-speed path travel usually needs `ease: "none"`.
+- Discrete UI states usually need a sharp ease-out.
+- Repeated elements need ordered offsets, not identical timing.
+- Final lockups need longer holds than transition poses.
+- Smoothness means continuous velocity on the same subject.
+- Do not overlap tweens that write the same transform property unless the overlap is intentional and verified.
+- Avoid animating large `clip-path`/mask changes while the same hero surface is also scaling or traveling; use nested reveals after the main move settles.
+
+## Text
+
+Preserve line boxes, word spacing, readability, and final fit. If text moves internally, move the glyphs or masked bands, not only decorations around the text. Snapshot readable frames.
+
+## SVG
+
+For stroke growth prefer `DrawSVGPlugin`, then `stroke-dasharray`/`stroke-dashoffset`.
+For shape interpolation prefer `MorphSVGPlugin`; convert primitives to paths when needed and split complex silhouettes into simpler parts.
+
+## 3D
+
+Scale alone is fake depth.
+Use perspective on a stable parent, `transform-style: preserve-3d`, z travel, rotation, camera/world motion, occlusion, and layer order when objects cross.
+
+Use one or two diagnostic angles that expose the depth relationship. If angled proof shows no depth crossing, improve z/camera/occlusion.
+
+## Canvas / WebGL
+
+Keyframe camera position, camera target, object transform, material opacity, shader uniforms, and postprocess intensity through deterministic state. Render from HyperFrames time. Use `--ghost` because marker boxes cannot see internal canvas motion.
+
+## CLI Proof
+
+```bash
+npx hyperframes lint
+npx hyperframes validate
+npx hyperframes keyframes .
+npx hyperframes keyframes . --json
+npx hyperframes keyframes . --runtime all
+npx hyperframes keyframes . --selector "<selector>" --shot "<file>" --samples <n>
+npx hyperframes keyframes . --selector "<selector>" --shot "<file>" --layout strip --from <t0> --to <t1>
+npx hyperframes keyframes . --shot "<file>" --ghost --angle <angle>
+npx hyperframes snapshot . --at <times>
+```
+
+Choose `<selector>` for the real animated subject.
+Choose `<times>` for first frame, proof poses, final-minus-hold, and exact final.
+Choose `<angle>` only when depth must be proven.
+
+| Tool | Proves |
+| ---------------- | --------------------------------------------------------------------------------------------------- |
+| `keyframes` | targets, explicit stops, paths, traces, composed parent/child motion, CSS stops, Anime registration |
+| `--shot` | ghosts, route shape, time spacing, DOM 3D projection, focused selector proof |
+| `--layout strip` | in-place motion, overlaps, contact, subtle scale/opacity, text waves |
+| `--ghost` | canvas, WebGL, shader motion, rendered 3D |
+| `snapshot --at` | masks, text readability, full state, final lockup, black/reset tails |
+
+If selector proof looks wrong:
+
+1. rerun `--json`
+2. find the actual animated target
+3. shoot that target
+4. snapshot full frames
+5. trust painted pixels over logs
+
+## Diagnostic Reading
+
+`flat` means no explicit middle poses. `keyframes` means explicit stops exist. `motionPath` means a route exists. `trace` means multi-stroke drawing. `composed with` means child motion inherits parent motion.
+
+Even ghost spacing means constant speed. Clustered ghosts mean slow-in or settle. Large gaps mean fast travel.
+
+A helper-selector shot is not proof. An onion shot over a broken full frame is not proof.
+
+## Error Handling
+
+| Failure | Fix |
+| ------------------ | ---------------------------------------------------------------------------------- |
+| endpoint-only | add middle poses, hold peak proof, rerun `--shot` |
+| identity break | keep one element alive, use shared source/final boxes, remove substitute crossfade |
+| fake 3D | add z/camera travel, occlusion, angled proof |
+| wrong final | add final hold, snapshot final-minus-hold and exact final |
+| unseekable runtime | pause autoplay, register instance, remove timers, build synchronously |
+| unreadable text | preserve line boxes, reduce displacement, add final hold, snapshot text frames |
+
+## Done
+
+Run lint, validate, keyframes, one focused `--shot`, and snapshots. Confirm first frame, proof poses, final-minus-hold, exact final, subject-owned motion, and no debug overlays.
diff --git a/skills/hyperframes-keyframes/agents/openai.yaml b/skills/hyperframes-keyframes/agents/openai.yaml
new file mode 100644
index 0000000000..2cb053d51e
--- /dev/null
+++ b/skills/hyperframes-keyframes/agents/openai.yaml
@@ -0,0 +1,4 @@
+interface:
+ display_name: "HyperFrames Keyframes"
+ short_description: "Author seek-safe video keyframes"
+ default_prompt: "Use $hyperframes-keyframes to author seek-safe 2D/3D keyframes and verify them with the CLI."
diff --git a/skills/hyperframes-keyframes/references/keyframe-patterns.md b/skills/hyperframes-keyframes/references/keyframe-patterns.md
new file mode 100644
index 0000000000..3c3211d1c6
--- /dev/null
+++ b/skills/hyperframes-keyframes/references/keyframe-patterns.md
@@ -0,0 +1,106 @@
+# Keyframe Mechanism Reference
+
+Use this after `SKILL.md` when choosing a concrete implementation mechanism. It is a parts shelf, not a style guide. Start with one primary mechanism; add supporting motion only when it clarifies the idea.
+
+## Runtime Skeletons
+
+GSAP:
+
+```js
+const root = document.querySelector("[data-composition-id]");
+const id = root.dataset.compositionId;
+const tl = gsap.timeline({ paused: true });
+tl.to("<selector>", {
+ keyframes: [
+ /* derive poses from the scene */
+ ],
+ ease: "none",
+});
+window.__timelines = window.__timelines || {};
+window.__timelines[id] = tl;
+```
+
+CSS:
+
+```css
+.<subject > {
+ animation: <name> <duration> <ease> both;
+ animation-iteration-count: 1;
+}
+@keyframes <name> {
+ 0% {
+ transform: <pose-a>;
+ opacity: <a>;
+ }
+ 100% {
+ transform: <pose-b>;
+ opacity: <b>;
+ }
+}
+```
+
+Anime.js:
+
+```js
+const animation = anime.timeline({ autoplay: false });
+animation.add({ targets: "<selector>" /* derived channels */ });
+window.__hfAnime = window.__hfAnime || [];
+window.__hfAnime.push(animation);
+```
+
+Three/WebGL:
+
+```js
+const state = { progress: 0 };
+tl.to(state, {
+ progress: 1,
+ duration: <duration>,
+ onUpdate: () => {
+ // derive camera/object/material values from state.progress
+ renderer.render(scene, camera);
+ },
+});
+```
+
+## Mechanisms
+
+| Mechanism | Solves | Keyframe | Runtime | Verify |
+| ------------------- | ---------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------ | ---------------------------------------------- |
+| Path travel | Subject must visibly follow a route | path progress, tangent rotation, follower offset, trail opacity | GSAP MotionPath or sampled x/y/z | strip shot at bends; final snapshot |
+| Stroke draw | A line, ring, or outline appears over time | dash/draw range, stroke opacity, endpoint state | DrawSVG or SVG dash fallback | partial mid snapshot; complete final |
+| Shape interpolation | One silhouette becomes another | source path, middle path, target path, fill/stroke | MorphSVG or path tween | first/mid/final snapshots |
+| Shared element | Same subject changes box or hierarchy | source box, target box, x/y, scale, radius, context opacity | GSAP Flip or manual FLIP | one identity moves; no substitute crossfade |
+| Clip/mask reveal | Animated boundary exposes content | clip path, mask position/size, edge softness, inner counter-motion | CSS, SVG, GSAP, or shader | snapshot edge frames and final unclipped state |
+| Ordered repetition | Many items enter, leave, or transform in order | indexed delay, x/y, scale, opacity, final alignment | GSAP stagger, Anime stagger, CSS vars | check first/middle/last item timing |
+| Text subdivision | Text motion needs readable internal timing | line/word/char/band wrappers, y/x, opacity, final fit | SplitText, authored spans, Anime splitText | strip shot plus final readability snapshot |
+| Surface transform | Image/card stretches, crops, or changes shape | parent scale/skew/clip, child counter-scale, transform origin | GSAP/CSS keyframes | no accidental warped final |
+| UI state machine | Interface passes through semantic states | closed, active, loading, success/error, final | GSAP/CSS/Anime | snapshots hit states in order |
+| DOM depth | HTML elements need 3D separation | perspective, z, rotationX/Y, opacity, crossing layer order | CSS 3D + GSAP/CSS/Anime | angled `--shot`; overlap snapshot |
+| Camera/object 3D | Canvas/WebGL scene moves in depth | camera, target, object transform, material opacity | Three.js/WebGL + GSAP proxy | `--ghost`; snapshots at proof poses |
+| Shader uniform | Pixel effect is driven by scalar progress | progress, edge width, noise, color mix, opacity | ShaderMaterial/WebGL uniforms | `--ghost`; snapshot 0/edge/mid/final |
+| Instanced system | Many 3D objects move as one system | instance transforms, scale, color/opacity, camera | Three InstancedMesh | snapshots, because DOM boxes miss internals |
+| Imported model | Model animation must scrub deterministically | `AnimationMixer.setTime`, camera, material, lights | Three AnimationMixer | drive from HyperFrames time; `--ghost` |
+
+## Source Links
+
+- GSAP keyframes: https://gsap.com/resources/keyframes/
+- GSAP timeline: https://gsap.com/docs/v3/GSAP/Timeline/
+- GSAP MotionPathPlugin: https://gsap.com/docs/v3/Plugins/MotionPathPlugin/
+- GSAP Flip: https://gsap.com/docs/v3/Plugins/Flip/
+- GSAP DrawSVGPlugin: https://gsap.com/docs/v3/Plugins/DrawSVGPlugin/
+- GSAP MorphSVGPlugin: https://gsap.com/docs/v3/Plugins/MorphSVGPlugin/
+- GSAP SplitText: https://gsap.com/docs/v3/Plugins/SplitText/
+- GSAP CSSPlugin: https://gsap.com/docs/v3/GSAP/CorePlugins/CSS/
+- Anime.js documentation: https://animejs.com/documentation/
+- Anime.js stagger grid: https://animejs.com/documentation/utilities/stagger/stagger-parameters/stagger-grid/
+- Anime.js timeline: https://animejs.com/documentation/timeline/
+- Anime.js SVG helpers: https://animejs.com/documentation/svg/createmotionpath/
+- MDN CSS animations: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animations/Using_CSS_animations
+- MDN `@keyframes`: https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes
+- MDN `clip-path`: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path
+- MDN CSS masking: https://developer.mozilla.org/en-US/docs/Web/CSS/mask
+- MDN perspective: https://developer.mozilla.org/en-US/docs/Web/CSS/perspective
+- MDN transform-style: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style
+- Three.js AnimationMixer: https://threejs.org/docs/#api/en/animation/AnimationMixer
+- Three.js ShaderMaterial: https://threejs.org/docs/#api/en/materials/ShaderMaterial
+- Three.js InstancedMesh: https://threejs.org/docs/#api/en/objects/InstancedMesh
diff --git a/skills/hyperframes/SKILL.md b/skills/hyperframes/SKILL.md
index edfcc5e6cd..e123e1cf2b 100644
--- a/skills/hyperframes/SKILL.md
+++ b/skills/hyperframes/SKILL.md
@@ -25,15 +25,16 @@ Below: a **capability map** (the domain skills, loaded on demand) and the **inte
Atomic capabilities you load **on demand** — not full video workflows. For "make me a video", use the intent router below.
-| You want to… | Skill |
-| ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------ |
-| **Author / edit an HTML composition** — the `data-*` contract, clips, tracks, sub-compositions, variables | `/hyperframes-core` |
-| **Animate** — atomic motion, scene blueprints, transitions, runtime adapters (GSAP / Lottie / Three.js / Anime.js / CSS / WAAPI / TypeGPU) | `/hyperframes-animation` |
-| **Creative direction** — `frame.md` / `design.md`, palettes, typography, narration, beat planning, audio-reactive | `/hyperframes-creative` |
-| **Media** — TTS voiceover, background music, transcription, background removal, captions | `/hyperframes-media` |
-| **Media resolve** — find + freeze BGM, SFX, images, icons from HeyGen catalog into `.media/` with manifest tracking | `/media-use` |
-| **CLI dev loop** — init, lint, validate, inspect, preview, render, publish, doctor | `/hyperframes-cli` |
-| **Install registry blocks / components** (`hyperframes add`) | `/hyperframes-registry` |
+| You want to… | Skill |
+| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
+| **Author / edit an HTML composition** — the `data-*` contract, clips, tracks, sub-compositions, variables | `/hyperframes-core` |
+| **Animate** — atomic motion, scene blueprints, transitions, runtime adapters (GSAP / Lottie / Three.js / Anime.js / CSS / WAAPI / TypeGPU) | `/hyperframes-animation` |
+| **Author seek-safe keyframes** — GSAP timelines, CSS keyframes, Anime.js, WAAPI, FLIP, paths, masks, SVG morph/draw, 3D depth, plus `hyperframes keyframes` diagnostics | `/hyperframes-keyframes` |
+| **Creative direction** — `frame.md` / `design.md`, palettes, typography, narration, beat planning, audio-reactive | `/hyperframes-creative` |
+| **Media** — TTS voiceover, background music, transcription, background removal, captions | `/hyperframes-media` |
+| **Media resolve** — find + freeze BGM, SFX, images, icons from HeyGen catalog into `.media/` with manifest tracking | `/media-use` |
+| **CLI dev loop** — init, lint, validate, inspect, preview, render, publish, doctor | `/hyperframes-cli` |
+| **Install registry blocks / components** (`hyperframes add`) | `/hyperframes-registry` |
---