From 51b63f548ec55ec09c93f66c72596dcdf4480b4d Mon Sep 17 00:00:00 2001 From: Zao Soula Date: Mon, 19 Feb 2024 16:42:08 +0100 Subject: [PATCH] feat: add hasOption tester Adds the new "hasOption" util to check for the existence of an option. --- packages/core/src/testers/testers.ts | 18 ++++++++++++++++++ packages/core/test/testers.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/packages/core/src/testers/testers.ts b/packages/core/src/testers/testers.ts index c14048e335..415762ab40 100644 --- a/packages/core/src/testers/testers.ts +++ b/packages/core/src/testers/testers.ts @@ -31,6 +31,7 @@ import isArray from 'lodash/isArray'; import reduce from 'lodash/reduce'; import toPairs from 'lodash/toPairs'; import includes from 'lodash/includes'; +import isUndefined from 'lodash/isUndefined'; import type { Categorization, ControlElement, @@ -215,6 +216,23 @@ export const optionIs = return !isEmpty(options) && options[optionName] === optionValue; }; +/** + * Checks whether the given UI schema has an option with the given + * name. If no options property is set, returns false. + * + * @param {string} optionName the name of the option to check + */ +export const hasOption = + (optionName: string): Tester => + (uischema: UISchemaElement): boolean => { + if (isEmpty(uischema)) { + return false; + } + + const options = uischema.options; + return !isEmpty(options) && !isUndefined(options[optionName]); + }; + /** * Only applicable for Controls. * diff --git a/packages/core/test/testers.test.ts b/packages/core/test/testers.test.ts index fcbf8cf9e1..346fb9d006 100644 --- a/packages/core/test/testers.test.ts +++ b/packages/core/test/testers.test.ts @@ -54,6 +54,7 @@ import { JsonSchema, LabelElement, UISchemaElement, + hasOption, } from '../src'; const test = anyTest as TestInterface<{ uischema: ControlElement }>; @@ -183,6 +184,30 @@ test('optionIs should return false for UI schema elements without options cell', t.false(optionIs('answer', 42)(control, undefined, undefined)); }); +test('hasOption should check for options', (t) => { + const control: ControlElement = { + type: 'Control', + scope: '#/properties/bar', + options: { + answer: 42, + }, + }; + t.true(hasOption('answer')(control, undefined, undefined)); +}); + +test('hasOption should not fail if uischema is undefined or null', (t) => { + const uischema: UISchemaElement = null; + t.false(hasOption('answer')(uischema, undefined, undefined)); +}); + +test('hasOption should return false for UI schema elements without options cell', (t) => { + const control: ControlElement = { + type: 'Control', + scope: '#/properties/bar', + }; + t.false(hasOption('answer')(control, undefined, undefined)); +}); + test('schemaMatches should check type sub-schema of control via predicate', (t) => { const schema: JsonSchema = { type: 'object',