@blac/react 2.0.0-rc-7 → 2.0.0-rc-10
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 +63 -14
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +27 -63
- package/dist/index.es.js +88 -157
- package/dist/index.es.js.map +1 -1
- package/package.json +10 -9
- package/src/__tests__/useBloc.tracking.test.tsx +198 -0
- package/src/index.ts +2 -4
- package/src/useBloc.ts +130 -0
- package/src/useExternalBlocStore.ts +116 -191
- package/src/useBloc.tsx +0 -193
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/useExternalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["import { Blac, BlacObserver, BlocBase, BlocBaseAbstract, BlocConstructor, BlocHookDependencyArrayFn, BlocState, generateUUID } from '@blac/core';\nimport { useCallback, useMemo, useRef } from 'react';\nimport { BlocHookOptions } from './useBloc';\n\nexport interface ExternalStore<\n B extends BlocConstructor<BlocBase<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<InstanceType<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<InstanceType<B>> | undefined;\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<InstanceType<B>> | undefined;\n}\n\nexport interface ExternalBlacStore<\n B extends BlocConstructor<BlocBase<any>>\n> {\n usedKeys: React.RefObject<Set<string>>;\n usedClassPropKeys: React.RefObject<Set<string>>;\n externalStore: ExternalStore<B>;\n instance: React.RefObject<InstanceType<B>>;\n rid: string;\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 */\nconst useExternalBlocStore = <\n B extends BlocConstructor<BlocBase<any>>\n>(\n bloc: B,\n options: BlocHookOptions<InstanceType<B>> | undefined,\n): ExternalBlacStore<B> => {\n const { id: blocId, props, selector } = options ?? {};\n\n const rid = useMemo(() => {\n return generateUUID();\n }, []);\n\n const base = bloc as unknown as BlocBaseAbstract;\n\n const isIsolated = base.isolated;\n const effectiveBlocId = isIsolated ? rid : blocId;\n\n const usedKeys = useRef<Set<string>>(new Set());\n const usedClassPropKeys = useRef<Set<string>>(new Set());\n\n const getBloc = useCallback(() => {\n return Blac.getBloc(bloc, {\n id: effectiveBlocId,\n props,\n instanceRef: rid\n });\n }, [bloc, effectiveBlocId, props, rid]);\n\n const blocInstance = useRef<InstanceType<B>>(getBloc());\n\n // Update the instance when dependencies change\n useMemo(() => {\n blocInstance.current = getBloc();\n }, [getBloc]);\n\n const dependencyArray: BlocHookDependencyArrayFn<BlocState<InstanceType<B>>> =\n useMemo(\n () =>\n (newState): ReturnType<BlocHookDependencyArrayFn<BlocState<InstanceType<B>>>> => {\n const instance = blocInstance.current;\n\n if (!instance) {\n return [];\n }\n\n // Use custom dependency selector if provided\n if (selector) {\n return selector(newState);\n }\n\n // Fall back to bloc's default dependency selector if available\n if (instance.defaultDependencySelector) {\n return instance.defaultDependencySelector(newState);\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: unknown[] = [];\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 instance) {\n try {\n const value = instance[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 // If no state properties have been accessed, return empty dependencies to prevent re-renders\n // Class properties can change independently of state\n if (usedKeys.current.size === 0) {\n return usedClassPropKeys.current.size > 0 ? [usedClassValues] : [[]];\n }\n\n return [usedStateValues, usedClassValues];\n },\n [],\n );\n\n const state: ExternalStore<B> = useMemo(() => {\n return {\n subscribe: (listener: (state: BlocState<InstanceType<B>>) => void) => {\n const currentInstance = blocInstance.current;\n if (!currentInstance) {\n return () => {}; // Return no-op if no instance\n }\n\n const observer: BlacObserver<BlocState<InstanceType<B>>> = {\n fn: () => {\n try {\n // Reset dependency tracking before listener is called \n // This ensures we only track properties accessed during the current render\n usedKeys.current = new Set();\n usedClassPropKeys.current = new Set();\n\n // Only trigger listener if there are actual subscriptions\n listener(currentInstance.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 blocInstance: currentInstance,\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 Blac.activateBloc(currentInstance);\n\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 = currentInstance._observer.subscribe(observer);\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<InstanceType<B>> | undefined => {\n const instance = blocInstance.current;\n if (!instance) {\n return {} as BlocState<InstanceType<B>>;\n }\n return instance.state;\n },\n // Server snapshot mirrors the client snapshot in this implementation\n getServerSnapshot: (): BlocState<InstanceType<B>> | undefined => {\n const instance = blocInstance.current;\n if (!instance) {\n return {} as BlocState<InstanceType<B>>;\n }\n return instance.state;\n },\n }\n }, [blocInstance.current?.uid]); // Re-create store when instance changes\n\n return {\n usedKeys,\n usedClassPropKeys,\n externalStore: state,\n instance: blocInstance,\n rid,\n };\n};\n\nexport default useExternalBlocStore;\n","import {\n BlocBase,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport {\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore\n} from 'react';\nimport useExternalBlocStore from './useExternalBlocStore';\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 */\nexport interface BlocHookOptions<B extends BlocBase<any>> {\n id?: string;\n selector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n onUnmount?: (bloc: B) => void;\n}\n\n/**\n * Default dependency selector that wraps the entire state in an array\n * @template T - State type\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 // 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 const {\n externalStore,\n usedKeys,\n usedClassPropKeys,\n instance,\n rid,\n } = useExternalBlocStore(bloc, options);\n\n // Subscribe to state changes using React's external store API\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n externalStore.subscribe,\n () => {\n const snapshot = externalStore.getSnapshot();\n if (snapshot === undefined) {\n throw new Error(`[useBloc] State snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`);\n }\n return snapshot;\n },\n externalStore.getServerSnapshot ? () => {\n const serverSnapshot = externalStore.getServerSnapshot!();\n if (serverSnapshot === undefined) {\n throw new Error(`[useBloc] Server state snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`);\n }\n return serverSnapshot;\n } : undefined,\n );\n\n // Cache proxies to avoid recreation on every render\n const stateProxyCache = useRef<WeakMap<object, object>>(new WeakMap());\n const classProxyCache = useRef<WeakMap<object, object>>(new WeakMap());\n\n const returnState = useMemo(() => {\n if (typeof state !== 'object' || state === null) {\n return state;\n }\n\n // Check cache first\n let proxy = stateProxyCache.current.get(state);\n if (!proxy) {\n proxy = new Proxy(state, {\n get(target, prop) {\n // Use setTimeout to defer dependency tracking until after render\n setTimeout(() => {\n usedKeys.current.add(prop as string);\n }, 0);\n const value = target[prop as keyof typeof target];\n return value;\n },\n // Handle symbols and non-enumerable properties\n has(target, prop) {\n return prop in target;\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n }\n });\n stateProxyCache.current.set(state as object, proxy as object);\n }\n return proxy;\n }, [state]);\n\n const returnClass = useMemo(() => {\n if (!instance.current) {\n throw new Error(`[useBloc] Bloc instance is null for ${bloc.name}. This should never happen - bloc instance must be defined.`);\n }\n\n // Check cache first\n let proxy = classProxyCache.current.get(instance.current);\n if (!proxy) {\n proxy = new Proxy(instance.current, {\n get(target, prop) {\n if (!target) {\n throw new Error(`[useBloc] Bloc target is null for ${bloc.name}. This should never happen - bloc target must be defined.`);\n }\n const value = target[prop as keyof InstanceType<B>];\n if (typeof value !== 'function') {\n usedClassPropKeys.current.add(prop as string);\n }\n return value;\n },\n });\n classProxyCache.current.set(instance.current, proxy);\n }\n return proxy;\n }, [instance.current?.uid]);\n\n // Create a stable reference object for this component\n const componentRef = useRef({});\n\n // Set up bloc lifecycle management\n useEffect(() => {\n const currentInstance = instance.current;\n if (!currentInstance) return;\n \n // Pass component reference for proper memory management\n currentInstance._addConsumer(rid, componentRef.current);\n\n // Call onMount callback if provided\n options?.onMount?.(currentInstance);\n\n // Cleanup: remove this component as a consumer using the captured instance\n return () => {\n if (!currentInstance) {\n return;\n }\n options?.onUnmount?.(currentInstance);\n currentInstance._removeConsumer(rid);\n };\n }, [instance.current?.uid, rid]); // Use UID to ensure we re-run when instance changes\n\n // Ensure state and instance are never undefined/null\n if (returnState === undefined) {\n throw new Error(`[useBloc] State is undefined for ${bloc.name}. This should never happen - state must be defined.`);\n }\n if (!returnClass) {\n throw new Error(`[useBloc] Instance is null for ${bloc.name}. This should never happen - instance must be defined.`);\n }\n\n // Safe return with proper typing\n return [returnState, returnClass] as [BlocState<InstanceType<B>>, InstanceType<B>];\n}\n"],"names":["useExternalBlocStore","bloc","options","blocId","props","selector","rid","useMemo","generateUUID","effectiveBlocId","usedKeys","useRef","usedClassPropKeys","getBloc","useCallback","Blac","blocInstance","dependencyArray","newState","instance","usedStateValues","key","usedClassValues","value","error","state","listener","currentInstance","observer","e","unSub","_a","useBloc","externalStore","useSyncExternalStore","snapshot","serverSnapshot","stateProxyCache","classProxyCache","returnState","proxy","target","prop","returnClass","componentRef","useEffect","_b"],"mappings":";;AA0CM,MAAAA,IAAuB,CAG3BC,GACAC,MACyB;;AACzB,QAAM,EAAE,IAAIC,GAAQ,OAAAC,GAAO,UAAAC,EAAS,IAAIH,KAAW,CAAC,GAE9CI,IAAMC,EAAQ,MACXC,EAAa,GACnB,EAAE,GAKCC,IAHOR,EAEW,WACaK,IAAMH,GAErCO,IAAWC,EAAwB,oBAAA,KAAK,GACxCC,IAAoBD,EAAwB,oBAAA,KAAK,GAEjDE,IAAUC,EAAY,MACnBC,EAAK,QAAQd,GAAM;AAAA,IACxB,IAAIQ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gBAAM,IAAI,MAAM,qCAAqCxC,EAAK,IAAI,2DAA2D;AAErH,cAAAsB,IAAQkB,EAAOC,CAA6B;AAC9C,eAAA,OAAOnB,KAAU,cACDX,EAAA,QAAQ,IAAI8B,CAAc,GAEvCnB;AAAA,MAAA;AAAA,IACT,CACD,GACDe,EAAgB,QAAQ,IAAInB,EAAS,SAASqB,CAAK,IAE9CA;AAAA,EACN,GAAA,EAACT,IAAAZ,EAAS,YAAT,gBAAAY,EAAkB,GAAG,CAAC,GAGpBa,IAAejC,EAAO,EAAE;AAwB9B,MArBAkC,EAAU,MAAM;;AACd,UAAMlB,IAAkBR,EAAS;AACjC,QAAKQ;AAGW,aAAAA,EAAA,aAAarB,GAAKsC,EAAa,OAAO,IAGtDb,IAAA7B,KAAA,gBAAAA,EAAS,YAAT,QAAA6B,EAAA,KAAA7B,GAAmByB,IAGZ,MAAM;;AACX,QAAKA,OAGLI,IAAA7B,KAAA,gBAAAA,EAAS,cAAT,QAAA6B,EAAA,KAAA7B,GAAqByB,IACrBA,EAAgB,gBAAgBrB,CAAG;AAAA,MACrC;AAAA,KACC,EAACwC,IAAA3B,EAAS,YAAT,gBAAA2B,EAAkB,KAAKxC,CAAG,CAAC,GAG3BiC,MAAgB;AAClB,UAAM,IAAI,MAAM,oCAAoCtC,EAAK,IAAI,qDAAqD;AAEpH,MAAI,CAAC0C;AACH,UAAM,IAAI,MAAM,kCAAkC1C,EAAK,IAAI,wDAAwD;AAI9G,SAAA,CAACsC,GAAaI,CAAW;AAClC;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/useBloc.ts","../src/useExternalBlocStore.ts"],"sourcesContent":["import {\n AdapterOptions,\n BlacAdapter,\n BlocBase,\n BlocConstructor,\n BlocState,\n} from '@blac/core';\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\n\n/**\n * Type definition for the return type of the useBloc hook\n */\ntype HookTypes<B extends BlocConstructor<BlocBase<any>>> = [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n];\n\n/**\n * React hook for integrating with Blac state management\n */\nfunction useBloc<B extends BlocConstructor<BlocBase<any>>>(\n blocConstructor: B,\n options?: AdapterOptions<InstanceType<B>>,\n): HookTypes<B> {\n // Create a unique identifier for this hook instance\n const renderCount = useRef(0);\n renderCount.current++;\n\n const componentRef = useRef<object>({});\n\n // Track adapter creation\n const adapter = useMemo(() => {\n const newAdapter = new BlacAdapter<B>(\n {\n componentRef: componentRef,\n blocConstructor,\n },\n options,\n );\n return newAdapter;\n }, []);\n\n // Reset tracking at the start of each render to ensure we only track\n // properties accessed during the current render\n adapter.resetConsumerTracking();\n\n // Track options changes\n const optionsChangeCount = useRef(0);\n useEffect(() => {\n optionsChangeCount.current++;\n adapter.options = options;\n }, [options]);\n\n // Register as consumer and handle lifecycle\n const mountEffectCount = useRef(0);\n useEffect(() => {\n mountEffectCount.current++;\n adapter.mount();\n\n return () => {\n adapter.unmount();\n };\n }, [adapter.blocInstance]);\n\n // Subscribe to state changes using useSyncExternalStore\n const subscribeMemoCount = useRef(0);\n const subscribe = useMemo(() => {\n subscribeMemoCount.current++;\n let subscriptionCount = 0;\n\n return (onStoreChange: () => void) => {\n subscriptionCount++;\n const unsubscribe = adapter.createSubscription({\n onChange: () => {\n onStoreChange();\n },\n });\n\n return () => {\n unsubscribe();\n };\n };\n }, [adapter.blocInstance]);\n\n const snapshotCount = useRef(0);\n const serverSnapshotCount = useRef(0);\n\n const rawState: BlocState<InstanceType<B>> = useSyncExternalStore(\n subscribe,\n // Get snapshot\n () => {\n snapshotCount.current++;\n const bloc = adapter.blocInstance;\n const state = bloc.state;\n return state;\n },\n // Get server snapshot (same as client for now)\n () => {\n const bloc = adapter.blocInstance;\n serverSnapshotCount.current++;\n const state = bloc.state;\n return state;\n },\n );\n\n // Create proxies for fine-grained tracking (if enabled)\n const stateMemoCount = useRef(0);\n const finalState = useMemo(() => {\n stateMemoCount.current++;\n const proxyState = adapter.getProxyState(rawState);\n return proxyState;\n }, [rawState]);\n\n const blocMemoCount = useRef(0);\n const finalBloc = useMemo(() => {\n blocMemoCount.current++;\n const proxyBloc = adapter.getProxyBlocInstance();\n return proxyBloc;\n }, [adapter.blocInstance]);\n\n // Mark consumer as rendered after each render\n useEffect(() => {\n adapter.updateLastNotified(componentRef.current);\n });\n\n // Log final hook return\n return [finalState, finalBloc];\n}\n\nexport default useBloc;\n","import {\n Blac,\n BlocBase,\n BlocConstructor,\n BlocState,\n InferPropsFromGeneric,\n generateUUID,\n} from '@blac/core';\nimport { useCallback, useMemo, useRef } from 'react';\n\ninterface ExternalStoreOptions<B extends BlocBase<any>> {\n id?: string;\n props?: InferPropsFromGeneric<B>;\n selector?: (\n currentState: BlocState<B>,\n previousState: BlocState<B>,\n instance: B,\n ) => any[];\n}\n\ninterface ExternalStore<T> {\n getSnapshot: () => T | undefined;\n subscribe: (listener: () => void) => () => void;\n getServerSnapshot?: () => T | undefined;\n}\n\ninterface ExternalBlocStoreResult<B extends BlocBase<any>> {\n externalStore: ExternalStore<BlocState<B>>;\n instance: { current: B | null };\n usedKeys: { current: Set<string> };\n usedClassPropKeys: { current: Set<string> };\n rid: string;\n}\n\n/**\n * Hook for using an external bloc store\n * Provides low-level access to bloc instances for use with React's useSyncExternalStore\n */\nexport default function useExternalBlocStore<\n B extends BlocConstructor<BlocBase<any>>,\n>(\n blocConstructor: B,\n options: ExternalStoreOptions<InstanceType<B>> = {},\n): ExternalBlocStoreResult<InstanceType<B>> {\n const ridRef = useRef<string>(`external-${generateUUID()}`);\n const usedKeysRef = useRef<Set<string>>(new Set());\n const usedClassPropKeysRef = useRef<Set<string>>(new Set());\n const instanceRef = useRef<InstanceType<B> | null>(null);\n\n // Get or create bloc instance\n const bloc = useMemo(() => {\n const blac = Blac.getInstance();\n const base = blocConstructor as unknown as BlocBase<any>;\n\n // For isolated blocs, always create a new instance\n if (\n (base.constructor as any).isolated ||\n (blocConstructor as any).isolated\n ) {\n const newBloc = new blocConstructor(options?.props) as InstanceType<B>;\n const uniqueId =\n options?.id || `${blocConstructor.name}_${generateUUID()}`;\n newBloc._updateId(uniqueId);\n blac.activateBloc(newBloc);\n return newBloc;\n }\n\n // For shared blocs, use the existing getBloc logic\n return blac.getBloc(blocConstructor, {\n id: options?.id,\n props: options?.props,\n });\n }, [blocConstructor, options?.id]);\n\n // Create external store interface\n const externalStore = useMemo<ExternalStore<BlocState<InstanceType<B>>>>(\n () => ({\n getSnapshot: () => {\n const currentInstance = instanceRef.current;\n return currentInstance ? currentInstance.state : undefined;\n },\n subscribe: (listener: () => void) => {\n const currentInstance = instanceRef.current;\n if (!currentInstance) {\n // Return no-op unsubscribe if no instance\n return () => {};\n }\n\n // Wrap listener to handle errors gracefully\n const safeListener = (\n newState: BlocState<InstanceType<B>>,\n oldState: BlocState<InstanceType<B>>,\n ) => {\n try {\n // Reset tracking keys on each listener call\n usedKeysRef.current.clear();\n usedClassPropKeysRef.current.clear();\n\n // Call selector if provided\n if (options.selector && currentInstance) {\n options.selector(newState, oldState, currentInstance);\n }\n\n // Call listener with state if it expects it\n if (listener.length > 0) {\n (listener as any)(newState);\n } else {\n listener();\n }\n } catch (error) {\n console.error('Listener error in useExternalBlocStore:', error);\n // Don't rethrow to prevent breaking other listeners\n }\n };\n\n const unsubscribe = currentInstance._observer.subscribe({\n id: ridRef.current,\n fn: safeListener,\n });\n return unsubscribe;\n },\n getServerSnapshot: () => {\n const currentInstance = instanceRef.current;\n return currentInstance ? currentInstance.state : undefined;\n },\n }),\n [],\n );\n\n // Update instance ref\n instanceRef.current = bloc;\n\n return {\n externalStore,\n instance: instanceRef,\n usedKeys: usedKeysRef,\n usedClassPropKeys: usedClassPropKeysRef,\n rid: ridRef.current,\n };\n}\n"],"names":["useBloc","blocConstructor","options","renderCount","useRef","componentRef","adapter","useMemo","BlacAdapter","optionsChangeCount","useEffect","mountEffectCount","subscribeMemoCount","subscribe","onStoreChange","unsubscribe","snapshotCount","serverSnapshotCount","rawState","useSyncExternalStore","bloc","stateMemoCount","finalState","blocMemoCount","finalBloc","useExternalBlocStore","ridRef","generateUUID","usedKeysRef","usedClassPropKeysRef","instanceRef","blac","Blac","newBloc","uniqueId","externalStore","currentInstance","listener","safeListener","newState","oldState","error"],"mappings":";;AAoBA,SAASA,EACPC,GACAC,GACc;AAER,QAAAC,IAAcC,EAAO,CAAC;AAChB,EAAAD,EAAA;AAEN,QAAAE,IAAeD,EAAe,EAAE,GAGhCE,IAAUC,EAAQ,MACH,IAAIC;AAAA,IACrB;AAAA,MACE,cAAAH;AAAA,MACA,iBAAAJ;AAAA,IACF;AAAA,IACAC;AAAA,EACF,GAEC,EAAE;AAIL,EAAAI,EAAQ,sBAAsB;AAGxB,QAAAG,IAAqBL,EAAO,CAAC;AACnC,EAAAM,EAAU,MAAM;AACK,IAAAD,EAAA,WACnBH,EAAQ,UAAUJ;AAAA,EAAA,GACjB,CAACA,CAAO,CAAC;AAGN,QAAAS,IAAmBP,EAAO,CAAC;AACjC,EAAAM,EAAU,OACSC,EAAA,WACjBL,EAAQ,MAAM,GAEP,MAAM;AACX,IAAAA,EAAQ,QAAQ;AAAA,EAClB,IACC,CAACA,EAAQ,YAAY,CAAC;AAGnB,QAAAM,IAAqBR,EAAO,CAAC,GAC7BS,IAAYN,EAAQ,OACLK,EAAA,WAGZ,CAACE,MAA8B;AAE9B,UAAAC,IAAcT,EAAQ,mBAAmB;AAAA,MAC7C,UAAU,MAAM;AACA,QAAAQ,EAAA;AAAA,MAAA;AAAA,IAChB,CACD;AAED,WAAO,MAAM;AACC,MAAAC,EAAA;AAAA,IACd;AAAA,EACF,IACC,CAACT,EAAQ,YAAY,CAAC,GAEnBU,IAAgBZ,EAAO,CAAC,GACxBa,IAAsBb,EAAO,CAAC,GAE9Bc,IAAuCC;AAAA,IAC3CN;AAAA;AAAA,IAEA,OACgBG,EAAA,WACDV,EAAQ,aACF;AAAA;AAAA,IAIrB,MAAM;AACJ,YAAMc,IAAOd,EAAQ;AACD,aAAAW,EAAA,WACNG,EAAK;AAAA,IAC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AAQ;AAAA,MACnD;AAAA,MACA,WAAW,CAACC,MAAyB;AACnC,cAAMD,IAAkBN,EAAY;AACpC,YAAI,CAACM;AAEH,iBAAO,MAAM;AAAA,UAAC;AAIV,cAAAE,IAAe,CACnBC,GACAC,MACG;AACC,cAAA;AAEF,YAAAZ,EAAY,QAAQ,MAAM,GAC1BC,EAAqB,QAAQ,MAAM,GAG/B3B,EAAQ,YAAYkC,KACdlC,EAAA,SAASqC,GAAUC,GAAUJ,CAAe,GAIlDC,EAAS,SAAS,IACnBA,EAAiBE,CAAQ,IAEjBF,EAAA;AAAA,mBAEJI,GAAO;AACN,oBAAA,MAAM,2CAA2CA,CAAK;AAAA,UAAA;AAAA,QAGlE;AAMO,eAJaL,EAAgB,UAAU,UAAU;AAAA,UACtD,IAAIV,EAAO;AAAA,UACX,IAAIY;AAAA,QAAA,CACL;AAAA,MAEH;AAAA,MACA,mBAAmB,MAAM;AACvB,cAAMF,IAAkBN,EAAY;AAC7B,eAAAM,IAAkBA,EAAgB,QAAQ;AAAA,MAAA;AAAA,IACnD;AAAA,IAEF,CAAA;AAAA,EACF;AAGA,SAAAN,EAAY,UAAUV,GAEf;AAAA,IACL,eAAAe;AAAA,IACA,UAAUL;AAAA,IACV,UAAUF;AAAA,IACV,mBAAmBC;AAAA,IACnB,KAAKH,EAAO;AAAA,EACd;AACF;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blac/react",
|
|
3
|
-
"version": "2.0.0-rc-
|
|
3
|
+
"version": "2.0.0-rc-10",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"author": "Brendan Mullins <jsnanigans@gmail.com>",
|
|
6
6
|
"main": "dist/index.cjs.js",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"@types/react-dom": "^18.0.0 || ^19.0.0",
|
|
31
31
|
"react": "^18.0.0 || ^19.0.0",
|
|
32
32
|
"react-dom": "^18.0.0 || ^19.0.0",
|
|
33
|
-
"@blac/core": "2.0.0-rc-
|
|
33
|
+
"@blac/core": "2.0.0-rc-10"
|
|
34
34
|
},
|
|
35
35
|
"peerDependenciesMeta": {
|
|
36
36
|
"@types/react": {
|
|
@@ -41,17 +41,17 @@
|
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@testing-library/dom": "^10.4.
|
|
44
|
+
"@testing-library/dom": "^10.4.1",
|
|
45
45
|
"@testing-library/jest-dom": "^6.6.3",
|
|
46
46
|
"@testing-library/react": "^16.3.0",
|
|
47
47
|
"@testing-library/user-event": "^14.6.1",
|
|
48
|
-
"@types/react": "^19.1.
|
|
49
|
-
"@vitejs/plugin-react": "^4.
|
|
50
|
-
"@vitest/browser": "^3.
|
|
51
|
-
"@vitest/coverage-v8": "^3.
|
|
52
|
-
"happy-dom": "^
|
|
48
|
+
"@types/react": "^19.1.8",
|
|
49
|
+
"@vitejs/plugin-react": "^4.7.0",
|
|
50
|
+
"@vitest/browser": "^3.2.4",
|
|
51
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
52
|
+
"happy-dom": "^18.0.1",
|
|
53
53
|
"jsdom": "^24.1.1",
|
|
54
|
-
"prettier": "^3.
|
|
54
|
+
"prettier": "^3.6.2",
|
|
55
55
|
"react": "^19.1.0",
|
|
56
56
|
"react-dom": "^19.1.0",
|
|
57
57
|
"typescript": "^5.8.3",
|
|
@@ -61,6 +61,7 @@
|
|
|
61
61
|
},
|
|
62
62
|
"scripts": {
|
|
63
63
|
"prettier": "prettier --write ./src",
|
|
64
|
+
"format": "prettier --write \"src/**/*.{ts,tsx,js,jsx}\"",
|
|
64
65
|
"test": "vitest run --config vitest.config.ts",
|
|
65
66
|
"test:watch": "vitest --watch --config vitest.config.ts",
|
|
66
67
|
"typecheck": "tsc --noEmit",
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { renderHook, act } from '@testing-library/react';
|
|
3
|
+
import { Cubit } from '@blac/core';
|
|
4
|
+
import useBloc from '../useBloc';
|
|
5
|
+
|
|
6
|
+
interface TestState {
|
|
7
|
+
count: number;
|
|
8
|
+
name: string;
|
|
9
|
+
unused: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
class TestCubit extends Cubit<TestState> {
|
|
13
|
+
constructor() {
|
|
14
|
+
super({ count: 0, name: 'Alice', unused: 'not-used' });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
increment = () => {
|
|
18
|
+
this.emit({ ...this.state, count: this.state.count + 1 });
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
changeName = (name: string) => {
|
|
22
|
+
this.emit({ ...this.state, name });
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
changeUnused = (value: string) => {
|
|
26
|
+
this.emit({ ...this.state, unused: value });
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
describe('useBloc dependency tracking', () => {
|
|
31
|
+
it('should only track properties accessed during current render', () => {
|
|
32
|
+
let renderCount = 0;
|
|
33
|
+
let accessedProperties: string[] = [];
|
|
34
|
+
|
|
35
|
+
const { result, rerender } = renderHook(() => {
|
|
36
|
+
const [state, cubit] = useBloc(TestCubit);
|
|
37
|
+
renderCount++;
|
|
38
|
+
|
|
39
|
+
// Reset tracked properties for this render
|
|
40
|
+
accessedProperties = [];
|
|
41
|
+
|
|
42
|
+
// First few renders: access both count and name
|
|
43
|
+
if (renderCount <= 2) {
|
|
44
|
+
// Access count and name
|
|
45
|
+
void state.count;
|
|
46
|
+
void state.name;
|
|
47
|
+
accessedProperties = ['count', 'name'];
|
|
48
|
+
} else {
|
|
49
|
+
// Later renders: only access count
|
|
50
|
+
void state.count;
|
|
51
|
+
accessedProperties = ['count'];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return { state, cubit, accessedProperties };
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
// Initial render - accessing count and name
|
|
58
|
+
expect(renderCount).toBe(1);
|
|
59
|
+
expect(result.current.accessedProperties).toEqual(['count', 'name']);
|
|
60
|
+
|
|
61
|
+
// Change name - should trigger re-render since we're tracking it
|
|
62
|
+
act(() => {
|
|
63
|
+
result.current.cubit.changeName('Bob');
|
|
64
|
+
});
|
|
65
|
+
expect(renderCount).toBe(2);
|
|
66
|
+
expect(result.current.state.name).toBe('Bob');
|
|
67
|
+
|
|
68
|
+
// Force a re-render (this will be render #3, where we stop accessing name)
|
|
69
|
+
rerender();
|
|
70
|
+
expect(renderCount).toBe(3);
|
|
71
|
+
expect(result.current.accessedProperties).toEqual(['count']); // Only accessing count now
|
|
72
|
+
|
|
73
|
+
// Change name again - should NOT trigger re-render since we're no longer tracking it
|
|
74
|
+
const prevRenderCount = renderCount;
|
|
75
|
+
act(() => {
|
|
76
|
+
result.current.cubit.changeName('Charlie');
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// Render count should not increase
|
|
80
|
+
expect(renderCount).toBe(prevRenderCount);
|
|
81
|
+
// But state should still be updated if we check it
|
|
82
|
+
expect(result.current.cubit.state.name).toBe('Charlie');
|
|
83
|
+
|
|
84
|
+
// Change count - should trigger re-render since we're still tracking it
|
|
85
|
+
act(() => {
|
|
86
|
+
result.current.cubit.increment();
|
|
87
|
+
});
|
|
88
|
+
expect(renderCount).toBe(prevRenderCount + 1);
|
|
89
|
+
expect(result.current.state.count).toBe(1);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('should not re-render when non-accessed properties change', () => {
|
|
93
|
+
let renderCount = 0;
|
|
94
|
+
|
|
95
|
+
const { result } = renderHook(() => {
|
|
96
|
+
const [state, cubit] = useBloc(TestCubit);
|
|
97
|
+
renderCount++;
|
|
98
|
+
|
|
99
|
+
// Only access count, never access unused
|
|
100
|
+
void state.count;
|
|
101
|
+
|
|
102
|
+
return { state, cubit };
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
expect(renderCount).toBe(1);
|
|
106
|
+
|
|
107
|
+
// Change unused property - should NOT trigger re-render
|
|
108
|
+
act(() => {
|
|
109
|
+
result.current.cubit.changeUnused('changed');
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
// Should not re-render
|
|
113
|
+
expect(renderCount).toBe(1);
|
|
114
|
+
|
|
115
|
+
// But the actual state should be updated
|
|
116
|
+
expect(result.current.cubit.state.unused).toBe('changed');
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it('should track nested property access correctly', () => {
|
|
120
|
+
interface NestedState {
|
|
121
|
+
user: {
|
|
122
|
+
profile: {
|
|
123
|
+
name: string;
|
|
124
|
+
age: number;
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
settings: {
|
|
128
|
+
theme: string;
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
class NestedCubit extends Cubit<NestedState> {
|
|
133
|
+
constructor() {
|
|
134
|
+
super({
|
|
135
|
+
user: {
|
|
136
|
+
profile: {
|
|
137
|
+
name: 'Alice',
|
|
138
|
+
age: 25,
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
settings: {
|
|
142
|
+
theme: 'light',
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
updateName = (name: string) => {
|
|
148
|
+
this.emit({
|
|
149
|
+
...this.state,
|
|
150
|
+
user: {
|
|
151
|
+
...this.state.user,
|
|
152
|
+
profile: {
|
|
153
|
+
...this.state.user.profile,
|
|
154
|
+
name,
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
});
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
updateTheme = (theme: string) => {
|
|
161
|
+
this.emit({
|
|
162
|
+
...this.state,
|
|
163
|
+
settings: {
|
|
164
|
+
...this.state.settings,
|
|
165
|
+
theme,
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
let renderCount = 0;
|
|
172
|
+
|
|
173
|
+
const { result } = renderHook(() => {
|
|
174
|
+
const [state, cubit] = useBloc(NestedCubit);
|
|
175
|
+
renderCount++;
|
|
176
|
+
|
|
177
|
+
// Only access user.profile.name
|
|
178
|
+
void state.user.profile.name;
|
|
179
|
+
|
|
180
|
+
return { state, cubit };
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
expect(renderCount).toBe(1);
|
|
184
|
+
|
|
185
|
+
// Change theme - should NOT trigger re-render
|
|
186
|
+
act(() => {
|
|
187
|
+
result.current.cubit.updateTheme('dark');
|
|
188
|
+
});
|
|
189
|
+
expect(renderCount).toBe(1);
|
|
190
|
+
|
|
191
|
+
// Change name - should trigger re-render
|
|
192
|
+
act(() => {
|
|
193
|
+
result.current.cubit.updateName('Bob');
|
|
194
|
+
});
|
|
195
|
+
expect(renderCount).toBe(2);
|
|
196
|
+
expect(result.current.state.user.profile.name).toBe('Bob');
|
|
197
|
+
});
|
|
198
|
+
});
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export { useExternalBlocStore as externalBlocStore, useBloc };
|
|
1
|
+
export { default as useBloc } from './useBloc';
|
|
2
|
+
export { default as useExternalBlocStore } from './useExternalBlocStore';
|
package/src/useBloc.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AdapterOptions,
|
|
3
|
+
BlacAdapter,
|
|
4
|
+
BlocBase,
|
|
5
|
+
BlocConstructor,
|
|
6
|
+
BlocState,
|
|
7
|
+
} from '@blac/core';
|
|
8
|
+
import { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Type definition for the return type of the useBloc hook
|
|
12
|
+
*/
|
|
13
|
+
type HookTypes<B extends BlocConstructor<BlocBase<any>>> = [
|
|
14
|
+
BlocState<InstanceType<B>>,
|
|
15
|
+
InstanceType<B>,
|
|
16
|
+
];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* React hook for integrating with Blac state management
|
|
20
|
+
*/
|
|
21
|
+
function useBloc<B extends BlocConstructor<BlocBase<any>>>(
|
|
22
|
+
blocConstructor: B,
|
|
23
|
+
options?: AdapterOptions<InstanceType<B>>,
|
|
24
|
+
): HookTypes<B> {
|
|
25
|
+
// Create a unique identifier for this hook instance
|
|
26
|
+
const renderCount = useRef(0);
|
|
27
|
+
renderCount.current++;
|
|
28
|
+
|
|
29
|
+
const componentRef = useRef<object>({});
|
|
30
|
+
|
|
31
|
+
// Track adapter creation
|
|
32
|
+
const adapter = useMemo(() => {
|
|
33
|
+
const newAdapter = new BlacAdapter<B>(
|
|
34
|
+
{
|
|
35
|
+
componentRef: componentRef,
|
|
36
|
+
blocConstructor,
|
|
37
|
+
},
|
|
38
|
+
options,
|
|
39
|
+
);
|
|
40
|
+
return newAdapter;
|
|
41
|
+
}, []);
|
|
42
|
+
|
|
43
|
+
// Reset tracking at the start of each render to ensure we only track
|
|
44
|
+
// properties accessed during the current render
|
|
45
|
+
adapter.resetConsumerTracking();
|
|
46
|
+
|
|
47
|
+
// Track options changes
|
|
48
|
+
const optionsChangeCount = useRef(0);
|
|
49
|
+
useEffect(() => {
|
|
50
|
+
optionsChangeCount.current++;
|
|
51
|
+
adapter.options = options;
|
|
52
|
+
}, [options]);
|
|
53
|
+
|
|
54
|
+
// Register as consumer and handle lifecycle
|
|
55
|
+
const mountEffectCount = useRef(0);
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
mountEffectCount.current++;
|
|
58
|
+
adapter.mount();
|
|
59
|
+
|
|
60
|
+
return () => {
|
|
61
|
+
adapter.unmount();
|
|
62
|
+
};
|
|
63
|
+
}, [adapter.blocInstance]);
|
|
64
|
+
|
|
65
|
+
// Subscribe to state changes using useSyncExternalStore
|
|
66
|
+
const subscribeMemoCount = useRef(0);
|
|
67
|
+
const subscribe = useMemo(() => {
|
|
68
|
+
subscribeMemoCount.current++;
|
|
69
|
+
let subscriptionCount = 0;
|
|
70
|
+
|
|
71
|
+
return (onStoreChange: () => void) => {
|
|
72
|
+
subscriptionCount++;
|
|
73
|
+
const unsubscribe = adapter.createSubscription({
|
|
74
|
+
onChange: () => {
|
|
75
|
+
onStoreChange();
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
return () => {
|
|
80
|
+
unsubscribe();
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
}, [adapter.blocInstance]);
|
|
84
|
+
|
|
85
|
+
const snapshotCount = useRef(0);
|
|
86
|
+
const serverSnapshotCount = useRef(0);
|
|
87
|
+
|
|
88
|
+
const rawState: BlocState<InstanceType<B>> = useSyncExternalStore(
|
|
89
|
+
subscribe,
|
|
90
|
+
// Get snapshot
|
|
91
|
+
() => {
|
|
92
|
+
snapshotCount.current++;
|
|
93
|
+
const bloc = adapter.blocInstance;
|
|
94
|
+
const state = bloc.state;
|
|
95
|
+
return state;
|
|
96
|
+
},
|
|
97
|
+
// Get server snapshot (same as client for now)
|
|
98
|
+
() => {
|
|
99
|
+
const bloc = adapter.blocInstance;
|
|
100
|
+
serverSnapshotCount.current++;
|
|
101
|
+
const state = bloc.state;
|
|
102
|
+
return state;
|
|
103
|
+
},
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
// Create proxies for fine-grained tracking (if enabled)
|
|
107
|
+
const stateMemoCount = useRef(0);
|
|
108
|
+
const finalState = useMemo(() => {
|
|
109
|
+
stateMemoCount.current++;
|
|
110
|
+
const proxyState = adapter.getProxyState(rawState);
|
|
111
|
+
return proxyState;
|
|
112
|
+
}, [rawState]);
|
|
113
|
+
|
|
114
|
+
const blocMemoCount = useRef(0);
|
|
115
|
+
const finalBloc = useMemo(() => {
|
|
116
|
+
blocMemoCount.current++;
|
|
117
|
+
const proxyBloc = adapter.getProxyBlocInstance();
|
|
118
|
+
return proxyBloc;
|
|
119
|
+
}, [adapter.blocInstance]);
|
|
120
|
+
|
|
121
|
+
// Mark consumer as rendered after each render
|
|
122
|
+
useEffect(() => {
|
|
123
|
+
adapter.updateLastNotified(componentRef.current);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
// Log final hook return
|
|
127
|
+
return [finalState, finalBloc];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export default useBloc;
|