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

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

<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { Rating, RatingItem } from "@ui-sdk/vue/rating"
</script>

<template>
  <Rating aria-label="Rating" :default-value="3">
    <RatingItem>
      <StarIcon aria-hidden="true" />
    </RatingItem>
  </Rating>
</template>
选择一颗星,然后用方向键改变分数。

安装

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

组合

用下面的组合构建 Rating:

Rating
└── RatingItem

Rating 每颗星渲染一次默认插槽,所以在里面放一个 RatingItem。没有插槽时,它渲染一个不带图标的 RatingItem。

用法

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

<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { Rating, RatingItem } from "@ui-sdk/vue/rating"
</script>

<template>
  <Rating aria-label="Rating" :default-value="3">
    <RatingItem>
      <StarIcon aria-hidden="true" />
    </RatingItem>
  </Rating>
</template>

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

星

把图标放进 RatingItem。每个部件表明显示出来的分数盖住了它这颗星的多大一部分:--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%) 为止,比如在星形遮罩后面垫一层渐变。

部件的默认插槽会收到它的 state,所以分数盖住这颗星后图标可以填满:

<RatingItem v-slot="{ state }">
  <StarIcon aria-hidden="true" :fill="state.fill === 1 ? 'currentColor' : 'none'" />
</RatingItem>

半星

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

<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { Rating, RatingItem } from "@ui-sdk/vue/rating"
</script>

<template>
  <Rating aria-label="Rating" :step="0.5" :default-value="3.5">
    <RatingItem>
      <StarIcon aria-hidden="true" />
    </RatingItem>
  </Rating>
</template>
选择一颗星的前半部分。这颗星会填满一半。

预览

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

可取消选择

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

<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { Rating, RatingItem } from "@ui-sdk/vue/rating"
</script>

<template>
  <Rating aria-label="Rating" :default-value="4" deselectable>
    <RatingItem>
      <StarIcon aria-hidden="true" />
    </RatingItem>
  </Rating>
</template>
按压第四颗星。分数被清空。

只读

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

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

<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { Rating, RatingItem } from "@ui-sdk/vue/rating"
</script>

<template>
  <Rating
    :value="4.2"
    read-only
    :get-value-label="(value, max) => `Rated ${value} out of ${max}`"
  >
    <RatingItem>
      <StarIcon aria-hidden="true" />
    </RatingItem>
  </Rating>
</template>
平均值 4.2,名称为 Rated 4.2 out of 5。

禁用

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

<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { Rating, RatingItem } from "@ui-sdk/vue/rating"
</script>

<template>
  <Rating aria-label="Rating" :default-value="2" disabled>
    <RatingItem>
      <StarIcon aria-hidden="true" />
    </RatingItem>
  </Rating>
</template>
评分已禁用,所以这些星无法聚焦或按压。

受控

用 v-model:value 绑定值,并监听 @value-change 获取原因。在监听器里调用 details.cancel() 可以保持当前分数。createRatingController() 创建的控制器可以从任何地方设置分数,比如下面的 Clear Rating 按钮。每个挂载的评分各建一个控制器。

控制台
<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { createRatingController, Rating, RatingItem } from "@ui-sdk/vue/rating"
import { ref } from "vue"
import { useLog } from "./log"

const log = useLog()
const rating = createRatingController()
const value = ref<number | null>(4)
</script>

<template>
  <div>
    <div data-slot="controls">
      <button type="button" @click="rating.setValue(null)">Clear Rating</button>
    </div>
    <Rating
      v-model:value="value"
      aria-label="Rating"
      :controller="rating"
      @value-change="
        (next, details) => log(`value: ${next} (${details.reason})`)
      "
    >
      <RatingItem>
        <StarIcon aria-hidden="true" />
      </RatingItem>
    </Rating>
  </div>
</template>
选择一颗星,然后按 Clear Rating。控制台会记录每次变更及其原因。

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

表单

每个单选按钮渲染一个隐藏的原生单选按钮,所以评分能参与表单。设置 name 以提交分数;没有名称或分数时,不提交任何内容。required 会阻止提交,直到有了分数,表单重置会恢复到 default-value。

控制台
<script setup lang="ts">
import { StarIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import { Rating, RatingItem } from "@ui-sdk/vue/rating"
import { useLog } from "./log"

const log = useLog()

function onSubmit(event: SubmitEvent) {
  log(
    `Submitted stay=${new FormData(event.currentTarget as HTMLFormElement).get("stay")}`
  )
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="onSubmit">
    <Field>
      <FieldLabel>Rate your stay</FieldLabel>
      <Rating name="stay" required>
        <RatingItem>
          <StarIcon aria-hidden="true" />
        </RatingItem>
      </Rating>
    </Field>
    <div data-slot="row">
      <button type="submit" data-variant="solid">Send Review</button>
      <button type="reset">Reset</button>
    </div>
  </form>
</template>
不选分数就按 Send Review,查看浏览器的提示。选择一颗星再发送一次。

星与名称

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

<Rating
  aria-label="Difficulty"
  :max="10"
  loop
  :get-value-label="(value, max) => `${value} of ${max}`"
/>

样式

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

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

RatingItem

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

数据属性

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

RatingItem

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

属性与下面相同。onValueChange 是 v-model:value,或用于拿到原因的 @value-change。

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.
@value-change((value: number | null, details: ChangeDetails<RatingValueChangeReason>) => void)
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.

原因

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

控制器

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

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

事件

事件先收到新分数,再收到详情。只有变更事件没有被取消时,v-model 才会更新。

绑定所属部件收到
v-model:valueRating分数,或 null
@value-changeRating(value, details):分数或 null,以及原因

无障碍

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

键盘

按键作用
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。