@carbon/react
Version:
React components for the Carbon Design System
56 lines (54 loc) • 1.89 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { usePrefix } from "./usePrefix.js";
import { Text } from "../components/Text/Text.js";
import "react";
import { jsx } from "react/jsx-runtime";
import { WarningAltFilled, WarningFilled } from "@carbon/icons-react";
//#region src/internal/useNormalizedInputProps.tsx
/**
* Returns an object containing normalized properties for an input component.
*
* This hook ensures that only one of `invalid` or `warn` is active (with
* `invalid` taking precedence) and that `readOnly` overrides the `disabled`,
* `invalid`, and `warn` states. It generates unique IDs for error, warning, and
* helper messages, and conditionally provides the appropriate validation
* message and accompanying icon.
*/
const useNormalizedInputProps = ({ id, readOnly, disabled, invalid, invalidText, warn, warnText }) => {
const prefix = usePrefix();
const normalizedProps = {
disabled: !readOnly && disabled,
invalid: !readOnly && !disabled && invalid,
invalidId: `${id}-error-msg`,
warn: !readOnly && !invalid && !disabled && warn,
warnId: `${id}-warn-msg`,
validation: null,
icon: null,
helperId: `${id}-helper-text`
};
if (normalizedProps.invalid) {
normalizedProps.icon = WarningFilled;
normalizedProps.validation = /* @__PURE__ */ jsx(Text, {
as: "div",
className: `${prefix}--form-requirement`,
id: normalizedProps.invalidId,
children: invalidText
});
} else if (normalizedProps.warn) {
normalizedProps.icon = WarningAltFilled;
normalizedProps.validation = /* @__PURE__ */ jsx(Text, {
as: "div",
className: `${prefix}--form-requirement`,
id: normalizedProps.warnId,
children: warnText
});
}
return normalizedProps;
};
//#endregion
export { useNormalizedInputProps };