網站導覽

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。

#選擇控制項

若純文字選項不超過 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-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;  }}