-
-
Notifications
You must be signed in to change notification settings - Fork 239
/
BaseForm.tsx
297 lines (261 loc) · 7.82 KB
/
BaseForm.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
import clone from 'lodash/clone';
import get from 'lodash/get';
import omit from 'lodash/omit';
import setWith from 'lodash/setWith';
import React, { Component, SyntheticEvent } from 'react';
import { Bridge } from './Bridge';
import { changedKeys } from './changedKeys';
import { context } from './context';
import { randomIds } from './randomIds';
import {
ChangedMap,
Context,
ModelTransformMode,
UnknownObject,
} from './types';
export type BaseFormProps<Model extends UnknownObject> = {
autosave: boolean;
autosaveDelay: number;
disabled?: boolean;
error: unknown;
id?: string;
label: boolean;
model: Model;
modelTransform?: (mode: ModelTransformMode, model: Model) => Model;
noValidate: boolean;
onChange?: (key: string, value: unknown) => void;
onSubmit: (model: Model) => void | Promise<unknown>;
placeholder?: boolean;
readOnly?: boolean;
schema: Bridge;
showInlineError?: boolean;
};
export type BaseFormState<Model extends UnknownObject> = {
changed: boolean;
changedMap: ChangedMap<Model>;
resetCount: number;
submitting: boolean;
submitted: boolean;
};
export class BaseForm<
Model extends UnknownObject,
Props extends BaseFormProps<Model> = BaseFormProps<Model>,
State extends BaseFormState<Model> = BaseFormState<Model>,
> extends Component<Props, State> {
static displayName = 'Form';
static defaultProps = {
autosave: false,
autosaveDelay: 0,
error: null,
label: true,
model: Object.create(null),
noValidate: true,
onSubmit() {},
};
constructor(props: Props) {
super(props);
// @ts-expect-error: State may be bigger, but it'll be covered by the subclasses.
this.state = {
changed: false,
changedMap: Object.create(null),
resetCount: 0,
submitted: false,
submitting: false,
};
this.mounted = false;
this.randomId = randomIds(this.props.id);
this.onReset = this.reset = this.onReset.bind(this);
this.onChange = this.change = this.onChange.bind(this);
this.onSubmit = this.submit = this.onSubmit.bind(this);
// TODO: It shouldn't be here
const getModel = this.getModel.bind(this);
this.getModel = (mode, model = getModel(mode)) =>
mode !== undefined && this.props.modelTransform
? this.props.modelTransform(mode, model)
: model;
}
componentDidMount() {
this.mounted = true;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
componentDidUpdate(prevProps: Props, prevState: State, snapshot: never) {}
componentWillUnmount() {
this.mounted = false;
if (this.delayId) {
clearTimeout(this.delayId);
}
// There are at least 4 places where we'd need to check, whether or not we
// actually perform `setState` after the component gets unmounted. Instead,
// we override it to hide the React warning. Also because React no longer
// will raise it in the newer versions.
// https://github.com/facebook/react/pull/22114
// https://github.com/vazco/uniforms/issues/1152
this.setState = () => {};
}
delayId?: ReturnType<typeof setTimeout> | undefined;
mounted: boolean;
reset: () => void;
change: (key: string, value: unknown) => void;
submit: (event?: SyntheticEvent) => Promise<unknown>;
randomId: () => string;
getContext(): Context<Model> {
return {
changed: this.state.changed,
changedMap: this.state.changedMap,
error: this.getContextError(),
formRef: this,
model: this.getContextModel(),
name: this.getContextName(),
onChange: this.getContextOnChange(),
onSubmit: this.getContextOnSubmit(),
randomId: this.randomId,
schema: this.getContextSchema(),
state: this.getContextState(),
submitted: this.state.submitted,
submitting: this.state.submitting,
validating: false,
};
}
getContextName(): Context<Model>['name'] {
return [];
}
getContextError(): Context<Model>['error'] {
return this.props.error;
}
getContextModel(): Context<Model>['model'] {
return this.getModel('form');
}
getContextState(): Context<Model>['state'] {
return {
disabled: !!this.props.disabled,
label: !!this.props.label,
placeholder: !!this.props.placeholder,
readOnly: !!this.props.readOnly,
showInlineError: !!this.props.showInlineError,
};
}
getContextSchema(): Context<Model>['schema'] {
return this.props.schema;
}
getContextOnChange(): Context<Model>['onChange'] {
// It's bound in constructor.
// eslint-disable-next-line @typescript-eslint/unbound-method
return this.onChange;
}
getContextOnSubmit(): Context<Model>['onSubmit'] {
// It's bound in constructor.
// eslint-disable-next-line @typescript-eslint/unbound-method
return this.onSubmit;
}
getModel(
mode?: ModelTransformMode,
model: Model = this.props.model,
): Context<Model>['model'] {
return model;
}
getNativeFormProps(): {
[key: string]: unknown;
onSubmit: BaseForm<Model, Props, State>['onSubmit'];
key: string;
} {
const props = omit(this.props, [
'autosave',
'autosaveDelay',
'disabled',
'error',
'label',
'model',
'modelTransform',
'onChange',
'onSubmit',
'placeholder',
'readOnly',
'schema',
'showInlineError',
]);
return {
...props,
// It's bound in constructor.
// eslint-disable-next-line @typescript-eslint/unbound-method
onSubmit: this.onSubmit,
key: `reset-${this.state.resetCount}`,
};
}
onChange(key: string, value: unknown) {
// Do not set `changed` before componentDidMount
if (this.mounted) {
const keys = changedKeys(key, value, get(this.getModel(), key));
if (keys.length !== 0) {
this.setState(state =>
// If all are already marked, we can skip the update completely.
state.changed && keys.every(key => !!get(state.changedMap, key))
? null
: {
changed: true,
changedMap: keys.reduce(
(changedMap, key) => setWith(changedMap, key, {}, clone),
clone(state.changedMap),
),
},
);
}
}
if (this.props.onChange) {
this.props.onChange(key, value);
}
// Do not call `onSubmit` before componentDidMount
if (this.mounted && this.props.autosave) {
if (this.delayId) {
clearTimeout(this.delayId);
}
// Delay autosave by `autosaveDelay` milliseconds...
this.delayId = setTimeout(() => {
// ...and wait for all scheduled `setState`s to commit. This is required
// for AutoForm to validate correct model, waiting in `onChange`.
this.setState(
() => null,
() => {
this.onSubmit();
},
);
}, this.props.autosaveDelay);
}
}
__reset(state: State) {
return {
changed: false,
changedMap: Object.create(null),
resetCount: state.resetCount + 1,
submitted: false,
submitting: false,
} as Partial<State>;
}
onReset() {
// @ts-expect-error
// It's bound in constructor.
// eslint-disable-next-line @typescript-eslint/unbound-method
this.setState(this.__reset);
}
onSubmit(event?: SyntheticEvent) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
this.setState(state => (state.submitted ? null : { submitted: true }));
const result = this.props.onSubmit(this.getModel('submit'));
if (!(result instanceof Promise)) {
return Promise.resolve();
}
this.setState({ submitting: true });
return result.finally(() => {
this.setState({ submitting: false });
});
}
render() {
return (
<context.Provider value={this.getContext()}>
<form {...this.getNativeFormProps()} />
</context.Provider>
);
}
}