Matches
Overview
matches(...)
is used to check if a given state node matches a
specified path. It's particularly useful for determining the current state of a
state machine or checking if a specific sub-state is active.
Syntax
function matches(state: StateNode, path: string): boolean;
Parameters
state
(StateNode): The current state node to check against.path
(string): A dot-separated string representing the path to match.
Return Value
Returns true
if the state matches the given path, false
otherwise.
Description
The matches(...)
function performs a recursive check to determine if
the given state
matches the specified path
. It works as
follows:
If the state's name exactly matches the path, it returns
true
.If the path starts with the state's name followed by a dot, it checks the active children of the state.
For each active child, it recursively calls
matches
with the remaining part of the path.If any active child matches, it returns
true
.If no match is found, it returns
false
.
Examples
import { atomic, compound, emitEvent, matches, resolveState } from 'hine';// Define a toggle state machineconst toggleConfig = compound('toggle', { initial: 'inactive', children: [ atomic('inactive', { on: { toggle: 'active' }, }), atomic('active', { on: { toggle: 'inactive' }, }), ],});// Create an instance of the state machineconst myToggle = resolveState(toggleConfig);// Check initial stateconsole.log(matches(myToggle, 'toggle.inactive')); // trueconsole.log(matches(myToggle, 'toggle.active')); // false// Emit an event to change stateemitEvent(myToggle, 'toggle');// Check new stateconsole.log(matches(myToggle, 'toggle.inactive')); // falseconsole.log(matches(myToggle, 'toggle.active')); // true
Notes
The
path
string should use dot notation to represent nested states (e.g.,'parent.child.grandchild'
).Be careful about using state names with a dot (
'.'
) in them. This may lead to false-positives.const stateConfig = compound('parent', {initial: 'child.with.dots',children: [atomic('child.with.dots'), atomic('other.child')],});const state = resolveState(stateConfig);console.log(matches(state, 'parent.child.with.dots')); // true (correct)console.log(matches(state, 'parent.child')); // true (false positive!)