-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathSelect.tsx
346 lines (309 loc) · 9.68 KB
/
Select.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { useEffect, useMemo } from 'react';
import { useId, usePrevious, useUncontrolled } from '@mantine/hooks';
import {
BoxProps,
ElementProps,
Factory,
factory,
MantineColor,
StylesApiProps,
useProps,
useResolvedStylesApi,
} from '../../core';
import {
Combobox,
ComboboxItem,
ComboboxLikeProps,
ComboboxLikeRenderOptionInput,
ComboboxLikeStylesNames,
getOptionsLockup,
getParsedComboboxData,
OptionsDropdown,
useCombobox,
} from '../Combobox';
import {
__BaseInputProps,
__InputStylesNames,
InputClearButtonProps,
InputVariant,
} from '../Input';
import { InputBase } from '../InputBase';
import { ScrollAreaProps } from '../ScrollArea';
export type SelectStylesNames = __InputStylesNames | ComboboxLikeStylesNames;
export interface SelectProps
extends BoxProps,
__BaseInputProps,
ComboboxLikeProps,
StylesApiProps<SelectFactory>,
ElementProps<'input', 'onChange' | 'size' | 'value' | 'defaultValue'> {
/** Controlled component value */
value?: string | null;
/** Uncontrolled component default value */
defaultValue?: string | null;
/** Called when value changes */
onChange?: (value: string | null, option: ComboboxItem) => void;
/** Called when the clear button is clicked */
onClear?: () => void;
/** Determines whether the select should be searchable, `false` by default */
searchable?: boolean;
/** Determines whether check icon should be displayed near the selected option label, `true` by default */
withCheckIcon?: boolean;
/** Position of the check icon relative to the option label, `'left'` by default */
checkIconPosition?: 'left' | 'right';
/** Message displayed when no option matches the current search query while the `searchable` prop is set or there is no data */
nothingFoundMessage?: React.ReactNode;
/** Controlled search value */
searchValue?: string;
/** Default search value */
defaultSearchValue?: string;
/** Called when search changes */
onSearchChange?: (value: string) => void;
/** Determines whether it should be possible to deselect value by clicking on the selected option, `true` by default */
allowDeselect?: boolean;
/** Determines whether the clear button should be displayed in the right section when the component has value, `false` by default */
clearable?: boolean;
/** Props passed down to the clear button */
clearButtonProps?: InputClearButtonProps & ElementProps<'button'>;
/** Props passed down to the hidden input */
hiddenInputProps?: Omit<React.ComponentPropsWithoutRef<'input'>, 'value'>;
/** A function to render content of the option, replaces the default content of the option */
renderOption?: (item: ComboboxLikeRenderOptionInput<ComboboxItem>) => React.ReactNode;
/** Props passed down to the underlying `ScrollArea` component in the dropdown */
scrollAreaProps?: ScrollAreaProps;
/** Controls color of the default chevron, by default depends on the color scheme */
chevronColor?: MantineColor;
}
export type SelectFactory = Factory<{
props: SelectProps;
ref: HTMLInputElement;
stylesNames: SelectStylesNames;
variant: InputVariant;
}>;
const defaultProps: Partial<SelectProps> = {
searchable: false,
withCheckIcon: true,
allowDeselect: true,
checkIconPosition: 'left',
};
export const Select = factory<SelectFactory>((_props, ref) => {
const props = useProps('Select', defaultProps, _props);
const {
classNames,
styles,
unstyled,
vars,
dropdownOpened,
defaultDropdownOpened,
onDropdownClose,
onDropdownOpen,
onFocus,
onBlur,
onClick,
onChange,
data,
value,
defaultValue,
selectFirstOptionOnChange,
onOptionSubmit,
comboboxProps,
readOnly,
disabled,
filter,
limit,
withScrollArea,
maxDropdownHeight,
size,
searchable,
rightSection,
checkIconPosition,
withCheckIcon,
nothingFoundMessage,
name,
form,
searchValue,
defaultSearchValue,
onSearchChange,
allowDeselect,
error,
rightSectionPointerEvents,
id,
clearable,
clearButtonProps,
hiddenInputProps,
renderOption,
onClear,
autoComplete,
scrollAreaProps,
__defaultRightSection,
__clearSection,
__clearable,
chevronColor,
...others
} = props;
const parsedData = useMemo(() => getParsedComboboxData(data), [data]);
const optionsLockup = useMemo(() => getOptionsLockup(parsedData), [parsedData]);
const _id = useId(id);
const [_value, setValue, controlled] = useUncontrolled({
value,
defaultValue,
finalValue: null,
onChange,
});
const selectedOption = typeof _value === 'string' ? optionsLockup[_value] : undefined;
const previousSelectedOption = usePrevious(selectedOption);
const [search, setSearch] = useUncontrolled({
value: searchValue,
defaultValue: defaultSearchValue,
finalValue: selectedOption ? selectedOption.label : '',
onChange: onSearchChange,
});
const combobox = useCombobox({
opened: dropdownOpened,
defaultOpened: defaultDropdownOpened,
onDropdownOpen: () => {
onDropdownOpen?.();
combobox.updateSelectedOptionIndex('active', { scrollIntoView: true });
},
onDropdownClose: () => {
onDropdownClose?.();
combobox.resetSelectedOption();
},
});
const { resolvedClassNames, resolvedStyles } = useResolvedStylesApi<SelectFactory>({
props,
styles,
classNames,
});
useEffect(() => {
if (selectFirstOptionOnChange) {
combobox.selectFirstOption();
}
}, [selectFirstOptionOnChange, _value]);
useEffect(() => {
if (value === null) {
setSearch('');
}
if (
typeof value === 'string' &&
selectedOption &&
(previousSelectedOption?.value !== selectedOption.value ||
previousSelectedOption?.label !== selectedOption.label)
) {
setSearch(selectedOption.label);
}
}, [value, selectedOption]);
const clearButton = (
<Combobox.ClearButton
{...clearButtonProps}
onClear={() => {
setValue(null, null);
setSearch('');
onClear?.();
}}
/>
);
const _clearable = clearable && !!_value && !disabled && !readOnly;
return (
<>
<Combobox
store={combobox}
__staticSelector="Select"
classNames={resolvedClassNames}
styles={resolvedStyles}
unstyled={unstyled}
readOnly={readOnly}
onOptionSubmit={(val) => {
onOptionSubmit?.(val);
const optionLockup = allowDeselect
? optionsLockup[val].value === _value
? null
: optionsLockup[val]
: optionsLockup[val];
const nextValue = optionLockup ? optionLockup.value : null;
nextValue !== _value && setValue(nextValue, optionLockup);
!controlled && setSearch(typeof nextValue === 'string' ? optionLockup?.label || '' : '');
combobox.closeDropdown();
}}
size={size}
{...comboboxProps}
>
<Combobox.Target targetType={searchable ? 'input' : 'button'} autoComplete={autoComplete}>
<InputBase
id={_id}
ref={ref}
__defaultRightSection={
<Combobox.Chevron
size={size}
error={error}
unstyled={unstyled}
color={chevronColor}
/>
}
__clearSection={clearButton}
__clearable={_clearable}
rightSection={rightSection}
rightSectionPointerEvents={rightSectionPointerEvents || (_clearable ? 'all' : 'none')}
{...others}
size={size}
__staticSelector="Select"
disabled={disabled}
readOnly={readOnly || !searchable}
value={search}
onChange={(event) => {
setSearch(event.currentTarget.value);
combobox.openDropdown();
selectFirstOptionOnChange && combobox.selectFirstOption();
}}
onFocus={(event) => {
searchable && combobox.openDropdown();
onFocus?.(event);
}}
onBlur={(event) => {
searchable && combobox.closeDropdown();
setSearch(_value != null ? optionsLockup[_value]?.label || '' : '');
onBlur?.(event);
}}
onClick={(event) => {
searchable ? combobox.openDropdown() : combobox.toggleDropdown();
onClick?.(event);
}}
classNames={resolvedClassNames}
styles={resolvedStyles}
unstyled={unstyled}
pointer={!searchable}
error={error}
/>
</Combobox.Target>
<OptionsDropdown
data={parsedData}
hidden={readOnly || disabled}
filter={filter}
search={search}
limit={limit}
hiddenWhenEmpty={!nothingFoundMessage}
withScrollArea={withScrollArea}
maxDropdownHeight={maxDropdownHeight}
filterOptions={searchable && selectedOption?.label !== search}
value={_value}
checkIconPosition={checkIconPosition}
withCheckIcon={withCheckIcon}
nothingFoundMessage={nothingFoundMessage}
unstyled={unstyled}
labelId={others.label ? `${_id}-label` : undefined}
aria-label={others.label ? undefined : others['aria-label']}
renderOption={renderOption}
scrollAreaProps={scrollAreaProps}
/>
</Combobox>
<Combobox.HiddenInput
value={_value}
name={name}
form={form}
disabled={disabled}
{...hiddenInputProps}
/>
</>
);
});
Select.classes = { ...InputBase.classes, ...Combobox.classes };
Select.displayName = '@mantine/core/Select';