UNPKG

2.68 kBPlain TextView Raw
1/*
2 * Copyright 2020 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13import {useCallback, useEffect, useRef} from 'react';
14
15interface GlobalListeners {
16 addGlobalListener<K extends keyof DocumentEventMap>(el: EventTarget, type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void,
17 addGlobalListener(el: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void,
18 removeGlobalListener<K extends keyof DocumentEventMap>(el: EventTarget, type: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | EventListenerOptions): void,
19 removeGlobalListener(el: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void,
20 removeAllGlobalListeners(): void
21}
22
23export function useGlobalListeners(): GlobalListeners {
24 let globalListeners = useRef(new Map());
25 let addGlobalListener = useCallback((eventTarget, type, listener, options) => {
26 // Make sure we remove the listener after it is called with the `once` option.
27 let fn = options?.once ? (...args) => {
28 globalListeners.current.delete(listener);
29 listener(...args);
30 } : listener;
31 globalListeners.current.set(listener, {type, eventTarget, fn, options});
32 eventTarget.addEventListener(type, listener, options);
33 }, []);
34 let removeGlobalListener = useCallback((eventTarget, type, listener, options) => {
35 let fn = globalListeners.current.get(listener)?.fn || listener;
36 eventTarget.removeEventListener(type, fn, options);
37 globalListeners.current.delete(listener);
38 }, []);
39 let removeAllGlobalListeners = useCallback(() => {
40 globalListeners.current.forEach((value, key) => {
41 removeGlobalListener(value.eventTarget, value.type, key, value.options);
42 });
43 }, [removeGlobalListener]);
44
45 // eslint-disable-next-line arrow-body-style
46 useEffect(() => {
47 return removeAllGlobalListeners;
48 }, [removeAllGlobalListeners]);
49
50 return {addGlobalListener, removeGlobalListener, removeAllGlobalListeners};
51}
52
\No newline at end of file