UNPKG

@carbon/react

Version:

React components for the Carbon Design System

333 lines (326 loc) 11.7 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. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var PropTypes = require('prop-types'); var React = require('react'); var cx = require('classnames'); var useNormalizedInputProps = require('../../internal/useNormalizedInputProps.js'); var deprecate = require('../../prop-types/deprecate.js'); var util = require('./util.js'); require('../FluidForm/FluidForm.js'); var FormContext = require('../FluidForm/FormContext.js'); var useMergedRefs = require('../../internal/useMergedRefs.js'); var usePrefix = require('../../internal/usePrefix.js'); var getAnnouncement = require('../../internal/getAnnouncement.js'); var Text = require('../Text/Text.js'); require('../Text/TextDirection.js'); var index = require('../AILabel/index.js'); var utils = require('../../internal/utils.js'); const TextInput = /*#__PURE__*/React.forwardRef(({ className, decorator, disabled = false, helperText, hideLabel, id, inline = false, invalid = false, invalidText, labelText, light, onChange = () => {}, onClick = () => {}, placeholder, readOnly, size, type = 'text', warn = false, warnText, enableCounter = false, maxCount, slug, ...rest }, ref) => { const prefix = usePrefix.usePrefix(); const { defaultValue, value } = rest; const inputRef = React.useRef(null); const mergedRef = useMergedRefs.useMergedRefs([ref, inputRef]); function getInitialTextCount() { const targetValue = defaultValue || value || inputRef.current?.value || ''; return targetValue.toString().length; } const [textCount, setTextCount] = React.useState(getInitialTextCount()); React.useEffect(() => { setTextCount(getInitialTextCount()); // eslint-disable-next-line react-hooks/exhaustive-deps -- https://github.com/carbon-design-system/carbon/issues/20452 }, [value, defaultValue, enableCounter]); const normalizedProps = useNormalizedInputProps.useNormalizedInputProps({ id, readOnly, disabled, invalid, invalidText, warn, warnText }); const textInputClasses = cx(`${prefix}--text-input`, { [`${prefix}--text-input--light`]: light, [`${prefix}--text-input--invalid`]: normalizedProps.invalid, [`${prefix}--text-input--warning`]: normalizedProps.warn, [`${prefix}--text-input--${size}`]: size, // TODO: V12 - Remove this class [`${prefix}--layout--size-${size}`]: size }); const sharedTextInputProps = { id, onChange: evt => { if (!normalizedProps.disabled) { setTextCount(evt.target.value?.length); onChange(evt); } }, onClick: evt => { if (!normalizedProps.disabled) { onClick(evt); } }, placeholder, type, ref: mergedRef, className: textInputClasses, title: placeholder, disabled: normalizedProps.disabled, readOnly, ['aria-describedby']: helperText && normalizedProps.helperId, ...rest }; if (enableCounter) { sharedTextInputProps.maxLength = maxCount; } const inputWrapperClasses = cx([cx(`${prefix}--form-item`, className)], `${prefix}--text-input-wrapper`, { [`${prefix}--text-input-wrapper--readonly`]: readOnly, [`${prefix}--text-input-wrapper--light`]: light, [`${prefix}--text-input-wrapper--inline`]: inline, [`${prefix}--text-input-wrapper--inline--invalid`]: inline && normalizedProps.invalid }); const labelClasses = cx(`${prefix}--label`, { [`${prefix}--visually-hidden`]: hideLabel, [`${prefix}--label--disabled`]: normalizedProps.disabled, [`${prefix}--label--inline`]: inline, [`${prefix}--label--inline--${size}`]: inline && !!size }); const helperTextClasses = cx(`${prefix}--form__helper-text`, { [`${prefix}--form__helper-text--disabled`]: normalizedProps.disabled, [`${prefix}--form__helper-text--inline`]: inline }); const fieldOuterWrapperClasses = cx(`${prefix}--text-input__field-outer-wrapper`, { [`${prefix}--text-input__field-outer-wrapper--inline`]: inline }); const fieldWrapperClasses = cx(`${prefix}--text-input__field-wrapper`, { [`${prefix}--text-input__field-wrapper--warning`]: normalizedProps.warn, [`${prefix}--text-input__field-wrapper--slug`]: slug, [`${prefix}--text-input__field-wrapper--decorator`]: decorator }); const iconClasses = cx({ [`${prefix}--text-input__invalid-icon`]: normalizedProps.invalid || normalizedProps.warn, [`${prefix}--text-input__invalid-icon--warning`]: normalizedProps.warn }); const counterClasses = cx(`${prefix}--label`, { [`${prefix}--label--disabled`]: disabled, [`${prefix}--text-input__label-counter`]: true }); const counter = enableCounter && maxCount ? /*#__PURE__*/React.createElement(Text.Text, { as: "div", className: counterClasses }, `${textCount}/${maxCount}`) : null; const label = typeof labelText !== 'undefined' && labelText !== null && /*#__PURE__*/React.createElement(Text.Text, { as: "label", htmlFor: id, className: labelClasses }, labelText); const labelWrapper = /*#__PURE__*/React.createElement("div", { className: `${prefix}--text-input__label-wrapper` }, label, counter); const helper = typeof helperText !== 'undefined' && helperText !== null && /*#__PURE__*/React.createElement(Text.Text, { as: "div", id: normalizedProps.helperId, className: helperTextClasses }, helperText); const input = /*#__PURE__*/React.createElement("input", util.getTextInputProps({ sharedTextInputProps, invalid: normalizedProps.invalid, invalidId: normalizedProps.invalidId, warn: normalizedProps.warn, warnId: normalizedProps.warnId })); const { isFluid } = React.useContext(FormContext.FormContext); const announcerRef = React.useRef(null); const [prevAnnouncement, setPrevAnnouncement] = React.useState(''); const ariaAnnouncement = getAnnouncement.getAnnouncement(textCount, maxCount); React.useEffect(() => { if (ariaAnnouncement && ariaAnnouncement !== prevAnnouncement) { const announcer = announcerRef.current; if (announcer) { // Clear the content first announcer.textContent = ''; // Set the new content after a small delay const timeoutId = setTimeout(() => { if (announcer) { announcer.textContent = ariaAnnouncement; setPrevAnnouncement(ariaAnnouncement); } }, 1000); // clear the timeout return () => { if (timeoutId) { clearTimeout(timeoutId); } }; } } }, [ariaAnnouncement, prevAnnouncement]); // eslint-disable-next-line @typescript-eslint/no-explicit-any -- https://github.com/carbon-design-system/carbon/issues/20452 const Icon = normalizedProps.icon; // AILabel is always size `mini` const candidate = slug ?? decorator; const candidateIsAILabel = utils.isComponentElement(candidate, index.AILabel); const normalizedDecorator = candidateIsAILabel ? /*#__PURE__*/React.cloneElement(candidate, { size: 'mini' }) : candidate; return /*#__PURE__*/React.createElement("div", { className: inputWrapperClasses }, !inline ? labelWrapper : /*#__PURE__*/React.createElement("div", { className: `${prefix}--text-input__label-helper-wrapper` }, labelWrapper, !isFluid && (normalizedProps.validation || helper)), /*#__PURE__*/React.createElement("div", { className: fieldOuterWrapperClasses }, /*#__PURE__*/React.createElement("div", { className: fieldWrapperClasses, "data-invalid": normalizedProps.invalid || null }, Icon && /*#__PURE__*/React.createElement(Icon, { className: iconClasses }), input, slug ? normalizedDecorator : decorator ? /*#__PURE__*/React.createElement("div", { className: `${prefix}--text-input__field-inner-wrapper--decorator` }, normalizedDecorator) : '', /*#__PURE__*/React.createElement("span", { className: `${prefix}--text-input__counter-alert`, role: "alert", "aria-live": "assertive", "aria-atomic": "true", ref: announcerRef }, ariaAnnouncement), isFluid && /*#__PURE__*/React.createElement("hr", { className: `${prefix}--text-input__divider` }), isFluid && !inline && normalizedProps.validation), !isFluid && !inline && (normalizedProps.validation || helper))); }); TextInput.displayName = 'TextInput'; TextInput.propTypes = { /** * Specify an optional className to be applied to the `<input>` node */ className: PropTypes.string, /** * **Experimental**: Provide a `decorator` component to be rendered inside the `TextInput` component */ decorator: PropTypes.node, /** * Optionally provide the default value of the `<input>` */ defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Specify whether the `<input>` should be disabled */ disabled: PropTypes.bool, /** * Specify whether to display the character counter */ enableCounter: PropTypes.bool, /** * Provide text that is used alongside the control label for additional help */ helperText: PropTypes.node, /** * Specify whether you want the underlying label to be visually hidden */ hideLabel: PropTypes.bool, /** * Specify a custom `id` for the `<input>` */ id: PropTypes.string.isRequired, /** * `true` to use the inline version. */ inline: PropTypes.bool, /** * Specify whether the control is currently invalid */ invalid: PropTypes.bool, /** * Provide the text that is displayed when the control is in an invalid state */ invalidText: PropTypes.node, /** * Provide the text that will be read by a screen reader when visiting this * control */ labelText: PropTypes.node.isRequired, /** * `true` to use the light version. For use on $ui-01 backgrounds only. * Don't use this to make tile background color same as container background color. */ light: deprecate.deprecate(PropTypes.bool, 'The `light` prop for `TextInput` has ' + 'been deprecated in favor of the new `Layer` component. It will be removed in the next major release.'), /** * Max character count allowed for the input. This is needed in order for enableCounter to display */ maxCount: PropTypes.number, /** * Optionally provide an `onChange` handler that is called whenever `<input>` * is updated */ onChange: PropTypes.func, /** * Optionally provide an `onClick` handler that is called whenever the * `<input>` is clicked */ onClick: PropTypes.func, /** * Specify the placeholder attribute for the `<input>` */ placeholder: PropTypes.string, /** * Whether the input should be read-only */ readOnly: PropTypes.bool, /** * Specify the size of the Text Input. Currently supports the following: */ size: PropTypes.oneOf(['sm', 'md', 'lg']), /** * **Experimental**: Provide a `Slug` component to be rendered inside the `TextInput` component */ slug: deprecate.deprecate(PropTypes.node, 'The `slug` prop for `TextInput` has ' + 'been deprecated in favor of the new `decorator` prop. It will be removed in the next major release.'), /** * Specify the type of the `<input>` */ type: PropTypes.string, /** * Specify the value of the `<input>` */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Specify whether the control is currently in warning state */ warn: PropTypes.bool, /** * Provide the text that is displayed when the control is in warning state */ warnText: PropTypes.node }; exports.default = TextInput;