refactor(components/layout): replace useOutSide hook with new component

This commit is contained in:
Walid 2023-05-04 14:02:15 +01:00
parent 636ebe8099
commit f6bd3e8ab7
Signed by: Walidoux
GPG Key ID: CCF21881FE8BEBAF
3 changed files with 36 additions and 41 deletions

View File

@ -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<OutSideEventHandlerProps> = (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 (
<div {...props} ref={ref}>
{props.children}
</div>
)
}

View File

@ -0,0 +1 @@
export * from './OutSideEventHandler'

View File

@ -1,41 +0,0 @@
import type { RefObject } from 'react'
import { useEffect, useRef } from 'react'
export const useOutSideClickEventHandler = (callback: () => void): RefObject<HTMLDivElement> => {
const wrapper = useRef<HTMLDivElement>(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
}