diff --git a/src/components/SplitButton.tsx b/src/components/SplitButton.tsx index 5173c8d..17611c2 100644 --- a/src/components/SplitButton.tsx +++ b/src/components/SplitButton.tsx @@ -9,10 +9,15 @@ import Paper from '@mui/material/Paper'; import Popper from '@mui/material/Popper'; import * as React from 'react'; +type Option = { + label: string; + value?: string; + disabled?: boolean; +}; interface Props { disabled?: boolean; onSelect: (option: string) => void; - options: string[]; + options: string[] | Option[]; startIcon?: React.ReactNode; } @@ -26,17 +31,27 @@ export default function SplitButton({ const anchorRef = React.useRef(null); const [selectedIndex, setSelectedIndex] = React.useState(0); + React.useEffect(() => { + setSelectedIndex(options.findIndex((option) => !option.disabled)); + }, [options]); + const handleClick = () => { - onSelect(options[selectedIndex]); + const selected = options[selectedIndex]; + onSelect( + typeof selected === 'string' ? selected : selected.value || selected.label + ); }; const handleMenuItemClick = ( event: React.MouseEvent, index: number ) => { + const selected = options[index]; setSelectedIndex(index); setOpen(false); - onSelect(options[index]); + onSelect( + typeof selected === 'string' ? selected : selected.value || selected.label + ); }; const handleToggle = () => { @@ -54,6 +69,11 @@ export default function SplitButton({ setOpen(false); }; + const selectedLabel = + typeof options[selectedIndex] === 'string' + ? options[selectedIndex] + : options[selectedIndex].label; + return ( } onSelect={async (selectedLabel: string) => { const fileType = selectedLabel.split(' ')[1].toLowerCase();