UNPKG

@snups/rjsf-utils

Version:
70 lines 3.32 kB
import get from 'lodash-es/get.js'; import { CONST_KEY, DEFAULT_KEY, PROPERTIES_KEY } from './constants.js'; import getDiscriminatorFieldFromSchema from './getDiscriminatorFieldFromSchema.js'; import getUiOptions from './getUiOptions.js'; import toConstant from './toConstant.js'; /** Gets the list of options from the `schema`. If the schema has an enum list, then those enum values are returned. The * label will be the same as the `value`. * * If the schema has a `oneOf` or `anyOf`, then the value is the list of either: * - The `const` values from the schema if present * - If the schema has a discriminator and the label using either the `schema.title` or the value. If a `uiSchema` is * provided, and it has the `ui:enumNames` matched with `enum` or it has an associated `oneOf` or `anyOf` with a list of * objects containing `ui:title` then the UI schema values will replace the values from the schema. * * @param schema - The schema from which to extract the options list * @param [uiSchema] - The optional uiSchema from which to get alternate labels for the options * @returns - The list of options from the schema */ export default function optionsList(schema, uiSchema) { if (schema.enum) { let enumNames; if (uiSchema) { const { enumNames: uiEnumNames } = getUiOptions(uiSchema); enumNames = uiEnumNames; } return schema.enum.map((value, i) => { const label = (enumNames === null || enumNames === void 0 ? void 0 : enumNames[i]) || String(value); return { label, value }; }); } let altSchemas = undefined; let altUiSchemas = undefined; if (schema.anyOf) { altSchemas = schema.anyOf; altUiSchemas = uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema.anyOf; } else if (schema.oneOf) { altSchemas = schema.oneOf; altUiSchemas = uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema.oneOf; } // See if there is a discriminator path specified in the schema, and if so, use it as the selectorField, otherwise // pull one from the uiSchema let selectorField = getDiscriminatorFieldFromSchema(schema); if (uiSchema) { const { optionsSchemaSelector = selectorField } = getUiOptions(uiSchema); selectorField = optionsSchemaSelector; } return (altSchemas && altSchemas.map((aSchemaDef, index) => { const { title } = getUiOptions(altUiSchemas === null || altUiSchemas === void 0 ? void 0 : altUiSchemas[index]); const aSchema = aSchemaDef; let value; let label = title; if (selectorField) { const innerSchema = get(aSchema, [PROPERTIES_KEY, selectorField], {}); value = get(innerSchema, DEFAULT_KEY, get(innerSchema, CONST_KEY)); label = label || (innerSchema === null || innerSchema === void 0 ? void 0 : innerSchema.title) || aSchema.title || String(value); } else { value = toConstant(aSchema); label = label || aSchema.title || String(value); } return { schema: aSchema, label, value, }; })); } //# sourceMappingURL=optionsList.js.map