@carbon/react
Version:
React components for the Carbon Design System
327 lines (322 loc) • 11.2 kB
JavaScript
/**
* 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 PropTypes from 'prop-types';
import React, { useRef, useState, useEffect, useContext, cloneElement } from 'react';
import cx from 'classnames';
import { useNormalizedInputProps } from '../../internal/useNormalizedInputProps.js';
import { deprecate } from '../../prop-types/deprecate.js';
import { textInputProps } from './util.js';
import '../FluidForm/FluidForm.js';
import { FormContext } from '../FluidForm/FormContext.js';
import { useMergedRefs } from '../../internal/useMergedRefs.js';
import { usePrefix } from '../../internal/usePrefix.js';
import { getAnnouncement } from '../../internal/getAnnouncement.js';
import '../Text/index.js';
import { AILabel } from '../AILabel/index.js';
import { isComponentElement } from '../../internal/utils.js';
import { Text } from '../Text/Text.js';
const TextInput = /*#__PURE__*/React.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();
const {
defaultValue,
value
} = rest;
const inputRef = useRef(null);
const mergedRef = useMergedRefs([ref, inputRef]);
function getInitialTextCount() {
const targetValue = defaultValue || value || inputRef.current?.value || '';
return targetValue.toString().length;
}
const [textCount, setTextCount] = useState(getInitialTextCount());
useEffect(() => {
setTextCount(getInitialTextCount());
}, [value, defaultValue, enableCounter]);
const normalizedProps = 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, {
as: "div",
className: counterClasses
}, `${textCount}/${maxCount}`) : null;
const label = labelText ? /*#__PURE__*/React.createElement(Text, {
as: "label",
htmlFor: id,
className: labelClasses
}, labelText) : null;
const labelWrapper = /*#__PURE__*/React.createElement("div", {
className: `${prefix}--text-input__label-wrapper`
}, label, counter);
const helper = helperText ? /*#__PURE__*/React.createElement(Text, {
as: "div",
id: normalizedProps.helperId,
className: helperTextClasses
}, helperText) : null;
const input = /*#__PURE__*/React.createElement("input", textInputProps({
sharedTextInputProps,
invalid: normalizedProps.invalid,
invalidId: normalizedProps.invalidId,
warn: normalizedProps.warn,
warnId: normalizedProps.warnId
}));
const {
isFluid
} = useContext(FormContext);
const announcerRef = useRef(null);
const [prevAnnouncement, setPrevAnnouncement] = useState('');
const ariaAnnouncement = getAnnouncement(textCount, maxCount);
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 = isComponentElement(candidate, AILabel);
const normalizedDecorator = candidateIsAILabel ? /*#__PURE__*/cloneElement(candidate, {
size: 'mini'
}) : null;
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(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(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
};
export { TextInput as default };