// @flow strict import * as React from 'react'; import { // $FlowFixMe[untyped-import] autoUpdate, // $FlowFixMe[untyped-import] flip, // $FlowFixMe[untyped-import] offset, // $FlowFixMe[untyped-import] shift, // $FlowFixMe[untyped-import] useFloating, } from '@floating-ui/react-dom'; import {sizeFluid} from '../../styles/variables/_size'; import {spaceNone, spaceXXSmall} from '../../styles/variables/_space'; import {classify} from '../../utils/classify'; import {ClickAway} from '../../utils/click-away'; import type {ButtonProps} from '../Button'; import {Button} from '../Button'; import type {MenuOption, MenuProps} from '../Menu'; import {Menu} from '../Menu'; import css from './ButtonDropdown.module.css'; export const ANCHOR_POSITION_TYPE = Object.freeze({ top: 'top', topStart: 'top-start', topEnd: 'top-end', bottom: 'bottom', bottomStart: 'bottom-start', bottomEnd: 'bottom-end', }); export type AnchorType = $Values; type ClassNames = $ReadOnly<{ buttonWrapper?: string, dropdownContainer?: string, buttonIcon?: string, }>; export type ButtonDropdownProps = { ...ButtonProps, classNames?: ClassNames, menu?: MenuProps, anchorPosition?: AnchorType, onOptionSelect?: (option: MenuOption) => mixed, onMenuOpen?: () => mixed, onMenuClose?: () => mixed, ... }; export const ButtonDropdown: React$AbstractComponent< ButtonDropdownProps, HTMLDivElement, > = React.forwardRef( ( { anchorPosition = 'bottom-start', size = 'medium', onOptionSelect, menu, classNames, disabled, onMenuOpen, onMenuClose, children, iconRightName, iconRightType = 'solid', isFluid, ...restButtonProps }: ButtonDropdownProps, forwardRef, ) => { const menuBtnRef = React.useRef(null); React.useImperativeHandle(forwardRef, () => menuBtnRef.current); const {x, y, reference, floating, strategy} = useFloating({ strategy: 'absolute', placement: anchorPosition, whileElementsMounted: autoUpdate, middleware: [shift(), flip(), offset(parseInt(spaceXXSmall))], }); const onMenuToggle = (isOpen: boolean) => { isOpen ? onMenuOpen && onMenuOpen() : onMenuClose && onMenuClose(); }; return ( {({isOpen, onOpen, cancelNext, clickAway}) => (
{isOpen && menu && (
{ onOptionSelect && onOptionSelect(option); if ( !menu.optionsVariant || menu.optionsVariant === 'normal' ) { clickAway(); } }} size={menu.size || size} />
)}
)}
); }, );