Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix default values and matching schemas when oneOf / anyOf subschemas contain references #2272

Merged
merged 21 commits into from
Apr 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/3.x upgrade guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,11 @@ For a slightly more elaborate setup, [@babel/preset-env](https://babeljs.io/docs
From `@babel/preset-env`'s docs

> We leverage [`browserslist`, `compat-table`, and `electron-to-chromium`] to maintain mappings of which version of our supported target environments gained support of a JavaScript syntax or browser feature, as well as a mapping of those syntaxes and features to Babel transform plugins and core-js polyfills.

### Dereferenced schemas for `anyOf`/`allOf` options

`options` prop for `MultiSchemaField` has been changed slightly.

Before an option could include a `$ref`.

Now any option with a reference will be resolved/dereferenced when given as props for `MultiSchemaField`.
8 changes: 6 additions & 2 deletions packages/core/src/components/fields/SchemaField.js
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,9 @@ function SchemaFieldRender(props) {
onBlur={props.onBlur}
onChange={props.onChange}
onFocus={props.onFocus}
options={schema.anyOf}
options={schema.anyOf.map(_schema =>
epicfaace marked this conversation as resolved.
Show resolved Hide resolved
retrieveSchema(_schema, rootSchema, formData)
epicfaace marked this conversation as resolved.
Show resolved Hide resolved
)}
baseType={schema.type}
registry={registry}
schema={schema}
Expand All @@ -380,7 +382,9 @@ function SchemaFieldRender(props) {
onBlur={props.onBlur}
onChange={props.onChange}
onFocus={props.onFocus}
options={schema.oneOf}
options={schema.oneOf.map(_schema =>
retrieveSchema(_schema, rootSchema, formData)
)}
baseType={schema.type}
registry={registry}
schema={schema}
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -1225,10 +1225,10 @@ export function getMatchingOption(formData, options, rootSchema) {
// been filled in yet, which will mean that the schema is not valid
delete augmentedSchema.required;

if (isValid(augmentedSchema, formData)) {
if (isValid(augmentedSchema, formData, rootSchema)) {
return i;
}
} else if (isValid(options[i], formData)) {
} else if (isValid(option, formData, rootSchema)) {
return i;
}
}
Expand Down
43 changes: 41 additions & 2 deletions packages/core/src/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { deepEquals, getDefaultFormState } from "./utils";

let formerCustomFormats = null;
let formerMetaSchema = null;
const ROOT_SCHEMA_PREFIX = "__rjsf_rootSchema";
epicfaace marked this conversation as resolved.
Show resolved Hide resolved
NixBiks marked this conversation as resolved.
Show resolved Hide resolved

import { isObject, mergeObjects } from "./utils";

Expand Down Expand Up @@ -263,15 +264,53 @@ export default function validateFormData(
};
}

/**
* Recursively prefixes all $ref's in a schema with `ROOT_SCHEMA_PREFIX`
* This is used in isValid to make references to the rootSchema
*/
export function withIdRefPrefix(schemaNode) {
let obj = schemaNode;
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
if (schemaNode.constructor === Object) {
obj = { ...schemaNode };
for (const key in obj) {
const value = obj[key];
if (
key === "$ref" &&
typeof value === "string" &&
value.startsWith("#")
) {
obj[key] = ROOT_SCHEMA_PREFIX + value;
} else {
obj[key] = withIdRefPrefix(value);
}
}
} else if (Array.isArray(schemaNode)) {
obj = [...schemaNode];
for (var i = 0; i < obj.length; i++) {
obj[i] = withIdRefPrefix(obj[i]);
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
}
}
return obj;
}

/**
* Validates data against a schema, returning true if the data is valid, or
* false otherwise. If the schema is invalid, then this function will return
* false.
*/
export function isValid(schema, data) {
export function isValid(schema, data, rootSchema) {
try {
return ajv.validate(schema, data);
// add the rootSchema ROOT_SCHEMA_PREFIX as id.
// then rewrite the schema ref's to point to the rootSchema
// this accounts for the case where schema have references to models
// that lives in the rootSchema but not in the schema in question.
return ajv
.addSchema(rootSchema, ROOT_SCHEMA_PREFIX)
.validate(withIdRefPrefix(schema), data);
} catch (e) {
return false;
} finally {
// make sure we remove the rootSchema from the global ajv instance
ajv.removeSchema(ROOT_SCHEMA_PREFIX);
}
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
}
256 changes: 256 additions & 0 deletions packages/core/test/anyOf_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,45 @@ describe("anyOf", () => {
});
});

it("should assign a default value and set defaults on option change when using references", () => {
const { node, onChange } = createFormComponent({
schema: {
anyOf: [
{
type: "object",
properties: {
foo: { type: "string", default: "defaultfoo" },
},
},
{
$ref: "#/definitions/bar",
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
},
],
definitions: {
bar: {
type: "object",
properties: {
foo: { type: "string", default: "defaultbar" },
},
},
},
},
});
sinon.assert.calledWithMatch(onChange.lastCall, {
formData: { foo: "defaultfoo" },
});

const $select = node.querySelector("select");

Simulate.change($select, {
target: { value: $select.options[1].value },
});

sinon.assert.calledWithMatch(onChange.lastCall, {
formData: { foo: "defaultbar" },
});
});

it("should assign a default value and set defaults on option change with 'type': 'object' missing", () => {
const { node, onChange } = createFormComponent({
schema: {
Expand Down Expand Up @@ -639,6 +678,98 @@ describe("anyOf", () => {
});
});

it("should use title from refs schema before using fallback generated value as title", () => {
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
const schema = {
definitions: {
address: {
title: "Address",
type: "object",
properties: {
street: {
title: "Street",
type: "string",
},
},
},
person: {
title: "Person",
type: "object",
properties: {
name: {
title: "Name",
type: "string",
},
},
},
nested: {
$ref: "#/definitions/person",
},
},
anyOf: [
{
$ref: "#/definitions/address",
},
{
$ref: "#/definitions/nested",
},
],
};

const { node } = createFormComponent({
schema,
});

let options = node.querySelectorAll("option");
expect(options[0].firstChild.nodeValue).eql("Address");
expect(options[1].firstChild.nodeValue).eql("Person");
});

it("should collect schema from $ref even when ref is within properties", () => {
const schema = {
properties: {
address: {
title: "Address",
type: "object",
properties: {
street: {
title: "Street",
type: "string",
},
},
},
person: {
title: "Person",
type: "object",
properties: {
name: {
title: "Name",
type: "string",
},
},
},
nested: {
$ref: "#/properties/person",
},
},
anyOf: [
{
$ref: "#/properties/address",
},
{
$ref: "#/properties/nested",
},
],
};

const { node } = createFormComponent({
schema,
});

let options = node.querySelectorAll("option");
expect(options[0].firstChild.nodeValue).eql("Address");
expect(options[1].firstChild.nodeValue).eql("Person");
});

describe("Arrays", () => {
it("should correctly render form inputs for anyOf inside array items", () => {
const schema = {
Expand Down Expand Up @@ -782,6 +913,46 @@ describe("anyOf", () => {
expect(strInputs[1].value).eql("bar");
});

it("should correctly set the label of the options", () => {
const schema = {
type: "object",
anyOf: [
{
title: "Foo",
properties: {
foo: { type: "string" },
},
},
{
properties: {
bar: { type: "string" },
},
},
{
$ref: "#/definitions/baz",
},
],
definitions: {
baz: {
title: "Baz",
properties: {
baz: { type: "string" },
},
},
},
};

const { node } = createFormComponent({
schema,
});

const $select = node.querySelector("select");

expect($select.options[0].text).eql("Foo");
expect($select.options[1].text).eql("Option 2");
expect($select.options[2].text).eql("Baz");
});

it("should correctly render mixed types for anyOf inside array items", () => {
const schema = {
type: "object",
Expand Down Expand Up @@ -827,5 +998,90 @@ describe("anyOf", () => {
expect(node.querySelectorAll("input#root_foo")).to.have.length.of(1);
expect(node.querySelectorAll("input#root_bar")).to.have.length.of(1);
});

it("should correctly infer the selected option based on value", () => {
const schema = {
$ref: "#/defs/any",
defs: {
chain: {
type: "object",
title: "Chain",
properties: {
id: {
enum: ["chain"],
},
components: {
type: "array",
items: { $ref: "#/defs/any" },
},
},
},

map: {
type: "object",
title: "Map",
properties: {
id: { enum: ["map"] },
fn: { $ref: "#/defs/any" },
},
},

to_absolute: {
type: "object",
title: "To Absolute",
properties: {
id: { enum: ["to_absolute"] },
base_url: { type: "string" },
},
},

transform: {
type: "object",
title: "Transform",
properties: {
id: { enum: ["transform"] },
property_key: { type: "string" },
transformer: { $ref: "#/defs/any" },
},
},
any: {
anyOf: [
{ $ref: "#/defs/chain" },
{ $ref: "#/defs/map" },
{ $ref: "#/defs/to_absolute" },
{ $ref: "#/defs/transform" },
],
},
},
};

const { node } = createFormComponent({
schema,
formData: {
id: "chain",
components: [
{
id: "map",
fn: {
id: "transform",
property_key: "uri",
transformer: {
id: "to_absolute",
base_url: "http://localhost",
},
},
},
],
},
});

const idSelects = node.querySelectorAll("select#root_id");

expect(idSelects).to.have.length(4);
expect(idSelects[0].value).eql("chain");
expect(idSelects[1].value).eql("map");
expect(idSelects[2].value).eql("transform");
expect(idSelects[3].value).eql("to_absolute");
});
});
});
Loading