导航

v2.1.0
表单

组合框

输入文字时打开匹配项列表的文本框,相当于可以输入文字的下拉选择框。

本页内容

组合框是可输入文字的选择控件,输入时会打开一个显示匹配项的列表框。外层的 combobox 将现有的输入组和浮动列表框组合在一起。样式表负责定位和呈现,combobox 行为脚本负责筛选选项、在选项间移动,并将选中的选项写入输入框。

组合框

<div class="field max-w(320) mx-auto">  <label for="region">Region</label>  <div class="combobox">    <div class="input-group">      <input class="input-group-field" id="region" role="combobox" aria-expanded="false" aria-controls="region-list" aria-autocomplete="list" autocomplete="off" placeholder="Search regions">      <button type="button" class="combobox-toggle" tabindex="-1" aria-label="Show regions">        <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="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(90 8 8)" />        </svg>      </button>    </div>    <div id="region-list" popover="manual" class="listbox" role="listbox" aria-label="Regions">      <div class="listbox-option" role="option" id="region-hnd" aria-checked="false">Tokyo</div>      <div class="listbox-option" role="option" id="region-sin" aria-checked="false">Singapore</div>      <div class="listbox-option" role="option" id="region-fra" aria-checked="false">Frankfurt</div>      <div class="listbox-option" role="option" id="region-lhr" aria-checked="false">London</div>      <div class="listbox-option" role="option" id="region-iad" aria-checked="false">Virginia</div>      <div class="listbox-option" role="option" id="region-pdx" aria-checked="false" aria-disabled="true">        Oregon      </div>      <div class="listbox-empty">No regions match.</div>    </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'import ChevronDownIcon from '@master/icons-react/native/16/soft/chevron-down'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="field max-w(320) mx-auto">      <label htmlFor="region">Region</label>      <div className="combobox">        <div className="input-group">          <input className="input-group-field" id="region" role="combobox" aria-expanded="false" aria-controls="region-list" aria-autocomplete="list" autoComplete="off" placeholder="Search regions" />          <button type="button" className="combobox-toggle" tabIndex={-1} aria-label="Show regions">            <ChevronDownIcon className="icon" />          </button>        </div>        <div id="region-list" popover="manual" className="listbox" role="listbox" aria-label="Regions">          <div className="listbox-option" role="option" id="region-hnd" aria-checked="false">Tokyo</div>          <div className="listbox-option" role="option" id="region-sin" aria-checked="false">            Singapore          </div>          <div className="listbox-option" role="option" id="region-fra" aria-checked="false">            Frankfurt          </div>          <div className="listbox-option" role="option" id="region-lhr" aria-checked="false">            London          </div>          <div className="listbox-option" role="option" id="region-iad" aria-checked="false">            Virginia          </div>          <div className="listbox-option" role="option" id="region-pdx" aria-checked="false" aria-disabled="true">            Oregon          </div>          <div className="listbox-empty">No regions match.</div>        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import ChevronDownIcon from '@master/icons-svelte/native/16/soft/chevron-down'</script><div class="field max-w(320) mx-auto" {@attach attach}>  <label for="region">Region</label>  <div class="combobox">    <div class="input-group">      <input class="input-group-field" id="region" role="combobox" aria-expanded="false" aria-controls="region-list" aria-autocomplete="list" autocomplete="off" placeholder="Search regions">      <button type="button" class="combobox-toggle" tabindex="-1" aria-label="Show regions">        <ChevronDownIcon class="icon" />      </button>    </div>    <div id="region-list" popover="manual" class="listbox" role="listbox" aria-label="Regions">      <div class="listbox-option" role="option" id="region-hnd" aria-checked="false">Tokyo</div>      <div class="listbox-option" role="option" id="region-sin" aria-checked="false">Singapore</div>      <div class="listbox-option" role="option" id="region-fra" aria-checked="false">Frankfurt</div>      <div class="listbox-option" role="option" id="region-lhr" aria-checked="false">London</div>      <div class="listbox-option" role="option" id="region-iad" aria-checked="false">Virginia</div>      <div class="listbox-option" role="option" id="region-pdx" aria-checked="false" aria-disabled="true">        Oregon      </div>      <div class="listbox-empty">No regions match.</div>    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import ChevronDownIcon from '@master/icons-vue/native/16/soft/chevron-down'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="field max-w(320) mx-auto">    <label for="region">Region</label>    <div class="combobox">      <div class="input-group">        <input class="input-group-field" id="region" role="combobox" aria-expanded="false" aria-controls="region-list" aria-autocomplete="list" autocomplete="off" placeholder="Search regions">        <button type="button" class="combobox-toggle" tabindex="-1" aria-label="Show regions">          <ChevronDownIcon class="icon" />        </button>      </div>      <div id="region-list" popover="manual" class="listbox" role="listbox" aria-label="Regions">        <div class="listbox-option" role="option" id="region-hnd" aria-checked="false">Tokyo</div>        <div class="listbox-option" role="option" id="region-sin" aria-checked="false">          Singapore        </div>        <div class="listbox-option" role="option" id="region-fra" aria-checked="false">          Frankfurt        </div>        <div class="listbox-option" role="option" id="region-lhr" aria-checked="false">London</div>        <div class="listbox-option" role="option" id="region-iad" aria-checked="false">          Virginia        </div>        <div class="listbox-option" role="option" id="region-pdx" aria-checked="false" aria-disabled="true">          Oregon        </div>        <div class="listbox-empty">No regions match.</div>      </div>    </div>  </div></template>
输入文字筛选选项,用方向键移动,按 Enter 或点击确认选择。

#样式表的作用

  • 定位。 外层的 combobox 为自身设置锚点名称,并将名称的作用域限定在自身。列表框在整个输入区域下方 6px 处打开,定位不受插入光标或按钮位置影响,并通过 anchor-size() 使其宽度至少与输入区域相同。整个过程无需测量尺寸,同一页面上的多个组合框可以独立定位。
  • 箭头。 combobox-toggle 是输入区域末端的小按钮,内含一个箭头图标。输入框处于 aria-expanded="true" 状态时,箭头会翻转。
  • 空状态。 所有选项都处于 hidden 状态时,listbox-empty 会自动显示。
  • 输入框状态。 悬停、聚焦、无效和禁用状态由输入组提供。

浏览器不支持锚点定位时,列表框仍可打开,并按它在标记中的位置直接显示在输入区域下方,宽度为列表框自身的宽度。

#行为脚本

combobox 接收带有 combobox 类的根元素和一个选项对象,并返回一个用于解除绑定的函数。它通过 role="combobox" 查找输入框,通过 role="listbox" 查找列表。filter 选项默认为 true;filter: false 将选项交由页面处理,如自动补全所示。name、removeLabel 和 draw 用于多个值。

app.js
import { combobox } from '@master/ui/behaviors/combobox.js'const box = combobox(document.querySelector('.combobox'))box.value // what the chosen option stands for, or nullbox.query // the text in the field

返回的函数有两个属性,可从外部读取和设置。设置其中任何一个都不会派发事件。

  • value 是所选选项代表的值,即其 data-value 或文本;输入框中的文字没有对应的已选选项时为 null。设置它会勾选对应的选项,并将其文本写入输入框。

  • query 是输入框中的文字,即读者要查找的内容。它不是值:每次按键都会变化,选定某个选项后则变为该选项的文本。设置它会写入输入框,并像输入文字时一样筛选选项。

  • 输入文字时,脚本会给文本中不含输入内容的选项设置 hidden,匹配时忽略大小写。随后打开列表,并将第一个匹配项设为活动选项。

  • 活动选项带有 aria-selected="true",输入框通过 aria-activedescendant 指向该选项。焦点保留在输入框中。

  • 选择选项时,按 Enter 或使用指针都会将选项文本写入输入框,省去其中的 listbox-description 和 listbox-end,将该选项标记为 aria-checked="true",将其余选项标记为 false,然后关闭列表。输入新内容覆盖已选值时,会清除该选项的勾选标记。

  • 打开和关闭。 列表框使用 popover="manual",因此在输入框中打字或点击时会保持打开。点击输入框或切换按钮,或按方向键时,脚本会打开列表。按 Esc 或焦点离开组合框时,脚本会关闭列表,并使 aria-expanded 与开关状态保持同步。

  • 事件。 选中选项时,输入框会像输入文字时一样,先派发 input,再派发 change。当前值取自输入框的 value。

移动时会跳过禁用和隐藏的选项。输入法处于组字状态时,Enter 和方向键由输入法处理。

未绑定行为脚本时,输入框仍可接受文本输入,列表保持关闭。

#多个值

带有 aria-multiselectable="true" 的列表框可以容纳多个值。此时输入区域是带有 input-group-wrap 的输入组,与标签输入相同,每个已选选项都以胶囊标签显示在输入框之前。选择选项会勾选或取消勾选该选项,清空输入框并保持列表打开,因此只需再按几个键就能选择下一个值。选项会保留勾选标记,因此列表和胶囊标签一样能表明已选择了哪些值。

多个值

<div class="field max-w(360) mx-auto">  <label for="regions">Regions</label>  <div class="combobox">    <div class="input-group input-group-wrap">      <span class="chip" data-value="hnd">        Tokyo<input type="hidden" name="regions" value="hnd"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove Tokyo">          <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 4L12 12" /><path d="M4 12L12 4" />          </svg>        </button>      </span>      <input class="input-group-field" id="regions" role="combobox" aria-expanded="false" aria-controls="regions-list" aria-autocomplete="list" autocomplete="off" placeholder="Add a region">      <button type="button" class="combobox-toggle" tabindex="-1" aria-label="Show regions">        <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="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(90 8 8)" />        </svg>      </button>    </div>    <div id="regions-list" popover="manual" class="listbox" role="listbox" aria-label="Regions" aria-multiselectable="true">      <div class="listbox-option" role="option" data-value="hnd" aria-checked="true">Tokyo</div>      <div class="listbox-option" role="option" data-value="sin" aria-checked="false">        Singapore      </div>      <div class="listbox-option" role="option" data-value="fra" aria-checked="false">        Frankfurt      </div>      <div class="listbox-option" role="option" data-value="lhr" aria-checked="false">London</div>      <div class="listbox-option" role="option" data-value="iad" aria-checked="false">Virginia</div>      <div class="listbox-empty">No regions match.</div>    </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'import XIcon from '@master/icons-react/native/16/soft/x'import ChevronDownIcon from '@master/icons-react/native/16/soft/chevron-down'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="field max-w(360) mx-auto">      <label htmlFor="regions">Regions</label>      <div className="combobox">        <div className="input-group input-group-wrap">          <span className="chip" data-value="hnd">            Tokyo<input type="hidden" name="regions" value="hnd" /><button type="button" className="chip-remove" tabIndex={-1} aria-label="Remove Tokyo">              <XIcon className="icon" />            </button>          </span>          <input className="input-group-field" id="regions" role="combobox" aria-expanded="false" aria-controls="regions-list" aria-autocomplete="list" autoComplete="off" placeholder="Add a region" />          <button type="button" className="combobox-toggle" tabIndex={-1} aria-label="Show regions">            <ChevronDownIcon className="icon" />          </button>        </div>        <div id="regions-list" popover="manual" className="listbox" role="listbox" aria-label="Regions" aria-multiselectable="true">          <div className="listbox-option" role="option" data-value="hnd" aria-checked="true">Tokyo</div>          <div className="listbox-option" role="option" data-value="sin" aria-checked="false">            Singapore          </div>          <div className="listbox-option" role="option" data-value="fra" aria-checked="false">            Frankfurt          </div>          <div className="listbox-option" role="option" data-value="lhr" aria-checked="false">            London          </div>          <div className="listbox-option" role="option" data-value="iad" aria-checked="false">            Virginia          </div>          <div className="listbox-empty">No regions match.</div>        </div>      </div>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import XIcon from '@master/icons-svelte/native/16/soft/x'  import ChevronDownIcon from '@master/icons-svelte/native/16/soft/chevron-down'</script><div class="field max-w(360) mx-auto" {@attach attach}>  <label for="regions">Regions</label>  <div class="combobox">    <div class="input-group input-group-wrap">      <span class="chip" data-value="hnd">        Tokyo<input type="hidden" name="regions" value="hnd"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove Tokyo">          <XIcon class="icon" />        </button>      </span>      <input class="input-group-field" id="regions" role="combobox" aria-expanded="false" aria-controls="regions-list" aria-autocomplete="list" autocomplete="off" placeholder="Add a region">      <button type="button" class="combobox-toggle" tabindex="-1" aria-label="Show regions">        <ChevronDownIcon class="icon" />      </button>    </div>    <div id="regions-list" popover="manual" class="listbox" role="listbox" aria-label="Regions" aria-multiselectable="true">      <div class="listbox-option" role="option" data-value="hnd" aria-checked="true">Tokyo</div>      <div class="listbox-option" role="option" data-value="sin" aria-checked="false">        Singapore      </div>      <div class="listbox-option" role="option" data-value="fra" aria-checked="false">        Frankfurt      </div>      <div class="listbox-option" role="option" data-value="lhr" aria-checked="false">London</div>      <div class="listbox-option" role="option" data-value="iad" aria-checked="false">Virginia</div>      <div class="listbox-empty">No regions match.</div>    </div>  </div></div>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'import XIcon from '@master/icons-vue/native/16/soft/x'import ChevronDownIcon from '@master/icons-vue/native/16/soft/chevron-down'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="field max-w(360) mx-auto">    <label for="regions">Regions</label>    <div class="combobox">      <div class="input-group input-group-wrap">        <span class="chip" data-value="hnd">          Tokyo<input type="hidden" name="regions" value="hnd"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove Tokyo">            <XIcon class="icon" />          </button>        </span>        <input class="input-group-field" id="regions" role="combobox" aria-expanded="false" aria-controls="regions-list" aria-autocomplete="list" autocomplete="off" placeholder="Add a region">        <button type="button" class="combobox-toggle" tabindex="-1" aria-label="Show regions">          <ChevronDownIcon class="icon" />        </button>      </div>      <div id="regions-list" popover="manual" class="listbox" role="listbox" aria-label="Regions" aria-multiselectable="true">        <div class="listbox-option" role="option" data-value="hnd" aria-checked="true">Tokyo</div>        <div class="listbox-option" role="option" data-value="sin" aria-checked="false">          Singapore        </div>        <div class="listbox-option" role="option" data-value="fra" aria-checked="false">          Frankfurt        </div>        <div class="listbox-option" role="option" data-value="lhr" aria-checked="false">London</div>        <div class="listbox-option" role="option" data-value="iad" aria-checked="false">          Virginia        </div>        <div class="listbox-empty">No regions match.</div>      </div>    </div>  </div></template>
选择几个区域。在空输入框中按 Backspace 会定位到最后一个胶囊标签,再按一次 Backspace 即可将其删除。
  • 输入框只负责搜索。 输入文字只会筛选列表,不会取消任何勾选;已选的值由胶囊标签保存。
  • 胶囊标签。 输入框是唯一的 Tab 停靠点。在空输入框中按 Backspace,或按指向前一项的方向键,会定位到胶囊标签,在胶囊标签上的按键操作与标签输入相同。用移除按钮或 Backspace 删除胶囊标签时,会取消勾选对应的选项。
  • 表单。 如果现有胶囊标签已带有设置了 name 的隐藏输入框,或传入了 name 选项,行为脚本写入的胶囊标签也会带有一个保存该值的隐藏输入框。removeLabel 以页面的语言为移除按钮命名。
  • 值是已选值的列表,按选择的先后排序。

如果值由读者自由输入,而不是从列表中选择,请使用标签输入。

#自动补全

匹配项来自服务器或页面自己的搜索时,用 filter: false 绑定行为脚本。脚本不会隐藏任何选项:在输入框的每次 input 事件中读取 query,查找匹配项,并将结果写为列表的选项。即使选项在触发查找的输入之后才到达,仍会设置活动选项,因此 Enter 和方向键对它们同样有效。

自动补全

<div class="field max-w(320) mx-auto">  <label for="city">City</label>  <div class="combobox" id="city-combobox">    <div class="input-group">      <input class="input-group-field" id="city" role="combobox" aria-expanded="false" aria-controls="city-list" aria-autocomplete="list" autocomplete="off" placeholder="Start typing a city">      <button type="button" class="combobox-toggle" tabindex="-1" aria-label="Show cities">        <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="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(90 8 8)" />        </svg>      </button>    </div>    <div id="city-list" popover="manual" class="listbox" role="listbox" aria-label="Cities">      <div class="listbox-empty">No cities start with that.</div>    </div>  </div></div><script>addEventListener('DOMContentLoaded', function () {var root = document.getElementById('city-combobox')var list = document.getElementById('city-list')var cities = ['Amsterdam', 'Athens', 'Auckland', 'Bangkok', 'Barcelona', 'Berlin', 'Bogotá', 'Boston', 'Brussels', 'Buenos Aires', 'Cairo', 'Cape Town', 'Chicago', 'Copenhagen', 'Dublin', 'Frankfurt', 'Helsinki', 'Hong Kong', 'Istanbul', 'Lisbon', 'London', 'Los Angeles', 'Madrid', 'Melbourne', 'Mexico City', 'Montreal', 'Mumbai', 'Nairobi', 'New York', 'Oslo', 'Paris', 'Prague', 'Rome', 'San Francisco', 'Santiago', 'São Paulo', 'Seoul', 'Singapore', 'Stockholm', 'Sydney', 'Taipei', 'Tokyo', 'Toronto', 'Vienna', 'Warsaw', 'Zurich']var box = MasterUI.combobox(root, { filter: false })var asked = 0// Stands for a request to a server: the cities that start with the query, a moment later.function search(query) {  return new Promise(function (resolve) {    setTimeout(function () {      var text = query.trim().toLowerCase()      resolve(cities.filter(function (city) { return city.toLowerCase().startsWith(text) }).slice(0, 6))    }, 120)  })}function write(matches) {  list.querySelectorAll('.listbox-option').forEach(function (option) { option.remove() })  matches.forEach(function (city) {    var option = document.createElement('div')    option.className = 'listbox-option'    option.setAttribute('role', 'option')    option.setAttribute('aria-checked', 'false')    option.textContent = city    list.insertBefore(option, list.querySelector('.listbox-empty'))  })}root.addEventListener('input', function (event) {  // A choice says input too; its text is the option's, with nothing more to look for.  if (event.target.getAttribute('role') !== 'combobox' || box.value !== null) return  var ticket = ++asked  search(box.query).then(function (matches) {    // An answer to an older query that arrives late is dropped.    if (ticket === asked) write(matches)  })})search('').then(write)})</script><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
输入几个字母:页面会查找该内容,稍后写入选项。用方向键和 Enter 选择其中一个。
  • 读取 query,而不是事件。 查询内容就是输入框中的文字;无论是读者输入的还是框架写入的,query 都以相同方式读取。
  • 选择选项同样会派发 input。 此时文字是所选选项的文本,value 也不再为 null:已无需查找,这时写入新选项反而会移除已选的那个。
  • 响应可能乱序到达。 只保留对最新查询的响应。
  • 空状态由样式表处理。 列表中没有选项时,listbox-empty 会自动显示。

在 React、Svelte 和 Vue 中,组件的 query 和 onQueryChange(Svelte 中为可绑定的 query,Vue 中为 v-model:query)传递同样的文字:用它进行查找,再将匹配项作为 options 传入,并将 filter 设为 false。

#选择控件

对于最多十二个纯文本选项,下拉选择框无需脚本即可利用平台原生的键入查找功能。如果选项多到需要搜索、需要随输入动态加载,或选项行包含丰富内容,请使用组合框。

#键盘操作

这些按键由行为脚本处理。列表关闭时,或按住 Shift 时,Home 和 End 会像在普通输入框中一样移动光标。没有活动选项时,脚本保留 Enter 的默认行为,因此仍可用它提交表单。

按键操作
ArrowDown, ArrowUp打开列表并切换活动选项,在首尾之间循环。
Home, End列表展开时,移到第一个或最后一个选项
Enter单选模式下,选择当前活动选项并关闭列表。多选模式下,勾选或取消勾选当前活动选项,列表保持打开
Escape关闭列表,保留输入字段中的文本
Typing筛选选项,打开列表并定位到首个匹配项
Backspace多选模式下,输入框为空时,将焦点移到最后一个胶囊标签。焦点在胶囊标签上时,取消勾选其对应选项,并将焦点移到前一个胶囊标签。若当前标签是第一个,则移到后一个。若已无胶囊标签,则回到输入框
Delete多选模式下,焦点在胶囊标签上时,取消勾选其对应选项,并将焦点移到后一个胶囊标签。若当前标签是最后一个,则回到输入框
ArrowLeft, ArrowRight多选模式下,从输入框的起始端依次在胶囊标签之间移动焦点,操作与标签输入框相同
Home, End多选模式下,焦点在胶囊标签上时,将焦点移到第一个胶囊标签,或移回输入框
Escape多选模式下,焦点在胶囊标签上时,将焦点移回输入框

#无障碍

  • 输入框带有 role="combobox"、指向列表框的 aria-controls、aria-autocomplete="list" 和 aria-expanded。
  • 焦点保留在输入框中,辅助技术通过 aria-activedescendant 播报活动选项。
  • 用 tabindex="-1" 将切换按钮移出 Tab 键导航顺序,因为在输入框中按方向键即可打开列表。
  • 设置 autocomplete="off",避免浏览器自带的建议遮住列表。

#React、Svelte 和 Vue

combobox 组件根据选项列表渲染这段标记,绑定行为脚本,并接收和传出选中的值。设置 multiple 时,组件会根据值写入胶囊标签,此时值是一个列表。带有 group 的选项写在对应的分组标题下,位于带 role="group" 的 listbox-group 中,并以其中的 listbox-label 作为标签;某个分组的选项全部被筛掉时,该分组随之隐藏。除了值,组件还传递查询内容:React 中为 query 和 onQueryChange,Svelte 中为可绑定的 query 和 onQueryChange,Vue 中为 v-model:query。读者输入时以及做出选择后(在值之后)都会传出查询内容;调用方传入的查询内容会写入输入框,并用于筛选选项。使用 npx master-ui add combobox 将组件复制到项目中。有关这些组件的实现和用法,请参阅 React、Svelte 和 Vue。

ui/combobox.tsx
'use client'import { useEffect, useId, useRef, useState, type ComponentProps, type ReactNode } from 'react'import { combobox } from '@master/ui/behaviors/combobox.js'import { useBehavior } from './use-behavior'export interface ComboboxOption {  /** What choosing the option gives `onValueChange`. */  value: string  /** What the option says, and what the field holds once it is chosen. */  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}interface Shared extends Omit<ComponentProps<'input'>, 'value' | 'defaultValue' | 'role' | 'multiple' | 'name'> {  options: ComboboxOption[]  /**   * The text in the field, what the reader is looking for: written into the field each time it changes.   * It is not the value; with one value it holds the chosen option's label once one is chosen.   */  query?: string  /** Called with the text in the field each time the reader changes it, by typing or by choosing. */  onQueryChange?: (query: string) => void  /** False when `options` are already the matches: search for `query` and give the matches as `options`. */  filter?: boolean  /** The name of the list, for assistive technology. */  listLabel: string  /** The name of the button that opens the list. */  toggleLabel: string  /** What the list says when no option matches. */  empty?: ReactNode}interface One extends Shared {  multiple?: false  /** The value of the chosen option; null while the field holds text no option was chosen for. */  value?: string | null  defaultValue?: string | null  onValueChange?: (value: string | null) => void}interface Several extends Shared {  /** Several values, each a chip in the field. */  multiple: true  /** The chosen values, in the order they were chosen. */  value?: string[]  defaultValue?: string[]  onValueChange?: (value: string[]) => void  /** The name each value is submitted with, in a hidden input of its chip. */  name?: string  /** The accessible name of a chip's remove button. `Remove <label>` by default. */  removeLabel?: (label: string) => string}export type ComboboxProps = One | Several/** * A combobox. Name the field with `aria-label`, or give it an `id` a label points at; every other prop of * an input goes to the field, so `onChange` hears what is typed. With `multiple`, the chosen values are * chips in the field, which React writes from the value. */export function Combobox(props: ComboboxProps) {  const { options, value, defaultValue, onValueChange, query, onQueryChange, filter = true, listLabel, toggleLabel, empty, className, multiple, ...rest } = props  const { name, removeLabel = (label: string) => `Remove ${label}`, ...field } = rest as Omit<Several, keyof Shared | 'multiple' | 'value' | 'defaultValue' | 'onValueChange'> & ComponentProps<'input'>  const id = useId()  const handle = useRef<ReturnType<typeof combobox> | null>(null)  /** The last query the owner gave or was told. */  const known = useRef<string | undefined>(undefined)  const heard = useRef(onQueryChange)  useEffect(() => { heard.current = onQueryChange })  const [first] = useState(value ?? defaultValue)  const [firstQuery] = useState(query)  const [chips, setChips] = useState<string[]>(() => (multiple ? [first ?? []].flat() as string[] : []))  const ref = useBehavior(combobox, multiple ? { filter, draw: setChips, removeLabel } : { filter }, {    value,    defaultValue,    onValueChange,    attached: (attached: unknown) => { handle.current = attached as ReturnType<typeof combobox> | null },    on: {      input: () => {        const next = handle.current?.query        if (next === undefined || next === known.current) return        heard.current?.(known.current = next)      },    },  } as never)  /** Where the first render drew a chosen option's name, that is what the field says: only a query given later is written over it. */  const drawn = useRef(false)  useEffect(() => {    if (!drawn.current) {      drawn.current = true      if (!multiple && options.some(option => option.value === first)) {        known.current = query        return      }    }    if (query === undefined || query === known.current || !handle.current) return    handle.current.query = known.current = query  }, [query])  const chosen = (option: ComboboxOption) => (multiple ? [first ?? []].flat().includes(option.value) : option.value === first)  const labelOf = (each: string) => options.find(option => option.value === each)?.label ?? each  const groups = [...new Set(options.map(option => option.group))]  return (    <div className={className ? `combobox ${className}` : 'combobox'} ref={ref}>      <div className={multiple ? 'input-group input-group-wrap' : 'input-group'}>        {multiple && (value !== undefined ? value as string[] : chips).map(each => (          <span className="chip" data-value={each} key={each}>            {labelOf(each)}            {name && <input type="hidden" name={name} value={each} />}            <button type="button" className="chip-remove" tabIndex={-1} aria-label={removeLabel(labelOf(each))}><svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M4 4L12 12" /><path d="M4 12L12 4" /></svg></button>          </span>        ))}        <input className="input-group-field" role="combobox" aria-expanded="false" aria-controls={`${id}list`} aria-autocomplete="list" autoComplete="off" defaultValue={(multiple ? undefined : options.find(option => option.value === first)?.label) ?? firstQuery} {...field} />        <button type="button" className="combobox-toggle" tabIndex={-1} aria-label={toggleLabel}><svg className="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(90 8 8)" /></svg></button>      </div>      <div id={`${id}list`} popover="manual" className="listbox" role="listbox" aria-label={listLabel} aria-multiselectable={multiple || undefined}>        {groups.map((group, index) => {          const rows = options.filter(option => option.group === group).map(option => (            <div className="listbox-option" role="option" key={option.value} data-value={option.value} aria-checked={chosen(option)} 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 group === undefined            ? rows            : (                <div className="listbox-group" role="group" aria-labelledby={`${id}group${index}`} key={group}>                  <div className="listbox-label" id={`${id}group${index}`}>{group}</div>                  {rows}                </div>              )        })}        {empty !== undefined && <div className="listbox-empty">{empty}</div>}      </div>    </div>  )}
ui/Combobox.svelte
<script lang="ts" module>  import type { HTMLInputAttributes } from 'svelte/elements'  export interface ComboboxOption {    /** What choosing the option gives `onValueChange`. */    value: string    /** What the option says, and what the field holds once it is chosen. */    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 ComboboxProps extends Omit<HTMLInputAttributes, 'value' | 'role' | 'children' | 'multiple' | 'name'> {    options: ComboboxOption[]    /**     * The value of the chosen option; null while the field holds text no option was chosen for. With     * `multiple`, the chosen values in the order they were chosen. Bind it, or leave it out.     */    value?: string | string[] | null    onValueChange?: (value: string | string[] | null) => void    /**     * The text in the field, what the reader is looking for. Bind it, or leave it out. It is not the value;     * with one value it holds the chosen option's label once one is chosen.     */    query?: string    /** Called with the text in the field each time the reader changes it, by typing or by choosing. */    onQueryChange?: (query: string) => void    /** Several values, each a chip in the field. */    multiple?: boolean    /** With `multiple`: the name each value is submitted with, in a hidden input of its chip. */    name?: string    /** With `multiple`: the accessible name of a chip's remove button. `Remove <label>` by default. */    removeLabel?: (label: string) => string    /** False when `options` are already the matches: search for `query` and give the matches as `options`. */    filter?: boolean    /** The name of the list, for assistive technology. */    listLabel: string    /** The name of the button that opens the list. */    toggleLabel: string    /** What the list says when no option matches. */    empty?: string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { combobox } from '@master/ui/behaviors/combobox.js'  import { behavior } from './behavior.svelte.js'  let { options, value = $bindable(), onValueChange, query = $bindable(), onQueryChange, multiple, name, removeLabel = (label: string) => `Remove ${label}`, filter = true, listLabel, toggleLabel, empty, class: className, ...field }: ComboboxProps = $props()  const id = $props.id()  const first = untrack(() => value)  const several = untrack(() => multiple)  const firsts = [first ?? []].flat() as string[]  // An option written later, from new options, is drawn with the value as it is then, which is not read as state.  const chosen = { values: firsts }  const text = (several ? undefined : untrack(() => options.find(option => option.value === first)?.label)) ?? untrack(() => query)  // With several values the behavior asks for the chips it wants; Svelte writes them from this list.  let chips = $state(several ? firsts : [])  const labelOf = (each: string) => options.find(option => option.value === each)?.label ?? each  const groups = $derived([...new Set(options.map(option => option.group))])  let handle = $state.raw<ReturnType<typeof combobox> | null>(null)  /** The last query the owner gave or was told. The first render drew the field, so the first query is known. */  let known: string | undefined = untrack(() => (!several && options.some(option => option.value === first) ? query : undefined))  const attach = behavior(combobox, () => (multiple ? { filter, removeLabel, draw: (values: string[]) => { chips = values } } : { filter }), {    value: () => value,    change: (next) => { chosen.values = [next ?? []].flat(); value = next; onValueChange?.(next) },    settled: (held) => { chosen.values = [held ?? []].flat() },    attached: (attached) => { handle = attached as ReturnType<typeof combobox> | null },    on: {      input: () => {        const next = handle?.query        if (next === undefined || next === known) return        query = known = next        onQueryChange?.(next)      },    },  })  $effect(() => {    const next = query    if (next === undefined || !handle || next === known) return    handle.query = known = next  })</script>{#snippet row(option: ComboboxOption)}  <!-- 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 combobox. Name the field with `aria-label`, or give it an `id` a label points at; every other prop of  an input goes to the field, so `oninput` hears what is typed. With `multiple`, the chosen values are chips  in the field.--><div class={['combobox', className]} {@attach attach}>  <div class={several ? 'input-group input-group-wrap' : 'input-group'}>    {#each chips as each (each)}      <span class="chip" data-value={each}>        {labelOf(each)}        {#if name}<input type="hidden" {name} value={each} />{/if}        <button type="button" class="chip-remove" tabindex={-1} aria-label={removeLabel(labelOf(each))}><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 4L12 12" /><path d="M4 12L12 4" /></svg></button>      </span>    {/each}    <input class="input-group-field" role="combobox" aria-expanded="false" aria-controls="{id}list" aria-autocomplete="list" autocomplete="off" value={text} {...field} />    <button type="button" class="combobox-toggle" tabindex={-1} aria-label={toggleLabel}><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="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(90 8 8)" /></svg></button>  </div>  <div id="{id}list" popover="manual" class="listbox" role="listbox" aria-label={listLabel} aria-multiselectable={several || undefined}>    {#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}    {#if empty !== undefined}<div class="listbox-empty">{empty}</div>{/if}  </div></div>
ui/Combobox.vue
<script lang="ts">export interface ComboboxOption {  /** What choosing the option gives the model. */  value: string  /** What the option says, and what the field holds once it is chosen. */  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, onMounted, ref, useAttrs, useId, useTemplateRef, watch, type FunctionalComponent } from 'vue'import { combobox } from '@master/ui/behaviors/combobox.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { options, filter = true, multiple, removeLabel = (label: string) => `Remove ${label}` } = defineProps<{  options: ComboboxOption[]  /** False when `options` are already the matches: search for the query and give the matches as `options`. */  filter?: boolean  /** Several values, each a chip in the field; the model is then the list of them. */  multiple?: boolean  /** With `multiple`: the name each value is submitted with, in a hidden input of its chip. */  name?: string  /** With `multiple`: the accessible name of a chip's remove button. `Remove <label>` by default. */  removeLabel?: (label: string) => string  /** The name of the list, for assistive technology. */  listLabel: string  /** The name of the button that opens the list. */  toggleLabel: string  /** What the list says when no option matches. */  empty?: string}>()/** * The value of the chosen option; null while the field holds text no option was chosen for. With * `multiple`, the chosen values in the order they were chosen: `v-model`. */const model = defineModel<string | string[] | null>()/** * The text in the field, what the reader is looking for: `v-model:query`. It is not the value; with one value * it holds the chosen option's label once one is chosen. */const query = defineModel<string>('query')/* * A combobox. Name the field with `aria-label`, or give it an `id` a label points at; every attribute but * the class goes to the field, so `@input` hears what is typed. With `multiple`, the chosen values are chips in * the field, which Vue writes from the list the behavior asks for. */const id = useId()const attrs = useAttrs()const field = () => {  const { class: _, ...rest } = attrs  return rest}const first = model.valueconst firsts = [first ?? []].flat() as string[]const several = multiple// The first label is the field's default value, an attribute: what is typed after is not Vue's to write.const firstLabel = (several ? undefined : options.find(option => option.value === first)?.label) ?? query.value// With several values the behavior asks for the chips it wants; Vue writes them from this list.const chips = ref<string[]>(several ? firsts : [])const labelOf = (each: string) => options.find(option => option.value === each)?.label ?? eachconst checked = (option: ComboboxOption) => (several ? firsts.includes(option.value) : option.value === first)const root = useTemplateRef<HTMLDivElement>('root')/** The last query the owner gave or was told. */// The first render drew the field, the chosen option's name before the query: the first query is known.let known: string | undefined = !several && options.some(option => option.value === first) ? query.value : undefinedconst behavior = useBehavior(root, combobox, () => (multiple ? { filter, removeLabel, draw: (values: string[]) => { chips.value = values } } : { filter }), model, {  input: () => {    const next = handle()?.query    if (next === undefined || next === known) return    query.value = known = next  },})const handle = () => behavior.handle() as ReturnType<typeof combobox> | undefined/** Query in: a query the owner gives is written into the field, and filters the options as typing does. */const write = () => {  const given = query.value  const current = handle()  if (given === undefined || !current || given === known) return  current.query = known = given}onMounted(write)watch(query, write, { flush: 'post' })const groups = computed(() => [...new Set(options.map(option => option.group))])const Row: FunctionalComponent<{ option: ComboboxOption }> = ({ option }) => h('div', {  'class': 'listbox-option',  'role': 'option',  'data-value': option.value,  'aria-checked': checked(option),  '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="combobox" :class="$attrs.class" ref="root">    <div :class="several ? 'input-group input-group-wrap' : 'input-group'">      <span v-for="each in chips" :key="each" class="chip" :data-value="each">        {{ labelOf(each) }}        <input v-if="name" type="hidden" :name="name" :value="each">        <button type="button" class="chip-remove" tabindex="-1" :aria-label="removeLabel(labelOf(each))"><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 4L12 12" /><path d="M4 12L12 4" /></svg></button>      </span>      <input class="input-group-field" role="combobox" aria-expanded="false" :aria-controls="`${id}-list`" aria-autocomplete="list" autocomplete="off" :value.attr="firstLabel" v-bind="field()">      <button type="button" class="combobox-toggle" tabindex="-1" :aria-label="toggleLabel"><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="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(90 8 8)" /></svg></button>    </div>    <div :id="`${id}-list`" popover="manual" class="listbox" role="listbox" :aria-label="listLabel" :aria-multiselectable="several || undefined">      <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 v-if="empty !== undefined" class="listbox-empty">{{ empty }}</div>    </div>  </div></template>

#类名

类名说明
combobox将列表框锚定到输入框的外层元素。
combobox-toggle字段末端的按钮,内含折线箭头图标,用于打开和关闭列表

它与 input-group、input-group-field 和带有 popover 属性的 listbox 配合使用。

组合框由以下组件组成,各组件保留自己的类名和状态。

#源码

@master/ui/components/combobox.css
/* * Combobox: a text field that opens a listbox of matches. * The wrapper names itself as an anchor and scopes that name, so its listbox opens against the whole field * and takes at least its width, with no measuring. Filtering, the active option and the popover's open state * belong to the script; the stylesheet reads aria-expanded to turn the chevron. */@layer components.ui {  .combobox {    display: block;    min-width: 0;    anchor-name: --combobox;    anchor-scope: --combobox;    /*     * The list. Without anchor positioning it stays where it is in the flow, directly under the field,     * which is why it is written after the field in the markup.     */    .listbox[popover] {      position-anchor: --combobox;      inset: auto;      margin: 6px 0;      min-inline-size: anchor-size(--combobox inline);    }    /* With several values, a chosen value grows out of the field it was chosen from, as in a tags field. */    .input-group-wrap .chip {      transform-origin: 100% 50%;      transition-property: opacity, scale;      transition-duration: var(--duration-quick);      transition-timing-function: var(--easing-glide);      /* The field is at the line's end, so right to left it stands on the left. */      &:dir(rtl) {        transform-origin: 0 50%;      }      @starting-style {        opacity: 0;        scale: .8;      }      @media (prefers-reduced-motion: reduce) {        transition-property: opacity;        @starting-style {          scale: 1;        }      }    }  }  /* The button that opens the list from the field's end: a chevron that turns over while the list is open. */  .combobox-toggle {    position: relative;    display: inline-grid;    flex: none;    place-items: center;    width: 1.5rem;    height: 1.5rem;    /* Its chevron ends 2px inside the field's padding at every size, where a select's chevron ends. */    margin-block: 0;    margin-inline: 0 -.4375rem;    padding: 0;    border: 0;    border-radius: calc((var(--radius-chip) - 2px) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: transparent;    -webkit-tap-highlight-color: transparent;    color: var(--color-text-muted);    appearance: none;    cursor: pointer;    /* The glyph is the button's icon. It takes no pointer of its own, so a press is the button's. */    .icon {      pointer-events: none;      width: .875rem;      height: .875rem;      transition: rotate var(--duration-base) var(--easing-glide);    }    @media (hover: hover) {      &:hover:not(:disabled) {        color: var(--color-text-strong);      }    }    /* Pressed: the strong ink, as under the pointer. */    &:active:not(:disabled) {      color: var(--color-text-strong);    }    /* Disabled with its field: the chevron takes the field's disabled ink and answers no pointer. */    &:disabled, .combobox:has(.input-group-field:disabled) & {      color: var(--color-text-disabled);      cursor: not-allowed;    }    /* A read-only field opens no list either: the chevron keeps its quiet ink under the pointer and offers no press. */    .combobox:has(.input-group-field[readonly]:not(:disabled)) &:not(:disabled) {      color: var(--color-text-muted);      cursor: default;    }    &:focus-visible {      @apply --focus-ring;      outline-offset: 0;    }    @media (prefers-reduced-motion: reduce) {      .icon {        transition: none;      }    }    @media (forced-colors: active) {      .icon {        color: ButtonText;      }      &:disabled .icon, .combobox:has(.input-group-field:disabled) & .icon {        color: GrayText;      }    }    /* On touch the target reaches 44px around the toggle, which keeps its size, and so does the field. */    @media (pointer: coarse) {      &::after {        @apply --touch-target;      }    }  }  .combobox:has([aria-expanded="true"]) .combobox-toggle .icon {    rotate: x 180deg;  }}