diff options
| author | Armand Philippot <git@armandphilippot.com> | 2022-05-18 14:27:11 +0200 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2022-05-18 14:27:11 +0200 |
| commit | b214baab3e17d92f784b4f782863deafc5558ee4 (patch) | |
| tree | cdc20c7e77ba6926285917eead8bb088bdc843f8 /src/utils | |
| parent | 54883bb5c36cf21462a421605a709fdd6f04b150 (diff) | |
chore: close toolbar modals on click/focus outside
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/hooks/use-click-outside.tsx | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/utils/hooks/use-click-outside.tsx b/src/utils/hooks/use-click-outside.tsx new file mode 100644 index 0000000..066c1c2 --- /dev/null +++ b/src/utils/hooks/use-click-outside.tsx @@ -0,0 +1,43 @@ +import { RefObject, useCallback, useEffect } from 'react'; + +/** + * Listen for click/focus outside an element and execute the given callback. + * + * @param el - A React reference to an element. + * @param callback - A callback function to execute on click outside. + */ +const useClickOutside = (el: RefObject<HTMLElement>, callback: () => void) => { + /** + * Check if an event target is outside an element. + * + * @param {RefObject<HTMLElement>} ref - A React reference object. + * @param {EventTarget} target - An event target. + * @returns {boolean} True if the event target is outside the ref object. + */ + const isTargetOutside = ( + ref: RefObject<HTMLElement>, + target: EventTarget + ): boolean => { + if (!ref.current) return false; + return !ref.current.contains(target as Node); + }; + + const handleEvent = useCallback( + (e: MouseEvent | FocusEvent) => { + if (e.target && isTargetOutside(el, e.target)) callback(); + }, + [el, callback] + ); + + useEffect(() => { + document.addEventListener('mousedown', handleEvent); + document.addEventListener('focusin', handleEvent); + + return () => { + document.removeEventListener('mousedown', handleEvent); + document.removeEventListener('focusin', handleEvent); + }; + }, [handleEvent]); +}; + +export default useClickOutside; |
