Compound States

In a heirarchy of states, compound states are parents. They contain atomic , parallel or other compound states.

Usage

Use compound(...) to create state configuration and resolveState(...) to initialize it.

import { atomic, compound, emitEvent, resolveState } from 'hine';
const toggleConfig = compound('toggle', {
initial: 'inactive',
children: [
atomic('inactive', {
on: { toggle: 'active' },
}),
atomic('active', {
on: { toggle: 'inactive' },
}),
],
});
const toggleState = resolveState(toggleConfig);
emitEvent(toggleState, 'toggle');

Active Children

Active states are those that can receive and handle emitted events at a particular time. Compound states have exactly one active child state. This is in contrast to parallel states , where all children are simultaneously active, and atomic states which have no children.

// Always `true` for compound states
console.log(toggleState.activeChildren.length === 1);

Children

Compound states must have at least one child and specify the initial active child when the state is initialized.

const activeChildCount = toggleState.activeChildren.length;
const childCount = toggleState.children.size;
// Always `true` for compound states
console.log(activeChildCount === 1);
console.log(childCount >= activeChildCount);

Hooks

Compound states accept hooks such as afterEntry and beforeExit . Hooks respond to life-cycle events of a state.

import { atomic, compound, emitEvent, resolveState } from 'hine';
import { logEvent } from './analytics.js';
const toggleConfig = compound('toggle', {
initial: 'inactive',
children: [
atomic('inactive', {
on: { toggle: 'active' },
}),
atomic('active', {
hooks: {
afterEntry: () => logEvent('active start'),
beforeExit: () => logEvent('active end'),
},
on: { toggle: 'inactive' },
}),
],
});
const toggleState = resolveState(toggleConfig);
emitEvent(toggleState, 'toggle');

When toggleState receives a 'toggle' event while inactive, it will transition to the active state and log 'active start' . When toggleState then transitions out of the active state, it will log 'active end' .