Compare commits

..
59 changed files with 1829 additions and 4157 deletions

No files matched your search

Whitespace-only changes.
-210
View File
@@ -1,210 +0,0 @@
---
name: 60fps-animation
description: This skill should be used when the user asks to "fix janky CSS animation", "make animation 60fps", "stop layout thrashing", "animate width/height/top/left smoothly", "convert animation to transform", "animate box-shadow performantly", "animate height auto", "FLIP animation", or "why is my scroll/hover animation choppy".
version: 0.1.0
---
# Performant Web Animation
Eliminate the #1 cause of janky web animation: animating properties that force the browser to recalculate layout (reflow) or repaint on every frame. The browser renders in stages — **layout → paint → composite**. Animating `width`, `height`, `top`, `left`, `margin`, `padding`, `box-shadow`, or `filter` re-runs layout and/or paint each frame, blocking the main thread. Animating **`transform`** and **`opacity`** runs entirely on the compositor (often the GPU), skipping layout and paint, which is what makes animation smooth at 60/120fps.
## When to use
Use when an animation stutters or drops frames, when a hover/scroll effect feels heavy, when animating size/position/shadow, when a layout change needs to animate smoothly (cards reordering, an element moving between containers), when animating `height: auto`, or when reviewing animation code for performance.
## Core rule: animate only transform and opacity
Map every "expensive" animation to a cheap equivalent.
| Animating (expensive) | Triggers | Replace with (cheap) |
|---|---|---|
| `width` / `height` | Layout + Paint | `transform: scaleX()/scaleY()` (+ FLIP for true size) |
| `top` / `left` / `margin` | Layout + Paint | `transform: translate()` |
| `box-shadow` | Paint | Animate `opacity` of a pseudo-element holding the shadow |
| `filter: blur()` | Paint (heavy) | Cross-fade two layers via `opacity`, or accept sparingly |
| `background-position` | Paint | `transform: translate()` on a child layer |
| `color` / `background` | Paint | Often acceptable; or cross-fade layers |
### Position and size via transform
```css
/* BAD: animates layout every frame */
.box { transition: left 300ms, width 300ms; left: 0; width: 100px; }
.box:hover { left: 200px; width: 200px; }
/* GOOD: compositor-only */
.box {
transition: transform 300ms ease;
transform: translateX(0) scaleX(1);
transform-origin: left center;
}
.box:hover { transform: translateX(200px) scaleX(2); }
```
`scaleX` distorts inner content (text stretches). For true resizing without distortion, use **FLIP**.
## Cheap box-shadow via pseudo-element opacity
Animating `box-shadow` repaints a large blurred region every frame. Instead paint the shadow once on a `::after`, then animate only its `opacity`.
```css
.card { position: relative; }
.card::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
box-shadow: 0 12px 28px rgba(0,0,0,0.35);
opacity: 0;
transition: opacity 300ms ease;
pointer-events: none;
}
.card:hover::after { opacity: 1; }
```
The blurred shadow is rasterized once; hovering only changes a compositor opacity — smooth at any frame rate.
## FLIP: animate layout changes cheaply
FLIP (First, Last, Invert, Play) animates a *layout* change (reorder, resize, move between containers) using only `transform`. Measure where the element was (First) and will be (Last), apply an inverting transform so it visually appears unmoved, then animate the transform back to identity (Play). The DOM ends in its real final layout; the motion is pure compositor work.
```js
function flip(el, mutate) {
const first = el.getBoundingClientRect(); // First
mutate(); // change the DOM/layout
const last = el.getBoundingClientRect(); // Last
const dx = first.left - last.left;
const dy = first.top - last.top;
const sx = first.width / last.width;
const sy = first.height / last.height;
el.animate(
[
{ transformOrigin: 'top left',
transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` }, // Invert
{ transformOrigin: 'top left', transform: 'none' }, // Play
],
{ duration: 300, easing: 'cubic-bezier(0.2, 0, 0, 1)' }
);
}
// usage: animate an element moving to a new grid position
flip(card, () => targetContainer.appendChild(card));
```
The Web Animations API `animate()` runs the transform on the compositor. For many elements, batch all `getBoundingClientRect()` reads *before* any mutation (see layout thrashing below).
## Animating height: auto
`height: auto` is not interpolatable historically. Modern and fallback approaches:
```css
/* Modern (Chrome 129+/supporting browsers): opt size keywords into animation */
.panel {
interpolate-size: allow-keywords; /* enables animating to/from auto */
height: 0;
overflow: clip;
transition: height 300ms ease;
}
.panel.open { height: auto; }
/* calc-size() also works: height: calc-size(auto, size); */
```
```css
/* Robust fallback today: CSS grid 1fr -> 0fr */
.wrapper {
display: grid;
grid-template-rows: 0fr; /* collapsed */
transition: grid-template-rows 300ms ease;
}
.wrapper.open { grid-template-rows: 1fr; }
.wrapper > .content { overflow: hidden; min-height: 0; }
```
The grid trick animates the track size (compositor-friendly enough and broadly supported) and needs no JS height measurement. Use `interpolate-size: allow-keywords` / `calc-size(auto, size)` where the target browsers support it; keep the grid technique as the cross-browser default.
## Avoid layout thrashing (batch reads, then writes)
Reading a layout property (`offsetWidth`, `getBoundingClientRect`, `scrollTop`, `getComputedStyle`) after a write forces a *synchronous* reflow. Interleaving reads and writes in a loop ("layout thrashing") can run dozens of forced reflows per frame.
```js
// BAD: read, write, read, write... forces reflow each iteration
items.forEach((el) => {
const w = el.offsetWidth; // read (forces layout)
el.style.width = w * 1.5 + 'px'; // write (invalidates layout)
});
// GOOD: batch all reads, then all writes
const widths = items.map((el) => el.offsetWidth); // all reads
items.forEach((el, i) => { // all writes
el.style.width = widths[i] * 1.5 + 'px';
});
```
For frame-synced work, read in a `requestAnimationFrame` callback and apply writes; libraries like fastdom formalize this read/write scheduling.
## will-change: use sparingly
`will-change: transform` promotes an element to its own compositor layer ahead of time, avoiding a hitch at animation start. But every promoted layer costs GPU memory, and over-use degrades performance.
```css
.menu { will-change: transform; } /* only on elements about to animate */
```
Rules: apply just before the animation (e.g. on hover/parent state), remove it after (`will-change: auto`) when idle, never blanket-apply to many elements, and never leave it permanently on large/numerous nodes. A single `transform: translateZ(0)` hack does the same promotion but is harder to undo — prefer `will-change`.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
The deliverable is **one self-contained `.html`** that opens directly in a browser — the markup, the CSS/JS animation, and a freeze harness in one file. For this skill, verification is two-pronged: the frame must look right *and* be cheap to produce (compositor-only).
**Output contract:**
- One `.html`, deps via CDN if any, animation driven by CSS transitions/`@keyframes` or the Web Animations API.
- A freeze mechanism so a screenshot lands on a deterministic frame:
- CSS `@keyframes` → `?t=N` sets `el.style.animationDelay = (-N)+'s'; el.style.animationPlayState = 'paused'`.
- WAAPI / JS → keep the animation object and `anim.pause(); anim.currentTime = N*1000`.
**Verify loop — freeze → screenshot, then profile for jank:**
1. Open headless at start / mid / end (`?t=0`, mid, end), screenshot each; confirm the motion is visually correct (no clipped/stretched text from `scaleX`, FLIP lands on the real layout, shadow/height transitions look right).
2. **Confirm it's compositor-only** — the whole point of this skill. Either:
- DevTools → Performance: record the animation, check there is **no purple "Layout" or green "Paint"** band per frame (only "Composite Layers").
- Or headless trace: `npx playwright screenshot` for the visual, plus a CDP/`tracing` capture, and assert no `Layout`/`Paint` events fire during the animation window.
3. Watch the FPS/“Frame Rendering Stats” overlay stays at 60 — dropped frames mean an expensive property slipped back in.
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/anim.html?t=0.3" frame.png
```
**Before you finish:**
1. Opens standalone — no console errors.
2. Only `transform` / `opacity` animate per frame; DevTools shows no per-frame Layout/Paint.
3. Screenshotted at start / mid / end — correct, no `scaleX` text distortion, FLIP lands true.
4. Holds 60fps; `will-change` applied just-in-time and removed when idle (no leftover layers).
5. `prefers-reduced-motion` honored.
## Quick reference
| Goal | Do this |
|---|---|
| Move element | `transform: translate()` |
| Resize without distortion | FLIP with `transform` |
| Shadow on hover | Animate `opacity` of shadow pseudo-element |
| Expand to content height | grid `0fr→1fr`, or `interpolate-size: allow-keywords` |
| Many elements moving | Batch `getBoundingClientRect` reads, then writes |
| Smooth animation start | `will-change` just-in-time, remove when idle |
| Verify it's compositor-only | DevTools Performance: no purple "Layout"/green "Paint" per frame |
## Gotchas
- `scaleX/scaleY` stretches text and children; use FLIP when content must stay crisp.
- `transform` percentages are relative to the element's own box, not the parent — different from `left: %`.
- Overusing `will-change` or `translateZ(0)` creates too many layers and *hurts* performance; promote only what animates.
- `filter` and `backdrop-filter` are compositor-related but still expensive; animate their presence via opacity cross-fades rather than animating the blur radius.
- The grid `1fr→0fr` content must have `overflow: hidden` and `min-height: 0` or it won't collapse.
- Always gate non-essential motion behind `@media (prefers-reduced-motion: reduce)`.
## Reference files
- `references/patterns-and-profiling.md` — full runnable examples (accordion, reorder list, parallax), DevTools profiling walkthrough to confirm compositor-only frames, reduced-motion patterns, and a property-cost cheat sheet.
@@ -1,132 +0,0 @@
# Patterns, profiling, and cost cheat sheet
## Property cost cheat sheet
| Property | Pipeline stage triggered | Verdict |
|---|---|---|
| `transform` | Composite only | Cheap — animate freely |
| `opacity` | Composite only | Cheap — animate freely |
| `filter` | Paint (+composite) | Expensive — avoid animating radius |
| `box-shadow` | Paint (large area) | Expensive — use pseudo + opacity |
| `width`, `height` | Layout + Paint | Avoid — use scale/FLIP |
| `top`, `left`, `right`, `bottom` | Layout + Paint | Avoid — use translate |
| `margin`, `padding` | Layout + Paint | Avoid |
| `border-width` | Layout + Paint | Avoid |
| `color`, `background-color` | Paint | Acceptable in moderation |
| `background-position` | Paint | Prefer translate on child |
| `clip-path` | Paint | Moderate; cheaper than filter |
## Accordion with grid height (no JS measurement)
```html
<button class="acc-trigger" aria-expanded="false">Details</button>
<div class="acc-wrap"><div class="acc-content">…content…</div></div>
```
```css
.acc-wrap {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 280ms cubic-bezier(0.2,0,0,1);
}
.acc-wrap.open { grid-template-rows: 1fr; }
.acc-content { overflow: hidden; min-height: 0; }
@media (prefers-reduced-motion: reduce) {
.acc-wrap { transition: none; }
}
```
```js
trigger.addEventListener('click', () => {
const open = wrap.classList.toggle('open');
trigger.setAttribute('aria-expanded', String(open));
});
```
## FLIP reorder list (batched reads)
```js
function flipReorder(container, mutate) {
const items = [...container.children];
const firsts = new Map(items.map((el) => [el, el.getBoundingClientRect()])); // all reads
mutate(); // e.g. sort/reinsert children
items.forEach((el) => {
const first = firsts.get(el);
const last = el.getBoundingClientRect();
const dx = first.left - last.left;
const dy = first.top - last.top;
if (dx || dy) {
el.animate(
[{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }],
{ duration: 300, easing: 'cubic-bezier(0.2,0,0,1)' }
);
}
});
}
```
Reading every rect *before* mutating, and using `animate()` (compositor), keeps a 50-item reorder smooth.
## Just-in-time will-change
```js
el.addEventListener('pointerenter', () => { el.style.willChange = 'transform'; });
el.addEventListener('transitionend', () => { el.style.willChange = 'auto'; });
```
Promote on intent, demote when the animation ends, so layers don't accumulate.
## Reduced-motion gate
```css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.001ms !important;
scroll-behavior: auto !important;
}
}
```
For JS: `const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;` and skip/shorten animations when true.
## Profiling: prove it's compositor-only
1. Open DevTools > **Performance**. Record while the animation runs.
2. Inspect the flame chart frames during the animation:
- **Purple "Layout"** or **green "Paint"** bars on every frame → still hitting layout/paint; the animation is not compositor-only. Find the offending property.
- Only **"Composite Layers"** / GPU work per frame → success.
3. Use **Rendering** tab tools:
- **Paint flashing** — green flashes show repainted regions; a good transform/opacity animation flashes nothing.
- **Layer borders** — confirms which elements are on their own compositor layer (watch for too many from over-using `will-change`).
- **Frame Rendering Stats / FPS meter** — confirm a stable 60/120fps.
4. The **Layers** panel shows layer count and memory; excessive layers indicate `will-change` overuse.
## Parallax without scroll-jank
Drive parallax with `transform: translate3d()` updated inside a single `requestAnimationFrame` loop reading `scrollY` once per frame — never read layout per element per frame.
```js
let ticking = false;
addEventListener('scroll', () => {
if (!ticking) {
requestAnimationFrame(() => {
const y = window.scrollY; // single read
layers.forEach((l, i) => { // writes only
l.style.transform = `translate3d(0, ${y * (0.1 * (i + 1))}px, 0)`;
});
ticking = false;
});
ticking = true;
}
}, { passive: true });
```
`{ passive: true }` lets the browser scroll without waiting on the handler.
---
Stay on transform and opacity, profile the jank away, and motion holds 60fps. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=60fps-animation)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
@@ -1,231 +0,0 @@
---
name: accessible-animation
description: This skill should be used when the user asks to "respect prefers-reduced-motion", "honor reduced motion", "make my animations accessible", "fix vestibular / motion-sickness issues", "add a useReducedMotion hook", "gate GSAP / Framer Motion / Lenis for reduced motion", or "meet WCAG 2.3.3 / C39". Provides tiered (not all-or-nothing) reduced-motion patterns in CSS and JS.
version: 0.1.0
---
# Accessible Animation (Reduced Motion, Tiered)
Honor `prefers-reduced-motion: reduce` as a *graceful degradation*, not a kill switch. The OS-level setting (macOS: Settings > Accessibility > Display > Reduce motion; Windows: Settings > Accessibility > Visual effects > Animation effects; iOS/Android equivalents) signals that *vestibular-triggering* motion causes nausea, dizziness, or migraines. The correct response is to remove the dangerous motion while keeping orientation cues.
## When to use
Use when adding or auditing animation in a web UI, when a user reports motion sickness or WCAG findings, or when integrating animation libraries (GSAP, Framer Motion, Lenis smooth scroll, Anime.js, CSS keyframes) into an accessible product.
## The core principle: tier motion, do not nuke it
Removing *all* animation is a common over-correction. An instant state change with no transition can be more disorienting (elements teleport) and removes useful affordances (focus rings, loading spinners that communicate progress). Sort every animation into three tiers:
- **Tier 1 — Remove entirely (vestibular triggers).** Parallax; large-area slides/translates across the viewport; scale/zoom of large elements; 3D rotation and spin; continuous auto-playing carousels and marquees; smooth-scroll hijacking (Lenis/Locomotive); scroll-jacked pinned scenes; motion-path animation; anything that moves a large portion of the screen or implies depth/self-motion.
- **Tier 2 — Soften / shorten.** Replace movement with a short opacity fade (≤200ms). Reduce distance and duration. Keep the *fact* of a transition (so elements don't teleport) but strip the displacement. Replace a 600ms slide-in-from-left with a 150ms cross-fade.
- **Tier 3 — Always keep.** Opacity fades, color/background transitions, focus-ring transitions, loading indicators, and motion that is *essential* to meaning (WCAG allows essential animation). These rarely trigger vestibular responses because they imply no self-motion.
## CSS layer: media-query gating
Write motion as the default, then override under the reduce query. Prefer a global safety net plus targeted overrides.
```css
/* Global safety net: neutralize runaway motion but DO NOT set 0s blindly,
which can break JS that waits for transitionend/animationend. Use 0.01ms. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important; /* stop infinite spins/marquees */
transition-duration: 0.01ms !important;
scroll-behavior: auto !important; /* kill smooth scroll */
}
}
```
The global net is a backstop. Layer *intentional, tiered* overrides on top so Tier 3 motion survives:
```css
.card {
transition: transform 400ms ease, opacity 400ms ease, background-color 200ms ease;
}
@media (prefers-reduced-motion: reduce) {
.card {
/* Tier 2: drop the transform (movement), keep opacity + color (Tier 3) */
transition: opacity 150ms ease, background-color 150ms ease;
}
.parallax-layer { transform: none !important; } /* Tier 1: remove */
.hero-zoom { animation: none !important; } /* Tier 1: remove */
}
```
Use the *positive* query `(prefers-reduced-motion: no-preference)` to opt motion IN, which is the safest pattern for elaborate effects:
```css
.hero { opacity: 1; } /* visible, static by default */
@media (prefers-reduced-motion: no-preference) {
.hero { animation: zoom-in 1.2s ease both; } /* only animate when allowed */
}
```
## JS layer: matchMedia gating
CSS cannot gate JS-driven animation (GSAP timelines, Framer's `animate`, canvas/WebGL, Lenis). Read the same signal via `matchMedia` and react to live changes (users toggle the OS setting without reloading).
```js
const REDUCE_QUERY = '(prefers-reduced-motion: reduce)';
export function prefersReducedMotion() {
return typeof window !== 'undefined'
&& window.matchMedia
&& window.matchMedia(REDUCE_QUERY).matches;
}
// Live updates: listen so toggling the OS setting takes effect immediately.
export function onReducedMotionChange(cb) {
const mq = window.matchMedia(REDUCE_QUERY);
const handler = (e) => cb(e.matches);
mq.addEventListener('change', handler); // modern API
return () => mq.removeEventListener('change', handler);
}
```
### Library gating, applied as one reusable layer
```js
// GSAP — use matchMedia(): GSAP reverts conditional setups on change.
import gsap from 'gsap';
const mm = gsap.matchMedia();
mm.add({
motionOK: '(prefers-reduced-motion: no-preference)',
motionReduce: '(prefers-reduced-motion: reduce)',
}, (ctx) => {
const { motionOK } = ctx.conditions;
if (motionOK) {
gsap.from('.hero', { y: 80, opacity: 0, duration: 1 }); // Tier 1 move
} else {
gsap.from('.hero', { opacity: 0, duration: 0.15 }); // Tier 2 fade
}
});
// Lenis smooth scroll — do not instantiate at all when reduced.
import Lenis from 'lenis';
let lenis = null;
if (!prefersReducedMotion()) {
lenis = new Lenis();
const raf = (t) => { lenis.raf(t); requestAnimationFrame(raf); };
requestAnimationFrame(raf);
}
```
## React: a `useReducedMotion` hook
```jsx
import { useState, useEffect } from 'react';
export function useReducedMotion() {
const query = '(prefers-reduced-motion: reduce)';
const get = () =>
typeof window !== 'undefined' && window.matchMedia
? window.matchMedia(query).matches
: false;
const [reduced, setReduced] = useState(get);
useEffect(() => {
const mq = window.matchMedia(query);
const onChange = () => setReduced(mq.matches);
onChange(); // sync after hydration
mq.addEventListener('change', onChange);
return () => mq.removeEventListener('change', onChange);
}, []);
return reduced;
}
```
```jsx
// Framer Motion has its own useReducedMotion(); the hook above also works.
import { motion } from 'framer-motion';
function Card() {
const reduced = useReducedMotion();
return (
<motion.div
initial={reduced ? { opacity: 0 } : { opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: reduced ? 0.15 : 0.5 }}
/>
);
}
```
Initialize SSR-rendered state to `false` (motion) and re-sync in `useEffect` to avoid a hydration mismatch; the OS value is only known client-side.
## WCAG mapping
- **2.3.3 Animation from Interactions (AAA).** Motion triggered by interaction (scroll, hover) must be disable-able unless essential. Honoring `prefers-reduced-motion` is the standard technique.
- **C39 (CSS technique).** Use the `prefers-reduced-motion` query to prevent motion. This is the named sufficient technique.
- **2.2.2 Pause, Stop, Hide (A).** Any auto-playing motion lasting >5s must offer pause/stop. Auto-carousels and marquees fail this regardless of the media query — give a control too.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained demo the deliverable is **one HTML file that opens directly in a browser** — markup, CSS, and any JS (GSAP/`matchMedia` from CDN) inline, no build step. For *this* skill the verification is the point: you must screenshot **both** the normal and the reduced-motion path and confirm the tiering is correct.
**Output contract:**
- One `.html` file with the full motion AND its tiered reduced-motion overrides (CSS query + `matchMedia`/`gsap.matchMedia()` for JS-driven motion).
- A seek harness to freeze a frame, plus a way to force the reduced-motion code path for screenshots.
**Seek harness — freeze a frame, force the preference.** `?t=N` freezes the timeline; `?reduce=1` forces the reduced path even when the OS setting is off (CSS can't be toggled from JS, so query the same flag you gate JS on, and screenshot with the OS/browser preference emulated for the CSS layer):
```html
<script>
const q = new URLSearchParams(location.search);
const reduce = q.get("reduce") === "1"
|| window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// build motion conditionally on `reduce` (Tier-1 removed, Tier-2 softened, Tier-3 kept)
const t = q.get("t");
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // GSAP; CSS: el.style.animationDelay=(-t)+"s"; playState="paused"
window.__ready = true;
</script>
```
**Verify loop — screenshot BOTH states:** capture the normal path AND the reduced path, mid-animation each, and confirm Tier-1 motion is gone, Tier-2 is a short fade, Tier-3 survives. Emulate the preference for the CSS layer (Playwright `--reduced-motion=reduce`; the agent's browser tool can emulate it too):
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/demo.html?t=0.6" normal.png
npx playwright screenshot --reduced-motion=reduce --wait-for-timeout=500 "file://$PWD/demo.html?t=0.6&reduce=1" reduced.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN (if any) loads.
2. The freeze + `?reduce=1` (and `--reduced-motion=reduce`) reliably exercises both code paths.
3. Screenshotted in BOTH states, mid-animation — normal looks intentional, reduced strips Tier-1/softens Tier-2.
4. `prefers-reduced-motion` honored as *tiering*, not a kill switch — no teleporting, Tier-3 fades/focus rings/spinners kept; any >5s auto-motion still has a pause control (2.2.2).
5. Easing is intentional in both paths — no accidental `linear`, durations sane (reduced fades ≤200ms, `0.01ms` not `0s`).
## Quick reference
| Motion type | Tier | Reduced behavior |
|---|---|---|
| Parallax / depth | 1 | Remove (`transform: none`) |
| Large slide / translate | 1 | Remove or replace with fade |
| Scale / zoom (large) | 1 | Remove |
| Spin / 3D rotate | 1 | Remove (`animation: none`) |
| Auto carousel / marquee | 1 | Stop + provide pause control (2.2.2) |
| Smooth-scroll (Lenis) | 1 | Don't instantiate |
| Small slide / pop-in | 2 | Cross-fade ≤200ms |
| Opacity fade | 3 | Keep (shorten if long) |
| Color / focus-ring transition | 3 | Keep |
| Loading spinner | 3 | Keep (essential feedback) |
## Gotchas
- `animation-duration: 0s` can break code waiting on `animationend`/`transitionend`; use `0.01ms` so the event still fires.
- The global `*` reset alone over-removes Tier 3 motion; always layer intentional overrides.
- Forgetting `animation-iteration-count: 1` leaves infinite spins running at near-zero duration (CPU churn, still animating).
- No media query covers JS/canvas/WebGL — gate those with `matchMedia` or the loop never stops.
- Toggling the OS setting fires no page reload; without a `change` listener the page keeps its stale state.
- SSR: reading `matchMedia` during render throws or mismatches; default to motion and sync in an effect.
- Auto-playing motion needs a visible pause control even when reduced-motion is off (2.2.2 is Level A).
## Reference files
- `references/patterns.md` — Full GSAP `matchMedia` teardown, Framer Motion `MotionConfig`, Lenis start/stop on live toggle, a reusable `animateWithMotionPreference` wrapper, marquee with pause control, and a tier-classification audit checklist.
@@ -1,196 +0,0 @@
# Reduced Motion — Detailed Patterns
## Reusable wrapper: animate with motion preference
A single helper that picks a "full" or "reduced" variant and stays live-reactive.
```js
const REDUCE = '(prefers-reduced-motion: reduce)';
export function createMotionController() {
const mq = window.matchMedia(REDUCE);
const listeners = new Set();
mq.addEventListener('change', () => listeners.forEach((fn) => fn(mq.matches)));
return {
get reduced() { return mq.matches; },
subscribe(fn) { listeners.add(fn); fn(mq.matches); return () => listeners.delete(fn); },
// Pick a variant object: { full, reduced }
pick(variants) { return mq.matches ? variants.reduced : variants.full; },
};
}
// Usage
const motion = createMotionController();
const opts = motion.pick({
full: { translateY: ['40px', '0'], opacity: [0, 1], duration: 500 },
reduced: { opacity: [0, 1], duration: 150 },
});
```
## GSAP: full matchMedia with teardown
`gsap.matchMedia()` automatically reverts (kills tweens, restores inline styles) when a condition stops matching, so toggling the OS setting cleans up correctly.
```js
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const mm = gsap.matchMedia();
mm.add({
motionOK: '(prefers-reduced-motion: no-preference)',
motionReduce: '(prefers-reduced-motion: reduce)',
}, (ctx) => {
const { motionOK } = ctx.conditions;
if (motionOK) {
// Tier 1 parallax — only when allowed
gsap.to('.parallax-layer', {
yPercent: -30,
ease: 'none',
scrollTrigger: { trigger: '.section', scrub: true },
});
gsap.from('.card', {
y: 60, opacity: 0, stagger: 0.1,
scrollTrigger: { trigger: '.grid', start: 'top 80%' },
});
} else {
// Reduced: no parallax at all; cards cross-fade in place (Tier 2)
gsap.from('.card', {
opacity: 0, duration: 0.15, stagger: 0.03,
scrollTrigger: { trigger: '.grid', start: 'top 80%' },
});
}
return () => { /* optional extra cleanup; mm reverts tweens automatically */ };
});
// Tear everything down (e.g. SPA route change)
// mm.revert();
```
## Framer Motion: MotionConfig for app-wide reduction
`MotionConfig reducedMotion="user"` makes every child `motion` component automatically drop transform/layout animations while keeping opacity. Set it once at the root.
```jsx
import { MotionConfig, motion } from 'framer-motion';
export function App() {
return (
<MotionConfig reducedMotion="user">
{/* All descendant motion components honor the OS setting */}
<motion.section
initial={{ opacity: 0, y: 80 }} // y is auto-dropped when reduced
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6 }}
/>
</MotionConfig>
);
}
```
For per-component control, Framer's own hook:
```jsx
import { useReducedMotion } from 'framer-motion';
function Hero() {
const reduced = useReducedMotion();
const variants = reduced
? { hidden: { opacity: 0 }, show: { opacity: 1, transition: { duration: 0.15 } } }
: { hidden: { opacity: 0, scale: 0.9 }, show: { opacity: 1, scale: 1, transition: { duration: 0.8 } } };
return <motion.div variants={variants} initial="hidden" animate="show" />;
}
```
## Lenis: start/stop on live toggle
Lenis hijacks scroll (Tier 1). Destroy it when reduced motion turns on, recreate when it turns off.
```js
import Lenis from 'lenis';
let lenis = null;
let rafId = null;
function startLenis() {
if (lenis) return;
lenis = new Lenis({ smoothWheel: true });
const loop = (t) => { lenis.raf(t); rafId = requestAnimationFrame(loop); };
rafId = requestAnimationFrame(loop);
}
function stopLenis() {
if (!lenis) return;
cancelAnimationFrame(rafId);
lenis.destroy();
lenis = null;
// Restore native scroll so the page is still usable
document.documentElement.style.removeProperty('scroll-behavior');
}
const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
function sync() { mq.matches ? stopLenis() : startLenis(); }
mq.addEventListener('change', sync);
sync();
```
## Auto-carousel / marquee with a pause control (WCAG 2.2.2)
Auto-playing motion longer than 5s needs a pause/stop control regardless of the media query. Reduced-motion users get it stopped by default; everyone gets the control.
```html
<div class="marquee" data-playing="true">
<button class="marquee__toggle" aria-pressed="false">Pause</button>
<ul class="marquee__track"><!-- items --></ul>
</div>
```
```css
.marquee__track { animation: scroll-left 20s linear infinite; }
.marquee[data-playing="false"] .marquee__track { animation-play-state: paused; }
@media (prefers-reduced-motion: reduce) {
.marquee__track { animation-play-state: paused; } /* paused by default */
}
@keyframes scroll-left { to { transform: translateX(-50%); } }
```
```js
const root = document.querySelector('.marquee');
const btn = root.querySelector('.marquee__toggle');
// Respect the OS setting for the initial state
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
root.dataset.playing = 'false';
btn.textContent = 'Play';
btn.setAttribute('aria-pressed', 'true');
}
btn.addEventListener('click', () => {
const playing = root.dataset.playing === 'true';
root.dataset.playing = String(!playing);
btn.textContent = playing ? 'Play' : 'Pause';
btn.setAttribute('aria-pressed', String(playing));
});
```
## Tier classification audit checklist
For each animation in the codebase, ask in order:
1. Is it essential to meaning (e.g. a progress bar, a diagram step)? -> Tier 3, keep.
2. Does a large area move, scale, spin, or imply depth/self-motion (parallax, zoom hero, slide-over)? -> Tier 1, remove under reduce.
3. Is it a small entrance with displacement (pop-in, slide-up)? -> Tier 2, replace displacement with a ≤200ms opacity fade.
4. Is it only opacity/color/focus? -> Tier 3, keep (shorten if >300ms).
5. Does it auto-play >5s (carousel, marquee, looping video bg)? -> Add a pause control (2.2.2) on top of any tier handling.
## Testing
- macOS: System Settings > Accessibility > Display > Reduce motion.
- Windows 11: Settings > Accessibility > Visual effects > Animation effects (off).
- Chrome DevTools: Rendering panel > "Emulate CSS media feature prefers-reduced-motion".
- Verify the `change` listener: toggle the OS setting with the page open and confirm motion stops without reload.
- Confirm `transitionend`/`animationend`-dependent flows still complete (the `0.01ms` rule).
---
Honor prefers-reduced-motion at every tier and motion stays inclusive by default. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=accessible-animation)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
-179
View File
@@ -1,179 +0,0 @@
---
name: ascii-animation
description: This skill should be used when the user asks to "make an ASCII animation", "build a terminal/CLI intro or loader", "convert an image or video to ASCII art", "add an ASCII shader/post-effect to a canvas or Three.js scene", "create retro/hacker text-character motion", or "animate text characters with a brightness ramp". Covers generative ASCII fields, image/video/3D-to-ASCII, and animated character art for both web and terminal.
version: 0.1.0
---
# ASCII Animation
Render motion entirely with text characters. ASCII output is extremely lightweight, distinctive, and works in browsers (`<pre>`/canvas), terminals (ANSI), and over any 3D scene (Three.js `AsciiEffect`).
## When to use
- Build terminal/CLI intros, loaders, banners, or a retro/hacker aesthetic.
- Convert an image, video frame, or 3D scene into animated ASCII.
- Add an ASCII post-effect over an existing canvas/WebGL render.
- Create generative text fields (plasma, sine waves, noise, tunnels).
## Core concept: the brightness ramp
Map luminance (0..1) to a character whose ink density matches. Order characters dark-to-light. Pick the index with `Math.round(lum * (ramp.length - 1))`.
Common ramps (dark to light):
- Short (10): ` .:-=+*#%@`
- Medium (16): ` .'\`^",:;Il!i><~+_-?][}{1)(|/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$` truncated — see table below.
- Standard 70-level (Paul Bourke), best for photos:
`` $@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. `` (reverse for dark-on-light).
Compute relative luminance from sRGB (perceptual):
```js
const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; // 0..1
```
Invert when drawing dark text on a light background: `lum = 1 - lum`.
## Character cell aspect correction (the #1 gotcha)
Monospace character cells are taller than wide — roughly **0.5 width:height**. Sampling a square pixel grid produces a vertically stretched image. Correct by sampling **fewer rows than columns**: for a target of `cols` characters wide, use `rows = Math.round(cols * (imgH / imgW) * fontAspect)` where `fontAspect ≈ 0.5`. Equivalently, when drawing to an offscreen canvas, set its height to `cols * aspect * 0.5`.
## Web rendering: `<pre>` vs canvas
- **`<pre>` + textContent**: simplest. One string with `\n` per row. Fine up to ~120×60 chars at 30fps. Set `white-space: pre; font-family: monospace; line-height: 1;`.
- **Canvas `fillText`**: needed for per-character color, larger grids, or 60fps. Draw each char at `x * cellW, y * cellH`. Faster than thousands of DOM nodes.
Generative `<pre>` field (plasma):
```js
const pre = document.querySelector('pre');
const COLS = 100, ROWS = 50, ramp = ' .:-=+*#%@';
function frame(t) {
let out = '';
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
const v = Math.sin(x * 0.2 + t * 0.001)
+ Math.sin(y * 0.3 + t * 0.0013)
+ Math.sin((x + y) * 0.15 + t * 0.0007);
const lum = (v + 3) / 6; // normalize -3..3 to 0..1
out += ramp[Math.round(lum * (ramp.length - 1))];
}
out += '\n';
}
pre.textContent = out;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```
## Image / video to ASCII
Draw the source to a small offscreen canvas at `cols × rows`, read pixels with `getImageContext().getImageData`, then map each pixel to a character. For video, repeat per frame from a `<video>` element.
```js
function videoToAscii(video, cols = 120) {
const aspect = video.videoHeight / video.videoWidth;
const rows = Math.round(cols * aspect * 0.5); // cell aspect correction
const cv = document.createElement('canvas');
cv.width = cols; cv.height = rows;
const ctx = cv.getContext('2d', { willReadFrequently: true });
const ramp = ' .:-=+*#%@', pre = document.querySelector('pre');
(function tick() {
ctx.drawImage(video, 0, 0, cols, rows);
const { data } = ctx.getImageData(0, 0, cols, rows);
let out = '';
for (let i = 0; i < data.length; i += 4) {
const lum = (0.2126*data[i] + 0.7152*data[i+1] + 0.0722*data[i+2]) / 255;
out += ramp[Math.round(lum * (ramp.length - 1))];
if (((i / 4) + 1) % cols === 0) out += '\n';
}
pre.textContent = out;
requestAnimationFrame(tick);
})();
}
```
For Node image→ASCII, see `scripts/img-to-ascii.mjs`.
## 3D-to-ASCII with Three.js
`AsciiEffect` wraps a renderer and renders any scene as ASCII into a DOM element. Render through the effect, not the renderer.
```js
import { AsciiEffect } from 'three/addons/effects/AsciiEffect.js';
const effect = new AsciiEffect(renderer, ' .:-=+*#%@', { invert: true });
effect.setSize(innerWidth, innerHeight);
effect.domElement.style.color = '#0f0';
effect.domElement.style.backgroundColor = 'black';
document.body.appendChild(effect.domElement);
// in loop: effect.render(scene, camera); // NOT renderer.render
```
## Terminal / CLI animation
Loop with ANSI escape codes: hide the cursor, move to home, print the frame, throttle to 12–24 fps. Show the cursor again on exit.
```js
const ESC = '\x1b[';
process.stdout.write(ESC + '?25l'); // hide cursor
function frame(t) {
process.stdout.write(ESC + 'H'); // cursor to top-left
// build and write rows...
}
const id = setInterval(() => frame(Date.now()), 1000 / 20);
process.on('SIGINT', () => {
clearInterval(id);
process.stdout.write(ESC + '?25h' + ESC + '2J'); // show cursor, clear
process.exit();
});
```
Use `ESC + '2J'` to clear the whole screen, `ESC + 'H'` for home (cheaper per frame than clearing). Color with `\x1b[38;2;R;G;Bm` (truecolor) and reset with `\x1b[0m`.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained web ASCII piece (generative field, image/video→ASCII, `AsciiEffect` scene) the deliverable is **one HTML file that opens directly in a browser** — the `<pre>`/canvas, the ramp, and the rAF loop inline (Three.js from CDN if used). No build step. One file is the right tier; don't reach for a bundler. (Terminal/CLI pieces verify differently — capture stdout or a screenshot of the terminal.)
**Output contract:**
- One `.html` file: the render target, the brightness ramp, and the `requestAnimationFrame` loop in one inline `<script>`.
- Drive frames from an **injectable time** (not `Date.now()`/`performance.now()` directly) and seed any randomness, so a frame is reproducible.
**Seek harness — freeze the rAF loop on a deterministic frame.** `?t=N` renders exactly one frame at simulated time `N` instead of looping, so a screenshot is reproducible. Feed `N` where the loop reads time, and fix the seed:
```html
<script>
const t = new URLSearchParams(location.search).get("t");
// your frame(time){…} reads `time`, not Date.now(); RNG uses a fixed seed
if (t !== null) { frame(parseFloat(t)); } // render ONE frame, no rAF
else { (function loop(now){ frame(now); requestAnimationFrame(loop); })(0); }
window.__ready = true;
</script>
```
**Verify loop — render → freeze → screenshot → check:** render at a few simulated times (`?t=0`, `?t=1000`, `?t=2000`), screenshot each, and check **fidelity** (ramp reads dark→light correctly, motion evolves) plus **artifacts** (vertical stretch from missing cell-aspect correction, wrong invert on a light bg, clipped grid, FOUC before the monospace font loads — fonts settle the cell metrics, so wait). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/ascii.html?t=1000" frame-mid.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN (Three.js, if used) loads, monospace font applied.
2. `?t=N` renders one deterministic frame (injected time + fixed seed), no live loop.
3. Screenshotted at 3 simulated times — matches the brief, no vertical stretch or wrong-invert.
4. `prefers-reduced-motion` honored — stop/slow the rAF loop, show a static frame.
5. Easing is intentional — frame rate throttled on purpose (12–24fps for retro feel), ramp ordering deliberate.
## Quick reference
| Need | Approach |
|------|----------|
| Simple generative field | `<pre>` + `textContent`, sine/noise → ramp |
| Photo fidelity | 70-level Bourke ramp, luminance from sRGB weights |
| Per-char color / 60fps | Canvas `fillText` per cell |
| Video | `<video>` → offscreen canvas → `getImageData` per frame |
| 3D scene | Three.js `AsciiEffect.render(scene, camera)` |
| Terminal | ANSI `\x1b[H` home + throttle 12–24fps, hide cursor |
| Aspect fix | `rows = cols * imgAspect * 0.5` |
## Reference files
- `references/rendering.md` — Full brightness ramp tables (10/70/extended), pixel sampling math and cell aspect correction, `<pre>` vs canvas tradeoffs with code, ANSI terminal frame loop with truecolor, and complete `AsciiEffect` wiring.
- `scripts/img-to-ascii.mjs` — Runnable Node script that converts a PNG/JPG file to ASCII text, with `--cols`, `--invert`, and `--ramp` flags.
@@ -1,194 +0,0 @@
# ASCII Rendering Reference
Detailed tables, sampling math, and complete renderers for ASCII animation.
## Brightness ramp tables
Order is **dark → light**. Index into the ramp with `Math.round(lum * (ramp.length - 1))` where `lum` is 0..1.
### 10-level (compact, generative)
```
.:-=+*#%@
```
Good for low-resolution generative fields and terminals. Distinct steps, low banding artifacts.
### 70-level Paul Bourke ramp (photo fidelity)
```
$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'.
```
This is ordered **light → dark** (densest first). For luminance mapping, either reverse the string or use `index = Math.round((1 - lum) * (len - 1))`. Best results for grayscale photos; whitespace at the end represents black/empty.
### 16-level extended (balance)
```
.'`,^:";~-_+<>i!lI?/\|()1{}[]rcvunxzjftLCJUYXZO0Qoahkbdpqwm*WMB8&%$#@
```
Truncate or downsample to taste. For UI/loaders a hand-picked 8–12 char ramp usually looks cleaner than a 70-char ramp because the steps are visually distinct.
### Block / shade characters (Unicode, smoother gradient)
```
░▒▓█
```
Or with the 1/8 block fills for vertical bars: `▁▂▃▄▅▆▇█`. Renders as a near-continuous gradient in monospace fonts; great for waveforms, meters, and smooth fades. Requires a font with box-drawing glyphs (most monospace fonts have them).
## Luminance computation
Perceptual (sRGB-weighted, recommended):
```js
const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; // 0..1
```
Fast average (acceptable for stylized output):
```js
const lum = (r + g + b) / (3 * 255);
```
Invert for dark-on-light surfaces: `lum = 1 - lum`. Apply gamma to spread midtones: `lum = Math.pow(lum, 0.8)` (lower exponent brightens).
## Pixel sampling and cell aspect correction
Monospace cells are about twice as tall as wide. Real cell aspect depends on the font: measure once.
```js
function measureCellAspect(fontFamily = 'monospace', fontPx = 16) {
const cv = document.createElement('canvas');
const ctx = cv.getContext('2d');
ctx.font = `${fontPx}px ${fontFamily}`;
const w = ctx.measureText('M').width; // glyph advance width
const h = fontPx * 1.0; // with line-height: 1
return w / h; // ~0.5 for most fonts
}
```
Compute the character grid for a source image, correcting aspect so the picture is not vertically stretched:
```js
function gridSize(imgW, imgH, cols, cellAspect = 0.5) {
const rows = Math.round(cols * (imgH / imgW) * cellAspect);
return { cols, rows };
}
```
Draw the source into an offscreen canvas at exactly `cols × rows`, then read all pixels once with `getImageData(0, 0, cols, rows)`. One `getImageData` call per frame is far cheaper than per-pixel reads.
## `<pre>` vs canvas
| Aspect | `<pre>` + textContent | Canvas `fillText` |
|--------|----------------------|-------------------|
| Setup | trivial, one string | per-cell draw loop |
| Color | single color (or per-span, slow) | per-char color cheap |
| Max size | ~120×60 @ 30fps | thousands of cells @ 60fps |
| Selectable text | yes | no |
| Best for | generative fields, loaders | video, per-char color, large grids |
`<pre>` styling that avoids gaps and stretching:
```css
pre { font-family: ui-monospace, monospace; line-height: 1; letter-spacing: 0;
margin: 0; white-space: pre; }
```
Canvas per-char color renderer:
```js
function drawAsciiCanvas(ctx, chars, colors, cols, rows, cellW, cellH) {
ctx.clearRect(0, 0, cols * cellW, rows * cellH);
ctx.textBaseline = 'top';
ctx.font = `${cellH}px monospace`;
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const i = y * cols + x;
ctx.fillStyle = colors[i]; // e.g. `rgb(r,g,b)`
ctx.fillText(chars[i], x * cellW, y * cellH);
}
}
}
```
## ANSI terminal frame loop (Node)
```js
const ESC = '\x1b[';
const out = process.stdout;
function start(render, fps = 20) {
out.write(ESC + '?25l'); // hide cursor
out.write(ESC + '2J'); // clear screen once
const interval = 1000 / fps;
let start = Date.now();
const id = setInterval(() => {
const t = Date.now() - start;
out.write(ESC + 'H'); // home (cheap, no full clear)
out.write(render(t, out.columns || 80, out.rows || 24));
}, interval);
const stop = () => {
clearInterval(id);
out.write(ESC + '0m' + ESC + '?25h' + ESC + '2J' + ESC + 'H');
process.exit(0);
};
process.on('SIGINT', stop);
return stop;
}
// Truecolor per character: foreground `\x1b[38;2;R;G;Bm`, reset `\x1b[0m`.
function colored(ch, r, g, b) {
return `${ESC}38;2;${r};${g};${b}m${ch}${ESC}0m`;
}
// Example: plasma using full terminal size
start((t, cols, rows) => {
const ramp = ' .:-=+*#%@';
let s = '';
for (let y = 0; y < rows - 1; y++) {
for (let x = 0; x < cols; x++) {
const v = Math.sin(x * 0.15 + t * 0.001)
+ Math.sin(y * 0.25 + t * 0.0015)
+ Math.sin((x + y) * 0.1 + t * 0.0008);
const lum = (v + 3) / 6;
s += ramp[Math.round(lum * (ramp.length - 1))];
}
s += '\n';
}
return s;
});
```
Notes: writing `ESC + 'H'` (home) and overwriting is much smoother than clearing the screen every frame, which causes flicker. Avoid printing a trailing newline on the last row or the terminal scrolls. `out.columns`/`out.rows` give the live terminal size; recompute the grid on `process.stdout.on('resize', ...)`.
## Three.js AsciiEffect — complete wiring
```js
import * as THREE from 'three';
import { AsciiEffect } from 'three/addons/effects/AsciiEffect.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
const effect = new AsciiEffect(renderer, ' .:-=+*#%@', { invert: true, resolution: 0.2 });
effect.setSize(innerWidth, innerHeight);
effect.domElement.style.color = 'white';
effect.domElement.style.backgroundColor = 'black';
document.body.appendChild(effect.domElement); // append the EFFECT's DOM, not renderer.domElement
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 1, 1000);
camera.position.z = 4;
scene.add(new THREE.PointLight(0xffffff, 3).position.set(5, 5, 5));
scene.add(new THREE.AmbientLight(0x808080));
const mesh = new THREE.Mesh(
new THREE.TorusKnotGeometry(1, 0.3, 100, 16),
new THREE.MeshStandardMaterial({ flatShading: true })
);
scene.add(mesh);
const controls = new OrbitControls(camera, effect.domElement); // attach to effect DOM
function animate(t) {
mesh.rotation.y = t * 0.0005;
effect.render(scene, camera); // render through the effect
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix();
effect.setSize(innerWidth, innerHeight);
});
```
Key gotchas: append `effect.domElement` (not the renderer's canvas) and call `effect.render`, not `renderer.render`. `resolution` (default ~0.15) controls character density; lower = fewer, larger characters. Lighting matters — ASCII reads luminance, so use strong directional contrast and `flatShading` for crisp edges.
---
Map brightness to the right glyph ramp and the characters come alive. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=ascii-animation)** — the AI motion agent for editable, on-brand motion graphics.
@@ -1,64 +0,0 @@
#!/usr/bin/env node
// img-to-ascii.mjs — Convert a PNG/JPG image to ASCII text.
//
// Usage:
// node img-to-ascii.mjs <image> [--cols 120] [--invert] [--ramp " .:-=+*#%@"]
//
// Dependency: sharp (npm i sharp). Sharp decodes PNG/JPG/WebP and resizes.
//
// Notes:
// - Applies monospace cell-aspect correction (cells are ~2x taller than wide),
// so rows = cols * (imgH/imgW) * 0.5.
// - Luminance uses sRGB perceptual weights (0.2126/0.7152/0.0722).
import sharp from 'sharp';
function parseArgs(argv) {
const args = { cols: 120, invert: false, ramp: ' .:-=+*#%@', file: null };
for (let i = 2; i < argv.length; i++) {
const a = argv[i];
if (a === '--cols') args.cols = parseInt(argv[++i], 10);
else if (a === '--invert') args.invert = true;
else if (a === '--ramp') args.ramp = argv[++i];
else if (!a.startsWith('--')) args.file = a;
}
return args;
}
async function main() {
const { cols, invert, ramp, file } = parseArgs(process.argv);
if (!file) {
console.error('Usage: node img-to-ascii.mjs <image> [--cols N] [--invert] [--ramp "..."]');
process.exit(1);
}
const CELL_ASPECT = 0.5; // monospace width:height
const meta = await sharp(file).metadata();
const rows = Math.max(1, Math.round(cols * (meta.height / meta.width) * CELL_ASPECT));
// Resize to the character grid, drop alpha, get raw RGB bytes.
const { data } = await sharp(file)
.resize(cols, rows, { fit: 'fill' })
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const last = ramp.length - 1;
const lines = [];
for (let y = 0; y < rows; y++) {
let line = '';
for (let x = 0; x < cols; x++) {
const i = (y * cols + x) * 3;
let lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255;
if (invert) lum = 1 - lum;
line += ramp[Math.round(lum * last)];
}
lines.push(line);
}
process.stdout.write(lines.join('\n') + '\n');
}
main().catch((err) => {
console.error('Error:', err.message);
process.exit(1);
});
@@ -0,0 +1,24 @@
# Caption Animation
Turn a transcript or voiceover into word-timed, scroll-stopping captions: each word pops in on the syllable, the active word highlights, and the text stays glued to the narration. Build the kind of captions that drive watch-time on TikTok, Reels, and Shorts — readable, on-beat, and inside the safe area. For short-form creators burning open captions onto vertical video.
## When it activates
- "Add animated captions," "make TikTok captions," or "karaoke captions."
- "Word-by-word subtitles," "auto subtitles," or "highlight the active word."
- "Burn in captions to a video" or "sync captions to a voiceover/narration."
- "Turn an SRT/transcript into animated text."
## Example prompts
- "Turn this Whisper transcript into karaoke captions with a per-word pop."
- "Restyle these auto subtitles into a branded, Hormozi-style reveal."
- "Burn word-level captions onto my voiceover and export a sidecar SRT."
## What's inside
- `SKILL.md` — the transcribe → normalize → page → animate → place → export pipeline.
- `references/word-timed-captions.md` — deeper guidance on word-level timing and animation.
---
Part of **[Short-Form Video Skills](../../)** · Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=tiktok-video-skills&utm_content=skill_footer&utm_term=caption-animation)** — the AI motion agent for editable, on-brand motion graphics.
+177
View File
@@ -0,0 +1,177 @@
---
name: caption-animation
description: This skill should be used when the user asks to "add animated captions", "make TikTok captions", "karaoke captions", "word-by-word subtitles", "auto subtitles", "highlight the active word", "burn in captions to a video", "sync captions to a voiceover/narration", or "turn an SRT/transcript into animated text". Covers word-level timing from Whisper, per-word pop/scale-in, active-word highlight, 9:16 safe-area placement, readable type, and burn-in vs sidecar SRT/VTT.
version: 0.1.0
---
# Caption Animation
Turn a transcript or voiceover into word-timed, scroll-stopping captions: each word pops in on the syllable, the active word highlights, and the text stays glued to the narration. Build the kind of captions that drive watch-time on TikTok, Reels, and Shorts — readable, on-beat, and inside the safe area.
## When to use
- Word-by-word or karaoke captions on short-form vertical video (9:16).
- Burning open captions onto a voiceover/narration track from a transcript.
- Turning a Whisper/SRT transcript into animated text in Remotion or on the web.
- Restyling auto-generated subtitles into a branded, "Hormozi-style" reveal.
## The pipeline
| Stage | Job | Tool |
|---|---|---|
| Transcribe | Audio → word-level timestamps | Whisper (`@remotion/install-whisper-cpp`), AssemblyAI |
| Normalize | → `{ text, startMs, endMs }[]` tokens | `@remotion/captions` `Caption` type |
| Page | Group words into 1–4 word "pages" | `createTikTokStyleCaptions()` |
| Animate | Per-word pop + active-word highlight | Remotion `spring()` / CSS |
| Place | Safe-area, readable type | layout rules below |
| Export | Burn-in (MP4) and/or sidecar SRT/VTT | Remotion render / file emit |
## Two non-negotiable rules
1. **Word-level timing, not line-level.** Karaoke reads as magic only when each word lands on the syllable. Always transcribe to word timestamps; never fake them by splitting a line evenly over its duration — drift is instantly visible.
2. **Readability beats style.** Captions are read on a phone, in sunlight, muted. Bold sans-serif, heavy stroke or shadow, high contrast first; decoration second. A caption nobody can read is decoration, not a caption.
## Word timing from a transcript
Whisper emits word-level timestamps directly. Normalize every source into one flat token shape so the renderer never cares where the words came from:
```ts
// Caption token — the one shape everything downstream consumes
type Token = { text: string; startMs: number; endMs: number };
// Parse an SRT cue block "00:00:01,200 --> 00:00:01,640" into ms
const toMs = (t: string) => {
const [h, m, rest] = t.split(":");
const [s, ms] = rest.split(",");
return ((+h * 60 + +m) * 60 + +s) * 1000 + +ms;
};
```
If only sentence-level cues exist, re-transcribe for word timing — do not interpolate. Whisper's `medium.en` is ~2x faster than `large` and accurate enough for clean voice audio.
## Per-word pop-in (Remotion)
Drive each word's scale and opacity off a spring anchored to its own `startMs`. The micro-overshoot is what makes it feel "alive".
```tsx
import { useCurrentFrame, useVideoConfig, spring, interpolate } from "remotion";
const Word: React.FC<{ token: Token; active: boolean }> = ({ token, active }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const enter = (token.startMs / 1000) * fps; // word's own entrance frame
const p = spring({ frame: frame - enter, fps, config: { damping: 12, mass: 0.6 } });
const scale = interpolate(p, [0, 1], [0.6, 1]); // pop from 60% → 100% (overshoots)
return (
<span style={{
display: "inline-block",
transform: `scale(${scale})`,
opacity: interpolate(p, [0, 1], [0, 1]),
color: active ? "#FFE45E" : "#FFFFFF", // active-word highlight
transition: "color 80ms linear",
}}>{token.text}&nbsp;</span>
);
};
```
Compute `active` by testing `frame` against each token's `[startMs, endMs]`. Keep the highlight a single accent color or a filled "box" behind the live word — never animate every word's color at once.
## Pages, not walls of text
Show 1–4 words at a time. Use Remotion's `createTikTokStyleCaptions()` (or group manually) and tune `combineTokensWithinMilliseconds`: ~200–500ms for true word-by-word, ~1000–1500ms for short readable phrases.
```ts
import { createTikTokStyleCaptions } from "@remotion/captions";
const { pages } = createTikTokStyleCaptions({
captions, combineTokensWithinMilliseconds: 1200, // ~2–3 words per page
});
```
## Web/CSS pop (no Remotion)
For a DOM/live player, give each word its own `animation-delay` equal to `startMs`:
```css
.word { display:inline-block; opacity:0; animation: pop .26s cubic-bezier(.34,1.56,.64,1) forwards; }
@keyframes pop { from { opacity:0; transform:translateY(.18em) scale(.7) } to { opacity:1; transform:none } }
.word.active { color:#FFE45E; }
```
```js
words.forEach(w => { const el = mk(w.text); el.style.animationDelay = `${w.startMs}ms`; track.append(el); });
```
## Readable type and safe-area placement (9:16, 1080×1920)
| Property | Value | Why |
|---|---|---|
| Font | Bold/ExtraBold sans (Montserrat, Inter, Helvetica) | Reads on small, busy screens |
| Size | 56–80px (≈8% of frame height), min 45px | Legible muted on a phone |
| Stroke | 2–6px solid black outline | Survives any background |
| Shadow | Soft drop shadow as backup to stroke | Separation on bright frames |
| Case | Uppercase or sentence; high contrast fill | Punch + scannability |
| Vertical pos | Center band, ~62–70% down | Above the UI, below the action |
| Bottom safe | Keep clear of bottom ~280px / 15% | Avoids caption/CTA/audio UI |
| Side safe | Keep within center 80% width | Avoids right-rail icons |
Place captions in the center band — not pinned to the very bottom, where the platform UI (username, audio, buttons) lives. Pad text to a max of ~2 lines.
## Sync to a voiceover / narration
The transcript already carries the timing of the exact audio. Lay that same audio under the composition and keep timestamps in the audio's timebase — captions and voice stay locked with zero manual nudging. If the VO is re-recorded, re-transcribe; never hand-shift offsets.
## Burn-in vs sidecar SRT/VTT
| | Burn-in (open) | Sidecar SRT/VTT (closed) |
|---|---|---|
| Where | Pixels in the MP4 | Separate `.srt`/`.vtt` file |
| Social (TikTok/Reels) | Required — guaranteed, styleable | Often ignored by the platform |
| Accessibility (ADA/WCAG) | Does not satisfy alone | Required (toggleable) |
| Best practice | Burn animated captions for social | Also ship a sidecar for the web/SEO |
Emit both: burn the animated captions for social, and write a plain SRT/VTT from the same tokens for accessible/SEO playback.
## Output checklist
- Word-level timestamps (real, from transcription) — no even-split fakery.
- Per-word pop with micro-overshoot; one accent color for the active word.
- 1–4 words per page; never a wall of text.
- Bold sans, 56–80px, 2–6px stroke + shadow, high contrast.
- Center band, clear of bottom ~280px and side rails.
- Audio laid under composition; timestamps in the audio timebase.
- Ship burn-in for social and a sidecar SRT/VTT for accessibility.
## Deliver & verify (rendered stills → MP4)
> **Packaged helper** (`scripts/`): tile your stills with `scripts/contact-sheet.sh sheet.png f-hook.png f-mid.png f-end.png`, then assert the encode with `scripts/probe-mp4.sh out.mp4 [WxH] [fps]`. See `scripts/README.md`.
Captions ship as a Remotion composition (`<Composition>` + zod `schema` + `defaultProps`) — all word motion frame-driven off `useCurrentFrame()`, never `Date.now()` / `Math.random()` / timers. Deliverable = `out/*.mp4` (burned-in) + the project + the sidecar SRT/VTT. 9:16 vertical (1080×1920) is the default.
**Verify loop — render stills → inspect → encode.** Word timing is the thing that breaks; check it at exact frames before you spend an encode.
```bash
# Stills at start / a sampled active-word frame / end — WITH SHIPPED PROPS (real tokens + audio)
npx remotion still Captions out/f-start.png --frame=0 --props='{"captionsSrc":"vo.json"}'
npx remotion still Captions out/f-mid.png --frame=90 --props='{"captionsSrc":"vo.json"}'
npx remotion still Captions out/f-end.png --frame=N --props='{"captionsSrc":"vo.json"}' # N = durationInFrames-1
# Inspect each PNG:
# - the word highlighted at frame 90 is the word whose [startMs,endMs] contains 90/fps (no drift)
# - burn-in legible: bold sans, stroke+shadow holds, no clipping
# - 9:16 safe area: caption sits in the center band, clear of top ~12% and bottom ~20-35% (captions/CTA/audio UI) and the right action rail
npx remotion render Captions out/captions.mp4 --props='{"captionsSrc":"vo.json"}' # encode once stills are right
npx remotion render Captions out/demo.gif --codec=gif # README proof clip
```
Use `npx remotion compositions` to read `durationInFrames`/`fps` and pick the active-word + end frames.
**Before you finish:**
1. Stills render cleanly at frame 0, a mid active-word frame, and last — no missing font/audio.
2. The correct word is highlighted at the sampled frame (frame/fps lands inside its token); no even-split fakery.
3. Burn-in is legible (stroke+shadow) and the caption is fully inside the 9:16 safe area at every checked frame.
4. Frame-driven only — no `Date.now()` / `Math.random()` / timers.
5. Shipped props (real tokens, not just `defaultProps`) render correctly; MP4 + sidecar SRT/VTT emitted, GIF optional.
## Reference files
- `references/word-timed-captions.md` — end-to-end build: Whisper transcription and the `Caption` type, a full SRT parser, Remotion word-timed component with active-highlight, manual paging, an SRT/VTT emitter, per-platform safe-area maps, and a readable-type spec sheet.
@@ -0,0 +1,254 @@
# Word-Timed Captions — End-to-End Build
A complete, runnable path from audio/transcript to animated burn-in captions plus a sidecar SRT/VTT. Code targets Remotion for burn-in and plain JS for the web; the data shapes are framework-agnostic.
## 1. The one data shape
Everything normalizes to a flat array of word tokens. Get to this shape and the renderer never cares about the source.
```ts
export type Token = { text: string; startMs: number; endMs: number };
export type Page = { startMs: number; endMs: number; tokens: Token[] };
```
Remotion's `@remotion/captions` uses a compatible `Caption` type:
```ts
type Caption = { text: string; startMs: number; endMs: number; timestampMs: number | null; confidence: number | null };
```
## 2. Transcribe to word-level timing (Whisper)
Word timestamps are non-negotiable for karaoke. Whisper produces them natively.
```bash
npx @remotion/install-whisper-cpp # one-time: installs whisper.cpp + a model
```
```ts
import { transcribe, toCaptions } from "@remotion/install-whisper-cpp";
const { transcription } = await transcribe({
inputPath: "voiceover.wav", // 16kHz mono WAV is ideal for whisper.cpp
model: "medium.en", // medium.en ≈ 2x faster than large, accurate on clean voice
tokenLevelTimestamps: true, // <-- the key flag: per-word, not per-line
whisperPath: "./whisper.cpp",
});
const { captions } = toCaptions({ transcription }); // → Caption[]
```
Tips:
- Feed clean voice audio (denoise/normalize first). Background music wrecks word boundaries.
- `large` is most accurate but 2–3x real-time on a laptop. Use `medium.en` unless accuracy is critical.
- Cloud alternatives (AssemblyAI, Deepgram, OpenAI Whisper API) also return word timing — map their `words[]` into `Token` the same way.
Map any token shape into `Token`:
```ts
const toTokens = (caps: Caption[]): Token[] =>
caps.map(c => ({ text: c.text.trim(), startMs: c.startMs, endMs: c.endMs }));
```
## 3. Parse an existing SRT into tokens
When handed an SRT, parse cues; if cues are sentence-level, re-transcribe for word timing rather than interpolating.
```ts
const toMs = (t: string) => {
const [h, m, rest] = t.trim().split(":");
const [s, ms] = rest.split(",");
return ((+h * 60 + +m) * 60 + +s) * 1000 + +ms;
};
export function parseSrt(src: string): Token[] {
return src.trim().split(/\n\s*\n/).map(block => {
const lines = block.split("\n");
const time = lines.find(l => l.includes("-->"))!;
const [a, b] = time.split("-->");
const text = lines.slice(lines.indexOf(time) + 1).join(" ").trim();
return { text, startMs: toMs(a), endMs: toMs(b) };
});
}
```
## 4. Page the tokens (1–4 words at a time)
Either use Remotion's helper or group manually. Manual grouping by gap + max-words keeps full control:
```ts
export function paginate(tokens: Token[], maxWords = 3, maxGapMs = 1200): Page[] {
const pages: Page[] = [];
let cur: Token[] = [];
for (const t of tokens) {
const span = cur.length ? t.endMs - cur[0].startMs : 0;
if (cur.length >= maxWords || span > maxGapMs) {
if (cur.length) pages.push(pageOf(cur)); cur = [];
}
cur.push(t);
}
if (cur.length) pages.push(pageOf(cur));
return pages;
}
const pageOf = (ts: Token[]): Page => ({ startMs: ts[0].startMs, endMs: ts.at(-1)!.endMs, tokens: ts });
```
Remotion equivalent:
```ts
import { createTikTokStyleCaptions } from "@remotion/captions";
const { pages } = createTikTokStyleCaptions({ captions, combineTokensWithinMilliseconds: 1200 });
// 200–500ms → word-by-word; 1000–1500ms → short readable phrases
```
## 5. Remotion component: word-timed with active highlight
```tsx
import { AbsoluteFill, Audio, Sequence, useCurrentFrame, useVideoConfig,
spring, interpolate, staticFile } from "remotion";
const CAPTION_STYLE: React.CSSProperties = {
fontFamily: "Montserrat, Inter, sans-serif",
fontWeight: 800,
fontSize: 72, // ~8% of 1920px height
color: "#fff",
textAlign: "center",
textTransform: "uppercase",
WebkitTextStroke: "5px #000", // heavy outline survives any background
paintOrder: "stroke fill", // stroke behind fill, not clipping glyphs
textShadow: "0 4px 16px rgba(0,0,0,.55)",
lineHeight: 1.1,
padding: "0 80px", // keep inside center 80% width
};
const Word: React.FC<{ token: Token; active: boolean }> = ({ token, active }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const enter = (token.startMs / 1000) * fps;
const p = spring({ frame: frame - enter, fps, config: { damping: 12, mass: 0.6 } });
return (
<span style={{
display: "inline-block",
transform: `scale(${interpolate(p, [0, 1], [0.6, 1])})`,
opacity: interpolate(p, [0, 1], [0, 1]),
color: active ? "#FFE45E" : undefined,
transition: "color 80ms linear",
}}>{token.text}&nbsp;</span>
);
};
export const Captions: React.FC<{ pages: Page[]; audio: string }> = ({ pages, audio }) => {
const { fps } = useVideoConfig();
const f = (ms: number) => Math.round((ms / 1000) * fps);
const frame = useCurrentFrame();
return (
<AbsoluteFill>
<Audio src={staticFile(audio)} /> {/* same audio the transcript came from */}
{pages.map((pg, i) => (
<Sequence key={i} from={f(pg.startMs)} durationInFrames={Math.max(1, f(pg.endMs - pg.startMs))}>
<AbsoluteFill style={{ justifyContent: "flex-start", alignItems: "center", paddingTop: "62%" }}>
<div style={CAPTION_STYLE}>
{pg.tokens.map((t, j) => {
const now = (frame / fps) * 1000;
return <Word key={j} token={t} active={now >= t.startMs && now < t.endMs} />;
})}
</div>
</AbsoluteFill>
</Sequence>
))}
</AbsoluteFill>
);
};
```
Because the `<Audio>` and the timestamps share one timebase, voice and captions stay locked with no manual nudging. Re-record the VO → re-transcribe → done.
## 6. Web/CSS path (live DOM player)
```js
function renderTrack(tokens, mountEl) {
tokens.forEach(t => {
const el = document.createElement("span");
el.className = "word";
el.textContent = t.text + " ";
el.style.animationDelay = `${t.startMs}ms`; // each word pops on its own start
mountEl.append(el);
});
}
// drive .active off the media element's currentTime
audio.addEventListener("timeupdate", () => {
const ms = audio.currentTime * 1000;
[...track.children].forEach((el, i) =>
el.classList.toggle("active", ms >= tokens[i].startMs && ms < tokens[i].endMs));
});
```
```css
.cap { font: 800 72px/1.1 Montserrat, sans-serif; text-transform: uppercase;
color:#fff; -webkit-text-stroke:5px #000; paint-order:stroke fill;
text-shadow:0 4px 16px rgba(0,0,0,.55); text-align:center; }
.word { display:inline-block; opacity:0; animation: pop .26s cubic-bezier(.34,1.56,.64,1) forwards; }
.word.active { color:#FFE45E; }
@keyframes pop { from { opacity:0; transform:translateY(.18em) scale(.7) } to { opacity:1; transform:none } }
```
## 7. Emit a sidecar SRT / VTT from the same tokens
Burn-in alone does not satisfy ADA/WCAG and many platforms ignore uploaded tracks — so ship both. Group tokens into readable cues and serialize:
```ts
const pad = (n: number, w = 2) => String(n).padStart(w, "0");
const stamp = (ms: number, sep: string) => {
const h = Math.floor(ms / 3.6e6), m = Math.floor(ms % 3.6e6 / 6e4),
s = Math.floor(ms % 6e4 / 1000), x = ms % 1000;
return `${pad(h)}:${pad(m)}:${pad(s)}${sep}${pad(x, 3)}`;
};
export const toSrt = (pages: Page[]) => pages.map((p, i) =>
`${i + 1}\n${stamp(p.startMs, ",")} --> ${stamp(p.endMs, ",")}\n${p.tokens.map(t => t.text).join(" ")}`
).join("\n\n") + "\n";
export const toVtt = (pages: Page[]) => "WEBVTT\n\n" + pages.map(p =>
`${stamp(p.startMs, ".")} --> ${stamp(p.endMs, ".")}\n${p.tokens.map(t => t.text).join(" ")}`
).join("\n\n") + "\n";
```
Use SRT for the broadest platform support; VTT when styling/positioning cues or serving on the web.
## 8. Per-platform safe areas (1080×1920, 9:16)
| Platform | Bottom keep-clear | Top keep-clear | Side keep-clear | Notes |
|---|---|---|---|---|
| TikTok | ~340px | ~120px | ~110px right rail | Captions, audio title, action buttons crowd the bottom-right |
| Instagram Reels | ~280px | ~130px | ~60px | Username/CTA bar at bottom |
| YouTube Shorts | ~240px | ~100px | ~120px right rail | Title + channel at bottom-left |
| Facebook Reels | ~300px | ~130px | ~80px | Similar to Reels |
Safe rule across all: place caption baseline at ~62–70% of frame height, keep text within the center 80% width, and never let it enter the bottom ~15%.
## 9. Readable-type spec sheet
| Property | Recommended | Floor |
|---|---|---|
| Weight | 800 (ExtraBold) | 700 |
| Size @1080p | 56–80px | 45px |
| Stroke | 4–6px solid #000 | 2px |
| Shadow | `0 4px 16px rgba(0,0,0,.55)` | soft 1px |
| Active accent | one color (e.g. #FFE45E) or filled box | — |
| Lines on screen | 1–2 | 2 max |
| Words per page | 1–4 | 5 max |
Set `paint-order: stroke fill` so a thick stroke sits behind the glyph instead of eating it. Test on a bright frame and a busy frame; if it survives both, it ships.
## 10. Render
```bash
npx remotion render src/index.ts Captions out/captions.mp4 \
--props='{"pages": ..., "audio": "voiceover.wav"}'
```
A 10-minute video with animated captions can take 30–60 min to render locally; render long-form in segments, or render on Remotion Lambda for parallel speed.
---
## Built by the team behind iart.ai
This skill is part of an open motion-graphics collection from iart.ai — the AI motion agent that turns data, scripts, and designs into editable motion graphics (Remotion → MP4). If you'd rather not hand-build this, iart.ai can auto-time captions to a narration track and one-click burn them in from a template — change the text/audio and re-export. → [iart.ai](https://iart.ai/?utm_source=github&utm_medium=reference&utm_campaign=tiktok-video-skills&utm_content=ref_footer&utm_term=caption-animation)
+25
View File
@@ -0,0 +1,25 @@
# Countdown Video
Make a countdown that ends exactly when it should. The whole craft is one idea: derive the remaining time from the frame (or a monotonic timestamp), then format and animate that number — never count down with a `setInterval`. Covers livestream "starting soon" screens, launch and flash-sale countdowns, and looping backgrounds. For creators who need a timer that lands on zero on the exact frame.
## When it activates
- "Make a countdown timer video" or "create a countdown animation."
- "Build a stream starting soon countdown" or "do an event/launch/sale countdown."
- "Animate a mm:ss or dd:hh:mm:ss timer."
- "Add digit roll/flip transitions to a counter" or "loop a countdown background."
## Example prompts
- "Build a 10-minute 'be right back' livestream countdown."
- "Make a dd:hh:mm:ss launch countdown to a fixed target date."
- "Add flip transitions to an mm:ss timer that hits zero on the exact frame."
## What's inside
- `SKILL.md` — frame-accurate (drift-free) timers, time formatting, and a configurable duration prop.
- `references/countdown-cookbook.md` — recipes for common countdown scenarios.
- `references/digit-flip.md` — digit flip/roll transition techniques.
---
Part of **[Short-Form Video Skills](../../)** · Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=tiktok-video-skills&utm_content=skill_footer&utm_term=countdown-video)** — the AI motion agent for editable, on-brand motion graphics.
+152
View File
@@ -0,0 +1,152 @@
---
name: countdown-video
description: This skill should be used when the user asks to "make a countdown timer video", "create a countdown animation", "build a stream starting soon countdown", "do an event/launch/sale countdown", "animate a mm:ss or dd:hh:mm:ss timer", "add digit roll/flip transitions to a counter", or "loop a countdown background". Covers frame-accurate (drift-free) timers, digit flip/roll motion, time formatting, and a configurable duration prop.
version: 0.1.0
---
# Countdown Video
Make a countdown that ends exactly when it should. The whole craft is one idea: derive the remaining time from the frame (or a monotonic timestamp), then format and animate that number — never count down with a `setInterval`. Covers livestream "starting soon" screens, launch/sale countdowns, and looping backgrounds.
## When to use
- "Starting soon" / "be right back" livestream screens with a 5–10 min timer.
- Launch and flash-sale countdowns (dd:hh:mm:ss down to a target date; mm:ss for urgency).
- Any animated counter where the number must land on zero on the exact frame.
## The one rule: drive the number from the clock, never a tick
A `setInterval(fn, 1000)` countdown **drifts** — the callback fires *at least* 1000 ms later, never exactly, and stacks up when the tab is throttled or a render frame is slow. Reports of ~1 second lost per minute are common. The fix is the same for rendered video and live web: compute remaining time as a pure function of an authoritative clock, so a late frame self-corrects on the next frame instead of accumulating error.
| Context | Authoritative clock | Remaining time |
|---|---|---|
| Remotion render | `useCurrentFrame()` | `total − frame/fps` |
| Web (live page) | `performance.now()` or `Date.now()` | `targetMs − now` |
| To a fixed date | `Date.now()` | `targetTimestamp − Date.now()` |
Never store remaining time in state and decrement it. Recompute it every frame.
## Frame-accurate countdown (Remotion → MP4)
`useCurrentFrame()` is deterministic: frame N is always rendered at exactly `N/fps` seconds. Subtract from the total and the timer is drift-free by construction.
```tsx
import { useCurrentFrame, useVideoConfig } from "remotion";
export const Countdown: React.FC<{ durationInSeconds: number }> = ({
durationInSeconds,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
// remaining seconds, clamped at 0 — ceil so "1" shows for its full second
const elapsed = frame / fps;
const remaining = Math.max(0, Math.ceil(durationInSeconds - elapsed));
return <div style={{ fontVariantNumeric: "tabular-nums" }}>{formatMMSS(remaining)}</div>;
};
```
`durationInSeconds` is a **prop**, not a constant — the same composition renders a 5-minute stream timer or a 30-second sale timer by changing one input. Set the composition's `durationInFrames` to `durationInSeconds * fps` so the video is exactly as long as the countdown.
## Web timer (live page, requestAnimationFrame)
For a live page, drive an rAF loop from `performance.now()` and only repaint when the displayed second changes (no work 60×/sec for a 1 Hz number):
```js
const start = performance.now();
let lastShown = -1;
function tick(now) {
const remaining = Math.max(0, Math.ceil(duration - (now - start) / 1000));
if (remaining !== lastShown) { render(remaining); lastShown = remaining; }
if (remaining > 0) requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
```
Counting down to a fixed date is the same idea with `Date.now()`: `Math.max(0, target - Date.now())`. See `references/countdown-cookbook.md` for the full date-target version with timezone handling.
## Time formatting
Break a remaining-seconds integer into fields with division + modulo, then zero-pad. Pick the format to fit the duration — never show `00d 00h 05m` when minutes is all that matters.
```js
const pad = (n) => String(n).padStart(2, "0");
const formatMMSS = (s) => `${pad(Math.floor(s / 60))}:${pad(s % 60)}`;
const formatDHMS = (s) => {
const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600);
const m = Math.floor((s % 3600) / 60), sec = s % 60;
return `${pad(d)}:${pad(h)}:${pad(m)}:${pad(sec)}`;
};
```
| Format | Use | Drop fields when |
|---|---|---|
| `mm:ss` | stream "starting soon", short timers (<1h) | — |
| `hh:mm:ss` | flash sale, same-day event | hide `dd` while 0 |
| `dd:hh:mm:ss` | launch / multi-day countdown | hide leading 0 units for cleaner read |
Always set `font-variant-numeric: tabular-nums` (or a monospace digit font) so digits keep equal width and the layout does not jitter as numbers change.
## Digit roll / flip transitions
A flat number swap reads as cheap; the rolling "odometer" look sells the countdown. Render each digit as a vertical strip 0–9 and translate it by `-digit × digitHeight`. Animate the *position*, not the text content, so the change is a glide, not a pop.
```css
.reel { height: 1em; overflow: hidden; }
.reel .col { transition: transform .45s cubic-bezier(.22,1,.36,1); }
/* col holds stacked 0..9; shift by -value em */
```
In Remotion, drive the strip offset off the frame instead of a CSS transition (so it is deterministic). The flip-card style (top half folds down over the bottom) and the per-digit reel are both detailed, with runnable components, in `references/digit-flip.md`.
## Looping background
Stream screens hold for minutes, so the background must loop seamlessly. Build motion on a cycle that divides evenly into the timeline (e.g. a gradient or particle drift whose period is `loopFrames`), and read it as `frame % loopFrames` so there is no visible seam at the wrap. Keep it low-contrast and slow — the number is the subject; the background is ambience. Recipes in `references/countdown-cookbook.md`.
## Output checklist
- Remaining time recomputed from `useCurrentFrame()` / `performance.now()` every frame — no `setInterval` decrement.
- Timer hits `00:00` on the exact intended frame; `durationInFrames === durationInSeconds × fps`.
- Duration is an input prop, not a hardcoded constant.
- Digits use `tabular-nums`; layout does not shift as numbers change.
- Format matches the span (mm:ss vs dd:hh:mm:ss); leading zero units dropped when distracting.
- Background loop period divides the timeline evenly; no seam at the wrap.
## Deliver & verify (rendered stills → MP4)
> **Packaged helper** (`scripts/`): tile your stills with `scripts/contact-sheet.sh sheet.png f-hook.png f-mid.png f-end.png`, then assert the encode with `scripts/probe-mp4.sh out.mp4 [WxH] [fps]`. See `scripts/README.md`.
The countdown ships as a Remotion composition (`<Composition>` + zod `schema` + `defaultProps`, `durationInSeconds` a prop) — the timer is a pure function of `useCurrentFrame()`, never `setInterval` / `Date.now()` / `Math.random()`. Set `durationInFrames = durationInSeconds * fps`. Deliverable = `out/*.mp4` + the project. 9:16 vertical (1080×1920) is the default.
**Verify loop — render stills → inspect → encode.** The whole point is frame-accuracy, so check the *digit value* at exact frames before encoding.
```bash
# Stills at start / mid / end — WITH SHIPPED PROPS (the real duration you'll render)
npx remotion still Countdown out/f-start.png --frame=0 --props='{"durationInSeconds":300}'
npx remotion still Countdown out/f-mid.png --frame=N --props='{"durationInSeconds":300}'
npx remotion still Countdown out/f-end.png --frame=L --props='{"durationInSeconds":300}' # L = durationInFrames-1
# Inspect each PNG — the digits must read EXACTLY the frame/fps math:
# - at frame N, displayed = ceil(durationInSeconds - N/fps) (e.g. 300s @ 30fps, frame 4500 → 150s → "02:30")
# - last frame reads 00:00 (or the end-state hold); no drift, no off-by-one second
# - tabular-nums: layout does not jitter between frames
# - 9:16 safe area: the timer + brand block sit clear of top ~12% and bottom ~20-35% UI and the right action rail
npx remotion render Countdown out/countdown.mp4 --props='{"durationInSeconds":300}' # encode once digits verify
npx remotion render Countdown out/demo.gif --codec=gif # README proof clip
```
Use `npx remotion compositions` to confirm `durationInFrames`/`fps`, then compute the frame for any second you want to check.
**Before you finish:**
1. Stills render cleanly at frame 0, mid, and last — no errors.
2. The digit value at frame N equals `ceil(durationInSeconds - N/fps)` exactly; last frame hits 00:00 on the intended frame (no drift / off-by-one).
3. Timer + brand stay inside the 9:16 safe area at every checked frame.
4. Frame-driven only — no `setInterval` / `Date.now()` / timers; `tabular-nums` so layout holds.
5. Shipped `durationInSeconds` (not just `defaultProps`) renders correctly; MP4 encoded, GIF optional.
## Reference files
- `references/countdown-cookbook.md` — complete runnable Remotion `<Countdown>` (configurable duration, mm:ss / dd:hh:mm:ss, end-state hold), the count-down-to-a-fixed-date web component with timezone handling, a "starting soon" stream-screen layout (brand block + social handles + looping gradient background), and the seamless-loop background pattern.
- `references/digit-flip.md` — two deterministic digit-animation components: the odometer reel (vertical 0–9 strip driven by frame) and the flip-card (top-half fold) effect, plus when each suits launch vs sale vs stream.
@@ -0,0 +1,205 @@
# Countdown Cookbook
Complete, runnable recipes. Every value is derived from an authoritative clock (frame or timestamp) so nothing drifts.
## 1. Configurable Remotion countdown (mm:ss + dd:hh:mm:ss)
A single composition that handles any duration and either format. Drop into `src/Countdown.tsx`.
```tsx
import React from "react";
import { useCurrentFrame, useVideoConfig, AbsoluteFill } from "remotion";
const pad = (n: number) => String(n).padStart(2, "0");
const formatTime = (totalSeconds: number, mode: "mm:ss" | "dd:hh:mm:ss") => {
const s = Math.max(0, totalSeconds);
if (mode === "mm:ss") {
return `${pad(Math.floor(s / 60))}:${pad(s % 60)}`;
}
const d = Math.floor(s / 86400);
const h = Math.floor((s % 86400) / 3600);
const m = Math.floor((s % 3600) / 60);
const sec = s % 60;
// drop leading day field once it is zero, for a cleaner read
return d > 0
? `${pad(d)}d ${pad(h)}:${pad(m)}:${pad(sec)}`
: `${pad(h)}:${pad(m)}:${pad(sec)}`;
};
export type CountdownProps = {
durationInSeconds: number;
format?: "mm:ss" | "dd:hh:mm:ss";
label?: string;
};
export const Countdown: React.FC<CountdownProps> = ({
durationInSeconds,
format = "mm:ss",
label = "",
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
// ceil so the last whole second ("1") is shown for its full duration,
// and the display reaches "0" exactly on the final frame.
const remaining = Math.max(0, Math.ceil(durationInSeconds - frame / fps));
const ended = remaining === 0;
return (
<AbsoluteFill
style={{
justifyContent: "center",
alignItems: "center",
background: "#0b0d17",
color: "#fff",
fontFamily: "Inter, system-ui, sans-serif",
}}
>
{label && (
<div style={{ fontSize: 36, opacity: 0.7, marginBottom: 16, letterSpacing: 4 }}>
{label.toUpperCase()}
</div>
)}
<div
style={{
fontSize: 180,
fontWeight: 800,
fontVariantNumeric: "tabular-nums", // equal-width digits → no jitter
lineHeight: 1,
color: ended ? "#ff4d4d" : "#fff",
}}
>
{ended ? formatTime(0, format) : formatTime(remaining, format)}
</div>
</AbsoluteFill>
);
};
```
Register it so `durationInFrames` matches the countdown exactly — the video ends when the timer does:
```tsx
import { Composition } from "remotion";
import { Countdown } from "./Countdown";
const FPS = 30;
const DURATION_SECONDS = 300; // 5-minute "starting soon" timer
export const RemotionRoot = () => (
<Composition
id="Countdown"
component={Countdown}
durationInFrames={DURATION_SECONDS * FPS}
fps={FPS}
width={1920}
height={1080}
defaultProps={{ durationInSeconds: DURATION_SECONDS, format: "mm:ss", label: "Starting soon" }}
/>
);
```
Render any duration/format without touching code — duration is a prop:
```bash
npx remotion render Countdown out/sale.mp4 \
--props='{"durationInSeconds":86400,"format":"dd:hh:mm:ss","label":"Sale ends in"}'
```
To hold a final state (e.g. "WE'RE LIVE") instead of ending on `00:00`, extend `durationInFrames` past the countdown and branch on `ended`.
## 2. Count down to a fixed date (live web component)
For a real-time page that targets a calendar moment. Drift-free because remaining time is `target − Date.now()` recomputed each frame, never a decrement.
```js
// targetISO must include an offset, e.g. "2026-07-01T09:00:00-07:00",
// so the deadline is unambiguous regardless of the viewer's timezone.
function startCountdown(targetISO, el) {
const target = new Date(targetISO).getTime();
const pad = (n) => String(n).padStart(2, "0");
let lastShown = -1;
function tick() {
const remainingMs = Math.max(0, target - Date.now());
const s = Math.floor(remainingMs / 1000);
if (s !== lastShown) {
const d = Math.floor(s / 86400);
const h = Math.floor((s % 86400) / 3600);
const m = Math.floor((s % 3600) / 60);
el.textContent = `${pad(d)}:${pad(h)}:${pad(m)}:${pad(s % 60)}`;
lastShown = s;
}
if (remainingMs > 0) requestAnimationFrame(tick);
else el.textContent = "00:00:00:00"; // or swap to an "It's live" state
}
requestAnimationFrame(tick);
}
```
Timezone notes:
- Bake the offset into the target string (`-07:00`, `Z`). A bare `"2026-07-01T09:00:00"` is parsed as the viewer's *local* time and every viewer sees a different deadline.
- To show "ends 9am in *your* timezone everywhere," instead pick the wall-clock time per locale and let each viewer's `Date` resolve it — but that is a different deadline per region. Decide which you want before building.
## 3. "Starting soon" stream screen
Livestream lead-in screens hold 5–10 minutes: a clean brand block, social handles, and a calm looping background, with the timer as the focal point. Keep it low-clutter — chat and music carry the wait; the screen just signals "we're about to start."
```tsx
import { AbsoluteFill, useCurrentFrame, useVideoConfig, interpolate } from "remotion";
export const StartingSoon: React.FC<{ durationInSeconds: number; handle: string; brand: string }> = ({
durationInSeconds,
handle,
brand,
}) => {
const frame = useCurrentFrame();
const { fps, durationInFrames } = useVideoConfig();
const remaining = Math.max(0, Math.ceil(durationInSeconds - frame / fps));
const pad = (n: number) => String(n).padStart(2, "0");
// seamless looping gradient: angle cycles over loopFrames with no seam
const loopFrames = fps * 8;
const angle = interpolate(frame % loopFrames, [0, loopFrames], [0, 360]);
return (
<AbsoluteFill
style={{
background: `linear-gradient(${angle}deg, #141a3a, #0b0d17 60%)`,
color: "#fff",
fontFamily: "Inter, system-ui, sans-serif",
justifyContent: "center",
alignItems: "center",
}}
>
<div style={{ fontSize: 64, fontWeight: 800, marginBottom: 8 }}>{brand}</div>
<div style={{ fontSize: 28, opacity: 0.6, letterSpacing: 6, marginBottom: 40 }}>
STARTING SOON
</div>
<div style={{ fontSize: 200, fontWeight: 800, fontVariantNumeric: "tabular-nums", lineHeight: 1 }}>
{pad(Math.floor(remaining / 60))}:{pad(remaining % 60)}
</div>
<div style={{ position: "absolute", bottom: 60, fontSize: 30, opacity: 0.7 }}>{handle}</div>
</AbsoluteFill>
);
};
```
Export as MP4 and add it as a Media/Video source in OBS, or use a looping playout for a browser source. Common durations: 300s (5 min) or 600s (10 min) at 1920×1080.
## 4. Seamless looping background
Any motion whose period divides the timeline evenly wraps without a seam. Read animation phase as `frame % loopFrames` so the value at the wrap equals the value at frame 0.
```tsx
const loopFrames = fps * 6; // one full cycle every 6 seconds
const phase = (frame % loopFrames) / loopFrames; // 0 → 1, repeats
const driftY = Math.sin(phase * Math.PI * 2) * 40; // returns to start each cycle
```
Use sine/cosine (inherently periodic) or `interpolate(frame % loopFrames, [0, loopFrames], [a, a])` with matching start/end so there is no jump. Keep contrast low and motion slow — the number is the subject.
---
## Built by the team behind iart.ai
This skill is part of an open motion-graphics collection from iart.ai — the AI motion agent that turns data, scripts, and designs into editable motion graphics (Remotion → MP4). If you'd rather not hand-build this, iart.ai can render countdown videos from a template with a set time and brand — change the text/data and re-export. → [iart.ai](https://iart.ai/?utm_source=github&utm_medium=reference&utm_campaign=tiktok-video-skills&utm_content=ref_footer&utm_term=countdown-video)
@@ -0,0 +1,146 @@
# Digit Flip & Roll Transitions
Two ways to animate a digit changing. Both are driven by the frame (deterministic) so they render identically every time — no CSS transition clock that the renderer can disagree with.
Pick by tone:
| Effect | Feel | Best for |
|---|---|---|
| Odometer reel | smooth, continuous glide | launch countdowns, premium/minimal timers |
| Flip card | mechanical "snap", split-flap board | sale urgency, retro/airport-board style |
## Shared idea
A single displayed digit is a stack of glyphs `0..9` laid out vertically. Showing digit `d` means translating the stack so glyph `d` sits in the window: `translateY(-d × digitHeight)`. Animate the *offset*, not the text, and you get a roll. The trick for a countdown is that the offset is continuous: between whole seconds the digit eases from its old value toward its new one.
## Odometer reel (Remotion, frame-driven)
```tsx
import React from "react";
import { useCurrentFrame, useVideoConfig, interpolate, Easing } from "remotion";
const DIGIT_H = 160; // px per glyph
const ROLL_FRAMES = 12; // how long a single digit roll takes
// Animated single digit: rolls from `prev` to `value` over the last ROLL_FRAMES
// of the current second.
const Reel: React.FC<{ value: number; prev: number; secondProgress: number }> = ({
value,
prev,
secondProgress,
}) => {
// secondProgress: 0→1 across the current whole second.
// Start the roll near the end of the second so the number "settles" on change.
const t = interpolate(secondProgress, [0.7, 1], [0, 1], {
extrapolateLeft: "clamp",
extrapolateRight: "clamp",
easing: Easing.bezier(0.22, 1, 0.36, 1),
});
// continuous position between prev and value
const shown = prev + (value - prev) * t;
const offset = -shown * DIGIT_H;
return (
<div style={{ height: DIGIT_H, width: 110, overflow: "hidden", position: "relative" }}>
<div style={{ transform: `translateY(${offset}px)` }}>
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((n) => (
<div
key={n}
style={{
height: DIGIT_H,
lineHeight: `${DIGIT_H}px`,
textAlign: "center",
fontSize: 140,
fontWeight: 800,
fontVariantNumeric: "tabular-nums",
}}
>
{n}
</div>
))}
</div>
</div>
);
};
// Renders an mm:ss reel where each digit rolls.
export const ReelClock: React.FC<{ durationInSeconds: number }> = ({ durationInSeconds }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const elapsed = frame / fps;
const remaining = Math.max(0, Math.ceil(durationInSeconds - elapsed));
const prevRemaining = Math.max(0, remaining + 1); // value one second ago
const secondProgress = elapsed % 1; // 0→1 within the current second
const digits = (s: number) =>
[Math.floor(s / 600) % 10, Math.floor(s / 60) % 10, Math.floor(s / 10) % 10, s % 10];
const cur = digits(remaining);
const prev = digits(prevRemaining);
return (
<div style={{ display: "flex", gap: 8, color: "#fff", background: "#0b0d17", padding: 40 }}>
{cur.map((d, i) => (
<React.Fragment key={i}>
{i === 2 && <div style={{ fontSize: 140, fontWeight: 800 }}>:</div>}
<Reel value={d} prev={prev[i]} secondProgress={secondProgress} />
</React.Fragment>
))}
</div>
);
};
```
Notes:
- Each digit only rolls when it actually changes; a digit whose `prev === value` sits still because `shown` stays constant.
- A `9 → 0` rollover rolls *backward* through the strip (the cheap-looking part). To make tens/units roll the natural way on a carry, render an extra `0` glyph below the `9` and clamp — covered as an exercise; for most timers the backward roll at the tens boundary is unnoticeable at speed.
- `ROLL_FRAMES` is unused above because the roll is tied to `secondProgress`; expose it instead if a fixed-length roll is preferred.
## Flip card (split-flap)
The top half of the old digit folds down over a static bottom half, revealing the new digit. Pure CSS keyframe version — fine for a live web page; for Remotion, drive the `rotateX` off `secondProgress` the same way as the reel so it stays deterministic.
```css
.flip { position: relative; width: 110px; height: 160px; perspective: 600px; }
.flip .card {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
font-size: 140px; font-weight: 800; font-variant-numeric: tabular-nums;
backface-visibility: hidden;
}
.flip .top { clip-path: inset(0 0 50% 0); transform-origin: bottom; }
.flip .bottom { clip-path: inset(50% 0 0 0); }
/* on change, animate the leaf folding down */
.flip .leaf {
position: absolute; inset: 0; transform-origin: bottom;
animation: fold .45s cubic-bezier(.36,0,.66,-0.2) forwards;
}
@keyframes fold {
0% { transform: rotateX(0deg); }
100% { transform: rotateX(-90deg); }
}
```
```js
// swap the digit and replay the fold whenever the value changes
function setFlip(el, newDigit) {
if (el.dataset.v === String(newDigit)) return; // no change → no flip
el.dataset.v = String(newDigit);
el.querySelector(".top").textContent = newDigit;
el.querySelector(".bottom").textContent = newDigit;
const leaf = el.querySelector(".leaf");
leaf.textContent = newDigit;
leaf.style.animation = "none";
void leaf.offsetWidth; // reflow → restart the animation
leaf.style.animation = "";
}
```
Drive `setFlip` from the same `requestAnimationFrame` + `performance.now()` loop in the cookbook (only call it when the displayed second changes), so the flips fire on real time and never drift.
## Choosing
- **Launch / premium:** odometer reel, slow ease, large tabular digits, muted palette.
- **Flash sale:** flip card for the mechanical urgency, or reel with a faster roll and a hot accent color on `mm:ss`.
- **Stream "starting soon":** either works, but keep it calm — a single reel on `mm:ss` reads better than a busy split-flap for a 5–10 minute hold.
Whitespace-only changes.
-177
View File
@@ -1,177 +0,0 @@
---
name: glassmorphism
description: This skill should be used when the user asks to "add a glassmorphism effect", "frosted glass UI", "Apple liquid glass style", "frosted blur card", "translucent glass panel animation", "make a frosted nav bar", "build a glass modal/dialog", "animate a glass card on hover", or "add a refracting liquid-glass hero". Covers frosted translucent panels with backdrop-filter blur, edge/specular highlights, SVG liquid-glass refraction, motion on hover/scroll/enter, and accessible reduced-transparency fallbacks.
version: 0.1.0
---
# Glassmorphism (Frosted & Liquid Glass)
Translucent, frosted UI: panels you can see through, blurred so the backdrop reads as soft color, rimmed by a bright edge of light, floating on layered shadow. The 2026 "liquid glass" evolution adds refraction — the background visibly bends through the panel — plus moving specular highlights. The goal is depth and material, not just opacity.
## When to use
- Frosted cards, nav bars, sidebars, modals/dialogs, and toolbars over busy/photo backgrounds
- Login/hero panels and overlays that should feel layered above the page
- Apple-style "liquid glass" heroes: refracting, slowly churning surfaces with a specular sweep
- Hover/scroll/enter motion on glass — frost deepening, highlight brightening, the panel lifting
- Any place where content needs to read as floating glass while staying legible
## The four ingredients of believable glass
Glass is never one property. Every panel needs all four, or it reads as a plain translucent box:
1. **Frost** — `backdrop-filter: blur()` plus `saturate()` to keep backdrop color vivid through the blur.
2. **Translucency** — a `background` with alpha (~0.08–0.18), never fully opaque, never fully clear.
3. **Edge of glass** — a hairline border *brighter* than the fill, ideally a lit top-left → dim bottom-right highlight, so the rim catches light.
4. **Depth** — layered `box-shadow`: an ambient drop shadow to float it, plus an `inset` top highlight and bottom shade to round the surface.
```css
.glass {
background: rgba(255, 255, 255, 0.12);
backdrop-filter: blur(16px) saturate(160%);
-webkit-backdrop-filter: blur(16px) saturate(160%); /* Safari needs the prefix */
border-radius: 20px;
border: 1px solid rgba(255, 255, 255, 0.25);
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.25), /* float */
inset 0 1px 0 rgba(255, 255, 255, 0.35), /* top highlight */
inset 0 -1px 0 rgba(0, 0, 0, 0.12); /* bottom shade */
}
```
Frost tiers: light UI chrome `blur(8–12px)` / alpha `0.08–0.14`; heavy modal/login `blur(24–40px)` / alpha `0.10–0.18`. Dark glass: fill `rgba(0,0,0,0.3)`, softer top highlight.
**`backdrop-filter` only blurs content that sits behind the element.** Over a flat background color it does nothing visible — glass needs a busy backdrop (image, gradient, video) to frost.
## Specular edge highlight and anti-banding grain
A flat border is dead. Draw a masked 1px ring with a lit corner via `::before`, and dither away gradient **banding** (stepped contour lines under heavy blur) with a faint `feTurbulence` noise overlay via `::after` at `opacity ≤ 0.06`. Full masked-border and inline-noise recipes are in `references/glass-recipes.md`.
## Motion: animate the glass, not the geometry
Animate the *qualities* of the glass — frost deepening, highlight brightening, the panel lifting — so it reads as the surface "leaning into the light."
```css
.glass {
transition: backdrop-filter .4s ease, background .4s ease,
box-shadow .4s ease, transform .4s cubic-bezier(.16,1,.3,1);
}
.glass:hover {
backdrop-filter: blur(24px) saturate(180%);
background: rgba(255,255,255,.18);
transform: translateY(-4px);
box-shadow: 0 16px 48px rgba(0,0,0,.3), inset 0 1px 0 rgba(255,255,255,.5);
}
```
- **Entrance** (frost resolving from clear): pair a `[data-enter]` transition with `@starting-style { backdrop-filter: blur(0); opacity: 0; transform: translateY(16px) }`.
- **Specular sweep**: a skewed white gradient animated across the surface on hover or as a slow ambient loop.
- **Caveat**: animating the blur *radius* is the most expensive thing here — the backdrop is re-blurred every frame. If hover janks, animate `transform`/`box-shadow`/`background` (cheap) and keep the blur delta small or snap it.
## Liquid glass — SVG refraction (the 2026 look)
Bend the background through the panel like a thick lens: drive `feDisplacementMap` from animated `feTurbulence`, applied via `filter` (it distorts the element's own pixels) layered over a `backdrop-filter` frost.
```html
<svg width="0" height="0" style="position:absolute"><filter id="liquid-glass">
<feTurbulence type="fractalNoise" baseFrequency="0.008 0.012" numOctaves="2" seed="3" result="n">
<animate attributeName="baseFrequency" dur="18s"
values="0.008 0.012;0.012 0.008;0.008 0.012" repeatCount="indefinite"/>
</feTurbulence>
<feDisplacementMap in="SourceGraphic" in2="n" scale="22" xChannelSelector="R" yChannelSelector="G"/>
</filter></svg>
```
`scale` = refraction strength (8–14 subtle, 20–30 pronounced, >40 molten). Lower `baseFrequency` = larger, slower waves (more liquid). Keep the `animate` `dur` long (12–20s) so it breathes. These filters are heavy — use on **one** hero element, not a grid.
## Performance — backdrop-filter is expensive
- Each glass element re-samples and blurs everything behind it. **Limit the count**; a dozen on screen tanks scroll FPS.
- Promote heavy glass to its own layer (`transform: translateZ(0)` or `will-change: transform`), and remove `will-change` after the animation.
- Don't stack `backdrop-filter` elements over each other — nested blur re-blurs the blur (quadratic cost).
- Big radii (>40px) over large areas are the worst case; cap radius and panel size.
## Accessibility — non-negotiable
Glass is decoration; content must stay legible and the effect must be defeatable.
```css
@media (prefers-reduced-transparency: reduce) {
.glass { background: #1a1a2e; backdrop-filter: none; -webkit-backdrop-filter: none; }
.glass::after { display: none; } /* drop grain */
}
@media (prefers-reduced-motion: reduce) {
.glass { transition: none; }
.liquid { filter: none; } /* stop the refraction churn */
}
@supports not (backdrop-filter: blur(1px)) {
.glass { background: rgba(30,30,50,.85); } /* opaque-enough fallback */
}
```
**Contrast over busy backgrounds**: translucent panels over photos can drop text below WCAG. Add a semi-opaque scrim or darkening gradient *under* the text, optionally `text-shadow: 0 1px 2px rgba(0,0,0,.4)`, and verify ≥ 4.5:1 body / ≥ 3:1 large against the *brightest* region of the backdrop.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained glass demo (card, nav, modal, liquid-glass hero) the deliverable is **one HTML file that opens directly in a browser** — markup, CSS, and (if liquid) one inline SVG filter, no build step. A single file is the right tier for a glass surface; don't reach for a bundler. The panel **must overlap a real backdrop** (drop in a photo or gradient) or there is nothing to frost and the demo lies.
**Output contract:**
- One `.html` file: a busy backdrop, your glass markup, the CSS (frost + edge highlight + grain + shadows), and any inline SVG `feDisplacementMap` filter.
- A way to land on the **resolved state** *and* a **frozen frame** of any loop — glass verifies by both state (rest/hover/enter) and time (the sweep/refraction).
- Include the freeze harness below so any moment can be pinned for inspection.
**Seek harness — pin a deterministic state + frame.** `?state=hover` forces the hover look; `?t=N` freezes CSS animations and the SVG refraction at `N` seconds, so a screenshot lands on a still, deterministic frame:
```html
<script>
const p = new URLSearchParams(location.search);
const state = p.get("state");
if (state) document.documentElement.dataset.state = state; // CSS keys off :root[data-state="hover"]
const t = p.get("t");
if (t !== null) {
document.getAnimations().forEach(a => { a.currentTime = parseFloat(t)*1000; a.pause(); }); // freeze CSS sweep
const svg = document.querySelector("svg");
svg?.pauseAnimations?.(); svg?.setCurrentTime?.(parseFloat(t)); // freeze refraction
}
window.__ready = true;
</script>
```
**Verify loop — render → set state/freeze → screenshot → check:** open each meaningful state (`?state=rest`, `?state=hover`) and a frozen loop frame (`?t=2`), screenshot, and confirm the glass **reads as glass** — blur and edge highlight visibly present, no color banding, text contrast holds over the backdrop — plus check **artifacts** (flat box because the backdrop is plain color, missing `-webkit-` prefix in Safari, refraction too strong/molten, jank from animating blur). Then load `prefers-reduced-transparency` and confirm the **solid fallback renders** legibly. Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/glass.html?state=hover" hover.png
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/glass.html?t=2" loop.png
```
To check the fallback headlessly, emulate the media feature (e.g. Playwright `--color-scheme`-style flags, or a `?reduced=1` query that toggles a class mirroring the media query) and screenshot that the panel is solid and readable.
**Before you finish:**
1. Opens standalone — no console errors; the glass overlaps a real busy backdrop, not a flat color.
2. Reads as glass — blur + bright edge highlight both visible, layered shadow floats it, no banding (grain present).
3. Text contrast holds over the brightest part of the backdrop (≥ 4.5:1 body).
4. `?state=` / `?t=N` freeze lands a deterministic, settled frame.
5. `prefers-reduced-transparency` → solid opaque panel; `prefers-reduced-motion` → refraction/sweep stopped; `@supports` fallback for no `backdrop-filter`.
6. Performance sane — glass count limited, blur not animated on a janky path, liquid refraction on one element only.
## Quick reference
| Need | Approach |
|------|----------|
| Base frost | `backdrop-filter: blur(16px) saturate(160%)` + alpha bg |
| Edge of glass | brighter `border` + masked `::before` lit-corner ring |
| Float / depth | `box-shadow` drop + `inset` top highlight & bottom shade |
| Kill banding | `feTurbulence` noise `::after`, `opacity ≤ .06` |
| Hover motion | transition `transform`/`box-shadow`/`background`, small blur delta |
| Entrance | `@starting-style { backdrop-filter: blur(0); opacity:0 }` |
| Liquid refraction | `feDisplacementMap` ← animated `feTurbulence`, via `filter` |
| Specular sweep | skewed white gradient animated across surface |
| Safari | always pair `-webkit-backdrop-filter` |
| Reduced transparency | solid opaque panel, drop grain |
| No backdrop-filter | `@supports not (...)` opaque-enough fallback |
## Reference files
- `references/glass-recipes.md` — full copy-paste recipes: base glass card with tiers, the masked specular edge ring, anti-banding grain, hover/enter/scroll motion, the specular sweep, the SVG `feDisplacementMap`/`feTurbulence` liquid-glass filter with tuning knobs, performance rules, the reduced-transparency/reduced-motion/`@supports` fallbacks, contrast defenses, and the standalone freeze harness.
@@ -1,242 +0,0 @@
# Glassmorphism Recipes
Copy-paste recipes for frosted translucent panels, the "edge of glass" highlight, animated liquid-glass refraction, and the reduced-transparency fallback. All standalone CSS + optional inline SVG — no build step.
## 1. The base glass card
The four ingredients of believable glass: **blur** (frost), **translucency** (you see through it), **edge highlight** (light catches the rim), **layered shadow** (it floats). Plus a touch of `saturate()` so the backdrop reads vivid through the frost.
```css
.glass {
/* translucency — never fully opaque, never fully clear */
background: rgba(255, 255, 255, 0.12);
/* frost: blur the backdrop, lift saturation so color survives the blur */
backdrop-filter: blur(16px) saturate(160%);
-webkit-backdrop-filter: blur(16px) saturate(160%); /* Safari still needs the prefix */
border-radius: 20px;
/* edge of glass: a hairline border slightly brighter than the fill */
border: 1px solid rgba(255, 255, 255, 0.25);
/* depth: ambient drop + a top inner highlight + a bottom inner shade */
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.25),
inset 0 1px 0 rgba(255, 255, 255, 0.35),
inset 0 -1px 0 rgba(0, 0, 0, 0.12);
}
```
Tuning by tier:
- **Light frost** (UI chrome over content): `blur(8–12px)`, alpha `0.08–0.14`.
- **Heavy frost** (modal scrim, login card): `blur(24–40px)`, alpha `0.10–0.18`.
- Dark glass: swap the fill to `rgba(0,0,0,0.3)` and the top inner highlight to a softer white.
`backdrop-filter` only has anything to blur if there is content **behind** the element — it must overlap a busy background (image, gradient, video). On a flat color it looks like a plain translucent box.
## 2. The specular edge highlight (the rim of light)
A single border is flat. Real glass catches a bright sweep along the top-left edge and falls off. Layer a soft conic/linear highlight via a pseudo-element with a masked border.
```css
.glass {
position: relative;
isolation: isolate; /* keep the highlight blend local */
}
.glass::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
padding: 1px; /* border thickness */
background: linear-gradient(
135deg,
rgba(255, 255, 255, 0.7),
rgba(255, 255, 255, 0) 40%,
rgba(255, 255, 255, 0) 60%,
rgba(255, 255, 255, 0.25)
);
/* mask trick: show only the 1px ring, punch out the interior */
-webkit-mask:
linear-gradient(#000 0 0) content-box,
linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
}
```
This gives the panel a lit top-left corner and a dim bottom-right, the cue the brain reads as "curved glass under a light."
## 3. Kill banding with grain
Heavy `blur()` over a smooth gradient produces visible color **banding** (stepped contour lines). A faint noise overlay dithers it away.
```css
.glass::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
pointer-events: none;
opacity: 0.04; /* barely there */
mix-blend-mode: overlay;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
}
```
`feTurbulence` generates the noise tile inline — no asset file. Keep opacity ≤ 0.06 or it reads as texture, not dither.
## 4. Motion: animate the glass on hover / enter / scroll
Animate the *qualities* of the glass, not its geometry. Frost deepening and the highlight brightening on hover reads as the panel "leaning into the light."
```css
.glass {
transition:
backdrop-filter 0.4s ease,
background 0.4s ease,
box-shadow 0.4s ease,
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
.glass:hover {
backdrop-filter: blur(24px) saturate(180%);
background: rgba(255, 255, 255, 0.18);
transform: translateY(-4px);
box-shadow:
0 16px 48px rgba(0, 0, 0, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.5);
}
```
Caveat: animating `backdrop-filter` itself is the most expensive thing here — the backdrop is re-sampled and re-blurred every frame. If hover feels janky, animate only `transform` + `box-shadow` + `background` (cheaper) and snap the blur, or keep the blur change small.
**Entrance** (frost resolving in) reads beautifully with `@starting-style`:
```css
.glass[data-enter] {
transition: opacity 0.5s ease, backdrop-filter 0.6s ease, transform 0.5s ease;
}
@starting-style {
.glass[data-enter] {
opacity: 0;
backdrop-filter: blur(0px) saturate(100%);
transform: translateY(16px) scale(0.98);
}
}
```
**Specular sweep** — a moving glint across the surface on hover or as an ambient loop:
```css
.glass .sweep {
position: absolute; inset: 0; border-radius: inherit; overflow: hidden; pointer-events: none;
}
.glass .sweep::before {
content: ""; position: absolute; top: 0; left: -60%; width: 50%; height: 100%;
background: linear-gradient(105deg, transparent, rgba(255,255,255,0.35), transparent);
transform: skewX(-15deg);
animation: sweep 4s ease-in-out infinite;
}
@keyframes sweep { 0%,100% { left: -60%; } 50% { left: 110%; } }
```
## 5. Liquid glass — SVG refraction (the 2026 look)
Apple-style "liquid glass" bends the background as if seen through a thick, wobbling lens. Drive a `feDisplacementMap` from animated `feTurbulence` and apply it via `filter` (note: `filter`, not `backdrop-filter` — it distorts the element's own rendered content; layer it over a `backdrop-filter` frost for the full effect).
```html
<svg width="0" height="0" style="position:absolute">
<filter id="liquid-glass">
<feTurbulence type="fractalNoise" baseFrequency="0.008 0.012"
numOctaves="2" seed="3" result="noise">
<!-- animate the field so the refraction slowly churns -->
<animate attributeName="baseFrequency"
dur="18s" values="0.008 0.012; 0.012 0.008; 0.008 0.012"
repeatCount="indefinite"/>
</feTurbulence>
<feDisplacementMap in="SourceGraphic" in2="noise"
scale="22" xChannelSelector="R" yChannelSelector="G"/>
</filter>
</svg>
```
```css
.liquid {
backdrop-filter: blur(6px) saturate(150%); /* light frost under the refraction */
filter: url(#liquid-glass); /* the lens distortion */
}
```
Knobs:
- `scale` on `feDisplacementMap` = refraction strength. 8–14 = subtle ripple; 20–30 = pronounced lens; >40 = molten.
- Lower `baseFrequency` = larger, slower waves (more "liquid"); higher = tight, busy ripples.
- Animate `baseFrequency` (above) or `scale` for a living surface. Keep `dur` long (12–20s) so it breathes rather than shimmers.
Cost warning: SVG displacement filters are heavy and force off-GPU paths in some browsers. Use on **one** hero element, not a grid of cards. Test on a mid-range laptop; drop to plain `backdrop-filter` if frames stutter.
## 6. Performance — backdrop-filter is expensive
- Each `backdrop-filter` element re-samples and blurs everything behind it. **Limit the count** — a dozen glass cards on screen will tank scroll FPS.
- Promote heavy glass to its own compositor layer: `transform: translateZ(0)` or `will-change: transform` (remove `will-change` after the animation; leaving it on wastes memory).
- Avoid stacking `backdrop-filter` elements over each other (nested blur re-blurs the blur — quadratic cost).
- Prefer animating `transform`/`opacity`/`box-shadow` over animating the blur radius. If you must animate blur, keep the radius delta small.
- Big blur radii (>40px) over large areas are the single worst case; cap the radius and the panel size.
## 7. Accessibility — non-negotiable
Glass is decorative; the content on it must stay legible and the effect must be defeatable.
**Honor reduced transparency and reduced motion** — fall back to a solid, opaque panel:
```css
@media (prefers-reduced-transparency: reduce) {
.glass {
background: #1a1a2e; /* solid, accessible panel */
backdrop-filter: none;
-webkit-backdrop-filter: none;
border-color: rgba(255, 255, 255, 0.15);
}
.glass::after { display: none; } /* drop grain/noise */
}
@media (prefers-reduced-motion: reduce) {
.glass, .glass .sweep::before { transition: none; animation: none; }
.liquid { filter: none; } /* stop the churning refraction */
}
```
**Contrast over busy backgrounds.** Translucent panels over photos can drop text below WCAG contrast. Defenses:
- Put a contrast floor *under* the text: a semi-opaque scrim or a darkening gradient inside the panel.
- Add `text-shadow: 0 1px 2px rgba(0,0,0,0.4)` to body text on glass.
- Target ≥ 4.5:1 for body text, ≥ 3:1 for large text — and verify against the *brightest* region of the backdrop, not the average.
**Feature fallback** for browsers without `backdrop-filter`:
```css
@supports not (backdrop-filter: blur(1px)) {
.glass { background: rgba(30, 30, 50, 0.85); } /* opaque-enough fallback */
}
```
## 8. Standalone freeze harness
Glass demos verify by *state* (rest / hover / enter) and *time* (the sweep/refraction loop). Wire both so a screenshot lands deterministically:
```html
<script>
const p = new URLSearchParams(location.search);
const state = p.get("state"); // ?state=hover → force the hover look
if (state) document.documentElement.dataset.state = state;
const t = p.get("t"); // ?t=2 → freeze CSS animations at 2s
if (t !== null) {
document.getAnimations().forEach(a => { a.currentTime = parseFloat(t) * 1000; a.pause(); });
// SVG SMIL (the <animate>): pin the refraction frame too
document.querySelector("svg")?.pauseAnimations?.();
document.querySelector("svg")?.setCurrentTime?.(parseFloat(t));
}
window.__ready = true;
</script>
```
CSS drives the forced state: `:root[data-state="hover"] .glass { /* hover values */ }`.
---
Frosted glass that reads as glass — blur, edge light, and refraction, with a clean fallback. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=glassmorphism)** — the AI motion agent for editable, on-brand motion graphics.
View File
Whitespace-only changes.
-225
View File
@@ -1,225 +0,0 @@
---
name: gsap-web
description: This skill should be used when the user asks to "build a scroll animation", "add ScrollTrigger", "pin a section while scrolling", "scrub an animation to scroll", "create a hero timeline", "do a horizontal scroll section", "split text and animate words", "animate a layout change with GSAP Flip", "sync ScrollTrigger with Lenis", "Lenis smooth scroll jittery", "ScrollTrigger markers drift", "ScrollTrigger pins break with Lenis/Locomotive", or "set up smooth scroll with GSAP pinning". Covers GSAP timelines, ScrollTrigger, SplitText, Flip, and Lenis/Locomotive smooth-scroll sync for code-driven web motion.
version: 0.1.0
---
# GSAP for the Web
GSAP (GreenSock Animation Platform) is the workhorse for code-driven web motion: sequenced timelines, scroll-driven storytelling, text reveals, and layout transitions. As of GSAP 3.12+, every plugin (ScrollTrigger, SplitText, Flip, MotionPath, MorphSVG, Draggable, Observer) is 100% free, including for commercial use.
## When to use
- Scroll-driven storytelling: pinned sections, parallax, progress scrubbing, horizontal scroll
- Sequenced hero animations and complex multi-element timelines with precise overlap control
- Text reveals split into chars/words/lines (SplitText)
- Layout transitions where an element changes position/size/parent (Flip)
- Any motion needing fine timing control, easing precision, or imperative orchestration
## Install and register
```js
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { SplitText } from "gsap/SplitText";
import { Flip } from "gsap/Flip";
gsap.registerPlugin(ScrollTrigger, SplitText, Flip);
```
Plugins MUST be registered before use or they silently no-op. With a bundler, register once at app entry.
## Core techniques
### Timelines first
Prefer one timeline over many independent tweens — it gives a single playhead, relative positioning, and easy reversal.
```js
const tl = gsap.timeline({ defaults: { ease: "power3.out", duration: 0.6 } });
tl.from(".title", { yPercent: 100, opacity: 0 })
.from(".sub", { y: 20, opacity: 0 }, "-=0.3") // start 0.3s before prev ends
.from(".cta", { scale: 0.9, opacity: 0 }, "<"); // align to prev tween START
```
Position parameter cheat sheet:
- `"+=0.5"` / `"-=0.3"` — relative to the end of the timeline (gap / overlap)
- `"<"` — start of the previous tween; `">"` — end of the previous tween
- `"<0.2"` — 0.2s after the previous tween's start
- `"myLabel"` — at a named label added via `tl.addLabel("myLabel")`
Use `.from()` for entrances (animates FROM the given values TO current CSS), `.to()` for exits, `.fromTo()` when both ends must be explicit (most robust against re-runs).
### gsap.to vs set vs quickTo
```js
gsap.set(el, { autoAlpha: 0 }); // instant, no tween (autoAlpha = opacity + visibility)
const xTo = gsap.quickTo(el, "x", { duration: 0.4, ease: "power3" });
window.addEventListener("pointermove", (e) => xTo(e.clientX)); // fast repeated updates
```
`autoAlpha` is preferred over raw `opacity` because it also toggles `visibility:hidden` at 0, removing the element from hit-testing.
### ScrollTrigger basics
```js
gsap.to(".panel", {
xPercent: -100,
ease: "none",
scrollTrigger: {
trigger: ".wrap",
start: "top top", // when trigger top hits viewport top
end: "+=2000", // 2000px of scroll distance
pin: true, // freeze .wrap while the tween plays
scrub: 1, // tie progress to scrollbar (1 = 1s catch-up smoothing)
markers: true, // dev-only visual markers — remove for prod
},
});
```
Key semantics:
- `start`/`end` take `"triggerPos viewportPos"` (e.g. `"top center"`) or `"+=px"`.
- `scrub: true` locks animation progress to scroll exactly; `scrub: <number>` adds smoothing lag.
- `toggleActions: "play pause resume reverse"` controls onEnter/onLeave/onEnterBack/onLeaveBack for non-scrubbed triggers.
- Use `ease: "none"` for scrubbed tweens so motion tracks scroll linearly.
### Smooth scroll (Lenis) + ScrollTrigger
Pairing Lenis (or Locomotive) smooth scrolling with ScrollTrigger desyncs unless both run on one loop. Lenis smooths scroll on its own rAF while ScrollTrigger reads scroll on GSAP's ticker; when they tick independently ScrollTrigger samples a stale position. The fix: drive Lenis from GSAP's ticker and update ScrollTrigger on every Lenis scroll.
```js
import Lenis from "lenis";
const lenis = new Lenis({ duration: 1.2, smoothWheel: true });
lenis.on("scroll", ScrollTrigger.update); // 1. update ScrollTrigger on every Lenis scroll
gsap.ticker.add((t) => lenis.raf(t * 1000)); // 2. one loop: ticker drives Lenis (seconds → ms)
gsap.ticker.lagSmoothing(0); // 3. stop GSAP catch-up jitter on heavy frames
```
Critical: `gsap.ticker` passes time in **seconds**, `lenis.raf()` wants **milliseconds** — multiply by 1000. Do NOT also run a standalone `requestAnimationFrame(raf)` loop for Lenis; that double-drives it.
Common bugs:
- **Jitter/stutter** — a leftover `requestAnimationFrame(raf)` loop competing with the ticker, or missing `lagSmoothing(0)`. Remove the rogue loop; set lag smoothing to 0.
- **Markers drift** from their triggers — `ScrollTrigger.update` is not subscribed to `lenis.on("scroll", …)`.
- **Pins break** — under Lenis do NOT set a `scrollerProxy` (it scrolls the document). Under Locomotive you MUST wire `scrollerProxy` + `pinType` and set `scroller:` on every trigger.
- **Scroll stuck / flipped direction** — missing the `* 1000` unit conversion, or two loops out of order.
Cleanup on SPA unmount: `gsap.ticker.remove(update)` + `lenis.destroy()`, else loops stack per navigation. Gate behind `prefers-reduced-motion` (skip Lenis, run native scroll). Full Lenis + Locomotive wiring, anchor-link routing, `data-lenis-prevent`, React (`useGSAP`/`useEffect`), and a symptom→cause table are in `references/scrolltrigger-lenis.md`.
### SplitText (text reveal)
```js
const split = SplitText.create(".headline", { type: "lines, words", linesClass: "line" });
gsap.from(split.lines, { yPercent: 100, opacity: 0, stagger: 0.08, duration: 0.7, ease: "power4.out" });
```
Gotchas:
- Wrap line-mask reveals: set `overflow: hidden` on the line wrapper so `yPercent: 100` hides cleanly. Add `autoSplit: true` (GSAP 3.13+) to re-split on font load / resize.
- Call `split.revert()` before re-splitting or on unmount to restore original DOM and avoid duplicated nodes.
- Always split AFTER web fonts load (`document.fonts.ready.then(...)`) to prevent wrong line breaks.
### Flip (layout transitions)
Flip records state, lets the DOM change instantly, then animates the visual difference (FLIP technique). Ideal for grid<->list, expanding cards, and reparenting.
```js
const state = Flip.getState(".item"); // 1. capture BEFORE
container.classList.toggle("grid"); // 2. mutate DOM/CSS (instant)
Flip.from(state, { // 3. animate the delta
duration: 0.6, ease: "power2.inOut", stagger: 0.05,
absolute: true, // take items out of flow during move (prevents reflow jitter)
});
```
### Easing quick guide
- `power2/3.out` — entrances (fast then settle)
- `power2.inOut` — moves between two on-screen states
- `back.out(1.7)` — overshoot/pop (number = overshoot amount)
- `elastic.out(1, 0.3)` — bouncy, use sparingly
- `none` — scrubbed scroll tweens
- `steps(n)` — sprite/stepped motion
- Custom cubic-bezier equivalent: `CustomEase.create("x", "M0,0 C0.2,0 0,1 1,1")` (CustomEase is free)
## Performance and cleanup
- Animate `transform` (`x/y/xPercent/scale/rotation`) and `opacity` only — they are GPU-composited and skip layout/paint. Avoid animating `top/left/width/height`.
- Set `will-change: transform` on heavy/pinned elements; remove after.
- Batch many similar scroll reveals with `ScrollTrigger.batch()` instead of one trigger per element.
- After a viewport/content change, call `ScrollTrigger.refresh()`.
SPA / framework cleanup is mandatory — orphaned triggers cause memory leaks and ghost pinning. Use `gsap.context()` (or `useGSAP` from `@gsap/react`):
```js
useEffect(() => {
const ctx = gsap.context(() => {
// all gsap + ScrollTrigger code here
}, rootRef);
return () => ctx.revert(); // kills tweens, triggers, and reverts inline styles
}, []);
```
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained animation (hero, reveal, loop, micro-scene) the deliverable is **one HTML file that opens directly in a browser** — no build step, no framework, no render pipeline. Match the deliverable to the weight of the work: a single file is the right tier for web motion; don't reach for a bundler when one file does the job.
**Output contract:**
- One `.html` file: GSAP + plugins from CDN, your markup, and the animation in one inline `<script>`.
- All motion on **one master timeline** (`const tl = gsap.timeline()`) — a single playhead you can seek.
- Include the seek harness below so any moment can be frozen for inspection.
**Seek harness — freeze an exact moment for screenshots.** The web parallel of a video player's frame-pin: `?t=N` seeks the master timeline to `N` seconds and pauses, so a screenshot lands on a still, deterministic frame.
```html
<script>
// ... build your master timeline as `tl` ...
const t = new URLSearchParams(location.search).get("t");
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // frozen at t seconds
// no ?t → plays normally
window.__ready = true; // ready signal for headless wait
console.log("duration", tl.duration());
</script>
```
**Verify loop — render → freeze → screenshot → check:**
1. Open the file at three moments across the timeline — start, mid, end:
`…/anim.html?t=0`, `?t=<dur/2>`, `?t=<dur>`. Read `tl.duration()` from the console for the end time.
2. Screenshot each frozen frame.
3. Check both **fidelity** (does it match the brief?) and **artifacts** (clipped text, elements off-canvas, FOUC before fonts load, jank at seams). Output should look intentional and finished.
Any headless screenshot tool works — your agent's browser tool, or Playwright:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/anim.html?t=1.2" frame-mid.png
```
**Before you finish:**
1. Opens standalone in a browser — no console errors, no missing CDN.
2. All animation on one master timeline; `?t=N` freezes correctly.
3. Screenshotted at start / mid / end — matches the brief, no artifacts.
4. `prefers-reduced-motion` honored (timeline simplified or skipped).
5. Easing is intentional — no accidental `linear` on spatial motion.
A complete runnable template with the harness wired in is in `examples/standalone-template.html`.
## Quick reference
| Goal | API |
|------|-----|
| Sequence with overlap | `tl.from(...).from(..., "-=0.3")` |
| Pin while scrolling | `scrollTrigger:{ pin:true, end:"+=N" }` |
| Scrub to scroll | `scrollTrigger:{ scrub:1, ease:"none" }` |
| Reveal lines of text | `SplitText.create(el,{type:"lines"})` |
| Animate layout change | `Flip.getState` → mutate → `Flip.from` |
| Fast pointer follow | `gsap.quickTo(el,"x",{...})` |
| Kill everything | `ScrollTrigger.getAll().forEach(t=>t.kill())` |
## Reference files
- `references/scrolltrigger-cookbook.md` — pin, scrub, horizontal scroll, snap, `ScrollTrigger.batch()` reveals, parallax, nested triggers, and SPA cleanup patterns with full code.
- `references/scrolltrigger-lenis.md` — full ScrollTrigger + Lenis/Locomotive smooth-scroll sync: canonical wiring, `scrollerProxy`, anchor links, reduced-motion, React (`useGSAP`/`useEffect`), debugging checklist, and symptom→cause table.
- `examples/hero-timeline.js` — a complete, runnable hero entrance timeline with SplitText, staggered reveals, and reduced-motion handling.
- `examples/standalone-template.html` — the deliverable template: self-contained (CDN GSAP), one master timeline, the `?t=N` seek harness for screenshot verification, and reduced-motion handling.
@@ -1,67 +0,0 @@
/**
* hero-timeline.js — complete, runnable GSAP hero entrance.
*
* Markup expected:
* <section class="hero">
* <p class="hero__eyebrow">EYEBROW</p>
* <h1 class="hero__title">Big bold headline that wraps</h1>
* <p class="hero__sub">Supporting copy.</p>
* <div class="hero__actions"><a class="btn">Primary</a><a class="btn btn--ghost">Secondary</a></div>
* <img class="hero__art" src="art.svg" alt="" />
* </section>
*
* CSS prerequisite: each split line wrapper needs overflow:hidden for the mask reveal:
* .hero__title .line { overflow: hidden; }
*
* Install: npm i gsap @gsap/react
*/
import gsap from "gsap";
import { SplitText } from "gsap/SplitText";
gsap.registerPlugin(SplitText);
export function playHeroIntro(root = document) {
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const q = gsap.utils.selector(root);
// Reduced motion: reveal everything instantly, no animation.
if (reduceMotion) {
gsap.set(q(".hero__eyebrow, .hero__sub, .hero__actions, .hero__art"), { autoAlpha: 1 });
gsap.set(q(".hero__title"), { autoAlpha: 1 });
return Promise.resolve();
}
// Wait for fonts so SplitText computes correct line breaks.
return document.fonts.ready.then(() => {
const titleEl = q(".hero__title")[0];
const split = new SplitText(titleEl, {
type: "lines",
linesClass: "line",
autoSplit: true, // GSAP 3.13+: re-split on resize/font swap
});
// Hidden start state (prevents flash of unstyled content).
gsap.set(q(".hero__eyebrow, .hero__sub, .hero__actions, .hero__art"), { autoAlpha: 0 });
gsap.set(titleEl, { autoAlpha: 1 });
const tl = gsap.timeline({
defaults: { ease: "power3.out", duration: 0.8 },
onComplete: () => split.revert(), // restore clean DOM once done (optional)
});
tl.from(".hero__eyebrow", { y: 16, autoAlpha: 0, duration: 0.5 })
.from(split.lines, { yPercent: 110, stagger: 0.12, duration: 0.9, ease: "power4.out" }, "-=0.2")
.from(".hero__sub", { y: 20, autoAlpha: 0 }, "-=0.6")
.from(".hero__actions .btn", { y: 12, autoAlpha: 0, stagger: 0.1, duration: 0.5 }, "-=0.4")
.from(".hero__art", { scale: 0.92, autoAlpha: 0, ease: "back.out(1.4)", duration: 1.1 }, "<0.1");
return tl;
});
}
// Auto-run on DOM ready when imported directly in a page.
if (typeof window !== "undefined" && document.querySelector(".hero")) {
if (document.readyState !== "loading") playHeroIntro();
else document.addEventListener("DOMContentLoaded", () => playHeroIntro());
}
@@ -1,59 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>loading</title>
<!-- GSAP core from CDN — no build step. Add plugins the same way if needed:
https://cdnjs.cloudflare.com/ajax/libs/gsap/3.13.0/ScrollTrigger.min.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.13.0/gsap.min.js"></script>
<style>
:root { color-scheme: dark; }
* { margin: 0; box-sizing: border-box; }
body {
min-height: 100svh; display: grid; place-items: center;
background: radial-gradient(120% 120% at 50% 0%, #1b1f3b 0%, #0a0a12 60%);
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
color: #f4f5ff; overflow: hidden;
}
.stage { text-align: center; padding: 6vmin; }
.title { font-size: clamp(2.5rem, 9vw, 6rem); font-weight: 800; letter-spacing: -0.03em; line-height: 1; }
.sub { font-size: clamp(1rem, 3.2vw, 1.6rem); margin-top: 1.2rem; color: #aab; }
.cta { display: inline-block; margin-top: 2.4rem; padding: 0.9rem 1.8rem;
border-radius: 999px; background: #5b6cff; color: #fff; font-weight: 600; }
</style>
</head>
<body>
<main class="stage">
<h1 class="title">Ship it.</h1>
<p class="sub">A standalone, screenshot-verifiable GSAP scene.</p>
<a class="cta" href="#">Get started</a>
</main>
<script>
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
// ── One master timeline: a single playhead the harness can seek ──────────
const tl = gsap.timeline({ defaults: { ease: "power3.out", duration: 0.7 } });
if (reduce) {
// Reduced motion: no spatial movement — just make the final state visible.
gsap.set([".title", ".sub", ".cta"], { opacity: 1, y: 0 });
} else {
tl.from(".title", { yPercent: 110, opacity: 0, ease: "power4.out", duration: 0.9 })
.from(".sub", { y: 24, opacity: 0 }, "-=0.45")
.from(".cta", { scale: 0.9, opacity: 0, ease: "back.out(1.7)" }, "-=0.3");
}
// ── Seek harness: ?t=N freezes the timeline at N seconds for a clean shot ─
const t = new URLSearchParams(location.search).get("t");
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // deterministic frozen frame
// no ?t → plays normally on load
// ── Ready signals for headless verification ──────────────────────────────
window.__ready = true;
document.title = "ready";
console.log("duration", tl.duration()); // end time for the ?t=<dur> shot
</script>
</body>
</html>
@@ -1,181 +0,0 @@
# ScrollTrigger Cookbook
Runnable patterns for GSAP 3.12+. Register first:
```js
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
```
## 1. Pin a section and scrub a timeline through it
The most common scrollytelling pattern: hold a section fixed and drive a multi-step timeline with scroll.
```js
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".story",
start: "top top",
end: "+=3000", // total scroll distance the pin lasts
pin: true,
scrub: 1,
anticipatePin: 1, // reduces a 1-frame jump when pinning fast scroll
},
});
tl.from(".story .step-1", { autoAlpha: 0, y: 60 })
.from(".story .step-2", { autoAlpha: 0, y: 60 })
.to(".story .bg", { scale: 1.2, ease: "none" }, 0); // runs across whole timeline
```
Tips:
- Each tween occupies an equal slice of the pinned distance unless you set durations/positions.
- `pinSpacing: true` (default) adds padding so content below does not jump. Set `false` only when overlaying.
- If the pinned element is inside a transformed/`overflow` ancestor, pinning breaks — pin a top-level element or set `pinReparent: true`.
## 2. Horizontal scroll (panels move sideways as the page scrolls vertically)
```html
<section class="h-wrap"><div class="track">
<div class="panel">1</div><div class="panel">2</div><div class="panel">3</div>
</div></section>
```
```css
.track { display: flex; width: max-content; }
.panel { width: 100vw; height: 100vh; flex: 0 0 100vw; }
```
```js
const track = document.querySelector(".track");
gsap.to(track, {
x: () => -(track.scrollWidth - window.innerWidth), // function = recalculated on refresh
ease: "none",
scrollTrigger: {
trigger: ".h-wrap",
pin: true,
scrub: 1,
end: () => "+=" + (track.scrollWidth - window.innerWidth),
invalidateOnRefresh: true, // re-run the x function on resize
},
});
```
`invalidateOnRefresh: true` plus function-based values is the correct way to stay responsive.
## 3. Snap to sections
```js
gsap.to(".sections", {
scrollTrigger: {
trigger: ".sections",
pin: true,
scrub: 1,
end: "+=4000",
snap: {
snapTo: 1 / 4, // 5 evenly spaced points (labels also possible: "labels")
duration: { min: 0.2, max: 0.6 },
delay: 0.05,
ease: "power1.inOut",
},
},
});
```
To snap to timeline labels: build a labeled timeline and use `snap: "labelsDirectional"`.
## 4. Batch reveals (performant many-element fade-in)
Instead of creating one ScrollTrigger per card (expensive at scale), batch them:
```js
ScrollTrigger.batch(".card", {
start: "top 85%",
onEnter: (els) =>
gsap.from(els, { autoAlpha: 0, y: 40, stagger: 0.12, overwrite: true }),
onLeaveBack: (els) =>
gsap.to(els, { autoAlpha: 0, y: 40, stagger: 0.12, overwrite: true }),
});
```
Set the initial hidden state to avoid a flash before JS runs: `gsap.set(".card", { autoAlpha: 0 })`.
## 5. Parallax layers
```js
gsap.utils.toArray(".parallax").forEach((layer) => {
const depth = layer.dataset.depth || 0.3; // 0 = static, 1 = scrolls with page
gsap.to(layer, {
yPercent: -depth * 100,
ease: "none",
scrollTrigger: { trigger: layer.parentElement, scrub: true, start: "top bottom", end: "bottom top" },
});
});
```
## 6. Linked timelines / containerAnimation (triggers inside horizontal scroll)
To trigger animations off elements that move horizontally inside a pinned horizontal scroller, pass the horizontal tween as `containerAnimation`:
```js
const scrollTween = gsap.to(track, { x: -2000, ease: "none",
scrollTrigger: { trigger: ".h-wrap", pin: true, scrub: 1, end: "+=2000" } });
gsap.from(".panel-2 .title", {
autoAlpha: 0, y: 50,
scrollTrigger: { trigger: ".panel-2 .title", containerAnimation: scrollTween, start: "left center" },
});
```
Note `start: "left center"` uses horizontal keywords because the trigger moves horizontally.
## 7. Refresh on dynamic content
Images and lazy content change layout after triggers are computed. Refresh when ready:
```js
window.addEventListener("load", () => ScrollTrigger.refresh());
imagesLoaded(document.body, () => ScrollTrigger.refresh()); // if using imagesLoaded lib
```
For accordions/tabs that change height, call `ScrollTrigger.refresh()` after the layout settles.
## 8. SPA / React cleanup (critical)
Orphaned ScrollTriggers cause ghost pins, leaks, and stacking bugs on route changes. Always scope and revert.
React with `@gsap/react`:
```jsx
import { useGSAP } from "@gsap/react";
function Section() {
const root = useRef(null);
useGSAP(() => {
gsap.from(".item", {
autoAlpha: 0, y: 40, stagger: 0.1,
scrollTrigger: { trigger: ".item", start: "top 80%" },
});
}, { scope: root }); // auto-reverts on unmount
return <div ref={root}>...</div>;
}
```
Plain SPA / manual:
```js
const ctx = gsap.context(() => { /* all gsap code */ }, rootEl);
// on teardown / route leave:
ctx.revert();
```
Nuclear option (e.g. global router hook): `ScrollTrigger.getAll().forEach((t) => t.kill());`
## Debugging checklist
- Triggers fire at wrong scroll position → likely created before images loaded; call `ScrollTrigger.refresh()`.
- Pinned element jumps to top-left → it has a transformed/`will-change`/`overflow:hidden` ancestor; pin higher up.
- Animation plays once then never resets → set appropriate `toggleActions` or use `scrub`.
- Horizontal scroll not responsive → use function-based `x`/`end` + `invalidateOnRefresh: true`.
- Markers misaligned → leftover triggers from previous render; ensure cleanup runs.
@@ -1,255 +0,0 @@
# ScrollTrigger + Lenis / Locomotive smooth-scroll sync
Wire GSAP ScrollTrigger together with Lenis (or Locomotive) smooth scrolling so there is no jitter, no marker drift, no broken pins, and no flipped/laggy scroll direction. Every one of those bugs has the same root cause: two animation loops running independently. Lenis transforms the scroll position on its own `requestAnimationFrame` loop while ScrollTrigger reads scroll on GSAP's ticker — when they tick separately, ScrollTrigger samples a stale position and everything desyncs. The fix is to run one loop: let GSAP's ticker drive Lenis, and tell ScrollTrigger to update on every Lenis scroll.
## The one canonical wiring (Lenis)
This is the entire correct setup. Do not add a separate `requestAnimationFrame` loop for Lenis — that is the most common mistake and the source of nearly all desync.
```js
import Lenis from 'lenis';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const lenis = new Lenis({
duration: 1.2,
smoothWheel: true,
// do NOT enable Lenis's own rAF; GSAP's ticker drives it (below)
});
// 1. Update ScrollTrigger every time Lenis scrolls
lenis.on('scroll', ScrollTrigger.update);
// 2. Drive Lenis from GSAP's ticker (single shared loop).
// gsap.ticker time is in SECONDS; Lenis expects MILLISECONDS.
gsap.ticker.add((time) => {
lenis.raf(time * 1000);
});
// 3. Disable GSAP's lag smoothing so ScrollTrigger never defers/
// catches up against Lenis (prevents jitter on heavy frames)
gsap.ticker.lagSmoothing(0);
```
Three lines do all the work:
1. `lenis.on('scroll', ScrollTrigger.update)` — ScrollTrigger recomputes positions the instant Lenis moves the page, so triggers/markers/pins track the smoothed scroll exactly.
2. `gsap.ticker.add(time => lenis.raf(time * 1000))` — Lenis advances inside GSAP's loop, guaranteeing both run on the same frame and in the same order. Critical unit conversion: `gsap.ticker` passes seconds, `lenis.raf()` wants milliseconds, so multiply by 1000.
3. `gsap.ticker.lagSmoothing(0)` — disables GSAP's catch-up behavior that, combined with Lenis, causes visible jitter when a frame is slow.
After this, never call `requestAnimationFrame(raf)` for Lenis yourself. If any tutorial code has a standalone `function raf(time){ lenis.raf(time); requestAnimationFrame(raf) }` loop, delete it — it competes with the ticker and reintroduces jitter and direction lag.
## Locomotive Scroll variant
Locomotive needs `scrollerProxy` because it scrolls an inner element, not `window`. The principle is identical (one loop, update ScrollTrigger on scroll), but the proxy maps coordinates:
```js
const locoScroll = new LocomotiveScroll({
el: document.querySelector('[data-scroll-container]'),
smooth: true,
});
locoScroll.on('scroll', ScrollTrigger.update);
ScrollTrigger.scrollerProxy('[data-scroll-container]', {
scrollTop(value) {
return arguments.length
? locoScroll.scrollTo(value, { duration: 0, disableLerp: true })
: locoScroll.scroll.instance.scroll.y;
},
getBoundingClientRect() {
return { top: 0, left: 0, width: innerWidth, height: innerHeight };
},
pinType: document.querySelector('[data-scroll-container]').style.transform
? 'transform' : 'fixed',
});
ScrollTrigger.addEventListener('refresh', () => locoScroll.update());
ScrollTrigger.refresh();
```
Every ScrollTrigger then needs `scroller: '[data-scroll-container]'`. Lenis is simpler because it scrolls the real document, so no `scrollerProxy` is needed.
## Pins, refresh, and resize
- Pinned ScrollTriggers work without `scrollerProxy` under Lenis because Lenis scrolls the document body. If pins still jump, ensure no rogue rAF loop exists and that `ScrollTrigger.update` is wired.
- On dynamic content/resize, call `ScrollTrigger.refresh()` after layout settles. With Lenis, also call `lenis.resize()` if container size changes.
- For elements that should *not* be smoothed (e.g. a modal that scrolls natively), mark with `data-lenis-prevent` so Lenis ignores them.
## Anchor links with smooth scroll
Native `<a href="#section">` jumps bypass Lenis (instant jump, then Lenis fights it). Route anchors through `lenis.scrollTo`:
```js
document.querySelectorAll('a[href^="#"]').forEach((a) => {
a.addEventListener('click', (e) => {
const id = a.getAttribute('href');
if (id.length > 1) {
e.preventDefault();
lenis.scrollTo(id, { offset: 0 }); // accepts selector, element, or number
}
});
});
```
If a sticky header overlaps the target, pass a negative offset or an offset callback:
```js
lenis.scrollTo(targetEl, { offset: -80 }); // 80px sticky header
```
## Reduced-motion gate
Respect `prefers-reduced-motion`: skip smooth scrolling entirely (do not instantiate Lenis, or stop it) and let ScrollTrigger run on native scroll.
```js
const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
let lenis;
if (!prefersReduced) {
lenis = new Lenis({ duration: 1.2 });
lenis.on('scroll', ScrollTrigger.update);
gsap.ticker.add((time) => lenis.raf(time * 1000));
gsap.ticker.lagSmoothing(0);
}
// ScrollTrigger animations are defined normally and work with or without Lenis
```
## Cleanup (SPA / React / route changes)
Destroy Lenis and remove the ticker callback on unmount, or stacked loops accumulate:
```js
function setup() {
const update = (time) => lenis.raf(time * 1000);
lenis.on('scroll', ScrollTrigger.update);
gsap.ticker.add(update);
gsap.ticker.lagSmoothing(0);
return () => {
gsap.ticker.remove(update);
lenis.destroy();
ScrollTrigger.getAll().forEach((t) => t.kill());
};
}
```
## Debugging checklist (work top to bottom)
1. **Is there a rogue rAF loop?** Search the codebase for `requestAnimationFrame` near `lenis.raf`. If Lenis is also driven by `gsap.ticker`, delete the standalone loop. Two loops = jitter, lag, flipped feel.
2. **Unit conversion present?** Confirm `lenis.raf(time * 1000)` inside the ticker. Missing `* 1000` makes scroll feel stuck or wildly slow.
3. **Is `ScrollTrigger.update` subscribed?** `lenis.on('scroll', ScrollTrigger.update)` must exist. Without it, markers and triggers drift behind the smoothed position.
4. **Is `lagSmoothing(0)` set?** Without it, heavy frames cause GSAP to "catch up", visible as jitter.
5. **Markers on for diagnosis.** Add `markers: true` to a trigger. If markers sit at the *native* scroll position but content moves with smoothed scroll, the update subscription is missing or a proxy is mis-set.
6. **Pins jumping?** Confirm no proxy is set for Lenis (it scrolls the document). For Locomotive, confirm `pinType` and `scroller` are correct.
7. **After dynamic content / fonts / images load**, call `ScrollTrigger.refresh()`. Stale measurements cause triggers to fire at wrong offsets.
8. **Nested scroll areas** (modals, code blocks) misbehave? Add `data-lenis-prevent` to the scrollable child.
9. **Cleanup on route change?** In SPAs, verify `gsap.ticker.remove(update)`, `lenis.destroy()`, and killing ScrollTriggers — otherwise each navigation stacks another loop.
## Symptom → cause table
| Symptom | Most likely cause |
|---|---|
| General jitter/stutter | Standalone rAF loop + ticker both driving Lenis |
| Scroll stuck / barely moves | Missing `* 1000` unit conversion |
| Markers offset from triggers | `ScrollTrigger.update` not bound to `lenis.on('scroll')` |
| Jitter only on heavy frames | `lagSmoothing(0)` not set |
| Pins jump / break | Proxy wrongly set under Lenis, or wrong `pinType` (Loco) |
| Animations a frame behind | Two loops out of order; consolidate to one ticker |
| Anchor links jump then snap back | Native `#hash` jump not routed via `lenis.scrollTo` |
| Triggers fire at wrong scroll position | Missing `ScrollTrigger.refresh()` after content/layout change |
| Worse after each route change | No cleanup; loops/triggers accumulating |
| Inner scroll container won't scroll | Lenis intercepting; add `data-lenis-prevent` |
## Complete React integration (useGSAP)
```jsx
'use client';
import { useRef } from 'react';
import Lenis from 'lenis';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useGSAP } from '@gsap/react';
gsap.registerPlugin(ScrollTrigger, useGSAP);
export default function ScrollSection() {
const root = useRef(null);
useGSAP(() => {
const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
let lenis;
let update;
if (!prefersReduced) {
lenis = new Lenis({ duration: 1.2, smoothWheel: true });
lenis.on('scroll', ScrollTrigger.update);
update = (time) => lenis.raf(time * 1000);
gsap.ticker.add(update);
gsap.ticker.lagSmoothing(0);
}
gsap.to('.panel', {
xPercent: -100,
ease: 'none',
scrollTrigger: {
trigger: '.panel',
start: 'top top',
end: '+=1500',
scrub: true,
pin: true,
// markers: true, // enable while debugging
},
});
return () => {
if (lenis) {
gsap.ticker.remove(update);
lenis.destroy();
}
};
}, { scope: root });
return (
<div ref={root}>
<section className="panel">…</section>
</div>
);
}
```
`useGSAP` auto-reverts GSAP tweens/ScrollTriggers created in its scope on unmount; the returned function additionally tears down Lenis and the ticker callback so nothing leaks across navigations.
## Plain useEffect equivalent
```jsx
useEffect(() => {
const lenis = new Lenis({ duration: 1.2 });
lenis.on('scroll', ScrollTrigger.update);
const update = (t) => lenis.raf(t * 1000);
gsap.ticker.add(update);
gsap.ticker.lagSmoothing(0);
const ctx = gsap.context(() => {
// ...ScrollTrigger animations here...
});
return () => {
gsap.ticker.remove(update);
lenis.destroy();
ctx.revert();
};
}, []);
```
## Excluding regions from smooth scroll
```html
<div class="code-block" data-lenis-prevent>…natively scrollable…</div>
```
`data-lenis-prevent` on a scrollable element makes Lenis ignore wheel/touch there, so inner scrolling works normally while the page stays smooth.
---
Sync ScrollTrigger to smooth scroll and the timeline tracks the page perfectly. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=gsap-web)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
-180
View File
@@ -1,180 +0,0 @@
---
name: lottie-animation
description: This skill should be used when the user asks to "add a Lottie animation", "play a .lottie or .json animation", "integrate a Bodymovin/After Effects animation on web or mobile", "control Lottie playback / segments", "make a scroll-driven Lottie", "recolor a Lottie at runtime", or "export an AE animation to Lottie". Covers dotLottie/lottie-web integration, playback control, interactivity, theming, and the AE export checklist.
version: 0.1.0
---
# Lottie Animation
The bridge from After Effects to product: vector animation shipped as JSON (or zipped `.lottie`), tiny and resolution-independent, played by a runtime on web, iOS, Android, and React Native. This skill covers integrating, controlling, and exporting Lottie.
## When to use
- Ship a designer's AE animation to web/iOS/Android/React Native
- Looping illustrations, onboarding, empty states, animated icons
- Scroll-driven or interaction-driven vector playback (hover, click, cursor)
- Runtime theming/recoloring instead of re-exporting per brand
## Formats: .json vs .lottie
- `.json` — the raw Bodymovin output. Human-readable, larger.
- `.lottie` — a zipped container (often 60–80% smaller) that can bundle multiple animations, images, and theming. Preferred for shipping. Player: `@lottiefiles/dotlottie-web` (modern, canvas + WASM) supersedes the older `lottie-web`.
Prefer the **dotLottie** runtime for new work; use `lottie-web` only for legacy `.json` + SVG renderer needs.
## Core workflow (web, dotLottie)
```bash
npm i @lottiefiles/dotlottie-web # vanilla
npm i @lottiefiles/dotlottie-react # React wrapper
```
Vanilla:
```js
import { DotLottie } from "@lottiefiles/dotlottie-web";
const dotLottie = new DotLottie({
canvas: document.querySelector("#lottie"), // a <canvas> element
src: "/hero.lottie", // or .json
loop: true,
autoplay: true,
// speed: 1, mode: "forward" | "reverse" | "bounce", renderConfig: { autoResize: true }
});
```
React:
```jsx
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
function Hero() {
return <DotLottieReact src="/hero.lottie" loop autoplay style={{ width: 320 }} />;
}
```
Capture the instance to control it:
```jsx
const [dl, setDl] = useState(null);
<DotLottieReact src="/icon.lottie" dotLottieRefCallback={setDl} />;
// dl?.play(); dl?.pause(); dl?.setSpeed(2);
```
## Playback control
```js
dotLottie.play();
dotLottie.pause();
dotLottie.stop();
dotLottie.setSpeed(1.5);
dotLottie.setMode("bounce"); // forward | reverse | bounce | reverse-bounce
dotLottie.setFrame(42); // jump to a frame
dotLottie.setSegment(30, 90); // constrain playback to a frame range (e.g. a "loading" loop)
```
Events drive sequencing and UI:
```js
dotLottie.addEventListener("load", () => { /* totalFrames now available */ });
dotLottie.addEventListener("complete", () => { /* non-looping playback finished */ });
dotLottie.addEventListener("frame", ({ currentFrame }) => { /* per-frame */ });
```
State-machine style (e.g. button that plays "checked" segment then idles): play a segment, listen for `complete`, then `setSegment` to the idle loop.
## Scroll-driven Lottie (no GSAP needed)
Map scroll progress (0–1) to a frame. Pause autoplay and drive frames yourself.
```js
const dotLottie = new DotLottie({ canvas, src: "/scroll.lottie", autoplay: false });
let total = 0;
dotLottie.addEventListener("load", () => { total = dotLottie.totalFrames; });
window.addEventListener("scroll", () => {
const el = canvas.closest(".scrolly");
const rect = el.getBoundingClientRect();
const p = clamp(-rect.top / (rect.height - window.innerHeight), 0, 1); // 0..1 through the section
dotLottie.setFrame(p * (total - 1));
}, { passive: true });
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
```
For richer interaction (hover-to-play, click toggles, cursor-follow) without writing the wiring, use `@lottiefiles/lottie-interactivity`, which maps `scroll`, `hover`, `click`, `play`, and `cursor` modes to frame ranges declaratively.
## Runtime theming / recoloring
Two paths:
- **dotLottie themes**: a `.lottie` can embed named color themes; switch with `dotLottie.setTheme("dark")` / `loadTheme(...)`. Authored in LottieFiles tooling — no re-export to recolor.
- **Manual color override**: load the JSON, walk `layers[].shapes[]` and patch `c.k` color arrays (normalized 0–1 RGBA), then init the player with the modified object. Brittle (depends on layer structure) — prefer themes or CSS-driven SVG-renderer (`lottie-web` `rendererSettings`) when you must restyle by class.
## Mobile runtimes (parity)
- iOS — `lottie-ios` (`LottieAnimationView`): `.play()`, `.currentProgress`, `.play(fromFrame:toFrame:)`.
- Android — `lottie-android` (`LottieAnimationView` / Compose `LottieAnimation`): `setMinAndMaxFrame`, `progress`.
- React Native — `lottie-react-native` (`<LottieView source={...} progress={anim} />`, drive `progress` with `Animated`).
The same `.lottie`/`.json` plays across all; segments and progress concepts match the web API.
## Optimization
- Ship `.lottie` (zipped) over raw `.json`; lazy-load offscreen players and pause when not visible (`IntersectionObserver` → `play`/`pause`).
- Prefer the canvas/WASM dotLottie renderer for many simultaneous animations; SVG renderer (lottie-web) is fine for one crisp icon but costs more DOM for complex files.
- Keep AE comps small: fewer layers/keyframes, no large embedded rasters; flatten precomps where possible. File size tracks keyframe and path complexity, not duration.
- Recolor at runtime (themes) instead of exporting a file per brand/theme.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained Lottie demo (looping illustration, animated icon, empty state) the deliverable is **one HTML file that opens directly in a browser** — the dotLottie/lottie-web runtime from CDN, a `<canvas>`, and your `.lottie`/`.json` (a relative file or a data URL). No build step. One file is the right tier for shipping a player; don't reach for a bundler.
**Output contract:**
- One `.html` file: the runtime via CDN (`@lottiefiles/dotlottie-web`), the canvas, and `autoplay:false` so the frame is yours to drive.
- Include the seek harness so any frame can be frozen for a screenshot.
**Seek harness — freeze an exact frame.** `?t=N` jumps to a frame and holds it so a screenshot lands on a still, deterministic frame. Lottie's playhead is in frames, so stop on the frame directly:
```html
<script>
const dl = new DotLottie({ canvas, src: "/icon.lottie", autoplay: false });
dl.addEventListener("load", () => {
const t = new URLSearchParams(location.search).get("t");
if (t !== null) dl.setFrame(parseFloat(t)); // freeze on frame N (lottie-web: anim.goToAndStop(N, true))
else dl.play();
console.log("totalFrames", dl.totalFrames); // read for end-frame
window.__ready = true;
});
</script>
```
**Verify loop — render → freeze → screenshot → check:** open the file at first / mid / last frame (`?t=0`, `?t=<total/2>`, `?t=<total-1>`; read `totalFrames` from the console), screenshot each, and check **fidelity** (colors/theme correct, segment loops where intended) plus **artifacts** (canvas blurry from missing `autoResize`/DPR, clipped composition, FOUC before the file loads, jank). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=600 "file://$PWD/lottie.html?t=42" frame-mid.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN runtime and the `.lottie`/`.json` load.
2. `?t=N` (`setFrame`/`goToAndStop`) freezes the correct, deterministic frame.
3. Screenshotted at first / mid / last frame — matches the brief, sharp, no clipping.
4. `prefers-reduced-motion` honored — don't `autoplay` a loop; show a static frame or offer a play control.
5. Easing is intentional — playback speed/segment chosen on purpose, motion baked in AE reads as designed.
## Quick reference
| Goal | Call |
|------|------|
| Play a range | `setSegment(start, end)` |
| Jump to frame | `setFrame(n)` |
| Reverse / bounce | `setMode("reverse"|"bounce")` |
| Scroll-drive | `autoplay:false` + `setFrame(p*totalFrames)` |
| Theme swap | `setTheme("dark")` |
| Know length | `totalFrames` after `load` event |
| Declarative interactivity | `@lottiefiles/lottie-interactivity` |
## Reference files
- `references/integration-and-export.md` — full dotLottie-web + React setup and event/segment control, `lottie-interactivity` mode configs, scroll/cursor patterns, runtime theming details, and the complete After Effects → Bodymovin export checklist with the list of unsupported AE features and how to work around them.
@@ -1,233 +0,0 @@
# Lottie Integration & Export (detailed)
## 1. dotLottie-web full setup
```bash
npm i @lottiefiles/dotlottie-web
```
```js
import { DotLottie } from "@lottiefiles/dotlottie-web";
const dotLottie = new DotLottie({
canvas: document.querySelector("#lottie"),
src: "/assets/onboarding.lottie", // .lottie or .json (URL or same-origin path)
autoplay: true,
loop: true,
speed: 1,
mode: "forward", // forward | reverse | bounce | reverse-bounce
useFrameInterpolation: true, // smoother than the source frame rate
renderConfig: {
autoResize: true, // keep the canvas crisp on resize/DPR changes
devicePixelRatio: window.devicePixelRatio,
},
});
```
The canvas MUST be a real `<canvas>` element. For responsiveness, size the canvas via CSS and keep `autoResize: true`; the runtime handles the backing store.
### Lifecycle and events
```js
dotLottie.addEventListener("load", () => console.log(dotLottie.totalFrames, dotLottie.duration));
dotLottie.addEventListener("loadError", (e) => console.error("bad src", e));
dotLottie.addEventListener("play", () => {});
dotLottie.addEventListener("pause", () => {});
dotLottie.addEventListener("complete", () => {}); // fires when a non-looping play finishes
dotLottie.addEventListener("loop", ({ loopCount }) => {});
dotLottie.addEventListener("frame", ({ currentFrame }) => {});
// always clean up (SPA/unmount)
dotLottie.destroy();
```
`totalFrames`, `duration`, and segment data are only valid AFTER the `load` event — read them there, not synchronously after construction.
### Multi-animation .lottie files
A single `.lottie` can hold several animations:
```js
dotLottie.addEventListener("load", () => {
console.log(dotLottie.manifest.animations); // list of animation ids
});
dotLottie.loadAnimation("success"); // switch by id without re-fetching
```
## 2. React wrapper
```bash
npm i @lottiefiles/dotlottie-react
```
```jsx
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
import { useState, useEffect } from "react";
function PlayButton() {
const [dl, setDl] = useState(null);
const [playing, setPlaying] = useState(true);
useEffect(() => {
if (!dl) return;
const onComplete = () => setPlaying(false);
dl.addEventListener("complete", onComplete);
return () => dl.removeEventListener("complete", onComplete);
}, [dl]);
return (
<DotLottieReact
src="/play.lottie"
autoplay
loop={false}
dotLottieRefCallback={setDl} // capture instance for imperative control
onClick={() => (playing ? dl.pause() : dl.play(), setPlaying((p) => !p))}
style={{ width: 200, height: 200 }}
/>
);
}
```
Props mirror the constructor: `src, autoplay, loop, speed, mode, useFrameInterpolation, renderConfig, themeId, segment`.
## 3. Segments and state machines
```js
// Loop only the "loading" portion (frames 30–90), then jump to a success segment.
dotLottie.setSegment(30, 90);
dotLottie.setLoop(true);
dotLottie.play();
function resolveSuccess() {
dotLottie.setLoop(false);
dotLottie.setSegment(91, 140); // success burst
dotLottie.play();
}
```
Pattern for icon toggles (e.g. like button): keep distinct frame ranges for each state in one file, and `setSegment` + `play` per interaction; listen for `complete` to settle into an idle range.
dotLottie also supports embedded **state machines** (`.lottie` with a `state-machine` definition): `dotLottie.stateMachineLoad("sm_id"); dotLottie.stateMachineStart();` then fire inputs/events — useful for complex interactive icons authored in LottieFiles without writing JS state logic.
## 4. lottie-interactivity (declarative)
```bash
npm i @lottiefiles/lottie-interactivity
```
Works with a `lottie-web`/dotLottie player instance (commonly the `<dotlottie-player>` / `<lottie-player>` web component):
```html
<dotlottie-player id="firstLottie" src="/scroll.lottie" style="width:300px"></dotlottie-player>
<script>
LottieInteractivity.create({
player: "#firstLottie",
mode: "scroll",
actions: [
{ visibility: [0, 0.3], type: "stop", frames: [0] },
{ visibility: [0.3, 1.0], type: "seek", frames: [0, 120] }, // map scroll → frames 0..120
],
});
</script>
```
Modes:
- `scroll` — tie frames to scroll position / element visibility (the canonical scrolly use).
- `cursor` — drive frames from cursor position over the element (hover scrub).
- `hover` — play on hover, control `loop`/`reset` on leave.
- `click` — advance to the next sync state on each click.
- `chain` — sequence multiple animations.
Use `type: "seek"` to scrub frames, `type: "loop"` / `"play"` / `"stop"` for segment behaviors.
## 5. Manual scroll mapping (full control, no extra lib)
```js
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
let total = 0;
dotLottie.addEventListener("load", () => { total = dotLottie.totalFrames - 1; });
const section = document.querySelector(".scrolly");
function update() {
const r = section.getBoundingClientRect();
const scrollable = r.height - window.innerHeight;
const p = clamp(-r.top / scrollable, 0, 1);
dotLottie.setFrame(p * total);
}
window.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", update);
```
Pause when offscreen to save CPU:
```js
new IntersectionObserver(([e]) => e.isIntersecting ? dotLottie.unfreeze() : dotLottie.freeze())
.observe(canvas);
```
## 6. Runtime theming
### Embedded themes (recommended)
A `.lottie` authored with named color themes:
```js
dotLottie.addEventListener("load", () => {
console.log(dotLottie.manifest.themes); // available theme ids
dotLottie.setTheme("dark"); // swap colors with no re-fetch / re-export
});
// or per slot:
dotLottie.setThemeData({ /* theme JSON */ });
```
### Manual color patching (last resort)
```js
const json = await fetch("/icon.json").then((r) => r.json());
// Lottie colors are normalized 0..1 [r,g,b,a] arrays at shapes[].it[].c.k
function recolor(layers, hex) {
const [r, g, b] = hexToRgb01(hex);
for (const layer of layers) {
for (const sh of layer.shapes ?? []) {
for (const it of sh.it ?? []) {
if (it.ty === "fl" || it.ty === "st") { it.c.k = [r, g, b, 1]; } // fill / stroke
}
}
if (layer.layers) recolor(layer.layers, hex); // precomps
}
}
recolor(json.layers, "#ff5500");
new DotLottie({ canvas, data: JSON.stringify(json), autoplay: true });
```
This depends on the exact layer/shape structure and breaks if the file changes — prefer embedded themes, or use the `lottie-web` SVG renderer and target paths with CSS where the markup is stable.
## 7. After Effects → Bodymovin export checklist
Plugin: **Bodymovin** (or LottieFiles plugin). `Window → Extensions → Bodymovin`. Select the comp, set destination, configure, Render.
Pre-export checklist:
1. Comp set to a sensible size and frame rate (24/30/60); avoid huge resolutions — Lottie is vector, the canvas scales.
2. Name layers/comps clearly — names survive into JSON and aid runtime theming/targeting.
3. Convert text you want crisp/animated-by-path to shapes if it uses unsupported text features; otherwise enable "Glyphs"/"Fonts" in Bodymovin settings for live text.
4. Trim the work area to exactly the frames you ship; trailing frames bloat the file.
5. In Bodymovin settings: enable **Compress assets / .lottie** output for the zipped format; enable "Glyphs" if using text; toggle "Standalone"/"Demo" only as needed.
6. Replace embedded raster images with vectors where possible; if rasters are required, they inflate `.json` (consider `.lottie` which bundles them).
7. Test the exported file in the LottieFiles preview AND your target runtime before handoff — renderers differ.
### Unsupported / partially-supported AE features (avoid or rework)
- **Expressions** — not evaluated by runtimes. Bake expression-driven motion to keyframes (Bodymovin can pre-render some) or remove. Heavy-expression rigs are the #1 source of "looks wrong in product".
- **Effects** — most AE effects (blurs, glows, distort, particle systems, CC effects) are NOT supported. Only a small set (e.g. some Gaussian blur, drop shadow, tint, fill via supported attributes) survive, and inconsistently across platforms. Recreate looks with shape layers, gradients, and mattes.
- **3D layers / camera** — not supported; fake depth with 2D scaling/position.
- **Time remapping / nested time stretch** — flaky; pre-compose and bake.
- **Auto-Orient, certain merge-paths modes, some matte combinations** — test explicitly.
- **Audio** — not part of Lottie.
- **Adjustment layers, layer styles (bevel/emboss/inner shadow)** — largely unsupported; convert to shapes/gradients.
- **Track mattes** — alpha/luma mattes generally work but increase cost; flatten when possible.
- **Gradients on strokes / complex gradient feathering** — limited; verify.
Workarounds summary: bake expressions to keyframes, replace effects with native shape/gradient/matte equivalents, flatten precomps, drop rasters, and verify on every target runtime (web/iOS/Android render slightly differently). Keep layer/keyframe count low for performance and file size.
---
Export clean from After Effects and the dotLottie plays light everywhere. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=lottie-animation)** — the AI motion agent for editable, on-brand motion graphics.
+24
View File
@@ -0,0 +1,24 @@
# Lower Thirds
Build a clean, branded lower third — the name/role caption that lives in the bottom band of the frame — that animates in, holds long enough to read, and exits without stealing the shot. The craft is restraint: a crisp reveal, a strong type hierarchy, correct safe-area placement, and one template that drives a whole roster of speakers. For creators producing interviews, panels, podcasts, and broadcast-style titles.
## When it activates
- "Make an animated lower third" or "add lower thirds."
- "Create a name tag/name lower third" or "do a speaker name overlay."
- "Build broadcast titles" or "animate a title/name/role caption."
- "Template lower thirds across a list of names."
## Example prompts
- "Add a lower third with the speaker's name and role, branded to my colors."
- "Build a staggered slide-in name plate for a podcast guest."
- "Template one lower-third design across a roster of 12 panelists."
## What's inside
- `SKILL.md` — enter/exit animation, in/out timing and dwell, safe-area conventions, and brand styling.
- `references/lower-third-component.md` — a reusable lower-third component.
---
Part of **[Short-Form Video Skills](../../)** · Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=tiktok-video-skills&utm_content=skill_footer&utm_term=lower-thirds)** — the AI motion agent for editable, on-brand motion graphics.
+146
View File
@@ -0,0 +1,146 @@
---
name: lower-thirds
description: This skill should be used when the user asks to "make an animated lower third", "add lower thirds", "create a name tag/name lower third", "build broadcast titles", "animate a title/name/role caption", "do a speaker name overlay", or "template lower thirds across a list of names". Covers enter/exit animation (slide/wipe/mask reveal), in/out timing & dwell, safe-area & broadcast conventions, name-vs-role type hierarchy, brand styling, and rendering one design across many names.
version: 0.1.0
---
# Lower Thirds
Build a clean, branded lower third — the name/role caption that lives in the bottom band of the frame — that animates in, holds long enough to read, and exits without stealing the shot. The craft is restraint: a crisp reveal, a strong type hierarchy, correct safe-area placement, and one template that drives a whole roster of speakers.
## When to use
- Speaker/interview name tags, panel rosters, talking-head captions.
- Broadcast-style titles, news straps, podcast/webinar name plates.
- Templating one design across a list of names/titles → many clips (the payoff).
## Anatomy
A lower third is two text lines plus a graphic bed, placed in the lower band:
| Element | Role | Type treatment |
|---|---|---|
| **Name** (primary) | Who | Largest, heaviest, tightest tracking |
| **Role/title** (secondary) | What/where | ~45–60% of name size, lighter weight, often a brand accent color |
| **Bar / panel / accent** | Reads against any background | Solid or 70–85% opacity; an accent rule ties to brand |
Keep it to two lines. A name line + role line is the whole job — extra lines erode the hierarchy and crowd the safe area.
## Three rules that prevent cheap-looking titles
1. **Never hard-cut a title on or off.** A bare appear/disappear reads as a mistake. Even a 12-frame fade or slide makes it feel produced.
2. **Stagger, don't slam.** Animate the bar first, then the name, then the role, each offset by 3–6 frames. Everything arriving at once feels flat; a short cascade feels designed.
3. **Hold long enough to read twice.** Roughly 3–5s on screen (read it aloud twice). Too short and it's missed; too long and it nags. Animate in/out, never mid-segment.
## Enter & exit animations
Pick one motion language and reuse it. The most reliable, premium-reading reveals:
| Reveal | Feel | How |
|---|---|---|
| **Slide + fade** | Clean, default | Translate in ~24–40px while fading; ease-out on enter |
| **Wipe bar** | Broadcast | A bar scales/sweeps in (`scaleX`/clip), text fades behind it |
| **Mask reveal** | Premium | Clip text to a moving rectangle so letters "wipe on" |
Use asymmetric easing: a snappy `ease-out` (`cubic-bezier(.22,1,.36,1)`) on enter, a quicker `ease-in` on exit. Exit faster than you entered (~⅔ the duration) so the title gets out of the way.
```css
/* Mask reveal: text wipes on left→right, no plugin needed */
.lt-name { clip-path: inset(0 100% 0 0); animation: wipe .5s cubic-bezier(.22,1,.36,1) forwards; }
@keyframes wipe { to { clip-path: inset(0 0 0 0); } }
```
## In/out timing & dwell
Think in three phases. Budget frames, not vibes (at 30fps):
| Phase | Budget | Note |
|---|---|---|
| Enter | 12–18f (0.4–0.6s) | Staggered: bar → name → role |
| Hold | 90–150f (3–5s) | The readable dwell; scale with line length |
| Exit | 8–12f (0.27–0.4s) | Faster than enter |
In code, drive every state from the current frame (or a paused timeline), not wall-clock time — a video renderer demands deterministic frames. Express enter/hold/exit as a single progress curve so the same component works live in a browser and frame-by-frame in a renderer.
## Safe area & broadcast conventions
The lower third must survive every screen and platform UI. Compose inside the **title-safe area** (inner ~90% / margin 5%) and respect platform chrome:
| Frame | Anchor | Avoid |
|---|---|---|
| 16:9 (1920×1080) | Left edge at ~5% margin; baseline ~80–85% down | Outer 5% (title-safe), action-safe outer 10% |
| 9:16 (1080×1920) | Same left margin; **lift the band up** | Bottom ~18% (captions/UI), top ~12% |
| 1:1 (1080×1080) | Lower band, center-left | Outer 5% |
Anchor to the **left** and grow rightward so names of different lengths stay pinned and never re-center awkwardly. Keep the role line within the same left margin as the name. For 9:16, do not park the title at the very bottom — platform captions and buttons sit there.
## Type hierarchy & brand styling
Hierarchy is the whole design. Make the name unmistakably dominant:
- **Size contrast** ≥ 1.6× (name vs role). If unsure, push the name bigger, not the role.
- **Weight + color**: name in bold/near-white; role in a lighter weight and a **brand accent** color (one accent, used consistently).
- **Contrast for legibility**: text rides over unknown footage. Use a solid/semi-opaque bar, a subtle scrim, or a soft text shadow so it reads over both bright and dark plates.
- **Brand lock**: pin font, accent color, bar style, and corner radius in one theme object so every title across a series matches.
## Templating one design across a list
The reason to build this in code: change the text/data, re-export — no re-animating. Make name/role/theme **props**, never hardcoded, then map a roster to instances.
```jsx
const ROSTER = [
{ name: "Ada Lovelace", role: "Founder, Analytical Engines" },
{ name: "Grace Hopper", role: "Rear Admiral, US Navy" },
{ name: "Alan Turing", role: "Mathematician" },
];
// One <LowerThird> design; map the list → many instances (sequence them in a renderer)
{ROSTER.map((p, i) => <LowerThird key={p.name} {...p} theme={BRAND} startFrame={i * 150} />)}
```
In a renderer, make the roster an input prop and render once per row (`--props`) to emit one branded clip per person — same animation, same brand, only the text changes. See `references/lower-third-component.md` for the full runnable component and batch script.
## Output checklist
- Two lines only: dominant name, secondary role (≥1.6× size contrast).
- Animated in and out (no hard cut); enter staggered bar→name→role; exit faster.
- Hold 3–5s (readable twice); motion only at the ends, never mid-segment.
- Left-anchored inside title-safe; 9:16 band lifted above the bottom-18% UI zone.
- Text legible over any plate (bar/scrim/shadow); one brand accent throughout.
- Name/role/theme are props — one template renders the whole roster.
## Deliver & verify (rendered stills → MP4)
> **Packaged helper** (`scripts/`): tile your stills with `scripts/contact-sheet.sh sheet.png f-hook.png f-mid.png f-end.png`, then assert the encode with `scripts/probe-mp4.sh out.mp4 [WxH] [fps]`. See `scripts/README.md`.
The lower third ships as a Remotion composition (`<Composition>` + zod `schema` + `defaultProps`, name/role/theme as props) — enter/dwell/exit all driven by `useCurrentFrame()`, never `Date.now()` / `Math.random()` / timers. Deliverable = `out/*.mp4` + the project (re-render per roster row). 9:16 vertical (1080×1920) is the default.
**Verify loop — render stills → inspect → encode.** Sample the three phases so you catch a stagger or safe-area bug before encoding (or batching the whole roster).
```bash
# Stills at enter / dwell / exit — WITH SHIPPED PROPS (a real roster row, not defaults)
npx remotion still LowerThird out/f-enter.png --frame=10 --props='{"name":"Ada Lovelace","role":"Founder, Analytical Engines"}'
npx remotion still LowerThird out/f-dwell.png --frame=75 --props='{"name":"Ada Lovelace","role":"Founder, Analytical Engines"}'
npx remotion still LowerThird out/f-exit.png --frame=N --props='{"name":"Ada Lovelace","role":"Founder, Analytical Engines"}'
# Inspect each PNG — focus the DWELL frame (fully on screen):
# - hierarchy holds: name dominant (>=1.6x role), role in brand accent; both fully revealed, not mid-wipe
# - brand lock: font, accent color, bar/scrim correct; legible over the plate
# - 9:16 safe area: band LIFTED above the bottom ~20-35% UI zone, clear of top ~12% and the right action rail; left-anchored inside title-safe
# - enter/exit frames show partial reveal (animation actually runs), not a hard cut
npx remotion render LowerThird out/lower-third.mp4 --props='{"name":"Ada Lovelace","role":"Founder, Analytical Engines"}'
npx remotion render LowerThird out/demo.gif --codec=gif # README proof clip
```
**Batch roster**: verify ONE row via stills *before* rendering all names — catch a layout/overflow bug once, not N times. Use `npx remotion compositions` for `durationInFrames`/`fps` to pick the dwell + exit frames.
**Before you finish:**
1. Stills render cleanly at enter, dwell, and exit — no missing font/brand assets.
2. At the dwell frame: name dominant over role, brand accent + bar correct, fully (not partly) revealed.
3. The band is inside the 9:16 safe area — lifted above the bottom UI zone, clear of top and right rail — at every checked frame.
4. Frame-driven only — no `Date.now()` / `Math.random()` / timers; enter/exit show motion, never a hard cut.
5. A real roster row (not `defaultProps`) renders correctly; MP4 encoded, GIF optional.
## Reference files
- `references/lower-third-component.md` — a complete runnable lower-third: a Remotion component with staggered spring enter, readable hold, and faster exit driven purely by frame; a typed theme object for brand lock; the list→many-instances sequencing pattern; a per-row batch render script; plus a dependency-free CSS/HTML version of the same design with mask-reveal and wipe-bar variants.
@@ -0,0 +1,268 @@
# Lower-Third Component — runnable code
A complete, production-grade lower third you can drop in. Two paths:
1. **Remotion** (frame-deterministic, renders to MP4, batches over a roster).
2. **CSS/HTML** (no dependencies, for the web or a quick preview) with mask-reveal and wipe-bar variants.
Both share the same design language: a left-anchored bar, a dominant name, a brand-accent role line, a staggered enter, a readable hold, and a faster exit.
---
## 1. Remotion component (props-driven, frame-deterministic)
The animation is a pure function of `frame`, so it renders identically every time and stays in sync with the renderer. Enter staggers the bar, name, then role; exit is computed from the end of the clip so the title leaves faster than it arrived.
```tsx
// LowerThird.tsx
import {
AbsoluteFill, Sequence, interpolate, spring,
useCurrentFrame, useVideoConfig,
} from "remotion";
// --- Brand lock: change once, every title matches -------------------------
export type Theme = {
font: string;
bar: string; // panel/bar color
name: string; // primary text color
role: string; // accent color for the role line
radius: number;
marginPct: number; // left/safe margin as % of width
};
export const BRAND: Theme = {
font: "Inter, system-ui, sans-serif",
bar: "rgba(12,14,22,0.86)",
name: "#FFFFFF",
role: "#6EE7F0", // single brand accent
radius: 10,
marginPct: 5,
};
export type LowerThirdProps = {
name: string;
role: string;
theme?: Theme;
holdSeconds?: number; // readable dwell, default 4s
};
// Staggered enter via spring; exit via a quick fade/slide near the end.
const useEnterExit = (delayFrames: number, holdSeconds: number) => {
const frame = useCurrentFrame();
const { fps, durationInFrames } = useVideoConfig();
// ENTER: spring 0→1, offset by delayFrames (the cascade)
const enter = spring({
frame: frame - delayFrames,
fps,
config: { damping: 200, stiffness: 180, mass: 0.6 },
});
// EXIT: faster than enter — last 10 frames of the clip
const exitStart = durationInFrames - 10;
const exit = interpolate(frame, [exitStart, durationInFrames], [1, 0], {
extrapolateLeft: "clamp",
extrapolateRight: "clamp",
});
const opacity = enter * exit;
const x = interpolate(enter, [0, 1], [-32, 0]); // slide in from left
return { opacity, x };
};
const Line: React.FC<{
delay: number; holdSeconds: number; children: React.ReactNode;
size: number; weight: number; color: string; tracking?: number;
}> = ({ delay, holdSeconds, children, size, weight, color, tracking = 0 }) => {
const { opacity, x } = useEnterExit(delay, holdSeconds);
return (
<div style={{
opacity,
transform: `translateX(${x}px)`,
fontSize: size, fontWeight: weight, color,
letterSpacing: tracking, lineHeight: 1.15, whiteSpace: "nowrap",
}}>
{children}
</div>
);
};
export const LowerThird: React.FC<LowerThirdProps> = ({
name, role, theme = BRAND, holdSeconds = 4,
}) => {
const { width, height } = useVideoConfig();
const bar = useEnterExit(0, holdSeconds); // bar leads the cascade
const left = (width * theme.marginPct) / 100;
const baseline = height * 0.80; // sit ~80% down, inside title-safe
return (
<AbsoluteFill style={{ fontFamily: theme.font }}>
<div style={{
position: "absolute", left, top: baseline,
opacity: bar.opacity,
transform: `translateX(${bar.x}px)`,
}}>
{/* panel behind text guarantees legibility over any plate */}
<div style={{
background: theme.bar, borderRadius: theme.radius,
padding: "14px 22px 16px",
borderLeft: `4px solid ${theme.role}`, // accent rule ties to brand
backdropFilter: "blur(6px)",
}}>
<Line delay={4} holdSeconds={holdSeconds} size={46} weight={800} color={theme.name} tracking={-0.5}>
{name}
</Line>
<Line delay={8} holdSeconds={holdSeconds} size={26} weight={500} color={theme.role}>
{role}
</Line>
</div>
</div>
</AbsoluteFill>
);
};
```
Why each choice matters:
- **`spring` per line, offset by `delay`** gives the bar→name→role cascade. Same offsets everywhere keep titles consistent.
- **Exit derived from `durationInFrames`** means any clip length exits cleanly without per-instance tuning, and it's quicker than the enter (10f vs the spring's settle).
- **`whiteSpace: nowrap` + left anchor** keeps long and short names pinned to the same edge — no awkward re-centering across a roster.
- **`borderLeft` accent + semi-opaque panel** is the brand tie plus the legibility guarantee over unknown footage.
### Roster → many instances (one design, a whole panel)
Sequence the same component down a list. Each person gets a slot; only the text changes.
```tsx
// Roster.tsx
import { Series } from "remotion";
import { LowerThird, BRAND } from "./LowerThird";
const ROSTER = [
{ name: "Ada Lovelace", role: "Founder, Analytical Engines" },
{ name: "Grace Hopper", role: "Rear Admiral, US Navy" },
{ name: "Alan Turing", role: "Mathematician" },
];
export const Roster: React.FC = () => (
<Series>
{ROSTER.map((p) => (
<Series.Sequence key={p.name} durationInFrames={150 /* ~5s @30fps */}>
<LowerThird name={p.name} role={p.role} theme={BRAND} />
</Series.Sequence>
))}
</Series>
);
```
### Batch: one branded clip per person
Make the roster an input prop and render once per row, so each speaker becomes a standalone overlay clip — identical animation and brand, only the text differs.
```bash
#!/usr/bin/env bash
# render one transparent-friendly lower-third clip per person in roster.json
# roster.json: [{"name":"Ada Lovelace","role":"Founder, Analytical Engines"}, ...]
set -euo pipefail
mkdir -p out
jq -c '.[]' roster.json | while read -r row; do
slug=$(echo "$row" | jq -r '.name' | tr '[:upper:] ' '[:lower:]-')
npx remotion render LowerThird "out/${slug}.mp4" --props="$row"
done
```
For overlay-ready output with transparency, render the `LowerThird` composition (transparent background) to a codec that keeps alpha, e.g. `--codec=prores --prores-profile=4444`, or `--image-format=png` for a PNG sequence.
---
## 2. CSS / HTML version (no dependencies)
The same design without a framework — for the web, OBS browser sources, or a fast look-test. Includes both a **slide+fade** default and a **mask-reveal** name, plus a **wipe-bar** variant.
```html
<div class="lt" style="--accent:#6EE7F0">
<div class="lt-bar">
<div class="lt-name">Ada Lovelace</div>
<div class="lt-role">Founder, Analytical Engines</div>
</div>
</div>
<style>
:root { font-family: Inter, system-ui, sans-serif; }
.lt {
position: absolute; left: 5%; top: 80%; /* title-safe, left-anchored */
}
.lt-bar {
display: inline-block;
background: rgba(12,14,22,0.86);
backdrop-filter: blur(6px);
border-left: 4px solid var(--accent);
border-radius: 10px;
padding: 14px 22px 16px;
/* bar leads the cascade: slide + fade in, then a faster fade out */
animation: lt-in .5s cubic-bezier(.22,1,.36,1) both,
lt-out .3s ease-in 4.5s forwards; /* hold ~4s, exit faster */
}
.lt-name {
font-size: 46px; font-weight: 800; color: #fff; letter-spacing: -.5px;
line-height: 1.15; white-space: nowrap;
/* MASK REVEAL: letters wipe on left→right, staggered after the bar */
clip-path: inset(0 100% 0 0);
animation: lt-wipe .5s cubic-bezier(.22,1,.36,1) .12s forwards;
}
.lt-role {
font-size: 26px; font-weight: 500; color: var(--accent);
line-height: 1.15; white-space: nowrap;
opacity: 0;
animation: lt-fade .4s ease-out .22s forwards; /* role arrives last */
}
@keyframes lt-in { from { opacity: 0; transform: translateX(-32px); }
to { opacity: 1; transform: none; } }
@keyframes lt-out { to { opacity: 0; transform: translateX(-16px); } }
@keyframes lt-wipe { to { clip-path: inset(0 0 0 0); } }
@keyframes lt-fade { to { opacity: 1; } }
/* Mobile/9:16: lift the band above the bottom UI/caption zone */
@media (max-aspect-ratio: 1/1) { .lt { top: 70%; } }
</style>
```
### Wipe-bar variant (broadcast feel)
Swap the bar animation so a colored bar sweeps in and the text rides behind it:
```css
.lt-bar.wipe {
position: relative; overflow: hidden;
animation: lt-in .45s cubic-bezier(.22,1,.36,1) both,
lt-out .3s ease-in 4.5s forwards;
}
.lt-bar.wipe::before {
content: ""; position: absolute; inset: 0;
background: var(--accent);
transform-origin: left;
animation: lt-sweep .55s cubic-bezier(.76,0,.24,1) both; /* sweep across, then reveal */
}
@keyframes lt-sweep { 0% { transform: scaleX(0); } 60% { transform: scaleX(1); }
100% { transform: scaleX(0); transform-origin: right; } }
```
The CSS clock (`animation`) is fine for live/web playback. For a deterministic MP4, prefer the Remotion path above — a frame renderer and CSS timers disagree, which causes flicker or desync at export.
---
## Quick reference
| Need | Knob |
|---|---|
| Slower/faster reveal | enter duration 12–18f / `.5s` |
| Longer dwell | `holdSeconds` / the `4.5s` exit delay |
| Bigger name dominance | name `fontSize` (keep ≥1.6× the role) |
| Rebrand everything | the `BRAND` theme object / `--accent` |
| 9:16 placement | `baseline 0.80→0.70` / the media query |
---
## Built by the team behind iart.ai
This skill is part of an open motion-graphics collection from iart.ai — the AI motion agent that turns data, scripts, and designs into editable motion graphics (Remotion → MP4). If you'd rather not hand-build this, iart.ai can generate branded lower-thirds from a list of names/titles, one-click — change the text/data and re-export. → [iart.ai](https://iart.ai/?utm_source=github&utm_medium=reference&utm_campaign=tiktok-video-skills&utm_content=ref_footer&utm_term=lower-thirds)
Whitespace-only changes.
-173
View File
@@ -1,173 +0,0 @@
---
name: micro-interaction
description: This skill should be used when the user asks to "add a hover/press effect", "animate a toggle or switch", "build an animated like button", "make a toast/snackbar slide in", "animate a drawer or modal", "animate list reordering or add/remove", "do a shared-element layout transition", or "polish UI feedback". Covers UI motion with Framer Motion (motion/react) and modern CSS.
version: 0.1.0
---
# Micro-interactions (UI Motion)
Small, functional motion that makes an interface feel responsive and alive: hover/press/focus feedback, toggles, toasts, drawers, and list/layout animation. The goal is feedback and continuity, not decoration.
## When to use
- Hover/press/focus feedback; toggles, checkboxes, like/heart buttons
- Toasts/snackbars, drawers, modals, tooltips, accordions (enter/exit)
- List add/remove/reorder; shared-element ("magic move") layout transitions
- Loading → success → error state transitions
## Principles (apply to all of it)
- Duration: UI micro-interactions live in **100–250ms**. Anything over ~400ms feels laggy for a click response.
- Animate `transform` and `opacity` only — they are GPU-composited (no layout/paint). Avoid animating `width/height/top/left`; use `scale` or layout animation instead.
- Give **instant** press feedback: `scale: 0.96` on tap with a fast spring.
- Asymmetric timing: enter slightly slower (ease-out), exit faster (ease-in). Things should arrive gracefully and leave promptly.
- Respect `prefers-reduced-motion`: gate non-essential motion; keep opacity changes, drop large movement.
- Easing defaults: ease-out for entrances `cubic-bezier(0.16, 1, 0.3, 1)`; a tasteful overshoot is `cubic-bezier(0.34, 1.56, 0.64, 1)`; standard move `cubic-bezier(0.4, 0, 0.2, 1)`.
## Framer Motion (motion/react) essentials
As of v11+, the package is imported as `motion/react` (the `framer-motion` name still works).
### Gestures and springs
```jsx
import { motion } from "motion/react";
<motion.button
whileHover={{ scale: 1.03 }}
whileTap={{ scale: 0.96 }}
whileFocus={{ boxShadow: "0 0 0 3px rgba(59,130,246,.5)" }}
transition={{ type: "spring", stiffness: 400, damping: 30 }}
/>
```
Spring intuition: higher `stiffness` = faster; higher `damping` = less bounce. `stiffness: 400, damping: 30` is a snappy UI default. For visible bounce, lower damping (e.g. `damping: 12`).
### Enter / exit with AnimatePresence
Exit animations require `AnimatePresence` wrapping conditionally-rendered children, each with a stable `key`.
```jsx
import { AnimatePresence, motion } from "motion/react";
<AnimatePresence>
{open && (
<motion.div
key="panel"
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 8 }}
transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
/>
)}
</AnimatePresence>
```
For toasts/lists, use `mode="popLayout"` so removed items don't hold space while exiting.
### Layout animation (the superpower)
`layout` automatically animates any layout change (position/size) using transforms — perfect for reordering, expanding cards, and grid<->list.
```jsx
<motion.li layout transition={{ type: "spring", stiffness: 500, damping: 40 }} />
```
Shared-element transition across components: give two elements the same `layoutId` and Framer Motion animates between them as one mounts and the other unmounts.
```jsx
{!open && <motion.div layoutId="card" onClick={() => setOpen(true)} />}
<AnimatePresence>
{open && <motion.div layoutId="card" />} {/* "magic moves" from the source */}
</AnimatePresence>
```
Gotcha: a plain `layout` element distorts `border-radius` and text during scale. Add `layout` to direct children that should counter-scale, and prefer `borderRadius`/`boxShadow` as motion values, or use `layout="position"` to animate position only.
## Pure CSS path (no JS, including discrete properties)
Modern CSS can animate enter/exit and even `display` toggles without a library.
```css
.toast {
transition: opacity 0.2s ease, transform 0.2s ease;
/* allow animating to/from display:none and from initial render */
transition-behavior: allow-discrete;
}
.toast[hidden] { display: none; }
/* animate FROM these values on first render / when entering */
@starting-style {
.toast { opacity: 0; transform: translateY(8px); }
}
```
`@starting-style` defines the "before-open" values so an element animates in on first appearance; `transition-behavior: allow-discrete` lets `display` (and `overlay` for popovers/dialogs) participate so exit animations run before the element is removed. Baseline in Chrome/Edge/Safari; provide a no-animation fallback for older browsers.
Always include a reduced-motion guard:
```css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
```
## State, not just decoration
Loading → success → error should be one continuous motion (e.g. a button morphs spinner → checkmark), not a jump cut. Keep the element mounted and animate between states so the eye tracks the same object.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained interaction demo (toggle, like button, toast, drawer) the deliverable is **one HTML file that opens directly in a browser**. Pure-CSS interactions ship as-is; for a Framer Motion demo, load React + `motion` from CDN (`esm.sh`) into one inline module — no build step. One file is the right tier; don't reach for a bundler.
**Output contract:**
- One `.html` file: your markup plus either CSS transitions/`@starting-style` or an inline `<script type="module">` importing `motion` from CDN.
- A way to land on the **resolved end state** for a screenshot — interactions are state-driven, not time-driven, so freeze the state rather than a clock.
**Seek harness — pin a deterministic state.** A micro-interaction's "frames" are its states (idle / hover / pressed / open). `?state=open` applies the target state on load so a screenshot captures it settled:
```html
<script>
const s = new URLSearchParams(location.search).get("state");
if (s) document.documentElement.dataset.state = s; // CSS keys off [data-state="open"]
// Framer Motion: set the controlled prop from `s` (e.g. const [open]=useState(s==="open"))
// For a CSS @keyframes loop instead, freeze it: el.style.animationDelay=(-N)+"s"; el.style.animationPlayState="paused";
window.__ready = true;
</script>
```
**Verify loop — render → set state → screenshot → check:** open each meaningful state (`?state=idle`, `?state=hover`, `?state=open`), screenshot, and check **fidelity** (press feedback reads instant, exit runs before unmount) plus **artifacts** (`layout` distorting `border-radius`/text, toast holding space after exit, FOUC, jank). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=400 "file://$PWD/demo.html?state=open" open.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN React/`motion` (if used) resolves.
2. The `?state=` (or controlled-prop) freeze lands a deterministic, settled state.
3. Screenshotted across states — idle / active / open — matches the brief, no artifacts.
4. `prefers-reduced-motion` honored — large movement dropped, opacity/feedback kept.
5. Easing is intentional — enter ease-out, exit ease-in, durations in the 100–250ms band.
## Quick reference
| Need | Approach |
|------|----------|
| Press feedback | `whileTap={{ scale: 0.96 }}` spring 400/30 |
| Enter/exit | `AnimatePresence` + `initial/animate/exit` |
| Reorder / resize | `layout` prop (spring) |
| Magic move | shared `layoutId` |
| Toast stack | `AnimatePresence mode="popLayout"` |
| No-JS enter | `@starting-style` + transition |
| Animate to display:none | `transition-behavior: allow-discrete` |
| Accessibility | `prefers-reduced-motion` guard always |
## Reference files
- `references/framer-motion-recipes.md` — variants + stagger, `AnimatePresence` modes, `layout`/`layoutId` magic move, `Reorder` drag-to-sort, drag constraints, gesture composition, and `useReducedMotion`.
- `references/css-recipes.md` — `@starting-style`, `transition-behavior: allow-discrete`, popover/dialog exit animation, keyframe spinners/toggles, `@property` for animatable custom properties, and `prefers-reduced-motion` patterns.
@@ -1,142 +0,0 @@
# CSS Micro-interaction Recipes
Modern CSS handles most UI motion with zero JavaScript, including enter/exit and `display` toggles. Baseline-available in current Chrome/Edge/Safari/Firefox (verify `@starting-style` and `allow-discrete` for your support floor; degrade to instant show/hide otherwise).
## Enter animation on first render: @starting-style
`@starting-style` supplies the values an element transitions FROM the first time it renders (or becomes shown). Without it, there is no "previous" state to transition from, so newly-inserted elements snap in.
```css
.menu {
opacity: 1;
transform: translateY(0);
transition: opacity 0.2s ease, transform 0.2s ease;
}
@starting-style {
.menu { opacity: 0; transform: translateY(-8px); }
}
```
## Animating to/from display:none: transition-behavior: allow-discrete
`display` and `content-visibility` are discrete properties — normally they flip instantly, killing exit animations. `allow-discrete` lets them flip at the correct moment (kept visible during exit, swapped at the end).
```css
.drawer {
transition:
transform 0.25s ease,
opacity 0.25s ease,
display 0.25s allow-discrete; /* keep displayed through the exit */
}
.drawer[hidden] { /* closed state */
opacity: 0;
transform: translateX(100%);
display: none;
}
@starting-style {
.drawer:not([hidden]) { opacity: 0; transform: translateX(100%); }
}
```
Shorthand alternative: `transition-behavior: allow-discrete;` applies to all discrete properties in the `transition` list.
## Popover / dialog exit animation (top-layer)
Native `popover` and `<dialog>` live in the top layer via the `overlay` property, which is also discrete — animate it too:
```css
[popover] {
opacity: 0;
transform: scale(0.95);
transition: opacity 0.2s, transform 0.2s, overlay 0.2s allow-discrete, display 0.2s allow-discrete;
}
[popover]:popover-open { opacity: 1; transform: scale(1); }
@starting-style {
[popover]:popover-open { opacity: 0; transform: scale(0.95); }
}
```
This gives a fully CSS-driven open AND close animation for `<button popovertarget>` popovers with no JS.
## Press / hover / focus feedback
```css
.btn {
transition: transform 0.12s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease;
}
.btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.15); }
.btn:active { transform: translateY(0) scale(0.97); transition-duration: 0.06s; } /* snappy press */
.btn:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
```
Use `:focus-visible` (not `:focus`) so keyboard users get a ring but mouse clicks don't.
## Animated toggle / switch
```css
.switch { width: 44px; height: 24px; border-radius: 999px; background: #cbd5e1;
transition: background 0.2s ease; }
.switch[aria-checked="true"] { background: #22c55e; }
.switch::after {
content: ""; width: 20px; height: 20px; border-radius: 50%; background: #fff;
transform: translateX(2px);
transition: transform 0.22s cubic-bezier(0.34, 1.56, 0.64, 1);
}
.switch[aria-checked="true"]::after { transform: translateX(22px); }
```
The `cubic-bezier(0.34, 1.56, 0.64, 1)` overshoot gives the knob a satisfying snap.
## Loading spinner and pulse
```css
@keyframes spin { to { transform: rotate(360deg); } }
.spinner { animation: spin 0.8s linear infinite; }
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.5; } }
.skeleton { animation: pulse 1.5s ease-in-out infinite; }
```
## Animatable custom properties with @property
Plain CSS variables animate discretely. Register them with `@property` to give them a type so they interpolate smoothly — enables gradient angle, number counters, and themed motion.
```css
@property --angle { syntax: "<angle>"; inherits: false; initial-value: 0deg; }
.gradient-border {
background: conic-gradient(from var(--angle), #6366f1, #ec4899, #6366f1);
transition: --angle 0.4s ease;
}
.gradient-border:hover { --angle: 360deg; }
```
## Accordion height (modern: interpolate-size)
Animating `height: auto` historically required JS measurement. With `interpolate-size: allow-keywords`, transitions to/from intrinsic sizes work:
```css
:root { interpolate-size: allow-keywords; }
.accordion__panel {
height: 0; overflow: hidden;
transition: height 0.3s ease;
}
.accordion__panel[data-open] { height: auto; }
```
Fallback for unsupported browsers: animate `grid-template-rows: 0fr -> 1fr` on a wrapper.
## Reduced motion (always include)
```css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
```
Then selectively re-enable essential, low-motion feedback (e.g. opacity-only fades) inside the same query if needed. The principle: never remove feedback entirely, just remove large/spatial motion.
@@ -1,187 +0,0 @@
# Framer Motion Recipes
Import from `motion/react` (v11+). All examples are React + Framer Motion.
```jsx
import { motion, AnimatePresence, Reorder, useReducedMotion, useDragControls } from "motion/react";
```
## Variants and staggered children
Variants are named animation states a parent can propagate to children, enabling orchestration like staggering without per-child timing math.
```jsx
const list = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.06, delayChildren: 0.1 },
},
};
const item = {
hidden: { opacity: 0, y: 12 },
show: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 500, damping: 30 } },
};
<motion.ul variants={list} initial="hidden" animate="show">
{items.map((t) => (
<motion.li key={t.id} variants={item}>{t.label}</motion.li>
))}
</motion.ul>
```
`staggerDirection: -1` staggers from last to first. `when: "beforeChildren"` / `"afterChildren"` sequences parent vs children.
## AnimatePresence modes
```jsx
<AnimatePresence mode="wait"> {/* outgoing finishes before incoming starts (route/tab switches) */}
<motion.div key={tab} initial={{opacity:0}} animate={{opacity:1}} exit={{opacity:0}} />
</AnimatePresence>
```
Modes:
- default (`"sync"`) — incoming and outgoing animate simultaneously.
- `"wait"` — finish exit before enter (single-element swaps like tabs/pages).
- `"popLayout"` — exiting items are popped from layout flow so siblings re-flow immediately (toast stacks, removing list items). Children must be capable of `layout`.
Require a unique, stable `key` on each child. To run exit on initial mount too, that is not needed; to suppress enter animation on first render set `<AnimatePresence initial={false}>`.
## Toast stack (popLayout + layout)
```jsx
function Toasts({ toasts }) {
return (
<div className="toast-region">
<AnimatePresence mode="popLayout">
{toasts.map((t) => (
<motion.div
key={t.id}
layout
initial={{ opacity: 0, y: 24, scale: 0.9 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.15 } }}
transition={{ type: "spring", stiffness: 500, damping: 40 }}
>
{t.message}
</motion.div>
))}
</AnimatePresence>
</div>
);
}
```
`layout` makes remaining toasts slide up smoothly when one is dismissed.
## Magic-move / shared-element layout
```jsx
function Gallery() {
const [active, setActive] = useState(null);
return (
<>
<div className="grid">
{photos.map((p) => (
<motion.img key={p.id} layoutId={`photo-${p.id}`} src={p.thumb}
onClick={() => setActive(p)} />
))}
</div>
<AnimatePresence>
{active && (
<motion.div className="backdrop" onClick={() => setActive(null)}
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
<motion.img layoutId={`photo-${active.id}`} src={active.full} />
</motion.div>
)}
</AnimatePresence>
</>
);
}
```
Matching `layoutId` makes the thumbnail visually fly to the lightbox and back.
## Drag-to-reorder list
`Reorder` handles pointer drag, axis locking, and live reordering with layout animation built in.
```jsx
function SortableList({ items, setItems }) {
return (
<Reorder.Group axis="y" values={items} onReorder={setItems}>
{items.map((item) => (
<Reorder.Item key={item} value={item}
whileDrag={{ scale: 1.03, boxShadow: "0 8px 24px rgba(0,0,0,.18)" }}>
{item}
</Reorder.Item>
))}
</Reorder.Group>
);
}
```
For a dedicated drag handle, use `useDragControls`:
```jsx
const controls = useDragControls();
<Reorder.Item value={item} dragListener={false} dragControls={controls}>
<span className="handle" onPointerDown={(e) => controls.start(e)}>⠿</span>
{item.label}
</Reorder.Item>
```
## Drag with constraints and elastic
```jsx
const ref = useRef(null);
<div ref={ref} className="bounds">
<motion.div drag dragConstraints={ref} dragElastic={0.2}
dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }} />
</div>
```
`dragElastic` (0–1) controls how far past constraints it can be pulled; `dragSnapToOrigin` returns it on release.
## Gesture composition (like button)
```jsx
function Like() {
const [liked, setLiked] = useState(false);
return (
<motion.button onClick={() => setLiked((v) => !v)} whileTap={{ scale: 0.85 }}>
<motion.span
animate={liked ? { scale: [1, 1.4, 1], color: "#ef4444" } : { scale: 1, color: "#9ca3af" }}
transition={{ duration: 0.35, ease: "easeOut" }}
>♥</motion.span>
</motion.button>
);
}
```
Arrays of values (`scale: [1, 1.4, 1]`) are keyframes; control their spacing with `times: [0, 0.6, 1]`.
## Respecting reduced motion
```jsx
function Panel() {
const reduce = useReducedMotion();
return (
<motion.div
initial={reduce ? false : { opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
/>
);
}
```
Wrap an app in `<MotionConfig reducedMotion="user">` to globally strip transform/layout animations for users who prefer reduced motion while keeping opacity.
## Performance notes
- Prefer `transform`/`opacity`; Framer Motion already uses transforms for `x/y/scale/rotate`.
- For frequently-updated values (cursor follow, scroll), use `useMotionValue` + `useSpring` instead of React state to avoid re-renders.
- `layout` is powerful but measure-heavy; avoid putting it on hundreds of simultaneously-animating nodes.
---
Tune the timing and easing and a micro-interaction feels effortless. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=micro-interaction)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
@@ -1,218 +0,0 @@
---
name: page-transition-animation
description: This skill should be used when the user asks to "animate page or route transitions", "add a page transition or crossfade between views", "animate route changes in Next.js App Router", "use the View Transitions API", "AnimatePresence exit doesn't fire on navigation", or "Framer Motion exit animation not working / exit animation before unmount in Next.js". Covers enter/exit page-transition animation with the View Transitions API and Framer Motion, for Next.js App Router and general SPA routing.
version: 0.1.0
---
# Page Transition Animation (Next.js App Router)
Implement page enter/exit transitions in the Next.js **App Router**, and fix the single most common failure: **Framer Motion `AnimatePresence` exit animations never fire on navigation**. The reason is structural — in the App Router, when navigating, Next.js unmounts the old route's content and mounts the new one almost immediately. `AnimatePresence` can only animate an exit if the *exiting element stays mounted* under a *persistent* `AnimatePresence` wrapper long enough to run the animation. Because the router swaps children out from under it, the exit is skipped. Two approaches solve this: a pathname-keyed `AnimatePresence` with the **FrozenRouter** pattern, or the **View Transitions API** (native / `next-view-transitions`).
## When to use
Use when adding animated page transitions in a Next.js App Router app, when a Framer Motion `exit` prop does nothing on route change, when an old page disappears instantly instead of animating out, when choosing between Framer Motion and the View Transitions API for Next.js, or when debugging why `AnimatePresence` won't animate between routes.
## Why exit doesn't fire (the core problem)
`AnimatePresence` detects removal of a *direct keyed child*. On App Router navigation:
1. The wrapper must persist across the navigation. If `AnimatePresence` lives in a component that itself unmounts, there is nothing left to run the exit.
2. The child's `key` must change per route so AnimatePresence sees "old removed, new added".
3. During the brief overlap, the *outgoing* subtree must still render its old content — but the App Router has already swapped the route context, so the outgoing tree would otherwise render the *new* page's data. This is what **FrozenRouter** fixes.
## Solution A: template.tsx + keyed AnimatePresence + FrozenRouter
`template.tsx` is the App Router's purpose-built hook for this: unlike `layout.tsx` (which persists), a **template remounts on every navigation**, giving each route a fresh instance — ideal for per-route enter animations. Combine it with a pathname-keyed `AnimatePresence` and FrozenRouter for clean exit + enter.
```tsx
// app/template.tsx
'use client';
import { AnimatePresence } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { FrozenRouter } from './frozen-router';
import { PageTransition } from './page-transition';
export default function Template({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
return (
<AnimatePresence mode="wait" initial={false}>
{/* key on pathname so AnimatePresence sees old removed / new added */}
<PageTransition key={pathname}>
{/* FrozenRouter keeps the OUTGOING tree rendering its old content
while it animates out */}
<FrozenRouter>{children}</FrozenRouter>
</PageTransition>
</AnimatePresence>
);
}
```
```tsx
// app/page-transition.tsx
'use client';
import { motion } from 'framer-motion';
export function PageTransition({ children }: { children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -12 }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
>
{children}
</motion.div>
);
}
```
```tsx
// app/frozen-router.tsx
'use client';
import { useContext, useRef } from 'react';
import {
LayoutRouterContext,
} from 'next/dist/shared/lib/app-router-context.shared-runtime';
// Freezes the router context so the exiting page keeps rendering its
// OWN content during the exit animation instead of the next route's.
export function FrozenRouter({ children }: { children: React.ReactNode }) {
const context = useContext(LayoutRouterContext ?? {});
const frozen = useRef(context).current;
return (
<LayoutRouterContext.Provider value={frozen}>
{children}
</LayoutRouterContext.Provider>
);
}
```
How it fits together:
- `mode="wait"` makes AnimatePresence fully finish the exit before mounting the new page. (Use the default mode if enter/exit should overlap/crossfade.)
- `initial={false}` skips the enter animation on first load (optional).
- `key={pathname}` is what makes AnimatePresence treat each route as a distinct presence.
- `FrozenRouter` snapshots `LayoutRouterContext` so the outgoing subtree renders the *previous* route's content throughout the exit, instead of flashing the new route's content. Without it, exit either skips or shows the wrong content.
Note: `LayoutRouterContext` is a Next.js internal; its import path can change between Next versions. If the import breaks after an upgrade, that path is the thing to update.
## Solution B: native View Transitions API
The View Transitions API animates between two DOM states with the browser capturing before/after snapshots — no per-element exit components.
```css
/* globals.css */
@view-transition { navigation: auto; } /* opt MPA-style in (where supported) */
::view-transition-old(root) { animation: fade 0.25s both reverse; }
::view-transition-new(root) { animation: fade 0.25s both; }
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
```
For SPA-style App Router navigations, wrap the router update:
```ts
if (document.startViewTransition) {
document.startViewTransition(() => router.push(href));
} else {
router.push(href);
}
```
### next-view-transitions library
`next-view-transitions` integrates the View Transitions API with the App Router's client navigation so it works out of the box:
```tsx
// app/layout.tsx
import { ViewTransitions } from 'next-view-transitions';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ViewTransitions>
<html lang="en"><body>{children}</body></html>
</ViewTransitions>
);
}
```
```tsx
// use the library's Link instead of next/link
import { Link } from 'next-view-transitions';
<Link href="/about">About</Link>;
```
Choose View Transitions for simple cross-page fades/morphs and shared-element transitions with minimal JS; choose Framer Motion when fine-grained, orchestrated, interruptible, or staggered exit animations are needed. View Transitions API browser support is still uneven, so provide a graceful fallback (the `if (document.startViewTransition)` guard).
## AnimatePresence debug checklist
When exit still won't fire, verify in order:
1. **Wrapper stays mounted.** `AnimatePresence` must live in something persistent — ideally `template.tsx`, or a layout-level client component — not inside the page that's unmounting.
2. **Stable, changing key.** The animated child needs `key={pathname}` (or similar) so removal is detected. No key, or a key that doesn't change → no exit.
3. **Direct motion descendant.** The element with the `exit` prop must be a `motion.*` component and a child of `AnimatePresence` (a non-motion wrapper in between can block detection).
4. **`mode="wait"`** if old and new should not overlap; without it both render simultaneously and may jump.
5. **FrozenRouter present** if the outgoing page flashes the new route's content during exit.
6. **`'use client'`** on every file using AnimatePresence/usePathname/motion.
7. **Single child at a time** under `mode="wait"` — AnimatePresence expects one keyed presence to swap.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
The real target is a Next.js app, but to *prove the transition shape* (the enter/exit curve, direction, crossfade) you can ship **one HTML file that opens directly in a browser** — two stub "pages" you toggle, animated with `motion` from CDN or the native View Transitions API. One file is the right tier for validating motion before wiring the router; don't stand up Next just to eyeball a fade.
**Output contract:**
- One `.html` file: two view stubs and a toggle, animated with either an inline `<script type="module">` importing `motion`/React from CDN, or `document.startViewTransition` + `::view-transition-*` CSS.
- A way to freeze the **resolved end state** — a route transition is state-driven (which view, mid-swap), so screenshot the state, not a clock.
**Seek harness — pin a transition phase.** `?view=b` mounts the destination view (or `?phase=exit` to hold the outgoing tree mid-animation) so a screenshot lands on a settled phase:
```html
<script>
const p = new URLSearchParams(location.search);
document.documentElement.dataset.view = p.get("view") || "a"; // CSS/React keys off this
// Framer Motion: set the controlled key/route from ?view; for mode="wait" the resolved end is the new page
// View Transitions: screenshot the END state (snapshots are transient); or pause via emulate slow animations
window.__ready = true;
</script>
```
**Verify loop — render → set phase → screenshot → check:** open source, mid, and destination (`?view=a`, `?phase=exit`, `?view=b`), screenshot each, and check **fidelity** (exit actually runs, direction/crossfade matches the brief, no `mode="wait"` lag) plus **artifacts** (outgoing tree flashing the new page's content, double-mount, FOUC, jank). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/transition.html?view=b" dest.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN `motion`/React (if used) resolves, `startViewTransition` guarded.
2. The `?view=`/`?phase=` freeze lands a deterministic transition phase.
3. Screenshotted at source / mid / destination — matches the brief, no content flash or skipped exit.
4. `prefers-reduced-motion` honored — slide/translate dropped to a short crossfade.
5. Easing is intentional — entrances ease-out, exits ease-in, durations ~0.2–0.4s (not laggy under `mode="wait"`).
## Quick reference
| Need | Approach |
|---|---|
| Per-route enter animation | `app/template.tsx` (remounts each nav) |
| Exit animation on nav | keyed `AnimatePresence mode="wait"` + FrozenRouter |
| Outgoing page shows old content | FrozenRouter (snapshot `LayoutRouterContext`) |
| Detect route change | `usePathname()` as the `key` |
| Simple cross-page fade/morph | View Transitions API / next-view-transitions |
| Shared element transition | `view-transition-name` CSS |
| Skip first-load animation | `initial={false}` |
## Gotchas
- `layout.tsx` persists and will NOT remount per route — use `template.tsx` for per-route enter animations.
- Omitting FrozenRouter makes the exiting page render the *new* route's content mid-animation (visible flash) or skip exit entirely.
- `LayoutRouterContext` import path is a Next internal; it may change across versions — first thing to fix after an upgrade.
- Without `key={pathname}`, AnimatePresence sees the same child and never triggers exit.
- `mode="wait"` waits for exit before enter; overusing it on slow exits makes navigation feel laggy — tune durations (~0.2-0.4s).
- View Transitions API lacks full browser support; always guard `document.startViewTransition`.
- Every transition file needs `'use client'`; server components can't use AnimatePresence/usePathname.
## Reference files
- `references/full-examples.md` — directional/slide transitions, shared-element View Transitions with `view-transition-name`, a non-`mode="wait"` crossfade variant, loading-state transitions with `loading.tsx`, and a complete working App Router folder layout.
@@ -1,176 +0,0 @@
# Full examples and variants
## Working folder layout
```
app/
layout.tsx # persistent shell (html/body, providers)
template.tsx # remounts per route -> hosts AnimatePresence
page-transition.tsx # motion wrapper (enter/exit variants)
frozen-router.tsx # FrozenRouter (LayoutRouterContext snapshot)
page.tsx # home
about/page.tsx
globals.css
```
## Directional slide transitions
Track direction by comparing route depth or a route order map, then feed it to variants.
```tsx
// app/page-transition.tsx
'use client';
import { motion } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { useRef } from 'react';
const order = ['/', '/about', '/work', '/contact'];
export function PageTransition({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const prev = useRef(pathname);
const dir =
order.indexOf(pathname) > order.indexOf(prev.current) ? 1 : -1;
prev.current = pathname;
return (
<motion.div
custom={dir}
variants={{
initial: (d: number) => ({ opacity: 0, x: 40 * d }),
animate: { opacity: 1, x: 0 },
exit: (d: number) => ({ opacity: 0, x: -40 * d }),
}}
initial="initial"
animate="animate"
exit="exit"
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
>
{children}
</motion.div>
);
}
```
## Crossfade variant (no mode="wait")
Omit `mode="wait"` so old and new overlap. Stack them absolutely to avoid layout jump.
```tsx
// app/template.tsx
'use client';
import { AnimatePresence, motion } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { FrozenRouter } from './frozen-router';
export default function Template({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
return (
<AnimatePresence initial={false}>
<motion.div
key={pathname}
style={{ gridArea: '1 / 1' }} // overlap in a 1-cell grid parent
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.35 }}
>
<FrozenRouter>{children}</FrozenRouter>
</motion.div>
</AnimatePresence>
);
}
```
Wrap the template output's parent in `display: grid` so both stacked children occupy `grid-area: 1 / 1`.
## Shared-element transition (View Transitions API)
Give the same logical element the same `view-transition-name` on both pages; the browser morphs between them.
```tsx
// list page
<img src={cover} style={{ viewTransitionName: `cover-${id}` }} />
// detail page
<img src={cover} style={{ viewTransitionName: `cover-${id}` }} />
```
```css
::view-transition-old(root),
::view-transition-new(root) { animation-duration: 0.3s; }
/* the named element animates automatically between its two positions */
```
With `next-view-transitions`, use its `<Link>` and the morph happens on navigation. Each `view-transition-name` must be unique on the page at a time.
## loading.tsx + transitions
`loading.tsx` shows an instant Suspense fallback during server work. To animate it, make the fallback a motion component; it mounts/unmounts within the same template-driven AnimatePresence flow.
```tsx
// app/work/loading.tsx
'use client';
import { motion } from 'framer-motion';
export default function Loading() {
return (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
Loading…
</motion.div>
);
}
```
## Reduced-motion
```tsx
'use client';
import { useReducedMotion, motion } from 'framer-motion';
export function PageTransition({ children }: { children: React.ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.div
initial={reduce ? false : { opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
exit={reduce ? { opacity: 1 } : { opacity: 0, y: -12 }}
transition={{ duration: reduce ? 0 : 0.3 }}
>
{children}
</motion.div>
);
}
```
For the View Transitions API, gate with CSS:
```css
@media (prefers-reduced-motion: reduce) {
::view-transition-old(root),
::view-transition-new(root) { animation: none; }
}
```
## FrozenRouter import note across versions
The internal context import has shifted across Next versions, e.g.:
```ts
// commonly:
import { LayoutRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';
```
If an upgrade breaks the import, search `node_modules/next/dist/shared/lib/` for `app-router-context` and update the path. Because it is internal, pin awareness of this in any upgrade checklist.
## Framer Motion vs View Transitions decision
| Factor | Framer Motion | View Transitions API |
|---|---|---|
| Browser support | Broad (JS lib) | Uneven; needs fallback |
| Orchestration/stagger | Excellent | Limited |
| Interruptible exits | Yes | Limited |
| Shared element morph | Manual (layoutId) | Native, simple |
| Bundle cost | Adds library | Minimal/native |
| Setup complexity | Medium (FrozenRouter) | Low (next-view-transitions) |
---
Freeze the outgoing route and exit transitions finally fire as intended. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=page-transition-animation)** — the AI motion agent for editable, on-brand motion graphics.
+24
View File
@@ -0,0 +1,24 @@
# Short-Form Video
Engineer a 9:16 video that survives the swipe. Short-form is a retention machine, not a small launch film: a hook that earns the first second, pattern interrupts that reset attention every few seconds, and often a loop that buys watch-time past 100%. The craft is timing, not polish. For creators making Reels, TikToks, and YouTube Shorts (7–60s, vertical).
## When it activates
- "Make a Reels/TikTok/YouTube Shorts video" or "build a short-form video template."
- "Write a hook for a short" or "fix the first 3 seconds."
- "Edit for retention," "add pattern interrupts," or "pace cuts for a vertical video."
- "Make a video loop" or "set up 9:16 safe areas."
## Example prompts
- "Build a reusable 9:16 short-form template — one design, many topics."
- "Fix the drop-off in this Reel: tighten pacing and add pattern interrupts."
- "Write three hook options for a 30-second educational short."
## What's inside
- `SKILL.md` — the retention arc, hook grammar, and pacing rules.
- `references/retention-pacing.md` — deeper guidance on retention editing and pacing.
---
Part of **[Short-Form Video Skills](../../)** · Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=tiktok-video-skills&utm_content=skill_footer&utm_term=short-form-video)** — the AI motion agent for editable, on-brand motion graphics.
+155
View File
@@ -0,0 +1,155 @@
---
name: short-form-video
description: This skill should be used when the user asks to "make a Reels/TikTok/YouTube Shorts video", "build a short-form video template", "write a hook for a short", "edit for retention", "add pattern interrupts", "make a video loop", "fix the first 3 seconds", "pace cuts for a vertical video", or "set up 9:16 safe areas". Covers the hook→retention→loop grammar of vertical short-form (distinct from a launch hype film).
version: 0.1.0
---
# Short-Form Video
Engineer a 9:16 video that survives the swipe. Short-form is not a small launch film — it is a retention machine: a hook that earns the first second, pattern interrupts that reset attention every few seconds, and often a loop that buys watch-time past 100%. The craft is timing, not polish.
## When to use
- Reels / TikTok / YouTube Shorts (7–60s, vertical 9:16).
- Retention editing: fixing drop-off, adding pattern interrupts, tightening pacing.
- Hooks, seamless loops, repeatable short-form templates (one design, many topics).
## Story structure (the retention contract)
Short-form storytelling is a contract with the viewer's thumb: every second must re-earn the next one. The narrative is shaped *backwards from the retention curve*, not forwards from an intro. Lock these before touching the timeline.
- **One idea per video.** A short carries exactly one payoff. A second idea splits attention and the curve sags in the middle — make it a second video instead. If you can't name the single takeaway in a sentence, you don't have a short yet.
- **Open a loop in the first ~3s, close it last.** The hook poses a question or gap (the open loop); the payoff answers it. The viewer stays because the loop is open — so never answer it early, and never bury the payoff under setup.
- **No dead air.** Every beat either advances the idea or resets attention. Cut anything that does neither. Silence, slow ramps, throat-clearing intros ("hey guys, in this video…") are where viewers swipe.
- **Why the curve, not the cut, is the unit of work.** The algorithm distributes whatever holds the per-second retention curve flat; a "good" edit that flattens the curve loses to an ugly one that keeps it up. You are editing the *curve*, and the hook gates everything after it — fix it first.
The narrative spine (the `Hook → Setup → Body → Payoff/loop` arc is budgeted in the table below):
| Move | Story job | Failure if missed |
|---|---|---|
| Hook | Open the loop; promise the payoff | Swipe in first 3s |
| Tension hold | Keep the gap open through the body | Flat middle, mid-drop |
| Payoff | Close the loop — the one idea, delivered | "Wasted my time," no share |
| Loop / CTA | Feed back to frame 0, or one clear ask | No re-watch, no action |
(`The retention arc` table below assigns seconds to each move; this section is the narrative logic and ordering behind it. `Hook grammar` lists the hook archetypes.)
## The one metric that drives everything
**Retention, not production value.** The algorithm distributes whatever holds viewers; ~87% decide to stay or swipe inside 3 seconds, and the threshold for distribution sits near **70%+ average view-through** (Shorts ~73%, TikTok ~78%, Reels ~65%). Every decision below trades against that curve. A flawless shot that bores at 0:04 loses to an ugly one that holds.
## The retention arc
| Beat | Job | Budget (of a 20s short) |
|---|---|---|
| Hook (0–1s) | One frame + one line that creates an open loop | 0–1s |
| Setup | Pay off *why watch* — promise, stakes, or the gap | 1–4s |
| Body | Deliver value in beats; one idea per beat | 4–17s |
| Payoff / loop | Close the loop — or feed it back to frame 0 | 17–20s |
Scale the *body*, never the hook. A 60s short has a longer body and more beats — the same 1-second hook.
## Hook grammar (first ~1s)
The hook is a sentence + a visual that opens a curiosity gap the brain needs closed. Pick one pattern and commit:
| Hook type | Shape | Best for |
|---|---|---|
| Open loop | "The reason your X keeps Y…" (answer delayed) | most content |
| Direct promise | "3 ways to ___ in 30 seconds" | educational / listicle |
| Pattern interrupt | snap-zoom / whip-pan / visual mismatch in frame 1 | entertainment |
| Negation | "Stop doing ___" / "You're ___ wrong" | strong opinions |
Two rules: the hook line is **on-screen as text by frame 1** (85% watch muted), and the most striking *visual* is also the first frame — never a slow ramp-in. Hold a strong opening frame; do not fade up from black.
## Pattern interrupts & cut rhythm
A pattern interrupt is any change that resets attention: a hard cut, zoom punch, b-roll insert, sound effect, caption pop, or angle change. In short-form, density is high — a *visual change every ~2–4 seconds*; videos with an interrupt roughly every 4s hold ~58% vs ~41% for a static talking head. The killer is a flat middle: TikTok throttles distribution when the watch-through curve flattens, so never stitch the body from low-energy takes.
```js
// Drive every interrupt off the FRAME, not wall-clock — renders deterministically.
import { useCurrentFrame } from "remotion";
const fps = 30;
const cuts = [0, 1.2, 3.0, 5.4, 8.0, 11.2, 14.0]; // seconds — uneven on purpose
const frame = useCurrentFrame();
const shot = cuts.findIndex((t, i) => frame < (cuts[i + 1] ?? Infinity) * fps);
```
Vary the interval — a metronome reads as boredom; uneven cuts read as momentum. A punch-in zoom is the cheapest interrupt that needs no new footage:
```jsx
import { useCurrentFrame, interpolate, spring, useVideoConfig } from "remotion";
const PunchIn = ({ at, children }) => {
const frame = useCurrentFrame(); const { fps } = useVideoConfig();
const s = spring({ frame: frame - at * fps, fps, config: { damping: 12, stiffness: 200 } });
const scale = interpolate(s, [0, 1], [1, 1.12]); // snap to 112% on the beat
return <div style={{ transform: `scale(${scale})`, transformOrigin: "50% 45%" }}>{children}</div>;
};
```
## Captions
Most viewers watch muted, so on-screen captions are not optional — they carry the content and double as a pattern interrupt when each phrase pops in. Keep 4–7 words per line, high contrast, inside the safe area. **Do not re-implement caption animation here** — use the `caption-animation` skill for word-by-word timing, karaoke highlight, and styling; this skill only places captions on the retention timeline and inside the 9:16 safe zone.
## Loops & re-watch
A seamless loop counts each re-watch as fresh watch-time — a clean 8s loop watched 3× is 300% view-through, the strongest possible signal. Two techniques: match the **last frame to the first** (same composition, position, color) so the cut is invisible, and write a **sentence loop** — phrase the hook so the payoff feeds back into frame 0 ("…and that's why I never — " → loops to the start). Best length for re-watch is ~7–15s.
## 9:16 safe areas
Compose inside the universal safe zone so platform UI never covers text or faces.
| Zone | Pixels (1080×1920) | Avoid |
|---|---|---|
| Universal safe (all platforms) | center **900×1400** | anything critical outside it |
| Top | keep clear ~120px | profile / sound UI |
| Bottom | keep clear ~320px | captions, CTA, hashtags, audio bar |
| Right | keep clear ~120px | like / comment / share rail |
Put the hook text and key subject in the center 900×1400 box. Reserve the bottom ~320px even if it looks empty in the editor — that is where the platform paints its own captions and buttons.
## Output checklist
- Hook line is on-screen text by frame 1; strongest visual is the first frame (no fade-up).
- One open loop / promise set in the first ~4s.
- A visual pattern interrupt every ~2–4s; intervals uneven; no flat middle.
- Captions present (via `caption-animation`), 4–7 words, inside safe area.
- Loop closed — matched first/last frame or a sentence that feeds frame 0.
- Composed inside the 900×1400 center box; bottom 320px / top 120px / right 120px kept clear.
- Every animated value derived from `useCurrentFrame()` — no CSS/library timers.
## Deliver & verify (rendered stills → MP4)
> **Packaged helper** (`scripts/`): tile your stills with `scripts/contact-sheet.sh sheet.png f-hook.png f-mid.png f-end.png`, then assert the encode with `scripts/probe-mp4.sh out.mp4 [WxH] [fps]`. See `scripts/README.md`.
The short ships as a Remotion composition (`<Composition>` + zod `schema` + `defaultProps`) — every cut, punch-in, and interrupt driven by `useCurrentFrame()`, never `Date.now()` / `Math.random()` / timers. Deliverable = `out/*.mp4` + the project (re-render per topic). 9:16 vertical (1080×1920) is the default.
**Verify loop — render stills → inspect → encode.** Three frames test the three things that make or break retention: the hook, the pacing, and the loop seam.
```bash
# Stills at hook / mid-body / last frame — WITH SHIPPED PROPS (the real topic, not defaults)
npx remotion still Short out/f-hook.png --frame=10 --props='{"topic":"...","hook":"..."}' # ~first 3s reads instantly
npx remotion still Short out/f-mid.png --frame=N --props='{"topic":"...","hook":"..."}'
npx remotion still Short out/f-end.png --frame=L --props='{"topic":"...","hook":"..."}' # L = durationInFrames-1
# Inspect each PNG:
# - HOOK frame (~frame 0-ish / first 3s): hook line is on-screen text and reads instantly; strongest visual already up (no fade-up)
# - LOOP seam: compare f-hook(frame 0) vs f-end(last frame) — same composition/position/color for an invisible loop cut
# - 9:16 safe area: hook + key subject inside the center 900x1400 box; clear of top ~12%, bottom ~20-35% (captions/CTA/audio), right action rail
npx remotion render Short out/short.mp4 --props='{"topic":"...","hook":"..."}' # encode once stills verify
npx remotion render Short out/demo.gif --codec=gif # README proof clip
```
**Per topic / batch**: verify ONE topic via stills *before* rendering all of them. Use `npx remotion compositions` for `durationInFrames`/`fps` to pick the mid + last frames.
**Before you finish:**
1. Stills render cleanly at the hook, mid, and last frame — no errors.
2. The hook frame reads instantly (on-screen text + strongest visual up front, no fade-up); first vs last frame match for a clean loop seam.
3. Hook + subject + captions sit inside the 9:16 center 900×1400 safe box at every checked frame.
4. Frame-driven only — no `Date.now()` / `Math.random()` / timers; cuts uneven, no flat middle.
5. A real topic's shipped props (not `defaultProps`) render correctly; MP4 encoded, GIF optional.
## Reference files
- `references/retention-pacing.md` — a complete runnable Remotion `<Short>` composition: a frame-driven shot scheduler with uneven cuts, the PunchIn pattern interrupt, an on-screen hook, a 9:16 safe-area overlay, and a seamless first/last-frame loop. Plus a hook-pattern library, a retention-curve debugging method, per-platform safe-zone maps, and the template×topic batch-render pattern.
@@ -0,0 +1,209 @@
# Retention Pacing — Short-Form Video Reference
Deep reference for the `short-form-video` skill: a full runnable Remotion short, a hook library, a retention-debugging method, per-platform safe zones, and batch output. All timing is frame-driven so renders are deterministic.
## 1. A complete `<Short>` composition
One self-contained vertical short: frame-driven shot scheduler with uneven cuts, a punch-in pattern interrupt, an on-screen hook, a 9:16 safe-area overlay (dev only), and a seamless loop. Topic content is a prop, so the same file renders many shorts.
```tsx
// Short.tsx — 1080×1920, 30fps. Register at 600 frames (20s) for a clean loop.
import {
AbsoluteFill, useCurrentFrame, useVideoConfig,
interpolate, spring, Sequence, Img,
} from "remotion";
type Beat = { at: number; text: string; src?: string }; // at = seconds
export type ShortProps = {
hook: string; // on-screen by frame 1
beats: Beat[]; // body, one idea each
loopText: string; // sentence that feeds back to frame 0
};
// --- frame-driven shot scheduler: uneven cuts read as momentum ---
const useShot = (cuts: number[]) => {
const { fps } = useVideoConfig();
const frame = useCurrentFrame();
let i = 0;
for (let k = 0; k < cuts.length; k++) if (frame >= cuts[k] * fps) i = k;
const startF = cuts[i] * fps;
const endF = (cuts[i + 1] ?? cuts[i] + 2) * fps;
const local = (frame - startF) / (endF - startF); // 0→1 within shot
return { index: i, local, startF };
};
// --- punch-in: the cheapest pattern interrupt, snaps on the cut ---
const PunchIn: React.FC<{ startF: number; to?: number; children: React.ReactNode }> = ({
startF, to = 1.1, children,
}) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const s = spring({ frame: frame - startF, fps, config: { damping: 13, stiffness: 220 } });
const scale = interpolate(s, [0, 1], [1, to]);
return <AbsoluteFill style={{ transform: `scale(${scale})`, transformOrigin: "50% 45%" }}>{children}</AbsoluteFill>;
};
// --- hook: text present from frame 0, micro-overshoot, no fade-up ---
const Hook: React.FC<{ text: string }> = ({ text }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const pop = spring({ frame, fps, config: { damping: 9, stiffness: 260 } });
const scale = interpolate(pop, [0, 1], [0.9, 1]);
return (
<div style={{
position: "absolute", top: 360, left: 90, right: 90, // inside 900-wide safe box
transform: `scale(${scale})`, transformOrigin: "0 0",
fontFamily: "Inter, sans-serif", fontWeight: 800, fontSize: 76, lineHeight: 1.05,
color: "#fff", textShadow: "0 4px 24px rgba(0,0,0,.55)",
}}>{text}</div>
);
};
export const Short: React.FC<ShortProps> = ({ hook, beats, loopText }) => {
const { fps, durationInFrames } = useVideoConfig();
const frame = useCurrentFrame();
const cuts = [0, ...beats.map((b) => b.at)]; // hook shot + one per beat
const { index, startF } = useShot(cuts);
const current = index === 0 ? null : beats[index - 1];
// seamless loop: match the LAST 0.5s back toward the opening frame
const tailF = durationInFrames - frame;
const loopFade = interpolate(tailF, [0, fps * 0.5], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
return (
<AbsoluteFill style={{ backgroundColor: "#0b0b0f" }}>
<PunchIn startF={startF}>
{current?.src && <Img src={current.src} style={{ width: "100%", height: "100%", objectFit: "cover" }} />}
</PunchIn>
{index === 0 && <Hook text={hook} />}
{/* body caption — placement only; styling/word-timing belongs to caption-animation */}
{current && (
<div style={{
position: "absolute", left: 90, right: 90, bottom: 380, // above the 320px bottom UI band
fontFamily: "Inter, sans-serif", fontWeight: 700, fontSize: 60, color: "#fff",
textAlign: "center", textShadow: "0 3px 18px rgba(0,0,0,.6)",
}}>{current.text}</div>
)}
{/* loop sentence rises as the clip ends, easing the eye back to frame 0 */}
<div style={{
position: "absolute", left: 90, right: 90, bottom: 380, opacity: 1 - loopFade,
fontFamily: "Inter, sans-serif", fontWeight: 800, fontSize: 64, color: "#fff", textAlign: "center",
}}>{loopText}</div>
<SafeZone />{/* remove for final render */}
</AbsoluteFill>
);
};
```
Register it with a duration that *is* the loop length:
```ts
// Root.tsx
import { Composition } from "remotion";
import { Short } from "./Short";
export const Root = () => (
<Composition
id="Short" component={Short}
durationInFrames={600} fps={30} width={1080} height={1920}
defaultProps={{
hook: "You're editing Shorts wrong —",
beats: [
{ at: 1.2, text: "Cut every 2–4 seconds", src: "b1.jpg" },
{ at: 4.0, text: "Never on a fixed grid", src: "b2.jpg" },
{ at: 7.5, text: "Kill the flat middle", src: "b3.jpg" },
{ at: 11.0, text: "Match last frame to first", src: "b4.jpg" },
],
loopText: "…and that's why mine loop forever",
}}
/>
);
```
## 2. The 9:16 safe-area overlay (dev-only)
Render this on top while editing; delete it before the final export.
```tsx
import { AbsoluteFill } from "remotion";
export const SafeZone: React.FC = () => (
<AbsoluteFill style={{ pointerEvents: "none" }}>
{/* universal safe box: center 900×1400 in 1080×1920 */}
<div style={{ position: "absolute", left: 90, top: 260, width: 900, height: 1400, outline: "2px dashed #39d", opacity: .6 }} />
{/* platform UI bands to keep clear */}
<div style={{ position: "absolute", top: 0, left: 0, right: 0, height: 120, background: "rgba(255,0,0,.12)" }} />
<div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 320, background: "rgba(255,0,0,.12)" }} />
<div style={{ position: "absolute", bottom: 320, top: 120, right: 0, width: 120, background: "rgba(255,128,0,.10)" }} />
</AbsoluteFill>
);
```
## 3. Hook pattern library
The hook is a sentence that opens a gap the brain must close, plus the most striking frame as frame 0. Copyable shapes:
| Pattern | Template | Note |
|---|---|---|
| Open loop | "The real reason your ___ keeps ___ …" | answer withheld until payoff |
| Direct promise | "___ in 30 seconds, no ___ needed" | name the payoff + the timebox |
| Negation | "Stop ___. You're doing it backwards." | strong-opinion content |
| Pattern interrupt | snap-zoom / whip / hard visual mismatch | entertainment, no text needed |
| Stakes | "This ___ cost me $___ — don't repeat it" | story / case-study |
| Listicle | "3 ___ that ___ (the 3rd one ___ )" | tees up a forward reference |
Rules that matter more than the wording: (1) the hook text is on-screen by frame 1 — most viewers are muted; (2) frame 0 is the best frame, never a fade-up from black; (3) one gap only — stacking two hooks closes neither.
## 4. Retention-curve debugging
Treat the per-second retention graph (TikTok Analytics, YT Studio "Audience retention", Reels) as a profiler.
| Symptom on the curve | Likely cause | Fix |
|---|---|---|
| Cliff at 0:00–0:02 | weak hook / slow first frame | new hook line; cut the ramp-in; lead with the best frame |
| Steady gentle decline | normal — leave it | — |
| Flat-then-drop in the middle | low-energy body, cuts too sparse | add interrupts; tighten cut spacing to 2–4s |
| Bump back up near the end | viewers are looping | lean in — tighten the loop, shorten total length |
| Spike at one timestamp | a re-watched moment | front-load that beat or make it the hook |
Target ≥70% average view-through. Iterate the hook first — it moves the curve more than any other edit because it gates everything after it.
## 5. Per-platform safe zones
All on a 1080×1920 canvas. The universal box (center 900×1400) is the intersection; design inside it and one master fits every platform.
| Platform | Top clear | Bottom clear | Right clear | Notes |
|---|---|---|---|---|
| Universal (use this) | ~120px | ~320px | ~120px | center 900×1400 holds on all |
| TikTok | ~108px | ~320px | ~120px | caption + button rail at bottom-right |
| Instagram Reels | ~120px | ~310px | ~84px | audio bar + caption bottom |
| YouTube Shorts | ~120px | ~300px | ~60px | channel + subscribe bottom band |
| TikTok Ads | ~108px | ~370px | ~120px | extra room for the CTA button |
When unsure, design to the *largest* margin (TikTok Ads bottom 370px) and nothing ever clips.
## 6. Template × topic — batch output
The payoff of code-driven shorts: lock the design once, swap only the props, render N videos. Make topic content a prop (already done above), keep one theme object, and loop over JSON files.
```jsx
// theme.ts — one source of truth so 50 shorts stay on-brand
export const theme = { font: "Inter", hookSize: 76, bodySize: 60, bg: "#0b0b0f", fg: "#fff", accent: "#39d" };
```
```bash
# render the same Short template for every topic file in /topics
for f in topics/*.json; do
name=$(basename "$f" .json)
npx remotion render Short "out/$name.mp4" --props="$f"
done
```
Each `topics/*.json` is one `ShortProps` object (`hook`, `beats`, `loopText`). Keep the hook line, cut points, and loop sentence per-topic; everything else stays fixed so the series reads as one brand.
---
## Built by the team behind iart.ai
This skill is part of an open motion-graphics collection from iart.ai — the AI motion agent that turns data, scripts, and designs into editable motion graphics (Remotion → MP4). If you'd rather not hand-build this, iart.ai can batch-produce short-form videos from one template × data — change the text/data and re-export. → [iart.ai](https://iart.ai/?utm_source=github&utm_medium=reference&utm_campaign=tiktok-video-skills&utm_content=ref_footer&utm_term=short-form-video)
Whitespace-only changes.
-167
View File
@@ -1,167 +0,0 @@
---
name: svg-animation
description: This skill should be used when the user asks to "animate an SVG", "make a line draw itself on", "do a stroke draw-on / signature animation", "morph one shape into another", "move an element along a path", "animate an icon/logo", or "animate an SVG gradient or filter". Covers stroke-dashoffset draw-on, path morphing, motion-along-path, and animated icons/gradients/filters via CSS, SMIL, and GSAP.
version: 0.1.0
---
# SVG Animation
Crisp, lightweight, infinitely scalable vector motion — ideal for icons, illustrations, logos, and data marks. SVG can be animated three ways: CSS (declarative, simple), SMIL (`<animate>` inside the SVG), and JS (GSAP/Web Animations, for control and morphing). Choose per task; the techniques below say which.
## When to use
- Stroke "draw-on" of icons, illustrations, signatures, maps
- Shape/path morphing and animated icon state changes (menu ↔ close, play ↔ pause)
- Moving an element along a path (motion path)
- Animated gradients, filters (glow, displacement), and animated logos
## Core techniques
### Stroke draw-on (the staple)
Draw the dash array as long as the path, offset it fully (invisible), then animate the offset to 0.
```css
.path {
stroke-dasharray: var(--len);
stroke-dashoffset: var(--len);
animation: draw 1.4s ease forwards;
}
@keyframes draw { to { stroke-dashoffset: 0; } }
```
Getting the length:
- JS (most reliable): `const len = path.getTotalLength(); path.style.setProperty("--len", len);`
- No-JS trick: set `pathLength="1"` on the `<path>`, then `stroke-dasharray: 1; stroke-dashoffset: 1;` and animate to `0`. This normalizes any path to a 0–1 length so no measurement is needed.
Reverse (erase) by animating offset from 0 back to `len`. Stagger multiple paths with `animation-delay`. Direction of drawing follows the path's point order; reverse it in the editor or negate the offset sign if it draws "backwards".
### Morphing one path into another
Paths interpolate point-by-point, so a naive morph requires both `d` attributes to have the **same number and type of commands**. Two robust approaches:
- **GSAP MorphSVG** (free as of GSAP 3.12) — handles mismatched point counts automatically and finds a good mapping:
```js
gsap.registerPlugin(MorphSVGPlugin);
gsap.to("#start", { morphSVG: "#end", duration: 0.8, ease: "power2.inOut" });
// Convert any shape to a morph-able path:
MorphSVGPlugin.convertToPath("circle, rect, ellipse, line, polygon");
```
- **Flubber** (small standalone lib) — generates interpolators without GSAP, good with React/Framer Motion:
```js
import { interpolate } from "flubber";
const interpolator = interpolate(pathA, pathB, { maxSegmentLength: 2 });
// interpolator(0) === pathA, interpolator(1) === pathB; feed t into a tween.
```
For hand-authored morphs (icon toggles), keep both paths with identical command structure and animate `d` directly via Web Animations or CSS (`d` is animatable in modern browsers via `path("...")`).
### Motion along a path
- **GSAP MotionPath** (preferred — control, alignment, scrub):
```js
gsap.registerPlugin(MotionPathPlugin);
gsap.to("#rocket", {
duration: 4, repeat: -1, ease: "none",
motionPath: { path: "#track", align: "#track", autoRotate: true, alignOrigin: [0.5, 0.5] },
});
```
`autoRotate: true` orients the object to the path tangent; `align` makes coordinates relative to the path element.
- **SMIL** (no JS):
```svg
<path id="track" d="M10,80 C40,10 120,10 150,80" fill="none"/>
<circle r="6" fill="#3b82f6">
<animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
<mpath href="#track"/>
</animateMotion>
</circle>
```
- **CSS** offset-path (modern, declarative): `offset-path: path("M10,80 C..."); animation: move 3s linear infinite;` with `@keyframes move { to { offset-distance: 100%; } }` and `offset-rotate: auto`.
### Animated gradients and filters
Gradients: animate `gradientTransform` or stop offsets. A sheen sweep:
```svg
<linearGradient id="sheen">
<stop offset="0%" stop-color="#fff" stop-opacity="0"/>
<stop offset="50%" stop-color="#fff" stop-opacity=".8"/>
<stop offset="100%" stop-color="#fff" stop-opacity="0"/>
<animateTransform attributeName="gradientTransform" type="translate"
from="-1 0" to="1 0" dur="2s" repeatCount="indefinite"/>
</linearGradient>
```
Filters: animate `feDisplacementMap` `scale` for gooey/wobble, `feGaussianBlur` `stdDeviation` for focus pulls, or `feColorMatrix`/`feFlood` for glow. Filters are paint-heavy — animate sparingly and prefer `transform`/`opacity` where possible.
## Implementation choice (pick fast)
| Need | Use |
|------|-----|
| Single declarative draw/fade | CSS |
| Self-contained, no JS bundle | SMIL (`<animate*>` in the SVG) |
| Coordinated, scrubbable, scroll-tied | GSAP |
| Mismatched-point morph | GSAP MorphSVG or Flubber |
| Path following with rotation | GSAP MotionPath / CSS offset-path |
SMIL caveat: not supported in IE/old Edge and historically deprecation-flagged; for max reach or scroll-syncing, prefer CSS or JS. SMIL is still fine for self-contained icon assets in evergreen browsers.
## Authoring and optimization
- Build/clean with **SVGO**: keep `viewBox`, drop editor metadata, but disable `cleanupIds`/`removeViewBox` and any plugin that renames IDs you reference from CSS/JS/SMIL. Disable `mergePaths` and `convertShapeToPath` if you animate individual sub-paths or shapes.
- Inline the SVG in the DOM (not `<img src>`) so CSS/JS can reach its internals; `<img>`-embedded SVG can only self-animate via internal SMIL/CSS.
- Set explicit `viewBox` and avoid fixed `width`/`height` so the asset scales fluidly.
- For draw-on, ensure paths are actual strokes (`fill:none; stroke:...`), not filled outlines — dashoffset only affects strokes.
- Respect `prefers-reduced-motion`: gate looping/large motion; keep a static final state.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained icon/logo/draw-on the deliverable is **one HTML file that opens directly in a browser** — inline the SVG in the markup, drive the animation with one mechanism, no build step. One file is the right tier for a vector asset; don't reach for a bundler.
**Output contract:**
- One `.html` file: inline `<svg>`, plus CSS `@keyframes` / a `<script>` with GSAP from CDN / SMIL `<animate*>` — pick one driver.
- Include the seek harness matching that driver so any moment can be frozen for a screenshot.
**Seek harness — freeze an exact moment.** `?t=N` seeks and pauses so a screenshot lands on a still frame. Use the mechanism that matches how the SVG animates:
```html
<script>
const t = new URLSearchParams(location.search).get("t");
if (t !== null) {
const N = parseFloat(t);
// SMIL: pause the SVG's own clock and scrub it
const svg = document.querySelector("svg");
svg.pauseAnimations(); svg.setCurrentTime(N);
// CSS @keyframes draw-on: el.style.animationDelay=(-N)+"s"; el.style.animationPlayState="paused";
// GSAP timeline: tl.pause(); tl.seek(N);
}
window.__ready = true;
</script>
```
**Verify loop — render → freeze → screenshot → check:** open the file at start / mid / end (`?t=0`, `?t=<dur/2>`, `?t=<dur>`), screenshot each, and check **fidelity** (stroke draws in the right direction, morph endpoints clean) plus **artifacts** (path clipped by `viewBox`, stroke vanishing from a stale dashoffset, FOUC, jank at the morph seam). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/icon.html?t=0.7" frame-mid.png
```
**Before you finish:**
1. Opens standalone — no console errors, inline SVG reachable, CDN (if any) loads.
2. The seek mechanism for your driver freezes a deterministic frame.
3. Screenshotted at start / mid / end — matches the brief, no clipping or off-`viewBox` strokes.
4. `prefers-reduced-motion` honored — looping/large motion gated, static final state kept.
5. Easing is intentional — `ease`/GSAP ease chosen on purpose, no accidental `linear` draw-on.
## Reference files
- `references/svg-techniques.md` — full dashoffset math and `getTotalLength` gotchas, the `pathLength="1"` normalization, GSAP MorphSVG vs Flubber decision guide with code, an icon-toggle morph (hamburger↔close), MotionPath/offset-path details, SMIL-vs-CSS-vs-JS tradeoffs, and an SVGO config tuned for animation.
@@ -1,214 +0,0 @@
# SVG Animation Techniques (detailed)
## 1. Stroke draw-on: the math
`stroke-dasharray` defines a dash pattern; `stroke-dashoffset` shifts where the pattern starts. Set the dash equal to the whole path length and offset it by that same length → the visible dash is pushed entirely off the path (invisible). Animating offset to 0 slides the dash into view, revealing the stroke progressively.
```
visible fraction = 1 - (dashoffset / pathLength)
```
So offset = length → 0% drawn; offset = 0 → 100% drawn; offset = length/2 → 50% drawn (useful for scroll mapping: `offset = length * (1 - progress)`).
### getTotalLength gotchas
```js
const path = document.querySelector("#sig");
const len = path.getTotalLength(); // returns user units of the path geometry
path.style.strokeDasharray = len;
path.style.strokeDashoffset = len;
requestAnimationFrame(() => { // next frame so the transition has a start value
path.style.transition = "stroke-dashoffset 1.6s ease";
path.style.strokeDashoffset = "0";
});
```
- `getTotalLength()` measures the path's own coordinate system, ignoring CSS transforms/scaling — which is what you want for dasharray.
- It only works on geometry elements (`path, line, polyline, polygon, circle, ellipse, rect`). For `<text>` draw-on you must convert text to paths first.
- Rounding: browsers can clip the last sub-pixel; pad slightly (`len + 1`) if the end never fully closes.
- Compound paths (multiple `M` subpaths in one `d`) draw all subpaths simultaneously. Split into separate `<path>`s with staggered `animation-delay` for sequential drawing.
### No-JS normalization with pathLength
`pathLength="1"` tells the browser to treat the path's length as exactly 1, regardless of real geometry. Then dash math is unit-free:
```svg
<path d="..." pathLength="1" fill="none" stroke="#111"
style="stroke-dasharray:1; stroke-dashoffset:1; animation:draw 1.4s ease forwards"/>
```
```css
@keyframes draw { to { stroke-dashoffset: 0; } }
```
This is the cleanest pure-CSS draw-on and avoids hardcoding measured lengths that break when the path is edited. Use `pathLength="100"` if you prefer to think in percentages.
### Scroll-driven draw-on (no library, via offset)
```js
const len = path.getTotalLength();
path.style.strokeDasharray = len;
function onScroll() {
const p = Math.min(1, Math.max(0, scrollProgress())); // 0..1
path.style.strokeDashoffset = len * (1 - p);
}
document.addEventListener("scroll", onScroll, { passive: true });
```
## 2. Morphing
### Why naive morphs break
Path interpolation walks the `d` command list of A and B in lockstep. If A has 4 cubic curves and B has 7, or A uses `L` where B uses `C`, the browser/animator either refuses or produces garbage. Fixes: match commands by hand, or use a library that resamples.
### GSAP MorphSVG (best for arbitrary shapes)
```js
import gsap from "gsap";
import { MorphSVGPlugin } from "gsap/MorphSVGPlugin";
gsap.registerPlugin(MorphSVGPlugin);
// any shape -> path so it can morph
MorphSVGPlugin.convertToPath("#circ, #star");
gsap.to("#circ", {
duration: 0.9, ease: "power2.inOut",
morphSVG: { shape: "#star", shapeIndex: "auto", type: "rotational" },
});
```
- `shapeIndex` rotates the starting point mapping to minimize twisting; `"auto"` lets GSAP pick, or pass a number to tune.
- `type: "rotational"` interpolates angles/lengths instead of raw coordinates — usually smoother for organic morphs.
- `map: "size" | "position" | "complexity"` changes how sub-paths in compound shapes are matched.
### Flubber (standalone, framework-friendly)
```js
import { interpolate, separate, combine } from "flubber";
// 1 -> 1 shape
const lerp = interpolate(pathA, pathB, { maxSegmentLength: 2 });
// splitting one shape into many (or vice versa)
const split = separate(oneShape, [shape1, shape2, shape3], { single: true });
```
Drive `lerp(t)` with any tween/`requestAnimationFrame`, or inside Framer Motion:
```jsx
import { motion, useMotionValue, useTransform, animate } from "motion/react";
const progress = useMotionValue(0);
const d = useTransform(progress, [0, 1], [0, 1], { clamp: false });
const path = useTransform(d, (v) => interpolate(A, B)(v));
// animate(progress, 1, { duration: 0.6 }) then <motion.path d={path} />
```
Use Flubber when you can't add GSAP or need React-native value plumbing; use MorphSVG for the highest-quality mapping and convenience.
### Hand-authored icon toggle (hamburger ↔ close) — no morph library
When you control both shapes, give them identical structure and animate transforms instead of `d`:
```svg
<svg viewBox="0 0 24 24" class="menu" aria-label="Menu">
<line class="top" x1="3" y1="6" x2="21" y2="6"/>
<line class="mid" x1="3" y1="12" x2="21" y2="12"/>
<line class="bot" x1="3" y1="18" x2="21" y2="18"/>
</svg>
```
```css
.menu line { stroke:#111; stroke-width:2; transition: transform .25s ease, opacity .2s ease;
transform-origin: center; transform-box: fill-box; }
.menu.open .top { transform: translateY(6px) rotate(45deg); }
.menu.open .mid { opacity: 0; }
.menu.open .bot { transform: translateY(-6px) rotate(-45deg); }
```
`transform-box: fill-box` makes `transform-origin: center` resolve to the element's own bounding box — essential for SVG rotation; without it the origin is the SVG viewport origin.
## 3. Motion along a path — details
### GSAP MotionPath
```js
gsap.to("#dot", {
duration: 5, repeat: -1, ease: "none",
motionPath: {
path: "#route",
align: "#route", // coordinates relative to the path element
alignOrigin: [0.5, 0.5], // pin the object's center to the path
autoRotate: true, // or a number to add a constant offset angle
start: 0, end: 1, // animate a sub-segment, e.g. 0.2..0.8
},
});
```
Convert a series of points into a smooth path: `MotionPathPlugin.convertToPath(...)`, or pass `motionPath: [{x:0,y:0},{x:100,y:50},...]` and GSAP draws a curve through them.
### CSS offset-path (declarative, modern)
```css
.dot {
offset-path: path("M10,80 C40,10 120,10 150,80");
offset-rotate: auto; /* face direction of travel */
animation: travel 3s linear infinite;
}
@keyframes travel { to { offset-distance: 100%; } }
```
Newer syntax also accepts `offset-path: url(#route)` referencing a `<path>` id and shapes like `ray()`. Good support in evergreen browsers; no JS needed.
### SMIL animateMotion
Self-contained inside the SVG; use `rotate="auto"` and `<mpath href="#id"/>`. Best for portable icon assets where you don't want external CSS/JS. Avoid when you need scroll-sync or broad legacy support.
## 4. SMIL vs CSS vs JS — tradeoffs
| Axis | SMIL | CSS | JS (GSAP/WAAPI) |
|------|------|-----|-----------------|
| Bundle cost | none (inline) | none | library (GSAP ~JS) |
| Works in `<img>` SVG | yes | yes (internal) | no |
| Reach (legacy IE/Edge) | no | partial | yes |
| Scroll/scrub sync | hard | hard | easy |
| Morph mismatched paths | no | no | yes (MorphSVG/Flubber) |
| Timeline orchestration | limited | limited | full |
| Animate `d`/gradients/filters | yes | partial | yes |
Default: CSS for simple declarative effects, GSAP for anything coordinated/scrubbable/morphing, SMIL only for portable self-animating assets in evergreen targets.
## 5. SVGO config tuned for animation
Aggressive SVGO defaults will strip the very things you animate. Use a config like:
```js
// svgo.config.js
module.exports = {
multipass: true,
plugins: [
{ name: "preset-default", params: { overrides: {
removeViewBox: false, // keep responsive scaling
cleanupIds: false, // DO NOT rename ids referenced by CSS/JS/SMIL/gradients
mergePaths: false, // keep sub-paths separate for staggered draw-on
convertShapeToPath: false, // keep <circle>/<rect> if SMIL/CSS targets them
removeHiddenElems: false, // keep elements you toggle visible via animation
inlineStyles: false, // preserve class hooks
} } },
{ name: "removeDimensions" }, // drop width/height, keep viewBox -> fluid scaling
{ name: "prefixIds" }, // namespace ids if inlining many SVGs to avoid id collisions
],
};
```
If multiple inlined SVGs share gradient/filter ids, id collisions make the LAST definition win for everyone — `prefixIds` (or unique authoring) prevents this classic bug.
## 6. Reduced motion
```css
@media (prefers-reduced-motion: reduce) {
.path { animation: none; stroke-dashoffset: 0; } /* show final drawn state instantly */
}
```
For looping decorative SVG (spinners, ambient gradients), pause or hide them under reduced-motion; for functional icon toggles, keep the state change but drop the easing duration.
---
Pick the right method per shape and SVG draws, morphs, and travels smoothly. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=svg-animation)** — the AI motion agent for editable, on-brand motion graphics.
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/60fps-animation
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/accessible-animation
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/ascii-animation
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/caption-animation
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/countdown-video
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/glassmorphism
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/gsap-web
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/lottie-animation
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/lower-thirds
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/micro-interaction
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/page-transition-animation
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/short-form-video
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/svg-animation
+16 -46
View File
@@ -1,59 +1,29 @@
{
"version": 1,
"skills": {
"60fps-animation": {
"source": "iart-ai/web-animation-skills",
"caption-animation": {
"source": "iart-ai/tiktok-video-skills",
"sourceType": "github",
"skillPath": "skills/60fps-animation/SKILL.md",
"computedHash": "d832ea4a0dc07c18483d4fd39352c65e4daa2f298998290730cf159df30f400e"
"skillPath": "skills/caption-animation/SKILL.md",
"computedHash": "e42c4828d3c6115dfb4d8fd3c3fd485b8e6a89c35a8835eee6dae39fb83210a4"
},
"accessible-animation": {
"source": "iart-ai/web-animation-skills",
"countdown-video": {
"source": "iart-ai/tiktok-video-skills",
"sourceType": "github",
"skillPath": "skills/accessible-animation/SKILL.md",
"computedHash": "46695e422851b64f2b680924584ba9f7690309c109b6d98925ef3021b139167c"
"skillPath": "skills/countdown-video/SKILL.md",
"computedHash": "dafb9127ededa76d0df08be73adc46e18d6ec3955153f6ecfd0f928984ce95b2"
},
"ascii-animation": {
"source": "iart-ai/web-animation-skills",
"lower-thirds": {
"source": "iart-ai/tiktok-video-skills",
"sourceType": "github",
"skillPath": "skills/ascii-animation/SKILL.md",
"computedHash": "cc219b1851f713f76934a2738ccdcec37d4a266f1d20ecc346487290cc40d2fb"
"skillPath": "skills/lower-thirds/SKILL.md",
"computedHash": "502c1a8a491e477dd855eb1a45469c09f6ff46a72ea841838d358d0a6a9fd790"
},
"glassmorphism": {
"source": "iart-ai/web-animation-skills",
"short-form-video": {
"source": "iart-ai/tiktok-video-skills",
"sourceType": "github",
"skillPath": "skills/glassmorphism/SKILL.md",
"computedHash": "c98e77044561fea5e51116156d0ba600a56f9961ed18b498d72504d49aff7882"
},
"gsap-web": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/gsap-web/SKILL.md",
"computedHash": "11585ce3142acae8db34c9d0eb57e03834972f1095643266eb2c41b432564b1d"
},
"lottie-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/lottie-animation/SKILL.md",
"computedHash": "3b9838145f5af19d03014a5eca9041ae0ba267b77e312332a129f3fe40078f68"
},
"micro-interaction": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/micro-interaction/SKILL.md",
"computedHash": "f236bc97a9f4c0e9c9a045d0b591e3ca6b6b2aeb26e42b661c15211f652ac131"
},
"page-transition-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/page-transition-animation/SKILL.md",
"computedHash": "62e103e2313433e77db26c67fdcae1c425030e1a51d0f5ffc0fb6fdac6d36132"
},
"svg-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/svg-animation/SKILL.md",
"computedHash": "b6902577f093a1cd724052b94e633154cb42020b5001138185982fb4ce230404"
"skillPath": "skills/short-form-video/SKILL.md",
"computedHash": "893ea19615f3199159b9fe94f05e37a5e538e7e0c3af7f77f9f9bed7ff933423"
}
}
}