Skip to content
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
3 changes: 3 additions & 0 deletions src/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ export function calculateFinalSchema({

if (jsonLogicContext?.schema.computedValues) {
applyComputedAttrsToSchema(schemaCopy, jsonLogicContext.schema.computedValues, values)
// If we had computed values applied to the schema,
// we need to re-apply the schema rules to update the fields
applySchemaRules(schemaCopy, values, options, jsonLogicContext)
}

return schemaCopy
Expand Down
11 changes: 6 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,17 @@ export type JsfSchema = JSONSchema & {
// schema (like an if inside another schema), the required property won't be
// present in the type
'required'?: string[]
// Defines the order of the fields in the form.
/** Defines the order of the fields in the form. */
'x-jsf-order'?: string[]
// Defines the presentation of the field in the form.
/** Defines the presentation of the field in the form. */
'x-jsf-presentation'?: JsfPresentation
// Defines the error message of the field in the form.
/** Defines the error message of the field in the form. */
'x-jsf-errorMessage'?: Record<string, string>
/** Defines all JSON Logic rules for the schema (both validations and computed values). */
'x-jsf-logic'?: JsonLogicSchema
// Extra validations to run. References validations in the `x-jsf-logic` root property.
/** Extra validations to run. References validations declared in the `x-jsf-logic` root property. */
'x-jsf-logic-validations'?: string[]
// Extra attributes to add to the schema. References computedValues in the `x-jsf-logic` root property.
/** Extra attributes to add to the schema. References computedValues in the `x-jsf-logic` root property. */
'x-jsf-logic-computedAttrs'?: Record<string, string | object>
}

Expand Down
55 changes: 48 additions & 7 deletions src/validation/json-logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,13 @@ export function applyComputedAttrsToSchema(schema: JsfObjectSchema, computedValu
* @param schemaCopy - The schema to apply computed values to
* @param computedValues - The computed values to apply
*/
function cycleThroughPropertiesAndApplyValues(schemaCopy: JsfObjectSchema, computedValues: Record<string, string>) {
function processProperty(propertySchema: JsfObjectSchema) {
function cycleThroughPropertiesAndApplyValues(schemaCopy: JsfSchema, computedValues: Record<string, string>) {
function processProperty(propertySchema: JsfSchema) {
// Checking that the schema is non-boolean and is has a type property before processing it
if (typeof propertySchema !== 'object') {
return
}

const computedAttrs = propertySchema['x-jsf-logic-computedAttrs']
if (computedAttrs) {
cycleThroughAttrsAndApplyValues(propertySchema, computedValues, computedAttrs)
Expand All @@ -165,24 +170,55 @@ function cycleThroughPropertiesAndApplyValues(schemaCopy: JsfObjectSchema, compu
delete propertySchema['x-jsf-logic-computedAttrs']
}

// If this is a full property schema, we need to cycle through the properties and apply the computed values
// If the schemas has properties, we need to cycle through each one and apply the computed values
// Otherwise, just process the property
if (schemaCopy.properties) {
for (const propertyName in schemaCopy.properties) {
processProperty(schemaCopy.properties[propertyName] as JsfObjectSchema)
processProperty(schemaCopy.properties[propertyName])
}
}
else {
processProperty(schemaCopy)
}

// If the schema has an if statement, we need to cycle through the properties and apply the computed values
if (typeof schemaCopy.if === 'object') {
cycleThroughPropertiesAndApplyValues(schemaCopy.if, computedValues)
}

/* If the schema has an allOf or anyOf property, we need to cycle through each property inside it and
* apply the computed values
*/

if (schemaCopy.allOf && schemaCopy.allOf.length > 0) {
for (const schema of schemaCopy.allOf) {
cycleThroughPropertiesAndApplyValues(schema, computedValues)
}
}

if (schemaCopy.anyOf && schemaCopy.anyOf.length > 0) {
for (const schema of schemaCopy.anyOf) {
cycleThroughPropertiesAndApplyValues(schema, computedValues)
}
}

if (schemaCopy.oneOf && schemaCopy.oneOf.length > 0) {
for (const schema of schemaCopy.oneOf) {
cycleThroughPropertiesAndApplyValues(schema, computedValues)
}
}
}

/**
* Cycles through the attributes of a schema and applies the computed values to it
* @param propertySchema - The schema to apply computed values to
* @param computedValues - The computed values to apply
*/
function cycleThroughAttrsAndApplyValues(propertySchema: JsfObjectSchema, computedValues: Record<string, string>, computedAttrs: JsfSchema['x-jsf-logic-computedAttrs']) {
function cycleThroughAttrsAndApplyValues(propertySchema: JsfSchema, computedValues: Record<string, string>, computedAttrs: JsfSchema['x-jsf-logic-computedAttrs']) {
if (typeof propertySchema !== 'object') {
return
}

/**
* Evaluates a string or a handlebars template, using the computed values mapping, and returns the computed value
* @param message - The string or template to evaluate
Expand All @@ -208,7 +244,12 @@ function cycleThroughAttrsAndApplyValues(propertySchema: JsfObjectSchema, comput
* @param computationName - The name of the computed value to apply
* @param computedValues - The computed values to apply
*/
function applyNestedComputedValues(propertySchema: JsfObjectSchema, attrName: string, computationName: string | object, computedValues: Record<string, string>) {
function applyNestedComputedValues(propertySchema: JsfSchema, attrName: string, computationName: string | object, computedValues: Record<string, string>) {
// Checking that the schema is non-boolean and is has a type property before processing it
if (typeof propertySchema !== 'object') {
return
}

const attributeName = attrName as keyof NonBooleanJsfSchema
if (!propertySchema[attributeName]) {
// Making sure the attribute object is created if it does not exist in the original schema
Expand All @@ -232,7 +273,7 @@ function cycleThroughAttrsAndApplyValues(propertySchema: JsfObjectSchema, comput
if (typeof computationName === 'string') {
propertySchema[attributeName] = evalStringOrTemplate(computationName)
}
else {
else if (typeof propertySchema === 'object') {
// Otherwise, it's a nested object, so we need to apply the computed values to the nested object
applyNestedComputedValues(propertySchema, attributeName, computationName, computedValues)
}
Expand Down
31 changes: 17 additions & 14 deletions test/form.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { JsfObjectSchema } from '../src/types'
import { describe, expect, it, jest } from '@jest/globals'
import { afterEach, describe, expect, it, jest } from '@jest/globals'
import { createHeadlessForm } from '../src'

describe('createHeadlessForm', () => {
Expand All @@ -14,28 +14,31 @@ describe('createHeadlessForm', () => {
name: { type: 'string' },
},
}
afterEach(() => {
jest.clearAllMocks()
})

it('should throw error when customProperties option is provided', () => {
it('should log error when customProperties option is provided', () => {
// spy on console.error
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
createHeadlessForm(basicSchema, { customProperties: {} } as any)
expect(consoleErrorSpy).toHaveBeenCalledWith('[json-schema-form] `customProperties` is a deprecated option and it\'s not supported on json-schema-form v1')
})

it('should not throw error when modifyConfig option is not provided', () => {
expect(() => {
createHeadlessForm(basicSchema, {})
}).not.toThrow()
it('should not log error when modifyConfig option is not provided', () => {
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
createHeadlessForm(basicSchema, {})
expect(consoleErrorSpy).not.toHaveBeenCalled()
})

it('should not throw error when other valid options are provided', () => {
expect(() => {
createHeadlessForm(basicSchema, {
initialValues: { name: 'test' },
legacyOptions: {},
strictInputType: true,
})
}).not.toThrow()
it('should not log error when other valid options are provided', () => {
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
createHeadlessForm(basicSchema, {
initialValues: { name: 'test' },
legacyOptions: {},
strictInputType: true,
})
expect(consoleErrorSpy).not.toHaveBeenCalled()
})
})
})
73 changes: 73 additions & 0 deletions test/validation/json-logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,4 +464,77 @@ describe('applyComputedAttrsToSchema', () => {
const ageProperties = result.properties?.age as JsfObjectSchema
expect(ageProperties?.minimum).toBe(21)
})

it('allows to use computed values inside conditional statements', () => {
const schema: JsfObjectSchema = {
'type': 'object',
'properties': {
pine_trees: {
title: 'Pine trees planted',
type: 'number',
description: 'The number of pine trees you have planted.',
},
oak_trees: {
type: 'number',
title: 'Oak trees planted',
description: 'Enter the number of oak trees you\'ve planted. If there are more pine trees than oak trees, you\'ll need to plant spruce trees as well. But this only counts if less than 10 pines planted.',
},
spruce_trees: {
title: 'Spruce trees planted',
type: 'number',
description: 'The number of spruce trees you have planted (only required if specific conditions are met).',
},
},
'allOf': [
{
if: {
properties: {
oak_trees: {
'x-jsf-logic-computedAttrs': {
minimum: 'pine_value',
},
},
},
},
then: {
required: [
'spruce_trees',
],
},
else: {
properties: {
spruce_trees: false,
},
},
},
],
'required': [
'pine_trees',
'oak_trees',
],
'x-jsf-logic': {
computedValues: {
pine_value: {
rule: {
'+': [
{
var: 'pine_trees',
},
1,
],
},
},
},
},
};

// Mock the jsonLogic.apply to return 10
(jsonLogic.apply as jest.Mock).mockReturnValue(10)

const result = JsonLogicValidation.applyComputedAttrsToSchema(schema, schema['x-jsf-logic']?.computedValues, { pine_trees: 10, oak_trees: 2 })

const conditionValue = result.allOf?.[0].if?.properties?.oak_trees as JsfObjectSchema
expect(conditionValue['x-jsf-logic-computedAttrs']).toBeUndefined()
expect(conditionValue.minimum).toBe(10)
})
})