網站導覽

v2.1.0
表單

標籤輸入

將輸入的文字轉成值的欄位,每個值都以膠囊標籤顯示在凹槽內。

本頁內容

標籤輸入會將輸入的文字轉成值,每個值都以膠囊標籤顯示在凹槽內。它是帶有 input-group-wrap 和 tags 類別的輸入群組:凹槽、凹槽的各種狀態和同心圓角的膠囊標籤都來自輸入群組,膠囊標籤後方的欄位則用來輸入下一個值。tags 行為負責將文字轉成膠囊標籤,並在膠囊標籤之間移動焦點。

標籤輸入

<div class="field max-w(420) mx-auto">  <label for="labels">Labels</label>  <div class="tags input-group input-group-wrap">    <span class="chip" data-value="design">      design<input type="hidden" name="labels" value="design"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove design">        <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>    <span class="chip" data-value="research">      research<input type="hidden" name="labels" value="research"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove research">        <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>    <span class="chip" data-value="accessibility">      accessibility<input type="hidden" name="labels" value="accessibility"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove accessibility">        <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="labels" placeholder="Add a label" autocomplete="off" aria-describedby="labels-hint">  </div>  <p class="field-hint" id="labels-hint">Press Enter or type a comma after each label.</p></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'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="field max-w(420) mx-auto">      <label htmlFor="labels">Labels</label>      <div className="tags input-group input-group-wrap">        <span className="chip" data-value="design">          design<input type="hidden" name="labels" value="design" /><button type="button" className="chip-remove" tabIndex={-1} aria-label="Remove design">            <XIcon className="icon" />          </button>        </span>        <span className="chip" data-value="research">          research<input type="hidden" name="labels" value="research" /><button type="button" className="chip-remove" tabIndex={-1} aria-label="Remove research">            <XIcon className="icon" />          </button>        </span>        <span className="chip" data-value="accessibility">          accessibility<input type="hidden" name="labels" value="accessibility" /><button type="button" className="chip-remove" tabIndex={-1} aria-label="Remove accessibility">            <XIcon className="icon" />          </button>        </span>        <input className="input-group-field" id="labels" placeholder="Add a label" autoComplete="off" aria-describedby="labels-hint" />      </div>      <p className="field-hint" id="labels-hint">Press Enter or type a comma after each label.</p>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import XIcon from '@master/icons-svelte/native/16/soft/x'</script><div class="field max-w(420) mx-auto" {@attach attach}>  <label for="labels">Labels</label>  <div class="tags input-group input-group-wrap">    <span class="chip" data-value="design">      design<input type="hidden" name="labels" value="design"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove design">        <XIcon class="icon" />      </button>    </span>    <span class="chip" data-value="research">      research<input type="hidden" name="labels" value="research"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove research">        <XIcon class="icon" />      </button>    </span>    <span class="chip" data-value="accessibility">      accessibility<input type="hidden" name="labels" value="accessibility"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove accessibility">        <XIcon class="icon" />      </button>    </span>    <input class="input-group-field" id="labels" placeholder="Add a label" autocomplete="off" aria-describedby="labels-hint">  </div>  <p class="field-hint" id="labels-hint">Press Enter or type a comma after each label.</p></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'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="field max-w(420) mx-auto">    <label for="labels">Labels</label>    <div class="tags input-group input-group-wrap">      <span class="chip" data-value="design">        design<input type="hidden" name="labels" value="design"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove design">          <XIcon class="icon" />        </button>      </span>      <span class="chip" data-value="research">        research<input type="hidden" name="labels" value="research"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove research">          <XIcon class="icon" />        </button>      </span>      <span class="chip" data-value="accessibility">        accessibility<input type="hidden" name="labels" value="accessibility"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove accessibility">          <XIcon class="icon" />        </button>      </span>      <input class="input-group-field" id="labels" placeholder="Add a label" autocomplete="off" aria-describedby="labels-hint">    </div>    <p class="field-hint" id="labels-hint">Press Enter or type a comma after each label.</p>  </div></template>
輸入標籤後按 Enter。在空白欄位中按 Backspace 會移到最後一個標籤,再按一次 Backspace 即可移除。

#在輸入群組之外增加的功能

  • 新增值時。 新的膠囊標籤會從文字游標原本的位置出現,並以快速動畫從 80% 放大至原尺寸。啟用減少動態效果時,只會淡入。
  • 保留輸入空間。 欄位寬度至少為 --tags-field-min,預設為 6rem;剩餘空間小於這個寬度時,欄位會換到下一列,文字游標就不會被擠在列尾的窄縫裡。
  • 鍵盤焦點所在的值整個顯示焦點外框,因為在這裡按 Backspace 會移除整個值,值上的叉號也會呈現按下時的色調。焦點外框屬於膠囊標籤本身:帶有 chip-remove 的膠囊標籤無論放在哪裡都會顯示。
  • 被拒絕的值會讓欄位設為 aria-invalid="true",輸入群組會將其顯示為危險色邊框,直到文字變更為止。

瀏覽器若不支援 @starting-style,新的值會直接出現。

#行為

tags 接收根元素,也就是帶有 tags 類別的輸入群組,並傳回用來解除行為的函式。

app.js
import { tags } from '@master/ui/behaviors/tags.js'const detach = tags(document.querySelector('.tags'), { max: 10 })
  • 新增。 按 Enter 或輸入分隔符號(預設為逗號)時,欄位中的文字會轉成一個值:膠囊標籤會寫在欄位前方,欄位隨即清空。貼上的文字若含有分隔符號、換行或 Tab 字元,就會拆成相應數量的值,最後一個分隔符號之後的文字則留在欄位中。
  • 拒絕。 值為空、已存在、加入後會使總數超過 max,或未通過 validate 時,都不會加入。欄位會保留文字,因此輸入的內容不會遺失,並會維持 aria-invalid="true",直到文字變更為止。
  • 移除。 點擊膠囊標籤的移除按鈕即可移除該值,焦點會回到欄位。
  • 表單。 若現有的膠囊標籤已帶有設定 name 的隱藏輸入元件,或有傳入 name,每個膠囊標籤都會帶有一個存放其值的隱藏輸入元件,因此表單會以該名稱送出所有值。重設表單時,會還原欄位一開始的值。
  • 事件。 每次新增或移除值時,根元素都會派送 input 和 change。傳回的函式帶有 value,依序列出所有值;設定 value 會取代這些值,但不會派送任何事件。
選項預設值
delimiters[',']與 Enter 一樣會新增值的按鍵;設為 [] 時只有 Enter 會新增
max無欄位最多可容納的值數量
validate無判斷值是否可以加入的函式
name沿用現有膠囊標籤所帶隱藏輸入元件的名稱新膠囊標籤所帶隱藏輸入元件的名稱
removeLabelRemove <value>膠囊標籤移除按鈕的無障礙名稱,請使用頁面的語言
draw無接手寫入膠囊標籤,適用於依自己的清單寫入膠囊標籤的渲染器

膠囊標籤代表其 data-value,沒有時則代表其文字。未掛上行為時,欄位就是一般的文字輸入欄位,膠囊標籤也固定不變;表單仍會送出膠囊標籤所帶的隱藏輸入元件。

#建議值

<datalist> 不需要額外腳本,就能讓欄位顯示瀏覽器內建的建議值:使用者先選取一個建議,再按 Enter 加入。若值必須來自既定清單,請改用多值組合方塊。

建議值

<div class="field max-w(420) mx-auto">  <label for="recipients">Recipients</label>  <div class="tags input-group input-group-wrap">    <span class="chip" data-value="ada@example.com">      ada@example.com<input type="hidden" name="to" value="ada@example.com"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove ada@example.com">        <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="recipients" type="email" list="recipient-suggestions" placeholder="Add a recipient" autocomplete="off">  </div>  <datalist id="recipient-suggestions">    <option value="grace@example.com"></option>    <option value="linus@example.com"></option>    <option value="margaret@example.com"></option>  </datalist></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'export function Example() {  const root = useRef<HTMLDivElement>(null)  useEffect(() => attach(root.current!), [])  return (    <div ref={root} className="field max-w(420) mx-auto">      <label htmlFor="recipients">Recipients</label>      <div className="tags input-group input-group-wrap">        <span className="chip" data-value="ada@example.com">          ada@example.com<input type="hidden" name="to" value="ada@example.com" /><button type="button" className="chip-remove" tabIndex={-1} aria-label="Remove ada@example.com">            <XIcon className="icon" />          </button>        </span>        <input className="input-group-field" id="recipients" type="email" list="recipient-suggestions" placeholder="Add a recipient" autoComplete="off" />      </div>      <datalist id="recipient-suggestions">        <option value="grace@example.com"></option>        <option value="linus@example.com"></option>        <option value="margaret@example.com"></option>      </datalist>    </div>  )}
<script>  import { attach } from '@master/ui/behaviors'  import XIcon from '@master/icons-svelte/native/16/soft/x'</script><div class="field max-w(420) mx-auto" {@attach attach}>  <label for="recipients">Recipients</label>  <div class="tags input-group input-group-wrap">    <span class="chip" data-value="ada@example.com">      ada@example.com<input type="hidden" name="to" value="ada@example.com"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove ada@example.com">        <XIcon class="icon" />      </button>    </span>    <input class="input-group-field" id="recipients" type="email" list="recipient-suggestions" placeholder="Add a recipient" autocomplete="off">  </div>  <datalist id="recipient-suggestions">    <option value="grace@example.com"></option>    <option value="linus@example.com"></option>    <option value="margaret@example.com"></option>  </datalist></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'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <div ref="root" class="field max-w(420) mx-auto">    <label for="recipients">Recipients</label>    <div class="tags input-group input-group-wrap">      <span class="chip" data-value="ada@example.com">        ada@example.com<input type="hidden" name="to" value="ada@example.com"><button type="button" class="chip-remove" tabindex="-1" aria-label="Remove ada@example.com">          <XIcon class="icon" />        </button>      </span>      <input class="input-group-field" id="recipients" type="email" list="recipient-suggestions" placeholder="Add a recipient" autocomplete="off">    </div>    <datalist id="recipient-suggestions">      <option value="grace@example.com"></option>      <option value="linus@example.com"></option>      <option value="margaret@example.com"></option>    </datalist>  </div></template>

#鍵盤操作

欄位是唯一的 Tab 停駐點。可從欄位將焦點移到膠囊標籤,膠囊標籤的移除按鈕則以 tabindex="-1" 移出 Tab 順序。輸入法組字期間,Enter 會交由輸入法處理。

按鍵動作
Enter, Comma將欄位中的文字轉成一個值。在空白欄位中按 Enter 時,交由表單處理
Backspace在空白欄位中,移到最後一個值;在值上時,移除該值並移到前一個值
Delete在值上時,移除該值並移到後一個值
ArrowLeft, ArrowRight在欄位開頭時,移到最後一個值;在值之間時,移到前一個或後一個值,越過最後一個值時回到欄位。由右至左排列時方向相反
Home, End在值上時,移到第一個值,或回到欄位
Escape在值上時,回到欄位

#無障礙

  • 用 <label> 或 aria-label 為欄位加上標籤。在欄位下方的提示中說明如何新增值,因為使用者不一定知道可以用逗號或 Enter 新增。
  • 用頁面的語言,以要移除的值為每個移除按鈕命名;行為寫入的膠囊標籤可透過 removeLabel 設定。
  • 被拒絕的值會將文字留在欄位中,並將欄位標示為無效。請和其他欄位一樣,在欄位的提示或錯誤訊息中說明原因。

#React、Svelte 和 Vue

tags 元件會根據值寫入膠囊標籤,並掛上將輸入文字轉成值的行為。用 npx master-ui add tags 將元件複製到專案中。元件的建置與使用方式請參閱 React、Svelte 和 Vue。

ui/tags.tsx
'use client'import { useState, type ComponentProps } from 'react'import { tags } from '@master/ui/behaviors/tags.js'import { useBehavior } from './use-behavior'export interface TagsProps extends Omit<ComponentProps<'input'>, 'value' | 'defaultValue' | 'name' | 'max'> {  /** The values, in order. */  value?: string[]  defaultValue?: string[]  onValueChange?: (value: string[]) => void  /** The name each value is submitted with, in a hidden input of its chip. */  name?: string  /** How many values the field holds at most. */  max?: number  /** Keys that add a value as Enter does. `[',']` by default. */  delimiters?: string[]  /** Says whether a value may be added. */  validate?: (value: string) => boolean  /** The accessible name of a chip's remove button. `Remove <value>` by default. */  removeLabel?: (value: string) => string}/** * A tags field. 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. React writes the chips from the value; the behavior turns what is typed into * values and moves focus between the chips. */export function Tags({ value, defaultValue, onValueChange, name, max, delimiters, validate, removeLabel = (text: string) => `Remove ${text}`, className, ...field }: TagsProps) {  const [shown, setShown] = useState(() => value ?? defaultValue ?? [])  // The behavior keeps the values it asked for, so the chips may be written after it has said so.  const draw = setShown  const ref = useBehavior(tags, { max, delimiters, validate, removeLabel, draw, name }, { value, defaultValue, onValueChange })  const values = value ?? shown  return (    <div className={className ? `tags input-group input-group-wrap ${className}` : 'tags input-group input-group-wrap'} ref={ref}>      {values.map(each => (        <span className="chip" data-value={each} key={each}>          {each}          {name && <input type="hidden" name={name} value={each} />}          <button type="button" className="chip-remove" tabIndex={-1} aria-label={removeLabel(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" autoComplete="off" {...field} />    </div>  )}
ui/Tags.svelte
<script lang="ts" module>  import type { HTMLInputAttributes } from 'svelte/elements'  export interface TagsProps extends Omit<HTMLInputAttributes, 'value' | 'name' | 'max' | 'children'> {    /** The values, in order. Bind it, or leave it out. */    value?: string[]    onValueChange?: (value: string[]) => void    /** The name each value is submitted with, in a hidden input of its chip. */    name?: string    /** How many values the field holds at most. */    max?: number    /** Keys that add a value as Enter does. `[',']` by default. */    delimiters?: string[]    /** Says whether a value may be added. */    validate?: (value: string) => boolean    /** The accessible name of a chip's remove button. `Remove <value>` by default. */    removeLabel?: (value: string) => string  }</script><script lang="ts">  import { untrack } from 'svelte'  import { tags } from '@master/ui/behaviors/tags.js'  import { behavior } from './behavior.svelte.js'  let { value = $bindable(), onValueChange, name, max, delimiters, validate, removeLabel = (text: string) => `Remove ${text}`, class: className, ...field }: TagsProps = $props()  // The behavior asks for the chips it wants; Svelte writes them from this list.  let shown = $state(untrack(() => value) ?? [])  const attach = behavior(tags, () => ({ max, delimiters, validate, removeLabel, name, draw: (values: string[]) => { shown = values } }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },  })</script><!--  @component  A tags field. 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.--><div class={['tags input-group input-group-wrap', className]} {@attach attach}>  {#each shown as each (each)}    <span class="chip" data-value={each}>      {each}      {#if name}<input type="hidden" {name} value={each} />{/if}      <button type="button" class="chip-remove" tabindex={-1} aria-label={removeLabel(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" autocomplete="off" {...field} /></div>
ui/Tags.vue
<script setup lang="ts">import { ref, useAttrs, useTemplateRef } from 'vue'import { tags } from '@master/ui/behaviors/tags.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { name, max, delimiters, validate, removeLabel = (text: string) => `Remove ${text}` } = defineProps<{  /** The name each value is submitted with, in a hidden input of its chip. */  name?: string  /** How many values the field holds at most. */  max?: number  /** Keys that add a value as Enter does. `[',']` by default. */  delimiters?: string[]  /** Says whether a value may be added. */  validate?: (value: string) => boolean  /** The accessible name of a chip's remove button. `Remove <value>` by default. */  removeLabel?: (value: string) => string}>()/** The values, in order: `v-model`. */const model = defineModel<string[]>()/* * A tags field. Name the field with `aria-label`, or give it an `id` a label points at; every attribute but * the class goes to the field. */const attrs = useAttrs()const field = () => {  const { class: _, ...rest } = attrs  return rest}// The behavior asks for the chips it wants; Vue writes them from this list.const shown = ref<string[]>(model.value ?? [])const root = useTemplateRef<HTMLDivElement>('root')useBehavior(root, tags, () => ({ name, max, delimiters, validate, removeLabel, draw: (values: string[]) => { shown.value = values } }), model)</script><template>  <div class="tags input-group input-group-wrap" :class="$attrs.class" ref="root">    <span v-for="each in shown" :key="each" class="chip" :data-value="each">      {{ each }}      <input v-if="name" type="hidden" :name="name" :value="each">      <button type="button" class="chip-remove" tabindex="-1" :aria-label="removeLabel(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" autocomplete="off" v-bind="field()">  </div></template>

#類別

類別說明
tags用於帶有 input-group-wrap 的輸入群組:群組內的膠囊標籤就是各個值,欄位用來輸入下一個值,並在換到獨立一列之前保留至少一個詞的寬度

搭配 input-group、input-group-wrap、input-group-field 使用,每個值則是一個帶有 chip-remove 的 chip。

#自訂屬性

屬性預設值說明
--tags-field-min6rem欄位換到獨立一列之前的最小寬度

#原始碼

@master/ui/components/tags.css
/* * Tags: a field that turns what is typed into values, each a chip in the well. * It is an input group with input-group-wrap, so the well, its states and the concentric chips are the input * group's. What tags add is the life of a value: a new chip grows out of the place the caret stood in, the * field keeps room for a word and takes a line of its own past that, and a chip the keys are on is marked as * a whole, since Backspace there removes all of it. * The script, the tags behavior, turns the text into chips and moves focus between them; without it the field * is a text input whose chips are fixed. */@layer components.ui {  .tags {    /* The narrowest the field becomes before it wraps to a line of its own. */    --tags-field-min: 6rem;    /* The script listens on the whole well: a tap there must not flash it grey on iOS. */    -webkit-tap-highlight-color: transparent;    /* As specific as the wrapping input group's own flex for its field, and later, so this one holds. */    &.input-group-wrap .input-group-field {      flex: 1 1 var(--tags-field-min);    }    /* A value arrives: it grows from the start of the field, where it was typed, instead of appearing. */    .chip {      transform-origin: 100% 50%;      transition-property: opacity, scale;      transition-duration: var(--duration-quick);      transition-timing-function: var(--easing-glide);      @starting-style {        opacity: 0;        scale: .8;      }      @media (prefers-reduced-motion: reduce) {        transition-property: opacity;        @starting-style {          scale: 1;        }      }    }    &:dir(rtl) .chip {      transform-origin: 0 50%;    }  }}