beestate 0.1.5 → 0.1.7

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 (50) hide show
  1. package/dist/@types/InternalStore.d.ts +10 -40
  2. package/dist/@types/StoreProvider.d.ts +7 -3
  3. package/dist/@types/createStore.d.ts +4 -4
  4. package/dist/@types/createStoreController.d.ts +6 -0
  5. package/dist/@types/createStoreRegistry.d.ts +1 -1
  6. package/dist/@types/createUseDispatcher.d.ts +6 -6
  7. package/dist/@types/createUseLatest.d.ts +6 -6
  8. package/dist/@types/createUseProp.d.ts +2 -2
  9. package/dist/@types/createUsePropAll.d.ts +2 -2
  10. package/dist/@types/createUseStore.d.ts +9 -9
  11. package/dist/@types/index.d.ts +2 -2
  12. package/dist/@types/requestState.d.ts +2 -2
  13. package/dist/@types/types/Dispatcher.d.ts +2 -2
  14. package/dist/@types/types/InitInstance.d.ts +2 -2
  15. package/dist/@types/types/InitPayload.d.ts +2 -2
  16. package/dist/@types/types/InstanceKey.d.ts +1 -1
  17. package/dist/@types/types/InternalStore/Dispatch.d.ts +7 -0
  18. package/dist/@types/types/InternalStore/GetState.d.ts +5 -0
  19. package/dist/@types/types/InternalStore/GetStateAll.d.ts +5 -0
  20. package/dist/@types/types/InternalStore/InitInstance.d.ts +8 -0
  21. package/dist/@types/types/InternalStore/Listener.d.ts +7 -0
  22. package/dist/@types/types/InternalStore/ListenerAll.d.ts +7 -0
  23. package/dist/@types/types/InternalStore/ResetInstance.d.ts +6 -0
  24. package/dist/@types/types/InternalStore/Subscribe.d.ts +7 -0
  25. package/dist/@types/types/InternalStore/SubscribeAll.d.ts +6 -0
  26. package/dist/@types/types/InternalStore/Unsubscribe.d.ts +3 -0
  27. package/dist/@types/types/InternalStore/UnsubscribeAll.d.ts +3 -0
  28. package/dist/@types/types/InternalStoreProps.d.ts +5 -5
  29. package/dist/@types/types/Reducer.d.ts +2 -2
  30. package/dist/@types/types/ReducerLink.d.ts +5 -5
  31. package/dist/@types/types/ReducerMap.d.ts +4 -4
  32. package/dist/@types/types/ReducerPayload.d.ts +2 -2
  33. package/dist/@types/types/RegisterDefaultInstance.d.ts +2 -2
  34. package/dist/@types/types/RegisterInstance.d.ts +3 -3
  35. package/dist/@types/types/RequestState/RequestRejectedState.d.ts +1 -1
  36. package/dist/@types/types/RequestState.d.ts +1 -1
  37. package/dist/@types/types/ResetInstance.d.ts +1 -1
  38. package/dist/@types/types/ResetPayload.d.ts +2 -2
  39. package/dist/@types/types/StateLink.d.ts +3 -3
  40. package/dist/@types/types/Store.d.ts +7 -8
  41. package/dist/@types/types/StoreController.d.ts +6 -5
  42. package/dist/@types/types/StoreInstanceController.d.ts +7 -0
  43. package/dist/@types/types/StoreRegistry.d.ts +1 -1
  44. package/dist/@types/types/UseProp.d.ts +4 -4
  45. package/dist/@types/types/UsePropAll.d.ts +4 -4
  46. package/dist/cjs/index.cjs.js +112 -89
  47. package/dist/esm/index.esm.js +113 -90
  48. package/package.json +1 -1
  49. package/dist/@types/types/StoreControllerInstance.d.ts +0 -7
  50. package/dist/@types/types/index.d.ts +0 -30
@@ -1,43 +1,13 @@
1
- import type { InitPayload } from './types/index.tsx';
2
- import type { InstanceKey } from './types/index.tsx';
3
- import type { Payload } from './types/index.tsx';
4
- import type { Reducer } from './types/index.tsx';
5
- import type { ReducerMap } from './types/index.tsx';
6
- import type { ResetPayload } from './types/index.tsx';
7
- import type { StoreState } from './types/index.tsx';
8
- export type Dispatch<TStoreState extends StoreState = StoreState> = {
9
- <TPayload extends void | Payload = void | Payload>(instanceKey: InstanceKey, payload: TPayload, reducer: Reducer<TStoreState, TPayload>): void;
10
- };
11
- export type Listener<TStoreState extends StoreState = StoreState> = {
12
- <TPayload extends void | Payload = void | Payload, TReducer extends Reducer<TStoreState, TPayload> = Reducer<TStoreState, TPayload>>(instanceKey: InstanceKey, payload: TPayload, reducer: TReducer): void;
13
- };
14
- export type ListenerAll<TStoreState extends StoreState = StoreState> = {
15
- <TPayload extends void | Payload = void | Payload, TReducer extends Reducer<TStoreState, TPayload> = Reducer<TStoreState, TPayload>>(instanceKey: InstanceKey, payload: TPayload, reducer: TReducer): void;
16
- };
17
- export type Subscribe<TStoreState extends StoreState = StoreState> = {
18
- (instanceKey: InstanceKey, listener: Listener<TStoreState>): Unsubscribe;
19
- };
20
- export type Unsubscribe = {
21
- (): void;
22
- };
23
- export type SubscribeAll<TStoreState extends StoreState = StoreState> = {
24
- (listener: ListenerAll<TStoreState>): UnsubscribeAll;
25
- };
26
- export type UnsubscribeAll = {
27
- (): void;
28
- };
29
- export type InitInstance<TStoreState extends StoreState = StoreState, TInitPayload extends void | Payload = void | Payload, TResetPayload extends void | Payload = void | Payload> = {
30
- (instanceKey: InstanceKey, initialState: TStoreState, initPayload: TInitPayload, initReducer: Reducer<TStoreState, TInitPayload>): ResetInstance<TStoreState, TResetPayload>;
31
- };
32
- export type ResetInstance<TStoreState extends StoreState = StoreState, TResetPayload extends void | Payload = void | Payload> = {
33
- (resetPayload: TResetPayload, resetReducer: Reducer<TStoreState, TResetPayload>): void;
34
- };
35
- export type GetState<TStoreState extends StoreState = StoreState> = {
36
- (instanceKey: InstanceKey): TStoreState;
37
- };
38
- export type GetStateAll<TStoreState extends StoreState = StoreState> = {
39
- (): Record<InstanceKey, TStoreState>;
40
- };
1
+ import type { Dispatch } from './types/InternalStore/Dispatch.tsx';
2
+ import type { GetState } from './types/InternalStore/GetState.tsx';
3
+ import type { GetStateAll } from './types/InternalStore/GetStateAll.tsx';
4
+ import type { InitInstance } from './types/InternalStore/InitInstance.tsx';
5
+ import type { InitPayload } from './types/InitPayload.tsx';
6
+ import type { ReducerMap } from './types/ReducerMap.tsx';
7
+ import type { ResetPayload } from './types/ResetPayload.tsx';
8
+ import type { StoreState } from './types/StoreState.tsx';
9
+ import type { Subscribe } from './types/InternalStore/Subscribe.tsx';
10
+ import type { SubscribeAll } from './types/InternalStore/SubscribeAll.tsx';
41
11
  export declare class InternalStore<TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>> {
42
12
  private listeners;
43
13
  private listenersAll;
@@ -1,8 +1,12 @@
1
1
  import React from 'react';
2
- import type { InstanceKey } from './types/index.tsx';
3
- import type { Store } from './types/index.tsx';
2
+ import type { InstanceKey } from './types/InstanceKey.tsx';
3
+ import { INTERNAL_STORE_PROPS_ACCESSOR } from './constants.tsx';
4
4
  export type StoreProviderProps = React.PropsWithChildren<{
5
- store: Store;
5
+ store: {
6
+ [INTERNAL_STORE_PROPS_ACCESSOR]: {
7
+ context: React.Context<null | InstanceKey>;
8
+ };
9
+ };
6
10
  instanceKey: InstanceKey;
7
11
  }>;
8
12
  export declare function StoreProvider(props: StoreProviderProps): import("react/jsx-runtime").JSX.Element;
@@ -1,7 +1,7 @@
1
- import type { Payload } from './types/index.tsx';
2
- import type { ReducerMap } from './types/index.tsx';
3
- import type { Store } from './types/index.tsx';
4
- import type { StoreState } from './types/index.tsx';
1
+ import type { Payload } from './types/Payload.tsx';
2
+ import type { ReducerMap } from './types/ReducerMap.tsx';
3
+ import type { Store } from './types/Store.tsx';
4
+ import type { StoreState } from './types/StoreState.tsx';
5
5
  type CheckReducerMap<TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>> = {
6
6
  [TKey in keyof TReducerMap]: TKey extends keyof TStoreState ? void : TReducerMap[TKey] extends (state: any, payload: void) => any ? TReducerMap[TKey] : TReducerMap[TKey] extends (state: any, payload: infer TPayload) => any ? TPayload extends Payload ? TReducerMap[TKey] : void : void;
7
7
  };
@@ -0,0 +1,6 @@
1
+ import type { InternalStoreProps } from './types/InternalStoreProps.tsx';
2
+ import type { ReducerMap } from './types/ReducerMap.tsx';
3
+ import type { StoreController } from './types/StoreController.tsx';
4
+ import type { StoreRegistry } from './types/StoreRegistry.tsx';
5
+ import type { StoreState } from './types/StoreState.tsx';
6
+ export declare function createStoreController<TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>>(storeRegistry: StoreRegistry, internalStoreProps: InternalStoreProps<string, TStoreState, TReducerMap>): StoreController<TStoreState, TReducerMap>;
@@ -1,4 +1,4 @@
1
- import type { StoreRegistry } from './types/index.tsx';
1
+ import type { StoreRegistry } from './types/StoreRegistry.tsx';
2
2
  export declare function createStoreRegistry(): {
3
3
  storeRegistry: StoreRegistry;
4
4
  useStore: {
@@ -1,7 +1,7 @@
1
- import type { ReducerMap } from './types/index.tsx';
2
- import type { Dispatcher } from './types/index.tsx';
3
- import type { ReducerLink } from './types/index.tsx';
4
- import type { ReducerPayload } from './types/index.tsx';
5
- import type { StoreRegistry } from './types/index.tsx';
6
- import type { StoreState } from './types/index.tsx';
1
+ import type { ReducerMap } from './types/ReducerMap.tsx';
2
+ import type { Dispatcher } from './types/Dispatcher.tsx';
3
+ import type { ReducerLink } from './types/ReducerLink.tsx';
4
+ import type { ReducerPayload } from './types/ReducerPayload.tsx';
5
+ import type { StoreRegistry } from './types/StoreRegistry.tsx';
6
+ import type { StoreState } from './types/StoreState.tsx';
7
7
  export declare function createUseDispatcher(storeRegistry: StoreRegistry): <TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>, TReducerName extends string = string, TPayload extends ReducerPayload<TReducerMap[TReducerName]> = ReducerPayload<TReducerMap[TReducerName]>>(reducerLink: ReducerLink<string, TStoreState, TReducerMap, TReducerName>) => Dispatcher<TPayload>;
@@ -1,9 +1,9 @@
1
- import type { InstanceKey } from './types/index.tsx';
2
- import type { Reducer } from './types/index.tsx';
3
- import type { ReducerLink } from './types/index.tsx';
4
- import type { ReducerMap } from './types/index.tsx';
5
- import type { StoreRegistry } from './types/index.tsx';
6
- import type { StoreState } from './types/index.tsx';
1
+ import type { InstanceKey } from './types/InstanceKey.tsx';
2
+ import type { Reducer } from './types/Reducer.tsx';
3
+ import type { ReducerLink } from './types/ReducerLink.tsx';
4
+ import type { ReducerMap } from './types/ReducerMap.tsx';
5
+ import type { StoreRegistry } from './types/StoreRegistry.tsx';
6
+ import type { StoreState } from './types/StoreState.tsx';
7
7
  type Saga<TActionName extends string = string, TPayload extends any = any, TContext extends any = any> = {
8
8
  (actionName: TActionName, payload: TPayload, ctx: TContext): void;
9
9
  };
@@ -1,3 +1,3 @@
1
- import type { StoreRegistry } from './types/index.tsx';
2
- import type { UseProp } from './types/index.tsx';
1
+ import type { StoreRegistry } from './types/StoreRegistry.tsx';
2
+ import type { UseProp } from './types/UseProp.tsx';
3
3
  export declare function createUseProp(storeRegistry: StoreRegistry): UseProp;
@@ -1,3 +1,3 @@
1
- import type { StoreRegistry } from './types/index.tsx';
2
- import type { UsePropAll } from './types/index.tsx';
1
+ import type { StoreRegistry } from './types/StoreRegistry.tsx';
2
+ import type { UsePropAll } from './types/UsePropAll.tsx';
3
3
  export declare function createUsePropAll(storeRegistry: StoreRegistry): UsePropAll;
@@ -1,12 +1,12 @@
1
- import type { InitPayload } from './types/index.tsx';
2
- import type { InstanceKey } from './types/index.tsx';
3
- import type { ReducerMap } from './types/index.tsx';
4
- import type { RegisterDefaultInstance } from './types/index.tsx';
5
- import type { RegisterInstance } from './types/index.tsx';
6
- import type { ResetPayload } from './types/index.tsx';
7
- import type { Store } from './types/index.tsx';
8
- import type { StoreRegistry } from './types/index.tsx';
9
- import type { StoreState } from './types/index.tsx';
1
+ import type { InitPayload } from './types/InitPayload.tsx';
2
+ import type { InstanceKey } from './types/InstanceKey.tsx';
3
+ import type { ReducerMap } from './types/ReducerMap.tsx';
4
+ import type { RegisterDefaultInstance } from './types/RegisterDefaultInstance.tsx';
5
+ import type { RegisterInstance } from './types/RegisterInstance.tsx';
6
+ import type { ResetPayload } from './types/ResetPayload.tsx';
7
+ import type { Store } from './types/Store.tsx';
8
+ import type { StoreRegistry } from './types/StoreRegistry.tsx';
9
+ import type { StoreState } from './types/StoreState.tsx';
10
10
  export declare function createUseStore(storeRegistry: StoreRegistry): {
11
11
  <TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>, TInitPayload extends InitPayload<TReducerMap> = InitPayload<TReducerMap>, TResetPayload extends ResetPayload<TReducerMap> = ResetPayload<TReducerMap>>(store: Store<string, TStoreState, TReducerMap>, registerInstance: RegisterDefaultInstance<TInitPayload, TResetPayload>): void;
12
12
  <TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>, TInitPayload extends InitPayload<TReducerMap> = InitPayload<TReducerMap>, TResetPayload extends ResetPayload<TReducerMap> = ResetPayload<TReducerMap>>(store: Store<string, TStoreState, TReducerMap>, instanceKeys: InstanceKey[], registerInstance: RegisterInstance<TInitPayload, TResetPayload>): void;
@@ -1,5 +1,5 @@
1
- export { type InstanceKey } from './types/index.tsx';
2
- export { type RequestState } from './types/index.tsx';
1
+ export { type InstanceKey } from './types/InstanceKey.tsx';
2
+ export { type RequestState } from './types/RequestState.tsx';
3
3
  export { type RequestAbortedState } from './types/RequestState/RequestAbortedState.tsx';
4
4
  export { type RequestFulfilledState } from './types/RequestState/RequestFulfilledState.tsx';
5
5
  export { type RequestIdleState } from './types/RequestState/RequestIdleState.tsx';
@@ -9,11 +9,11 @@ export declare const requestState: {
9
9
  idle: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestIdleState<TMeta>;
10
10
  pending: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestPendingState<TMeta>;
11
11
  fulfilled: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestFulfilledState<TMeta>;
12
- rejected: <TError extends Error = Error, TMeta extends RequestStateMeta = RequestStateMeta>(error?: null | TError, meta?: null | TMeta) => RequestRejectedState<TError, TMeta>;
12
+ rejected: <TMeta extends RequestStateMeta = RequestStateMeta, TError extends unknown = unknown>(error?: null | TError, meta?: null | TMeta) => RequestRejectedState<TMeta, TError>;
13
13
  aborted: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestAbortedState<TMeta>;
14
14
  forceIdle: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestIdleState<TMeta>;
15
15
  forcePending: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestPendingState<TMeta>;
16
16
  forceFulfilled: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestFulfilledState<TMeta>;
17
- forceRejected: <TError extends Error = Error, TMeta extends RequestStateMeta = RequestStateMeta>(error?: null | TError, meta?: null | TMeta) => RequestRejectedState<TError, TMeta>;
17
+ forceRejected: <TMeta extends RequestStateMeta = RequestStateMeta, TError extends unknown = unknown>(error?: null | TError, meta?: null | TMeta) => RequestRejectedState<TMeta, TError>;
18
18
  forceAborted: <TMeta extends RequestStateMeta = RequestStateMeta>(meta?: null | TMeta) => RequestAbortedState<TMeta>;
19
19
  };
@@ -1,5 +1,5 @@
1
- import type { InstanceKey } from './index.tsx';
2
- import type { Payload } from './index.tsx';
1
+ import type { InstanceKey } from './InstanceKey.tsx';
2
+ import type { Payload } from './Payload.tsx';
3
3
  export type Dispatcher<TPayload extends void | Payload = void | Payload> = {
4
4
  (payload: TPayload): void;
5
5
  (instanceKey: InstanceKey, payload: TPayload): void;
@@ -1,5 +1,5 @@
1
- import type { Payload } from './index.tsx';
2
- import type { ResetInstance } from './index.tsx';
1
+ import type { Payload } from './Payload.tsx';
2
+ import type { ResetInstance } from './ResetInstance.tsx';
3
3
  export type InitInstance<TInitPayload extends void | Payload = void | Payload, TResetPayload extends void | Payload = void | Payload> = {
4
4
  (payload: TInitPayload): ResetInstance<TResetPayload>;
5
5
  };
@@ -1,3 +1,3 @@
1
- import type { ReducerMap } from './index.tsx';
2
- import type { ReducerPayload } from './index.tsx';
1
+ import type { ReducerMap } from './ReducerMap.tsx';
2
+ import type { ReducerPayload } from './ReducerPayload.tsx';
3
3
  export type InitPayload<TReducerMap extends ReducerMap<any> = ReducerMap<any>> = ReducerPayload<TReducerMap[`$$init`]>;
@@ -1 +1 @@
1
- export type InstanceKey = number | string | symbol;
1
+ export type InstanceKey = string | symbol;
@@ -0,0 +1,7 @@
1
+ import type { InstanceKey } from '../InstanceKey.tsx';
2
+ import type { Payload } from '../Payload.tsx';
3
+ import type { Reducer } from '../Reducer.tsx';
4
+ import type { StoreState } from '../StoreState.tsx';
5
+ export type Dispatch<TStoreState extends StoreState = StoreState> = {
6
+ <TPayload extends void | Payload = void | Payload>(instanceKey: InstanceKey, payload: TPayload, reducer: Reducer<TStoreState, TPayload>): void;
7
+ };
@@ -0,0 +1,5 @@
1
+ import type { InstanceKey } from '../InstanceKey.tsx';
2
+ import type { StoreState } from '../StoreState.tsx';
3
+ export type GetState<TStoreState extends StoreState = StoreState> = {
4
+ (instanceKey: InstanceKey): TStoreState;
5
+ };
@@ -0,0 +1,5 @@
1
+ import type { InstanceKey } from '../InstanceKey.tsx';
2
+ import type { StoreState } from '../StoreState.tsx';
3
+ export type GetStateAll<TStoreState extends StoreState = StoreState> = {
4
+ (): Record<InstanceKey, TStoreState>;
5
+ };
@@ -0,0 +1,8 @@
1
+ import type { InstanceKey } from '../InstanceKey.tsx';
2
+ import type { Payload } from '../Payload.tsx';
3
+ import type { Reducer } from '../Reducer.tsx';
4
+ import type { ResetInstance } from './ResetInstance.tsx';
5
+ import type { StoreState } from '../StoreState.tsx';
6
+ export type InitInstance<TStoreState extends StoreState = StoreState, TInitPayload extends void | Payload = void | Payload, TResetPayload extends void | Payload = void | Payload> = {
7
+ (instanceKey: InstanceKey, initialState: TStoreState, initPayload: TInitPayload, initReducer: Reducer<TStoreState, TInitPayload>): ResetInstance<TStoreState, TResetPayload>;
8
+ };
@@ -0,0 +1,7 @@
1
+ import type { InstanceKey } from '../InstanceKey.tsx';
2
+ import type { Payload } from '../Payload.tsx';
3
+ import type { Reducer } from '../Reducer.tsx';
4
+ import type { StoreState } from '../StoreState.tsx';
5
+ export type Listener<TStoreState extends StoreState = StoreState> = {
6
+ <TPayload extends void | Payload = void | Payload, TReducer extends Reducer<TStoreState, TPayload> = Reducer<TStoreState, TPayload>>(instanceKey: InstanceKey, payload: TPayload, reducer: TReducer): void;
7
+ };
@@ -0,0 +1,7 @@
1
+ import type { InstanceKey } from '../InstanceKey.tsx';
2
+ import type { Payload } from '../Payload.tsx';
3
+ import type { Reducer } from '../Reducer.tsx';
4
+ import type { StoreState } from '../StoreState.tsx';
5
+ export type ListenerAll<TStoreState extends StoreState = StoreState> = {
6
+ <TPayload extends void | Payload = void | Payload, TReducer extends Reducer<TStoreState, TPayload> = Reducer<TStoreState, TPayload>>(instanceKey: InstanceKey, payload: TPayload, reducer: TReducer): void;
7
+ };
@@ -0,0 +1,6 @@
1
+ import type { Payload } from '../Payload.tsx';
2
+ import type { Reducer } from '../Reducer.tsx';
3
+ import type { StoreState } from '../StoreState.tsx';
4
+ export type ResetInstance<TStoreState extends StoreState = StoreState, TResetPayload extends void | Payload = void | Payload> = {
5
+ (resetPayload: TResetPayload, resetReducer: Reducer<TStoreState, TResetPayload>): void;
6
+ };
@@ -0,0 +1,7 @@
1
+ import type { InstanceKey } from '../InstanceKey.tsx';
2
+ import type { Listener } from './Listener.tsx';
3
+ import type { StoreState } from '../StoreState.tsx';
4
+ import type { Unsubscribe } from './Unsubscribe.tsx';
5
+ export type Subscribe<TStoreState extends StoreState = StoreState> = {
6
+ (instanceKey: InstanceKey, listener: Listener<TStoreState>): Unsubscribe;
7
+ };
@@ -0,0 +1,6 @@
1
+ import type { ListenerAll } from './ListenerAll.tsx';
2
+ import type { StoreState } from '../StoreState.tsx';
3
+ import type { UnsubscribeAll } from './UnsubscribeAll.tsx';
4
+ export type SubscribeAll<TStoreState extends StoreState = StoreState> = {
5
+ (listener: ListenerAll<TStoreState>): UnsubscribeAll;
6
+ };
@@ -0,0 +1,3 @@
1
+ export type Unsubscribe = {
2
+ (): void;
3
+ };
@@ -0,0 +1,3 @@
1
+ export type UnsubscribeAll = {
2
+ (): void;
3
+ };
@@ -1,10 +1,10 @@
1
1
  import React from 'react';
2
- import type { InstanceKey } from './index.tsx';
3
- import type { ReducerMap } from './index.tsx';
4
- import type { StoreState } from './index.tsx';
2
+ import type { InstanceKey } from './InstanceKey.tsx';
3
+ import type { ReducerMap } from './ReducerMap.tsx';
4
+ import type { StoreState } from './StoreState.tsx';
5
5
  export type InternalStoreProps<TStoreName extends string = string, TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>> = {
6
- [`$$init`]: TReducerMap[`$$init`];
7
- [`$$reset`]: TReducerMap[`$$reset`];
6
+ $$init: TReducerMap[`$$init`];
7
+ $$reset: TReducerMap[`$$reset`];
8
8
  context: React.Context<null | InstanceKey>;
9
9
  initialState: TStoreState;
10
10
  name: TStoreName;
@@ -1,5 +1,5 @@
1
- import type { Payload } from './index.tsx';
2
- import type { StoreState } from './index.tsx';
1
+ import type { Payload } from './Payload.tsx';
2
+ import type { StoreState } from './StoreState.tsx';
3
3
  export type Reducer<TStoreState extends StoreState = StoreState, TPayload extends void | Payload = void | Payload> = {
4
4
  (state: TStoreState, payload: TPayload): TStoreState;
5
5
  };
@@ -1,10 +1,10 @@
1
1
  import { INTERNAL_STORE_PROPS_ACCESSOR } from '../constants.tsx';
2
2
  import { REDUCER_LINK } from '../constants.tsx';
3
- import type { InternalStoreProps } from './index.tsx';
4
- import type { Reducer } from './index.tsx';
5
- import type { ReducerMap } from './index.tsx';
6
- import type { ReducerPayload } from './index.tsx';
7
- import type { StoreState } from './index.tsx';
3
+ import type { InternalStoreProps } from './InternalStoreProps.tsx';
4
+ import type { Reducer } from './Reducer.tsx';
5
+ import type { ReducerMap } from './ReducerMap.tsx';
6
+ import type { ReducerPayload } from './ReducerPayload.tsx';
7
+ import type { StoreState } from './StoreState.tsx';
8
8
  export type ReducerLink<TStoreName extends string = string, TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>, TReducerName extends string = string> = {
9
9
  [INTERNAL_STORE_PROPS_ACCESSOR]: InternalStoreProps<TStoreName, TStoreState, TReducerMap>;
10
10
  reducer: Reducer<TStoreState, ReducerPayload<TReducerMap[TReducerName]>>;
@@ -1,6 +1,6 @@
1
- import type { Reducer } from './index.tsx';
2
- import type { StoreState } from './index.tsx';
1
+ import type { Reducer } from './Reducer.tsx';
2
+ import type { StoreState } from './StoreState.tsx';
3
3
  export type ReducerMap<TStoreState extends StoreState = StoreState> = Record<string, Reducer<TStoreState, void | any>> & {
4
- [`$$init`]: Reducer<TStoreState, void | any>;
5
- [`$$reset`]: Reducer<TStoreState, void | any>;
4
+ $$init: Reducer<TStoreState, void | any>;
5
+ $$reset: Reducer<TStoreState, void | any>;
6
6
  };
@@ -1,3 +1,3 @@
1
- import type { Payload } from './index.tsx';
2
- import type { Reducer } from './index.tsx';
1
+ import type { Payload } from './Payload.tsx';
2
+ import type { Reducer } from './Reducer.tsx';
3
3
  export type ReducerPayload<TReducer extends Reducer<any, any> = Reducer<any, any>> = Parameters<TReducer>[1] extends Payload ? Parameters<TReducer>[1] : void;
@@ -1,6 +1,6 @@
1
1
  import { STORE_INSTANCE_UNREGISTERED } from '../constants.tsx';
2
- import type { InitInstance } from './index.tsx';
3
- import type { Payload } from './index.tsx';
2
+ import type { InitInstance } from './InitInstance.tsx';
3
+ import type { Payload } from './Payload.tsx';
4
4
  export type RegisterDefaultInstance<TInitPayload extends void | Payload = void | Payload, TResetPayload extends void | Payload = void | Payload> = {
5
5
  (initInstance: InitInstance<TInitPayload, TResetPayload>, instanceKey: void): () => typeof STORE_INSTANCE_UNREGISTERED;
6
6
  };
@@ -1,7 +1,7 @@
1
1
  import { STORE_INSTANCE_UNREGISTERED } from '../constants.tsx';
2
- import type { InitInstance } from './index.tsx';
3
- import type { InstanceKey } from './index.tsx';
4
- import type { Payload } from './index.tsx';
2
+ import type { InitInstance } from './InitInstance.tsx';
3
+ import type { InstanceKey } from './InstanceKey.tsx';
4
+ import type { Payload } from './Payload.tsx';
5
5
  export type RegisterInstance<TInitPayload extends void | Payload = void | Payload, TResetPayload extends void | Payload = void | Payload> = {
6
6
  (initInstance: InitInstance<TInitPayload, TResetPayload>, instanceKey: InstanceKey): () => typeof STORE_INSTANCE_UNREGISTERED;
7
7
  };
@@ -1,6 +1,6 @@
1
1
  import type { requestStatus } from '../../requestStatus.tsx';
2
2
  import type { RequestStateMeta } from '../RequestStateMeta.tsx';
3
- export type RequestRejectedState<TResponseError extends Error = Error, TMeta extends RequestStateMeta = RequestStateMeta> = {
3
+ export type RequestRejectedState<TMeta extends RequestStateMeta = RequestStateMeta, TResponseError extends unknown = unknown> = {
4
4
  isIdle: false;
5
5
  isPending: false;
6
6
  isFulfilled: false;
@@ -4,4 +4,4 @@ import type { RequestIdleState } from './RequestState/RequestIdleState.tsx';
4
4
  import type { RequestPendingState } from './RequestState/RequestPendingState.tsx';
5
5
  import type { RequestRejectedState } from './RequestState/RequestRejectedState.tsx';
6
6
  import type { RequestStateMeta } from './RequestStateMeta.tsx';
7
- export type RequestState<TError extends Error = Error, TMeta extends RequestStateMeta = RequestStateMeta> = RequestIdleState<TMeta> | RequestPendingState<TMeta> | RequestFulfilledState<TMeta> | RequestRejectedState<TError, TMeta> | RequestAbortedState<TMeta>;
7
+ export type RequestState<TMeta extends RequestStateMeta = RequestStateMeta, TError extends unknown = unknown> = RequestIdleState<TMeta> | RequestPendingState<TMeta> | RequestFulfilledState<TMeta> | RequestRejectedState<TMeta, TError> | RequestAbortedState<TMeta>;
@@ -1,5 +1,5 @@
1
1
  import { STORE_INSTANCE_UNREGISTERED } from '../constants.tsx';
2
- import type { Payload } from './index.tsx';
2
+ import type { Payload } from './Payload.tsx';
3
3
  export type ResetInstance<TPayload extends void | Payload = void | Payload> = {
4
4
  (payload: TPayload): typeof STORE_INSTANCE_UNREGISTERED;
5
5
  };
@@ -1,3 +1,3 @@
1
- import type { ReducerMap } from './index.tsx';
2
- import type { ReducerPayload } from './index.tsx';
1
+ import type { ReducerMap } from './ReducerMap.tsx';
2
+ import type { ReducerPayload } from './ReducerPayload.tsx';
3
3
  export type ResetPayload<TReducerMap extends ReducerMap<any> = ReducerMap<any>> = ReducerPayload<TReducerMap[`$$reset`]>;
@@ -1,8 +1,8 @@
1
1
  import { INTERNAL_STORE_PROPS_ACCESSOR } from '../constants.tsx';
2
2
  import { STATE_LINK } from '../constants.tsx';
3
- import type { InternalStoreProps } from './index.tsx';
4
- import type { ReducerMap } from './index.tsx';
5
- import type { StoreState } from './index.tsx';
3
+ import type { InternalStoreProps } from './InternalStoreProps.tsx';
4
+ import type { ReducerMap } from './ReducerMap.tsx';
5
+ import type { StoreState } from './StoreState.tsx';
6
6
  export type StateLink<TStoreName extends string = string, TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>, TStateName extends keyof TStoreState = keyof TStoreState> = {
7
7
  [INTERNAL_STORE_PROPS_ACCESSOR]: InternalStoreProps<TStoreName, TStoreState, TReducerMap>;
8
8
  stateName: TStateName;
@@ -1,14 +1,13 @@
1
1
  import { INTERNAL_STORE_PROPS_ACCESSOR } from '../constants.tsx';
2
- import type { InternalStoreProps } from './index.tsx';
3
- import type { ReducerMap } from './index.tsx';
4
- import type { ReducerLink } from './index.tsx';
5
- import type { StateLink } from './index.tsx';
6
- import type { StoreState } from './index.tsx';
2
+ import type { InternalStoreProps } from './InternalStoreProps.tsx';
3
+ import type { ReducerMap } from './ReducerMap.tsx';
4
+ import type { ReducerLink } from './ReducerLink.tsx';
5
+ import type { StateLink } from './StateLink.tsx';
6
+ import type { StoreState } from './StoreState.tsx';
7
7
  export type Store<TStoreName extends string = string, TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>> = {
8
8
  [INTERNAL_STORE_PROPS_ACCESSOR]: InternalStoreProps<TStoreName, TStoreState, TReducerMap>;
9
- } & {
10
- [`$$init`]: void;
11
- [`$$reset`]: void;
9
+ $$init: void;
10
+ $$reset: void;
12
11
  } & {
13
12
  [TKey in keyof TStoreState]: TKey extends string ? StateLink<TStoreName, TStoreState, TReducerMap, TKey> : never;
14
13
  } & {
@@ -1,9 +1,10 @@
1
1
  import { InternalStore } from '../InternalStore.tsx';
2
- import type { InstanceKey } from './index.tsx';
3
- import type { ReducerMap } from './index.tsx';
4
- import type { StoreControllerInstance } from './index.tsx';
5
- import type { StoreState } from './index.tsx';
2
+ import type { InstanceKey } from './InstanceKey.tsx';
3
+ import type { ReducerMap } from './ReducerMap.tsx';
4
+ import type { StoreInstanceController } from './StoreInstanceController.tsx';
5
+ import type { StoreState } from './StoreState.tsx';
6
6
  export type StoreController<TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>> = {
7
7
  internalStore: InternalStore<TStoreState, TReducerMap>;
8
- instances: Record<InstanceKey, StoreControllerInstance<TStoreState, Parameters<TReducerMap[`$$reset`]>[1]>>;
8
+ instances: Record<InstanceKey, StoreInstanceController<TStoreState, Parameters<TReducerMap[`$$reset`]>[1]>>;
9
+ earlySubscribers: Record<InstanceKey, (() => void)[]>;
9
10
  };
@@ -0,0 +1,7 @@
1
+ import type { StoreState } from './StoreState.tsx';
2
+ import type { Payload } from './Payload.tsx';
3
+ import type { Reducer } from './Reducer.tsx';
4
+ export type StoreInstanceController<TStoreState extends StoreState = StoreState, TResetPayload extends void | Payload = void | Payload> = {
5
+ owners: symbol[];
6
+ resetState: (resetPayload: TResetPayload, resetReducer: Reducer<TStoreState, TResetPayload>) => void;
7
+ };
@@ -1,2 +1,2 @@
1
- import type { StoreController } from './index.tsx';
1
+ import type { StoreController } from './StoreController.tsx';
2
2
  export type StoreRegistry = Record<symbol, StoreController>;
@@ -1,7 +1,7 @@
1
- import type { InstanceKey } from './index.tsx';
2
- import type { ReducerMap } from './index.tsx';
3
- import type { StateLink } from './index.tsx';
4
- import type { StoreState } from './index.tsx';
1
+ import type { InstanceKey } from './InstanceKey.tsx';
2
+ import type { ReducerMap } from './ReducerMap.tsx';
3
+ import type { StateLink } from './StateLink.tsx';
4
+ import type { StoreState } from './StoreState.tsx';
5
5
  export type UseProp = {
6
6
  <TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>, TStateName extends keyof TStoreState = keyof TStoreState>(stateLink: StateLink<string, TStoreState, TReducerMap, TStateName>, instanceKey?: InstanceKey): TStoreState[TStateName];
7
7
  };
@@ -1,7 +1,7 @@
1
- import type { InstanceKey } from './index.tsx';
2
- import type { ReducerMap } from './index.tsx';
3
- import type { StateLink } from './index.tsx';
4
- import type { StoreState } from './index.tsx';
1
+ import type { InstanceKey } from './InstanceKey.tsx';
2
+ import type { ReducerMap } from './ReducerMap.tsx';
3
+ import type { StateLink } from './StateLink.tsx';
4
+ import type { StoreState } from './StoreState.tsx';
5
5
  export type UsePropAll = {
6
6
  <TStoreState extends StoreState = StoreState, TReducerMap extends ReducerMap<TStoreState> = ReducerMap<TStoreState>, TStateName extends keyof TStoreState = keyof TStoreState>(stateLink: StateLink<string, TStoreState, TReducerMap, TStateName>, instanceKeys?: InstanceKey[] | ((state: TStoreState) => boolean)): [instanceKey: InstanceKey, state: TStoreState[TStateName]][];
7
7
  };
@@ -49,40 +49,105 @@ function createUseLatest(storeRegistry) {
49
49
  };
50
50
  }
51
51
 
52
+ class InternalStore {
53
+ constructor(name) {
54
+ this.getState = (instanceKey) => {
55
+ return this.state[instanceKey];
56
+ };
57
+ this.getStateAll = () => {
58
+ return this.state;
59
+ };
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
+ // TODO Тут место для уничтожения состояния экземпляра хранилища через `delete this.state[instanceKey];`
69
+ };
70
+ };
71
+ this.subscribe = (instanceKey, listener) => {
72
+ this.listeners[instanceKey].add(listener);
73
+ return () => {
74
+ this.listeners[instanceKey].delete(listener);
75
+ if (this.listeners[instanceKey].size === 0) {
76
+ delete this.listeners[instanceKey];
77
+ }
78
+ };
79
+ };
80
+ this.subscribeAll = (listener) => {
81
+ this.listenersAll.add(listener);
82
+ return () => {
83
+ this.listenersAll.delete(listener);
84
+ };
85
+ };
86
+ this.dispatch = (instanceKey, payload, reducer) => {
87
+ const instanceState = this.state[instanceKey];
88
+ const instanceNextState = reducer(instanceState, payload);
89
+ this.state = { ...this.state, [instanceKey]: instanceNextState };
90
+ this.listeners[instanceKey].forEach((listener) => listener(instanceKey, payload, reducer));
91
+ this.listenersAll.forEach((listener) => listener(instanceKey, payload, reducer));
92
+ // TODO Убрать в логгер
93
+ console.log(`dispatch [store: ${this.name}, instanceKey: ${String(instanceKey)}, action: ${reducer.name}]:`);
94
+ // TODO Убрать в логгер
95
+ console.log({ payload, [`prev state`]: instanceState, [`next state`]: instanceNextState });
96
+ };
97
+ this.listeners = {};
98
+ this.listenersAll = new Set();
99
+ this.name = name;
100
+ this.state = {};
101
+ }
102
+ }
103
+
104
+ function createStoreController(storeRegistry, internalStoreProps) {
105
+ let storeController = storeRegistry[internalStoreProps.uniqKey];
106
+ if (!storeController) {
107
+ const internalStore = new InternalStore(internalStoreProps.name);
108
+ storeController = { earlySubscribers: {}, instances: {}, internalStore };
109
+ storeRegistry[internalStoreProps.uniqKey] = storeController;
110
+ }
111
+ return storeController;
112
+ }
113
+
52
114
  function createUseProp(storeRegistry) {
53
115
  return function useProp(stateLink, instanceKey) {
54
116
  const internalStoreProps = stateLink[INTERNAL_STORE_PROPS_ACCESSOR];
55
117
  const contextInstanceKey = React.useContext(internalStoreProps.context);
56
118
  const actualInstanceKey = instanceKey ?? contextInstanceKey ?? DEFAULT_INSTANCE_KEY;
57
119
  const [, setUninitializedHack] = React.useState(0);
58
- const initialized = internalStoreProps.uniqKey in storeRegistry && storeRegistry[internalStoreProps.uniqKey].instances[actualInstanceKey];
120
+ const earlySubscriberRef = React.useRef({ earlySubscriber: null });
121
+ const storeController = createStoreController(storeRegistry, internalStoreProps);
122
+ const initialized = actualInstanceKey in storeController.instances;
59
123
  const { getSnapshot, subscribe } = React.useMemo(() => {
60
124
  let subscribe;
61
125
  let getSnapshot;
62
126
  if (initialized) {
63
- const internalStore = storeRegistry[internalStoreProps.uniqKey].internalStore;
64
127
  subscribe = (listener) => {
65
- return internalStore.subscribe(actualInstanceKey, listener);
128
+ return storeController.internalStore.subscribe(actualInstanceKey, listener);
66
129
  };
67
130
  getSnapshot = () => {
68
- return internalStore.getState(actualInstanceKey);
131
+ return storeController.internalStore.getState(actualInstanceKey);
69
132
  };
70
133
  }
71
134
  else {
72
135
  subscribe = () => () => undefined;
73
136
  getSnapshot = () => internalStoreProps.initialState;
137
+ if (!storeController.earlySubscribers[actualInstanceKey]) {
138
+ storeController.earlySubscribers[actualInstanceKey] = [];
139
+ }
140
+ else if (earlySubscriberRef.current.earlySubscriber) {
141
+ storeController.earlySubscribers[actualInstanceKey].splice(storeController.earlySubscribers[actualInstanceKey].indexOf(earlySubscriberRef.current.earlySubscriber), 1);
142
+ }
143
+ const earlySubscriber = earlySubscriberRef.current.earlySubscriber = () => setUninitializedHack(state => state + 1);
144
+ storeController.earlySubscribers[actualInstanceKey].push(earlySubscriber);
74
145
  }
75
146
  return { getSnapshot, subscribe };
76
- }, [actualInstanceKey, initialized, internalStoreProps, storeRegistry]);
147
+ }, [actualInstanceKey, initialized, internalStoreProps, storeController]);
77
148
  const selector = React.useCallback((state) => {
78
149
  return state[stateLink.stateName];
79
150
  }, [stateLink]);
80
- React.useEffect(() => {
81
- const initializedAfterEffect = internalStoreProps.uniqKey in storeRegistry && storeRegistry[internalStoreProps.uniqKey].instances[actualInstanceKey];
82
- if (!initialized && initializedAfterEffect) {
83
- setUninitializedHack(state => state + 1);
84
- }
85
- }, [actualInstanceKey, initialized, internalStoreProps, storeRegistry]);
86
151
  return withSelector.useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector);
87
152
  };
88
153
  }
@@ -148,107 +213,65 @@ function isEqual(prevStateAll, stateAll) {
148
213
  }
149
214
  }
150
215
 
151
- class InternalStore {
152
- constructor(name) {
153
- this.getState = (instanceKey) => {
154
- return this.state[instanceKey];
155
- };
156
- this.getStateAll = () => {
157
- return this.state;
158
- };
159
- this.initInstance = (instanceKey, initialState, initPayload, initReducer) => {
160
- const initState = initReducer(initialState, initPayload);
161
- this.state = { ...this.state, [instanceKey]: initState };
162
- // TODO Убрать в логгер
163
- console.log(`initInstance [store: ${this.name}, instance: ${String(instanceKey)}]:`);
164
- console.dir(this.state);
165
- return (resetPayload, resetReducer) => {
166
- const resetState = resetReducer(initState, resetPayload);
167
- // TODO Тут место для уничтожения состояния экземпляра хранилища через `delete this.state[instanceKey];`
168
- this.state = { ...this.state, [instanceKey]: resetState };
169
- // TODO Убрать в логгер
170
- console.log(`resetInstance [store: ${this.name}, instance: ${String(instanceKey)}]:`);
171
- console.dir(this.state);
172
- };
173
- };
174
- this.subscribe = (instanceKey, listener) => {
175
- if (!this.listeners[instanceKey]) {
176
- this.listeners[instanceKey] = new Set();
177
- }
178
- this.listeners[instanceKey].add(listener);
179
- return () => {
180
- this.listeners[instanceKey].delete(listener);
181
- if (this.listeners[instanceKey].size === 0) {
182
- delete this.listeners[instanceKey];
183
- }
184
- };
185
- };
186
- this.subscribeAll = (listener) => {
187
- this.listenersAll.add(listener);
188
- return () => {
189
- this.listenersAll.delete(listener);
190
- };
191
- };
192
- this.dispatch = (instanceKey, payload, reducer) => {
193
- const instanceState = this.state[instanceKey];
194
- const instanceNextState = reducer(instanceState, payload);
195
- this.state = { ...this.state, [instanceKey]: instanceNextState };
196
- this.listeners[instanceKey].forEach((listener) => listener(instanceKey, payload, reducer));
197
- this.listenersAll.forEach((listener) => listener(instanceKey, payload, reducer));
198
- // TODO Убрать в логгер
199
- console.log(`dispatch [store: ${this.name}, instance: ${String(instanceKey)}, action: ${reducer.name}]:`);
200
- console.dir({ payload, [`prev state`]: instanceState, [`next state`]: instanceNextState });
201
- };
202
- this.listeners = {};
203
- this.listenersAll = new Set();
204
- this.name = name;
205
- this.state = {};
206
- }
207
- }
208
-
209
216
  function createUseStore(storeRegistry) {
210
217
  function useStore(store, ...args) {
218
+ const storeRef = React.useRef({ store });
219
+ const storeMismatchWarnedRef = React.useRef({ warned: false });
220
+ if (storeRef.current.store !== store) {
221
+ console.warn(`Store reference mismatch. You must pass the same store instance on every render.`);
222
+ storeMismatchWarnedRef.current.warned = true;
223
+ }
211
224
  let instanceKeys;
212
225
  let registerInstance;
226
+ const internalStoreProps = storeRef.current.store[INTERNAL_STORE_PROPS_ACCESSOR];
227
+ const contextInstanceKey = React.useContext(internalStoreProps.context);
213
228
  if (typeof args[0] === `function`) {
214
- instanceKeys = [];
229
+ instanceKeys = [contextInstanceKey ?? DEFAULT_INSTANCE_KEY];
215
230
  registerInstance = args[0];
216
231
  }
217
232
  else {
218
233
  instanceKeys = args[0];
219
234
  registerInstance = args[1];
220
235
  }
221
- const actualInstanceKeys = instanceKeys.length ? instanceKeys : [DEFAULT_INSTANCE_KEY];
222
- const storeRef = React.useRef({ store });
236
+ // eslint-disable-next-line react-hooks/exhaustive-deps
237
+ const actualInstanceKeys = React.useMemo(() => instanceKeys, instanceKeys);
223
238
  const ownerKeyRef = React.useRef({ ownerKey: Symbol(`ownerKey`) });
224
239
  const initInstancesRef = React.useRef({ initInstances: {} });
225
- React.useMemo(() => {
226
- const initInstances = initInstancesRef.current.initInstances;
227
- const store = storeRef.current.store;
240
+ React.useEffect(() => {
241
+ const { ownerKey } = ownerKeyRef.current;
242
+ const { initInstances } = initInstancesRef.current;
228
243
  for (const instanceKey of actualInstanceKeys) {
229
244
  if (!initInstances[instanceKey]) {
230
- const ownerKey = ownerKeyRef.current.ownerKey;
231
245
  const initInstance = (initPayload) => {
232
- const internalStoreProps = store[INTERNAL_STORE_PROPS_ACCESSOR];
233
- let storeController = storeRegistry[internalStoreProps.uniqKey];
234
- if (!storeController) {
235
- const internalStore = new InternalStore(internalStoreProps.name);
236
- storeController = { internalStore, instances: {} };
237
- storeRegistry[internalStoreProps.uniqKey] = storeController;
238
- // TODO Убрать в логгер
239
- console.log(`registerStore [store: ${storeController.internalStore.name}]:`);
240
- console.dir(storeRegistry);
241
- }
246
+ const storeController = createStoreController(storeRegistry, internalStoreProps);
242
247
  if (!storeController.instances[instanceKey]) {
243
- const resetState = storeController.internalStore.initInstance(instanceKey, internalStoreProps.initialState, initPayload, internalStoreProps[`$$init`]);
248
+ // TODO Убрать в логгер
249
+ console.log(`Store instance initialization [store: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
250
+ // TODO Убрать в логгер
251
+ console.log({ storeRegistry });
252
+ const resetState = storeController.internalStore.initInstance(instanceKey, internalStoreProps.initialState, initPayload, internalStoreProps.$$init);
244
253
  storeController.instances[instanceKey] = { owners: [], resetState };
254
+ if (storeController.earlySubscribers[instanceKey]) {
255
+ for (const subscriber of storeController.earlySubscribers[instanceKey]) {
256
+ subscriber();
257
+ }
258
+ storeController.earlySubscribers[instanceKey].splice(0);
259
+ }
260
+ }
261
+ else {
262
+ // TODO Множественная инициализация хранилища
263
+ // Архитектура позволяет несколько раз инициализировать одно и то же хранилище с
264
+ // одним и тем же ключом, однако возможно от этого стоит отказаться. Возможно
265
+ // стоит просить разработчиков проверять инициализирована ли стора и
266
+ // инициализировать ее при необходимости.
267
+ console.warn(`Duplicate store initialization for key "${instanceKey.toString()}"`);
245
268
  }
246
269
  storeController.instances[instanceKey].owners.push(ownerKey);
247
270
  return (resetPayload) => {
248
271
  storeController.instances[instanceKey].owners.splice(storeController.instances[instanceKey].owners.indexOf(ownerKey), 1);
249
272
  if (storeController.instances[instanceKey].owners.length === 0) {
250
273
  // TODO Надо ли оповещать слушателей если один экземпляр хранилища удалился
251
- storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps[`$$reset`]);
274
+ storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps.$$reset);
252
275
  delete storeController.instances[instanceKey];
253
276
  }
254
277
  delete initInstances[instanceKey];
@@ -269,7 +292,7 @@ function createUseStore(storeRegistry) {
269
292
  }
270
293
  },
271
294
  // eslint-disable-next-line react-hooks/exhaustive-deps
272
- actualInstanceKeys);
295
+ [actualInstanceKeys, internalStoreProps, /*registerInstance*/]);
273
296
  React.useEffect(() => {
274
297
  const initInstances = initInstancesRef.current.initInstances;
275
298
  return () => {
@@ -1,4 +1,4 @@
1
- import React, { useContext, useMemo, useState, useCallback, useEffect, useRef } from 'react';
1
+ import React, { useContext, useMemo, useState, useRef, useCallback, useEffect } from 'react';
2
2
  import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/with-selector';
3
3
  import { jsx } from 'react/jsx-runtime';
4
4
 
@@ -47,40 +47,105 @@ function createUseLatest(storeRegistry) {
47
47
  };
48
48
  }
49
49
 
50
+ class InternalStore {
51
+ constructor(name) {
52
+ this.getState = (instanceKey) => {
53
+ return this.state[instanceKey];
54
+ };
55
+ this.getStateAll = () => {
56
+ return this.state;
57
+ };
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
+ // TODO Тут место для уничтожения состояния экземпляра хранилища через `delete this.state[instanceKey];`
67
+ };
68
+ };
69
+ this.subscribe = (instanceKey, listener) => {
70
+ this.listeners[instanceKey].add(listener);
71
+ return () => {
72
+ this.listeners[instanceKey].delete(listener);
73
+ if (this.listeners[instanceKey].size === 0) {
74
+ delete this.listeners[instanceKey];
75
+ }
76
+ };
77
+ };
78
+ this.subscribeAll = (listener) => {
79
+ this.listenersAll.add(listener);
80
+ return () => {
81
+ this.listenersAll.delete(listener);
82
+ };
83
+ };
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 = {};
96
+ this.listenersAll = new Set();
97
+ this.name = name;
98
+ this.state = {};
99
+ }
100
+ }
101
+
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;
108
+ }
109
+ return storeController;
110
+ }
111
+
50
112
  function createUseProp(storeRegistry) {
51
113
  return function useProp(stateLink, instanceKey) {
52
114
  const internalStoreProps = stateLink[INTERNAL_STORE_PROPS_ACCESSOR];
53
115
  const contextInstanceKey = useContext(internalStoreProps.context);
54
116
  const actualInstanceKey = instanceKey ?? contextInstanceKey ?? DEFAULT_INSTANCE_KEY;
55
117
  const [, setUninitializedHack] = useState(0);
56
- const initialized = internalStoreProps.uniqKey in storeRegistry && storeRegistry[internalStoreProps.uniqKey].instances[actualInstanceKey];
118
+ const earlySubscriberRef = useRef({ earlySubscriber: null });
119
+ const storeController = createStoreController(storeRegistry, internalStoreProps);
120
+ const initialized = actualInstanceKey in storeController.instances;
57
121
  const { getSnapshot, subscribe } = useMemo(() => {
58
122
  let subscribe;
59
123
  let getSnapshot;
60
124
  if (initialized) {
61
- const internalStore = storeRegistry[internalStoreProps.uniqKey].internalStore;
62
125
  subscribe = (listener) => {
63
- return internalStore.subscribe(actualInstanceKey, listener);
126
+ return storeController.internalStore.subscribe(actualInstanceKey, listener);
64
127
  };
65
128
  getSnapshot = () => {
66
- return internalStore.getState(actualInstanceKey);
129
+ return storeController.internalStore.getState(actualInstanceKey);
67
130
  };
68
131
  }
69
132
  else {
70
133
  subscribe = () => () => undefined;
71
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);
72
143
  }
73
144
  return { getSnapshot, subscribe };
74
- }, [actualInstanceKey, initialized, internalStoreProps, storeRegistry]);
145
+ }, [actualInstanceKey, initialized, internalStoreProps, storeController]);
75
146
  const selector = useCallback((state) => {
76
147
  return state[stateLink.stateName];
77
148
  }, [stateLink]);
78
- useEffect(() => {
79
- const initializedAfterEffect = internalStoreProps.uniqKey in storeRegistry && storeRegistry[internalStoreProps.uniqKey].instances[actualInstanceKey];
80
- if (!initialized && initializedAfterEffect) {
81
- setUninitializedHack(state => state + 1);
82
- }
83
- }, [actualInstanceKey, initialized, internalStoreProps, storeRegistry]);
84
149
  return useSyncExternalStoreWithSelector(subscribe, getSnapshot, null, selector);
85
150
  };
86
151
  }
@@ -146,107 +211,65 @@ function isEqual(prevStateAll, stateAll) {
146
211
  }
147
212
  }
148
213
 
149
- class InternalStore {
150
- constructor(name) {
151
- this.getState = (instanceKey) => {
152
- return this.state[instanceKey];
153
- };
154
- this.getStateAll = () => {
155
- return this.state;
156
- };
157
- this.initInstance = (instanceKey, initialState, initPayload, initReducer) => {
158
- const initState = initReducer(initialState, initPayload);
159
- this.state = { ...this.state, [instanceKey]: initState };
160
- // TODO Убрать в логгер
161
- console.log(`initInstance [store: ${this.name}, instance: ${String(instanceKey)}]:`);
162
- console.dir(this.state);
163
- return (resetPayload, resetReducer) => {
164
- const resetState = resetReducer(initState, resetPayload);
165
- // TODO Тут место для уничтожения состояния экземпляра хранилища через `delete this.state[instanceKey];`
166
- this.state = { ...this.state, [instanceKey]: resetState };
167
- // TODO Убрать в логгер
168
- console.log(`resetInstance [store: ${this.name}, instance: ${String(instanceKey)}]:`);
169
- console.dir(this.state);
170
- };
171
- };
172
- this.subscribe = (instanceKey, listener) => {
173
- if (!this.listeners[instanceKey]) {
174
- this.listeners[instanceKey] = new Set();
175
- }
176
- this.listeners[instanceKey].add(listener);
177
- return () => {
178
- this.listeners[instanceKey].delete(listener);
179
- if (this.listeners[instanceKey].size === 0) {
180
- delete this.listeners[instanceKey];
181
- }
182
- };
183
- };
184
- this.subscribeAll = (listener) => {
185
- this.listenersAll.add(listener);
186
- return () => {
187
- this.listenersAll.delete(listener);
188
- };
189
- };
190
- this.dispatch = (instanceKey, payload, reducer) => {
191
- const instanceState = this.state[instanceKey];
192
- const instanceNextState = reducer(instanceState, payload);
193
- this.state = { ...this.state, [instanceKey]: instanceNextState };
194
- this.listeners[instanceKey].forEach((listener) => listener(instanceKey, payload, reducer));
195
- this.listenersAll.forEach((listener) => listener(instanceKey, payload, reducer));
196
- // TODO Убрать в логгер
197
- console.log(`dispatch [store: ${this.name}, instance: ${String(instanceKey)}, action: ${reducer.name}]:`);
198
- console.dir({ payload, [`prev state`]: instanceState, [`next state`]: instanceNextState });
199
- };
200
- this.listeners = {};
201
- this.listenersAll = new Set();
202
- this.name = name;
203
- this.state = {};
204
- }
205
- }
206
-
207
214
  function createUseStore(storeRegistry) {
208
215
  function useStore(store, ...args) {
216
+ const storeRef = useRef({ store });
217
+ const storeMismatchWarnedRef = useRef({ warned: false });
218
+ if (storeRef.current.store !== store) {
219
+ console.warn(`Store reference mismatch. You must pass the same store instance on every render.`);
220
+ storeMismatchWarnedRef.current.warned = true;
221
+ }
209
222
  let instanceKeys;
210
223
  let registerInstance;
224
+ const internalStoreProps = storeRef.current.store[INTERNAL_STORE_PROPS_ACCESSOR];
225
+ const contextInstanceKey = useContext(internalStoreProps.context);
211
226
  if (typeof args[0] === `function`) {
212
- instanceKeys = [];
227
+ instanceKeys = [contextInstanceKey ?? DEFAULT_INSTANCE_KEY];
213
228
  registerInstance = args[0];
214
229
  }
215
230
  else {
216
231
  instanceKeys = args[0];
217
232
  registerInstance = args[1];
218
233
  }
219
- const actualInstanceKeys = instanceKeys.length ? instanceKeys : [DEFAULT_INSTANCE_KEY];
220
- const storeRef = useRef({ store });
234
+ // eslint-disable-next-line react-hooks/exhaustive-deps
235
+ const actualInstanceKeys = useMemo(() => instanceKeys, instanceKeys);
221
236
  const ownerKeyRef = useRef({ ownerKey: Symbol(`ownerKey`) });
222
237
  const initInstancesRef = useRef({ initInstances: {} });
223
- useMemo(() => {
224
- const initInstances = initInstancesRef.current.initInstances;
225
- const store = storeRef.current.store;
238
+ useEffect(() => {
239
+ const { ownerKey } = ownerKeyRef.current;
240
+ const { initInstances } = initInstancesRef.current;
226
241
  for (const instanceKey of actualInstanceKeys) {
227
242
  if (!initInstances[instanceKey]) {
228
- const ownerKey = ownerKeyRef.current.ownerKey;
229
243
  const initInstance = (initPayload) => {
230
- const internalStoreProps = store[INTERNAL_STORE_PROPS_ACCESSOR];
231
- let storeController = storeRegistry[internalStoreProps.uniqKey];
232
- if (!storeController) {
233
- const internalStore = new InternalStore(internalStoreProps.name);
234
- storeController = { internalStore, instances: {} };
235
- storeRegistry[internalStoreProps.uniqKey] = storeController;
236
- // TODO Убрать в логгер
237
- console.log(`registerStore [store: ${storeController.internalStore.name}]:`);
238
- console.dir(storeRegistry);
239
- }
244
+ const storeController = createStoreController(storeRegistry, internalStoreProps);
240
245
  if (!storeController.instances[instanceKey]) {
241
- const resetState = storeController.internalStore.initInstance(instanceKey, internalStoreProps.initialState, initPayload, internalStoreProps[`$$init`]);
246
+ // TODO Убрать в логгер
247
+ console.log(`Store instance initialization [store: ${storeController.internalStore.name}, instanceKey: ${instanceKey.toString()}]`);
248
+ // TODO Убрать в логгер
249
+ console.log({ storeRegistry });
250
+ const resetState = storeController.internalStore.initInstance(instanceKey, internalStoreProps.initialState, initPayload, internalStoreProps.$$init);
242
251
  storeController.instances[instanceKey] = { owners: [], resetState };
252
+ if (storeController.earlySubscribers[instanceKey]) {
253
+ for (const subscriber of storeController.earlySubscribers[instanceKey]) {
254
+ subscriber();
255
+ }
256
+ storeController.earlySubscribers[instanceKey].splice(0);
257
+ }
258
+ }
259
+ else {
260
+ // TODO Множественная инициализация хранилища
261
+ // Архитектура позволяет несколько раз инициализировать одно и то же хранилище с
262
+ // одним и тем же ключом, однако возможно от этого стоит отказаться. Возможно
263
+ // стоит просить разработчиков проверять инициализирована ли стора и
264
+ // инициализировать ее при необходимости.
265
+ console.warn(`Duplicate store initialization for key "${instanceKey.toString()}"`);
243
266
  }
244
267
  storeController.instances[instanceKey].owners.push(ownerKey);
245
268
  return (resetPayload) => {
246
269
  storeController.instances[instanceKey].owners.splice(storeController.instances[instanceKey].owners.indexOf(ownerKey), 1);
247
270
  if (storeController.instances[instanceKey].owners.length === 0) {
248
271
  // TODO Надо ли оповещать слушателей если один экземпляр хранилища удалился
249
- storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps[`$$reset`]);
272
+ storeController.instances[instanceKey].resetState(resetPayload, internalStoreProps.$$reset);
250
273
  delete storeController.instances[instanceKey];
251
274
  }
252
275
  delete initInstances[instanceKey];
@@ -267,7 +290,7 @@ function createUseStore(storeRegistry) {
267
290
  }
268
291
  },
269
292
  // eslint-disable-next-line react-hooks/exhaustive-deps
270
- actualInstanceKeys);
293
+ [actualInstanceKeys, internalStoreProps, /*registerInstance*/]);
271
294
  useEffect(() => {
272
295
  const initInstances = initInstancesRef.current.initInstances;
273
296
  return () => {
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.5"
23
+ "version": "0.1.7"
24
24
  }
@@ -1,7 +0,0 @@
1
- import type { StoreState } from './index.tsx';
2
- import type { Payload } from './index.tsx';
3
- import type { Reducer } from './index.tsx';
4
- export type StoreControllerInstance<TStoreState extends StoreState = StoreState, TResetPayload extends void | Payload = void | Payload> = {
5
- owners: symbol[];
6
- resetState: (resetPayload: TResetPayload, resetReducer: Reducer<TStoreState, TResetPayload>) => void;
7
- };
@@ -1,30 +0,0 @@
1
- export * from './Dispatcher.tsx';
2
- export * from './InitInstance.tsx';
3
- export * from './InstanceKey.tsx';
4
- export * from './InitPayload.tsx';
5
- export * from './InternalStoreProps.tsx';
6
- export * from './Payload.tsx';
7
- export * from './Reducer.tsx';
8
- export * from './ReducerLink.tsx';
9
- export * from './ReducerMap.tsx';
10
- export * from './ReducerPayload.tsx';
11
- export * from './RegisterDefaultInstance.tsx';
12
- export * from './RegisterInstance.tsx';
13
- export * from './RequestState/RequestAbortedState.tsx';
14
- export * from './RequestState/RequestFulfilledState.tsx';
15
- export * from './RequestState/RequestIdleState.tsx';
16
- export * from './RequestState/RequestPendingState.tsx';
17
- export * from './RequestState/RequestRejectedState.tsx';
18
- export * from './RequestState.tsx';
19
- export * from './RequestStateMeta.tsx';
20
- export * from './RequestStateStoreKey.tsx';
21
- export * from './ResetInstance.tsx';
22
- export * from './ResetPayload.tsx';
23
- export * from './StateLink.tsx';
24
- export * from './Store.tsx';
25
- export * from './StoreController.tsx';
26
- export * from './StoreControllerInstance.tsx';
27
- export * from './StoreRegistry.tsx';
28
- export * from './StoreState.tsx';
29
- export * from './UseProp.tsx';
30
- export * from './UsePropAll.tsx';