| 20 | * floating element. |
| 21 | */ |
| 22 | export function useAnchoredPosition( |
| 23 | settings?: AnchoredPositionHookSettings, |
| 24 | dependencies: React.DependencyList = [], |
| 25 | ): { |
| 26 | floatingElementRef: React.RefObject<Element> |
| 27 | anchorElementRef: React.RefObject<Element> |
| 28 | position: AnchorPosition | undefined |
| 29 | } { |
| 30 | const floatingElementRef = useProvidedRefOrCreate(settings?.floatingElementRef) |
| 31 | const anchorElementRef = useProvidedRefOrCreate(settings?.anchorElementRef) |
| 32 | const [position, setPosition] = React.useState<AnchorPosition | undefined>(undefined) |
| 33 | |
| 34 | const updatePosition = React.useCallback( |
| 35 | () => { |
| 36 | if (floatingElementRef.current instanceof Element && anchorElementRef.current instanceof Element) { |
| 37 | setPosition(getAnchoredPosition(floatingElementRef.current, anchorElementRef.current, settings)) |
| 38 | } else { |
| 39 | setPosition(undefined) |
| 40 | } |
| 41 | }, |
| 42 | // eslint-disable-next-line react-hooks/exhaustive-deps |
| 43 | [floatingElementRef, anchorElementRef, ...dependencies], |
| 44 | ) |
| 45 | |
| 46 | useLayoutEffect(updatePosition, [updatePosition]) |
| 47 | |
| 48 | useResizeObserver(updatePosition) |
| 49 | |
| 50 | return { |
| 51 | floatingElementRef, |
| 52 | anchorElementRef, |
| 53 | position, |
| 54 | } |
| 55 | } |