Skip to content

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

TypeScript

fix(inputgroup): wire group ARIA through context (#3502)

Cindy Zhangc7a5088fffd5
diff --git a/.changeset/inputgroup-context-aria.md b/.changeset/inputgroup-context-aria.md
new file mode 100644
index 0000000000..1a16415c5c
--- /dev/null
+++ b/.changeset/inputgroup-context-aria.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] InputGroup: grouped TextInput and NumberInput controls now include both the group label and their own label in the input name, while preserving the group's description and status associations (#3343).
+@cixzhang
diff --git a/packages/core/src/InputGroup/InputGroup.doc.mjs b/packages/core/src/InputGroup/InputGroup.doc.mjs
index cb86285ef9..20c0c85941 100644
--- a/packages/core/src/InputGroup/InputGroup.doc.mjs
+++ b/packages/core/src/InputGroup/InputGroup.doc.mjs
@@ -92,7 +92,7 @@ export const docs = {
bestPractices: [
{guidance: true, description: 'Use text addons to show units, prefixes, or suffixes that clarify the input format (e.g., "$", "kg", "https://").'},
{guidance: true, description: 'Use InputGroupText for static prefixes/suffixes like "$", "kg", or "https://".'},
- {guidance: true, description: 'Set isLabelHidden on the inner input and let the group label be visible.'},
+ {guidance: true, description: "Keep each inner input's label specific; grouped inputs automatically combine the group label with their own label and inherit the group description/status context."},
{guidance: false, description: 'Don\'t put multiple text inputs in one group; use separate fields instead.'},
{guidance: false, description: 'Don\'t use InputGroup for unrelated inputs; it\'s for a single input with decorations.'},
],
@@ -114,7 +114,7 @@ export const docsDense = {
bestPractices: [
{guidance: true, description: 'Use text addons to show units, prefixes, or suffixes that clarify input format (e.g. "$", "kg", "https://").'},
{guidance: true, description: 'Use InputGroupText for static prefixes/suffixes like "$", "kg", or "https://".'},
- {guidance: true, description: 'Set isLabelHidden on the inner input and let the group label be visible.'},
+ {guidance: true, description: "Keep each inner input's label specific; grouped inputs combine the group label with their own label and inherit group description/status."},
{guidance: false, description: 'Don\'t put multiple text inputs in one group; use separate fields instead.'},
{guidance: false, description: 'Don\'t use InputGroup for unrelated inputs; it\'s for a single input with decorations.'},
],
diff --git a/packages/core/src/InputGroup/InputGroup.test.tsx b/packages/core/src/InputGroup/InputGroup.test.tsx
index da852acec3..70777e7639 100644
--- a/packages/core/src/InputGroup/InputGroup.test.tsx
+++ b/packages/core/src/InputGroup/InputGroup.test.tsx
@@ -14,6 +14,7 @@ import {render, screen} from '@testing-library/react';
import {InputGroup} from './InputGroup';
import {InputGroupText} from './InputGroupText';
import {TextInput} from '../TextInput';
+import {NumberInput} from '../NumberInput';
describe('InputGroup', () => {
it('names the group via the label element (forms-14)', () => {
@@ -37,6 +38,85 @@ describe('InputGroup', () => {
expect(group.getAttribute('aria-labelledby')).toBe(label.id);
});
+ it('associates group description and status through aria-describedby', () => {
+ render(
+ <InputGroup
+ label="Price"
+ description="Enter the amount in USD"
+ status={{type: 'error', message: 'Price is required'}}>
+ <InputGroupText>$</InputGroupText>
+ <TextInput label="Amount" isLabelHidden value="" onChange={() => {}} />
+ </InputGroup>,
+ );
+
+ const group = screen.getByRole('group', {name: 'Price'});
+ const describedBy = group.getAttribute('aria-describedby');
+ expect(describedBy).toBeTruthy();
+ expect(describedBy!.split(' ')).toHaveLength(2);
+ expect(describedBy).toContain(
+ screen.getByText('Enter the amount in USD').id,
+ );
+ expect(describedBy).toContain(screen.getByText('Price is required').id);
+ });
+
+ it('labels grouped TextInput from the group and inner input labels', () => {
+ render(
+ <InputGroup
+ label="Price"
+ description="Enter the amount in USD"
+ status={{type: 'error', message: 'Price is required'}}>
+ <InputGroupText>$</InputGroupText>
+ <TextInput label="Amount" isLabelHidden value="" onChange={() => {}} />
+ </InputGroup>,
+ );
+
+ const group = screen.getByRole('group', {name: 'Price'});
+ const groupLabelID = group.getAttribute('aria-labelledby');
+ const describedBy = group.getAttribute('aria-describedby');
+ const input = screen.getByRole('textbox', {name: 'Price Amount'});
+ const labelledByIDs =
+ input.getAttribute('aria-labelledby')?.split(' ') ?? [];
+
+ expect(labelledByIDs).toHaveLength(2);
+ expect(labelledByIDs[0]).toBe(groupLabelID);
+ expect(document.getElementById(labelledByIDs[1])).toHaveTextContent(
+ 'Amount',
+ );
+ expect(input).not.toHaveAttribute('aria-label');
+ expect(input).toHaveAttribute('aria-describedby', describedBy);
+ });
+
+ it('labels grouped NumberInput from the group and inner input labels', () => {
+ render(
+ <InputGroup label="Budget" description="Whole dollars only">
+ <InputGroupText>$</InputGroupText>
+ <NumberInput
+ label="Amount"
+ isLabelHidden
+ value={null}
+ onChange={() => {}}
+ />
+ </InputGroup>,
+ );
+
+ const group = screen.getByRole('group', {name: 'Budget'});
+ const groupLabelID = group.getAttribute('aria-labelledby');
+ const input = screen.getByRole('spinbutton', {name: 'Budget Amount'});
+ const labelledByIDs =
+ input.getAttribute('aria-labelledby')?.split(' ') ?? [];
+
+ expect(labelledByIDs).toHaveLength(2);
+ expect(labelledByIDs[0]).toBe(groupLabelID);
+ expect(document.getElementById(labelledByIDs[1])).toHaveTextContent(
+ 'Amount',
+ );
+ expect(input).not.toHaveAttribute('aria-label');
+ expect(input).toHaveAttribute(
+ 'aria-describedby',
+ group.getAttribute('aria-describedby'),
+ );
+ });
+
it('renders the visible label', () => {
render(
<InputGroup label="Price">
diff --git a/packages/core/src/InputGroup/InputGroup.tsx b/packages/core/src/InputGroup/InputGroup.tsx
index 877db0d55b..b062bd771d 100644
--- a/packages/core/src/InputGroup/InputGroup.tsx
+++ b/packages/core/src/InputGroup/InputGroup.tsx
@@ -4,8 +4,8 @@
/**
* @file InputGroup.tsx
- * @input Uses React, StyleX, theme tokens, InputGroupContext
- * @output Exports InputGroup component
+ * @input Uses React, StyleX, theme tokens, InputGroupContext, Field
+ * @output Exports InputGroup component with group label/description ARIA wiring
* @position Groups input with prefix/suffix addons; consumed by index.ts
*
* Children (TextInput, NumberInput) consume the InputGroup context
@@ -157,9 +157,21 @@ export function InputGroup({
const size = useSize(sizeProp, 'md');
const inputId = useId();
const labelID = useId();
+ const descriptionID = useId();
const statusMessageId = useId();
- const contextValue = useMemo(() => ({isInGroup: true as const}), []);
+ const describedByIDs =
+ [
+ description ? descriptionID : null,
+ status?.message ? statusMessageId : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ const contextValue = useMemo(
+ () => ({isInGroup: true as const, labelID, describedByIDs}),
+ [labelID, describedByIDs],
+ );
return (
<InputGroupContext value={contextValue}>
@@ -170,6 +182,7 @@ export function InputGroup({
description={description}
inputID={inputId}
labelID={labelID}
+ descriptionID={description ? descriptionID : undefined}
isGroupLabel
isOptional={isOptional}
isRequired={isRequired}
@@ -189,6 +202,7 @@ export function InputGroup({
ref={ref}
role="group"
aria-labelledby={labelID}
+ aria-describedby={describedByIDs}
data-testid={testId}
{...rest}
{...mergeProps(
diff --git a/packages/core/src/InputGroup/InputGroupContext.ts b/packages/core/src/InputGroup/InputGroupContext.ts
index 65fbc5fb75..a7aff09028 100644
--- a/packages/core/src/InputGroup/InputGroupContext.ts
+++ b/packages/core/src/InputGroup/InputGroupContext.ts
@@ -4,19 +4,24 @@
/**
* @file InputGroupContext.ts
- * @input None (pure context definition)
+ * @input React createContext/use
* @output Exports InputGroup context and useInputGroup hook
- * @position Shared context; consumed by input components for group-aware styling
+ * @position Shared context; consumed by input components for group-aware styling and ARIA associations
*/
import {createContext, use} from 'react';
export interface InputGroupContextValue {
isInGroup: true;
+ /** ID of the group label element, for aria-labelledby composition. */
+ labelID: string;
+ /** IDs of helper/status text owned by the group, for aria-describedby composition. */
+ describedByIDs?: string;
}
-export const InputGroupContext =
- createContext<InputGroupContextValue | null>(null);
+export const InputGroupContext = createContext<InputGroupContextValue | null>(
+ null,
+);
InputGroupContext.displayName = 'InputGroupContext';
/**
diff --git a/packages/core/src/InputGroup/index.ts b/packages/core/src/InputGroup/index.ts
index 2beedabefe..a4e557a6d0 100644
--- a/packages/core/src/InputGroup/index.ts
+++ b/packages/core/src/InputGroup/index.ts
@@ -16,3 +16,4 @@ export {InputGroupText} from './InputGroupText';
export type {InputGroupTextProps} from './InputGroupText';
export {useInputGroup} from './InputGroupContext';
+export type {InputGroupContextValue} from './InputGroupContext';
diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsx
index 8aa7b65686..3a97d82bda 100644
--- a/packages/core/src/NumberInput/NumberInput.tsx
+++ b/packages/core/src/NumberInput/NumberInput.tsx
@@ -4,7 +4,7 @@
/**
* @file NumberInput.tsx
- * @input Uses React, useId, useState, useMemo, useCallback, Field, Icon
+ * @input Uses React, useId, useState, useMemo, useCallback, Field, Icon, InputGroupContext
* @output Exports NumberInput component, NumberInputProps
* @position Core implementation; consumed by index.ts, tested by NumberInput.test.tsx
*
@@ -48,6 +48,7 @@ import {
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {VisuallyHidden} from '../VisuallyHidden';
import {useTooltip} from '../Tooltip';
+import {getInputARIA} from '../utils';
import {useSize} from '../SizeContext/SizeContext';
import {useInputContainer} from '../hooks/useInputContainer';
import {useInputGroup} from '../InputGroup/InputGroupContext';
@@ -400,6 +401,7 @@ export function NumberInput({
}: NumberInputProps) {
const size = useSize(sizeProp, 'md');
const id = useId();
+ const inputLabelID = useId();
const descriptionID = useId();
const statusMessageID = useId();
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -438,14 +440,15 @@ export function NumberInput({
success: 'success',
};
- const ariaDescribedBy =
+ const {ariaLabelledBy, ariaDescribedBy} = getInputARIA(
+ inputLabelID,
[
description ? descriptionID : null,
status?.message ? statusMessageID : null,
showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
+ ],
+ inputGroup,
+ );
// Display value: pending input if typing, otherwise the raw value
// Note: With type="number", we can't use formatted display values
@@ -593,6 +596,7 @@ export function NumberInput({
style,
)}>
{startIcon && renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
+ {inputGroup && <VisuallyHidden id={inputLabelID}>{label}</VisuallyHidden>}
<input
{...rest}
ref={mergeRefs(ref, inputRef)}
@@ -622,7 +626,7 @@ export function NumberInput({
aria-invalid={
status?.type === 'error' || !isInputValid ? 'true' : undefined
}
- aria-label={inputGroup ? label : undefined}
+ aria-labelledby={ariaLabelledBy}
{...stylex.props(
styles.input,
isDisabled && styles.inputDisabled,
diff --git a/packages/core/src/TextInput/TextInput.tsx b/packages/core/src/TextInput/TextInput.tsx
index b088d0a0d1..e15995d374 100644
--- a/packages/core/src/TextInput/TextInput.tsx
+++ b/packages/core/src/TextInput/TextInput.tsx
@@ -4,7 +4,7 @@
/**
* @file TextInput.tsx
- * @input Uses React, useId, ChangeEvent, Field, Icon
+ * @input Uses React, useId, ChangeEvent, Field, Icon, InputGroupContext
* @output Exports TextInput component, TextInputProps
* @position Core implementation; consumed by index.ts, tested by TextInput.test.tsx
*
@@ -48,6 +48,8 @@ import {
import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Spinner} from '../Spinner';
import {useTooltip} from '../Tooltip';
+import {VisuallyHidden} from '../VisuallyHidden';
+import {getInputARIA} from '../utils';
const styles = stylex.create({
clearButton: {
@@ -299,6 +301,7 @@ export function TextInput({
const size = useSize(sizeProp, 'md');
const id = useId();
+ const inputLabelID = useId();
const descriptionID = useId();
const statusMessageID = useId();
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -338,14 +341,15 @@ export function TextInput({
success: 'success',
};
- const ariaDescribedBy =
+ const {ariaLabelledBy, ariaDescribedBy} = getInputARIA(
+ inputLabelID,
[
description ? descriptionID : null,
status?.message ? statusMessageID : null,
showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
+ ],
+ inputGroup,
+ );
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
// Value can't change while showing a disabled message (the field is
@@ -405,6 +409,7 @@ export function TextInput({
style,
)}>
{startIcon && renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
+ {inputGroup && <VisuallyHidden id={inputLabelID}>{label}</VisuallyHidden>}
<input
{...rest}
ref={mergeRefs(ref, inputRef)}
@@ -436,7 +441,7 @@ export function TextInput({
aria-required={isRequired === true ? 'true' : undefined}
aria-invalid={status?.type === 'error' ? 'true' : undefined}
aria-busy={isBusy || undefined}
- aria-label={inputGroup ? label : undefined}
+ aria-labelledby={ariaLabelledBy}
{...stylex.props(styles.input, isDisabled && styles.inputDisabled)}
/>
{hasClear && value !== '' && !isDisabled && (
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index ae4de34f09..d3b7ccd4ed 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -79,3 +79,5 @@ export {groupItems, getItemGroup} from './groupItems';
export type {ItemGroup} from './groupItems';
export {observeResize, unobserveResize} from './sharedResizeObserver';
export {isRenderable} from './isRenderable';
+export {getInputARIA} from './inputAria';
+export type {InputARIA, InputARIAInputGroup} from './inputAria';
diff --git a/packages/core/src/utils/inputAria.test.ts b/packages/core/src/utils/inputAria.test.ts
new file mode 100644
index 0000000000..a6d21c28dd
--- /dev/null
+++ b/packages/core/src/utils/inputAria.test.ts
@@ -0,0 +1,39 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {getInputARIA} from './inputAria';
+
+describe('getInputARIA', () => {
+ it('keeps standalone input labeling native while composing descriptions', () => {
+ expect(
+ getInputARIA('input-label', ['input-help', undefined, 'input-error']),
+ ).toEqual({
+ ariaLabelledBy: undefined,
+ ariaDescribedBy: 'input-help input-error',
+ });
+ });
+
+ it('composes InputGroup context before input labels and descriptions', () => {
+ expect(
+ getInputARIA('input-label', ['input-help'], {
+ labelID: 'group-label',
+ describedByIDs: 'group-help group-error',
+ }),
+ ).toEqual({
+ ariaLabelledBy: 'group-label input-label',
+ ariaDescribedBy: 'group-help group-error input-help',
+ });
+ });
+
+ it('deduplicates repeated IDs', () => {
+ expect(
+ getInputARIA('group-label', ['shared', 'input-help'], {
+ labelID: 'group-label',
+ describedByIDs: 'shared group-error',
+ }),
+ ).toEqual({
+ ariaLabelledBy: 'group-label',
+ ariaDescribedBy: 'shared group-error input-help',
+ });
+ });
+});
diff --git a/packages/core/src/utils/inputAria.ts b/packages/core/src/utils/inputAria.ts
new file mode 100644
index 0000000000..0ecfd95c24
--- /dev/null
+++ b/packages/core/src/utils/inputAria.ts
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file inputAria.ts
+ * @input Receives input label/description IDs and optional InputGroup context
+ * @output Exports helpers for consistent input ARIA composition
+ * @position Internal utility; used by inputs that compose labels/descriptions
+ */
+
+export interface InputARIAInputGroup {
+ /** ID of the visible InputGroup label. */
+ labelID: string;
+ /** Space-separated IDs for InputGroup description/status text. */
+ describedByIDs?: string;
+}
+
+export interface InputARIA {
+ /** Value for aria-labelledby on the input. */
+ ariaLabelledBy?: string;
+ /** Value for aria-describedby on the input. */
+ ariaDescribedBy?: string;
+}
+
+type AriaID = string | null | undefined | false;
+
+function joinAriaIDs(...values: AriaID[]): string | undefined {
+ const ids = values
+ .flatMap(value =>
+ typeof value === 'string' ? value.trim().split(/\s+/) : [],
+ )
+ .filter(Boolean);
+
+ if (ids.length === 0) {
+ return undefined;
+ }
+
+ return Array.from(new Set(ids)).join(' ');
+}
+
+/**
+ * Builds ARIA label/description wiring for an input.
+ *
+ * Standalone inputs keep their normal native label association. Grouped inputs
+ * are named by the visible InputGroup label plus their own input label, and
+ * inherit group description/status text in addition to input-local text.
+ */
+export function getInputARIA(
+ labelID: string,
+ describedByIDs: AriaID[] = [],
+ inputGroup?: InputARIAInputGroup | null,
+): InputARIA {
+ return {
+ ariaLabelledBy: inputGroup
+ ? joinAriaIDs(inputGroup.labelID, labelID)
+ : undefined,
+ ariaDescribedBy: joinAriaIDs(inputGroup?.describedByIDs, ...describedByIDs),
+ };
+}