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,200 +1,307 @@
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
 
266
+ function pickPropAll(stateAll, stateName, instanceKeys) {
267
+ let actualInstanceKeys;
268
+ if (instanceKeys == null) {
269
+ actualInstanceKeys = [...Object.keys(stateAll), ...Object.getOwnPropertySymbols(stateAll)];
270
+ }
271
+ else if (typeof instanceKeys === `function`) {
272
+ actualInstanceKeys = [...Object.keys(stateAll), ...Object.getOwnPropertySymbols(stateAll)].filter((instanceKey) => {
273
+ return instanceKeys(stateAll[instanceKey]);
274
+ });
275
+ }
276
+ else {
277
+ actualInstanceKeys = instanceKeys.filter((instanceKey) => {
278
+ return instanceKey in stateAll;
279
+ });
280
+ }
281
+ return actualInstanceKeys.map((instanceKey) => {
282
+ return [instanceKey, stateAll[instanceKey][stateName]];
283
+ });
284
+ }
285
+
153
286
  function createUsePropAll(storeRegistry) {
154
287
  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.`);
288
+ const stateLinkRef = React.useRef({ stateLink });
289
+ if (stateLinkRef.current.stateLink !== stateLink) {
290
+ console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
159
291
  }
160
- const internalStore = storeRegistry[internalStoreProps.uniqKey].internalStore;
292
+ const actualStateLink = stateLinkRef.current.stateLink;
293
+ const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
294
+ const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
161
295
  const subscribe = React.useCallback((listener) => {
162
296
  return internalStore.subscribeAll(listener);
163
297
  }, [internalStore]);
164
298
  const getSnapshot = React.useCallback(() => {
165
299
  return internalStore.getStateAll();
166
300
  }, [internalStore]);
167
- const selector = React.useCallback((state) => {
168
- let stateAll;
169
- if (instanceKeys == null) {
170
- stateAll = Object.entries(state)
171
- .map(([instanceKey, state]) => {
172
- return [instanceKey, state[stateLink.stateName]];
173
- });
174
- }
175
- 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]];
182
- });
183
- }
184
- else {
185
- stateAll = instanceKeys.map((instanceKey) => {
186
- return [instanceKey, state[instanceKey][stateLink.stateName]];
187
- });
188
- }
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);
301
+ const selector = React.useCallback((stateAll) => {
302
+ return pickPropAll(stateAll, actualStateLink.stateName, instanceKeys);
303
+ }, [actualStateLink, instanceKeys]);
304
+ return withSelector.useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector, isEqual);
198
305
  };
199
306
  }
200
307
  function isEqual(prevStateAll, stateAll) {
@@ -202,27 +309,69 @@ function isEqual(prevStateAll, stateAll) {
202
309
  return false;
203
310
  }
204
311
  else {
205
- return prevStateAll.every(([prevInstanceKey, prevState]) => {
206
- const stateAllEntry = stateAll.find(([instanceKey]) => {
207
- return prevInstanceKey === instanceKey;
208
- });
209
- return stateAllEntry && stateAllEntry[1] === prevState;
312
+ return prevStateAll.every(([prevInstanceKey, prevState], index) => {
313
+ return prevInstanceKey === stateAll[index][0] && prevState === stateAll[index][1];
210
314
  });
211
315
  }
212
316
  }
213
317
 
318
+ function createUsePropSelector(storeRegistry) {
319
+ return function usePropSelector(stateLink, instanceKey) {
320
+ const stateLinkRef = React.useRef({ stateLink });
321
+ if (stateLinkRef.current.stateLink !== stateLink) {
322
+ console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
323
+ }
324
+ const actualStateLink = stateLinkRef.current.stateLink;
325
+ const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
326
+ const storeContextValue = React.useContext(internalStoreProps.context);
327
+ const actualInstanceKey = instanceKey ?? storeContextValue?.instanceKey ?? DEFAULT_INSTANCE_KEY;
328
+ const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
329
+ const uninitializedState = storeContextValue?.instanceKey === actualInstanceKey
330
+ ? storeContextValue.uninitializedState
331
+ : internalStoreProps.initialState;
332
+ return React.useCallback(() => {
333
+ if (actualStateLink.stateName === INITIALIZED_STATE_NAME) {
334
+ return internalStore.isInitialized(actualInstanceKey);
335
+ }
336
+ else if (actualStateLink.stateName === INSTANCE_KEY_STATE_NAME) {
337
+ return actualInstanceKey;
338
+ }
339
+ else if (internalStore.isInitialized(actualInstanceKey)) {
340
+ return internalStore.getState(actualInstanceKey)[actualStateLink.stateName];
341
+ }
342
+ else {
343
+ return uninitializedState[actualStateLink.stateName];
344
+ }
345
+ }, [actualInstanceKey, actualStateLink, internalStore, uninitializedState]);
346
+ };
347
+ }
348
+
349
+ function createUsePropSelectorAll(storeRegistry) {
350
+ return function usePropSelectorAll(stateLink, instanceKeys) {
351
+ const stateLinkRef = React.useRef({ stateLink });
352
+ if (stateLinkRef.current.stateLink !== stateLink) {
353
+ console.warn(`State link reference mismatch. You must pass the same state link on every render.`);
354
+ }
355
+ const actualStateLink = stateLinkRef.current.stateLink;
356
+ const internalStoreProps = actualStateLink[INTERNAL_STORE_PROPS_ACCESSOR];
357
+ const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
358
+ return React.useCallback(() => {
359
+ return pickPropAll(internalStore.getStateAll(), actualStateLink.stateName, instanceKeys);
360
+ }, [actualStateLink, instanceKeys, internalStore]);
361
+ };
362
+ }
363
+
214
364
  function createUseStore(storeRegistry) {
215
365
  function useStore(store, ...args) {
216
366
  const storeRef = React.useRef({ store });
217
- const storeMismatchWarnedRef = React.useRef({ warned: false });
218
367
  if (storeRef.current.store !== store) {
219
368
  console.warn(`Store reference mismatch. You must pass the same store instance on every render.`);
220
- storeMismatchWarnedRef.current.warned = true;
221
369
  }
222
370
  let instanceKeys;
223
371
  let registerInstance;
224
- const internalStoreProps = storeRef.current.store[INTERNAL_STORE_PROPS_ACCESSOR];
225
- const contextInstanceKey = React.useContext(internalStoreProps.context);
372
+ const actualStore = storeRef.current.store;
373
+ const internalStoreProps = actualStore[INTERNAL_STORE_PROPS_ACCESSOR];
374
+ const contextInstanceKey = React.useContext(internalStoreProps.context)?.instanceKey;
226
375
  if (typeof args[0] === `function`) {
227
376
  instanceKeys = [contextInstanceKey ?? DEFAULT_INSTANCE_KEY];
228
377
  registerInstance = args[0];
@@ -233,74 +382,57 @@ function createUseStore(storeRegistry) {
233
382
  }
234
383
  // eslint-disable-next-line react-hooks/exhaustive-deps
235
384
  const actualInstanceKeys = React.useMemo(() => instanceKeys, instanceKeys);
236
- const ownerKeyRef = React.useRef({ ownerKey: Symbol(`ownerKey`) });
237
- const initInstancesRef = React.useRef({ initInstances: {} });
385
+ const registeredInstancesRef = React.useRef({ registeredInstances: Object.create(null) });
386
+ const registerInstanceRef = React.useRef({ registerInstance });
387
+ registerInstanceRef.current.registerInstance = registerInstance;
238
388
  React.useEffect(() => {
239
- const { ownerKey } = ownerKeyRef.current;
240
- const { initInstances } = initInstancesRef.current;
389
+ const { registeredInstances } = registeredInstancesRef.current;
390
+ const { registerInstance } = registerInstanceRef.current;
241
391
  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 {
392
+ if (!registeredInstances[instanceKey]) {
393
+ const initInstance = (prefill) => {
394
+ const internalStore = ensureInternalStore(storeRegistry, internalStoreProps);
395
+ const owner = !internalStore.isInitialized(instanceKey);
396
+ if (owner) {
255
397
  // TODO Убрать в логгер
256
- console.log(`Store instance initialization [store: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
398
+ console.log(`Store instance initialization [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
257
399
  // TODO Убрать в логгер
258
400
  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
- }
401
+ internalStore.initInstance(instanceKey, internalStoreProps.$$init, internalStoreProps.initialState, prefill);
402
+ }
403
+ else {
404
+ console.warn(`Store instance is already initialized, initialization skipped [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
267
405
  }
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) {
406
+ return () => {
407
+ if (owner) {
272
408
  // TODO Убрать в логгер
273
- console.log(`Store instance resetting [store: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
409
+ console.log(`Store instance resetting [store: ${internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
274
410
  // TODO Убрать в логгер
275
411
  console.log({ storeRegistry });
276
- // TODO Надо ли оповещать слушателей если один экземпляр хранилища удалился
277
- storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps.$$reset);
278
- delete storeController.instances[instanceKey];
412
+ internalStore.resetInstance(instanceKey, internalStoreProps.$$reset);
279
413
  }
280
- delete initInstances[instanceKey];
414
+ delete registeredInstances[instanceKey];
281
415
  return STORE_INSTANCE_UNREGISTERED;
282
416
  };
283
417
  };
284
- initInstances[instanceKey] = {
418
+ registeredInstances[instanceKey] = {
285
419
  resetInstance: instanceKey === DEFAULT_INSTANCE_KEY
286
420
  ? registerInstance(initInstance)
287
421
  : registerInstance(initInstance, instanceKey),
288
422
  };
289
423
  }
290
424
  }
291
- for (const instanceKey of [...Object.keys(initInstances), ...Object.getOwnPropertySymbols(initInstances)]) {
425
+ for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
292
426
  if (!actualInstanceKeys.includes(instanceKey)) {
293
- initInstances[instanceKey].resetInstance();
427
+ registeredInstances[instanceKey].resetInstance();
294
428
  }
295
429
  }
296
- },
297
- // eslint-disable-next-line react-hooks/exhaustive-deps
298
- [actualInstanceKeys, internalStoreProps, /*registerInstance*/]);
430
+ }, [actualInstanceKeys, internalStoreProps]);
299
431
  React.useEffect(() => {
300
- const { initInstances } = initInstancesRef.current;
432
+ const { registeredInstances } = registeredInstancesRef.current;
301
433
  return () => {
302
- for (const instanceKey of [...Object.keys(initInstances), ...Object.getOwnPropertySymbols(initInstances)]) {
303
- initInstances[instanceKey].resetInstance();
434
+ for (const instanceKey of [...Object.keys(registeredInstances), ...Object.getOwnPropertySymbols(registeredInstances)]) {
435
+ registeredInstances[instanceKey].resetInstance();
304
436
  }
305
437
  };
306
438
  }, []);
@@ -309,27 +441,33 @@ function createUseStore(storeRegistry) {
309
441
  }
310
442
 
311
443
  function createStoreRegistry() {
312
- const storeRegistry = {};
444
+ const storeRegistry = Object.create(null);
313
445
  const useStore = createUseStore(storeRegistry);
314
446
  const useProp = createUseProp(storeRegistry);
315
447
  const usePropAll = createUsePropAll(storeRegistry);
448
+ const usePropSelector = createUsePropSelector(storeRegistry);
449
+ const usePropSelectorAll = createUsePropSelectorAll(storeRegistry);
316
450
  const useDispatcher = createUseDispatcher(storeRegistry);
317
451
  const useLatest = createUseLatest();
452
+ const StoreProvider = createStoreProvider(useStore);
318
453
  return {
454
+ StoreProvider,
319
455
  storeRegistry,
320
- useStore,
321
- useProp,
322
- usePropAll,
323
456
  useDispatcher,
324
457
  useLatest,
458
+ useProp,
459
+ usePropAll,
460
+ usePropSelector,
461
+ usePropSelectorAll,
462
+ useStore,
325
463
  };
326
464
  }
327
465
 
328
- function createStore(name, initialState, reducers) {
466
+ function createStore(name, initialState, reducerMap) {
329
467
  const context = React.createContext(null);
330
468
  const internalStoreProps = {
331
- $$init: reducers.$$init,
332
- $$reset: reducers.$$reset,
469
+ $$init: reducerMap.$$init,
470
+ $$reset: reducerMap.$$reset,
333
471
  context,
334
472
  initialState,
335
473
  name,
@@ -345,11 +483,21 @@ function createStore(name, initialState, reducers) {
345
483
  type: STATE_LINK,
346
484
  };
347
485
  }
348
- for (const key in reducers) {
486
+ store[INITIALIZED_STATE_NAME] = {
487
+ [INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
488
+ stateName: INITIALIZED_STATE_NAME,
489
+ type: STATE_LINK,
490
+ };
491
+ store[INSTANCE_KEY_STATE_NAME] = {
492
+ [INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
493
+ stateName: INSTANCE_KEY_STATE_NAME,
494
+ type: STATE_LINK,
495
+ };
496
+ for (const key in reducerMap) {
349
497
  if (!(key in initialState) && ![`$$init`, `$$reset`].includes(key)) {
350
498
  store[key] = {
351
499
  [INTERNAL_STORE_PROPS_ACCESSOR]: internalStoreProps,
352
- reducer: reducers[key],
500
+ reducer: reducerMap[key],
353
501
  reducerName: key,
354
502
  type: REDUCER_LINK,
355
503
  };
@@ -442,14 +590,7 @@ const requestState = {
442
590
  },
443
591
  };
444
592
 
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();
593
+ const { StoreProvider, useDispatcher, useProp, usePropAll, usePropSelector, usePropSelectorAll, useStore, } = createStoreRegistry();
453
594
 
454
595
  exports.DESTROY = DESTROY;
455
596
  exports.InternalStore = InternalStore;
@@ -461,4 +602,6 @@ exports.requestStatus = requestStatus;
461
602
  exports.useDispatcher = useDispatcher;
462
603
  exports.useProp = useProp;
463
604
  exports.usePropAll = usePropAll;
605
+ exports.usePropSelector = usePropSelector;
606
+ exports.usePropSelectorAll = usePropSelectorAll;
464
607
  exports.useStore = useStore;