GitHub image
xstate
โŒ˜K
Exports
Readme
Classes
3
StateNode
Docs
Import
Tests
3
References
2
class StateNode<TContext', TStateSchema', TEvent', TTypestate'> {
constructor(
config: StateNodeConfig<TContext', TStateSchema', TEvent', BaseActionObject>,
options?: Partial<
MachineOptions<TContext', TEvent', ActionObject<TContext', TEvent'>>,
>,
_context?: Readonly<TContext'> | () => Readonly<TContext'>
): StateNode

The raw config used to create the machine.

config: StateNodeConfig<TContext', TStateSchema', TEvent', BaseActionObject>

The relative key of the state node, which represents its location in the overall state value.

key: string

The unique ID of the state node.

id: string

The machine's own version.

version?: string

The type of this state node:

  • 'atomic' - no child state nodes
  • 'compound' - nested child state nodes (XOR)
  • 'parallel' - orthogonal nested child state nodes (AND)
  • 'history' - history state node
  • 'final' - final state node
type: "atomic" | "compound" | "parallel" | "final" | "history"

The string path from the root machine node to this node.

path: string[]

The initial state node key.

initial?: keyof TStateSchema["states"]

(DEPRECATED) Whether the state node is a parallel state node.

Use type: 'parallel' instead.

parallel?: boolean

The child state nodes.

states: StateNodesConfig<TContext', TStateSchema', TEvent'>

The type of history on this state node. Can be:

  • 'shallow' - recalls only top-level historical state value
  • 'deep' - recalls historical state value at all levels
history: false | "shallow" | "deep"

The action(s) to be executed upon entering the state node.

onEntry: ActionObject<TContext', TEvent'>[]

The action(s) to be executed upon exiting the state node.

onExit: ActionObject<TContext', TEvent'>[]

The activities to be started upon entering the state node, and stopped upon exiting the state node.

activities: ActivityDefinition<TContext', TEvent'>[]
strict: boolean

The parent state node.

parent?: StateNode<TContext', any, TEvent', any>

The root machine node.

machine: StateNode<TContext', any, TEvent', TTypestate'>

The meta data associated with this state node, which will be returned in State instances.

meta?: TStateSchema extends { meta: infer D; } ? D : any

The data sent with the "done.state.id" event if this is a final state node.

doneData?: Mapper<TContext', TEvent', any> | PropertyMapper<TContext', TEvent', any>

The string delimiter for serializing the path to a string. The default is "."

delimiter: string

The order this state node appears. Corresponds to the implicit SCXML document order.

order: number

The services invoked by this state node.

invoke: InvokeDefinition<TContext', TEvent'>[]
options: MachineOptions<TContext', TEvent', ActionObject<TContext', TEvent'>>
schema: MachineSchema<TContext', TEvent'>
__xstatenode: true
description?: string
tags: string[]

Clones this state machine with custom options and context.

withConfig: (

Options (actions, guards, activities, services) to recursively merge with the existing options.

options: Partial<
MachineOptions<
TContext',
TEvent',
ActionObject<TContext', TEvent'>,
>,
>,

Custom context (will override predefined context)

context?: TContext' | () => TContext'
) => StateNode

Clones this state machine with custom context.

withContext: (

Custom context (will override predefined context, not recursive)

context: TContext' | () => TContext'
) => StateNode
context: TContext'

The well-structured state node definition.

definition: StateNodeDefinition<TContext', TStateSchema', TEvent'>
toJSON: () => StateNodeDefinition<TContext', TStateSchema', TEvent'>

The mapping of events to transitions.

on: TransitionDefinitionMap<TContext', TEvent'>
after: DelayedTransitionDefinition<TContext', TEvent'>[]

All the transitions that can be taken from this state node.

transitions: TransitionDefinition<TContext', TEvent'>[]

Returns the state nodes represented by the current state value.

getStateNodes: (

The state value or State instance

state:
|
string
|
State<TContext', TEvent', any, TTypestate'>
) => StateNode<TContext', any, TEvent', TTypestate'>[]

Returns true if this state node explicitly handles the given event.

handles: (

The event in question

event: Event<TEvent'>
) => boolean

Resolves the given state to a new State instance relative to this machine.

This ensures that .events and .nextEvents represent the correct values.

resolveState: (

The state to resolve

state: State<TContext', TEvent', any, any>
) => State<TContext', TEvent', TStateSchema', TTypestate'>

Determines the next state given the current state and sent event.

transition: (

The current State instance or state value

state:
|
string
|
State<TContext', TEvent', any, TTypestate'>
,

The event that was sent at the current state

event: TEvent' | TEvent["type"] | Event<TEvent'>,

The current context (extended state) of the current state

context?: TContext'
) => State<TContext', TEvent', TStateSchema', TTypestate'>

Returns the child state node from its relative stateKey, or throws.

getStateNode: (stateKey: string) => StateNode<TContext', any, TEvent', TTypestate'>

Returns the state node with the given stateId, or throws.

getStateNodeById: (

The state ID. The prefix "#" is removed.

stateId: string
) => StateNode<TContext', any, TEvent', any>

Returns the relative state node from the given statePath, or throws.

getStateNodeByPath: (

The string or string array relative path to the state node.

statePath: string | string[]
) => StateNode<TContext', any, TEvent', any>

Resolves a partial state value with its full representation in this machine.

resolve: (

The partial state value to resolve.

stateValue: StateValue
) => StateValue
getInitialState: (
stateValue: StateValue,
context?: TContext'
) => State<TContext', TEvent', TStateSchema', TTypestate'>

The initial State instance, which includes all actions to be executed from entering the initial state.

initialState: State<TContext', TEvent', TStateSchema', TTypestate'>

The target state value of the history state node, if it exists. This represents the default state value to transition to if no history value exists yet.

target: StateValue

Returns the leaf nodes from a state path relative to this state node.

getRelativeStateNodes: (

The relative state path to retrieve the state nodes

relativeStateId: StateNode<
TContext',
any,
TEvent',
{ value: any, context: TContext' },
>,
historyValue?: HistoryValue,

Whether state nodes should resolve to initial child state nodes

resolve?: boolean
) => StateNode<
TContext',
any,
TEvent',
{ value: any, context: TContext' },
>[]
initialStateNodes: StateNode<TContext', any, TEvent', any>[]

Retrieves state nodes from a relative path to this state node.

getFromRelativePath: (

The relative path from this state node

relativePath: string[]
) => StateNode<TContext', any, TEvent', any>[]

All the state node IDs of this state node and its descendant state nodes.

stateIds: string[]

All the event types accepted by this state node and its descendants.

events: TEvent["type"][]

All the events that have transitions directly from this state node.

Excludes any inert events.

ownEvents: TEvent["type"][]
}
State
Docs
Import
Tests
3
References
2
class State<TContext', TEvent', TStateSchema', TTypestate'> {

Creates a new State instance.

constructor(config: StateConfig<TContext', TEvent'>): State

Creates a new State instance for the given stateValue and context.

static from: <TC', TE'>(
stateValue: string | StateValueMap | State<TC', TE', any, any>,
context?: TC'
) => State<TC', TE', any, any>

Creates a new State instance for the given config.

static create: <TC', TE'>(

The state config

config: StateConfig<TC', TE'>
) => State<TC', TE', any, <>>

Creates a new State instance for the given stateValue and context with no actions (side-effects).

static inert: <TC', TE'>(
stateValue: string | StateValueMap | State<TC', TE', any, <>>,
context: TC'
) => State<TC', TE', any, <>>
value: StateValue
context: TContext'
historyValue?: HistoryValue
history?: State
actions: ActionObject<TContext', TEvent'>[]
activities: ActivityMap
meta: any
events: TEvent'[]
event: TEvent'
_event: Event<TEvent'>
_sessionid: string

Indicates whether the state has changed from the previous state. A state is considered "changed" if:

  • Its value is not equal to its previous value, or:
  • It has any new actions (side-effects) to execute.

An initial state (with no history) will return undefined.

changed: boolean

Indicates whether the state is a final state.

done: boolean

The enabled state nodes representative of the state value.

configuration: StateNode<TContext', any, TEvent', any>[]

The next events that will cause a transition from the current state.

nextEvents: string[]

The transition definitions that resulted in this state.

transitions: TransitionDefinition<TContext', TEvent'>[]

An object mapping actor IDs to spawned actors/invoked services.

children: Record<string, ActorRef<any, any>>
tags: any
machine: StateMachine<
TContext',
any,
TEvent',
TTypestate',
ActionObject<TContext', TEvent'>,
>

Returns an array of all the string leaf state node paths.

toStrings: (
stateValue?: StateValue,

The character(s) that separate each subpath in the string state node path.

delimiter?: string
) => string[]
toJSON: () => (
&
Omit<State', ("machine" | "tags" | "transitions" | "configuration")>
&
{ tags: string[] }
)

Whether the current state value is a subset of the given parent state value.

matches: <TSV'>(parentStateValue: TSV') => boolean

Whether the current state configuration has a state node with the specified tag.

hasTag: (tag: string) => boolean

Determines whether sending the event will cause a transition.

can: (

The event to test

event: TEvent' | ExtractWithSimpleSupport<TEvent>["type"]
) => boolean
}
Interpreter
Docs
Import
Tests
3
References
2
class Interpreter<TContext', TStateSchema', TEvent', TTypestate'>
implements ActorRef<TEvent', State<TContext', TEvent', TStateSchema', TTypestate'>, Interpreter'>
{

Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any.

constructor(

The machine to be interpreted

machine: StateMachine<
TContext',
TStateSchema',
TEvent',
TTypestate',
ActionObject<TContext', TEvent'>,
>,

Interpreter options

options?: Partial<InterpreterOptions>
): Interpreter

The default interpreter options:

  • clock uses the global setTimeout and clearTimeout functions
  • logger uses the global console.log() method
static defaultOptions: InterpreterOptions
static interpret: <TContext', TStateSchema', TEvent', TTypestate'>(

The machine to interpret

machine: StateMachine<
TContext',
TStateSchema',
TEvent',
TTypestate',
ActionObject<TContext', TEvent'>,
>,

Interpreter options

options?: Partial<InterpreterOptions>
) => Interpreter<TContext', TStateSchema', TEvent', TTypestate'>
machine: StateMachine<
TContext',
TStateSchema',
TEvent',
TTypestate',
ActionObject<TContext', TEvent'>,
>

The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.

clock: Clock
options: Readonly<InterpreterOptions>

Whether the service is started.

initialized: boolean
parent?: Interpreter<any, any, EventObject, <>>
id: string

The globally unique process ID for this invocation.

sessionId: string
children: any
initialState: State<TContext', TEvent', TStateSchema', TTypestate'>
state: State<TContext', TEvent', TStateSchema', TTypestate'>

Executes the actions of the given state, with that state's context and event.

execute: (

The state whose actions will be executed

state: State<TContext', TEvent', TStateSchema', TTypestate'>,

The action implementations to use

actionsConfig?: ActionFunctionMap<
TContext',
TEvent',
ActionObject<TContext', TEvent'>,
>
) => void
onTransition: (
listener: StateListener<
TContext',
TEvent',
TStateSchema',
TTypestate',
>
) => Interpreter'
subscribe: (
nextListener?: (
state: State<TContext', TEvent', any, TTypestate'>
) => void,
errorListener?: (error: any) => void,
completeListener?: () => void
) => Subscription+1

Adds an event listener that is notified whenever an event is sent to the running interpreter.

onEvent: (

The event listener

listener: EventListener<EventObject>
) => Interpreter

Adds an event listener that is notified whenever a send event occurs.

onSend: (

The event listener

listener: EventListener<EventObject>
) => Interpreter

Adds a context listener that is notified whenever the state context changes.

onChange: (

The context listener

listener: ContextListener<TContext'>
) => Interpreter

Adds a listener that is notified when the machine is stopped.

onStop: (

The listener

listener: Listener
) => Interpreter

Adds a state listener that is notified when the statechart has reached its final state.

onDone: (

The state listener

listener: EventListener<DoneEvent>
) => Interpreter

Removes a listener.

off: (

The listener to remove

listener: (args: any[]) => void
) => Interpreter

Alias for Interpreter.prototype.start

init: (
initialState?:
|
string
|
State<TContext', TEvent', TStateSchema', TTypestate'>
) => Interpreter

Starts the interpreter from the given state, or the initial state.

start: (

The state to start the statechart from

initialState?:
|
string
|
State<TContext', TEvent', TStateSchema', TTypestate'>
) => Interpreter

Stops the interpreter and unsubscribe all listeners.

This will also notify the onStop listeners.

stop: () => Interpreter

Sends an event to the running interpreter to trigger a transition.

An array of events (batched) can be sent as well, which will send all batched events to the running interpreter. The listeners will be notified only once when all events are processed.

send: (
event: TEvent' | TEvent["type"] | Event<TEvent'>[] | Event<TEvent'>,
payload?: EventData
) => State<TContext', TEvent', TStateSchema', TTypestate'>

Returns a send function bound to this interpreter instance.

sender: (

The event to be sent by the sender.

event: Event<TEvent'>
) => () => State<TContext', TEvent', TStateSchema', TTypestate'>

Returns the next state given the interpreter's current state and the event.

This is a pure method that does not update the interpreter's state.

nextState: (

The event to determine the next state

event: TEvent' | TEvent["type"] | Event<TEvent'>
) => State<TContext', TEvent', TStateSchema', TTypestate'>
spawn: (entity: Spawnable, name: string, options?: SpawnOptions) => ActorRef<any, any>
spawnMachine: <TChildContext', TChildStateSchema', TChildEvent'>(
machine: StateMachine<
TChildContext',
TChildStateSchema',
TChildEvent',
<>,
ActionObject<TChildContext', TChildEvent'>,
>,
options?: { id?: string, autoForward?: boolean, sync?: boolean }
) => ActorRef<TChildEvent', State<TChildContext', TChildEvent', any, <>>>
toJSON: () => { id: string }
[Symbol.observable]: () => Subscribable<
State<TContext', TEvent', TStateSchema', TTypestate'>,
>
getSnapshot: () => State<TContext', TEvent', TStateSchema', TTypestate'>
}
Functions
14
Machine
Docs
Import
Tests
3
References
2
function Machine<TContext', TStateSchema', TEvent'>(
config: MachineConfig<
TContext',
TStateSchema',
TEvent',
ActionObject<TContext', TEvent'>,
>,
options?: Partial<
MachineOptions<TContext', TEvent', ActionObject<TContext', TEvent'>>,
>,
initialContext?: TContext'
): StateMachine<TContext', TStateSchema', TEvent', <>, ActionObject<TContext', TEvent'>>+1
matchesState
Docs
Import
Tests
3
References
2
function matchesState(
parentStateId: StateValue,
childStateId: StateValue,
delimiter?: string
): boolean
mapState
Docs
Import
Tests
3
References
2
function mapState(stateMap: { }, stateId: string): any
assign
Docs
Import
Tests
3
References
2
function assign<TContext', TEvent'>(
assignment: Assigner<TContext', TEvent'> | PropertyAssigner<TContext', TEvent'>
): AssignAction<TContext', TEvent'>
send
Docs
Import
Tests
3
References
2

Sends an event. This returns an action that will be read by an interpreter to send the event in the next step, after the current step is finished executing.

function send<TContext', TEvent', TSentEvent'>(

The event to send.

event: TSentEvent' | TSentEvent["type"] | SendExpr<TContext', TEvent', TSentEvent'>,

Options to pass into the send event:

  • id - The unique send event identifier (used with cancel()).
  • delay - The number of milliseconds to delay the sending of the event.
  • to - The target of this event (by default, the machine the event was sent from).
options?: SendActionOptions<TContext', TEvent'>
): SendAction<TContext', TEvent', TSentEvent'>
sendParent
Docs
Import
Tests
3
References
2

Sends an event to this machine's parent.

function sendParent<TContext', TEvent', TSentEvent'>(

The event to send to the parent machine.

event: TSentEvent' | TSentEvent["type"] | SendExpr<TContext', TEvent', TSentEvent'>,

Options to pass into the send event.

options?: SendActionOptions<TContext', TEvent'>
): SendAction<TContext', TEvent', TSentEvent'>
sendUpdate
Docs
Import
Tests
3
References
2

Sends an update event to this machine's parent.

function sendUpdate<TContext', TEvent'>(): SendAction<
TContext',
TEvent',
{ type: import("/lib/types").ActionTypes.Update },
>
forwardTo
Docs
Import
Tests
3
References
2

Forwards (sends) an event to a specified service.

function forwardTo<TContext', TEvent'>(

The target service to forward the event to.

target:
|
string
|
ExprWithMeta<TContext', TEvent', (string | number | ActorRef<any, any>)>
,

Options to pass into the send action creator.

options?: SendActionOptions<TContext', TEvent'>
): SendAction<TContext', TEvent', AnyEventObject>
interpret
Docs
Import
Tests
3
References
2

Creates a new Interpreter instance for the given machine with the provided options, if any.

function interpret<TContext', TStateSchema', TEvent', TTypestate'>(

The machine to interpret

machine: StateMachine<
TContext',
TStateSchema',
TEvent',
TTypestate',
ActionObject<TContext', TEvent'>,
>,

Interpreter options

options?: Partial<InterpreterOptions>
): Interpreter<TContext', TStateSchema', TEvent', TTypestate'>
matchState
Docs
Import
Tests
3
References
2
function matchState<T', TContext', TEvent'>(
state: string | StateValueMap | State<TContext', TEvent', any, <>>,
patterns: StatePatternTuple<T', TContext', TEvent'>[],
defaultValue: ValueFromStateGetter<T', TContext', TEvent'>
): T'
spawn
Docs
Import
Tests
3
References
2
function spawn<T'>(entity: T', nameOrOptions?: string | SpawnOptions): ActorRefFrom<T'>+2
doneInvoke
Docs
Import
Tests
3
References
2

Returns an event that represents that an invoked service has terminated.

An invoked service is terminated when it has reached a top-level final state node, but not when it is canceled.

function doneInvoke(

The final state node ID

id: string,

The data to pass into the event

data?: any
): DoneEvent
createMachine
Docs
Import
Tests
3
References
2
function createMachine<TContext', TEvent', TTypestate'>(
config: TContext extends Model<any, any, any, any> ? "Model type no longer supported as generic type. Please use `model.createMachine(...)` instead." : MachineConfig<TContext, any, TEvent, ActionObject<...>>,
options?: Partial<
MachineOptions<TContext', TEvent', ActionObject<TContext', TEvent'>>,
>
): StateMachine<TContext', any, TEvent', TTypestate', ActionObject<TContext', TEvent'>>
createSchema
Docs
Import
Tests
3
References
2
function createSchema<T'>(schema?: any): T'
object
1
actions
Docs
Import
Tests
3
References
2
{
raise: <TContext', TEvent'>(
event: Event<TEvent'>
) => (RaiseAction<TEvent'> | SendAction<TContext', AnyEventObject, TEvent'>)
send: <TContext', TEvent', TSentEvent'>(

The event to send.

event:
|
TSentEvent'
|
TSentEvent["type"]
|
SendExpr<TContext', TEvent', TSentEvent'>
,

Options to pass into the send event:

  • id - The unique send event identifier (used with cancel()).
  • delay - The number of milliseconds to delay the sending of the event.
  • to - The target of this event (by default, the machine the event was sent from).
options?: SendActionOptions<TContext', TEvent'>
) => SendAction<TContext', TEvent', TSentEvent'>
sendParent: <TContext', TEvent', TSentEvent'>(

The event to send to the parent machine.

event:
|
TSentEvent'
|
TSentEvent["type"]
|
SendExpr<TContext', TEvent', TSentEvent'>
,

Options to pass into the send event.

options?: SendActionOptions<TContext', TEvent'>
) => SendAction<TContext', TEvent', TSentEvent'>
sendUpdate: <TContext', TEvent'>() => SendAction<
TContext',
TEvent',
{ type: import("/lib/types").ActionTypes.Update },
>
log: <TContext', TEvent'>(

The expression function to evaluate which will be logged. Takes in 2 arguments:

  • ctx - the current state context
  • event - the event that caused this action to be executed.
expr?: string | LogExpr<TContext', TEvent'>,

The label to give to the logged expression.

label?: string
) => LogAction<TContext', TEvent'>
cancel: (sendId: string | number) => CancelAction
start: <TContext', TEvent'>(

The activity to start.

activity: string | ActivityDefinition<TContext', TEvent'>
) => ActivityActionObject<TContext', TEvent'>
stop: <TContext', TEvent'>(

The activity to stop.

actorRef:
|
string
|
ActivityDefinition<TContext', TEvent'>
|
Expr<TContext', TEvent', (string | { id: string })>
) => StopAction<TContext', TEvent'>
assign: <TContext', TEvent'>(
assignment:
|
Assigner<TContext', TEvent'>
|
PropertyAssigner<TContext', TEvent'>
) => AssignAction<TContext', TEvent'>
after: (

The delay in milliseconds

delayRef: string | number,

The state node ID where this event is handled

id?: string
) => string
done: (

The final state node's parent state node id

id: string,

The data to pass into the event

data?: any
) => DoneEventObject
respond: <TContext', TEvent', TSentEvent'>(

The event to send back to the sender

event: TEvent' | TEvent["type"] | SendExpr<TContext', TEvent', TSentEvent'>,

Options to pass into the send event

options?: SendActionOptions<TContext', TEvent'>
) => SendAction<TContext', TEvent', AnyEventObject>
forwardTo: <TContext', TEvent'>(

The target service to forward the event to.

target:
|
string
|
ExprWithMeta<
TContext',
TEvent',
(string | number | ActorRef<any, any>),
>
,

Options to pass into the send action creator.

options?: SendActionOptions<TContext', TEvent'>
) => SendAction<TContext', TEvent', AnyEventObject>
escalate: <TContext', TEvent', TErrorData'>(

The error data to send, or the expression function that takes in the context, event, and meta, and returns the error data to send.

errorData: TErrorData' | ExprWithMeta<TContext', TEvent', TErrorData'>,

Options to pass into the send action creator.

options?: SendActionOptions<TContext', TEvent'>
) => SendAction<TContext', TEvent', AnyEventObject>
choose: <TContext', TEvent'>(conds: ChooseCondition<TContext', TEvent'>[]) => ChooseAction<TContext', TEvent'>
pure: <TContext', TEvent'>(
getActions: (
context: TContext',
event: TEvent'
) => SingleOrArray<ActionObject<TContext', TEvent'>>
) => PureAction<TContext', TEvent'>
}
Enums
1
InterpreterStatus
Docs
Import
Tests
3
References
2
enum InterpreterStatus {
NotStarted = 0,
Runningย ย ย  = 1,
Stoppedย ย ย  = 2,
}
Interfaces
1
Actor
Docs
Import
Tests
3
References
2
interface Actor<TContext' = any, TEvent' = AnyEventObject> {
id: string
send: (event: TEvent') => any
stop?: () => any
toJSON: () => { id: string }
meta?: InvokeDefinition<TContext', TEvent'>
state?: any
deferred?: boolean
subscribe: (
next: (value: T') => void,
error?: (error: any) => void,
complete?: () => void
) => Subscription+1
}
Description
Finite State Machines and Statecharts for the Modern Web.
Install
yarn add xstate
Copy
Details
MIT License
0 Dependencies
Native TypeScript Package
Metrics
Weekly Downloads