forked from cerebral/overmind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
563 lines (476 loc) · 15.4 KB
/
index.ts
File metadata and controls
563 lines (476 loc) · 15.4 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import {
ContextFunction,
ENVIRONMENT,
IConfiguration,
derived,
filter,
pipe,
} from 'overmind'
const ACTIONS = 'ACTIONS'
const CHART = 'CHART'
export interface Statechart<
C extends IConfiguration,
S extends {
[state: string]: Statecharts | Statechart<any, any> | void
}
> {
initial: keyof S
states: {
[N in keyof S]: {
entry?: keyof C['actions']
exit?: keyof C['actions']
chart?: S[N]
on?: {
[N in keyof C['actions']]?:
| keyof S
| {
target: keyof S
condition: (state: C['state']) => boolean
}
| null
}
}
}
}
interface Statecharts {
[id: string]: Statechart<any, any>
}
function isRootChart(chart) {
return 'initial' in chart && 'states' in chart
}
function forceNestedCharts(charts: Statecharts | Statechart<any, any>) {
if (isRootChart(charts)) {
charts = { [CHART]: charts } as Statecharts
}
return Object.keys(charts).reduce((aggr, chartKey) => {
aggr[chartKey] = {
...charts[chartKey],
states: Object.keys(charts[chartKey].states).reduce(
(statesAggr, stateKey) => {
if (charts[chartKey].states[stateKey].chart) {
statesAggr[stateKey] = {
...charts[chartKey].states[stateKey],
chart: forceNestedCharts(charts[chartKey].states[stateKey].chart),
}
} else {
statesAggr[stateKey] = charts[chartKey].states[stateKey]
}
return statesAggr
},
{}
),
}
return aggr
}, {})
}
function getActionTransitions(
actionName: string,
charts: Statecharts,
state: { states: Array<(string | number)[]> }
) {
const transitions: Array<{ index: number; target?: string }> = []
state.states.forEach((statePath, index) => {
const path = statePath.slice()
while (path.length) {
const target = getStateTarget(charts, path)
if (target.on && target.on[actionName] === null) {
transitions.push({ index })
return
}
if (
target.on &&
typeof target.on[actionName] === 'string' &&
!transitions.find(
(transition) => transition.target === target.on[actionName]
)
) {
transitions.push({ index, target: target.on[actionName] })
return
}
if (
target.on &&
target.on[actionName] &&
target.on[actionName].target &&
!transitions.find(
(transition) => transition.target === target.on[actionName].target
) &&
target.on[actionName].condition(state)
) {
transitions.push({
index,
target: target.on[actionName].target,
})
return
}
path.pop()
}
})
return transitions
}
function getCanTransitionActions(actions, charts, state) {
return Object.keys(actions || {}).reduce((aggr, key) => {
aggr[key] = Boolean(getActionTransitions(key, charts, state).length)
return aggr
}, {})
}
function getMatchPaths(matches, paths: Array<string[]> = [[]]) {
const initialPath = paths[paths.length - 1].slice()
Object.keys(matches).forEach((matchKey, index) => {
const match = matches[matchKey]
if (index > 0) {
paths.push(initialPath.slice())
}
paths[paths.length - 1].push(matchKey)
if (typeof match !== 'boolean') {
getMatchPaths(match, paths)
}
})
return paths
}
function getInitialStates(charts: Statecharts, paths: Array<string[]> = [[]]) {
const initialPath = paths[paths.length - 1].slice()
Object.keys(charts).forEach((chartKey, index) => {
const chart = charts[chartKey]
if (index > 0) {
paths.push(initialPath.slice())
}
paths[paths.length - 1].push(chartKey)
paths[paths.length - 1].push(chart.initial as string)
const nestedChart = chart.states[chart.initial as string].chart
if (nestedChart && isRootChart(nestedChart)) {
getInitialStates(
{
[CHART]: nestedChart,
} as Statecharts,
paths
)
} else if (nestedChart) {
getInitialStates(nestedChart as Statecharts, paths)
}
})
return paths
}
function createNewStatePath(
currentStates: Array<string[]>,
transitionStates: string[],
charts: Statecharts,
index: number
) {
const newStatePath: string[] = []
let x = 0
let transitionState = transitionStates.shift()
// Keep existing state before transition
while (!transitionState && transitionStates.length) {
newStatePath.push(currentStates[index][x])
transitionState = transitionStates.shift()
x++
}
if (!transitionState) {
return currentStates[index]
}
// Add the new transition
newStatePath.push(transitionState)
const stateTarget = getStateTarget(charts, newStatePath)
// If we have more nested state, go grab the initial states
if (stateTarget.chart) {
return newStatePath.concat(getInitialStates(stateTarget.chart)[index])
}
return newStatePath
}
function getTarget(source, path) {
return path.reduce((aggr, key) => aggr[key], source)
}
function getStateTarget(charts, path) {
return path.reduce((aggr, key, index) => {
const isChart = index % 2
if (!isChart) {
return aggr[key]
}
if (index === path.length - 1) {
return aggr.states[key]
}
return aggr.states[key].chart
}, charts)
}
type Match<T extends Statecharts | Statechart<any, any>> = T extends Statecharts
? {
[I in keyof T]?: {
[S in keyof T[I]['states']]?: T[I]['states'][S]['chart'] extends void
? boolean
: boolean | Match<T[I]['states'][S]['chart']>
}
}
: T extends Statechart<any, any>
? {
[S in keyof T['states']]?: T['states'][S]['chart'] extends void
? boolean
: boolean | Match<T['states'][S]['chart']>
}
: never
export function statechart<
C extends IConfiguration,
Charts extends Statecharts | Statechart<any, any>
>(
config: C,
chartDefinition: Charts
): {
state: C['state'] & {
states: Array<(string | number)[]>
actions: { [N in keyof C['actions']]: boolean }
matches: (match: Match<Charts>) => boolean
}
actions: C['actions']
effects: C['effects']
} {
let currentInstance
const charts = forceNestedCharts(chartDefinition)
const actions = config.actions || {}
const state = config.state || {}
if (currentInstance !== undefined && config.state && (config.state as any).states) {
throw new Error(
`Overmind statecharts: You have already defined the state "states" in your configuration. Statecharts needs this, please rename it`
)
}
if (currentInstance !== undefined && config.state && (config.state as any).matches) {
throw new Error(
`Overmind statecharts: You have already defined the state "matches" in your configuration. Statecharts needs this, please rename it`
)
}
let currentTransitionAction: string | null = null
// @ts-ignore
const onInitializeOvermindAction = actions.onInitializeOvermind
const copiedActions = {... actions}
// @ts-ignore
delete(copiedActions.onInitializeOvermind)
const initialActions = {
[ACTIONS]: copiedActions,
onInitializeOvermind: ( async (context, instance) => {
if (onInitializeOvermindAction) {
await onInitializeOvermindAction(context, instance)
}
currentInstance = instance
const stateTarget = getTarget(
context.state,
context.execution.namespacePath
)
const actionsTarget = getTarget(
context.actions,
context.execution.namespacePath
)
const statePaths = stateTarget.states.slice()
// Run entry actions of initial state
statePaths.forEach((statePath) => {
const state = statePath.slice()
while (state.length) {
const target = getStateTarget(charts, state)
if (config.actions && config.actions[target.entry]) {
actionsTarget[ACTIONS][target.entry](context)
}
state.pop()
}
})
if (ENVIRONMENT === 'development' && instance.devtools) {
instance.devtools.send({
type: 'chart',
data: {
path: context.execution.namespacePath,
states: getInitialStates(charts),
charts: charts,
actions: getCanTransitionActions(copiedActions, charts, stateTarget),
},
})
}
}) as any,
};
return {
state: Object.assign(state, {
states: getInitialStates(charts),
actions: derived((state) =>
getCanTransitionActions(copiedActions, charts, state)
) as any,
matches: derived((state: any) => (match) => {
const matchPaths = getMatchPaths(match)
const statesWithoutRootChartIndicator = state.states.map((statePath) =>
statePath.filter((path) => path !== CHART)
)
for (let x = 0; x < matchPaths.length; x++) {
const matchPath = matchPaths[x]
const shouldMatch = matchPath.reduce((aggr, key) => aggr[key], match)
const hasMatch = statesWithoutRootChartIndicator.reduce(
(aggr, statePath) => {
if (aggr) {
return aggr
}
return matchPath.reduce((aggr, path, index) => {
if (!aggr) {
return aggr
}
return path === statePath[index]
}, true)
},
false
)
if (shouldMatch !== hasMatch) {
return false
}
}
return true
}),
}),
actions: Object.keys(copiedActions).reduce(
(aggr, key) => {
aggr[key] = pipe(
function getTransition({ state, execution }: any, payload) {
const stateTarget = getTarget(state, execution.namespacePath)
const canTransition = stateTarget.actions[key]
if (currentTransitionAction && !canTransition) {
console.warn(
`Overmind Statecharts: Transition action "${currentTransitionAction}" is calling transition action "${key}" synchronously. The previous transition is not done yet and "${key}" will be ignored. Consider calling it asynchronously `
)
} else if (!canTransition && ENVIRONMENT === 'development') {
console.warn(
`You tried to call action "${key}", but it was blocked by the statechart. You are not supposed to call this action in the current state of the chart. This warning only appear during development`
)
}
return {
canTransition,
payload,
}
},
filter(function canTransition(_, payload) {
return payload.canTransition
}),
function runAction(context: any, { payload }) {
const stateTarget = getTarget(
context.state,
context.execution.namespacePath
)
const actionsTarget = getTarget(
context.actions,
context.execution.namespacePath
)
const transitionActions = getActionTransitions(
key,
charts,
stateTarget
)
// If there are no new transition target, just drop moving on, just run the action
if (
!transitionActions.some(
(transitionAction) => transitionAction.target
)
) {
if (config.actions) {
return actionsTarget[ACTIONS][key](payload)
}
return
}
const exitActions: string[] = []
const entryActions: string[] = []
const newStates: Array<string[]> = []
transitionActions.forEach((transitionAction) => {
// It is an action that does not cause a transition
if (!transitionAction.target) {
return
}
const currentStatePath = stateTarget.states[
transitionAction.index
].slice()
const stateTransitions = currentStatePath.map(() => null)
// Build new transition path
while (currentStatePath.length) {
const target = getStateTarget(charts, currentStatePath)
// Collect the new transition state
if (target.on && target.on[key]) {
stateTransitions[currentStatePath.length - 1] =
target.on[key].target || target.on[key]
}
currentStatePath.pop()
}
const newStatePath = createNewStatePath(
stateTarget.states,
stateTransitions,
charts,
transitionAction.index
)
// Go down old path and trigger exits where the state has changed
const traverseOldPath = stateTarget.states[
transitionAction.index
].slice()
while (traverseOldPath.length) {
const target = getStateTarget(charts, traverseOldPath)
if (
target.exit &&
newStatePath[traverseOldPath.length - 1] !==
traverseOldPath[traverseOldPath.length - 1]
) {
exitActions.push(target.exit)
}
traverseOldPath.pop()
}
newStates.push(newStatePath.slice())
// Go down new path and trigger any entry on new states
const traverseNewPath = newStatePath.slice()
while (traverseNewPath.length) {
const target = getStateTarget(charts, traverseNewPath)
if (
target.entry &&
newStatePath[traverseNewPath.length - 1] !==
stateTarget.states[transitionAction.index][
traverseNewPath.length - 1
]
) {
entryActions.push(target.entry)
}
traverseNewPath.pop()
}
})
// Run exits
exitActions.forEach((exitAction) => {
if (config.actions) {
actionsTarget[ACTIONS][exitAction](payload)
}
})
currentTransitionAction = key
let actionResult
if (config.actions) {
actionResult = actionsTarget[ACTIONS][key](payload)
}
currentTransitionAction = null
// Transition to new state
stateTarget.states = newStates
// Run entry actions
entryActions.forEach((entryAction) => {
if (config.actions) {
actionsTarget[ACTIONS][entryAction](payload)
}
})
if (
ENVIRONMENT === 'development' &&
currentInstance &&
currentInstance.devtools
) {
currentInstance.devtools.send({
type: 'chart',
data: {
path: context.execution.namespacePath,
states: stateTarget.states,
charts: charts,
actions: getCanTransitionActions(
config.actions,
charts,
stateTarget
),
},
})
}
return actionResult
}
)
return aggr
},
initialActions
),
effects: config.effects || {},
}
}