Chip group
FreeA row of filter chips with counts: press one and it fills with the accent tint, and the total beside it rolls only the digits that changed.
npx shadcn@latest add https://pixilui.com/r/chip-group.jsonPreview
Press a filter and only the changed digits of the total roll.
Mode
Size
import { useState } from "react";
import { ChipGroup, ChipGroupTotal, chipGroupTotal, type ChipGroupOption } from "@/components/pixilui/chip-group";
// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
mode: ["several", "single"],
size: ["md", "sm"],
} as const;
const options: ChipGroupOption[] = [
{ value: "all", label: "All", count: 128, all: true },
{ value: "review", label: "Needs review", count: 3 },
{ value: "refunds", label: "Refunds", count: 41 },
{ value: "billing", label: "Billing", count: 12 },
{ value: "archived", label: "Archived", count: 0, disabled: true },
];
/** Filters over a run list, with the total rolling in the sentence above. */
export default function ChipGroupDemo({ mode = "several", size = "md" }: KnobValues<typeof knobs>) {
const [value, setValue] = useState<string[]>(["all"]);
return (
<div className="flex w-full max-w-lg flex-col gap-4">
<p className="type-label text-secondary" aria-live="polite">
Showing <ChipGroupTotal value={chipGroupTotal(options, value)} /> runs
</p>
<ChipGroup key={mode} aria-label="Filter runs" options={options} value={value} onValueChange={setValue} single={mode === "single"} size={size} />
</div>
);
}When to use
Use it when
- Filtering a list of runs, tickets or sources by a few known groups, with a count on each.
- A single choice among a few short options that read as filters (single).
- Showing how many results the filters leave, with ChipGroupTotal in the sentence beside it.
Use something else when
- Switching between views of the same thing: use a segmented control or tabs.
- Many options or a search: use a menu or a select.
- Context attached to a prompt: use Chip in a ChipRow.
Installation
Terminal
npx shadcn@latest add https://pixilui.com/r/chip-group.jsonAdds chip-group.tsx with 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-group.tsx
"use client";
/*
The filter group, locked 28 Nov 2026 with the chips (design/explorations/components/locked/chips,
chips.js wire and roll). Filter chips are buttons with aria-pressed:
- a chip marked all clears the others, and comes back when none is on;
- single allows one at a time;
- the total is each pressed chip's count added up (the all chip's count when none is on).
ChipGroupTotal rolls that total: changed digits slide up out and the new ones slide in (the move time,
the out curve); a digit that leaves narrows its slot, one that arrives widens it, and every digit stays
on the text's baseline. Reduced motion: the number swaps at once.
*/
import { forwardRef, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef, type ReactNode } from "react";
import { cn } from "./lib/utils";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";
import { Chip } from "./chip";
import { safeAnimate } from "./lib/motion/animate";
/** A missing list prop (plain JavaScript, a guessing agent): one stable empty list, so nothing throws or re-renders. */
const NONE: never[] = [];
export type ChipGroupOption = {
/** What the group reports when the chip is on. */
value: string;
/** The words. */
label: ReactNode;
/** How many this filter matches: shown in the chip and added into the total. */
count?: number;
/** A leading icon. */
icon?: ReactNode;
/** The chip that clears the others ("All"). */
all?: boolean;
/** Disabled. */
disabled?: boolean;
};
export type ChipGroupProps = Omit<ComponentPropsWithoutRef<"div">, "onChange" | "defaultValue"> & {
/** The filters, in order. */
options: ChipGroupOption[];
/** Controlled: the values that are on. */
value?: string[];
/** Starting values when uncontrolled (defaults to the all chip, if there is one). */
defaultValue?: string[];
/** Runs with the values that are on and the total of their counts. */
onValueChange?: (value: string[], total: number) => void;
/** One at a time. */
single?: boolean;
/** md 30 (the default), sm 26. */
size?: "md" | "sm";
/** The group's accessible name, such as "Filter runs". */
"aria-label": string;
};
/** The total of a filter group's counts: the pressed chips', or the all chip's when none is on. */
export function chipGroupTotal(options: ChipGroupOption[], value: string[]): number {
const all = options.find((o) => o.all);
const on = options.filter((o) => o !== all && value.includes(o.value));
return (on.length ? on : all ? [all] : []).reduce((sum, o) => sum + (o.count ?? 0), 0);
}
/** The next set of values after a click (chips.js wire). */
function press(options: ChipGroupOption[], value: string[], picked: ChipGroupOption, single: boolean): string[] {
const all = options.find((o) => o.all);
if (single) return [picked.value];
const on = !value.includes(picked.value);
if (picked === all) return on ? [all.value] : value;
let next = options.filter((o) => o !== all && (o === picked ? on : value.includes(o.value))).map((o) => o.value);
if (all && next.length === 0) next = [all.value];
return next;
}
/** A row of filter chips: tap one and it fills; its count rolls into the total. */
export const ChipGroup = forwardRef<HTMLDivElement, ChipGroupProps>(function ChipGroup(
{ options = NONE, value, defaultValue, onValueChange, single = false, size = "md", className, ...props },
ref,
) {
const all = options.find((o) => o.all);
const [own, setOwn] = useState<string[]>(defaultValue ?? (all ? [all.value] : []));
const current = value ?? own;
return (
<div ref={ref} role="group" data-chip-group="" className={cn("flex flex-wrap items-center gap-2 font-body", className)} {...props}>
{options.map((o) => (
<Chip
key={o.value}
size={size}
icon={o.icon}
count={o.count}
data-all={o.all ? "" : undefined}
data-count={o.count}
disabled={o.disabled}
pressed={current.includes(o.value)}
onClick={() => {
const next = press(options, current, o, single);
if (value === undefined) setOwn(next);
onValueChange?.(next, chipGroupTotal(options, next));
}}
>
{o.label}
</Chip>
))}
</div>
);
});
const read = (el: Element, name: string) => getComputedStyle(el).getPropertyValue(name).trim();
/** Rolls the changed digits of a number in place (chips.js roll), on the element itself. */
function roll(el: HTMLElement & { _rollClear?: ReturnType<typeof setTimeout> }, next: string) {
const prev = el.dataset.value ?? el.textContent?.trim() ?? "";
if (next === prev) return;
el.dataset.value = next;
el.classList.add("pixilui-roll");
clearTimeout(el._rollClear); // a quicker second change must not clear the new digits early
const len = Math.max(prev.length, next.length);
const a = prev.padStart(len, " ");
const b = next.padStart(len, " ");
const still = prefersReducedMotion();
const slots: [HTMLSpanElement, "in" | "out"][] = [];
el.innerHTML = "";
for (let i = 0; i < len; i++) {
const o = a[i]!;
const n = b[i]!;
const cell = document.createElement("span");
if (o === n || still) {
if (n === " ") continue;
cell.textContent = n;
} else if (n === " ") {
// a digit leaves: its slot narrows to nothing
cell.innerHTML = `<span class="pixilui-roll-out pixilui-roll-gone" aria-hidden="true">${o}</span>`;
slots.push([cell, "out"]);
} else if (o === " ") {
// a digit arrives: its slot widens from nothing
cell.innerHTML = `<span class="pixilui-roll-in">${n}</span>`;
slots.push([cell, "in"]);
} else cell.innerHTML = `<span class="pixilui-roll-in">${n}</span><span class="pixilui-roll-out" aria-hidden="true">${o}</span>`;
el.append(cell);
}
const time: KeyframeAnimationOptions = { duration: parseFloat(read(el, "--pixilui-dur-move")) || 0, easing: read(el, "--pixilui-ease-out"), fill: "forwards" };
slots.forEach(([cell, dir]) => {
const w = `${cell.getBoundingClientRect().width}px`;
cell.classList.add("pixilui-roll-grow");
if (typeof cell.animate === "function") safeAnimate(cell, dir === "in" ? [{ width: "0px" }, { width: w }] : [{ width: w }, { width: "0px" }], time);
});
el._rollClear = setTimeout(() => {
el.querySelectorAll(".pixilui-roll-gone").forEach((x) => x.parentElement?.remove());
el.querySelectorAll(".pixilui-roll-out").forEach((x) => x.remove());
el.querySelectorAll<HTMLElement>(".pixilui-roll-grow").forEach((c) => {
c.getAnimations?.().forEach((x) => x.cancel());
c.classList.remove("pixilui-roll-grow");
});
}, parseFloat(read(el, "--pixilui-roll-clear")) || 0);
}
export type ChipGroupTotalProps = Omit<ComponentPropsWithoutRef<"span">, "children"> & {
/** The number to show; a change rolls the digits that changed. Formatted numbers (1,240) roll too. */
value: number | string;
};
/** The group's total, beside it in a sentence ("Showing 12 runs"): changed digits roll. */
export const ChipGroupTotal = forwardRef<HTMLSpanElement, ChipGroupTotalProps>(function ChipGroupTotal({ value, ...props }, forwarded) {
const ref = useRef<HTMLSpanElement | null>(null);
// React writes the first value; every change after is the roll, on the element itself
const [first] = useState(String(value));
useLayoutEffect(() => {
if (ref.current) roll(ref.current, String(value));
}, [value]);
return (
<span
ref={(el) => {
ref.current = el;
if (typeof forwarded === "function") forwarded(el);
else if (forwarded) forwarded.current = el;
}}
data-chip-total=""
{...props}
>
{first}
</span>
);
});
It uses Chip: add it the same way. Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { ChipGroup } from "@/components/pixilui/chip-group";
<ChipGroup
aria-label={aria-label}
options={options}
onValueChange={onValueChange}
/>The chips wrap; the total sits in its own sentence and wraps with it.
API reference
PropTypeDefault
aria-labelRequiredstring–The group's accessible name, such as "Filter runs".optionsRequiredChipGroupOption[]NONEThe filters, in order.valuestring[]–Controlled: the values that are on.defaultValuestring[]–Starting values when uncontrolled (defaults to the all chip, if there is one).onValueChange(value: string[], total: number) => void–Runs with the values that are on and the total of their counts.singlebooleanfalseOne at a time.size"md" | "sm""md"md 30 (the default), sm 26.Also takes every native <div> attribute except onChange, defaultValue, and a ref.
Keyboard
TabMoves through the filter chips in order.
Enter SpacePresses or releases the focused filter.
Accessibility
- The group is role="group" named by its aria-label, such as "Filter runs".
- Each filter is a button with aria-pressed.
- The all chip clears the others and comes back on its own when none is pressed.
- Put ChipGroupTotal inside a sentence ("Showing 12 runs") and give that sentence aria-live="polite" if the count should be announced.
Motion
- A pressed chip takes the accent tint, ring and deep accent words in 150ms.
- The total rolls only the digits that changed, up and out, in 350ms on the out curve; a digit that leaves narrows its slot and one that arrives widens it, all on the text's baseline.
- Reduced motion: the number swaps at once.