State button
An explicit state graph on a shared Button surface, with optimistic rollback, confirmation and three pending presentations.
npx @swipeui/cli add state-buttonWhen 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.tsand 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 installso versions match your SDK.
Usage
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
| Prop | Default | Behavior |
|---|---|---|
states | required | Nonempty graph of unique value, label, explicit next, optional icon, variant, tone, pendingLabel, failureLabel, confirm, after, accessibilityLabel. Omit next for a terminal state. |
value | uncontrolled | Controlled current state. Parent applies optimistic changes and rollback callbacks. |
defaultValue | first state | Initial uncontrolled state. |
onValueChange | none | Reports committed, optimistic, rollback and automatic changes. |
onTransition | none | (next, previous) => void or Promise<void>. Runs only on press transitions. |
onError | none | Latest failure callback, once after minimum pending time. |
optimistic | false | Apply the destination immediately; roll back on failure. |
pendingStyle | inline | Independent fold, inline or progress pending presentation. |
progress | 0 | Controlled determinate fraction, clamped to 0–1. Nonfinite becomes zero. |
minPending | 450 | Minimum pending visibility in milliseconds, including synchronous work. |
pendingLabel | Working | Pending text, overridden by the source state. Optimistic inline retains destination text. |
failureLabel | Try again | Failure text, overridden by the source state. |
failureDuration | 1800 | Milliseconds before failure feedback returns to rest. |
failureTone | destructive | Shared 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. |
shakeOnError | true | One short shake on failure, suppressed under Reduce Motion. |
retryOnPress | true | Retry the failed edge while error feedback shows. False blocks until expiry. |
confirmWindow | 3000 | Milliseconds to press again after a state's confirm label appears. |
iconMorph | true | Animate IconMorph geometry; false swaps endpoints. |
effects | true | IconMorph check draw, bell ring and other one-shots. |
labelMorph | true | Fade/rise new labels; false updates in place. Labels use one-line clip mode. |
animateWidth | true | Spring current-label width and folds independently of label arrival. |
reserveLabelWidth | false | Reserve the widest graph/feedback label. |
haptics | true | Boolean or { press, confirm, success, error }, each defaulting to true. |
variant | solid | Shared five Button styles and legacy aliases, overridable per state. |
tone | Button default | Shared primary, neutral, destructive or success tone, overridable per state. |
size | md | Shared sm / md / lg, with at least a 44pt touch target. |
shape | preset | Preset control corners or pill. Pending fold becomes circular. |
block | false | Fill the available width at rest. |
highlight | true | Shared solid Button top rim. |
glow | false | Shared solid Button tone glow. |
pressEffect | both | Shared scale, wash, both or none. |
disabledStyle | muted | Muted or dim explicit disabled appearance. |
disabled | false | Block activation and pause automatic advancement. |
motion | inherited | Shared press/morph/number/ambient roles; Reduce Motion keeps feedback and removes travel. |
accessibilityLabel | current label | Resting fallback name; per-state name takes precedence. Feedback uses its visible label. |
accessibilityHint | none | Additional spoken action context. |
hitSlop | sm vertical 4pt | Native touch expansion override. |
className | none | Shared surface classes merged on the pressable. |
style | none | Pressable native style escape hatch. |
textClassName | none | Label classes. |
testID | none | Pressable id; parts append -frame, -measure, -label, -icon, -failure-icon, -spinner, -progress, -wash, -highlight. |
State settings
| Setting | Default | Behavior |
|---|---|---|
value, label | required | Stable graph identity and visible resting text. |
next | terminal | Explicit destination. Missing destinations and duplicate values throw. |
icon | none | IconMorph name, { name, state } frame, node or { color, size } render function. Use an explicit frame for multistate graphs. |
variant, tone | inherited | State-specific shared Button surface and tone. |
pendingLabel, failureLabel | inherited | Feedback for work leaving this state. |
confirm.label | no confirmation | First press arms; second press within the window runs work. |
confirm.tone | destructive | Confirmation tone. |
after | off | Milliseconds before advancing to next without work or confirmation. Pauses while busy, failed, armed or disabled. |
accessibilityLabel | label | State'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,numberandambientmotion roles, so it follows your app's feel. Passmotionto 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 on | Supported |
|---|---|
| Expo SDK 57 | Yes |
| Expo SDK 58 | Yes |
| React Native CLI (with Expo modules) | Yes |
| Expo Go | Yes |
| iOS | Yes |
| Android | Yes |
This table describes API support and static bundle checks. Native runtime, device accessibility and bare Uniwind compatibility remain pending.