ナビゲーション

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 キーを押すと最後のラベルに移動し、もう一度押すとそのラベルを削除します。

#入力グループに加わる機能

  • 値の追加 新しいチップは、いきなり表示されるのではなく、キャレットのあった位置から quick の再生時間で 80% から短く拡大して現れます。動きを抑える設定では、フェードインだけになります。
  • 単語 1 つ分の幅 フィールドは少なくとも --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 付きの hidden input を持っている場合、または name を指定した場合、各チップは値を持つ hidden input を含みます。そのため、フォームはすべての値をその名前で送信します。フォームをリセットすると、フィールドに最初にあった値に戻ります。
  • イベント 値を追加または削除するたびに、ルート要素が input と change を発行します。返される関数の value は、値を順番どおりに並べたものです。value に代入すると値が置き換わりますが、イベントは発行されません。
オプション既定値
delimiters[',']Enter と同様に値を追加するキー。[] にすると Enter だけになります
maxなしフィールドに入れられる値の最大数
validateなし値を追加してよいかどうかを判定する関数
name既存のチップが持つ hidden input の名前新しいチップが持つ hidden input の名前
removeLabelRemove <value>チップの削除ボタンのアクセシブルネーム。ページの言語で指定します
drawなしチップの書き込みを肩代わりします。独自のリストからチップを描画するレンダラー向けです

チップは data-value、なければテキストを値とします。ビヘイビアを適用しない場合、フィールドは通常のテキスト入力で、チップは固定されます。その場合も、チップが持つ hidden input はフォームで送信されます。

#入力候補

<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>

#クラス

クラス説明
tagsinput-group-wrap を指定した入力グループに適用します。チップが値を表し、フィールドが次の値を受け付けます。フィールドは単語 1 つ分の幅を確保し、それより狭くなると次の行に単独で移ります。

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%;    }  }}