-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.ts
163 lines (131 loc) · 4.06 KB
/
index.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import { useCallback, useMemo, useReducer, useRef } from 'react';
import { useSyncExternalStore } from 'use-sync-external-store/shim';
let run = (callback: () => void) => {
callback();
};
const __DEV__ = process.env.NODE_ENV !== 'production';
type Obj = Record<string, any>;
type Setter<T> = (partial: Partial<T>) => void;
type Payload<T> = Partial<T> | ((prevState: T) => Partial<T>);
type Store<T> = {
(): T;
(payload: Payload<T>): void;
};
type InitObj<T> = (store: Store<T>) => T;
const create = <T extends Obj>(initObj: InitObj<T>): (() => T) => {
if (__DEV__ && typeof initObj !== 'function') {
throw new Error('Expected a function');
}
let state = {} as T;
const setters = new Set<Setter<T>>();
function store(payload?: Payload<T>) {
// get state
if (typeof payload === 'undefined') {
return state;
}
// set state
run(() => {
const newState = typeof payload === 'function' ? payload(state) : payload;
state = { ...state, ...newState };
setters.forEach((setter) => setter(newState));
});
}
type K = keyof T;
const obj = initObj(store as Store<T>);
Object.keys(obj).forEach((key: K) => {
const value = obj[key];
if (typeof value !== 'function') {
state[key] = value;
}
});
return function useStore() {
const proxy = useRef<T>({} as T);
const [, dispatch] = useReducer((s) => ++s, 0);
// component level data
const stateDeps = useRef<Set<K>>();
stateDeps.current = new Set();
const actions = useRef<T>({} as T);
// init proxy
useMemo(() => {
proxy.current = new Proxy({} as T, {
get(_target, p) {
const key = p as K;
if (key in state) {
stateDeps.current!.add(key);
return state[key];
}
if (key in actions.current) {
return actions.current[key];
}
// action utils
const fnGetter = (fnTarget: T[K], fnKey: string) => {
if (fnKey === 'loading' && !('loading' in fnTarget)) {
fnTarget.loading = false;
}
return fnTarget[fnKey];
};
const addLoading = (fnTarget: T[K]) => {
if ('loading' in fnTarget) {
actions.current[key].loading = true;
dispatch();
setTimeout(() => {
actions.current[key].loading = false;
});
}
};
// init actions.current
if (__DEV__ && !(key in obj)) {
throw new Error(`${key as string} not exist`);
}
const rawFn = obj[key];
const fakeFn = (() => {}) as T[K];
actions.current[key] = new Proxy(fakeFn, {
get: fnGetter,
apply: (fnTarget: T[K], _this, args) => {
addLoading(fnTarget);
const res = rawFn(...args);
if (typeof res?.then !== 'function') {
actions.current[key] = rawFn;
return res;
}
actions.current[key] = new Proxy(fakeFn, {
get: fnGetter,
apply: (newFnTarget: T[K], _newThis, newArgs) => {
addLoading(newFnTarget);
return rawFn(...newArgs);
},
});
return res;
},
});
return actions.current[key];
},
});
}, []);
// set useSyncExternalStore
const subscribe = useCallback((triggerUpdate: () => void) => {
const setter = (newState: Partial<T>) => {
for (const key of stateDeps.current!) {
if (key in newState) {
triggerUpdate();
return;
}
}
};
setters.add(setter);
return () => {
setters.delete(setter);
};
}, []);
const getSnapshot = useCallback(() => {
return state;
}, []);
useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
// return proxy
return proxy.current;
};
};
create.config = ({ batch }: { batch: typeof run }) => {
run = batch;
};
export default create;