An open source design system that's fully customizable and agent ready
TypeScript
fix(ToggleButton): pass click event to onPressedChange for preventDefault opt-out (#3160)
Cindy Zhang080d887dfd11
diff --git a/.changeset/button-action-spinner-delay.md b/.changeset/button-action-spinner-delay.mdnew file mode 100644index 0000000000..b094ec3d37--- /dev/null+++ b/.changeset/button-action-spinner-delay.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Button: add `isInterruptible` to keep the button clickable while a `clickAction` is pending — the spinner and `aria-busy` still show, but the button is not disabled or deduped, so a re-click interrupts the in-flight action. ToggleButton's async toggle now runs through this path, staying interruptible.+@cixzhangdiff --git a/.changeset/togglebutton-onpressedchange-event.md b/.changeset/togglebutton-onpressedchange-event.mdnew file mode 100644index 0000000000..a124d26431--- /dev/null+++ b/.changeset/togglebutton-onpressedchange-event.md@@ -0,0 +1,13 @@+---+'@astryxdesign/core': patch+---++[fix] ToggleButton onPressedChange receives the click event for preventDefault opt-out+@cixzhang++`onPressedChange` now receives the originating click event as a second+argument. Calling `event.preventDefault()` skips `pressedChangeAction`, so a+consumer can handle the toggle entirely in `onPressedChange` without firing the+action — matching how `Switch`'s `onChange` and `Button`'s `onClick` already+gate their action props. Existing `(isPressed) => void` handlers keep working;+the event is an added trailing argument.diff --git a/packages/core/src/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjsindex ceb030e51c..e73382749c 100644--- a/packages/core/src/Button/Button.doc.mjs+++ b/packages/core/src/Button/Button.doc.mjs@@ -78,6 +78,12 @@ export const docs = {description: 'Shows a loading spinner and disables interaction. Announces "Loading" via a live region.',default: 'false',},+ {+ name: 'isInterruptible',+ type: 'boolean',+ description: 'Keep the button clickable while a clickAction is pending: the spinner and aria-busy still show, but the button is not disabled and the action is not deduped, so a re-click lands and interrupts the in-flight action with a fresh one.',+ default: 'false',+ },{name: 'isDisabled',type: 'boolean',diff --git a/packages/core/src/Button/Button.test.tsx b/packages/core/src/Button/Button.test.tsxindex 6b70636c5b..52829ca8ba 100644--- a/packages/core/src/Button/Button.test.tsx+++ b/packages/core/src/Button/Button.test.tsx@@ -71,6 +71,32 @@ describe('Button', () => {expect(button).toBeDisabled();});+ it('sets aria-busy synchronously while clickAction is pending', async () => {+ // The spinner reveal is visually delayed (CSS animation-delay), but the+ // loading DOM state — aria-busy and disabled — must not be delayed.+ const user = userEvent.setup();+ let resolveAction: (() => void) | undefined;+ const clickAction = vi.fn(+ async () =>+ new Promise<void>(resolve => {+ resolveAction = resolve;+ }),+ );+ render(<Button label="Save" clickAction={clickAction} />);+ const button = screen.getByRole('button');++ await user.click(button);+ expect(button).toHaveAttribute('aria-busy', 'true');+ expect(button).toBeDisabled();++ await act(async () => {+ resolveAction?.();+ await Promise.resolve();+ });+ expect(button).not.toHaveAttribute('aria-busy', 'true');+ expect(button).not.toBeDisabled();+ });+it('renders the loading spinner with the inherit shade for every variant (#2717)', () => {// The spinner must follow the button's resolved foreground color rather// than a hardcoded white, so it keeps contrast on themed variants like the@@ -273,6 +299,59 @@ describe('Button', () => {});});+ it('stays clickable (not disabled) while a clickAction is pending when isInterruptible', async () => {+ const user = userEvent.setup();+ let resolveAction: (() => void) | undefined;+ const clickAction = vi.fn(+ async () =>+ new Promise<void>(resolve => {+ resolveAction = resolve;+ }),+ );+ render(<Button label="Toggle" isInterruptible clickAction={clickAction} />);+ const button = screen.getByRole('button');++ await user.click(button);+ // Loading is announced via aria-busy, but the button is not disabled so it+ // can be re-clicked to interrupt the in-flight action.+ expect(button).toHaveAttribute('aria-busy', 'true');+ expect(button).not.toBeDisabled();++ await act(async () => {+ resolveAction?.();+ await Promise.resolve();+ });+ expect(button).not.toHaveAttribute('aria-busy', 'true');+ expect(button).not.toBeDisabled();+ });++ it('re-fires clickAction on re-click while pending when isInterruptible (no dedupe)', async () => {+ // Unlike the fire-once default, an interruptible action is not deduped: a+ // re-click while pending starts a fresh action that interrupts the prior.+ const resolvers: (() => void)[] = [];+ const clickAction = vi.fn(+ async () =>+ new Promise<void>(resolve => {+ resolvers.push(resolve);+ }),+ );+ render(<Button label="Toggle" isInterruptible clickAction={clickAction} />);++ const button = screen.getByRole('button');+ await act(async () => {+ fireEvent.click(button);+ });+ await act(async () => {+ fireEvent.click(button);+ });+ expect(clickAction).toHaveBeenCalledTimes(2);++ await act(async () => {+ resolvers.forEach(resolve => resolve());+ await Promise.resolve();+ });+ });+// type/name/value/form propsit('defaults type to button', () => {render(<Button label="Test" />);diff --git a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsxindex 83fcb86238..70874bb5c7 100644--- a/packages/core/src/Button/Button.tsx+++ b/packages/core/src/Button/Button.tsx@@ -15,7 +15,7 @@* - /apps/storybook/stories/Button.stories.tsx (storybook stories)* - /packages/cli/templates/blocks/components/Button/ (showcase blocks)*- * Last synced props: label, variant, size, isDisabled, isLoading, clickAction, icon, isIconOnly, children, tooltip, endContent, href, as, target, rel+ * Last synced props: label, variant, size, isDisabled, isLoading, isInterruptible, clickAction, icon, isIconOnly, children, tooltip, endContent, href, as, target, rel*/import {useRef, useTransition, type ReactNode} from 'react';@@ -320,6 +320,16 @@ export interface ButtonProps extends BaseProps<HTMLButtonElement> {* @default false*/isLoading?: boolean;+ /**+ * Keep the button interactive while a `clickAction` is pending. The loading+ * state still renders the spinner and `aria-busy`, but the button is not+ * disabled and the in-flight action is not deduped — so a re-click lands and+ * interrupts the previous action with a fresh one. Use for interruptible+ * actions (e.g. a toggle whose action can be re-triggered before the previous+ * one settles), not fire-once actions (submit/save/pay).+ * @default false+ */+ isInterruptible?: boolean;/*** Click handler. For async actions that should show a loading state,* use `clickAction` instead.@@ -380,6 +390,22 @@ export interface ButtonProps extends BaseProps<HTMLButtonElement> {rel?: string;}+const spinnerReveal = stylex.keyframes({+ from: {opacity: 0},+ to: {opacity: 1},+});++const contentHide = stylex.keyframes({+ from: {color: 'inherit'},+ to: {color: 'transparent'},+});++// Hold the loading swap for a short delay so a fast action (e.g. clickAction)+// that settles within the delay never flashes a spinner. The spinner fade-in+// and the content hide share the same delay so the button never shows an empty+// frame in between. Reduced motion is instant.+const SPINNER_DELAY = durationVars['--duration-medium-min'];+const loadingStyles = stylex.create({// Hide the button's own content while the spinner overlay is shown. Applied// to the content wrapper (not the button) so the button keeps its variant@@ -387,6 +413,17 @@ const loadingStyles = stylex.create({hiddenContent: {color: 'transparent',},+ // Delayed variant: keep content visible, then hide it in lockstep with the+ // spinner reveal once the delay elapses.+ hiddenContentDelayed: {+ animationName: contentHide,+ animationDuration: '1ms',+ animationFillMode: 'forwards',+ animationDelay: {+ default: SPINNER_DELAY,+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ },spinnerOverlay: {position: 'absolute',top: 0,@@ -396,6 +433,15 @@ const loadingStyles = stylex.create({display: 'grid',placeItems: 'center',},+ spinnerDelayed: {+ animationName: spinnerReveal,+ animationDuration: durationVars['--duration-fast'],+ animationFillMode: 'backwards',+ animationDelay: {+ default: SPINNER_DELAY,+ '@media (prefers-reduced-motion: reduce)': '0s',+ },+ },});const groupStyles = stylex.create({@@ -493,6 +539,7 @@ export function Button({type = 'button',isDisabled = false,isLoading = false,+ isInterruptible = false,clickAction,icon,isIconOnly = false,@@ -513,12 +560,23 @@ export function Button({const buttonGroup = useButtonGroup();const [isPending, startTransition] = useTransition();- // clickAction is fire-once (submit/save/pay), so a same-tick double-click must- // dedupe — which neither isPending nor useOptimistic do. Hence the ref guard.+ // clickAction is normally fire-once (submit/save/pay), so a same-tick+ // double-click must dedupe — which neither isPending nor useOptimistic do.+ // Hence the ref guard. Interruptible callers (e.g. ToggleButton) opt out so a+ // re-click can land and interrupt the in-flight action with a fresh one.const actionInFlightRef = useRef(false);const isLoadingState = isLoading || isPending;+ // Delay the spinner reveal for action-driven loading (clickAction's own+ // transition) so a fast action that settles within the delay does not flash+ // a spinner. Interruptible loading is delayed too, so rapid re-clicks settle+ // before any spinner shows. Explicit isLoading-only stays immediate, since+ // the consumer is deliberately showing it.+ const delaySpinner = isPending || isInterruptible;const groupDisabled = buttonGroup?.isDisabled ?? false;- const buttonDisabled = isDisabled || groupDisabled || isLoadingState;+ // When interruptible, the loading state drives the spinner and aria-busy but+ // not disabled, so clicks keep landing and can interrupt the in-flight action.+ const buttonDisabled =+ isDisabled || groupDisabled || (isLoadingState && !isInterruptible);// isIconOnly prop is the source of truth for icon-only rendering.// When false (default), label is always rendered as visible text.@@ -533,7 +591,9 @@ export function Button({const useAriaDisabled = tooltip != null && buttonDisabled;const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {- if (buttonDisabled || actionInFlightRef.current) {+ // The ref guard dedupes fire-once actions. Interruptible callers skip it so+ // a re-click while pending starts a fresh action that interrupts the prior.+ if (buttonDisabled || (actionInFlightRef.current && !isInterruptible)) {e.preventDefault();return;}@@ -600,7 +660,10 @@ export function Button({<>{isLoadingState && (<span- {...stylex.props(loadingStyles.spinnerOverlay)}+ {...stylex.props(+ loadingStyles.spinnerOverlay,+ delaySpinner && loadingStyles.spinnerDelayed,+ )}aria-hidden="true"><Spinner size="sm" shade="inherit" /></span>@@ -608,7 +671,10 @@ export function Button({<span{...stylex.props(styles.contentWrapper,- isLoadingState && loadingStyles.hiddenContent,+ isLoadingState &&+ (delaySpinner+ ? loadingStyles.hiddenContentDelayed+ : loadingStyles.hiddenContent),)}aria-hidden={isLoadingState || undefined}>{icon && (diff --git a/packages/core/src/ToggleButton/ToggleButton.doc.mjs b/packages/core/src/ToggleButton/ToggleButton.doc.mjsindex 42307ad956..ece4dc013e 100644--- a/packages/core/src/ToggleButton/ToggleButton.doc.mjs+++ b/packages/core/src/ToggleButton/ToggleButton.doc.mjs@@ -34,13 +34,13 @@ export const docs = {},{name: 'onPressedChange',- type: '(isPressed: boolean) => void',- description: 'Called when pressed state should change. Ignored when inside a group.',+ 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.',},{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 (debounced) spinner while pending; interruptible by re-clicks.',+ 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.',},{name: 'size',diff --git a/packages/core/src/ToggleButton/ToggleButton.test.tsx b/packages/core/src/ToggleButton/ToggleButton.test.tsxindex 7c683bb1fc..e9026ac40c 100644--- a/packages/core/src/ToggleButton/ToggleButton.test.tsx+++ b/packages/core/src/ToggleButton/ToggleButton.test.tsx@@ -9,9 +9,9 @@*/import {describe, it, expect, vi} from 'vitest';-import {render, screen, act, fireEvent, waitFor} from '@testing-library/react';+import {render, screen, act, fireEvent} from '@testing-library/react';import userEvent from '@testing-library/user-event';-import {useState} from 'react';+import {useState, type MouseEvent} from 'react';import {ToggleButton} from './ToggleButton';import {ToggleButtonGroup} from './ToggleButtonGroup';@@ -88,7 +88,7 @@ describe('ToggleButton', () => {);await user.click(screen.getByRole('button'));- expect(handleChange).toHaveBeenCalledWith(true);+ expect(handleChange).toHaveBeenCalledWith(true, expect.anything());});it('calls onPressedChange with false when clicking pressed button', async () => {@@ -103,7 +103,7 @@ describe('ToggleButton', () => {);await user.click(screen.getByRole('button'));- expect(handleChange).toHaveBeenCalledWith(false);+ expect(handleChange).toHaveBeenCalledWith(false, expect.anything());});it('renders pressedIcon when pressed', () => {@@ -193,7 +193,7 @@ describe('ToggleButton', () => {expect(screen.getByTestId('bold-toggle')).toBeInTheDocument();});- it('shows the optimistic pressed state immediately, before any spinner', async () => {+ it('shows the optimistic pressed state and stays interruptible while pending', async () => {const user = userEvent.setup();let resolveAction: (() => void) | undefined;const pressedChangeAction = vi.fn(@@ -217,12 +217,13 @@ describe('ToggleButton', () => {await user.click(button);- // The optimistic state flips immediately. The spinner is debounced, so the- // button is not disabled or aria-busy yet — it stays interruptible.+ // The optimistic state flips immediately and the spinner shows via+ // aria-busy, but the button is never disabled — it stays clickable so the+ // action can be interrupted by another click.expect(pressedChangeAction).toHaveBeenCalledWith(true);expect(button).toHaveAttribute('aria-pressed', 'true');+ expect(button).toHaveAttribute('aria-busy', 'true');expect(button).not.toBeDisabled();- expect(button).not.toHaveAttribute('aria-busy', 'true');// Settle the action so the pending transition doesn't leak into later tests.await act(async () => {@@ -231,7 +232,7 @@ describe('ToggleButton', () => {});});- it('shows a loading spinner once the action stays pending past the delay', async () => {+ it('clears the loading state once the action settles', async () => {const user = userEvent.setup();let resolveAction: (() => void) | undefined;const pressedChangeAction = vi.fn(@@ -253,18 +254,15 @@ describe('ToggleButton', () => {const button = screen.getByRole('button', {name: 'Favorite'});await user.click(button);- // The optimistic state shows immediately; the spinner is debounced and- // appears only after the action stays pending past the delay window.- expect(button).toHaveAttribute('aria-pressed', 'true');- await waitFor(() => expect(button).toBeDisabled());expect(button).toHaveAttribute('aria-busy', 'true');+ expect(button).not.toBeDisabled();await act(async () => {resolveAction?.();await Promise.resolve();});- expect(button).not.toBeDisabled();expect(button).not.toHaveAttribute('aria-busy', 'true');+ expect(button).not.toBeDisabled();});it('interrupts an in-flight action on re-click (true -> false -> true)', async () => {@@ -290,9 +288,8 @@ describe('ToggleButton', () => {const button = screen.getByRole('button', {name: 'Favorite'});// Each click derives the next state from the optimistic (in-progress)- // value, so rapid clicks toggle rather than being dropped. fireEvent keeps- // the clicks within the spinner debounce window so the button stays- // interruptible.+ // value, so rapid clicks toggle rather than being dropped. The button is+ // never disabled while pending, so every click lands and interrupts.await act(async () => {fireEvent.click(button);});@@ -335,9 +332,33 @@ describe('ToggleButton', () => {const button = screen.getByRole('button', {name: 'Favorite'});await user.click(button);- expect(onPressedChange).toHaveBeenCalledWith(true);+ expect(onPressedChange).toHaveBeenCalledWith(true, expect.anything());expect(pressedChangeAction).toHaveBeenCalledWith(true);});++ 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>) => {+ event.preventDefault();+ },+ );++ render(+ <ToggleButton+ label="Favorite"+ isPressed={false}+ onPressedChange={onPressedChange}+ pressedChangeAction={pressedChangeAction}+ />,+ );++ await user.click(screen.getByRole('button', {name: 'Favorite'}));++ expect(onPressedChange).toHaveBeenCalledWith(true, expect.anything());+ expect(pressedChangeAction).not.toHaveBeenCalled();+ });});// =============================================================================diff --git a/packages/core/src/ToggleButton/ToggleButton.tsx b/packages/core/src/ToggleButton/ToggleButton.tsxindex 473fa16fa2..a4f5ca2bb3 100644--- a/packages/core/src/ToggleButton/ToggleButton.tsx+++ b/packages/core/src/ToggleButton/ToggleButton.tsx@@ -20,14 +20,7 @@* - /packages/cli/templates/blocks/components/ToggleButton/ (showcase blocks)*/-import React, {- useCallback,- useEffect,- useOptimistic,- useState,- useTransition,- type ReactNode,-} from 'react';+import React, {useOptimistic, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars, fontWeightVars} from '../theme/tokens.stylex';@@ -36,37 +29,6 @@ import {useToggleButtonGroup} from './ToggleButtonGroup';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';-// =============================================================================-// Constants & helpers-// =============================================================================--/**- * The spinner only appears once the action has been pending for this long.- * A fast action shows the optimistic pressed state immediately with no spinner- * flash, and rapid re-clicks can interrupt the in-flight action before the- * button locks behind the spinner.- */-const PENDING_SPINNER_DELAY_MS = 150;--/**- * Returns `true` only once `active` has stayed `true` for `delayMs`.- * Used to debounce the loading spinner so the optimistic state shows first.- */-function useDelayed(active: boolean, delayMs: number): boolean {- const [delayed, setDelayed] = useState(false);- useEffect(() => {- if (!active) {- return undefined;- }- const timer = setTimeout(() => setDelayed(true), delayMs);- return () => {- clearTimeout(timer);- setDelayed(false);- };- }, [active, delayMs]);- return active && delayed;-}-// =============================================================================// Styles// =============================================================================@@ -122,23 +84,24 @@ export interface ToggleButtonProps extends BaseProps<HTMLButtonElement> {isPressed?: boolean;/**- * Called when the pressed state should change.+ * Called when the pressed state should change. Receives the next pressed+ * state and the originating click event. Call `event.preventDefault()` to+ * opt out of running `pressedChangeAction` (e.g. to handle the toggle+ * entirely in this callback).* When used inside ToggleButtonGroup, this is handled by the group* and this prop is ignored.*/- onPressedChange?: (isPressed: boolean) => void;+ onPressedChange?: (+ isPressed: boolean,+ event: React.MouseEvent<HTMLButtonElement>,+ ) => void;/*** Action handler for API- or navigation-backed toggles, run inside a- * transition. The button shows a loading spinner while the action is- * pending — whether it returns a promise or synchronously triggers 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).*- * Because it runs in a transition, the toggle is *interruptible*: clicking- * again while an action is pending starts a new transition with the next- * optimistic state, so the action reflects the latest intent rather than- * being dropped.- ** @example* ```* <ToggleButton@@ -272,54 +235,52 @@ export function ToggleButton({const size = sizeProp ?? group?.size ?? 'md';const isDisabled = group?.isDisabled ?? isDisabledProp;- // Track the pressed state optimistically. While an action is pending, the- // button reflects the intended (optimistic) state immediately, and a click- // mid-flight derives its next state from this value — so rapid toggles read- // true -> false -> true rather than stalling on the last committed value.+ // 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.+ const nextPressed = !isPressed;+const resolvedIcon = isPressed && pressedIcon ? pressedIcon : icon;- // Run the toggle inside a transition. The action is interruptible: clicking- // again while it is pending starts a fresh transition with the next- // optimistic state instead of being dropped, so there is no re-entry guard.- // Both onPressedChange and pressedChangeAction run inside the transition,- // which means a synchronous-but-suspending handler (e.g. a router navigation- // that suspends on data) also drives the pending state — not just promises.- const [isPending, startTransition] = useTransition();- // Debounce the spinner so a fast action shows the optimistic state without a- // spinner flash, and rapid re-clicks can interrupt before the button locks.- const showSpinner = useDelayed(isPending, PENDING_SPINNER_DELAY_MS);- const isLoadingState = isLoading || showSpinner;-- const handleClick = useCallback(() => {+ // 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;}-- const newState = !optimisticPressed;- startTransition(async () => {- setOptimisticPressed(newState);- onPressedChangeProp?.(newState);- await pressedChangeAction?.(newState);- });- }, [- isDisabled,- group,- value,- optimisticPressed,- onPressedChangeProp,- pressedChangeAction,- setOptimisticPressed,- ]);+ 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.+ const clickAction =+ group && value != null+ ? undefined+ : async () => {+ setOptimisticPressed(nextPressed);+ await pressedChangeAction?.(nextPressed);+ };// isIconOnly prop is the source of truth for icon-only rendering.const labelContent =@@ -352,7 +313,8 @@ export function ToggleButton({variant="ghost"size={size}isDisabled={isDisabled}- isLoading={isLoadingState}+ isLoading={isLoading}+ isInterruptibleisIconOnly={isIconOnly}aria-pressed={isPressed}icon={resolvedIcon}@@ -363,6 +325,7 @@ export function ToggleButton({xstyle={[isPressed ? pressedStyles.background : undefined, xstyle]}style={style}onClick={handleClick}+ clickAction={clickAction}{...props}>{labelContent}</Button>