An open source design system that's fully customizable and agent ready
TypeScript
fix(ToggleButton): keep a member's own disabled state inside an enabled group (#6356)
Cindy Zhang5a7b81959305
diff --git a/.changeset/toggle-button-member-disabled.md b/.changeset/toggle-button-member-disabled.mdnew file mode 100644index 0000000000..9ad3bcf6b8--- /dev/null+++ b/.changeset/toggle-button-member-disabled.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Keep a ToggleButton's own `isDisabled` when its ToggleButtonGroup does not disable anything. The group always supplies an `isDisabled` boolean, so the previous `??` fallback never ran and an enabled group re-enabled a member that had disabled itself — the member selected on click, and a member carrying a `tooltip` stayed operable while looking unavailable. A disabled group still disables every member; it just cannot re-enable one. (#6356)++@cixzhangdiff --git a/apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsx b/apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsxnew file mode 100644index 0000000000..99b4d0cdd4--- /dev/null+++ b/apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsx@@ -0,0 +1,177 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToggleButtonDisabledA11y.stories.tsx+ * @input Uses ToggleButton and ToggleButtonGroup from core+ * @output The four disabled/enabled fixtures the ToggleButton disabled-state+ * regression spec drives in a real browser.+ * @position The reproduction path for+ * `packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts`+ * (`docs/specs/AST-009/spec.md` FR30: a browser claim is checked against a+ * checked-in story, not a page a test builds and throws away).+ *+ * Each story counts its own activations and publishes the count as+ * `data-a11y-activations`, so a person opening the story reads the same number+ * the spec does. A toggle that refuses a press leaves no trace on itself, so+ * counting the handler is the only honest way to ask whether pressing it did+ * anything.+ *+ * The two disabled fixtures cover the two halves of `docs/families/buttons.md`+ * FR3 that regressed together: a member's own disabled state must survive an+ * enabled group, and a disabled toggle kept focusable by a tooltip must still+ * refuse a pointer press. The two enabled fixtures are the control — they fail+ * if a fix over-disables.+ *+ * SYNC: The spec navigates to these story ids by name. Nothing at compile time+ * catches a renamed export — the Chromium spec does, when it finds no story.+ */++import {useState, type ReactNode} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {ToggleButton, ToggleButtonGroup} from '@astryxdesign/core/ToggleButton';++/** Render one fixture and count how many times its handler ran. */+function Counted({+ children,+}: {+ children: (activate: () => void) => ReactNode;+}): ReactNode {+ const [count, setCount] = useState(0);+ return (+ <div data-a11y-activations={count}>+ {children(() => {+ setCount(current => current + 1);+ })}+ <p>+ activations: <output>{count}</output>+ </p>+ </div>+ );+}++const meta: Meta = {+ title: 'a11y/ToggleButton disabled state',+ // These fixtures exist to be DRIVEN by the regression spec, not photographed:+ // a disabled control inside an enabled group is a state no product ships on+ // purpose, so a baseline frame would be a picture nobody reviews. Excluding+ // them costs no coverage — every one is still driven in a real browser.+ tags: ['no-visual'],+ parameters: {+ docs: {+ description: {+ component:+ 'Disabled-state fixtures for ToggleButton and ToggleButtonGroup. Each story counts its own activations, because a toggle that refuses a press leaves no trace of having been pressed.',+ },+ },+ },+};++export default meta;++/**+ * A member that disables itself, inside a group that does not disable anything.+ * The group must not hand the member its availability back.+ */+export const GroupEnabledMemberDisabled: StoryObj = {+ name: 'group enabled — member disabled',+ render: function Render() {+ const [value, setValue] = useState<string | null>(null);+ return (+ <Counted>+ {activate => (+ <ToggleButtonGroup+ label="View mode"+ value={value}+ onChange={next => {+ activate();+ setValue(next);+ }}>+ <ToggleButton value="list" label="List" isDisabled />+ <ToggleButton value="grid" label="Grid" />+ </ToggleButtonGroup>+ )}+ </Counted>+ );+ },+};++/**+ * The other half of the same rule: a group that disables everything still+ * disables a member that says nothing about its own availability.+ */+export const GroupDisabledMemberSilent: StoryObj = {+ name: 'group disabled — member silent',+ render: function Render() {+ const [value, setValue] = useState<string | null>(null);+ return (+ <Counted>+ {activate => (+ <ToggleButtonGroup+ label="View mode"+ value={value}+ isDisabled+ onChange={next => {+ activate();+ setValue(next);+ }}>+ <ToggleButton value="list" label="List" />+ </ToggleButtonGroup>+ )}+ </Counted>+ );+ },+};++/**+ * A disabled toggle kept focusable by its tooltip, so the reason it is+ * unavailable stays reachable. Focusable is not operable: a pointer press must+ * still be refused.+ */+export const DisabledWithTooltip: StoryObj = {+ name: 'disabled — kept focusable by a tooltip',+ render: function Render() {+ const [isPressed, setIsPressed] = useState(false);+ return (+ <Counted>+ {activate => (+ <ToggleButton+ label="Bold"+ tooltip="Formatting is locked for this document"+ isDisabled+ isPressed={isPressed}+ onPressedChange={next => {+ activate();+ setIsPressed(next);+ }}+ />+ )}+ </Counted>+ );+ },+};++/**+ * The control. An enabled toggle carrying the same tooltip must still toggle —+ * this is the story that fails if a fix disables too much.+ */+export const EnabledWithTooltip: StoryObj = {+ name: 'enabled — with a tooltip',+ render: function Render() {+ const [isPressed, setIsPressed] = useState(false);+ return (+ <Counted>+ {activate => (+ <ToggleButton+ label="Bold"+ tooltip="Bold the selected text"+ isPressed={isPressed}+ onPressedChange={next => {+ activate();+ setIsPressed(next);+ }}+ />+ )}+ </Counted>+ );+ },+};diff --git a/packages/core/src/ToggleButton/ToggleButton.test.tsx b/packages/core/src/ToggleButton/ToggleButton.test.tsxindex 01c2221d76..8411ad4169 100644--- a/packages/core/src/ToggleButton/ToggleButton.test.tsx+++ b/packages/core/src/ToggleButton/ToggleButton.test.tsx@@ -570,6 +570,139 @@ describe('ToggleButtonGroup (multiple)', () => {});});+// =============================================================================+// Disabled state — family:buttons FR3 (disabled means non-operable)+// =============================================================================++/**+ * Two ways a ToggleButton becomes unavailable, and the rule that binds them:+ * a group disables everything it contains, and a member can disable itself+ * while the group stays enabled. Neither source may cancel the other out.+ *+ * The tooltip cases are here at the attribute and callback level only. A+ * tooltip'd disabled toggle carries `aria-disabled` instead of the native+ * `disabled` attribute, so whether a REAL mouse press is refused is an engine+ * fact that jsdom's synthetic click cannot settle — that half lives in+ * ./__tests__/ToggleButton.a11y.chromium.spec.ts.+ */+describe('disabled state', () => {+ it('keeps a member disabled when the group disables nothing', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <ToggleButtonGroup value={null} onChange={handleChange} label="View mode">+ <ToggleButton value="list" label="List" isDisabled />+ <ToggleButton value="grid" label="Grid" />+ </ToggleButtonGroup>,+ );++ expect(screen.getByRole('button', {name: 'List'})).toBeDisabled();++ await user.click(screen.getByRole('button', {name: 'List'}));+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('leaves the rest of an enabled group selectable', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <ToggleButtonGroup value={null} onChange={handleChange} label="View mode">+ <ToggleButton value="list" label="List" isDisabled />+ <ToggleButton value="grid" label="Grid" />+ </ToggleButtonGroup>,+ );++ expect(screen.getByRole('button', {name: 'Grid'})).toBeEnabled();++ await user.click(screen.getByRole('button', {name: 'Grid'}));+ expect(handleChange).toHaveBeenCalledWith('grid');+ });++ it('still disables a member that says nothing when the group is disabled', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <ToggleButtonGroup+ value={null}+ onChange={handleChange}+ label="View mode"+ isDisabled>+ <ToggleButton value="list" label="List" />+ </ToggleButtonGroup>,+ );++ expect(screen.getByRole('button', {name: 'List'})).toBeDisabled();++ await user.click(screen.getByRole('button', {name: 'List'}));+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('keeps a tooltip-bearing disabled member focusable but inert', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <ToggleButtonGroup value={null} onChange={handleChange} label="View mode">+ <ToggleButton+ value="list"+ label="List"+ tooltip="List view is unavailable for this dataset"+ isDisabled+ />+ </ToggleButtonGroup>,+ );++ const member = screen.getByRole('button', {name: 'List'});+ // The tooltip is the disabled reason, so the control stays reachable to+ // read it: aria-disabled rather than the native attribute, which would+ // take it out of the tab order along with its own explanation.+ expect(member).toHaveAttribute('aria-disabled', 'true');+ expect(member).not.toBeDisabled();++ await user.click(member);+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('does not toggle a standalone disabled toggle that carries a tooltip', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <ToggleButton+ label="Bold"+ tooltip="Formatting is locked for this document"+ isPressed={false}+ onPressedChange={handleChange}+ isDisabled+ />,+ );++ const toggle = screen.getByRole('button', {name: 'Bold'});+ expect(toggle).toHaveAttribute('aria-disabled', 'true');++ await user.click(toggle);+ expect(handleChange).not.toHaveBeenCalled();+ expect(toggle).toHaveAttribute('aria-pressed', 'false');+ });++ it('still toggles an enabled toggle that carries the same tooltip', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <ToggleButton+ label="Bold"+ tooltip="Bold the selected text"+ isPressed={false}+ onPressedChange={handleChange}+ />,+ );++ const toggle = screen.getByRole('button', {name: 'Bold'});+ expect(toggle).not.toHaveAttribute('aria-disabled');++ await user.click(toggle);+ expect(handleChange).toHaveBeenCalledWith(true, expect.anything());+ });+});+// jsdom cannot emulate forced-colors rendering, so these assert that the// compiled output includes the forced-colors rules; visual behavior needs// manual verification under Windows High Contrast.diff --git a/packages/core/src/ToggleButton/ToggleButton.tsx b/packages/core/src/ToggleButton/ToggleButton.tsxindex 180bc5518d..2972f3ebfd 100644--- a/packages/core/src/ToggleButton/ToggleButton.tsx+++ b/packages/core/src/ToggleButton/ToggleButton.tsx@@ -154,7 +154,8 @@ export interface ToggleButtonProps extends BaseProps<HTMLButtonElement> {/*** Whether the button is disabled.- * When used inside ToggleButtonGroup, the group's isDisabled overrides this.+ * When used inside ToggleButtonGroup, a disabled group disables this button+ * too, but an enabled group does not re-enable a button that disables itself.* @default false*/isDisabled?: boolean;@@ -263,7 +264,13 @@ export function ToggleButton({? group.selectedValues.has(value): (isPressedProp ?? false);const size = sizeProp ?? group?.size ?? 'md';- const isDisabled = group?.isDisabled ?? isDisabledProp;+ // Either source disabling this button is enough. `??` could not express that:+ // the group always supplies a boolean (its own prop defaults to false), so the+ // fallback never ran and an enabled group handed a member that had disabled+ // itself its availability back. A group still disables everything it contains+ // — that is the half `??` got right — but it cannot re-enable a member+ // (family:buttons FR3).+ const isDisabled = (group?.isDisabled ?? false) || isDisabledProp;// Track the pressed state optimistically so the button reflects the intended// state immediately while an async action is pending. The optimistic updatediff --git a/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.tsnew file mode 100644index 0000000000..8e7d8cfeac--- /dev/null+++ b/packages/core/src/ToggleButton/__tests__/ToggleButton.a11y.chromium.spec.ts@@ -0,0 +1,209 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ToggleButton.a11y.chromium.spec.ts+ * @input Uses @playwright/test, the a11y-spec static Storybook server, and the+ * checked-in ToggleButtonDisabledA11y stories+ * @output Real-browser evidence for `docs/families/buttons.md` FR3 — disabled+ * means non-operable — across the two ways a ToggleButton becomes disabled,+ * plus the enabled control that catches a fix which disables too much.+ * @position The half of FR3 that jsdom cannot honestly reach. A disabled toggle+ * kept focusable by a tooltip carries `aria-disabled` instead of the native+ * `disabled` attribute, so whether a real mouse press is refused is an engine+ * fact — jsdom's synthetic click does not settle it+ * (`docs/specs/AST-013/spec.md`: a browser claim is made in a browser).+ *+ * Each state drives a checked-in story rather than a page this file builds, so+ * the reproduction path for any failure is a URL a person can open+ * (`docs/specs/AST-009/spec.md` FR30). Each story counts its own activations,+ * which is what `activationsOn` reads — a toggle that refuses a press leaves no+ * trace on itself.+ *+ * Presses go through `page.mouse` at the control's own centre rather than+ * `locator.click()`. Playwright's actionability wait would refuse to press a+ * natively disabled control at all, which would prove nothing about what the+ * engine does with a press that really lands.+ *+ * SYNC: Fixtures live in+ * /apps/storybook/stories/ToggleButtonDisabledA11y.stories.tsx.+ */++import {expect, test, type Page} from '@playwright/test';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const STORY_BASE = 'a11y-togglebutton-disabled-state';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++/** Load a story and wait for the control the assertions press. */+async function mountStory(page: Page, storyId: string): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY_BASE}--${storyId}&viewMode=story`,+ {waitUntil: 'load'},+ );+ await holdMotionStill(page);+ await page+ .locator('#storybook-root')+ .getByRole('button')+ .first()+ .waitFor({state: 'attached'});+}++/**+ * How many times this story's own handler has run.+ *+ * The story publishes the count as an attribute, so this reads a fact the story+ * renders rather than instrumenting the page from the test — a person opening+ * the story sees the same number the spec does.+ */+async function activationsOn(page: Page): Promise<number> {+ const raw = await page+ .locator('[data-a11y-activations]')+ .first()+ .getAttribute('data-a11y-activations');+ return Number(raw ?? '0');+}++/**+ * A real mouse press at the control's own centre, landing whether or not+ * Playwright would consider the control actionable. This is the press the+ * expectations are about: a user aiming at a control that looks unavailable.+ */+async function pressWithMouse(page: Page, name: string): Promise<void> {+ const control = page+ .locator('#storybook-root')+ .getByRole('button', {name, includeHidden: true})+ .first();+ const box = await control.boundingBox();+ if (box == null) {+ throw new Error(+ `"${name}" has no layout box, so no mouse press could land on it`,+ );+ }+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);+}++/**+ * Whether the engine reports this control as unavailable, by either of the two+ * spellings FR3 permits: the native attribute, or focusable `aria-disabled`.+ */+async function isUnavailable(page: Page, name: string): Promise<boolean> {+ return page+ .locator('#storybook-root')+ .getByRole('button', {name, includeHidden: true})+ .first()+ .evaluate(+ element =>+ (element as HTMLButtonElement).disabled ||+ element.getAttribute('aria-disabled') === 'true',+ );+}++test('a member that disables itself stays disabled inside an enabled group', async ({+ page,+}) => {+ await mountStory(page, 'group-enabled-member-disabled');++ expect(+ await isUnavailable(page, 'List'),+ 'the member sets isDisabled, so it must be exposed as unavailable even though the group disables nothing',+ ).toBe(true);++ await pressWithMouse(page, 'List');+ expect(+ await activationsOn(page),+ 'a disabled member must not invoke the group selection callback (family:buttons FR3)',+ ).toBe(0);+});++test('an enabled member of the same group still toggles', async ({page}) => {+ await mountStory(page, 'group-enabled-member-disabled');++ expect(await isUnavailable(page, 'Grid')).toBe(false);++ await pressWithMouse(page, 'Grid');+ expect(+ await activationsOn(page),+ 'the sibling says nothing about its own availability and the group disables nothing, so it must still select',+ ).toBe(1);+});++test('a group disabled state still disables a member that says nothing', async ({+ page,+}) => {+ await mountStory(page, 'group-disabled-member-silent');++ expect(await isUnavailable(page, 'List')).toBe(true);++ await pressWithMouse(page, 'List');+ expect(+ await activationsOn(page),+ 'a group disabled state overrides member availability (family:buttons FR3)',+ ).toBe(0);+});++test('a disabled toggle kept focusable by its tooltip refuses a mouse press', async ({+ page,+}) => {+ await mountStory(page, 'disabled-with-tooltip');++ const control = page.locator('#storybook-root').getByRole('button').first();++ // The tooltip is why this control is focusable rather than natively disabled,+ // so the press has to be made the way a user reaches it: hover first, let the+ // tip come up, then press. Pressing cold would skip the hover state the+ // tooltip's own pointer listeners run in.+ await control.hover();+ await expect(page.getByRole('tooltip')).toBeVisible();++ expect(+ await control.evaluate(element => element.getAttribute('aria-disabled')),+ 'a tooltip keeps the reason reachable by making the control focusable rather than natively disabled',+ ).toBe('true');+ expect(await control.getAttribute('aria-pressed')).toBe('false');++ await pressWithMouse(page, 'Bold');++ expect(+ await activationsOn(page),+ 'focusable is not operable: a disabled toggle must not invoke onPressedChange from a mouse press (family:buttons FR3)',+ ).toBe(0);+ expect(+ await control.getAttribute('aria-pressed'),+ 'the pressed state must not flip',+ ).toBe('false');+});++test('an enabled toggle with the same tooltip still toggles on a mouse press', async ({+ page,+}) => {+ await mountStory(page, 'enabled-with-tooltip');++ const control = page.locator('#storybook-root').getByRole('button').first();+ await control.hover();+ await expect(page.getByRole('tooltip')).toBeVisible();+ expect(await control.getAttribute('aria-pressed')).toBe('false');++ await pressWithMouse(page, 'Bold');++ expect(+ await activationsOn(page),+ 'the enabled path must be untouched by the disabled-state fix',+ ).toBe(1);+ expect(await control.getAttribute('aria-pressed')).toBe('true');+});