import { Icon, Icons } from "components/Icon"; import React, { MouseEventHandler, SyntheticEvent, useEffect, useState, } from "react"; import { Backdrop, useBackdrop } from "components/layout/Backdrop"; import { ButtonControl } from "./buttons/ButtonControl"; export interface OptionItem { id: string; name: string; } interface DropdownProps { open: boolean; setOpen: React.Dispatch>; selectedItem: string; setSelectedItem: (value: string) => void; options: Array; } export interface OptionProps { option: OptionItem; onClick: MouseEventHandler; tabIndex?: number; } function Option({ option, onClick, tabIndex }: OptionProps) { return (
); } export const Dropdown = React.forwardRef( (props: DropdownProps, ref) => { const [setBackdrop, backdropProps, highlightedProps] = useBackdrop(); const [delayedSelectedId, setDelayedSelectedId] = useState( props.selectedItem ); useEffect(() => { let id: NodeJS.Timeout; if (props.open) { setDelayedSelectedId(props.selectedItem); } else { id = setTimeout(() => { setDelayedSelectedId(props.selectedItem); }, 200); } return () => { if (id) clearTimeout(id); }; /* eslint-disable-next-line */ }, [props.open]); const selectedItem: OptionItem = props.options.find((opt) => opt.id === props.selectedItem) || props.options[0]; useEffect(() => { setBackdrop(props.open); /* eslint-disable-next-line */ }, [props.open]); const onOptionClick = (e: SyntheticEvent, option: OptionItem) => { e.stopPropagation(); props.setSelectedItem(option.id); props.setOpen(false); }; return (
props.setOpen((open) => !open)} >
{selectedItem.name}
{props.options .filter((opt) => opt.id !== delayedSelectedId) .map((opt) => (
props.setOpen(false)} {...backdropProps} />
); } );