-
Notifications
You must be signed in to change notification settings - Fork 140
/
Dropdown.tsx
102 lines (90 loc) · 2.63 KB
/
Dropdown.tsx
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import React, {
FC,
MutableRefObject,
ReactNode,
createContext,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { createPortal } from 'react-dom'
import { Rect } from './dropdownHelper'
import { usePortal } from '../../hooks/usePortal'
type Props = {
children: ReactNode
}
type DropdownContextType = {
active: boolean
triggerRect: Rect
triggerElementRef: MutableRefObject<HTMLDivElement | null>
onClickTrigger: (rect: Rect) => void
onClickCloser: () => void
DropdownContentRoot: FC<{ children: ReactNode }>
}
const initialRect = { top: 0, right: 0, bottom: 0, left: 0 }
export const DropdownContext = createContext<DropdownContextType>({
active: false,
triggerRect: initialRect,
triggerElementRef: React.createRef(),
onClickTrigger: () => {
/* noop */
},
onClickCloser: () => {
/* noop */
},
DropdownContentRoot: () => null,
})
export const Dropdown: FC<Props> = ({ children }) => {
const [active, setActive] = useState(false)
const [triggerRect, setTriggerRect] = useState<Rect>(initialRect)
const { portalRoot, isChildPortal, PortalParentProvider } = usePortal()
const triggerElementRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const onClickBody = (e: any) => {
// ignore events from events within DropdownTrigger and DropdownContent
if (e.target === triggerElementRef.current || isChildPortal(e.target)) {
return
}
setActive(false)
}
document.body.appendChild(portalRoot)
document.body.addEventListener('click', onClickBody, false)
return () => {
document.body.removeChild(portalRoot)
document.body.removeEventListener('click', onClickBody, false)
}
}, [isChildPortal, portalRoot])
// This is the root container of a dropdown content located in outside the DOM tree
const DropdownContentRoot = useMemo<FC<{ children: ReactNode }>>(
() => (props) => {
if (!active) return null
return createPortal(props.children, portalRoot)
},
[active, portalRoot],
)
// set the displayName explicit for DevTools
DropdownContentRoot.displayName = 'DropdownContentRoot'
return (
<PortalParentProvider>
<DropdownContext.Provider
value={{
active,
triggerRect,
triggerElementRef,
onClickTrigger: (rect) => {
const newActive = !active
setActive(newActive)
if (newActive) setTriggerRect(rect)
},
onClickCloser: () => {
setActive(false)
},
DropdownContentRoot,
}}
>
{children}
</DropdownContext.Provider>
</PortalParentProvider>
)
}