From 59c7859bd4781480304a19c9fc248af74cbe8419 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 21:51:39 +0000 Subject: [PATCH] Add web animation skills (iart-ai/web-animation-skills) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01GYeokZtSmqg42ZGWsLXX2C --- .agents/skills/60fps-animation/README.md | 0 .agents/skills/60fps-animation/SKILL.md | 210 +++++++++++++++ .../references/patterns-and-profiling.md | 132 +++++++++ .agents/skills/accessible-animation/README.md | 0 .agents/skills/accessible-animation/SKILL.md | 231 ++++++++++++++++ .../references/patterns.md | 196 ++++++++++++++ .agents/skills/ascii-animation/README.md | 0 .agents/skills/ascii-animation/SKILL.md | 179 ++++++++++++ .../ascii-animation/references/rendering.md | 194 +++++++++++++ .../ascii-animation/scripts/img-to-ascii.mjs | 64 +++++ .agents/skills/glassmorphism/README.md | 0 .agents/skills/glassmorphism/SKILL.md | 177 ++++++++++++ .../glassmorphism/references/glass-recipes.md | 242 +++++++++++++++++ .agents/skills/gsap-web/README.md | 0 .agents/skills/gsap-web/SKILL.md | 225 ++++++++++++++++ .../skills/gsap-web/examples/hero-timeline.js | 67 +++++ .../examples/standalone-template.html | 59 ++++ .../references/scrolltrigger-cookbook.md | 181 +++++++++++++ .../references/scrolltrigger-lenis.md | 255 ++++++++++++++++++ .agents/skills/lottie-animation/README.md | 0 .agents/skills/lottie-animation/SKILL.md | 180 +++++++++++++ .../references/integration-and-export.md | 233 ++++++++++++++++ .agents/skills/micro-interaction/README.md | 0 .agents/skills/micro-interaction/SKILL.md | 173 ++++++++++++ .../references/css-recipes.md | 142 ++++++++++ .../references/framer-motion-recipes.md | 187 +++++++++++++ .../page-transition-animation/README.md | 0 .../skills/page-transition-animation/SKILL.md | 218 +++++++++++++++ .../references/full-examples.md | 176 ++++++++++++ .agents/skills/svg-animation/README.md | 0 .agents/skills/svg-animation/SKILL.md | 167 ++++++++++++ .../references/svg-techniques.md | 214 +++++++++++++++ .claude/skills/60fps-animation | 1 + .claude/skills/accessible-animation | 1 + .claude/skills/ascii-animation | 1 + .claude/skills/glassmorphism | 1 + .claude/skills/gsap-web | 1 + .claude/skills/lottie-animation | 1 + .claude/skills/micro-interaction | 1 + .claude/skills/page-transition-animation | 1 + .claude/skills/svg-animation | 1 + skills-lock.json | 59 ++++ 42 files changed, 4170 insertions(+) create mode 100644 .agents/skills/60fps-animation/README.md create mode 100644 .agents/skills/60fps-animation/SKILL.md create mode 100644 .agents/skills/60fps-animation/references/patterns-and-profiling.md create mode 100644 .agents/skills/accessible-animation/README.md create mode 100644 .agents/skills/accessible-animation/SKILL.md create mode 100644 .agents/skills/accessible-animation/references/patterns.md create mode 100644 .agents/skills/ascii-animation/README.md create mode 100644 .agents/skills/ascii-animation/SKILL.md create mode 100644 .agents/skills/ascii-animation/references/rendering.md create mode 100644 .agents/skills/ascii-animation/scripts/img-to-ascii.mjs create mode 100644 .agents/skills/glassmorphism/README.md create mode 100644 .agents/skills/glassmorphism/SKILL.md create mode 100644 .agents/skills/glassmorphism/references/glass-recipes.md create mode 100644 .agents/skills/gsap-web/README.md create mode 100644 .agents/skills/gsap-web/SKILL.md create mode 100644 .agents/skills/gsap-web/examples/hero-timeline.js create mode 100644 .agents/skills/gsap-web/examples/standalone-template.html create mode 100644 .agents/skills/gsap-web/references/scrolltrigger-cookbook.md create mode 100644 .agents/skills/gsap-web/references/scrolltrigger-lenis.md create mode 100644 .agents/skills/lottie-animation/README.md create mode 100644 .agents/skills/lottie-animation/SKILL.md create mode 100644 .agents/skills/lottie-animation/references/integration-and-export.md create mode 100644 .agents/skills/micro-interaction/README.md create mode 100644 .agents/skills/micro-interaction/SKILL.md create mode 100644 .agents/skills/micro-interaction/references/css-recipes.md create mode 100644 .agents/skills/micro-interaction/references/framer-motion-recipes.md create mode 100644 .agents/skills/page-transition-animation/README.md create mode 100644 .agents/skills/page-transition-animation/SKILL.md create mode 100644 .agents/skills/page-transition-animation/references/full-examples.md create mode 100644 .agents/skills/svg-animation/README.md create mode 100644 .agents/skills/svg-animation/SKILL.md create mode 100644 .agents/skills/svg-animation/references/svg-techniques.md create mode 120000 .claude/skills/60fps-animation create mode 120000 .claude/skills/accessible-animation create mode 120000 .claude/skills/ascii-animation create mode 120000 .claude/skills/glassmorphism create mode 120000 .claude/skills/gsap-web create mode 120000 .claude/skills/lottie-animation create mode 120000 .claude/skills/micro-interaction create mode 120000 .claude/skills/page-transition-animation create mode 120000 .claude/skills/svg-animation create mode 100644 skills-lock.json diff --git a/.agents/skills/60fps-animation/README.md b/.agents/skills/60fps-animation/README.md new file mode 100644 index 0000000..e69de29 diff --git a/.agents/skills/60fps-animation/SKILL.md b/.agents/skills/60fps-animation/SKILL.md new file mode 100644 index 0000000..99a1c78 --- /dev/null +++ b/.agents/skills/60fps-animation/SKILL.md @@ -0,0 +1,210 @@ +--- +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. diff --git a/.agents/skills/60fps-animation/references/patterns-and-profiling.md b/.agents/skills/60fps-animation/references/patterns-and-profiling.md new file mode 100644 index 0000000..abf57e5 --- /dev/null +++ b/.agents/skills/60fps-animation/references/patterns-and-profiling.md @@ -0,0 +1,132 @@ +# 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 + +
…content…
+``` + +```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. diff --git a/.agents/skills/accessible-animation/README.md b/.agents/skills/accessible-animation/README.md new file mode 100644 index 0000000..e69de29 diff --git a/.agents/skills/accessible-animation/SKILL.md b/.agents/skills/accessible-animation/SKILL.md new file mode 100644 index 0000000..8337a1a --- /dev/null +++ b/.agents/skills/accessible-animation/SKILL.md @@ -0,0 +1,231 @@ +--- +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 ( + + ); +} +``` + +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 + +``` + +**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. diff --git a/.agents/skills/accessible-animation/references/patterns.md b/.agents/skills/accessible-animation/references/patterns.md new file mode 100644 index 0000000..287c164 --- /dev/null +++ b/.agents/skills/accessible-animation/references/patterns.md @@ -0,0 +1,196 @@ +# 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 ( + + {/* All descendant motion components honor the OS setting */} + + + ); +} +``` + +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 ; +} +``` + +## 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 +
+ +
+
+``` + +```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. diff --git a/.agents/skills/ascii-animation/README.md b/.agents/skills/ascii-animation/README.md new file mode 100644 index 0000000..e69de29 diff --git a/.agents/skills/ascii-animation/SKILL.md b/.agents/skills/ascii-animation/SKILL.md new file mode 100644 index 0000000..839963e --- /dev/null +++ b/.agents/skills/ascii-animation/SKILL.md @@ -0,0 +1,179 @@ +--- +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 (`
`/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: `
` vs canvas
+
+- **`
` + 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 `
` 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 `