Elements

Button

A button is a press target. It owns the behavior: presses, press feedback through the app’s state styles, the disabled and selected states, keyboard focus, and its role for screen readers. The look is the app’s: a Button has no colors, sizes, paddings or label of its own, so one component becomes a primary button, an icon button, a menu’s trigger or the row of a list, depending on the styles and children you give it.

el-button.tsx
el-button.tsxLive
import { mount, signal, Text, View } from "nsh";
import { Button, Switch, Toggle } from "nsh/base";
import { button, buttonText, desktop, Inspector, Panel, Stage, switchLook, toggleLabel, toggleLook, ui, wide } from "./palette";


function App() {
  const presses = signal(0);
  const pressing = signal(false);
  const disabled = signal(false);
  const bold = signal(true);
  const italic = signal(false);
  const last = signal("–");
  const label = () => ({ color: ui().text, fontSize: desktop ? 13 : 15, fontWeight: "600" as const });

  const counter = () => (
    <Button
      onPress={() => {
        presses.update((n) => n + 1);
        last.set(`counter ${presses()}`);
      }}
      onPressDown={() => pressing.set(true)}
      onPressUp={() => pressing.set(false)}
      disabled={disabled()}
      {...button("accent", { disabled })}
    >
      <Text style={buttonText("accent")}>Pressed {presses()}×</Text>
    </Button>
  );
  const pressState = () => `${pressing() ? "onPressDown: pressing…" : "onPressUp: released"} · disabled ${String(disabled())}`;
  const disabler = () => (
    <Switch
      checked={disabled()}
      onChange={({ checked }) => disabled.set(checked)}
      class={`flex-row items-center gap-2 active:opacity-70 ${desktop && !wide() ? "self-start" : ""}`}
      {...switchLook(() => disabled())}
    >
      <Text style={label()}>{wide() ? (disabled() ? "Enable it" : "Disable it") : disabled() ? "Enable the button above" : "Disable the button above"}</Text>
    </Switch>
  );
  // On / off formatting is a `Toggle` (a button is an action), in the
  // toggles' look: on a field's edge while off, the on fill while on.
  const toggle = (name: string, on: () => boolean, set: (on: boolean) => void, mark: object, glyph: string) => (
    <Toggle pressed={on()} onChange={({ pressed }) => set(pressed)} accessibilityLabel={name} {...toggleLook({ variant: "outline" })}>
      <Text style={{ ...toggleLabel(on), ...mark }}>{glyph}</Text>
    </Toggle>
  );
  const toggles = () => (
    <>
      {toggle("Bold", bold, (on) => bold.set(on), { fontWeight: "800" }, "B")}
      {toggle("Italic", italic, (on) => italic.set(on), { fontStyle: "italic" }, "I")}
    </>
  );
  const caption = (text: string) => <Text style={{ fontSize: 12, color: ui().muted }}>{text}</Text>;

  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 12 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>button</Text>
      <Text style={{ color: ui().muted }}>{desktop ? "Click, hover, or Tab to a button and press Space" : "Tap; move your finger away to cancel"}</Text>

      {() =>
        wide() ? (
          <View style={{ flex: 1, flexDirection: "row", gap: 16 }}>
            <Stage width={360} gap={24}>
              <View style={{ gap: 8 }}>
                {caption("onPress, onPressDown, onPressUp")}
                <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>
                  {counter()}
                  {disabler()}
                </View>
              </View>
              <View style={{ gap: 8 }}>
                {caption("on / off: Toggle")}
                <View style={{ flexDirection: "row", gap: 8 }}>{toggles()}</View>
              </View>
            </Stage>
            <Inspector>
              <Panel title="press · disabled">
                <Text style={{ fontSize: 13, color: ui().text }}>{pressState()}</Text>
              </Panel>
              <Panel title="Toggle pressed">
                <Text style={{ fontSize: 13, color: ui().text }}>
                  bold {String(bold())} · italic {String(italic())}
                </Text>
              </Panel>
              <Panel title="last onPress">
                <Text style={{ fontSize: 13, color: ui().up }}>{last()}</Text>
              </Panel>
            </Inspector>
          </View>
        ) : (
          <View style={{ gap: 12 }}>
            {counter()}
            <Text style={{ color: ui().muted, fontSize: 13 }}>{pressState()}</Text>

            {disabler()}

            <Text style={{ color: ui().muted, marginTop: 6 }}>on / off: Toggle</Text>
            <View style={{ flexDirection: "row", gap: 8 }}>
              {toggles()}
              <Text style={{ color: ui().muted, alignSelf: "center", flex: 1 }}>
                bold {String(bold())} · italic {String(italic())}
              </Text>
            </View>

            <Text style={{ color: ui().up }}>last onPress: {last()}</Text>
          </View>
        )
      }
    </View>
  );
}

mount(App);
import { mount, signal, Text } from "nsh";
import { Button } from "nsh/base";
import { Window } from "nsh/desktop";

function App() {
  const count = signal(0);
  return (
    <Button
      onPress={() => count.update((n) => n + 1)}
      class="self-center rounded-xl bg-blue-600 px-5 py-3 active:bg-blue-700"
    >
      <Text class="text-base font-semibold text-white">{`Pressed ${count()}`}</Text>
    </Button>
  );
}

mount(() => (
  <Window id="main">
    <App />
  </Window>
));

Button comes from nsh/base, the nsh-base crate in Rust. In TSX its look is class and style, with the state variants active:, hover:, focus-visible:, selected: and disabled: (or the matching activeStyle, hoverStyle, focusVisibleStyle, selectedStyle and disabledStyle). In Rust, button() makes one as view() makes a view: a setter per prop (.disabled(..), .selected(..)), a listener per event (.on_press(..)), the typed style methods (.px_4(), .bg(..)) for its look, the state methods (.active(..), .hover(..), .focus(..), .selected_style(..), .disabled_style(..)) for its states and .child(..) for its content.

#Props

Prop Rust Type Default Description
disabled .disabled(..) boolean false No presses and no press feedback; disabled: styles apply and screen readers say it is dimmed.
selected .selected(..) boolean false Selected: the current item (a folder, a filter) or the trigger of an open menu. Something on or off is a Toggle. Screen readers say so. The app owns the value and styles it.
selectedStyle .selected_style(|s| ..) StyleProp<ViewStyle> none The style while selected and not disabled, as selected: classes.
busy .busy(..) boolean false Busy: its action is running, as a “Saving…” button. Screen readers say so. Presses still count; set disabled too to refuse them.
accessibilityLabel .accessibility_label(..) string none What screen readers say when the content is not enough, as for an icon.
accessibilityHint .accessibility_hint(..) string none Explains what activating the button does, as a view’s accessibilityHint.
role .role(..) AccessibilityRole "button" What it is for screen readers when no nsh/base component is that control: "link" (it opens a URL), …
hitSlop .hit_slop(..) number | Partial<Edges> none How far outside its bounds presses still count, in points: one number for every side, or the sides named. As a view’s hitSlop.
children .child(..) JSX.Element none The content: text, an icon, any layout.
class, style style methods string, StyleProp<ViewStyle> none Its look, all of it.
activeStyle, hoverStyle, focusStyle, disabledStyle .active(|s| ..), .hover(..), .focus(..), .disabled_style(..) StyleProp<ViewStyle> none The style while pressed, hovered, focused or disabled, as the <state>: classes. Later states win; disabled wins over all.

In Rust each prop is a setter that takes a value, a signal or a closure; the props you leave out keep their defaults:

button()
    .disabled(move || saving.get())
    .accessibility_label("Save")

#Events

Event Rust Description
onPress .on_press(|| ..) The button was pressed: a tap, a click, Return or Space while it has the keyboard focus, or a screen reader’s activation.
onPressDown .on_press_down(|| ..) A press went down on it.
onPressUp .on_press_up(|| ..) The press ended: released, moved away or cancelled.

onPressDown and onPressUp are for press feedback of your own, such as a spring or a highlight that the state styles do not express. A disabled button reports none of them.

#Styling

The look of a button is your app’s: the app decides what a primary or a secondary button is. A pair of small components keeps that decision in one place:

import { Text } from "nsh";
import { Button } from "nsh/base";

function Primary(props: { label: string; onPress: () => void; disabled?: boolean }) {
  return (
    <Button
      onPress={props.onPress}
      disabled={props.disabled}
      class="items-center rounded-lg bg-blue-600 px-4 py-3 active:bg-blue-700 disabled:opacity-40"
    >
      <Text class="font-semibold text-white">{props.label}</Text>
    </Button>
  );
}

function Secondary(props: { label: string; onPress: () => void }) {
  return (
    <Button
      onPress={props.onPress}
      class="items-center rounded-lg border border-neutral-300 px-4 py-3 active:bg-neutral-100 hover:bg-neutral-50"
    >
      <Text class="text-neutral-900">{props.label}</Text>
    </Button>
  );
}

The state variants are applied natively: a press darkens the button on the main thread with no JS or Rust running. In Rust the state methods are the same variants: .active(..), .hover(..), .focus(..), .selected_style(..) and .disabled_style(..) follow the button’s own states. Your theme’s colors work the same way: bg-primary in TSX, theme().primary in Rust (see Theme tokens).

#Disabled

A disabled button takes no presses and gives no feedback, and screen readers announce it as dimmed. Its look while disabled is yours, with disabled: classes or disabledStyle:

<Button disabled={saving()} onPress={save} class="rounded-lg bg-blue-600 px-4 py-3 disabled:opacity-40">
  <Text class="text-white">Save</Text>
</Button>

#The current item with selected

selected shows a button as the current one of its kind or as the trigger of what is open: the folder a sidebar shows, the active filter, a menu button while its menu is open (Design Guides, “Interaction states”). The app holds the value and styles the selected state; screen readers announce the button as selected.

<Button
  selected={folder() === "Inbox"}
  onPress={() => folder.set("Inbox")}
  class="rounded-(--radius) px-3 py-2 selected:bg-accent"
>
  <Text>Inbox</Text>
</Button>

Something that is on or off (bold in a toolbar, a favorite, a view option) is a Toggle: it owns the pressed state, and screen readers announce it as a toggle button. A row of tabs is Tabs and a setting that is on or off is Switch, from nsh/base: they own the role, the state and the keyboard of their kind, which a Button with role="tab" or role="switch" does not.

#A small target with hitSlop

An icon button can be smaller than a finger. hitSlop makes presses that land near it count, in points past each side, without changing its layout or its look: one number for every side, or the sides named ({ top: 8, bottom: 8 }), as a view’s hitSlop takes them.

<Button hitSlop={12} accessibilityLabel="Close" onPress={() => open.set(false)} class="size-5 items-center justify-center">
  <Text>×</Text>
</Button>

#Accessibility

  • Give accessibilityHint when the label does not explain the result of pressing the button. It follows reactive values; setting it to undefined removes the hint.
  • A button is one element for screen readers, with the role "button" unless role says otherwise. Its label is its text content; give accessibilityLabel when the content is an icon or says too little.
  • disabled, selected and busy are announced as the platform announces them (VoiceOver, TalkBack, UI Automation, the browser’s accessibility tree).
  • On macOS and the web a button is a stop of the keyboard focus: Tab reaches it, Return and Space press it, and focus-visible: styles show where the focus is.

See Accessibility for labels, roles and announcements in general.

#Platform notes

  • iOS, Android and Mac Catalyst: a press is a tap that ends on the button; moving away cancels it, as with the system’s own buttons.
  • Desktops (macOS, Windows, Linux, GPUI) and the web: a press is a click. On macOS and the web, Return and Space also press the button that has the keyboard focus. hover: styles apply under a mouse or a trackpad’s pointer.
  • Every platform draws what the app styles: press feedback is active: / activeStyle or an animation of your own.