Checkbox Tree with Mixed Parent
A parent checkbox that controls an indented list of child checkboxes and shows a mixed state when only some are checked. Use it for permission scopes or export field selection.
How it differs. Two levels: the parent derives checked, unchecked or mixed from its children and sets them all when toggled. Children hang off a guide line under the parent, which carries a running count.
Install
pnpm dlx shadcn@latest add @hazine/checkbox-tree-mixed-parentAdds 1 file, 1 Hazine item (@hazine/use-controllable-state), and 2 packages (lucide-react, class-variance-authority).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/checkbox-tree-mixed-parent.tsx, 328 lines
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Check, CircleAlert, Minus } from "lucide-react"
import { cn } from "@/lib/utils"
import { useControllableState } from "@/hooks/use-controllable-state"
export interface CheckboxTreeItem {
value: string
label: string
description?: string
/** Keeps its current state when the parent is toggled. */
disabled?: boolean
}
type CheckState = "checked" | "unchecked" | "mixed"
const SKELETON_WIDTHS = ["w-32", "w-44", "w-24"]
const checkboxTreeMixedParentVariants = cva(
"relative flex w-full cursor-pointer items-start gap-3 rounded-md px-1.5 text-start text-sm transition-colors duration-100 hover:bg-muted/50 active:bg-muted",
{
variants: {
density: {
compact: "py-1.5",
default: "py-2.5",
comfortable: "py-3",
},
},
defaultVariants: {
density: "default",
},
}
)
const parentClass =
"focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground disabled:pointer-events-none disabled:opacity-50"
const itemClass =
"has-[:focus-visible]:outline-2 has-[:focus-visible]:-outline-offset-2 has-[:focus-visible]:outline-foreground has-[:disabled]:pointer-events-none has-[:disabled]:opacity-50"
const boxClass =
"flex size-5 shrink-0 items-center justify-center rounded-sm border border-foreground/50 bg-background text-primary-foreground transition-colors duration-150 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=mixed]:border-primary data-[state=mixed]:bg-primary"
function Box({ state, invalid }: { state: CheckState; invalid?: boolean }) {
return (
<span
aria-hidden="true"
data-slot="checkbox-tree-mixed-parent-box"
data-state={state}
className={cn(
boxClass,
invalid && state === "unchecked" && "border-destructive"
)}
>
{state === "checked" ? <Check className="size-3.5" /> : null}
{state === "mixed" ? <Minus className="size-3.5" /> : null}
</span>
)
}
function defaultFormatCount(checked: number, total: number) {
return `${checked} of ${total}`
}
export interface CheckboxTreeMixedParentProps
extends
Omit<React.ComponentProps<"div">, "defaultValue" | "onChange" | "children">,
VariantProps<typeof checkboxTreeMixedParentVariants> {
/** Text of the parent checkbox. Also names the group of children. */
label: string
description?: string
items: CheckboxTreeItem[]
/** Values of the checked children. */
value?: string[]
defaultValue?: string[]
onValueChange?: (value: string[]) => void
/** Form field name given to every child checkbox. */
name?: string
disabled?: boolean
loading?: boolean
loadingLabel?: string
/** Validation message. Marks the parent invalid while present. */
error?: React.ReactNode
/** Shown in place of the children when `items` is empty. */
empty?: React.ReactNode
/** Count at the end of the parent row, also announced after each change. */
formatCount?: (checked: number, total: number) => string
}
export function CheckboxTreeMixedParent({
label,
description,
items,
value: valueProp,
defaultValue,
onValueChange,
name,
disabled = false,
loading = false,
loadingLabel = "Loading options",
error,
empty = "No options available.",
formatCount = defaultFormatCount,
density = "default",
className,
...props
}: CheckboxTreeMixedParentProps) {
const baseId = React.useId()
const titleId = `${baseId}-title`
const descriptionId = `${baseId}-description`
const countId = `${baseId}-count`
const errorId = `${baseId}-error`
const [value, setValue] = useControllableState<string[]>({
value: valueProp,
defaultValue: defaultValue ?? [],
onChange: onValueChange,
})
const selected = new Set(value)
const checkedCount = items.filter((item) => selected.has(item.value)).length
const enabledItems = items.filter((item) => !item.disabled)
const state: CheckState =
items.length > 0 && checkedCount === items.length
? "checked"
: checkedCount > 0
? "mixed"
: "unchecked"
const invalid = Boolean(error)
const parentDisabled = disabled || loading || enabledItems.length === 0
const count = formatCount(checkedCount, items.length)
const rowClass = checkboxTreeMixedParentVariants({ density })
const showCount = !loading && items.length > 0
const describedBy = [
description ? descriptionId : "",
showCount ? countId : "",
invalid ? errorId : "",
]
.filter(Boolean)
.join(" ")
// Values that belong to no item are kept in front, the rest follow the
// order of `items`, so the array is stable however the user got there.
function commit(next: Set<string>, previous: string[]) {
const known = new Set(items.map((item) => item.value))
return [
...previous.filter((entry) => !known.has(entry)),
...items.filter((item) => next.has(item.value)).map((item) => item.value),
]
}
function toggleAll() {
setValue((previous) => {
const next = new Set(previous)
const allOn = enabledItems.every((item) => next.has(item.value))
for (const item of enabledItems) {
if (allOn) next.delete(item.value)
else next.add(item.value)
}
return commit(next, previous)
})
}
function toggleItem(itemValue: string, checked: boolean) {
setValue((previous) => {
const next = new Set(previous)
if (checked) next.add(itemValue)
else next.delete(itemValue)
return commit(next, previous)
})
}
return (
<div
data-slot="checkbox-tree-mixed-parent"
data-state={state}
data-density={density}
aria-busy={loading || undefined}
className={cn("flex flex-col text-foreground", className)}
{...props}
>
<button
type="button"
role="checkbox"
data-slot="checkbox-tree-mixed-parent-parent"
aria-checked={state === "mixed" ? "mixed" : state === "checked"}
aria-labelledby={titleId}
aria-describedby={describedBy.length > 0 ? describedBy : undefined}
aria-controls={
!showCount
? undefined
: items.map((_, index) => `${baseId}-item-${index}`).join(" ")
}
aria-invalid={invalid || undefined}
disabled={parentDisabled}
onClick={toggleAll}
// A checkbox toggles on Space only. Enter would also click a button.
onKeyDown={(event) => {
if (event.key === "Enter") event.preventDefault()
}}
className={cn(rowClass, parentClass)}
>
<Box state={state} invalid={invalid} />
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span id={titleId} className="font-semibold break-words">
{label}
</span>
{description ? (
<span
id={descriptionId}
className="break-words text-muted-foreground"
>
{description}
</span>
) : null}
</span>
{showCount ? (
<span
id={countId}
data-slot="checkbox-tree-mixed-parent-count"
className="shrink-0 whitespace-nowrap text-muted-foreground tabular-nums"
>
{count}
</span>
) : null}
</button>
<p role="status" className="sr-only">
{loading ? loadingLabel : items.length > 0 ? `${label}: ${count}` : ""}
</p>
<div
role="group"
aria-labelledby={titleId}
aria-describedby={invalid ? errorId : undefined}
data-slot="checkbox-tree-mixed-parent-group"
className="relative ps-8"
>
<span
aria-hidden="true"
className="absolute inset-y-1 start-4 w-px bg-border"
/>
{loading ? (
<div aria-hidden="true">
{SKELETON_WIDTHS.map((width) => (
<div key={width} className={cn(rowClass, "pointer-events-none")}>
<span className="size-5 shrink-0 rounded-sm bg-muted motion-safe:animate-pulse" />
<span
className={cn(
"my-0.5 h-4 rounded-md bg-muted motion-safe:animate-pulse",
width
)}
/>
</div>
))}
</div>
) : items.length === 0 ? (
<p
data-slot="checkbox-tree-mixed-parent-empty"
className="px-1.5 py-1.5 text-sm text-muted-foreground"
>
{empty}
</p>
) : (
<ul>
{items.map((item, index) => {
const itemId = `${baseId}-item-${index}`
const checked = selected.has(item.value)
return (
<li key={item.value}>
<label
data-slot="checkbox-tree-mixed-parent-item"
data-state={checked ? "checked" : "unchecked"}
className={cn(rowClass, itemClass)}
>
<input
type="checkbox"
id={itemId}
name={name}
value={item.value}
checked={checked}
disabled={disabled || item.disabled}
aria-labelledby={`${itemId}-label`}
aria-describedby={
item.description ? `${itemId}-description` : undefined
}
onChange={(event) =>
toggleItem(item.value, event.target.checked)
}
className="sr-only"
/>
<Box state={checked ? "checked" : "unchecked"} />
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
<span id={`${itemId}-label`} className="break-words">
{item.label}
</span>
{item.description ? (
<span
id={`${itemId}-description`}
className="break-words text-muted-foreground"
>
{item.description}
</span>
) : null}
</span>
</label>
</li>
)
})}
</ul>
)}
</div>
{invalid ? (
<p
id={errorId}
data-slot="checkbox-tree-mixed-parent-error"
className="mt-1.5 flex items-center gap-1.5 px-1.5 text-sm text-destructive"
>
<CircleAlert aria-hidden="true" className="size-3.5 shrink-0" />
{error}
</p>
) : null}
</div>
)
}
export { checkboxTreeMixedParentVariants }
The demo in the preview, 294 lines
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import {
CheckboxTreeMixedParent,
type CheckboxTreeItem,
} from "@/components/hazine/checkbox-tree-mixed-parent"
interface ScopeGroup {
id: string
label: string
description: string
items: CheckboxTreeItem[]
}
const SCOPE_GROUPS: ScopeGroup[] = [
{
id: "invoices",
label: "Invoices",
description: "Billing documents and their line items.",
items: [
{
value: "invoices:read",
label: "Read invoices",
description: "List, open and download as PDF.",
},
{ value: "invoices:write", label: "Create and edit drafts" },
{
value: "invoices:send",
label: "Send to customers",
description: "Emails the invoice and starts the payment term.",
},
{
value: "invoices:void",
label: "Void invoices",
description: "Cannot be undone once the period is closed.",
},
],
},
{
id: "customers",
label: "Customers",
description: "Contact records, tax details and notes.",
items: [
{ value: "customers:read", label: "Read customers" },
{ value: "customers:write", label: "Create and edit customers" },
{ value: "customers:merge", label: "Merge duplicates" },
],
},
{
id: "payouts",
label: "Payouts",
description: "Transfers from your balance to the bank.",
items: [
{ value: "payouts:read", label: "Read payouts" },
{ value: "payouts:schedule", label: "Change the payout schedule" },
{ value: "payouts:bank", label: "Change the bank account" },
],
},
]
const DEFAULT_SCOPES: Record<string, string[]> = {
invoices: ["invoices:read", "invoices:write"],
customers: ["customers:read", "customers:write", "customers:merge"],
payouts: [],
}
const TOTAL_SCOPES = SCOPE_GROUPS.reduce(
(sum, group) => sum + group.items.length,
0
)
function plural(count: number, one: string, many: string) {
return count === 1 ? one : many
}
export default function CheckboxTreeMixedParentDemo() {
const [scopes, setScopes] = React.useState(DEFAULT_SCOPES)
const granted = SCOPE_GROUPS.reduce(
(sum, group) => sum + (scopes[group.id]?.length ?? 0),
0
)
const breakdown = SCOPE_GROUPS.map(
(group) =>
`${scopes[group.id]?.length ?? 0} ${group.label.toLowerCase()}`
).join(" + ")
return (
<div className="flex w-lg max-w-full flex-col">
<p className="px-1.5 text-sm text-muted-foreground">
<span className="font-medium text-foreground">
Scopes for the Ledgerline sync token.
</span>{" "}
Grant only what the integration needs.
</p>
<div className="mt-4 divide-y divide-border border-y border-border">
{SCOPE_GROUPS.map((group) => (
<CheckboxTreeMixedParent
key={group.id}
label={group.label}
description={group.description}
items={group.items}
name="scopes"
value={scopes[group.id] ?? []}
onValueChange={(next) =>
setScopes((current) => ({ ...current, [group.id]: next }))
}
className="py-2"
/>
))}
</div>
<div className="mt-4 flex flex-wrap items-center justify-between gap-3 px-1.5">
<p role="status" className="text-sm text-muted-foreground">
<span className="font-medium text-foreground tabular-nums">
{granted} of {TOTAL_SCOPES}
</span>{" "}
{plural(TOTAL_SCOPES, "scope", "scopes")} granted
<span className="block text-xs tabular-nums">
{granted === 0 ? "A token needs at least one scope." : breakdown}
</span>
</p>
<Button type="button" disabled={granted === 0}>
{granted === 0
? "Create token"
: `Create token with ${granted} ${plural(granted, "scope", "scopes")}`}
</Button>
</div>
</div>
)
}
const EXPORT_COLUMNS: CheckboxTreeItem[] = [
{ value: "name", label: "Customer name" },
{ value: "email", label: "Billing email" },
{ value: "vat", label: "VAT number" },
{ value: "balance", label: "Open balance" },
{ value: "last-invoice", label: "Last invoice date" },
]
function InvalidScenario() {
const [columns, setColumns] = React.useState<string[]>([])
return (
<div className="flex w-sm max-w-full flex-col gap-3">
<p className="px-1.5 text-sm text-muted-foreground">
<span className="font-medium text-foreground">
Export customers to CSV.
</span>{" "}
Each checked field becomes a column.
</p>
<CheckboxTreeMixedParent
label="Customer fields"
items={EXPORT_COLUMNS}
name="columns"
density="compact"
value={columns}
onValueChange={setColumns}
error={
columns.length === 0
? "Choose at least one field. An export needs a column."
: undefined
}
/>
</div>
)
}
function DisabledScenario() {
const payouts = SCOPE_GROUPS[2]
return (
<div className="flex w-lg max-w-full flex-col gap-2">
<CheckboxTreeMixedParent
label={payouts.label}
description={payouts.description}
items={payouts.items}
defaultValue={["payouts:read"]}
disabled
/>
<p className="px-1.5 text-xs text-muted-foreground">
Only workspace owners can change payout scopes. Ask Ines Oyelaran to
update this token.
</p>
</div>
)
}
const LOCKED_ITEMS: CheckboxTreeItem[] = [
{
value: "invoices:read",
label: "Read invoices",
description: "Included with every token, so it cannot be turned off.",
disabled: true,
},
...SCOPE_GROUPS[0].items.slice(1),
]
function LockedItemScenario() {
return (
<div className="w-lg max-w-full">
<CheckboxTreeMixedParent
label="Invoices"
description="The parent sets the three scopes that can change."
items={LOCKED_ITEMS}
defaultValue={["invoices:read", "invoices:send"]}
/>
</div>
)
}
function LoadingScenario() {
return (
<div className="w-lg max-w-full">
<CheckboxTreeMixedParent
label="Custom fields"
description="Fields your workspace added to customer records."
items={[]}
loading
loadingLabel="Loading custom fields"
/>
</div>
)
}
function EmptyScenario() {
return (
<div className="w-lg max-w-full">
<CheckboxTreeMixedParent
label="Custom fields"
description="Fields your workspace added to customer records."
items={[]}
empty={
<>
No custom fields yet. Fields you add to customer records appear
here.{" "}
<a
href="#custom-fields"
className="inline-flex min-h-6 items-center rounded-sm font-medium text-foreground underline underline-offset-4 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground"
>
Add a custom field
</a>
</>
}
/>
</div>
)
}
const OVERFLOW_ITEMS: CheckboxTreeItem[] = [
{
value: "reports:revenue-recognition",
label:
"Deferred revenue recognition schedule by contract, entity and reporting currency",
description:
"Includes every amendment made after the original signature date, which can add several thousand rows for long contracts with monthly true-ups.",
},
{ value: "reports:aged-receivables", label: "Aged receivables, 30 to 120 days" },
{ value: "reports:aged-payables", label: "Aged payables, 30 to 120 days" },
{ value: "reports:vat-return", label: "VAT return working papers" },
{ value: "reports:intercompany", label: "Intercompany_eliminations_FY2026_consolidated_final" },
{ value: "reports:trial-balance", label: "Trial balance" },
{ value: "reports:cash-flow", label: "Cash flow, direct method" },
{ value: "reports:budget-variance", label: "Budget variance by cost centre" },
{ value: "reports:payroll-journal", label: "Payroll journal" },
{ value: "reports:fixed-assets", label: "Fixed asset register" },
{ value: "reports:audit-trail", label: "Audit trail" },
{ value: "reports:bank-reconciliation", label: "Bank reconciliation, all 14 accounts" },
{ value: "reports:credit-notes", label: "Credit notes issued" },
{ value: "reports:write-offs", label: "Write-offs awaiting approval" },
]
function OverflowScenario() {
return (
<div className="w-sm max-w-full">
<CheckboxTreeMixedParent
label="Finance reports shared with Thornbury Audit for the year end review"
description="External auditors see checked reports until Jan 31, 2027."
items={OVERFLOW_ITEMS}
density="compact"
defaultValue={OVERFLOW_ITEMS.slice(0, 9).map((item) => item.value)}
formatCount={(checked, total) => `${checked} of ${total} shared`}
/>
</div>
)
}
export const scenarios = {
invalid: InvalidScenario,
disabled: DisabledScenario,
"locked-item": LockedItemScenario,
loading: LoadingScenario,
empty: EmptyScenario,
overflow: OverflowScenario,
}
Props13
- labelrequired
- string
- Text of the parent checkbox. Also names the group of children.
- description
- string
- itemsrequired
- CheckboxTreeItem[]
- value
- string[]
- Values of the checked children.
- defaultValue
- string[]
- onValueChange
- (value: string[]) => void
- name
- string
- Form field name given to every child checkbox.
- disabled
- boolean = false
- loading
- boolean = false
- loadingLabel
- string = "Loading options"
- error
- React.ReactNode
- Validation message. Marks the parent invalid while present.
- empty
- React.ReactNode = "No options available."
- Shown in place of the children when `items` is empty.
- formatCount
- (checked: number, total: number) => string = defaultFormatCount
- Count at the end of the parent row, also announced after each change.
Also accepts every prop of Omit<React.ComponentProps<"div">, "defaultValue" | "onChange" | "children"> and VariantProps<typeof checkboxTreeMixedParentVariants>.
Accessibility
- Keyboard
Keyboard support for Checkbox Tree with Mixed Parent Key Effect Tab Moves to the parent checkbox, then to each enabled child in order Space on the parent Checks every enabled child, or clears them when all are already checked Space on a child Toggles that child and updates the parent to checked, unchecked or mixed - Screen reader
The parent is a button with role checkbox and aria-checked true, false or mixed, so the mixed state is correct before hydration. Children are native checkboxes in a group labelled by the parent, and the count describes the parent and repeats in a status region.
- Announces: {label}: {checked} of {total}
- Announces: Loading options
- Reduced motion
- Colour transitions only. The loading skeleton does not pulse.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies3
- @hazine/use-controllable-state
- lucide-react
- class-variance-authority
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.