Checkbox
FreeA 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.
npx shadcn@latest add https://pixilui.com/r/checkbox.jsonPreview
The tick draws itself just after the color comes up.
Save
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>
);
}When to use
Use it when
- 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.
Use something else when
- 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.
Installation
Terminal
npx shadcn@latest add https://pixilui.com/r/checkbox.jsonAdds checkbox.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/checkbox.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>
);
});
Then npm i clsx tailwind-merge, and add the foundation once per app, as in Installation.
Usage
example.tsx
import { Checkbox } from "@/components/pixilui/checkbox";
<Checkbox onCheckedChange={onCheckedChange}>Save changes</Checkbox>The box is 14px at every width; a row's words wrap beside it, the box on the first line.
API reference
PropTypeDefault
namestring–A form field name: a hidden input carries value while the box is on.defaultCheckedCheckboxCheckedfalseUncontrolled: the state on the first render.checkedCheckboxChecked–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.valuestring"on"The value sent with the form while on.Also takes every native <button> attribute except onChange, value, defaultValue, role, and a ref.
Keyboard
TabMoves to each checkbox in turn.
Space EnterTurns 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.