@vectara/vectara-ui
Version:
Vectara's design system, codified as a React and Sass component library
53 lines (52 loc) • 2.46 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { cloneElement } from "react";
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";
import { VuiInlineFormGroup } from "./InlineFormGroup";
import { VuiBlockFormGroup } from "./BlockFormGroup";
const VALIDATION_ALLOWLIST = [VuiTextInput, VuiNumberInput, VuiTextArea, VuiSelect];
export const VuiFormGroup = ({ children, labelFor, helpText, label, labelSize = "s", labelRightContent, errors, isRequired, inline }) => {
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: inline ? "empty" : "danger" }, { children: error })) }) }), 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);
const props = {
label,
labelRightContent,
labelFor,
labelSize,
isRequired,
helpText,
ariaDescribedByLabel,
errorMessages,
content
};
if (inline) {
return _jsx(VuiInlineFormGroup, Object.assign({}, props));
}
return _jsx(VuiBlockFormGroup, Object.assign({}, props));
};