import { onBeforeUnmount, onMounted, type Ref } from 'vue' export interface UseContextMenuClickOutsideOptions { selector?: string ignore?: Ref[] } const DEFAULT_SELECTOR = '.ivyforms-context-menu, .ivyforms-popper-context-menu' function resolveElement(value: unknown): HTMLElement | null { if (!value) return null if (value instanceof HTMLElement) return value if (typeof value === 'object' && value !== null && '$el' in value) { const el = (value as { $el: unknown }).$el return el instanceof HTMLElement ? el : null } return null } export function useContextMenuClickOutside( close: () => void, options: UseContextMenuClickOutsideOptions = {}, ) { const { selector = DEFAULT_SELECTOR, ignore = [] } = options const handler = (event: MouseEvent) => { const target = event.target if (!(target instanceof Node)) return const menus = document.querySelectorAll(selector) for (const menu of menus) { if (menu.contains(target)) return } for (const ref of ignore) { const el = resolveElement(ref.value) if (el?.contains(target)) return } close() } onMounted(() => { document.addEventListener('mousedown', handler) }) onBeforeUnmount(() => { document.removeEventListener('mousedown', handler) }) }