xstate 6.0.0-alpha.8 → 6.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -78
- package/bin/agent.js +347 -0
- package/bin/xstate.js +52 -0
- package/dist/createActor-25900f76.cjs.js +7015 -0
- package/dist/createActor-551369be.development.esm.js +7175 -0
- package/dist/createActor-a49ae0ce.development.cjs.js +7289 -0
- package/dist/createActor-cbe3abac.esm.js +6902 -0
- package/dist/declarations/src/SimulatedClock.d.ts +2 -1
- package/dist/declarations/src/State.d.ts +66 -5
- package/dist/declarations/src/StateMachine.d.ts +107 -32
- package/dist/declarations/src/StateNode.d.ts +21 -16
- package/dist/declarations/src/actions.d.ts +11 -6
- package/dist/declarations/src/actors/callback.d.ts +11 -2
- package/dist/declarations/src/actors/index.d.ts +6 -5
- package/dist/declarations/src/actors/listener.d.ts +8 -3
- package/dist/declarations/src/actors/logic.d.ts +42 -52
- package/dist/declarations/src/actors/observable.d.ts +15 -2
- package/dist/declarations/src/actors/promise.d.ts +90 -22
- package/dist/declarations/src/actors/subscription.d.ts +9 -3
- package/dist/declarations/src/assert.d.ts +1 -0
- package/dist/declarations/src/base.types.d.ts +102 -0
- package/dist/declarations/src/createActor.d.ts +101 -27
- package/dist/declarations/src/createMachine.d.ts +38 -17
- package/dist/declarations/src/delay.d.ts +8 -0
- package/dist/declarations/src/durable/index.d.ts +231 -0
- package/dist/declarations/src/effectDescriptor.d.ts +95 -0
- package/dist/declarations/src/eventTypes.d.ts +9 -0
- package/dist/declarations/src/fsm/index.d.ts +2 -0
- package/dist/declarations/src/fsm.d.ts +169 -0
- package/dist/declarations/src/graph/adjacency.d.ts +6 -3
- package/dist/declarations/src/graph/graph.d.ts +6 -3
- package/dist/declarations/src/graph/index.d.ts +2 -3
- package/dist/declarations/src/graph/pathFromEvents.d.ts +5 -2
- package/dist/declarations/src/graph/shortestPaths.d.ts +5 -3
- package/dist/declarations/src/graph/simplePaths.d.ts +5 -3
- package/dist/declarations/src/graph/types.d.ts +113 -59
- package/dist/declarations/src/hotSwap.d.ts +18 -0
- package/dist/declarations/src/index.d.ts +28 -19
- package/dist/declarations/src/inspection.d.ts +24 -1
- package/dist/declarations/src/machineFromJSON.d.ts +171 -0
- package/dist/declarations/src/machineSchemas.d.ts +27 -0
- package/dist/declarations/src/machineVersion.types.d.ts +53 -0
- package/dist/declarations/src/machineVersions.d.ts +103 -0
- package/dist/declarations/src/mapState.d.ts +2 -0
- package/dist/declarations/src/persist/index.d.ts +36 -0
- package/dist/declarations/src/persistedSnapshotValidation.d.ts +18 -0
- package/dist/declarations/src/runtimeHelpers.d.ts +43 -0
- package/dist/declarations/src/schema.types.d.ts +31 -4
- package/dist/declarations/src/serialize.d.ts +39 -28
- package/dist/declarations/src/setup.d.ts +1086 -147
- package/dist/declarations/src/spawn.d.ts +6 -4
- package/dist/declarations/src/stateUtils.d.ts +57 -14
- package/dist/declarations/src/system.d.ts +178 -17
- package/dist/declarations/src/systemTransition.d.ts +108 -0
- package/dist/declarations/src/toPromise.d.ts +1 -0
- package/dist/declarations/src/transition.d.ts +48 -10
- package/dist/declarations/src/transitionActions.d.ts +22 -4
- package/dist/declarations/src/typeUtils.d.ts +51 -0
- package/dist/declarations/src/types.d.ts +835 -318
- package/dist/declarations/src/types.v6.d.ts +547 -104
- package/dist/declarations/src/utils.d.ts +38 -8
- package/dist/declarations/src/validation/index.d.ts +49 -0
- package/dist/declarations/src/validation.types.d.ts +29 -0
- package/dist/declarations/src/waitFor.d.ts +1 -0
- package/dist/effectDescriptor-2fa27c54.cjs.js +351 -0
- package/dist/effectDescriptor-321a8ce9.development.esm.js +343 -0
- package/dist/effectDescriptor-d8b0f749.esm.js +343 -0
- package/dist/effectDescriptor-f73da4ec.development.cjs.js +351 -0
- package/dist/machineSchemas-45c21bc2.esm.js +1292 -0
- package/dist/machineSchemas-6d96bef4.development.cjs.js +1379 -0
- package/dist/machineSchemas-88d01821.cjs.js +1300 -0
- package/dist/machineSchemas-b5736804.development.esm.js +1371 -0
- package/dist/schema.types-0ecd17b8.esm.js +71 -0
- package/dist/schema.types-15a68ddc.cjs.js +74 -0
- package/dist/schema.types-1c16f035.development.cjs.js +74 -0
- package/dist/schema.types-1cd4652e.development.esm.js +71 -0
- package/dist/validation-05f1d517.esm.js +8 -0
- package/dist/validation-4561b43c.cjs.js +10 -0
- package/dist/validation-e69470ad.development.esm.js +8 -0
- package/dist/validation-f2714a35.development.cjs.js +10 -0
- package/dist/xstate-actors.cjs.js +1068 -12
- package/dist/xstate-actors.cjs.mjs +2 -4
- package/dist/xstate-actors.development.cjs.js +1068 -12
- package/dist/xstate-actors.development.cjs.mjs +2 -4
- package/dist/xstate-actors.development.esm.js +1064 -1
- package/dist/xstate-actors.esm.js +1064 -1
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.d.mts +2 -0
- package/dist/xstate-durable.cjs.d.ts +2 -0
- package/dist/xstate-durable.cjs.js +513 -0
- package/dist/xstate-durable.cjs.mjs +5 -0
- package/dist/xstate-durable.development.cjs.js +513 -0
- package/dist/xstate-durable.development.cjs.mjs +5 -0
- package/dist/xstate-durable.development.esm.js +507 -0
- package/dist/xstate-durable.esm.js +507 -0
- package/dist/xstate-durable.umd.min.js +2 -0
- package/dist/xstate-durable.umd.min.js.map +1 -0
- package/dist/xstate-fsm.cjs.d.mts +2 -0
- package/dist/xstate-fsm.cjs.d.ts +2 -0
- package/dist/xstate-fsm.cjs.js +111 -0
- package/dist/xstate-fsm.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.cjs.js +111 -0
- package/dist/xstate-fsm.development.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.esm.js +105 -0
- package/dist/xstate-fsm.esm.js +105 -0
- package/dist/xstate-fsm.umd.min.js +2 -0
- package/dist/xstate-fsm.umd.min.js.map +1 -0
- package/dist/xstate-graph.cjs.js +173 -457
- package/dist/xstate-graph.cjs.mjs +2 -5
- package/dist/xstate-graph.development.cjs.js +173 -457
- package/dist/xstate-graph.development.cjs.mjs +2 -5
- package/dist/xstate-graph.development.esm.js +171 -451
- package/dist/xstate-graph.esm.js +171 -451
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-persist.cjs.d.mts +2 -0
- package/dist/xstate-persist.cjs.d.ts +2 -0
- package/dist/xstate-persist.cjs.js +314 -0
- package/dist/xstate-persist.cjs.mjs +6 -0
- package/dist/xstate-persist.development.cjs.js +325 -0
- package/dist/xstate-persist.development.cjs.mjs +6 -0
- package/dist/xstate-persist.development.esm.js +319 -0
- package/dist/xstate-persist.esm.js +308 -0
- package/dist/xstate-persist.umd.min.js +2 -0
- package/dist/xstate-persist.umd.min.js.map +1 -0
- package/dist/xstate-validation.cjs.d.mts +2 -0
- package/dist/xstate-validation.cjs.d.ts +2 -0
- package/dist/xstate-validation.cjs.js +330 -0
- package/dist/xstate-validation.cjs.mjs +5 -0
- package/dist/xstate-validation.development.cjs.js +330 -0
- package/dist/xstate-validation.development.cjs.mjs +5 -0
- package/dist/xstate-validation.development.esm.js +324 -0
- package/dist/xstate-validation.esm.js +324 -0
- package/dist/xstate-validation.umd.min.js +2 -0
- package/dist/xstate-validation.umd.min.js.map +1 -0
- package/dist/xstate.cjs.js +2486 -1430
- package/dist/xstate.cjs.mjs +23 -13
- package/dist/xstate.development.cjs.js +2486 -1430
- package/dist/xstate.development.cjs.mjs +23 -13
- package/dist/xstate.development.esm.js +2445 -1398
- package/dist/xstate.esm.js +2445 -1398
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/docs/actions.md +75 -0
- package/docs/actor-logic.md +250 -0
- package/docs/actors.md +64 -0
- package/docs/agents.md +132 -0
- package/docs/api-stability.json +4287 -0
- package/docs/async-logic.md +75 -0
- package/docs/async-requests.md +157 -0
- package/docs/backend-workflows.md +124 -0
- package/docs/cancellation.md +42 -0
- package/docs/cheatsheet.md +563 -0
- package/docs/choice-states.md +109 -0
- package/docs/choose-xstate.md +47 -0
- package/docs/configuration.md +161 -0
- package/docs/context.md +67 -0
- package/docs/create-actor.md +159 -0
- package/docs/data-and-effects.md +48 -0
- package/docs/delays.md +81 -0
- package/docs/durable-execution.md +520 -0
- package/docs/emitted-events.md +146 -0
- package/docs/errors.md +812 -0
- package/docs/examples.md +75 -0
- package/docs/faq.md +60 -0
- package/docs/final-states.md +149 -0
- package/docs/forms-and-wizards.md +166 -0
- package/docs/frameworks.md +69 -0
- package/docs/fsm.md +164 -0
- package/docs/glossary.md +68 -0
- package/docs/guards.md +137 -0
- package/docs/history-states.md +161 -0
- package/docs/how-xstate-runs-machines.md +86 -0
- package/docs/index.md +74 -0
- package/docs/input-output.md +69 -0
- package/docs/inspect-actor-systems.md +118 -0
- package/docs/inspection.md +75 -0
- package/docs/internal-events.md +156 -0
- package/docs/invoke.md +371 -0
- package/docs/lifecycle-and-errors.md +48 -0
- package/docs/listen-and-subscribe.md +126 -0
- package/docs/model-based-testing.md +321 -0
- package/docs/modeling.md +40 -0
- package/docs/parallel-states.md +182 -0
- package/docs/persist-and-restore-actors.md +120 -0
- package/docs/persistence.md +312 -0
- package/docs/quick-start.md +55 -0
- package/docs/retries-and-timeouts.md +122 -0
- package/docs/route-states.md +104 -0
- package/docs/scxml.md +92 -0
- package/docs/selectors.md +99 -0
- package/docs/serialization.md +127 -0
- package/docs/setup-and-provide.md +273 -0
- package/docs/snapshots.md +134 -0
- package/docs/spawn.md +212 -0
- package/docs/state-input.md +162 -0
- package/docs/statecharts.md +54 -0
- package/docs/states-events-transitions.md +82 -0
- package/docs/states.md +168 -0
- package/docs/system-transitions.md +172 -0
- package/docs/systems.md +166 -0
- package/docs/testing.md +152 -0
- package/docs/timeouts.md +125 -0
- package/docs/transition-functions.md +89 -0
- package/docs/transitions.md +187 -0
- package/docs/troubleshooting.md +56 -0
- package/docs/tutorial.md +481 -0
- package/docs/typescript.md +213 -0
- package/docs/typestates.md +112 -0
- package/docs/utilities.md +39 -0
- package/docs/why-state-machines.md +59 -0
- package/docs/xstate-v5-to-v6.md +1923 -0
- package/docs/your-first-machine.md +79 -0
- package/durable/package.json +8 -0
- package/fsm/package.json +8 -0
- package/package.json +72 -10
- package/persist/package.json +8 -0
- package/validation/package.json +8 -0
- package/actions/package.json +0 -8
- package/dev/package.json +0 -8
- package/dist/StateMachine-0aa98f54.development.esm.js +0 -746
- package/dist/StateMachine-aef700df.cjs.js +0 -732
- package/dist/StateMachine-d4931336.esm.js +0 -729
- package/dist/StateMachine-da872dde.development.cjs.js +0 -749
- package/dist/declarations/src/createMachineFromConfig.d.ts +0 -177
- package/dist/declarations/src/getNextSnapshot.d.ts +0 -37
- package/dist/declarations/src/graph/TestModel.d.ts +0 -70
- package/dist/declarations/src/graph/pathGenerators.d.ts +0 -4
- package/dist/index-219cb621.development.cjs.js +0 -4476
- package/dist/index-2f2fbd9b.development.esm.js +0 -4421
- package/dist/index-559ceab3.cjs.js +0 -4437
- package/dist/index-8828376f.esm.js +0 -4382
- package/guards/package.json +0 -8
- package/invoke/package.json +0 -4
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Actor snapshots
|
|
3
|
+
description: Read and observe actor state.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
An actor snapshot describes the actor at one point in time.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
const subscription = actor.subscribe((snapshot) => {
|
|
10
|
+
console.log(snapshot.status);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
actor.start();
|
|
14
|
+
subscription.unsubscribe();
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`getSnapshot()` reads the current snapshot without subscribing. `subscribe(...)` observes future snapshots. A subscription created before `start()` also receives the initial snapshot.
|
|
18
|
+
|
|
19
|
+
Use a snapshot to render a checkout step or upload progress. Machine snapshots also carry `value`, `context`, `children` and helpers such as `matches(...)` and `can(...)`; see [states](states.md) for the full member list.
|
|
20
|
+
|
|
21
|
+
## Status
|
|
22
|
+
|
|
23
|
+
Every snapshot has a `status`.
|
|
24
|
+
|
|
25
|
+
| Status | Meaning | Set by |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| `active` | The actor is running and can receive events. | Creating and starting the actor. |
|
|
28
|
+
| `done` | The actor completed. `output` is set. | Reaching a top-level [final state](final-states.md), or the logic resolving. |
|
|
29
|
+
| `error` | The actor failed. `error` is set. | An uncaught error in a transition function, action or invoked actor. |
|
|
30
|
+
| `stopped` | The actor was stopped before completing. | `actor.stop()`, or its parent stopping it when a state is exited. |
|
|
31
|
+
|
|
32
|
+
`done`, `error` and `stopped` are terminal: the actor no longer processes events, its children and timers are disposed, and its observers are completed or errored. The pure [`transition(...)`](utilities.md) function treats every event on a terminal snapshot as unhandled: it returns the same snapshot and no effects.
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
const snapshot = actor.getSnapshot();
|
|
36
|
+
|
|
37
|
+
if (snapshot.status === 'done') {
|
|
38
|
+
console.log(snapshot.output);
|
|
39
|
+
} else if (snapshot.status === 'error') {
|
|
40
|
+
console.error(snapshot.error);
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`output` is only defined for `done` snapshots, and `error` only for `error` snapshots. TypeScript narrows both from `status`.
|
|
45
|
+
|
|
46
|
+
## Immutability and identity
|
|
47
|
+
|
|
48
|
+
Snapshots are never mutated. Each transition produces a new snapshot object, so a previously captured snapshot keeps describing the moment it was read.
|
|
49
|
+
|
|
50
|
+
An event that takes no transition produces no new object: subscribers are still notified, with the same snapshot reference as before.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const before = actor.getSnapshot();
|
|
54
|
+
actor.send({ type: 'unhandled' });
|
|
55
|
+
actor.getSnapshot() === before; // true
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
This makes reference equality a valid re-render check in UI bindings. For finer-grained comparisons, use [selectors](selectors.md).
|
|
59
|
+
|
|
60
|
+
## Waiting for a snapshot
|
|
61
|
+
|
|
62
|
+
`waitFor(...)` resolves with the first snapshot that satisfies a predicate, including the current one.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { waitFor } from 'xstate';
|
|
66
|
+
|
|
67
|
+
const snapshot = await waitFor(actor, (snapshot) =>
|
|
68
|
+
snapshot.matches('ready')
|
|
69
|
+
);
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
| Option | Default | Description |
|
|
73
|
+
| --- | --- | --- |
|
|
74
|
+
| `timeout` | `Infinity` | Milliseconds before rejecting with a timeout error. |
|
|
75
|
+
| `signal` | none | An `AbortSignal` that stops waiting and rejects with the signal's reason. |
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
const snapshot = await waitFor(actor, (snapshot) => snapshot.hasTag('loaded'), {
|
|
79
|
+
timeout: 5_000,
|
|
80
|
+
signal: request.signal
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The promise also rejects if the actor errors, or if it terminates without ever satisfying the predicate. Use `waitFor(...)` in a test or a request handler that must block until the machine reaches a state.
|
|
85
|
+
|
|
86
|
+
To wait for completion instead of a specific state, use [`toPromise(actor)`](utilities.md), which resolves with the actor's [output](input-output.md) and rejects on error.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { toPromise } from 'xstate';
|
|
90
|
+
|
|
91
|
+
const output = await toPromise(actor);
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Child snapshots
|
|
95
|
+
|
|
96
|
+
`snapshot.children` holds the actor's invoked and [spawned](spawn.md) children, keyed by their id. Each child is an actor reference with its own snapshot.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
const upload = actor.getSnapshot().children.upload;
|
|
100
|
+
|
|
101
|
+
upload?.getSnapshot().context.progress;
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Children appear while the state that owns them is active and disappear when it is exited, so read them defensively. `getPersistedSnapshot()` includes child state, so a restored actor restores its children too. See [persistence](persistence.md).
|
|
105
|
+
|
|
106
|
+
## TypeScript
|
|
107
|
+
|
|
108
|
+
Use `SnapshotFrom` to get the snapshot type for actor logic or an actor reference.
|
|
109
|
+
State-level context schemas provide [typestates](typestates.md):
|
|
110
|
+
`snapshot.matches(...)` narrows context to the matched state contracts.
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
import type { SnapshotFrom } from 'xstate';
|
|
114
|
+
|
|
115
|
+
type MachineSnapshot = SnapshotFrom<typeof machine>;
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Snapshots cheatsheet
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
actor.getSnapshot();
|
|
122
|
+
actor.getSnapshot().status;
|
|
123
|
+
actor.getSnapshot().output;
|
|
124
|
+
actor.getSnapshot().error;
|
|
125
|
+
actor.subscribe((snapshot) => console.log(snapshot));
|
|
126
|
+
actor.getSnapshot().can({ type: 'submit' });
|
|
127
|
+
actor.getSnapshot().children.upload?.getSnapshot();
|
|
128
|
+
|
|
129
|
+
await waitFor(actor, (snapshot) => snapshot.status === 'done');
|
|
130
|
+
await waitFor(actor, (snapshot) => snapshot.matches('ready'), {
|
|
131
|
+
timeout: 5_000
|
|
132
|
+
});
|
|
133
|
+
await toPromise(actor);
|
|
134
|
+
```
|
package/docs/spawn.md
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Spawn actors
|
|
3
|
+
description: Create child actors during a transition.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Use `enq.spawn(...)` when a child should outlive the state that created it, or when the number of children is dynamic.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
on: {
|
|
10
|
+
'file.added': ({ context, event }, enq) => {
|
|
11
|
+
const upload = enq.spawn(uploadLogic, {
|
|
12
|
+
id: `upload-${event.fileId}`,
|
|
13
|
+
input: { file: event.file }
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
return {
|
|
17
|
+
context: {
|
|
18
|
+
...context,
|
|
19
|
+
uploads: [...context.uploads, upload]
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`enq.spawn(source, options)` returns the [actor reference](actors.md) immediately, so the same transition can store it, send to it or subscribe to it. `source` may be registered actor logic or its registered name.
|
|
27
|
+
|
|
28
|
+
## Spawn options
|
|
29
|
+
|
|
30
|
+
| Option | Description |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| `id` | Identifier for the child, and its key in `snapshot.children`. Defaults to a deterministic generated id keyed by the actor source, such as `worker:0`. |
|
|
33
|
+
| `input` | [Input](input-output.md) for the child. Required when its logic requires input. |
|
|
34
|
+
| `registryKey` | Registers the child in the [actor registry](systems.md) under that key. |
|
|
35
|
+
| `syncSnapshot` | When `true`, each child snapshot is sent to the parent as an `xstate.snapshot.actor` event. |
|
|
36
|
+
|
|
37
|
+
Use a registered name when its durable source identity matters:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
entry: (_, enq) => {
|
|
41
|
+
enq.spawn('upload', { input: { file } });
|
|
42
|
+
};
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The name is checked against `actors`; its required input and returned actor reference are inferred from that entry. An unknown name is a type error. If a declared entry has not been implemented through the machine config, `provide(...)` or `extend(...)`, spawning it throws immediately.
|
|
46
|
+
|
|
47
|
+
Passing the logic value remains convenient: `enq.spawn(actors.upload, options)`. XState recovers its registered name when possible. Inline unregistered logic may run but cannot be durably persisted.
|
|
48
|
+
|
|
49
|
+
Spawning with an `id` that a live child of the same parent already uses throws: an address names at most one live actor. Stop the existing child first — an id stopped earlier in the same transition is free to reuse, and a child that completed on its own frees its id for the transition handling its completion. Generate ids from something stable, such as a file or participant id.
|
|
50
|
+
|
|
51
|
+
## Where you can spawn
|
|
52
|
+
|
|
53
|
+
`enq.spawn(...)` is available in every transition function: `entry`, `exit`, `on`, `always` and `after`. A child spawned in `exit` still starts, because the spawn is part of the transition, not part of the state being left.
|
|
54
|
+
|
|
55
|
+
The context initializer also receives a `spawn` function for children that exist from the start:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
const machine = createMachine({
|
|
59
|
+
actors: { connection },
|
|
60
|
+
context: ({ spawn, actors }) => ({
|
|
61
|
+
connection: spawn(actors.connection, { id: 'connection' })
|
|
62
|
+
})
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Spawn or invoke
|
|
67
|
+
|
|
68
|
+
Invoke a child when its lifetime matches a state: the state starts it on entry and stops it on exit. Spawn a child when the machine decides at runtime how many children exist and when each one stops. See [invoke or spawn](invoke.md#invoke-or-spawn) for a comparison.
|
|
69
|
+
|
|
70
|
+
## Referencing spawned children
|
|
71
|
+
|
|
72
|
+
Spawned children appear on `snapshot.children` under their `id` and are passed to transition functions as `children`:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
on: {
|
|
76
|
+
'upload.cancel': ({ children, event }, enq) => {
|
|
77
|
+
enq.sendTo(children[`upload-${event.fileId}`], { type: 'cancel' });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Store references in `context` instead when the machine needs its own ordering, grouping or metadata, such as an array of uploads rendered in order. Keep the context list and the children record in sync: `children` only reflects live actors.
|
|
83
|
+
|
|
84
|
+
## Stopping spawned actors
|
|
85
|
+
|
|
86
|
+
A spawned actor runs until it completes, until `enq.stop(ref)` stops it, or until the parent actor stops. Exiting the state that spawned it does not stop it.
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
on: {
|
|
90
|
+
'upload.remove': ({ context, event }, enq) => {
|
|
91
|
+
const upload = context.uploads.find((ref) => ref.id === event.id);
|
|
92
|
+
enq.stop(upload);
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
context: {
|
|
96
|
+
...context,
|
|
97
|
+
uploads: context.uploads.filter((ref) => ref !== upload)
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`enq.stop(ref)` removes the child from `snapshot.children` in the same transition. Remove the stored reference from context at the same time, otherwise the machine holds a reference to a stopped actor. A machine can only stop its own children; stopping any other actor reference errors.
|
|
105
|
+
|
|
106
|
+
## Communicating with spawned actors
|
|
107
|
+
|
|
108
|
+
Send events to a child with `enq.sendTo(ref, event)`. A child machine sends events back through its `parent` argument:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
const uploadMachine = createMachine({
|
|
112
|
+
on: {
|
|
113
|
+
progress: ({ parent, event }, enq) => {
|
|
114
|
+
enq.sendTo(parent, { type: 'uploadProgress', value: event.value });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Spawned children have no `onDone` or `onError`. Subscribe to their outcome instead:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
entry: (_, enq) => {
|
|
124
|
+
const upload = enq.spawn(uploadLogic, { id: 'upload' });
|
|
125
|
+
|
|
126
|
+
enq.subscribeTo(upload, {
|
|
127
|
+
done: (output) => ({ type: 'uploadFinished', output }),
|
|
128
|
+
error: (error) => ({ type: 'uploadFailed', error })
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
enq.listen(upload, 'upload.*', (event) => ({
|
|
132
|
+
type: 'uploadEvent',
|
|
133
|
+
eventType: event.type
|
|
134
|
+
}));
|
|
135
|
+
};
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
<!-- enq.listen and enq.subscribeTo behavior from packages/core/src/stateUtils.ts and packages/core/src/transitionActions.ts -->
|
|
139
|
+
|
|
140
|
+
`enq.listen(...)` maps [emitted events](emitted-events.md), while
|
|
141
|
+
`enq.subscribeTo(...)` maps snapshots and outcomes. Both return an actor that
|
|
142
|
+
can be stopped with `enq.stop(...)`, and both work in transition, `entry` and
|
|
143
|
+
`exit` functions. See [listen and subscribe](listen-and-subscribe.md).
|
|
144
|
+
|
|
145
|
+
`syncSnapshot: true` is the lower-level alternative: the parent then receives `xstate.snapshot.actor` events that it can handle with `matches: { actorId }`.
|
|
146
|
+
|
|
147
|
+
## Persistence
|
|
148
|
+
|
|
149
|
+
<!-- registered spawn source persistence behavior from packages/core/src/spawn.ts, packages/core/src/transitionActions.ts, and packages/core/src/StateMachine.ts -->
|
|
150
|
+
|
|
151
|
+
Children spawned from sources registered in `actors` are persisted and restored with the parent snapshot. The context initializer accepts registered logic. Transition functions additionally accept its typed name:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const machine = createMachine({
|
|
155
|
+
actors: { connection },
|
|
156
|
+
context: ({ spawn, actors }) => ({
|
|
157
|
+
connection: spawn(actors.connection, { id: 'connection' })
|
|
158
|
+
}),
|
|
159
|
+
on: {
|
|
160
|
+
reconnect: (_, enq) => {
|
|
161
|
+
enq.spawn('connection', { id: 'replacement' });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Each child records `src: 'connection'`, which `restoreActor(machine, persisted)` resolves back to the currently registered logic. `provide(...)` may replace that implementation under the same source key. Restoring a snapshot whose child source is not registered fails instead of silently dropping the child.
|
|
168
|
+
|
|
169
|
+
Register persistent child logic in `actors`. Spawning inline logic that is not registered works while the parent is running, but `getPersistedSnapshot()` throws `An inline child actor cannot be persisted.` while that child exists.
|
|
170
|
+
|
|
171
|
+
Several source keys may share one logic object. `enq.spawn('second')` records exactly `src: 'second'`, so implementations under those names may diverge through `provide(...)`, `extend(...)` or a later machine version. Passing the shared logic value instead uses the first registered key as its canonical source identity.
|
|
172
|
+
|
|
173
|
+
## TypeScript
|
|
174
|
+
|
|
175
|
+
`enq.spawn(...)` returns an actor reference typed from the selected source or logic, and requires `input` when it requires input. Type references stored in context with `ActorRefFrom`:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
const machine = createMachine({
|
|
179
|
+
schemas: {
|
|
180
|
+
context: z.object({
|
|
181
|
+
uploads: z.custom<ActorRefFrom<typeof uploadLogic>[]>()
|
|
182
|
+
})
|
|
183
|
+
},
|
|
184
|
+
context: { uploads: [] }
|
|
185
|
+
});
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Declare `schemas.children` to type the `children` record for known ids:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
schemas: {
|
|
192
|
+
children: {
|
|
193
|
+
connection: z.custom<ActorRefFrom<typeof connection>>()
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`children.connection` is then typed, unknown keys are type errors, and
|
|
199
|
+
`enq.sendTo('connection', event)` checks the event against the declared actor
|
|
200
|
+
ref. Dynamic children keyed by a runtime id stay typed through their returned
|
|
201
|
+
refs or refs stored in context.
|
|
202
|
+
|
|
203
|
+
## Spawn cheatsheet
|
|
204
|
+
|
|
205
|
+
```ts
|
|
206
|
+
const child = enq.spawn(logic, { id, input, registryKey, syncSnapshot: true });
|
|
207
|
+
const durableChild = enq.spawn('registeredSource', { id, input });
|
|
208
|
+
enq.sendTo(child, { type: 'start' });
|
|
209
|
+
enq.sendTo('connection', { type: 'start' });
|
|
210
|
+
enq.subscribeTo(child, { done: (output) => ({ type: 'finished', output }) });
|
|
211
|
+
enq.stop(child);
|
|
212
|
+
```
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: State input
|
|
3
|
+
description: Pass typed data to a state when it is entered.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
A state can declare an input schema. Transitions that target the state pass `input` alongside `target`, and the state's own functions read it from their arguments.
|
|
7
|
+
|
|
8
|
+
Declare the schema in `setup(...)`:
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
const uploadSetup = setup({
|
|
12
|
+
states: {
|
|
13
|
+
idle: {},
|
|
14
|
+
uploading: {
|
|
15
|
+
schemas: { input: z.object({ fileName: z.string() }) }
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Then pass `input` from the transition:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
const uploadMachine = uploadSetup.createMachine({
|
|
25
|
+
initial: 'idle',
|
|
26
|
+
states: {
|
|
27
|
+
idle: {
|
|
28
|
+
on: {
|
|
29
|
+
upload: { target: 'uploading', input: { fileName: 'report.pdf' } }
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
uploading: {
|
|
33
|
+
entry: ({ input }) => console.log(input.fileName)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
<!-- state input replacement behavior from packages/core/src/stateUtils.ts and packages/core/test/stateInput.test.ts -->
|
|
40
|
+
|
|
41
|
+
State input is available to the target state's `entry`, `exit`, `on`, `after`, `timeout`, `onTimeout` and `output` functions. An invoked actor's `invoke.input` function also receives the state input, so it can adapt the state data to the actor's input contract. A transition's `input` takes effect only when its target state is entered. A non-reentering transition to an already-active state preserves that state's current input; set `reenter: true` to exit and enter the state again with the new input.
|
|
42
|
+
|
|
43
|
+
## Computing input
|
|
44
|
+
|
|
45
|
+
A transition function can compute input from context and the event.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
idle: {
|
|
49
|
+
on: {
|
|
50
|
+
upload: ({ context, event }) => ({
|
|
51
|
+
target: 'uploading',
|
|
52
|
+
input: { fileName: event.fileName, token: context.authToken }
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Initial state input
|
|
59
|
+
|
|
60
|
+
The `initial` property accepts an object form so the initial state receives input too. A plain string is still used when the state needs none.
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
uploadSetup.createMachine({
|
|
64
|
+
initial: { target: 'uploading', input: { fileName: 'report.pdf' } },
|
|
65
|
+
states: {
|
|
66
|
+
uploading: { entry: ({ input }) => console.log(input.fileName) }
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Nested states work the same way: a parent's `initial` passes input to its child.
|
|
72
|
+
|
|
73
|
+
## Multiple targets
|
|
74
|
+
|
|
75
|
+
XState applies one transition `input` to every target in a target array. When
|
|
76
|
+
setup declares input schemas for those targets, the input must satisfy all of
|
|
77
|
+
them:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
target: ['active.left.ready', 'active.right.ready'],
|
|
81
|
+
input: { leftId: 1, rightId: true }
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Each target's descendants still receive their own input from their normal
|
|
85
|
+
`initial` transitions. Widened target arrays remain compatible with existing
|
|
86
|
+
configurations.
|
|
87
|
+
|
|
88
|
+
## Input lifetime
|
|
89
|
+
|
|
90
|
+
State input lasts as long as its state is active. When the state exits, its input is removed, along with the inputs of its child states. Entering the state again without `input` gives it no input; the previous value does not come back.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const machine = createMachine({
|
|
94
|
+
initial: 'idle',
|
|
95
|
+
states: {
|
|
96
|
+
idle: {
|
|
97
|
+
on: {
|
|
98
|
+
UPLOAD: { target: 'uploading', input: { fileName: 'report.pdf' } }
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
uploading: {
|
|
102
|
+
on: { CANCEL: { target: 'idle' } }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const actor = createActor(machine).start();
|
|
108
|
+
actor.send({ type: 'UPLOAD' });
|
|
109
|
+
actor.getSnapshot().getInputs(); // { 'uploading': { fileName: 'report.pdf' } }
|
|
110
|
+
|
|
111
|
+
actor.send({ type: 'CANCEL' });
|
|
112
|
+
actor.getSnapshot().getInputs(); // {}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Persisted snapshots only include inputs for active states.
|
|
116
|
+
|
|
117
|
+
## Reading input from a snapshot
|
|
118
|
+
|
|
119
|
+
`snapshot.getInputs()` returns the current inputs keyed by state node ID.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
const inputs = actor.getSnapshot().getInputs();
|
|
123
|
+
inputs['uploading']; // { fileName: 'report.pdf' }
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Use state input for data that belongs to one state rather than to the whole machine:
|
|
127
|
+
|
|
128
|
+
- a checkout `paying` state that needs the selected payment method
|
|
129
|
+
- a media player `buffering` state that needs the track being loaded
|
|
130
|
+
- a form `submitting` state that needs the validated values
|
|
131
|
+
|
|
132
|
+
> **Warning:** State input is not [actor input](input-output.md), which is passed once when an actor is created, and it is not action `params`, which belong to a named action call. State input belongs to a state and is provided by whichever transition enters it.
|
|
133
|
+
|
|
134
|
+
## TypeScript
|
|
135
|
+
|
|
136
|
+
Input is typed by the state's `schemas.input`. Transitions targeting the state require a matching `input`, and `({ input })` is typed inside that state's functions, including `invoke.input`. Modular state configs created with `setup(...).createStateConfig(...)` are typed the same way. See [setup and provide](setup-and-provide.md).
|
|
137
|
+
|
|
138
|
+
## State input cheatsheet
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
const s = setup({
|
|
142
|
+
states: { loading: { schemas: { input: z.object({ id: z.string() }) } } }
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
s.createMachine({
|
|
146
|
+
initial: { target: 'loading', input: { id: 'a1' } },
|
|
147
|
+
states: {
|
|
148
|
+
loading: {
|
|
149
|
+
entry: ({ input }) => input.id,
|
|
150
|
+
on: {
|
|
151
|
+
retry: {
|
|
152
|
+
target: 'loading',
|
|
153
|
+
reenter: true,
|
|
154
|
+
input: { id: 'a2' }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
actor.getSnapshot().getInputs();
|
|
162
|
+
```
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Statecharts
|
|
3
|
+
description: Model nested, parallel and historical state.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Statecharts extend state machines with ways to organize complex states.
|
|
7
|
+
|
|
8
|
+
## Parent states
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
playing: {
|
|
12
|
+
initial: 'normal',
|
|
13
|
+
states: {
|
|
14
|
+
normal: { on: { mute: { target: 'muted' } } },
|
|
15
|
+
muted: { on: { unmute: { target: 'normal' } } }
|
|
16
|
+
},
|
|
17
|
+
on: { stop: { target: 'stopped' } }
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The `stop` transition applies to every child of `playing`.
|
|
22
|
+
|
|
23
|
+
## Parallel states
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
active: {
|
|
27
|
+
type: 'parallel',
|
|
28
|
+
states: {
|
|
29
|
+
playback: { initial: 'playing', states: { playing: {}, paused: {} } },
|
|
30
|
+
volume: { initial: 'audible', states: { audible: {}, muted: {} } }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## History states
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
history: { type: 'history', target: 'normal' }
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Target the history state when returning to its parent. The default `target` is used when there is no recorded history.
|
|
42
|
+
|
|
43
|
+
## Real examples
|
|
44
|
+
|
|
45
|
+
A media player can use parallel regions for playback and volume. Pausing playback does not mute audio, and muting audio does not change the playback state.
|
|
46
|
+
|
|
47
|
+
A checkout can use a parent `payment` state with `editingCard`, `authorizing` and `declined` children. A `cancel` transition on `payment` applies to every child.
|
|
48
|
+
|
|
49
|
+
History is useful when a user temporarily leaves a multi-step form or a media player reconnects and should return to its previous mode.
|
|
50
|
+
|
|
51
|
+
## What next?
|
|
52
|
+
|
|
53
|
+
- [Final states](final-states.md), [history states](history-states.md), and [parallel states](parallel-states.md) for the full reference on each.
|
|
54
|
+
- [How XState runs your machine](how-xstate-runs-machines.md) for how nested and parallel states process events.
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: States, events and transitions
|
|
3
|
+
description: Learn the three parts of a state machine.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
A state machine describes states and the events that move the machine between them.
|
|
7
|
+
|
|
8
|
+
## States
|
|
9
|
+
|
|
10
|
+
A state describes how something behaves now. Good state names describe a mode or status, such as `loading`, `playing` or `awaitingPayment`.
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
const machine = createMachine({
|
|
14
|
+
initial: 'idle',
|
|
15
|
+
states: {
|
|
16
|
+
idle: {},
|
|
17
|
+
loading: {},
|
|
18
|
+
success: {},
|
|
19
|
+
failure: {}
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The initial state is entered when an actor starts.
|
|
25
|
+
|
|
26
|
+
## Events
|
|
27
|
+
|
|
28
|
+
An event describes something that happened.
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
actor.send({ type: 'load' });
|
|
32
|
+
actor.send({ type: 'cancel' });
|
|
33
|
+
actor.send({ type: 'search', query: 'state machines' });
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Events are objects with a `type` property. They can also contain data.
|
|
37
|
+
|
|
38
|
+
## Transitions
|
|
39
|
+
|
|
40
|
+
A transition describes how a state responds to an event.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
loading: {
|
|
44
|
+
on: {
|
|
45
|
+
cancel: { target: 'idle' },
|
|
46
|
+
resolved: { target: 'success' },
|
|
47
|
+
rejected: { target: 'failure' }
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The same event can have different meanings in different states. An event with no matching transition is ignored.
|
|
53
|
+
|
|
54
|
+
## Transition functions
|
|
55
|
+
|
|
56
|
+
Use a transition function when the result depends on context or event data.
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
on: {
|
|
60
|
+
submit: ({ context }) => {
|
|
61
|
+
if (!context.email) return;
|
|
62
|
+
return { target: 'submitting' };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Returning `undefined` without enqueuing anything prevents the transition. Keep transition functions deterministic.
|
|
68
|
+
|
|
69
|
+
Functions keep conditions, typed updates and effects together. See [transition functions and graph analysis](transition-functions.md) for the benefits and the distinction between valid targets, graph coverage and reachability.
|
|
70
|
+
|
|
71
|
+
## Real examples
|
|
72
|
+
|
|
73
|
+
In a checkout, `submit` can move `reviewing` to `paying`. The same event is ignored while payment is already in progress. `paymentSucceeded` and `paymentFailed` only matter in `paying`.
|
|
74
|
+
|
|
75
|
+
In a media player, `play` can move `paused` to `playing`. While the player is `buffering`, `play` may do nothing until a `bufferReady` event arrives.
|
|
76
|
+
|
|
77
|
+
Use event data for facts about what happened:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
actor.send({ type: 'paymentFailed', reason: 'card_declined' });
|
|
81
|
+
actor.send({ type: 'bufferReady', duration: 184 });
|
|
82
|
+
```
|