UNPKG

@carbon/react

Version:

React components for the Carbon Design System

62 lines (58 loc) 1.88 kB
/** * Copyright IBM Corp. 2016, 2023 * * 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 React from 'react'; import { WarningFilled, WarningAltFilled } from '@carbon/icons-react'; import '../components/Text/index.js'; import { usePrefix } from './usePrefix.js'; import { Text } from '../components/Text/Text.js'; /** * 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 && invalid, invalidId: `${id}-error-msg`, warn: !readOnly && !invalid && warn, warnId: `${id}-warn-msg`, validation: null, icon: null, helperId: `${id}-helper-text` }; if (normalizedProps.invalid) { normalizedProps.icon = WarningFilled; normalizedProps.validation = /*#__PURE__*/React.createElement(Text, { as: "div", className: `${prefix}--form-requirement`, id: normalizedProps.invalidId }, invalidText); } else if (normalizedProps.warn) { normalizedProps.icon = WarningAltFilled; normalizedProps.validation = /*#__PURE__*/React.createElement(Text, { as: "div", className: `${prefix}--form-requirement`, id: normalizedProps.warnId }, warnText); } return normalizedProps; }; export { useNormalizedInputProps };