@@ -32,7 +32,6 @@ import React, {
3232 RefObject ,
3333 Ref ,
3434 SyntheticEvent ,
35- useRef ,
3635} from 'react'
3736import { Popper } from 'react-popper'
3837import { Box } from '../Layout'
@@ -236,7 +235,9 @@ function usePopoverToggle(
236235 triggerElement : HTMLElement | null
237236) : [ boolean , ( value : boolean ) => void ] {
238237 const [ uncontrolledIsOpen , uncontrolledSetOpen ] = useState ( controlledIsOpen )
239- const mouseDownTarget = useRef < EventTarget | null > ( )
238+ const [ mouseDownTarget , setMouseDownTarget ] = useState < EventTarget | null > (
239+ null
240+ )
240241 const isControlled = useControlWarn ( {
241242 controllingProps : [ 'setOpen' ] ,
242243 isControlledCheck : ( ) => controlledSetOpen !== undefined ,
@@ -255,9 +256,9 @@ function usePopoverToggle(
255256 // outside the popover as this is preferable to a bug where another
256257 // component triggers a scroll animation resulting in an
257258 // unintentional drag, which closes the popover
258- if ( portalElement && mouseDownTarget . current ) {
259+ if ( portalElement && mouseDownTarget ) {
259260 const relationship = portalElement . compareDocumentPosition (
260- mouseDownTarget . current as Node
261+ mouseDownTarget as Node
261262 )
262263 if (
263264 relationship === Node . DOCUMENT_POSITION_FOLLOWING ||
@@ -303,7 +304,7 @@ function usePopoverToggle(
303304 }
304305
305306 function handleMouseDown ( event : MouseEvent ) {
306- mouseDownTarget . current = event . target
307+ setMouseDownTarget ( event . target )
307308 checkCloseAndStopEvent ( event )
308309 }
309310
@@ -312,20 +313,16 @@ function usePopoverToggle(
312313 }
313314
314315 function handleMouseUp ( ) {
315- window . requestAnimationFrame ( ( ) => {
316- mouseDownTarget . current = null
317- document . removeEventListener ( 'click' , handleClickOutside , true )
318- document . removeEventListener ( 'mouseup' , handleMouseUp , true )
319- } )
316+ setMouseDownTarget ( null )
320317 }
321318
322319 if ( isOpen ) {
323320 document . addEventListener ( 'mousedown' , handleMouseDown , true )
324- if ( ! mouseDownTarget . current ) {
325- document . addEventListener ( 'click' , handleClickOutside , true )
326- }
327- } else if ( mouseDownTarget . current ) {
328321 document . addEventListener ( 'click' , handleClickOutside , true )
322+ } else if ( mouseDownTarget ) {
323+ // popover was closed via mousedown, but still need to cancel next click
324+ document . addEventListener ( 'click' , handleClickOutside , true )
325+ // and then cleanup mouseDownTarget
329326 document . addEventListener ( 'mouseup' , handleMouseUp , true )
330327 }
331328
@@ -342,6 +339,7 @@ function usePopoverToggle(
342339 triggerElement ,
343340 portalElement ,
344341 triggerToggle ,
342+ mouseDownTarget ,
345343 ] )
346344
347345 return [ isOpen , setOpen ]
0 commit comments