import { RadioButtonChecked, RadioButtonUnchecked, SortRounded, } from '@mui/icons-material' import { useMemo, useState } from 'react' import { ButtonPopupProps, SortFn, TypedOption } from '@dao-dao/types' import { ButtonLink } from '../components' type UseButtonPopupSorterOptions = { /** * The data to sort. If undefined, returns empty array. This is useful when * data is not yet ready, and passing an empty array would cause the useMemo * to run every time. */ data?: T[] options: TypedOption>[] initialIndex?: number } type UseButtonPopupSorterReturn = { buttonPopupProps: Pick< ButtonPopupProps, 'sections' | 'sectionClassName' | 'trigger' | 'ButtonLink' > sortedData: T[] } // Pass an array of data and sort options, and get `buttonPopupProps` (for // passing to `ButtonPopup`) and memoized `sortedData`. export const useButtonPopupSorter = ({ data, options, initialIndex = 0, }: UseButtonPopupSorterOptions): UseButtonPopupSorterReturn => { const [selectedIndex, setSelectedIndex] = useState(initialIndex) const selectedOption = options[selectedIndex] const sortedData = useMemo( // Copy data since sort mutates. () => !data ? [] : selectedOption ? [...data].sort(selectedOption.value) : data, [data, selectedOption] ) return { buttonPopupProps: { trigger: { type: 'button', props: { variant: 'ghost', children: ( <>

{selectedOption?.label}

), }, }, sectionClassName: 'gap-1', sections: [ { buttons: options.map(({ label }, index) => ({ Icon: selectedIndex === index ? RadioButtonChecked : RadioButtonUnchecked, pressed: selectedIndex === index, label, onClick: () => setSelectedIndex(index), })), }, ], // No button links, so using the stateless component is fine here. ButtonLink, }, sortedData, } }