176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
docs: add READMEs for all 17 micro-interaction demos + category index
matin9db311089299
diff --git a/animations/04-micro-interactions/README.md b/animations/04-micro-interactions/README.mdnew file mode 100644index 00000000..93cb66e1--- /dev/null+++ b/animations/04-micro-interactions/README.md@@ -0,0 +1,39 @@+# 04 — Micro-Interactions & UI Animation++Short, user-triggered animations that provide feedback, confirm actions, and communicate state. Duration is typically ≤300ms — they must feel instant, not decorative.++## Animations++| Demo | Description |+|------|-------------|+| [Hover State Animation](hover-state/) | Color, scale, lift, underline, icon nudge, and background sweep on cursor entry |+| [Click / Tap Ripple](click-ripple/) | Ripple from exact click point — Material Design's tactile confirmation |+| [Focus Ring Animation](focus-ring/) | Animated outline on keyboard Tab — :focus-visible for keyboard users only |+| [Button Press Scale](button-press-scale/) | Scales down on press, springs back on release — asymmetric timing |+| [Toggle / Switch Slide](toggle-switch/) | Pill slides between on/off — smooth cubic-bezier for weighted feel |+| [Skeleton Loader](skeleton-loader/) | Pulsing placeholder blocks while real content loads |+| [Shimmer Effect](shimmer-effect/) | Gradient sweep across skeleton placeholders |+| [Loading Spinner](loading-spinner/) | Six spinner variants — ring, orbit, arc, bounce, pulse, square |+| [Progress Animation](progress-animation/) | Linear bar, circular ring, and stepped segments |+| [Checkmark Draw](checkmark-draw/) | SVG stroke-dashoffset draws a checkmark or X on success/failure |+| [Form Field Morph](form-field-morph/) | Floating label rises on focus, persists when filled |+| [Notification Badge Pulse](badge-pulse/) | Dot pulses to draw peripheral attention without interrupting |+| [Tooltip Reveal](tooltip-reveal/) | Info box after 300ms hover delay — focus-visible for keyboard |+| [Drawer / Panel Slide](drawer-slide/) | Off-canvas panel — ease-out open, ease-in close |+| [Modal Expand](modal-expand/) | Modal scales from trigger button position — spatial continuity |+| [Accordion Open/Close](accordion/) | Height 0 → auto: JS measured vs CSS grid-template-rows |+| [Cursor Follower](cursor-follower/) | Lerp-lagged cursor + mix-blend-mode: difference inversion |++## Key concepts++**Duration discipline**: micro-interactions must complete in ≤200ms for hover states, ≤300ms for click responses, ≤400ms for loading indicators appearing. Longer durations shift perception from "feedback" to "animation."++**Asymmetric timing**: press events animate faster than release events (80ms press / 180ms release for button scale). Opening events are slightly slower than closing (280ms open / 220ms close for drawers). The asymmetry matches physical intuition.++**Touch parity**: every hover-triggered effect needs an `:active` or `pointerdown` equivalent on touch. Use `@media (hover: hover)` to gate hover-only styles.++**Reduced motion**: all demos respect `prefers-reduced-motion: reduce`. Disable motion, preserve state changes.++## See also+- [02 — Entrance & Exit](../02-entrance-and-exit/) — longer element-level transitions+- [03 — Page Transitions](../03-page-transitions/) — full-page transition patternsdiff --git a/animations/04-micro-interactions/accordion/README.md b/animations/04-micro-interactions/accordion/README.mdnew file mode 100644index 00000000..5ce49102--- /dev/null+++ b/animations/04-micro-interactions/accordion/README.md@@ -0,0 +1,90 @@+# Accordion Open/Close++## What it is+An accordion is a vertically stacked list of items where each item has a clickable header that reveals or collapses its body content. The animation challenge is that the body must transition between a height of zero (collapsed) and its natural height (expanded) — and CSS cannot natively animate `height: 0` to `height: auto`. The demo shows two solutions: JavaScript measurement and the CSS `grid-template-rows` trick.++## When to use it+- FAQ sections and documentation pages+- Settings panels with grouped options+- Navigation menus with nested sub-items+- Any hierarchical content where not everything should be visible at once++## How it works+**Approach 1 — JavaScript measured height:**++Measure `scrollHeight` (the full content height including overflow) before the transition, set it explicitly, then animate to it:++```js+function openItem(item) {+ const body = item.querySelector('.acc-body');+ const inner = item.querySelector('.acc-inner');++ const targetHeight = inner.scrollHeight;+ body.style.setProperty('--target-h', targetHeight + 'px');+ body.classList.add('open');+}+```++```css+.acc-body {+ overflow: hidden;+ height: 0;+ transition: height 300ms ease-in-out;+}+.acc-body.open {+ height: var(--target-h);+}+```++After transition, set `height: auto` so the content can reflow naturally if its size changes.++**Approach 2 — CSS `grid-template-rows`:**++No JavaScript required. Wrap content in a grid container and animate the row from `0fr` to `1fr`:++```css+.acc-body {+ display: grid;+ grid-template-rows: 0fr;+ transition: grid-template-rows 300ms ease-in-out;+}+.acc-body.open {+ grid-template-rows: 1fr;+}++.acc-inner {+ overflow: hidden;+ min-height: 0; /* required for 0fr to work */+}+```++Toggle the `.open` class in JS — no measurement needed:++```js+trigger.addEventListener('click', () => {+ item.classList.toggle('open');+ body.classList.toggle('open');+ trigger.setAttribute('aria-expanded', item.classList.contains('open'));+});+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 300ms | 150–400ms; shorter feels snappy, longer feels deliberate |+| Easing | ease-in-out | Symmetrical for expand and collapse; ease-out for expand-only bias |+| Single/multi open | Single | Single-open accordion is more navigable; multi-open for settings |+| Chevron rotation | 180° | Standard indicator — point down when collapsed, up when open |++## Production notes+- **Never animate `max-height` to a large value**: the easing runs across the unused space first, making the timing unpredictable and the animation feel front-loaded. Always animate the actual height.+- **CSS grid approach browser support**: `grid-template-rows` animation works in Chrome 107+, Firefox 107+, Safari 16+. For older browsers, fall back to the JS measurement method.+- **Setting `height: auto` after open**: for the JS approach, listen for `transitionend` and set `height: auto` so the content can reflow (e.g., if the user resizes the window). Reset to the explicit pixel value before closing.+- **ARIA requirements**: `aria-expanded` on the trigger, `id` on the content panel, `aria-controls` linking them, and `role="region"` on the content for landmark navigation.+- **Stagger on reveal**: child elements inside the body can fade in with staggered delays once the height animation is underway — see the toggle in the demo.+- **Radix UI Accordion**: fully accessible, keyboard-navigable, animatable via `data-state="open"/"closed"` attributes. Framer Motion's `AnimatePresence` handles entry/exit for conditionally rendered content.++## See also+- [Toggle / Switch Slide](../toggle-switch/) — simpler binary show/hide without height animation+- [Drawer / Panel Slide](../drawer-slide/) — off-canvas equivalent of the accordion body+- [FLIP Technique](../../03-page-transitions/flip-technique/) — height changes that need to animate other elements simultaneouslydiff --git a/animations/04-micro-interactions/badge-pulse/README.md b/animations/04-micro-interactions/badge-pulse/README.mdnew file mode 100644index 00000000..2e22dcad--- /dev/null+++ b/animations/04-micro-interactions/badge-pulse/README.md@@ -0,0 +1,76 @@+# Notification Badge Pulse++## What it is+A notification badge is a small indicator — a numbered chip or colored dot — overlaid on an icon to signal unread items. The pulse animation (a subtle scale loop) draws peripheral attention without demanding focus. It is one of the most restrained attention-capture patterns in UI: it works in the user's periphery without interrupting their current task.++## When to use it+- Notification bells with unread message counts+- Inbox or chat icons indicating new messages+- Avatar status dots indicating online presence+- Any persistent indicator that must remain visible but not disruptive++## How it works+The badge pulses via a looping `scale` keyframe animation:++```css+:root {+ --pulse-dur: 1500ms;+ --pulse-scale: 1.3;+ --badge-color: #f85149;+}++.badge {+ position: absolute;+ top: -8px; right: -8px;+ min-width: 22px; height: 22px;+ border-radius: 11px;+ background: var(--badge-color);+ border: 2px solid var(--page-bg);+ animation: badge-scale var(--pulse-dur) ease-in-out infinite;+}++@keyframes badge-scale {+ 0%, 100% { transform: scale(1); }+ 50% { transform: scale(var(--pulse-scale)); }+}+```++The halo variant adds a radiating ring that expands and fades:++```css+.badge::after {+ content: '';+ position: absolute;+ inset: -4px;+ border-radius: 50%;+ background: var(--badge-color);+ opacity: 0.4;+ animation: halo-grow var(--pulse-dur) ease-out infinite;+}++@keyframes halo-grow {+ 0% { transform: scale(1); opacity: 0.5; }+ 100% { transform: scale(2.2); opacity: 0; }+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 1500ms | 800ms feels urgent; 3000ms is almost imperceptible; 1500ms is the peripheral-vision sweet spot |+| Scale | 1.3 | 1.1–1.5 range; beyond 1.5 the badge grows large enough to feel alarming |+| Halo style | Scale + halo | Halo alone is subtler; scale alone is more contained |+| Border offset | `border: 2px solid bg` | The badge border must match the icon background to appear floating |++## Production notes+- **Peripheral vision threshold**: 1.15× scale at 1.5s is the minimum perceptible in peripheral vision for most users. Below that, the badge reads as static.+- **Dismiss on interaction**: always remove the pulse (and the badge itself) when the user views the notifications. A persistent pulse on already-seen content is confusing.+- **Fade-after-attention**: pulse strongly for the first 5 seconds, then reduce scale or stop entirely. This mirrors real notification system behavior (the alert has been "seen" peripherally).+- **`border: 2px solid` background color trick**: this makes the badge appear to float above the icon surface with a gap. Update the border color if the icon sits on a non-uniform background.+- **`prefers-reduced-motion`**: disable the pulse animation entirely. The badge remains visible — users who need reduced motion still see the indicator, just without motion.+- **React**: `react-hot-toast` and Sonner implement badge-style indicators for toast notifications. For nav badges, most component libraries include a `Badge` with optional `animate` prop.++## See also+- [Tooltip Reveal](../tooltip-reveal/) — hover-triggered information on the same icons+- [Loading Spinner](../loading-spinner/) — another attention indicator for active states+- [Hover State Animation](../hover-state/) — hover feedback on the icon behind the badgediff --git a/animations/04-micro-interactions/button-press-scale/README.md b/animations/04-micro-interactions/button-press-scale/README.mdnew file mode 100644index 00000000..ef62e813--- /dev/null+++ b/animations/04-micro-interactions/button-press-scale/README.md@@ -0,0 +1,67 @@+# Button Press Scale++## What it is+Button press scale is a micro-animation where a button shrinks slightly on `pointerdown` and springs back on `pointerup`. Without physical button travel, this visual shrink substitutes for the tactile sensation of pressing a real button — it confirms the press registered and creates a satisfying click-like feel.++## When to use it+- Primary action buttons (submit, confirm, pay, send)+- Any button where missing the tap would cause frustration+- Mobile-first interfaces where touch targets replace mouse clicks+- Icon buttons that need stronger press confirmation than a ripple alone++## How it works+Two separate transitions handle press and release with different timings — press is fast, release is slower and optionally springy:++```css+:root {+ --press-scale: 0.95;+ --press-dur: 80ms;+ --release-dur: 180ms;+ --release-ease: cubic-bezier(.34, 1.56, .64, 1);+}++.btn {+ transition: transform var(--release-dur) var(--release-ease);+ transform-origin: center;+}+.btn.pressed {+ transition: transform var(--press-dur) ease;+ transform: scale(var(--press-scale));+}+```++```js+const press = () => btn.classList.add('pressed');+const release = () => btn.classList.remove('pressed');++btn.addEventListener('pointerdown', press);+btn.addEventListener('pointerup', release);+btn.addEventListener('pointercancel', () => btn.classList.remove('pressed'));++// Keyboard support+btn.addEventListener('keydown', e => { if (e.key === ' ' || e.key === 'Enter') press() });+btn.addEventListener('keyup', e => { if (e.key === ' ' || e.key === 'Enter') release() });+```++The asymmetric timing is the key insight: pressing (80ms) mirrors the physical suddenness of contact; releasing (180ms) mirrors the slower mechanical spring-back of a real button.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Press scale | 0.95 | 0.92–0.97 is the useful range; below 0.9 looks broken |+| Press duration | 80ms | Should feel instantaneous — 50–100ms is typical |+| Release duration | 180ms | 1.5–2.5× the press duration for spring-back feel |+| Release easing | `cubic-bezier(.34,1.56,.64,1)` | Overshoot creates the spring; remove overshoot for flat |++## Production notes+- **`pointercancel` handling**: always listen for `pointercancel` in addition to `pointerup`. If the user starts a scroll gesture after pressing, `pointerup` may not fire, leaving the button stuck in its pressed state.+- **`touch-action: manipulation`** on the button element suppresses the 300ms tap delay on mobile browsers without needing a separate fast-tap library.+- **Shadow pairing**: coupling a shadow-shrink to the scale change increases realism — a button that lifts slightly on hover and drops on press mirrors physical button behavior.+- **`prefers-reduced-motion`**: users who request reduced motion should see no transform. Wrap the transition in a media query or check `matchMedia` in JS.+- **GSAP**: `gsap.to(btn, { scale: 0.95, duration: 0.08, ease: "power1.in" })` on press; `gsap.to(btn, { scale: 1, duration: 0.18, ease: "back.out(1.7)" })` on release.+- **Framer Motion**: `<motion.button whileTap={{ scale: 0.95 }} />` — single prop, handles press/release automatically.++## See also+- [Click / Tap Ripple](../click-ripple/) — complementary click-point feedback+- [Hover State Animation](../hover-state/) — pre-click affordance+- [Checkmark Draw](../checkmark-draw/) — post-action success confirmationdiff --git a/animations/04-micro-interactions/checkmark-draw/README.md b/animations/04-micro-interactions/checkmark-draw/README.mdnew file mode 100644index 00000000..747463a3--- /dev/null+++ b/animations/04-micro-interactions/checkmark-draw/README.md@@ -0,0 +1,72 @@+# Checkmark Draw++## What it is+The checkmark draw animates an SVG path progressively from one end to the other, giving the impression of something being hand-drawn. It uses the `stroke-dashoffset` technique: the path is pre-drawn but hidden behind a full-length dash gap, then the gap shrinks to zero over time, revealing the stroke. Most commonly used as a success confirmation after form submission or payment.++## When to use it+- Form submission success state (the button transforms into a checkmark)+- Payment confirmation screens+- Step completion indicators in multi-step flows+- Any binary success/failure state where a visual reward is appropriate++## How it works+Every SVG path has a `getTotalLength()` value — the pixel length of its stroke. Setting `stroke-dasharray` to that length and `stroke-dashoffset` to that same length makes the stroke invisible (the gap covers it entirely). Animating `stroke-dashoffset` to 0 draws the path in:++```html+<svg viewBox="0 0 80 80">+ <circle class="check-circle" cx="40" cy="40" r="30"/>+ <polyline class="check-mark" points="24,41 35,52 56,30"/>+</svg>+```++```css+.check-circle {+ fill: none; stroke: #56d364; stroke-width: 4;+ stroke-dasharray: 188; /* 2π × 30 */+ stroke-dashoffset: 188;+ transition: stroke-dashoffset 500ms ease-out;+}+.check-mark {+ fill: none; stroke: #56d364; stroke-width: 4; stroke-linecap: round; stroke-linejoin: round;+ stroke-dasharray: 52;+ stroke-dashoffset: 52;+ transition: stroke-dashoffset 500ms ease-out 200ms; /* delay after circle */+}++.drawn .check-circle { stroke-dashoffset: 0; }+.drawn .check-mark { stroke-dashoffset: 0; }+```++The circle draws first (0ms delay), the checkmark follows with a `200ms` delay — creating the sequenced "circle then tick" effect.++For paths that aren't simple geometry, measure length in JavaScript:++```js+const path = document.querySelector('.my-path');+const length = path.getTotalLength();+path.style.strokeDasharray = length;+path.style.strokeDashoffset = length;+// Trigger draw:+path.style.strokeDashoffset = 0;+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 500ms | 200–800ms is the legible range; faster feels technical, slower feels dramatic |+| Easing | ease-out | Decelerating draw mimics natural handwriting — fast start, slow finish |+| Stroke width | 4px | Thicker reads as confident; thinner reads as precise |+| Delay between paths | 200ms | Sequence circle → mark; simultaneous is also valid but less theatrical |++## Production notes+- **Path length must match `stroke-dasharray`**: if the length is wrong, the path draws partially or overshoots. For computed paths, always use `getTotalLength()` rather than hardcoding.+- **`stroke-dasharray` on `<polyline>`**: polylines report `getTotalLength()` correctly in all major browsers. Use it for checkmarks; `<path d="M 24,41 L 35,52 L 56,30">` is equivalent.+- **Error state pairing**: the same technique draws an X for failure. Two crossing `<line>` elements with staggered delays produce a cross-draw effect (see toggle in the demo).+- **Shake on error**: after drawing the X, `animation: shake 400ms ease` on the container reinforces the rejection.+- **GSAP**: `gsap.to(path, { strokeDashoffset: 0, duration: 0.5, ease: "power2.out" })`. The DrawSVG plugin is more convenient for complex paths.+- **Framer Motion**: `<motion.path initial={{ pathLength: 0 }} animate={{ pathLength: 1 }} transition={{ duration: 0.5 }} />` — `pathLength` is a 0–1 shorthand for the dashoffset technique.++## See also+- [Progress Animation](../progress-animation/) — the predecessor state before success+- [Loading Spinner](../loading-spinner/) — the loading state that transitions to a checkmark+- [Button Press Scale](../button-press-scale/) — press feedback before the async operation startsdiff --git a/animations/04-micro-interactions/click-ripple/README.md b/animations/04-micro-interactions/click-ripple/README.mdnew file mode 100644index 00000000..3540c997--- /dev/null+++ b/animations/04-micro-interactions/click-ripple/README.md@@ -0,0 +1,65 @@+# Click / Tap Ripple++## What it is+A ripple is a circle that expands from the point of click or tap, fading as it grows. Popularized by Material Design, it gives users haptic-substitute feedback: the visual expansion communicates that the press registered, and the origin point confirms exactly where contact was made.++## When to use it+- Primary action buttons (submit, confirm, purchase)+- List items and menu entries that respond to tap+- Any surface where the user needs instant confirmation that a touch registered+- Icon buttons where the ripple prevents a "did it work?" pause++## How it works+On `pointerdown`, measure the click position relative to the button using `getBoundingClientRect()`, spawn an absolutely-positioned `<span>`, and animate it from `scale(0)` to a large scale while fading opacity to 0:++```js+function spawnRipple(btn, e) {+ const r = btn.getBoundingClientRect();+ const size = Math.max(r.width, r.height) * 2;+ const x = e.clientX - r.left;+ const y = e.clientY - r.top;++ const el = document.createElement('span');+ el.style.cssText = `+ position: absolute;+ width: ${size}px; height: ${size}px;+ left: ${x - size/2}px; top: ${y - size/2}px;+ border-radius: 50%;+ background: rgba(255,255,255,0.4);+ transform: scale(0);+ animation: ripple 600ms ease-out forwards;+ pointer-events: none;+ `;+ btn.appendChild(el);+ el.addEventListener('animationend', () => el.remove(), { once: true });+}+```++```css+@keyframes ripple {+ to { transform: scale(2.5); opacity: 0; }+}+```++The button needs `position: relative; overflow: hidden` to contain the ripple.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 600ms | Longer than a hover animation — the user has already committed the click |+| Max scale | 2.5× | Must be large enough to reach all button corners from any click point |+| Start opacity | 0.4 | Controls visibility of the highlight without washing out button content |+| Origin | Click point | Material default; "from center" is simpler but less accurate |++## Production notes+- **`overflow: hidden`** on the button is required — without it the ripple extends beyond the button boundary.+- **`pointer-events: none`** on the ripple element prevents it from interfering with subsequent clicks fired in quick succession.+- **Touch events**: `pointerdown` works for both mouse and touch. Avoid `mousedown` — it doesn't fire on touch.+- **Cleanup**: always remove the element in `animationend`. In stress tests (rapid clicking) DOM nodes accumulate quickly without cleanup.+- **GSAP**: `gsap.fromTo(el, { scale: 0 }, { scale: 2.5, opacity: 0, duration: 0.6, ease: "power2.out", onComplete: () => el.remove() })`.+- **Material Web Components**: the `<md-ripple>` component handles all of this automatically including touch and keyboard activation.++## See also+- [Button Press Scale](../button-press-scale/) — scale-based feedback complementing the ripple+- [Hover State Animation](../hover-state/) — pre-click affordance signaling+- [Checkmark Draw](../checkmark-draw/) — post-click confirmation feedbackdiff --git a/animations/04-micro-interactions/cursor-follower/README.md b/animations/04-micro-interactions/cursor-follower/README.mdnew file mode 100644index 00000000..c5074df0--- /dev/null+++ b/animations/04-micro-interactions/cursor-follower/README.md@@ -0,0 +1,78 @@+# Cursor Follower++## What it is+A cursor follower is a custom DOM element that tracks the mouse position with a lag, creating a smooth trailing effect. Combined with `mix-blend-mode: difference`, it inverts the color of whatever is beneath it — making the follower automatically visible against any background: white on dark areas, black on light areas, without any color calculation.++## When to use it+- Portfolio and agency sites where the cursor itself becomes part of the brand experience+- Interactive storytelling experiences where cursor reactivity reinforces immersion+- Landing pages where hover targets expand the follower for tactile feedback+- Any site where the default OS cursor is too subtle for the intended aesthetic++## How it works+Track `mousemove` to record target coordinates (`mx`, `my`). Each animation frame, interpolate the follower's position toward the target using a lerp (linear interpolation):++```js+let mx = 0, my = 0; // mouse position+let fx = 0, fy = 0; // follower position+const ease = 0.15; // fraction to close each frame++document.addEventListener('mousemove', e => { mx = e.clientX; my = e.clientY; });++function loop() {+ fx += (mx - fx) * ease;+ fy += (my - fy) * ease;+ follower.style.left = fx + 'px';+ follower.style.top = fy + 'px';+ requestAnimationFrame(loop);+}+loop();+```++Each frame closes 15% of the remaining gap between follower and cursor. At 60fps, the follower reaches ~95% of the way in about 15 frames (~250ms), producing a smooth lag without ever quite reaching the cursor.++The `mix-blend-mode: difference` CSS property makes the follower invert whatever background color is beneath it:++```css+#follower {+ position: fixed;+ width: 32px; height: 32px;+ border-radius: 50%;+ background: #fff;+ mix-blend-mode: difference;+ pointer-events: none;+ transform: translate(-50%, -50%);+ will-change: transform;+ z-index: 9999;+}+```++For hover reactivity, scale the follower up when over interactive targets:++```js+document.querySelectorAll('a, button, [data-hover]').forEach(el => {+ el.addEventListener('mouseenter', () => follower.classList.add('expanded'));+ el.addEventListener('mouseleave', () => follower.classList.remove('expanded'));+});+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Easing factor | 0.15 | 0.05 = heavy lag (slow follower); 0.5 = almost no lag; 0.1–0.2 is the readable range |+| Size | 32px | 16–24px for subtle; 40–60px for dramatic; scales with hover expansion |+| Mix-blend-mode | difference | `normal` falls back to a colored dot; `difference` works universally |+| Hover expansion | 2.5× | Enlarges on hover targets for "magnetic" cursor feel |++## Production notes+- **Touch devices**: cursor effects don't apply to touch. Detect `(pointer: coarse)` and hide the follower entirely — never simulate a cursor on touch.+- **Performance**: `position: fixed` + `will-change: transform` promotes the follower to its own GPU layer. Updating `left`/`top` (rather than `transform`) on every frame is less optimal — in production, update `transform: translate(x, y)` instead.+- **Lag calibration**: at 60fps with `ease = 0.15`, the follower lags ~250ms. At 120fps (high refresh displays), the same `ease` value produces ~125ms lag — the follower will appear snappier. Account for frame rate differences in high-performance contexts.+- **Cursor hide**: add `cursor: none` to the `body` to hide the OS cursor when the follower is active. Re-enable on touch or when the cursor leaves the window.+- **GSAP QuickTo**: `const xTo = gsap.quickTo(follower, 'x', { duration: 0.3 })` is GSAP's optimized cursor follower pattern — more precise than rAF lerp at variable frame rates.+- **`@motionone/animate`**: lightweight alternative to GSAP for cursor followers; no tree-shaking overhead.++## See also+- [Hover State Animation](../hover-state/) — cursor-triggered changes on interactive elements+- [Tooltip Reveal](../tooltip-reveal/) — cursor-proximity information reveal+- [Click / Tap Ripple](../click-ripple/) — click-point feedback complementing the cursor followerdiff --git a/animations/04-micro-interactions/drawer-slide/README.md b/animations/04-micro-interactions/drawer-slide/README.mdnew file mode 100644index 00000000..93852aa3--- /dev/null+++ b/animations/04-micro-interactions/drawer-slide/README.md@@ -0,0 +1,88 @@+# Drawer / Panel Slide++## What it is+A drawer is an off-canvas panel that slides in from a screen edge, typically carrying navigation, filters, or settings. It overlays the main content with a dimmed backdrop. The key animation insight is asymmetric easing: the drawer decelerates into its open position (ease-out — feels like arrival) and accelerates away when closing (ease-in — feels like dismissal).++## When to use it+- Mobile navigation menus behind a hamburger button+- Filter panels on e-commerce and search result pages+- Settings, preferences, and configuration panels+- Context panels that appear alongside selected content (VS Code-style side panels)++## How it works+The drawer starts translated fully off-screen and transitions to its natural position:++```css+:root {+ --drawer-w: 280px;+ --open-dur: 280ms;+ --close-dur: 220ms;+ --open-ease: ease-out;+ --close-ease: ease-in;+}++.drawer {+ position: fixed;+ top: 0; left: 0; bottom: 0;+ width: var(--drawer-w);+ transform: translateX(-100%);+ transition: transform var(--open-dur) var(--open-ease);+ will-change: transform;+ z-index: 200;+}++.drawer.open {+ transform: translateX(0);+}++/* Backdrop */+.backdrop {+ position: fixed; inset: 0;+ background: rgba(0,0,0,.5);+ opacity: 0;+ transition: opacity var(--open-dur) ease;+ pointer-events: none;+ z-index: 199;+}+.backdrop.visible {+ opacity: 1;+ pointer-events: auto;+}+```++Close on Escape key, backdrop click, and swipe gesture:++```js+function open() { drawer.classList.add('open'); backdrop.classList.add('visible'); }+function close() { drawer.classList.remove('open'); backdrop.classList.remove('visible'); }++document.addEventListener('keydown', e => { if (e.key === 'Escape') close(); });+backdrop.addEventListener('click', close);++// Swipe-to-close+let dragStartX = 0;+drawer.addEventListener('pointerdown', e => { dragStartX = e.clientX; });+drawer.addEventListener('pointerup', e => { if (e.clientX - dragStartX < -50) close(); });+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Open duration | 280ms | 200–350ms — the drawer must feel instant, not cinematic |+| Close duration | 220ms | Slightly shorter than open — dismissal feels snappier than arrival |+| Open easing | ease-out | Decelerates into position — mimics a physical panel sliding to a stop |+| Close easing | ease-in | Accelerates away — mimics a panel being pulled |+| Backdrop opacity | 0.5 | 0.3–0.6 range; above 0.7 feels like a modal, not a drawer |++## Production notes+- **Focus trap**: when the drawer is open, Tab focus must cycle within it. Use a focus trap library (e.g., `focus-trap`) or the native `<dialog>` element which traps focus automatically.+- **`aria-modal="true"` and `role="dialog"`**: required for screen readers to announce the drawer as a modal context. Add `aria-label` or `aria-labelledby` for the drawer title.+- **`will-change: transform`**: promotes the drawer to its own compositing layer, preventing paint during the slide. Remove `will-change` after the animation completes if memory is a concern on low-end devices.+- **Right/bottom drawers**: for filters, slides from right (`translateX(100%)`); for action sheets, slides from bottom (`translateY(100%)`).+- **Swipe-to-close on touch**: use `pointerdown`/`pointermove`/`pointerup` (not mouse/touch events separately). Measure the delta and close if the swipe distance exceeds ~50px in the close direction.+- **Radix UI Sheet / shadcn Drawer**: fully accessible, animated drawer components. Vaul (Emil Kowalski) adds native mobile-style drag-to-dismiss for bottom drawers.++## See also+- [Modal Expand](../modal-expand/) — for content that should appear centered, not from an edge+- [Accordion Open/Close](../accordion/) — inline expand/collapse rather than overlay+- [Tooltip Reveal](../tooltip-reveal/) — lightweight alternative for small amounts of additional informationdiff --git a/animations/04-micro-interactions/focus-ring/README.md b/animations/04-micro-interactions/focus-ring/README.mdnew file mode 100644index 00000000..7ce04b6c--- /dev/null+++ b/animations/04-micro-interactions/focus-ring/README.md@@ -0,0 +1,73 @@+# Focus Ring Animation++## What it is+A focus ring is the visible outline that appears around a focused element during keyboard navigation. Animating it — rather than simply toggling it on — makes the transition feel intentional rather than abrupt. The critical implementation detail is using `:focus-visible` instead of `:focus`, so the ring only appears for keyboard users, never for mouse clicks.++## When to use it+- Every interactive element on every page — focus rings are mandatory for WCAG 2.4.7 compliance+- Forms where keyboard navigation between fields must be clearly tracked+- Navigation menus and modal dialogs where Tab order needs visual confirmation+- Any site with keyboard-reliant users (power users, accessibility needs, screen reader users)++## How it works+Remove the browser's default outline entirely, then rebuild it using `:focus-visible` with an animation:++```css+:root {+ --ring-color: #58a6ff;+ --ring-w: 2px;+ --ring-offset: 3px;+ --ring-dur: 140ms;+}++/* Remove default — only for elements we control */+.focusable { outline: none; }++/* Rebuild with animation — keyboard only */+.focusable:focus-visible {+ outline: var(--ring-w) solid var(--ring-color);+ outline-offset: var(--ring-offset);+ animation: ring-in var(--ring-dur) ease-out both;+}++@keyframes ring-in {+ from {+ outline-offset: calc(var(--ring-offset) + 8px);+ opacity: 0.3;+ }+ to {+ outline-offset: var(--ring-offset);+ opacity: 1;+ }+}+```++The animation interpolates `outline-offset` from a larger value inward — the ring appears to contract onto the element, drawing the eye. A glow variant adds `box-shadow` for a softer look:++```css+.focusable:focus-visible {+ outline: 2px solid var(--ring-color);+ outline-offset: 3px;+ box-shadow: 0 0 0 5px rgba(88,166,255,.18);+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 140ms | Fast enough to not feel delayed; slow enough to be visible |+| Ring width | 2px | WCAG 2.4.11 requires 2px minimum |+| Ring offset | 3px | Gap between element edge and ring — 2–4px feels natural |+| Ring color | accent | Must have 3:1 contrast ratio against adjacent colors (WCAG) |++## Production notes+- **Never use `:focus` alone** — it fires on mouse clicks in all browsers, creating unwanted rings that designers suppress by setting `outline: none` globally, breaking keyboard access entirely. `:focus-visible` solves both problems.+- **Do not globally `outline: none`** — this removes keyboard navigation visibility for all users and is a WCAG failure. Only remove it on elements where you're rebuilding the ring yourself.+- **Browser support**: `:focus-visible` is supported in all modern browsers (Chrome 86+, Firefox 85+, Safari 15.4+). For older browsers, use the `focus-visible` polyfill from WICG.+- **Framer Motion**: focus ring animations are best kept in CSS — JS animation of outline-offset is less performant. Framer Motion's `whileFocus` works for `box-shadow` glow variants.+- **Design tokens**: expose ring color as a design token. Systems like Radix UI and shadcn/ui wire focus ring color to the theme's primary accent automatically.++## See also+- [Button Press Scale](../button-press-scale/) — complementary click feedback+- [Form Field Morph](../form-field-morph/) — focus-triggered label animation+- [Hover State Animation](../hover-state/) — pre-click visual affordancediff --git a/animations/04-micro-interactions/form-field-morph/README.md b/animations/04-micro-interactions/form-field-morph/README.mdnew file mode 100644index 00000000..f1bb8363--- /dev/null+++ b/animations/04-micro-interactions/form-field-morph/README.md@@ -0,0 +1,89 @@+# Form Field Morph++## What it is+Form field morph, also called the floating label pattern, is an input animation where the placeholder label translates upward and scales down when the field receives focus. Unlike a traditional placeholder that disappears on first keystroke, the floating label persists above the input as a visible identifier throughout the entire editing session.++## When to use it+- Any form where screen space is limited and a separate `<label>` above each input would be too tall+- Sign-up, sign-in, and checkout forms+- Settings pages where many fields appear in a compact list+- Mobile forms where vertical space is at a premium++## How it works+The label is positioned absolutely inside the field container, overlapping the input at placeholder height. On focus (or when the input is filled), it transforms upward using `translateY` and `scale`:++```css+:root {+ --field-dur: 200ms;+ --float-dist: 22px;+ --label-scale: 0.8;+ --focus-color: #58a6ff;+}++.float-field { position: relative; padding-top: 20px; }++.float-field label {+ position: absolute;+ left: 0; top: 20px;+ font-size: 12px;+ color: var(--muted);+ pointer-events: none;+ transform-origin: left center;+ transition:+ transform var(--field-dur) ease,+ color var(--field-dur) ease;+}++.float-field input {+ display: block; width: 100%;+ background: transparent;+ border: none; border-bottom: 1px solid var(--border);+ outline: none;+ transition: border-color var(--field-dur) ease;+}++/* Float on focus OR when filled */+.float-field:focus-within label,+.float-field.filled label {+ transform: translateY(calc(var(--float-dist) * -1)) scale(var(--label-scale));+ color: var(--focus-color);+}+```++The `.filled` class is toggled in JavaScript by checking `input.value.length > 0` on `blur` — this keeps the label floated when the user leaves a filled field:++```js+input.addEventListener('blur', () => {+ wrapper.classList.toggle('filled', input.value.trim().length > 0);+});+```++A CSS-only alternative uses `:placeholder-shown` (the placeholder is visible only when the field is empty):++```css+input:not(:placeholder-shown) ~ label,+input:focus ~ label {+ transform: translateY(-22px) scale(0.8);+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 200ms | 120–250ms; slower feels heavy on forms with many fields |+| Float distance | 22px | Must clear the input text height with a small gap |+| Label scale | 0.8 | 0.75–0.85 — readable but visually subordinate to input text |+| Focus color | accent | Reinforces which field is active |++## Production notes+- **The filled-state retention bug**: the most common mistake is animating on `:focus-within` alone. When the user tabs to the next field, the label snaps back even though the field is filled. Always combine with a filled class or `:placeholder-shown`.+- **Placeholder text conflict**: floating labels and placeholder text serve the same purpose — don't use both. If using floating labels, leave the `placeholder` attribute blank or set it to a single space `" "` (needed for `:placeholder-shown` CSS detection).+- **Box style variant**: the demo includes a box-style (Material-style) floating label where the label floats inside the border, not above it. This works better with bordered inputs than underline-only inputs.+- **`transform-origin: left center`**: without this, the label scales from its center, shifting position horizontally.+- **Accessibility**: always use a real `<label>` element (not `aria-label` or `placeholder` alone). Screen readers announce the label text; `placeholder` text is not reliably announced.+- **React Hook Form + Floating UI**: common pairing in production. The float state is controlled via `formState.dirtyFields` or watched field values.++## See also+- [Focus Ring Animation](../focus-ring/) — complementary keyboard-focus indicator+- [Toggle / Switch Slide](../toggle-switch/) — another input state transition pattern+- [Accordion Open/Close](../accordion/) — expand/collapse with height animationdiff --git a/animations/04-micro-interactions/hover-state/README.md b/animations/04-micro-interactions/hover-state/README.mdnew file mode 100644index 00000000..fb3635d2--- /dev/null+++ b/animations/04-micro-interactions/hover-state/README.md@@ -0,0 +1,59 @@+# Hover State Animation++## What it is+A hover state animation is any visual change that fires when the cursor enters an interactive element. It confirms interactivity before the user clicks. Six distinct techniques exist — color shift, scale, lift+shadow, underline grow, icon nudge, and background sweep — each with different affordance strength and motion character.++## When to use it+- Navigation links and buttons that need to signal clickability+- Cards in a grid where hover previews the action+- Icon buttons where hover reveals a label or changes the icon color+- Any element where the default cursor alone is insufficient to communicate interaction++## How it works+All six techniques use CSS `transition` driven by `:hover` (or `:active` as a touch fallback). A single `--dur` and `--ease` CSS variable controls every card simultaneously:++```css+:root { --dur: 180ms; --ease: ease; }++/* Color shift */+.h-color { transition: background var(--dur) var(--ease), border-color var(--dur) var(--ease); }+.h-color:hover { background: #1a2a3a; border-color: var(--ui-accent); }++/* Scale */+.h-scale { transition: transform var(--dur) var(--ease); }+@media (hover: hover) { .h-scale:hover { transform: scale(1.03); } }+.h-scale:active { transform: scale(1.03); }++/* Background sweep */+.h-sweep::before {+ content: '';+ position: absolute;+ inset: 0;+ background: rgba(88,166,255,.13);+ transform: translateX(-100%);+ transition: transform var(--dur) var(--ease);+}+@media (hover: hover) { .h-sweep:hover::before { transform: translateX(0); } }+```++The `@media (hover: hover)` gate prevents hover styles from sticking on touch devices, while `:active` provides a tap fallback.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| `--dur` | 180ms | Transition duration — keep ≤200ms for responsiveness |+| `--ease` | ease | Easing curve — ease-out feels snappier, springy adds delight |+| Scale amount | 1.03 | 1.01–1.05 is the useful range; beyond 1.05 feels unstable |+| Shadow elevation | 8px / 24px | `translateY(-4px)` paired with a larger shadow sells the lift |++## Production notes+- **Duration ceiling**: hover animations over 200ms make rapid cursor movement across multiple elements feel sluggish and "sticky." Keep it at or below 180ms.+- **Touch fallback**: `:hover` does not fire reliably on touch. Use `@media (hover: hover)` to gate hover-only styles, and add `:active` equivalents for tap feedback.+- **Background sweep implementation**: use `::before` with `overflow: hidden` on the parent and `translateX` rather than `width` — `width` triggers layout, `transform` does not.+- **GSAP**: `gsap.to(el, { scale: 1.03, duration: 0.18 })` on `mouseenter` / `mouseleave`. Overkill for simple hover; CSS handles this natively.+- **Framer Motion**: `<motion.div whileHover={{ scale: 1.03 }} />` — idiomatic React equivalent.++## See also+- [Button Press Scale](../button-press-scale/) — the complement: press-down feedback+- [Tooltip Reveal](../tooltip-reveal/) — hover that reveals additional information+- [Click / Tap Ripple](../click-ripple/) — confirmation on click rather than hoverdiff --git a/animations/04-micro-interactions/loading-spinner/README.md b/animations/04-micro-interactions/loading-spinner/README.mdnew file mode 100644index 00000000..0dac6d3d--- /dev/null+++ b/animations/04-micro-interactions/loading-spinner/README.md@@ -0,0 +1,79 @@+# Loading Spinner++## What it is+A loading spinner is a looping animation indicating that the system is busy and the user should wait. Unlike a progress bar, it conveys no information about duration — only that work is happening. This makes it appropriate for unpredictably-timed operations like network requests, file processing, or authentication handshakes.++## When to use it+- Network requests where response time is unknown+- Authentication flows, payment processing, and other server-round-trip operations+- Background operations the user triggered but cannot cancel+- Inline loading states within buttons after click (replacing the label briefly)++## How it works+The classic ring spinner uses a `border` trick: a full circle with one quadrant colored differently, rotated continuously:++```css+:root { --spd: 800ms; --clr: #58a6ff; --sz: 40px; }++.sp-ring {+ width: var(--sz); height: var(--sz);+ border-radius: 50%;+ border: 3px solid rgba(255,255,255,.1);+ border-top-color: var(--clr);+ animation: spin var(--spd) linear infinite;+}++@keyframes spin { to { transform: rotate(360deg); } }+```++The SVG arc variant offers more control over arc length, which can also animate:++```css+.sp-arc circle {+ fill: none;+ stroke: var(--clr);+ stroke-width: 4;+ stroke-linecap: round;+ stroke-dasharray: 60 100;+ animation: arc-pulse calc(var(--spd)*2) ease-in-out infinite;+}++@keyframes arc-pulse {+ 0%,100% { stroke-dasharray: 15 100; }+ 50% { stroke-dasharray: 80 100; }+}+```++The bounce-dots variant uses staggered animation delays on three sibling elements:++```css+.dot { animation: bounce var(--spd) ease-in-out infinite; }+.dot:nth-child(2) { animation-delay: calc(var(--spd) * 0.15); }+.dot:nth-child(3) { animation-delay: calc(var(--spd) * 0.30); }++@keyframes bounce {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-14px); }+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Speed | 800ms | 600–1000ms is the legible range; faster reads as anxious |+| Size | 40px | 20px inline, 40px full-screen, 60–80px for empty states |+| Color | accent | Should be distinct from the page background |+| Minimum display | 400ms | Flash a spinner for less than 400ms and hide it — the flash is worse than nothing |++## Production notes+- **Minimum display time**: if the operation completes in under ~400ms, either show no spinner at all or enforce a minimum display time. A spinner that flashes briefly causes more confusion than it resolves.+- **Inline button spinner**: replace the button label with a spinner on click, re-enable on response. This pattern prevents double-submission.+- **`role="status"` and `aria-label`**: screen readers need to announce the loading state. Add `role="status"` and `aria-label="Loading"` to the spinner container.+- **`prefers-reduced-motion`**: reduce to a simple opacity pulse or hide the spinner and rely on `aria-live` region announcements.+- **React ecosystem**: `react-spinners` (by David Hu) has 15+ variants. For Tailwind, use the `animate-spin` utility on a bordered circle div.+- **When not to use**: if you know total progress (file upload, multi-step process), use a progress bar instead — it conveys more information and reduces anxiety.++## See also+- [Progress Animation](../progress-animation/) — for known-duration or known-percentage loads+- [Skeleton Loader](../skeleton-loader/) — for content-shaped placeholders+- [Checkmark Draw](../checkmark-draw/) — the success state after a spinner resolvesdiff --git a/animations/04-micro-interactions/modal-expand/README.md b/animations/04-micro-interactions/modal-expand/README.mdnew file mode 100644index 00000000..ba0e8ea6--- /dev/null+++ b/animations/04-micro-interactions/modal-expand/README.md@@ -0,0 +1,82 @@+# Modal Expand++## What it is+Modal expand is a transition where a modal dialog scales into view from the position of the button that triggered it. By setting `transform-origin` to the trigger button's location, the modal appears to "grow from" that point — maintaining spatial continuity between trigger and result. This gives users a clear mental model of where the modal came from and, by extension, where it will return to when dismissed.++## When to use it+- Card actions where tapping a card opens a detail modal+- Floating action buttons (FABs) that expand into a form or panel+- Any trigger where the spatial relationship between button and modal matters for comprehension+- App-like interfaces mimicking iOS long-press → context menu expansion++## How it works+On click, measure the button's position with `getBoundingClientRect()`, then compute the origin point relative to the modal's final centered position:++```js+function openModal(triggerBtn) {+ const stageRect = stage.getBoundingClientRect();+ const btnRect = triggerBtn.getBoundingClientRect();+ const modalRect = modal.getBoundingClientRect();++ // Button center relative to stage+ const bx = btnRect.left + btnRect.width/2 - stageRect.left;+ const by = btnRect.top + btnRect.height/2 - stageRect.top;++ // Modal center in stage+ const mx = stageRect.width / 2;+ const my = stageRect.height / 2;++ // Origin point relative to modal's top-left corner+ const ox = bx - mx + modalRect.width/2;+ const oy = by - my + modalRect.height/2;++ modal.style.transformOrigin = `${ox}px ${oy}px`;+ modal.classList.add('open');+}+```++```css+:root {+ --modal-dur: 320ms;+ --modal-ease: cubic-bezier(.34, 1.3, .64, 1);+ --start-scale: 0.1;+}++.modal {+ position: absolute;+ top: 50%; left: 50%;+ transform: translate(-50%, -50%) scale(var(--start-scale));+ opacity: 0;+ transition: transform var(--modal-dur) var(--modal-ease),+ opacity 200ms ease;+ pointer-events: none;+}+.modal.open {+ transform: translate(-50%, -50%) scale(1);+ opacity: 1;+ pointer-events: auto;+}+```++The springy easing (`cubic-bezier(.34, 1.3, .64, 1)`) causes a slight overshoot, giving the modal a satisfying "pop" as it settles into position.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 320ms | 200–400ms — longer than hover, shorter than a page transition |+| Start scale | 0.1 | 0.05–0.3; too large and the grow effect is invisible; too small and it flickers |+| Easing | Springy | Overshoot makes the arrival feel physical; ease-out is more conservative |+| Backdrop fade | 200ms | Independent from modal — the backdrop can fade in faster |++## Production notes+- **Recalculate `transform-origin` on resize**: if the user resizes the window between opens, the cached origin is stale. Recalculate in the click handler, not at mount time.+- **Dismiss animation**: reverse the effect on close — scale back down toward the origin point. This requires keeping track of which button was last used to open the modal.+- **Focus management**: move focus into the modal on open (`modal.querySelector('button, input, [tabindex]')?.focus()`). Return focus to the trigger button on close.+- **`<dialog>` element**: the native `<dialog>` element handles focus trapping and Escape key automatically. Animate it with `::backdrop` for the overlay and `@starting-style` (Chrome 117+) for entry animation without JavaScript class toggling.+- **Framer Motion**: `<motion.div initial={{ scale: 0.1, originX: "50%", originY: "50%" }} animate={{ scale: 1 }} />`. For dynamic origins, pass computed values as motion props.+- **GSAP**: `gsap.fromTo(modal, { scale: 0.1, transformOrigin: `${ox}px ${oy}px` }, { scale: 1, duration: 0.32, ease: "back.out(1.5)" })`.++## See also+- [Drawer / Panel Slide](../drawer-slide/) — for content that slides from an edge rather than expanding from a point+- [Tooltip Reveal](../tooltip-reveal/) — for small supplementary content that doesn't need a full modal+- [FLIP Technique](../../03-page-transitions/flip-technique/) — the positional measurement technique underlying this animationdiff --git a/animations/04-micro-interactions/progress-animation/README.md b/animations/04-micro-interactions/progress-animation/README.mdnew file mode 100644index 00000000..4bbf743b--- /dev/null+++ b/animations/04-micro-interactions/progress-animation/README.md@@ -0,0 +1,87 @@+# Progress Animation++## What it is+A progress animation visualizes completion percentage through a filling shape — a horizontal bar, a circular ring, or a stepped sequence. It differs from a spinner in that it conveys specific information: how much is done and how much remains. This reduces user anxiety during long operations and sets accurate expectations about wait time.++## When to use it+- File uploads and downloads where byte progress is available+- Multi-step forms and onboarding flows (5-step wizard, 3 of 5 complete)+- Installation and build processes+- Reading progress indicators on long-form articles+- Any operation where `loaded / total` can be computed++## How it works+**Linear bar**: update `width` via a CSS transition, or animate it manually with `requestAnimationFrame` for easing control:++```css+.prog-fill {+ height: 100%;+ background: #58a6ff;+ width: 0%;+ transition: width 2000ms ease-out;+}+```++```js+// Or with rAF for custom easing:+function animateProgress(target, duration) {+ const start = performance.now();+ function tick(now) {+ const t = Math.min((now - start) / duration, 1);+ const eased = 1 - (1 - t) ** 3; // ease-out cubic+ fill.style.width = (target * eased) + '%';+ if (t < 1) requestAnimationFrame(tick);+ }+ requestAnimationFrame(tick);+}+```++**Circular ring** uses `stroke-dashoffset` on an SVG circle. The circumference of a circle with `r=32` is `2π × 32 ≈ 201px`:++```css+circle {+ fill: none; stroke: #58a6ff; stroke-width: 6;+ stroke-dasharray: 201;+ stroke-dashoffset: 201; /* fully hidden */+ transition: stroke-dashoffset 2s ease-out;+}+```++```js+// p = progress 0..1+circle.style.strokeDashoffset = 201 * (1 - p);+```++**Indeterminate bar** (unknown duration): use an infinite sliding animation instead:++```css+.indet {+ animation: slide 2s ease-in-out infinite;+ width: 40%;+}+@keyframes slide {+ 0% { transform: translateX(-150%); }+ 100% { transform: translateX(350%); }+}+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 2000ms | Match to actual estimated load time; animated progress that finishes early stalls |+| Easing | ease-out | Decelerating fill feels natural — fast start, slow near 100% |+| Circumference | 201px (r=32) | `2π × r`; scales with radius choice |+| Step count | 5 | 3–7 steps; more than 8 steps individual dots become unreadable |++## Production notes+- **Don't fake progress**: animating to 90% and stalling while waiting for a response (common pattern) is deceptive and erodes trust. Either animate to an honest checkpoint, or use indeterminate mode.+- **`transition` vs `rAF`**: CSS `transition` is simpler but can't be paused or reversed mid-flight. `rAF` gives full control — necessary for chunked uploads where progress arrives in bursts.+- **Accessibility**: wrap the progress bar in `<progress value="60" max="100">` or add `role="progressbar"`, `aria-valuenow`, `aria-valuemin`, and `aria-valuemax` attributes.+- **GSAP**: `gsap.to(fill, { width: "75%", duration: 2, ease: "power2.out" })`. For circular rings, animate `strokeDashoffset` directly.+- **React**: the HTML `<progress>` element is accessible out of the box. Radix UI's `<Progress>` provides a headless, styled alternative.++## See also+- [Loading Spinner](../loading-spinner/) — for unknown-duration loads+- [Skeleton Loader](../skeleton-loader/) — content-shaped placeholder while loading+- [Checkmark Draw](../checkmark-draw/) — success state after progress reaches 100%+- [Progress Bar](../../01-scroll-based/progress-bar/) — scroll-driven reading progress variantdiff --git a/animations/04-micro-interactions/shimmer-effect/README.md b/animations/04-micro-interactions/shimmer-effect/README.mdnew file mode 100644index 00000000..2885e5e6--- /dev/null+++ b/animations/04-micro-interactions/shimmer-effect/README.md@@ -0,0 +1,66 @@+# Shimmer Effect++## What it is+A shimmer effect is a diagonal or horizontal gradient highlight that sweeps repeatedly across skeleton placeholder blocks. Where a skeleton pulse fades opacity up and down uniformly, a shimmer moves directionally — giving the impression that data is streaming in from one side. It is a more sophisticated loading state that reads as active progress rather than passive waiting.++## When to use it+- Card and list skeleton loaders where the content streams from a server+- Premium or branded loading experiences where skeleton pulse alone feels too plain+- Any skeleton component where the motion direction matches the data source (left-to-right for left-aligned content)++## How it works+A `::after` pseudo-element containing a translucent gradient is positioned absolutely over the skeleton block and translated from `-100%` to `+200%`:++```css+:root {+ --shim-dur: 1500ms;+ --shim-bright: 0.25;+}++.skel-card {+ position: relative;+ overflow: hidden;+}++.skel-card::after {+ content: '';+ position: absolute;+ inset: 0;+ background: linear-gradient(+ 90deg,+ transparent 25%,+ rgba(255,255,255,var(--shim-bright)) 50%,+ transparent 75%+ );+ background-size: 200% 100%;+ animation: shimmer var(--shim-dur) linear infinite;+}++@keyframes shimmer {+ from { background-position: 200% 0; }+ to { background-position: -200% 0; }+}+```++The `background-size: 200% 100%` and position animation gives more control over the highlight width than `translateX` alone.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 1500ms | 1–2s per sweep is the perceptible range; under 800ms feels frantic |+| Brightness | 0.25 | Highlight opacity — 0.1 is subtle, 0.5 is bright-branded |+| Angle | 90° (horizontal) | Diagonal (`-45deg`) can look more dynamic; keep consistent across components |+| Color | White | Gold or blue for branded variants; stay translucent to work on any skeleton bg |++## Production notes+- **Single direction only**: multiple shimmer components sweeping in different directions simultaneously create visual chaos. All skeletons on a page should shimmer in the same direction.+- **`overflow: hidden` required**: the shimmer pseudo-element extends beyond the card. Without overflow clipping, it bleeds into adjacent elements.+- **Combining with pulse**: the demo supports pulse + shimmer together. In practice, pick one — both simultaneously are redundant and visually loud.+- **Performance**: shimmer uses `background-position` animation rather than `transform`. While `transform` is typically preferred, background-position on a GPU-composited layer is acceptably performant. Alternatively, `translateX` with `will-change: transform` on the pseudo-element is the most performant approach.+- **CSS-only**: no JavaScript required. The animation is infinite and stops automatically when the element is removed from DOM.+- **React**: `react-loading-skeleton` includes shimmer. For custom components, the CSS pattern above is framework-agnostic.++## See also+- [Skeleton Loader](../skeleton-loader/) — the underlying placeholder structure shimmer enhances+- [Loading Spinner](../loading-spinner/) — alternative for unknown-duration loads+- [Progress Animation](../progress-animation/) — when duration or percentage is knowndiff --git a/animations/04-micro-interactions/skeleton-loader/README.md b/animations/04-micro-interactions/skeleton-loader/README.mdnew file mode 100644index 00000000..6aee9f21--- /dev/null+++ b/animations/04-micro-interactions/skeleton-loader/README.md@@ -0,0 +1,65 @@+# Skeleton Loader++## What it is+A skeleton loader is a set of placeholder shapes — gray blocks matching the layout of real content — displayed while data loads. The blocks pulse subtly to signal active loading. Unlike a spinner, a skeleton tells the user what shape of content is coming, which measurably reduces perceived wait time even when actual load time is identical.++## When to use it+- Social feeds, cards, and lists where content arrives from an API+- Dashboard widgets that load independently+- Image galleries where dimensions are known before the image loads+- Any interface where users would otherwise stare at a blank white area++## How it works+Skeleton blocks are plain `<div>` elements styled to match the shape of expected content. A CSS animation pulses their opacity:++```css+.skel {+ background: #1a1f28;+ border-radius: 4px;+ animation: pulse 1.5s ease-in-out infinite;+}++@keyframes pulse {+ 0%, 100% { opacity: 0.5; }+ 50% { opacity: 1; }+}+```++When real content arrives, fade the skeleton out and the content in:++```js+async function load() {+ showSkeleton();+ const data = await fetchData();+ hideSkeleton();+ showContent(data);+}++function hideSkeleton() {+ skeletonEl.style.display = 'none';+ contentEl.style.opacity = '1'; // triggers CSS transition+}+```++The content element needs `opacity: 0; transition: opacity 400ms ease` to fade in smoothly.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Pulse speed | 1.5s | 1–2s is the natural breathing range; faster feels anxious |+| Min opacity | 0.5 | Lower = more dramatic pulse; 0.4–0.6 is subtle |+| Shape fidelity | Medium | Match line heights, avatar sizes, image ratios exactly for best effect |+| Content fade | 400ms | Instant swap feels jarring; 300–500ms is smooth |++## Production notes+- **Shape matching matters**: a skeleton that doesn't match the incoming content causes layout shift and undermines the effect. Measure real content dimensions and match them.+- **Avoid animating too many skeletons simultaneously** on a single page — 3–4 independent pulsing elements is the limit before the screen starts to feel chaotic.+- **Real data approximation**: if you know the content length, dynamically size the skeleton lines to match (e.g., profile names are typically 1–2 lines; descriptions are 3–4).+- **`prefers-reduced-motion`**: disable the pulse animation entirely for users who request it. A static gray block is still a valid skeleton loader.+- **React**: `react-loading-skeleton` (by Dvtng) is the standard library. It auto-matches skeleton widths to inline text nodes.+- **Pairing**: skeleton + shimmer (see [Shimmer Effect](../shimmer-effect/)) is the most polished loading state — pulse for structure, shimmer for motion.++## See also+- [Shimmer Effect](../shimmer-effect/) — gradient sweep enhancement for skeleton loaders+- [Loading Spinner](../loading-spinner/) — alternative for unknown-duration loads+- [Progress Animation](../progress-animation/) — alternative when total progress is knowndiff --git a/animations/04-micro-interactions/toggle-switch/README.md b/animations/04-micro-interactions/toggle-switch/README.mdnew file mode 100644index 00000000..bcd60dbb--- /dev/null+++ b/animations/04-micro-interactions/toggle-switch/README.md@@ -0,0 +1,70 @@+# Toggle / Switch Slide++## What it is+A toggle switch is a binary control — on or off — where the thumb pill slides horizontally between states. Unlike a checkbox, which changes state instantly, a toggle communicates the transition between states through motion. The animation duration and easing determine whether the control feels mechanical, weighted, or springy.++## When to use it+- Settings and preferences panels (notifications on/off, dark mode, feature flags)+- Any binary option where the visual metaphor of a physical switch aids comprehension+- Mobile-first UIs where toggles are more tap-friendly than checkboxes+- Inline toggles within table rows or list items++## How it works+The toggle is built entirely in CSS using a hidden `<input type="checkbox">`. The track background and thumb position both transition on `:checked`:++```html+<label class="sw">+ <input type="checkbox">+ <span class="track"></span>+ <span class="thumb"></span>+</label>+```++```css+:root {+ --tog-dur: 200ms;+ --tog-ease: cubic-bezier(.4, 0, .2, 1);+ --on-color: #58a6ff;+}++.sw { position: relative; display: inline-block; width: 52px; height: 30px; }+.sw input { position: absolute; opacity: 0; width: 0; height: 0; }++.track {+ position: absolute; inset: 0; border-radius: 15px;+ background: #21262d;+ transition: background var(--tog-dur) var(--tog-ease);+}+.thumb {+ position: absolute; top: 3px; left: 3px;+ width: 24px; height: 24px; border-radius: 50%; background: #fff;+ transition: transform var(--tog-dur) var(--tog-ease);+ box-shadow: 0 1px 4px rgba(0,0,0,.4);+}++.sw input:checked ~ .track { background: var(--on-color); }+.sw input:checked ~ .thumb { transform: translateX(22px); }+```++For an elastic feel, swap the thumb transition easing to `cubic-bezier(.34, 1.56, .64, 1)` — this causes a slight overshoot before settling.++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Duration | 200ms | Under 120ms = mechanical; over 350ms = sluggish |+| Easing | Material smooth | `cubic-bezier(.4,0,.2,1)` — weighted deceleration |+| Thumb travel | 22px | (track width - 2×padding - thumb width) |+| On color | accent blue | Must contrast 3:1 with the thumb color (white) |++## Production notes+- **Accessibility**: the hidden `<input type="checkbox">` provides keyboard control, `aria-checked` state, and screen reader announcements for free — no JS needed for state management.+- **Label wrapping**: wrapping the entire component in `<label>` makes the full surface (track + thumb) the click/tap target — no `for`/`id` wiring required.+- **`touch-action: manipulation`**: add this to the label to suppress the 300ms delay on mobile browsers.+- **Elastic easing pitfall**: the spring overshoot in `cubic-bezier(.34,1.56,.64,1)` can clip visually if the thumb reaches the edge of the track before the bounce completes. Add 1–2px of extra track padding to compensate.+- **Headless UI / Radix UI**: `<Switch>` components handle all ARIA and keyboard events. Style via `data-state="checked"` attribute.+- **Framer Motion**: animate the `x` value of a `<motion.div>` between 0 and the track width — simpler than CSS for controlled components.++## See also+- [Button Press Scale](../button-press-scale/) — press-down feedback on toggle tap+- [Form Field Morph](../form-field-morph/) — another input state transition pattern+- [Accordion Open/Close](../accordion/) — another binary expand/collapse patterndiff --git a/animations/04-micro-interactions/tooltip-reveal/README.md b/animations/04-micro-interactions/tooltip-reveal/README.mdnew file mode 100644index 00000000..6fc903a5--- /dev/null+++ b/animations/04-micro-interactions/tooltip-reveal/README.md@@ -0,0 +1,82 @@+# Tooltip Reveal++## What it is+A tooltip is a small floating label that appears near an element on hover (or focus), providing supplementary information that doesn't fit inline. The reveal animation — typically a fade combined with a subtle scale — makes the tooltip feel responsive rather than jarring. A delay before showing (300ms) prevents tooltips from triggering on accidental cursor pass-through.++## When to use it+- Icon buttons without visible text labels+- Truncated text that needs to show the full content on hover+- Form fields with validation rules or format requirements+- Data visualization elements (chart bars, graph nodes) that show exact values on hover++## How it works+The tooltip is positioned absolutely relative to the trigger, initially invisible. On hover it fades and scales in after a `setTimeout` delay. On mouse-leave it hides after a short second delay — allowing the user to move the cursor from trigger to tooltip without it disappearing:++```css+.tooltip {+ position: absolute;+ bottom: calc(100% + 8px);+ left: 50%;+ transform: translateX(-50%) scale(0.95);+ background: #1e2433;+ border: 1px solid #21262d;+ padding: 7px 10px;+ border-radius: 6px;+ font-size: 11px;+ opacity: 0;+ pointer-events: none;+ transition: opacity 150ms ease, transform 150ms ease;+ white-space: nowrap;+}++.tooltip.visible {+ opacity: 1;+ transform: translateX(-50%) scale(1);+}+```++```js+let showTimer, hideTimer;++trigger.addEventListener('mouseenter', () => {+ clearTimeout(hideTimer);+ showTimer = setTimeout(() => tip.classList.add('visible'), 300);+});++trigger.addEventListener('mouseleave', () => {+ clearTimeout(showTimer);+ hideTimer = setTimeout(() => tip.classList.remove('visible'), 100);+});++// Keyboard support+trigger.addEventListener('focusin', () => {+ clearTimeout(hideTimer);+ showTimer = setTimeout(() => tip.classList.add('visible'), 300);+});+trigger.addEventListener('focusout', () => {+ clearTimeout(showTimer);+ hideTimer = setTimeout(() => tip.classList.remove('visible'), 100);+});+```++## Key parameters+| Parameter | Default | Effect |+|-----------|---------|--------|+| Show delay | 300ms | Prevents flash on cursor pass-through — the most important parameter |+| Hide delay | 100ms | Keeps tooltip alive briefly so the cursor can move onto it |+| Animation duration | 150ms | Fast enough to feel instant; slow enough to be perceivable |+| Scale start | 0.95 | Subtle — scale from 0.9 or less feels like a popup, not a tooltip |++## Production notes+- **The 300ms rule**: without a show delay, every cursor movement across the page triggers tooltip flashes. 300ms is the minimum that feels responsive without being annoying. 200ms can work if the tooltip is very small.+- **Smart positioning**: the demo positions tooltips in fixed directions. Production implementations need viewport-aware positioning — flip the tooltip when it would overflow the edge. Floating UI (by Atomics Design) handles this automatically.+- **Touch devices**: tooltips have no hover trigger on touch. Long-press or a dedicated info button is the touch equivalent. The demo uses `touchstart` to toggle visibility as a fallback.+- **`pointer-events: none`** on the tooltip prevents it from intercepting mouse events when using the `hide-delay` technique of allowing cursor movement onto the tooltip.+- **WCAG 1.4.13 (Content on Hover or Focus)**: the tooltip must be dismissible without moving the cursor (e.g., Escape key), hoverable itself without disappearing, and persistent until the cursor moves away. The 100ms hide delay satisfies "hoverable."+- **Floating UI / Popper.js**: production-grade positioning library. `computePosition()` with `flip` and `shift` middleware handles all edge cases.+- **Radix UI Tooltip**: `<Tooltip.Root>`, `<Tooltip.Trigger>`, `<Tooltip.Content>` — fully accessible, WCAG 1.4.13 compliant, animation-ready.++## See also+- [Hover State Animation](../hover-state/) — hover feedback on the trigger element+- [Badge Pulse](../badge-pulse/) — persistent attention indicator vs. hover-triggered info+- [Modal Expand](../modal-expand/) — for content too large for a tooltip