diff --git a/src/mutations.ts b/src/mutations.ts index 5ffb7a84..f06e13fc 100644 --- a/src/mutations.ts +++ b/src/mutations.ts @@ -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 diff --git a/src/types.ts b/src/types.ts index d97da782..817f9a54 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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 + /** 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 } diff --git a/src/validation/json-logic.ts b/src/validation/json-logic.ts index 3c5c5d30..1530f1f8 100644 --- a/src/validation/json-logic.ts +++ b/src/validation/json-logic.ts @@ -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) { - function processProperty(propertySchema: JsfObjectSchema) { +function cycleThroughPropertiesAndApplyValues(schemaCopy: JsfSchema, computedValues: Record) { + 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) @@ -165,16 +170,43 @@ 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) + } + } } /** @@ -182,7 +214,11 @@ function cycleThroughPropertiesAndApplyValues(schemaCopy: JsfObjectSchema, compu * @param propertySchema - The schema to apply computed values to * @param computedValues - The computed values to apply */ -function cycleThroughAttrsAndApplyValues(propertySchema: JsfObjectSchema, computedValues: Record, computedAttrs: JsfSchema['x-jsf-logic-computedAttrs']) { +function cycleThroughAttrsAndApplyValues(propertySchema: JsfSchema, computedValues: Record, 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 @@ -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) { + function applyNestedComputedValues(propertySchema: JsfSchema, attrName: string, computationName: string | object, computedValues: Record) { + // 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 @@ -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) } diff --git a/test/form.test.ts b/test/form.test.ts index 4240dc3b..dcbcd5aa 100644 --- a/test/form.test.ts +++ b/test/form.test.ts @@ -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', () => { @@ -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() }) }) }) diff --git a/test/validation/json-logic.test.ts b/test/validation/json-logic.test.ts index 69b883e4..ce08dc62 100644 --- a/test/validation/json-logic.test.ts +++ b/test/validation/json-logic.test.ts @@ -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) + }) })