@blac/react 0.0.31 → 0.0.40

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.
@@ -0,0 +1,8 @@
1
+ module.exports = {
2
+ presets: [
3
+ ['@babel/env', { modules: false }],
4
+ '@babel/preset-typescript',
5
+ '@babel/preset-react',
6
+ ],
7
+ plugins: ['@babel/plugin-proposal-decorators'],
8
+ };
package/dev.ts ADDED
@@ -0,0 +1,45 @@
1
+ // bun runtime
2
+
3
+ // watch for any changes in ./src and run `npm run build` if any changes are detected
4
+
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import { exec } from 'child_process';
8
+
9
+ const srcDir = path.join(__dirname, 'src');
10
+ let building = false;
11
+
12
+ const build = () => {
13
+ console.log('Building...');
14
+ exec('npm run build', (err, stdout, stderr) => {
15
+ if (err) {
16
+ console.error(err);
17
+ building = false;
18
+ return;
19
+ }
20
+ console.log(stdout);
21
+ console.log(stderr);
22
+ building = false;
23
+ });
24
+ };
25
+
26
+ const watch = () => {
27
+ console.log('Watching for changes...');
28
+ fs.watch(srcDir, { recursive: true }, (eventType, filename) => {
29
+ if (building) {
30
+ return;
31
+ }
32
+ building = true;
33
+ console.log(`Change detected in ${filename}`);
34
+ build();
35
+ });
36
+ };
37
+
38
+ const main = () => {
39
+ build();
40
+ watch();
41
+ };
42
+
43
+ main();
44
+
45
+
package/index.html ADDED
File without changes
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@blac/react",
3
- "version": "0.0.31",
3
+ "version": "0.0.40",
4
4
  "license": "MIT",
5
- "main": "index.cjs.js",
6
- "module": "index.es.js",
7
- "typings": "src/index.d.ts",
8
- "types": "src/index.d.ts",
5
+ "main": "src/index.ts",
6
+ "module": "src/index.ts",
7
+ "typings": "src/index.ts",
8
+ "types": "src/index.ts",
9
9
  "keywords": [
10
10
  "react",
11
11
  "typescript",
@@ -28,9 +28,9 @@
28
28
  "blac": "*"
29
29
  },
30
30
  "devDependencies": {
31
- "vite-plugin-dts": "^3.7.1",
32
- "@types/react": "^18.2.48",
31
+ "@types/react": "^18.2.69",
33
32
  "react": "^18.2.0",
34
- "vitest": "^1.2.1"
33
+ "vite-plugin-dts": "^3.7.3",
34
+ "vitest": "^1.4.0"
35
35
  }
36
- }
36
+ }
package/publish.ts ADDED
@@ -0,0 +1,45 @@
1
+ // Run with Bun
2
+
3
+ const packageJsonConfig = {
4
+ main: 'index.cjs.js',
5
+ module: 'index.es.js',
6
+ typings: 'src/index.d.ts',
7
+ types: 'src/index.d.ts',
8
+ };
9
+
10
+ const filesToCopy = ['README.md', '.npmignore'];
11
+ const outputDir = 'dist';
12
+
13
+ (async () => {
14
+ // copy files to outputDir
15
+ for (const file of filesToCopy) {
16
+ const input = Bun.file(file);
17
+ const output = Bun.file(`${outputDir}/${file}`);
18
+ await Bun.write(output, input);
19
+ }
20
+
21
+ // update package.json
22
+ const packageJson = Bun.file(`package.json`);
23
+ const content = await packageJson.text();
24
+ const json = JSON.parse(content);
25
+
26
+ // patch version
27
+ const currentVersion = json.version;
28
+ const versionParts = currentVersion.split('.');
29
+ versionParts[2] = Number(versionParts[2]) + 1;
30
+ const newVersion = versionParts.join('.');
31
+
32
+ // update package.json version
33
+ json.version = newVersion;
34
+ await Bun.write(packageJson, JSON.stringify(json, null, 2));
35
+
36
+ // write package.json in outputDir for publishing
37
+ const publishContent = JSON.stringify(
38
+ { ...json, ...packageJsonConfig },
39
+ null,
40
+ 2,
41
+ );
42
+ await Bun.write(`${outputDir}/package.json`, publishContent);
43
+
44
+ console.log('Files Copied to dist and modified');
45
+ })();
@@ -0,0 +1,57 @@
1
+ import { BlocBase, BlocGeneric, InferStateFromGeneric } from 'blac';
2
+
3
+ export interface ExternalStore<
4
+ B extends BlocGeneric<any, any>,
5
+ S extends InferStateFromGeneric<B>,
6
+ > {
7
+ subscribe: (onStoreChange: () => void) => () => void;
8
+ getSnapshot: () => S;
9
+ getServerSnapshot?: () => S;
10
+ }
11
+
12
+ const externalBlocStore = <
13
+ B extends BlocGeneric<any, any>,
14
+ S extends InferStateFromGeneric<B>,
15
+ >(
16
+ bloc: B,
17
+ dependencyArray: (state: S) => unknown[],
18
+ ): ExternalStore<B, S> => {
19
+ let lastDependencyCheck = dependencyArray(bloc.state);
20
+
21
+ return {
22
+ subscribe: (listener: () => void) => {
23
+ const unSub = bloc.addSubscriber((data) => {
24
+ try {
25
+ const newDependencyCheck = dependencyArray(data) ?? [];
26
+
27
+ let allEqual = true;
28
+ for (let i = 0; i < newDependencyCheck.length; i++) {
29
+ if (newDependencyCheck[i] !== lastDependencyCheck[i]) {
30
+ allEqual = false;
31
+ break;
32
+ }
33
+ }
34
+
35
+ if (!allEqual) {
36
+ lastDependencyCheck = newDependencyCheck;
37
+ listener();
38
+ }
39
+ } catch (e) {
40
+ console.error({
41
+ e,
42
+ bloc,
43
+ dependencyArray,
44
+ lastDependencyCheck,
45
+ });
46
+ }
47
+ });
48
+ return () => {
49
+ unSub();
50
+ };
51
+ },
52
+ getSnapshot: (): S => bloc.state,
53
+ getServerSnapshot: (): S => bloc.state,
54
+ };
55
+ };
56
+
57
+ export default externalBlocStore;
@@ -1,3 +1,4 @@
1
1
  import externalBlocStore from './externalBlocStore';
2
2
  import useBloc from './useBloc';
3
+
3
4
  export { externalBlocStore, useBloc };
@@ -0,0 +1,130 @@
1
+ import {
2
+ Blac,
3
+ BlocBase,
4
+ BlocConstructor,
5
+ BlocGeneric,
6
+ BlocInstanceId,
7
+ BlocProps,
8
+ CubitPropsType,
9
+ InferStateFromGeneric,
10
+ ValueType,
11
+ } from 'blac';
12
+ import { useEffect, useId, useMemo, useSyncExternalStore } from 'react';
13
+ import externalBlocStore from './externalBlocStore';
14
+
15
+ // export type BlocHookData<B extends BlocBase<S>, S> = [
16
+ // value: ValueType<B>,
17
+ // instance: B,
18
+ // ];
19
+
20
+ type HookTypes<
21
+ B extends BlocConstructor<BlocGeneric<S, A>>,
22
+ S = any,
23
+ A = any,
24
+ > = [InferStateFromGeneric<InstanceType<B>>, InstanceType<B>];
25
+
26
+ // type BlocHookData<B extends BlocBase<S>, S> = [S, InstanceType<B>]; // B is the bloc class, S is the state of the bloc
27
+ // type UseBlocClassResult<B, S> = BlocHookData<B, S>;
28
+
29
+ export type BlocHookDependencyArrayFn<B extends BlocGeneric<any, any>> = (
30
+ state: InferStateFromGeneric<B>,
31
+ ) => unknown[];
32
+
33
+ export interface BlocHookOptions<B extends BlocGeneric<any, any>> {
34
+ id?: string;
35
+ dependencySelector?: BlocHookDependencyArrayFn<B>;
36
+ props?: CubitPropsType<B>;
37
+ }
38
+
39
+ export class UseBlocClass {
40
+ // static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(
41
+ // bloc: B,
42
+ // ): BlocHookData<InstanceType<B>, S> {
43
+ // static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(
44
+ // bloc: B,
45
+ // depsSelector: BlocHookDependencyArrayFn<InstanceType<B>, S>,
46
+ // ): BlocHookData<InstanceType<B>, S>;
47
+ // static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(
48
+ // bloc: B,
49
+ // instanceId: string,
50
+ // ): BlocHookData<InstanceType<B>, S>;
51
+ // static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(
52
+ // bloc: B,
53
+ // options?:
54
+ // | BlocHookOptions<InstanceType<B>, S>
55
+ // | BlocHookDependencyArrayFn<InstanceType<B>, S>
56
+ // | BlocInstanceId,
57
+ // ): BlocHookData<InstanceType<B>, S> {
58
+
59
+ // constructor, no options
60
+ static useBloc<
61
+ B extends BlocConstructor<BlocGeneric<S, A>>,
62
+ S = any,
63
+ A = any,
64
+ >(bloc: B, options?: BlocHookOptions<InstanceType<B>>): HookTypes<B> {
65
+ const rid = useId();
66
+ // default options
67
+ let dependencyArray: BlocHookDependencyArrayFn<InstanceType<B>> = (
68
+ state: InferStateFromGeneric<B>,
69
+ ) => [state];
70
+ let blocId: BlocInstanceId | undefined;
71
+ let props: BlocProps | undefined;
72
+
73
+ // parse options
74
+
75
+ // if options is a function, its a dependencySelector
76
+ // if (typeof options === 'function') {
77
+ // dependencyArray = options;
78
+ // }
79
+ //
80
+ // if options is a string its an ID
81
+ // if (typeof options === 'string') {
82
+ // blocId = options;
83
+ // }
84
+
85
+ if (typeof options === 'object') {
86
+ dependencyArray = options.dependencySelector ?? dependencyArray;
87
+ blocId = options.id;
88
+ props = options.props ?? props;
89
+ }
90
+
91
+ const base = bloc as unknown as BlocBase<S>;
92
+ const isIsolated = base.isolated;
93
+ if (isIsolated) {
94
+ blocId = rid;
95
+ }
96
+
97
+ const resolvedBloc = Blac.getInstance().getBloc(bloc, {
98
+ id: blocId,
99
+ props,
100
+ reconnect: false,
101
+ }) as InstanceType<B>;
102
+
103
+ if (!resolvedBloc) {
104
+ throw new Error(`useBloc: could not resolve: ${bloc.name || bloc}`);
105
+ }
106
+
107
+ const { subscribe, getSnapshot, getServerSnapshot } = useMemo(
108
+ () => externalBlocStore(resolvedBloc, dependencyArray),
109
+ [resolvedBloc.createdAt],
110
+ );
111
+
112
+ const state = useSyncExternalStore<InferStateFromGeneric<S>>(
113
+ subscribe,
114
+ getSnapshot,
115
+ getServerSnapshot,
116
+ );
117
+
118
+ useEffect(() => {
119
+ if ((resolvedBloc.isolated && props) || (props && !resolvedBloc.props)) {
120
+ resolvedBloc.props = props;
121
+ }
122
+ }, [props]);
123
+
124
+ return [state, resolvedBloc];
125
+ }
126
+ }
127
+
128
+ const useBloc = UseBlocClass.useBloc;
129
+
130
+ export default useBloc;
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es5",
4
+ "module": "esnext",
5
+ "jsx": "react",
6
+ "sourceMap": true,
7
+ "outDir": "dist",
8
+ "strict": true,
9
+ "moduleResolution": "node",
10
+ "allowSyntheticDefaultImports": true,
11
+ "esModuleInterop": true,
12
+ "skipLibCheck": true,
13
+ "forceConsistentCasingInFileNames": true
14
+ },
15
+ "exclude": ["publish.ts"]
16
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,30 @@
1
+ import { defineConfig } from 'vite';
2
+ import reactRefresh from '@vitejs/plugin-react';
3
+ import dts from 'vite-plugin-dts';
4
+ import { dependencies, devDependencies } from './package.json';
5
+
6
+ const external = [
7
+ ...Object.keys(dependencies),
8
+ ...Object.keys(devDependencies),
9
+ ].filter((name) => {
10
+ return name;
11
+ });
12
+
13
+ // https://vitejs.dev/config/
14
+ export default defineConfig({
15
+ plugins: [reactRefresh(), dts()],
16
+ publicDir: 'public',
17
+ build: {
18
+ lib: {
19
+ entry: './src/index.ts', // Specifies the entry point for building the library.
20
+ name: 'blac-react', // Sets the name of the generated library.
21
+ fileName: (format) => `index.${format}.js`, // Generates the output file name based on the format.
22
+ formats: ['cjs', 'es'], // Specifies the output formats (CommonJS and ES modules).
23
+ },
24
+ rollupOptions: {
25
+ external: [...external, 'react', 'react-dom', 'react/jsx-runtime'], // Defines external dependencies for Rollup bundling.
26
+ },
27
+ sourcemap: true, // Generates source maps for debugging.
28
+ emptyOutDir: true, // Clears the output directory before building.
29
+ },
30
+ });
@@ -0,0 +1,5 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ export default defineConfig({
4
+
5
+ })
package/index.cjs.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("blac"),l=require("react"),f=(r,s)=>{let e=s(r.state);return{subscribe:u=>{const c=r.addEventListenerStateChange(n=>{try{const t=s(n)??[];let i=!0;for(let o=0;o<t.length;o++)if(t[o]!==e[o]){i=!1;break}i||(e=t,u())}catch(t){console.error({e:t,bloc:r,dependencyArray:s,lastDependencyCheck:e})}});return()=>{c()}},getSnapshot:()=>r.state,getServerSnapshot:()=>r.state}};class y{static useBloc(s,e){const u=l.useId();let c=h=>[h],n,t;typeof e=="function"&&(c=e),typeof e=="string"&&(n=e),typeof e=="object"&&(c=e.dependencySelector??c,n=e.id,t=e.props??t),s.isolated&&(n=u);const a=p.Blac.getInstance().getBloc(s,{id:n,props:t,reconnect:!1});if(!a)throw new Error(`useBloc: could not resolve: ${s.name||s}`);const{subscribe:d,getSnapshot:S,getServerSnapshot:g}=l.useMemo(()=>f(a,c),[a.createdAt]),B=l.useSyncExternalStore(d,S,g);return l.useEffect(()=>{t&&(a.props=t)},[t]),[B,a]}}const b=y.useBloc;exports.externalBlocStore=f;exports.useBloc=b;
2
- //# sourceMappingURL=index.cjs.js.map
package/index.cjs.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/externalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["import { BlocBase } from 'blac';\n\nexport interface ExternalStore<B extends BlocBase<S>, S> {\n subscribe: (onStoreChange: () => void) => () => void;\n getSnapshot: () => S;\n getServerSnapshot?: () => S;\n}\n\nconst externalBlocStore = <B extends BlocBase<S>, S>(\n bloc: B,\n dependencyArray: (state: S) => unknown[],\n): ExternalStore<B, S> => {\n let lastDependencyCheck = dependencyArray(bloc.state);\n\n return {\n subscribe: (listener: () => void) => {\n const unSub = bloc.addEventListenerStateChange((data) => {\n try {\n const newDependencyCheck = dependencyArray(data) ?? [];\n\n let allEqual = true;\n for (let i = 0; i < newDependencyCheck.length; i++) {\n if (newDependencyCheck[i] !== lastDependencyCheck[i]) {\n allEqual = false;\n break;\n }\n }\n\n if (!allEqual) {\n lastDependencyCheck = newDependencyCheck;\n listener();\n }\n } catch (e) {\n console.error({\n e,\n bloc,\n dependencyArray,\n lastDependencyCheck,\n });\n }\n });\n return () => {\n unSub();\n };\n },\n getSnapshot: (): S => bloc.state,\n getServerSnapshot: (): S => bloc.state,\n };\n};\n\nexport default externalBlocStore;\n","import {\n Blac,\n BlocBase,\n BlocConstructor,\n BlocInstanceId,\n BlocProps,\n CubitPropsType,\n ValueType,\n} from 'blac';\nimport { useEffect, useId, useMemo, useSyncExternalStore } from 'react';\nimport externalBlocStore from './externalBlocStore';\n\nexport type BlocHookData<B extends BlocBase<S>, S> = [\n value: ValueType<B>,\n instance: B,\n];\n\n// type BlocHookData<B extends BlocBase<S>, S> = [S, InstanceType<B>]; // B is the bloc class, S is the state of the bloc\n// type UseBlocClassResult<B, S> = BlocHookData<B, S>;\n\nexport type BlocHookDependencyArrayFn<B extends BlocBase<S>, S> = (\n state: ValueType<B>,\n) => unknown[];\n\nexport interface BlocHookOptions<B extends BlocBase<S>, S> {\n id?: string;\n dependencySelector?: BlocHookDependencyArrayFn<B, S>;\n props?: CubitPropsType<B>;\n}\n\nexport class UseBlocClass {\n // constructor, no options\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n options: BlocHookOptions<InstanceType<B>, S>,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n depsSelector: BlocHookDependencyArrayFn<InstanceType<B>, S>,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n instanceId: string,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n options?:\n | BlocHookOptions<InstanceType<B>, S>\n | BlocHookDependencyArrayFn<InstanceType<B>, S>\n | BlocInstanceId,\n ): BlocHookData<InstanceType<B>, S> {\n const rid = useId();\n // default options\n let dependencyArray: BlocHookDependencyArrayFn<InstanceType<B>, S> = (\n state: ValueType<InstanceType<B>>,\n ) => [state];\n let blocId: BlocInstanceId | undefined;\n let props: BlocProps | undefined;\n\n // parse options\n\n // if options is a function, its a dependencySelector\n if (typeof options === 'function') {\n dependencyArray = options;\n }\n\n // if options is a string its an ID\n if (typeof options === 'string') {\n blocId = options;\n }\n\n if (typeof options === 'object') {\n dependencyArray = options.dependencySelector ?? dependencyArray;\n blocId = options.id;\n props = options.props ?? props;\n }\n\n const base = bloc as unknown as BlocBase<S>;\n const isIsolated = base.isolated;\n if (isIsolated) {\n blocId = rid;\n }\n\n const resolvedBloc = Blac.getInstance().getBloc(bloc, {\n id: blocId,\n props,\n reconnect: false,\n }) as InstanceType<B>;\n\n if (!resolvedBloc) {\n throw new Error(`useBloc: could not resolve: ${bloc.name || bloc}`);\n }\n\n const { subscribe, getSnapshot, getServerSnapshot } = useMemo(\n () => externalBlocStore(resolvedBloc, dependencyArray),\n [resolvedBloc.createdAt],\n );\n\n const state = useSyncExternalStore<ValueType<InstanceType<B>>>(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n );\n\n useEffect(() => {\n if (props) {\n resolvedBloc.props = props;\n }\n }, [props]);\n\n return [state, resolvedBloc];\n }\n}\n\nconst useBloc = UseBlocClass.useBloc;\n\nexport default useBloc;\n"],"names":["externalBlocStore","bloc","dependencyArray","lastDependencyCheck","listener","unSub","data","newDependencyCheck","allEqual","i","e","UseBlocClass","options","rid","useId","state","blocId","props","resolvedBloc","Blac","subscribe","getSnapshot","getServerSnapshot","useMemo","useSyncExternalStore","useEffect","useBloc"],"mappings":"2HAQMA,EAAoB,CACxBC,EACAC,IACwB,CACpB,IAAAC,EAAsBD,EAAgBD,EAAK,KAAK,EAE7C,MAAA,CACL,UAAYG,GAAyB,CACnC,MAAMC,EAAQJ,EAAK,4BAA6BK,GAAS,CACnD,GAAA,CACF,MAAMC,EAAqBL,EAAgBI,CAAI,GAAK,CAAA,EAEpD,IAAIE,EAAW,GACf,QAASC,EAAI,EAAGA,EAAIF,EAAmB,OAAQE,IAC7C,GAAIF,EAAmBE,CAAC,IAAMN,EAAoBM,CAAC,EAAG,CACzCD,EAAA,GACX,KACF,CAGGA,IACmBL,EAAAI,EACbH,WAEJM,EAAG,CACV,QAAQ,MAAM,CACZ,EAAAA,EACA,KAAAT,EACA,gBAAAC,EACA,oBAAAC,CAAA,CACD,CACH,CAAA,CACD,EACD,MAAO,IAAM,CACLE,GAAA,CAEV,EACA,YAAa,IAASJ,EAAK,MAC3B,kBAAmB,IAASA,EAAK,KAAA,CAErC,EClBO,MAAMU,CAAa,CAiBxB,OAAO,QACLV,EACAW,EAIkC,CAClC,MAAMC,EAAMC,EAAAA,QAEZ,IAAIZ,EACFa,GACG,CAACA,CAAK,EACPC,EACAC,EAKA,OAAOL,GAAY,aACHV,EAAAU,GAIhB,OAAOA,GAAY,WACZI,EAAAJ,GAGP,OAAOA,GAAY,WACrBV,EAAkBU,EAAQ,oBAAsBV,EAChDc,EAASJ,EAAQ,GACjBK,EAAQL,EAAQ,OAASK,GAGdhB,EACW,WAEbe,EAAAH,GAGX,MAAMK,EAAeC,EAAA,KAAK,YAAY,EAAE,QAAQlB,EAAM,CACpD,GAAIe,EACJ,MAAAC,EACA,UAAW,EAAA,CACZ,EAED,GAAI,CAACC,EACH,MAAM,IAAI,MAAM,+BAA+BjB,EAAK,MAAQA,CAAI,EAAE,EAGpE,KAAM,CAAE,UAAAmB,EAAW,YAAAC,EAAa,kBAAAC,CAAsB,EAAAC,EAAA,QACpD,IAAMvB,EAAkBkB,EAAchB,CAAe,EACrD,CAACgB,EAAa,SAAS,CAAA,EAGnBH,EAAQS,EAAA,qBACZJ,EACAC,EACAC,CAAA,EAGFG,OAAAA,EAAAA,UAAU,IAAM,CACVR,IACFC,EAAa,MAAQD,EACvB,EACC,CAACA,CAAK,CAAC,EAEH,CAACF,EAAOG,CAAY,CAC7B,CACF,CAEA,MAAMQ,EAAUf,EAAa"}
package/index.es.js DELETED
@@ -1,64 +0,0 @@
1
- import { Blac as h } from "blac";
2
- import { useId as g, useMemo as B, useSyncExternalStore as m, useEffect as y } from "react";
3
- const v = (r, s) => {
4
- let e = s(r.state);
5
- return {
6
- subscribe: (l) => {
7
- const c = r.addEventListenerStateChange((n) => {
8
- try {
9
- const t = s(n) ?? [];
10
- let f = !0;
11
- for (let o = 0; o < t.length; o++)
12
- if (t[o] !== e[o]) {
13
- f = !1;
14
- break;
15
- }
16
- f || (e = t, l());
17
- } catch (t) {
18
- console.error({
19
- e: t,
20
- bloc: r,
21
- dependencyArray: s,
22
- lastDependencyCheck: e
23
- });
24
- }
25
- });
26
- return () => {
27
- c();
28
- };
29
- },
30
- getSnapshot: () => r.state,
31
- getServerSnapshot: () => r.state
32
- };
33
- };
34
- class E {
35
- static useBloc(s, e) {
36
- const l = g();
37
- let c = (p) => [p], n, t;
38
- typeof e == "function" && (c = e), typeof e == "string" && (n = e), typeof e == "object" && (c = e.dependencySelector ?? c, n = e.id, t = e.props ?? t), s.isolated && (n = l);
39
- const a = h.getInstance().getBloc(s, {
40
- id: n,
41
- props: t,
42
- reconnect: !1
43
- });
44
- if (!a)
45
- throw new Error(`useBloc: could not resolve: ${s.name || s}`);
46
- const { subscribe: u, getSnapshot: i, getServerSnapshot: d } = B(
47
- () => v(a, c),
48
- [a.createdAt]
49
- ), S = m(
50
- u,
51
- i,
52
- d
53
- );
54
- return y(() => {
55
- t && (a.props = t);
56
- }, [t]), [S, a];
57
- }
58
- }
59
- const b = E.useBloc;
60
- export {
61
- v as externalBlocStore,
62
- b as useBloc
63
- };
64
- //# sourceMappingURL=index.es.js.map
package/index.es.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/externalBlocStore.ts","../src/useBloc.tsx"],"sourcesContent":["import { BlocBase } from 'blac';\n\nexport interface ExternalStore<B extends BlocBase<S>, S> {\n subscribe: (onStoreChange: () => void) => () => void;\n getSnapshot: () => S;\n getServerSnapshot?: () => S;\n}\n\nconst externalBlocStore = <B extends BlocBase<S>, S>(\n bloc: B,\n dependencyArray: (state: S) => unknown[],\n): ExternalStore<B, S> => {\n let lastDependencyCheck = dependencyArray(bloc.state);\n\n return {\n subscribe: (listener: () => void) => {\n const unSub = bloc.addEventListenerStateChange((data) => {\n try {\n const newDependencyCheck = dependencyArray(data) ?? [];\n\n let allEqual = true;\n for (let i = 0; i < newDependencyCheck.length; i++) {\n if (newDependencyCheck[i] !== lastDependencyCheck[i]) {\n allEqual = false;\n break;\n }\n }\n\n if (!allEqual) {\n lastDependencyCheck = newDependencyCheck;\n listener();\n }\n } catch (e) {\n console.error({\n e,\n bloc,\n dependencyArray,\n lastDependencyCheck,\n });\n }\n });\n return () => {\n unSub();\n };\n },\n getSnapshot: (): S => bloc.state,\n getServerSnapshot: (): S => bloc.state,\n };\n};\n\nexport default externalBlocStore;\n","import {\n Blac,\n BlocBase,\n BlocConstructor,\n BlocInstanceId,\n BlocProps,\n CubitPropsType,\n ValueType,\n} from 'blac';\nimport { useEffect, useId, useMemo, useSyncExternalStore } from 'react';\nimport externalBlocStore from './externalBlocStore';\n\nexport type BlocHookData<B extends BlocBase<S>, S> = [\n value: ValueType<B>,\n instance: B,\n];\n\n// type BlocHookData<B extends BlocBase<S>, S> = [S, InstanceType<B>]; // B is the bloc class, S is the state of the bloc\n// type UseBlocClassResult<B, S> = BlocHookData<B, S>;\n\nexport type BlocHookDependencyArrayFn<B extends BlocBase<S>, S> = (\n state: ValueType<B>,\n) => unknown[];\n\nexport interface BlocHookOptions<B extends BlocBase<S>, S> {\n id?: string;\n dependencySelector?: BlocHookDependencyArrayFn<B, S>;\n props?: CubitPropsType<B>;\n}\n\nexport class UseBlocClass {\n // constructor, no options\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n options: BlocHookOptions<InstanceType<B>, S>,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n depsSelector: BlocHookDependencyArrayFn<InstanceType<B>, S>,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n instanceId: string,\n ): BlocHookData<InstanceType<B>, S>;\n static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(\n bloc: B,\n options?:\n | BlocHookOptions<InstanceType<B>, S>\n | BlocHookDependencyArrayFn<InstanceType<B>, S>\n | BlocInstanceId,\n ): BlocHookData<InstanceType<B>, S> {\n const rid = useId();\n // default options\n let dependencyArray: BlocHookDependencyArrayFn<InstanceType<B>, S> = (\n state: ValueType<InstanceType<B>>,\n ) => [state];\n let blocId: BlocInstanceId | undefined;\n let props: BlocProps | undefined;\n\n // parse options\n\n // if options is a function, its a dependencySelector\n if (typeof options === 'function') {\n dependencyArray = options;\n }\n\n // if options is a string its an ID\n if (typeof options === 'string') {\n blocId = options;\n }\n\n if (typeof options === 'object') {\n dependencyArray = options.dependencySelector ?? dependencyArray;\n blocId = options.id;\n props = options.props ?? props;\n }\n\n const base = bloc as unknown as BlocBase<S>;\n const isIsolated = base.isolated;\n if (isIsolated) {\n blocId = rid;\n }\n\n const resolvedBloc = Blac.getInstance().getBloc(bloc, {\n id: blocId,\n props,\n reconnect: false,\n }) as InstanceType<B>;\n\n if (!resolvedBloc) {\n throw new Error(`useBloc: could not resolve: ${bloc.name || bloc}`);\n }\n\n const { subscribe, getSnapshot, getServerSnapshot } = useMemo(\n () => externalBlocStore(resolvedBloc, dependencyArray),\n [resolvedBloc.createdAt],\n );\n\n const state = useSyncExternalStore<ValueType<InstanceType<B>>>(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n );\n\n useEffect(() => {\n if (props) {\n resolvedBloc.props = props;\n }\n }, [props]);\n\n return [state, resolvedBloc];\n }\n}\n\nconst useBloc = UseBlocClass.useBloc;\n\nexport default useBloc;\n"],"names":["externalBlocStore","bloc","dependencyArray","lastDependencyCheck","listener","unSub","data","newDependencyCheck","allEqual","i","e","UseBlocClass","options","rid","useId","state","blocId","props","resolvedBloc","Blac","subscribe","getSnapshot","getServerSnapshot","useMemo","useSyncExternalStore","useEffect","useBloc"],"mappings":";;AAQM,MAAAA,IAAoB,CACxBC,GACAC,MACwB;AACpB,MAAAC,IAAsBD,EAAgBD,EAAK,KAAK;AAE7C,SAAA;AAAA,IACL,WAAW,CAACG,MAAyB;AACnC,YAAMC,IAAQJ,EAAK,4BAA4B,CAACK,MAAS;AACnD,YAAA;AACF,gBAAMC,IAAqBL,EAAgBI,CAAI,KAAK,CAAA;AAEpD,cAAIE,IAAW;AACf,mBAASC,IAAI,GAAGA,IAAIF,EAAmB,QAAQE;AAC7C,gBAAIF,EAAmBE,CAAC,MAAMN,EAAoBM,CAAC,GAAG;AACzC,cAAAD,IAAA;AACX;AAAA,YACF;AAGF,UAAKA,MACmBL,IAAAI,GACbH;iBAEJM,GAAG;AACV,kBAAQ,MAAM;AAAA,YACZ,GAAAA;AAAA,YACA,MAAAT;AAAA,YACA,iBAAAC;AAAA,YACA,qBAAAC;AAAA,UAAA,CACD;AAAA,QACH;AAAA,MAAA,CACD;AACD,aAAO,MAAM;AACL,QAAAE;MAAA;AAAA,IAEV;AAAA,IACA,aAAa,MAASJ,EAAK;AAAA,IAC3B,mBAAmB,MAASA,EAAK;AAAA,EAAA;AAErC;AClBO,MAAMU,EAAa;AAAA,EAiBxB,OAAO,QACLV,GACAW,GAIkC;AAClC,UAAMC,IAAMC;AAEZ,QAAIZ,IAAiE,CACnEa,MACG,CAACA,CAAK,GACPC,GACAC;AAKA,IAAA,OAAOL,KAAY,eACHV,IAAAU,IAIhB,OAAOA,KAAY,aACZI,IAAAJ,IAGP,OAAOA,KAAY,aACrBV,IAAkBU,EAAQ,sBAAsBV,GAChDc,IAASJ,EAAQ,IACjBK,IAAQL,EAAQ,SAASK,IAGdhB,EACW,aAEbe,IAAAH;AAGX,UAAMK,IAAeC,EAAK,YAAY,EAAE,QAAQlB,GAAM;AAAA,MACpD,IAAIe;AAAA,MACJ,OAAAC;AAAA,MACA,WAAW;AAAA,IAAA,CACZ;AAED,QAAI,CAACC;AACH,YAAM,IAAI,MAAM,+BAA+BjB,EAAK,QAAQA,CAAI,EAAE;AAGpE,UAAM,EAAE,WAAAmB,GAAW,aAAAC,GAAa,mBAAAC,EAAsB,IAAAC;AAAA,MACpD,MAAMvB,EAAkBkB,GAAchB,CAAe;AAAA,MACrD,CAACgB,EAAa,SAAS;AAAA,IAAA,GAGnBH,IAAQS;AAAA,MACZJ;AAAA,MACAC;AAAA,MACAC;AAAA,IAAA;AAGF,WAAAG,EAAU,MAAM;AACd,MAAIR,MACFC,EAAa,QAAQD;AAAA,IACvB,GACC,CAACA,CAAK,CAAC,GAEH,CAACF,GAAOG,CAAY;AAAA,EAC7B;AACF;AAEA,MAAMQ,IAAUf,EAAa;"}
@@ -1,8 +0,0 @@
1
- import { BlocBase } from 'blac';
2
- export interface ExternalStore<B extends BlocBase<S>, S> {
3
- subscribe: (onStoreChange: () => void) => () => void;
4
- getSnapshot: () => S;
5
- getServerSnapshot?: () => S;
6
- }
7
- declare const externalBlocStore: <B extends BlocBase<S, {}>, S>(bloc: B, dependencyArray: (state: S) => unknown[]) => ExternalStore<B, S>;
8
- export default externalBlocStore;
package/src/useBloc.d.ts DELETED
@@ -1,19 +0,0 @@
1
- import { BlocBase, BlocConstructor, CubitPropsType, ValueType } from 'blac';
2
- export type BlocHookData<B extends BlocBase<S>, S> = [
3
- value: ValueType<B>,
4
- instance: B
5
- ];
6
- export type BlocHookDependencyArrayFn<B extends BlocBase<S>, S> = (state: ValueType<B>) => unknown[];
7
- export interface BlocHookOptions<B extends BlocBase<S>, S> {
8
- id?: string;
9
- dependencySelector?: BlocHookDependencyArrayFn<B, S>;
10
- props?: CubitPropsType<B>;
11
- }
12
- export declare class UseBlocClass {
13
- static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B): BlocHookData<InstanceType<B>, S>;
14
- static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, options: BlocHookOptions<InstanceType<B>, S>): BlocHookData<InstanceType<B>, S>;
15
- static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, depsSelector: BlocHookDependencyArrayFn<InstanceType<B>, S>): BlocHookData<InstanceType<B>, S>;
16
- static useBloc<B extends BlocConstructor<BlocBase<S>>, S>(bloc: B, instanceId: string): BlocHookData<InstanceType<B>, S>;
17
- }
18
- declare const useBloc: typeof UseBlocClass.useBloc;
19
- export default useBloc;
File without changes