Ani
Core API

createStates

Creates a state machine to manage and transition between different animations.

The createStates function is a high-level utility for managing complex animation logic. It allows you to define a set of named animation trees and provides a simple API for seamless transitions between them.

Example

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

// 1. Define different animation structures for each named state.
const animations = {
  inactive: a.ani({ to: { scale: 1, opacity: 0.5 }, duration: 0.5 }),
  active: a.ani({ to: { scale: 1.2, opacity: 1 }, duration: 0.3 }),
};

// 2. Create a state machine controller with an initial state and initial values.
const myStates = a.createStates({
  initial: 'inactive',
  initialValue: { scale: 1, opacity: 0.5 }, // The starting point for the first animation
  states: animations,
});

// 3. Write the value to an element. The binding follows every transition.
const element = document.createElement("div");
const unbind = myStates.bind(element);

// 4. Transition to a new state. This will smoothly switch to the 'active' animation.
const result = await myStates.transitionTo('active'); // 'ended'

Usage & Concepts

Overview

createStates is ideal for UI components with multiple visual states (e.g., hover, active, disabled, selected) or complex character animations. Each transitionTo creates a new timeline for the target state and plays it from the current value, so transitions are seamless instead of abrupt cuts.

  • The from of the new state is, in order: timelineConfig.from, the current timeline's value, the last value the machine showed (it survives timeline().reset()), then initialValue.
  • When a timeline is playing, its velocity is handed to the new one (velocity-continuous retargeting for a spring timing). Pass velocity in timelineConfig to override it.

Transition rules

  • Atomic. An unknown state name throws a RangeError before anything changes. An invalid timelineConfig (for example a malformed from) is rolled back: the machine keeps its previous state and timeline, and the error is rethrown.
  • interrupt: false. If the current timeline is PLAYING, the transition is rejected, nothing changes (state, timeline and listeners stay as they are) and the promise resolves 'skipped'. transitionTo takes the state and one config: a third argument throws a TypeError.
  • The promise. transitionTo returns the run of the new timeline and never rejects: 'ended', 'interrupted' (another transition replaced it), 'skipped', 'reset' or 'disposed' (also after dispose()).
  • Seconds. The delay of a timelineConfig is in seconds, like on play().
  • Reduced motion. Pass reducedMotion to createStates to set the policy for every timeline the machine creates ('jump' by default, 'ignore', or { maxDuration: seconds }). See Reduced motion.
  • Replaced timelines are disposed. After a transition the old timeline is dead (dispose()d), together with the bindings and listeners attached through the machine. Do not keep a reference to timeline() across transitions: use bind, onUpdate or onTransition, which follow the current timeline.

The Controller

The createStates function returns a controller object with the following members:

MemberDescription
timeline()The currently active timeline. Use it to subscribe to updates or control playback.
state()The current state name.
valueThe current timeline's value, else the last value the machine showed, else the initial value. Frozen.
transitionTo(newState, [timelineConfig])Switches state and returns Promise<RunResult>. timelineConfig is the same as play() options except that from is optional.
bind(target, [{ resolver }])Writes the value to target.style on every notification of the current timeline, now and after every transition. Returns an unbind function that stops it for all future timelines.
onUpdate(callback)Receives the same { state, status } frames as a timeline listener, from the current timeline and every later one. Returns an unsubscribe function.
onTransition(callback)Called with (state, timeline) right before the new timeline starts playing, so listeners see its first update. Returns an unsubscribe function. Errors thrown by callbacks are rethrown asynchronously.
dispose()Disposes the current timeline and clears every binding and subscriber. Idempotent. Afterwards transitionTo resolves 'disposed'.
disposedRead-only; true once dispose() ran.
import * as a from "@freestylejs/ani-core";

const myStates = a.createStates({
  initial: "idle",
  initialValue: { opacity: 0 },
  states: { idle: a.ani({ to: { opacity: 0 }, duration: 0.2 }) },
});
const element = document.createElement("div");

const unbind = myStates.bind(element);
const stop = myStates.onUpdate(({ state }) => console.log(state.opacity));

// when the owner goes away
unbind();
stop();
myStates.dispose();

Ownership

The controller owns the timelines it creates. Call dispose() when it is no longer needed, otherwise a looping state keeps running on the clock. The framework bindings do this for you.

Best Practices

  • Do use createStates to manage distinct visual states of a component, especially when smooth transitions between states are required.
  • Do provide a sensible initialValue that matches the component's initial appearance.
  • Do call dispose() when the owner is destroyed.
  • Don't manually manage multiple timeline instances and their transitions; createStates is designed to abstract this complexity.
  • Don't create a new createStates instance frequently; it should be initialized once for a given set of states.

API Reference

OptionTypeDescription
initialkeyof StatesThe initial state name.
initialValueAniGroup<G>Start values for the first transition. Required; a missing one throws a TypeError.
statesRecord<string, AnimationNode<G>>Named animation trees.
clockAnimationClockInterface(Optional) Clock for every timeline created by the machine.
reducedMotionReducedMotionPolicy(Optional) Policy forwarded to every state's timeline: 'jump' (default), 'ignore', or { maxDuration }.
  • rafTimeline - The underlying controller for each state within the machine.
  • ani - The basic building block for individual animations within each state.
  • sequence - To compose animations into sequential stages within a state.
  • parallel - To run multiple animations simultaneously within a state.