Elements

Collapsible

A collapsible is a region whose content expands and collapses: details under a summary, a “show more”, a section of advanced settings. It renders its children always and its content after them while open. The app owns open and the trigger that flips it (one of the children), and the look is the app’s: a Collapsible has no trigger, chevron or label of its own. With reveal, the content opens and closes with motion: its region’s height springs from nothing to the content’s own and back, and what follows the collapsible moves along.

el-collapsible.tsx
el-collapsible.tsxLive
import { type JSX, mount, signal, Text, View } from "nsh";
import { Collapsible, Switch } from "nsh/base";
import { desktop, Log, Panel, Split, switchLook, ui, controlSize, listRow, RowDivider, RowLabel, sectionSurface, DisclosureChevron, disclosureTriggerLook } from "./palette";

// Each section: a summary row, the app's trigger (it says whether it is
// expanded to screen readers), and details the collapsible reveals while the
// app has it open: its height springs open and shut (`reveal`), and the
// sections below move with it. The summary is a shared row (`listRow`,
// through `disclosureTriggerLook`: the hover fill reaching past the
// content, the keyboard's focus ring, a press that dims); its chevron
// (`DisclosureChevron`) turns in a lane as wide as its stroke, so it ends
// where the values below it end. The reveal, the chevron and the switch
// stay still with reduced motion.
function Section(props: { label: string; detail: string; open: boolean; first?: boolean; onToggle: () => void; content: JSX.Element }) {
  return (
    <Collapsible open={props.open} reveal content={props.content}>
      <View role="button" accessibilityState={{ expanded: props.open }} onPress={props.onToggle} {...disclosureTriggerLook({ first: props.first })}>
        <RowDivider show={!props.first} />
        <RowLabel label={props.label} detail={props.detail} />
        <DisclosureChevron open={props.open} />
      </View>
    </Collapsible>
  );
}

const USAGE: [string, string][] = [
  ["Photos", "120 GB"],
  ["Apps", "54 GB"],
  ["System", "38 GB"],
];

function App() {
  const storage = signal(true);
  const advanced = signal(false);
  const originals = signal(false);
  const events = signal<string[]>([]);
  const log = (line: string) => events.set([line, ...events()].slice(0, 4));
  const toggle = (name: string, open: { (): boolean; set: (v: boolean) => void }) => () => {
    open.set(!open());
    log(`${name} → ${open() ? "open" : "closed"}`);
  };
  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>collapsible</Text>
      <Text style={{ color: ui().muted }}>{desktop ? "Click a summary, or Tab to it and press Space" : "Tap a summary to show its details"}</Text>

      <Split
        gap={14}
        inspector={
          <>
            <Panel title="open">
              <Text style={{ fontSize: 13, color: ui().text }}>
                Storage {storage() ? "open" : "closed"} · Advanced {advanced() ? "open" : "closed"}
              </Text>
              <Text style={{ fontSize: 12, color: ui().muted }}>Keep originals {originals() ? "on" : "off"}: kept while collapsed</Text>
            </Panel>
            <Log title="onPress (trigger) → open" lines={events()} minHeight={92} />
          </>
        }
      >
        <View style={sectionSurface({ padded: true })}>
          <Section
            first
            label="Storage"
            detail="212 GB of 256 GB used"
            open={storage()}
            onToggle={toggle("Storage", storage)}
            content={
              <View style={{ paddingStart: controlSize.gap, paddingBottom: controlSize.padding }}>
                {USAGE.map(([name, value]) => (
                  <View style={{ flexDirection: "row", alignItems: "center", minHeight: controlSize.line }}>
                    <Text style={{ flex: 1, fontSize: controlSize.label, color: ui().muted }}>{name}</Text>
                    <Text style={{ fontSize: controlSize.label, color: ui().muted, fontVariant: ["tabular-nums"] }}>{value}</Text>
                  </View>
                ))}
              </View>
            }
          />
          <Section
            label="Advanced"
            detail="Options most people leave alone"
            open={advanced()}
            onToggle={toggle("Advanced", advanced)}
            content={
              <Switch
                checked={originals()}
                onChange={({ checked }) => {
                  originals.set(checked);
                }}
                {...listRow({ start: controlSize.gap, style: { flexDirection: "row-reverse" } })}
                {...switchLook(() => originals())}
              >
                <RowDivider show />
                <RowLabel label="Keep originals" detail={originals() ? "Edits are saved as copies" : "Edits replace the photo"} />
              </Switch>
            }
          />
        </View>
      </Split>
    </View>
  );
}

mount(App);
use nsh_base::{collapsible, theme};
use nsh_core::{AccessibilityState, prelude::*};

fn storage() -> impl IntoElement {
    let open = signal(false);
    collapsible()
        .open(open)
        .reveal(true)
        .gap_2()
        .child(
            view()
                .role(AccessibilityRole::Button)
                .accessibility_state(move || AccessibilityState {
                    expanded: Some(open.get()),
                    ..AccessibilityState::default()
                })
                .on_press(move || open.update(|o| *o = !*o))
                .flex_row()
                .items_center()
                .justify_between()
                .child(text("Storage"))
                .child(text("›").transition_transform().rotate(move || {
                    if open.get() { deg(90.0) } else { deg(0.0) }
                })),
        )
        .content(text("Photos 120 GB · Apps 54 GB · System 38 GB").text_color(move || theme().muted_foreground))
}

Collapsible comes from nsh/base, the nsh-base crate in Rust. The value is the app’s: its trigger flips open, and the collapsible shows the value the app passes. In Rust, collapsible() makes one with a setter per prop (.open(..), .reveal(..), .content(..)), the typed style methods for the region and .child(..) for what shows always.

#Props

Prop Rust Type Default Description
open .open(..) boolean false Expanded: the content is in the tree, after the children. The app owns the value.
reveal .reveal(..) boolean false Opens and closes with a reveal: the content sits in a region that clips it, whose height springs from zero to the content’s own as open turns on and back as it turns off, critically damped (about 265 ms, no overshoot). What follows the collapsible moves with it, and the content stays in the tree until the region has closed. With reduced motion it opens and closes at once. The region is in the layout while closed too, zero high, so a gap of the collapsible’s also comes before it.
revealSpring .reveal_spring(..) { stiffness?, damping?, mass? } (Rust Spring) none The spring the reveal moves on, the options of AnimatedValue.spring with its defaults (stiffness 170, damping 26, mass 1 for those left out): an app’s own motion token ({ stiffness: 620, damping: 36 } overshoots a little and settles in about 384 ms). Without it, the critically damped spring above. The content leaves the tree once this spring has settled. Used only with reveal; with reduced motion the region still opens and closes at once.
content .content(..) JSX.Element none What expands. It is made once and kept while collapsed, so what is inside keeps its state (an input’s text, a scroll position, a switch) from one opening to the next.
children .child(..) JSX.Element none What shows either way: a summary, the trigger that flips open.
class, style style methods string, StyleProp<ViewStyle> none The region around the children and the content (gap-2 spaces them).

#Events

A collapsible reports nothing of its own: the trigger is the app’s, and its press (onPress of the View with role="button") is where the app flips open.

#Parts

Part Inside Styled with
The region class, style
The children the region, first their own elements
The reveal’s region the region, after the children, with reveal none: it clips the content and takes its height
The content the region, after the children (in the reveal’s region with reveal), while open its own elements (content)

Without reveal, the content comes and goes at once, and each platform lays the region out again when it arrives or leaves. With reveal, the change is a layout animation of the commit that changes open (as LayoutAnimation.configureNext, run natively, so no JavaScript runs while it moves): the reveal’s region grows from zero to the content’s height and shrinks back, and the frames of whatever the same change moves, the views after the collapsible among them, move with it. A transition of the app’s goes along: the trigger’s chevron turns (transition-transform), and the content can fade in with its own classes.

#Accessibility

  • The region is no element of its own for screen readers: its children and content are read as they are.
  • The trigger says whether the region is expanded: give it accessibilityState={{ expanded: open }} and a button role (role="button" on a View), and screen readers announce “expanded” or “collapsed” with its label.
  • On macOS and the web the trigger is a stop of the keyboard focus when it takes presses: Tab reaches it, Space and Return flip the region.

See Accessibility for labels, roles and announcements in general.

#Platform notes

  • Every platform shows the content after the children while open, and leaves it out of the layout otherwise.
  • With reveal, every platform springs the region’s height on its own animator (iOS, Android, macOS, Windows, Linux, GPUI and the web), and opens and closes it at once while the system asks for reduced motion.
  • iOS, Android and Mac Catalyst: the trigger’s press is a tap. Desktops (macOS, Windows, Linux, GPUI) and the web: a click, and Space or Return on the focused trigger on macOS and the web.