/
devtools.ts
115 lines (94 loc) 路 2.89 KB
/
devtools.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Credit - https://github.com/pmndrs/zustand/blob/6109bc3bd0f3850c2d9546956de971f27834ac7a/src/middleware/devtools.ts
/* eslint-disable @typescript-eslint/no-explicit-any */
import type {} from "@redux-devtools/extension";
const isDEV = import.meta.env.MODE !== "production";
type Message = {
type: string;
payload?: any;
state?: any;
};
type SetupDevtoolsConfig<T> = {
getState: () => T;
setState: (newState: Partial<T>) => void;
dispatch: (action: any) => void;
};
function setupDevtoolsImplementation<T>({
getState,
setState,
dispatch,
}: SetupDevtoolsConfig<T>) {
const extensionConnector = window.__REDUX_DEVTOOLS_EXTENSION__;
if (!extensionConnector) {
console.warn("Please install/enable Redux devtools extension");
return;
}
const connection = extensionConnector.connect({});
const initialState = getState();
connection.init(initialState);
(
connection as unknown as {
subscribe: (
listener: (message: Message) => void
) => (() => void) | undefined;
}
).subscribe((message) => {
switch (message.type) {
case "ACTION":
return parseJsonThen(message.payload, (action) => {
dispatch(action);
return;
});
case "DISPATCH":
switch (message.payload.type) {
case "RESET":
setState(initialState);
return connection.init(getState());
case "COMMIT":
return connection.init(getState());
case "ROLLBACK":
return parseJsonThen(message.state, (state: any) => {
setState(state);
connection.init(getState());
});
case "JUMP_TO_STATE":
case "JUMP_TO_ACTION":
return parseJsonThen(message.state, (state: any) => {
setState(state);
if (state._meta?.stackTrace) {
console.clear();
console.log(state._meta.stackTrace);
}
});
case "IMPORT_STATE": {
const { nextLiftedState } = message.payload;
const lastComputedState =
nextLiftedState.computedStates.slice(-1)[0]?.state;
if (!lastComputedState) return;
setState(lastComputedState);
connection?.send(null as any, nextLiftedState);
return;
}
}
return;
}
});
return {
dispatch: (action: any) => {
const stackTrace = new Error("stack trace").stack ?? "";
connection.send(action, { ...getState(), _meta: { stackTrace } });
},
};
}
export const setupDevtools = isDEV ? setupDevtoolsImplementation : undefined;
const parseJsonThen = <T>(
stringified: string,
callBack: (parsed: T) => void
) => {
let parsed: T | undefined;
try {
parsed = JSON.parse(stringified);
} catch (e) {
console.error("Could not parse the received json", e);
}
if (parsed) callBack(parsed as T);
};