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.
Files changed (51) hide show
  1. package/dist/@types/InternalStore.d.ts +17 -10
  2. package/dist/@types/StoreProvider.d.ts +3 -8
  3. package/dist/@types/constants.d.ts +3 -0
  4. package/dist/@types/createStore.d.ts +5 -2
  5. package/dist/@types/createStoreRegistry.d.ts +9 -6
  6. package/dist/@types/createUsePropSelector.d.ts +3 -0
  7. package/dist/@types/createUsePropSelectorAll.d.ts +3 -0
  8. package/dist/@types/createUseStore.d.ts +2 -4
  9. package/dist/@types/ensureInternalStore.d.ts +6 -0
  10. package/dist/@types/index.d.ts +3 -4
  11. package/dist/@types/pickPropAll.d.ts +3 -0
  12. package/dist/@types/types/DeferredAction.d.ts +7 -0
  13. package/dist/@types/types/InitInstance.d.ts +3 -3
  14. package/dist/@types/types/InitializedStateLink.d.ts +11 -0
  15. package/dist/@types/types/InitializedStoreInstance.d.ts +5 -0
  16. package/dist/@types/types/InstanceKeyStateLink.d.ts +11 -0
  17. package/dist/@types/types/InternalStore/ApplyState.d.ts +5 -0
  18. package/dist/@types/types/InternalStore/Dispatch.d.ts +1 -1
  19. package/dist/@types/types/InternalStore/EnsureInstance.d.ts +4 -0
  20. package/dist/@types/types/InternalStore/GetInitializedInstance.d.ts +6 -0
  21. package/dist/@types/types/InternalStore/GetInstance.d.ts +6 -0
  22. package/dist/@types/types/InternalStore/GetUninitializedInstance.d.ts +6 -0
  23. package/dist/@types/types/InternalStore/InitInstance.d.ts +2 -4
  24. package/dist/@types/types/InternalStore/IsInitialized.d.ts +4 -0
  25. package/dist/@types/types/InternalStore/Listener.d.ts +1 -1
  26. package/dist/@types/types/InternalStore/ListenerAll.d.ts +1 -1
  27. package/dist/@types/types/InternalStore/PruneInstance.d.ts +4 -0
  28. package/dist/@types/types/InternalStore/ResetInstance.d.ts +3 -3
  29. package/dist/@types/types/InternalStoreProps.d.ts +2 -2
  30. package/dist/@types/types/ReducerMap.d.ts +2 -2
  31. package/dist/@types/types/RegisterDefaultInstance.d.ts +3 -3
  32. package/dist/@types/types/RegisterInstance.d.ts +3 -3
  33. package/dist/@types/types/ResetInstance.d.ts +2 -3
  34. package/dist/@types/types/Store.d.ts +4 -0
  35. package/dist/@types/types/StoreContextValue.d.ts +6 -0
  36. package/dist/@types/types/StoreInstance.d.ts +8 -0
  37. package/dist/@types/types/StoreProviderProps.d.ts +10 -0
  38. package/dist/@types/types/StoreRegistry.d.ts +2 -2
  39. package/dist/@types/types/UninitializedStoreInstance.d.ts +5 -0
  40. package/dist/@types/types/UseProp.d.ts +4 -0
  41. package/dist/@types/types/UsePropSelector.d.ts +11 -0
  42. package/dist/@types/types/UsePropSelectorAll.d.ts +7 -0
  43. package/dist/cjs/index.cjs.js +353 -210
  44. package/dist/esm/index.esm.js +353 -212
  45. package/package.json +1 -1
  46. package/dist/@types/createStoreController.d.ts +0 -6
  47. package/dist/@types/createUseSelector.d.ts +0 -1
  48. package/dist/@types/types/InitPayload.d.ts +0 -3
  49. package/dist/@types/types/ResetPayload.d.ts +0 -3
  50. package/dist/@types/types/StoreController.d.ts +0 -10
  51. package/dist/@types/types/StoreInstanceController.d.ts +0 -7
@@ -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 createUseDispatcher(storeRegistry) {
13
- return function useDispatcher(reducerLink) {
14
- const contextInstanceKey = useContext(reducerLink[INTERNAL_STORE_PROPS_ACCESSOR].context);
15
- return useMemo(() => {
16
- const internalStoreProps = reducerLink[INTERNAL_STORE_PROPS_ACCESSOR];
17
- function dispatch(...args) {
18
- let instanceKey;
19
- let payload;
20
- if ([`number`, `symbol`, `string`].includes(typeof args[0])) {
21
- instanceKey = args[0];
22
- payload = args[1];
23
- }
24
- else {
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
- return this.state[instanceKey];
88
+ const instance = this.getInitializedInstance(instanceKey);
89
+ return instance.state;
54
90
  };
55
91
  this.getStateAll = () => {
56
- return this.state;
92
+ return this.stateAll;
57
93
  };
58
- this.initInstance = (instanceKey, initialState, initPayload, initReducer) => {
59
- // TODO От множественной инициализации было решено отказаться. Надо кинуть предупреждение.
60
- this.state = { ...this.state, [instanceKey]: this.state[instanceKey] ?? initialState };
61
- // TODO От множественной инициализации было решено отказаться. Надо кинуть предупреждение.
62
- this.listeners[instanceKey] = this.listeners[instanceKey] ?? new Set();
63
- this.dispatch(instanceKey, initPayload, initReducer);
64
- return (resetPayload, resetReducer) => {
65
- this.dispatch(instanceKey, resetPayload, resetReducer);
66
- delete this.state[instanceKey];
67
- delete this.listeners[instanceKey];
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
- const listeners = this.listeners[instanceKey].add(listener);
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(listener);
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 listenersAll = this.listenersAll.add(listener);
162
+ const actualListener = (...args) => listener(...args);
163
+ this.listenersAll.add(actualListener);
78
164
  return () => {
79
- listenersAll.delete(listener);
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.dispatch = (instanceKey, payload, reducer) => {
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.state = {};
174
+ this.stateAll = Object.create(null);
97
175
  }
98
176
  }
99
177
 
100
- function createStoreController(storeRegistry, internalStoreProps) {
101
- let storeController = storeRegistry[internalStoreProps.uniqKey];
102
- if (!storeController) {
103
- const internalStore = new InternalStore(internalStoreProps.name);
104
- storeController = { earlySubscribers: {}, instances: {}, internalStore };
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 storeController;
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 internalStoreProps = stateLink[INTERNAL_STORE_PROPS_ACCESSOR];
113
- const contextInstanceKey = useContext(internalStoreProps.context);
114
- const actualInstanceKey = instanceKey ?? contextInstanceKey ?? DEFAULT_INSTANCE_KEY;
115
- const [, setUninitializedHack] = useState(0);
116
- const earlySubscriberRef = useRef({ earlySubscriber: null });
117
- const storeController = createStoreController(storeRegistry, internalStoreProps);
118
- const initialized = actualInstanceKey in storeController.instances;
119
- const { getSnapshot, subscribe } = useMemo(() => {
120
- let subscribe;
121
- let getSnapshot;
122
- if (initialized) {
123
- subscribe = (listener) => {
124
- return storeController.internalStore.subscribe(actualInstanceKey, listener);
125
- };
126
- getSnapshot = () => {
127
- return storeController.internalStore.getState(actualInstanceKey);
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
- subscribe = () => () => undefined;
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
- return { getSnapshot, subscribe };
143
- }, [actualInstanceKey, initialized, internalStoreProps, storeController]);
248
+ }, [actualInstanceKey, internalStore, uninitializedState]);
144
249
  const selector = useCallback((state) => {
145
- return state[stateLink.stateName];
146
- }, [stateLink]);
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 internalStoreProps = stateLink[INTERNAL_STORE_PROPS_ACCESSOR];
154
- const prevStateAllRef = useRef({ prevStateAll: [] });
155
- if (!(internalStoreProps.uniqKey in storeRegistry)) {
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 internalStore = storeRegistry[internalStoreProps.uniqKey].internalStore;
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((state) => {
166
- let stateAll;
167
- if (instanceKeys == null) {
168
- stateAll = Object.entries(state)
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
- const stateAllEntry = stateAll.find(([instanceKey]) => {
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 internalStoreProps = storeRef.current.store[INTERNAL_STORE_PROPS_ACCESSOR];
223
- const contextInstanceKey = useContext(internalStoreProps.context);
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 ownerKeyRef = useRef({ ownerKey: Symbol(`ownerKey`) });
235
- const initInstancesRef = useRef({ initInstances: {} });
383
+ const registeredInstancesRef = useRef({ registeredInstances: Object.create(null) });
384
+ const registerInstanceRef = useRef({ registerInstance });
385
+ registerInstanceRef.current.registerInstance = registerInstance;
236
386
  useEffect(() => {
237
- const { ownerKey } = ownerKeyRef.current;
238
- const { initInstances } = initInstancesRef.current;
387
+ const { registeredInstances } = registeredInstancesRef.current;
388
+ const { registerInstance } = registerInstanceRef.current;
239
389
  for (const instanceKey of actualInstanceKeys) {
240
- // TODO А что по поводу альтернативного сценария?
241
- if (!initInstances[instanceKey]) {
242
- const initInstance = (initPayload) => {
243
- const storeController = createStoreController(storeRegistry, internalStoreProps);
244
- if (storeController.instances[instanceKey]) {
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: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
396
+ console.log(`Store instance initialization [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
255
397
  // TODO Убрать в логгер
256
398
  console.log({ storeRegistry });
257
- const resetState = storeController.internalStore.initInstance(instanceKey, internalStoreProps.initialState, initPayload, internalStoreProps.$$init);
258
- storeController.instances[instanceKey] = { owners: [], resetState };
259
- if (storeController.earlySubscribers[instanceKey]) {
260
- for (const subscriber of storeController.earlySubscribers[instanceKey]) {
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
- storeController.instances[instanceKey].owners.push(ownerKey);
267
- return (resetPayload) => {
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: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
407
+ console.log(`Store instance resetting [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
272
408
  // TODO Убрать в логгер
273
409
  console.log({ storeRegistry });
274
- // TODO Надо ли оповещать слушателей если один экземпляр хранилища удалился
275
- storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps.$$reset);
276
- delete storeController.instances[instanceKey];
410
+ internalStore.resetInstance(instanceKey, internalStoreProps.$$reset);
277
411
  }
278
- delete initInstances[instanceKey];
412
+ delete registeredInstances[instanceKey];
279
413
  return STORE_INSTANCE_UNREGISTERED;
280
414
  };
281
415
  };
282
- initInstances[instanceKey] = {
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(initInstances), ...Object.getOwnPropertySymbols(initInstances)]) {
423
+ for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
290
424
  if (!actualInstanceKeys.includes(instanceKey)) {
291
- initInstances[instanceKey].resetInstance();
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 { initInstances } = initInstancesRef.current;
430
+ const { registeredInstances } = registeredInstancesRef.current;
299
431
  return () => {
300
- for (const instanceKey of [...Object.keys(initInstances), ...Object.getOwnPropertySymbols(initInstances)]) {
301
- initInstances[instanceKey].resetInstance();
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, reducers) {
464
+ function createStore(name, initialState, reducerMap) {
327
465
  const context = React.createContext(null);
328
466
  const internalStoreProps = {
329
- $$init: reducers.$$init,
330
- $$reset: reducers.$$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
- for (const key in reducers) {
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: reducers[key],
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
- function StoreProvider({ children,
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 };