@mkbabb/keyframes.js 5.3.5 → 6.0.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 CHANGED
@@ -6,7 +6,7 @@ CSS keyframe animations for anything in JavaScript. Specify your keyframes in st
6
6
 
7
7
  ## Quick Start
8
8
 
9
- Create a `CSSKeyframesAnimation`, feed it CSS `@keyframes`, add targets, play. The engine class is a static, synchronous import from the `@mkbabb/keyframes.js/engine` subpath (it carries the CSS parser + `@mkbabb/value.js`; the light `.` barrel stays value.js-free):
9
+ Create a `CSSKeyframesAnimation`, feed it CSS `@keyframes`, add targets, play. The engine class is a static, synchronous import from the `@mkbabb/keyframes.js/engine` subpath (it carries Value's CSS parser and color/value capabilities; the light `.` barrel shares only Value's small `/math` leaf):
10
10
 
11
11
  ```ts run
12
12
  import { CSSKeyframesAnimation } from "@mkbabb/keyframes.js/engine";
@@ -85,7 +85,7 @@ type TransformFunction<V extends Vars> = (v: V, t: number) => void;
85
85
 
86
86
  Called at each timestep `t` (0 to `duration`) with the interpolated variables `v`. The variables arrive in the same shape you specified in your keyframes—deeply nested objects included.
87
87
 
88
- Every value is parsed as a CSS value unit (`1px`, `1em`, `1deg`, etc.). To interpolate between two units they must share a supertype: `px` and `em` are both **length**, so they interpolate; `px` and `deg` are not.
88
+ Every declaration is parsed into a structural `CssValue` tree. Numeric scalar leaves retain their CSS unit (`px`, `em`, `deg`, etc.); compatible units share a numeric interpolation slot, computed lengths resolve against the bound browser target, and incompatible kinds fail explicitly.
89
89
 
90
90
  ### The timing function
91
91
 
@@ -138,7 +138,7 @@ anim.setTargets(element);
138
138
  await anim.play();
139
139
  ```
140
140
 
141
- The engine surface (`AnimationEngine`): `KeyframesAnimation`, `CSSKeyframesAnimation`, `AnimationGroup`, `getAnimationId`, `getTimingFunction`, `resolveKeyframes`, `MotionPath`/`fromMotionPath`, `DrawSVG`/`fromDrawSVG`, `MorphSVG`/`fromMorphSVG`, `presets`, and the option constants `DIRECTIONS`, `FILL_MODES`, `defaultOptions`, `defaultLayerConfig`. The **type** surface stays on the static barrel — `import type { KeyframesAnimation } from "@mkbabb/keyframes.js"` costs no runtime edge.
141
+ The engine surface (`AnimationEngine`): `KeyframesAnimation`, `CSSKeyframesAnimation`, `AnimationGroup`, `getAnimationId`, `resolveKeyframes`, `MotionPath`/`fromMotionPath`, `DrawSVG`/`fromDrawSVG`, `MorphSVG`/`fromMorphSVG`, `presets`, and the option constants `DIRECTIONS`, `FILL_MODES`, `defaultOptions`, `defaultLayerConfig`. The **type** surface stays on the static barrel — `import type { KeyframesAnimation } from "@mkbabb/keyframes.js"` costs no runtime edge.
142
142
 
143
143
  ### `MotionPath`
144
144
 
@@ -179,7 +179,7 @@ Options: `from`/`to` (`"0%"`–`"100%"` strings or `0`–`1` numbers; default dr
179
179
 
180
180
  ### `MorphSVG`
181
181
 
182
- Path-shape morphing — interpolate one SVG path `d` into another. value.js's `PathGeometry` owns the geometry (arc-length sampling via `getTotalLength()`/`getPointAtLength()`); keyframes samples both paths at `samples` uniform points and lerps the matched point sets, so the engine's native numeric interpolation *is* the morph (a true blend — the midpoint is distinct from both endpoints, not a cross-fade).
182
+ Path-shape morphing — interpolate one SVG path `d` into another. value.js's `PathGeometry` owns the geometry (arc-length sampling via `getTotalLength()`/`getPointAtLength()`); keyframes samples both paths at `samples` uniform points and lerps the matched point sets, so the engine's native numeric interpolation _is_ the morph (a true blend — the midpoint is distinct from both endpoints, not a cross-fade).
183
183
 
184
184
  ```ts run
185
185
  const { fromMorphSVG, MorphSVG } = await loadAnimationEngine();
@@ -212,10 +212,15 @@ const { keyframes } = resolveKeyframes(`
212
212
  100% { color: green }
213
213
  }
214
214
  `);
215
- String(keyframes.get("0%")?.color); // => "rgb(0 0 255)"
215
+ const resolvedColor = keyframes.get("0%")?.color;
216
+ resolvedColor?.kind; // => "scalar"
217
+ const channels = resolvedColor?.kind === "scalar" && resolvedColor.payload.type === "color"
218
+ ? resolvedColor.payload.value.channels
219
+ : [];
220
+ channels; // => [0, 0, 255]
216
221
  ```
217
222
 
218
- **What it refuses.** A condition that resolves to nothing is a CSS *guaranteed-invalid value* — `if()` with no matching branch and no `else`, or an over-deep/self-referential `@function` chain (cycle-guarded at depth 32) — **drops the declaration** (the prior/initial value wins), never an empty or malformed string. A `@function` call whose argument can't be coerced to the parameter's declared syntax drops the whole call too, surfaced as a named `CUSTOM_FN_ARG_DROP` diagnostic on `resolveKeyframes`'s `diagnostics` channel — never a silent `NaN`.
223
+ **What it refuses.** A condition that resolves to nothing is a CSS _guaranteed-invalid value_ — `if()` with no matching branch and no `else`, or an over-deep/self-referential `@function` chain (cycle-guarded at depth 32) — **drops the declaration** (the prior/initial value wins), never an empty or malformed string. A `@function` call whose argument can't be coerced to the parameter's declared syntax drops the whole call too, surfaced as a named `CUSTOM_FN_ARG_DROP` diagnostic on `resolveKeyframes`'s `diagnostics` channel — never a silent `NaN`.
219
224
 
220
225
  Covered by the three focused Vitest files in `test/resolve/` (the
221
226
  `if(supports)`/`if(media)` pass, the element-aware
@@ -256,11 +261,11 @@ The default transform applies interpolated values to `element.style` for each ta
256
261
  - Math expressions (`calc(100% - 10px)`)
257
262
  - Any `key: value` pair parseable as a CSS value, function, or list thereof
258
263
 
259
- The parser uses [`@mkbabb/parse-that`](https://github.com/mkbabb/parse-that) and [`@mkbabb/value.js`](https://github.com/mkbabb/value.js) for CSS value parsing. All exported parse functions are memoized.
264
+ The parser consumes [`@mkbabb/value.js/css`](https://github.com/mkbabb/value.js) for CSS grammar and typed parse results. Keyframes does not carry a second parser dependency or consume Value's package root.
260
265
 
261
266
  ### Units
262
267
 
263
- Unit parsing and resolution (length, angle, time, percentage, color, and container-query units) are handled by [`@mkbabb/value.js`](https://github.com/mkbabb/value.js). `ValueUnit`, `FunctionValue`, and `ValueArray` are the three token shapes; all define `toString()`, `valueOf()`, and `lerp()`. Computed container units are resolved against the measured layout epoch; consumers that change the containing layout must call `bumpLayoutEpoch()` before sampling again so cached conversions are invalidated.
268
+ Unit parsing and resolution (length, angle, time, percentage, color, and container-query units) are handled through Value 4's rootless capability entries. Parsed values use immutable structural `CssScalar`, `CssList`, and `CssCall` nodes; parsing returns an explicit result rather than mutable token objects. Computed container units are resolved against the measured layout epoch; consumers that change the containing layout must call `bumpLayoutEpoch()` before sampling again so cached conversions are invalidated.
264
269
 
265
270
  ## `AnimationGroup`
266
271
 
@@ -272,17 +277,23 @@ group.setTargets(element);
272
277
  group.play();
273
278
  ```
274
279
 
275
- Three blend modes:
280
+ Three composition operators:
276
281
 
277
282
  - **`replace`**: highest `zIndex` wins (default)
278
283
  - **`add`**: numeric values accumulate
279
- - **`weighted`**: linear interpolation by `weight` (0–1)
284
+ - **`accumulate`**: numeric values accumulate across repeated composition
285
+
286
+ Replacement and composition are orthogonal to the layer's `weight` (0–1). A
287
+ static `weight` produces a linear blend; `weightSpring` lets the same scalar be
288
+ driven by the group's spring-transition API.
280
289
 
281
290
  Managed children are paused and resumed by the group clock: pause captures the
282
291
  last rAF timestamp, resume clears the managed pause directly (never by calling a
283
292
  child's public `resume()`), and settling releases the child from group ownership.
284
293
 
285
- Layer configuration per animation: `zIndex`, `weight`, `blendMode`, `enabled`, `properties` (whitelist). Property whitelisting enables effect layering—one layer animates position, another animates opacity.
294
+ Layer configuration per animation: `zIndex`, `op`, `weight`, `weightSpring`,
295
+ `enabled`, `properties` (whitelist). Property whitelisting enables effect
296
+ layering—one layer animates position, another animates opacity.
286
297
 
287
298
  The group manages its own `requestAnimationFrame` loop and marks child animations as `managed`.
288
299
 
@@ -290,7 +301,7 @@ The group manages its own `requestAnimationFrame` loop and marks child animation
290
301
 
291
302
  ## Presets
292
303
 
293
- 30+ ready-to-use animations in `src/animation/presets/`. 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:
304
+ 30+ ready-to-use animations in `src/animation/presets/`. All return `CSSKeyframesAnimation` instances and accept optional `InputAnimationOptions`. Each builds a `CSSKeyframesAnimation` with Value's parser/color graph, so the presets ride the heavy dynamic boundary (the `presets` namespace on `loadAnimationEngine()`) rather than the parser-free static barrel:
294
305
 
295
306
  ```ts
296
307
  import { loadAnimationEngine } from "@mkbabb/keyframes.js";
@@ -307,15 +318,15 @@ anim.play();
307
318
 
308
319
  keyframes.js's authoring object **is** parsed CSS `@keyframes`. That one fact opens a loop no other engine can close:
309
320
 
310
- 1. **Ingest** — read the live web's CSS (`@keyframes` in a stylesheet, or a *running* CSS animation) straight into a kf `CSSKeyframesAnimation`.
321
+ 1. **Ingest** — read the live web's CSS (`@keyframes` in a stylesheet, or a _running_ CSS animation) straight into a kf `CSSKeyframesAnimation`.
311
322
  2. **Drive** — run it through the engine: physics-shaped springs, perceptual `oklab` color, scroll-driven progress, weighted blending.
312
- 3. **Compile** — emit the result **back** to zero-runtime CSS. Three sibling emitters run the SAME parser *backward* over the same data model (`format.ts` is `keyframes.ts` in reverse): [`compileToCSS`](#compile--the-parser-run-backward) (plain `@keyframes`), [`compileToViewTransition`](#compiletoviewtransition) (the `::view-transition-*` pseudo tree), and [`compileToEntry`](#compiletoentry) (`@starting-style`/`allow-discrete` entry-exit).
323
+ 3. **Compile** — emit the result **back** to zero-runtime CSS. Three sibling emitters run the SAME parser _backward_ over the same data model (`format.ts` is `keyframes.ts` in reverse): [`compileToCSS`](#compile--the-parser-run-backward) (plain `@keyframes`), [`compileToViewTransition`](#compiletoviewtransition) (the `::view-transition-*` pseudo tree), and [`compileToEntry`](#compiletoentry) (`@starting-style`/`allow-discrete` entry-exit).
313
324
 
314
- 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()`.
325
+ 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()`.
315
326
 
316
327
  ### Ingest — read the live web's CSS
317
328
 
318
- 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.
329
+ 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.
319
330
 
320
331
  ```ts
321
332
  const { fromStyleSheets, fromLiveAnimations, adoptRunning } =
@@ -348,8 +359,13 @@ const { animation } = await adoptRunning(element, { animationName: "spin" });
348
359
  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).
349
360
 
350
361
  ```ts
351
- const { parseScrollCSS, roundTripScrollCSS, createScrollScene, driveScrollCSS, pinCSS } =
352
- await loadAnimationEngine();
362
+ const {
363
+ parseScrollCSS,
364
+ roundTripScrollCSS,
365
+ createScrollScene,
366
+ driveScrollCSS,
367
+ pinCSS,
368
+ } = await loadAnimationEngine();
353
369
 
354
370
  // PARSE the author grammar into typed options — verbatim, no DOM resolution:
355
371
  const opts = parseScrollCSS(`
@@ -372,7 +388,7 @@ const driven = driveScrollCSS(opts, element, { scrub: 0.2 });
372
388
  driven.backend; // "native" or "js"
373
389
 
374
390
  // pinCSS — synthesize the position:sticky pin a scroll-pinned scene needs:
375
- pinCSS(); // => "position: sticky; top: 0px;"
391
+ pinCSS(); // => "position: sticky; top: 0px;"
376
392
  pinCSS({ top: 24 }); // => "position: sticky; top: 24px;"
377
393
  ```
378
394
 
@@ -386,7 +402,9 @@ pinCSS({ top: 24 }); // => "position: sticky; top: 24px;"
386
402
  const { CSSKeyframesAnimation, compileToCSS } = await loadAnimationEngine();
387
403
 
388
404
  const fade = new CSSKeyframesAnimation({ duration: 600 })
389
- .fromString(`from { background-color: #c462d8; } to { background-color: #e85252; }`)
405
+ .fromString(
406
+ `from { background-color: #c462d8; } to { background-color: #e85252; }`,
407
+ )
390
408
  .setTargets(element);
391
409
 
392
410
  const { css, eligible, refusals } = await compileToCSS([fade]);
@@ -405,14 +423,14 @@ const { css, eligible, refusals } = await compileToCSS([fade]);
405
423
 
406
424
  **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:
407
425
 
408
- | Refusal reason | What it proves | The faithful path |
409
- |---|---|---|
410
- | `weighted-blend` | no `animation-composition` twin exists | JS `AnimationGroup` |
411
- | `custom-renderer` | a closure cannot be CSS | JS playback |
412
- | `perceptual-oklab` | the oklab densify exceeds the ΔE band | JS playback (true perceptual lerp) |
413
- | `computed-unit-drift` | the narrow case where verbatim emit would drift | JS playback |
426
+ | Refusal reason | What it proves | The faithful path |
427
+ | --------------------- | ----------------------------------------------- | ---------------------------------- |
428
+ | `weighted-blend` | no `animation-composition` twin exists | JS `AnimationGroup` |
429
+ | `custom-renderer` | a closure cannot be CSS | JS playback |
430
+ | `perceptual-oklab` | the oklab densify exceeds the ΔE band | JS playback (true perceptual lerp) |
431
+ | `computed-unit-drift` | the narrow case where verbatim emit would drift | JS playback |
414
432
 
415
- 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`.
433
+ 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).
416
434
 
417
435
  > The snippets in this section are reached through `loadAnimationEngine()` and run against the built `dist/`; the executable examples are covered by the test suite.
418
436
 
@@ -428,15 +446,15 @@ A spring keyframed across **multiple** declared stops is compositor-eligible too
428
446
 
429
447
  keyframes.js targets a modern-web Baseline and documents the tier of every platform facility it leans on:
430
448
 
431
- | Facility | Baseline tier | Behavior |
432
- |---|---|---|
433
- | `prefers-reduced-motion` | Widely available | Native `matchMedia`; SSR-safe no-op off-DOM |
434
- | `scheduler.yield()` | Newly available | Feature-detected; falls back to a `MessageChannel` macrotask (≤20 LOC) |
435
- | WAAPI `linear()` springs | Newly available | Feature-detected; the rAF spring path is the default fallback |
436
- | `Element.animate()` (WAAPI) | Widely available | Opt-out via `useWAAPI: false` |
437
- | CSS `if()` / `@function` | Limited availability (Chromium) | kf resolves both in JS at parse/bind time — see [The emerging-CSS resolver](#the-emerging-css-resolver) |
449
+ | Facility | Baseline tier | Behavior |
450
+ | --------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------- |
451
+ | `prefers-reduced-motion` | Widely available | Native `matchMedia`; SSR-safe no-op off-DOM |
452
+ | `scheduler.yield()` | Newly available | Feature-detected; falls back to a `MessageChannel` macrotask (≤20 LOC) |
453
+ | WAAPI `linear()` springs | Newly available | Feature-detected; the rAF spring path is the default fallback |
454
+ | `Element.animate()` (WAAPI) | Widely available | Opt-out via `useWAAPI: false` |
455
+ | CSS `if()` / `@function` | Limited availability (Chromium) | kf resolves both in JS at parse/bind time — see [The emerging-CSS resolver](#the-emerging-css-resolver) |
438
456
 
439
- **Tree-shaking — the value.js boundary.** The package is `"sideEffects": false` and splits along a static/dynamic boundary. The light physics/interpolation engines — `SpringProgress`, `SmoothProgress`, `NumericAnimation`, `ElementMorph`, the `Timeline` family, `RAFPlayback`, and the spring-stop helpers — carry **zero** static import edge to `@mkbabb/value.js`. A consumer that imports only these never pulls value.js (or the heavy CSS-keyframe parser) into its graph; the heavy engine (`KeyframesAnimation`, `CSSKeyframesAnimation`, `AnimationGroup`) is reached only through `loadAnimationEngine()`'s dynamic `import()`. `npm run proof:publish` verifies both sides of this boundary: it bundles every LIGHT entry from source, then bundles the published `dist/keyframes.js` as a downstream consumer and fails if either eager graph carries value.js, parse-that, or a statically inlined engine class. (Deliberately no prose kB figure here: the check floors the LIGHT edge's *composition* — zero value.js, zero engine — not a byte count.)
457
+ **Tree-shaking — the Value boundary.** The package is `"sideEffects": false` and splits along a static/dynamic boundary. The light physics/interpolation engines — `SpringProgress`, `SmoothProgress`, `NumericAnimation`, `ElementMorph`, the `Timeline` family, `RAFPlayback`, and the spring-stop helpers — share only the rootless `@mkbabb/value.js/math` leaf. They do not pull Value's CSS parser, color system, or Keyframes' heavy engine into the eager graph. The heavy engine (`KeyframesAnimation`, `CSSKeyframesAnimation`, `AnimationGroup`) is reached through `loadAnimationEngine()`'s dynamic `import()` or the explicit `./engine` entry.
440
458
 
441
459
  **Reduced motion.** Both the light and heavy engines honor `prefers-reduced-motion: reduce`. Opt in per surface:
442
460
 
@@ -452,9 +470,9 @@ Off-DOM (SSR / Node) the check is a no-op and animations proceed normally.
452
470
 
453
471
  The library also ships general-purpose interpolation primitives, decoupled from CSS and the DOM. These compose into a pipeline: `timeline → progress → interpolator → values → apply`.
454
472
 
455
- 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:
473
+ Everything in this section lives on the **light static barrel** — `import { NumericAnimation, SpringProgress, … } from "@mkbabb/keyframes.js"` — and carries only Value's rootless `/math` leaf, never its parser/color graph (see [tree-shaking](#baseline-tree-shaking--reduced-motion)). Two conventions hold throughout:
456
474
 
457
- - **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")`.
475
+ - **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")`.
458
476
  - **Every snippet executes.** Each example below runs against the built package in CI; `// =>` comments are asserted results, not aspirations.
459
477
 
460
478
  ### `NumericAnimation`
@@ -492,7 +510,7 @@ Exponential smoothing for progress values. Frame-rate independent via `tickDt(dt
492
510
  const smooth = new SmoothProgress({ damping: 0.15 });
493
511
  smooth.setTarget(1);
494
512
  smooth.tickDt(16.7); // one frame step — asymptotically approaches the target
495
- smooth.snap(); // instantly converge
513
+ smooth.snap(); // instantly converge
496
514
  smooth.current; // => 1
497
515
 
498
516
  // Managed — the smoother owns a rAF loop until it settles:
@@ -515,7 +533,10 @@ morph.apply(element, 0.5); // writes transform + transformOrigin at progress 0.5
515
533
  // Managed playback — feed it a spring for the canonical overshoot
516
534
  const springy = new ElementMorph(sourceEl, targetEl, {
517
535
  duration: 250,
518
- timingFunction: springTimingFunction({ response: 0.4, dampingFraction: 0.7 }),
536
+ timingFunction: springTimingFunction({
537
+ response: 0.4,
538
+ dampingFraction: 0.7,
539
+ }),
519
540
  });
520
541
  await springy.play(element);
521
542
  ```
@@ -549,6 +570,7 @@ manual.tick(); // => 0.25
549
570
  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).
550
571
 
551
572
  Subclasses:
573
+
552
574
  - **`KeyframesScrollTimeline`** — scroll position → progress. `threshold` sets viewport fraction for full progress (default 0.35). Injectable `getScrollY`/`getViewportHeight`.
553
575
  - **`ManualTimeline`** — externally set value → progress. Smoothing off by default.
554
576
 
@@ -562,7 +584,7 @@ A live-target spring tracker — the physics core under [`drag`](#drag--draggabl
562
584
 
563
585
  ```ts run
564
586
  const spring = new SpringProgress({ response: 0.5, dampingFraction: 0.86 });
565
- spring.target = 1; // re-seat the closed form — continuous, no jump
587
+ spring.target = 1; // re-seat the closed form — continuous, no jump
566
588
  spring.tickDt(16.7); // advance one frame (milliseconds); returns the new value
567
589
  spring.settled; // => false
568
590
 
@@ -575,7 +597,10 @@ spring.target = 0.5;
575
597
  spring.stop();
576
598
 
577
599
  // The time-based surface (Motion's idiom): perceptual duration + bounce
578
- const bouncy = SpringProgress.fromDuration({ visualDuration: 0.4, bounce: 0.3 });
600
+ const bouncy = SpringProgress.fromDuration({
601
+ visualDuration: 0.4,
602
+ bounce: 0.3,
603
+ });
579
604
  bouncy.settled; // => true
580
605
  ```
581
606
 
@@ -643,7 +668,10 @@ delay.delays(5); // => [100, 50, 0, 50, 100]
643
668
  delay(0, 5); // => 100
644
669
 
645
670
  // Reshape the distribution with an easing (resolved up front):
646
- const eased = stagger(4, { each: 100, ease: await resolveEasing("easeOutCubic") });
671
+ const eased = stagger(4, {
672
+ each: 100,
673
+ ease: await resolveEasing("easeOutCubic"),
674
+ });
647
675
  eased(3, 4); // => 300
648
676
  ```
649
677
 
@@ -660,7 +688,10 @@ await flip(card, () => card.classList.toggle("expanded"), { duration: 200 });
660
688
  // Shared-element FLIP — animate `a` onto `b`'s rect; springs welcome:
661
689
  await flipShared(a, b, {
662
690
  duration: 200,
663
- timingFunction: springTimingFunction({ response: 0.3, dampingFraction: 0.8 }),
691
+ timingFunction: springTimingFunction({
692
+ response: 0.3,
693
+ dampingFraction: 0.8,
694
+ }),
664
695
  });
665
696
  ```
666
697
 
@@ -713,16 +744,18 @@ const fade = new CSSKeyframesAnimation({ duration: 300 })
713
744
  .fromString(`from { opacity: 0; } to { opacity: 1; }`)
714
745
  .setTargets(box);
715
746
  const slide = new CSSKeyframesAnimation({ duration: 400 })
716
- .fromString(`from { transform: translateX(-100px); } to { transform: translateX(0); }`)
747
+ .fromString(
748
+ `from { transform: translateX(-100px); } to { transform: translateX(0); }`,
749
+ )
717
750
  .setTargets(card);
718
751
 
719
752
  const seq = new Sequence()
720
- .add(fade) // auto-append at 0
753
+ .add(fade) // auto-append at 0
721
754
  .add(slide, "-=100"); // overlap the previous segment by 100ms
722
755
 
723
756
  seq.duration; // => 600
724
- seq.seek(300); // scrub — master playhead → each child's local clock
725
- await seq.play(); // the rAF transport drives the SAME map: play ≡ seek
757
+ seq.seek(300); // scrub — master playhead → each child's local clock
758
+ await seq.play(); // the rAF transport drives the SAME map: play ≡ seek
726
759
  seq.timeScale(2).repeat(2).yoyo(); // transport persists across plays
727
760
  ```
728
761
 
@@ -730,11 +763,11 @@ Positions: a number (absolute ms), `"+=n"` / `"-=n"` (relative to the insertion
730
763
 
731
764
  **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.
732
765
 
733
- | Web Animations Level 2 concept | keyframes.js surface |
734
- | --- | --- |
735
- | `GroupEffect` (parallel children) | [`AnimationGroup`](#animationgroup) |
736
- | `SequenceEffect` / proposed `EffectTiming` `align: sequence` | `Sequence` auto-append |
737
- | `EffectTiming` `align: start` | `Sequence` `at: 0` |
766
+ | Web Animations Level 2 concept | keyframes.js surface |
767
+ | ------------------------------------------------------------ | ----------------------------------- |
768
+ | `GroupEffect` (parallel children) | [`AnimationGroup`](#animationgroup) |
769
+ | `SequenceEffect` / proposed `EffectTiming` `align: sequence` | `Sequence` auto-append |
770
+ | `EffectTiming` `align: start` | `Sequence` `at: 0` |
738
771
 
739
772
  ### `viewTransition`
740
773
 
@@ -743,7 +776,9 @@ The LIGHT View-Transitions dispatch: mutate the DOM behind a native View Transit
743
776
  ```ts run
744
777
  // Off-platform (no `document.startViewTransition`, no shared pairs) it degrades
745
778
  // to a bare immediate mutation — backend queryable SYNCHRONOUSLY at dispatch:
746
- const vt = viewTransition(() => box.classList.add("open"), { types: ["forward"] });
779
+ const vt = viewTransition(() => box.classList.add("open"), {
780
+ types: ["forward"],
781
+ });
747
782
  vt.backend; // => "immediate"
748
783
  await vt.finished; // never rejects — a skipped/aborted transition settles cleanly
749
784
  ```
@@ -755,14 +790,22 @@ Options: `types` (typed same-doc VT), `shared` (`[from, to]` `flipShared` fallba
755
790
  The round-trip engine pointed at native View Transitions: compile a **name-keyed role spec** to a PURE, ZERO-RUNTIME CSS artifact over the `::view-transition-*` pseudo tree (HEAVY — reached via `loadAnimationEngine()`). Each name's `old`/`new` get a full kf `@keyframes` block + `animation` shorthand (springs → `linear()`); `::view-transition-group(name)` gets a **timing-only** override (duration + timing-function, never `animation-name` — the UA's rect-morph keyframes ARE the free zero-runtime FLIP), so the group stays temporally coherent with the tracks. Non-round-trippable shapes REFUSE with a named reason (the CC-3 four ∪ `vt-scroll-grammar` / `vt-element-scoped-computed` / `vt-snapshot-inapplicable` / `vt-name-collision`).
756
791
 
757
792
  ```ts run
758
- const { CSSKeyframesAnimation, compileToViewTransition } = await loadAnimationEngine();
793
+ const { CSSKeyframesAnimation, compileToViewTransition } =
794
+ await loadAnimationEngine();
759
795
 
760
796
  const out = new CSSKeyframesAnimation({ duration: 300 });
761
- out.fromString(`@keyframes o { from { opacity: 1 } to { opacity: 0; transform: scale(0.9) } }`);
797
+ out.fromString(
798
+ `@keyframes o { from { opacity: 1 } to { opacity: 0; transform: scale(0.9) } }`,
799
+ );
762
800
  const enter = new CSSKeyframesAnimation({ duration: 300 });
763
- enter.fromString(`@keyframes n { from { opacity: 0; transform: scale(1.05) } to { opacity: 1 } }`);
764
-
765
- const vt = await compileToViewTransition({ hero: { old: out, new: enter } }, { types: ["forward"] });
801
+ enter.fromString(
802
+ `@keyframes n { from { opacity: 0; transform: scale(1.05) } to { opacity: 1 } }`,
803
+ );
804
+
805
+ const vt = await compileToViewTransition(
806
+ { hero: { old: out, new: enter } },
807
+ { types: ["forward"] },
808
+ );
766
809
  vt.names; // => ["hero"]
767
810
  vt.css.includes("::view-transition-group(hero)"); // => true
768
811
  vt.css.includes("animation-name"); // => false // the group override is timing-only
@@ -778,15 +821,20 @@ Modern entry/exit compilation: compile a selector-keyed `{ enter?, exit? }` spec
778
821
  const { CSSKeyframesAnimation, compileToEntry } = await loadAnimationEngine();
779
822
 
780
823
  const enter = new CSSKeyframesAnimation({ duration: 350 });
781
- enter.fromString(`@keyframes en { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: translateY(0) } }`);
782
-
783
- const dialog = await compileToEntry({ ".dialog": { enter } }, { openSelector: "[open]" });
824
+ enter.fromString(
825
+ `@keyframes en { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: translateY(0) } }`,
826
+ );
827
+
828
+ const dialog = await compileToEntry(
829
+ { ".dialog": { enter } },
830
+ { openSelector: "[open]" },
831
+ );
784
832
  dialog.eligible; // => true
785
833
  dialog.css.includes("@starting-style"); // => true
786
834
  dialog.css.includes("display 350ms allow-discrete"); // => true
787
835
  ```
788
836
 
789
- Options: `openSelector` (`".open"` | `"[data-open]"` | `":popover-open"` | `"[open]"`, concatenated onto the base selector), `display` (the open display, default `"block"`), `overlay` (emit `overlay allow-discrete`, default `true`), `printWidth`. The `exit` defaults to `enter` reversed. **Born-open elements RUN the entry at first render** (an `@starting-style` platform semantic — an SSR'd open dialog animates in on load; opt out by not matching the open selector at initial render). Where `transition-behavior` is unsupported the artifact **degrades honestly** — snap-entry, correct end state, no broken half-transition.
837
+ Options: `openSelector` (`".open"` | `"[data-open]"` | `":popover-open"` | `"[open]"`, concatenated onto the base selector), `display` (the open display, default `"block"`), `overlay` (emit `overlay allow-discrete`, default `true`). The `exit` defaults to `enter` reversed. **Born-open elements RUN the entry at first render** (an `@starting-style` platform semantic — an SSR'd open dialog animates in on load; opt out by not matching the open selector at initial render). Where `transition-behavior` is unsupported the artifact **degrades honestly** — snap-entry, correct end state, no broken half-transition.
790
838
 
791
839
  ## Ecosystem & agents
792
840
 
@@ -816,7 +864,7 @@ make ci-linux # node:24-slim container · npm ci → gh-pages → demo:correc
816
864
 
817
865
  It pulls `node:24-slim` (kf's CI Node), mounts the repo at `/workspace`, installs the Playwright browser, builds the demo, and runs the demo gate roster with `KF_REQUIRE_BROWSER=1`, exiting with the container's code. `docker` is the only requirement.
818
866
 
819
- **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).
867
+ **Dependency**: [`@mkbabb/value.js`](https://github.com/mkbabb/value.js), consumed only through its exact `/color`, `/value`, `/css`, `/easing`, `/math`, and `/transform` capability entries.
820
868
 
821
869
  **TypeScript**: `strict: true`, `verbatimModuleSyntax: true`, `target: ES2022`, `moduleResolution: bundler`.
822
870
 
@@ -839,5 +887,4 @@ before pushing.
839
887
  - [CSSOM View Module](https://www.w3.org/TR/cssom-view-1/). W3C. — `getComputedStyle`, unit resolution for relative values.
840
888
  - [Web Animations API](https://www.w3.org/TR/web-animations-1/). W3C. — `Element.animate()`; the WAAPI delegation path.
841
889
  - [`@mkbabb/value.js`](https://github.com/mkbabb/value.js) — CSS value parsing, color spaces, unit conversion, easing functions.
842
- - [`@mkbabb/parse-that`](https://github.com/mkbabb/parse-that) — Parser combinators for the `@keyframes` grammar.
843
- - de Casteljau, P. (1959). *Outillages méthodes calcul*. — The recursive subdivision algorithm used for general Bezier curves.
890
+ - de Casteljau, P. (1959). _Outillages méthodes calcul_. — The recursive subdivision algorithm used for general Bezier curves.
@@ -0,0 +1,79 @@
1
+ import { CubicBezier as e, bezierPresets as t, easing as n, linearEasing as r, steppedEase as i } from "@mkbabb/value.js/easing";
2
+ import { parseTimingFunction as a } from "@mkbabb/value.js/css";
3
+ //#region src/animation/compile/easing/easing-registry.ts
4
+ var o = [
5
+ "easeOutCubic",
6
+ "easeInOutSine",
7
+ "easeInOutCubic",
8
+ "easeInOutQuad",
9
+ "easeInOutExpo",
10
+ "easeInOutCirc",
11
+ "easeOutExpo",
12
+ "smoothStep3",
13
+ "easeInBounce"
14
+ ], s = [
15
+ ...Object.keys(t),
16
+ "ease-in-bounce",
17
+ ...o
18
+ ].map((e) => {
19
+ let t = n(e);
20
+ if (!t.ok) throw Error(`value.js rejected its own easing ${JSON.stringify(e)}: ${t.error.code}`);
21
+ return [e, t.value];
22
+ }), c = new Map(s), l = (e) => {
23
+ let t = e.flatMap(({ output: e, input: t }) => t.length === 2 ? [{
24
+ output: e,
25
+ input: t[0]
26
+ }, {
27
+ output: e,
28
+ input: t[1]
29
+ }] : [{
30
+ output: e,
31
+ input: t[0]
32
+ }]);
33
+ t[0].input ??= 0, t[t.length - 1].input ??= 1;
34
+ let n = t[0].input;
35
+ for (let e = 1; e < t.length; e++) {
36
+ let r = t[e].input;
37
+ r !== void 0 && (t[e].input = Math.max(n, r), n = t[e].input);
38
+ }
39
+ for (let e = 0; e < t.length - 1;) {
40
+ let n = e + 1;
41
+ for (; t[n].input === void 0;) n++;
42
+ let r = t[e].input, i = t[n].input;
43
+ for (let a = e + 1; a < n; a++) t[a].input = r + (i - r) * (a - e) / (n - e);
44
+ e = n;
45
+ }
46
+ return t;
47
+ }, u = (t) => {
48
+ switch (t.kind) {
49
+ case "keyword": {
50
+ let e = n(t.name);
51
+ if (e.ok) return e.value;
52
+ throw TypeError(`Invalid timing function: ${e.error.code}.`);
53
+ }
54
+ case "cubic-bezier": {
55
+ let n = e(t.x1, t.y1, t.x2, t.y2);
56
+ if (n.ok) return n.value;
57
+ throw TypeError(`Invalid cubic-bezier(): ${n.error.code}.`);
58
+ }
59
+ case "steps": {
60
+ let e = i(t.count, t.position);
61
+ if (e.ok) return e.value;
62
+ throw TypeError(`Invalid steps(): ${e.error.code}.`);
63
+ }
64
+ case "linear-function": {
65
+ let e = r(l(t.stops));
66
+ if (e.ok) return e.value;
67
+ throw TypeError(`Invalid linear(): ${e.error.code}.`);
68
+ }
69
+ }
70
+ }, d = (e) => {
71
+ if (typeof e != "string") return e;
72
+ let t = a(e);
73
+ if (t.ok) return u(t.value);
74
+ let n = c.get(e);
75
+ if (n !== void 0) return n;
76
+ throw TypeError(`Unknown timing function "${e}".`);
77
+ };
78
+ //#endregion
79
+ export { s as n, d as t };
@@ -0,0 +1,2 @@
1
+ import { n as e, t } from "./easing-registry-B0rLmOtw.js";
2
+ export { t as resolveTimingFunction, e as timingFunctionEntries };