-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathMultiSchemaField.tsx
More file actions
250 lines (230 loc) · 9.37 KB
/
MultiSchemaField.tsx
File metadata and controls
250 lines (230 loc) · 9.37 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
import { Component } from 'react';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import omit from 'lodash/omit';
import {
ANY_OF_KEY,
deepEquals,
ERRORS_KEY,
FieldProps,
FormContextType,
getDiscriminatorFieldFromSchema,
getUiOptions,
getWidget,
mergeSchemas,
ONE_OF_KEY,
RJSFSchema,
StrictRJSFSchema,
TranslatableString,
UiSchema,
} from '@rjsf/utils';
/** Type used for the state of the `AnyOfField` component */
type AnyOfFieldState<S extends StrictRJSFSchema = RJSFSchema> = {
/** The currently selected option */
selectedOption: number;
/** The option schemas after retrieving all $refs */
retrievedOptions: S[];
};
/** The `AnyOfField` component is used to render a field in the schema that is an `anyOf`, `allOf` or `oneOf`. It tracks
* the currently selected option and cleans up any irrelevant data in `formData`.
*
* @param props - The `FieldProps` for this template
*/
class AnyOfField<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any> extends Component<
FieldProps<T, S, F>,
AnyOfFieldState<S>
> {
/** Constructs an `AnyOfField` with the given `props` to initialize the initially selected option in state
*
* @param props - The `FieldProps` for this template
*/
constructor(props: FieldProps<T, S, F>) {
super(props);
const {
formData,
options,
registry: { schemaUtils },
} = this.props;
// cache the retrieved options in state in case they have $refs to save doing it later
const retrievedOptions = options.map((opt: S) => schemaUtils.retrieveSchema(opt, formData));
this.state = {
retrievedOptions,
selectedOption: this.getMatchingOption(0, formData, retrievedOptions),
};
}
/** React lifecycle method that is called when the props and/or state for this component is updated. It recomputes the
* currently selected option based on the overall `formData`
*
* @param prevProps - The previous `FieldProps` for this template
* @param prevState - The previous `AnyOfFieldState` for this template
*/
componentDidUpdate(prevProps: Readonly<FieldProps<T, S, F>>, prevState: Readonly<AnyOfFieldState>) {
const { formData, options, idSchema } = this.props;
const { selectedOption } = this.state;
let newState = this.state;
if (!deepEquals(prevProps.options, options)) {
const {
registry: { schemaUtils },
} = this.props;
// re-cache the retrieved options in state in case they have $refs to save doing it later
const retrievedOptions = options.map((opt: S) => schemaUtils.retrieveSchema(opt, formData));
newState = { selectedOption, retrievedOptions };
}
if (!deepEquals(formData, prevProps.formData) && idSchema.$id === prevProps.idSchema.$id) {
const { retrievedOptions } = newState;
const matchingOption = this.getMatchingOption(selectedOption, formData, retrievedOptions);
if (prevState && matchingOption !== selectedOption) {
newState = { selectedOption: matchingOption, retrievedOptions };
}
}
if (newState !== this.state) {
this.setState(newState);
}
}
/** Determines the best matching option for the given `formData` and `options`.
*
* @param formData - The new formData
* @param options - The list of options to choose from
* @return - The index of the `option` that best matches the `formData`
*/
getMatchingOption(selectedOption: number, formData: T | undefined, options: S[]) {
const {
schema,
registry: { schemaUtils },
} = this.props;
const discriminator = getDiscriminatorFieldFromSchema<S>(schema);
const option = schemaUtils.getClosestMatchingOption(formData, options, selectedOption, discriminator);
return option;
}
/** Callback handler to remember what the currently selected option is. In addition to that the `formData` is updated
* to remove properties that are not part of the newly selected option schema, and then the updated data is passed to
* the `onChange` handler.
*
* @param option - The new option value being selected
*/
onOptionChange = (option?: string) => {
const { selectedOption, retrievedOptions } = this.state;
const { formData, onChange, registry } = this.props;
const { schemaUtils } = registry;
const intOption = option !== undefined ? parseInt(option, 10) : -1;
if (intOption === selectedOption) {
return;
}
const newOption = intOption >= 0 ? retrievedOptions[intOption] : undefined;
const oldOption = selectedOption >= 0 ? retrievedOptions[selectedOption] : undefined;
let newFormData = schemaUtils.sanitizeDataForNewSchema(newOption, oldOption, formData);
if (newOption) {
// Call getDefaultFormState to make sure defaults are populated on change. Pass "excludeObjectChildren"
// so that only the root objects themselves are created without adding undefined children properties
newFormData = schemaUtils.getDefaultFormState(newOption, newFormData, false, 'excludeObjectChildren') as T;
}
this.setState({ selectedOption: intOption }, () => {
onChange(newFormData, undefined, this.getFieldId());
});
};
getFieldId() {
const { idSchema, schema } = this.props;
return `${idSchema.$id}${schema.oneOf ? '__oneof_select' : '__anyof_select'}`;
}
/** Renders the `AnyOfField` selector along with a `SchemaField` for the value of the `formData`
*/
render() {
const {
name,
disabled = false,
errorSchema = {},
formContext,
onBlur,
onFocus,
readonly,
registry,
schema,
uiSchema,
} = this.props;
const { widgets, fields, translateString, globalUiOptions, schemaUtils } = registry;
const { SchemaField: _SchemaField } = fields;
const { selectedOption, retrievedOptions } = this.state;
const {
widget = 'select',
placeholder,
autofocus,
autocomplete,
title = schema.title,
...uiOptions
} = getUiOptions<T, S, F>(uiSchema, globalUiOptions);
const Widget = getWidget<T, S, F>({ type: 'number' }, widget, widgets);
const rawErrors = get(errorSchema, ERRORS_KEY, []);
const fieldErrorSchema = omit(errorSchema, [ERRORS_KEY]);
const displayLabel = schemaUtils.getDisplayLabel(schema, uiSchema, globalUiOptions);
const option = selectedOption >= 0 ? retrievedOptions[selectedOption] || null : null;
let optionSchema: S | undefined | null;
if (option) {
// merge top level required field
const { required } = schema;
// Merge in all the non-oneOf/anyOf properties and also skip the special ADDITIONAL_PROPERTY_FLAG property
optionSchema = required ? (mergeSchemas({ required }, option) as S) : option;
}
// First we will check to see if there is an anyOf/oneOf override for the UI schema
let optionsUiSchema: UiSchema<T, S, F>[] = [];
if (ONE_OF_KEY in schema && uiSchema && ONE_OF_KEY in uiSchema) {
if (Array.isArray(uiSchema[ONE_OF_KEY])) {
optionsUiSchema = uiSchema[ONE_OF_KEY];
} else {
console.warn(`uiSchema.oneOf is not an array for "${title || name}"`);
}
} else if (ANY_OF_KEY in schema && uiSchema && ANY_OF_KEY in uiSchema) {
if (Array.isArray(uiSchema[ANY_OF_KEY])) {
optionsUiSchema = uiSchema[ANY_OF_KEY];
} else {
console.warn(`uiSchema.anyOf is not an array for "${title || name}"`);
}
}
// Then we pick the one that matches the selected option index, if one exists otherwise default to the main uiSchema
let optionUiSchema = uiSchema;
if (selectedOption >= 0 && optionsUiSchema.length > selectedOption) {
optionUiSchema = optionsUiSchema[selectedOption];
}
const translateEnum: TranslatableString = title
? TranslatableString.TitleOptionPrefix
: TranslatableString.OptionPrefix;
const translateParams = title ? [title] : [];
const enumOptions = retrievedOptions.map((opt: { title?: string }, index: number) => {
// Also see if there is an override title in the uiSchema for each option, otherwise use the title from the option
const { title: uiTitle = opt.title } = getUiOptions<T, S, F>(optionsUiSchema[index]);
return {
label: uiTitle || translateString(translateEnum, translateParams.concat(String(index + 1))),
value: index,
};
});
return (
<div className='panel panel-default panel-body'>
<div className='form-group'>
<Widget
id={this.getFieldId()}
name={`${name}${schema.oneOf ? '__oneof_select' : '__anyof_select'}`}
schema={{ type: 'number', default: 0 } as S}
onChange={this.onOptionChange}
onBlur={onBlur}
onFocus={onFocus}
disabled={disabled || isEmpty(enumOptions)}
multiple={false}
rawErrors={rawErrors}
errorSchema={fieldErrorSchema}
value={selectedOption >= 0 ? selectedOption : undefined}
options={{ enumOptions, ...uiOptions }}
registry={registry}
formContext={formContext}
placeholder={placeholder}
autocomplete={autocomplete}
autofocus={autofocus}
label={title ?? name}
hideLabel={!displayLabel}
readonly={readonly}
/>
</div>
{optionSchema && <_SchemaField {...this.props} schema={optionSchema} uiSchema={optionUiSchema} />}
</div>
);
}
}
export default AnyOfField;