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