A Claude Code skill that reverse-engineers any animation frame by frame, then proves the copy moves the same.
motion-clone: clone any animation frame by frame and verify it
NiazMorshed20075b98fd1b962d
diff --git a/.github/assets/bento-clone.webp b/.github/assets/bento-clone.webpnew file mode 100644index 0000000..39bcbfbBinary files /dev/null and b/.github/assets/bento-clone.webp differdiff --git a/.github/assets/entrance-compare.webp b/.github/assets/entrance-compare.webpnew file mode 100644index 0000000..ca8e0e1Binary files /dev/null and b/.github/assets/entrance-compare.webp differdiff --git a/.github/assets/hover-agentic-commerce.webp b/.github/assets/hover-agentic-commerce.webpnew file mode 100644index 0000000..56da53dBinary files /dev/null and b/.github/assets/hover-agentic-commerce.webp differdiff --git a/.github/assets/hover-crypto.webp b/.github/assets/hover-crypto.webpnew file mode 100644index 0000000..c3389bdBinary files /dev/null and b/.github/assets/hover-crypto.webp differdiff --git a/.github/assets/hover-issuing.webp b/.github/assets/hover-issuing.webpnew file mode 100644index 0000000..4090b55Binary files /dev/null and b/.github/assets/hover-issuing.webp differdiff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..0539f5a--- /dev/null+++ b/.gitignore@@ -0,0 +1,3 @@+node_modules/+.DS_Store+.motion-clone/diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..4623130--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Niaz Morshed++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..49f0e3a--- /dev/null+++ b/README.md@@ -0,0 +1,131 @@+<h1 align="center">motion-clone</h1>++<p align="center"><b>A Claude Code skill that clones any animation frame by frame, then proves the copy moves the same.</b><br>From a live site, a screen recording, an mp4, a gif or a Lottie file, into your own codebase.</p>++<p align="center">+ <a href="https://code.claude.com/docs/en/skills"><img src="https://img.shields.io/badge/Claude_Code-skill-171717?style=flat-square&logo=claude&logoColor=white" alt="Claude Code skill"></a>+ <a href="https://agentskills.io"><img src="https://img.shields.io/badge/Agent_Skills-compatible-171717?style=flat-square" alt="Agent Skills compatible"></a>+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-171717?style=flat-square" alt="MIT license"></a>+ <a href="#requirements"><img src="https://img.shields.io/badge/runs_on-Bun-171717?style=flat-square&logo=bun&logoColor=white" alt="Runs on Bun"></a>+</p>++<p align="center">+ <a href="#install"><img src="https://img.shields.io/badge/Install-npx_skills_add-d7d7d0?style=for-the-badge&labelColor=171717&logo=npm&logoColor=white" alt="Install with npx"></a>+</p>++<p align="center">+ <a href="#quick-start">Quick start</a> ·+ <a href="#gallery">Gallery</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="#writing-a-prompt">Writing a prompt</a> ·+ <a href="#whats-inside">What's inside</a> ·+ <a href="#limits">Limits</a>+</p>++<p align="center">+ <img src=".github/assets/entrance-compare.webp" width="720" alt="Two recordings of the same three cards fading in: stripe.com on top, the clone below. The chat bubbles, the particle ring, the Visa card and the dotted globe appear at the same moments in both.">+</p>++<p align="center"><sub>Three cards from the stripe.com homepage. Top: stripe.com. Bottom: the clone motion-clone built, recorded with the same command.</sub></p>++---++Copying an animation by eye goes the same way every time. The copy looks right in a screenshot and feels wrong in motion: the easing is a little sharper, the second line starts a beat late, the card lifts four pixels instead of six. Nobody can say what is off, so nobody fixes it.++motion-clone treats an animation as something to measure. Claude records the reference, reads it frame by frame and writes down every timing and easing. Then it rebuilds the animation in your stack, records the copy the same way and compares the two until the numbers agree. You get the code and the evidence: timing errors, pixel mismatch, easing fits and side-by-side sheets.++## Quick start++```sh+npx skills add NiazMorshed2007/motion-clone -g+```++The [skills CLI](https://skills.sh) asks which agents to set up. Add `-a claude-code` to skip the question.++Then, in Claude Code:++```text+/motion-clone the hero entrance on https://example.com, into components/Hero.tsx+```++The first run downloads Playwright's Chromium and a static ffmpeg into the skill's folder (about 250 MB). No API keys.++## Gallery++Each card was cloned by its own agent running this skill, in 28 to 40 minutes. Left: stripe.com. Right: the clone. Same pointer path, same recording command.++<table>+ <tr>+ <td width="33%"><img src=".github/assets/hover-agentic-commerce.webp" alt="The agentic commerce card on stripe.com and in the clone, side by side: a chat with two product cards over a ring of pink particles; the pointer enters, the card grows and the border lights up."></td>+ <td width="33%"><img src=".github/assets/hover-issuing.webp" alt="The card issuing card on stripe.com and in the clone, side by side: an iridescent Visa card that tilts towards the pointer."></td>+ <td width="33%"><img src=".github/assets/hover-crypto.webp" alt="The crypto card on stripe.com and in the clone, side by side: a rotating dotted globe with arcs and amount labels."></td>+ </tr>+ <tr>+ <td><sub><b>Agentic commerce</b>: chat timing within 43 ms, layout within 0.05 px, 10,000-point particle ring that reacts to the pointer.</sub></td>+ <td><sub><b>Card issuing</b>: three.js. 0.03 % of pixels differ at rest; the tilt settles within 0.4 px of stripe.com's.</sub></td>+ <td><sub><b>Stablecoins and crypto</b>: globe pose exact, arc and label timings within stripe.com's own spread.</sub></td>+ </tr>+</table>++<p align="center"><img src=".github/assets/bento-clone.webp" width="720" alt="The three cloned cards side by side at rest."></p>++## How it works++| Step | What happens |+|---|---|+| **Capture** | Records the reference in a headless browser at a fixed viewport and frame rate: a video, numbered frames, every CSS and Web Animations API animation it finds, and the position of chosen elements on every frame. |+| **Spec** | One row per element per property: start, duration, from → to, easing, stagger. A row with a "?" means the frames haven't been read yet. |+| **Build** | Implements it with what your project already uses: CSS, Framer Motion, GSAP, three.js. |+| **Verify** | Records the clone with the exact same command, then compares timing, pixels and easing curves and builds side-by-side sheets. |+| **Repeat** | Fixes the smallest thing the evidence points at and records again, usually 2 to 5 rounds. A row that still fails after 5 is reported with its numbers and the reason. |++How close it has to be depends on your words:++| Level | Say | Must match |+|---|---|---|+| Motion-faithful (default) | "clone this animation" | trigger, order, stagger, timing within 80 ms, easing family, distance |+| Pixel-faithful | "match it exactly", "pixel-perfect" | all of the above plus fonts, sizes, colours, spacing, assets; ≤ 2 % mean pixel mismatch |+| Mixed | "clone X and add Y" | the cloned parts at one of the levels above; your additions kept separate |++## Writing a prompt++Name the thing, where it is and where it should go. Narrow it to one section, one widget or a time range when you only want part of it.++```text+/motion-clone the hero entrance on https://example.com, into components/Hero.tsx+/motion-clone this loader, 0:03 to 0:05 of ~/Downloads/loader.mov+/motion-clone the card hover in this gif, match it exactly+/motion-clone the logo marquee from https://example.com, with our logos and pause on hover+```++## What's inside++| Path | What it is |+|---|---|+| `SKILL.md` | The workflow Claude follows: scope, capture, spec, build, verify, report. |+| `references/` | Capture recipes per source type, how to read frames into a spec, implementation patterns per stack, pass criteria and fixes. |+| `scripts/capture.ts` | Records a page: video, frames, declared animations, computed styles, fonts, libraries, per-frame element tracks. Triggers: load, scroll, hover, leave, pointer path, drag, click, none. |+| `scripts/frames.ts` | Extracts and crops frames from a video or gif. |+| `scripts/compare.ts` | Frame-by-frame comparison: alignment, timing error, mismatch, activity curves, diff images. |+| `scripts/easing.ts` | Fits a tracked property to named easings, detects overshoot and springs, diffs two tracks. |+| `scripts/sheet.ts` | Labelled contact sheets and reference / clone / diff comparison sheets. |++## Requirements++- [Bun](https://bun.sh) 1.1 or later.+- macOS or Linux. Windows is untested.+- About 250 MB on first run for Chromium and ffmpeg, installed by `scripts/setup.sh` into the skill's own folder.++The skills CLI can install it for other agents that read `SKILL.md`, but it has only been tested with Claude Code.++## Limits++- WebGL and canvas are compared as pixels. Random content, like particles, never matches exactly, so it is judged against two recordings of the reference.+- Headless browsers draw WebGL in software, so frame pacing in recordings differs from a real screen.+- Pages behind a login, YouTube and Loom can't be recorded directly; hand it a screen recording.+- Physics springs are fitted from their overshoot and settle time, not read from the source.+- It clones what you point it at. Fonts, images and code from another site still belong to their owners; make sure you may use what you copy.++## License++[MIT](LICENSE). The gallery recreates three cards from stripe.com as a study of the technique; it is not affiliated with or endorsed by Stripe. Stripe and Visa are trademarks of their respective owners.diff --git a/SKILL.md b/SKILL.mdnew file mode 100644index 0000000..18b66ad--- /dev/null+++ b/SKILL.md@@ -0,0 +1,100 @@+---+name: motion-clone+description: Clone a section, widget, page or animation from any reference (a live website URL, a screen recording, an mp4/mov/webm, a gif, a Lottie file, a prototype export) frame by frame into the user's own codebase, then record the clone and verify it against the reference frame by frame, iterating until timing, easing, sequence and layout match. Use whenever the user wants to clone, copy, replicate, recreate, port or "steal" a hero, section, widget, marquee, carousel, hover effect, page transition, loader, scroll animation or interaction from a site or video, says "make it look/feel/move like this", "same animation as", "match this exactly", or hands over a gif/video and asks to build it, including when they also want to add their own content, colours or extra features on top, or only want part of the reference (one section, one widget, a few seconds). Pixel-level matching of fonts, colours and spacing is done only when they ask for it.+---++# motion-clone++Rebuild what the user points at so that it moves the way the reference moves, prove it with a frame-by-frame comparison, and keep going until the comparison passes. The deliverable is code in the user's project plus evidence (numbers and side-by-side sheets), never "it looks about right".++## What "done" means++Pick the fidelity level from the user's words and state it in the first message; it decides what you verify.++| Level | When | Must match | May differ |+|---|---|---|---|+| **motion-faithful** (default) | "clone this animation", "make ours feel like theirs", "same hero as X but our copy" | trigger, sequence and order, stagger, timing of every step (±80 ms), easing family, direction and distance of movement relative to the element size, layout proportions | copy, colours, fonts, images, brand details |+| **pixel-faithful** | "match it exactly", "pixel-perfect", "details should match", "1:1" | everything above plus fonts, sizes, colours, spacing, radii, shadows, assets; mean frame mismatch ≤ 2 % | nothing the user did not ask to change |+| **mixed** | "clone X and add Y", "like theirs but with our pricing tiers" | the cloned parts at one of the levels above | the additions, which you describe and show but verify only for not breaking the cloned motion |++The user can narrow the target to one section, one widget, one page, or a time range of a video ("the first 3 seconds", "0:12 to 0:15"). Clone exactly that; do not pull in the rest of the page.++## Workflow++Everything below lives in `.motion-clone/<name>/` inside the user's project (add it to `.gitignore` unless they want the evidence committed). Keep each round's artefacts; they are the proof.++### 0. Scope++Write three lines at the top of `.motion-clone/<name>/spec.md` before any capture:++- **Target**: what to clone, as precisely as the user said it (URL + selector / time range / "the toggle in the gif").+- **Destination**: where the code goes and in what stack (read `package.json`, existing components and the animation library already in use; match it rather than introducing a new one).+- **Fidelity**: motion-faithful, pixel-faithful or mixed, plus the list of additions for mixed.++Infer what you can from the request and the repo. Ask only when two readings lead to different work (for instance "the hero" on a page with two candidate sections). When a reference is a login-walled page or a YouTube/Loom link you cannot download here, ask the user for a screen recording and continue with everything else meanwhile.++### 1. Setup++`<skill>` below is the directory this SKILL.md lives in. Scripts need [Bun](https://bun.sh); the first run downloads Playwright's Chromium and a static ffmpeg (about 250 MB).++```bash+bash <skill>/scripts/setup.sh # installs playwright, ffmpeg, pixelmatch once; prints "ready"+```++All scripts are run with `bun <skill>/scripts/<name>.ts --help`. They are deterministic and share one rule: capture the reference and the clone with the **same** viewport, selector crop, trigger, duration and fps, otherwise the comparison measures your setup instead of your work.++### 2. Capture the reference++Read `references/capture.md` for the recipe for your source type. In short:++- **Website**: `capture.ts --url … --out ref --selector <section> --trigger load|scroll|hover|click|none --duration … --track "<moving elements>"`. You get `video.webm`, `frames/`, `inspect.json` (declared animations, keyframes, computed styles, fonts, detected libraries) and `track.json` (per animation frame position, size, opacity, transform of each tracked element). For CSS/WAAPI motion `inspect.json` often contains the exact durations, delays and easings: use them, it beats estimating.+- **Video or gif**: `frames.ts --in file --out ref/frames --fps 10..30 --start … --end … --crop …`. Probe first with `--probe`, then view a few frames to find the crop of the widget you are cloning.+- **Lottie / Rive / prototype export**: the file is the spec; read it, do not re-derive it from pixels.++Then build labelled sheets and look at them: `sheet.ts filmstrip --frames ref/frames --out ref/sheets`. Read every sheet with the image viewer. This is the frame-by-frame inspection the user asked for; do not skip it or sample only the first sheet.++### 3. Write the motion spec++Fill `spec.md` using the template in `references/analysis.md`. One row per element per property: trigger, start time, duration, delay or stagger, from → to, easing, notes. Get the numbers from, in order of preference: `inspect.json` animations and keyframes → `easing.ts` on `track.json` → reading frames (first frame where it changes, last frame where it changes, overshoot or not). Also note the static facts the motion depends on: element sizes and positions, z-order, overflow clipping, transform origins, and for pixel-faithful work fonts, colours, spacing and assets.++The spec is the contract between the reference and the clone. Every row becomes a check in step 5. If a row has a "?" you have not finished reading the frames.++### 4. Build++Implement in the user's stack following `references/implementation.md` (easing tables, stagger math, scroll and hover triggers, reduced motion). Keep the DOM structure close to the reference's role structure so the tracked selectors have equivalents. For mixed work, put additions in clearly separate components or blocks and mention them in `spec.md` under "Additions".++Give the clone a way to be captured the same way as the reference: a route or a static page that renders the component at the reference viewport with the same trigger. A dev server is fine (`capture.ts --url http://localhost:5173/…`); a standalone HTML file also works.++### 5. Verify, fix, repeat++Capture the clone with the exact command used for the reference, changing only `--url` and `--out clone-N`, then:++```bash+bun <skill>/scripts/compare.ts --ref ref/frames --clone clone-N/frames --out compare-N+bun <skill>/scripts/sheet.ts compare --ref ref/frames --clone clone-N/frames --diff compare-N/diff --out compare-N/sheets --every 2+bun <skill>/scripts/easing.ts --track clone-N/track.json --selector "<el>" --prop <translateY|opacity|…> --compare-track ref/track.json+```++Read `references/verify.md` for how to read the report, the pass criteria for each fidelity level and the fixes that each kind of failure usually needs. Look at the compare sheets yourself, every round; the numbers tell you that something is off, the sheets tell you what.++Loop until every spec row passes. Each round: change the smallest thing the evidence points at, re-capture, re-compare. Expect 2 to 5 rounds. If after 5 rounds a row still fails, stop and report it with its numbers and the reason (missing font, WebGL, a physics spring you approximated), do not quietly lower the threshold or drop the row.++### 6. Report++The final message must stand alone:++- Fidelity level and what was cloned, what was added.+- Where the code is (files) and how to trigger the motion.+- A short table of the last compare round: timing error, mean mismatch, easing match per key element, pass/fail.+- Paths to the final compare sheets, embedded as images when the environment shows them.+- Residual deviations, each with a number and a reason.++## Pitfalls that waste rounds++- Different viewport or crop between reference and clone: fix the capture before touching code.+- Judging from the first frame and the last frame only: the easing lives in the middle frames; read the sheets.+- Fonts: a different fallback font changes every frame's pixels. For pixel-faithful work load the same font (from `inspect.json` fonts) before judging mismatch; for motion-faithful work ignore text pixels and read the timing columns.+- Reference recorded on a loaded page vs clone captured cold: use `--wait-before`, or `--trigger none` with a `--pre-js` that restarts the animation, so both start from rest.+- Scroll-driven motion: it is a function of scroll position, not time. Capture both with the same `--scroll-steps` and `--scroll-ms`, and compare per scroll position (the track's `scrollY`), not per second.+- JS libraries (GSAP, Framer Motion springs): `--playback-rate` does not slow them. Use `track.json` and `easing.ts` (it reports overshoot and "spring-like") and tune spring parameters by the overshoot and settle time.+- Videos of someone else's screen have a cursor, a browser chrome and compression noise: crop them out and raise `--pixel-threshold` a little (0.15) rather than chasing noise.diff --git a/references/analysis.md b/references/analysis.mdnew file mode 100644index 0000000..637fb7f--- /dev/null+++ b/references/analysis.md@@ -0,0 +1,67 @@+# Reading frames and writing the motion spec++The spec turns "I watched it" into rows you can check. Write it before building; update it when verification teaches you something; it is the first thing to show the user when they ask "does it match?".++## spec.md template++```markdown+# <name> motion spec++Target: <url + selector | file + time range> Viewport: 1440x900 Fps: 25+Destination: <path/Component.tsx> (<stack: React + Framer Motion | CSS | GSAP …>)+Fidelity: motion-faithful | pixel-faithful | mixed (additions: …)+Reference capture: .motion-clone/<name>/ref (command: …)++## Structure (static)+| element | role / selector (ref → clone) | box at rest (x,y,w,h) | notes (overflow, z-index, origin, clip) |++## Timeline (t=0 is the trigger)+| # | element | property | from → to | start ms | duration ms | easing | stagger / repeat | source |+| 1 | h1 | opacity | 0 → 1 | 200 | 700 | cubic-bezier(.16,1,.3,1) | – | inspect.json |+| 2 | h1 | translateY | 40px → 0 | 200 | 700 | same | – | inspect.json |+| 3 | p | opacity, translateY | 0→1, 30px→0 | 400 | 700 | same | +200 ms after h1 | track.json + easing.ts |+| 4 | .cta | opacity, translateY | 0→1, 24px→0 | 600 | 600 | same | +200 ms | frames #15–#30 |++Trigger: load | enters viewport (threshold ~25 %) | hover | click | scroll-linked (0–600px) | loop every N ms+Total length: <ms> Last visible change: <ms>++## Style facts needed for the motion (and everything, if pixel-faithful)+fonts, sizes, colours, radii, shadows, gaps, assets (with URLs or where copied)++## Additions (mixed only)+what is new, where it lives, how it is kept out of the compared region or why it does not affect timing+```++## Where the numbers come from++1. **`inspect.json › animations`** (websites with CSS/WAAPI motion): `timing.delay`, `timing.duration`, per-keyframe `easing`, `iterations`, `direction`. Transitions show up as `CSSTransition` with `transitionProperty`. Copy them.+2. **`track.json` + `easing.ts`** (websites, any technology): per element and property, prints delay, visible duration, overshoot and the best-fitting named easing with its fitted duration. Run it for every moving element and property (`translateY`, `opacity`, `scale`, `x`, `w`…). Overshoot > 2 % means a spring or a back easing; note the overshoot percentage and the settle time, the implementation notes say how to map them.+3. **Frames** (videos, gifs, canvas): for each element find the first frame where it changes and the last frame where it changes; `start = first/fps`, `duration = (last − first + 1)/fps`. Judge the easing from where the midpoint lands: if the element has covered more than half of its distance at a third of the duration it is an ease-out; less than a quarter, an ease-in; symmetric, ease-in-out; constant steps, linear. Overshoot past the final position then return: back/spring. `compare.ts` prints an activity curve per set that shows these shapes as bars even without a track.+4. **Staggers**: the gap between the start frames of siblings. Note whether it is a constant (each +80 ms), grows (ease on the stagger), or is per-character/per-word (text reveals).++## Patterns worth recognising++Most landing-page motion is one of these; naming it saves rounds.++| Pattern | Tell-tale frames | Typical numbers |+|---|---|---|+| fade-up stagger | siblings rise 16–48 px while fading, each one slightly later | 500–800 ms, ease-out-expo/quint, stagger 60–150 ms |+| text reveal (lines, words, chars) | pieces appear in order, often clipped by their line box (`overflow: hidden` wrapper) | 600–1000 ms, per-piece stagger 20–50 ms |+| clip/mask reveal | content uncovers along an edge, no fade | 800–1200 ms, ease-in-out, `clip-path: inset()` |+| scale-in (modal, menu, card) | grows from 0.9–0.96 with a fade, transform-origin at the anchor | 150–250 ms, ease-out |+| hover lift | card moves up 2–8 px, shadow grows | 150–300 ms, ease-out; reverse uses a shorter or same time |+| marquee | continuous translateX of a duplicated row | linear, period 10–40 s, loops; measure the period, not the easing |+| scroll-linked | changes only while scrolling, stops when you stop | ties to `scrollY` ranges; read `track.json` scrollY vs value |+| pinned section | element stays fixed while the page scrolls past | track `y` stays constant for a scroll range |+| parallax | layers move at different fractions of the scroll delta | ratios like 0.2 / 0.5 / 1 |+| count-up / typewriter | numbers or characters change per frame | duration plus easing on the value |+| spring | overshoots then settles, sometimes twice | stiffness/damping; see implementation notes |+| loader / skeleton pulse | opacity or gradient position oscillates | period 1–2 s, ease-in-out, infinite alternate |+| page transition | old view exits, new view enters, often with a shared element | 300–600 ms, exit shorter than enter |++## How to read a sheet++- Go row by row with the timestamp labels. Write down, per element, the frame it first moves and the frame it rests. Do this for every element, not just the biggest one.+- Compare consecutive frames: a big jump early then small changes = ease-out; small then big = ease-in.+- Look for things that are easy to miss: a backdrop that fades, a shadow that grows, letter-spacing that tightens, a blur that clears, a border that appears, an icon that rotates. They are part of the motion.+- Note what does **not** move. A clone that animates an element the reference keeps still fails just as much.diff --git a/references/capture.md b/references/capture.mdnew file mode 100644index 0000000..30c4870--- /dev/null+++ b/references/capture.md@@ -0,0 +1,78 @@+# Capturing a reference++Goal: a numbered set of PNG frames of exactly the thing to clone, at a known fps, starting a little before the motion begins, plus whatever ground truth the source can give you (declared animations, tracked element positions). The same capture, later run on the clone, is the verification.++## Live website++```bash+bun <skill>/scripts/capture.ts --url https://example.com --out .motion-clone/<name>/ref \+ --viewport 1440x900 --selector "section.hero" --trigger load --duration 3000 \+ --track "section.hero h1, section.hero p, section.hero .cta"+```++Find the selector first: `capture.ts --no-video --selector body` dumps `inspect.json` with every node under the target, its rect and styles. Or open the page in any browser tool your agent has (a Playwright or Chrome DevTools MCP, the host app's preview) and read the accessibility tree. Prefer selectors by role or stable class names; generated class names (`css-1x2y3z`) change between loads on some sites, so pick a parent with a semantic tag or `id`.++Triggers:++| Motion starts when… | `--trigger` | Notes |+|---|---|---|+| the page loads | `load` | window starts at navigation; nothing else is needed |+| the section scrolls into view | `scroll` | starts just below the fold and wheels the section in over `--scroll-ms` in `--scroll-steps` steps; same values on the clone |+| the page reaches a scroll position | `scroll --scroll-to 1800` | scroll-linked (parallax, pinned) motion; compare by `scrollY` in `track.json` |+| the pointer enters an element | `hover --target ".card"` | `--selector` is the crop, `--target` the element hovered; `--hover-at 0.2,0.8` picks the spot |+| the pointer leaves (hover-out) | `leave --pre-hover ".card"` | hovers first for `--pre-hover-ms`, then moves to `--leave-to` |+| something follows the pointer (glow, tilt, spotlight) | `move --target ".card" --path "0.1,0.1;0.9,0.1;0.9,0.9"` | `--path-ms` per leg; same path on the clone |+| something is dragged (globe, carousel, slider, inertia/fling) | `drag --target ".globe" --path "0.3,0.5;0.7,0.5"` | button down at the first point, glide each leg in `--path-ms`, released while moving so fling velocity is non-zero |+| something is clicked (menu, tab, accordion, toggle) | `click --target "button[aria-label=Menu]"` | add `--pre-js` to reach the state before the click |+| never, it loops (marquee, idle loader, background) | `none` | capture 2 to 3 loop periods and measure the period from the activity curve |++Useful options:++- `--pre-js "document.querySelector('.cookie button')?.click()"` dismisses overlays or opens the state you need before the trigger.+- `--playback-rate 0.25` slows CSS animations and transitions 4x (CDP). The frames then have 4x the time resolution (`--fps 100` works). JS-driven motion ignores it.+- `--reduced-motion reduce` shows what the site does for users who turn motion off; clone that path too when the project cares about accessibility.+- `--color-scheme dark` when the reference is dark-mode.+- `--clip x,y,w,h` when the element grows or moves outside its initial box; measure the box on `final.png`.+- `--pad 24` keeps shadows and overshoot inside the crop.++What you get and what each is for:++| File | Use |+|---|---|+| `inspect.json › animations` | every CSS animation, transition and Web Animations API animation that ran under the target: `timing.duration/delay/easing`, keyframes with per-keyframe easing. When present this is the spec; copy numbers from here. |+| `inspect.json › keyframes` | `@keyframes` rules found in reachable stylesheets (cross-origin sheets are listed as unreadable). |+| `inspect.json › nodes` | rect and the motion-relevant computed styles of up to 150 nodes under the target: fonts, colours, radii, shadows, overflow, transforms. The static side of the spec. |+| `inspect.json › libs` | gsap, framer-motion, lottie, webgl, lenis, webflow, scroll-driven CSS… tells you where the motion is defined and which capture limits apply. |+| `track.json` | one sample per animation frame (≈16 ms) per tracked selector: `x y w h opacity transform`. Feed it to `easing.ts`. |+| `frames/` + `frames.json` | the pictures; `triggerFrame` is where t=0 of the motion sits. |++Limits: WebGL and canvas content is captured as pixels only (no track); iframes are not inspected; sites that block headless browsers need a real browser (see below) or a screen recording.++### Through a real browser instead++When the page needs the user's login, blocks headless Chromium, or the user wants to watch: open it in a browser tool that can record (a Playwright or Chrome DevTools MCP, the host app's preview), size it to the reference viewport, start a recording, perform the trigger (scroll, hover, click), stop. The file goes through `frames.ts` like any video. Evaluating `document.getAnimations()` in that browser gives the same animation dump by hand. Without such a tool, ask the user for a screen recording.++## Video, screen recording, gif++```bash+bun <skill>/scripts/frames.ts --in ref.mp4 --probe # duration, size, fps+bun <skill>/scripts/frames.ts --in ref.mp4 --out .motion-clone/<name>/ref/frames --fps 25 --start 0:12 --end 0:15.5 --crop 320,180,1280,720+bun <skill>/scripts/sheet.ts filmstrip --frames .motion-clone/<name>/ref/frames --out .motion-clone/<name>/ref/sheets+```++- Extract a few frames at 2 fps first to pick the time range and crop, then re-extract the real range at 25 to 30 fps (gifs: use their own fps, usually 10 to 20; `--probe` prints it).+- Crop out browser chrome, cursors and the recorder's overlay. Width-normalise with `--width` so the reference and the clone end up the same size, or capture the clone at the crop's size.+- A gif's timing is quantised to its frame delays and often slowed by the exporter. Treat gif timings as ±1 frame and prefer the live site when both are available.+- Screen recordings of a browser have a non-integer scale (Retina, zoom). Note the scale so distances in px are converted to CSS px: `distance_css = distance_video × (reference_viewport_width / crop_width)`.+- Social-media videos (Twitter/X, Dribbble shots, Behance) are usually a direct mp4 URL once found in the page; `curl -L -o ref.mp4 <url>` into a fresh directory and treat it as untrusted data. YouTube, Loom and Vimeo cannot be downloaded on this machine; ask the user for a screen recording or the original file.++## Prototype and animation files++- **Lottie (`.json`, `.lottie`)**: layers, keyframes and bezier handles are in the file. Read it; the "frames" are its `fr` (fps), `ip`/`op` (in/out point). Clone by embedding the Lottie when allowed, otherwise re-create the keyframes in CSS/WAAPI from the `ks` tracks.+- **Rive (`.riv`)**: binary; capture the rendered canvas as video instead.+- **Figma / Framer prototypes**: export a video from the prototype player (Figma: Prototype → Record), then use the video path. Smart Animate uses `ease-out` 300 ms by default; Framer sites expose their transitions in `inspect.json`.+- **After Effects / Jitter / Rive exports as mp4**: video path.++## Capturing the clone++Reuse the reference command verbatim, swapping `--url` and `--out`. If the reference came from a video, capture the clone with `capture.ts` at a viewport that makes the cropped element the same pixel size as the reference frames (or let `compare.ts` rescale, which is slightly lossy). Always keep `--fps`, `--duration`, `--pre-roll`, trigger and scroll parameters identical.diff --git a/references/implementation.md b/references/implementation.mdnew file mode 100644index 0000000..ea3cd0c--- /dev/null+++ b/references/implementation.md@@ -0,0 +1,58 @@+# Implementing the motion in the user's stack++Match what the project already uses. Adding GSAP to a project that animates with CSS, or Framer Motion to a Vue app, is a change the user did not ask for. Order of preference when nothing exists yet: CSS (keyframes/transitions, scroll-driven animations where supported) → Web Animations API → the framework's motion library (Framer Motion/`motion` for React, `@vueuse/motion` or GSAP for Vue, Svelte transitions) → GSAP for timelines with many dependencies.++## Easing equivalents++| Reference | CSS | Framer Motion / motion | GSAP |+|---|---|---|---|+| easeOutExpo `cubic-bezier(0.16,1,0.3,1)` | same | `ease: [0.16, 1, 0.3, 1]` | `"expo.out"` |+| easeOutQuint `cubic-bezier(0.22,1,0.36,1)` | same | `[0.22, 1, 0.36, 1]` | `"quint.out"` |+| easeOutCubic `cubic-bezier(0.33,1,0.68,1)` | same | `[0.33, 1, 0.68, 1]` or `"easeOut"` | `"power2.out"` |+| easeInOutCubic `cubic-bezier(0.65,0,0.35,1)` | same | `[0.65, 0, 0.35, 1]` | `"power2.inOut"` |+| material standard `cubic-bezier(0.4,0,0.2,1)` | same | `[0.4, 0, 0.2, 1]` | `"power1.inOut"` ≈ |+| easeOutBack `cubic-bezier(0.34,1.56,0.64,1)` | same | `[0.34, 1.56, 0.64, 1]` | `"back.out(1.7)"` |+| spring, overshoot ~10 %, settles in ~600 ms | `linear(...)` sampled curve, or WAAPI with sampled keyframes | `type: "spring", stiffness: 300, damping: 20` (less damping → more overshoot; lower stiffness → slower) | `"elastic.out(1, 0.5)"` or `gsap` + physics plugin |+| linear | `linear` | `"linear"` | `"none"` |++Spring tuning from measurements: overshoot ≈ `exp(−π ζ / sqrt(1 − ζ²))` where `ζ = damping / (2·sqrt(stiffness·mass))`. 10 % overshoot → ζ ≈ 0.59; 5 % → 0.69; 20 % → 0.46. Settle time ≈ `4 / (ζ·ω)` with `ω = sqrt(stiffness/mass)`. Start from `mass: 1`, pick ζ from the overshoot, then stiffness from the settle time, then verify with `easing.ts`.++## Patterns++**Fade-up stagger (CSS)**+```css+.item { opacity: 0; transform: translateY(32px); animation: up 700ms cubic-bezier(.16,1,.3,1) forwards; animation-delay: calc(var(--i) * 90ms + 200ms); }+@keyframes up { to { opacity: 1; transform: none; } }+```+Set `--i` per child (`style="--i: 2"`), or `:nth-child` rules. Keep `forwards` so the end state holds.++**Framer Motion stagger**+```tsx+const parent = { hidden: {}, show: { transition: { staggerChildren: 0.09, delayChildren: 0.2 } } };+const child = { hidden: { opacity: 0, y: 32 }, show: { opacity: 1, y: 0, transition: { duration: 0.7, ease: [0.16, 1, 0.3, 1] } } };+<motion.ul variants={parent} initial="hidden" animate="show">{items.map(i => <motion.li key={i} variants={child} />)}</motion.ul>+```++**Enter-viewport trigger**: Framer `whileInView` + `viewport={{ once: true, amount: 0.25 }}`; plain JS `IntersectionObserver` with `threshold` set to the fraction visible when the reference starts (read `track.json`: the `y` of the element at the first moving sample over the viewport height). CSS scroll-driven: `animation-timeline: view(); animation-range: entry 0% entry 40%` where supported.++**Scroll-linked**: CSS `animation-timeline: scroll()` with `animation-range`, GSAP ScrollTrigger `scrub: true`, or Framer `useScroll` + `useTransform([0, 600], [0, -120])`. The mapping is scroll px → value, take the two endpoints from the track.++**Text reveal by line/word**: split into spans with an `overflow: hidden` wrapper per line, animate `translateY(110%) → 0`. Keep accessible text intact (`aria-label` on the container, `aria-hidden` on the spans).++**Hover lift**: `transition: transform 220ms cubic-bezier(.2,.8,.2,1), box-shadow 220ms` on the card; animate `transform`, not `top`. Reverse often uses the same timing; check the reference's hover-out frames too.++**Marquee**: duplicate the content once, `animation: scroll Ns linear infinite` from `translateX(0)` to `translateX(-50%)`. `N` is the measured period. Pause on hover only if the reference does.++**Clip/mask reveal**: `clip-path: inset(0 100% 0 0)` → `inset(0 0 0 0)`, or `mask-image` with an animated gradient position.++**Loops and idle**: `animation-iteration-count: infinite; animation-direction: alternate` for pulses; measure one period from the activity curve.++## Details that make or break the match++- `transform-origin`: scale-ins grow from the anchor (a menu from its button corner, a modal from centre). Read `nodes › transform-origin` in `inspect.json` if it was non-default.+- `will-change: transform` or `translateZ(0)` on elements the reference composites, to avoid jank in the comparison video.+- `overflow: hidden` wrappers decide whether a sliding element is clipped or visible outside its box; copy them.+- Order of transforms: `translate() scale()` ≠ `scale() translate()`. Use individual properties (`translate`, `scale`, `rotate`) when the stack allows it.+- Fill mode and initial state: render the pre-motion state in CSS (opacity 0 etc.) so the first frame already matches; avoid a flash of the final state before JS runs.+- `prefers-reduced-motion`: wrap non-essential motion in `@media (prefers-reduced-motion: no-preference)` or Framer `useReducedMotion()`; if the reference ignores it, still add it unless the user says not to, and mention it.+- Fonts (pixel-faithful): load the same family and weights listed in `inspect.json › fonts` before capturing the clone (`document.fonts.ready`), otherwise every frame mismatches.diff --git a/references/verify.md b/references/verify.mdnew file mode 100644index 0000000..2ef4937--- /dev/null+++ b/references/verify.md@@ -0,0 +1,65 @@+# Verifying the clone++A round is: capture the clone the same way as the reference → `compare.ts` → `sheet.ts compare` → `easing.ts --compare-track` for each tracked element → read everything → fix one cause → next round. Keep every round's directory (`clone-1`, `compare-1`, `clone-2`, …) so the report can show progress.++## What compare.ts tells you++`report.md` / `report.json`:++- **offset**: the clone frame matched to reference frame 0 (auto-aligned on the first ten frames). A large offset means the clone starts late or early; fix the trigger timing or `--wait-before`, do not rely on alignment to hide it.+- **mean mismatch** and **worst frames**: fraction of pixels that differ per frame. Pixel-faithful work reads this directly. Motion-faithful work reads it as a trend: it should be low at rest and spike only where the two differ in state.+- **motion window**: first/last frame with visible change, and the peak, for both sets. The **timing error** is the difference, in seconds, of start, end, duration and peak. This is the main motion metric, independent of colours and copy.+- **activity curve**: bars of change per frame. Same shape = same easing and stagger; a clone whose bars are front-loaded against a reference whose bars are even is using a stronger ease-out, and so on.+- `diff/NNNN.png`: red where pixels differ. `sheet.ts compare --diff` puts reference, clone and diff side by side with the mismatch per row.++`easing.ts --compare-track other.json` prints `maxAbsDiff` / `meanAbsDiff` of the property over time between the two tracks (in CSS px or opacity units) and the best-fit easing of the clone, to compare with the reference's.++## Pass criteria++Motion-faithful (per spec row):++- start and end timing error ≤ 0.08 s (two frames at 25 fps); duration error ≤ 0.08 s+- easing: same best-fit family (out / in / in-out / linear / spring) and RMSE of the reference's best fit applied to the clone's track ≤ 0.05, or `meanAbsDiff` ≤ 5 % of the travel distance+- stagger order and gaps within 0.04 s+- travel distance within 10 % of the reference relative to the element size, same direction+- nothing moves in the clone that is still in the reference, and vice versa+- compare sheets: the same visual state at the same timestamp, allowing for different copy/colours++Pixel-faithful adds:++- mean mismatch ≤ 2 %, no frame above 5 % (set `--threshold 0.02`); at rest frames ≤ 0.5 %+- fonts loaded and identical (check `inspect.json › fonts` on both captures), colours and sizes equal in `nodes`+- same assets at the same size++Mixed: the cloned region passes one of the above with `--region` limited to it; the additions are shown on a sheet and described.++## Reading failures → usual fix++| Symptom | Usual cause | Fix |+|---|---|---|+| everything shifted by the same offset, shape identical | trigger latency or missing delay | add/adjust the initial delay; check `--wait-before` |+| clone shorter and front-loaded | easing too aggressive (expo vs quint), or duration from visible window instead of declared | use `easing.ts` fitted `durationMs`, set the declared duration |+| clone ends on time but starts late | delay too long, duration too short | fix both together |+| bars spread evenly in clone, spiky in reference | linear or ease-in-out where the reference is ease-out | change easing family |+| mismatch high at rest frames | layout/style differences, font fallback, crop differs | fix capture crop; for pixel-faithful load the font, fix sizes |+| reference overshoots, clone does not | spring vs bezier | use a spring (Framer `type: "spring"`, GSAP `back.out`/`elastic`, CSS `linear()` with sampled spring) |+| stagger gaps differ | per-item delay math | `delay = base + index × step`; check index source |+| activity in clone where reference is still | an element animates that should not, or a hover state is triggered by the mouse position | move the mouse out, remove the stray transition |+| only the last frames differ | fill-mode or end state (`forwards` missing), or final value rounds differently | set `animation-fill-mode: forwards` / `fill: "forwards"` |+| scroll trigger: clone starts earlier/later | IntersectionObserver threshold / rootMargin differ | match threshold to the reference's entry point in `track.json` (`y` where motion begins) |++## When to stop++- Stop when every spec row passes its criteria and the latest sheets look the same state-by-state. Say so with the numbers.+- Stop after 5 rounds without progress on a row, or when the remaining difference is outside your control (font licence, WebGL shader, third-party embed, physics you approximated). Report the row, its last numbers, and the reason. Never relax thresholds silently; if you think the user would accept a looser bar, say which and why.+- If the reference itself is inconsistent between captures (randomised content, A/B variants, network-dependent lazy loading), capture it twice and compare it against itself to learn the noise floor before judging the clone.++## Report block++```markdown+## Verification (round N of M)+| element / property | timing err (start/end/dur) | easing (ref → clone) | mismatch mean / worst | result |+| h1 translateY+opacity | +0.00 / −0.04 / −0.04 s | easeOutExpo 700 → easeOutExpo 700 | 0.3 % / 1.1 % | pass |+Sheets: .motion-clone/<name>/compare-N/sheets/compare-01.png …+Residuals: <none | row, numbers, reason>+```diff --git a/scripts/bun.lock b/scripts/bun.locknew file mode 100644index 0000000..134f135--- /dev/null+++ b/scripts/bun.lock@@ -0,0 +1,64 @@+{+ "lockfileVersion": 2,+ "configVersion": 1,+ "workspaces": {+ "": {+ "name": "motion-clone-scripts",+ "dependencies": {+ "ffmpeg-static": "^5.2.0",+ "pixelmatch": "^8.0.0",+ "playwright": "1.64.1",+ "pngjs": "^7.0.0",+ },+ },+ },+ "packages": {+ "@derhuerst/http-basic": ["@derhuerst/[email protected]", "", { "dependencies": { "caseless": "^0.12.0", "concat-stream": "^2.0.0", "http-response-object": "^3.0.1", "parse-cache-control": "^1.0.1" } }, "sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw=="],++ "@types/node": ["@types/[email protected]", "", {}, "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw=="],++ "agent-base": ["[email protected]", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="],++ "buffer-from": ["[email protected]", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],++ "caseless": ["[email protected]", "", {}, "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw=="],++ "concat-stream": ["[email protected]", "", { "dependencies": { "buffer-from": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.0.2", "typedarray": "^0.0.6" } }, "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A=="],++ "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],++ "env-paths": ["[email protected]", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],++ "ffmpeg-static": ["[email protected]", "", { "dependencies": { "@derhuerst/http-basic": "^8.2.0", "env-paths": "^2.2.0", "https-proxy-agent": "^5.0.0", "progress": "^2.0.3" } }, "sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg=="],++ "http-response-object": ["[email protected]", "", { "dependencies": { "@types/node": "^10.0.3" } }, "sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA=="],++ "https-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "6", "debug": "4" } }, "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA=="],++ "inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],++ "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],++ "parse-cache-control": ["[email protected]", "", {}, "sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg=="],++ "pixelmatch": ["[email protected]", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-cIqOLfh5k52us715qf3B3+kTOxZv+WDv77HN7xokLScYQGYQHi4m/ynoDIPpvF2LvCyUJGyvzY64i0QCXtzu1g=="],++ "playwright": ["[email protected]", "", { "dependencies": { "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" } }, "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA=="],++ "playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],++ "pngjs": ["[email protected]", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="],++ "progress": ["[email protected]", "", {}, "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA=="],++ "readable-stream": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],++ "safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],++ "string_decoder": ["[email protected]", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],++ "typedarray": ["[email protected]", "", {}, "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA=="],++ "util-deprecate": ["[email protected]", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],+ }+}diff --git a/scripts/capture.ts b/scripts/capture.tsnew file mode 100644index 0000000..8e39cd7--- /dev/null+++ b/scripts/capture.ts@@ -0,0 +1,313 @@+// Capture a web page (reference or your clone) the same way every time:+// video + extracted frames, an inspection dump (animations, keyframes, styles, fonts, libraries)+// and a per-frame track of chosen elements (position, size, opacity, transform).+//+// Usage: bun capture.ts --url <url|file.html> --out <dir> [options]+import { chromium, type Page } from "playwright";+import { join } from "node:path";+import { existsSync, readFileSync, renameSync, readdirSync, statSync } from "node:fs";+import { ensureDir, ffmpeg, num, pad, parseArgs, parseRect, parseSize, usage, writeJson, abs } from "./lib.ts";++const HELP = `+capture.ts — record a page and dump everything needed to clone its motion.++ bun capture.ts --url <url|file.html> --out <dir> [options]++Window+ --viewport WxH viewport, default 1440x900 (use the same for reference and clone)+ --scale N deviceScaleFactor, default 1+ --color-scheme S light | dark+ --reduced-motion S no-preference (default) | reduce++What to look at+ --selector CSS element to scroll into view and crop frames to (default: whole viewport)+ --pad PX extra margin around the selector crop, default 0+ --clip x,y,w,h explicit crop in CSS px (overrides --selector crop)++How to start the motion+ --trigger T load (default) | scroll | hover | leave | move | drag | click | none+ load: the window starts at navigation (page-load animations)+ scroll: wheel the page in steps so scroll-reveal / scroll-linked motion plays+ hover / click: act on --target (default: --selector)+ leave: move the pointer off whatever it is on (hover-out); pair with --pre-hover+ move: glide the pointer through --path inside --target (pointer-follow effects)+ drag: like move, with the button held: down at the first --path point, glide, up at the last+ none: just record (loops, marquees, idle animations)+ --target CSS element to hover/click/move over+ --hover-at FX,FY where to put the pointer on --target, as fractions of its box (default 0.5,0.5)+ --pre-hover CSS hover this element before the trigger (uses --hover-at) and wait --pre-hover-ms+ --pre-hover-ms MS default 1500+ --leave-to X,Y viewport point the pointer moves to for --trigger leave, default <width/2>,8+ --path "FX,FY;…" move/drag trigger: fractional points inside --target, visited in order+ --path-ms MS move/drag trigger: time spent between two points, default 400 (20 pointer steps each)+ --scroll-to PX|CSS scroll position (or element) to reach during a scroll trigger;+ default for scroll: bring --selector into view from just below the fold+ --scroll-ms MS how long the stepped scroll takes, default 600+ --scroll-steps N wheel steps, default 12+ --wait-before MS settle time after load before the trigger, default 800+ --pre-js FILE|CODE JS to run after load, before the trigger (dismiss banners, open a menu…)+ --duration MS how long to record after the trigger, default 3000+ --pre-roll MS frames to keep before the trigger, default 200++Output+ --fps N extracted frame rate, default 25 (the video is 25 fps; higher only helps with --playback-rate)+ --playback-rate R slow CSS/WAAPI animations with CDP (0.25 = 4x slower). JS-driven motion is not affected.+ --track "CSS, CSS" elements sampled every animation frame → track.json (default: --selector, if any)+ --no-video skip the video and frames (inspection + track only)+ --headed show the browser (needs a display)++Writes to <out>/: video.webm, frames/NNNN.png, frames.json, inspect.json, track.json, capture.json+`;++const a = parseArgs(process.argv.slice(2));+if (a.help || !a.url || !a.out) usage(HELP);++const out = ensureDir(abs(a.out));+const viewport = parseSize(a.viewport, { width: 1440, height: 900 });+const scale = num(a.scale, 1);+const fps = num(a.fps, 25);+const rate = num(a["playback-rate"], 1);+const duration = num(a.duration, 3000);+const preRoll = num(a["pre-roll"], 200);+const waitBefore = num(a["wait-before"], 800);+const trigger: string = a.trigger || "load";+const selector: string | undefined = a.selector;+const target: string | undefined = a.target || selector;+const padPx = num(a.pad, 0);+const wantVideo = !a["no-video"];+const trackSelectors: string[] = (a.track ? String(a.track) : selector || "").split(",").map((s) => s.trim()).filter(Boolean);+let url: string = String(a.url);+if (!/^[a-z]+:/i.test(url)) url = "file://" + abs(url);++const hoverAt = String(a["hover-at"] ?? "0.5,0.5").split(",").map(Number);+const preHover: string | undefined = a["pre-hover"] ? String(a["pre-hover"]) : undefined;+const preHoverMs = num(a["pre-hover-ms"], 1500);+const leaveTo = a["leave-to"] ? String(a["leave-to"]).split(",").map(Number) : [viewport.width / 2, 8];+const movePath = String(a.path ?? "0.5,0.5").split(";").map((p) => p.split(",").map(Number));+const pathMs = num(a["path-ms"], 400);+async function pointAt(page: Page, sel: string, fx: number, fy: number) {+ const b = await page.locator(sel).first().boundingBox();+ if (!b) throw new Error(`not visible: ${sel}`);+ return { x: b.x + b.width * fx, y: b.y + b.height * fy };+}++const preJs = a["pre-js"] ? (existsSync(String(a["pre-js"])) ? readFileSync(String(a["pre-js"]), "utf8") : String(a["pre-js"])) : undefined;++// ---------- in-page tracker (installed before any script runs so load-triggered motion is caught) ----------+const TRACKER = `(() => {+ const sels = __SELS__;+ const w = window;+ w.__mc = { samples: [], t0: null, running: true };+ const sample = () => {+ if (!w.__mc.running) return;+ const t = performance.now();+ const els = {};+ for (const s of sels) {+ let el = null; try { el = document.querySelector(s); } catch {}+ if (!el) { els[s] = null; continue; }+ const r = el.getBoundingClientRect();+ const cs = getComputedStyle(el);+ els[s] = { x: +r.x.toFixed(2), y: +r.y.toFixed(2), w: +r.width.toFixed(2), h: +r.height.toFixed(2),+ opacity: +(+cs.opacity).toFixed(3), transform: cs.transform, clipPath: cs.clipPath === 'none' ? undefined : cs.clipPath };+ }+ w.__mc.samples.push({ t, scrollY: w.scrollY, els });+ requestAnimationFrame(sample);+ };+ requestAnimationFrame(sample);+})();`;++// ---------- inspection (run after the motion so getAnimations() has seen everything) ----------+const INSPECT = `(sel) => {+ const desc = (el) => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.classList.length ? '.' + [...el.classList].slice(0, 4).join('.') : '');+ const root = sel ? document.querySelector(sel) : document.body;+ const w = window;+ const libs = [];+ const has = (c) => { try { return !!c(); } catch { return false; } };+ if (has(() => w.gsap)) libs.push('gsap' + (has(() => w.ScrollTrigger) ? '+ScrollTrigger' : ''));+ if (has(() => w.lottie || w.bodymovin || document.querySelector('lottie-player,dotlottie-player,[data-lottie],.lottie'))) libs.push('lottie');+ if (has(() => w.THREE || [...document.querySelectorAll('canvas')].some(c => c.getContext && (c.getContext('webgl2') || c.getContext('webgl'))))) libs.push('webgl/three');+ if (has(() => w.rive || document.querySelector('canvas[data-rive], .rive-canvas'))) libs.push('rive');+ if (has(() => w.anime)) libs.push('anime.js');+ if (has(() => w.Lenis || document.documentElement.classList.contains('lenis'))) libs.push('lenis smooth-scroll');+ if (has(() => w.Webflow || document.querySelector('[data-wf-page]'))) libs.push('webflow');+ if (has(() => document.querySelector('[data-framer-name],[data-framer-component-type]'))) libs.push('framer-sites');+ if (has(() => document.querySelector('[data-projection-id],[data-framer-appear-id]') || [...document.scripts].some(s => /framer-motion|motion-dom/.test(s.src)))) libs.push('framer-motion/motion');+ if (has(() => w.__NEXT_DATA__ || document.getElementById('__next'))) libs.push('next.js');+ if (has(() => w.__nuxt)) libs.push('nuxt');+ if (has(() => document.querySelector('astro-island'))) libs.push('astro');+ if (has(() => document.querySelector('.swiper, .splide, .slick-slider, .embla'))) libs.push('carousel lib');+ if (has(() => [...document.styleSheets].some(s => { try { return [...s.cssRules].some(r => r.cssText.includes('animation-timeline')) } catch { return false } }))) libs.push('css scroll-driven animations');++ const fonts = [...new Set([...document.fonts].filter(f => f.status === 'loaded').map(f => f.family.replace(/"/g, '') + ' ' + f.weight + ' ' + f.style))];++ const keyframes = [];+ for (const sheet of document.styleSheets) {+ let rules; try { rules = sheet.cssRules; } catch { keyframes.push({ unreadable: sheet.href }); continue; }+ const walk = (list) => { for (const r of list) { if (r.type === 7) keyframes.push({ name: r.name, css: r.cssText }); else if (r.cssRules) walk(r.cssRules); } };+ walk(rules);+ }++ const anims = (root ? root.getAnimations({ subtree: true }) : document.getAnimations()).slice(0, 200).map(an => {+ const eff = an.effect; const tgt = eff && eff.target;+ let kf = []; try { kf = eff.getKeyframes().slice(0, 24).map(k => { const o = {}; for (const [p, v] of Object.entries(k)) if (p !== 'computedOffset' && p !== 'composite') o[p] = v; return o; }); } catch {}+ return { kind: an.constructor.name, name: an.animationName || an.transitionProperty || an.id || '', target: tgt ? desc(tgt) : null,+ timing: eff ? eff.getTiming() : null, keyframes: kf, playState: an.playState, currentTime: an.currentTime,+ timeline: an.timeline && an.timeline.constructor.name };+ });++ const PROPS = ['opacity','transform','transform-origin','transition','animation','will-change','color','background-color','background-image','font-family','font-size','font-weight','line-height','letter-spacing','border-radius','box-shadow','filter','backdrop-filter','clip-path','overflow','position','display','gap','padding','mask-image'];+ const nodes = [];+ if (root) {+ const all = [root, ...root.querySelectorAll('*')].slice(0, 150);+ for (const el of all) {+ const cs = getComputedStyle(el); const r = el.getBoundingClientRect();+ if (r.width === 0 && r.height === 0) continue;+ const style = {}; for (const p of PROPS) { const v = cs.getPropertyValue(p); if (!v || v === 'none' || v === 'normal' || v === 'auto' || v === 'static' || v === 'visible' || v === '0px' || v === 'all' || v === 'all 0s ease 0s' || v === 'rgba(0, 0, 0, 0)') continue; if (p === 'opacity' && v === '1') continue; if (p === 'transform' && v === 'matrix(1, 0, 0, 1, 0, 0)') continue; if (p === 'transform-origin') continue; style[p] = v; }+ const text = el.childElementCount === 0 ? (el.textContent || '').trim().slice(0, 60) : undefined;+ nodes.push({ el: desc(el), rect: [Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height)], text, style,+ src: el.currentSrc || el.src || undefined });+ }+ }+ const rect = root ? root.getBoundingClientRect() : null;+ return { url: location.href, title: document.title, viewport: [innerWidth, innerHeight], scrollY, devicePixelRatio, libs, fonts,+ target: sel ? { selector: sel, found: !!root, rect: rect && [Math.round(rect.x), Math.round(rect.y), Math.round(rect.width), Math.round(rect.height)] } : null,+ animations: anims, keyframes, nodes };+}`;++async function runTrigger(page: Page): Promise<number> {+ const now = () => Date.now();+ switch (trigger) {+ case "load": return now(); // handled by the caller: the window starts at navigation+ case "none": return now();+ case "hover": { if (!target) throw new Error("--target or --selector needed for hover"); const pt = await pointAt(page, target, hoverAt[0], hoverAt[1]); const t = now(); await page.mouse.move(pt.x, pt.y); return t; }+ case "leave": { const t = now(); await page.mouse.move(leaveTo[0], leaveTo[1]); return t; }+ case "move": {+ if (!target) throw new Error("--target or --selector needed for move");+ const pts = [] as { x: number; y: number }[];+ for (const [fx, fy] of movePath) pts.push(await pointAt(page, target, fx, fy));+ await page.mouse.move(pts[0].x, pts[0].y);+ const t = now();+ for (let i = 1; i < pts.length; i++) {+ for (let k = 1; k <= 20; k++) { const f = k / 20; await page.mouse.move(pts[i - 1].x + (pts[i].x - pts[i - 1].x) * f, pts[i - 1].y + (pts[i].y - pts[i - 1].y) * f); await page.waitForTimeout(pathMs / 20); }+ }+ return t;+ }+ case "drag": {+ if (!target) throw new Error("--target or --selector needed for drag");+ const pts = [] as { x: number; y: number }[];+ for (const [fx, fy] of movePath) pts.push(await pointAt(page, target, fx, fy));+ await page.mouse.move(pts[0].x, pts[0].y);+ const t = now();+ await page.mouse.down();+ for (let i = 1; i < pts.length; i++) {+ for (let k = 1; k <= 20; k++) { const f = k / 20; await page.mouse.move(pts[i - 1].x + (pts[i].x - pts[i - 1].x) * f, pts[i - 1].y + (pts[i].y - pts[i - 1].y) * f); await page.waitForTimeout(pathMs / 20); }+ }+ await page.mouse.up(); // released while still moving, so fling/inertia code sees a velocity+ return t;+ }+ case "click": { if (!target) throw new Error("--target or --selector needed for click"); const t = now(); await page.click(target, { timeout: 10000, noWaitAfter: true }); return t; }+ case "scroll": {+ const steps = num(a["scroll-steps"], 12);+ const ms = num(a["scroll-ms"], 600);+ const from = await page.evaluate(() => window.scrollY);+ let to: number;+ if (a["scroll-to"] !== undefined && a["scroll-to"] !== true && /^\d+$/.test(String(a["scroll-to"]))) to = Number(a["scroll-to"]);+ else {+ const sel = (a["scroll-to"] && a["scroll-to"] !== true) ? String(a["scroll-to"]) : selector;+ if (!sel) throw new Error("--scroll-to or --selector needed for a scroll trigger");+ to = await page.evaluate((s) => { const el = document.querySelector(s); if (!el) throw new Error("not found: " + s); return window.scrollY + el.getBoundingClientRect().top - innerHeight * 0.25; }, sel);+ }+ const t = now();+ const delta = (to - from) / steps;+ await page.mouse.move(viewport.width / 2, viewport.height / 2);+ for (let i = 0; i < steps; i++) { await page.mouse.wheel(0, delta); await page.waitForTimeout(ms / steps); }+ return t;+ }+ default: throw new Error(`unknown trigger ${trigger}`);+ }+}++const browser = await chromium.launch({ headless: !a.headed });+const context = await browser.newContext({+ viewport, deviceScaleFactor: scale,+ colorScheme: a["color-scheme"] || undefined,+ reducedMotion: a["reduced-motion"] || "no-preference",+ recordVideo: wantVideo ? { dir: join(out, ".video"), size: viewport } : undefined,+});+if (trackSelectors.length) await context.addInitScript(TRACKER.replace("__SELS__", JSON.stringify(trackSelectors)));+const page = await context.newPage();+const tPageCreated = Date.now();+if (rate !== 1) {+ const cdp = await context.newCDPSession(page);+ await cdp.send("Animation.enable");+ await cdp.send("Animation.setPlaybackRate", { playbackRate: rate });+}++let tTrigger = Date.now();+let perfAtTrigger: number | null = null; // page clock at the trigger, so track.json has t=0 at the trigger+await page.goto(url, { waitUntil: trigger === "load" ? "commit" : "load", timeout: 60000 });+if (trigger !== "load") {+ await page.waitForTimeout(waitBefore);+ if (preJs) await page.evaluate(preJs);+ if (selector && trigger !== "scroll") {+ const found = await page.$(selector);+ if (!found) throw new Error(`selector not found: ${selector}`);+ await found.scrollIntoViewIfNeeded();+ await page.waitForTimeout(300);+ } else if (trigger === "scroll" && selector) {+ // start just below the fold so the element enters the viewport during the scroll+ await page.evaluate((s) => { const el = document.querySelector(s); if (el) window.scrollTo(0, Math.max(0, window.scrollY + el.getBoundingClientRect().top - innerHeight - 20)); }, selector);+ await page.waitForTimeout(300);+ }+ if (preHover) { const pt = await pointAt(page, preHover, hoverAt[0], hoverAt[1]); await page.mouse.move(pt.x, pt.y); await page.waitForTimeout(preHoverMs); }+ perfAtTrigger = await page.evaluate(() => performance.now());+ tTrigger = await runTrigger(page);+}+await page.waitForTimeout(duration / rate);++// crop rect, measured after the motion (use --clip if the element moves a lot)+let clip = parseRect(a.clip);+if (!clip && selector) {+ const r = await page.evaluate((s) => { const el = document.querySelector(s); if (!el) return null; const b = el.getBoundingClientRect(); return { x: b.x, y: b.y, width: b.width, height: b.height }; }, selector);+ if (r) clip = { x: Math.max(0, Math.floor(r.x - padPx)), y: Math.max(0, Math.floor(r.y - padPx)), width: Math.ceil(Math.min(viewport.width - r.x + padPx, r.width + 2 * padPx)), height: Math.ceil(Math.min(viewport.height - r.y + padPx, r.height + 2 * padPx)) };+}++const track = trackSelectors.length ? await page.evaluate(() => { const m = (window as any).__mc; m.running = false; return m.samples; }) : [];+const inspect: any = await page.evaluate(`(${INSPECT})(${JSON.stringify(selector ?? null)})`);+await page.screenshot({ path: join(out, "final.png"), clip: clip && clip.width > 0 && clip.height > 0 ? clip : undefined });+await context.close();+await browser.close();++// ---------- video → frames ----------+let frames: any = null;+if (wantVideo) {+ const vdir = join(out, ".video");+ const webm = readdirSync(vdir).filter((f) => f.endsWith(".webm")).map((f) => join(vdir, f)).sort((x, y) => statSync(y).mtimeMs - statSync(x).mtimeMs)[0];+ if (!webm) throw new Error("no video recorded");+ renameSync(webm, join(out, "video.webm"));+ const framesDir = ensureDir(join(out, "frames"));+ for (const f of readdirSync(framesDir)) if (f.endsWith(".png")) require("node:fs").unlinkSync(join(framesDir, f));+ // the video clock starts at page creation; the trigger offset is wall-clock, refine with compare.ts --auto-align+ const triggerOffset = Math.max(0, (tTrigger - tPageCreated) / 1000 - preRoll / 1000);+ const videoFps = fps * rate; // frames per *video* second so that timestamps map to reference time+ const vf = [`fps=${videoFps}`];+ if (clip) vf.push(`crop=${Math.round(clip.width * scale)}:${Math.round(clip.height * scale)}:${Math.round(clip.x * scale)}:${Math.round(clip.y * scale)}`);+ ffmpeg(["-y", "-ss", triggerOffset.toFixed(3), "-i", join(out, "video.webm"), "-t", ((duration + preRoll) / rate / 1000).toFixed(3), "-vf", vf.join(","), join(framesDir, "%04d.png")], { quiet: true });+ const count = readdirSync(framesDir).filter((f) => f.endsWith(".png")).length;+ frames = { fps, count, playbackRate: rate, preRollMs: preRoll, triggerFrame: Math.round((preRoll / 1000) * fps), clip, viewport, scale, note: "frame i is at t = i/fps seconds of reference time, with t=0 at preRoll before the trigger" };+ writeJson(join(out, "frames.json"), frames);+}++// normalise track time: t=0 at the trigger (for --trigger load, at the first animation frame of the document)+const t0 = perfAtTrigger ?? (track.length ? track[0].t : 0);+const trackOut = { selectors: trackSelectors, playbackRate: rate, note: "t in ms of reference time, 0 = trigger; negative samples are before it",+ samples: track.map((s: any) => ({ ...s, t: +((s.t - t0) * rate).toFixed(1) })) };+if (trackSelectors.length) writeJson(join(out, "track.json"), trackOut);+writeJson(join(out, "inspect.json"), inspect);+writeJson(join(out, "capture.json"), { url, out, viewport, scale, fps, rate, trigger, target, selector, clip, duration, preRoll, waitBefore, scrollTo: a["scroll-to"], track: trackSelectors, capturedAt: new Date().toISOString() });++console.log(JSON.stringify({+ out, frames: frames && { count: frames.count, fps, triggerFrame: frames.triggerFrame, clip },+ libs: inspect.libs, fonts: inspect.fonts.slice(0, 8), animations: inspect.animations.length, keyframes: inspect.keyframes.length,+ target: inspect.target, trackSamples: track.length, trackSelectors,+}, null, 2));diff --git a/scripts/compare.ts b/scripts/compare.tsnew file mode 100644index 0000000..af26a5c--- /dev/null+++ b/scripts/compare.ts@@ -0,0 +1,156 @@+// Compare the clone's frames against the reference's, frame by frame.+// Produces per-frame mismatch (pixel diff), an "activity curve" (how much changes between consecutive+// frames, which captures timing and easing regardless of colours or copy), diff images, and a report.+// Usage: bun compare.ts --ref <frames dir> --clone <frames dir> --out <dir> [--auto-align] [--threshold 0.05]+import { PNG } from "pngjs";+import pixelmatch from "pixelmatch";+import { join } from "node:path";+import { existsSync, readFileSync, writeFileSync, unlinkSync, readdirSync } from "node:fs";+import { abs, ensureDir, ffmpeg, listFrames, num, parseArgs, parseRect, readJson, usage, writeJson, pad } from "./lib.ts";++const HELP = `+compare.ts — frame-by-frame comparison of clone vs reference.++ bun compare.ts --ref <dir> --clone <dir> --out <dir> [options]++ --auto-align find the clone frame offset (±--max-shift) that best matches the reference start, default on+ --offset K fixed offset instead (clone frame = ref frame + K)+ --max-shift N search range for auto-align, default 15 frames+ --region x,y,w,h only compare this region (in reference pixel coordinates)+ --pixel-threshold T pixelmatch colour sensitivity 0..1, default 0.1 (raise to ignore anti-aliasing/noise)+ --threshold T pass if mean mismatch ≤ T (fraction of pixels), default 0.05; use 0.01-0.02 for pixel fidelity+ --motion-threshold T pass if activity-curve timing error ≤ T seconds, default 0.08+ --fps N frames per second (default: frames.json beside --ref, else 25)+ --no-diffs skip writing diff PNGs++Output in <out>/: report.json, report.md, diff/NNNN.png (red = differing pixels)+Both frame sets must share fps and be clipped to the same region; the clone is rescaled to the reference size if needed.+`;++const a = parseArgs(process.argv.slice(2));+if (a.help || !a.ref || !a.clone || !a.out) usage(HELP);+const refDir = abs(String(a.ref)), cloneDir = abs(String(a.clone)), out = ensureDir(abs(String(a.out)));+const fps = num(a.fps, existsSync(join(refDir, "frames.json")) ? Number(readJson(join(refDir, "frames.json")).fps) || 25 : 25);+const pixelThreshold = num(a["pixel-threshold"], 0.1);+const threshold = num(a.threshold, 0.05);+const motionThreshold = num(a["motion-threshold"], 0.08);+const region = parseRect(a.region);+const wantDiffs = !a["no-diffs"];++const refFiles = listFrames(refDir);+let cloneFiles = listFrames(cloneDir);+if (!refFiles.length || !cloneFiles.length) throw new Error("no frames found");++const readPng = (p: string) => PNG.sync.read(readFileSync(p));+const ref0 = readPng(refFiles[0]);+const c0 = readPng(cloneFiles[0]);+// rescale the clone set once if sizes differ (keeps the comparison honest, but prefer capturing at the same size)+if (c0.width !== ref0.width || c0.height !== ref0.height) {+ const scaled = ensureDir(join(out, ".clone-scaled"));+ for (const f of readdirSync(scaled)) unlinkSync(join(scaled, f));+ console.error(`clone frames are ${c0.width}x${c0.height}, reference ${ref0.width}x${ref0.height}: rescaling clone`);+ cloneFiles.forEach((p, i) => ffmpeg(["-y", "-i", p, "-vf", `scale=${ref0.width}:${ref0.height}:flags=lanczos`, join(scaled, `${pad(i)}.png`)], { quiet: true }));+ cloneFiles = listFrames(scaled);+}+const W = ref0.width, H = ref0.height;++function crop(img: PNG): PNG {+ if (!region) return img;+ const o = new PNG({ width: region.width, height: region.height });+ PNG.bitblt(img, o, region.x, region.y, region.width, region.height, 0, 0);+ return o;+}+function mismatch(aP: PNG, bP: PNG, diff?: PNG): number {+ const n = pixelmatch(aP.data, bP.data, diff?.data, aP.width, aP.height, { threshold: pixelThreshold, includeAA: false });+ return n / (aP.width * aP.height);+}++// cache decoded + cropped frames (frames are small after clipping; fine for a few hundred)+const refImgs = refFiles.map((p) => crop(readPng(p)));+const cloneImgs = cloneFiles.map((p) => crop(readPng(p)));++// ---- activity curve: change between consecutive frames, per set ----+function activity(imgs: PNG[]): number[] {+ const out: number[] = [0];+ for (let i = 1; i < imgs.length; i++) out.push(mismatch(imgs[i - 1], imgs[i]));+ return out;+}+const refAct = activity(refImgs), cloneAct = activity(cloneImgs);+function motionWindow(act: number[], floor = 0.002) {+ // first and last frame where something visibly changes+ let first = -1, last = -1;+ act.forEach((v, i) => { if (v > floor) { if (first < 0) first = i; last = i; } });+ const peak = act.indexOf(Math.max(...act));+ return { first, last, peak, durationS: first < 0 ? 0 : (last - first + 1) / fps };+}++// ---- alignment ----+let offset = a.offset !== undefined ? num(a.offset, 0) : 0;+if (a.offset === undefined && !(a["auto-align"] === "false")) {+ const maxShift = num(a["max-shift"], 15);+ const probeN = Math.min(10, refImgs.length);+ let best = Infinity;+ for (let k = -maxShift; k <= maxShift; k++) {+ let sum = 0, n = 0;+ for (let i = 0; i < probeN; i++) { const j = i + k; if (j < 0 || j >= cloneImgs.length) continue; sum += mismatch(refImgs[i], cloneImgs[j]); n++; }+ if (n >= Math.min(5, probeN) && sum / n < best) { best = sum / n; offset = k; }+ }+}++// ---- per-frame mismatch + diffs ----+const diffDir = wantDiffs ? ensureDir(join(out, "diff")) : undefined;+if (diffDir) for (const f of readdirSync(diffDir)) if (f.endsWith(".png")) unlinkSync(join(diffDir, f));+const frames: { i: number; t: number; cloneIndex: number | null; mismatch: number | null }[] = [];+for (let i = 0; i < refImgs.length; i++) {+ const j = i + offset;+ if (j < 0 || j >= cloneImgs.length) { frames.push({ i, t: +(i / fps).toFixed(3), cloneIndex: null, mismatch: null }); continue; }+ const diff = diffDir ? new PNG({ width: refImgs[i].width, height: refImgs[i].height }) : undefined;+ const m = mismatch(refImgs[i], cloneImgs[j], diff);+ if (diff && diffDir) writeFileSync(join(diffDir, `${pad(i)}.png`), PNG.sync.write(diff));+ frames.push({ i, t: +(i / fps).toFixed(3), cloneIndex: j, mismatch: +m.toFixed(4) });+}+const compared = frames.filter((f) => f.mismatch !== null) as { i: number; t: number; mismatch: number }[];+const mean = compared.reduce((s, f) => s + f.mismatch, 0) / Math.max(1, compared.length);+const worst = [...compared].sort((x, y) => y.mismatch - x.mismatch).slice(0, 5);+const refWin = motionWindow(refAct), cloneWin = motionWindow(cloneAct.slice(Math.max(0, offset)));+const timingError = {+ startS: +((cloneWin.first - refWin.first) / fps).toFixed(3),+ endS: +((cloneWin.last - refWin.last) / fps).toFixed(3),+ peakS: +((cloneWin.peak - refWin.peak) / fps).toFixed(3),+ durationS: +(cloneWin.durationS - refWin.durationS).toFixed(3),+};+const maxTimingErr = Math.max(Math.abs(timingError.startS), Math.abs(timingError.endS), Math.abs(timingError.durationS));+const pass = { pixels: mean <= threshold, timing: maxTimingErr <= motionThreshold };++const report = {+ fps, size: [W, H], region, offset, threshold, motionThreshold, pixelThreshold,+ frames: frames.length, compared: compared.length,+ meanMismatch: +mean.toFixed(4), maxMismatch: worst[0]?.mismatch ?? 0, worstFrames: worst,+ motion: { reference: refWin, clone: cloneWin, timingError },+ activity: { reference: refAct.map((v) => +v.toFixed(4)), clone: cloneAct.map((v) => +v.toFixed(4)) },+ pass,+ frameDetails: frames,+};+writeJson(join(out, "report.json"), report);++const bar = (v: number) => "█".repeat(Math.min(40, Math.round(v * 400))) || "·";+const md = [+ `# compare: ${refDir} vs ${cloneDir}`,+ ``,+ `- frames compared: ${compared.length}/${frames.length} at ${fps} fps, clone offset ${offset}`,+ `- mean mismatch: **${(mean * 100).toFixed(2)}%** (threshold ${(threshold * 100).toFixed(1)}%) → ${pass.pixels ? "PASS" : "FAIL"}`,+ `- motion window — reference: frames ${refWin.first}–${refWin.last} (${refWin.durationS.toFixed(2)}s, peak #${refWin.peak}); clone: ${cloneWin.first}–${cloneWin.last} (${cloneWin.durationS.toFixed(2)}s, peak #${cloneWin.peak})`,+ `- timing error (clone − ref): start ${timingError.startS}s, end ${timingError.endS}s, duration ${timingError.durationS}s, peak ${timingError.peakS}s → ${pass.timing ? "PASS" : "FAIL"} (limit ${motionThreshold}s)`,+ `- worst frames: ${worst.map((w) => `#${w.i} (${(w.mismatch * 100).toFixed(1)}% @ ${w.t}s)`).join(", ")}`,+ ``,+ `## activity per frame (how much changed since the previous frame)`,+ ``,+ "```",+ `frame t(s) reference clone`,+ ...frames.map((f) => `${String(f.i).padStart(5)} ${f.t.toFixed(2).padStart(6)} ${bar(refAct[f.i]).padEnd(40)} ${f.cloneIndex === null ? "" : bar(cloneAct[f.cloneIndex])}`),+ "```",+ ``,+ `Diff images: ${diffDir ?? "(skipped)"} — red pixels differ. Build labelled sheets with sheet.ts compare.`,+].join("\n");+writeFileSync(join(out, "report.md"), md + "\n");+console.log(md);diff --git a/scripts/easing.ts b/scripts/easing.tsnew file mode 100644index 0000000..63b4af0--- /dev/null+++ b/scripts/easing.ts@@ -0,0 +1,129 @@+// Fit a recorded motion curve to known easings and report duration, delay and overshoot.+// Input: a track.json from capture.ts (choose selector + property) or a plain JSON array of [t_ms, value].+// Usage: bun easing.ts --track <track.json> --selector ".hero h1" --prop y+// bun easing.ts --series '[[0,0],[100,12],[200,40],...]'+import { readJson, parseArgs, usage, num } from "./lib.ts";++const HELP = `+easing.ts — which easing is this?++ bun easing.ts --track <track.json> --selector <css> --prop <x|y|w|h|opacity|scale|translateX|translateY|rotate> [--from-ms T --to-ms T]+ bun easing.ts --series '[[t_ms, value], ...]'+ bun easing.ts --track <track.json> --selector <css> --prop y --compare-track <other.json> # also diffs two tracks++Prints: start/end values, delay (first change), duration (first → last change), overshoot, and the best-fitting+named easings with their RMSE. Use the top match as the CSS/Framer/GSAP easing in the clone, then re-run on the+clone's track to confirm the curve matches.+`;++const a = parseArgs(process.argv.slice(2));+if (a.help || (!a.track && !a.series)) usage(HELP);++function matrixPart(transform: string): { tx: number; ty: number; sx: number; sy: number; rot: number } {+ if (!transform || transform === "none") return { tx: 0, ty: 0, sx: 1, sy: 1, rot: 0 };+ const m = transform.match(/matrix(3d)?\(([^)]+)\)/);+ if (!m) return { tx: 0, ty: 0, sx: 1, sy: 1, rot: 0 };+ const v = m[2].split(",").map(Number);+ if (m[1]) return { tx: v[12], ty: v[13], sx: Math.hypot(v[0], v[1]), sy: Math.hypot(v[4], v[5]), rot: (Math.atan2(v[1], v[0]) * 180) / Math.PI };+ return { tx: v[4], ty: v[5], sx: Math.hypot(v[0], v[1]), sy: Math.hypot(v[2], v[3]), rot: (Math.atan2(v[1], v[0]) * 180) / Math.PI };+}++function seriesFromTrack(path: string, selector: string, prop: string): [number, number][] {+ const t = readJson(path);+ const outS: [number, number][] = [];+ for (const s of t.samples) {+ const e = s.els?.[selector];+ if (!e) continue;+ const mp = matrixPart(e.transform);+ const v: Record<string, number> = { x: e.x, y: e.y, w: e.w, h: e.h, opacity: e.opacity, translateX: mp.tx, translateY: mp.ty, scale: mp.sx, scaleX: mp.sx, scaleY: mp.sy, rotate: mp.rot };+ if (!(prop in v)) throw new Error(`unknown prop ${prop}; use one of ${Object.keys(v).join(", ")}`);+ outS.push([s.t, v[prop]]);+ }+ return outS;+}++let series: [number, number][] = a.series ? JSON.parse(String(a.series)) : seriesFromTrack(String(a.track), String(a.selector), String(a.prop || "y"));+const fromMs = num(a["from-ms"], -Infinity), toMs = num(a["to-ms"], Infinity);+series = series.filter(([t]) => t >= fromMs && t <= toMs);+if (series.length < 4) { console.log("not enough samples (element missing from track, or window too narrow)"); process.exit(1); }++// bezier easings (CSS cubic-bezier) and a few others, sampled numerically+const bez = (x1: number, y1: number, x2: number, y2: number) => (t: number) => {+ // solve x(u)=t for u by bisection, return y(u)+ let lo = 0, hi = 1, u = t;+ for (let i = 0; i < 30; i++) { u = (lo + hi) / 2; const x = 3 * (1 - u) ** 2 * u * x1 + 3 * (1 - u) * u ** 2 * x2 + u ** 3; if (x < t) lo = u; else hi = u; }+ return 3 * (1 - u) ** 2 * u * y1 + 3 * (1 - u) * u ** 2 * y2 + u ** 3;+};+const EASINGS: Record<string, (t: number) => number> = {+ "linear": (t) => t,+ "ease": bez(0.25, 0.1, 0.25, 1), "ease-in": bez(0.42, 0, 1, 1), "ease-out": bez(0, 0, 0.58, 1), "ease-in-out": bez(0.42, 0, 0.58, 1),+ "cubic-bezier(0.4,0,0.2,1) material standard": bez(0.4, 0, 0.2, 1),+ "cubic-bezier(0.2,0,0,1) material emphasized": bez(0.2, 0, 0, 1),+ "cubic-bezier(0.16,1,0.3,1) easeOutExpo": bez(0.16, 1, 0.3, 1),+ "cubic-bezier(0.22,1,0.36,1) easeOutQuint": bez(0.22, 1, 0.36, 1),+ "cubic-bezier(0.33,1,0.68,1) easeOutCubic": bez(0.33, 1, 0.68, 1),+ "cubic-bezier(0.25,1,0.5,1) easeOutQuart": bez(0.25, 1, 0.5, 1),+ "cubic-bezier(0.5,1,0.89,1) easeOutQuad": bez(0.5, 1, 0.89, 1),+ "cubic-bezier(0.65,0,0.35,1) easeInOutCubic": bez(0.65, 0, 0.35, 1),+ "cubic-bezier(0.83,0,0.17,1) easeInOutQuint": bez(0.83, 0, 0.17, 1),+ "cubic-bezier(0.87,0,0.13,1) easeInOutExpo": bez(0.87, 0, 0.13, 1),+ "cubic-bezier(0.76,0,0.24,1) easeInOutQuart": bez(0.76, 0, 0.24, 1),+ "cubic-bezier(0.45,0,0.55,1) easeInOutQuad": bez(0.45, 0, 0.55, 1),+ "cubic-bezier(0.32,0,0.67,0) easeInCubic": bez(0.32, 0, 0.67, 0),+ "cubic-bezier(0.7,0,0.84,0) easeInExpo": bez(0.7, 0, 0.84, 0),+ "cubic-bezier(0.34,1.56,0.64,1) easeOutBack": bez(0.34, 1.56, 0.64, 1),+ "cubic-bezier(0.68,-0.6,0.32,1.6) easeInOutBack": bez(0.68, -0.6, 0.32, 1.6),+ "cubic-bezier(0.19,1,0.22,1) 'expo' (common in landing pages)": bez(0.19, 1, 0.22, 1),+ "cubic-bezier(0.77,0,0.175,1) 'power3.inOut' (gsap)": bez(0.77, 0, 0.175, 1),+ "cubic-bezier(0.075,0.82,0.165,1) easeOutCirc": bez(0.075, 0.82, 0.165, 1),+ "cubic-bezier(0.23,1,0.32,1) ease-out-quint variant": bez(0.23, 1, 0.32, 1),+};++const t0 = series[0][0];+const start = series[0][1], end = series[series.length - 1][1];+const range = end - start;+const eps = Math.max(Math.abs(range) * 0.01, 0.002);+let firstChange = series.findIndex(([, v]) => Math.abs(v - start) > eps);+let lastChange = series.length - 1;+for (let i = series.length - 1; i > 0; i--) if (Math.abs(series[i][1] - end) > eps) { lastChange = Math.min(series.length - 1, i + 1); break; }+if (firstChange < 1) firstChange = 1;+const delayMs = series[firstChange - 1][0] - t0;+const durMs = series[lastChange][0] - series[firstChange - 1][0];+const extremes = series.map(([, v]) => v);+const overshoot = range === 0 ? 0 : Math.max(0, (Math.max(...extremes.map((v) => (v - start) * Math.sign(range))) - Math.abs(range)) / Math.abs(range));++// Fit each easing with the duration as a free parameter (1x..2x the visible duration): expo-style curves have+// long tails that fall under the 1% change floor, so the declared duration is often longer than the visible one.+const fits: { name: string; rmse: number; durationMs: number }[] = [];+if (Math.abs(range) > 0 && durMs > 0) {+ const base = series[firstChange - 1][0];+ const raw = series.slice(firstChange - 1).map(([t, v]) => [t - base, (v - start) / range] as [number, number]);+ for (const [name, fn] of Object.entries(EASINGS)) {+ let best = { rmse: Infinity, durationMs: durMs };+ for (let k = 1; k <= 2.0001; k += 0.05) {+ const d = durMs * k;+ const pts = raw.filter(([t]) => t <= d * 1.05);+ const err = Math.sqrt(pts.reduce((s, [t, y]) => s + (fn(Math.min(1, Math.max(0, t / d))) - y) ** 2, 0) / pts.length);+ if (err < best.rmse) best = { rmse: err, durationMs: Math.round(d) };+ }+ fits.push({ name, rmse: +best.rmse.toFixed(4), durationMs: best.durationMs });+ }+ fits.sort((x, y) => x.rmse - y.rmse);+}++const result = {+ samples: series.length, start: +start.toFixed(3), end: +end.toFixed(3), change: +range.toFixed(3),+ delayMs: +delayMs.toFixed(0), visibleDurationMs: +durMs.toFixed(0), overshootPct: +(overshoot * 100).toFixed(1),+ verdict: overshoot > 0.02 ? "spring-like / back easing (overshoots)" : fits[0] ? `${fits[0].name} over ~${fits[0].durationMs}ms${fits[0].rmse < 0.03 ? " (good fit)" : fits[0].rmse < 0.08 ? " (approximate)" : " (poor fit: maybe multi-step, spring, or scroll-linked)"}` : "no motion",+ note: "visibleDurationMs = time until within 1% of the final value; durationMs in bestFits is the fitted declared duration",+ bestFits: fits.slice(0, 5),+};++if (a["compare-track"]) {+ const other = seriesFromTrack(String(a["compare-track"]), String(a.selector), String(a.prop || "y"));+ // both tracks have t=0 at their trigger, so compare at the same t (not from each track's first sample)+ const at = (s: [number, number][], t: number) => { let best = s[0]; for (const p of s) if (Math.abs(p[0] - t) < Math.abs(best[0] - t)) best = p; return best[1]; };+ const diffs = series.map(([t, v]) => +(at(other, t) - v).toFixed(2));+ (result as any).compare = { otherSamples: other.length, maxAbsDiff: Math.max(...diffs.map(Math.abs)), meanAbsDiff: +(diffs.reduce((s, d) => s + Math.abs(d), 0) / diffs.length).toFixed(2), sampledDiffs: diffs.filter((_, i) => i % Math.ceil(diffs.length / 20) === 0) };+}+console.log(JSON.stringify(result, null, 2));diff --git a/scripts/frames.ts b/scripts/frames.tsnew file mode 100644index 0000000..79fa31e--- /dev/null+++ b/scripts/frames.ts@@ -0,0 +1,56 @@+// Turn a video or gif (reference recording, screen capture, exported prototype) into numbered PNG frames.+// Usage: bun frames.ts --in <file> --out <dir> [--fps 10] [--start 0:03] [--end 0:08] [--crop x,y,w,h] [--width 800]+import { join } from "node:path";+import { readdirSync, unlinkSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { abs, ensureDir, ffmpeg, ffmpegPath, num, parseArgs, parseRect, parseTime, usage, writeJson } from "./lib.ts";++const HELP = `+frames.ts — extract frames from a video or gif.++ bun frames.ts --in <file.mp4|.mov|.webm|.gif> --out <dir> [options]++ --fps N frames per second to keep, default 10 (use 25-30 for fast motion, 5 for long slow sequences)+ --start T start time: "0:03", "3.5", "1500ms". default 0+ --end T end time (same formats). default: end of file+ --crop x,y,w,h crop in source pixels (find values on a full frame first)+ --width W downscale frames to this width (keeps aspect). default: source size+ --probe only print the source's duration, size and fps, extract nothing++Writes <out>/NNNN.png and <out>/frames.json (fps, count, start, source size).+Frame i is at reference time start + i/fps.+`;++const a = parseArgs(process.argv.slice(2));+if (a.help || !a.in || (!a.out && !a.probe)) usage(HELP);++const input = abs(String(a.in));+// probe with ffmpeg itself (no ffprobe in ffmpeg-static)+const probe = spawnSync(ffmpegPath(), ["-hide_banner", "-i", input], { encoding: "utf8" }).stderr;+const dur = probe.match(/Duration:\s*(\d+):(\d+):([\d.]+)/);+const durationS = dur ? Number(dur[1]) * 3600 + Number(dur[2]) * 60 + Number(dur[3]) : undefined;+const vid = probe.match(/Video:.*?(\d{2,5})x(\d{2,5})/);+const srcFps = probe.match(/([\d.]+) fps/);+const info = { input, durationS, width: vid ? Number(vid[1]) : undefined, height: vid ? Number(vid[2]) : undefined, sourceFps: srcFps ? Number(srcFps[1]) : undefined };+if (a.probe) { console.log(JSON.stringify(info, null, 2)); process.exit(0); }++const out = ensureDir(abs(String(a.out)));+for (const f of readdirSync(out)) if (f.endsWith(".png")) unlinkSync(join(out, f));+const fps = num(a.fps, 10);+const start = parseTime(a.start) ?? 0;+const end = parseTime(a.end);+const crop = parseRect(a.crop);+const width = a.width ? num(a.width, 0) : 0;++const vf = [`fps=${fps}`];+if (crop) vf.push(`crop=${crop.width}:${crop.height}:${crop.x}:${crop.y}`);+if (width) vf.push(`scale=${width}:-2`);+const args = ["-y", "-ss", String(start), "-i", input];+if (end !== undefined) args.push("-t", String(end - start));+args.push("-vf", vf.join(","), "-vsync", "0", join(out, "%04d.png"));+ffmpeg(args, { quiet: true });++const count = readdirSync(out).filter((f) => f.endsWith(".png")).length;+const meta = { ...info, fps, count, start, end, crop, width: width || info.width, note: "frame i (1-based file name) is at t = start + (i-1)/fps seconds of the source" };+writeJson(join(out, "frames.json"), meta);+console.log(JSON.stringify(meta, null, 2));diff --git a/scripts/lib.ts b/scripts/lib.tsnew file mode 100644index 0000000..8b1fb5c--- /dev/null+++ b/scripts/lib.ts@@ -0,0 +1,80 @@+// Shared helpers for the motion-clone scripts. Bun + TypeScript, no build step.+import { mkdirSync, existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { join, resolve, dirname } from "node:path";+import { fileURLToPath } from "node:url";+import { spawnSync } from "node:child_process";++export const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));++export function ffmpegPath(): string {+ const p = join(SCRIPTS_DIR, "node_modules", "ffmpeg-static", "ffmpeg");+ if (!existsSync(p)) throw new Error(`ffmpeg not installed, run ${join(SCRIPTS_DIR, "setup.sh")}`);+ return p;+}++export function ffmpeg(args: string[], opts: { quiet?: boolean } = {}): string {+ const r = spawnSync(ffmpegPath(), ["-hide_banner", "-loglevel", opts.quiet ? "error" : "warning", ...args], { encoding: "utf8", maxBuffer: 64 << 20 });+ if (r.status !== 0) throw new Error(`ffmpeg failed (${r.status}): ${r.stderr}`);+ return r.stderr;+}++/** Minimal argv parser: --key value, --flag, --key=value. Returns { _: positionals, ...flags }. */+export function parseArgs(argv: string[], defaults: Record<string, any> = {}): Record<string, any> {+ const out: Record<string, any> = { _: [], ...defaults };+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (!a.startsWith("--")) { out._.push(a); continue; }+ const eq = a.indexOf("=");+ if (eq > 0) { out[a.slice(2, eq)] = a.slice(eq + 1); continue; }+ const key = a.slice(2);+ const next = argv[i + 1];+ if (next === undefined || next.startsWith("--")) out[key] = true;+ else { out[key] = next; i++; }+ }+ return out;+}++export function usage(text: string): never {+ console.log(text.trim() + "\n");+ process.exit(0);+}++export function ensureDir(p: string): string { mkdirSync(p, { recursive: true }); return p; }++export function num(v: any, fallback: number): number {+ if (v === undefined || v === true) return fallback;+ const n = Number(v);+ return Number.isFinite(n) ? n : fallback;+}++/** "1:23.5" | "83.5" | "83.5s" | "1500ms" -> seconds */+export function parseTime(v: any): number | undefined {+ if (v === undefined || v === true) return undefined;+ const s = String(v).trim();+ if (s.endsWith("ms")) return Number(s.slice(0, -2)) / 1000;+ if (s.includes(":")) { const [m, sec] = s.split(":"); return Number(m) * 60 + Number(sec); }+ return Number(s.replace(/s$/, ""));+}++export function parseSize(v: any, fallback: { width: number; height: number }) {+ if (!v || v === true) return fallback;+ const m = String(v).match(/^(\d+)x(\d+)$/);+ if (!m) throw new Error(`bad size "${v}", expected WxH`);+ return { width: Number(m[1]), height: Number(m[2]) };+}++export function parseRect(v: any): { x: number; y: number; width: number; height: number } | undefined {+ if (!v || v === true) return undefined;+ const p = String(v).split(",").map(Number);+ if (p.length !== 4 || p.some((n) => !Number.isFinite(n))) throw new Error(`bad rect "${v}", expected x,y,w,h`);+ return { x: p[0], y: p[1], width: p[2], height: p[3] };+}++export function listFrames(dir: string): string[] {+ return readdirSync(dir).filter((f) => /\.png$/i.test(f)).sort().map((f) => join(dir, f));+}++export function readJson<T = any>(p: string): T { return JSON.parse(readFileSync(p, "utf8")); }+export function writeJson(p: string, v: any) { writeFileSync(p, JSON.stringify(v, null, 2) + "\n"); }+export function abs(p: string) { return resolve(p); }+export const pad = (n: number, w = 4) => String(n).padStart(w, "0");diff --git a/scripts/package.json b/scripts/package.jsonnew file mode 100644index 0000000..3be3e92--- /dev/null+++ b/scripts/package.json@@ -0,0 +1,11 @@+{+ "name": "motion-clone-scripts",+ "private": true,+ "type": "module",+ "dependencies": {+ "ffmpeg-static": "^5.2.0",+ "pixelmatch": "^8.0.0",+ "playwright": "1.64.1",+ "pngjs": "^7.0.0"+ }+}diff --git a/scripts/setup.sh b/scripts/setup.shnew file mode 100755index 0000000..f05fe0c--- /dev/null+++ b/scripts/setup.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash+# Installs the script dependencies once (bun) and checks that Chromium and ffmpeg are usable.+# Safe to re-run; it is a no-op when everything is already in place.+set -euo pipefail+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+cd "$HERE"+if ! command -v bun >/dev/null; then echo "bun is required (https://bun.sh)"; exit 1; fi+if [ ! -d node_modules/playwright ] || [ ! -x node_modules/ffmpeg-static/ffmpeg ]; then+ bun install --silent+fi+if ! bun -e 'const {chromium}=await import("playwright"); const b=await chromium.launch(); await b.close(); console.log("chromium ok")' 2>/dev/null; then+ echo "Chromium missing for this Playwright version, installing it..."+ bunx playwright install chromium+fi+node_modules/ffmpeg-static/ffmpeg -hide_banner -version | head -1+echo "ready: $HERE"diff --git a/scripts/sheet.ts b/scripts/sheet.tsnew file mode 100644index 0000000..0a9295e--- /dev/null+++ b/scripts/sheet.ts@@ -0,0 +1,98 @@+// Lay frames out on labelled contact sheets so a whole motion can be read in one image.+// Two modes:+// filmstrip: one directory of frames → sheet-NN.png with the timestamp under each frame+// compare: reference frames vs clone frames (and diffs from compare.ts) side by side, one row per frame+// Rendered with Chromium (HTML + screenshot), so labels work without ffmpeg drawtext.+import { chromium } from "playwright";+import { join, basename } from "node:path";+import { existsSync, readFileSync } from "node:fs";+import { abs, ensureDir, listFrames, num, parseArgs, readJson, usage } from "./lib.ts";++const HELP = `+sheet.ts — labelled contact sheets.++ bun sheet.ts filmstrip --frames <dir> --out <dir> [--fps N] [--cols 6] [--per-sheet 24] [--width 240] [--every K] [--from I --to J]+ bun sheet.ts compare --ref <dir> --clone <dir> --out <dir> [--diff <dir>] [--fps N] [--per-sheet 8] [--width 420] [--every K] [--offset K]++ --fps used for the time labels (default: fps from frames.json next to the frames, else 25)+ --every K show every K-th frame (default 1)+ --from/--to frame index range (0-based, inclusive)+ --offset K compare: clone frame = ref frame + K (take it from compare.ts report.json alignment)++Writes <out>/sheet-01.png, sheet-02.png … and prints their paths. Read them with the image viewer.+`;++const a = parseArgs(process.argv.slice(2));+const mode = a._[0];+if (a.help || !mode || !a.out) usage(HELP);+const out = ensureDir(abs(String(a.out)));++function fpsOf(dir: string, fallback: number) {+ const j = join(dir, "frames.json");+ if (existsSync(j)) { const m = readJson(j); if (m.fps) return Number(m.fps); }+ return fallback;+}+const label = (i: number, fps: number) => `#${i} ${(i / fps).toFixed(2)}s`;+// data URIs: a page built with setContent has no file:// access+const fileUrl = (p: string) => "data:image/png;base64," + readFileSync(p).toString("base64");++type Sheet = { html: string; name: string };+const sheets: Sheet[] = [];+const css = `body{margin:0;background:#111;color:#ddd;font:12px/1.3 ui-monospace,Menlo,monospace;padding:10px}+.grid{display:grid;gap:10px}.cell{display:flex;flex-direction:column;gap:3px;align-items:center}+.cell img{display:block;background:#000;outline:1px solid #333}.cap{color:#9ad}.hdr{margin:0 0 8px;color:#fff;font-weight:600}+.row{display:grid;gap:8px;align-items:start;margin-bottom:10px}.row img{display:block;background:#000;outline:1px solid #333}+.colhdr{display:grid;gap:8px;color:#9ad;margin-bottom:4px}`;++if (mode === "filmstrip") {+ if (!a.frames) usage(HELP);+ const dir = abs(String(a.frames));+ const fps = num(a.fps, fpsOf(dir, 25));+ const every = num(a.every, 1), cols = num(a.cols, 6), per = num(a["per-sheet"], 24), width = num(a.width, 240);+ let frames = listFrames(dir).map((p, i) => ({ p, i }));+ const from = num(a.from, 0), to = num(a.to, frames.length - 1);+ frames = frames.filter((f) => f.i >= from && f.i <= to && (f.i - from) % every === 0);+ for (let s = 0; s * per < frames.length; s++) {+ const chunk = frames.slice(s * per, (s + 1) * per);+ const cells = chunk.map((f) => `<div class="cell"><img src="${fileUrl(f.p)}" style="width:${width}px"><div class="cap">${label(f.i, fps)}</div></div>`).join("");+ sheets.push({ name: `sheet-${String(s + 1).padStart(2, "0")}.png`, html: `<style>${css}</style><p class="hdr">${basename(dir)} · frames ${chunk[0].i}–${chunk[chunk.length - 1].i} · ${fps} fps</p><div class="grid" style="grid-template-columns:repeat(${cols},max-content)">${cells}</div>` });+ }+} else if (mode === "compare") {+ if (!a.ref || !a.clone) usage(HELP);+ const refDir = abs(String(a.ref)), cloneDir = abs(String(a.clone));+ const diffDir = a.diff ? abs(String(a.diff)) : undefined;+ const fps = num(a.fps, fpsOf(refDir, 25));+ const every = num(a.every, 1), per = num(a["per-sheet"], 8), width = num(a.width, 420), offset = num(a.offset, 0);+ const ref = listFrames(refDir), clone = listFrames(cloneDir);+ const diffs = diffDir ? listFrames(diffDir) : [];+ let report: any = null;+ if (diffDir && existsSync(join(diffDir, "..", "report.json"))) report = readJson(join(diffDir, "..", "report.json"));+ const n = Math.min(ref.length, clone.length - Math.max(0, offset));+ const idx: number[] = [];+ const from = num(a.from, 0), to = num(a.to, n - 1);+ for (let i = from; i <= to && i < n; i += every) idx.push(i);+ const ncol = diffs.length ? 3 : 2;+ for (let s = 0; s * per < idx.length; s++) {+ const chunk = idx.slice(s * per, (s + 1) * per);+ const rows = chunk.map((i) => {+ const c = clone[i + offset];+ const d = diffs[i];+ const mm = report?.frames?.[i]?.mismatch;+ const cap = `${label(i, fps)}${mm !== undefined ? ` · mismatch ${(mm * 100).toFixed(1)}%` : ""}`;+ return `<div class="cap">${cap}</div><div class="row" style="grid-template-columns:repeat(${ncol},${width}px)"><img src="${fileUrl(ref[i])}" style="width:${width}px"><img src="${c ? fileUrl(c) : ""}" style="width:${width}px">${d ? `<img src="${fileUrl(d)}" style="width:${width}px">` : ""}</div>`;+ }).join("");+ sheets.push({ name: `compare-${String(s + 1).padStart(2, "0")}.png`, html: `<style>${css}</style><p class="hdr">reference vs clone${diffs.length ? " vs diff" : ""} · ${fps} fps · clone offset ${offset}</p><div class="colhdr" style="grid-template-columns:repeat(${ncol},${width}px)"><div>reference</div><div>clone</div>${diffs.length ? "<div>diff (red = differs)</div>" : ""}</div>${rows}` });+ }+} else usage(HELP);++const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 1 });+const paths: string[] = [];+for (const s of sheets) {+ await page.setContent(s.html, { waitUntil: "load" });+ const p = join(out, s.name);+ await page.screenshot({ path: p, fullPage: true });+ paths.push(p);+}+await browser.close();+console.log(paths.join("\n") || "no frames selected");