从一排星里选一个分数,可以选整星或半星,指针移过时还能预览。

用评分收集分数,比如一次住宿的体验,或者展示一个分数,比如平均值。每颗星都是一个单选按钮,所以它像单选按钮组一样工作,只有一个值和一个 Tab 停靠点。

import "@ui-sdk/web/rating"
import { createElement, Star } from "lucide"

const star = createElement(Star, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-rating aria-label="Rating" default-value="3">
      <template><ui-rating-item>${star}</ui-rating-item></template>
    </ui-rating>
  `
}

export { mount }
选择一颗星,然后用方向键改变分数。

安装

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

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

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

组合

用下面的组合构建 ui-rating:

ui-rating
└── template
    └── ui-rating-item

ui-rating 每颗星渲染一个 ui-rating-item,从它的 <template> 里的那个复制而来,并渲染每个部件里的单选按钮。没有模板时,各部件是空的。

用法

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

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

<ui-rating aria-label="Rating" default-value="3">
  <template>
    <ui-rating-item>
      <svg
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        aria-hidden="true"
      >
        <path
          d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"
        />
      </svg>
    </ui-rating-item>
  </template>
</ui-rating>

用 aria-label 给评分命名,或者把它放进 Field,由字段的标签命名。没有 default-value 时,初始没有星被选中,Tab 会落在第一颗星上。

星

把图标放进 ui-rating-item。每个部件表明显示出来的分数盖住了它这颗星的多大一部分:--rating-fill 从 0 到 1,data-filled 标记整颗星,data-partial 标记分数半途结束的那颗星。选择分数的单选按钮叠在图标上方,所以图标自己不需要处理事件。

[data-slot="rating-item"] {
  color: lightgray;
}

[data-slot="rating-item"][data-filled] {
  color: gold;
}

要显示半星和平均值,把图标涂到 calc(var(--rating-fill) * 100%) 为止,比如在星形遮罩后面垫一层渐变。

半星

设置 step="0.5",把每颗星分成两半。每一半都是自己的单选按钮,名称类似 “2.5 stars”,按压一颗星的前半部分会选中半分。

import "@ui-sdk/web/rating"
import { createElement, Star } from "lucide"

const star = createElement(Star, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-rating aria-label="Rating" step="0.5" default-value="3.5">
      <template><ui-rating-item>${star}</ui-rating-item></template>
    </ui-rating>
  `
}

export { mount }
选择一颗星的前半部分。这颗星会填满一半。

预览

指针悬停在星上时,它们显示指针下的分数:--rating-fill 跟随指针,data-highlighted 标记到它为止的星。离开星时会重新显示分数。触摸没有预览,因为轻点会立刻选中分数。

可取消选择

设置 deselectable,让人可以清空分数:按压已选中的星,或者在它上面按 Space,就把分数设回 null。

import "@ui-sdk/web/rating"
import { createElement, Star } from "lucide"

const star = createElement(Star, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-rating aria-label="Rating" default-value="4" deselectable>
      <template><ui-rating-item>${star}</ui-rating-item></template>
    </ui-rating>
  `
}

export { mount }
按压第四颗星。分数被清空。

只读

设置 read-only 来展示不能改变的分数,比如平均值。任何分数都能显示,比如 4.2,它会填满最后一颗星的五分之一。对屏幕阅读器来说,整个评分变成一张图片,它的单选按钮对它们隐藏。

用 getValueLabel property 给只读评分命名,这样它的名称里包含分数。aria-label 会替换它。

import type { UiRatingElement } from "@ui-sdk/web"
import "@ui-sdk/web/rating"
import { createElement, Star } from "lucide"

const star = createElement(Star, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-rating value="4.2" read-only>
      <template><ui-rating-item>${star}</ui-rating-item></template>
    </ui-rating>
  `
  const rating = root.querySelector("ui-rating") as UiRatingElement
  rating.getValueLabel = (value, max) => `Rated ${value} out of ${max}`
}

export { mount }
平均值 4.2,名称为 Rated 4.2 out of 5。

禁用

设置 disabled,让每颗星都无法聚焦或改变。禁用的评分不提交任何内容。

import "@ui-sdk/web/rating"
import { createElement, Star } from "lucide"

const star = createElement(Star, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-rating aria-label="Rating" default-value="2" disabled>
      <template><ui-rating-item>${star}</ui-rating-item></template>
    </ui-rating>
  `
}

export { mount }
评分已禁用,所以这些星无法聚焦或按压。

受控

监听 valuechange 获取每次变更及其原因。调用 event.preventDefault() 可以保持当前分数。元素的 api property 有同样的方法,比如下面的 Clear Rating 按钮用 api.setValue(null)。

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

const star = createElement(Star, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div>
      <div data-slot="controls">
        <button type="button">Clear Rating</button>
      </div>
      <ui-rating aria-label="Rating" default-value="4">
        <template><ui-rating-item>${star}</ui-rating-item></template>
      </ui-rating>
    </div>
  `
  const rating = root.querySelector("ui-rating")!
  rating.addEventListener("valuechange", (event) => {
    const { value, reason } = event.detail
    log(root, `value: ${value} (${reason})`)
  })
  root
    .querySelector('[data-slot="controls"] button')!
    .addEventListener("click", () => rating.api.setValue(null))
}

export { mount }
选择一颗星,然后按 Clear Rating。控制台会记录每次变更及其原因。

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

表单

评分通过 ElementInternals 参与表单。设置 name 以提交分数;没有名称或分数时,不提交任何内容。required 会阻止提交,直到有了分数,表单重置会恢复到 default-value。

控制台
import "@ui-sdk/web/field"
import "@ui-sdk/web/rating"
import { createElement, Star } from "lucide"
import { log } from "./log"

const star = createElement(Star, { "aria-hidden": "true" }).outerHTML

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field>
        <ui-field-label>Rate your stay</ui-field-label>
        <ui-rating name="stay" required>
          <template><ui-rating-item>${star}</ui-rating-item></template>
        </ui-rating>
      </ui-field>
      <div data-slot="row">
        <button type="submit" data-variant="solid">Send Review</button>
        <button type="reset">Reset</button>
      </div>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    log(root, `Submitted stay=${new FormData(form).get("stay")}`)
  })
}

export { mount }
不选分数就按 Send Review,查看浏览器的提示。选择一颗星再发送一次。

星与名称

用 max 设置星的数量,用 loop 让方向键从最后一颗星绕回第一颗。每个单选按钮由 getValueLabel property 命名,它接收分数和 max,默认说 “1 star” 或 “3 stars”。

<ui-rating aria-label="Difficulty" max="10" loop></ui-rating>
<script type="module">
  document.querySelector("ui-rating").getValueLabel = (value, max) =>
    `${value} of ${max}`
</script>

样式

部件没有样式。用每颗星上的 data-filled、data-partial、data-checked 和 data-highlighted,以及 --rating-fill 表示它有多满。data-disabled、data-readonly 和 data-required 在评分和它的星上。

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

ui-rating-item

变量内容
--rating-fillHow much of the star the shown score covers, from 0 to 1.

数据属性

ui-rating

[data-slot="rating"]

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

ui-rating-item

[data-slot="rating-item"]

属性含义
data-filledPresent on stars the shown score covers whole.
data-partialPresent on the star the shown score covers part of, like the last of 2.5.
data-checkedPresent on the star the score ends in.
data-disabledPresent when the rating is disabled, by its own prop or a <fieldset>.
data-readonlyPresent when the rating only shows its score.
data-highlightedPresent on the stars up to the score a pointer previews.

API 参考

props 是以 kebab case 写成的属性,比如 default-value 和 read-only。getValueLabel 和 controller 是 property。value 是实时的 property 和属性。回调是 DOM 事件。

ui-rating

value?number | null
The score. Pass it to control the rating. null means no score yet.
defaultValue?number | null
The score at first, when uncontrolled. A form reset returns to it.
valuechange event
Runs when a user or a form reset wants to change the score. details.reason says why, and details.cancel() stops it.
max?number
How many stars there are.
step?number
The smallest change, as a fraction of a star: 0.5 makes half stars, each half its own radio.
deselectable?boolean
Lets a press on the checked star clear the score.
disabled?boolean
Disables every star: they can't be focused or changed, and the score isn't submitted.
readOnly?boolean
Shows the score as an image, named by getValueLabel, that can't be changed. Any score shows, like an average of 4.2.
required?boolean
Blocks form submission until there's a score, with the browser's own message.
name?string
The name the score submits under. Without one, the rating submits nothing.
form?string
The id of a form to belong to, when the rating isn't inside that form.
loop?boolean
Whether arrow keys wrap from the last star to the first.
getValueLabel?((value: number, max: number) => string)
Names a score, for each star's radio and for a read-only rating.
controller?{ getValue: () => number | null; setValue: (value: number | null, details?: RatingChangeOptions) => boolean; focus: () => void; }
Sets the score from anywhere. Create one with createRatingController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

状态

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

valuenumber | null
The score, or null before anyone rates.
highlightednumber | null
The score a pointer previews over the stars, or null while none does.
disabledboolean
Whether the rating is disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether the rating only shows its score.
requiredboolean
Whether a form won't submit until there's a score.
indexnumber
Which star this is, from 1.
fillnumber
How much of this star the shown score covers, from 0 to 1. Also --rating-fill.
checkedboolean
Whether the score ends in this star.
highlightedboolean
Whether a pointer previews a score that reaches this star.
disabledboolean
Whether the rating is disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether the rating only shows its score.

原因

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()() => number | null
The score, or null before anyone rates.
setValue(value, details?)(value: number | null, details?: RatingChangeOptions | undefined) => boolean
Sets the score, as a user would. Disabled and read-only ratings ignore it.
focus()() => void
Moves focus to the checked star, or the first one.

事件

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

成员所属部件说明
value property, attributeui-rating分数,或 null。属性设置起始值,且是实时的
api propertyui-rating控制器
valuechange eventui-ratingdetail: { value, reason, event, source }

无障碍

评分是一个单选按钮组,所以它遵循 WAI-ARIA 单选按钮组模式,行为与共享同一 name 的原生单选按钮一致。每颗星为它能选的每个分数各渲染一个带 radio 角色的按钮,以及一个参与表单的隐藏原生单选按钮。星里面的图标应该用 aria-hidden 对屏幕阅读器隐藏,因为每个单选按钮已经有名称。只读评分改用 img 角色,由 getValueLabel 命名。

键盘

按键作用
Tab进入评分,落在已选中的星或第一颗星上
方向键移到下一个或上一个分数并选中它,除非设置了 loop,否则在两端停下
Space选中聚焦的星;当它已选中且 deselectable 时,则清除
Enter提交它的表单

经过测试的行为

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

Selection
  • The default score is checked, and the stars up to it are full.
  • Clicking a star checks it and says why.
  • A half star fills half of its star.
  • Clicking the checked star clears a deselectable rating, and only that one.
  • A change can be cancelled.
  • A controller sets the score.
Preview
  • A pointer over a star previews its score, and leaving shows the score again.
Keyboard
  • Tab lands on the checked star, and the next Tab leaves.
  • Arrow keys change the score by a step, and stop at the ends.
  • Space on the checked star clears a deselectable rating.
Read-only
  • A read-only rating is one image, named by its label, that shows any score.
  • A read-only rating holds nothing focusable, as an image must.
Forms
  • Each score submits under its rating's name.
  • A form reset returns to the default score.
  • A disabled rating submits nothing, and its stars can't be focused or checked.

运行于 React、Vue 和 web components。