An open source design system that's fully customizable and agent ready
TypeScript
fix(lab): MobilePowerSearch names its trigger by what it shows and announces inside its sheets (#8007)
Xinzi Zhouf0a5ceac78ba
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsxindex 8760bf6810..9d29b3dfe6 100644--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx@@ -16,13 +16,14 @@import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';import {+ act,render,screen,fireEvent,waitFor,within,} from '@testing-library/react';-import React, {createRef, useState} from 'react';+import React, {createRef, StrictMode, useState} from 'react';import type {PowerSearchConfig,PowerSearchEditorProps,@@ -46,7 +47,7 @@ import {// jsdom implements neither <dialog> open/close nor pointer capture; the sheet// needs both. Same stubs BottomSheet's own tests install.-beforeEach(() => {+beforeEach(async () => {HTMLDialogElement.prototype.showModal = vi.fn(function (this: HTMLDialogElement,) {@@ -88,6 +89,15 @@ beforeEach(() => {vi.fn((id: number) => window.clearTimeout(id)),);window.scrollTo = vi.fn();+ // The shared page-body live regions outlive a test and clear on a 2s+ // timer, and a previous test's announcement may still be a frame away;+ // let it land, then start this test with the regions empty.+ await new Promise(resolve => setTimeout(resolve, 0));+ for (const region of document.querySelectorAll(+ 'body > [data-astryx-live-region]',+ )) {+ region.textContent = '';+ }});afterEach(() => {@@ -447,14 +457,43 @@ function expectBleedRowsOnBodyInset(list: HTMLElement): void {}describe('MobilePowerSearch trigger', () => {- it('uses the field label for its single sheet trigger', () => {+ it('names its single sheet trigger by the field label followed by its visible text', () => {setup({label: 'Filter issues'});- const button = screen.getByRole('button', {name: 'Filter issues'});+ const button = screen.getByRole('button', {name: 'Filter issues Filters…'});expect(button).toHaveAttribute('aria-haspopup', 'dialog');expect(button).toHaveTextContent('Filters…');expect(screen.getAllByRole('button')).toHaveLength(1);});+ it("keeps the trigger's visible text inside its accessible name with a custom label and placeholder, and with tokens", () => {+ // WCAG 2.5.3: a speech-input user says what they see. The name is the+ // label plus the visible content: the placeholder when empty...+ const {rerender} = setup({+ label: 'Search issues',+ placeholder: 'Search content…',+ });+ expect(trigger()).toHaveAccessibleName('Search issues Search content…');+ expect(trigger().textContent).toBe('Search content…');+ // ...or the tokens once filters are selected.+ rerender(+ <MobilePowerSearch+ config={config}+ filters={[openFilter, authorFilter]}+ onChange={vi.fn()}+ label="Search issues"+ placeholder="Search content…"+ />,+ );+ const name = trigger().getAttribute('aria-labelledby')!;+ expect(name.split(' ')).toHaveLength(2);+ expect(trigger()).toHaveAccessibleName(+ /^Search issues .*Status: is.*Open.*Author: is/,+ );+ for (const visible of ['Status: is', 'Open', 'Author: is']) {+ expect(within(field()).getByText(visible)).toBeTruthy();+ }+ });+it('renders display-only tokens with bold values and no remove controls', () => {setup({filters: [openFilter, authorFilter]});expect(within(field()).getByText('Status: is')).toBeTruthy();@@ -479,7 +518,7 @@ describe('MobilePowerSearch trigger', () => {it('wraps tokens without reserving a row for the trigger', () => {setup({filters: [openFilter, authorFilter]});- const button = screen.getByRole('button', {name: 'Manage filters'});+ const button = screen.getByRole('button', {name: /^Manage filters/});expect(getComputedStyle(button.parentElement!).flexWrap).toBe('wrap');expect(getComputedStyle(button).position).toBe('absolute');});@@ -538,6 +577,79 @@ describe('MobilePowerSearch trigger', () => {expect(screen.getByText('1 result')).toBeTruthy();});+ it('announces a result count change through the page channel while closed, and nothing for the count present on mount, under StrictMode', async () => {+ const pageRegion = () =>+ document.querySelector('body > [aria-live="polite"]');+ const {rerender} = render(+ <StrictMode>+ <MobilePowerSearch+ config={config}+ filters={[]}+ onChange={vi.fn()}+ resultCount={12}+ />+ </StrictMode>,+ );+ // StrictMode mounts, unmounts and remounts effects; a mounted-flag guard+ // announces the initial count on the replay. The region stays empty.+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20));+ });+ expect(pageRegion()?.textContent ?? '').toBe('');+ // A real change announces once, with the words shown.+ rerender(+ <StrictMode>+ <MobilePowerSearch+ config={config}+ filters={[]}+ onChange={vi.fn()}+ resultCount={1}+ />+ </StrictMode>,+ );+ await waitFor(() => expect(pageRegion()?.textContent).toBe('1 result'));+ // The same value again is not a new occasion.+ rerender(+ <StrictMode>+ <MobilePowerSearch+ config={config}+ filters={[]}+ onChange={vi.fn()}+ resultCount={1}+ />+ </StrictMode>,+ );+ await act(async () => {+ await new Promise(resolve => setTimeout(resolve, 20));+ });+ expect(pageRegion()?.textContent).toBe('1 result');+ });++ it('routes a result count change to the live region inside the open sheet, which stays mounted and empty until then', async () => {+ const pageRegion = () =>+ document.querySelector('body > [aria-live="polite"]');+ const {rerender} = setup({resultCount: 12});+ openSheet();+ const region = within(sheet()).getByTestId(+ 'mobile-power-search-sheet-status',+ );+ expect(region).toHaveAttribute('role', 'status');+ expect(region).toHaveAttribute('aria-live', 'polite');+ expect(region.textContent).toBe('');+ expect(sheet().contains(region)).toBe(true);+ rerender(+ <MobilePowerSearch+ config={config}+ filters={[]}+ onChange={vi.fn()}+ resultCount={3}+ />,+ );+ await waitFor(() => expect(region.textContent).toBe('3 results'));+ // The page-body channel, which a native modal hides, is left alone.+ expect(pageRegion()?.textContent ?? '').toBe('');+ });+it('forwards display-only props to token overrides', () => {const seenProps = vi.fn();function CustomToken(props: PowerSearchTokenProps) {@@ -1412,6 +1524,54 @@ describe('MobilePowerSearch content search', () => {expect(within(sheet()).getByRole('heading', {name: 'Filters'}),).toBeTruthy();+ // The add is announced inside the sheet the flow is now on, not on the+ // page body, which assistive technology does not expose under a native+ // modal dialog.+ const region = within(sheet()).getByTestId(+ 'mobile-power-search-sheet-status',+ );+ await waitFor(() =>+ expect(region.textContent).toBe('Added "release notes"'),+ );+ expect(+ document.querySelector('body > [aria-live="polite"]')?.textContent ?? '',+ ).toBe('');+ });++ it('announces both the add and a result count that follows the filters in the same commit, joined in the sheet region', async () => {+ // A consumer that derives `resultCount` from `filters` re-renders in the+ // add's commit, so the count's announcement arrives while the add's is+ // still a frame away. Neither may drop the other (FR6, once per+ // occasion; FR9's join for messages that arrive before exposure).+ function CountFollowsFilters() {+ const [filters, setFilters] = useState<PowerSearchFilter[]>([openFilter]);+ return (+ <MobilePowerSearch+ config={contentSearchConfig}+ filters={filters}+ onChange={next => setFilters([...next])}+ resultCount={filters.length * 10}+ />+ );+ }+ render(<CountFollowsFilters />);+ openSheet();+ tapRow('Add filter');+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});+ fireEvent.change(input, {target: {value: 'release notes'}});+ fireEvent.click(+ within(sheet()).getByRole('button', {name: '"release notes"'}),+ );+ await waitFor(() => expect(isSheetOpen()).toBe(true));+ const region = within(sheet()).getByTestId(+ 'mobile-power-search-sheet-status',+ );+ await waitFor(() =>+ expect(region.textContent).toBe('Added "release notes" 20 results'),+ );+ expect(+ document.querySelector('body > [aria-live="polite"]')?.textContent ?? '',+ ).toBe('');});it('adds a value suggestion from Enter and announces it', () => {diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsxindex 6bf04325e5..50aefcd2a4 100644--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx@@ -28,6 +28,11 @@* and tokens wrap inside the trigger;* - strings are literals (no new i18n keys; existing Core keys are reused* only for the result count and the add announcement);+ * - announcements made while a sheet is open go to a persistent polite+ * region inside each sheet, created empty and kept mounted (spec AST-086+ * FR3), because the shared page-body channel is not exposed while a+ * native modal dialog is open (its Platform support section); the closed+ * field still uses the shared channel;* - no theming contract: no `power-search` theme target or selectors;* - `components[type].Token` overrides receive Core's PowerSearchTokenProps,* which carry no `timezoneID`; the built-in token renders Core `Token`@@ -98,6 +103,7 @@ import {Text} from '@astryxdesign/core/Text';import {TextInput} from '@astryxdesign/core/TextInput';import {Token} from '@astryxdesign/core/Token';import {useTooltip} from '@astryxdesign/core/Tooltip';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';import {useAnnounce,useDevWarning,@@ -432,6 +438,9 @@ function resolveDraftFilterIndex(const SEARCHABLE_FIELD_COUNT = 8;const DEFAULT_MAX_SEARCH_RESULTS = 10;const MAX_BROWSE_MENU_ITEMS = 1000;+// How long a message stays in the sheets' live region; the shared channel+// clears on the same schedule.+const SHEET_ANNOUNCEMENT_CLEAR_MS = 2000;// =============================================================================// Token@@ -544,7 +553,70 @@ export function MobilePowerSearch({const config = useMobilePowerSearchConfig(configProp);const t = useTranslator();const locale = useLocale();- const announce = useAnnounce();+ const announceOnPage = useAnnounce();+ // While a sheet is open the page-body live region is not exposed (the+ // sheets are native modal dialogs), so a message then goes to the polite+ // region rendered inside the sheets; `step` is read through a ref because+ // the add path changes the step in the same tick it announces.+ const [sheetAnnouncement, setSheetAnnouncement] = useState('');+ const sheetAnnouncementFrameRef = useRef<number | null>(null);+ const pendingSheetMessagesRef = useRef<string[]>([]);+ const sheetAnnouncementClearRef = useRef<ReturnType<+ typeof setTimeout+ > | null>(null);+ const stepRef = useRef<SheetStep | null>(null);+ const announce = useCallback(+ (message: string) => {+ if (stepRef.current == null) {+ announceOnPage(message);+ return;+ }+ // Clear, then write on the next frame so the same words announce again+ // (FR6: a new occasion), and clear shortly after so stale text does not+ // linger in a sheet that opens later (FR3). Messages that arrive while+ // the frame is pending are joined in order into that one write, the way+ // the shared channel joins them (FR9), so an add and the result count+ // it changes in the same commit are both heard.+ pendingSheetMessagesRef.current.push(message);+ if (sheetAnnouncementFrameRef.current != null) {+ return;+ }+ if (sheetAnnouncementClearRef.current != null) {+ clearTimeout(sheetAnnouncementClearRef.current);+ sheetAnnouncementClearRef.current = null;+ }+ setSheetAnnouncement('');+ sheetAnnouncementFrameRef.current = requestAnimationFrame(() => {+ sheetAnnouncementFrameRef.current = null;+ const joined = pendingSheetMessagesRef.current.join(' ');+ pendingSheetMessagesRef.current = [];+ setSheetAnnouncement(joined);+ sheetAnnouncementClearRef.current = setTimeout(() => {+ sheetAnnouncementClearRef.current = null;+ setSheetAnnouncement('');+ }, SHEET_ANNOUNCEMENT_CLEAR_MS);+ });+ },+ [announceOnPage],+ );+ // Owns the sheet announcer's frame and clear timer: released on teardown,+ // with the refs and the pending queue reset, so an Effect teardown that is+ // not an unmount (an <Activity> hide) leaves no cancelled id behind that+ // would block later in-sheet announcements.+ useEffect(+ () => () => {+ if (sheetAnnouncementFrameRef.current != null) {+ cancelAnimationFrame(sheetAnnouncementFrameRef.current);+ sheetAnnouncementFrameRef.current = null;+ }+ if (sheetAnnouncementClearRef.current != null) {+ clearTimeout(sheetAnnouncementClearRef.current);+ sheetAnnouncementClearRef.current = null;+ }+ pendingSheetMessagesRef.current = [];+ },+ [],+ );const triggerLabel = labelFromProps ?? 'Manage filters';const fieldPlaceholder = placeholderFromProps ?? 'Filters…';@@ -562,6 +634,8 @@ export function MobilePowerSearch({);const triggerId = useId();+ const triggerLabelId = useId();+ const triggerContentId = useId();const statusMessageId = useId();const contentResultsId = useId();const triggerRef = useRef<HTMLButtonElement>(null);@@ -577,6 +651,7 @@ export function MobilePowerSearch({const pendingMutationFocusRef = useRef(false);const [step, setStep] = useState<SheetStep | null>(null);+ stepRef.current = step;// The draft outlives a step change on purpose: the switcher keeps the// outgoing sheet mounted while the incoming one enters, and clearing the// draft with the step would blank that sheet mid-transition.@@ -1085,12 +1160,20 @@ export function MobilePowerSearch({return resultCount;}, [resultCount, t]);- const hasMountedRef = useRef(false);+ // This Effect synchronizes a polite live region with the result count: the+ // shared page-body one while the field is closed, the sheets' own while a+ // sheet is open. A count present on mount is not announced unprompted, and+ // the guard compares against the last announced text rather than a mounted+ // flag, so StrictMode's effect replay announces nothing either (FR6). It+ // needs no cleanup of its own: on the open-sheet path `announce` starts a+ // frame and a clear timer, which the sheet announcer's teardown Effect and+ // the next write release.+ const announcedResultCountRef = useRef(resultCountText);useEffect(() => {- if (!hasMountedRef.current) {- hasMountedRef.current = true;+ if (resultCountText === announcedResultCountRef.current) {return;}+ announcedResultCountRef.current = resultCountText;if (resultCountText != null) {announce(resultCountText);}@@ -1224,11 +1307,28 @@ export function MobilePowerSearch({const isDraftRenderable =draft != null && draftField != null && draftOperator != null;+ // One persistent polite region per sheet, created empty and kept mounted+ // while its text changes (FR3), because the shared page-body channel is+ // not exposed while a native modal dialog is open; only the active sheet's+ // dialog is exposed, so a message is heard once. A polite status region+ // needs no name to announce, so it carries none rather than one assembled+ // from the label and a literal.+ const sheetStatus = (+ <VisuallyHidden+ role="status"+ aria-live="polite"+ aria-atomic="true"+ data-testid="mobile-power-search-sheet-status">+ {sheetAnnouncement}+ </VisuallyHidden>+ );+return (<><Fieldref={ref}label={triggerLabel}+ labelID={triggerLabelId}isLabelHidden={isLabelHidden}inputID={triggerId}isDisabled={isDisabled}@@ -1262,7 +1362,11 @@ export function MobilePowerSearch({status && !isDisabled && inputStatusHoverShadowStyles[status.type],status && inputStatusFocusWithinStyles[status.type],)}>- <div {...stylex.props(styles.contentSection)}>+ {/* The trigger's name is the label plus everything visible here:+ the placeholder, or the tokens, so speech input can say what it+ sees and assistive technology hears the selected filters+ (WCAG 2.5.3). */}+ <div id={triggerContentId} {...stylex.props(styles.contentSection)}>{startIcon && (<span{...stylex.props(@@ -1282,6 +1386,7 @@ export function MobilePowerSearch({aria-disabled={isDisabled ? true : undefined}aria-haspopup="dialog"aria-expanded={step != null}+ aria-labelledby={`${triggerLabelId} ${triggerContentId}`}aria-describedby={triggerDescribedBy}{...stylex.props(styles.trigger,@@ -1310,6 +1415,7 @@ export function MobilePowerSearch({onActiveSheetChange={handleActiveSheetChange}><BottomSheet sheetId="manage" label="Filters" height="tall" padding={0}><div {...stylex.props(styles.sheet)}>+ {sheetStatus}<div {...stylex.props(styles.header)}><div {...stylex.props(styles.headerRow)}><div {...stylex.props(styles.headerText)}>@@ -1401,6 +1507,7 @@ export function MobilePowerSearch({height="tall"padding={0}><div {...stylex.props(styles.sheet)}>+ {sheetStatus}<div {...stylex.props(styles.header)}><div {...stylex.props(styles.headerRow)}><Button@@ -1582,6 +1689,7 @@ export function MobilePowerSearch({padding={0}purpose="form"><div {...stylex.props(styles.sheet)}>+ {sheetStatus}<div {...stylex.props(styles.header)}><div {...stylex.props(styles.headerRow)}><div {...stylex.props(styles.headerText)}>