@blac/react 2.0.0-rc-7 → 2.0.0-rc-8
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 +1 -0
- package/dist/index.es.js +347 -127
- package/dist/index.es.js.map +1 -1
- package/package.json +2 -2
- package/src/DependencyTracker.ts +350 -0
- package/src/useBloc.tsx +69 -44
- package/src/useExternalBlocStore.ts +145 -45
package/README.md
CHANGED
|
@@ -10,7 +10,8 @@ A powerful React integration for the Blac state management library, providing se
|
|
|
10
10
|
- 🎨 TypeScript support with full type inference
|
|
11
11
|
- ⚡️ Efficient state management with minimal boilerplate
|
|
12
12
|
- 🔄 Support for isolated and shared bloc instances
|
|
13
|
-
- 🎯 Custom dependency selectors
|
|
13
|
+
- 🎯 Custom dependency selectors with access to state, previous state, and instance
|
|
14
|
+
- 🚀 Optimized re-rendering with intelligent snapshot comparison
|
|
14
15
|
|
|
15
16
|
## Important: Arrow Functions Required
|
|
16
17
|
|
|
@@ -83,13 +84,13 @@ const [state, bloc] = useBloc(YourBloc, {
|
|
|
83
84
|
id: 'custom-id', // Optional: Custom identifier for the bloc
|
|
84
85
|
props: { /* ... */ }, // Optional: Props to pass to the bloc
|
|
85
86
|
onMount: (bloc) => { /* ... */ }, // Optional: Callback when bloc is mounted (similar to useEffect(<>, []))
|
|
86
|
-
|
|
87
|
+
selector: (currentState, previousState, instance) => [/* ... */], // Optional: Custom dependency tracking
|
|
87
88
|
});
|
|
88
89
|
```
|
|
89
90
|
|
|
90
|
-
### Dependency Tracking
|
|
91
|
+
### Automatic Dependency Tracking
|
|
91
92
|
|
|
92
|
-
The hook automatically tracks which state properties are accessed in your component and only triggers re-renders when those specific
|
|
93
|
+
The hook automatically tracks which state properties and bloc instance properties are accessed in your component and only triggers re-renders when those specific values change:
|
|
93
94
|
|
|
94
95
|
```tsx
|
|
95
96
|
function UserProfile() {
|
|
@@ -100,30 +101,75 @@ function UserProfile() {
|
|
|
100
101
|
}
|
|
101
102
|
```
|
|
102
103
|
|
|
103
|
-
This also works for getters on the Bloc or Cubit class:
|
|
104
|
+
This also works for getters and computed properties on the Bloc or Cubit class:
|
|
104
105
|
|
|
105
106
|
```tsx
|
|
106
107
|
function UserProfile() {
|
|
107
|
-
const [, userBloc] = useBloc(UserBloc);
|
|
108
|
+
const [state, userBloc] = useBloc(UserBloc);
|
|
108
109
|
|
|
109
|
-
// Only re-renders when
|
|
110
|
-
|
|
110
|
+
// Only re-renders when:
|
|
111
|
+
// - state.firstName changes, OR
|
|
112
|
+
// - state.lastName changes (because the getter accesses these properties)
|
|
113
|
+
return <h1>{userBloc.fullName}</h1>; // Assuming fullName is a getter
|
|
111
114
|
}
|
|
112
115
|
```
|
|
113
116
|
|
|
117
|
+
#### How It Works
|
|
118
|
+
|
|
119
|
+
The dependency tracking system uses JavaScript Proxies to monitor property access during component renders:
|
|
120
|
+
|
|
121
|
+
1. **State Properties**: When you access `state.propertyName`, it's automatically tracked
|
|
122
|
+
2. **Instance Properties**: When you access `bloc.computedValue`, it's automatically tracked
|
|
123
|
+
3. **Intelligent Comparison**: The system separately tracks state dependencies and instance dependencies to handle edge cases where properties are dynamically added/removed
|
|
124
|
+
4. **Optimized Updates**: Components only re-render when tracked dependencies actually change their values
|
|
125
|
+
|
|
114
126
|
### Custom Dependency Selector
|
|
115
127
|
|
|
116
|
-
For more control over when your component re-renders, you can provide a custom dependency selector:
|
|
128
|
+
For more control over when your component re-renders, you can provide a custom dependency selector. The selector function receives the current state, previous state, and bloc instance, and should return an array of values to track:
|
|
117
129
|
|
|
118
130
|
```tsx
|
|
119
131
|
const [state, bloc] = useBloc(YourBloc, {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
132
|
+
selector: (currentState, previousState, instance) => [
|
|
133
|
+
currentState.specificField,
|
|
134
|
+
currentState.anotherField,
|
|
135
|
+
instance.computedValue // You can also track computed properties from the bloc instance
|
|
123
136
|
]
|
|
124
137
|
});
|
|
125
138
|
```
|
|
126
139
|
|
|
140
|
+
The component will only re-render when any of the values in the returned array change (using `Object.is` comparison, similar to React's `useEffect` dependency array).
|
|
141
|
+
|
|
142
|
+
#### Examples of Custom Selectors
|
|
143
|
+
|
|
144
|
+
**Track only specific state properties:**
|
|
145
|
+
```tsx
|
|
146
|
+
const [state, userBloc] = useBloc(UserBloc, {
|
|
147
|
+
selector: (currentState) => [
|
|
148
|
+
currentState.name,
|
|
149
|
+
currentState.email
|
|
150
|
+
] // Only re-render when name or email changes, ignore other properties
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
**Track computed values:**
|
|
155
|
+
```tsx
|
|
156
|
+
const [state, shoppingCartBloc] = useBloc(ShoppingCartBloc, {
|
|
157
|
+
selector: (currentState, previousState, instance) => [
|
|
158
|
+
instance.totalPrice, // Computed getter
|
|
159
|
+
currentState.items.length // Number of items
|
|
160
|
+
] // Only re-render when total price or item count changes
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
**Compare with previous state:**
|
|
165
|
+
```tsx
|
|
166
|
+
const [state, chatBloc] = useBloc(ChatBloc, {
|
|
167
|
+
selector: (currentState, previousState) => [
|
|
168
|
+
currentState.messages.length > (previousState?.messages.length || 0) ? 'new-message' : 'no-change'
|
|
169
|
+
] // Only re-render when new messages are added, not when existing messages change
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
127
173
|
## API Reference
|
|
128
174
|
|
|
129
175
|
### useBloc Hook
|
|
@@ -140,7 +186,7 @@ function useBloc<B extends BlocConstructor<BlocGeneric>>(
|
|
|
140
186
|
- `id?: string` - Custom identifier for the bloc instance
|
|
141
187
|
- `props?: InferPropsFromGeneric<B>` - Props to pass to the bloc
|
|
142
188
|
- `onMount?: (bloc: B) => void` - Callback function invoked when the react component (the consumer) is connected to the bloc instance
|
|
143
|
-
- `
|
|
189
|
+
- `selector?: (currentState: BlocState<InstanceType<B>>, previousState: BlocState<InstanceType<B>> | undefined, instance: InstanceType<B>) => unknown[]` - Function to select dependencies for re-renders
|
|
144
190
|
|
|
145
191
|
## Best Practices
|
|
146
192
|
|
|
@@ -182,7 +228,10 @@ function useBloc<B extends BlocConstructor<BlocGeneric>>(
|
|
|
182
228
|
}
|
|
183
229
|
```
|
|
184
230
|
|
|
185
|
-
3. **
|
|
231
|
+
3. **Choose the Right Dependency Strategy**:
|
|
232
|
+
- **Use automatic tracking** (default) for most cases - it's efficient and requires no setup
|
|
233
|
+
- **Use custom selectors** when you need complex logic, computed comparisons, or want to ignore certain property changes
|
|
234
|
+
- **Avoid custom selectors** for simple property access - automatic tracking is more efficient
|
|
186
235
|
|
|
187
236
|
4. **Type Safety**: Take advantage of TypeScript's type inference for better development experience and catch errors early.
|
|
188
237
|
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";var U=Object.defineProperty;var W=(i,e,s)=>e in i?U(i,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[e]=s;var b=(i,e,s)=>W(i,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react"),E=require("@blac/core"),O=(i,e)=>{var k,I;const{id:s,props:f,selector:d}=e??{},n=c.useMemo(()=>E.generateUUID(),[]),a=i.isolated?n:s,p=c.useRef(new Set),M=c.useRef(new Set),K=c.useRef(!1),P=c.useCallback(()=>E.Blac.getBloc(i,{id:a,props:f,instanceRef:n}),[i,a,f,n]),v=c.useRef(P());c.useMemo(()=>{v.current=P()},[P]);const D=c.useRef(void 0),A=c.useRef(void 0),R=c.useRef(void 0),t=c.useRef(void 0);t.current!==((k=v.current)==null?void 0:k.uid)&&(t.current=(I=v.current)==null?void 0:I.uid);const h=c.useMemo(()=>(l,C)=>{const y=v.current;if(!y)return[[],[]];const S=C??D.current;let m;if(d)m=[d(l,S,y),[]];else if(y.defaultDependencySelector)m=[y.defaultDependencySelector(l,S,y),[]];else if(typeof l!="object")m=[[l],[]];else{const g=[],B=[];for(const T of p.current)T in l&&g.push(l[T]);for(const T of M.current)if(T in y)try{const w=y[T];typeof w!="function"&&B.push(w)}catch(w){E.Blac.instance.log("useBloc Error",w)}p.current.size===0&&M.current.size===0&&(K.current||g.push(l)),m=[g,B]}return D.current=l,m},[]),u=c.useRef(new Map),x=c.useMemo(()=>({subscribe:l=>{const C=v.current;if(!C)return()=>{};const y=u.current.get(l);if(y)return y.unsubscribe;const S={fn:()=>{try{!d&&!C.defaultDependencySelector&&(p.current=new Set,M.current=new Set),l(C.state)}catch(B){console.error({e:B,blocInstance:C,dependencyArray:h})}},dependencyArray:h,id:n};E.Blac.activateBloc(C);const m=C._observer.subscribe(S),g=()=>{u.current.delete(l),m()};return u.current.set(l,{observer:S,unsubscribe:g}),g},getSnapshot:()=>{const l=v.current;if(!l)return{};const C=l.state,y=h(C,D.current),S=A.current;let m=!1;if(!S)m=!0;else if(S.length!==y.length)m=!0;else for(let g=0;g<y.length;g++){const B=S[g]||[],T=y[g]||[];if(B.length!==T.length){m=!0;break}for(let w=0;w<T.length;w++)if(!Object.is(B[w],T[w])){m=!0;break}if(m)break}return A.current=y,!m&&R.current?R.current:(R.current=C,C)},getServerSnapshot:()=>{const l=v.current;return l?l.state:{}}}),[]);return{usedKeys:p,usedClassPropKeys:M,externalStore:x,instance:v,rid:n,hasProxyTracking:K}};class F{constructor(e={}){b(this,"stateKeys",new Set);b(this,"classKeys",new Set);b(this,"batchedCallbacks",new Set);b(this,"flushScheduled",!1);b(this,"flushTimeoutId");b(this,"metrics",{stateAccessCount:0,classAccessCount:0,proxyCreationCount:0,batchFlushCount:0,averageResolutionTime:0,memoryUsageKB:0});b(this,"resolutionTimes",[]);b(this,"config");b(this,"stateProxyCache",new WeakMap);b(this,"classProxyCache",new WeakMap);b(this,"lastStateSnapshot",null);b(this,"lastClassSnapshot",null);this.config={enableBatching:!0,batchTimeout:0,enableMetrics:process.env.NODE_ENV==="development",maxCacheSize:1e3,enableDeepTracking:!1,...e}}trackStateAccess(e){this.config.enableMetrics&&this.metrics.stateAccessCount++,this.stateKeys.add(e),this.config.enableBatching&&this.scheduleFlush()}trackClassAccess(e){this.config.enableMetrics&&this.metrics.classAccessCount++,this.classKeys.add(e),this.config.enableBatching&&this.scheduleFlush()}createStateProxy(e,s){const f=this.stateProxyCache.get(e);if(f)return f;const d=this.config.enableMetrics?performance.now():0,n=new Proxy(e,{get:(r,o)=>{typeof o=="string"&&(this.trackStateAccess(o),s==null||s(o));const a=r[o];return this.config.enableDeepTracking&&a&&typeof a=="object"&&!Array.isArray(a)?this.createStateProxy(a):a},has:(r,o)=>o in r,ownKeys:r=>Reflect.ownKeys(r),getOwnPropertyDescriptor:(r,o)=>Reflect.getOwnPropertyDescriptor(r,o)});if(this.stateProxyCache.set(e,n),this.config.enableMetrics){this.metrics.proxyCreationCount++;const r=performance.now();this.resolutionTimes.push(r-d),this.updateAverageResolutionTime()}return n}createClassProxy(e,s){const f=this.classProxyCache.get(e);if(f)return f;const d=this.config.enableMetrics?performance.now():0,n=new Proxy(e,{get:(r,o)=>{const a=r[o];return typeof o=="string"&&typeof a!="function"&&(this.trackClassAccess(o),s==null||s(o)),a}});if(this.classProxyCache.set(e,n),this.config.enableMetrics){this.metrics.proxyCreationCount++;const r=performance.now();this.resolutionTimes.push(r-d),this.updateAverageResolutionTime()}return n}getStateKeys(){return new Set(this.stateKeys)}getClassKeys(){return new Set(this.classKeys)}reset(){this.stateKeys.clear(),this.classKeys.clear(),this.cancelScheduledFlush()}subscribe(e){return this.batchedCallbacks.add(e),()=>{this.batchedCallbacks.delete(e)}}computeDependencyArray(e,s){const f=this.config.enableMetrics?performance.now():0;if(typeof e!="object"||e===null)return[[e]];const d=[];for(const r of this.stateKeys)r in e&&d.push(e[r]);const n=[];for(const r of this.classKeys)if(r in s)try{const o=s[r];typeof o!="function"&&n.push(o)}catch{}if(this.config.enableMetrics){const r=performance.now();this.resolutionTimes.push(r-f),this.updateAverageResolutionTime()}return d.length===0&&n.length===0?[[]]:n.length===0?[d]:d.length===0?[n]:[d,n]}getMetrics(){if(!this.config.enableMetrics)return{stateAccessCount:0,classAccessCount:0,proxyCreationCount:0,batchFlushCount:0,averageResolutionTime:0,memoryUsageKB:0};const e=this.stateKeys.size*50+this.classKeys.size*50+(this.stateProxyCache instanceof WeakMap?100:0)+(this.classProxyCache instanceof WeakMap?100:0);return{...this.metrics,memoryUsageKB:Math.round(e/1024)}}clearCaches(){this.stateProxyCache=new WeakMap,this.classProxyCache=new WeakMap,this.resolutionTimes=[],this.config.enableMetrics&&(this.metrics={stateAccessCount:0,classAccessCount:0,proxyCreationCount:0,batchFlushCount:0,averageResolutionTime:0,memoryUsageKB:0})}scheduleFlush(){this.flushScheduled||(this.flushScheduled=!0,this.config.batchTimeout>0?this.flushTimeoutId=setTimeout(()=>{this.flushBatchedChanges()},this.config.batchTimeout):Promise.resolve().then(()=>this.flushBatchedChanges()))}cancelScheduledFlush(){this.flushTimeoutId&&(clearTimeout(this.flushTimeoutId),this.flushTimeoutId=void 0),this.flushScheduled=!1}flushBatchedChanges(){if(!this.flushScheduled)return;this.flushScheduled=!1,this.flushTimeoutId=void 0,this.config.enableMetrics&&this.metrics.batchFlushCount++;const e=new Set([...this.stateKeys,...this.classKeys]);for(const s of this.batchedCallbacks)try{s(e)}catch(f){console.error("Error in dependency change callback:",f)}}updateAverageResolutionTime(){if(this.resolutionTimes.length===0)return;this.resolutionTimes.length>100&&(this.resolutionTimes=this.resolutionTimes.slice(-100));const e=this.resolutionTimes.reduce((s,f)=>s+f,0);this.metrics.averageResolutionTime=e/this.resolutionTimes.length}}function z(i){return new F(i)}z();function $(i,e){var A,R;const{externalStore:s,usedKeys:f,usedClassPropKeys:d,instance:n,rid:r,hasProxyTracking:o}=O(i,e),a=c.useSyncExternalStore(s.subscribe,()=>{const t=s.getSnapshot();if(t===void 0)throw new Error(`[useBloc] State snapshot is undefined for bloc ${i.name}. Bloc may not be properly initialized.`);return t},s.getServerSnapshot?()=>{const t=s.getServerSnapshot();if(t===void 0)throw new Error(`[useBloc] Server state snapshot is undefined for bloc ${i.name}. Bloc may not be properly initialized.`);return t}:void 0),p=c.useRef(null);p.current||(p.current=new F({enableBatching:!0,enableMetrics:process.env.NODE_ENV==="development",enableDeepTracking:!1}));const M=c.useRef(new WeakMap),K=c.useRef(new WeakMap),P=c.useMemo(()=>{if(e!=null&&e.selector||(o.current=!0,typeof a!="object"||a===null))return a;let t=M.current.get(a);return t||(t=new Proxy(a,{get(h,u){var k;return typeof u=="string"&&(f.current.add(u),(k=p.current)==null||k.trackStateAccess(u)),h[u]},has(h,u){return u in h},ownKeys(h){return Reflect.ownKeys(h)},getOwnPropertyDescriptor(h,u){return Reflect.getOwnPropertyDescriptor(h,u)}}),M.current.set(a,t)),t},[a]),v=c.useMemo(()=>{if(!n.current)throw new Error(`[useBloc] Bloc instance is null for ${i.name}. This should never happen - bloc instance must be defined.`);let t=K.current.get(n.current);return t||(t=new Proxy(n.current,{get(h,u){var k;if(!h)throw new Error(`[useBloc] Bloc target is null for ${i.name}. This should never happen - bloc target must be defined.`);const x=h[u];return typeof x!="function"&&typeof u=="string"&&(d.current.add(u),(k=p.current)==null||k.trackClassAccess(u)),x}}),K.current.set(n.current,t)),t},[(A=n.current)==null?void 0:A.uid]),D=c.useRef({});if(c.useEffect(()=>{var h;const t=n.current;if(t)return t._addConsumer(r,D.current),(h=e==null?void 0:e.onMount)==null||h.call(e,t),()=>{var u,x;t&&((u=e==null?void 0:e.onUnmount)==null||u.call(e,t),t._removeConsumer(r),(x=p.current)==null||x.reset())}},[(R=n.current)==null?void 0:R.uid,r]),c.useEffect(()=>{if(process.env.NODE_ENV==="development"&&p.current){const t=p.current.getMetrics();(t.stateAccessCount>0||t.classAccessCount>0)&&console.debug(`[useBloc] ${i.name} Performance Metrics:`,t)}}),P===void 0)throw new Error(`[useBloc] State is undefined for ${i.name}. This should never happen - state must be defined.`);if(!v)throw new Error(`[useBloc] Instance is null for ${i.name}. This should never happen - instance must be defined.`);return[P,v]}exports.externalBlocStore=O;exports.useBloc=$;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.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":"iIA0CMA,EAAuB,CAG3BC,EACAC,IACyB,OACzB,KAAM,CAAE,GAAIC,EAAQ,MAAAC,EAAO,SAAAC,CAAS,EAAIH,GAAW,CAAC,EAE9CI,EAAMC,EAAAA,QAAQ,IACXC,eAAa,EACnB,EAAE,EAKCC,EAHOR,EAEW,SACaK,EAAMH,EAErCO,EAAWC,EAAAA,OAAwB,IAAA,GAAK,EACxCC,EAAoBD,EAAAA,OAAwB,IAAA,GAAK,EAEjDE,EAAUC,EAAAA,YAAY,IACnBC,EAAA,KAAK,QAAQd,EAAM,CACxB,GAAIQ,EACJ,MAAAL,EACA,YAAaE,CAAA,CACd,EACA,CAACL,EAAMQ,EAAiBL,EAAOE,CAAG,CAAC,EAEhCU,EAAeL,SAAwBE,GAAS,EAGtDN,EAAAA,QAAQ,IAAM,CACZS,EAAa,QAAUH,EAAQ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AAA7B,EAAqByB,GACrBA,EAAgB,gBAAgBrB,CAAG,EACrC,GACC,EAACwC,EAAA3B,EAAS,UAAT,YAAA2B,EAAkB,IAAKxC,CAAG,CAAC,EAG3BiC,IAAgB,OAClB,MAAM,IAAI,MAAM,oCAAoCtC,EAAK,IAAI,qDAAqD,EAEpH,GAAI,CAAC0C,EACH,MAAM,IAAI,MAAM,kCAAkC1C,EAAK,IAAI,wDAAwD,EAI9G,MAAA,CAACsC,EAAaI,CAAW,CAClC"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/useExternalBlocStore.ts","../src/DependencyTracker.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 hasProxyTracking: React.RefObject<boolean>;\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 // Track whether proxy-based dependency tracking has been initialized\n // This helps distinguish between direct external store usage and useBloc proxy usage\n const hasProxyTracking = useRef<boolean>(false);\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 // Track previous state and dependencies for selector\n const previousStateRef = useRef<BlocState<InstanceType<B>> | undefined>(undefined);\n const lastDependenciesRef = useRef<unknown[][] | undefined>(undefined);\n const lastStableSnapshot = useRef<BlocState<InstanceType<B>> | undefined>(undefined);\n \n // Track bloc instance uid to prevent unnecessary store recreation\n const blocUidRef = useRef<string | undefined>(undefined);\n if (blocUidRef.current !== blocInstance.current?.uid) {\n blocUidRef.current = blocInstance.current?.uid;\n }\n\n const dependencyArray = useMemo(\n () =>\n (newState: BlocState<InstanceType<B>>, oldState?: BlocState<InstanceType<B>>): unknown[][] => {\n const instance = blocInstance.current;\n\n if (!instance) {\n return [[], []]; // [stateArray, classArray]\n }\n\n // Use the provided oldState or fall back to our tracked previous state\n const previousState = oldState ?? previousStateRef.current;\n \n let currentDependencies: unknown[][];\n\n // Use custom dependency selector if provided\n if (selector) {\n const flatDeps = selector(newState, previousState, instance);\n // Wrap flat custom selector result in the two-array structure for consistency\n currentDependencies = [flatDeps, []]; // [customSelectorDeps, classArray]\n }\n // Fall back to bloc's default dependency selector if available\n else if (instance.defaultDependencySelector) {\n const flatDeps = instance.defaultDependencySelector(newState, previousState, instance);\n // Wrap flat default selector result in the two-array structure for consistency\n currentDependencies = [flatDeps, []]; // [defaultSelectorDeps, classArray]\n }\n // For primitive states, use default selector\n else if (typeof newState !== 'object') {\n // Default behavior for primitive states: re-render if the state itself changes.\n currentDependencies = [[newState], []]; // [primitiveStateArray, classArray]\n }\n else {\n // For object states, track which properties were actually used\n const stateDependencies: unknown[] = [];\n const classDependencies: unknown[] = [];\n \n // Add state property values that were accessed\n for (const key of usedKeys.current) {\n if (key in newState) {\n stateDependencies.push(newState[key as keyof typeof newState]);\n }\n }\n\n // Add class property values that were accessed\n for (const key of usedClassPropKeys.current) {\n if (key in instance) {\n try {\n const value = instance[key as keyof InstanceType<B>];\n if (typeof value !== 'function') {\n classDependencies.push(value);\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n }\n }\n\n // If no properties have been accessed through proxy\n if (usedKeys.current.size === 0 && usedClassPropKeys.current.size === 0) {\n // If proxy tracking has never been initialized, this is direct external store usage\n // In this case, always track the entire state to ensure notifications\n if (!hasProxyTracking.current) {\n stateDependencies.push(newState);\n }\n // If proxy tracking was initialized but no properties accessed, \n // return empty dependencies to prevent unnecessary re-renders\n }\n\n currentDependencies = [stateDependencies, classDependencies];\n }\n\n // Update tracked state\n previousStateRef.current = newState;\n\n\n // Return the dependencies for BlacObserver to compare\n return currentDependencies;\n },\n [],\n );\n\n // Store active subscriptions to reuse observers\n const activeObservers = useRef<Map<Function, { observer: BlacObserver<BlocState<InstanceType<B>>>, unsubscribe: () => void }>>(new Map());\n\n const state: ExternalStore<B> = useMemo(() => {\n return {\n subscribe: (listener: (state: BlocState<InstanceType<B>>) => void) => {\n \n const currentInstance = blocInstance.current;\n if (!currentInstance) {\n return () => {}; // Return no-op if no instance\n }\n\n // Check if we already have an observer for this listener\n const existing = activeObservers.current.get(listener);\n if (existing) {\n return existing.unsubscribe;\n }\n const observer: BlacObserver<BlocState<InstanceType<B>>> = {\n fn: () => {\n try {\n \n // Only reset dependency tracking if we're not using a custom selector\n // Custom selectors override proxy-based tracking entirely\n if (!selector && !currentInstance.defaultDependencySelector) {\n usedKeys.current = new Set();\n usedClassPropKeys.current = new Set();\n }\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 const unsubscribe = () => {\n activeObservers.current.delete(listener);\n unSub();\n };\n\n // Store the observer and unsubscribe function\n activeObservers.current.set(listener, { observer, unsubscribe });\n\n // Return an unsubscribe function that can be called to clean up the subscription\n return unsubscribe;\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\n const currentState = instance.state;\n const currentDependencies = dependencyArray(currentState, previousStateRef.current);\n \n // Check if dependencies have changed using the two-array comparison logic\n const lastDeps = lastDependenciesRef.current;\n let dependenciesChanged = false;\n \n if (!lastDeps) {\n // First time - dependencies changed\n dependenciesChanged = true;\n } else if (lastDeps.length !== currentDependencies.length) {\n // Array structure changed\n dependenciesChanged = true;\n } else {\n // Compare each array (state and class dependencies)\n for (let arrayIndex = 0; arrayIndex < currentDependencies.length; arrayIndex++) {\n const lastArray = lastDeps[arrayIndex] || [];\n const newArray = currentDependencies[arrayIndex] || [];\n \n if (lastArray.length !== newArray.length) {\n dependenciesChanged = true;\n break;\n }\n \n // Compare each dependency value using Object.is\n for (let i = 0; i < newArray.length; i++) {\n if (!Object.is(lastArray[i], newArray[i])) {\n dependenciesChanged = true;\n break;\n }\n }\n \n if (dependenciesChanged) break;\n }\n }\n \n // Update dependency tracking\n lastDependenciesRef.current = currentDependencies;\n \n // If dependencies haven't changed, return the same snapshot reference\n // This prevents React from re-rendering when dependencies are stable\n if (!dependenciesChanged && lastStableSnapshot.current) {\n return lastStableSnapshot.current;\n }\n \n // Dependencies changed - update and return new snapshot\n lastStableSnapshot.current = currentState;\n return currentState;\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 }, []); // Store is stable - individual methods handle instance changes\n\n return {\n usedKeys,\n usedClassPropKeys,\n externalStore: state,\n instance: blocInstance,\n rid,\n hasProxyTracking,\n };\n};\n\nexport default useExternalBlocStore;\n","\nexport interface DependencyMetrics {\n stateAccessCount: number;\n classAccessCount: number;\n proxyCreationCount: number;\n batchFlushCount: number;\n averageResolutionTime: number;\n memoryUsageKB: number;\n}\n\nexport interface DependencyTrackerConfig {\n enableBatching: boolean;\n batchTimeout: number;\n enableMetrics: boolean;\n maxCacheSize: number;\n enableDeepTracking: boolean;\n}\n\nexport type DependencyChangeCallback = (changedKeys: Set<string>) => void;\n\nexport class DependencyTracker {\n private stateKeys = new Set<string>();\n private classKeys = new Set<string>();\n private batchedCallbacks = new Set<DependencyChangeCallback>();\n private flushScheduled = false;\n private flushTimeoutId: ReturnType<typeof setTimeout> | undefined;\n \n private metrics: DependencyMetrics = {\n stateAccessCount: 0,\n classAccessCount: 0,\n proxyCreationCount: 0,\n batchFlushCount: 0,\n averageResolutionTime: 0,\n memoryUsageKB: 0,\n };\n \n private resolutionTimes: number[] = [];\n \n private config: DependencyTrackerConfig;\n \n private stateProxyCache = new WeakMap<object, object>();\n private classProxyCache = new WeakMap<object, object>();\n \n private lastStateSnapshot: unknown = null;\n private lastClassSnapshot: unknown = null;\n \n constructor(config: Partial<DependencyTrackerConfig> = {}) {\n this.config = {\n enableBatching: true,\n batchTimeout: 0, // Use React's scheduler\n enableMetrics: process.env.NODE_ENV === 'development',\n maxCacheSize: 1000,\n enableDeepTracking: false,\n ...config,\n };\n }\n\n public trackStateAccess(key: string): void {\n if (this.config.enableMetrics) {\n this.metrics.stateAccessCount++;\n }\n \n this.stateKeys.add(key);\n \n if (this.config.enableBatching) {\n this.scheduleFlush();\n }\n }\n\n public trackClassAccess(key: string): void {\n if (this.config.enableMetrics) {\n this.metrics.classAccessCount++;\n }\n \n this.classKeys.add(key);\n \n if (this.config.enableBatching) {\n this.scheduleFlush();\n }\n }\n\n public createStateProxy<T extends object>(target: T, onAccess?: (prop: string) => void): T {\n const cachedProxy = this.stateProxyCache.get(target);\n if (cachedProxy) {\n return cachedProxy as T;\n }\n\n const startTime = this.config.enableMetrics ? performance.now() : 0;\n\n const proxy = new Proxy(target, {\n get: (obj: T, prop: string | symbol) => {\n if (typeof prop === 'string') {\n this.trackStateAccess(prop);\n onAccess?.(prop);\n }\n \n const value = obj[prop as keyof T];\n \n if (\n this.config.enableDeepTracking &&\n value &&\n typeof value === 'object' &&\n !Array.isArray(value)\n ) {\n return this.createStateProxy(value as object);\n }\n \n return value;\n },\n \n has: (obj: T, prop: string | symbol) => {\n return prop in obj;\n },\n \n ownKeys: (obj: T) => {\n return Reflect.ownKeys(obj);\n },\n \n getOwnPropertyDescriptor: (obj: T, prop: string | symbol) => {\n return Reflect.getOwnPropertyDescriptor(obj, prop);\n },\n });\n\n this.stateProxyCache.set(target, proxy);\n \n if (this.config.enableMetrics) {\n this.metrics.proxyCreationCount++;\n const endTime = performance.now();\n this.resolutionTimes.push(endTime - startTime);\n this.updateAverageResolutionTime();\n }\n\n return proxy;\n }\n\n public createClassProxy<T extends object>(target: T, onAccess?: (prop: string) => void): T {\n const cachedProxy = this.classProxyCache.get(target);\n if (cachedProxy) {\n return cachedProxy as T;\n }\n\n const startTime = this.config.enableMetrics ? performance.now() : 0;\n\n const proxy = new Proxy(target, {\n get: (obj: T, prop: string | symbol) => {\n const value = obj[prop as keyof T];\n \n if (typeof prop === 'string' && typeof value !== 'function') {\n this.trackClassAccess(prop);\n onAccess?.(prop);\n }\n \n return value;\n },\n });\n\n this.classProxyCache.set(target, proxy);\n \n if (this.config.enableMetrics) {\n this.metrics.proxyCreationCount++;\n const endTime = performance.now();\n this.resolutionTimes.push(endTime - startTime);\n this.updateAverageResolutionTime();\n }\n\n return proxy;\n }\n\n public getStateKeys(): Set<string> {\n return new Set(this.stateKeys);\n }\n\n public getClassKeys(): Set<string> {\n return new Set(this.classKeys);\n }\n\n public reset(): void {\n this.stateKeys.clear();\n this.classKeys.clear();\n this.cancelScheduledFlush();\n }\n\n public subscribe(callback: DependencyChangeCallback): () => void {\n this.batchedCallbacks.add(callback);\n \n return () => {\n this.batchedCallbacks.delete(callback);\n };\n }\n\n public computeDependencyArray<TState, TClass>(\n state: TState,\n classInstance: TClass,\n ): unknown[] {\n const startTime = this.config.enableMetrics ? performance.now() : 0;\n \n if (typeof state !== 'object' || state === null) {\n return [[state]];\n }\n\n const stateValues: unknown[] = [];\n for (const key of this.stateKeys) {\n if (key in (state as object)) {\n stateValues.push((state as any)[key]);\n }\n }\n\n const classValues: unknown[] = [];\n for (const key of this.classKeys) {\n if (key in (classInstance as object)) {\n try {\n const value = (classInstance as any)[key];\n if (typeof value !== 'function') {\n classValues.push(value);\n }\n } catch (error) {\n }\n }\n }\n\n if (this.config.enableMetrics) {\n const endTime = performance.now();\n this.resolutionTimes.push(endTime - startTime);\n this.updateAverageResolutionTime();\n }\n\n if (stateValues.length === 0 && classValues.length === 0) {\n return [[]];\n }\n \n if (classValues.length === 0) {\n return [stateValues];\n }\n \n if (stateValues.length === 0) {\n return [classValues];\n }\n \n return [stateValues, classValues];\n }\n\n public getMetrics(): DependencyMetrics {\n if (!this.config.enableMetrics) {\n return {\n stateAccessCount: 0,\n classAccessCount: 0,\n proxyCreationCount: 0,\n batchFlushCount: 0,\n averageResolutionTime: 0,\n memoryUsageKB: 0,\n };\n }\n\n const estimatedMemory = \n (this.stateKeys.size * 50) +\n (this.classKeys.size * 50) +\n (this.stateProxyCache instanceof WeakMap ? 100 : 0) +\n (this.classProxyCache instanceof WeakMap ? 100 : 0);\n\n return {\n ...this.metrics,\n memoryUsageKB: Math.round(estimatedMemory / 1024),\n };\n }\n\n public clearCaches(): void {\n this.stateProxyCache = new WeakMap();\n this.classProxyCache = new WeakMap();\n this.resolutionTimes = [];\n \n if (this.config.enableMetrics) {\n this.metrics = {\n stateAccessCount: 0,\n classAccessCount: 0,\n proxyCreationCount: 0,\n batchFlushCount: 0,\n averageResolutionTime: 0,\n memoryUsageKB: 0,\n };\n }\n }\n\n private scheduleFlush(): void {\n if (this.flushScheduled) {\n return;\n }\n\n this.flushScheduled = true;\n\n if (this.config.batchTimeout > 0) {\n this.flushTimeoutId = setTimeout(() => {\n this.flushBatchedChanges();\n }, this.config.batchTimeout);\n } else {\n Promise.resolve().then(() => this.flushBatchedChanges());\n }\n }\n\n private cancelScheduledFlush(): void {\n if (this.flushTimeoutId) {\n clearTimeout(this.flushTimeoutId);\n this.flushTimeoutId = undefined;\n }\n this.flushScheduled = false;\n }\n\n private flushBatchedChanges(): void {\n if (!this.flushScheduled) {\n return;\n }\n\n this.flushScheduled = false;\n this.flushTimeoutId = undefined;\n\n if (this.config.enableMetrics) {\n this.metrics.batchFlushCount++;\n }\n\n const allChangedKeys = new Set([...this.stateKeys, ...this.classKeys]);\n \n for (const callback of this.batchedCallbacks) {\n try {\n callback(allChangedKeys);\n } catch (error) {\n console.error('Error in dependency change callback:', error);\n }\n }\n }\n\n private updateAverageResolutionTime(): void {\n if (this.resolutionTimes.length === 0) {\n return;\n }\n\n if (this.resolutionTimes.length > 100) {\n this.resolutionTimes = this.resolutionTimes.slice(-100);\n }\n\n const sum = this.resolutionTimes.reduce((a, b) => a + b, 0);\n this.metrics.averageResolutionTime = sum / this.resolutionTimes.length;\n }\n}\n\nexport function createDependencyTracker(\n config?: Partial<DependencyTrackerConfig>,\n): DependencyTracker {\n return new DependencyTracker(config);\n}\n\nexport const defaultDependencyTracker = createDependencyTracker();","import {\n BlocBase,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport useExternalBlocStore from './useExternalBlocStore';\nimport { DependencyTracker } from './DependencyTracker';\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 const {\n externalStore,\n usedKeys,\n usedClassPropKeys,\n instance,\n rid,\n hasProxyTracking,\n } = useExternalBlocStore(bloc, options);\n\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n externalStore.subscribe,\n () => {\n const snapshot = externalStore.getSnapshot();\n if (snapshot === undefined) {\n throw new Error(\n `[useBloc] State snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`,\n );\n }\n return snapshot;\n },\n externalStore.getServerSnapshot\n ? () => {\n const serverSnapshot = externalStore.getServerSnapshot!();\n if (serverSnapshot === undefined) {\n throw new Error(\n `[useBloc] Server state snapshot is undefined for bloc ${bloc.name}. Bloc may not be properly initialized.`,\n );\n }\n return serverSnapshot;\n }\n : undefined,\n );\n\n const dependencyTracker = useRef<DependencyTracker | null>(null);\n if (!dependencyTracker.current) {\n dependencyTracker.current = new DependencyTracker({\n enableBatching: true,\n enableMetrics: process.env.NODE_ENV === 'development',\n enableDeepTracking: false,\n });\n }\n\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 a custom selector is provided, don't use proxy tracking\n if (options?.selector) {\n return state;\n }\n\n hasProxyTracking.current = true;\n\n if (typeof state !== 'object' || state === null) {\n return state;\n }\n\n let proxy = stateProxyCache.current.get(state);\n if (!proxy) {\n proxy = new Proxy(state, {\n get(target, prop) {\n if (typeof prop === 'string') {\n usedKeys.current.add(prop);\n dependencyTracker.current?.trackStateAccess(prop);\n }\n const value = target[prop as keyof typeof target];\n return value;\n },\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(\n `[useBloc] Bloc instance is null for ${bloc.name}. This should never happen - bloc instance must be defined.`,\n );\n }\n\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(\n `[useBloc] Bloc target is null for ${bloc.name}. This should never happen - bloc target must be defined.`,\n );\n }\n const value = target[prop as keyof InstanceType<B>];\n if (typeof value !== 'function' && typeof prop === 'string') {\n usedClassPropKeys.current.add(prop);\n dependencyTracker.current?.trackClassAccess(prop);\n }\n return value;\n },\n });\n classProxyCache.current.set(instance.current, proxy);\n }\n return proxy;\n }, [instance.current?.uid]);\n\n const componentRef = useRef({});\n\n useEffect(() => {\n const currentInstance = instance.current;\n if (!currentInstance) return;\n\n currentInstance._addConsumer(rid, componentRef.current);\n\n options?.onMount?.(currentInstance);\n\n return () => {\n if (!currentInstance) {\n return;\n }\n options?.onUnmount?.(currentInstance);\n currentInstance._removeConsumer(rid);\n\n dependencyTracker.current?.reset();\n };\n }, [instance.current?.uid, rid]);\n useEffect(() => {\n if (process.env.NODE_ENV === 'development' && dependencyTracker.current) {\n const metrics = dependencyTracker.current.getMetrics();\n if (metrics.stateAccessCount > 0 || metrics.classAccessCount > 0) {\n console.debug(`[useBloc] ${bloc.name} Performance Metrics:`, metrics);\n }\n }\n });\n\n if (returnState === undefined) {\n throw new Error(\n `[useBloc] State is undefined for ${bloc.name}. This should never happen - state must be defined.`,\n );\n }\n if (!returnClass) {\n throw new Error(\n `[useBloc] Instance is null for ${bloc.name}. This should never happen - instance must be defined.`,\n );\n }\n\n return [returnState, returnClass] as [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n ];\n}\n"],"names":["useExternalBlocStore","bloc","options","blocId","props","selector","rid","useMemo","generateUUID","effectiveBlocId","usedKeys","useRef","usedClassPropKeys","hasProxyTracking","getBloc","useCallback","Blac","blocInstance","previousStateRef","lastDependenciesRef","lastStableSnapshot","blocUidRef","_a","_b","dependencyArray","newState","oldState","instance","previousState","currentDependencies","stateDependencies","classDependencies","key","value","error","activeObservers","state","listener","currentInstance","existing","observer","e","unSub","unsubscribe","currentState","lastDeps","dependenciesChanged","arrayIndex","lastArray","newArray","i","DependencyTracker","config","__publicField","target","onAccess","cachedProxy","startTime","proxy","obj","prop","endTime","callback","classInstance","stateValues","classValues","estimatedMemory","allChangedKeys","sum","a","b","createDependencyTracker","useBloc","externalStore","useSyncExternalStore","snapshot","serverSnapshot","dependencyTracker","stateProxyCache","classProxyCache","returnState","returnClass","componentRef","useEffect","metrics"],"mappings":"qSA2CMA,EAAuB,CAG3BC,EACAC,IACyB,SACzB,KAAM,CAAE,GAAIC,EAAQ,MAAAC,EAAO,SAAAC,CAAS,EAAIH,GAAW,CAAC,EAE9CI,EAAMC,EAAAA,QAAQ,IACXC,eAAa,EACnB,EAAE,EAKCC,EAHOR,EAEW,SACaK,EAAMH,EAErCO,EAAWC,EAAAA,OAAwB,IAAA,GAAK,EACxCC,EAAoBD,EAAAA,OAAwB,IAAA,GAAK,EAIjDE,EAAmBF,SAAgB,EAAK,EAExCG,EAAUC,EAAAA,YAAY,IACnBC,EAAA,KAAK,QAAQf,EAAM,CACxB,GAAIQ,EACJ,MAAAL,EACA,YAAaE,CAAA,CACd,EACA,CAACL,EAAMQ,EAAiBL,EAAOE,CAAG,CAAC,EAEhCW,EAAeN,SAAwBG,GAAS,EAGtDP,EAAAA,QAAQ,IAAM,CACZU,EAAa,QAAUH,EAAQ,CAAA,EAC9B,CAACA,CAAO,CAAC,EAGN,MAAAI,EAAmBP,SAA+C,MAAS,EAC3EQ,EAAsBR,SAAgC,MAAS,EAC/DS,EAAqBT,SAA+C,MAAS,EAG7EU,EAAaV,SAA2B,MAAS,EACnDU,EAAW,YAAYC,EAAAL,EAAa,UAAb,YAAAK,EAAsB,OACpCD,EAAA,SAAUE,EAAAN,EAAa,UAAb,YAAAM,EAAsB,KAG7C,MAAMC,EAAkBjB,EAAA,QACtB,IACE,CAACkB,EAAsCC,IAAuD,CAC5F,MAAMC,EAAWV,EAAa,QAE9B,GAAI,CAACU,EACH,MAAO,CAAC,CAAI,EAAA,EAAE,EAIV,MAAAC,EAAgBF,GAAYR,EAAiB,QAE/C,IAAAW,EAGJ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