forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 1
/
useButtonPopupSorter.tsx
77 lines (70 loc) · 1.97 KB
/
useButtonPopupSorter.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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<T> = {
data: T[]
options: TypedOption<SortFn<T>>[]
initialIndex?: number
}
type UseButtonPopupSorterReturn<T> = {
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 = <T extends unknown>({
data,
options,
initialIndex = 0,
}: UseButtonPopupSorterOptions<T>): UseButtonPopupSorterReturn<T> => {
const [selectedIndex, setSelectedIndex] = useState<number>(initialIndex)
const selectedOption = options[selectedIndex]
const sortedData = useMemo(
// Copy data since sort mutates.
() => (selectedOption ? [...data].sort(selectedOption.value) : data),
[data, selectedOption]
)
return {
buttonPopupProps: {
trigger: {
type: 'button',
props: {
variant: 'ghost',
children: (
<>
<SortRounded />
<p className="body-text whitespace-nowrap">
{selectedOption?.label}
</p>
</>
),
},
},
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,
}
}