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 11 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
35 changes: 33 additions & 2 deletions packages/core/src/validate.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,14 +263,45 @@ export default function validateFormData(
};
}

function isDict(v) {
return (
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
typeof v === "object" &&
v !== null &&
!(v instanceof Array) &&
!(v instanceof Date)
);
}

/**
* Get a similar schema where ref's are prefixed with "__rjsf_rootSchema"
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
*/
function withIdRefPrefix(schema) {
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
const obj = { ...schema };
for (let key of Object.keys(obj)) {
const value = obj[key];
if (key === "$ref") {
obj[key] = "__rjsf_rootSchema" + value;
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
} else if (isDict(value)) {
obj[key] = withIdRefPrefix(value);
}
}
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) {
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.

return createAjvInstance()
.addSchema(rootSchema, "__rjsf_rootSchema")
.validate(withIdRefPrefix(schema), data);
} else {
return ajv.validate(schema, data);
}
} catch (e) {
return false;
}
NixBiks marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
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