forked from rjsf-team/react-jsonschema-form
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
1337 lines (1221 loc) · 37.6 KB
/
utils.js
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React from "react";
import * as ReactIs from "react-is";
import fill from "core-js-pure/features/array/fill";
import union from "lodash/union";
import jsonpointer from "jsonpointer";
import fields from "./components/fields";
import widgets from "./components/widgets";
import validateFormData, { isValid } from "./validate";
import _ from "lodash";
// Use the same default object to optimize memoized functions that rely on referential equality
const DEFAULT_ROOT_SCHEMA = {};
const DEFAULT_FORM_DATA = {};
export const ADDITIONAL_PROPERTY_FLAG = "__additional_property";
const widgetMap = {
boolean: {
checkbox: "CheckboxWidget",
radio: "RadioWidget",
select: "SelectWidget",
hidden: "HiddenWidget",
},
string: {
text: "TextWidget",
password: "PasswordWidget",
email: "EmailWidget",
hostname: "TextWidget",
ipv4: "TextWidget",
ipv6: "TextWidget",
uri: "URLWidget",
"data-url": "FileWidget",
radio: "RadioWidget",
select: "SelectWidget",
textarea: "TextareaWidget",
hidden: "HiddenWidget",
date: "DateWidget",
datetime: "DateTimeWidget",
"date-time": "DateTimeWidget",
"alt-date": "AltDateWidget",
"alt-datetime": "AltDateTimeWidget",
color: "ColorWidget",
file: "FileWidget",
},
number: {
text: "TextWidget",
select: "SelectWidget",
updown: "UpDownWidget",
range: "RangeWidget",
radio: "RadioWidget",
hidden: "HiddenWidget",
},
integer: {
text: "TextWidget",
select: "SelectWidget",
updown: "UpDownWidget",
range: "RangeWidget",
radio: "RadioWidget",
hidden: "HiddenWidget",
},
array: {
select: "SelectWidget",
checkboxes: "CheckboxesWidget",
files: "FileWidget",
hidden: "HiddenWidget",
},
};
export function canExpand(schema, uiSchema, formData) {
if (!schema.additionalProperties) {
return false;
}
const { expandable } = getUiOptions(uiSchema);
if (expandable === false) {
return expandable;
}
// if ui:options.expandable was not explicitly set to false, we can add
// another property if we have not exceeded maxProperties yet
if (schema.maxProperties !== undefined) {
return Object.keys(formData).length < schema.maxProperties;
}
return true;
}
export function getDefaultRegistry() {
return {
fields,
widgets,
definitions: {},
rootSchema: {},
formContext: {},
};
}
/* Gets the type of a given schema. */
export function getSchemaType(schema) {
let { type } = schema;
if (!type && schema.const) {
return guessType(schema.const);
}
if (!type && schema.enum) {
return "string";
}
if (!type && (schema.properties || schema.additionalProperties)) {
return "object";
}
if (type instanceof Array && type.length === 2 && type.includes("null")) {
return type.find(type => type !== "null");
}
return type;
}
export function getWidget(schema, widget, registeredWidgets = {}) {
const type = getSchemaType(schema);
function mergeOptions(Widget) {
// cache return value as property of widget for proper react reconciliation
if (!Widget.MergedWidget) {
const defaultOptions =
(Widget.defaultProps && Widget.defaultProps.options) || {};
Widget.MergedWidget = ({ options = {}, ...props }) => (
<Widget options={{ ...defaultOptions, ...options }} {...props} />
);
}
return Widget.MergedWidget;
}
if (
typeof widget === "function" ||
ReactIs.isForwardRef(React.createElement(widget)) ||
ReactIs.isMemo(widget)
) {
return mergeOptions(widget);
}
if (typeof widget !== "string") {
throw new Error(`Unsupported widget definition: ${typeof widget}`);
}
if (registeredWidgets.hasOwnProperty(widget)) {
const registeredWidget = registeredWidgets[widget];
return getWidget(schema, registeredWidget, registeredWidgets);
}
if (!widgetMap.hasOwnProperty(type)) {
throw new Error(`No widget for type "${type}"`);
}
if (widgetMap[type].hasOwnProperty(widget)) {
const registeredWidget = registeredWidgets[widgetMap[type][widget]];
return getWidget(schema, registeredWidget, registeredWidgets);
}
throw new Error(`No widget "${widget}" for type "${type}"`);
}
export function hasWidget(schema, widget, registeredWidgets = {}) {
try {
getWidget(schema, widget, registeredWidgets);
return true;
} catch (e) {
if (
e.message &&
(e.message.startsWith("No widget") ||
e.message.startsWith("Unsupported widget"))
) {
return false;
}
throw e;
}
}
const cacheKeyFn = (...args) => args.map(arg => JSON.stringify(arg)).join("_");
const computeDefaults = _.memoize(_computeDefaults, cacheKeyFn);
function _computeDefaults(
_schema,
parentDefaults,
rootSchema,
rawFormData = DEFAULT_FORM_DATA,
includeUndefinedValues = false
) {
let schema = isObject(_schema) ? _schema : {};
const formData = isObject(rawFormData) ? rawFormData : {};
// Compute the defaults recursively: give highest priority to deepest nodes.
let defaults = parentDefaults;
if (isObject(defaults) && isObject(schema.default)) {
// For object defaults, only override parent defaults that are defined in
// schema.default.
defaults = mergeObjects(defaults, schema.default);
} else if ("default" in schema) {
// Use schema defaults for this node.
defaults = schema.default;
} else if ("const" in schema) {
defaults = schema.const;
} else if ("$ref" in schema) {
// Use referenced schema defaults for this node.
const refSchema = findSchemaDefinition(schema.$ref, rootSchema);
return computeDefaults(
refSchema,
defaults,
rootSchema,
formData,
includeUndefinedValues
);
} else if ("dependencies" in schema) {
const resolvedSchema = resolveDependencies(schema, rootSchema, formData);
return computeDefaults(
resolvedSchema,
defaults,
rootSchema,
formData,
includeUndefinedValues
);
} else if (isFixedItems(schema)) {
defaults = schema.items.map((itemSchema, idx) =>
computeDefaults(
itemSchema,
Array.isArray(parentDefaults) ? parentDefaults[idx] : undefined,
rootSchema,
formData,
includeUndefinedValues
)
);
} else if ("oneOf" in schema) {
schema =
schema.oneOf[getMatchingOption(undefined, schema.oneOf, rootSchema)];
} else if ("anyOf" in schema) {
schema =
schema.anyOf[getMatchingOption(undefined, schema.anyOf, rootSchema)];
}
// Not defaults defined for this node, fallback to generic typed ones.
if (typeof defaults === "undefined") {
defaults = schema.default;
}
switch (getSchemaType(schema)) {
// We need to recur for object schema inner default values.
case "object":
return Object.keys(schema.properties || {}).reduce((acc, key) => {
// Compute the defaults for this node, with the parent defaults we might
// have from a previous run: defaults[key].
let computedDefault = computeDefaults(
schema.properties[key],
(defaults || {})[key],
rootSchema,
(formData || {})[key],
includeUndefinedValues
);
if (includeUndefinedValues || computedDefault !== undefined) {
acc[key] = computedDefault;
}
return acc;
}, {});
case "array":
// Inject defaults into existing array defaults
if (Array.isArray(defaults)) {
defaults = defaults.map((item, idx) => {
return computeDefaults(
schema.items[idx] || schema.additionalItems || {},
item,
rootSchema
);
});
}
// Deeply inject defaults into already existing form data
if (Array.isArray(rawFormData)) {
defaults = rawFormData.map((item, idx) => {
return computeDefaults(
schema.items,
(defaults || {})[idx],
rootSchema,
item
);
});
}
if (schema.minItems) {
if (!isMultiSelect(schema, rootSchema)) {
const defaultsLength = defaults ? defaults.length : 0;
if (schema.minItems > defaultsLength) {
const defaultEntries = defaults || [];
// populate the array with the defaults
const fillerSchema = Array.isArray(schema.items)
? schema.additionalItems
: schema.items;
const fillerEntries = fill(
new Array(schema.minItems - defaultsLength),
computeDefaults(fillerSchema, fillerSchema.defaults, rootSchema)
);
// then fill up the rest with either the item default or empty, up to minItems
return defaultEntries.concat(fillerEntries);
}
} else {
return defaults ? defaults : [];
}
}
}
return defaults;
}
export function getDefaultFormState(
_schema,
formData,
rootSchema = DEFAULT_ROOT_SCHEMA,
includeUndefinedValues = false
) {
if (!isObject(_schema)) {
throw new Error("Invalid schema: " + _schema);
}
const schema = retrieveSchema(_schema, rootSchema, formData);
const defaults = computeDefaults(
schema,
_schema.default,
rootSchema,
formData,
includeUndefinedValues
);
if (typeof formData === "undefined") {
// No form data? Use schema defaults.
return defaults;
}
if (isObject(formData) || Array.isArray(formData)) {
return mergeDefaultsWithFormData(defaults, formData);
}
if (formData === 0 || formData === false || formData === "") {
return formData;
}
return formData || defaults;
}
/**
* When merging defaults and form data, we want to merge in this specific way:
* - objects are deeply merged
* - arrays are merged in such a way that:
* - when the array is set in form data, only array entries set in form data
* are deeply merged; additional entries from the defaults are ignored
* - when the array is not set in form data, the default is copied over
* - scalars are overwritten/set by form data
*/
export function mergeDefaultsWithFormData(defaults, formData) {
if (Array.isArray(formData)) {
if (!Array.isArray(defaults)) {
defaults = [];
}
return formData.map((value, idx) => {
if (defaults[idx]) {
return mergeDefaultsWithFormData(defaults[idx], value);
}
return value;
});
} else if (isObject(formData)) {
const acc = Object.assign({}, defaults); // Prevent mutation of source object.
return Object.keys(formData).reduce((acc, key) => {
acc[key] = mergeDefaultsWithFormData(
defaults ? defaults[key] : {},
formData[key]
);
return acc;
}, acc);
} else {
return formData;
}
}
export function getUiOptions(uiSchema) {
// get all passed options from ui:widget, ui:options, and ui:<optionName>
return Object.keys(uiSchema)
.filter(key => key.indexOf("ui:") === 0)
.reduce((options, key) => {
const value = uiSchema[key];
if (key === "ui:widget" && isObject(value)) {
console.warn(
"Setting options via ui:widget object is deprecated, use ui:options instead"
);
return {
...options,
...(value.options || {}),
widget: value.component,
};
}
if (key === "ui:options" && isObject(value)) {
return { ...options, ...value };
}
return { ...options, [key.substring(3)]: value };
}, {});
}
export function getDisplayLabel(schema, uiSchema, rootSchema) {
const uiOptions = getUiOptions(uiSchema);
let { label: displayLabel = true } = uiOptions;
if (schema.type === "array") {
displayLabel =
isMultiSelect(schema, rootSchema) ||
isFilesArray(schema, uiSchema, rootSchema);
}
if (schema.type === "object") {
displayLabel = false;
}
if (schema.type === "boolean" && !uiSchema["ui:widget"]) {
displayLabel = false;
}
if (uiSchema["ui:field"]) {
displayLabel = false;
}
return displayLabel;
}
export function isObject(thing) {
if (typeof File !== "undefined" && thing instanceof File) {
return false;
}
return typeof thing === "object" && thing !== null && !Array.isArray(thing);
}
export function mergeObjects(obj1, obj2, concatArrays = false) {
// Recursively merge deeply nested objects.
var acc = Object.assign({}, obj1); // Prevent mutation of source object.
return Object.keys(obj2).reduce((acc, key) => {
const left = obj1 ? obj1[key] : {},
right = obj2[key];
if (obj1 && obj1.hasOwnProperty(key) && isObject(right)) {
acc[key] = mergeObjects(left, right, concatArrays);
} else if (concatArrays && Array.isArray(left) && Array.isArray(right)) {
acc[key] = left.concat(right);
} else {
acc[key] = right;
}
return acc;
}, acc);
}
export function asNumber(value) {
if (value === "") {
return undefined;
}
if (value === null) {
return null;
}
if (/\.$/.test(value)) {
// "3." can't really be considered a number even if it parses in js. The
// user is most likely entering a float.
return value;
}
if (/\.0$/.test(value)) {
// we need to return this as a string here, to allow for input like 3.07
return value;
}
const n = Number(value);
const valid = typeof n === "number" && !Number.isNaN(n);
if (/\.\d*0$/.test(value)) {
// It's a number, that's cool - but we need it as a string so it doesn't screw
// with the user when entering dollar amounts or other values (such as those with
// specific precision or number of significant digits)
return value;
}
return valid ? n : value;
}
export function orderProperties(properties, order) {
if (!Array.isArray(order)) {
return properties;
}
const arrayToHash = arr =>
arr.reduce((prev, curr) => {
prev[curr] = true;
return prev;
}, {});
const errorPropList = arr =>
arr.length > 1
? `properties '${arr.join("', '")}'`
: `property '${arr[0]}'`;
const propertyHash = arrayToHash(properties);
const orderFiltered = order.filter(
prop => prop === "*" || propertyHash[prop]
);
const orderHash = arrayToHash(orderFiltered);
const rest = properties.filter(prop => !orderHash[prop]);
const restIndex = orderFiltered.indexOf("*");
if (restIndex === -1) {
if (rest.length) {
throw new Error(
`uiSchema order list does not contain ${errorPropList(rest)}`
);
}
return orderFiltered;
}
if (restIndex !== orderFiltered.lastIndexOf("*")) {
throw new Error("uiSchema order list contains more than one wildcard item");
}
const complete = [...orderFiltered];
complete.splice(restIndex, 1, ...rest);
return complete;
}
/**
* This function checks if the given schema matches a single
* constant value.
*/
export function isConstant(schema) {
return (
(Array.isArray(schema.enum) && schema.enum.length === 1) ||
schema.hasOwnProperty("const")
);
}
export function toConstant(schema) {
if (Array.isArray(schema.enum) && schema.enum.length === 1) {
return schema.enum[0];
} else if (schema.hasOwnProperty("const")) {
return schema.const;
} else {
throw new Error("schema cannot be inferred as a constant");
}
}
export function isSelect(_schema, rootSchema = DEFAULT_ROOT_SCHEMA) {
const schema = retrieveSchema(_schema, rootSchema);
const altSchemas = schema.oneOf || schema.anyOf;
if (Array.isArray(schema.enum)) {
return true;
} else if (Array.isArray(altSchemas)) {
return altSchemas.every(altSchemas => isConstant(altSchemas));
}
return false;
}
export function isMultiSelect(schema, rootSchema = DEFAULT_ROOT_SCHEMA) {
if (!schema.uniqueItems || !schema.items) {
return false;
}
return isSelect(schema.items, rootSchema);
}
export function isFilesArray(
schema,
uiSchema,
rootSchema = DEFAULT_ROOT_SCHEMA
) {
if (uiSchema["ui:widget"] === "files") {
return true;
} else if (schema.items) {
const itemsSchema = retrieveSchema(schema.items, rootSchema);
return itemsSchema.type === "string" && itemsSchema.format === "data-url";
}
return false;
}
export function isFixedItems(schema) {
return (
Array.isArray(schema.items) &&
schema.items.length > 0 &&
schema.items.every(item => isObject(item))
);
}
export function allowAdditionalItems(schema) {
if (schema.additionalItems === true) {
console.warn("additionalItems=true is currently not supported");
}
return isObject(schema.additionalItems);
}
export function optionsList(schema) {
if (schema.enum) {
return schema.enum.map((value, i) => {
const label = (schema.enumNames && schema.enumNames[i]) || String(value);
return { label, value };
});
} else {
const altSchemas = schema.oneOf || schema.anyOf;
return altSchemas.map((schema, i) => {
const value = toConstant(schema);
const label = schema.title || String(value);
return {
schema,
label,
value,
};
});
}
}
export function findSchemaDefinition($ref, rootSchema = DEFAULT_ROOT_SCHEMA) {
const origRef = $ref;
if ($ref.startsWith("#")) {
// Decode URI fragment representation.
$ref = decodeURIComponent($ref.substring(1));
} else {
throw new Error(`Could not find a definition for ${origRef}.`);
}
const current = jsonpointer.get(rootSchema, $ref);
if (current === undefined) {
throw new Error(`Could not find a definition for ${origRef}.`);
}
if (current.hasOwnProperty("$ref")) {
return findSchemaDefinition(current.$ref, rootSchema);
}
return current;
}
// In the case where we have to implicitly create a schema, it is useful to know what type to use
// based on the data we are defining
export const guessType = function guessType(value) {
if (Array.isArray(value)) {
return "array";
} else if (typeof value === "string") {
return "string";
} else if (value == null) {
return "null";
} else if (typeof value === "boolean") {
return "boolean";
} else if (!isNaN(value)) {
return "number";
} else if (typeof value === "object") {
return "object";
}
// Default to string if we can't figure it out
return "string";
};
// This function will create new "properties" items for each key in our formData
export function stubExistingAdditionalProperties(
schema,
rootSchema = DEFAULT_ROOT_SCHEMA,
formData = DEFAULT_FORM_DATA
) {
// Clone the schema so we don't ruin the consumer's original
schema = {
...schema,
properties: { ...schema.properties },
};
Object.keys(formData).forEach(key => {
if (schema.properties.hasOwnProperty(key)) {
// No need to stub, our schema already has the property
return;
}
let additionalProperties;
if (schema.additionalProperties.hasOwnProperty("$ref")) {
additionalProperties = retrieveSchema(
{ $ref: schema.additionalProperties["$ref"] },
rootSchema,
formData
);
} else if (schema.additionalProperties.hasOwnProperty("type")) {
additionalProperties = { ...schema.additionalProperties };
} else {
additionalProperties = { type: guessType(formData[key]) };
}
// The type of our new key should match the additionalProperties value;
schema.properties[key] = additionalProperties;
// Set our additional property flag so we know it was dynamically added
schema.properties[key][ADDITIONAL_PROPERTY_FLAG] = true;
});
return schema;
}
export const resolveSchema = _.memoize(_resolveSchema, cacheKeyFn);
export function _resolveSchema(
schema,
rootSchema = DEFAULT_ROOT_SCHEMA,
formData = DEFAULT_FORM_DATA
) {
if (schema.hasOwnProperty("$ref")) {
return resolveReference(schema, rootSchema, formData);
} else if (schema.hasOwnProperty("dependencies")) {
const resolvedSchema = resolveDependencies(schema, rootSchema, formData);
return retrieveSchema(resolvedSchema, rootSchema, formData);
} else if (schema["allOf"]) {
return {
...schema,
allOf: schema.allOf.map(allOfSubschema =>
retrieveSchema(allOfSubschema, rootSchema, formData)
),
};
} else {
// No $ref, dependencies, or allOf attribute found, so there's nothing to resolve.
// Returning the original schema.
return schema;
}
}
function resolveReference(schema, rootSchema, formData) {
// Retrieve the referenced schema definition.
const $refSchema = findSchemaDefinition(schema.$ref, rootSchema);
// Drop the $ref property of the source schema.
const { $ref, ...localSchema } = schema;
// Update referenced schema definition with local schema properties.
return retrieveSchema(
{ ...$refSchema, ...localSchema },
rootSchema,
formData
);
}
export function _retrieveSchema(
schema,
rootSchema = DEFAULT_ROOT_SCHEMA,
formData = DEFAULT_FORM_DATA
) {
if (!isObject(schema)) {
return DEFAULT_ROOT_SCHEMA;
}
let resolvedSchema = resolveSchema(schema, rootSchema, formData);
while ("if" in resolvedSchema) {
// Note that if and else are key words in javascript so extract to variable names which are allowed
var {
if: expression,
then,
else: otherwise,
...resolvedSchemaLessConditional
} = resolvedSchema;
var conditionalSchema = isValid(expression, formData, rootSchema)
? then
: otherwise;
if (conditionalSchema) {
conditionalSchema = resolveSchema(
conditionalSchema,
rootSchema,
formData
);
}
resolvedSchema = mergeSchemas(
resolvedSchemaLessConditional,
conditionalSchema || {}
);
}
let allOf = resolvedSchema.allOf;
if (allOf) {
for (var i = 0; i < allOf.length; i++) {
let allOfSchema = allOf[i];
// if we see an if in our all of schema then evaluate the if schema and select the then / else, not sure if we should still merge without our if then else
if ("if" in allOfSchema) {
allOfSchema = isValid(allOfSchema.if, formData, rootSchema)
? allOfSchema.then
: allOfSchema.else;
}
if (allOfSchema) {
allOfSchema = resolveSchema(allOfSchema, rootSchema, formData); // resolve references etc.
resolvedSchema = {
...mergeSchemas(resolvedSchema, allOfSchema),
allOf: undefined,
};
}
}
}
const hasAdditionalProperties =
resolvedSchema.hasOwnProperty("additionalProperties") &&
resolvedSchema.additionalProperties !== false;
if (hasAdditionalProperties) {
resolvedSchema = stubExistingAdditionalProperties(
resolvedSchema,
rootSchema,
formData
);
}
return resolvedSchema;
}
export const retrieveSchema = _.memoize(_retrieveSchema, cacheKeyFn);
function resolveDependencies(schema, rootSchema, formData) {
// Drop the dependencies from the source schema.
let { dependencies = {}, ...resolvedSchema } = schema;
if ("oneOf" in resolvedSchema) {
resolvedSchema =
resolvedSchema.oneOf[
getMatchingOption(formData, resolvedSchema.oneOf, rootSchema)
];
} else if ("anyOf" in resolvedSchema) {
resolvedSchema =
resolvedSchema.anyOf[
getMatchingOption(formData, resolvedSchema.anyOf, rootSchema)
];
}
return processDependencies(
dependencies,
resolvedSchema,
rootSchema,
formData
);
}
function processDependencies(
dependencies,
resolvedSchema,
rootSchema,
formData
) {
// Process dependencies updating the local schema properties as appropriate.
for (const dependencyKey in dependencies) {
// Skip this dependency if its trigger property is not present.
if (formData[dependencyKey] === undefined) {
continue;
}
// Skip this dependency if it is not included in the schema (such as when dependencyKey is itself a hidden dependency.)
if (
resolvedSchema.properties &&
!(dependencyKey in resolvedSchema.properties)
) {
continue;
}
const {
[dependencyKey]: dependencyValue,
...remainingDependencies
} = dependencies;
if (Array.isArray(dependencyValue)) {
resolvedSchema = withDependentProperties(resolvedSchema, dependencyValue);
} else if (isObject(dependencyValue)) {
resolvedSchema = withDependentSchema(
resolvedSchema,
rootSchema,
formData,
dependencyKey,
dependencyValue
);
}
return processDependencies(
remainingDependencies,
resolvedSchema,
rootSchema,
formData
);
}
return resolvedSchema;
}
function withDependentProperties(schema, additionallyRequired) {
if (!additionallyRequired) {
return schema;
}
const required = Array.isArray(schema.required)
? Array.from(new Set([...schema.required, ...additionallyRequired]))
: additionallyRequired;
return { ...schema, required: required };
}
function withDependentSchema(
schema,
rootSchema,
formData,
dependencyKey,
dependencyValue
) {
let { oneOf, ...dependentSchema } = retrieveSchema(
dependencyValue,
rootSchema,
formData
);
schema = mergeSchemas(schema, dependentSchema);
// Since it does not contain oneOf, we return the original schema.
if (oneOf === undefined) {
return schema;
} else if (!Array.isArray(oneOf)) {
throw new Error(`invalid: it is some ${typeof oneOf} instead of an array`);
}
// Resolve $refs inside oneOf.
const resolvedOneOf = oneOf.map(subschema =>
subschema.hasOwnProperty("$ref")
? resolveReference(subschema, rootSchema, formData)
: subschema
);
return withExactlyOneSubschema(
schema,
rootSchema,
formData,
dependencyKey,
resolvedOneOf
);
}
function withExactlyOneSubschema(
schema,
rootSchema,
formData,
dependencyKey,
oneOf
) {
const validSubschemas = oneOf.filter(subschema => {
if (!subschema.properties) {
return false;
}
const { [dependencyKey]: conditionPropertySchema } = subschema.properties;
if (conditionPropertySchema) {
const conditionSchema = {
type: "object",
properties: {
[dependencyKey]: conditionPropertySchema,
},
};
const { errors } = validateFormData(formData, conditionSchema);
return errors.length === 0;
}
});
if (validSubschemas.length !== 1) {
console.warn(
"ignoring oneOf in dependencies because there isn't exactly one subschema that is valid"
);
return schema;
}
const subschema = validSubschemas[0];
const {
[dependencyKey]: conditionPropertySchema,
...dependentSubschema
} = subschema.properties;
const dependentSchema = { ...subschema, properties: dependentSubschema };
return mergeSchemas(
schema,
retrieveSchema(dependentSchema, rootSchema, formData)
);
}
// Recursively merge deeply nested schemas.
// The difference between mergeSchemas and mergeObjects
// is that mergeSchemas only concats arrays for
// values under the "required" keyword, and when it does,
// it doesn't include duplicate values.
export function mergeSchemas(obj1, obj2) {
var acc = Object.assign({}, obj1); // Prevent mutation of source object.
return Object.keys(obj2).reduce((acc, key) => {
const left = obj1 ? obj1[key] : {},
right = obj2[key];
if (obj1 && obj1.hasOwnProperty(key) && isObject(right)) {
acc[key] = mergeSchemas(left, right);
} else if (
obj1 &&
obj2 &&
(getSchemaType(obj1) === "object" || getSchemaType(obj2) === "object") &&
key === "required" &&
Array.isArray(left) &&
Array.isArray(right)
) {
// Don't include duplicate values when merging
// "required" fields.
acc[key] = union(left, right);
} else {
acc[key] = right;
}
return acc;
}, acc);
}
function isArguments(object) {
return Object.prototype.toString.call(object) === "[object Arguments]";
}
export function deepEquals(a, b, ca = [], cb = []) {
// Partially extracted from node-deeper and adapted to exclude comparison
// checks for functions.
// https://github.com/othiym23/node-deeper
if (a === b) {
return true;
} else if (typeof a === "function" || typeof b === "function") {
// Assume all functions are equivalent
// see https://github.com/rjsf-team/react-jsonschema-form/issues/255
return true;
} else if (typeof a !== "object" || typeof b !== "object") {
return false;
} else if (a === null || b === null) {
return false;
} else if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
} else if (a instanceof RegExp && b instanceof RegExp) {
return (
a.source === b.source &&
a.global === b.global &&
a.multiline === b.multiline &&
a.lastIndex === b.lastIndex &&
a.ignoreCase === b.ignoreCase
);
} else if (isArguments(a) || isArguments(b)) {
if (!(isArguments(a) && isArguments(b))) {
return false;