-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathfromStore.ts
57 lines (55 loc) · 1.74 KB
/
fromStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { ActorLogic } from 'xstate';
import { createStoreTransition, TransitionsFromEventPayloadMap } from './store';
import {
EventPayloadMap,
StoreContext,
Snapshot,
StoreSnapshot,
EventObject,
ExtractEventsFromPayloadMap
} from './types';
type StoreLogic<
TContext extends StoreContext,
TEvent extends EventObject,
TInput
> = ActorLogic<StoreSnapshot<TContext>, TEvent, TInput, any, any>;
/**
* An actor logic creator which creates store [actor
* logic](https://stately.ai/docs/actors#actor-logic) for use with XState.
*
* @param initialContext The initial context for the store, either a function
* that returns context based on input, or the context itself
* @param transitions The transitions object defining how the context updates
* due to events
* @returns An actor logic creator function that creates store actor logic
*/
export function fromStore<
TContext extends StoreContext,
TEventPayloadMap extends EventPayloadMap,
TInput
>(
initialContext: ((input: TInput) => TContext) | TContext,
transitions: TransitionsFromEventPayloadMap<
TEventPayloadMap,
NoInfer<TContext>,
EventObject
>
): StoreLogic<TContext, ExtractEventsFromPayloadMap<TEventPayloadMap>, TInput> {
const transition = createStoreTransition(transitions);
return {
transition,
getInitialSnapshot: (_, input: TInput) => {
return {
status: 'active',
context:
typeof initialContext === 'function'
? initialContext(input)
: initialContext,
output: undefined,
error: undefined
} satisfies StoreSnapshot<TContext>;
},
getPersistedSnapshot: (s: StoreSnapshot<TContext>) => s,
restoreSnapshot: (s: Snapshot<unknown>) => s as StoreSnapshot<TContext>
};
}