-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathRadioButtonGroupInput.tsx
295 lines (277 loc) · 8.67 KB
/
RadioButtonGroupInput.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
import * as React from 'react';
import { styled } from '@mui/material/styles';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import {
FormControl,
FormHelperText,
FormLabel,
RadioGroup,
} from '@mui/material';
import { RadioGroupProps } from '@mui/material/RadioGroup';
import { FormControlProps } from '@mui/material/FormControl';
import get from 'lodash/get';
import { useInput, FieldTitle, ChoicesProps, useChoicesContext } from 'ra-core';
import { CommonInputProps } from './CommonInputProps';
import { sanitizeInputRestProps } from './sanitizeInputRestProps';
import { InputHelperText } from './InputHelperText';
import { RadioButtonGroupInputItem } from './RadioButtonGroupInputItem';
import { Labeled } from '../Labeled';
import { LinearProgress } from '../layout';
/**
* An Input component for a radio button group, 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: 'M', name: 'Male' },
* { id: 'F', name: 'Female' },
* ];
* <RadioButtonGroupInput source="gender" 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' },
* ];
* <RadioButtonGroupInput source="author_id" 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}`;
* <CheckboxGroupInput source="recipients" 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>)
* };
* <RadioButtonGroupInput source="recipients" choices={choices} optionText={<FullNameField />}/>
*
* The choices are translated by default, so you can use translation identifiers as choices:
* @example
* const choices = [
* { id: 'M', name: 'myroot.gender.male' },
* { id: 'F', name: 'myroot.gender.female' },
* ];
*
* However, in some cases (e.g. inside a `<ReferenceInput>`), you may not want
* the choice to be translated. In that case, set the `translateChoice` prop to false.
* @example
* <RadioButtonGroupInput source="gender" choices={choices} translateChoice={false}/>
*
* The object passed as `options` props is passed to the Material UI <RadioButtonGroup> component
*/
export const RadioButtonGroupInput = (props: RadioButtonGroupInputProps) => {
const {
choices: choicesProp,
className,
format,
helperText,
isFetching: isFetchingProp,
isLoading: isLoadingProp,
label,
margin = 'dense',
onBlur,
onChange,
options = defaultOptions,
optionText = 'name',
optionValue = 'id',
parse,
resource: resourceProp,
row = true,
source: sourceProp,
translateChoice = true,
validate,
...rest
} = props;
const {
allChoices,
isLoading,
error: fetchError,
resource,
source,
} = useChoicesContext({
choices: choicesProp,
isFetching: isFetchingProp,
isLoading: isLoadingProp,
resource: resourceProp,
source: sourceProp,
});
if (source === undefined) {
throw new Error(
`If you're not wrapping the RadioButtonGroupInput inside a ReferenceArrayInput, you must provide the source prop`
);
}
if (!isLoading && !fetchError && allChoices === undefined) {
throw new Error(
`If you're not wrapping the RadioButtonGroupInput inside a ReferenceArrayInput, you must provide the choices prop`
);
}
const { id, isRequired, fieldState, field, formState } = useInput({
format,
onBlur,
onChange,
parse,
resource,
source,
validate,
...rest,
});
const { error, invalid, isTouched } = fieldState;
const { isSubmitted } = formState;
if (isLoading) {
return (
<Labeled
htmlFor={id}
label={label}
source={source}
resource={resource}
className={clsx('ra-input', `ra-input-${source}`, className)}
isRequired={isRequired}
>
<LinearProgress />
</Labeled>
);
}
const renderHelperText =
!!fetchError ||
helperText !== false ||
((isTouched || isSubmitted) && invalid);
return (
<StyledFormControl
component="fieldset"
className={clsx('ra-input', `ra-input-${source}`, className)}
margin={margin}
error={fetchError || ((isTouched || isSubmitted) && invalid)}
{...sanitizeRestProps(rest)}
>
<FormLabel
component="legend"
className={RadioButtonGroupInputClasses.label}
>
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
/>
</FormLabel>
<RadioGroup
id={id}
row={row}
{...field}
{...options}
{...sanitizeRestProps(rest)}
>
{allChoices?.map(choice => (
<RadioButtonGroupInputItem
key={get(choice, optionValue)}
choice={choice}
optionText={optionText}
optionValue={optionValue}
source={id}
translateChoice={translateChoice}
/>
))}
</RadioGroup>
{renderHelperText ? (
<FormHelperText>
<InputHelperText
touched={isTouched || isSubmitted || fetchError}
error={error?.message || fetchError?.message}
helperText={helperText}
/>
</FormHelperText>
) : null}
</StyledFormControl>
);
};
RadioButtonGroupInput.propTypes = {
choices: PropTypes.arrayOf(PropTypes.any),
label: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool,
PropTypes.element,
]),
options: PropTypes.object,
optionText: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
PropTypes.element,
]),
optionValue: PropTypes.string,
resource: PropTypes.string,
source: PropTypes.string,
translateChoice: PropTypes.bool,
};
const sanitizeRestProps = ({
afterSubmit,
allowNull,
beforeSubmit,
choices,
className,
crudGetMatching,
crudGetOne,
data,
filter,
filterToQuery,
formatOnBlur,
isEqual,
limitChoicesToValue,
multiple,
name,
pagination,
perPage,
ref,
reference,
refetch,
render,
setFilter,
setPagination,
setSort,
sort,
subscription,
type,
validateFields,
validation,
value,
...rest
}: any) => sanitizeInputRestProps(rest);
export type RadioButtonGroupInputProps = Omit<CommonInputProps, 'source'> &
ChoicesProps &
FormControlProps &
RadioGroupProps & {
options?: RadioGroupProps;
source?: string;
};
const PREFIX = 'RaRadioButtonGroupInput';
export const RadioButtonGroupInputClasses = {
label: `${PREFIX}-label`,
};
const StyledFormControl = styled(FormControl, {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme }) => ({
[`& .${RadioButtonGroupInputClasses.label}`]: {
transform: 'translate(0, 5px) scale(0.75)',
transformOrigin: `top ${theme.direction === 'ltr' ? 'left' : 'right'}`,
},
}));
const defaultOptions = {};