An open source design system that's fully customizable and agent ready
TypeScript
fix(SegmentedControl): the disabled reason describes each segment, and one Tab stop remains when no enabled segment is selected (#9176)
Cindy Zhangdf6d16feaa4b
diff --git a/.changeset/segmented-control-disabled-reason-on-segment.md b/.changeset/segmented-control-disabled-reason-on-segment.mdnew file mode 100644index 0000000000..8a27f0e46c--- /dev/null+++ b/.changeset/segmented-control-disabled-reason-on-segment.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] SegmentedControl: a control disabled with a `disabledMessage` gives that reason to each segment as its description (`aria-describedby`), as well as to the group, so a screen reader announces it on the segment that has focus. The control also always keeps one Tab stop: the selected segment, even when it is itself disabled, else the first segment not disabled on its own, else the first.++@cixzhangdiff --git a/packages/core/src/RadioList/__tests__/RadioGroup.a11y.states.ts b/packages/core/src/RadioList/__tests__/RadioGroup.a11y.states.tsindex 9fd150528d..208e126865 100644--- a/packages/core/src/RadioList/__tests__/RadioGroup.a11y.states.ts+++ b/packages/core/src/RadioList/__tests__/RadioGroup.a11y.states.ts@@ -375,10 +375,11 @@ export const RADIO_GROUP_BINDING_STATES = [id: 'segmented-option-group-disabled-with-message',binding: 'SegmentedControlItem',summary:- 'a selected unavailable segment kept tabReachable for the group reason',+ 'a selected unavailable segment kept tabReachable and described by the group reason',facts: optionFacts({checked: true,disabled: true,+ description: 'Choose a project to switch views',operable: false,tabReachable: true,pointerCancellation: false,diff --git a/packages/core/src/SegmentedControl/SegmentedControl.spec.md b/packages/core/src/SegmentedControl/SegmentedControl.spec.mdindex c03ec9d141..2623e01b3b 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.spec.md+++ b/packages/core/src/SegmentedControl/SegmentedControl.spec.md@@ -49,15 +49,15 @@ system_specs: [spec:AST-020, spec:AST-085]## Contract at a glance-| Area | Contract |-| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | None changes. SegmentedControl takes `label`, `value`, `onChange`, `size`, `layout`, `isDisabled`, `disabledMessage`, base props, and SegmentedControlItem children. |-| Behavior | A `role="radiogroup"` named by `label` with one Tab stop; arrow keys, Home, and End move focus between enabled segments, wrap, and select the segment they land on. Tabbing in never changes the value. |-| End-user impact | People switch between a few modes with one click or arrow press, and the control shrinks with its row by truncating labels. A disabled control without a reason drops out of the tab order. |-| Builder impact | None. |-| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A disabled selected segment loses the Tab stop, a disabled control can have no Tab stop, a press while focused selects before any click, a caller `onFocus` or `onBlur` can cancel built-in focus behavior, a group reason describes only the radiogroup, caller handlers run while disabled, and a caller `aria-describedby` is dropped; all are listed under Current-state impact. |-| Review checks | Reject more than one Tab stop, a value change on Tab entry, arrows that land on a disabled segment, a control that overflows its container when segments have labels, or a selection while disabled. |-| Governing rules | WAI-ARIA radio group pattern; `spec:AST-020` FR9, FR15, DEC-5; `spec:AST-085` FR1, FR2, FR5, FR7; `design:user-states` DR1–DR3 (through SegmentedControlItem); `design:bidirectionality` DR6; `architecture:component-size-cascade` INV3–INV5; `architecture:interaction-modality` INV1; `architecture:public-component-api` INV5, INV7. |+| Area | Contract |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Public contract | None changes. SegmentedControl takes `label`, `value`, `onChange`, `size`, `layout`, `isDisabled`, `disabledMessage`, base props, and SegmentedControlItem children. |+| Behavior | A `role="radiogroup"` named by `label` with one Tab stop; arrow keys, Home, and End move focus between enabled segments, wrap, and select the segment they land on. Tabbing in never changes the value. |+| End-user impact | People switch between a few modes with one click or arrow press, and the control shrinks with its row by truncating labels. A disabled control without a reason drops out of the tab order. |+| Builder impact | None. |+| Compatibility/readiness | Records shipped behavior; no API, default, or DOM change. A disabled selected segment loses the Tab stop, a disabled control can have no Tab stop, a press while focused selects before any click, a caller `onFocus` or `onBlur` can cancel built-in focus behavior, caller handlers run while disabled, and a caller `aria-describedby` is dropped; all are listed under Current-state impact. |+| Review checks | Reject more than one Tab stop, a value change on Tab entry, arrows that land on a disabled segment, a control that overflows its container when segments have labels, or a selection while disabled. |+| Governing rules | WAI-ARIA radio group pattern; `spec:AST-020` FR9, FR15, DEC-5; `spec:AST-085` FR1, FR2, FR5, FR7; `design:user-states` DR1–DR3 (through SegmentedControlItem); `design:bidirectionality` DR6; `architecture:component-size-cascade` INV3–INV5; `architecture:interaction-modality` INV1; `architecture:public-component-api` INV5, INV7. |This table is a review projection; the body below is authoritative.@@ -112,16 +112,16 @@ Consumer migration instructions belong in consumer docs and release notes.## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |-| FR1 | The radiogroup container carries the current `segmented-control` target with `data-size`, sets `aria-label` to `label`, and renders its supplied children. | Current source, docs, and tests |-| FR2 | The group is one Tab stop: the selected segment, or, when the value matches no segment, the first segment not disabled by its own `isDisabled` (in a disabled group that segment keeps the stop, FR7); a disabled selected segment MUST keep the Tab stop (`spec:AST-085` FR1). Implementation gap: when the selected segment is disabled, the first enabled segment takes the Tab stop; and once the stop has fallen back to the first enabled segment, selecting another segment by click or by `value` leaves the stop there, so Tab re-enters on an unchecked segment. ArrowLeft and ArrowRight move focus between enabled segments in the visual direction, flipping in right-to-left layouts (`design:bidirectionality` DR6), and wrap; Home and End jump to the ends; ArrowUp and ArrowDown do nothing. Disabled segments are skipped. | WAI-ARIA radio group pattern; current tests; `design:bidirectionality` DR6 |-| FR3 | When arrow, Home, or End navigation moves focus to an enabled segment, that segment's value is passed to `onChange` if it differs. A pointer press MUST select only on a click whose lift lands inside the segment (`spec:AST-020` FR9, DEC-5). Implementation gap: while focus is already in the group, a pointer press on another segment moves focus there and selects before any click, so a press that slides off still selects. Focus entering the group from outside never changes the value. | WAI-ARIA radio group pattern; current tests; `spec:AST-020` FR9, DEC-5 |-| FR4 | A caller `onKeyDown` runs before built-in navigation and can cancel it with `preventDefault()`; a caller `onFocus` runs before selection-follows-focus. On first keyboard focus an ephemeral hint naming the arrow keys appears at the focused segment and dismisses on the first arrow press, a timeout, or blur. Built-in focus behavior MUST NOT be cancellable except where the public API promises it (`architecture:public-component-api` INV7). Implementation gap: a caller `onFocus` that calls `preventDefault()` also cancels the hint, the Tab-stop sync, and selection-follows-focus, and a caller `onBlur` that does so cancels the hint's blur dismissal. | Current source and tests; `architecture:public-component-api` INV7 |-| FR5 | `hug` sizes the control to its segments; when any segment shows a visible label, the control never exceeds its container and labelled segments shrink and truncate. A control of only icon-only segments keeps its size. `fill` stretches the control to its container and gives segments equal shares that can shrink and truncate. | Current tests |-| FR6 | Size resolves from an explicit `size`, then the nearest size provider, then `md`, and reaches every segment. | `architecture:component-size-cascade` INV3–INV5; current source |-| FR7 | `isDisabled` sets `aria-disabled` on the radiogroup, disables every segment, dims the control to half opacity, and blocks selection. The group MUST keep a Tab stop while disabled (`spec:AST-085` FR1, FR7). With `disabledMessage`, the selected segment stays the Tab stop, pointer events stay on, and a reason tooltip opens on hover and keyboard focus; the reason MUST describe the focusable segment (`spec:AST-085` FR5, FR7). Implementation gap: the reason describes only the radiogroup; caller handlers on the radiogroup, such as `onKeyDown`, still run while disabled (`spec:AST-085` FR2); without a `disabledMessage` the group ignores pointer input and every segment leaves the tab order, so the control has no Tab stop; and with a `disabledMessage`, the control also has no Tab stop when the value matches no segment or the selected segment is itself `isDisabled`. | `spec:AST-085`; current tests |-| FR8 | The radiogroup owns `role`, `aria-label` (from `label`), `aria-disabled`, and `data-size`; a caller value for any of them is replaced. Other base props reach the radiogroup, and `ref` reaches it. Implementation gap: a caller `aria-describedby` is replaced, by the disabled-reason id or by nothing, against `architecture:public-component-api` INV5. | `architecture:public-component-api` INV5; current source and tests |+| ID | Invariant | Basis |+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |+| FR1 | The radiogroup container carries the current `segmented-control` target with `data-size`, sets `aria-label` to `label`, and renders its supplied children. | Current source, docs, and tests |+| FR2 | The group is one Tab stop: the selected segment, or, when the value matches no segment, the first segment not disabled by its own `isDisabled` (in a disabled group that segment keeps the stop, FR7); a disabled selected segment MUST keep the Tab stop (`spec:AST-085` FR1). Implementation gap: when the selected segment is disabled, the first enabled segment takes the Tab stop; and once the stop has fallen back to the first enabled segment, selecting another segment by click or by `value` leaves the stop there, so Tab re-enters on an unchecked segment. ArrowLeft and ArrowRight move focus between enabled segments in the visual direction, flipping in right-to-left layouts (`design:bidirectionality` DR6), and wrap; Home and End jump to the ends; ArrowUp and ArrowDown do nothing. Disabled segments are skipped. | WAI-ARIA radio group pattern; current tests; `design:bidirectionality` DR6 |+| FR3 | When arrow, Home, or End navigation moves focus to an enabled segment, that segment's value is passed to `onChange` if it differs. A pointer press MUST select only on a click whose lift lands inside the segment (`spec:AST-020` FR9, DEC-5). Implementation gap: while focus is already in the group, a pointer press on another segment moves focus there and selects before any click, so a press that slides off still selects. Focus entering the group from outside never changes the value. | WAI-ARIA radio group pattern; current tests; `spec:AST-020` FR9, DEC-5 |+| FR4 | A caller `onKeyDown` runs before built-in navigation and can cancel it with `preventDefault()`; a caller `onFocus` runs before selection-follows-focus. On first keyboard focus an ephemeral hint naming the arrow keys appears at the focused segment and dismisses on the first arrow press, a timeout, or blur. Built-in focus behavior MUST NOT be cancellable except where the public API promises it (`architecture:public-component-api` INV7). Implementation gap: a caller `onFocus` that calls `preventDefault()` also cancels the hint, the Tab-stop sync, and selection-follows-focus, and a caller `onBlur` that does so cancels the hint's blur dismissal. | Current source and tests; `architecture:public-component-api` INV7 |+| FR5 | `hug` sizes the control to its segments; when any segment shows a visible label, the control never exceeds its container and labelled segments shrink and truncate. A control of only icon-only segments keeps its size. `fill` stretches the control to its container and gives segments equal shares that can shrink and truncate. | Current tests |+| FR6 | Size resolves from an explicit `size`, then the nearest size provider, then `md`, and reaches every segment. | `architecture:component-size-cascade` INV3–INV5; current source |+| FR7 | `isDisabled` sets `aria-disabled` on the radiogroup, disables every segment, dims the control to half opacity, and blocks selection. The group MUST keep a Tab stop while disabled (`spec:AST-085` FR1, FR7). With `disabledMessage`, the selected segment stays the Tab stop, pointer events stay on, and a reason tooltip opens on hover and keyboard focus; the reason MUST describe the focusable segment (`spec:AST-085` FR5, FR7). Implementation gap: caller handlers on the radiogroup, such as `onKeyDown`, still run while disabled (`spec:AST-085` FR2); and without a `disabledMessage` the group ignores pointer input and every segment leaves the tab order, so the control has no Tab stop. | `spec:AST-085`; current tests |+| FR8 | The radiogroup owns `role`, `aria-label` (from `label`), `aria-disabled`, and `data-size`; a caller value for any of them is replaced. Other base props reach the radiogroup, and `ref` reaches it. Implementation gap: a caller `aria-describedby` is replaced, by the disabled-reason id or by nothing, against `architecture:public-component-api` INV5. | `architecture:public-component-api` INV5; current source and tests |### Allowed variation@@ -149,8 +149,8 @@ Consumer migration instructions belong in consumer docs and release notes.- **ORD2 — Tab stop.** The selected segment; for a value that matches nosegment, the first segment not disabled by its own `isDisabled`. Today adisabled selected segment keeps the stop only in a group disabled with a- reason when it is not itself `isDisabled`, and a fallen-back stop stays on- the first enabled segment after another segment is selected (FR2, FR7 gaps).+ reason, and a fallen-back stop stays on the first enabled segment after+ another segment is selected (FR2, FR7 gaps).### Performance and resources@@ -206,27 +206,26 @@ segment parts as well.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------- |-| FR1, AR1 | `SegmentedControl.test.tsx` rendering, size, and data-testid cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states | Control with several segments; sizes | Lost group semantics or name fails. Evidence gap: no test asserts the `segmented-control` target or `data-size`. | `audit:SegmentedControl/anatomy` |-| FR2, FR3, ORD2, AR2 | `SegmentedControl.test.tsx` keyboard-navigation and unmatched-value cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states; the radio-group pattern's aborted-press check on `segmented-option-unselected`; the `segmented-group-selected-rtl` state's arrow round trip under `dir="rtl"` | Arrows, wrap, Home, End; Tab-in with an unmatched or disabled selection | A value change on Tab entry, no wrap, or landing on a disabled segment fails. A press that slides off with focus outside the group and still selects fails. Evidence gap: no test covers a slide-off press while focus is already in the group. No test selects another segment after the stop has fallen back. | `audit:SegmentedControl/accessibility` |-| FR4, ORD1 | `SegmentedControl.test.tsx` container handler forwarding cases | Caller `onKeyDown`, with and without `preventDefault` | A caller key handler that cannot cancel navigation fails. Evidence gap: no test asserts the caller `onFocus` order or the keyboard hint. | `audit:SegmentedControl/behavior` |-| FR5 | `SegmentedControl.test.tsx` layout cases | Hug, fill, narrow row, icon-only | A control that overflows, or squeezes icon-only segments, fails. | `audit:SegmentedControl/layout` |-| FR6 | Evidence gap: no test asserts size precedence or its propagation | — | — | `audit:SegmentedControl/layout` |-| FR7, AR3 | `SegmentedControl.test.tsx` disabled and disabledMessage cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-disabled` and `segmented-group-disabled-with-message` states | Group and item disabled; with reason | A selection while disabled, or a missing reason tooltip, fails. Evidence gap: no test asserts the half opacity, or caller handlers while disabled. The `segmented-group-disabled` state declares `tabReachable: false`, asserting the current FR7 gap pending conformance. The `segmented-option-group-disabled-with-message` state declares no description on the focusable segment, asserting the reason-target gap pending conformance. | `audit:SegmentedControl/accessibility` |-| FR8 | `SegmentedControl.test.tsx` role-override and data-testid cases | Forwarded role | A forwarded prop that overrides the role fails. Evidence gap: no test asserts `ref` or a caller `aria-describedby`. | `audit:SegmentedControl/api` |-| PR1 | Evidence gap: no test asserts the absence of global listeners | — | — | `audit:SegmentedControl/behavior` |-| Target inventory | `packages/core/src/theme/themingTargets.test.ts` | Control and item targets | A rendered class absent from the documented targets fails. | `audit:SegmentedControl/theming` |-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and both current targets | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:SegmentedControl/theming` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |+| FR1, AR1 | `SegmentedControl.test.tsx` rendering, size, and data-testid cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states | Control with several segments; sizes | Lost group semantics or name fails. Evidence gap: no test asserts the `segmented-control` target or `data-size`. | `audit:SegmentedControl/anatomy` |+| FR2, FR3, ORD2, AR2 | `SegmentedControl.test.tsx` keyboard-navigation and unmatched-value cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-*` states; the radio-group pattern's aborted-press check on `segmented-option-unselected`; the `segmented-group-selected-rtl` state's arrow round trip under `dir="rtl"` | Arrows, wrap, Home, End; Tab-in with an unmatched or disabled selection | A value change on Tab entry, no wrap, or landing on a disabled segment fails. A press that slides off with focus outside the group and still selects fails. Evidence gap: no test covers a slide-off press while focus is already in the group. No test selects another segment after the stop has fallen back. | `audit:SegmentedControl/accessibility` |+| FR4, ORD1 | `SegmentedControl.test.tsx` container handler forwarding cases | Caller `onKeyDown`, with and without `preventDefault` | A caller key handler that cannot cancel navigation fails. Evidence gap: no test asserts the caller `onFocus` order or the keyboard hint. | `audit:SegmentedControl/behavior` |+| FR5 | `SegmentedControl.test.tsx` layout cases | Hug, fill, narrow row, icon-only | A control that overflows, or squeezes icon-only segments, fails. | `audit:SegmentedControl/layout` |+| FR6 | Evidence gap: no test asserts size precedence or its propagation | — | — | `audit:SegmentedControl/layout` |+| FR7, AR3 | `SegmentedControl.test.tsx` disabled and disabledMessage cases; `RadioGroup.a11y.test.tsx` and `RadioGroup.a11y.chromium.spec.ts` (in `RadioList/__tests__`) `segmented-group-disabled` and `segmented-group-disabled-with-message` states | Group and item disabled; with reason | A selection while disabled, or a missing reason tooltip, fails. Evidence gap: no test asserts the half opacity, or caller handlers while disabled. The `segmented-group-disabled` state declares `tabReachable: false`, asserting the current FR7 gap pending conformance. | `audit:SegmentedControl/accessibility` |+| FR8 | `SegmentedControl.test.tsx` role-override and data-testid cases | Forwarded role | A forwarded prop that overrides the role fails. Evidence gap: no test asserts `ref` or a caller `aria-describedby`. | `audit:SegmentedControl/api` |+| PR1 | Evidence gap: no test asserts the absence of global listeners | — | — | `audit:SegmentedControl/behavior` |+| Target inventory | `packages/core/src/theme/themingTargets.test.ts` | Control and item targets | A rendered class absent from the documented targets fails. | `audit:SegmentedControl/theming` |+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and both current targets | Missing, extra, prefixed, or stale mappings fail repository validation. | `audit:SegmentedControl/theming` |## Current-state impact- **Disabled Tab stop (FR7).** A control disabled without a reason has no Tabstop, against `spec:AST-085` FR1 and FR7.-- **Disabled selected Tab stop (FR2, FR7).** A disabled selected segment- loses the Tab stop to the first enabled segment, and a control disabled with- a reason has no Tab stop when its value matches no segment or its selected- segment is itself disabled, against `spec:AST-085` FR1.+- **Disabled selected Tab stop (FR2).** Outside a group disabled with a+ reason, a disabled selected segment loses the Tab stop to the first enabled+ segment, against `spec:AST-085` FR1.- **Stale fallback Tab stop (FR2).** After the Tab stop falls back to thefirst enabled segment, selecting another segment by click or by `value`leaves the stop there, so Tab re-enters on an unchecked segment.@@ -236,8 +235,6 @@ segment parts as well.- **Focus handler cancellation (FR4).** A caller `onFocus` or `onBlur` thatcalls `preventDefault()` cancels built-in focus behavior the public API doesnot promise to expose, against `architecture:public-component-api` INV7.-- **Group reason (FR7).** A group `disabledMessage` describes only the- radiogroup, not the focusable segment, against `spec:AST-085` FR5 and FR7.- **Caller handlers while disabled (FR7).** Caller handlers on the radiogroup,such as `onKeyDown`, still run while disabled, against `spec:AST-085` FR2.- **Caller description (FR8).** A caller `aria-describedby` on the control isdiff --git a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx b/packages/core/src/SegmentedControl/SegmentedControl.test.tsxindex 631651fd5c..6f338d0a6b 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.test.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControl.test.tsx@@ -16,6 +16,7 @@ import {describe, it, expect, vi, beforeEach} from 'vitest';import {render, screen, fireEvent, waitFor} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {hasPressedArm} from '../__tests__/pressState';+import {__resetInteractionModalityForTest} from '../utils/interactionModality';import {SegmentedControl} from './SegmentedControl';import {SegmentedControlItem} from './SegmentedControlItem';import {@@ -669,6 +670,11 @@ describe('SegmentedControl disabled state', () => {describe('disabledMessage', () => {const h = {hidden: true} as const;+ // The input modality is document-global; each case starts without one.+ beforeEach(() => {+ __resetInteractionModalityForTest();+ });+function renderControl(props?: {onChange?: (v: string) => void}) {return render(<SegmentedControl@@ -735,6 +741,127 @@ describe('SegmentedControl disabled state', () => {fireEvent.click(list);expect(onChange).not.toHaveBeenCalled();});++ // spec:AST-085 FR5: the reason describes the segment that has focus.+ it('describes the focused segment with the reason', async () => {+ const user = userEvent.setup();+ renderControl();+ await user.tab();+ const grid = screen.getByRole('radio', {name: 'Grid'});+ expect(grid).toHaveFocus();+ expect(grid).toHaveAccessibleDescription(+ 'Choose a project to switch views',+ );+ expect(+ screen.getByRole('radio', {name: 'List'}),+ ).toHaveAccessibleDescription('Choose a project to switch views');+ });++ it('keeps a caller description ahead of the reason', () => {+ render(+ <>+ <span id="grid-hint">Shows thumbnails</span>+ <SegmentedControl+ value="grid"+ onChange={() => {}}+ label="View mode"+ isDisabled+ disabledMessage="Choose a project to switch views">+ <SegmentedControlItem+ value="grid"+ label="Grid"+ aria-describedby="grid-hint"+ />+ </SegmentedControl>+ </>,+ );+ expect(+ screen.getByRole('radio', {name: 'Grid'}),+ ).toHaveAccessibleDescription(+ 'Shows thumbnails Choose a project to switch views',+ );+ });++ it('adds no reason to the segments of a control that is not disabled', () => {+ render(+ <SegmentedControl+ value="grid"+ onChange={() => {}}+ label="View mode"+ disabledMessage="Choose a project to switch views">+ <SegmentedControlItem value="grid" label="Grid" />+ </SegmentedControl>,+ );+ expect(screen.getByRole('radio', {name: 'Grid'})).not.toHaveAttribute(+ 'aria-describedby',+ );+ });++ // FR7: the control keeps one Tab stop while disabled with a reason, even+ // when no enabled segment is selected.+ it.each([+ ['the value matches no segment', 'none', undefined, 'Grid'],+ ['the selected segment is itself disabled', 'grid', 'grid', 'Grid'],+ [+ 'the value matches no segment and the first is itself disabled',+ 'none',+ 'grid',+ 'List',+ ],+ ] as const)(+ 'keeps one Tab stop when %s',+ async (_case, value, disabledSegment, expectedStop) => {+ const user = userEvent.setup();+ render(+ <>+ <button type="button">Before</button>+ <SegmentedControl+ value={value}+ onChange={() => {}}+ label="View mode"+ isDisabled+ disabledMessage="Choose a project to switch views">+ <SegmentedControlItem+ value="grid"+ label="Grid"+ isDisabled={disabledSegment === 'grid'}+ />+ <SegmentedControlItem value="list" label="List" />+ </SegmentedControl>+ <button type="button">After</button>+ </>,+ );+ const stops = screen+ .getAllByRole('radio')+ .filter(radio => radio.tabIndex === 0);+ expect(stops.map(radio => radio.textContent)).toEqual([expectedStop]);+ await user.tab();+ expect(screen.getByRole('button', {name: 'Before'})).toHaveFocus();+ await user.tab();+ const stop = screen.getByRole('radio', {name: expectedStop});+ expect(stop).toHaveFocus();+ expect(stop).toHaveAccessibleDescription(+ 'Choose a project to switch views',+ );+ await user.tab();+ expect(screen.getByRole('button', {name: 'After'})).toHaveFocus();+ },+ );++ it('opens the reason on a tap and selects nothing', async () => {+ const onChange = vi.fn();+ renderControl({onChange});+ const tooltip = screen.getByRole('tooltip', h);+ const list = screen.getByRole('radio', {name: 'List'});+ // A tap, in the order a browser dispatches it.+ fireEvent.pointerEnter(list, {pointerType: 'touch'});+ fireEvent.pointerDown(list, {pointerType: 'touch'});+ fireEvent.pointerUp(list, {pointerType: 'touch'});+ fireEvent.mouseEnter(list);+ fireEvent.click(list);+ await waitFor(() => expect(tooltip).toHaveAttribute('popover-open'));+ expect(onChange).not.toHaveBeenCalled();+ });});});diff --git a/packages/core/src/SegmentedControl/SegmentedControl.tsx b/packages/core/src/SegmentedControl/SegmentedControl.tsxindex f74825d32a..c19ad97475 100644--- a/packages/core/src/SegmentedControl/SegmentedControl.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControl.tsx@@ -19,7 +19,8 @@ import React, {useMemo, useCallback, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars, spacingVars, radiusVars} from '../theme/tokens.stylex';import {SegmentedControlContext} from './SegmentedControlContext';-import {useListFocus} from '../hooks/useListFocus';+import {useInternalListFocus} from '../hooks/useListFocus';+import {isSegmentDisabledOnItsOwn} from '../privateAttributes/segmentDisabled.stylex';import {useKeyboardHint} from '../hooks/useKeyboardHint';import {useTooltip} from '../Tooltip';import type {@@ -198,12 +199,17 @@ export function SegmentedControl({// the radios, skips disabled ones, wraps at the ends, handles Home/End, and// repairs the tab stop on mount and whenever items mount/disable — replacing// the component's former inline keyboard handler and tab-stop repair effect.- const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({- itemSelector: '[role="radio"]:not([aria-disabled="true"])',- hasRovingTabIndex: true,- wrap: true,- orientation: 'horizontal',- });+ const {listRef, handleKeyDown, handleFocus} =+ useInternalListFocus<HTMLDivElement>({+ itemSelector: '[role="radio"]:not([aria-disabled="true"])',+ hasRovingTabIndex: true,+ // Disabled with a reason, the control keeps one Tab stop so the reason is+ // reachable (FR2, FR7): the selected segment, else the first segment not+ // disabled by its own isDisabled, else the first.+ disabledTabStop: showsDisabledMessage ? orderDisabledTabStop : undefined,+ wrap: true,+ orientation: 'horizontal',+ });const hint = useKeyboardHint({orientation: 'horizontal',@@ -271,8 +277,19 @@ export function SegmentedControl({layout,isDisabled,hasDisabledMessage: showsDisabledMessage,+ disabledReasonID: showsDisabledMessage+ ? disabledMessageTooltip.describedBy+ : undefined,}),- [value, onChange, size, layout, isDisabled, showsDisabledMessage],+ [+ value,+ onChange,+ size,+ layout,+ isDisabled,+ showsDisabledMessage,+ disabledMessageTooltip.describedBy,+ ],);return (@@ -316,3 +333,21 @@ export function SegmentedControl({}SegmentedControl.displayName = 'SegmentedControl';++/**+ * The segments of a control disabled with a reason, its Tab stop first: the+ * selected segment, else the first segment not disabled by its own+ * isDisabled, else the first (FR2, FR7).+ */+function orderDisabledTabStop(list: HTMLElement): ReadonlyArray<HTMLElement> {+ const segments = Array.from(+ list.querySelectorAll<HTMLElement>('[role="radio"]'),+ );+ const stop =+ segments.find(segment => segment.getAttribute('aria-checked') === 'true') ??+ segments.find(segment => !isSegmentDisabledOnItsOwn(segment)) ??+ segments[0];+ return stop == null+ ? []+ : [stop, ...segments.filter(segment => segment !== stop)];+}diff --git a/packages/core/src/SegmentedControl/SegmentedControlContext.ts b/packages/core/src/SegmentedControl/SegmentedControlContext.tsindex 375cdf9a63..66a845d015 100644--- a/packages/core/src/SegmentedControl/SegmentedControlContext.ts+++ b/packages/core/src/SegmentedControl/SegmentedControlContext.ts@@ -30,6 +30,12 @@ export interface SegmentedControlContextValue {* tooltip is keyboard-discoverable; selection is still blocked.*/hasDisabledMessage?: boolean;+ /**+ * The id of the group's disabled-reason tooltip while `hasDisabledMessage`+ * is true. It also describes each segment, so the segment that has focus is+ * described by the reason (spec:AST-085 FR5).+ */+ disabledReasonID?: string;}export const SegmentedControlContext =diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.spec.md b/packages/core/src/SegmentedControl/SegmentedControlItem.spec.mdindex 79ef628d82..83d6b04f25 100644--- a/packages/core/src/SegmentedControl/SegmentedControlItem.spec.md+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.spec.md@@ -108,7 +108,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR1 | Each segment renders one `<button type="button" role="radio">` with `aria-checked` true when its `value` equals the group value, `data-value`, and the `segmented-control-item` target reflecting `data-size`, `data-selected`, and `data-disabled`. A forwarded prop cannot override the role. | WAI-ARIA radio pattern; current source and tests || FR2 | A click, including one from Space or Enter on the focused segment (native button activation; `spec:AST-020` FR15), runs the caller `onClick` first; unless it prevents default, an enabled, unselected segment passes its value to the group's `onChange`. Clicking the selected segment does nothing. The caller's `preventDefault()` MUST veto every press. Implementation gap: a press while focus is already in the group selects through `component:SegmentedControl` FR3 before the click, so the veto does not apply to it. | `spec:AST-020` FR15; current tests || FR3 | The segment renders its icon (sized to the segment size) followed by its label. With `isLabelHidden`, the label is not rendered and becomes `aria-label`, and the segment does not shrink. A visible label truncates with an ellipsis when the segment is narrower than it. | Current tests |-| FR4 | A segment disabled by its own `isDisabled` or by the group sets `aria-disabled`, refuses selection, shows disabled text color, and shows no hover or press paint. A disabled selected segment MUST keep the Tab stop (`spec:AST-085` FR1); for a value that matches no segment, `component:SegmentedControl` FR2 places the stop. Implementation gap: a disabled selected segment leaves the tab order, except in a group disabled with a reason when it is not itself `isDisabled`, and a caller `onClick` still runs on a disabled segment (`spec:AST-085` FR2). | `spec:AST-085` FR1, FR2; current tests |+| FR4 | A segment disabled by its own `isDisabled` or by the group sets `aria-disabled`, refuses selection, shows disabled text color, and shows no hover or press paint. A disabled selected segment MUST keep the Tab stop (`spec:AST-085` FR1); for a value that matches no segment, `component:SegmentedControl` FR2 places the stop. Implementation gap: a disabled selected segment leaves the tab order, except in a group disabled with a reason, and a caller `onClick` still runs on a disabled segment (`spec:AST-085` FR2). | `spec:AST-085` FR1, FR2; current tests || FR5 | The selected segment paints a raised surface with a low shadow and semibold primary text; under forced colors it paints `Highlight` with `HighlightText`. Unselected enabled segments paint the shared hover tint and, under `design:user-states` DR1 and DR2, the pressed overlay; the selected segment keeps its raised surface during a press (DR3). | WCAG 1.4.11; `design:user-states` DR1–DR3; current tests || FR6 | Segment height is the element height for the size minus 4 CSS px (24, 28, or 32) as a minimum that grows with a set text size under `spec:AST-102` FR4 (implementation gap: the height is fixed), with corners concentric with the control; `sm` uses supporting text and tighter padding. Keyboard focus paints the shared focus outline. | `architecture:interaction-modality` INV1; current source; `spec:AST-102` FR4 || FR7 | The segment owns `role`, `aria-checked`, `aria-disabled`, `aria-label` (set from the label when hidden), `tabIndex`, `type`, `data-value`, and `data-size`, and writes `data-selected`, `data-disabled`, and the press marker `data-astryx-pressable` in their own states; a caller value for an owned attribute is replaced, while a caller `data-selected`, `data-disabled`, or `data-astryx-pressable` passes through on segments outside that state. `ref`, other `data-*`, `style`, other ARIA such as `aria-describedby`, and other base props reach the button; `xstyle` composes last. Caller `className` MUST compose with the component's classes (`architecture:public-component-api` INV5, INV6). Implementation gap: the component's merged class replaces a caller `className`. | `architecture:public-component-api` INV5, INV6; current tests |diff --git a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx b/packages/core/src/SegmentedControl/SegmentedControlItem.tsxindex 836188771e..cb190f3bb1 100644--- a/packages/core/src/SegmentedControl/SegmentedControlItem.tsx+++ b/packages/core/src/SegmentedControl/SegmentedControlItem.tsx@@ -16,6 +16,8 @@*/import React, {type ReactNode} from 'react';+import {joinAriaIDs} from '../utils/inputAria';+import {segmentDisabledProps} from '../privateAttributes/segmentDisabled.stylex';import * as stylex from '@stylexjs/stylex';import {colorVars,@@ -192,6 +194,7 @@ export function SegmentedControlItem({isDisabled = false,onClick: onClickProp,xstyle,+ 'aria-describedby': ariaDescribedByProp,...rest}: SegmentedControlItemProps) {const pressable = usePressFeedback();@@ -203,8 +206,11 @@ export function SegmentedControlItem({// segment focusable so the group's reason tooltip is keyboard-discoverable.// Per-item disabling (`isDisabled` on the item) always drops out of the tab// order. Activation stays blocked by the isItemDisabled guard in handleClick.+ // Disabled with a reason, the selected segment keeps the Tab stop even when+ // it is itself disabled (FR4); with no selected segment, the group places+ // the stop (SegmentedControl FR2).const keepsSelectedFocusable =- isSelected && (ctx.hasDisabledMessage ?? false) && !isDisabled;+ isSelected && (ctx.hasDisabledMessage ?? false);const size: SegmentedControlSize = ctx.size;const isFill = ctx.layout === 'fill';@@ -235,7 +241,12 @@ export function SegmentedControlItem({aria-checked={isSelected}aria-disabled={isItemDisabled || undefined}aria-label={isLabelHidden ? label : undefined}+ // A caller description, then the group's disabled reason, which+ // describes each segment (FR7).+ aria-describedby={joinAriaIDs(ariaDescribedByProp, ctx.disabledReasonID)}data-value={value}+ // The group's fallback Tab stop skips segments disabled on their own.+ {...segmentDisabledProps(isDisabled)}{...(!isSelected && !isItemDisabled ? pressable : undefined)}// Disabled items (including when the whole group is disabled) are not tab// stops — otherwise the selected segment stays keyboard-focusable but isdiff --git a/packages/core/src/hooks/useListFocus.test.tsx b/packages/core/src/hooks/useListFocus.test.tsxindex 8b383a4877..493846d3a5 100644--- a/packages/core/src/hooks/useListFocus.test.tsx+++ b/packages/core/src/hooks/useListFocus.test.tsx@@ -13,7 +13,7 @@import {describe, it, expect, vi} from 'vitest';import type {KeyboardEvent as ReactKeyboardEvent} from 'react';import {render, screen, fireEvent} from '@testing-library/react';-import {useListFocus} from './useListFocus';+import {useInternalListFocus, useListFocus} from './useListFocus';const NO_DISABLED: string[] = [];@@ -122,13 +122,15 @@ function RovingToolbar({}: {labels?: string[];disabledLabels?: string[];-} & Parameters<typeof useListFocus>[0]) {- const {listRef, handleKeyDown, handleFocus} = useListFocus<HTMLDivElement>({- itemSelector: 'button, input, [tabindex]',- hasRovingTabIndex: true,- orientation: 'horizontal',- ...opts,- });+} & Parameters<typeof useInternalListFocus>[0]) {+ // The internal hook takes the public options plus the Core-only ones.+ const {listRef, handleKeyDown, handleFocus} =+ useInternalListFocus<HTMLDivElement>({+ itemSelector: 'button, input, [tabindex]',+ hasRovingTabIndex: true,+ orientation: 'horizontal',+ ...opts,+ });return (<divref={listRef}@@ -148,6 +150,16 @@ function RovingToolbar({);}+function orderBy(first: string) {+ return (list: HTMLElement) => {+ const buttons = Array.from(list.querySelectorAll<HTMLElement>('button'));+ const stop = buttons.find(button => button.dataset.testid === first);+ return stop == null+ ? buttons+ : [stop, ...buttons.filter(button => button !== stop)];+ };+}+describe('useListFocus roving tabindex (hasRovingTabIndex)', () => {it('stamps a single tab stop (first enabled item is tabbable)', () => {render(<RovingToolbar />);@@ -162,6 +174,36 @@ describe('useListFocus roving tabindex (hasRovingTabIndex)', () => {expect(screen.getByTestId('A')).toHaveAttribute('tabindex', '-1');});+ it('leaves no tab stop while every item is disabled, by default', () => {+ render(<RovingToolbar disabledLabels={ROVING_LABELS} />);+ for (const label of ROVING_LABELS) {+ expect(screen.getByTestId(label)).not.toHaveAttribute('tabindex', '0');+ }+ });++ it('keeps one tab stop while every item is disabled, on the element the callback returns first', () => {+ const {rerender} = render(+ <RovingToolbar+ disabledLabels={ROVING_LABELS}+ disabledTabStop={orderBy('B')}+ />,+ );+ expect(screen.getByTestId('B')).toHaveAttribute('tabindex', '0');+ expect(screen.getByTestId('A')).toHaveAttribute('tabindex', '-1');+ expect(screen.getByTestId('C')).toHaveAttribute('tabindex', '-1');++ // The stop follows what the callback returns first.+ rerender(+ <RovingToolbar+ disabledLabels={ROVING_LABELS}+ disabledTabStop={orderBy('A')}+ />,+ );+ expect(screen.getByTestId('A')).toHaveAttribute('tabindex', '0');+ expect(screen.getByTestId('B')).toHaveAttribute('tabindex', '-1');+ expect(screen.getByTestId('C')).toHaveAttribute('tabindex', '-1');+ });+it('ArrowRight moves the tab stop to the next enabled item', () => {render(<RovingToolbar />);const toolbar = screen.getByRole('toolbar');diff --git a/packages/core/src/hooks/useListFocus.ts b/packages/core/src/hooks/useListFocus.tsindex 528e8398f3..358bb97621 100644--- a/packages/core/src/hooks/useListFocus.ts+++ b/packages/core/src/hooks/useListFocus.ts@@ -121,6 +121,21 @@ export interface UseListFocusOptions {hasCaretGuard?: boolean;}+/**+ * Options only Core components pass; this module's internal export, not+ * re-exported from `hooks/index.ts`, so not public API.+ */+export interface InternalListFocusOptions extends UseListFocusOptions {+ /**+ * With `hasRovingTabIndex`, keeps one tab stop while every item is disabled:+ * returns the elements that share it, the stop first. The hook gives the+ * first `tabindex="0"` and the rest `tabindex="-1"`. For a group that stays+ * focusable while disabled, so its disabled reason is reachable by keyboard.+ * Unset (the default): no item holds the stop while every item is disabled.+ */+ disabledTabStop?: (list: HTMLElement) => ReadonlyArray<HTMLElement>;+}+/*** Return type for useListFocus hook*/@@ -325,6 +340,16 @@ function shouldDeferToCaret(target: EventTarget | null, key: string): boolean {*/export function useListFocus<T extends HTMLElement = HTMLElement>(options: UseListFocusOptions = {},+): UseListFocusReturn<T> {+ return useInternalListFocus<T>(options);+}++/**+ * {@link useListFocus} with the Core-only {@link InternalListFocusOptions}.+ * Not re-exported from `hooks/index.ts`.+ */+export function useInternalListFocus<T extends HTMLElement = HTMLElement>(+ options: InternalListFocusOptions = {},): UseListFocusReturn<T> {const {itemSelector = '[role="menuitem"]',@@ -335,6 +360,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(hasHomeEnd = true,hasPaging = false,hasRovingTabIndex = false,+ disabledTabStop,hasCaretGuard = false,} = options;@@ -462,6 +488,17 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(const items = getItems();const enabled = items.filter(el => !isItemDisabled(el));if (enabled.length === 0) {+ const listEl = listRef.current;+ if (listEl == null || disabledTabStop == null) {+ return;+ }+ const [stop, ...others] = disabledTabStop(listEl);+ if (stop != null) {+ setTabIndex(stop, 0);+ }+ for (const el of others) {+ setTabIndex(el, -1);+ }return;}const current = enabled.find(el => el.getAttribute('tabindex') === '0');@@ -469,7 +506,7 @@ export function useListFocus<T extends HTMLElement = HTMLElement>(for (const el of items) {setTabIndex(el, el === tabbable ? 0 : -1);}- }, [getItems, isItemDisabled, setTabIndex]);+ }, [getItems, isItemDisabled, setTabIndex, disabledTabStop]);// Keep the tab stop valid across renders (items added/removed, disabled// toggled). Runs after every commit but only when roving tabindex is on.diff --git a/packages/core/src/privateAttributes/segmentDisabled.stylex.ts b/packages/core/src/privateAttributes/segmentDisabled.stylex.tsnew file mode 100644index 0000000000..05cbe74f7b--- /dev/null+++ b/packages/core/src/privateAttributes/segmentDisabled.stylex.ts@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file privateAttributes/segmentDisabled.stylex.ts+ * @input A segment's own `isDisabled`+ * @output segmentDisabledProps, which marks a SegmentedControl segment+ * disabled by its own `isDisabled`, and isSegmentDisabledOnItsOwn, which+ * reads that mark+ * @position Owner module of the private segment-disabled attribute+ * (`architecture:public-component-api` INV23): the only file that writes+ * its name. SegmentedControl reads it to place the Tab stop of a control+ * disabled with a reason (`component:SegmentedControl` FR2). No package+ * entry exports it.+ */++const SEGMENT_DISABLED = 'data-astryx-segment-disabled';++/** Spread on a segment: marks it when it is disabled by its own isDisabled. */+export function segmentDisabledProps(+ isDisabled: boolean,+): Readonly<Record<string, string>> {+ return isDisabled ? {[SEGMENT_DISABLED]: ''} : {};+}++/** Whether a segment element is disabled by its own isDisabled. */+export function isSegmentDisabledOnItsOwn(segment: Element): boolean {+ return segment.hasAttribute(SEGMENT_DISABLED);+}