import { ListboxArrow, ListboxButton, ListboxInput, ListboxList, ListboxOption, ListboxPopover, } from '@reach/listbox'; import VisuallyHidden from '@reach/visually-hidden'; import { FunctionComponent } from 'preact'; import { IconType, Icon } from './Icon'; import { useEffect, useState } from 'preact/hooks'; export type DropdownItem = { icon?: IconType; iconClassName?: string; label: string; value: string; }; type DropdownProps = { id: string; label: string; items: DropdownItem[]; defaultValue: string; onChange: (value: string) => void; }; type ListboxButtonProps = DropdownItem & { isExpanded: boolean; }; const CustomDropdownButton: FunctionComponent = ({ label, isExpanded, icon, iconClassName = '', }) => ( <>
{icon ? (
) : null}
{label}
); export const Dropdown: FunctionComponent = ({ id, label, items, defaultValue, onChange, }) => { const [value, setValue] = useState(defaultValue); useEffect(() => { setValue(defaultValue); }, [defaultValue]); const labelId = `${id}-label`; const handleChange = (value: string) => { setValue(value); onChange(value); }; return ( <> {label} { const current = items.find((item) => item.value === value); const icon = current ? current?.icon : null; const iconClassName = current ? current?.iconClassName : null; return CustomDropdownButton({ value: value ? value : label.toLowerCase(), label, isExpanded, ...(icon ? { icon } : null), ...(iconClassName ? { iconClassName } : null), }); }} />
{items.map((item) => ( {item.icon ? (
) : null}
{item.label}
))}
); };