# Checkbox

A controlled checkbox with a mixed state and a form value.

- Page: https://www.effectcn.com/components/checkbox
- Kind: Headless component with parts
- File: `src/ui/checkbox.ts`
- Built on: `Checkbox` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/checkbox.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/checkbox.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { Checkbox } from "@effect/ui-kit"
import { cn } from "#lib/cn"

type CheckboxParts = Component.Headless.Parts<typeof Checkbox>

interface ClassOption {
  readonly class?: string | undefined
}

/**
 * The box. Draw it inside the kit's `view` and put the indicator in it:
 * `CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox))`.
 */
export const CheckboxRoot = <Msg>(h: Html.H<Msg>, checkbox: CheckboxParts, options: ClassOption = {}) =>
  checkbox.root(
    h.button.class(cn(
      "inline-grid size-4 shrink-0 place-items-center rounded-xs border border-input bg-background p-0 " +
        "text-brand-foreground shadow-sm transition-colors duration-150 hover:border-muted-foreground " +
        "data-[checked]:border-brand data-[checked]:bg-brand " +
        "data-[indeterminate]:border-brand data-[indeterminate]:bg-brand " +
        "data-[readonly]:cursor-default data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
      options.class
    ))
  )

/** The tick, or a dash while the checkbox is indeterminate. Both are borders, so there is no icon to ship. */
export const CheckboxIndicator = <Msg>(h: Html.H<Msg>, checkbox: CheckboxParts, options: ClassOption = {}) =>
  checkbox.indicator(
    h.span.class(cn(
      "-mt-0.5 h-[5px] w-[9px] -rotate-45 border-b-[1.5px] border-l-[1.5px] border-current " +
        "data-[unchecked]:hidden " +
        "data-[indeterminate]:mt-0 data-[indeterminate]:h-0 data-[indeterminate]:w-2 " +
        "data-[indeterminate]:rotate-0 data-[indeterminate]:border-l-0",
      options.class
    ))
  )

/** A label for the checkbox: around the root, or beside it with `for`. It dims with a disabled checkbox inside it. */
export const CheckboxLabel = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.label.class(cn(
    "inline-flex cursor-pointer items-center gap-2 text-[13px] leading-4 font-medium select-none " +
      "has-[[data-disabled]]:cursor-not-allowed has-[[data-disabled]]:text-muted-foreground",
    options.class
  ))
```

```ts
import { CheckboxRoot, CheckboxIndicator, CheckboxLabel } from "#ui/checkbox"
```

## Usage

A label around the root names the checkbox and toggles it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Checkbox } from "@effect/ui-kit"
import { Schema } from "effect"
import { CheckboxIndicator, CheckboxLabel, CheckboxRoot } from "#ui/checkbox"

const CheckboxBasicMessage = UiSchema.TaggedEnum({ ToggledTerms: { checked: Schema.Boolean } })

export const CheckboxBasic = Html.component({
  name: "CheckboxBasic",
  model: Schema.Struct({ terms: Schema.Boolean }),
  message: CheckboxBasicMessage
}).make({
  init: () => ({ terms: false }),
  update: {
    ToggledTerms: ($, { checked }) => $.evolve({ terms: checked })
  },
  view: (h, model) =>
    Checkbox(h, {
      props: { checked: model.terms },
      onEmit: { Toggled: ({ checked }) => CheckboxBasicMessage.ToggledTerms({ checked }) },
      view: (checkbox) =>
        CheckboxLabel(h).children(
          CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox)),
          "Accept terms and conditions"
        )
    })
})
```

## Examples

### With description

A label that points at the root's id, and a description beside it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Checkbox } from "@effect/ui-kit"
import { Schema } from "effect"
import { CheckboxIndicator, CheckboxLabel, CheckboxRoot } from "#ui/checkbox"

const CheckboxWithDescriptionMessage = UiSchema.TaggedEnum({
  ToggledUpdates: { checked: Schema.Boolean }
})

export const CheckboxWithDescription = Html.component({
  name: "CheckboxWithDescription",
  model: Schema.Struct({ updates: Schema.Boolean }),
  message: CheckboxWithDescriptionMessage
}).make({
  init: () => ({ updates: true }),
  update: {
    ToggledUpdates: ($, { checked }) => $.evolve({ updates: checked })
  },
  view: (h, model) =>
    Checkbox(h, {
      props: { checked: model.updates, id: "checkbox-updates" },
      onEmit: { Toggled: ({ checked }) => CheckboxWithDescriptionMessage.ToggledUpdates({ checked }) },
      view: (checkbox) =>
        h.div.class("flex max-w-xs items-start gap-2.5").children(
          CheckboxRoot(h, checkbox)
            .attr("aria-describedby", "checkbox-updates-description")
            .children(CheckboxIndicator(h, checkbox)),
          h.div.class("grid gap-1").children(
            CheckboxLabel(h).attr("for", "checkbox-updates").children("Product updates"),
            h.p.class("text-[13px] text-muted-foreground").attr("id", "checkbox-updates-description").children(
              "A short email when we ship something new. No more than one a month."
            )
          )
        )
    })
})
```

### Indeterminate

A select-all checkbox that is mixed while only some rows are ticked.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Checkbox } from "@effect/ui-kit"
import { Schema } from "effect"
import { CheckboxIndicator, CheckboxLabel, CheckboxRoot } from "#ui/checkbox"

const CheckboxIndeterminateMessage = UiSchema.TaggedEnum({
  ToggledAll: { checked: Schema.Boolean },
  ToggledFile: { file: Schema.String, checked: Schema.Boolean }
})

const files = ["report.pdf", "budget.xlsx", "notes.md"]

export const CheckboxIndeterminate = Html.component({
  name: "CheckboxIndeterminate",
  model: Schema.Struct({ selected: Schema.Array(Schema.String) }),
  message: CheckboxIndeterminateMessage
}).make({
  init: () => ({ selected: ["report.pdf"] }),
  update: {
    ToggledAll: ($, { checked }) => $.evolve({ selected: checked ? files : [] }),
    ToggledFile: ($, { checked, file }) =>
      $.evolve({
        selected: (selected) =>
          checked ? [...selected, file] : selected.filter((other) => other !== file)
      })
  },
  view: (h, model) => {
    const all = model.selected.length === files.length
    const some = model.selected.length > 0 && !all

    return h.div.class("flex flex-col items-start gap-3.5").children(
      // A click on a mixed checkbox emits the opposite of `checked`, here true.
      Checkbox(h, {
        key: "all",
        props: { checked: all, indeterminate: some },
        onEmit: { Toggled: ({ checked }) => CheckboxIndeterminateMessage.ToggledAll({ checked }) },
        view: (checkbox) =>
          CheckboxLabel(h).children(
            CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox)),
            "Select all files"
          )
      }),
      h.div.class("flex flex-col items-start gap-2.5 pl-6").children(
        files.map((file) =>
          Checkbox(h, {
            key: file,
            props: { checked: model.selected.includes(file) },
            onEmit: {
              Toggled: ({ checked }) => CheckboxIndeterminateMessage.ToggledFile({ file, checked })
            },
            view: (checkbox) =>
              CheckboxLabel(h, { class: "font-normal" }).children(
                CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox)),
                file
              )
          })
        )
      ),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(`${model.selected.length} of ${files.length} selected`)
    )
  }
})
```

### Disabled and read-only

A disabled checkbox leaves the tab order. A read-only one keeps focus and ignores clicks.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Checkbox } from "@effect/ui-kit"
import { Schema } from "effect"
import { CheckboxIndicator, CheckboxLabel, CheckboxRoot } from "#ui/checkbox"

const CheckboxDisabledMessage = UiSchema.TaggedEnum({
  ToggledCheckbox: { checked: Schema.Boolean }
})

const states = [
  { key: "disabled", label: "Disabled", props: { checked: false, disabled: true } },
  { key: "disabled-checked", label: "Disabled and checked", props: { checked: true, disabled: true } },
  { key: "read-only", label: "Read-only, still focusable", props: { checked: true, readOnly: true } }
]

export const CheckboxDisabled = Html.component({
  name: "CheckboxDisabled",
  model: Schema.Struct({ toggles: Schema.Number }),
  message: CheckboxDisabledMessage
}).make({
  init: () => ({ toggles: 0 }),
  update: {
    ToggledCheckbox: ($) => $.evolve({ toggles: (toggles) => toggles + 1 })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-start gap-3.5").children(
      states.map(({ key, label, props }) =>
        Checkbox(h, {
          key,
          props,
          onEmit: { Toggled: ({ checked }) => CheckboxDisabledMessage.ToggledCheckbox({ checked }) },
          view: (checkbox) =>
            CheckboxLabel(h).children(
              CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox)),
              label
            )
        })
      ),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(`Toggled ${model.toggles} times`)
    )
})
```

### Card

The whole card is the label, styled from the checkbox inside it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Checkbox } from "@effect/ui-kit"
import { Schema } from "effect"
import { CheckboxIndicator, CheckboxRoot } from "#ui/checkbox"

const CheckboxCardMessage = UiSchema.TaggedEnum({
  ToggledAddOn: { addOn: Schema.String, checked: Schema.Boolean }
})

const addOns = [
  { value: "backups", label: "Daily backups", description: "Kept for 30 days, restored in one click." },
  { value: "analytics", label: "Analytics", description: "Traffic and conversion reports for every page." },
  { value: "support", label: "Priority support", description: "An answer within four working hours." }
]

export const CheckboxCard = Html.component({
  name: "CheckboxCard",
  model: Schema.Struct({ addOns: Schema.Array(Schema.String) }),
  message: CheckboxCardMessage
}).make({
  init: () => ({ addOns: ["backups"] }),
  update: {
    ToggledAddOn: ($, { addOn, checked }) =>
      $.evolve({
        addOns: (current) =>
          checked ? [...current, addOn] : current.filter((other) => other !== addOn)
      })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-2.5").children(
      addOns.map(({ description, label, value }) =>
        Checkbox(h, {
          key: value,
          props: { checked: model.addOns.includes(value) },
          onEmit: {
            Toggled: ({ checked }) => CheckboxCardMessage.ToggledAddOn({ addOn: value, checked })
          },
          view: (checkbox) =>
            h.label
              .class(
                "flex cursor-pointer items-start gap-2.5 rounded-md border bg-card px-3.5 py-3 transition-colors duration-150 select-none hover:bg-accent has-[[data-checked]]:border-brand has-[[data-checked]]:bg-brand-wash"
              ).children(
              CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox)),
              h.span.class("grid gap-1").children(
                h.span.class("text-[13px] leading-4 font-medium").children(label),
                h.span.class("text-[13px] text-muted-foreground").children(description)
              )
            )
        })
      )
    )
})
```

### In a form

The root carries a hidden input, so the form submits name and value.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Checkbox } from "@effect/ui-kit"
import { Schema } from "effect"
import { CheckboxIndicator, CheckboxLabel, CheckboxRoot } from "#ui/checkbox"
import { Button } from "#ui/button"

const CheckboxFormMessage = UiSchema.TaggedEnum({
  ToggledTerms: { checked: Schema.Boolean },
  ToggledNewsletter: { checked: Schema.Boolean },
  SubmittedForm: { fields: Schema.Record(Schema.String, Schema.String) }
})

export const CheckboxForm = Html.component({
  name: "CheckboxForm",
  model: Schema.Struct({
    terms: Schema.Boolean,
    newsletter: Schema.Boolean,
    submitted: Schema.NullOr(Schema.String)
  }),
  message: CheckboxFormMessage
}).make({
  init: () => ({ terms: false, newsletter: true, submitted: null }),
  update: {
    ToggledTerms: ($, { checked }) => $.evolve({ terms: checked }),
    ToggledNewsletter: ($, { checked }) => $.evolve({ newsletter: checked }),
    SubmittedForm: ($, { fields }) => $.evolve({ submitted: JSON.stringify(fields) })
  },
  view: (h, model) =>
    h.form
      .class("flex flex-col items-start gap-3.5")
      .on("submit", ({ fields }) => CheckboxFormMessage.SubmittedForm({ fields }))
      .children(
        Checkbox(h, {
          key: "terms",
          props: { checked: model.terms, name: "terms", required: true },
          onEmit: { Toggled: ({ checked }) => CheckboxFormMessage.ToggledTerms({ checked }) },
          view: (checkbox) =>
            CheckboxLabel(h).children(
              CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox)),
              "I accept the terms"
            )
        }),
        // An unticked checkbox submits nothing unless it has an uncheckedValue.
        Checkbox(h, {
          key: "newsletter",
          props: { checked: model.newsletter, name: "newsletter", value: "yes", uncheckedValue: "no" },
          onEmit: { Toggled: ({ checked }) => CheckboxFormMessage.ToggledNewsletter({ checked }) },
          view: (checkbox) =>
            CheckboxLabel(h).children(
              CheckboxRoot(h, checkbox).children(CheckboxIndicator(h, checkbox)),
              "Send me the newsletter"
            )
        }),
        // `required` doesn't block the submit, so the button waits for the terms.
        Button(h, { size: "sm", props: { type: "submit", disabled: !model.terms } })
          .children("Create account"),
        h.p.class("text-xs text-muted-foreground tabular-nums").children(
          model.submitted === null ? "Nothing submitted yet" : `Submitted ${model.submitted}`
        )
      )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `root` | The <button role="checkbox">. It appends the hidden input when there is a value to submit. |
| `indicator` | A <span> inside the root for the tick. It stays in the DOM, so hide it with [data-unchecked]. |
| `checked, indeterminate, disabled, readOnly, required` | The state resolved to booleans, for markup that depends on it. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `checked` | `boolean` | Whether the checkbox is ticked. Unticked when left out. |
| `indeterminate` | `boolean` | Shows neither state, with aria-checked="mixed". A click still emits the opposite of checked. |
| `disabled` | `boolean` | Sets the native disabled attribute: skipped by Tab, ignores clicks. |
| `readOnly` | `boolean` | Ignores clicks but stays focusable. |
| `required` | `boolean` | Sets aria-required and data-required. It doesn't block a submit. |
| `name` | `string` | The form field's name. Without it nothing is submitted. |
| `value` | `string` | What a ticked checkbox submits, "on" by default. Inside a CheckboxGroup it makes the checkbox a member. |
| `uncheckedValue` | `string` | What an unticked checkbox submits. Nothing when unset. |
| `parent` | `boolean` | Makes the checkbox the parent of the CheckboxGroup around it. |
| `id` | `string` | The root's id, for a label's for attribute. |

### Events

| Event | Description |
| --- | --- |
| `Toggled` | { checked }: the value the user asked for. Store it and pass it back as checked. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-checked` | On root and indicator while ticked. |
| `data-unchecked` | On root and indicator while unticked. Neither is present while indeterminate. |
| `data-indeterminate` | On root and indicator while mixed. |
| `data-disabled` | On root and indicator while disabled. |
| `data-readonly` | On root and indicator while read-only. |
| `data-required` | On root and indicator while required. |
| `data-parent` | On the root of a group's parent checkbox. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
