# Checkbox

选择一个或多个选项，可以单独选，也可以成组选。

用复选框表示一个可以勾选或取消勾选的选项。几个选项属于同一个值时，用分组。

```ts title="basic.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <label data-slot="label">
      <ui-checkbox>
        <ui-checkbox-indicator>
          ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
        </ui-checkbox-indicator>
      </ui-checkbox>
      Accept terms and conditions
    </label>
  `
}

export { mount }
```

点击复选框或它的标签，或聚焦它后按 Space，接受条款。

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

导入组件来注册它的元素。这个 import 在服务器上是安全的。

```ts
import "@ui-sdk/web/checkbox"
```

## 组合
用下面的组合构建一个 `ui-checkbox`：

```text
ui-checkbox
└── ui-checkbox-indicator
```

把复选框和它的文字包在一个 label 里。复选框已勾选或处于混合状态时，指示器会显示。

## 用法
导入部件并把它们组合起来：

```html
<script type="module">
  import "@ui-sdk/web/checkbox"
</script>

<label>
  <ui-checkbox>
    <ui-checkbox-indicator aria-hidden="true">✓</ui-checkbox-indicator>
  </ui-checkbox>
  Accept terms and conditions
</label>
```

## 描述
选项需要更多说明时，用 `ui-field-label` 和 `ui-field-description`。字段会把标签和描述都连接到复选框。

```ts title="description.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-checkbox>
        <ui-checkbox-indicator>
          ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
        </ui-checkbox-indicator>
      </ui-checkbox>
      <div data-slot="stack">
        <ui-field-label>Accept terms and conditions</ui-field-label>
        <ui-field-description>
          By clicking this checkbox, you agree to the terms and conditions.
        </ui-field-description>
      </div>
    </ui-field>
  `
}

export { mount }
```

点击 Accept terms and conditions。字段把标签和描述连接到复选框。

## 禁用
`disabled` 阻止聚焦和更改，并让复选框不参与表单提交。禁用的 `fieldset` 也一样。

```ts title="disabled.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <label data-slot="label">
        <ui-checkbox default-checked>
          <ui-checkbox-indicator>
            ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
          </ui-checkbox-indicator>
        </ui-checkbox>
        Product updates
      </label>
      <label data-slot="label">
        <ui-checkbox default-checked disabled>
          <ui-checkbox-indicator>
            ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
          </ui-checkbox-indicator>
        </ui-checkbox>
        Security alerts
      </label>
    </div>
  `
}

export { mount }
```

Security alerts 始终开启，所以那个复选框处于禁用状态。点击它的标签不会改变勾选状态。

## 只读
`read-only` 让复选框保持可聚焦并参与表单提交，同时阻止用户更改它。

```ts title="read-only.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-checkbox name="two-factor" default-checked read-only>
        <ui-checkbox-indicator>
          ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
        </ui-checkbox-indicator>
      </ui-checkbox>
      <div data-slot="stack">
        <ui-field-label>Require two-factor authentication</ui-field-label>
        <ui-field-description>
          Your organization requires this setting.
        </ui-field-description>
      </div>
    </ui-field>
  `
}

export { mount }
```

按 Tab 到达已勾选的复选框。按 Space 或点击都不会改变这个设置。

## 不确定
不确定的复选框表示一个部分勾选的集合。它有 `aria-checked="mixed"` 和 `data-indeterminate`。按压会勾选它；只有你的代码能把它放回混合状态。

从 `default-checked="indeterminate"` 开始，或把 `"indeterminate"` 作为受控值传入。指示器的 `data-indeterminate` 告诉它该显示哪个图标。[父复选框](https://ui-sdk.cn/docs/web-components/components/checkbox#parent-checkbox)会替你从分组推导这个状态。

```html
<ui-checkbox default-checked="indeterminate">
  <ui-checkbox-indicator aria-hidden="true">–</ui-checkbox-indicator>
</ui-checkbox>

<script type="module">
  import "@ui-sdk/web/checkbox"

  const indicator = document.querySelector("ui-checkbox-indicator")
  new MutationObserver(() => {
    indicator.textContent = indicator.hasAttribute("data-indeterminate")
      ? "–"
      : "✓"
  }).observe(indicator, { attributeFilter: ["data-indeterminate"] })
</script>
```

## 受控
读取或设置元素的 `checked` property，并监听 `checkedchange`。它的 `api` property 是一个[控制器](https://ui-sdk.cn/docs/web-components/components/checkbox#checkbox-controller)，可以从任何地方更改它，比如下面的 Toggle 按钮。

```ts title="controlled.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Toggle</button>
      </div>
      <label data-slot="label">
        <ui-checkbox>
          <ui-checkbox-indicator>
            ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
          </ui-checkbox-indicator>
        </ui-checkbox>
        Email me about product updates
      </label>
    </div>
  `
  const updates = root.querySelector("ui-checkbox")!
  root
    .querySelector("[data-slot=controls] button")!
    .addEventListener("click", () => updates.api.toggle())
  updates.addEventListener("checkedchange", (event) => {
    const { value, reason } = event.detail
    log(
      root,
      `${value === "indeterminate" ? "Mixed" : value ? "Checked" : "Unchecked"} (${reason})`
    )
  })
}

export { mount }
```

更改复选框，或按 Toggle。控制台会记录每次变更及其原因。

## 表单
设置 `name` 和 `value`，让已勾选的复选框进入原生表单。未勾选和混合状态的复选框不提交任何内容。默认值是 `"on"`。独立的复选框可以共用一个 `name` 来提交多个值；应用还需要一份已勾选值的列表时，用[分组](https://ui-sdk.cn/docs/web-components/components/checkbox#group)。

`required` 会阻止提交，直到复选框被勾选。Reset 会把它恢复到 `default-checked`。把 `form` 设为表单的 id，就能从页面其他地方加入该表单。

```ts title="form.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field>
        <ui-checkbox name="terms" value="yes" required>
          <ui-checkbox-indicator>
            ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
          </ui-checkbox-indicator>
        </ui-checkbox>
        <div data-slot="stack">
          <ui-field-label>Accept terms and conditions</ui-field-label>
          <ui-field-description>You agree to our Terms of Service and Privacy Policy.</ui-field-description>
        </div>
      </ui-field>
      <ui-field>
        <ui-checkbox name="newsletter" value="weekly" default-checked>
          <ui-checkbox-indicator>
            ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
          </ui-checkbox-indicator>
        </ui-checkbox>
        <div data-slot="stack">
          <ui-field-label>Send me the weekly newsletter</ui-field-label>
          <ui-field-description>Product news and tips, once a week. Unsubscribe anytime.</ui-field-description>
        </div>
      </ui-field>
      <div data-slot="row">
        <button type="submit">Create Account</button>
        <button type="reset">Reset</button>
      </div>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    const entries = [...new FormData(form)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(
      root,
      entries.length ? `Submitted ${entries.join("&")}` : "Submitted nothing"
    )
  })
}

export { mount }
```

在条款未勾选的情况下创建账户，查看原生校验，然后接受条款并重试。控制台会记录提交的内容，Reset 会恢复默认值。

## 分组
`ui-checkbox-group` 维护一份已勾选值的列表。每个复选框提供它的 `value`；分组按复选框出现的顺序返回选中的值。用 `aria-label`、`aria-labelledby` 或 [field](https://ui-sdk.cn/docs/web-components/components/checkbox#group-in-a-form) 为分组命名。

```ts title="group.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"

const toppings = [
  { value: "cheese", label: "Cheese" },
  { value: "mushrooms", label: "Mushrooms" },
  { value: "olives", label: "Olives" },
  { value: "peppers", label: "Peppers" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <h3 id="basic-toppings">Toppings</h3>
      <ui-checkbox-group aria-labelledby="basic-toppings" default-value="cheese">
        ${toppings
          .map(
            (topping) => `
              <label data-slot="label">
                <ui-checkbox value="${topping.value}">
                  <ui-checkbox-indicator>
                    ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                  </ui-checkbox-indicator>
                </ui-checkbox>
                ${topping.label}
              </label>
            `
          )
          .join("")}
      </ui-checkbox-group>
    </div>
  `
}

export { mount }
```

选择多种配料。分组维护一份已勾选值的列表。

## 父复选框
添加一个带 `parent` 的复选框，用来勾选或取消勾选整个分组。所有值都选中时它处于勾选状态，一个都没有时处于未勾选状态，其余情况为混合状态。它用 `aria-controls` 指向子复选框，自身不提交任何内容。

把 `all-values` 传给分组，让父复选框在首次渲染时就有正确的状态，在服务器上也是如此。否则它要等复选框挂载后才能发现这些值。

```ts title="group-parent.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement, Minus } from "lucide"

const toppings = [
  { value: "cheese", label: "Cheese" },
  { value: "mushrooms", label: "Mushrooms" },
  { value: "olives", label: "Olives" },
  { value: "peppers", label: "Peppers" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <h3 id="parent-toppings">Toppings</h3>
      <ui-checkbox-group
        aria-labelledby="parent-toppings"
        default-value="cheese,olives"
        all-values="${toppings.map((topping) => topping.value).join(",")}"
      >
        <label data-slot="label">
          <ui-checkbox parent>
            <ui-checkbox-indicator>
              ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </ui-checkbox-indicator>
          </ui-checkbox>
          Select all
        </label>
        <div data-slot="stack">
          ${toppings
            .map(
              (topping) => `
                <label data-slot="label">
                  <ui-checkbox value="${topping.value}">
                    <ui-checkbox-indicator>
                      ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                    </ui-checkbox-indicator>
                  </ui-checkbox>
                  ${topping.label}
                </label>
              `
            )
            .join("")}
        </div>
      </ui-checkbox-group>
    </div>
  `
}

export { mount }
```

Select all 会勾选每一种配料。取消勾选一种配料，Select all 就进入混合状态。

## 禁用的分组
禁用分组可以锁定每个复选框，或者禁用一个子项，只固定那个值。父复选框只会更改启用的子项。

```ts title="group-disabled.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement, Minus } from "lucide"

const backups = [
  { value: "photos", label: "Photos" },
  { value: "documents", label: "Documents" },
  { value: "messages", label: "Messages" },
]

const folders = [
  { value: "desktop", label: "Desktop", disabled: true },
  { value: "projects", label: "Projects", disabled: false },
  { value: "downloads", label: "Downloads", disabled: false },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="stack">
        <h3 id="disabled-backups">Backups</h3>
        <p data-slot="hint">Managed by your organization.</p>
        <ui-checkbox-group aria-labelledby="disabled-backups" default-value="photos,documents" disabled>
          ${backups
            .map(
              (item) => `
                <label data-slot="label">
                  <ui-checkbox value="${item.value}">
                    <ui-checkbox-indicator>
                      ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                    </ui-checkbox-indicator>
                  </ui-checkbox>
                  ${item.label}
                </label>
              `
            )
            .join("")}
        </ui-checkbox-group>
      </div>
      <div data-slot="stack">
        <h3 id="disabled-folders">Sync folders</h3>
        <ui-checkbox-group
          aria-labelledby="disabled-folders"
          default-value="desktop"
          all-values="${folders.map((item) => item.value).join(",")}"
        >
          <label data-slot="label">
            <ui-checkbox parent>
              <ui-checkbox-indicator>
                ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
              </ui-checkbox-indicator>
            </ui-checkbox>
            Select all
          </label>
          <div data-slot="stack">
            ${folders
              .map(
                (item) => `
                  <label data-slot="label">
                    <ui-checkbox value="${item.value}"${item.disabled ? " disabled" : ""}>
                      <ui-checkbox-indicator>
                        ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                      </ui-checkbox-indicator>
                    </ui-checkbox>
                    ${item.label}
                  </label>
                `
              )
              .join("")}
          </div>
        </ui-checkbox-group>
      </div>
    </div>
  `
}

export { mount }
```

Backups 分组已禁用。在 Sync folders 中，Select all 会更改启用的文件夹，而 Desktop 保持勾选。

## 受控的分组
读取或设置分组元素的 `value` property，并监听 `valuechange`。它的 `api` property 是一个[控制器](https://ui-sdk.cn/docs/web-components/components/checkbox#checkboxgroup-controller)，可以替换这份列表，就像下面的 Select Weekdays 和 Clear 那样。

```ts title="group-controlled.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"
import { log } from "./log"

const days = [
  { value: "mon", label: "Monday" },
  { value: "tue", label: "Tuesday" },
  { value: "wed", label: "Wednesday" },
  { value: "thu", label: "Thursday" },
  { value: "fri", label: "Friday" },
  { value: "sat", label: "Saturday" },
  { value: "sun", label: "Sunday" },
]

const weekdays = ["mon", "tue", "wed", "thu", "fri"]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-action="weekdays">Select Weekdays</button>
        <button type="button" data-action="clear">Clear</button>
      </div>
      <h3 id="controlled-days">Working days</h3>
      <ui-checkbox-group aria-labelledby="controlled-days" default-value="mon,tue">
        ${days
          .map(
            (day) => `
              <label data-slot="label">
                <ui-checkbox value="${day.value}">
                  <ui-checkbox-indicator>
                    ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                  </ui-checkbox-indicator>
                </ui-checkbox>
                ${day.label}
              </label>
            `
          )
          .join("")}
      </ui-checkbox-group>
    </div>
  `
  const schedule = root.querySelector("ui-checkbox-group")!
  root
    .querySelector('[data-action="weekdays"]')!
    .addEventListener("click", () => schedule.api.setValue(weekdays))
  root
    .querySelector('[data-action="clear"]')!
    .addEventListener("click", () => schedule.api.setValue([]))
  schedule.addEventListener("valuechange", (event) => {
    const { value, reason } = event.detail
    const names = days
      .filter((day) => value.includes(day.value))
      .map((day) => day.label)
    log(root, `${names.join(", ") || "No days"} (${reason})`)
  })
}

export { mount }
```

选择工作日，或按 Select Weekdays 或 Clear。控制台会记录分组的值以及变更原因。

## 表单中的分组
在分组上设置 `name`，把每个已勾选的值都以该 name 提交。`required` 要求至少选择一项，Reset 会恢复 `default-value`。`disabled` 和 `form` 选项与单个复选框相同。

在字段中，字段提供分组的标签和描述，`ui-field-error` 会在选择让分组通过校验之前就地显示校验消息。[表单与校验](/docs/web-components/forms)涵盖了共用的字段行为。

```ts title="group-field.ts"
import "@ui-sdk/web/checkbox"
import "@ui-sdk/web/field"
import { Check, createElement } from "lucide"
import { log } from "./log"

const channels = [
  { value: "email", label: "Email" },
  { value: "sms", label: "SMS" },
  { value: "push", label: "Push notifications" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field>
        <ui-field-label>Notifications</ui-field-label>
        <ui-field-description>Choose how we tell you about your orders.</ui-field-description>
        <ui-checkbox-group name="notifications" required>
          ${channels
            .map(
              (channel) => `
                <label data-slot="label">
                  <ui-checkbox value="${channel.value}">
                    <ui-checkbox-indicator>
                      ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                    </ui-checkbox-indicator>
                  </ui-checkbox>
                  ${channel.label}
                </label>
              `
            )
            .join("")}
        </ui-checkbox-group>
        <div>
          <ui-field-error>Choose at least one way to be notified.</ui-field-error>
        </div>
      </ui-field>
      <button type="submit">Save</button>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    const entries = [...new FormData(form)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(root, `Saved ${entries.join("&")}`)
  })
}

export { mount }
```

什么都不勾选就 Save，查看就地显示的错误。选择一种通知方式并保存；控制台会记录提交的值。

## 表格
同一个父复选框可以从表格表头中选择行。每一行提供它的值和无障碍名称。

```ts title="table.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement, Minus } from "lucide"
import { log } from "./log"

const people = [
  {
    id: "hollis",
    name: "Hollis Grant",
    email: "hollis@example.com",
    role: "Owner",
  },
  {
    id: "ines",
    name: "Inès Moreau",
    email: "ines@example.com",
    role: "Editor",
  },
  {
    id: "kofi",
    name: "Kofi Mensah",
    email: "kofi@example.com",
    role: "Viewer",
  },
  {
    id: "wren",
    name: "Wren Takahashi",
    email: "wren@example.com",
    role: "Editor",
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-checkbox-group aria-label="Team members" default-value="hollis" all-values="${people.map((person) => person.id).join(",")}">
      <table>
        <caption data-slot="visually-hidden">Team members</caption>
        <thead>
          <tr>
            <th>
              <ui-checkbox aria-label="Select all" parent>
                <ui-checkbox-indicator>
                  ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                  ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
                </ui-checkbox-indicator>
              </ui-checkbox>
            </th>
            <th>Name</th>
            <th>Email</th>
            <th>Role</th>
          </tr>
        </thead>
        <tbody>
          ${people
            .map(
              (person) => `
                <tr>
                  <td>
                    <ui-checkbox value="${person.id}" aria-label="Select ${person.name}">
                      <ui-checkbox-indicator>
                        ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                      </ui-checkbox-indicator>
                    </ui-checkbox>
                  </td>
                  <td>${person.name}</td>
                  <td>${person.email}</td>
                  <td>${person.role}</td>
                </tr>
              `
            )
            .join("")}
        </tbody>
      </table>
    </ui-checkbox-group>
  `
  root
    .querySelector("ui-checkbox-group")!
    .addEventListener("valuechange", (event) => {
      log(root, `${event.detail.value.length} of ${people.length} selected`)
    })
}

export { mount }
```

逐行选择，或使用表头里的 Select all。控制台会记录选中的行数。

## 动画
指示器出现时带有 `data-starting-style`，离开时带有 `data-ending-style`，并保持挂载直到退场结束。从这些状态过渡：

```css
[data-slot="checkbox-indicator"] {
  transition:
    opacity 0.15s,
    scale 0.15s;

  &:is([data-starting-style], [data-ending-style]) {
    opacity: 0;
    scale: 0.5;
  }
}
```

`keep-mounted` 让指示器在未勾选时也留在页面中，并带有 `data-unchecked`，用于同时展示两种状态的样式。

```ts title="indicator.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement } from "lucide"

const tasks = [
  { label: "Write the release notes", done: false },
  { label: "Update the changelog", done: true },
  { label: "Tag the release", done: false },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      ${tasks
        .map(
          (task) => `
            <label data-slot="label">
              <ui-checkbox${task.done ? " default-checked" : ""}>
                <ui-checkbox-indicator>
                  ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
                </ui-checkbox-indicator>
              </ui-checkbox>
              ${task.label}
            </label>
          `
        )
        .join("")}
    </div>
  `
}

export { mount }
```

勾选再取消勾选一个任务。对勾会缩放并淡入，在卸载前淡出。

## 自定义渲染
元素没有 render 函数。`ui-checkbox` 本身就是交互元素，所以把你的内容放在它里面，它的角色、标签和键盘行为就保持连接。用它的属性设置样式，并观察这些属性来改变里面的内容：这里每个复选框在 `data-checked` 改变时切换图标。

```ts title="render.ts"
import "@ui-sdk/web/checkbox"
import { Check, createElement, Plus } from "lucide"

const topics = [
  { value: "design", label: "Design", checked: true },
  { value: "engineering", label: "Engineering", checked: false },
  { value: "marketing", label: "Marketing", checked: false },
  { value: "sales", label: "Sales", checked: false },
]

const icon = (checked: boolean) =>
  createElement(checked ? Check : Plus, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <fieldset>
      <legend>Topics you follow</legend>
      <div data-slot="row">
        ${topics
          .map(
            (topic) =>
              `<ui-checkbox name="topics" value="${topic.value}"${topic.checked ? " default-checked" : ""}>${icon(topic.checked)}${topic.label}</ui-checkbox>`
          )
          .join("")}
      </div>
    </fieldset>
  `
  const update = (checkbox: Element) => {
    checkbox.querySelector("svg")!.outerHTML = icon(
      checkbox.hasAttribute("data-checked")
    )
  }
  new MutationObserver((records) =>
    records.forEach((record) => update(record.target as Element))
  ).observe(root, { subtree: true, attributeFilter: ["data-checked"] })
  root.querySelectorAll("ui-checkbox").forEach(update)
}

export { mount }
```

选择主题。每个复选框根据它的状态显示对勾或加号。

## 样式
用 `data-checked`、`data-unchecked` 和 `data-indeterminate` 表示勾选状态，用 `data-disabled`、`data-readonly` 和 `data-required` 表示其余状态。指示器会得到与它的复选框相同的状态属性。

每个部件都有一个 `data-slot`，比如 `checkbox`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/checkbox#data-attributes)下。

## 数据属性
### `<ui-checkbox>`
`[data-slot="checkbox"]`

- `data-checked`: Present while checked.
- `data-disabled`: Present when disabled, by its own prop, a group or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while unchecked.
- `data-indeterminate`: Present while indeterminate.

### `<ui-checkbox-indicator>`
`[data-slot="checkbox-indicator"]`

- `data-checked`: Present while checked.
- `data-disabled`: Present when disabled, by its own prop, a group or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while unchecked.
- `data-indeterminate`: Present while indeterminate.
- `data-starting-style`: Present for the indicator's first frame. Style the state you animate from.
- `data-ending-style`: Present while the indicator animates out. Style the state you animate to.

### `<ui-checkbox-group>`
`[data-slot="checkbox-group"]`

- `data-disabled`: Present when the group is disabled, by its own prop or a `<fieldset>`.
- `data-required`: Present when at least one checkbox must be checked.

## API 参考
props 是以 kebab case 写成的属性，比如 `default-checked`、`read-only` 和 `all-values`：`"false"` 表示
false，分组的 `value`、`default-value` 和 `all-values` 接受逗号分隔的值。`checked` 和
`value` 是实时的 property 和属性。回调是 DOM 事件。

### Checkbox
- `checked?` (`CheckedState`): Whether it's checked. Pass it to control the checkbox.
- `defaultChecked?` (`CheckedState`): Whether it's checked at first, when uncontrolled. A form reset returns to it.
- `checkedchange event`: Runs when a user or a form reset wants to change it. `details.reason` says why, and `details.cancel()` stops it.
- `disabled?` (`boolean`): Disables it like a native control: it can't be focused or changed, and isn't submitted.
- `readOnly?` (`boolean`): Keeps it focusable and submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission until it's checked, with the browser's own message.
- `name?` (`string`): The name it submits under. Without one, it submits nothing.
- `value?` (`string`): What it submits while checked.
- `form?` (`string`): The id of a form to belong to, when it isn't inside that form.
- `controller?` (`{ toggle: (details?: Details) => boolean; getChecked: () => CheckedState; setChecked: (checked: CheckedState, details?: Details) => boolean; focus: () => void; }`): Toggles it from anywhere. Create one with `createCheckboxController()`.
- `parent?` (`boolean`): Makes it the parent of its group: it checks or unchecks every checkbox in the group, and shows checked, unchecked or indeterminate from them.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### CheckboxIndicator
- `keepMounted?` (`boolean`): Whether the indicator stays in the page while unchecked, so it can be styled or animated in both states.

### CheckboxGroup
- `value?` (`T[]`): The checked checkboxes' values. Pass it to control the group.
- `defaultValue?` (`T[]`): The values checked at first, when uncontrolled. A form reset returns to them.
- `valuechange event`: Runs when a user or a form reset wants to change the value. `details.reason` says why, and `details.cancel()` stops it.
- `allValues?` (`T[]`): Every value a parent checkbox checks. Without it, the parent checks the checkboxes in the group. Pass it to render the parent right on the server.
- `disabled?` (`boolean`): Disables every checkbox in the group, and leaves them out of the form.
- `readOnly?` (`boolean`): Makes every checkbox in the group read-only: focusable and submitted, but presses don't change it.
- `required?` (`boolean`): Blocks form submission until at least one checkbox is checked, with the browser's own message.
- `name?` (`string`): The name every checkbox in the group submits under.
- `form?` (`string`): The id of a form to belong to, when the group isn't inside that form.
- `controller?` (`{ getValue: () => T[]; setValue: (value: T[], details?: Details) => boolean; focus: () => void; }`): Checks values from anywhere. Create one with `createCheckboxGroupController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
相同的状态会以数据属性的形式显示在每个元素上。

- `checked` (`boolean`): Whether it's checked. False while indeterminate.
- `indeterminate` (`boolean`): Whether it's `"indeterminate"`, for a partly checked group. A press makes it checked.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but presses don't change it.
- `required` (`boolean`): Whether a form won't submit until it's checked. Indeterminate doesn't count.

指示器收到相同的状态。

- `checked` (`boolean`): Whether it's checked. False while indeterminate.
- `indeterminate` (`boolean`): Whether it's `"indeterminate"`, for a partly checked group. A press makes it checked.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but presses don't change it.
- `required` (`boolean`): Whether a form won't submit until it's checked. Indeterminate doesn't count.

分组：

- `value` (`string[]`): The checked values.
- `disabled` (`boolean`): Whether the group is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the group is read-only: its checkboxes stay focusable and submitted, but presses don't change them.
- `required` (`boolean`): Whether a form won't submit until at least one of its checkboxes is checked.

### 原因
`event.detail.reason` 说明勾选状态为什么改变。

- `press` (`MouseEvent | KeyboardEvent`): A single-element control was pressed: a checkbox, a switch or a toggle.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

对分组来说，它说明已勾选的值为什么改变。

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### Checkbox 控制器
元素的 `api` property 有相同的方法。`checked` property 读取并设置状态。

每个写入方法都接受可选的 `{ reason, event }`，像按压一样触发变更事件，并在变更被取消时返回 `false`。

- `toggle(details?)` (`(details?: CheckboxChangeOptions | undefined) => boolean`): Checks it, or unchecks it. An indeterminate checkbox becomes checked.
- `getChecked()` (`() => CheckedState`): Whether it's checked: `true`, `false` or `"indeterminate"`.
- `setChecked(checked, details?)` (`(checked: CheckedState, details?: CheckboxChangeOptions | undefined) => boolean`): Sets whether it's checked, as a user would.
- `focus()` (`() => void`): Moves focus to it.

### CheckboxGroup 控制器
元素的 `api` property 有相同的方法。`value` property 读取并设置已勾选的值。

它的写入方法与复选框控制器相同。

- `getValue()` (`() => T[]`): The checked values.
- `setValue(value, details?)` (`(value: T[], details?: CheckboxGroupChangeOptions | undefined) => boolean`): Sets the checked values, as a user would. A disabled group ignores it.
- `focus()` (`() => void`): Moves focus to the first enabled checkbox.

### 事件
事件在各自的元素上触发，不冒泡，新状态或新值在 `event.detail.value` 中，`reason` 和 `event` 在它旁边。调用 `preventDefault()` 会取消变更。

| 成员                          | 所属部件            | 说明                                                |
| ----------------------------- | ------------------- | --------------------------------------------------- |
| `checked` property, attribute | `ui-checkbox`       | 勾选状态。属性设置起始值，且是实时的                |
| `api` property                | `ui-checkbox`       | [控制器](https://ui-sdk.cn/docs/web-components/components/checkbox#checkbox-controller)                      |
| `checkedchange` event         | `ui-checkbox`       | `detail: { value: checked, reason, event, source }` |
| `value` property, attribute   | `ui-checkbox-group` | 已勾选的值。属性以逗号分隔，设置起始值，且是实时的  |
| `api` property                | `ui-checkbox-group` | [控制器](https://ui-sdk.cn/docs/web-components/components/checkbox#checkboxgroup-controller)                 |
| `valuechange` event           | `ui-checkbox-group` | `detail: { value, reason, event, source }`          |

## 无障碍
复选框遵循 [WAI-ARIA 复选框模式](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/)，分组的父复选框遵循它的[混合复选框示例](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/examples/checkbox-mixed/)。`ui-checkbox` 本身就是控件，带 `checkbox` 角色，并通过 `ElementInternals` 参与表单，没有隐藏的输入框。下面每一行都是一个自动化测试。

### 键盘
| Key   | 作用                                         |
| ----- | -------------------------------------------- |
| Tab   | 移动到下一个复选框                           |
| Space | 勾选或取消勾选它，或勾选一个混合状态的复选框 |
| Enter | 提交它的表单                                 |

### 经过测试的行为
**Checkbox**

- Clicking toggles it.
- Clicking its label toggles it.
- Clicking a label around it toggles it once.
- Space toggles it.
- Enter submits the form and never toggles it.
- Tab moves through checkboxes in order.
- The indicator shows only while checked.
- A change can be cancelled.
- A controlled checkbox follows its value.
- A read-only checkbox can be focused but not changed.
- Exit keyframes keyed on data-unchecked play before the indicator unmounts.
- An infinite exit animation still unmounts the indicator.

Runs in React、Vue 和 web components.

分组和父复选框：

- The group is named by its label.
- Starts on its default value.
- Checking a checkbox adds its value to the group.
- Every checked value submits under the group's name, in order.
- A reset returns to the default value.
- A required group blocks submission until one is checked.

**Parent checkbox**

- Is mixed while some checkboxes are checked.
- Checks every checkbox from mixed, then unchecks them all.
- Is checked once every checkbox is.
- Submits nothing itself.

Runs in React、Vue 和 web components.

在表单中：

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React、Vue 和 web components.

在模式基线之外：

**Enhancements**

- The first invalid control takes focus in document order.
- A later required field without an error part doesn't take focus from the first.

**Form-associated custom elements**

- Take part in the form with no hidden input. Web components only.
- Report validity like native controls. Web components only.
- Have live checked and value properties. Web components only.
- Are named by their labels. Web components only.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器录制：

- Announcements while checking boxes with a keyboard.
- Announcements while choosing a radio with a keyboard.

Runs in React、Vue 和 web components.
