beestate 0.1.9 → 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/@types/InternalStore.d.ts +17 -10
- package/dist/@types/StoreProvider.d.ts +3 -8
- package/dist/@types/constants.d.ts +3 -0
- package/dist/@types/createStore.d.ts +5 -2
- package/dist/@types/createStoreRegistry.d.ts +3 -2
- package/dist/@types/createUseStore.d.ts +2 -4
- package/dist/@types/ensureInternalStore.d.ts +6 -0
- package/dist/@types/index.d.ts +3 -4
- package/dist/@types/types/DeferredAction.d.ts +7 -0
- package/dist/@types/types/InitInstance.d.ts +3 -3
- package/dist/@types/types/InitializedStateLink.d.ts +11 -0
- package/dist/@types/types/InitializedStoreInstance.d.ts +5 -0
- package/dist/@types/types/InstanceKeyStateLink.d.ts +11 -0
- package/dist/@types/types/InternalStore/ApplyState.d.ts +5 -0
- package/dist/@types/types/InternalStore/Dispatch.d.ts +1 -1
- package/dist/@types/types/InternalStore/EnsureInstance.d.ts +4 -0
- package/dist/@types/types/InternalStore/GetInitializedInstance.d.ts +6 -0
- package/dist/@types/types/InternalStore/GetInstance.d.ts +6 -0
- package/dist/@types/types/InternalStore/GetUninitializedInstance.d.ts +6 -0
- package/dist/@types/types/InternalStore/InitInstance.d.ts +2 -4
- package/dist/@types/types/InternalStore/IsInitialized.d.ts +4 -0
- package/dist/@types/types/InternalStore/Listener.d.ts +1 -1
- package/dist/@types/types/InternalStore/ListenerAll.d.ts +1 -1
- package/dist/@types/types/InternalStore/PruneInstance.d.ts +4 -0
- package/dist/@types/types/InternalStore/ResetInstance.d.ts +3 -3
- package/dist/@types/types/InternalStoreProps.d.ts +2 -2
- package/dist/@types/types/ReducerMap.d.ts +2 -2
- package/dist/@types/types/RegisterDefaultInstance.d.ts +3 -3
- package/dist/@types/types/RegisterInstance.d.ts +3 -3
- package/dist/@types/types/ResetInstance.d.ts +2 -3
- package/dist/@types/types/Store.d.ts +4 -0
- package/dist/@types/types/StoreContextValue.d.ts +6 -0
- package/dist/@types/types/StoreInstance.d.ts +8 -0
- package/dist/@types/types/StoreProviderProps.d.ts +10 -0
- package/dist/@types/types/StoreRegistry.d.ts +2 -2
- package/dist/@types/types/UninitializedStoreInstance.d.ts +5 -0
- package/dist/@types/types/UseProp.d.ts +4 -0
- package/dist/cjs/index.cjs.js +286 -199
- package/dist/esm/index.esm.js +287 -200
- package/package.json +1 -1
- package/dist/@types/createStoreController.d.ts +0 -6
- package/dist/@types/types/InitPayload.d.ts +0 -3
- package/dist/@types/types/ResetPayload.d.ts +0 -3
- package/dist/@types/types/StoreController.d.ts +0 -10
- package/dist/@types/types/StoreInstanceController.d.ts +0 -7
package/dist/esm/index.esm.js
CHANGED
|
@@ -1,198 +1,301 @@
|
|
|
1
|
-
import React, { useContext, useMemo, useState, useRef, useCallback, useEffect } from 'react';
|
|
2
|
-
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';
|
|
3
1
|
import { jsx } from 'react/jsx-runtime';
|
|
2
|
+
import React, { useRef, useMemo, useContext, useCallback, useEffect } from 'react';
|
|
3
|
+
import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';
|
|
4
4
|
|
|
5
5
|
const DEFAULT_INSTANCE_KEY = Symbol(`DEFAULT_INSTANCE_KEY`);
|
|
6
6
|
const DESTROY = Symbol(`DESTROY_INSTRUCTION`);
|
|
7
|
+
const INITIALIZED_STATE_NAME = `$$initialized`;
|
|
8
|
+
const INSTANCE_KEY_STATE_NAME = `$$instanceKey`;
|
|
9
|
+
const INTERNAL_BUG_MESSAGE = `This must never happen and may mean a bug inside the library itself. Please report it to the library developers.`;
|
|
7
10
|
const INTERNAL_STORE_PROPS_ACCESSOR = Symbol(`INTERNAL_STORE_PROPS`);
|
|
8
11
|
const REDUCER_LINK = Symbol(`REDUCER_LINK`);
|
|
9
12
|
const STATE_LINK = Symbol(`STATE_LINK`);
|
|
10
13
|
const STORE_INSTANCE_UNREGISTERED = Symbol(`STORE_INSTANCE_UNREGISTERED_INSTRUCTION`);
|
|
11
14
|
|
|
12
|
-
function
|
|
13
|
-
return function
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
payload = args[0];
|
|
26
|
-
}
|
|
27
|
-
const actualInstanceKey = instanceKey ?? contextInstanceKey ?? DEFAULT_INSTANCE_KEY;
|
|
28
|
-
// TODO Вынести в отдельную функцию, т.к. уже встречается в проекте пару раз
|
|
29
|
-
if (!(internalStoreProps.uniqKey in storeRegistry)) {
|
|
30
|
-
throw new Error(`Store "${internalStoreProps.name}" is not registered.`);
|
|
31
|
-
}
|
|
32
|
-
// TODO Вынести в отдельную функцию, т.к. уже встречается в проекте пару раз
|
|
33
|
-
if (!(storeRegistry[internalStoreProps.uniqKey].instances[actualInstanceKey])) {
|
|
34
|
-
throw new Error(`Store "${internalStoreProps.name}" is not initialized for instance "${String(actualInstanceKey)}".`);
|
|
35
|
-
}
|
|
36
|
-
const internalStore = storeRegistry[internalStoreProps.uniqKey].internalStore;
|
|
37
|
-
internalStore.dispatch(actualInstanceKey, payload, reducerLink.reducer);
|
|
38
|
-
}
|
|
39
|
-
return dispatch;
|
|
40
|
-
}, [contextInstanceKey, reducerLink]);
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function createUseLatest(storeRegistry) {
|
|
45
|
-
return function useLatest(saga, reducerLinks, instanceKey) {
|
|
46
|
-
return;
|
|
15
|
+
function createStoreProvider(useStore) {
|
|
16
|
+
return function StoreProvider(props) {
|
|
17
|
+
const internalStoreProps = props.store[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
18
|
+
const Context = internalStoreProps.context;
|
|
19
|
+
const actualInstanceKey = props.instanceKey ?? DEFAULT_INSTANCE_KEY;
|
|
20
|
+
const prefillRef = useRef({ prefill: props.prefill });
|
|
21
|
+
useStore(props.store, [actualInstanceKey], (initInstance) => {
|
|
22
|
+
return initInstance(prefillRef.current.prefill);
|
|
23
|
+
});
|
|
24
|
+
const contextValue = useMemo(() => {
|
|
25
|
+
return { instanceKey: actualInstanceKey, uninitializedState: { ...internalStoreProps.initialState, ...prefillRef.current.prefill } };
|
|
26
|
+
}, [actualInstanceKey, internalStoreProps]);
|
|
27
|
+
return (jsx(Context.Provider, { value: contextValue, children: props.children }));
|
|
47
28
|
};
|
|
48
29
|
}
|
|
49
30
|
|
|
50
31
|
class InternalStore {
|
|
51
32
|
constructor(name) {
|
|
33
|
+
this.applyState = (instanceKey, state) => {
|
|
34
|
+
const instance = this.getInstance(instanceKey);
|
|
35
|
+
instance.state = state;
|
|
36
|
+
const stateAll = Object.assign(Object.create(null), this.stateAll);
|
|
37
|
+
if (state) {
|
|
38
|
+
stateAll[instanceKey] = state;
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
delete stateAll[instanceKey];
|
|
42
|
+
}
|
|
43
|
+
this.stateAll = stateAll;
|
|
44
|
+
};
|
|
45
|
+
this.dispatch = (instanceKey, reducer, payload) => {
|
|
46
|
+
this.ensureInstance(instanceKey);
|
|
47
|
+
if (this.isInitialized(instanceKey)) {
|
|
48
|
+
const instance = this.getInitializedInstance(instanceKey);
|
|
49
|
+
const prevState = instance.state;
|
|
50
|
+
const nextState = reducer(prevState, payload);
|
|
51
|
+
this.applyState(instanceKey, nextState);
|
|
52
|
+
instance.listeners.forEach((listener) => listener(instanceKey, reducer, payload));
|
|
53
|
+
this.listenersAll.forEach((listener) => listener(instanceKey, reducer, payload));
|
|
54
|
+
// TODO Убрать в логгер
|
|
55
|
+
console.log(`dispatch [store: ${this.name}, instanceKey: ${String(instanceKey)}, action: ${reducer.name}]:`);
|
|
56
|
+
// TODO Убрать в логгер
|
|
57
|
+
console.log({ payload, [`prev state`]: prevState, [`next state`]: nextState });
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
const instance = this.getUninitializedInstance(instanceKey);
|
|
61
|
+
instance.deferredActions.push({ payload, reducer });
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
this.ensureInstance = (instanceKey) => {
|
|
65
|
+
if (!this.instances[instanceKey]) {
|
|
66
|
+
this.instances[instanceKey] = { deferredActions: [], listeners: new Set(), state: undefined };
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
this.getInstance = (instanceKey) => {
|
|
70
|
+
const instance = this.instances[instanceKey];
|
|
71
|
+
if (instance) {
|
|
72
|
+
return instance;
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
throw new Error(`Store instance record is missing [store: ${this.name}, instanceKey: ${String(instanceKey)}]. ${INTERNAL_BUG_MESSAGE}`);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
this.getInitializedInstance = (instanceKey) => {
|
|
79
|
+
const instance = this.getInstance(instanceKey);
|
|
80
|
+
if (this.isInitialized(instanceKey)) {
|
|
81
|
+
return instance;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
throw new Error(`Store instance is not initialized [store: ${this.name}, instanceKey: ${String(instanceKey)}]. ${INTERNAL_BUG_MESSAGE}`);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
52
87
|
this.getState = (instanceKey) => {
|
|
53
|
-
|
|
88
|
+
const instance = this.getInitializedInstance(instanceKey);
|
|
89
|
+
return instance.state;
|
|
54
90
|
};
|
|
55
91
|
this.getStateAll = () => {
|
|
56
|
-
return this.
|
|
92
|
+
return this.stateAll;
|
|
57
93
|
};
|
|
58
|
-
this.
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
94
|
+
this.getUninitializedInstance = (instanceKey) => {
|
|
95
|
+
const instance = this.getInstance(instanceKey);
|
|
96
|
+
if (this.isInitialized(instanceKey)) {
|
|
97
|
+
throw new Error(`Store instance is already initialized [store: ${this.name}, instanceKey: ${String(instanceKey)}]. ${INTERNAL_BUG_MESSAGE}`);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
return instance;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
this.initInstance = (instanceKey, initReducer, initialState, prefill = {}) => {
|
|
104
|
+
this.ensureInstance(instanceKey);
|
|
105
|
+
const instance = this.getUninitializedInstance(instanceKey);
|
|
106
|
+
// TODO Смущает наличие `prefill` в этих двух вызовах...
|
|
107
|
+
// Такое ощущение, что он должен маячить где-то в одном из них.
|
|
108
|
+
// TODO Смущает наличие двух этих вызовов подряд...
|
|
109
|
+
// Такое ощущение, что надо бы обойтись одним.
|
|
110
|
+
this.applyState(instanceKey, { ...initialState, ...prefill });
|
|
111
|
+
this.dispatch(instanceKey, initReducer, prefill);
|
|
112
|
+
// TODO Требуется комментарий в коде...
|
|
113
|
+
// Почему мы сначала сохраняем в переменную массив, и только потом идем по нему? Почему нельзя
|
|
114
|
+
// идти сразу по нему?
|
|
115
|
+
const deferredActions = instance.deferredActions;
|
|
116
|
+
instance.deferredActions = [];
|
|
117
|
+
for (const deferredAction of deferredActions) {
|
|
118
|
+
this.dispatch(instanceKey, deferredAction.reducer, deferredAction.payload);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
this.isInitialized = (instanceKey) => {
|
|
122
|
+
return !!this.instances[instanceKey]?.state;
|
|
123
|
+
};
|
|
124
|
+
this.pruneInstance = (instanceKey) => {
|
|
125
|
+
const instance = this.getInstance(instanceKey);
|
|
126
|
+
if (!instance.state && !instance.listeners.size && !instance.deferredActions.length) {
|
|
127
|
+
delete this.instances[instanceKey];
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
this.resetInstance = (instanceKey, resetReducer) => {
|
|
131
|
+
// TODO Сомнителен порядок вызовов всех этих инструкций, которые ниже
|
|
132
|
+
const instance = this.getInitializedInstance(instanceKey);
|
|
133
|
+
// TODO Сомнение: что должно нести прощальное состояние сброса и какой быть роли $$reset.
|
|
134
|
+
// Пейлоад у сброса убран, есть идеи на этот счёт, но они ещё не оформились.
|
|
135
|
+
const prevState = instance.state;
|
|
136
|
+
const nextState = resetReducer(prevState, undefined);
|
|
137
|
+
this.applyState(instanceKey, undefined);
|
|
138
|
+
instance.listeners.forEach((listener) => listener(instanceKey, resetReducer, undefined));
|
|
139
|
+
this.listenersAll.forEach((listener) => listener(instanceKey, resetReducer, undefined));
|
|
140
|
+
// TODO Убрать в логгер
|
|
141
|
+
console.log(`reset [store: ${this.name}, instanceKey: ${String(instanceKey)}, action: ${resetReducer.name}]:`);
|
|
142
|
+
// TODO Убрать в логгер
|
|
143
|
+
console.log({ [`prev state`]: prevState, [`next state`]: nextState });
|
|
144
|
+
this.pruneInstance(instanceKey);
|
|
69
145
|
};
|
|
70
146
|
this.subscribe = (instanceKey, listener) => {
|
|
71
|
-
this.
|
|
147
|
+
this.ensureInstance(instanceKey);
|
|
148
|
+
const instance = this.getInstance(instanceKey);
|
|
149
|
+
const actualListener = (...args) => listener(...args);
|
|
150
|
+
instance.listeners.add(actualListener);
|
|
72
151
|
return () => {
|
|
73
|
-
|
|
152
|
+
const deleted = instance.listeners.delete(actualListener);
|
|
153
|
+
if (deleted) {
|
|
154
|
+
this.pruneInstance(instanceKey);
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
throw new Error(`Store instance listener is missing on unsubscribe [store: ${this.name}, instanceKey: ${String(instanceKey)}]. ${INTERNAL_BUG_MESSAGE}`);
|
|
158
|
+
}
|
|
74
159
|
};
|
|
75
160
|
};
|
|
76
161
|
this.subscribeAll = (listener) => {
|
|
77
|
-
|
|
162
|
+
const actualListener = (...args) => listener(...args);
|
|
163
|
+
this.listenersAll.add(actualListener);
|
|
78
164
|
return () => {
|
|
79
|
-
this.listenersAll.delete(
|
|
165
|
+
const deleted = this.listenersAll.delete(actualListener);
|
|
166
|
+
if (!deleted) {
|
|
167
|
+
throw new Error(`Store listener is missing on unsubscribe [store: ${this.name}]. ${INTERNAL_BUG_MESSAGE}`);
|
|
168
|
+
}
|
|
80
169
|
};
|
|
81
170
|
};
|
|
82
|
-
this.
|
|
83
|
-
const instanceState = this.state[instanceKey];
|
|
84
|
-
const instanceNextState = reducer(instanceState, payload);
|
|
85
|
-
this.state = { ...this.state, [instanceKey]: instanceNextState };
|
|
86
|
-
this.listeners[instanceKey].forEach((listener) => listener(instanceKey, payload, reducer));
|
|
87
|
-
this.listenersAll.forEach((listener) => listener(instanceKey, payload, reducer));
|
|
88
|
-
// TODO Убрать в логгер
|
|
89
|
-
console.log(`dispatch [store: ${this.name}, instanceKey: ${String(instanceKey)}, action: ${reducer.name}]:`);
|
|
90
|
-
// TODO Убрать в логгер
|
|
91
|
-
console.log({ payload, [`prev state`]: instanceState, [`next state`]: instanceNextState });
|
|
92
|
-
};
|
|
93
|
-
this.listeners = {};
|
|
171
|
+
this.instances = Object.create(null);
|
|
94
172
|
this.listenersAll = new Set();
|
|
95
173
|
this.name = name;
|
|
96
|
-
this.
|
|
174
|
+
this.stateAll = Object.create(null);
|
|
97
175
|
}
|
|
98
176
|
}
|
|
99
177
|
|
|
100
|
-
function
|
|
101
|
-
let
|
|
102
|
-
if (!
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
storeRegistry[internalStoreProps.uniqKey] = storeController;
|
|
178
|
+
function ensureInternalStore(storeRegistry, internalStoreProps) {
|
|
179
|
+
let internalStore = storeRegistry[internalStoreProps.uniqKey];
|
|
180
|
+
if (!internalStore) {
|
|
181
|
+
internalStore = new InternalStore(internalStoreProps.name);
|
|
182
|
+
storeRegistry[internalStoreProps.uniqKey] = internalStore;
|
|
106
183
|
}
|
|
107
|
-
return
|
|
184
|
+
return internalStore;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function createUseDispatcher(storeRegistry) {
|
|
188
|
+
return function useDispatcher(reducerLink) {
|
|
189
|
+
const reducerLinkRef = useRef({ reducerLink });
|
|
190
|
+
if (reducerLinkRef.current.reducerLink !== reducerLink) {
|
|
191
|
+
console.warn(`Reducer link reference mismatch. You must pass the same reducer link on every render.`);
|
|
192
|
+
}
|
|
193
|
+
const actualReducerLink = reducerLinkRef.current.reducerLink;
|
|
194
|
+
const internalStoreProps = actualReducerLink[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
195
|
+
const storeContextValue = useContext(internalStoreProps.context);
|
|
196
|
+
const contextInstanceKey = storeContextValue?.instanceKey;
|
|
197
|
+
return useMemo(() => {
|
|
198
|
+
const internalStoreProps = actualReducerLink[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
199
|
+
function dispatch(...args) {
|
|
200
|
+
let instanceKey;
|
|
201
|
+
let payload;
|
|
202
|
+
if ([`symbol`, `string`].includes(typeof args[0])) {
|
|
203
|
+
instanceKey = args[0];
|
|
204
|
+
payload = args[1];
|
|
205
|
+
}
|
|
206
|
+
else {
|
|
207
|
+
payload = args[0];
|
|
208
|
+
}
|
|
209
|
+
const actualInstanceKey = instanceKey ?? contextInstanceKey ?? DEFAULT_INSTANCE_KEY;
|
|
210
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
211
|
+
internalStore.dispatch(actualInstanceKey, actualReducerLink.reducer, payload);
|
|
212
|
+
}
|
|
213
|
+
return dispatch;
|
|
214
|
+
}, [actualReducerLink, contextInstanceKey]);
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function createUseLatest(storeRegistry) {
|
|
219
|
+
return function useLatest(saga, reducerLinks, instanceKey) {
|
|
220
|
+
return;
|
|
221
|
+
};
|
|
108
222
|
}
|
|
109
223
|
|
|
110
224
|
function createUseProp(storeRegistry) {
|
|
111
225
|
return function useProp(stateLink, instanceKey) {
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
const
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
226
|
+
const stateLinkRef = useRef({ stateLink });
|
|
227
|
+
if (stateLinkRef.current.stateLink !== stateLink) {
|
|
228
|
+
console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
|
|
229
|
+
}
|
|
230
|
+
const actualStateLink = stateLinkRef.current.stateLink;
|
|
231
|
+
const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
232
|
+
const storeContextValue = useContext(internalStoreProps.context);
|
|
233
|
+
const actualInstanceKey = instanceKey ?? storeContextValue?.instanceKey ?? DEFAULT_INSTANCE_KEY;
|
|
234
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
235
|
+
const uninitializedState = storeContextValue?.instanceKey === actualInstanceKey
|
|
236
|
+
? storeContextValue.uninitializedState
|
|
237
|
+
: internalStoreProps.initialState;
|
|
238
|
+
const subscribe = useCallback((listener) => {
|
|
239
|
+
return internalStore.subscribe(actualInstanceKey, listener);
|
|
240
|
+
}, [actualInstanceKey, internalStore]);
|
|
241
|
+
const getSnapshot = useCallback(() => {
|
|
242
|
+
if (internalStore.isInitialized(actualInstanceKey)) {
|
|
243
|
+
return internalStore.getState(actualInstanceKey);
|
|
129
244
|
}
|
|
130
245
|
else {
|
|
131
|
-
|
|
132
|
-
getSnapshot = () => internalStoreProps.initialState;
|
|
133
|
-
if (!storeController.earlySubscribers[actualInstanceKey]) {
|
|
134
|
-
storeController.earlySubscribers[actualInstanceKey] = [];
|
|
135
|
-
}
|
|
136
|
-
else if (earlySubscriberRef.current.earlySubscriber) {
|
|
137
|
-
storeController.earlySubscribers[actualInstanceKey].splice(storeController.earlySubscribers[actualInstanceKey].indexOf(earlySubscriberRef.current.earlySubscriber), 1);
|
|
138
|
-
}
|
|
139
|
-
const earlySubscriber = earlySubscriberRef.current.earlySubscriber = () => setUninitializedHack(state => state + 1);
|
|
140
|
-
storeController.earlySubscribers[actualInstanceKey].push(earlySubscriber);
|
|
246
|
+
return uninitializedState;
|
|
141
247
|
}
|
|
142
|
-
|
|
143
|
-
}, [actualInstanceKey, initialized, internalStoreProps, storeController]);
|
|
248
|
+
}, [actualInstanceKey, internalStore, uninitializedState]);
|
|
144
249
|
const selector = useCallback((state) => {
|
|
145
|
-
|
|
146
|
-
|
|
250
|
+
if (actualStateLink.stateName === INITIALIZED_STATE_NAME) {
|
|
251
|
+
return internalStore.isInitialized(actualInstanceKey);
|
|
252
|
+
}
|
|
253
|
+
else if (actualStateLink.stateName === INSTANCE_KEY_STATE_NAME) {
|
|
254
|
+
return actualInstanceKey;
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
return state[actualStateLink.stateName];
|
|
258
|
+
}
|
|
259
|
+
}, [actualInstanceKey, actualStateLink, internalStore]);
|
|
147
260
|
return useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector);
|
|
148
261
|
};
|
|
149
262
|
}
|
|
150
263
|
|
|
151
264
|
function createUsePropAll(storeRegistry) {
|
|
152
265
|
return function usePropAll(stateLink, instanceKeys) {
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
throw new Error(`Store "${internalStoreProps.name}" is not registered.`);
|
|
266
|
+
const stateLinkRef = useRef({ stateLink });
|
|
267
|
+
if (stateLinkRef.current.stateLink !== stateLink) {
|
|
268
|
+
console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
|
|
157
269
|
}
|
|
158
|
-
const
|
|
270
|
+
const actualStateLink = stateLinkRef.current.stateLink;
|
|
271
|
+
const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
272
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
159
273
|
const subscribe = useCallback((listener) => {
|
|
160
274
|
return internalStore.subscribeAll(listener);
|
|
161
275
|
}, [internalStore]);
|
|
162
276
|
const getSnapshot = useCallback(() => {
|
|
163
277
|
return internalStore.getStateAll();
|
|
164
278
|
}, [internalStore]);
|
|
165
|
-
const selector = useCallback((
|
|
166
|
-
let
|
|
279
|
+
const selector = useCallback((stateAll) => {
|
|
280
|
+
let actualInstanceKeys;
|
|
167
281
|
if (instanceKeys == null) {
|
|
168
|
-
|
|
169
|
-
.map(([instanceKey, state]) => {
|
|
170
|
-
return [instanceKey, state[stateLink.stateName]];
|
|
171
|
-
});
|
|
282
|
+
actualInstanceKeys = [...Object.keys(stateAll), ...Object.getOwnPropertySymbols(stateAll)];
|
|
172
283
|
}
|
|
173
284
|
else if (typeof instanceKeys === `function`) {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return instanceKeys(state);
|
|
177
|
-
})
|
|
178
|
-
.map(([instanceKey, state]) => {
|
|
179
|
-
return [instanceKey, state[stateLink.stateName]];
|
|
285
|
+
actualInstanceKeys = [...Object.keys(stateAll), ...Object.getOwnPropertySymbols(stateAll)].filter((instanceKey) => {
|
|
286
|
+
return instanceKeys(stateAll[instanceKey]);
|
|
180
287
|
});
|
|
181
288
|
}
|
|
182
289
|
else {
|
|
183
|
-
|
|
184
|
-
return
|
|
290
|
+
actualInstanceKeys = instanceKeys.filter((instanceKey) => {
|
|
291
|
+
return instanceKey in stateAll;
|
|
185
292
|
});
|
|
186
293
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
return prevStateAllRef.current.prevStateAll;
|
|
193
|
-
}
|
|
194
|
-
}, [instanceKeys, stateLink]);
|
|
195
|
-
return useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector);
|
|
294
|
+
return actualInstanceKeys.map((instanceKey) => {
|
|
295
|
+
return [instanceKey, stateAll[instanceKey][actualStateLink.stateName]];
|
|
296
|
+
});
|
|
297
|
+
}, [actualStateLink, instanceKeys]);
|
|
298
|
+
return useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector, isEqual);
|
|
196
299
|
};
|
|
197
300
|
}
|
|
198
301
|
function isEqual(prevStateAll, stateAll) {
|
|
@@ -200,11 +303,8 @@ function isEqual(prevStateAll, stateAll) {
|
|
|
200
303
|
return false;
|
|
201
304
|
}
|
|
202
305
|
else {
|
|
203
|
-
return prevStateAll.every(([prevInstanceKey, prevState]) => {
|
|
204
|
-
|
|
205
|
-
return prevInstanceKey === instanceKey;
|
|
206
|
-
});
|
|
207
|
-
return stateAllEntry && stateAllEntry[1] === prevState;
|
|
306
|
+
return prevStateAll.every(([prevInstanceKey, prevState], index) => {
|
|
307
|
+
return prevInstanceKey === stateAll[index][0] && prevState === stateAll[index][1];
|
|
208
308
|
});
|
|
209
309
|
}
|
|
210
310
|
}
|
|
@@ -212,15 +312,14 @@ function isEqual(prevStateAll, stateAll) {
|
|
|
212
312
|
function createUseStore(storeRegistry) {
|
|
213
313
|
function useStore(store, ...args) {
|
|
214
314
|
const storeRef = useRef({ store });
|
|
215
|
-
const storeMismatchWarnedRef = useRef({ warned: false });
|
|
216
315
|
if (storeRef.current.store !== store) {
|
|
217
316
|
console.warn(`Store reference mismatch. You must pass the same store instance on every render.`);
|
|
218
|
-
storeMismatchWarnedRef.current.warned = true;
|
|
219
317
|
}
|
|
220
318
|
let instanceKeys;
|
|
221
319
|
let registerInstance;
|
|
222
|
-
const
|
|
223
|
-
const
|
|
320
|
+
const actualStore = storeRef.current.store;
|
|
321
|
+
const internalStoreProps = actualStore[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
322
|
+
const contextInstanceKey = useContext(internalStoreProps.context)?.instanceKey;
|
|
224
323
|
if (typeof args[0] === `function`) {
|
|
225
324
|
instanceKeys = [contextInstanceKey ?? DEFAULT_INSTANCE_KEY];
|
|
226
325
|
registerInstance = args[0];
|
|
@@ -231,74 +330,57 @@ function createUseStore(storeRegistry) {
|
|
|
231
330
|
}
|
|
232
331
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
233
332
|
const actualInstanceKeys = useMemo(() => instanceKeys, instanceKeys);
|
|
234
|
-
const
|
|
235
|
-
const
|
|
333
|
+
const registeredInstancesRef = useRef({ registeredInstances: Object.create(null) });
|
|
334
|
+
const registerInstanceRef = useRef({ registerInstance });
|
|
335
|
+
registerInstanceRef.current.registerInstance = registerInstance;
|
|
236
336
|
useEffect(() => {
|
|
237
|
-
const {
|
|
238
|
-
const {
|
|
337
|
+
const { registeredInstances } = registeredInstancesRef.current;
|
|
338
|
+
const { registerInstance } = registerInstanceRef.current;
|
|
239
339
|
for (const instanceKey of actualInstanceKeys) {
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
const
|
|
244
|
-
if (
|
|
245
|
-
// TODO Множественная инициализация хранилища
|
|
246
|
-
// Архитектура позволяет несколько раз инициализировать одно и то же хранилище с
|
|
247
|
-
// одним и тем же ключом, однако возможно от этого стоит отказаться. Возможно
|
|
248
|
-
// стоит просить разработчиков проверять инициализирована ли стора и
|
|
249
|
-
// инициализировать ее при необходимости.
|
|
250
|
-
console.warn(`Duplicate store initialization [store: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
|
|
251
|
-
}
|
|
252
|
-
else {
|
|
340
|
+
if (!registeredInstances[instanceKey]) {
|
|
341
|
+
const initInstance = (prefill) => {
|
|
342
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
343
|
+
const owner = !internalStore.isInitialized(instanceKey);
|
|
344
|
+
if (owner) {
|
|
253
345
|
// TODO Убрать в логгер
|
|
254
|
-
console.log(`Store instance initialization [store: ${
|
|
346
|
+
console.log(`Store instance initialization [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
|
|
255
347
|
// TODO Убрать в логгер
|
|
256
348
|
console.log({ storeRegistry });
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
subscriber();
|
|
262
|
-
}
|
|
263
|
-
storeController.earlySubscribers[instanceKey].splice(0);
|
|
264
|
-
}
|
|
349
|
+
internalStore.initInstance(instanceKey, internalStoreProps.$$init, internalStoreProps.initialState, prefill);
|
|
350
|
+
}
|
|
351
|
+
else {
|
|
352
|
+
console.warn(`Store instance is already initialized, initialization skipped [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
|
|
265
353
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
storeController.instances[instanceKey].owners.splice(storeController.instances[instanceKey].owners.indexOf(ownerKey), 1);
|
|
269
|
-
if (storeController.instances[instanceKey].owners.length === 0) {
|
|
354
|
+
return () => {
|
|
355
|
+
if (owner) {
|
|
270
356
|
// TODO Убрать в логгер
|
|
271
|
-
console.log(`Store instance resetting [store: ${
|
|
357
|
+
console.log(`Store instance resetting [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
|
|
272
358
|
// TODO Убрать в логгер
|
|
273
359
|
console.log({ storeRegistry });
|
|
274
|
-
|
|
275
|
-
storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps.$$reset);
|
|
276
|
-
delete storeController.instances[instanceKey];
|
|
360
|
+
internalStore.resetInstance(instanceKey, internalStoreProps.$$reset);
|
|
277
361
|
}
|
|
278
|
-
delete
|
|
362
|
+
delete registeredInstances[instanceKey];
|
|
279
363
|
return STORE_INSTANCE_UNREGISTERED;
|
|
280
364
|
};
|
|
281
365
|
};
|
|
282
|
-
|
|
366
|
+
registeredInstances[instanceKey] = {
|
|
283
367
|
resetInstance: instanceKey === DEFAULT_INSTANCE_KEY
|
|
284
368
|
? registerInstance(initInstance)
|
|
285
369
|
: registerInstance(initInstance, instanceKey),
|
|
286
370
|
};
|
|
287
371
|
}
|
|
288
372
|
}
|
|
289
|
-
for (const instanceKey of [...Object.keys(
|
|
373
|
+
for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
|
|
290
374
|
if (!actualInstanceKeys.includes(instanceKey)) {
|
|
291
|
-
|
|
375
|
+
registeredInstances[instanceKey].resetInstance();
|
|
292
376
|
}
|
|
293
377
|
}
|
|
294
|
-
},
|
|
295
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
296
|
-
[actualInstanceKeys, internalStoreProps, /*registerInstance*/]);
|
|
378
|
+
}, [actualInstanceKeys, internalStoreProps]);
|
|
297
379
|
useEffect(() => {
|
|
298
|
-
const {
|
|
380
|
+
const { registeredInstances } = registeredInstancesRef.current;
|
|
299
381
|
return () => {
|
|
300
|
-
for (const instanceKey of [...Object.keys(
|
|
301
|
-
|
|
382
|
+
for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
|
|
383
|
+
registeredInstances[instanceKey].resetInstance();
|
|
302
384
|
}
|
|
303
385
|
};
|
|
304
386
|
}, []);
|
|
@@ -307,14 +389,16 @@ function createUseStore(storeRegistry) {
|
|
|
307
389
|
}
|
|
308
390
|
|
|
309
391
|
function createStoreRegistry() {
|
|
310
|
-
const storeRegistry =
|
|
392
|
+
const storeRegistry = Object.create(null);
|
|
311
393
|
const useStore = createUseStore(storeRegistry);
|
|
312
394
|
const useProp = createUseProp(storeRegistry);
|
|
313
395
|
const usePropAll = createUsePropAll(storeRegistry);
|
|
314
396
|
const useDispatcher = createUseDispatcher(storeRegistry);
|
|
315
397
|
const useLatest = createUseLatest();
|
|
398
|
+
const StoreProvider = createStoreProvider(useStore);
|
|
316
399
|
return {
|
|
317
400
|
storeRegistry,
|
|
401
|
+
StoreProvider,
|
|
318
402
|
useStore,
|
|
319
403
|
useProp,
|
|
320
404
|
usePropAll,
|
|
@@ -323,11 +407,11 @@ function createStoreRegistry() {
|
|
|
323
407
|
};
|
|
324
408
|
}
|
|
325
409
|
|
|
326
|
-
function createStore(name, initialState,
|
|
410
|
+
function createStore(name, initialState, reducerMap) {
|
|
327
411
|
const context = React.createContext(null);
|
|
328
412
|
const internalStoreProps = {
|
|
329
|
-
$$init:
|
|
330
|
-
$$reset:
|
|
413
|
+
$$init: reducerMap.$$init,
|
|
414
|
+
$$reset: reducerMap.$$reset,
|
|
331
415
|
context,
|
|
332
416
|
initialState,
|
|
333
417
|
name,
|
|
@@ -343,11 +427,21 @@ function createStore(name, initialState, reducers) {
|
|
|
343
427
|
type: STATE_LINK,
|
|
344
428
|
};
|
|
345
429
|
}
|
|
346
|
-
|
|
430
|
+
store[INITIALIZED_STATE_NAME] = {
|
|
431
|
+
[INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
|
|
432
|
+
stateName: INITIALIZED_STATE_NAME,
|
|
433
|
+
type: STATE_LINK,
|
|
434
|
+
};
|
|
435
|
+
store[INSTANCE_KEY_STATE_NAME] = {
|
|
436
|
+
[INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
|
|
437
|
+
stateName: INSTANCE_KEY_STATE_NAME,
|
|
438
|
+
type: STATE_LINK,
|
|
439
|
+
};
|
|
440
|
+
for (const key in reducerMap) {
|
|
347
441
|
if (!(key in initialState) && ![`$$init`, `$$reset`].includes(key)) {
|
|
348
442
|
store[key] = {
|
|
349
443
|
[INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
|
|
350
|
-
reducer:
|
|
444
|
+
reducer: reducerMap[key],
|
|
351
445
|
reducerName: key,
|
|
352
446
|
type: REDUCER_LINK,
|
|
353
447
|
};
|
|
@@ -440,13 +534,6 @@ const requestState = {
|
|
|
440
534
|
},
|
|
441
535
|
};
|
|
442
536
|
|
|
443
|
-
|
|
444
|
-
// initialState,
|
|
445
|
-
instanceKey, store, }) {
|
|
446
|
-
const Context = store[INTERNAL_STORE_PROPS_ACCESSOR].context;
|
|
447
|
-
return (jsx(Context.Provider, { value: instanceKey, children: children }));
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
const { useDispatcher, useProp, usePropAll, useStore, } = createStoreRegistry();
|
|
537
|
+
const { StoreProvider, useDispatcher, useProp, usePropAll, useStore, } = createStoreRegistry();
|
|
451
538
|
|
|
452
539
|
export { DESTROY, InternalStore, StoreProvider, createStore, createStoreRegistry, requestState, requestStatus, useDispatcher, useProp, usePropAll, useStore };
|
package/package.json
CHANGED