refactor(components/layout): replace useOutSide hook with new component
This commit is contained in:
parent
636ebe8099
commit
f6bd3e8ab7
@ -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>
|
||||
)
|
||||
}
|
1
src/components/layout/OutSideEventHandler/index.ts
Normal file
1
src/components/layout/OutSideEventHandler/index.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from './OutSideEventHandler'
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue
Block a user