This repository has been archived by the owner on Sep 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
on-dom-event.ts
79 lines (71 loc) · 2.17 KB
/
on-dom-event.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import {
eventReceiver,
EventReceiver,
OnEvent,
OnEvent__symbol,
onEventBy,
} from '@proc7ts/fun-events';
import { noop } from '@proc7ts/primitives';
import type { Supply } from '@proc7ts/supply';
/**
* DOM event listener.
*
* DOM events are never recurrent.
*
* May be constructed using {@link onDomEventBy} function.
*
* @typeParam TEvent - Supported DOM event type.
*/
export type DomEventListener<TEvent extends Event> = EventReceiver<[TEvent]>;
/**
* Signature of {@link EventSender} implementation able to register DOM event listeners.
*
* @typeParam TEvent - Supported DOM event type.
*/
export interface OnDomEvent<TEvent extends Event> extends OnEvent<[TEvent]> {
/**
* Starts sending DOM events to the given `listener`.
*
* @param listener - Target listener of DOM events.
* @param opts - DOM event listener options to pass to `EventTarget.addEventListener()`.
*
* @returns A supply of DOM events from this sender to the given `listener`.
*/
(listener: DomEventListener<TEvent>, opts?: AddEventListenerOptions | boolean): Supply;
}
/**
* @internal
* @hidden
*/
const OnDomEvent$sample = /*#__PURE__*/ onEventBy<any>(noop);
/**
* Converts a plain DOM event listener registration function to {@link OnDomEvent} sender.
*
* @typeParam TEvent - Supported DOM event type.
* @param register - A generic DOM event listener registration function.
*
* @returns An {@link OnDomEvent} sender registering event listeners with the given `register` function.
*/
export function onDomEventBy<TEvent extends Event>(
register: (
this: void,
listener: EventReceiver.Generic<[TEvent]>,
opts?: AddEventListenerOptions | boolean,
) => void,
): OnDomEvent<TEvent> {
const onDomEvent = ((
listener: DomEventListener<TEvent>,
opts?: AddEventListenerOptions | boolean,
): Supply => {
const receiver = eventReceiver(listener);
const { supply } = receiver;
if (!supply.isOff) {
register(receiver, opts);
}
return supply;
}) as OnDomEvent<TEvent>;
onDomEvent[OnEvent__symbol] = OnDomEvent$sample[OnEvent__symbol];
onDomEvent.do = OnDomEvent$sample.do;
onDomEvent.then = OnDomEvent$sample.then;
return onDomEvent;
}