-
-
Notifications
You must be signed in to change notification settings - Fork 85
/
stateHooks.ts
91 lines (72 loc) · 2.31 KB
/
stateHooks.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
import { cache as createCache, nestedArray, asArray, assign } from 'vest-utils';
import type { ValueOf } from 'vest-utils';
import VestTest from 'VestTest';
import type { StateKey, StateRef, StateValue, VestTests } from 'createStateRef';
import ctx from 'ctx';
// STATE REF
export function useStateRef(): Exclude<StateRef, void> {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return ctx.useX().stateRef!; // I should revisit this
}
// STATE KEYS
export function useSuiteId(): StateValue<'suiteId'> {
return useStateRef().suiteId()[0];
}
export function useSuiteName(): StateValue<'suiteName'> {
return useStateRef().suiteName()[0];
}
export function useTestCallbacks(): StateKey<'testCallbacks'> {
return useStateRef().testCallbacks();
}
// OPTIONAL FIELDS
export function useOptionalFields(): StateKey<'optionalFields'> {
return useStateRef().optionalFields();
}
export function useSetOptionalField(
fieldName: string,
setter: (
current: ValueOf<StateValue<'optionalFields'>>
) => Partial<ValueOf<StateValue<'optionalFields'>>>
) {
const [, setOptionalFields] = useOptionalFields();
setOptionalFields(prev =>
assign(prev, {
[fieldName]: assign({}, prev[fieldName], setter(prev[fieldName])),
})
);
}
export function useOptionalField(
fieldName: string
): ValueOf<StateValue<'optionalFields'>> {
const [optionalFields] = useOptionalFields();
return optionalFields[fieldName] ?? {};
}
export function useTestObjects(): StateKey<'testObjects'> {
return useStateRef().testObjects();
}
// STATE ACTIONS
export function useRefreshTestObjects(): void {
useSetTests(tests => tests);
}
export function useSetTests(handler: (current: VestTests) => VestTests): void {
const [, testObjects] = useTestObjects();
testObjects(({ current, prev }) => ({
prev,
current: asArray(handler(current)),
}));
}
// Derived state
export function useAllIncomplete(): VestTest[] {
return useTestsFlat().filter(test => test.isPending());
}
const flatCache = createCache();
export function useTestsFlat(): VestTest[] {
const [{ current }] = useTestObjects();
return flatCache([current], () => nestedArray.flatten(current));
}
export function useEachTestObject(
handler: (testObject: VestTest) => void
): void {
const testObjects = useTestsFlat();
testObjects.forEach(handler);
}