/
FieldFeedback.tsx
253 lines (214 loc) · 8.36 KB
/
FieldFeedback.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
import * as React from 'react';
import { instanceOf } from 'prop-types';
import { Async, AsyncChildContext } from './Async';
import { Field } from './Field';
import { FieldFeedbacks, FieldFeedbacksChildContext } from './FieldFeedbacks';
import { FieldFeedbackType } from './FieldFeedbackType';
import { FieldFeedbackValidation } from './FieldFeedbackValidation';
import { FieldFeedbackWhenValid } from './FieldFeedbackWhenValid';
import { FormWithConstraints, FormWithConstraintsChildContext } from './FormWithConstraints';
import { InputElement } from './InputElement';
import { Nullable } from './Nullable';
type WhenString =
| 'valid'
| '*'
| 'badInput' // input type="number"
| 'patternMismatch' // pattern attribute
| 'rangeOverflow' // max attribute
| 'rangeUnderflow' // min attribute
| 'stepMismatch' // step attribute
| 'tooLong' // maxlength attribute
| 'tooShort' // minlength attribute
| 'typeMismatch' // input type="email" or input type="url"
| 'valueMissing'; // required attribute
type WhenFn = (value: string) => boolean;
type When = WhenString | WhenFn;
export interface FieldFeedbackClasses {
classes?: {
// FIXME Should not be declared "?" thanks to defaultProps?
[index: string]: string | undefined;
error?: string;
warning?: string;
info?: string;
whenValid?: string;
};
}
export interface FieldFeedbackBaseProps {
when?: When; // FIXME Should not be declared "?" thanks to defaultProps?
error?: boolean;
warning?: boolean;
info?: boolean;
}
export interface FieldFeedbackProps
extends FieldFeedbackBaseProps,
FieldFeedbackClasses,
React.HTMLAttributes<HTMLSpanElement> {}
interface FieldFeedbackState {
validation: FieldFeedbackValidation;
// Copy of input.validationMessage
// https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement
// https://www.w3.org/TR/html51/sec-forms.html#the-constraint-validation-api
validationMessage: string;
}
// Why Nullable? https://github.com/DefinitelyTyped/DefinitelyTyped/pull/27973
export type FieldFeedbackContext = FormWithConstraintsChildContext &
FieldFeedbacksChildContext &
Partial<Nullable<AsyncChildContext>>;
export class FieldFeedback<
Props extends FieldFeedbackBaseProps = FieldFeedbackProps
> extends React.Component<Props, FieldFeedbackState> {
static defaultProps: FieldFeedbackProps = {
when: () => true,
classes: {
error: 'error',
warning: 'warning',
info: 'info',
whenValid: 'when-valid'
}
};
static contextTypes: React.ValidationMap<FieldFeedbackContext> = {
form: instanceOf(FormWithConstraints).isRequired,
fieldFeedbacks: instanceOf(FieldFeedbacks).isRequired,
async: instanceOf(Async)
};
context!: FieldFeedbackContext;
// Tested: there is no conflict with React key prop (https://reactjs.org/docs/lists-and-keys.html)
readonly key: string; // '0.1', '1.0', '3.5'...
constructor(props: Props, context: FieldFeedbackContext) {
super(props, context);
this.key = context.fieldFeedbacks.addFieldFeedback();
const { error, warning, info, when } = props;
let type = FieldFeedbackType.Error; // Default is error
if (when === 'valid') type = FieldFeedbackType.WhenValid;
else if (warning) type = FieldFeedbackType.Warning;
else if (info) type = FieldFeedbackType.Info;
// Special case for when="valid"
if (type === FieldFeedbackType.WhenValid && (error ?? warning ?? info)) {
throw new Error(
'Cannot have an attribute (error, warning...) with FieldFeedback when="valid"'
);
}
// eslint-disable-next-line react/state-in-constructor
this.state = {
validation: {
key: this.key,
type,
show: undefined // undefined means the FieldFeedback was not checked
},
validationMessage: ''
};
}
componentDidMount() {
const { form, fieldFeedbacks, async } = this.context;
if (async) async.addValidateFieldEventListener(this.validate);
else fieldFeedbacks.addValidateFieldEventListener(this.validate);
form.addFieldDidResetEventListener(this.fieldDidReset);
}
componentWillUnmount() {
const { form, fieldFeedbacks, async } = this.context;
if (async) async.removeValidateFieldEventListener(this.validate);
else fieldFeedbacks.removeValidateFieldEventListener(this.validate);
form.removeFieldDidResetEventListener(this.fieldDidReset);
}
validate = (input: InputElement) => {
const { when } = this.props;
const { form, fieldFeedbacks } = this.context;
const field = form.fieldsStore.getField(input.name)!;
// Copy state so we don't modify it directly (use of setState() instead)
// eslint-disable-next-line react/no-access-state-in-setstate, react/destructuring-assignment
const validation = { ...this.state.validation };
if (
(fieldFeedbacks.props.stop === 'first' && field.hasFeedbacks(fieldFeedbacks.key)) ||
(fieldFeedbacks.props.stop === 'first-error' && field.hasErrors(fieldFeedbacks.key)) ||
(fieldFeedbacks.props.stop === 'first-warning' && field.hasWarnings(fieldFeedbacks.key)) ||
(fieldFeedbacks.props.stop === 'first-info' && field.hasInfos(fieldFeedbacks.key))
) {
// Do nothing
validation.show = undefined; // undefined means the FieldFeedback was not checked
} else {
validation.show = false;
if (typeof when === 'function') {
validation.show = when(input.value);
} else if (typeof when === 'string') {
if (when === 'valid') {
// undefined => special case for when="valid": always displayed, then FieldFeedbackWhenValid decides what to do
validation.show = undefined;
} else {
const { validity } = input;
if (!validity.valid) {
if (when === '*') {
validation.show = true;
} else if (
(validity.badInput && when === 'badInput') ||
(validity.patternMismatch && when === 'patternMismatch') ||
(validity.rangeOverflow && when === 'rangeOverflow') ||
(validity.rangeUnderflow && when === 'rangeUnderflow') ||
(validity.stepMismatch && when === 'stepMismatch') ||
(validity.tooLong && when === 'tooLong') ||
(validity.tooShort && when === 'tooShort') ||
(validity.typeMismatch && when === 'typeMismatch') ||
(validity.valueMissing && when === 'valueMissing')
) {
validation.show = true;
}
}
}
} else {
throw new TypeError(`Invalid FieldFeedback 'when' type: ${typeof when}`);
}
}
field.addOrReplaceValidation(validation);
this.setState({
validation,
validationMessage: input.validationMessage
});
return validation;
};
fieldDidReset = (field: Field) => {
// Ignore the event if it's not for us
// eslint-disable-next-line react/destructuring-assignment
if (field.name === this.context.fieldFeedbacks.fieldName) {
this.setState(prevState => ({
validation: { ...prevState.validation, show: undefined },
validationMessage: ''
}));
}
};
// Don't forget to update native/FieldFeedback.render()
render() {
const { when, error, warning, info, className, classes, style, children, ...otherProps } = this
.props as unknown as FieldFeedbackProps;
const { validation, validationMessage } = this.state;
const fieldFeedbackClassName = classes![validation.type]!;
const classNames =
className !== undefined ? `${className} ${fieldFeedbackClassName}` : fieldFeedbackClassName;
// Special case for when="valid": always displayed, then FieldFeedbackWhenValid decides what to do
if (validation.type === FieldFeedbackType.WhenValid) {
return (
<FieldFeedbackWhenValid
data-feedback={this.key}
style={style}
className={classNames}
{...otherProps}
>
{children}
</FieldFeedbackWhenValid>
);
}
if (validation.show) {
const feedback = children !== undefined ? children : validationMessage;
// <span style="display: block"> instead of <div> so FieldFeedback can be wrapped inside a <p>
return (
<span
data-feedback={this.key}
className={classNames}
style={{ display: 'block', ...style }}
{...otherProps}
>
{feedback}
</span>
);
}
return null;
}
}