Turn any SVG into a professional 60 fps animation. A Claude Code skill that brings anything drawn to life: live faces, full-body acting and whole scenes, in React Native and SwiftUI.
Swift
Animate anything: a shared engine, recipes by subject, per-platform templates
Eder Rosa60c6399f2c5c
diff --git a/MOTION.md b/MOTION.mdindex cc5a124..60dddb3 100644--- a/MOTION.md+++ b/MOTION.md@@ -1,82 +1,76 @@# MOTION.md: living illustrations in this project-> Copy this file next to the project's illustrations (for example `src/art/MOTION.md`) and fill in **Part 2** as you learn the project. Part 1 is the method and stays as it is. The `rossark-motion-skill` reads this file first, and Part 2 overrides the skill's defaults.+> Copy this file next to the project's art (for example `src/art/MOTION.md`) and fill in **Part 2** as you learn the project. Part 1 is the method and stays as it is. The `rossark-motion-skill` reads this file first, and Part 2 overrides the skill's defaults.---## Part 1. The method-**The goal:** characters that feel alive and calm. Nothing teleports, nothing bounces, nothing shouts.--### Rules-1. **Never swap drawings mid-motion.** Pupils slide, lids lower and rise, mouths open and close, heads rotate.-2. **No bounce.** Timed motion with strong curves, never springy overshoot.-3. **Small amplitudes.**- - breathing: 1 to 2 units;- - head tilt: 3 to 6°;- - gaze: a few units inside the eye.-4. **Opacity only to appear or disappear**, never to dim a part halfway.-5. **The art keeps its layout.** Motion happens inside the drawing (translate and rotate on groups), never by resizing or moving the view.-6. **Reduced motion means still.** Frame 0 of every clock must be a good drawing.-7. **One main action per scene, plus two or three idle loops.** Side characters and mascots stay quiet.-8. **Unique SVG ids** (clip paths are global to the screen).--### Curves-- **Things that travel** (gaze, head, lid closing): ease-in-out `bezier(0.77, 0, 0.175, 1)`.-- **Things that open** (mouth, lid reopening, a prop appearing): ease-out `bezier(0.23, 1, 0.32, 1)`.-- **Endless loops** (rain, conveyor, rotation): linear.-- **Declare easings at the top of the module:** worklets capture them when they are created.-- **In SwiftUI:** `UnitCurve.bezier` with the same points, or `.timingCurve(...)`, and never a spring with bounce.--### The live face-1. Draw the eyes as plain whites, with no pupils.-2. On top, in the head's coordinates, draw:- - the live eyes: the pupil slides, clipped to the white, and the lid and cheek are skin clipped to a shape 2 units larger than the white;- - then whatever covers the lids (nose, fringe);- - then the live mouth.-3. **One clock per character** (0 to `period` ms, looping). Every channel is a keyframe track `[ms, value, 'out'?]` read from it:- - `lookX` and `lookY`: where the pupil looks;- - `lid`, 0 open to 1 closed (`lidRight` for one eye only);- - `cheek`, 0 to 1, for a happy squint;- - `mouth`, the depth of the open mouth;- - `tilt`, the head angle in degrees.-4. **A loop of 6 to 9 s:**- - a resting gaze, plus one or two glances that glide in about 500 ms and hold for at least 1 s;- - a blink every 3 to 4 s: close in ~90 ms, hold up to 60 ms, reopen in ~150 ms with ease-out;- - the last key equals the first.--| Feeling | Gaze | Lid | Extra |-|---|---|---|---|-| tired | down or at a screen | rests at 0.3 to 0.4 | slow blinks |-| sad | down and away | rests at 0.1 | slow blinks, one slow look up |-| happy | at the viewer or a friend | 0 | `cheek` up once per loop |-| talking | at the listener | 0 | `mouth` in syllables |-| focused | on the task | 0.1 | rare blinks |--### Body, head, scene-- **Breathing:** the character's layer rises 1 to 2 units over 3 to 5 s, ease-in-out. Characters on the same screen breathe out of phase.-- **Head tilt:** layers for back hair, body, head and front, with the head and back hair rotating around the neck pivot. Don't tilt if a hand touches the face.-- **Cropped by an edge:** draw a few units below the crop, so the cut never shows when the character rises.-- **Props:**- - steam rises and fades in and out (`sin(π·p)`);- - rain and drift are linear loops, each with its own phase;- - a clock's colon blinks and its hand steps;- - a phone buzzes in short ±3° bursts, then pauses.-- **A scene that tells an action** plays a one-shot clock when it appears, with windows for each beat. After that, only the idle loops run.+**The goal:** anything drawn (a character, a plant, a flame, a street, a logo, a chart) feels alive and calm. Nothing teleports, nothing bounces, nothing shouts.++### Principles+1. **Never teleport:** interpolate everything; never swap drawings.+2. **Calm by default:** strong curves, no bouncy overshoot.+3. **Small amplitudes:** when unsure, halve it.+4. **Arcs and pivots:** each moving part is a layer rotating around its joint (stem base, hinge, neck, hook).+5. **Overlap and follow-through:** tips and trailing parts move later and further; give each part the same wave with a growing phase delay.+6. **Variety without chaos:**+ - repeated items get a seeded phase, speed and size;+ - nothing moves in sync, and there's no random value per frame.+7. **One main action per scene, plus two or three idle loops.** Side things stay quiet.+8. **Opacity only to appear or disappear.**+9. **The layout never moves:** motion lives inside the drawing.+10. **Reduced motion:** loops freeze on a good frame 0, and one-shots show their final frame.+11. **Nothing runs unseen:** pause off screen, when hidden and in the background.++### The engine+- **Clocks:** a loop clock for idle life, a one-shot clock for a scene that tells an action. One per character, group or scene.+- **Tracks:** keyframes `[ms, value, 'out'?]` read with `track(t, keys)`. The last key equals the first.+- **Helpers:**+ - `wave` (−1 to 1), for sway and breathing;+ - `loop` (0 to 1), for drift and falling;+ - `bell`, to fade in and out;+ - `seg`, for one beat of a one-shot;+ - `seeded(i)`, for per-item variety.+- **Curves:**+ - travel uses ease-in-out `(0.77, 0, 0.175, 1)`;+ - open and arrive use ease-out `(0.23, 1, 0.32, 1)`;+ - leaving uses ease-in;+ - endless loops are linear.++### Quick recipes+| Subject | Recipe |+|---|---|+| Character | breathing 1–2 units over 3–5 s; a blink every 3–4 s; pupils glide; head tilt 3–6° |+| Tail, hair, ears | rotation around the root, phase delayed along the chain, 4–10° |+| Plant | sway 1.5–4° around the base over 3–6 s; leaves on seeded phases |+| Cloth, flag | a wave that travels along the length, growing away from the fixed edge |+| Fire | a lean of 2–4° and a 3–6% stretch on two waves of different periods |+| Smoke, steam | rises 8–14 units and fades in and out with `bell` |+| Water | ripples grow and fade; floating things bob 1–2 units and rock 2° |+| Rain, snow | seeded `loop`s; snow sways sideways |+| Sky | clouds drift over 20–60 s with parallax; sun rays take 30–60 s per turn |+| Lights | a glow of 2–5% over 2–4 s; stars twinkle at seeded times |+| Machines | gears turn linearly by ratio; a clock hand steps with ease-out |+| Phone | ±3° bursts, then a pause |+| Icon, logo | plays once on appear, then rests |+| Chart | a one-shot draw-on, with bars staggered 40–80 ms |### Performance-- One clock per character or scene; everything else is a worklet reading it.-- Freeze clocks off screen, when hidden and with reduced motion. A loop running behind opacity 0 still costs.-- A repeating animation restarts from its current value: reset to 0 before starting, and cancel on cleanup.-- Prefer one SVG per layer over many animated views.+- Everything is a function of one clock's time.+- Draw many items in one SVG or `Canvas`.+- Reset repeating animations to 0 before starting, and cancel them on cleanup.+- Declare curves at the top of the module.### Workflow-1. Read Part 2 and the header comments of the illustration file.-2. List what could live, pick one main action and two or three idle loops.-3. Put every number in a token object at the top of the file.-4. Check frame 0 and that every loop closes without a jump.-5. Run the project's checks.-6. Hand off: what moves, and what hasn't been seen on a real device.+1. Read Part 2 and the art file's header comments.+2. List what could live in the drawing.+3. Pick one main action and two or three idle loops.+4. Split the art into layers at their pivots.+5. Put the numbers in tokens.+6. Check frame 0, the final frames and the loop seams.+7. Run the checks.+8. Hand off: what moves, and what hasn't been seen on a real device.---@@ -86,16 +80,16 @@### Where the code is- **Platform:** *React Native, SwiftUI, web*-- **Live face module:** *path, or "copy `templates/liveFace.tsx` (React Native) or `templates/LiveFace.swift` (SwiftUI) from the skill"*-- **Character / kit / poses:** *paths, and the character's coordinate system (where the head centre is, units)*-- **Existing animated scenes to copy from:** *paths*+- **Motion engine and live face:** *paths, or "copy `templates/react-native/` or `templates/swiftui/` from the skill"*+- **Art kit, characters, poses:** *paths, and the coordinate system (where the head centre or pivot is, units)*+- **Existing animated pieces to copy from:** *paths*### The owner's rules*Quote them in their own words, with the date. They override Part 1.*- …### Rig limits-*Which poses or characters can't do what (no separate head layer, eyes baked into the drawing, a hand on the face).*+*What can't move how (no separate head layer, eyes baked into the drawing, a hand on the face, one flat image).*- …### How changes are checkeddiff --git a/README.md b/README.mdindex 4f4a71e..5a09c2e 100644--- a/README.md+++ b/README.md@@ -1,17 +1,19 @@# rossark-motion-skill-A Claude Code skill for bringing character illustrations to life: eyes whose pupils glide and lids blink, breathing, head tilts, and small scene props (steam, rain, a ticking clock, a buzzing phone). Calm, believable motion that never teleports and never bounces.+A Claude Code skill for bringing anything drawn to life: characters and creatures, plants, cloth, fire, smoke, water, weather, lights, machines, vehicles, icons, logos, charts and whole scenes. The motion is calm and believable; it never teleports and never bounces.-It comes with ready-made templates for React Native (`react-native-svg` + `react-native-reanimated`) and SwiftUI (`TimelineView` + `Canvas`, iOS 17+ / macOS 14+), and the method works the same on the web.+It comes with a small motion engine and templates for React Native (`react-native-svg` + `react-native-reanimated`) and SwiftUI (`TimelineView` + `Canvas`, iOS 17+ / macOS 14+), and the method works the same on the web.## What's inside| File | What it is ||---|---|-| `SKILL.md` | The skill: rules, curves, the live face, choreography recipes, body/head/scene motion, performance pitfalls and a workflow. |+| `SKILL.md` | The skill: principles, the engine, recipes for every kind of subject, characters in depth, scenes that tell an action, performance pitfalls, platforms and a workflow. || `MOTION.md` | A notes file to copy into your project. Part 1 is the method in short form; Part 2 is where your project's specifics go (where the code is, the owner's rules, rig limits, how changes are checked). The skill reads it first. |-| `templates/liveFace.tsx` | React Native: a ready-to-copy live face (`LiveEye`, `LiveMouth`, keyframe `track`, `Choreo`, `useChoreoClock`). You give it the eye geometry and colours; nothing else is assumed. |-| `templates/LiveFace.swift` | SwiftUI: the same live face (`drawLiveEye`, `drawLiveMouth`, `track`, `Choreo`, `ChoreoClock`), drawn into a `Canvas` and driven by a `TimelineView`. |+| `templates/react-native/motion.ts` | The engine: loop and one-shot clocks, keyframe `track`, `seg`, `wave`, `loop`, `bell`, `seeded` and the curves. |+| `templates/react-native/liveFace.tsx` | A live face on top of the engine: `LiveEye`, `LiveMouth`, `Choreo`. You give it the eye geometry and colours. |+| `templates/swiftui/Motion.swift` | The same engine in SwiftUI: `LoopClock`, `OneShotClock`, `track`, `seg`, `wave`, `loop`, `bell`, `seeded`, and the `travel` and `open` animations. |+| `templates/swiftui/LiveFace.swift` | The same live face, drawn into a `Canvas`: `drawLiveEye`, `drawLiveMouth`, `Choreo`. |## Install@@ -23,17 +25,17 @@ git clone https://github.com/rossark0/rossark-motion-skill ~/.claude/skills/rossFor one project only, clone it into that project's `.claude/skills/rossark-motion-skill` instead.-Then, in Claude Code, ask to animate an illustration, or type `/rossark-motion-skill`.+Then, in Claude Code, ask it to animate something ("make this plant sway", "bring the mascot to life", "animate the onboarding illustrations"), or type `/rossark-motion-skill`.## First time in a project-1. Copy `MOTION.md` next to your illustrations (for example `src/art/MOTION.md`).-2. Fill in Part 2 as you go: the files, your rules (in your own words), what your rig can't do, and how you test.-3. If you don't have a live-face module yet, copy `templates/liveFace.tsx` (React Native) or `templates/LiveFace.swift` (SwiftUI) into the project, and set the eye geometry to match your character.+1. Copy `MOTION.md` next to your art (for example `src/art/MOTION.md`).+2. Fill in Part 2 as you go: the files, your rules (in your own words), what your art can't do, and how you test.+3. Copy the engine for your platform (`templates/react-native/` or `templates/swiftui/`) if the project doesn't have one yet.## The idea in one paragraph-Draw the character once, with plain eye whites. On top, in the head's coordinates, live eyes slide their pupils and lower their lids, and the cheeks push up for a happy squint. One looping clock per character feeds keyframe tracks (gaze, lid, cheek, mouth, tilt), eased with strong curves. The body breathes a unit or two, the head tilts a few degrees around the neck, and props loop quietly. Everything stops on a good-looking frame 0 when the user asks for reduced motion, and nothing runs off screen.+Every moving thing reads a clock. A loop clock gives idle life; a one-shot clock tells a small story when a scene appears. Parts are layers that rotate around their real pivots, trailing parts lag behind, and repeated things never move in sync. Amplitudes stay small, the curves are strong and nothing bounces. Characters get live eyes: pupils glide and lids blink over plain eye whites. Everything stops on a good frame when the user asks for reduced motion, and nothing runs off screen.## Licensediff --git a/SKILL.md b/SKILL.mdindex 1f576b8..52349a6 100644--- a/SKILL.md+++ b/SKILL.md@@ -1,68 +1,103 @@---name: rossark-motion-skill-description: Bring character illustrations to life (mascots, people, scenes drawn in SVG) with calm, believable idle motion. Eyes whose pupils glide and lids blink, breathing, head tilts, and small scene props like steam, rain, a ticking clock or a buzzing phone. Use it whenever someone asks to animate an illustration, make a character "feel alive", add blinking or breathing, or build a scene's motion. Ready-made templates for React Native (react-native-svg + Reanimated) and SwiftUI (TimelineView + Canvas); the method also works on the web.+description: Bring anything drawn to life with calm, believable motion. It covers characters and creatures (gliding pupils, blinks, breathing, head tilts), plants, fabric, fire, smoke, water, weather, lights, machines, vehicles, icons, logos, charts and whole scenes. Use it whenever someone asks to animate an illustration, an icon, a mascot or a scene, to make something "feel alive", to add idle motion, or to turn a static drawing into a living one. Comes with a small motion engine and templates for React Native (react-native-svg + Reanimated) and SwiftUI (TimelineView + Canvas); the method also works on the web.----# rossark-motion-skill: living illustrations+# rossark-motion-skill: bring anything to life-A method for making drawn characters feel alive without making them busy. It came from a production app's onboarding and paywall art, where the brief was "the character has to feel ALIVE" and "NO TELEPORTING in the animation".+A method for making drawn things feel alive without making them busy. It came from a production app's onboarding and paywall art, where the brief was "it has to feel ALIVE" and "NO TELEPORTING in the animation". It works the same for a character, a houseplant, a candle, a rainy street, a logo or a chart.## 0. Read the project's notes first-Before touching anything, look for the project's own motion notes: a `MOTION.md` next to the illustrations (search the repo for `MOTION.md`), the project's `CLAUDE.md`, and any saved memory about animation. **Project rules override the defaults below.** They usually name the existing live-face module, the character kit, poses that can't be animated a certain way, and things the owner has banned.--If the project has none, copy `MOTION.md` from this skill's folder next to the illustrations. Its Part 1 is this method in short form; fill in Part 2 (where the code is, the owner's rules, rig limits, how changes are checked) as you learn the project, and keep it up to date after each round.--## 1. Rules--- **Never swap drawings mid-motion.** Pupils slide, lids lower and rise, mouths open and close, heads rotate. Snapping from one expression to another is "teleporting", and it is what makes animation look cheap.-- **No bounce.** Use timed motion with strong curves (below), not springy overshoot. Characters breathe; they don't wobble.-- **Small amplitudes.**- - breathing: 1 to 2 drawing units;- - head tilt: 3 to 6 degrees;- - gaze: a few units inside the eye.- This is life, not a dance.-- **Opacity only for appearing and disappearing** (steam, raindrops, a notification). Never use it to dim a part halfway.-- **Never animate the view's size or position on the page.** The art keeps its layout; motion happens inside the drawing (translate and rotate on groups). The size goes in as a transform matrix, not as a view scale.-- **Reduced motion means still.** Every clock frozen at 0, and frame 0 must be a good-looking drawing on its own.-- **One main action per scene, plus two or three idle loops.** Mascots and side characters stay quiet unless the scene is about them.-- **Unique ids.** SVG `clipPath` ids are global to the screen.--## 2. Curves--```ts-// At the TOP of the module: a worklet captures what it references when it's created,-// and easings declared further down are undefined inside it.-const EASE_IN_OUT = Easing.bezierFn(0.77, 0, 0.175, 1); // things that travel: gaze, head, lid closing-const EASE_OUT = Easing.bezierFn(0.23, 1, 0.32, 1); // things that open: mouth, lid reopening, a prop appearing-```--Continuous loops (rain, conveyor, rotating sun) are linear.--## 3. The live face--Ready-made modules live in this skill's `templates/` folder. Copy the one for your platform into the project, or use the project's own version if the notes name one:-- **React Native:** `templates/liveFace.tsx` exports `LiveEye`, `LiveMouth`, `track`, `Choreo`, `Keys` and `useChoreoClock`.-- **SwiftUI:** `templates/LiveFace.swift` exports `drawLiveEye`, `drawLiveMouth`, `track`, `Choreo`, `Key` and `ChoreoClock`. See the SwiftUI section below.--The steps, and the React Native example:--1. **The static eyes.** Draw the character with plain eye whites and no pupils (if the character comes from a kit, use its "no pupils" option).-2. **The live layer.** Inside the same transform as the head, draw two `LiveEye` on top, then anything that must cover the lids (nose, hair, glasses), then `LiveMouth` if the mouth talks or laughs.-3. **The clock.** Run one clock per character, and derive every channel from it:--```tsx-const clock = useChoreoClock(CHOREO.period, live); // live = on screen && !reducedMotion-<G transform={`translate(${headX} ${headY}) scale(${s})`}>- <LiveEye side={-1} eye={EYE_L} ink={INK} choreo={CHOREO} clock={clock} id="introEyeL" />- <LiveEye side={1} eye={EYE_R} ink={INK} choreo={CHOREO} clock={clock} id="introEyeR" />- {/* nose / hair fringe here, above the lids */}-</G>-```--### The choreography--A `Choreo` holds keyframe tracks `[ms, value, 'out'?]`. Each segment eases in and out, or eases out when marked `'out'`.+Before touching anything, look for the project's motion notes:+- a `MOTION.md` next to the art (search the repo for it);+- the project's `CLAUDE.md`;+- any saved memory about animation.++**Project rules override everything below.** They usually name the existing motion code, the art kit, what the rig can't do, and what the owner has banned.++If the project has no notes:+1. Copy `MOTION.md` from this skill's folder next to the art. Its Part 1 is this method in short form.+2. Fill in Part 2 as you learn the project.+3. Keep it up to date after each round.++## 1. Principles++These hold for anything you animate.++1. **Never teleport.** Interpolate everything. A pupil slides, a door swings, a flame leans; nothing snaps from one drawing to another.+2. **Calm by default.** Use timed motion with strong curves. No bouncy overshoot unless the project explicitly wants a bouncy brand.+3. **Small amplitudes.** Life is subtle. See the table in section 3; when unsure, halve it.+4. **Arcs and pivots.** Real things rotate around a joint. Draw every moving part as its own layer and rotate it around its pivot: a stem's base, a door's hinge, a head's neck, a lamp's hook. Sliding in a straight line looks mechanical.+5. **Overlap and follow-through.** Parts don't move together. The tip of a branch moves later and further than its base; hair and tails lag behind the head; a hanging sign keeps swinging after the wind stops. In practice, give each part the same wave with a phase delay that grows along the chain.+6. **Variety without chaos.**+ - Repeated items (raindrops, leaves, stars, bubbles) each get their own phase and a slightly different speed and size, from `seeded(i)`.+ - Never `Math.random()` per frame, and never everything in sync.+ - Things on the same screen breathe out of phase.+7. **One main action per scene, plus two or three idle loops.** The main action tells the story: the alarm rings, the plant gets watered, the chart draws on. The loops only say "this place is alive". Side characters, mascots and backgrounds stay quiet.+8. **Opacity only to appear or disappear** (steam, a drop, a sparkle, a notification). Never use it to dim something halfway.+9. **The layout never moves.** Motion happens inside the drawing (transforms on groups), never by resizing or moving the view on the page.+10. **Reduced motion means still.**+ - Loops freeze at frame 0, which must be a good drawing.+ - One-shot scenes show their final frame, which must read on its own.+11. **Nothing runs unseen.** Off screen, hidden or in the background, every clock is paused.++## 2. The engine++The templates have one small engine per platform:+- **React Native:** `templates/react-native/motion.ts`;+- **SwiftUI:** `templates/swiftui/Motion.swift`.++Copy it into the project, unless the project's notes name its own.++- **Clocks.** Everything that moves reads a clock.+ - `useLoopClock(period, live)` / `LoopClock` loops forever, for idle life.+ - `useOneShotClock(duration, play, reduced)` / `OneShotClock` plays once and holds, for a scene that tells an action.+ - Use one clock per character, object group or scene, never one per tiny part.+- **Tracks.** Keyframes `[ms, value, 'out'?]` read with `track(t, keys)`. Each segment eases in and out, or eases out when marked `'out'`. The last key equals the first, so a loop never jumps.+- **Shaping helpers:**+ - `wave(t, period, phase)` gives a smooth -1 to 1, for sway, bob and breathing;+ - `loop(t, period, phase)` gives 0 to 1 progress, for drift and falling;+ - `bell(p)` fades in and out over a loop;+ - `seg(t, a, b)` turns a window of a one-shot clock into 0 to 1, for one beat of a scene;+ - `seeded(i)` gives stable per-item variety.+- **Curves.**+ - Things that travel (gaze, sway, a door, a lid closing) use ease-in-out `bezier(0.77, 0, 0.175, 1)`.+ - Things that open or arrive (a mouth, a lid reopening, a prop appearing, a bar growing) use ease-out `bezier(0.23, 1, 0.32, 1)`.+ - Only things leaving or falling away use ease-in.+ - Endless loops (rain, conveyor, gears, rotation) are linear.++## 3. Recipes by subject++Numbers are in drawing units (the artwork's own coordinate system) and milliseconds. They are starting points, not laws.++| Subject | What lives | Recipe |+|---|---|---|+| **Character, creature** | eyes, breath, head | See section 4. Breathing 1–2 units over 3–5 s; head tilt 3–6°; a blink every 3–4 s |+| **Tail, ears, hair, antenna** | follow-through | Rotation around the root, `wave` with the phase delayed 0.1–0.2 per segment; 4–10° |+| **Plant, tree, grass** | sway | Rotation around the base, 1.5–4°, 3–6 s per cycle. Leaves add their own small sway with a phase from `seeded(i)`; tips move more than the base |+| **Flag, curtain, cloth, scarf** | wave | Split into strips or points; each one offsets by `wave(t, period, phase = k·i)`, so the wave travels along the length. Amplitude grows away from the fixed edge |+| **Fire, candle** | flicker | Lean the flame 2–4° and stretch it 3–6% in the drawing on two waves of different periods (for example 700 and 1100 ms); the inner flame moves on a third. No random jitter |+| **Smoke, steam** | rise | Wisps rise 8–14 units while `bell(p)` fades them in and out; 2–3 wisps out of phase |+| **Water** | ripples, waves | Ripples are rings that grow 0 → 1 and fade with `bell`. Surface waves are a path whose points follow `wave` with a travelling phase. Floating things bob 1–2 units and rock 2° |+| **Rain, snow, leaves falling** | fall | `loop` per item with a seeded phase, speed (±20%) and x drift. Snow sways sideways with a slow `wave`. Linear |+| **Clouds, sky** | drift | Horizontal `loop` over 20–60 s; layers further back move slower (parallax). Sun rays rotate one turn in 30–60 s |+| **Lights, lamps, stars, screens** | glow, twinkle | A glow grows 2–5% in the drawing over 2–4 s. Stars twinkle with a small scale and an opacity dip at seeded times. An LED blinks on and off. A screen flickers rarely, never constantly |+| **Machines, gears, fans, clocks** | mechanism | Gears rotate linearly at speeds set by their tooth ratio. A clock hand steps once a second with ease-out; the colon blinks every 0.5 s. A fan spins steadily |+| **Phone, alarm, notification** | buzz | Bursts of ±3° (4 cycles in about 0.45 s), then a pause; vibration ticks show only during the burst. A notification slides in with ease-out and stays |+| **Vehicles** | ride | The body bobs 0.5–1 unit; wheels rotate linearly; scenery passes in parallax `loop`s. Never shake the whole frame |+| **Icon, logo** | a moment | Play once on appear (a draw-on, a small turn, a blink), then rest. No endless loops on UI chrome. A press is a 0.97 scale on the button, not inside the drawing |+| **Chart, diagram** | draw-on | One-shot: lines draw with a stroke-dash offset, bars grow from their base with ease-out and a small stagger (40–80 ms), and numbers count up with ease-out. Final frame = the data |+| **Scene** | a story | One one-shot action when the scene appears (section 5), then the idle loops of whatever is in it |++## 4. Characters in depth++**The live face.** The templates (`templates/react-native/liveFace.tsx` and `templates/swiftui/LiveFace.swift`) use the engine:+1. Draw the eyes as plain whites, with no pupils (if the art comes from a kit, use its "no pupils" option).+2. On top, in the head's coordinates, draw the two live eyes. The pupil slides, clipped to the white; the lid and cheek are skin clipped to a shape 2 units LARGER than the white. With the exact white, the anti-aliased edge leaks around a closed eye and looks like glasses.+3. Then draw whatever covers the lids (nose, fringe, glasses), then the live mouth.++A `Choreo` holds the tracks:| Track | What it moves ||---|---|@@ -72,10 +107,10 @@ A `Choreo` holds keyframe tracks `[ms, value, 'out'?]`. Each segment eases in an| `mouth` | depth of the open mouth || `tilt` | head rotation, in degrees, which you apply to the head layer |-The recipe for one loop of 6 to 9 seconds:+The recipe for one loop of 6 to 9 s:- **Gaze:** a resting gaze, plus one or two glances at something in the scene. Glide there in about 500 ms and hold for at least 1 s.-- **Blinks:** one every 3 to 4 s. Close in about 90 ms with ease-in-out, hold 0 to 60 ms, and reopen in about 150 ms with `'out'`. Now and then, a double blink.-- **The loop closes:** the last key equals the first, so the loop never jumps.+- **Blinks:** one every 3 to 4 s. Close in about 90 ms, hold up to 60 ms, reopen in about 150 ms with `'out'`. Now and then, a double blink.+- **The loop closes:** the last key equals the first.| Feeling | Gaze | Lid | Extra ||---|---|---|---|@@ -86,73 +121,87 @@ The recipe for one loop of 6 to 9 seconds:| focused | fixed on the task | 0.1 | rare blinks, small saccades || sleepless | wide, at the ceiling, then the clock | 0 | a slow, tired close near the end |-## 4. Body, head and scene+**Body and head.**+- **Layers:** split the character into back hair, body, head (with the live face) and front (hands, held props).+- **Breathing:** the character's layer rises 1 to 2 units, with ease-in-out.+- **Head tilt:** the head and back hair rotate around the neck pivot. Don't tilt if a hand touches the face; it would come apart.+- **Cropped by an edge:** draw a few units below the crop, so the cut never shows when the character rises.+- **Creatures without a face rig:** breathing, ear and tail follow-through, and an occasional whole-head turn still make them feel alive.-- **Breathing:** the whole body rises 1 to 2 units and comes back over 3 to 5 s, with ease-in-out, on a loop (`translateY` on the character's layer). Characters on the same screen should be out of phase.-- **Head tilt:** split the character into layers: back hair, body, head (with the live face) and front (hands, held props). Rotate the head and back-hair layers around the neck pivot with the `tilt` track. If a hand touches the face, don't tilt; it would come apart.-- **Cropped characters** (cut by a card edge): when they bob, draw a few units below the crop line, or the cut edge shows at the top of the motion. Things in front (a desk, a table) go on a layer above.-- **Scene props:**- - **steam:** a wisp rises about 10 units while its opacity follows `sin(π·p)`, so it fades in and out;- - **rain and drift:** linear loops, each item with its own phase;- - **ticking clock:** the colon blinks every 0.5 s and a hand steps once a second, with ease-out;- - **buzzing phone:** short bursts of ±3 degrees (4 cycles in about 0.45 s), then a pause, with vibration ticks that show only during the burst.-- **A scene that tells an action** (press, buzz, a message arrives): run a one-shot clock that plays once when the scene appears, with windows `seg(t, a, b)` for each beat. After that, only the idle loops run.+## 5. Scenes that tell an action-## 5. Performance and pitfalls+Some scenes tell a small story: the phone buzzes, she picks it up, the alarm stops. Here's how to build one.-- One clock per character or scene; everything else is a worklet reading it.-- Put `live` in the dependencies of every `useAnimatedProps`, and freeze clocks for anything off screen or hidden. A layer at opacity 0 with a running loop still costs.-- `withRepeat` restarts from the current value: set it to 0 before starting again, and cancel in the effect cleanup.-- Clip the skin (lid, cheek) to a shape 2 units larger than the eye white. Clipped to the exact white, the anti-aliased edge leaks around a closed eye and looks like glasses.-- Prefer one SVG per layer over many animated views. Canvas engines (Skia) are heavier: don't multiply them.+1. **The clock:** a one-shot clock of a few seconds that starts when the scene appears.+2. **The beats:** each beat is a window, with `seg(t, a, b)` turning it into 0 to 1. Write them as data, for example `{ ring: [0, 900], reach: [900, 1500], stop: [1500, 1700] }`.+3. **Overlap:** the next beat starts a little before the last one ends.+4. **The end:** the scene holds on its final frame and only the idle loops keep running.+5. **A carousel of scenes:** the one leaving finishes its exit before the next one starts (or crossfades over it, never through an empty or dark frame). Only the scene on screen runs.-## 6. Workflow+## 6. Performance and pitfalls-1. Read the project notes (section 0) and the header comments of the illustration file; decisions recorded there are law.-2. List what could live: the face, the body, the head, the props and the mascot.-3. Pick ONE main action and two or three idle loops. Less is more.-4. Put every number in a token object at the top of the file, so "slower" or "smaller" is a one-line change.-5. Check frame 0 (reduced motion) and that every loop closes without a jump.-6. Run the project's type check, lint and tests.-7. Hand off in plain words: what moves on each screen, and what has not been seen on a real device yet.+- **Clocks:** one clock per character, group or scene; everything else is a function of its time.+- **Pausing:** pause clocks off screen, when hidden, in the background and with reduced motion. A loop running behind opacity 0 still costs.+- **React Native:**+ - put `live` in the dependencies of every `useAnimatedProps`;+ - `withRepeat` restarts from the current value, so reset it to 0 before starting and cancel it in the cleanup;+ - declare easings at the top of the module, because worklets capture them when they're created.+- **SwiftUI:** a `TimelineView(.animation)` redraws every frame while it runs. Pause it, and keep one per scene rather than one per part.+- **Many items** (particles, leaves, stars): draw them in one SVG or one `Canvas`, computing each from the same clock, never one animated view each.+- **Unique SVG ids:** clip paths are global to the screen.+- **Canvas engines** (Skia, a big `Canvas`): they're heavier. Don't multiply them, and don't keep one running behind another.-## SwiftUI+## 7. Platforms-The same method, with SwiftUI's tools (iOS 17+, macOS 14+; template in `templates/LiveFace.swift`).+| Piece | React Native | SwiftUI | Web |+|---|---|---|---|+| Engine | `templates/react-native/motion.ts` | `templates/swiftui/Motion.swift` | the same math on `requestAnimationFrame` or a Motion value |+| Loop clock | `useLoopClock` (Reanimated `withRepeat`) | `LoopClock { t in ... }` (`TimelineView(.animation)`) | a time value modulo the period |+| Drawing | `react-native-svg` groups, `useAnimatedProps` | `Canvas` with `GraphicsContext`, or views with `.offset` and `.rotationEffect` | SVG attributes, or CSS `transform` on groups |+| Reduced motion | `useReducedMotion()` | `@Environment(\.accessibilityReduceMotion)` (built into the clocks) | `prefers-reduced-motion` |+| Curves | `Easing.bezierFn` | `UnitCurve.bezier`; `Animation.travel(_:)` and `.open(_:)` | `cubic-bezier(...)` |-| Piece | React Native | SwiftUI |-|---|---|---|-| The clock | `useChoreoClock` (Reanimated `withRepeat`) | `ChoreoClock { t in ... }` (`TimelineView(.animation)`) |-| Drawing | `react-native-svg` groups | `Canvas`: `drawLiveEye` and `drawLiveMouth` into a `GraphicsContext` already in the head's coordinates |-| Curves | `Easing.bezierFn` | `UnitCurve.bezier` inside `track`; `Animation.travel(_:)` and `.open(_:)` for one-off animations |-| Reduced motion | `useReducedMotion()` | `@Environment(\.accessibilityReduceMotion)` (built into `ChoreoClock`) |-| Off screen | `live = false` | `ChoreoClock(period:, paused:)`, driven by `onAppear`/`onDisappear` and `scenePhase` |+SwiftUI example: a plant that sways and a character with live eyes, on one clock.```swift-ChoreoClock(period: choreo.period, paused: !visible) { t in+LoopClock(period: 6000, paused: !visible) { t inZStack {- CharacterArt() // eyes drawn as plain whites, no pupils+ Plant()+ .rotationEffect(.degrees(2.5 * wave(t, period: 4200)), anchor: .bottom)+ CharacterArt() // eyes drawn as plain whites+ .offset(y: -1.5 * (wave(t, period: 3600) + 1) / 2)Canvas { ctx, _ in- var head = ctx // the head's own coordinates+ var head = ctxhead.translateBy(x: headX, y: headY)- head.scaleBy(x: s, y: s)drawLiveEye(head, side: -1, eye: eyeL, ink: ink, choreo: choreo, t: t)drawLiveEye(head, side: 1, eye: eyeR, ink: ink, choreo: choreo, t: t)- // then whatever covers the lids (nose, fringe)}.allowsHitTesting(false)}}```-- **Breathing and head tilt:** compute them from the same `t` and apply them as render-only modifiers, which never change layout:- - breathing: `.offset(y: -track(t, breath))`;- - head tilt: `.rotationEffect(.degrees(track(t, tilt)), anchor: neckAnchor)`, on the head layer.-- **Layers:** split the character into back-hair, body, head and front views (or images) in a `ZStack`. Tilt only the head and back hair.-- **No springs with bounce.** Avoid `.bouncy` and `.spring` with bounce. Use `.timingCurve(...)` (the `travel` and `open` helpers), or drive everything from the clock.-- **Cost:** a `TimelineView(.animation)` redraws every frame while it runs. Pause it off screen and in the background, and keep one per character or scene, not one per eye.-- **Images instead of vector art:** live eyes still work. Draw the eyes as plain whites in the artwork and lay the `Canvas` over the image, with the head's transform matching the image's coordinates.+React Native example: falling snow, with one clock and one SVG.++```tsx+const t = useLoopClock(8000, live);+function Flake({ i }: { i: number }) {+ const speed = 0.8 + seeded(i) * 0.4;+ const props = useAnimatedProps(() => {+ const p = loop(t.value * speed, 8000, seeded(i, 1));+ return { cx: 20 + seeded(i, 2) * 360 + 6 * wave(t.value, 3000, seeded(i, 3)), cy: -10 + p * 420 };+ }, [live]);+ return <ACircle animatedProps={props} r={2 + seeded(i, 4) * 2} fill="#fff" />;+}+```-## On the web+## 8. Workflow-The same model works: one clock (`requestAnimationFrame`, or a Motion value) feeding keyframe tracks into SVG attributes. Animate only `transform` and `opacity`, and respect `prefers-reduced-motion`.+1. **Read** the project notes (section 0) and the header comments of the art file; decisions recorded there are law.+2. **List** what could live in the drawing: the main subject, its parts and pivots, repeated items, light, the background.+3. **Pick** ONE main action and two or three idle loops. Cut the rest.+4. **Split** the art into layers at their pivots, without changing how it looks at frame 0.+5. **Tune** by putting every number in a token object at the top of the file, so "slower", "smaller" or "less" is a one-line change.+6. **Check** frame 0 (reduced motion), the final frame of one-shots, and that every loop closes without a jump.+7. **Run** the project's type check, lint and tests.+8. **Hand off** in plain words: what moves, what was left still on purpose, and what hasn't been seen on a real device yet.diff --git a/templates/liveFace.tsx b/templates/react-native/liveFace.tsxsimilarity index 80%rename from templates/liveFace.tsxrename to templates/react-native/liveFace.tsxindex 91cc5c3..19e8820 100644--- a/templates/liveFace.tsx+++ b/templates/react-native/liveFace.tsx@@ -4,54 +4,25 @@// cheek pushes up for a happy squint, the mouth OPENS and CLOSES. One clock per// character drives every channel through keyframe tracks.//-// Usage (see SKILL.md, "The live face"):+// Needs `motion.ts` (the engine) next to it.+//+// Usage (see SKILL.md, "Characters"):// 1. Draw your character's eyes as plain whites, with no pupils.// 2. Inside the same <G> transform as the head, draw two <LiveEye> on top,// then anything that must cover the eyelids (nose, hair, glasses).// 3. One `useChoreoClock(choreo.period, live)` per character.-import React, { useEffect } from 'react';-import Animated, {- Easing,- cancelAnimation,- useAnimatedProps,- useSharedValue,- withRepeat,- withTiming,- type SharedValue,-} from 'react-native-reanimated';+import React from 'react';+import Animated, { useAnimatedProps, type SharedValue } from 'react-native-reanimated';import { Circle, ClipPath, Defs, G, Line, Path, Rect } from 'react-native-svg';+import { track, useLoopClock, type Keys } from './motion';-// ⚠️ Keep these at the TOP of the module. A worklet captures what it uses when-// it is created; easings declared further down are undefined inside it.-const EASE_IN_OUT = Easing.bezierFn(0.77, 0, 0.175, 1); // things that travel: gaze, head, lid closing-const EASE_OUT = Easing.bezierFn(0.23, 1, 0.32, 1); // things that open: mouth, lid reopening+export { track, type Key, type Keys } from './motion';const ARect = Animated.createAnimatedComponent(Rect);const APath = Animated.createAnimatedComponent(Path);const ACircle = Animated.createAnimatedComponent(Circle);const ALine = Animated.createAnimatedComponent(Line);-/** A keyframe: time (ms), value, and the curve of the segment ARRIVING here ('out', or ease-in-out by default). */-export type Key = readonly [number, number, 'out'?];-export type Keys = readonly Key[];--/** The value of a track at time `t`. */-export function track(t: number, keys: Keys): number {- 'worklet';- if (t <= keys[0][0]) return keys[0][1];- for (let i = 1; i < keys.length; i++) {- const k1 = keys[i];- if (t <= k1[0]) {- const k0 = keys[i - 1];- const span = k1[0] - k0[0];- const p = span > 0 ? (t - k0[0]) / span : 1;- const e = k1[2] === 'out' ? EASE_OUT(p) : EASE_IN_OUT(p);- return k0[1] + (k1[1] - k0[1]) * e;- }- }- return keys[keys.length - 1][1];-}-/*** One character's choreography. `lookX`/`lookY`: pupil offset in eye units.* `lid`: upper eyelid, 0 open to 1 closed (`lidRight` for a one-eyed blink or wink).@@ -69,19 +40,8 @@ export type Choreo = {tilt?: Keys;};-/** A looping clock from 0 to `period` ms. Frozen at 0 when `live` is false (reduced motion, off screen). */-export function useChoreoClock(period: number, live: boolean): SharedValue<number> {- const clock = useSharedValue(0);- useEffect(() => {- cancelAnimation(clock);- // withRepeat restarts from the CURRENT value: always reset first.- clock.value = 0;- if (!live) return;- clock.value = withRepeat(withTiming(period, { duration: period, easing: Easing.linear }), -1);- return () => cancelAnimation(clock);- }, [live, period, clock]);- return clock;-}+/** The character's clock: a loop of `period` ms, frozen at 0 when `live` is false. */+export const useChoreoClock = useLoopClock;/** A rounded pill (stadium) path centred on (cx, cy). */export function pill(cx: number, cy: number, w: number, h: number): string {diff --git a/templates/react-native/motion.ts b/templates/react-native/motion.tsnew file mode 100644index 0000000..bc20965--- /dev/null+++ b/templates/react-native/motion.ts@@ -0,0 +1,114 @@+// motion.ts: the motion engine for living illustrations (react-native-reanimated 3/4).+//+// Everything that moves reads a clock: a looping clock for idle life, a one-shot+// clock for a scene that tells an action. Values come from keyframe tracks and a+// few shaping helpers, all worklets, so they run on the UI thread.+import { useEffect } from 'react';+import { Easing, cancelAnimation, useSharedValue, withRepeat, withTiming, type SharedValue } from 'react-native-reanimated';++// ⚠️ Keep curves at the TOP of the module. A worklet captures what it references+// when it is created; constants declared further down are undefined inside it.+/** Things that travel (gaze, sway, a head turning, a lid closing). */+export const EASE_IN_OUT = Easing.bezierFn(0.77, 0, 0.175, 1);+/** Things that open or arrive (a mouth, a lid reopening, a prop appearing). */+export const EASE_OUT = Easing.bezierFn(0.23, 1, 0.32, 1);+/** Only for things leaving or falling away. Never for something the eye is waiting on. */+export const EASE_IN = Easing.bezierFn(0.55, 0, 1, 0.45);++/** A keyframe: time (ms), value, and the curve of the segment ARRIVING here ('out', or ease-in-out by default). */+export type Key = readonly [number, number, 'out'?];+export type Keys = readonly Key[];++/** The value of a track at time `t`. The last key should equal the first, so loops never jump. */+export function track(t: number, keys: Keys): number {+ 'worklet';+ if (t <= keys[0][0]) return keys[0][1];+ for (let i = 1; i < keys.length; i++) {+ const k1 = keys[i];+ if (t <= k1[0]) {+ const k0 = keys[i - 1];+ const span = k1[0] - k0[0];+ const p = span > 0 ? (t - k0[0]) / span : 1;+ const e = k1[2] === 'out' ? EASE_OUT(p) : EASE_IN_OUT(p);+ return k0[1] + (k1[1] - k0[1]) * e;+ }+ }+ return keys[keys.length - 1][1];+}++/** 0 → 1 inside the window [a, b] of a clock (eased), 0 before it, 1 after. One beat of a scene. */+export function seg(t: number, a: number, b: number, curve: 'out' | 'inOut' = 'out'): number {+ 'worklet';+ if (t <= a) return 0;+ if (t >= b) return 1;+ const p = (t - a) / (b - a);+ return curve === 'out' ? EASE_OUT(p) : EASE_IN_OUT(p);+}++/** A smooth back-and-forth from -1 to 1. `phase` (0 to 1) offsets one item from the next. */+export function wave(t: number, period: number, phase = 0): number {+ 'worklet';+ return Math.sin((t / period + phase) * Math.PI * 2);+}++/** Progress through a loop, 0 to 1, with a phase (for drifting or falling items). */+export function loop(t: number, period: number, phase = 0): number {+ 'worklet';+ const p = (t / period + phase) % 1;+ return p < 0 ? p + 1 : p;+}++/** 0 at both ends of a loop and 1 in the middle: fade in and out (steam, sparkles, ripples). */+export function bell(p: number): number {+ 'worklet';+ return Math.sin(Math.PI * Math.min(1, Math.max(0, p)));+}++/** A stable pseudo-random number in [0, 1) for item `i`: variety that is the same every render. */+export function seeded(i: number, salt = 0): number {+ 'worklet';+ const x = Math.sin(i * 12.9898 + salt * 78.233) * 43758.5453;+ return x - Math.floor(x);+}++/**+ * A looping clock from 0 to `period` ms. Frozen at 0 when `live` is false+ * (reduced motion, off screen, hidden): frame 0 must be a good drawing.+ */+export function useLoopClock(period: number, live: boolean): SharedValue<number> {+ const clock = useSharedValue(0);+ useEffect(() => {+ cancelAnimation(clock);+ // withRepeat restarts from the CURRENT value: always reset first.+ clock.value = 0;+ if (!live) return;+ clock.value = withRepeat(withTiming(period, { duration: period, easing: Easing.linear }), -1);+ return () => cancelAnimation(clock);+ }, [live, period, clock]);+ return clock;+}++/**+ * A clock that plays ONCE from 0 to `duration` ms when `play` turns true, and+ * holds at the end (a scene that tells an action, a chart drawing itself on).+ * With reduced motion it jumps straight to the end: the final frame is the one+ * that carries meaning, so it must read on its own.+ */+export function useOneShotClock(duration: number, play: boolean, reduced: boolean): SharedValue<number> {+ const clock = useSharedValue(reduced ? duration : 0);+ useEffect(() => {+ cancelAnimation(clock);+ if (!play) {+ clock.value = 0;+ return;+ }+ if (reduced) {+ clock.value = duration;+ return;+ }+ clock.value = 0;+ clock.value = withTiming(duration, { duration, easing: Easing.linear });+ return () => cancelAnimation(clock);+ }, [play, reduced, duration, clock]);+ return clock;+}diff --git a/templates/LiveFace.swift b/templates/swiftui/LiveFace.swiftsimilarity index 76%rename from templates/LiveFace.swiftrename to templates/swiftui/LiveFace.swiftindex 1b18e85..c30fa5e 100644--- a/templates/LiveFace.swift+++ b/templates/swiftui/LiveFace.swift@@ -4,6 +4,8 @@// cheek pushes up for a happy squint, the mouth OPENS and CLOSES. One clock per// character (`ChoreoClock`) drives every channel through keyframe tracks.//+// Needs `Motion.swift` (the engine) in the same target.+//// Usage (see SKILL.md, "SwiftUI"):// ChoreoClock(period: blink.period) { t in// ZStack {@@ -20,58 +22,6 @@// }import SwiftUI-// MARK: - Curves--/// Things that travel (gaze, head, lid closing): a strong ease-in-out.-private let easeInOut = UnitCurve.bezier(- startControlPoint: UnitPoint(x: 0.77, y: 0),- endControlPoint: UnitPoint(x: 0.175, y: 1)-)-/// Things that open (mouth, lid reopening): a strong ease-out.-private let easeOut = UnitCurve.bezier(- startControlPoint: UnitPoint(x: 0.23, y: 1),- endControlPoint: UnitPoint(x: 0.32, y: 1)-)--/// The same curves for SwiftUI animations elsewhere in the scene (never a bouncy spring).-public extension Animation {- static func travel(_ duration: Double) -> Animation { .timingCurve(0.77, 0, 0.175, 1, duration: duration) }- static func open(_ duration: Double) -> Animation { .timingCurve(0.23, 1, 0.32, 1, duration: duration) }-}--// MARK: - Keyframe tracks--/// A keyframe: time (ms), value, and whether the segment ARRIVING here eases out (default: ease-in-out).-public struct Key: Sendable {- public let ms: Double- public let value: Double- public let easeOut: Bool- public init(_ ms: Double, _ value: Double, out easeOut: Bool = false) {- self.ms = ms- self.value = value- self.easeOut = easeOut- }-}--public typealias Keys = [Key]--/// The value of a track at time `t` (ms).-public func track(_ t: Double, _ keys: Keys) -> Double {- guard let first = keys.first else { return 0 }- if t <= first.ms { return first.value }- for i in 1..<keys.count {- let k1 = keys[i]- if t <= k1.ms {- let k0 = keys[i - 1]- let span = k1.ms - k0.ms- let p = span > 0 ? (t - k0.ms) / span : 1- let e = (k1.easeOut ? easeOut : easeInOut).value(at: p)- return k0.value + (k1.value - k0.value) * e- }- }- return keys[keys.count - 1].value-}-/// One character's choreography. `lookX`/`lookY`: pupil offset in eye units./// `lid`: upper eyelid, 0 open to 1 closed (`lidRight` for a one-eyed blink or wink)./// `cheek`: 0 to 1, a happy squint. `mouth`: open-mouth depth. `tilt`: head angle in degrees.@@ -101,29 +51,8 @@ public struct Choreo: Sendable {// MARK: - The clock-/// A looping clock from 0 to `period` ms. Frozen at 0 with Reduce Motion, or when `paused`-/// (off screen, app in the background). Frame 0 must be a good drawing on its own.-public struct ChoreoClock<Content: View>: View {- let period: Double- var paused: Bool- let content: (Double) -> Content- @Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var start = Date()-- public init(period: Double, paused: Bool = false, @ViewBuilder content: @escaping (Double) -> Content) {- self.period = period- self.paused = paused- self.content = content- }-- public var body: some View {- let still = paused || reduceMotion- TimelineView(.animation(minimumInterval: nil, paused: still)) { context in- let t = still ? 0 : (context.date.timeIntervalSince(start) * 1000).truncatingRemainder(dividingBy: period)- content(t)- }- }-}+/// The character's clock: a `LoopClock` (in Motion.swift) of `choreo.period` ms.+public typealias ChoreoClock<Content: View> = LoopClock<Content>// MARK: - Geometry and coloursdiff --git a/templates/swiftui/Motion.swift b/templates/swiftui/Motion.swiftnew file mode 100644index 0000000..5bf0dde--- /dev/null+++ b/templates/swiftui/Motion.swift@@ -0,0 +1,148 @@+// Motion.swift: the motion engine for living illustrations in SwiftUI (iOS 17+, macOS 14+).+//+// Everything that moves reads a clock: `LoopClock` for idle life, `OneShotClock`+// for a scene that tells an action. Values come from keyframe tracks and a few+// shaping helpers, computed from the clock's time `t` (ms) on every frame.+import SwiftUI++// MARK: - Curves++/// Things that travel (gaze, sway, a head turning, a lid closing): a strong ease-in-out.+let easeInOut = UnitCurve.bezier(startControlPoint: UnitPoint(x: 0.77, y: 0), endControlPoint: UnitPoint(x: 0.175, y: 1))+/// Things that open or arrive (a mouth, a lid reopening, a prop appearing): a strong ease-out.+let easeOut = UnitCurve.bezier(startControlPoint: UnitPoint(x: 0.23, y: 1), endControlPoint: UnitPoint(x: 0.32, y: 1))++/// The same curves for one-off SwiftUI animations (never a spring with bounce).+public extension Animation {+ static func travel(_ duration: Double) -> Animation { .timingCurve(0.77, 0, 0.175, 1, duration: duration) }+ static func open(_ duration: Double) -> Animation { .timingCurve(0.23, 1, 0.32, 1, duration: duration) }+}++// MARK: - Tracks and shaping++/// A keyframe: time (ms), value, and whether the segment ARRIVING here eases out (default: ease-in-out).+public struct Key: Sendable {+ public let ms: Double+ public let value: Double+ public let easeOut: Bool+ public init(_ ms: Double, _ value: Double, out easeOut: Bool = false) {+ self.ms = ms+ self.value = value+ self.easeOut = easeOut+ }+}++public typealias Keys = [Key]++/// The value of a track at time `t` (ms). The last key should equal the first, so loops never jump.+public func track(_ t: Double, _ keys: Keys) -> Double {+ guard let first = keys.first else { return 0 }+ if t <= first.ms { return first.value }+ for i in 1..<keys.count {+ let k1 = keys[i]+ if t <= k1.ms {+ let k0 = keys[i - 1]+ let span = k1.ms - k0.ms+ let p = span > 0 ? (t - k0.ms) / span : 1+ let e = (k1.easeOut ? easeOut : easeInOut).value(at: p)+ return k0.value + (k1.value - k0.value) * e+ }+ }+ return keys[keys.count - 1].value+}++/// 0 → 1 inside the window [a, b] of a clock (eased), 0 before it, 1 after. One beat of a scene.+public func seg(_ t: Double, _ a: Double, _ b: Double, easeOut useEaseOut: Bool = true) -> Double {+ if t <= a { return 0 }+ if t >= b { return 1 }+ let p = (t - a) / (b - a)+ return (useEaseOut ? easeOut : easeInOut).value(at: p)+}++/// A smooth back-and-forth from -1 to 1. `phase` (0 to 1) offsets one item from the next.+public func wave(_ t: Double, period: Double, phase: Double = 0) -> Double {+ sin((t / period + phase) * .pi * 2)+}++/// Progress through a loop, 0 to 1, with a phase (for drifting or falling items).+public func loop(_ t: Double, period: Double, phase: Double = 0) -> Double {+ let p = (t / period + phase).truncatingRemainder(dividingBy: 1)+ return p < 0 ? p + 1 : p+}++/// 0 at both ends of a loop and 1 in the middle: fade in and out (steam, sparkles, ripples).+public func bell(_ p: Double) -> Double {+ sin(.pi * min(1, max(0, p)))+}++/// A stable pseudo-random number in [0, 1) for item `i`: variety that is the same every frame.+public func seeded(_ i: Int, salt: Double = 0) -> Double {+ let x = sin(Double(i) * 12.9898 + salt * 78.233) * 43758.5453+ return x - floor(x)+}++// MARK: - Clocks++/// A looping clock from 0 to `period` ms. Frozen at 0 with Reduce Motion, or when `paused`+/// (off screen, app in the background). Frame 0 must be a good drawing on its own.+public struct LoopClock<Content: View>: View {+ let period: Double+ var paused: Bool+ let content: (Double) -> Content+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var start = Date()++ public init(period: Double, paused: Bool = false, @ViewBuilder content: @escaping (Double) -> Content) {+ self.period = period+ self.paused = paused+ self.content = content+ }++ public var body: some View {+ let still = paused || reduceMotion+ TimelineView(.animation(minimumInterval: nil, paused: still)) { context in+ let t = still ? 0 : (context.date.timeIntervalSince(start) * 1000).truncatingRemainder(dividingBy: period)+ content(t)+ }+ }+}++/// A clock that plays ONCE from 0 to `duration` ms when `play` turns true, then holds at the end+/// (a scene that tells an action, a chart drawing itself on). With Reduce Motion it shows the end+/// straight away: the final frame carries the meaning, so it must read on its own.+public struct OneShotClock<Content: View>: View {+ let duration: Double+ let play: Bool+ let content: (Double) -> Content+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var startedAt: Date?++ public init(duration: Double, play: Bool, @ViewBuilder content: @escaping (Double) -> Content) {+ self.duration = duration+ self.play = play+ self.content = content+ }++ public var body: some View {+ Group {+ if !play {+ content(0)+ } else if reduceMotion {+ content(duration)+ } else {+ TimelineView(.animation(minimumInterval: nil, paused: isDone)) { context in+ let elapsed = startedAt.map { context.date.timeIntervalSince($0) * 1000 } ?? 0+ content(min(duration, elapsed))+ }+ }+ }+ .onChange(of: play, initial: true) { _, now in+ startedAt = now ? Date() : nil+ }+ }++ private var isDone: Bool {+ guard let startedAt else { return false }+ return Date().timeIntervalSince(startedAt) * 1000 >= duration+ }+}