Ani
Core API

rafTimeline (RequestAnimationFrame)

The controller that runs an animation tree frame by frame, manages its state and controls its playback.

The rafTimeline is the execution engine for any animation you create. It takes a root animation node (like a sequence or parallel block), computes the animation state on every frame of a clock, and notifies subscribers through onUpdate.

Example

import * as a from "@freestylejs/ani-core";

// 1. Define the animation structure.
// TypeScript infers the data shape `G` as { opacity: number, x: number }
const myAnimation = a.sequence([
  a.ani({ to: { opacity: 1, x: 0 }, duration: 1 }),
  a.ani({ to: { opacity: 1, x: 100 }, duration: 2 }),
]);

// 2. Create a reusable timeline instance from the structure.
const myTimeline = a.rafTimeline(myAnimation);

// 3. Listen for updates to apply the animated values to your UI.
const unsubscribe = myTimeline.onUpdate(({ state, status }) => {
  // `state` is strongly typed as { opacity: number, x: number }
  console.log(`Opacity: ${state.opacity}, X: ${state.x} (${status})`);
});

// 4. Play the animation from a starting state.
myTimeline.play({ from: { opacity: 0, x: 0 } });

// 5. Release the timeline when it is no longer needed.
// myTimeline.dispose();

Usage & Concepts

Overview

The timeline separates the animation definition (the node tree) from its execution and values. When you call play(), it compiles the tree into per-property lanes once, then advances them from the clock.

  • Per-frame cost depends on the number of animated properties, not on how many segments the tree has or how many already finished.
  • Subscribers of one notification receive the same state object. Treat it as read-only.
  • One notification per frame. update only computes; bound styles are written and onUpdate listeners run in the clock's commit phase, after every timeline on the clock has computed. The frame a run ends notifies once, with ENDED and the final value; a frame that wraps a repeat notifies once with the post-wrap value. play(), seek() and reset() notify synchronously.
  • Errors thrown by an onUpdate callback do not affect other callbacks or the timeline. They are rethrown asynchronously (they surface as uncaught errors).

Lifecycle

status is one of four values:

StatusMeaningEntered by
IDLENothing is playing and no value exists.Creation, reset()
PLAYINGSubscribed to the clock and advancing.play(), resume()
PAUSEDHolding its value, not on the clock.pause(), seek()
ENDEDReached the end (after all repeats). Emitted exactly once per run.Natural end
  • pause() only acts on PLAYING and resume() only acts on PAUSED. In any other status they do nothing.
  • seek(time) clamps time to [0, duration], pauses a PLAYING or ENDED timeline at that time and notifies once. Call resume() to continue from there. Calling seek() before the first play() does nothing.
  • reset() returns to IDLE, drops the value (value is null) and restores the base duration. Subscribers receive one IDLE notification with an empty state. It takes no arguments.
  • dispose() stops the timeline for good: it leaves the clock, removes every onUpdate callback, and play() / resume() become no-ops. It is idempotent.

Binding styles

bind(target, options?) writes the timeline's value to target.style (an element or any { style }) on every notification, so you do not need an onUpdate callback just to set styles.

import * as a from "@freestylejs/ani-core";

const myTimeline = a.rafTimeline(a.ani({ to: { x: 100 }, duration: 1 }));
const element = document.createElement("div");
const other = document.createElement("div");

const unbind = myTimeline.bind(element)
// optional: decide which declaration a value becomes
myTimeline.bind(other, {
    resolver: { x: (v) => ({ key: 'left', value: `${v}px` }) },
})
  • The value goes through createStyleSheet; resolver is the mapping from animated values to style declarations.
  • Writes happen in the commit phase, before the onUpdate listeners of the same notification, and only for declarations whose value changed since that binding's previous write.
  • A timeline that already has a value writes it immediately; otherwise the first write happens at the next notification.
  • An invalid target (not an element or an object with a style object) throws a TypeError synchronously.
  • The returned function unbinds (idempotent) and keeps the written styles. dispose() drops all bindings.
  • Positional (array) values cannot be styled: the first write reports a TypeError asynchronously and the binding is dropped.
  • A write that throws is isolated per binding and rethrown asynchronously.

Validation

Malformed input throws synchronously from play() and leaves the timeline untouched. Nothing can throw later inside the clock.

  • A property animated by the tree is missing from from.
  • Array and record shapes are mixed (array to with a record from, or the reverse), or lengths differ.
  • A record timing has no function for an animated property.
  • from, to or velocity contain a non-finite number.
  • A segment duration is negative or not finite. delay is negative or not finite.
  • keyframes or durations do not match the number of ani nodes.

Interrupting a running animation

Calling play() on a PLAYING timeline interrupts it. Pass interrupt: false in the config to ignore the call instead; the returned promise then resolves 'skipped'. play() takes the config only: an extra argument throws a TypeError.

  • Velocity carries over. Without config.velocity, the new run starts from the current velocity, so springs retarget without a visible kink.
  • Pass velocity: { x: 0 } (same shape as from, partial for records) to start from rest.
  • play() from IDLE, PAUSED or ENDED starts from zero velocity.

Values and velocity

  • value is a frozen snapshot that is stable until the next frame. It never aliases the from object you passed to play(). It is null before the first play() and after reset().
  • velocity is the per-property velocity in units per second: the spring's own velocity for a timing.spring, otherwise the finite difference of the last frame. It is zeros unless the status is PLAYING, and null before the first advanced frame.
  • config is the config of the current run, or null.

Run result

play() returns a Promise<RunResult> that never rejects and resolves exactly once per run, synchronously at the moment the run ends:

ResultWhen
'ended'The run, repeats included, completed.
'interrupted'Another play() replaced it.
'skipped'interrupt: false on a PLAYING timeline.
'reset'reset() was called.
'disposed'dispose() was called, or play() on a disposed timeline.

An invalid config still throws synchronously before anything changes; no promise is created then. isRafTimeline(value) is a type guard that is true for a timeline and for the facade returned by createTimelineController.

Repeat, delay and time

  • repeat is the number of additional runs (Infinity for endless). The frame overshoot at the end of a run is carried into the next one, so repeats do not drift.
  • delay is in seconds (finite and >= 0) and holds the animation before the first frame.
  • Progress per frame follows the clock's lag smoothing: real elapsed time up to 0.5 s, one ordinary frame after a longer suspension. See clock.
  • An animation is considered finished within 1e-9 seconds of its end (END_TOLERANCE).

Progress-linked time

drive(progress, config) makes the time follow an external progress value (scroll position, a scrubbed gesture) instead of the clock. It starts a run from config.from (keyframes and durations are honored; repeat, delay and velocity are ignored) and replaces the current run, so a pending play() promise resolves 'interrupted'.

import * as a from "@freestylejs/ani-core";

const hero = document.querySelector<HTMLElement>(".hero")!
const reveal = a.rafTimeline(a.ani({ to: { opacity: 1, translateY: 0 }, duration: 1 }))
reveal.bind(hero)
const stop = reveal.drive(() => Math.min(1, window.scrollY / 400), { from: { opacity: 0, translateY: 40 } })
  • progress() is called once synchronously for the first value (targets written, listeners notified once) and then once per frame in the clock's read phase. The time is clamp(progress(), 0, 1) * duration.
  • Bound targets are written and listeners notified only in frames where the time changed. The status stays PLAYING and the run never ends by itself (reaching 1 does not emit ENDED).
  • velocity is the time-derivative of the values in units per second, and zero after a frame in which the progress did not change.
  • A non-finite progress keeps the previous time and is reported once, asynchronously.
  • Reduced motion does not apply: the user controls the motion.
  • The returned function stops driving (idempotent): the timeline leaves the clock and becomes PAUSED at the current time, and resume() plays forward from there. play(), seek(), reset() and dispose() stop driving too.
  • Invalid config, or a progress that is not a function, throws synchronously and changes nothing.

Reduced motion

rafTimeline honors prefers-reduced-motion by default. With the preference on, the policy 'jump' completes every run at once: the value is the end state, bound targets are written, listeners are notified once with ENDED and the promise resolves 'ended'. The clock is not subscribed. The preference is read once at the start of each play().

  • reducedMotion: { maxDuration } plays a longer run faster instead; duration still reports the plan's.
  • reducedMotion: 'ignore' keeps the normal behavior, for essential motion.
  • drive() is not affected: the user controls the motion.
import * as a from "@freestylejs/ani-core";

const progress = a.rafTimeline(
  a.ani({ to: { width: 100 }, duration: 1 }),
  { reducedMotion: "ignore" }
);

See Reduced motion.

Same-property overlap

When several segments animate the same property at overlapping times (parallel, stagger, nested trees), the segment that started most recently produces the value. If two start together, the later one in declaration order wins.

  • Each segment's from is the property's value at the segment's start time, captured once. It is never a moving target.
  • Times within 1e-9 s of each other are one instant: sums taken in different orders (a loop's i * period, a sequence's durations added one by one) leave the same instant a few ulps apart, and the plan stores one value per instant. A zero-length segment applies at its start time, so a time sampled at that instant shows its value. rafTimeline and waapiTimeline follow the same rule.
  • The rule is identical for record and array shapes.

Best Practices

  • Do create one timeline per independent animation and reuse the same node tree for many timelines.
  • Do call dispose() for timelines you create when their owner goes away. Bindings dispose only what they create.
  • Don't create a new timeline inside a render loop. Create it once and store it.
  • Don't call update(dt) yourself outside tests. The clock drives it.

API Reference

Factory

NameTypeDescription
rootNodeAnimationNode<G>Root of the animation tree.
options.clockAnimationClockInterface(Optional) Drives the timeline. Defaults to the shared defaultClock. A bare clock in place of the options object throws a TypeError: pass { clock }.
options.reducedMotion'jump' | 'ignore' | { maxDuration: number }(Optional) Policy while the user prefers reduced motion. Default 'jump'.

play(config)

OptionTypeDescription
fromAniGroup<G>Start values. Every animated property must be present. Copied at play().
repeatnumberAdditional runs. Infinity loops forever.
delaynumberSeconds to wait before starting (finite and >= 0).
keyframesArray<G | 'keep'>Override each ani node's to. See Dynamic Animations.
durationsArray<number | 'keep'>Override each ani node's duration (seconds).
velocityPartial<G>Initial velocity (units per second) that seeds a timing.spring.
interruptbooleanDefault true. With false, a PLAYING timeline is left untouched and the promise resolves 'skipped'.

Members

MemberDescription
status'IDLE' | 'PLAYING' | 'PAUSED' | 'ENDED'.
durationTotal duration in seconds of the current plan (reflects durations overrides).
configThe config of the current run, or null.
value / velocityFrozen value snapshot and per-property velocity, or null.
drive(progress, config)Link the time to an external progress value; returns a stop function. See Progress-linked time.
pause() / resume()Pause a PLAYING timeline, resume a PAUSED one.
seek(time)Jump to time seconds and pause.
reset()Return to IDLE.
dispose()Stop for good and release everything.
disposedRead-only; true once dispose() ran.
bind(target, options?)Write the value to target.style on every notification. Returns an unbind function.
onUpdate(cb)Subscribe to { state, status } (commit phase). Returns an unsubscribe function.

Type Definitions

type TimelineStatus = 'IDLE' | 'PLAYING' | 'PAUSED' | 'ENDED'

type OnUpdateCallback<G extends Groupable> = (current: {
  state: AniGroup<G>   // shared by all callbacks of one notification
  status: TimelineStatus
}) => void

interface RafTimelineConfig<G extends Groupable> {
  from: AniGroup<G>
  repeat?: number
  delay?: number // seconds
  keyframes?: Array<G | 'keep'>
  durations?: Array<number | 'keep'>
  velocity?: Partial<G>
  interrupt?: boolean // default true
}

type RunResult = 'ended' | 'interrupted' | 'skipped' | 'reset' | 'disposed'

function rafTimeline<G extends Groupable>(
  rootNode: AnimationNode<G>,
  options?: {
    clock?: AnimationClockInterface
    reducedMotion?: 'jump' | 'ignore' | { maxDuration: number }
  }
): RafTimeline<G>

function isRafTimeline(value: unknown): value is RafTimeline<Groupable>
  • ani - The basic building block for animations controlled by a timeline.
  • clock - What drives rafTimeline frame by frame.
  • createStates - A state machine of timelines.
  • Dynamic Animations - For creating interactive animations.
  • Large-scale usage - Costs, sharing and ownership rules.