diff --git a/.claude/skills/EMIL-SKILLS-LICENSE b/.claude/skills/EMIL-SKILLS-LICENSE new file mode 100644 index 0000000000..57b46f1fd1 --- /dev/null +++ b/.claude/skills/EMIL-SKILLS-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Emil Kowalski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.claude/skills/EMIL-SKILLS-README.md b/.claude/skills/EMIL-SKILLS-README.md new file mode 100644 index 0000000000..aafd734a4b --- /dev/null +++ b/.claude/skills/EMIL-SKILLS-README.md @@ -0,0 +1,16 @@ +# Emil Kowalski's skills + +These skills come from [emilkowalski/skills](https://github.com/emilkowalski/skills) at commit +`cdc447ac47ade70daa931b5134a56f9ba0b26e95`, under the MIT licence in `EMIL-SKILLS-LICENSE`: + +animate, animate-expo, animation-performance, animation-vocabulary, apple-design, ask-emil, +ask-sonner, break-ui, choreograph, emil-design-eng, find-animation-opportunities, gestures, +improve-animations, learn-taste, mobile-native, pick-ui-library, prototype, remove-animations, +review-animations, write-swift. + +They are copied as they are. Where one disagrees with OpenBot's own rules +([docs/design-system.md](../../docs/design-system.md), [docs/app-guidelines.md](../../docs/app-guidelines.md), +the `openbot-*` skills), OpenBot's rules win: no new token without agreeing it first, no second look, +and a change to a primitive lands in a pull request of its own. + +To update them, copy the `skills/` folder of a newer commit over these folders and change the commit above. diff --git a/.claude/skills/JAKUB-SKILLS-LICENSE b/.claude/skills/JAKUB-SKILLS-LICENSE new file mode 100644 index 0000000000..6a067e906e --- /dev/null +++ b/.claude/skills/JAKUB-SKILLS-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Jakub Krehel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.claude/skills/JAKUB-SKILLS-README.md b/.claude/skills/JAKUB-SKILLS-README.md new file mode 100644 index 0000000000..90bf8c2be0 --- /dev/null +++ b/.claude/skills/JAKUB-SKILLS-README.md @@ -0,0 +1,16 @@ +# Jakub Krehel's skills + +These skills come from [jakubkrehel/skills](https://github.com/jakubkrehel/skills) at commit +`672ae44ace6aaed65b86cbb1e2fd6fbea0e79578`, under the MIT licence in `JAKUB-SKILLS-LICENSE`: + +better-accessibility, better-colors, better-interface, better-layout, better-motion, +better-typography, better-ui, better-writing, interface-review. + +They were installed with `npx skills add jakubkrehel/skills --skill -a claude-code`, which +records them in `skills-lock.json`, and are copied as they are. Where one disagrees with OpenBot's +own rules ([docs/design-system.md](../../docs/design-system.md), +[docs/app-guidelines.md](../../docs/app-guidelines.md), the `openbot-*` skills), OpenBot's rules +win: words follow `openbot-copy`, no new token without agreeing it first, no second look, and a +change to a primitive lands in a pull request of its own. + +To update them, run the same command again and change the commit above. diff --git a/.claude/skills/animate-expo/RECIPES.md b/.claude/skills/animate-expo/RECIPES.md new file mode 100644 index 0000000000..5f702a71a9 --- /dev/null +++ b/.claude/skills/animate-expo/RECIPES.md @@ -0,0 +1,386 @@ +# Expo Animation Recipes + +Ready-to-build implementations for the cases that come up most in a React Native app. Start from the recipe, then adapt. + +--- + +## Setup the recipes assume + +```bash +npx expo install react-native-reanimated react-native-worklets react-native-gesture-handler expo-haptics +``` + +(`react-native-keyboard-controller` only for the keyboard recipe.) `expo install`, not `npm install` — it resolves the versions that match the SDK. The worklets Babel plugin is configured by `babel-preset-expo` automatically. + +`GestureHandlerRootView` wraps the app once — in Expo Router, the root `_layout`: + +```jsx +import { GestureHandlerRootView } from 'react-native-gesture-handler'; + +export default function RootLayout() { + return ( + + + + ); +} +``` + +Imports and constants every recipe below shares: + +```js +import { useState, useEffect, useMemo } from 'react'; +import Animated, { + useSharedValue, useAnimatedStyle, useAnimatedScrollHandler, useAnimatedReaction, + withSpring, withTiming, cancelAnimation, interpolate, Extrapolation, Easing, + FadeInDown, FadeOutDown, LinearTransition, +} from 'react-native-reanimated'; +import { Gesture, GestureDetector } from 'react-native-gesture-handler'; +import { scheduleOnRN } from 'react-native-worklets'; +import * as Haptics from 'expo-haptics'; + +const EASE_OUT = Easing.bezier(0.23, 1, 0.32, 1); // strong ease-out for UI +const EASE_IN_OUT = Easing.bezier(0.77, 0, 0.175, 1); // on-screen movement +const EASE_SHEET = Easing.bezier(0.32, 0.72, 0, 1); // iOS sheet curve +``` + +Three conventions, explained once here instead of in every recipe: + +- **Shared values are read and written with `.get()` / `.set()`**, the form the Reanimated docs recommend for React Compiler support. `.value` still works, but the compiler can't see through it. +- **`scheduleOnRN(fn, ...args)` replaces the deprecated `runOnJS(fn)(...args)`** for calling back to the React Native runtime from a worklet. +- **Gestures are wrapped in `useMemo`.** Rebuilding a gesture on every render can reattach the recognizer and drop a drag that's mid-flight. + +**Gesture Handler v3:** Expo installs v2, and the recipes use its `Gesture.Pan()` builder. If the project is already on v3, the builder is legacy — each gesture is a hook taking one config object, with `onStart` → `onActivate`, `onEnd` → `onDeactivate`, and the `success` flag replaced by `event.canceled` (inverted). The hook manages its own identity, so drop the `useMemo`: + +```jsx +const pan = usePanGesture({ + activeOffsetY: [-10, 10], + onActivate: () => { context.set(translateY.get()); }, + onUpdate: (e) => { translateY.set(context.get() + e.translationY); }, + onDeactivate: (e) => { /* settle with withSpring as below */ }, +}); +``` + +--- + +## Two worklets you'll need everywhere + +Momentum projection decides *where a flick was going*, so a fast short swipe commits and a slow long one doesn't. Rubber-banding makes a boundary resist instead of stopping dead. + +```js +// Where the finger would come to rest if it kept decelerating. +// Apple's exponential-decay form — not the v²/2a from physics class. +function project(velocity, decelerationRate = 0.998) { + 'worklet'; + return ((velocity / 1000) * decelerationRate) / (1 - decelerationRate); +} + +// The further past the edge, the less the element follows. +function rubberband(overshoot, dimension, constant = 0.55) { + 'worklet'; + return (overshoot * dimension * constant) / (dimension + constant * Math.abs(overshoot)); +} +``` + +--- + +## Press feedback + +Every pressable in the app. This passes the frequency gate only because it's near-imperceptible: 120ms and a 3% scale, inside the 100–150ms press budget — anything longer or larger belongs to rarer moments, per step 1 in SKILL.md. No gesture, no shared value — a CSS transition is the whole implementation. + +```jsx +import Animated from 'react-native-reanimated'; +import { Pressable, StyleSheet } from 'react-native'; + +function PressableScale({ onPress, children }) { + const [pressed, setPressed] = useState(false); + return ( + setPressed(true)} + onPressOut={() => setPressed(false)} + hitSlop={12} + pressRetentionOffset={16} + > + {children} + + ); +} + +const styles = StyleSheet.create({ + box: { + transform: [{ scale: 1 }], + transitionProperty: 'transform', + transitionDuration: '120ms', + transitionTimingFunction: 'cubic-bezier(0.23, 1, 0.32, 1)', + }, + pressed: { transform: [{ scale: 0.97 }] }, +}); +``` + +`setState` is fine here — it fires twice per press, not per frame. `hitSlop` brings a small icon up to the 44pt target without growing it; `pressRetentionOffset` stops a slight finger drift from cancelling. + +--- + +## Bottom sheet you can drag to dismiss + +Before writing this: if the sheet is its own destination, use `presentation: 'formSheet'` (see **Screen transitions**) and get the platform's real sheet for free. Build this only when the sheet has to live inside an existing screen. + +```jsx +const translateY = useSharedValue(0); +const context = useSharedValue(0); + +const pan = useMemo(() => Gesture.Pan() + .activeOffsetY([-10, 10]) // let a horizontal swipe win; require intent before committing + .onStart(() => { + cancelAnimation(translateY); // stop a running spring so the grab doesn't jump + context.set(translateY.get()); // start from the current on-screen value, not from 0 + }) + .onUpdate((e) => { + const next = context.get() + e.translationY; + // downward is free; upward past the top resists + translateY.set(next >= 0 ? next : rubberband(next, HEIGHT)); + }) + .onEnd((e) => { + const projected = translateY.get() + project(e.velocityY); + if (projected > HEIGHT * 0.4) { + translateY.set(withSpring(HEIGHT, { + duration: 300, dampingRatio: 1, velocity: e.velocityY, overshootClamping: true, + }, (finished) => { if (finished) scheduleOnRN(onClose); })); + } else { + translateY.set(withSpring(0, { duration: 300, dampingRatio: 0.8, velocity: e.velocityY })); + scheduleOnRN(Haptics.impactAsync, Haptics.ImpactFeedbackStyle.Light); // it snapped home + } + }), [onClose]); + +const sheetStyle = useAnimatedStyle(() => ({ transform: [{ translateY: translateY.get() }] })); +``` + +The four details that separate this from a bad drag: + +- **`onStart` captures the current value.** Without it, grabbing a sheet mid-animation teleports it — the animation must continue from where the eye last saw it. +- **Velocity decides, not distance.** `project()` means a quick flick dismisses even a few pixels down. Requiring 40% travel makes the sheet feel heavy. +- **Velocity is handed to the spring**, so there's no seam between the finger releasing and the animation continuing. This is the single detail that most separates "fluid" from "fine". +- **`overshootClamping` on dismissal** — otherwise the sheet springs past the bottom of the screen and flashes a gap. + +The backdrop derives from the same value, so it's always in sync and costs nothing: + +```jsx +const backdropStyle = useAnimatedStyle(() => ({ + opacity: interpolate(translateY.get(), [0, HEIGHT], [1, 0], Extrapolation.CLAMP), +})); +``` + +--- + +## Swipe to delete a row + +Before writing this: gesture-handler ships [`ReanimatedSwipeable`](https://docs.swmansion.com/react-native-gesture-handler/docs/components/reanimated_swipeable/), which already does swipe-to-reveal actions — thresholds, overshoot, open/close methods — on the UI thread. Reach for it when the row reveals action buttons. Build the gesture yourself only when the interaction is different in kind: swipe-to-commit with momentum projection, like this one. + +```jsx +const x = useSharedValue(0); +const context = useSharedValue(0); + +const pan = useMemo(() => Gesture.Pan() + .activeOffsetX([-10, 10]) // must declare the axis, or it fights the vertical scroll + .onStart(() => { cancelAnimation(x); context.set(x.get()); }) // grab mid-spring continues from where the row is, not from 0 + .onUpdate((e) => { x.set(Math.min(0, context.get() + e.translationX)); }) + .onEnd((e) => { + const projected = x.get() + project(e.velocityX); + if (projected < -SWIPE_THRESHOLD) { + x.set(withTiming(-WIDTH, { duration: 200, easing: EASE_OUT }, (f) => { + if (f) scheduleOnRN(onDelete, id); + })); + } else { + x.set(withSpring(0, { duration: 300, dampingRatio: 1, velocity: e.velocityX })); + } + }), [onDelete, id]); +``` + +Closing the gap the deleted row left is the list's job, not the row's: + +```jsx +const ROW_CLOSE = LinearTransition.duration(200); // module scope — builders rebuilt in render cost every re-render + + +``` + +`activeOffsetX` is the mobile-specific part. A pan handler inside a scroll view with no axis declared will steal vertical scrolls, and the list will feel broken in a way that looks like a scrolling bug rather than a gesture bug. + +--- + +## Collapsing header on scroll + +```jsx +const scrollY = useSharedValue(0); +const onScroll = useAnimatedScrollHandler((e) => { scrollY.set(e.contentOffset.y); }); + +const titleStyle = useAnimatedStyle(() => ({ + opacity: interpolate(scrollY.get(), [0, 60], [1, 0], Extrapolation.CLAMP), + transform: [{ translateY: interpolate(scrollY.get(), [0, 60], [0, -12], Extrapolation.CLAMP) }], +})); + + +``` + +**Never animate the header's `height` to collapse it.** That runs a layout pass on the header and everything below it on every scroll frame — the one animation guaranteed to stutter, because it's competing with the scroll itself. Give the container a fixed height and translate the content inside it, clipping with `overflow: 'hidden'`. + +`Extrapolation.CLAMP` is not optional: without it, scrolling past 60 keeps driving `translateY` past −12 and the title slides out of its container. + +--- + +## List entrances + +```jsx +// The Reanimated docs recommend building layout animations outside components, +// or in useMemo — an inline chain in JSX rebuilds the builder on every render. +// A per-index delay can't live at module scope, so the row memoizes its own: +function Row({ item, index }) { + const entering = useMemo(() => FadeInDown.duration(250).delay(index * 40), [index]); + return {/* ... */}; +} + +{items.map((item, i) => )} +``` + +Stagger 30–80ms. Longer feels slow, shorter reads as simultaneous. + +**Never put `entering` on a row inside `FlatList`, `FlashList`, or any virtualized list.** Rows are recycled, so the animation re-fires every time one scrolls back into view — the list appears to flicker while the user scrolls. Animate the list container once on mount, or use `itemLayoutAnimation` for reflow only. + +Entrance animations are for content the user asked for and is waiting on. A list they scroll past all day should already be there. + +--- + +## Keyboard-synced UI + +Needs its own module and a one-time provider ([Expo keyboard guide](https://docs.expo.dev/guides/keyboard-handling/)): + +```bash +npx expo install react-native-keyboard-controller +``` + +```jsx +import { KeyboardProvider } from 'react-native-keyboard-controller'; + +// Root _layout, next to GestureHandlerRootView — hooks below do nothing without it. + + + +``` + +```jsx +import { useReanimatedKeyboardAnimation } from 'react-native-keyboard-controller'; + +const { height } = useReanimatedKeyboardAnimation(); // 0 → -keyboardHeight, on the UI thread +const footerStyle = useAnimatedStyle(() => ({ transform: [{ translateY: height.get() }] })); +``` + +Never build this from `Keyboard.addListener` plus a timing animation. The keyboard rides a private system curve, the event arrives on the JS thread after the keyboard has already started moving, and any duration you pick will visibly lag or lead it. The UI must be driven by the keyboard's actual position, frame by frame. + +--- + +## Tab / segmented indicator + +Measure once, then animate transforms. + +```jsx +const [layouts, setLayouts] = useState({}); // measured with onLayout, not per frame +const x = useSharedValue(0); +const w = useSharedValue(0); + +useEffect(() => { + const l = layouts[active]; + if (!l) return; + x.set(withTiming(l.x, { duration: 250, easing: EASE_IN_OUT })); + w.set(withTiming(l.width, { duration: 250, easing: EASE_IN_OUT })); +}, [active, layouts]); + +const pillStyle = useAnimatedStyle(() => ({ + transform: [{ translateX: x.get() }], + width: w.get(), +})); +``` + +This is the sanctioned `width` animation: the pill is absolutely positioned with no children, so nothing else re-lays-out, and its corner radius survives — `scaleX` would smear the corners into ovals. + +`ease-in-out`, because the pill is moving across the screen rather than entering or leaving it. Fire `Haptics.selectionAsync()` on the press, not when the pill lands. + +--- + +## Screen transitions (Expo Router) + +Configure the native stack. Never rebuild a screen transition in JS: the native one runs on the platform side, keeps the interactive back gesture, and matches every other app on the device. + +```jsx + + + + + +``` + +| Navigation | Option | +| --- | --- | +| Deeper into a hierarchy | `animation: 'default'` — the platform push, unmodified | +| A self-contained task the user can abandon | `presentation: 'modal'` | +| A short interruption: picker, filter, share | `presentation: 'formSheet'` with detents | +| Between tabs | `animation: 'none'` | +| Reduced motion | `animation: 'fade'` | + +`animationMatchesGesture: true` makes the iOS back swipe run your transition in reverse under the finger, instead of the default push. Set it whenever you set a custom `animation`, or dragging back looks like a different app than pushing forward. + +`formSheet` is native on both platforms, but not the same on both — the [Expo modal docs](https://docs.expo.dev/router/advanced/modals/#form-sheet-presentation) have the full list: + +- **Android caps detents at three.** A longer `sheetAllowedDetents` array works on iOS and silently truncates on Android — design for three. +- **`sheetGrabberVisible` is iOS-only.** Android shows no grabber; don't rely on it as the only "this is draggable" affordance. +- **Android form sheets can't host native headers or nested stacks.** Keep the sheet's content a single screen; if it needs its own navigation, use `presentation: 'modal'` instead. +- **`fitToContents` needs explicitly sized content.** A `flex: 1` root has no intrinsic height to fit — size the content, or the detent is wrong. + +--- + +## Toast + +```jsx +// Module scope — layout-animation builders live outside the component. +const TOAST_ENTER = FadeInDown.duration(300).easing(EASE_OUT); +const TOAST_EXIT = FadeOutDown.duration(250).easing(EASE_OUT); + + +``` + +- **The 300ms cap holds here too.** The web exception is Sonner's 400ms toast; on native a toast is uninvited, so if anything it should be quicker and quieter than motion the user asked for. +- **It exits the way it entered.** Entering from the bottom and leaving to the side reads as two unrelated elements. +- **Exit ~20% faster than entry.** The user has finished reading; the arrival deserves the time, the departure doesn't. +- **Safe area insets, always.** A toast at `bottom: 16` sits under the home indicator on every modern iPhone. + +If toasts stack and the list reflows, add `itemLayoutAnimation` and expect to tune the opacity against the reflow by eye — there's no formula for that pair. Look at it again the next day. + +--- + +## Firing something once at a threshold + +When a crossing point matters — a detent, a snap, a pull-to-refresh arming — don't poll it from JS and don't `scheduleOnRN` every frame. + +```jsx +const armed = useSharedValue(false); + +useAnimatedReaction( + () => pullDistance.get() > REFRESH_THRESHOLD, + (isArmed, wasArmed) => { + if (isArmed !== wasArmed) { + armed.set(isArmed); + scheduleOnRN(Haptics.impactAsync, Haptics.ImpactFeedbackStyle.Light); + } + } +); +``` + +The comparison runs on the UI thread every frame; the JS call happens twice per pull. That's the pattern for every "do something when the animation reaches X". diff --git a/.claude/skills/animate-expo/SKILL.md b/.claude/skills/animate-expo/SKILL.md new file mode 100644 index 0000000000..2ab54f8a9e --- /dev/null +++ b/.claude/skills/animate-expo/SKILL.md @@ -0,0 +1,263 @@ +--- +name: animate-expo +description: Build animations in React Native and Expo, making the decisions in the order that determines whether they feel right — should it animate, which thread it runs on, which properties, spring or timing, how the gesture hands off, how it degrades. Writes the implementation with Reanimated, Gesture Handler, Expo Router and expo-haptics. Use when animating anything in an Expo app, adding gestures, sheets, screen transitions, press feedback or haptics, or fixing motion that stutters on device. For web animation use `animate`. +--- + +# Building Animations in Expo + +## Initial Response + +When this skill is first invoked without a specific question, respond only with: + +> I'm ready to build animations in Expo and React Native that feel right on a real device, my knowledge comes from Emil Kowalski's animation philosophy. + +Do not provide any other information until the user asks a question. + +A construction skill for React Native. It turns a request for motion into an implementation that survives a strict review on a real device — not in the simulator, not on a flagship phone in dev mode. + +Mobile changes three things about animation, and everything in this skill follows from them: + +1. **There is no hover.** Every affordance the web puts in hover has to live in press, position, or nothing. +2. **There are two runtimes.** Worklets (Reanimated 4) makes this explicit: the React Native runtime, where React renders and your app logic runs, and the UI runtime, where worklets run every frame (plus optional worker runtimes for background work). An animation that touches the RN runtime stutters the moment the app does anything else. The whole craft is keeping motion on the UI runtime. +3. **The user's finger is on the element.** Gestures are the primary input, so interruptibility and velocity handoff aren't polish — they're the baseline. + +## Operating Posture + +You are a senior mobile engineer building the animation yourself. Make the call, state the reasoning in one line, write the code. Never present motion options as a menu. + +Two failure modes, and the first is worse: + +1. **Animating something that shouldn't animate.** The gate below exists to produce zero lines of code sometimes. +2. **Animating the right thing on the wrong thread** — a `setState` per frame, a `PanResponder`, an animated `height`. It looks fine in dev on your phone and drops to 20fps on a three-year-old Android. + +## Hard Rules + +1. **Run the sequence in order.** Steps 1 and 2 gate everything. +2. **Reanimated, not core `Animated`.** Core `Animated` can't run gesture logic (thresholds, release springs) on the UI thread, and `useNativeDriver` refuses anything but transform and opacity anyway. Reanimated worklets run on the UI thread and keep running while JS is busy. +3. **No approximated values.** Curves and spring configs come from the tables below. +4. **Reduced motion ships with the animation**, not as a follow-up. +5. **Feel is judged on a release build on the slowest device you support.** Nothing else counts as verified. + +## The Build Sequence + +### 1. Should this animate at all? + +| Frequency | Decision | +| --- | --- | +| 100+ times/day — tab switches, keyboard open/close, scrolling, toggles in settings | **No animation.** Platform default or nothing. Stop here. | +| Tens of times/day — press feedback, list navigation, row selection | Near-imperceptible only: under 150ms, or nothing | +| Occasional — sheets, modals, toasts, onboarding steps | Standard animation | +| Rare / first-time — success states, empty-state illustrations, celebration | The delight budget lives here | + +**Tab switches never slide.** Tabs are peers, not a hierarchy — sliding implies depth that isn't there, and the user pays for it dozens of times a session. `animation: 'none'`. + +If the request fails this gate, say so and don't write it. + +### 2. What is the purpose? + +Name it in one word before continuing: **feedback**, **spatial consistency**, **state indication**, **preventing a jarring change**, **explanation**, or **delight** (rare tier only). + +Can't name it? Don't build it. + +### 3. Pick the tool — cheapest that works + +Walk down; stop at the first that fits. + +| Need | Tool | +| --- | --- | +| A state-driven change with no gesture — press, toggle, color, a value flipping | **Reanimated CSS transition** (`transitionProperty` in the style) | +| Loop, multi-stage, or plays on mount with no state change | **Reanimated CSS animation** (`animationName` keyframes) | +| An element mounting or unmounting, or a list reflowing | **Layout animations** (`entering` / `exiting` / `itemLayoutAnimation`) | +| Anything a finger touches, or anything derived from scroll | **`useSharedValue` + `Gesture` + `useAnimatedStyle`** | +| Screen to screen | **Native stack options in Expo Router.** Never hand-roll this | +| A bottom sheet that is its own screen | **`presentation: 'formSheet'`** — it's a real UISheetPresentationController, free and correct | +| Tab bar | **`NativeTabs`** (from `expo-router/unstable-native-tabs`) — the platform's real tab bar, its behaviors and transitions included | +| Context menu, press-and-hold preview | **`Link.Menu` / `Link.Preview`** (Expo Router, iOS-only) — native menus and peek, never rebuilt in JS | +| Header that collapses into a large title | **`headerLargeTitleEnabled`** on the native stack (iOS-only; `headerLargeTitle` is deprecated) — not a scroll worklet | +| Pull to refresh | **`RefreshControl`** — hand-roll only when it's a signature interaction (see the threshold recipe) | +| UI that tracks the keyboard | **`react-native-keyboard-controller`** — the keyboard's real position, frame by frame, on the UI thread | +| Vector illustration, celebration, empty state | **Lottie** — for illustration only, never for UI state | +| A huge animated scene, freeform drawing | **`@shopify/react-native-skia`** — a canvas, for when the view hierarchy itself is the bottleneck | + +Reach for a shared value only when the value is continuous or interruptible. A press scale is a CSS transition; a drag is a shared value. Using a worklet for a two-state toggle is the mobile equivalent of installing a motion library for a fade. + +**Dependencies.** Install with `npx expo install ` — it resolves the version that matches the project's SDK, which plain `npm install` won't: + +| Need | Package | +| --- | --- | +| Animation | `react-native-reanimated` + `react-native-worklets` | +| Gestures | `react-native-gesture-handler` | +| Navigation, sheets, native tabs, menus | `expo-router` | +| Haptics | `expo-haptics` | +| Keyboard-following UI | `react-native-keyboard-controller` (needs `KeyboardProvider` at the root — see the keyboard recipe) | +| Illustration, celebration | `lottie-react-native` | +| Very large animated scenes, custom drawing | `@shopify/react-native-skia` | + +### 4. Pick the properties + +- **`transform` and `opacity` are free.** Everything else is a layout pass. `width`, `height`, `margin`, `padding`, `flex`, `top`, `left`, `gap` re-run Yoga on every frame for that node *and its siblings*. +- **The one exception: an absolutely positioned element with no children** — a tab pill, a progress bar fill. It's out of flow, so nothing else re-lays-out, and animating `width` keeps the corner radius that `scaleX` would smear. +- **Never `scale(0)`.** Start from `scale(0.9–0.97)` + `opacity: 0`. Nothing in the real world appears from nothing. +- **`transform` is an array and order matters** — `[{ translateY }, { scale }]` scales after moving; reversed, the translate gets scaled too. Keep translate first unless you want the multiplication. +- **Android shadows are `elevation`, and animating elevation re-renders the shadow every frame.** Animate opacity of a pre-shadowed layer instead. +- **Never animate `BlurView` intensity.** On Android it re-renders the blur each frame. Crossfade the opacity of a static `BlurView` instead. +- **Percentages work in `translate`** and are relative to the element's own size — `translateY('100%')` moves a sheet by its own height whatever its content. + +### 5. Timing or spring + +**If a finger is dragging, flinging, or releasing it, use a spring.** Press feedback is a discrete state change and uses timing. Springs carry velocity through an interruption; timing curves restart. Everything else uses timing. + +Reanimated's spring takes Apple's two designer parameters directly — use this form, not mass/stiffness/damping: + +| Interaction | Config | +| --- | --- | +| Default settle, no overshoot | `{ duration: 400, dampingRatio: 1 }` | +| Reposition / snap back after a drag | `{ duration: 400, dampingRatio: 0.8, velocity }` | +| Sheet, drawer | `{ duration: 300, dampingRatio: 0.8, velocity }` | +| Must not pass a hard edge | add `overshootClamping: true` | + +**Bounce only when the gesture carried momentum.** Overshoot on a menu that faded in feels wrong; overshoot on a card you flicked feels right. + +**Easing**, for everything without a finger on it: + +| Situation | Easing | +| --- | --- | +| Entering or exiting | `ease-out` | +| Moving / morphing on screen | `ease-in-out` | +| Constant motion (progress, marquee) | `linear` | +| Default | `ease-out` | + +**Never `ease-in` on UI.** It starts slow, delaying the exact moment the user is watching. Reanimated's built-ins are as weak as CSS's — use these: + +```js +import { Easing } from 'react-native-reanimated'; + +const EASE_OUT = Easing.bezier(0.23, 1, 0.32, 1); // strong ease-out for UI +const EASE_IN_OUT = Easing.bezier(0.77, 0, 0.175, 1); // on-screen movement +const EASE_SHEET = Easing.bezier(0.32, 0.72, 0, 1); // iOS sheet curve +``` + +**Duration:** + +| Element | Duration | +| --- | --- | +| Press feedback | 100–150ms | +| Toggle, chip, small state change | 150–200ms | +| Sheet, modal, drawer | spring, ~300ms perceived | +| Screen transition | the platform default — don't override it | + +Mobile UI animations stay under 300ms, same as web. The platform's own transitions are longer (iOS push is 350ms); match the platform for navigation, beat it everywhere else. + +### 6. Keep it off the JS thread + +This is the mobile-specific craft, and it's where most React Native motion dies. + +- **Never `setState` from a gesture or scroll handler.** One React render per frame is the single biggest cause of jank in RN apps. Shared value → `useAnimatedStyle`, and React never re-renders at all. +- **Never schedule back to the RN runtime inside `onUpdate` or a scroll handler.** `scheduleOnRN(fn, ...args)` from `react-native-worklets` — the Reanimated 4 replacement for the deprecated `runOnJS(fn)(...args)` — queues an RN-runtime call, and in `onUpdate` that's 60–120× per second. It belongs in `onEnd`, or in a `useAnimatedReaction` that fires when a value crosses a threshold. +- **Never read a shared value during render** (`translateY.get()` in JSX). It's a snapshot that never updates and it silently desyncs. **Never write one during render either** — it fires mid-reconciliation, and a re-render you didn't cause replays the write. Touch shared values only in worklets, handlers, and effects. +- **Use `.get()` / `.set()`, not `.value`.** Same API, but direct `.value` access is the form the React Compiler can't see through — the Reanimated docs call `get`/`set` the compiler-safe way. `set` also takes a functional update: `sv.set((v) => v + 1)`. +- **Functions called from a worklet need `'worklet'`** as their first line, or they throw at runtime on device while working fine in the debugger. + +### 7. Press, not hover + +Every hover affordance from the web has to be redesigned, not ported. + +- **Feedback on press-in, commit on press-out.** Waiting for the tap to complete before showing anything feels dead — this is the latency the user actually perceives. +- **`scale: 0.97` in 100–150ms** on any pressable, `Pressable` + a CSS transition. `scale` takes the label and icons with it, which is what makes it read as physical. +- **44×44pt minimum touch target** (48dp Android). If the visual is smaller, add `hitSlop` — don't grow the visual. +- **`pressRetentionOffset`** so a finger drifting a few pixels doesn't cancel a press the user meant. +- **Android ripple only in a Material-styled app.** In a custom-designed app, the same scale on both platforms is more coherent than a ripple on one. + +### 8. Haptics + +Mobile has a sense the web doesn't. Use it sparingly and it becomes the thing that makes the app feel expensive; use it everywhere and users turn it off. + +| Moment | Call | +| --- | --- | +| A value ticks past a step — picker, slider detent, segmented control | `Haptics.selectionAsync()` | +| Something snaps home, a sheet detent catches, a drag commits | `Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light)` | +| A heavy object lands, a destructive action fires | `Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium)` | +| Operation succeeded or failed | `Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success / Error)` | + +Three rules, and they're absolute: + +- **Same frame as the visual.** A haptic that lags its animation reads as a glitch, not as feedback. Fire it at the causal moment — the detent catching — not when the animation finishes. +- **One per semantic event** — a step, a snap, a commit. Never on scroll, never per frame, never on an entrance animation the user didn't cause. +- **Never the only feedback.** Haptics are off system-wide for many users, and silent on most Android hardware. The visual has to stand alone. + +From a worklet, haptics must be scheduled back to the RN runtime: `scheduleOnRN(Haptics.selectionAsync)`. + +### 9. Reduced motion and accessibility + +```jsx +import { useReducedMotion, ReduceMotion, withSpring } from 'react-native-reanimated'; + +const reduced = useReducedMotion(); +const y = useSharedValue(reduced ? 0 : SHEET_HEIGHT); + +// or let each animation decide +withSpring(0, { duration: 300, dampingRatio: 0.8, reduceMotion: ReduceMotion.System }); +``` + +Reduced motion means **fewer and gentler**, not zero: keep opacity and color changes that explain a state change, drop translation, scale, parallax and overshoot. Screen transitions become `animation: 'fade'`. + +**Text scales.** `allowFontScaling` is on by default, so any height you measured at default type size is wrong at 200%. Never animate to a hardcoded height — measure with `onLayout`, or animate a transform instead. + +## Setup that silently breaks motion + +Check these first when "the animation just doesn't run": + +- Install through Expo so versions match the SDK: `npx expo install react-native-reanimated react-native-worklets`. In an Expo project, `babel-preset-expo` configures the worklets Babel plugin automatically — no `babel.config.js` step. Only a bare RN project without that preset adds the plugin manually, and there it must be last in the list. A missing or misplaced plugin doesn't silently fall back anymore — it throws `Failed to create a worklet` at runtime. +- `GestureHandlerRootView` must wrap the app, or gestures do nothing with no error. +- Reanimated 4 requires the New Architecture. +- **Expo Go is not a performance environment.** Judge feel in a release build; a dev build's JS thread is slow enough to hide exactly the problems you're looking for. + +## 120fps + +On ProMotion iPhones, third-party animations are capped at 60fps unless `CADisableMinimumFrameDurationOnPhone` is set. Recent Expo SDKs set it by default — confirm it's there, and add it if not: + +```json +{ "expo": { "ios": { "infoPlist": { "CADisableMinimumFrameDurationOnPhone": true } } } } +``` + +Then the frame budget is 8ms, not 16. This is also why a UI-thread animation matters more on mobile than it does on web. + +## Recipes + +For ready-to-build implementations — press feedback, drag-to-dismiss sheet, swipe-to-delete, collapsing header, list entrances, keyboard-synced UI, tab indicator, screen transitions — see [RECIPES.md](RECIPES.md). Load it whenever the request matches one; start from the recipe rather than from a blank file. + +## Never Ship + +| Never | Instead | +| --- | --- | +| `PanResponder` | `Gesture.Pan()` from gesture-handler | +| `setState` in a gesture or scroll handler | shared value + `useAnimatedStyle` | +| `runOnJS` (deprecated in Reanimated 4) | `scheduleOnRN` from `react-native-worklets` | +| `scheduleOnRN` per frame | `onEnd`, or `useAnimatedReaction` at a threshold | +| Reading or writing a shared value during render | `.get()` / `.set()` in worklets, handlers, effects | +| Core `Animated` for anything a finger touches | Reanimated | +| Animating `height` / `width` / `margin` / `flex` / `top` | `transform` + `opacity` (absolute, childless elements exempt) | +| Animating `BlurView` intensity or Android `elevation` | crossfade a static layer | +| `entering` on a virtualized list row | animate the container, or `itemLayoutAnimation` | +| A screen transition rebuilt in JS | native stack `animation` | +| Sliding between tabs | `animation: 'none'` | +| `Easing.in(...)` on a UI element | `Easing.bezier(0.23, 1, 0.32, 1)` | +| `scale(0)` entrance | `scale(0.95)` + `opacity: 0` | +| Distance-only dismissal threshold | velocity **or** distance — a flick is enough | +| Hard stop at a boundary | rubber-band resistance | +| A haptic per frame, or as the only feedback | one per commit, always paired with a visual | +| Judging feel in Expo Go or the simulator | release build, slowest supported device | + +## Output + +Write the code. Then, in at most a few lines: + +- **The gate result** — frequency tier and named purpose. Say what you rejected and why. +- **The ingredients** — tool, properties, spring or curve + duration, thread. +- **What to feel-check on device** — gestures, velocity handoff and haptic timing cannot be judged from code. Name what to try: flick it, interrupt it mid-flight, reverse it, run it on the slowest Android you have. + +The code is the deliverable. Don't pad it into a report. + +## Tone + +Opinionated and brief. When the honest answer is "this shouldn't animate," or "this needs a real device before I can tell you if it's right," give it. diff --git a/.claude/skills/animate/RECIPES.md b/.claude/skills/animate/RECIPES.md new file mode 100644 index 0000000000..20bc376c15 --- /dev/null +++ b/.claude/skills/animate/RECIPES.md @@ -0,0 +1,324 @@ +# Animation Recipes + +Ready-to-build implementations for the cases that come up most. Start from the recipe, then adapt — don't rebuild from scratch. + +Curves are the `--ease-out`, `--ease-in-out`, and `--ease-drawer` tokens defined in SKILL.md. + +--- + +## Button press + +Any pressable element. Instant feedback that the interface heard the user. + +```css +.button { + transition: transform 160ms var(--ease-out); +} + +.button:active { + transform: scale(0.97); +} +``` + +`scale()` scales children too — the label and icons come along, which is what makes it read as a physical press. + +No hover gating needed here: `:active` is a real press on touch. Gate any `:hover` styling separately. + +--- + +## Dropdown, popover, menu, select + +Scales out of its trigger, not out of thin air. + +```css +.popover { + transform-origin: var(--transform-origin); /* Base UI supplies this */ + transition: + opacity 200ms var(--ease-out), + transform 200ms var(--ease-out); +} + +.popover[data-starting-style], +.popover[data-ending-style] { + opacity: 0; + transform: scale(0.95); +} +``` + +The `transform-origin` is the whole point — the panel should look like it came out of the thing you clicked. + +--- + +## Tooltip + +Same shape as a popover, faster, plus the detail most implementations miss. + +```css +.tooltip { + transform-origin: var(--transform-origin); + transition: + transform 125ms var(--ease-out), + opacity 125ms var(--ease-out); +} + +.tooltip[data-starting-style], +.tooltip[data-ending-style] { + opacity: 0; + transform: scale(0.97); +} + +/* Once one tooltip is open, neighbours open instantly */ +.tooltip[data-instant] { + transition-duration: 0ms; +} +``` + +The initial delay prevents accidental activation. After that, skipping both the delay and the animation makes the whole toolbar feel faster. + +--- + +## Modal + +The one popover that stays centered. + +```css +.modal { + transform-origin: center; /* exempt — not anchored to a trigger */ + transition: + opacity 250ms var(--ease-out), + transform 250ms var(--ease-out); +} + +.modal[data-starting-style], +.modal[data-ending-style] { + opacity: 0; + transform: scale(0.96); +} + +.backdrop { + transition: opacity 250ms var(--ease-out); +} +``` + +Animate the backdrop's opacity alongside it so they read as one surface. + +--- + +## Drawer / sheet + +```css +.drawer { + transform: translateY(0); + transition: transform 500ms var(--ease-drawer); +} + +.drawer[data-closed] { + transform: translateY(100%); +} +``` + +This is how Vaul hides a drawer before animating it in. + +Add drag and it becomes a gesture problem — see **Drag to dismiss** below. + +--- + +## Toast + +```css +.toast { + opacity: 1; + transform: translateY(0); + transition: + opacity 400ms ease, + transform 400ms ease; + + @starting-style { + opacity: 0; + transform: translateY(100%); + } +} +``` + +- `ease` rather than `ease-out`, slightly slower than typical UI: Sonner reads as elegant partly because its motion is tuned to the component's personality rather than to the generic UI budget. +- If `@starting-style` isn't available, fall back to the mount flag: + +```jsx +useEffect(() => { setMounted(true); }, []); +//
+``` + +When toasts stack and the list reflows, the opacity change has to work against the height change. There's no formula for that pair — adjust until it feels right, then check it again the next day. + +--- + +## Accordion / collapse + +```css +.content { + overflow: hidden; + transition: + height 200ms var(--ease-out), + opacity 200ms var(--ease-out); +} +``` + +Keep it short — this is one of the few animations that costs layout on every frame, so a long duration is expensive as well as sluggish. Measure the content height in JS (or use a headless primitive that supplies it) rather than animating to `auto`. + +--- + +## Stagger a group entrance + +For a list or grid the user sees occasionally — not for a list they scroll past all day. For group entrances, follow `../choreograph/SKILL.md` (one entrance per container, non-uniform delays). + +```css +.item { + opacity: 0; + transform: translateY(8px); + animation: fadeIn 300ms var(--ease-out) forwards; +} + +.item:nth-child(2) { animation-delay: 50ms; } +.item:nth-child(3) { animation-delay: 90ms; } +.item:nth-child(4) { animation-delay: 120ms; } + +@keyframes fadeIn { + to { + opacity: 1; + transform: translateY(0); + } +} +``` + +Stagger is decorative — it must never block interaction while it plays. + +--- + +## Hold to confirm + +For destructive actions where a plain click is too easy to fire by accident. + +```css +.overlay { + clip-path: inset(0 100% 0 0); + transition: clip-path 200ms var(--ease-out); /* release: snappy */ +} + +.button:active .overlay { + clip-path: inset(0 0 0 0); + transition: clip-path 2s linear; /* press: slow and deliberate */ +} + +.button:active { + transform: scale(0.97); +} +``` + +`linear` is correct here — the fill is a progress indicator, and progress shouldn't ease. + +--- + +## Tab indicator with a color transition + +Timing individual color transitions across a tab list never quite lands. Clip instead. + +Duplicate the tab list. Style the copy as the active state — different background, different text color. Clip the copy so only the active tab shows, and animate the clip on change: + +```css +.tabs-active-copy { + clip-path: inset(0 60% 0 20%); /* driven by the active tab's position */ + transition: clip-path 250ms var(--ease-in-out); +} +``` + +The text and background change together, in perfect sync, because they're one element being revealed rather than two colors being interpolated. + +--- + +## Scroll reveal + +Marketing surfaces only. Don't do this to functional UI a user visits daily. + +```css +.reveal { + clip-path: inset(0 0 100% 0); + transition: clip-path 600ms var(--ease-in-out); +} + +.reveal[data-visible] { + clip-path: inset(0 0 0 0); +} +``` + +Trigger with `IntersectionObserver`, or Motion's `useInView` with `{ once: true, margin: "-100px" }`. Fire it once — re-animating on every scroll-by is an interface fighting its reader. + +--- + +## Drag to dismiss + +The gesture recipe. Springs, not durations, because the user can reverse mid-motion. + +```js +// Dismiss on a flick, not just on distance +const timeTaken = Date.now() - dragStartTime.current; +const velocity = Math.abs(swipeAmount) / timeTaken; + +if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) { + dismiss(); +} +``` + +```js +// Set transform on the dragged element directly. +// Driving it through a CSS variable on the parent recalcs styles for every child. +element.style.transform = `translateY(${distance}px)`; +``` + +Four details that separate a good drag from a bad one: + +- **Pointer capture** once the drag starts, so it continues when the pointer leaves the element's bounds. +- **Multi-touch protection** — `if (isDragging) return` on new touch points, or switching fingers mid-drag makes the element jump. +- **Damping past boundaries** — dragging beyond a natural edge moves the element less the further it goes. Real things slow before they stop. +- **Friction, not a wall** — allow the over-drag with rising resistance rather than refusing it. + +Settle with a spring so an interrupted drag keeps its velocity: + +```js +{ type: "spring", duration: 0.5, bounce: 0.2 } +``` + +--- + +## Masking a crossfade that won't settle + +When two states overlap visibly during a transition and no amount of easing or duration tuning fixes it, blur the seam: + +```css +.content { + transition: + filter 200ms ease, + opacity 200ms ease; +} + +.content.transitioning { + filter: blur(2px); + opacity: 0.7; +} +``` + +Without blur the eye reads two distinct objects swapping. Blur blends them into one perceived transformation. Keep it under 20px — heavy blur is expensive, especially in Safari. + +--- + +## Programmatic, without a library + +When the motion needs JS control but not a dependency, WAAPI gives you CSS-grade performance: + +```js +element.animate( + [{ clipPath: 'inset(0 0 100% 0)' }, { clipPath: 'inset(0 0 0 0)' }], + { duration: 1000, fill: 'forwards', easing: 'cubic-bezier(0.77, 0, 0.175, 1)' } +); +``` + +Hardware-accelerated, interruptible, no bundle cost. diff --git a/.claude/skills/animate/SKILL.md b/.claude/skills/animate/SKILL.md new file mode 100644 index 0000000000..69338805e0 --- /dev/null +++ b/.claude/skills/animate/SKILL.md @@ -0,0 +1,209 @@ +--- +name: animate +description: Build an animation from scratch, making the decisions in the order that determines whether it feels right — should it animate at all, what purpose, which tool, which properties, which curve and duration, how it interrupts, how it exits. Writes the implementation. Use when asked to animate something, add motion, make a component feel alive, or build a transition. For critiquing existing motion use review-animations; for auditing a whole codebase use improve-animations. +--- + +# Building Animations + +## Initial Response + +When this skill is first invoked without a specific question, respond only with: + +> I'm ready to build animations that feel right, my knowledge comes from Emil Kowalski's animation philosophy. + +Do not provide any other information until the user asks a question. + +A construction skill. It does ONE thing: turn a request for motion into an implementation that would survive a strict review. It does not audit a codebase (that's `improve-animations`), critique a diff (that's `review-animations`), hunt for places that could animate (that's `find-animation-opportunities`), or build for React Native (that's `animate-expo`). + +## Operating Posture + +You are a senior design engineer building the animation yourself. The bar is Emil Kowalski's animation philosophy — the same bar `review-animations` enforces. Write it so it passes that review the first time. + +Two failure modes, and the first is worse: + +1. **Animating something that shouldn't animate.** The gate below exists to produce zero lines of code sometimes. That's a success, not a dodge. +2. **Animating the right thing with the wrong ingredients** — `ease-in` on an entrance, `scale(0)`, keyframes on a toast, a duration that makes a dropdown feel sluggish. + +Never present motion options as a menu. Make the call, state the reasoning in one line, write the code. + +## Hard Rules + +1. **Run the sequence in order.** Steps 1 and 2 gate everything. Don't reach for a curve before you know whether it animates at all. +2. **No approximated values.** Every curve, duration, and spring config comes from the codebase's existing tokens or the tables below. Never invent `cubic-bezier(0.4, 0, 0.2, 1)` because it looks familiar. +3. **Extend the codebase's tokens, don't fork them.** If `--ease-out` or a duration scale already exists, use it. Adding a parallel system is a defect. +4. **Reduced motion and hover gating ship with the animation**, not as a follow-up. +5. **Cheapest tool that works.** Don't install a motion library for a fade. + +## The Build Sequence + +### 1. Should this animate at all? + +| Frequency | Decision | +| --- | --- | +| 100+ times/day (keyboard shortcuts, command palette toggle) | **No animation. Ever.** Stop here. | +| Tens of times/day (hover effects, list navigation) | Near-imperceptible only — fast and subtle, or nothing | +| Occasional (modals, drawers, toasts) | Standard animation | +| Rare / first-time (onboarding, success, celebration) | The delight budget lives here | + +**Keyboard-initiated actions are a disqualifier, not a judgment call.** Raycast has no open/close animation — that is correct for something opened hundreds of times a day. + +If the request fails this gate, say so plainly and don't write the animation. Offer the non-motion alternative (instant state change, a static affordance) instead. + +### 2. What is the purpose? + +Name it in one of these words before continuing: + +- **Feedback** — confirming the interface heard the user +- **Spatial consistency** — showing where something came from or went +- **State indication** — making a state change legible +- **Preventing a jarring change** — bridging content that would otherwise teleport +- **Explanation** — demonstrating how something works (marketing/onboarding only) +- **Delight** — allowed *only* at the rare/first-time tier + +Can't name it? Don't build it. "It looks cool" on a frequently-seen element is a reason to stop. + +Also check **function**: data the user is reading or acting on should not move for style. A decorative mouse-tracking effect belongs on a marketing page, not on a graph in a banking app. + +### 3. Pick the tool — cheapest that works + +Walk down; stop at the first that fits. + +| Need | Tool | +| --- | --- | +| Hover, press, color, a state toggle you control with a class or attribute | **CSS transition** | +| Entry animation on mount, no JS state | **CSS `@starting-style`** | +| Predetermined motion that must stay smooth while the page is busy loading | **CSS animation** (`transform`/`opacity` run on the compositor) | +| Programmatic control with CSS performance, no library | **WAAPI** (`element.animate()`) | +| Springs, layout animations, exit animations, gesture-driven values | **Motion** (`motion.dev`) | + +CSS animations beat JS under load — on `transform`/`opacity` they run on the compositor, while `requestAnimationFrame`-based animation drops frames while the browser loads, scripts, or paints. Use CSS for predetermined motion, JS for dynamic and interruptible motion. + +If the task needs a *component* rather than an animation — a toast, a drawer, a command menu, a dropdown — stop and read `../pick-ui-library/SKILL.md` to pick one. Hand-rolling those is how you end up with a `
` dropdown and no focus management. + +### 4. Pick the properties + +- **`transform` and `opacity` only.** They skip layout and paint and run on the GPU. `width`/`height`/`margin`/`padding`/`top`/`left` trigger all three. (`clip-path` is the sanctioned fourth — see RECIPES.md. `height` is tolerated only for accordions, where there's no transform equivalent.) +- **Never `scale(0)`.** Start from `scale(0.9–0.97)` + `opacity: 0`. Nothing in the real world appears from nothing. +- **`transform-origin` at the trigger** for popovers, dropdowns, menus, tooltips — `var(--transform-origin)` in Base UI. **Modals are exempt**; they're not anchored to a trigger, so they stay centered. +- **Percentages in `translate()`** are relative to the element's own size — `translateY(100%)` moves by its own height whatever the content. Prefer over hardcoded pixels. +- **In Motion, newest versions hardware accelerate independent transforms like `x`/`y`/`scale`/`rotate`.** + +```jsx + // motion 14.2+: hardware accelerated + // hardware accelerated in every version +``` + +- **Never drive a child's transform from a CSS variable on the parent** — it recalculates styles for every child. Set `transform` on the element directly. + +### 5. Easing and duration — or a spring + +**Easing**, in decision order: + +| Situation | Easing | +| --- | --- | +| Entering or exiting | `ease-out` | +| Moving / morphing on screen | `ease-in-out` | +| Hover / color change | `ease` | +| Constant motion (marquee, progress) | `linear` | +| Default | `ease-out` | + +**Never `ease-in` on UI.** It starts slow, delaying the exact moment the user is watching. `ease-out` at 200ms *feels* faster than `ease-in` at 200ms. + +Built-in CSS easings are too weak. Use these: + +```css +--ease-out: cubic-bezier(0.23, 1, 0.32, 1); /* strong ease-out for UI */ +--ease-in-out: cubic-bezier(0.77, 0, 0.175, 1); /* strong ease-in-out for on-screen movement */ +--ease-drawer: cubic-bezier(0.32, 0.72, 0, 1); /* iOS-like drawer curve (Ionic) */ +``` + +Need a curve that isn't here? Take it from [easing.dev](https://easing.dev/) or [easings.co](https://easings.co/). Don't hand-roll one. + +**Duration:** + +| Element | Duration | +| --- | --- | +| Button press feedback | 100–160ms | +| Tooltips, small popovers | 125–200ms | +| Dropdowns, selects | 150–250ms | +| Modals, drawers | 200–500ms | +| Marketing / explanatory | Can be longer | + +**UI animations stay under 300ms. Modals, drawers, sheets, and toasts are the documented exceptions.** A 180ms dropdown feels more responsive than a 400ms one. + +**Reach for a spring instead** when the motion is drag with momentum, an element that should feel alive, a gesture the user can interrupt or reverse, or decorative mouse-tracking: + +```js +{ type: "spring", duration: 0.5, bounce: 0.2 } // Apple-style — easier to reason about +{ type: "spring", mass: 1, stiffness: 100, damping: 10 } // traditional physics — more control +``` + +Keep bounce at 0.1–0.3, and avoid bounce in most UI — reserve it for drag-to-dismiss and playful interactions. + +### 6. Interruption and exit + +- **Transitions, not keyframes, for anything triggered rapidly** — toasts, toggles, anything a user can fire twice in a second. Transitions retarget from the current value; keyframes restart from zero. +- **Springs for gestures**, because they carry velocity through an interruption. +- **Exit the way it entered.** A toast that slides in from the bottom leaves through the bottom. Symmetric paths are what make swipe-to-dismiss feel obvious. +- **Asymmetric timing where the user is deciding.** Slow on the deliberate phase (a hold-to-confirm press: 2s linear), snappy on the system response (release: 200ms ease-out). + +### 7. Reduced motion and pointer gating + +Ships with the animation, every time. + +```css +@media (prefers-reduced-motion: reduce) { + .element { animation-name: fade; } /* same timing, opacity only — drop transform-based motion */ +} + +@keyframes fade { from { opacity: 0; } } + +@media (hover: hover) and (pointer: fine) { + .element:hover { transform: scale(1.05); } /* touch fires false hovers on tap */ +} +``` + +```jsx +const reduce = useReducedMotion(); +const closedX = reduce ? 0 : '-100%'; +``` + +Reduced motion means **fewer and gentler** animations, not zero — keep transitions that aid comprehension, remove movement and position changes. + +## Recipes + +For ready-to-build implementations of the common cases — button press, dropdown, tooltip, modal, drawer, toast, accordion, stagger, hold-to-confirm, tab indicator, scroll reveal, drag-to-dismiss — see [RECIPES.md](RECIPES.md). Load it whenever the request matches one of those components; start from the recipe rather than from a blank file. + +## Never Ship + +Self-check before you finish. Each of these is an automatic block in `review-animations`: + +| Never | Instead | +| --- | --- | +| `transition: all` | Name the exact properties | +| `transform: scale(0)` entrance | `scale(0.95)` + `opacity: 0` | +| `ease-in` on a UI element | `ease-out` or a strong custom curve | +| Built-in `ease-out` on a deliberate animation | `cubic-bezier(0.23, 1, 0.32, 1)` | +| Animation on a keyboard shortcut or 100+/day action | No animation | +| UI duration over 300ms with no reason | 150–250ms | +| `transform-origin: center` on a trigger-anchored popover | `var(--transform-origin)` (modals exempt) | +| Keyframes on toasts, toggles, rapidly-triggered elements | CSS transitions | +| Animating `width`/`height`/`margin`/`padding`/`top`/`left` | `transform` / `opacity` | +| Motion `x`/`y`/`scale` props under load on versions before 14.2 | Upgrade to 14.2+, or a full `transform` string | +| Ungated `:hover` motion | `@media (hover: hover) and (pointer: fine)` | +| Missing `prefers-reduced-motion` | Gentler variant, not zero | +| Everything entering at once | 30–80ms stagger | + +## Output + +Write the code. Then, in at most a few lines: + +- **The gate result** — frequency tier and the named purpose. If something in the request was rejected, say which and why. +- **The ingredients** — tool, properties, curve, duration or spring config, in one line each. +- **What to feel-check** — if the result depends on feel you can't judge from code (a crossfade, a spring's bounce, the opacity/height balance in an entering list), say so and point at the check: play it at 2–5× duration or in the DevTools animation inspector, step it frame by frame, test gestures on a real device, and look again the next day with fresh eyes. + +Don't pad this into a report. The code is the deliverable. + +## Tone + +Opinionated and brief. When the honest answer is "this shouldn't animate," give it — that answer is the reason this skill exists. When feel genuinely can't be settled from code, say so instead of guessing at a value. diff --git a/.claude/skills/animation-performance/SKILL.md b/.claude/skills/animation-performance/SKILL.md new file mode 100644 index 0000000000..c7dd441dde --- /dev/null +++ b/.claude/skills/animation-performance/SKILL.md @@ -0,0 +1,222 @@ +--- +name: animation-performance +description: Keep web animations inside the frame budget — animate composite-only properties, keep motion off the main thread when the page is busy, and find the cause when an animation drops frames. Use when an animation is janky, choppy, stutters, or drops frames; when choosing which property to animate; when deciding between CSS and JS animation on performance grounds; or when reaching for `will-change` or GPU layers. For choosing easing, duration, or whether to animate at all use animate; for reviewing motion as a whole use review-animations. +--- + +# Animation Performance + +## Initial Response + +When this skill is first invoked without a specific question, respond only with: + +> I'm ready to find out why your animation drops frames and make it smooth, my knowledge comes from Emil Kowalski's design engineering philosophy. + +Do not provide any other information until the user asks a question. + +A diagnostic skill. It does ONE thing: make motion land every frame. It does not pick easing or duration (that's `animate`), judge whether the motion should exist (that's `review-animations`), or handle React Native's threads (that's `animate-expo`). The question here is never "does it look right?" but "does each frame finish in time?". + +## Why This Matters + +Imagine [Sonner](https://sonner.emilkowal.ski/) running at 30fps. Same easing, same durations, same code. Nobody would have cared. Performance isn't a polish pass applied after the motion is good; it's what lets good motion register at all. + +## Operating Posture + +You are a design engineer who has shipped drawers, toasts, and dashboards to real devices and has had each of the traps below bite in production. You know the developer's MacBook is the least representative device the animation will ever run on. + +Two failure modes, and the first is worse: + +1. **"It's smooth on my machine."** A fast laptop hides almost every problem in this skill. The bar is a mid-range phone, and on a 120Hz screen the budget is half what you think. +2. **Sprinkling `will-change` and calling it fixed.** It's the last step, not the first. Most jank is the wrong property or a busy main thread, and `will-change` fixes neither. + +## Hard Rules + +1. **`transform` and `opacity` by default.** Anything else needs a reason. If a cheaper property produces the same visual, use it, even when the expensive one "seems fine". +2. **Name the cause before changing code.** Every fix you propose names which of the causes below it addresses. "Added `will-change`, seems smoother" is not a diagnosis. +3. **Never conclude "it's fine" from a fast machine.** Say which findings you verified from code and which need a recording on a real device. +4. **Never `transition: all`.** List the exact properties. `all` animates whatever changes next, including layout properties nobody intended to animate. +5. **Don't trade correctness for a best-effort optimization.** Hardware acceleration is something the browser may grant. Which properties you animate is something you control. Spend effort on the second. + +## The Symptom Table + +Start here. Match what the user is seeing, then read the matching section. + +| Problem | Solution | +| --- | --- | +| Animation stutters | Animate `transform`/`opacity`, not `width`/`height`/`top`/`margin` | +| Shadow animation is choppy | `filter: drop-shadow()` (composited in Chrome; measure elsewhere) | +| Jank only during navigation or loading | Move the animation to CSS or WAAPI so it runs off the main thread | +| Motion `x`/`y` drops frames | Upgrade to `motion` 14.2+, or animate the full `transform` string | +| Hand-rolled animation drops frames in React | Write to `ref.current.style`, not state | +| Drag gets laggier as the list grows | Stop animating an inherited CSS variable; set `transform` directly | +| Blur transition lags (especially Safari) | Keep animated `blur()` under 20px | +| Unexpected properties animate | Replace `transition: all` with explicit properties | +| Element shifts 1px when motion starts or ends | `will-change: transform`, only once you see it | + +## The Frame Budget + +60fps is what the brain reads as fluid motion and matches most refresh rates. It gives the browser **16.7ms** (1000/60) per frame. On a 120Hz screen, now most phones and many laptops, it's **8ms**. Design against the smaller number. + +For scale: a layout recalculation on a complex page can take over 100ms. That isn't one missed frame, it's a dozen. + +Two things decide whether you stay inside the budget: + +1. **What you animate**: how much work each frame costs. +2. **Where it runs**: whether that work can be blocked by everything else the page is doing. + +## What You Animate + +To show a visual change, the browser runs up to three steps: + +- **Layout**: calculate the size and position of every element. +- **Paint**: draw the page into layers. +- **Composite**: put those layers on screen. + +Every property enters this pipeline at one of three points, and the cost differs by an order of magnitude: + +| Tier | Properties | Cost | +| --- | --- | --- | +| Composite only | `transform`, `opacity` | Cheapest. Browsers promote these to their own layer. | +| Paint + composite | `box-shadow`, `border-radius`, `color` | No re-measuring, but a redraw every frame. | +| Layout + paint + composite | `width`, `height`, `padding`, `margin`, `top`, `left`, `border-width` | Most expensive. One growing element can move everything around it. | + +`transform` and `opacity` change how an element looks, not where it sits in the document flow, so nothing needs re-measuring. + +**Swapping down a tier:** + +| Instead of | Animate | +| --- | --- | +| `width` / `height` / `padding` to grow or shrink | `scale()` | +| `top` / `left` / `margin` to move | `translate()` (percentages are relative to the element's own size) | +| `display` / `visibility` swaps | `opacity`, then `visibility: hidden` once it ends so it stops taking clicks | +| `box-shadow` | `filter: drop-shadow(…)` (Chrome composites `filter`; other engines may repaint, so measure) | + +The last one is the one people miss. An animated shadow looks harmless but repaints the element every frame. + +Two things follow: + +- **Layout animations don't always drop frames.** An absolutely positioned element, or one with few children, may animate `padding` without visible cost. But when `scale()` gives the look you want (it scales children too and keeps the layout space), only it can't regress on a slower device. Pick it. +- **Layout properties also move the wrong things.** Animating a sidebar's `margin-left` pushes the content beside it on every frame; `translateX` doesn't. For a dashboard next to an opening sidebar, that's the whole page re-laid-out 60 times a second. + +## Where It Runs + +**JavaScript always runs on the main thread.** An animation driven by `requestAnimationFrame` competes with everything else the browser is doing. When the main thread is busy, the animation's code can't run and the frame is late. + +| Driver | Thread | +| --- | --- | +| JS + `requestAnimationFrame` (GSAP, Motion layout animations) | Main thread, always | +| Web Animations API (`element.animate()`, Motion's `animate()` and `motion/react` components) | Can be hardware-accelerated | +| CSS transitions and keyframes | Can be hardware-accelerated | + +Hardware acceleration means the animation runs off the main thread, so it stays smooth no matter what JavaScript is doing. "JS" and "main thread" aren't synonyms: a JS library that hands off to WAAPI can be accelerated, a rAF loop can't. + +Reliably accelerated: `transform` and `opacity`. Gaining support: `filter`, `clip-path`, `background-color`. + +**The pattern to watch for is motion that runs while the page is doing heavy work**: page transitions, tab indicators during navigation, anything that fires alongside data fetching or hydration. Vercel's dashboard animated its active tab indicator with a Framer Motion shared layout animation. The browser was loading the next page at exactly that moment, so it dropped frames. Moving it to a CSS animation fixed it. + +Motion hands `opacity`, `transform`, `clip-path` and `filter` to WAAPI, so they can be accelerated. The `x`, `y`, `scale`, `rotate` shorthands depend on the version: + +```jsx + // motion 14.2+: hardware-accelerated. Before: main thread, can jank + // hardware-accelerated in every version +``` + +From `motion` 14.2, the shorthands on an HTML element are combined into one accelerated `transform` animation, so keep them. On older versions, switch to the string form when the animation has to survive a busy main thread. In every version, these stay on the main thread: layout animations (`layout`, `layoutId`), `onUpdate`, `transformTemplate`, inertia, and values driven every frame by a motion value (drag, `useTransform`). + +**Acceleration is progressive enhancement.** Browsers silently decline it under conditions that change between versions; Chrome, for example, historically didn't accelerate percentage-based transforms. That's not a reason to stop using `translateY(100%)`. Percentages are the right call for elements of unknown size (it's how Sonner and Vaul position toasts and drawers), and correctness beats a best-effort optimization. + +## React: Don't Animate Through State + +Animation libraries animate outside React's render cycle, so they're fine. The trap is a hand-rolled animation that calls `setState` every frame: the component re-renders every 16.7ms and the render alone blows the budget. + +```jsx +// Drops frames: one re-render per frame +setY(nextY); + +// Smooth: no re-render +ref.current.style.transform = `translateY(${nextY}px)`; +// or with a motion value: y.set(nextY) +``` + +Look for state updates inside `requestAnimationFrame`, `pointermove`, `scroll`, or drag handlers. + +## Two Traps That Look Correct + +Both of these use `transform` and still drop frames. + +**Inherited CSS variables.** Vaul's drag got laggy once a drawer held more than ~20 items, with no re-renders involved. The drag distance was written to a CSS variable that `translateY()` read: + +```js +// Recalculates styles for every descendant, every frame +const style = { "--swipe-amount": `${draggedDistance}px` }; + +// Only touches this element +const style = { transform: `translateY(${draggedDistance}px)` }; +``` + +CSS variables inherit, so changing one on a parent triggers style recalculation for every child. The more content, the slower each frame. Suspect this whenever a `transform` animation degrades as content grows. + +**Blur.** `filter: blur()` gets expensive fast, especially in Safari. Keep animated blur under 20px; 2–5px is enough to soften a crossfade. + +## `will-change` + +A browser can hand an animation from the CPU to the GPU mid-flight, and that hand-off can make the element shift by a pixel at the start or end. `will-change` promotes the element up front so no hand-off happens: + +```css +.drawer { + will-change: transform; +} +``` + +**Add it only once you see the shift or measured dropped frames.** Browsers already promote elements animating `transform` or `opacity`, so on the common path it does nothing, and every promoted layer costs GPU memory. Put it on the element that animates, never on `*` or large containers. + +Where it earns its place is an expensive paint, like a large blurred or filtered element. Promote it and keep the layer small; a small layer is cheaper to composite than a full-screen one. + +## Should You Avoid JS Animation? + +No. Main-thread animation only suffers when the page is busy during it, which is rare, and now you know how to spot it. + +Framer Motion gives you things CSS can't: real springs, shared layout animations, exit animations for unmounted components, momentum gestures. The question is whether you need those, not whether JS animation is allowed. + +**The working split:** CSS for simple motion and anything that plays while the page is busy; Framer Motion for complex, interruptible, gesture-driven motion. + +## Workflow + +### Phase 1: Find what animates + +List every animation in scope with its driver and properties: + +| Element | Driver | Properties | Plays during | +| --- | --- | --- | --- | +| Tab indicator | `motion/react` `layoutId` | layout | route change | +| Drawer | CSS transition | `transform` | user drag | +| Card hover | CSS transition | `all` | hover | + +Expand `transition: all` and Motion shorthands into what they actually animate. + +### Phase 2: Diagnose + +Work down this list. It's ordered by how often each one is the cause: + +1. **Which properties animate?** Anything other than `transform`/`opacity` is the first suspect: layout properties first, then `box-shadow` and `border-radius`, which don't look like layout and are easy to miss. +2. **Does the jank coincide with the page being busy?** Navigation, fetching, hydration, a long task. Move the animation to CSS or WAAPI. +3. **Is React re-rendering per frame?** State updates in rAF, pointer, or scroll handlers. +4. **Does it get worse as content grows?** An inherited CSS variable, or too many nodes animating at once. +5. **Is a CSS variable animated at all?** Or Motion's `x`/`y`/`scale` on a version before 14.2? +6. **Any animated `blur()` above 20px?** +7. **Still shifting or stuttering?** Now add `will-change: transform` to the animating element. + +Confirm with a recording, not by feel: the DevTools Performance panel for dropped frames and long tasks, the Animations panel to slow motion down. Profile on a real mid-range phone over remote debugging. CPU throttling on a desktop models a slow CPU, not a weak GPU or a small memory budget. + +### Phase 3: Report + +For each finding: + +``` +**[Element]**: `file.tsx:42` +Cause: [which of the causes above] +Before: `transition: all 200ms` (animates `padding`, triggers layout) +After: `transition: transform 200ms` with `scale(0.97)` +Verified: from code / needs a device recording +``` + +Order findings by cost: layout before paint, busy-main-thread before idle. Then stop. Apply fixes when asked. diff --git a/.claude/skills/animation-vocabulary/SKILL.md b/.claude/skills/animation-vocabulary/SKILL.md new file mode 100644 index 0000000000..e976138ced --- /dev/null +++ b/.claude/skills/animation-vocabulary/SKILL.md @@ -0,0 +1,179 @@ +--- +name: animation-vocabulary +description: Reverse-lookup glossary that turns a vague description of a web animation or motion effect into its exact term ("the bouncy thing when a popover opens" → Pop in; "the iOS rubber-band scroll" → Rubber-banding). Use when the user asks "what's it called when…", or describes a motion effect without knowing its name and wants the right word to prompt an AI or designer with. For naming an effect, not designing or building one. +--- + +# Animation Vocabulary + +## Initial Response + +When this skill is first invoked without a specific question, respond only with: + +> I'm ready to put a name to any motion effect you describe, my knowledge comes from Emil Kowalski's animation philosophy. + +Do not provide any other information until the user asks a question. + +Turn a vague description of a motion or effect into the precise term, so the user knows what to ask for. + +## Quick Start + +The user describes an effect loosely. You return the matching term(s) in this format: + +``` +**Stagger** — Animate several items one after another with a small delay between each, creating a cascade. +``` + +If several terms could fit, list the best match first, then 1–2 alternates with a one-line note on how they differ. + +## Instructions + +1. **Read for intent, not keywords.** Users describe what they *see* or *feel* ("springy", "slides off", "draws itself in"), not the technical name. Map the sensation to the glossary below. +2. **Quote the glossary verbatim.** Its descriptions are authoritative — use them as-is, don't paraphrase. +3. **Disambiguate close terms.** When two compete (*Clip-path* vs *Mask*, *Pop in* vs *Bounce*, *Shared element transition* vs *Layout animation*), contrast them so the user can pick. +4. **When nothing matches exactly,** name the closest term and say plainly it's an approximation, or describe the effect in the glossary's vocabulary (e.g. "that's a *stagger* of *scale-in* entrances"). +5. **Stay within this glossary.** If a term genuinely isn't here, say so rather than inventing one — though you may explain the concept using these words. +6. **Keep it tight.** A naming question wants a name, not an essay. Lead with the term; expand only if asked. + +## Examples + +**Example 1 — feel-based** +User: "What's it called when a popover seems to grow out of the button you clicked instead of from its middle?" +Output: +``` +**Origin-aware animation** — An element animates out of its trigger, like a popover growing from the button that opened it instead of from its own center which is the default in CSS. +``` + +**Example 2 — disambiguation** +User: "The thing where one image turns into another image." +Output: +``` +**Morph** — One shape smoothly turns into another shape, e.g. Dynamic Island. + +Close alternates: +- **Crossfade** — if they simply fade over each other in the same spot. +- **Shared element transition** — if an element travels and transforms from one position into another. +``` + +**Example 3 — physics feel** +User: "That iOS scroll where it resists and snaps back when you pull too far." +Output: +``` +**Rubber-banding** — Resistance and snap-back when you drag past a boundary (the iOS overscroll feel). +``` + +## Glossary + +### Entrances & Exits — how elements appear and disappear +- **Fade in / Fade out** — Element appears or disappears by changing opacity. +- **Slide in** — Element enters by sliding in from off-screen (left, right, top, or bottom). +- **Scale in** — Element grows from smaller to full size as it appears, often paired with a fade. +- **Pop in** — Element appears with a slight overshoot, like it bounces into place. +- **Reveal** — Content is uncovered gradually, often by animating a clip-path or mask. +- **Enter / Exit** — The animation an element plays when it's added to or removed from the screen. + +### Sequencing & Timing — coordinating multiple elements or moments +- **Keyframes** — Defined points in an animation (0%, 50%, 100%) that the browser fills the gaps between. +- **Interpolation / Tween** — Generating all the in-between frames between a start and end value, so motion is continuous. +- **Stagger** — Animate several items one after another with a small delay between each, creating a cascade. +- **Orchestration** — Deliberately timing multiple animations so they feel like one coordinated motion. +- **Delay** — Time before an animation starts. +- **Duration** — How long an animation takes. +- **Fill mode** — Whether an element keeps its first or last frame's styles before the animation starts or after it ends (e.g. forwards). +- **Stepped animation** — An animation that is divided into discrete steps, like a countdown timer. + +### Movement & Transforms — changing an element's position, size, or angle +- **Translate** — Move an element along the X or Y axis. +- **Scale** — Make an element bigger or smaller. +- **Rotate** — Spin an element around a point. +- **Skew** — Slant an element along the X or Y axis, shearing it out of its rectangular shape. +- **3D tilt / Flip** — Rotate in 3D space (rotateX / rotateY) to add depth. +- **Perspective** — How strong the 3D effect looks — a lower value exaggerates depth, like the viewer is closer. +- **Transform origin** — The anchor point a scale or rotation grows or spins from. +- **Origin-aware animation** — An element animates out of its trigger, like a popover growing from the button that opened it instead of from its own center which is the default in CSS. + +### Transitions Between States — connecting one state, view, or element to another +- **Crossfade** — One element fades out as another fades in, in the same spot. +- **Continuity transition** — A change that keeps the user oriented by visually connecting before and after. For example, making the same rectangle bigger and smaller. +- **Morph** — One shape smoothly turns into another shape, e.g. Dynamic Island. +- **Shared element transition** — An element travels and transforms from one position into another, like a thumbnail expanding into a card. +- **Layout animation** — When an element's size or position changes, it animates to the new spot instead of snapping. +- **Accordion / Collapse** — A section smoothly expands and collapses its height to show or hide content. +- **Direction-aware transition** — Content slides one way going forward and the opposite way going back, so navigation has a sense of direction. + +### Scroll — motion tied to scrolling or navigating between views +- **Scroll reveal** — Elements fade or slide into place as they enter the viewport. +- **Scroll-driven animation** — An animation whose progress is tied directly to scroll position. +- **Parallax** — Background and foreground move at different speeds while scrolling, creating depth. +- **Page transition** — An animation that plays when navigating from one page or route to another. +- **View transition** — The browser morphs between two states or pages, connecting shared elements. + +### Feedback & Interaction — responding to the user's actions +- **Hover effect** — Visual change when the cursor moves over an element. +- **Press / Tap feedback** — A subtle scale-down when an element is clicked, so it feels physical. +- **Hold to confirm** — A progress effect that fills up while the user holds a button. +- **Drag** — Moving an element by grabbing it, often with momentum when released. +- **Drag to reorder** — Dragging items in a list to rearrange them, while the others shift to make room. +- **Swipe to dismiss** — Dragging an element off-screen to close it, like a drawer or toast. +- **Rubber-banding** — Resistance and snap-back when you drag past a boundary (the iOS overscroll feel). +- **Shake / Wiggle** — A quick side-to-side jitter signaling an error or rejected input. +- **Ripple** — A circle expanding from the point of a tap, confirming the press. + +### Easing — how speed changes over an animation +- **Easing** — The rate at which an animation speeds up or slows down. +- **Ease-out** — Starts fast, ends slow. The default for most UI and anything responding to the user. +- **Ease-in** — Starts slow, ends fast. Usually avoided; can feel sluggish. +- **Ease-in-out** — Slow, fast, slow. Good for elements already on screen moving from A to B. +- **Linear** — Constant speed. Avoid for UI; reserve for spinners or marquees. +- **Cubic-bezier** — A custom easing curve you define for precise control. +- **Asymmetric easing** — A curve that accelerates and decelerates at different rates. Feels more alive than a symmetric one. + +### Spring Animations — physics-based motion as an alternative to fixed-duration easing +- **Spring** — Motion driven by physics (tension, mass, damping) rather than a set duration. +- **Stiffness / Tension** — How strongly the spring pulls toward its target. Higher feels snappier. +- **Damping** — How quickly a spring settles. Lower damping means more bounce and oscillation. +- **Mass** — How heavy the animated element feels. More mass makes it slower and more sluggish. +- **Bounce** — A spring that overshoots and settles, adding playfulness. +- **Perceptual duration** — How long a spring takes to look finished, even though it keeps micro-settling underneath. +- **Momentum** — Motion that carries velocity, especially after a drag or interruption. +- **Velocity** — How fast and in which direction an element is moving. A spring carries it into the next animation when interrupted, so a flicked element keeps its speed. +- **Interruptible animation** — An animation that can be smoothly redirected mid-flight instead of finishing first. + +### Looping & Ambient Motion — animations that run on their own +- **Marquee** — Text or content that scrolls continuously in a loop. +- **Loop** — An animation that repeats, a set number of times or infinitely. +- **Alternate (yoyo)** — A loop that plays forward then reverses each iteration, instead of jumping back to the start. +- **Orbit** — An element circling around another in a continuous path. +- **Pulse** — A gentle repeating scale or opacity change to draw attention. +- **Float** — A gentle, continuous up-and-down drift that makes a static element feel alive and weightless. +- **Idle animation** — Subtle motion that plays while an element is just sitting there, waiting to be interacted with. + +### Polish & Effects — the small touches that separate good from great +- **Blur** — A blur filter used to soften an element or mask tiny imperfections. +- **Clip-path** — Clipping an element to a shape, used for reveals, masks, and before/after sliders. +- **Mask** — Hiding or revealing parts of an element using a shape or gradient — like clip-path, but with soft, fadeable edges. +- **Before / after slider** — A draggable divider that wipes between two overlaid images to compare them. +- **Line drawing** — An SVG path that draws itself in, like an invisible pen tracing it. +- **Text morph** — Text that animates character by character when it changes, drawing attention to the new value. +- **Skeleton / Shimmer** — A placeholder with a moving sheen shown while content loads. +- **Number ticker** — Digits rolling or counting up to a value. +- **Tabular numbers** — Fixed-width digits so numbers don't shift around as they change. Essential for tickers, timers, and counters. +- **Typewriter** — Text appearing one character at a time, as if being typed. + +### Performance — what keeps motion smooth instead of stuttering +- **Frame rate (FPS)** — Frames drawn per second. 60fps is the baseline for smooth motion; 120fps on newer displays. +- **Jank** — Visible stutter when the browser drops frames because it can't keep up with the animation. +- **Dropped frame** — A frame the browser missed its deadline to draw, causing a tiny hitch in motion. +- **Compositing** — Letting the GPU move or fade an element on its own layer without redoing layout or paint. +- **will-change** — A CSS hint that an element is about to animate, so the browser can promote it to its own layer ahead of time. +- **Layout thrashing** — Reading layout (`offsetHeight`, `getBoundingClientRect`) right after writing styles, repeatedly, forcing the browser to recalculate layout synchronously each time. + +### Principles to Know — concepts that guide when and how to animate +- **Purposeful animation** — Motion should serve a function — orient, give feedback, show relationships — not just decorate. +- **Anticipation** — A small wind-up in the opposite direction before a move, hinting at what's about to happen. +- **Follow-through** — Parts of an element keep moving and settle slightly after the main motion stops, adding weight. +- **Squash & stretch** — Deforming an element as it moves to convey weight, speed, and flexibility. +- **Perceived performance** — The right animation makes an interface feel faster, even when it isn't. +- **Frequency of use** — The more often a user sees an animation, the shorter and subtler it should be. +- **Spatial consistency** — Animating so an element keeps its identity and position across states, so users never lose track of where things went. +- **Hardware acceleration** — Animating transform and opacity lets the GPU keep motion smooth. +- **Reduced motion** — Respecting the user's prefers-reduced-motion setting by toning down or removing motion. diff --git a/.claude/skills/apple-design/SKILL.md b/.claude/skills/apple-design/SKILL.md new file mode 100644 index 0000000000..97ec82d4ef --- /dev/null +++ b/.claude/skills/apple-design/SKILL.md @@ -0,0 +1,287 @@ +--- +name: apple-design +description: Apple's approach to interface design and fluid, physical motion, translated for the web. Use when building or reviewing gesture-driven UI, spring animations, drag/swipe/sheet interactions, momentum and interruptible transitions, translucent materials and depth, typography (optical sizing, tracking, leading), reduced-motion, or the design foundations (feedback, spatial consistency, restraint) behind Apple-style interfaces. +--- + +# Apple Design + +## Initial Response + +When this skill is first invoked without a specific question, respond only with: + +> I'm ready to help you build fluid, Apple-style interfaces on the web, my knowledge comes from Apple's WWDC design talks, translated for the web. + +Do not provide any other information until the user asks a question. + +How Apple builds interfaces that stop feeling like a computer and start feeling like an extension of you. This knowledge comes from Apple's WWDC design talks — chiefly *Designing Fluid Interfaces* (WWDC 2018) — distilled and translated into the web platform (CSS, Pointer Events, `requestAnimationFrame`, spring libraries like Motion/Framer Motion). + +The through-line: **an interface feels alive when motion starts from the current on-screen value, inherits the user's velocity, projects momentum forward, and can be grabbed and reversed at any instant.** Springs are the tool that makes all of this natural, because they are inherently interruptible and velocity-aware. + +## The Core Idea + +> "When we align the interface to the way we think and move, something magical happens — it stops feeling like a computer and starts feeling like a seamless extension of us." + +An interface is fluid when it behaves like the physical world: things respond instantly, move continuously, carry momentum, resist at boundaries, and can be redirected mid-motion. Everything below is a way to get closer to that. + +Apple frames design as serving four human needs: **safety/predictability, understanding, achievement, and joy.** Every rule here serves one of them. + +## 1. Response — kill latency + +The moment lag appears, the feeling of directness "falls off a cliff." Response is the foundation everything else is built on. + +- **Respond on pointer-down, not on release.** Highlight a button the instant it's pressed. Waiting for `click`/touch-up to show feedback feels dead. +- **Be vigilant about every latency.** Audit debounces, artificial timers, transition waits, and the ~300ms tap delay. Anything on the input path that isn't essential is a regression. +- **Feedback must be continuous *during* the interaction, not just at the end.** For a drag, slider, or drawer, update the UI 1:1 with the pointer the whole way through — never animate only when the gesture completes. + +```css +/* Feedback lives on the press, and it's instant */ +.button:active { + transform: scale(0.97); + transition: transform 100ms ease-out; +} +``` + +## 2. Direct manipulation — 1:1 tracking + +> "Touch and content should move together." + +When the user drags something, it must stay glued to the finger — and respect the offset from *where they grabbed it*. Snapping to the element's center on grab breaks the illusion immediately. + +- Use Pointer Events with `setPointerCapture` so tracking continues even when the pointer leaves the element's bounds. +- Track a short **velocity/position history** (last few `pointermove` events), not just the current point — you'll need velocity at release. + +```js +el.addEventListener('pointerdown', (e) => { + el.setPointerCapture(e.pointerId); + const grabOffset = e.clientY - el.getBoundingClientRect().top; // respect where they grabbed + // ...track position + timestamp history for velocity +}); +``` + +## 3. Interruptibility — the single most important principle + +> "The thought and the gesture happen in parallel." + +Every animation must be interruptible and redirectable at any moment. A user must be able to grab a moving element mid-flight and reverse it without waiting for the animation to finish. A closing modal the user grabs again should follow the finger — not finish closing first, then reopen. + +- **Never lock out input during a transition.** +- **Always animate from the *presentation* (current) value, never the target value.** On interrupt, read the element's live on-screen transform and start the new animation from there. Starting from the logical/target value causes a visible jump. +- **Avoid CSS transitions and `@keyframes` for anything gesture-driven** — they can't be smoothly grabbed and reversed mid-flight. Springs animate from the current value by default, which is exactly what interruption needs. +- **When a gesture reverses, blend velocity — don't hard-cut it.** Replacing one animation with another at a reversal creates a velocity discontinuity, a "brick wall." Spring libraries that carry velocity through a re-target avoid it. (This is what iOS's *additive animations* do natively; on the web, choose a spring library that re-targets from the current velocity.) +- **Decompose 2D motion into independent X and Y springs.** A single spring on a 2D distance desyncs when X and Y have different velocities. + +## 4. Behavior over animation — use springs + +> "Think of animation as a conversation between you and the object, not something prescribed by the interface." + +A pre-scripted, fixed-duration animation can't respond to new input. A spring can — new input just changes the target, and the motion stays continuous. Reach for springs for anything a user can touch. + +Apple deliberately replaced the physics triplet (mass/stiffness/damping) with two designer-friendly parameters. Think in these: + +- **Damping ratio** — controls overshoot. `1.0` = critically damped, no bounce, smooth settle. `< 1.0` = overshoots and oscillates. Lower = bouncier. +- **Response** — how quickly the value reaches the target, in seconds. Lower = snappier. **This is not "duration"** — a spring has no fixed duration; its settle time emerges from the parameters. + +**Defaults:** +- Start most UI at **damping `1.0`** (critically damped) — graceful and non-distracting. +- Add bounce (**damping ~`0.8`**) **only when the gesture itself carried momentum** (a flick, a throw, a drag release). Overshoot on a menu that just faded in feels wrong; overshoot on a card you flicked feels right. + +**Concrete values Apple ships:** + +| Interaction | Damping | Response | +| --- | --- | --- | +| Move / reposition (e.g. PiP) | `1.0` | `0.4` | +| Rotation | `0.8` | `0.4` | +| Drawer / sheet | `0.8` | `0.3` | + +**Web mapping (Motion / Framer Motion):** the `bounce` + `duration` spring API maps closely to Apple's damping + response. A safe house style is `bounce: 0` springs everywhere by default (Motion's `damping` is a physics coefficient, not Apple's damping ratio); reserve bounce for momentum-driven, physical interactions. + +```js +import { animate } from 'motion'; + +// Critically damped default (no overshoot) +animate(el, { y: 0 }, { type: 'spring', bounce: 0, duration: 0.4 }); + +// Momentum interaction — a little bounce, only because a flick preceded it +animate(el, { y: target }, { type: 'spring', bounce: 0.2, duration: 0.4 }); +``` + +## 5. Velocity handoff — the seam between drag and animation + +When a gesture ends, the animation must **continue at the finger's exact velocity**, so there's no visible seam between dragging and animating. This is the detail that most separates "fluid" from "fine." + +Pass the pointer's release velocity as the spring's initial velocity. Some spring APIs want **relative** velocity — normalize it by the remaining distance to the target: + +``` +relativeVelocity = gestureVelocity / (targetValue − currentValue) +``` + +Example: element at `y=50`, target `y=150` (100px to go), finger moving 50px/s → initial spring velocity = `50 / 100 = 0.5`. Framer Motion / Motion take absolute px/s velocity directly (`velocity` option), so you usually hand it the raw value. + +## 6. Momentum projection — animate to where the gesture is *going* + +> "Take a small input and make a big output." + +Don't snap to the nearest boundary from the *release point*. Use velocity to **project the resting position** — exactly like scroll deceleration — then snap to the target nearest that projected point. This is what makes a flick feel like it throws the element. + +Apple's exact projection function (from the *Designing Fluid Interfaces* sample code): + +```js +// decelerationRate ≈ 0.998 for normal scroll feel; 0.99 for snappier +function project(initialVelocity /* px/s */, decelerationRate = 0.998) { + return (initialVelocity / 1000) * decelerationRate / (1 - decelerationRate); +} + +const projectedEndpoint = currentPosition + project(releaseVelocity); +const target = nearestSnapPoint(projectedEndpoint); // choose target from the projection +animateSpringTo(target, { velocity: releaseVelocity }); // then hand off velocity (§5) +``` + +Note: the physics-textbook `v²/(2·decel)` is *not* what Apple ships — use the exponential-decay form above. This is the standard behavior in good bottom-sheets and carousels (Vaul, Embla). + +## 7. Spatial consistency — symmetric paths, anchored origins + +> "If something disappears one way, we expect it to emerge from where it came." + +- **Enter and exit along the same path.** A panel that slides in from the right must dismiss to the right. In-from-right / out-the-bottom feels disconnected and confusing. +- **Anchor interactions to their source.** A menu, popover, or sheet should originate from the element that triggered it — set `transform-origin` to the trigger, so the spatial relationship between button and content is obvious. (This is the same origin-awareness point as popovers scaling from their trigger, not their center.) + +## 8. Hint in the direction of the gesture + +Humans predict a final state from a trajectory. Intermediate motion should telegraph where things are going — Control Center modules "grow up and out toward your finger." Make the in-between frames point at the outcome, not just interpolate blindly to it. + +## 9. Rubber-banding — soft boundaries + +At an edge, resist progressively instead of stopping hard. A hard stop reads as "frozen"; continuous resistance reads as "responsive, but there's nothing more here." Apply damping that increases the further past the boundary the user drags. + +```js +// The further past the bound, the less the element follows — real things slow before they stop +function rubberband(overshoot, dimension, constant = 0.55) { + return (overshoot * dimension * constant) / (dimension + constant * Math.abs(overshoot)); +} +``` + +## 10. Gesture design details (the "feel" checklist) + +- **Tap:** highlight on touch-*down* (instant), commit on touch-*up*. Add ~10px of hysteresis/hit padding around the target, and allow cancel-by-dragging-away and back. +- **Drag/swipe:** require a small movement threshold (hysteresis, ~10px) before committing to a direction, then track 1:1. +- **Detect all plausible gestures in parallel from the first move**, then confidently cancel the losers once intent is clear. Avoid recognizers that only report a *final* state (`swipeleft`-type events) — they throw away the continuous tracking you need for feedback. +- **Minimize disambiguation delays.** Double-tap detection unavoidably delays single taps; only pay that cost where double-tap truly exists. + +## 11. Frame-level smoothness + +Smoothness is about *what's in the frames*, not just the frame rate. + +- For very fast motion, a subtle **motion blur / stretch** encodes speed and reads better than a hard sharp streak. +- `requestAnimationFrame` is the web's display-synced clock (Apple uses `CADisplayLink`). Animate only compositor-friendly properties — `transform` and `opacity` — and add `will-change` only after you measure a shift or dropped frames (see `../animation-performance/SKILL.md`). + +## 12. Materials & depth — translucency conveys hierarchy + +Apple uses translucent materials as a floating functional layer that brings structure without stealing focus. On the web, approximate with `backdrop-filter`. + +- **Build nav/toolbars/sheets as translucent layers** (`backdrop-filter: blur()` + a semi-transparent background) with content scrolling underneath — not opaque bars that consume a fixed strip. +- **Material weight encodes hierarchy:** darker/heavier materials separate structural regions (sidebars); lighter materials draw attention to interactive elements (buttons). **Never stack a light translucent surface on another** — legibility collapses. +- **Bigger surfaces should read as thicker:** stronger blur + a deeper shadow than small chips. Consider context-aware shadow — heavier over busy/text content for separation, lighter over plain backgrounds. +- **Dim to focus, separate to keep flow.** A modal task pairs the surface with a dimming scrim and pushes the background back/down. A parallel, non-blocking panel uses translucency and offset *without* a scrim so the flow isn't broken. For stacked sheets, progressively dim and push back each parent layer. +- **Vibrancy keeps text legible over changing backgrounds.** Over blurred/translucent surfaces, don't use flat gray text — use higher-contrast, slightly heavier weight, and a small letter-spacing bump. Put color on a solid layer, not the translucent foreground. +- **Scroll edge effects, not hard dividers.** Instead of a 1px border under a sticky header, fade a small blur/gradient mask where content meets floating chrome — only where floating UI actually overlaps content. +- **Materialize, don't just fade.** For glass/blur surfaces, animate blur radius and scale together on enter/exit, so the surface reads as a real material arriving rather than a plain opacity fade. + +```css +.toolbar { + background: rgba(255, 255, 255, 0.6); + backdrop-filter: blur(20px) saturate(180%); + border-top: 1px solid rgba(255, 255, 255, 0.4); /* bright top edge = light catching the material */ +} +``` + +## 13. Multimodal feedback — motion + sound + haptics + +Three rules for combining senses (from *Designing Audio-Haptic Experiences*): + +1. **Causality** — it must be obvious what caused the feedback. Trigger it on the actual causal event (the toggle flipping, the item snapping home), and match its character to the action's physicality. +2. **Harmony** — the visual, the sound, and the haptic must fire on the **same frame**. Latency between them destroys the illusion. Don't let a CSS transition lag the audio/haptic (Vibration API). +3. **Utility** — add feedback only where it earns its place. Reserve haptics/sound for meaningful moments (success, error, commit, snap). Over-feedback trains users to ignore all of it. + +## 14. Reduced motion & accessibility + +Reduced motion doesn't mean *no* feedback — it means a gentler, non-vestibular equivalent. Respond to three independent signals and bake them into your components: + +- **`prefers-reduced-motion: reduce`** — replace slides/springs/parallax with short opacity **cross-fades or static transitions**. Drop elastic/overshoot. Keep opacity/color changes that aid comprehension. +- **`prefers-reduced-transparency: reduce`** — make translucent surfaces frostier/solid: raise background opacity, drop the blur. +- **`prefers-contrast: more`** — near-solid backgrounds with a defined, contrasting border. + +Also: avoid full-viewport moving backgrounds, slow looping oscillations (near 0.2 Hz / one cycle per 5s), and abrupt brightness jumps (ease dark↔light theme changes). Make large moving objects semi-transparent while they travel, and fade big surfaces out during a large reposition and back in once settled. + +```css +@media (prefers-reduced-motion: reduce) { + .sheet { transition: opacity 200ms ease; transform: none !important; } +} +@media (prefers-reduced-transparency: reduce) { + .toolbar { background: white; backdrop-filter: none; } +} +``` + +## 15. Typography — optical sizing, tracking, leading + +Apple designs type to change shape with size; the same discipline applies on the web. (From *The Details of UI Typography*, WWDC 2020.) + +- **Tracking (letter-spacing) is size-specific — never one value for all sizes.** Large display text wants *negative* tracking (letters read too far apart as they grow); small text wants slightly *positive* tracking for legibility. A fixed `letter-spacing` is wrong somewhere. Tighten headings, leave body near `0`. +- **Leading (line-height) tracks size inversely.** Tight on large headings, looser on body copy. Increase it for scripts with tall ascenders/descenders; tighten it for dense, information-heavy UI. +- **Build hierarchy from weight + size + leading as a set,** not size alone. Emphasize with weight — it adds presence without taking more space. +- **Respect the user's text-size setting** (Dynamic Type). Scale layout *with* the text — spacing in `rem`/`em`, not fixed px — so a larger font doesn't break the layout. +- **Default to the platform's system font** before a custom face; it already ships optical sizing, tracking tables, and legibility tuning. Override only with a reason. + +```css +:root { font: 100%/1.5 system-ui, sans-serif; } /* body: system font, comfortable leading */ + +.display { + font-size: clamp(2rem, 5vw, 4rem); + line-height: 1.05; /* tight leading for large text */ + letter-spacing: -0.02em; /* negative tracking as it grows */ + font-optical-sizing: auto; +} +``` + +## 16. Design foundations — the eight principles + +The motion and craft above serve Apple's eight design principles (*Principles of Great Design*, WWDC 2026). Use these as the names you reason with: + +1. **Purpose.** Make with intention; decide what *not* to build. Every feature asks for the user's time, attention, and trust — spend that budget only where it pays off. +2. **Agency.** Keep people in control: offer choices, don't force a single path. Back it with forgiveness — easy undo for slips, a confirmation dialog only for genuinely destructive, irreversible actions (use sparingly; overusing it trains people to click through). +3. **Responsibility.** Act in the user's interest. Privacy: ask at the right moment, only for what's needed, transparently. Safety: anticipate misuse and harm — especially with AI (an allergy-aware recipe app must not suggest a harmful ingredient). Add previews, confirmations, disclaimers; cut a feature whose risk outweighs its value. +4. **Familiarity.** Build on what people already know. Use metaphors that are neither too literal nor too abstract (a trash can means delete), and honor their physics. Be consistent: things that look the same must behave the same and live in the same place (close is always top-left on macOS) so people can predict what happens next. Only break a familiar pattern if you can prove it's better — then test it, don't assume. +5. **Flexibility.** Design for different contexts, devices, and the full range of abilities. Adapt to the platform (iPhone = quick touch; desktop = deep workflows with precise pointer control) and to the situation. Design inclusively (age, language, expertise, accessibility). When no single layout fits everyone, let people personalize — rearrange controls, hide what they don't use. +6. **Simplicity — not minimalism.** Strip the unnecessary so the core purpose shines; burying everything in one place looks minimal but isn't simple. Be concise (plain language, no jargon, fewer steps) and clear (use hierarchy — order, spacing, contrast — so the most important thing is the most obvious). Every element earns its place; sometimes *adding* context simplifies (a video scrubber that shows time remaining). Show the common path first, advanced options one level deeper. +7. **Craft.** Uncompromising attention to detail builds trust. Beautiful typography, colors that adapt to light/dark, clear iconography, and responsive animations that give immediate, natural feedback. Nothing is random — every spacing, timing, and alignment value is a deliberate choice you can defend. Jittery scroll, misaligned icons, and layouts that break on rotation read as carelessness. Craft needs iteration and longevity — keep evolving the design as features and hardware change. +8. **Delight.** The result of getting the other seven right, not confetti tacked on top. Decide the emotion you want people to feel (calm, confident, excited) and reinforce it in every decision. + +Tactical rules that serve these: + +- **Feedback comes in four kinds:** status, completion, warning, error. Confirm meaningful actions, expose ongoing status, warn before problems, validate inline (not on submit). +- **Wayfinding.** Every screen should answer: Where am I? Where can I go? What's there? How do I get out? Never trap the user. +- **Grouping & mapping.** Proximity implies relationship; place a control near what it affects and arrange controls to mirror what they change. If you need a label to explain a control, the mapping is weak. +- **Direct, specific labels beat safe generic ones.** Name nav items for their contents ("Progress", "Library"), not vague umbrellas ("Home"). Specificity creates predictability. + +## 17. Process + +- **Prototype interactively — an interactive demo is worth "a million static designs."** You discover the interface by building and playing with it; a working prototype also sets a concrete bar that prevents a mediocre final implementation. +- **Design interaction and visuals together.** "You shouldn't be able to tell where one ends and the other begins." Motion is not a layer added after the pixels. +- **Test with real people in real context**, and review motion with fresh eyes — play it in slow motion / frame-by-frame to catch what's invisible at full speed. + +## Quick Reference + +| Need | Technique | Concrete value | +| --- | --- | --- | +| Default UI spring | Critically damped, no overshoot | `damping 1.0`, `response 0.3–0.4` | +| Momentum / flick spring | Under-damped, slight bounce | `damping ~0.8`, `response 0.3–0.4` | +| Gesture → spring velocity | Hand off release velocity | `gestureVelocity / (target − current)` if normalized | +| Flick landing point | Project momentum | `current + (v/1000)·d/(1−d)`, `d ≈ 0.998` | +| Interrupt cleanly | Start from presentation (live) value | read the on-screen transform | +| Avoid reversal "brick wall" | Carry velocity through re-target | spring that blends velocity | +| Decide reverse vs. commit | Snap to the point nearest the projected endpoint | at release | +| 1:1 drag | Pointer Events + capture | respect the grab offset | +| Feedback | On pointer-down, continuous | never only at the end | +| Boundary | Rubber-band, don't hard-stop | progressive resistance | +| Translucent chrome | `backdrop-filter` layer | content scrolls under | +| Type tracking | Size-specific, never fixed | tighten large text (`-0.02em`), body near `0` | +| Reduced motion | Cross-fade, not slide/spring | `@media (prefers-reduced-motion)` | diff --git a/.claude/skills/ask-emil/SKILL.md b/.claude/skills/ask-emil/SKILL.md new file mode 100644 index 0000000000..2fe1a76a2e --- /dev/null +++ b/.claude/skills/ask-emil/SKILL.md @@ -0,0 +1,72 @@ +--- +name: ask-emil +description: Ask which skill or flow fits your situation. A router over the skills in this repo. +disable-model-invocation: true +--- + +# Ask Emil + +Before stating what a skill does or recommending one, read that skill's SKILL.md: the summaries here are for orientation only. Then recommend **one** skill (or one short sequence) for the user's situation, say why in a sentence, and name the skill they'd reach for next. Don't list the whole map back at them. + +A **flow** is a path through the skills. Most UI work travels one **main flow**, from idea to shipped. Some skills are **upkeep** you run on a codebase that already exists, some are **references** that sit underneath everything, and a few stand alone. + +## The main flow: idea → ship + +1. **Not sure what it should look or feel like?** Detour through **`/prototype`**. It builds several genuinely different versions behind a live picker, then promotes the one you pick into the real code. Reach for it whenever a design question is hard to settle in words. + +2. **Build it.** Pick the builder by what's moving: + - **`/pick-ui-library`** first if the task needs a dependency (dropdown, dialog, toast, drawer, command menu, drag and drop, charts). Don't let the agent hand-roll a toast. + - **`/animate`** for one animation on the web: whether to animate at all, then tool, properties, curve, duration, interruption, exit. + - **`/choreograph`** when several elements move together: staggers, hero entrances, view swaps, an item leaving while siblings close the gap. + - **`/gestures`** when the user's finger drives it: drag, swipe, sheets, snap points, swipe-to-dismiss. + - **`/animate-expo`** for any of the above in React Native or Expo. + - **`/ask-sonner`** when the work is toasts with Sonner. + +3. **Try to break it.** Before calling it done: + - **`/break-ui`** feeds it worst-case data (long names, empty lists, huge counts, emoji, non-Latin text) behind a toggle and reports what broke. + - **`/review-animations`** reviews the motion in the diff against a strict bar. Default to flagging; approval is earned. + - **`/mobile-native`** if it runs on a phone as a web app: sticky hover, the 100vh bug, inputs that zoom, safe areas. + - **`/animation-performance`** if anything drops frames. + +4. **Learn from the session.** **`/learn-taste`** closes the loop. Run it at the end, in the same session, before you clear: it collects every design correction you made (including edits you made yourself) and turns each into a rule with its why, so the next agent doesn't repeat the mistake. + +## Upkeep: a codebase that already exists + +Not feature work. Run these when you have a spare moment, or when the app "feels off". + +- **The motion needs work across the app** → **`/improve-animations`**. Read-only: it audits every animation and writes prioritized, self-contained plans another agent (or a cheaper model) can execute. +- **It feels static** → **`/find-animation-opportunities`**. Read-only: it proposes motion with exact values, and rejects everything that shouldn't move. Build the ones you accept with `/animate`. +- **It feels slow or over-animated** → **`/remove-animations`**. Edits code, but only to subtract: motion on keyboard actions, high-frequency surfaces, decoration with no purpose. + +These three cover different questions. If the user isn't sure which, ask whether the problem is *bad* motion, *missing* motion, or *too much* motion. + +## References underneath + +Model-invoked skills the others lean on. Reach for them directly when the **knowledge**, not a process, is what's missing. + +- **`/emil-design-eng`**: the core philosophy for UI polish, component interactions, and the invisible details. The fallback when no narrower skill fits. +- **`/apple-design`**: Apple's principles for interface design and fluid, physical motion, translated for the web. +- **`/animation-vocabulary`**: when the problem is the **word**. "What's it called when…" turns a vague description into the exact term to prompt with. + +## Standalone + +- **`/write-swift`**: modern Swift, Swift 6 concurrency, and native iOS code. Off the web flow entirely. + +## Common situations + +| You say | Reach for | +| --- | --- | +| "Animate this" | `/animate` | +| "These should come in one after another" | `/choreograph` | +| "It doesn't follow my finger" | `/gestures` | +| "It stutters" / "it's janky" | `/animation-performance` | +| "Does this animation feel right?" | `/review-animations` | +| "Make the app feel better" | `/improve-animations` | +| "What could animate here?" | `/find-animation-opportunities` | +| "Too much is moving" | `/remove-animations` | +| "Give me a few options" | `/prototype` | +| "Which library should I use?" | `/pick-ui-library` | +| "Works in Chrome, feels wrong on my phone" | `/mobile-native` | +| "Try the worst case" | `/break-ui` | +| "What's that bouncy thing called?" | `/animation-vocabulary` | +| "Stop making that mistake" | `/learn-taste` | diff --git a/.claude/skills/ask-sonner/API.md b/.claude/skills/ask-sonner/API.md new file mode 100644 index 0000000000..74c883d5ff --- /dev/null +++ b/.claude/skills/ask-sonner/API.md @@ -0,0 +1,64 @@ +# Sonner API Reference + +Exact props, types, and defaults. Options passed to `toast()` override the same options set via the Toaster's `toastOptions`. + +## `` + +| Prop | Type | Default | Description | +| --- | --- | --- | --- | +| `theme` | `string` | `'light'` | `'light'`, `'dark'`, or `'system'`. | +| `richColors` | `boolean` | `false` | Makes error and success states more colorful. | +| `expand` | `boolean` | `false` | Toasts expanded by default (otherwise they expand on hover). | +| `visibleToasts` | `number` | `3` | Amount of visible toasts. | +| `id` | `string` | – | Toaster id, targeted by `toast()`'s `toasterId` option. | +| `position` | `string` | `'bottom-right'` | `top-left`, `top-center`, `top-right`, `bottom-left`, `bottom-center`, `bottom-right`. | +| `closeButton` | `boolean` | `false` | Adds a close button to all toasts. | +| `offset` | `string \| number \| object` | `'24px'` | Offset from screen edges. Object form is per-side: `{ bottom: '24px', right: '16px' }`. | +| `mobileOffset` | `string \| number \| object` | `'16px'` | Offset when screen width < 600px. | +| `swipeDirections` | `array` | based on position | Allowed swipe-to-dismiss directions. | +| `dir` | `'ltr' \| 'rtl' \| 'auto'` | document direction | Text directionality. | +| `hotkey` | `string[]` | `['altKey', 'KeyT']` | Keyboard shortcut that focuses the toaster area. | +| `invert` | `boolean` | `false` | Dark toasts in light mode and vice versa. | +| `toastOptions` | `object` | – | Default options applied to every toast (any `toast()` option below). | +| `gap` | `number` | `14` | Gap between toasts when expanded. | +| `icons` | `object` | – | Replace default icons: `{ success, info, warning, error, loading }`; `null` removes one. | +| `containerAriaLabel` | `string` | `'Notifications'` | ARIA label for the toast container. | + +## `toast()` options + +`toast(message, options)` — message is a string, JSX, or a function returning JSX. Returns the toast's id. + +| Option | Type | Default | Description | +| --- | --- | --- | --- | +| `description` | `ReactNode` | – | Renders underneath the title; also accepts a function returning JSX. | +| `closeButton` | `boolean` | `false` | Adds a close button. | +| `invert` | `boolean` | `false` | Dark toast in light mode and vice versa. | +| `duration` | `number` | `4000` | Milliseconds before auto-close. `Infinity` persists the toast. | +| `position` | `string` | `'bottom-right'` | Position of this toast. | +| `dismissible` | `boolean` | `true` | If `false`, the user cannot dismiss the toast. | +| `icon` | `ReactNode` | – | Icon in front of the text; `null` removes the default. | +| `action` | `ReactNode \| { label, onClick }` | – | Primary button; clicking closes the toast unless `onClick` calls `event.preventDefault()`. | +| `cancel` | `ReactNode \| { label, onClick }` | – | Secondary button; clicking closes the toast. | +| `actionButtonStyle` | `object` | `{}` | Styles for the action button. | +| `cancelButtonStyle` | `object` | `{}` | Styles for the cancel button. | +| `id` | `string \| number` | – | Custom id; calling `toast()` again with the same id updates the existing toast. | +| `testId` | `string` | – | Rendered as `data-testid` for e2e tests. | +| `toasterId` | `string` | – | Id of the toaster to render this toast in. | +| `style` | `object` | – | Inline styles for the toast. | +| `classNames` | `object` | – | Classes per part: `{ toast, title, description, actionButton, cancelButton, closeButton }`. Needs `!important` unless `unstyled`. | +| `unstyled` | `boolean` | `false` | Removes all default styles. | +| `onDismiss` | `(toast) => void` | – | Fires when the close button is clicked, the toast is swiped away, or `toast.dismiss()` closes it. | +| `onAutoClose` | `(toast) => void` | – | Fires when the toast closes automatically after `duration`. | + +## Functions + +| Function | Purpose | +| --- | --- | +| `toast(message, opts?)` | Render a toast; returns its id. | +| `toast.success / .error / .info / .warning(message, opts?)` | Typed toast with matching icon. | +| `toast.loading(message, opts?)` | Toast with a spinner; update it by id. | +| `toast.promise(promise, { loading, success, error })` | Loading toast that resolves with the promise; `success`/`error` accept strings, JSX, functions of the result, or objects of toast options. | +| `toast.custom((t) => jsx, opts?)` | Headless toast — your JSX, Sonner's behavior. | +| `toast.dismiss(id?)` | Dismiss one toast, or all when called without an id. | +| `toast.getToasts()` | All active toasts, usable outside React. `toast.getHistory()` includes dismissed ones. | +| `useSonner()` | React hook returning `{ toasts }`. | diff --git a/.claude/skills/ask-sonner/SKILL.md b/.claude/skills/ask-sonner/SKILL.md new file mode 100644 index 0000000000..368752157d --- /dev/null +++ b/.claude/skills/ask-sonner/SKILL.md @@ -0,0 +1,88 @@ +--- +name: ask-sonner +description: Guide to Sonner, the React toast library — install and wire up the Toaster, pick the right toast() call, promise and loading toasts, updating, dismissing and persisting toasts, styling, theming and icons, positioning and multiple toasters. Use when working with Sonner or troubleshooting it — toasts that don't appear, appear twice, lose their styles, ignore Tailwind classes, sit behind a modal, or don't follow dark mode. +--- + +# Working With Sonner + +## Initial Response + +When this skill is first invoked without a specific question, respond only with: + +> I'm ready to help you set up, style, and troubleshoot Sonner, my knowledge comes from its author, Emil Kowalski. + +Do not provide any other information until the user asks a question. + +A guide skill for [Sonner](https://sonner.emilkowal.ski), the toast library. When a task involves Sonner — wiring it up, rendering toasts, styling them, or fixing them — answer from this file first. Full prop tables for `` and `toast()` live in [API.md](API.md); read it when you need an exact prop name, type, or default. + +## Setup + +Two pieces, and only two: + +1. **One ``, mounted once**, as close to the root as possible (in Next.js: `layout.tsx` — it works inside server components). Never render it per-page or conditionally; a second Toaster without its own `id` duplicates every toast. +2. **`toast()` called from client code** — event handlers, effects, callbacks. It's a plain function, no hook or provider needed, but it does nothing on the server: in a server action, return the result and call `toast()` in the client code that receives it. + +```jsx +import { Toaster } from 'sonner'; // once, in layout +import { toast } from 'sonner'; // anywhere client-side +``` + +## Picking the right call + +| You want | Call | +| --- | --- | +| Plain message | `toast('Title')` — add `{ description }` for a second line | +| Success / error / info / warning icon | `toast.success('…')`, `toast.error('…')`, etc. | +| Spinner while you manage state yourself | `toast.loading('…')`, then update it by id | +| Loading → success/error tied to a promise | `toast.promise(promise, { loading, success, error })` — success/error accept functions receiving the resolved value/error | +| Button that does something | `{ action: { label, onClick } }` — closes the toast unless `onClick` calls `event.preventDefault()`; `cancel` is the secondary variant | +| Custom JSX, default toast shell | `toast()` | +| Custom JSX, no styles at all | `toast.custom((t) => )` — headless, `t` gives you the id to dismiss | + +## Recipes + +**Update a toast** — call `toast()` again with the same `id`; only the props you pass change. Switching to `toast.success(…, { id })` changes the type. This is how loading → success flows work without `toast.promise`: + +```jsx +const id = toast.loading('Uploading…'); +toast.success('Uploaded', { id }); +``` + +**Persist** — `{ duration: Infinity }`. **Dismiss** — `toast.dismiss(id)`, or `toast.dismiss()` for all. **Read active toasts** — `useSonner()` in React, `toast.getToasts()` outside it. + +**Links or components in the text** — pass a function for the title or description: `toast(() => View)`. + +**Multiple toasters** — give each an `id` and target with `toast('…', { toasterId: 'canvas' })`. A toaster with an `id` renders only toasts targeted at it; a toaster without one renders only untargeted toasts. + +**Close callbacks** — `onDismiss` fires on close button, swipe, or `toast.dismiss()`; `onAutoClose` fires on timeout. They are separate; there is no single "closed" callback. + +## Styling — the escalation ladder + +Climb only as far as the change requires. Exception: if you'd mark more than a few classes `!important`, go straight to headless — it's the recommended end state. + +1. **Defaults** — plus `richColors` on the Toaster for colorful success/error, `invert` to flip against the theme. +2. **Inline tweaks** — `toastOptions={{ style: {…} }}` on the Toaster for all toasts, or `style` per `toast()` call. +3. **Classes on parts** — `toastOptions={{ classNames: { toast, title, description, actionButton, cancelButton, closeButton } }}`. Sonner's injected styles win the cascade, so every class needs `!important` (Tailwind: `!text-red-900`). If you're marking more than a few things important, stop — go headless. +4. **Headless** — `toast.custom()` with your own JSX, keeping Sonner's positioning, stacking, and swipe. The recommended approach for a design-system toast: wrap it in your own `toast()` abstraction. (`unstyled: true` exists as a halfway house, but headless gives more control for the same effort.) + +**Icons** — swap defaults per-type with the Toaster's `icons` prop, per-toast with `icon`, remove with `null`. + +**Theme** — `theme` defaults to `'light'` and does not track the OS. Pass `theme="system"`, or wire your theme provider: `` from `next-themes`. + +## Troubleshooting + +| Symptom | Cause → fix | +| --- | --- | +| Toast never appears | No `` mounted, or it unmounted (conditional render, per-page placement). Mount one at the root. If calling from a server action: `toast()` is client-only — call it with the action's result on the client. | +| Same toast appears twice | Two Toasters mounted (layout **and** page) — keep one. Or `toast()` fired in an effect under React StrictMode's dev double-invoke — fire from the event handler instead, or pass a stable `id` so the second call updates rather than duplicates. | +| Tailwind/CSS classes have no effect | Default styles override them. Mark them `!important`, or use `unstyled` / headless (see the ladder above). | +| Toasts render completely unstyled (common in Astro, view transitions) | Sonner's injected stylesheet was lost — import it explicitly in a layout: `import 'sonner/dist/styles.css'`. | +| Unstyled inside Shadow DOM | Styles land in `document.head`, not the shadow root. Copy the style tag whose text includes `[data-sonner-toaster]` into the shadow root. | +| Toast behind a modal/overlay, or clipped | An ancestor creates a stacking context (`transform`, `filter`) or clips it (`overflow`), or the overlay out-z-indexes the toaster. Move `` to the document root, outside any dialog/portal container. | +| Dark mode ignored | `theme` defaults to `'light'` — set `theme="system"` or pass the resolved theme (see Theme above). | +| Success/error look gray, not green/red | That's the default. Add `richColors` to the Toaster. | +| Toast never closes | `duration: Infinity`, or a `toast.promise` whose promise never settles — the loading toast waits forever. | +| `toast.promise` stuck on loading | It needs a promise (or a function returning one) as its first argument, and the promise must actually resolve/reject. | +| Swipe-to-dismiss goes the wrong way / doesn't work | Directions derive from `position`. Override with `swipeDirections` on the Toaster. | +| Toast shows up in every toaster | Multiple toasters need targeting: give each Toaster an `id` and pass `toasterId` in the `toast()` call. | +| Toasts too close to the screen edge on mobile | `offset` (desktop, default 24px) and `mobileOffset` (<600px, default 16px) — numbers, CSS strings, or per-side objects. | diff --git a/.claude/skills/better-accessibility/SKILL.md b/.claude/skills/better-accessibility/SKILL.md new file mode 100644 index 0000000000..e882d3cb0a --- /dev/null +++ b/.claude/skills/better-accessibility/SKILL.md @@ -0,0 +1,130 @@ +--- +name: better-accessibility +description: Reviews and fixes keyboard and focus behavior, ARIA, accessible names, forms, screen-reader announcements, motion and zoom against WCAG 2.2. +--- + +# Accessibility + +This skill reviews and fixes semantics, keyboard and focus behavior, accessible names, forms, announcements, motion and zoom. It reports each failure against the WCAG criterion it breaks and writes the fix in the project's styling system. + +Reviewing means two walks. Keyboard-only, where every flow completes without a mouse. Then screen-reader, where every control announces a name, a role and its state. When unsure, take the platform default over a custom rebuild, and remove ARIA rather than add it. + +Contrast measurement and color fixes belong to `better-colors`. Text sizing, iOS input zoom and language metadata belong to `better-typography`. Spacing between targets and spatial RTL belong to `better-layout`. Label, error and alt-text wording belong to `better-writing`. Animation recipes belong to `better-motion`. Hover styling and scroll containment belong to `better-ui`. + +## Criteria, not conventions + +A finding cites a WCAG 2.2 Level A or AA criterion by number, a concrete task an assistive-technology user cannot complete or an escalation trigger listed in [reporting.md](reporting.md). Everything else is a recommendation and never `HIGH`. That covers AAA criteria, APG conventions, the one-`

` and no-skipped-levels outline, validating on submit over a disabled button and the 44px and 40px targets. The criterion thresholds below are exact. The larger targets are heuristics, so keep an established, usable density. + +## Native elements first + +The first rule of ARIA: don't use ARIA when a native element exists. ` +``` + +Check the whole perimeter of a custom indicator against every adjacent color it crosses. That means component fills, page surfaces, images, gradients and hover and selected states. A token, brand color or `currentColor` passes only when that rendered check does. + +In `forced-colors: active` (Windows High Contrast), keep the default color adjustment or name a system color such as `Highlight`. `forced-color-adjust: none` freezes the authored color, so use it only where you have checked the control stays perceivable. + +Group focus styles with `:focus-within` when a wrapper should light up while an inner input has focus, such as a search box with an icon inside the border. + +## Focus not obscured + +Pad the scroll container with `scroll-padding-block-start` for a sticky header and `scroll-padding-block-end` for a sticky footer or cookie banner. The recipe is `better-layout`'s. + +## Skip link + +Target `
` and visually hide the link until focused: + +```css +.skip-link { + position: absolute; + inset-inline-start: -999px; +} +.skip-link:focus { + inset-inline-start: 16px; + inset-block-start: 16px; +} +``` + +```html + + +
…
+
…
+ +``` + +Where the scroller sets no `scroll-padding-block-start`, give in-page anchor targets `scroll-margin-block-start`, such as `80px` under a sticky header. The two add up, so never set both for one header. + +## tabindex rules + +`tabindex="0"` is only for custom interactive elements that aren't natively focusable. `tabindex="-1"` suits headings you move focus to, modal containers and roving-tabindex members. Where a positive value was patching the order, fix the DOM order instead. + +### Roving tabindex + +Tabs, menus, toolbars and radio groups each occupy one Tab stop. Arrow keys move both focus and the `0`: + +```tsx +
+ {tabs.map((tab, i) => ( + + ))} +
+``` + +A combobox keeps DOM focus in its input instead. Point `aria-activedescendant` on the input at the `id` of the highlighted option and update it on arrow keys. + +## Focus trapping and restoration + +Native `` with `showModal()` makes everything behind it inert and closes on Escape: + +```tsx +dialogRef.current.showModal(); // on open +dialogRef.current.close(); // on close +triggerRef.current?.focus(); // return focus to the element that opened it +``` + +A custom overlay that can't use `` needs `role="dialog"`, `aria-modal="true"` and an accessible name via `aria-labelledby`. Put `inert` on everything behind it, which removes background content from the tab order and from assistive tech in one move. Render the overlay outside the inert container, in a portal or a sibling element, because `inert` on an ancestor disables the dialog too: + +```tsx +// On open +document.getElementById("app-content").inert = true; +const dialog = dialogRef.current; +(dialog.querySelector("[autofocus]") ?? + dialog.querySelector("button, [href], input, select, textarea"))?.focus(); + +// On close +document.getElementById("app-content").inert = false; +triggerRef.current?.focus(); +``` + +Either way: + +- On open, focus the first focusable element. For destructive confirmations, focus the least destructive action instead. +- On close, return focus to the trigger, or to the nearest logical container if the trigger is gone. + +## Keyboard patterns (ARIA APG) + +Native elements come with these behaviors; custom widgets must implement them. + +| Widget | Keys | +| --- | --- | +| Dialog | Tab and Shift+Tab stay inside; Escape closes | +| Tabs | Arrow keys move between tabs (wrapping); Tab exits to the panel; Home/End jump to first/last | +| Menu button | Enter/Space/ArrowDown opens and focuses first item; ArrowUp opens and focuses last; arrows navigate; Escape closes and refocuses the button | +| Disclosure / accordion | Header is a `