用共享状态和键盘导航构建一个星级评分。

到目前为止,每个原语都只有自己的一个行为。现在让我们组合 @ui-sdk/core 里的行为,构建一个五星评分:createChange 上报每一次新的评分,createRovingFocus 管理整个组的 Tab 停靠点和方向键。我们会一次加一个。

从共享状态开始

评分的 value 是一个数字:0 表示还没有评分。defaultValue 设置起始评分。

创建 rating.ts。目前,它有一个容纳星星的根部件,和一个选择值的 rate 函数:

rating.ts
import { createChange, definePrimitive, type ChangeDetails } from "@ui-sdk/core"

type RatingOptions = {
  value?: number
  defaultValue?: number
  onValueChange?: (
    value: number,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const rating = definePrimitive({
  name: "rating",
  options: {
    value: "number",
    defaultValue: "number",
    onValueChange: "callback",
  },
  controlled: ["value"],
  state: (options: RatingOptions) => ({
    value: options.value ?? options.defaultValue ?? 0,
  }),
  sync: (options) =>
    options.value === undefined ? {} : { value: options.value },
  api: (context) => {
    const change = createChange(context)

    return {
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "radiogroup" }),
    }),
  }),
})

export { rating, type RatingOptions }
  • createChange(context) 返回 change。rate 用新的值和原因调用它。它会先调用 onValueChange,然后更新 value,除非回调取消,或者由应用控制。
  • controlled 和 sync 让父级拥有 value。sync 会把新的 value 选项复制进状态。

处理变更 深入介绍变更模式。

在添加星星之前,我们先试试改变值。这些按钮会调用 rate(3) 和 rate(0):

import * as React from "react"
import { createChange, definePrimitive, type ChangeDetails } from "@ui-sdk/core"
import { usePrimitive } from "@ui-sdk/react/primitive"

type RatingOptions = {
  value?: number
  defaultValue?: number
  onValueChange?: (
    value: number,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const rating = definePrimitive({
  name: "rating",
  options: {
    value: "number",
    defaultValue: "number",
    onValueChange: "callback",
  },
  controlled: ["value"],
  state: (options: RatingOptions) => ({
    value: options.value ?? options.defaultValue ?? 0,
  }),
  sync: (options) =>
    options.value === undefined ? {} : { value: options.value },
  api: (context) => {
    const change = createChange(context)

    return {
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "radiogroup" }),
    }),
  }),
})

function Example() {
  const handle = usePrimitive(rating, {})
  const state = React.useSyncExternalStore(
    handle.instance.subscribe,
    handle.instance.get,
    handle.instance.get
  )

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button
          type="button"
          data-size="sm"
          onClick={(event) => handle.api.rate(3, event.nativeEvent)}
        >
          Set to 3
        </button>
        <button
          type="button"
          data-size="sm"
          onClick={(event) => handle.api.rate(0, event.nativeEvent)}
        >
          Reset
        </button>
      </div>
      <div data-slot="rating-readout">
        <output data-slot="rating-value" data-value aria-label="Rating">
          {state.value}
        </output>
        <span data-slot="hint">Rating</span>
      </div>
    </div>
  )
}

export { Example, rating }
按压 Set to 3,再按压 Reset 回到 0。

添加一颗星

添加一个 star 部件。按压它会把评分设为那颗星的值。

在 slots 里、root 旁边加上 star:

star: slot<{ value: string }>({
  props: { value: "string" },
  attrs: (state, part) => ({
    type: "button",
    role: "radio",
    "aria-checked": String(Number(part.key) === state.value),
    "data-filled": Number(part.key) <= state.value ? "" : undefined,
  }),
  press: ({ api, key }, event) => api.rate(Number(key), event),
}),
  • props 给每颗星一个 value,比如 "3"。它会成为这颗星的键。我们用 Number(key) 把它作为数字传给 rate。选项种类 列出了属性(prop)可以取的种类。
  • aria-checked 标记被选中的星。根部件和星星组成一个单选组:从多个选项里选一个。
  • data-filled 标记直到选中项为止的每一颗星,所以选三颗时,前三颗星会填满。
import * as React from "react"
import { StarIcon } from "lucide-react"
import { createParts } from "@ui-sdk/react/primitive"
import { rating } from "../rating-stages/star"

const { Root: Rating, Star: RatingStar } = createParts(rating, {
  root: "div",
  star: "button",
})

function Example() {
  const [value, setValue] = React.useState(0)

  return (
    <div data-slot="stack">
      <div data-slot="rating-readout">
        <output data-slot="rating-value" data-value aria-label="Rating">
          {value}
        </output>
        <span data-slot="hint">Rating</span>
      </div>
      <Rating onValueChange={setValue} aria-label="Rating">
        <RatingStar value="1" aria-label="1 star">
          <StarIcon aria-hidden="true" />
        </RatingStar>
      </Rating>
    </div>
  )
}

export { Example, rating }
按压这颗星。评分变成 1,这颗星会填满。

把五颗星放进组里

现在用同一个部件渲染五颗星。它们共享一个评分,每颗星有自己的值和无障碍名称。

"use client"

import { createParts } from "@ui-sdk/react/primitive"
import { rating } from "./rating"

const { Root: Rating, Star: RatingStar } = createParts(rating, {
  root: "div",
  star: "button",
})

function Example() {
  return (
    <Rating aria-label="Rating">
      {Array.from({ length: 5 }, (_, index) => (
        <RatingStar
          key={index}
          value={String(index + 1)}
          aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
        >
          ★
        </RatingStar>
      ))}
    </Rating>
  )
}

export { Example }

用 data-filled 给星星上色,就像 为组件设置样式 用 data-copied 给复制按钮设置样式那样:

[data-slot="rating"] {
  display: flex;
  gap: 0.25rem;
}

[data-slot="rating-star"][data-filled],
[data-slot="rating-star"]:hover {
  color: #b45309;
}
import * as React from "react"
import { StarIcon } from "lucide-react"
import { createParts } from "@ui-sdk/react/primitive"
import { rating } from "../rating-stages/star"

const { Root: Rating, Star: RatingStar } = createParts(rating, {
  root: "div",
  star: "button",
})

function Example() {
  const [value, setValue] = React.useState(0)

  return (
    <div data-slot="stack">
      <div data-slot="rating-readout">
        <output
          data-slot="rating-value"
          data-value
          aria-label="Rating out of 5"
        >
          {value}
        </output>
        <span data-slot="hint">out of 5</span>
      </div>
      <Rating onValueChange={setValue} aria-label="Rating">
        {Array.from({ length: 5 }, (_, index) => (
          <RatingStar
            key={index}
            value={String(index + 1)}
            aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
          >
            <StarIcon aria-hidden="true" />
          </RatingStar>
        ))}
      </Rating>
    </div>
  )
}

export { Example, rating }
悬停可以预览评分,然后点击选定它。试试 Tab:每颗星仍然有自己的 Tab 停靠点。

让组只有一个 Tab 停靠点

让 Tab 只进入这个组一次,落在选中的星上。如果没有选中项,就落在第一颗星上。

@ui-sdk/core 的 createRovingFocus 负责这件事。把它加到导入里,然后在状态里加上 focused:

state: (options: RatingOptions) => ({
  value: options.value ?? options.defaultValue ?? 0,
  focused: null as string | null,
}),

value 是评分。focused 是拥有 Tab 停靠点的那颗星的键。

更新 api,让它创建这个行为,并和 rate 一起返回:

api: (context) => {
  const change = createChange(context)
  const roving = createRovingFocus(context, {
    slot: "star",
    key: "focused",
    remember: false,
    preferred: (star) => Number(star.key) === context.store.get().value,
    claims: (state, star) => (state.value ? Number(star.key) === state.value : star.key === "1"),
  })

  return {
    roving,
    rate: (value: number, event?: Event) => change("value", value, { reason: "item-press", event }),
  }
},
  • slot 指定要跟踪的部件;key 指定要更新的状态字段。
  • preferred 选择被选中的那颗星。remember: false 让焦点回来时回到这个选择。
  • claims 在元素挂载之前就决定 Tab 停靠点,在服务器上也是如此。它选中被选中的星;没有选择时选第一颗。

现在把星星槽位连接到这个行为。在 attrs 里加上 tabindex,并在 press 旁边加上 bind:

star: slot<{ value: string }>({
  props: { value: "string" },
  attrs: (state, part) => ({
    type: "button",
    role: "radio",
    "aria-checked": String(Number(part.key) === state.value),
    tabindex: part.api.roving.tabIndex(state, part),
    "data-filled": Number(part.key) <= state.value ? "" : undefined,
  }),
  press: ({ api, key }, event) => api.rate(Number(key), event),
  bind: (el, part) => part.api.roving.bind(el, part),
}),

bind 注册每个按钮,并在它卸载时清理。tabIndex 给一颗星 0,其余的 -1。

import * as React from "react"
import { StarIcon } from "lucide-react"
import {
  createChange,
  createRovingFocus,
  definePrimitive,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type RatingOptions = {
  value?: number
  defaultValue?: number
  onValueChange?: (
    value: number,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const rating = definePrimitive({
  name: "rating",
  options: {
    value: "number",
    defaultValue: "number",
    onValueChange: "callback",
  },
  controlled: ["value"],
  state: (options: RatingOptions) => ({
    value: options.value ?? options.defaultValue ?? 0,
    focused: null as string | null,
  }),
  sync: (options) =>
    options.value === undefined ? {} : { value: options.value },
  api: (context) => {
    const change = createChange(context)
    const roving = createRovingFocus(context, {
      slot: "star",
      key: "focused",
      remember: false,
      preferred: (star) => Number(star.key) === context.store.get().value,
      claims: (state, star) =>
        state.value ? Number(star.key) === state.value : star.key === "1",
    })

    return {
      roving,
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "radiogroup" }),
    }),
    star: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        role: "radio",
        "aria-checked": String(Number(part.key) === state.value),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-filled": Number(part.key) <= state.value ? "" : undefined,
      }),
      press: ({ api, key }, event) => api.rate(Number(key), event),
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const { Root: Rating, Star: RatingStar } = createParts(rating, {
  root: "div",
  star: "button",
})

function Example() {
  const [value, setValue] = React.useState(0)

  return (
    <div data-slot="stack">
      <div data-slot="rating-readout">
        <output
          data-slot="rating-value"
          data-value
          aria-label="Rating out of 5"
        >
          {value}
        </output>
        <span data-slot="hint">out of 5</span>
      </div>
      <Rating onValueChange={setValue} aria-label="Rating">
        {Array.from({ length: 5 }, (_, index) => (
          <RatingStar
            key={index}
            value={String(index + 1)}
            aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
          >
            <StarIcon aria-hidden="true" />
          </RatingStar>
        ))}
      </Rating>
    </div>
  )
}

export { Example, rating }
选择一颗星。Tab 离开这个组;Shift+Tab 回到你的选择。

用方向键移动

createRovingFocus 处理方向键、Home 和 End,以及从右到左(RTL)的布局。默认情况下它使用 Up 和 Down,像垂直列表一样。

对这个评分来说,我们需要全部四个方向键,而且最后一颗星应该绕回第一颗。在 createRovingFocus 的选项里加上 orientation 和 loop:

orientation: () => "both",
loop: () => true,

Down 和 Right 移到下一颗星,Up 和 Left 移到上一颗。在从右到左的布局里,Left 和 Right 互换。Home 和 End 跳到第一颗和最后一颗星。

行为负责移动焦点;评分决定选中什么。在 api 返回的对象里、rate 旁边加上 keydown:

keydown(event: KeyboardEvent, el: HTMLElement) {
  const moved = roving.keydown(event, el)
  if (moved) {
    change("value", Number(moved.key), { reason: "list-navigation", event })
  }
},

点击和方向键都会经过 createChange。onValueChange 回调会收到新的值和原因:item-press 或 list-navigation。

最后,连接星星的按键事件。在它的 press 和 bind 字段旁边加上 on:

on: {
  keydown: (event, { el, api }) => {
    if (el) {
      api.keydown(event, el)
    }
  },
},
import * as React from "react"
import { StarIcon } from "lucide-react"
import {
  createChange,
  createRovingFocus,
  definePrimitive,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type RatingOptions = {
  value?: number
  defaultValue?: number
  onValueChange?: (
    value: number,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const rating = definePrimitive({
  name: "rating",
  options: {
    value: "number",
    defaultValue: "number",
    onValueChange: "callback",
  },
  controlled: ["value"],
  state: (options: RatingOptions) => ({
    value: options.value ?? options.defaultValue ?? 0,
    focused: null as string | null,
  }),
  sync: (options) =>
    options.value === undefined ? {} : { value: options.value },
  api: (context) => {
    const change = createChange(context)
    const roving = createRovingFocus(context, {
      slot: "star",
      key: "focused",
      orientation: () => "both",
      loop: () => true,
      remember: false,
      preferred: (star) => Number(star.key) === context.store.get().value,
      claims: (state, star) =>
        state.value ? Number(star.key) === state.value : star.key === "1",
    })
    return {
      roving,
      rate: (value: number, event?: Event) =>
        change("value", value, { reason: "item-press", event }),
      keydown(event: KeyboardEvent, el: HTMLElement) {
        const moved = roving.keydown(event, el)
        if (moved) {
          change("value", Number(moved.key), {
            reason: "list-navigation",
            event,
          })
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "radiogroup" }),
    }),
    star: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        role: "radio",
        "aria-checked": String(Number(part.key) === state.value),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-filled": Number(part.key) <= state.value ? "" : undefined,
      }),
      press: ({ api, key }, event) => api.rate(Number(key), event),
      on: {
        keydown: (event, { el, api }) => {
          if (el) {
            api.keydown(event, el)
          }
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(rating, { root: "div", star: "button" })

const Rating = parts.Root

const RatingStar = parts.Star

function Example() {
  const [value, setValue] = React.useState(3)
  return (
    <div data-slot="stack">
      <div data-slot="rating-readout">
        <output
          data-slot="rating-value"
          data-value
          aria-label="Rating out of 5"
        >
          {value}
        </output>
        <span data-slot="hint">out of 5</span>
      </div>
      <Rating value={value} onValueChange={setValue} aria-label="Rating">
        {Array.from({ length: 5 }, (_, index) => (
          <RatingStar
            key={index}
            value={String(index + 1)}
            aria-label={`${index + 1} ${index === 0 ? "star" : "stars"}`}
          >
            <StarIcon aria-hidden="true" />
          </RatingStar>
        ))}
      </Rating>
    </div>
  )
}

export { Example, rating, Rating, RatingStar, type RatingOptions }
用方向键改变评分。Home 和 End 跳到第一颗和最后一颗星。

检查行为

我们可以直接测试这个共享原语。下面是一个很小的 Vitest 测试,它选择三颗星并检查值:

// rating.test.ts
import { expect, test } from "vitest"
import { rating } from "./rating"

test("choosing a star changes the rating", () => {
  const instance = rating({ id: "rating" })
  instance.api.rate(3)
  expect(instance.get().value).toBe(3)
})

要检查焦点和键盘操作,就渲染组件,并运行 @ui-sdk/core/testing 的 checkPattern(root, "radio-group")。测试 展示了怎么做。

完整原语

下面是我们添加的所有内容,放在一个文件里:

继续构建

接下来,处理变更 会进一步讲解这个评分用到的变更模式:回调、受控状态、提交和撤销。

  • 自定义行为 给这个评分添加按键,并修改它的规则。
  • 焦点与按键 介绍网格,以及在组里移动的其他方式。
  • 测试 检查组件的键盘行为和无障碍。