diff --git a/src/components/layout/OutSideEventHandler/OutSideEventHandler.tsx b/src/components/layout/OutSideEventHandler/OutSideEventHandler.tsx new file mode 100644 index 0000000..ed132cb --- /dev/null +++ b/src/components/layout/OutSideEventHandler/OutSideEventHandler.tsx @@ -0,0 +1,35 @@ +import type { Component, ComponentProps } from 'solid-js' +import { onCleanup, onMount } from 'solid-js' + +interface OutSideEventHandlerProps extends ComponentProps<'div'> { + onOutsideClick: () => void +} + +export const OutSideEventHandler: Component = (props) => { + let ref: HTMLDivElement | undefined + + const handleClickOutside = (event: MouseEvent | KeyboardEvent): void => { + const currentEvent = event as KeyboardEvent + + if (ref == null) return + if (ref.contains(event.target as Node) || currentEvent.key !== 'Escape') return + + return props.onOutsideClick() + } + + onMount(() => { + window.addEventListener('keydown', handleClickOutside) + return window.addEventListener('click', handleClickOutside) + }) + + onCleanup(() => { + window.removeEventListener('keydown', handleClickOutside) + return window.removeEventListener('click', handleClickOutside) + }) + + return ( +
+ {props.children} +
+ ) +} diff --git a/src/components/layout/OutSideEventHandler/index.ts b/src/components/layout/OutSideEventHandler/index.ts new file mode 100644 index 0000000..8ad90a9 --- /dev/null +++ b/src/components/layout/OutSideEventHandler/index.ts @@ -0,0 +1 @@ +export * from './OutSideEventHandler' diff --git a/src/hooks/useOutsideClickEventHandler.ts b/src/hooks/useOutsideClickEventHandler.ts deleted file mode 100644 index 59b1c43..0000000 --- a/src/hooks/useOutsideClickEventHandler.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { RefObject } from 'react' -import { useEffect, useRef } from 'react' - -export const useOutSideClickEventHandler = (callback: () => void): RefObject => { - const wrapper = useRef(null) - - useEffect(() => { - const handleClickOutside = (event: KeyboardEvent | MouseEvent): void => { - const currentEvent = event as KeyboardEvent - - if ( - wrapper.current == null || - Boolean(wrapper.current.contains(currentEvent.target as Node)) || - currentEvent.key !== 'Escape' - ) - return - - return callback() - } - - window.addEventListener('click', (event) => { - return handleClickOutside(event) - }) - - window.addEventListener('keydown', (event) => { - return handleClickOutside(event) - }) - - return () => { - window.removeEventListener('click', (event) => { - return handleClickOutside(event) - }) - - window.removeEventListener('keydown', (event) => { - return handleClickOutside(event) - }) - } - }, []) - - return wrapper -}