Repository navigation
fix(ToggleButton): run pressedChangeAction in a transition for pending state #3056
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cixzhang
merged 3 commits into
main
from
navi/fix/togglebutton-pressedchangeaction-transition
Jun 25, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
54c0c4a
fix(ToggleButton): run pressedChangeAction in a transition for pendin…
cixzhang c628f63
fix(ToggleButton): make pressedChangeAction interruptible with optimi…
cixzhang 5f5fe87
chore(ToggleButton): drop comments that restate self-explanatory code
cixzhang File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| --- | ||
| '@astryxdesign/core': patch | ||
| --- | ||
|
|
||
| [fix] ToggleButton runs pressedChangeAction in an interruptible transition with optimistic state | ||
| @cixzhang | ||
|
|
||
| `pressedChangeAction` was fired as a non-awaited promise, so the documented | ||
| loading spinner never appeared and the toggle ignored the action's lifecycle. | ||
| It now runs inside a transition with an optimistic pressed state, matching | ||
| `Switch`: | ||
|
|
||
| - The optimistic pressed state flips immediately on click; the spinner is | ||
| debounced so a fast action shows the new state without a spinner flash. | ||
| - The action is interruptible — clicking again while it is pending starts a | ||
| new transition with the next optimistic state (e.g. true -> false -> true), | ||
| instead of being dropped or guarded out. | ||
| - Synchronous handlers are supported too: a `pressedChangeAction` (or | ||
| `onPressedChange`) that synchronously triggers a suspending update, such as | ||
| a router navigation that suspends on data, also drives the pending state. | ||
| `pressedChangeAction` now accepts `void | Promise<void>`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,7 +20,14 @@ | |
| * - /packages/cli/templates/blocks/components/ToggleButton/ (showcase blocks) | ||
| */ | ||
|
|
||
| import React, {useCallback, type ReactNode} from 'react'; | ||
| import React, { | ||
| useCallback, | ||
| useEffect, | ||
| useOptimistic, | ||
| useState, | ||
| useTransition, | ||
| type ReactNode, | ||
| } from 'react'; | ||
| import * as stylex from '@stylexjs/stylex'; | ||
| import {colorVars, fontWeightVars} from '../theme/tokens.stylex'; | ||
|
|
||
|
|
@@ -29,6 +36,37 @@ import {useToggleButtonGroup} from './ToggleButtonGroup'; | |
| import type {BaseProps} from '../BaseProps'; | ||
| import {xdsThemeProps} from '../utils/xdsThemeProps'; | ||
|
|
||
| // ============================================================================= | ||
| // 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 | ||
| // ============================================================================= | ||
|
|
@@ -91,8 +129,15 @@ export interface ToggleButtonProps extends BaseProps<HTMLButtonElement> { | |
| onPressedChange?: (isPressed: boolean) => void; | ||
|
|
||
| /** | ||
| * Async action handler for API-backed toggles. | ||
| * The button shows a loading spinner while the promise is pending. | ||
| * 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 | ||
| * 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 | ||
| * ``` | ||
|
|
@@ -106,7 +151,7 @@ export interface ToggleButtonProps extends BaseProps<HTMLButtonElement> { | |
| * /> | ||
| * ``` | ||
| */ | ||
| pressedChangeAction?: (isPressed: boolean) => Promise<void>; | ||
| pressedChangeAction?: (isPressed: boolean) => void | Promise<void>; | ||
|
|
||
| /** | ||
| * The size of the toggle button. | ||
|
|
@@ -218,46 +263,64 @@ export function ToggleButton({ | |
| style, | ||
| ...props | ||
| }: ToggleButtonProps): ReactNode { | ||
| // Read group context if inside a group | ||
| const group = useToggleButtonGroup(); | ||
|
|
||
| // Resolve state from group or props | ||
| const isPressed = | ||
| const committedPressed = | ||
| group && value != null | ||
| ? group.selectedValues.has(value) | ||
| : (isPressedProp ?? false); | ||
| 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. | ||
| const [optimisticPressed, setOptimisticPressed] = | ||
| useOptimistic(committedPressed); | ||
| const isPressed = optimisticPressed; | ||
|
|
||
| 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); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ideally this is delayed with a css |
||
| const isLoadingState = isLoading || showSpinner; | ||
|
|
||
| const handleClick = useCallback(() => { | ||
| if (isDisabled || isLoading) { | ||
| if (isDisabled) { | ||
| return; | ||
| } | ||
|
|
||
| if (group && value != null) { | ||
| // Delegate to group context | ||
| // Group mode delegates selection to the group; no async-action path. | ||
| group.toggle(value); | ||
| } else if (onPressedChangeProp) { | ||
| // Standalone toggle | ||
| const newState = !isPressed; | ||
| onPressedChangeProp(newState); | ||
| if (pressedChangeAction) { | ||
| void pressedChangeAction(newState); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| const newState = !optimisticPressed; | ||
| startTransition(async () => { | ||
| setOptimisticPressed(newState); | ||
| onPressedChangeProp?.(newState); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you could consider passing the event here, which allows calling |
||
| await pressedChangeAction?.(newState); | ||
| }); | ||
| }, [ | ||
| isDisabled, | ||
| isLoading, | ||
| group, | ||
| value, | ||
| optimisticPressed, | ||
| onPressedChangeProp, | ||
| pressedChangeAction, | ||
| isPressed, | ||
| setOptimisticPressed, | ||
| ]); | ||
|
|
||
| // Label with font weight shift and width reservation | ||
| // isIconOnly prop is the source of truth for icon-only rendering. | ||
| const labelContent = | ||
| children != null ? ( | ||
|
|
@@ -289,7 +352,7 @@ export function ToggleButton({ | |
| variant="ghost" | ||
| size={size} | ||
| isDisabled={isDisabled} | ||
| isLoading={isLoading} | ||
| isLoading={isLoadingState} | ||
| isIconOnly={isIconOnly} | ||
| aria-pressed={isPressed} | ||
| icon={resolvedIcon} | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's another option here, which has trade offs to consider: you can use the isomorphic start transition and check isPending with:
The subtle tradeoffs are that errors thrown inside
actionwill not re-throw from isomorphicstartTransitionbut will re-throw foruseTransitionwhich may or may not be the behavior you want.Also, by using the optimistic state for
isPending, if the user clicks false -> true -> false, then when it's back to the original value optimistically thenisPendingis back to false. Which may or may not be what you want.