File size: 1,272 Bytes
1e92f2d |
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 |
import { useCallback, useEffect } from 'react';
import * as React from 'react';
/**
* Hook that executes `callback` is the 'Escape' key is pressed
* or if the user clicks outside of `ref`.
* @param ref Ref to an HTML element
* @param callback Function to be executed
*/
export default function useOutsideClickCallback(
ref: React.MutableRefObject< null | HTMLElement >,
callback: () => void
): void {
const handleEscape = useCallback(
( event: KeyboardEvent ) => {
if ( event.key === 'Escape' ) {
callback();
}
},
[ callback ]
);
const handleClick = useCallback(
( { target }: MouseEvent ) => {
if ( ref.current && ! ref.current.contains( target as Node ) ) {
callback();
}
},
[ ref, callback ]
);
useEffect( () => {
// HACK: adding these event listeners synchronously causes some sort of
// race condition on the Plugins page, but delaying them via setTimeout
// seems to take care of it.
setTimeout( () => {
document.addEventListener( 'keydown', handleEscape );
document.addEventListener( 'click', handleClick );
}, 0 );
return () => {
document.removeEventListener( 'keydown', handleEscape );
document.removeEventListener( 'click', handleClick );
};
}, [ handleClick, handleEscape ] );
}
|