-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
180 lines (173 loc) · 4.78 KB
/
index.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import {
ActorLogic,
ActorRefFrom,
AnyActorLogic,
AnyActorRef,
SnapshotFrom,
assign,
fromTransition,
setup,
} from "xstate";
// types defs
type SpawnEventType = ReturnType<typeof spawnActorTypes.spawn>;
type Slices<TLogic extends AnyActorLogic = AnyActorLogic> = Record<
string,
TLogic
>;
export interface StoreContext<
TSlices extends Record<string, AnyActorLogic> = Record<string, AnyActorLogic>
> {
slices: { [TKey in keyof TSlices]: ActorRefFrom<TSlices[TKey]> };
spawned: Record<string, AnyActorRef>;
}
interface SpawnActorEvent<TInput = any> {
type: SpawnEventType;
actorId: string;
logic: ActorLogic<any, any, TInput>;
input: TInput;
}
export type Store<TSlices extends Slices = any> = ReturnType<
typeof createStore<TSlices>
>;
type SimpleTransitionCase<TState> = (state: TState, action?: any) => void;
type TransitionCase<TState, TPayload> = (
state: TState,
action: { payload: TPayload }
) => void;
interface CreateSliceConfig<
TState,
TTransitionMap extends Record<string, SimpleTransitionCase<TState>>
> {
name: string;
transitions: TTransitionMap;
initialState: TState;
}
type GetActionCreators<
TState,
TTransitionMap extends Record<string, SimpleTransitionCase<TState>>
> = {
[TKey in keyof TTransitionMap]: TTransitionMap[TKey] extends TransitionCase<
TState,
infer TPayload
>
? TPayload extends {}
? (payload: TPayload) => { type: string; payload: TPayload }
: () => { type: string }
: never;
};
// implementation
const spawnActorTypes = {
spawn: () => "xstate.store.spawn" as const,
init: (actorId: string) => `xstate.init.actor.${actorId}`,
done: (actorId: string) => `xstate.done.actor.${actorId}`,
error: (actorId: string) => `xstate.error.actor.${actorId}`,
};
export function createStore<TSlices extends Record<string, AnyActorLogic>>(
slices: TSlices
) {
const store = setup({
types: {} as {
context: StoreContext<TSlices>;
},
actions: {
spawnActor: assign({
spawned: ({ context, event, spawn }) => {
const spawned = { ...context.spawned };
const spawnEvent = event as SpawnActorEvent;
spawned[spawnEvent.actorId] = spawn(spawnEvent.logic, {
id: spawnEvent.actorId,
input: spawnEvent.input,
});
Object.values(context.slices).forEach((sliceRef) => {
(sliceRef as AnyActorRef).send({
type: spawnActorTypes.init(spawnEvent.actorId),
input: spawnEvent.input,
});
});
return spawned;
},
}),
forwardToSlices: ({ context, event }) => {
Object.values(context.slices).forEach((sliceRef) => {
(sliceRef as AnyActorRef).send(event);
});
},
},
}).createMachine({
context: ({ spawn }) => {
return {
slices: Object.fromEntries(
Object.entries(slices).map(([key, value]) => {
return [key, spawn(value)];
})
) as StoreContext<TSlices>["slices"],
spawned: {},
};
},
on: {
[spawnActorTypes.spawn()]: {
actions: "spawnActor",
},
"*": {
actions: "forwardToSlices",
},
},
});
return store;
}
export function createSpawnEvent<TInput>(
actorId: string,
logic: ActorLogic<any, any, TInput>
) {
const spawnEvent = (input: TInput): SpawnActorEvent<TInput> => ({
type: spawnActorTypes.spawn(),
actorId,
logic,
input,
});
spawnEvent["init"] = spawnActorTypes.init(actorId);
spawnEvent["done"] = spawnActorTypes.done(actorId);
spawnEvent["error"] = spawnActorTypes.error(actorId);
return spawnEvent;
}
export function createSelector<TSnapshot, TSlice extends AnyActorRef, TSelect>(
sliceSelect: (root: TSnapshot) => TSlice,
reselect: (slice: SnapshotFrom<TSlice>) => TSelect
) {
const selector = (root: TSnapshot) => {
const sliceRef = sliceSelect(root);
return reselect(sliceRef.getSnapshot());
};
selector[0] = sliceSelect;
selector[1] = reselect;
return selector;
}
function getTransitionKey(sliceName: string, actionType: string) {
const typeSplits = actionType.split(".");
if (typeSplits[0] === sliceName) return typeSplits[1]; // action creator
if (typeSplits[0] === "xstate") return actionType; // spawn actor
}
export function createSlice<
TState,
TTransitionMap extends Record<string, SimpleTransitionCase<TState>>
>(config: CreateSliceConfig<TState, TTransitionMap>) {
const transition = fromTransition((state, action) => {
const transitionKey = getTransitionKey(config.name, action.type);
if (!transitionKey) return state;
const transitionCase = config.transitions[transitionKey];
if (!transitionCase) return state;
const stateCopy = { ...state };
transitionCase(stateCopy, action);
return stateCopy;
}, config.initialState);
const actions = Object.fromEntries(
Object.keys(config.transitions).map((type) => [
type,
(payload: any) => ({ type: `${config.name}.${type}`, payload }),
])
) as unknown as GetActionCreators<TState, typeof config.transitions>;
return {
transition,
actions,
};
}