@sanity-labs/xstate-react 0.2.0 → 0.3.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 CHANGED
@@ -1,20 +1,19 @@
1
1
  # @sanity-labs/xstate-react
2
2
 
3
- React bindings for [XState](https://stately.ai/docs) v6, built on React's async APIs: sending an event is a transition, so machine updates render together with the transition they belong to, and controlled inputs stay in sync through `useOptimistic`.
3
+ React bindings for [XState](https://stately.ai/docs) v6, built on React's async APIs. There is one hook, `useActor`. Every snapshot change renders in a transition, and `send` sends in a transition, so machine updates render together with the transition they belong to.
4
4
 
5
- The snapshot lives in React state instead of an external store read with `useSyncExternalStore`, which would turn every transition that changes the actor into a blocking update. One component subscribes to each actor and passes the snapshot down, so every reader renders the same snapshot in the same commit.
5
+ The snapshot lives in React state instead of an external store read with `useSyncExternalStore`, which would turn every transition that changes the actor into a blocking update. The component that calls `useActor` is the only subscriber, and passes the snapshot down, so every reader renders the same snapshot in the same commit.
6
6
 
7
7
  ## Requirements
8
8
 
9
- - `react` and `react-dom` `^19.3`. `addTransitionType` is stable from React 19.3.
10
- - `xstate` `^6.0.0-beta`.
9
+ - `react` and `react-dom` `^19.3.1`.
10
+ - `xstate` `^6.0.0-beta`. Machines from `xstate` and from `xstate/fsm` both work.
11
+ - The [React Compiler](https://react.dev/learn/react-compiler). The hook returns a new tuple on every render and doesn't memoize what you derive from the snapshot: the compiler does.
11
12
 
12
13
  ```sh
13
14
  pnpm add @sanity-labs/xstate-react xstate@beta
14
15
  ```
15
16
 
16
- The hooks have the same names and signatures as `@xstate/react` for XState v6.
17
-
18
17
  ## Usage
19
18
 
20
19
  ```tsx
@@ -31,7 +30,7 @@ const counterMachine = createMachine({
31
30
  })
32
31
 
33
32
  function Counter() {
34
- const [snapshot, send, actor] = useActor(counterMachine)
33
+ const [snapshot, send] = useActor(counterMachine)
35
34
  return (
36
35
  <button type="button" onClick={() => send({type: 'inc'})}>
37
36
  {snapshot.context.count}
@@ -40,43 +39,35 @@ function Counter() {
40
39
  }
41
40
  ```
42
41
 
43
- - `useActor(logic, options)` creates an actor, starts it, and returns `[snapshot, send, actor]`. `useMachine` is a deprecated alias.
44
- - `useActorRef(logic, options)` creates and starts an actor without subscribing to its snapshot.
45
- - `useSelector(actor, selector, compare?)` reads a value derived from the snapshot, and returns the previous value while `compare` says it is unchanged. `shallowEqual` is exported for use as `compare`.
46
- - `useSend(actor)` returns the same `send` that `useActor` returns, for an actor created with `useActorRef` or received as a prop.
47
- - `useOptimisticSend(actor)` returns a `send` for updates that must show right away, like a controlled input's `onChange`.
48
- - `createActorContext(logic, options)` returns `{Provider, useSelector, useSend, useOptimisticSend, useActorRef}` for sharing one actor with a subtree.
49
-
50
- ### Sharing an actor
42
+ `useActor(logic, options)` creates an actor from `logic`, starts it when the component mounts, stops it when it unmounts, and returns `[snapshot, send]`. `options` are the actor's options, like `input`. They are read once, when the actor is created.
51
43
 
52
- `createActorContext` is the way to read one actor in many components. Its `Provider` is the only component that subscribes to the actor. It holds the snapshot in state and passes it down through context, so a component that mounts while a transition is changing the actor renders the same snapshot as the rest of the tree.
44
+ `xstate/fsm` machines are logic too:
53
45
 
54
46
  ```tsx
55
- import {createActorContext} from '@sanity-labs/xstate-react'
56
-
57
- const Counter = createActorContext(counterMachine)
47
+ import {useActor} from '@sanity-labs/xstate-react'
48
+ import {createFSM} from 'xstate/fsm'
58
49
 
59
- function Count() {
60
- const count = Counter.useSelector((snapshot) => snapshot.context.count)
61
- return <output>{count}</output>
62
- }
50
+ const toggleMachine = createFSM({
51
+ initial: 'inactive',
52
+ states: {
53
+ inactive: {on: {toggle: {target: 'active'}}},
54
+ active: {on: {toggle: {target: 'inactive'}}},
55
+ },
56
+ })
63
57
 
64
- function App() {
65
- return (
66
- <Counter.Provider>
67
- <Count />
68
- </Counter.Provider>
69
- )
58
+ function Toggle() {
59
+ const [snapshot, send] = useActor(toggleMachine)
60
+ return <button onClick={() => send({type: 'toggle'})}>{snapshot.value}</button>
70
61
  }
71
62
  ```
72
63
 
73
- A reader re-renders whenever the snapshot changes, because React has no way to select from a context. `useSelector` returns the previous value while `compare` says it is unchanged, so with the [React Compiler](https://react.dev/learn/react-compiler), or `memo`, what the reader renders bails out. `useSelector(actor, …)` with the provided actor reads from the provider too.
64
+ ### Sharing a snapshot
74
65
 
75
- Outside a provider, `useSelector(actor, …)` subscribes to the actor itself and re-renders only when the selection changes. Each such hook is a subscriber of its own, so a component that mounts during a transition can render a newer snapshot than the components that are waiting for that transition. Use a provider when several components read the same actor.
66
+ Pass the snapshot, or values derived from it, and `send` down as props, or through a context of your own. Readers then render the snapshot the owner holds, so a component that mounts while a transition is changing the actor renders the same snapshot as the rest of the tree.
76
67
 
77
68
  ### The first machine, and `key` to start over
78
69
 
79
- The machine passed on the first render is used for the component's lifetime, and `input` is read once. Implementations passed with `machine.provide()` are picked up on every render, so they can close over props and state:
70
+ The machine passed on the first render is used for the component's lifetime, and `options` are read once. Implementations passed with `machine.provide()` are picked up on every render, so they can close over props and state:
80
71
 
81
72
  ```tsx
82
73
  import {useActor} from '@sanity-labs/xstate-react'
@@ -104,7 +95,7 @@ function Stepper({start, limit}: {start: number; limit: number}) {
104
95
  }
105
96
  ```
106
97
 
107
- To start over with fresh `input`, or to switch to a different machine, give the component a new `key`. React then unmounts it, stops its actor, and mounts a new one:
98
+ To reset, give the component a new `key`, as you would to reset `useState`. React then unmounts it, stops its actor, and mounts a new one with fresh `input`:
108
99
 
109
100
  ```tsx
110
101
  <Stepper key={documentId} start={1} limit={10} />
@@ -116,34 +107,36 @@ The same goes for switching machines:
116
107
  <Editor key={mode} machine={mode === 'draft' ? draftMachine : reviewMachine} />
117
108
  ```
118
109
 
119
- ### Restoring an actor
110
+ ### Restoring a persisted actor
120
111
 
121
- The hooks also take an actor that is already created, for example one restored from a persisted snapshot. Create it once, in a `useState` initializer, so it isn't recreated on every render:
112
+ `useActor` also takes an actor you created, like one from `restoreActor`. Create it once, in `useState`'s initializer, so later renders don't create another:
122
113
 
123
114
  ```tsx
124
115
  import {useActor} from '@sanity-labs/xstate-react'
125
116
  import {useState} from 'react'
126
- import type {SnapshotFrom} from 'xstate'
117
+ import type {Snapshot} from 'xstate'
127
118
  import {restoreActor} from 'xstate/persist'
128
119
 
129
- function Editor({persisted}: {persisted: SnapshotFrom<typeof editorMachine>}) {
130
- const [actor] = useState(() => restoreActor(editorMachine, persisted))
120
+ function Checkout({persisted}: {persisted: Snapshot<unknown>}) {
121
+ const [actor] = useState(() => restoreActor(checkoutMachine, persisted))
131
122
  const [snapshot, send] = useActor(actor)
132
123
  // ...
133
124
  }
134
125
  ```
135
126
 
127
+ The hook starts and stops the actor you pass, as it does one it creates, and its snapshot changes render as transitions too. The actor passed on the first render is used for the component's lifetime: to restore a different snapshot, change the component's `key`. Pass it options, like `input`, when you create it, since `useActor` takes no options with an actor.
128
+
136
129
  ### Starting and stopping
137
130
 
138
- The actor starts when the component mounts and stops when it unmounts. Stopping waits a microtask, so the unmount and remount that `StrictMode` simulates keep the running actor. v6 actors can't be restarted once stopped, so when a stopped actor's component is shown again, the hooks create a fresh actor from the same machine.
131
+ The actor starts when the component mounts and stops when it unmounts. Stopping waits a microtask, so the unmount and remount that `StrictMode` simulates keep the running actor. v6 actors can't be restarted once stopped, so when a stopped actor's component is shown again, the hook creates a fresh actor from the same machine. For an actor you passed, the fresh actor is created with the same options, so one from `restoreActor` starts again from the snapshot it restored, not from where the stopped actor left off.
139
132
 
140
- `<Activity mode="hidden">` cleans up effects, so an actor that a hidden component owns stops, and the component starts over with a fresh actor when it's shown again. To keep an actor running while part of the tree is hidden, own it above the `Activity` boundary, for example with a `createActorContext` provider.
133
+ `<Activity mode="hidden">` cleans up effects, so an actor that a hidden component owns stops, and the component starts over with a fresh actor when it's shown again. To keep an actor running while part of the tree is hidden, call `useActor` above the `Activity` boundary and pass the snapshot down.
141
134
 
142
135
  ### Transitions
143
136
 
144
- `send` is a transition. The snapshot change it causes renders in the background, so a part of the tree that suspends on it keeps showing the previous snapshot instead of falling back to a `Suspense` boundary. Read `isPending` from `useTransition` to show that work is in progress.
137
+ Every snapshot change renders as a transition: the one that sent the event, or a transition of its own. That includes changes `send` didn't cause, like delayed transitions, invoked actors settling and events from child actors. So a part of the tree that suspends on a change keeps showing the previous snapshot instead of falling back to a `Suspense` boundary, and no change reveals a transition that is still suspended. Read `isPending` from `useTransition` to show that work is in progress.
145
138
 
146
- Called inside `startTransition`, `send` joins that transition, including its `addTransitionType` types, so `<ViewTransition>` can animate the change. Events sent with `actor.send` or `actor.trigger` inside `startTransition` join it too:
139
+ Called inside `startTransition`, `send` joins that transition, including its `addTransitionType` types, so `<ViewTransition>` can animate the change:
147
140
 
148
141
  ```tsx
149
142
  import {useActor} from '@sanity-labs/xstate-react'
@@ -183,54 +176,49 @@ startTransition(async () => {
183
176
  })
184
177
  ```
185
178
 
186
- ### Controlled inputs
179
+ ### UI that must update right away
187
180
 
188
- A controlled input has to show what was typed right away, but a transition renders later. Send its events with `useOptimisticSend`: the event's outcome is computed with XState's `transition()` and shown with `useOptimistic` until the transition renders, so the input keeps its value and caret. A pending transition that suspends stays hidden, because the preview is computed from the snapshot React has committed:
181
+ A controlled input has to show what was typed right away, but a transition renders later. Keep that value with React's `useOptimistic` in the component that renders it, and send the event from the action that sets it. This is the action prop pattern of the [Async React demo](https://github.com/rickhanlonii/async-react)'s `SearchInput`, `TabList` and `CompleteButton`:
189
182
 
190
183
  ```tsx
191
- import {useActor, useOptimisticSend} from '@sanity-labs/xstate-react'
192
-
193
- function Search() {
194
- const [snapshot, , actor] = useActor(searchMachine)
195
- const send = useOptimisticSend(actor)
184
+ import {useActor} from '@sanity-labs/xstate-react'
185
+ import {startTransition, useOptimistic} from 'react'
186
+
187
+ function SearchInput({
188
+ value,
189
+ changeAction,
190
+ }: {
191
+ value: string
192
+ changeAction: (value: string) => void | Promise<void>
193
+ }) {
194
+ const [inputValue, setInputValue] = useOptimistic(value)
196
195
  return (
197
196
  <input
198
- value={snapshot.context.query}
199
- onChange={(event) => send({type: 'query.change', query: event.target.value})}
197
+ value={inputValue}
198
+ data-pending={inputValue !== value}
199
+ onChange={(event) => {
200
+ const next = event.target.value
201
+ startTransition(async () => {
202
+ setInputValue(next)
203
+ await changeAction(next)
204
+ })
205
+ }}
200
206
  />
201
207
  )
202
208
  }
203
- ```
204
-
205
- A preview never runs effects: entry actions, invoked and spawned actors run only in the actor itself. A child actor in a preview snapshot is a copy that never starts and ignores events, until the transition renders the snapshot with the running child. Send to children through their parent rather than through a ref read from a preview.
206
209
 
207
- Components that manage their own optimistic state and call an action prop inside a transition work with plain `send`. Pass it from the action:
208
-
209
- ```tsx
210
- import {createActorContext} from '@sanity-labs/xstate-react'
211
-
212
- const Router = createActorContext(routerMachine)
213
-
214
- function Filters() {
215
- const tab = Router.useSelector((snapshot) => snapshot.context.tab)
216
- const send = Router.useSend()
217
- return <TabList activeTab={tab} changeAction={(value) => send({type: 'tab.set', value})} />
210
+ function Search() {
211
+ const [snapshot, send] = useActor(searchMachine)
212
+ return (
213
+ <SearchInput
214
+ value={snapshot.context.query}
215
+ changeAction={(query) => send({type: 'query.change', query})}
216
+ />
217
+ )
218
218
  }
219
219
  ```
220
220
 
221
- ### Updates `send` did not cause
222
-
223
- Delayed transitions, invoked promises, child actors and events sent from outside React change the snapshot without a `send`. By default these changes render as transitions too, so they never reveal a transition that is still suspended. The tradeoff: while a transition is suspended, their visible effect waits for it. A toast that a delayed transition hides stays on screen until the suspended transition renders, and then both render together.
224
-
225
- Pass `updates: 'sync'` to render them as regular updates instead:
226
-
227
- ```tsx
228
- const [snapshot] = useActor(toastMachine, {updates: 'sync'})
229
- ```
230
-
231
- The toast then hides right away. The snapshot it renders includes the suspended transition's changes too, so a `Suspense` boundary waiting on them shows its fallback.
232
-
233
- `send` is a transition either way. After an `await` in an async transition, wrap `send` in `startTransition` again to add transition types to it.
221
+ The input shows what was typed, and keeps its caret, while the transition renders the actor's snapshot in the background. A pending transition that suspends stays hidden. Once it commits, the optimistic value gives way to the snapshot's.
234
222
 
235
223
  ## License
236
224
 
package/dist/index.d.ts CHANGED
@@ -1,132 +1,20 @@
1
- import { ReactNode } from "react";
2
- import { Actor, ActorOptions, AnyActorLogic, AnyActorRef, AnyStateMachine, ConditionalRequired, IsNotNever, Observer, RequiredActorOptionsFor, RequiredActorOptionsKeys, SnapshotFrom, StateFrom } from "xstate";
3
- /**
4
- * How snapshot changes reach React when nothing wraps them in a transition, such as delayed
5
- * transitions, invoked actors settling, and events sent with `actor.send` outside `startTransition`.
6
- *
7
- * - `'transition'` (default): as transition updates. They never reveal a transition that is still
8
- * suspended, and their visible effect waits for it.
9
- * - `'sync'`: as regular updates, with the priority of whatever caused them. They render right
10
- * away, with the suspended transition's changes, so a `Suspense` boundary waiting on those shows
11
- * its fallback.
12
- *
13
- * @public
14
- */
15
- type Updates = 'transition' | 'sync';
16
- /** @public */
17
- interface BindingOptions {
18
- /**
19
- * How snapshot changes reach React when nothing wraps them in a transition, such as delayed
20
- * transitions and invoked actors settling. Defaults to `'transition'`.
21
- */
22
- updates?: Updates;
23
- }
24
- /**
25
- * `useActor`, `useActorRef` and `createActorContext` options: the actor's own options, read once
26
- * when the actor is created, and how its snapshots reach React.
27
- *
28
- * @public
29
- */
30
- type HookOptions<TLogic extends AnyActorLogic> = ActorOptions<TLogic> & BindingOptions;
1
+ import { Actor, ActorOptions, AnyActorLogic, ConditionalRequired, IsNotNever, RequiredActorOptionsFor, RequiredActorOptionsKeys, SnapshotFrom } from "xstate";
31
2
  /**
32
3
  * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`),
33
- * starts it on mount and stops it on unmount. Create a passed actor once, e.g.
34
- * `useState(() => restoreActor(machine, persisted))[0]`.
35
- *
36
- * The logic passed on the first render is used for the component's lifetime. To start over, or to
37
- * switch to a different machine, change the component's `key`.
38
- *
39
- * @public
40
- */
41
- export declare function useActorRef<TLogic extends AnyActorLogic>(actor: Actor<TLogic>, observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void)): Actor<TLogic>;
42
- /** @public */
43
- export declare function useActorRef<TLogic extends AnyActorLogic>(logic: TLogic, ...[options, observerOrListener]: IsNotNever<RequiredActorOptionsKeys<TLogic>> extends true ? [options: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>, observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void)] : [options?: HookOptions<TLogic>, observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void)]): Actor<TLogic>;
44
- /** @public */
45
- interface ActorContext<TLogic extends AnyActorLogic> {
46
- /**
47
- * Reads a value derived from the provided actor's snapshot. The provider holds the snapshot, so
48
- * every reader renders the same snapshot. A reader re-renders whenever the snapshot changes, and
49
- * returns the previous value while `compare` says it is unchanged, for memoizing what it renders.
50
- */
51
- useSelector: <T>(selector: (snapshot: SnapshotFrom<TLogic>) => T, compare?: (a: T, b: T) => boolean) => T;
52
- /** The provided actor. Reading it does not re-render when the snapshot changes. */
53
- useActorRef: () => Actor<TLogic>;
54
- /** The provided actor's `send`, which sends in a transition, like the one `useActor` returns. */
55
- useSend: () => Actor<TLogic>['send'];
56
- /** The provided actor's `send` for updates that must show right away, like `useOptimisticSend`. */
57
- useOptimisticSend: () => Actor<TLogic>['send'];
58
- Provider: (props: {
59
- children: ReactNode;
60
- options?: HookOptions<TLogic>;
61
- logic?: TLogic;
62
- /**
63
- * An already-created actor (e.g. from `restoreActor`) to provide instead of creating one from
64
- * `logic` and `options`. Create it once.
65
- */
66
- actor?: Actor<TLogic>;
67
- }) => ReactNode;
68
- }
69
- /** @public */
70
- export declare function createActorContext<TLogic extends AnyActorLogic>(actorLogic: TLogic, actorOptions?: HookOptions<TLogic>): ActorContext<TLogic>;
71
- /** @public */
72
- export declare function shallowEqual(objA: any, objB: any): boolean;
73
- /**
74
- * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`) and
75
- * subscribes to its snapshot. Create a passed actor once, e.g.
76
- * `useState(() => restoreActor(machine, persisted))[0]`.
4
+ * starts it on mount, stops it on unmount, and returns its snapshot and a `send` for it. Create a
5
+ * passed actor once, e.g. `useState(() => restoreActor(machine, persisted))[0]`.
77
6
  *
78
- * The snapshot is held in React state, and this hook is the only subscriber that puts it there.
79
- * `send` sends in a transition: the one it is called in, or a transition of its own. For an update
80
- * that must show right away, like a controlled input's `onChange`, use `useOptimisticSend(actor)`.
7
+ * Every snapshot change renders as a transition. `send` sends in a transition: the one it is called
8
+ * in, or a transition of its own. For UI that must update right away, like a controlled input, hold
9
+ * the value with `useOptimistic` in the component that renders it, and call `send` from the action
10
+ * that sets it.
81
11
  *
82
- * The logic passed on the first render is used for the component's lifetime, and `input` is read
83
- * once. To start over, or to switch to a different machine, change the component's `key`.
12
+ * The logic passed on the first render is used for the component's lifetime, and `options` are
13
+ * read once. To start over, or to switch to a different machine, change the component's `key`.
84
14
  *
85
15
  * @public
86
16
  */
87
- export declare function useActor<TLogic extends AnyActorLogic>(actor: Actor<TLogic>): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>];
17
+ export declare function useActor<TLogic extends AnyActorLogic>(actor: Actor<TLogic>): [SnapshotFrom<TLogic>, Actor<TLogic>['send']];
88
18
  /** @public */
89
- export declare function useActor<TLogic extends AnyActorLogic>(logic: TLogic, ...[options]: ConditionalRequired<[options?: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>], IsNotNever<RequiredActorOptionsKeys<TLogic>>>): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>];
90
- /**
91
- * @deprecated Use `useActor(machine, options)`.
92
- * @public
93
- */
94
- export declare function useMachine<TMachine extends AnyStateMachine>(actor: Actor<TMachine>): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>];
95
- /**
96
- * @deprecated Use `useActor(machine, options)`.
97
- * @public
98
- */
99
- export declare function useMachine<TMachine extends AnyStateMachine>(machine: TMachine, ...[options]: ConditionalRequired<[options?: HookOptions<TMachine> & RequiredActorOptionsFor<TMachine>], IsNotNever<RequiredActorOptionsKeys<TMachine>>>): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>];
100
- /**
101
- * Reads a value derived from an actor's snapshot, and returns the previous value while `compare`
102
- * says it is unchanged.
103
- *
104
- * Below a `createActorContext` provider of the actor, the snapshot comes from that provider, which
105
- * is the only component that subscribes to the actor. Elsewhere this hook subscribes to the actor
106
- * itself, and re-renders only when the selection changes.
107
- *
108
- * @public
109
- */
110
- export declare function useSelector<TActor extends Pick<AnyActorRef, 'subscribe' | 'getSnapshot'> | undefined, T>(actor: TActor, selector: (snapshot: TActor extends {
111
- getSnapshot(): infer TSnapshot;
112
- } ? TSnapshot : undefined) => T, compare?: (a: T, b: T) => boolean): T;
113
- /**
114
- * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with
115
- * `useActorRef` or `createActorContext`. It sends in a transition: the one it is called in, or a
116
- * transition of its own.
117
- *
118
- * @public
119
- */
120
- export declare function useSend<TActor extends AnyActorRef>(actor: TActor): TActor['send'];
121
- /**
122
- * Returns a `send` for updates that must show right away, like a controlled input's `onChange`.
123
- * The event's outcome is computed with XState's `transition()` and shown with `useOptimistic` by
124
- * every hook that holds the actor's snapshot, while the actor's own snapshot renders in a
125
- * transition. Previews never run effects: a child actor in a preview is a copy that never starts and
126
- * ignores events, until the transition renders the snapshot with the running child.
127
- *
128
- * @public
129
- */
130
- export declare function useOptimisticSend<TActor extends AnyActorRef>(actor: TActor): TActor['send'];
131
- export type { ActorContext, BindingOptions, HookOptions, Updates };
19
+ export declare function useActor<TLogic extends AnyActorLogic>(logic: TLogic, ...[options]: ConditionalRequired<[options?: ActorOptions<TLogic> & RequiredActorOptionsFor<TLogic>], IsNotNever<RequiredActorOptionsKeys<TLogic>>>): [SnapshotFrom<TLogic>, Actor<TLogic>['send']];
132
20
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/store.ts","../src/useActorRef.ts","../src/createActorContext.tsx","../src/shallowEqual.ts","../src/useActor.ts","../src/useMachine.ts","../src/useSelector.ts","../src/useSend.ts"],"mappings":";;;;;;;;;;;;;;KAeY;;UAGK;;;;;EAKf,UAAU;;;;;;;;KCCA,YAAY,eAAe,iBAAiB,aAAa,UAAU;;;;;;;;;;;wBAoJ/D,YAAY,eAAe,eACzC,OAAO,MAAM,SACb,qBAAqB,SAAS,aAAa,aAAa,OAAO,aAAa,oBAC3E,MAAM;;wBAEO,YAAY,eAAe,eACzC,OAAO,YACH,SAAS,qBAAqB,WAAW,yBAAyB,yBAEhE,SAAS,YAAY,UAAU,wBAAwB,SACvD,qBACI,SAAS,aAAa,aACpB,OAAO,aAAa,sBAG1B,UAAU,YAAY,SACtB,qBACI,SAAS,aAAa,aACpB,OAAO,aAAa,qBAE/B,MAAM;;UCrLQ,aAAa,eAAe;;;;;;EAM3C,cAAc,GACZ,WAAW,UAAU,aAAa,YAAY,GAC9C,WAAW,GAAG,GAAG,GAAG,kBACjB;;EAEL,mBAAmB,MAAM;;EAEzB,eAAe,MAAM;;EAErB,yBAAyB,MAAM;EAC/B,WAAW;IACT,UAAU;IACV,UAAU,YAAY;IACtB,QAAQ;;;;;IAKR,QAAQ,MAAM;QACV;;;wBAQQ,mBAAmB,eAAe,eAChD,YAAY,QACZ,eAAe,YAAY,UAC1B,aAAa;;wBCvCA,aAAa,WAAW;;;;;;;;;;;;;;;wBC+BxB,SAAS,eAAe,eACtC,OAAO,MAAM,WACX,aAAa,SAAS,MAAM,iBAAiB,MAAM;;wBAEvC,SAAS,eAAe,eACtC,OAAO,YACH,UAAU,qBACX,UAAU,YAAY,UAAU,wBAAwB,UACzD,WAAW,yBAAyB,aAEpC,aAAa,SAAS,MAAM,iBAAiB,MAAM;;;;;wBChCvC,WAAW,iBAAiB,iBAC1C,OAAO,MAAM,aACX,UAAU,WAAW,MAAM,mBAAmB,MAAM;;;;;wBAKxC,WAAW,iBAAiB,iBAC1C,SAAS,cACL,UAAU,qBACX,UAAU,YAAY,YAAY,wBAAwB,YAC3D,WAAW,yBAAyB,eAEpC,UAAU,WAAW,MAAM,mBAAmB,MAAM;;;;;;;;;;;wBCyBxC,YACd,eAAe,KAAK,uDACpB,GAEA,OAAO,QACP,WACE,UAAU;EAAgB,qBAAqB;IAAa,0BACzD,GACL,WAAU,GAAG,GAAG,GAAG,gBAClB;;;;;;;;wBCpDa,QAAQ,eAAe,aAAa,OAAO,SAAS;;;;;;;;;;wBAapD,kBAAkB,eAAe,aAAa,OAAO,SAAS"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/useActor.ts"],"mappings":";;;;;;;;;;;;;;;;wBA8BgB,SAAS,eAAe,eACtC,OAAO,MAAM,WACX,aAAa,SAAS,MAAM;;wBAEhB,SAAS,eAAe,eACtC,OAAO,YACH,UAAU,qBACX,UAAU,aAAa,UAAU,wBAAwB,UAC1D,WAAW,yBAAyB,aAEpC,aAAa,SAAS,MAAM"}
package/dist/index.js CHANGED
@@ -1,114 +1,6 @@
1
- import { createContext, startTransition, use, useEffect, useEffectEvent, useLayoutEffect, useMemo, useOptimistic, useRef, useState } from "react";
2
- import { Actor, _hotSwapActorLogic, _toObserver, createActor, transition } from "xstate";
3
1
  import { c } from "react/compiler-runtime";
4
- import { jsx } from "react/jsx-runtime";
5
- const notProvided = Symbol("notProvided"), providers = /* @__PURE__ */ new WeakMap();
6
- /**
7
- * The context that carries an actor's snapshot from a provider to the readers below. Each
8
- * `createActorContext` has one, so a provider keeps its element type when its actor changes.
9
- */
10
- function createSnapshotContext() {
11
- return createContext(null);
12
- }
13
- /** Lets `useProvidedSnapshot(actor)` find the context of the provider that holds `actor`. */
14
- function registerProvider(actor, context) {
15
- providers.set(actor, context);
16
- }
17
- /** The snapshot a provider above holds for `actor`, or `notProvided`. */
18
- function useProvidedSnapshot(actor) {
19
- let context = actor ? providers.get(actor) : void 0, provided = context ? use(context) : null;
20
- return provided && provided.actor === actor ? provided.snapshot : notProvided;
21
- }
22
- /**
23
- * Reads an actor for the hooks that hold its snapshot in React state, through a single
24
- * subscription to the actor however many of those hooks there are.
25
- */
26
- var ActorStore = class {
27
- actor;
28
- updates = "transition";
29
- head;
30
- seq = 0;
31
- version = 0;
32
- listeners = /* @__PURE__ */ new Set();
33
- unsubscribeActor;
34
- constructor(actor) {
35
- this.actor = actor, this.head = {
36
- snapshot: actor.getSnapshot(),
37
- seq: 0,
38
- version: 0
39
- };
40
- }
41
- /** The newest entry, for initializing React state and for checks outside render. */
42
- read() {
43
- return this.unsubscribeActor || this.pull(!1), this.head;
44
- }
45
- subscribe(listener) {
46
- if (this.listeners.add(listener), !this.unsubscribeActor) {
47
- let subscription = this.actor.subscribe({
48
- next: () => this.pull(!0),
49
- error: () => this.pull(!0)
50
- });
51
- this.unsubscribeActor = () => subscription.unsubscribe(), this.pull(!0);
52
- }
53
- return () => {
54
- this.listeners.delete(listener), this.listeners.size === 0 && (this.unsubscribeActor?.(), this.unsubscribeActor = void 0);
55
- };
56
- }
57
- /** Sends `event` in a transition: the caller's, or a transition of its own. */
58
- send = (event) => {
59
- startTransition(() => {
60
- this.actor.send(event);
61
- });
62
- };
63
- /**
64
- * Sends `event` in a transition, and shows its outcome right away with `useOptimistic` until that
65
- * transition settles.
66
- */
67
- sendOptimistic = (event) => {
68
- let seq = ++this.seq;
69
- startTransition(() => {
70
- let logic = this.actor.logic;
71
- if (logic) for (let listener of this.listeners) listener.optimistic({
72
- logic,
73
- event,
74
- seq
75
- });
76
- this.actor.send(event);
77
- });
78
- };
79
- pull(notify) {
80
- let snapshot = this.actor.getSnapshot();
81
- if (snapshot !== this.head.snapshot && (this.head = {
82
- snapshot,
83
- seq: this.seq,
84
- version: ++this.version
85
- }, notify)) for (let listener of this.listeners) listener.update(this.head);
86
- }
87
- };
88
- const stores = /* @__PURE__ */ new WeakMap();
89
- function getStore(actor) {
90
- let store = stores.get(actor);
91
- return store || (store = new ActorStore(actor), stores.set(actor, store)), store;
92
- }
93
- /**
94
- * The `useOptimistic` reducer. React replays it on top of every new base until the transition that
95
- * sent the event settles, and the actor has already processed the event by the time any base after
96
- * the send is read. So an event the base already includes is skipped, instead of applied twice.
97
- */
98
- function reduceOptimistic(current, action) {
99
- let base = action.fallback && action.fallback.version > current.version ? action.fallback : current;
100
- if (base.seq >= action.seq) return base;
101
- try {
102
- let [snapshot] = transition(action.logic, base.snapshot, action.event);
103
- return {
104
- snapshot,
105
- seq: base.seq,
106
- version: base.version
107
- };
108
- } catch {
109
- return base;
110
- }
111
- }
2
+ import { startTransition, useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { Actor, _hotSwapActorLogic, createActor } from "xstate";
112
4
  function isStateMachine(logic) {
113
5
  return typeof logic.provide == "function" && !!logic.config && !!logic.sources;
114
6
  }
@@ -119,8 +11,7 @@ function ownLogic(logic) {
119
11
  return isStateMachine(logic) ? logic.provide({}) : logic;
120
12
  }
121
13
  function create(logic, options) {
122
- let { updates, ...actorOptions } = options ?? {}, actor = createActor(logic, actorOptions);
123
- return updates && (getStore(actor).updates = updates), actor;
14
+ return createActor(logic, options);
124
15
  }
125
16
  function adoptLogic(actorRef, logic, refreshed, options, setActorRef) {
126
17
  let currentLogic = actorRef.logic;
@@ -143,13 +34,13 @@ function useIdleActorRef(logicOrActor, options) {
143
34
  options
144
35
  ]), [actorRef, setActorRef];
145
36
  }
146
- function useActorLifecycle(actorRef, setActorRef, createReplacement) {
147
- let $ = c(9), t0;
37
+ function useActorLifecycle(actorRef, setActorRef, options) {
38
+ let $ = c(10), t0;
148
39
  $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = /* @__PURE__ */ new Map(), $[0] = t0) : t0 = $[0];
149
40
  let pendingStopsRef = useRef(t0), t1;
150
- $[1] !== createReplacement || $[2] !== setActorRef ? (t1 = () => setActorRef(createReplacement()), $[1] = createReplacement, $[2] = setActorRef, $[3] = t1) : t1 = $[3];
41
+ $[1] !== actorRef.logic || $[2] !== options || $[3] !== setActorRef ? (t1 = () => setActorRef(create(actorRef.logic, options)), $[1] = actorRef.logic, $[2] = options, $[3] = setActorRef, $[4] = t1) : t1 = $[4];
151
42
  let replace = useEffectEvent(t1), t2;
152
- $[4] !== actorRef || $[5] !== replace ? (t2 = () => {
43
+ $[5] !== actorRef || $[6] !== replace ? (t2 = () => {
153
44
  let pendingStops = pendingStopsRef.current, cancelPendingStop = pendingStops.get(actorRef);
154
45
  if (cancelPendingStop && (cancelPendingStop(), pendingStops.delete(actorRef)), actorRef._processingStatus === 2 && actorRef.getSnapshot()?.status === "stopped") replace();
155
46
  else return actorRef.start(), () => {
@@ -160,246 +51,71 @@ function useActorLifecycle(actorRef, setActorRef, createReplacement) {
160
51
  canceled || actorRef.stop(), pendingStops.get(actorRef) === cancel && pendingStops.delete(actorRef);
161
52
  });
162
53
  };
163
- }, $[4] = actorRef, $[5] = replace, $[6] = t2) : t2 = $[6];
54
+ }, $[5] = actorRef, $[6] = replace, $[7] = t2) : t2 = $[7];
164
55
  let t3;
165
- $[7] === actorRef ? t3 = $[8] : (t3 = [actorRef], $[7] = actorRef, $[8] = t3), useEffect(t2, t3);
56
+ $[8] === actorRef ? t3 = $[9] : (t3 = [actorRef], $[8] = actorRef, $[9] = t3), useEffect(t2, t3);
166
57
  }
167
- /** Creates an actor to replace a stopped one, keeping how its snapshots reach React. */
168
- function recreate(actorRef, options) {
169
- return create(actorRef.logic, {
170
- ...options,
171
- updates: getStore(actorRef).updates
172
- });
173
- }
174
- function useActorRef(logicOrActor, ...t0) {
175
- let $ = c(6), args = t0, readyActor = isActor(logicOrActor), options = readyActor ? void 0 : args[0], observerOrListener = readyActor ? args[0] : args[1], [actorRef, setActorRef] = useIdleActorRef(logicOrActor, options), t1, t2;
176
- $[0] !== actorRef || $[1] !== observerOrListener ? (t1 = () => {
177
- if (!observerOrListener) return;
178
- let subscription = actorRef.subscribe(_toObserver(observerOrListener));
179
- return () => subscription.unsubscribe();
180
- }, t2 = [actorRef, observerOrListener], $[0] = actorRef, $[1] = observerOrListener, $[2] = t1, $[3] = t2) : (t1 = $[2], t2 = $[3]), useEffect(t1, t2);
181
- let t3;
182
- return $[4] === actorRef ? t3 = $[5] : (t3 = () => recreate(actorRef, actorRef.options), $[4] = actorRef, $[5] = t3), useActorLifecycle(actorRef, setActorRef, t3), actorRef;
183
- }
184
- const emptyEntry = {
185
- snapshot: void 0,
186
- seq: 0,
187
- version: -1
188
- };
189
58
  function isErrored(snapshot) {
190
59
  return !!snapshot && typeof snapshot == "object" && "status" in snapshot && snapshot.status === "error" && "error" in snapshot;
191
60
  }
192
- function initialState(store, selector) {
193
- let entry = store ? store.read() : emptyEntry;
194
- return {
195
- store,
196
- entry,
197
- selected: selector(entry.snapshot)
198
- };
199
- }
200
61
  /**
201
- * Holds `selector(snapshot)` of the actor behind `store` in React state, and subscribes to the actor
202
- * to keep it up to date. This is the only place a snapshot enters React: other readers get it from
203
- * here through props or context.
62
+ * Holds the snapshot of `actor` in React state, and subscribes to the actor to keep it up to date.
63
+ * This is the only place a snapshot enters React.
204
64
  *
205
65
  * The snapshot is read from the actor only to initialize the state. Later snapshots arrive as
206
- * values in state updates, so every update renders, and commits, as one consistent snapshot, in the
207
- * transition that caused it. Events sent with `sendOptimistic` are previewed with `useOptimistic`
208
- * until the transition that sent them settles.
209
- *
210
- * An errored snapshot is thrown, unless `rethrow` is false: a provider passes it on so that its
211
- * readers throw it, below any error boundary inside the provider.
212
- */
213
- function useStoreSelection(store, selector, compare, t0) {
214
- let $ = c(22), rethrow = t0 === void 0 || t0, t1;
215
- $[0] !== selector || $[1] !== store ? (t1 = () => initialState(store, selector), $[0] = selector, $[1] = store, $[2] = t1) : t1 = $[2];
216
- let [state, setState] = useState(t1), current;
217
- $[3] !== selector || $[4] !== state || $[5] !== store ? (current = state, state.store !== store && (current = initialState(store, selector), setState(current)), $[3] = selector, $[4] = state, $[5] = store, $[6] = current) : current = $[6];
218
- let [optimistic, addOptimistic] = useOptimistic(current.entry, reduceOptimistic), selectorRef = useRef(selector), compareRef = useRef(compare), stateRef = useRef(current), t2;
219
- $[7] !== compare || $[8] !== current || $[9] !== selector ? (t2 = () => {
220
- selectorRef.current = selector, compareRef.current = compare, stateRef.current = current;
221
- }, $[7] = compare, $[8] = current, $[9] = selector, $[10] = t2) : t2 = $[10], useLayoutEffect(t2);
222
- let t3, t4;
223
- $[11] === store ? (t3 = $[12], t4 = $[13]) : (t3 = () => {
224
- if (!store) return;
225
- let skipped, apply = function apply(entry) {
226
- let previous = stateRef.current;
227
- if (previous.store === store && previous.entry.version >= entry.version) return;
228
- let selected = selectorRef.current(entry.snapshot);
229
- if (previous.store === store && !isErrored(entry.snapshot) && compareRef.current(previous.selected, selected)) {
230
- skipped = entry;
231
- return;
232
- }
233
- skipped = void 0;
234
- let next = {
235
- store,
236
- entry,
237
- selected
238
- };
239
- stateRef.current = next, store?.updates === "sync" ? setState(next) : startTransition(() => setState(next));
240
- }, unsubscribe = store.subscribe({
241
- update: apply,
242
- optimistic(action) {
243
- addOptimistic({
244
- ...action,
245
- fallback: skipped
246
- });
247
- }
248
- });
249
- return apply(store.read()), unsubscribe;
250
- }, t4 = [store, addOptimistic], $[11] = store, $[12] = t3, $[13] = t4), useEffect(t3, t4);
251
- let { snapshot } = optimistic;
252
- if (rethrow && isErrored(snapshot)) throw snapshot.error;
253
- let selected_0, t5;
254
- return $[14] !== compare || $[15] !== current.entry || $[16] !== current.selected || $[17] !== optimistic || $[18] !== selector || $[19] !== snapshot ? (selected_0 = selector(snapshot), t5 = optimistic === current.entry && compare(current.selected, selected_0), $[14] = compare, $[15] = current.entry, $[16] = current.selected, $[17] = optimistic, $[18] = selector, $[19] = snapshot, $[20] = selected_0, $[21] = t5) : (selected_0 = $[20], t5 = $[21]), t5 ? current.selected : selected_0;
255
- }
256
- function defaultCompare(a, b) {
257
- return a === b;
258
- }
259
- function ignore() {}
260
- /**
261
- * Keeps the previous selection while `compare` says it is unchanged, so that what the caller
262
- * renders from it can be memoized.
66
+ * values in state updates, and every one of them is a transition: the one that sent the event, or
67
+ * a transition of its own. So a snapshot change never reveals a transition that is still
68
+ * suspended, and every update renders, and commits, one consistent snapshot.
263
69
  */
264
- function useSelection(snapshot, selector, compare) {
265
- let $ = c(12), t0;
266
- $[0] !== selector || $[1] !== snapshot ? (t0 = () => snapshot === notProvided || isErrored(snapshot) ? void 0 : {
267
- snapshot,
268
- selected: selector(snapshot)
269
- }, $[0] = selector, $[1] = snapshot, $[2] = t0) : t0 = $[2];
270
- let [previous, setPrevious] = useState(t0);
271
- if (snapshot === notProvided) return;
272
- if (isErrored(snapshot)) throw snapshot.error;
273
- let next, t1;
274
- if ($[3] !== compare || $[4] !== previous || $[5] !== selector || $[6] !== snapshot ? (next = selector(snapshot), t1 = previous && compare(previous.selected, next), $[3] = compare, $[4] = previous, $[5] = selector, $[6] = snapshot, $[7] = next, $[8] = t1) : (next = $[7], t1 = $[8]), t1) return previous.selected;
275
- if (previous?.snapshot !== snapshot) {
70
+ function useActorSnapshot(actor) {
71
+ let $ = c(10), t0;
72
+ $[0] === actor ? t0 = $[1] : (t0 = () => ({
73
+ actor,
74
+ snapshot: actor.getSnapshot()
75
+ }), $[0] = actor, $[1] = t0);
76
+ let [state, setState] = useState(t0), current = state;
77
+ if (state.actor !== actor) {
78
+ let t1;
79
+ $[2] === actor ? t1 = $[3] : (t1 = actor.getSnapshot(), $[2] = actor, $[3] = t1);
276
80
  let t2;
277
- $[9] !== next || $[10] !== snapshot ? (t2 = {
278
- snapshot,
279
- selected: next
280
- }, $[9] = next, $[10] = snapshot, $[11] = t2) : t2 = $[11], setPrevious(t2);
281
- }
282
- return next;
283
- }
284
- /**
285
- * Reads a value derived from an actor's snapshot, and returns the previous value while `compare`
286
- * says it is unchanged.
287
- *
288
- * Below a `createActorContext` provider of the actor, the snapshot comes from that provider, which
289
- * is the only component that subscribes to the actor. Elsewhere this hook subscribes to the actor
290
- * itself, and re-renders only when the selection changes.
291
- *
292
- * @public
293
- */
294
- function useSelector(actor, selector, t0) {
295
- let $ = c(3), compare = t0 === void 0 ? defaultCompare : t0, provided = useProvidedSnapshot(actor), isProvided = provided !== notProvided, t1;
296
- $[0] !== actor || $[1] !== isProvided ? (t1 = actor && !isProvided ? getStore(actor) : void 0, $[0] = actor, $[1] = isProvided, $[2] = t1) : t1 = $[2];
297
- let subscribed = useStoreSelection(t1, isProvided ? ignore : selector, isProvided ? defaultCompare : compare), selected = useSelection(provided, selector, compare);
298
- return isProvided ? selected : subscribed;
299
- }
300
- /**
301
- * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with
302
- * `useActorRef` or `createActorContext`. It sends in a transition: the one it is called in, or a
303
- * transition of its own.
304
- *
305
- * @public
306
- */
307
- function useSend(actor) {
308
- let $ = c(2), t0;
309
- return $[0] === actor ? t0 = $[1] : (t0 = getStore(actor), $[0] = actor, $[1] = t0), t0.send;
310
- }
311
- /**
312
- * Returns a `send` for updates that must show right away, like a controlled input's `onChange`.
313
- * The event's outcome is computed with XState's `transition()` and shown with `useOptimistic` by
314
- * every hook that holds the actor's snapshot, while the actor's own snapshot renders in a
315
- * transition. Previews never run effects: a child actor in a preview is a copy that never starts and
316
- * ignores events, until the transition renders the snapshot with the running child.
317
- *
318
- * @public
319
- */
320
- function useOptimisticSend(actor) {
321
- let $ = c(2), t0;
322
- return $[0] === actor ? t0 = $[1] : (t0 = getStore(actor), $[0] = actor, $[1] = t0), t0.sendOptimistic;
323
- }
324
- function identity$1(value) {
325
- return value;
326
- }
327
- /** @public */
328
- function createActorContext(actorLogic, actorOptions) {
329
- let ReactContext = createContext(null), SnapshotContext = createSnapshotContext();
330
- function Provider({ children, logic: providedLogic = actorLogic, options: providedOptions, actor: providedActor }) {
331
- let actor = useActorRef(providedActor ?? providedLogic, providedActor ? void 0 : {
332
- ...actorOptions,
333
- ...providedOptions
334
- }), snapshot = useStoreSelection(useMemo(() => getStore(actor), [actor]), identity$1, Object.is, !1), provided = useMemo(() => ({
81
+ $[4] !== actor || $[5] !== t1 ? (t2 = {
335
82
  actor,
336
- snapshot
337
- }), [actor, snapshot]);
338
- return registerProvider(actor, SnapshotContext), /* @__PURE__ */ jsx(ReactContext, {
339
- value: actor,
340
- children: /* @__PURE__ */ jsx(SnapshotContext, {
341
- value: provided,
342
- children
343
- })
344
- });
345
- }
346
- Provider.displayName = "ActorProvider";
347
- function useContext() {
348
- let actor = use(ReactContext);
349
- if (!actor) throw Error(`You used a hook from "${Provider.displayName}" but it's not inside a <${Provider.displayName}> component.`);
350
- return actor;
351
- }
352
- function useSelector$1(selector, compare) {
353
- return useSelector(useContext(), selector, compare);
354
- }
355
- function useSend$1() {
356
- return useSend(useContext());
357
- }
358
- function useOptimisticSend$1() {
359
- return useOptimisticSend(useContext());
83
+ snapshot: t1
84
+ }, $[4] = actor, $[5] = t1, $[6] = t2) : t2 = $[6], current = t2, setState(current);
360
85
  }
361
- return {
362
- Provider,
363
- useActorRef: useContext,
364
- useSelector: useSelector$1,
365
- useSend: useSend$1,
366
- useOptimisticSend: useOptimisticSend$1
367
- };
368
- }
369
- function is(x, y) {
370
- return x === y ? x !== 0 || y !== 0 || 1 / x == 1 / y : x !== x && y !== y;
371
- }
372
- /** @public */
373
- function shallowEqual(objA, objB) {
374
- if (is(objA, objB)) return !0;
375
- if (typeof objA != "object" || !objA || typeof objB != "object" || !objB) return !1;
376
- let keysA = Object.keys(objA), keysB = Object.keys(objB);
377
- if (keysA.length !== keysB.length) return !1;
378
- for (let key of keysA) if (!Object.prototype.hasOwnProperty.call(objB, key) || !is(objA[key], objB[key])) return !1;
379
- return !0;
380
- }
381
- function identity(value) {
382
- return value;
86
+ let t1, t2;
87
+ $[7] === actor ? (t1 = $[8], t2 = $[9]) : (t1 = () => {
88
+ let pushed, update = function update(snapshot) {
89
+ snapshot !== pushed && (pushed = snapshot, startTransition(() => {
90
+ setState((previous) => previous.actor === actor && previous.snapshot === snapshot ? previous : {
91
+ actor,
92
+ snapshot
93
+ });
94
+ }));
95
+ }, subscription = actor.subscribe({
96
+ next: update,
97
+ error: () => update(actor.getSnapshot())
98
+ });
99
+ return update(actor.getSnapshot()), () => subscription.unsubscribe();
100
+ }, t2 = [actor], $[7] = actor, $[8] = t1, $[9] = t2), useEffect(t1, t2);
101
+ let snapshot_0 = current.snapshot;
102
+ if (isErrored(snapshot_0)) throw snapshot_0.error;
103
+ return current.snapshot;
383
104
  }
384
105
  function useActor(logic, options) {
385
- let $ = c(12), t0;
386
- $[0] === logic ? t0 = $[1] : (t0 = isActor(logic), $[0] = logic, $[1] = t0);
387
- let readyActor = t0;
388
- if (!readyActor && logic && "send" in logic && typeof logic.send == "function") throw Error("useActor() expects actor logic (e.g. a machine), but received an ActorRef. Pass an Actor created with createActor()/restoreActor(), or use the useSelector(actorRef, ...) hook to read an ActorRef's snapshot.");
389
- let [actorRef, setActorRef] = useIdleActorRef(logic, options), t1;
390
- $[2] === actorRef ? t1 = $[3] : (t1 = getStore(actorRef), $[2] = actorRef, $[3] = t1);
391
- let store = t1, snapshot = useStoreSelection(store, identity, Object.is), t2;
392
- $[4] !== actorRef || $[5] !== options || $[6] !== readyActor ? (t2 = () => recreate(actorRef, readyActor ? actorRef.options : options), $[4] = actorRef, $[5] = options, $[6] = readyActor, $[7] = t2) : t2 = $[7], useActorLifecycle(actorRef, setActorRef, t2);
393
- let t3 = store.send, t4;
394
- return $[8] !== actorRef || $[9] !== snapshot || $[10] !== t3 ? (t4 = [
395
- snapshot,
396
- t3,
397
- actorRef
398
- ], $[8] = actorRef, $[9] = snapshot, $[10] = t3, $[11] = t4) : t4 = $[11], t4;
399
- }
400
- function useMachine(machine, options) {
401
- return useActor(machine, options);
106
+ let $ = c(5), readyActor = isActor(logic);
107
+ if (!readyActor && logic && "send" in logic && typeof logic.send == "function") throw Error("useActor() expects actor logic (e.g. a machine) or an Actor created with createActor() or restoreActor(), but received another kind of actor ref.");
108
+ let [actorRef, setActorRef] = useIdleActorRef(logic, options), snapshot = useActorSnapshot(actorRef), t0;
109
+ $[0] === actorRef ? t0 = $[1] : (t0 = (event) => {
110
+ startTransition(() => {
111
+ actorRef.send(event);
112
+ });
113
+ }, $[0] = actorRef, $[1] = t0);
114
+ let send = t0;
115
+ useActorLifecycle(actorRef, setActorRef, readyActor ? actorRef.options : options);
116
+ let t1;
117
+ return $[2] !== send || $[3] !== snapshot ? (t1 = [snapshot, send], $[2] = send, $[3] = snapshot, $[4] = t1) : t1 = $[4], t1;
402
118
  }
403
- export { createActorContext, shallowEqual, useActor, useActorRef, useMachine, useOptimisticSend, useSelector, useSend };
119
+ export { useActor };
404
120
 
405
121
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["new Map<Actor<TLogic>, () => void>()","() => setActorRef(createReplacement())","() => {\n const pendingStops = pendingStopsRef.current\n const cancelPendingStop = pendingStops.get(actorRef)\n if (cancelPendingStop) {\n cancelPendingStop()\n pendingStops.delete(actorRef)\n }\n\n // A stopped actor cannot be restarted, so one that stopped before this effect reconnected is\n // replaced.\n if (\n (actorRef as any)._processingStatus === 2 &&\n (actorRef.getSnapshot() as any)?.status === 'stopped'\n ) {\n replace()\n return\n }\n\n actorRef.start()\n // Stopping waits a microtask so that StrictMode's simulated unmount and remount, and a move\n // within the tree, keep the running actor.\n return () => {\n let canceled = false\n const cancel = () => {\n canceled = true\n }\n pendingStops.set(actorRef, cancel)\n queueMicrotask(() => {\n if (!canceled) {\n actorRef.stop()\n }\n if (pendingStops.get(actorRef) === cancel) {\n pendingStops.delete(actorRef)\n }\n })\n }\n }","[actorRef]","...args: any[]","() => {\n if (!observerOrListener) {\n return\n }\n const subscription = actorRef.subscribe(toObserver(observerOrListener))\n return () => subscription.unsubscribe()\n }","[actorRef, observerOrListener]","() => recreate(actorRef, actorRef.options)","hotSwapActorLogic","toObserver","rethrow = true","() => initialState(store, selector)","let current = state","() => {\n selectorRef.current = selector\n compareRef.current = compare\n stateRef.current = current\n }","() => {\n if (!store) {\n return\n }\n let skipped: Entry | undefined\n\n function apply(entry: Entry): void {\n const previous = stateRef.current\n if (previous.store === store && previous.entry.version >= entry.version) {\n return\n }\n const selected = selectorRef.current(entry.snapshot)\n // The selection did not change, so there is nothing to render. The entry is still the\n // newest base for previews of events sent after it.\n if (\n previous.store === store &&\n !isErrored(entry.snapshot) &&\n compareRef.current(previous.selected, selected)\n ) {\n skipped = entry\n return\n }\n skipped = undefined\n const next: State<T> = {store, entry, selected}\n stateRef.current = next\n if (store?.updates === 'sync') {\n setState(next)\n } else {\n startTransition(() => setState(next))\n }\n }\n\n const unsubscribe = store.subscribe({\n update: apply,\n optimistic(action) {\n addOptimistic({...action, fallback: skipped} as OptimisticAction)\n },\n })\n // The actor may have moved on between render and subscribing.\n apply(store.read())\n return unsubscribe\n }","[store, addOptimistic]","selected","optimistic === current.entry && compare(current.selected, selected)","entry","const selected = selector(snapshot)","() =>\n snapshot === notProvided || isErrored(snapshot)\n ? undefined\n : {snapshot, selected: selector(snapshot)}","previous && compare(previous.selected, next)","const next = selector(snapshot)","{snapshot, selected: next}","compare: (a: T, b: T) => boolean = defaultCompare","actor && !isProvided ? getStore(actor) : undefined","store","getStore(actor)","identity","_jsx","useSelector","useSelectorUnbound","useSend","useSendUnbound","useOptimisticSend","useOptimisticSendUnbound","isActor(logic)","getStore(actorRef)","useMemo(() => getStore(actorRef), [actorRef])","() =>\n recreate(actorRef, readyActor ? actorRef.options : options)","actorRef.options","store.send as Actor<TLogic>['send']","[snapshot, store.send as Actor<TLogic>['send'], actorRef]"],"sources":["../src/snapshotContext.ts","../src/store.ts","../src/useActorRef.ts","../src/useStoreSelection.ts","../src/useSelector.ts","../src/useSend.ts","../src/createActorContext.tsx","../src/shallowEqual.ts","../src/useActor.ts","../src/useMachine.ts"],"sourcesContent":["import {createContext, use, type Context} from 'react'\nimport type {AnyActorRef} from 'xstate'\n\nexport const notProvided: unique symbol = Symbol('notProvided')\n\ntype Actor = Pick<AnyActorRef, 'getSnapshot'>\n\ninterface Provided {\n readonly actor: Actor\n readonly snapshot: unknown\n}\n\nexport type SnapshotContext = Context<Provided | null>\n\nconst providers = new WeakMap<Actor, SnapshotContext>()\n\n/**\n * The context that carries an actor's snapshot from a provider to the readers below. Each\n * `createActorContext` has one, so a provider keeps its element type when its actor changes.\n */\nexport function createSnapshotContext(): SnapshotContext {\n return createContext<Provided | null>(null)\n}\n\n/** Lets `useProvidedSnapshot(actor)` find the context of the provider that holds `actor`. */\nexport function registerProvider(actor: Actor, context: SnapshotContext): void {\n providers.set(actor, context)\n}\n\n/** The snapshot a provider above holds for `actor`, or `notProvided`. */\nexport function useProvidedSnapshot(actor: Actor | undefined): unknown {\n const context = actor ? providers.get(actor) : undefined\n const provided = context ? use(context) : null\n return provided && provided.actor === actor ? provided.snapshot : notProvided\n}\n","import {startTransition} from 'react'\nimport {transition, type AnyActorLogic, type AnyActorRef} from 'xstate'\n\n/**\n * How snapshot changes reach React when nothing wraps them in a transition, such as delayed\n * transitions, invoked actors settling, and events sent with `actor.send` outside `startTransition`.\n *\n * - `'transition'` (default): as transition updates. They never reveal a transition that is still\n * suspended, and their visible effect waits for it.\n * - `'sync'`: as regular updates, with the priority of whatever caused them. They render right\n * away, with the suspended transition's changes, so a `Suspense` boundary waiting on those shows\n * its fallback.\n *\n * @public\n */\nexport type Updates = 'transition' | 'sync'\n\n/** @public */\nexport interface BindingOptions {\n /**\n * How snapshot changes reach React when nothing wraps them in a transition, such as delayed\n * transitions and invoked actors settling. Defaults to `'transition'`.\n */\n updates?: Updates\n}\n\ntype ReadableActor = Pick<AnyActorRef, 'subscribe' | 'getSnapshot'>\n\nexport interface Entry {\n readonly snapshot: unknown\n /** The number of optimistic events the snapshot already includes. */\n readonly seq: number\n /** Increases with every snapshot the actor emits. */\n readonly version: number\n}\n\nexport interface OptimisticAction {\n readonly logic: AnyActorLogic\n readonly event: unknown\n readonly seq: number\n /** A newer base than the hook's state, for hooks that skipped updates their selector ignored. */\n readonly fallback: Entry | undefined\n}\n\nexport interface Listener {\n update(entry: Entry): void\n optimistic(action: Omit<OptimisticAction, 'fallback'>): void\n}\n\n/**\n * Reads an actor for the hooks that hold its snapshot in React state, through a single\n * subscription to the actor however many of those hooks there are.\n */\nexport class ActorStore {\n readonly actor: ReadableActor\n updates: Updates = 'transition'\n private head: Entry\n private seq = 0\n private version = 0\n private readonly listeners = new Set<Listener>()\n private unsubscribeActor: (() => void) | undefined\n\n constructor(actor: ReadableActor) {\n this.actor = actor\n this.head = {snapshot: actor.getSnapshot(), seq: 0, version: 0}\n }\n\n /** The newest entry, for initializing React state and for checks outside render. */\n read(): Entry {\n if (!this.unsubscribeActor) {\n this.pull(false)\n }\n return this.head\n }\n\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener)\n if (!this.unsubscribeActor) {\n const subscription = this.actor.subscribe({\n next: () => this.pull(true),\n error: () => this.pull(true),\n })\n this.unsubscribeActor = () => subscription.unsubscribe()\n this.pull(true)\n }\n return () => {\n this.listeners.delete(listener)\n if (this.listeners.size === 0) {\n this.unsubscribeActor?.()\n this.unsubscribeActor = undefined\n }\n }\n }\n\n /** Sends `event` in a transition: the caller's, or a transition of its own. */\n send = (event: unknown): void => {\n startTransition(() => {\n ;(this.actor as AnyActorRef).send(event)\n })\n }\n\n /**\n * Sends `event` in a transition, and shows its outcome right away with `useOptimistic` until that\n * transition settles.\n */\n sendOptimistic = (event: unknown): void => {\n const seq = ++this.seq\n startTransition(() => {\n const logic = (this.actor as {logic?: AnyActorLogic}).logic\n if (logic) {\n for (const listener of this.listeners) {\n listener.optimistic({logic, event, seq})\n }\n }\n ;(this.actor as AnyActorRef).send(event)\n })\n }\n\n private pull(notify: boolean): void {\n const snapshot = this.actor.getSnapshot()\n if (snapshot === this.head.snapshot) {\n return\n }\n this.head = {snapshot, seq: this.seq, version: ++this.version}\n if (notify) {\n for (const listener of this.listeners) {\n listener.update(this.head)\n }\n }\n }\n}\n\nconst stores = new WeakMap<ReadableActor, ActorStore>()\n\nexport function getStore(actor: ReadableActor): ActorStore {\n let store = stores.get(actor)\n if (!store) {\n store = new ActorStore(actor)\n stores.set(actor, store)\n }\n return store\n}\n\n/**\n * The `useOptimistic` reducer. React replays it on top of every new base until the transition that\n * sent the event settles, and the actor has already processed the event by the time any base after\n * the send is read. So an event the base already includes is skipped, instead of applied twice.\n */\nexport function reduceOptimistic(current: Entry, action: OptimisticAction): Entry {\n const base =\n action.fallback && action.fallback.version > current.version ? action.fallback : current\n if (base.seq >= action.seq) {\n return base\n }\n try {\n const [snapshot] = transition(action.logic, base.snapshot as never, action.event as never)\n return {snapshot, seq: base.seq, version: base.version}\n } catch {\n // The running actor reports the error itself; the preview falls back to the base.\n return base\n }\n}\n","import {useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState} from 'react'\nimport {\n _hotSwapActorLogic as hotSwapActorLogic,\n _toObserver as toObserver,\n Actor,\n createActor,\n type ActorOptions,\n type AnyActorLogic,\n type AnyStateMachine,\n type IsNotNever,\n type Observer,\n type RequiredActorOptionsFor,\n type RequiredActorOptionsKeys,\n type SnapshotFrom,\n} from 'xstate'\n\nimport {getStore, type BindingOptions} from './store'\n\n/**\n * `useActor`, `useActorRef` and `createActorContext` options: the actor's own options, read once\n * when the actor is created, and how its snapshots reach React.\n *\n * @public\n */\nexport type HookOptions<TLogic extends AnyActorLogic> = ActorOptions<TLogic> & BindingOptions\n\nfunction isStateMachine(logic: AnyActorLogic): logic is AnyStateMachine {\n return (\n typeof (logic as any).provide === 'function' &&\n !!(logic as any).config &&\n !!(logic as any).sources\n )\n}\n\nexport function isActor(value: unknown): value is Actor<AnyActorLogic> {\n return value instanceof Actor\n}\n\n// The hook updates the sources of its machine on later renders. A per-hook copy keeps those\n// updates from reaching the caller's machine, which other actors may share.\nfunction ownLogic<TLogic extends AnyActorLogic>(logic: TLogic): TLogic {\n return isStateMachine(logic) ? (logic.provide({}) as any) : logic\n}\n\nfunction create<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options: HookOptions<TLogic> | undefined,\n): Actor<TLogic> {\n const {updates, ...actorOptions} = options ?? {}\n const actor = createActor(logic, actorOptions as ActorOptions<TLogic>)\n if (updates) {\n getStore(actor).updates = updates\n }\n return actor\n}\n\nfunction adoptLogic<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n logic: TLogic,\n refreshed: boolean,\n options: HookOptions<TLogic> | undefined,\n setActorRef: (actorRef: Actor<TLogic>) => void,\n): void {\n const currentLogic = actorRef.logic\n if ((logic as any).config === (currentLogic as any).config) {\n if (isStateMachine(logic) && isStateMachine(currentLogic)) {\n currentLogic.sources = logic.sources\n }\n return\n }\n // Fast Refresh re-evaluated the module that defines the machine: keep the running actor and\n // carry its live snapshot over, or start a fresh actor if it cannot be carried.\n if (refreshed) {\n const nextLogic = ownLogic(logic)\n if (!hotSwapActorLogic(actorRef, nextLogic as any as AnyStateMachine)) {\n setActorRef(create(nextLogic, options))\n }\n }\n}\n\nexport function useIdleActorRef<TLogic extends AnyActorLogic>(\n logicOrActor: TLogic | Actor<TLogic>,\n options: HookOptions<TLogic> | undefined,\n): [Actor<TLogic>, (actorRef: Actor<TLogic>) => void] {\n // React Compiler would turn the `useMemo` below into a cache slot that Fast Refresh never resets.\n 'use no memo'\n const [actorRef, setActorRef] = useState(() =>\n isActor(logicOrActor) ? logicOrActor : create(ownLogic(logicOrActor), options),\n )\n // Its identity changes only when React Fast Refresh re-renders this component: Fast Refresh\n // ignores dependency lists while it applies an update.\n const refreshSignal = useMemo(() => ({}), [])\n const refreshSignalRef = useRef(refreshSignal)\n\n // The logic passed on the first render is used for the hook's lifetime. Later renders only\n // contribute implementations provided with `machine.provide()` for the same machine config.\n useLayoutEffect(() => {\n const refreshed = refreshSignalRef.current !== refreshSignal\n refreshSignalRef.current = refreshSignal\n if (!isActor(logicOrActor)) {\n adoptLogic(actorRef, logicOrActor, refreshed, options, setActorRef)\n }\n }, [actorRef, logicOrActor, refreshSignal, options])\n\n return [actorRef, setActorRef]\n}\n\nexport function useActorLifecycle<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n setActorRef: (actorRef: Actor<TLogic>) => void,\n createReplacement: () => Actor<TLogic>,\n): void {\n const pendingStopsRef = useRef(new Map<Actor<TLogic>, () => void>())\n const replace = useEffectEvent(() => setActorRef(createReplacement()))\n\n useEffect(() => {\n const pendingStops = pendingStopsRef.current\n const cancelPendingStop = pendingStops.get(actorRef)\n if (cancelPendingStop) {\n cancelPendingStop()\n pendingStops.delete(actorRef)\n }\n\n // A stopped actor cannot be restarted, so one that stopped before this effect reconnected is\n // replaced.\n if (\n (actorRef as any)._processingStatus === 2 &&\n (actorRef.getSnapshot() as any)?.status === 'stopped'\n ) {\n replace()\n return\n }\n\n actorRef.start()\n // Stopping waits a microtask so that StrictMode's simulated unmount and remount, and a move\n // within the tree, keep the running actor.\n return () => {\n let canceled = false\n const cancel = () => {\n canceled = true\n }\n pendingStops.set(actorRef, cancel)\n queueMicrotask(() => {\n if (!canceled) {\n actorRef.stop()\n }\n if (pendingStops.get(actorRef) === cancel) {\n pendingStops.delete(actorRef)\n }\n })\n }\n }, [actorRef])\n}\n\n/** Creates an actor to replace a stopped one, keeping how its snapshots reach React. */\nexport function recreate<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n options: ActorOptions<TLogic> | undefined,\n): Actor<TLogic> {\n return create(actorRef.logic, {...options, updates: getStore(actorRef).updates})\n}\n\n/**\n * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`),\n * starts it on mount and stops it on unmount. Create a passed actor once, e.g.\n * `useState(() => restoreActor(machine, persisted))[0]`.\n *\n * The logic passed on the first render is used for the component's lifetime. To start over, or to\n * switch to a different machine, change the component's `key`.\n *\n * @public\n */\nexport function useActorRef<TLogic extends AnyActorLogic>(\n actor: Actor<TLogic>,\n observerOrListener?: Observer<SnapshotFrom<TLogic>> | ((value: SnapshotFrom<TLogic>) => void),\n): Actor<TLogic>\n/** @public */\nexport function useActorRef<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options, observerOrListener]: IsNotNever<RequiredActorOptionsKeys<TLogic>> extends true\n ? [\n options: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>,\n observerOrListener?:\n | Observer<SnapshotFrom<TLogic>>\n | ((value: SnapshotFrom<TLogic>) => void),\n ]\n : [\n options?: HookOptions<TLogic>,\n observerOrListener?:\n | Observer<SnapshotFrom<TLogic>>\n | ((value: SnapshotFrom<TLogic>) => void),\n ]\n): Actor<TLogic>\nexport function useActorRef(\n logicOrActor: AnyActorLogic | Actor<AnyActorLogic>,\n ...args: any[]\n): Actor<AnyActorLogic> {\n const readyActor = isActor(logicOrActor)\n const options: HookOptions<AnyActorLogic> | undefined = readyActor ? undefined : args[0]\n const observerOrListener: Observer<unknown> | ((value: unknown) => void) | undefined = readyActor\n ? args[0]\n : args[1]\n const [actorRef, setActorRef] = useIdleActorRef(logicOrActor, options)\n\n useEffect(() => {\n if (!observerOrListener) {\n return\n }\n const subscription = actorRef.subscribe(toObserver(observerOrListener))\n return () => subscription.unsubscribe()\n }, [actorRef, observerOrListener])\n\n useActorLifecycle(actorRef, setActorRef, () => recreate(actorRef, actorRef.options))\n\n return actorRef\n}\n","import {startTransition, useEffect, useLayoutEffect, useOptimistic, useRef, useState} from 'react'\n\nimport {reduceOptimistic, type ActorStore, type Entry, type OptimisticAction} from './store'\n\ninterface State<T> {\n readonly store: ActorStore | undefined\n readonly entry: Entry\n readonly selected: T\n}\n\nconst emptyEntry: Entry = {snapshot: undefined, seq: 0, version: -1}\n\nexport function isErrored(snapshot: unknown): snapshot is {error: unknown} {\n return (\n !!snapshot &&\n typeof snapshot === 'object' &&\n 'status' in snapshot &&\n snapshot.status === 'error' &&\n 'error' in snapshot\n )\n}\n\nfunction initialState<T>(store: ActorStore | undefined, selector: (snapshot: any) => T): State<T> {\n const entry = store ? store.read() : emptyEntry\n return {store, entry, selected: selector(entry.snapshot)}\n}\n\n/**\n * Holds `selector(snapshot)` of the actor behind `store` in React state, and subscribes to the actor\n * to keep it up to date. This is the only place a snapshot enters React: other readers get it from\n * here through props or context.\n *\n * The snapshot is read from the actor only to initialize the state. Later snapshots arrive as\n * values in state updates, so every update renders, and commits, as one consistent snapshot, in the\n * transition that caused it. Events sent with `sendOptimistic` are previewed with `useOptimistic`\n * until the transition that sent them settles.\n *\n * An errored snapshot is thrown, unless `rethrow` is false: a provider passes it on so that its\n * readers throw it, below any error boundary inside the provider.\n */\nexport function useStoreSelection<T>(\n store: ActorStore | undefined,\n selector: (snapshot: any) => T,\n compare: (a: T, b: T) => boolean,\n rethrow = true,\n): T {\n const [state, setState] = useState(() => initialState(store, selector))\n let current = state\n if (state.store !== store) {\n // A new actor, e.g. one that replaced a stopped actor: its snapshot is read once, like the\n // initial state's.\n current = initialState(store, selector)\n setState(current)\n }\n const [optimistic, addOptimistic] = useOptimistic(current.entry, reduceOptimistic)\n\n const selectorRef = useRef(selector)\n const compareRef = useRef(compare)\n const stateRef = useRef(current)\n useLayoutEffect(() => {\n selectorRef.current = selector\n compareRef.current = compare\n stateRef.current = current\n })\n\n useEffect(() => {\n if (!store) {\n return\n }\n let skipped: Entry | undefined\n\n function apply(entry: Entry): void {\n const previous = stateRef.current\n if (previous.store === store && previous.entry.version >= entry.version) {\n return\n }\n const selected = selectorRef.current(entry.snapshot)\n // The selection did not change, so there is nothing to render. The entry is still the\n // newest base for previews of events sent after it.\n if (\n previous.store === store &&\n !isErrored(entry.snapshot) &&\n compareRef.current(previous.selected, selected)\n ) {\n skipped = entry\n return\n }\n skipped = undefined\n const next: State<T> = {store, entry, selected}\n stateRef.current = next\n if (store?.updates === 'sync') {\n setState(next)\n } else {\n startTransition(() => setState(next))\n }\n }\n\n const unsubscribe = store.subscribe({\n update: apply,\n optimistic(action) {\n addOptimistic({...action, fallback: skipped} as OptimisticAction)\n },\n })\n // The actor may have moved on between render and subscribing.\n apply(store.read())\n return unsubscribe\n }, [store, addOptimistic])\n\n const {snapshot} = optimistic\n if (rethrow && isErrored(snapshot)) {\n throw snapshot.error\n }\n const selected = selector(snapshot)\n if (optimistic === current.entry && compare(current.selected, selected)) {\n return current.selected\n }\n return selected\n}\n","import {useMemo, useState} from 'react'\nimport type {AnyActorRef} from 'xstate'\n\nimport {notProvided, useProvidedSnapshot} from './snapshotContext'\nimport {getStore} from './store'\nimport {isErrored, useStoreSelection} from './useStoreSelection'\n\nfunction defaultCompare<T>(a: T, b: T) {\n return a === b\n}\n\nfunction ignore(): undefined {\n return undefined\n}\n\n/**\n * Keeps the previous selection while `compare` says it is unchanged, so that what the caller\n * renders from it can be memoized.\n */\nfunction useSelection<T>(\n snapshot: unknown,\n selector: (snapshot: any) => T,\n compare: (a: T, b: T) => boolean,\n): T | undefined {\n const [previous, setPrevious] = useState<{snapshot: unknown; selected: T} | undefined>(() =>\n snapshot === notProvided || isErrored(snapshot)\n ? undefined\n : {snapshot, selected: selector(snapshot)},\n )\n if (snapshot === notProvided) {\n return undefined\n }\n if (isErrored(snapshot)) {\n throw snapshot.error\n }\n const next = selector(snapshot)\n if (previous && compare(previous.selected, next)) {\n return previous.selected\n }\n if (previous?.snapshot !== snapshot) {\n setPrevious({snapshot, selected: next})\n }\n return next\n}\n\n/**\n * Reads a value derived from an actor's snapshot, and returns the previous value while `compare`\n * says it is unchanged.\n *\n * Below a `createActorContext` provider of the actor, the snapshot comes from that provider, which\n * is the only component that subscribes to the actor. Elsewhere this hook subscribes to the actor\n * itself, and re-renders only when the selection changes.\n *\n * @public\n */\nexport function useSelector<\n TActor extends Pick<AnyActorRef, 'subscribe' | 'getSnapshot'> | undefined,\n T,\n>(\n actor: TActor,\n selector: (\n snapshot: TActor extends {getSnapshot(): infer TSnapshot} ? TSnapshot : undefined,\n ) => T,\n compare: (a: T, b: T) => boolean = defaultCompare,\n): T {\n const provided = useProvidedSnapshot(actor)\n const isProvided = provided !== notProvided\n const store = useMemo(\n () => (actor && !isProvided ? getStore(actor) : undefined),\n [actor, isProvided],\n )\n const subscribed = useStoreSelection<T | undefined>(\n store,\n isProvided ? ignore : selector,\n isProvided ? defaultCompare : (compare as (a: T | undefined, b: T | undefined) => boolean),\n )\n const selected = useSelection(provided, selector, compare)\n return (isProvided ? selected : subscribed) as T\n}\n","import {useMemo} from 'react'\nimport type {AnyActorRef} from 'xstate'\n\nimport {getStore} from './store'\n\n/**\n * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with\n * `useActorRef` or `createActorContext`. It sends in a transition: the one it is called in, or a\n * transition of its own.\n *\n * @public\n */\nexport function useSend<TActor extends AnyActorRef>(actor: TActor): TActor['send'] {\n return useMemo(() => getStore(actor).send, [actor]) as TActor['send']\n}\n\n/**\n * Returns a `send` for updates that must show right away, like a controlled input's `onChange`.\n * The event's outcome is computed with XState's `transition()` and shown with `useOptimistic` by\n * every hook that holds the actor's snapshot, while the actor's own snapshot renders in a\n * transition. Previews never run effects: a child actor in a preview is a copy that never starts and\n * ignores events, until the transition renders the snapshot with the running child.\n *\n * @public\n */\nexport function useOptimisticSend<TActor extends AnyActorRef>(actor: TActor): TActor['send'] {\n return useMemo(() => getStore(actor).sendOptimistic, [actor]) as TActor['send']\n}\n","import {createContext, use, useMemo, type ReactNode} from 'react'\nimport type {Actor, AnyActorLogic, SnapshotFrom} from 'xstate'\n\nimport {createSnapshotContext, registerProvider} from './snapshotContext'\nimport {getStore} from './store'\nimport {useActorRef, type HookOptions} from './useActorRef'\nimport {useSelector as useSelectorUnbound} from './useSelector'\nimport {useOptimisticSend as useOptimisticSendUnbound, useSend as useSendUnbound} from './useSend'\nimport {useStoreSelection} from './useStoreSelection'\n\n/** @public */\nexport interface ActorContext<TLogic extends AnyActorLogic> {\n /**\n * Reads a value derived from the provided actor's snapshot. The provider holds the snapshot, so\n * every reader renders the same snapshot. A reader re-renders whenever the snapshot changes, and\n * returns the previous value while `compare` says it is unchanged, for memoizing what it renders.\n */\n useSelector: <T>(\n selector: (snapshot: SnapshotFrom<TLogic>) => T,\n compare?: (a: T, b: T) => boolean,\n ) => T\n /** The provided actor. Reading it does not re-render when the snapshot changes. */\n useActorRef: () => Actor<TLogic>\n /** The provided actor's `send`, which sends in a transition, like the one `useActor` returns. */\n useSend: () => Actor<TLogic>['send']\n /** The provided actor's `send` for updates that must show right away, like `useOptimisticSend`. */\n useOptimisticSend: () => Actor<TLogic>['send']\n Provider: (props: {\n children: ReactNode\n options?: HookOptions<TLogic>\n logic?: TLogic\n /**\n * An already-created actor (e.g. from `restoreActor`) to provide instead of creating one from\n * `logic` and `options`. Create it once.\n */\n actor?: Actor<TLogic>\n }) => ReactNode\n}\n\nfunction identity<T>(value: T): T {\n return value\n}\n\n/** @public */\nexport function createActorContext<TLogic extends AnyActorLogic>(\n actorLogic: TLogic,\n actorOptions?: HookOptions<TLogic>,\n): ActorContext<TLogic> {\n const ReactContext = createContext<Actor<TLogic> | null>(null)\n const SnapshotContext = createSnapshotContext()\n\n function Provider({\n children,\n logic: providedLogic = actorLogic,\n options: providedOptions,\n actor: providedActor,\n }: {\n children: ReactNode\n logic?: TLogic\n options?: HookOptions<TLogic>\n actor?: Actor<TLogic>\n }) {\n const actor = (useActorRef as any)(\n providedActor ?? providedLogic,\n providedActor ? undefined : {...actorOptions, ...providedOptions},\n ) as Actor<TLogic>\n const store = useMemo(() => getStore(actor), [actor])\n const snapshot = useStoreSelection(store, identity, Object.is, false)\n const provided = useMemo(() => ({actor, snapshot}), [actor, snapshot])\n registerProvider(actor, SnapshotContext)\n\n return (\n <ReactContext value={actor}>\n <SnapshotContext value={provided}>{children}</SnapshotContext>\n </ReactContext>\n )\n }\n\n Provider.displayName = `ActorProvider`\n\n function useContext(): Actor<TLogic> {\n const actor = use(ReactContext)\n if (!actor) {\n throw new Error(\n `You used a hook from \"${Provider.displayName}\" but it's not inside a <${Provider.displayName}> component.`,\n )\n }\n return actor\n }\n\n function useSelector<T>(\n selector: (snapshot: SnapshotFrom<TLogic>) => T,\n compare?: (a: T, b: T) => boolean,\n ): T {\n return useSelectorUnbound(useContext(), selector, compare)\n }\n\n function useSend(): Actor<TLogic>['send'] {\n return useSendUnbound(useContext())\n }\n\n function useOptimisticSend(): Actor<TLogic>['send'] {\n return useOptimisticSendUnbound(useContext())\n }\n\n return {Provider, useActorRef: useContext, useSelector, useSend, useOptimisticSend}\n}\n","function is(x: unknown, y: unknown) {\n if (x === y) {\n return x !== 0 || y !== 0 || 1 / x === 1 / y\n }\n return x !== x && y !== y\n}\n\n/** @public */\nexport function shallowEqual(objA: any, objB: any): boolean {\n if (is(objA, objB)) {\n return true\n }\n if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {\n return false\n }\n const keysA = Object.keys(objA)\n const keysB = Object.keys(objB)\n if (keysA.length !== keysB.length) {\n return false\n }\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(objB, key) || !is(objA[key], objB[key])) {\n return false\n }\n }\n return true\n}\n","import {useMemo} from 'react'\nimport type {\n Actor,\n AnyActorLogic,\n ConditionalRequired,\n IsNotNever,\n RequiredActorOptionsFor,\n RequiredActorOptionsKeys,\n SnapshotFrom,\n} from 'xstate'\n\nimport {getStore} from './store'\nimport {\n isActor,\n recreate,\n useActorLifecycle,\n useIdleActorRef,\n type HookOptions,\n} from './useActorRef'\nimport {useStoreSelection} from './useStoreSelection'\n\nfunction identity<T>(value: T): T {\n return value\n}\n\n/**\n * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`) and\n * subscribes to its snapshot. Create a passed actor once, e.g.\n * `useState(() => restoreActor(machine, persisted))[0]`.\n *\n * The snapshot is held in React state, and this hook is the only subscriber that puts it there.\n * `send` sends in a transition: the one it is called in, or a transition of its own. For an update\n * that must show right away, like a controlled input's `onChange`, use `useOptimisticSend(actor)`.\n *\n * The logic passed on the first render is used for the component's lifetime, and `input` is read\n * once. To start over, or to switch to a different machine, change the component's `key`.\n *\n * @public\n */\nexport function useActor<TLogic extends AnyActorLogic>(\n actor: Actor<TLogic>,\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>]\n/** @public */\nexport function useActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: ConditionalRequired<\n [options?: HookOptions<TLogic> & RequiredActorOptionsFor<TLogic>],\n IsNotNever<RequiredActorOptionsKeys<TLogic>>\n >\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>]\nexport function useActor<TLogic extends AnyActorLogic>(\n logic: TLogic | Actor<TLogic>,\n options?: HookOptions<TLogic>,\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send'], Actor<TLogic>] {\n const readyActor = isActor(logic)\n if (!readyActor && !!logic && 'send' in logic && typeof logic.send === 'function') {\n throw new Error(\n `useActor() expects actor logic (e.g. a machine), but received an ActorRef. Pass an Actor created with createActor()/restoreActor(), or use the useSelector(actorRef, ...) hook to read an ActorRef's snapshot.`,\n )\n }\n\n const [actorRef, setActorRef] = useIdleActorRef(logic, options)\n const store = useMemo(() => getStore(actorRef), [actorRef])\n const snapshot = useStoreSelection(store, identity, Object.is) as SnapshotFrom<TLogic>\n\n useActorLifecycle(actorRef, setActorRef, () =>\n recreate(actorRef, readyActor ? actorRef.options : options),\n )\n\n return [snapshot, store.send as Actor<TLogic>['send'], actorRef]\n}\n","import type {\n Actor,\n AnyStateMachine,\n ConditionalRequired,\n IsNotNever,\n RequiredActorOptionsFor,\n RequiredActorOptionsKeys,\n StateFrom,\n} from 'xstate'\n\nimport {useActor} from './useActor'\nimport type {HookOptions} from './useActorRef'\n\n/**\n * @deprecated Use `useActor(machine, options)`.\n * @public\n */\nexport function useMachine<TMachine extends AnyStateMachine>(\n actor: Actor<TMachine>,\n): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>]\n/**\n * @deprecated Use `useActor(machine, options)`.\n * @public\n */\nexport function useMachine<TMachine extends AnyStateMachine>(\n machine: TMachine,\n ...[options]: ConditionalRequired<\n [options?: HookOptions<TMachine> & RequiredActorOptionsFor<TMachine>],\n IsNotNever<RequiredActorOptionsKeys<TMachine>>\n >\n): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>]\nexport function useMachine<TMachine extends AnyStateMachine>(\n machine: TMachine | Actor<TMachine>,\n options?: HookOptions<TMachine>,\n): [StateFrom<TMachine>, Actor<TMachine>['send'], Actor<TMachine>] {\n return (useActor as any)(machine, options)\n}\n"],"mappings":";;;;AAGA,MAAa,cAA6B,OAAO,aAAa,GAWxD,4BAAY,IAAI,QAAgC;;;;;AAMtD,SAAgB,wBAAyC;CACvD,OAAO,cAA+B,IAAI;AAC5C;;AAGA,SAAgB,iBAAiB,OAAc,SAAgC;CAC7E,UAAU,IAAI,OAAO,OAAO;AAC9B;;AAGA,SAAgB,oBAAoB,OAAmC;CACrE,IAAM,UAAU,QAAQ,UAAU,IAAI,KAAK,IAAI,KAAA,GACzC,WAAW,UAAU,IAAI,OAAO,IAAI;CAC1C,OAAO,YAAY,SAAS,UAAU,QAAQ,SAAS,WAAW;AACpE;;;;;ACmBA,IAAa,aAAb,MAAwB;CACb;CACT,UAAmB;CACX;CACA,MAAM;CACN,UAAU;CACD,4BAAY,IAAI,IAAc;CACvC;CAER,YAAY,OAAsB;EAChC,KAAK,QAAQ,OACb,KAAK,OAAO;GAAC,UAAU,MAAM,YAAY;GAAG,KAAK;GAAG,SAAS;EAAC;CAChE;;CAGA,OAAc;EAIZ,OAHK,KAAK,oBACR,KAAK,KAAK,EAAK,GAEV,KAAK;CACd;CAEA,UAAU,UAAgC;EAExC,IADA,KAAK,UAAU,IAAI,QAAQ,GACvB,CAAC,KAAK,kBAAkB;GAC1B,IAAM,eAAe,KAAK,MAAM,UAAU;IACxC,YAAY,KAAK,KAAK,EAAI;IAC1B,aAAa,KAAK,KAAK,EAAI;GAC7B,CAAC;GACD,KAAK,yBAAyB,aAAa,YAAY,GACvD,KAAK,KAAK,EAAI;EAChB;EACA,aAAa;GACX,KAAK,UAAU,OAAO,QAAQ,GAC1B,KAAK,UAAU,SAAS,MAC1B,KAAK,mBAAmB,GACxB,KAA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M,QAAQC,IACR,WAAW,kBAAkB,OAAO,UAAU,OAAO,EAAE,GAEpBC;CACPC,EAAAA,OAAAA,YAAAA,EAAAA,OAAmB,WAAA,EAAA,OAAhC,cADoBD,WACvC,SAAS,UAAU,aAAa,SAAS,UAAU,OAAO,GAA1BC,EAAAA,KAAAA,UAAmB,EAAA,KAAA,SAAhC,EAAA,KAAA,Y,wBADrB,kBAAkB,UAAU,aAAaD,EAEzC;CAEkBE,IAAAA,KAAAA,MAAM,MAAjBC;CAAP,OAAuD,EAAA,OAAA,YAAA,EAAA,OAA/C,YAAA,EAAA,QAAUD,MAAXC,KAAAA;EAAC;EAAUD;EAAqC;CAAQ,GAAR,EAAA,KAAA,UAA/C,EAAA,KAAA,UAAUA,EAAAA,MAAAA,I,0BAAXC;AACT;ACvCA,SAAgB,WACd,SACA,SACiE;CACjE,OAAQ,SAAiB,SAAS,OAAO;AAC3C"}
1
+ {"version":3,"file":"index.js","names":["new Map<Actor<TLogic>, () => void>()","() => setActorRef(create(actorRef.logic, options))","logic","() => {\n const pendingStops = pendingStopsRef.current\n const cancelPendingStop = pendingStops.get(actorRef)\n if (cancelPendingStop) {\n cancelPendingStop()\n pendingStops.delete(actorRef)\n }\n\n // A stopped actor cannot be restarted, so one that stopped before this effect reconnected is\n // replaced.\n if (\n (actorRef as any)._processingStatus === 2 &&\n (actorRef.getSnapshot() as any)?.status === 'stopped'\n ) {\n replace()\n return\n }\n\n actorRef.start()\n // Stopping waits a microtask so that StrictMode's simulated unmount and remount, and a move\n // within the tree, keep the running actor.\n return () => {\n let canceled = false\n const cancel = () => {\n canceled = true\n }\n pendingStops.set(actorRef, cancel)\n queueMicrotask(() => {\n if (!canceled) {\n actorRef.stop()\n }\n if (pendingStops.get(actorRef) === cancel) {\n pendingStops.delete(actorRef)\n }\n })\n }\n }","[actorRef]","hotSwapActorLogic","() => ({actor, snapshot: actor.getSnapshot()})","actor.getSnapshot()","{actor, snapshot: actor.getSnapshot()}","() => {\n let pushed: unknown = undefined\n function update(snapshot: SnapshotFrom<TLogic>): void {\n if (snapshot === pushed) {\n return\n }\n pushed = snapshot\n startTransition(() => {\n setState((previous) =>\n previous.actor === actor && previous.snapshot === snapshot ? previous : {actor, snapshot},\n )\n })\n }\n const subscription = actor.subscribe({\n next: update,\n error: () => update(actor.getSnapshot()),\n })\n // The actor may have moved on between render and subscribing.\n update(actor.getSnapshot())\n return () => subscription.unsubscribe()\n }","[actor]","snapshot","(event: unknown) => {\n startTransition(() => {\n actorRef.send(event as never)\n })\n }","[snapshot, send]"],"sources":["../src/actorRef.ts","../src/useActorSnapshot.ts","../src/useActor.ts"],"sourcesContent":["import {useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState} from 'react'\nimport {\n _hotSwapActorLogic as hotSwapActorLogic,\n Actor,\n createActor,\n type ActorOptions,\n type AnyActorLogic,\n type AnyStateMachine,\n} from 'xstate'\n\nfunction isStateMachine(logic: AnyActorLogic): logic is AnyStateMachine {\n return (\n typeof (logic as any).provide === 'function' &&\n !!(logic as any).config &&\n !!(logic as any).sources\n )\n}\n\nexport function isActor(value: unknown): value is Actor<AnyActorLogic> {\n return value instanceof Actor\n}\n\n// The hook updates the sources of its machine on later renders. A per-hook copy keeps those\n// updates from reaching the caller's machine, which other actors may share.\nfunction ownLogic<TLogic extends AnyActorLogic>(logic: TLogic): TLogic {\n return isStateMachine(logic) ? (logic.provide({}) as any) : logic\n}\n\nfunction create<TLogic extends AnyActorLogic>(\n logic: TLogic,\n options: ActorOptions<TLogic> | undefined,\n): Actor<TLogic> {\n return createActor(logic, options as ActorOptions<TLogic>)\n}\n\nfunction adoptLogic<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n logic: TLogic,\n refreshed: boolean,\n options: ActorOptions<TLogic> | undefined,\n setActorRef: (actorRef: Actor<TLogic>) => void,\n): void {\n const currentLogic = actorRef.logic\n if ((logic as any).config === (currentLogic as any).config) {\n if (isStateMachine(logic) && isStateMachine(currentLogic)) {\n currentLogic.sources = logic.sources\n }\n return\n }\n // Fast Refresh re-evaluated the module that defines the machine: keep the running actor and\n // carry its live snapshot over, or start a fresh actor if it cannot be carried.\n if (refreshed) {\n const nextLogic = ownLogic(logic)\n if (!hotSwapActorLogic(actorRef, nextLogic as any as AnyStateMachine)) {\n setActorRef(create(nextLogic, options))\n }\n }\n}\n\nexport function useIdleActorRef<TLogic extends AnyActorLogic>(\n logicOrActor: TLogic | Actor<TLogic>,\n options: ActorOptions<TLogic> | undefined,\n): [Actor<TLogic>, (actorRef: Actor<TLogic>) => void] {\n // React Compiler would turn the `useMemo` below into a cache slot that Fast Refresh never resets.\n 'use no memo'\n const [actorRef, setActorRef] = useState(() =>\n isActor(logicOrActor) ? logicOrActor : create(ownLogic(logicOrActor), options),\n )\n // Its identity changes only when React Fast Refresh re-renders this component: Fast Refresh\n // ignores dependency lists while it applies an update.\n const refreshSignal = useMemo(() => ({}), [])\n const refreshSignalRef = useRef(refreshSignal)\n\n // The logic passed on the first render is used for the hook's lifetime. Later renders only\n // contribute implementations provided with `machine.provide()` for the same machine config.\n useLayoutEffect(() => {\n const refreshed = refreshSignalRef.current !== refreshSignal\n refreshSignalRef.current = refreshSignal\n if (!isActor(logicOrActor)) {\n adoptLogic(actorRef, logicOrActor, refreshed, options, setActorRef)\n }\n }, [actorRef, logicOrActor, refreshSignal, options])\n\n return [actorRef, setActorRef]\n}\n\nexport function useActorLifecycle<TLogic extends AnyActorLogic>(\n actorRef: Actor<TLogic>,\n setActorRef: (actorRef: Actor<TLogic>) => void,\n options: ActorOptions<TLogic> | undefined,\n): void {\n const pendingStopsRef = useRef(new Map<Actor<TLogic>, () => void>())\n const replace = useEffectEvent(() => setActorRef(create(actorRef.logic, options)))\n\n useEffect(() => {\n const pendingStops = pendingStopsRef.current\n const cancelPendingStop = pendingStops.get(actorRef)\n if (cancelPendingStop) {\n cancelPendingStop()\n pendingStops.delete(actorRef)\n }\n\n // A stopped actor cannot be restarted, so one that stopped before this effect reconnected is\n // replaced.\n if (\n (actorRef as any)._processingStatus === 2 &&\n (actorRef.getSnapshot() as any)?.status === 'stopped'\n ) {\n replace()\n return\n }\n\n actorRef.start()\n // Stopping waits a microtask so that StrictMode's simulated unmount and remount, and a move\n // within the tree, keep the running actor.\n return () => {\n let canceled = false\n const cancel = () => {\n canceled = true\n }\n pendingStops.set(actorRef, cancel)\n queueMicrotask(() => {\n if (!canceled) {\n actorRef.stop()\n }\n if (pendingStops.get(actorRef) === cancel) {\n pendingStops.delete(actorRef)\n }\n })\n }\n }, [actorRef])\n}\n","import {startTransition, useEffect, useState} from 'react'\nimport type {Actor, AnyActorLogic, SnapshotFrom} from 'xstate'\n\ninterface State<TLogic extends AnyActorLogic> {\n readonly actor: Actor<TLogic>\n readonly snapshot: SnapshotFrom<TLogic>\n}\n\nfunction isErrored(snapshot: unknown): snapshot is {error: unknown} {\n return (\n !!snapshot &&\n typeof snapshot === 'object' &&\n 'status' in snapshot &&\n snapshot.status === 'error' &&\n 'error' in snapshot\n )\n}\n\n/**\n * Holds the snapshot of `actor` in React state, and subscribes to the actor to keep it up to date.\n * This is the only place a snapshot enters React.\n *\n * The snapshot is read from the actor only to initialize the state. Later snapshots arrive as\n * values in state updates, and every one of them is a transition: the one that sent the event, or\n * a transition of its own. So a snapshot change never reveals a transition that is still\n * suspended, and every update renders, and commits, one consistent snapshot.\n */\nexport function useActorSnapshot<TLogic extends AnyActorLogic>(\n actor: Actor<TLogic>,\n): SnapshotFrom<TLogic> {\n const [state, setState] = useState<State<TLogic>>(() => ({actor, snapshot: actor.getSnapshot()}))\n let current = state\n if (state.actor !== actor) {\n // A new actor, e.g. one that replaced a stopped actor: its snapshot is read once, like the\n // initial state's.\n current = {actor, snapshot: actor.getSnapshot()}\n setState(current)\n }\n\n useEffect(() => {\n let pushed: unknown = undefined\n function update(snapshot: SnapshotFrom<TLogic>): void {\n if (snapshot === pushed) {\n return\n }\n pushed = snapshot\n startTransition(() => {\n setState((previous) =>\n previous.actor === actor && previous.snapshot === snapshot ? previous : {actor, snapshot},\n )\n })\n }\n const subscription = actor.subscribe({\n next: update,\n error: () => update(actor.getSnapshot()),\n })\n // The actor may have moved on between render and subscribing.\n update(actor.getSnapshot())\n return () => subscription.unsubscribe()\n }, [actor])\n\n const snapshot: unknown = current.snapshot\n if (isErrored(snapshot)) {\n throw snapshot.error\n }\n return current.snapshot\n}\n","import {startTransition, useMemo} from 'react'\nimport type {\n Actor,\n ActorOptions,\n AnyActorLogic,\n ConditionalRequired,\n IsNotNever,\n RequiredActorOptionsFor,\n RequiredActorOptionsKeys,\n SnapshotFrom,\n} from 'xstate'\n\nimport {isActor, useActorLifecycle, useIdleActorRef} from './actorRef'\nimport {useActorSnapshot} from './useActorSnapshot'\n\n/**\n * Creates an actor from `logic` (or uses an already-created `actor`, e.g. from `restoreActor`),\n * starts it on mount, stops it on unmount, and returns its snapshot and a `send` for it. Create a\n * passed actor once, e.g. `useState(() => restoreActor(machine, persisted))[0]`.\n *\n * Every snapshot change renders as a transition. `send` sends in a transition: the one it is called\n * in, or a transition of its own. For UI that must update right away, like a controlled input, hold\n * the value with `useOptimistic` in the component that renders it, and call `send` from the action\n * that sets it.\n *\n * The logic passed on the first render is used for the component's lifetime, and `options` are\n * read once. To start over, or to switch to a different machine, change the component's `key`.\n *\n * @public\n */\nexport function useActor<TLogic extends AnyActorLogic>(\n actor: Actor<TLogic>,\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send']]\n/** @public */\nexport function useActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: ConditionalRequired<\n [options?: ActorOptions<TLogic> & RequiredActorOptionsFor<TLogic>],\n IsNotNever<RequiredActorOptionsKeys<TLogic>>\n >\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send']]\nexport function useActor<TLogic extends AnyActorLogic>(\n logic: TLogic | Actor<TLogic>,\n options?: ActorOptions<TLogic>,\n): [SnapshotFrom<TLogic>, Actor<TLogic>['send']] {\n const readyActor = isActor(logic)\n if (!readyActor && !!logic && 'send' in logic && typeof logic.send === 'function') {\n throw new Error(\n `useActor() expects actor logic (e.g. a machine) or an Actor created with createActor() or restoreActor(), but received another kind of actor ref.`,\n )\n }\n\n const [actorRef, setActorRef] = useIdleActorRef(logic, options)\n const snapshot = useActorSnapshot(actorRef)\n const send = useMemo(\n () =>\n ((event: unknown) => {\n startTransition(() => {\n actorRef.send(event as never)\n })\n }) as Actor<TLogic>['send'],\n [actorRef],\n )\n\n useActorLifecycle(actorRef, setActorRef, readyActor ? actorRef.options : options)\n\n return [snapshot, send]\n}\n"],"mappings":";;;AAUA,SAAS,eAAe,OAAgD;CACtE,OACE,OAAQ,MAAc,WAAY,cAClC,CAAC,CAAE,MAAc,UACjB,CAAC,CAAE,MAAc;AAErB;AAEA,SAAgB,QAAQ,OAA+C;CACrE,OAAO,iBAAiB;AAC1B;AAIA,SAAS,SAAuC,OAAuB;CACrE,OAAO,eAAe,KAAK,IAAK,MAAM,QAAQ,CAAC,CAAC,IAAY;AAC9D;AAEA,SAAS,OACP,OACA,SACe;CACf,OAAO,YAAY,OAAO,OAA+B;AAC3D;AAEA,SAAS,WACP,UACA,OACA,WACA,SACA,aACM;CACN,IAAM,eAAe,SAAS;CAC9B,IAAK,MAAc,WAAY,aAAqB,QAC9C,eAAe,KAAK,KAAK,eAAe,YAAY,MACtD,aAAa,UAAU,MAAM;MAMjC,IAAI,WAAW;EACb,IAAM,YAAY,SAAS,KAAK;EAC3BK,mBAAkB,UAAU,SAAmC,KAClE,YAAY,OAAO,WAAW,OAAO,CAAC;CAE1C;AACF;AAEA,SAAgB,gBACd,cACA,SACoD;CAEpD;CACA,IAAM,CAAC,UAAU,eAAe,eAC9B,QAAQ,YAAY,IAAI,eAAe,OAAO,SAAS,YAAY,GAAG,OAAO,CAC/E,GAGM,gBAAgB,eAAe,CAAC,IAAI,CAAC,CAAC,GACtC,mBAAmB,OAAO,aAAa;CAY7C,OARA,sBAAsB;EACpB,IAAM,YAAY,iBAAiB,YAAY;EAC/C,iBAAi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,iBAAiB,QAAQ,GAGrCC;CAEG,EAAA,OAAA,W,aAFHA,MAAC,UAAmB;EACnB,sBAAsB;GACpB,SAAS,KAAK,KAAc;EAC9B,CAAC;CACH,GAFI,EAAA,KAAA,U;CAJR,IAAM,OAEDA;CAQL,kBAAkB,UAAU,aAAa,aAAa,SAAS,UAAU,OAAO;CAEzEC,IAAAA;CAAP,OAAkB,EAAA,OAAA,QAAA,EAAA,OAAV,YAADA,KAAAA,CAAC,UAAU,IAAI,GAAJ,EAAA,KAAA,MAAV,EAAA,KAAA,U,wBAADA;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity-labs/xstate-react",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "React 19 bindings for XState v6, built for transitions and useOptimistic",
5
5
  "keywords": [
6
6
  "concurrent",
@@ -56,13 +56,13 @@
56
56
  "rxjs": "^7.8.2",
57
57
  "tsdown": "^0.23.7",
58
58
  "typescript": "7.0.2",
59
- "vite": "^8.3.8",
59
+ "vite": "^8.4.0",
60
60
  "vitest": "^5.1.2",
61
61
  "xstate": "6.0.0-beta.5",
62
- "zod": "^3.25.76"
62
+ "zod": "^4.6.7"
63
63
  },
64
64
  "peerDependencies": {
65
- "react": "^19.3",
65
+ "react": "^19.3.1",
66
66
  "xstate": "^6.0.0-beta"
67
67
  },
68
68
  "engines": {