An open source design system that's fully customizable and agent ready
TypeScript
fix(textarea): span full container; move character counter inside (#4233) (#4533)
Cindy Zhangc366298986b5
diff --git a/.changeset/textarea-full-span-counter.md b/.changeset/textarea-full-span-counter.mdnew file mode 100644index 0000000000..c19ced01bb--- /dev/null+++ b/.changeset/textarea-full-span-counter.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] TextArea: the `<textarea>` now spans the full input container, with icons, status/spinner, and the character counter as absolutely-positioned overlays. The native resize grip sits in the container's bottom-right corner and the scrollbar covers the whole field. The `maxLength` counter moved inside the container, anchored bottom-right beneath the text (#4233).+@cixzhangdiff --git a/apps/storybook/stories/TextArea.stories.tsx b/apps/storybook/stories/TextArea.stories.tsxindex ee55a25e41..d3932bc3c5 100644--- a/apps/storybook/stories/TextArea.stories.tsx+++ b/apps/storybook/stories/TextArea.stories.tsx@@ -4,6 +4,8 @@ import {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {TextArea} from '@astryxdesign/core/TextArea';import {TextInput} from '@astryxdesign/core/TextInput';+import {Selector} from '@astryxdesign/core/Selector';+import {FormLayout} from '@astryxdesign/core/FormLayout';import {DocumentTextIcon,ChatBubbleLeftIcon,@@ -483,6 +485,56 @@ export const TooltipWithOptional: Story = {},};+export const Loading: Story = {+ render: args => {+ const [value, setValue] = useState(args.value ?? 'Saving your changes…');+ return <TextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Description',+ placeholder: 'Enter a description...',+ isLoading: true,+ },+};++// The loading spinner and status icon share the end slot and render side by+// side (matching TextInput/DateInput/TimeInput), not mutually exclusively.+// Toggle isLoading to see the spinner appear beside the status icon.+export const LoadingWithStatus: Story = {+ render: () => {+ const [value, setValue] = useState('Too short');+ const [isLoading, setIsLoading] = useState(true);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: 12,+ width: 360,+ }}>+ <label style={{display: 'flex', alignItems: 'center', gap: 8}}>+ <input+ type="checkbox"+ checked={isLoading}+ onChange={e => setIsLoading(e.target.checked)}+ />+ isLoading+ </label>+ <TextArea+ label="Description"+ value={value}+ onChange={setValue}+ isLoading={isLoading}+ status={{+ type: 'error',+ message: 'Description must be at least 50 characters',+ }}+ />+ </div>+ );+ },+};+export const CombinedFeatures: Story = {render: () => {const [value, setValue] = useState('');@@ -595,6 +647,23 @@ export const MaxLengthWithValue: Story = {},};+// When the value exceeds maxLength the counter turns red AND shows a warning+// icon, so the over-limit state isn't conveyed by color alone (WCAG 1.4.1).+// Screen-reader users hear the over-limit count announced as they type.+export const MaxLengthOverLimit: Story = {+ render: args => {+ const [value, setValue] = useState(+ args.value ??+ 'This bio is intentionally longer than the limit to show the over-limit state.',+ );+ return <TextArea {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Bio',+ maxLength: 50,+ },+};+export const MaxLengthVariations: Story = {render: () => {const [short, setShort] = useState('');@@ -641,7 +710,8 @@ export const StatusVariantComparison: Story = {const [a, setA] = useState('Too short');const [b, setB] = useState('Too short');return (- <div style={{display: 'flex', flexDirection: 'column', gap: 24, width: 320}}>+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 24, width: 320}}><TextArealabel="Attached (default)"value={a}@@ -659,3 +729,48 @@ export const StatusVariantComparison: Story = {);},};++// TextArea composed with other inputs in a vertical FormLayout, to validate+// that its label, control edges, and internal content align with sibling+// inputs (TextInput, Selector) now that the textarea spans the full container.+export const VerticalFormAlignment: Story = {+ name: 'Vertical Form Alignment',+ render: () => {+ const [name, setName] = useState('');+ const [visibility, setVisibility] = useState('public');+ const [summary, setSummary] = useState('');+ const [bio, setBio] = useState('Design systems engineer.');+ return (+ <div style={{width: 360}}>+ <FormLayout>+ <TextInput label="Display name" value={name} onChange={setName} />+ <Selector+ label="Visibility"+ value={visibility}+ onChange={v => setVisibility(v as string)}+ options={[+ {label: 'Public', value: 'public'},+ {label: 'Followers only', value: 'followers'},+ {label: 'Private', value: 'private'},+ ]}+ />+ <TextArea+ label="Summary"+ value={summary}+ onChange={setSummary}+ placeholder="A short one-liner"+ maxLength={80}+ />+ <TextArea+ label="Bio"+ value={bio}+ onChange={setBio}+ rows={4}+ description="Tell people a bit about yourself."+ maxLength={200}+ />+ </FormLayout>+ </div>+ );+ },+};diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 0a7ed670e2..9c4b611100 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -883,6 +883,14 @@"defaultMessage": "Expand all rows","description": "Aria label for the Table tree-data header toggle when rows are collapsed and clicking it expands them."},+ "@astryx.textArea.charactersRemaining": {+ "defaultMessage": "{count, number} {count, plural, one {character} other {characters}} remaining",+ "description": "Screen-reader-only announcement of how many characters the user can still type before hitting a TextArea's maxLength. Announced politely as the count nears the limit. `{count}` is the number remaining — example: `12 characters remaining`."+ },+ "@astryx.textArea.charactersOverLimit": {+ "defaultMessage": "{count, number} {count, plural, one {character} other {characters}} over the limit",+ "description": "Screen-reader-only assertive announcement when the user has typed past a TextArea's maxLength. `{count}` is how many characters over — example: `3 characters over the limit`."+ },"@astryx.textInput.clearLabel": {"defaultMessage": "Clear {label}","description": "Screen-reader-only label on the X that clears the value from a TextInput. Example: `Clear Email`, `Clear Name`."diff --git a/packages/core/src/TextArea/TextArea.doc.mjs b/packages/core/src/TextArea/TextArea.doc.mjsindex 1f53cc1490..0f953b544a 100644--- a/packages/core/src/TextArea/TextArea.doc.mjs+++ b/packages/core/src/TextArea/TextArea.doc.mjs@@ -98,7 +98,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. Does not enforce the limit natively; the counter shows error styling when exceeded.',+ 'Maximum number of characters allowed. When set, a character counter (current/max) is displayed inside the input container, anchored to the bottom-right beneath the text. Does not enforce the limit natively; when exceeded the counter turns red and shows a warning icon (a non-color cue), and screen-reader users hear the remaining/over-limit count announced.',},{name: 'status',@@ -407,7 +407,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. No native enforcement.',+ maxLength: 'Max chars allowed. Shows counter (current/max) inside the container, bottom-right beneath the text. No native enforcement; over-limit shows red + a warning icon and is announced to screen readers.',status: 'Colored border+icon status. Optional floating message below textarea.',statusVariant: 'How status message is placed: attached overlaps below input; detached floats below w/ spacing; tooltip hides the box and shows it on the status icon.',labelTooltip: 'Tooltip in info icon at label end.',diff --git a/packages/core/src/TextArea/TextArea.test.tsx b/packages/core/src/TextArea/TextArea.test.tsxindex 667f33cbb8..e018a65bb6 100644--- a/packages/core/src/TextArea/TextArea.test.tsx+++ b/packages/core/src/TextArea/TextArea.test.tsx@@ -335,6 +335,23 @@ describe('TextArea', () => {expect(messageElement).toHaveAttribute('id');expect(describedBy).toContain(messageElement.id);});++ it('shows both the loading spinner and the status icon while busy', () => {+ const {container} = render(+ <TextArea+ label="Description"+ value=""+ onChange={() => {}}+ isLoading+ status={{type: 'error'}}+ />,+ );+ // Matches the other inputs: spinner (role="status") and the status icon+ // render side by side in the end slot, not mutually exclusively.+ expect(screen.getByRole('status')).toBeInTheDocument();+ // Status icon svg is also present alongside the spinner.+ expect(container.querySelectorAll('svg').length).toBeGreaterThan(0);+ });});it('renders tooltip info icon when labelTooltip is provided', () => {@@ -506,7 +523,70 @@ describe('TextArea', () => {expect(screen.getByText('5/50')).toBeInTheDocument();});- it('counter has aria-live region for screen reader announcements', () => {+ it('announces remaining characters politely as the value nears the limit', async () => {+ const user = userEvent.setup();+ function Wrapper() {+ const [val, setVal] = useState('x'.repeat(44));+ return (+ <TextArea+ label="Description"+ value={val}+ onChange={setVal}+ maxLength={50}+ />+ );+ }+ render(<Wrapper />);+ // Type one more char to cross into the "near the limit" zone (45/50).+ await user.type(screen.getByRole('textbox'), 'x');+ const politeRegion = () =>+ document.querySelector('[data-astryx-live-region="polite"]');+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('5 characters remaining');+ });+ });++ it('announces over-limit assertively once the value exceeds the max', async () => {+ const user = userEvent.setup();+ function Wrapper() {+ const [val, setVal] = useState('x'.repeat(50));+ return (+ <TextArea+ label="Description"+ value={val}+ onChange={setVal}+ maxLength={50}+ />+ );+ }+ render(<Wrapper />);+ await user.type(screen.getByRole('textbox'), 'x');+ const assertiveRegion = () =>+ document.querySelector('[data-astryx-live-region="assertive"]');+ await waitFor(() => {+ expect(assertiveRegion()).toHaveTextContent(+ '1 character over the limit',+ );+ });+ });++ it('shows a non-color over-limit indicator icon when exceeded', () => {+ const {container} = render(+ <TextArea+ label="Description"+ value={'x'.repeat(55)}+ onChange={() => {}}+ maxLength={50}+ />,+ );+ // The counter renders a warning icon (a shape cue) alongside the red+ // count, so the over-limit state is not conveyed by color alone.+ const counter = screen.getByText('55/50').closest('div');+ expect(counter?.querySelector('svg')).toBeInTheDocument();+ expect(container).toBeInTheDocument();+ });++ it('does not show the over-limit indicator icon within the limit', () => {render(<TextArealabel="Description"@@ -515,9 +595,8 @@ describe('TextArea', () => {maxLength={50}/>,);- const liveRegion = document.querySelector('[aria-live="polite"]');- expect(liveRegion).toBeInTheDocument();- expect(liveRegion).toHaveTextContent('5 characters remaining');+ const counter = screen.getByText('45/50').closest('div');+ expect(counter?.querySelector('svg')).not.toBeInTheDocument();});it('counter is linked to textarea via aria-describedby', () => {@@ -535,6 +614,22 @@ describe('TextArea', () => {expect(counter).toHaveAttribute('id');expect(describedBy).toContain(counter.id);});++ it('renders the counter inside the input container (same wrapper as textarea)', () => {+ render(+ <TextArea+ label="Description"+ value="Hello"+ onChange={() => {}}+ maxLength={50}+ />,+ );+ const textarea = screen.getByRole('textbox');+ const counter = screen.getByText('5/50');+ // The counter now lives inside the bordered input container as a sibling+ // overlay of the textarea, not below it as an out-of-container element.+ expect(textarea.parentElement).toBe(counter.parentElement);+ });});describe('hasAutoFocus prop', () => {@@ -737,11 +832,15 @@ describe('TextArea', () => {});});-describe('TextArea statusVariant forwarding', () => {it('defaults to attached (status renders with data-variant="attached")', () => {const {container} = render(- <TextArea label="Bio" value="" onChange={() => {}} status={{type: 'error', message: 'Required'}} />,+ <TextArea+ label="Bio"+ value=""+ onChange={() => {}}+ status={{type: 'error', message: 'Required'}}+ />,);expect(container.querySelector('.astryx-field-status')).toHaveAttribute('data-variant',@@ -751,7 +850,13 @@ describe('TextArea statusVariant forwarding', () => {it('forwards statusVariant="detached" to the underlying Field status', () => {const {container} = render(- <TextArea label="Bio" value="" onChange={() => {}} status={{type: 'error', message: 'Required'}} statusVariant="detached" />,+ <TextArea+ label="Bio"+ value=""+ onChange={() => {}}+ status={{type: 'error', message: 'Required'}}+ statusVariant="detached"+ />,);expect(container.querySelector('.astryx-field-status')).toHaveAttribute('data-variant',diff --git a/packages/core/src/TextArea/TextArea.tsx b/packages/core/src/TextArea/TextArea.tsxindex 81ca58a250..42ff6d09dd 100644--- a/packages/core/src/TextArea/TextArea.tsx+++ b/packages/core/src/TextArea/TextArea.tsx@@ -21,6 +21,7 @@ import {useOptimistic,useTransition,useRef,+ useCallback,type ChangeEvent,type ClipboardEvent,type FocusEvent,@@ -41,7 +42,7 @@ import {inputStatusFocusWithinStyles,type FieldStatusVariant,} from '../Field';-import {renderIconSlot, type IconType} from '../Icon';+import {Icon, renderIconSlot, type IconType} from '../Icon';import {Spinner} from '../Spinner';import {useTooltip} from '../Tooltip';import {mergeProps, mergeRefs} from '../utils';@@ -49,25 +50,39 @@ import type {BaseProps} from '../BaseProps';import type {SizeValue} from '../utils/types';import {useInputContainer} from '../hooks/useInputContainer';import {useInputStatusIcon} from '../hooks/useInputStatusIcon';+import {useAnnounce} from '../hooks/useAnnounce';import {useSize} from '../SizeContext/SizeContext';import {themeProps} from '../utils/themeProps';-import {VisuallyHidden} from '../VisuallyHidden';+import {useTranslator} from '../i18n';const COUNTER_WARNING_THRESHOLD = 0.8;const styles = stylex.create({+ // The wrapper is a bare positioning context. The <textarea> spans the full+ // container and carries its own internal padding; icons, status/spinner, and+ // the character counter are absolutely-positioned overlays anchored to the+ // container corners. This keeps the native resize grip in the true+ // bottom-right corner and lets the scrollbar represent the full input area.wrapper: {zIndex: 1,- alignItems: 'flex-start',- paddingBlock: spacingVars['--spacing-1'],+ display: 'block',+ padding: 0,+ // Internal inline padding for the textarea's text. Defined on the wrapper+ // so the counter (a sibling overlay) inherits the same value and stays+ // aligned with the text edge. Kept as an internal var so it can later be+ // driven by a theme "padding" translation without touching either child.+ '--_textarea-inline-padding': spacingVars['--spacing-2'],},textarea: {display: 'block',- flex: 1,+ width: '100%',+ boxSizing: 'border-box',minWidth: 0,borderWidth: 0,borderStyle: 'none',- padding: 0,+ // Base internal padding; overlays get their own reserved space below.+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: 'var(--_textarea-inline-padding)',fontFamily: typographyVars['--font-family-body'],fontSize: {default: typeScaleVars['--text-body-size'],@@ -85,29 +100,59 @@ const styles = stylex.create({textareaDisabled: {cursor: 'not-allowed',},+ // Reserve start padding so text clears the start icon.+ // inline inset + 16px icon (sm) + 8px gap+ textareaWithStartIcon: {+ paddingInlineStart: `calc(var(--_textarea-inline-padding) + ${spacingVars['--spacing-6']})`,+ },+ // Reserve end padding so text clears the status icon / spinner overlay.+ // inline inset + 20px icon (md) + 4px gap+ textareaWithStatus: {+ paddingInlineEnd: `calc(var(--_textarea-inline-padding) + ${spacingVars['--spacing-6']})`,+ },+ // Reserve wider end padding when the spinner AND status icon both show.+ // inline inset + 16px spinner + 8px gap + 20px icon + 4px gap+ textareaWithBusyStatus: {+ paddingInlineEnd: `calc(var(--_textarea-inline-padding) + ${spacingVars['--spacing-12']})`,+ },+ // Reserve bottom padding so text clears the character counter overlay.+ textareaWithCounter: {+ paddingBottom: spacingVars['--spacing-7'],+ },+ startIcon: {+ position: 'absolute',+ top: spacingVars['--spacing-2'],+ insetInlineStart: 'var(--_textarea-inline-padding)',+ pointerEvents: 'none',+ display: 'flex',+ },+ endSlot: {+ position: 'absolute',+ top: spacingVars['--spacing-2'],+ insetInlineEnd: 'var(--_textarea-inline-padding)',+ pointerEvents: 'none',+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ },+ // Character counter lives inside the input container, anchored bottom-right+ // underneath the textarea, aligned to the same inline inset as the text.counter: {+ position: 'absolute',+ bottom: spacingVars['--spacing-1'],+ insetInlineEnd: 'var(--_textarea-inline-padding)',+ pointerEvents: 'none',display: 'flex',- justifyContent: 'flex-end',- marginTop: spacingVars['--spacing-1'],+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],fontFamily: typographyVars['--font-family-body'],fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],color: colorVars['--color-text-secondary'],},counterError: {color: colorVars['--color-error'],},- 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'],- },});const textareaSizeStyles = stylex.create({@@ -326,12 +371,17 @@ export function TextArea({...rest}: TextAreaProps) {const size = useSize(sizeProp, 'md');+ const t = useTranslator();+ const announce = useAnnounce();const id = useId();const descriptionID = useId();const statusMessageID = useId();const counterID = useId();const textareaRef = useRef<HTMLTextAreaElement | null>(null);const containerRef = useRef<HTMLDivElement | null>(null);+ // Tracks the counter "zone" last announced (under / near / over) so we only+ // announce on a zone change, not on every keystroke.+ const counterZoneRef = useRef<'under' | 'near' | 'over' | null>(null);const [, startTransition] = useTransition();const [optimisticValue, setOptimisticValue] = useOptimistic(value);@@ -370,6 +420,43 @@ export function TextArea({.filter(Boolean).join(' ') || undefined;+ // Announce the character-count status through the shared live region, but+ // only when the value crosses into a new zone (near the limit / over the+ // limit) so we don't speak on every keystroke. Over-limit is assertive (an+ // error the user should hear immediately); nearing the limit is polite.+ const announceCounter = useCallback(+ (length: number) => {+ if (maxLength == null) {+ return;+ }+ const zone: 'under' | 'near' | 'over' =+ length > maxLength+ ? 'over'+ : length >= maxLength * COUNTER_WARNING_THRESHOLD+ ? 'near'+ : 'under';+ if (zone === counterZoneRef.current) {+ return;+ }+ counterZoneRef.current = zone;+ if (zone === 'over') {+ announce(+ t('@astryx.textArea.charactersOverLimit', {+ count: length - maxLength,+ }),+ 'assertive',+ );+ } else if (zone === 'near') {+ announce(+ t('@astryx.textArea.charactersRemaining', {+ count: maxLength - length,+ }),+ );+ }+ },+ [announce, t, maxLength],+ );+const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {// Value can't change while showing a disabled message (the field is// read-only and non-native-disabled), but guard the handler too so the@@ -378,6 +465,7 @@ export function TextArea({return;}const newValue = e.target.value;+ announceCounter(newValue.length);onChange?.(newValue, e);if (changeAction && !e.defaultPrevented) {startTransition(async () => {@@ -434,20 +522,20 @@ export function TextArea({stylex.props(inputWrapperStyles.base,styles.wrapper,- textareaSizeStyles[size],- effectivelyDisabled && inputWrapperStyles.disabled,+ isDisabled && inputWrapperStyles.disabled,status && inputStatusBorderStyles[status.type],- status &&- !effectivelyDisabled &&- inputStatusHoverShadowStyles[status.type],+ status && !isDisabled && inputStatusHoverShadowStyles[status.type],status && inputStatusFocusWithinStyles[status.type],xstyle,),className,style,)}>- {startIcon &&- renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}+ {startIcon && (+ <span {...stylex.props(styles.startIcon)}>+ {renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}+ </span>+ )}<textarea{...rest}ref={mergeRefs(ref, textareaRef)}@@ -480,32 +568,37 @@ export function TextArea({aria-busy={isBusy || undefined}{...stylex.props(styles.textarea,- effectivelyDisabled && styles.textareaDisabled,- status && styles.textareaWithStatus,+ textareaSizeStyles[size],+ isDisabled && styles.textareaDisabled,+ Boolean(startIcon) && styles.textareaWithStartIcon,+ (status || isBusy) && styles.textareaWithStatus,+ isBusy && !!statusIcon && styles.textareaWithBusyStatus,+ maxLength != null && styles.textareaWithCounter,)}/>- {isBusy && <Spinner size="sm" />}- {statusIcon && (- <span {...stylex.props(styles.statusIcon)}>{statusIcon}</span>+ {(isBusy || statusIcon) && (+ <span {...stylex.props(styles.endSlot)}>+ {isBusy && <Spinner size="sm" />}+ {statusIcon}+ </span>+ )}+ {maxLength != null && (+ <div+ id={counterID}+ {...stylex.props(+ styles.counter,+ optimisticValue.length > maxLength && styles.counterError,+ )}>+ {optimisticValue.length > maxLength && (+ // Non-color cue so the over-limit state isn't conveyed by the red+ // color alone (WCAG 1.4.1). Decorative — the count text and the+ // live-region announcement carry the meaning.+ <Icon icon="warning" size="sm" />+ )}+ {optimisticValue.length}/{maxLength}+ </div>)}</div>- {maxLength != null && (- <div- id={counterID}- {...stylex.props(- styles.counter,- optimisticValue.length > maxLength && styles.counterError,- )}>- {optimisticValue.length}/{maxLength}- <VisuallyHidden aria-live="polite">- {optimisticValue.length >= maxLength * COUNTER_WARNING_THRESHOLD- ? optimisticValue.length > maxLength- ? `${optimisticValue.length - maxLength} characters over limit`- : `${maxLength - optimisticValue.length} characters remaining`- : ''}- </VisuallyHidden>- </div>- )}{showsDisabledMessage &&disabledMessageTooltip.renderTooltip(disabledMessage)}</Field>