@blac/react 2.0.0 → 2.0.1
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.
- package/README.md +207 -129
- package/dist/index.cjs +260 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +165 -0
- package/dist/index.d.ts +143 -77
- package/dist/index.js +257 -0
- package/dist/index.js.map +1 -0
- package/package.json +73 -28
- package/dist/index.cjs.js +0 -2
- package/dist/index.cjs.js.map +0 -1
- package/dist/index.es.js +0 -116
- package/dist/index.es.js.map +0 -1
- package/src/externalBlocStore.ts +0 -93
- package/src/index.ts +0 -4
- package/src/useBloc.tsx +0 -261
package/dist/index.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { useEffect, useMemo, useReducer, useRef, useSyncExternalStore } from "react";
|
|
2
|
+
import { ExternalDepsManager, acquire, autoTrackInit, autoTrackSnapshot, autoTrackSubscribe, disableGetterTracking, generateIsolatedKey, isIsolatedClass, isStatelessClass, manualDepsInit, manualDepsSnapshot, manualDepsSubscribe, noTrackInit, noTrackSnapshot, noTrackSubscribe, release } from "@blac/core";
|
|
3
|
+
|
|
4
|
+
//#region src/utils/instance-keys.ts
|
|
5
|
+
/**
|
|
6
|
+
* Instance key generation utilities for React integration
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Generate an instance key for a bloc
|
|
10
|
+
*
|
|
11
|
+
* Logic:
|
|
12
|
+
* - If user provides instanceId, use it (convert number to string)
|
|
13
|
+
* - If isolated, generate or reuse a unique key for this component
|
|
14
|
+
* - Otherwise, return undefined (use default key)
|
|
15
|
+
*
|
|
16
|
+
* @param componentRef - React component reference (persists across remounts)
|
|
17
|
+
* @param isIsolated - Whether the bloc is isolated
|
|
18
|
+
* @param providedId - User-provided instance ID (from options)
|
|
19
|
+
* @returns Instance key string or undefined for default
|
|
20
|
+
*/
|
|
21
|
+
function generateInstanceKey(componentRef, isIsolated, providedId) {
|
|
22
|
+
if (providedId !== void 0) return typeof providedId === "number" ? String(providedId) : providedId;
|
|
23
|
+
if (isIsolated) {
|
|
24
|
+
if (!componentRef.__blocInstanceId) componentRef.__blocInstanceId = generateIsolatedKey();
|
|
25
|
+
return componentRef.__blocInstanceId;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//#endregion
|
|
30
|
+
//#region src/config.ts
|
|
31
|
+
const defaultConfig = { autoTrack: true };
|
|
32
|
+
let globalConfig = { ...defaultConfig };
|
|
33
|
+
/**
|
|
34
|
+
* Configure global defaults for @blac/react hooks.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* import { configureBlacReact } from '@blac/react';
|
|
39
|
+
*
|
|
40
|
+
* // Disable auto-tracking globally
|
|
41
|
+
* configureBlacReact({
|
|
42
|
+
* autoTrack: false
|
|
43
|
+
* });
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @param config - Partial configuration to merge with defaults
|
|
47
|
+
*/
|
|
48
|
+
function configureBlacReact(config) {
|
|
49
|
+
globalConfig = {
|
|
50
|
+
...globalConfig,
|
|
51
|
+
...config
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Get the current global configuration.
|
|
56
|
+
* @internal
|
|
57
|
+
*/
|
|
58
|
+
function getBlacReactConfig() {
|
|
59
|
+
return globalConfig;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Reset configuration to defaults (useful for testing).
|
|
63
|
+
* @internal
|
|
64
|
+
*/
|
|
65
|
+
function resetBlacReactConfig() {
|
|
66
|
+
globalConfig = { ...defaultConfig };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region src/useBloc.ts
|
|
71
|
+
function determineTrackingMode(options) {
|
|
72
|
+
const globalConfig$1 = getBlacReactConfig();
|
|
73
|
+
const autoTrackEnabled = options?.autoTrack !== void 0 ? options.autoTrack : globalConfig$1.autoTrack;
|
|
74
|
+
return {
|
|
75
|
+
useManualDeps: options?.dependencies !== void 0,
|
|
76
|
+
autoTrackEnabled
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* React hook that connects a component to a state container with automatic re-render on state changes.
|
|
81
|
+
*
|
|
82
|
+
* Supports three tracking modes:
|
|
83
|
+
* - **Auto-tracking** (default): Automatically detects accessed state properties via Proxy
|
|
84
|
+
* - **Manual dependencies**: Explicit dependency array like useEffect
|
|
85
|
+
* - **No tracking**: Returns full state without optimization
|
|
86
|
+
*
|
|
87
|
+
* **Note:** This hook does NOT support stateless containers (StatelessCubit, StatelessVertex).
|
|
88
|
+
* Use `useBlocActions()` instead for stateless containers.
|
|
89
|
+
*
|
|
90
|
+
* @template T - The state container constructor type (inferred from BlocClass)
|
|
91
|
+
* @param BlocClass - The state container class to connect to (must not be stateless)
|
|
92
|
+
* @param options - Configuration options for tracking mode and instance management
|
|
93
|
+
* @returns Tuple with [state, bloc instance, ref]
|
|
94
|
+
*
|
|
95
|
+
* @example Basic usage
|
|
96
|
+
* ```ts
|
|
97
|
+
* const [state, myBloc, ref] = useBloc(MyBloc);
|
|
98
|
+
* ```
|
|
99
|
+
*
|
|
100
|
+
* @example With manual dependencies
|
|
101
|
+
* ```ts
|
|
102
|
+
* const [state, myBloc] = useBloc(MyBloc, {
|
|
103
|
+
* dependencies: (state) => [state.count]
|
|
104
|
+
* });
|
|
105
|
+
* ```
|
|
106
|
+
*
|
|
107
|
+
* @example With isolated instance
|
|
108
|
+
* ```ts
|
|
109
|
+
* const [state, myBloc] = useBloc(MyBloc, {
|
|
110
|
+
* instanceId: 'unique-id'
|
|
111
|
+
* });
|
|
112
|
+
* ```
|
|
113
|
+
*/
|
|
114
|
+
function useBloc(BlocClass, options) {
|
|
115
|
+
const componentRef = useRef({});
|
|
116
|
+
const initialPropsRef = useRef(options?.props);
|
|
117
|
+
const isStateless = isStatelessClass(BlocClass);
|
|
118
|
+
const isIsolated = isIsolatedClass(BlocClass);
|
|
119
|
+
const [bloc, subscribe, getSnapshot, instanceKey, adapterState, rawInstance] = useMemo(() => {
|
|
120
|
+
if (isStateless) {
|
|
121
|
+
console.error(`[BlaC] useBloc() does not support stateless containers. "${BlocClass.name}" is a StatelessCubit or StatelessVertex. Use useBlocActions() instead for stateless containers.`);
|
|
122
|
+
const instance$1 = acquire(BlocClass, "default");
|
|
123
|
+
return [
|
|
124
|
+
instance$1,
|
|
125
|
+
() => () => {},
|
|
126
|
+
() => ({}),
|
|
127
|
+
void 0,
|
|
128
|
+
null,
|
|
129
|
+
instance$1
|
|
130
|
+
];
|
|
131
|
+
}
|
|
132
|
+
const instanceKey$1 = generateInstanceKey(componentRef.current, isIsolated, options?.instanceId);
|
|
133
|
+
const instance = acquire(BlocClass, instanceKey$1, { props: initialPropsRef.current });
|
|
134
|
+
if (initialPropsRef.current !== void 0) instance.updateProps(initialPropsRef.current);
|
|
135
|
+
const { useManualDeps, autoTrackEnabled } = determineTrackingMode(options);
|
|
136
|
+
let subscribeFn;
|
|
137
|
+
let getSnapshotFn;
|
|
138
|
+
let adapterState$1;
|
|
139
|
+
if (useManualDeps && options?.dependencies) {
|
|
140
|
+
adapterState$1 = manualDepsInit(instance);
|
|
141
|
+
subscribeFn = manualDepsSubscribe(instance, adapterState$1, { dependencies: options.dependencies });
|
|
142
|
+
getSnapshotFn = manualDepsSnapshot(instance, adapterState$1, { dependencies: options.dependencies });
|
|
143
|
+
} else if (!autoTrackEnabled) {
|
|
144
|
+
adapterState$1 = noTrackInit(instance);
|
|
145
|
+
subscribeFn = noTrackSubscribe(instance);
|
|
146
|
+
getSnapshotFn = noTrackSnapshot(instance);
|
|
147
|
+
} else {
|
|
148
|
+
adapterState$1 = autoTrackInit(instance);
|
|
149
|
+
subscribeFn = autoTrackSubscribe(instance, adapterState$1);
|
|
150
|
+
getSnapshotFn = autoTrackSnapshot(instance, adapterState$1);
|
|
151
|
+
}
|
|
152
|
+
return [
|
|
153
|
+
adapterState$1.proxiedBloc,
|
|
154
|
+
subscribeFn,
|
|
155
|
+
getSnapshotFn,
|
|
156
|
+
instanceKey$1,
|
|
157
|
+
adapterState$1,
|
|
158
|
+
instance
|
|
159
|
+
];
|
|
160
|
+
}, [
|
|
161
|
+
BlocClass,
|
|
162
|
+
isStateless,
|
|
163
|
+
isIsolated,
|
|
164
|
+
options?.instanceId
|
|
165
|
+
]);
|
|
166
|
+
const state = useSyncExternalStore(subscribe, getSnapshot);
|
|
167
|
+
const [, forceUpdate] = useReducer((x) => x + 1, 0);
|
|
168
|
+
const externalDepsManager = useRef(new ExternalDepsManager());
|
|
169
|
+
useEffect(() => {
|
|
170
|
+
if (isStateless) return;
|
|
171
|
+
if (options?.props !== initialPropsRef.current) rawInstance.updateProps(options?.props);
|
|
172
|
+
}, [
|
|
173
|
+
options?.props,
|
|
174
|
+
rawInstance,
|
|
175
|
+
isStateless
|
|
176
|
+
]);
|
|
177
|
+
useEffect(() => {
|
|
178
|
+
if (isStateless || !adapterState) return;
|
|
179
|
+
disableGetterTracking(adapterState, rawInstance);
|
|
180
|
+
externalDepsManager.current.updateSubscriptions(adapterState.getterState, rawInstance, forceUpdate);
|
|
181
|
+
});
|
|
182
|
+
useEffect(() => {
|
|
183
|
+
if (isStateless) return;
|
|
184
|
+
if (options?.onMount) options.onMount(bloc);
|
|
185
|
+
return () => {
|
|
186
|
+
externalDepsManager.current.cleanup();
|
|
187
|
+
if (options?.onUnmount) options.onUnmount(bloc);
|
|
188
|
+
release(BlocClass, instanceKey);
|
|
189
|
+
if (isIsolated && !rawInstance.isDisposed) rawInstance.dispose();
|
|
190
|
+
};
|
|
191
|
+
}, []);
|
|
192
|
+
return [
|
|
193
|
+
state,
|
|
194
|
+
bloc,
|
|
195
|
+
componentRef
|
|
196
|
+
];
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/useBlocActions.ts
|
|
201
|
+
/**
|
|
202
|
+
* React hook that connects to a state container instance without triggering re-renders.
|
|
203
|
+
* Use this when you only need to call actions on the bloc without subscribing to state changes.
|
|
204
|
+
*
|
|
205
|
+
* **This is the recommended hook for stateless containers** (StatelessCubit, StatelessVertex).
|
|
206
|
+
* It also works with regular Cubit/Vertex when you don't need state subscriptions.
|
|
207
|
+
*
|
|
208
|
+
* @template T - The state container constructor type (inferred from BlocClass)
|
|
209
|
+
* @param BlocClass - The state container class to connect to (supports both stateful and stateless)
|
|
210
|
+
* @param options - Configuration options for instance management and lifecycle
|
|
211
|
+
* @returns The state container instance for calling actions
|
|
212
|
+
*
|
|
213
|
+
* @example Basic usage with stateless container
|
|
214
|
+
* ```ts
|
|
215
|
+
* class AnalyticsService extends StatelessCubit {
|
|
216
|
+
* trackEvent(name: string) { ... }
|
|
217
|
+
* }
|
|
218
|
+
*
|
|
219
|
+
* const analytics = useBlocActions(AnalyticsService);
|
|
220
|
+
* analytics.trackEvent('page_view');
|
|
221
|
+
* ```
|
|
222
|
+
*
|
|
223
|
+
* @example With stateful container (no re-renders)
|
|
224
|
+
* ```ts
|
|
225
|
+
* const myBloc = useBlocActions(MyBloc);
|
|
226
|
+
* myBloc.someMethod(); // Won't cause re-renders
|
|
227
|
+
* ```
|
|
228
|
+
*
|
|
229
|
+
* @example With isolated instance
|
|
230
|
+
* ```ts
|
|
231
|
+
* const myBloc = useBlocActions(MyBloc, {
|
|
232
|
+
* instanceId: 'unique-id'
|
|
233
|
+
* });
|
|
234
|
+
* ```
|
|
235
|
+
*/
|
|
236
|
+
function useBlocActions(BlocClass, options) {
|
|
237
|
+
const componentRef = useRef({});
|
|
238
|
+
const initialPropsRef = useRef(options?.props);
|
|
239
|
+
const [bloc, instanceKey] = useMemo(() => {
|
|
240
|
+
const isIsolated = isIsolatedClass(BlocClass);
|
|
241
|
+
const instanceKey$1 = generateInstanceKey(componentRef.current, isIsolated, options?.instanceId);
|
|
242
|
+
return [acquire(BlocClass, instanceKey$1, { props: initialPropsRef.current }), instanceKey$1];
|
|
243
|
+
}, [BlocClass]);
|
|
244
|
+
useEffect(() => {
|
|
245
|
+
if (options?.onMount) options.onMount(bloc);
|
|
246
|
+
return () => {
|
|
247
|
+
if (options?.onUnmount) options.onUnmount(bloc);
|
|
248
|
+
release(BlocClass, instanceKey);
|
|
249
|
+
if (isIsolatedClass(BlocClass) && !bloc.isDisposed) bloc.dispose();
|
|
250
|
+
};
|
|
251
|
+
}, []);
|
|
252
|
+
return bloc;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
//#endregion
|
|
256
|
+
export { configureBlacReact, resetBlacReactConfig, useBloc, useBlocActions };
|
|
257
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["globalConfig","instance","instanceKey","adapterState","instanceKey"],"sources":["../src/utils/instance-keys.ts","../src/config.ts","../src/useBloc.ts","../src/useBlocActions.ts"],"sourcesContent":["/**\n * Instance key generation utilities for React integration\n */\n\nimport { generateIsolatedKey } from '@blac/core';\nimport type { ComponentRef } from '../types';\n\n/**\n * Generate an instance key for a bloc\n *\n * Logic:\n * - If user provides instanceId, use it (convert number to string)\n * - If isolated, generate or reuse a unique key for this component\n * - Otherwise, return undefined (use default key)\n *\n * @param componentRef - React component reference (persists across remounts)\n * @param isIsolated - Whether the bloc is isolated\n * @param providedId - User-provided instance ID (from options)\n * @returns Instance key string or undefined for default\n */\nexport function generateInstanceKey(\n componentRef: ComponentRef,\n isIsolated: boolean,\n providedId?: string | number,\n): string | undefined {\n // User explicitly provided an ID - use it\n if (providedId !== undefined) {\n return typeof providedId === 'number' ? String(providedId) : providedId;\n }\n\n // Isolated bloc - generate unique key per component\n if (isIsolated) {\n if (!componentRef.__blocInstanceId) {\n componentRef.__blocInstanceId = generateIsolatedKey();\n }\n return componentRef.__blocInstanceId;\n }\n\n // Shared bloc - use default key (undefined)\n return undefined;\n}\n","/**\n * Global configuration for @blac/react\n */\n\nexport interface BlacReactConfig {\n /** Enable automatic property tracking via Proxy (default: true) */\n autoTrack: boolean;\n}\n\nconst defaultConfig: BlacReactConfig = {\n autoTrack: true,\n};\n\nlet globalConfig: BlacReactConfig = { ...defaultConfig };\n\n/**\n * Configure global defaults for @blac/react hooks.\n *\n * @example\n * ```ts\n * import { configureBlacReact } from '@blac/react';\n *\n * // Disable auto-tracking globally\n * configureBlacReact({\n * autoTrack: false\n * });\n * ```\n *\n * @param config - Partial configuration to merge with defaults\n */\nexport function configureBlacReact(config: Partial<BlacReactConfig>): void {\n globalConfig = { ...globalConfig, ...config };\n}\n\n/**\n * Get the current global configuration.\n * @internal\n */\nexport function getBlacReactConfig(): BlacReactConfig {\n return globalConfig;\n}\n\n/**\n * Reset configuration to defaults (useful for testing).\n * @internal\n */\nexport function resetBlacReactConfig(): void {\n globalConfig = { ...defaultConfig };\n}\n","import {\n useMemo,\n useSyncExternalStore,\n useEffect,\n useRef,\n useReducer,\n} from 'react';\nimport {\n type ExtractState,\n type AdapterState,\n type IsStatelessContainer,\n ExternalDepsManager,\n autoTrackSubscribe,\n manualDepsSubscribe,\n noTrackSubscribe,\n autoTrackSnapshot,\n manualDepsSnapshot,\n noTrackSnapshot,\n autoTrackInit,\n manualDepsInit,\n noTrackInit,\n disableGetterTracking,\n isIsolatedClass,\n isStatelessClass,\n StateContainerConstructor,\n InstanceState,\n acquire,\n release,\n} from '@blac/core';\nimport type { UseBlocOptions, UseBlocReturn, ComponentRef } from './types';\nimport { generateInstanceKey } from './utils/instance-keys';\nimport { getBlacReactConfig } from './config';\n\ninterface TrackingMode {\n useManualDeps: boolean;\n autoTrackEnabled: boolean;\n}\n\nfunction determineTrackingMode<TBloc extends StateContainerConstructor>(\n options?: UseBlocOptions<TBloc>,\n): TrackingMode {\n const globalConfig = getBlacReactConfig();\n const autoTrackEnabled =\n options?.autoTrack !== undefined\n ? options.autoTrack\n : globalConfig.autoTrack;\n\n return {\n useManualDeps: options?.dependencies !== undefined,\n autoTrackEnabled,\n };\n}\n\n/**\n * Type that produces a TypeScript error when a stateless container is used.\n * Evaluates to `never` for stateless containers, causing a type mismatch.\n */\ntype StatefulContainer<T extends StateContainerConstructor> =\n IsStatelessContainer<T> extends true ? never : T;\n\n/**\n * React hook that connects a component to a state container with automatic re-render on state changes.\n *\n * Supports three tracking modes:\n * - **Auto-tracking** (default): Automatically detects accessed state properties via Proxy\n * - **Manual dependencies**: Explicit dependency array like useEffect\n * - **No tracking**: Returns full state without optimization\n *\n * **Note:** This hook does NOT support stateless containers (StatelessCubit, StatelessVertex).\n * Use `useBlocActions()` instead for stateless containers.\n *\n * @template T - The state container constructor type (inferred from BlocClass)\n * @param BlocClass - The state container class to connect to (must not be stateless)\n * @param options - Configuration options for tracking mode and instance management\n * @returns Tuple with [state, bloc instance, ref]\n *\n * @example Basic usage\n * ```ts\n * const [state, myBloc, ref] = useBloc(MyBloc);\n * ```\n *\n * @example With manual dependencies\n * ```ts\n * const [state, myBloc] = useBloc(MyBloc, {\n * dependencies: (state) => [state.count]\n * });\n * ```\n *\n * @example With isolated instance\n * ```ts\n * const [state, myBloc] = useBloc(MyBloc, {\n * instanceId: 'unique-id'\n * });\n * ```\n */\nexport function useBloc<\n T extends StateContainerConstructor = StateContainerConstructor,\n>(\n BlocClass: StatefulContainer<T>,\n options?: UseBlocOptions<T>,\n): UseBlocReturn<T, ExtractState<T>> {\n type TBloc = InstanceState<T>;\n\n const componentRef = useRef<ComponentRef>({});\n const initialPropsRef = useRef(options?.props);\n const isStateless = isStatelessClass(BlocClass);\n const isIsolated = isIsolatedClass(BlocClass);\n\n const [bloc, subscribe, getSnapshot, instanceKey, adapterState, rawInstance] =\n useMemo<\n readonly [\n TBloc,\n (callback: () => void) => () => void,\n () => ExtractState<T>,\n string | undefined,\n AdapterState<T> | null,\n TBloc,\n ]\n >(() => {\n // Runtime check for stateless containers - log error but don't crash\n if (isStateless) {\n console.error(\n `[BlaC] useBloc() does not support stateless containers. ` +\n `\"${BlocClass.name}\" is a StatelessCubit or StatelessVertex. ` +\n `Use useBlocActions() instead for stateless containers.`,\n );\n const instance = acquire(BlocClass, 'default') as TBloc;\n // Return minimal working functions that won't subscribe to anything\n return [\n instance,\n () => () => {},\n () => ({}) as ExtractState<T>,\n undefined,\n null,\n instance,\n ];\n }\n\n const instanceKey = generateInstanceKey(\n componentRef.current,\n isIsolated,\n options?.instanceId,\n );\n\n const instance = acquire(BlocClass, instanceKey, {\n props: initialPropsRef.current,\n }) as TBloc;\n\n if (initialPropsRef.current !== undefined) {\n instance.updateProps(initialPropsRef.current);\n }\n\n const { useManualDeps, autoTrackEnabled } =\n determineTrackingMode(options);\n\n let subscribeFn: (callback: () => void) => () => void;\n let getSnapshotFn: () => ExtractState<T>;\n let adapterState: AdapterState<T>;\n\n if (useManualDeps && options?.dependencies) {\n adapterState = manualDepsInit(instance);\n subscribeFn = manualDepsSubscribe(instance, adapterState, {\n dependencies: options.dependencies,\n });\n getSnapshotFn = manualDepsSnapshot(instance, adapterState, {\n dependencies: options.dependencies,\n });\n } else if (!autoTrackEnabled) {\n adapterState = noTrackInit(instance);\n subscribeFn = noTrackSubscribe(instance);\n getSnapshotFn = noTrackSnapshot(instance);\n } else {\n adapterState = autoTrackInit(instance);\n subscribeFn = autoTrackSubscribe(instance, adapterState);\n getSnapshotFn = autoTrackSnapshot(instance, adapterState);\n }\n\n return [\n adapterState.proxiedBloc as TBloc,\n subscribeFn,\n getSnapshotFn,\n instanceKey,\n adapterState,\n instance,\n ];\n }, [BlocClass, isStateless, isIsolated, options?.instanceId]);\n\n const state = useSyncExternalStore(subscribe, getSnapshot);\n\n const [, forceUpdate] = useReducer((x: number) => x + 1, 0);\n\n const externalDepsManager = useRef(new ExternalDepsManager());\n\n useEffect(() => {\n if (isStateless) return;\n if (options?.props !== initialPropsRef.current) {\n rawInstance.updateProps(options?.props);\n }\n }, [options?.props, rawInstance, isStateless]);\n\n useEffect(() => {\n if (isStateless || !adapterState) return;\n disableGetterTracking(adapterState, rawInstance);\n externalDepsManager.current.updateSubscriptions(\n adapterState.getterState,\n rawInstance,\n forceUpdate,\n );\n });\n\n useEffect(() => {\n if (isStateless) return;\n\n if (options?.onMount) {\n options.onMount(bloc as InstanceType<T>);\n }\n\n return () => {\n externalDepsManager.current.cleanup();\n\n if (options?.onUnmount) {\n options.onUnmount(bloc as InstanceType<T>);\n }\n\n release(BlocClass, instanceKey);\n\n if (isIsolated && !rawInstance.isDisposed) {\n rawInstance.dispose();\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return [state, bloc, componentRef] as UseBlocReturn<T, ExtractState<T>>;\n}\n","import { useMemo, useEffect, useRef } from 'react';\nimport {\n StateContainerConstructor,\n isIsolatedClass,\n acquire,\n release,\n} from '@blac/core';\nimport type { ComponentRef } from './types';\nimport { generateInstanceKey } from './utils/instance-keys';\n\n/**\n * Configuration options for useBlocActions hook\n * @template TBloc - The state container type\n * @template TProps - Props type passed to the container\n */\nexport interface UseBlocActionsOptions<TBloc, TProps = any> {\n /** Props passed to bloc constructor or updateProps */\n props?: TProps;\n /** Custom instance identifier for shared or isolated instances */\n instanceId?: string | number;\n /** Callback invoked when bloc instance mounts */\n onMount?: (bloc: TBloc) => void;\n /** Callback invoked when bloc instance unmounts */\n onUnmount?: (bloc: TBloc) => void;\n}\n\n/**\n * React hook that connects to a state container instance without triggering re-renders.\n * Use this when you only need to call actions on the bloc without subscribing to state changes.\n *\n * **This is the recommended hook for stateless containers** (StatelessCubit, StatelessVertex).\n * It also works with regular Cubit/Vertex when you don't need state subscriptions.\n *\n * @template T - The state container constructor type (inferred from BlocClass)\n * @param BlocClass - The state container class to connect to (supports both stateful and stateless)\n * @param options - Configuration options for instance management and lifecycle\n * @returns The state container instance for calling actions\n *\n * @example Basic usage with stateless container\n * ```ts\n * class AnalyticsService extends StatelessCubit {\n * trackEvent(name: string) { ... }\n * }\n *\n * const analytics = useBlocActions(AnalyticsService);\n * analytics.trackEvent('page_view');\n * ```\n *\n * @example With stateful container (no re-renders)\n * ```ts\n * const myBloc = useBlocActions(MyBloc);\n * myBloc.someMethod(); // Won't cause re-renders\n * ```\n *\n * @example With isolated instance\n * ```ts\n * const myBloc = useBlocActions(MyBloc, {\n * instanceId: 'unique-id'\n * });\n * ```\n */\nexport function useBlocActions<\n T extends StateContainerConstructor = StateContainerConstructor,\n>(\n BlocClass: T,\n options?: UseBlocActionsOptions<InstanceType<T>>,\n): InstanceType<T> {\n const componentRef = useRef<ComponentRef>({});\n const initialPropsRef = useRef(options?.props);\n\n const [bloc, instanceKey] = useMemo(() => {\n const isIsolated = isIsolatedClass(BlocClass);\n\n const instanceKey = generateInstanceKey(\n componentRef.current,\n isIsolated,\n options?.instanceId,\n );\n\n const instance = acquire(BlocClass, instanceKey, {\n props: initialPropsRef.current,\n });\n\n return [instance, instanceKey] as const;\n }, [BlocClass]);\n\n useEffect(() => {\n if (options?.onMount) {\n options.onMount(bloc);\n }\n\n return () => {\n if (options?.onUnmount) {\n options.onUnmount(bloc);\n }\n\n release(BlocClass, instanceKey);\n\n if (isIsolatedClass(BlocClass) && !bloc.isDisposed) {\n bloc.dispose();\n }\n };\n }, []);\n\n return bloc as InstanceType<T>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,oBACd,cACA,YACA,YACoB;AAEpB,KAAI,eAAe,OACjB,QAAO,OAAO,eAAe,WAAW,OAAO,WAAW,GAAG;AAI/D,KAAI,YAAY;AACd,MAAI,CAAC,aAAa,iBAChB,cAAa,mBAAmB,qBAAqB;AAEvD,SAAO,aAAa;;;;;;AC1BxB,MAAM,gBAAiC,EACrC,WAAW,MACZ;AAED,IAAI,eAAgC,EAAE,GAAG,eAAe;;;;;;;;;;;;;;;;AAiBxD,SAAgB,mBAAmB,QAAwC;AACzE,gBAAe;EAAE,GAAG;EAAc,GAAG;EAAQ;;;;;;AAO/C,SAAgB,qBAAsC;AACpD,QAAO;;;;;;AAOT,SAAgB,uBAA6B;AAC3C,gBAAe,EAAE,GAAG,eAAe;;;;;ACTrC,SAAS,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AgB;AACd,MAAI,SAAS,QACX,SAAQ,QAAQ,KAAK;AAGvB,eAAa;AACX,OAAI,SAAS,UACX,SAAQ,UAAU,KAAK;AAGzB,WAAQ,WAAW,YAAY;AAE/B,OAAI,gBAAgB,UAAU,IAAI,CAAC,KAAK,WACtC,MAAK,SAAS;;IAGjB,EAAE,CAAC;AAEN,QAAO"}
|
package/package.json
CHANGED
|
@@ -1,15 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blac/react",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": "Brendan Mullins <jsnanigans@gmail.com>",
|
|
6
|
-
"
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/jsnanigans/blac.git",
|
|
9
|
+
"directory": "packages/blac-react"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/jsnanigans/blac#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/jsnanigans/blac/issues"
|
|
14
|
+
},
|
|
15
|
+
"main": "./dist/index.cjs",
|
|
16
|
+
"module": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/index.d.cts",
|
|
26
|
+
"default": "./dist/index.cjs"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
10
30
|
"files": [
|
|
11
|
-
"dist",
|
|
12
|
-
"
|
|
31
|
+
"dist/index.js",
|
|
32
|
+
"dist/index.cjs",
|
|
33
|
+
"dist/index.d.ts",
|
|
34
|
+
"dist/index.d.cts",
|
|
35
|
+
"dist/*.map",
|
|
13
36
|
"README.md",
|
|
14
37
|
"LICENSE"
|
|
15
38
|
],
|
|
@@ -17,42 +40,64 @@
|
|
|
17
40
|
"keywords": [
|
|
18
41
|
"react",
|
|
19
42
|
"typescript",
|
|
20
|
-
"rxjs",
|
|
21
43
|
"state-management",
|
|
22
44
|
"reactjs",
|
|
23
45
|
"observer-pattern",
|
|
24
46
|
"bloc",
|
|
25
47
|
"bloc-pattern"
|
|
26
48
|
],
|
|
27
|
-
"dependencies": {},
|
|
28
49
|
"peerDependencies": {
|
|
29
|
-
"react": "^18.0.0",
|
|
30
|
-
"
|
|
50
|
+
"@types/react": "^18.0.0 || ^19.0.0",
|
|
51
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
52
|
+
"@blac/core": "2.0.1"
|
|
53
|
+
},
|
|
54
|
+
"peerDependenciesMeta": {
|
|
55
|
+
"@types/react": {
|
|
56
|
+
"optional": true
|
|
57
|
+
},
|
|
58
|
+
"@types/react-dom": {
|
|
59
|
+
"optional": true
|
|
60
|
+
}
|
|
31
61
|
},
|
|
32
62
|
"devDependencies": {
|
|
33
|
-
"@testing-library/dom": "^10.4.
|
|
34
|
-
"@testing-library/jest-dom": "^6.6.
|
|
63
|
+
"@testing-library/dom": "^10.4.1",
|
|
64
|
+
"@testing-library/jest-dom": "^6.6.4",
|
|
35
65
|
"@testing-library/react": "^16.3.0",
|
|
36
66
|
"@testing-library/user-event": "^14.6.1",
|
|
37
|
-
"@types/react": "^
|
|
38
|
-
"@vitejs/plugin-react": "^4.
|
|
39
|
-
"@vitest/browser": "^3.
|
|
40
|
-
"@vitest/coverage-v8": "^3.
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"
|
|
67
|
+
"@types/react": "^19.1.9",
|
|
68
|
+
"@vitejs/plugin-react": "^4.7.0",
|
|
69
|
+
"@vitest/browser": "^3.2.4",
|
|
70
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
71
|
+
"babel-plugin-react-compiler": "^1.0.0",
|
|
72
|
+
"eslint-plugin-react-compiler": "19.1.0-rc.2",
|
|
73
|
+
"happy-dom": "^18.0.1",
|
|
74
|
+
"jsdom": "^26.1.0",
|
|
75
|
+
"prettier": "^3.6.2",
|
|
76
|
+
"react": "^19.1.1",
|
|
77
|
+
"react-dom": "^19.1.1",
|
|
78
|
+
"tsdown": "^0.15.7",
|
|
79
|
+
"typescript": "^5.9.2",
|
|
80
|
+
"vitest": "3.2.4",
|
|
81
|
+
"@blac/core": "2.0.1"
|
|
49
82
|
},
|
|
50
83
|
"scripts": {
|
|
51
|
-
"
|
|
84
|
+
"dev": "tsdown --watch",
|
|
85
|
+
"build": "pnpm build:js && pnpm build:types && pnpm build:dts",
|
|
86
|
+
"build:js": "tsdown",
|
|
87
|
+
"build:types": "tsc -p tsconfig.build.json",
|
|
88
|
+
"build:dts": "api-extractor run --local && cp dist/index.d.ts dist/index.d.cts && rm -rf dist/.types",
|
|
89
|
+
"clean": "rm -rf dist",
|
|
90
|
+
"format": "prettier --write \".\"",
|
|
91
|
+
"lint": "eslint src --ext .ts,.tsx",
|
|
92
|
+
"lint:fix": "eslint src --ext .ts,.tsx --fix",
|
|
52
93
|
"test": "vitest run --config vitest.config.ts",
|
|
53
94
|
"test:watch": "vitest --watch --config vitest.config.ts",
|
|
95
|
+
"test:memory": "NODE_OPTIONS='--expose-gc' vitest run --config vitest.config.performance.ts",
|
|
96
|
+
"test:performance": "vitest run --config vitest.config.performance.ts",
|
|
97
|
+
"test:compiler": "vitest run --config vitest.config.compiler.ts",
|
|
98
|
+
"test:watch:compiler": "vitest --watch --config vitest.config.compiler.ts",
|
|
99
|
+
"test:both": "pnpm test && echo '\n\n=== Running tests WITH React Compiler ===\n' && pnpm test:compiler",
|
|
54
100
|
"typecheck": "tsc --noEmit",
|
|
55
|
-
"
|
|
56
|
-
"deploy": "pnpm run build && pnpm publish --access public"
|
|
101
|
+
"deploy": "pnpm publish --access public"
|
|
57
102
|
}
|
|
58
103
|
}
|
package/dist/index.cjs.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("@blac/core"),n=require("react"),E=(u,r,i)=>{const o=u;return{subscribe:B=>{const s=o._observer.subscribe({fn:()=>{try{B(o.state)}catch(l){console.error({e:l,resolvedBloc:u,dependencyArray:r})}},dependencyArray:r,id:i});return()=>{s()}},getSnapshot:()=>o.state,getServerSnapshot:()=>o.state}},M=E;function _(u,r){const{dependencySelector:i,id:o,props:B}=r??{},s=n.useMemo(()=>Math.random().toString(36),[]),l=n.useRef(new Set),g=n.useRef(new Set),R=n.useRef(new Set),h=n.useRef(new Set),I={},m=u.isolated?s:o,b=n.useRef(null);n.useMemo(()=>{b.current=S.Blac.getBloc(u,{id:m,props:B,instanceRef:s})},[u,m,s]);const t=b.current;if(!t)throw new Error(`useBloc: could not resolve bloc: ${u.name||u}`);s===t._instanceRef&&(r!=null&&r.props)&&S.Blac.instance.findRegisteredBlocInstance(u,m)===t&&t.props!==r.props&&(t.props=r.props);const p=(e,c)=>{if(i)return i(e,c);if(t.defaultDependencySelector)return t.defaultDependencySelector(e,c);if(typeof e!="object")return[[e]];const a=[];for(const d of l.current)d in e&&a.push(e[d]);const w=[];for(const d of R.current)if(d in t)try{const y=t[d];switch(typeof y){case"function":continue;default:w.push(y);continue}}catch(y){S.Blac.instance.log("useBloc Error",y)}return setTimeout(()=>{g.current=new Set,h.current=new Set}),[a,w]},v=n.useMemo(()=>M(t,p,s),[t,s]),f=n.useSyncExternalStore(v.subscribe,v.getSnapshot,v.getServerSnapshot),x=n.useMemo(()=>{try{if(typeof f=="object")return new Proxy(f,{get(e,c){return g.current.add(c),l.current.add(c),f[c]}})}catch(e){S.Blac.instance.log("useBloc Error",e)}return f},[f]),C=n.useMemo(()=>new Proxy(t,{get(e,c){const a=t[c];return typeof a!="function"&&h.current.add(c),a}}),[t]);return n.useLayoutEffect(()=>{l.current=new Set(g.current),R.current=new Set(h.current)},[I]),n.useEffect(()=>{var c;const e=b.current;if(e)return e._addConsumer(s),(c=r==null?void 0:r.onMount)==null||c.call(r,e),()=>{e._removeConsumer(s)}},[u,s]),[x,C]}exports.externalBlocStore=M;exports.useBloc=_;
|
|
2
|
-
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/externalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BlocBase, BlocConstructor, BlocHookDependencyArrayFn, BlocState } from '@blac/core';\n\n/**\n * Interface defining an external store that can be used to subscribe to and access bloc state.\n * This interface follows the React external store pattern for state management.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n */\nexport interface ExternalStore<\n B extends InstanceType<BlocConstructor<any>>\n> {\n /**\n * Subscribes to changes in the store and returns an unsubscribe function.\n * @param onStoreChange - Callback function that will be called whenever the store changes\n * @returns A function that can be called to unsubscribe from store changes\n */\n subscribe: (onStoreChange: (state: BlocState<B>) => void) => () => void;\n\n /**\n * Gets the current snapshot of the store state.\n * @returns The current state of the store\n */\n getSnapshot: () => BlocState<B>;\n\n /**\n * Gets the server snapshot of the store state.\n * This is optional and defaults to the same value as getSnapshot.\n * @returns The server state of the store\n */\n getServerSnapshot?: () => BlocState<B>;\n}\n\n/**\n * Creates an external store that wraps a Bloc instance, providing a React-compatible interface\n * for subscribing to and accessing bloc state.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n * @param bloc - The Bloc instance to wrap\n * @param dependencyArray - Function that returns an array of dependencies for the subscription\n * @param rid - Unique identifier for the subscription\n * @returns An ExternalStore instance that provides methods to subscribe to and access bloc state\n */\nconst externalBlocStore = <\n B extends InstanceType<BlocConstructor<any>>\n>(\n resolvedBloc: B,\n dependencyArray: BlocHookDependencyArrayFn<BlocState<B>>,\n rid: string,\n): ExternalStore<B> => {\n // TODO: Revisit this type assertion. Ideally, 'resolvedBloc' should conform to a type\n // that guarantees '_observer' and 'state' properties without needing 'as unknown as ...'.\n // This might require adjustments in the core @blac/core types.\n const asBlocBase = resolvedBloc as unknown as BlocBase<BlocState<B>>;\n return {\n subscribe: (listener: (state: BlocState<B>) => void) => {\n // Subscribe to the bloc's observer with the provided listener function\n // This will trigger the callback whenever the bloc's state changes\n const unSub = asBlocBase._observer.subscribe({\n fn: () => {\n try {\n listener(asBlocBase.state);\n } catch (e) {\n // Log any errors that occur during the listener callback\n // This ensures errors in listeners don't break the entire application\n console.error({\n e,\n resolvedBloc,\n dependencyArray,\n });\n }\n },\n // Pass the dependency array to control when the subscription is updated\n dependencyArray,\n // Use the provided id to identify this subscription\n id: rid,\n });\n\n // Return an unsubscribe function that can be called to clean up the subscription\n return () => {\n unSub();\n };\n },\n // Return an immutable snapshot of the current bloc state\n getSnapshot: (): BlocState<B> => asBlocBase.state,\n // Server snapshot mirrors the client snapshot in this implementation\n getServerSnapshot: (): BlocState<B> => asBlocBase.state,\n };\n};\n\nexport default externalBlocStore;\n","/* eslint-disable @typescript-eslint/restrict-template-expressions */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Blac,\n BlocBase,\n BlocBaseAbstract,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport externalBlocStore from './externalBlocStore';\n\n/**\n * Type definition for the return type of the useBloc hook\n * @template B - Bloc constructor type\n */\ntype HookTypes<B extends BlocConstructor<BlocBase<any>>> = [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n];\n\n/**\n * Configuration options for the useBloc hook\n * @template B - Bloc generic type\n * @property {string} [id] - Optional identifier for the Bloc instance\n * @property {BlocHookDependencyArrayFn<B>} [dependencySelector] - Function to select dependencies for re-renders\n * @property {InferPropsFromGeneric<B>} [props] - Props to pass to the Bloc\n * @property {(bloc: B) => void} [onMount] - Callback function invoked when the Bloc is mounted\n */\nexport interface BlocHookOptions<B extends BlocBase<any>> {\n id?: string;\n dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n}\n\n/**\n * Default dependency selector that wraps the entire state in an array\n * @template T - State type\n * @param {T} s - Current state\n * @returns {Array<Array<T>>} Dependency array containing the entire state\n */\n\n/**\n * React hook for integrating with Blac state management\n *\n * This hook connects a React component to a Bloc state container, providing\n * automatic re-rendering when relevant state changes, dependency tracking,\n * and proper lifecycle management.\n *\n * @template B - Bloc constructor type\n * @template O - BlocHookOptions type\n * @param {B} bloc - Bloc constructor class\n * @param {O} [options] - Configuration options for the hook\n * @returns {HookTypes<B>} Tuple containing [state, bloc instance]\n *\n * @example\n * const [state, counterBloc] = useBloc(CounterBloc);\n * // Access state\n * console.log(state.count);\n * // Call bloc methods\n * counterBloc.increment();\n */\nexport default function useBloc<B extends BlocConstructor<BlocBase<any>>>(\n bloc: B,\n options?: BlocHookOptions<InstanceType<B>>,\n): HookTypes<B> {\n const { dependencySelector, id: blocId, props } = options ?? {};\n const rid = useMemo(() => {\n return Math.random().toString(36);\n }, []);\n\n // Track used state keys\n const usedKeys = useRef<Set<string>>(new Set());\n const instanceKeys = useRef<Set<string>>(new Set());\n\n // Track used class properties\n const usedClassPropKeys = useRef<Set<string>>(new Set());\n const instanceClassPropKeys = useRef<Set<string>>(new Set());\n\n const renderInstance = {};\n\n // Determine ID for isolated or shared blocs\n const base = bloc as unknown as BlocBaseAbstract;\n const isIsolated = base.isolated;\n const effectiveBlocId = isIsolated ? rid : blocId;\n\n // Use useRef to hold the bloc instance reference consistently across renders\n const blocRef = useRef<InstanceType<B> | null>(null);\n\n // Initialize or get the bloc instance ONCE using useMemo based on the effective ID\n // This avoids re-running Blac.getBloc on every render.\n useMemo(() => {\n blocRef.current = Blac.getBloc(bloc, {\n id: effectiveBlocId,\n props,\n instanceRef: rid, // Pass component ID for consumer tracking\n });\n }, [bloc, effectiveBlocId, rid]); // Dependencies ensure this runs only when bloc type or ID changes\n\n const resolvedBloc = blocRef.current;\n\n if (!resolvedBloc) {\n // This should ideally not happen if Blac.getBloc works correctly\n throw new Error(`useBloc: could not resolve bloc: ${bloc.name || bloc}`);\n }\n\n // Update props ONLY if this hook instance created the bloc (or is the designated main instance)\n // We rely on Blac.getBloc to handle initial props correctly during creation.\n // Subsequent calls should not overwrite props.\n // Check if this instanceRef matches the one stored on the bloc when it was created/first retrieved.\n if (\n rid === resolvedBloc._instanceRef &&\n options?.props &&\n Blac.instance.findRegisteredBlocInstance(bloc, effectiveBlocId) ===\n resolvedBloc\n ) {\n // Avoid double-setting props if Blac.getBloc already set them during creation\n if (resolvedBloc.props !== options.props) {\n resolvedBloc.props = options.props;\n }\n }\n\n // Configure dependency tracking for re-renders\n const dependencyArray: BlocHookDependencyArrayFn<BlocState<InstanceType<B>>> = (\n newState,\n oldState,\n ): ReturnType<BlocHookDependencyArrayFn<BlocState<InstanceType<B>>>> => {\n // Use custom dependency selector if provided\n if (dependencySelector) {\n return dependencySelector(newState, oldState);\n }\n\n // Fall back to bloc's default dependency selector if available\n if (resolvedBloc.defaultDependencySelector) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return resolvedBloc.defaultDependencySelector(newState, oldState);\n }\n\n // For primitive states, use default selector\n if (typeof newState !== 'object') {\n // Default behavior for primitive states: re-render if the state itself changes.\n return [[newState]];\n }\n\n // For object states, track which properties were actually used\n const usedStateValues: string[] = [];\n for (const key of usedKeys.current) {\n if (key in newState) {\n usedStateValues.push(newState[key as keyof typeof newState]);\n }\n }\n\n // Track used class properties for dependency tracking, this enables rerenders when class getters change\n const usedClassValues: unknown[] = [];\n for (const key of usedClassPropKeys.current) {\n if (key in resolvedBloc) {\n try {\n const value = resolvedBloc[key as keyof InstanceType<B>];\n switch (typeof value) {\n case 'function':\n continue;\n default:\n usedClassValues.push(value);\n continue;\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n }\n }\n\n setTimeout(() => {\n instanceKeys.current = new Set();\n instanceClassPropKeys.current = new Set();\n });\n return [usedStateValues, usedClassValues];\n };\n\n // Set up external store subscription for state updates\n const store = useMemo(\n () => externalBlocStore(resolvedBloc, dependencyArray, rid),\n [resolvedBloc, rid],\n ); // dependencyArray removed as it changes frequently\n\n // Subscribe to state changes using React's external store API\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n store.subscribe,\n store.getSnapshot,\n store.getServerSnapshot,\n );\n\n // Create a proxy for state to track property access\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const returnState: BlocState<InstanceType<B>> = useMemo(() => {\n try {\n if (typeof state === 'object') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return new Proxy(state as any, {\n get(_, prop) {\n instanceKeys.current.add(prop as string);\n usedKeys.current.add(prop as string);\n const value = state[prop as keyof typeof state];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n },\n });\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n return state;\n }, [state]);\n\n // Create a proxy for the bloc instance to track property access\n const returnClass = useMemo(() => {\n return new Proxy(resolvedBloc, {\n get(_, prop) {\n const value = resolvedBloc[prop as keyof InstanceType<B>];\n // Track which class properties are accessed (excluding methods)\n if (typeof value !== 'function') {\n instanceClassPropKeys.current.add(prop as string);\n }\n return value;\n },\n });\n }, [resolvedBloc]);\n\n // Clean up tracked keys after each render\n useLayoutEffect(() => {\n // inherit the keys from the previous render\n usedKeys.current = new Set(instanceKeys.current);\n usedClassPropKeys.current = new Set(instanceClassPropKeys.current);\n }, [renderInstance]);\n\n // Set up bloc lifecycle management\n useEffect(() => {\n const currentBlocInstance = blocRef.current; // Capture instance for cleanup\n if (!currentBlocInstance) return;\n\n currentBlocInstance._addConsumer(rid);\n\n // Call onMount callback if provided\n options?.onMount?.(currentBlocInstance);\n\n // Cleanup: remove this component as a consumer using the captured instance\n return () => {\n currentBlocInstance._removeConsumer(rid);\n };\n }, [bloc, rid]); // Do not add options.onMount to deps, it will cause a loop\n\n return [returnState, returnClass];\n}\n"],"names":["externalBlocStore","resolvedBloc","dependencyArray","rid","asBlocBase","listener","unSub","e","externalBlocStore$1","useBloc","bloc","options","dependencySelector","blocId","props","useMemo","usedKeys","useRef","instanceKeys","usedClassPropKeys","instanceClassPropKeys","renderInstance","effectiveBlocId","blocRef","Blac","newState","oldState","usedStateValues","key","usedClassValues","value","error","store","state","useSyncExternalStore","returnState","_","prop","returnClass","useLayoutEffect","useEffect","currentBlocInstance","_a"],"mappings":"iIA6CMA,EAAoB,CAGxBC,EACAC,EACAC,IACqB,CAIrB,MAAMC,EAAaH,EACZ,MAAA,CACL,UAAYI,GAA4C,CAGhD,MAAAC,EAAQF,EAAW,UAAU,UAAU,CAC3C,GAAI,IAAM,CACJ,GAAA,CACFC,EAASD,EAAW,KAAK,QAClBG,EAAG,CAGV,QAAQ,MAAM,CACZ,EAAAA,EACA,aAAAN,EACA,gBAAAC,CAAA,CACD,CACH,CACF,EAEA,gBAAAA,EAEA,GAAIC,CAAA,CACL,EAGD,MAAO,IAAM,CACLG,GAAA,CAEV,EAEA,YAAa,IAAoBF,EAAW,MAE5C,kBAAmB,IAAoBA,EAAW,KAAA,CAEtD,EAEAI,EAAeR,ECrBS,SAAAS,EACtBC,EACAC,EACc,CACd,KAAM,CAAE,mBAAAC,EAAoB,GAAIC,EAAQ,MAAAC,CAAM,EAAIH,GAAW,GACvDR,EAAMY,EAAAA,QAAQ,IACX,KAAK,OAAA,EAAS,SAAS,EAAE,EAC/B,CAAE,CAAA,EAGCC,EAAWC,EAAAA,OAAwB,IAAA,GAAK,EACxCC,EAAeD,EAAAA,OAAwB,IAAA,GAAK,EAG5CE,EAAoBF,EAAAA,OAAwB,IAAA,GAAK,EACjDG,EAA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C"}
|
package/dist/index.es.js
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
import { Blac as B } from "@blac/core";
|
|
2
|
-
import { useMemo as d, useRef as i, useSyncExternalStore as R, useLayoutEffect as K, useEffect as P } from "react";
|
|
3
|
-
const M = (s, r, y) => {
|
|
4
|
-
const u = s;
|
|
5
|
-
return {
|
|
6
|
-
subscribe: (h) => {
|
|
7
|
-
const c = u._observer.subscribe({
|
|
8
|
-
fn: () => {
|
|
9
|
-
try {
|
|
10
|
-
h(u.state);
|
|
11
|
-
} catch (a) {
|
|
12
|
-
console.error({
|
|
13
|
-
e: a,
|
|
14
|
-
resolvedBloc: s,
|
|
15
|
-
dependencyArray: r
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
},
|
|
19
|
-
// Pass the dependency array to control when the subscription is updated
|
|
20
|
-
dependencyArray: r,
|
|
21
|
-
// Use the provided id to identify this subscription
|
|
22
|
-
id: y
|
|
23
|
-
});
|
|
24
|
-
return () => {
|
|
25
|
-
c();
|
|
26
|
-
};
|
|
27
|
-
},
|
|
28
|
-
// Return an immutable snapshot of the current bloc state
|
|
29
|
-
getSnapshot: () => u.state,
|
|
30
|
-
// Server snapshot mirrors the client snapshot in this implementation
|
|
31
|
-
getServerSnapshot: () => u.state
|
|
32
|
-
};
|
|
33
|
-
}, j = M;
|
|
34
|
-
function L(s, r) {
|
|
35
|
-
const { dependencySelector: y, id: u, props: h } = r ?? {}, c = d(() => Math.random().toString(36), []), a = i(/* @__PURE__ */ new Set()), g = i(/* @__PURE__ */ new Set()), w = i(/* @__PURE__ */ new Set()), m = i(/* @__PURE__ */ new Set()), I = {}, v = s.isolated ? c : u, b = i(null);
|
|
36
|
-
d(() => {
|
|
37
|
-
b.current = B.getBloc(s, {
|
|
38
|
-
id: v,
|
|
39
|
-
props: h,
|
|
40
|
-
instanceRef: c
|
|
41
|
-
// Pass component ID for consumer tracking
|
|
42
|
-
});
|
|
43
|
-
}, [s, v, c]);
|
|
44
|
-
const t = b.current;
|
|
45
|
-
if (!t)
|
|
46
|
-
throw new Error(`useBloc: could not resolve bloc: ${s.name || s}`);
|
|
47
|
-
c === t._instanceRef && (r != null && r.props) && B.instance.findRegisteredBlocInstance(s, v) === t && t.props !== r.props && (t.props = r.props);
|
|
48
|
-
const C = (e, n) => {
|
|
49
|
-
if (y)
|
|
50
|
-
return y(e, n);
|
|
51
|
-
if (t.defaultDependencySelector)
|
|
52
|
-
return t.defaultDependencySelector(e, n);
|
|
53
|
-
if (typeof e != "object")
|
|
54
|
-
return [[e]];
|
|
55
|
-
const o = [];
|
|
56
|
-
for (const l of a.current)
|
|
57
|
-
l in e && o.push(e[l]);
|
|
58
|
-
const x = [];
|
|
59
|
-
for (const l of w.current)
|
|
60
|
-
if (l in t)
|
|
61
|
-
try {
|
|
62
|
-
const S = t[l];
|
|
63
|
-
switch (typeof S) {
|
|
64
|
-
case "function":
|
|
65
|
-
continue;
|
|
66
|
-
default:
|
|
67
|
-
x.push(S);
|
|
68
|
-
continue;
|
|
69
|
-
}
|
|
70
|
-
} catch (S) {
|
|
71
|
-
B.instance.log("useBloc Error", S);
|
|
72
|
-
}
|
|
73
|
-
return setTimeout(() => {
|
|
74
|
-
g.current = /* @__PURE__ */ new Set(), m.current = /* @__PURE__ */ new Set();
|
|
75
|
-
}), [o, x];
|
|
76
|
-
}, p = d(
|
|
77
|
-
() => j(t, C, c),
|
|
78
|
-
[t, c]
|
|
79
|
-
), f = R(
|
|
80
|
-
p.subscribe,
|
|
81
|
-
p.getSnapshot,
|
|
82
|
-
p.getServerSnapshot
|
|
83
|
-
), E = d(() => {
|
|
84
|
-
try {
|
|
85
|
-
if (typeof f == "object")
|
|
86
|
-
return new Proxy(f, {
|
|
87
|
-
get(e, n) {
|
|
88
|
-
return g.current.add(n), a.current.add(n), f[n];
|
|
89
|
-
}
|
|
90
|
-
});
|
|
91
|
-
} catch (e) {
|
|
92
|
-
B.instance.log("useBloc Error", e);
|
|
93
|
-
}
|
|
94
|
-
return f;
|
|
95
|
-
}, [f]), _ = d(() => new Proxy(t, {
|
|
96
|
-
get(e, n) {
|
|
97
|
-
const o = t[n];
|
|
98
|
-
return typeof o != "function" && m.current.add(n), o;
|
|
99
|
-
}
|
|
100
|
-
}), [t]);
|
|
101
|
-
return K(() => {
|
|
102
|
-
a.current = new Set(g.current), w.current = new Set(m.current);
|
|
103
|
-
}, [I]), P(() => {
|
|
104
|
-
var n;
|
|
105
|
-
const e = b.current;
|
|
106
|
-
if (e)
|
|
107
|
-
return e._addConsumer(c), (n = r == null ? void 0 : r.onMount) == null || n.call(r, e), () => {
|
|
108
|
-
e._removeConsumer(c);
|
|
109
|
-
};
|
|
110
|
-
}, [s, c]), [E, _];
|
|
111
|
-
}
|
|
112
|
-
export {
|
|
113
|
-
j as externalBlocStore,
|
|
114
|
-
L as useBloc
|
|
115
|
-
};
|
|
116
|
-
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/externalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BlocBase, BlocConstructor, BlocHookDependencyArrayFn, BlocState } from '@blac/core';\n\n/**\n * Interface defining an external store that can be used to subscribe to and access bloc state.\n * This interface follows the React external store pattern for state management.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n */\nexport interface ExternalStore<\n B extends InstanceType<BlocConstructor<any>>\n> {\n /**\n * Subscribes to changes in the store and returns an unsubscribe function.\n * @param onStoreChange - Callback function that will be called whenever the store changes\n * @returns A function that can be called to unsubscribe from store changes\n */\n subscribe: (onStoreChange: (state: BlocState<B>) => void) => () => void;\n\n /**\n * Gets the current snapshot of the store state.\n * @returns The current state of the store\n */\n getSnapshot: () => BlocState<B>;\n\n /**\n * Gets the server snapshot of the store state.\n * This is optional and defaults to the same value as getSnapshot.\n * @returns The server state of the store\n */\n getServerSnapshot?: () => BlocState<B>;\n}\n\n/**\n * Creates an external store that wraps a Bloc instance, providing a React-compatible interface\n * for subscribing to and accessing bloc state.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n * @param bloc - The Bloc instance to wrap\n * @param dependencyArray - Function that returns an array of dependencies for the subscription\n * @param rid - Unique identifier for the subscription\n * @returns An ExternalStore instance that provides methods to subscribe to and access bloc state\n */\nconst externalBlocStore = <\n B extends InstanceType<BlocConstructor<any>>\n>(\n resolvedBloc: B,\n dependencyArray: BlocHookDependencyArrayFn<BlocState<B>>,\n rid: string,\n): ExternalStore<B> => {\n // TODO: Revisit this type assertion. Ideally, 'resolvedBloc' should conform to a type\n // that guarantees '_observer' and 'state' properties without needing 'as unknown as ...'.\n // This might require adjustments in the core @blac/core types.\n const asBlocBase = resolvedBloc as unknown as BlocBase<BlocState<B>>;\n return {\n subscribe: (listener: (state: BlocState<B>) => void) => {\n // Subscribe to the bloc's observer with the provided listener function\n // This will trigger the callback whenever the bloc's state changes\n const unSub = asBlocBase._observer.subscribe({\n fn: () => {\n try {\n listener(asBlocBase.state);\n } catch (e) {\n // Log any errors that occur during the listener callback\n // This ensures errors in listeners don't break the entire application\n console.error({\n e,\n resolvedBloc,\n dependencyArray,\n });\n }\n },\n // Pass the dependency array to control when the subscription is updated\n dependencyArray,\n // Use the provided id to identify this subscription\n id: rid,\n });\n\n // Return an unsubscribe function that can be called to clean up the subscription\n return () => {\n unSub();\n };\n },\n // Return an immutable snapshot of the current bloc state\n getSnapshot: (): BlocState<B> => asBlocBase.state,\n // Server snapshot mirrors the client snapshot in this implementation\n getServerSnapshot: (): BlocState<B> => asBlocBase.state,\n };\n};\n\nexport default externalBlocStore;\n","/* eslint-disable @typescript-eslint/restrict-template-expressions */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Blac,\n BlocBase,\n BlocBaseAbstract,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport externalBlocStore from './externalBlocStore';\n\n/**\n * Type definition for the return type of the useBloc hook\n * @template B - Bloc constructor type\n */\ntype HookTypes<B extends BlocConstructor<BlocBase<any>>> = [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n];\n\n/**\n * Configuration options for the useBloc hook\n * @template B - Bloc generic type\n * @property {string} [id] - Optional identifier for the Bloc instance\n * @property {BlocHookDependencyArrayFn<B>} [dependencySelector] - Function to select dependencies for re-renders\n * @property {InferPropsFromGeneric<B>} [props] - Props to pass to the Bloc\n * @property {(bloc: B) => void} [onMount] - Callback function invoked when the Bloc is mounted\n */\nexport interface BlocHookOptions<B extends BlocBase<any>> {\n id?: string;\n dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n}\n\n/**\n * Default dependency selector that wraps the entire state in an array\n * @template T - State type\n * @param {T} s - Current state\n * @returns {Array<Array<T>>} Dependency array containing the entire state\n */\n\n/**\n * React hook for integrating with Blac state management\n *\n * This hook connects a React component to a Bloc state container, providing\n * automatic re-rendering when relevant state changes, dependency tracking,\n * and proper lifecycle management.\n *\n * @template B - Bloc constructor type\n * @template O - BlocHookOptions type\n * @param {B} bloc - Bloc constructor class\n * @param {O} [options] - Configuration options for the hook\n * @returns {HookTypes<B>} Tuple containing [state, bloc instance]\n *\n * @example\n * const [state, counterBloc] = useBloc(CounterBloc);\n * // Access state\n * console.log(state.count);\n * // Call bloc methods\n * counterBloc.increment();\n */\nexport default function useBloc<B extends BlocConstructor<BlocBase<any>>>(\n bloc: B,\n options?: BlocHookOptions<InstanceType<B>>,\n): HookTypes<B> {\n const { dependencySelector, id: blocId, props } = options ?? {};\n const rid = useMemo(() => {\n return Math.random().toString(36);\n }, []);\n\n // Track used state keys\n const usedKeys = useRef<Set<string>>(new Set());\n const instanceKeys = useRef<Set<string>>(new Set());\n\n // Track used class properties\n const usedClassPropKeys = useRef<Set<string>>(new Set());\n const instanceClassPropKeys = useRef<Set<string>>(new Set());\n\n const renderInstance = {};\n\n // Determine ID for isolated or shared blocs\n const base = bloc as unknown as BlocBaseAbstract;\n const isIsolated = base.isolated;\n const effectiveBlocId = isIsolated ? rid : blocId;\n\n // Use useRef to hold the bloc instance reference consistently across renders\n const blocRef = useRef<InstanceType<B> | null>(null);\n\n // Initialize or get the bloc instance ONCE using useMemo based on the effective ID\n // This avoids re-running Blac.getBloc on every render.\n useMemo(() => {\n blocRef.current = Blac.getBloc(bloc, {\n id: effectiveBlocId,\n props,\n instanceRef: rid, // Pass component ID for consumer tracking\n });\n }, [bloc, effectiveBlocId, rid]); // Dependencies ensure this runs only when bloc type or ID changes\n\n const resolvedBloc = blocRef.current;\n\n if (!resolvedBloc) {\n // This should ideally not happen if Blac.getBloc works correctly\n throw new Error(`useBloc: could not resolve bloc: ${bloc.name || bloc}`);\n }\n\n // Update props ONLY if this hook instance created the bloc (or is the designated main instance)\n // We rely on Blac.getBloc to handle initial props correctly during creation.\n // Subsequent calls should not overwrite props.\n // Check if this instanceRef matches the one stored on the bloc when it was created/first retrieved.\n if (\n rid === resolvedBloc._instanceRef &&\n options?.props &&\n Blac.instance.findRegisteredBlocInstance(bloc, effectiveBlocId) ===\n resolvedBloc\n ) {\n // Avoid double-setting props if Blac.getBloc already set them during creation\n if (resolvedBloc.props !== options.props) {\n resolvedBloc.props = options.props;\n }\n }\n\n // Configure dependency tracking for re-renders\n const dependencyArray: BlocHookDependencyArrayFn<BlocState<InstanceType<B>>> = (\n newState,\n oldState,\n ): ReturnType<BlocHookDependencyArrayFn<BlocState<InstanceType<B>>>> => {\n // Use custom dependency selector if provided\n if (dependencySelector) {\n return dependencySelector(newState, oldState);\n }\n\n // Fall back to bloc's default dependency selector if available\n if (resolvedBloc.defaultDependencySelector) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return resolvedBloc.defaultDependencySelector(newState, oldState);\n }\n\n // For primitive states, use default selector\n if (typeof newState !== 'object') {\n // Default behavior for primitive states: re-render if the state itself changes.\n return [[newState]];\n }\n\n // For object states, track which properties were actually used\n const usedStateValues: string[] = [];\n for (const key of usedKeys.current) {\n if (key in newState) {\n usedStateValues.push(newState[key as keyof typeof newState]);\n }\n }\n\n // Track used class properties for dependency tracking, this enables rerenders when class getters change\n const usedClassValues: unknown[] = [];\n for (const key of usedClassPropKeys.current) {\n if (key in resolvedBloc) {\n try {\n const value = resolvedBloc[key as keyof InstanceType<B>];\n switch (typeof value) {\n case 'function':\n continue;\n default:\n usedClassValues.push(value);\n continue;\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n }\n }\n\n setTimeout(() => {\n instanceKeys.current = new Set();\n instanceClassPropKeys.current = new Set();\n });\n return [usedStateValues, usedClassValues];\n };\n\n // Set up external store subscription for state updates\n const store = useMemo(\n () => externalBlocStore(resolvedBloc, dependencyArray, rid),\n [resolvedBloc, rid],\n ); // dependencyArray removed as it changes frequently\n\n // Subscribe to state changes using React's external store API\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n store.subscribe,\n store.getSnapshot,\n store.getServerSnapshot,\n );\n\n // Create a proxy for state to track property access\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const returnState: BlocState<InstanceType<B>> = useMemo(() => {\n try {\n if (typeof state === 'object') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return new Proxy(state as any, {\n get(_, prop) {\n instanceKeys.current.add(prop as string);\n usedKeys.current.add(prop as string);\n const value = state[prop as keyof typeof state];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n },\n });\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n return state;\n }, [state]);\n\n // Create a proxy for the bloc instance to track property access\n const returnClass = useMemo(() => {\n return new Proxy(resolvedBloc, {\n get(_, prop) {\n const value = resolvedBloc[prop as keyof InstanceType<B>];\n // Track which class properties are accessed (excluding methods)\n if (typeof value !== 'function') {\n instanceClassPropKeys.current.add(prop as string);\n }\n return value;\n },\n });\n }, [resolvedBloc]);\n\n // Clean up tracked keys after each render\n useLayoutEffect(() => {\n // inherit the keys from the previous render\n usedKeys.current = new Set(instanceKeys.current);\n usedClassPropKeys.current = new Set(instanceClassPropKeys.current);\n }, [renderInstance]);\n\n // Set up bloc lifecycle management\n useEffect(() => {\n const currentBlocInstance = blocRef.current; // Capture instance for cleanup\n if (!currentBlocInstance) return;\n\n currentBlocInstance._addConsumer(rid);\n\n // Call onMount callback if provided\n options?.onMount?.(currentBlocInstance);\n\n // Cleanup: remove this component as a consumer using the captured instance\n return () => {\n currentBlocInstance._removeConsumer(rid);\n };\n }, [bloc, rid]); // Do not add options.onMount to deps, it will cause a loop\n\n return [returnState, returnClass];\n}\n"],"names":["externalBlocStore","resolvedBloc","dependencyArray","rid","asBlocBase","listener","unSub","e","externalBlocStore$1","useBloc","bloc","options","dependencySelector","blocId","props","useMemo","usedKeys","useRef","instanceKeys","usedClassPropKeys","instanceClassPropKeys","renderInstance","effectiveBlocId","blocRef","Blac","newState","oldState","usedStateValues","key","usedClassValues","value","error","store","state","useSyncExternalStore","returnState","_","prop","returnClass","useLayoutEffect","useEffect","currentBlocInstance","_a"],"mappings":";;AA6CA,MAAMA,IAAoB,CAGxBC,GACAC,GACAC,MACqB;AAIrB,QAAMC,IAAaH;AACZ,SAAA;AAAA,IACL,WAAW,CAACI,MAA4C;AAGhD,YAAAC,IAAQF,EAAW,UAAU,UAAU;AAAA,QAC3C,IAAI,MAAM;AACJ,cAAA;AACF,YAAAC,EAASD,EAAW,KAAK;AAAA,mBAClBG,GAAG;AAGV,oBAAQ,MAAM;AAAA,cACZ,GAAAA;AAAA,cACA,cAAAN;AAAA,cACA,iBAAAC;AAAA,YAAA,CACD;AAAA,UACH;AAAA,QACF;AAAA;AAAA,QAEA,iBAAAA;AAAA;AAAA,QAEA,IAAIC;AAAA,MAAA,CACL;AAGD,aAAO,MAAM;AACL,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