Skip to content

Component specification for GhostTagsInput ​

Status: Approved for #416.

Purpose and user problems ​

A Vue author needs a labelled field for editable strings such as project labels or skills. A user can type a new tag, remove an existing tag, and submit the committed collection as ordinary form data. An unfinished entry stays available while the user reviews the existing tags.

Non-goals ​

Suggestions, predefined choices, remote validation, object-valued tags, tag editing in place, and drag reordering are outside this contract. Consumers control business validation and can reorder or replace the string array. A predefined multi-selection field belongs to GhostSelect.

Public API ​

Props and configuration ​

Use one named GhostTagsInput export from @ghostvue/vue. The themed export in @ghostvue/themes wraps the same behavior. The example shows the approved themed API.

PropTypeDefaultContract
modelValuereadonly string[]omittedControlled committed tags. An empty array is controlled.
defaultValuereadonly string[][]Initial uncontrolled tags and reset baseline for either mode. Snapshot once at setup.
delimitersreadonly (',' | ';')[][]Opt-in typed separators and paste splitting. Enter always works.
namestringomittedRepeated form entry name. An empty or omitted name suppresses submission.
disabledbooleanfalseDisable editing, remove controls, focus and submission.
readonlybooleanfalseKeep the entry focusable and submit the tags. Suppress editing and remove controls.
requiredbooleanfalseAn editable field requires at least one committed tag.
invalidbooleanfalseConsumer validation state for the entry and styling.
messagesPartial<GhostTagsInputMessages>omittedReactive overrides for component-owned text. See Messages.

The only model event is update:modelValue(next: string[]). Each emitted array is fresh. The instance exposes element: HTMLInputElement | null and focus(), which focuses the text input. The default tag display shows the tag text and a native remove button. A tag slot exposes { value: string } for the text content while the component retains control of the remove button, its name and its keyboard behavior. Tag slot content is non-interactive.

vue
<script setup lang="ts">
import { ref } from 'vue'
import {
  GhostField,
  GhostFieldControl,
  GhostFieldDescription,
  GhostFieldLabel,
  GhostTagsInput,
} from '@ghostvue/themes'

const initialLabels = ['frontend']
const labels = ref([...initialLabels])
</script>

<template>
  <form>
    <GhostField>
      <GhostFieldLabel>Project labels</GhostFieldLabel>
      <GhostFieldDescription>
        Press Enter to add a label. When the entry is empty, press Backspace to
        focus the last label’s remove button.
      </GhostFieldDescription>
      <GhostFieldControl v-slot="field">
        <GhostTagsInput
          v-bind="field"
          v-model="labels"
          :default-value="initialLabels"
          name="labels"
        />
      </GhostFieldControl>
    </GhostField>
    <button type="submit">Save project</button>
    <button type="reset">Reset labels</button>
  </form>
</template>

Type urgent and press Enter to add it. Use the Remove urgent button to remove it. Reset labels restores ['frontend'] even after removing both labels.

Messages ​

Export GhostTagsInputMessages from @ghostvue/vue and re-export the type from the themed package. Follow GhostFileUpload's message overrides with English defaults and application-supplied formatters that handle pluralization.

ts
interface GhostTagsInputMessages {
  removeLabel(value: string): string
  added(values: readonly string[]): string
  removed(value: string): string
  duplicate(value: string): string
  required: string
}
KeyEnglish default
removeLabelRemove
added{value} added. / {count} tags added.
removed{value} removed.
duplicate{value} already exists.
requiredAdd at least one tag.

added receives the accepted strings in proposal order. When paste produces no new tags, duplicate receives the first repeated value in paste order. Omitted overrides use the corresponding default. Re-read the current overrides when an announcement is produced and update button names and the current native validity message when the locale changes. A blank formatter result can suppress a live announcement. Blank removeLabel and required overrides use the default so every button stays named and missing tags keep the field invalid. Caller-supplied labels, tag content and hints remain application text.

Form submission and reset ​

The editable input handles labelling, native focus and constraint validation. The name applies to one hidden form input per committed tag, in rendered order. The draft is never submitted. new FormData(form).getAll('labels') returns ['frontend', 'urgent'] after the example add, and [] for an empty collection. An explicit form attribute associates the text input and the hidden inputs with the same form, including across dynamic association changes. An ancestor disabled fieldset applies native disabled rules to all those controls, including the first legend exception.

Use the native input for the required constraint. Set aria-required on the input without making the draft itself natively required. Set native custom validity with messages.required when the editable field requires a tag and has none, even if the draft has text. Clear the missing-tag constraint when a tag is accepted or required is removed. The invalid prop and Field error remain independent of this constraint. A browser validation failure focuses the input, which remains visible and focusable. Native readonly and disabled controls are barred from constraint validation.

Use the text input's current form owner for native reset. After reset dispatch finishes, skip a canceled reset or a form that is no longer the input's owner. Clear the draft and restore the captured defaultValue (empty when omitted). A controlled field requests that array and keeps displaying the parent's actual tags. An uncontrolled field writes it locally. Emit at most one update when the normalized sequence differs. Clear the live message without announcing a series of removals on reset. Keep focus where it is unless the focused remove button disappears.

State model ​

Draft text is local to the input. Committed tags are local when modelValue is undefined and parent-owned otherwise. Keep the ownership mode for the instance lifetime. Only committed changes emit the model event. A successful add clears the draft and keeps input focus. A removal preserves the draft. Blur and Tab preserve the draft without committing or sending an update.

  • Enter: A nonempty trimmed draft proposes one tag and consumes Enter to avoid submitting the form. A blank draft leaves native Enter behavior available, including implicit form submission and native validation. A duplicate leaves the draft in place and announces that it already exists.
  • Typed delimiter: An enabled separator consumes a printable key only at the end of the text with no selection. Apply the same trim and duplicate rules as Enter. A separator with a blank draft at that position is ignored and consumed. At other caret positions leave ordinary text editing intact.
  • Paste: With no configured separator, paste is native editing. When a paste contains a configured delimiter, replace the selected draft range with the clipboard text, split the result on configured delimiters, trim tokens, and skip blanks and duplicate values in first-occurrence order. Propose the new tags in one event. With no new tags, keep the original draft and selection. Announce the duplicate only when at least one token already exists. An accepted multi-tag paste clears the draft.
  • IME: Do not intercept Enter, separators, paste or removal while composing. Observe composition start/end and the event's composing state, including the browser key-code 229 fallback. Composition end only updates draft text. A subsequent ordinary key or paste can commit it. Leave Alt, Ctrl and Meta shortcuts alone. A Shift-modified printable key can insert a configured delimiter. Shift+navigation in the input remains native text selection.

For a controlled edit, emit one proposal and reconcile after the next Vue render flush. An add succeeds when the proposed new tags are present in the rendered value. Removal succeeds when its string is absent. Until settlement, leave the current draft and focus intact and accept no second user mutation against the stale array. Clear the draft on acceptance only if the user has not edited it since the request. Announce the action only after acceptance. Retaining the old value rejects the request. Later parent updates render as ordinary external replacements, without replaying the draft clear or announcement. Keep submit mirrors tied to the rendered value throughout.

The empty collection keeps the ordinary input available. There are no loading or remote-request states. Read-only mode preserves the draft for later editing and shows committed tags as text. Disabled state takes precedence over read-only. Use the native disabled state of the input to guard custom actions when an ancestor fieldset disables it. Consumer errors set aria-invalid on the input and can point at a Field error message.

Consumer data ​

Identity is the normalized string. Trim leading and trailing whitespace for both supplied values and user entries, preserve internal whitespace and compare case-sensitively. Skip empty and repeated values in the rendered model and form mirrors, retaining first-occurrence order. Initial render and parent updates never emit normalization events. The next user edit proposes a canonical ordered array. Consumers replace the array to update it. The component never sorts, splices or mutates an array supplied by the parent.

Key tags by string. Parent insertion or reorder keeps focus on the same named remove button when it still exists. If a focused tag disappears, use the same fallback as user removal. Parent changes outside the widget leave external focus alone and never announce a user action.

Accessibility contract ​

Semantics and relationships ​

Use a labelled native text input, a list of committed tags, and native type="button" remove controls. Each button has a locale-aware name such as “Remove frontend.” Keep that name when a slot changes the visible tag content. The control has no listbox semantics. Use one persistent polite status region for accepted additions, accepted removals and duplicate feedback. Report the tag name for a single change and the count for a batch. Provide localized messages without exposing the draft through the live region.

Apply id, form, text-input attributes and aria-* supplied by the caller to the actual input. GhostFieldControl's bindings link the native label, hint and active error to that input. Preserve caller description IDs and merge them with Field IDs through the existing Field contract. Keep the native input label action working even when a tag button is currently the Tab stop.

Keyboard interaction and focus ​

The editable composite uses roving tabindex with one Tab stop. The input is the default entry point from either direction. While a remove button has focus, it becomes the sole Tab stop. Tab and Shift+Tab use native exit and the next entry returns to the text input. There is no focus trap.

FocusKeyResult
InputArrow toward the tagsOn an exactly empty draft with no selection, focus the last tag's remove button if present.
InputBackspaceOn an exactly empty draft with no selection, focus the last remove button. This press makes no deletion.
InputDelete, Home, End, other arrowsNative text editing.
Remove buttonLeft / RightMove one item along the rendered tag order. Toward the entry from the last tag returns to the input. No wrap from the first tag.
Remove buttonHome / EndFocus the first remove button or the text input, respectively.
Remove buttonBackspace / DeleteRequest removal of this tag.
Remove buttonEnter / SpaceUse the native button activation path once.

The list precedes the input in reading order. The arrow toward the tags is Left in LTR and Right in RTL. Resolve direction from the widget's inherited direction. Arrows follow logical sequence even when the themed layout wraps. With nonempty text or a selection, leave input arrows and deletion to native editing. Leave Escape, Up/Down and platform shortcuts available to the browser or containing widget. Pointer activation requests the same remove action.

If a focused button is removed, focus the tag now at the old index, else the previous tag, else the input. The focus fallback runs only if focus was still in the widget on removal. Activating a remove control that did not acquire focus leaves the existing focus alone. When read-only removes a focused button, move to the input. Disabled widgets have no Tab stop and do not force focus elsewhere. Provide a visible focus indicator on the input and buttons.

Assistive technology expectations ​

The input reads its actual label, current text, hint and active error. The committed tags remain available in reading order, independently of the Tab sequence. Check that the name of the newly focused button and the status message communicate deletion without duplicate activation. Read-only fields expose the native state and a readable tag list with no removal buttons.

Rendering and customization ​

Expose styling hooks for root, list, tag, remove button, input and status. Class and style apply to the root. Document the named parts and state attributes without promising wrapper nesting. The themed recipe uses scoped tokens for the entry, tag surfaces and focus indicators. Use wrapping and logical spacing so long tags and the entry fit at phone width.

Environment behavior ​

SSR and hydration ​

Render the same normalized tag order, input associations and hidden form values on the server and during hydration. Start with an empty draft and an empty live region. Generate per-instance internal IDs with useGhostId where needed and honor a caller-provided field ID. Native validity, form listeners and focus recovery run after mount. Initial hydration does not emit or move focus. Verify sibling controls with the same tag text and different labels.

Mobile and touch ​

Each native remove button has an adequate touch target and visible focus. Test entry with the mobile keyboard and touch removal with a wrapped list. Keep the keyboard hint, the editable input and each button reachable at narrow widths. The same submit and reset rules apply with a hardware or virtual keyboard.

Performance ​

The intended scale is a typical form field with tens of tags. Normalize in a single ordered pass and use string keys for DOM reuse. Keep focus lookup local to the widget. There is no layout measurement for arrow movement or virtualization contract.

Composition ​

Follow the GhostInput native text semantics and the GhostField control binding contract. The TagsInput owns entry, form mirrors and reset so draft and tags reset together. Reuse useNativeFormReset when wiring the current owner and let it wait until the full reset dispatch has finished. Follow the existing roving focus behavior for buttons while keeping the entry's selection and IME-specific decisions local.

Multi-value Select and TagsInput can both use stable string keys and repeated form names. Select chooses existing options and retains its own focus, selection and popup semantics. Extract shared internal form or collection logic only when both concrete implementations need the same contract.

Test plan ​

  • Vue behavior: Empty and duplicate handling, whitespace and case, literal and configured separators, caret and selection, atomic paste, IME Enter/separator/paste, frozen prop arrays, controlled acceptance and rejection, same-turn mutation attempts, draft edits while reconciling, and parent insertion, removal and reorder of the focused tag.
  • Native forms: Assert ordered FormData.getAll for enabled, disabled, read-only and empty values. Check an ancestor disabled fieldset and its first legend, external and changing form ownership, required with a nonempty draft and no tags, native submit from an empty draft, and canceled and uncanceled resets. Verify the controlled reset request and default snapshot.
  • Browser and accessibility: Press every documented key and assert actual focus, input value or selection, accessible names, relationships and state. Cover one Tab stop in both directions, RTL, wrapped tags, touch removal and focus after a tag disappears. Change the message locale while mounted and verify the remove button name, next announcement, and native validation message. Run axe for empty, populated and invalid fields. Review NVDA with Firefox and VoiceOver with Safari for the Field label, tag traversal, focus recovery and announcements.
  • SSR and types: Hydrate multiple labelled instances with stable IDs, tag order and form entries. Assert no hydration warning or initial update. Compile a consumer using readonly strings, v-model, slot and exposed input types. Reject object models and unrecognized delimiter types.

Documentation plan ​

Lead with the themed project-labels form and show adding, removing, submitting and resetting with a visible label and hint. Show what FormData.getAll returns. Add a headless Field example and examples for paste and read-only use. Publish input attribute routing, keyboard instructions, duplicate rules and the controlled reset contract. Register executable examples and manifest metadata when implementation lands.

Compatibility and release impact ​

The proposal adds an independent headless component and themed wrapper. GhostInput, GhostField and GhostSelect retain their existing behavior. Implementation requires approval, behavior and browser evidence, manifests, docs and a consumer-facing Changeset in #422.

Open architectural questions ​

The maintainer approved Enter-only commit by default, opt-in comma and semicolon splitting, separate native semantics for draft text and committed form values, required and reset behavior, the single-Tab-stop removal path, and reactive localization. Design sign-off