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 15 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: 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
44 changes: 42 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,54 @@ 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") {
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);
// if rootSchema is given then we add that schema with an id.
// then we rewrite the schema ref's to point to the rootSchema using the id
// this accounts for the case where schema have references to models
// that lives in the rootSchema but not in the schema in question.
if (rootSchema) {
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think rootSchema is always given -- so maybe we can just remove this check.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right - except for some tests, but I've just updated those tests to add the schema as rootSchema as well

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively I could leave the tests as is and have this instead

return ajv
  .addSchema(rootSchema || schema, ROOT_SCHEMA_PREFIX)
  .validate(withIdRefPrefix(schema), data);

So if no rootSchema is provided then the schema itself will be used. Any preferences with one or the other?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to just go ahead and update the tests rather than adding unnecessary functionality to this function.

const result = ajv
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
.addSchema(rootSchema, ROOT_SCHEMA_PREFIX)
.validate(withIdRefPrefix(schema), data);
return result;
} else {
return ajv.validate(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
}
210 changes: 210 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,52 @@ 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");
});

describe("Arrays", () => {
it("should correctly render form inputs for anyOf inside array items", () => {
const schema = {
Expand Down Expand Up @@ -782,6 +867,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 +952,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