-
-
Notifications
You must be signed in to change notification settings - Fork 401
Expand file tree
/
Copy pathCreate.tsx
More file actions
339 lines (312 loc) · 9.95 KB
/
Copy pathCreate.tsx
File metadata and controls
339 lines (312 loc) · 9.95 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
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
'use client';
import * as React from 'react';
import PropTypes from 'prop-types';
import invariant from 'invariant';
import { useNotifications } from '../useNotifications';
import { CrudContext } from '../shared/context';
import { useLocaleText } from '../AppProvider/LocalizationProvider';
import { CrudForm, CrudFormSlotProps, CrudFormSlots } from './CrudForm';
import { DataSourceCache } from './cache';
import { useCachedDataSource } from './useCachedDataSource';
import { CRUD_DEFAULT_LOCALE_TEXT, type CRUDLocaleText } from './localeText';
import type { DataFieldFormValue, DataModel, DataSource, OmitId } from './types';
import { PageContainer, type PageContainerProps } from '../PageContainer';
import { useActivePage } from '../useActivePage';
export interface CreateProps<D extends DataModel> {
/**
* Server-side [data source](https://mui.com/toolpad/core/react-crud/#data-sources).
*/
dataSource?: DataSource<D> & Required<Pick<DataSource<D>, 'createOne'>>;
/**
* Initial form values.
* @default {}
*/
initialValues?: Partial<OmitId<D>>;
/**
* Callback fired when the form is successfully submitted.
*/
onSubmitSuccess?: (formValues: OmitId<D>) => void | Promise<void>;
/**
* Whether the form fields should reset after the form is submitted.
* @default false
*/
resetOnSubmit?: boolean;
/**
* [Cache](https://mui.com/toolpad/core/react-crud/#data-caching) for the data source.
*/
dataSourceCache?: DataSourceCache | null;
/**
* The title of the page.
*/
pageTitle?: string;
/**
* Locale text for the component.
*/
localeText?: CRUDLocaleText;
/**
* The components used for each slot inside.
* @default {}
*/
slots?: {
form?: CrudFormSlots;
pageContainer?: React.JSXElementConstructor<PageContainerProps>;
};
/**
* The props used for each slot inside.
* @default {}
*/
slotProps?: {
form?: CrudFormSlotProps;
pageContainer?: PageContainerProps;
};
}
/**
*
* Demos:
*
* - [CRUD](https://mui.com/toolpad/core/react-crud/)
*
* API:
*
* - [Create API](https://mui.com/toolpad/core/api/create)
*/
function Create<D extends DataModel>(props: CreateProps<D>) {
const {
initialValues = {} as Partial<OmitId<D>>,
onSubmitSuccess,
resetOnSubmit = false,
dataSourceCache,
pageTitle,
localeText: propsLocaleText,
slots,
slotProps,
} = props;
const globalLocaleText = useLocaleText();
const localeText = { ...CRUD_DEFAULT_LOCALE_TEXT, ...globalLocaleText, ...propsLocaleText };
const crudContext = React.useContext(CrudContext);
const dataSource = (props.dataSource ?? crudContext.dataSource) as NonNullable<
typeof props.dataSource
>;
const notifications = useNotifications();
invariant(dataSource, 'No data source found.');
const cache = React.useMemo(() => {
const manualCache = dataSourceCache ?? crudContext.dataSourceCache;
return typeof manualCache !== 'undefined' ? manualCache : new DataSourceCache();
}, [crudContext.dataSourceCache, dataSourceCache]);
const cachedDataSource = useCachedDataSource<D>(dataSource, cache) as NonNullable<
typeof props.dataSource
>;
const { fields, createOne, validate } = cachedDataSource;
const activePage = useActivePage();
const [formState, setFormState] = React.useState<{
values: Partial<OmitId<D>>;
errors: Partial<Record<keyof D, string>>;
}>(() => ({
values: {
...Object.fromEntries(
fields
.filter(({ field, editable }) => field !== 'id' && editable !== false)
.map(({ field, type }) => [
field,
type === 'boolean' ? (initialValues?.[field] ?? false) : initialValues?.[field],
]),
),
...initialValues,
},
errors: {},
}));
const formValues = formState.values;
const formErrors = formState.errors;
const setFormValues = React.useCallback((newFormValues: Partial<OmitId<D>>) => {
setFormState((previousState) => ({
...previousState,
values: newFormValues,
}));
}, []);
const setFormErrors = React.useCallback((newFormErrors: Partial<Record<keyof D, string>>) => {
setFormState((previousState) => ({
...previousState,
errors: newFormErrors,
}));
}, []);
const handleFormFieldChange = React.useCallback(
(name: keyof D, value: DataFieldFormValue) => {
const validateField = async (values: Partial<OmitId<D>>) => {
if (validate) {
const { issues } = await validate(values);
setFormErrors({
...formErrors,
[name]: issues?.find((issue) => issue.path?.[0] === name)?.message,
});
}
};
const newFormValues = { ...formValues, [name]: value };
setFormValues(newFormValues);
validateField(newFormValues);
},
[formErrors, formValues, setFormErrors, setFormValues, validate],
);
const handleFormReset = React.useCallback(() => {
setFormValues(initialValues);
}, [initialValues, setFormValues]);
const handleFormSubmit = React.useCallback(async () => {
// Check if all required fields are present
const requiredFields = fields.filter(
({ field, editable }) => field !== 'id' && editable !== false,
);
const missingFields = requiredFields.filter(
({ field }) =>
formValues[field] === undefined || formValues[field] === null || formValues[field] === '',
);
if (missingFields.length > 0) {
const missingFieldErrors = Object.fromEntries(
missingFields.map(({ field, headerName }) => [
field as keyof D,
`${headerName || field} is required`,
]),
) as Partial<Record<keyof D, string>>;
setFormErrors(missingFieldErrors);
throw new Error('Required fields are missing');
}
// At this point, we know all required fields are present, so we can safely cast to OmitId<D>
const completeFormValues = formValues as unknown as OmitId<D>;
if (validate) {
const { issues } = await validate(completeFormValues);
if (issues && issues.length > 0) {
setFormErrors(Object.fromEntries(issues.map((issue) => [issue.path?.[0], issue.message])));
throw new Error('Form validation failed');
}
}
setFormErrors({});
try {
await createOne(completeFormValues);
notifications.show(localeText.createSuccessMessage, {
severity: 'success',
autoHideDuration: 3000,
});
if (onSubmitSuccess) {
await onSubmitSuccess(completeFormValues);
}
if (resetOnSubmit) {
handleFormReset();
}
} catch (createError) {
notifications.show(`${localeText.createErrorMessage} ${(createError as Error).message}`, {
severity: 'error',
autoHideDuration: 3000,
});
throw createError;
}
}, [
createOne,
fields,
formValues,
handleFormReset,
localeText.createErrorMessage,
localeText.createSuccessMessage,
notifications,
onSubmitSuccess,
resetOnSubmit,
setFormErrors,
validate,
]);
const PageContainerSlot = slots?.pageContainer ?? PageContainer;
return (
<PageContainerSlot
title={pageTitle}
breadcrumbs={
activePage && pageTitle
? [
...activePage.breadcrumbs,
{
title: pageTitle,
},
]
: undefined
}
{...slotProps?.pageContainer}
>
<CrudForm
dataSource={dataSource}
formState={formState}
onFieldChange={handleFormFieldChange}
onSubmit={handleFormSubmit}
onReset={handleFormReset}
submitButtonLabel={localeText.createLabel}
slots={slots?.form}
slotProps={slotProps?.form}
/>
</PageContainerSlot>
);
}
Create.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the TypeScript types and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* Server-side [data source](https://mui.com/toolpad/core/react-crud/#data-sources).
*/
dataSource: PropTypes.object,
/**
* [Cache](https://mui.com/toolpad/core/react-crud/#data-caching) for the data source.
*/
dataSourceCache: PropTypes.shape({
cache: PropTypes.object.isRequired,
clear: PropTypes.func.isRequired,
get: PropTypes.func.isRequired,
set: PropTypes.func.isRequired,
ttl: PropTypes.number.isRequired,
}),
/**
* Initial form values.
* @default {}
*/
initialValues: PropTypes.object,
/**
* Locale text for the component.
*/
localeText: PropTypes.object,
/**
* Callback fired when the form is successfully submitted.
*/
onSubmitSuccess: PropTypes.func,
/**
* The title of the page.
*/
pageTitle: PropTypes.string,
/**
* Whether the form fields should reset after the form is submitted.
* @default false
*/
resetOnSubmit: PropTypes.bool,
/**
* The props used for each slot inside.
* @default {}
*/
slotProps: PropTypes.shape({
form: PropTypes.shape({
checkbox: PropTypes.object,
datePicker: PropTypes.object,
dateTimePicker: PropTypes.object,
select: PropTypes.object,
textField: PropTypes.object,
}),
pageContainer: PropTypes.object,
}),
/**
* The components used for each slot inside.
* @default {}
*/
slots: PropTypes.shape({
form: PropTypes.shape({
checkbox: PropTypes.elementType,
datePicker: PropTypes.elementType,
dateTimePicker: PropTypes.elementType,
select: PropTypes.elementType,
textField: PropTypes.elementType,
}),
pageContainer: PropTypes.elementType,
}),
} as any;
export { Create };