waapiTimeline (Web Animations API)
The controller that runs an animation tree with the browser's native Web Animations API, manages its state and controls its playback.
waapiTimeline compiles your declarative animation tree into native browser keyframes and plays them using Element.animate().
This allows animations to run on the compositor thread (where possible), resulting in silky smooth performance even when the JavaScript main thread is busy.
Example
import * as a from "@freestylejs/ani-core";
// 1. Define the animation structure.
const myAnimation = a.sequence([
a.ani({ to: { translateX: 100 }, duration: 1 }),
a.ani({ to: { translateY: 100 }, duration: 1 }),
]);
// 2. Create a web-native timeline.
const timeline = a.waapiTimeline(myAnimation);
// 3. Play on a specific DOM element.
const element = document.getElementById("box");
if (element) {
timeline.play(element, {
from: { translateX: 0, translateY: 0 },
repeat: Infinity
});
}Usage & Concepts
Overview
Unlike rafTimeline, which runs frame-by-frame via JavaScript, waapiTimeline uses the browser's native animation engine. This offers significant performance benefits, especially for continuous animations (loops) or on lower-end devices.
Runs natively using the web Animation API, so waapiTimeline does not emit onUpdate events. It reports onStatus changes and run results instead.
The browser's engine drives the animation. The plan value is available through value and valueAt(index).
isWaapiTimeline(value) is a type guard that is true for a timeline made by waapiTimeline.
Key Differences from rafTimeline
| Feature | rafTimeline (JS) | waapiTimeline (Native) |
|---|---|---|
| Engine | JavaScript requestAnimationFrame | Browser Element.animate() |
| Performance | Good, but blocked by main thread | Excellent, often compositor-threaded |
| Events | onUpdate for every frame | onStatus for status changes |
| Properties | Any numeric property | CSS properties only |
| Targets | Bind elements with bind() | play() takes one element or a list |
| Velocity on interruption | Carries over | Position only |
Both engines share the run results, the validation of the config and the reduced motion policy.
Best Practices
- Do use
waapiTimelinefor purely visual UI transitions (fades, slides, scaling) and infinite background loops. - Do use standard
CSSproperty names liketranslateXinstead of shorthands likexto ensure compatibility. - Don't use
waapiTimelineif you need to sync non-DOM elements (like Canvas or WebGL) or if you need to react to value changes every frame.
Timing Functions
Since waapiTimeline compiles to native CSS Keyframes, standard easing functions are compiled directly to CSS strings, while complex physics-based timings are sampled into a series of linear keyframes.
| Timing Function | Compilation Behavior |
|---|---|
linear() | Compiles to linear. Recommended. |
bezier() | Compiles to cubic-bezier(...) when its segment maps 1:1 onto a keyframe interval; if adjacent segments subdivide the interval, it is sampled (60fps) so the curve is not restarted at split points. |
spring() | Sampled from the same closed form as the RAF engine, from the segment start and with no state shared between runs, into high-density linear keyframes (60fps). A spring may settle before its nominal duration; at a duration cap it lands with a jump, as in the RAF engine. |
| User Custom | Sampled, provided the function is stateless (pure function of time) or declares stateful (see Custom Timing Functions). |
Note: Using spring() or subdivided bezier() timings with waapiTimeline will generate a larger number of keyframes to approximate the curve. This is generally performant but significantly more verbose than standard CSS easing.
Compilation cache
Compiling a tree to keyframes is cached per root node, from values and resolver. Playing the same tree again, or on many elements with the same from, reuses the compiled keyframes. Plans with keyframes or durations overrides, and array-shaped from, are not cached.
- Do build the tree once and share it between timelines.
- Reuse the same
resolverobject between calls so the cache can hit.
Several targets
play() accepts one element or a list of elements. Every target gets its own native Animation (timeline.animations), started delay seconds from now plus a per-target stagger offset:
import * as a from "@freestylejs/ani-core";
const timeline = a.waapiTimeline(
a.ani({ to: { opacity: 1, translateY: 0 }, duration: 0.4 })
);
const run = timeline.play(document.querySelectorAll('.card'), {
from: { opacity: 0, translateY: 20 },
delay: 0.2,
stagger: 0.05, // or (index, count) => (count - 1 - index) * 0.05
})from may be a function of the target index. Targets whose from values are equal share the compiled keyframes. The animations use fill: 'forwards', so they keep holding their final values until cancelled; call cancel() / dispose() when the elements are removed.
Results and status
play() returns a Promise<RunResult> that never rejects and settles exactly once per run:
| Result | When |
|---|---|
'ended' | Every animation finished, or finish() was called. |
'interrupted' | A later play() replaced the run. |
'skipped' | The timeline was running and interrupt: false was set. |
'reset' | cancel() / reset() / dispose() stopped the run. |
'disposed' | play() was called after dispose(). |
status is 'IDLE', 'PLAYING', 'PAUSED' or 'ENDED'; onStatus(listener) is called on every change (a throwing listener never affects the others).
Interruptions
Playing again while the timeline is running commits the current styles of every old animation (commitStyles(), skipped for elements that are not rendered) and then cancels it, so the element continues from the value it showed instead of jumping back.
Velocity is not continuous on WAAPI. Only the position is kept. A spring restarts from rest. Use rafTimeline when velocity must carry over.
Reading values
timeline.value (target 0) and timeline.valueAt(index) return the value of a target, computed from the plan at that animation's currentTime (minus its delay, wrapped for repeats, clamped to one run). Computed styles are never parsed. They are null without a run or for an index that does not exist. Options in effect that change the playhead mapping (direction, easing, iterationStart) are not reflected.
Reduced motion
waapiTimeline honors prefers-reduced-motion by default. With the preference on, the policy 'jump' creates the animations and finishes them at once (status ENDED, result 'ended'), and { maxDuration } raises each animation's playbackRate for runs longer than maxDuration. Pass reducedMotion: 'ignore' for essential motion. clock only provides the preference and defaults to the shared clock. See Reduced motion.
import * as a from "@freestylejs/ani-core";
const spinner = a.waapiTimeline(
a.loop(a.ani({ to: { rotate: 360 }, duration: 1 }), Infinity),
{ reducedMotion: "ignore" }
);Endless loops
Only a root loop(child, Infinity) is supported: the child is compiled once and played with iterations: Infinity. Any other tree with an endless loop throws a RangeError from play() that points to the RAF engine. See loop.
Server rendering
waapiTimeline(...).play() needs KeyframeEffect and document.timeline. Call it on the client only (for example in an effect or onMount). See SSR.
API Reference
waapiTimeline(rootNode, options?)
| Name | Type | Description |
|---|---|---|
rootNode | AnimationNode<G> | Root of the animation tree. |
options.reducedMotion | 'jump' | 'ignore' | { maxDuration: number } | (Optional) Policy while the preference is on. Default 'jump'. |
options.clock | { readonly reducedMotion: boolean } | (Optional) Provides the preference. Defaults to the shared defaultClock. |
Members
| Member | Description |
|---|---|
play(targets, config) | Compiles (or reuses cached keyframes) and plays on one element or a list. Returns Promise<RunResult>. |
pause() / resume() | No-op unless PLAYING / PAUSED. |
seek(time) | Seconds, clamped to the duration. Applies to every target and keeps their offsets. |
finish() | Jumps to the end: status ENDED, result 'ended'. Throws for repeat: Infinity. |
reset() / cancel() | Cancels the native animations: status IDLE, result 'reset'. |
dispose() | cancel() and drops the listeners. Further play() resolves 'disposed'. Idempotent. |
disposed | Read-only; true once dispose() ran. |
onStatus(listener) | Called on every status change. Returns an unsubscribe function. |
status | 'IDLE', 'PLAYING', 'PAUSED' or 'ENDED'. |
duration | Seconds of one run, without delay or stagger. |
animations | The native Animation of every target. |
value / valueAt(index) | Plan value of a target, or null. |
play(targets, config)
| Option | Type | Description |
|---|---|---|
from | G | ((index: number) => G) | Start values: a record of CSS properties, or a function of the target index. |
repeat | number | Additional runs. Infinity loops forever. |
delay | number | Seconds before the run starts (finite and >= 0). |
stagger | number | ((index: number, count: number) => number) | Seconds of start offset per target. |
keyframes | Array<G | 'keep'> | Override each ani node's to. |
durations | Array<number | 'keep'> | Override each ani node's duration (seconds). |
resolver | Resolver<Record<string, number>> | Maps values to style declarations. |
effect | KeyframeEffectOptions without duration, iterations and delay | Extra KeyframeEffect options. |
interrupt | boolean | Default true; false resolves 'skipped' while running. |
Invalid input (array from, negative or non-finite delay / stagger offsets, no target) throws synchronously before anything is touched.
Related Components
rafTimeline- The standard JavaScript-based controller.ani- The building block for animations.Dynamic Animations- For creating interactive animations.- Reduced motion - Policies and testing.