@mkbabb/keyframes.js 5.1.0 → 5.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 CHANGED
@@ -43,15 +43,16 @@ Works both in and out of the browser. Anything that touches the DOM (`getCompute
43
43
  ## Project Structure
44
44
 
45
45
  ```
46
- src/animation/ # THE library — engine + every primitive (see src/animation/CLAUDE.md)
47
- demo/ # Vue 3 demo apps (see demo/CLAUDE.md)
46
+ src/animation/ # THE library — engine + every primitive
47
+ demo/ # Vue 3 demo apps
48
48
  test/ # Vitest suites (jsdom)
49
49
  bench/ # Vitest benchmarks
50
50
  scripts/ # CI gates (proof:* scripts) + code generators
51
51
  docs/ # Migration guide, published surface manifest, architecture notes
52
52
  ```
53
53
 
54
- For the authoritative per-file inventory, see [`src/animation/CLAUDE.md`](src/animation/CLAUDE.md).
54
+ Each library zone documents its contract at its owning barrel; the published
55
+ surface and package manifests are the authorities for exports and build shape.
55
56
 
56
57
  ## Animation
57
58
 
@@ -193,6 +194,31 @@ const dAtMid = morph.sampleD(0.5); // the interpolated `d` at t = 0.5
193
194
 
194
195
  Options: `samples` (point count per path; default `64`), plus every `AnimationOptions` key. Both inputs must be non-degenerate path `d` strings (non-zero arc length, ≥ 2 samples) — a degenerate input refuses with a typed `AnimationOptionError`. `MorphSVG.sampleD(t)` reassembles the morphed `d` at any `t`; the per-point coordinates also surface as `--morph-{i}-x`/`--morph-{i}-y` custom properties for direct CSS binding.
195
196
 
197
+ ### The emerging-CSS resolver
198
+
199
+ kf's parser accepts CSS the platform can't animate yet. The `resolve/` zone lowers `if(supports(...))` / `if(media(...))` / `if(style(--custom-prop))` and `@function` calls to concrete values **in JS, at parse/bind time** — so a `@keyframes` block authored against tomorrow's conditional grammar plays correctly **today, in every browser kf runs in**, even though the native CSS features themselves are Chromium-only (`if()` shipped Chrome 137; `@function`, Chrome 139 — neither ships in Firefox or Safari). `env()` sits outside this: it's ordinary CSS the platform has resolved for years, so there's no cross-browser gap for kf to bridge there.
200
+
201
+ This is a **resolve-once, not react-forever** lowering, not a live binding. The element-independent forms (`if(supports)`, `if(media)`, `@function`) resolve once when the keyframes parse; the element-aware forms (`if(style(--p))`, `sibling-index()`, `sibling-count()`) resolve once per `setTargets()`. None of them re-evaluate on a later media-query flip or custom-property write — rebuild the animation to re-resolve.
202
+
203
+ ```ts run
204
+ const { resolveKeyframes } = await loadAnimationEngine();
205
+
206
+ // Author against a condition the browser can't natively evaluate in if() yet —
207
+ // kf resolves it in JS and bakes the concrete branch into the parsed frame.
208
+ // Off-DOM (no CSS.supports), the SSR-safe default deterministically picks `else`:
209
+ const { keyframes } = resolveKeyframes(`
210
+ @keyframes x {
211
+ 0% { color: if(supports(color: lch(0 0 0)): red; else: blue) }
212
+ 100% { color: green }
213
+ }
214
+ `);
215
+ String(keyframes.get("0%")?.color); // => "rgb(0 0 255)"
216
+ ```
217
+
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`.
219
+
220
+ Gated by `npm run proof:emerging-css-resolve` (the `if(supports)`/`if(media)` pass, the element-aware `if(style)`/`sibling-index()`/`sibling-count()` pass, and `@function` call-inlining) — all jsdom-clean, behavior-level; no browser required, because the resolution is kf's JS, not a platform feature.
221
+
196
222
  ## `CSSKeyframesAnimation`
197
223
 
198
224
  An abstraction over `KeyframesAnimation` that parses CSS `@keyframes` into `TemplateAnimationFrame` objects, then adds them to a base `KeyframesAnimation`.
@@ -230,7 +256,7 @@ The parser uses [`@mkbabb/parse-that`](https://github.com/mkbabb/parse-that) and
230
256
 
231
257
  ### Units
232
258
 
233
- 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()`.
259
+ 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.
234
260
 
235
261
  ## `AnimationGroup`
236
262
 
@@ -248,6 +274,10 @@ Three blend modes:
248
274
  - **`add`**: numeric values accumulate
249
275
  - **`weighted`**: linear interpolation by `weight` (0–1)
250
276
 
277
+ Managed children are paused and resumed by the group clock: pause captures the
278
+ last rAF timestamp, resume clears the managed pause directly (never by calling a
279
+ child's public `resume()`), and settling releases the child from group ownership.
280
+
251
281
  Layer configuration per animation: `zIndex`, `weight`, `blendMode`, `enabled`, `properties` (whitelist). Property whitelisting enables effect layering—one layer animates position, another animates opacity.
252
282
 
253
283
  The group manages its own `requestAnimationFrame` loop and marks child animations as `managed`.
@@ -275,7 +305,7 @@ keyframes.js's authoring object **is** parsed CSS `@keyframes`. That one fact op
275
305
 
276
306
  1. **Ingest** — read the live web's CSS (`@keyframes` in a stylesheet, or a *running* CSS animation) straight into a kf `CSSKeyframesAnimation`.
277
307
  2. **Drive** — run it through the engine: physics-shaped springs, perceptual `oklab` color, scroll-driven progress, weighted blending.
278
- 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).
308
+ 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).
279
309
 
280
310
  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()`.
281
311
 
@@ -314,7 +344,7 @@ const { animation } = await adoptRunning(element, { animationName: "spin" });
314
344
  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).
315
345
 
316
346
  ```ts
317
- const { parseScrollCSS, roundTripScrollCSS, createScrollScene, pinCSS } =
347
+ const { parseScrollCSS, roundTripScrollCSS, createScrollScene, driveScrollCSS, pinCSS } =
318
348
  await loadAnimationEngine();
319
349
 
320
350
  // PARSE the author grammar into typed options — verbatim, no DOM resolution:
@@ -332,6 +362,11 @@ roundTripScrollCSS(`.hero { animation-timeline: scroll(root block); }`);
332
362
  const scene = createScrollScene({ range: opts.range, scrub: 0.2 });
333
363
  element.style.opacity = String(scene.progress);
334
364
 
365
+ // DRIVE the complete parsed value through the range scene, optional trigger,
366
+ // and conservative native-vs-JS backend decision in one symmetric entry:
367
+ const driven = driveScrollCSS(opts, element, { scrub: 0.2 });
368
+ driven.backend; // "native" or "js"
369
+
335
370
  // pinCSS — synthesize the position:sticky pin a scroll-pinned scene needs:
336
371
  pinCSS(); // => "position: sticky; top: 0px;"
337
372
  pinCSS({ top: 24 }); // => "position: sticky; top: 24px;"
@@ -341,7 +376,7 @@ pinCSS({ top: 24 }); // => "position: sticky; top: 24px;"
341
376
 
342
377
  ### Compile — the parser run backward
343
378
 
344
- `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**.
379
+ `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**. Two siblings emit from the same substrate for two other target surfaces — [`compileToViewTransition`](#compiletoviewtransition) (the `::view-transition-*` pseudo tree) and [`compileToEntry`](#compiletoentry) (`@starting-style`/`allow-discrete` entry-exit) — both taught under [Beyond CSS](#beyond-css).
345
380
 
346
381
  ```ts
347
382
  const { CSSKeyframesAnimation, compileToCSS } = await loadAnimationEngine();
@@ -383,6 +418,8 @@ When `useWAAPI` is `true` (default), eligible animations run on the compositor t
383
418
 
384
419
  A spring timing function (`springTimingFunction`) carries its CSS `linear()` equivalent, so a WAAPI-delegated spring animation runs the true overshoot/settle curve on the compositor instead of a flattened `linear` ramp — the JS easing and the compositor curve are one solver.
385
420
 
421
+ A spring keyframed across **multiple** declared stops is compositor-eligible too: rather than restart the curve at each stop (WAAPI's one-easing-per-segment model would), kf **densifies** the composite curve into extra keyframe stops fed a single bare `linear` effect easing, so the compositor's piecewise-linear fill still tracks the true multi-segment curve. Gated by `proof:waapi-adaptive-densify`.
422
+
386
423
  ## Baseline, tree-shaking & reduced motion
387
424
 
388
425
  keyframes.js targets a modern-web Baseline and documents the tier of every platform facility it leans on:
@@ -393,8 +430,9 @@ keyframes.js targets a modern-web Baseline and documents the tier of every platf
393
430
  | `scheduler.yield()` | Newly available | Feature-detected; falls back to a `MessageChannel` macrotask (≤20 LOC) |
394
431
  | WAAPI `linear()` springs | Newly available | Feature-detected; the rAF spring path is the default fallback |
395
432
  | `Element.animate()` (WAAPI) | Widely available | Opt-out via `useWAAPI: false` |
433
+ | CSS `if()` / `@function` | Limited availability (Chromium) | kf resolves both in JS at parse/bind time — see [The emerging-CSS resolver](#the-emerging-css-resolver) |
396
434
 
397
- **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()`. This boundary is **gated in CI** by `proof:boundary`, which builds a spring-only entry and fails the build if any light module reintroduces a static value.js edge.
435
+ **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()`. This boundary is **gated in CI** by `proof:boundary`, which builds a spring-only entry from SOURCE and fails the build if any light module reintroduces a static value.js edge. `proof:consume-bundle` re-proves the same claim from the CONSUMER side — it bundles the PUBLISHED `dist/keyframes.js` (value.js/parse-that kept non-external, so any leak must surface) exactly as a downstream app's bundler would, and fails if that eager graph carries a single value.js/parse-that module or a statically-inlined engine class. (Deliberately no prose kB figure here: `proof:consume-bundle` floors the LIGHT edge's *composition* — zero value.js, zero engine — not a byte count, so a specific kB number would be a claim neither gate actually verifies; re-run `npm run proof:consume-bundle` against a fresh build for the current graph, not a number frozen in prose.)
398
436
 
399
437
  **Reduced motion.** Both the light and heavy engines honor `prefers-reduced-motion: reduce`. Opt in per surface:
400
438
 
@@ -694,6 +732,58 @@ Positions: a number (absolute ms), `"+=n"` / `"-=n"` (relative to the insertion
694
732
  | `SequenceEffect` / proposed `EffectTiming` `align: sequence` | `Sequence` auto-append |
695
733
  | `EffectTiming` `align: start` | `Sequence` `at: 0` |
696
734
 
735
+ ### `viewTransition`
736
+
737
+ The LIGHT View-Transitions dispatch: mutate the DOM behind a native View Transition where the platform ships one, and fall back to a `flipShared` shared-element morph (or a bare immediate mutation) everywhere else — behind ONE normalized handle whose `backend` is queryable and whose promises never reject. Feature-detects `startViewTransition` (and its typed-`update` object overload); PRM routes through the ONE `withReducedMotion` gate (mutate directly, settle).
738
+
739
+ ```ts run
740
+ // Off-platform (no `document.startViewTransition`, no shared pairs) it degrades
741
+ // to a bare immediate mutation — backend queryable SYNCHRONOUSLY at dispatch:
742
+ const vt = viewTransition(() => box.classList.add("open"), { types: ["forward"] });
743
+ vt.backend; // => "immediate"
744
+ await vt.finished; // never rejects — a skipped/aborted transition settles cleanly
745
+ ```
746
+
747
+ Options: `types` (typed same-doc VT), `shared` (`[from, to]` `flipShared` fallback pairs — `backend: "flip"`), `duration`/`timingFunction` (the fallback play), `fallback` (`"flip"` | `"none"` | a custom async runner), `respectReducedMotion` (default `true` — PRM snaps to `"immediate"`). The `backend` is `"view-transition"` (native), `"flip"` (the `flipShared` fallback), or `"immediate"` (bare mutate). Its zero-runtime CSS twin is [`compileToViewTransition`](#compiletoviewtransition).
748
+
749
+ ### `compileToViewTransition`
750
+
751
+ 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`).
752
+
753
+ ```ts run
754
+ const { CSSKeyframesAnimation, compileToViewTransition } = await loadAnimationEngine();
755
+
756
+ const out = new CSSKeyframesAnimation({ duration: 300 });
757
+ out.fromString(`@keyframes o { from { opacity: 1 } to { opacity: 0; transform: scale(0.9) } }`);
758
+ const enter = new CSSKeyframesAnimation({ duration: 300 });
759
+ enter.fromString(`@keyframes n { from { opacity: 0; transform: scale(1.05) } to { opacity: 1 } }`);
760
+
761
+ const vt = await compileToViewTransition({ hero: { old: out, new: enter } }, { types: ["forward"] });
762
+ vt.names; // => ["hero"]
763
+ vt.css.includes("::view-transition-group(hero)"); // => true
764
+ vt.css.includes("animation-name"); // => false // the group override is timing-only
765
+ ```
766
+
767
+ Options: `types` (wraps rules in `:active-view-transition-type(...)`), `crossDocument` (prepend `@view-transition { navigation: auto }`), `reducedMotion` (append the PRM `animation: none` block, default `true`), plus every `CompileOptions` key. The consumer assigns `view-transition-name: <name>` to its elements from the returned `names`.
768
+
769
+ ### `compileToEntry`
770
+
771
+ Modern entry/exit compilation: compile a selector-keyed `{ enter?, exit? }` spec to zero-runtime **`@starting-style` + `transition-behavior: allow-discrete`** CSS — the two-endpoint entrance/exit grammar the platform shipped (Chromium 117+/Safari 26). HEAVY (reached via `loadAnimationEngine()`). It is a **declared-endpoint projection** (each animation is a 2-stop transition endpoint pair), emitting the three-rule grammar: a base/closed rule (exit's last frame + `display: none` + the exit transition list), an open rule (enter's last frame + `display` + the entry list), and `@starting-style { <open> { enter's first frame } }`. Asymmetric entry/exit duration+easing ride the two lists; `display`/`overlay <dur> allow-discrete` ride BOTH (`overlay` is inert-but-harmless off the top layer); spring `linear()`s ride verbatim; **color endpoints canonicalize to `oklab()`** so the transition interpolates in kf's default perceptual space natively — NO densify, ZERO intermediate stops (the `@keyframes` `perceptual-oklab` refusal INVERTED to a feature). Non-two-endpoint shapes REFUSE (3 inherited + 6 entry-specific: `entry-multi-keyframe` / `entry-iteration` / `entry-composition` / `entry-scroll-grammar` / `entry-color-space` / `entry-easing-twin`).
772
+
773
+ ```ts run
774
+ const { CSSKeyframesAnimation, compileToEntry } = await loadAnimationEngine();
775
+
776
+ const enter = new CSSKeyframesAnimation({ duration: 350 });
777
+ enter.fromString(`@keyframes en { from { opacity: 0; transform: translateY(8px) } to { opacity: 1; transform: translateY(0) } }`);
778
+
779
+ const dialog = await compileToEntry({ ".dialog": { enter } }, { openSelector: "[open]" });
780
+ dialog.eligible; // => true
781
+ dialog.css.includes("@starting-style"); // => true
782
+ dialog.css.includes("display 350ms allow-discrete"); // => true
783
+ ```
784
+
785
+ 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.
786
+
697
787
  ## Ecosystem & agents
698
788
 
699
789
  - **`llms.txt`** — the agent surface: a machine-readable index of every capability, generated
@@ -0,0 +1,2 @@
1
+ import { t as e } from "./easing-registry-BlbS88NR.js";
2
+ export { e as getTimingFunction };
@@ -1,5 +1,5 @@
1
- import { CSSCubicBezier as e, cssLinear as t, parseLinearStops as n, parseSteps as r, steppedEase as i, timingFunctions as a } from "@mkbabb/value.js";
2
- //#region src/animation/compile/easing-registry.ts
1
+ import { CSSCubicBezier as e, cssLinear as t, parseLinearStops as n, parseSteps as r, steppedEase as i, timingFunctions as a } from "@mkbabb/value.js/easing";
2
+ //#region src/animation/compile/easing/easing-registry.ts
3
3
  var o = /^\s*cubic-bezier\s*\(\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\)\s*$/i, s = /^\s*steps\s*\(/i, c = /^\s*linear\s*\(/i, l = (l) => {
4
4
  if (l == null) return;
5
5
  if (typeof l != "string") return l;