An open source design system that's fully customizable and agent ready
TypeScript
fix(core): announce FileInput required state; dedupe validation-error announcements (#4357)
Baraa Hamodife6baeb1c997
diff --git a/.changeset/a11y-file-input-required.md b/.changeset/a11y-file-input-required.mdnew file mode 100644index 0000000000..794df0b8b2--- /dev/null+++ b/.changeset/a11y-file-input-required.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] FileInput: announce the required state via a visually hidden description on the trigger (aria-required is unsupported on role="button") and announce validation errors exactly once+@bhamodidiff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 7b0ae1cd6c..c93740f3da 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -691,6 +691,10 @@"defaultMessage": "Clear {label}","description": "Screen-reader-only label on the X that removes the selected file from a FileInput. Example: `Clear Attachment`, `Clear Résumé`."},+ "@astryx.fileInput.required": {+ "defaultMessage": "Required",+ "description": "Screen-reader-only description on the FileInput trigger indicating the field must be filled in. Mirrors the visible `Required` indicator next to the field label; conveyed via description because aria-required is not supported on role=\"button\"."+ },"@astryx.fileInput.triggerWithFiles": {"defaultMessage": "{label}, {fileNames}","description": "Accessible name for a FileInput trigger that has files attached, composing the field label with the selected filenames. Example: `Attachments, report.pdf, notes.txt`."diff --git a/packages/core/src/FileInput/FileInput.doc.mjs b/packages/core/src/FileInput/FileInput.doc.mjsindex 52670c9c19..84acc82cd5 100644--- a/packages/core/src/FileInput/FileInput.doc.mjs+++ b/packages/core/src/FileInput/FileInput.doc.mjs@@ -78,7 +78,7 @@ export const docs = {name: 'isRequired',type: 'boolean',description:- 'Displays a "Required" indicator next to the label and sets aria-required. Mutually exclusive with isOptional.',+ 'Displays a "Required" indicator next to the label and adds a screen-reader-only "Required" description to the trigger (aria-required is not supported on role="button"). Mutually exclusive with isOptional.',default: 'false',},{@@ -322,7 +322,7 @@ export const docsDense = {isLabelHidden: 'Visually hides label; keeps screen reader access.',description: 'Description text between label+input.',isOptional: 'Shows "Optional" indicator.',- isRequired: 'Shows "Required" indicator+sets aria-required.',+ isRequired: 'Shows "Required" indicator+SR-only trigger description.',isDisabled: 'Disables input, prevents interaction.',disabledMessage:'Explains why input is disabled. With isDisabled, shows tooltip on hover/focus + keeps trigger focusable via aria-disabled (opening picker stays blocked). Use instead of wrapping a disabled FileInput in Tooltip.',diff --git a/packages/core/src/FileInput/FileInput.test.tsx b/packages/core/src/FileInput/FileInput.test.tsxindex af70b94ef2..33628f744d 100644--- a/packages/core/src/FileInput/FileInput.test.tsx+++ b/packages/core/src/FileInput/FileInput.test.tsx@@ -147,16 +147,33 @@ describe('FileInput', () => {expect(screen.getByText('Upload')).toBeInTheDocument();});- it('sets aria-required when isRequired is true', () => {+ it('conveys required state through the accessible description', () => {render(<FileInput label="Resume" isRequired value={null} onChange={() => {}} />,);- // aria-required lives on the focusable role="button" wrapper, not the+ const trigger = screen.getByRole('button', {name: 'Resume'});+ // Required is conveyed via a visually hidden "Required" node referenced+ // from aria-describedby on the focusable role="button" trigger — not the// hidden file input (forms-6).- expect(screen.getByRole('button', {name: 'Resume'})).toHaveAttribute(- 'aria-required',- 'true',+ expect(trigger).toHaveAccessibleDescription(/Required/);+ // aria-required is not a supported property of role="button" in+ // WAI-ARIA 1.2 (AT does not announce it), so it must never appear.+ expect(trigger).not.toHaveAttribute('aria-required');+ });++ it('combines required with the description in the accessible description', () => {+ render(+ <FileInput+ label="Resume"+ description="PDF only"+ isRequired+ value={null}+ onChange={() => {}}+ />,);+ const trigger = screen.getByRole('button', {name: 'Resume'});+ expect(trigger).toHaveAccessibleDescription(/PDF only/);+ expect(trigger).toHaveAccessibleDescription(/Required/);});it('places aria-describedby on the focusable button, not the hidden input (forms-6)', () => {@@ -176,11 +193,11 @@ describe('FileInput', () => {expect(input).toHaveAttribute('aria-hidden', 'true');});- it('does not set aria-required by default', () => {+ it('does not mention required without isRequired', () => {render(<FileInput label="Resume" value={null} onChange={() => {}} />);- expect(screen.getByRole('button', {name: 'Resume'})).not.toHaveAttribute(- 'aria-required',- );+ const trigger = screen.getByRole('button', {name: 'Resume'});+ expect(trigger).not.toHaveAccessibleDescription(/Required/);+ expect(trigger).not.toHaveAttribute('aria-required');});it('sets disabled attribute when isDisabled is true', () => {@@ -353,6 +370,40 @@ describe('FileInput', () => {// FieldStatus, but the polite channel must stay empty.)expect(politeRegion()?.textContent ?? '').toBe('');});++ it('announces a validation error exactly once across live regions', async () => {+ render(+ <FileInput+ label="Upload"+ value={null}+ onChange={() => {}}+ accept=".pdf"+ />,+ );+ fireEvent.change(fileInputEl(), {+ target: {files: [createFile('note.txt', 100)]},+ });+ const errorText = '"note.txt" is not an accepted file type';+ // The error lands in the assertive announce region (via the FieldStatus+ // the derived error status mounts)…+ await waitFor(() => {+ expect(+ document.querySelector('[data-astryx-live-region="assertive"]'),+ ).toHaveTextContent(errorText);+ });+ // …and in exactly one live region overall. FileInput's own role="status"+ // region used to duplicate the FieldStatus announcement, so the same+ // error was read twice (assertively, then politely).+ const liveRegions = Array.from(+ document.querySelectorAll(+ '[role="status"], [role="alert"], [aria-live]',+ ),+ );+ const regionsWithError = liveRegions.filter(el =>+ (el.textContent ?? '').includes(errorText),+ );+ expect(regionsWithError).toHaveLength(1);+ });});describe('validation', () => {diff --git a/packages/core/src/FileInput/FileInput.tsx b/packages/core/src/FileInput/FileInput.tsxindex 6dabc744b9..a5cd9780fc 100644--- a/packages/core/src/FileInput/FileInput.tsx+++ b/packages/core/src/FileInput/FileInput.tsx@@ -4,7 +4,7 @@/*** @file FileInput.tsx- * @input Uses React, useId, Field, Icon, Spinner+ * @input Uses React, useId, Field, Icon, Spinner, VisuallyHidden* @output Exports FileInput component, FileInputProps, FileInputStatus* @position Core implementation; consumed by index.ts, tested by FileInput.test.tsx*@@ -45,6 +45,7 @@ import {} from '../Field';import {Icon, type IconName} from '../Icon';import {Spinner} from '../Spinner';+import {VisuallyHidden} from '../VisuallyHidden';import {useAnnounce} from '../hooks/useAnnounce';import {useTooltip} from '../Tooltip';@@ -247,17 +248,6 @@ const styles = stylex.create({flex: 1,minWidth: 0,},- liveRegion: {- position: 'absolute',- width: 1,- height: 1,- padding: 0,- margin: -1,- overflow: 'hidden',- clip: 'rect(0, 0, 0, 0)',- whiteSpace: 'nowrap',- borderWidth: 0,- },});const statusBorderStyles = stylex.create({@@ -439,15 +429,16 @@ export function FileInput({const id = useId();const descriptionID = useId();const statusMessageID = useId();- const liveRegionID = useId();+ const requiredID = useId();const inputRef = useRef<HTMLInputElement | null>(null);const [isDragOver, setIsDragOver] = useState(false);const [validationError, setValidationError] = useState<string | null>(null);const [, startTransition] = useTransition();// Announce successful file selection to screen readers via a persistent- // live region (forms-17). The component's own role="status" region only- // carries validation errors, so a successful attach was previously silent.+ // live region (forms-17). Validation errors are announced (assertively) by+ // the FieldStatus that the derived error status mounts, so only the+ // successful attach needs an explicit announcement here.const announce = useAnnounce();// Disabled-reason tooltip. Disabled controls swallow pointer events, so the@@ -483,10 +474,18 @@ export function FileInput({success: 'success',};+ // Required state. `aria-required` is not a supported property of+ // role="button" in WAI-ARIA 1.2 (AT does not announce it there), so the+ // trigger instead points its aria-describedby at a visually hidden+ // "Required" span — mirroring the Field label's visible indicator (where+ // isOptional takes precedence) and the pattern Slider uses for its thumbs.+ const conveysRequired = isRequired && !isOptional;+const ariaDescribedBy =[description ? descriptionID : null,status?.message ? statusMessageID : null,+ conveysRequired ? requiredID : null,showsDisabledMessage ? disabledMessageTooltip.describedBy : null,].filter(Boolean)@@ -524,8 +523,9 @@ export function FileInput({onChange(result);// Announce the successful selection politely. Validation errors are- // handled by the role="status" region below, so only announce the- // attach here (do not double-announce errors).+ // announced assertively by the FieldStatus that the derived error+ // status mounts, so only announce the attach here (do not+ // double-announce errors).if (errors.length === 0) {announce(valid.length === 1@@ -767,9 +767,15 @@ export function FileInput({aria-busy={isLoading || undefined}// These describe the operable control, so they belong on the focusable// role="button" wrapper — not the hidden tabIndex={-1} file input the- // user never focuses (forms-6).+ // user never focuses (forms-6). Required state is conveyed through+ // the visually hidden "Required" node in aria-describedby, not+ // aria-required, which role="button" does not support in ARIA 1.2.aria-describedby={ariaDescribedBy}- aria-required={isRequired ? 'true' : undefined}+ // aria-invalid is likewise unsupported on role="button", but it stays:+ // a message-less error status (`status={{type: 'error'}}`) has no+ // described-by replacement, and some AT still honor the attribute, so+ // removing it would not be strictly better. Errors *with* a message+ // are described via statusMessageID above.aria-invalid={status?.type === 'error' ? 'true' : undefined}{...dragDropProps}{...mergeProps(@@ -809,13 +815,11 @@ export function FileInput({/>)}</div>- <div- id={liveRegionID}- role="status"- aria-live="polite"- {...stylex.props(styles.liveRegion)}>- {validationError}- </div>+ {conveysRequired && (+ <VisuallyHidden id={requiredID}>+ {t('@astryx.fileInput.required')}+ </VisuallyHidden>+ )}{showsDisabledMessage &&disabledMessageTooltip.renderTooltip(disabledMessage)}</Field>