-
Notifications
You must be signed in to change notification settings - Fork 0
/
SelectOptions.tsx
240 lines (219 loc) · 6.36 KB
/
SelectOptions.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import React, {
FC,
ReactNode,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { FixedSizeList } from 'react-window';
import { GetItemPropsOptions } from 'downshift3';
import { MdCheck, MdHighlightOff } from 'react-icons/md';
import { Box, Flex } from '../Layout';
import { Heading } from '../Typography';
import { Icon } from '../Icon';
import { useLocale } from '../locale';
import { StyledSelectOption } from './styles';
import { fuzzyFilter, getDataTestId, itemToString } from './utils';
export type Option =
| {
label: ReactNode;
value: string | number;
disabled?: boolean;
}
| string
| number;
export type SelectedValue = Option | Option[];
export interface CreateOption {
label: 'CREATE_OPTION';
value: string;
}
const DefaultNoOptionsMessage: FC = () => {
const { locale } = useLocale();
return (
<Flex
py="3"
alignItems="center"
justifyContent="center"
style={{ cursor: 'not-allowed' }}
>
<Icon type={MdHighlightOff} mr="2" />
<Heading.H5 color="gray500">{locale.Select.noDataText}</Heading.H5>
</Flex>
);
};
interface SelectOptionsProps {
visible: boolean;
creatable: boolean;
searchable: boolean;
multiple: boolean;
itemSize: number;
optionsMaxHeight: number;
getMenuProps: () => any;
getItemProps: (option: GetItemPropsOptions<Option>) => any;
options: Option[];
inputValue: string;
menu?: ReactNode;
highlightedIndex: number | null;
selectedItem?: Option;
selectedItems?: Option[];
noOptionsMessage?: () => ReactNode;
formatCreateLabel?: (labelInfo: {
value: string;
active: boolean;
hovered: boolean;
}) => ReactNode;
isValidNewOption?: (value: string) => boolean;
'data-testid'?: string;
}
const SelectOptions: FC<SelectOptionsProps> = ({
visible,
creatable,
searchable,
multiple,
itemSize,
optionsMaxHeight,
getMenuProps,
getItemProps,
options,
inputValue,
menu,
highlightedIndex,
selectedItem,
selectedItems,
noOptionsMessage = () => <DefaultNoOptionsMessage />,
formatCreateLabel = ({ value }) => `Create new option: ${value}`,
isValidNewOption = (value) => value.trim() !== '',
...props
}) => {
const listRef = useRef<FixedSizeList>(null);
const [prevSearchValue, setPrevSearchValue] = useState(inputValue);
const [createOptionWidth, setCreateOptionWidth] = useState<
number | undefined
>(undefined);
const createOptionRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (listRef.current && highlightedIndex) {
listRef.current.scrollToItem(highlightedIndex);
}
}, [highlightedIndex]);
useEffect(() => {
// save previous inputValue to prevent options reset when options animating fade out
if (visible) {
setPrevSearchValue(inputValue);
} else {
setCreateOptionWidth(undefined);
}
if (createOptionRef.current) {
setCreateOptionWidth(createOptionRef.current.scrollWidth + 10);
}
}, [inputValue, visible]);
const filteredItems = useMemo(() => {
// filter options when searchable or creatable or multiple
if (searchable || creatable || multiple) {
const filter = fuzzyFilter(itemToString);
return prevSearchValue.trim() === ''
? options
: filter(options, prevSearchValue);
}
return options;
}, [creatable, multiple, options, prevSearchValue, searchable]);
const additionItems = useMemo(() => {
// if creatable is true, append create option to options
if (creatable && isValidNewOption(visible ? inputValue : prevSearchValue)) {
return [
{
label: 'CREATE_OPTION',
value: visible ? inputValue : prevSearchValue,
},
];
}
return [];
}, [creatable, inputValue, isValidNewOption, prevSearchValue, visible]);
const items = useMemo(
() => [...filteredItems, ...additionItems],
[additionItems, filteredItems]
);
if (items.length === 0) {
return <>{noOptionsMessage()}</>;
}
return (
<Box
borderRadius="lg"
overflow="hidden"
style={{
minWidth: createOptionWidth,
}}
{...getDataTestId(props, 'menu')}
{...getMenuProps()}
>
<FixedSizeList
ref={listRef}
width="100%"
height={Math.min(items.length * itemSize, optionsMaxHeight)}
itemSize={itemSize}
itemCount={items.length}
initialScrollOffset={highlightedIndex ? highlightedIndex * itemSize : 0}
>
{({ index, style }) => {
const option = items[index];
const isCreateOption =
(option as CreateOption).label === 'CREATE_OPTION';
const optionString = itemToString(option);
const hovered = visible && highlightedIndex === index;
const disabled =
typeof option === 'object' && 'disabled' in option
? option.disabled
: undefined;
const active = multiple
? (selectedItems as Option[])
.map(itemToString)
.includes(optionString)
: itemToString(selectedItem) === optionString;
const content = isCreateOption
? formatCreateLabel({
value: (option as CreateOption).value,
active,
hovered,
})
: optionString;
return (
<StyledSelectOption
key={optionString}
active={active}
hovered={hovered}
disabled={disabled}
style={style}
{...getDataTestId(props, `item-${index}`)}
{...getItemProps({
index,
item: option,
disabled,
})}
>
<div
ref={isCreateOption ? createOptionRef : undefined}
title={isCreateOption ? undefined : String(content)}
>
{multiple &&
(active ? (
<Icon
type={MdCheck}
fill={hovered ? 'light' : 'primaryLight'}
size="16"
mr="8px"
/>
) : (
<Box width="16px" mr="8px" />
))}
{content}
</div>
</StyledSelectOption>
);
}}
</FixedSizeList>
{menu}
</Box>
);
};
export default SelectOptions;