@mkbabb/keyframes.js 4.1.0 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +520 -65
- package/dist/{animate-12YQKwyY.js → animate-D5KoLKwi.js} +2 -2
- package/dist/{animations-CcAWdZlW.js → animations-DaMcGoCd.js} +2 -2
- package/dist/binarySearch-DOP8erk-.js +13 -0
- package/dist/compile-C0xOTIC4.js +249 -0
- package/dist/decay-BvNmFk51.js +25 -0
- package/dist/{draw-svg-DwAa5cbU.js → draw-svg-CF2cTJj-.js} +1 -1
- package/dist/{engine-Cj0T6OIH.js → engine-BKm1GcJT.js} +338 -361
- package/dist/ingest-BFBYGTH-.js +139 -0
- package/dist/keyframes.d.ts +1068 -29
- package/dist/keyframes.js +82 -236
- package/dist/{motion-path-683GcEZK.js → motion-path-CqmlG74k.js} +1 -1
- package/dist/scroll-scene-JpRpH1uU.js +197 -0
- package/dist/sequence-COn8zk5o.js +156 -0
- package/dist/springTimingFunction-CcJEvGwN.js +51 -0
- package/dist/{timeline-BHz0o8dZ.js → timeline-BjcmprQ6.js} +184 -49
- package/dist/waapi-Bd5QadtA.js +179 -0
- package/package.json +110 -11
- package/dist/springTimingFunction-cMJnhbug.js +0 -178
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ anim.play();
|
|
|
35
35
|
|
|
36
36
|
This animates the element's style properties as specified in the keyframes. The default behavior, but you can get far more inventive with it.
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
The [demo apps](demo/) exercise this pattern end-to-end — [try them live](https://keyframes.babb.dev/).
|
|
39
39
|
|
|
40
40
|
## Table of Contents
|
|
41
41
|
|
|
@@ -46,11 +46,19 @@ Plucked directly from the [`demo/simple`](demo/simple/App.vue) Vue file.
|
|
|
46
46
|
- [Transform Function](#the-transform-function)
|
|
47
47
|
- [Timing Function](#the-timing-function)
|
|
48
48
|
- [TemplateAnimationFrame](#templateanimationframe)
|
|
49
|
+
- [The dynamic engine — loadAnimationEngine()](#the-dynamic-engine--loadanimationengine)
|
|
50
|
+
- [animate](#animate)
|
|
51
|
+
- [MotionPath](#motionpath)
|
|
52
|
+
- [DrawSVG](#drawsvg)
|
|
49
53
|
- [CSSKeyframesAnimation](#csskeyframesanimation)
|
|
50
54
|
- [Parsing CSS Keyframes](#parsing-css-keyframes)
|
|
51
55
|
- [Units](#units)
|
|
52
56
|
- [AnimationGroup](#animationgroup)
|
|
53
57
|
- [Presets](#presets)
|
|
58
|
+
- [The round-trip — ingest, drive, compile](#the-round-trip--ingest-drive-compile)
|
|
59
|
+
- [Ingest — read the live web's CSS](#ingest--read-the-live-webs-css)
|
|
60
|
+
- [Scroll-as-CSS — the animation-timeline grammar](#scroll-as-css--the-animation-timeline-grammar)
|
|
61
|
+
- [Compile — the parser run backward](#compile--the-parser-run-backward)
|
|
54
62
|
- [Web Animations API](#web-animations-api)
|
|
55
63
|
- [Baseline, tree-shaking & reduced motion](#baseline-tree-shaking--reduced-motion)
|
|
56
64
|
- [Beyond CSS](#beyond-css)
|
|
@@ -58,6 +66,15 @@ Plucked directly from the [`demo/simple`](demo/simple/App.vue) Vue file.
|
|
|
58
66
|
- [SmoothProgress](#smoothprogress)
|
|
59
67
|
- [ElementMorph](#elementmorph)
|
|
60
68
|
- [Timeline](#timeline)
|
|
69
|
+
- [SpringProgress](#springprogress)
|
|
70
|
+
- [springLinearStops & springTimingFunction](#springlinearstops--springtimingfunction)
|
|
71
|
+
- [RAFPlayback](#rafplayback)
|
|
72
|
+
- [stagger](#stagger)
|
|
73
|
+
- [flip / flipShared](#flip--flipshared)
|
|
74
|
+
- [drag / Draggable](#drag--draggable)
|
|
75
|
+
- [decay / decayRest](#decay--decayrest)
|
|
76
|
+
- [Sequence](#sequence)
|
|
77
|
+
- [Ecosystem & agents](#ecosystem--agents)
|
|
61
78
|
- [Build & Development](#build--development)
|
|
62
79
|
|
|
63
80
|
## Installation
|
|
@@ -72,43 +89,46 @@ Works both in and out of the browser. Anything that touches the DOM (`getCompute
|
|
|
72
89
|
|
|
73
90
|
```
|
|
74
91
|
src/
|
|
75
|
-
├── animation/
|
|
76
|
-
│ ├── index.ts
|
|
77
|
-
│ ├──
|
|
78
|
-
│ ├──
|
|
79
|
-
│ ├──
|
|
80
|
-
│ ├──
|
|
81
|
-
│ ├──
|
|
82
|
-
│ ├──
|
|
83
|
-
│ ├──
|
|
84
|
-
│ ├──
|
|
85
|
-
│
|
|
86
|
-
├──
|
|
87
|
-
│ ├──
|
|
88
|
-
│ ├──
|
|
89
|
-
│ ├──
|
|
90
|
-
│
|
|
91
|
-
├──
|
|
92
|
-
│ ├──
|
|
93
|
-
│ ├──
|
|
94
|
-
│
|
|
95
|
-
├──
|
|
96
|
-
├──
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
├──
|
|
103
|
-
├──
|
|
104
|
-
├──
|
|
105
|
-
├──
|
|
106
|
-
├──
|
|
107
|
-
├──
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
92
|
+
├── animation/ # THE library — engine + every primitive (see src/animation/CLAUDE.md)
|
|
93
|
+
│ ├── index.ts # Package barrel: the LIGHT static surface + loadAnimationEngine()
|
|
94
|
+
│ ├── engine.ts # HEAVY: Animation, CSSKeyframesAnimation, AnimationGroup
|
|
95
|
+
│ ├── group.ts # AnimationGroup — multi-animation compositor
|
|
96
|
+
│ ├── frame-compiler.ts # Keyframe → frame compilation
|
|
97
|
+
│ ├── animate.ts # animate() — the single-call front door (HEAVY)
|
|
98
|
+
│ ├── motion-path.ts # MotionPath — offset-distance over an offset-path (HEAVY)
|
|
99
|
+
│ ├── draw-svg.ts # DrawSVG — stroke-dashoffset line drawing (HEAVY)
|
|
100
|
+
│ ├── animations.ts # 30+ presets (HEAVY — `presets` on loadAnimationEngine())
|
|
101
|
+
│ ├── numeric.ts # NumericAnimation — zero-alloc keyframe interpolation
|
|
102
|
+
│ ├── smooth.ts # SmoothProgress — exponential smoothing
|
|
103
|
+
│ ├── spring.ts # SpringProgress — analytic spring solver
|
|
104
|
+
│ ├── springLinearStops.ts # spring → CSS linear() stop string
|
|
105
|
+
│ ├── springTimingFunction.ts # spring → typed Easing (.fn + .css twin)
|
|
106
|
+
│ ├── morph.ts # ElementMorph — rect-to-rect transform interpolation
|
|
107
|
+
│ ├── timeline.ts # Timeline, ScrollTimeline, ManualTimeline (+ native bridge)
|
|
108
|
+
│ ├── playback.ts # RAFPlayback — THE managed rAF driver
|
|
109
|
+
│ ├── stagger.ts # stagger — per-index delay distributions
|
|
110
|
+
│ ├── flip.ts # flip / flipShared — FLIP over ElementMorph
|
|
111
|
+
│ ├── drag.ts # drag / Draggable — spring-backed pointer drag
|
|
112
|
+
│ ├── decay.ts # decay / decayRest — frictional glide closed form
|
|
113
|
+
│ ├── sequence.ts # Sequence — master-playhead orchestrator
|
|
114
|
+
│ ├── easing.ts # toEasing / resolveEasing — the easing boundary
|
|
115
|
+
│ ├── adapter.ts / waapi.ts / format.ts / constants.ts / utils.ts / internal/
|
|
116
|
+
└── env.d.ts
|
|
117
|
+
|
|
118
|
+
demo/ # Vue 3 demo apps (see demo/CLAUDE.md)
|
|
119
|
+
├── @/ # Shared editor shell, composables, UI, styles
|
|
120
|
+
├── app/ # Multi-scene demo SPA — the deployed demo
|
|
121
|
+
├── cube/ # 3D cube + AnimationGroup + matrix editor
|
|
122
|
+
├── square/ # Custom transform function
|
|
123
|
+
├── amiga/ # 3D animated sphere (Three.js)
|
|
124
|
+
├── easing/ # Easing editor
|
|
125
|
+
├── motion-path/ # MotionPath scene
|
|
126
|
+
├── sequence/ # Sequence orchestration scene
|
|
127
|
+
├── spring/ # Spring physics scene
|
|
128
|
+
└── playground/ # Asset playground
|
|
129
|
+
|
|
130
|
+
test/ # Vitest suites (jsdom)
|
|
131
|
+
bench/ # Vitest benchmarks
|
|
112
132
|
```
|
|
113
133
|
|
|
114
134
|
## Animation
|
|
@@ -132,6 +152,8 @@ The `Animation` object drives `CSSKeyframesAnimation` and `AnimationGroup`. It's
|
|
|
132
152
|
- `hueMethod`: hue interpolation method for cylindrical color spaces (optional)
|
|
133
153
|
- `useWAAPI`: delegate to Web Animations API when eligible (default: `true`)
|
|
134
154
|
|
|
155
|
+
Validation is fail-explicit: a malformed option — a negative `duration`, an unknown `direction` — throws a typed `AnimationOptionError` naming the option and the offending value.
|
|
156
|
+
|
|
135
157
|
### The transform function
|
|
136
158
|
|
|
137
159
|
```ts
|
|
@@ -205,6 +227,79 @@ const kf3 = { start: "100%", vars: { x: 0, y: 1 } };
|
|
|
205
227
|
|
|
206
228
|
`kf2` gets `y: 0` from `kf1`. This lets you specify keyframes loosely.
|
|
207
229
|
|
|
230
|
+
### The dynamic engine — `loadAnimationEngine()`
|
|
231
|
+
|
|
232
|
+
The package splits along a static/dynamic boundary (see [tree-shaking](#baseline-tree-shaking--reduced-motion)). The classes above — `Animation`, `CSSKeyframesAnimation`, `AnimationGroup` — are the **heavy** tier: they carry the CSS parser and `@mkbabb/value.js`, and their runtime constructors are reached **only** through `loadAnimationEngine()`, one awaited dynamic import:
|
|
233
|
+
|
|
234
|
+
```ts run
|
|
235
|
+
import { loadAnimationEngine } from "@mkbabb/keyframes.js";
|
|
236
|
+
|
|
237
|
+
// ONE await loads the CSS engine (and value.js with it); repeat calls
|
|
238
|
+
// resolve from the module cache. Light-only consumers never pay this.
|
|
239
|
+
const { CSSKeyframesAnimation, presets } = await loadAnimationEngine();
|
|
240
|
+
|
|
241
|
+
const anim = presets.fadeIn({ duration: 200 });
|
|
242
|
+
anim.setTargets(element);
|
|
243
|
+
await anim.play();
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
The engine surface (`AnimationEngine`): `Animation`, `CSSKeyframesAnimation`, `AnimationGroup`, `getAnimationId`, `getTimingFunction`, `resolveKeyframes`, `animate`, `MotionPath`/`fromMotionPath`, `DrawSVG`/`fromDrawSVG`, `presets`, and the option constants `DIRECTIONS`, `FILL_MODES`, `defaultOptions`, `defaultLayerConfig`. The **type** surface stays on the static barrel — `import type { Animation } from "@mkbabb/keyframes.js"` costs no runtime edge.
|
|
247
|
+
|
|
248
|
+
### `animate`
|
|
249
|
+
|
|
250
|
+
The single-call front door: construct + target + play in one call, dispatched on the **shape** of the input. The returned `CSSKeyframesAnimation` is the control handle — `.pause()` / `.play()` / `.stop()` / `await handle.finished`.
|
|
251
|
+
|
|
252
|
+
```ts run
|
|
253
|
+
const { animate } = await loadAnimationEngine();
|
|
254
|
+
|
|
255
|
+
const fade = animate(box, { "0%": { opacity: 0 }, "100%": { opacity: 1 } }, { duration: 200 });
|
|
256
|
+
await fade.finished;
|
|
257
|
+
|
|
258
|
+
// Dispatch on the input's shape:
|
|
259
|
+
animate(box, `from { opacity: 0 } to { opacity: 1 }`, { autoPlay: false }); // CSS string → fromString
|
|
260
|
+
animate(box, [{ opacity: 0 }, { opacity: 1 }], { autoPlay: false }); // vars array → fromVars
|
|
261
|
+
animate(box, { path: "path('M 0 0 H 100')" }, { autoPlay: false }); // MotionPath spec → fromMotionPath
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
Options: every [`AnimationOptions`](#animationoptions) key, plus `transform` (a custom renderer forwarded to the `from*` factory) and `autoPlay` (default `true`; `false` returns a constructed, targeted, not-yet-playing handle).
|
|
265
|
+
|
|
266
|
+
### `MotionPath`
|
|
267
|
+
|
|
268
|
+
CSS-native path motion: sweep `offset-distance` from → to over an author `offset-path`. The browser owns the geometry — keyframes interpolates one scalar — so the sweep is WAAPI-eligible and runs on the compositor thread where possible.
|
|
269
|
+
|
|
270
|
+
```ts run
|
|
271
|
+
const { fromMotionPath, MotionPath } = await loadAnimationEngine();
|
|
272
|
+
|
|
273
|
+
const along = fromMotionPath(box, {
|
|
274
|
+
path: "path('M 0 0 Q 100 -100 200 0')",
|
|
275
|
+
rotate: "auto", // offset-rotate — face along the path
|
|
276
|
+
duration: 200,
|
|
277
|
+
autoPlay: false,
|
|
278
|
+
});
|
|
279
|
+
await along.play();
|
|
280
|
+
|
|
281
|
+
new MotionPath(card, { path: "path('M 0 0 H 200')", autoPlay: false }); // class form
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Options: `path` (required — any `offset-path` value: `path()`, `ray()`, `url(#id)`, a basic shape), `from` (default `"0%"`), `to` (default `"100%"`), `rotate` (a static `offset-rotate`), `autoPlay`, plus every `AnimationOptions` key.
|
|
285
|
+
|
|
286
|
+
### `DrawSVG`
|
|
287
|
+
|
|
288
|
+
CSS-native SVG line drawing: ONE `getTotalLength()` read sets `stroke-dasharray` to the path length; the animation sweeps `stroke-dashoffset` `L → 0`, so the stroke draws in. A bare `<length>` — WAAPI-eligible, the simplest compositor-thread shape.
|
|
289
|
+
|
|
290
|
+
```ts run
|
|
291
|
+
const { fromDrawSVG, DrawSVG } = await loadAnimationEngine();
|
|
292
|
+
|
|
293
|
+
const draw = fromDrawSVG(pathEl, { duration: 200, autoPlay: false });
|
|
294
|
+
await draw.play();
|
|
295
|
+
|
|
296
|
+
// Erase instead — sweep 100% → 0% (percent strings, or 0..1 fractions):
|
|
297
|
+
fromDrawSVG(pathEl, { from: "100%", to: "0%", autoPlay: false });
|
|
298
|
+
new DrawSVG(pathEl, { autoPlay: false }); // class form; `.finished` resolves on completion
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
Options: `from`/`to` (`"0%"`–`"100%"` strings or `0`–`1` numbers; default draw-in `0% → 100%`), `autoPlay`, plus every `AnimationOptions` key. The target must be SVG geometry (`<path>`, `<line>`, `<circle>`, …) exposing `getTotalLength()`.
|
|
302
|
+
|
|
208
303
|
## `CSSKeyframesAnimation`
|
|
209
304
|
|
|
210
305
|
An abstraction over `Animation` that parses CSS `@keyframes` into `TemplateAnimationFrame` objects, then adds them to a base `Animation`.
|
|
@@ -280,6 +375,8 @@ Layer configuration per animation: `zIndex`, `weight`, `blendMode`, `enabled`, `
|
|
|
280
375
|
|
|
281
376
|
The group manages its own `requestAnimationFrame` loop and marks child animations as `managed`.
|
|
282
377
|
|
|
378
|
+
`AnimationGroup` (parallel children, blended per-frame) and [`Sequence`](#sequence) (children positioned along a master clock) are the production realization of Web Animations Level 2's `GroupEffect`/`SequenceEffect` model — see [`Sequence`](#sequence) for the correspondence table.
|
|
379
|
+
|
|
283
380
|
## Presets
|
|
284
381
|
|
|
285
382
|
30+ ready-to-use animations in [`animations.ts`](src/animation/animations.ts). All return `CSSKeyframesAnimation` instances and accept optional `InputAnimationOptions`. Each builds a value.js-bearing `CSSKeyframesAnimation`, so the presets ride the heavy dynamic boundary (the `presets` namespace on `loadAnimationEngine()`) rather than the value.js-free static barrel:
|
|
@@ -299,6 +396,114 @@ animate(element, presets.fadeIn());
|
|
|
299
396
|
|
|
300
397
|
**Fade**: `fadeIn`, `fadeOut` · **Attention**: `pulse`, `heartbeat`, `glow`, `shake`, `bounce` · **Entrance/Exit**: `flip`, `rotateIn`, `slideIn`, `slideInLeft/Right`, `slideOutLeft/Right`, `blurIn/Out/InOut`, `jumpUp/Down`, `warpLeft/Right` · **Effects**: `hover`, `typewriter`, `typingCursor`, `rainbowText`, `progressBar`, `skeletonLoading`, `spinner`, `parallaxScroll`, `gradientBackground`, `rotateScale`, `accordionExpand`, `notificationBounce`, `textFocusBlur`
|
|
301
398
|
|
|
399
|
+
## The round-trip — ingest, drive, compile
|
|
400
|
+
|
|
401
|
+
keyframes.js's authoring object **is** parsed CSS `@keyframes`. That one fact opens a loop no other engine can close:
|
|
402
|
+
|
|
403
|
+
1. **Ingest** — read the live web's CSS (`@keyframes` in a stylesheet, or a *running* CSS animation) straight into a kf `CSSKeyframesAnimation`.
|
|
404
|
+
2. **Drive** — run it through the engine: physics-shaped springs, perceptual `oklab` color, scroll-driven progress, weighted blending.
|
|
405
|
+
3. **Compile** — emit the result **back** to zero-runtime CSS — `compileToCSS` is the parser run *backward* over the same data model (`format.ts` is `keyframes.ts` in reverse).
|
|
406
|
+
|
|
407
|
+
This is the moat. GSAP, Motion, and anime author in a bespoke tween model — for them "export to CSS" is a lossy re-derivation nobody ships, and "import the page's CSS" has no meaning. Because kf's internal model is *already* CSS, the forward and backward halves are inverses over one structure: a `var()`, a `matrix3d()`, a `cqw` round-trips **verbatim**. The whole round-trip rides the heavy engine, reached through one `await loadAnimationEngine()`.
|
|
408
|
+
|
|
409
|
+
### Ingest — read the live web's CSS
|
|
410
|
+
|
|
411
|
+
Walk the document's stylesheets into kf objects, or take over a CSS animation *mid-flight*. Every entry point returns a **diagnostics** channel — a cross-origin sheet whose `cssRules` throws becomes a `CORS_SKIP` row, never a silent drop.
|
|
412
|
+
|
|
413
|
+
```ts
|
|
414
|
+
const { fromStyleSheets, fromLiveAnimations, adoptRunning } =
|
|
415
|
+
await loadAnimationEngine();
|
|
416
|
+
|
|
417
|
+
// Every @keyframes rule in document.styleSheets, reconstructed and keyed by name.
|
|
418
|
+
// The sibling `.class { animation: spin 2s … }` rule's options are recovered too,
|
|
419
|
+
// so each reconstructed animation carries its AUTHORED timing.
|
|
420
|
+
const { animations, diagnostics } = fromStyleSheets();
|
|
421
|
+
const spin = animations.get("spin")?.animation; // a CSSKeyframesAnimation
|
|
422
|
+
for (const d of diagnostics) console.warn(d.code, d.message); // e.g. CORS_SKIP
|
|
423
|
+
|
|
424
|
+
// Narrow to one name, or pass an explicit source (a sheet / array of sheets):
|
|
425
|
+
fromStyleSheets({ animationName: "spin" });
|
|
426
|
+
fromStyleSheets([...document.styleSheets]);
|
|
427
|
+
|
|
428
|
+
// fromLiveAnimations — the same walk, scoped to a RUNNING element's animations.
|
|
429
|
+
fromLiveAnimations(element);
|
|
430
|
+
|
|
431
|
+
// adoptRunning — the mid-flight TEMPORAL takeover: read the element's running
|
|
432
|
+
// CSS animation via getAnimations(), seed kf at the SAME currentTime (continuity,
|
|
433
|
+
// not seed-at-zero), and hand back the kf object to keep driving.
|
|
434
|
+
const { animation } = await adoptRunning(element, { animationName: "spin" });
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
`fromStyleSheets(source?, options?)` and `fromLiveAnimations(element, options?)` return `{ animations: Map<name, { name, animation, diagnostics }>, diagnostics }`. `resolveLiveKeyframes` is the lower-level walk both share. `adoptRunning(el, options)` returns `{ animation, … }` — the reconstructed kf object seeded at the live playhead.
|
|
438
|
+
|
|
439
|
+
### Scroll-as-CSS — the animation-timeline grammar
|
|
440
|
+
|
|
441
|
+
The CSS `animation-timeline` / `animation-range` grammar, round-tripped through value.js's typed extractor, and driven by a JS `ScrollScene` where the platform's native scroll-driven timelines aren't available. value.js owns the scroll **values** (the grammar, parsed verbatim — `scroll(root block)`, `entry 0%`, `cover 100%`); the kf `ScrollScene` owns **time** (resolving the live scroller against the DOM).
|
|
442
|
+
|
|
443
|
+
```ts
|
|
444
|
+
const { parseScrollCSS, roundTripScrollCSS, createScrollScene, pinCSS } =
|
|
445
|
+
await loadAnimationEngine();
|
|
446
|
+
|
|
447
|
+
// PARSE the author grammar into typed options — verbatim, no DOM resolution:
|
|
448
|
+
const opts = parseScrollCSS(`
|
|
449
|
+
.hero { animation-timeline: scroll(root block); animation-range: entry 0% cover 100%; }
|
|
450
|
+
`);
|
|
451
|
+
// opts.timeline => { kind: "scroll", scroller: "root", axis: "block" }
|
|
452
|
+
// opts.range => { start: { phase: "entry", offset: "0%" }, end: { phase: "cover", offset: "100%" } }
|
|
453
|
+
|
|
454
|
+
// roundTripScrollCSS proves the grammar is an inverse pair (parse → serialize):
|
|
455
|
+
roundTripScrollCSS(`.hero { animation-timeline: scroll(root block); }`);
|
|
456
|
+
|
|
457
|
+
// DRIVE it — the JS fallback scene resolves the scroller against the DOM and
|
|
458
|
+
// maps the resolved range onto [0, 1]; feed `.progress` to any interpolator.
|
|
459
|
+
const scene = createScrollScene({ range: opts.range, scrub: 0.2 });
|
|
460
|
+
element.style.opacity = String(scene.progress);
|
|
461
|
+
|
|
462
|
+
// pinCSS — synthesize the position:sticky pin a scroll-pinned scene needs:
|
|
463
|
+
pinCSS(); // => "position: sticky; top: 0px;"
|
|
464
|
+
pinCSS({ top: 24 }); // => "position: sticky; top: 24px;"
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
`dispatchScrollBackend` picks the conservative-correct backend (native `ScrollTimeline` where eligible, the JS scene otherwise); `serializeScrollOptions` is the inverse of `parseScrollCSS`. Where the platform ships native scroll-driven timelines, [`createNativeTimeline`](#timeline) is the additive fast lane and this scene is the general fallback.
|
|
468
|
+
|
|
469
|
+
### Compile — the parser run backward
|
|
470
|
+
|
|
471
|
+
`compileToCSS` walks an orchestration graph — an [`AnimationGroup`](#animationgroup), a [`Sequence`](#sequence), or a bare child list (e.g. a [`stagger`](#stagger)-delayed cohort) — and emits a **pure, zero-runtime CSS** artifact: one `@keyframes` block + an `animation` shorthand per child, `replace`/`add` layering as `animation-composition`, springs as `linear()`, materialized stagger delays, and computed units (`vh`/`cqw`/`calc()`/`var()`) verbatim. A human pastes the result and ships with **zero kf bytes on the page**.
|
|
472
|
+
|
|
473
|
+
```ts
|
|
474
|
+
const { CSSKeyframesAnimation, compileToCSS } = await loadAnimationEngine();
|
|
475
|
+
|
|
476
|
+
const fade = new CSSKeyframesAnimation({ duration: 600 })
|
|
477
|
+
.fromString(`from { background-color: #c462d8; } to { background-color: #e85252; }`)
|
|
478
|
+
.setTargets(element);
|
|
479
|
+
|
|
480
|
+
const { css, eligible, refusals } = await compileToCSS([fade]);
|
|
481
|
+
// eligible === true, refusals === []
|
|
482
|
+
// css is a paste-ready @keyframes block. Because the platform interpolates color
|
|
483
|
+
// in sRGB but kf interpolates in perceptual oklab, the compiler DENSIFIES the
|
|
484
|
+
// color track into intermediate oklab() stops, so the browser's piecewise-linear
|
|
485
|
+
// fill TRACKS kf's perceptual lerp — gated on a ΔE proof (ship only if it matches):
|
|
486
|
+
//
|
|
487
|
+
// @keyframes a0 {
|
|
488
|
+
// 0% { background-color: oklab(0.6573 0.1489 -0.1223); }
|
|
489
|
+
// 6.6667% { background-color: oklab(0.6563 0.1503 -0.1091); }
|
|
490
|
+
// …
|
|
491
|
+
// }
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
**The honest-refusal surface (the trust seam).** What cannot round-trip faithfully is **refused** with a named reason — never silently approximated. `compileToCSS` returns `{ css, eligible, refusals }`; when `eligible` is `false`, `refusals` names each child and why, and the JS playback is the only faithful path for those:
|
|
495
|
+
|
|
496
|
+
| Refusal reason | What it proves | The faithful path |
|
|
497
|
+
|---|---|---|
|
|
498
|
+
| `weighted-blend` | no `animation-composition` twin exists | JS `AnimationGroup` |
|
|
499
|
+
| `custom-renderer` | a closure cannot be CSS | JS playback |
|
|
500
|
+
| `perceptual-oklab` | the oklab densify exceeds the ΔE band | JS playback (true perceptual lerp) |
|
|
501
|
+
| `computed-unit-drift` | the narrow case where verbatim emit would drift | JS playback |
|
|
502
|
+
|
|
503
|
+
A refusal is **marketing for the moat**: it names exactly the kf axis (weighted blending, perceptual color) that exceeds pure CSS. `compileToCSS(input, options?)` options: `staggerDelays` (the materialized `stagger.delays(total)`, emitted as literal per-child `animation-delay`), `densifyStops` (the oklab stop count), `deltaEEpsilon` (the ship-vs-refuse threshold), `printWidth`.
|
|
504
|
+
|
|
505
|
+
> The snippets in this section are reached through `loadAnimationEngine()` and run against the built `dist/` (the `ts run` README examples in §Beyond CSS / §Animation are the CI-asserted set — `npm run proof:readme-runs`); the round-trip surface above is additionally exercised by `proof:ingest-replay`, `proof:scroll-roundtrip`, and `proof:compile-replay`.
|
|
506
|
+
|
|
302
507
|
## Web Animations API
|
|
303
508
|
|
|
304
509
|
When `useWAAPI` is `true` (default), eligible animations run on the compositor thread via `Element.animate()`. Eligibility requires: DOM targets, uniform timing function across frames, no computed units, no custom transform function, no color interpolation. Falls back to `requestAnimationFrame` silently.
|
|
@@ -332,11 +537,16 @@ Off-DOM (SSR / Node) the check is a no-op and animations proceed normally.
|
|
|
332
537
|
|
|
333
538
|
The library also ships general-purpose interpolation primitives, decoupled from CSS and the DOM. These compose into a pipeline: `timeline → progress → interpolator → values → apply`.
|
|
334
539
|
|
|
540
|
+
Everything in this section lives on the **light static barrel** — `import { NumericAnimation, SpringProgress, … } from "@mkbabb/keyframes.js"` — and carries zero static value.js edge (see [tree-shaking](#baseline-tree-shaking--reduced-motion)). Two conventions hold throughout:
|
|
541
|
+
|
|
542
|
+
- **Easing is callable.** Every light primitive takes a `TimingFunction` (`t => t'`) or a typed `Easing` — `toEasing` normalizes a bare callable to the typed shape, synchronously. A string easing *name* throws an `UnknownEasingError` — resolve it once, up front: `const easing = await resolveEasing("easeOutCubic")`.
|
|
543
|
+
- **Every snippet executes.** Each example below runs verbatim against the built package in CI (`npm run proof:readme-runs`); `// =>` comments are asserted results, not aspirations.
|
|
544
|
+
|
|
335
545
|
### `NumericAnimation`
|
|
336
546
|
|
|
337
547
|
Keyframe interpolation over plain `{key: number}` objects. Zero-allocation hot path — returns the same object reference each call. Two usage modes: stateless `.at()` queries, or managed `.play()` with rAF-driven playback.
|
|
338
548
|
|
|
339
|
-
```ts
|
|
549
|
+
```ts run
|
|
340
550
|
// Stateless — drive from your own render loop
|
|
341
551
|
const anim = new NumericAnimation([
|
|
342
552
|
{ x: 0, y: 0, opacity: 0 },
|
|
@@ -344,85 +554,330 @@ const anim = new NumericAnimation([
|
|
|
344
554
|
]);
|
|
345
555
|
anim.at(0.5); // => { x: 50, y: 100, opacity: 0.5 }
|
|
346
556
|
|
|
347
|
-
// Managed — rAF playback with per-frame callback
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
557
|
+
// Managed — rAF playback with a per-frame callback; a string easing
|
|
558
|
+
// name resolves once, up front:
|
|
559
|
+
const easing = await resolveEasing("easeOutCubic");
|
|
560
|
+
const dial = new NumericAnimation([{ angle: 0 }, { angle: Math.PI * 4 }], {
|
|
561
|
+
duration: 250,
|
|
562
|
+
timingFunction: easing,
|
|
563
|
+
});
|
|
564
|
+
await dial.play(({ angle }) => {
|
|
353
565
|
ctx.clearRect(0, 0, w, h);
|
|
354
566
|
drawDial(angle);
|
|
355
567
|
});
|
|
356
568
|
```
|
|
357
569
|
|
|
358
|
-
Options: `duration` (ms, required for `.play()`), `timingFunction
|
|
570
|
+
Options: `duration` (ms, required for `.play()`), `timingFunction` (callable or `Easing` — string names throw; resolve via `resolveEasing`), `positions` (explicit keyframe positions as percentages), `respectReducedMotion`. Call `.stop()` to cancel a running playback — the play promise resolves immediately.
|
|
359
571
|
|
|
360
572
|
### `SmoothProgress`
|
|
361
573
|
|
|
362
|
-
Exponential smoothing for progress values. Frame-rate independent via `tickDt(dt)
|
|
574
|
+
Exponential smoothing for progress values. Frame-rate independent via `tickDt(dt)` — the canonical millisecond step, the same `Tickable` surface [`RAFPlayback.drive`](#rafplayback) owns.
|
|
363
575
|
|
|
364
|
-
```ts
|
|
576
|
+
```ts run
|
|
365
577
|
const smooth = new SmoothProgress({ damping: 0.15 });
|
|
366
578
|
smooth.setTarget(1);
|
|
367
|
-
smooth.
|
|
579
|
+
smooth.tickDt(16.7); // one frame step — asymptotically approaches the target
|
|
368
580
|
smooth.snap(); // instantly converge
|
|
581
|
+
smooth.current; // => 1
|
|
582
|
+
|
|
583
|
+
// Managed — the smoother owns a rAF loop until it settles:
|
|
584
|
+
smooth.setTarget(0);
|
|
585
|
+
smooth.play((value) => element.style.setProperty("--p", String(value)));
|
|
586
|
+
smooth.stop();
|
|
369
587
|
```
|
|
370
588
|
|
|
371
|
-
Options: `damping` (lerp factor, default 0.1), `snapThreshold` (auto-snap distance, default 0.001), `targetEpsilon` (ignore target changes smaller than this — filters scroll jitter, default 0), `initial`, `clamp`.
|
|
589
|
+
Options: `damping` (lerp factor, default 0.1), `snapThreshold` (auto-snap distance, default 0.001), `targetEpsilon` (ignore target changes smaller than this — filters scroll jitter, default 0), `initial`, `clamp` (default `true` — constrain to `[0, 1]`), `respectReducedMotion`. Reads: `.current`, `.target`, `.settled`.
|
|
372
590
|
|
|
373
591
|
### `ElementMorph`
|
|
374
592
|
|
|
375
593
|
Interpolates position and scale between two DOM elements (or rects). Produces CSS transforms. Stateless `.apply()` or managed `.play()`.
|
|
376
594
|
|
|
377
|
-
```ts
|
|
595
|
+
```ts run
|
|
378
596
|
// Stateless
|
|
379
597
|
const morph = new ElementMorph(sourceEl, targetEl);
|
|
380
|
-
morph.apply(element,
|
|
598
|
+
morph.apply(element, 0.5); // writes transform + transformOrigin at progress 0.5
|
|
381
599
|
|
|
382
|
-
// Managed playback
|
|
383
|
-
const
|
|
384
|
-
duration:
|
|
385
|
-
timingFunction:
|
|
600
|
+
// Managed playback — feed it a spring for the canonical overshoot
|
|
601
|
+
const springy = new ElementMorph(sourceEl, targetEl, {
|
|
602
|
+
duration: 250,
|
|
603
|
+
timingFunction: springTimingFunction({ response: 0.4, dampingFraction: 0.7 }),
|
|
386
604
|
});
|
|
387
|
-
await
|
|
605
|
+
await springy.play(element);
|
|
388
606
|
```
|
|
389
607
|
|
|
390
|
-
Re-measures on demand via `morph.measure(from, to)
|
|
608
|
+
Re-measures on demand via `morph.measure(from, to)` (elements or `{ x, y, width, height }` rects). Call `.stop()` to cancel. Options: `duration`, `timingFunction` (callable or `Easing`), `transformOrigin` (default `"top left"`).
|
|
391
609
|
|
|
392
610
|
### `Timeline`
|
|
393
611
|
|
|
394
612
|
Abstract progress driver. Pipeline: `sample() → clamp → easing → boundary snap → smoothing`.
|
|
395
613
|
|
|
396
|
-
```ts
|
|
614
|
+
```ts run
|
|
615
|
+
const easing = await resolveEasing("easeOutCubic");
|
|
397
616
|
const timeline = new ScrollTimeline({
|
|
398
617
|
threshold: 0.35,
|
|
399
|
-
easing
|
|
618
|
+
easing,
|
|
400
619
|
boundaryEpsilon: 0.005,
|
|
401
620
|
smoothing: { damping: 0.15, targetEpsilon: 0.002 },
|
|
402
621
|
});
|
|
403
622
|
|
|
404
623
|
function update() {
|
|
405
|
-
|
|
624
|
+
element.style.opacity = String(timeline.tick());
|
|
406
625
|
requestAnimationFrame(update);
|
|
407
626
|
}
|
|
627
|
+
|
|
628
|
+
// ManualTimeline — externally-set value → progress; smoothing off by default
|
|
629
|
+
const manual = new ManualTimeline();
|
|
630
|
+
manual.set(0.25);
|
|
631
|
+
manual.tick(); // => 0.25
|
|
408
632
|
```
|
|
409
633
|
|
|
410
|
-
Options: `easing
|
|
634
|
+
Options: `easing` (callable or `Easing`), `smoothing` (`SmoothProgressOptions` or `false`), `boundaryEpsilon` (snap eased values within this distance of 0/1 to the boundary — prevents scroll-endpoint oscillation, default 0.005).
|
|
411
635
|
|
|
412
636
|
Subclasses:
|
|
413
637
|
- **`ScrollTimeline`** — scroll position → progress. `threshold` sets viewport fraction for full progress (default 0.35). Injectable `getScrollY`/`getViewportHeight`.
|
|
414
638
|
- **`ManualTimeline`** — externally set value → progress. Smoothing off by default.
|
|
415
639
|
|
|
640
|
+
Where the platform ships native scroll-driven timelines, `createNativeTimeline({ kind: "scroll" | "view", … })` feature-detects and returns a native `AnimationTimeline` (or `null`) as an additive fast lane — the JS sampler stays the general fallback.
|
|
641
|
+
|
|
416
642
|
See [`docs/scroll-morph.md`](docs/scroll-morph.md) for an architecture guide on building jitter-free scroll-driven morph animations.
|
|
417
643
|
|
|
644
|
+
### `SpringProgress`
|
|
645
|
+
|
|
646
|
+
A live-target spring tracker — the physics core under [`drag`](#drag--draggable). The solver integrates the damped harmonic oscillator **analytically** between target changes; setting `target` mid-flight re-seats the closed-form solution from the current `(value, velocity)`, so the trajectory never jumps. API mirrors SwiftUI's `.spring(response:dampingFraction:)`.
|
|
647
|
+
|
|
648
|
+
```ts run
|
|
649
|
+
const spring = new SpringProgress({ response: 0.5, dampingFraction: 0.86 });
|
|
650
|
+
spring.target = 1; // re-seat the closed form — continuous, no jump
|
|
651
|
+
spring.tickDt(16.7); // advance one frame (milliseconds); returns the new value
|
|
652
|
+
spring.settled; // => false
|
|
653
|
+
|
|
654
|
+
// Managed — the spring owns a rAF loop until it settles; a new target
|
|
655
|
+
// while playing auto-resumes the loop:
|
|
656
|
+
spring.play((value, velocity) => {
|
|
657
|
+
element.style.transform = `translateX(${value * 100}px)`;
|
|
658
|
+
});
|
|
659
|
+
spring.target = 0.5;
|
|
660
|
+
spring.stop();
|
|
661
|
+
|
|
662
|
+
// The time-based surface (Motion's idiom): perceptual duration + bounce
|
|
663
|
+
const bouncy = SpringProgress.fromDuration({ visualDuration: 0.4, bounce: 0.3 });
|
|
664
|
+
bouncy.settled; // => true
|
|
665
|
+
```
|
|
666
|
+
|
|
667
|
+
Options: `response` (oscillation period in seconds, default 0.5), `dampingFraction` (ζ — `1` critically damped, `< 1` rings, `> 1` overdamped; default 0.86), `initial`, `initialVelocity` (units/s), `settleThreshold` / `velocitySettleThreshold` (default `1e-3`), `respectReducedMotion`. Reads: `.value`, `.velocity`, `.target`, `.settled`; plus `subscribe(fn)` → unsubscribe, `reset(value?, velocity?)`, `snap()`, `dispose()`. `SpringProgress.fromDuration({ visualDuration | duration, bounce })` maps `response = visualDuration`, `dampingFraction = 1 − bounce`.
|
|
668
|
+
|
|
669
|
+
### `springLinearStops` & `springTimingFunction`
|
|
670
|
+
|
|
671
|
+
One analytic solver, two emissions. `springLinearStops` samples a `0 → 1` spring into a CSS `linear()` timing-function string (stylesheets, design tokens); `springTimingFunction` samples the same curve into a typed `Easing` — `.fn` is the callable for JS interpolation, `.css` its identical `linear()` twin, so a WAAPI delegation runs the true overshoot on the compositor (see [Web Animations API](#web-animations-api)).
|
|
672
|
+
|
|
673
|
+
```ts run
|
|
674
|
+
// CSS: a linear() string for transition/animation-timing-function
|
|
675
|
+
const stops = springLinearStops({ response: 0.5, dampingFraction: 0.45 });
|
|
676
|
+
stops.startsWith("linear(0, "); // => true
|
|
677
|
+
stops.endsWith(", 1)"); // => true
|
|
678
|
+
|
|
679
|
+
// JS: a typed Easing — feed it to NumericAnimation / ElementMorph / Animation
|
|
680
|
+
const spring = springTimingFunction({ response: 0.5, dampingFraction: 0.45 });
|
|
681
|
+
spring.fn(0); // => 0
|
|
682
|
+
spring.fn(1); // => 1
|
|
683
|
+
// ζ < 1 overshoots past 1 mid-curve — the whole point:
|
|
684
|
+
Math.max(...Array.from({ length: 101 }, (_, i) => spring.fn(i / 100))) > 1; // => true
|
|
685
|
+
// Same solver, same preset, ONE curve:
|
|
686
|
+
spring.css === springLinearStops({ response: 0.5, dampingFraction: 0.45 }); // => true
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
Options (both): `response`, `dampingFraction`, `sampleCount` (default 24 stops / 64 samples), `settleThreshold` (default `1e-3`), `maxDuration` (default `4 × response` — raise it for very underdamped springs, ζ < 0.3).
|
|
690
|
+
|
|
691
|
+
### `RAFPlayback`
|
|
692
|
+
|
|
693
|
+
THE managed rAF driver — every loop in the engine rides this one generation-guarded core, through three entry shapes: `play(duration, onTick)` (progress loop), `drive(tickable)` (step a `Tickable` — `SpringProgress`, `SmoothProgress` — until it settles), and `loop(cb)` (self-rescheduling async frame loop).
|
|
694
|
+
|
|
695
|
+
```ts run
|
|
696
|
+
const playback = new RAFPlayback();
|
|
697
|
+
|
|
698
|
+
// Duration loop — progress 0 → 1 over 200ms; resolves on completion or stop():
|
|
699
|
+
await playback.play(200, (progress) => {
|
|
700
|
+
element.style.opacity = String(progress);
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
// Bind-proof by construction: the control surface is arrow class-fields, so a
|
|
704
|
+
// destructured method keeps its receiver — no .bind(), ever:
|
|
705
|
+
const { stop } = playback;
|
|
706
|
+
playback.play(10_000, () => {});
|
|
707
|
+
stop(); // safe — the pending play promise resolves immediately
|
|
708
|
+
playback.running; // => false
|
|
709
|
+
|
|
710
|
+
// Settle loop — drive any Tickable to rest:
|
|
711
|
+
const spring = new SpringProgress({ response: 0.3 });
|
|
712
|
+
spring.target = 1;
|
|
713
|
+
playback.drive(spring, () => {
|
|
714
|
+
element.style.transform = `translateX(${spring.value * 100}px)`;
|
|
715
|
+
});
|
|
716
|
+
playback.stop();
|
|
717
|
+
```
|
|
718
|
+
|
|
719
|
+
Notes: `play(duration, onTick, { respectReducedMotion })` snaps to `onTick(1)` in a single paint under `prefers-reduced-motion: reduce` — the shared reduced-motion gate the light primitives route through. `drive` is idempotent (re-arm freely on every target re-seat; the loop auto-stops on settle). `loop(cb)` reschedules only after the (possibly async) callback completes, so a slow frame never double-schedules. `.running` reports loop ownership.
|
|
720
|
+
|
|
721
|
+
### `stagger`
|
|
722
|
+
|
|
723
|
+
A construction-time per-index delay generator — a pure distribution, zero per-frame cost. Returns `(index, total) => delayMs` with a `.delays(total)` materializer.
|
|
724
|
+
|
|
725
|
+
```ts run
|
|
726
|
+
const delay = stagger(5, { each: 50, from: "center" });
|
|
727
|
+
delay.delays(5); // => [100, 50, 0, 50, 100]
|
|
728
|
+
delay(0, 5); // => 100
|
|
729
|
+
|
|
730
|
+
// Reshape the distribution with an easing (resolved up front):
|
|
731
|
+
const eased = stagger(4, { each: 100, ease: await resolveEasing("easeOutCubic") });
|
|
732
|
+
eased(3, 4); // => 300
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
Options: `each` (per-step ms, default 100), `from` (`"first"` | `"last"` | `"center"` | `"edges"` | an index; default `"first"`), `ease` (callable or `Easing`; string names throw). Feed the delays to `AnimationGroup` per-child `delay`, `setTimeout`, or `animation-delay` — the generator is just arithmetic.
|
|
736
|
+
|
|
737
|
+
#### Recipe — structural stagger, the CSS way
|
|
738
|
+
|
|
739
|
+
The genre's text-reveal tools (GSAP SplitText) split text into per-letter DOM nodes. **Don't split text into letters**: letter-splitting produces non-functional accessibility markup across screen-reader/browser pairs (a 2026-documented hazard — `aria-label` is not honored on generic wrapper spans). keyframes.js takes the structural position: *we don't split your DOM; we stagger and spring over structure you own* — a visual-only reveal that never changes reading or tab order.
|
|
740
|
+
|
|
741
|
+
- Reveal at **word or line** granularity, over markup you author: `aria-label` on a true container, `aria-hidden` fragments inside (or a visually-hidden duplicate) — the mitigations that actually work.
|
|
742
|
+
- Drive the reveal with the shipped `stagger` + `SpringProgress` — the library performs no DOM mutation.
|
|
743
|
+
- Perceptual color across the reveal is free — the engine's default `oklab` interpolation already applies.
|
|
744
|
+
|
|
745
|
+
```ts run
|
|
746
|
+
// Markup you own:
|
|
747
|
+
// <h1 aria-label="Spring forward">
|
|
748
|
+
// <span aria-hidden="true">Spring</span> <span aria-hidden="true">forward</span>
|
|
749
|
+
// </h1>
|
|
750
|
+
const words = Array.from(heading.querySelectorAll<HTMLElement>("[aria-hidden]"));
|
|
751
|
+
const delay = stagger(words.length, { each: 60 });
|
|
752
|
+
|
|
753
|
+
words.forEach((word, i) => {
|
|
754
|
+
setTimeout(() => {
|
|
755
|
+
const spring = new SpringProgress({ response: 0.4, dampingFraction: 0.6 });
|
|
756
|
+
spring.target = 1;
|
|
757
|
+
spring.play((v) => {
|
|
758
|
+
word.style.opacity = String(Math.min(1, v));
|
|
759
|
+
word.style.transform = `translateY(${(1 - v) * 0.5}em)`;
|
|
760
|
+
});
|
|
761
|
+
}, delay(i, words.length));
|
|
762
|
+
});
|
|
763
|
+
```
|
|
764
|
+
|
|
765
|
+
Where `sibling-index()` is available, the same distribution emits as zero-runtime CSS — the progressive-enhancement path, not the default: `sibling-index()` is **not yet Baseline** (expected mid–late 2026), cannot appear inside `@keyframes`, and cannot carry the spring curve (pair it with a [`springLinearStops`](#springlinearstops--springtimingfunction) `linear()` timing function for that).
|
|
766
|
+
|
|
767
|
+
```css
|
|
768
|
+
/* CSS-only structural stagger — progressive enhancement */
|
|
769
|
+
h1 > span {
|
|
770
|
+
animation: word-in 600ms both;
|
|
771
|
+
animation-delay: calc(sibling-index() * 60ms);
|
|
772
|
+
}
|
|
773
|
+
```
|
|
774
|
+
|
|
775
|
+
### `flip` / `flipShared`
|
|
776
|
+
|
|
777
|
+
FLIP (First-Last-Invert-Play) layout animation over [`ElementMorph`](#elementmorph). `flip` animates a layout change on one element: measure (First) → `mutate()` (Last) → invert + play, with the two layout reads batched (no read/write thrash). `flipShared` animates element `a` onto element `b`'s rect — the shared-element / `layoutId` idiom.
|
|
778
|
+
|
|
779
|
+
```ts run
|
|
780
|
+
// FLIP a layout change — class toggle, reparent, any synchronous mutation:
|
|
781
|
+
await flip(card, () => card.classList.toggle("expanded"), { duration: 200 });
|
|
782
|
+
|
|
783
|
+
// Shared-element FLIP — animate `a` onto `b`'s rect; springs welcome:
|
|
784
|
+
await flipShared(a, b, {
|
|
785
|
+
duration: 200,
|
|
786
|
+
timingFunction: springTimingFunction({ response: 0.3, dampingFraction: 0.8 }),
|
|
787
|
+
});
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
Options: `duration` (default 300), `timingFunction` (callable or `Easing` — `springTimingFunction(…)` makes the FLIP springy), `transformOrigin` (default `"top left"`). Both return the play promise.
|
|
791
|
+
|
|
792
|
+
### `drag` / `Draggable`
|
|
793
|
+
|
|
794
|
+
A one-axis spring-backed drag: pointer capture follows the pointer as a live spring target; release hands the sampled pointer velocity (a rolling 100ms window) to the spring's re-seat, so the fling leaves the hand C¹-continuous — at exactly the flick speed. A 2-D drag composes two `Draggable`s, one per axis.
|
|
795
|
+
|
|
796
|
+
```ts run
|
|
797
|
+
const draggable = drag(element, {
|
|
798
|
+
axis: "x",
|
|
799
|
+
springOptions: { response: 0.3, dampingFraction: 0.9 },
|
|
800
|
+
});
|
|
801
|
+
|
|
802
|
+
const unsubscribe = draggable.subscribe((value, velocity) => {
|
|
803
|
+
element.style.transform = `translateX(${value}px)`;
|
|
804
|
+
});
|
|
805
|
+
|
|
806
|
+
draggable.dragging; // => false
|
|
807
|
+
unsubscribe();
|
|
808
|
+
draggable.detach(); // remove listeners; `.dispose()` tears down spring and all
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
Options: `axis` (`"x"` | `"y"`, default `"x"`), `transform` (map a client px coordinate → your value domain), `spring` (bring your own `SpringProgress`) or `springOptions`, `velocityWindow` (ms, default 100). Reads: `.value`, `.velocity`, `.dragging`, `.settled`, and `.spring` (the physics core). `drag(element, options)` is the one-call form of `new Draggable(options)` + `.attach(element)`.
|
|
812
|
+
|
|
813
|
+
### `decay` / `decayRest`
|
|
814
|
+
|
|
815
|
+
Frictional decay (inertial glide) — the closed-form sibling of the spring, for the fling with no target: velocity bleeds off under friction (`v' = −k·v`), coasting toward a finite rest point. `decay` returns a pure sampler; `decayRest` returns just the projected endpoint — the snap-target / paginated-fling decision without running a loop.
|
|
816
|
+
|
|
817
|
+
```ts run
|
|
818
|
+
const glide = decay({ initial: 0, velocity: 1200, friction: 5 });
|
|
819
|
+
glide(0); // => { value: 0, velocity: 1200 }
|
|
820
|
+
glide(0.25).value < 240; // => true
|
|
821
|
+
|
|
822
|
+
// The projected endpoint, x0 + v0/k — no loop needed:
|
|
823
|
+
decayRest({ velocity: 1200, friction: 5 }); // => 240
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
Options: `velocity` (required — release speed, units/s), `initial` (default 0), `friction` (1/s, strictly positive — larger = shorter glide; default 5). The sampler takes `t` in **seconds** (the spring's native clock).
|
|
827
|
+
|
|
828
|
+
### `Sequence`
|
|
829
|
+
|
|
830
|
+
The temporal orchestrator: position many animations along ONE master clock and drive them with a GSAP-class transport. Where [`AnimationGroup`](#animationgroup) composites many animations on one target per frame (spatial), `Sequence` maps a master playhead onto each child's local clock (temporal) — they compose, not compete. `Sequence` itself is light; the children arrive from the heavy engine.
|
|
831
|
+
|
|
832
|
+
```ts run
|
|
833
|
+
const { CSSKeyframesAnimation } = await loadAnimationEngine();
|
|
834
|
+
|
|
835
|
+
const fade = new CSSKeyframesAnimation({ duration: 300 })
|
|
836
|
+
.fromString(`from { opacity: 0; } to { opacity: 1; }`)
|
|
837
|
+
.setTargets(box);
|
|
838
|
+
const slide = new CSSKeyframesAnimation({ duration: 400 })
|
|
839
|
+
.fromString(`from { transform: translateX(-100px); } to { transform: translateX(0); }`)
|
|
840
|
+
.setTargets(card);
|
|
841
|
+
|
|
842
|
+
const seq = new Sequence()
|
|
843
|
+
.add(fade) // auto-append at 0
|
|
844
|
+
.add(slide, "-=100"); // overlap the previous segment by 100ms
|
|
845
|
+
|
|
846
|
+
seq.duration; // => 600
|
|
847
|
+
seq.seek(300); // scrub — master playhead → each child's local clock
|
|
848
|
+
await seq.play(); // the rAF transport drives the SAME map: play ≡ seek
|
|
849
|
+
seq.timeScale(2).repeat(2).yoyo(); // transport persists across plays
|
|
850
|
+
```
|
|
851
|
+
|
|
852
|
+
Positions: a number (absolute ms), `"+=n"` / `"-=n"` (relative to the insertion cursor), or a label registered via `.label(name, at)` (unknown labels throw). Transport: `play()` / `pause()` / `resume()` / `stop()`, `seek(ms)`, `progress` (get/set, `[0, 1]`), `timeScale(n)`, `reverse()`, `repeat(n | Infinity)`, `yoyo()`, `await seq.finished`. Options: `respectReducedMotion` (snap to the rest frame in one paint).
|
|
853
|
+
|
|
854
|
+
**Web Animations Level 2, in production.** `AnimationGroup` and `Sequence` are the production realization of WAAPI Level 2's `GroupEffect`/`SequenceEffect` model — grouping semantics no browser has ever shipped (polyfill-only, still a Working Draft, with `SequenceEffect` proposed for deletion upstream — [csswg-drafts#9557](https://github.com/w3c/csswg-drafts/issues/9557)) — running over real WAAPI children where eligible, with weighted blending and a transport the spec lacks. The correspondence is named, not mimicked: keyframes.js does not mirror the unsettled L2 class shapes, polyfill the missing native API, or pin its surface to class names the CSSWG is actively reworking.
|
|
855
|
+
|
|
856
|
+
| Web Animations Level 2 concept | keyframes.js surface |
|
|
857
|
+
| --- | --- |
|
|
858
|
+
| `GroupEffect` (parallel children) | [`AnimationGroup`](#animationgroup) |
|
|
859
|
+
| `SequenceEffect` / proposed `EffectTiming` `align: sequence` | `Sequence` auto-append |
|
|
860
|
+
| `EffectTiming` `align: start` | `Sequence` `at: 0` |
|
|
861
|
+
|
|
862
|
+
## Ecosystem & agents
|
|
863
|
+
|
|
864
|
+
- **[`@mkbabb/keyframes-vue`](packages/keyframes-vue/)** — a thin Vue 3 adapter over this library. Two on-brand primitives: the declarative `<Keyframes :css>` component (the author's CSS `@keyframes` → a scalar-progress slot — the component no other engine can write, because no other engine parses author CSS as its source format) and the `useKfAnimation` composable kernel. `@mkbabb/keyframes.js` and `vue` are **peers** — the core library never carries Vue.
|
|
865
|
+
|
|
866
|
+
```sh
|
|
867
|
+
npm i @mkbabb/keyframes-vue @mkbabb/keyframes.js vue
|
|
868
|
+
```
|
|
869
|
+
|
|
870
|
+
- **[`llms.txt`](./llms.txt)** — the agent surface: a machine-readable index of every capability, **generated** from the CI-verified published surface (`docs/published-surface.md`) so it cannot drift from the shipped API. Point an LLM/agent at it for a grounded map of the primitives, the static/dynamic boundary, and the round-trip. `llms-full.txt` carries the expanded form.
|
|
871
|
+
|
|
418
872
|
## Build & Development
|
|
419
873
|
|
|
420
874
|
```sh
|
|
421
|
-
npm run build # library → dist/keyframes.js +
|
|
422
|
-
npm run gh-pages # demo → dist/
|
|
423
|
-
npm run dev # vite dev server
|
|
875
|
+
npm run build # library (ESM) → dist/keyframes.js + lazy engine chunks + keyframes.d.ts
|
|
876
|
+
npm run gh-pages # demo (multi-scene SPA, demo/app) → dist/gh-pages/
|
|
877
|
+
npm run dev # vite dev server (demo/app)
|
|
424
878
|
npm test # vitest (jsdom)
|
|
425
879
|
npm run bench # vitest bench
|
|
880
|
+
npm run proof:readme-runs # execute every runnable README snippet against the built dist/
|
|
426
881
|
```
|
|
427
882
|
|
|
428
883
|
**Dependencies**: [`@mkbabb/value.js`](https://github.com/mkbabb/value.js) (ValueUnit, Color, math, parsing, normalization) and [`@mkbabb/parse-that`](https://github.com/mkbabb/parse-that) (parser combinators).
|