// ~/src/siteplane/components/tags-input/tags-input.tsx "use client"; import * as React from "react"; import { type SiteplaneControlSize, useResolvedControlSize, } from "../../system/provider/siteplane-ui-provider"; import { useSiteplaneMessages } from "../../system/locale/messages-context"; import type { FormControlVariant } from "../../system/styles/surface"; import { cn } from "../../system/utils/cn"; import { slotClass } from "../../system/utils/slot-class"; import { useFieldControlBridge } from "../field/field-control-bridge"; import { Input, unnamedInputRender } from "../input/input"; import { KitInput } from "../input/input-internal"; import { FieldStatus } from "../input-group/field-status"; import { Tag, TagGroup } from "../tag-group"; import { acceptedTag, addTags, splitAtDelimiter, tagEntries, type TagRules, } from "./tags-input-entries"; import "./tags-input.css"; /* * The tags of a field are the Tag sizes of its chips (the chip rule, * design-rework.css): sm in an sm field, md in an md or lg field and xl in an * xl field. */ const tagSizes = { lg: "md", md: "md", sm: "sm", xl: "xl", } as const satisfies Record; export type TagsInputProps = Omit< React.ComponentProps<"div">, | "aria-describedby" | "aria-invalid" | "aria-label" | "aria-labelledby" | "children" | "defaultValue" | "id" | "onChange" > & TagRules & { /** The tags, controlled. */ value?: readonly string[] | undefined; /** The tags the field starts with, uncontrolled. */ defaultValue?: readonly string[] | undefined; /** Called with the new tags when a tag is added or removed. */ onValueChange?: ((tags: string[]) => void) | undefined; /** What the field shows while it holds no tag. */ placeholder?: string | undefined; /** The control size, as Input takes it; unset, the provider's. */ size?: SiteplaneControlSize | undefined; /** * The surface, as on Input and ComboboxChips: `default` rests inset on * the field's light shade, `soft` lays a subtle fill under the same edge * and takes the page background while the field has focus. Default: * `default`. */ variant?: FormControlVariant | undefined; disabled?: boolean | undefined; /** * The name of the tags in the form data, one entry per tag; a Field's * name comes first. The text being typed is not sent. */ name?: string | undefined; /** The id of the form that the tags belong to. */ form?: string | undefined; /** * Marks the field as required for assistive technology and for a Field's * `requiredIndicator`. The field does not stop a form that is sent * without a tag. */ required?: boolean | undefined; /** * Typing this text, or pasting text with it, adds the text before it as a * tag, as Enter does. `null` turns it off. Default: a comma. */ delimiter?: string | null | undefined; /** * A help text behind a help icon at the end of the field, shown in a * Tooltip on hover and keyboard focus, as Input's `tooltip`. */ tooltip?: React.ReactNode; /** * While the field is invalid (`aria-invalid`, which an invalid Field * sets), an alert icon stands at its end in the help icon's place. * `false` turns it off. Default: `true`. */ showInvalidIcon?: boolean | undefined; /** * The name of a tag's remove action. Default: the `chip.remove` message * with the tag, "Remove" and the tag in English. */ removeLabel?: ((tag: string) => string) | undefined; /** The id of the text input, which a label's `htmlFor` names. */ id?: string | undefined; "aria-describedby"?: string | undefined; "aria-invalid"?: React.AriaAttributes["aria-invalid"]; /** The name of the text input, and of the tags without a Field label. */ "aria-label"?: string | undefined; "aria-labelledby"?: string | undefined; }; /** * A field that takes free text as tags: the tags stand in the field before * the text, Enter adds what was typed (and so does the delimiter, a comma by * default), and each tag's remove action takes it out. A new tag is trimmed, * and an empty one, a duplicate (unless `allowDuplicates`), one past * `maxTags` or one that `validate` rejects is not added. * * Backspace in the empty text, and ArrowLeft at its start, move to the last * tag; the arrows move between the tags, Backspace or Delete removes the * focused tag, and ArrowRight on the last tag returns to the text. Once the * last tag is removed, the text takes focus. * * The field is the chips field of the kit (design-rework.css) on the field * scale of its size; the tags are a TagGroup of Tags, and the text is the * kit's Input, which takes a Field's label, description, error and state. */ export function TagsInput({ allowDuplicates, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, className, defaultValue, delimiter = ",", disabled, form, id, maxTags, name, onMouseDown, onValueChange, placeholder, removeLabel: removeLabelProp, required, showInvalidIcon = true, size, tooltip, validate, value, variant = "default", ...props }: TagsInputProps): React.ReactElement { const messages = useSiteplaneMessages("tagsInput"); const resolvedSize = useResolvedControlSize(size); // The Field's name, label and disabled state reach the tags as they reach // the text. const field = useFieldControlBridge({ "aria-labelledby": ariaLabelledBy, disabled, name, }); const [ownTags, setOwnTags] = React.useState( () => defaultValue ?? [], ); const tags = value ?? ownTags; const entries = React.useMemo(() => tagEntries(tags), [tags]); const [draft, setDraft] = React.useState(""); const inputRef = React.useRef(null); const tagsRef = React.useRef(null); const focusTimer = React.useRef>(undefined); React.useEffect(() => () => clearTimeout(focusTimer.current), []); const rules: TagRules = { allowDuplicates, maxTags, validate }; function commit(next: string[]) { if (value === undefined) setOwnTags(next); onValueChange?.(next); } /** The tags that are in the collection, without one that fades out. */ function tagRows(): HTMLElement[] { return [ ...(tagsRef.current?.querySelectorAll('[role="row"]') ?? []), ]; } function remove(key: string) { const remaining = entries.filter((entry) => entry.key !== key); if (remaining.length === entries.length) return; commit(remaining.map((entry) => entry.label)); // Without a tag to move to, focus returns to the text, after the tag // group has moved its own. if (remaining.length === 0) { clearTimeout(focusTimer.current); focusTimer.current = setTimeout(() => inputRef.current?.focus(), 0); } } return (
{ onMouseDown?.(event); if (event.defaultPrevented || field.disabled) return; if ((event.target as Element).closest('input, button, [role="row"]')) return; event.preventDefault(); inputRef.current?.focus(); }} role="group" >
{ if (event.key !== "ArrowRight") return; const last = tagRows().at(-1); if (!last?.contains(event.target as Node)) return; event.preventDefault(); event.stopPropagation(); inputRef.current?.focus(); }} > {/* The tags flow in the field's row with the text after them (the group adds no box of its own). */} {entries.map((entry) => ( remove(entry.key)} // Without a removeLabel the Tag names its remove action, the // chip.remove message with the tag. removeLabel={removeLabelProp?.(entry.label)} > {entry.label} ))} { const text = event.currentTarget.value; const { parts, rest } = splitAtDelimiter(text, delimiter); if (parts.length === 0) { setDraft(text); return; } const { added, tags: next } = addTags(tags, parts, rules); if (added.length > 0) commit(next); // A text the field does not take stays in it, without the // delimiter, as it does on Enter. setDraft( added.length === 0 && parts.length === 1 ? parts[0] + rest : rest, ); }} onKeyDown={(event) => { if (event.nativeEvent.isComposing) return; const input = event.currentTarget; const atStart = input.selectionStart === 0 && input.selectionEnd === 0; if (event.key === "Enter") { // Enter adds the text and never sends the form. event.preventDefault(); const tag = acceptedTag(tags, draft, rules); if (tag === null) return; commit([...tags, tag]); setDraft(""); return; } const toTags = (event.key === "Backspace" && draft === "") || event.key === "ArrowLeft"; if (!toTags || !atStart) return; const last = tagRows().at(-1); if (!last) return; event.preventDefault(); last.focus(); }} placeholder={entries.length === 0 ? placeholder : undefined} profile="input-group" ref={inputRef} // Base UI writes the Field's name on its input. The text is not // the value, the tags are, so it renders without a name. render={unnamedInputRender} showInvalidIcon={false} size={resolvedSize} unstyled value={draft} />
{field.name ? entries.map((entry) => ( )) : null}
); } // ~/src/siteplane/components/tags-input/tags-input-entries.ts /* * The values of a Tags Input, apart from its markup, so they can be tested on * their own: the keys of its tags, the check a new tag must pass and the * split of typed or pasted text at the delimiter. */ /** A tag as the field renders it: its text and a key that stays its own. */ export type TagsInputEntry = { key: string; label: string }; /** * The tags with their keys. A key is made of the text and how often the same * text came before it, so the second "react" is always "1:react": the keys * stay stable from render to render, also with duplicates allowed, and a tag * that is removed takes its own key with it. */ export function tagEntries(tags: readonly string[]): TagsInputEntry[] { const seen = new Map(); return tags.map((label) => { const count = seen.get(label) ?? 0; seen.set(label, count + 1); return { key: `${count}:${label}`, label }; }); } export type TagRules = { /** Whether a text that is a tag already may be added again. */ allowDuplicates?: boolean | undefined; /** The most tags the field holds. */ maxTags?: number | undefined; /** Accepts or rejects a new tag; it gets the trimmed text. */ validate?: ((tag: string) => boolean) | undefined; }; /** * The tag that `text` adds to `tags`, trimmed, or null when it adds none: * when it is empty, when it is a tag already and duplicates are not allowed, * when the field holds its most tags, or when `validate` rejects it. */ export function acceptedTag( tags: readonly string[], text: string, { allowDuplicates = false, maxTags, validate }: TagRules, ): string | null { const tag = text.trim(); if (!tag) return null; if (!allowDuplicates && tags.includes(tag)) return null; if (maxTags !== undefined && tags.length >= maxTags) return null; if (validate && !validate(tag)) return null; return tag; } /** * Typed or pasted text split at the delimiter: every part before the last * delimiter is a tag to add, the rest stays in the field. Without a delimiter * in the text, or without a delimiter at all, nothing is split. */ export function splitAtDelimiter( text: string, delimiter: string | null | undefined, ): { parts: string[]; rest: string } { if (!delimiter || !text.includes(delimiter)) return { parts: [], rest: text }; const parts = text.split(delimiter); const rest = parts.pop() ?? ""; return { parts, rest: rest.trimStart() }; } /** * The tags after adding each of `parts` that passes the rules, in order, and * the tags that were added. */ export function addTags( tags: readonly string[], parts: readonly string[], rules: TagRules, ): { added: string[]; tags: string[] } { const next = [...tags]; const added: string[] = []; for (const part of parts) { const tag = acceptedTag(next, part, rules); if (tag === null) continue; next.push(tag); added.push(tag); } return { added, tags: next }; } // ~/src/siteplane/components/tags-input/tags-input.css @layer theme, base, components, siteplane, utilities; @layer siteplane { /* The field is the kit's chips field (design-rework.css, beside the * Combobox chips): its surface, focus, invalid and disabled states, its * height on the field scale, the padding that centres a row of tags and the * chip gap, 6 px between the tags. These defaults lay it out: one row of * tags and text, which wraps, then the status of the field at its end, * centred on the rows, 4 px after them, so the text ends 8 px before its * glyph (I3). A press on it puts the caret in the text. */ :where(.sp-tags-input) { position: relative; display: flex; width: 100%; min-width: 0; align-items: center; gap: var(--sp-rw-space-1); cursor: text; } /* The tags and the text stand the field's chip gap apart, and the text is * as high as a tag of the field (the input-group profile of Input reads the * composite context). It starts 8 px after the last tag, as the text of * Combobox chips does, and at the field's inline padding, 12 px from the * edge, in an empty field, where the empty tag list keeps no gap. */ :where(.sp-tags-input-area) { --sp-composite-control-height: var(--sp-pill-height, var(--sp-rw-space-6)); --sp-composite-control-padding-inline-start: var(--sp-rw-space-0-5); --sp-composite-control-padding-inline-end: 0px; position: relative; display: flex; min-width: 0; flex: 1 1 0%; flex-wrap: wrap; align-items: center; gap: var(--sp-chip-gap); } .sp-tags-input-area:not(:has(.sp-tag)) { --sp-composite-control-padding-inline-start: var(--sp-rw-space-1); column-gap: 0; } /* The text keeps 48 px, the least width of the text of Combobox chips, and * moves to a row of its own where less is left beside the tags. */ .sp-tags-input-area > .sp-base-input[data-profile="input-group"] .sp-input { flex: 1 1 var(--sp-rw-space-12); } :where(.sp-tags-input .sp-tag) { cursor: default; } /* A field that fades as disabled fades its tags with it: a disabled tag in * it keeps its full opacity instead of fading a second time, as the * disabled parts of every field do (design-rework.css). */ .sp-tags-input:has(.sp-input:disabled) .sp-tag { --sp-rw-disabled-opacity-action: 1; } /* The status of the field (FieldStatus, input-group.css): the help icon of * `tooltip`, and the alert icon in its place while the text is invalid. * Its 24 px box keeps 4 px around the 16 px glyph, so the glyph ends at the * field's inline padding and the text ends 8 px before it, with the gap. */ .sp-tags-input > .sp-field-status { margin-inline-end: calc((var(--sp-rw-space-6) - var(--sp-rw-space-4)) / -2); } .sp-tags-input:has([aria-invalid="true"]) > .sp-field-status[data-alert] { display: flex; } .sp-tags-input:has([aria-invalid="true"]) > .sp-field-status[data-alert] > .sp-input-invalid-icon { display: block; } .sp-tags-input:has([aria-invalid="true"]) > .sp-field-status[data-alert] > .sp-input-group-tooltip { display: none; } } // ~/src/siteplane/components/tags-input/index.ts export * from "./tags-input";