-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathSchemaField.tsx
369 lines (344 loc) · 11.9 KB
/
SchemaField.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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import { useCallback, Component } from 'react';
import {
ADDITIONAL_PROPERTY_FLAG,
deepEquals,
descriptionId,
ErrorSchema,
FieldProps,
FieldTemplateProps,
FormContextType,
getSchemaType,
getTemplate,
getUiOptions,
ID_KEY,
IdSchema,
mergeObjects,
Registry,
RJSFSchema,
StrictRJSFSchema,
TranslatableString,
UI_OPTIONS_KEY,
UIOptionsType,
} from '@rjsf/utils';
import isObject from 'lodash/isObject';
import omit from 'lodash/omit';
import Markdown from 'markdown-to-jsx';
/** The map of component type to FieldName */
const COMPONENT_TYPES: { [key: string]: string } = {
array: 'ArrayField',
boolean: 'BooleanField',
integer: 'NumberField',
number: 'NumberField',
object: 'ObjectField',
string: 'StringField',
null: 'NullField',
};
/** Computes and returns which `Field` implementation to return in order to render the field represented by the
* `schema`. The `uiOptions` are used to alter what potential `Field` implementation is actually returned. If no
* appropriate `Field` implementation can be found then a wrapper around `UnsupportedFieldTemplate` is used.
*
* @param schema - The schema from which to obtain the type
* @param uiOptions - The UI Options that may affect the component decision
* @param idSchema - The id that is passed to the `UnsupportedFieldTemplate`
* @param registry - The registry from which fields and templates are obtained
* @returns - The `Field` component that is used to render the actual field data
*/
function getFieldComponent<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(
schema: S,
uiOptions: UIOptionsType<T, S, F>,
idSchema: IdSchema<T>,
registry: Registry<T, S, F>
) {
const field = uiOptions.field;
const { fields, translateString } = registry;
if (typeof field === 'function') {
return field;
}
if (typeof field === 'string' && field in fields) {
return fields[field];
}
const schemaType = getSchemaType(schema);
const type: string = Array.isArray(schemaType) ? schemaType[0] : schemaType || '';
const schemaId = schema.$id;
let componentName = COMPONENT_TYPES[type];
if (schemaId && schemaId in fields) {
componentName = schemaId;
}
// If the type is not defined and the schema uses 'anyOf' or 'oneOf', don't
// render a field and let the MultiSchemaField component handle the form display
if (!componentName && (schema.anyOf || schema.oneOf)) {
return () => null;
}
return componentName in fields
? fields[componentName]
: () => {
const UnsupportedFieldTemplate = getTemplate<'UnsupportedFieldTemplate', T, S, F>(
'UnsupportedFieldTemplate',
registry,
uiOptions
);
return (
<UnsupportedFieldTemplate
schema={schema}
idSchema={idSchema}
reason={translateString(TranslatableString.UnknownFieldType, [String(schema.type)])}
registry={registry}
/>
);
};
}
/** The `SchemaFieldRender` component is the work-horse of react-jsonschema-form, determining what kind of real field to
* render based on the `schema`, `uiSchema` and all the other props. It also deals with rendering the `anyOf` and
* `oneOf` fields.
*
* @param props - The `FieldProps` for this component
*/
function SchemaFieldRender<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(
props: FieldProps<T, S, F>
) {
const {
schema: _schema,
idSchema: _idSchema,
uiSchema,
formData,
errorSchema,
idPrefix,
idSeparator,
name,
onChange,
onKeyChange,
onDropPropertyClick,
required,
registry,
wasPropertyKeyModified = false,
} = props;
const { formContext, schemaUtils, globalUiOptions } = registry;
const uiOptions = getUiOptions<T, S, F>(uiSchema, globalUiOptions);
const FieldTemplate = getTemplate<'FieldTemplate', T, S, F>('FieldTemplate', registry, uiOptions);
const DescriptionFieldTemplate = getTemplate<'DescriptionFieldTemplate', T, S, F>(
'DescriptionFieldTemplate',
registry,
uiOptions
);
const FieldHelpTemplate = getTemplate<'FieldHelpTemplate', T, S, F>('FieldHelpTemplate', registry, uiOptions);
const FieldErrorTemplate = getTemplate<'FieldErrorTemplate', T, S, F>('FieldErrorTemplate', registry, uiOptions);
const schema = schemaUtils.retrieveSchema(_schema, formData);
const fieldId = _idSchema[ID_KEY];
const idSchema = mergeObjects(
schemaUtils.toIdSchema(schema, fieldId, formData, idPrefix, idSeparator),
_idSchema
) as IdSchema<T>;
/** Intermediary `onChange` handler for field components that will inject the `id` of the current field into the
* `onChange` chain if it is not already being provided from a deeper level in the hierarchy
*/
const handleFieldComponentChange = useCallback(
(formData: T | undefined, newErrorSchema?: ErrorSchema<T>, id?: string) => {
const theId = id || fieldId;
return onChange(formData, newErrorSchema, theId);
},
[fieldId, onChange]
);
const FieldComponent = getFieldComponent<T, S, F>(schema, uiOptions, idSchema, registry);
const disabled = Boolean(uiOptions.disabled ?? props.disabled);
const readonly = Boolean(uiOptions.readonly ?? (props.readonly || props.schema.readOnly || schema.readOnly));
const uiSchemaHideError = uiOptions.hideError;
// Set hideError to the value provided in the uiSchema, otherwise stick with the prop to propagate to children
const hideError = uiSchemaHideError === undefined ? props.hideError : Boolean(uiSchemaHideError);
const autofocus = Boolean(uiOptions.autofocus ?? props.autofocus);
if (Object.keys(schema).length === 0) {
return null;
}
const displayLabel = schemaUtils.getDisplayLabel(schema, uiSchema, globalUiOptions);
const { __errors, ...fieldErrorSchema } = errorSchema || {};
// See #439: uiSchema: Don't pass consumed class names or style to child components
const fieldUiSchema = omit(uiSchema, ['ui:classNames', 'classNames', 'ui:style']);
if (UI_OPTIONS_KEY in fieldUiSchema) {
fieldUiSchema[UI_OPTIONS_KEY] = omit(fieldUiSchema[UI_OPTIONS_KEY], ['classNames', 'style']);
}
const field = (
<FieldComponent
{...props}
onChange={handleFieldComponentChange}
idSchema={idSchema}
schema={schema}
uiSchema={fieldUiSchema}
disabled={disabled}
readonly={readonly}
hideError={hideError}
autofocus={autofocus}
errorSchema={fieldErrorSchema}
formContext={formContext}
rawErrors={__errors}
/>
);
const id = idSchema[ID_KEY];
// If this schema has a title defined, but the user has set a new key/label, retain their input.
let label;
if (wasPropertyKeyModified) {
label = name;
} else {
label =
ADDITIONAL_PROPERTY_FLAG in schema
? name
: uiOptions.title || props.schema.title || schema.title || props.title || name;
}
const description = uiOptions.description || props.schema.description || schema.description || '';
const richDescription = uiOptions.enableMarkdownInDescription ? (
<Markdown options={{ disableParsingRawHTML: true }}>{description}</Markdown>
) : (
description
);
const help = uiOptions.help;
const hidden = uiOptions.widget === 'hidden';
const classNames = ['form-group', 'field', `field-${getSchemaType(schema)}`];
if (!hideError && __errors && __errors.length > 0) {
classNames.push('field-error has-error has-danger');
}
if (uiSchema?.classNames) {
if (process.env.NODE_ENV !== 'production') {
console.warn(
"'uiSchema.classNames' is deprecated and may be removed in a major release; Use 'ui:classNames' instead."
);
}
classNames.push(uiSchema.classNames);
}
if (uiOptions.classNames) {
classNames.push(uiOptions.classNames);
}
const helpComponent = (
<FieldHelpTemplate
help={help}
idSchema={idSchema}
schema={schema}
uiSchema={uiSchema}
hasErrors={!hideError && __errors && __errors.length > 0}
registry={registry}
/>
);
/*
* AnyOf/OneOf errors handled by child schema
* unless it can be rendered as select control
*/
const errorsComponent =
hideError || ((schema.anyOf || schema.oneOf) && !schemaUtils.isSelect(schema)) ? undefined : (
<FieldErrorTemplate
errors={__errors}
errorSchema={errorSchema}
idSchema={idSchema}
schema={schema}
uiSchema={uiSchema}
registry={registry}
/>
);
const fieldProps: Omit<FieldTemplateProps<T, S, F>, 'children'> = {
description: (
<DescriptionFieldTemplate
id={descriptionId<T>(id)}
description={richDescription}
schema={schema}
uiSchema={uiSchema}
registry={registry}
/>
),
rawDescription: description,
help: helpComponent,
rawHelp: typeof help === 'string' ? help : undefined,
errors: errorsComponent,
rawErrors: hideError ? undefined : __errors,
id,
label,
hidden,
onChange,
onKeyChange,
onDropPropertyClick,
required,
disabled,
readonly,
hideError,
displayLabel,
classNames: classNames.join(' ').trim(),
style: uiOptions.style,
formContext,
formData,
schema,
uiSchema,
registry,
};
const _AnyOfField = registry.fields.AnyOfField;
const _OneOfField = registry.fields.OneOfField;
const isReplacingAnyOrOneOf = uiSchema?.['ui:field'] && uiSchema?.['ui:fieldReplacesAnyOrOneOf'] === true;
return (
<FieldTemplate {...fieldProps}>
<>
{field}
{/*
If the schema `anyOf` or 'oneOf' can be rendered as a select control, don't
render the selection and let `StringField` component handle
rendering
*/}
{schema.anyOf && !isReplacingAnyOrOneOf && !schemaUtils.isSelect(schema) && (
<_AnyOfField
name={name}
disabled={disabled}
readonly={readonly}
hideError={hideError}
errorSchema={errorSchema}
formData={formData}
formContext={formContext}
idPrefix={idPrefix}
idSchema={idSchema}
idSeparator={idSeparator}
onBlur={props.onBlur}
onChange={props.onChange}
onFocus={props.onFocus}
options={schema.anyOf.map((_schema) =>
schemaUtils.retrieveSchema(isObject(_schema) ? (_schema as S) : ({} as S), formData)
)}
registry={registry}
required={required}
schema={schema}
uiSchema={uiSchema}
/>
)}
{schema.oneOf && !isReplacingAnyOrOneOf && !schemaUtils.isSelect(schema) && (
<_OneOfField
name={name}
disabled={disabled}
readonly={readonly}
hideError={hideError}
errorSchema={errorSchema}
formData={formData}
formContext={formContext}
idPrefix={idPrefix}
idSchema={idSchema}
idSeparator={idSeparator}
onBlur={props.onBlur}
onChange={props.onChange}
onFocus={props.onFocus}
options={schema.oneOf.map((_schema) =>
schemaUtils.retrieveSchema(isObject(_schema) ? (_schema as S) : ({} as S), formData)
)}
registry={registry}
required={required}
schema={schema}
uiSchema={uiSchema}
/>
)}
</>
</FieldTemplate>
);
}
/** The `SchemaField` component determines whether it is necessary to rerender the component based on any props changes
* and if so, calls the `SchemaFieldRender` component with the props.
*/
class SchemaField<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> extends Component<
FieldProps<T, S, F>
> {
shouldComponentUpdate(nextProps: Readonly<FieldProps<T, S, F>>) {
return !deepEquals(this.props, nextProps);
}
render() {
return <SchemaFieldRender<T, S, F> {...this.props} />;
}
}
export default SchemaField;