@sanity-labs/xstate-react 0.0.0 → 0.2.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
@@ -2,6 +2,8 @@
2
2
 
3
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`.
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.
6
+
5
7
  ## Requirements
6
8
 
7
9
  - `react` and `react-dom` `^19.3`. `addTransitionType` is stable from React 19.3.
@@ -40,11 +42,37 @@ function Counter() {
40
42
 
41
43
  - `useActor(logic, options)` creates an actor, starts it, and returns `[snapshot, send, actor]`. `useMachine` is a deprecated alias.
42
44
  - `useActorRef(logic, options)` creates and starts an actor without subscribing to its snapshot.
43
- - `useSelector(actor, selector, compare?)` re-renders only when the selected value changes. `shallowEqual` is exported for use as `compare`.
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`.
44
46
  - `useSend(actor)` returns the same `send` that `useActor` returns, for an actor created with `useActorRef` or received as a prop.
45
- - `createActorContext(logic, options)` returns `{Provider, useSelector, useSend, useActorRef}` for sharing one actor with a subtree.
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
51
+
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.
53
+
54
+ ```tsx
55
+ import {createActorContext} from '@sanity-labs/xstate-react'
56
+
57
+ const Counter = createActorContext(counterMachine)
58
+
59
+ function Count() {
60
+ const count = Counter.useSelector((snapshot) => snapshot.context.count)
61
+ return <output>{count}</output>
62
+ }
46
63
 
47
- Use `send` from these hooks rather than `actor.send`: it is the one that takes part in transitions and optimistic updates.
64
+ function App() {
65
+ return (
66
+ <Counter.Provider>
67
+ <Count />
68
+ </Counter.Provider>
69
+ )
70
+ }
71
+ ```
72
+
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.
74
+
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.
48
76
 
49
77
  ### The first machine, and `key` to start over
50
78
 
@@ -61,7 +89,7 @@ function Checkout({onPaid}: {onPaid: () => void}) {
61
89
  }
62
90
  ```
63
91
 
64
- Props the machine should react to after mounting are events. Send them from an effect:
92
+ Props the machine should react to after mounting are events. Send them from an effect. `send` wraps the event in `startTransition`, so the change renders as a transition, like one from an event handler:
65
93
 
66
94
  ```tsx
67
95
  import {useActor} from '@sanity-labs/xstate-react'
@@ -82,11 +110,40 @@ To start over with fresh `input`, or to switch to a different machine, give the
82
110
  <Stepper key={documentId} start={1} limit={10} />
83
111
  ```
84
112
 
113
+ The same goes for switching machines:
114
+
115
+ ```tsx
116
+ <Editor key={mode} machine={mode === 'draft' ? draftMachine : reviewMachine} />
117
+ ```
118
+
119
+ ### Restoring an actor
120
+
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:
122
+
123
+ ```tsx
124
+ import {useActor} from '@sanity-labs/xstate-react'
125
+ import {useState} from 'react'
126
+ import type {SnapshotFrom} from 'xstate'
127
+ import {restoreActor} from 'xstate/persist'
128
+
129
+ function Editor({persisted}: {persisted: SnapshotFrom<typeof editorMachine>}) {
130
+ const [actor] = useState(() => restoreActor(editorMachine, persisted))
131
+ const [snapshot, send] = useActor(actor)
132
+ // ...
133
+ }
134
+ ```
135
+
136
+ ### Starting and stopping
137
+
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.
139
+
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.
141
+
85
142
  ### Transitions
86
143
 
87
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.
88
145
 
89
- Called inside `startTransition`, `send` joins that transition, including its `addTransitionType` types, so `<ViewTransition>` can animate the change:
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:
90
147
 
91
148
  ```tsx
92
149
  import {useActor} from '@sanity-labs/xstate-react'
@@ -115,7 +172,7 @@ function Slides() {
115
172
  }
116
173
  ```
117
174
 
118
- As with any state update, a `send` after an `await` in an async transition is no longer part of it. Wrap it in `startTransition` again:
175
+ As with any state update, a `send` after an `await` in an async transition is no longer part of it: it is a transition of its own. Types added before the `await` aren't tied to it either: React applies them to the next transition that commits. Wrap the `send` in `startTransition` again, and add the types it needs there:
119
176
 
120
177
  ```tsx
121
178
  startTransition(async () => {
@@ -128,13 +185,14 @@ startTransition(async () => {
128
185
 
129
186
  ### Controlled inputs
130
187
 
131
- A controlled input has to show what was typed right away, but a transition renders later. When `send` is called outside a transition, as in an `onChange` handler, the event's outcome is computed with XState's `transition()` and shown with `useOptimistic` until the transition renders. The caret stays where it was:
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:
132
189
 
133
190
  ```tsx
134
- import {useActor} from '@sanity-labs/xstate-react'
191
+ import {useActor, useOptimisticSend} from '@sanity-labs/xstate-react'
135
192
 
136
193
  function Search() {
137
- const [snapshot, send] = useActor(searchMachine)
194
+ const [snapshot, , actor] = useActor(searchMachine)
195
+ const send = useOptimisticSend(actor)
138
196
  return (
139
197
  <input
140
198
  value={snapshot.context.query}
@@ -144,7 +202,9 @@ function Search() {
144
202
  }
145
203
  ```
146
204
 
147
- Components that manage their own optimistic state and call an action prop inside a transition work too. Pass `send` from the action:
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
+
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:
148
208
 
149
209
  ```tsx
150
210
  import {createActorContext} from '@sanity-labs/xstate-react'
@@ -160,13 +220,17 @@ function Filters() {
160
220
 
161
221
  ### Updates `send` did not cause
162
222
 
163
- Delayed transitions, invoked promises and child actors change the snapshot without a `send`. By default these changes render as transitions too. Pass `updates: 'sync'` to render them as regular updates instead:
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:
164
226
 
165
227
  ```tsx
166
- const [snapshot] = useActor(timerMachine, {updates: 'sync'})
228
+ const [snapshot] = useActor(toastMachine, {updates: 'sync'})
167
229
  ```
168
230
 
169
- `send` is a transition either way.
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.
170
234
 
171
235
  ## License
172
236
 
package/dist/index.d.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import { ReactNode } from "react";
2
2
  import { Actor, ActorOptions, AnyActorLogic, AnyActorRef, AnyStateMachine, ConditionalRequired, IsNotNever, Observer, RequiredActorOptionsFor, RequiredActorOptionsKeys, SnapshotFrom, StateFrom } from "xstate";
3
3
  /**
4
- * How snapshot changes that `send` did not cause, such as delayed transitions and invoked actors
5
- * settling, reach React.
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
6
  *
7
- * - `'transition'` (default): as transition updates.
8
- * - `'sync'`: as regular updates, with the priority of whatever triggered them.
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.
9
12
  *
10
13
  * @public
11
14
  */
@@ -13,8 +16,8 @@ type Updates = 'transition' | 'sync';
13
16
  /** @public */
14
17
  interface BindingOptions {
15
18
  /**
16
- * How snapshot changes that `send` did not cause, such as delayed transitions and invoked
17
- * actors settling, reach React. Defaults to `'transition'`.
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'`.
18
21
  */
19
22
  updates?: Updates;
20
23
  }
@@ -40,10 +43,18 @@ export declare function useActorRef<TLogic extends AnyActorLogic>(actor: Actor<T
40
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>;
41
44
  /** @public */
42
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
+ */
43
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. */
44
53
  useActorRef: () => Actor<TLogic>;
45
- /** The provided actor's `send`, with the same transition and optimistic behavior as `useActor`. */
54
+ /** The provided actor's `send`, which sends in a transition, like the one `useActor` returns. */
46
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'];
47
58
  Provider: (props: {
48
59
  children: ReactNode;
49
60
  options?: HookOptions<TLogic>;
@@ -64,9 +75,9 @@ export declare function shallowEqual(objA: any, objB: any): boolean;
64
75
  * subscribes to its snapshot. Create a passed actor once, e.g.
65
76
  * `useState(() => restoreActor(machine, persisted))[0]`.
66
77
  *
67
- * `send` is a transition: snapshot updates it causes render together with the transition it is
68
- * called in, or in a transition of its own. Until that transition settles, the returned snapshot
69
- * already shows the event's outcome, so a controlled input can call `send` in `onChange`.
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)`.
70
81
  *
71
82
  * The logic passed on the first render is used for the component's lifetime, and `input` is read
72
83
  * once. To start over, or to switch to a different machine, change the component's `key`.
@@ -87,8 +98,12 @@ export declare function useMachine<TMachine extends AnyStateMachine>(actor: Acto
87
98
  */
88
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>];
89
100
  /**
90
- * Reads a value derived from an actor's snapshot, and re-renders only when `compare` says it
91
- * changed.
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.
92
107
  *
93
108
  * @public
94
109
  */
@@ -97,10 +112,21 @@ export declare function useSelector<TActor extends Pick<AnyActorRef, 'subscribe'
97
112
  } ? TSnapshot : undefined) => T, compare?: (a: T, b: T) => boolean): T;
98
113
  /**
99
114
  * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with
100
- * `useActorRef` or `createActorContext`.
115
+ * `useActorRef` or `createActorContext`. It sends in a transition: the one it is called in, or a
116
+ * transition of its own.
101
117
  *
102
118
  * @public
103
119
  */
104
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'];
105
131
  export type { ActorContext, BindingOptions, HookOptions, Updates };
106
132
  //# 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":";;;;;;;;;;;KAsBY;;UAGK;;;;;EAKf,UAAU;;;;;;;;KCNA,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;;UCxLQ,aAAa,eAAe;EAC3C,cAAc,GACZ,WAAW,UAAU,aAAa,YAAY,GAC9C,WAAW,GAAG,GAAG,GAAG,kBACjB;EACL,mBAAmB,MAAM;;EAEzB,eAAe,MAAM;EACrB,WAAW;IACT,UAAU;IACV,UAAU,YAAY;IACtB,QAAQ;;;;;IAKR,QAAQ,MAAM;QACV;;;wBAIQ,mBAAmB,eAAe,eAChD,YAAY,QACZ,eAAe,YAAY,UAC1B,aAAa;;wBCxBA,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;;;;;;;wBCdxC,YACd,eAAe,KAAK,uDACpB,GAEA,OAAO,QACP,WACE,UAAU;EAAgB,qBAAqB;IAAa,0BACzD,GACL,WAAU,GAAG,GAAG,GAAG,gBAClB;;;;;;;wBCda,QAAQ,eAAe,aAAa,OAAO,SAAS"}
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"}
package/dist/index.js CHANGED
@@ -1,91 +1,88 @@
1
- import * as React from "react";
2
- import { createContext, startTransition, use, useEffect, useEffectEvent, useInsertionEffect, useLayoutEffect, useMemo, useOptimistic, useRef, useState } from "react";
3
- import { c } from "react/compiler-runtime";
1
+ import { createContext, startTransition, use, useEffect, useEffectEvent, useLayoutEffect, useMemo, useOptimistic, useRef, useState } from "react";
4
2
  import { Actor, _hotSwapActorLogic, _toObserver, createActor, transition } from "xstate";
3
+ import { c } from "react/compiler-runtime";
5
4
  import { jsx } from "react/jsx-runtime";
6
- const internals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
7
- function isInTransition() {
8
- return internals?.T != null;
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);
9
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
+ */
10
26
  var ActorStore = class {
11
27
  actor;
12
28
  updates = "transition";
13
29
  head;
14
- /** The newest entry React has committed, which a component mounting outside a transition sees. */
15
- committed;
16
30
  seq = 0;
17
31
  version = 0;
18
- sending = 0;
19
32
  listeners = /* @__PURE__ */ new Set();
20
- lagging = /* @__PURE__ */ new Set();
21
33
  unsubscribeActor;
22
34
  constructor(actor) {
23
35
  this.actor = actor, this.head = {
24
36
  snapshot: actor.getSnapshot(),
25
37
  seq: 0,
26
38
  version: 0
27
- }, this.committed = this.head;
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;
28
44
  }
29
45
  subscribe(listener) {
30
46
  if (this.listeners.add(listener), !this.unsubscribeActor) {
31
47
  let subscription = this.actor.subscribe({
32
- next: () => this.pull(),
33
- error: () => this.pull()
48
+ next: () => this.pull(!0),
49
+ error: () => this.pull(!0)
34
50
  });
35
- this.unsubscribeActor = () => subscription.unsubscribe(), this.pull();
51
+ this.unsubscribeActor = () => subscription.unsubscribe(), this.pull(!0);
36
52
  }
37
53
  return () => {
38
- this.listeners.delete(listener), this.listeners.size === 0 && (this.unsubscribeActor?.(), this.unsubscribeActor = void 0, this.committed = this.head);
54
+ this.listeners.delete(listener), this.listeners.size === 0 && (this.unsubscribeActor?.(), this.unsubscribeActor = void 0);
39
55
  };
40
56
  }
41
- commit(entry) {
42
- entry.version > this.committed.version && (this.committed = entry);
43
- }
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
+ };
44
63
  /**
45
- * Registers a reader that mounted showing `committed` while others were rendering a newer
46
- * snapshot in a transition, to catch up when they commit it. Returns a function that unregisters.
64
+ * Sends `event` in a transition, and shows its outcome right away with `useOptimistic` until that
65
+ * transition settles.
47
66
  */
48
- lag(catchUp) {
49
- return this.lagging.add(catchUp), () => this.lagging.delete(catchUp);
50
- }
51
- /** Called in the layout phase of a commit that included readers of the actor. */
52
- catchUp() {
53
- for (let catchUp of this.lagging) catchUp();
54
- }
55
- send = (event) => {
67
+ sendOptimistic = (event) => {
56
68
  let seq = ++this.seq;
57
- isInTransition() ? this.deliver(event) : startTransition(() => {
69
+ startTransition(() => {
58
70
  let logic = this.actor.logic;
59
71
  if (logic) for (let listener of this.listeners) listener.optimistic({
60
72
  logic,
61
73
  event,
62
74
  seq
63
75
  });
64
- this.deliver(event);
76
+ this.actor.send(event);
65
77
  });
66
78
  };
67
- deliver(event) {
68
- this.sending++;
69
- try {
70
- this.actor.send(event);
71
- } finally {
72
- this.sending--;
73
- }
74
- }
75
- pull() {
79
+ pull(notify) {
76
80
  let snapshot = this.actor.getSnapshot();
77
- if (snapshot === this.head.snapshot) return;
78
- if (this.head = {
81
+ if (snapshot !== this.head.snapshot && (this.head = {
79
82
  snapshot,
80
83
  seq: this.seq,
81
84
  version: ++this.version
82
- }, this.listeners.size === 0) {
83
- this.committed = this.head;
84
- return;
85
- }
86
- let sentInTransition = this.sending > 0, scheduled = !1;
87
- for (let listener of this.listeners) scheduled = listener.update(this.head, sentInTransition) || scheduled;
88
- scheduled || (this.committed = this.head);
85
+ }, notify)) for (let listener of this.listeners) listener.update(this.head);
89
86
  }
90
87
  };
91
88
  const stores = /* @__PURE__ */ new WeakMap();
@@ -187,125 +184,123 @@ function useActorRef(logicOrActor, ...t0) {
187
184
  const emptyEntry = {
188
185
  snapshot: void 0,
189
186
  seq: 0,
190
- version: 0
187
+ version: -1
191
188
  };
192
189
  function isErrored(snapshot) {
193
190
  return !!snapshot && typeof snapshot == "object" && "status" in snapshot && snapshot.status === "error" && "error" in snapshot;
194
191
  }
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
+ }
195
200
  /**
196
- * Reads `selector(snapshot)` from the actor behind `store`.
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.
197
204
  *
198
- * The snapshot lives in React state, so an update that `send` or a transition causes renders, and
199
- * commits, together with the rest of that transition. Events sent with the store's `send` are
200
- * previewed with `useOptimistic` until the transition that sent them settles, which keeps
201
- * controlled inputs in sync.
205
+ * 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.
202
212
  */
203
- function useStoreSelection(store, selector, compare) {
204
- let $ = c(31), t0;
205
- $[0] !== selector || $[1] !== store ? (t0 = () => {
206
- let entry = store?.head;
207
- return {
208
- store,
209
- entry,
210
- selected: selector(entry?.snapshot),
211
- updated: !1
212
- };
213
- }, $[0] = selector, $[1] = store, $[2] = t0) : t0 = $[2];
214
- let [state, setState] = useState(t0), current = state.store === store ? state : void 0, base = current ? current.entry : store?.head, [optimistic, addOptimistic] = useOptimistic(base ?? emptyEntry, reduceOptimistic), selectorRef = useRef(selector), compareRef = useRef(compare), stateRef = useRef(state), lagTargetRef = useRef(void 0), t1;
215
- $[3] !== compare || $[4] !== selector || $[5] !== state ? (t1 = () => {
216
- selectorRef.current = selector, compareRef.current = compare, stateRef.current = state;
217
- }, $[3] = compare, $[4] = selector, $[5] = state, $[6] = t1) : t1 = $[6], useLayoutEffect(t1);
218
- let t2, t3;
219
- $[7] !== current || $[8] !== store ? (t2 = () => {
220
- store && current?.updated && current.entry && store.commit(current.entry);
221
- }, t3 = [store, current], $[7] = current, $[8] = store, $[9] = t2, $[10] = t3) : (t2 = $[9], t3 = $[10]), useInsertionEffect(t2, t3);
222
- let t4, t5;
223
- $[11] === store ? (t4 = $[12], t5 = $[13]) : (t4 = () => {
224
- lagTargetRef.current = void 0;
225
- let mounted = stateRef.current;
226
- if (!store || mounted.store !== store || mounted.updated || mounted.entry === store.committed) return;
227
- let target = mounted.entry;
228
- lagTargetRef.current = target;
229
- let show = (entry_0) => {
230
- let next = {
231
- store,
232
- entry: entry_0,
233
- selected: selectorRef.current(entry_0.snapshot),
234
- updated: !0
235
- };
236
- stateRef.current = next, setState(next);
237
- };
238
- show(store.committed);
239
- let stopLagging = store.lag(() => {
240
- let { committed } = store;
241
- committed.version > (stateRef.current.entry?.version ?? 0) && show(committed), (!target || committed.version >= target.version) && stopLagging();
242
- });
243
- return stopLagging;
244
- }, t5 = [store], $[11] = store, $[12] = t4, $[13] = t5), useLayoutEffect(t4, t5);
245
- let t6;
246
- $[14] !== current?.updated || $[15] !== store ? (t6 = () => {
247
- store && current?.updated && store.catchUp();
248
- }, $[14] = current?.updated, $[15] = store, $[16] = t6) : t6 = $[16];
249
- let t7;
250
- $[17] !== current || $[18] !== store ? (t7 = [store, current], $[17] = current, $[18] = store, $[19] = t7) : t7 = $[19], useLayoutEffect(t6, t7);
251
- let t8, t9;
252
- $[20] === store ? (t8 = $[21], t9 = $[22]) : (t8 = () => {
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 = () => {
253
224
  if (!store) return;
254
- let skipped, apply = function apply(entry_1, asTransition) {
225
+ let skipped, apply = function apply(entry) {
255
226
  let previous = stateRef.current;
256
- if (previous.store === store && previous.entry === entry_1) return !1;
257
- let selected = selectorRef.current(entry_1.snapshot);
258
- if (previous.store === store && !isErrored(entry_1.snapshot) && compareRef.current(previous.selected, selected)) return skipped = entry_1, !1;
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
+ }
259
233
  skipped = void 0;
260
- let next_0 = {
234
+ let next = {
261
235
  store,
262
- entry: entry_1,
263
- selected,
264
- updated: !0
236
+ entry,
237
+ selected
265
238
  };
266
- return stateRef.current = next_0, asTransition ? startTransition(() => setState(next_0)) : setState(next_0), !0;
239
+ stateRef.current = next, store?.updates === "sync" ? setState(next) : startTransition(() => setState(next));
267
240
  }, unsubscribe = store.subscribe({
268
- update(entry_2, sentInTransition) {
269
- return apply(entry_2, sentInTransition || store.updates === "transition");
270
- },
241
+ update: apply,
271
242
  optimistic(action) {
272
- startTransition(() => addOptimistic({
243
+ addOptimistic({
273
244
  ...action,
274
245
  fallback: skipped
275
- }));
246
+ });
276
247
  }
277
- }), seen = stateRef.current.store === store ? stateRef.current.entry : void 0, known = Math.max(seen?.version ?? -1, lagTargetRef.current?.version ?? -1);
278
- return store.head.version > known && apply(store.head, store.updates === "transition"), unsubscribe;
279
- }, t9 = [store, addOptimistic], $[20] = store, $[21] = t8, $[22] = t9), useEffect(t8, t9);
280
- let entry_3 = optimistic === emptyEntry ? void 0 : optimistic, snapshot = entry_3?.snapshot;
281
- if (isErrored(snapshot)) throw snapshot.error;
282
- if (current && entry_3 === current.entry) {
283
- let t10;
284
- if ($[23] !== compare || $[24] !== current.selected || $[25] !== selector || $[26] !== snapshot) {
285
- let selected_0 = selector(snapshot);
286
- t10 = compare(current.selected, selected_0) ? current.selected : selected_0, $[23] = compare, $[24] = current.selected, $[25] = selector, $[26] = snapshot, $[27] = t10;
287
- } else t10 = $[27];
288
- return t10;
289
- }
290
- let t10;
291
- return $[28] !== selector || $[29] !== snapshot ? (t10 = selector(snapshot), $[28] = selector, $[29] = snapshot, $[30] = t10) : t10 = $[30], t10;
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;
292
255
  }
293
256
  function defaultCompare(a, b) {
294
257
  return a === b;
295
258
  }
259
+ function ignore() {}
296
260
  /**
297
- * Reads a value derived from an actor's snapshot, and re-renders only when `compare` says it
298
- * changed.
261
+ * Keeps the previous selection while `compare` says it is unchanged, so that what the caller
262
+ * renders from it can be memoized.
263
+ */
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) {
276
+ 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.
299
291
  *
300
292
  * @public
301
293
  */
302
294
  function useSelector(actor, selector, t0) {
303
- let $ = c(2), compare = t0 === void 0 ? defaultCompare : t0, t1;
304
- return $[0] === actor ? t1 = $[1] : (t1 = actor ? getStore(actor) : void 0, $[0] = actor, $[1] = t1), useStoreSelection(t1, selector, compare);
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;
305
299
  }
306
300
  /**
307
301
  * Returns the same `send` that `useActor` returns, for an actor created elsewhere, e.g. with
308
- * `useActorRef` or `createActorContext`.
302
+ * `useActorRef` or `createActorContext`. It sends in a transition: the one it is called in, or a
303
+ * transition of its own.
309
304
  *
310
305
  * @public
311
306
  */
@@ -313,17 +308,39 @@ function useSend(actor) {
313
308
  let $ = c(2), t0;
314
309
  return $[0] === actor ? t0 = $[1] : (t0 = getStore(actor), $[0] = actor, $[1] = t0), t0.send;
315
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
+ }
316
327
  /** @public */
317
328
  function createActorContext(actorLogic, actorOptions) {
318
- let ReactContext = createContext(null);
329
+ let ReactContext = createContext(null), SnapshotContext = createSnapshotContext();
319
330
  function Provider({ children, logic: providedLogic = actorLogic, options: providedOptions, actor: providedActor }) {
320
331
  let actor = useActorRef(providedActor ?? providedLogic, providedActor ? void 0 : {
321
332
  ...actorOptions,
322
333
  ...providedOptions
323
- });
324
- return /* @__PURE__ */ jsx(ReactContext, {
334
+ }), snapshot = useStoreSelection(useMemo(() => getStore(actor), [actor]), identity$1, Object.is, !1), provided = useMemo(() => ({
335
+ actor,
336
+ snapshot
337
+ }), [actor, snapshot]);
338
+ return registerProvider(actor, SnapshotContext), /* @__PURE__ */ jsx(ReactContext, {
325
339
  value: actor,
326
- children
340
+ children: /* @__PURE__ */ jsx(SnapshotContext, {
341
+ value: provided,
342
+ children
343
+ })
327
344
  });
328
345
  }
329
346
  Provider.displayName = "ActorProvider";
@@ -338,11 +355,15 @@ function createActorContext(actorLogic, actorOptions) {
338
355
  function useSend$1() {
339
356
  return useSend(useContext());
340
357
  }
358
+ function useOptimisticSend$1() {
359
+ return useOptimisticSend(useContext());
360
+ }
341
361
  return {
342
362
  Provider,
343
363
  useActorRef: useContext,
344
364
  useSelector: useSelector$1,
345
- useSend: useSend$1
365
+ useSend: useSend$1,
366
+ useOptimisticSend: useOptimisticSend$1
346
367
  };
347
368
  }
348
369
  function is(x, y) {
@@ -379,6 +400,6 @@ function useActor(logic, options) {
379
400
  function useMachine(machine, options) {
380
401
  return useActor(machine, options);
381
402
  }
382
- export { createActorContext, shallowEqual, useActor, useActorRef, useMachine, useSelector, useSend };
403
+ export { createActorContext, shallowEqual, useActor, useActorRef, useMachine, useOptimisticSend, useSelector, useSend };
383
404
 
384
405
  //# 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","() => {\n const entry = store?.head\n return {store, entry, selected: selector(entry?.snapshot), updated: false}\n }","store?.head","() => {\n selectorRef.current = selector\n compareRef.current = compare\n stateRef.current = state\n }","() => {\n if (store && current?.updated && current.entry) {\n store.commit(current.entry)\n }\n }","[store, current]","current?.updated","() => {\n lagTargetRef.current = undefined\n const mounted = stateRef.current\n if (!store || mounted.store !== store || mounted.updated || mounted.entry === store.committed) {\n return\n }\n const target = mounted.entry\n lagTargetRef.current = target\n const show = (entry: Entry) => {\n const next: State<T> = {\n store,\n entry,\n selected: selectorRef.current(entry.snapshot),\n updated: true,\n }\n stateRef.current = next\n setState(next)\n }\n show(store.committed)\n const stopLagging = store.lag(() => {\n const {committed} = store\n if (committed.version > (stateRef.current.entry?.version ?? 0)) {\n show(committed)\n }\n if (!target || committed.version >= target.version) {\n stopLagging()\n }\n })\n return stopLagging\n }","[store]","entry","() => {\n if (store && current?.updated) {\n store.catchUp()\n }\n }","updated","() => {\n if (!store) {\n return\n }\n let skipped: Entry | undefined\n\n function apply(entry: Entry, asTransition: boolean): boolean {\n const previous = stateRef.current\n if (previous.store === store && previous.entry === entry) {\n return false\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 previewing events this component did not render the outcome of.\n if (\n previous.store === store &&\n !isErrored(entry.snapshot) &&\n compareRef.current(previous.selected, selected)\n ) {\n skipped = entry\n return false\n }\n skipped = undefined\n const next: State<T> = {store, entry, selected, updated: true}\n stateRef.current = next\n if (asTransition) {\n startTransition(() => setState(next))\n } else {\n setState(next)\n }\n return true\n }\n\n const unsubscribe = store.subscribe({\n update(entry, sentInTransition) {\n return apply(entry, sentInTransition || store.updates === 'transition')\n },\n optimistic(action) {\n startTransition(() => addOptimistic({...action, fallback: skipped} as OptimisticAction))\n },\n })\n // The snapshot may have changed between render and subscribing.\n const seen = stateRef.current.store === store ? stateRef.current.entry : undefined\n const known = Math.max(seen?.version ?? -1, lagTargetRef.current?.version ?? -1)\n if (store.head.version > known) {\n apply(store.head, store.updates === 'transition')\n }\n return unsubscribe\n }","[store, addOptimistic]","next","compare(current.selected, selected) ? current.selected : selected","selected","selector(snapshot)","compare: (a: T, b: T) => boolean = defaultCompare","actor ? getStore(actor) : undefined","store","getStore(actor)","_jsx","useSelector","useSelectorUnbound","useSend","useSendUnbound","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/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 * as React from 'react'\nimport {startTransition} from 'react'\nimport {transition, type AnyActorLogic, type AnyActorRef} from 'xstate'\n\n// React has no public way to ask whether code runs inside `startTransition`. Its client internals\n// hold the current transition in `T`.\nconst internals: {T: unknown} | undefined = (React as any)\n .__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE\n\nfunction isInTransition(): boolean {\n return internals?.T != null\n}\n\n/**\n * How snapshot changes that `send` did not cause, such as delayed transitions and invoked actors\n * settling, reach React.\n *\n * - `'transition'` (default): as transition updates.\n * - `'sync'`: as regular updates, with the priority of whatever triggered them.\n *\n * @public\n */\nexport type Updates = 'transition' | 'sync'\n\n/** @public */\nexport interface BindingOptions {\n /**\n * How snapshot changes that `send` did not cause, such as delayed transitions and invoked\n * actors settling, reach React. 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 events sent through the store that the snapshot already includes. */\n readonly seq: number\n /** Increases with every snapshot the actor emits, to order entries that share a `seq`. */\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 /** Returns whether the listener scheduled a render for the entry. */\n update(entry: Entry, sentInTransition: boolean): boolean\n optimistic(action: Omit<OptimisticAction, 'fallback'>): void\n}\n\nexport class ActorStore {\n readonly actor: ReadableActor\n updates: Updates = 'transition'\n head: Entry\n /** The newest entry React has committed, which a component mounting outside a transition sees. */\n committed: Entry\n private seq = 0\n private version = 0\n private sending = 0\n private readonly listeners = new Set<Listener>()\n private readonly lagging = new Set<() => void>()\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 this.committed = 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(),\n error: () => this.pull(),\n })\n this.unsubscribeActor = () => subscription.unsubscribe()\n this.pull()\n }\n return () => {\n this.listeners.delete(listener)\n if (this.listeners.size === 0) {\n this.unsubscribeActor?.()\n this.unsubscribeActor = undefined\n this.committed = this.head\n }\n }\n }\n\n commit(entry: Entry): void {\n if (entry.version > this.committed.version) {\n this.committed = entry\n }\n }\n\n /**\n * Registers a reader that mounted showing `committed` while others were rendering a newer\n * snapshot in a transition, to catch up when they commit it. Returns a function that unregisters.\n */\n lag(catchUp: () => void): () => void {\n this.lagging.add(catchUp)\n return () => this.lagging.delete(catchUp)\n }\n\n /** Called in the layout phase of a commit that included readers of the actor. */\n catchUp(): void {\n for (const catchUp of this.lagging) {\n catchUp()\n }\n }\n\n send = (event: unknown): void => {\n const seq = ++this.seq\n if (isInTransition()) {\n this.deliver(event)\n return\n }\n // An urgent send, like one from a controlled input's `onChange`: the outcome is previewed with\n // `useOptimistic`, rebased on what is committed, while the snapshot itself updates in a\n // transition.\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.deliver(event)\n })\n }\n\n private deliver(event: unknown): void {\n this.sending++\n try {\n ;(this.actor as AnyActorRef).send(event)\n } finally {\n this.sending--\n }\n }\n\n private pull(): 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 (this.listeners.size === 0) {\n this.committed = this.head\n return\n }\n const sentInTransition = this.sending > 0\n let scheduled = false\n for (const listener of this.listeners) {\n scheduled = listener.update(this.head, sentInTransition) || scheduled\n }\n // No reader renders anything different, so React already shows this snapshot.\n if (!scheduled) {\n this.committed = this.head\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 {\n startTransition,\n useEffect,\n useInsertionEffect,\n useLayoutEffect,\n useOptimistic,\n useRef,\n useState,\n} 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 | undefined\n readonly selected: T\n /** Whether `entry` came from a snapshot change rather than from mounting. */\n readonly updated: boolean\n}\n\nconst emptyEntry: Entry = {snapshot: undefined, seq: 0, version: 0}\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 * Reads `selector(snapshot)` from the actor behind `store`.\n *\n * The snapshot lives in React state, so an update that `send` or a transition causes renders, and\n * commits, together with the rest of that transition. Events sent with the store's `send` are\n * previewed with `useOptimistic` until the transition that sent them settles, which keeps\n * controlled inputs in sync.\n */\nexport function useStoreSelection<T>(\n store: ActorStore | undefined,\n selector: (snapshot: any) => T,\n compare: (a: T, b: T) => boolean,\n): T {\n const [state, setState] = useState<State<T>>(() => {\n const entry = store?.head\n return {store, entry, selected: selector(entry?.snapshot), updated: false}\n })\n const current = state.store === store ? state : undefined\n const base = current ? current.entry : store?.head\n const [optimistic, addOptimistic] = useOptimistic(base ?? emptyEntry, reduceOptimistic)\n\n const selectorRef = useRef(selector)\n const compareRef = useRef(compare)\n const stateRef = useRef(state)\n const lagTargetRef = useRef<Entry | undefined>(undefined)\n useLayoutEffect(() => {\n selectorRef.current = selector\n compareRef.current = compare\n stateRef.current = state\n })\n\n // Insertion effects of a commit all run before its layout effects, so by the time a component\n // that mounts in this commit checks `store.committed`, it already includes this commit.\n useInsertionEffect(() => {\n if (store && current?.updated && current.entry) {\n store.commit(current.entry)\n }\n }, [store, current])\n\n // A component that mounts while a transition is changing the actor renders that transition's\n // snapshot, which is right only if the transition is the render that mounts it. Otherwise it\n // shows the committed snapshot before paint, and catches up when the other readers commit.\n // Only the snapshot the component mounted with is checked, so it is read from `stateRef`.\n useLayoutEffect(() => {\n lagTargetRef.current = undefined\n const mounted = stateRef.current\n if (!store || mounted.store !== store || mounted.updated || mounted.entry === store.committed) {\n return\n }\n const target = mounted.entry\n lagTargetRef.current = target\n const show = (entry: Entry) => {\n const next: State<T> = {\n store,\n entry,\n selected: selectorRef.current(entry.snapshot),\n updated: true,\n }\n stateRef.current = next\n setState(next)\n }\n show(store.committed)\n const stopLagging = store.lag(() => {\n const {committed} = store\n if (committed.version > (stateRef.current.entry?.version ?? 0)) {\n show(committed)\n }\n if (!target || committed.version >= target.version) {\n stopLagging()\n }\n })\n return stopLagging\n }, [store])\n\n useLayoutEffect(() => {\n if (store && current?.updated) {\n store.catchUp()\n }\n }, [store, current])\n\n useEffect(() => {\n if (!store) {\n return\n }\n let skipped: Entry | undefined\n\n function apply(entry: Entry, asTransition: boolean): boolean {\n const previous = stateRef.current\n if (previous.store === store && previous.entry === entry) {\n return false\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 previewing events this component did not render the outcome of.\n if (\n previous.store === store &&\n !isErrored(entry.snapshot) &&\n compareRef.current(previous.selected, selected)\n ) {\n skipped = entry\n return false\n }\n skipped = undefined\n const next: State<T> = {store, entry, selected, updated: true}\n stateRef.current = next\n if (asTransition) {\n startTransition(() => setState(next))\n } else {\n setState(next)\n }\n return true\n }\n\n const unsubscribe = store.subscribe({\n update(entry, sentInTransition) {\n return apply(entry, sentInTransition || store.updates === 'transition')\n },\n optimistic(action) {\n startTransition(() => addOptimistic({...action, fallback: skipped} as OptimisticAction))\n },\n })\n // The snapshot may have changed between render and subscribing.\n const seen = stateRef.current.store === store ? stateRef.current.entry : undefined\n const known = Math.max(seen?.version ?? -1, lagTargetRef.current?.version ?? -1)\n if (store.head.version > known) {\n apply(store.head, store.updates === 'transition')\n }\n return unsubscribe\n }, [store, addOptimistic])\n\n const entry = optimistic === emptyEntry ? undefined : optimistic\n const snapshot = entry?.snapshot\n if (isErrored(snapshot)) {\n throw snapshot.error\n }\n if (current && entry === current.entry) {\n const selected = selector(snapshot)\n return compare(current.selected, selected) ? current.selected : selected\n }\n return selector(snapshot)\n}\n","import {useMemo} from 'react'\nimport type {AnyActorRef} from 'xstate'\n\nimport {getStore} from './store'\nimport {useStoreSelection} from './useStoreSelection'\n\nfunction defaultCompare<T>(a: T, b: T) {\n return a === b\n}\n\n/**\n * Reads a value derived from an actor's snapshot, and re-renders only when `compare` says it\n * changed.\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 store = useMemo(() => (actor ? getStore(actor) : undefined), [actor])\n return useStoreSelection(store, selector, compare)\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`.\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","import {createContext, use, type ReactNode} from 'react'\nimport type {Actor, AnyActorLogic, SnapshotFrom} from 'xstate'\n\nimport {useActorRef, type HookOptions} from './useActorRef'\nimport {useSelector as useSelectorUnbound} from './useSelector'\nimport {useSend as useSendUnbound} from './useSend'\n\n/** @public */\nexport interface ActorContext<TLogic extends AnyActorLogic> {\n useSelector: <T>(\n selector: (snapshot: SnapshotFrom<TLogic>) => T,\n compare?: (a: T, b: T) => boolean,\n ) => T\n useActorRef: () => Actor<TLogic>\n /** The provided actor's `send`, with the same transition and optimistic behavior as `useActor`. */\n useSend: () => 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\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\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\n return <ReactContext value={actor}>{children}</ReactContext>\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 return {Provider, useActorRef: useContext, useSelector, useSend}\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 * `send` is a transition: snapshot updates it causes render together with the transition it is\n * called in, or in a transition of its own. Until that transition settles, the returned snapshot\n * already shows the event's outcome, so a controlled input can call `send` in `onChange`.\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<TM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AAhC,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(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,K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AAM,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity-labs/xstate-react",
3
- "version": "0.0.0",
3
+ "version": "0.2.0",
4
4
  "description": "React 19 bindings for XState v6, built for transitions and useOptimistic",
5
5
  "keywords": [
6
6
  "concurrent",
@@ -46,8 +46,10 @@
46
46
  "@types/react": "^19.3.3",
47
47
  "@types/react-dom": "^19.3.0",
48
48
  "@vitejs/plugin-react": "^6.3.0",
49
+ "@vitest/browser-playwright": "^5.1.2",
49
50
  "jsdom": "^31.0.1",
50
51
  "oxc-transform-react": "^0.158.0",
52
+ "playwright": "^1.65.1",
51
53
  "publint": "^0.3.25",
52
54
  "react": "^19.3.1",
53
55
  "react-dom": "^19.3.1",
@@ -69,6 +71,7 @@
69
71
  "scripts": {
70
72
  "build": "tsdown",
71
73
  "test": "vitest run --typecheck",
74
+ "test:browser": "vitest run --config vitest.browser.config.ts",
72
75
  "watch": "tsdown --watch"
73
76
  }
74
77
  }