Elements

Menu

A menu is a list of actions its trigger opens. One structure serves every device, presented as each expects:

el-menu.tsx
el-menu.tsxLive
import { mount, signal, Text, View } from "nsh";
import { ContextMenu, Menu, MenuItem, MenuSeparator, type OpenChangeReason, Submenu } from "nsh/base";
import { button, buttonText, desktop, Inspector, MenuLabel, MenuMark, menuIndicator, menuItemLabel, menuItemLook, menuItemSize, menuSeparator, Panel, Stage, SubmenuBack, SubmenuRow, ui, wide, menuPopup } from "./palette"

/**
 * One row (`menuItemLook`: the hover and the keyboard's highlight alike).
 * A checkable row (`checked`) leads with its mark: a check for a setting, a
 * dot for one choice of a group (`radio`), which fades in as the app checks
 * the item; rows of the same menu keep the mark's room so their labels line
 * up (`inset`).
 */
function Item(props: { label: string; onSelect?: () => void; checked?: boolean; radio?: boolean; inset?: boolean; disabled?: boolean; keepOpen?: boolean; danger?: boolean }) {
  return (
    <MenuItem
      onSelect={props.onSelect}
      disabled={props.disabled}
      checked={props.checked}
      role={props.radio ? "menuitemradio" : undefined}
      indicatorClass={menuIndicator}
      indicator={props.checked === undefined ? undefined : <MenuMark kind={props.radio ? "dot" : "check"} size={menuItemSize.icon} tint={ui().accent} />}
      closeOnSelect={!props.keepOpen}
      {...menuItemLook()}
    >
      <If when={props.inset}>
        <View style={{ width: menuItemSize.icon }} />
      </If>
      <Text style={menuItemLabel({ danger: props.danger })}>{props.label}</Text>
    </MenuItem>
  );
}

function Share(props: { onSelect: (what: string) => void }) {
  return (
    <Submenu offset={4} trigger={<SubmenuRow label="Share" />} back={<SubmenuBack label="Share" />}>
      <Item label="Mail" onSelect={() => props.onSelect("Mail")} />
      <Item label="Messages" onSelect={() => props.onSelect("Messages")} />
      <Item label="Copy link" onSelect={() => props.onSelect("Copy link")} />
    </Submenu>
  );
}

const SORTS = ["Name", "Date modified", "Size"];

function App() {
  const last = signal("—");
  const reasons = signal<string[]>([]);
  const hidden = signal(false);
  const sidebar = signal(true);
  const minimap = signal(false);
  const sort = signal("Name");
  const pinned = signal(false);
  const changed = (name: string) => ({ open, reason }: { open: boolean; reason: OpenChangeReason }) =>
    reasons.set([`${name} ${open ? "opened" : "closed"} · ${reason}`, ...reasons()].slice(0, 8));
  const choose = (what: string) => last.set(what);
  const menu = () => (
    <Menu
      offset={4}
      margin={8}
      {...menuPopup()}
      onOpenChange={changed("File")}
      trigger={
        <View {...button("secondary", { align: "flex-start" })}>
          <Text style={buttonText()}>File ▾</Text>
        </View>
      }
    >
      <Item label="New" onSelect={() => choose("New")} />
      <Item label="Open…" onSelect={() => choose("Open…")} />
      <Item label="Paste" disabled />
      <MenuSeparator style={menuSeparator()} />
      <Share onSelect={(what) => choose(`Share › ${what}`)} />
      <MenuSeparator style={menuSeparator()} />
      <Item label="Delete" danger onSelect={() => choose("Delete")} />
    </Menu>
  );
  const view = () => (
    <Menu
      offset={4}
      margin={8}
      {...menuPopup()}
      onOpenChange={changed("View")}
      trigger={
        <View {...button("secondary", { align: "flex-start" })}>
          <Text style={buttonText()}>View ▾</Text>
        </View>
      }
    >
      {/* Settings keep the menu open: each shows its new value at once. */}
      <Item label="Show sidebar" checked={sidebar()} keepOpen onSelect={() => sidebar.set(!sidebar())} />
      <Item label="Show minimap" checked={minimap()} keepOpen onSelect={() => minimap.set(!minimap())} />
      <Item label="Show hidden files" checked={hidden()} keepOpen onSelect={() => hidden.set(!hidden())} />
      <MenuSeparator style={menuSeparator()} />
      <MenuLabel text="Sort by" />
      {/* One choice of a group: choosing closes the menu. */}
      <Each of={SORTS}>{(by) => <Item label={by()} radio checked={sort() === by()} onSelect={() => sort.set(by())} />}</Each>
    </Menu>
  );
  const context = () => (
    <ContextMenu
      margin={8}
      {...menuPopup()}
      onOpenChange={changed("Context")}
      trigger={
        <View
          style={{
            height: wide() ? 220 : 150,
            borderRadius: 14,
            borderWidth: 2,
            borderStyle: "dashed",
            borderColor: ui().faint,
            alignItems: "center",
            justifyContent: "center",
            gap: 4,
          }}
        >
          <Text style={{ fontSize: 15, fontWeight: "600", color: ui().text }}>{pinned() ? "ContextMenu · pinned" : "ContextMenu"}</Text>
          <Text style={{ fontSize: 13, color: ui().muted }}>{desktop ? "Right click here" : "Hold a finger here"}</Text>
        </View>
      }
    >
      <Item label="Pinned" checked={pinned()} onSelect={() => pinned.set(!pinned())} />
      <Item label="Copy" inset onSelect={() => choose("Copy")} />
      <Item label="Rename" inset onSelect={() => choose("Rename")} />
      <MenuSeparator style={menuSeparator()} />
      <Item label="Delete" inset danger onSelect={() => choose("Delete")} />
    </ContextMenu>
  );
  const panels = () => (
    <>
      <Panel title="onSelect · checked">
        <Text style={{ fontSize: 13, color: ui().text }}>{last()}</Text>
        <Text style={{ fontSize: 13, color: ui().muted }}>
          sidebar {sidebar() ? "on" : "off"} · minimap {minimap() ? "on" : "off"} · hidden files {hidden() ? "shown" : "hidden"} · by {sort()} · {pinned() ? "pinned" : "not pinned"}
        </Text>
      </Panel>
      <Panel title="onOpenChange({ open, reason })" grow>
        <View style={{ gap: 2 }}>
          <Each of={reasons()}>{(e, i) => <Text style={{ fontSize: 12, color: i() === 0 ? ui().text : ui().faint }}>{e()}</Text>}</Each>
        </View>
      </Panel>
    </>
  );
  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>menu</Text>
      <Text style={{ color: ui().muted }}>
        {desktop ? "Click File; hover Share to open its submenu. View has settings and a choice of one. Right click the box below" : "Tap File: a sheet; Share shows its items in place. View has settings and a choice of one"}
      </Text>

      {() =>
        wide() ? (
          <View style={{ flex: 1, flexDirection: "row", gap: 16 }}>
            <Stage>
              <View style={{ flexDirection: "row", gap: 8 }}>
                {menu()}
                {view()}
              </View>
              {context()}
            </Stage>
            <Inspector>{panels()}</Inspector>
          </View>
        ) : (
          <>
            <View style={{ flexDirection: "row", gap: 8 }}>
              {menu()}
              {view()}
            </View>
            {context()}
            {panels()}
          </>
        )
      }
    </View>
  );
}

mount(App);
  • On the desktops and in desktop browsers, a popup at the trigger; a Submenu cascades beside its item as the pointer comes over it or presses it.
  • On phones and tablets, a sheet at the bottom of the screen over a backdrop; a Submenu shows its items in the sheet in place of the menu’s, with a row of yours leading back.

Choosing an item, a press outside, Escape, the Android back button and VoiceOver’s escape gesture close it. ContextMenu is the same menu opened by the secondary button (a right click) at the pointer, by a finger held on its trigger on touch screens, or below its trigger by the keyboard in the browser and on Linux, and by screen readers on macOS and Windows.

Return, Space or Down on the focused trigger opens the menu with the keyboard focus on its first enabled item, and Up with it on its last; the arrow keys then move between the items. A press opens it with no item focused; on the desktops Down or Home then focuses the first enabled item and Up or End the last. Page Down moves to the last enabled item in view and Page Up to the first, a view at a time, stopping at the ends (a MenuList the same, see Long lists). On the desktops the pointer moving over an item gives it the keyboard focus, so the keys go on from the item under the pointer; style an item’s focus: state as its hover: one. On the desktops and in a terminal, Right, Return or Space on a Submenu’s item opens it with the keyboard focus on its first enabled item; Left on one of its items, or Escape, closes it and puts the focus back on its item. A submenu the pointer opened closes when the arrow keys move the focus to another item of its menu.

use nsh_base::{menu, menu_item, menu_separator, submenu};
use nsh_core::prelude::*;

fn item(label: &'static str, on_select: impl Fn() + 'static) -> impl IntoElement {
    menu_item()
        .on_select(on_select)
        .px_3()
        .py_2()
        .rounded_md()
        .child(text(label))
}

fn file_menu() -> impl IntoElement {
    menu()
        .offset(px(4.0))
        .trigger(view().px_3().py_2().child(text("File")))
        .child(item("New", || log::info!("new")))
        .child(item("Open…", || log::info!("open")))
        .child(menu_separator().h(px(1.0)).my_1().bg(rgb(0xe5e7eb)))
        .child(
            submenu()
                .trigger(view().px_3().py_2().child(text("Share ›")))
                .back(view().px_3().py_2().child(text("‹ Back")))
                .child(item("Mail", || log::info!("mail")))
                .child(item("Copy link", || log::info!("link"))),
        )
}

All five come from nsh/base. The items reach their menu on their own, so you arrange them freely: groups in views, labels, items that come and go with If. popupClass styles the popup on desktops and the sheet on phones; a style that differs between them can compare platform.idiom (nsh) with "desktop".

The popup is never taller than the room on the side it opens on, and a submenu’s popup never taller than its own: a long menu in a short window opens on the side where it fits whole, or where there is more room, and its items scroll inside it. The keys bring the item they move to into view, and a submenu closes once its item scrolls out of view. The sheet on phones stays below the status bar the same way. Draw the surface (background, border, shadow) with popupClass, around the items, so it stays in place while they scroll.

Menus whose triggers are items of one Toolbar form a menu bar: with one of its menus open, the pointer over another menu’s trigger opens that menu in its place, and the arrow keys move between the triggers.

<Toolbar accessibilityLabel="Menu bar">
  <Menu trigger={<View><Text>File</Text></View>}>{/* … */}</Menu>
  <Menu trigger={<View><Text>Edit</Text></View>}>{/* … */}</Menu>
</Toolbar>

#Context menus

import { ContextMenu, MenuItem } from "nsh/base";

<ContextMenu
  popupClass="min-w-40 rounded-lg bg-white p-1 shadow-lg"
  backdropClass="bg-black/40"
  trigger={<PhotoTile photo={photo} />}
>
  <MenuItem onSelect={() => share(photo)}><Text>Share</Text></MenuItem>
  <MenuItem onSelect={() => remove(photo)}><Text>Delete</Text></MenuItem>
</ContextMenu>

On the desktops the secondary button opens it where the pointer is. On touch screens a finger held on the trigger opens it as a sheet; the trigger’s own presses and the scroll views around it keep working, and moving the finger cancels the hold.

Keyboard and screen reader users open it too. In the browser and on Linux, Shift+F10 and the Menu key on the focused trigger open it. On macOS, VoiceOver’s “show menu” action (VO-Shift-M) opens it, and on Windows, a screen reader’s “show context menu” action through UI Automation does. These openings place the menu below the trigger, starting at its start edge, with the keyboard focus on its first enabled item, as WAI-ARIA describes for context menus. Make the trigger focusable so the keyboard reaches it. A view’s own onContextMenu tells these openings apart by pointerType, which is null for them.

#Checkable items

checked makes an item checkable: a setting the menu shows (“Show sidebar”) or, with role="menuitemradio", one choice of a group (“Sort by”). The value is yours: choosing the item calls onSelect, you set the next value, and the item shows it. While it is checked, its checked: classes and checkedStyle apply, and so do those of its indicator: the part before its content (indicatorClass, indicatorStyle) around the mark you give it (indicator). The mark is made once and kept; the indicator’s checked: classes show and hide it, or the mark’s own group-checked: classes with group in indicatorClass. closeOnSelect={false} keeps the menu open, so a setting shows its new value at once.

use nsh_base::{menu, menu_item};
use nsh_core::{element::StyleRefinement, prelude::*};

fn view_menu(sidebar: Signal<bool>, sort: Signal<&'static str>) -> impl IntoElement {
    // The indicator part shows the mark while the item is checked.
    let part = |s: StyleRefinement| s.w(px(16.0)).opacity(0.0).checked(|s| s.opacity(1.0));
    let by = move |label: &'static str| {
        menu_item()
            .role(AccessibilityRole::MenuItemRadio)
            .checked(move || Some(sort.get() == label))
            .indicator_style(part)
            .indicator(text("✓"))
            .on_select(move || sort.set(label))
            .flex_row()
            .gap_2()
            .px_3()
            .py_2()
            .child(text(label))
    };
    menu()
        .trigger(view().px_3().py_2().child(text("View")))
        .child(
            menu_item()
                .checked(move || Some(sidebar.get()))
                .close_on_select(false)
                .indicator_style(part)
                .indicator(text("✓"))
                .on_select(move || sidebar.set(!sidebar.get_untracked()))
                .flex_row()
                .gap_2()
                .px_3()
                .py_2()
                .child(text("Show sidebar")),
        )
        .child(by("Name"))
        .child(by("Date modified"))
}

A mark at the trailing edge goes in the content instead, styled with group-checked: classes under group on the item.

#Entrance and exit

On the desktops the popup comes and goes with your transitions, as a Popover’s: popupStartingClass is its look in its first frame, popupEndingClass its look once closed, which it keeps while the transition-* classes of popupClass run, and onClose follows. On its way out it takes no presses or keys: the keyboard focus is back on the trigger as it closes, so Return during the exit chooses no item and opens the menu again. Submenus take the same looks and close with their menu. The sheet of phones slides in and out on its own.

<Menu
  popupClass="min-w-40 rounded-lg bg-white p-1 shadow-lg transition-all duration-100"
  popupStartingClass="opacity-0 -translate-y-1"
  popupEndingClass="opacity-0"
  trigger={<Text>File</Text>}
>
  <MenuItem onSelect={newFile}><Text>New</Text></MenuItem>
</Menu>

#Open state

Without open, a menu keeps its own state (from defaultOpen for Menu). With open, the app owns it and changes it in onOpenChange({ open, reason }): "triggerPress", "select", "pressOutside", "backdropPress", "cancel", "contextMenu" or "longPress".

A Submenu keeps its own state, and reports each opening and closing the user asks for in onOpenChange({ open, reason }): "hover" (its item hovered, or another item of its menu), "focus" (the keyboard focus moved to another item of its menu), "triggerPress" (its item pressed, or Right, Return or Space on it), "cancel" (Left, Escape, back or its back row), or the menu’s reason when the whole menu closes ("select", "pressOutside", …). Its items are made as it opens, so an app can start loading them there the first time and show them as they arrive. When the app closes the menu itself, nothing is reported.

const recent = signal<string[] | null>(null);

<Submenu
  trigger={<Text>Open Recent</Text>}
  onOpenChange={({ open }) => {
    if (open && recent() === null) loadRecent().then((names) => recent.set(names));
  }}
>
  <Each of={recent() ?? []}>
    {(name) => <MenuItem onSelect={() => openFile(name())}><Text>{name()}</Text></MenuItem>}
  </Each>
</Submenu>

#Long lists

A menu of many items, or of as many as the data has (models, accounts, recent files), puts them in a MenuList (Rust): a virtualized list whose rows are made only near its viewport. Its rows are items of the menu among the ones around it: Up, Down, Home and End walk every row of the list, scrolling to a row before focusing it and passing over disabled ones, then go on to the items before and after the list, a Submenu’s item among them. Page Down and Page Up scroll the list a view at a time. render_item draws each row from its index, one MenuItem or Submenu per row; give the list a height.

use nsh_base::{MenuListEntry, menu, menu_item, menu_list, submenu};
use nsh_core::prelude::*;

let models = signal(vec![/* … */]);
menu()
    .trigger(text("Model"))
    .child(
        menu_list()
            .count(move || models.with(|m: &Vec<Model>| m.len() as u32))
            .render_item(move |e: &MenuListEntry| {
                let index = e.index as usize;
                menu_item()
                    .on_select(move || choose(index))
                    .child(text(move || models.with(|m| m[index].name.clone())))
            })
            .h(px(240.0)),
    )
    .child(submenu().trigger(text("Reasoning")).child(/* … */))

#Props

Prop Rust Type Default Description
open .open(..) boolean none Open, controlled by the app.
defaultOpen .default_open(..) boolean false Open at first, without open.
placement .placement(..) "top" | "bottom" | "left" | "right" "bottom" Desktops: the side of the trigger it goes on.
align .align(..) "start" | "center" | "end" "start" Desktops: how it lines up with the trigger.
offset .offset(..) number 0 Desktops: the gap between the trigger and the popup.
margin .margin(..) number 0 Desktops: the distance it keeps from the edges of the safe area.
popupClass, popupStyle .popup_class(..), .popup_style(..) string, StyleProp<ViewStyle> none The popup (desktops) or the sheet (phones), and the submenus’ popups.
popupStartingClass, popupStartingStyle .popup_starting_class(..), .popup_starting_style(..) string, StyleProp<ViewStyle> none Desktops: the popups’ look in their first frame, over their own.
popupEndingClass, popupEndingStyle .popup_ending_class(..), .popup_ending_style(..) string, StyleProp<ViewStyle> none Desktops: the popups’ look once closed, kept while their transitions run.
backdropClass, backdropStyle .backdrop_class(..), .backdrop_style(..) string, StyleProp<ViewStyle> none Phones: the backdrop behind the sheet.
trigger .trigger(..) JSX.Element none What opens it when pressed. While the menu is open its aria-expanded: classes and expandedStyle apply.
children .child(..) JSX.Element none The items, made each time it opens.

#ContextMenu

open, popupClass / popupStyle, the starting and ending looks, backdropClass / backdropStyle, trigger and children as for Menu, and:

Prop Rust Type Default Description
disabled .disabled(..) boolean false Nothing opens it: not the secondary button, held fingers, the keyboard or a screen reader.
offset .offset(..) number 0 Desktops: the gap between the pointer and the popup.
margin .margin(..) number 0 Desktops: the distance it keeps from the edges of the safe area.
Prop Rust Type Default Description
disabled .disabled(..) boolean false Not chosen; disabled: styles apply.
checked .checked(..) boolean none Checked or not, which makes it a checkable item; owned by the app.
checkedStyle .checked_style(..) StyleProp<ViewStyle> none Its style while checked, as checked: classes.
role .role(..) AccessibilityRole "menuitemcheckbox" with checked, else "menuitem" What it is for screen readers; "menuitemradio" for one choice of a group.
indicatorClass, indicatorStyle .indicator_class(..), .indicator_style(..) string, StyleProp<ViewStyle> none The indicator, the part before its content; its checked: and disabled: classes follow the item.
indicator .indicator(..) JSX.Element none The mark inside the indicator.
closeOnSelect .close_on_select(..) boolean true Choosing it closes the menu.
accessibilityLabel .accessibility_label(..) string none What screen readers say, when the content is not enough.
children, class, style .child(..), style methods none Its content and look, with hover:, active: and checked: states.
Prop Rust Type Default Description
trigger .trigger(..) JSX.Element none The item that opens it.
back .back(..) JSX.Element none Phones: the row above its items that returns to the items around it.
disabled .disabled(..) boolean false It does not open.
offset .offset(..) number 0 Desktops: the gap between the menu around it and its popup.
children .child(..) JSX.Element none Its items.
Rust Type Default Description
.count(..) u32 0 How many rows.
.render_item(|e: &MenuListEntry| ..) MenuListEntry { index } none Draws a row from its index: one MenuItem or Submenu.
style methods none The list’s look; give it a height (.h(..)).

MenuSeparator is a view you style (class, style), shown with the items of its level.

#Events

Event Rust Description
onOpenChange (Menu, ContextMenu) .on_open_change(|e| ..) It opened or closed, with why.
onOpen (Menu, ContextMenu) .on_open(|| ..) It is shown; as a sheet, once it came in.
onClose (Menu, ContextMenu) .on_close(|| ..) It is gone: as a sheet once it went, as a popup after its exit. Also when the app closed it.
onPosition (Menu, ContextMenu) .on_position(|e| ..) Desktops: the popup was placed: placement (the side it went on), bounds, available.
onCancel (Menu, ContextMenu) .on_cancel(|| ..) The user tried to close it without choosing (Escape or back, a press outside or on the backdrop).
onSelect (MenuItem) .on_select(|| ..) The item was chosen; a checkable item asks for its other value.
onOpenChange (Submenu) .on_open_change(|e| ..) It opened or closed as the user asked, with why.

#Accessibility

The popup or sheet is a menu and its items menu items for screen readers; the trigger tells whether the menu is expanded. A checkable item is a checkbox or radio menu item, read as checked or not checked; its indicator is part of the item. In TSX the trigger is the element you pass, a Button or a view of your own: it takes the presses and the expanded state itself, so its own active: classes and activeStyle show while it is pressed, and its own onPress runs too. Only the items of the level shown are on screen, so screen readers read what is there.