@@ -16,11 +16,12 @@ type TouchEvents = 'touchstart' | 'touchend';
16
16
type Events = FocusEvent | MouseEvent | TouchEvent ;
17
17
18
18
interface Props extends HTMLAttributes < HTMLElement > {
19
- onClickAway : ( event : Events ) => void ;
19
+ onClickAway : ( event : Event ) => void ;
20
20
focusEvent ?: FocusEvents ;
21
21
mouseEvent ?: MouseEvents ;
22
22
touchEvent ?: TouchEvents ;
23
23
children : ReactElement < any > ;
24
+ bodyEventsToCapture ?: Array < keyof DocumentEventMap > ;
24
25
}
25
26
26
27
const eventTypeMapping = {
@@ -55,6 +56,7 @@ const ClickAwayListener: FunctionComponent<Props> = ({
55
56
focusEvent = 'focusin' ,
56
57
mouseEvent = 'click' ,
57
58
touchEvent = 'touchend' ,
59
+ bodyEventsToCapture,
58
60
...rest
59
61
} ) => {
60
62
const node = useRef < HTMLElement | null > ( null ) ;
@@ -102,7 +104,7 @@ const ClickAwayListener: FunctionComponent<Props> = ({
102
104
useEffect ( ( ) => {
103
105
const nodeDocument = node . current ?. ownerDocument ?? document ;
104
106
105
- const handleEvents = ( event : Events ) : void => {
107
+ const handleEvents : EventListener = ( event ) => {
106
108
if ( ! mountedRef . current ) return ;
107
109
108
110
if (
@@ -119,13 +121,21 @@ const ClickAwayListener: FunctionComponent<Props> = ({
119
121
nodeDocument . addEventListener ( mouseEvent , handleEvents ) ;
120
122
nodeDocument . addEventListener ( touchEvent , handleEvents ) ;
121
123
nodeDocument . addEventListener ( focusEvent , handleEvents ) ;
124
+ const customListeners = bodyEventsToCapture || [ ] ;
125
+ customListeners . forEach ( ( eventType ) => {
126
+ nodeDocument . addEventListener ( eventType , handleEvents ) ;
127
+ } ) ;
122
128
123
129
return ( ) => {
124
130
nodeDocument . removeEventListener ( mouseEvent , handleEvents ) ;
125
131
nodeDocument . removeEventListener ( touchEvent , handleEvents ) ;
126
132
nodeDocument . removeEventListener ( focusEvent , handleEvents ) ;
133
+
134
+ customListeners . forEach ( ( eventType ) => {
135
+ nodeDocument . removeEventListener ( eventType , handleEvents ) ;
136
+ } ) ;
127
137
} ;
128
- } , [ focusEvent , mouseEvent , onClickAway , touchEvent ] ) ;
138
+ } , [ focusEvent , mouseEvent , onClickAway , touchEvent , bodyEventsToCapture ] ) ;
129
139
130
140
const mappedMouseEvent = eventTypeMapping [ mouseEvent ] ;
131
141
const mappedTouchEvent = eventTypeMapping [ touchEvent ] ;
0 commit comments