From 91cd9be3863ed8d7f11b0c8506909072f2323459 Mon Sep 17 00:00:00 2001 From: Ivor Zhou Date: Fri, 23 Oct 2026 14:03:59 -0700 Subject: [PATCH] fix(lab): MobilePowerSearch names its trigger by what it shows and announces inside its sheets Three accessibility defects in the Lab MobilePowerSearch, all on the sheet flow's trigger and its announcements. The trigger's accessible name is now the field label followed by its visible content, the placeholder or the selected tokens, through aria-labelledby on the label and the content section; with a custom label or placeholder the name and the visible text no longer differ (WCAG 2.5.3). The result count announcement compares against the last announced text instead of a mounted flag, so the count present on mount is not announced and StrictMode's effect replay announces nothing; a real change announces once. Announcements made while a sheet is open went to the shared page-body live region, which assistive technology does not expose under a native modal dialog. Each sheet now carries a persistent, named polite status region, created empty and kept mounted, and the add announcement and a result count change that happen while a sheet is open are written there; the closed field keeps using the shared channel. Messages that arrive while a write is pending are joined in order into that write, the way the shared channel joins them, so an add and the result count it changes in the same commit are both heard. --- .../MobilePowerSearch.test.tsx | 170 +++++++++++++++++- .../MobilePowerSearch/MobilePowerSearch.tsx | 118 +++++++++++- 2 files changed, 278 insertions(+), 10 deletions(-) diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx index b48107d2e1f65..c94f6b665bab7 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 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( + , + ); + 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 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( + + + , + ); + await waitFor(() => expect(pageRegion()?.textContent).toBe('1 result')); + // The same value again is not a new occasion. + rerender( + + + , + ); + 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( + , + ); + 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) { @@ -1380,6 +1492,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([openFilter]); + return ( + setFilters([...next])} + resultCount={filters.length * 10} + /> + ); + } + render(); + 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.tsx index c7f1ac4ceb6d8..5909d263cba53 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, @@ -426,6 +432,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 @@ -538,7 +547,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(null); + const pendingSheetMessagesRef = useRef([]); + const sheetAnnouncementClearRef = useRef | null>(null); + const stepRef = useRef(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 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…'; @@ -556,6 +628,8 @@ export function MobilePowerSearch({ ); const triggerId = useId(); + const triggerLabelId = useId(); + const triggerContentId = useId(); const statusMessageId = useId(); const contentResultsId = useId(); const triggerRef = useRef(null); @@ -571,6 +645,7 @@ export function MobilePowerSearch({ const pendingMutationFocusRef = useRef(false); const [step, setStep] = useState(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. @@ -1079,12 +1154,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); } @@ -1218,11 +1301,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 = ( + + {sheetAnnouncement} + + ); + return ( <> -
+ {/* 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). */} +
{startIcon && (
+ {sheetStatus}
@@ -1395,6 +1501,7 @@ export function MobilePowerSearch({ height="tall" padding={0}>
+ {sheetStatus}