@atomic-reactor/use-event-handle 0.0.0-stage → 1.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 +83 -2
- package/dist/index.cjs +56 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +11 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -0
- package/package.json +83 -4
- package/src/index.ts +6 -0
- package/src/useEventHandle.ts +51 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 camdagr8
|
|
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
CHANGED
|
@@ -1,3 +1,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @atomic-reactor/use-event-handle
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A tiny React hook that subscribes a component to an
|
|
4
|
+
[`@atomic-reactor/event-handle`](https://github.com/ReactiumCore/EventHandle)
|
|
5
|
+
target, or to any DOM `EventTarget`, and unsubscribes on unmount. Works in
|
|
6
|
+
React DOM and React Native, and ships ESM, CommonJS and TypeScript types.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install --save @atomic-reactor/use-event-handle
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
`react` (16.8+) is a peer dependency. `@atomic-reactor/event-handle` is
|
|
15
|
+
installed with this package, and its `Event` and `EventTarget` are re-exported,
|
|
16
|
+
so one import covers both.
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```tsx
|
|
21
|
+
import { useState } from 'react';
|
|
22
|
+
import {
|
|
23
|
+
Event,
|
|
24
|
+
EventTarget,
|
|
25
|
+
useEventEffect,
|
|
26
|
+
} from '@atomic-reactor/use-event-handle';
|
|
27
|
+
|
|
28
|
+
class DatePicker extends EventTarget {
|
|
29
|
+
setDate(value: Date) {
|
|
30
|
+
this.dispatchEvent(new Event('date-changed', { value }));
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const picker = new DatePicker();
|
|
35
|
+
|
|
36
|
+
export function SelectedDate() {
|
|
37
|
+
const [date, setDate] = useState<Date>();
|
|
38
|
+
|
|
39
|
+
useEventEffect(picker, {
|
|
40
|
+
'date-changed': (event) => setDate(event.value),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
return <span>{date?.toDateString()}</span>;
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### `useEventEffect(target, handlers, deps?)`
|
|
48
|
+
|
|
49
|
+
| Argument | Description |
|
|
50
|
+
| ---------- | --------------------------------------------------------------------------------------------------------- |
|
|
51
|
+
| `target` | Anything with `addEventListener`/`removeEventListener`. When `null` or `undefined`, nothing is added |
|
|
52
|
+
| `handlers` | `{ [type]: listener }`. Entries that aren't functions are skipped, e.g. `{ change: enabled && onChange }` |
|
|
53
|
+
| `deps` | Re-adds the handlers when these change. Defaults to `[]` |
|
|
54
|
+
|
|
55
|
+
The handlers are added when the component mounts and removed when it
|
|
56
|
+
unmounts. They're also moved when `target` changes, and replaced when `deps`
|
|
57
|
+
change.
|
|
58
|
+
|
|
59
|
+
### Stale closures
|
|
60
|
+
|
|
61
|
+
With no `deps`, the handlers from the first render are the ones that stay
|
|
62
|
+
subscribed. A handler that reads props or state should either list them in
|
|
63
|
+
`deps`, or read current values from a ref or a SyncState:
|
|
64
|
+
|
|
65
|
+
```tsx
|
|
66
|
+
useEventEffect(picker, { 'date-changed': onDateChanged }, [onDateChanged]);
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### DOM targets
|
|
70
|
+
|
|
71
|
+
Any DOM `EventTarget` works too, such as `window` or an element:
|
|
72
|
+
|
|
73
|
+
```tsx
|
|
74
|
+
useEventEffect(window, { resize: onResize });
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Compatibility
|
|
78
|
+
|
|
79
|
+
The hook uses only React and ES2019 built-ins and is compiled to ES2019, so
|
|
80
|
+
it needs no polyfills in any current browser, React Native 0.60+ or Node 12+.
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
Event: () => import_event_handle.Event,
|
|
24
|
+
EventTarget: () => import_event_handle.EventTarget,
|
|
25
|
+
useEventEffect: () => useEventEffect
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
|
|
29
|
+
// src/useEventHandle.ts
|
|
30
|
+
var import_react = require("react");
|
|
31
|
+
var useEventEffect = (target, handlers = {}, deps = []) => {
|
|
32
|
+
(0, import_react.useEffect)(() => {
|
|
33
|
+
if (!target) return;
|
|
34
|
+
const subs = [];
|
|
35
|
+
Object.keys(handlers).forEach((type) => {
|
|
36
|
+
const listener = handlers[type];
|
|
37
|
+
if (typeof listener === "function") subs.push([type, listener]);
|
|
38
|
+
});
|
|
39
|
+
subs.forEach(([type, listener]) => target.addEventListener(type, listener));
|
|
40
|
+
return () => {
|
|
41
|
+
subs.forEach(
|
|
42
|
+
([type, listener]) => target.removeEventListener(type, listener)
|
|
43
|
+
);
|
|
44
|
+
};
|
|
45
|
+
}, [target, ...deps]);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
// src/index.ts
|
|
49
|
+
var import_event_handle = require("@atomic-reactor/event-handle");
|
|
50
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
51
|
+
0 && (module.exports = {
|
|
52
|
+
Event,
|
|
53
|
+
EventTarget,
|
|
54
|
+
useEventEffect
|
|
55
|
+
});
|
|
56
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/useEventHandle.ts"],"sourcesContent":["export { useEventEffect } from './useEventHandle';\nexport type { EventHandlers, EventTargetLike } from './useEventHandle';\n\n// Re-exported so one import covers both creating targets and subscribing\nexport { Event, EventTarget } from '@atomic-reactor/event-handle';\nexport type { AppEvent, Listener } from '@atomic-reactor/event-handle';\n","// A hook to subscribe a component to an event target's events. Built for\n// @atomic-reactor/event-handle, where listeners get a copy of the event with\n// its detail spread onto it, e.g. dispatching\n// new Event('date-changed', { value }) reaches listeners as\n// ({ type, value, ... }).\n//\n// Uses only React and ES2019 built-ins (no DOM or Node APIs), so it runs the\n// same in React DOM and React Native.\nimport { useEffect } from 'react';\nimport type { Listener } from '@atomic-reactor/event-handle';\n\n// Anything listeners can be added to and removed from: an event-handle\n// EventTarget, or a DOM EventTarget such as window or an element\nexport interface EventTargetLike {\n addEventListener(type: string, listener: Listener): unknown;\n removeEventListener(type: string, listener: Listener): unknown;\n}\n\n// Listeners by event type. Entries that aren't functions are skipped, so\n// handlers can be added conditionally ({ change: enabled && onChange }).\nexport type EventHandlers = Record<string, Listener | false | null | undefined>;\n\n// Adds `handlers` ({ type: listener }) to `target` and removes them on unmount\n// or when `target` or `deps` change. With no deps they're added once per\n// target, so a listener should read current values from a SyncState or a ref\n// rather than from its render's closure.\nexport const useEventEffect = (\n target: EventTargetLike | null | undefined,\n handlers: EventHandlers = {},\n deps: unknown[] = [],\n) => {\n useEffect(() => {\n if (!target) return;\n\n const subs: Array<[string, Listener]> = [];\n Object.keys(handlers).forEach((type) => {\n const listener = handlers[type];\n if (typeof listener === 'function') subs.push([type, listener]);\n });\n\n subs.forEach(([type, listener]) => target.addEventListener(type, listener));\n\n return () => {\n subs.forEach(([type, listener]) =>\n target.removeEventListener(type, listener),\n );\n };\n // Handlers are read when the effect runs; callers opt in to re-running it\n // through `deps`\n }, [target, ...deps]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQA,mBAA0B;AAkBnB,IAAM,iBAAiB,CAC5B,QACA,WAA0B,CAAC,GAC3B,OAAkB,CAAC,MAChB;AACH,8BAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AAEb,UAAM,OAAkC,CAAC;AACzC,WAAO,KAAK,QAAQ,EAAE,QAAQ,CAAC,SAAS;AACtC,YAAM,WAAW,SAAS,IAAI;AAC9B,UAAI,OAAO,aAAa,WAAY,MAAK,KAAK,CAAC,MAAM,QAAQ,CAAC;AAAA,IAChE,CAAC;AAED,SAAK,QAAQ,CAAC,CAAC,MAAM,QAAQ,MAAM,OAAO,iBAAiB,MAAM,QAAQ,CAAC;AAE1E,WAAO,MAAM;AACX,WAAK;AAAA,QAAQ,CAAC,CAAC,MAAM,QAAQ,MAC3B,OAAO,oBAAoB,MAAM,QAAQ;AAAA,MAC3C;AAAA,IACF;AAAA,EAGF,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC;AACtB;;;AD9CA,0BAAmC;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Listener } from '@atomic-reactor/event-handle';
|
|
2
|
+
export { AppEvent, Event, EventTarget, Listener } from '@atomic-reactor/event-handle';
|
|
3
|
+
|
|
4
|
+
interface EventTargetLike {
|
|
5
|
+
addEventListener(type: string, listener: Listener): unknown;
|
|
6
|
+
removeEventListener(type: string, listener: Listener): unknown;
|
|
7
|
+
}
|
|
8
|
+
type EventHandlers = Record<string, Listener | false | null | undefined>;
|
|
9
|
+
declare const useEventEffect: (target: EventTargetLike | null | undefined, handlers?: EventHandlers, deps?: unknown[]) => void;
|
|
10
|
+
|
|
11
|
+
export { type EventHandlers, type EventTargetLike, useEventEffect };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Listener } from '@atomic-reactor/event-handle';
|
|
2
|
+
export { AppEvent, Event, EventTarget, Listener } from '@atomic-reactor/event-handle';
|
|
3
|
+
|
|
4
|
+
interface EventTargetLike {
|
|
5
|
+
addEventListener(type: string, listener: Listener): unknown;
|
|
6
|
+
removeEventListener(type: string, listener: Listener): unknown;
|
|
7
|
+
}
|
|
8
|
+
type EventHandlers = Record<string, Listener | false | null | undefined>;
|
|
9
|
+
declare const useEventEffect: (target: EventTargetLike | null | undefined, handlers?: EventHandlers, deps?: unknown[]) => void;
|
|
10
|
+
|
|
11
|
+
export { type EventHandlers, type EventTargetLike, useEventEffect };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// src/useEventHandle.ts
|
|
2
|
+
import { useEffect } from "react";
|
|
3
|
+
var useEventEffect = (target, handlers = {}, deps = []) => {
|
|
4
|
+
useEffect(() => {
|
|
5
|
+
if (!target) return;
|
|
6
|
+
const subs = [];
|
|
7
|
+
Object.keys(handlers).forEach((type) => {
|
|
8
|
+
const listener = handlers[type];
|
|
9
|
+
if (typeof listener === "function") subs.push([type, listener]);
|
|
10
|
+
});
|
|
11
|
+
subs.forEach(([type, listener]) => target.addEventListener(type, listener));
|
|
12
|
+
return () => {
|
|
13
|
+
subs.forEach(
|
|
14
|
+
([type, listener]) => target.removeEventListener(type, listener)
|
|
15
|
+
);
|
|
16
|
+
};
|
|
17
|
+
}, [target, ...deps]);
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
import { Event, EventTarget } from "@atomic-reactor/event-handle";
|
|
22
|
+
export {
|
|
23
|
+
Event,
|
|
24
|
+
EventTarget,
|
|
25
|
+
useEventEffect
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/useEventHandle.ts","../src/index.ts"],"sourcesContent":["// A hook to subscribe a component to an event target's events. Built for\n// @atomic-reactor/event-handle, where listeners get a copy of the event with\n// its detail spread onto it, e.g. dispatching\n// new Event('date-changed', { value }) reaches listeners as\n// ({ type, value, ... }).\n//\n// Uses only React and ES2019 built-ins (no DOM or Node APIs), so it runs the\n// same in React DOM and React Native.\nimport { useEffect } from 'react';\nimport type { Listener } from '@atomic-reactor/event-handle';\n\n// Anything listeners can be added to and removed from: an event-handle\n// EventTarget, or a DOM EventTarget such as window or an element\nexport interface EventTargetLike {\n addEventListener(type: string, listener: Listener): unknown;\n removeEventListener(type: string, listener: Listener): unknown;\n}\n\n// Listeners by event type. Entries that aren't functions are skipped, so\n// handlers can be added conditionally ({ change: enabled && onChange }).\nexport type EventHandlers = Record<string, Listener | false | null | undefined>;\n\n// Adds `handlers` ({ type: listener }) to `target` and removes them on unmount\n// or when `target` or `deps` change. With no deps they're added once per\n// target, so a listener should read current values from a SyncState or a ref\n// rather than from its render's closure.\nexport const useEventEffect = (\n target: EventTargetLike | null | undefined,\n handlers: EventHandlers = {},\n deps: unknown[] = [],\n) => {\n useEffect(() => {\n if (!target) return;\n\n const subs: Array<[string, Listener]> = [];\n Object.keys(handlers).forEach((type) => {\n const listener = handlers[type];\n if (typeof listener === 'function') subs.push([type, listener]);\n });\n\n subs.forEach(([type, listener]) => target.addEventListener(type, listener));\n\n return () => {\n subs.forEach(([type, listener]) =>\n target.removeEventListener(type, listener),\n );\n };\n // Handlers are read when the effect runs; callers opt in to re-running it\n // through `deps`\n }, [target, ...deps]);\n};\n","export { useEventEffect } from './useEventHandle';\nexport type { EventHandlers, EventTargetLike } from './useEventHandle';\n\n// Re-exported so one import covers both creating targets and subscribing\nexport { Event, EventTarget } from '@atomic-reactor/event-handle';\nexport type { AppEvent, Listener } from '@atomic-reactor/event-handle';\n"],"mappings":";AAQA,SAAS,iBAAiB;AAkBnB,IAAM,iBAAiB,CAC5B,QACA,WAA0B,CAAC,GAC3B,OAAkB,CAAC,MAChB;AACH,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AAEb,UAAM,OAAkC,CAAC;AACzC,WAAO,KAAK,QAAQ,EAAE,QAAQ,CAAC,SAAS;AACtC,YAAM,WAAW,SAAS,IAAI;AAC9B,UAAI,OAAO,aAAa,WAAY,MAAK,KAAK,CAAC,MAAM,QAAQ,CAAC;AAAA,IAChE,CAAC;AAED,SAAK,QAAQ,CAAC,CAAC,MAAM,QAAQ,MAAM,OAAO,iBAAiB,MAAM,QAAQ,CAAC;AAE1E,WAAO,MAAM;AACX,WAAK;AAAA,QAAQ,CAAC,CAAC,MAAM,QAAQ,MAC3B,OAAO,oBAAoB,MAAM,QAAQ;AAAA,MAC3C;AAAA,IACF;AAAA,EAGF,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC;AACtB;;;AC9CA,SAAS,OAAO,mBAAmB;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,85 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@atomic-reactor/use-event-handle",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A React hook that subscribes components to @atomic-reactor/event-handle targets (or any EventTarget). Works in React DOM and React Native.",
|
|
5
|
+
"author": "camdagr8",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/ReactiumCore/useEventHandle"
|
|
10
|
+
},
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/ReactiumCore/useEventHandle/issues"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/ReactiumCore/useEventHandle#readme",
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"main": "./dist/index.cjs",
|
|
21
|
+
"module": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"react-native": "./dist/index.js",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"import": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"require": {
|
|
31
|
+
"types": "./dist/index.d.cts",
|
|
32
|
+
"default": "./dist/index.cjs"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"src"
|
|
40
|
+
],
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsup",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"lint": "eslint .",
|
|
46
|
+
"lint:fix": "eslint . --fix",
|
|
47
|
+
"format": "prettier --write .",
|
|
48
|
+
"format:check": "prettier --check .",
|
|
49
|
+
"prepublishOnly": "npm run typecheck && npm run lint && npm test && npm run build"
|
|
50
|
+
},
|
|
51
|
+
"keywords": [
|
|
52
|
+
"react",
|
|
53
|
+
"react-hooks",
|
|
54
|
+
"hook",
|
|
55
|
+
"event",
|
|
56
|
+
"events",
|
|
57
|
+
"eventtarget",
|
|
58
|
+
"event-emitter",
|
|
59
|
+
"react-native"
|
|
60
|
+
],
|
|
61
|
+
"dependencies": {
|
|
62
|
+
"@atomic-reactor/event-handle": "^1.0.2"
|
|
63
|
+
},
|
|
64
|
+
"peerDependencies": {
|
|
65
|
+
"react": ">=16.8.0"
|
|
66
|
+
},
|
|
67
|
+
"devDependencies": {
|
|
68
|
+
"@eslint/js": "^10.0.1",
|
|
69
|
+
"@stylistic/eslint-plugin": "^5.10.0",
|
|
70
|
+
"@testing-library/react": "^16.3.3",
|
|
71
|
+
"@types/react": "^19.3.0",
|
|
72
|
+
"@types/react-dom": "^19.3.0",
|
|
73
|
+
"eslint": "^10.15.0",
|
|
74
|
+
"eslint-config-prettier": "^10.1.8",
|
|
75
|
+
"globals": "^17.14.0",
|
|
76
|
+
"jsdom": "^31.0.1",
|
|
77
|
+
"prettier": "^3.10.1",
|
|
78
|
+
"react": "^19.3.1",
|
|
79
|
+
"react-dom": "^19.3.1",
|
|
80
|
+
"tsup": "^8.5.1",
|
|
81
|
+
"typescript": "^5.9.3",
|
|
82
|
+
"typescript-eslint": "^8.73.0",
|
|
83
|
+
"vitest": "^3.2.7"
|
|
84
|
+
}
|
|
85
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { useEventEffect } from './useEventHandle';
|
|
2
|
+
export type { EventHandlers, EventTargetLike } from './useEventHandle';
|
|
3
|
+
|
|
4
|
+
// Re-exported so one import covers both creating targets and subscribing
|
|
5
|
+
export { Event, EventTarget } from '@atomic-reactor/event-handle';
|
|
6
|
+
export type { AppEvent, Listener } from '@atomic-reactor/event-handle';
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// A hook to subscribe a component to an event target's events. Built for
|
|
2
|
+
// @atomic-reactor/event-handle, where listeners get a copy of the event with
|
|
3
|
+
// its detail spread onto it, e.g. dispatching
|
|
4
|
+
// new Event('date-changed', { value }) reaches listeners as
|
|
5
|
+
// ({ type, value, ... }).
|
|
6
|
+
//
|
|
7
|
+
// Uses only React and ES2019 built-ins (no DOM or Node APIs), so it runs the
|
|
8
|
+
// same in React DOM and React Native.
|
|
9
|
+
import { useEffect } from 'react';
|
|
10
|
+
import type { Listener } from '@atomic-reactor/event-handle';
|
|
11
|
+
|
|
12
|
+
// Anything listeners can be added to and removed from: an event-handle
|
|
13
|
+
// EventTarget, or a DOM EventTarget such as window or an element
|
|
14
|
+
export interface EventTargetLike {
|
|
15
|
+
addEventListener(type: string, listener: Listener): unknown;
|
|
16
|
+
removeEventListener(type: string, listener: Listener): unknown;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Listeners by event type. Entries that aren't functions are skipped, so
|
|
20
|
+
// handlers can be added conditionally ({ change: enabled && onChange }).
|
|
21
|
+
export type EventHandlers = Record<string, Listener | false | null | undefined>;
|
|
22
|
+
|
|
23
|
+
// Adds `handlers` ({ type: listener }) to `target` and removes them on unmount
|
|
24
|
+
// or when `target` or `deps` change. With no deps they're added once per
|
|
25
|
+
// target, so a listener should read current values from a SyncState or a ref
|
|
26
|
+
// rather than from its render's closure.
|
|
27
|
+
export const useEventEffect = (
|
|
28
|
+
target: EventTargetLike | null | undefined,
|
|
29
|
+
handlers: EventHandlers = {},
|
|
30
|
+
deps: unknown[] = [],
|
|
31
|
+
) => {
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
if (!target) return;
|
|
34
|
+
|
|
35
|
+
const subs: Array<[string, Listener]> = [];
|
|
36
|
+
Object.keys(handlers).forEach((type) => {
|
|
37
|
+
const listener = handlers[type];
|
|
38
|
+
if (typeof listener === 'function') subs.push([type, listener]);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
subs.forEach(([type, listener]) => target.addEventListener(type, listener));
|
|
42
|
+
|
|
43
|
+
return () => {
|
|
44
|
+
subs.forEach(([type, listener]) =>
|
|
45
|
+
target.removeEventListener(type, listener),
|
|
46
|
+
);
|
|
47
|
+
};
|
|
48
|
+
// Handlers are read when the effect runs; callers opt in to re-running it
|
|
49
|
+
// through `deps`
|
|
50
|
+
}, [target, ...deps]);
|
|
51
|
+
};
|