An open source design system that's fully customizable and agent ready
TypeScript
fix(Spinner): route standalone loading through the shared announcement channel (#7910)
zakelstorm1ef21f898e30
diff --git a/.changeset/spinner-shared-announcement.md b/.changeset/spinner-shared-announcement.mdnew file mode 100644index 0000000000..1c8b25f94c--- /dev/null+++ b/.changeset/spinner-shared-announcement.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A standalone Spinner used to mount `role="status"` already holding its name, so screen readers often said nothing when it appeared. It is now an indeterminate progress indicator (`role="progressbar"` with no `aria-valuenow`, named by its visible string label, its `aria-label` or a translated "Loading") that announces once through the shared polite channel when it appears after page load, reading its rendered text in order with stacked lines kept apart, or its accessible name (AST-020 FR15; AST-086 FR2, FR7, FR11–FR12; WCAG 2.2 4.1.3). BaseTypeahead, Typeahead and Tokenizer keep their search Spinner named and never live while they announce the search themselves, and app code silences a composed Spinner with `aria-hidden`. No app change is needed (AST-017 FR53): a Spinner given a `role` other than `progressbar` stays silent, as before. The lab EmojiPicker and Schedule now hide their loading rings and announce their own busy start once, and the Comments history dialog announces it inside the dialog (AST-086 FR6, FR8, FR14); their loading words stay readable. Every Spinner's indicator changes from `status` to `progressbar`, so a test that queries it by role changes, including the hidden rings inside Button, CheckboxInput, CheckboxList, CheckIndicator, ChatMessageList, ChatToolCalls, CommandPaletteInput, ComplexSelector, DateInput, DateRangeInput, DateTimeInput, DropdownMenu's sub-menus, FileInput, MultiSelector, Selector, Switch, TextArea, TextInput, Thumbnail and TimeInput, and lab's EmojiPicker, Comments and Schedule.++@korkt-kimdiff --git a/docs/specs/components/Spinner/Spinner.spec.md b/docs/specs/components/Spinner/Spinner.spec.mdindex 1189308b7d..5da7d421d2 100644--- a/docs/specs/components/Spinner/Spinner.spec.md+++ b/docs/specs/components/Spinner/Spinner.spec.md@@ -28,22 +28,23 @@ architecture:architecture:public-component-api,]contributing: []-system_specs: [spec:AST-009, spec:AST-086, spec:AST-108/FR4]+system_specs:+ [spec:AST-009, spec:AST-017, spec:AST-020, spec:AST-086, spec:AST-108/FR4]---# Spinner component contract## Contract at a glance-| Area | Contract |-| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | An animated ring with `size` (`sm`–`xl`), `shade`, an optional visible `label`, and five public theme variables for geometry and color. |-| Behavior | The ring sits in a named indicator; a visible label renders below it, and a non-empty string label names the indicator through `aria-labelledby` instead of repeating it. A standalone Spinner announces through the shared channel (AR1). |-| End-user impact | Sighted users see ongoing work; screen-reader users find a named indicator, defaulting to a translated "Loading"; readers who reduce motion see a slowed ring rather than a frozen one. |-| Builder impact | None; the record describes shipped behavior. |-| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. Two implementation gaps are listed under Current-state impact. |-| Review checks | Reject an indicator without an accessible name, a duplicated string-label name, a live role mounted already holding its text, a box that a flex host can compress, a caller `style` that overrides the box size, or a ring that stops under reduced motion. |-| Governing rules | `spec:AST-086/FR2,FR8,FR11`; `architecture:component-theming-surface/INV6`; `architecture:internationalization/INV1a`; `architecture:public-component-api/INV5,INV6,INV8`. |+| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | An animated ring with `size` (`sm`–`xl`), `shade`, an optional visible `label`, and five public theme variables for geometry and color. |+| Behavior | The ring sits in a named indicator; a visible label renders below it, and a non-empty string label names the indicator through `aria-labelledby` instead of repeating it. A standalone Spinner announces through the shared channel (AR1). |+| End-user impact | Sighted users see ongoing work; screen-reader users find a named indicator, defaulting to a translated "Loading"; readers who reduce motion see a slowed ring rather than a frozen one. |+| Builder impact | Every Spinner's indicator changes from `status` to `progressbar`, including the hidden rings inside composing components, so a consumer test that queries the indicator by role changes; no prop, default or styling changes. |+| Compatibility/readiness | An accessibility fix: the role becomes `progressbar` and a standalone Spinner announces through the channel; no public prop or default changes, and app code needs no change (`spec:AST-017` FR53): a caller `role` other than `progressbar` keeps the Spinner silent, as it shipped. The remaining gaps are listed under Current-state impact. |+| Review checks | Reject an indicator without an accessible name, a duplicated string-label name, a live role mounted already holding its text, a box that a flex host can compress, a caller `style` that overrides the box size, or a ring that stops under reduced motion. |+| Governing rules | `spec:AST-086/FR2,FR8,FR11`; `spec:AST-020/FR15`; `spec:AST-017/FR53`; `architecture:component-theming-surface/INV6`; `architecture:internationalization/INV1a`; `architecture:public-component-api/INV5,INV6,INV8`. |This table is a review projection; the body below is authoritative.@@ -51,13 +52,18 @@ This table is a review projection; the body below is authoritative.Spinner shows that work of unknown duration is in progress. It owns the ring'sgeometry, motion, and shades, the optional visible label beneath it, and the-status element's accessible name.+indicator's accessible name.## Compatibility and migration-- Released default preserved: `yes`-- Compatibility class: records shipped behavior; no public prop, default, DOM,- or styling output changes+- Released default preserved: `yes` for every prop; the indicator's role and+ announcement change as an accessibility fix (AR1)+- Compatibility class: accessibility fix with no public prop, default, or+ styling output change; app code needs no change (`spec:AST-017` FR53)+- Shipped compatibility under FR53: a caller `role` other than `progressbar`+ keeps the Spinner silent, as it shipped, so app code that silenced a+ composed ring that way keeps working. It is not a recommended mode; new code+ hides a composed Spinner with `aria-hidden`- Controlled/uncontrolled behavior: not applicable; Spinner holds no state- Migration decision: none@@ -65,35 +71,30 @@ Consumer migration instructions belong in consumer docs and release notes.## Current-state impact-- **Standalone status mounts holding its name (AR1).** A standalone Spinner- mounts as `role="status"` with its accessible name already present and- writes nothing to the shared announcement channel, where `spec:AST-086` FR2- and FR11 require a standalone indicator that appears after page load to- announce through the channel and not mount a live role holding its text. A- conditionally rendered Spinner is therefore often silent.-- **Empty or lost name (AR1).** `aria-label=""` is used as the name, and- `label=""` renders an empty visible Text and names the status from it; either- leaves the status with an empty accessible name (WCAG 2.2 4.1.2). With a+ `label=""` renders an empty visible Text and names the indicator from it; either+ leaves the indicator with an empty accessible name (WCAG 2.2 4.1.2). With a`label`, a caller `aria-labelledby` reaches the role-less wrapper instead of- the status.+ the indicator.## Ownership boundary**Owns**-- The status element, the ring drawn inside it, and the optional label below+- The indicator, the ring drawn inside it, and the optional label belowit.- Ring geometry per `size`, ring and track color per `shade`, the arc's turn,and the reduced-motion rate.- The five public theme variables and where they are declared.-- The status element's accessible name, including the translated default.+- The indicator's accessible name, including the translated default.**Does not own / non-goals**- Whether a composing component's busy indicator is silent — owned by that- component under `spec:AST-086` FR8; a composer silences Spinner through- passthrough attributes.+ component under `spec:AST-086` FR8. Core composers and app code hide it+ with `aria-hidden`; Typeahead, BaseTypeahead and Tokenizer, which keep+ their search indicator named, silence it through an internal,+ non-exported path.- Content-shaped loading placeholders — owned by `component:Skeleton`.- Determinate progress — owned by `component:ProgressBar`.- Rich label content, when `label` is a node — owned by the caller.@@ -111,14 +112,14 @@ Consumer migration instructions belong in consumer docs and release notes.| ID | Invariant | Basis || --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |-| FR1 | Without a label, Spinner renders one inline-grid `span` status element that carries the `spinner` target, ref, `data-testid`, and passthrough props. With a label, a column `div` wrapper with `--spacing-2` gap carries the target, ref, `data-testid`, passthrough props, and styling inputs; the status `span` and then the label render inside it. | Current source and tests |-| FR2 | The status element's box is the ring diameter plus one stroke width on each side, set inline after the caller's `style`, so a caller `width` or `height` never resizes it while other caller styles still apply. The box does not shrink in a flex host. With no stylesheet, the box and ring draw at the size's default geometry. | Current source and tests |+| FR1 | Without a label, Spinner renders one inline-grid `span` indicator that carries the `spinner` target, ref, `data-testid`, and passthrough props. With a label, a column `div` wrapper with `--spacing-2` gap carries the target, ref, `data-testid`, passthrough props, and styling inputs; the indicator `span` and then the label render inside it. | Current source and tests |+| FR2 | The indicator's box is the ring diameter plus one stroke width on each side, set inline after the caller's `style`, so a caller `width` or `height` never resizes it while other caller styles still apply. The box does not shrink in a flex host. With no stylesheet, the box and ring draw at the size's default geometry. | Current source and tests || FR3 | The ring is an `aria-hidden` track circle and an `aria-hidden` arc covering `--spinner-arc-fraction` of the circumference (0.375 by default), starting at twelve o'clock with round caps. The arc turns around the stationary track at `--duration-slow-min` per cycle, as the theme sets it before `tempo` scales it (`spec:AST-108` FR4), linear, indefinitely; under `prefers-reduced-motion: reduce` the cycle slows to 3 seconds and does not stop. | Current source and tests || FR4 | All mounted rings turn in the same phase, whenever each mounted. Where the browser cannot report running animations, Spinner does no phase work. | Current source and tests || FR5 | `default` paints `--color-accent` on `--color-track`; `subtle` paints `--color-text-secondary` on `--color-track`; `onMedia` paints `--color-on-dark` on itself at track opacity 77/255; `inherit` paints `currentColor` on itself at track opacity 0.3. | Current source and tests |-| FR6 | The five public variables are declared only on the element carrying the `spinner` target, per `size` and `shade`, so a theme rule on that target and its `size:` or `shade:` variants overrides them; the inner status element inherits them when a label moves the target to the wrapper. | Current source and tests |+| FR6 | The five public variables are declared only on the element carrying the `spinner` target, per `size` and `shade`, so a theme rule on that target and its `size:` or `shade:` variants overrides them; the inner indicator inherits them when a label moves the target to the wrapper. | Current source and tests || FR7 | A string label renders as bold body Text; a rich-node label renders as supplied. | Current source and tests |-| FR8 | `xstyle` and `className` reach the element carrying the target and merge after component styles; `style` merges after them except for the status box's `width` and `height` (FR2). | Current source and tests |+| FR8 | `xstyle` and `className` reach the element carrying the target and merge after component styles; `style` merges after them except for the indicator box's `width` and `height` (FR2). | Current source and tests |### Allowed variation@@ -129,19 +130,19 @@ Consumer migration instructions belong in consumer docs and release notes.### Representative states-| State | Required invariant | Allowed variation |-| --------------------- | ---------------------------------------------------------------------------------------------------- | ----------------- |-| Unlabelled | Status `span` carries the target and the translated "Loading" name (`role="status"` is the AR1 gap). | Size, shade. |-| String label | Wrapper carries the target; status named by `aria-labelledby` to the visible Text. | Label text. |-| Rich label | Status named by `aria-label` (caller's, else "Loading"); node renders as supplied. | Node content. |-| Explicit `aria-label` | Status named by that value, with or without a label. | — |-| Reduced motion | Arc keeps moving at a 3-second cycle. | — |-| Narrow flex host | Status box keeps its full size and overflows rather than compressing. | — |+| State | Required invariant | Allowed variation |+| --------------------- | ------------------------------------------------------------------------------------- | ----------------- |+| Unlabelled | Progressbar `span` carries the target and the translated "Loading" name. | Size, shade. |+| String label | Wrapper carries the target; indicator named by `aria-labelledby` to the visible Text. | Label text. |+| Rich label | Indicator named by `aria-label` (caller's, else "Loading"); node renders as supplied. | Node content. |+| Explicit `aria-label` | Indicator named by that value, with or without a label. | — |+| Reduced motion | Arc keeps moving at a 3-second cycle. | — |+| Narrow flex host | Indicator box keeps its full size and overflows rather than compressing. | — |### Transformation and precedence order- **ORD1 — Accessible name.** Without a `label`, a caller `aria-labelledby`- reaches the status element and names it from the referenced element. Then:+ reaches the indicator and names it from the referenced element. Then:non-empty caller `aria-label` → non-empty string `label` (by`aria-labelledby` when no `aria-label` is set) → translated`@astryx.spinner.loading` ("Loading"). An empty `aria-label` or `label`, and@@ -167,10 +168,17 @@ Consumer migration instructions belong in consumer docs and release notes.page load announces through the shared channel, and its element carries nolive role or `aria-live` (`spec:AST-086` FR2, FR11); a Spinner inside a busyowner is silent (`spec:AST-086` FR8). The indicator has an accessible name by- ORD1, and a visible string label is never repeated as `aria-label`. OQ1 holds- the role and name it exposes without a live role. Implementation gaps: the- element is `role="status"`, mounted already holding its name, and writes- nothing to the shared channel; `aria-label=""` or `label=""` leaves it with an+ ORD1, and a visible string label is never repeated as `aria-label`. The+ indicator is an indeterminate progress indicator: `role="progressbar"` with no+ `aria-valuenow`, named as ORD1 orders it (a visible+ string label through `aria-labelledby`, never repeated as `aria-label`) (`spec:AST-020` FR15;+ OQ1, decided). A composed Spinner is silenced by hiding it with+ `aria-hidden`, as CheckboxInput, Switch, Button and most Core composers+ and app code do; Typeahead, BaseTypeahead and Tokenizer, which keep their+ search indicator named, silence it through an internal, non-exported path. A caller `role` other than+ `progressbar` also keeps it silent, as shipped compatibility under+ `spec:AST-017` FR53 (see Compatibility and migration). No public prop+ silences it. Implementation gaps: `aria-label=""` or `label=""` leaves it with anempty name; and with a `label`, a caller `aria-labelledby` lands on therole-less wrapper and names nothing.@@ -193,8 +201,8 @@ consumer anatomy names no parts, so no anatomy-theming block is declared.## Family and system relationships-- `spec:AST-086` owns status-announcement delivery; AR1 records Spinner's gap- against FR2 and FR11, and composing busy owners are silent under FR8.+- `spec:AST-086` owns status-announcement delivery; AR1 records how Spinner+ meets FR2 and FR11, and composing busy owners are silent under FR8.- `architecture:component-theming-surface` owns target and variablequalification; FR6 records where Spinner declares its variables.- `architecture:internationalization` owns the catalog the default name uses.@@ -210,21 +218,25 @@ consumer anatomy names no parts, so no anatomy-theming block is declared.| FR3, FR4, PR2 | `Spinner.test.tsx` ring suite, including the 135-degree sweep test; `SpinnerMotion.a11y.chromium.spec.ts` | Track and rotor structure, default dash and arc fraction, frame scheduling; a 700 ms main-thread block, one period, several rings | A lost circle, a changed default dash or arc fraction, an extra frame, or unbatched pinning fails, and so does a ring that stops while a script runs, paints every frame, turns at another rate or direction, or drifts out of phase. Gap: the start-angle test checks only for no SVG `transform` attribute, so removing the CSS start rotation passes; the themed arc fraction and dropping an unmounted ring from pending phase work have no automated check. | `audit:Spinner/motion` || FR5, FR6 | `Spinner.test.tsx` theme-variable suite | Size-, shade-, and base-scoped overrides | A themed variable emitted on the wrong selector fails. Gap: no test fails if the component declares its defaults on the inner span of a labelled Spinner, and the shade tests assert presence and reflection only, so the default colors and track opacities have no automated check. | `audit:Spinner/theming` || PR1 | `Spinner.test.tsx` registration suite | Import, repeated evaluation | Doing the work on mount or throwing on a second evaluation fails. Gap: the suite runs only with a DOM, so server-side safety has no automated check. | `audit:Spinner/behavior` |-| AR1, AR3 | `Spinner.test.tsx` naming and localization tests | Default, explicit, string, and rich labels | A missing name, a string label repeated as `aria-label`, or an untranslated default fails. Gap: no test covers an empty `aria-label` or `label`, or a caller `aria-labelledby`. | `audit:Spinner/a11y` |+| AR1, AR3 | `Spinner.test.tsx` naming and localization tests | Default, explicit, string, and rich labels | A missing name, a string label repeated as `aria-label`, or an untranslated default fails. The announcement suite covers once-per-appearance delivery, page-load silence, silence inside a Core owner and a caller `aria-labelledby` name. Gap: no test covers an empty `aria-label` or `label`. | `audit:Spinner/a11y` || AR4 | `SpinnerMotion.a11y.chromium.spec.ts` reduced-motion test | Reduced motion | A ring that stops, or turns at another rate than 3 seconds per cycle, fails. | `audit:Spinner/motion` || AR2 | Source review | Every state | Gap: no automated check fails if the track or the rotor loses `aria-hidden`. | `audit:Spinner/a11y` |-| AR1, AR2 | `StatusMessage.a11y.chromium.spec.ts` Spinner states | Default label and visible string label, mounted | A changed role or name fails the accessibility-tree assertions. Gap: rich labels, empty names, the hidden ring, and channel delivery have no accessibility-tree check. | `audit:Spinner/a11y` |+| AR1, AR2 | `StatusMessage.a11y.chromium.spec.ts` Spinner states | Default label and visible string label, mounted | A changed role or name fails the accessibility-tree assertions. Gap: rich labels, empty names and the hidden ring have no accessibility-tree check; channel delivery is checked by `Spinner.test.tsx`'s announcement suite. | `audit:Spinner/a11y` |## Decision log-None recorded. The record describes shipped behavior.+- **OQ1 — the role and name of a standalone Spinner without a live role.**+ Decided by `spec:AST-020` FR15: an indeterminate progress indicator,+ `role="progressbar"` with no `aria-valuenow`, named as ORD1 orders it. A composed+ indicator is silent (`spec:AST-086` FR8): hidden with `aria-hidden` by most+ Core composers and by app code, silenced through an internal path by the+ three search composers, and a caller `role` other than+ `progressbar` stays silent as shipped compatibility (`spec:AST-017` FR53);+ Spinner admits no announcement prop.## Open questions-- **OQ1 — What role and name should a standalone Spinner expose once it no- longer carries a live role?** (`human-api`) `spec:AST-086` leaves this outside- its scope. Options: a named image, a named generic element with no role, or- no exposed node with the channel message as the only output.+None open. OQ1 is decided (see the decision log).## Content boundarydiff --git a/packages/core/src/CheckboxList/CheckboxList.test.tsx b/packages/core/src/CheckboxList/CheckboxList.test.tsxindex 52bb65e21f..0bda7c54ff 100644--- a/packages/core/src/CheckboxList/CheckboxList.test.tsx+++ b/packages/core/src/CheckboxList/CheckboxList.test.tsx@@ -1063,7 +1063,9 @@ describe('CheckboxListItem ARIA props', () => {// The spinner is decorative — it lives inside the checkbox's// aria-hidden visual box, so query with hidden:true. The accessible// loading signal is `aria-busy` on the item (asserted above).- expect(screen.getByRole('status', {hidden: true})).toBeInTheDocument();+ const spinner = screen.getByRole('progressbar', {hidden: true});+ expect(spinner).toBeInTheDocument();+ expect(spinner.closest('[aria-hidden="true"]')).not.toBeNull();});it('does not toggle when item-level isLoading is set', () => {@@ -1101,12 +1103,12 @@ describe('CheckboxListItem ARIA props', () => {// The toggled item becomes busy and shows a spinner; the sibling stays idle.// The spinner is decorative (inside the aria-hidden box), so query hidden.expect(- await within(itemA).findByRole('status', {hidden: true}),+ await within(itemA).findByRole('progressbar', {hidden: true}),).toBeInTheDocument();expect(itemA).toHaveAttribute('aria-busy', 'true');expect(itemB).not.toHaveAttribute('aria-busy');expect(- within(itemB).queryByRole('status', {hidden: true}),+ within(itemB).queryByRole('progressbar', {hidden: true}),).not.toBeInTheDocument();expect(changeAction).toHaveBeenCalledWith(['a']);});@@ -1175,7 +1177,7 @@ describe('CheckboxListItem ARIA props', () => {await waitFor(() => expect(itemB).toHaveAttribute('aria-busy', 'true'));expect(itemA).toHaveAttribute('aria-busy', 'true');expect(- within(itemA).getByRole('status', {hidden: true}),+ within(itemA).getByRole('progressbar', {hidden: true}),).toBeInTheDocument();// Re-toggling the still-pending item stays blocked.diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.ts b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.tsindex a47f0bd881..868cdda325 100644--- a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.ts+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.chromium.spec.ts@@ -88,6 +88,7 @@ async function bindSubject(name: facts.initialMessage,});} else {+ await expect(candidates).toContainText([facts.initialMessage]);const texts = await candidates.evaluateAll(elements =>elements.map(element =>(element.textContent ?? '').replace(/\s+/g, ' ').trim(),@@ -139,6 +140,22 @@ async function transition(page: Page, name: string): Promise<void> {);}+async function expectSpinnerIndicator(+ page: Page,+ cdp: CDPSession,+ name: string,+): Promise<void> {+ const harness = createChromiumHarness({+ page,+ cdp,+ subject: page.getByRole('progressbar', {name}),+ });+ expect(await (await harness.subject()).computed()).toMatchObject({+ role: 'progressbar',+ name,+ });+}+async function runState(page: Page,cdp: CDPSession,@@ -152,6 +169,12 @@ async function runState(knownFailures: CORE_STATUS_MESSAGE_KNOWN_FAILURES,mount: async () => {await mountState(page, state);+ if (+ state.binding === 'Spinner announcement channel' &&+ state.facts.kind === 'live-region'+ ) {+ await expectSpinnerIndicator(page, cdp, state.facts.initialMessage);+ }return createChromiumHarness({page,cdp,@@ -180,6 +203,12 @@ for (const state of CORE_STATUS_MESSAGE_BINDING_STATES) {test.setTimeout(2 * 60 * 1000);const cdp = await page.context().newCDPSession(page);const result = await runState(page, cdp, state);+ if (+ state.binding === 'Spinner announcement channel' &&+ state.facts.kind === 'live-region'+ ) {+ await expectSpinnerIndicator(page, cdp, state.facts.replacement);+ }recorded.set(state.id, result);const report = summarize(STATUS_MESSAGE_PATTERN, [result]);// eslint-disable-next-line no-console -- the report is this run's artifact@@ -190,7 +219,7 @@ for (const state of CORE_STATUS_MESSAGE_BINDING_STATES) {});}-test('every expectation is exercised by at least one Core binding state', async ({+test('every Core-applicable expectation is exercised by a binding state', async ({page,}) => {test.setTimeout(4 * 60 * 1000);@@ -199,7 +228,9 @@ test('every expectation is exercised by at least one Core binding state', asyncfor (const state of CORE_STATUS_MESSAGE_BINDING_STATES) {results.push(recorded.get(state.id) ?? (await runState(page, cdp, state)));}- expect(neverExercised(results)).toEqual([]);+ expect(neverExercised(results)).toEqual([+ 'status-message.message.name-exposed',+ ]);expect(unmatchedKnownFailures(CORE_STATUS_MESSAGE_KNOWN_FAILURES, results),).toEqual([]);diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.tsindex 34192d6122..8f20c54896 100644--- a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.states.ts@@ -13,7 +13,7 @@ export type CoreStatusMessageBinding =| 'Toast announcement channel'| 'Toast card'| 'FieldStatus announcement channel'- | 'Spinner'+ | 'Spinner announcement channel'| 'ProgressBar';export interface CoreStatusMessageBindingDefinition {@@ -157,14 +157,13 @@ export const CORE_STATUS_MESSAGE_BINDING_STATES = [},{id: 'spinner-default-label-mounted',- binding: 'Spinner',+ binding: 'Spinner announcement channel',summary:- 'a loading spinner is mounted with its default accessible status name',+ 'a mounted spinner sends its default label and updates through the persistent polite channel',facts: liveFacts({role: 'status',politeness: 'polite',initialMessage: 'Loading',- messageSource: 'accessible-name',message: 'Loading',replacement: 'Saving',semanticTransitions: ['replace'],@@ -173,14 +172,13 @@ export const CORE_STATUS_MESSAGE_BINDING_STATES = [},{id: 'spinner-visible-label-mounted',- binding: 'Spinner',+ binding: 'Spinner announcement channel',summary:- 'a loading spinner is mounted with a visible label that names its status role',+ 'a mounted spinner sends its visible label and updates through the persistent polite channel',facts: liveFacts({role: 'status',politeness: 'polite',initialMessage: 'Fetching data',- messageSource: 'accessible-name',message: 'Fetching data',replacement: 'Saving data',semanticTransitions: ['replace'],diff --git a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsx b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsxindex 9156b98906..7da4ed1fda 100644--- a/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsx+++ b/packages/core/src/FieldStatus/__tests__/StatusMessage.a11y.test.tsx@@ -46,6 +46,7 @@ async function renderState(await waitFor(() =>expect(document.querySelector('[data-a11y-ready="true"]')).not.toBeNull(),);+ await waitFor(() => expect(subjectFor(state)).toBeInTheDocument());}function subjectFor(state: CoreStatusMessageBindingState): Element {@@ -130,7 +131,7 @@ describe('Core status-message binding inventory', () => {).toEqual(['FieldStatus announcement channel','ProgressBar',- 'Spinner',+ 'Spinner announcement channel','Toast announcement channel','Toast card',]);diff --git a/packages/core/src/Spinner/Spinner.doc.mjs b/packages/core/src/Spinner/Spinner.doc.mjsindex 4b7d031a93..ad36330983 100644--- a/packages/core/src/Spinner/Spinner.doc.mjs+++ b/packages/core/src/Spinner/Spinner.doc.mjs@@ -6,7 +6,18 @@ export const docs = {name: 'Spinner',displayName: 'Spinner',category: 'Feedback & Status',- keywords: ["spinner","loader","loading","circular","progress","spin","activity","busy","indeterminate","circularprogress"],+ keywords: [+ 'spinner',+ 'loader',+ 'loading',+ 'circular',+ 'progress',+ 'spin',+ 'activity',+ 'busy',+ 'indeterminate',+ 'circularprogress',+ ],props: [{name: 'size',@@ -24,7 +35,7 @@ export const docs = {name: 'label',type: 'ReactNode',description:- 'Visible content below the spinner. String labels auto-set aria-label.',+ 'Visible content below the spinner. A string label names the indicator through aria-labelledby.',},{name: 'aria-label',@@ -39,26 +50,68 @@ export const docs = {description:'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value, not an inline style object like style={{}}.',},- ], theming: {- targets: [- {className: 'astryx-spinner', visualProps: ['size', 'shade']},- ],+ ],+ theming: {+ targets: [{className: 'astryx-spinner', visualProps: ['size', 'shade']}],vars: [- {name: '--spinner-diameter', description: "Diameter of the drawn ring. Set it on a size-variant target to retheme what each named size resolves to, e.g. spinner: { 'size:xl': { '--spinner-diameter': '2.5rem' } }. The rendered box is this plus the stroke width on each side, and follows automatically. Any length works: rem, em and calc() are resolved before the ring is drawn.", default: '10px (sm), 14px (md), 18px (lg), 28px (xl)'},- {name: '--spinner-stroke-width', description: 'Stroke width of both circles the ring is drawn from: the moving arc and the track behind it. Set it per size alongside the diameter. One stroke width drives both, so 0 is honoured as a zero-width stroke and paints nothing at all rather than falling back to the default; for an arc with no track behind it, set --spinner-track-color to transparent instead.', default: '2px (sm), 3px (md), 3px (lg), 4px (xl)'},- {name: '--spinner-color', description: "Color of the moving arc. Defaults to the shade's token, so set it on a shade-variant target to retheme one shade (spinner: { 'shade:subtle': { '--spinner-color': 'var(--color-text-tertiary)' } }), or on the base target to retheme all four. Accepts any color notation, including var(), color-mix() and currentColor.", default: 'var(--color-accent) (default), var(--color-text-secondary) (subtle), var(--color-on-dark) (onMedia), currentColor (inherit)'},- {name: '--spinner-track-color', description: 'Color of the track the arc travels on. Set it to `transparent` for an arc with no track. The onMedia and inherit shades draw the track at reduced alpha (30%) so it reads against an arbitrary backdrop; that fade applies to a themed color too.', default: 'var(--color-track) (default, subtle), var(--color-on-dark) (onMedia), currentColor (inherit)'},- {name: '--spinner-arc-fraction', description: "Fraction of the ring the moving arc covers, as a plain number (not a percentage or angle). Set it on a size-variant target the same way as --spinner-diameter, e.g. spinner: { 'size:xl': { '--spinner-arc-fraction': '0.75' } } for a 270deg sweep. Only takes effect once the stylesheet loads; a render with no CSS (SSR, no-JS) always draws the default 135deg arc.", default: '0.375 (135deg), same for every size'},+ {+ name: '--spinner-diameter',+ description:+ "Diameter of the drawn ring. Set it on a size-variant target to retheme what each named size resolves to, e.g. spinner: { 'size:xl': { '--spinner-diameter': '2.5rem' } }. The rendered box is this plus the stroke width on each side, and follows automatically. Any length works: rem, em and calc() are resolved before the ring is drawn.",+ default: '10px (sm), 14px (md), 18px (lg), 28px (xl)',+ },+ {+ name: '--spinner-stroke-width',+ description:+ 'Stroke width of both circles the ring is drawn from: the moving arc and the track behind it. Set it per size alongside the diameter. One stroke width drives both, so 0 is honoured as a zero-width stroke and paints nothing at all rather than falling back to the default; for an arc with no track behind it, set --spinner-track-color to transparent instead.',+ default: '2px (sm), 3px (md), 3px (lg), 4px (xl)',+ },+ {+ name: '--spinner-color',+ description:+ "Color of the moving arc. Defaults to the shade's token, so set it on a shade-variant target to retheme one shade (spinner: { 'shade:subtle': { '--spinner-color': 'var(--color-text-tertiary)' } }), or on the base target to retheme all four. Accepts any color notation, including var(), color-mix() and currentColor.",+ default:+ 'var(--color-accent) (default), var(--color-text-secondary) (subtle), var(--color-on-dark) (onMedia), currentColor (inherit)',+ },+ {+ name: '--spinner-track-color',+ description:+ 'Color of the track the arc travels on. Set it to `transparent` for an arc with no track. The onMedia and inherit shades draw the track at reduced alpha (30%) so it reads against an arbitrary backdrop; that fade applies to a themed color too.',+ default:+ 'var(--color-track) (default, subtle), var(--color-on-dark) (onMedia), currentColor (inherit)',+ },+ {+ name: '--spinner-arc-fraction',+ description:+ "Fraction of the ring the moving arc covers, as a plain number (not a percentage or angle). Set it on a size-variant target the same way as --spinner-diameter, e.g. spinner: { 'size:xl': { '--spinner-arc-fraction': '0.75' } } for a 270deg sweep. Only takes effect once the stylesheet loads; a render with no CSS (SSR, no-JS) always draws the default 135deg arc.",+ default: '0.375 (135deg), same for every size',+ },],},usage: {description:'An animated loading indicator for processes with unknown duration, such as data fetching or form submission. Supports visible labels, multiple sizes, and a dark background variant. For content with known dimensions, use Skeleton instead.',bestPractices: [- {guidance: true, description: 'Provide a meaningful label to describe what is loading for screen reader users.'},- {guidance: true, description: 'Use the "onMedia" shade when placed on dark or accent-colored backgrounds.'},- {guidance: false, description: 'Use for content areas with known dimensions; use Skeleton to preserve layout instead.'},- {guidance: false, description: 'Stack multiple spinners in the same view; use one to represent the overall loading state.'},+ {+ guidance: true,+ description:+ 'Provide a meaningful label to describe what is loading for screen reader users.',+ },+ {+ guidance: true,+ description:+ 'Use the "onMedia" shade when placed on dark or accent-colored backgrounds.',+ },+ {+ guidance: false,+ description:+ 'Use for content areas with known dimensions; use Skeleton to preserve layout instead.',+ },+ {+ guidance: false,+ description:+ 'Stack multiple spinners in the same view; use one to represent the overall loading state.',+ },],},};@@ -83,12 +136,14 @@ export const docsZh = {{name: 'label',type: 'ReactNode',- description: '旋转器下方的可见内容。字符串标签自动设置 aria-label。',+ description:+ '旋转器下方的可见内容。未设置 aria-label 时,字符串标签提供无障碍名称。',},{name: 'aria-label',type: 'string',- description: '屏幕阅读器的无障碍名称。默认为 label(如果是字符串)或来自 i18n 词条的已翻译 "Loading"。',+ description:+ '屏幕阅读器的无障碍名称。默认为 label(如果是字符串)或来自 i18n 词条的已翻译 "Loading"。',default: "'Loading'",},{@@ -99,25 +154,66 @@ export const docsZh = {},],theming: {- targets: [- {className: 'astryx-spinner', visualProps: ['size', 'shade']},- ],+ targets: [{className: 'astryx-spinner', visualProps: ['size', 'shade']}],vars: [- {name: '--spinner-diameter', description: "绘制环的直径。在尺寸变体目标上设置,以重新定义每个命名尺寸的解析值,例如 spinner: { 'size:xl': { '--spinner-diameter': '2.5rem' } }。渲染盒子的尺寸为该值加上两侧的描边宽度,并自动跟随。支持任意长度单位——rem、em 与 calc() 会在绘制前解析。", default: '10px (sm), 14px (md), 18px (lg), 28px (xl)'},- {name: '--spinner-stroke-width', description: '绘制环的两个圆——移动圆弧与其后的轨道——的描边宽度。与直径一起按尺寸设置。同一个描边宽度同时驱动两者,因此 0 会被采纳为零宽描边——什么都不绘制,而不会回退到默认值;若想要没有轨道的圆弧,请改将 --spinner-track-color 设为 transparent。', default: '2px (sm), 3px (md), 3px (lg), 4px (xl)'},- {name: '--spinner-color', description: "运动圆弧的颜色。默认取所在 shade 的令牌,因此可在 shade 变体目标上设置以重新定义单个 shade——spinner: { 'shade:subtle': { '--spinner-color': 'var(--color-text-tertiary)' } }——或在 base 目标上设置以覆盖全部四种。接受任意颜色写法,包括 var()、color-mix() 与 currentColor。", default: 'var(--color-accent)(default)、var(--color-text-secondary)(subtle)、var(--color-on-dark)(onMedia)、currentColor(inherit)'},- {name: '--spinner-track-color', description: '圆弧所在轨道的颜色。设为 `transparent` 可得到无轨道的圆弧。onMedia 与 inherit 两种 shade 会以降低的透明度(30%)绘制轨道,以便在任意背景上可辨;该淡化同样作用于主题化的颜色。', default: 'var(--color-track)(default、subtle)、var(--color-on-dark)(onMedia)、currentColor(inherit)'},- {name: '--spinner-arc-fraction', description: "运动圆弧覆盖圆环的比例,为纯数字(非百分比或角度)。在尺寸变体目标上设置,方式与 --spinner-diameter 相同,例如 spinner: { 'size:xl': { '--spinner-arc-fraction': '0.75' } } 可得到 270 度的圆弧。仅在样式表加载后生效;无 CSS 的渲染(SSR、无 JS)始终绘制默认的 135 度圆弧。", default: '0.375(135 度),各尺寸相同'},+ {+ name: '--spinner-diameter',+ description:+ "绘制环的直径。在尺寸变体目标上设置,以重新定义每个命名尺寸的解析值,例如 spinner: { 'size:xl': { '--spinner-diameter': '2.5rem' } }。渲染盒子的尺寸为该值加上两侧的描边宽度,并自动跟随。支持任意长度单位——rem、em 与 calc() 会在绘制前解析。",+ default: '10px (sm), 14px (md), 18px (lg), 28px (xl)',+ },+ {+ name: '--spinner-stroke-width',+ description:+ '绘制环的两个圆——移动圆弧与其后的轨道——的描边宽度。与直径一起按尺寸设置。同一个描边宽度同时驱动两者,因此 0 会被采纳为零宽描边——什么都不绘制,而不会回退到默认值;若想要没有轨道的圆弧,请改将 --spinner-track-color 设为 transparent。',+ default: '2px (sm), 3px (md), 3px (lg), 4px (xl)',+ },+ {+ name: '--spinner-color',+ description:+ "运动圆弧的颜色。默认取所在 shade 的令牌,因此可在 shade 变体目标上设置以重新定义单个 shade——spinner: { 'shade:subtle': { '--spinner-color': 'var(--color-text-tertiary)' } }——或在 base 目标上设置以覆盖全部四种。接受任意颜色写法,包括 var()、color-mix() 与 currentColor。",+ default:+ 'var(--color-accent)(default)、var(--color-text-secondary)(subtle)、var(--color-on-dark)(onMedia)、currentColor(inherit)',+ },+ {+ name: '--spinner-track-color',+ description:+ '圆弧所在轨道的颜色。设为 `transparent` 可得到无轨道的圆弧。onMedia 与 inherit 两种 shade 会以降低的透明度(30%)绘制轨道,以便在任意背景上可辨;该淡化同样作用于主题化的颜色。',+ default:+ 'var(--color-track)(default、subtle)、var(--color-on-dark)(onMedia)、currentColor(inherit)',+ },+ {+ name: '--spinner-arc-fraction',+ description:+ "运动圆弧覆盖圆环的比例,为纯数字(非百分比或角度)。在尺寸变体目标上设置,方式与 --spinner-diameter 相同,例如 spinner: { 'size:xl': { '--spinner-arc-fraction': '0.75' } } 可得到 270 度的圆弧。仅在样式表加载后生效;无 CSS 的渲染(SSR、无 JS)始终绘制默认的 135 度圆弧。",+ default: '0.375(135 度),各尺寸相同',+ },],},usage: {description:'An animated loading indicator for processes with unknown duration, such as data fetching or form submission. Supports visible labels, multiple sizes, and a dark background variant. For content with known dimensions, use Skeleton instead.',bestPractices: [- {guidance: true, description: 'Provide a meaningful label to describe what is loading for screen reader users.'},- {guidance: true, description: 'Use the "onMedia" shade when placed on dark or accent-colored backgrounds.'},- {guidance: false, description: 'Use for content areas with known dimensions; use Skeleton to preserve layout instead.'},- {guidance: false, description: 'Stack multiple spinners in the same view; use one to represent the overall loading state.'},+ {+ guidance: true,+ description:+ 'Provide a meaningful label to describe what is loading for screen reader users.',+ },+ {+ guidance: true,+ description:+ 'Use the "onMedia" shade when placed on dark or accent-colored backgrounds.',+ },+ {+ guidance: false,+ description:+ 'Use for content areas with known dimensions; use Skeleton to preserve layout instead.',+ },+ {+ guidance: false,+ description:+ 'Stack multiple spinners in the same view; use one to represent the overall loading state.',+ },],},};@@ -128,18 +224,36 @@ export const docsDense = {description:'An animated loading indicator for processes with unknown duration, such as data fetching or form submission. Supports visible labels, multiple sizes, and a dark background variant. For content with known dimensions, use Skeleton instead.',bestPractices: [- {guidance: true, description: 'Provide a meaningful label to describe what is loading for screen reader users.'},- {guidance: true, description: 'Use the "onMedia" shade when placed on dark or accent-colored backgrounds.'},- {guidance: false, description: 'Use for content areas with known dimensions; use Skeleton to preserve layout instead.'},- {guidance: false, description: 'Stack multiple spinners in the same view; use one to represent the overall loading state.'},+ {+ guidance: true,+ description:+ 'Provide a meaningful label to describe what is loading for screen reader users.',+ },+ {+ guidance: true,+ description:+ 'Use the "onMedia" shade when placed on dark or accent-colored backgrounds.',+ },+ {+ guidance: false,+ description:+ 'Use for content areas with known dimensions; use Skeleton to preserve layout instead.',+ },+ {+ guidance: false,+ description:+ 'Stack multiple spinners in the same view; use one to represent the overall loading state.',+ },],},propDescriptions: {size: 'Spinner size: ring diameter (10px, 14px, 18px, 28px).',shade: 'Color shade for light or dark backgrounds.',- label: 'Visible content below spinner. String auto-sets aria-label.',+ label:+ 'Visible content below spinner. String provides its accessible name unless aria-label is set.','aria-label':'A11y name for screen readers. Defaults to label or a translated "Loading".',- xstyle: 'StyleX styles for layout customization. Must be stylex.create() value, not inline style.',+ xstyle:+ 'StyleX styles for layout customization. Must be stylex.create() value, not inline style.',},-};\ No newline at end of file+};diff --git a/packages/core/src/Spinner/Spinner.test.tsx b/packages/core/src/Spinner/Spinner.test.tsxindex fe5f6b2c60..e4511208df 100644--- a/packages/core/src/Spinner/Spinner.test.tsx+++ b/packages/core/src/Spinner/Spinner.test.tsx@@ -9,17 +9,28 @@* SYNC: When Spinner.tsx changes, update tests to match new behavior*/-import {describe, it, expect, vi, afterEach} from 'vitest';-import {Profiler} from 'react';+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {createRef, Profiler, StrictMode} from 'react';import {render, screen} from '@testing-library/react';import {SPINNER_ARC_FRACTION} from './spinnerRotor';import {Spinner} from './Spinner';+import {SpinnerOwnerContext} from './SpinnerOwnerContext';import {InternationalizationProvider} from '../i18n';import {defineTheme} from '../theme/defineTheme';import {generateThemeCSS} from '../theme/generateThemeRules';import {getAllInjectedCss} from '../__tests__/forcedColors';import {declaredValue} from '../__tests__/stylexDeclarations';+const {announce} = vi.hoisted(() => ({announce: vi.fn()}));+vi.mock('../hooks/useAnnounce', () => ({useAnnounce: () => announce}));++beforeEach(() => {+ announce.mockClear();+ vi.spyOn(document, 'readyState', 'get').mockReturnValue('complete');+});++afterEach(() => vi.restoreAllMocks());+/** sm/md/lg/xl, as Spinner.tsx defines them. */const SIZES = {sm: {diameter: 10, border: 2},@@ -54,6 +65,7 @@ describe('Spinner', () => {it('renders with default props', () => {render(<Spinner data-testid="spinner" />);expect(screen.getByTestId('spinner')).toBeInTheDocument();+ expect(announce).toHaveBeenCalledExactlyOnceWith('Loading', 'polite');});it('renders with size sm', () => {@@ -100,6 +112,7 @@ describe('Spinner', () => {'aria-label','Chargement',);+ expect(announce).toHaveBeenCalledExactlyOnceWith('Chargement', 'polite');});it('keeps an explicit aria-label over the localized default', () => {@@ -114,13 +127,17 @@ describe('Spinner', () => {'aria-label','Veuillez patienter',);+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Veuillez patienter',+ 'polite',+ );});it('does not duplicate a visible string label as aria-label', () => {render(<Spinner label="Fetching data" data-testid="spinner" />);- const status = screen.getByRole('status');- expect(status).not.toHaveAttribute('aria-label');- expect(status).toHaveAttribute('aria-labelledby');+ const image = screen.getByRole('progressbar', {name: 'Fetching data'});+ expect(image).not.toHaveAttribute('aria-label');+ expect(image).toHaveAttribute('aria-labelledby');});it('uses explicit aria-label over string label', () => {@@ -131,7 +148,7 @@ describe('Spinner', () => {data-testid="spinner"/>,);- expect(screen.getByRole('status')).toHaveAttribute(+ expect(screen.getByRole('progressbar')).toHaveAttribute('aria-label','Please wait',);@@ -155,7 +172,10 @@ describe('Spinner', () => {it('defaults aria-label to "Loading" for ReactNode label without explicit aria-label', () => {render(<Spinner label={<span>Rich content</span>} data-testid="spinner" />);- expect(screen.getByRole('status')).toHaveAttribute('aria-label', 'Loading');+ expect(screen.getByRole('progressbar')).toHaveAttribute(+ 'aria-label',+ 'Loading',+ );});it('accepts data-testid', () => {@@ -260,10 +280,6 @@ describe('Spinner', () => {});describe('Spinner ring', () => {- afterEach(() => {- vi.restoreAllMocks();- });-it('draws the ring in SVG', () => {render(<Spinner data-testid="spinner" />);// The track and the arc each have their own svg: the track stays put and@@ -599,3 +615,229 @@ describe('geometry var registration', () => {expect(registerProperty).toHaveBeenCalledTimes(2);});});++describe('shared announcement lifecycle', () => {+ it('announces once per appearance, including a new appearance with the same words', () => {+ const view = (loading: boolean) => (+ <StrictMode>{loading && <Spinner label="Loading results" />}</StrictMode>+ );+ const {rerender} = render(view(false));+ expect(announce).not.toHaveBeenCalled();++ rerender(view(true));+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Loading results',+ 'polite',+ );+ rerender(view(true));+ expect(announce).toHaveBeenCalledTimes(1);++ rerender(view(false));+ rerender(view(true));+ expect(announce.mock.calls).toEqual([+ ['Loading results', 'polite'],+ ['Loading results', 'polite'],+ ]);+ });++ it('announces when the label changes', () => {+ const {rerender} = render(<Spinner label="Loading results" />);++ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Loading results',+ 'polite',+ );++ rerender(<Spinner label="Saving results" />);++ expect(announce.mock.calls).toEqual([+ ['Loading results', 'polite'],+ ['Saving results', 'polite'],+ ]);+ });++ it('stays silent with a caller role other than progressbar, as it shipped (AST-017 FR53)', () => {+ const {rerender} = render(<Spinner aria-label="Searching" role="img" />);+ rerender(<Spinner aria-label="Searching again" role="img" />);+ expect(+ screen.getByRole('img', {name: 'Searching again'}),+ ).toBeInTheDocument();+ expect(announce).not.toHaveBeenCalled();++ rerender(<Spinner aria-label="Searching once more" />);+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Searching once more',+ 'polite',+ );+ });++ it('stays silent inside a Core owner, and announces once it stands alone (AST-086 FR8)', () => {+ const {rerender} = render(+ <SpinnerOwnerContext value={true}>+ <Spinner aria-label="Loading results" />+ </SpinnerOwnerContext>,+ );+ expect(+ screen.getByRole('progressbar', {name: 'Loading results'}),+ ).toBeInTheDocument();+ expect(announce).not.toHaveBeenCalled();++ rerender(+ <SpinnerOwnerContext value={false}>+ <Spinner aria-label="Loading results" />+ </SpinnerOwnerContext>,+ );+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Loading results',+ 'polite',+ );+ });++ it('stays silent when app code hides it with aria-hidden', () => {+ const {rerender} = render(<Spinner label="Loading events" aria-hidden />);+ rerender(<Spinner label="Loading events" aria-hidden />);+ expect(screen.queryByRole('progressbar')).toBeNull();+ expect(announce).not.toHaveBeenCalled();+ });++ it('announces a stacked rich label word by word, not run together (AST-086 FR7)', () => {+ const {rerender} = render(<div />);+ rerender(+ <Spinner+ aria-label="Fetching data"+ label={+ <div style={{display: 'flex', flexDirection: 'column'}}>+ <span>Fetching data</span>+ <span>This may take a moment</span>+ </div>+ }+ />,+ );+ expect(announce).toHaveBeenCalledWith(+ 'Fetching data This may take a moment',+ 'polite',+ );+ });++ it('keeps directly hidden and ancestor-hidden indicators silent', () => {+ render(+ <>+ <Spinner aria-hidden="true" role={undefined} />+ <Spinner aria-hidden="true" label="Decorative label" />+ <div aria-hidden="true">+ <Spinner />+ </div>+ <div hidden>+ <Spinner />+ </div>+ </>,+ );+ expect(announce).not.toHaveBeenCalled();+ });++ it('leaves announcements to existing live containers', () => {+ const view = (loading: boolean) => (+ <>+ <div role="log">{loading && <Spinner />}</div>+ <div aria-live="polite">{loading && <Spinner />}</div>+ <div aria-live="assertive">{loading && <Spinner />}</div>+ </>+ );+ const {rerender} = render(view(false));+ rerender(view(true));+ expect(announce).not.toHaveBeenCalled();+ });++ it('preserves refs when switching between labeled and unlabeled roots', () => {+ const ref = createRef<HTMLSpanElement>();+ const {rerender, unmount} = render(+ <Spinner ref={ref} data-testid="spinner" />,+ );+ expect(ref.current).toBe(screen.getByTestId('spinner'));+ rerender(+ <Spinner ref={ref} label="Loading results" data-testid="spinner" />,+ );+ expect(ref.current).toBe(screen.getByTestId('spinner'));+ expect(announce).toHaveBeenLastCalledWith('Loading results', 'polite');+ unmount();+ expect(ref.current).toBeNull();+ });++ it('stays silent during page load and announces a later text change', () => {+ const readyState = vi+ .spyOn(document, 'readyState', 'get')+ .mockReturnValue('loading');+ const {rerender} = render(<Spinner aria-label="Loading records" />);+ expect(announce).not.toHaveBeenCalled();+ readyState.mockReturnValue('complete');+ rerender(<Spinner aria-label="Loading records" />);+ expect(announce).not.toHaveBeenCalled();+ rerender(<Spinner aria-label="Saving records" />);+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Saving records',+ 'polite',+ );+ });++ it('announces rendered ReactNode text and changes without changing the progressbar name', () => {+ function LoadingLabel() {+ return (+ <span>+ <strong>Fetch</strong>ing records+ <span aria-hidden="true"> decoration</span>+ <span hidden> hidden</span>+ </span>+ );+ }+ const {rerender} = render(+ <Spinner label={<LoadingLabel />} aria-label="Please wait" />,+ );+ expect(screen.getByRole('progressbar')).toHaveAccessibleName('Please wait');+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Fetching records',+ 'polite',+ );+ rerender(<Spinner label={<LoadingLabel />} aria-label="Please wait" />);+ expect(announce).toHaveBeenCalledTimes(1);+ rerender(+ <Spinner label={<em>Saving records</em>} aria-label="Please wait" />,+ );+ expect(screen.getByRole('progressbar')).toHaveAccessibleName('Please wait');+ expect(announce.mock.calls).toEqual([+ ['Fetching records', 'polite'],+ ['Saving records', 'polite'],+ ]);+ });++ it('announces the aria-labelledby name and its updates instead of the default', () => {+ const view = (name: string) => (+ <>+ <Spinner aria-labelledby="upload-label" aria-label="Please wait" />+ <span id="upload-label">{name}</span>+ </>+ );+ const {rerender} = render(view('Uploading files'));+ expect(screen.getByRole('progressbar')).toHaveAccessibleName(+ 'Uploading files',+ );+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Uploading files',+ 'polite',+ );+ rerender(view('Uploading files'));+ expect(announce).toHaveBeenCalledTimes(1);+ rerender(view('Saving files'));+ expect(screen.getByRole('progressbar')).toHaveAccessibleName(+ 'Saving files',+ );+ expect(announce.mock.calls).toEqual([+ ['Uploading files', 'polite'],+ ['Saving files', 'polite'],+ ]);+ });++ it('uses the accessible-name fallback for a textless ReactNode label', () => {+ render(<Spinner label={<span aria-hidden="true">Decoration</span>} />);+ expect(announce).toHaveBeenCalledExactlyOnceWith('Loading', 'polite');+ });+});diff --git a/packages/core/src/Spinner/Spinner.tsx b/packages/core/src/Spinner/Spinner.tsxindex 68fd286e73..3cce7c2467 100644--- a/packages/core/src/Spinner/Spinner.tsx+++ b/packages/core/src/Spinner/Spinner.tsx@@ -16,12 +16,15 @@* - /packages/cli/assets/templates/blocks/components/Spinner/ (showcase blocks)*/-import {useId, type ReactNode} from 'react';+import {use, useId, useMemo, useRef, type ReactNode} from 'react';+import {SpinnerOwnerContext} from './SpinnerOwnerContext';import * as stylex from '@stylexjs/stylex';import {colorVars, spacingVars} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';import {Text} from '../Text/Text';import {mergeProps} from '../utils/mergeProps';+import {mergeRefs} from '../utils/mergeRefs';+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';import {themeProps} from '../utils/themeProps';import {registerEnglishFallback,@@ -387,7 +390,7 @@ export interface SpinnerProps extends BaseProps<HTMLSpanElement> {* Accepts a string or ReactNode for rich content.** When `label` is a string, the visible text also provides the accessible- * name of the status element (via aria-labelledby, avoiding a duplicate+ * name of the progressbar (via aria-labelledby, avoiding a duplicate* announcement) unless `aria-label` is explicitly set.** @example@@ -438,9 +441,11 @@ export function Spinner({const hasLabel = label != null;const labelId = useId();const t = useComponentTranslator();+ const spinnerRef = useRef<HTMLSpanElement>(null);+ const rootRef = useMemo(() => mergeRefs(spinnerRef, ref), [ref]);// When a visible string label renders (and no explicit aria-label is set),- // name the status element from the visible Text via aria-labelledby instead+ // name the progressbar from the visible Text via aria-labelledby instead// of duplicating the same string as aria-label — the duplicate would be// announced twice by screen readers (WCAG 4.1.2).const namedByVisibleLabel =@@ -454,10 +459,33 @@ export function Spinner({(typeof label === 'string' ? label : undefined) ??t('@astryx.spinner.loading');+ // Only a standalone Spinner announces. A Core component that composes it+ // owns the task and silences it through the internal SpinnerOwnerContext;+ // app code hides it with `aria-hidden`. A caller `role` other than+ // progressbar also keeps it silent, as it shipped, so app code that+ // silenced a composed ring that way keeps working; new code uses+ // `aria-hidden`.+ const isComposedInOwner = use(SpinnerOwnerContext);+ const isHidden =+ restProps['aria-hidden'] === true || restProps['aria-hidden'] === 'true';+ const callerRole = restProps.role;+ const hasShippedSilentRole =+ callerRole != null && callerRole !== 'progressbar';+ useAnnounceRenderedText(+ spinnerRef,+ !isComposedInOwner && !isHidden && !hasShippedSilentRole,+ '',+ {+ skipFirstRender: true,+ fallbackText: resolvedAriaLabel,+ },+ );+const spinner = (<span- ref={hasLabel ? undefined : ref}- role="status"+ ref={hasLabel ? undefined : rootRef}+ // An indeterminate progress indicator, so no aria-valuenow.+ role="progressbar"aria-label={namedByVisibleLabel ? undefined : resolvedAriaLabel}aria-labelledby={namedByVisibleLabel ? labelId : undefined}data-testid={hasLabel ? undefined : testId}@@ -539,7 +567,7 @@ export function Spinner({return (<div- ref={ref as React.Ref<HTMLDivElement>}+ ref={rootRef}data-testid={testId}{...restProps}{...mergeProps(diff --git a/packages/core/src/Spinner/SpinnerOwnerContext.ts b/packages/core/src/Spinner/SpinnerOwnerContext.tsnew file mode 100644index 0000000000..cee12d56bc--- /dev/null+++ b/packages/core/src/Spinner/SpinnerOwnerContext.ts@@ -0,0 +1,22 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file SpinnerOwnerContext.ts+ * @input React+ * @output SpinnerOwnerContext: true inside a Core component that owns the+ * task a composed Spinner shows, so that Spinner announces nothing+ * @position Internal to core: not exported from Spinner/index.ts, and core's+ * `exports` do not list this module. The owner of a task announces it, so+ * a Spinner it composes stays silent; app code hides a composed Spinner+ * with `aria-hidden` instead.+ *+ * SYNC: When modified, update:+ * - /packages/core/src/Spinner/Spinner.tsx+ */++import {createContext} from 'react';++export const SpinnerOwnerContext = createContext(false);+SpinnerOwnerContext.displayName = 'SpinnerOwnerContext';diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex dc146e1182..446564f2a1 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -73,6 +73,7 @@ import {} from '../Field';import {Token} from '../Token';import {Spinner} from '../Spinner';+import {SpinnerOwnerContext} from '../Spinner/SpinnerOwnerContext';import {useEndLaneReserve} from './useEndLaneReserve';import {renderIconSlot, type IconType} from '../Icon';import {OverflowList} from '../OverflowList';@@ -743,16 +744,19 @@ function EndLane({return (<div ref={laneRef} {...stylex.props(laneXStyle)}>{(isBusy || hasBusySlot) && (- <Spinner- // Remounts when a search starts, so the ring syncs its phase on- // mount exactly as a newly shown Spinner did before.- key={isBusy ? 'busy' : 'idle'}- size="sm"- aria-label={loadingLabel}- role="img"- aria-hidden={isBusy ? undefined : true}- xstyle={isBusy ? undefined : styles.idleSpinner}- />+ // Named, never live: the tokenizer announces its search.+ <SpinnerOwnerContext value={true}>+ <Spinner+ // Remounts when a search starts, so the ring syncs its phase on+ // mount exactly as a newly shown Spinner did before.+ key={isBusy ? 'busy' : 'idle'}+ size="sm"+ aria-label={loadingLabel}+ role="img"+ aria-hidden={isBusy ? undefined : true}+ xstyle={isBusy ? undefined : styles.idleSpinner}+ />+ </SpinnerOwnerContext>)}{children}</div>diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex 7e5a543611..27b3ec976b 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -51,6 +51,7 @@ import {isImeKeyEvent} from '../utils/ime';import {TypeaheadItem} from './TypeaheadItem';import {Icon} from '../Icon';import {Spinner} from '../Spinner';+import {SpinnerOwnerContext} from '../Spinner/SpinnerOwnerContext';import {borderVars,colorVars,@@ -1775,11 +1776,14 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({/>{isLoading && busyLane == null && (<span {...stylex.props(styles.loadingStatus)}>- <Spinner- size="sm"- aria-label={t('@astryx.typeahead.loading')}- role="img"- />+ {/* Named, never live: the typeahead announces its search. */}+ <SpinnerOwnerContext value={true}>+ <Spinner+ size="sm"+ aria-label={t('@astryx.typeahead.loading')}+ role="img"+ />+ </SpinnerOwnerContext></span>)}{popover.render(diff --git a/packages/core/src/Typeahead/Typeahead.tsx b/packages/core/src/Typeahead/Typeahead.tsxindex b85d5f9771..16e81e3de3 100644--- a/packages/core/src/Typeahead/Typeahead.tsx+++ b/packages/core/src/Typeahead/Typeahead.tsx@@ -52,6 +52,7 @@ import {useTooltip} from '../Tooltip';import {renderIconSlot, type IconType} from '../Icon';import {VisuallyHidden} from '../VisuallyHidden';import {Spinner} from '../Spinner';+import {SpinnerOwnerContext} from '../Spinner/SpinnerOwnerContext';import {spacingVars, sizeVars} from '../theme/tokens.stylex';import {groupStyles, inputGroupItemProps} from '../InputGroup/groupStyles';import {useInputGroup} from '../InputGroup/InputGroupContext';@@ -385,7 +386,12 @@ function EndLane({}return (<div {...stylex.props(styles.endLane)}>- {isBusy && <Spinner size="sm" aria-label={loadingLabel} role="img" />}+ {isBusy && (+ // Named, never live: the typeahead announces its search.+ <SpinnerOwnerContext value={true}>+ <Spinner size="sm" aria-label={loadingLabel} role="img" />+ </SpinnerOwnerContext>+ )}{clear}</div>);diff --git a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsxindex 7b9caf3288..baf86a8537 100644--- a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx+++ b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx@@ -3,8 +3,8 @@/*** @file useAnnounceRenderedText.adopters.test.tsx* @input Every core component that announces its own rendered content,- * Tooltip's show() hold included, with the shared own-content module replaced by a- * recorder+ * Spinner and Tooltip's show() hold included, with the shared own-content+ * module replaced by a recorder* @output architecture:react-component-runtime INV10 test: each adopter hands* its own-content announcement to the shared module and announces none of it* itself@@ -24,6 +24,7 @@ import path from 'node:path';import {useEffect, useRef, type HTMLAttributes, type RefObject} from 'react';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {fireEvent, render, screen, waitFor} from '@testing-library/react';+import type {AnnounceRenderedTextOptions} from './useAnnounceRenderedText';interface ModuleCall {isShown: boolean;@@ -38,10 +39,15 @@ vi.mock('./useAnnounceRenderedText', async importOriginal => ({useAnnounceRenderedText: (ref: RefObject<HTMLElement | null>,isShown: boolean,+ _occasion: string,+ {fallbackText}: AnnounceRenderedTextOptions = {},) => {// Read after commit, the way the real module does.useEffect(() => {- calls.push({isShown, text: ref.current?.textContent ?? ''});+ calls.push({+ isShown,+ text: ref.current?.textContent || fallbackText || '',+ });});},}));@@ -67,6 +73,7 @@ const {CommandPalette} = await import('../CommandPalette');const {BaseTypeahead} = await import('../Typeahead/BaseTypeahead');const {Tokenizer} = await import('../Tokenizer/Tokenizer');const {PowerSearch} = await import('../PowerSearch/PowerSearch');+const {Spinner} = await import('../Spinner');const {createStaticSource} = await import('../Typeahead/createStaticSource');const {InfoTip} = await import('../InfoTip/InfoTip');// Tokenizer and PowerSearch load their sheets on demand. This file loads@@ -113,6 +120,18 @@ async function expectDelegated(text: string) {/** Each adopter, shown in the state where its own content appears. */const ADOPTERS: Record<string, () => Promise<void>> = {+ 'Spinner/Spinner.tsx': async () => {+ const {rerender} = render(<Spinner />);+ await expectDelegated('Loading');+ rerender(<Spinner label={<span>Loading records</span>} />);+ await expectDelegated('Loading records');+ rerender(<Spinner aria-label="Waiting for results" />);+ await expectDelegated('Waiting for results');+ // App code silences a composed Spinner by hiding it.+ rerender(<Spinner aria-hidden />);+ expect(calls.at(-1)?.isShown).toBe(false);+ expect(announce).not.toHaveBeenCalled();+ },'EmptyState/EmptyState.tsx': async () => {render(<EmptyState title="Nothing here" description="Add an item" />);await expectDelegated('Nothing here');diff --git a/packages/core/src/hooks/useAnnounceRenderedText.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.test.tsxnew file mode 100644index 0000000000..44f506453b--- /dev/null+++ b/packages/core/src/hooks/useAnnounceRenderedText.test.tsx@@ -0,0 +1,111 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useAnnounceRenderedText.test.tsx+ * @input Rendered content, fallback text in both extraction modes, and visibility+ * @output Regression tests for fallback text and shared announcement ownership+ * @position Unit tests for the internal own-content announcement hook+ */++import {useRef, type HTMLAttributes} from 'react';+import {render} from '@testing-library/react';+import {beforeEach, describe, expect, it, vi} from 'vitest';+import {renderedText, useAnnounceRenderedText} from './useAnnounceRenderedText';++const {announce} = vi.hoisted(() => ({announce: vi.fn()}));+vi.mock('./useAnnounce', () => ({useAnnounce: () => announce}));++function Message({+ fallbackText,+ ...props+}: HTMLAttributes<HTMLDivElement> & {fallbackText?: string}) {+ const ref = useRef<HTMLDivElement>(null);+ useAnnounceRenderedText(ref, true, '', {fallbackText});+ return <div ref={ref} {...props} />;+}++beforeEach(() => announce.mockClear());++describe('useAnnounceRenderedText text priority', () => {+ it('prefers rendered text over referenced and fallback names', () => {+ render(+ <>+ <Message fallbackText="Loading" aria-labelledby="label">+ Fetching records+ </Message>+ <span id="label">Referenced name</span>+ </>,+ );+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Fetching records',+ 'polite',+ );+ });++ it('prefers referenced text in ID order over the fallback', () => {+ render(+ <>+ <Message fallbackText="Loading" aria-labelledby="action missing file" />+ <span id="file"> files </span>+ <span id="action" hidden>+ Uploading+ </span>+ </>,+ );+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Uploading files',+ 'polite',+ );+ });++ it('uses the fallback when rendered and referenced text are unavailable', () => {+ render(+ <Message fallbackText="Loading" aria-labelledby="missing">+ <span aria-hidden="true">Decorative ring</span>+ <span hidden>Hidden label</span>+ </Message>,+ );+ expect(announce).toHaveBeenCalledExactlyOnceWith('Loading', 'polite');+ });++ it('keeps empty content silent when no fallback is provided', () => {+ render(+ <>+ <Message aria-labelledby="label" />+ <span id="label">Referenced name</span>+ </>,+ );+ expect(announce).not.toHaveBeenCalled();+ });+});++describe('renderedText reads block boxes apart (AST-086 FR7)', () => {+ it('separates the inline children of a flex or grid stack, as the layout blockifies them', () => {+ const {container} = render(+ <div>+ <div style={{display: 'flex', flexDirection: 'column'}}>+ <span>Fetching data</span>+ <span>This may take a moment</span>+ </div>+ <div style={{display: 'grid'}}>+ <span>One</span>+ <span>Two</span>+ </div>+ </div>,+ );+ expect(renderedText(container.firstElementChild as HTMLElement)).toBe(+ 'Fetching data This may take a moment One Two',+ );+ });++ it('keeps inline runs together and still skips hidden parts', () => {+ const {container} = render(+ <p>+ Saving <strong>3</strong> files<span aria-hidden="true">…</span>+ </p>,+ );+ expect(renderedText(container.firstElementChild as HTMLElement)).toBe(+ 'Saving 3 files',+ );+ });+});diff --git a/packages/core/src/hooks/useAnnounceRenderedText.ts b/packages/core/src/hooks/useAnnounceRenderedText.tsindex 37c11ac017..a4c9d1fd87 100644--- a/packages/core/src/hooks/useAnnounceRenderedText.ts+++ b/packages/core/src/hooks/useAnnounceRenderedText.ts@@ -75,6 +75,8 @@ export interface AnnounceRenderedTextOptions {* polite. Defaults to polite.*/politeness?: AnnouncePoliteness;+ /** Accessible name to announce when the element has no rendered text. */+ fallbackText?: string;/*** The owner's announcer, when the rendered text states the next value of* that announcer's state. For example, a picker's empty-panel message goes@@ -84,14 +86,48 @@ export interface AnnounceRenderedTextOptions {announce?: AnnounceFn;}-/** The rendered text an assistive technology would read from `element`. */+/**+ * The rendered text an assistive technology would read from `element`. Block+ * boxes read apart: a block tag, an element whose computed display is not+ * inline, and any child of a flex or grid container (which the layout+ * blockifies), so two stacked `Text` spans never run together. Hidden parts+ * are skipped; nothing on screen changes.+ */export function renderedText(element: HTMLElement): string {- // Clone so removing the hidden parts cannot disturb what is on screen. The- // clone is never attached to the document.- const copy = element.cloneNode(true) as HTMLElement;- copy.querySelectorAll(HIDDEN).forEach(node => node.remove());- copy.querySelectorAll(BLOCKS).forEach(node => node.after(' ')); // blocks apart- return (copy.textContent ?? '').replace(/\s+/g, ' ').trim();+ const view = element.ownerDocument.defaultView;+ const displayOf = (node: Element) =>+ view?.getComputedStyle(node).display ?? '';+ const parts: string[] = [];+ const walk = (node: Node, parentDisplay: string) => {+ if (node.nodeType === Node.TEXT_NODE) {+ parts.push(node.textContent ?? '');+ return;+ }+ if (node.nodeType !== Node.ELEMENT_NODE) {+ return;+ }+ const part = node as Element;+ if (part.matches(HIDDEN)) {+ return;+ }+ const display = displayOf(part);+ const isBlock =+ part.matches(BLOCKS) ||+ (display !== '' &&+ display !== 'contents' &&+ !display.startsWith('inline')) ||+ /\b(flex|grid)\b/.test(parentDisplay);+ if (isBlock) {+ parts.push(' ');+ }+ part.childNodes.forEach(child => walk(child, display));+ if (isBlock) {+ parts.push(' ');+ }+ };+ const ownDisplay = displayOf(element);+ element.childNodes.forEach(child => walk(child, ownDisplay));+ return parts.join('').replace(/\s+/g, ' ').trim();}/**@@ -121,6 +157,7 @@ export function useAnnounceRenderedText({skipFirstRender = false,politeness = 'polite',+ fallbackText,announce: ownerAnnounce,}: AnnounceRenderedTextOptions = {},): void {@@ -157,7 +194,21 @@ export function useAnnounceRenderedText(if (skipFirstRender && element.parentElement?.closest(LIVE_CONTAINER)) {return;}- const text = skipFirstRender ? blockText(element) : renderedText(element);+ let text = skipFirstRender ? blockText(element) : renderedText(element);+ if (text === '' && fallbackText !== undefined) {+ text =+ (element.getAttribute('aria-labelledby') ?? '')+ .split(/\s+/)+ .map(id => {+ // Each referenced element as read: its hidden parts dropped, as+ // the accessible name drops them.+ const target = element.ownerDocument.getElementById(id);+ return target == null ? '' : renderedText(target);+ })+ .join(' ')+ .replace(/\s+/g, ' ')+ .trim() || fallbackText;+ }if (text === '') {// Nothing readable on screen either, so there is no announcement that// would match what the sighted user is seeing.diff --git a/packages/lab/src/Comments/CommentParts.tsx b/packages/lab/src/Comments/CommentParts.tsxindex 70eecb77c8..8634107165 100644--- a/packages/lab/src/Comments/CommentParts.tsx+++ b/packages/lab/src/Comments/CommentParts.tsx@@ -6,7 +6,8 @@* @file CommentParts.tsx* @input Uses React, StyleX, theme tokens, and Astryx primitives (Avatar,* Badge, Banner, Blockquote, Button, Card, Dialog, EmptyState, Item, Link,- * Section, Skeleton, Spinner, Text, Thumbnail, Timestamp, Tooltip)+ * Section, Skeleton, Text, Thumbnail, Timestamp, Tooltip), plus Lab's+ * loading-message and shared status-announcement helpers* @output Exports the presentational parts of a comment row: author name and* avatar, metadata, quoted passages, progress, clamped body, error banner,* reply rail, activity event row, edit history dialog, and loading skeletons@@ -41,7 +42,6 @@ import {import {Link} from '@astryxdesign/core/Link';import {Section} from '@astryxdesign/core/Section';import {Skeleton} from '@astryxdesign/core/Skeleton';-import {Spinner} from '@astryxdesign/core/Spinner';import {Text} from '@astryxdesign/core/Text';import {Thumbnail} from '@astryxdesign/core/Thumbnail';import {Timestamp} from '@astryxdesign/core/Timestamp';@@ -57,7 +57,6 @@ import {spacingVars,} from '@astryxdesign/core/theme/tokens.stylex';import {CommentIcon} from './icons';-import {useStatusAnnouncement} from './useStatusAnnouncement';import {eventAnchorId, type AnyComment} from './utils';import type {CommentAnchor,@@ -67,6 +66,8 @@ import type {CommentVersion,CommentActivityEvent,} from './types';+import {LoadingMessage} from '../LoadingMessage';+import {useStatusAnnouncement} from '../useStatusAnnouncement';/** The 28px avatar column every comment row, reply, and event aligns to. */export const AVATAR_SIZE = `calc(${spacingVars['--spacing-6']} + ${spacingVars['--spacing-1']})`;@@ -296,13 +297,13 @@ export function ErrorBanner({const t = useTranslator();const bannerRef = useRef<HTMLDivElement>(null);useStatusAnnouncement(- bannerRef,content.isRetrying === true || content.isAnnounced === true? null: description != null? t('@astryx.comments.errorAnnouncement', {title, description}): title,'assertive',+ {ref: bannerRef},);return (<Banner@@ -495,7 +496,7 @@ export function CommentProgressStatus({progress}: {progress: CommentProgress}) {// The label carries no live role: it mounts already holding its text. It is// announced politely through the shared channel, unless the chat log around// it delivers it (spec:AST-086 FR2, FR4).- useStatusAnnouncement(labelRef, progress.label, 'polite');+ useStatusAnnouncement(progress.label, 'polite', {ref: labelRef});return (<HStackgap={1}@@ -653,6 +654,14 @@ export function CommentAvatarFrame({user}: {user: CommentUser}) {);}+/** Runs beneath Dialog so useAnnounce reaches its modal scope. */+function BusyStatus({isBusy, message}: {isBusy: boolean; message: string}) {+ useStatusAnnouncement(isBusy ? message : null, 'polite', {+ skipPageLoad: true,+ });+ return null;+}+/** The empty 28px avatar column, for rows without an avatar. */export function AvatarSpacer() {return (@@ -754,6 +763,12 @@ export function HistoryDialog({}content={<LayoutContent>+ {/* Keep the announcement owner beneath Dialog: the shared channel+ routes its busy start into this modal. */}+ <BusyStatus+ isBusy={history.isLoading}+ message={t('@astryx.comments.historyLoading')}+ />{/* The shared channel is not exposed while a native modal is open(spec:AST-086), so a failure here is delivered by a persistentalert slot inside the dialog. The slot is mounted empty and the@@ -769,7 +784,10 @@ export function HistoryDialog({)}</div>{history.isLoading ? (- <Spinner size="lg" label={t('@astryx.comments.historyLoading')} />+ <LoadingMessage+ size="lg"+ label={t('@astryx.comments.historyLoading')}+ />) : history.error != null ? null : history.versions.length === 0 ? (<EmptyStatetitle={t('@astryx.comments.historyEmptyTitle')}diff --git a/packages/lab/src/Comments/Comments.test.tsx b/packages/lab/src/Comments/Comments.test.tsxindex 1d7b7584e9..693c22de40 100644--- a/packages/lab/src/Comments/Comments.test.tsx+++ b/packages/lab/src/Comments/Comments.test.tsx@@ -274,6 +274,10 @@ beforeAll(() => {if (selector === ':popover-open') {return popoverOpenState.get(this) ?? false;}+ // showModal below marks the dialog open; jsdom has no modal top layer.+ if (selector === ':modal') {+ return this instanceof HTMLDialogElement && this.open;+ }return originalMatches.call(this, selector);},});@@ -1041,6 +1045,29 @@ describe('Comments threads', () => {expect(document.body.textContent).toContain('Current version');});+ it('announces the history load through the shared dialog channel, then clears it (AST-086 FR8, FR14)', async () => {+ const loadVersions = vi.fn(() => new Promise<never>(() => {}));+ render(+ <Sized>+ <Comments comments={COMMENTS} loadVersions={loadVersions} />+ </Sized>,+ );+ await click(screen.getByRole('button', {name: 'View edit history'}));+ await flush();+ const dialog = screen.getByRole('dialog');+ const region = await waitFor(() => {+ const regions = dialog.querySelectorAll(+ ':scope > [data-astryx-modal-live-region="polite"]',+ );+ expect(regions).toHaveLength(1);+ expect(regions[0]).toHaveTextContent('Loading edit history');+ return regions[0];+ });+ await new Promise(resolve => setTimeout(resolve, 2100));+ expect(region).toBeEmptyDOMElement();+ expect(within(dialog).getByText('Loading edit history')).toBeVisible();+ });+it('retries a comment that failed to send', async () => {const onRetryComment = vi.fn().mockResolvedValue(undefined);render(diff --git a/packages/lab/src/Comments/Comments.tsx b/packages/lab/src/Comments/Comments.tsxindex cf3856d011..df7c53a69e 100644--- a/packages/lab/src/Comments/Comments.tsx+++ b/packages/lab/src/Comments/Comments.tsx@@ -44,7 +44,7 @@ import {ErrorBanner,} from './CommentParts';import {CommentRow, THREAD_DIVIDERS, type ThreadDivider} from './CommentRow';-import {useStatusAnnouncement} from './useStatusAnnouncement';+import {useStatusAnnouncement} from '../useStatusAnnouncement';import {CommentsContextProvider,useCommentsController,@@ -255,7 +255,6 @@ export function Comments({// (spec:AST-086 FR2, FR5).const loadErrorRef = useRef<HTMLDivElement>(null);useStatusAnnouncement(- loadErrorRef,loadError != null? t('@astryx.comments.errorAnnouncement', {title: t('@astryx.comments.loadFailed'),@@ -263,6 +262,7 @@ export function Comments({}): null,'assertive',+ {ref: loadErrorRef},);const rootRef = useRef<HTMLElement | null>(null);const setRootRef = useCallback(diff --git a/packages/lab/src/EmojiPicker/EmojiPicker.test.tsx b/packages/lab/src/EmojiPicker/EmojiPicker.test.tsxindex 5e99c72ed9..2b52d01a42 100644--- a/packages/lab/src/EmojiPicker/EmojiPicker.test.tsx+++ b/packages/lab/src/EmojiPicker/EmojiPicker.test.tsx@@ -257,7 +257,7 @@ describe('EmojiPicker', () => {it('loads the bundled set when no categories are passed', async () => {render(<EmojiPicker frequentEmojis={[]} onSelect={() => {}} />);- expect(screen.getByRole('status', {name: 'Loading emoji'})).toBeTruthy();+ expect(screen.getByText('Loading emoji')).toBeTruthy();await act(async () => {for (let attempt = 0; attempt < 40; attempt++) {if (screen.queryAllByRole('grid').length > 0) {diff --git a/packages/lab/src/EmojiPicker/EmojiPicker.tsx b/packages/lab/src/EmojiPicker/EmojiPicker.tsxindex 5cdc6749b8..5ea2e9f179 100644--- a/packages/lab/src/EmojiPicker/EmojiPicker.tsx+++ b/packages/lab/src/EmojiPicker/EmojiPicker.tsx@@ -5,7 +5,7 @@/*** @file EmojiPicker.tsx* @input Uses React, StyleX, theme tokens, useGridFocus, useTranslator,- * TextInput, ScrollableArea, Text, Spinner, Icon, and the lazily loaded CLDR+ * TextInput, ScrollableArea, Text, LoadingMessage, Icon, and the lazily loaded CLDR* emoji set (emojiData.ts)* @output Exports EmojiPicker, EmojiPickerProps, EmojiOption, EmojiCategory,* DEFAULT_FREQUENT_EMOJIS, and a persistent search-status announcement@@ -57,9 +57,10 @@ import {Center} from '@astryxdesign/core/Center';import {Icon} from '@astryxdesign/core/Icon';import {HStack, VStack} from '@astryxdesign/core/Layout';import {ScrollableArea} from '@astryxdesign/core/ScrollableArea';-import {Spinner} from '@astryxdesign/core/Spinner';import {Text} from '@astryxdesign/core/Text';import {TextInput} from '@astryxdesign/core/TextInput';+import {LoadingMessage} from '../LoadingMessage';+import {useStatusAnnouncement} from '../useStatusAnnouncement';export interface EmojiOption {/** The emoji character, e.g. "🎉". */@@ -405,6 +406,14 @@ export function EmojiPicker({t,]);const firstMatch = sections[0]?.emojis[0];+ // The ring is silent; the picker announces its own busy start.+ useStatusAnnouncement(+ isLoading && (queryWords.length === 0 || sections.length === 0)+ ? t('@astryx.emojiPicker.loading')+ : null,+ 'polite',+ {skipPageLoad: true},+ );const noResultsMessage =!isLoading && queryWords.length > 0 && sections.length === 0? t('@astryx.emojiPicker.noResults', {query: query.trim()})@@ -520,11 +529,17 @@ export function EmojiPicker({{sections.map(renderSection)}{queryWords.length > 0 && sections.length === 0 && isLoading ? (<Center>- <Spinner size="sm" label={t('@astryx.emojiPicker.loading')} />+ <LoadingMessage+ size="sm"+ label={t('@astryx.emojiPicker.loading')}+ /></Center>) : queryWords.length === 0 && isLoading ? (<Center>- <Spinner size="sm" label={t('@astryx.emojiPicker.loading')} />+ <LoadingMessage+ size="sm"+ label={t('@astryx.emojiPicker.loading')}+ /></Center>) : null}<HStackdiff --git a/packages/lab/src/LoadingMessage.tsx b/packages/lab/src/LoadingMessage.tsxnew file mode 100644index 0000000000..307dfe6219--- /dev/null+++ b/packages/lab/src/LoadingMessage.tsx@@ -0,0 +1,44 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file LoadingMessage.tsx+ * @input A loading message, a Spinner size+ * @output LoadingMessage: a silent Spinner ring above readable loading words+ * @position Shared by Lab owners that announce their own busy start: the ring+ * is hidden from assistive technology, since its owner announces, and the+ * words stay readable, laid out as Spinner's own labelled wrapper is (an+ * inline column, centred, with `--spacing-2` between)+ */++import * as stylex from '@stylexjs/stylex';+import {Spinner, type SpinnerSize} from '@astryxdesign/core/Spinner';+import {Text} from '@astryxdesign/core/Text';+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';++const styles = stylex.create({+ column: {+ display: 'inline-flex',+ flexDirection: 'column',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ },+});++export function LoadingMessage({+ label,+ size = 'md',+}: {+ label: string;+ size?: SpinnerSize;+}) {+ return (+ <span {...stylex.props(styles.column)}>+ <Spinner size={size} aria-hidden />+ <Text type="body" weight="bold">+ {label}+ </Text>+ </span>+ );+}diff --git a/packages/lab/src/Schedule/Schedule.test.tsx b/packages/lab/src/Schedule/Schedule.test.tsxindex ce6927cd30..ef5f47c7d0 100644--- a/packages/lab/src/Schedule/Schedule.test.tsx+++ b/packages/lab/src/Schedule/Schedule.test.tsx@@ -252,6 +252,11 @@ describe('Schedule', () => {/>,);+ expect(+ screen+ .getByLabelText('Loading events')+ .parentElement?.closest('[aria-hidden="true"]'),+ ).toBeNull();await waitFor(() => expect(loader).toHaveBeenCalledTimes(1));const [start, end] = loader.mock.calls[0];expect(typeof start).toBe('number');@@ -259,6 +264,11 @@ describe('Schedule', () => {expect(start).toBe(Date.UTC(2026, 4, 13));expect(end).toBe(Date.UTC(2026, 4, 14));expect(await screen.findByText('Loaded event')).toBeInTheDocument();+ expect(+ screen+ .getByLabelText('Loading events')+ .parentElement?.closest('[aria-hidden="true"]'),+ ).not.toBeNull();});it('renders list view grouped by localized day', async () => {diff --git a/packages/lab/src/Schedule/shared.tsx b/packages/lab/src/Schedule/shared.tsxindex 5ec1c23483..20be74a8ba 100644--- a/packages/lab/src/Schedule/shared.tsx+++ b/packages/lab/src/Schedule/shared.tsx@@ -54,6 +54,7 @@ import type {ScheduleHeaderContent,ScheduleEventColor,} from './types';+import {useStatusAnnouncement} from '../useStatusAnnouncement';const DEFAULT_EVENT_CATEGORY: ScheduleCategory = {label: 'Event',@@ -78,17 +79,22 @@ export function ScheduleFrame({children: ReactNode;}) {const {plugins} = useScheduleContext();+ // The ring is silent; the Schedule announces its own busy start.+ useStatusAnnouncement(isLoading ? 'Loading events' : null, 'polite', {+ skipPageLoad: true,+ });const initialHeader: ScheduleHeaderContent = {startContent: null,centerContent: (<span {...stylex.props(styles.headerTitleContent)}><Heading level={2}>{title}</Heading><span+ aria-hidden={!isLoading}{...stylex.props(styles.loadingSpinner,!isLoading && styles.loadingSpinnerHidden,)}>- <Spinner size="md" aria-label="Loading events" />+ <Spinner size="md" aria-label="Loading events" aria-hidden /></span></span>),diff --git a/packages/lab/src/useStatusAnnouncement.test.tsx b/packages/lab/src/useStatusAnnouncement.test.tsxnew file mode 100644index 0000000000..6ba1f1f546--- /dev/null+++ b/packages/lab/src/useStatusAnnouncement.test.tsx@@ -0,0 +1,133 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useStatusAnnouncement.test.tsx+ * @input useStatusAnnouncement with a mocked announcement channel+ * @output Proof of once-per-occasion status delivery, optional page-load+ * silence, and live-container ownership (`spec:AST-086` FR4, FR6, FR8, FR11)+ * @position Unit test beside useStatusAnnouncement.ts+ */++import {StrictMode, useRef} from 'react';+import {render, renderHook} from '@testing-library/react';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {useStatusAnnouncement} from './useStatusAnnouncement';++const {announce} = vi.hoisted(() => ({announce: vi.fn()}));+vi.mock('@astryxdesign/core/hooks', async importOriginal => ({+ ...(await importOriginal<object>()),+ useAnnounce: () => announce,+}));++function Owner({isBusy}: {isBusy: boolean}) {+ useStatusAnnouncement(isBusy ? 'Loading events' : null, 'polite', {+ skipPageLoad: true,+ });+ return null;+}++function Status({message}: {message: string}) {+ const ref = useRef<HTMLSpanElement>(null);+ useStatusAnnouncement(message, 'assertive', {ref});+ return <span ref={ref}>{message}</span>;+}++beforeEach(() => {+ announce.mockClear();+ vi.spyOn(document, 'readyState', 'get').mockReturnValue('complete');+});+afterEach(() => vi.restoreAllMocks());++describe('useStatusAnnouncement', () => {+ it('announces each busy start once, and nothing while busy or idle', () => {+ const {rerender} = render(<Owner isBusy={false} />);+ expect(announce).not.toHaveBeenCalled();+ rerender(<Owner isBusy={true} />);+ rerender(<Owner isBusy={true} />);+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Loading events',+ 'polite',+ );+ rerender(<Owner isBusy={false} />);+ rerender(<Owner isBusy={true} />);+ expect(announce).toHaveBeenCalledTimes(2);+ });++ it('announces an owner that mounts busy after page load once in StrictMode', () => {+ render(+ <StrictMode>+ <Owner isBusy={true} />+ </StrictMode>,+ );+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Loading events',+ 'polite',+ );+ });++ it.each(['loading', 'interactive'] as const)(+ 'skips a busy start while the document is %s, then re-arms for a later start',+ readyState => {+ const ready = vi+ .spyOn(document, 'readyState', 'get')+ .mockReturnValue(readyState);+ const {rerender} = render(<Owner isBusy={true} />);+ expect(announce).not.toHaveBeenCalled();+ ready.mockReturnValue('complete');+ rerender(<Owner isBusy={true} />);+ expect(announce).not.toHaveBeenCalled();+ rerender(<Owner isBusy={false} />);+ rerender(<Owner isBusy={true} />);+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Loading events',+ 'polite',+ );+ },+ );++ it('announces changed words after page load, but not a repeated message', () => {+ const ready = vi+ .spyOn(document, 'readyState', 'get')+ .mockReturnValue('loading');+ const {rerender} = renderHook(+ ({message}) =>+ useStatusAnnouncement(message, 'polite', {skipPageLoad: true}),+ {initialProps: {message: 'Loading events'}},+ );+ expect(announce).not.toHaveBeenCalled();+ ready.mockReturnValue('complete');+ rerender({message: 'Loading more events'});+ rerender({message: 'Loading more events'});+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Loading more events',+ 'polite',+ );+ });++ it('preserves default status delivery during page load and re-arms for empty text', () => {+ vi.spyOn(document, 'readyState', 'get').mockReturnValue('loading');+ const {rerender} = render(<Status message="Could not load comments" />);+ expect(announce).toHaveBeenCalledExactlyOnceWith(+ 'Could not load comments',+ 'assertive',+ );+ rerender(<Status message="" />);+ expect(announce).toHaveBeenCalledTimes(1);+ rerender(<Status message="Could not load comments" />);+ expect(announce).toHaveBeenCalledTimes(2);+ });++ it('leaves referenced content and its updates to the enclosing live container', () => {+ const {rerender} = render(+ <div role="log">+ <Status message="Could not load comments" />+ </div>,+ );+ rerender(+ <div role="log">+ <Status message="Could not save comment" />+ </div>,+ );+ expect(announce).not.toHaveBeenCalled();+ });+});diff --git a/packages/lab/src/Comments/useStatusAnnouncement.ts b/packages/lab/src/useStatusAnnouncement.tssimilarity index 59%rename from packages/lab/src/Comments/useStatusAnnouncement.tsrename to packages/lab/src/useStatusAnnouncement.tsindex eaa436b45c..adcb3a813f 100644--- a/packages/lab/src/Comments/useStatusAnnouncement.ts+++ b/packages/lab/src/useStatusAnnouncement.ts@@ -6,13 +6,13 @@* @file useStatusAnnouncement.ts* @input Uses React, useAnnounce from core hooks* @output Exports useStatusAnnouncement hook- * @position Internal to Comments; announces a transient status element- * (error banner, progress label) once instead of mounting it as a live region+ * @position Internal to Lab; announces transient status messages and busy starts+ * once instead of mounting them as live regions** A live region that mounts already holding its text may not be announced, so- * the visible element carries no live role (spec:AST-086 FR2). This hook says- * the words once through the shared channel instead, unless a live container- * such as a chat log already delivers content added inside it (FR4).+ * the visible element carries no live role. This hook says the words once+ * through the shared channel instead, unless a live container such as a chat+ * log already delivers content added inside it.*/import {useEffect, useRef, type RefObject} from 'react';@@ -26,16 +26,25 @@ const LIVE_CONTAINER_SELECTOR =* Announce `message` once per occasion: when the element first shows it, and* again whenever the message changes. A rerender or a StrictMode effect replay* does not repeat it, and a message that goes away and comes back is a new- * occasion (spec:AST-086 FR6).+ * occasion.*- * @param ref The visible element, used to find an enclosing live container.* @param message The words to say, or `null` for nothing.- * @param politeness Errors are `'assertive'`, progress is `'polite'` (FR5).+ * @param politeness Errors are `'assertive'`, progress is `'polite'`.+ * @param options.ref The visible element, when present, used to find an+ * enclosing live container.+ * @param options.skipPageLoad Keep messages present during page load silent.+ * Defaults to false to preserve Comments' error and progress delivery.*/export function useStatusAnnouncement(- ref: RefObject<HTMLElement | null>,message: string | null,politeness: AnnouncePoliteness,+ {+ ref,+ skipPageLoad = false,+ }: {+ ref?: RefObject<HTMLElement | null>;+ skipPageLoad?: boolean;+ } = {},): void {const announce = useAnnounce();const announcedRef = useRef<string | null>(null);@@ -48,10 +57,14 @@ export function useStatusAnnouncement(return;}announcedRef.current = message;+ // Remember a skipped message so completing page load is not a new occasion.+ if (skipPageLoad && document.readyState !== 'complete') {+ return;+ }const isInsideLiveContainer =- ref.current?.parentElement?.closest(LIVE_CONTAINER_SELECTOR) != null;+ ref?.current?.parentElement?.closest(LIVE_CONTAINER_SELECTOR) != null;if (!isInsideLiveContainer) {announce(message, politeness);}- }, [announce, message, politeness, ref]);+ }, [announce, message, politeness, ref, skipPageLoad]);}