An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a search's busy start is never announced after its outcome (#8235)
Cindy Zhangdb7e94503b68
diff --git a/.changeset/busy-start-not-after-outcome.md b/.changeset/busy-start-not-after-outcome.mdnew file mode 100644index 0000000000..ffdad2d744--- /dev/null+++ b/.changeset/busy-start-not-after-outcome.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] BaseTypeahead and CommandPalette: when a typed search finishes before its "Loading" announcement is made, the pending "Loading" is dropped, so a screen reader no longer hears "Loading" after the result count or has it replace the count. This meets the busy-announcement requirement in spec:AST-086 (FR8).++@cixzhangdiff --git a/packages/core/src/CommandPalette/CommandPalette.tsx b/packages/core/src/CommandPalette/CommandPalette.tsxindex 117bffa0dc..02976a8262 100644--- a/packages/core/src/CommandPalette/CommandPalette.tsx+++ b/packages/core/src/CommandPalette/CommandPalette.tsx@@ -30,6 +30,7 @@ import type {SearchSource, SearchableItem} from '../Typeahead';import {useCombobox} from '../Selector';import type {SelectorOptionData} from '../Selector';import {CommandPaletteContext} from './CommandPaletteContext';+import {BusyStartSettleContext} from './busyStartSettle';import {CommandPaletteList} from './CommandPaletteList';import {CommandPaletteItem} from './CommandPaletteItem';import {CommandPaletteGroup} from './CommandPaletteGroup';@@ -317,6 +318,13 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({const isBusy = isPending;const searchVersionRef = useRef(0);const emptyStateRef = useRef<HTMLDivElement>(null);+ const settleBusyAnnouncementRef = useRef<(() => void) | null>(null);+ const registerBusyAnnouncementSettle = useCallback(+ (settle: (() => void) | null) => {+ settleBusyAnnouncementRef.current = settle;+ },+ [],+ );// Announce search results to screen readers through the shared polite live// region (comboboxes-7 announce path, mirroring Selector / BaseTypeahead).@@ -427,6 +435,12 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({const items = await Promise.resolve(result);if (searchVersionRef.current === version) {+ if (!isBootstrap) {+ // This query's outcome is announced below (a count) or from the+ // rendered empty state; a busy start not yet announced would+ // follow it, so the input drops it (spec:AST-086 FR8).+ settleBusyAnnouncementRef.current?.();+ }// Commit query and results togethersetSearch(query);setOptimisticResults(items);@@ -666,7 +680,9 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({defaultHasDividersheader={<LayoutHeader hasDivider padding={0}>- {input ?? <CommandPaletteInput />}+ <BusyStartSettleContext value={registerBusyAnnouncementSettle}>+ {input ?? <CommandPaletteInput />}+ </BusyStartSettleContext></LayoutHeader>}content={diff --git a/packages/core/src/CommandPalette/CommandPaletteInput.tsx b/packages/core/src/CommandPalette/CommandPaletteInput.tsxindex 4011324c09..867f35ae1d 100644--- a/packages/core/src/CommandPalette/CommandPaletteInput.tsx+++ b/packages/core/src/CommandPalette/CommandPaletteInput.tsx@@ -13,7 +13,14 @@* - /packages/cli/assets/templates/blocks/components/CommandPalette/ (showcase blocks)*/-import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';+import {+ use,+ useCallback,+ useEffect,+ useRef,+ useState,+ type ReactNode,+} from 'react';import * as stylex from '@stylexjs/stylex';import {Icon} from '../Icon';import {Spinner} from '../Spinner';@@ -25,6 +32,7 @@ import {typographyVars,} from '../theme/tokens.stylex';import {useCommandPaletteContext} from './CommandPaletteContext';+import {BusyStartSettleContext} from './busyStartSettle';import {useDialogContext} from '../Dialog/DialogContext';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';@@ -194,11 +202,22 @@ export function CommandPaletteInput({// The search Spinner is decorative; the input announces each busy start,// including the load on opening or clearing the query. Inside the palette's// native modal it does so from a region in the dialog (spec:AST-086 FR8, FR3).- useBusyAnnouncement(+ const settleBusyAnnouncement = useBusyAnnouncement(ctx?.isBusy === true,t('@astryx.commandPalette.loading'),inputRef,);+ // Keeps the palette holding this input's settle function, so the palette can+ // drop a busy start not yet announced when a search's outcome is about to be+ // announced (spec:AST-086 FR8).+ const registerSettle = use(BusyStartSettleContext);+ useEffect(() => {+ if (registerSettle == null) {+ return;+ }+ registerSettle(settleBusyAnnouncement);+ return () => registerSettle(null);+ }, [registerSettle, settleBusyAnnouncement]);const [isKeyboardFocus, setIsKeyboardFocus] = useState(false);// Text-entry controls match :focus-visible after pointer focus in Chromium.diff --git a/packages/core/src/CommandPalette/busyStartSettle.ts b/packages/core/src/CommandPalette/busyStartSettle.tsnew file mode 100644index 0000000000..b88464b518--- /dev/null+++ b/packages/core/src/CommandPalette/busyStartSettle.ts@@ -0,0 +1,26 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file busyStartSettle.ts+ * @input The palette's registration for its input's busy-start settle function+ * @output Context the input uses to register that function+ * @position Package-internal; not exported from the package entry point+ *+ * The input owns the search's busy start; the palette is the only thing that+ * knows when a search's outcome is about to be announced, and so when a busy+ * start not yet announced has to be dropped (`spec:AST-086` FR8). A context+ * rather than a member of `CommandPaletteContextValue`, which is exported:+ * this module is not exported from `index.ts`, so the seam stays closed by+ * module boundary.+ */++import {createContext} from 'react';++/** Registers the input's settle function, or `null` when the input goes away. */+export type RegisterBusyStartSettle = (settle: (() => void) | null) => void;++export const BusyStartSettleContext =+ createContext<RegisterBusyStartSettle | null>(null);+BusyStartSettleContext.displayName = 'BusyStartSettleContext';diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex c2b341c154..e12e4514c6 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -565,7 +565,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({// Without a wrapper that took the indicator over, this input announces each// search's busy start (spec:AST-086 FR8); its Spinner stays named but is not// a live region (family:input-fields FR7).- useBusyAnnouncement(+ const settleBusyAnnouncement = useBusyAnnouncement(isLoading && busyLane == null,t('@astryx.typeahead.loading'),inputRef,@@ -735,6 +735,12 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({}// Announce the outcome only for an active query (not the initial// focus-open), so screen-reader users hear result counts / no-results.+ if (searchQuery.length > 0) {+ // This query's outcome is announced now (a count) or from the+ // rendered row (an empty result); a busy start not yet announced+ // would follow it, so it is dropped (spec:AST-086 FR8).+ settleBusyAnnouncement();+ }if (searchQuery.length > 0 && shown.length > 0) {announce(t('@astryx.typeahead.resultCount', {count: shown.length}));}@@ -759,6 +765,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({announce,__queryEntries,setLoading,+ settleBusyAnnouncement,t,],);diff --git a/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx b/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsxindex d0b34d5a6d..81213603cf 100644--- a/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx+++ b/packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx@@ -472,6 +472,65 @@ const SHEET_OWNERS: ReadonlyArray<],];+/** A source whose searches settle in a frame callback that runs before the+ * busy start's frame, as a fast or cached search can. */+function frameSettledSource(): SearchSource<SearchableItem> {+ return {+ search: async () =>+ new Promise<SearchableItem[]>(resolve =>+ requestAnimationFrame(() => resolve([{id: 'alex', label: 'Alex'}])),+ ),+ bootstrap: () => [],+ };+}++describe.each([+ ...SEARCH_OWNERS.filter(([name]) => name !== 'Tokenizer'),+ [+ 'CommandPalette',+ (source: SearchSource<SearchableItem>) => (+ <CommandPalette+ isOpen+ isInline+ onOpenChange={() => {}}+ searchSource={source}+ />+ ),+ ] as const,+])(+ '%s search that settles before its busy start is announced (spec:AST-086 FR8)',+ (_name, renderOwner) => {+ // Browsers run microtasks after each frame callback, while jsdom runs a+ // frame's callbacks back to back. One task per callback lets a search that+ // settles in one callback announce its outcome before the next one runs.+ const jsdomRequestFrame = window.requestAnimationFrame;+ const jsdomCancelFrame = window.cancelAnimationFrame;+ beforeEach(() => {+ window.requestAnimationFrame = callback =>+ window.setTimeout(() => callback(performance.now()), 16);+ window.cancelAnimationFrame = frame => window.clearTimeout(frame);+ });+ afterEach(() => {+ window.requestAnimationFrame = jsdomRequestFrame;+ window.cancelAnimationFrame = jsdomCancelFrame;+ });++ it('announces the outcome and never the overtaken busy start', async () => {+ render(renderOwner(frameSettledSource()));+ await nextFrame();+ announce.mockClear();+ act(() => {+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'Al'}});+ });+ await nextFrame();+ await nextFrame();+ await nextFrame();+ expect(announce).toHaveBeenCalledWith('1 result');+ expect(busyAnnouncements()).toEqual([]);+ });+ },+);+describe.each(SHEET_OWNERS)('%s busy start from inside its open sheet (spec:AST-086 Platform support)',(_name, renderOwner, openSheet) => {diff --git a/packages/core/src/hooks/useBusyAnnouncement.adopters.test.tsx b/packages/core/src/hooks/useBusyAnnouncement.adopters.test.tsxnew file mode 100644index 0000000000..c7acc2d628--- /dev/null+++ b/packages/core/src/hooks/useBusyAnnouncement.adopters.test.tsx@@ -0,0 +1,69 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useBusyAnnouncement.adopters.test.tsx+ * @input Uses vitest, @testing-library/react, BaseTypeahead, CommandPalette+ * @output Tests that search controls settle their busy start when a search ends+ * @position Testing; validates the settle wiring in useBusyAnnouncement adopters+ */++import {beforeEach, describe, expect, it, vi} from 'vitest';+import {fireEvent, render, screen, waitFor} from '@testing-library/react';+import {BaseTypeahead} from '../Typeahead/BaseTypeahead';+import {CommandPalette} from '../CommandPalette';+import {createStaticSource} from '../Typeahead/createStaticSource';++const settle = vi.hoisted(() => vi.fn());+vi.mock('./useBusyAnnouncement', () => ({+ useBusyAnnouncement: () => settle,+}));++const source = createStaticSource([+ {id: 'apple', label: 'Apple'},+ {id: 'banana', label: 'Banana'},+]);++// jsdom does not implement the modal dialog methods CommandPalette uses.+beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+});++describe('busy-start settle wiring (AST-086 FR8)', () => {+ it("BaseTypeahead settles its busy start when a typed query's search settles", async () => {+ render(+ <BaseTypeahead+ searchSource={source}+ value={null}+ onChange={() => {}}+ debounceMs={0}+ />,+ );+ settle.mockClear();+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'Ap'}});+ await waitFor(() => expect(settle).toHaveBeenCalled());+ // An empty result is announced from the rendered row; it settles too.+ settle.mockClear();+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});+ await waitFor(() => expect(settle).toHaveBeenCalled());+ });++ it("CommandPalette settles its input busy start when a typed query's search settles", async () => {+ render(+ <CommandPalette isOpen onOpenChange={() => {}} searchSource={source} />,+ );+ await waitFor(() => expect(screen.getByText('Apple')).toBeInTheDocument());+ settle.mockClear();+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'ban'}});+ await waitFor(() => expect(settle).toHaveBeenCalled());+ settle.mockClear();+ fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});+ await waitFor(() => expect(settle).toHaveBeenCalled());+ });+});diff --git a/packages/core/src/hooks/useBusyAnnouncement.test.tsx b/packages/core/src/hooks/useBusyAnnouncement.test.tsxnew file mode 100644index 0000000000..f1153a60e6--- /dev/null+++ b/packages/core/src/hooks/useBusyAnnouncement.test.tsx@@ -0,0 +1,82 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useBusyAnnouncement.test.tsx+ * @input Uses vitest, @testing-library/react, useBusyAnnouncement+ * @output Unit tests for the busy-start announcement and its settle function+ * @position Testing; validates useBusyAnnouncement.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {act, renderHook} from '@testing-library/react';+import {useRef} from 'react';+import {useBusyAnnouncement} from './useBusyAnnouncement';+import {__resetLiveRegionsForTest} from './useAnnounce';++function politeText(): string {+ return (+ document.querySelector('[data-astryx-live-region="polite"]')?.textContent ??+ ''+ );+}++interface BusyProps {+ isBusy: boolean;+ message?: string;+}++function renderBusy() {+ return renderHook<() => void, BusyProps>(+ ({isBusy, message = 'Loading'}) =>+ useBusyAnnouncement(isBusy, message, useRef(null)),+ {initialProps: {isBusy: true}},+ );+}++function runFrames() {+ act(() => {+ vi.advanceTimersByTime(50);+ });+}++describe('useBusyAnnouncement', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ __resetLiveRegionsForTest();+ vi.useRealTimers();+ });++ it('announces a busy start a frame after it begins', () => {+ renderBusy();+ runFrames();+ expect(politeText()).toBe('Loading');+ });++ it('drops a busy start its owner settled before it was announced (AST-086 FR8)', () => {+ const {result} = renderBusy();+ act(() => {+ result.current();+ });+ runFrames();+ expect(politeText()).toBe('');+ });++ it('keeps a settled busy start dropped until the next busy start', () => {+ const {result, rerender} = renderBusy();+ act(() => {+ result.current();+ });+ // Still busy until the settled state commits: nothing is rescheduled,+ // even when the busy message changes (a locale switch, say).+ rerender({isBusy: true, message: 'Chargement'});+ runFrames();+ expect(politeText()).toBe('');++ rerender({isBusy: false});+ rerender({isBusy: true});+ runFrames();+ expect(politeText()).toBe('Loading');+ });+});diff --git a/packages/core/src/hooks/useBusyAnnouncement.ts b/packages/core/src/hooks/useBusyAnnouncement.tsindex 1279c95775..7db40c9df3 100644--- a/packages/core/src/hooks/useBusyAnnouncement.ts+++ b/packages/core/src/hooks/useBusyAnnouncement.ts@@ -13,7 +13,9 @@* The busy Spinner inside a control is decorative (hidden, no live role); the* control announces its busy state instead (`spec:AST-086` FR8), once per busy* start (FR6): rerenders and StrictMode replay do not repeat it, and settling- * re-arms it. While a native modal is open, the body-level channel is not+ * re-arms it. The returned function is called by an owner announcing the+ * busy operation's outcome: a busy start not yet announced is dropped, so it+ * never follows its own outcome (FR8). While a native modal is open, the body-level channel is not* exposed, so a control inside it announces through one persistent polite* region in that dialog, inserted empty and filled a frame later (Platform* support, FR3).@@ -22,7 +24,7 @@* this is a shared implementation detail of Astryx's busy controls.*/-import {useEffect, useRef, type RefObject} from 'react';+import {useCallback, useEffect, useRef, type RefObject} from 'react';import {useAnnounce} from './useAnnounce';const REGION_ATTR = 'data-astryx-modal-busy-region';@@ -73,9 +75,10 @@ export function useBusyAnnouncement(isBusy: boolean,message: string,elementRef: RefObject<Element | null>,-): void {+): () => void {const announce = useAnnounce();const hasAnnouncedRef = useRef(false);+ const frameRef = useRef<number | null>(null);useEffect(() => {if (!isBusy) {hasAnnouncedRef.current = false;@@ -87,6 +90,7 @@ export function useBusyAnnouncement(// Choose the route a frame later: a Dialog opening in the same commit// calls showModal() in its own Effect, which runs after this one.const frame = requestAnimationFrame(() => {+ frameRef.current = null;hasAnnouncedRef.current = true;const dialog = elementRef.current?.closest('dialog');if (dialog?.open && dialog.matches(':modal')) {@@ -95,6 +99,19 @@ export function useBusyAnnouncement(announce(message, 'polite');}});- return () => cancelAnimationFrame(frame);+ frameRef.current = frame;+ return () => {+ cancelAnimationFrame(frame);+ frameRef.current = null;+ };}, [announce, elementRef, isBusy, message]);++ return useCallback(() => {+ if (frameRef.current != null) {+ cancelAnimationFrame(frameRef.current);+ frameRef.current = null;+ // Still busy until the settled state commits; do not schedule again.+ hasAnnouncedRef.current = true;+ }+ }, []);}