-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
52 lines (45 loc) · 1.36 KB
/
index.tsx
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
import { useMachine } from "@xstate/react"
import { useMemo } from "react"
import type { MachineConfig } from "xstate"
import { createMachine } from "xstate"
import composeActions from "./composeActions"
import composeMachineConfigs from "./composeMachineConfigs"
import composeStatuses from "./composeStatuses"
import type {
CreateMachineParamsConfig,
MachineContext,
MachineEvent,
MachineState,
MachineStatuses,
RecursiveRecord,
UseMachinesReturn,
} from "./types"
export default function useMachines(
config: CreateMachineParamsConfig,
// options: UseMachineOptions = {},
): UseMachinesReturn {
const machine = useMemo(
() => {
const [machine, options] = composeMachineConfigs(config)
return createMachine<MachineContext, MachineEvent>(
// @ts-ignore: !@#$%^ TypeScript!
machine as MachineConfig<MachineContext, MachineState, MachineEvent>,
options as Record<string, RecursiveRecord>,
)
},
[config],
)
const debug = sessionStorage && sessionStorage.getItem("DEBUG") ? { devTools: true } : undefined
const [state, send] = useMachine(machine, debug)
const actions = composeActions(config, send)
const status = composeStatuses(config).reduce((acc, name: MachineStatuses) => ({
...acc,
[name]: () => JSON.stringify(state.value).includes(`"${name}"`),
}), {})
return {
actions,
context: state.context,
state: state.value,
status,
}
}