Components
Token Field
A text field where tokens sit between the words, such as variables in a template or mentions in a note.
Introduction
Token Field is a text field in which some of the words are tokens: a variable in an email template (“Hi {{first_name}}”), a mention in a note (“Thanks @Ana”), a link to a page. The user writes normally, and adds a token by typing a trigger character, or with a button. Each token is one unit in the text.
- Type
@(or any character you choose) and the suggestions open under it. They narrow as you type, and the arrow keys, Enter, Tab or a click pick one. - A token is deleted whole with Backspace or Delete, and the cursor moves over it in one step. Pasted text stays plain, and any
{{id}}in it becomes a token. - The value is a plain string with tokens written as
{{id}}, easy to store and to submit, andresolveTokensturns it into the final text. - Single line or multiline, and tokens can also be inserted from buttons outside the field.
For a list of separate values, such as keywords, use Tag Field. For plain text, use Text Field or Textarea.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Token Field uses Avatar for the avatars in its suggestions.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxManual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles
src/types/token-field-styles.tsShow code
import { tv } from "tailwind-variants";
// The editor is one box of text where tokens sit between the words. It carries
// the border, the background and the focus ring. The state of the field around
// it (invalid, disabled) comes through the `group/token-field` name, from data
// attributes on the root.
export const tokenFieldStyles = tv({
slots: {
editor: [
"block w-full rounded-md py-(--py) text-fg outline-none transition-colors",
"leading-5 break-words whitespace-pre-wrap",
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
// The placeholder: shown while the editor is empty, from its data attribute.
"data-empty:before:pointer-events-none data-empty:before:text-muted-fg data-empty:before:content-[attr(data-placeholder)]",
"group-data-invalid/token-field:border-danger",
"group-data-disabled/token-field:cursor-not-allowed group-data-disabled/token-field:opacity-50",
"group-data-readonly/token-field:cursor-default",
],
// A token inside the text. It is built in the DOM by the component, not
// rendered by React, so its classes are a plain string.
token:
"mx-px inline-block rounded-[5px] bg-secondary px-1.5 font-medium leading-5 text-secondary-fg select-none",
list: "popover z-50 w-64 overflow-hidden rounded-xl border bg-card text-card-fg shadow-lg",
option:
"flex cursor-default items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm outline-none aria-selected:bg-muted",
},
variants: {
variant: {
outline: { editor: "border bg-transparent" },
secondary: { editor: "bg-secondary text-secondary-fg" },
ghost: {
editor: "bg-transparent hover:bg-muted focus-visible:bg-muted",
},
},
// `--py` is the vertical padding. With it the height of a single line comes
// out at 32, 36 and 44px, like the other fields, and `--rows` sets the
// minimum height of a multiline editor.
size: {
sm: { editor: "px-2.5 text-sm [--py:5px]" },
md: { editor: "px-3 text-sm [--py:7px]" },
lg: { editor: "px-3.5 text-base [--py:9px]" },
},
isMultiline: {
true: {
editor: "min-h-[calc(var(--rows)*1lh+var(--py)*2+2px)]",
},
false: { editor: "" },
},
},
defaultVariants: { variant: "outline", size: "md", isMultiline: false },
});2. Add the Avatar file
It shows the picture of an item that has an avatar. Skip it and remove the import if you do not need avatars.
src/components/ui/avatar/avatar.tsxShow code
"use client";
import Image from "next/image";
import { Children, type ReactNode, useState } from "react";
import { UserIcon } from "@/components/icons";
import { cn } from "@/lib/cn";
import {
AvatarGroupProvider,
useAvatarGroup,
} from "@/types/avatar-group-context";
import { avatarGroupStyles, avatarStyles } from "@/types/avatar-styles";
type Size = "xs" | "sm" | "md" | "lg" | "xl";
// The size in pixels, so the image is requested at the size it is drawn.
const pixels: Record<Size, number> = { xs: 20, sm: 24, md: 32, lg: 40, xl: 56 };
export interface AvatarProps {
/** Image URL. Falls back to the initials of `name` if missing or if it fails to load. */
src?: string;
/** Used for the initials. Also the accessible name when the avatar has a `status`. */
name?: string;
/** Describes the image. Leave it out when the name is written next to the avatar. */
alt?: string;
/** Shown when there is no image and no `name`. Defaults to a person icon. */
fallback?: ReactNode;
size?: Size;
shape?: "circle" | "square";
/** A small dot on the corner. */
status?: "online" | "away" | "busy" | "offline";
className?: string;
}
function initialsOf(name?: string) {
if (!name) return "";
return name
.trim()
.split(/\s+/)
.slice(0, 2)
.map((word) => word[0]?.toUpperCase() ?? "")
.join("");
}
/**
* A small picture of a person or thing. When there is no picture, or it fails
* to load, it shows the initials of `name`, then `fallback`, then a person
* icon. It is decorative unless you pass `alt` (or a `status`), because the
* name is normally written next to it.
*
* Inside an `AvatarGroup` it takes its size and shape from the group.
*
* @example
* <Avatar src="/ana.png" name="Ana Wijaya" status="online" />
*/
export function Avatar({
src,
name,
alt,
fallback,
size,
shape,
status,
className,
}: AvatarProps) {
const group = useAvatarGroup();
// Remember which URL failed, so a new `src` gets its own chance.
const [failedSrc, setFailedSrc] = useState<string | null>(null);
const showImage = Boolean(src) && failedSrc !== src;
const resolvedSize = size ?? group?.size ?? "sm";
const styles = avatarStyles({
size: resolvedSize,
shape: shape ?? group?.shape,
status,
grouped: group ? true : undefined,
});
const initials = initialsOf(name);
const content =
showImage && src ? (
<Image
src={src}
alt=""
width={pixels[resolvedSize]}
height={pixels[resolvedSize]}
unoptimized
onError={() => setFailedSrc(src)}
className={styles.image()}
/>
) : (
initials ||
fallback || <UserIcon className="size-1/2" aria-hidden="true" />
);
// A status is information, so it is spoken along with the name.
const label = alt ?? (status ? name : undefined);
const spoken = label ? (status ? `${label}, ${status}` : label) : undefined;
const classes = cn(styles.root(), className);
const inner = (
<>
<span className={styles.frame()}>{content}</span>
{status ? <span aria-hidden="true" className={styles.status()} /> : null}
</>
);
if (spoken) {
return (
<span role="img" aria-label={spoken} className={classes}>
{inner}
</span>
);
}
return (
<span aria-hidden="true" className={classes}>
{inner}
</span>
);
}
export interface AvatarGroupProps {
/** The avatars. */
children: ReactNode;
/** Show at most this many avatars, then a "+N" for the rest. */
max?: number;
/** Passed down to every avatar in the group. */
size?: Size;
/** Passed down to every avatar in the group. */
shape?: "circle" | "square";
/** Names the group for screen readers, for example "Project members". */
"aria-label"?: string;
className?: string;
}
/**
* Avatars in an overlapping row, for members of a team or people in a thread.
* The group sets the size and shape of the avatars inside it, and with `max`
* it shows the first few and a "+N" for the rest.
*
* @example
* <AvatarGroup max={3} aria-label="Project members">
* <Avatar name="Ana Wijaya" />
* <Avatar name="Budi Santoso" />
* </AvatarGroup>
*/
export function AvatarGroup({
children,
max,
size = "sm",
shape = "circle",
className,
...props
}: AvatarGroupProps) {
const all = Children.toArray(children);
const shown = max !== undefined && all.length > max ? all.slice(0, max) : all;
const hidden = all.length - shown.length;
return (
<AvatarGroupProvider value={{ size, shape }}>
{/* biome-ignore lint/a11y/useSemanticElements: a div with role="group" is the standard pattern for a labelled set of avatars; <fieldset> brings form styling quirks. */}
<div
role="group"
aria-label={props["aria-label"]}
className={cn(avatarGroupStyles({ size }), className)}
>
{shown}
{hidden > 0 ? (
<Avatar
fallback={`+${hidden}`}
alt={`${hidden} more`}
className="[&>span]:bg-muted [&>span]:text-fg"
/>
) : null}
</div>
</AvatarGroupProvider>
);
}3. Add the Token Field file
src/components/ui/token-field/token-field.tsxShow code
"use client";
import {
type ReactNode,
type Ref,
useCallback,
useEffect,
useId,
useImperativeHandle,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { Popover, useFilter } from "react-aria-components";
import { Avatar, type AvatarProps } from "@/components/ui/avatar/avatar";
import { cn } from "@/lib/cn";
import { tokenFieldStyles } from "@/types/token-field-styles";
/** One token the user can put in the text. */
export interface TokenFieldItem {
/** What the token is written as in the value: `{{id}}`. Letters, digits, `_`, `-` and `.`. */
id: string;
/** The text shown in the token, and what typing matches. */
label: string;
/** A smaller line under the label in the suggestions. */
description?: ReactNode;
/** An icon before the label in the suggestions. */
icon?: ReactNode;
/** An avatar before the label in the suggestions. */
avatar?: AvatarProps;
}
/** What you can do to a Token Field from the outside, through its `ref`. */
export interface TokenFieldHandle {
/** Put a token at the cursor, or where it was last, or at the end. */
insertToken: (id: string) => void;
focus: () => void;
}
export interface TokenFieldProps {
label?: ReactNode;
/** Help text under the field. */
description?: ReactNode;
/** Shown under the field while it is invalid. */
errorMessage?: ReactNode;
/** Shown while the field is empty. */
placeholder?: string;
/** The tokens that can be inserted. */
items: TokenFieldItem[];
/**
* The text, for a controlled field. A token is written as `{{id}}`, so
* "Hello {{first_name}}" is the word Hello followed by the token first_name.
*/
value?: string;
/** The text to start with, for an uncontrolled field. */
defaultValue?: string;
onChange?: (value: string) => void;
/** Typing this opens the suggestions. Defaults to `@`. */
trigger?: string;
/** Written before the label inside each token, for example `@` for mentions. */
tokenPrefix?: string;
/** Allow line breaks (Enter). Otherwise the text is a single line. */
isMultiline?: boolean;
/** How many lines tall a multiline field is at least. */
rows?: number;
variant?: "outline" | "secondary" | "ghost";
size?: "sm" | "md" | "lg";
/** The text is submitted with a form under this name, tokens as `{{id}}`. */
name?: string;
autoFocus?: boolean;
isDisabled?: boolean;
isReadOnly?: boolean;
isInvalid?: boolean;
isRequired?: boolean;
"aria-label"?: string;
className?: string;
ref?: Ref<TokenFieldHandle>;
}
const ZWSP = "";
const tokenPattern = /\{\{([\w.-]+)\}\}/g;
const escapeRegExp = (text: string) =>
text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
/**
* Replaces every `{{id}}` in a Token Field's value with the value you have for
* it. A token you have nothing for is left as it is.
*
* @example
* resolveTokens("Hi {{first_name}}", { first_name: "Ana" }); // "Hi Ana"
*/
export function resolveTokens(
value: string,
values: Record<string, string | number>,
) {
return value.replace(tokenPattern, (match, id: string) =>
id in values ? String(values[id]) : match,
);
}
// ---- The text in the editor, read from and written to the DOM. ----
function isToken(node: Node | null | undefined): node is HTMLElement {
return node instanceof HTMLElement && node.dataset.token !== undefined;
}
function makeToken(id: string, label: string, className: string) {
const token = document.createElement("span");
token.dataset.token = id;
token.contentEditable = "false";
token.className = className;
token.textContent = label;
return token;
}
// A caret can only be put between two things if there is a text node there, so
// a token that is not followed by text gets an invisible one.
function padTokens(root: HTMLElement) {
for (const child of Array.from(root.childNodes)) {
if (isToken(child) && child.nextSibling?.nodeType !== Node.TEXT_NODE) {
child.after(document.createTextNode(ZWSP));
}
}
if (isToken(root.firstChild)) root.prepend(document.createTextNode(ZWSP));
}
// A line break at the very end of a text does not show a new line, unless
// something follows it. This break is that something.
function endMarker() {
const marker = document.createElement("br");
marker.dataset.end = "true";
return marker;
}
function ensureEndMarker(root: HTMLElement) {
const last = root.lastElementChild;
if (
!(last instanceof HTMLElement && last.dataset.end) ||
last !== root.lastChild
) {
root.querySelectorAll("br[data-end]").forEach((node) => {
node.remove();
});
root.append(endMarker());
}
}
function write(
root: HTMLElement,
value: string,
labels: Map<string, string>,
prefix: string,
tokenClass: string,
) {
root.replaceChildren();
let last = 0;
for (const match of value.matchAll(tokenPattern)) {
const label = labels.get(match[1]);
if (label === undefined) continue; // Not a token we know: it stays as text.
if (match.index > last) {
root.append(document.createTextNode(value.slice(last, match.index)));
}
root.append(makeToken(match[1], prefix + label, tokenClass));
last = match.index + match[0].length;
}
if (last < value.length)
root.append(document.createTextNode(value.slice(last)));
padTokens(root);
root.append(endMarker());
}
function read(root: HTMLElement) {
let text = "";
const visit = (node: Node) => {
if (node.nodeType === Node.TEXT_NODE) {
text += (node.textContent ?? "").replaceAll(ZWSP, "");
} else if (isToken(node)) {
text += `{{${node.dataset.token}}}`;
} else if (node instanceof HTMLElement) {
if (node.tagName === "BR") {
if (!node.dataset.end) text += "\n";
} else node.childNodes.forEach(visit);
}
};
root.childNodes.forEach(visit);
return text;
}
function putCaret(node: Node, offset: number) {
const selection = window.getSelection();
if (!selection) return;
const range = document.createRange();
range.setStart(node, offset);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
function currentRange(root: HTMLElement) {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return null;
const range = selection.getRangeAt(0);
return root.contains(range.startContainer) ? range : null;
}
// The token right before (or after) the cursor, if the cursor is next to one.
function tokenNextToCursor(range: Range, direction: "back" | "forward") {
if (!range.collapsed) return null;
const { startContainer: node, startOffset: offset } = range;
if (node.nodeType === Node.TEXT_NODE) {
const text = (node as Text).data;
const beside =
direction === "back"
? text.slice(0, offset).replaceAll(ZWSP, "")
: text.slice(offset).replaceAll(ZWSP, "");
if (beside !== "") return null;
const sibling =
direction === "back" ? node.previousSibling : node.nextSibling;
return isToken(sibling) ? sibling : null;
}
const child = node.childNodes[direction === "back" ? offset - 1 : offset];
return isToken(child) ? child : null;
}
/**
* A text field where tokens sit between the words: a variable such as
* `{{first_name}}` in an email template, or a mention such as @Ana in a note.
* Type the trigger character (`@` by default) to pick a token from the
* suggestions, or insert one from a button with the `ref`. A token is one unit:
* Backspace deletes all of it, and the cursor moves over it in one step.
*
* The value is a plain string with each token written as `{{id}}`, which is
* easy to store and to submit with a form. `resolveTokens` turns it into the
* final text.
*
* It is a contenteditable element with the role of a textbox, so a screen
* reader announces it as a text field, and it is named by its label.
*
* @example
* <TokenField
* label="Subject"
* items={[{ id: "first_name", label: "First name" }]}
* defaultValue="Hello {{first_name}}"
* />
*/
export function TokenField({
label,
description,
errorMessage,
placeholder,
items,
value,
defaultValue = "",
onChange,
trigger = "@",
tokenPrefix = "",
isMultiline = false,
rows = 3,
variant,
size = "md",
name,
autoFocus,
isDisabled,
isReadOnly,
isInvalid,
isRequired,
className,
ref,
...props
}: TokenFieldProps) {
const styles = tokenFieldStyles({ variant, size, isMultiline });
const { contains } = useFilter({ sensitivity: "base" });
const editorRef = useRef<HTMLDivElement>(null);
const wrapRef = useRef<HTMLDivElement>(null);
const anchorRef = useRef<HTMLSpanElement>(null);
// Where the cursor was last, for inserting from a button outside the editor.
const savedRange = useRef<Range | null>(null);
// The trigger and the text after it that a pick will replace.
const pending = useRef<{ node: Text; start: number; end: number } | null>(
null,
);
const renderedKey = useRef("");
const isControlled = value !== undefined;
const [inner, setInner] = useState(defaultValue);
const current = isControlled ? value : inner;
const [isEmpty, setEmpty] = useState(current === "");
const canEdit = !isDisabled && !isReadOnly;
const [suggest, setSuggest] = useState<{
query: string;
session: number;
left: number;
top: number;
} | null>(null);
const [active, setActive] = useState(0);
const session = useRef(0);
const uid = useId();
const editorId = `${uid}-editor`;
const labelId = `${uid}-label`;
const descriptionId = `${uid}-description`;
const errorId = `${uid}-error`;
const listId = `${uid}-list`;
const labels = useMemo(
() => new Map(items.map((item) => [item.id, item.label])),
[items],
);
const labelsKey = `${tokenPrefix}|${items.map((item) => `${item.id}:${item.label}`).join("|")}`;
const tokenClass = styles.token();
const matches = suggest
? items.filter(
(item) => suggest.query === "" || contains(item.label, suggest.query),
)
: [];
const isOpen = suggest !== null && matches.length > 0;
// Keep the editor in step with `value`. The DOM is the source of truth while
// the user types, so it is only rewritten when the value changed from outside
// or the labels changed.
useLayoutEffect(() => {
const editor = editorRef.current;
if (!editor) return;
if (renderedKey.current !== labelsKey || read(editor) !== current) {
renderedKey.current = labelsKey;
write(editor, current, labels, tokenPrefix, tokenClass);
}
setEmpty(current === "");
}, [current, labels, labelsKey, tokenPrefix, tokenClass]);
useEffect(() => {
if (autoFocus) editorRef.current?.focus();
}, [autoFocus]);
// Nothing in the editor should be formatted: no bold, no italics.
useEffect(() => {
const editor = editorRef.current;
if (!editor) return;
const block = (event: InputEvent) => {
if (event.inputType.startsWith("format")) event.preventDefault();
};
editor.addEventListener("beforeinput", block);
return () => editor.removeEventListener("beforeinput", block);
}, []);
const closeSuggest = useCallback(() => {
pending.current = null;
setSuggest(null);
}, []);
function commit() {
const editor = editorRef.current;
if (!editor) return;
ensureEndMarker(editor);
const next = read(editor);
setEmpty(next === "");
if (next !== current) {
if (!isControlled) setInner(next);
onChange?.(next);
}
}
function saveRange() {
const editor = editorRef.current;
const range = editor && currentRange(editor);
if (range) savedRange.current = range.cloneRange();
}
// Put a token where `range` is, then the cursor after it.
function placeToken(range: Range, id: string) {
const editor = editorRef.current;
if (!editor) return;
range.deleteContents();
const token = makeToken(
id,
tokenPrefix + (labels.get(id) ?? id),
tokenClass,
);
range.insertNode(token);
let after = token.nextSibling;
if (after?.nodeType !== Node.TEXT_NODE) {
after = document.createTextNode(ZWSP);
token.after(after);
}
if (isToken(token.previousSibling) || token.previousSibling === null) {
token.before(document.createTextNode(ZWSP));
}
putCaret(
after,
(after as Text).data.length > 0 && after.textContent === ZWSP ? 1 : 0,
);
savedRange.current = currentRange(editor)?.cloneRange() ?? null;
commit();
}
function insertToken(id: string) {
const editor = editorRef.current;
if (!editor || !canEdit || !labels.has(id)) return;
// Read where the cursor is before focusing: focusing an editor puts its
// cursor at the start, which is not where the user was.
let range = currentRange(editor) ?? savedRange.current;
editor.focus();
if (!range || !editor.contains(range.startContainer)) {
// Never had a cursor: the end of the text, before the end marker.
range = document.createRange();
const end = editor.querySelector("br[data-end]");
if (end) range.setStartBefore(end);
else range.selectNodeContents(editor);
range.collapse(true);
}
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
placeToken(range, id);
}
useImperativeHandle(ref, () => ({
insertToken,
focus: () => editorRef.current?.focus(),
}));
// Text is inserted as plain text, with any {{id}} in it turned into a token.
function insertText(text: string) {
const editor = editorRef.current;
const range = editor && currentRange(editor);
if (!editor || !range) return;
const clean = isMultiline ? text : text.replace(/\r?\n/g, " ");
range.deleteContents();
const fragment = document.createDocumentFragment();
let last = 0;
for (const match of clean.matchAll(tokenPattern)) {
const known = labels.get(match[1]);
if (known === undefined) continue;
if (match.index > last) {
fragment.append(
document.createTextNode(clean.slice(last, match.index)),
);
}
fragment.append(makeToken(match[1], tokenPrefix + known, tokenClass));
last = match.index + match[0].length;
}
if (last < clean.length)
fragment.append(document.createTextNode(clean.slice(last)));
if (!fragment.lastChild) return;
const end = fragment.lastChild;
range.insertNode(fragment);
padTokens(editor);
// The cursor goes after what was inserted.
if (isToken(end)) {
const after = end.nextSibling;
if (after) putCaret(after, after.textContent === ZWSP ? 1 : 0);
} else {
putCaret(end, (end as Text).data.length);
}
saveRange();
commit();
}
// Look at the text before the cursor for the trigger, and open the
// suggestions if it is there.
function updateSuggest() {
const editor = editorRef.current;
const wrap = wrapRef.current;
const range = editor && currentRange(editor);
if (!editor || !wrap || !range || !range.collapsed || !canEdit) {
return closeSuggest();
}
const node = range.startContainer;
if (node.nodeType !== Node.TEXT_NODE) return closeSuggest();
const before = (node as Text).data.slice(0, range.startOffset);
const found = new RegExp(
`(^|[\\s${ZWSP}])${escapeRegExp(trigger)}([^\\s${ZWSP}]*)$`,
).exec(before);
if (!found) return closeSuggest();
const query = found[2];
const start = range.startOffset - query.length - trigger.length;
const isNew =
!pending.current ||
pending.current.node !== node ||
pending.current.start !== start;
pending.current = { node: node as Text, start, end: range.startOffset };
if (isNew) {
// Anchor the list under the trigger, and keep it there while typing.
const at = document.createRange();
at.setStart(node, start);
at.setEnd(node, start + trigger.length);
const rect = at.getBoundingClientRect();
const box = wrap.getBoundingClientRect();
session.current += 1;
setActive(0);
setSuggest({
query,
session: session.current,
left: rect.left - box.left,
top: rect.bottom - box.top,
});
} else {
setSuggest((state) => (state ? { ...state, query } : state));
setActive(0);
}
}
function pick(item: TokenFieldItem) {
const editor = editorRef.current;
const at = pending.current;
if (!editor || !at || !editor.contains(at.node)) return closeSuggest();
const range = document.createRange();
range.setStart(at.node, at.start);
range.setEnd(at.node, at.end);
closeSuggest();
placeToken(range, item.id);
}
function onKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
if (!canEdit) return;
const editor = editorRef.current;
if (!editor) return;
if (isOpen) {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
const step = event.key === "ArrowDown" ? 1 : -1;
setActive((index) => (index + step + matches.length) % matches.length);
return;
}
if (event.key === "Enter" || event.key === "Tab") {
event.preventDefault();
pick(matches[active]);
return;
}
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
closeSuggest();
return;
}
}
if (event.key === "Enter") {
event.preventDefault();
if (!isMultiline) return;
insertText("\n");
return;
}
if (event.key === "Backspace" || event.key === "Delete") {
const range = currentRange(editor);
const token =
range &&
tokenNextToCursor(
range,
event.key === "Backspace" ? "back" : "forward",
);
if (token && range) {
// A token goes in one piece, and takes its padding with it.
event.preventDefault();
const { startContainer, startOffset } = range;
token.remove();
if (editor.contains(startContainer))
putCaret(startContainer, startOffset);
saveRange();
commit();
}
}
}
const showError = Boolean(isInvalid && errorMessage);
const describedBy =
[description ? descriptionId : null, showError ? errorId : null]
.filter(Boolean)
.join(" ") || undefined;
return (
<div
data-invalid={isInvalid || undefined}
data-disabled={isDisabled || undefined}
data-readonly={isReadOnly || undefined}
data-required={isRequired || undefined}
className={cn(
"group/token-field flex w-full flex-col gap-1.5",
className,
)}
>
{label ? (
// biome-ignore lint/a11y/useKeyWithClickEvents: a click on the label only moves the focus to the editor, which is already reachable by keyboard
<label
id={labelId}
htmlFor={editorId}
onClick={() => editorRef.current?.focus()}
className="w-fit text-sm font-medium group-data-required/token-field:after:ml-0.5 group-data-required/token-field:after:text-danger group-data-required/token-field:after:content-['*']"
>
{label}
</label>
) : null}
<div ref={wrapRef} className="relative">
{/* biome-ignore lint/a11y/useSemanticElements: an input or a textarea cannot hold tokens between the words, so this is a contenteditable element with the textbox role */}
<div
ref={editorRef}
id={editorId}
role="textbox"
tabIndex={isDisabled ? -1 : 0}
contentEditable={canEdit}
suppressContentEditableWarning
spellCheck={false}
aria-multiline={isMultiline}
aria-label={label ? undefined : props["aria-label"]}
aria-labelledby={label ? labelId : undefined}
aria-describedby={describedBy}
aria-invalid={isInvalid || undefined}
aria-required={isRequired || undefined}
aria-readonly={isReadOnly || undefined}
aria-disabled={isDisabled || undefined}
aria-autocomplete="list"
aria-controls={isOpen ? listId : undefined}
aria-activedescendant={isOpen ? `${listId}-${active}` : undefined}
data-empty={isEmpty || undefined}
data-placeholder={placeholder}
className={styles.editor()}
style={
isMultiline
? ({ "--rows": rows } as React.CSSProperties)
: undefined
}
onInput={() => {
commit();
saveRange();
updateSuggest();
}}
onKeyDown={onKeyDown}
onKeyUp={(event) => {
saveRange();
if (
["ArrowLeft", "ArrowRight", "Home", "End", "Backspace"].includes(
event.key,
)
) {
updateSuggest();
}
}}
onMouseUp={() => {
saveRange();
updateSuggest();
}}
onFocus={saveRange}
onBlur={() => {
saveRange();
closeSuggest();
}}
onPaste={(event) => {
if (!canEdit) return;
event.preventDefault();
insertText(event.clipboardData.getData("text/plain"));
}}
onDrop={(event) => event.preventDefault()}
/>
{/* Where the suggestions open: under the trigger character. */}
<span
ref={anchorRef}
aria-hidden="true"
className="pointer-events-none absolute size-0"
style={{ left: suggest?.left ?? 0, top: suggest?.top ?? 0 }}
/>
{isOpen ? (
<Popover
key={suggest.session}
triggerRef={anchorRef}
isOpen
isNonModal
placement="bottom start"
offset={6}
onOpenChange={(open) => {
if (!open) closeSuggest();
}}
className={styles.list()}
>
{/* The focus stays in the editor, so the list is driven from its
keyboard handler, and pressing an option must not move focus. */}
<div
id={listId}
role="listbox"
aria-label="Suggestions"
className="max-h-60 overflow-auto p-1"
onMouseDown={(event) => event.preventDefault()}
>
{matches.map((item, index) => (
// biome-ignore lint/a11y/useKeyWithClickEvents: the editor keeps the focus and handles the keys (arrows, Enter, Tab), see onKeyDown
<div
key={item.id}
id={`${listId}-${index}`}
role="option"
aria-selected={index === active}
tabIndex={-1}
className={styles.option()}
onMouseEnter={() => setActive(index)}
onClick={() => pick(item)}
>
{item.avatar ? (
<Avatar {...item.avatar} />
) : item.icon ? (
<span className="shrink-0 text-muted-fg [&_svg]:size-4">
{item.icon}
</span>
) : null}
<span className="flex min-w-0 flex-col">
<span className="truncate">{item.label}</span>
{item.description ? (
<span className="truncate text-xs text-muted-fg">
{item.description}
</span>
) : null}
</span>
</div>
))}
</div>
</Popover>
) : null}
</div>
{name ? <input type="hidden" name={name} value={current} /> : null}
{description ? (
<p id={descriptionId} className="text-sm text-muted-fg">
{description}
</p>
) : null}
{showError ? (
<p id={errorId} className="text-sm text-danger">
{errorMessage}
</p>
) : null}
</div>
);
}4. Add the popover styles
In src/app/globals.css copy the popover-in keyframes and the .popover[data-entering] rule. Without them the suggestions still work, they just appear without the small fade.
5. Use it
import {
resolveTokens,
TokenField,
} from "@/components/ui/token-field/token-field";Anatomy
One box of text, with tokens between the words and a list of suggestions under the trigger.
<TokenField
label="Subject"
description="Type @ to add a variable."
placeholder="Write a subject"
items={variables}
defaultValue="Order {{order_id}} is confirmed"
/>| Part | Rendered as | Notes |
|---|---|---|
| Label | label | Names the field. Clicking it focuses the text. |
| Text | div, contenteditable | Where the user types. It has the textbox role, so a screen reader announces a text field. |
| Token | span inside the text | One unit in the middle of the words. Backspace deletes all of it, and the cursor moves over it in one step. |
| Suggestions | list under the trigger | Opens when the trigger character is typed and narrows as you type. Arrow keys, Enter or Tab and a click pick one, and Escape closes it. |
| Description / error | text under the field | Help text, replaced by the error message when the field is invalid. |
Without a label, give the field an aria-label so a screen reader can name it.
Items
The tokens that can be inserted are a plain array of objects.
const variables = [
{ id: "first_name", label: "First name", description: "Ana" },
{ id: "order_id", label: "Order number", description: "#4821" },
];| Field | Type | Notes |
|---|---|---|
| id | string | What the token is written as in the value: {{id}}. Letters, digits, _, - and . |
| label | string | The text inside the token, and what typing after the trigger matches. |
| description | ReactNode | A smaller line under the label in the suggestions. |
| icon | ReactNode | An icon before the label in the suggestions. |
| avatar | AvatarProps | An avatar before the label in the suggestions. |
A token shows only its label, since it lives inside the text. The description, icon and avatar are for the suggestions.
Value
The text is a string, and a token in it is written with double braces.
// The value is a plain string. A token is written {{id}}.
"Hi {{first_name}}, your order {{order_id}} is confirmed."
// resolveTokens fills them in:
resolveTokens(value, { first_name: "Ana", order_id: "#4821" });
// "Hi Ana, your order #4821 is confirmed."Only ids that are in items become tokens. Anything else written in braces stays as plain text, so a stored value never breaks the field. resolveTokens leaves a token it has no value for as it is.
Examples
Click into a field and type @ to add a token.
Usage
Label
Every field needs a name. Use label, or aria-label when the label is written elsewhere.
Description
Help text under the field.
Type @ to add a variable, such as the customer's name.
Default text
Start with text that already has tokens in it, by writing them as {{id}}.
Mentions
Items with an avatar and a description make a mention list. tokenPrefix writes an @ before each name inside the text.
Trigger character
The character that opens the suggestions is @ by default. Use trigger for another one, for example # to link a page.
Multiline
With isMultiline, Enter starts a new line, and rows sets the least number of lines. Line breaks are \n in the value.
Uncontrolled
Let the field keep its own text. Start with defaultValue, and give it a name to read the text from a form.
Controlled
Keep the text in your own state with value and onChange, so you can read, replace or clear it from outside.
value: "Hi {{first_name}}, thanks for {{company}}!"
Resolving tokens
resolveTokens fills each token with a value you have for it. Here it shows the finished message for a sample customer, as you write.
What the customer gets
Hi Ana, your order #4821 of $49.90 is confirmed.
In a form
With a name, the text is submitted as it is, with the tokens written as {{id}}.
Read only
The text can be selected and copied, but not changed.
Sizes
Variants
Disabled
Validation
Set isInvalid with an errorMessage. The field gets a red border and the message shows under it.
It must mention the order number.
Component API
Token Field takes the props below.
| Prop | Type | Default |
|---|---|---|
| items | TokenFieldItem[] | - (required) |
| label | ReactNode | - |
| description | ReactNode | - |
| errorMessage | ReactNode | - |
| placeholder | string | - |
| value | string | - |
| defaultValue | string | "" |
| onChange | (value: string) => void | - |
| trigger | string | "@" |
| tokenPrefix | string | "" |
| isMultiline | boolean | false |
| rows | number | 3 |
| name | string | - |
| variant | "outline" | "secondary" | "ghost" | "outline" |
| size | "sm" | "md" | "lg" | "md" |
| autoFocus | boolean | false |
| isDisabled | boolean | false |
| isReadOnly | boolean | false |
| isInvalid | boolean | false |
| isRequired | boolean | false |
| aria-label | string | - (when there is no label) |
| ref | Ref<TokenFieldHandle> | - |
Ref
| Method | What it does |
|---|---|
| insertToken(id) | Puts the token at the cursor. If the field was never focused it goes at the end. Use it from buttons outside the field. |
| focus() | Moves the cursor into the field. |
resolveTokens
resolveTokens(value, values) returns the text with every {{id}} replaced by values[id]. Ids that are missing from values are left as they are.