SwipeUI

State button

An explicit state graph on a shared Button surface, with optimistic rollback, confirmation and three pending presentations.

npx @swipeui/cli add state-button
Variant
Preset
Material
Scheme
Feel
Real free component with a browser animation bridge. Native motion, haptics and materials need a device.

When to use it

  • One action moves through explicit states with different labels, tones or destinations.
  • Async work needs pending, retry and optional optimistic feedback on the control.

When not to use it

  • Independent choices belong in Button group or Menu.
  • A destructive action needs split confirmation or undo; use Confirm morph.

Installation

Run this from your app's root. If SwipeUI isn't set up yet, run npx @swipeui/cli init first; it sets up Uniwind, the theme tokens and the cn helper.

npx @swipeui/cli add state-button
  • Adds components/swipeui/ui/state-button.tsx, components/swipeui/ui/use-state-button.ts and 12 shared helpers.
  • Installs react-native-reanimated, uniwind, react-native-worklets, clsx, tailwind-merge, expo-haptics, class-variance-authority, react-native-svg. In Expo apps it uses npx expo install so versions match your SDK.

Usage

app/follow.tsx
import { StateButton } from '@/components/swipeui/ui/state-button';

<StateButton
  optimistic
  onTransition={updateFollow}
  states={[
    { value: 'off', label: 'Follow', next: 'on', icon: { name: 'plus-check', state: false } },
    {
      value: 'on', label: 'Following', next: 'off', tone: 'success',
      icon: { name: 'plus-check', state: true },
      confirm: { label: 'Unfollow?', tone: 'destructive' },
    },
  ]}
/>

The follow, save, upload and cycle boards are the same specimen in the app and browser preview. Failure and behavior controls sit outside the action. Save compares fold and inline pending; upload shows a determinate fill.

Settings

PropDefaultBehavior
statesrequiredNonempty graph of unique value, label, explicit next, optional icon, variant, tone, pendingLabel, failureLabel, confirm, after, accessibilityLabel. Omit next for a terminal state.
valueuncontrolledControlled current state. Parent applies optimistic changes and rollback callbacks.
defaultValuefirst stateInitial uncontrolled state.
onValueChangenoneReports committed, optimistic, rollback and automatic changes.
onTransitionnone(next, previous) => void or Promise<void>. Runs only on press transitions.
onErrornoneLatest failure callback, once after minimum pending time.
optimisticfalseApply the destination immediately; roll back on failure.
pendingStyleinlineIndependent fold, inline or progress pending presentation.
progress0Controlled determinate fraction, clamped to 0–1. Nonfinite becomes zero.
minPending450Minimum pending visibility in milliseconds, including synchronous work.
pendingLabelWorkingPending text, overridden by the source state. Optimistic inline retains destination text.
failureLabelTry againFailure text, overridden by the source state.
failureDuration1800Milliseconds before failure feedback returns to rest.
failureTonedestructiveShared tinted Button tone during failure: red text and a soft red surface by default, matching Unfollow confirmation. A circle-X replaces the state icon until retry/reset.
shakeOnErrortrueOne short shake on failure, suppressed under Reduce Motion.
retryOnPresstrueRetry the failed edge while error feedback shows. False blocks until expiry.
confirmWindow3000Milliseconds to press again after a state's confirm label appears.
iconMorphtrueAnimate IconMorph geometry; false swaps endpoints.
effectstrueIconMorph check draw, bell ring and other one-shots.
labelMorphtrueFade/rise new labels; false updates in place. Labels use one-line clip mode.
animateWidthtrueSpring current-label width and folds independently of label arrival.
reserveLabelWidthfalseReserve the widest graph/feedback label.
hapticstrueBoolean or { press, confirm, success, error }, each defaulting to true.
variantsolidShared five Button styles and legacy aliases, overridable per state.
toneButton defaultShared primary, neutral, destructive or success tone, overridable per state.
sizemdShared sm / md / lg, with at least a 44pt touch target.
shapepresetPreset control corners or pill. Pending fold becomes circular.
blockfalseFill the available width at rest.
highlighttrueShared solid Button top rim.
glowfalseShared solid Button tone glow.
pressEffectbothShared scale, wash, both or none.
disabledStylemutedMuted or dim explicit disabled appearance.
disabledfalseBlock activation and pause automatic advancement.
motioninheritedShared press/morph/number/ambient roles; Reduce Motion keeps feedback and removes travel.
accessibilityLabelcurrent labelResting fallback name; per-state name takes precedence. Feedback uses its visible label.
accessibilityHintnoneAdditional spoken action context.
hitSlopsm vertical 4ptNative touch expansion override.
classNamenoneShared surface classes merged on the pressable.
stylenonePressable native style escape hatch.
textClassNamenoneLabel classes.
testIDnonePressable id; parts append -frame, -measure, -label, -icon, -failure-icon, -spinner, -progress, -wash, -highlight.

State settings

SettingDefaultBehavior
value, labelrequiredStable graph identity and visible resting text.
nextterminalExplicit destination. Missing destinations and duplicate values throw.
iconnoneIconMorph name, { name, state } frame, node or { color, size } render function. Use an explicit frame for multistate graphs.
variant, toneinheritedState-specific shared Button surface and tone.
pendingLabel, failureLabelinheritedFeedback for work leaving this state.
confirm.labelno confirmationFirst press arms; second press within the window runs work.
confirm.tonedestructiveConfirmation tone.
afteroffMilliseconds before advancing to next without work or confirmation. Pauses while busy, failed, armed or disabled.
accessibilityLabellabelState's resting spoken name.

Composition and behavior

onTransition(next, previous) performs the operation. The shared async engine holds pending feedback for minPending, ignores stale settlements and cancels UI timers on unmount. Pending blocks additional presses. Failure keeps the original edge for retry, including after an optimistic rollback; an already accepted confirmation is retained for that retry.

An after edge is presentation timing: Saved can return to Save without saving again. It does not call onTransition or require confirmation. Timers use primitive state settings so parent rerenders do not extend them. Use onValueChange to observe automatic advancement. Changing controlled value externally invalidates obsolete pending settlement; the caller owns cancellation of underlying work.

Two-state graphs expose a toggle's checked state relative to the first state; larger graphs expose an ordinary button. Busy and disabled semantics, named confirmation/failure steps and once-only announcements stay on the action. Progress reports its value and announces new 25% milestones. The progress fill starts on the right in RTL. Reduce Motion holds the resting width while the fold cross-fades to a still spinner, removes shake and switches progress without interpolation.

Review VoiceOver/TalkBack, Dynamic Type, native RTL, haptics, motion and recordings on actual devices before release. These gates remain pending; unit and browser evidence cannot close them.

Behavior and gestures

  • Press follows the current next edge; pending blocks duplicate activation. Terminal states are inert.
  • Optimistic mode changes immediately and restores the source on failure. Retry repeats the failed edge. Failure uses the shared tinted destructive red and a dedicated circle-X icon, then restores the state icon on retry/reset.
  • Per-state confirmation requires another press within confirmWindow; expiry returns to rest.
  • after advances to next without running work or confirmation; disabled, pending, failure and confirmation pause it.
  • External controls in the shared specimen choose failure, optimistic mode and pending style.

Accessibility

  • Two states use togglebutton with checked; larger graphs use button with the current state name.
  • Pending reports busy and disabled; determinate progress exposes a percentage and announces new 25% milestones.
  • Names, confirmation and failure changes are announced once; labels remain single-line with clip mode.
  • Small controls expand their touch target to 44pt. VoiceOver, TalkBack, native large text, RTL and device feedback remain pending.

Motion

  • Uses the press, morph, number and ambient motion roles, so it follows your app's feel. Pass motion to tune this one instance.
  • Shared Button press feedback and morph-role label/width transitions.
  • Fold pending narrows without scaling content; IconMorph stays mounted while busy.
  • Reduce Motion removes shake, fold travel, progress interpolation and icon effects; short fades and haptics remain.

Performance

  • The shared async hook owns minimum-pending timing, stale-run rejection and unmount safety.
  • The state graph and press guards live in JavaScript refs/state; no immediate shared-value readback.
  • Progress and shake animated styles live in leaf components. Worklet closures capture primitives/shared values, never CSS easing objects.
  • Timers are cancelled on unmount, state changes and lifecycle changes.

Notes for AI

  • Give each state a unique value and an explicit next, except terminal nodes. All destinations must exist.
  • onTransition(next, previous) owns actual work. Automatic after changes are presentation-only.
  • Controlled owners must apply onValueChange for both optimistic destinations and rollback sources. External value changes cancel obsolete UI settlement, not underlying work.
  • Keep failure switches and other demonstration settings outside the control. Never add result lines.
  • Source and browser evidence do not establish native runtime or accessibility completion.

Compatibility

Runs onSupported
Expo SDK 57Yes
Expo SDK 58Yes
React Native CLI (with Expo modules)Yes
Expo GoYes
iOSYes
AndroidYes

This table describes API support and static bundle checks. Native runtime, device accessibility and bare Uniwind compatibility remain pending.

Related items