diff --git a/src/common/__mocks__/useOutsideEvent.ts b/src/common/__mocks__/useOutsideEvent.ts new file mode 100644 index 000000000..36129d344 --- /dev/null +++ b/src/common/__mocks__/useOutsideEvent.ts @@ -0,0 +1,5 @@ +export default jest.fn((_type: string, _ref?: React.RefObject, callback?: () => void): void => { + if (callback) { + callback(); + } +}); diff --git a/src/common/useOutsideEvent.ts b/src/common/useOutsideEvent.ts index 0b60fc656..e033cde1d 100644 --- a/src/common/useOutsideEvent.ts +++ b/src/common/useOutsideEvent.ts @@ -1,7 +1,7 @@ import * as React from 'react'; // Utilizes the useEffect hook to handle when an event is fired on the document, but outside of the specified element -export default function useOutsideEvent(type: string, ref: React.RefObject, callback: () => void): void { +export default function useOutsideEvent(type: string, ref?: React.RefObject, callback?: () => void): void { React.useEffect(() => { function handleEvent(event: Event): void { const containsEventTarget = !!ref?.current?.contains(event.target as Node); diff --git a/src/components/Popups/PopupHighlight.tsx b/src/components/Popups/PopupHighlight.tsx index 26160a0c7..8f1a7d2fb 100644 --- a/src/components/Popups/PopupHighlight.tsx +++ b/src/components/Popups/PopupHighlight.tsx @@ -4,11 +4,13 @@ import noop from 'lodash/noop'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; import PopupBase from './PopupBase'; +import useOutsideEvent from '../../common/useOutsideEvent'; import { Options } from './Popper'; import { Shape } from '../../@types/model'; import './PopupHighlight.scss'; export type Props = { + onCancel?: () => void; onClick?: (event: React.MouseEvent) => void; shape: Shape; }; @@ -43,7 +45,7 @@ const options: Partial = { placement: 'bottom', }; -export default function PopupHighlight({ onClick = noop, shape }: Props): JSX.Element { +export default function PopupHighlight({ onCancel = noop, onClick = noop, shape }: Props): JSX.Element { const buttonRef = React.useRef(null); const { height, width, x, y } = shape; @@ -62,6 +64,8 @@ export default function PopupHighlight({ onClick = noop, shape }: Props): JSX.El onClick(event); }; + useOutsideEvent('mousedown', buttonRef, onCancel); + return (