RegexHelpIcon and LogPreview's ColumnPicker each reimplemented the same mousedown-outside-ref-closes-popover effect; share it via a small hook. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01TeyhRfMYjMditek6geDRoQ
15 lines
662 B
TypeScript
15 lines
662 B
TypeScript
import { useEffect, type RefObject } from 'react'
|
|
|
|
// Shared by popover-style UI (RegexHelpIcon, LogPreview's ColumnPicker) that closes itself when a
|
|
// mousedown lands outside its container ref, while `active`.
|
|
export function useClickOutside(ref: RefObject<HTMLElement | null>, onOutside: () => void, active: boolean) {
|
|
useEffect(() => {
|
|
if (!active) return
|
|
function onClickOutside(e: MouseEvent) {
|
|
if (ref.current && !ref.current.contains(e.target as Node)) onOutside()
|
|
}
|
|
document.addEventListener('mousedown', onClickOutside)
|
|
return () => document.removeEventListener('mousedown', onClickOutside)
|
|
}, [active, ref, onOutside])
|
|
}
|