@carbon/react
Version:
React components for the Carbon Design System
325 lines (323 loc) • 12.4 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 "../../internal/usePrefix.js";
import { Text } from "../Text/Text.js";
import useIsomorphicEffect from "../../internal/useIsomorphicEffect.js";
import { useId } from "../../internal/useId.js";
import { noopFn } from "../../internal/noopFn.js";
import { deprecate } from "../../prop-types/deprecate.js";
import { isComponentElement } from "../../internal/utils.js";
import { useMergedRefs } from "../../internal/useMergedRefs.js";
import { AILabel } from "../AILabel/index.js";
import { FormContext } from "../FluidForm/FormContext.js";
import { getAnnouncement } from "../../internal/getAnnouncement.js";
import classNames from "classnames";
import { cloneElement, forwardRef, useContext, useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import { jsx, jsxs } from "react/jsx-runtime";
import { WarningAltFilled, WarningFilled } from "@carbon/icons-react";
//#region src/components/TextArea/TextArea.tsx
/**
* 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.
*/
const TextArea = forwardRef((props, forwardRef) => {
const { className, decorator, disabled = false, id, labelText, hideLabel, onChange = noopFn, onClick = noopFn, onKeyDown = noopFn, invalid = false, invalidText = "", helperText, light, placeholder = "", enableCounter = false, maxCount, counterMode = "character", warn = false, warnText = "", rows = 4, slug, ...other } = props;
const prefix = usePrefix();
const { isFluid } = useContext(FormContext);
const { defaultValue, value } = other;
const textAreaInstanceId = useId();
const wrapperRef = useRef(null);
const textareaRef = useRef(null);
const helperTextRef = useRef(null);
const errorTextRef = useRef(null);
const warnTextRef = useRef(null);
const ref = useMergedRefs([forwardRef, textareaRef]);
function getInitialTextCount() {
const strValue = (defaultValue || value || textareaRef.current?.value || "").toString();
if (counterMode === "character") return strValue.length;
else return strValue.match(/\p{L}+/gu)?.length || 0;
}
const [textCount, setTextCount] = useState(getInitialTextCount());
useEffect(() => {
setTextCount(getInitialTextCount());
}, [
value,
defaultValue,
counterMode
]);
useIsomorphicEffect(() => {
if (other.cols && textareaRef.current) {
textareaRef.current.style.width = "";
textareaRef.current.style.resize = "none";
} else if (textareaRef.current) textareaRef.current.style.width = `100%`;
if (!wrapperRef.current) return;
const applyWidth = (width) => {
[
helperTextRef,
errorTextRef,
warnTextRef
].forEach((r) => {
if (r.current) {
r.current.style.maxWidth = `${width}px`;
r.current.style.overflowWrap = "break-word";
}
});
};
const resizeObserver = new ResizeObserver(([entry]) => {
applyWidth(entry.contentRect.width);
});
resizeObserver.observe(wrapperRef.current);
return () => resizeObserver && resizeObserver.disconnect();
}, [
other.cols,
invalid,
warn
]);
const textareaProps = {
id,
onKeyDown: (evt) => {
if (!disabled && enableCounter && counterMode === "word") {
const key = evt.which;
if (maxCount && textCount >= maxCount && key === 32 || maxCount && textCount >= maxCount && key === 13) evt.preventDefault();
}
if (!disabled && onKeyDown) onKeyDown(evt);
},
onPaste: (evt) => {
if (!disabled) {
if (counterMode === "word" && enableCounter && typeof maxCount !== "undefined" && textareaRef.current !== null) {
const existingWords = textareaRef.current.value.match(/\p{L}+/gu) || [];
const pastedWords = evt.clipboardData.getData("Text").match(/\p{L}+/gu) || [];
if (existingWords.length + pastedWords.length > maxCount) {
evt.preventDefault();
const allowedWords = existingWords.concat(pastedWords).slice(0, maxCount);
setTimeout(() => {
setTextCount(maxCount);
}, 0);
textareaRef.current.value = allowedWords.join(" ");
}
}
}
},
onChange: (evt) => {
if (!disabled) {
if (counterMode == "character") {
evt?.persist?.();
setTimeout(() => {
setTextCount(evt.target?.value?.length);
}, 0);
} else if (counterMode == "word") {
if (!evt.target.value) setTimeout(() => {
setTextCount(0);
}, 0);
else if (enableCounter && typeof maxCount !== "undefined" && textareaRef.current !== null) {
const matchedWords = evt.target?.value?.match(/\p{L}+/gu);
if (matchedWords && matchedWords.length <= maxCount) {
textareaRef.current.removeAttribute("maxLength");
setTimeout(() => {
setTextCount(matchedWords.length);
}, 0);
} else if (matchedWords && matchedWords.length > maxCount) setTimeout(() => {
setTextCount(matchedWords.length);
}, 0);
}
}
if (onChange) onChange(evt);
}
},
onClick: (evt) => {
if (!disabled && onClick) onClick(evt);
}
};
const formItemClasses = classNames(`${prefix}--form-item`, className);
const textAreaWrapperClasses = classNames(`${prefix}--text-area__wrapper`, {
[`${prefix}--text-area__wrapper--cols`]: other.cols,
[`${prefix}--text-area__wrapper--readonly`]: other.readOnly,
[`${prefix}--text-area__wrapper--warn`]: warn,
[`${prefix}--text-area__wrapper--slug`]: slug,
[`${prefix}--text-area__wrapper--decorator`]: decorator
});
const labelClasses = classNames(`${prefix}--label`, {
[`${prefix}--visually-hidden`]: hideLabel && !isFluid,
[`${prefix}--label--disabled`]: disabled
});
const textareaClasses = classNames(`${prefix}--text-area`, {
[`${prefix}--text-area--light`]: light,
[`${prefix}--text-area--invalid`]: invalid,
[`${prefix}--text-area--warn`]: warn
});
const counterClasses = classNames(`${prefix}--label`, {
[`${prefix}--label--disabled`]: disabled,
[`${prefix}--text-area__label-counter`]: true
});
const helperTextClasses = classNames(`${prefix}--form__helper-text`, { [`${prefix}--form__helper-text--disabled`]: disabled });
const label = typeof labelText !== "undefined" && labelText !== null && /* @__PURE__ */ jsx(Text, {
as: "label",
htmlFor: id,
className: labelClasses,
children: labelText
});
const counter = enableCounter && maxCount && (counterMode === "character" || counterMode === "word") ? /* @__PURE__ */ jsx(Text, {
as: "div",
className: counterClasses,
"aria-hidden": "true",
children: `${textCount}/${maxCount}`
}) : null;
const counterDescriptionId = enableCounter && maxCount ? `${id}-counter-desc` : void 0;
const hasHelper = typeof helperText !== "undefined" && helperText !== null;
const helperId = !hasHelper ? void 0 : `text-area-helper-text-${textAreaInstanceId}`;
const helper = hasHelper && /* @__PURE__ */ jsx(Text, {
as: "div",
id: helperId,
className: helperTextClasses,
ref: helperTextRef,
children: helperText
});
const errorId = id + "-error-msg";
const error = invalid ? /* @__PURE__ */ jsxs(Text, {
as: "div",
role: "alert",
className: `${prefix}--form-requirement`,
id: errorId,
ref: errorTextRef,
children: [invalidText, isFluid && /* @__PURE__ */ jsx(WarningFilled, { className: `${prefix}--text-area__invalid-icon` })]
}) : null;
const warnId = id + "-warn-msg";
const warning = warn ? /* @__PURE__ */ jsxs(Text, {
as: "div",
role: "alert",
className: `${prefix}--form-requirement`,
id: warnId,
ref: warnTextRef,
children: [warnText, isFluid && /* @__PURE__ */ jsx(WarningAltFilled, { className: `${prefix}--text-area__invalid-icon ${prefix}--text-area__invalid-icon--warning` })]
}) : null;
let ariaDescribedBy;
if (invalid) ariaDescribedBy = errorId;
else if (warn && !isFluid) ariaDescribedBy = warnId;
else {
const ids = [];
if (!isFluid && hasHelper && helperId) ids.push(helperId);
if (counterDescriptionId) ids.push(counterDescriptionId);
ariaDescribedBy = ids.length > 0 ? ids.join(" ") : void 0;
}
if (enableCounter) {
if (counterMode == "character") textareaProps.maxLength = maxCount;
}
const announcerRef = useRef(null);
const [prevAnnouncement, setPrevAnnouncement] = useState("");
const ariaAnnouncement = getAnnouncement(textCount, maxCount, counterMode === "word" ? "word" : void 0, counterMode === "word" ? "words" : void 0);
useEffect(() => {
if (ariaAnnouncement && ariaAnnouncement !== prevAnnouncement) {
const announcer = announcerRef.current;
if (announcer) {
announcer.textContent = "";
const timeoutId = setTimeout(() => {
if (announcer) {
announcer.textContent = ariaAnnouncement;
setPrevAnnouncement(ariaAnnouncement);
}
}, counterMode === "word" ? 2e3 : 1e3);
return () => {
if (timeoutId) clearTimeout(timeoutId);
};
}
}
}, [
ariaAnnouncement,
prevAnnouncement,
counterMode
]);
const input = /* @__PURE__ */ jsx("textarea", {
...other,
...textareaProps,
placeholder,
"aria-readonly": other.readOnly,
className: textareaClasses,
"aria-invalid": invalid,
"aria-describedby": ariaDescribedBy,
disabled,
rows,
readOnly: other.readOnly,
ref
});
const candidate = slug ?? decorator;
const normalizedDecorator = isComponentElement(candidate, AILabel) ? cloneElement(candidate, { size: "mini" }) : candidate;
return /* @__PURE__ */ jsxs("div", {
className: formItemClasses,
children: [
/* @__PURE__ */ jsxs("div", {
className: `${prefix}--text-area__label-wrapper`,
children: [label, counter]
}),
enableCounter && maxCount && /* @__PURE__ */ jsx("span", {
id: counterDescriptionId,
className: `${prefix}--visually-hidden`,
children: counterMode === "word" ? `Word limit ${maxCount}` : `Character limit ${maxCount}`
}),
/* @__PURE__ */ jsxs("div", {
ref: wrapperRef,
className: textAreaWrapperClasses,
"data-invalid": invalid || null,
children: [
invalid && !isFluid && /* @__PURE__ */ jsx(WarningFilled, { className: `${prefix}--text-area__invalid-icon` }),
warn && !invalid && !isFluid && /* @__PURE__ */ jsx(WarningAltFilled, { className: `${prefix}--text-area__invalid-icon ${prefix}--text-area__invalid-icon--warning` }),
input,
slug ? normalizedDecorator : decorator ? /* @__PURE__ */ jsx("div", {
className: `${prefix}--text-area__inner-wrapper--decorator`,
children: normalizedDecorator
}) : "",
/* @__PURE__ */ jsx("span", {
className: `${prefix}--text-area__counter-alert`,
role: "alert",
"aria-live": "assertive",
"aria-atomic": "true",
ref: announcerRef,
children: ariaAnnouncement
}),
isFluid && /* @__PURE__ */ jsx("hr", { className: `${prefix}--text-area__divider` }),
isFluid && invalid ? error : null,
isFluid && warn && !invalid ? warning : null
]
}),
!invalid && !warn && !isFluid ? helper : null,
invalid && !isFluid ? error : null,
warn && !invalid && !isFluid ? warning : null
]
});
});
TextArea.displayName = "TextArea";
TextArea.propTypes = {
className: PropTypes.string,
cols: PropTypes.number,
counterMode: PropTypes.oneOf(["character", "word"]),
decorator: PropTypes.node,
defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
disabled: PropTypes.bool,
enableCounter: PropTypes.bool,
helperText: PropTypes.node,
hideLabel: PropTypes.bool,
id: PropTypes.string,
invalid: PropTypes.bool,
invalidText: PropTypes.node,
labelText: PropTypes.node.isRequired,
light: deprecate(PropTypes.bool, "The `light` prop for `TextArea` has been deprecated in favor of the new `Layer` component. It will be removed in the next major release."),
maxCount: PropTypes.number,
onChange: PropTypes.func,
onClick: PropTypes.func,
onKeyDown: PropTypes.func,
placeholder: PropTypes.string,
readOnly: PropTypes.bool,
rows: PropTypes.number,
slug: deprecate(PropTypes.node, "The `slug` prop for `TextArea` has been deprecated in favor of the new `decorator` prop. It will be removed in the next major release."),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
warn: PropTypes.bool,
warnText: PropTypes.node
};
//#endregion
export { TextArea as default };