import { createContext, useContext, useId, useMemo, type PropsWithChildren, useState, useRef, useLayoutEffect, } from 'react' import type { PopoverContextValue, PopoverProviderProps } from './types.ts' const PopoverContext = createContext(null) // export function PopoverProvider( props: PropsWithChildren, ) { const parentRef = useRef(null) const [height, setHeight] = useState(0) const [width, setWidth] = useState(0) const id = useId() const triggerId = useId() useLayoutEffect(() => { if (parentRef.current) { const { height, width } = parentRef.current.getBoundingClientRect() setHeight(height) setWidth(width) } }, []) const value = useMemo( () => ({ height, width, id, position: props.position, triggerId, }), [height, id, props.position, triggerId, width], ) return ( {props.children} ) } // usePopover() export function usePopover() { const context = useContext(PopoverContext) if (!context) { throw new Error('usePopover must be used within a PopoverProvider') } return context }