-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
patterns.ts
81 lines (71 loc) · 2.03 KB
/
patterns.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
import {
AtomicStateNodeConfig,
StatesConfig,
Event,
EventObject,
StateSchema,
StateNodeConfig
} from './types';
import { toEventObject } from './utils';
export function toggle<TEventType extends string = string>(
onState: string,
offState: string,
eventType: TEventType
): Record<string, AtomicStateNodeConfig<any, { type: TEventType }>> {
return {
[onState]: {
on: { [eventType]: offState }
},
[offState]: {
on: { [eventType]: onState }
}
} as Record<string, AtomicStateNodeConfig<any, { type: TEventType }>>;
}
interface SequencePatternOptions<TEvent extends EventObject> {
nextEvent: Event<TEvent> | undefined;
prevEvent: Event<TEvent> | undefined;
}
const defaultSequencePatternOptions = {
nextEvent: 'NEXT',
prevEvent: 'PREV'
};
export function sequence<
TStateSchema extends StateSchema,
TEvent extends EventObject
>(
items: Array<keyof TStateSchema['states']>,
options?: Partial<SequencePatternOptions<TEvent>>
): {
initial: keyof TStateSchema['states'];
states: StatesConfig<any, TStateSchema, TEvent>;
} {
const resolvedOptions = { ...defaultSequencePatternOptions, ...options };
const states = {} as Record<keyof TStateSchema['states'], any>;
const nextEventObject =
resolvedOptions.nextEvent === undefined
? undefined
: toEventObject(resolvedOptions.nextEvent);
const prevEventObject =
resolvedOptions.prevEvent === undefined
? undefined
: toEventObject(resolvedOptions.prevEvent);
items.forEach((item, i) => {
const state: StateNodeConfig<TEvent, TStateSchema, TEvent> = {
on: {}
};
if (i + 1 === items.length) {
state.type = 'final';
}
if (nextEventObject && i + 1 < items.length) {
state.on![nextEventObject.type] = items[i + 1];
}
if (prevEventObject && i > 0) {
state.on![prevEventObject.type] = items[i - 1];
}
states[item] = state;
});
return {
initial: items[0] as keyof TStateSchema['states'],
states: states as StatesConfig<any, TStateSchema, TEvent>
};
}