Skip to content

OnOffSwitch

OnOffSwitch (from scenerystack/sun) is a sliding switch bound to a Property<boolean> — off on the left, on on the right, styled like iOS's UISwitch. It's a thin subclass of the more general ToggleSwitch<T> with leftValue/rightValue fixed to false/true. scenerystack/sun gives you three different affordances for the exact same "toggle a boolean" pattern, and they read differently to users:

ComponentReads asTypical use
CheckboxA labeled option to enable/disableA settings list, "Show velocity vectors"
BooleanRectangularToggleButtonA momentary-feeling control with two icon statesPlay/pause, mute/unmute
OnOffSwitchA physical on/off switchA single prominent power/enable toggle, sound on/off
ts
import { OnOffSwitch } from 'scenerystack/sun';
import { BooleanProperty } from 'scenerystack/axon';
import { Tandem } from 'scenerystack/tandem';

const soundEnabledProperty = new BooleanProperty( true );

const soundSwitch = new OnOffSwitch( soundEnabledProperty, {
  tandem: Tandem.REQUIRED
} );

Unlike Checkbox, OnOffSwitch has no separate label argument — pair it with your own Text (or an HBox/AlignBox layout) if you need one, and use accessibleName for the accessible label.

Interaction

OnOffSwitch (via its ToggleSwitch base) supports both click-to-toggle and drag-to-set: clicking anywhere on the switch toggles the value; dragging the thumb past the track's midpoint and releasing snaps it to whichever side it's closest to; dragging the thumb far enough outside the track toggles the value immediately, even before release.

Options

OptionDefaultEffect
size60 x 30Dimension2 for the switch; use 2 x height for width if you want a circular thumb
trackFillLeft'white'Track fill when the Property is false (off)
trackFillRight'rgb( 0, 200, 0 )'Track fill when the Property is true (on)
thumbFill / thumbStrokecomputed gradient / 'black'Thumb appearance
toggleWhileDraggingnullnull: iOS-style (change on far drag); true: change as soon as thumb crosses center; false: only change on release
thumbTouchAreaXDilation / thumbTouchAreaYDilation8 / 8Expand the thumb's touch hit area
accessibleSwitchtrueAdds role="switch" and aria-checked PDOM semantics; set false if you need non-boolean-style ARIA

OnOffSwitch requires reference-equality Properties

Both OnOffSwitch and its ToggleSwitch base assert that the bound Property's valueComparisonStrategy is 'reference' (the default for BooleanProperty) — they compare property.value against true/false with ===. If you've customized valueComparisonStrategy on the Property you're binding, OnOffSwitch will fail its assertion.