-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathSelectArrayInput.tsx
448 lines (425 loc) · 13.8 KB
/
SelectArrayInput.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import * as React from 'react';
import { styled } from '@mui/material/styles';
import { useCallback, useRef, ChangeEvent } from 'react';
import clsx from 'clsx';
import {
Select,
SelectProps,
MenuItem,
InputLabel,
FormHelperText,
FormControl,
Chip,
OutlinedInput,
} from '@mui/material';
import {
ChoicesProps,
FieldTitle,
useInput,
useChoicesContext,
useChoices,
RaRecord,
useGetRecordRepresentation,
} from 'ra-core';
import { InputHelperText } from './InputHelperText';
import { FormControlProps } from '@mui/material/FormControl';
import { LinearProgress } from '../layout';
import { CommonInputProps } from './CommonInputProps';
import { Labeled } from '../Labeled';
import {
SupportCreateSuggestionOptions,
useSupportCreateSuggestion,
} from './useSupportCreateSuggestion';
/**
* An Input component for a select box allowing multiple selections, using an array of objects for the options
*
* Pass possible options as an array of objects in the 'choices' attribute.
*
* By default, the options are built from:
* - the 'id' property as the option value,
* - the 'name' property as the option text
* @example
* const choices = [
* { id: 'programming', name: 'Programming' },
* { id: 'lifestyle', name: 'Lifestyle' },
* { id: 'photography', name: 'Photography' },
* ];
* <SelectArrayInput source="tags" choices={choices} />
*
* You can also customize the properties to use for the option name and value,
* thanks to the 'optionText' and 'optionValue' attributes.
* @example
* const choices = [
* { _id: 123, full_name: 'Leo Tolstoi', sex: 'M' },
* { _id: 456, full_name: 'Jane Austen', sex: 'F' },
* ];
* <SelectArrayInput source="authors" choices={choices} optionText="full_name" optionValue="_id" />
*
* `optionText` also accepts a function, so you can shape the option text at will:
* @example
* const choices = [
* { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
* { id: 456, first_name: 'Jane', last_name: 'Austen' },
* ];
* const optionRenderer = choice => `${choice.first_name} ${choice.last_name}`;
* <SelectArrayInput source="authors" choices={choices} optionText={optionRenderer} />
*
* `optionText` also accepts a React Element, that can access
* the related choice through the `useRecordContext` hook. You can use Field components there.
* @example
* const choices = [
* { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
* { id: 456, first_name: 'Jane', last_name: 'Austen' },
* ];
* const FullNameField = () => {
* const record = useRecordContext();
* return (<span>{record.first_name} {record.last_name}</span>)
* };
* <SelectArrayInput source="authors" choices={choices} optionText={<FullNameField />}/>
*
* The choices are translated by default, so you can use translation identifiers as choices:
* @example
* const choices = [
* { id: 'programming', name: 'myroot.tags.programming' },
* { id: 'lifestyle', name: 'myroot.tags.lifestyle' },
* { id: 'photography', name: 'myroot.tags.photography' },
* ];
*/
export const SelectArrayInput = (props: SelectArrayInputProps) => {
const {
choices: choicesProp,
className,
create,
createLabel,
createValue,
disableValue = 'disabled',
format,
helperText,
label,
isFetching: isFetchingProp,
isLoading: isLoadingProp,
isPending: isPendingProp,
margin,
onBlur,
onChange,
onCreate,
options = defaultOptions,
optionText,
optionValue = 'id',
parse,
resource: resourceProp,
size = 'small',
source: sourceProp,
translateChoice,
validate,
variant,
disabled,
readOnly,
...rest
} = props;
const inputLabel = useRef(null);
const {
allChoices,
isPending,
error: fetchError,
source,
resource,
isFromReference,
} = useChoicesContext({
choices: choicesProp,
isLoading: isLoadingProp,
isPending: isPendingProp,
isFetching: isFetchingProp,
resource: resourceProp,
source: sourceProp,
});
const {
field,
isRequired,
fieldState: { error, invalid },
id,
} = useInput({
format,
onBlur,
onChange,
parse,
resource,
source,
validate,
disabled,
readOnly,
...rest,
});
const getRecordRepresentation = useGetRecordRepresentation(resource);
const { getChoiceText, getChoiceValue, getDisableValue } = useChoices({
optionText:
optionText ??
(isFromReference ? getRecordRepresentation : undefined),
optionValue,
disableValue,
translateChoice: translateChoice ?? !isFromReference,
});
const handleChange = useCallback(
(eventOrChoice: ChangeEvent<HTMLInputElement> | RaRecord) => {
// We might receive an event from the mui component
// In this case, it will be the choice id
if (eventOrChoice?.target) {
// when used with different IDs types, unselection leads to double selection with both types
// instead of the value being removed from the array
// e.g. we receive eventOrChoice.target.value = [1, '2', 2] instead of [1] after removing 2
// this snippet removes a value if it is present twice
eventOrChoice.target.value = eventOrChoice.target.value.reduce(
(acc, value) => {
// eslint-disable-next-line eqeqeq
const index = acc.findIndex(v => v == value);
return index < 0
? [...acc, value]
: [...acc.slice(0, index), ...acc.slice(index + 1)];
},
[]
);
field.onChange(eventOrChoice);
} else {
// Or we might receive a choice directly, for instance a newly created one
field.onChange([
...(field.value || []),
getChoiceValue(eventOrChoice),
]);
}
},
[field, getChoiceValue]
);
const {
getCreateItem,
handleChange: handleChangeWithCreateSupport,
createElement,
} = useSupportCreateSuggestion({
create,
createLabel,
createValue,
handleChange,
onCreate,
optionText,
});
const createItem = create || onCreate ? getCreateItem() : null;
const finalChoices =
create || onCreate
? [...(allChoices || []), createItem]
: allChoices || [];
const renderMenuItemOption = useCallback(
choice =>
!!createItem &&
choice?.id === createItem.id &&
typeof optionText === 'function'
? createItem.name
: getChoiceText(choice),
[createItem, getChoiceText, optionText]
);
const renderMenuItem = useCallback(
choice => {
return choice ? (
<MenuItem
key={getChoiceValue(choice)}
value={getChoiceValue(choice)}
disabled={getDisableValue(choice)}
>
{renderMenuItemOption(
!!createItem && choice?.id === createItem.id
? createItem
: choice
)}
</MenuItem>
) : null;
},
[getChoiceValue, getDisableValue, renderMenuItemOption, createItem]
);
if (isPending) {
return (
<Labeled
label={label}
source={source}
resource={resource}
className={clsx('ra-input', `ra-input-${source}`, className)}
isRequired={isRequired}
>
<LinearProgress />
</Labeled>
);
}
// Here wen ensure we always have an array and this array does not contain the default value (empty string)
const finalValue = Array.isArray(field.value ?? [])
? field.value
: field.value
? [field.value]
: [];
const outlinedInputProps =
variant === 'outlined'
? {
input: (
<OutlinedInput
id="select-multiple-chip"
label={
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
/>
}
/>
),
}
: {};
const renderHelperText = !!fetchError || helperText !== false || invalid;
return (
<>
<StyledFormControl
margin={margin}
className={clsx('ra-input', `ra-input-${source}`, className)}
error={fetchError || invalid}
variant={variant}
{...sanitizeRestProps(rest)}
>
<InputLabel
ref={inputLabel}
id={`${id}-outlined-label`}
htmlFor={id}
>
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
/>
</InputLabel>
<Select
id={id}
labelId={`${id}-outlined-label`}
label={
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
/>
}
multiple
error={!!fetchError || invalid}
renderValue={(selected: any[]) => (
<div className={SelectArrayInputClasses.chips}>
{(Array.isArray(selected) ? selected : [])
.map(item =>
(allChoices || []).find(
// eslint-disable-next-line eqeqeq
choice => getChoiceValue(choice) == item
)
)
.filter(item => !!item)
.map(item => (
<Chip
key={getChoiceValue(item)}
label={renderMenuItemOption(item)}
className={SelectArrayInputClasses.chip}
size="small"
/>
))}
</div>
)}
disabled={disabled || readOnly}
readOnly={readOnly}
data-testid="selectArray"
size={size}
{...field}
{...options}
onChange={handleChangeWithCreateSupport}
value={finalValue}
{...outlinedInputProps}
>
{finalChoices.map(renderMenuItem)}
</Select>
{renderHelperText ? (
<FormHelperText error={!!fetchError || !!error}>
<InputHelperText
error={error?.message || fetchError?.message}
helperText={helperText}
/>
</FormHelperText>
) : null}
</StyledFormControl>
{createElement}
</>
);
};
export type SelectArrayInputProps = ChoicesProps &
Omit<SupportCreateSuggestionOptions, 'handleChange'> &
Omit<CommonInputProps, 'source'> &
Omit<FormControlProps, 'defaultValue' | 'onBlur' | 'onChange'> & {
options?: SelectProps;
disableValue?: string;
source?: string;
onChange?: (event: ChangeEvent<HTMLInputElement> | RaRecord) => void;
};
const sanitizeRestProps = ({
alwaysOn,
choices,
classNamInputWithOptionsPropse,
componenInputWithOptionsPropst,
crudGetMInputWithOptionsPropsatching,
crudGetOInputWithOptionsPropsne,
defaultValue,
disableValue,
emptyText,
enableGetChoices,
filter,
filterToQuery,
initializeForm,
initialValue,
input,
isRequired,
label,
limitChoicesToValue,
loaded,
locale,
meta,
onChange,
options,
optionValue,
optionText,
perPage,
record,
reference,
resource,
setFilter,
setPagination,
setSort,
sort,
source,
textAlign,
translate,
translateChoice,
validation,
...rest
}: any) => rest;
const PREFIX = 'RaSelectArrayInput';
export const SelectArrayInputClasses = {
chips: `${PREFIX}-chips`,
chip: `${PREFIX}-chip`,
};
const StyledFormControl = styled(FormControl, {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme }) => ({
minWidth: theme.spacing(20),
[theme.breakpoints.down('sm')]: {
width: '100%',
},
[`& .${SelectArrayInputClasses.chips}`]: {
display: 'flex',
flexWrap: 'wrap',
},
[`& .${SelectArrayInputClasses.chip}`]: {
marginTop: theme.spacing(0.5),
marginRight: theme.spacing(0.5),
},
}));
const defaultOptions = {};