导航

v2.1.0
表单

列表框

供用户选择的选项列表,也是组合框和命令面板打开时显示的列表。

本页内容

列表框提供一组选项供用户选择。组合框和命令面板打开时都会显示列表框,列表框也可以独立放在页面中。样式表根据 ARIA 属性呈现各个状态,脚本更新属性,管理当前活动项、按键行为和选中项。独立列表框由 listbox 行为脚本驱动,组合框和命令面板则通过各自的输入字段控制列表。

列表框

<div class="sheet sheet-flat max-w(320) mx-auto">  <div class="listbox" role="listbox" aria-label="Framework" tabindex="0" aria-activedescendant="fw-astro">    <div class="listbox-option" role="option" id="fw-astro" aria-selected="true" aria-checked="true">      Astro    </div>    <div class="listbox-option" role="option" id="fw-next" aria-checked="false">Next.js</div>    <div class="listbox-option" role="option" id="fw-svelte" aria-checked="false">SvelteKit</div>    <div class="listbox-option" role="option" id="fw-nuxt" aria-checked="false" aria-disabled="true">      Nuxt    </div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="sheet sheet-flat max-w(320) mx-auto">      <div className="listbox" role="listbox" aria-label="Framework" tabIndex={0} aria-activedescendant="fw-astro">        <div className="listbox-option" role="option" id="fw-astro" aria-selected="true" aria-checked="true">          Astro        </div>        <div className="listbox-option" role="option" id="fw-next" aria-checked="false">Next.js</div>        <div className="listbox-option" role="option" id="fw-svelte" aria-checked="false">          SvelteKit        </div>        <div className="listbox-option" role="option" id="fw-nuxt" aria-checked="false" aria-disabled="true">          Nuxt        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="sheet sheet-flat max-w(320) mx-auto" {@attach attach}>  <div class="listbox" role="listbox" aria-label="Framework" tabindex="0" aria-activedescendant="fw-astro">    <div class="listbox-option" role="option" id="fw-astro" aria-selected="true" aria-checked="true">      Astro    </div>    <div class="listbox-option" role="option" id="fw-next" aria-checked="false">Next.js</div>    <div class="listbox-option" role="option" id="fw-svelte" aria-checked="false">SvelteKit</div>    <div class="listbox-option" role="option" id="fw-nuxt" aria-checked="false" aria-disabled="true">      Nuxt    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="sheet sheet-flat max-w(320) mx-auto">    <div class="listbox" role="listbox" aria-label="Framework" tabindex="0" aria-activedescendant="fw-astro">      <div class="listbox-option" role="option" id="fw-astro" aria-selected="true" aria-checked="true">        Astro      </div>      <div class="listbox-option" role="option" id="fw-next" aria-checked="false">Next.js</div>      <div class="listbox-option" role="option" id="fw-svelte" aria-checked="false">SvelteKit</div>      <div class="listbox-option" role="option" id="fw-nuxt" aria-checked="false" aria-disabled="true">        Nuxt      </div>    </div>  </div></template>
点击选项,或聚焦列表后用方向键移动,再按 Enter 或空格键选择。

#两种状态与对应的属性

列表框分别标记键盘当前指向的选项和已经选中的选项。

  • 活动项由 aria-selected="true" 标记,是方向键当前指向、按 Enter 即可选中的选项。该选项使用胶囊标签色调。指针所在的行也会立即显示相同的色调,无淡入效果。
  • 选中项由 aria-checked="true" 标记,表示已设置的值,行尾显示对勾。带有 aria-checked 的选项在两种状态下都为对勾预留空间,标签位置因此保持不变。

焦点通常留在列表或文本字段上,由 aria-activedescendant 指明当前活动项。选项本身获得焦点时,还会显示墨色轮廓。

#带附加内容的选项

将 icon 用于行首图标。listbox-body 将标题放在 listbox-description 上方,listbox-end 在行尾放置快捷键或提示。listbox-group 将一组选项及其 listbox-label 包在一起,listbox-separator 在组之间绘制分隔线。

带附加内容的选项

<div class="sheet sheet-flat max-w(360) mx-auto">  <div class="listbox" role="listbox" aria-label="Commands">    <div class="listbox-group" role="group" aria-labelledby="rich-suggestions">      <div class="listbox-label" id="rich-suggestions">Suggestions</div>      <div class="listbox-option" role="option" aria-selected="true">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <path d="M3 8L13 8" /><path d="M8 3L8 13" />        </svg> New project <span class="listbox-end"><kbd class="kbd">⌘</kbd><kbd class="kbd">N</kbd></span>      </div>      <div class="listbox-option" role="option">        <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">          <circle cx="7" cy="7" r="4.5" /><path d="M10.182 10.182L14 14" />        </svg>        <span class="listbox-body">          <span>Search deployments</span>          <span class="listbox-description">By branch, commit or author</span>        </span>      </div>    </div>    <hr class="listbox-separator">    <div class="listbox-group" role="group" aria-labelledby="rich-team">      <div class="listbox-label" id="rich-team">Team</div>      <div class="listbox-option" role="option">        <span class="avatar avatar-xs">          <img class="avatar-image" src="/demo/portrait-1.svg" alt>        </span> Ada Lovelace      </div>      <div class="listbox-option" role="option">        <span class="avatar avatar-xs">          <img class="avatar-image" src="/demo/portrait-2.svg" alt>        </span> Alan Turing      </div>    </div>  </div></div>
import PlusIcon from '@master/icons-react/native/16/soft/plus'import SearchIcon from '@master/icons-react/native/16/soft/search'<div className="sheet sheet-flat max-w(360) mx-auto">  <div className="listbox" role="listbox" aria-label="Commands">    <div className="listbox-group" role="group" aria-labelledby="rich-suggestions">      <div className="listbox-label" id="rich-suggestions">Suggestions</div>      <div className="listbox-option" role="option" aria-selected="true">        <PlusIcon className="icon" /> New project <span className="listbox-end">          <kbd className="kbd">⌘</kbd><kbd className="kbd">N</kbd>        </span>      </div>      <div className="listbox-option" role="option">        <SearchIcon className="icon" />        <span className="listbox-body">          <span>Search deployments</span>          <span className="listbox-description">By branch, commit or author</span>        </span>      </div>    </div>    <hr className="listbox-separator" />    <div className="listbox-group" role="group" aria-labelledby="rich-team">      <div className="listbox-label" id="rich-team">Team</div>      <div className="listbox-option" role="option">        <span className="avatar avatar-xs">          <img className="avatar-image" src="/demo/portrait-1.svg" alt="" />        </span> Ada Lovelace      </div>      <div className="listbox-option" role="option">        <span className="avatar avatar-xs">          <img className="avatar-image" src="/demo/portrait-2.svg" alt="" />        </span> Alan Turing      </div>    </div>  </div></div>
<script>  import PlusIcon from '@master/icons-svelte/native/16/soft/plus'  import SearchIcon from '@master/icons-svelte/native/16/soft/search'</script><div class="sheet sheet-flat max-w(360) mx-auto">  <div class="listbox" role="listbox" aria-label="Commands">    <div class="listbox-group" role="group" aria-labelledby="rich-suggestions">      <div class="listbox-label" id="rich-suggestions">Suggestions</div>      <div class="listbox-option" role="option" aria-selected="true">        <PlusIcon class="icon" /> New project <span class="listbox-end"><kbd class="kbd">⌘</kbd><kbd class="kbd">N</kbd></span>      </div>      <div class="listbox-option" role="option">        <SearchIcon class="icon" />        <span class="listbox-body">          <span>Search deployments</span>          <span class="listbox-description">By branch, commit or author</span>        </span>      </div>    </div>    <hr class="listbox-separator">    <div class="listbox-group" role="group" aria-labelledby="rich-team">      <div class="listbox-label" id="rich-team">Team</div>      <div class="listbox-option" role="option">        <span class="avatar avatar-xs">          <img class="avatar-image" src="/demo/portrait-1.svg" alt>        </span> Ada Lovelace      </div>      <div class="listbox-option" role="option">        <span class="avatar avatar-xs">          <img class="avatar-image" src="/demo/portrait-2.svg" alt>        </span> Alan Turing      </div>    </div>  </div></div>
<script setup>import PlusIcon from '@master/icons-vue/native/16/soft/plus'import SearchIcon from '@master/icons-vue/native/16/soft/search'</script><template>  <div class="sheet sheet-flat max-w(360) mx-auto">    <div class="listbox" role="listbox" aria-label="Commands">      <div class="listbox-group" role="group" aria-labelledby="rich-suggestions">        <div class="listbox-label" id="rich-suggestions">Suggestions</div>        <div class="listbox-option" role="option" aria-selected="true">          <PlusIcon class="icon" /> New project <span class="listbox-end"><kbd class="kbd">⌘</kbd><kbd class="kbd">N</kbd></span>        </div>        <div class="listbox-option" role="option">          <SearchIcon class="icon" />          <span class="listbox-body">            <span>Search deployments</span>            <span class="listbox-description">By branch, commit or author</span>          </span>        </div>      </div>      <hr class="listbox-separator">      <div class="listbox-group" role="group" aria-labelledby="rich-team">        <div class="listbox-label" id="rich-team">Team</div>        <div class="listbox-option" role="option">          <span class="avatar avatar-xs">            <img class="avatar-image" src="/demo/portrait-1.svg" alt>          </span> Ada Lovelace        </div>        <div class="listbox-option" role="option">          <span class="avatar avatar-xs">            <img class="avatar-image" src="/demo/portrait-2.svg" alt>          </span> Alan Turing        </div>      </div>    </div>  </div></template>

#搜索结果

搜索结果要说明它的位置和匹配的内容。listbox-path 是标题下方的一行小字,每一级各用一个 listbox-crumb;listbox-excerpt 是匹配的段落,最多两行。把输入的文字包在 mark 中:在选项里它会采用标题的文字颜色和字重,因此在弱化的文字行中也能找到。

搜索结果

<div class="sheet sheet-flat max-w(420) mx-auto">  <div class="listbox" role="listbox" aria-label="Results">    <div class="listbox-option" role="option" aria-selected="true">      <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">        <path d="M2.5 5.75L13.5 5.75" /><path d="M2.5 10.25L13.5 10.25" /><path d="M6.5 2.5L4.5 13.5" /><path d="M11.5 2.5L9.5 13.5" />      </svg>      <span class="listbox-body">        <span>Retune <mark class="mark">token</mark>s</span>        <span class="listbox-path">          <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span><span class="listbox-crumb">Theming</span>        </span>        <span class="listbox-excerpt">          Override a <mark class="mark">token</mark> after the import. Every component that reads it follows.        </span>      </span>    </div>    <div class="listbox-option" role="option">      <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">        <path d="M4.5 2L9.0858 2A1 1 0 0 1 9.7929 2.2929L12.2071 4.7071A1 1 0 0 1 12.5 5.4142L12.5 13A1 1 0 0 1 11.5 14L4.5 14A1 1 0 0 1 3.5 13L3.5 3A1 1 0 0 1 4.5 2Z" /><path d="M10 2.5V4.4A0.1 0.1 0 0 0 10.1 4.5H12L12.2409 4.7427A0.9993 0.9993 0 0 1 12.5 5.4142V5.5H10.1Q9.6444 5.5 9.3222 5.1778Q9 4.8556 9 4.4V2A1.1002 1.1002 0 0 1 9.3761 2.0431A1.0001 1.0001 0 0 1 9.7929 2.2929L10 2.5Z" fill="currentColor" stroke="none" fill-rule="evenodd" />      </svg>      <span class="listbox-body">        <span>Default theme</span>        <span class="listbox-path">          <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span>        </span>        <span class="listbox-excerpt">          Moonstone and obsidian: the default materials, <mark class="mark">token</mark> roles and implementation values in Master UI.        </span>      </span>    </div>    <div class="listbox-option" role="option">      <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">        <path d="M4.5 2L9.0858 2A1 1 0 0 1 9.7929 2.2929L12.2071 4.7071A1 1 0 0 1 12.5 5.4142L12.5 13A1 1 0 0 1 11.5 14L4.5 14A1 1 0 0 1 3.5 13L3.5 3A1 1 0 0 1 4.5 2Z" /><path d="M10 2.5V4.4A0.1 0.1 0 0 0 10.1 4.5H12L12.2409 4.7427A0.9993 0.9993 0 0 1 12.5 5.4142V5.5H10.1Q9.6444 5.5 9.3222 5.1778Q9 4.8556 9 4.4V2A1.1002 1.1002 0 0 1 9.3761 2.0431A1.0001 1.0001 0 0 1 9.7929 2.2929L10 2.5Z" fill="currentColor" stroke="none" fill-rule="evenodd" />      </svg>      <span class="listbox-body">        <span>Customization</span>        <span class="listbox-path">          <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span>        </span>      </span>    </div>  </div></div>
import HashIcon from '@master/icons-react/native/16/soft/hash'import FileIcon from '@master/icons-react/native/16/soft/file'<div className="sheet sheet-flat max-w(420) mx-auto">  <div className="listbox" role="listbox" aria-label="Results">    <div className="listbox-option" role="option" aria-selected="true">      <HashIcon className="icon" />      <span className="listbox-body">        <span>Retune <mark className="mark">token</mark>s</span>        <span className="listbox-path">          <span className="listbox-crumb">Guide</span><span className="listbox-crumb">Customizing</span><span className="listbox-crumb">Theming</span>        </span>        <span className="listbox-excerpt">          Override a <mark className="mark">token</mark> after the import. Every component that reads it follows.        </span>      </span>    </div>    <div className="listbox-option" role="option">      <FileIcon className="icon" />      <span className="listbox-body">        <span>Default theme</span>        <span className="listbox-path">          <span className="listbox-crumb">Guide</span><span className="listbox-crumb">Customizing</span>        </span>        <span className="listbox-excerpt">          Moonstone and obsidian: the default materials, <mark className="mark">token</mark> roles and implementation values in Master UI.        </span>      </span>    </div>    <div className="listbox-option" role="option">      <FileIcon className="icon" />      <span className="listbox-body">        <span>Customization</span>        <span className="listbox-path">          <span className="listbox-crumb">Guide</span><span className="listbox-crumb">Customizing</span>        </span>      </span>    </div>  </div></div>
<script>  import HashIcon from '@master/icons-svelte/native/16/soft/hash'  import FileIcon from '@master/icons-svelte/native/16/soft/file'</script><div class="sheet sheet-flat max-w(420) mx-auto">  <div class="listbox" role="listbox" aria-label="Results">    <div class="listbox-option" role="option" aria-selected="true">      <HashIcon class="icon" />      <span class="listbox-body">        <span>Retune <mark class="mark">token</mark>s</span>        <span class="listbox-path">          <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span><span class="listbox-crumb">Theming</span>        </span>        <span class="listbox-excerpt">          Override a <mark class="mark">token</mark> after the import. Every component that reads it follows.        </span>      </span>    </div>    <div class="listbox-option" role="option">      <FileIcon class="icon" />      <span class="listbox-body">        <span>Default theme</span>        <span class="listbox-path">          <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span>        </span>        <span class="listbox-excerpt">          Moonstone and obsidian: the default materials, <mark class="mark">token</mark> roles and implementation values in Master UI.        </span>      </span>    </div>    <div class="listbox-option" role="option">      <FileIcon class="icon" />      <span class="listbox-body">        <span>Customization</span>        <span class="listbox-path">          <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span>        </span>      </span>    </div>  </div></div>
<script setup>import HashIcon from '@master/icons-vue/native/16/soft/hash'import FileIcon from '@master/icons-vue/native/16/soft/file'</script><template>  <div class="sheet sheet-flat max-w(420) mx-auto">    <div class="listbox" role="listbox" aria-label="Results">      <div class="listbox-option" role="option" aria-selected="true">        <HashIcon class="icon" />        <span class="listbox-body">          <span>Retune <mark class="mark">token</mark>s</span>          <span class="listbox-path">            <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span><span class="listbox-crumb">Theming</span>          </span>          <span class="listbox-excerpt">            Override a <mark class="mark">token</mark> after the import. Every component that reads it follows.          </span>        </span>      </div>      <div class="listbox-option" role="option">        <FileIcon class="icon" />        <span class="listbox-body">          <span>Default theme</span>          <span class="listbox-path">            <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span>          </span>          <span class="listbox-excerpt">            Moonstone and obsidian: the default materials, <mark class="mark">token</mark> roles and implementation values in Master UI.          </span>        </span>      </div>      <div class="listbox-option" role="option">        <FileIcon class="icon" />        <span class="listbox-body">          <span>Customization</span>          <span class="listbox-path">            <span class="listbox-crumb">Guide</span><span class="listbox-crumb">Customizing</span>          </span>        </span>      </div>    </div>  </div></template>
  • 图标始终与标题所在的一行对齐,无论下方是路径、说明还是摘录。标题搭配路径或说明时仍是一个选项行,因此 listbox-end 与这两行文字的中央对齐;摘录会让文字超出选项行的高度,此时 listbox-end 也改为与标题对齐。
  • 路径的各级是文字。一个选项只有一个目标,所以它们不是面包屑导航的链接。
  • 只要有一个结果带图标,就让每个结果都带图标:页面用文档图标,页面内的标题用井号,即可覆盖没有专属图标的结果。

#筛选

脚本为不匹配的选项设置 hidden 属性来筛选。随后,:has() 会自动处理以下两种情况,无需额外脚本:

  • 所有选项都隐藏时,listbox-empty 会显示。只要有一个选项重新显示,它就会再次隐藏。
  • listbox-group 是一个包住组标题及其选项的 role="group" 元素。组内所有选项都隐藏时,该元素也会隐藏,避免组标题单独显示。

没有匹配项

<div class="sheet sheet-flat max-w(320) mx-auto">  <div class="listbox" role="listbox" aria-label="Regions">    <div class="listbox-option" role="option" hidden>Tokyo</div>    <div class="listbox-option" role="option" hidden>Frankfurt</div>    <div class="listbox-empty">No regions match "zz".</div>  </div></div>
<div className="sheet sheet-flat max-w(320) mx-auto">  <div className="listbox" role="listbox" aria-label="Regions">    <div className="listbox-option" role="option" hidden>Tokyo</div>    <div className="listbox-option" role="option" hidden>Frankfurt</div>    <div className="listbox-empty">No regions match "zz".</div>  </div></div>
<div class="sheet sheet-flat max-w(320) mx-auto">  <div class="listbox" role="listbox" aria-label="Regions">    <div class="listbox-option" role="option" hidden>Tokyo</div>    <div class="listbox-option" role="option" hidden>Frankfurt</div>    <div class="listbox-empty">No regions match "zz".</div>  </div></div>
<template>  <div class="sheet sheet-flat max-w(320) mx-auto">    <div class="listbox" role="listbox" aria-label="Regions">      <div class="listbox-option" role="option" hidden>Tokyo</div>      <div class="listbox-option" role="option" hidden>Frankfurt</div>      <div class="listbox-empty">No regions match "zz".</div>    </div>  </div></template>

#行为脚本

listbox 驱动独立放在页面中、由自身持有焦点的列表框,因此列表框带有 tabindex="0"。它接收带有 role="listbox" 的元素,没有配置项,并返回用于解除绑定的函数。

app.js
import { listbox } from '@master/ui/behaviors/listbox.js'const list = document.querySelector('.listbox')listbox(list)list.addEventListener('change', () => {  const chosen = list.querySelectorAll('[aria-checked="true"]')})
  • 活动项。 按键或点击会将 aria-selected="true" 移到某个选项,在列表框的 aria-activedescendant 中指明该选项,并将其滚动到可见区域。焦点始终留在列表框上。脚本会为缺少 id 的选项补上该属性。列表框获得焦点时,如果没有活动项,就将已选中的选项设为活动项。若没有选中项,则激活第一项。
  • 选择。 按 Enter、空格键或点击选项时,脚本会为该选项设置 aria-checked="true",并为其余选项设置 false。
  • 事件。 每当选中项发生变化,列表框都会先派发 input,再派发 change。通过 aria-checked="true" 读取选项。
  • 跳过的选项。 隐藏的选项和带有 aria-disabled="true" 的选项都不能成为活动项,也不能被选中。

列表框带有 aria-multiselectable="true" 时,可以独立选中或取消选中某个选项,其他选项保留各自的状态。与文件列表一样,也可以用按键选中一段连续的选项:最后选中的选项作为锚点,按住 Shift 再按方向键、空格键或点击,会选中从锚点到键盘或指针当前指向的选项为止的所有选项,包含两端。按 Control 或 Command 加 A 会选中所有选项;如果所有选项都已选中,则全部取消选中。

多选

<div class="sheet sheet-flat max-w(320) mx-auto">  <div class="listbox" role="listbox" aria-label="Notify me about" aria-multiselectable="true" tabindex="0">    <div class="listbox-option" role="option" id="notify-deploys" aria-checked="true">      Deployments    </div>    <div class="listbox-option" role="option" id="notify-comments" aria-checked="false">      Comments    </div>    <div class="listbox-option" role="option" id="notify-billing" aria-checked="true">Billing</div>    <div class="listbox-option" role="option" id="notify-mentions" aria-checked="false">      Mentions    </div>    <div class="listbox-option" role="option" id="notify-digest" aria-checked="false" aria-disabled="true">      Weekly digest    </div>  </div></div><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="sheet sheet-flat max-w(320) mx-auto">      <div className="listbox" role="listbox" aria-label="Notify me about" aria-multiselectable="true" tabIndex={0}>        <div className="listbox-option" role="option" id="notify-deploys" aria-checked="true">          Deployments        </div>        <div className="listbox-option" role="option" id="notify-comments" aria-checked="false">          Comments        </div>        <div className="listbox-option" role="option" id="notify-billing" aria-checked="true">          Billing        </div>        <div className="listbox-option" role="option" id="notify-mentions" aria-checked="false">          Mentions        </div>        <div className="listbox-option" role="option" id="notify-digest" aria-checked="false" aria-disabled="true">          Weekly digest        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><div class="sheet sheet-flat max-w(320) mx-auto" {@attach attach}>  <div class="listbox" role="listbox" aria-label="Notify me about" aria-multiselectable="true" tabindex="0">    <div class="listbox-option" role="option" id="notify-deploys" aria-checked="true">      Deployments    </div>    <div class="listbox-option" role="option" id="notify-comments" aria-checked="false">      Comments    </div>    <div class="listbox-option" role="option" id="notify-billing" aria-checked="true">Billing</div>    <div class="listbox-option" role="option" id="notify-mentions" aria-checked="false">      Mentions    </div>    <div class="listbox-option" role="option" id="notify-digest" aria-checked="false" aria-disabled="true">      Weekly digest    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="sheet sheet-flat max-w(320) mx-auto">    <div class="listbox" role="listbox" aria-label="Notify me about" aria-multiselectable="true" tabindex="0">      <div class="listbox-option" role="option" id="notify-deploys" aria-checked="true">        Deployments      </div>      <div class="listbox-option" role="option" id="notify-comments" aria-checked="false">        Comments      </div>      <div class="listbox-option" role="option" id="notify-billing" aria-checked="true">        Billing      </div>      <div class="listbox-option" role="option" id="notify-mentions" aria-checked="false">        Mentions      </div>      <div class="listbox-option" role="option" id="notify-digest" aria-checked="false" aria-disabled="true">        Weekly digest      </div>    </div>  </div></template>
聚焦列表,然后按住 Shift 并按向下方向键,即可选中一段连续的选项。

文本字段控制的列表框由该字段的行为脚本驱动。listbox 会跳过由 role="combobox" 字段的 aria-controls 指定的列表框,attach() 则会跳过组合框或命令面板内的列表框。没有脚本时,列表框按现有属性呈现,状态保持不变。

#浮动列表框

带有 popover 属性时,列表框呈现为浮动面板,外层圆角为 12px,选项行圆角为 8px。面板贴着锚点放置,遇到视口边缘时翻转,进入和退出的动效与菜单相同。如果列表框由文本字段控制,请使用 popover="manual",让输入时列表框保持打开。组合框展示了这种用法。

#列表框、菜单或下拉选择框

  • 下拉选择框是从列表中选取单个值的原生控件。选项为纯文本时可使用它,无需脚本。
  • 菜单使用原生按钮和链接提供操作。
  • 列表框承载由脚本筛选、分组或加载的值或结果,适用于组合框、命令面板和多选控件。

#键盘操作

以下按键适用于列表框自身持有焦点时的 listbox 行为。方向键移动到首项或末项时停止。组合框和命令面板的按键由各自的输入字段处理,遵循各自的键盘操作规则。

按键操作
ArrowDown, ArrowUp切换活动选项,跳过禁用项,并将新活动项滚动到可见区域
Home, End移到第一个或最后一个选项
Enter, Space选择当前活动选项;若列表设有 aria-multiselectable="true",则切换该选项的选中状态
Shift+ArrowDown, Shift+ArrowUp在可多选的列表中,移动活动选项,并选中从最后选中的选项到新活动选项之间的所有选项
Shift+Space, Shift+click在可多选的列表中,选中从最后选中的选项到此选项之间的所有选项
Control+Shift+Home, Control+Shift+End在可多选的列表中,选中从最后选中的选项直到第一个或最后一个选项的所有选项;在 Mac 上使用 Command
Control+A在可多选的列表中,选中所有选项;如果所有选项都已选中,则全部取消选中;在 Mac 上使用 Command
Typing移到下一个以所输入字母开头的选项

#无障碍

  • 为容器设置 role="listbox" 并提供标签,为每个选项设置 role="option"。将 listbox-group 设为 role="group",并通过 aria-labelledby 将组标题用作标签。
  • 行为脚本同步更新 aria-selected 和 aria-activedescendant,并将当前活动选项滚动到可见范围内。选项设有滚动外边距,与列表边缘留出间距。
  • 禁用的选项带有 aria-disabled="true",键盘导航会跳过这些选项。

#React、Svelte 和 Vue

listbox 组件根据数据渲染选项,挂载行为脚本,并支持传入和读出选中值。带有 group 的选项写在对应的分组标题下:组件为每个分组写出一个带 role="group" 的 listbox-group,以其中的 listbox-label 作为标签,并把同组的选项放在一起,分组按首次出现的顺序排列。使用 npx master-ui add listbox 将组件复制到项目中。React、Svelte 和 Vue 介绍这些组件的实现和用法。

ui/listbox.tsx
'use client'import { useId, useState, type ComponentProps } from 'react'import { listbox } from '@master/ui/behaviors/listbox.js'import { useBehavior } from './use-behavior'export interface ListboxOption {  /** What choosing the option gives `onValueChange`. */  value: string  label: string  description?: string  /** The caption of the group the option belongs to. Options of one group are written together, under it. */  group?: string  disabled?: boolean}export interface ListboxProps extends Omit<ComponentProps<'div'>, 'defaultValue' | 'children' | 'role' | 'ref'> {  options: ListboxOption[]  /** The value of the chosen option, null for none; a list of them when `multiple`. */  value?: string | string[] | null  defaultValue?: string | string[] | null  onValueChange?: (value: string | string[] | null) => void  /** Any number of options may be chosen. */  multiple?: boolean}/** A listbox that stands in the page. Name it with `aria-label` or `aria-labelledby`. */export function Listbox({ options, value, defaultValue, onValueChange, multiple, className, ...root }: ListboxProps) {  const id = useId()  const ref = useBehavior(listbox, undefined, { value, defaultValue, onValueChange })  const [first] = useState(() => [value ?? defaultValue ?? []].flat())  const groups = [...new Set(options.map(option => option.group))]  const row = (option: ListboxOption) => (    <div className="listbox-option" role="option" key={option.value} data-value={option.value} aria-checked={first.includes(option.value)} aria-disabled={option.disabled || undefined}>      {option.description        ? <span className="listbox-body"><span>{option.label}</span><span className="listbox-description">{option.description}</span></span>        : option.label}    </div>  )  return (    <div className={className ? `listbox ${className}` : 'listbox'} role="listbox" tabIndex={0} aria-multiselectable={multiple || undefined} ref={ref} {...root}>      {groups.map((group, index) => group === undefined        ? options.filter(option => option.group === undefined).map(row)        : (            <div className="listbox-group" role="group" aria-labelledby={`${id}group${index}`} key={group}>              <div className="listbox-label" id={`${id}group${index}`}>{group}</div>              {options.filter(option => option.group === group).map(row)}            </div>          ))}    </div>  )}
ui/Listbox.svelte
<script lang="ts" module>  import type { HTMLAttributes } from 'svelte/elements'  export interface ListboxOption {    /** What choosing the option gives `onValueChange`. */    value: string    label: string    description?: string    /** The caption of the group the option belongs to. Options of one group are written together, under it. */    group?: string    disabled?: boolean  }  export interface ListboxProps extends Omit<HTMLAttributes<HTMLDivElement>, 'role' | 'children'> {    options: ListboxOption[]    /** The value of the chosen option, null for none; a list of them when `multiple`. Bind it, or leave it out. */    value?: string | string[] | null    onValueChange?: (value: string | string[] | null) => void    /** Any number of options may be chosen. */    multiple?: boolean  }</script><script lang="ts">  import { untrack } from 'svelte'  import { listbox } from '@master/ui/behaviors/listbox.js'  import { behavior } from './behavior.svelte.js'  let { options, value = $bindable(), onValueChange, multiple, class: className, ...root }: ListboxProps = $props()  const id = $props.id()  // The first value is drawn into the first render; after that the behavior marks what is chosen. A row written  // later, from new options, is drawn with the value as it is then, which is not read as state.  const chosen = { values: untrack(() => [value ?? []].flat()) }  const groups = $derived([...new Set(options.map(option => option.group))])  const attach = behavior(listbox, undefined, {    value: () => value,    change: (next) => { chosen.values = [next ?? []].flat(); value = next; onValueChange?.(next) },    settled: (held) => { chosen.values = [held ?? []].flat() },  })</script>{#snippet row(option: ListboxOption)}  <!-- The behavior writes `aria-selected` on the option the keys are on. -->  <!-- svelte-ignore a11y_role_has_required_aria_props -->  <div class="listbox-option" role="option" data-value={option.value} aria-checked={chosen.values.includes(option.value)} aria-disabled={option.disabled || undefined}>    {#if option.description}      <span class="listbox-body"><span>{option.label}</span><span class="listbox-description">{option.description}</span></span>    {:else}      {option.label}    {/if}  </div>{/snippet}<!--  @component  A listbox that stands in the page. Name it with `aria-label` or `aria-labelledby`.--><div class={['listbox', className]} role="listbox" tabindex={0} aria-multiselectable={multiple || undefined} {@attach attach} {...root}>  {#each groups as group, index (group)}    {#if group === undefined}      {#each options.filter(option => option.group === undefined) as option (option.value)}{@render row(option)}{/each}    {:else}      <div class="listbox-group" role="group" aria-labelledby="{id}group{index}">        <div class="listbox-label" id="{id}group{index}">{group}</div>        {#each options.filter(option => option.group === group) as option (option.value)}{@render row(option)}{/each}      </div>    {/if}  {/each}</div>
ui/Listbox.vue
<script lang="ts">export interface ListboxOption {  /** What choosing the option gives the model. */  value: string  label: string  description?: string  /** The caption of the group the option belongs to. Options of one group are written together, under it. */  group?: string  disabled?: boolean}</script><script setup lang="ts">import { computed, h, useId, useTemplateRef, type FunctionalComponent } from 'vue'import { listbox } from '@master/ui/behaviors/listbox.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { options } = defineProps<{  options: ListboxOption[]  /** Any number of options may be chosen. */  multiple?: boolean}>()/** The value of the chosen option, null for none; a list of them when `multiple`: `v-model`. */const model = defineModel<string | string[] | null>()/* A listbox that stands in the page. Name it with `aria-label` or `aria-labelledby`. */const id = useId()const first = [model.value ?? []].flat()const groups = computed(() => [...new Set(options.map(option => option.group))])const root = useTemplateRef<HTMLDivElement>('root')useBehavior(root, listbox, undefined, model)const Row: FunctionalComponent<{ option: ListboxOption }> = ({ option }) => h('div', {  'class': 'listbox-option',  'role': 'option',  'data-value': option.value,  'aria-checked': first.includes(option.value),  'aria-disabled': option.disabled || undefined,}, option.description  ? h('span', { class: 'listbox-body' }, [h('span', option.label), h('span', { class: 'listbox-description' }, option.description)])  : option.label)Row.props = ['option']</script><template>  <div class="listbox" role="listbox" tabindex="0" :aria-multiselectable="multiple || undefined" ref="root" v-bind="$attrs">    <template v-for="(group, index) in groups" :key="group ?? ''">      <template v-if="group === undefined">        <template v-for="option in options" :key="option.value"><Row v-if="option.group === undefined" :option="option" /></template>      </template>      <div v-else class="listbox-group" role="group" :aria-labelledby="`${id}-group-${index}`">        <div class="listbox-label" :id="`${id}-group-${index}`">{{ group }}</div>        <template v-for="option in options" :key="option.value"><Row v-if="option.group === group" :option="option" /></template>      </div>    </template>  </div></template>

#类名

类名说明
listbox列表本体。带有 popover 属性时显示为浮动面板。
listbox-option在带 role="option" 的元素上使用。选项代表其 data-value,未设置时使用自身文本。
listbox-body用于选项内部,将标题置于说明上方。
listbox-descriptionlistbox-body 内选项标题下方的弱化文字。
listbox-path选项所在的位置:标题下方的一行小字,位于 listbox-body 内,每一级各用一个 listbox-crumb。它不换行,上方的标题采用控件的字重
listbox-crumblistbox-path 的一级,除第一级外,每一级前面都有箭头。它是文字,不是链接
listbox-excerpt选项文字下方的段落,位于 listbox-body 内,用于显示搜索匹配的内容,最多两行。有了它,图标和行尾内容会与标题对齐
listbox-end选项末尾的快捷键或提示
listbox-group将选项和组标题放在 role="group" 的元素中,并以组标题作为该元素的可访问名称。所有选项都隐藏时,整组随之隐藏。
listbox-label选项组上方的组标题,采用弱化样式。
listbox-separator在列表组之间绘制一条延伸到两侧边缘的细线
listbox-empty无匹配项时的列表提示,在所有选项都隐藏后显示

#自定义属性

属性默认值说明
--listbox-inset4px列表内围绕选项的内边距。
--listbox-option-radiusvar(--radius-control-sm)行圆角半径。浮动列表的圆角半径为此值加内边距

#源码

@master/ui/components/listbox.css
/* * Listbox: a list of options to choose from, the surface a combobox and a command palette open. * The stylesheet draws every state from ARIA and leaves the behavior to the script that drives it: * aria-selected marks the active option, the one the arrow keys are on; aria-checked marks a chosen value * with a check. In the flow of the page it is a plain list; with the popover attribute it is a floating * sheet placed against its anchor, whose corner is a row's corner plus its 4px inset. * An option follows one alignment: its icon, its words and its end center on one another, which holds while the * words are a title and one line under it, a description or a path. With an excerpt, a passage of up to two * lines, the option turns to its first line: the icon and the end stand beside the title and the rest runs * under it. A match in an option is a mark, in the title's ink and weight so it is found in a muted line too. */@layer components.ui {  .listbox {    --listbox-inset: 4px;    --listbox-option-radius: var(--radius-control-sm);    min-width: 0;    margin: 0;    padding: var(--listbox-inset);    overflow-y: auto;    overscroll-behavior: contain;    color: var(--color-text-strong);    font: 400 .84375rem/1.2 var(--font-family-sans);    font-feature-settings: inherit;    /* A label, a description or a query echoed in the empty state wraps rather than scroll the list sideways. */    overflow-wrap: anywhere;    list-style: none;    scrollbar-width: thin;    scrollbar-color: var(--color-line-strong) transparent;    /*     * The list holds focus while aria-activedescendant moves through it: the active row shows where, with the     * ink outline the keys leave inside a row, so it never reads as a row under the pointer.     */    &:focus-visible {      outline: none;      .listbox-option[aria-selected="true"] {        outline: 2px solid var(--color-focus);        outline-offset: -2px;      }    }    /*     * Until an option is active (the script has not run yet, a press gave the list focus, or every option is     * filtered out) the list itself shows that it holds the keys.     */    &:focus-visible:not(:has(.listbox-option[aria-selected="true"]:not([hidden]))) {      @apply --focus-ring;    }    /* Floating: opened with showPopover() by the script that owns the field. */    &[popover] {      --surface-color: var(--color-surface-floating);      min-width: 11rem;      max-width: min(24rem, calc(100vw - 1rem));      max-height: min(20rem, 60dvh);      border: 0;      border-radius: calc(var(--listbox-option-radius) * var(--corner-scale) + var(--listbox-inset));      corner-shape: var(--corner-shape);      background: var(--color-surface-floating);      box-shadow: var(--shadow-floating);      transform-origin: top;      @apply --anchored;      @apply --pop;    }    @media (forced-colors: active) {      &[popover] {        outline: 1px solid CanvasText;        outline-offset: -1px;      }    }  }  /* An option: role="option" on any element. */  .listbox-option {    --icon-size: 1rem;    --icon-offset: -.0625rem;    --icon-color: var(--color-text-muted);    display: flex;    align-items: center;    gap: .625rem;    min-height: 2rem;    padding: .25rem .5rem;    border-radius: calc(var(--listbox-option-radius) * var(--corner-scale));    corner-shape: var(--corner-shape);    outline: none;    color: var(--color-text-strong);    scroll-margin: var(--listbox-inset);    user-select: none;    -webkit-user-select: none;    -webkit-tap-highlight-color: transparent;    cursor: pointer;    touch-action: manipulation;    /* A script filters by setting hidden; a display on this rule would otherwise bring the option back. */    &[hidden] {      display: none;    }    /* A row answers at once: no fade between rows as the pointer or the keys travel. */    @media (hover: hover) {      &:hover:not([aria-disabled="true"]) {        --icon-color: currentColor;        background: var(--color-surface-chip);      }    }    /* Pressed: a step deeper than the pointer's tone. */    &:active:not([aria-disabled="true"]) {      background: var(--color-surface-inset-hover);    }    &[aria-selected="true"] {      --icon-color: currentColor;      background: var(--color-surface-chip);    }    /* With real focus on the option, the ink outline says so. */    &:focus-visible {      --icon-color: currentColor;      background: var(--color-surface-chip);      outline: 2px solid var(--color-focus);      outline-offset: -2px;    }    &[aria-disabled="true"] {      --icon-color: currentColor;      color: var(--color-text-disabled);      cursor: not-allowed;    }    /* A checkable option keeps room for its mark at the end, so nothing moves when it is chosen. */    &[aria-checked]::after {      content: '';      flex: none;      width: 14px;      height: 14px;      margin-inline-start: auto;      opacity: 0;      background: currentColor;      mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3 8L6.3532 11.3532A0.2 0.2 0 0 0 6.6412 11.3479L13 4.5'/%3E%3C/svg%3E") center / contain no-repeat;    }    /* Beside something at the end of the option, the mark follows it: only one of the two is pushed to the end. */    &[aria-checked]:has(.listbox-end)::after {      margin-inline-start: 0;    }    &[aria-checked="true"]::after {      opacity: 1;    }    @media (pointer: coarse) {      min-height: 2.75rem;    }    @media (forced-colors: active) {      &:is(:focus-visible, [aria-selected="true"]):not([aria-disabled="true"]) {        background: Highlight;        color: HighlightText;        forced-color-adjust: none;      }      /* Only a pointer that hovers lights a row: a tap would leave it lit on a touch screen. */      @media (hover: hover) {        &:hover:not([aria-disabled="true"]) {          background: Highlight;          color: HighlightText;          forced-color-adjust: none;        }      }      &[aria-disabled="true"] {        color: GrayText;      }      /* The check is a fill cut by a mask: kept out of forced colors, it takes the row's system ink. */      &::after {        forced-color-adjust: none;        background: currentColor;      }    }  }  /* A title with a line under it, for an option that needs a sentence. */  .listbox-body {    display: grid;    flex: 1 1 0;    gap: .125rem;    min-width: 0;    padding-block: .125rem;  }  .listbox-description {    margin: 0;    color: var(--color-text-muted);    font-size: .75rem;    line-height: 1.4;    text-wrap: pretty;  }  /*   * Where an option is: the steps of a path on one line under the title, a chevron between them. They are not   * links (an option is one target), so this is not a breadcrumb. The line never wraps: its steps give way   * together and end in an ellipsis.   */  .listbox-path {    display: flex;    min-width: 0;    margin: 0;    color: var(--color-text-muted);    font-size: .71875rem;    line-height: 1.4;    white-space: nowrap;  }  .listbox-crumb {    flex: 0 1 auto;    min-width: 0;    overflow: hidden;    text-overflow: ellipsis;    &:not(:first-child)::before {      content: '';      display: inline-block;      width: .75rem;      height: .75rem;      margin-inline: .125rem;      background: var(--color-text-disabled);      vertical-align: -.125rem;      mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5'/%3E%3C/svg%3E") center / contain no-repeat;    }    &:dir(rtl)::before {      scale: -1 1;    }  }  /*   * A passage under an option's words, where a search shows what it matched: two lines at most, then an ellipsis.   * Without line-clamp the passage runs to its end.   */  .listbox-excerpt {    display: -webkit-box;    margin: .125rem 0 0;    overflow: hidden;    color: var(--color-text-muted);    font-size: .75rem;    line-height: 1.45;    -webkit-box-orient: vertical;    -webkit-line-clamp: 2;    line-clamp: 2;  }  /*   * An icon names the option, so it stands on the title's line whatever the body holds under it: a description,   * a path or an excerpt. Centred on two lines it sat between the title and the line under, beside neither, and a   * list that mixes results with and without an excerpt showed its icons at two heights. A picture, an avatar or   * a thumbnail, is as tall as the two lines and still centers on them.   */  .listbox-option:has(.listbox-body) {    /* The title's line and the body's padding, in rem: the end reads it at its own smaller size. */    --listbox-line: calc(.84375rem * 1.2 + .25rem);    .icon {      align-self: start;      margin-block: calc((var(--listbox-line) - var(--icon-size)) / 2);    }  }  /*   * Centering reads as one row for a title and a line under it. An excerpt makes the words taller than that, so   * the option turns to its first line: the icon, the end and the check stand beside the title, each in a box   * as tall as the title's line with the body's own padding, and the row keeps a little more room around it.   */  .listbox-option:has(.listbox-excerpt) {    align-items: start;    padding-block: .375rem;    .listbox-end {      min-height: var(--listbox-line);    }    &[aria-checked]::after {      margin-block: calc((var(--listbox-line) - 14px) / 2);    }  }  /*   * A result's title leads smaller lines, so it takes a control's weight and they do not. A list of results   * keeps one weight whether or not a result has a passage to show.   */  .listbox-option:has(.listbox-path, .listbox-excerpt) {    font-weight: var(--font-weight-control);    :is(.listbox-description, .listbox-path, .listbox-excerpt, .listbox-end) {      font-weight: 400;    }  }  /* A match: the title's ink and a control's weight over the wash, so it is found at a glance in a muted line. */  .listbox-option .mark {    --mark-weight: var(--font-weight-control);  }  .listbox-option:not([aria-disabled="true"]) .mark {    --mark-ink: var(--color-text-strong);  }  /* A shortcut or a hint at the end of an option. */  .listbox-end {    display: inline-flex;    flex: none;    align-items: center;    gap: .25rem;    margin-inline-start: auto;    padding-inline-start: 1rem;    color: var(--color-text-muted);    font-size: .71875rem;    font-variant-numeric: tabular-nums;  }  /* Secondary ink must follow the system-selected foreground, including on highlighted options. */  @media (forced-colors: active) {    :is(.listbox-description, .listbox-path, .listbox-excerpt, .listbox-end) {      color: inherit;    }    /* The chevron is a fill cut by a mask: it takes the row's system ink, as the check does. */    .listbox-crumb:not(:first-child)::before {      forced-color-adjust: none;      background: currentColor;    }  }  /* A group: role="group" around a caption and its options. With every option filtered out, it steps aside. */  .listbox-group:not(:has(.listbox-option:not([hidden]))) {    display: none;  }  /*   * A quiet caption over a group of options. It belongs to the options under it: the room above parts its group from   * the one before, and the room below is small, so the caption reads with the options it leads. The first group still   * shown, or one after a separator, has nothing to part from or a hairline that does it, and keeps a little room.   * Without :nth-child(of), the first group keeps the larger room.   */  .listbox-label {    margin: 0;    padding: .75rem .5rem .25rem;    color: var(--color-text-muted);    font-size: .71875rem;    user-select: none;    -webkit-user-select: none;    .listbox-separator + .listbox-group & {      padding-block-start: .375rem;    }    .listbox-group:nth-child(1 of .listbox-group:has(.listbox-option:not([hidden]))) & {      padding-block-start: .375rem;    }  }  /* A hairline between groups, running to the list's edges. */  .listbox-separator {    height: 1px;    margin: var(--listbox-inset) calc(-1 * var(--listbox-inset));    border: 0;    background: var(--color-line-hair);    /* Forced colors repaint the background as the canvas; a system color keeps the rule. */    @media (forced-colors: active) {      background: CanvasText;    }  }  /* What the list says when nothing matches. It shows by itself once every option is hidden. */  .listbox-empty {    margin: 0;    padding: 1.5rem .75rem;    color: var(--color-text-muted);    text-align: center;    text-wrap: balance;  }  .listbox:has(.listbox-option:not([hidden])) .listbox-empty {    display: none;  }  /* A caption or a rule with no visible option left under its list has nothing to introduce. */  .listbox:not(:has(.listbox-option:not([hidden]))) :is(.listbox-label, .listbox-separator) {    display: none;  }}