UNPKG

@vectara/vectara-ui

Version:

Vectara's design system, codified as a React and Sass component library

38 lines (37 loc) 2.55 kB
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime"; import { cloneElement } from "react"; import { VuiLabel } from "../form/label/Label"; import { VuiSpacer } from "../spacer/Spacer"; import { VuiText } from "../typography/Text"; import { VuiTextColor } from "../typography/TextColor"; import { createId } from "../../utils/createId"; import { VuiTextInput } from "../form/input/TextInput"; import { VuiNumberInput } from "../form/input/NumberInput"; import { VuiTextArea } from "../form/textArea/TextArea"; import { VuiSelect } from "../form/select/Select"; const VALIDATION_ALLOWLIST = [VuiTextInput, VuiNumberInput, VuiTextArea, VuiSelect]; export const VuiFormGroup = ({ children, labelFor, helpText, label, errors, isRequired }) => { const ariaProps = { "aria-describedby": "" }; const ariaDescribedByLabel = `help-${createId()}`; const errorMessageIds = []; const errorMessages = errors === null || errors === void 0 ? void 0 : errors.map((error, index) => { const id = `error-${createId()}`; errorMessageIds.push(id); return (_jsxs("div", { children: [index > 0 && _jsx(VuiSpacer, { size: "xs" }), _jsx(VuiText, Object.assign({ size: "xs", id: id }, { children: _jsx("p", { children: _jsx(VuiTextColor, Object.assign({ color: "danger" }, { children: error })) }) }), error)] })); }); if (helpText) { ariaProps["aria-describedby"] += ariaDescribedByLabel; } if (errorMessages === null || errorMessages === void 0 ? void 0 : errorMessages.length) { ariaProps["aria-describedby"] += " " + errorMessageIds.join(" "); } const cloneProps = Object.assign(Object.assign({}, ariaProps), { id: labelFor, required: isRequired }); const canValidateChild = VALIDATION_ALLOWLIST.includes(children.type); if (canValidateChild) { cloneProps.isInvalid = errors && errors.length > 0; } const content = cloneElement(children, cloneProps); return (_jsxs("div", { children: [_jsxs(VuiLabel, Object.assign({ labelFor: labelFor }, { children: [label, isRequired && " (required)"] })), _jsx(VuiSpacer, { size: "xs" }), helpText && (_jsxs(_Fragment, { children: [_jsx(VuiText, Object.assign({ size: "xs", id: ariaDescribedByLabel }, { children: _jsx("p", { children: _jsx(VuiTextColor, Object.assign({ color: "subdued" }, { children: helpText })) }) })), _jsx(VuiSpacer, { size: "xs" })] })), errorMessages && (_jsxs(_Fragment, { children: [errorMessages, _jsx(VuiSpacer, { size: "xs" })] })), content] })); };