import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { cx } from '../internal/cx.js' import { Portal } from '../internal/Portal.jsx' const GAP = 6 const MARGIN = 8 /** * A small floating panel under a button (2026-11-21): a colour picker, an "Add…" menu. Drawn over * everything (portal, fixed), like the Dropdown's list: below its button, above when there's no * room, and always kept inside the window, so it never makes a page or a section scroll sideways. * Closes on a click outside (the button excluded) and on Escape. * * const btn = useRef(null) * * setOpen(false)} role="menu">… */ export function Popover({ open, anchor, onClose, className, style, children, role = 'dialog', ...rest }) { const panel = useRef(null) const [pos, setPos] = useState(null) const place = useCallback(() => { const b = anchor?.current?.getBoundingClientRect() const p = panel.current?.getBoundingClientRect() if (!b || !p) return const below = window.innerHeight - b.bottom - GAP - MARGIN const above = b.top - GAP - MARGIN const up = p.height > below && above > below const left = Math.min(Math.max(MARGIN, b.left), Math.max(MARGIN, window.innerWidth - MARGIN - p.width)) const top = up ? Math.max(MARGIN, b.top - GAP - p.height) : b.bottom + GAP setPos({ left, top, maxHeight: Math.max(160, up ? above : below) }) }, [anchor]) useLayoutEffect(() => { if (open) place(); else setPos(null) }, [open, place]) useEffect(() => { if (!open) return undefined const away = e => { if (panel.current?.contains(e.target) || anchor?.current?.contains(e.target)) return onClose?.() } const esc = e => { if (e.key === 'Escape') { e.stopPropagation(); onClose?.() } } const onScroll = e => { if (!panel.current?.contains(e.target)) place() } document.addEventListener('pointerdown', away) window.addEventListener('keydown', esc) window.addEventListener('resize', place) window.addEventListener('scroll', onScroll, true) return () => { document.removeEventListener('pointerdown', away) window.removeEventListener('keydown', esc) window.removeEventListener('resize', place) window.removeEventListener('scroll', onScroll, true) } }, [open, anchor, onClose, place]) if (!open) return null return (
{children}
) }