An open source design system that's fully customizable and agent ready
TypeScript
fix(ToggleButton): keep pressed Actions on Button's clickAction path (#6463)
Cindy Zhang21756e8c7903
diff --git a/.changeset/toggle-button-click-action.md b/.changeset/toggle-button-click-action.mdnew file mode 100644index 0000000000..9eb1bac796--- /dev/null+++ b/.changeset/toggle-button-click-action.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Keep ToggleButton callbacks synchronous and run pressed Actions through Button’s clickAction pathway, preserving callback cancellation and optimistic pending feedback. Omit the Action pathway for callback-only toggles and value-identified ToggleButtonGroup members, whose selection remains group-owned.++@cixzhangdiff --git a/docs/families/buttons.md b/docs/families/buttons.mdindex a01f751094..39f752aba2 100644--- a/docs/families/buttons.md+++ b/docs/families/buttons.md@@ -121,7 +121,13 @@ Membership follows public responsibility, not an import of Button or a rendereddistinct.- **FR5 — Callback and Action order is consistent.** Where a member exposes botha synchronous callback and an Action, the callback runs first. Preventing that- event prevents the Action. A fire-once action deduplicates activation while+ event prevents the Action. Standalone ToggleButton runs `onPressedChange` from+ its internal `onClick` and delegates `pressedChangeAction` to Button's+ `clickAction`. Button runs the callback before the Action and skips the Action+ when the callback calls `preventDefault()`. The Action also runs when no callback+ is supplied. Without `pressedChangeAction`, ToggleButton MUST leave `clickAction`+ absent so callback-only activation starts no empty Action transition and reports+ no Action-pending feedback. A fire-once action deduplicates activation whilepending; an explicitly interruptible persistent action may accept a newactivation and replace the in-flight intent.- **FR6 — Persistent state is explicit and reversible.** A ToggleButton MUST@@ -148,6 +154,10 @@ Membership follows public responsibility, not an import of Button or a renderedToggleButtonGroup MUST expose an accessible group label and propagate theirdocumented size and disabled defaults without removing a member's accessiblename. The group owns only the behavior and surface declared by its group mode.+ A ToggleButtonGroup member identified by `value` MUST derive pressed state and+ selection requests from the group, not its standalone `isPressed`,+ `onPressedChange`, or `pressedChangeAction`. Member `onPressedChange` and+ `pressedChangeAction` are ignored, and Button's `clickAction` MUST be absent.- **FR12 — Connected and spaced groups stay distinct.** ButtonGroup's connectedpresentation removes inter-member gaps, shares outer edges, owns one elevation,and uses its documented roving-focus keyboard model. The current@@ -208,13 +218,13 @@ and any later fill or outline treatment requires separate visual review.## Verification map-| Contract | Verification | Representative members and states | Mutation or failure expectation |-| --------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |-| FR1–FR3 | role/name, keyboard, callback, disabled, and disabled-reason tests | text Button, IconButton, ToggleButton, link mode, member/group disabled | a member loses its name, keyboard path, or invokes while disabled |-| FR4–FR6 | Action order, pending, optimistic, dedupe, and interruptibility tests | Button fire-once Action; ToggleButton rapid pressed/unpressed Actions | dimensions or purpose change, Action bypasses callback cancellation, or stale state wins |-| FR7 | unit plus real-browser geometry checks | all sizes; text/icon-only; pressed/unpressed; loading | family heights diverge, icon-only stops being square, or state shifts outer size |-| FR8–FR10 | data attribute, theme metadata, and computed-shadow tests | standalone Button/IconButton/ToggleButton; connected and spaced groups; every elevation tier | shadow lands on the wrong box, state changes depth, or public/theme/rendered values disagree |-| FR11–FR12 | group semantics, propagation, DOM, keyboard, and rendered-surface tests | connected ButtonGroup; spaced ToggleButtonGroup; horizontal/vertical; disabled members | group lacks a name, default propagation fails, or spaced/connected ownership is conflated |+| Contract | Verification | Representative members and states | Mutation or failure expectation |+| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |+| FR1–FR3 | role/name, keyboard, callback, disabled, and disabled-reason tests | text Button, IconButton, ToggleButton, link mode, member/group disabled | a member loses its name, keyboard path, or invokes while disabled |+| FR4–FR6 | `ToggleButton.test.tsx`: callback/Action order and cancellation, callback-only no-pending path, Action-only settlement, and optimistic re-click tests | standalone ToggleButton with either/both callbacks; Button fire-once Action | callback is dropped, an empty Action reports busy, cancellation is bypassed, or stale state wins |+| FR7 | unit plus real-browser geometry checks | all sizes; text/icon-only; pressed/unpressed; loading | family heights diverge, icon-only stops being square, or state shifts outer size |+| FR8–FR10 | data attribute, theme metadata, and computed-shadow tests | standalone Button/IconButton/ToggleButton; connected and spaced groups; every elevation tier | shadow lands on the wrong box, state changes depth, or public/theme/rendered values disagree |+| FR11–FR12 | group semantics, propagation, DOM, keyboard, and rendered-surface tests; `ToggleButton.test.tsx` group ownership cases | single/multiple selection with member callbacks/Actions and delayed parent acceptance; connected/spaced groups | member callback or Action competes with group state, or surface ownership is conflated |## Decision linksdiff --git a/packages/core/src/ToggleButton/ToggleButton.doc.mjs b/packages/core/src/ToggleButton/ToggleButton.doc.mjsindex 40ba2a556c..1cf97b6e94 100644--- a/packages/core/src/ToggleButton/ToggleButton.doc.mjs+++ b/packages/core/src/ToggleButton/ToggleButton.doc.mjs@@ -31,17 +31,17 @@ export const docs = {{name: 'isPressed',type: 'boolean',- description: 'Whether the button is currently pressed. Ignored when inside a group.',+ description: 'Whether the button is currently pressed. Ignored for a ToggleButtonGroup member with a value.',},{name: 'onPressedChange',type: '(isPressed: boolean, event: MouseEvent) => void',- description: 'Called when pressed state should change. Receives the next state and the click event; call event.preventDefault() to skip pressedChangeAction. Ignored when inside a group.',+ description: 'Called synchronously from the internal click handler when pressed state should change. Receives the next state and the click event; call event.preventDefault() to skip pressedChangeAction. Without an Action, the callback starts no Action transition. Ignored for a ToggleButtonGroup member with a value.',},{name: 'pressedChangeAction',type: '(isPressed: boolean) => void | Promise<void>',- description: 'Action handler for API- or navigation-backed toggles, run in a transition. Shows an optimistic pressed state immediately and a spinner while pending; the button stays interruptible by re-clicks.',+ description: 'Action handler for API- or navigation-backed toggles, run through Button’s clickAction transition after the synchronous onPressedChange callback unless that callback calls event.preventDefault(). Works without onPressedChange. Shows an optimistic pressed state and a spinner while pending, and remains interruptible by re-clicks. Omit it for callback-only toggles with no Action transition. Ignored for a ToggleButtonGroup member with a value.',},{name: 'size',diff --git a/packages/core/src/ToggleButton/ToggleButton.test.tsx b/packages/core/src/ToggleButton/ToggleButton.test.tsxindex 8411ad4169..57bc3e8799 100644--- a/packages/core/src/ToggleButton/ToggleButton.test.tsx+++ b/packages/core/src/ToggleButton/ToggleButton.test.tsx@@ -3,7 +3,8 @@/*** @file ToggleButton.test.tsx* @input Uses vitest, @testing-library/react, ToggleButton, ToggleButtonGroup- * @output Unit tests for ToggleButton and ToggleButtonGroup+ * @output Unit tests for ToggleButton callback/Action order, pending state,+ * group-owned selection, and ToggleButtonGroup** SYNC: When ToggleButton.tsx or ToggleButtonGroup.tsx changes, update tests*/@@ -388,8 +389,94 @@ describe('ToggleButton', () => {expect(pressedChangeAction).toHaveBeenCalledWith(true);});+ it('runs the synchronous callback before the Action with the same next state', async () => {+ const calls: string[] = [];+ const pressedChangeAction = vi.fn(() => {+ calls.push('action');+ });+ const onPressedChange = vi.fn(() => {+ expect(pressedChangeAction).not.toHaveBeenCalled();+ calls.push('change');+ });+ render(+ <ToggleButton+ label="Favorite"+ isPressed={false}+ onPressedChange={onPressedChange}+ pressedChangeAction={pressedChangeAction}+ />,+ );++ await userEvent.setup().click(screen.getByRole('button'));++ expect(calls).toEqual(['change', 'action']);+ expect(onPressedChange).toHaveBeenCalledExactlyOnceWith(+ true,+ expect.anything(),+ );+ expect(pressedChangeAction).toHaveBeenCalledExactlyOnceWith(true);+ });++ it('keeps callback-only controlled toggles synchronous without pending feedback', async () => {+ function LegacyToggle() {+ const [isPressed, setIsPressed] = useState(false);+ return (+ <ToggleButton+ label="Bold"+ isPressed={isPressed}+ onPressedChange={setIsPressed}+ />+ );+ }+ render(<LegacyToggle />);+ const button = screen.getByRole('button');++ fireEvent.click(button);+ expect(button).toHaveAttribute('aria-pressed', 'true');+ expect(button).not.toHaveAttribute('aria-busy', 'true');+ fireEvent.click(button);+ expect(button).toHaveAttribute('aria-pressed', 'false');+ expect(button).not.toHaveAttribute('aria-busy', 'true');+ await act(async () => {});+ });++ it('runs an Action without onPressedChange and settles to the controlled value', async () => {+ let resolveAction: (() => void) | undefined;+ const pressedChangeAction = vi.fn(+ async () =>+ new Promise<void>(resolve => {+ resolveAction = resolve;+ }),+ );+ const {rerender} = render(+ <ToggleButton+ label="Favorite"+ isPressed={false}+ pressedChangeAction={pressedChangeAction}+ />,+ );+ const button = screen.getByRole('button');++ await userEvent.setup().click(button);+ expect(pressedChangeAction).toHaveBeenCalledExactlyOnceWith(true);+ expect(button).toHaveAttribute('aria-pressed', 'true');+ expect(button).toHaveAttribute('aria-busy', 'true');+ await act(async () => resolveAction?.());+ expect(button).toHaveAttribute('aria-pressed', 'false');+ expect(button).not.toHaveAttribute('aria-busy', 'true');++ rerender(+ <ToggleButton+ label="Favorite"+ isPressed+ pressedChangeAction={pressedChangeAction}+ />,+ );+ expect(button).toHaveAttribute('aria-pressed', 'true');+ expect(pressedChangeAction).toHaveBeenCalledTimes(1);+ });+it('skips pressedChangeAction when onPressedChange calls preventDefault', async () => {- const user = userEvent.setup();const pressedChangeAction = vi.fn();const onPressedChange = vi.fn((_next: boolean, event: MouseEvent<HTMLButtonElement>) => {@@ -406,10 +493,17 @@ describe('ToggleButton', () => {/>,);- await user.click(screen.getByRole('button', {name: 'Favorite'}));+ const button = screen.getByRole('button', {name: 'Favorite'});+ fireEvent.click(button);- expect(onPressedChange).toHaveBeenCalledWith(true, expect.anything());+ expect(onPressedChange).toHaveBeenCalledExactlyOnceWith(+ true,+ expect.anything(),+ );expect(pressedChangeAction).not.toHaveBeenCalled();+ expect(button).toHaveAttribute('aria-pressed', 'false');+ expect(button).not.toHaveAttribute('aria-busy', 'true');+ await act(async () => {});});});@@ -570,6 +664,74 @@ describe('ToggleButtonGroup (multiple)', () => {});});+// =============================================================================+// Group ownership — member Actions must not compete with controlled selection+// =============================================================================++describe.each(['single', 'multiple'] as const)(+ 'ToggleButtonGroup (%s) ownership',+ type => {+ it('keeps selection group-owned even when a member has standalone handlers', async () => {+ const onChange = vi.fn();+ const onPressedChange = vi.fn();+ const pressedChangeAction = vi.fn();+ const groupProps =+ type === 'single'+ ? {type, value: 'list', onChange}+ : {type, value: ['list'], onChange};+ const children = (+ <>+ <ToggleButton value="list" label="List" isPressed={false} />+ <ToggleButton+ value="grid"+ label="Grid"+ isPressed+ onPressedChange={onPressedChange}+ pressedChangeAction={pressedChangeAction}+ />+ </>+ );+ const {rerender} = render(+ <ToggleButtonGroup {...groupProps} label="View">+ {children}+ </ToggleButtonGroup>,+ );+ const grid = screen.getByRole('button', {name: 'Grid'});+ expect(grid).toHaveAttribute('aria-pressed', 'false');+ expect(screen.getByRole('button', {name: 'List'})).toHaveAttribute(+ 'aria-pressed',+ 'true',+ );++ await userEvent.setup().click(grid);+ expect(onChange).toHaveBeenCalledExactlyOnceWith(+ type === 'single' ? 'grid' : ['list', 'grid'],+ );+ expect(onPressedChange).not.toHaveBeenCalled();+ expect(pressedChangeAction).not.toHaveBeenCalled();+ expect(grid).toHaveAttribute('aria-pressed', 'false');+ expect(grid).not.toHaveAttribute('aria-busy', 'true');++ const acceptedProps =+ type === 'single'+ ? {type, value: 'grid', onChange}+ : {type, value: ['list', 'grid'], onChange};+ rerender(+ <ToggleButtonGroup {...acceptedProps} label="View">+ {children}+ </ToggleButtonGroup>,+ );+ expect(grid).toHaveAttribute('aria-pressed', 'true');+ await userEvent.setup().click(grid);+ expect(onChange).toHaveBeenLastCalledWith(+ type === 'single' ? null : ['list'],+ );+ expect(onPressedChange).not.toHaveBeenCalled();+ expect(pressedChangeAction).not.toHaveBeenCalled();+ });+ },+);+// =============================================================================// Disabled state — family:buttons FR3 (disabled means non-operable)// =============================================================================diff --git a/packages/core/src/ToggleButton/ToggleButton.tsx b/packages/core/src/ToggleButton/ToggleButton.tsxindex 2972f3ebfd..d1d579b5af 100644--- a/packages/core/src/ToggleButton/ToggleButton.tsx+++ b/packages/core/src/ToggleButton/ToggleButton.tsx@@ -9,7 +9,7 @@* @position Thin wrapper over Button; adds controlled toggle pattern** ToggleButton wraps Button with `isPressed` and adds:- * - `onPressedChange` controlled toggle callback+ * - `onPressedChange` from internal `onClick`; `pressedChangeAction` via Button* - `pressedIcon` for outline-to-filled icon swap* - Font weight shift on press with width reservation to prevent layout shift* - Group integration via ToggleButtonGroupContext@@ -116,10 +116,12 @@ export interface ToggleButtonProps extends BaseProps<HTMLButtonElement> {) => void;/**- * Action handler for API- or navigation-backed toggles, run inside a- * transition by Button. The button shows a loading spinner while the action- * is pending — whether it returns a promise or synchronously triggers a- * suspending update (e.g. a router navigation that suspends on data).+ * Action handler for API- or navigation-backed toggles, run through Button's+ * clickAction transition after onPressedChange unless that callback prevents+ * default. It also runs without a callback. Omit it for callback-only toggles+ * that need no Action transition. The button shows a loading spinner while+ * the action is pending, including synchronous actions that suspend.+ * Ignored when a value identifies this button as a ToggleButtonGroup member.** @example* ```@@ -272,52 +274,36 @@ export function ToggleButton({// (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 update- // is applied inside Button's clickAction transition (below), satisfying- // React's "useOptimistic must run in a transition" rule.const [optimisticPressed, setOptimisticPressed] =useOptimistic(committedPressed);const isPressed = optimisticPressed;-- // Next state derives from the *optimistic* value, not the committed one, so a- // re-click while an action is pending reads the in-flight intent and toggles- // (true -> false -> true) rather than recomputing from the stale committed- // state. handleClick and clickAction share this so the callback and the- // optimistic update always agree within a single click.+ // Both paths use the same in-flight intent, so re-clicks reverse a pending+ // toggle rather than deriving from the stale controlled value.const nextPressed = !isPressed;-const resolvedIcon = isPressed && pressedIcon ? pressedIcon : icon;- // Synchronous part of the toggle. Button calls onClick before clickAction and- // skips clickAction when the event is defaultPrevented, so calling- // preventDefault() inside onPressedChange opts out of pressedChangeAction.const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {if (isDisabled) {return;}if (group && value != null) {- // Group mode delegates selection to the group; no async-action path.group.toggle(value);event.preventDefault();return;}+onPressedChangeProp?.(nextPressed, event);};- // Async part of the toggle, run inside Button's transition (so the optimistic- // update is valid and Button's isPending drives the pending spinner). Skipped- // automatically by Button when handleClick called preventDefault, and never- // wired in group mode (where there is no async action). Button is rendered- // interruptible, so it stays clickable while pending and a re-click starts a- // fresh transition that interrupts the previous one.+ // Button runs onClick first and skips clickAction when the callback prevents+ // default. Its transition owns both the optimistic update and pending UI.const clickAction =- group && value != null- ? undefined- : async () => {+ pressedChangeAction && !(group && value != null)+ ? async () => {setOptimisticPressed(nextPressed);- await pressedChangeAction?.(nextPressed);- };+ await pressedChangeAction(nextPressed);+ }+ : undefined;// isIconOnly prop is the source of truth for icon-only rendering.const labelContent =diff --git a/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs b/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjsindex 61742a592f..9819c88a41 100644--- a/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs+++ b/packages/core/src/ToggleButton/ToggleButtonGroup.doc.mjs@@ -11,7 +11,7 @@ export const docs = {{name: 'children',type: 'ReactNode',- description: 'ToggleButton children.',+ description: 'ToggleButton children. Give each member a value; the group owns its pressed state and ignores its isPressed, onPressedChange, and pressedChangeAction props. Member activation calls the group’s onChange without starting a member Action transition.',required: true,slotElements: [{@@ -83,7 +83,7 @@ export const docsZh = {displayName: 'Toggle Button Group',description: '将切换按钮分组,支持单选或多选行为。通过 type 判别联合类型实现类型安全。',propDescriptions: {- children: 'ToggleButton 子元素。',+ children: 'ToggleButton 子元素;每个成员都需要 value。分组控制按下状态,并忽略成员的 isPressed、onPressedChange 和 pressedChangeAction。激活成员只调用分组的 onChange,不启动成员的 Action 过渡。',label: '分组的无障碍标签 (aria-label)。',type: '选择模式。single 允许单个激活,multiple 允许多个。',value: '当前选中的值。类型取决于选择模式。',@@ -101,7 +101,7 @@ export const docsDense = {displayName: 'Toggle Button Group',description: 'groups toggle btns for exclusive/multi-select; discriminated union on type',propDescriptions: {- children: 'ToggleButton children',+ children: 'ToggleButton children; each member needs a value. Group owns pressed state; member isPressed/onPressedChange/pressedChangeAction are ignored. Selection uses group onChange, with no member Action transition.',label: 'a11y label (aria-label)',type: 'selection mode: single or multiple',value: 'selected value(s); type depends on mode',