@mkbabb/keyframes.js 4.0.0 → 4.2.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 +397 -65
- package/dist/{animate-DjKYCuyH.js → animate-WjeAtXAe.js} +2 -2
- package/dist/{animations-CK1FLX_G.js → animations-WlZvjmDT.js} +2 -2
- package/dist/draw-svg-Dm9f0vTl.js +41 -0
- package/dist/{engine-BZeJ58xD.js → engine-Gk4Q7ltr.js} +204 -152
- package/dist/keyframes.d.ts +237 -28
- package/dist/keyframes.js +14 -8
- package/dist/{motion-path-723lMAlR.js → motion-path-DQ73oD2j.js} +1 -1
- package/dist/{springTimingFunction-BgkJPP-_.js → springTimingFunction-DMb11kBe.js} +1 -1
- package/dist/{timeline-5rnU0j6r.js → timeline-CPT7qUV1.js} +12 -11
- package/package.json +229 -131
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,6 +46,10 @@ 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)
|
|
@@ -58,6 +62,14 @@ Plucked directly from the [`demo/simple`](demo/simple/App.vue) Vue file.
|
|
|
58
62
|
- [SmoothProgress](#smoothprogress)
|
|
59
63
|
- [ElementMorph](#elementmorph)
|
|
60
64
|
- [Timeline](#timeline)
|
|
65
|
+
- [SpringProgress](#springprogress)
|
|
66
|
+
- [springLinearStops & springTimingFunction](#springlinearstops--springtimingfunction)
|
|
67
|
+
- [RAFPlayback](#rafplayback)
|
|
68
|
+
- [stagger](#stagger)
|
|
69
|
+
- [flip / flipShared](#flip--flipshared)
|
|
70
|
+
- [drag / Draggable](#drag--draggable)
|
|
71
|
+
- [decay / decayRest](#decay--decayrest)
|
|
72
|
+
- [Sequence](#sequence)
|
|
61
73
|
- [Build & Development](#build--development)
|
|
62
74
|
|
|
63
75
|
## Installation
|
|
@@ -72,43 +84,46 @@ Works both in and out of the browser. Anything that touches the DOM (`getCompute
|
|
|
72
84
|
|
|
73
85
|
```
|
|
74
86
|
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
|
-
|
|
87
|
+
├── animation/ # THE library — engine + every primitive (see src/animation/CLAUDE.md)
|
|
88
|
+
│ ├── index.ts # Package barrel: the LIGHT static surface + loadAnimationEngine()
|
|
89
|
+
│ ├── engine.ts # HEAVY: Animation, CSSKeyframesAnimation, AnimationGroup
|
|
90
|
+
│ ├── group.ts # AnimationGroup — multi-animation compositor
|
|
91
|
+
│ ├── frame-compiler.ts # Keyframe → frame compilation
|
|
92
|
+
│ ├── animate.ts # animate() — the single-call front door (HEAVY)
|
|
93
|
+
│ ├── motion-path.ts # MotionPath — offset-distance over an offset-path (HEAVY)
|
|
94
|
+
│ ├── draw-svg.ts # DrawSVG — stroke-dashoffset line drawing (HEAVY)
|
|
95
|
+
│ ├── animations.ts # 30+ presets (HEAVY — `presets` on loadAnimationEngine())
|
|
96
|
+
│ ├── numeric.ts # NumericAnimation — zero-alloc keyframe interpolation
|
|
97
|
+
│ ├── smooth.ts # SmoothProgress — exponential smoothing
|
|
98
|
+
│ ├── spring.ts # SpringProgress — analytic spring solver
|
|
99
|
+
│ ├── springLinearStops.ts # spring → CSS linear() stop string
|
|
100
|
+
│ ├── springTimingFunction.ts # spring → typed Easing (.fn + .css twin)
|
|
101
|
+
│ ├── morph.ts # ElementMorph — rect-to-rect transform interpolation
|
|
102
|
+
│ ├── timeline.ts # Timeline, ScrollTimeline, ManualTimeline (+ native bridge)
|
|
103
|
+
│ ├── playback.ts # RAFPlayback — THE managed rAF driver
|
|
104
|
+
│ ├── stagger.ts # stagger — per-index delay distributions
|
|
105
|
+
│ ├── flip.ts # flip / flipShared — FLIP over ElementMorph
|
|
106
|
+
│ ├── drag.ts # drag / Draggable — spring-backed pointer drag
|
|
107
|
+
│ ├── decay.ts # decay / decayRest — frictional glide closed form
|
|
108
|
+
│ ├── sequence.ts # Sequence — master-playhead orchestrator
|
|
109
|
+
│ ├── easing.ts # toEasing / resolveEasing — the easing boundary
|
|
110
|
+
│ ├── adapter.ts / waapi.ts / format.ts / constants.ts / utils.ts / internal/
|
|
111
|
+
└── env.d.ts
|
|
112
|
+
|
|
113
|
+
demo/ # Vue 3 demo apps (see demo/CLAUDE.md)
|
|
114
|
+
├── @/ # Shared editor shell, composables, UI, styles
|
|
115
|
+
├── app/ # Multi-scene demo SPA — the deployed demo
|
|
116
|
+
├── cube/ # 3D cube + AnimationGroup + matrix editor
|
|
117
|
+
├── square/ # Custom transform function
|
|
118
|
+
├── amiga/ # 3D animated sphere (Three.js)
|
|
119
|
+
├── easing/ # Easing editor
|
|
120
|
+
├── motion-path/ # MotionPath scene
|
|
121
|
+
├── sequence/ # Sequence orchestration scene
|
|
122
|
+
├── spring/ # Spring physics scene
|
|
123
|
+
└── playground/ # Asset playground
|
|
124
|
+
|
|
125
|
+
test/ # Vitest suites (jsdom)
|
|
126
|
+
bench/ # Vitest benchmarks
|
|
112
127
|
```
|
|
113
128
|
|
|
114
129
|
## Animation
|
|
@@ -132,6 +147,8 @@ The `Animation` object drives `CSSKeyframesAnimation` and `AnimationGroup`. It's
|
|
|
132
147
|
- `hueMethod`: hue interpolation method for cylindrical color spaces (optional)
|
|
133
148
|
- `useWAAPI`: delegate to Web Animations API when eligible (default: `true`)
|
|
134
149
|
|
|
150
|
+
Validation is fail-explicit: a malformed option — a negative `duration`, an unknown `direction` — throws a typed `AnimationOptionError` naming the option and the offending value.
|
|
151
|
+
|
|
135
152
|
### The transform function
|
|
136
153
|
|
|
137
154
|
```ts
|
|
@@ -205,6 +222,79 @@ const kf3 = { start: "100%", vars: { x: 0, y: 1 } };
|
|
|
205
222
|
|
|
206
223
|
`kf2` gets `y: 0` from `kf1`. This lets you specify keyframes loosely.
|
|
207
224
|
|
|
225
|
+
### The dynamic engine — `loadAnimationEngine()`
|
|
226
|
+
|
|
227
|
+
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:
|
|
228
|
+
|
|
229
|
+
```ts run
|
|
230
|
+
import { loadAnimationEngine } from "@mkbabb/keyframes.js";
|
|
231
|
+
|
|
232
|
+
// ONE await loads the CSS engine (and value.js with it); repeat calls
|
|
233
|
+
// resolve from the module cache. Light-only consumers never pay this.
|
|
234
|
+
const { CSSKeyframesAnimation, presets } = await loadAnimationEngine();
|
|
235
|
+
|
|
236
|
+
const anim = presets.fadeIn({ duration: 200 });
|
|
237
|
+
anim.setTargets(element);
|
|
238
|
+
await anim.play();
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
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.
|
|
242
|
+
|
|
243
|
+
### `animate`
|
|
244
|
+
|
|
245
|
+
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`.
|
|
246
|
+
|
|
247
|
+
```ts run
|
|
248
|
+
const { animate } = await loadAnimationEngine();
|
|
249
|
+
|
|
250
|
+
const fade = animate(box, { "0%": { opacity: 0 }, "100%": { opacity: 1 } }, { duration: 200 });
|
|
251
|
+
await fade.finished;
|
|
252
|
+
|
|
253
|
+
// Dispatch on the input's shape:
|
|
254
|
+
animate(box, `from { opacity: 0 } to { opacity: 1 }`, { autoPlay: false }); // CSS string → fromString
|
|
255
|
+
animate(box, [{ opacity: 0 }, { opacity: 1 }], { autoPlay: false }); // vars array → fromVars
|
|
256
|
+
animate(box, { path: "path('M 0 0 H 100')" }, { autoPlay: false }); // MotionPath spec → fromMotionPath
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
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).
|
|
260
|
+
|
|
261
|
+
### `MotionPath`
|
|
262
|
+
|
|
263
|
+
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.
|
|
264
|
+
|
|
265
|
+
```ts run
|
|
266
|
+
const { fromMotionPath, MotionPath } = await loadAnimationEngine();
|
|
267
|
+
|
|
268
|
+
const along = fromMotionPath(box, {
|
|
269
|
+
path: "path('M 0 0 Q 100 -100 200 0')",
|
|
270
|
+
rotate: "auto", // offset-rotate — face along the path
|
|
271
|
+
duration: 200,
|
|
272
|
+
autoPlay: false,
|
|
273
|
+
});
|
|
274
|
+
await along.play();
|
|
275
|
+
|
|
276
|
+
new MotionPath(card, { path: "path('M 0 0 H 200')", autoPlay: false }); // class form
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
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.
|
|
280
|
+
|
|
281
|
+
### `DrawSVG`
|
|
282
|
+
|
|
283
|
+
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.
|
|
284
|
+
|
|
285
|
+
```ts run
|
|
286
|
+
const { fromDrawSVG, DrawSVG } = await loadAnimationEngine();
|
|
287
|
+
|
|
288
|
+
const draw = fromDrawSVG(pathEl, { duration: 200, autoPlay: false });
|
|
289
|
+
await draw.play();
|
|
290
|
+
|
|
291
|
+
// Erase instead — sweep 100% → 0% (percent strings, or 0..1 fractions):
|
|
292
|
+
fromDrawSVG(pathEl, { from: "100%", to: "0%", autoPlay: false });
|
|
293
|
+
new DrawSVG(pathEl, { autoPlay: false }); // class form; `.finished` resolves on completion
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
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()`.
|
|
297
|
+
|
|
208
298
|
## `CSSKeyframesAnimation`
|
|
209
299
|
|
|
210
300
|
An abstraction over `Animation` that parses CSS `@keyframes` into `TemplateAnimationFrame` objects, then adds them to a base `Animation`.
|
|
@@ -280,6 +370,8 @@ Layer configuration per animation: `zIndex`, `weight`, `blendMode`, `enabled`, `
|
|
|
280
370
|
|
|
281
371
|
The group manages its own `requestAnimationFrame` loop and marks child animations as `managed`.
|
|
282
372
|
|
|
373
|
+
`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.
|
|
374
|
+
|
|
283
375
|
## Presets
|
|
284
376
|
|
|
285
377
|
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:
|
|
@@ -332,11 +424,16 @@ Off-DOM (SSR / Node) the check is a no-op and animations proceed normally.
|
|
|
332
424
|
|
|
333
425
|
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
426
|
|
|
427
|
+
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:
|
|
428
|
+
|
|
429
|
+
- **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")`.
|
|
430
|
+
- **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.
|
|
431
|
+
|
|
335
432
|
### `NumericAnimation`
|
|
336
433
|
|
|
337
434
|
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
435
|
|
|
339
|
-
```ts
|
|
436
|
+
```ts run
|
|
340
437
|
// Stateless — drive from your own render loop
|
|
341
438
|
const anim = new NumericAnimation([
|
|
342
439
|
{ x: 0, y: 0, opacity: 0 },
|
|
@@ -344,85 +441,320 @@ const anim = new NumericAnimation([
|
|
|
344
441
|
]);
|
|
345
442
|
anim.at(0.5); // => { x: 50, y: 100, opacity: 0.5 }
|
|
346
443
|
|
|
347
|
-
// Managed — rAF playback with per-frame callback
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
444
|
+
// Managed — rAF playback with a per-frame callback; a string easing
|
|
445
|
+
// name resolves once, up front:
|
|
446
|
+
const easing = await resolveEasing("easeOutCubic");
|
|
447
|
+
const dial = new NumericAnimation([{ angle: 0 }, { angle: Math.PI * 4 }], {
|
|
448
|
+
duration: 250,
|
|
449
|
+
timingFunction: easing,
|
|
450
|
+
});
|
|
451
|
+
await dial.play(({ angle }) => {
|
|
353
452
|
ctx.clearRect(0, 0, w, h);
|
|
354
453
|
drawDial(angle);
|
|
355
454
|
});
|
|
356
455
|
```
|
|
357
456
|
|
|
358
|
-
Options: `duration` (ms, required for `.play()`), `timingFunction
|
|
457
|
+
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
458
|
|
|
360
459
|
### `SmoothProgress`
|
|
361
460
|
|
|
362
|
-
Exponential smoothing for progress values. Frame-rate independent via `tickDt(dt)
|
|
461
|
+
Exponential smoothing for progress values. Frame-rate independent via `tickDt(dt)` — the canonical millisecond step, the same `Tickable` surface [`RAFPlayback.drive`](#rafplayback) owns.
|
|
363
462
|
|
|
364
|
-
```ts
|
|
463
|
+
```ts run
|
|
365
464
|
const smooth = new SmoothProgress({ damping: 0.15 });
|
|
366
465
|
smooth.setTarget(1);
|
|
367
|
-
smooth.
|
|
466
|
+
smooth.tickDt(16.7); // one frame step — asymptotically approaches the target
|
|
368
467
|
smooth.snap(); // instantly converge
|
|
468
|
+
smooth.current; // => 1
|
|
469
|
+
|
|
470
|
+
// Managed — the smoother owns a rAF loop until it settles:
|
|
471
|
+
smooth.setTarget(0);
|
|
472
|
+
smooth.play((value) => element.style.setProperty("--p", String(value)));
|
|
473
|
+
smooth.stop();
|
|
369
474
|
```
|
|
370
475
|
|
|
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`.
|
|
476
|
+
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
477
|
|
|
373
478
|
### `ElementMorph`
|
|
374
479
|
|
|
375
480
|
Interpolates position and scale between two DOM elements (or rects). Produces CSS transforms. Stateless `.apply()` or managed `.play()`.
|
|
376
481
|
|
|
377
|
-
```ts
|
|
482
|
+
```ts run
|
|
378
483
|
// Stateless
|
|
379
484
|
const morph = new ElementMorph(sourceEl, targetEl);
|
|
380
|
-
morph.apply(element,
|
|
485
|
+
morph.apply(element, 0.5); // writes transform + transformOrigin at progress 0.5
|
|
381
486
|
|
|
382
|
-
// Managed playback
|
|
383
|
-
const
|
|
384
|
-
duration:
|
|
385
|
-
timingFunction:
|
|
487
|
+
// Managed playback — feed it a spring for the canonical overshoot
|
|
488
|
+
const springy = new ElementMorph(sourceEl, targetEl, {
|
|
489
|
+
duration: 250,
|
|
490
|
+
timingFunction: springTimingFunction({ response: 0.4, dampingFraction: 0.7 }),
|
|
386
491
|
});
|
|
387
|
-
await
|
|
492
|
+
await springy.play(element);
|
|
388
493
|
```
|
|
389
494
|
|
|
390
|
-
Re-measures on demand via `morph.measure(from, to)
|
|
495
|
+
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
496
|
|
|
392
497
|
### `Timeline`
|
|
393
498
|
|
|
394
499
|
Abstract progress driver. Pipeline: `sample() → clamp → easing → boundary snap → smoothing`.
|
|
395
500
|
|
|
396
|
-
```ts
|
|
501
|
+
```ts run
|
|
502
|
+
const easing = await resolveEasing("easeOutCubic");
|
|
397
503
|
const timeline = new ScrollTimeline({
|
|
398
504
|
threshold: 0.35,
|
|
399
|
-
easing
|
|
505
|
+
easing,
|
|
400
506
|
boundaryEpsilon: 0.005,
|
|
401
507
|
smoothing: { damping: 0.15, targetEpsilon: 0.002 },
|
|
402
508
|
});
|
|
403
509
|
|
|
404
510
|
function update() {
|
|
405
|
-
|
|
511
|
+
element.style.opacity = String(timeline.tick());
|
|
406
512
|
requestAnimationFrame(update);
|
|
407
513
|
}
|
|
514
|
+
|
|
515
|
+
// ManualTimeline — externally-set value → progress; smoothing off by default
|
|
516
|
+
const manual = new ManualTimeline();
|
|
517
|
+
manual.set(0.25);
|
|
518
|
+
manual.tick(); // => 0.25
|
|
408
519
|
```
|
|
409
520
|
|
|
410
|
-
Options: `easing
|
|
521
|
+
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
522
|
|
|
412
523
|
Subclasses:
|
|
413
524
|
- **`ScrollTimeline`** — scroll position → progress. `threshold` sets viewport fraction for full progress (default 0.35). Injectable `getScrollY`/`getViewportHeight`.
|
|
414
525
|
- **`ManualTimeline`** — externally set value → progress. Smoothing off by default.
|
|
415
526
|
|
|
527
|
+
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.
|
|
528
|
+
|
|
416
529
|
See [`docs/scroll-morph.md`](docs/scroll-morph.md) for an architecture guide on building jitter-free scroll-driven morph animations.
|
|
417
530
|
|
|
531
|
+
### `SpringProgress`
|
|
532
|
+
|
|
533
|
+
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:)`.
|
|
534
|
+
|
|
535
|
+
```ts run
|
|
536
|
+
const spring = new SpringProgress({ response: 0.5, dampingFraction: 0.86 });
|
|
537
|
+
spring.target = 1; // re-seat the closed form — continuous, no jump
|
|
538
|
+
spring.tickDt(16.7); // advance one frame (milliseconds); returns the new value
|
|
539
|
+
spring.settled; // => false
|
|
540
|
+
|
|
541
|
+
// Managed — the spring owns a rAF loop until it settles; a new target
|
|
542
|
+
// while playing auto-resumes the loop:
|
|
543
|
+
spring.play((value, velocity) => {
|
|
544
|
+
element.style.transform = `translateX(${value * 100}px)`;
|
|
545
|
+
});
|
|
546
|
+
spring.target = 0.5;
|
|
547
|
+
spring.stop();
|
|
548
|
+
|
|
549
|
+
// The time-based surface (Motion's idiom): perceptual duration + bounce
|
|
550
|
+
const bouncy = SpringProgress.fromDuration({ visualDuration: 0.4, bounce: 0.3 });
|
|
551
|
+
bouncy.settled; // => true
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
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`.
|
|
555
|
+
|
|
556
|
+
### `springLinearStops` & `springTimingFunction`
|
|
557
|
+
|
|
558
|
+
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)).
|
|
559
|
+
|
|
560
|
+
```ts run
|
|
561
|
+
// CSS: a linear() string for transition/animation-timing-function
|
|
562
|
+
const stops = springLinearStops({ response: 0.5, dampingFraction: 0.45 });
|
|
563
|
+
stops.startsWith("linear(0, "); // => true
|
|
564
|
+
stops.endsWith(", 1)"); // => true
|
|
565
|
+
|
|
566
|
+
// JS: a typed Easing — feed it to NumericAnimation / ElementMorph / Animation
|
|
567
|
+
const spring = springTimingFunction({ response: 0.5, dampingFraction: 0.45 });
|
|
568
|
+
spring.fn(0); // => 0
|
|
569
|
+
spring.fn(1); // => 1
|
|
570
|
+
// ζ < 1 overshoots past 1 mid-curve — the whole point:
|
|
571
|
+
Math.max(...Array.from({ length: 101 }, (_, i) => spring.fn(i / 100))) > 1; // => true
|
|
572
|
+
// Same solver, same preset, ONE curve:
|
|
573
|
+
spring.css === springLinearStops({ response: 0.5, dampingFraction: 0.45 }); // => true
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
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).
|
|
577
|
+
|
|
578
|
+
### `RAFPlayback`
|
|
579
|
+
|
|
580
|
+
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).
|
|
581
|
+
|
|
582
|
+
```ts run
|
|
583
|
+
const playback = new RAFPlayback();
|
|
584
|
+
|
|
585
|
+
// Duration loop — progress 0 → 1 over 200ms; resolves on completion or stop():
|
|
586
|
+
await playback.play(200, (progress) => {
|
|
587
|
+
element.style.opacity = String(progress);
|
|
588
|
+
});
|
|
589
|
+
|
|
590
|
+
// Bind-proof by construction: the control surface is arrow class-fields, so a
|
|
591
|
+
// destructured method keeps its receiver — no .bind(), ever:
|
|
592
|
+
const { stop } = playback;
|
|
593
|
+
playback.play(10_000, () => {});
|
|
594
|
+
stop(); // safe — the pending play promise resolves immediately
|
|
595
|
+
playback.running; // => false
|
|
596
|
+
|
|
597
|
+
// Settle loop — drive any Tickable to rest:
|
|
598
|
+
const spring = new SpringProgress({ response: 0.3 });
|
|
599
|
+
spring.target = 1;
|
|
600
|
+
playback.drive(spring, () => {
|
|
601
|
+
element.style.transform = `translateX(${spring.value * 100}px)`;
|
|
602
|
+
});
|
|
603
|
+
playback.stop();
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
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.
|
|
607
|
+
|
|
608
|
+
### `stagger`
|
|
609
|
+
|
|
610
|
+
A construction-time per-index delay generator — a pure distribution, zero per-frame cost. Returns `(index, total) => delayMs` with a `.delays(total)` materializer.
|
|
611
|
+
|
|
612
|
+
```ts run
|
|
613
|
+
const delay = stagger(5, { each: 50, from: "center" });
|
|
614
|
+
delay.delays(5); // => [100, 50, 0, 50, 100]
|
|
615
|
+
delay(0, 5); // => 100
|
|
616
|
+
|
|
617
|
+
// Reshape the distribution with an easing (resolved up front):
|
|
618
|
+
const eased = stagger(4, { each: 100, ease: await resolveEasing("easeOutCubic") });
|
|
619
|
+
eased(3, 4); // => 300
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
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.
|
|
623
|
+
|
|
624
|
+
#### Recipe — structural stagger, the CSS way
|
|
625
|
+
|
|
626
|
+
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.
|
|
627
|
+
|
|
628
|
+
- 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.
|
|
629
|
+
- Drive the reveal with the shipped `stagger` + `SpringProgress` — the library performs no DOM mutation.
|
|
630
|
+
- Perceptual color across the reveal is free — the engine's default `oklab` interpolation already applies.
|
|
631
|
+
|
|
632
|
+
```ts run
|
|
633
|
+
// Markup you own:
|
|
634
|
+
// <h1 aria-label="Spring forward">
|
|
635
|
+
// <span aria-hidden="true">Spring</span> <span aria-hidden="true">forward</span>
|
|
636
|
+
// </h1>
|
|
637
|
+
const words = Array.from(heading.querySelectorAll<HTMLElement>("[aria-hidden]"));
|
|
638
|
+
const delay = stagger(words.length, { each: 60 });
|
|
639
|
+
|
|
640
|
+
words.forEach((word, i) => {
|
|
641
|
+
setTimeout(() => {
|
|
642
|
+
const spring = new SpringProgress({ response: 0.4, dampingFraction: 0.6 });
|
|
643
|
+
spring.target = 1;
|
|
644
|
+
spring.play((v) => {
|
|
645
|
+
word.style.opacity = String(Math.min(1, v));
|
|
646
|
+
word.style.transform = `translateY(${(1 - v) * 0.5}em)`;
|
|
647
|
+
});
|
|
648
|
+
}, delay(i, words.length));
|
|
649
|
+
});
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
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).
|
|
653
|
+
|
|
654
|
+
```css
|
|
655
|
+
/* CSS-only structural stagger — progressive enhancement */
|
|
656
|
+
h1 > span {
|
|
657
|
+
animation: word-in 600ms both;
|
|
658
|
+
animation-delay: calc(sibling-index() * 60ms);
|
|
659
|
+
}
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
### `flip` / `flipShared`
|
|
663
|
+
|
|
664
|
+
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.
|
|
665
|
+
|
|
666
|
+
```ts run
|
|
667
|
+
// FLIP a layout change — class toggle, reparent, any synchronous mutation:
|
|
668
|
+
await flip(card, () => card.classList.toggle("expanded"), { duration: 200 });
|
|
669
|
+
|
|
670
|
+
// Shared-element FLIP — animate `a` onto `b`'s rect; springs welcome:
|
|
671
|
+
await flipShared(a, b, {
|
|
672
|
+
duration: 200,
|
|
673
|
+
timingFunction: springTimingFunction({ response: 0.3, dampingFraction: 0.8 }),
|
|
674
|
+
});
|
|
675
|
+
```
|
|
676
|
+
|
|
677
|
+
Options: `duration` (default 300), `timingFunction` (callable or `Easing` — `springTimingFunction(…)` makes the FLIP springy), `transformOrigin` (default `"top left"`). Both return the play promise.
|
|
678
|
+
|
|
679
|
+
### `drag` / `Draggable`
|
|
680
|
+
|
|
681
|
+
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.
|
|
682
|
+
|
|
683
|
+
```ts run
|
|
684
|
+
const draggable = drag(element, {
|
|
685
|
+
axis: "x",
|
|
686
|
+
springOptions: { response: 0.3, dampingFraction: 0.9 },
|
|
687
|
+
});
|
|
688
|
+
|
|
689
|
+
const unsubscribe = draggable.subscribe((value, velocity) => {
|
|
690
|
+
element.style.transform = `translateX(${value}px)`;
|
|
691
|
+
});
|
|
692
|
+
|
|
693
|
+
draggable.dragging; // => false
|
|
694
|
+
unsubscribe();
|
|
695
|
+
draggable.detach(); // remove listeners; `.dispose()` tears down spring and all
|
|
696
|
+
```
|
|
697
|
+
|
|
698
|
+
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)`.
|
|
699
|
+
|
|
700
|
+
### `decay` / `decayRest`
|
|
701
|
+
|
|
702
|
+
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.
|
|
703
|
+
|
|
704
|
+
```ts run
|
|
705
|
+
const glide = decay({ initial: 0, velocity: 1200, friction: 5 });
|
|
706
|
+
glide(0); // => { value: 0, velocity: 1200 }
|
|
707
|
+
glide(0.25).value < 240; // => true
|
|
708
|
+
|
|
709
|
+
// The projected endpoint, x0 + v0/k — no loop needed:
|
|
710
|
+
decayRest({ velocity: 1200, friction: 5 }); // => 240
|
|
711
|
+
```
|
|
712
|
+
|
|
713
|
+
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).
|
|
714
|
+
|
|
715
|
+
### `Sequence`
|
|
716
|
+
|
|
717
|
+
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.
|
|
718
|
+
|
|
719
|
+
```ts run
|
|
720
|
+
const { CSSKeyframesAnimation } = await loadAnimationEngine();
|
|
721
|
+
|
|
722
|
+
const fade = new CSSKeyframesAnimation({ duration: 300 })
|
|
723
|
+
.fromString(`from { opacity: 0; } to { opacity: 1; }`)
|
|
724
|
+
.setTargets(box);
|
|
725
|
+
const slide = new CSSKeyframesAnimation({ duration: 400 })
|
|
726
|
+
.fromString(`from { transform: translateX(-100px); } to { transform: translateX(0); }`)
|
|
727
|
+
.setTargets(card);
|
|
728
|
+
|
|
729
|
+
const seq = new Sequence()
|
|
730
|
+
.add(fade) // auto-append at 0
|
|
731
|
+
.add(slide, "-=100"); // overlap the previous segment by 100ms
|
|
732
|
+
|
|
733
|
+
seq.duration; // => 600
|
|
734
|
+
seq.seek(300); // scrub — master playhead → each child's local clock
|
|
735
|
+
await seq.play(); // the rAF transport drives the SAME map: play ≡ seek
|
|
736
|
+
seq.timeScale(2).repeat(2).yoyo(); // transport persists across plays
|
|
737
|
+
```
|
|
738
|
+
|
|
739
|
+
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).
|
|
740
|
+
|
|
741
|
+
**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.
|
|
742
|
+
|
|
743
|
+
| Web Animations Level 2 concept | keyframes.js surface |
|
|
744
|
+
| --- | --- |
|
|
745
|
+
| `GroupEffect` (parallel children) | [`AnimationGroup`](#animationgroup) |
|
|
746
|
+
| `SequenceEffect` / proposed `EffectTiming` `align: sequence` | `Sequence` auto-append |
|
|
747
|
+
| `EffectTiming` `align: start` | `Sequence` `at: 0` |
|
|
748
|
+
|
|
418
749
|
## Build & Development
|
|
419
750
|
|
|
420
751
|
```sh
|
|
421
|
-
npm run build # library → dist/keyframes.js +
|
|
422
|
-
npm run gh-pages # demo → dist/
|
|
423
|
-
npm run dev # vite dev server
|
|
752
|
+
npm run build # library (ESM) → dist/keyframes.js + lazy engine chunks + keyframes.d.ts
|
|
753
|
+
npm run gh-pages # demo (multi-scene SPA, demo/app) → dist/gh-pages/
|
|
754
|
+
npm run dev # vite dev server (demo/app)
|
|
424
755
|
npm test # vitest (jsdom)
|
|
425
756
|
npm run bench # vitest bench
|
|
757
|
+
npm run proof:readme-runs # execute every runnable README snippet against the built dist/
|
|
426
758
|
```
|
|
427
759
|
|
|
428
760
|
**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).
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CSSKeyframesAnimation as e } from "./engine-
|
|
2
|
-
import { fromMotionPath as t } from "./motion-path-
|
|
1
|
+
import { CSSKeyframesAnimation as e } from "./engine-Gk4Q7ltr.js";
|
|
2
|
+
import { fromMotionPath as t } from "./motion-path-DQ73oD2j.js";
|
|
3
3
|
//#region src/animation/animate.ts
|
|
4
4
|
var n = (e) => typeof e == "object" && !!e && !Array.isArray(e) && !(e instanceof Map) && typeof e.path == "string", r = (e) => e instanceof Map || typeof e == "object" && !!e && !Array.isArray(e);
|
|
5
5
|
function i(i, a, o) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as e } from "./springTimingFunction-
|
|
2
|
-
import { CSSKeyframesAnimation as t } from "./engine-
|
|
1
|
+
import { t as e } from "./springTimingFunction-DMb11kBe.js";
|
|
2
|
+
import { CSSKeyframesAnimation as t } from "./engine-Gk4Q7ltr.js";
|
|
3
3
|
import { CSSCubicBezier as n, steppedEase as r } from "@mkbabb/value.js";
|
|
4
4
|
//#region src/animation/animations.ts
|
|
5
5
|
var ee = "\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n", i = (e) => new t({
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { CSSKeyframesAnimation as e } from "./engine-Gk4Q7ltr.js";
|
|
2
|
+
//#region src/animation/draw-svg.ts
|
|
3
|
+
var t = (e) => {
|
|
4
|
+
if (typeof e == "number") {
|
|
5
|
+
if (!Number.isFinite(e) || e < 0 || e > 1) throw Error(`fromDrawSVG(): a numeric draw position is a 0..1 fraction, got ${JSON.stringify(e)} — pass a fraction in [0, 1] or a percent string ("0%".."100%").`);
|
|
6
|
+
return e;
|
|
7
|
+
}
|
|
8
|
+
if (!/^\s*\d*\.?\d+\s*%\s*$/.test(e)) throw Error(`fromDrawSVG(): invalid draw position ${JSON.stringify(e)} — pass a percent string ("0%".."100%") or a 0..1 number.`);
|
|
9
|
+
return parseFloat(e) / 100;
|
|
10
|
+
};
|
|
11
|
+
function n(n, r = {}) {
|
|
12
|
+
let { from: i = "0%", to: a = "100%", autoPlay: o = !0, ...s } = r;
|
|
13
|
+
if (n == null || typeof n.getTotalLength != "function") throw Error("fromDrawSVG(): `target` must be an SVG geometry element exposing getTotalLength() (a <path>/<line>/<circle>/<rect>/<polygon>/…).");
|
|
14
|
+
let c = t(i), l = t(a), u = n.getTotalLength();
|
|
15
|
+
n.style.strokeDasharray = `${u}`;
|
|
16
|
+
let d = {
|
|
17
|
+
"0%": { "stroke-dashoffset": u * (1 - c) },
|
|
18
|
+
"100%": { "stroke-dashoffset": u * (1 - l) }
|
|
19
|
+
}, f = new e(s).fromKeyframes(d);
|
|
20
|
+
return f.setTargets(n), o && f.play(), f;
|
|
21
|
+
}
|
|
22
|
+
var r = class {
|
|
23
|
+
animation;
|
|
24
|
+
constructor(e, t = {}) {
|
|
25
|
+
this.animation = n(e, t);
|
|
26
|
+
}
|
|
27
|
+
play() {
|
|
28
|
+
return this.animation.play();
|
|
29
|
+
}
|
|
30
|
+
pause() {
|
|
31
|
+
return this.animation.pause(), this;
|
|
32
|
+
}
|
|
33
|
+
stop() {
|
|
34
|
+
return this.animation.stop(), this;
|
|
35
|
+
}
|
|
36
|
+
get finished() {
|
|
37
|
+
return this.animation.finished;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
//#endregion
|
|
41
|
+
export { r as DrawSVG, n as fromDrawSVG };
|