导航

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 或输入分隔符(默认为逗号)时,输入框中的文字会转为一个值:脚本在输入框之前写入一个胶囊标签,并清空输入框。粘贴的文字中含有分隔符、换行符或制表符时,会拆分成相应数量的值,最后一个分隔符之后的内容留在输入框中。
  • 拒绝。 值为空、已存在、超出 max,或被 validate 拒绝时,不会被添加。输入框保留这段文字,因此输入的内容不会丢失,并在文字改变前一直带有 aria-invalid="true"。
  • 删除。 点击胶囊标签的移除按钮即可删除该值,焦点随后回到输入框。
  • 表单。 如果现有胶囊标签已带有设置了 name 的隐藏输入框,或传入了 name 选项,新的胶囊标签也会带有一个保存其值的隐藏输入框,这样表单会以该名称提交所有值。重置表单时,会恢复输入框最初的那些值。
  • 事件。 每次添加或删除值时,根元素都会派发 input 和 change。返回的函数带有 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%;    }  }}