An open source design system that's fully customizable and agent ready
TypeScript
fix(core): announce Tokenizer token add/remove to screen readers (#3993)
Baraa Hamodi501433e68557
diff --git a/.changeset/tokenizer-announce.md b/.changeset/tokenizer-announce.mdnew file mode 100644index 0000000000..e8ea92ed82--- /dev/null+++ b/.changeset/tokenizer-announce.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Tokenizer: adding and removing tokens (including Backspace on an empty input) is now announced to screen readers. Previously tokens appeared and disappeared silently.+@bhamodidiff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjsindex 4d6bfbe254..e6d9d6d1d1 100644--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs@@ -31,7 +31,7 @@ export const docs = {name: 'onChange',type: '(items: T[], change: TokenizerChange<T>) => void',description:- "Called when selection changes. The change argument includes the affected item and type ('add' | 'create' | 'remove' | 'reorder').",+ "Called when selection changes. The change argument includes the affected item and type ('add' | 'create' | 'remove' | 'reorder'). Additions and removals (including Backspace on an empty input) are announced to screen readers via a polite live region.",required: true,},{diff --git a/packages/core/src/Tokenizer/Tokenizer.test.tsx b/packages/core/src/Tokenizer/Tokenizer.test.tsxindex 0f9a0cda58..9f201217f5 100644--- a/packages/core/src/Tokenizer/Tokenizer.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.test.tsx@@ -9,12 +9,17 @@* SYNC: When Tokenizer.tsx changes, update tests to match*/-import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';+import {describe, it, expect, vi, beforeAll, afterAll, afterEach} from 'vitest';import {render, screen, fireEvent, act, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Tokenizer} from './Tokenizer';+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import type {SearchSource, SearchableItem} from '../Typeahead/types';+function politeRegion(): HTMLElement | null {+ return document.querySelector('[data-astryx-live-region="polite"]');+}+// Store original matches to restore laterconst originalMatches = HTMLElement.prototype.matches;@@ -60,6 +65,10 @@ afterAll(() => {(HTMLElement.prototype as any).matches = originalMatches;});+afterEach(() => {+ __resetLiveRegionsForTest();+});+// Test dataconst users: SearchableItem[] = [{id: '1', label: 'Alice'},@@ -921,6 +930,130 @@ describe('Tokenizer', () => {expect(screen.getByRole('combobox')).toBeDisabled();});});+ describe('announcements', () => {+ it('announces removal politely on Backspace with an empty input', async () => {+ const onChange = vi.fn();+ render(+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0], users[1]]}+ onChange={onChange}+ />,+ );+ const input = screen.getByRole('combobox');+ fireEvent.keyDown(input, {key: 'Backspace'});+ expect(onChange).toHaveBeenCalledWith([users[0]], {+ item: users[1],+ type: 'remove',+ });+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Removed Bob');+ });+ });++ it("announces removal politely when clicking a token's remove button", async () => {+ render(+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0], users[1]]}+ onChange={() => {}}+ />,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Remove Alice'}));+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Removed Alice');+ });+ });++ it('announces addition politely when selecting a search result', async () => {+ render(+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ hasEntriesOnFocus+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');+ fireEvent.focus(input);+ await act(async () => {+ await new Promise(r => setTimeout(r, 50));+ });+ fireEvent.click(screen.getByText('Alice'));+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Added Alice');+ });+ });++ it('announces addition politely when creating a token with hasCreate', async () => {+ const emptySource: SearchSource = {+ search: () => [],+ bootstrap: () => [],+ };+ render(+ <Tokenizer+ label="Tags"+ searchSource={emptySource}+ value={[]}+ onChange={() => {}}+ hasCreate+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');+ await act(async () => {+ fireEvent.change(input, {target: {value: 'new-tag'}});+ });+ await act(async () => {+ await new Promise(r => setTimeout(r, 50));+ });+ fireEvent.click(screen.getByText('Create "new-tag"'));+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Added new-tag');+ });+ });++ it('does not announce on mount', () => {+ render(+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[users[0]]}+ onChange={() => {}}+ />,+ );+ // The live regions are created lazily on first announce, so a mount+ // with pre-selected tokens must not create (or speak through) one.+ expect(politeRegion()).toBeNull();+ });++ it('does not announce add/remove while typing', async () => {+ render(+ <Tokenizer+ label="Members"+ searchSource={userSource}+ value={[]}+ onChange={() => {}}+ debounceMs={0}+ />,+ );+ const input = screen.getByRole('combobox');+ await act(async () => {+ fireEvent.change(input, {target: {value: 'Ali'}});+ });+ await act(async () => {+ await new Promise(r => setTimeout(r, 50));+ });+ // BaseTypeahead announces result counts while typing (existing+ // behavior); typing alone must not produce add/remove announcements.+ expect(politeRegion()?.textContent ?? '').not.toMatch(/Added|Removed/);+ });+ });+describe('form participation', () => {it('submits one entry per token id under htmlName', () => {const {container} = render(@@ -951,7 +1084,9 @@ describe('Tokenizer', () => {/></form>,);- expect([...new FormData(container.querySelector('form')!).keys()]).toEqual([]);+ expect([+ ...new FormData(container.querySelector('form')!).keys(),+ ]).toEqual([]);});});});diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex e60c481b34..db4b6609ad 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -4,7 +4,7 @@/*** @file Tokenizer.tsx- * @input Uses React, BaseTypeahead, Field, Token+ * @input Uses React, BaseTypeahead, Field, Token, useAnnounce* @output Exports Tokenizer multi-select typeahead component* @position Composed component; forwards DOM ref and exposes focus control via* handleRef@@ -43,6 +43,7 @@ import {renderIconSlot, type IconType} from '../Icon';import {OverflowList} from '../OverflowList';import {useLayer} from '../Layer/useLayer';import {useTooltip} from '../Tooltip';+import {useAnnounce} from '../hooks/useAnnounce';import {colorVars,spacingVars,@@ -560,6 +561,12 @@ export function Tokenizer<T extends SearchableItem>({[],);+ // Announce token add/remove politely via the persistent live region.+ // Tokens previously appeared and disappeared silently — Backspace on an+ // empty input removes the trailing token, and the per-token remove buttons+ // gave no audible feedback either.+ const announce = useAnnounce();+// Handle adding an item — detect creatable synthetic itemsconst handleAdd = useCallback((item: T | null) => {@@ -584,6 +591,7 @@ export function Tokenizer<T extends SearchableItem>({const realItem = base as T;const newItems = [...value, realItem];onChange(newItems, {item: realItem, type: 'create'});+ announce(`Added ${createdValue}`);return;}@@ -592,18 +600,22 @@ export function Tokenizer<T extends SearchableItem>({}const newItems = [...value, item];onChange(newItems, {item, type: 'add'});+ announce(`Added ${item.label}`);},- [value, onChange, isAtMax, selectedIds, hasCreate],+ [value, onChange, isAtMax, selectedIds, hasCreate, announce],);- // Handle removing an item+ // Handle removing an item. Single removal path: both Backspace on an empty+ // input and the per-token remove buttons route through here, so the+ // announcement covers both.const handleRemove = useCallback((item: T) => {const newItems = value.filter(v => v.id !== item.id);onChange(newItems, {item, type: 'remove'});+ announce(`Removed ${item.label}`);inputRef.current?.focus();},- [value, onChange],+ [value, onChange, announce],);// Handle clearing all items