beestate 0.1.10 → 0.1.12
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 +9 -6
- package/dist/@types/createUsePropSelector.d.ts +3 -0
- package/dist/@types/createUsePropSelectorAll.d.ts +3 -0
- 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/pickPropAll.d.ts +3 -0
- 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/@types/types/UsePropSelector.d.ts +11 -0
- package/dist/@types/types/UsePropSelectorAll.d.ts +7 -0
- package/dist/cjs/index.cjs.js +353 -210
- package/dist/esm/index.esm.js +353 -212
- package/package.json +1 -1
- package/dist/@types/createStoreController.d.ts +0 -6
- package/dist/@types/createUseSelector.d.ts +0 -1
- 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,305 @@
|
|
|
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
|
-
|
|
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
|
-
listeners.delete(
|
|
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
|
-
const
|
|
162
|
+
const actualListener = (...args) => listener(...args);
|
|
163
|
+
this.listenersAll.add(actualListener);
|
|
78
164
|
return () => {
|
|
79
|
-
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
|
|
|
264
|
+
function pickPropAll(stateAll, stateName, instanceKeys) {
|
|
265
|
+
let actualInstanceKeys;
|
|
266
|
+
if (instanceKeys == null) {
|
|
267
|
+
actualInstanceKeys = [...Object.keys(stateAll), ...Object.getOwnPropertySymbols(stateAll)];
|
|
268
|
+
}
|
|
269
|
+
else if (typeof instanceKeys === `function`) {
|
|
270
|
+
actualInstanceKeys = [...Object.keys(stateAll), ...Object.getOwnPropertySymbols(stateAll)].filter((instanceKey) => {
|
|
271
|
+
return instanceKeys(stateAll[instanceKey]);
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
else {
|
|
275
|
+
actualInstanceKeys = instanceKeys.filter((instanceKey) => {
|
|
276
|
+
return instanceKey in stateAll;
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return actualInstanceKeys.map((instanceKey) => {
|
|
280
|
+
return [instanceKey, stateAll[instanceKey][stateName]];
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
|
|
151
284
|
function createUsePropAll(storeRegistry) {
|
|
152
285
|
return function usePropAll(stateLink, instanceKeys) {
|
|
153
|
-
const
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
throw new Error(`Store "${internalStoreProps.name}" is not registered.`);
|
|
286
|
+
const stateLinkRef = useRef({ stateLink });
|
|
287
|
+
if (stateLinkRef.current.stateLink !== stateLink) {
|
|
288
|
+
console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
|
|
157
289
|
}
|
|
158
|
-
const
|
|
290
|
+
const actualStateLink = stateLinkRef.current.stateLink;
|
|
291
|
+
const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
292
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
159
293
|
const subscribe = useCallback((listener) => {
|
|
160
294
|
return internalStore.subscribeAll(listener);
|
|
161
295
|
}, [internalStore]);
|
|
162
296
|
const getSnapshot = useCallback(() => {
|
|
163
297
|
return internalStore.getStateAll();
|
|
164
298
|
}, [internalStore]);
|
|
165
|
-
const selector = useCallback((
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
.map(([instanceKey, state]) => {
|
|
170
|
-
return [instanceKey, state[stateLink.stateName]];
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
else if (typeof instanceKeys === `function`) {
|
|
174
|
-
stateAll = Object.entries(state)
|
|
175
|
-
.filter(([_instanceKey, state]) => {
|
|
176
|
-
return instanceKeys(state);
|
|
177
|
-
})
|
|
178
|
-
.map(([instanceKey, state]) => {
|
|
179
|
-
return [instanceKey, state[stateLink.stateName]];
|
|
180
|
-
});
|
|
181
|
-
}
|
|
182
|
-
else {
|
|
183
|
-
stateAll = instanceKeys.map((instanceKey) => {
|
|
184
|
-
return [instanceKey, state[instanceKey][stateLink.stateName]];
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
if (isEqual(prevStateAllRef.current.prevStateAll, stateAll)) {
|
|
188
|
-
prevStateAllRef.current.prevStateAll = stateAll;
|
|
189
|
-
return stateAll;
|
|
190
|
-
}
|
|
191
|
-
else {
|
|
192
|
-
return prevStateAllRef.current.prevStateAll;
|
|
193
|
-
}
|
|
194
|
-
}, [instanceKeys, stateLink]);
|
|
195
|
-
return useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector);
|
|
299
|
+
const selector = useCallback((stateAll) => {
|
|
300
|
+
return pickPropAll(stateAll, actualStateLink.stateName, instanceKeys);
|
|
301
|
+
}, [actualStateLink, instanceKeys]);
|
|
302
|
+
return useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector, isEqual);
|
|
196
303
|
};
|
|
197
304
|
}
|
|
198
305
|
function isEqual(prevStateAll, stateAll) {
|
|
@@ -200,27 +307,69 @@ function isEqual(prevStateAll, stateAll) {
|
|
|
200
307
|
return false;
|
|
201
308
|
}
|
|
202
309
|
else {
|
|
203
|
-
return prevStateAll.every(([prevInstanceKey, prevState]) => {
|
|
204
|
-
|
|
205
|
-
return prevInstanceKey === instanceKey;
|
|
206
|
-
});
|
|
207
|
-
return stateAllEntry && stateAllEntry[1] === prevState;
|
|
310
|
+
return prevStateAll.every(([prevInstanceKey, prevState], index) => {
|
|
311
|
+
return prevInstanceKey === stateAll[index][0] && prevState === stateAll[index][1];
|
|
208
312
|
});
|
|
209
313
|
}
|
|
210
314
|
}
|
|
211
315
|
|
|
316
|
+
function createUsePropSelector(storeRegistry) {
|
|
317
|
+
return function usePropSelector(stateLink, instanceKey) {
|
|
318
|
+
const stateLinkRef = useRef({ stateLink });
|
|
319
|
+
if (stateLinkRef.current.stateLink !== stateLink) {
|
|
320
|
+
console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
|
|
321
|
+
}
|
|
322
|
+
const actualStateLink = stateLinkRef.current.stateLink;
|
|
323
|
+
const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
324
|
+
const storeContextValue = useContext(internalStoreProps.context);
|
|
325
|
+
const actualInstanceKey = instanceKey ?? storeContextValue?.instanceKey ?? DEFAULT_INSTANCE_KEY;
|
|
326
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
327
|
+
const uninitializedState = storeContextValue?.instanceKey === actualInstanceKey
|
|
328
|
+
? storeContextValue.uninitializedState
|
|
329
|
+
: internalStoreProps.initialState;
|
|
330
|
+
return useCallback(() => {
|
|
331
|
+
if (actualStateLink.stateName === INITIALIZED_STATE_NAME) {
|
|
332
|
+
return internalStore.isInitialized(actualInstanceKey);
|
|
333
|
+
}
|
|
334
|
+
else if (actualStateLink.stateName === INSTANCE_KEY_STATE_NAME) {
|
|
335
|
+
return actualInstanceKey;
|
|
336
|
+
}
|
|
337
|
+
else if (internalStore.isInitialized(actualInstanceKey)) {
|
|
338
|
+
return internalStore.getState(actualInstanceKey)[actualStateLink.stateName];
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
return uninitializedState[actualStateLink.stateName];
|
|
342
|
+
}
|
|
343
|
+
}, [actualInstanceKey, actualStateLink, internalStore, uninitializedState]);
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function createUsePropSelectorAll(storeRegistry) {
|
|
348
|
+
return function usePropSelectorAll(stateLink, instanceKeys) {
|
|
349
|
+
const stateLinkRef = useRef({ stateLink });
|
|
350
|
+
if (stateLinkRef.current.stateLink !== stateLink) {
|
|
351
|
+
console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
|
|
352
|
+
}
|
|
353
|
+
const actualStateLink = stateLinkRef.current.stateLink;
|
|
354
|
+
const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
355
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
356
|
+
return useCallback(() => {
|
|
357
|
+
return pickPropAll(internalStore.getStateAll(), actualStateLink.stateName, instanceKeys);
|
|
358
|
+
}, [actualStateLink, instanceKeys, internalStore]);
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
212
362
|
function createUseStore(storeRegistry) {
|
|
213
363
|
function useStore(store, ...args) {
|
|
214
364
|
const storeRef = useRef({ store });
|
|
215
|
-
const storeMismatchWarnedRef = useRef({ warned: false });
|
|
216
365
|
if (storeRef.current.store !== store) {
|
|
217
366
|
console.warn(`Store reference mismatch. You must pass the same store instance on every render.`);
|
|
218
|
-
storeMismatchWarnedRef.current.warned = true;
|
|
219
367
|
}
|
|
220
368
|
let instanceKeys;
|
|
221
369
|
let registerInstance;
|
|
222
|
-
const
|
|
223
|
-
const
|
|
370
|
+
const actualStore = storeRef.current.store;
|
|
371
|
+
const internalStoreProps = actualStore[INTERNAL_STORE_PROPS_ACCESSOR];
|
|
372
|
+
const contextInstanceKey = useContext(internalStoreProps.context)?.instanceKey;
|
|
224
373
|
if (typeof args[0] === `function`) {
|
|
225
374
|
instanceKeys = [contextInstanceKey ?? DEFAULT_INSTANCE_KEY];
|
|
226
375
|
registerInstance = args[0];
|
|
@@ -231,74 +380,57 @@ function createUseStore(storeRegistry) {
|
|
|
231
380
|
}
|
|
232
381
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
233
382
|
const actualInstanceKeys = useMemo(() => instanceKeys, instanceKeys);
|
|
234
|
-
const
|
|
235
|
-
const
|
|
383
|
+
const registeredInstancesRef = useRef({ registeredInstances: Object.create(null) });
|
|
384
|
+
const registerInstanceRef = useRef({ registerInstance });
|
|
385
|
+
registerInstanceRef.current.registerInstance = registerInstance;
|
|
236
386
|
useEffect(() => {
|
|
237
|
-
const {
|
|
238
|
-
const {
|
|
387
|
+
const { registeredInstances } = registeredInstancesRef.current;
|
|
388
|
+
const { registerInstance } = registerInstanceRef.current;
|
|
239
389
|
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 {
|
|
390
|
+
if (!registeredInstances[instanceKey]) {
|
|
391
|
+
const initInstance = (prefill) => {
|
|
392
|
+
const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
|
|
393
|
+
const owner = !internalStore.isInitialized(instanceKey);
|
|
394
|
+
if (owner) {
|
|
253
395
|
// TODO Убрать в логгер
|
|
254
|
-
console.log(`Store instance initialization [store: ${
|
|
396
|
+
console.log(`Store instance initialization [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
|
|
255
397
|
// TODO Убрать в логгер
|
|
256
398
|
console.log({ storeRegistry });
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
subscriber();
|
|
262
|
-
}
|
|
263
|
-
storeController.earlySubscribers[instanceKey].splice(0);
|
|
264
|
-
}
|
|
399
|
+
internalStore.initInstance(instanceKey, internalStoreProps.$$init, internalStoreProps.initialState, prefill);
|
|
400
|
+
}
|
|
401
|
+
else {
|
|
402
|
+
console.warn(`Store instance is already initialized, initialization skipped [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
|
|
265
403
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
storeController.instances[instanceKey].owners.splice(storeController.instances[instanceKey].owners.indexOf(ownerKey), 1);
|
|
269
|
-
if (storeController.instances[instanceKey].owners.length === 0) {
|
|
404
|
+
return () => {
|
|
405
|
+
if (owner) {
|
|
270
406
|
// TODO Убрать в логгер
|
|
271
|
-
console.log(`Store instance resetting [store: ${
|
|
407
|
+
console.log(`Store instance resetting [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
|
|
272
408
|
// TODO Убрать в логгер
|
|
273
409
|
console.log({ storeRegistry });
|
|
274
|
-
|
|
275
|
-
storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps.$$reset);
|
|
276
|
-
delete storeController.instances[instanceKey];
|
|
410
|
+
internalStore.resetInstance(instanceKey, internalStoreProps.$$reset);
|
|
277
411
|
}
|
|
278
|
-
delete
|
|
412
|
+
delete registeredInstances[instanceKey];
|
|
279
413
|
return STORE_INSTANCE_UNREGISTERED;
|
|
280
414
|
};
|
|
281
415
|
};
|
|
282
|
-
|
|
416
|
+
registeredInstances[instanceKey] = {
|
|
283
417
|
resetInstance: instanceKey === DEFAULT_INSTANCE_KEY
|
|
284
418
|
? registerInstance(initInstance)
|
|
285
419
|
: registerInstance(initInstance, instanceKey),
|
|
286
420
|
};
|
|
287
421
|
}
|
|
288
422
|
}
|
|
289
|
-
for (const instanceKey of [...Object.keys(
|
|
423
|
+
for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
|
|
290
424
|
if (!actualInstanceKeys.includes(instanceKey)) {
|
|
291
|
-
|
|
425
|
+
registeredInstances[instanceKey].resetInstance();
|
|
292
426
|
}
|
|
293
427
|
}
|
|
294
|
-
},
|
|
295
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
296
|
-
[actualInstanceKeys, internalStoreProps, /*registerInstance*/]);
|
|
428
|
+
}, [actualInstanceKeys, internalStoreProps]);
|
|
297
429
|
useEffect(() => {
|
|
298
|
-
const {
|
|
430
|
+
const { registeredInstances } = registeredInstancesRef.current;
|
|
299
431
|
return () => {
|
|
300
|
-
for (const instanceKey of [...Object.keys(
|
|
301
|
-
|
|
432
|
+
for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
|
|
433
|
+
registeredInstances[instanceKey].resetInstance();
|
|
302
434
|
}
|
|
303
435
|
};
|
|
304
436
|
}, []);
|
|
@@ -307,27 +439,33 @@ function createUseStore(storeRegistry) {
|
|
|
307
439
|
}
|
|
308
440
|
|
|
309
441
|
function createStoreRegistry() {
|
|
310
|
-
const storeRegistry =
|
|
442
|
+
const storeRegistry = Object.create(null);
|
|
311
443
|
const useStore = createUseStore(storeRegistry);
|
|
312
444
|
const useProp = createUseProp(storeRegistry);
|
|
313
445
|
const usePropAll = createUsePropAll(storeRegistry);
|
|
446
|
+
const usePropSelector = createUsePropSelector(storeRegistry);
|
|
447
|
+
const usePropSelectorAll = createUsePropSelectorAll(storeRegistry);
|
|
314
448
|
const useDispatcher = createUseDispatcher(storeRegistry);
|
|
315
449
|
const useLatest = createUseLatest();
|
|
450
|
+
const StoreProvider = createStoreProvider(useStore);
|
|
316
451
|
return {
|
|
452
|
+
StoreProvider,
|
|
317
453
|
storeRegistry,
|
|
318
|
-
useStore,
|
|
319
|
-
useProp,
|
|
320
|
-
usePropAll,
|
|
321
454
|
useDispatcher,
|
|
322
455
|
useLatest,
|
|
456
|
+
useProp,
|
|
457
|
+
usePropAll,
|
|
458
|
+
usePropSelector,
|
|
459
|
+
usePropSelectorAll,
|
|
460
|
+
useStore,
|
|
323
461
|
};
|
|
324
462
|
}
|
|
325
463
|
|
|
326
|
-
function createStore(name, initialState,
|
|
464
|
+
function createStore(name, initialState, reducerMap) {
|
|
327
465
|
const context = React.createContext(null);
|
|
328
466
|
const internalStoreProps = {
|
|
329
|
-
$$init:
|
|
330
|
-
$$reset:
|
|
467
|
+
$$init: reducerMap.$$init,
|
|
468
|
+
$$reset: reducerMap.$$reset,
|
|
331
469
|
context,
|
|
332
470
|
initialState,
|
|
333
471
|
name,
|
|
@@ -343,11 +481,21 @@ function createStore(name, initialState, reducers) {
|
|
|
343
481
|
type: STATE_LINK,
|
|
344
482
|
};
|
|
345
483
|
}
|
|
346
|
-
|
|
484
|
+
store[INITIALIZED_STATE_NAME] = {
|
|
485
|
+
[INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
|
|
486
|
+
stateName: INITIALIZED_STATE_NAME,
|
|
487
|
+
type: STATE_LINK,
|
|
488
|
+
};
|
|
489
|
+
store[INSTANCE_KEY_STATE_NAME] = {
|
|
490
|
+
[INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
|
|
491
|
+
stateName: INSTANCE_KEY_STATE_NAME,
|
|
492
|
+
type: STATE_LINK,
|
|
493
|
+
};
|
|
494
|
+
for (const key in reducerMap) {
|
|
347
495
|
if (!(key in initialState) && ![`$$init`, `$$reset`].includes(key)) {
|
|
348
496
|
store[key] = {
|
|
349
497
|
[INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
|
|
350
|
-
reducer:
|
|
498
|
+
reducer: reducerMap[key],
|
|
351
499
|
reducerName: key,
|
|
352
500
|
type: REDUCER_LINK,
|
|
353
501
|
};
|
|
@@ -440,13 +588,6 @@ const requestState = {
|
|
|
440
588
|
},
|
|
441
589
|
};
|
|
442
590
|
|
|
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();
|
|
591
|
+
const { StoreProvider, useDispatcher, useProp, usePropAll, usePropSelector, usePropSelectorAll, useStore, } = createStoreRegistry();
|
|
451
592
|
|
|
452
|
-
export { DESTROY, InternalStore, StoreProvider, createStore, createStoreRegistry, requestState, requestStatus, useDispatcher, useProp, usePropAll, useStore };
|
|
593
|
+
export { DESTROY, InternalStore, StoreProvider, createStore, createStoreRegistry, requestState, requestStatus, useDispatcher, useProp, usePropAll, usePropSelector, usePropSelectorAll, useStore };
|