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
fromof the new state is, in order:timelineConfig.from, the current timeline's value, the last value the machine showed (it survivestimeline().reset()), theninitialValue. - When a timeline is playing, its velocity is handed to the new one (velocity-continuous retargeting for a
springtiming). PassvelocityintimelineConfigto override it.
Transition rules
- Atomic. An unknown state name throws a
RangeErrorbefore anything changes. An invalidtimelineConfig(for example a malformedfrom) is rolled back: the machine keeps its previous state and timeline, and the error is rethrown. interrupt: false. If the current timeline isPLAYING, the transition is rejected, nothing changes (state, timeline and listeners stay as they are) and the promise resolves'skipped'.transitionTotakes the state and one config: a third argument throws aTypeError.- The promise.
transitionToreturns the run of the new timeline and never rejects:'ended','interrupted'(another transition replaced it),'skipped','reset'or'disposed'(also afterdispose()). - Seconds. The
delayof atimelineConfigis in seconds, like onplay(). - Reduced motion. Pass
reducedMotiontocreateStatesto 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 totimeline()across transitions: usebind,onUpdateoronTransition, which follow the current timeline.
The Controller
The createStates function returns a controller object with the following members:
| Member | Description |
|---|---|
timeline() | The currently active timeline. Use it to subscribe to updates or control playback. |
state() | The current state name. |
value | The 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'. |
disposed | Read-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
createStatesto manage distinct visual states of a component, especially when smooth transitions between states are required. - Do provide a sensible
initialValuethat matches the component's initial appearance. - Do call
dispose()when the owner is destroyed. - Don't manually manage multiple
timelineinstances and their transitions;createStatesis designed to abstract this complexity. - Don't create a new
createStatesinstance frequently; it should be initialized once for a given set of states.
API Reference
| Option | Type | Description |
|---|---|---|
initial | keyof States | The initial state name. |
initialValue | AniGroup<G> | Start values for the first transition. Required; a missing one throws a TypeError. |
states | Record<string, AnimationNode<G>> | Named animation trees. |
clock | AnimationClockInterface | (Optional) Clock for every timeline created by the machine. |
reducedMotion | ReducedMotionPolicy | (Optional) Policy forwarded to every state's timeline: 'jump' (default), 'ignore', or { maxDuration }. |
Related Components
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.