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.
Files changed (45) 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 +3 -2
  6. package/dist/@types/createUseStore.d.ts +2 -4
  7. package/dist/@types/ensureInternalStore.d.ts +6 -0
  8. package/dist/@types/index.d.ts +3 -4
  9. package/dist/@types/types/DeferredAction.d.ts +7 -0
  10. package/dist/@types/types/InitInstance.d.ts +3 -3
  11. package/dist/@types/types/InitializedStateLink.d.ts +11 -0
  12. package/dist/@types/types/InitializedStoreInstance.d.ts +5 -0
  13. package/dist/@types/types/InstanceKeyStateLink.d.ts +11 -0
  14. package/dist/@types/types/InternalStore/ApplyState.d.ts +5 -0
  15. package/dist/@types/types/InternalStore/Dispatch.d.ts +1 -1
  16. package/dist/@types/types/InternalStore/EnsureInstance.d.ts +4 -0
  17. package/dist/@types/types/InternalStore/GetInitializedInstance.d.ts +6 -0
  18. package/dist/@types/types/InternalStore/GetInstance.d.ts +6 -0
  19. package/dist/@types/types/InternalStore/GetUninitializedInstance.d.ts +6 -0
  20. package/dist/@types/types/InternalStore/InitInstance.d.ts +2 -4
  21. package/dist/@types/types/InternalStore/IsInitialized.d.ts +4 -0
  22. package/dist/@types/types/InternalStore/Listener.d.ts +1 -1
  23. package/dist/@types/types/InternalStore/ListenerAll.d.ts +1 -1
  24. package/dist/@types/types/InternalStore/PruneInstance.d.ts +4 -0
  25. package/dist/@types/types/InternalStore/ResetInstance.d.ts +3 -3
  26. package/dist/@types/types/InternalStoreProps.d.ts +2 -2
  27. package/dist/@types/types/ReducerMap.d.ts +2 -2
  28. package/dist/@types/types/RegisterDefaultInstance.d.ts +3 -3
  29. package/dist/@types/types/RegisterInstance.d.ts +3 -3
  30. package/dist/@types/types/ResetInstance.d.ts +2 -3
  31. package/dist/@types/types/Store.d.ts +4 -0
  32. package/dist/@types/types/StoreContextValue.d.ts +6 -0
  33. package/dist/@types/types/StoreInstance.d.ts +8 -0
  34. package/dist/@types/types/StoreProviderProps.d.ts +10 -0
  35. package/dist/@types/types/StoreRegistry.d.ts +2 -2
  36. package/dist/@types/types/UninitializedStoreInstance.d.ts +5 -0
  37. package/dist/@types/types/UseProp.d.ts +4 -0
  38. package/dist/cjs/index.cjs.js +286 -199
  39. package/dist/esm/index.esm.js +287 -200
  40. package/package.json +1 -1
  41. package/dist/@types/createStoreController.d.ts +0 -6
  42. package/dist/@types/types/InitPayload.d.ts +0 -3
  43. package/dist/@types/types/ResetPayload.d.ts +0 -3
  44. package/dist/@types/types/StoreController.d.ts +0 -10
  45. package/dist/@types/types/StoreInstanceController.d.ts +0 -7
@@ -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 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
- 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
- this.listeners[instanceKey].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
- this.listenersAll.add(listener);
162
+ const actualListener = (...args) => listener(...args);
163
+ this.listenersAll.add(actualListener);
78
164
  return () => {
79
- this.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
 
151
264
  function createUsePropAll(storeRegistry) {
152
265
  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.`);
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 internalStore = storeRegistry[internalStoreProps.uniqKey].internalStore;
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((state) => {
166
- let stateAll;
279
+ const selector = useCallback((stateAll) => {
280
+ let actualInstanceKeys;
167
281
  if (instanceKeys == null) {
168
- stateAll = Object.entries(state)
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
- stateAll = Object.entries(state)
175
- .filter(([_instanceKey, state]) => {
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
- stateAll = instanceKeys.map((instanceKey) => {
184
- return [instanceKey, state[instanceKey][stateLink.stateName]];
290
+ actualInstanceKeys = instanceKeys.filter((instanceKey) => {
291
+ return instanceKey in stateAll;
185
292
  });
186
293
  }
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);
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
- const stateAllEntry = stateAll.find(([instanceKey]) => {
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 internalStoreProps = storeRef.current.store[INTERNAL_STORE_PROPS_ACCESSOR];
223
- const contextInstanceKey = useContext(internalStoreProps.context);
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 ownerKeyRef = useRef({ ownerKey: Symbol(`ownerKey`) });
235
- const initInstancesRef = useRef({ initInstances: {} });
333
+ const registeredInstancesRef = useRef({ registeredInstances: Object.create(null) });
334
+ const registerInstanceRef = useRef({ registerInstance });
335
+ registerInstanceRef.current.registerInstance = registerInstance;
236
336
  useEffect(() => {
237
- const { ownerKey } = ownerKeyRef.current;
238
- const { initInstances } = initInstancesRef.current;
337
+ const { registeredInstances } = registeredInstancesRef.current;
338
+ const { registerInstance } = registerInstanceRef.current;
239
339
  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 {
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: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
346
+ console.log(`Store instance initialization [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
255
347
  // TODO Убрать в логгер
256
348
  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
- }
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
- 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) {
354
+ return () => {
355
+ if (owner) {
270
356
  // TODO Убрать в логгер
271
- console.log(`Store instance resetting [store: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
357
+ console.log(`Store instance resetting [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
272
358
  // TODO Убрать в логгер
273
359
  console.log({ storeRegistry });
274
- // TODO Надо ли оповещать слушателей если один экземпляр хранилища удалился
275
- storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps.$$reset);
276
- delete storeController.instances[instanceKey];
360
+ internalStore.resetInstance(instanceKey, internalStoreProps.$$reset);
277
361
  }
278
- delete initInstances[instanceKey];
362
+ delete registeredInstances[instanceKey];
279
363
  return STORE_INSTANCE_UNREGISTERED;
280
364
  };
281
365
  };
282
- initInstances[instanceKey] = {
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(initInstances), ...Object.getOwnPropertySymbols(initInstances)]) {
373
+ for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
290
374
  if (!actualInstanceKeys.includes(instanceKey)) {
291
- initInstances[instanceKey].resetInstance();
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 { initInstances } = initInstancesRef.current;
380
+ const { registeredInstances } = registeredInstancesRef.current;
299
381
  return () => {
300
- for (const instanceKey of [...Object.keys(initInstances), ...Object.getOwnPropertySymbols(initInstances)]) {
301
- initInstances[instanceKey].resetInstance();
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, reducers) {
410
+ function createStore(name, initialState, reducerMap) {
327
411
  const context = React.createContext(null);
328
412
  const internalStoreProps = {
329
- $$init: reducers.$$init,
330
- $$reset: reducers.$$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
- for (const key in reducers) {
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: reducers[key],
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
- 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();
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
@@ -20,5 +20,5 @@
20
20
  "prepublishOnly": "npm run build"
21
21
  },
22
22
  "types": "dist/@types",
23
- "version": "0.1.9"
23
+ "version": "0.1.11"
24
24
  }