# Checkbox

A control that allows the user to toggle between checked and not checked.

Source: https://webjs.dev/ui/docs/components/checkbox

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldGroupClass, fieldClass, fieldContentClass, fieldLabelClass,
  fieldTitleClass, fieldDescriptionClass,
} from '#components/ui/field.ts';
import { labelClass } from '#components/ui/label.ts';

export default function CheckboxDemo() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'max-w-sm')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox" name="terms-checkbox" class=${checkboxClass()}>
        <label data-slot="label" for="terms-checkbox" class=${labelClass()}>Accept terms and conditions</label>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-2" name="terms-checkbox-2" checked class=${checkboxClass()}>
        <div data-slot="field-content" class=${fieldContentClass()}>
          <label data-slot="field-label" for="terms-checkbox-2" class=${fieldLabelClass()}>
            Accept terms and conditions
          </label>
          <p data-slot="field-description" class=${fieldDescriptionClass()}>
            By clicking this checkbox, you agree to the terms.
          </p>
        </div>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" data-disabled="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="toggle-checkbox" name="toggle-checkbox" disabled class=${checkboxClass()}>
        <label data-slot="field-label" for="toggle-checkbox" class=${fieldLabelClass()}>Enable notifications</label>
      </div>
      <label data-slot="field-label" class=${fieldLabelClass()}>
        <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
          <input type="checkbox" data-slot="checkbox" id="toggle-checkbox-2" name="toggle-checkbox-2" class=${checkboxClass()}>
          <div data-slot="field-content" class=${fieldContentClass()}>
            <div data-slot="field-label" class=${fieldTitleClass()}>Enable notifications</div>
            <p data-slot="field-description" class=${fieldDescriptionClass()}>
              You can enable or disable notifications at any time.
            </p>
          </div>
        </div>
      </label>
    </div>
  `;
}
```

## Installation

```bash
npx @webjsdev/ui add checkbox
```

### Copy and paste the following code into your project.

````ts title="components/ui/checkbox.ts"
/**
 * Checkbox: styled native `<input type="checkbox">`. Tier-1 class
 * helper. Uses `appearance: none` + a masked `::before` for the checkmark
 * when `:checked`, so it remains a real form control
 * (participates in `<form>` submission, no ElementInternals required).
 *
 * shadcn parity:
 *   Checkbox  → checkboxClass()  (visual: size-4, rounded, primary fill
 *                                 when checked, inset shadow, focus ring;
 *                                 bypasses Radix)
 *
 * Design tokens used: --input, --primary, --primary-foreground, --background,
 * --ring, --destructive.
 *
 * A11y (required for accessible output):
 *   The tick is drawn by the class itself, so the checked state never reads as
 *   colour alone (WCAG 1.4.1), with or without JavaScript. Keep
 *   `data-slot="checkbox"` on the input, as every example here does, since the
 *   styles' field rules select on it.
 *   Associate a label with the input, either `<label for>` pointing at the
 *   input's `id` (as below) or by nesting the input inside the `<label>`. A
 *   checkbox with no label has no accessible name.
 *   Group related checkboxes in a `<fieldset>` with a `<legend>` naming the
 *   group, so the set is announced as one thing rather than N loose controls.
 *   Set `aria-invalid="true"` on a failed checkbox (the class styles it) and
 *   point `aria-describedby` at the element holding the error text.
 *   The indeterminate state is a PROPERTY, not an attribute
 *   (`el.indeterminate = true`). Do NOT add `aria-checked="mixed"` alongside it:
 *   the browser already maps a native checkbox's `indeterminate` to a mixed
 *   checked state, and hand-writing the ARIA duplicates a state the host
 *   language owns, which is discouraged precisely because the two can then
 *   disagree. Set the property and leave the ARIA alone.
 *
 * @example
 * ```html
 * <div class="flex items-center gap-2">
 *   <input type="checkbox" data-slot="checkbox" name="terms" id="terms" class=${checkboxClass()}>
 *   <label class=${labelClass()} for="terms">I accept the terms</label>
 * </div>
 *
 * <!-- A group of related checkboxes is named by its legend. -->
 * <fieldset class=${stackClass({ gap: 'sm' })}>
 *   <legend class=${fieldLabelClass()}>Email preferences</legend>
 *   <div class="flex items-center gap-2">
 *     <input type="checkbox" data-slot="checkbox" name="digest" id="pref-digest" class=${checkboxClass()}>
 *     <label class=${labelClass()} for="pref-digest">Weekly digest</label>
 *   </div>
 *   <div class="flex items-center gap-2">
 *     <input type="checkbox" data-slot="checkbox" name="security" id="pref-security" class=${checkboxClass()}>
 *     <label class=${labelClass()} for="pref-security">Security alerts</label>
 *   </div>
 * </fieldset>
 * ```
 */
import { cn } from '../lib/utils.ts';

// The checked and indeterminate paint rides the helper's own classes, so it is
// in the first paint, renders with JavaScript off, and holds in every style.
// The tick is shadcn's (Lucide's CheckIcon, stroke 2, round caps and joins),
// drawn by a `::before` that fills the box's padding box (14px of the 16px
// box, shadcn's size-3.5) in `currentColor` through a mask of the icon. So the
// tick takes the box's text colour, which every style sets on a checked box
// (`text-primary-foreground` on the `bg-primary` fill), and it flips with the
// theme with no per-theme rule. The indeterminate dash is the same fill
// masked to a centred bar, 60% across and 2px tall. The data URI is fully
// percent-encoded so it sits in a class with no space or quote.
// One literal, since Tailwind finds a class only where it is written out whole.
const CHECKBOX_CLASS =
  'size-4 appearance-none rounded-[4px] border border-input bg-transparent shadow-xs transition-shadow focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 checked:border-primary checked:bg-primary checked:bg-no-repeat checked:bg-center checked:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 peer relative shrink-0 outline-none after:absolute after:-inset-x-3 after:-inset-y-2 disabled:cursor-not-allowed disabled:opacity-50 checked:before:absolute checked:before:inset-0 checked:before:bg-current checked:before:[mask:url(data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20viewBox=%220%200%2024%2024%22%20fill=%22none%22%20stroke=%22%23000%22%20stroke-width=%222%22%20stroke-linecap=%22round%22%20stroke-linejoin=%22round%22%3E%3Cpath%20d=%22M20%206%209%2017l-5-5%22/%3E%3C/svg%3E)_center/contain_no-repeat] indeterminate:border-primary indeterminate:bg-primary indeterminate:text-primary-foreground indeterminate:before:absolute indeterminate:before:inset-0 indeterminate:before:bg-current indeterminate:before:[mask:linear-gradient(#000,#000)_center/60%_2px_no-repeat]';

/**
 * Tailwind classes for a styled native `<input type="checkbox">`. The classes
 * draw the tick and the indeterminate dash themselves, so a checked box paints
 * with JavaScript off. Keep `data-slot="checkbox"` on the input as shadcn
 * does: the styles' field rules select on it.
 */
export function checkboxClass(): string {
  return cn(CHECKBOX_CLASS);
}
````

### Update the import paths to match your project setup.

## Usage

```ts
import { checkboxClass } from '#components/ui/checkbox.ts';
```

```ts
<input type="checkbox" data-slot="checkbox" class=${checkboxClass()}>
```

## Checked State

The checkbox is a native `<input type="checkbox">`, so it keeps its own state. Use the `checked` attribute for the initial state, and read or set the `checked` property, listening for the `change` event, to follow it.

```ts
<input
  type="checkbox"
  data-slot="checkbox"
  checked
  class=${checkboxClass()}
  @change=${(e: Event) => this.onCheckedChange((e.target as HTMLInputElement).checked)}
>
```

## Invalid State

Set `aria-invalid` on the checkbox and `data-invalid` on the field wrapper to show the invalid styles.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function CheckboxInvalid() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-56')}>
      <div role="group" data-slot="field" data-orientation="horizontal" data-invalid="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input
          type="checkbox"
          data-slot="checkbox"
          id="terms-checkbox-invalid"
          name="terms-checkbox-invalid"
          aria-invalid="true"
          class=${checkboxClass()}
        >
        <label data-slot="field-label" for="terms-checkbox-invalid" class=${fieldLabelClass()}>
          Accept terms and conditions
        </label>
      </div>
    </div>
  `;
}
```

## Basic

Pair the checkbox with `fieldClass()` and `fieldLabelClass()` for proper layout and labeling.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function CheckboxBasic() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-56')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-basic" name="terms-checkbox-basic" class=${checkboxClass()}>
        <label data-slot="field-label" for="terms-checkbox-basic" class=${fieldLabelClass()}>
          Accept terms and conditions
        </label>
      </div>
    </div>
  `;
}
```

## Description

Use `fieldContentClass()` and `fieldDescriptionClass()` for helper text.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldGroupClass, fieldClass, fieldContentClass, fieldLabelClass, fieldDescriptionClass,
} from '#components/ui/field.ts';

export default function CheckboxDescription() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-72')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input
          type="checkbox"
          data-slot="checkbox"
          id="terms-checkbox-desc"
          name="terms-checkbox-desc"
          checked
          class=${checkboxClass()}
        >
        <div data-slot="field-content" class=${fieldContentClass()}>
          <label data-slot="field-label" for="terms-checkbox-desc" class=${fieldLabelClass()}>
            Accept terms and conditions
          </label>
          <p data-slot="field-description" class=${fieldDescriptionClass()}>
            By clicking this checkbox, you agree to the terms and conditions.
          </p>
        </div>
      </div>
    </div>
  `;
}
```

## Disabled

Use the `disabled` attribute to prevent interaction and add the `data-disabled` attribute to the field for disabled styles.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import { fieldGroupClass, fieldClass, fieldLabelClass } from '#components/ui/field.ts';

export default function CheckboxDisabled() {
  return html`
    <div data-slot="field-group" class=${cn(fieldGroupClass(), 'mx-auto w-56')}>
      <div role="group" data-slot="field" data-orientation="horizontal" data-disabled="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input
          type="checkbox"
          data-slot="checkbox"
          id="toggle-checkbox-disabled"
          name="toggle-checkbox-disabled"
          disabled
          class=${checkboxClass()}
        >
        <label data-slot="field-label" for="toggle-checkbox-disabled" class=${fieldLabelClass()}>
          Enable notifications
        </label>
      </div>
    </div>
  `;
}
```

## Group

Use multiple fields to create a checkbox list.

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldSetClass, fieldLegendClass, fieldDescriptionClass, fieldGroupClass, fieldClass, fieldLabelClass,
} from '#components/ui/field.ts';

const items = [
  { id: 'finder-pref-9k2-hard-disks-ljj-checkbox', label: 'Hard disks', checked: true },
  { id: 'finder-pref-9k2-external-disks-1yg-checkbox', label: 'External disks', checked: true },
  { id: 'finder-pref-9k2-cds-dvds-fzt-checkbox', label: 'CDs, DVDs, and iPods', checked: false },
  { id: 'finder-pref-9k2-connected-servers-6l2-checkbox', label: 'Connected servers', checked: false },
];

export default function CheckboxGroup() {
  return html`
    <fieldset data-slot="field-set" class=${fieldSetClass()}>
      <legend data-slot="field-legend" data-variant="label" class=${fieldLegendClass({ variant: 'label' })}>
        Show these items on the desktop:
      </legend>
      <p data-slot="field-description" class=${fieldDescriptionClass()}>
        Select the items you want to show on the desktop.
      </p>
      <div data-slot="field-group" class=${cn(fieldGroupClass(), 'gap-3')}>
        ${items.map((item) => html`
          <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
            <input type="checkbox" data-slot="checkbox" id=${item.id} name=${item.id} ?checked=${item.checked} class=${checkboxClass()}>
            <label data-slot="field-label" for=${item.id} class=${cn(fieldLabelClass(), 'font-normal')}>${item.label}</label>
          </div>
        `)}
      </div>
    </fieldset>
  `;
}
```

## Table

```ts
import { html, nothing } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  tableContainerClass, tableClass, tableHeaderClass, tableBodyClass,
  tableRowClass, tableHeadClass, tableCellClass,
} from '#components/ui/table.ts';

const tableData = [
  { id: '1', name: 'Sarah Chen', email: 'sarah.chen@example.com', role: 'Admin' },
  { id: '2', name: 'Marcus Rodriguez', email: 'marcus.rodriguez@example.com', role: 'User' },
  { id: '3', name: 'Priya Patel', email: 'priya.patel@example.com', role: 'User' },
  { id: '4', name: 'David Kim', email: 'david.kim@example.com', role: 'Editor' },
];

// The first row starts selected. data-state="selected" is what the row's
// selected style keys on, so it travels with the checked box.
const selected = new Set(['1']);

export default function CheckboxTable() {
  return html`
    <div data-slot="table-container" class=${tableContainerClass()}>
      <table data-slot="table" class=${tableClass()}>
        <thead data-slot="table-header" class=${tableHeaderClass()}>
          <tr data-slot="table-row" class=${tableRowClass()}>
            <th scope="col" data-slot="table-head" class=${cn(tableHeadClass(), 'w-8')}>
              <input
                type="checkbox"
                data-slot="checkbox"
                id="select-all-checkbox"
                name="select-all-checkbox"
                aria-label="Select all"
                ?checked=${selected.size === tableData.length}
                class=${checkboxClass()}
              >
            </th>
            <th scope="col" data-slot="table-head" class=${tableHeadClass()}>Name</th>
            <th scope="col" data-slot="table-head" class=${tableHeadClass()}>Email</th>
            <th scope="col" data-slot="table-head" class=${tableHeadClass()}>Role</th>
          </tr>
        </thead>
        <tbody data-slot="table-body" class=${tableBodyClass()}>
          ${tableData.map((row) => html`
            <tr data-slot="table-row" data-state=${selected.has(row.id) ? 'selected' : nothing} class=${tableRowClass()}>
              <td data-slot="table-cell" class=${tableCellClass()}>
                <input
                  type="checkbox"
                  data-slot="checkbox"
                  id=${`row-${row.id}-checkbox`}
                  name=${`row-${row.id}-checkbox`}
                  aria-label=${`Select ${row.name}`}
                  ?checked=${selected.has(row.id)}
                  class=${checkboxClass()}
                >
              </td>
              <td data-slot="table-cell" class=${cn(tableCellClass(), 'font-medium')}>${row.name}</td>
              <td data-slot="table-cell" class=${tableCellClass()}>${row.email}</td>
              <td data-slot="table-cell" class=${tableCellClass()}>${row.role}</td>
            </tr>
          `)}
        </tbody>
      </table>
    </div>
  `;
}
```

## RTL

To enable RTL support, see the [RTL configuration guide](https://webjs.dev/ui/docs/rtl).

```ts
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { checkboxClass } from '#components/ui/checkbox.ts';
import {
  fieldGroupClass, fieldClass, fieldContentClass, fieldLabelClass,
  fieldTitleClass, fieldDescriptionClass,
} from '#components/ui/field.ts';
import { labelClass } from '#components/ui/label.ts';

const translations = {
  en: {
    dir: 'ltr',
    values: {
      acceptTerms: 'Accept terms and conditions',
      acceptTermsDescription: 'By clicking this checkbox, you agree to the terms.',
      enableNotifications: 'Enable notifications',
      enableNotificationsDescription: 'You can enable or disable notifications at any time.',
    },
  },
  ar: {
    dir: 'rtl',
    values: {
      acceptTerms: 'قبول الشروط والأحكام',
      acceptTermsDescription: 'بالنقر على هذا المربع، فإنك توافق على الشروط.',
      enableNotifications: 'تفعيل الإشعارات',
      enableNotificationsDescription: 'يمكنك تفعيل أو إلغاء تفعيل الإشعارات في أي وقت.',
    },
  },
  he: {
    dir: 'rtl',
    values: {
      acceptTerms: 'קבל תנאים והגבלות',
      acceptTermsDescription: 'על ידי לחיצה על תיבת הסימון הזו, אתה מסכים לתנאים.',
      enableNotifications: 'הפעל התראות',
      enableNotificationsDescription: 'אתה יכול להפעיל או להשבית התראות בכל עת.',
    },
  },
};

// The provider is the dir attribute: every part styles itself with logical
// properties, so dir="rtl" on the group flips the whole layout.
export default function CheckboxRtl() {
  const lang = 'ar';
  const { dir, values: t } = translations[lang];

  return html`
    <div data-slot="field-group" dir=${dir} lang=${lang} class=${cn(fieldGroupClass(), 'max-w-sm')}>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-rtl" name="terms-checkbox" class=${checkboxClass()}>
        <label data-slot="label" for="terms-checkbox-rtl" class=${labelClass()}>${t.acceptTerms}</label>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="terms-checkbox-2-rtl" name="terms-checkbox-2" checked class=${checkboxClass()}>
        <div data-slot="field-content" class=${fieldContentClass()}>
          <label data-slot="field-label" for="terms-checkbox-2-rtl" class=${fieldLabelClass()}>${t.acceptTerms}</label>
          <p data-slot="field-description" class=${fieldDescriptionClass()}>${t.acceptTermsDescription}</p>
        </div>
      </div>
      <div role="group" data-slot="field" data-orientation="horizontal" data-disabled="true" class=${fieldClass({ orientation: 'horizontal' })}>
        <input type="checkbox" data-slot="checkbox" id="toggle-checkbox-rtl" name="toggle-checkbox" disabled class=${checkboxClass()}>
        <label data-slot="field-label" for="toggle-checkbox-rtl" class=${fieldLabelClass()}>${t.enableNotifications}</label>
      </div>
      <label data-slot="field-label" class=${fieldLabelClass()}>
        <div role="group" data-slot="field" data-orientation="horizontal" class=${fieldClass({ orientation: 'horizontal' })}>
          <input type="checkbox" data-slot="checkbox" id="toggle-checkbox-2-rtl" name="toggle-checkbox-2" class=${checkboxClass()}>
          <div data-slot="field-content" class=${fieldContentClass()}>
            <div data-slot="field-label" class=${fieldTitleClass()}>${t.enableNotifications}</div>
            <p data-slot="field-description" class=${fieldDescriptionClass()}>${t.enableNotificationsDescription}</p>
          </div>
        </div>
      </label>
    </div>
  `;
}
```

## API Reference

### checkboxClass

`checkboxClass()` returns the classes for a native `<input type="checkbox">` and takes no options. The checkbox is a real form control, so it submits with its `<form>` and supports every native attribute.

| Attribute | Type | Default |
| --- | --- | --- |
| `data-slot` | `"checkbox"` | required |
| `checked` | `boolean` | `false` |
| `disabled` | `boolean` | `false` |
| `required` | `boolean` | `false` |
| `name` | `string` | - |
| `value` | `string` | `"on"` |
| `aria-invalid` | `"true"` | - |

`data-slot="checkbox"` is required: the checkmark is drawn by a stylesheet keyed on it. The indeterminate state is the `indeterminate` property (`el.indeterminate = true`), not an attribute.
