@blac/react 0.1.1 → 2.0.0
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/LICENSE +21 -0
- package/README.md +195 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +99 -0
- package/dist/index.es.js +116 -0
- package/dist/index.es.js.map +1 -0
- package/package.json +51 -19
- package/src/externalBlocStore.ts +93 -0
- package/src/index.ts +4 -0
- package/src/useBloc.tsx +261 -0
- package/dist/blac-react.mjs +0 -104
- package/dist/blac-react.umd.js +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) Facebook, Inc. and its affiliates.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# @blac/react
|
|
2
|
+
|
|
3
|
+
A powerful React integration for the Blac state management library, providing seamless integration between React components and Blac's reactive state management system.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🔄 Automatic re-rendering when relevant state changes
|
|
8
|
+
- 🎯 Fine-grained dependency tracking
|
|
9
|
+
- 🔍 Property access tracking for optimized updates
|
|
10
|
+
- 🎨 TypeScript support with full type inference
|
|
11
|
+
- ⚡️ Efficient state management with minimal boilerplate
|
|
12
|
+
- 🔄 Support for isolated and shared bloc instances
|
|
13
|
+
- 🎯 Custom dependency selectors for precise control
|
|
14
|
+
|
|
15
|
+
## Important: Arrow Functions Required
|
|
16
|
+
|
|
17
|
+
All methods in Bloc or Cubit classes must use arrow function syntax (`method = () => {}`) instead of the traditional method syntax (`method() {}`). This is because arrow functions automatically bind `this` to the class instance. Without this binding, methods called from React components would lose their context and could not access instance properties like `this.state` or `this.emit()`.
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
// Correct way to define methods in your Bloc/Cubit classes
|
|
21
|
+
class CounterBloc extends Cubit<CounterState> {
|
|
22
|
+
increment = () => {
|
|
23
|
+
this.emit({ ...this.state, count: this.state.count + 1 });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
decrement = () => {
|
|
27
|
+
this.emit({ ...this.state, count: this.state.count - 1 });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Incorrect way (will cause issues when called from React):
|
|
32
|
+
class CounterBloc extends Cubit<CounterState> {
|
|
33
|
+
increment() { // ❌ Will lose 'this' context when called from components
|
|
34
|
+
this.emit({ ...this.state, count: this.state.count + 1 });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm install @blac/react
|
|
43
|
+
# or
|
|
44
|
+
yarn add @blac/react
|
|
45
|
+
# or
|
|
46
|
+
pnpm add @blac/react
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
```tsx
|
|
52
|
+
import { useBloc } from '@blac/react';
|
|
53
|
+
import { CounterBloc } from './CounterBloc';
|
|
54
|
+
|
|
55
|
+
function Counter() {
|
|
56
|
+
const [state, counterBloc] = useBloc(CounterBloc);
|
|
57
|
+
|
|
58
|
+
return (
|
|
59
|
+
<div>
|
|
60
|
+
<p>Count: {state.count}</p>
|
|
61
|
+
<button onClick={() => counterBloc.increment()}>Increment</button>
|
|
62
|
+
</div>
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Usage
|
|
68
|
+
|
|
69
|
+
### Basic Usage
|
|
70
|
+
|
|
71
|
+
The `useBloc` hook provides a simple way to connect your React components to Blac's state management system:
|
|
72
|
+
|
|
73
|
+
```tsx
|
|
74
|
+
const [state, bloc] = useBloc(YourBloc);
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Advanced Configuration
|
|
78
|
+
|
|
79
|
+
The hook accepts configuration options for more control:
|
|
80
|
+
|
|
81
|
+
```tsx
|
|
82
|
+
const [state, bloc] = useBloc(YourBloc, {
|
|
83
|
+
id: 'custom-id', // Optional: Custom identifier for the bloc
|
|
84
|
+
props: { /* ... */ }, // Optional: Props to pass to the bloc
|
|
85
|
+
onMount: (bloc) => { /* ... */ }, // Optional: Callback when bloc is mounted (similar to useEffect(<>, []))
|
|
86
|
+
dependencySelector: (newState, oldState) => [/* ... */], // Optional: Custom dependency tracking
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Dependency Tracking
|
|
91
|
+
|
|
92
|
+
The hook automatically tracks which state properties are accessed in your component and only triggers re-renders when those specific properties change:
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
function UserProfile() {
|
|
96
|
+
const [state, userBloc] = useBloc(UserBloc);
|
|
97
|
+
|
|
98
|
+
// Only re-renders when state.name changes
|
|
99
|
+
return <h1>{state.name}</h1>;
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
This also works for getters on the Bloc or Cubit class:
|
|
104
|
+
|
|
105
|
+
```tsx
|
|
106
|
+
function UserProfile() {
|
|
107
|
+
const [, userBloc] = useBloc(UserBloc);
|
|
108
|
+
|
|
109
|
+
// Only re-renders when the return value from the getter formattedName changes
|
|
110
|
+
return <h1>{userBloc.formattedName}</h1>;
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Custom Dependency Selector
|
|
115
|
+
|
|
116
|
+
For more control over when your component re-renders, you can provide a custom dependency selector:
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
const [state, bloc] = useBloc(YourBloc, {
|
|
120
|
+
dependencySelector: (newState, oldState) => [
|
|
121
|
+
newState.specificField,
|
|
122
|
+
newState.anotherField
|
|
123
|
+
]
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## API Reference
|
|
128
|
+
|
|
129
|
+
### useBloc Hook
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
function useBloc<B extends BlocConstructor<BlocGeneric>>(
|
|
133
|
+
bloc: B,
|
|
134
|
+
options?: BlocHookOptions<InstanceType<B>>
|
|
135
|
+
): [BlocState<InstanceType<B>>, InstanceType<B>]
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
#### Options
|
|
139
|
+
|
|
140
|
+
- `id?: string` - Custom identifier for the bloc instance
|
|
141
|
+
- `props?: InferPropsFromGeneric<B>` - Props to pass to the bloc
|
|
142
|
+
- `onMount?: (bloc: B) => void` - Callback function invoked when the react component (the consumer) is connected to the bloc instance
|
|
143
|
+
- `dependencySelector?: BlocHookDependencyArrayFn<B>` - Function to select dependencies for re-renders
|
|
144
|
+
|
|
145
|
+
## Best Practices
|
|
146
|
+
|
|
147
|
+
1. **Use Isolated Blocs**: When you need component-specific state, use isolated blocs:
|
|
148
|
+
```tsx
|
|
149
|
+
class MyIsolatedBloc extends BlocBase {
|
|
150
|
+
static isolated = true;
|
|
151
|
+
// ... rest of your bloc implementation
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
2. **Use Custom Identifiers**: When you need multiple independent instances of the same Bloc type, use custom identifiers to manage different state contexts:
|
|
156
|
+
```tsx
|
|
157
|
+
// In a chat application with multiple chat rooms
|
|
158
|
+
function ChatRoom({ roomId }: { roomId: string }) {
|
|
159
|
+
const [state, chatBloc] = useBloc(ChatBloc, {
|
|
160
|
+
id: `chat-${roomId}`, // Each room gets its own instance
|
|
161
|
+
props: { roomId }
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
return (
|
|
165
|
+
<div>
|
|
166
|
+
<h2>Room: {roomId}</h2>
|
|
167
|
+
{state.messages.map(msg => (
|
|
168
|
+
<Message key={msg.id} message={msg} />
|
|
169
|
+
))}
|
|
170
|
+
</div>
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Usage:
|
|
175
|
+
function ChatApp() {
|
|
176
|
+
return (
|
|
177
|
+
<div>
|
|
178
|
+
<ChatRoom roomId="general" />
|
|
179
|
+
<ChatRoom roomId="support" />
|
|
180
|
+
</div>
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
3. **Optimize Re-renders**: Let the hook track dependencies automatically unless you have a specific need for custom dependency tracking.
|
|
186
|
+
|
|
187
|
+
4. **Type Safety**: Take advantage of TypeScript's type inference for better development experience and catch errors early.
|
|
188
|
+
|
|
189
|
+
## Contributing
|
|
190
|
+
|
|
191
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
MIT
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("@blac/core"),n=require("react"),E=(u,r,i)=>{const o=u;return{subscribe:B=>{const s=o._observer.subscribe({fn:()=>{try{B(o.state)}catch(l){console.error({e:l,resolvedBloc:u,dependencyArray:r})}},dependencyArray:r,id:i});return()=>{s()}},getSnapshot:()=>o.state,getServerSnapshot:()=>o.state}},M=E;function _(u,r){const{dependencySelector:i,id:o,props:B}=r??{},s=n.useMemo(()=>Math.random().toString(36),[]),l=n.useRef(new Set),g=n.useRef(new Set),R=n.useRef(new Set),h=n.useRef(new Set),I={},m=u.isolated?s:o,b=n.useRef(null);n.useMemo(()=>{b.current=S.Blac.getBloc(u,{id:m,props:B,instanceRef:s})},[u,m,s]);const t=b.current;if(!t)throw new Error(`useBloc: could not resolve bloc: ${u.name||u}`);s===t._instanceRef&&(r!=null&&r.props)&&S.Blac.instance.findRegisteredBlocInstance(u,m)===t&&t.props!==r.props&&(t.props=r.props);const p=(e,c)=>{if(i)return i(e,c);if(t.defaultDependencySelector)return t.defaultDependencySelector(e,c);if(typeof e!="object")return[[e]];const a=[];for(const d of l.current)d in e&&a.push(e[d]);const w=[];for(const d of R.current)if(d in t)try{const y=t[d];switch(typeof y){case"function":continue;default:w.push(y);continue}}catch(y){S.Blac.instance.log("useBloc Error",y)}return setTimeout(()=>{g.current=new Set,h.current=new Set}),[a,w]},v=n.useMemo(()=>M(t,p,s),[t,s]),f=n.useSyncExternalStore(v.subscribe,v.getSnapshot,v.getServerSnapshot),x=n.useMemo(()=>{try{if(typeof f=="object")return new Proxy(f,{get(e,c){return g.current.add(c),l.current.add(c),f[c]}})}catch(e){S.Blac.instance.log("useBloc Error",e)}return f},[f]),C=n.useMemo(()=>new Proxy(t,{get(e,c){const a=t[c];return typeof a!="function"&&h.current.add(c),a}}),[t]);return n.useLayoutEffect(()=>{l.current=new Set(g.current),R.current=new Set(h.current)},[I]),n.useEffect(()=>{var c;const e=b.current;if(e)return e._addConsumer(s),(c=r==null?void 0:r.onMount)==null||c.call(r,e),()=>{e._removeConsumer(s)}},[u,s]),[x,C]}exports.externalBlocStore=M;exports.useBloc=_;
|
|
2
|
+
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/externalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BlocBase, BlocConstructor, BlocHookDependencyArrayFn, BlocState } from '@blac/core';\n\n/**\n * Interface defining an external store that can be used to subscribe to and access bloc state.\n * This interface follows the React external store pattern for state management.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n */\nexport interface ExternalStore<\n B extends InstanceType<BlocConstructor<any>>\n> {\n /**\n * Subscribes to changes in the store and returns an unsubscribe function.\n * @param onStoreChange - Callback function that will be called whenever the store changes\n * @returns A function that can be called to unsubscribe from store changes\n */\n subscribe: (onStoreChange: (state: BlocState<B>) => void) => () => void;\n\n /**\n * Gets the current snapshot of the store state.\n * @returns The current state of the store\n */\n getSnapshot: () => BlocState<B>;\n\n /**\n * Gets the server snapshot of the store state.\n * This is optional and defaults to the same value as getSnapshot.\n * @returns The server state of the store\n */\n getServerSnapshot?: () => BlocState<B>;\n}\n\n/**\n * Creates an external store that wraps a Bloc instance, providing a React-compatible interface\n * for subscribing to and accessing bloc state.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n * @param bloc - The Bloc instance to wrap\n * @param dependencyArray - Function that returns an array of dependencies for the subscription\n * @param rid - Unique identifier for the subscription\n * @returns An ExternalStore instance that provides methods to subscribe to and access bloc state\n */\nconst externalBlocStore = <\n B extends InstanceType<BlocConstructor<any>>\n>(\n resolvedBloc: B,\n dependencyArray: BlocHookDependencyArrayFn<BlocState<B>>,\n rid: string,\n): ExternalStore<B> => {\n // TODO: Revisit this type assertion. Ideally, 'resolvedBloc' should conform to a type\n // that guarantees '_observer' and 'state' properties without needing 'as unknown as ...'.\n // This might require adjustments in the core @blac/core types.\n const asBlocBase = resolvedBloc as unknown as BlocBase<BlocState<B>>;\n return {\n subscribe: (listener: (state: BlocState<B>) => void) => {\n // Subscribe to the bloc's observer with the provided listener function\n // This will trigger the callback whenever the bloc's state changes\n const unSub = asBlocBase._observer.subscribe({\n fn: () => {\n try {\n listener(asBlocBase.state);\n } catch (e) {\n // Log any errors that occur during the listener callback\n // This ensures errors in listeners don't break the entire application\n console.error({\n e,\n resolvedBloc,\n dependencyArray,\n });\n }\n },\n // Pass the dependency array to control when the subscription is updated\n dependencyArray,\n // Use the provided id to identify this subscription\n id: rid,\n });\n\n // Return an unsubscribe function that can be called to clean up the subscription\n return () => {\n unSub();\n };\n },\n // Return an immutable snapshot of the current bloc state\n getSnapshot: (): BlocState<B> => asBlocBase.state,\n // Server snapshot mirrors the client snapshot in this implementation\n getServerSnapshot: (): BlocState<B> => asBlocBase.state,\n };\n};\n\nexport default externalBlocStore;\n","/* eslint-disable @typescript-eslint/restrict-template-expressions */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Blac,\n BlocBase,\n BlocBaseAbstract,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport externalBlocStore from './externalBlocStore';\n\n/**\n * Type definition for the return type of the useBloc hook\n * @template B - Bloc constructor type\n */\ntype HookTypes<B extends BlocConstructor<BlocBase<any>>> = [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n];\n\n/**\n * Configuration options for the useBloc hook\n * @template B - Bloc generic type\n * @property {string} [id] - Optional identifier for the Bloc instance\n * @property {BlocHookDependencyArrayFn<B>} [dependencySelector] - Function to select dependencies for re-renders\n * @property {InferPropsFromGeneric<B>} [props] - Props to pass to the Bloc\n * @property {(bloc: B) => void} [onMount] - Callback function invoked when the Bloc is mounted\n */\nexport interface BlocHookOptions<B extends BlocBase<any>> {\n id?: string;\n dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n}\n\n/**\n * Default dependency selector that wraps the entire state in an array\n * @template T - State type\n * @param {T} s - Current state\n * @returns {Array<Array<T>>} Dependency array containing the entire state\n */\n\n/**\n * React hook for integrating with Blac state management\n *\n * This hook connects a React component to a Bloc state container, providing\n * automatic re-rendering when relevant state changes, dependency tracking,\n * and proper lifecycle management.\n *\n * @template B - Bloc constructor type\n * @template O - BlocHookOptions type\n * @param {B} bloc - Bloc constructor class\n * @param {O} [options] - Configuration options for the hook\n * @returns {HookTypes<B>} Tuple containing [state, bloc instance]\n *\n * @example\n * const [state, counterBloc] = useBloc(CounterBloc);\n * // Access state\n * console.log(state.count);\n * // Call bloc methods\n * counterBloc.increment();\n */\nexport default function useBloc<B extends BlocConstructor<BlocBase<any>>>(\n bloc: B,\n options?: BlocHookOptions<InstanceType<B>>,\n): HookTypes<B> {\n const { dependencySelector, id: blocId, props } = options ?? {};\n const rid = useMemo(() => {\n return Math.random().toString(36);\n }, []);\n\n // Track used state keys\n const usedKeys = useRef<Set<string>>(new Set());\n const instanceKeys = useRef<Set<string>>(new Set());\n\n // Track used class properties\n const usedClassPropKeys = useRef<Set<string>>(new Set());\n const instanceClassPropKeys = useRef<Set<string>>(new Set());\n\n const renderInstance = {};\n\n // Determine ID for isolated or shared blocs\n const base = bloc as unknown as BlocBaseAbstract;\n const isIsolated = base.isolated;\n const effectiveBlocId = isIsolated ? rid : blocId;\n\n // Use useRef to hold the bloc instance reference consistently across renders\n const blocRef = useRef<InstanceType<B> | null>(null);\n\n // Initialize or get the bloc instance ONCE using useMemo based on the effective ID\n // This avoids re-running Blac.getBloc on every render.\n useMemo(() => {\n blocRef.current = Blac.getBloc(bloc, {\n id: effectiveBlocId,\n props,\n instanceRef: rid, // Pass component ID for consumer tracking\n });\n }, [bloc, effectiveBlocId, rid]); // Dependencies ensure this runs only when bloc type or ID changes\n\n const resolvedBloc = blocRef.current;\n\n if (!resolvedBloc) {\n // This should ideally not happen if Blac.getBloc works correctly\n throw new Error(`useBloc: could not resolve bloc: ${bloc.name || bloc}`);\n }\n\n // Update props ONLY if this hook instance created the bloc (or is the designated main instance)\n // We rely on Blac.getBloc to handle initial props correctly during creation.\n // Subsequent calls should not overwrite props.\n // Check if this instanceRef matches the one stored on the bloc when it was created/first retrieved.\n if (\n rid === resolvedBloc._instanceRef &&\n options?.props &&\n Blac.instance.findRegisteredBlocInstance(bloc, effectiveBlocId) ===\n resolvedBloc\n ) {\n // Avoid double-setting props if Blac.getBloc already set them during creation\n if (resolvedBloc.props !== options.props) {\n resolvedBloc.props = options.props;\n }\n }\n\n // Configure dependency tracking for re-renders\n const dependencyArray: BlocHookDependencyArrayFn<BlocState<InstanceType<B>>> = (\n newState,\n oldState,\n ): ReturnType<BlocHookDependencyArrayFn<BlocState<InstanceType<B>>>> => {\n // Use custom dependency selector if provided\n if (dependencySelector) {\n return dependencySelector(newState, oldState);\n }\n\n // Fall back to bloc's default dependency selector if available\n if (resolvedBloc.defaultDependencySelector) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return resolvedBloc.defaultDependencySelector(newState, oldState);\n }\n\n // For primitive states, use default selector\n if (typeof newState !== 'object') {\n // Default behavior for primitive states: re-render if the state itself changes.\n return [[newState]];\n }\n\n // For object states, track which properties were actually used\n const usedStateValues: string[] = [];\n for (const key of usedKeys.current) {\n if (key in newState) {\n usedStateValues.push(newState[key as keyof typeof newState]);\n }\n }\n\n // Track used class properties for dependency tracking, this enables rerenders when class getters change\n const usedClassValues: unknown[] = [];\n for (const key of usedClassPropKeys.current) {\n if (key in resolvedBloc) {\n try {\n const value = resolvedBloc[key as keyof InstanceType<B>];\n switch (typeof value) {\n case 'function':\n continue;\n default:\n usedClassValues.push(value);\n continue;\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n }\n }\n\n setTimeout(() => {\n instanceKeys.current = new Set();\n instanceClassPropKeys.current = new Set();\n });\n return [usedStateValues, usedClassValues];\n };\n\n // Set up external store subscription for state updates\n const store = useMemo(\n () => externalBlocStore(resolvedBloc, dependencyArray, rid),\n [resolvedBloc, rid],\n ); // dependencyArray removed as it changes frequently\n\n // Subscribe to state changes using React's external store API\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n store.subscribe,\n store.getSnapshot,\n store.getServerSnapshot,\n );\n\n // Create a proxy for state to track property access\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const returnState: BlocState<InstanceType<B>> = useMemo(() => {\n try {\n if (typeof state === 'object') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return new Proxy(state as any, {\n get(_, prop) {\n instanceKeys.current.add(prop as string);\n usedKeys.current.add(prop as string);\n const value = state[prop as keyof typeof state];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n },\n });\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n return state;\n }, [state]);\n\n // Create a proxy for the bloc instance to track property access\n const returnClass = useMemo(() => {\n return new Proxy(resolvedBloc, {\n get(_, prop) {\n const value = resolvedBloc[prop as keyof InstanceType<B>];\n // Track which class properties are accessed (excluding methods)\n if (typeof value !== 'function') {\n instanceClassPropKeys.current.add(prop as string);\n }\n return value;\n },\n });\n }, [resolvedBloc]);\n\n // Clean up tracked keys after each render\n useLayoutEffect(() => {\n // inherit the keys from the previous render\n usedKeys.current = new Set(instanceKeys.current);\n usedClassPropKeys.current = new Set(instanceClassPropKeys.current);\n }, [renderInstance]);\n\n // Set up bloc lifecycle management\n useEffect(() => {\n const currentBlocInstance = blocRef.current; // Capture instance for cleanup\n if (!currentBlocInstance) return;\n\n currentBlocInstance._addConsumer(rid);\n\n // Call onMount callback if provided\n options?.onMount?.(currentBlocInstance);\n\n // Cleanup: remove this component as a consumer using the captured instance\n return () => {\n currentBlocInstance._removeConsumer(rid);\n };\n }, [bloc, rid]); // Do not add options.onMount to deps, it will cause a loop\n\n return [returnState, returnClass];\n}\n"],"names":["externalBlocStore","resolvedBloc","dependencyArray","rid","asBlocBase","listener","unSub","e","externalBlocStore$1","useBloc","bloc","options","dependencySelector","blocId","props","useMemo","usedKeys","useRef","instanceKeys","usedClassPropKeys","instanceClassPropKeys","renderInstance","effectiveBlocId","blocRef","Blac","newState","oldState","usedStateValues","key","usedClassValues","value","error","store","state","useSyncExternalStore","returnState","_","prop","returnClass","useLayoutEffect","useEffect","currentBlocInstance","_a"],"mappings":"iIA6CMA,EAAoB,CAGxBC,EACAC,EACAC,IACqB,CAIrB,MAAMC,EAAaH,EACZ,MAAA,CACL,UAAYI,GAA4C,CAGhD,MAAAC,EAAQF,EAAW,UAAU,UAAU,CAC3C,GAAI,IAAM,CACJ,GAAA,CACFC,EAASD,EAAW,KAAK,QAClBG,EAAG,CAGV,QAAQ,MAAM,CACZ,EAAAA,EACA,aAAAN,EACA,gBAAAC,CAAA,CACD,CACH,CACF,EAEA,gBAAAA,EAEA,GAAIC,CAAA,CACL,EAGD,MAAO,IAAM,CACLG,GAAA,CAEV,EAEA,YAAa,IAAoBF,EAAW,MAE5C,kBAAmB,IAAoBA,EAAW,KAAA,CAEtD,EAEAI,EAAeR,ECrBS,SAAAS,EACtBC,EACAC,EACc,CACd,KAAM,CAAE,mBAAAC,EAAoB,GAAIC,EAAQ,MAAAC,CAAM,EAAIH,GAAW,GACvDR,EAAMY,EAAAA,QAAQ,IACX,KAAK,OAAA,EAAS,SAAS,EAAE,EAC/B,CAAE,CAAA,EAGCC,EAAWC,EAAAA,OAAwB,IAAA,GAAK,EACxCC,EAAeD,EAAAA,OAAwB,IAAA,GAAK,EAG5CE,EAAoBF,EAAAA,OAAwB,IAAA,GAAK,EACjDG,EAAwBH,EAAAA,OAAwB,IAAA,GAAK,EAErDI,EAAiB,CAAA,EAKjBC,EAFOZ,EACW,SACaP,EAAMU,EAGrCU,EAA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BlocConstructor } from '@blac/core';
|
|
3
|
+
import { BlocHookDependencyArrayFn } from '@blac/core';
|
|
4
|
+
import { BlocState } from '@blac/core';
|
|
5
|
+
import { InferPropsFromGeneric } from '@blac/core';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Configuration options for the useBloc hook
|
|
9
|
+
* @template B - Bloc generic type
|
|
10
|
+
* @property {string} [id] - Optional identifier for the Bloc instance
|
|
11
|
+
* @property {BlocHookDependencyArrayFn<B>} [dependencySelector] - Function to select dependencies for re-renders
|
|
12
|
+
* @property {InferPropsFromGeneric<B>} [props] - Props to pass to the Bloc
|
|
13
|
+
* @property {(bloc: B) => void} [onMount] - Callback function invoked when the Bloc is mounted
|
|
14
|
+
*/
|
|
15
|
+
declare interface BlocHookOptions<B extends BlocBase<any>> {
|
|
16
|
+
id?: string;
|
|
17
|
+
dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;
|
|
18
|
+
props?: InferPropsFromGeneric<B>;
|
|
19
|
+
onMount?: (bloc: B) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Creates an external store that wraps a Bloc instance, providing a React-compatible interface
|
|
24
|
+
* for subscribing to and accessing bloc state.
|
|
25
|
+
*
|
|
26
|
+
* @template B - The type of the Bloc instance
|
|
27
|
+
* @template S - The type of the Bloc state
|
|
28
|
+
* @param bloc - The Bloc instance to wrap
|
|
29
|
+
* @param dependencyArray - Function that returns an array of dependencies for the subscription
|
|
30
|
+
* @param rid - Unique identifier for the subscription
|
|
31
|
+
* @returns An ExternalStore instance that provides methods to subscribe to and access bloc state
|
|
32
|
+
*/
|
|
33
|
+
export declare const externalBlocStore: <B extends InstanceType<BlocConstructor<any>>>(resolvedBloc: B, dependencyArray: BlocHookDependencyArrayFn<BlocState<B>>, rid: string) => ExternalStore<B>;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Interface defining an external store that can be used to subscribe to and access bloc state.
|
|
37
|
+
* This interface follows the React external store pattern for state management.
|
|
38
|
+
*
|
|
39
|
+
* @template B - The type of the Bloc instance
|
|
40
|
+
* @template S - The type of the Bloc state
|
|
41
|
+
*/
|
|
42
|
+
declare interface ExternalStore<B extends InstanceType<BlocConstructor<any>>> {
|
|
43
|
+
/**
|
|
44
|
+
* Subscribes to changes in the store and returns an unsubscribe function.
|
|
45
|
+
* @param onStoreChange - Callback function that will be called whenever the store changes
|
|
46
|
+
* @returns A function that can be called to unsubscribe from store changes
|
|
47
|
+
*/
|
|
48
|
+
subscribe: (onStoreChange: (state: BlocState<B>) => void) => () => void;
|
|
49
|
+
/**
|
|
50
|
+
* Gets the current snapshot of the store state.
|
|
51
|
+
* @returns The current state of the store
|
|
52
|
+
*/
|
|
53
|
+
getSnapshot: () => BlocState<B>;
|
|
54
|
+
/**
|
|
55
|
+
* Gets the server snapshot of the store state.
|
|
56
|
+
* This is optional and defaults to the same value as getSnapshot.
|
|
57
|
+
* @returns The server state of the store
|
|
58
|
+
*/
|
|
59
|
+
getServerSnapshot?: () => BlocState<B>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Type definition for the return type of the useBloc hook
|
|
64
|
+
* @template B - Bloc constructor type
|
|
65
|
+
*/
|
|
66
|
+
declare type HookTypes<B extends BlocConstructor<BlocBase<any>>> = [
|
|
67
|
+
BlocState<InstanceType<B>>,
|
|
68
|
+
InstanceType<B>
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Default dependency selector that wraps the entire state in an array
|
|
73
|
+
* @template T - State type
|
|
74
|
+
* @param {T} s - Current state
|
|
75
|
+
* @returns {Array<Array<T>>} Dependency array containing the entire state
|
|
76
|
+
*/
|
|
77
|
+
/**
|
|
78
|
+
* React hook for integrating with Blac state management
|
|
79
|
+
*
|
|
80
|
+
* This hook connects a React component to a Bloc state container, providing
|
|
81
|
+
* automatic re-rendering when relevant state changes, dependency tracking,
|
|
82
|
+
* and proper lifecycle management.
|
|
83
|
+
*
|
|
84
|
+
* @template B - Bloc constructor type
|
|
85
|
+
* @template O - BlocHookOptions type
|
|
86
|
+
* @param {B} bloc - Bloc constructor class
|
|
87
|
+
* @param {O} [options] - Configuration options for the hook
|
|
88
|
+
* @returns {HookTypes<B>} Tuple containing [state, bloc instance]
|
|
89
|
+
*
|
|
90
|
+
* @example
|
|
91
|
+
* const [state, counterBloc] = useBloc(CounterBloc);
|
|
92
|
+
* // Access state
|
|
93
|
+
* console.log(state.count);
|
|
94
|
+
* // Call bloc methods
|
|
95
|
+
* counterBloc.increment();
|
|
96
|
+
*/
|
|
97
|
+
export declare function useBloc<B extends BlocConstructor<BlocBase<any>>>(bloc: B, options?: BlocHookOptions<InstanceType<B>>): HookTypes<B>;
|
|
98
|
+
|
|
99
|
+
export { }
|
package/dist/index.es.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { Blac as B } from "@blac/core";
|
|
2
|
+
import { useMemo as d, useRef as i, useSyncExternalStore as R, useLayoutEffect as K, useEffect as P } from "react";
|
|
3
|
+
const M = (s, r, y) => {
|
|
4
|
+
const u = s;
|
|
5
|
+
return {
|
|
6
|
+
subscribe: (h) => {
|
|
7
|
+
const c = u._observer.subscribe({
|
|
8
|
+
fn: () => {
|
|
9
|
+
try {
|
|
10
|
+
h(u.state);
|
|
11
|
+
} catch (a) {
|
|
12
|
+
console.error({
|
|
13
|
+
e: a,
|
|
14
|
+
resolvedBloc: s,
|
|
15
|
+
dependencyArray: r
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
// Pass the dependency array to control when the subscription is updated
|
|
20
|
+
dependencyArray: r,
|
|
21
|
+
// Use the provided id to identify this subscription
|
|
22
|
+
id: y
|
|
23
|
+
});
|
|
24
|
+
return () => {
|
|
25
|
+
c();
|
|
26
|
+
};
|
|
27
|
+
},
|
|
28
|
+
// Return an immutable snapshot of the current bloc state
|
|
29
|
+
getSnapshot: () => u.state,
|
|
30
|
+
// Server snapshot mirrors the client snapshot in this implementation
|
|
31
|
+
getServerSnapshot: () => u.state
|
|
32
|
+
};
|
|
33
|
+
}, j = M;
|
|
34
|
+
function L(s, r) {
|
|
35
|
+
const { dependencySelector: y, id: u, props: h } = r ?? {}, c = d(() => Math.random().toString(36), []), a = i(/* @__PURE__ */ new Set()), g = i(/* @__PURE__ */ new Set()), w = i(/* @__PURE__ */ new Set()), m = i(/* @__PURE__ */ new Set()), I = {}, v = s.isolated ? c : u, b = i(null);
|
|
36
|
+
d(() => {
|
|
37
|
+
b.current = B.getBloc(s, {
|
|
38
|
+
id: v,
|
|
39
|
+
props: h,
|
|
40
|
+
instanceRef: c
|
|
41
|
+
// Pass component ID for consumer tracking
|
|
42
|
+
});
|
|
43
|
+
}, [s, v, c]);
|
|
44
|
+
const t = b.current;
|
|
45
|
+
if (!t)
|
|
46
|
+
throw new Error(`useBloc: could not resolve bloc: ${s.name || s}`);
|
|
47
|
+
c === t._instanceRef && (r != null && r.props) && B.instance.findRegisteredBlocInstance(s, v) === t && t.props !== r.props && (t.props = r.props);
|
|
48
|
+
const C = (e, n) => {
|
|
49
|
+
if (y)
|
|
50
|
+
return y(e, n);
|
|
51
|
+
if (t.defaultDependencySelector)
|
|
52
|
+
return t.defaultDependencySelector(e, n);
|
|
53
|
+
if (typeof e != "object")
|
|
54
|
+
return [[e]];
|
|
55
|
+
const o = [];
|
|
56
|
+
for (const l of a.current)
|
|
57
|
+
l in e && o.push(e[l]);
|
|
58
|
+
const x = [];
|
|
59
|
+
for (const l of w.current)
|
|
60
|
+
if (l in t)
|
|
61
|
+
try {
|
|
62
|
+
const S = t[l];
|
|
63
|
+
switch (typeof S) {
|
|
64
|
+
case "function":
|
|
65
|
+
continue;
|
|
66
|
+
default:
|
|
67
|
+
x.push(S);
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
} catch (S) {
|
|
71
|
+
B.instance.log("useBloc Error", S);
|
|
72
|
+
}
|
|
73
|
+
return setTimeout(() => {
|
|
74
|
+
g.current = /* @__PURE__ */ new Set(), m.current = /* @__PURE__ */ new Set();
|
|
75
|
+
}), [o, x];
|
|
76
|
+
}, p = d(
|
|
77
|
+
() => j(t, C, c),
|
|
78
|
+
[t, c]
|
|
79
|
+
), f = R(
|
|
80
|
+
p.subscribe,
|
|
81
|
+
p.getSnapshot,
|
|
82
|
+
p.getServerSnapshot
|
|
83
|
+
), E = d(() => {
|
|
84
|
+
try {
|
|
85
|
+
if (typeof f == "object")
|
|
86
|
+
return new Proxy(f, {
|
|
87
|
+
get(e, n) {
|
|
88
|
+
return g.current.add(n), a.current.add(n), f[n];
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
} catch (e) {
|
|
92
|
+
B.instance.log("useBloc Error", e);
|
|
93
|
+
}
|
|
94
|
+
return f;
|
|
95
|
+
}, [f]), _ = d(() => new Proxy(t, {
|
|
96
|
+
get(e, n) {
|
|
97
|
+
const o = t[n];
|
|
98
|
+
return typeof o != "function" && m.current.add(n), o;
|
|
99
|
+
}
|
|
100
|
+
}), [t]);
|
|
101
|
+
return K(() => {
|
|
102
|
+
a.current = new Set(g.current), w.current = new Set(m.current);
|
|
103
|
+
}, [I]), P(() => {
|
|
104
|
+
var n;
|
|
105
|
+
const e = b.current;
|
|
106
|
+
if (e)
|
|
107
|
+
return e._addConsumer(c), (n = r == null ? void 0 : r.onMount) == null || n.call(r, e), () => {
|
|
108
|
+
e._removeConsumer(c);
|
|
109
|
+
};
|
|
110
|
+
}, [s, c]), [E, _];
|
|
111
|
+
}
|
|
112
|
+
export {
|
|
113
|
+
j as externalBlocStore,
|
|
114
|
+
L as useBloc
|
|
115
|
+
};
|
|
116
|
+
//# sourceMappingURL=index.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/externalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BlocBase, BlocConstructor, BlocHookDependencyArrayFn, BlocState } from '@blac/core';\n\n/**\n * Interface defining an external store that can be used to subscribe to and access bloc state.\n * This interface follows the React external store pattern for state management.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n */\nexport interface ExternalStore<\n B extends InstanceType<BlocConstructor<any>>\n> {\n /**\n * Subscribes to changes in the store and returns an unsubscribe function.\n * @param onStoreChange - Callback function that will be called whenever the store changes\n * @returns A function that can be called to unsubscribe from store changes\n */\n subscribe: (onStoreChange: (state: BlocState<B>) => void) => () => void;\n\n /**\n * Gets the current snapshot of the store state.\n * @returns The current state of the store\n */\n getSnapshot: () => BlocState<B>;\n\n /**\n * Gets the server snapshot of the store state.\n * This is optional and defaults to the same value as getSnapshot.\n * @returns The server state of the store\n */\n getServerSnapshot?: () => BlocState<B>;\n}\n\n/**\n * Creates an external store that wraps a Bloc instance, providing a React-compatible interface\n * for subscribing to and accessing bloc state.\n * \n * @template B - The type of the Bloc instance\n * @template S - The type of the Bloc state\n * @param bloc - The Bloc instance to wrap\n * @param dependencyArray - Function that returns an array of dependencies for the subscription\n * @param rid - Unique identifier for the subscription\n * @returns An ExternalStore instance that provides methods to subscribe to and access bloc state\n */\nconst externalBlocStore = <\n B extends InstanceType<BlocConstructor<any>>\n>(\n resolvedBloc: B,\n dependencyArray: BlocHookDependencyArrayFn<BlocState<B>>,\n rid: string,\n): ExternalStore<B> => {\n // TODO: Revisit this type assertion. Ideally, 'resolvedBloc' should conform to a type\n // that guarantees '_observer' and 'state' properties without needing 'as unknown as ...'.\n // This might require adjustments in the core @blac/core types.\n const asBlocBase = resolvedBloc as unknown as BlocBase<BlocState<B>>;\n return {\n subscribe: (listener: (state: BlocState<B>) => void) => {\n // Subscribe to the bloc's observer with the provided listener function\n // This will trigger the callback whenever the bloc's state changes\n const unSub = asBlocBase._observer.subscribe({\n fn: () => {\n try {\n listener(asBlocBase.state);\n } catch (e) {\n // Log any errors that occur during the listener callback\n // This ensures errors in listeners don't break the entire application\n console.error({\n e,\n resolvedBloc,\n dependencyArray,\n });\n }\n },\n // Pass the dependency array to control when the subscription is updated\n dependencyArray,\n // Use the provided id to identify this subscription\n id: rid,\n });\n\n // Return an unsubscribe function that can be called to clean up the subscription\n return () => {\n unSub();\n };\n },\n // Return an immutable snapshot of the current bloc state\n getSnapshot: (): BlocState<B> => asBlocBase.state,\n // Server snapshot mirrors the client snapshot in this implementation\n getServerSnapshot: (): BlocState<B> => asBlocBase.state,\n };\n};\n\nexport default externalBlocStore;\n","/* eslint-disable @typescript-eslint/restrict-template-expressions */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n Blac,\n BlocBase,\n BlocBaseAbstract,\n BlocConstructor,\n BlocHookDependencyArrayFn,\n BlocState,\n InferPropsFromGeneric,\n} from '@blac/core';\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport externalBlocStore from './externalBlocStore';\n\n/**\n * Type definition for the return type of the useBloc hook\n * @template B - Bloc constructor type\n */\ntype HookTypes<B extends BlocConstructor<BlocBase<any>>> = [\n BlocState<InstanceType<B>>,\n InstanceType<B>,\n];\n\n/**\n * Configuration options for the useBloc hook\n * @template B - Bloc generic type\n * @property {string} [id] - Optional identifier for the Bloc instance\n * @property {BlocHookDependencyArrayFn<B>} [dependencySelector] - Function to select dependencies for re-renders\n * @property {InferPropsFromGeneric<B>} [props] - Props to pass to the Bloc\n * @property {(bloc: B) => void} [onMount] - Callback function invoked when the Bloc is mounted\n */\nexport interface BlocHookOptions<B extends BlocBase<any>> {\n id?: string;\n dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;\n props?: InferPropsFromGeneric<B>;\n onMount?: (bloc: B) => void;\n}\n\n/**\n * Default dependency selector that wraps the entire state in an array\n * @template T - State type\n * @param {T} s - Current state\n * @returns {Array<Array<T>>} Dependency array containing the entire state\n */\n\n/**\n * React hook for integrating with Blac state management\n *\n * This hook connects a React component to a Bloc state container, providing\n * automatic re-rendering when relevant state changes, dependency tracking,\n * and proper lifecycle management.\n *\n * @template B - Bloc constructor type\n * @template O - BlocHookOptions type\n * @param {B} bloc - Bloc constructor class\n * @param {O} [options] - Configuration options for the hook\n * @returns {HookTypes<B>} Tuple containing [state, bloc instance]\n *\n * @example\n * const [state, counterBloc] = useBloc(CounterBloc);\n * // Access state\n * console.log(state.count);\n * // Call bloc methods\n * counterBloc.increment();\n */\nexport default function useBloc<B extends BlocConstructor<BlocBase<any>>>(\n bloc: B,\n options?: BlocHookOptions<InstanceType<B>>,\n): HookTypes<B> {\n const { dependencySelector, id: blocId, props } = options ?? {};\n const rid = useMemo(() => {\n return Math.random().toString(36);\n }, []);\n\n // Track used state keys\n const usedKeys = useRef<Set<string>>(new Set());\n const instanceKeys = useRef<Set<string>>(new Set());\n\n // Track used class properties\n const usedClassPropKeys = useRef<Set<string>>(new Set());\n const instanceClassPropKeys = useRef<Set<string>>(new Set());\n\n const renderInstance = {};\n\n // Determine ID for isolated or shared blocs\n const base = bloc as unknown as BlocBaseAbstract;\n const isIsolated = base.isolated;\n const effectiveBlocId = isIsolated ? rid : blocId;\n\n // Use useRef to hold the bloc instance reference consistently across renders\n const blocRef = useRef<InstanceType<B> | null>(null);\n\n // Initialize or get the bloc instance ONCE using useMemo based on the effective ID\n // This avoids re-running Blac.getBloc on every render.\n useMemo(() => {\n blocRef.current = Blac.getBloc(bloc, {\n id: effectiveBlocId,\n props,\n instanceRef: rid, // Pass component ID for consumer tracking\n });\n }, [bloc, effectiveBlocId, rid]); // Dependencies ensure this runs only when bloc type or ID changes\n\n const resolvedBloc = blocRef.current;\n\n if (!resolvedBloc) {\n // This should ideally not happen if Blac.getBloc works correctly\n throw new Error(`useBloc: could not resolve bloc: ${bloc.name || bloc}`);\n }\n\n // Update props ONLY if this hook instance created the bloc (or is the designated main instance)\n // We rely on Blac.getBloc to handle initial props correctly during creation.\n // Subsequent calls should not overwrite props.\n // Check if this instanceRef matches the one stored on the bloc when it was created/first retrieved.\n if (\n rid === resolvedBloc._instanceRef &&\n options?.props &&\n Blac.instance.findRegisteredBlocInstance(bloc, effectiveBlocId) ===\n resolvedBloc\n ) {\n // Avoid double-setting props if Blac.getBloc already set them during creation\n if (resolvedBloc.props !== options.props) {\n resolvedBloc.props = options.props;\n }\n }\n\n // Configure dependency tracking for re-renders\n const dependencyArray: BlocHookDependencyArrayFn<BlocState<InstanceType<B>>> = (\n newState,\n oldState,\n ): ReturnType<BlocHookDependencyArrayFn<BlocState<InstanceType<B>>>> => {\n // Use custom dependency selector if provided\n if (dependencySelector) {\n return dependencySelector(newState, oldState);\n }\n\n // Fall back to bloc's default dependency selector if available\n if (resolvedBloc.defaultDependencySelector) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return resolvedBloc.defaultDependencySelector(newState, oldState);\n }\n\n // For primitive states, use default selector\n if (typeof newState !== 'object') {\n // Default behavior for primitive states: re-render if the state itself changes.\n return [[newState]];\n }\n\n // For object states, track which properties were actually used\n const usedStateValues: string[] = [];\n for (const key of usedKeys.current) {\n if (key in newState) {\n usedStateValues.push(newState[key as keyof typeof newState]);\n }\n }\n\n // Track used class properties for dependency tracking, this enables rerenders when class getters change\n const usedClassValues: unknown[] = [];\n for (const key of usedClassPropKeys.current) {\n if (key in resolvedBloc) {\n try {\n const value = resolvedBloc[key as keyof InstanceType<B>];\n switch (typeof value) {\n case 'function':\n continue;\n default:\n usedClassValues.push(value);\n continue;\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n }\n }\n\n setTimeout(() => {\n instanceKeys.current = new Set();\n instanceClassPropKeys.current = new Set();\n });\n return [usedStateValues, usedClassValues];\n };\n\n // Set up external store subscription for state updates\n const store = useMemo(\n () => externalBlocStore(resolvedBloc, dependencyArray, rid),\n [resolvedBloc, rid],\n ); // dependencyArray removed as it changes frequently\n\n // Subscribe to state changes using React's external store API\n const state = useSyncExternalStore<BlocState<InstanceType<B>>>(\n store.subscribe,\n store.getSnapshot,\n store.getServerSnapshot,\n );\n\n // Create a proxy for state to track property access\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n const returnState: BlocState<InstanceType<B>> = useMemo(() => {\n try {\n if (typeof state === 'object') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return new Proxy(state as any, {\n get(_, prop) {\n instanceKeys.current.add(prop as string);\n usedKeys.current.add(prop as string);\n const value = state[prop as keyof typeof state];\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value;\n },\n });\n }\n } catch (error) {\n Blac.instance.log('useBloc Error', error);\n }\n return state;\n }, [state]);\n\n // Create a proxy for the bloc instance to track property access\n const returnClass = useMemo(() => {\n return new Proxy(resolvedBloc, {\n get(_, prop) {\n const value = resolvedBloc[prop as keyof InstanceType<B>];\n // Track which class properties are accessed (excluding methods)\n if (typeof value !== 'function') {\n instanceClassPropKeys.current.add(prop as string);\n }\n return value;\n },\n });\n }, [resolvedBloc]);\n\n // Clean up tracked keys after each render\n useLayoutEffect(() => {\n // inherit the keys from the previous render\n usedKeys.current = new Set(instanceKeys.current);\n usedClassPropKeys.current = new Set(instanceClassPropKeys.current);\n }, [renderInstance]);\n\n // Set up bloc lifecycle management\n useEffect(() => {\n const currentBlocInstance = blocRef.current; // Capture instance for cleanup\n if (!currentBlocInstance) return;\n\n currentBlocInstance._addConsumer(rid);\n\n // Call onMount callback if provided\n options?.onMount?.(currentBlocInstance);\n\n // Cleanup: remove this component as a consumer using the captured instance\n return () => {\n currentBlocInstance._removeConsumer(rid);\n };\n }, [bloc, rid]); // Do not add options.onMount to deps, it will cause a loop\n\n return [returnState, returnClass];\n}\n"],"names":["externalBlocStore","resolvedBloc","dependencyArray","rid","asBlocBase","listener","unSub","e","externalBlocStore$1","useBloc","bloc","options","dependencySelector","blocId","props","useMemo","usedKeys","useRef","instanceKeys","usedClassPropKeys","instanceClassPropKeys","renderInstance","effectiveBlocId","blocRef","Blac","newState","oldState","usedStateValues","key","usedClassValues","value","error","store","state","useSyncExternalStore","returnState","_","prop","returnClass","useLayoutEffect","useEffect","current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
+
"version": "2.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"author": "Brendan Mullins <jsnanigans@gmail.com>",
|
|
6
|
+
"main": "dist/index.cjs.js",
|
|
7
|
+
"module": "dist/index.es.js",
|
|
8
|
+
"typings": "dist/index.d.ts",
|
|
9
|
+
"types": "dist/index.d.ts",
|
|
4
10
|
"files": [
|
|
5
|
-
"dist"
|
|
11
|
+
"dist",
|
|
12
|
+
"src",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
6
15
|
],
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"keywords": [
|
|
18
|
+
"react",
|
|
19
|
+
"typescript",
|
|
20
|
+
"rxjs",
|
|
21
|
+
"state-management",
|
|
22
|
+
"reactjs",
|
|
23
|
+
"observer-pattern",
|
|
24
|
+
"bloc",
|
|
25
|
+
"bloc-pattern"
|
|
26
|
+
],
|
|
27
|
+
"dependencies": {},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"react": "^18.0.0",
|
|
30
|
+
"@blac/core": "2.0.0"
|
|
17
31
|
},
|
|
18
|
-
"keywords": [],
|
|
19
|
-
"author": "",
|
|
20
|
-
"license": "ISC",
|
|
21
|
-
"description": "",
|
|
22
32
|
"devDependencies": {
|
|
23
|
-
"@
|
|
24
|
-
"
|
|
33
|
+
"@testing-library/dom": "^10.4.0",
|
|
34
|
+
"@testing-library/jest-dom": "^6.6.3",
|
|
35
|
+
"@testing-library/react": "^16.3.0",
|
|
36
|
+
"@testing-library/user-event": "^14.6.1",
|
|
37
|
+
"@types/react": "^18.3.3",
|
|
38
|
+
"@vitejs/plugin-react": "^4.4.1",
|
|
39
|
+
"@vitest/browser": "^3.1.3",
|
|
40
|
+
"@vitest/coverage-v8": "^3.1.3",
|
|
41
|
+
"happy-dom": "^17.4.7",
|
|
42
|
+
"jsdom": "^24.1.1",
|
|
43
|
+
"prettier": "^3.5.3",
|
|
44
|
+
"react-dom": "^18.0.0",
|
|
45
|
+
"typescript": "^5.8.3",
|
|
46
|
+
"vite": "^5.3.1",
|
|
47
|
+
"vite-plugin-dts": "^4.5.3",
|
|
48
|
+
"vitest": "^1.6.0"
|
|
49
|
+
},
|
|
50
|
+
"scripts": {
|
|
51
|
+
"prettier": "prettier --write ./src",
|
|
52
|
+
"test": "vitest run --config vitest.config.ts",
|
|
53
|
+
"test:watch": "vitest --watch --config vitest.config.ts",
|
|
54
|
+
"typecheck": "tsc --noEmit",
|
|
55
|
+
"build": "vite build",
|
|
56
|
+
"deploy": "pnpm run build && pnpm publish --access public"
|
|
25
57
|
}
|
|
26
|
-
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
+
import { BlocBase, BlocConstructor, BlocHookDependencyArrayFn, BlocState } from '@blac/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Interface defining an external store that can be used to subscribe to and access bloc state.
|
|
6
|
+
* This interface follows the React external store pattern for state management.
|
|
7
|
+
*
|
|
8
|
+
* @template B - The type of the Bloc instance
|
|
9
|
+
* @template S - The type of the Bloc state
|
|
10
|
+
*/
|
|
11
|
+
export interface ExternalStore<
|
|
12
|
+
B extends InstanceType<BlocConstructor<any>>
|
|
13
|
+
> {
|
|
14
|
+
/**
|
|
15
|
+
* Subscribes to changes in the store and returns an unsubscribe function.
|
|
16
|
+
* @param onStoreChange - Callback function that will be called whenever the store changes
|
|
17
|
+
* @returns A function that can be called to unsubscribe from store changes
|
|
18
|
+
*/
|
|
19
|
+
subscribe: (onStoreChange: (state: BlocState<B>) => void) => () => void;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Gets the current snapshot of the store state.
|
|
23
|
+
* @returns The current state of the store
|
|
24
|
+
*/
|
|
25
|
+
getSnapshot: () => BlocState<B>;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Gets the server snapshot of the store state.
|
|
29
|
+
* This is optional and defaults to the same value as getSnapshot.
|
|
30
|
+
* @returns The server state of the store
|
|
31
|
+
*/
|
|
32
|
+
getServerSnapshot?: () => BlocState<B>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Creates an external store that wraps a Bloc instance, providing a React-compatible interface
|
|
37
|
+
* for subscribing to and accessing bloc state.
|
|
38
|
+
*
|
|
39
|
+
* @template B - The type of the Bloc instance
|
|
40
|
+
* @template S - The type of the Bloc state
|
|
41
|
+
* @param bloc - The Bloc instance to wrap
|
|
42
|
+
* @param dependencyArray - Function that returns an array of dependencies for the subscription
|
|
43
|
+
* @param rid - Unique identifier for the subscription
|
|
44
|
+
* @returns An ExternalStore instance that provides methods to subscribe to and access bloc state
|
|
45
|
+
*/
|
|
46
|
+
const externalBlocStore = <
|
|
47
|
+
B extends InstanceType<BlocConstructor<any>>
|
|
48
|
+
>(
|
|
49
|
+
resolvedBloc: B,
|
|
50
|
+
dependencyArray: BlocHookDependencyArrayFn<BlocState<B>>,
|
|
51
|
+
rid: string,
|
|
52
|
+
): ExternalStore<B> => {
|
|
53
|
+
// TODO: Revisit this type assertion. Ideally, 'resolvedBloc' should conform to a type
|
|
54
|
+
// that guarantees '_observer' and 'state' properties without needing 'as unknown as ...'.
|
|
55
|
+
// This might require adjustments in the core @blac/core types.
|
|
56
|
+
const asBlocBase = resolvedBloc as unknown as BlocBase<BlocState<B>>;
|
|
57
|
+
return {
|
|
58
|
+
subscribe: (listener: (state: BlocState<B>) => void) => {
|
|
59
|
+
// Subscribe to the bloc's observer with the provided listener function
|
|
60
|
+
// This will trigger the callback whenever the bloc's state changes
|
|
61
|
+
const unSub = asBlocBase._observer.subscribe({
|
|
62
|
+
fn: () => {
|
|
63
|
+
try {
|
|
64
|
+
listener(asBlocBase.state);
|
|
65
|
+
} catch (e) {
|
|
66
|
+
// Log any errors that occur during the listener callback
|
|
67
|
+
// This ensures errors in listeners don't break the entire application
|
|
68
|
+
console.error({
|
|
69
|
+
e,
|
|
70
|
+
resolvedBloc,
|
|
71
|
+
dependencyArray,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
// Pass the dependency array to control when the subscription is updated
|
|
76
|
+
dependencyArray,
|
|
77
|
+
// Use the provided id to identify this subscription
|
|
78
|
+
id: rid,
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// Return an unsubscribe function that can be called to clean up the subscription
|
|
82
|
+
return () => {
|
|
83
|
+
unSub();
|
|
84
|
+
};
|
|
85
|
+
},
|
|
86
|
+
// Return an immutable snapshot of the current bloc state
|
|
87
|
+
getSnapshot: (): BlocState<B> => asBlocBase.state,
|
|
88
|
+
// Server snapshot mirrors the client snapshot in this implementation
|
|
89
|
+
getServerSnapshot: (): BlocState<B> => asBlocBase.state,
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export default externalBlocStore;
|
package/src/index.ts
ADDED
package/src/useBloc.tsx
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/* eslint-disable @typescript-eslint/restrict-template-expressions */
|
|
2
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
3
|
+
import {
|
|
4
|
+
Blac,
|
|
5
|
+
BlocBase,
|
|
6
|
+
BlocBaseAbstract,
|
|
7
|
+
BlocConstructor,
|
|
8
|
+
BlocHookDependencyArrayFn,
|
|
9
|
+
BlocState,
|
|
10
|
+
InferPropsFromGeneric,
|
|
11
|
+
} from '@blac/core';
|
|
12
|
+
import {
|
|
13
|
+
useEffect,
|
|
14
|
+
useLayoutEffect,
|
|
15
|
+
useMemo,
|
|
16
|
+
useRef,
|
|
17
|
+
useSyncExternalStore,
|
|
18
|
+
} from 'react';
|
|
19
|
+
import externalBlocStore from './externalBlocStore';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Type definition for the return type of the useBloc hook
|
|
23
|
+
* @template B - Bloc constructor type
|
|
24
|
+
*/
|
|
25
|
+
type HookTypes<B extends BlocConstructor<BlocBase<any>>> = [
|
|
26
|
+
BlocState<InstanceType<B>>,
|
|
27
|
+
InstanceType<B>,
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Configuration options for the useBloc hook
|
|
32
|
+
* @template B - Bloc generic type
|
|
33
|
+
* @property {string} [id] - Optional identifier for the Bloc instance
|
|
34
|
+
* @property {BlocHookDependencyArrayFn<B>} [dependencySelector] - Function to select dependencies for re-renders
|
|
35
|
+
* @property {InferPropsFromGeneric<B>} [props] - Props to pass to the Bloc
|
|
36
|
+
* @property {(bloc: B) => void} [onMount] - Callback function invoked when the Bloc is mounted
|
|
37
|
+
*/
|
|
38
|
+
export interface BlocHookOptions<B extends BlocBase<any>> {
|
|
39
|
+
id?: string;
|
|
40
|
+
dependencySelector?: BlocHookDependencyArrayFn<BlocState<B>>;
|
|
41
|
+
props?: InferPropsFromGeneric<B>;
|
|
42
|
+
onMount?: (bloc: B) => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Default dependency selector that wraps the entire state in an array
|
|
47
|
+
* @template T - State type
|
|
48
|
+
* @param {T} s - Current state
|
|
49
|
+
* @returns {Array<Array<T>>} Dependency array containing the entire state
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* React hook for integrating with Blac state management
|
|
54
|
+
*
|
|
55
|
+
* This hook connects a React component to a Bloc state container, providing
|
|
56
|
+
* automatic re-rendering when relevant state changes, dependency tracking,
|
|
57
|
+
* and proper lifecycle management.
|
|
58
|
+
*
|
|
59
|
+
* @template B - Bloc constructor type
|
|
60
|
+
* @template O - BlocHookOptions type
|
|
61
|
+
* @param {B} bloc - Bloc constructor class
|
|
62
|
+
* @param {O} [options] - Configuration options for the hook
|
|
63
|
+
* @returns {HookTypes<B>} Tuple containing [state, bloc instance]
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* const [state, counterBloc] = useBloc(CounterBloc);
|
|
67
|
+
* // Access state
|
|
68
|
+
* console.log(state.count);
|
|
69
|
+
* // Call bloc methods
|
|
70
|
+
* counterBloc.increment();
|
|
71
|
+
*/
|
|
72
|
+
export default function useBloc<B extends BlocConstructor<BlocBase<any>>>(
|
|
73
|
+
bloc: B,
|
|
74
|
+
options?: BlocHookOptions<InstanceType<B>>,
|
|
75
|
+
): HookTypes<B> {
|
|
76
|
+
const { dependencySelector, id: blocId, props } = options ?? {};
|
|
77
|
+
const rid = useMemo(() => {
|
|
78
|
+
return Math.random().toString(36);
|
|
79
|
+
}, []);
|
|
80
|
+
|
|
81
|
+
// Track used state keys
|
|
82
|
+
const usedKeys = useRef<Set<string>>(new Set());
|
|
83
|
+
const instanceKeys = useRef<Set<string>>(new Set());
|
|
84
|
+
|
|
85
|
+
// Track used class properties
|
|
86
|
+
const usedClassPropKeys = useRef<Set<string>>(new Set());
|
|
87
|
+
const instanceClassPropKeys = useRef<Set<string>>(new Set());
|
|
88
|
+
|
|
89
|
+
const renderInstance = {};
|
|
90
|
+
|
|
91
|
+
// Determine ID for isolated or shared blocs
|
|
92
|
+
const base = bloc as unknown as BlocBaseAbstract;
|
|
93
|
+
const isIsolated = base.isolated;
|
|
94
|
+
const effectiveBlocId = isIsolated ? rid : blocId;
|
|
95
|
+
|
|
96
|
+
// Use useRef to hold the bloc instance reference consistently across renders
|
|
97
|
+
const blocRef = useRef<InstanceType<B> | null>(null);
|
|
98
|
+
|
|
99
|
+
// Initialize or get the bloc instance ONCE using useMemo based on the effective ID
|
|
100
|
+
// This avoids re-running Blac.getBloc on every render.
|
|
101
|
+
useMemo(() => {
|
|
102
|
+
blocRef.current = Blac.getBloc(bloc, {
|
|
103
|
+
id: effectiveBlocId,
|
|
104
|
+
props,
|
|
105
|
+
instanceRef: rid, // Pass component ID for consumer tracking
|
|
106
|
+
});
|
|
107
|
+
}, [bloc, effectiveBlocId, rid]); // Dependencies ensure this runs only when bloc type or ID changes
|
|
108
|
+
|
|
109
|
+
const resolvedBloc = blocRef.current;
|
|
110
|
+
|
|
111
|
+
if (!resolvedBloc) {
|
|
112
|
+
// This should ideally not happen if Blac.getBloc works correctly
|
|
113
|
+
throw new Error(`useBloc: could not resolve bloc: ${bloc.name || bloc}`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Update props ONLY if this hook instance created the bloc (or is the designated main instance)
|
|
117
|
+
// We rely on Blac.getBloc to handle initial props correctly during creation.
|
|
118
|
+
// Subsequent calls should not overwrite props.
|
|
119
|
+
// Check if this instanceRef matches the one stored on the bloc when it was created/first retrieved.
|
|
120
|
+
if (
|
|
121
|
+
rid === resolvedBloc._instanceRef &&
|
|
122
|
+
options?.props &&
|
|
123
|
+
Blac.instance.findRegisteredBlocInstance(bloc, effectiveBlocId) ===
|
|
124
|
+
resolvedBloc
|
|
125
|
+
) {
|
|
126
|
+
// Avoid double-setting props if Blac.getBloc already set them during creation
|
|
127
|
+
if (resolvedBloc.props !== options.props) {
|
|
128
|
+
resolvedBloc.props = options.props;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Configure dependency tracking for re-renders
|
|
133
|
+
const dependencyArray: BlocHookDependencyArrayFn<BlocState<InstanceType<B>>> = (
|
|
134
|
+
newState,
|
|
135
|
+
oldState,
|
|
136
|
+
): ReturnType<BlocHookDependencyArrayFn<BlocState<InstanceType<B>>>> => {
|
|
137
|
+
// Use custom dependency selector if provided
|
|
138
|
+
if (dependencySelector) {
|
|
139
|
+
return dependencySelector(newState, oldState);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Fall back to bloc's default dependency selector if available
|
|
143
|
+
if (resolvedBloc.defaultDependencySelector) {
|
|
144
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
145
|
+
return resolvedBloc.defaultDependencySelector(newState, oldState);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// For primitive states, use default selector
|
|
149
|
+
if (typeof newState !== 'object') {
|
|
150
|
+
// Default behavior for primitive states: re-render if the state itself changes.
|
|
151
|
+
return [[newState]];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// For object states, track which properties were actually used
|
|
155
|
+
const usedStateValues: string[] = [];
|
|
156
|
+
for (const key of usedKeys.current) {
|
|
157
|
+
if (key in newState) {
|
|
158
|
+
usedStateValues.push(newState[key as keyof typeof newState]);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Track used class properties for dependency tracking, this enables rerenders when class getters change
|
|
163
|
+
const usedClassValues: unknown[] = [];
|
|
164
|
+
for (const key of usedClassPropKeys.current) {
|
|
165
|
+
if (key in resolvedBloc) {
|
|
166
|
+
try {
|
|
167
|
+
const value = resolvedBloc[key as keyof InstanceType<B>];
|
|
168
|
+
switch (typeof value) {
|
|
169
|
+
case 'function':
|
|
170
|
+
continue;
|
|
171
|
+
default:
|
|
172
|
+
usedClassValues.push(value);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
} catch (error) {
|
|
176
|
+
Blac.instance.log('useBloc Error', error);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
setTimeout(() => {
|
|
182
|
+
instanceKeys.current = new Set();
|
|
183
|
+
instanceClassPropKeys.current = new Set();
|
|
184
|
+
});
|
|
185
|
+
return [usedStateValues, usedClassValues];
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
// Set up external store subscription for state updates
|
|
189
|
+
const store = useMemo(
|
|
190
|
+
() => externalBlocStore(resolvedBloc, dependencyArray, rid),
|
|
191
|
+
[resolvedBloc, rid],
|
|
192
|
+
); // dependencyArray removed as it changes frequently
|
|
193
|
+
|
|
194
|
+
// Subscribe to state changes using React's external store API
|
|
195
|
+
const state = useSyncExternalStore<BlocState<InstanceType<B>>>(
|
|
196
|
+
store.subscribe,
|
|
197
|
+
store.getSnapshot,
|
|
198
|
+
store.getServerSnapshot,
|
|
199
|
+
);
|
|
200
|
+
|
|
201
|
+
// Create a proxy for state to track property access
|
|
202
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
203
|
+
const returnState: BlocState<InstanceType<B>> = useMemo(() => {
|
|
204
|
+
try {
|
|
205
|
+
if (typeof state === 'object') {
|
|
206
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
207
|
+
return new Proxy(state as any, {
|
|
208
|
+
get(_, prop) {
|
|
209
|
+
instanceKeys.current.add(prop as string);
|
|
210
|
+
usedKeys.current.add(prop as string);
|
|
211
|
+
const value = state[prop as keyof typeof state];
|
|
212
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
|
213
|
+
return value;
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
} catch (error) {
|
|
218
|
+
Blac.instance.log('useBloc Error', error);
|
|
219
|
+
}
|
|
220
|
+
return state;
|
|
221
|
+
}, [state]);
|
|
222
|
+
|
|
223
|
+
// Create a proxy for the bloc instance to track property access
|
|
224
|
+
const returnClass = useMemo(() => {
|
|
225
|
+
return new Proxy(resolvedBloc, {
|
|
226
|
+
get(_, prop) {
|
|
227
|
+
const value = resolvedBloc[prop as keyof InstanceType<B>];
|
|
228
|
+
// Track which class properties are accessed (excluding methods)
|
|
229
|
+
if (typeof value !== 'function') {
|
|
230
|
+
instanceClassPropKeys.current.add(prop as string);
|
|
231
|
+
}
|
|
232
|
+
return value;
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
}, [resolvedBloc]);
|
|
236
|
+
|
|
237
|
+
// Clean up tracked keys after each render
|
|
238
|
+
useLayoutEffect(() => {
|
|
239
|
+
// inherit the keys from the previous render
|
|
240
|
+
usedKeys.current = new Set(instanceKeys.current);
|
|
241
|
+
usedClassPropKeys.current = new Set(instanceClassPropKeys.current);
|
|
242
|
+
}, [renderInstance]);
|
|
243
|
+
|
|
244
|
+
// Set up bloc lifecycle management
|
|
245
|
+
useEffect(() => {
|
|
246
|
+
const currentBlocInstance = blocRef.current; // Capture instance for cleanup
|
|
247
|
+
if (!currentBlocInstance) return;
|
|
248
|
+
|
|
249
|
+
currentBlocInstance._addConsumer(rid);
|
|
250
|
+
|
|
251
|
+
// Call onMount callback if provided
|
|
252
|
+
options?.onMount?.(currentBlocInstance);
|
|
253
|
+
|
|
254
|
+
// Cleanup: remove this component as a consumer using the captured instance
|
|
255
|
+
return () => {
|
|
256
|
+
currentBlocInstance._removeConsumer(rid);
|
|
257
|
+
};
|
|
258
|
+
}, [bloc, rid]); // Do not add options.onMount to deps, it will cause a loop
|
|
259
|
+
|
|
260
|
+
return [returnState, returnClass];
|
|
261
|
+
}
|
package/dist/blac-react.mjs
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import { Blac as v } from "@blac/core";
|
|
2
|
-
import { useId as K, useRef as a, useState as D, useMemo as C, useSyncExternalStore as M, useLayoutEffect as O, useEffect as k } from "react";
|
|
3
|
-
const A = (n, s, c) => ({
|
|
4
|
-
subscribe: (d) => {
|
|
5
|
-
const f = n._observer.subscribe({
|
|
6
|
-
fn: () => {
|
|
7
|
-
try {
|
|
8
|
-
d(Object.freeze(n.state));
|
|
9
|
-
} catch (y) {
|
|
10
|
-
console.error({
|
|
11
|
-
e: y,
|
|
12
|
-
bloc: n,
|
|
13
|
-
dependencyArray: s
|
|
14
|
-
});
|
|
15
|
-
}
|
|
16
|
-
},
|
|
17
|
-
dependencyArray: s,
|
|
18
|
-
id: c
|
|
19
|
-
});
|
|
20
|
-
return () => {
|
|
21
|
-
f();
|
|
22
|
-
};
|
|
23
|
-
},
|
|
24
|
-
getSnapshot: () => Object.freeze(n.state),
|
|
25
|
-
getServerSnapshot: () => Object.freeze(n.state)
|
|
26
|
-
}), L = (n) => [[n]];
|
|
27
|
-
class T {
|
|
28
|
-
static useBloc(s, c) {
|
|
29
|
-
let { dependencySelector: d, id: f, props: y } = c ?? {};
|
|
30
|
-
const o = K(), S = a(/* @__PURE__ */ new Set()), p = a(/* @__PURE__ */ new Set()), h = a(!1), B = a(/* @__PURE__ */ new Set()), g = a(/* @__PURE__ */ new Set()), m = a(!1), _ = /* @__PURE__ */ new Set();
|
|
31
|
-
s.isolated && (f = o);
|
|
32
|
-
const [e, w] = D(
|
|
33
|
-
v.getInstance().getBloc(s, {
|
|
34
|
-
id: f,
|
|
35
|
-
props: y,
|
|
36
|
-
instanceRef: o
|
|
37
|
-
})
|
|
38
|
-
);
|
|
39
|
-
if (!e)
|
|
40
|
-
throw new Error(`useBloc: could not resolve: ${s.name || s}`);
|
|
41
|
-
o === e._instanceRef && (c != null && c.props) && (e.props = c.props);
|
|
42
|
-
const j = (t, r) => {
|
|
43
|
-
if (d)
|
|
44
|
-
return d(t, r);
|
|
45
|
-
if (e.defaultDependencySelector)
|
|
46
|
-
return e.defaultDependencySelector(t, r);
|
|
47
|
-
if (typeof t != "object")
|
|
48
|
-
return L(t);
|
|
49
|
-
const u = [];
|
|
50
|
-
for (const i of S.current)
|
|
51
|
-
i in t && u.push(t[i]);
|
|
52
|
-
const I = [];
|
|
53
|
-
for (const i of B.current)
|
|
54
|
-
if (i in e) {
|
|
55
|
-
const b = e[i];
|
|
56
|
-
if (typeof b == "function")
|
|
57
|
-
continue;
|
|
58
|
-
I.push(b);
|
|
59
|
-
}
|
|
60
|
-
return [u, I];
|
|
61
|
-
}, { subscribe: x, getSnapshot: E, getServerSnapshot: P } = C(
|
|
62
|
-
() => A(e, j, o),
|
|
63
|
-
[e._createdAt]
|
|
64
|
-
), l = M(
|
|
65
|
-
x,
|
|
66
|
-
E,
|
|
67
|
-
P
|
|
68
|
-
), R = C(() => {
|
|
69
|
-
try {
|
|
70
|
-
if (typeof l == "object")
|
|
71
|
-
return new Proxy(l, {
|
|
72
|
-
get(t, r) {
|
|
73
|
-
const u = l[r];
|
|
74
|
-
return S.current.add(r), p.current.add(r), h.current = !0, u;
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
} catch (t) {
|
|
78
|
-
v.instance.log("useBloc Error", t);
|
|
79
|
-
}
|
|
80
|
-
return l;
|
|
81
|
-
}, [l, S, p]), z = C(() => new Proxy(e, {
|
|
82
|
-
get(t, r) {
|
|
83
|
-
const u = e[r];
|
|
84
|
-
return typeof u != "function" && (B.current.add(r), g.current.add(r), m.current = !0), u;
|
|
85
|
-
}
|
|
86
|
-
}), [e, B, g]);
|
|
87
|
-
return O(() => (S.current = new Set(p.current), B.current = new Set(g.current), () => {
|
|
88
|
-
setTimeout(() => {
|
|
89
|
-
m.current && (g.current.clear(), m.current = !1), h.current && (p.current.clear(), h.current = !1);
|
|
90
|
-
});
|
|
91
|
-
}), [_]), k(() => (e._addConsumer(o), e._consumers.size !== 0 && w(
|
|
92
|
-
v.getInstance().getBloc(s, {
|
|
93
|
-
id: f,
|
|
94
|
-
props: y,
|
|
95
|
-
instanceRef: o
|
|
96
|
-
})
|
|
97
|
-
), () => e._removeConsumer(o)), []), [R, z];
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
const H = T.useBloc;
|
|
101
|
-
export {
|
|
102
|
-
A as externalBlocStore,
|
|
103
|
-
H as useBloc
|
|
104
|
-
};
|
package/dist/blac-react.umd.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
(function(r,o){typeof exports=="object"&&typeof module<"u"?o(exports,require("@blac/core"),require("react")):typeof define=="function"&&define.amd?define(["exports","@blac/core","react"],o):(r=typeof globalThis<"u"?globalThis:r||self,o(r.BlacReact={},r.BlacCore,r.react))})(this,function(r,o,t){"use strict";const C=(c,u,f)=>({subscribe:S=>{const l=c._observer.subscribe({fn:()=>{try{S(Object.freeze(c.state))}catch(B){console.error({e:B,bloc:c,dependencyArray:u})}},dependencyArray:u,id:f});return()=>{l()}},getSnapshot:()=>Object.freeze(c.state),getServerSnapshot:()=>Object.freeze(c.state)}),_=c=>[[c]];class j{static useBloc(u,f){let{dependencySelector:S,id:l,props:B}=f??{};const a=t.useId(),p=t.useRef(new Set),h=t.useRef(new Set),g=t.useRef(!1),m=t.useRef(new Set),b=t.useRef(new Set),v=t.useRef(!1),x=new Set;u.isolated&&(l=a);const[e,M]=t.useState(o.Blac.getInstance().getBloc(u,{id:l,props:B,instanceRef:a}));if(!e)throw new Error(`useBloc: could not resolve: ${u.name||u}`);a===e._instanceRef&&(f!=null&&f.props)&&(e.props=f.props);const P=(n,s)=>{if(S)return S(n,s);if(e.defaultDependencySelector)return e.defaultDependencySelector(n,s);if(typeof n!="object")return _(n);const i=[];for(const y of p.current)y in n&&i.push(n[y]);const R=[];for(const y of m.current)if(y in e){const I=e[y];if(typeof I=="function")continue;R.push(I)}return[i,R]},{subscribe:E,getSnapshot:z,getServerSnapshot:K}=t.useMemo(()=>C(e,P,a),[e._createdAt]),d=t.useSyncExternalStore(E,z,K),O=t.useMemo(()=>{try{if(typeof d=="object")return new Proxy(d,{get(n,s){const i=d[s];return p.current.add(s),h.current.add(s),g.current=!0,i}})}catch(n){o.Blac.instance.log("useBloc Error",n)}return d},[d,p,h]),T=t.useMemo(()=>new Proxy(e,{get(n,s){const i=e[s];return typeof i!="function"&&(m.current.add(s),b.current.add(s),v.current=!0),i}}),[e,m,b]);return t.useLayoutEffect(()=>(p.current=new Set(h.current),m.current=new Set(b.current),()=>{setTimeout(()=>{v.current&&(b.current.clear(),v.current=!1),g.current&&(h.current.clear(),g.current=!1)})}),[x]),t.useEffect(()=>(e._addConsumer(a),e._consumers.size!==0&&M(o.Blac.getInstance().getBloc(u,{id:l,props:B,instanceRef:a})),()=>e._removeConsumer(a)),[]),[O,T]}}const w=j.useBloc;r.externalBlocStore=C,r.useBloc=w,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
|