From af6bfda3ee4d0472ca1233df3c9dc1ab3788b853 Mon Sep 17 00:00:00 2001 From: maoyingjie Date: Sun, 25 Oct 2026 10:45:43 +0800 Subject: [PATCH 1/2] 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. --- apps/docs/.vitepress/theme/navigation.ts | 10 + apps/docs/components/error-message.md | 124 ++ apps/docs/components/tag-group.md | 285 +++++ apps/docs/demos/error-message-basic.vue | 29 + .../demos/error-message-custom-styles.vue | 34 + apps/docs/demos/tag-group-basic.vue | 32 + apps/docs/demos/tag-group-controlled.vue | 31 + apps/docs/demos/tag-group-custom-styles.vue | 38 + apps/docs/demos/tag-group-disabled.vue | 33 + apps/docs/demos/tag-group-render-function.vue | 38 + apps/docs/demos/tag-group-selection-modes.vue | 40 + apps/docs/demos/tag-group-sizes.vue | 32 + apps/docs/demos/tag-group-variants.vue | 25 + .../demos/tag-group-with-error-message.vue | 32 + apps/docs/demos/tag-group-with-list-data.vue | 121 ++ apps/docs/demos/tag-group-with-prefix.vue | 79 ++ .../demos/tag-group-with-remove-button.vue | 88 ++ docs/compatibility.md | 6 +- docs/migrations/B03-tag-error-message.md | 176 +++ docs/upstream.md | 6 + docs/verification.md | 24 + package.json | 2 +- packages/styles/components/error-message.css | 15 + packages/styles/components/tag-group.css | 17 + packages/styles/components/tag.css | 114 ++ packages/styles/index.css | 3 + packages/styles/src/index.ts | 49 + .../components/error-message/ErrorMessage.vue | 24 + packages/vue/src/components/tag/Tag.vue | 254 ++++ packages/vue/src/components/tag/TagGroup.vue | 476 ++++++++ .../vue/src/components/tag/TagGroupList.vue | 83 ++ .../src/components/tag/TagRemoveButton.vue | 38 + packages/vue/src/components/tag/context.ts | 85 ++ packages/vue/src/components/tag/dom.ts | 9 + packages/vue/src/index.ts | 29 + packages/vue/src/types.ts | 16 + tests/package/README.md | 2 + .../package/b03-tag-error-message-contract.ts | 121 ++ .../package/consume-b03-tag-error-message.mjs | 88 ++ tests/tag-error-message.test.ts | 1086 +++++++++++++++++ 40 files changed, 3790 insertions(+), 4 deletions(-) create mode 100644 apps/docs/components/error-message.md create mode 100644 apps/docs/components/tag-group.md create mode 100644 apps/docs/demos/error-message-basic.vue create mode 100644 apps/docs/demos/error-message-custom-styles.vue create mode 100644 apps/docs/demos/tag-group-basic.vue create mode 100644 apps/docs/demos/tag-group-controlled.vue create mode 100644 apps/docs/demos/tag-group-custom-styles.vue create mode 100644 apps/docs/demos/tag-group-disabled.vue create mode 100644 apps/docs/demos/tag-group-render-function.vue create mode 100644 apps/docs/demos/tag-group-selection-modes.vue create mode 100644 apps/docs/demos/tag-group-sizes.vue create mode 100644 apps/docs/demos/tag-group-variants.vue create mode 100644 apps/docs/demos/tag-group-with-error-message.vue create mode 100644 apps/docs/demos/tag-group-with-list-data.vue create mode 100644 apps/docs/demos/tag-group-with-prefix.vue create mode 100644 apps/docs/demos/tag-group-with-remove-button.vue create mode 100644 docs/migrations/B03-tag-error-message.md create mode 100644 packages/styles/components/error-message.css create mode 100644 packages/styles/components/tag-group.css create mode 100644 packages/styles/components/tag.css create mode 100644 packages/vue/src/components/error-message/ErrorMessage.vue create mode 100644 packages/vue/src/components/tag/Tag.vue create mode 100644 packages/vue/src/components/tag/TagGroup.vue create mode 100644 packages/vue/src/components/tag/TagGroupList.vue create mode 100644 packages/vue/src/components/tag/TagRemoveButton.vue create mode 100644 packages/vue/src/components/tag/context.ts create mode 100644 packages/vue/src/components/tag/dom.ts create mode 100644 tests/package/b03-tag-error-message-contract.ts create mode 100644 tests/package/consume-b03-tag-error-message.mjs create mode 100644 tests/tag-error-message.test.ts diff --git a/apps/docs/.vitepress/theme/navigation.ts b/apps/docs/.vitepress/theme/navigation.ts index f364817..8d68d3c 100644 --- a/apps/docs/.vitepress/theme/navigation.ts +++ b/apps/docs/.vitepress/theme/navigation.ts @@ -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", diff --git a/apps/docs/components/error-message.md b/apps/docs/components/error-message.md new file mode 100644 index 0000000..03b6f39 --- /dev/null +++ b/apps/docs/components/error-message.md @@ -0,0 +1,124 @@ +--- +title: ErrorMessage 错误消息 +description: 用于展示错误的底层错误消息组件 +component: error-message +group: 组件 +--- + +## 用法 + +```vue + + + +``` + + + +`ErrorMessage` 是基于固定基线 `Text` 组件 `errorMessage` slot 的底层组件,用于在 **非表单组件**(如 `TagGroup`、`Calendar` 及其他集合类组件)中展示错误消息。 + +## 组件结构 + +```vue + + + +``` + +## 何时使用 + +`ErrorMessage` **不绑定表单**,是用于非表单上下文的通用错误展示组件。 + +- **推荐用于** 非表单组件(如 `TagGroup`、`Calendar`、集合类组件) +- **表单字段** 建议使用 [FieldError](./field-error),它提供表单专用校验特性与自动错误处理,遵循标准化表单校验模式 + +## ErrorMessage 与 FieldError + +| 组件 | 使用场景 | 表单集成 | 示例组件 | +| -------------- | ---------- | -------- | ------------------------------------ | +| `ErrorMessage` | 非表单组件 | 否 | `TagGroup`、`Calendar` | +| `FieldError` | 表单字段 | 是 | `TextField`、`NumberField`、`Select` | + +表单校验建议使用 `FieldError`,它遵循标准化表单校验模式并提供表单专用特性。 + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 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` 渲染为 `

`,带 `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) diff --git a/apps/docs/components/tag-group.md b/apps/docs/components/tag-group.md new file mode 100644 index 0000000..f72e095 --- /dev/null +++ b/apps/docs/components/tag-group.md @@ -0,0 +1,285 @@ +--- +title: TagGroup 标签组 +description: 可聚焦的标签列表,支持键盘导航、选择与移除。 +component: tag-group +group: 组件 +--- + +## 用法 + +```vue + + + +``` + + + +`TagGroup` 是标签集合的根部件,负责选择状态、禁用范围、移除请求与名称/描述关联;`TagGroupList` 渲染真正的 `role="grid"` 容器,`Tag` 渲染 `role="row"` 条目。上游的对象式子部件 `TagGroup.List`、`Tag.RemoveButton` 在本库中是具名导出 `TagGroupList`、`TagRemoveButton`。 + +## 组件结构 + +```vue + + + +``` + +`Label`、`Description`、`ErrorMessage` 直接放在 `TagGroup` 的默认插槽中:它们的 `id` 会作为列表节点的 `aria-labelledby` / `aria-describedby`,不要再写 React 的 `slot="..."` 形式。 + +## 示例 + +### 尺寸 + + + +### 变体 + + + +### 禁用 + + + +### 选择模式 + + + +### 受控组件 + + + +### 带错误信息 + + + +### 带列表数据 + + + +### 带前缀 + + + +### 带移除按钮 + + + +### 渲染函数 + + + +上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(使用自定义组件作为唯一根)。本库示例用 `as="section"` 演示同一能力。 + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 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` | - | 当前选中的 key(受控,`v-model`) | +| `selected-keys` | `Array` | - | 当前选中的 key(`model-value` 的别名,受控) | +| `default-value` | `Array` | - | 初始选中的 key(非受控) | +| `default-selected-keys` | `Array` | - | 初始选中的 key(非受控,`default-value` 的别名) | +| `disabled-keys` | `Array` | `[]` | 禁用标签的 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` | 选择变化时发出(配合 `v-model`) | +| `selectionChange` | `Array` | 选择变化时发出 | +| `remove` | `Array` | 用户请求移除标签时发出;不包含在数据中删除条目的行为 | + +`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) diff --git a/apps/docs/demos/error-message-basic.vue b/apps/docs/demos/error-message-basic.vue new file mode 100644 index 0000000..b0f927f --- /dev/null +++ b/apps/docs/demos/error-message-basic.vue @@ -0,0 +1,29 @@ + + + diff --git a/apps/docs/demos/error-message-custom-styles.vue b/apps/docs/demos/error-message-custom-styles.vue new file mode 100644 index 0000000..d2efa20 --- /dev/null +++ b/apps/docs/demos/error-message-custom-styles.vue @@ -0,0 +1,34 @@ + + + diff --git a/apps/docs/demos/tag-group-basic.vue b/apps/docs/demos/tag-group-basic.vue new file mode 100644 index 0000000..38eca6e --- /dev/null +++ b/apps/docs/demos/tag-group-basic.vue @@ -0,0 +1,32 @@ + + + diff --git a/apps/docs/demos/tag-group-controlled.vue b/apps/docs/demos/tag-group-controlled.vue new file mode 100644 index 0000000..c6e62a4 --- /dev/null +++ b/apps/docs/demos/tag-group-controlled.vue @@ -0,0 +1,31 @@ + + + diff --git a/apps/docs/demos/tag-group-custom-styles.vue b/apps/docs/demos/tag-group-custom-styles.vue new file mode 100644 index 0000000..65825f2 --- /dev/null +++ b/apps/docs/demos/tag-group-custom-styles.vue @@ -0,0 +1,38 @@ + + + diff --git a/apps/docs/demos/tag-group-disabled.vue b/apps/docs/demos/tag-group-disabled.vue new file mode 100644 index 0000000..398cf70 --- /dev/null +++ b/apps/docs/demos/tag-group-disabled.vue @@ -0,0 +1,33 @@ + + + diff --git a/apps/docs/demos/tag-group-render-function.vue b/apps/docs/demos/tag-group-render-function.vue new file mode 100644 index 0000000..a7050a9 --- /dev/null +++ b/apps/docs/demos/tag-group-render-function.vue @@ -0,0 +1,38 @@ + + + diff --git a/apps/docs/demos/tag-group-selection-modes.vue b/apps/docs/demos/tag-group-selection-modes.vue new file mode 100644 index 0000000..a0593a5 --- /dev/null +++ b/apps/docs/demos/tag-group-selection-modes.vue @@ -0,0 +1,40 @@ + + + diff --git a/apps/docs/demos/tag-group-sizes.vue b/apps/docs/demos/tag-group-sizes.vue new file mode 100644 index 0000000..03bdff7 --- /dev/null +++ b/apps/docs/demos/tag-group-sizes.vue @@ -0,0 +1,32 @@ + + + diff --git a/apps/docs/demos/tag-group-variants.vue b/apps/docs/demos/tag-group-variants.vue new file mode 100644 index 0000000..0955802 --- /dev/null +++ b/apps/docs/demos/tag-group-variants.vue @@ -0,0 +1,25 @@ + + + diff --git a/apps/docs/demos/tag-group-with-error-message.vue b/apps/docs/demos/tag-group-with-error-message.vue new file mode 100644 index 0000000..c6abe6c --- /dev/null +++ b/apps/docs/demos/tag-group-with-error-message.vue @@ -0,0 +1,32 @@ + + + diff --git a/apps/docs/demos/tag-group-with-list-data.vue b/apps/docs/demos/tag-group-with-list-data.vue new file mode 100644 index 0000000..a9203b8 --- /dev/null +++ b/apps/docs/demos/tag-group-with-list-data.vue @@ -0,0 +1,121 @@ + + + diff --git a/apps/docs/demos/tag-group-with-prefix.vue b/apps/docs/demos/tag-group-with-prefix.vue new file mode 100644 index 0000000..0ccba2b --- /dev/null +++ b/apps/docs/demos/tag-group-with-prefix.vue @@ -0,0 +1,79 @@ + + + diff --git a/apps/docs/demos/tag-group-with-remove-button.vue b/apps/docs/demos/tag-group-with-remove-button.vue new file mode 100644 index 0000000..abc35c9 --- /dev/null +++ b/apps/docs/demos/tag-group-with-remove-button.vue @@ -0,0 +1,88 @@ + + + diff --git a/docs/compatibility.md b/docs/compatibility.md index 78a33ed..9b1e83f 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -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 | | toolbar | 验证中(M29) | Toolbar;5/5 基线例;isAttached/orientation/dir;跨组单 Tab 入口与方向键;子组焦点让位;Separator 垂直继承 | | tooltip | 验证中(OVERLAY-02) | Root/Trigger/Content/Arrow;6/6 基线例;CSS 延迟/焦点/禁用/替换/定位;Provider warmup 与 RAC 全局调度不同 | diff --git a/docs/migrations/B03-tag-error-message.md b/docs/migrations/B03-tag-error-message.md new file mode 100644 index 0000000..c231a35 --- /dev/null +++ b/docs/migrations/B03-tag-error-message.md @@ -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 | `

`,仅展示、不校验 | + +上游测试确认的契约:网格下有若干 `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`) | +| 描述关联 | `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 页输出 `

`。 + +## 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)` → `@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`:确认两个示例渲染 `

`,并检查 API 表满宽无溢出。 +4. 独立消费:把 `tests/package/{consume-b03-tag-error-message.mjs,b03-tag-error-message-contract.ts}` 复制到工作区外的新工程,装两份 `pnpm pack` 产物后执行脚本 + 两种 `tsc` 模式。 diff --git a/docs/upstream.md b/docs/upstream.md index 01d2020..b375f93 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -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 仓库。 diff --git a/docs/verification.md b/docs/verification.md index 7e4f4eb..3f46e7a 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -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 页面渲染 `

`。 + +未验证:逐像素对比、读屏软件、物理触屏、窄屏断点截图。截图在本轮首次采集后 IAB 合成器不再返回帧(`capture timed out`),因此尺寸/配色改为计算样式断言,未以旧截图充当本轮证据。 diff --git a/package.json b/package.json index 9271795..6eae02d 100644 --- a/package.json +++ b/package.json @@ -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 .", diff --git a/packages/styles/components/error-message.css b/packages/styles/components/error-message.css new file mode 100644 index 0000000..5fd73f5 --- /dev/null +++ b/packages/styles/components/error-message.css @@ -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; +} diff --git a/packages/styles/components/tag-group.css b/packages/styles/components/tag-group.css new file mode 100644 index 0000000..369877e --- /dev/null +++ b/packages/styles/components/tag-group.css @@ -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; +} diff --git a/packages/styles/components/tag.css b/packages/styles/components/tag.css new file mode 100644 index 0000000..6f017dd --- /dev/null +++ b/packages/styles/components/tag.css @@ -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; + } +} diff --git a/packages/styles/index.css b/packages/styles/index.css index 859bac1..994b424 100644 --- a/packages/styles/index.css +++ b/packages/styles/index.css @@ -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); diff --git a/packages/styles/src/index.ts b/packages/styles/src/index.ts index b5bdf8a..1edac8b 100644 --- a/packages/styles/src/index.ts +++ b/packages/styles/src/index.ts @@ -1627,3 +1627,52 @@ export const dropdownVariants = tv({ }); export type DropdownVariants = VariantProps; + +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; + +export const tagGroupVariants = tv({ + slots: { + base: "hv-tag-group", + list: "hv-tag-group__list", + }, +}); + +export type TagGroupVariants = VariantProps; + +export const errorMessageVariants = tv({ + base: "hv-error-message", +}); + +export type ErrorMessageVariants = VariantProps; diff --git a/packages/vue/src/components/error-message/ErrorMessage.vue b/packages/vue/src/components/error-message/ErrorMessage.vue new file mode 100644 index 0000000..e400cec --- /dev/null +++ b/packages/vue/src/components/error-message/ErrorMessage.vue @@ -0,0 +1,24 @@ + + + diff --git a/packages/vue/src/components/tag/Tag.vue b/packages/vue/src/components/tag/Tag.vue new file mode 100644 index 0000000..93de9cb --- /dev/null +++ b/packages/vue/src/components/tag/Tag.vue @@ -0,0 +1,254 @@ + diff --git a/packages/vue/src/components/tag/TagGroup.vue b/packages/vue/src/components/tag/TagGroup.vue new file mode 100644 index 0000000..a2805ed --- /dev/null +++ b/packages/vue/src/components/tag/TagGroup.vue @@ -0,0 +1,476 @@ + diff --git a/packages/vue/src/components/tag/TagGroupList.vue b/packages/vue/src/components/tag/TagGroupList.vue new file mode 100644 index 0000000..c14674e --- /dev/null +++ b/packages/vue/src/components/tag/TagGroupList.vue @@ -0,0 +1,83 @@ + + + diff --git a/packages/vue/src/components/tag/TagRemoveButton.vue b/packages/vue/src/components/tag/TagRemoveButton.vue new file mode 100644 index 0000000..23aa986 --- /dev/null +++ b/packages/vue/src/components/tag/TagRemoveButton.vue @@ -0,0 +1,38 @@ + + + diff --git a/packages/vue/src/components/tag/context.ts b/packages/vue/src/components/tag/context.ts new file mode 100644 index 0000000..90b4e08 --- /dev/null +++ b/packages/vue/src/components/tag/context.ts @@ -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>; + tagSlots: ComputedRef>; + mode: ComputedRef; + disabled: ComputedRef; + 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; + focused: Ref; + pressed: Ref; + keyboard: Ref; + activate: (key: TagKey, event: MouseEvent | KeyboardEvent) => void; + focus: (key: TagKey) => Promise; + 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>; + textValue: () => string; +} +export const tagGroupKey: InjectionKey = + Symbol("hv-tag-group"); +export const tagKey: InjectionKey = Symbol("hv-tag"); + +export function useTagGroup(): TagGroupContext { + const context = inject(tagGroupKey, undefined); + if (!context) throw new Error("Tag requires TagGroup and TagGroupList."); + return context; +} diff --git a/packages/vue/src/components/tag/dom.ts b/packages/vue/src/components/tag/dom.ts new file mode 100644 index 0000000..b36e492 --- /dev/null +++ b/packages/vue/src/components/tag/dom.ts @@ -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; +} diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index 011b078..a7c07b8 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -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"; diff --git a/packages/vue/src/types.ts b/packages/vue/src/types.ts index 30560b6..468c48d 100644 --- a/packages/vue/src/types.ts +++ b/packages/vue/src/types.ts @@ -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["$props"]; + +import type TagGroup from "./components/tag/TagGroup.vue"; +export type TagGroupProps = InstanceType["$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["$props"]; diff --git a/tests/package/README.md b/tests/package/README.md index 5bfe407..2fd66cb 100644 --- a/tests/package/README.md +++ b/tests/package/README.md @@ -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)。 diff --git a/tests/package/b03-tag-error-message-contract.ts b/tests/package/b03-tag-error-message-contract.ts new file mode 100644 index 0000000..1678050 --- /dev/null +++ b/tests/package/b03-tag-error-message-contract.ts @@ -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, +]; diff --git a/tests/package/consume-b03-tag-error-message.mjs b/tests/package/consume-b03-tag-error-message.mjs new file mode 100644 index 0000000..193f4a7 --- /dev/null +++ b/tests/package/consume-b03-tag-error-message.mjs @@ -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"); diff --git a/tests/tag-error-message.test.ts b/tests/tag-error-message.test.ts new file mode 100644 index 0000000..79ed52e --- /dev/null +++ b/tests/tag-error-message.test.ts @@ -0,0 +1,1086 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { readFileSync } from "node:fs"; +import { mount } from "@vue/test-utils"; +import { createApp, defineComponent, h, nextTick, ref } from "vue"; +import { + Description, + ErrorMessage, + Label, + Tag, + TagGroup, + TagGroupList, + TagRemoveButton, +} from "../packages/vue/src"; + +type Item = { id: string | number; label: string; disabled?: boolean }; + +type Mounted = ReturnType; +// Each case queries inside its own root: a shared document hides ordering bugs. +const wrappers: Mounted[] = []; + +/** Vue skips an invoker when the event timestamp is not newer than the listener + * attachment time (`e._vts <= invoker.attached`). Synthetic dispatch inside the + * same millisecond is ignored, so move past that millisecond first. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 2)); + +async function mountGroup( + options: { + tags?: Item[]; + props?: Record; + groupProps?: Record; + slots?: Record; + content?: (item: Item) => unknown; + } = {}, +) { + const tags = options.tags ?? [ + { id: "news", label: "资讯" }, + { id: "travel", label: "旅行" }, + { id: "gaming", label: "游戏" }, + ]; + const wrapper = mount( + defineComponent({ + setup() { + return () => + h( + TagGroup, + { selectionMode: "single", "aria-label": "分类", ...options.props }, + { + default: () => [ + h(TagGroupList, options.groupProps ?? {}, { + default: () => [ + ...tags.map((tag) => + h( + Tag, + { id: tag.id, key: tag.id, isDisabled: tag.disabled }, + { + default: () => + options.content ? options.content(tag) : tag.label, + }, + ), + ), + ...(((options.slots?.default as unknown[]) ?? + []) as never[]), + ], + }), + ], + }, + ); + }, + }), + { attachTo: document.body }, + ); + wrappers.push(wrapper); + await nextTick(); + await settle(); + return wrapper; +} + +function root(): HTMLElement { + return (wrappers.at(-1)?.element as HTMLElement | undefined) ?? document.body; +} +const queryAll = (selector: string) => { + const element = root(); + const found = [...element.querySelectorAll(selector)]; + if (element.matches(selector)) found.unshift(element as unknown as T); + return found; +}; +const queryOne = (selector: string) => + queryAll(selector)[0] ?? null; +const row = (label: string) => + queryAll('[data-slot="tag"]').find( + (element) => element.textContent?.replace(/\s+/g, "") === label, + ); + +afterEach(async () => { + // Unmount through Vue so the registry/focus cleanup runs; never yank the DOM + // out from under a live tree. + while (wrappers.length) wrappers.pop()?.unmount(); + await nextTick(); + await settle(); + vi.restoreAllMocks(); +}); + +describe("TagGroup structure", () => { + it("exposes the baseline data-slots and BEM blocks", async () => { + await mountGroup(); + const root = queryOne('[data-slot="tag-group"]')!; + const list = queryOne('[data-slot="tag-group-list"]')!; + + expect(root.className).toContain("hv-tag-group"); + expect(root.className).not.toContain("hv-tag-group__list"); + expect(list.className).toContain("hv-tag-group__list"); + expect(list.className).not.toContain("hv-tag-group "); + expect(queryAll('[data-slot="tag"]')).toHaveLength(3); + }); + + it("renders each tag as a row inside the grid", async () => { + await mountGroup(); + const list = queryOne('[data-slot="tag-group-list"]')!; + + expect(list.getAttribute("role")).toBe("grid"); + expect(list.getAttribute("aria-label")).toBe("分类"); + expect(list.getAttribute("aria-atomic")).toBe("false"); + expect(list.getAttribute("aria-relevant")).toBe("additions text"); + const rows = [...list.querySelectorAll('[data-slot="tag"]')]; + + expect(rows.map((element) => element.getAttribute("role"))).toEqual([ + "row", + "row", + "row", + ]); + expect(rows.map((element) => element.textContent?.trim())).toEqual([ + "资讯", + "旅行", + "游戏", + ]); + }); + + it("names the grid from Label and describes it with Description and ErrorMessage", async () => { + const named = mount(TagGroup, { + props: { selectionMode: "single" }, + slots: { + default: () => [ + h(Label, () => "设施"), + h(TagGroupList, null, { + default: () => [h(Tag, { id: "pool" }, () => "游泳池")], + }), + h(Description, () => "可多选"), + h(ErrorMessage, () => "请选择一个设施"), + ], + }, + attachTo: document.body, + }); + wrappers.push(named); + await nextTick(); + await settle(); + const list = queryOne('[data-slot="tag-group-list"]')!; + const label = queryOne('[data-slot="label"]')!; + const description = queryOne('[data-slot="description"]')!; + const error = queryOne('[data-slot="error-message"]')!; + + expect(list.getAttribute("aria-label")).toBeNull(); + expect(list.getAttribute("aria-labelledby")).toBe(label.id); + expect(label.tagName).toBe("SPAN"); + expect(list.getAttribute("aria-describedby")).toContain(description.id); + expect(list.getAttribute("aria-describedby")).toContain(error.id); + expect(error.className).toContain("hv-error-message"); + expect(error.getAttribute("slot")).toBe("errorMessage"); + }); + + it("applies group size and variant to every tag", async () => { + await mountGroup({ props: { size: "lg", variant: "surface" } }); + const rows = [...queryAll('[data-slot="tag"]')]; + + for (const element of rows) { + expect(element.className).toContain("hv-tag--lg"); + expect(element.className).toContain("hv-tag--surface"); + } + }); + + it("keeps caller class, attrs and listeners on the semantic nodes", async () => { + const onClick = vi.fn(); + const caller = mount(TagGroup, { + props: { selectionMode: "none", class: "caller", onClick }, + attrs: { "data-test": "group" }, + slots: { + default: () => [ + h( + TagGroupList, + { class: "list-caller" }, + { + default: () => [ + h(Tag, { id: "a", class: "tag-caller" }, () => "A"), + ], + }, + ), + ], + }, + attachTo: document.body, + }); + wrappers.push(caller); + await nextTick(); + await settle(); + const root = queryOne('[data-slot="tag-group"]')!; + const list = queryOne('[data-slot="tag-group-list"]')!; + const tag = queryOne('[data-slot="tag"]')!; + + expect(root.className).toContain("hv-tag-group"); + expect(root.className).toContain("caller"); + expect(root.getAttribute("data-test")).toBe("group"); + expect(list.className).toContain("hv-tag-group__list"); + expect(list.className).toContain("list-caller"); + expect(tag.className).toContain("hv-tag"); + expect(tag.className).toContain("tag-caller"); + expect(tag.getAttribute("aria-selected")).toBeNull(); + + tag.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + expect(onClick).toHaveBeenCalledTimes(1); + }); +}); + +describe("TagGroup selection", () => { + it("toggles a single selection and reflects it in ARIA and data attributes", async () => { + const onUpdate = vi.fn(); + await mountGroup({ props: { "onUpdate:modelValue": onUpdate } }); + const news = row("资讯")!; + + expect(news.getAttribute("aria-selected")).toBe("false"); + expect(news.hasAttribute("data-selected")).toBe(false); + + news.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + + expect(onUpdate).toHaveBeenCalledTimes(1); + expect(onUpdate.mock.calls[0][0]).toEqual(["news"]); + expect(news.getAttribute("aria-selected")).toBe("true"); + expect(news.getAttribute("data-selected")).toBe("true"); + }); + + it("clears a single selection on a second activation", async () => { + const selected = ref(["news"]); + const Demo = defineComponent({ + setup() { + return () => + h( + TagGroup, + { + "aria-label": "分类", + selectionMode: "single", + modelValue: selected.value, + "onUpdate:modelValue": (keys: (string | number)[]) => { + selected.value = keys as string[]; + }, + }, + { + default: () => [ + h(TagGroupList, null, { + default: () => [ + h( + Tag, + { id: "news", key: "news" }, + { default: () => "资讯" }, + ), + h( + Tag, + { id: "travel", key: "travel" }, + { default: () => "旅行" }, + ), + ], + }), + ], + }, + ); + }, + }); + const wrapper = mount(Demo, { attachTo: document.body }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + expect(row("资讯")!.getAttribute("aria-selected")).toBe("true"); + + row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + + expect(selected.value).toEqual([]); + expect(row("资讯")!.getAttribute("aria-selected")).toBe("false"); + }); + + it("honours disallowEmptySelection", async () => { + const onUpdate = vi.fn(); + await mountGroup({ + props: { + modelValue: ["news"], + disallowEmptySelection: true, + "onUpdate:modelValue": onUpdate, + }, + }); + + row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + + expect(onUpdate).not.toHaveBeenCalled(); + expect(row("资讯")!.getAttribute("aria-selected")).toBe("true"); + }); + + it("accumulates multiple selection and marks the grid multiselectable", async () => { + const onUpdate = vi.fn(); + await mountGroup({ + props: { selectionMode: "multiple", "onUpdate:modelValue": onUpdate }, + }); + const list = queryOne('[data-slot="tag-group-list"]')!; + + expect(list.getAttribute("aria-multiselectable")).toBe("true"); + + row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + + expect(onUpdate.mock.calls.at(-1)?.[0]).toEqual(["news", "travel"]); + expect(row("资讯")!.getAttribute("aria-selected")).toBe("true"); + expect(row("旅行")!.getAttribute("aria-selected")).toBe("true"); + }); + + it("keeps the accepted value when the parent rejects the proposal", async () => { + const onUpdate = vi.fn(); + await mountGroup({ + props: { modelValue: [], "onUpdate:modelValue": onUpdate }, + }); + + row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + await nextTick(); + + expect(onUpdate).toHaveBeenCalledWith(["travel"]); + expect(row("旅行")!.getAttribute("aria-selected")).toBe("false"); + }); + + it("accepts a rejected proposal again after the parent starts accepting", async () => { + const accepted = ref(null); + const Demo = defineComponent({ + setup() { + return () => + h( + TagGroup, + { + selectionMode: "single", + "aria-label": "分类", + modelValue: accepted.value ?? [], + "onUpdate:modelValue": (keys: (string | number)[]) => { + if (accepted.value !== null) accepted.value = keys as string[]; + }, + }, + { + default: () => [ + h(TagGroupList, null, { + default: () => [ + h(Tag, { id: "news" }, () => "资讯"), + h(Tag, { id: "travel" }, () => "旅行"), + ], + }), + ], + }, + ); + }, + }); + const wrapper = mount(Demo, { attachTo: document.body }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + expect(row("旅行")!.getAttribute("aria-selected")).toBe("false"); + + accepted.value = []; + await nextTick(); + row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + expect(row("旅行")!.getAttribute("aria-selected")).toBe("true"); + }); + + it("disables keys and individual tags without selecting them", async () => { + const onUpdate = vi.fn(); + await mountGroup({ + tags: [ + { id: "news", label: "资讯" }, + { id: "travel", label: "旅行", disabled: true }, + { id: "gaming", label: "游戏" }, + ], + props: { + disabledKeys: ["gaming"], + "onUpdate:modelValue": onUpdate, + }, + }); + + expect(row("旅行")!.getAttribute("aria-disabled")).toBe("true"); + expect(row("旅行")!.getAttribute("data-disabled")).toBe("true"); + expect(row("游戏")!.getAttribute("aria-disabled")).toBe("true"); + expect(row("资讯")!.hasAttribute("aria-disabled")).toBe(false); + + row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + row("游戏")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + + expect(onUpdate).not.toHaveBeenCalled(); + }); + + it("disables the whole group", async () => { + const onUpdate = vi.fn(); + await mountGroup({ + props: { isDisabled: true, "onUpdate:modelValue": onUpdate }, + }); + + for (const label of ["资讯", "旅行", "游戏"]) + expect(row(label)!.getAttribute("aria-disabled")).toBe("true"); + + row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + expect(onUpdate).not.toHaveBeenCalled(); + }); +}); + +describe("TagGroup removal", () => { + it("renders a default remove button only when removal is allowed", async () => { + await mountGroup(); + expect(queryOne('[data-slot=\"tag-remove-button\"]')).toBeNull(); + + await mountGroup({ props: { onRemove: vi.fn() } }); + const buttons = [...queryAll('[data-slot="tag-remove-button"]')]; + + expect(buttons).toHaveLength(3); + expect(buttons[0].getAttribute("aria-label")).toBe("Remove tag 资讯"); + expect(buttons[0].tagName).toBe("BUTTON"); + expect(buttons[0].getAttribute("type")).toBe("button"); + }); + + it("requests removal without changing the selection", async () => { + const onRemove = vi.fn(); + const onUpdate = vi.fn(); + await mountGroup({ props: { onRemove, "onUpdate:modelValue": onUpdate } }); + + queryAll('[data-slot="tag-remove-button"]')[1].dispatchEvent( + new MouseEvent("click", { bubbles: true }), + ); + await nextTick(); + + expect(onRemove).toHaveBeenCalledTimes(1); + expect(onRemove.mock.calls[0][0]).toEqual(["travel"]); + expect(onUpdate).not.toHaveBeenCalled(); + }); + + it("replaces the default button with a custom TagRemoveButton", async () => { + const onRemove = vi.fn(); + const custom = mount(TagGroup, { + props: { selectionMode: "single", "aria-label": "分类", onRemove }, + slots: { + default: () => [ + h(TagGroupList, null, { + default: () => [ + h( + Tag, + { id: "news" }, + { + default: () => [ + "资讯", + h( + TagRemoveButton, + { "data-test": "custom" }, + { default: () => h("span", "×") }, + ), + ], + }, + ), + ], + }), + ], + }, + attachTo: document.body, + }); + wrappers.push(custom); + await nextTick(); + await settle(); + const buttons = [...queryAll('[data-slot="tag-remove-button"]')]; + + expect(buttons).toHaveLength(1); + expect(buttons[0].getAttribute("data-test")).toBe("custom"); + expect(buttons[0].textContent).toBe("×"); + expect(buttons[0].getAttribute("aria-label")).toBe("Remove tag 资讯"); + + buttons[0].dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + expect(onRemove).toHaveBeenCalledWith(["news"]); + }); + + it("removes the focused tag with Delete and Backspace", async () => { + const onRemove = vi.fn(); + await mountGroup({ props: { onRemove } }); + + row("旅行")!.focus(); + await nextTick(); + row("旅行")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "Delete", bubbles: true }), + ); + await nextTick(); + expect(onRemove).toHaveBeenLastCalledWith(["travel"]); + + row("旅行")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "Backspace", bubbles: true }), + ); + await nextTick(); + expect(onRemove).toHaveBeenCalledTimes(2); + expect(onRemove).toHaveBeenLastCalledWith(["travel"]); + }); + + it("moves focus to the next neighbour after a confirmed removal", async () => { + const tags = ref([ + { id: "news", label: "资讯" }, + { id: "travel", label: "旅行" }, + { id: "gaming", label: "游戏" }, + ]); + const Demo = defineComponent({ + setup() { + return () => + h( + TagGroup, + { + "aria-label": "分类", + onRemove: (keys: (string | number)[]) => { + tags.value = tags.value.filter((tag) => !keys.includes(tag.id)); + }, + }, + { + default: () => [ + h(TagGroupList, null, { + default: () => + tags.value.map((tag) => + h( + Tag, + { id: tag.id, key: tag.id }, + { default: () => tag.label }, + ), + ), + }), + ], + }, + ); + }, + }); + const wrapper = mount(Demo, { attachTo: document.body }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + row("旅行")!.focus(); + await nextTick(); + document + .querySelectorAll('[data-slot="tag-remove-button"]')[1] + .dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + await nextTick(); + + expect(row("旅行")).toBeUndefined(); + expect(document.activeElement).toBe(row("游戏")); + }); + + it("moves focus to the neighbour after removing through the button", async () => { + const tags = ref([ + { id: "news", label: "资讯" }, + { id: "travel", label: "旅行" }, + { id: "gaming", label: "游戏" }, + ]); + const Demo = defineComponent({ + setup() { + return () => + h( + TagGroup, + { + "aria-label": "分类", + onRemove: (keys: (string | number)[]) => { + tags.value = tags.value.filter((tag) => !keys.includes(tag.id)); + }, + }, + { + default: () => [ + h(TagGroupList, null, { + default: () => + tags.value.map((tag) => + h( + Tag, + { id: tag.id, key: tag.id }, + { default: () => tag.label }, + ), + ), + }), + ], + }, + ); + }, + }); + const wrapper = mount(Demo, { attachTo: document.body }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + queryAll('[data-slot="tag-remove-button"]')[1].dispatchEvent( + new MouseEvent("click", { bubbles: true }), + ); + await nextTick(); + await nextTick(); + + expect(row("旅行")).toBeUndefined(); + expect(document.activeElement).toBe(row("游戏")); + }); + + it("focuses the grid when the last tag is removed", async () => { + const tags = ref([{ id: "news", label: "资讯" }]); + const Demo = defineComponent({ + setup() { + return () => + h( + TagGroup, + { + "aria-label": "分类", + onRemove: () => { + tags.value = []; + }, + }, + { + default: () => [ + h(TagGroupList, null, { + default: () => + tags.value.map((tag) => + h( + Tag, + { id: tag.id, key: tag.id }, + { default: () => tag.label }, + ), + ), + }), + ], + }, + ); + }, + }); + const wrapper = mount(Demo, { attachTo: document.body }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + row("资讯")!.focus(); + await nextTick(); + document + .querySelector('[data-slot="tag-remove-button"]')! + .dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + await nextTick(); + + const list = queryOne('[data-slot="tag-group-list"]')!; + + expect(list.children).toHaveLength(0); + expect(list.getAttribute("tabindex")).toBe("0"); + expect(document.activeElement).toBe(list); + }); + + it("keeps the tag and its focus when the parent rejects the removal", async () => { + const onRemove = vi.fn(); + await mountGroup({ props: { onRemove } }); + + row("旅行")!.focus(); + await nextTick(); + document + .querySelectorAll('[data-slot="tag-remove-button"]')[1] + .dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + await nextTick(); + + expect(onRemove).toHaveBeenCalledTimes(1); + expect(row("旅行")).toBeDefined(); + expect(document.activeElement).toBe(row("旅行")); + + row("旅行")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "Delete", bubbles: true }), + ); + await nextTick(); + expect(onRemove).toHaveBeenCalledTimes(2); + }); +}); + +describe("TagGroup keyboard", () => { + it("moves focus with the arrow keys, Home and End and skips disabled tags", async () => { + await mountGroup({ + tags: [ + { id: "news", label: "资讯" }, + { id: "travel", label: "旅行", disabled: true }, + { id: "gaming", label: "游戏" }, + ], + }); + row("资讯")!.focus(); + await nextTick(); + expect(document.activeElement).toBe(row("资讯")); + + row("资讯")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }), + ); + await nextTick(); + await nextTick(); + expect(document.activeElement).toBe(row("游戏")); + + row("游戏")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "Home", bubbles: true }), + ); + await nextTick(); + await nextTick(); + expect(document.activeElement).toBe(row("资讯")); + + row("资讯")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "End", bubbles: true }), + ); + await nextTick(); + await nextTick(); + expect(document.activeElement).toBe(row("游戏")); + + row("游戏")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }), + ); + await nextTick(); + await nextTick(); + expect(document.activeElement).toBe(row("资讯")); + }); + + it("reverses the horizontal direction in RTL", async () => { + await mountGroup({ + props: { dir: "rtl" }, + tags: [ + { id: "news", label: "资讯" }, + { id: "travel", label: "旅行" }, + { id: "gaming", label: "游戏" }, + ], + }); + row("资讯")!.focus(); + await nextTick(); + + row("资讯")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }), + ); + await nextTick(); + await nextTick(); + expect(document.activeElement).toBe(row("旅行")); + + row("旅行")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }), + ); + await nextTick(); + await nextTick(); + expect(document.activeElement).toBe(row("资讯")); + }); + + it("activates once on the Space key sequence and lets the caller cancel", async () => { + const onUpdate = vi.fn(); + await mountGroup({ props: { "onUpdate:modelValue": onUpdate } }); + row("资讯")!.focus(); + await nextTick(); + + row("资讯")!.dispatchEvent( + new KeyboardEvent("keydown", { + key: " ", + bubbles: true, + cancelable: true, + }), + ); + expect(onUpdate).not.toHaveBeenCalled(); + row("资讯")!.dispatchEvent( + new KeyboardEvent("keyup", { key: " ", bubbles: true, cancelable: true }), + ); + await nextTick(); + expect(onUpdate).toHaveBeenCalledTimes(1); + + const cancel = (event: Event) => event.preventDefault(); + const list = queryOne('[data-slot="tag-group-list"]')!; + list.addEventListener("keyup", cancel, true); + row("资讯")!.dispatchEvent( + new KeyboardEvent("keydown", { + key: " ", + bubbles: true, + cancelable: true, + }), + ); + row("资讯")!.dispatchEvent( + new KeyboardEvent("keyup", { key: " ", bubbles: true, cancelable: true }), + ); + await nextTick(); + list.removeEventListener("keyup", cancel, true); + expect(onUpdate).toHaveBeenCalledTimes(1); + }); + + it("activates with Enter once", async () => { + const onUpdate = vi.fn(); + await mountGroup({ props: { "onUpdate:modelValue": onUpdate } }); + row("旅行")!.focus(); + await nextTick(); + + row("旅行")!.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }), + ); + await nextTick(); + + expect(onUpdate).toHaveBeenCalledTimes(1); + expect(onUpdate).toHaveBeenCalledWith(["travel"]); + }); +}); + +describe("TagGroupList items", () => { + it("renders data items in order and keys them by id", async () => { + const items = [ + { id: "a", name: "A" }, + { id: 2, name: "B" }, + { id: "b", name: "C" }, + ]; + const wrapper = mount(TagGroup, { + props: { "aria-label": "分类" }, + slots: { + default: () => [ + h( + TagGroupList, + { items }, + { + default: ({ + item, + }: { + item: { id: string | number; name: string }; + }) => h(Tag, { id: item.id, key: item.id }, () => item.name), + }, + ), + ], + }, + attachTo: document.body, + }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + expect(queryAll('[data-slot="tag"]').map((tag) => tag.textContent)).toEqual( + ["A", "B", "C"], + ); + }); + + it("renders the empty slot when items is empty", async () => { + const wrapper = mount(TagGroup, { + props: { "aria-label": "分类" }, + slots: { + default: () => [ + h( + TagGroupList, + { items: [] as { id: string }[] }, + { + default: () => [], + empty: () => h("p", { "data-test": "empty" }, "暂无标签"), + }, + ), + ], + }, + attachTo: document.body, + }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + expect(queryAll('[data-slot="tag"]')).toHaveLength(0); + expect(queryOne('[data-test="empty"]')).not.toBeNull(); + }); + + it("rejects duplicate collection keys", async () => { + const errors: string[] = []; + const app = createApp({ + render: () => + h( + TagGroup, + { "aria-label": "分类" }, + { + default: () => [ + h(TagGroupList, null, { + default: () => [ + h(Tag, { id: "dup" }, () => "A"), + h(Tag, { id: "dup" }, () => "B"), + ], + }), + ], + }, + ), + }); + + app.config.errorHandler = (error) => { + errors.push(String((error as Error).message)); + }; + app.config.warnHandler = () => {}; + const host = document.createElement("div"); + + document.body.appendChild(host); + app.mount(host); + await nextTick(); + app.unmount(); + host.remove(); + + expect(errors.join(" ")).toMatch(/Duplicate collection key/); + }); + + it("keeps numeric and string keys distinct", async () => { + const onChange = vi.fn(); + await mountGroup({ + tags: [ + { id: 0, label: "零" }, + { id: "0", label: "字符串零" }, + ], + props: { onSelectionChange: onChange }, + }); + + row("零")!.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + + expect(onChange).toHaveBeenCalledWith([0]); + expect(row("字符串零")!.getAttribute("aria-selected")).toBe("false"); + }); +}); + +describe("ErrorMessage", () => { + it("renders standalone with baseline markers", async () => { + const wrapper = mount(ErrorMessage, { + slots: { default: () => "出错了" }, + attachTo: document.body, + }); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + const message = queryOne('[data-slot="error-message"]')!; + + expect(message.tagName).toBe("P"); + expect(message.className).toContain("hv-error-message"); + expect(message.getAttribute("slot")).toBe("errorMessage"); + expect(message.textContent).toBe("出错了"); + expect(message.id).not.toBe(""); + }); + + it("keeps its own unique id per instance", async () => { + const wrapper = mount( + defineComponent({ + setup() { + return () => + h("div", [ + h(ErrorMessage, { key: "a" }, () => "一"), + h(ErrorMessage, { key: "b" }, () => "二"), + ]); + }, + }), + { attachTo: document.body }, + ); + wrappers.push(wrapper); + await nextTick(); + await settle(); + + const [first, second] = queryAll('[data-slot="error-message"]'); + + expect(first.id).not.toBe(second.id); + }); +}); + +describe("Tag demos and documentation", () => { + const previews = [ + "basic", + "sizes", + "variants", + "disabled", + "selection-modes", + "controlled", + "with-error-message", + "with-list-data", + "with-prefix", + "with-remove-button", + "render-function", + "custom-styles", + ]; + + it("includes every preview from the pinned upstream documents", () => { + const document = readFileSync("apps/docs/components/tag-group.md", "utf8"); + const names = [ + ...document.matchAll(/ match[1]); + + expect(names).toEqual(previews); + for (const name of previews) { + const source = readFileSync( + `apps/docs/demos/tag-group-${name}.vue`, + "utf8", + ); + + expect(source).toContain("