打开或关闭一项设置。

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

import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"

function Example() {
  return (
    <label data-slot="label">
      Airplane mode
      <Switch>
        <SwitchThumb />
      </Switch>
    </label>
  )
}

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

安装

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

组合

用下面的组合构建一个 Switch:

Switch
└── SwitchThumb

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

用法

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

import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"

function Example() {
  return (
    <label>
      Airplane mode
      <Switch>
        <SwitchThumb />
      </Switch>
    </label>
  )
}

export { Example }

描述

设置需要更多说明时,用 FieldLabel 和 FieldDescription。字段会把标签和描述都连接到开关。

import { Field, FieldDescription, FieldLabel } from "@ui-sdk/solid/field"
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"

function Example() {
  return (
    <Field>
      <div data-slot="stack">
        <FieldLabel>Weekly digest</FieldLabel>
        <FieldDescription>
          A summary of your week, every Monday.
        </FieldDescription>
      </div>
      <Switch>
        <SwitchThumb />
      </Switch>
    </Field>
  )
}

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

选择卡片

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

import { Field, FieldDescription, FieldLabel } from "@ui-sdk/solid/field"
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"
import { For } from "solid-js"

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 Example() {
  return (
    <div data-slot="stack">
      <For each={settings}>
        {(setting) => (
          <Field data-variant="card">
            <div data-slot="stack">
              <FieldLabel>{setting.label}</FieldLabel>
              <FieldDescription>{setting.description}</FieldDescription>
            </div>
            <Switch defaultChecked={setting.defaultChecked}>
              <SwitchThumb />
            </Switch>
          </Field>
        )}
      </For>
    </div>
  )
}

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

禁用

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

import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"

function Example() {
  return (
    <div data-slot="stack">
      <label data-slot="label">
        Product updates
        <Switch>
          <SwitchThumb />
        </Switch>
      </label>
      <label data-slot="label">
        Security alerts
        <Switch defaultChecked disabled>
          <SwitchThumb />
        </Switch>
      </label>
    </div>
  )
}

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

只读

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

import { Field, FieldDescription, FieldLabel } from "@ui-sdk/solid/field"
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"

function Example() {
  return (
    <Field>
      <div data-slot="stack">
        <FieldLabel>Encrypt backups</FieldLabel>
        <FieldDescription>
          Your organization manages this setting.
        </FieldDescription>
      </div>
      <Switch name="encrypt" defaultChecked readOnly>
        <SwitchThumb />
      </Switch>
    </Field>
  )
}

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

受控

传入响应式的 checked,并在 onCheckedChange 里更新它,来自己持有值。createSwitchController() 创建的控制器可以从任何地方更改它,比如下面的 Toggle 按钮。共用的变更回调见状态与事件。

控制台
import { createSwitchController } from "@ui-sdk/core/switch"
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"
import { createSignal } from "solid-js"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const wifi = createSwitchController()
  const [checked, setChecked] = createSignal(true)

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={() => wifi.toggle()}>
          Toggle
        </button>
      </div>
      <label data-slot="label">
        Wi-Fi
        <Switch
          checked={checked()}
          onCheckedChange={(next, details) => {
            setChecked(next)
            log(`${next ? "On" : "Off"} (${details.reason})`)
          }}
          controller={wifi}
        >
          <SwitchThumb />
        </Switch>
      </label>
    </div>
  )
}

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

表单

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

控制台
import { FieldLegend, FieldSet } from "@ui-sdk/solid/field"
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        const entries = [...new FormData(event.currentTarget)].map(
          ([name, value]) => `${name}=${value}`
        )
        log(
          entries.length
            ? `Submitted ${entries.join("&")}`
            : "Submitted nothing"
        )
      }}
    >
      <FieldSet>
        <FieldLegend>Email notifications</FieldLegend>
        <label data-slot="label">
          Product updates
          <Switch name="updates">
            <SwitchThumb />
          </Switch>
        </label>
        <label data-slot="label">
          Security alerts
          <Switch name="security" defaultChecked>
            <SwitchThumb />
          </Switch>
        </label>
        <label data-slot="label">
          Weekly digest
          <Switch name="digest" value="weekly" defaultChecked>
            <SwitchThumb />
          </Switch>
        </label>
      </FieldSet>
      <div data-slot="row">
        <button type="submit" data-variant="solid">
          Save
        </button>
        <button type="reset">Reset</button>
      </div>
    </form>
  )
}

export { Example }
打开 Product updates 并按 Save。控制台会记录提交的值,Reset 会恢复默认值。

校验

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

控制台
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/solid/field"
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        log(
          `Submitted two-factor=${new FormData(event.currentTarget).get("two-factor")}`
        )
      }}
    >
      <Field>
        <div data-slot="row">
          <div data-slot="stack">
            <FieldLabel>Two-factor authentication</FieldLabel>
            <FieldDescription>
              Required for admins of this workspace.
            </FieldDescription>
          </div>
          <Switch name="two-factor" required>
            <SwitchThumb />
          </Switch>
        </div>
        <FieldError match="valueMissing">Turn this on to continue.</FieldError>
      </Field>
      <div data-slot="row">
        <button type="submit" data-variant="solid">
          Continue
        </button>
      </div>
    </form>
  )
}

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

切换时保存

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

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

控制台
import { createSwitchController } from "@ui-sdk/core/switch"
import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"
import { createSignal, Show } from "solid-js"
import { useLog } from "./log"

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

function Example() {
  const log = useLog()
  const backups = createSwitchController()
  const [saving, setSaving] = createSignal(false)
  let pending = false

  return (
    <label data-slot="label">
      Automatic backups
      <Switch
        controller={backups}
        aria-busy={saving() ? "true" : "false"}
        onCheckedChange={(next, details) => {
          if (details.reason === "imperative" && details.source !== "agent") {
            return
          }
          details.cancel()
          if (pending) {
            return
          }
          pending = true
          setSaving(true)
          log("Saving…")
          save(next).then(() => {
            pending = false
            backups.setChecked(next, { reason: "imperative" })
            setSaving(false)
            log(`Saved: ${next ? "on" : "off"}`)
          })
        }}
      >
        <SwitchThumb>
          <Show when={saving()}>
            <svg
              data-slot="spinner"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M21 12a9 9 0 1 1-6.219-8.56" />
            </svg>
          </Show>
        </SwitchThumb>
      </Switch>
    </label>
  )
}

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

自定义渲染

开关和滑块手柄都接受 render,它是一个函数,接收要展开的 props 和部件的状态。把部件的 props 留在元素上,让它的角色、标签和键盘行为保持连接。渲染约定见部件与组合。

import { Switch, SwitchThumb } from "@ui-sdk/solid/switch"

function Example() {
  return (
    <label data-slot="label">
      Dark mode
      <Switch>
        <SwitchThumb
          render={(props, state) => (
            <span {...props}>
              {state.checked ? (
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401" />
                </svg>
              ) : (
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <circle cx="12" cy="12" r="4" />
                  <path d="M12 2v2" />
                  <path d="M12 20v2" />
                  <path d="m4.93 4.93 1.41 1.41" />
                  <path d="m17.66 17.66 1.41 1.41" />
                  <path d="M2 12h2" />
                  <path d="M20 12h2" />
                  <path d="m6.34 17.66-1.41 1.41" />
                  <path d="m19.07 4.93-1.41 1.41" />
                </svg>
              )}
            </span>
          )}
        />
      </Switch>
    </label>
  )
}

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

样式

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

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

数据属性

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.

SwitchThumb

[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 参考

属性和回调与下面相同,都是 Solid props。

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.
onCheckedChange?((checked: boolean, details: ChangeDetails<CheckboxCheckedChangeReason>) => void)
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.

状态

渲染函数和基于状态的 class、style 与 children 收到什么。滑块手柄的状态 SwitchThumbState 相同。

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.

原因

details.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.

控制器

用 createSwitchController() 创建一个,并作为 controller 传入。

每个写入方法都接受可选的 { 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.

事件

回调先收到新状态,再收到详情。

Prop所属部件收到
onCheckedChangeSwitch(checked, details):新状态,以及原因

无障碍

开关遵循 WAI-ARIA 开关模式。Switch 渲染一个带 switch 角色的按钮,以及一个参与表单的隐藏原生复选框。

键盘

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。