-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuseEvent.ts
73 lines (63 loc) · 2.05 KB
/
useEvent.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
import * as React from 'react'
function useEvent<
T extends Window = Window,
K extends keyof WindowEventMap = keyof WindowEventMap
>(
target: Window | null,
type: K,
listener: WindowEventListener<K>,
cleanup?: (...args: any[]) => void
): void
function useEvent<
T extends Document = Document,
K extends keyof DocumentEventMap = keyof DocumentEventMap
>(
target: Document | null,
type: K,
listener: DocumentEventListener<K>,
cleanup?: (...args: any[]) => void
): void
function useEvent<
T extends HTMLElement = HTMLElement,
K extends keyof HTMLElementEventMap = keyof HTMLElementEventMap
>(
target: React.RefObject<T> | T | null,
type: K,
listener: ElementEventListener<K>,
cleanup?: (...args: any[]) => void
): void
function useEvent(target: any, type: any, listener: any, cleanup: any): void {
const storedListener = React.useRef(listener)
const storedCleanup = React.useRef(cleanup)
React.useEffect(() => {
storedListener.current = listener
storedCleanup.current = cleanup
})
React.useEffect(() => {
const targetEl = target && 'current' in target ? target.current : target
if (!targetEl) return
let didUnsubscribe = 0
function listener(this: any, ...args: any[]) {
if (didUnsubscribe) return
storedListener.current.apply(this, args)
}
targetEl.addEventListener(type, listener)
const cleanup = storedCleanup.current
return () => {
didUnsubscribe = 1
targetEl.removeEventListener(type, listener)
cleanup && cleanup()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [target, type])
}
export type ElementEventListener<
K extends keyof HTMLElementEventMap = keyof HTMLElementEventMap
> = (this: HTMLElement, ev: HTMLElementEventMap[K]) => any
export type DocumentEventListener<
K extends keyof DocumentEventMap = keyof DocumentEventMap
> = (this: Document, ev: DocumentEventMap[K]) => any
export type WindowEventListener<
K extends keyof WindowEventMap = keyof WindowEventMap
> = (this: Document, ev: WindowEventMap[K]) => any
export default useEvent