选择按钮或上下文菜单中的操作和设置。

从一个触发器和几个操作开始。随着任务变复杂,再加入分组、复选框、单选选项或子菜单。焦点、方向键、键入查找(typeahead)和关闭都由菜单处理。

控制台
import {
  Menu,
  MenuContent,
  MenuGroup,
  MenuGroupLabel,
  MenuItem,
  MenuSeparator,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu onAction={(value) => log(`Chose ${value}`)}>
      <MenuTrigger>Open Menu</MenuTrigger>
      <MenuContent>
        <MenuGroup>
          <MenuGroupLabel>Project</MenuGroupLabel>
          <MenuItem value="overview">Overview</MenuItem>
          <MenuItem value="members">Members</MenuItem>
          <MenuItem value="settings">Settings</MenuItem>
        </MenuGroup>
        <MenuSeparator />
        <MenuGroup>
          <MenuGroupLabel>Help</MenuGroupLabel>
          <MenuItem value="docs">Documentation</MenuItem>
          <MenuItem value="feedback">Send feedback</MenuItem>
        </MenuGroup>
      </MenuContent>
    </Menu>
  )
}

export { Example }
按 Open Menu,用指针或方向键加 Enter 选择一个条目。菜单会关闭,控制台会记录你的选择。

安装

npm install @ui-sdk/solid @ui-sdk/core

组合

用下面的组合构建 Menu:

Menu
├── MenuTrigger
└── MenuContent
    ├── MenuItem
    └── MenuItem

给条目一个 value,并在菜单上处理 onAction 来运行选中的命令。Group 和 GroupLabel 可以组织相关的操作;Separator 把它们分开,而不会成为焦点停靠点。

从 onAction 或条目的 onSelect 返回一个 promise,可以让条目保持待处理(pending)。它会得到 data-pending、aria-busy 和 aria-disabled,菜单保持打开,在 promise 兑现之前再次选择它不会有任何作用。promise 兑现后菜单关闭。被拒绝时菜单保持打开,并把原因放进条目的 error 状态,直到下一次尝试。一秒钟后,屏幕阅读器会听到 pendingAnnouncement,默认是“Loading”。

用法

导入部件并把它们组合起来:

import { Menu, MenuContent, MenuItem, MenuTrigger } from "@ui-sdk/solid/menu"

function Example() {
  return (
    <Menu>
      <MenuTrigger>Actions</MenuTrigger>
      <MenuContent>
        <MenuItem value="rename">Rename</MenuItem>
        <MenuItem value="duplicate">Duplicate</MenuItem>
      </MenuContent>
    </Menu>
  )
}

export { Example }

嵌套 Sub、SubTrigger 和 SubContent 来增加一层。悬停或朝子菜单的方向按方向键即可打开它。菜单允许指针沿对角线移入子菜单,而不会误选经过的条目。Escape 只关闭子菜单并把焦点返回它的触发器,符合菜单模式的要求。

控制台
import {
  Menu,
  MenuContent,
  MenuItem,
  MenuSeparator,
  MenuSub,
  MenuSubContent,
  MenuSubTrigger,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu onAction={(value) => log(`Chose ${value}`)}>
      <MenuTrigger>Edit</MenuTrigger>
      <MenuContent>
        <MenuItem value="undo" shortcut="mod+z">
          Undo
        </MenuItem>
        <MenuItem value="redo" shortcut="mod+shift+z">
          Redo
        </MenuItem>
        <MenuSeparator />
        <MenuSub>
          <MenuSubTrigger>
            Find
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m9 18 6-6-6-6" />
            </svg>
          </MenuSubTrigger>
          <MenuSubContent>
            <MenuItem value="find" shortcut="mod+f">
              Find…
            </MenuItem>
            <MenuItem value="find-next" shortcut="mod+g">
              Find next
            </MenuItem>
            <MenuItem value="find-previous" shortcut="mod+shift+g">
              Find previous
            </MenuItem>
          </MenuSubContent>
        </MenuSub>
        <MenuSub>
          <MenuSubTrigger>
            Transform
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m9 18 6-6-6-6" />
            </svg>
          </MenuSubTrigger>
          <MenuSubContent>
            <MenuSub>
              <MenuSubTrigger>
                Case
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m9 18 6-6-6-6" />
                </svg>
              </MenuSubTrigger>
              <MenuSubContent>
                <MenuItem value="uppercase">Uppercase</MenuItem>
                <MenuItem value="lowercase">Lowercase</MenuItem>
              </MenuSubContent>
            </MenuSub>
            <MenuItem value="trim">Trim whitespace</MenuItem>
          </MenuSubContent>
        </MenuSub>
      </MenuContent>
    </Menu>
  )
}

export { Example }
打开 Edit,然后进入 Find 或 Transform。用方向键进入和离开每一层;选择一个操作会关闭整棵菜单树。

快捷键

条目的 shortcut 显示适合当前平台的提示,并设置 aria-keyshortcuts。mod+s 在 Apple 平台上显示为 Command+S,在其他平台上是 Control+S。

在标记里,这只是一个提示:按键处理函数由你的应用负责。数据菜单在关闭时也会注册它们的快捷键。字母和数字匹配物理按键,也包括 Option+N 这样的组合。

控制台
import {
  Menu,
  MenuContent,
  MenuItem,
  MenuSeparator,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu onAction={(value) => log(`Chose ${value}`)}>
      <MenuTrigger>File</MenuTrigger>
      <MenuContent>
        <MenuItem value="new-tab" shortcut="mod+t">
          New tab
        </MenuItem>
        <MenuItem value="new-window" shortcut="mod+n">
          New window
        </MenuItem>
        <MenuItem value="open" shortcut="mod+o">
          Open…
        </MenuItem>
        <MenuSeparator />
        <MenuItem value="save" shortcut="mod+s">
          Save
        </MenuItem>
        <MenuItem value="save-as" shortcut="mod+shift+s">
          Save as…
        </MenuItem>
        <MenuSeparator />
        <MenuItem value="print" shortcut="mod+p">
          Print…
        </MenuItem>
      </MenuContent>
    </Menu>
  )
}

export { Example }
打开 File 查看适合你平台的快捷键提示。选择一个条目来报告它的操作;这个标记示例不会注册全局快捷键。

图标

把装饰性图标放进 ItemIcon,这样屏幕阅读器和键入查找会忽略它们。mirror 会在从右到左的文本中翻转方向性图标。只有图标的条目仍然需要 aria-label。

条目上的 data-has-icon 和菜单上的 data-has-icons 让只有部分条目带图标时文字也能对齐。

控制台
import {
  Menu,
  MenuContent,
  MenuItem,
  MenuItemIcon,
  MenuSeparator,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu onAction={(value) => log(`Chose ${value}`)}>
      <MenuTrigger>
        <svg
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="M12 2v13" />
          <path d="m16 6-4-4-4 4" />
          <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
        </svg>
        Share
      </MenuTrigger>
      <MenuContent>
        <MenuItem value="copy-link">
          <MenuItemIcon>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
              <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
            </svg>
          </MenuItemIcon>
          Copy link
        </MenuItem>
        <MenuItem value="email">
          <MenuItemIcon>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7" />
              <rect x="2" y="4" width="20" height="16" rx="2" />
            </svg>
          </MenuItemIcon>
          Email
        </MenuItem>
        <MenuItem value="reply">
          <MenuItemIcon mirror>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M20 18v-2a4 4 0 0 0-4-4H4" />
              <path d="m9 17-5-5 5-5" />
            </svg>
          </MenuItemIcon>
          Reply
        </MenuItem>
        <MenuSeparator />
        <MenuItem value="download">
          <MenuItemIcon>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M12 15V3" />
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
              <path d="m7 10 5 5 5-5" />
            </svg>
          </MenuItemIcon>
          Download
        </MenuItem>
        <MenuItem value="embed">
          <MenuItemIcon>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m16 18 6-6-6-6" />
              <path d="m8 6-6 6 6 6" />
            </svg>
          </MenuItemIcon>
          Embed
        </MenuItem>
      </MenuContent>
    </Menu>
  )
}

export { Example }
打开 Share 并输入条目的名称。图标不属于条目的无障碍名称,也不参与键入查找匹配的文字。

复选框

复选框条目各自独立切换,默认保持菜单打开。使用 checked 配合 onCheckedChange,非受控条目则使用 defaultChecked。ItemIndicator 渲染勾选标记;keepMounted 在未勾选时保留它的空间。为每种状态设置 data-checked 和 data-unchecked 的样式。

控制台
import {
  Menu,
  MenuCheckboxItem,
  MenuContent,
  MenuGroup,
  MenuGroupLabel,
  MenuItemIndicator,
  MenuSeparator,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu
      onCheckedChange={(checked, details) =>
        log(`${details.value} ${checked ? "on" : "off"}`)
      }
    >
      <MenuTrigger>View</MenuTrigger>
      <MenuContent>
        <MenuGroup>
          <MenuGroupLabel>Appearance</MenuGroupLabel>
          <MenuCheckboxItem value="status-bar" defaultChecked>
            <MenuItemIndicator keepMounted>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </MenuItemIndicator>
            Status bar
          </MenuCheckboxItem>
          <MenuCheckboxItem value="minimap">
            <MenuItemIndicator keepMounted>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </MenuItemIndicator>
            Minimap
          </MenuCheckboxItem>
        </MenuGroup>
        <MenuSeparator />
        <MenuCheckboxItem value="line-numbers" defaultChecked>
          <MenuItemIndicator keepMounted>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M20 6 9 17l-5-5" />
            </svg>
          </MenuItemIndicator>
          Line numbers
        </MenuCheckboxItem>
        <MenuCheckboxItem value="word-wrap">
          <MenuItemIndicator keepMounted>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M20 6 9 17l-5-5" />
            </svg>
          </MenuItemIndicator>
          Word wrap
        </MenuCheckboxItem>
      </MenuContent>
    </Menu>
  )
}

export { Example }
打开 View,切换 Status bar 或 Minimap。菜单保持打开,方便你修改多个设置,控制台会记录每一项。

单选组

单选条目在组内选择一个值,默认保持菜单打开。使用 value 配合 onValueChange,非受控组则使用 defaultValue。如果组需要在菜单的值变更回调中表明自己,给它一个 name。

控制台
import {
  Menu,
  MenuContent,
  MenuGroupLabel,
  MenuItemIndicator,
  MenuRadioGroup,
  MenuRadioItem,
  MenuSeparator,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { For } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu>
      <MenuTrigger>Panel</MenuTrigger>
      <MenuContent>
        <MenuRadioGroup
          name="position"
          defaultValue="bottom"
          onValueChange={(value) => log(`Panel at the ${value}`)}
        >
          <MenuGroupLabel>Position</MenuGroupLabel>
          <For each={["Top", "Bottom", "Right"]}>
            {(option) => (
              <MenuRadioItem value={option.toLowerCase()}>
                <MenuItemIndicator />
                {option}
              </MenuRadioItem>
            )}
          </For>
        </MenuRadioGroup>
        <MenuSeparator />
        <MenuRadioGroup
          defaultValue="comfortable"
          onValueChange={(value) => log(`${value} density`)}
        >
          <MenuGroupLabel>Density</MenuGroupLabel>
          <For each={["Compact", "Comfortable"]}>
            {(option) => (
              <MenuRadioItem value={option.toLowerCase()}>
                <MenuItemIndicator />
                {option}
              </MenuRadioItem>
            )}
          </For>
        </MenuRadioGroup>
      </MenuContent>
    </Menu>
  )
}

export { Example }
打开 Panel 并选择一个位置。每组只有一个条目被勾选,菜单保持打开,控制台会记录这次变更。

上下文菜单

ContextTrigger 在右键点击或长按时打开。给这个区域一个 Tab 停靠点,这样 Shift+F10 和上下文菜单键就能从键盘打开它。在同一区域的其他位置右键点击,会重新定位已打开的菜单。

设置 disabled 可以保留该区域原生的浏览器菜单。上下文触发器也可以传入 payload。

控制台
import {
  Menu,
  MenuContent,
  MenuContextTrigger,
  MenuItem,
  MenuSeparator,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu onAction={(value) => log(`Chose ${value}`)}>
      <MenuContextTrigger tabindex={0}>
        Right-click or long-press here
      </MenuContextTrigger>
      <MenuContent>
        <MenuItem value="back">Back</MenuItem>
        <MenuItem value="forward" disabled>
          Forward
        </MenuItem>
        <MenuItem value="reload">Reload</MenuItem>
        <MenuSeparator />
        <MenuItem value="save">Save page as…</MenuItem>
        <MenuItem value="print">Print…</MenuItem>
      </MenuContent>
    </Menu>
  )
}

export { Example }
右键点击或长按这个区域,或聚焦它并按 Shift+F10。选择一个操作,控制台会记录它。

放置位置

side 和 align 选择起始位置。放不下时,菜单会翻转或平移;data-side 报告它最终落在哪里。逻辑对齐和子菜单按键跟随周围的文本方向。共享的定位约定见浮层指南。

<MenuContent side="right" align="start" />

偏移与碰撞边距

sideOffset 设置间距,alignOffset 沿锚点平移,collisionPadding 在视口周围留出空间。用 --anchor-width 匹配触发器的宽度,用 --available-height 滚动长列表。

<MenuContent sideOffset={8} alignOffset={-4} collisionPadding={24} />

默认的 modal="pointer" 会在关闭菜单时消费一次外部按压。true 还会锁定滚动,并让页面不可交互(inert)。false 会在关闭后让这次外部按压到达它的目标。

<Menu modal={false}>
  <MenuTrigger>Actions</MenuTrigger>
  <MenuContent />
</Menu>

delay 是悬停等待时间,单位毫秒,默认 100。它作用于直接位于该菜单内的子菜单。在 Sub 上设置它可以改变下一层的延迟。

<Menu delay={300}>
  <MenuTrigger>File</MenuTrigger>
  <MenuContent>
    <MenuSub delay={0}>
      <MenuSubTrigger>Open recent</MenuSubTrigger>
      <MenuSubContent />
    </MenuSub>
  </MenuContent>
</Menu>

键盘导航

方向键默认会绕回;loop 为 false 时在两端停止。输入会按名称查找条目。如果条目带有额外的描述性文字,把 label 设为键入查找应该匹配的文字。label 不会替代它的无障碍名称;无障碍名称要用 aria-label。

<Menu loop={false}>
  <MenuTrigger>Status</MenuTrigger>
  <MenuContent>
    <MenuItem value="busy" label="Do not disturb">
      Do not disturb
      <span>Notifications are muted</span>
    </MenuItem>
  </MenuContent>
</Menu>

菜单包含条目、分组和分隔符。对于选项列表旁边的文本字段,比如搜索框或重命名字段,请使用 Popover。在 popover 里,字段保留自己的按键;而在菜单里,指针会把焦点从一个条目移到另一个条目。

关闭后的焦点

菜单在焦点位于内部时关闭,焦点会返回触发器。如果某个操作移除了触发器,或把用户带到别处,就把内容上的 finalFocus 设为选择器、元素或返回元素的函数,或设为 "none" 让焦点留在操作放置的位置。共享的焦点规则见浮层焦点。

<MenuContent finalFocus="#file-list" />

禁用的条目

禁用的条目仍然可以获得焦点,以便用户发现它们,但不能运行,也不能打开子菜单。禁用的 Trigger 是原生禁用的按钮,无法接收焦点。加上 focusableWhenDisabled 可以让它留在 Tab 顺序中,从而承载说明原因的 tooltip;按压仍然不会有任何作用。

控制台
import {
  Menu,
  MenuCheckboxItem,
  MenuContent,
  MenuGroupLabel,
  MenuItem,
  MenuItemIndicator,
  MenuRadioGroup,
  MenuRadioItem,
  MenuSeparator,
  MenuSub,
  MenuSubContent,
  MenuSubTrigger,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <div data-slot="row">
      <Menu onAction={(value) => log(`Chose ${value}`)}>
        <MenuTrigger>Document</MenuTrigger>
        <MenuContent>
          <MenuItem value="undo" shortcut="mod+z" disabled>
            Undo
          </MenuItem>
          <MenuItem value="redo" shortcut="mod+shift+z">
            Redo
          </MenuItem>
          <MenuSeparator />
          <MenuCheckboxItem value="autosave" defaultChecked disabled>
            <MenuItemIndicator>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M20 6 9 17l-5-5" />
              </svg>
            </MenuItemIndicator>
            Autosave
          </MenuCheckboxItem>
          <MenuSeparator />
          <MenuRadioGroup defaultValue="pdf">
            <MenuGroupLabel>Export as</MenuGroupLabel>
            <MenuRadioItem value="pdf">
              <MenuItemIndicator>
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="M20 6 9 17l-5-5" />
                </svg>
              </MenuItemIndicator>
              PDF
            </MenuRadioItem>
            <MenuRadioItem value="docx" disabled>
              <MenuItemIndicator>
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="M20 6 9 17l-5-5" />
                </svg>
              </MenuItemIndicator>
              Word
            </MenuRadioItem>
            <MenuRadioItem value="markdown">
              <MenuItemIndicator>
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="M20 6 9 17l-5-5" />
                </svg>
              </MenuItemIndicator>
              Markdown
            </MenuRadioItem>
          </MenuRadioGroup>
          <MenuSeparator />
          <MenuSub>
            <MenuSubTrigger disabled>
              Move to
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="m9 18 6-6-6-6" />
              </svg>
            </MenuSubTrigger>
            <MenuSubContent>
              <MenuItem>Archive</MenuItem>
            </MenuSubContent>
          </MenuSub>
        </MenuContent>
      </Menu>
      <Menu>
        <MenuTrigger disabled>Locked</MenuTrigger>
        <MenuContent>
          <MenuItem>Unlock</MenuItem>
        </MenuContent>
      </Menu>
    </div>
  )
}

export { Example }
打开 Document,用方向键在各个条目之间移动。禁用的操作仍然可以被发现,但不能运行;Locked 无法打开菜单。

保持菜单打开

普通条目被选中后关闭;复选框和单选条目保持打开。closeOnSelect 可以改变这两种默认行为。选择处理函数也可以阻止默认事件,让菜单为某一次操作保持打开。

<MenuItem closeOnSelect={false} onSelect={() => setZoom(zoom() + 10)}>
  Zoom in
</MenuItem>
<MenuCheckboxItem value="fit" closeOnSelect>
  Fit to window
</MenuCheckboxItem>

容器

菜单就地渲染,并使用顶层。container 把浮层移到另一个元素;子菜单仍留在父浮层内部。等元素存在后再传入实际元素,如浮层指南所述。

<MenuContent container={panel} />

动画

菜单在退场动画期间保持挂载。data-starting-style、data-ending-style、data-side 和 --transform-origin 描述这次过渡。keepMounted 让关闭后的内容继续隐藏;onOpenChangeComplete 在动画结束时报告。

控制台
import {
  Menu,
  MenuContent,
  MenuItem,
  MenuSeparator,
  MenuSub,
  MenuSubContent,
  MenuSubTrigger,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu
      onOpenChange={(open) => log(open ? "Opening" : "Closing")}
      onOpenChangeComplete={(open) =>
        log(open ? "Finished opening" : "Finished closing")
      }
    >
      <MenuTrigger>Animated</MenuTrigger>
      <MenuContent keepMounted>
        <MenuItem>Back</MenuItem>
        <MenuItem>Forward</MenuItem>
        <MenuItem>Reload</MenuItem>
        <MenuSeparator />
        <MenuSub>
          <MenuSubTrigger>
            More tools
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m9 18 6-6-6-6" />
            </svg>
          </MenuSubTrigger>
          <MenuSubContent>
            <MenuItem>Save page as…</MenuItem>
            <MenuItem>Developer tools</MenuItem>
          </MenuSubContent>
        </MenuSub>
      </MenuContent>
    </Menu>
  )
}

export { Example }
打开 Animated,再打开它的 More tools 子菜单,然后关闭它们。控制台会记录 Opening 或 Closing,以及动画结束的时间。

呈现方式

presentation="auto" 在小尺寸触摸屏上使用底部面板(sheet),在其他地方使用 popover;"sheet" 总是请求底部面板。底部面板保留菜单的角色和按键。子菜单替换当前层级,Escape 或朝父级方向的方向键会返回上一层。上下文菜单和菜单栏中的菜单仍然是 popover。

用 data-presentation 或内容的 presentation 状态区分两种布局。底部面板的位移交给 SDK 处理。--sheet-backdrop 设置它的遮罩颜色,除非 modal 为 false,否则底部面板是模态的。浮层指南介绍了共享的呈现方式行为。

控制台
import {
  Menu,
  MenuContent,
  MenuItem,
  MenuSeparator,
  MenuSub,
  MenuSubContent,
  MenuSubTrigger,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Menu presentation="sheet" onAction={(value) => log(`Chose ${value}`)}>
      <MenuTrigger>Options</MenuTrigger>
      <MenuContent>
        <MenuItem value="share">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M12 2v13" />
            <path d="m16 6-4-4-4 4" />
            <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" />
          </svg>
          Share
        </MenuItem>
        <MenuItem value="copy-link">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
            <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
          </svg>
          Copy link
        </MenuItem>
        <MenuSub>
          <MenuSubTrigger>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M12 15V3" />
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
              <path d="m7 10 5 5 5-5" />
            </svg>
            Move to
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m9 18 6-6-6-6" />
            </svg>
          </MenuSubTrigger>
          <MenuSubContent>
            <MenuItem value="inbox">Inbox</MenuItem>
            <MenuItem value="archive">Archive</MenuItem>
          </MenuSubContent>
        </MenuSub>
        <MenuSeparator />
        <MenuItem value="delete" destructive>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M10 11v6" />
            <path d="M14 11v6" />
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
            <path d="M3 6h18" />
            <path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
          </svg>
          Delete
        </MenuItem>
      </MenuContent>
    </Menu>
  )
}

export { Example }
以底部面板打开 Options,进入 Move to,然后返回或选择一个目标位置。你可以向下拖动来关闭底部面板。

受控

传入 open={open()},并在 onOpenChange 中更新 signal。变更会带有原因,details.cancel() 可以拒绝它。控制器可以从另一个控件打开菜单;这种共享模式见状态与事件和控制器。

const [open, setOpen] = createSignal(false)

<Menu open={open()} onOpenChange={(next, details) => setOpen(next)}>
  <MenuTrigger>Actions</MenuTrigger>
  <MenuContent />
</Menu>

Menu 之外的触发器

把外部触发器和同一个菜单连接到 createMenuController<File>()。每个触发器把自己的行作为 payload 传入,内容从状态里读取它。只有活动的触发器会展开并接收返回的焦点。代码也可以带着 payload 和 anchor 打开;Promise 在菜单关闭时兑现。

控制台
import {
  createMenuController,
  Menu,
  MenuContent,
  MenuGroup,
  MenuGroupLabel,
  MenuItem,
  MenuSeparator,
  MenuTrigger,
} from "@ui-sdk/solid/menu"
import { For } from "solid-js"
import { useLog } from "./log"

type File = { name: string; size: string }

const files: File[] = [
  { name: "Roadmap.pdf", size: "2.4 MB" },
  { name: "Budget.xlsx", size: "860 KB" },
  { name: "Team photo.jpg", size: "5.1 MB" },
]

function Example() {
  const menu = createMenuController<File>()
  const log = useLog()

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button
          onClick={async (event) => {
            const result = await menu.open({
              payload: files[0],
              anchor: event.currentTarget,
            })
            log(`Closed with ${result.reason}`)
          }}
        >
          Open {files[0].name} Actions
        </button>
      </div>
      <ul data-slot="list">
        <For each={files}>
          {(file) => (
            <li data-slot="row">
              {file.name}
              <span data-slot="hint">{file.size}</span>
              <MenuTrigger
                controller={menu}
                payload={file}
                aria-label={`Actions for ${file.name}`}
                data-variant="ghost"
                data-size="sm"
              >
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <circle cx="12" cy="12" r="1" />
                  <circle cx="19" cy="12" r="1" />
                  <circle cx="5" cy="12" r="1" />
                </svg>
              </MenuTrigger>
            </li>
          )}
        </For>
      </ul>
      <Menu
        controller={menu}
        onAction={(action) => log(`${action} ${menu.getPayload()?.name}`)}
      >
        <MenuContent<File> align="end">
          {(state) => (
            <>
              <MenuGroup>
                <MenuGroupLabel>{state.payload?.name}</MenuGroupLabel>
                <MenuItem value="open">Open</MenuItem>
                <MenuItem value="rename">Rename</MenuItem>
                <MenuItem value="duplicate">Duplicate</MenuItem>
              </MenuGroup>
              <MenuSeparator />
              <MenuItem value="delete">Delete</MenuItem>
            </>
          )}
        </MenuContent>
      </Menu>
    </div>
  )
}

export { Example }
打开不同文件的操作。同一个菜单会显示活动的行;从代码打开会使用相同的 payload,并报告关闭原因。

items 接受 MenuData:操作、分组、复选框、单选组和子菜单。字符串是标签和值相同的条目的简写。数据菜单即使在关闭时也会注册快捷键;把 itemShortcuts 设为 false 可以关掉这个行为。

onCheckedChange 在 details.value 中报告复选框的值;onValueChange 在 details.group 中报告单选组的名称。两种变更都可以取消。你也可以用同一份数据渲染自己的部件,同时让 items 继续注册快捷键。列表与菜单指南介绍了数据形状。

const fileMenu: MenuData = [
  { value: "open", label: "Open…", shortcut: "mod+o" },
  { type: "separator" },
  { type: "checkbox", value: "toolbar", label: "Toolbar", defaultChecked: true },
  {
    type: "radio-group",
    name: "sort",
    label: "Sort by",
    defaultValue: "name",
    items: [
      { value: "name", label: "Name" },
      { value: "date", label: "Date modified" },
    ],
  },
  { type: "submenu", label: "Share", items: ["Copy link", "Email"] },
]

<Menu items={fileMenu} onAction={(value) => run(value)}>
  <MenuTrigger>File</MenuTrigger>
  <MenuContent />
</Menu>

用共享的组合 API把条目渲染成原生链接。Enter 会像点击一样跟随链接,保留它的 target 和修饰键行为。

<MenuItem render={(props) => <a {...props} href="#composition" />}>
  Composition
</MenuItem>

自定义渲染

原生链接见链接与自定义渲染。共享的组合指南介绍了元素替换和基于状态的渲染。

样式

用 data-highlighted 标记活动条目,data-disabled 标记不可用的操作,data-checked 标记已选中的设置。浮层的尺寸和动画钩子与样式指南共享。

每个部件都有一个 data-slot,比如 menu-item,它的状态属性列在数据属性下。

MenuContent

变量内容
--anchor-widthWidth of the anchor, usually the trigger. Use it to match widths.
--anchor-heightHeight of the anchor.
--available-widthSpace beside the popup, up to the viewport edge. Not inherited either.
--available-heightSpace between the anchor and the viewport edge. Use it for max-height. Not inherited, so a child that needs it copies it on the popup, like [--list-height:var(--available-height)], and reads max-h-(--list-height). The first popup registers both names for the whole page with CSS.registerProperty, so they don't inherit anywhere. A page that needs them to inherit calls it first, with inherits: true. An @property rule can't, since a registration in script wins.
--transform-originThe point on the anchor the popup opens from. Use it to scale from the right place.
--arrow-offsetWhere the anchor's center falls along the popup's edge, kept arrowPadding from the corners. Position a ::before arrow with it.
--drawer-progressWhile it presents as a sheet: how far open the sheet is, from 0 closed to 1 at its largest snap point. Never past 1.
--drawer-dimWhile it presents as a sheet: how dim the page behind is, from 0 to 1. The backdrop's opacity follows it.
--drawer-expandWhile it presents as a sheet: 0 at the second-largest snap point and below, 1 at the largest. With one snap point, the whole travel.
--drawer-stackWhile it presents as a sheet: how many sheets opened from inside this one are open above it, rising smoothly as each one opens. Push it back with it.
--sheet-backdropSet it yourself: the color the page dims to while it presents as a sheet. Black at 0.2 by default.

Viewport

变量内容
--keyboard-insetWhile it presents as a sheet: how many pixels of the page the on-screen keyboard covers, 0 without one.
--visual-viewport-widthWhile it presents as a sheet: the width of the part of the page you can see.
--visual-viewport-heightWhile it presents as a sheet: the height of the part of the page you can see, above the keyboard.
--visual-viewport-topWhile it presents as a sheet: how far the part of the page you can see is scrolled from the top of the layout, as when the keyboard pushes it up.

数据属性

MenuRadioGroup、MenuGroup、MenuGroupLabel、MenuSeparator 和 MenuShortcut 没有状态属性。

MenuTrigger

[data-slot="menu-trigger"]

属性含义
data-closedPresent on a trigger while the menu isn't open from it.
data-openPresent on the trigger that opened the menu, while it's open.

MenuContextTrigger

[data-slot="menu-context-trigger"]

属性含义
data-closedPresent on an area while the menu isn't open from it.
data-disabledPresent when the area is disabled.
data-openPresent on the area that opened the menu, while it's open.

MenuContent

[data-slot="menu-content"]

属性含义
data-closedPresent while the menu is closed, including while it animates out.
data-presentationpopoversheetHow the menu presents this time it's open. Submenus present like their root.
data-nestedPresent on submenus.
data-openPresent while the menu is open. A submenu trigger has it while its submenu is open.
data-starting-stylePresent for the first frame. Style the state you animate from.
data-ending-stylePresent while the menu animates out. Style the state you animate to.
data-sidetoprightbottomleftWhere the menu ended up, after flipping away from edges.
data-alignstartcenterendHow the menu lines up with its trigger.
data-has-iconsPresent while any item inside holds an icon part, so items without one can line up.

MenuItem

[data-slot="menu-item"]

属性含义
data-disabledPresent when the item can't be chosen.
data-highlightedPresent on the item with keyboard focus or under the pointer.
data-has-iconPresent on an item while it holds an icon part.

MenuCheckboxItem

[data-slot="menu-checkbox-item"]

属性含义
data-checkedPresent on checked checkbox items, and on the radio item that's its group's value.
data-uncheckedPresent on items that aren't checked.
data-highlightedPresent on the item with keyboard focus or under the pointer.

MenuItemIndicator

[data-slot="menu-item-indicator"]

属性含义
data-checkedPresent while its item is checked.
data-uncheckedPresent while its item isn't checked, with keepMounted.

MenuRadioItem

[data-slot="menu-radio-item"]

属性含义
data-checkedPresent on checked checkbox items, and on the radio item that's its group's value.
data-uncheckedPresent on items that aren't checked.
data-highlightedPresent on the item with keyboard focus or under the pointer.

MenuItemIcon

[data-slot="menu-item-icon"]

属性含义
data-mirrorPresent on an icon that flips in right-to-left text, with mirror.

API 参考

属性和回调与下面相同,都作为 Solid props。

container?DocumentFragment | Element | null
Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
open?boolean
Whether the menu is open. Pass it to control the menu.
defaultOpen?boolean
Whether the menu starts open, when uncontrolled.
onOpenChange?((open: boolean, details: ChangeDetails<MenuOpenChangeReason>) => void)
Runs when the menu wants to open or close. details.reason says why, and details.cancel() stops it.
onOpenChangeComplete?((open: boolean) => void)
Runs once the menu has finished opening or closing, after any animation.
onPayloadChange?((payload: unknown, details: ChangeDetails<MenuPayloadChangeReason>) => void)
Runs when the payload the content shows changes: a trigger or context area with another payload opens the menu, or takes the open menu over, which fires no onOpenChange, and so does a controller's open({ payload }) on the open menu. details.cancel() keeps the previous payload.
onAction?((value: string, details: MenuActionDetails) => unknown)
Runs for every plain item, including items in submenus, with the item's value. Return a Promise to mark the item pending until it settles: it gets data-pending, aria-busy and aria-disabled, the menu stays open, and choosing it again waits. It closes once the Promise resolves, and a rejection keeps it open with the reason in the item's error state until the next try.
pendingAnnouncement?string
What screen readers hear once an item has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.
onCheckedChange?((checked: boolean, details: MenuCheckedChangeDetails) => void)
Runs when any checkbox item in the menu or its submenus toggles, with the item's value in details.value. Made for data menus.
onValueChange?((value: string, details: MenuValueChangeDetails) => void)
Runs when any radio group in the menu or its submenus changes, with the group in details.group. Made for data menus.
items?MenuData
The menu as data. Renders the content for you, unless you place a content part of your own, and runs the items' shortcuts.
itemShortcuts?boolean
Whether a data menu runs its items' shortcuts while closed.
loop?boolean
Whether arrow keys wrap from the last item to the first.
delay?number
Milliseconds the pointer rests on a submenu trigger before its submenu opens.
presentation?PresentationSetting<"popover">
How the menu presents. "sheet" slides it up from the bottom of the screen, where it can be swiped away and submenus open in its place, and "auto" does that on small touch screens. Decided each time it opens; the server renders "popover" for "auto". A context menu and a menu in a menubar are always popovers.
controller?MenuController
Opens, closes and inspects the menu from anywhere, and connects triggers outside it. Create one with createMenuController().
modal?"pointer" | boolean
"pointer": an outside press only closes the menu. true: also locks scroll, traps focus and makes the rest of the page inert. false: outside presses reach what they hit.
dismissible?boolean
Whether Escape, an outside press, focus or the window leaving, Android's back gesture and a sheet's swipe can close it. Triggers, Close parts and the controller always can. Pass false while it holds unsaved work, and ask in onDismissAttempt.
onDismissAttempt?function
Runs when dismissible refused a dismissal made on purpose: Escape, an outside press, back or a swipe. Focus or the window leaving is refused without it. Ask "Discard changes?" here.
debug?boolean
Logs every state change with its reason to the console, in development builds.

菜单之外的触发器还接受 controller。

disabled?boolean
Stops the trigger from opening the menu. A native button can't be focused or pressed, unless focusableWhenDisabled is set.
focusableWhenDisabled?boolean
Keeps a disabled trigger in the tab order with aria-disabled instead of the native attribute, so it can host a tooltip that says why. Presses still do nothing.
payload?unknown
Data for the content to render when this trigger opens the menu, like the row it belongs to.
shortcut?string
A keyboard shortcut that opens the menu from anywhere, like "mod+j". mod is Command on Apple platforms and Control elsewhere. Sets aria-keyshortcuts.
controller?PopupController<any, MenuOpenChangeReason, MenuOpenOptions, string, MenuPayloadChangeReason>
Connects a trigger outside the menu, like one per table row, to the menu with this controller.
disabled?boolean
Stops a right-click, a long press or Shift+F10 from opening the menu here. The browser's own menu shows instead.
payload?unknown
Data for the content to render when this area opens the menu, like the row it belongs to.
controller?PopupController<any, MenuOpenChangeReason, MenuOpenOptions, string, MenuPayloadChangeReason>
Connects an area outside the menu to the menu with this controller.
side?Side
Which side of the anchor the popup opens on. Flips to the other side when there isn't room. Which side of the trigger the menu opens on. Submenus open to the side, mirrored in right-to-left layouts.
align?Align
How the popup lines up with the anchor along that side. start and end follow the reading direction. How the menu lines up with the trigger along that side.
sideOffset?number
Gap between the anchor and the popup, in pixels. Gap between the trigger and the menu, in pixels.
alignOffset?number
Shift along the anchor, in pixels. Shift along the trigger, in pixels. Submenus default to lining up their first item with the trigger.
collisionPadding?number
Space to keep from the viewport edges, in pixels.
arrowPadding?number
Space to keep between the arrow and the popup's corners, in pixels.
anchor?string | Anchor | null
Positions the popup against this instead of its trigger: an element, a CSS selector, a point like { x, y }, or anything with getBoundingClientRect(). It's read on every check, so it can move. A controller's open({ anchor }) wins for that open.
container?DocumentFragment | Element | null
Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.
finalFocus?PopupFocusTarget
Where focus goes when the menu closes while focus is inside it. "trigger" returns it to the trigger and "none" leaves it. A CSS selector, an element or a function picks a specific element.
keepMounted?boolean
Whether the menu stays in the page, hidden, while closed. Its content keeps its state between opens.
value?string
Passed to onAction when the item runs.
label?string
The text typeahead matches, when the content isn't plain text. It isn't the accessible name: use aria-label for that.
disabled?boolean
Keeps the item focusable but stops it from running, as the menu pattern asks. Sets data-disabled and aria-disabled.
destructive?boolean
Styles the item as dangerous, like Delete. Sets data-destructive.
shortcut?string
A keyboard shortcut like "mod+n". Shows ⌘N on Apple platforms and Ctrl+N elsewhere, and sets aria-keyshortcuts.
closeOnSelect?boolean
Whether running the item closes the menu.
onSelect?((event: Event) => unknown)
Runs when the item is selected, by pointer or keyboard, with the event that selected it, or a new select Event when no DOM event did. Call event.preventDefault() to keep the menu open and skip onAction. Return a Promise to mark the item pending until it settles, like onAction.
valuestring
Identifies the item, in the menu's onCheckedChange.
label?string
The text typeahead matches, when the content isn't plain text. It isn't the accessible name: use aria-label for that.
disabled?boolean
Keeps the item focusable but stops it from toggling, as the menu pattern asks.
checked?boolean
Whether the item is checked. Pass it to control the item.
defaultChecked?boolean
Whether the item starts checked, when uncontrolled.
onCheckedChange?((checked: boolean, details: ChangeDetails<MenuCheckedChangeReason>) => void)
Runs when the item wants to toggle. details.reason says why, and details.cancel() stops it.
closeOnSelect?boolean
Whether toggling closes the menu.
value?T | null
The selected value. Pass it to control the group. null selects nothing.
defaultValue?T | null
The value selected at first, when uncontrolled.
onValueChange?((value: T, details: ChangeDetails<MenuValueChangeReason>) => void)
Runs when the selection wants to change. details.reason says why, and details.cancel() stops it.
name?string
Identifies the group in the menu's onValueChange. Defaults to a generated id, and the group then keeps its choice by its place among the menu's groups. Give a group that's shown only some of the time a name, so it keeps its own.
valuestring
Selected in the group when the item is chosen.
label?string
The text typeahead matches, when the content isn't plain text. It isn't the accessible name: use aria-label for that.
disabled?boolean
Keeps the item focusable but stops it from being chosen, as the menu pattern asks.
closeOnSelect?boolean
Whether choosing the item closes the menu.
keepMounted?boolean
Whether the indicator stays in the page while its item is unchecked, so it can be styled or animated in both states.
mirror?boolean
Flips the icon horizontally in right-to-left text, for icons that point a way, like arrows and chevrons. Icons that picture a thing, like a clock or a check, stay as they are.
debug?boolean
Logs every state change with its reason to the console, in development builds.
open?boolean
Whether the submenu is open. Pass it to control the submenu.
defaultOpen?boolean
Whether the submenu starts open, when uncontrolled.
onOpenChange?((open: boolean, details: ChangeDetails<MenuOpenChangeReason>) => void)
Runs when the menu wants to open or close. details.reason says why, and details.cancel() stops it.
onOpenChangeComplete?((open: boolean) => void)
Runs once the menu has finished opening or closing, after any animation.
loop?boolean
Whether arrow keys wrap from the last item to the first.
delay?number
Milliseconds the pointer rests on a submenu trigger before its submenu opens.
controller?MenuController
Opens, closes and inspects the submenu. Create one with createMenuController(). Triggers outside the menu can't connect to it.
disabled?boolean
Keeps the submenu trigger focusable but stops it from opening its submenu, as the menu pattern asks. Sets data-disabled and aria-disabled.

它接受与 MenuContent 相同的 props。

它们没有自己的 props,只有它们渲染的元素所带的 props。

状态

每个部件的渲染函数、基于状态的类名和槽位会收到什么。

MenuTrigger, MenuContextTrigger and MenuSubTrigger:

openboolean
Whether the menu is open from this trigger.
disabledboolean
Whether the trigger's disabled prop is set, or the menubar it's in is disabled.

MenuContent:

openboolean
Whether the menu is open. False while it animates out.
nestedboolean
Whether this is a submenu.
presentationPresentation
How the menu is shown.
payloadPayload | undefined
The payload of the last open, from the trigger that opened it or a controller, typed as the controller's Payload.

MenuItem:

highlightedboolean
Whether the item has keyboard focus or is under the pointer.
disabledboolean
Whether the item can't be chosen.
pendingboolean
Whether its onSelect or onAction Promise is running.
errorunknown
Why its last action failed, until it runs again.

MenuCheckboxItem and MenuRadioItem:

highlightedboolean
Whether the item has keyboard focus or is under the pointer.
disabledboolean
Whether the item can't be chosen.
checkedboolean
Whether the item is on: its checked prop when you pass one, otherwise defaultChecked until a press changes it.

MenuRadioGroup:

valuestring | null
The selected value, or null when nothing is selected.

MenuItemIndicator:

checkedboolean
Whether its checkbox item is on, or its radio item is its group's value. While false, the indicator isn't shown unless keepMounted is set.
disabledboolean
Whether the item can't be chosen.

MenuItemIcon:

mirrorboolean
Whether it flips in right-to-left text.

原因

details.reason 说明菜单或子菜单为什么打开或关闭。

trigger-pressMouseEvent | KeyboardEvent | TouchEvent
Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its touchend.
trigger-hoverPointerEvent
The pointer rested on a trigger, or left it, with hover opening.
item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
outside-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
close-pressMouseEvent | KeyboardEvent | SubmitEvent
A Close part was pressed, or a form with method="dialog" was submitted.
focus-outKeyboardEvent | FocusEvent
Focus left the layer, or Tab moved it out.
window-blurFocusEvent
The window lost focus.
submenu-switchKeyboardEvent | PointerEvent
Another submenu in the same menu, or another menu in the same menubar, took over.
parent-closenone
The parent layer closed.
trigger-releasePointerEvent
A press-and-hold open was released outside the popup.
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.
anchor-hiddennone
The element the popup sits beside stopped rendering, like a trigger a breakpoint hides.
imperativenone
A controller or api call.

payload 变更时,它说明是什么打开了菜单或接管了它。

trigger-pressMouseEvent | KeyboardEvent | TouchEvent
Click, tap, Enter or Space on the part that opens, closes or toggles. Arrow keys that open a menu or submenu count too. A tap on a combobox's input that opens a sheet reports its touchend.
trigger-hoverPointerEvent
The pointer rested on a trigger, or left it, with hover opening.
shortcutKeyboardEvent
A keyboard shortcut, like a trigger's shortcut.
imperativenone
A controller or api call.

dismissible 为 false 时,onDismissAttempt 报告的、被拒绝的关闭尝试:

outside-pressMouseEvent
A press outside the layer.
escape-keyKeyboardEvent
Escape, or a submenu's close key (ArrowLeft in left-to-right layouts).
backEvent
Going back: the Android back button or gesture, or Backspace in an empty command input, which returns to the previous page.
swipeTouchEvent | PointerEvent
A swipe gesture: a finger, mouse or pen dragged it.

复选框条目在 onCheckedChange 中报告它们为什么切换:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone
A controller or api call.

单选组在 onValueChange 中报告它们的值为什么变化:

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone
A controller or api call.

控制器

用 createMenuController<Payload>() 创建一个,并作为 controller 传给菜单以及它之外的所有触发器。Payload 是触发器和 open() 传入数据的类型。

每个写入方法都接受一个可选的 { reason, event },传给 onOpenChange。open() 还接受 focus:"first"、"last"、"popup" 或 "none"。

isOpen()() => boolean
Whether it's open. False as soon as it starts closing, while it still animates out.
setOpen(open, options?)(open: boolean, options?: PopupChangeOptions<MenuOpenChangeReason> | undefined) => boolean
Opens or closes it. Returns false when the change was canceled or it was already open or closed.
open(options?)(options?: (PopupChangeOptions<MenuPayloadChangeReason> & { payload?: Payload | undefined; anchor?: Anchor | undefined; signal?: AbortSignal | undefined; } & MenuOpenOptions) | undefined) => Promise<...>
Opens it, and resolves once it closes, with why, how and any return value. Resolves exactly once and never rejects: on the next close from any source, when signal aborts, or with reason "unmount" when the component leaves the page.
close(options?)(options?: (PopupChangeOptions<MenuOpenChangeReason> & { returnValue?: Result | undefined; }) | undefined) => boolean
Closes it. returnValue is passed to the promise open() returned. Returns false when the close was canceled or it was already closed.
toggle(options?)(options?: PopupChangeOptions<MenuOpenChangeReason> | undefined) => boolean
Opens it when it's closed, and closes it when it's open. Returns false when the change was canceled.
getPayload()() => Payload | undefined
The payload of the last open, from a controller or the trigger that opened it.
focus()() => void
Moves focus to the trigger that opened it last, or the first trigger.

事件

回调先收到新状态,然后收到详情。

属性所属收到
onOpenChangeMenu(open, details):新状态,以及原因
onOpenChangeCompleteMenu(open),在动画之后
onPayloadChangeMenu(payload, details):内容的新 payload,以及原因
onActionMenu每个普通条目都会收到 (value, { event }),包括子菜单里的条目
onCheckedChangeMenu(checked, details),条目的值在 details.value 中。用于数据菜单
onValueChangeMenu(value, details),组的名称在 details.group 中。用于数据菜单
onDismissAttemptMenu({ reason, event }),在关闭尝试被拒绝时
onSelectMenuItem(event),在菜单关闭之前。event.preventDefault() 会让它保持打开
onCheckedChangeMenuCheckboxItem(checked, details),在菜单的 onCheckedChange 之前
onValueChangeMenuRadioGroup(value, details),在菜单的 onValueChange 之前

无障碍

菜单遵循 WAI-ARIA 菜单按钮模式。

经过测试的行为

下面每一行都是一个自动化测试。

Trigger
  • Advertises its menu and reflects the open state.
  • Click opens the menu and moves focus into it.
  • Click on the open trigger closes the menu.
  • Enter opens the menu and focuses the first item.
  • Space opens the menu and focuses the first item.
  • ArrowDown opens the menu and focuses the first item.
  • ArrowUp opens the menu and focuses the last item.
  • Open written back during openchange keeps focus on the last item. 仅在 Web components 运行。
  • Open written back after openchange keeps focus on the last item. 仅在 Web components 运行。
  • SetOpen(true) on an open menu leaves focus where it is. 仅在 Web components 运行。
  • A click on a trigger in a shadow root opens the menu, and it stays open. 仅在 Vue 和 web components 运行。
Keyboard navigation
  • ArrowDown and ArrowUp move between items, skipping separators and labels.
  • ArrowDown and ArrowUp skip items the page hides.
  • Disabled items are focusable.
  • Focus wraps at both ends.
  • Home and End move to the first and last items.
  • Typing a character moves to the next item that starts with it.
  • Typing several characters quickly matches the whole prefix.
Activation
  • Enter on an item runs it, closes the menu and returns focus.
  • Clicking an item runs it and closes the menu.
  • Disabled items do nothing.
  • Checkbox items toggle and keep the menu open.
  • Radio items select one value and keep the menu open.
  • Hovering an item highlights it.
Dismissal
  • Escape closes the menu and returns focus to the trigger.
  • Clicking outside closes the menu.
  • Escape while an input method is composing text leaves the menu open.
  • Pressing a scrollbar outside the menu leaves it open.
  • Tab closes the menu.
Submenu
  • The submenu trigger advertises its menu.
  • ArrowRight opens the submenu and focuses its first item.
  • Enter opens the submenu and focuses its first item.
  • Space opens the submenu and focuses its first item.
  • ArrowLeft closes the submenu and returns focus to its trigger.
  • Nested submenus open and run their items.
  • Submenu keyboard navigation stays inside the submenu.
  • Keys pressed in quick succession are never lost.
  • Clicking outside closes every menu.

运行于 React、Vue 和 web components。

在每个经过测试的框架里,屏幕阅读器听到的内容相同,由虚拟屏幕阅读器记录:

  • Announcements while using the menu with a keyboard.
  • Item shortcuts are announced.

运行于 React、Vue 和 web components。