UNPKG

@rjsf/core

Version:

A simple React component capable of building HTML forms out of a JSON schema.

44 lines (43 loc) 2.4 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { getSchemaType, getTemplate, getUiOptions, isFormDataAvailable, optionalControlsId, TranslatableString, } from '@rjsf/utils'; /** The `OptionalDataControlsField` component is used to render the optional data controls for the field associated * with the given props. * * @param props - The `FieldProps` for this template */ export default function OptionalDataControlsField(props) { const { schema, uiSchema = {}, formData, disabled = false, readonly = false, onChange, errorSchema, fieldPathId, registry, } = props; const { globalUiOptions = {}, schemaUtils, translateString } = registry; const uiOptions = getUiOptions(uiSchema, globalUiOptions); const OptionalDataControlsTemplate = getTemplate('OptionalDataControlsTemplate', registry, uiOptions); const hasFormData = isFormDataAvailable(formData); let id; let label; let onAddClick; let onRemoveClick; if (disabled || readonly) { id = optionalControlsId(fieldPathId, 'Msg'); label = hasFormData ? undefined : translateString(TranslatableString.OptionalObjectEmptyMsg); } else { const labelEnum = hasFormData ? TranslatableString.OptionalObjectRemove : TranslatableString.OptionalObjectAdd; label = translateString(labelEnum); if (hasFormData) { id = optionalControlsId(fieldPathId, 'Remove'); onRemoveClick = () => onChange(undefined, fieldPathId.path, errorSchema); } else { id = optionalControlsId(fieldPathId, 'Add'); onAddClick = () => { // If it has form data, store an empty object, otherwise get the default form state and use it let newFormData = schemaUtils.getDefaultFormState(schema, formData, 'excludeObjectChildren'); if (newFormData === undefined) { // If new form data ended up being undefined, and we have pushed the add button we need to actually add data newFormData = getSchemaType(schema) === 'array' ? [] : {}; } onChange(newFormData, fieldPathId.path, errorSchema); }; } } return (label && (_jsx(OptionalDataControlsTemplate, { id: id, registry: registry, schema: schema, uiSchema: uiSchema, label: label, onAddClick: onAddClick, onRemoveClick: onRemoveClick }))); }