Debian Codegraph @

node/rxjs/src/internal/observable/fromEvent.ts

raw
1 import { innerFrom } from '../observable/innerFrom';
2 import { Observable } from '../Observable';
3 import { mergeMap } from '../operators/mergeMap';
4 import { isArrayLike } from '../util/isArrayLike';
5 import { isFunction } from '../util/isFunction';
6 import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
7
8 // These constants are used to create handler registry functions using array mapping below.
9 const nodeEventEmitterMethods = ['addListener', 'removeListener'] as const;
10 const eventTargetMethods = ['addEventListener', 'removeEventListener'] as const;
11 const jqueryMethods = ['on', 'off'] as const;
12
13 export interface NodeStyleEventEmitter {
14 addListener(eventName: string | symbol, handler: NodeEventHandler): this;
15 removeListener(eventName: string | symbol, handler: NodeEventHandler): this;
16 }
17
18 export type NodeEventHandler = (...args: any[]) => void;
19
20 // For APIs that implement `addListener` and `removeListener` methods that may
21 // not use the same arguments or return EventEmitter values
22 // such as React Native
23 export interface NodeCompatibleEventEmitter {
24 addListener(eventName: string, handler: NodeEventHandler): void | {};
25 removeListener(eventName: string, handler: NodeEventHandler): void | {};
26 }
27
28 // Use handler types like those in @types/jquery. See:
29 // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/847731ba1d7fa6db6b911c0e43aa0afe596e7723/types/jquery/misc.d.ts#L6395
30 export interface JQueryStyleEventEmitter<TContext, T> {
31 on(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;
32 off(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;
33 }
34
35 export interface EventListenerObject<E> {
36 handleEvent(evt: E): void;
37 }
38
39 export interface HasEventTargetAddRemove<E> {
40 addEventListener(
41 type: string,
42 listener: ((evt: E) => void) | EventListenerObject<E> | null,
43 options?: boolean | AddEventListenerOptions
44 ): void;
45 removeEventListener(
46 type: string,
47 listener: ((evt: E) => void) | EventListenerObject<E> | null,
48 options?: EventListenerOptions | boolean
49 ): void;
50 }
51
52 export interface EventListenerOptions {
53 capture?: boolean;
54 passive?: boolean;
55 once?: boolean;
56 }
57
58 export interface AddEventListenerOptions extends EventListenerOptions {
59 once?: boolean;
60 passive?: boolean;
61 }
62
63 export function fromEvent<T>(target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>, eventName: string): Observable<T>;
64 export function fromEvent<T, R>(
65 target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,
66 eventName: string,
67 resultSelector: (event: T) => R
68 ): Observable<R>;
69 export function fromEvent<T>(
70 target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,
71 eventName: string,
72 options: EventListenerOptions
73 ): Observable<T>;
74 export function fromEvent<T, R>(
75 target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,
76 eventName: string,
77 options: EventListenerOptions,
78 resultSelector: (event: T) => R
79 ): Observable<R>;
80
81 export function fromEvent(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<unknown>;
82 /** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */
83 export function fromEvent<T>(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<T>;
84 export function fromEvent<R>(
85 target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>,
86 eventName: string,
87 resultSelector: (...args: any[]) => R
88 ): Observable<R>;
89
90 export function fromEvent(
91 target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,
92 eventName: string
93 ): Observable<unknown>;
94 /** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */
95 export function fromEvent<T>(target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>, eventName: string): Observable<T>;
96 export function fromEvent<R>(
97 target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,
98 eventName: string,
99 resultSelector: (...args: any[]) => R
100 ): Observable<R>;
101
102 export function fromEvent<T>(
103 target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,
104 eventName: string
105 ): Observable<T>;
106 export function fromEvent<T, R>(
107 target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,
108 eventName: string,
109 resultSelector: (value: T, ...args: any[]) => R
110 ): Observable<R>;
111
112 /**
113 * Creates an Observable that emits events of a specific type coming from the
114 * given event target.
115 *
116 * <span class="informal">Creates an Observable from DOM events, or Node.js
117 * EventEmitter events or others.</span>
118 *
119 * ![](fromEvent.png)
120 *
121 * `fromEvent` accepts as a first argument event target, which is an object with methods
122 * for registering event handler functions. As a second argument it takes string that indicates
123 * type of event we want to listen for. `fromEvent` supports selected types of event targets,
124 * which are described in detail below. If your event target does not match any of the ones listed,
125 * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
126 * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
127 * handler functions have different names, but they all accept a string describing event type
128 * and function itself, which will be called whenever said event happens.
129 *
130 * Every time resulting Observable is subscribed, event handler function will be registered
131 * to event target on given event type. When that event fires, value
132 * passed as a first argument to registered function will be emitted by output Observable.
133 * When Observable is unsubscribed, function will be unregistered from event target.
134 *
135 * Note that if event target calls registered function with more than one argument, second
136 * and following arguments will not appear in resulting stream. In order to get access to them,
137 * you can pass to `fromEvent` optional project function, which will be called with all arguments
138 * passed to event handler. Output Observable will then emit value returned by project function,
139 * instead of the usual value.
140 *
141 * Remember that event targets listed below are checked via duck typing. It means that
142 * no matter what kind of object you have and no matter what environment you work in,
143 * you can safely use `fromEvent` on that object if it exposes described methods (provided
144 * of course they behave as was described above). So for example if Node.js library exposes
145 * event target which has the same method names as DOM EventTarget, `fromEvent` is still
146 * a good choice.
147 *
148 * If the API you use is more callback then event handler oriented (subscribed
149 * callback function fires only once and thus there is no need to manually
150 * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
151 * instead.
152 *
153 * `fromEvent` supports following types of event targets:
154 *
155 * **DOM EventTarget**
156 *
157 * This is an object with `addEventListener` and `removeEventListener` methods.
158 *
159 * In the browser, `addEventListener` accepts - apart from event type string and event
160 * handler function arguments - optional third parameter, which is either an object or boolean,
161 * both used for additional configuration how and when passed function will be called. When
162 * `fromEvent` is used with event target of that type, you can provide this values
163 * as third parameter as well.
164 *
165 * **Node.js EventEmitter**
166 *
167 * An object with `addListener` and `removeListener` methods.
168 *
169 * **JQuery-style event target**
170 *
171 * An object with `on` and `off` methods
172 *
173 * **DOM NodeList**
174 *
175 * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
176 *
177 * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
178 * it contains and install event handler function in every of them. When returned Observable
179 * is unsubscribed, function will be removed from all Nodes.
180 *
181 * **DOM HtmlCollection**
182 *
183 * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
184 * installed and removed in each of elements.
185 *
186 *
187 * ## Examples
188 *
189 * Emit clicks happening on the DOM document
190 *
191 * ```ts
192 * import { fromEvent } from 'rxjs';
193 *
194 * const clicks = fromEvent(document, 'click');
195 * clicks.subscribe(x => console.log(x));
196 *
197 * // Results in:
198 * // MouseEvent object logged to console every time a click
199 * // occurs on the document.
200 * ```
201 *
202 * Use `addEventListener` with capture option
203 *
204 * ```ts
205 * import { fromEvent } from 'rxjs';
206 *
207 * const div = document.createElement('div');
208 * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';
209 * document.body.appendChild(div);
210 *
211 * // note optional configuration parameter which will be passed to addEventListener
212 * const clicksInDocument = fromEvent(document, 'click', { capture: true });
213 * const clicksInDiv = fromEvent(div, 'click');
214 *
215 * clicksInDocument.subscribe(() => console.log('document'));
216 * clicksInDiv.subscribe(() => console.log('div'));
217 *
218 * // By default events bubble UP in DOM tree, so normally
219 * // when we would click on div in document
220 * // "div" would be logged first and then "document".
221 * // Since we specified optional `capture` option, document
222 * // will catch event when it goes DOWN DOM tree, so console
223 * // will log "document" and then "div".
224 * ```
225 *
226 * @see {@link bindCallback}
227 * @see {@link bindNodeCallback}
228 * @see {@link fromEventPattern}
229 *
230 * @param target The DOM EventTarget, Node.js EventEmitter, JQuery-like event target,
231 * NodeList or HTMLCollection to attach the event handler to.
232 * @param eventName The event name of interest, being emitted by the `target`.
233 * @param options Options to pass through to the underlying `addListener`,
234 * `addEventListener` or `on` functions.
235 * @param resultSelector A mapping function used to transform events. It takes the
236 * arguments from the event handler and should return a single value.
237 * @return An Observable emitting events registered through `target`'s
238 * listener handlers.
239 */
240 export function fromEvent<T>(
241 target: any,
242 eventName: string,
243 options?: EventListenerOptions | ((...args: any[]) => T),
244 resultSelector?: (...args: any[]) => T
245 ): Observable<T> {
246 if (isFunction(options)) {
247 resultSelector = options;
248 options = undefined;
249 }
250 if (resultSelector) {
251 return fromEvent<T>(target, eventName, options as EventListenerOptions).pipe(mapOneOrManyArgs(resultSelector));
252 }
253
254 // Figure out our add and remove methods. In order to do this,
255 // we are going to analyze the target in a preferred order, if
256 // the target matches a given signature, we take the two "add" and "remove"
257 // method names and apply them to a map to create opposite versions of the
258 // same function. This is because they all operate in duplicate pairs,
259 // `addListener(name, handler)`, `removeListener(name, handler)`, for example.
260 // The call only differs by method name, as to whether or not you're adding or removing.
261 const [add, remove] =
262 // If it is an EventTarget, we need to use a slightly different method than the other two patterns.
263 isEventTarget(target)
264 ? eventTargetMethods.map((methodName) => (handler: any) => target[methodName](eventName, handler, options as EventListenerOptions))
265 : // In all other cases, the call pattern is identical with the exception of the method names.
266 isNodeStyleEventEmitter(target)
267 ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))
268 : isJQueryStyleEventEmitter(target)
269 ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))
270 : [];
271
272 // If add is falsy, it's because we didn't match a pattern above.
273 // Check to see if it is an ArrayLike, because if it is, we want to
274 // try to apply fromEvent to all of it's items. We do this check last,
275 // because there are may be some types that are both ArrayLike *and* implement
276 // event registry points, and we'd rather delegate to that when possible.
277 if (!add) {
278 if (isArrayLike(target)) {
279 return mergeMap((subTarget: any) => fromEvent(subTarget, eventName, options as EventListenerOptions))(
280 innerFrom(target)
281 ) as Observable<T>;
282 }
283 }
284
285 // If add is falsy and we made it here, it's because we didn't
286 // match any valid target objects above.
287 if (!add) {
288 throw new TypeError('Invalid event target');
289 }
290
291 return new Observable<T>((subscriber) => {
292 // The handler we are going to register. Forwards the event object, by itself, or
293 // an array of arguments to the event handler, if there is more than one argument,
294 // to the consumer.
295 const handler = (...args: any[]) => subscriber.next(1 < args.length ? args : args[0]);
296 // Do the work of adding the handler to the target.
297 add(handler);
298 // When we finalize, we want to remove the handler and free up memory.
299 return () => remove!(handler);
300 });
301 }
302
303 /**
304 * Used to create `add` and `remove` functions to register and unregister event handlers
305 * from a target in the most common handler pattern, where there are only two arguments.
306 * (e.g. `on(name, fn)`, `off(name, fn)`, `addListener(name, fn)`, or `removeListener(name, fn)`)
307 * @param target The target we're calling methods on
308 * @param eventName The event name for the event we're creating register or unregister functions for
309 */
310 function toCommonHandlerRegistry(target: any, eventName: string) {
311 return (methodName: string) => (handler: any) => target[methodName](eventName, handler);
312 }
313
314 /**
315 * Checks to see if the target implements the required node-style EventEmitter methods
316 * for adding and removing event handlers.
317 * @param target the object to check
318 */
319 function isNodeStyleEventEmitter(target: any): target is NodeStyleEventEmitter {
320 return isFunction(target.addListener) && isFunction(target.removeListener);
321 }
322
323 /**
324 * Checks to see if the target implements the required jQuery-style EventEmitter methods
325 * for adding and removing event handlers.
326 * @param target the object to check
327 */
328 function isJQueryStyleEventEmitter(target: any): target is JQueryStyleEventEmitter<any, any> {
329 return isFunction(target.on) && isFunction(target.off);
330 }
331
332 /**
333 * Checks to see if the target implements the required EventTarget methods
334 * for adding and removing event handlers.
335 * @param target the object to check
336 */
337 function isEventTarget(target: any): target is HasEventTargetAddRemove<any> {
338 return isFunction(target.addEventListener) && isFunction(target.removeEventListener);
339 }