diff --git a/next/src/field/schema.ts b/next/src/field/schema.ts index 27ae20fb4..af0307397 100644 --- a/next/src/field/schema.ts +++ b/next/src/field/schema.ts @@ -19,6 +19,42 @@ function addCheckboxAttributes(inputType: string, field: Field, schema: NonBoole } } +/** + * Add options attribute to a field + * @param field - The field to add the options to + * @param schema - The schema of the field + * @description + * This adds the options attribute to based on the schema's oneOf, anyOf, or enum if we don't already have options on the field. + */ +function addOptions(field: Field, schema: NonBooleanJsfSchema) { + if (field.options === undefined) { + const options = getFieldOptions(schema) + if (options) { + field.options = options + if (schema.type === 'array') { + field.multiple = true + } + } + } +} + +/** + * Add fields attribute to a field + * @param field - The field to add the fields to + * @param schema - The schema of the field + * @description + * This adds the fields attribute to based on the schema's items. + * Since options and fields are mutually exclusive, we only add fields if no options were provided. + */ +function addFields(field: Field, schema: NonBooleanJsfSchema, strictInputType?: boolean) { + if (field.options === undefined) { + const fields = getFields(schema, strictInputType) + if (fields) { + field.fields = fields + } + } +} + /** * Get the presentation input type for a field from a schema type (ported from v0) * @param type - The schema type @@ -332,21 +368,8 @@ export function buildFieldSchema( }) } - // Handle options - const options = getFieldOptions(schema) - if (options) { - field.options = options - if (schema.type === 'array') { - field.multiple = true - } - } - else { - // We did not find options, so we might have an array to generate fields from - const fields = getFields(schema, strictInputType) - if (fields) { - field.fields = fields - } - } + addOptions(field, schema) + addFields(field, schema) return field } diff --git a/next/test/fields.test.ts b/next/test/fields.test.ts index 2c0634326..35034c087 100644 --- a/next/test/fields.test.ts +++ b/next/test/fields.test.ts @@ -235,6 +235,45 @@ describe('fields', () => { ]) }) + it('creates options from an enum inside items (deprecated)', () => { + const schema: JsfSchema = { + type: 'object', + properties: { + currency: { + 'type': 'array', + 'items': { + type: 'string', + enum: ['usd', 'eur', 'gbp'], + }, + 'x-jsf-presentation': { + options: [ + { + label: 'USD', + value: 'usd', + }, + { + label: 'EUR', + value: 'eur', + }, + { + label: 'GBP', + value: 'gbp', + }, + ], + }, + }, + }, + } + + const fields = buildFieldSchema(schema, 'root', true)!.fields! + + expect(fields[0].options).toEqual([ + { label: 'USD', value: 'usd' }, + { label: 'EUR', value: 'eur' }, + { label: 'GBP', value: 'gbp' }, + ]) + }) + describe('radio field', () => { it('builds a radio field with options', () => { const schema: JsfSchema = {