-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathArrayInput.tsx
More file actions
255 lines (242 loc) · 7.86 KB
/
ArrayInput.tsx
File metadata and controls
255 lines (242 loc) · 7.86 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
import * as React from 'react';
import clsx from 'clsx';
import {
isRequired,
FieldTitle,
useSourceContext,
ArrayInputBase,
type ArrayInputBaseProps,
} from 'ra-core';
import { useFormContext } from 'react-hook-form';
import {
InputLabel,
FormControl,
FormHelperText,
type FormControlProps,
styled,
type ComponentsOverrides,
useThemeProps,
} from '@mui/material';
import get from 'lodash/get.js';
import isEqual from 'lodash/isEqual.js';
import { LinearProgress } from '../../layout/LinearProgress';
import { InputHelperText } from '../InputHelperText';
import { sanitizeInputRestProps } from '../sanitizeInputRestProps';
import { Labeled } from '../../Labeled';
/**
* To edit arrays of data embedded inside a record, <ArrayInput> creates a list of sub-forms.
*
* @example
*
* import { ArrayInput, SimpleFormIterator, DateInput, TextInput } from 'react-admin';
*
* <ArrayInput source="backlinks">
* <SimpleFormIterator>
* <DateInput source="date" />
* <TextInput source="url" />
* </SimpleFormIterator>
* </ArrayInput>
*
* <ArrayInput> allows the edition of embedded arrays, like the backlinks field
* in the following post record:
*
* {
* id: 123
* backlinks: [
* {
* date: '2012-08-10T00:00:00.000Z',
* url: 'http://example.com/foo/bar.html',
* },
* {
* date: '2012-08-14T00:00:00.000Z',
* url: 'https://blog.johndoe.com/2012/08/12/foobar.html',
* }
* ]
* }
*
* <ArrayInput> expects a single child, which must be a *form iterator* component.
* A form iterator is a component accepting a fields object as passed by
* react-hook-form-arrays's useFieldArray() hook, and defining a layout for
* an array of fields. For instance, the <SimpleFormIterator> component
* displays an array of fields in an unordered list (<ul>), one sub-form by
* list item (<li>). It also provides controls for adding and removing
* a sub-record (a backlink in this example).
*
* @see {@link https://react-hook-form.com/docs/usefieldarray}
*/
export const ArrayInput = (inProps: ArrayInputProps) => {
const props = useThemeProps({
props: inProps,
name: PREFIX,
});
const {
className,
defaultValue = [],
label,
children,
helperText,
isPending,
resource: resourceFromProps,
source: arraySource,
validate,
variant,
margin = 'dense',
...rest
} = props;
const parentSourceContext = useSourceContext();
const finalSource = parentSourceContext.getSource(arraySource);
const { subscribe } = useFormContext();
const [{ error, hasBeenInteractedWith, isSubmitted }, setArrayInputState] =
React.useState<{
error: any;
hasBeenInteractedWith: boolean;
isSubmitted: boolean;
}>({
error: undefined,
hasBeenInteractedWith: false,
isSubmitted: false,
});
React.useEffect(() => {
return subscribe({
formState: {
dirtyFields: true,
errors: true,
isSubmitted: true,
touchedFields: true,
},
callback: ({ dirtyFields, errors, isSubmitted, touchedFields }) => {
const error = get(errors ?? {}, finalSource);
const hasBeenInteractedWith =
get(dirtyFields ?? {}, finalSource, false) !== false ||
get(touchedFields ?? {}, finalSource, false) !== false;
setArrayInputState(previousState =>
isEqual(previousState, {
error,
hasBeenInteractedWith,
isSubmitted: !!isSubmitted,
})
? previousState
: {
error,
hasBeenInteractedWith,
isSubmitted: !!isSubmitted,
}
);
},
});
}, [finalSource, subscribe]);
const displayedError =
hasBeenInteractedWith || isSubmitted ? error : undefined;
const displayedErrorMessage = (displayedError?.root?.message ??
displayedError?.message) as any;
const renderHelperText = helperText !== false || !!displayedError;
if (isPending) {
// We handle the loading state here instead of using the loading prop
// of ArrayInputBase to avoid wrapping the content below inside Root
return (
<Labeled label={label} className={className}>
<LinearProgress />
</Labeled>
);
}
return (
<Root
fullWidth
margin={margin}
className={clsx(
'ra-input',
`ra-input-${finalSource}`,
ArrayInputClasses.root,
className
)}
error={!!displayedError}
{...sanitizeInputRestProps(rest)}
>
<InputLabel
component="span"
className={ArrayInputClasses.label}
shrink
error={!!displayedError}
>
<FieldTitle
label={label}
source={arraySource}
resource={resourceFromProps}
isRequired={isRequired(validate)}
/>
</InputLabel>
{/*
We must put the ArrayInputBase inside Root so that the FieldTitle above
is not inside the ArrayInputBase's SourceContext,
Otherwise, the ArrayInput label translation key would be wrong
*/}
<ArrayInputBase {...props} defaultValue={defaultValue}>
{children}
</ArrayInputBase>
{renderHelperText ? (
<FormHelperText error={!!displayedError}>
<InputHelperText
// root property is applicable to built-in validation only,
// Resolvers are yet to support useFieldArray root level validation.
// Reference: https://react-hook-form.com/docs/usefieldarray
error={displayedErrorMessage}
helperText={helperText}
/>
</FormHelperText>
) : null}
</Root>
);
};
export interface ArrayInputProps
extends ArrayInputBaseProps,
Omit<
FormControlProps,
| 'children'
| 'defaultValue'
| 'disabled'
| 'readOnly'
| 'onBlur'
| 'onChange'
> {
className?: string;
loading?: React.ReactNode;
isFetching?: boolean;
isLoading?: boolean;
isPending?: boolean;
}
const PREFIX = 'RaArrayInput';
export const ArrayInputClasses = {
root: `${PREFIX}-root`,
label: `${PREFIX}-label`,
};
const Root = styled(FormControl, {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme }) => ({
marginTop: 0,
[`& .${ArrayInputClasses.label}`]: {
position: 'relative',
top: theme.spacing(0.5),
left: theme.spacing(-1.5),
},
[`& .${ArrayInputClasses.root}`]: {
// nested ArrayInput
paddingLeft: theme.spacing(2),
},
}));
declare module '@mui/material/styles' {
interface ComponentNameToClassKey {
RaArrayInput: 'root' | 'label';
}
interface ComponentsPropsList {
RaArrayInput: Partial<ArrayInputProps>;
}
interface Components {
RaArrayInput?: {
defaultProps?: ComponentsPropsList['RaArrayInput'];
styleOverrides?: ComponentsOverrides<
Omit<Theme, 'components'>
>['RaArrayInput'];
};
}
}