打开或关闭一项设置。

用开关表示一更改就立即生效的设置,比如 Airplane mode 或通知偏好。让它的标签在两种状态下保持一致:标签说明设置是什么,开关显示它是否开启。

import "@ui-sdk/web/switch"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <label data-slot="label">
      Airplane mode
      <ui-switch>
        <ui-switch-thumb></ui-switch-thumb>
      </ui-switch>
    </label>
  `
}

export { mount }
点击 Airplane mode,或聚焦开关后按 Space,把它打开或关闭。

安装

npm install @ui-sdk/web @ui-sdk/core

导入组件会定义它的元素。如果用到字段,也把字段导进来。在服务器上,这个 import 什么也不做。

import "@ui-sdk/web/switch"
import "@ui-sdk/web/field"

组合

用下面的组合构建一个 ui-switch:

ui-switch
└── ui-switch-thumb

把开关和它的文字包在一个 label 里。滑块手柄保持挂载并取得开关的状态,所以 CSS 可以让它从一端滑到另一端。

用法

导入部件并把它们组合起来:

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

<label>
  Airplane mode
  <ui-switch>
    <ui-switch-thumb></ui-switch-thumb>
  </ui-switch>
</label>

描述

设置需要更多说明时,在 ui-field 里用 ui-field-label 和 ui-field-description。字段会把标签和描述都连接到开关。

import "@ui-sdk/web/switch"
import "@ui-sdk/web/field"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <div data-slot="stack">
        <ui-field-label>Weekly digest</ui-field-label>
        <ui-field-description>A summary of your week, every Monday.</ui-field-description>
      </div>
      <ui-switch>
        <ui-switch-thumb></ui-switch-thumb>
      </ui-switch>
    </ui-field>
  `
}

export { mount }
点击 Weekly digest。字段把标签和描述连接到开关。

选择卡片

一项设置可以占满整张卡片。这里标签的 ::after 覆盖整张卡片,所以点击卡片任意位置都会切换开关,:has([data-checked]) 会标记已开启的卡片。

import "@ui-sdk/web/switch"
import "@ui-sdk/web/field"

const settings = [
  {
    label: "Public profile",
    description: "Anyone can see your name and photo.",
    defaultChecked: false,
  },
  {
    label: "Show activity status",
    description: "Teammates can see when you're online.",
    defaultChecked: true,
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      ${settings
        .map(
          (setting) => `
            <ui-field data-variant="card">
              <div data-slot="stack">
                <ui-field-label>${setting.label}</ui-field-label>
                <ui-field-description>${setting.description}</ui-field-description>
              </div>
              <ui-switch${setting.defaultChecked ? " default-checked" : ""}>
                <ui-switch-thumb></ui-switch-thumb>
              </ui-switch>
            </ui-field>
          `
        )
        .join("")}
    </div>
  `
}

export { mount }
点击 Public profile 卡片的任意位置把它打开。每张卡片的开关各自保存自己的值。

禁用

disabled 阻止聚焦和更改,并让开关不参与表单提交。禁用的 fieldset 也一样。

import "@ui-sdk/web/switch"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <label data-slot="label">
        Product updates
        <ui-switch>
          <ui-switch-thumb></ui-switch-thumb>
        </ui-switch>
      </label>
      <label data-slot="label">
        Security alerts
        <ui-switch default-checked disabled>
          <ui-switch-thumb></ui-switch-thumb>
        </ui-switch>
      </label>
    </div>
  `
}

export { mount }
Security alerts 始终开启,所以那个开关处于禁用状态。点击它不会改变状态,Tab 会跳过它。

只读

read-only 让开关保持可聚焦并参与表单提交,同时阻止用户更改它。用于在别处管理的设置。

import "@ui-sdk/web/switch"
import "@ui-sdk/web/field"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <div data-slot="stack">
        <ui-field-label>Encrypt backups</ui-field-label>
        <ui-field-description>Your organization manages this setting.</ui-field-description>
      </div>
      <ui-switch name="encrypt" default-checked read-only>
        <ui-switch-thumb></ui-switch-thumb>
      </ui-switch>
    </ui-field>
  `
}

export { mount }
按 Tab 到达 Encrypt backups。按 Space 或点击都不会改变它的开启状态。

受控

监听 checkedchange 来跟随值,并设置元素的 checked property 来更改它。元素的 api 可以从任何地方更改它,比如下面的 Toggle 按钮。共用的变更回调见状态与事件。

控制台
import "@ui-sdk/web/switch"
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">
        Wi-Fi
        <ui-switch default-checked>
          <ui-switch-thumb></ui-switch-thumb>
        </ui-switch>
      </label>
    </div>
  `
  const wifi = root.querySelector("ui-switch")!
  root
    .querySelector("button")!
    .addEventListener("click", () => wifi.api.toggle())
  wifi.addEventListener("checkedchange", (event) => {
    const { value, reason } = event.detail
    log(root, `${value ? "On" : "Off"} (${reason})`)
  })
}

export { mount }
关闭 Wi-Fi,或按 Toggle。控制台会记录每次变更及其原因。

表单

设置 name,让开关进入原生表单。开启的开关会提交它的 value,默认是 "on";关闭的开关不提交任何内容。Reset 会把它恢复到 default-checked。把 form 设为表单的 id,就能从页面其他地方加入该表单。

控制台
import "@ui-sdk/web/switch"
import "@ui-sdk/web/field"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field-set>
        <fieldset>
          <legend>Email notifications</legend>
          <label data-slot="label">
            Product updates
            <ui-switch name="updates">
              <ui-switch-thumb></ui-switch-thumb>
            </ui-switch>
          </label>
          <label data-slot="label">
            Security alerts
            <ui-switch name="security" default-checked>
              <ui-switch-thumb></ui-switch-thumb>
            </ui-switch>
          </label>
          <label data-slot="label">
            Weekly digest
            <ui-switch name="digest" value="weekly" default-checked>
              <ui-switch-thumb></ui-switch-thumb>
            </ui-switch>
          </label>
        </fieldset>
      </ui-field-set>
      <div data-slot="row">
        <button type="submit" data-variant="solid">Save</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 }
打开 Product updates 并按 Save。控制台会记录提交的值,Reset 会恢复默认值。

校验

required 会阻止提交,直到开关开启。在 Field 中,ui-field-error 会在开关下方显示消息,并把它连接到开关。表单与校验涵盖了共用的字段行为。

控制台
import "@ui-sdk/web/switch"
import "@ui-sdk/web/field"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field>
        <div data-slot="row">
          <div data-slot="stack">
            <ui-field-label>Two-factor authentication</ui-field-label>
            <ui-field-description>Required for admins of this workspace.</ui-field-description>
          </div>
          <ui-switch name="two-factor" required>
            <ui-switch-thumb></ui-switch-thumb>
          </ui-switch>
        </div>
        <ui-field-error match="valueMissing">Turn this on to continue.</ui-field-error>
      </ui-field>
      <div data-slot="row">
        <button type="submit" data-variant="solid">Continue</button>
      </div>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    log(root, `Submitted two-factor=${new FormData(form).get("two-factor")}`)
  })
}

export { mount }
在开关关闭时按 Continue,查看错误。打开 Two-factor authentication 并继续;控制台会记录提交的值。

切换时保存

要在变更显示之前先保存,就在 checkedchange 里调用 event.preventDefault(),让当前值在保存期间保持不变。保存结束后,调用 api.setChecked(next, { reason: "imperative" }),并在监听器里放行这个原因,让保存的值生效。Agent 的变更也会上报 "imperative",同时 source 为 "agent",所以示例会检查 source,并像其他变更一样保存它。

示例在保存进行时忽略按压,并在滑块手柄里显示加载指示器。aria-busy 告诉辅助技术开关正忙;真正阻止另一次变更的是监听器。

控制台
import "@ui-sdk/web/switch"
import { createElement, LoaderCircle } from "lucide"
import { log } from "./log"

const save = (_checked: boolean) =>
  new Promise((resolve) => setTimeout(resolve, 800))

function mount(root: HTMLElement) {
  root.innerHTML = `
    <label data-slot="label">
      Automatic backups
      <ui-switch aria-busy="false">
        <ui-switch-thumb></ui-switch-thumb>
      </ui-switch>
    </label>
  `
  const backups = root.querySelector("ui-switch")!
  const thumb = root.querySelector("ui-switch-thumb")!
  let saving = false

  backups.addEventListener("checkedchange", (event) => {
    const { value, reason, source } = event.detail
    if (reason === "imperative" && source !== "agent") {
      return
    }
    event.preventDefault()
    if (saving) {
      return
    }
    saving = true
    backups.setAttribute("aria-busy", "true")
    thumb.replaceChildren(
      createElement(LoaderCircle, {
        "data-slot": "spinner",
        "aria-hidden": "true",
      })
    )
    log(root, "Saving…")
    save(value).then(() => {
      saving = false
      backups.api.setChecked(value, { reason: "imperative" })
      backups.setAttribute("aria-busy", "false")
      thumb.replaceChildren()
      log(root, `Saved: ${value ? "on" : "off"}`)
    })
  })
}

export { mount }
打开 Automatic backups。保存期间滑块手柄会显示加载指示器,之后开关开启。

自定义渲染

元素没有 render 函数。ui-switch 是可聚焦的控件,ui-switch-thumb 存放你放进去的任何内容。这里 checkedchange 监听器把太阳或月亮放进滑块手柄,样式表可以在任一部件上读取 data-checked。渲染约定见部件与组合。

import "@ui-sdk/web/switch"
import { createElement, Moon, Sun } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <label data-slot="label">
      Dark mode
      <ui-switch>
        <ui-switch-thumb></ui-switch-thumb>
      </ui-switch>
    </label>
  `
  const darkMode = root.querySelector("ui-switch")!
  const thumb = root.querySelector("ui-switch-thumb")!
  const render = (checked: boolean) =>
    thumb.replaceChildren(
      createElement(checked ? Moon : Sun, { "aria-hidden": "true" })
    )
  render(darkMode.checked)
  darkMode.addEventListener("checkedchange", (event) =>
    render(event.detail.value)
  )
}

export { mount }
打开 Dark mode。滑块手柄根据它的状态渲染太阳或月亮。

样式

用 data-checked 和 data-unchecked 为开关和滑块手柄设置样式,用 data-disabled、data-readonly 和 data-required 表示其余状态。在无效的字段中,开关还会得到 data-invalid 和 aria-invalid;滑块手柄没有。在 data-checked 上用 translate 滑动滑块手柄,并在 dir="rtl" 下反向。

每个部件都有一个 data-slot,比如 switch,它的状态属性列在数据属性下。

数据属性

<ui-switch>

[data-slot="switch"]

属性含义
data-checkedPresent while on.
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-readonlyPresent when read-only.
data-requiredPresent when required.
data-uncheckedPresent while off.
data-invalidPresent while a Field around it shows as invalid. The thumb doesn't get it.

<ui-switch-thumb>

[data-slot="switch-thumb"]

属性含义
data-checkedPresent while on.
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-readonlyPresent when read-only.
data-requiredPresent when required.
data-uncheckedPresent while off.

API 参考

props 是以 kebab case 写成的属性,比如 default-checked 和 read-only:"false" 表示 false。checked 是实时的 property 和属性。回调是 DOM 事件。

Switch

checked?boolean
Whether it's checked. Pass it to control the checkbox.
defaultChecked?boolean
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: () => boolean; setChecked: (checked: boolean, details?: Details) => boolean; focus: () => void; }
Toggles it from anywhere. Create one with createSwitchController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

状态

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

checkedboolean
Whether it's checked. False while indeterminate.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether it's read-only: it stays focusable and submitted, but presses don't change it.
requiredboolean
Whether a form won't submit until it's checked. Indeterminate doesn't count.

原因

event.detail.reason 说明开关为什么打开或关闭。

pressMouseEvent | KeyboardEvent
A single-element control was pressed: a checkbox, a switch or a toggle.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

控制器

元素的 api property 有相同的方法。checked property 读取并设置状态。

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

toggle(details?)(details?: CheckboxChangeOptions | undefined) => boolean
Turns it on, or off.
getChecked()() => boolean
Whether it's on.
setChecked(checked, details?)(checked: boolean, details?: CheckboxChangeOptions | undefined) => boolean
Turns it on or off, as a user would.
focus()() => void
Moves focus to it.

事件

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

成员所属部件说明
checked property, attributeui-switch开关是否开启。属性设置起始值,且是实时的
api propertyui-switch控制器
checkedchange eventui-switchdetail: { value: checked, reason, event, source }

无障碍

开关遵循 WAI-ARIA 开关模式。ui-switch 自己承担 switch 角色,并通过 ElementInternals 参与表单,没有隐藏的输入框。

键盘

Key作用
Tab移动到下一个开关
Space打开或关闭它
Enter提交它的表单,从不切换它

经过测试的行为

下面每一行都是一个自动化测试。

  • Starts in its default state.
  • Clicking toggles it.
  • Clicking its label toggles it.
  • Space toggles it.
  • Enter submits the form and never toggles it.
  • The thumb follows the state.
The first input on a page
  • The first Space reports keyboard.
On a touch screen
  • The first tap reports touch.

运行于 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.

运行于 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 运行。
  • Report validity like native controls. 仅在 Web components 运行。
  • Have live checked and value properties. 仅在 Web components 运行。
  • Are named by their labels. 仅在 Web components 运行。

运行于 React、Vue 和 web components。

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

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

运行于 React、Vue 和 web components。