feat: migrate Tag, TagGroup and ErrorMessage with collection and focus contracts

Port the fixed HeroUI baseline tag/tag-group/error-message components onto the
existing collection selection/registry protocols instead of a second state model.

- TagGroup owns selection, disabled scope, removal requests and name/description
  wiring; TagGroupList renders the role=grid node and Tag renders role=row.
- Removal has one path: a press inside the remove subtree is a removal request,
  so custom remove buttons work without a second event source; focus follows the
  next neighbour only after the item is actually gone.
- ErrorMessage keeps the baseline slot marker and reuses the field part ids
  without gaining validation or aria-invalid semantics.
- Ship the 12 tag-group and 2 error-message previews, both doc pages, navigation,
  a 35-case behavioural suite and independent tarball consumption checks.
This commit is contained in:
maoyingjie
2026-10-25 10:45:43 +08:00
parent 3532cc6aad
commit af6bfda3ee
40 changed files with 3790 additions and 4 deletions
+10
View File
@@ -110,6 +110,11 @@ export const componentItems: DocsItem[] = [
url: "/components/empty-state",
category: "feedback",
},
{
title: "ErrorMessage 错误消息",
url: "/components/error-message",
category: "forms",
},
{
title: "FieldError 字段错误",
url: "/components/field-error",
@@ -260,6 +265,11 @@ export const componentItems: DocsItem[] = [
url: "/components/tabs",
category: "navigation",
},
{
title: "TagGroup 标签组",
url: "/components/tag-group",
category: "collections",
},
{
title: "TextArea 多行文本框",
url: "/components/textarea",
+124
View File
@@ -0,0 +1,124 @@
---
title: ErrorMessage 错误消息
description: 用于展示错误的底层错误消息组件
component: error-message
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import { ErrorMessage } from "@heroui-vue/components";
</script>
<template>
<ErrorMessage>请至少选择一个分类</ErrorMessage>
</template>
```
<ComponentPreview name="error-message-basic" />
`ErrorMessage` 是基于固定基线 `Text` 组件 `errorMessage` slot 的底层组件,用于在 **非表单组件**(如 `TagGroup`、`Calendar` 及其他集合类组件)中展示错误消息。
## 组件结构
```vue
<script setup lang="ts">
import {
Description,
ErrorMessage,
Label,
Tag,
TagGroup,
TagGroupList,
} from "@heroui-vue/components";
</script>
<template>
<TagGroup>
<Label>分类</Label>
<TagGroupList>
<Tag id="news">资讯</Tag>
</TagGroupList>
<Description>说明</Description>
<ErrorMessage>请至少选择一个分类</ErrorMessage>
</TagGroup>
</template>
```
## 何时使用
`ErrorMessage` **不绑定表单**,是用于非表单上下文的通用错误展示组件。
- **推荐用于** 非表单组件(如 `TagGroup`、`Calendar`、集合类组件)
- **表单字段** 建议使用 [FieldError](./field-error),它提供表单专用校验特性与自动错误处理,遵循标准化表单校验模式
## ErrorMessage 与 FieldError
| 组件 | 使用场景 | 表单集成 | 示例组件 |
| -------------- | ---------- | -------- | ------------------------------------ |
| `ErrorMessage` | 非表单组件 | 否 | `TagGroup`、`Calendar` |
| `FieldError` | 表单字段 | 是 | `TextField`、`NumberField`、`Select` |
表单校验建议使用 `FieldError`,它遵循标准化表单校验模式并提供表单专用特性。
## 自定义样式
### Tailwind CSS
<ComponentPreview name="error-message-custom-styles" />
### 全局 CSS
可使用 `@layer components` 指令自定义 ErrorMessage 组件类。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-error-message {
@apply text-sm font-medium text-danger;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。类名前缀为 `hv-`。
### CSS 类
ErrorMessage 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/error-message.css)):
#### 基础类 [!toc]
- `.hv-error-message` - 基础错误消息样式,danger 色与文本换行
#### 插槽类 [!toc]
- `[slot="errorMessage"]` - 与固定基线一致的 DOM 标记,可用作 CSS 选择器
- `[data-slot="error-message"]` - 组件标记
## API 参考
### ErrorMessage
| Prop | 类型 | 默认值 | 描述 |
| -------- | --------------------------- | ------ | ----------------------------- |
| `id` | `string` | 自动 | 元素 id;位于字段内时参与描述 |
| 默认插槽 | `Component` | - | 错误消息内容 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
## 说明
`ErrorMessage` 渲染为 `<p>`,带 `slot="errorMessage"` 与 `data-slot="error-message"` 标记;在 Vue 中 `slot` 是普通 DOM 属性(CSS 钩子),不是插槽分配——直接把 `ErrorMessage` 放进父组件的默认插槽即可。显示与隐藏由调用方根据自身状态控制,组件本身不做校验。
## 无障碍
- 使用语义化 HTML 展示错误文本
- 放在字段或标签组内时,其 `id` 会进入所属容器的 `aria-describedby`
- 错误状态使用主题的 danger 色,保持足够对比度
- 上游经 `Text` 的 `errorMessage` slot 提供节点;本库保留同样的 DOM 标记,但不改写 `TagGroup` 的 `aria-invalid`
## 相关组件
[FieldError 字段错误](./field-error) · [Description 描述](./description) · [TagGroup 标签组](./tag-group)
+285
View File
@@ -0,0 +1,285 @@
---
title: TagGroup 标签组
description: 可聚焦的标签列表,支持键盘导航、选择与移除。
component: tag-group
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import { Tag, TagGroup, TagGroupList } from "@heroui-vue/components";
</script>
<template>
<TagGroup aria-label="标签" selection-mode="single">
<TagGroupList>
<Tag id="news">资讯</Tag>
<Tag id="travel">旅行</Tag>
</TagGroupList>
</TagGroup>
</template>
```
<ComponentPreview name="tag-group-basic" />
`TagGroup` 是标签集合的根部件,负责选择状态、禁用范围、移除请求与名称/描述关联;`TagGroupList` 渲染真正的 `role="grid"` 容器,`Tag` 渲染 `role="row"` 条目。上游的对象式子部件 `TagGroup.List`、`Tag.RemoveButton` 在本库中是具名导出 `TagGroupList`、`TagRemoveButton`。
## 组件结构
```vue
<script setup lang="ts">
import {
Description,
ErrorMessage,
Label,
Tag,
TagGroup,
TagGroupList,
TagRemoveButton,
} from "@heroui-vue/components";
</script>
<template>
<TagGroup>
<Label>分类</Label>
<TagGroupList>
<Tag id="news">
资讯
<TagRemoveButton />
</Tag>
</TagGroupList>
<Description>说明</Description>
<ErrorMessage>错误</ErrorMessage>
</TagGroup>
</template>
```
`Label`、`Description`、`ErrorMessage` 直接放在 `TagGroup` 的默认插槽中:它们的 `id` 会作为列表节点的 `aria-labelledby` / `aria-describedby`,不要再写 React 的 `slot="..."` 形式。
## 示例
### 尺寸
<ComponentPreview name="tag-group-sizes" />
### 变体
<ComponentPreview name="tag-group-variants" />
### 禁用
<ComponentPreview name="tag-group-disabled" />
### 选择模式
<ComponentPreview name="tag-group-selection-modes" />
### 受控组件
<ComponentPreview name="tag-group-controlled" />
### 带错误信息
<ComponentPreview name="tag-group-with-error-message" />
### 带列表数据
<ComponentPreview name="tag-group-with-list-data" />
### 带前缀
<ComponentPreview name="tag-group-with-prefix" />
### 带移除按钮
<ComponentPreview name="tag-group-with-remove-button" />
### 渲染函数
<ComponentPreview name="tag-group-render-function" />
上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(使用自定义组件作为唯一根)。本库示例用 `as="section"` 演示同一能力。
## 自定义样式
### Tailwind CSS
<ComponentPreview name="tag-group-custom-styles" />
### 全局 CSS
若要自定义组件类,可使用 `@layer components` 指令。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-tag-group {
@apply flex flex-col gap-2;
}
.hv-tag-group__list {
@apply flex flex-wrap gap-2;
}
.hv-tag {
@apply rounded-full px-3 py-1;
}
.hv-tag__remove-button {
@apply ml-1;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。类名前缀为 `hv-`。
### CSS 类
TagGroup 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/tag-group.css) 与 [tag.css](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/tag.css)):
#### 基础类 [!toc]
- `.hv-tag-group` - TagGroup 根容器
- `.hv-tag-group__list` - 标签列表容器
- `.hv-tag` - 标签基础样式
- `.hv-tag__remove-button` - 移除按钮触发器
#### 插槽类 [!toc]
- `.hv-tag-group [data-slot="description"]` - Description 插槽样式
- `.hv-tag-group [data-slot="error-message"]` - ErrorMessage 插槽样式
#### 尺寸类 [!toc]
- `.hv-tag--sm` - 小尺寸标签
- `.hv-tag--md` - 中尺寸标签(默认)
- `.hv-tag--lg` - 大尺寸标签
#### 变体类 [!toc]
- `.hv-tag--default` - 默认变体
- `.hv-tag--surface` - 带 Surface 背景的变体
#### 状态类 [!toc]
- `.hv-tag[data-selected="true"]` - 选中状态
- `.hv-tag[data-disabled="true"]` - 禁用状态
- `.hv-tag[data-hovered="true"]` - 悬停状态
- `.hv-tag[data-pressed="true"]` - 按下状态
- `.hv-tag[data-focus-visible="true"]` - 聚焦状态(键盘焦点)
### 交互状态
该组件同时支持 CSS 伪类与 data 属性:
- **悬停**:标签上 `:hover` 或 `[data-hovered="true"]`
- **聚焦**:标签上 `:focus-visible` 或 `[data-focus-visible="true"]`
- **按下**:标签上 `:active` 或 `[data-pressed="true"]`
- **已选中**:标签上 `[data-selected="true"]` 或 `[aria-selected="true"]`
- **禁用**:标签上 `[aria-disabled="true"]` 或 `[data-disabled="true"]`
## API 参考
### TagGroup
| Prop | 类型 | 默认值 | 描述 |
| -------------------------- | ---------------------------------- | ------------------- | -------------------------------------------------------- |
| `selection-mode` | `'none' \| 'single' \| 'multiple'` | `'none'` | 允许的选择类型 |
| `model-value` | `Array<string \| number>` | - | 当前选中的 key(受控,`v-model`) |
| `selected-keys` | `Array<string \| number>` | - | 当前选中的 key(`model-value` 的别名,受控) |
| `default-value` | `Array<string \| number>` | - | 初始选中的 key(非受控) |
| `default-selected-keys` | `Array<string \| number>` | - | 初始选中的 key(非受控,`default-value` 的别名) |
| `disabled-keys` | `Array<string \| number>` | `[]` | 禁用标签的 key |
| `is-disabled` | `boolean` | `false` | 是否禁用整个 TagGroup |
| `disallow-empty-selection` | `boolean` | `false` | 是否阻止用户清空已有选择 |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | 组内标签尺寸 |
| `variant` | `'default' \| 'surface'` | `'default'` | 标签视觉变体 |
| `dir` | `'ltr' \| 'rtl'` | 继承 ConfigProvider | 水平方向键的导航方向 |
| `as` | `string` | `'div'` | 自定义根元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 |
| 默认插槽 | `Component` | - | 组内容(Label、TagGroupList、Description、ErrorMessage) |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
事件:
| 事件 | 载荷 | 描述 |
| ------------------- | ------------------------- | ---------------------------------------------------- |
| `update:modelValue` | `Array<string \| number>` | 选择变化时发出(配合 `v-model`) |
| `selectionChange` | `Array<string \| number>` | 选择变化时发出 |
| `remove` | `Array<string \| number>` | 用户请求移除标签时发出;不包含在数据中删除条目的行为 |
`aria-label`、`aria-labelledby`、`aria-describedby` 会落在 `role="grid"` 的列表节点,而不是外层容器。
### TagGroupList
| Prop | 类型 | 默认值 | 描述 |
| ------------ | --------------------------------- | ------- | ------------------------------------------------------------- |
| `items` | `Array<{ id: string \| number }>` | - | 数据驱动渲染;每项需要 `id`,作用域插槽接收 `item` 与 `index` |
| `as` | `string` | `'div'` | 自定义列表元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为列表节点并合并属性 |
| 默认插槽 | `{ item, index }` | - | 标签列表内容;提供 `items` 时按数据渲染 |
| `empty` 插槽 | - | - | `items` 为空时的内容 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
### Tag
| Prop | 类型 | 默认值 | 描述 |
| ------------- | --------------------------- | ------- | -------------------------------------------------- |
| `id` | `string \| number` | - | 标签唯一标识(必填,集合 key) |
| `text-value` | `string` | - | 标签内容的字符串表示,用于无障碍名称与移除按钮名称 |
| `is-disabled` | `boolean` | `false` | 是否禁用该标签 |
| `as` | `string` | `'div'` | 自定义行元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为行节点并合并属性 |
| 默认插槽 | `{ ...TagRenderState }` | - | 标签内容;作用域提供渲染状态 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
**提示:** `size`、`variant` 由父级 `TagGroup` 继承,不能在单个 `Tag` 上直接设置。
### TagRemoveButton
| Prop | 类型 | 默认值 | 描述 |
| ------------- | --------------------------- | ------- | ------------------------------------------ |
| `text-value` | `string` | - | 供无障碍名称使用的标签文本;未传时取父 Tag |
| `is-disabled` | `boolean` | `false` | 是否禁用移除按钮 |
| 默认插槽 | `Component` | - | 自定义移除按钮内容(默认为关闭图标) |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
**提示:** 为 `TagGroup` 监听 `remove` 时:
- **自动渲染**:若 `Tag` 的子节点中未包含 `TagRemoveButton`,会自动渲染默认移除按钮。
- **自定义按钮**:若在 `Tag` 下提供了 `TagRemoveButton`,将替换自动渲染的按钮。
- **自定义图标**:可向 `TagRemoveButton` 传入自定义插槽内容改变外观。
默认按钮的可访问名称为 `Remove tag {标签文本}`;移除按钮的点击不会触发选择变化。
### 作用域插槽状态
`Tag` 的默认插槽提供以下渲染状态:
| 字段 | 类型 | 描述 |
| ---------------- | --------- | ---------------------- |
| `isSelected` | `boolean` | 标签是否选中 |
| `isDisabled` | `boolean` | 标签是否禁用 |
| `isHovered` | `boolean` | 标签是否悬停 |
| `isPressed` | `boolean` | 标签是否按下 |
| `isFocused` | `boolean` | 标签是否聚焦 |
| `isFocusVisible` | `boolean` | 标签是否为可见键盘焦点 |
| `allowsRemoving` | `boolean` | 组是否允许移除 |
上游 `children` 渲染函数对应 Vue 的作用域插槽。
## 无障碍
- 列表节点为 `role="grid"`,每个标签为 `role="row"`,行的可访问名称来自其文本内容。
- 方向键在标签之间移动焦点(RTL 下左右互换),`Home` / `End` 跳到第一个 / 最后一个标签;禁用标签会被跳过。
- `Enter` 与 `Space` 切换选中(`Space` 在 `keyup` 时激活,调用方可通过 `preventDefault` 取消)。
- `Backspace` / `Delete` 在允许移除时请求移除当前聚焦标签。
- 移除确认后焦点移到原位置的下一个标签,删除最后一项时回到列表本身;父级拒绝删除时标签与焦点都保留。
- 列表节点声明 `aria-atomic="false"` 与 `aria-relevant="additions text"`,集合内容的增删会被读屏软件播报。
## 相关组件
[Chip 标签](./chip) · [Description 描述](./description) · [ErrorMessage 错误消息](./error-message) · [Label 标签](./label)
+29
View File
@@ -0,0 +1,29 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Description,
ErrorMessage,
Label,
Tag,
TagGroup,
TagGroupList,
type TagKey,
} from "@heroui-vue/components";
const selected = ref<TagKey[]>([]);
const isInvalid = computed(() => selected.value.length === 0);
</script>
<template>
<TagGroup v-model="selected" selection-mode="multiple">
<Label>必选分类</Label>
<TagGroupList>
<Tag id="news">新闻</Tag>
<Tag id="travel">旅游</Tag>
<Tag id="gaming">游戏</Tag>
<Tag id="shopping">购物</Tag>
</TagGroupList>
<Description>请至少选择一个分类</Description>
<ErrorMessage>{{ isInvalid ? "请至少选择一个分类" : "" }}</ErrorMessage>
</TagGroup>
</template>
@@ -0,0 +1,34 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Description,
ErrorMessage,
Label,
Tag,
TagGroup,
TagGroupList,
type TagKey,
} from "@heroui-vue/components";
const selected = ref<TagKey[]>([]);
const isInvalid = computed(() => selected.value.length === 0);
</script>
<template>
<TagGroup
v-model="selected"
class="w-full max-w-xs gap-1.5"
selection-mode="multiple"
>
<Label>主题</Label>
<TagGroupList>
<Tag id="api">API</Tag>
<Tag id="design">设计</Tag>
<Tag id="docs">文档</Tag>
</TagGroupList>
<Description>请至少选择一个主题</Description>
<ErrorMessage class="font-medium text-danger">
{{ isInvalid ? "请至少选择一个主题" : "" }}
</ErrorMessage>
</TagGroup>
</template>
+32
View File
@@ -0,0 +1,32 @@
<script setup lang="ts">
import {
IconArticle,
IconPlanet,
IconRocket,
IconShoppingBag,
} from "@tabler/icons-vue";
import { Tag, TagGroup, TagGroupList } from "@heroui-vue/components";
</script>
<template>
<TagGroup aria-label="标签" selection-mode="single">
<TagGroupList>
<Tag id="default-news">
<IconArticle aria-hidden="true" />
资讯
</Tag>
<Tag id="default-travel">
<IconPlanet aria-hidden="true" />
旅行
</Tag>
<Tag id="default-gaming">
<IconRocket aria-hidden="true" />
游戏
</Tag>
<Tag id="default-shopping">
<IconShoppingBag aria-hidden="true" />
购物
</Tag>
</TagGroupList>
</TagGroup>
</template>
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Description,
Label,
Tag,
TagGroup,
TagGroupList,
type TagKey,
} from "@heroui-vue/components";
const selected = ref<TagKey[]>(["news", "travel"]);
const summary = computed(() =>
selected.value.length > 0 ? selected.value.join(", ") : "无",
);
</script>
<template>
<div class="flex flex-col gap-3">
<TagGroup v-model="selected" selection-mode="multiple">
<Label>分类(受控)</Label>
<TagGroupList>
<Tag id="news">资讯</Tag>
<Tag id="travel">旅行</Tag>
<Tag id="gaming">游戏</Tag>
<Tag id="shopping">购物</Tag>
</TagGroupList>
<Description>已选:{{ summary }}</Description>
</TagGroup>
</div>
</template>
@@ -0,0 +1,38 @@
<script setup lang="ts">
import {
IconArticle,
IconPlanet,
IconRocket,
IconShoppingBag,
} from "@tabler/icons-vue";
import { Tag, TagGroup, TagGroupList } from "@heroui-vue/components";
const tagClass =
"group/tag gap-1.5 rounded-full border border-neutral-300/80 bg-white/80 px-2.5 py-1 text-sm font-medium text-neutral-700 shadow-sm ring-1 ring-black/5 backdrop-blur-sm transition-colors data-[selected=true]:border-neutral-500 data-[selected=true]:bg-neutral-900 data-[selected=true]:text-neutral-50 dark:border-neutral-600/80 dark:bg-neutral-900/60 dark:text-neutral-200 dark:ring-white/10 dark:data-[selected=true]:border-neutral-400 dark:data-[selected=true]:bg-neutral-100 dark:data-[selected=true]:text-neutral-900";
const iconClass =
"size-4 shrink-0 text-neutral-500 group-data-[selected=true]/tag:text-current dark:text-neutral-400";
</script>
<template>
<TagGroup aria-label="主题" selection-mode="single">
<TagGroupList class="gap-2">
<Tag id="custom-news" :class="tagClass">
<IconArticle aria-hidden="true" :class="iconClass" />
资讯
</Tag>
<Tag id="custom-travel" :class="tagClass">
<IconPlanet aria-hidden="true" :class="iconClass" />
旅行
</Tag>
<Tag id="custom-gaming" :class="tagClass">
<IconRocket aria-hidden="true" :class="iconClass" />
游戏
</Tag>
<Tag id="custom-shopping" :class="tagClass">
<IconShoppingBag aria-hidden="true" :class="iconClass" />
购物
</Tag>
</TagGroupList>
</TagGroup>
</template>
+33
View File
@@ -0,0 +1,33 @@
<script setup lang="ts">
import {
Description,
Label,
Tag,
TagGroup,
TagGroupList,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-4">
<TagGroup selection-mode="single">
<Label>已禁用的标签</Label>
<TagGroupList>
<Tag id="disabled-news" is-disabled>资讯</Tag>
<Tag id="disabled-travel">旅行</Tag>
<Tag id="disabled-gaming" is-disabled>游戏</Tag>
</TagGroupList>
<Description>部分标签已禁用</Description>
</TagGroup>
<TagGroup :disabled-keys="['travel']" selection-mode="single">
<Label>禁用的键</Label>
<TagGroupList>
<Tag id="news">资讯</Tag>
<Tag id="travel">旅行</Tag>
<Tag id="gaming">游戏</Tag>
</TagGroupList>
<Description>通过 disabledKeys 属性禁用的标签</Description>
</TagGroup>
</div>
</template>
@@ -0,0 +1,38 @@
<script setup lang="ts">
import {
IconArticle,
IconPlanet,
IconRocket,
IconShoppingBag,
} from "@tabler/icons-vue";
import { Tag, TagGroup, TagGroupList } from "@heroui-vue/components";
</script>
<template>
<!-- Upstream 的 render 函数在此对应 as(自定义根元素标签)。 -->
<TagGroup
aria-label="标签"
as="section"
data-custom="foo"
selection-mode="single"
>
<TagGroupList>
<Tag id="render-news">
<IconArticle aria-hidden="true" />
资讯
</Tag>
<Tag id="render-travel">
<IconPlanet aria-hidden="true" />
旅行
</Tag>
<Tag id="render-gaming">
<IconRocket aria-hidden="true" />
游戏
</Tag>
<Tag id="render-shopping">
<IconShoppingBag aria-hidden="true" />
购物
</Tag>
</TagGroupList>
</TagGroup>
</template>
@@ -0,0 +1,40 @@
<script setup lang="ts">
import { ref } from "vue";
import {
Description,
Label,
Tag,
TagGroup,
TagGroupList,
type TagKey,
} from "@heroui-vue/components";
const singleSelected = ref<TagKey[]>(["news"]);
const multipleSelected = ref<TagKey[]>(["news", "travel"]);
</script>
<template>
<div class="flex flex-col gap-8">
<TagGroup v-model="singleSelected" selection-mode="single">
<Label>单选</Label>
<TagGroupList>
<Tag id="single-news">资讯</Tag>
<Tag id="single-travel">旅行</Tag>
<Tag id="single-gaming">游戏</Tag>
<Tag id="single-shopping">购物</Tag>
</TagGroupList>
<Description>选择一个分类</Description>
</TagGroup>
<TagGroup v-model="multipleSelected" selection-mode="multiple">
<Label>多选</Label>
<TagGroupList>
<Tag id="multiple-news">资讯</Tag>
<Tag id="multiple-travel">旅行</Tag>
<Tag id="multiple-gaming">游戏</Tag>
<Tag id="multiple-shopping">购物</Tag>
</TagGroupList>
<Description>选择多个分类</Description>
</TagGroup>
</div>
</template>
+32
View File
@@ -0,0 +1,32 @@
<script setup lang="ts">
import { Label, Tag, TagGroup, TagGroupList } from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-6">
<TagGroup selection-mode="single" size="sm">
<Label>小</Label>
<TagGroupList>
<Tag id="sm-news">资讯</Tag>
<Tag id="sm-travel">旅行</Tag>
<Tag id="sm-gaming">游戏</Tag>
</TagGroupList>
</TagGroup>
<TagGroup selection-mode="single" size="md">
<Label>中</Label>
<TagGroupList>
<Tag id="md-news">资讯</Tag>
<Tag id="md-travel">旅行</Tag>
<Tag id="md-gaming">游戏</Tag>
</TagGroupList>
</TagGroup>
<TagGroup selection-mode="single" size="lg">
<Label>大</Label>
<TagGroupList>
<Tag id="lg-news">资讯</Tag>
<Tag id="lg-travel">旅行</Tag>
<Tag id="lg-gaming">游戏</Tag>
</TagGroupList>
</TagGroup>
</div>
</template>
+25
View File
@@ -0,0 +1,25 @@
<script setup lang="ts">
import { Label, Tag, TagGroup, TagGroupList } from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-8">
<TagGroup selection-mode="single" variant="default">
<Label>默认</Label>
<TagGroupList>
<Tag id="default-news">资讯</Tag>
<Tag id="default-travel">旅行</Tag>
<Tag id="default-gaming">游戏</Tag>
</TagGroupList>
</TagGroup>
<TagGroup selection-mode="single" variant="surface">
<Label>表面</Label>
<TagGroupList>
<Tag id="surface-news">资讯</Tag>
<Tag id="surface-travel">旅行</Tag>
<Tag id="surface-gaming">游戏</Tag>
</TagGroupList>
</TagGroup>
</div>
</template>
@@ -0,0 +1,32 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Description,
ErrorMessage,
Label,
Tag,
TagGroup,
TagGroupList,
type TagKey,
} from "@heroui-vue/components";
const selected = ref<TagKey[]>([]);
const isInvalid = computed(() => selected.value.length === 0);
</script>
<template>
<TagGroup v-model="selected" selection-mode="multiple">
<Label>设施</Label>
<TagGroupList>
<Tag id="laundry">洗衣</Tag>
<Tag id="fitness">健身中心</Tag>
<Tag id="parking">停车</Tag>
<Tag id="pool">游泳池</Tag>
<Tag id="breakfast">早餐</Tag>
</TagGroupList>
<Description>
{{ isInvalid ? "请至少选择一个分类" : "已选:" + selected.join(", ") }}
</Description>
<ErrorMessage>{{ isInvalid ? "请至少选择一个分类" : "" }}</ErrorMessage>
</TagGroup>
</template>
@@ -0,0 +1,121 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
Avatar,
AvatarFallback,
AvatarImage,
Description,
EmptyState,
Label,
Tag,
TagGroup,
TagGroupList,
type TagKey,
} from "@heroui-vue/components";
type User = {
id: string;
name: string;
avatar: string;
fallback: string;
};
const users = ref<User[]>([
{
avatar:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
fallback: "F",
id: "fred",
name: "Fred",
},
{
avatar:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
fallback: "M",
id: "michael",
name: "Michael",
},
{
avatar:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
fallback: "J",
id: "jane",
name: "Jane",
},
{
avatar:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/red.jpg",
fallback: "A",
id: "alice",
name: "Alice",
},
{
avatar:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/orange.jpg",
fallback: "B",
id: "bob",
name: "Bob",
},
{
avatar:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/black.jpg",
fallback: "C",
id: "charlie",
name: "Charlie",
},
]);
const selectedKeys = ref<TagKey[]>(["fred", "michael"]);
function onRemove(keys: TagKey[]) {
users.value = users.value.filter((user) => !keys.includes(user.id));
}
const selectedUsers = computed(() =>
users.value.filter((user) => selectedKeys.value.includes(user.id)),
);
</script>
<template>
<div class="w-sm">
<TagGroup
v-model="selectedKeys"
selection-mode="multiple"
@remove="onRemove"
>
<Label>团队成员</Label>
<TagGroupList :items="users">
<template #default="{ item }">
<Tag :id="item.id" :key="item.id" :text-value="item.name">
<Avatar class="size-4" size="sm">
<AvatarImage :src="item.avatar" />
<AvatarFallback>{{ item.fallback }}</AvatarFallback>
</Avatar>
{{ item.name }}
</Tag>
</template>
<template #empty>
<EmptyState class="p-1">暂无团队成员</EmptyState>
</template>
</TagGroupList>
<Description>为项目选择团队成员</Description>
</TagGroup>
<div v-if="selectedUsers.length > 0" class="mt-4 flex flex-col gap-2">
<p class="text-sm font-medium text-muted">已选:</p>
<div class="flex flex-wrap gap-2">
<div
v-for="user in selectedUsers"
:key="`${user.id}-selected`"
class="flex items-center gap-2 rounded-lg bg-surface-tertiary px-2 py-1"
>
<Avatar class="size-4" size="sm">
<AvatarImage :src="user.avatar" />
<AvatarFallback>{{ user.fallback }}</AvatarFallback>
</Avatar>
<span class="text-sm">{{ user.name }}</span>
</div>
</div>
</div>
</div>
</template>
+79
View File
@@ -0,0 +1,79 @@
<script setup lang="ts">
import {
IconArticle,
IconPlanet,
IconRocket,
IconShoppingBag,
} from "@tabler/icons-vue";
import {
Avatar,
AvatarFallback,
AvatarImage,
Description,
Label,
Tag,
TagGroup,
TagGroupList,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-8">
<TagGroup selection-mode="single">
<Label>带图标</Label>
<TagGroupList>
<Tag id="icon-news">
<IconArticle aria-hidden="true" />
News
</Tag>
<Tag id="icon-travel">
<IconPlanet aria-hidden="true" />
Travel
</Tag>
<Tag id="icon-gaming">
<IconRocket aria-hidden="true" />
Gaming
</Tag>
<Tag id="icon-shopping">
<IconShoppingBag aria-hidden="true" />
Shopping
</Tag>
</TagGroupList>
<Description>带图标的标签</Description>
</TagGroup>
<TagGroup selection-mode="single">
<Label>带头像</Label>
<TagGroupList>
<Tag id="avatar-fred">
<Avatar class="size-4">
<AvatarImage
src="https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg"
/>
<AvatarFallback>F</AvatarFallback>
</Avatar>
Fred
</Tag>
<Tag id="avatar-michael">
<Avatar class="size-4">
<AvatarImage
src="https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg"
/>
<AvatarFallback>M</AvatarFallback>
</Avatar>
Michael
</Tag>
<Tag id="avatar-jane">
<Avatar class="size-4">
<AvatarImage
src="https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg"
/>
<AvatarFallback>J</AvatarFallback>
</Avatar>
Jane
</Tag>
</TagGroupList>
<Description>带头像的标签</Description>
</TagGroup>
</div>
</template>
@@ -0,0 +1,88 @@
<script setup lang="ts">
import { ref } from "vue";
import { IconCircleXFilled } from "@tabler/icons-vue";
import {
Description,
EmptyState,
Label,
Tag,
TagGroup,
TagGroupList,
TagRemoveButton,
type TagKey,
type TagRenderState,
} from "@heroui-vue/components";
type TagItem = { id: string; name: string };
const tags = ref<TagItem[]>([
{ id: "news", name: "资讯" },
{ id: "travel", name: "旅行" },
{ id: "gaming", name: "游戏" },
{ id: "shopping", name: "购物" },
]);
const frameworks = ref<TagItem[]>([
{ id: "react", name: "React" },
{ id: "vue", name: "Vue" },
{ id: "angular", name: "Angular" },
{ id: "svelte", name: "Svelte" },
]);
function onRemoveTags(keys: TagKey[]) {
tags.value = tags.value.filter((tag) => !keys.includes(tag.id));
}
function onRemoveFrameworks(keys: TagKey[]) {
frameworks.value = frameworks.value.filter(
(framework) => !keys.includes(framework.id),
);
}
function allowsRemoving(state: TagRenderState) {
return state.allowsRemoving;
}
</script>
<template>
<div class="flex flex-col gap-8">
<div class="w-sm">
<TagGroup selection-mode="single" @remove="onRemoveTags">
<Label>默认移除按钮</Label>
<TagGroupList :items="tags">
<template #default="{ item }">
<Tag :id="item.id" :key="item.id" :text-value="item.name">
{{ item.name }}
</Tag>
</template>
<template #empty>
<EmptyState class="p-1">未找到分类</EmptyState>
</template>
</TagGroupList>
<Description>点击 × 移除标签</Description>
</TagGroup>
</div>
<div class="w-md">
<TagGroup selection-mode="single" @remove="onRemoveFrameworks">
<Label>自定义移除按钮</Label>
<TagGroupList :items="frameworks">
<template #default="{ item }">
<Tag :id="item.id" :key="item.id" :text-value="item.name">
<template #default="state">
{{ item.name }}
<TagRemoveButton v-if="allowsRemoving(state)">
<IconCircleXFilled aria-hidden="true" />
</TagRemoveButton>
</template>
</Tag>
</template>
<template #empty>
<EmptyState class="p-1">未找到框架</EmptyState>
</template>
</TagGroupList>
<Description>带图标的自定义移除按钮</Description>
</TagGroup>
</div>
</div>
</template>
+3 -3
View File
@@ -34,7 +34,7 @@
| time-field | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| disclosure | 验证中(M21) | Disclosure/Heading/Trigger/Content/Body/Indicator;3/3 基线例;v-model:expanded;asChild 触发;高度动画映射测量变量 |
| disclosure-group | 验证中(M22) | DisclosureGroup + useDisclosureGroupNavigation;3/3 基线例;展开键为数组(string 或 number);单选替换/多选增量 |
| error-message | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| error-message | 已迁移(有已知差异) | ErrorMessage 单部件;2/2 基线例;复用字段错误 id 与样式变量,`slot="errorMessage"` 仅为 DOM 标记,不做校验也不改 aria-invalid;见 B03 报告 |
| kbd | 验证中(最小实现) | variant;KbdAbbr keyValue 映射与 title;KbdContent;上下文类名;导出 kbdKeysMap/LabelMap |
| link | 验证中(最小实现) | 原生 a + LinkIcon;isDisabled/asChild/焦点与 data 状态;默认图标为基线 ExternalLinkIcon;onPress 由 click 适配 |
| popover | 验证中(OVERLAY-02) | Root/Trigger/Content/Dialog/Heading/Arrow;6/6 基线例;逻辑定位/碰撞/退出/标题;模态 closeAutoFocus 不支持取消恢复,见 OVERLAY-02 |
@@ -48,8 +48,8 @@
| switch | 验证中(最小实现) | 根字段与组合部件、3 尺寸、ARIA 透传、原生/ARIA 校验、FormData/reset;PressEvent 不等价 |
| switch-group | 验证中(布局) | vertical/horizontal;不共享选择值,已移植基线 CSS |
| tabs | 验证中(M25) | 七部件、10/10 基线例;primary/secondary、方向/对齐、受控/键盘/禁用/滚动/指示器;Vue 模型与 ID/集合差异见报告 |
| tag | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| tag-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
| tag | 已迁移(有已知差异) | Tag/TagRemoveButton;与 TagGroup 同页 12 例;textValue 决定文字与移除按钮名称 `Remove tag {文本}`;移除由行统一处理;见 B03 报告 |
| tag-group | 已迁移(有已知差异) | TagGroup/TagGroupList 两部件;role=grid/row、single/multiple、disabledKeys、移除与焦点恢复、aria-labelledby/describedby;12/12 基线例;见 B03 报告 |
| toggle-button-group | 验证中(M28) | ToggleButtonGroup/Separator;10/10 基线例;single/multiple、disallowEmptySelection、roving focus;Vue 数组模型替代 Set<Key> |
| toolbar | 验证中(M29) | Toolbar;5/5 基线例;isAttached/orientation/dir;跨组单 Tab 入口与方向键;子组焦点让位;Separator 垂直继承 |
| tooltip | 验证中(OVERLAY-02) | Root/Trigger/Content/Arrow;6/6 基线例;CSS 延迟/焦点/禁用/替换/定位;Provider warmup 与 RAC 全局调度不同 |
+176
View File
@@ -0,0 +1,176 @@
# B03 Tag / TagGroup / ErrorMessage 迁移报告
分支 `feat/b03-tag-error-message`,起点 `3532cc6`(本地 main,含 B01 合并 `836752d`、交接说明 `3532cc6`)。**未合 main、未推送**。独立 worktree `heroui-vue-b03`(`heroui-vue-b01` 当时有 5181 开发服务运行,未在其 checkout 切分支)。
固定基线 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`。开发端口 5183。
## 1. 源公开契约
### 源文件
- `packages/react/src/components/tag/tag.tsx`、`tag-group/tag-group.tsx`、`error-message/error-message.tsx`
- `packages/styles/components/{tag,tag-group,error-message}.css`
- `packages/styles/src/components/{tag,tag-group,error-message}/*.styles.ts`
- 中文正文:`apps/docs/content/docs/cn/react/components/(collections)/tag-group.mdx`、`(forms)/error-message.mdx`
- 演示:`apps/docs/src/demos/cn/tag-group`(12 例)、`demos/cn/error-message`(2 例)
- 行为证据(RAC 未安装、无法读源码,用上游测试代替):`packages/react/tests/components/{tag-group,tag,error-message}`
### 部件与公开能力
| 源部件 | 公开 Props / 事件 | 状态与状态标记 |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `TagGroup` | selectionMode、selectedKeys、defaultSelectedKeys、onSelectionChange、disabledKeys、isDisabled、onRemove、size、variant、className、children、render | 组级禁用、单选/多选、移除回调;`data-slot="tag-group"` |
| `TagGroup.List` | items、renderEmptyState、className、children、render | `role="grid"`、`aria-label`/`aria-labelledby`/`aria-describedby`、`aria-atomic`/`aria-relevant` |
| `Tag` | id、textValue、isDisabled、className、children(含 render props)、render | `role="row"`、`aria-selected`/`aria-disabled`、`data-selected`/`data-disabled`/`data-hovered`/`data-pressed`/`data-focus-visible` |
| `Tag.RemoveButton` | className、children | 默认渲染条件 `allowsRemoving`;可访问名称 `Remove tag {文本}`;点击不改变选择 |
| `ErrorMessage` | className、children | `<p class="error-message" slot="errorMessage" data-slot="error-message">`,仅展示、不校验 |
上游测试确认的契约:网格下有若干 `row`;`aria-label` 或 `Label` 命名网格;单选点击切换 `aria-selected`;`disabledKeys` 与 `isDisabled` 输出 `aria-disabled`;默认移除按钮存在时可访问名称为 `Remove tag News`;`Delete` 键移除当前聚焦标签并调用 `onRemove(Set)`;`size`/`variant` 在 `Tag` 上渲染为 `tag--lg`/`tag--surface`;自定义 `Tag.RemoveButton` 替换默认按钮。
### 预览清单(顺序与固定正文一致)
tag-group:basic、sizes、variants、disabled、selection-modes、controlled、with-error-message、with-list-data、with-prefix、with-remove-button、render-function、custom-styles(12)。
error-message:basic、custom-styles(2)。
## 2. 实现映射
| 层 | 实现 |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 状态 | 复用 `collection/selection`(`useCollectionSelection`)与 `collection/registry`,未修改内核 |
| 组件 | `TagGroup`(状态/注册/焦点/移除/名称关联)、`TagGroupList`(grid 节点)、`Tag`(row)、`TagRemoveButton`、`ErrorMessage` |
| 插槽 | 全部使用具名/作用域插槽:`Tag` 默认插槽提供 `TagRenderState`,`TagGroupList` 提供 `{ item, index }` 与 `empty` |
| 事件 | `update:modelValue`、`selectionChange`、`remove`(载荷为 `TagKey[]`,替代 React 的 `Set<Key>`) |
| 描述关联 | `TagGroup` 提供 `fieldContextKey`(kind=group),`Label`/`Description`/`ErrorMessage` 经 `useFieldPart` 注册;渲染期 id 规划保证首次渲染即可正确 `aria-labelledby`/`aria-describedby` |
| 样式 | 三个 CSS 文件按上游数值移植,仅加 `hv-` 前缀;tv 变体加入 `@heroui-vue/styles` |
| 底座差异 | 未使用 Reka 的集合组件(无对应 grid/row 语义),按本地 choice/collection 协议组合原生 DOM |
公开 API 摘要:
- `TagGroup`:`selection-mode`、`model-value`/`selected-keys`/`default-value`/`default-selected-keys`、`disabled-keys`、`is-disabled`、`disallow-empty-selection`、`size`、`variant`、`dir`、`as`、`as-child`;`@update:model-value`、`@selection-change`、`@remove`。
- `TagGroupList`:`items`(需 `id`)、`as`、`as-child`;默认插槽 `{ item, index }`、`empty` 插槽。
- `Tag`:`id`(必填)、`text-value`、`is-disabled`、`as`、`as-child`;作用域插槽状态 `isSelected`/`isDisabled`/`isHovered`/`isPressed`/`isFocused`/`isFocusVisible`/`allowsRemoving`。
- `TagRemoveButton`:`text-value`、`is-disabled`;默认插槽替换图标。
- `ErrorMessage`:无自有 Props(`id`/`class` 为普通属性),默认插槽为内容。
## 3. 命令与真实结果
| 命令 | 结果 |
| --------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `pnpm typecheck` | 通过 |
| `pnpm test` | **74 文件 / 973 项**通过(新增 `tests/tag-error-message.test.ts` 35 项);连跑两次一致 |
| `pnpm build:docs` | 退出码 0(含 SSG 预渲染) |
| `pnpm format` | 通过(提交前已仅对本批文件执行 `--write`) |
| `git diff --check` | 通过 |
| `node consume-b03-tag-error-message.mjs`(独立消费者) | 通过:11 项导出、SSR HTML 契约、8 类 CSS 选择器与 list 内边距规则 |
| `tsc --moduleResolution bundler` / `nodenext`(契约文件) | 两种模式均通过;4 个 `@ts-expect-error` 反例实际触发 |
独立消费目录 `/private/tmp/heroui-b03-consumer`:`pnpm pack` 两份 tarball + `pnpm-workspace.yaml` overrides(pnpm 11 写法),无源码 alias。
### 新增/修改文件
- 新增:`packages/styles/components/{tag,tag-group,error-message}.css`、`packages/vue/src/components/tag/*`、`packages/vue/src/components/error-message/ErrorMessage.vue`、`apps/docs/components/{tag-group,error-message}.md`、14 个 `apps/docs/demos/*.vue`、`tests/tag-error-message.test.ts`、`tests/package/{consume-b03-tag-error-message.mjs,b03-tag-error-message-contract.ts}`
- 增量修改:`packages/styles/index.css`(3 行 import)、`packages/styles/src/index.ts`(3 个 tv,追加)、`packages/vue/src/index.ts`(导出,追加)、`packages/vue/src/types.ts`(Props 类型,追加)、`apps/docs/.vitepress/theme/navigation.ts`(2 条)、`package.json`(test:unit 列表)
- 未改动:共享 collection/field/choice 内核、Toast/Table 文件、文档外壳样式、锁文件、`apps/docs/.vitepress/theme/style.css`
## 4. 浏览器重点证据
127.0.0.1:5183(strictPort),浅色 + 深色。
- 语义:`role="grid"` + `aria-label="标签"`;行 `role="row"`;`Label` 在组内渲染为 `span` 并成为 `aria-labelledby`;Description 与 ErrorMessage 的 id 同时进入 `aria-describedby`。
- 选择:点击 `资讯` 后 `aria-selected/data-selected` 同步,背景 `oklab(0.6204 -0.0543052 -0.187286 / 0.2)`(accent-soft),字体 12px、圆角 12px、内边距 4px 8px。
- 键盘:`ArrowRight` 资讯→旅行、`End`→购物、`Space` 选中购物并取消资讯(单选替换);`:focus-visible` 与 `data-focus-visible="true"` 同时成立,2px surface + 4px focus 双层焦点环。
- 移除:按钮 12×12,`::after` 命中区 24×24;点击后 `旅行` 消失,焦点落到 `游戏`。
- 尺寸/变体/禁用:sm 2px 8px、md 4px 8px、lg 6px 10px/14px/16px;surface 背景 `oklch(1 0 0)`;`isDisabled` 与 `disabledKeys` 均 `aria-disabled`/`data-disabled` + opacity 0.5;深色默认背景 `oklch(0.274 0.006 286.033)`。
- 文档:6 张正文表格均 728px(= 正文宽度)、`display: table`、`table-layout: fixed`、`scrollWidth === clientWidth`;侧栏顺序 EmptyState → ErrorMessage → FieldError、TagGroup 在 Tabs 与 TextArea 之间;ErrorMessage 页输出 `<p class="hv-error-message" slot="errorMessage">`。
## 5. 上游差异(逐项记录)
1. **部件命名**:`TagGroup.List` / `Tag.RemoveButton` → 具名导出 `TagGroupList` / `TagRemoveButton`(项目公共 API 约定)。
2. **render 函数**:React `render` 自定义 DOM 元素 → Vue `as`(标签名)与 `as-child`(唯一子元素)。render-function 示例用 `as="section"` 演示同一能力。
3. **`useListData`**:Vue 无对应公共 hook,with-list-data 示例改为响应式数组 + 计算 selected,保留数据驱动、移除、空状态与已选展示。
4. **数据驱动列表的 key**:`TagGroupList` 的 `items` 要求每项带 `id`(作用域插槽自行渲染 `Tag`,`:key` 由调用方给出),等价于 RAC 从渲染函数返回元素取 key。
5. **`FieldSlotsGate` / RAC `TextContext`**:该 gate 只为 RAC 集合的隐藏渲染趟次服务;Vue 端集合不存在隐藏趟次,改为字段上下文注册 + 渲染期 id 规划(`prepare`),首次渲染即写出正确 `aria-labelledby`/`aria-describedby`。未移植该 gate。
6. **`ErrorMessage` 的 `slot` 属性**:保留为普通 DOM 属性(CSS 钩子,样式表同时匹配 `[slot="errorMessage"]` 与 `[data-slot="error-message"]`),在 Vue 中写成 `slot="..."` 放在父组件上会被当作插槽分配,文档已提示直接放默认插槽。
7. **`ErrorMessage` 的 ARIA**:上游经 `TextContext` 提供节点但不设置 `aria-invalid`/`aria-errormessage`;本库把已渲染的 ErrorMessage id 并入所属组的 `aria-describedby`(增补项,未改变校验语义),并明确不覆盖 `FieldError`。
8. **移除按钮名称**:`Remove tag {标签文本}` 与固定基线测试字符串一致;自定义移除按钮由 `Tag` 克隆时注入 `text-value`,因此也能得到同样名称。
9. **移除事件载荷**:`onRemove(Set<Key>)` → `@remove(TagKey[])`。
10. **额外接受的能力**:`dir`、`disallowEmptySelection`、`as`/`as-child`。RAC 支持但基线文档表格未列;已写入本库 API 表。
11. **单选语义**:单击已选中标签会取消选择(RAC 默认 toggle 行为),`disallow-empty-selection` 可阻止清空。
12. **无表单值**:TagGroup 不生成隐藏 input、不参与 FormData,与基线一致。
## 6. 验证边界与未验证项
- 未做逐像素视觉对比;尺寸/配色以计算样式核对。
- 未做读屏软件实测;`aria-atomic="false"` + `aria-relevant="additions text"` 依据 RAC `useTagGroup` 的 TagList 属性,未在真实 AT 上复验播报。
- 未验证物理触屏、窄屏断点截图、RTL 视觉(RTL 仅由单测覆盖方向键翻转)。
- 截图:本轮首次截图成功(页面顶部),随后 IAB 合成器持续返回 `capture timed out`,因此后续证据全部改用计算样式与 DOM 查询;未以旧截图冒充新证据。
- 未建立自动 visual/浏览器测试入口(项目现状),浏览器结论来自本轮手工重点验证。
## 7. 共享缺口与需要注意的环境问题
**(重要)Vue 事件 invoker 的同毫秒跳过**:`@vue/runtime-dom` 的 `createInvoker` 在 `e._vts <= invoker.attached` 时直接返回,`invoker.attached` 来自按微任务缓存的 `Date.now()`。若在 `mount()` 后**同一毫秒内**同步 `dispatchEvent` 一个合成事件,监听器会被静默跳过,表现为「事件处理器有时不执行」,并且**同一个事件上后运行的处理器更容易被跳过**(先运行的处理器写入 `e._vts`)。本轮一开始把它误判为 CloseButton 缺陷,实际是测试环境现象:浏览器中用户点击远晚于监听器挂载时间,不会触发该守卫。本批做法:单测统一用 `settle()`(`setTimeout(2)`)跨过该毫秒,并在报告中记录,避免后续批次再次误判为组件缺陷。**没有为此改动任何共享组件**。
其他缺口:
- `CloseButton` 被 `TagRemoveButton` 复用(视觉与基线一致,含默认 CloseIcon)。若后续批次要给 `CloseButton` 增加自带 `@click` 语义,需要回归本组件的移除路径。
- 移除逻辑集中在 `Tag` 行的点击处理:命中 `[data-slot="tag-remove-button"]` 时请求移除而非选择。这样自定义移除按钮(不经 `TagRemoveButton`)也能工作,且只有一条移除路径(不会重复触发)。
- 复制示例代码沿用文档站既有能力,未新增文档外壳改动。
## 8. 集成增量(便于解决共享文件冲突)
导出(`packages/vue/src/index.ts`,追加在文件末尾):
```ts
export { default as Tag } from "./components/tag/Tag.vue";
export { default as TagGroup } from "./components/tag/TagGroup.vue";
export { default as TagGroupList } from "./components/tag/TagGroupList.vue";
export { default as TagRemoveButton } from "./components/tag/TagRemoveButton.vue";
export type {
TagProps,
TagGroupProps,
TagGroupListProps,
TagRemoveButtonProps,
} from "./types";
export type {
TagKey,
TagGroupDataItem,
TagRenderState,
TagGroupOptions,
} from "./components/tag/context";
export { default as ErrorMessage } from "./components/error-message/ErrorMessage.vue";
export type { ErrorMessageProps } from "./types";
export {
tagVariants,
tagGroupVariants,
errorMessageVariants,
type TagVariants,
type TagGroupVariants,
type ErrorMessageVariants,
} from "@heroui-vue/styles";
```
样式入口(`packages/styles/index.css`):
```css
@import "./components/error-message.css" layer(components); /* description.css 之后 */
@import "./components/tag-group.css" layer(components); /* dropdown.css 之后 */
@import "./components/tag.css" layer(components);
```
样式变体(`packages/styles/src/index.ts` 末尾追加):`tagVariants`(slots: base/removeButton;size sm/md/lg;variant default/surface)、`tagGroupVariants`(base/list)、`errorMessageVariants`(base)。
导航(`apps/docs/.vitepress/theme/navigation.ts`):`ErrorMessage 错误消息`(forms,EmptyState 之后)、`TagGroup 标签组`(collections,Tabs 之后)。
依赖:无新增。`@tabler/icons-vue` 仅用于 apps/docs(既有依赖)。
兼容矩阵条目已写入 `docs/compatibility.md`(tag / tag-group / error-message 三行)。
## 9. 复核最短路径
1. `pnpm typecheck && pnpm test`(重点看 `tests/tag-error-message.test.ts` 35 项)。
2. `pnpm dev:docs`(5183)打开 `/components/tag-group`:
- 点击「资讯」→ 选中;`ArrowRight`/`End`/`Space` 检查焦点与选择;
- 「带移除按钮」第一组点 `旅行` 的 ×,确认标签消失且焦点落到「游戏」;
- 检查 sm/md/lg 间距、surface 背景、禁用透明度 0.5、键盘焦点环。
3. 打开 `/components/error-message`:确认两个示例渲染 `<p class="hv-error-message" slot="errorMessage">`,并检查 API 表满宽无溢出。
4. 独立消费:把 `tests/package/{consume-b03-tag-error-message.mjs,b03-tag-error-message-contract.ts}` 复制到工作区外的新工程,装两份 `pnpm pack` 产物后执行脚本 + 两种 `tsc` 模式。
+6
View File
@@ -202,3 +202,9 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生
## B01 Menu / Dropdown(2026-10-24)
固定 ce90ea3 的 `packages/react/src/components/{menu,menu-item,menu-section,dropdown}`、`packages/styles/components/{menu,menu-item,menu-section,dropdown}.css` 与对应 tv,中文 `(collections)/dropdown.mdx` 及 `demos/cn/dropdown` 17 例。样式加 hv- 前缀;演示图标采用 Tabler Vue。Menu/Item/Section 无独立 Web 文档页(native menu.mdx 属 heroui-native,不作为本契约)。底座为安装版 Reka 2.11 DropdownMenu,未复制 React 源码构建。
## B03 Tag / TagGroup / ErrorMessage(2026-10-25)
固定 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`:`packages/react/src/components/{tag,tag-group,error-message}`、`packages/styles/components/{tag,tag-group,error-message}.css`、`packages/styles/src/components/{tag,tag-group,error-message}/*.styles.ts`,中文 `(collections)/tag-group.mdx`、`(forms)/error-message.mdx` 与 `demos/cn/tag-group` 12 例、`demos/cn/error-message` 2 例。Tag 无独立文档页,按固定 tag-group 正文与示例迁移。
CSS/tv 仅加 `hv-` 前缀与 Vue 状态适配,保留 Apache-2.0 来源。TagRemoveButton 复用本库 CloseButton 与基线 CloseIcon,可访问名称为 `Remove tag {标签文本}`(固定基线测试的同一字符串)。上游 `TagGroup.List` / `Tag.RemoveButton` 在本库为具名导出 `TagGroupList` / `TagRemoveButton`;React `render` 函数对应 `as` / `as-child`;`useListData` 演示改为 Vue 响应式数组。RAC 的 `FieldSlotsGate`/`TextContext` 只在集合渲染时需要,Vue 端改用字段上下文与渲染期 id 规划,不移植该 gate。无新增依赖,未运行时依赖相邻 React 仓库。
+24
View File
@@ -985,3 +985,27 @@ Button/PopoverTrigger/Link/ToggleButtonGroup 源码及几何复核后,移除
## 2026-10-25 B01 最终验收
整批23项复核回归通过;集成人修正CSS.escape测试补丁边界并将相关探针加入test:unit入口。最终pnpm test为73文件/938项通过,无未捕获错误;typecheck、build:docs和diff检查通过。独立消费夹具真实浏览器确认子菜单First向上循环至Last。范围及限制见 `migrations/B01-final-acceptance.md`,不新增SSR/水合/Nuxt要求,未合main、未推送。
## 2026-10-25 B03 Tag / TagGroup / ErrorMessage
迁移与差异范围见 [B03 报告](migrations/B03-tag-error-message.md):Tag、TagGroup、TagGroupList、TagRemoveButton、ErrorMessage 五部件,TagGroup 12 例 + ErrorMessage 2 例,分支 `feat/b03-tag-error-message`(起点 `3532cc6`,未合 main、未推送)。
### 自动化
- `pnpm typecheck`:通过(vue-tsc --noEmit)。
- `pnpm test`:**74 文件 / 973 项**通过(本批新增 `tests/tag-error-message.test.ts` 35 项,同时加入 `test:unit` 显式列表);连续两次执行结果一致。
- `pnpm build:docs`:退出码 0;SSG 预渲染阶段曾在 `elementFromRef` 触发 `Element is not defined`,已用非浏览器环境保护修复后重跑通过。
- `pnpm format`(prettier --check .)与 `git diff --check`:通过。
- 独立 tarball 消费(`/private/tmp/heroui-b03-consumer`,pnpm 11.25.0 + 两份 `pnpm pack` 产物):`node consume-b03-tag-error-message.mjs` 通过(11 项导出、SSR HTML 契约、CSS 选择器);`b03-tag-error-message-contract.ts` 在 `--moduleResolution bundler` 与 `nodenext` 两种模式下通过,4 个 `@ts-expect-error` 反例均实际触发。
### 浏览器重点验证(127.0.0.1:5183,Chromium/IAB,浅色 + 深色)
- 语义:列表 `role="grid"`、`aria-label` 来自 TagGroup 的 `aria-label`,行 `role="row"`;`Label` 存在时 `aria-labelledby` 指向 Label(`span`),Description/ErrorMessage 的 id 进入 `aria-describedby`。
- 选择:点击行后 `aria-selected/data-selected` 同步,选中态背景为 `accent-soft`(`oklab(0.6204 -0.0543052 -0.187286 / 0.2)`),单选用 `ArrowRight`/`End` 移动焦点(资讯→旅行→购物),`Space` 切换后原选中项取消。
- 尺寸/变体:`sm` 2px 8px/12px/12px、`md` 4px 8px/12px/12px、`lg` 6px 10px/14px/16px;`surface` 背景为 `oklch(1 0 0)`,`default` 为 `oklch(0.94 0.001 286.375)`;深色下默认背景 `oklch(0.274 0.006 286.033)`、文字 `oklch(0.9911 0 0)`。
- 禁用:`isDisabled` 与 `disabledKeys` 均输出 `aria-disabled="true"`/`data-disabled="true"`,计算透明度 0.5。
- 移除:移除按钮 12×12,`::after` 提供 24×24 命中区;点击后该标签消失,焦点落到原位置的下一个标签(旅行被移除后落到游戏)。
- 焦点环:键盘聚焦标签时 `:focus-visible` 与 `data-focus-visible="true"` 同时成立,`status-focused` 上屏(2px surface + 4px focus 双层 box-shadow)。
- 文档:API 表格全部 728px = 正文宽度、`display: table`、`table-layout: fixed`、`scrollWidth === clientWidth`(长 16 行与短 4 行表均无横向溢出);侧栏顺序为 EmptyState → ErrorMessage → FieldError,TagGroup 位于 Tabs 与 TextArea 之间;ErrorMessage 页面渲染 `<p class="hv-error-message" slot="errorMessage">`。
未验证:逐像素对比、读屏软件、物理触屏、窄屏断点截图。截图在本轮首次采集后 IAB 合成器不再返回帧(`capture timed out`),因此尺寸/配色改为计算样式断言,未以旧截图充当本轮证据。
+1 -1
View File
@@ -15,7 +15,7 @@
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
"typecheck": "vue-tsc --noEmit",
"test": "vitest run",
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/b01-menu-dropdown.test.ts tests/b01-review.probe.test.ts tests/b01-complete-review.probe.test.ts tests/cssom.test.ts",
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/b01-menu-dropdown.test.ts tests/b01-review.probe.test.ts tests/b01-complete-review.probe.test.ts tests/cssom.test.ts tests/tag-error-message.test.ts",
"test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts tests/select-ssr.test.ts tests/date-foundation-ssr.test.ts tests/date-field-ssr.test.ts tests/m35-m36-ssr.test.ts",
"format": "prettier --check .",
"format:fix": "prettier --write .",
@@ -0,0 +1,15 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
/* Base error message styles */
.hv-error-message {
@apply h-auto text-xs wrap-break-word text-danger;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
opacity 150ms var(--ease-out),
height 350ms var(--ease-smooth);
@apply motion-reduce:transition-none;
}
+17
View File
@@ -0,0 +1,17 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
/* Base styles */
.hv-tag-group {
@apply relative flex flex-col gap-1;
}
.hv-tag-group__list {
@apply relative flex flex-wrap gap-1.5;
}
.hv-tag-group [slot="description"],
.hv-tag-group [data-slot="description"],
.hv-tag-group [slot="errorMessage"],
.hv-tag-group [data-slot="error-message"] {
@apply p-1;
}
+114
View File
@@ -0,0 +1,114 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* Tag component styles */
.hv-tag {
--optical-offset: 0.031em;
@apply relative inline-flex items-center gap-1 rounded-xl font-medium select-none no-highlight;
/* Default size - matches .hv-tag--md */
@apply px-2 py-1 text-xs;
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition:
color 100ms var(--ease-smooth),
scale 100ms var(--ease-smooth),
opacity 100ms var(--ease-smooth),
background-color 100ms var(--ease-smooth),
box-shadow 100ms var(--ease-out);
@apply origin-center transform-gpu motion-reduce:transition-none;
/* Cursor */
cursor: var(--cursor-interactive);
/* SVG icon styling */
& svg {
@apply pointer-events-none size-3 shrink-0 self-center text-current;
}
}
/* Disabled state */
.hv-tag:is([data-disabled="true"], [aria-disabled="true"]) {
@apply status-disabled;
}
/* Focus visible state (keyboard focus only) */
.hv-tag:is(:focus-visible, [data-focus-visible]) {
@apply status-focused;
}
/* Pressed/Active state */
.hv-tag:is(:active, [data-pressed="true"]) {
}
/* Selected state */
.hv-tag:is([data-selected="true"], [aria-selected="true"]) {
@apply bg-accent-soft text-accent-soft-foreground;
/* Selected + Hover state */
@media (hover: hover) {
&:is(:hover, [data-hovered="true"]) {
@apply bg-accent-soft-hover;
}
}
}
/* Size */
.hv-tag--sm {
@apply px-2 py-0.5 text-xs;
}
.hv-tag--md {
/* No styles as this is the default size */
}
.hv-tag--lg {
@apply rounded-2xl px-2.5 py-1.5 text-sm;
}
/* Variant */
.hv-tag--default {
@apply bg-default text-default-foreground;
/* Hover state (when not selected or disabled) */
@media (hover: hover) {
&:is(:hover, [data-hovered="true"]):not([data-selected="true"]):not(
[data-disabled="true"]
) {
@apply bg-default-hover;
}
}
}
.hv-tag--surface {
@apply bg-surface text-surface-foreground;
/* Hover state (when not selected or disabled) */
@media (hover: hover) {
&:is(:hover, [data-hovered="true"]):not([data-selected="true"]):not(
[data-disabled="true"]
) {
@apply bg-surface-hover;
}
}
}
/* Remove Button */
.hv-tag__remove-button {
/**
* The glyph is 12px, half the minimum target size. A finger tap that misses it lands on the
* tag body, which consumes the press without removing anything, so removing a tag by touch
* takes several attempts. `touch-target` widens the pressable area to 24px. On `--sm` the
* overlay reaches ~2px past the tag box, which the 6px list gap absorbs, so it never
* overlaps a neighbouring tag.
*/
@apply touch-target size-3 text-inherit;
/* SVG icon styling */
& svg {
@apply size-[inherit] shrink-0 self-center text-current;
}
}
+3
View File
@@ -15,6 +15,7 @@
@import "./components/switch-group.css" layer(components);
@import "./components/label.css" layer(components);
@import "./components/description.css" layer(components);
@import "./components/error-message.css" layer(components);
@import "./components/surface.css" layer(components);
/* Keep breadcrumbs before link.css, matching the baseline component order.
* Breadcrumb link rules then override Link defaults, while Link's disabled
@@ -153,6 +154,8 @@
@import "./components/menu-item.css" layer(components);
@import "./components/menu-section.css" layer(components);
@import "./components/dropdown.css" layer(components);
@import "./components/tag-group.css" layer(components);
@import "./components/tag.css" layer(components);
@import "./components/select.css" layer(components);
+49
View File
@@ -1627,3 +1627,52 @@ export const dropdownVariants = tv({
});
export type DropdownVariants = VariantProps<typeof dropdownVariants>;
export const tagVariants = tv({
defaultVariants: {
size: "md",
variant: "default",
},
slots: {
base: "hv-tag",
removeButton: "hv-tag__remove-button",
},
variants: {
size: {
lg: {
base: "hv-tag--lg",
},
md: {
base: "hv-tag--md",
},
sm: {
base: "hv-tag--sm",
},
},
variant: {
default: {
base: "hv-tag--default",
},
surface: {
base: "hv-tag--surface",
},
},
},
});
export type TagVariants = VariantProps<typeof tagVariants>;
export const tagGroupVariants = tv({
slots: {
base: "hv-tag-group",
list: "hv-tag-group__list",
},
});
export type TagGroupVariants = VariantProps<typeof tagGroupVariants>;
export const errorMessageVariants = tv({
base: "hv-error-message",
});
export type ErrorMessageVariants = VariantProps<typeof errorMessageVariants>;
@@ -0,0 +1,24 @@
<script setup lang="ts">
import { useAttrs } from "vue";
import { errorMessageVariants } from "@heroui-vue/styles";
import { useFieldPart } from "../field/useFieldPart";
defineOptions({ name: "ErrorMessage", inheritAttrs: false });
// The `slot` attribute mirrors the fixed baseline's RAC Text slot. In Vue it is
// a plain DOM attribute (a CSS hook), not a slot assignment.
const attrs = useAttrs();
const { id } = useFieldPart("error", attrs);
</script>
<template>
<p
v-bind="attrs"
:id="id"
:class="errorMessageVariants()"
slot="errorMessage"
data-slot="error-message"
>
<slot />
</p>
</template>
+254
View File
@@ -0,0 +1,254 @@
<script lang="ts">
import {
Fragment,
cloneVNode,
computed,
defineComponent,
h,
isVNode,
mergeProps,
onBeforeUnmount,
provide,
ref,
watchEffect,
type PropType,
type SlotsType,
type VNode,
type VNodeChild,
} from "vue";
import { Primitive } from "reka-ui";
import {
useTagGroup,
tagKey,
type TagKey,
type TagRenderState,
} from "./context";
import TagRemoveButton from "./TagRemoveButton.vue";
import { elementFromRef } from "./dom";
function isRemoveButton(node: VNode): boolean {
const type = node.type as { name?: string; __name?: string };
return (type?.name ?? type?.__name) === "TagRemoveButton";
}
/** RAC `pickChildren`: the custom remove button is re-rendered last. */
function pickRemoveButton(nodes: VNodeChild[]): [VNodeChild[], VNode[]] {
const rest: VNodeChild[] = [];
const removed: VNode[] = [];
const walk = (children: VNodeChild[]) => {
for (const node of children) {
if (!isVNode(node)) {
rest.push(node);
continue;
}
if (isRemoveButton(node)) {
removed.push(node);
continue;
}
if (node.type === Fragment && Array.isArray(node.children)) {
walk(node.children as VNodeChild[]);
continue;
}
rest.push(node);
}
};
walk(nodes);
return [rest, removed];
}
/** Baseline derives `textValue` from the first string child. */
function firstText(nodes: VNodeChild[], depth = 0): string | undefined {
for (const node of nodes) {
if (typeof node === "string" && node.trim()) return node.trim();
if (typeof node === "number") return String(node);
if (!isVNode(node) || depth > 3) continue;
const children = node.children;
if (typeof children === "string" && children.trim()) return children.trim();
if (typeof children === "number") return String(children);
if (Array.isArray(children)) {
const found = firstText(children as VNodeChild[], depth + 1);
if (found) return found;
}
}
return undefined;
}
export default defineComponent({
name: "Tag",
inheritAttrs: false,
slots: Object as SlotsType<{
default: (state: TagRenderState) => VNodeChild[];
}>,
props: {
/** Collection identity, distinct from the generated DOM id. */
id: { type: [String, Number] as PropType<TagKey>, required: true },
textValue: { type: String, default: undefined },
isDisabled: { type: Boolean, default: false },
as: { type: String, default: "div" },
asChild: { type: Boolean, default: false },
},
setup(props, { attrs, slots, expose }) {
const group = useTagGroup();
const root = ref<unknown>();
const element = () => elementFromRef(root.value);
const hovered = ref(false);
const pressed = ref(false);
const focused = ref(false);
const focusVisible = ref(false);
// Rendered text is read through a plain variable so nothing writes reactive
// state during render.
let latestText = "";
const disabled = computed(
() => props.isDisabled || group.isDisabledKey(props.id),
);
const textValue = () => props.textValue ?? latestText;
const state = (): TagRenderState => ({
isSelected: group.selected(props.id),
isDisabled: disabled.value,
isHovered: hovered.value && !disabled.value,
isPressed:
(pressed.value || group.pressed.value === props.id) && !disabled.value,
isFocused: group.focused.value === props.id,
isFocusVisible:
group.focused.value === props.id &&
(group.keyboard.value || !!element()?.matches(":focus-visible")),
allowsRemoving: group.allowsRemoving(),
});
provide(tagKey, {
tagSlots: group.tagSlots,
textValue,
});
const unregister = group.register({
key: () => props.id,
element,
textValue,
disabled: () => disabled.value,
noteBlur: () => {
pressed.value = false;
},
});
onBeforeUnmount(unregister);
// A press released outside the row must not leave the visual state stuck.
watchEffect((cleanup) => {
const node = element();
if (!pressed.value || !node) return;
const owner = node.ownerDocument;
const release = () => {
pressed.value = false;
};
owner.addEventListener("pointerup", release, true);
owner.addEventListener("pointercancel", release, true);
cleanup(() => {
owner.removeEventListener("pointerup", release, true);
owner.removeEventListener("pointercancel", release, true);
});
});
function click(event: MouseEvent) {
if (event.defaultPrevented || disabled.value) return;
const target = event.target as Element | null;
const owner = element();
const removeButton = target?.closest?.('[data-slot="tag-remove-button"]');
if (removeButton && owner?.contains(removeButton)) {
group.requestRemoval(props.id);
return;
}
const interactive = target?.closest?.(
'button, a, input, select, textarea, [role="button"], [role="checkbox"], [role="switch"]',
);
if (interactive && interactive !== owner) return;
group.activate(props.id, event);
void group.focus(props.id);
}
return () => {
const current = state();
const rendered = slots.default?.(current) ?? [];
const raw = (
Array.isArray(rendered) ? rendered : [rendered]
) as VNodeChild[];
const [content, custom] = pickRemoveButton(raw);
const label = props.textValue ?? firstText(content) ?? "";
latestText = label;
const removable = current.allowsRemoving
? [
...content,
...(custom.length
? custom.map((node: VNode) =>
cloneVNode(node, {
textValue: node.props?.textValue ?? label,
}),
)
: [h(TagRemoveButton, { textValue: label })]),
]
: content;
const restAttrs: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) {
if (key === "class" || key === "style") continue;
restAttrs[key] = value;
}
return h(
Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, restAttrs, {
ref: root,
style: attrs.style,
role: "row",
class: [group.tagSlots.value.base(), attrs.class],
"data-slot": "tag",
"data-allows-removing": current.allowsRemoving || undefined,
"data-disabled": disabled.value || undefined,
"data-selected":
(group.mode.value !== "none" && current.isSelected) || undefined,
"data-focused": current.isFocused || undefined,
"data-focus-visible": current.isFocusVisible || undefined,
"data-hovered": current.isHovered || undefined,
"data-pressed": current.isPressed || undefined,
"aria-selected":
group.mode.value === "none" ? undefined : current.isSelected,
"aria-disabled": disabled.value || undefined,
tabindex: !disabled.value && group.active.value === props.id ? 0 : -1,
onClick: click,
onFocus: () => {
focused.value = true;
focusVisible.value = !!element()?.matches(":focus-visible");
if (!disabled.value) group.noteFocus(props.id);
},
onBlur: () => {
focused.value = false;
focusVisible.value = false;
pressed.value = false;
if (group.focused.value === props.id)
group.focused.value = undefined;
},
onPointerenter: () => {
hovered.value = true;
},
onPointerleave: () => {
hovered.value = false;
pressed.value = false;
},
onPointerdown: (event: PointerEvent) => {
if (
!event.defaultPrevented &&
!disabled.value &&
event.button === 0
)
pressed.value = true;
group.pressed.value = props.id;
},
onPointerup: () => {
pressed.value = false;
if (group.pressed.value === props.id)
group.pressed.value = undefined;
},
}),
{ default: () => removable },
);
};
},
});
</script>
@@ -0,0 +1,476 @@
<script lang="ts">
import {
Fragment,
cloneVNode,
computed,
defineComponent,
getCurrentInstance,
h,
isVNode,
createVNode,
mergeProps,
nextTick,
onBeforeUnmount,
onBeforeUpdate,
onMounted,
provide,
ref,
shallowRef,
useId,
watch,
type VNodeChild,
} from "vue";
import { Primitive } from "reka-ui";
import { tagGroupVariants, tagVariants } from "@heroui-vue/styles";
import { useConfig } from "../../providers/context";
import { useInheritedDisabled, disabledContextKey } from "../field/disabled";
import { fieldContextKey, mergeIds, type FieldContext } from "../field/context";
import { useCollectionSelection } from "../collection/selection";
import { useCollectionRegistry } from "../collection/registry";
import {
tagGroupKey,
type TagGroupOptions,
type TagKey,
type TagMember,
} from "./context";
const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"];
export default defineComponent({
name: "TagGroup",
inheritAttrs: false,
props: {
modelValue: { type: Array as () => readonly TagKey[], default: undefined },
selectedKeys: {
type: Array as () => readonly TagKey[],
default: undefined,
},
defaultValue: {
type: Array as () => readonly TagKey[],
default: undefined,
},
defaultSelectedKeys: {
type: Array as () => readonly TagKey[],
default: undefined,
},
selectionMode: {
type: String as () => NonNullable<TagGroupOptions["selectionMode"]>,
default: "none",
},
disabledKeys: {
type: Array as () => readonly TagKey[],
default: () => [],
},
isDisabled: { type: Boolean, default: false },
disallowEmptySelection: { type: Boolean, default: false },
size: {
type: String as () => NonNullable<TagGroupOptions["size"]>,
default: "md",
},
variant: {
type: String as () => NonNullable<TagGroupOptions["variant"]>,
default: "default",
},
dir: { type: String as () => "ltr" | "rtl", default: undefined },
as: { type: String, default: "div" },
asChild: { type: Boolean, default: false },
},
emits: {
"update:modelValue": (_keys: TagKey[]) => true,
selectionChange: (_keys: TagKey[]) => true,
remove: (_keys: TagKey[]) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const instance = getCurrentInstance()!;
const present = (key: string) =>
Object.hasOwn(instance.vnode.props ?? {}, key);
const hasModel = ref(present("modelValue") || present("model-value"));
const controlled = ref(
hasModel.value || present("selectedKeys") || present("selected-keys"),
);
const removing = ref(present("onRemove"));
onBeforeUpdate(() => {
hasModel.value = present("modelValue") || present("model-value");
controlled.value =
hasModel.value || present("selectedKeys") || present("selected-keys");
removing.value = present("onRemove");
});
const config = useConfig();
const disabled = useInheritedDisabled(() => props.isDisabled);
provide(disabledContextKey, disabled);
const groupSlots = computed(() => tagGroupVariants());
const tagSlots = computed(() =>
tagVariants({ size: props.size, variant: props.variant }),
);
const dir = computed<"ltr" | "rtl">(
() =>
props.dir ??
(typeof attrs.dir === "string"
? (attrs.dir as "ltr" | "rtl")
: undefined) ??
config?.dir.value ??
"ltr",
);
const registry = useCollectionRegistry<TagMember>();
const blockedKeys = computed(() =>
registry
.ordered()
.filter((member) => member.disabled())
.map((member) => member.key()),
);
const isDisabledKey = (key: TagKey) =>
disabled.value ||
props.disabledKeys.includes(key) ||
!!registry
.ordered()
.find((member) => member.key() === key)
?.disabled();
const selection = useCollectionSelection({
mode: () => props.selectionMode,
controlled: () => controlled.value,
value: () => (hasModel.value ? props.modelValue : props.selectedKeys),
defaultValue: props.defaultValue ?? props.defaultSelectedKeys,
disabled: () => disabled.value,
readOnly: () => false,
disabledKeys: () => [...props.disabledKeys, ...blockedKeys.value],
disallowEmptySelection: () => props.disallowEmptySelection,
onChange: (keys) => {
emit("update:modelValue", [...keys]);
emit("selectionChange", [...keys]);
},
});
const labels = ref<string[]>([]);
const descriptions = ref<string[]>([]);
const errors = ref<string[]>([]);
const fieldId = `hv-tag-group-${useId()}`;
const controlId = computed(() =>
typeof attrs.id === "string" && attrs.id ? attrs.id : fieldId,
);
const field: FieldContext = {
kind: "group",
controlId,
disabled,
readOnly: computed(() => false),
required: computed(() => false),
invalid: computed(() => false),
errors: computed(() => []),
labelIds: labels,
descriptionIds: descriptions,
errorIds: errors,
};
provide(fieldContextKey, field);
// Description / ErrorMessage / Label ids are planned here so the grid can
// reference them on the first render pass, before those parts register.
const planned = shallowRef({
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
});
function prepare(nodes: VNodeChild[], position = ""): VNodeChild[] {
const found = {
labels: [] as string[],
descriptions: [] as string[],
errors: [] as string[],
};
const walk = (children: VNodeChild[], path: string): VNodeChild[] =>
children.map((node, index) => {
if (!isVNode(node)) return node;
const at = `${path}-${index}`;
const type = node.type as
{ name?: string; __name?: string } | undefined;
const name = type?.name ?? type?.__name;
const part =
name === "Label"
? "labels"
: name === "Description"
? "descriptions"
: name === "ErrorMessage"
? "errors"
: undefined;
if (part) {
const partId = String(node.props?.id ?? `${fieldId}-${part}-${at}`);
found[part].push(partId);
return cloneVNode(node, { id: partId });
}
if (node.type === Fragment && Array.isArray(node.children)) {
// Rebuilt children must be fully diffed: a cloned fragment keeps the
// original patch flag, which can mark them stable and skip patching.
return createVNode(
Fragment,
{ key: node.key ?? undefined },
walk(node.children as VNodeChild[], at) as VNodeChild[],
);
}
return node;
});
const result = walk(nodes, position);
if (JSON.stringify(found) !== JSON.stringify(planned.value))
planned.value = found;
return result;
}
const ariaLabel = () =>
typeof attrs["aria-label"] === "string"
? (attrs["aria-label"] as string)
: undefined;
const ariaLabelledBy = () =>
typeof attrs["aria-labelledby"] === "string"
? (attrs["aria-labelledby"] as string)
: undefined;
const ariaDescribedBy = () =>
typeof attrs["aria-describedby"] === "string"
? (attrs["aria-describedby"] as string)
: undefined;
const focused = ref<TagKey>();
const lastFocused = ref<TagKey>();
const pressed = ref<TagKey>();
const keyboard = ref(true);
const listElement = shallowRef<() => HTMLElement | undefined>();
// A plain flag: the first render must not depend on a post-mount update.
let mounted = false;
onMounted(() => {
mounted = true;
});
const eligible = () => registry.available();
const active = computed<TagKey | undefined>(() => {
const items = eligible();
return (
items.find((member) => member.key() === lastFocused.value)?.key() ??
items
.find(
(member) =>
props.selectionMode !== "none" &&
selection.selected(member.key()),
)
?.key() ??
items[0]?.key()
);
});
let focusRequest = 0;
let disposing = false;
onBeforeUnmount(() => {
disposing = true;
focusRequest++;
});
async function focus(key: TagKey) {
if (disposing || disabled.value) return;
if (!eligible().some((member) => member.key() === key)) return;
const request = ++focusRequest;
lastFocused.value = key;
await nextTick();
if (disposing || request !== focusRequest) return;
const element = registry
.available()
.find((member) => member.key() === key)
?.element();
element?.focus({ preventScroll: true });
element?.scrollIntoView?.({ block: "nearest" });
}
function restoreFocus() {
lastFocused.value = undefined;
focused.value = undefined;
listElement.value?.()?.focus({ preventScroll: true });
}
function activate(key: TagKey, event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value) return;
const member = registry.ordered().find((entry) => entry.key() === key);
if (!member || member.disabled()) return;
if (props.selectionMode !== "none") selection.toggle(key);
void focus(key);
}
const allowsRemoving = () => removing.value && !disabled.value;
function requestRemoval(key: TagKey) {
if (disabled.value || !removing.value || isDisabledKey(key)) return;
// Remember where the removal started: pressing the remove button moves
// DOM focus to that button, so the row itself was never focused.
lastFocused.value = key;
lastIndex = order.value.indexOf(key);
emit("remove", [key]);
}
// Focus follows the removal only after the item is actually gone: a parent
// that rejects the proposal keeps both the item and the focus.
const order = computed(() =>
registry.ordered().map((member) => member.key()),
);
let lastIndex = -1;
watch(order, (next) => {
const key = lastFocused.value;
if (key === undefined || !mounted || disposing) return;
if (next.includes(key)) return;
const remaining = eligible();
if (!remaining.length) {
restoreFocus();
return;
}
const index = Math.min(Math.max(lastIndex, 0), remaining.length - 1);
void focus(remaining[index].key());
});
let pendingSpace: TagKey | undefined;
function onKeydown(event: KeyboardEvent) {
if (
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
disabled.value
)
return;
keyboard.value = true;
const items = eligible();
const index = items.findIndex((member) => member.key() === active.value);
if (items.length) {
const backward = dir.value === "rtl" ? "ArrowRight" : "ArrowLeft";
const forward = dir.value === "rtl" ? "ArrowLeft" : "ArrowRight";
let target: number | undefined;
if (event.key === "Home") target = 0;
else if (event.key === "End") target = items.length - 1;
else if (event.key === backward || event.key === "ArrowUp")
target = index - 1;
else if (event.key === forward || event.key === "ArrowDown")
target = index + 1;
if (target !== undefined) {
event.preventDefault();
const bounded = Math.max(0, Math.min(target, items.length - 1));
void focus(items[bounded].key());
return;
}
}
if (event.key === "Backspace" || event.key === "Delete") {
if (!removing.value || active.value === undefined) return;
event.preventDefault();
if (event.repeat) return;
requestRemoval(active.value);
return;
}
if (event.key === "Enter" || event.key === " ") {
if (event.repeat) {
event.preventDefault();
return;
}
if (active.value === undefined) return;
if (event.key === " ") {
event.preventDefault();
pressed.value = active.value;
pendingSpace = active.value;
return;
}
activate(active.value, event);
event.preventDefault();
}
}
function onKeyup(event: KeyboardEvent) {
if (event.key !== " ") return;
const key = pendingSpace;
pendingSpace = undefined;
pressed.value = undefined;
if (key !== undefined && !event.defaultPrevented) {
activate(key, event);
event.preventDefault();
}
}
const labelledBy = () =>
mergeIds(ariaLabelledBy(), planned.value.labels, labels.value);
const describedBy = () =>
mergeIds(
ariaDescribedBy(),
planned.value.descriptions,
descriptions.value,
planned.value.errors,
errors.value,
);
const textValue = (key: TagKey) =>
registry
.ordered()
.find((member) => member.key() === key)
?.textValue() ?? "";
provide(tagGroupKey, {
slots: groupSlots,
tagSlots,
mode: computed(() => props.selectionMode),
disabled,
selected: (key) => selection.selected(key),
isDisabledKey,
allowsRemoving,
requestRemoval,
register: registry.register,
hasEnabled: () => eligible().length > 0,
registerList: (element) => {
listElement.value = element;
},
active,
focused,
pressed,
keyboard,
activate,
focus,
noteFocus: (key) => {
lastFocused.value = key;
focused.value = key;
lastIndex = order.value.indexOf(key);
},
textValue,
ariaLabel,
labelledBy,
describedBy,
onKeydown,
onKeyup,
});
watch(
disabled,
(value) => {
if (value) {
pressed.value = undefined;
pendingSpace = undefined;
}
},
{ flush: "sync" },
);
expose({
element: () => listElement.value?.(),
focus: (key?: TagKey) =>
key === undefined ? restoreFocus() : focus(key),
});
return () => {
const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) {
if (NAMING_ATTRS.includes(key) || key === "class" || key === "style")
continue;
rest[key] = value;
}
return h(
Primitive,
mergeProps({ as: props.as, asChild: props.asChild }, rest, {
class: [tagGroupVariants().base(), attrs.class],
dir: dir.value,
"data-slot": "tag-group",
"data-disabled": disabled.value || undefined,
}),
{
default: () => {
const rendered = slots.default?.() ?? [];
return prepare(
(Array.isArray(rendered) ? rendered : [rendered]) as VNodeChild[],
);
},
},
);
};
},
});
</script>
@@ -0,0 +1,83 @@
<script setup lang="ts" generic="T extends TagGroupDataItem = TagGroupDataItem">
import { computed, mergeProps, ref, useAttrs } from "vue";
import { Primitive } from "reka-ui";
import { elementFromRef } from "./dom";
import {
useTagGroup,
type TagGroupDataItem,
type TagGroupListProps,
} from "./context";
defineOptions({ name: "TagGroupList", inheritAttrs: false });
const props = withDefaults(defineProps<TagGroupListProps<T>>(), {
as: "div",
asChild: false,
});
defineSlots<{
default?: (props: { item: T; index: number }) => unknown;
empty?: () => unknown;
}>();
const attrs = useAttrs();
const group = useTagGroup();
const root = ref<unknown>();
const element = () => elementFromRef(root.value);
group.registerList(element);
const describedBy = computed(() => group.describedBy());
const labelledBy = computed(() =>
group.ariaLabel() ? undefined : group.labelledBy(),
);
function rootAttrs() {
const rest: Record<string, unknown> = {};
for (const [key, value] of Object.entries(attrs)) {
if (
key === "class" ||
key === "style" ||
key === "aria-label" ||
key === "aria-labelledby" ||
key === "aria-describedby"
)
continue;
rest[key] = value;
}
return mergeProps(rest, {
ref: root,
role: "grid",
class: [group.slots.value.list(), attrs.class],
"data-slot": "tag-group-list",
"data-disabled": group.disabled.value || undefined,
"aria-label": group.ariaLabel(),
"aria-labelledby": labelledBy.value,
"aria-describedby": describedBy.value,
"aria-disabled": group.disabled.value || undefined,
"aria-multiselectable": group.mode.value === "multiple" ? true : undefined,
// Baseline announces collection additions/removals on the list itself.
"aria-atomic": "false",
"aria-relevant": "additions text",
tabindex: group.hasEnabled() ? -1 : 0,
onKeydown: group.onKeydown,
onKeyup: group.onKeyup,
onFocusout: (event: FocusEvent) => {
if (!element()?.contains(event.relatedTarget as Node | null)) {
group.focused.value = undefined;
}
},
});
}
</script>
<template>
<Primitive v-bind="rootAttrs()" :as="props.as" :as-child="props.asChild">
<template v-if="props.items">
<template v-if="props.items.length">
<template v-for="(item, index) in props.items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</template>
<slot v-else name="empty" />
</template>
<slot v-else :item="undefined!" :index="-1" />
</Primitive>
</template>
@@ -0,0 +1,38 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import CloseButton from "../close-button/CloseButton.vue";
import { tagKey } from "./context";
defineOptions({ name: "TagRemoveButton", inheritAttrs: false });
const props = withDefaults(
defineProps<{
/** Tag text used for the accessible name; `Tag` supplies it when omitted. */
textValue?: string;
isDisabled?: boolean;
}>(),
{ textValue: undefined, isDisabled: false },
);
const attrs = useAttrs();
const tag = inject(tagKey, undefined);
const label = computed(() => {
const text = props.textValue ?? tag?.textValue() ?? "";
return text ? `Remove tag ${text}` : "Remove tag";
});
// Removal stays owned by the enclosing Tag row: its click handler treats a
// press inside this subtree as a removal request rather than a selection. One
// path also covers custom remove buttons supplied through the tag slot.
</script>
<template>
<CloseButton
v-bind="attrs"
:aria-label="(attrs['aria-label'] as string | undefined) ?? label"
:class="[tag?.tagSlots.value.removeButton(), attrs.class]"
:is-disabled="props.isDisabled || !tag"
data-slot="tag-remove-button"
>
<slot />
</CloseButton>
</template>
@@ -0,0 +1,85 @@
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
import type { tagGroupVariants, tagVariants } from "@heroui-vue/styles";
import type { CollectionKey } from "../collection/keys";
import type { CollectionMember } from "../collection/registry";
import type { CollectionSelectionMode } from "../collection/selection";
export type TagKey = CollectionKey;
export interface TagGroupDataItem {
id: TagKey;
textValue?: string;
isDisabled?: boolean;
}
/** Public schema shared by the SFC props and the context. */
export interface TagGroupOptions {
modelValue?: readonly TagKey[];
selectedKeys?: readonly TagKey[];
defaultValue?: readonly TagKey[];
defaultSelectedKeys?: readonly TagKey[];
selectionMode?: CollectionSelectionMode;
disabledKeys?: readonly TagKey[];
isDisabled?: boolean;
disallowEmptySelection?: boolean;
size?: "sm" | "md" | "lg";
variant?: "default" | "surface";
as?: string;
asChild?: boolean;
}
export interface TagRenderState {
isSelected: boolean;
isDisabled: boolean;
isHovered: boolean;
isPressed: boolean;
isFocused: boolean;
isFocusVisible: boolean;
allowsRemoving: boolean;
}
export interface TagMember extends CollectionMember {
noteBlur: () => void;
}
export interface TagGroupListProps<
T extends TagGroupDataItem = TagGroupDataItem,
> {
items?: readonly T[];
as?: string;
asChild?: boolean;
}
export interface TagGroupContext {
slots: ComputedRef<ReturnType<typeof tagGroupVariants>>;
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
mode: ComputedRef<CollectionSelectionMode>;
disabled: ComputedRef<boolean>;
selected: (key: TagKey) => boolean;
isDisabledKey: (key: TagKey) => boolean;
allowsRemoving: () => boolean;
requestRemoval: (key: TagKey) => void;
register: (member: TagMember) => () => void;
hasEnabled: () => boolean;
registerList: (element: () => HTMLElement | undefined) => void;
active: ComputedRef<TagKey | undefined>;
focused: Ref<TagKey | undefined>;
pressed: Ref<TagKey | undefined>;
keyboard: Ref<boolean>;
activate: (key: TagKey, event: MouseEvent | KeyboardEvent) => void;
focus: (key: TagKey) => Promise<void>;
noteFocus: (key: TagKey) => void;
textValue: (key: TagKey) => string;
ariaLabel: () => string | undefined;
labelledBy: () => string | undefined;
describedBy: () => string | undefined;
onKeydown: (event: KeyboardEvent) => void;
onKeyup: (event: KeyboardEvent) => void;
}
export interface TagContext {
tagSlots: ComputedRef<ReturnType<typeof tagVariants>>;
textValue: () => string;
}
export const tagGroupKey: InjectionKey<TagGroupContext> =
Symbol("hv-tag-group");
export const tagKey: InjectionKey<TagContext> = Symbol("hv-tag");
export function useTagGroup(): TagGroupContext {
const context = inject(tagGroupKey, undefined);
if (!context) throw new Error("Tag requires TagGroup and TagGroupList.");
return context;
}
+9
View File
@@ -0,0 +1,9 @@
/** Reka's Primitive exposes the element through `$el`, not as a DOM node. */
export function elementFromRef(value: unknown): HTMLElement | undefined {
// Server rendering and prerendering have no DOM; the collection then keeps
// registration order because no element is available.
if (typeof Element === "undefined") return undefined;
if (value instanceof Element) return value as HTMLElement;
const element = (value as { $el?: unknown } | null)?.$el;
return element instanceof Element ? (element as HTMLElement) : undefined;
}
+29
View File
@@ -929,3 +929,32 @@ export type {
DropdownSubmenuIndicatorProps,
DropdownSubmenuTriggerProps,
} from "./types-menu";
export { default as Tag } from "./components/tag/Tag.vue";
export { default as TagGroup } from "./components/tag/TagGroup.vue";
export { default as TagGroupList } from "./components/tag/TagGroupList.vue";
export { default as TagRemoveButton } from "./components/tag/TagRemoveButton.vue";
export type {
TagProps,
TagGroupProps,
TagGroupListProps,
TagRemoveButtonProps,
} from "./types";
export type {
TagKey,
TagGroupDataItem,
TagRenderState,
TagGroupOptions,
} from "./components/tag/context";
export { default as ErrorMessage } from "./components/error-message/ErrorMessage.vue";
export type { ErrorMessageProps } from "./types";
export {
tagVariants,
tagGroupVariants,
errorMessageVariants,
type TagVariants,
type TagGroupVariants,
type ErrorMessageVariants,
} from "@heroui-vue/styles";
+16
View File
@@ -728,3 +728,19 @@ export type TableLoadMoreContentProps = InstanceType<
typeof TableLoadMoreContent
>["$props"];
export type TableLoadMoreProps = TableLoadMoreItemProps;
import type Tag from "./components/tag/Tag.vue";
export type TagProps = InstanceType<typeof Tag>["$props"];
import type TagGroup from "./components/tag/TagGroup.vue";
export type TagGroupProps = InstanceType<typeof TagGroup>["$props"];
export type { TagGroupListProps } from "./components/tag/context";
import type TagRemoveButton from "./components/tag/TagRemoveButton.vue";
export type TagRemoveButtonProps = InstanceType<
typeof TagRemoveButton
>["$props"];
import type ErrorMessage from "./components/error-message/ErrorMessage.vue";
export type ErrorMessageProps = InstanceType<typeof ErrorMessage>["$props"];
+2
View File
@@ -25,3 +25,5 @@ SELECT-01 增加 `consume-select.mjs` / `select-contract.ts`。新 tarball 安
DATE-02 增加 `consume-date-field.mjs` / `date-field-contract.ts`。独立消费者显式安装 `@internationalized/date@3.12.4`,运行完整 ISO 时区提交/SSR/样式检查,分别用 NodeNext 与 bundler 验证 DateValue、粒度、变体、范围和 segment 的正反类型,不从源码 alias 取公共类型。
M35–M36 使用 `consume-m35-m36.mjs` / `m35-m36-contract.ts`,新建 `/private/tmp/heroui-m35-consumer`。pnpm 11 的本地样式 tarball override 写在消费者 `pnpm-workspace.yaml`;不依赖已弃用的 package.json pnpm 字段。分别验证 ESM/CSS、真正 node SSR、所有部件导出,以及 bundler/NodeNext 类型正反例(含 Promise 参数推断)。
B03 使用 `consume-b03-tag-error-message.mjs` / `b03-tag-error-message-contract.ts`,消费者目录 `/private/tmp/heroui-b03-consumer`(pnpm 11 的样式包 override 写在 `pnpm-workspace.yaml`)。验证 ESM 运行时(导出、SSR HTML 契约)、编译产物 CSS 选择器,以及 Tag/TagGroup/TagGroupList/TagRemoveButton/ErrorMessage 的正反类型(bundler 与 NodeNext)。
@@ -0,0 +1,121 @@
import { h } from "vue";
import {
ErrorMessage,
Tag,
TagGroup,
TagGroupList,
TagRemoveButton,
type TagGroupProps,
type TagGroupListProps,
type TagKey,
type TagProps,
type TagRemoveButtonProps,
type TagRenderState,
type ErrorMessageProps,
} from "@heroui-vue/components";
const key: TagKey = "news";
const numericKey: TagKey = 0;
// @ts-expect-error collection keys are strings or finite numbers
const invalidKey: TagKey = {};
const groupProps: TagGroupProps = {
selectionMode: "multiple",
modelValue: [key, numericKey],
defaultValue: [],
disabledKeys: [key],
isDisabled: false,
disallowEmptySelection: true,
size: "lg",
variant: "surface",
dir: "rtl",
as: "section",
asChild: false,
};
// @ts-expect-error selectionMode is a closed union
const badMode: TagGroupProps = { selectionMode: "triple" };
// @ts-expect-error size is a closed union
const badSize: TagGroupProps = { size: "xl" };
// `items` keeps the caller's item type: extra fields are allowed and reach the
// scoped slot unchanged.
const listProps: TagGroupListProps<{ id: string; name: string }> = {
items: [{ id: "a", name: "A" }],
as: "div",
};
// @ts-expect-error items must carry a collection key
const listPropsWithoutId: TagGroupListProps<{ name: string }> = {
items: [{ name: "A" }],
};
const tagProps: TagProps = { id: key, textValue: "资讯", isDisabled: false };
const removeProps: TagRemoveButtonProps = {
textValue: "资讯",
isDisabled: true,
};
// ErrorMessage declares no props of its own: content, `id` and `class` are
// ordinary attributes / slots.
const messageProps: ErrorMessageProps = {};
const state: TagRenderState = {
isSelected: true,
isDisabled: false,
isHovered: false,
isPressed: false,
isFocused: true,
isFocusVisible: true,
allowsRemoving: true,
};
const tree = h(
TagGroup,
{
selectionMode: "single",
modelValue: [key],
"onUpdate:modelValue": (keys: TagKey[]) => keys.length,
onSelectionChange: (keys: TagKey[]) => keys,
onRemove: (keys: TagKey[]) => keys,
},
{
default: () => [
h(TagGroupList, null, {
default: () =>
h(
Tag,
{ id: key },
{
default: (tagState: TagRenderState) =>
tagState.isSelected ? "selected" : "tag",
},
),
empty: () =>
h(ErrorMessage, { ...messageProps, id: "error" }, () => "empty"),
}),
h(Tag, tagProps, {
default: () => [
"资讯",
h(TagRemoveButton, removeProps, { default: () => "x" }),
],
}),
h(ErrorMessage, null, () => "请选择"),
],
},
);
// @ts-expect-error Tag requires a collection key
const missingId = h(Tag, {});
// @ts-expect-error remove button text must be a string
const badRemoveText = h(TagRemoveButton, { textValue: 1 });
void [
listPropsWithoutId,
invalidKey,
badMode,
badSize,
state,
tree,
missingId,
badRemoveText,
groupProps,
];
@@ -0,0 +1,88 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { createSSRApp, h } from "vue";
import { renderToString } from "@vue/server-renderer";
import * as lib from "@heroui-vue/components";
for (const name of [
"TagGroup",
"TagGroupList",
"Tag",
"TagRemoveButton",
"ErrorMessage",
"tagVariants",
"tagGroupVariants",
"errorMessageVariants",
])
assert(lib[name], name);
const html = await renderToString(
createSSRApp({
render: () =>
h(
lib.TagGroup,
{
"aria-label": "分类",
selectionMode: "multiple",
modelValue: ["news"],
onRemove: () => {},
},
{
default: () => [
h(lib.TagGroupList, null, {
default: () => [
h(lib.Tag, { id: "news" }, { default: () => "资讯" }),
h(
lib.Tag,
{ id: 0, isDisabled: true },
{ default: () => "零" },
),
],
}),
h(lib.ErrorMessage, null, { default: () => "请至少选择一项" }),
],
},
),
}),
);
assert(html.includes('role="grid"'), "grid role on the list");
assert(html.includes('aria-label="分类"'), "grid carries the group label");
assert(html.includes('aria-multiselectable="true"'), "multiple selection flag");
assert(html.includes('role="row"'), "rows for tags");
assert(html.includes('aria-selected="true"'), "accepted selection");
assert(html.includes('aria-disabled="true"'), "disabled tag");
assert(html.includes("Remove tag 资讯"), "composed remove button name");
assert(html.includes('data-slot="tag-remove-button"'), "remove button slot");
assert(html.includes('data-slot="error-message"'), "error message slot");
assert(html.includes('slot="errorMessage"'), "baseline error message marker");
const css = readFileSync(
"node_modules/@heroui-vue/styles/dist/styles.css",
"utf8",
);
for (const rule of [
".hv-tag",
".hv-tag--sm",
".hv-tag--lg",
".hv-tag--surface",
".hv-tag__remove-button",
".hv-tag-group",
".hv-tag-group__list",
".hv-error-message",
])
assert(css.includes(rule), `missing CSS rule ${rule}`);
// The list padding rule must survive minification for Description/ErrorMessage.
assert(
/\.hv-tag-group\s*\[data-slot=["']?error-message/.test(css),
"missing tag-group error-message padding rule",
);
assert.equal(typeof lib.tagVariants({ size: "sm" }).base, "function");
assert(lib.tagVariants({ size: "sm" }).base().includes("hv-tag--sm"));
assert(
lib.tagVariants({ variant: "surface" }).base().includes("hv-tag--surface"),
);
assert(lib.errorMessageVariants().includes("hv-error-message"));
console.log("B03 tag/error-message consumption OK");
File diff suppressed because it is too large Load Diff