-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.ts
65 lines (53 loc) · 1.54 KB
/
index.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
import { useEffect } from 'react'
import arePassiveEventsSupported from 'are-passive-events-supported'
import useLatest from 'use-latest'
const MOUSEDOWN = 'mousedown'
const TOUCHSTART = 'touchstart'
type HandledEvents = [typeof MOUSEDOWN, typeof TOUCHSTART]
type HandledEventsType = HandledEvents[number]
type PossibleEvent = {
[Type in HandledEventsType]: HTMLElementEventMap[Type]
}[HandledEventsType]
type Handler = (event: PossibleEvent) => void
const events: HandledEvents = [MOUSEDOWN, TOUCHSTART]
const getAddOptions = (
event: HandledEventsType,
): AddEventListenerOptions | undefined => {
if (event === TOUCHSTART && arePassiveEventsSupported()) {
return { passive: true }
}
}
const currentDocument = typeof document !== 'undefined' ? document : undefined
export default function useOnClickOutside(
ref: React.RefObject<HTMLElement>,
handler: Handler | null,
{ document = currentDocument } = {},
) {
if (typeof document === 'undefined') {
return
}
const handlerRef = useLatest(handler)
useEffect(() => {
if (!handler) {
return
}
const listener = (event: PossibleEvent) => {
if (
!ref.current ||
!handlerRef.current ||
ref.current.contains(event.target as Node)
) {
return
}
handlerRef.current(event)
}
events.forEach(event => {
document.addEventListener(event, listener, getAddOptions(event))
})
return () => {
events.forEach(event => {
document.removeEventListener(event, listener)
})
}
}, [!handler])
}