Navigation

v2.1.0
Forms

Tags

A field that turns what is typed into values, each a chip in the well.

On this page

A tags field turns what is typed into values, each a chip in the well. It is an input group with input-group-wrap and the tags class: the well, its states and the concentric chips are the input group's, and the field after the chips takes the next value. The tags behavior turns the text into chips and moves focus between them.

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>
Type a label and press Enter. Backspace in the empty field reaches the last label, and Backspace again removes it.

#What it adds to the input group

  • A value arrives. A new chip grows out of the place the caret stood in, a short scale from 80% with the quick duration, instead of appearing. With reduced motion it only fades in.
  • Room for a word. The field keeps at least --tags-field-min, 6rem by default, and takes a line of its own below that, so the caret is never squeezed into a sliver at the end of a line.
  • A value the keys are on wears the focus ring as a whole, since Backspace there removes all of it, and its cross takes the pressed tone. The ring is the chip's: a chip with a chip-remove draws it wherever it stands.
  • A value that is refused marks the field aria-invalid="true", which the input group draws as the danger edge until the text changes.

Without @starting-style a new value appears at once.

#The behavior

tags takes the root, the input group with the tags class, and returns the function that detaches it.

app.js
import { tags } from '@master/ui/behaviors/tags.js'const detach = tags(document.querySelector('.tags'), { max: 10 })
  • Adding. Enter, and a delimiter, a comma by default, turn the field's text into a value: a chip is written before the field and the field is emptied. Pasted text with delimiters, line breaks or tabs in it becomes as many values, and what follows the last delimiter stays in the field.
  • Refusing. A value that is empty, already there, past max or refused by validate is not added. The field keeps the text, so nothing typed is lost, and says aria-invalid="true" until it changes.
  • Removing. A chip's remove button removes it on a click, and focus returns to the field.
  • The form. A chip carries a hidden input with its value when the chips already carry one with a name, or when name is given, so a form submits every value under that name. A form's reset puts back the values the field started with.
  • Events. The root dispatches input and change each time a value is added or removed. The function it returns has a value, the values in order; set it to replace them, which dispatches nothing.
OptionDefault
delimiters[',']Keys that add the value as Enter does; [] leaves only Enter
maxnoneHow many values the field holds at most
validatenoneA function that says whether a value may be added
namethe chips'The name of the hidden input a new chip carries
removeLabelRemove <value>The accessible name of a chip's remove button, in the page's language
drawnoneTakes over writing the chips, for a renderer that writes them from its own list

A chip stands for its data-value, or for its text. Without the behavior the field is a text input and its chips are fixed: a form still submits the hidden inputs they carry.

#Suggestions

A <datalist> gives the field the browser's own suggestions with no script of its own: the reader picks one, then presses Enter to add it. When the values have to come from a list, use a combobox with several values instead.

Suggestions

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

#Keyboard

The field is the one tab stop. The chips are reached from it, and their remove buttons are out of the tab order with tabindex="-1". While an input method composes, Enter belongs to it.

KeysAction
Enter, CommaTurn the field's text into a value; Enter in an empty field is left to the form
BackspaceIn an empty field, move to the last value; on a value, remove it and move to the one before
DeleteOn a value, remove it and move to the one after
ArrowLeft, ArrowRightFrom the start of the field, move to the last value; between values, move to the one before or after, and past the last back to the field. The other way around from right to left
Home, EndOn a value, move to the first value, or back to the field
EscapeOn a value, return to the field

#Accessibility

  • Label the field, with a <label> or aria-label. Say how a value is added in a hint under it: a comma or Enter is not obvious.
  • Name each remove button with the value it removes, in the page's language: removeLabel does that for the chips the behavior writes.
  • A value that is refused leaves the text in the field and marks it invalid; say why in the field's hint or error, as for any field.

#React, Svelte and Vue

The tags component writes the chips from the value and attaches the behavior, which turns what is typed into values. Copy it into the project with npx master-ui add tags; React, Svelte and Vue says how the components are built and used.

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>

#Classes

ClassDescription
tagsOn an input group with input-group-wrap: the values are its chips and the field takes the next one, keeping room for a word before it wraps to a line of its own

It is used with input-group, input-group-wrap, input-group-field, and a chip with a chip-remove for each value.

#Custom properties

PropertyDefaultDescription
--tags-field-min6remThe narrowest the field becomes before it wraps to a line of its own

#Source

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