UNPKG

@carbon/react

Version:

React components for the Carbon Design System

337 lines (328 loc) 12.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'); require('../Text/index.js'); var index = require('../AILabel/index.js'); var utils = require('../../internal/utils.js'); var Text = require('../Text/Text.js'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes); var React__default = /*#__PURE__*/_interopDefaultLegacy(React); var cx__default = /*#__PURE__*/_interopDefaultLegacy(cx); const TextInput = /*#__PURE__*/React__default["default"].forwardRef(function TextInput({ 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()); }, [value, defaultValue, enableCounter]); const normalizedProps = useNormalizedInputProps.useNormalizedInputProps({ id, readOnly, disabled, invalid, invalidText, warn, warnText }); const textInputClasses = cx__default["default"](`${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__default["default"]([cx__default["default"](`${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__default["default"](`${prefix}--label`, { [`${prefix}--visually-hidden`]: hideLabel, [`${prefix}--label--disabled`]: normalizedProps.disabled, [`${prefix}--label--inline`]: inline, [`${prefix}--label--inline--${size}`]: inline && !!size }); const helperTextClasses = cx__default["default"](`${prefix}--form__helper-text`, { [`${prefix}--form__helper-text--disabled`]: normalizedProps.disabled, [`${prefix}--form__helper-text--inline`]: inline }); const fieldOuterWrapperClasses = cx__default["default"](`${prefix}--text-input__field-outer-wrapper`, { [`${prefix}--text-input__field-outer-wrapper--inline`]: inline }); const fieldWrapperClasses = cx__default["default"](`${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__default["default"]({ [`${prefix}--text-input__invalid-icon`]: normalizedProps.invalid || normalizedProps.warn, [`${prefix}--text-input__invalid-icon--warning`]: normalizedProps.warn }); const counterClasses = cx__default["default"](`${prefix}--label`, { [`${prefix}--label--disabled`]: disabled, [`${prefix}--text-input__label-counter`]: true }); const counter = enableCounter && maxCount ? /*#__PURE__*/React__default["default"].createElement(Text.Text, { as: "div", className: counterClasses }, `${textCount}/${maxCount}`) : null; const label = labelText ? /*#__PURE__*/React__default["default"].createElement(Text.Text, { as: "label", htmlFor: id, className: labelClasses }, labelText) : null; const labelWrapper = /*#__PURE__*/React__default["default"].createElement("div", { className: `${prefix}--text-input__label-wrapper` }, label, counter); const helper = helperText ? /*#__PURE__*/React__default["default"].createElement(Text.Text, { as: "div", id: normalizedProps.helperId, className: helperTextClasses }, helperText) : null; const input = /*#__PURE__*/React__default["default"].createElement("input", util.textInputProps({ 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]); 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' }) : null; return /*#__PURE__*/React__default["default"].createElement("div", { className: inputWrapperClasses }, !inline ? labelWrapper : /*#__PURE__*/React__default["default"].createElement("div", { className: `${prefix}--text-input__label-helper-wrapper` }, labelWrapper, !isFluid && (normalizedProps.validation || helper)), /*#__PURE__*/React__default["default"].createElement("div", { className: fieldOuterWrapperClasses }, /*#__PURE__*/React__default["default"].createElement("div", { className: fieldWrapperClasses, "data-invalid": normalizedProps.invalid || null }, Icon && /*#__PURE__*/React__default["default"].createElement(Icon, { className: iconClasses }), input, slug ? normalizedDecorator : decorator ? /*#__PURE__*/React__default["default"].createElement("div", { className: `${prefix}--text-input__field-inner-wrapper--decorator` }, normalizedDecorator) : '', /*#__PURE__*/React__default["default"].createElement("span", { className: `${prefix}--text-input__counter-alert`, role: "alert", "aria-live": "assertive", "aria-atomic": "true", ref: announcerRef }, ariaAnnouncement), isFluid && /*#__PURE__*/React__default["default"].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__default["default"].string, /** * **Experimental**: Provide a `decorator` component to be rendered inside the `TextInput` component */ decorator: PropTypes__default["default"].node, /** * Optionally provide the default value of the `<input>` */ defaultValue: PropTypes__default["default"].oneOfType([PropTypes__default["default"].string, PropTypes__default["default"].number]), /** * Specify whether the `<input>` should be disabled */ disabled: PropTypes__default["default"].bool, /** * Specify whether to display the character counter */ enableCounter: PropTypes__default["default"].bool, /** * Provide text that is used alongside the control label for additional help */ helperText: PropTypes__default["default"].node, /** * Specify whether you want the underlying label to be visually hidden */ hideLabel: PropTypes__default["default"].bool, /** * Specify a custom `id` for the `<input>` */ id: PropTypes__default["default"].string.isRequired, /** * `true` to use the inline version. */ inline: PropTypes__default["default"].bool, /** * Specify whether the control is currently invalid */ invalid: PropTypes__default["default"].bool, /** * Provide the text that is displayed when the control is in an invalid state */ invalidText: PropTypes__default["default"].node, /** * Provide the text that will be read by a screen reader when visiting this * control */ labelText: PropTypes__default["default"].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["default"](PropTypes__default["default"].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__default["default"].number, /** * Optionally provide an `onChange` handler that is called whenever `<input>` * is updated */ onChange: PropTypes__default["default"].func, /** * Optionally provide an `onClick` handler that is called whenever the * `<input>` is clicked */ onClick: PropTypes__default["default"].func, /** * Specify the placeholder attribute for the `<input>` */ placeholder: PropTypes__default["default"].string, /** * Whether the input should be read-only */ readOnly: PropTypes__default["default"].bool, /** * Specify the size of the Text Input. Currently supports the following: */ size: PropTypes__default["default"].oneOf(['sm', 'md', 'lg']), /** * **Experimental**: Provide a `Slug` component to be rendered inside the `TextInput` component */ slug: deprecate["default"](PropTypes__default["default"].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__default["default"].string, /** * Specify the value of the `<input>` */ value: PropTypes__default["default"].oneOfType([PropTypes__default["default"].string, PropTypes__default["default"].number]), /** * Specify whether the control is currently in warning state */ warn: PropTypes__default["default"].bool, /** * Provide the text that is displayed when the control is in warning state */ warnText: PropTypes__default["default"].node }; exports["default"] = TextInput;