forked from pmndrs/zustand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
59 lines (56 loc) · 1.53 KB
/
middleware.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
const redux = (reducer: any, initial: any) => (
set: any,
get: any,
api: any
) => {
api.dispatch = (action: any) => {
set((state: any) => reducer(state, action))
api.devtools && api.devtools.send(api.devtools.prefix + action.type, get())
return action
}
return { dispatch: api.dispatch, ...initial }
}
const devtools = (fn: any, prefix?: string) => (
set: any,
get: any,
api: any
) => {
let extension
try {
extension =
(window as any).__REDUX_DEVTOOLS_EXTENSION__ ||
(window as any).top.__REDUX_DEVTOOLS_EXTENSION__
} catch {}
if (!extension) {
if (process.env.NODE_ENV === 'development') {
console.warn('Please install/enable Redux devtools extension')
}
api.devtools = null
return fn(set, get, api)
}
const namedSet = (state: any, name?: any) => {
set(state)
if (name) {
api.devtools.send(api.devtools.prefix + name, get())
}
}
const initialState = fn(namedSet, get, api)
if (!api.devtools) {
api.devtools = extension.connect()
api.devtools.prefix = prefix ? `${prefix} > ` : ''
api.devtools.subscribe((message: any) => {
if (message.type === 'DISPATCH' && message.state) {
const ignoreState =
message.payload.type === 'JUMP_TO_ACTION' ||
message.payload.type === 'JUMP_TO_STATE'
namedSet(
JSON.parse(message.state),
!initialState.dispatch && !ignoreState && 'setState'
)
}
})
api.devtools.init(initialState)
}
return initialState
}
export { devtools, redux }