-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
use-outside-click.ts
77 lines (65 loc) · 2.27 KB
/
use-outside-click.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
import { getOwnerDocument } from "@chakra-ui/utils"
import { RefObject, useEffect, useRef } from "react"
import { useCallbackRef } from "./use-callback-ref"
interface UseOutsideClickOptions {
ref: RefObject<HTMLElement>
handler: (e: Event) => void
}
/**
* Example, used in components like Dialogs and Popovers so they can close
* when a user clicks outside them.
*/
export function useOutsideClick(props: UseOutsideClickOptions) {
const { ref, handler } = props
const savedHandler = useCallbackRef(handler)
const stateRef = useRef({
isPointerDown: false,
ignoreEmulatedMouseEvents: false,
})
const state = stateRef.current
useEffect(() => {
const onPointerDown: any = (e: PointerEvent) => {
if (isValidEvent(e, ref)) {
state.isPointerDown = true
}
}
const onMouseUp: any = (event: MouseEvent) => {
if (state.ignoreEmulatedMouseEvents) {
state.ignoreEmulatedMouseEvents = false
return
}
if (state.isPointerDown && handler && isValidEvent(event, ref)) {
state.isPointerDown = false
savedHandler(event)
}
}
const onTouchEnd = (event: TouchEvent) => {
state.ignoreEmulatedMouseEvents = true
if (handler && state.isPointerDown && isValidEvent(event, ref)) {
state.isPointerDown = false
savedHandler(event)
}
}
const doc = getOwnerDocument(ref.current)
doc.addEventListener("mousedown", onPointerDown, true)
doc.addEventListener("mouseup", onMouseUp, true)
doc.addEventListener("touchstart", onPointerDown, true)
doc.addEventListener("touchend", onTouchEnd, true)
return () => {
doc.removeEventListener("mousedown", onPointerDown, true)
doc.removeEventListener("mouseup", onMouseUp, true)
doc.removeEventListener("touchstart", onPointerDown, true)
doc.removeEventListener("touchend", onTouchEnd, true)
}
}, [handler, ref, savedHandler, state])
}
function isValidEvent(event: any, ref: React.RefObject<HTMLElement>) {
const target = event.target as HTMLElement
if (event.button > 0) return false
// if the event target is no longer in the document
if (target) {
const doc = getOwnerDocument(target)
if (!doc.body.contains(target)) return false
}
return !ref.current?.contains(target)
}