UNPKG

react-bootstrap-typeahead

Version:
42 lines (41 loc) 1.31 kB
import { autoUpdate, flip, size, useFloating, } from '@floating-ui/react-dom'; import { useState } from 'react'; export function getMiddleware(props) { const middleware = []; if (props.flip) { middleware.push(flip()); } if (props.align !== 'right' && props.align !== 'left') { middleware.push(size({ apply({ rects, elements }) { Object.assign(elements.floating.style, { width: `${rects.reference.width}px`, }); }, })); } return middleware; } export function getPlacement(props) { const x = props.align === 'right' ? 'end' : 'start'; const y = props.dropup ? 'top' : 'bottom'; return `${y}-${x}`; } export function useOverlay(referenceElement, options) { const [floatingElement, attachRef] = useState(null); const { floatingStyles } = useFloating({ elements: { floating: floatingElement, reference: referenceElement, }, middleware: getMiddleware(options), placement: getPlacement(options), strategy: options.positionFixed ? 'fixed' : 'absolute', whileElementsMounted: autoUpdate, }); return { innerRef: attachRef, style: floatingStyles, }; } export default useOverlay;