-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathSelect.tsx
More file actions
313 lines (280 loc) · 8.73 KB
/
Select.tsx
File metadata and controls
313 lines (280 loc) · 8.73 KB
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
import React, { useEffect, useMemo } from 'react';
import { useId, useUncontrolled } from '@mantine/hooks';
import {
BoxProps,
ElementProps,
Factory,
factory,
StylesApiProps,
useProps,
useResolvedStylesApi,
} from '../../core';
import { __CloseButtonProps } from '../CloseButton';
import {
Combobox,
ComboboxItem,
ComboboxLikeProps,
ComboboxLikeRenderOptionInput,
ComboboxLikeStylesNames,
getOptionsLockup,
getParsedComboboxData,
OptionsDropdown,
useCombobox,
} from '../Combobox';
import { __BaseInputProps, __InputStylesNames, InputVariant } from '../Input';
import { InputBase } from '../InputBase';
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 matched current search query, only applicable when `searchable` prop is set */
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?: __CloseButtonProps & ElementProps<'button'>;
/** Props passed down to the hidden input */
hiddenInputProps?: React.ComponentPropsWithoutRef<'input'>;
/** A function to render content of the option, replaces the default content of the option */
renderOption?: (item: ComboboxLikeRenderOptionInput<ComboboxItem>) => React.ReactNode;
}
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,
...others
} = props;
const parsedData = useMemo(() => getParsedComboboxData(data), [data]);
const optionsLockup = useMemo(() => getOptionsLockup(parsedData), [parsedData]);
const _id = useId(id);
const [_value, setValue] = useUncontrolled({
value,
defaultValue,
finalValue: null,
onChange,
});
const selectedOption = typeof _value === 'string' ? optionsLockup[_value] : undefined;
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) {
setSearch(selectedOption.label);
}
}, [value, selectedOption]);
const clearButton = clearable && !!_value && !disabled && !readOnly && (
<Combobox.ClearButton
size={size as string}
{...clearButtonProps}
onClear={() => {
setValue(null, null);
setSearch('');
onClear?.();
}}
/>
);
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;
setValue(nextValue, optionLockup);
setSearch(typeof nextValue === 'string' ? optionLockup?.label || '' : '');
combobox.closeDropdown();
}}
size={size}
{...comboboxProps}
>
<Combobox.Target targetType={searchable ? 'input' : 'button'} autoComplete={autoComplete}>
<InputBase
id={_id}
ref={ref}
rightSection={
rightSection ||
clearButton || <Combobox.Chevron size={size} error={error} unstyled={unstyled} />
}
rightSectionPointerEvents={rightSectionPointerEvents || (clearButton ? '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={!searchable || !nothingFoundMessage}
withScrollArea={withScrollArea}
maxDropdownHeight={maxDropdownHeight}
filterOptions={searchable && selectedOption?.label !== search}
value={_value}
checkIconPosition={checkIconPosition}
withCheckIcon={withCheckIcon}
nothingFoundMessage={nothingFoundMessage}
unstyled={unstyled}
labelId={`${_id}-label`}
renderOption={renderOption}
/>
</Combobox>
<input
type="hidden"
name={name}
value={_value || ''}
form={form}
disabled={disabled}
{...hiddenInputProps}
/>
</>
);
});
Select.classes = { ...InputBase.classes, ...Combobox.classes };
Select.displayName = '@mantine/core/Select';