# Checkbox

A glass checkbox whose tick draws itself, with a mixed state for a parent, rows that click anywhere, and a save that can fail and put itself back.

Tier: free. Type: component. Category: selection. Tags: settings, permissions, form, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/checkbox.json
```

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

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

Files: `components/pixilui/checkbox.tsx`.

## Preview

Live preview: https://pixilui.com/components/checkbox

Knobs:

- `save`: `instant`, `fails`

Signature: Check a box and the candy glass rises first, then 40ms later the white tick draws itself across it.

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/checkbox.tsx, quiet https://pixilui.com/r/standalone/checkbox.quiet.tsx.

## Code

`components/pixilui/checkbox.tsx`

```tsx
"use client";

/*
  The checkbox, locked 27 Nov 2026 with the toggles (design/explorations/components/locked/toggles). Its
  look and motion are foundation.css section 8 (.pixilui-checkbox); this file writes the locked markup and
  plays the locked behavior (toggles.js):

  Cap       a 14px white glass cap; hover darkens the edge and previews a faint tick.
  On        the candy glass cross-fades in (200ms), and the tick draws itself 40ms later (220ms).
  Mixed     the candy with a white dash that draws (180ms): a parent with some of its children on.
  Press     scales to .9.
  Load      boxes checked on the first render show their tick at once: the tick draws only after the
            page has painted (.pixilui-toggles-ready on <html>, as the locked page does).
  Pending   onCheckedChange may return a promise: the box shows the new state at once, is aria-busy
            until it settles, and goes back if it rejects.
  Reduced   no transitions, the tick shown at once.
*/

import { forwardRef, useEffect, useId, useState, type ComponentPropsWithoutRef, type MouseEvent, type ReactNode } from "react";
import { cn } from "./lib/utils";

export type CheckboxChecked = boolean | "mixed";

export type CheckboxProps = Omit<ComponentPropsWithoutRef<"button">, "onChange" | "value" | "defaultValue" | "children" | "role"> & {
  /** Controlled: on, off, or "mixed" (a parent with some of its children on). */
  checked?: CheckboxChecked;
  /** Uncontrolled: the state on the first render. */
  defaultChecked?: CheckboxChecked;
  /**
   * Runs with the new state on a click, Space or Enter. Return a promise to save first: the box shows the new
   * state, is aria-busy until it settles, and goes back if it rejects.
   */
  onCheckedChange?: (checked: boolean) => void | Promise<void>;
  /** A form field name: a hidden input carries value while the box is on. */
  name?: string;
  /** The value sent with the form while on. */
  value?: string;
};

/** The tick draws only after the first paint, so boxes checked on load don't draw in (toggles.js). */
let readyQueued = false;
function useTogglesReady() {
  useEffect(() => {
    if (readyQueued) return;
    readyQueued = true;
    requestAnimationFrame(() => requestAnimationFrame(() => document.documentElement.classList.add("pixilui-toggles-ready")));
  }, []);
}

/** The state a parent checkbox shows for its children: on when all are, off when none are, mixed between. */
export function checkboxGroupState(children: boolean[]): CheckboxChecked {
  const on = children.filter(Boolean).length;
  return on === 0 ? false : on === children.length ? true : "mixed";
}

/** A parent's click: every child it can change goes on, or off once they are all on (toggles.js). */
export function checkboxGroupNext(children: boolean[], disabled: boolean[] = []): boolean[] {
  const next = !children.every((c, i) => c || disabled[i]);
  return children.map((c, i) => (disabled[i] ? c : next));
}

/** One checkbox: a glass cap whose tick draws itself. Give it an aria-label, or put it in a CheckboxRow. */
export const Checkbox = forwardRef<HTMLButtonElement, CheckboxProps>(function Checkbox(
  { checked, defaultChecked = false, onCheckedChange, name, value = "on", disabled, onClick, className, ...props },
  ref,
) {
  useTogglesReady();
  const [own, setOwn] = useState<CheckboxChecked>(defaultChecked);
  const [pending, setPending] = useState<boolean | null>(null);
  const shown = pending ?? checked ?? own;
  const flip = async (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented || disabled || pending !== null) return;
    const before = shown;
    const next = shown !== true;
    if (checked === undefined) setOwn(next);
    const result = onCheckedChange?.(next);
    if (!result || typeof (result as Promise<void>).then !== "function") return;
    setPending(next);
    try {
      await result;
    } catch {
      if (checked === undefined) setOwn(before);
    } finally {
      setPending(null);
    }
  };
  return (
    <>
      <button
        ref={ref}
        type="button"
        role="checkbox"
        aria-checked={shown === "mixed" ? "mixed" : shown ? "true" : "false"}
        aria-busy={pending !== null || undefined}
        disabled={disabled}
        className={cn("pixilui-checkbox focus-visible:focus-ring", className)}
        onClick={flip}
        {...props}
      >
        <svg viewBox="0 0 14 14" aria-hidden="true">
          <path className="pixilui-checkbox-tick" pathLength={1} d="M3.7 7.35l2.2 2.2 4.4-4.9" />
          <path className="pixilui-checkbox-dash" pathLength={1} d="M4.4 7h5.2" />
        </svg>
      </button>
      {name && shown === true && <input type="hidden" name={name} value={value} />}
    </>
  );
});

export type CheckboxRowProps = CheckboxProps & {
  /** The row's label: names the checkbox, and a click on it reaches the box. */
  label: ReactNode;
  /** A second line under the label. */
  description?: ReactNode;
  /** Sets the second line in the warning color, for a choice with a cost ("Sends as you"). */
  risk?: boolean;
  /** Text at the row's end, such as "3 of 5". */
  meta?: ReactNode;
  /** Class for the row (className goes to the checkbox). */
  rowClassName?: string;
};

/** A checkbox with its label and an optional second line; the whole row clicks. */
export const CheckboxRow = forwardRef<HTMLButtonElement, CheckboxRowProps>(function CheckboxRow(
  { label, description, risk, meta, rowClassName, "aria-label": ariaLabel, ...props },
  ref,
) {
  const id = useId();
  return (
    <label className={cn("pixilui-toggle-row font-body", rowClassName)}>
      <Checkbox ref={ref} aria-label={ariaLabel ?? (typeof label === "string" ? label : undefined)} aria-describedby={description ? `${id}-d` : undefined} {...props} />
      <span className="pixilui-toggle-row-text">
        <b>{label}</b>
        {description && (
          <small id={`${id}-d`} data-tone={risk ? "risk" : undefined}>
            {description}
          </small>
        )}
      </span>
      {meta != null && <span className="pixilui-toggle-row-meta">{meta}</span>}
    </label>
  );
});
```

## Usage

When to use:

- Picking several from a short list: the tools an agent may use, the sources a search reads.
- A parent over a group, showing all, none or some (mixed) with an "n of m" count.
- An agreement or opt-in inside a form that is submitted later.

When not to use:

- A setting that takes effect at once: use Switch.
- One choice among a few: use Radio group.
- A long list with search: use a menu with checkbox rows.

```tsx
import { useState } from "react";
import { CheckboxRow, checkboxGroupNext, checkboxGroupState } from "@/components/pixilui/checkbox";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  save: ["instant", "fails"],
} as const;

const tools = [
  { name: "Web search", note: "Reads public pages" },
  { name: "Read files", note: "Only the folders you shared" },
  { name: "Send email", note: "Sends as you, from your address", risk: true },
  { name: "Run code", note: "In a sandbox, no network" },
  { name: "Spend money", note: "Needs an admin", disabled: true },
];

/** The tools an agent may use: a parent with its count over five rows; "fails" makes every save reject after 700ms so the box puts itself back. */
export default function CheckboxDemo({ save = "instant" }: KnobValues<typeof knobs>) {
  const [on, setOn] = useState([true, true, false, true, false]);
  const disabled = tools.map((t) => Boolean(t.disabled));
  const enabled = on.filter((_, i) => !disabled[i]);
  const settle = () => (save === "fails" ? new Promise<void>((_, reject) => setTimeout(() => reject(new Error("Not saved")), 700)) : undefined);
  return (
    <div className="w-full max-w-sm rounded-panel bg-surface px-5 py-3 elevation-raised">
      <CheckboxRow
        label="All tools"
        checked={checkboxGroupState(enabled)}
        meta={`${enabled.filter(Boolean).length} of ${enabled.length}`}
        onCheckedChange={() => setOn(checkboxGroupNext(on, disabled))}
      />
      <div className="ps-6.5">
        {tools.map((t, i) => (
          <CheckboxRow
            key={t.name}
            label={t.name}
            description={t.note}
            risk={t.risk}
            disabled={t.disabled}
            checked={on[i]}
            onCheckedChange={(next) => {
              setOn((all) => all.map((v, j) => (j === i ? next : v)));
              const result = settle();
              return result?.catch((error: unknown) => {
                setOn((all) => all.map((v, j) => (j === i ? !next : v)));
                throw error;
              });
            }}
          />
        ))}
      </div>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` |  | A form field name: a hidden input carries value while the box is on. |
| `defaultChecked` | `CheckboxChecked` | `false` | Uncontrolled: the state on the first render. |
| `checked` | `CheckboxChecked` |  | Controlled: on, off, or "mixed" (a parent with some of its children on). |
| `onCheckedChange` | `(checked: boolean) => void \| Promise<void>` |  | Runs with the new state on a click, Space or Enter. Return a promise to save first: the box shows the new state, is aria-busy until it settles, and goes back if it rejects. |
| `value` | `string` | `"on"` | The value sent with the form while on. |

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

## Keyboard

- `Tab`: Moves to each checkbox in turn.
- `Space` + `Enter`: Turns the focused checkbox on or off.

## Accessibility

- A button with role="checkbox" and aria-checked true, false or mixed.
- In a CheckboxRow the label names it and the second line describes it (aria-describedby); alone, give it an aria-label.
- The row is a label, so a click on the words reaches the box once.
- While a returned promise is pending the box is aria-busy and keeps its focus.

## Motion

- On, the candy glass cross-fades in over 200ms and the tick draws itself 40ms later in 220ms; mixed draws its dash in 180ms.
- Press scales the box to .9; hover darkens the edge and previews a faint tick.
- Boxes checked on the first render show their tick at once: it draws only after the page has painted.
- Reduced motion: no transitions, the tick shown at once.

## Responsive

- The box is 14px at every width; a row's words wrap beside it, the box on the first line.

## Performance

- The look and motion are CSS in the foundation (section 8); the component writes one button and one small SVG.

## Notes for AI

- <CheckboxRow label="Send email" description="Sends as you, from your address" risk checked={on} onCheckedChange={setOn} />.
- checked takes true, false or "mixed"; onCheckedChange always gets a boolean.
- For a parent: checked={checkboxGroupState(children)} and on change set the children to checkboxGroupNext(children, disabled); meta shows "3 of 5".
- Return a promise from onCheckedChange to save to a server: the box flips at once and flips back if it rejects.
- Pass name (and value) to send it with a native form.

## Related

- [Switch](https://pixilui.com/components/switch/markdown): A glass switch for a setting that takes effect at once: the capsule knob springs across, turns into a clear lens while held, and puts itself back if the save fails.
- [Radio group](https://pixilui.com/components/radio-group/markdown): One choice among a few, as glass radio rows whose white bead springs in, with arrow keys that skip what can't be picked and a risky option set in the warning color.
- [Dropdown menu](https://pixilui.com/components/dropdown-menu/markdown): The base for every menu, select and picker: it grows out of its trigger, a highlight glides between rows, and rows can be actions, choices that say what they cost, checkboxes, switches or submenus.
