选择一个选项,用方向键移动选择,并通过表单提交。

选项不多且只能选一个时,用单选按钮,比如配送速度或套餐。分组保存一个值,并让整个列表只有一个 Tab 停靠点。

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

const speeds = [
  { value: "standard", label: "Standard" },
  { value: "express", label: "Express" },
  { value: "overnight", label: "Overnight" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Shipping speed</ui-field-label>
      <ui-radio-group default-value="standard">
        ${speeds
          .map(
            (speed) => `
              <label data-slot="label">
                <ui-radio value="${speed.value}">
                  <ui-radio-indicator></ui-radio-indicator>
                </ui-radio>
                ${speed.label}
              </label>
            `
          )
          .join("")}
      </ui-radio-group>
    </ui-field>
  `
}

export { mount }
选择 Express,然后用方向键在几种速度之间移动选择。

安装

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

导入组件;如果用到字段,也导入字段,以注册它们的元素。这个 import 在服务器上是安全的。

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

组合

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

ui-radio-group
├── ui-radio
│   └── ui-radio-indicator
└── ui-radio
    └── ui-radio-indicator

给每个单选按钮一个 value,并把它和文字一起包在 label 里。分组的值是已选中单选按钮的值,指示器在它的单选按钮被选中时显示。

用法

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

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

<ui-field>
  <ui-field-label>Shipping speed</ui-field-label>
  <ui-radio-group default-value="standard">
    <label>
      <ui-radio value="standard">
        <ui-radio-indicator></ui-radio-indicator>
      </ui-radio>
      Standard
    </label>
    <label>
      <ui-radio value="express">
        <ui-radio-indicator></ui-radio-indicator>
      </ui-radio>
      Express
    </label>
  </ui-radio-group>
</ui-field>

字段的标签为分组提供名称。没有字段时,用 aria-label 或 aria-labelledby 为它命名。没有 default-value 时,初始没有任何选项被选中,Tab 会进入第一个启用的单选按钮。

描述

某个选项需要更多说明时,把每个单选按钮放进各自的 ui-field,并带上 ui-field-label 和 ui-field-description。这个字段把标签和描述都连接到它的单选按钮,同时外层字段仍然为分组提供名称。

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

const frequencies = [
  { value: "instant", label: "Instantly", description: "An email right away." },
  {
    value: "daily",
    label: "Daily digest",
    description: "One email each morning.",
  },
  {
    value: "weekly",
    label: "Weekly digest",
    description: "A summary every Monday.",
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Email notifications</ui-field-label>
      <ui-radio-group default-value="daily">
        ${frequencies
          .map(
            (frequency) => `
              <ui-field>
                <ui-radio value="${frequency.value}">
                  <ui-radio-indicator></ui-radio-indicator>
                </ui-radio>
                <div data-slot="stack">
                  <ui-field-label>${frequency.label}</ui-field-label>
                  <ui-field-description>${frequency.description}</ui-field-description>
                </div>
              </ui-field>
            `
          )
          .join("")}
      </ui-radio-group>
    </ui-field>
  `
}

export { mount }
点击 Weekly digest 的标签来选择它。每个单选按钮还会由它下面的一行文字来描述。

选择卡片

把选项的内容包在它的标签里,让整张卡片都可点击。:has([data-checked]) 让卡片反映它里面的单选按钮。

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

const plans = [
  {
    value: "hobby",
    label: "Hobby",
    description: "Free for personal projects.",
  },
  {
    value: "pro",
    label: "Pro",
    description: "$20 per month for growing teams.",
  },
  {
    value: "enterprise",
    label: "Enterprise",
    description: "Custom pricing and support.",
  },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Plan</ui-field-label>
      <ui-radio-group default-value="hobby">
        ${plans
          .map(
            (plan) => `
              <label data-slot="card">
                <span data-slot="stack">
                  <span>${plan.label}</span>
                  <span data-slot="hint">${plan.description}</span>
                </span>
                <ui-radio value="${plan.value}">
                  <ui-radio-indicator></ui-radio-indicator>
                </ui-radio>
              </label>
            `
          )
          .join("")}
      </ui-radio-group>
    </ui-field>
  `
}

export { mount }
点击 Pro 卡片上的任意位置来选择它。方向键也会在卡片之间移动选择。

字段集与图例

把 ui-field-set 套在原生 fieldset 和 legend 外面,把一组选项放在一起描述。用 aria-labelledby 把分组连接到图例,用 aria-describedby 连接到描述。

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

const periods = [
  { value: "monthly", label: "Monthly", price: "$12 per month" },
  { value: "yearly", label: "Yearly", price: "$120 per year" },
]

function mount(root: HTMLElement) {
  const id = crypto.randomUUID()
  root.innerHTML = `
    <ui-field-set>
      <fieldset>
        <legend id="${id}-legend">Billing period</legend>
        <ui-field-description id="${id}-description">Yearly billing gets you two months free.</ui-field-description>
        <ui-radio-group default-value="monthly" aria-labelledby="${id}-legend" aria-describedby="${id}-description">
          ${periods
            .map(
              (period) => `
                <label data-slot="label">
                  <ui-radio value="${period.value}">
                    <ui-radio-indicator></ui-radio-indicator>
                  </ui-radio>
                  ${period.label}
                  <span data-slot="hint">(${period.price})</span>
                </label>
              `
            )
            .join("")}
        </ui-radio-group>
      </fieldset>
    </ui-field-set>
  `
}

export { mount }
选择 Yearly。图例和它下面的一行文字描述了两个计费周期。

禁用

在分组或单个单选按钮上设置 disabled。禁用的单选按钮无法聚焦,也无法选中,方向键会跳过它们。禁用的 fieldset 也会禁用分组,禁用的分组不提交任何内容。

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

const themes = [
  { value: "light", label: "Light" },
  { value: "dark", label: "Dark" },
  { value: "system", label: "System" },
]

const backups = [
  { value: "hourly", label: "Hourly", disabled: true },
  { value: "daily", label: "Daily", disabled: false },
  { value: "weekly", label: "Weekly", disabled: false },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ui-field>
        <ui-field-label>Theme</ui-field-label>
        <ui-field-description>Set by your organization.</ui-field-description>
        <ui-radio-group default-value="light" disabled>
          ${themes
            .map(
              (theme) => `
                <label data-slot="label">
                  <ui-radio value="${theme.value}">
                    <ui-radio-indicator></ui-radio-indicator>
                  </ui-radio>
                  ${theme.label}
                </label>
              `
            )
            .join("")}
        </ui-radio-group>
      </ui-field>
      <ui-field>
        <ui-field-label>Backups</ui-field-label>
        <ui-field-description>Hourly backups need the Pro plan.</ui-field-description>
        <ui-radio-group default-value="daily">
          ${backups
            .map(
              (backup) => `
                <label data-slot="label">
                  <ui-radio value="${backup.value}"${backup.disabled ? " disabled" : ""}>
                    <ui-radio-indicator></ui-radio-indicator>
                  </ui-radio>
                  ${backup.label}
                </label>
              `
            )
            .join("")}
        </ui-radio-group>
      </ui-field>
    </div>
  `
}

export { mount }
Theme 分组已禁用。在 Backups 中,Hourly 已禁用,所以方向键会在 Daily 和 Weekly 之间移动。

只读

在分组上设置 read-only,可以保留它的值,同时仍让人聚焦和读取各个选项。方向键移动焦点,不选中任何选项,值仍会随表单提交。

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

const plans = [
  { value: "free", label: "Free" },
  { value: "pro", label: "Pro" },
  { value: "team", label: "Team" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Your plan</ui-field-label>
      <ui-field-description>Ask an admin to change plans.</ui-field-description>
      <ui-radio-group default-value="pro" read-only>
        ${plans
          .map(
            (plan) => `
              <label data-slot="label">
                <ui-radio value="${plan.value}">
                  <ui-radio-indicator></ui-radio-indicator>
                </ui-radio>
                ${plan.label}
              </label>
            `
          )
          .join("")}
      </ui-radio-group>
    </ui-field>
  `
}

export { mount }
点击 Team,或聚焦 Pro 并按向下方向键。Pro 保持选中。

受控

读取或设置分组元素的 value property,并监听 valuechange。在监听器里调用 event.preventDefault() 可以保持当前值。它的 api property 是一个控制器,可以从任何地方选中一个单选按钮,比如下面的 Choose Team 按钮。

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

const plans = [
  { value: "starter", label: "Starter" },
  { value: "pro", label: "Pro" },
  { value: "team", label: "Team" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button">Choose Team</button>
      </div>
      <ui-field>
        <ui-field-label>Plan</ui-field-label>
        <ui-radio-group default-value="pro">
          ${plans
            .map(
              (plan) => `
                <label data-slot="label">
                  <ui-radio value="${plan.value}">
                    <ui-radio-indicator></ui-radio-indicator>
                  </ui-radio>
                  ${plan.label}
                </label>
              `
            )
            .join("")}
        </ui-radio-group>
      </ui-field>
    </div>
  `
  const group = root.querySelector("ui-radio-group")!
  root
    .querySelector("[data-slot=controls] button")!
    .addEventListener("click", () => group.api.setValue("team"))
  group.addEventListener("valuechange", (event) => {
    const { value, reason } = event.detail
    log(
      root,
      `${plans.find((plan) => plan.value === value)?.label ?? "None"} (${reason})`
    )
  })
}

export { mount }
选择 Starter,然后按 Choose Team。控制台会记录每次变更及其原因。

受控状态、取消和调试见状态与事件。

表单

ui-radio-group 与表单关联,所以分组不需要隐藏输入就能参与表单。设置 name 以提交选中的值;没有 name 或没有选中的单选按钮时,分组不提交任何内容。required 会阻止提交,直到做出选择,Reset 会恢复到 default-value。

把 form 设为表单的 id,就能从页面其他地方加入该表单,就像这个分组一样。

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

const speeds = [
  { value: "standard", label: "Standard", detail: "Free, 5 to 7 days" },
  { value: "express", label: "Express", detail: "$9, 2 days" },
  { value: "overnight", label: "Overnight", detail: "$24, next day" },
]

function mount(root: HTMLElement) {
  const id = crypto.randomUUID()
  root.innerHTML = `
    <div data-slot="stack">
      <ui-field>
        <ui-field-label>Shipping speed</ui-field-label>
        <ui-radio-group name="shipping" form="${id}-checkout" required default-value="standard">
          ${speeds
            .map(
              (speed) => `
                <label data-slot="label">
                  <ui-radio value="${speed.value}">
                    <ui-radio-indicator></ui-radio-indicator>
                  </ui-radio>
                  ${speed.label}
                  <span data-slot="hint">(${speed.detail})</span>
                </label>
              `
            )
            .join("")}
        </ui-radio-group>
      </ui-field>
      <form data-slot="row" id="${id}-checkout">
        <button type="submit" data-variant="solid">Continue</button>
        <button type="reset">Reset</button>
      </form>
    </div>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    log(root, `Submitted shipping=${new FormData(form).get("shipping")}`)
  })
}

export { mount }
选择 Express 并按 Continue。控制台会记录提交的值,Reset 会把选择恢复为 Standard。

校验

把必选分组放进带 ui-field-error 的 Field。没有做出选择就提交时,错误会显示在分组下方,焦点也会移到那里。表单与校验涵盖了共用的字段行为。

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

const channels = [
  { value: "email", label: "Email only" },
  { value: "sms", label: "SMS only" },
  { value: "both", label: "Email and SMS" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field>
        <ui-field-label>Order updates</ui-field-label>
        <ui-field-description>Choose how we tell you about your orders.</ui-field-description>
        <ui-radio-group name="updates" required>
          ${channels
            .map(
              (channel) => `
                <label data-slot="label">
                  <ui-radio value="${channel.value}">
                    <ui-radio-indicator></ui-radio-indicator>
                  </ui-radio>
                  ${channel.label}
                </label>
              `
            )
            .join("")}
        </ui-radio-group>
        <ui-field-error>Choose how to get order updates.</ui-field-error>
      </ui-field>
      <div data-slot="row">
        <button type="submit" data-variant="solid">Save</button>
      </div>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    log(root, `Saved updates=${new FormData(form).get("updates")}`)
  })
}

export { mount }
不选任何选项就按 Save,查看错误。只选择 SMS 再保存;控制台会记录保存的值。

动画

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

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

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

keep-mounted 让指示器在未选中时也留在页面中,并带有 data-unchecked。这里它让悬停的选项预览自己的圆点。

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

const themes = [
  { value: "light", label: "Light" },
  { value: "dark", label: "Dark" },
  { value: "system", label: "System" },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Theme</ui-field-label>
      <ui-radio-group default-value="system">
        ${themes
          .map(
            (theme) => `
              <label data-slot="label">
                <ui-radio value="${theme.value}">
                  <ui-radio-indicator keep-mounted></ui-radio-indicator>
                </ui-radio>
                ${theme.label}
              </label>
            `
          )
          .join("")}
      </ui-radio-group>
    </ui-field>
  `
}

export { mount }
悬停 Light 预览它的圆点,然后选择它。圆点在 Light 上放大出现,在 System 上缩小消失。

循环

方向键会从最后一个单选按钮绕回第一个。设置 loop="false" 可以停在两端。

<ui-radio-group default-value="low" loop="false"> ... </ui-radio-group>

自定义渲染

元素没有渲染函数。ui-radio 本身就是交互元素,所以把你的内容放进它里面,它的角色、标签和键盘行为就会保持连接。用它的属性为它设置样式,并观察这些属性来改变里面的内容:这里每个单选按钮在 data-checked 变化时标记自己的对勾。渲染约定见部件与组合。

import "@ui-sdk/web/field"
import "@ui-sdk/web/radio"
import { Check, createElement } from "lucide"

const options = [
  {
    value: "all",
    label: "Everything",
    description: "Every message and update.",
  },
  {
    value: "mentions",
    label: "Mentions",
    description: "Only when someone mentions you.",
  },
  { value: "none", label: "Nothing", description: "Turn notifications off." },
]

function mount(root: HTMLElement) {
  const id = crypto.randomUUID()
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Notify me about</ui-field-label>
      <ui-radio-group default-value="mentions">
        ${options
          .map(
            (option) => `
              <ui-radio
                value="${option.value}"
                aria-labelledby="${id}-${option.value}-label"
                aria-describedby="${id}-${option.value}-description"
              >
                <span data-slot="stack">
                  <span id="${id}-${option.value}-label">${option.label}</span>
                  <span data-slot="hint" id="${id}-${option.value}-description">${option.description}</span>
                </span>
                ${createElement(Check, { "aria-hidden": "true" }).outerHTML}
              </ui-radio>
            `
          )
          .join("")}
      </ui-radio-group>
    </ui-field>
  `
  const update = (radio: Element) => {
    radio
      .querySelector("svg")!
      .toggleAttribute("data-checked", radio.hasAttribute("data-checked"))
  }
  const radios = root.querySelectorAll("ui-radio")
  radios.forEach((radio) => {
    new MutationObserver(() => update(radio)).observe(radio, {
      attributeFilter: ["data-checked"],
    })
    update(radio)
  })
}

export { mount }
选择 Nothing。每个单选按钮渲染一个占满宽度的按钮,根据它的状态显示对勾。

样式

用 data-checked 和 data-unchecked 表示选中状态,用 data-disabled、data-readonly 和 data-required 表示其余状态。指示器会得到与它的单选按钮相同的状态属性,分组会得到 data-disabled、data-readonly 和 data-required。

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

数据属性

<ui-radio-group>

[data-slot="radio-group"]

属性含义
data-readonlyPresent when the group is read-only.
data-requiredPresent when the group is required.
data-disabledPresent when disabled, by its own prop, the group or a <fieldset>.

<ui-radio>

[data-slot="radio"]

属性含义
data-checkedPresent on the checked radio.
data-readonlyPresent when the group is read-only.
data-requiredPresent when the group is required.
data-uncheckedPresent on radios that aren't checked.
data-disabledPresent when disabled, by its own prop, the group or a <fieldset>.

<ui-radio-indicator>

[data-slot="radio-indicator"]

属性含义
data-checkedPresent on the checked radio.
data-readonlyPresent when the group is read-only.
data-requiredPresent when the group is required.
data-uncheckedPresent on radios that aren't checked.
data-disabledPresent when disabled, by its own prop, the group or a <fieldset>.
data-starting-stylePresent for the indicator's first frame. Style the state you animate from.
data-ending-stylePresent while the indicator animates out. Style the state you animate to.

API 参考

props 是以 kebab case 写成的属性,比如 default-value、read-only 和 keep-mounted:"false" 表示 false,所以 loop="false" 会关闭循环。value 是实时的 property 和属性。回调是 DOM 事件。

RadioGroup

value?T | null
The checked radio's value. Pass it to control the group. null checks nothing.
defaultValue?T | null
The radio checked at first, when uncontrolled. A form reset returns to it.
valuechange event
Runs when a user or a form reset wants to change the value. details.reason says why, and details.cancel() stops it.
disabled?boolean
Disables every radio like native ones: they can't be focused or changed, and the value isn't submitted.
readOnly?boolean
Keeps the items focusable and the value submitted, but stops changes.
required?boolean
Blocks form submission until an item is checked, with the browser's own message.
name?string
The name the value submits under. Without one, the group submits nothing.
form?string
The id of a form to belong to, when the group isn't inside that form.
loop?boolean
Whether arrow keys wrap from the last item to the first.
controller?{ getValue: () => T | null; setValue: (value: T | null, details?: Details) => boolean; focus: () => void; }
Checks radios from anywhere. Create one with createRadioGroupController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

Radio

valuestring
What the group's value becomes when this item is checked.
disabled?boolean
Skips the item, like a disabled native radio: arrow keys pass it and it can't be focused or checked.

RadioIndicator

keepMounted?boolean
Whether the indicator stays in the page while its item is unchecked.

状态

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

valuestring | null
The checked item's value.
disabledboolean
Whether the group is disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether the group is read-only: arrow keys still move focus, but nothing changes the checked item.
requiredboolean
Whether a form won't submit until an item is checked.
checkedboolean
Whether this item is checked.
disabledboolean
Whether this item is disabled, by itself, its group or a <fieldset>.
readOnlyboolean
Whether the group is read-only.
requiredboolean
Whether the group is required.
checkedboolean
Whether this item is checked.
disabledboolean
Whether this item is disabled, by itself, its group or a <fieldset>.
readOnlyboolean
Whether the group is read-only.
requiredboolean
Whether the group is required.

原因

event.detail.reason 说明选中的值为什么改变。

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent
Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
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 有相同的方法。value property 读取并设置选中的值。

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

getValue()() => T | null
The checked radio's value.
setValue(value, details?)(value: T | null, details?: RadioGroupChangeOptions | undefined) => boolean
Checks a radio, as a user would. Disabled radios and read-only groups ignore it.
focus()() => void
Moves focus to the checked radio, or the first one.

事件

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

成员所属部件说明
value property, attributeui-radio-group选中的值。属性设置起始值,且是实时的
api propertyui-radio-group控制器
valuechange eventui-radio-groupdetail: { value, reason, event, source }

无障碍

单选按钮分组遵循 WAI-ARIA 单选按钮组模式,行为与共享同一 name 的原生单选按钮一致。ui-radio 本身就是控件,带有 radio 角色,分组通过 ElementInternals 参与表单,不需要隐藏输入。

键盘

Key作用
Tab进入分组,停在已选中的单选按钮或第一个启用的单选按钮上
方向键移到下一个或上一个单选按钮并选中它,跳过禁用的那些
Space选中当前聚焦的单选按钮
Enter提交它的表单

经过测试的行为

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

Selection
  • Nothing is checked at first without a default value.
  • Clicking an item checks it and unchecks the others.
  • Clicking an item's label checks it.
  • Clicking a disabled item does nothing.
  • A change can be cancelled.
Keyboard
  • Tab lands on the first item when nothing is checked.
  • Tab lands on the checked item.
  • Tab leaves the group after one stop.
  • Space checks the focused item.
  • ArrowDown and ArrowRight move to the next item and check it.
  • ArrowUp and ArrowLeft move to the previous item and check it.
  • Arrow keys skip disabled items.
  • Arrow keys wrap at both ends.
  • Enter never checks an item.
  • Keys pressed in quick succession are never lost.
  • Enter on an item submits the form.
Read-only and disabled
  • A read-only group moves focus with arrow keys but checks nothing.
  • A disabled group can't be focused or changed.
  • Clicking a radio in a disabled group doesn't focus it.
  • Clicking the label of a radio in a disabled group neither focuses nor checks it.
Animation
  • The indicator animates in from its starting style.

运行于 React、Vue 和 web components。

在字段中:

With every radio enabled
  • Each radio is named by the label of its own field.
  • The field around the group still names the group.
  • Clicking a radio's label checks it and unchecks the others.
  • The group keeps one tab stop.
  • Arrow keys move between the radios and check them.
A disabled radio
  • A disabled field around the first radio moves the tab stop to the next.
  • Disabling the first radio after it renders moves the tab stop to the next.
  • Enabling the first radio again gives it back the tab stop.

运行于 React、Vue 和 web components。

在从右到左的页面中:

  • ArrowLeft moves to the next radio and ArrowRight to the previous one.
  • ArrowDown and ArrowUp keep their direction.

运行于 React、Vue 和 web components。