Chip
FreeThe small labelled pill of an AI product: context in a composer, a filter, a fact behind a decision and the citation after a claim, in one shape and one light grey.
npx shadcn@latest add https://pixilui.com/r/chip.jsonPreview
A removed chip folds away while the row closes the gap.
Size
import { useState } from "react";
import { IconAdd } from "@/components/pixilui/icons/add";
import { IconClear } from "@/components/pixilui/icons/clear";
import { IconFile } from "@/components/pixilui/icons/file";
import { IconLink } from "@/components/pixilui/icons/link";
import { IconCode } from "@/components/pixilui/icons/code";
import { ChipCitation, Chip, ChipRow, ChipFact, type ChipCitationSource } from "@/components/pixilui/chip";
// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
size: ["md", "sm"],
} as const;
type Context = { id: string; name: string; kind: "file" | "repo" | "agent" | "person" };
const start: Context[] = [
{ id: "c1", name: "refund-policy.md", kind: "file" },
{ id: "c2", name: "acme-webapp", kind: "repo" },
{ id: "c3", name: "Refund agent", kind: "agent" },
{ id: "c4", name: "Maya Okafor", kind: "person" },
];
const more: Context[] = [
{ id: "c5", name: "orders-2026-11.csv", kind: "file" },
{ id: "c6", name: "Priya Raman", kind: "person" },
];
const sources: ChipCitationSource[] = [
{ id: "help", name: "help.acme.com", icon: <IconLink />, ink: "var(--pixilui-h-read)", domain: "help.acme.com", title: "What to do if your order arrives damaged", text: "Send us a photo of the damage and we'll refund the full amount. You don't need to send the item back." },
{ id: "faq", name: "Returns FAQ", icon: <IconFile />, domain: "acme.com/returns", title: "Returns and refunds FAQ", text: "Refunds go back to the card you paid with and usually arrive in 3 to 5 business days." },
];
/** A composer's context row (remove a chip, add one back), a fact chip and a cited claim. */
export default function ChipDemo({ size = "md" }: KnobValues<typeof knobs>) {
const [items, setItems] = useState(start);
const lead = (c: Context) =>
c.kind === "file" ? { icon: <IconFile /> } : c.kind === "repo" ? { icon: <IconCode /> } : c.kind === "agent" ? { dot: "var(--pixilui-st-done-h)" } : { avatar: "var(--pixilui-t-read)" };
const next = more.find((m) => !items.some((i) => i.id === m.id)) ?? start.find((m) => !items.some((i) => i.id === m.id));
return (
<div className="flex w-full max-w-lg flex-col gap-6">
<ChipRow aria-label="Context">
{items.map((c) => (
<Chip key={c.id} size={size} {...lead(c)} onRemove={() => setItems((all) => all.filter((x) => x.id !== c.id))} removeLabel={`Remove ${c.name}`} removeIcon={<IconClear />}>
{c.name}
</Chip>
))}
<Chip size={size} adder icon={<IconAdd />} onClick={() => next && setItems((all) => [...all, next])}>
Add context
</Chip>
</ChipRow>
<div className="flex flex-wrap items-center gap-2">
<ChipFact figure="$86.40">under the $500 limit</ChipFact>
<ChipFact figure="2 of 3">photos show the damage</ChipFact>
</div>
<p className="type-body text-secondary">
Refunded order 4471 in full without a return <ChipCitation sources={sources} />
</p>
</div>
);
}When to use
Use it when
- Context attached to a prompt: files, repos, agents and people, each removable.
- The evidence behind an agent's decision, as a fact chip with the figure set apart.
- The source right after a claim, as a citation chip that opens its source card on hover or focus.
Use something else when
- A row of filters that add up a total: use Chip group, which wires the pressed state and the rolling total.
- A fixed fact about a run, such as Pass or Needs review: use a tag or badge (Badge).
- Opening a menu: a menu opens from a button, never from a chip.
Installation
Terminal
npx shadcn@latest add https://pixilui.com/r/chip.jsonAdds chip.tsx, and installs clsx and tailwind-merge. The URL works in any app with a components.json, with no registry to add first.
components/pixilui/chip.tsx
"use client";
/*
Chips, locked 28 Nov 2026 (design/explorations/components/locked/chips). The look and motion are
foundation.css section 8 (.pixilui-chip, .pixilui-fact, .pixilui-cite); this file writes the locked
markup and plays the locked behavior (chips.js), reading every time and scale from the CSS:
Remove click, Enter, Backspace or Delete on the remove: the chip shrinks to nothing and fades while
the row closes the gap (180ms, the move curve), then onRemove runs and focus lands on the next
chip's remove, else the previous one, else the row's add chip.
Add a chip that mounts in a ChipRow after the row's first render grows from nothing, rising 2px
(200ms, the out curve). Chips there on first render never move.
Citation hover or focus opens its source card after 120ms (one card per page), leaving closes it
140ms later; the card grows from the chip's corner. Escape closes it and keeps focus on the
chip; click toggles it.
Reduced removed and added at once; the card has no animation.
*/
import {
cloneElement,
createContext,
forwardRef,
isValidElement,
useCallback,
useContext,
useEffect,
useId,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
type ComponentPropsWithoutRef,
type CSSProperties,
type KeyboardEvent,
type MouseEvent,
type ReactElement,
type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import { cn } from "./lib/utils";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";
import { safeAnimate } from "./lib/motion/animate";
const css = (el: Element, name: string) => getComputedStyle(el).getPropertyValue(name).trim();
const ms = (el: Element, name: string) => parseFloat(css(el, name)) || 0;
const canAnimate = (el: Element) => typeof (el as HTMLElement).animate === "function";
/** An icon with the locked part's classes, so it sizes and colors as the lock says. */
function withClass(node: ReactNode, className: string): ReactNode {
if (!isValidElement(node)) return node;
const el = node as ReactElement<{ className?: string; "aria-hidden"?: boolean | "true" | "false" }>;
return cloneElement(el, { className: cn(className, el.props.className), "aria-hidden": el.props["aria-hidden"] ?? true });
}
/* ------------------------------------------------------------------ the row */
type RowContext = { ready: { current: boolean } };
const Row = createContext<RowContext | null>(null);
export type ChipRowProps = ComponentPropsWithoutRef<"div">;
/**
* A row of chips. Chips added after its first render grow in; a removed chip's neighbours close the gap.
* Put an add chip (Chip with adder) last so focus has somewhere to go when the last chip leaves.
*/
export const ChipRow = forwardRef<HTMLDivElement, ChipRowProps>(function ChipRow({ className, children, ...props }, ref) {
const ready = useRef(false);
useEffect(() => {
ready.current = true;
}, []);
return (
<Row.Provider value={{ ready }}>
<div ref={ref} className={cn("flex flex-wrap items-center gap-2 font-body", className)} {...props}>
{children}
</div>
</Row.Provider>
);
});
/* ------------------------------------------------------------------ the chip */
export type ChipSize = "md" | "sm";
export type ChipProps = Omit<ComponentPropsWithoutRef<"span">, "children" | "onClick"> & {
/** The label. */
children?: ReactNode;
/** md 30 (the default), sm 26. */
size?: ChipSize;
/** A leading icon (an animated icon from packages/registry/icons). */
icon?: ReactNode;
/** A leading status dot in this color (any CSS color or token, such as var(--pixilui-st-done-h)). */
dot?: string;
/** A leading avatar circle in this color, for a person. */
avatar?: string;
/** A leading favicon tile: the product's mark on its own color. */
favicon?: { icon: ReactNode; color: string };
/** The grey rest of a two-tone label: "Opus 5.5" with note "fast". */
note?: ReactNode;
/** A count after the label, grey (deep accent when pressed). */
count?: number | string;
/** Pressed state: the chip becomes a toggle button (aria-pressed), the filter chip. */
pressed?: boolean;
/** Makes the chip a button. */
onClick?: (event: MouseEvent<HTMLElement>) => void;
/** The add chip of a ChipRow: focus lands on it when the last chip leaves. */
adder?: boolean;
/** Disabled: muted at 55%, no hover or press. */
disabled?: boolean;
/** Shows a remove button; runs once the chip has folded away. Remove it from your list here. */
onRemove?: () => void | Promise<void>;
/** The remove button's accessible name, such as "Remove acme-webapp". */
removeLabel?: string;
/** The remove button's icon (a cross). */
removeIcon?: ReactNode;
};
/** The leaving move (chips.js remove): shrinks to nothing and fades while the row closes the gap. */
function leave(chip: HTMLElement, done: () => void) {
if (chip.dataset.leaving) return;
chip.dataset.leaving = "1";
const row = chip.parentElement;
const gap = row ? parseFloat(getComputedStyle(row).columnGap) || 0 : 0;
const chips = row ? [...row.querySelectorAll<HTMLElement>(":scope > .pixilui-chip:not([data-chip-add])")] : [];
const finish = () => {
// focus moves to the next chip's remove, else the previous one, else the row's add chip
const left = row ? [...row.querySelectorAll<HTMLElement>(":scope > .pixilui-chip:not([data-leaving]):not([data-chip-add])")] : [];
const target = left[Math.min(chips.indexOf(chip), left.length - 1)];
const focus = target?.querySelector<HTMLElement>(".pixilui-chip-remove") ?? row?.querySelector<HTMLElement>("[data-chip-add]");
done();
focus?.focus({ preventScroll: true });
};
if (prefersReducedMotion() || !canAnimate(chip)) return finish();
const w = chip.getBoundingClientRect().width;
chip.style.overflow = "hidden";
const a = safeAnimate(chip,
[
{ width: `${w}px`, opacity: 1, marginRight: "0px", transform: "scale(1)" },
{ width: "0px", opacity: 0, marginRight: `${-gap}px`, transform: `scale(${css(chip, "--pixilui-chip-leave-scale")})`, paddingLeft: "0px", paddingRight: "0px" },
],
{ duration: ms(chip, "--pixilui-chip-leave-time"), easing: css(chip, "--pixilui-ease-move"), fill: "forwards" },
);
a.onfinish = finish;
}
/** The arriving move (chips.js add): grows from nothing, rising. */
function arrive(chip: HTMLElement) {
if (prefersReducedMotion() || !canAnimate(chip)) return;
const row = chip.parentElement;
const gap = row ? parseFloat(getComputedStyle(row).columnGap) || 0 : 0;
const w = chip.getBoundingClientRect().width;
chip.style.overflow = "hidden";
const a = safeAnimate(chip,
[
{ width: "0px", opacity: 0, marginRight: `${-gap}px`, transform: `translateY(${css(chip, "--pixilui-chip-enter-rise")}) scale(${css(chip, "--pixilui-chip-enter-scale")})` },
{ width: `${w}px`, opacity: 1, marginRight: "0px", transform: "none" },
],
{ duration: ms(chip, "--pixilui-chip-enter-time"), easing: css(chip, "--pixilui-ease-out") },
);
a.onfinish = () => {
chip.style.overflow = "";
};
}
/** A small labelled pill: context in a composer, a filter, a tool. Removable, pressable, with an icon, dot, avatar or favicon. */
export const Chip = forwardRef<HTMLElement, ChipProps>(function Chip(
{ children, size = "md", icon, dot, avatar, favicon, note, count, pressed, onClick, adder, disabled, onRemove, removeLabel, removeIcon, className, ...props },
forwarded,
) {
const ref = useRef<HTMLElement | null>(null);
const row = useContext(Row);
const setRef = useCallback(
(el: HTMLElement | null) => {
ref.current = el;
if (typeof forwarded === "function") forwarded(el);
else if (forwarded) forwarded.current = el;
},
[forwarded],
);
useLayoutEffect(() => {
if (row?.ready.current && ref.current) arrive(ref.current);
// a chip grows in only when it arrives after its row's first render
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const remove = () => {
if (ref.current && onRemove) leave(ref.current, () => void onRemove());
};
const onRemoveKey = (event: KeyboardEvent<HTMLSpanElement>) => {
if (event.key === "Backspace" || event.key === "Delete" || event.key === "Enter") {
event.preventDefault();
remove();
}
};
const button = pressed !== undefined || onClick !== undefined || adder;
const lead = dot ? (
<span className="pixilui-chip-dot" style={{ "--pixilui-dot": dot } as CSSProperties} />
) : avatar ? (
<span className="pixilui-chip-avatar" style={{ "--pixilui-av": avatar } as CSSProperties} />
) : favicon ? (
<span className="pixilui-chip-fav" style={{ "--pixilui-fav": favicon.color } as CSSProperties}>
{withClass(favicon.icon, "pixilui-i")}
</span>
) : (
withClass(icon, "pixilui-i")
);
const body = (
<>
{lead}
{children}
{note != null && " "}
{note != null && <span className="pixilui-chip-note">{note}</span>}
{count != null && <span className="pixilui-chip-count">{count}</span>}
{onRemove && (
<span
className="pixilui-chip-remove"
role="button"
tabIndex={0}
aria-label={removeLabel}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
remove();
}}
onKeyDown={onRemoveKey}
>
{withClass(removeIcon, "pixilui-i")}
</span>
)}
</>
);
const shared = {
className: cn("pixilui-chip font-body", className),
"data-size": size === "md" ? undefined : size,
"data-chip-add": adder ? "" : undefined,
};
if (button) {
return (
<button
ref={setRef as (el: HTMLButtonElement | null) => void}
type="button"
{...shared}
aria-pressed={pressed}
disabled={disabled}
onClick={onClick}
{...(props as ComponentPropsWithoutRef<"button">)}
>
{body}
</button>
);
}
return (
<span ref={setRef as (el: HTMLSpanElement | null) => void} {...shared} data-disabled={disabled ? "" : undefined} {...props}>
{body}
</span>
);
});
/* ------------------------------------------------------------------ the fact chip */
export type ChipFactProps = Omit<ComponentPropsWithoutRef<"span">, "children"> & {
/** The figure, set dark and medium: "$240". */
figure: ReactNode;
/** The rest, grey: "under the $500 limit". */
children?: ReactNode;
};
/** The evidence behind an agent's decision: the figure dark, the rest grey. Static. */
export const ChipFact = forwardRef<HTMLSpanElement, ChipFactProps>(function ChipFact({ figure, children, className, ...props }, ref) {
return (
<span ref={ref} className={cn("pixilui-fact font-body", className)} {...props}>
<b>{figure}</b> {children}
</span>
);
});
/* ------------------------------------------------------------------ the citation chip and its source card */
export type ChipCitationSource = {
/** Stable id. */
id: string;
/** What the chip says: "refund-policy.md", "Stripe docs". */
name: string;
/** The source's line icon (a file, a globe, a link). */
icon: ReactNode;
/** The source's own color for its icon (any CSS color); grey when left out. */
ink?: string;
/** Where it lives, in the card's head: "docs.stripe.com". */
domain: string;
/** The card's title. */
title: string;
/** The passage, cut to two lines. */
text: string;
};
export type ChipCitationCardProps = Omit<ComponentPropsWithoutRef<"div">, "children"> & {
/** The sources to show, in order. */
sources: ChipCitationSource[];
/** Draws the card in place, open and still (for a frozen copy or a reasoning trail's open card). */
still?: boolean;
};
/** The source card: each source's domain, title and passage, on the float surface. */
export const ChipCitationCard = forwardRef<HTMLDivElement, ChipCitationCardProps & { "data-in"?: string; "data-out"?: string }>(function ChipCitationCard({ sources, still, className, ...props }, ref) {
return (
<div ref={ref} className={cn("pixilui-cite-card", className)} data-static={still ? "" : undefined} {...props}>
{sources.map((s) => (
<div key={s.id} className="pixilui-cite-src" style={s.ink ? ({ "--pixilui-src-ink": s.ink } as CSSProperties) : undefined}>
<div className="pixilui-cite-src-h">
{withClass(s.icon, "pixilui-i pixilui-cite-ic pixilui-cite-ol")}
{s.domain}
</div>
<b>{s.title}</b>
<p>{s.text}</p>
</div>
))}
</div>
);
});
/* One card per page: which citation's card is in, and which one closed last (its card plays out). */
type CardState = { current: string | null; last: string | null };
let card: CardState = { current: null, last: null };
const listeners = new Set<() => void>();
const timers = { open: 0 as ReturnType<typeof setTimeout> | 0, close: 0 as ReturnType<typeof setTimeout> | 0 };
const chips = new Map<string, HTMLElement>();
let quiet = false;
const setCard = (next: CardState) => {
card = next;
listeners.forEach((l) => l());
};
const subscribe = (l: () => void) => {
listeners.add(l);
return () => listeners.delete(l);
};
const openCard = (id: string) => {
if (timers.close) clearTimeout(timers.close);
if (card.current === id) return;
setCard({ current: id, last: id });
};
const closeCard = () => {
if (!card.current) return;
setCard({ current: null, last: card.current });
};
const closeLater = (from: Element) => {
if (timers.close) clearTimeout(timers.close);
timers.close = setTimeout(closeCard, ms(from, "--pixilui-cite-close-delay"));
};
let escapeWired = false;
function wireEscape() {
if (escapeWired || typeof document === "undefined") return;
escapeWired = true;
document.addEventListener("keydown", (e) => {
if (e.key !== "Escape" || !card.current) return;
const chip = chips.get(card.current);
closeCard();
quiet = true;
chip?.focus();
quiet = false;
});
}
export type ChipCitationProps = Omit<ComponentPropsWithoutRef<"button">, "children"> & {
/** The sources behind the claim; the chip names the first and counts the rest (+1). */
sources: ChipCitationSource[];
/** The start of the chip's accessible name. */
labelPrefix?: string;
/** The word that joins source names in the accessible name. */
labelJoin?: string;
/** A frozen copy: no card, no listeners. */
frozen?: boolean;
/** Where the card portals to. Defaults to document.body. */
container?: HTMLElement | null;
};
/** The source right after a claim, on the sentence's own line; hover or focus opens its source card. */
export const ChipCitation = forwardRef<HTMLButtonElement, ChipCitationProps>(function ChipCitation(
{ sources, labelPrefix = "Source:", labelJoin = "and", frozen, container, className, style, ...props },
forwarded,
) {
const id = useId();
const cardId = `${id.replace(/[^\w-]/g, "")}-card`;
const ref = useRef<HTMLButtonElement | null>(null);
const cardRef = useRef<HTMLDivElement | null>(null);
const state = useSyncExternalStore(subscribe, () => card, () => card);
const open = !frozen && state.current === id;
const out = !frozen && !state.current && state.last === id;
const setRef = useCallback(
(el: HTMLButtonElement | null) => {
ref.current = el;
if (el) chips.set(id, el);
else chips.delete(id);
if (typeof forwarded === "function") forwarded(el);
else if (forwarded) forwarded.current = el;
},
[forwarded, id],
);
// where the card portals to, known only after mount (no document in the first render)
const [host, setHost] = useState<HTMLElement | null>(null);
useEffect(() => {
if (!frozen) wireEscape();
setHost(container ?? document.body);
}, [frozen, container]);
// place the card under the chip, kept inside the window's edges (chips.js open)
useLayoutEffect(() => {
const c = ref.current;
const el = cardRef.current;
if (!open || !c || !el) return;
const r = c.getBoundingClientRect();
const w = el.offsetWidth;
const edge = ms(el, "--pixilui-cite-card-edge");
const off = ms(el, "--pixilui-cite-card-offset");
el.style.left = `${Math.max(edge, Math.min(r.left + scrollX, scrollX + innerWidth - w - edge))}px`;
el.style.top = `${r.bottom + scrollY + off}px`;
}, [open]);
const [first, ...rest] = sources;
const handlers = frozen
? {}
: {
onPointerEnter: () => {
if (timers.open) clearTimeout(timers.open);
timers.open = setTimeout(() => openCard(id), ms(ref.current!, "--pixilui-cite-open-delay"));
},
onPointerLeave: () => {
if (timers.open) clearTimeout(timers.open);
closeLater(ref.current!);
},
onFocus: () => {
if (!quiet) openCard(id);
},
onBlur: () => closeLater(ref.current!),
onClick: () => (card.current === id ? closeCard() : openCard(id)),
};
return (
<>
<button
ref={setRef}
type="button"
className={cn("pixilui-cite font-body", className)}
data-src={sources.map((s) => s.id).join(",")}
aria-expanded={open}
aria-describedby={open ? cardId : undefined}
aria-label={`${labelPrefix} ${sources.map((s) => s.name).join(` ${labelJoin} `)}`}
style={first?.ink ? ({ "--pixilui-src-ink": first.ink, ...style } as CSSProperties) : style}
{...handlers}
{...props}
>
{first && withClass(first.icon, "pixilui-i pixilui-cite-ic pixilui-cite-ol")}
{first && <span className="pixilui-cite-name">{first.name}</span>}
{rest.length > 0 && <span className="pixilui-cite-more">{`+${rest.length}`}</span>}
</button>
{(open || out) &&
host &&
createPortal(
<ChipCitationCard
ref={cardRef}
id={cardId}
role="tooltip"
sources={sources}
data-in={open ? "" : undefined}
data-out={out ? "" : undefined}
onPointerEnter={() => timers.close && clearTimeout(timers.close)}
onPointerLeave={(e) => closeLater(e.currentTarget)}
/>,
host,
)}
</>
);
});
Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { Chip } from "@/components/pixilui/chip";
<Chip onClick={onClick} onRemove={onRemove}>Save changes</Chip>Chips wrap inside a ChipRow; a citation sits on the sentence's own line and wraps with it.
API reference
PropTypeDefault
size"md" | "sm""md"md 30 (the default), sm 26.iconReactNode–A leading icon (an animated icon from packages/registry/icons).dotstring–A leading status dot in this color (any CSS color or token, such as var(--pixilui-st-done-h)).avatarstring–A leading avatar circle in this color, for a person.favicon{ icon: ReactNode; color: string }–A leading favicon tile: the product's mark on its own color.noteReactNode–The grey rest of a two-tone label: "Opus 5.5" with note "fast".countnumber | string–A count after the label, grey (deep accent when pressed).pressedboolean–Pressed state: the chip becomes a toggle button (aria-pressed), the filter chip.onClick(event: MouseEvent<HTMLElement>) => void–Makes the chip a button.adderboolean–The add chip of a ChipRow: focus lands on it when the last chip leaves.disabledboolean–Disabled: muted at 55%, no hover or press.onRemove() => void | Promise<void>–Shows a remove button; runs once the chip has folded away. Remove it from your list here.removeLabelstring–The remove button's accessible name, such as "Remove acme-webapp".removeIconReactNode–The remove button's icon (a cross).childrenReactNode–The label.Also takes every native <span> attribute except onClick, and a ref.
Keyboard
TabMoves to each remove button, pressable chip and citation in turn.
Enter Backspace DeleteOn a remove button, removes the chip and moves focus to the next chip's remove, else the previous one, else the add chip.
EscCloses an open source card and keeps focus on its citation.
Accessibility
- A chip at rest is a span; with pressed or onClick it is a button, and pressed writes aria-pressed.
- The remove is a focusable role="button" named by removeLabel, such as "Remove refund-policy.md".
- A citation is a button named "Source: name and name" with aria-expanded; its card is role="tooltip", tied with aria-describedby while open.
- Every word passes 4.5:1 in both themes; disabled chips are muted to 55%.
Motion
- A removed chip shrinks to nothing and fades in 180ms while the row closes the gap.
- A chip added to a ChipRow after its first render grows from nothing, rising 2px, in 200ms.
- A citation's card opens 120ms after hover or focus and grows from the chip's corner; it closes 140ms after the pointer leaves.
- Hover tints and press scales in 150ms. Reduced motion: removed and added at once, the card without animation.