Machine definitions and interaction contracts
Machine definitions describe the behavior of a component without tying it to a UI framework. They turn props and events into state changes, context updates, side effects, and a small public API that component packages can use to render accessible UI. See also State machine platform, Machine runtime, and Component machines.
Machine definition model
The machine is the behavior contract for one component. A component package supplies a typed schema and a machine definition, while a framework adapter runs the definition and a connect function turns the running service into DOM props and public methods.
The main parts have separate roles:
| Part | Purpose |
|---|---|
| Props | External configuration and callbacks. The machine can normalize defaults before use. |
| State | A finite behavior mode. Transitions move the machine between named states. |
| Context | Reactive values that change during the machine lifetime. |
| Refs | Non-reactive values such as caches or helper objects. |
| Computed values | Values derived from props, context, refs, or other computed values. |
| Events | The inputs that request behavior from the machine. |
| Guards | Boolean rules that select whether a transition can run. |
| Actions | Short operations that update context, call callbacks, or send events. |
| Effects | Work that stays active while a state is active and can provide cleanup. |
| Connect API | The framework-neutral view and control surface used by component code. |
createMachine validates and returns this definition. The typed schema names the allowed states, events, context values, computed values, guards, actions, and effects. This keeps the machine contract and the component API aligned. References: packages/…/types.ts• L196-242, packages/…/create-machine.ts• L24-27, packages/…/toggle.types.ts• L23-37
State and transition model
States represent meaningful behavior modes rather than every value in the component. An event is looked up in the active state and its parent states, then the first transition whose guard passes is selected. A transition may keep the current state, move to another state, or run actions while staying in place.
Nested states express a parent behavior with a more specific child mode. Use a dotted state path for a nested value, such as open.idle. A parent can handle events for its active children. State tags provide stable facts such as open when callers should not depend on one exact state path. References: packages/…/state.ts• L33-70, packages/…/state.ts• L192-207, packages/…/state.ts• L241-248
Initial state
The initial-state function chooses the first state from normalized props. It is the place to map an initial or controlled input into the machine's behavior chart. For example, a dialog starts in open when open or defaultOpen is true; otherwise it starts in closed.
References: packages/…/types.ts• L209-212 packages/…/dialog.machine.ts• L28-31
State entry and exit
State entry and exit actions mark the boundaries of a state. State effects run for the lifetime of that state and are cleaned up when the state exits or the service stops. This lets a component keep focus control, outside-click tracking, or scroll locking tied to the behavior that needs it.
References: packages/…/types.ts• L177-194 packages/…/machine.ts• L242-281
Event contracts
Events are the internal language of a machine. Component interaction code sends events such as OPEN, CLOSE, or PRESS.TOGGLE; effects can send events when the DOM reports an outside click or another external change. Event payloads carry data needed by the selected action, such as a value for TRIGGER_VALUE.SET.
Use event names that state the intent and keep them stable within the component package. Public connect methods should send events instead of changing context directly. This keeps user calls, DOM interactions, and external effects on the same transition path. References: packages/…/dialog.types.ts• L146-150, packages/…/dialog.connect.ts• L18-27, packages/…/dialog.machine.ts• L147-155
Controlled and queued events
Controlled props are synchronized through explicit events. A prop watcher detects a change and sends a CONTROLLED.* event so the machine can reflect the external value without treating it as a user action. Public setters send the desired event even when the current state may not yet include an earlier queued event.
When a public setter represents the latest value, its event can use replaces with a shared key. The runtime then keeps only the newest queued event for that key. Use this only for public declarative setters; internal dismissal and timing events must remain separate so a user call cannot hide them.
References: packages/…/dialog.machine.ts• L51-55 packages/…/dialog.machine.ts• L62-74 packages/…/dialog.connect.ts• L18-22 packages/…/types.ts• L89-95
The following diagram shows the normal path from component input to rendered behavior.
flowchart LR
P[Props or DOM input] --> C[connect API]
C --> E[Event]
E --> G{Guard selection}
G -->|allowed| T[Transition]
T --> A[Actions and context updates]
T --> S[State change]
S --> F[State effects]
A --> O[Public callback or rendered output]
F --> O
Context and props
Props describe what the component receives from its caller. Context describes reactive state that the machine owns or mirrors. A bindable context value supports an uncontrolled default, an optional controlled value, and an optional change callback. This gives component packages one state model for both usage styles.
Read context with context.get, update it with context.set, and read its starting value with context.initial. A context update can notify the caller through the bindable onChange function. Refs are different: they hold non-reactive data and do not represent rendered component state. References: packages/…/types.ts• L34-65, packages/…/toggle.machine.ts• L12-21
Props are normalized before the machine uses them. Defaults must allow caller values to override them. The normalized props also provide the machine scope, which gives framework-neutral access to instance IDs and DOM roots. References: packages/…/types.ts• L163-166, packages/…/dialog.machine.ts• L11-25, packages/…/types.ts• L78-87
Guards and actions
Guards answer whether a transition is allowed. They should inspect the current event, state, props, context, refs, or computed values and return a boolean. They do not perform state changes. When a transition has several guarded choices, the first matching choice wins; an unguarded choice acts as the fallback.
Actions perform the work selected by a transition. They can update context, call a prop callback, send another event, or use scope for a DOM-related task. Keep the transition decision in guards and the resulting change in actions so the behavior chart remains readable. References: packages/…/types.ts• L99-121, packages/…/machine.ts• L190-212, packages/…/machine.ts• L233-239
Computed values and watchers
Computed values expose derived facts without storing duplicate state in context. They are evaluated when requested and can combine props, context, refs, scope, and other computed values. Use them when a value should follow its inputs rather than become a second source of truth.
Watchers connect changes in props or context to actions. They are useful when external controlled input must enter the machine as an event or when a change needs a side effect. Track only the values that should trigger the response. References: packages/…/types.ts• L3-10, packages/…/types.ts• L27-32, packages/…/types.ts• L213-215, packages/…/dialog.machine.ts• L51-55
Effects and cleanup
Effects represent ongoing work tied to a state. They are the right boundary for subscriptions, DOM listeners, focus traps, scroll locks, and outside-interaction tracking. An effect may return a cleanup function; the runtime calls it when the state exits or the service stops.
An effect can return no cleanup when it has no resource to release. Any effect that adds a listener, observer, timer, or lock must return the matching cleanup. This prevents work from a former state from acting on a later state. References: packages/…/types.ts• L173-175, packages/…/machine.ts• L214-231, packages/…/dialog.machine.ts• L128-203
Connect API
The connect function is the public interaction contract for a component package. It receives a running machine service and a prop normalizer, then returns state values, imperative setters, and prop getters for the component's parts. Framework code uses this API instead of reading machine internals or sending events directly.
Prop getters combine part attributes, generated IDs, current state, accessibility attributes, and event handlers. The normalizer converts the common prop shape into the target framework's element shape. Public setters send named events, so they preserve the machine's guards, callbacks, and effects. References: plop/machine/src/{{machine}}.connect.ts.hbs#L1-L17, packages/…/prop-types.ts• L62-79, packages/…/dialog.connect.ts• L29-120
Service boundary
The service exposes the pieces that a connect function needs: current state, context, props, scope, computed access, refs, events, and send. The service is created by a framework adapter, but its shape stays common across adapters. This is what lets one machine serve React, Vue, Solid, Svelte, Preact, and vanilla consumers.
References: packages/…/types.ts• L269-285 packages/…/machine.ts• L37-40
Public API shape
The API type should describe what component consumers can observe and do. It should include semantic state values and setters, then prop getters for each supported component part. The toggle API illustrates a small contract; the dialog API illustrates a multi-part component with open state, trigger selection, and accessible element props.
References: packages/…/toggle.types.ts• L39-61 packages/…/dialog.types.ts• L167-192
Authoring flow
When a component package needs a machine, author the behavior and public interaction surface in this order:
- Define the schema for props, states, context, events, guards, actions, effects, and computed values.
- Normalize props and choose the initial state.
- Add bindable context for reactive state and refs for non-reactive helpers.
- Draw the states and events, then add guards for conditional paths.
- Add actions for state updates and callbacks. Add effects for work that must live with a state.
- Define the connect API with semantic values, public setters, and prop getters.
- Keep DOM queries in the component's DOM helper boundary and pass normalized props through the framework adapter.
This order separates the behavior contract from its rendering surface. It also makes the machine usable by more than one framework without changing its state model. References: plop/machine/src/{{machine}}.machine.ts.hbs#L1-L28, plop/machine/src/{{machine}}.types.ts.hbs#L1-L22, plop/machine/src/{{machine}}.connect.ts.hbs#L1-L17
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the schema unions in sync with every state, event, guard, action, effect, and computed key used by the machine.
- When a controlled prop changes, preserve the matching
CONTROLLED.*event path and callback behavior instead of updating context from the watcher. - When a public setter queues a replaceable event, use the same
replaceskey only for that setter's declarative value. - When a state effect adds a resource, keep its cleanup aligned with state exit and service stop behavior.
- When a connect API adds a component part, keep its API type, anatomy part, DOM ID helper, and normalized prop getter aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A controlled state change bypasses its machine event | The visible state and change callback can follow different paths | Route prop changes through a watcher and a CONTROLLED.* event |
| A public setter checks stale state before sending | Rapid setter calls can drop the latest intended value | Send unconditionally and use replaces for the setter's queue slot |
| An effect does not clean up its listener or lock | Old state behavior remains active after the component changes state | Return cleanup from every resource-owning effect |
| A guarded transition has no matching fallback | An event is ignored when no guard passes | Order guarded transitions deliberately and add an unguarded fallback when the event must act |
| A connect getter reads a stale snapshot or omits a part contract | DOM attributes and event handlers do not match machine state | Read the service contract and keep API types and getters paired |
Key files
| File | Why to read it |
|---|---|
| packages/…/types.ts | Defines the shared contracts for machines, services, transitions, context, and effects. |
| packages/…/state.ts | Shows how state paths, nested states, tags, and transition lookup work. |
| packages/…/machine.ts | Shows the runtime boundary that evaluates guards, actions, effects, and queued events. |
| packages/…/dialog.machine.ts | Shows a complete state and interaction model with controlled state, effects, focus, and dismissal. |
| packages/…/dialog.connect.ts | Shows how a multi-part component exposes state, setters, accessibility props, and DOM handlers. |
| packages/…/dialog.types.ts | Shows how a component's props, schema, service, and public API are typed together. |
| packages/…/toggle.machine.ts | Shows the smallest useful controlled and uncontrolled context pattern. |
| packages/…/toggle.connect.ts | Shows the link from public DOM interaction to machine events. |
plop/machine/src/{{machine}}.machine.ts.hbs | Provides the standard starting shape for a new machine definition. |
plop/machine/src/{{machine}}.connect.ts.hbs | Provides the standard starting shape for a framework-neutral connect API. |