# 构建组件

构建一个回应栏，然后一步步加上状态、方向键和无障碍支持。

让我们构建一个回应栏，就像聊天消息下方的那种。按压一个回应就能加上它，再按压一次就能收回。

按压一个回应即可切换它。聚焦其中一个，然后用 Left 和 Right 在它们之间移动。

我们先从部件开始，然后一次加一样东西：状态、方向键和无障碍。本页的示例已经设置好样式，方便你看清每一处变化。这些样式我们会在接近结尾时再写。

## 安装
先安装 `@ui-sdk/core` 和你所用框架对应的包。

**React**

```bash
npm add @ui-sdk/core @ui-sdk/react
```

**Vue**

```bash
npm add @ui-sdk/core @ui-sdk/vue
```

**Svelte**

```bash
npm add @ui-sdk/core @ui-sdk/svelte
```

**Solid**

```bash
npm add @ui-sdk/core @ui-sdk/solid
```

**Web Components**

```bash
npm add @ui-sdk/core @ui-sdk/web
```

## 定义原语
**原语（primitive）** 描述一个组件：它的部件、它的状态，以及它做什么。创建 `lib/reactions.ts`，列出各个部件：

```ts title="lib/reactions.ts"
import { definePrimitive } from "@ui-sdk/core"

const reactions = definePrimitive({
  name: "reactions",
  state: () => ({}),
  api: () => ({}),
  slots: (slot) => ({
    root: slot({}),
    reaction: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
    }),
  }),
})

export { reactions }
```

- `name` 给组件命名。根部件的 `data-slot` 就是这个名字本身，`reactions`，其他部件的 `data-slot` 都以它开头，比如 `reactions-reaction`。
- `state` 和 `api` 暂时是空的。我们很快就会填上。
- `slots` 列出各个部件：`root` 包住整条栏，每个按钮是一个 `reaction`。
- `props` 让每个回应接收一个 `value`，比如 `"heart"`，这样栏就能区分它们。

## 渲染部件
`createParts` 把每个槽位变成可以渲染的组件。传入的对象说明每个组件渲染成哪个元素：根部件是 `<div>`，每个回应是 `<button>`。在 Web Components 里，改为给每个部件指定一个自定义元素。

**React**

```tsx title="components/message-reactions.tsx"
"use client"

import { createParts } from "@ui-sdk/react/primitive"
import { reactions } from "@/lib/reactions"

const { Root: Reactions, Reaction } = createParts(reactions, {
  root: "div",
  reaction: "button",
})

function MessageReactions() {
  return (
    <Reactions>
      <Reaction value="thumbs-up">👍</Reaction>
      <Reaction value="heart">❤️</Reaction>
      <Reaction value="laugh">😂</Reaction>
      <Reaction value="celebrate">🎉</Reaction>
    </Reactions>
  )
}

export { MessageReactions }
```

**Vue**

部件只创建一次，放在它们自己的模块里：

```ts title="components/reactions.ts"
import { createParts } from "@ui-sdk/vue/primitive"
import { reactions } from "@/lib/reactions"

const { Root: Reactions, Reaction } = createParts(reactions, {
  root: "div",
  reaction: "button",
})

export { Reaction, Reactions }
```

然后在组件里使用它们：

```vue title="components/MessageReactions.vue"
<script setup lang="ts">
import { Reaction, Reactions } from "./reactions"
</script>

<template>
  <Reactions>
    <Reaction value="thumbs-up">👍</Reaction>
    <Reaction value="heart">❤️</Reaction>
    <Reaction value="laugh">😂</Reaction>
    <Reaction value="celebrate">🎉</Reaction>
  </Reactions>
</template>
```

**Svelte**

```svelte title="components/MessageReactions.svelte"
<script lang="ts">
  import { createParts } from "@ui-sdk/svelte/primitive"
  import { reactions } from "../lib/reactions"

  const { Root: Reactions, Reaction } = createParts(reactions, {
    root: "div",
    reaction: "button",
  })
</script>

<Reactions>
  <Reaction value="thumbs-up">👍</Reaction>
  <Reaction value="heart">❤️</Reaction>
  <Reaction value="laugh">😂</Reaction>
  <Reaction value="celebrate">🎉</Reaction>
</Reactions>
```

**Solid**

```tsx title="components/message-reactions.tsx"
import { createParts } from "@ui-sdk/solid/primitive"
import { reactions } from "@/lib/reactions"

const { Root: Reactions, Reaction } = createParts(reactions, {
  root: "div",
  reaction: "button",
})

function MessageReactions() {
  return (
    <Reactions>
      <Reaction value="thumbs-up">👍</Reaction>
      <Reaction value="heart">❤️</Reaction>
      <Reaction value="laugh">😂</Reaction>
      <Reaction value="celebrate">🎉</Reaction>
    </Reactions>
  )
}

export { MessageReactions }
```

**Web Components**

在应用的浏览器入口处为每个部件注册一个元素。`wrappedButton` 把每个回应的行为放到它内部的 `<button>` 上：

```ts title="components/message-reactions.ts"
import { createParts, wrappedButton } from "@ui-sdk/web"
import { reactions } from "@/lib/reactions"

createParts(reactions, {
  root: "my-reactions",
  reaction: { tag: "my-reaction", target: wrappedButton },
})
```

然后在 HTML 里使用这些元素：

```html title="index.html"
<my-reactions>
  <my-reaction value="thumbs-up">
    <button>👍</button>
  </my-reaction>
  <my-reaction value="heart">
    <button>❤️</button>
  </my-reaction>
  <my-reaction value="laugh">
    <button>😂</button>
  </my-reaction>
  <my-reaction value="celebrate">
    <button>🎉</button>
  </my-reaction>
</my-reactions>
```

你会看到一排四个按钮。每个按钮都有一个 `data-slot`，比如 `data-slot="reactions-reaction"`，但现在按压它还没有任何效果。

## 添加状态
接下来，让我们记住你选了哪些回应。`lib/reactions.ts` 里有四处改动：

```ts title="lib/reactions.ts" {5-15,20,22-24}
import { definePrimitive } from "@ui-sdk/core"

const reactions = definePrimitive({
  name: "reactions",
  state: () => ({ picked: [] as string[] }),
  api: (context) => ({
    toggle: (value: string) => {
      const { picked } = context.store.get()
      context.store.set({
        picked: picked.includes(value)
          ? picked.filter((item) => item !== value)
          : [...picked, value],
      })
    },
  }),
  slots: (slot) => ({
    root: slot({}),
    reaction: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        "aria-pressed": String(state.picked.includes(part.key)),
      }),
      press: ({ api, key }) => api.toggle(key),
    }),
  }),
})

export { reactions }
```

- `state` 保存 `picked`，也就是你选中的那些回应的值。它一开始是空的。
- `api` 定义了 `toggle`，它把一个值加进 `picked`，如果值已经在里面就把它取出来。
- `press` 用回应自己的值调用 `toggle`。在槽位里，`key` 就是部件的 `value`。
- `attrs` 把状态变成属性。被选中的回应会得到 `aria-pressed="true"`，它告诉屏幕阅读器这个回应已打开，也让你可以据此设置样式。

按压一个回应即可选中它，再按压一次就能收回。然后按 Tab：焦点会停在每一个回应上。

## 用方向键移动
这样一排按钮应该只占一个 Tab 停靠点。进入之后，用方向键在它们之间移动。

这就是一个**行为**，`@ui-sdk/core` 里的构建块之一。`createRovingFocus` 让一组部件只有一个 Tab 停靠点，并用方向键移动焦点。把它加到 `lib/reactions.ts`：

```ts title="lib/reactions.ts" {1,5-8,10-14,31,34-41}
import { createRovingFocus, definePrimitive } from "@ui-sdk/core"

const reactions = definePrimitive({
  name: "reactions",
  state: () => ({
    picked: [] as string[],
    focused: null as string | null,
  }),
  api: (context) => ({
    roving: createRovingFocus(context, {
      slot: "reaction",
      key: "focused",
      orientation: () => "horizontal",
    }),
    toggle: (value: string) => {
      const { picked } = context.store.get()
      context.store.set({
        picked: picked.includes(value)
          ? picked.filter((item) => item !== value)
          : [...picked, value],
      })
    },
  }),
  slots: (slot) => ({
    root: slot({}),
    reaction: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        "aria-pressed": String(state.picked.includes(part.key)),
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      press: ({ api, key }) => api.toggle(key),
      on: {
        keydown: (event, { el, api }) => {
          if (el) {
            api.roving.keydown(event, el)
          }
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

export { reactions }
```

- `focused` 是一项新状态。`createRovingFocus` 把拥有 Tab 停靠点的那个回应的值保存在这里。
- `slot` 和 `key` 说明在哪些部件之间移动，以及把停靠点保存在哪里。`orientation` 选择 Left 和 Right。
- `tabIndex` 给停靠点 `0`，其他每个回应 `-1`。
- `keydown` 在你按方向键时移动焦点，`bind` 把每个回应接入这一组。

按 Tab 聚焦这条栏，然后用 Left 和 Right 移动。Home 和 End 跳到第一个和最后一个回应。按 Space 切换。

Home 和 End 是 `createRovingFocus` 自带的，从右到左也一样：在从右到左的页面上，Left 和 Right 会自动互换。

## 让它可访问
这条栏已经能用鼠标和键盘操作。现在让我们告诉屏幕阅读器它是什么。一排只占一个 Tab 停靠点的按钮就是一个**工具栏**。给根部件这个角色：

```ts title="lib/reactions.ts" {25-28}
import { createRovingFocus, definePrimitive } from "@ui-sdk/core"

const reactions = definePrimitive({
  name: "reactions",
  state: () => ({
    picked: [] as string[],
    focused: null as string | null,
  }),
  api: (context) => ({
    roving: createRovingFocus(context, {
      slot: "reaction",
      key: "focused",
      orientation: () => "horizontal",
    }),
    toggle: (value: string) => {
      const { picked } = context.store.get()
      context.store.set({
        picked: picked.includes(value)
          ? picked.filter((item) => item !== value)
          : [...picked, value],
      })
    },
  }),
  slots: (slot) => ({
    root: slot({
      role: "toolbar",
      keys: { none: "Each reaction handles its own arrow keys." },
    }),
    reaction: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        "aria-pressed": String(state.picked.includes(part.key)),
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      press: ({ api, key }) => api.toggle(key),
      on: {
        keydown: (event, { el, api }) => {
          if (el) {
            api.roving.keydown(event, el)
          }
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

export { reactions }
```

- `role` 说明这个部件是什么。这由 Core 替你写入。
- `keys` 说明由谁处理方向键。每种角色都会要求它的模式所需的内容，所以工具栏不写 `keys` 就是类型错误。这里每个回应自己处理按键，所以用 `none` 说明根部件为什么不处理。

单凭一个 emoji 起不了好名字，所以给每个回应一个 `aria-label`，也给这条栏一个：

**React**

```tsx title="components/message-reactions.tsx" {13-14,17,20,23}
"use client"

import { createParts } from "@ui-sdk/react/primitive"
import { reactions } from "@/lib/reactions"

const { Root: Reactions, Reaction } = createParts(reactions, {
  root: "div",
  reaction: "button",
})

function MessageReactions() {
  return (
    <Reactions aria-label="Reactions">
      <Reaction value="thumbs-up" aria-label="Thumbs up">
        👍
      </Reaction>
      <Reaction value="heart" aria-label="Heart">
        ❤️
      </Reaction>
      <Reaction value="laugh" aria-label="Laugh">
        😂
      </Reaction>
      <Reaction value="celebrate" aria-label="Celebrate">
        🎉
      </Reaction>
    </Reactions>
  )
}

export { MessageReactions }
```

**Vue**

```vue title="components/MessageReactions.vue" {6-10}
<script setup lang="ts">
import { Reaction, Reactions } from "./reactions"
</script>

<template>
  <Reactions aria-label="Reactions">
    <Reaction value="thumbs-up" aria-label="Thumbs up">👍</Reaction>
    <Reaction value="heart" aria-label="Heart">❤️</Reaction>
    <Reaction value="laugh" aria-label="Laugh">😂</Reaction>
    <Reaction value="celebrate" aria-label="Celebrate">🎉</Reaction>
  </Reactions>
</template>
```

**Svelte**

```svelte title="components/MessageReactions.svelte" {11-15}
<script lang="ts">
  import { createParts } from "@ui-sdk/svelte/primitive"
  import { reactions } from "../lib/reactions"

  const { Root: Reactions, Reaction } = createParts(reactions, {
    root: "div",
    reaction: "button",
  })
</script>

<Reactions aria-label="Reactions">
  <Reaction value="thumbs-up" aria-label="Thumbs up">👍</Reaction>
  <Reaction value="heart" aria-label="Heart">❤️</Reaction>
  <Reaction value="laugh" aria-label="Laugh">😂</Reaction>
  <Reaction value="celebrate" aria-label="Celebrate">🎉</Reaction>
</Reactions>
```

**Solid**

```tsx title="components/message-reactions.tsx" {11-12,15,18,21}
import { createParts } from "@ui-sdk/solid/primitive"
import { reactions } from "@/lib/reactions"

const { Root: Reactions, Reaction } = createParts(reactions, {
  root: "div",
  reaction: "button",
})

function MessageReactions() {
  return (
    <Reactions aria-label="Reactions">
      <Reaction value="thumbs-up" aria-label="Thumbs up">
        👍
      </Reaction>
      <Reaction value="heart" aria-label="Heart">
        ❤️
      </Reaction>
      <Reaction value="laugh" aria-label="Laugh">
        😂
      </Reaction>
      <Reaction value="celebrate" aria-label="Celebrate">
        🎉
      </Reaction>
    </Reactions>
  )
}

export { MessageReactions }
```

**Web Components**

```html title="index.html" {1,3,6,9,12}
<my-reactions aria-label="Reactions">
  <my-reaction value="thumbs-up">
    <button aria-label="Thumbs up">👍</button>
  </my-reaction>
  <my-reaction value="heart">
    <button aria-label="Heart">❤️</button>
  </my-reaction>
  <my-reaction value="laugh">
    <button aria-label="Laugh">😂</button>
  </my-reaction>
  <my-reaction value="celebrate">
    <button aria-label="Celebrate">🎉</button>
  </my-reaction>
</my-reactions>
```

这就是本页顶部的这条栏。屏幕阅读器会把它播报为 Reactions 工具栏，然后按名称读出每个回应，并说出它是否处于按压状态。

## 为它设置样式
部件渲染出来没有样式。用 `data-slot` 选中部件，用 `aria-pressed` 为被选中的回应设置样式：

```css
[data-slot="reactions"] {
  display: flex;
  gap: 0.25rem;
  padding: 0.25rem;
  border: 1px solid #e5e5e5;
  border-radius: 999px;
}

[data-slot="reactions-reaction"] {
  border: 0;
  border-radius: 999px;
  background: transparent;
  padding: 0.375rem 0.625rem;
  font-size: 1.25rem;

  &:hover {
    background: #f5f5f5;
  }

  &[aria-pressed="true"] {
    background: #fde68a;
  }
}
```

这些属性在每个框架里都一样，所以同一段 CSS 能给全部五个版本设置样式。

## 检查它
`@ui-sdk/core/testing` 里的 `checkPattern` 会按 WAI-ARIA 模式检查渲染后的组件。把这条栏的根元素传给它：

```ts
import { checkPattern } from "@ui-sdk/core/testing"

await checkPattern(root, "toolbar")
```

它会检查工具栏的角色，确认它只有一个 Tab 停靠点，然后按下这些键：方向键、Home 和 End。如果有问题，它会抛出一个错误，列出所有问题。

## 下一步
你已经从零构建了一个组件：部件、状态、一个行为和无障碍。接下来可以从这些地方继续：

- [处理变更](/docs/core/kernel/handle-changes): 在某个回应被选中时通知应用，并让应用决定哪些回应被选中。
- [组合行为](/docs/core/compose-behaviors): 组合行为，构建一个带共享状态和方向键的星级评分。
- [为组件设置样式](/docs/core/kernel/style-a-component): 依据每个部件的 data-slot 和状态所设的属性，用 CSS 或 Tailwind 设置样式。
- [测试](/docs/core/testing): 测试原语的交互、服务端输出和阅读方向。
