@siggn/react 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -2
- package/dist/hooks.d.ts +38 -6
- package/dist/hooks.d.ts.map +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +34 -274
- package/dist/index.es.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -49,7 +49,7 @@ Alternatively, you can use the `useSiggn` hook to create a `Siggn` instance that
|
|
|
49
49
|
|
|
50
50
|
### 2. Subscribe to Events in a Component
|
|
51
51
|
|
|
52
|
-
Use the `useSubscribe` hook to listen for
|
|
52
|
+
Use the `useSubscribe` hook to listen for a message. It automatically handles subscribing and unsubscribing.
|
|
53
53
|
|
|
54
54
|
```tsx
|
|
55
55
|
// src/components/Notification.tsx
|
|
@@ -60,7 +60,30 @@ import { siggn, type Message } from '../siggn';
|
|
|
60
60
|
function Notification() {
|
|
61
61
|
const [notification, setNotification] = useState<string | null>(null);
|
|
62
62
|
|
|
63
|
-
useSubscribe(siggn, (
|
|
63
|
+
useSubscribe(siggn, 'user_login', (msg) => {
|
|
64
|
+
setNotification(`Welcome, ${msg.name}!`);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
if (!notification) {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return <div className='notification'>{notification}</div>;
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
You can also use the `useSubscribeMany` hook to listen for multiple messages. It automatically handles subscribing and unsubscribing.
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
// src/components/Notification.tsx
|
|
79
|
+
import { useState } from 'react';
|
|
80
|
+
import { useSubscribeMany } from '@siggn/react';
|
|
81
|
+
import { siggn, type Message } from '../siggn';
|
|
82
|
+
|
|
83
|
+
function Notification() {
|
|
84
|
+
const [notification, setNotification] = useState<string | null>(null);
|
|
85
|
+
|
|
86
|
+
useSubscribeMany(siggn, (subscribe) => {
|
|
64
87
|
subscribe('user_login', (msg) => {
|
|
65
88
|
setNotification(`Welcome, ${msg.name}!`);
|
|
66
89
|
});
|
package/dist/hooks.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Msg, Siggn } from '@siggn/core';
|
|
2
|
-
import { SubscriptionOptions } from 'packages/react/src/types';
|
|
3
2
|
import { DependencyList } from 'react';
|
|
4
3
|
/**
|
|
5
4
|
* Creates and returns a `Siggn` instance that persists for the lifetime of the component.
|
|
@@ -20,7 +19,7 @@ import { DependencyList } from 'react';
|
|
|
20
19
|
*/
|
|
21
20
|
export declare function useSiggn<T extends Msg>(): Siggn<T>;
|
|
22
21
|
/**
|
|
23
|
-
* Subscribes to messages and automatically unsubscribes when the component unmounts.
|
|
22
|
+
* Subscribes to multiple messages and automatically unsubscribes when the component unmounts.
|
|
24
23
|
*
|
|
25
24
|
* @template T A union of all possible message types.
|
|
26
25
|
* @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.
|
|
@@ -34,16 +33,46 @@ export declare function useSiggn<T extends Msg>(): Siggn<T>;
|
|
|
34
33
|
* import { siggn } from './siggn'; // Your shared instance
|
|
35
34
|
*
|
|
36
35
|
* function MyComponent() {
|
|
37
|
-
*
|
|
36
|
+
* useSubscribeMany(siggn, (subscribe) => {
|
|
38
37
|
* subscribe('user-created', (msg) => console.log(msg.name));
|
|
38
|
+
* subscribe('user-updated', (msg) => console.log(msg.name));
|
|
39
39
|
* });
|
|
40
40
|
* // ...
|
|
41
41
|
* }
|
|
42
42
|
* ```
|
|
43
43
|
*/
|
|
44
|
-
export declare function
|
|
45
|
-
|
|
44
|
+
export declare function useSubscribeMany<M extends Msg>(options: Siggn<M> | {
|
|
45
|
+
instance: Siggn<M>;
|
|
46
|
+
id?: string;
|
|
47
|
+
}, setup: (subscribe: <T extends M['type']>(type: T, callback: (msg: Extract<M, {
|
|
48
|
+
type: T;
|
|
46
49
|
}>) => void) => void) => void, deps?: DependencyList): void;
|
|
50
|
+
/**
|
|
51
|
+
* Subscribes to a single message and automatically unsubscribe when the component unmounts.
|
|
52
|
+
*
|
|
53
|
+
* @template T A union of all possible message types.
|
|
54
|
+
* @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.
|
|
55
|
+
* @param setup A function that receives a `subscribe` helper to define subscriptions.
|
|
56
|
+
* @param deps An optional dependency array to control when the subscriptions are re-created.
|
|
57
|
+
* @category Subscription
|
|
58
|
+
* @since 0.0.1
|
|
59
|
+
* @example
|
|
60
|
+
*
|
|
61
|
+
```tsx
|
|
62
|
+
* import { siggn } from './siggn'; // Your shared instance
|
|
63
|
+
*
|
|
64
|
+
* function MyComponent() {
|
|
65
|
+
* useSubscribe(siggn, 'user-created', (msg) => console.log(msg.name));
|
|
66
|
+
* // ...
|
|
67
|
+
* }
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare function useSubscribe<M extends Msg, T extends string>(options: Siggn<M> | {
|
|
71
|
+
instance: Siggn<M>;
|
|
72
|
+
id?: string;
|
|
73
|
+
}, type: T, callback: (msg: Extract<M, {
|
|
74
|
+
type: T;
|
|
75
|
+
}>) => void, deps?: DependencyList): void;
|
|
47
76
|
/**
|
|
48
77
|
* Subscribes to all messages on a `Siggn` instance and automatically unsubscribes
|
|
49
78
|
* when the component unmounts.
|
|
@@ -67,5 +96,8 @@ export declare function useSubscribe<T extends Msg>(options: SubscriptionOptions
|
|
|
67
96
|
* }
|
|
68
97
|
* ```
|
|
69
98
|
*/
|
|
70
|
-
export declare function useSubscribeAll<T extends Msg>(options:
|
|
99
|
+
export declare function useSubscribeAll<T extends Msg>(options: Siggn<T> | {
|
|
100
|
+
instance: Siggn<T>;
|
|
101
|
+
id?: string;
|
|
102
|
+
}, callback: (msg: T) => void, deps?: DependencyList): void;
|
|
71
103
|
//# sourceMappingURL=hooks.d.ts.map
|
package/dist/hooks.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,GAAG,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,GAAG,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAE9C,OAAO,EAAgC,KAAK,cAAc,EAAE,MAAM,OAAO,CAAC;AAE1E;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,CAGlD;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,GAAG,EAC5C,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,EACvD,KAAK,EAAE,CACL,SAAS,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,EAC7B,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAC,KAAK,IAAI,KAC7C,IAAI,KACN,IAAI,EACT,IAAI,GAAE,cAAmB,QAe1B;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,GAAG,EAAE,CAAC,SAAS,MAAM,EAC1D,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,EACvD,IAAI,EAAE,CAAC,EACP,QAAQ,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,EAAE;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAAC,KAAK,IAAI,EAChD,IAAI,GAAE,cAAmB,QAe1B;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,GAAG,EAC3C,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IAAC,EAAE,CAAC,EAAE,MAAM,CAAA;CAAE,EACvD,QAAQ,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,EAC1B,IAAI,GAAE,cAAmB,QAe1B"}
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@siggn/core"),n=require("react");function b(){const[e]=n.useState(new s.Siggn);return e}function a(e,i,r=[]){const u=n.useMemo(()=>e instanceof s.Siggn?e:e.instance,[e]),c=n.useMemo(()=>u.makeId("id"in e?e.id:void 0),[u]);n.useEffect(()=>(u.subscribeMany(c,i),()=>{u.unsubscribe(c)}),[u,c,...r])}function d(e,i,r,u=[]){const c=n.useMemo(()=>e instanceof s.Siggn?e:e.instance,[e]),t=n.useMemo(()=>c.makeId("id"in e?e.id:void 0),[c]);n.useEffect(()=>(c.subscribe(t,i,r),()=>{c.unsubscribe(t)}),[c,t,...u])}function f(e,i,r=[]){const u=n.useMemo(()=>e instanceof s.Siggn?e:e.instance,[e]),c=n.useMemo(()=>u.makeId("id"in e?e.id:void 0),[u]);n.useEffect(()=>(u.subscribeAll(c,i),()=>{u.unsubscribeGlobal(c)}),[u,c,...r])}exports.useSiggn=b;exports.useSubscribe=d;exports.useSubscribeAll=f;exports.useSubscribeMany=a;Object.keys(s).forEach(e=>{e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>s[e]})});
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../../core/dist/index.es.js","../src/hooks.ts"],"sourcesContent":["class e {\n nextId = 0;\n subscriptions;\n globalSubscriptions = [];\n /**\n * A FinalizationRegistry to automatically unregister specific subscriptions\n * when the subscribed callback function is garbage collected.\n */\n registry = new FinalizationRegistry((s) => {\n this.unsubscribe(s);\n });\n /**\n * A FinalizationRegistry to automatically unregister global subscriptions\n * when the subscribed callback function is garbage collected.\n */\n registryGlobal = new FinalizationRegistry((s) => {\n this.unsubscribeGlobal(s);\n });\n /**\n * Creates a new Siggn instance.\n * @category Lifecycle\n * @since 0.0.5\n */\n constructor() {\n this.subscriptions = /* @__PURE__ */ new Map();\n }\n /**\n * Creates a new, independent `Siggn` instance that inherits the message\n * types of its parent and adds new ones.\n *\n * @template C The new message types to add.\n * @returns A new `Siggn` instance with combined message types.\n * @category Lifecycle\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const baseSiggn = new Siggn<{ type: 'A' }>();\n * const childSiggn = baseSiggn.createClone<{ type: 'B' }>();\n * // childSiggn can now publish and subscribe to types 'A' and 'B'.\n * ```\n */\n createClone() {\n return new e();\n }\n /**\n * Generates a unique ID for a subscriber.\n * If an ID is provided, it will be used; otherwise, a new one is generated.\n *\n * @param id An optional ID to use.\n * @returns A unique subscriber ID.\n * @category Utilities\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn();\n * const id1 = siggn.makeId(); // e.g., \"sub_0\"\n * const id2 = siggn.makeId('custom-id'); // \"custom-id\"\n * ```\n */\n makeId(s) {\n return s ?? `sub_${(this.nextId++).toString(36)}`;\n }\n /**\n * Creates a subscription helper object that is pre-configured with a\n * specific subscriber ID. This simplifies managing multiple subscriptions\n * for a single component or service.\n *\n * @param id The subscriber ID to use for all subscriptions.\n * @returns An object with `subscribe`, `unsubscribe`, `subscribeMany`, and `subscribeAll` methods.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'event' }>();\n * const component = siggn.make('my-component');\n * component.subscribe('event', () => console.log('event received!'));\n * component.unsubscribe();\n * ```\n */\n make(s) {\n return {\n subscribe: (i, t) => {\n this.subscribe(s, i, t);\n },\n unsubscribe: () => {\n this.unsubscribe(s);\n },\n subscribeMany: (i) => {\n this.subscribeMany(s, i);\n },\n subscribeAll: (i) => {\n this.subscribeAll(s, i);\n }\n };\n }\n /**\n * Subscribes to multiple message types using a single subscriber ID.\n *\n * @param id The subscriber ID.\n * @param setup A function that receives a `subscribe` helper to register callbacks.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeMany('subscriber-1', (subscribe) => {\n * subscribe('A', () => console.log('A received'));\n * subscribe('B', () => console.log('B received'));\n * });\n * ```\n */\n subscribeMany(s, i) {\n i((t, r) => this.subscribe(s, t, r));\n }\n /**\n * Subscribes to a specific message type.\n *\n * @param id The subscriber ID.\n * @param type The message type to subscribe to.\n * @param callback The function to call when a message of the specified type is published.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event', payload: string }>();\n * siggn.subscribe('subscriber-1', 'my-event', (msg) => {\n * console.log(msg.payload);\n * });\n * ```\n */\n subscribe(s, i, t) {\n this.subscriptions.has(i) || this.subscriptions.set(i, []), this.registry.register(t, s), this.subscriptions.get(i)?.push({ id: s, ref: new WeakRef(t) });\n }\n /**\n * Subscribes to all message types. The callback will be invoked for every\n * message published on the bus.\n *\n * @param id The subscriber ID.\n * @param callback The function to call for any message.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeAll('logger', (msg) => {\n * console.log(`Received message of type: ${msg.type}`);\n * });\n * ```\n */\n subscribeAll(s, i) {\n this.registryGlobal.register(i, s), this.globalSubscriptions.push({ id: s, ref: new WeakRef(i) });\n }\n /**\n * Publishes a message to all relevant subscribers.\n *\n * @param msg The message to publish.\n * @category Publishing\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.publish({ type: 'my-event' }); // \"received\"\n * ```\n */\n publish(s) {\n this.globalSubscriptions.forEach((i) => {\n const t = i.ref.deref();\n if (!t) {\n this.unsubscribeGlobal(i.id);\n return;\n }\n t(s);\n }), this.subscriptions.has(s.type) && this.subscriptions.get(s.type)?.forEach((i) => {\n const t = i.ref.deref();\n if (!t) {\n this.unsubscribe(i.id);\n return;\n }\n t(s);\n });\n }\n /**\n * Removes all subscriptions (both specific and global) for a given\n * subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.unsubscribe('sub-1');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribe(s) {\n this.unsubscribeGlobal(s);\n for (const [i, t] of this.subscriptions)\n this.subscriptions.set(\n i,\n t.filter((r) => r.id !== s)\n );\n }\n /**\n * Removes a global subscription for a given subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribeAll('logger', console.log);\n * siggn.unsubscribeGlobal('logger');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribeGlobal(s) {\n this.globalSubscriptions = this.globalSubscriptions.filter((i) => i.id !== s);\n }\n /**\n * Returns the total number of subscriptions (both specific and global).\n *\n * @category Subscription\n * @since 0.1.0\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => {});\n * siggn.subscribeAll('logger', () => {});\n * console.log(siggn.subscriptionsCount); // 2\n * ```\n */\n get subscriptionsCount() {\n let s = 0;\n return this.subscriptions.forEach((i) => {\n s += i.length;\n }), s += this.globalSubscriptions.length, s;\n }\n}\nexport {\n e as Siggn\n};\n//# sourceMappingURL=index.es.js.map\n","import { type Msg, Siggn } from '@siggn/core';\nimport type { SubscriptionOptions } from 'packages/react/src/types';\nimport { useEffect, useMemo, useRef, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const siggn = useRef(new Siggn<T>());\n return siggn.current;\n}\n\n/**\n * Subscribes to messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<T extends Msg>(\n options: SubscriptionOptions<T>,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: SubscriptionOptions<T>,\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["e","t","useSiggn","useRef","Siggn","useSubscribe","options","setup","deps","instance","useMemo","id","useEffect","useSubscribeAll","callback"],"mappings":"yGAAA,MAAMA,CAAE,CACN,OAAS,EACT,cACA,oBAAsB,CAAA,EAKtB,SAAW,IAAI,qBAAsB,GAAM,CACzC,KAAK,YAAY,CAAC,CACpB,CAAC,EAKD,eAAiB,IAAI,qBAAsB,GAAM,CAC/C,KAAK,kBAAkB,CAAC,CAC1B,CAAC,EAMD,aAAc,CACZ,KAAK,cAAgC,IAAI,GAC3C,CAiBA,aAAc,CACZ,OAAO,IAAIA,CAC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AkBE,CAAE,CAC/B,GACC,CAACF,EAAUE,EAAI,GAAGH,CAAI,CAAC,CAC5B"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/hooks.ts"],"sourcesContent":["import { type Msg, Siggn } from '@siggn/core';\n\nimport { useEffect, useMemo, useState, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const [siggn] = useState(new Siggn<T>());\n return siggn;\n}\n\n/**\n * Subscribes to multiple messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribeMany(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * subscribe('user-updated', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribeMany<M extends Msg>(\n options: Siggn<M> | { instance: Siggn<M>; id?: string },\n setup: (\n subscribe: <T extends M['type']>(\n type: T,\n callback: (msg: Extract<M, { type: T }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to a single message and automatically unsubscribe when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, 'user-created', (msg) => console.log(msg.name));\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<M extends Msg, T extends string>(\n options: Siggn<M> | { instance: Siggn<M>; id?: string },\n type: T,\n callback: (msg: Extract<M, { type: T }>) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribe(id, type, callback);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: Siggn<T> | { instance: Siggn<T>; id?: string },\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["useSiggn","siggn","useState","Siggn","useSubscribeMany","options","setup","deps","instance","useMemo","id","useEffect","useSubscribe","type","callback","useSubscribeAll"],"mappings":"kIAqBO,SAASA,GAAoC,CAClD,KAAM,CAACC,CAAK,EAAIC,WAAS,IAAIC,EAAAA,KAAU,EACvC,OAAOF,CACT,CAyBO,SAASG,EACdC,EACAC,EAMAC,EAAuB,CAAA,EACvB,CACA,MAAMC,EAAWC,EAAAA,QACf,IAAOJ,aAAmBF,EAAAA,MAAQE,EAAUA,EAAQ,SACpD,CAACA,CAAO,CAAA,EAEJK,EAAKD,EAAAA,QAAQ,IAAMD,EAAS,OAAO,OAAQH,EAAUA,EAAQ,GAAK,MAAS,EAAG,CAACG,CAAQ,CAAC,EAE9FG,EAAAA,UAAU,KACRH,EAAS,cAAcE,EAAIJ,CAAK,EAEzB,IAAM,CACXE,EAAS,YAAYE,CAAE,CACzB,GACC,CAACF,EAAUE,EAAI,GAAGH,CAAI,CAAC,CAC5B,CAsBO,SAASK,EACdP,EACAQ,EACAC,EACAP,EAAuB,CAAA,EACvB,CACA,MAAMC,EAAWC,EAAAA,QACf,IAAOJ,aAAmBF,EAAAA,MAAQE,EAAUA,EAAQ,SACpD,CAACA,CAAO,CAAA,EAEJK,EAAKD,EAAAA,QAAQ,IAAMD,EAAS,OAAO,OAAQH,EAAUA,EAAQ,GAAK,MAAS,EAAG,CAACG,CAAQ,CAAC,EAE9FG,EAAAA,UAAU,KACRH,EAAS,UAAUE,EAAIG,EAAMC,CAAQ,EAE9B,IAAM,CACXN,EAAS,YAAYE,CAAE,CACzB,GACC,CAACF,EAAUE,EAAI,GAAGH,CAAI,CAAC,CAC5B,CAyBO,SAASQ,EACdV,EACAS,EACAP,EAAuB,CAAA,EACvB,CACA,MAAMC,EAAWC,EAAAA,QACf,IAAOJ,aAAmBF,EAAAA,MAAQE,EAAUA,EAAQ,SACpD,CAACA,CAAO,CAAA,EAEJK,EAAKD,EAAAA,QAAQ,IAAMD,EAAS,OAAO,OAAQH,EAAUA,EAAQ,GAAK,MAAS,EAAG,CAACG,CAAQ,CAAC,EAE9FG,EAAAA,UAAU,KACRH,EAAS,aAAaE,EAAII,CAAQ,EAE3B,IAAM,CACXN,EAAS,kBAAkBE,CAAE,CAC/B,GACC,CAACF,EAAUE,EAAI,GAAGH,CAAI,CAAC,CAC5B"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,281 +1,41 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
* A FinalizationRegistry to automatically unregister specific subscriptions
|
|
8
|
-
* when the subscribed callback function is garbage collected.
|
|
9
|
-
*/
|
|
10
|
-
registry = new FinalizationRegistry((s) => {
|
|
11
|
-
this.unsubscribe(s);
|
|
12
|
-
});
|
|
13
|
-
/**
|
|
14
|
-
* A FinalizationRegistry to automatically unregister global subscriptions
|
|
15
|
-
* when the subscribed callback function is garbage collected.
|
|
16
|
-
*/
|
|
17
|
-
registryGlobal = new FinalizationRegistry((s) => {
|
|
18
|
-
this.unsubscribeGlobal(s);
|
|
19
|
-
});
|
|
20
|
-
/**
|
|
21
|
-
* Creates a new Siggn instance.
|
|
22
|
-
* @category Lifecycle
|
|
23
|
-
* @since 0.0.5
|
|
24
|
-
*/
|
|
25
|
-
constructor() {
|
|
26
|
-
this.subscriptions = /* @__PURE__ */ new Map();
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Creates a new, independent `Siggn` instance that inherits the message
|
|
30
|
-
* types of its parent and adds new ones.
|
|
31
|
-
*
|
|
32
|
-
* @template C The new message types to add.
|
|
33
|
-
* @returns A new `Siggn` instance with combined message types.
|
|
34
|
-
* @category Lifecycle
|
|
35
|
-
* @since 0.0.5
|
|
36
|
-
* @example
|
|
37
|
-
*
|
|
38
|
-
```typescript
|
|
39
|
-
* const baseSiggn = new Siggn<{ type: 'A' }>();
|
|
40
|
-
* const childSiggn = baseSiggn.createClone<{ type: 'B' }>();
|
|
41
|
-
* // childSiggn can now publish and subscribe to types 'A' and 'B'.
|
|
42
|
-
* ```
|
|
43
|
-
*/
|
|
44
|
-
createClone() {
|
|
45
|
-
return new n();
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Generates a unique ID for a subscriber.
|
|
49
|
-
* If an ID is provided, it will be used; otherwise, a new one is generated.
|
|
50
|
-
*
|
|
51
|
-
* @param id An optional ID to use.
|
|
52
|
-
* @returns A unique subscriber ID.
|
|
53
|
-
* @category Utilities
|
|
54
|
-
* @since 0.0.5
|
|
55
|
-
* @example
|
|
56
|
-
*
|
|
57
|
-
```typescript
|
|
58
|
-
* const siggn = new Siggn();
|
|
59
|
-
* const id1 = siggn.makeId(); // e.g., "sub_0"
|
|
60
|
-
* const id2 = siggn.makeId('custom-id'); // "custom-id"
|
|
61
|
-
* ```
|
|
62
|
-
*/
|
|
63
|
-
makeId(s) {
|
|
64
|
-
return s ?? `sub_${(this.nextId++).toString(36)}`;
|
|
65
|
-
}
|
|
66
|
-
/**
|
|
67
|
-
* Creates a subscription helper object that is pre-configured with a
|
|
68
|
-
* specific subscriber ID. This simplifies managing multiple subscriptions
|
|
69
|
-
* for a single component or service.
|
|
70
|
-
*
|
|
71
|
-
* @param id The subscriber ID to use for all subscriptions.
|
|
72
|
-
* @returns An object with `subscribe`, `unsubscribe`, `subscribeMany`, and `subscribeAll` methods.
|
|
73
|
-
* @category Subscription
|
|
74
|
-
* @since 0.0.5
|
|
75
|
-
* @example
|
|
76
|
-
*
|
|
77
|
-
```typescript
|
|
78
|
-
* const siggn = new Siggn<{ type: 'event' }>();
|
|
79
|
-
* const component = siggn.make('my-component');
|
|
80
|
-
* component.subscribe('event', () => console.log('event received!'));
|
|
81
|
-
* component.unsubscribe();
|
|
82
|
-
* ```
|
|
83
|
-
*/
|
|
84
|
-
make(s) {
|
|
85
|
-
return {
|
|
86
|
-
subscribe: (i, e) => {
|
|
87
|
-
this.subscribe(s, i, e);
|
|
88
|
-
},
|
|
89
|
-
unsubscribe: () => {
|
|
90
|
-
this.unsubscribe(s);
|
|
91
|
-
},
|
|
92
|
-
subscribeMany: (i) => {
|
|
93
|
-
this.subscribeMany(s, i);
|
|
94
|
-
},
|
|
95
|
-
subscribeAll: (i) => {
|
|
96
|
-
this.subscribeAll(s, i);
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Subscribes to multiple message types using a single subscriber ID.
|
|
102
|
-
*
|
|
103
|
-
* @param id The subscriber ID.
|
|
104
|
-
* @param setup A function that receives a `subscribe` helper to register callbacks.
|
|
105
|
-
* @category Subscription
|
|
106
|
-
* @since 0.0.5
|
|
107
|
-
* @example
|
|
108
|
-
*
|
|
109
|
-
```typescript
|
|
110
|
-
* const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();
|
|
111
|
-
* siggn.subscribeMany('subscriber-1', (subscribe) => {
|
|
112
|
-
* subscribe('A', () => console.log('A received'));
|
|
113
|
-
* subscribe('B', () => console.log('B received'));
|
|
114
|
-
* });
|
|
115
|
-
* ```
|
|
116
|
-
*/
|
|
117
|
-
subscribeMany(s, i) {
|
|
118
|
-
i((e, r) => this.subscribe(s, e, r));
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Subscribes to a specific message type.
|
|
122
|
-
*
|
|
123
|
-
* @param id The subscriber ID.
|
|
124
|
-
* @param type The message type to subscribe to.
|
|
125
|
-
* @param callback The function to call when a message of the specified type is published.
|
|
126
|
-
* @category Subscription
|
|
127
|
-
* @since 0.0.5
|
|
128
|
-
* @example
|
|
129
|
-
*
|
|
130
|
-
```typescript
|
|
131
|
-
* const siggn = new Siggn<{ type: 'my-event', payload: string }>();
|
|
132
|
-
* siggn.subscribe('subscriber-1', 'my-event', (msg) => {
|
|
133
|
-
* console.log(msg.payload);
|
|
134
|
-
* });
|
|
135
|
-
* ```
|
|
136
|
-
*/
|
|
137
|
-
subscribe(s, i, e) {
|
|
138
|
-
this.subscriptions.has(i) || this.subscriptions.set(i, []), this.registry.register(e, s), this.subscriptions.get(i)?.push({ id: s, ref: new WeakRef(e) });
|
|
139
|
-
}
|
|
140
|
-
/**
|
|
141
|
-
* Subscribes to all message types. The callback will be invoked for every
|
|
142
|
-
* message published on the bus.
|
|
143
|
-
*
|
|
144
|
-
* @param id The subscriber ID.
|
|
145
|
-
* @param callback The function to call for any message.
|
|
146
|
-
* @category Subscription
|
|
147
|
-
* @since 0.0.5
|
|
148
|
-
* @example
|
|
149
|
-
*
|
|
150
|
-
```typescript
|
|
151
|
-
* const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();
|
|
152
|
-
* siggn.subscribeAll('logger', (msg) => {
|
|
153
|
-
* console.log(`Received message of type: ${msg.type}`);
|
|
154
|
-
* });
|
|
155
|
-
* ```
|
|
156
|
-
*/
|
|
157
|
-
subscribeAll(s, i) {
|
|
158
|
-
this.registryGlobal.register(i, s), this.globalSubscriptions.push({ id: s, ref: new WeakRef(i) });
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Publishes a message to all relevant subscribers.
|
|
162
|
-
*
|
|
163
|
-
* @param msg The message to publish.
|
|
164
|
-
* @category Publishing
|
|
165
|
-
* @since 0.0.5
|
|
166
|
-
* @example
|
|
167
|
-
*
|
|
168
|
-
```typescript
|
|
169
|
-
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
170
|
-
* siggn.subscribe('sub-1', 'my-event', () => console.log('received'));
|
|
171
|
-
* siggn.publish({ type: 'my-event' }); // "received"
|
|
172
|
-
* ```
|
|
173
|
-
*/
|
|
174
|
-
publish(s) {
|
|
175
|
-
this.globalSubscriptions.forEach((i) => {
|
|
176
|
-
const e = i.ref.deref();
|
|
177
|
-
if (!e) {
|
|
178
|
-
this.unsubscribeGlobal(i.id);
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
e(s);
|
|
182
|
-
}), this.subscriptions.has(s.type) && this.subscriptions.get(s.type)?.forEach((i) => {
|
|
183
|
-
const e = i.ref.deref();
|
|
184
|
-
if (!e) {
|
|
185
|
-
this.unsubscribe(i.id);
|
|
186
|
-
return;
|
|
187
|
-
}
|
|
188
|
-
e(s);
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Removes all subscriptions (both specific and global) for a given
|
|
193
|
-
* subscriber ID.
|
|
194
|
-
*
|
|
195
|
-
* @param id The subscriber ID to unsubscribe.
|
|
196
|
-
* @category Subscription
|
|
197
|
-
* @since 0.0.5
|
|
198
|
-
* @example
|
|
199
|
-
*
|
|
200
|
-
```typescript
|
|
201
|
-
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
202
|
-
* siggn.subscribe('sub-1', 'my-event', () => console.log('received'));
|
|
203
|
-
* siggn.unsubscribe('sub-1');
|
|
204
|
-
* siggn.publish({ type: 'my-event' }); // (nothing is logged)
|
|
205
|
-
* ```
|
|
206
|
-
*/
|
|
207
|
-
unsubscribe(s) {
|
|
208
|
-
this.unsubscribeGlobal(s);
|
|
209
|
-
for (const [i, e] of this.subscriptions)
|
|
210
|
-
this.subscriptions.set(
|
|
211
|
-
i,
|
|
212
|
-
e.filter((r) => r.id !== s)
|
|
213
|
-
);
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Removes a global subscription for a given subscriber ID.
|
|
217
|
-
*
|
|
218
|
-
* @param id The subscriber ID to unsubscribe.
|
|
219
|
-
* @category Subscription
|
|
220
|
-
* @since 0.0.5
|
|
221
|
-
* @example
|
|
222
|
-
*
|
|
223
|
-
```typescript
|
|
224
|
-
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
225
|
-
* siggn.subscribeAll('logger', console.log);
|
|
226
|
-
* siggn.unsubscribeGlobal('logger');
|
|
227
|
-
* siggn.publish({ type: 'my-event' }); // (nothing is logged)
|
|
228
|
-
* ```
|
|
229
|
-
*/
|
|
230
|
-
unsubscribeGlobal(s) {
|
|
231
|
-
this.globalSubscriptions = this.globalSubscriptions.filter((i) => i.id !== s);
|
|
232
|
-
}
|
|
233
|
-
/**
|
|
234
|
-
* Returns the total number of subscriptions (both specific and global).
|
|
235
|
-
*
|
|
236
|
-
* @category Subscription
|
|
237
|
-
* @since 0.1.0
|
|
238
|
-
* @example
|
|
239
|
-
*
|
|
240
|
-
```typescript
|
|
241
|
-
* const siggn = new Siggn<{ type: 'my-event' }>();
|
|
242
|
-
* siggn.subscribe('sub-1', 'my-event', () => {});
|
|
243
|
-
* siggn.subscribeAll('logger', () => {});
|
|
244
|
-
* console.log(siggn.subscriptionsCount); // 2
|
|
245
|
-
* ```
|
|
246
|
-
*/
|
|
247
|
-
get subscriptionsCount() {
|
|
248
|
-
let s = 0;
|
|
249
|
-
return this.subscriptions.forEach((i) => {
|
|
250
|
-
s += i.length;
|
|
251
|
-
}), s += this.globalSubscriptions.length, s;
|
|
252
|
-
}
|
|
1
|
+
import { Siggn as s } from "@siggn/core";
|
|
2
|
+
export * from "@siggn/core";
|
|
3
|
+
import { useState as t, useMemo as i, useEffect as a } from "react";
|
|
4
|
+
function m() {
|
|
5
|
+
const [e] = t(new s());
|
|
6
|
+
return e;
|
|
253
7
|
}
|
|
254
|
-
function
|
|
255
|
-
|
|
8
|
+
function g(e, u, r = []) {
|
|
9
|
+
const n = i(
|
|
10
|
+
() => e instanceof s ? e : e.instance,
|
|
11
|
+
[e]
|
|
12
|
+
), c = i(() => n.makeId("id" in e ? e.id : void 0), [n]);
|
|
13
|
+
a(() => (n.subscribeMany(c, u), () => {
|
|
14
|
+
n.unsubscribe(c);
|
|
15
|
+
}), [n, c, ...r]);
|
|
256
16
|
}
|
|
257
|
-
function
|
|
258
|
-
const
|
|
259
|
-
() =>
|
|
260
|
-
[
|
|
261
|
-
),
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
}), [
|
|
17
|
+
function l(e, u, r, n = []) {
|
|
18
|
+
const c = i(
|
|
19
|
+
() => e instanceof s ? e : e.instance,
|
|
20
|
+
[e]
|
|
21
|
+
), b = i(() => c.makeId("id" in e ? e.id : void 0), [c]);
|
|
22
|
+
a(() => (c.subscribe(b, u, r), () => {
|
|
23
|
+
c.unsubscribe(b);
|
|
24
|
+
}), [c, b, ...n]);
|
|
265
25
|
}
|
|
266
|
-
function
|
|
267
|
-
const
|
|
268
|
-
() =>
|
|
269
|
-
[
|
|
270
|
-
),
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
}), [
|
|
26
|
+
function S(e, u, r = []) {
|
|
27
|
+
const n = i(
|
|
28
|
+
() => e instanceof s ? e : e.instance,
|
|
29
|
+
[e]
|
|
30
|
+
), c = i(() => n.makeId("id" in e ? e.id : void 0), [n]);
|
|
31
|
+
a(() => (n.subscribeAll(c, u), () => {
|
|
32
|
+
n.unsubscribeGlobal(c);
|
|
33
|
+
}), [n, c, ...r]);
|
|
274
34
|
}
|
|
275
35
|
export {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
36
|
+
m as useSiggn,
|
|
37
|
+
l as useSubscribe,
|
|
38
|
+
S as useSubscribeAll,
|
|
39
|
+
g as useSubscribeMany
|
|
280
40
|
};
|
|
281
41
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../../core/dist/index.es.js","../src/hooks.ts"],"sourcesContent":["class e {\n nextId = 0;\n subscriptions;\n globalSubscriptions = [];\n /**\n * A FinalizationRegistry to automatically unregister specific subscriptions\n * when the subscribed callback function is garbage collected.\n */\n registry = new FinalizationRegistry((s) => {\n this.unsubscribe(s);\n });\n /**\n * A FinalizationRegistry to automatically unregister global subscriptions\n * when the subscribed callback function is garbage collected.\n */\n registryGlobal = new FinalizationRegistry((s) => {\n this.unsubscribeGlobal(s);\n });\n /**\n * Creates a new Siggn instance.\n * @category Lifecycle\n * @since 0.0.5\n */\n constructor() {\n this.subscriptions = /* @__PURE__ */ new Map();\n }\n /**\n * Creates a new, independent `Siggn` instance that inherits the message\n * types of its parent and adds new ones.\n *\n * @template C The new message types to add.\n * @returns A new `Siggn` instance with combined message types.\n * @category Lifecycle\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const baseSiggn = new Siggn<{ type: 'A' }>();\n * const childSiggn = baseSiggn.createClone<{ type: 'B' }>();\n * // childSiggn can now publish and subscribe to types 'A' and 'B'.\n * ```\n */\n createClone() {\n return new e();\n }\n /**\n * Generates a unique ID for a subscriber.\n * If an ID is provided, it will be used; otherwise, a new one is generated.\n *\n * @param id An optional ID to use.\n * @returns A unique subscriber ID.\n * @category Utilities\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn();\n * const id1 = siggn.makeId(); // e.g., \"sub_0\"\n * const id2 = siggn.makeId('custom-id'); // \"custom-id\"\n * ```\n */\n makeId(s) {\n return s ?? `sub_${(this.nextId++).toString(36)}`;\n }\n /**\n * Creates a subscription helper object that is pre-configured with a\n * specific subscriber ID. This simplifies managing multiple subscriptions\n * for a single component or service.\n *\n * @param id The subscriber ID to use for all subscriptions.\n * @returns An object with `subscribe`, `unsubscribe`, `subscribeMany`, and `subscribeAll` methods.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'event' }>();\n * const component = siggn.make('my-component');\n * component.subscribe('event', () => console.log('event received!'));\n * component.unsubscribe();\n * ```\n */\n make(s) {\n return {\n subscribe: (i, t) => {\n this.subscribe(s, i, t);\n },\n unsubscribe: () => {\n this.unsubscribe(s);\n },\n subscribeMany: (i) => {\n this.subscribeMany(s, i);\n },\n subscribeAll: (i) => {\n this.subscribeAll(s, i);\n }\n };\n }\n /**\n * Subscribes to multiple message types using a single subscriber ID.\n *\n * @param id The subscriber ID.\n * @param setup A function that receives a `subscribe` helper to register callbacks.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeMany('subscriber-1', (subscribe) => {\n * subscribe('A', () => console.log('A received'));\n * subscribe('B', () => console.log('B received'));\n * });\n * ```\n */\n subscribeMany(s, i) {\n i((t, r) => this.subscribe(s, t, r));\n }\n /**\n * Subscribes to a specific message type.\n *\n * @param id The subscriber ID.\n * @param type The message type to subscribe to.\n * @param callback The function to call when a message of the specified type is published.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event', payload: string }>();\n * siggn.subscribe('subscriber-1', 'my-event', (msg) => {\n * console.log(msg.payload);\n * });\n * ```\n */\n subscribe(s, i, t) {\n this.subscriptions.has(i) || this.subscriptions.set(i, []), this.registry.register(t, s), this.subscriptions.get(i)?.push({ id: s, ref: new WeakRef(t) });\n }\n /**\n * Subscribes to all message types. The callback will be invoked for every\n * message published on the bus.\n *\n * @param id The subscriber ID.\n * @param callback The function to call for any message.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'A' } | { type: 'B' }>();\n * siggn.subscribeAll('logger', (msg) => {\n * console.log(`Received message of type: ${msg.type}`);\n * });\n * ```\n */\n subscribeAll(s, i) {\n this.registryGlobal.register(i, s), this.globalSubscriptions.push({ id: s, ref: new WeakRef(i) });\n }\n /**\n * Publishes a message to all relevant subscribers.\n *\n * @param msg The message to publish.\n * @category Publishing\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.publish({ type: 'my-event' }); // \"received\"\n * ```\n */\n publish(s) {\n this.globalSubscriptions.forEach((i) => {\n const t = i.ref.deref();\n if (!t) {\n this.unsubscribeGlobal(i.id);\n return;\n }\n t(s);\n }), this.subscriptions.has(s.type) && this.subscriptions.get(s.type)?.forEach((i) => {\n const t = i.ref.deref();\n if (!t) {\n this.unsubscribe(i.id);\n return;\n }\n t(s);\n });\n }\n /**\n * Removes all subscriptions (both specific and global) for a given\n * subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => console.log('received'));\n * siggn.unsubscribe('sub-1');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribe(s) {\n this.unsubscribeGlobal(s);\n for (const [i, t] of this.subscriptions)\n this.subscriptions.set(\n i,\n t.filter((r) => r.id !== s)\n );\n }\n /**\n * Removes a global subscription for a given subscriber ID.\n *\n * @param id The subscriber ID to unsubscribe.\n * @category Subscription\n * @since 0.0.5\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribeAll('logger', console.log);\n * siggn.unsubscribeGlobal('logger');\n * siggn.publish({ type: 'my-event' }); // (nothing is logged)\n * ```\n */\n unsubscribeGlobal(s) {\n this.globalSubscriptions = this.globalSubscriptions.filter((i) => i.id !== s);\n }\n /**\n * Returns the total number of subscriptions (both specific and global).\n *\n * @category Subscription\n * @since 0.1.0\n * @example\n * \n ```typescript\n * const siggn = new Siggn<{ type: 'my-event' }>();\n * siggn.subscribe('sub-1', 'my-event', () => {});\n * siggn.subscribeAll('logger', () => {});\n * console.log(siggn.subscriptionsCount); // 2\n * ```\n */\n get subscriptionsCount() {\n let s = 0;\n return this.subscriptions.forEach((i) => {\n s += i.length;\n }), s += this.globalSubscriptions.length, s;\n }\n}\nexport {\n e as Siggn\n};\n//# sourceMappingURL=index.es.js.map\n","import { type Msg, Siggn } from '@siggn/core';\nimport type { SubscriptionOptions } from 'packages/react/src/types';\nimport { useEffect, useMemo, useRef, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const siggn = useRef(new Siggn<T>());\n return siggn.current;\n}\n\n/**\n * Subscribes to messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<T extends Msg>(\n options: SubscriptionOptions<T>,\n setup: (\n subscribe: <K extends T['type']>(\n type: K,\n callback: (msg: Extract<T, { type: K }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: SubscriptionOptions<T>,\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["e","t","useSiggn","useRef","Siggn","useSubscribe","options","setup","deps","instance","useMemo","id","useEffect","useSubscribeAll","callback"],"mappings":";AAAA,MAAMA,EAAE;AAAA,EACN,SAAS;AAAA,EACT;AAAA,EACA,sBAAsB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKtB,WAAW,IAAI,qBAAqB,CAAC,MAAM;AACzC,SAAK,YAAY,CAAC;AAAA,EACpB,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,EAKD,iBAAiB,IAAI,qBAAqB,CAAC,MAAM;AAC/C,SAAK,kBAAkB,CAAC;AAAA,EAC1B,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMD,cAAc;AACZ,SAAK,gBAAgC,oBAAI,IAAG;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,cAAc;AACZ,WAAO,IAAIA,EAAC;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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@siggn/core';\n\nimport { useEffect, useMemo, useState, type DependencyList } from 'react';\n\n/**\n * Creates and returns a `Siggn` instance that persists for the lifetime of the component.\n * This is useful for creating a message bus scoped to a component and its children.\n *\n * @template T A union of all possible message types for the new instance.\n * @returns A `Siggn<T>` instance.\n * @category Lifecycle\n * @since 0.0.1\n * @example\n * \n```tsx\n * function MyComponent() {\n * const localSiggn = useSiggn<{ type: 'local-event' }>();\n * // ...\n * }\n * ```\n */\nexport function useSiggn<T extends Msg>(): Siggn<T> {\n const [siggn] = useState(new Siggn<T>());\n return siggn;\n}\n\n/**\n * Subscribes to multiple messages and automatically unsubscribes when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribeMany(siggn, (subscribe) => {\n * subscribe('user-created', (msg) => console.log(msg.name));\n * subscribe('user-updated', (msg) => console.log(msg.name));\n * });\n * // ...\n * }\n * ```\n */\nexport function useSubscribeMany<M extends Msg>(\n options: Siggn<M> | { instance: Siggn<M>; id?: string },\n setup: (\n subscribe: <T extends M['type']>(\n type: T,\n callback: (msg: Extract<M, { type: T }>) => void,\n ) => void,\n ) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeMany(id, setup);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to a single message and automatically unsubscribe when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param setup A function that receives a `subscribe` helper to define subscriptions.\n * @param deps An optional dependency array to control when the subscriptions are re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn'; // Your shared instance\n *\n * function MyComponent() {\n * useSubscribe(siggn, 'user-created', (msg) => console.log(msg.name));\n * // ...\n * }\n * ```\n */\nexport function useSubscribe<M extends Msg, T extends string>(\n options: Siggn<M> | { instance: Siggn<M>; id?: string },\n type: T,\n callback: (msg: Extract<M, { type: T }>) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribe(id, type, callback);\n\n return () => {\n instance.unsubscribe(id);\n };\n }, [instance, id, ...deps]);\n}\n\n/**\n * Subscribes to all messages on a `Siggn` instance and automatically unsubscribes\n * when the component unmounts.\n *\n * @template T A union of all possible message types.\n * @param options A `Siggn` instance or an object with the instance and an optional subscriber ID.\n * @param callback The function to call for any message.\n * @param deps An optional dependency array to control when the subscription is re-created.\n * @category Subscription\n * @since 0.0.1\n * @example\n * \n```tsx\n * import { siggn } from './siggn';\n *\n * function LoggerComponent() {\n * useSubscribeAll(siggn, (msg) => {\n * console.log(`[LOG]: ${msg.type}`);\n * }, []);\n * // ...\n * }\n * ```\n */\nexport function useSubscribeAll<T extends Msg>(\n options: Siggn<T> | { instance: Siggn<T>; id?: string },\n callback: (msg: T) => void,\n deps: DependencyList = [],\n) {\n const instance = useMemo(\n () => (options instanceof Siggn ? options : options.instance),\n [options],\n );\n const id = useMemo(() => instance.makeId('id' in options ? options.id : undefined), [instance]);\n\n useEffect(() => {\n instance.subscribeAll(id, callback);\n\n return () => {\n instance.unsubscribeGlobal(id);\n };\n }, [instance, id, ...deps]);\n}\n"],"names":["useSiggn","siggn","useState","Siggn","useSubscribeMany","options","setup","deps","instance","useMemo","id","useEffect","useSubscribe","type","callback","useSubscribeAll"],"mappings":";;;AAqBO,SAASA,IAAoC;AAClD,Q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AACX,IAAAN,EAAS,kBAAkBE,CAAE;AAAA,EAC/B,IACC,CAACF,GAAUE,GAAI,GAAGH,CAAI,CAAC;AAC5B;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@siggn/react",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "A lightweight type safe message bus system for React",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pub/sub",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"react": ">=18 <20"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@siggn/core": "0.1.
|
|
61
|
+
"@siggn/core": "0.1.1"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"dev": "vite build --watch",
|