An open source design system that's fully customizable and agent ready
TypeScript
XDSTextArea (#48)
Andrey Goder4d432b6171fd
diff --git a/apps/storybook/stories/TextArea.stories.tsx b/apps/storybook/stories/TextArea.stories.tsxnew file mode 100644index 0000000000..bdc7fab835--- /dev/null+++ b/apps/storybook/stories/TextArea.stories.tsx@@ -0,0 +1,246 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSTextArea} from '@xds/core/TextArea';++const meta: Meta<typeof XDSTextArea> = {+ title: 'Core/XDSTextArea',+ component: XDSTextArea,+ tags: ['autodocs'],+ argTypes: {+ label: {+ control: 'text',+ description: 'Label text (required)',+ },+ isLabelHidden: {+ control: 'boolean',+ description:+ 'Visually hide the label (still accessible to screen readers)',+ },+ placeholder: {+ control: 'text',+ description: 'Placeholder text',+ },+ description: {+ control: 'text',+ description: 'Description text displayed between the label and textarea',+ },+ value: {+ control: 'text',+ description: 'Current textarea value (required)',+ },+ isOptional: {+ control: 'boolean',+ description:+ 'Whether the field is optional (mutually exclusive with isRequired)',+ },+ isRequired: {+ control: 'boolean',+ description:+ 'Whether the field is required (mutually exclusive with isOptional)',+ },+ rows: {+ control: 'number',+ description: 'Number of visible text rows (default: 3)',+ },+ isDisabled: {+ control: 'boolean',+ description: 'Whether the textarea is disabled',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSTextArea>;++export const Default: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Description',+ placeholder: 'Enter a description...',+ },+};++export const WithDescription: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Bio',+ description: 'Tell us about yourself in a few sentences.',+ placeholder: 'Write your bio here...',+ },+};++export const WithHiddenLabel: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Comments',+ isLabelHidden: true,+ placeholder: 'Add a comment...',+ },+};++export const WithValue: Story = {+ render: args => {+ const [value, setValue] = useState(+ args.value ??+ 'This is a pre-filled textarea with some content that demonstrates how the component handles existing text.',+ );+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Notes',+ value:+ 'This is a pre-filled textarea with some content that demonstrates how the component handles existing text.',+ },+};++export const CustomRows: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Message',+ rows: 6,+ placeholder: 'Write a longer message...',+ },+};++export const AllVariations: Story = {+ render: () => {+ const [value1, setValue1] = useState('');+ const [value2, setValue2] = useState('');+ const [value3, setValue3] = useState('Pre-filled content in the textarea.');+ const [value4, setValue4] = useState('');+ const [value5, setValue5] = useState('');+ const [value6, setValue6] = useState('');+ const [value7, setValue7] = useState('');+ const [value8, setValue8] = useState('');+ const [value9, setValue9] = useState('This field is disabled');+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '400px',+ }}>+ <XDSTextArea+ label="Visible label"+ value={value1}+ onChange={setValue1}+ placeholder="Enter text..."+ />+ <XDSTextArea+ label="With description"+ description="Helpful description text"+ value={value4}+ onChange={setValue4}+ placeholder="Enter text..."+ />+ <XDSTextArea+ label="Hidden label"+ isLabelHidden+ value={value2}+ onChange={setValue2}+ placeholder="Hidden label textarea"+ />+ <XDSTextArea label="With value" value={value3} onChange={setValue3} />+ <XDSTextArea+ label="Optional field"+ isOptional+ value={value5}+ onChange={setValue5}+ placeholder="Optional..."+ />+ <XDSTextArea+ label="Required field"+ isRequired+ value={value6}+ onChange={setValue6}+ placeholder="Required..."+ />+ <XDSTextArea+ label="Description with optional"+ description="Additional notes"+ isOptional+ value={value7}+ onChange={setValue7}+ placeholder="Notes..."+ />+ <XDSTextArea+ label="Custom rows (6)"+ rows={6}+ value={value8}+ onChange={setValue8}+ placeholder="Larger textarea..."+ />+ <XDSTextArea+ label="Disabled field"+ isDisabled+ value={value9}+ onChange={setValue9}+ />+ </div>+ );+ },+};++export const OptionalField: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Additional Notes',+ isOptional: true,+ placeholder: 'Any additional notes...',+ },+};++export const RequiredField: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Feedback',+ isRequired: true,+ placeholder: 'Please provide your feedback...',+ },+};++export const DescriptionWithOptional: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? '');+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Comments',+ description: 'Share any additional thoughts or comments',+ isOptional: true,+ placeholder: 'Your comments here...',+ },+};++export const Disabled: Story = {+ render: args => {+ const [value, setValue] = useState(+ args.value ?? 'This textarea is disabled and cannot be edited.',+ );+ return <XDSTextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Disabled Field',+ isDisabled: true,+ value: 'This textarea is disabled and cannot be edited.',+ },+};diff --git a/packages/core/src/TextArea/README.md b/packages/core/src/TextArea/README.mdnew file mode 100644index 0000000000..4c6bd0473c--- /dev/null+++ b/packages/core/src/TextArea/README.md@@ -0,0 +1,78 @@+# /packages/core/src/TextArea++A multi-line text input component for collecting longer user input.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Label Support**: Required label for accessibility (can be visually hidden)+- **Description**: Optional description text displayed between the label and textarea+- **Optional/Required Indicators**: Display "Optional" or "Required" text with bullet separator+- **Disabled State**: Support for disabled textarea with visual styling+- **Accessible**: Label properly associated with textarea via htmlFor/id+- **Styled with StyleX**: Uses XDS design tokens for consistent styling+- **Resizable**: Vertical resize enabled by default with a minimum height++## Usage++```tsx+import { XDSTextArea } from '@xds/core/TextArea';++// Basic textarea with label+<XDSTextArea label="Description" value={description} onChange={setDescription} />++// With placeholder+<XDSTextArea label="Notes" value={notes} onChange={setNotes} placeholder="Enter your notes..." />++// With custom rows+<XDSTextArea label="Message" rows={5} value={message} onChange={setMessage} />++// Hidden label (for screen readers only)+<XDSTextArea label="Comments" isLabelHidden value={comments} onChange={setComments} placeholder="Add a comment..." />++// With description+<XDSTextArea label="Bio" description="Tell us about yourself" value={bio} onChange={setBio} />++// Optional field+<XDSTextArea label="Additional Notes" isOptional value={notes} onChange={setNotes} />++// Required field+<XDSTextArea label="Feedback" isRequired value={feedback} onChange={setFeedback} />++// Disabled field+<XDSTextArea label="Disabled" isDisabled value="Cannot edit this" onChange={setDisabled} />+```++## Props++| Prop | Type | Required | Description |+| --------------- | -------------------------------------------------------------- | -------- | ------------------------------------------------------------------ |+| `label` | `string` | Yes | Label text for the textarea (always rendered for accessibility) |+| `value` | `string` | Yes | Current value of the textarea |+| `onChange` | `(value: string, e: ChangeEvent<HTMLTextAreaElement>) => void` | Yes | Callback fired when textarea value changes |+| `isLabelHidden` | `boolean` | No | Visually hide the label (still accessible to screen readers) |+| `description` | `string` | No | Description text displayed between the label and textarea |+| `isOptional` | `boolean` | No | Whether the field is optional (mutually exclusive with isRequired) |+| `isRequired` | `boolean` | No | Whether the field is required (mutually exclusive with isOptional) |+| `placeholder` | `string` | No | Placeholder text |+| `rows` | `number` | No | Number of visible text rows (default: 3) |+| `isDisabled` | `boolean` | No | Whether the textarea is disabled (default: false) |++## Files++| File | Role | Purpose |+| ---------------------- | ----- | --------------------------- |+| `index.ts` | Entry | Exports component and types |+| `XDSTextArea.tsx` | Core | Component implementation |+| `XDSTextArea.test.tsx` | Test | Unit tests |++## Implementation Notes++- Uses `useId` hook for accessible label-textarea association+- Label is always rendered for accessibility; use `isLabelHidden` to hide visually+- Hidden label uses CSS technique that remains accessible to screen readers+- Wraps `XDSField` component for label, description, and optional/required handling+- `isOptional` and `isRequired` are mutually exclusive; setting both will show "Optional"+- Optional/Required text appears on the same line as the label+- Textarea has vertical resize enabled with a minimum height of 80pxdiff --git a/packages/core/src/TextArea/XDSTextArea.test.tsx b/packages/core/src/TextArea/XDSTextArea.test.tsxnew file mode 100644index 0000000000..84814c0416--- /dev/null+++ b/packages/core/src/TextArea/XDSTextArea.test.tsx@@ -0,0 +1,163 @@+/**+ * @file XDSTextArea.test.tsx+ * @input Uses vitest, @testing-library/react, XDSTextArea component+ * @output Unit tests for XDSTextArea component behavior+ * @position Testing; validates XDSTextArea.tsx implementation+ *+ * SYNC: When XDSTextArea.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {XDSTextArea} from './XDSTextArea';++describe('XDSTextArea', () => {+ it('renders with label', () => {+ render(<XDSTextArea label="Description" value="" onChange={() => {}} />);+ expect(screen.getByLabelText('Description')).toBeInTheDocument();+ });++ it('renders with placeholder', () => {+ render(+ <XDSTextArea+ label="Description"+ value=""+ onChange={() => {}}+ placeholder="Enter description"+ />,+ );+ expect(+ screen.getByPlaceholderText('Enter description'),+ ).toBeInTheDocument();+ });++ it('calls onChange with value and event when typing', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSTextArea label="Description" value="" onChange={handleChange} />,+ );++ const textarea = screen.getByRole('textbox');+ await user.type(textarea, 'Hi');+ expect(handleChange).toHaveBeenCalledTimes(2);+ expect(handleChange).toHaveBeenLastCalledWith('i', expect.any(Object));+ });++ it('works with state setter function directly', async () => {+ const user = userEvent.setup();+ const setValue = vi.fn();+ render(<XDSTextArea label="Description" value="" onChange={setValue} />);++ const textarea = screen.getByRole('textbox');+ await user.type(textarea, 'A');+ expect(setValue).toHaveBeenCalledWith('A', expect.any(Object));+ });++ it('displays controlled value', () => {+ render(+ <XDSTextArea+ label="Description"+ value="Controlled value"+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('textbox')).toHaveValue('Controlled value');+ });++ it('forwards ref correctly', () => {+ const ref = vi.fn();+ render(+ <XDSTextArea+ ref={ref}+ label="Description"+ value=""+ onChange={() => {}}+ />,+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLTextAreaElement));+ });++ it('visually hides label when isLabelHidden is true', () => {+ render(+ <XDSTextArea+ label="Comments"+ isLabelHidden+ value=""+ onChange={() => {}}+ />,+ );+ const label = screen.getByText('Comments');+ expect(label).toBeInTheDocument();+ // Label should still be accessible+ expect(screen.getByLabelText('Comments')).toBeInTheDocument();+ });++ it('shows label visually by default', () => {+ render(<XDSTextArea label="Notes" value="" onChange={() => {}} />);+ const label = screen.getByText('Notes');+ expect(label).toBeVisible();+ });++ it('sets aria-required when isRequired is true', () => {+ render(+ <XDSTextArea label="Feedback" isRequired value="" onChange={() => {}} />,+ );+ expect(screen.getByRole('textbox')).toHaveAttribute(+ 'aria-required',+ 'true',+ );+ });++ it('does not set aria-required when isRequired is false', () => {+ render(<XDSTextArea label="Feedback" value="" onChange={() => {}} />);+ expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-required');+ });++ it('renders with custom rows', () => {+ render(+ <XDSTextArea label="Description" value="" onChange={() => {}} rows={5} />,+ );+ expect(screen.getByRole('textbox')).toHaveAttribute('rows', '5');+ });++ it('renders with default rows of 3', () => {+ render(<XDSTextArea label="Description" value="" onChange={() => {}} />);+ expect(screen.getByRole('textbox')).toHaveAttribute('rows', '3');+ });++ it('is disabled when isDisabled is true', () => {+ render(+ <XDSTextArea+ label="Description"+ isDisabled+ value=""+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('textbox')).toBeDisabled();+ });++ it('is not disabled by default', () => {+ render(<XDSTextArea label="Description" value="" onChange={() => {}} />);+ expect(screen.getByRole('textbox')).not.toBeDisabled();+ });++ it('does not call onChange when disabled', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSTextArea+ label="Description"+ isDisabled+ value=""+ onChange={handleChange}+ />,+ );++ const textarea = screen.getByRole('textbox');+ await user.type(textarea, 'Hi');+ expect(handleChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/TextArea/XDSTextArea.tsx b/packages/core/src/TextArea/XDSTextArea.tsxnew file mode 100644index 0000000000..603ddea82a--- /dev/null+++ b/packages/core/src/TextArea/XDSTextArea.tsx@@ -0,0 +1,171 @@+/**+ * @file XDSTextArea.tsx+ * @input Uses React forwardRef, useId, ChangeEvent, XDSField+ * @output Exports XDSTextArea component, XDSTextAreaProps+ * @position Core implementation; consumed by index.ts, tested by XDSTextArea.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/TextArea/README.md (props table, features, implementation notes)+ * - /packages/core/src/TextArea/XDSTextArea.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/TextArea/index.ts (exports if types change)+ * - /apps/storybook/stories/TextArea.stories.tsx (storybook stories)+ */++import {forwardRef, useId, type ChangeEvent} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ spacingVars,+ radiusVars,+ transitionVars,+ typographyVars,+} from '../theme/tokens.stylex';+import {XDSField} from '../Field';++const styles = stylex.create({+ textarea: {+ display: 'block',+ width: '100%',+ paddingBlock: spacingVars['--spacing-2'],+ paddingInline: spacingVars['--spacing-3'],+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: {+ default: colorVars['--color-divider-emphasized'],+ ':hover': colorVars['--color-divider-high-contrast'],+ },+ borderRadius: radiusVars['--radius-element'],+ fontFamily: typographyVars['--font-body'],+ fontSize: '0.875rem',+ lineHeight: 1.429,+ color: colorVars['--color-text-primary'],+ backgroundColor: colorVars['--color-surface'],+ transitionProperty: 'border-color, outline',+ transitionDuration: transitionVars['--transition-fast'],+ outline: {+ default: 'none',+ ':focus': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus': '1px',+ },+ '::placeholder': {+ color: colorVars['--color-text-placeholder'],+ },+ resize: 'vertical',+ minHeight: '80px',+ },+ disabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ borderColor: {+ default: colorVars['--color-divider-emphasized'],+ ':hover': colorVars['--color-divider-emphasized'],+ },+ },+});++export interface XDSTextAreaProps {+ /**+ * Label text for the textarea (always rendered for accessibility).+ */+ label: string;+ /**+ * Whether to visually hide the label (still accessible to screen readers).+ * @default false+ */+ isLabelHidden?: boolean;+ /**+ * Description text displayed between the label and textarea.+ */+ description?: string;+ /**+ * Whether the field is optional. Mutually exclusive with isRequired.+ * @default false+ */+ isOptional?: boolean;+ /**+ * Whether the field is required. Mutually exclusive with isOptional.+ * @default false+ */+ isRequired?: boolean;+ /**+ * Callback fired when the textarea value changes.+ */+ onChange: (value: string, e: ChangeEvent<HTMLTextAreaElement>) => void;+ /**+ * The current value of the textarea.+ */+ value: string;+ /**+ * Placeholder text shown when the textarea is empty.+ */+ placeholder?: string;+ /**+ * The number of visible text rows.+ * @default 3+ */+ rows?: number;+ /**+ * Whether the textarea is disabled.+ * @default false+ */+ isDisabled?: boolean;+}++/**+ * A multi-line text input component for collecting longer user input.+ *+ * @example+ * ```tsx+ * <XDSTextArea label="Description" value={description} onChange={setDescription} />+ * <XDSTextArea label="Notes" rows={5} value={notes} onChange={setNotes} />+ * ```+ */+export const XDSTextArea = forwardRef<HTMLTextAreaElement, XDSTextAreaProps>(+ (+ {+ label,+ isLabelHidden = false,+ description,+ isOptional = false,+ isRequired = false,+ onChange,+ value,+ placeholder,+ rows = 3,+ isDisabled = false,+ },+ ref,+ ) => {+ const id = useId();+ const descriptionID = useId();++ return (+ <XDSField+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={id}+ descriptionID={description ? descriptionID : undefined}+ isOptional={isOptional}+ isRequired={isRequired}>+ <textarea+ ref={ref}+ id={id}+ value={value}+ onChange={e => onChange(e.target.value, e)}+ placeholder={placeholder}+ rows={rows}+ disabled={isDisabled}+ aria-describedby={description ? descriptionID : undefined}+ aria-required={isRequired === true ? 'true' : undefined}+ {...stylex.props(styles.textarea, isDisabled && styles.disabled)}+ />+ </XDSField>+ );+ },+);++XDSTextArea.displayName = 'XDSTextArea';diff --git a/packages/core/src/TextArea/index.ts b/packages/core/src/TextArea/index.tsnew file mode 100644index 0000000000..53b64f92d1--- /dev/null+++ b/packages/core/src/TextArea/index.ts@@ -0,0 +1,11 @@+/**+ * @file index.ts+ * @input Imports XDSTextArea component and types from XDSTextArea.tsx+ * @output Exports XDSTextArea, XDSTextAreaProps+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/TextArea/README.md+ */++export {XDSTextArea} from './XDSTextArea';+export type {XDSTextAreaProps} from './XDSTextArea';diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsxindex a6b478b63d..3001af0f6c 100644--- a/packages/core/src/TextInput/XDSTextInput.tsx+++ b/packages/core/src/TextInput/XDSTextInput.tsx@@ -34,7 +34,7 @@ const styles = stylex.create({default: colorVars['--color-divider-emphasized'],':hover': colorVars['--color-divider-high-contrast'],},- borderRadius: radiusVars['--radius-content'],+ borderRadius: radiusVars['--radius-element'],fontFamily: typographyVars['--font-body'],fontSize: '0.875rem',lineHeight: 1.429,diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 33d130c1ca..8dcb57158d 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -13,6 +13,7 @@ export * from './Button';export * from './CheckboxInput';export * from './Field';export * from './TextInput';+export * from './TextArea';// Layout utilities and components (includes XDSHStack, XDSVStack)export * from './Layout';