-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathSaveButton.tsx
More file actions
228 lines (212 loc) · 7.27 KB
/
SaveButton.tsx
File metadata and controls
228 lines (212 loc) · 7.27 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
import * as React from 'react';
import { type MouseEventHandler, useCallback } from 'react';
import type { UseMutationOptions } from '@tanstack/react-query';
import {
type ComponentsOverrides,
styled,
useThemeProps,
} from '@mui/material/styles';
import { Button, type ButtonProps, CircularProgress } from '@mui/material';
import ContentSave from '@mui/icons-material/Save';
import { useFormContext, useFormState } from 'react-hook-form';
import {
type CreateParams,
type RaRecord,
type TransformData,
type UpdateParams,
useSaveContext,
useTranslate,
warning,
setSubmissionErrors,
useRecordFromLocation,
} from 'ra-core';
/**
* Submit button for resource forms (Edit and Create).
*
* @typedef {Object} Props the props you can use (other props are injected by the <Toolbar>)
* @prop {string} className
* @prop {string} label Button label. Defaults to 'ra.action.save', translated.
* @prop {boolean} disabled Disable the button.
* @prop {string} variant Material UI variant for the button. Defaults to 'contained'.
* @prop {ReactNode} icon
* @prop {function} mutationOptions Object of options passed to react-query.
* @prop {function} transform Callback to execute before calling the dataProvider. Receives the data from the form, must return that transformed data. Can be asynchronous (and return a Promise)
* @prop {boolean} alwaysEnable Force enabling the <SaveButton>. If it's not defined, the `<SaveButton>` will be enabled using `react-hook-form`'s `isValidating` state props and form context's `saving` prop (disabled if isValidating or saving, enabled otherwise).
*
* @param {Props} props
*
* @example // with custom success side effect
*
* const MySaveButton = props => {
* const notify = useNotify();
* const redirect = useRedirect();
* const onSuccess = (response) => {
* notify(`Post "${response.data.title}" saved!`);
* redirect('/posts');
* };
* return <SaveButton {...props} mutationOptions={{ onSuccess }} />;
* }
*/
export const SaveButton = <RecordType extends RaRecord = any>(
inProps: SaveButtonProps<RecordType>
) => {
const props = useThemeProps({
props: inProps,
name: PREFIX,
});
const {
color = 'primary',
icon = defaultIcon,
invalid,
label = 'ra.action.save',
onClick,
mutationOptions,
disabled: disabledProp,
type = 'submit',
transform,
variant = 'contained',
alwaysEnable = false,
...rest
} = props;
const translate = useTranslate();
const form = useFormContext();
const saveContext = useSaveContext();
const { dirtyFields, isValidating, isSubmitting } = useFormState();
// useFormState().isDirty might differ from useFormState().dirtyFields (https://github.com/react-hook-form/react-hook-form/issues/4740)
const isDirty = Object.keys(dirtyFields).length > 0;
// Use form isDirty, isValidating and form context saving to enable or disable the save button
// if alwaysEnable is undefined and the form wasn't prefilled
const recordFromLocation = useRecordFromLocation();
const disabled = valueOrDefault(
alwaysEnable === false || alwaysEnable === undefined
? undefined
: !alwaysEnable,
disabledProp ||
(!isDirty && recordFromLocation == null) ||
isValidating ||
isSubmitting
);
warning(
type === 'submit' &&
((mutationOptions &&
(mutationOptions.onSuccess || mutationOptions.onError)) ||
transform),
'Cannot use <SaveButton mutationOptions> props on a button of type "submit". To override the default mutation options on a particular save button, set the <SaveButton type="button"> prop, or set mutationOptions in the main view component (<Create> or <Edit>).'
);
const handleSubmit = useCallback(
async values => {
let errors;
if (saveContext?.save) {
errors = await saveContext.save(values, {
...mutationOptions,
transform,
});
}
if (errors != null) {
setSubmissionErrors(errors, form.setError);
}
},
[form.setError, saveContext, mutationOptions, transform]
);
const handleClick: MouseEventHandler<HTMLButtonElement> = useCallback(
async event => {
if (onClick) {
onClick(event);
}
if (event.defaultPrevented) {
return;
}
if (type === 'button') {
// this button doesn't submit the form, so it doesn't trigger useIsFormInvalid in <FormContent>
// therefore we need to check for errors manually
event.stopPropagation();
await form.handleSubmit(handleSubmit)(event);
}
},
[onClick, type, form, handleSubmit]
);
const displayedLabel = label && translate(label, { _: label });
return (
<StyledButton
variant={variant}
type={type}
color={color}
aria-label={displayedLabel}
disabled={disabled}
onClick={handleClick}
{...rest}
>
{isSubmitting ? (
<CircularProgress
sx={circularProgressStyle}
size={14}
thickness={3}
color="inherit"
/>
) : (
icon
)}
{displayedLabel}
</StyledButton>
);
};
const circularProgressStyle = {
'&.MuiCircularProgress-root': {
marginRight: '10px',
marginLeft: '2px',
},
};
const defaultIcon = <ContentSave />;
interface Props<
RecordType extends RaRecord = any,
MutationOptionsError = unknown,
> {
className?: string;
disabled?: boolean;
icon?: React.ReactNode;
invalid?: boolean;
label?: string;
mutationOptions?: UseMutationOptions<
RecordType,
MutationOptionsError,
CreateParams<RecordType> | UpdateParams<RecordType>
>;
transform?: TransformData;
variant?: string;
}
export type SaveButtonProps<RecordType extends RaRecord = any> =
Props<RecordType> &
ButtonProps & {
alwaysEnable?: boolean;
};
const PREFIX = 'RaSaveButton';
const StyledButton = styled(Button, {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme }) => ({
position: 'relative',
[`& .MuiSvgIcon-root, & .MuiIcon-root, & .MuiCircularProgress-root`]: {
marginRight: theme.spacing(1),
},
[`& .MuiSvgIcon-root, & .MuiIcon-root`]: {
fontSize: 18,
},
}));
const valueOrDefault = (value, defaultValue) =>
typeof value === 'undefined' ? defaultValue : value;
declare module '@mui/material/styles' {
interface ComponentNameToClassKey {
RaSaveButton: 'root';
}
interface ComponentsPropsList {
RaSaveButton: Partial<SaveButtonProps>;
}
interface Components {
RaSaveButton?: {
defaultProps?: ComponentsPropsList['RaSaveButton'];
styleOverrides?: ComponentsOverrides<
Omit<Theme, 'components'>
>['RaSaveButton'];
};
}
}