SwipeUI

Quantity button

A centered Add action that becomes an adjustable stepper with accelerating hold repeat and safe async rollback.

npx @swipeui/cli add quantity-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

  • Adjust a product quantity inline in a cart or product row.
  • Update cart quantities asynchronously with pending feedback and local rollback.

When not to use it

  • Free numeric entry or negative values; use Number field.
  • One action without a count; use Button.

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 quantity-button
  • Adds components/swipeui/ui/quantity-button.tsx, components/swipeui/ui/use-quantity-button.ts and 12 shared helpers.
  • Installs react-native-reanimated, uniwind, react-native-worklets, clsx, tailwind-merge, expo-haptics, class-variance-authority. In Expo apps it uses npx expo install so versions match your SDK.

Usage

app/product.tsx
import { QuantityButton } from '@/components/swipeui/ui/quantity-button';

<QuantityButton max={3} onValueChange={updateCart} />;

Examples

The Checkout demo adjusts the quantity and line total for a pocket sketchbook. Use Limit to three to try a stock cap, Repeat while held to toggle hold gestures, and Cart sync to try a pending update. In Cart sync mode, Fail next update shows the rollback and retry behavior.

Tap Add to reveal minus, a count and plus. Hold either side to repeat with accelerating selection ticks. Release, cancellation, backgrounding, blur, disabling, unmounting, reaching a bound or starting asynchronous work ends that hold session. Async work requires a fresh press after settlement.

Settings

Repeat clocks and feedback lifetimes are content timing in milliseconds, separate from motion feel. Repeat/failure durations must be finite and positive; minPending may be zero. repeatMinInterval cannot exceed repeatInterval. Bounds are finite, nonnegative and at most Number.MAX_SAFE_INTEGER; step is at least 0.0000000001. Changes round to ten decimal places and clamp the final partial step to a bound. Nonfinite input values fall back to min.

SettingDefaultBehavior
valueabsentControlled authoritative quantity.
defaultValue0Initial uncontrolled value, clamped to bounds.
onValueChangeabsentOne persistence request per accepted update; may return a promise. Rollback never invokes it again.
min0Inclusive lower bound; only zero displays Add.
max99Inclusive upper bound; increment disables at this value.
step1Positive increment/decrement; fractional and partial final steps are supported.
addLabelAddVisible resting label.
addIconabsentButton icon node or { color, size } render function, centered with the visible label.
decrementIconabsentOptional Button icon node/render function for the decrement action; the checkout supplies trash at one and minus above one.
decrementLabelDecrease quantitySpoken name for the real decrement button and adjustable decrement action.
compactfalseUse a 28pt visible surface within 44pt touch frames; text size still follows size. The checkout pairs this with sm and the short Retry failure label.
repeatOnHoldtrueEnable held repeats independently of press feedback.
repeatDelay400Delay before the first held change.
repeatInterval180Initial interval between held changes.
repeatMinInterval60Fastest held interval.
repeatAcceleration0.8Multiply the interval after each tick; 1 keeps a constant pace.
minPending450Minimum visible pending ring duration.
failureDuration1800Failure label lifetime; the rolled-back count then returns.
failureLabelTry againOn-control failure text. A subsequent explicit press starts a new bounded update.
onErrorabsentLatest relevant failure callback; stale/unmounted settlements are ignored.
limitFeedbacktrueWarning notification once when an accepted update reaches max. Increment stays disabled when off.
shakeOnErrortrueOne short failure shake; suppressed with Reduce Motion.
animateWidthtrueMorph-role width spring between Add and the stepper.
controlsMotiontrueSide-control arrivals on the morph role.
countMotiontrueSlotText rolling digits; false updates in place.
hapticstrueGlobal feedback or { press, repeat, limit, error } switches.
haptics.presstrueImpact for accepted taps.
haptics.repeattrueSelection tick for accepted held changes.
haptics.limittrueWarning when max is reached, also gated by limitFeedback.
haptics.errortrueError notification when work fails.
variantsolidShared Button solid/tinted/outline/ghost/plain surfaces and legacy aliases. Failure uses tinted destructive feedback.
tonefrom variantShared primary/neutral/destructive/success palette.
sizemdShared sm/md/lg sizes; side targets remain at least 44pt.
shapepresetPreset corners or explicit pill.
highlighttrueShared solid-surface top rim.
glowfalseShared solid-surface glow.
pressEffectbothShared both/scale/wash/none feedback on Add and the real side controls.
disabledfalsePrevent mutations and stop repeating.
disabledStylemutedShared muted/dim unavailable treatment.
motionapp feelPress, morph, number and ambient roles. Reduce Motion removes travel and retains readable feedback.
accessibilityLabelAdd to cartResting button name; active adjustable name is Quantity.
accessibilityHintabsentOptional instructions; bounded side controls explain their limit.
classNameabsentOuter footprint classes.
styleabsentNative outer layout override.
textClassNameabsentLabel/count classes.
testIDabsentRoot identifier; parts append add/minus/plus/count/spinner/failure and geometry suffixes.

Controlled and asynchronous updates

Return the cart mutation promise from onValueChange. The requested quantity appears optimistically while ButtonSpinner occupies the count region. Another tap, hold or accessibility action cannot overlap that mutation. Success commits uncontrolled state and announces once. Failure restores the previous value locally, shows the failure label and announces once; it never sends a compensating server request.

With controlled value, commit the authoritative value in the parent after persistence succeeds. If the parent echoes the requested value optimistically, the component can still display the previous value on failure without invoking onValueChange again. The parent owns persistent state reconciliation. An unrelated owner value invalidates old UI settlement; the mutation lock remains until the old request settles, so a replacement update cannot overlap it. Neither an external value change nor unmount aborts the caller's underlying server work.

The Add icon/label group centers at its actual visible width. The count reserves a separate footprint, then centers digits, the ring or failure text inside it. Hidden reservations do not become part of the visible group.

Accessibility and motion

Add is a named button. The count is an adjustable element with its current value, bounds and increment/decrement actions. Named real Increase quantity and Decrease quantity buttons sit beside it, so holding is optional and the adjustable element does not swallow the gesture alternatives. Pending is busy, and side controls are disabled. Changes announce once when committed; failures announce the restored quantity. RTL mirrors the control order. Text can grow without a fixed-height count box.

Native runtime, VoiceOver/TalkBack, Dynamic Type, RTL, haptics, device motion/performance and recordings remain pending founder device review in milestone 7.9. Earlier reviews and release gate 15 remain open.

API reference

QuantityButtonProps

PropTypeDefaultDescription
motion?MotionOverridethe app's feel (`smooth` without a provider)

The app's press character, or a local override. The app's motion feel, or a local override for the press, label and width springs.

variant?ButtonVariant'solid'

How much the button stands out: solid, tinted (a soft wash of the tone), outline, ghost (no fill until pressed) or plain (text only). The 1.x names default, secondary and destructive still work as solid primary, neutral and destructive.

tone?ButtonTone'primary' for solid, tinted and plain; 'neutral' for outline and ghost

The colour family: primary, neutral, destructive or success.

size?ButtonSize'md'

The height: sm 36pt (with a 44pt touch target), md 44pt, lg 52pt.

shape?ButtonShape'preset'

preset follows your preset's control radius; pill is a capsule.

highlight?booleantrue

A faint rim of light along the top edge of solid buttons.

glow?booleanfalse

A soft shadow in the tone's colour under solid buttons.

pressEffect?ButtonPressEffect'both'

Feedback while pressed: both scales and washes the surface, scale, wash or none. Text-only buttons dim their label instead of washing.

disabledStyle?ButtonDisabledStyle'muted'

How a disabled button looks: muted mutes its fill and label; dim halves its opacity.

className?string—

Classes merged over the style.

textClassName?string—

Classes for the label text.

style?StyleProp<ViewStyle>—

Style escape hatch for the container.

value?numberundefined

Controlled quantity; accept successful requests in the parent.

defaultValue?number0

Initial uncontrolled quantity, clamped to bounds.

onValueChange?((value: number) => void | Promise<void>)undefined

One persistence request per accepted user update. Return a promise for pending/rollback. Rollback never calls this again.

min?number0

Inclusive nonnegative lower bound; zero is the Add state.

max?number99

Inclusive finite upper bound, at most MAX_SAFE_INTEGER.

step?number1

Finite increment of at least 1e-10, rounded to ten decimal places.

addLabel?string'Add'

Resting text.

addIcon?ButtonIconundefined

Optional node or Button icon render function; centered with the current label.

decrementIcon?ButtonIconundefined

Optional replacement for the decrement mark; caller can show a trash icon for the last item.

decrementLabel?string'Decrease quantity'

Spoken name for the real decrement control and its accessibility action.

compact?booleanfalse

Compact 28pt visible surface within 44pt touch frames; text still follows size.

repeatOnHold?booleantrue

Enable repeating independently of press feedback.

repeatDelay?number400

Milliseconds before the first held update; content timing.

repeatInterval?number180

Initial milliseconds between repeats; content timing.

repeatMinInterval?number60

Fastest interval in milliseconds; content timing.

repeatAcceleration?number0.8

Interval multiplier after each repeat, in (0, 1]; 1 disables acceleration.

minPending?number450

Minimum visible asynchronous pending time in milliseconds.

failureDuration?number1800

Failure feedback lifetime in milliseconds.

failureLabel?string'Try again'

Text on the failed control; next minus/plus tap requests its own change.

onError?((error: unknown) => void)undefined

Latest relevant failure; stale/unmounted work does not call it.

limitFeedback?booleantrue

Warning haptic when an accepted update reaches max; increment remains disabled when off.

shakeOnError?booleantrue

One failure shake; Reduce Motion suppresses travel.

animateWidth?booleantrue

Spring Add/stepper width on the morph role.

controlsMotion?booleantrue

Animate arriving side controls on the morph role.

countMotion?booleantrue

Roll count changes with SlotText; false updates in place.

haptics?boolean | QuantityButtonHapticstrue

Global or independent press/repeat/limit/error feedback.

Behavior and gestures

  • Add becomes minus, count and plus; returning to zero restores Add.
  • Holding a side control repeats after repeatDelay and accelerates down to repeatMinInterval. Lift, cancellation, background, blur, disabling, unmount, bounds and async work stop the session.
  • Each accepted update invokes onValueChange once. Promise work locks all mutations until settlement and minimum pending visibility. Failure rolls back locally without invoking persistence again.
  • Increment is disabled at max; optional warning feedback happens once when max is reached.

Accessibility

  • Add is a named button. The count exposes adjustable semantics, numeric bounds/current value and increment/decrement accessibility actions.
  • Named real minus/plus controls remain independent siblings of the adjustable count, providing alternatives to hold. Busy and disabled state block duplicate actions.
  • Committed changes and failures are announced once. Pending preview values are not separately announced. Native assistive technology evidence remains pending for 7.9.
  • Side controls have at least 44pt targets. Logical order mirrors in RTL and count geometry grows for text.

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; morph-role width spring and side arrivals. SlotText rolls the count and ButtonSpinner occupies the same centered slot.
  • Reduce Motion removes width/side/shake travel and count rolling, retaining fading readable pending/error feedback. Repeat clocks are content timing, independent of motion.

Performance

  • JavaScript refs own serial mutations and repeat state; worklets capture only primitives/shared values, never CSS easing objects.
  • No immediate JavaScript shared-value readback. Timers/listeners clean up on unmount; use-async-action prevents stale settlement.
  • No new dependency, telemetry, network service or proprietary source.

Notes for AI

  • Return a promise for asynchronous cart persistence. Rollback is local UI state, never a second onValueChange call.
  • Controlled owners should commit the authoritative quantity when persistence succeeds. Pending shows the requested quantity; an optimistic owner echo is rolled back locally on failure. Unrelated owner changes invalidate old visual settlement but keep the mutation lock until underlying work settles.
  • Use repeatOnHold, repeatDelay, repeatInterval, repeatMinInterval and repeatAcceleration independently of motion.
  • Use independent limitFeedback, shakeOnError, animateWidth, controlsMotion, countMotion and per-feature haptics switches.
  • Bounds are finite and nonnegative, step is at least 1e-10 and results round to ten decimals; max is at most MAX_SAFE_INTEGER. Caller owns server cancellation and reconciliation.
  • Native accessibility, haptics, motion and recordings require actual device evidence; pending founder review / 7.9.
  • Checkout specimens start at one with caller-supplied decrementIcon/decrementLabel showing a trash action for the last item. The Checkout demo turns repeat off while Cart sync is enabled.
  • compact=true renders a 28pt visual surface inside 44pt touch frames. Pair size=sm with a short failureLabel for a compact checkout row.

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