# Chip group

A 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.

Tier: free. Type: component. Category: selection. Tags: run, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/chip-group.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/chip-group.tsx`.

## Preview

Live preview: https://pixilui.com/components/chip-group

Knobs:

- `mode`: `several`, `single`
- `size`: `md`, `sm`

Signature: Press a filter and only the digits of the total that changed roll up, each slot widening or narrowing on the baseline so 12 to 3 never jumps.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/chip-group.tsx, quiet https://pixilui.com/r/standalone/chip-group.quiet.tsx.

## Code

`components/pixilui/chip-group.tsx`

```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>
  );
});
```

## Usage

When to use:

- 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.

When not to use:

- 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.

```tsx
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>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` (required) | `string` |  | The group's accessible name, such as "Filter runs". |
| `options` (required) | `ChipGroupOption[]` | `NONE` | The filters, in order. |
| `value` | `string[]` |  | Controlled: the values that are on. |
| `defaultValue` | `string[]` |  | 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. |
| `single` | `boolean` | `false` | One at a time. |
| `size` | `"md" \| "sm"` | `"md"` | md 30 (the default), sm 26. |

Also accepts every native `<div>` attribute except `onChange`, `defaultValue`, and a ref to it.

## Keyboard

- `Tab`: Moves through the filter chips in order.
- `Enter` + `Space`: Presses 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.

## Responsive

- The chips wrap; the total sits in its own sentence and wraps with it.

## Performance

- The roll touches only the total's own spans and clears itself after 400ms; the chips are CSS.

## Notes for AI

- <ChipGroup aria-label="Filter runs" options={[{ value: "all", label: "All", count: 12, all: true }, ...]} onValueChange={(values, total) => ...} />.
- value is the list of pressed values; the all option clears the rest. single allows one at a time.
- chipGroupTotal(options, value) adds up the pressed counts (or the all chip's): pass it to <ChipGroupTotal value={...} /> in a sentence.
- Counts are plain numbers in the options; the component never fetches.

## Related

- [Chip](https://pixilui.com/components/chip/markdown): The 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.
- [Segmented control](https://pixilui.com/components/segmented-control/markdown): One choice from two to five on a grey track: the picked pill slides to your next pick, its words changing color as it passes, and a time-boxed option says when it ends and switches back.
- [Badge](https://pixilui.com/components/badge/markdown): A fixed fact about a run as a tag, a badge inline in a table, or a small count beside a name, in the locked status colors with solid icons cut from the free Hugeicons.
