Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(TextArea): hardening — counter a11y, soft maxLength, disabled states (#849)

Joey77afe12397c9
diff --git a/packages/core/src/TextArea/TextArea.doc.mjs b/packages/core/src/TextArea/TextArea.doc.mjs
index f139743396..f548aa5efb 100644
--- a/packages/core/src/TextArea/TextArea.doc.mjs
+++ b/packages/core/src/TextArea/TextArea.doc.mjs
@@ -9,15 +9,16 @@ export const docs = {
'Description — optional text displayed between the label and textarea',
'Optional/Required indicators — displays "Optional" or "Required" text with bullet separator',
'Status variants — warning, error, and success states with colored borders and icons',
- 'Character counter — displays current/max length when maxLength is set',
+ 'Character counter — displays current/max length when maxLength is set (does not enforce natively)',
'Start icon — optional icon rendered inside the leading edge of the input',
'Label tooltip — optional info icon with tooltip at the end of the label',
'Loading state — shows a spinner and uses optimistic updates via useOptimistic',
'Async action support — onChangeAction fires after onChange inside a React transition',
'Disabled state — visual opacity and cursor changes, no interaction',
'Accessible — label associated via htmlFor/id, aria-describedby, aria-required, aria-invalid, aria-busy',
- 'Resizable — vertical resize enabled by default with a minimum height of 80px',
+ 'Resizable — vertical resize enabled by default',
'Spell check — browser spell checking enabled by default, configurable',
+ 'Reduced motion — respects prefers-reduced-motion for input wrapper transitions',
],
examples: [
{
@@ -56,6 +57,12 @@ export const docs = {
},
],
props: [
+ {
+ name: 'ref',
+ type: 'React.Ref<HTMLTextAreaElement>',
+ description:
+ 'Ref forwarded to the underlying <textarea> element.',
+ },
{
name: 'label',
type: 'string',
@@ -134,7 +141,7 @@ export const docs = {
name: 'maxLength',
type: 'number',
description:
- 'Maximum number of characters allowed. When set, a character counter (current/max) is displayed below the textarea.',
+ 'Maximum number of characters allowed. When set, a character counter (current/max) is displayed below the textarea. Does not enforce the limit natively — the counter shows error styling when exceeded.',
},
{
name: 'status',
@@ -177,7 +184,22 @@ export const docs = {
description:
'HTML name attribute for the textarea element, useful for form submissions.',
},
+ {
+ name: 'onFocus',
+ type: '(e: FocusEvent<HTMLTextAreaElement>) => void',
+ description: 'Callback fired when the textarea receives focus.',
+ },
+ {
+ name: 'onBlur',
+ type: '(e: FocusEvent<HTMLTextAreaElement>) => void',
+ description: 'Callback fired when the textarea loses focus.',
+ },
],
+ theming: {
+ targets: [
+ {className: 'xds-textarea'},
+ ],
+ },
accessibility: [
'Label is always rendered in the DOM; use isLabelHidden to hide it visually while keeping it accessible.',
'The textarea id is generated via useId and linked to its label via htmlFor, ensuring correct label association.',
@@ -189,9 +211,11 @@ export const docs = {
notes: [
'isOptional and isRequired are mutually exclusive; if both are set, "Optional" takes precedence.',
'The component uses useOptimistic for instant UI feedback when onChangeAction returns a Promise.',
- 'Textarea has vertical resize enabled via CSS with a minimum height of 80px.',
+ 'Textarea has vertical resize enabled via CSS.',
'Wraps XDSField for consistent label, description, and status message layout.',
- 'The character counter text turns red when value.length exceeds maxLength.',
+ 'The character counter uses optimisticValue and turns red when it exceeds maxLength.',
+ 'Interaction is blocked during busy state (loading or pending async action) to prevent double-input.',
+ 'Character counter is connected to the textarea via aria-describedby and uses aria-live="polite" for screen reader announcements.',
],
};
@@ -205,15 +229,16 @@ export const docsZh = {
'描述 — 显示在标签和文本域之间的可选文本',
'可选/必填指示器 — 显示带圆点分隔符的"可选"或"必填"文本',
'状态变体 — 警告、错误和成功状态,带彩色边框和图标',
- '字符计数器 — 设置 maxLength 时显示当前/最大长度',
+ '字符计数器 — 设置 maxLength 时显示当前/最大长度(不原生强制限制)',
'起始图标 — 在输入框前端内部渲染的可选图标',
'标签工具提示 — 标签末尾带工具提示的可选信息图标',
'加载状态 — 显示旋转器并通过 useOptimistic 使用乐观更新',
'异步操作支持 — onChangeAction 在 React transition 内于 onChange 之后触发',
'禁用状态 — 视觉透明度和光标变化,无交互',
'无障碍 — 标签通过 htmlFor/id 关联,aria-describedby、aria-required、aria-invalid、aria-busy',
- '可调整大小 — 默认启用垂直调整大小,最小高度 80px',
+ '可调整大小 — 默认启用垂直调整大小',
'拼写检查 — 默认启用浏览器拼写检查,可配置',
+ '减少动画 — 尊重 prefers-reduced-motion 输入包装过渡',
],
examples: [
{
@@ -252,6 +277,11 @@ export const docsZh = {
},
],
props: [
+ {
+ name: 'ref',
+ type: 'React.Ref<HTMLTextAreaElement>',
+ description: '转发至底层 <textarea> 元素的 ref。',
+ },
{
name: 'label',
type: 'string',
@@ -330,7 +360,7 @@ export const docsZh = {
name: 'maxLength',
type: 'number',
description:
- '允许的最大字符数。设置后,在文本域下方显示字符计数器(当前/最大)。',
+ '允许的最大字符数。设置后,在文本域下方显示字符计数器(当前/最大)。不原生强制限制——超出时计数器显示错误样式。',
},
{
name: 'status',
@@ -373,7 +403,22 @@ export const docsZh = {
description:
'文本域元素的 HTML name 属性,用于表单提交。',
},
+ {
+ name: 'onFocus',
+ type: '(e: FocusEvent<HTMLTextAreaElement>) => void',
+ description: '文本域获得焦点时触发的回调。',
+ },
+ {
+ name: 'onBlur',
+ type: '(e: FocusEvent<HTMLTextAreaElement>) => void',
+ description: '文本域失去焦点时触发的回调。',
+ },
],
+ theming: {
+ targets: [
+ {className: 'xds-textarea'},
+ ],
+ },
accessibility: [
'标签始终在 DOM 中渲染;使用 isLabelHidden 视觉上隐藏它,同时保持无障碍性。',
'文本域 id 通过 useId 生成并通过 htmlFor 与其标签关联,确保正确的标签关联。',
@@ -385,9 +430,11 @@ export const docsZh = {
notes: [
'isOptional 和 isRequired 互斥;如果同时设置,"可选"优先。',
'当 onChangeAction 返回 Promise 时,组件使用 useOptimistic 实现即时 UI 反馈。',
- '文本域通过 CSS 启用垂直调整大小,最小高度为 80px。',
+ '文本域通过 CSS 启用垂直调整大小。',
'包装 XDSField 以实现一致的标签、描述和状态消息布局。',
- '当 value.length 超过 maxLength 时,字符计数器文本变为红色。',
+ '字符计数器使用 optimisticValue,超出 maxLength 时变为红色。',
+ '忙碌状态(加载中或异步操作等待中)期间阻止交互,防止重复输入。',
+ '字符计数器通过 aria-describedby 连接到文本域,并使用 aria-live="polite" 进行屏幕阅读器公告。',
],
};
@@ -406,15 +453,18 @@ export const docsDense = {
'Async action support; onChangeAction fires after onChange in React transition',
'Disabled state; visual opacity+cursor changes, no interaction',
'Accessible; label via htmlFor/id, aria-describedby, aria-required, aria-invalid, aria-busy',
- 'Resizable; vertical resize enabled by default, min height 80px',
+ 'Resizable; vertical resize enabled by default',
'Spell check; browser spell checking enabled by default, configurable',
+ 'Reduced motion; respects prefers-reduced-motion for input wrapper transitions',
],
notes: [
'isOptional+isRequired mutually exclusive; both set = "Optional" wins.',
'Uses useOptimistic for instant UI feedback when onChangeAction returns Promise.',
- 'Textarea has vertical resize via CSS w/ min height 80px.',
+ 'Textarea has vertical resize via CSS.',
'Wraps XDSField for consistent label, description, status message layout.',
- 'Character counter text turns red when value.length exceeds maxLength.',
+ 'Character counter uses optimisticValue; turns red when exceeds maxLength.',
+ 'Interaction blocked during busy state to prevent double-input.',
+ 'Counter connected via aria-describedby + aria-live="polite" for screen readers.',
],
accessibility: [
'Label always in DOM; isLabelHidden hides visually, keeps a11y.',
@@ -425,6 +475,7 @@ export const docsDense = {
'aria-busy set during optimistic update or loading state.',
],
propDescriptions: {
+ ref: 'ref forwarded to underlying <textarea>.',
label: 'Label text for textarea; always rendered for a11y.',
value: 'Current textarea value.',
onChange: 'Fired on textarea value change.',
@@ -437,7 +488,7 @@ export const docsDense = {
isLoading: 'Loading state w/ spinner inside input.',
placeholder: 'Placeholder when textarea empty.',
rows: 'Visible text rows.',
- maxLength: 'Max chars allowed. Shows counter (current/max) below textarea.',
+ maxLength: 'Max chars allowed. Shows counter (current/max) below textarea. No native enforcement.',
status: 'Colored border+icon status. Optional floating message below textarea.',
labelTooltip: 'Tooltip in info icon at label end.',
startIcon: 'Icon inside leading edge of textarea wrapper.',
@@ -445,5 +496,7 @@ export const docsDense = {
hasAutoFocus: 'Auto-focus textarea on mount.',
onPaste: 'Fired on paste into textarea.',
htmlName: 'HTML name attr for form submissions.',
+ onFocus: 'Callback on focus.',
+ onBlur: 'Callback on blur.',
},
};
diff --git a/packages/core/src/TextArea/XDSTextArea.test.tsx b/packages/core/src/TextArea/XDSTextArea.test.tsx
index 6eb2762f51..0b988364be 100644
--- a/packages/core/src/TextArea/XDSTextArea.test.tsx
+++ b/packages/core/src/TextArea/XDSTextArea.test.tsx
@@ -7,6 +7,7 @@
* SYNC: When XDSTextArea.tsx changes, update tests to match new behavior
*/
+import React from 'react';
import {describe, it, expect, vi} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -145,6 +146,18 @@ describe('XDSTextArea', () => {
expect(screen.getByRole('textbox')).not.toBeDisabled();
});
+ it('is disabled when isLoading is true (isBusy)', () => {
+ render(
+ <XDSTextArea
+ label="Description"
+ isLoading
+ value=""
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByRole('textbox')).toBeDisabled();
+ });
+
it('does not call onChange when disabled', async () => {
const user = userEvent.setup();
const handleChange = vi.fn();
@@ -429,7 +442,7 @@ describe('XDSTextArea', () => {
expect(screen.getByText('11/100')).toBeInTheDocument();
});
- it('sets maxLength attribute on textarea', () => {
+ it('does not set native maxLength attribute (counter is visual-only)', () => {
render(
<XDSTextArea
label="Description"
@@ -438,13 +451,63 @@ describe('XDSTextArea', () => {
maxLength={50}
/>,
);
- expect(screen.getByRole('textbox')).toHaveAttribute('maxlength', '50');
+ expect(screen.getByRole('textbox')).not.toHaveAttribute('maxlength');
+ expect(screen.getByText('0/50')).toBeInTheDocument();
});
it('does not set maxLength attribute when not provided', () => {
render(<XDSTextArea label="Description" value="" onChange={() => {}} />);
expect(screen.getByRole('textbox')).not.toHaveAttribute('maxlength');
});
+
+ it('counter updates as user types (controlled)', async () => {
+ const user = userEvent.setup();
+ function Wrapper() {
+ const [val, setVal] = React.useState('');
+ return (
+ <XDSTextArea
+ label="Description"
+ value={val}
+ onChange={setVal}
+ maxLength={50}
+ />
+ );
+ }
+ render(<Wrapper />);
+ const textarea = screen.getByRole('textbox');
+ await user.type(textarea, 'Hello');
+ expect(screen.getByText('5/50')).toBeInTheDocument();
+ });
+
+ it('counter has aria-live region for screen reader announcements', () => {
+ render(
+ <XDSTextArea
+ label="Description"
+ value={'x'.repeat(45)}
+ onChange={() => {}}
+ maxLength={50}
+ />,
+ );
+ const liveRegion = document.querySelector('[aria-live="polite"]');
+ expect(liveRegion).toBeInTheDocument();
+ expect(liveRegion).toHaveTextContent('5 characters remaining');
+ });
+
+ it('counter is linked to textarea via aria-describedby', () => {
+ render(
+ <XDSTextArea
+ label="Description"
+ value="Hello"
+ onChange={() => {}}
+ maxLength={50}
+ />,
+ );
+ const textarea = screen.getByRole('textbox');
+ const describedBy = textarea.getAttribute('aria-describedby');
+ const counter = screen.getByText('5/50');
+ expect(counter).toHaveAttribute('id');
+ expect(describedBy).toContain(counter.id);
+ });
});
describe('hasAutoFocus prop', () => {
diff --git a/packages/core/src/TextArea/XDSTextArea.tsx b/packages/core/src/TextArea/XDSTextArea.tsx
index 3e10cadae1..10b5c0b7ba 100644
--- a/packages/core/src/TextArea/XDSTextArea.tsx
+++ b/packages/core/src/TextArea/XDSTextArea.tsx
@@ -2,7 +2,7 @@
/**
* @file XDSTextArea.tsx
- * @input Uses React, useId, ChangeEvent, ClipboardEvent, XDSField, XDSIcon
+ * @input Uses React, useId, ChangeEvent, ClipboardEvent, FocusEvent, XDSField, XDSIcon, XDSSpinner
* @output Exports XDSTextArea component, XDSTextAreaProps, XDSTextAreaStatus, XDSTextAreaStatusType
* @position Core implementation; consumed by index.ts, tested by XDSTextArea.test.tsx
*
@@ -19,6 +19,7 @@ import {
useTransition,
type ChangeEvent,
type ClipboardEvent,
+ type FocusEvent,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {XDSIconName} from '../Icon';
@@ -41,6 +42,8 @@ import {XDSSpinner} from '../Spinner';
import {xdsClassName, mergeProps} from '../utils';
import type {StyleXStyles} from '@stylexjs/stylex';
+const COUNTER_WARNING_THRESHOLD = 0.8;
+
const styles = stylex.create({
wrapper: {
zIndex: 1,
@@ -80,6 +83,29 @@ const styles = stylex.create({
counterError: {
color: colorVars['--color-error'],
},
+ srOnly: {
+ position: 'absolute',
+ width: '1px',
+ height: '1px',
+ padding: 0,
+ margin: '-1px',
+ overflow: 'hidden',
+ clip: 'rect(0,0,0,0)',
+ whiteSpace: 'nowrap',
+ borderWidth: 0,
+ },
+ statusIcon: {
+ position: 'absolute',
+ top: spacingVars['--spacing-2'],
+ insetInlineEnd: spacingVars['--spacing-2'],
+ pointerEvents: 'none',
+ display: 'flex',
+ },
+ textareaWithStatus: {
+ // Reserve space so text doesn't flow under the absolutely-positioned icon.
+ // 20px (icon md) + 4px gap = 24px (--spacing-6)
+ paddingInlineEnd: spacingVars['--spacing-6'],
+ },
});
export type XDSTextAreaStatusType = 'warning' | 'error' | 'success';
@@ -177,6 +203,8 @@ export interface XDSTextAreaProps {
/**
* Maximum number of characters allowed.
* When set, displays a character counter below the textarea.
+ * Does not enforce the limit natively — the counter shows error styling
+ * when exceeded, and the consumer can validate via onChange.
*/
maxLength?: number;
/**
@@ -189,6 +217,14 @@ export interface XDSTextAreaProps {
* Useful for form submissions.
*/
htmlName?: string;
+ /**
+ * Callback fired when the textarea receives focus.
+ */
+ onFocus?: (e: FocusEvent<HTMLTextAreaElement>) => void;
+ /**
+ * Callback fired when the textarea loses focus.
+ */
+ onBlur?: (e: FocusEvent<HTMLTextAreaElement>) => void;
/**
* StyleX styles created via `stylex.create()`. Merged with the component's
* base styles inside a single `stylex.props()` call for optimal deduplication.
@@ -242,6 +278,8 @@ export function XDSTextArea({
maxLength,
hasAutoFocus = false,
htmlName,
+ onFocus,
+ onBlur,
xstyle,
className,
style,
@@ -250,6 +288,7 @@ export function XDSTextArea({
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
+ const counterID = useId();
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
@@ -274,6 +313,7 @@ export function XDSTextArea({
[
description ? descriptionID : null,
status?.message ? statusMessageID : null,
+ maxLength != null ? counterID : null,
]
.filter(Boolean)
.join(' ') || undefined;
@@ -289,6 +329,8 @@ export function XDSTextArea({
}
};
+ const effectivelyDisabled = isDisabled || isBusy;
+
return (
<XDSField
label={label}
@@ -310,11 +352,11 @@ export function XDSTextArea({
labelTooltip={labelTooltip}>
<div
{...mergeProps(
- xdsClassName('text-area'),
+ xdsClassName('textarea'),
stylex.props(
inputWrapperStyles.base,
styles.wrapper,
- isDisabled && inputWrapperStyles.disabled,
+ effectivelyDisabled && inputWrapperStyles.disabled,
status && inputStatusBorderStyles[status.type],
status && inputStatusHoverShadowStyles[status.type],
status && inputStatusFocusWithinStyles[status.type],
@@ -331,37 +373,54 @@ export function XDSTextArea({
value={String(optimisticValue)}
onChange={handleChange}
onPaste={onPaste}
+ onFocus={onFocus}
+ onBlur={onBlur}
placeholder={placeholder}
rows={rows}
- disabled={isDisabled}
+ disabled={effectivelyDisabled}
spellCheck={hasSpellCheck}
- maxLength={maxLength}
autoFocus={hasAutoFocus}
aria-describedby={ariaDescribedBy}
- aria-required={isRequired === true ? 'true' : undefined}
- aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ aria-required={isRequired && !isOptional ? 'true' : undefined}
+ aria-invalid={
+ status?.type === 'error' ||
+ (maxLength != null && optimisticValue.length > maxLength)
+ ? 'true'
+ : undefined
+ }
aria-busy={isBusy || undefined}
{...stylex.props(
styles.textarea,
- isDisabled && styles.textareaDisabled,
+ effectivelyDisabled && styles.textareaDisabled,
+ status && styles.textareaWithStatus,
)}
/>
{isBusy && <XDSSpinner size="sm" />}
{status && (
- <XDSIcon
- icon={statusIconMap[status.type]}
- size="md"
- color={statusIconColorMap[status.type]}
- />
+ <span {...stylex.props(styles.statusIcon)}>
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
+ </span>
)}
</div>
{maxLength != null && (
<div
+ id={counterID}
{...stylex.props(
styles.counter,
- value.length > maxLength && styles.counterError,
+ optimisticValue.length > maxLength && styles.counterError,
)}>
- {value.length}/{maxLength}
+ {optimisticValue.length}/{maxLength}
+ <span aria-live="polite" {...stylex.props(styles.srOnly)}>
+ {optimisticValue.length >= maxLength * COUNTER_WARNING_THRESHOLD
+ ? optimisticValue.length > maxLength
+ ? `${optimisticValue.length - maxLength} characters over limit`
+ : `${maxLength - optimisticValue.length} characters remaining`
+ : ''}
+ </span>
</div>
)}
</XDSField>