ナビゲーション

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

返される関数には 2 つのプロパティがあり、外部から読み取りと設定ができます。どちらを設定してもイベントは発行されません。

  • 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 キーを押すと最後のチップに移動し、もう一度押すとそのチップを削除します。
  • フィールドは検索専用 文字を入力するとリストが絞り込まれますが、チェックが外れることはありません。選択した値はチップが保持します。
  • チップ Tab キーで止まるのはフィールドだけです。空のフィールドで Backspace を押すか、戻る方向を指す矢印キーを押すとチップに移動します。チップ上でのキー操作はタグ入力と同じです。削除ボタンまたは Backspace でチップを削除すると、対応する選択肢のチェックが外れます。
  • フォーム 既存のチップが name 付きの hidden input を持っている場合、または name を指定した場合、ビヘイビアが書き込むチップは値を持つ hidden input を含みます。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 にします。

#コントロールの選び方

単純な選択肢が 12 個程度までなら、セレクトを使うと、スクリプトなしでプラットフォーム標準の文字入力による候補選択が使えます。検索が必要な長いリスト、入力に応じて候補を読み込むリスト、複数の要素を含む行には、コンボボックスを使います。

#キーボード操作

キー操作はビヘイビアが処理します。リストが閉じているときや、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-label でラベル付けされた listbox-group 内に書き出されます。選択肢がすべて絞り込みで除外されたグループは、選択肢と一緒に非表示になります。値のほかにクエリも受け渡します。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;  }}