From b086d7f30d256158631ceb57a2283633588cdc4f Mon Sep 17 00:00:00 2001 From: maoyingjie Date: Thu, 22 Oct 2026 18:25:08 +0800 Subject: [PATCH] feat: add Disclosure DisclosureGroup and Accordion --- AGENTS.md | 9 + apps/docs/.vitepress/theme/Layout.vue | 6 + apps/docs/components.md | 3 + apps/docs/components/accordion.md | 171 +++ apps/docs/components/disclosure-group.md | 115 ++ apps/docs/components/disclosure.md | 174 +++ apps/docs/demos/accordion-basic.vue | 94 ++ apps/docs/demos/accordion-controlled.vue | 94 ++ .../docs/demos/accordion-custom-indicator.vue | 77 ++ apps/docs/demos/accordion-custom-styles.vue | 42 + apps/docs/demos/accordion-disabled.vue | 85 ++ apps/docs/demos/accordion-faq.vue | 83 ++ apps/docs/demos/accordion-multiple.vue | 50 + apps/docs/demos/accordion-render-function.vue | 83 ++ apps/docs/demos/accordion-surface.vue | 94 ++ .../demos/accordion-without-separator.vue | 58 + apps/docs/demos/disclosure-basic.vue | 50 + apps/docs/demos/disclosure-custom-styles.vue | 43 + apps/docs/demos/disclosure-group-basic.vue | 109 ++ .../demos/disclosure-group-controlled.vue | 145 +++ .../demos/disclosure-group-custom-styles.vue | 49 + .../docs/demos/disclosure-render-function.vue | 50 + docs/compatibility.md | 6 +- docs/migration-handoff.md | 6 + docs/migrations/M13-M20-lessons.md | 45 + .../M21-M23-disclosure-accordion-prompt.md | 103 ++ docs/migrations/M21-M23-review.md | 141 +++ docs/migrations/M21-disclosure.md | 130 ++ docs/migrations/M22-disclosure-group.md | 112 ++ docs/migrations/M23-accordion.md | 125 ++ docs/upstream.md | 10 + docs/verification.md | 57 + package.json | 2 +- packages/styles/components/accordion.css | 163 +++ .../styles/components/disclosure-group.css | 10 + packages/styles/components/disclosure.css | 93 ++ packages/styles/index.css | 6 + packages/styles/src/index.ts | 51 + .../src/components/accordion/Accordion.vue | 108 ++ .../components/accordion/AccordionBody.vue | 30 + .../components/accordion/AccordionHeading.vue | 33 + .../accordion/AccordionIndicator.vue | 59 + .../components/accordion/AccordionItem.vue | 74 ++ .../components/accordion/AccordionPanel.vue | 45 + .../components/accordion/AccordionTrigger.vue | 94 ++ .../vue/src/components/accordion/context.ts | 24 + .../disclosure-group/DisclosureGroup.vue | 88 ++ .../components/disclosure-group/context.ts | 164 +++ .../useDisclosureGroupNavigation.ts | 100 ++ .../src/components/disclosure/Disclosure.vue | 68 + .../components/disclosure/DisclosureBody.vue | 26 + .../disclosure/DisclosureChevronIcon.vue | 30 + .../disclosure/DisclosureContent.vue | 42 + .../disclosure/DisclosureHeading.vue | 34 + .../disclosure/DisclosureIndicator.vue | 55 + .../disclosure/DisclosureTrigger.vue | 87 ++ .../components/disclosure/triggerEvents.ts | 180 +++ .../disclosure/useDisclosureItem.ts | 129 ++ .../disclosure/useDisclosurePanelHeight.ts | 118 ++ packages/vue/src/index.ts | 50 + packages/vue/src/types.ts | 47 + tests/disclosure-accordion.test.ts | 1121 +++++++++++++++++ tests/ssr.test.ts | 51 + 63 files changed, 5597 insertions(+), 4 deletions(-) create mode 100644 apps/docs/components/accordion.md create mode 100644 apps/docs/components/disclosure-group.md create mode 100644 apps/docs/components/disclosure.md create mode 100644 apps/docs/demos/accordion-basic.vue create mode 100644 apps/docs/demos/accordion-controlled.vue create mode 100644 apps/docs/demos/accordion-custom-indicator.vue create mode 100644 apps/docs/demos/accordion-custom-styles.vue create mode 100644 apps/docs/demos/accordion-disabled.vue create mode 100644 apps/docs/demos/accordion-faq.vue create mode 100644 apps/docs/demos/accordion-multiple.vue create mode 100644 apps/docs/demos/accordion-render-function.vue create mode 100644 apps/docs/demos/accordion-surface.vue create mode 100644 apps/docs/demos/accordion-without-separator.vue create mode 100644 apps/docs/demos/disclosure-basic.vue create mode 100644 apps/docs/demos/disclosure-custom-styles.vue create mode 100644 apps/docs/demos/disclosure-group-basic.vue create mode 100644 apps/docs/demos/disclosure-group-controlled.vue create mode 100644 apps/docs/demos/disclosure-group-custom-styles.vue create mode 100644 apps/docs/demos/disclosure-render-function.vue create mode 100644 docs/migrations/M13-M20-lessons.md create mode 100644 docs/migrations/M21-M23-disclosure-accordion-prompt.md create mode 100644 docs/migrations/M21-M23-review.md create mode 100644 docs/migrations/M21-disclosure.md create mode 100644 docs/migrations/M22-disclosure-group.md create mode 100644 docs/migrations/M23-accordion.md create mode 100644 packages/styles/components/accordion.css create mode 100644 packages/styles/components/disclosure-group.css create mode 100644 packages/styles/components/disclosure.css create mode 100644 packages/vue/src/components/accordion/Accordion.vue create mode 100644 packages/vue/src/components/accordion/AccordionBody.vue create mode 100644 packages/vue/src/components/accordion/AccordionHeading.vue create mode 100644 packages/vue/src/components/accordion/AccordionIndicator.vue create mode 100644 packages/vue/src/components/accordion/AccordionItem.vue create mode 100644 packages/vue/src/components/accordion/AccordionPanel.vue create mode 100644 packages/vue/src/components/accordion/AccordionTrigger.vue create mode 100644 packages/vue/src/components/accordion/context.ts create mode 100644 packages/vue/src/components/disclosure-group/DisclosureGroup.vue create mode 100644 packages/vue/src/components/disclosure-group/context.ts create mode 100644 packages/vue/src/components/disclosure-group/useDisclosureGroupNavigation.ts create mode 100644 packages/vue/src/components/disclosure/Disclosure.vue create mode 100644 packages/vue/src/components/disclosure/DisclosureBody.vue create mode 100644 packages/vue/src/components/disclosure/DisclosureChevronIcon.vue create mode 100644 packages/vue/src/components/disclosure/DisclosureContent.vue create mode 100644 packages/vue/src/components/disclosure/DisclosureHeading.vue create mode 100644 packages/vue/src/components/disclosure/DisclosureIndicator.vue create mode 100644 packages/vue/src/components/disclosure/DisclosureTrigger.vue create mode 100644 packages/vue/src/components/disclosure/triggerEvents.ts create mode 100644 packages/vue/src/components/disclosure/useDisclosureItem.ts create mode 100644 packages/vue/src/components/disclosure/useDisclosurePanelHeight.ts create mode 100644 tests/disclosure-accordion.test.ts diff --git a/AGENTS.md b/AGENTS.md index db922f8..f4d08d1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -326,3 +326,12 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V - Label 的显式 ID 优先,自动 ID 按实例唯一;标签注册需清理陈旧引用。标签 ID/for 与组件类型在渲染时读取,不缓存 setup 快照;验证增删、重排、卸载及 SSR/实际水合。 - 不同上下文的 Label 有明确所有者。indicator 桥接保存创建时的 fieldScope:当前 indicator 的标签屏蔽外围字段状态,嵌套字段拥有自己的标签。新增其他组合组件前先验证不会让内部 TextField/Choice 标签污染外层名称。 - 新组件页同时加入实际 Layout 导航,回归侧栏/移动菜单、选中态和相邻页面;只改 components.md 总览不算导航接入。 + +## 近期返工规则与后续任务入口(2026-10-22) + +- 新批次先读 [M13–M20 问题总结与执行清单](docs/migrations/M13-M20-lessons.md),将其中适用的失败场景纳入实际回归,不以测试总数、外层状态或构建成功替代验收。 +- 计划交给其他 AI 的下一批为 [M21–M23 折叠家族](docs/migrations/M21-M23-disclosure-accordion-prompt.md)。DisclosureGroup 的 useDisclosureGroupNavigation 也是基线公共能力;未执行的计划不能写成已实现。 + +## 独立复核方式(用户约定,2026-10-22) + +- 复核以代码规范、设计/状态协议、公共 API、固定 HeroUI 基线差异和集成回归为主;浏览器只重点验证测量/焦点/动画等关键风险,不逐个点击全部演示。全量示例清单、编译与自动挂载仍按适用性执行,不能因减少手工点击而省略契约检查。 diff --git a/apps/docs/.vitepress/theme/Layout.vue b/apps/docs/.vitepress/theme/Layout.vue index 4f0727f..e00e17e 100644 --- a/apps/docs/.vitepress/theme/Layout.vue +++ b/apps/docs/.vitepress/theme/Layout.vue @@ -45,6 +45,7 @@ const groups = [ { title: "组件", items: [ + { title: "Accordion 手风琴", url: "/components/accordion" }, { title: "Alert 警告", url: "/components/alert" }, { title: "Avatar 头像", url: "/components/avatar" }, { title: "AvatarGroup 头像组", url: "/components/avatar-group" }, @@ -57,6 +58,11 @@ const groups = [ { title: "Chip 标签", url: "/components/chip" }, { title: "CloseButton 关闭按钮", url: "/components/close-button" }, { title: "Description 描述", url: "/components/description" }, + { title: "Disclosure 折叠面板", url: "/components/disclosure" }, + { + title: "DisclosureGroup 折叠面板组", + url: "/components/disclosure-group", + }, { title: "EmptyState 空状态", url: "/components/empty-state" }, { title: "FieldError 字段错误", url: "/components/field-error" }, { title: "Fieldset 字段组", url: "/components/fieldset" }, diff --git a/apps/docs/components.md b/apps/docs/components.md index c3629c0..46df12f 100644 --- a/apps/docs/components.md +++ b/apps/docs/components.md @@ -3,6 +3,7 @@ title: 组件 description: 已迁移组件及文档 --- +- [Accordion 手风琴](./components/accordion) - [Alert 警告](./components/alert) - [Avatar 头像](./components/avatar) - [AvatarGroup 头像组](./components/avatar-group) @@ -13,6 +14,8 @@ description: 已迁移组件及文档 - [Chip 标签](./components/chip) - [CloseButton 关闭按钮](./components/close-button) - [Description 描述](./components/description) +- [Disclosure 折叠面板](./components/disclosure) +- [DisclosureGroup 折叠面板组](./components/disclosure-group) - [EmptyState 空状态](./components/empty-state) - [FieldError 字段错误](./components/field-error) - [Input 输入框](./components/input) diff --git a/apps/docs/components/accordion.md b/apps/docs/components/accordion.md new file mode 100644 index 0000000..4ce7b7e --- /dev/null +++ b/apps/docs/components/accordion.md @@ -0,0 +1,171 @@ +--- +title: Accordion 手风琴 +description: 用于在紧凑空间中组织信息的可折叠内容面板 +component: accordion +group: 组件 +--- + +## 用法 + +```vue + + + +``` + + + +## 组件结构 + +```vue + + + +``` + +Accordion 复用 DisclosureGroup 的展开键协议(数组、字符串/数字 key),部件与布局按手风琴基线独立。 + +## 示例 + +### 表面样式 + + + +### 无分隔线 + + + +### 多项展开 + + + +### 禁用状态 + + + +### 受控组件 + + + +### 自定义指示器 + + + +### 渲染函数 + +上游 `render` 映射为 `as` 与透传属性。 + + + +### 常见问题布局 + + + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 CSS + +```css +@layer components { + .hv-accordion { + @apply rounded-xl bg-gray-50; + } + + .hv-accordion__trigger { + @apply font-semibold text-lg; + } +} +``` + +## 样式参考 + +- `.hv-accordion` - 根容器 +- `.hv-accordion__item` - 单项与分隔线 +- `.hv-accordion__heading` / `.hv-accordion__trigger` / `.hv-accordion__indicator` +- `.hv-accordion__panel` / `.hv-accordion__body` / `.hv-accordion__body-inner` +- `.hv-accordion--surface` - 表面变体 + +## API 参考 + +### Accordion + +| 属性 | 类型 | 默认值 | 描述 | +| ------------------------ | --------------------------- | ----------- | -------------------- | +| `expandedKeys` | `Array` | - | 受控展开 key | +| `defaultExpandedKeys` | `Array` | `[]` | 初始展开 key | +| `allowsMultipleExpanded` | `boolean` | `false` | 是否允许多项同时展开 | +| `isDisabled` | `boolean` | `false` | 禁用整个 Accordion | +| `variant` | `"default" \| "surface"` | `"default"` | 视觉变体 | +| `hideSeparator` | `boolean` | `false` | 隐藏项之间的分隔线 | +| `as` | `string` | `"div"` | 根元素 | +| `class` | `string \| Array \| Object` | - | 额外的 CSS 类 | + +### AccordionItem + +| 属性 | 类型 | 默认值 | 描述 | +| ----------------- | ------------------ | ------- | -------------------- | +| `id` | `string \| number` | - | 该项唯一标识(组键) | +| `expanded` | `boolean` | - | 受控展开状态 | +| `defaultExpanded` | `boolean` | `false` | 初始展开 | +| `isDisabled` | `boolean` | `false` | 禁用该项 | +| `as` | `string` | `"div"` | 项根元素 | + +### AccordionHeading / Trigger / Panel / Body / Indicator + +与 Disclosure 对应部件语义一致,使用 `hv-accordion__*` 样式;Trigger 为 `type="button"`,Panel 负责高度动画,Indicator 支持自定义图标插槽。 + +## 相关组件 + +- [Disclosure 折叠面板](./disclosure) +- [DisclosureGroup 折叠面板组](./disclosure-group) diff --git a/apps/docs/components/disclosure-group.md b/apps/docs/components/disclosure-group.md new file mode 100644 index 0000000..ba9ebe9 --- /dev/null +++ b/apps/docs/components/disclosure-group.md @@ -0,0 +1,115 @@ +--- +title: DisclosureGroup 折叠面板组 +description: 管理多个 Disclosure 项展开状态的容器 +component: disclosure-group +group: 组件 +--- + +## 用法 + +```vue + + + +``` + + + +## 组件结构 + +```vue + + + +``` + +`DisclosureGroup` 用数组管理展开键(空集合为 `[]`),支持字符串或数字 key(`1` 与 `"1"` 不会碰撞)。 + +## 示例 + +### 受控组件 + +可使用 `expandedKeys` 与 `update:expandedKeys` 配合 `useDisclosureGroupNavigation` 外部导航。 + + + +`useDisclosureGroupNavigation` 为公开 composable:提供 `currentIndex`、`isPrevDisabled`、`isNextDisabled`、`onPrevious`、`onNext`。单选替换集合,多选增量添加;不修改传入集合。 + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 CSS + +```css +@layer components { + .hv-disclosure-group { + @apply w-full; + contain: layout style; + } +} +``` + +## 样式参考 + +- `.hv-disclosure-group` - 基础容器样式,含布局 containment + +## API 参考 + +### DisclosureGroup + +| 属性 | 类型 | 默认值 | 描述 | +| ------------------------ | ------------------------------ | ------- | ------------------------------------- | +| `expandedKeys` | `Array` | - | 受控展开项(`v-model:expanded-keys`) | +| `defaultExpandedKeys` | `Array` | `[]` | 初始展开项 | +| `allowsMultipleExpanded` | `boolean` | `false` | 是否允许多项同时展开 | +| `isDisabled` | `boolean` | `false` | 禁用组内所有 Disclosure | +| `as` | `string` | `"div"` | 根元素 | +| `class` | `string \| Array \| Object` | - | 合并到根元素 | +| 默认插槽 | `{ expandedKeys, isDisabled }` | - | Disclosure 项 | + +事件:`update:expandedKeys`、`expandedChange`。 + +### useDisclosureGroupNavigation + +| 属性 | 类型 | 默认值 | 描述 | +| ------------------------ | ----------------------------------------- | ------- | ------------- | +| `expandedKeys` | `Array` 或 getter | - | 当前展开键 | +| `itemIds` | `Array` 或 getter | `[]` | 成员 key 列表 | +| `onExpandedChange` | `(keys: Array) => void` | - | 提交新集合 | +| `allowsMultipleExpanded` | `boolean` | `false` | 多选增量 | + +返回:`currentIndex`、`isPrevDisabled`、`isNextDisabled`、`onPrevious`、`onNext`。 + +## 相关组件 + +- [Disclosure 折叠面板](./disclosure) +- [Accordion 手风琴](./accordion) diff --git a/apps/docs/components/disclosure.md b/apps/docs/components/disclosure.md new file mode 100644 index 0000000..7000e20 --- /dev/null +++ b/apps/docs/components/disclosure.md @@ -0,0 +1,174 @@ +--- +title: Disclosure 折叠面板 +description: 可折叠区块,包含标题、触发按钮与内容面板 +component: disclosure +group: 组件 +--- + +## 用法 + +```vue + + + +``` + + + +## 组件结构 + +```vue + + + +``` + +`Disclosure` 渲染为带 `data-slot="disclosure"` 的容器。`DisclosureTrigger` 默认是 `type="button"` 的按钮,点击/Enter/Space 切换展开;`as-child` 可把触发语义合并到 `Button` 等单个子元素。 + +## 示例 + +### 渲染函数 + +上游 `render` 用于替换根元素;Vue 版通过 `as` 更换元素类型,`data-*` 等属性直接透传。 + + + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 CSS + +可使用 `@layer components` 指令自定义 Disclosure 组件类。 + +```css +@layer components { + .hv-disclosure { + @apply relative; + } + + .hv-disclosure__trigger { + @apply cursor-pointer; + } + + .hv-disclosure__indicator { + @apply transition-transform duration-300; + } + + .hv-disclosure__content { + @apply overflow-hidden transition-all; + } +} +``` + +## 样式参考 + +HeroUI 遵循 [BEM](https://getbem.com/) 方法论。类名前缀为 `hv-`。 + +### CSS 类 + +- `.hv-disclosure` - 基础容器样式 +- `.hv-disclosure__heading` - 标题包裹层 +- `.hv-disclosure__trigger` - 触发按钮样式 +- `.hv-disclosure__indicator` - 箭头指示器样式 +- `.hv-disclosure__content` - 带动画的内容容器 +- `.hv-disclosure__body` / `.hv-disclosure__body-inner` - 正文与内层 + +### 交互状态 + +- **Expanded**:指示器上 `[data-expanded="true"]` 用于旋转;内容上 `[data-expanded="true"]` +- **Focus**:触发器上 `:focus-visible` +- **Disabled**:触发器上 `:disabled` 或 `[aria-disabled="true"]` +- 内容高度使用测量变量驱动展开动画,并支持 `prefers-reduced-motion` + +## API 参考 + +### Disclosure + +| 属性 | 类型 | 默认值 | 描述 | +| ----------------- | ---------------------------- | ------- | ------------------------------------- | +| `id` | `string \| number` | - | 组键与 DOM id | +| `expanded` | `boolean` | - | 受控展开状态;配合 `v-model:expanded` | +| `defaultExpanded` | `boolean` | `false` | 非受控初始展开 | +| `isDisabled` | `boolean` | `false` | 是否禁用 | +| `as` | `string` | `"div"` | 根元素类型 | +| `class` | `string \| Array \| Object` | - | 合并到根元素 | +| 默认插槽 | `{ isExpanded, isDisabled }` | - | 内容或作用域插槽 | + +事件:`update:expanded`、`expandedChange`。 + +### DisclosureHeading + +| 属性 | 类型 | 默认值 | 描述 | +| ------- | --------------------------- | ------ | -------------- | +| `as` | `string` | `"h3"` | 标题元素 | +| `level` | `1`–`6` | `3` | 标题级别 | +| `class` | `string \| Array \| Object` | - | 合并到标题元素 | + +### DisclosureTrigger + +| 属性 | 类型 | 默认值 | 描述 | +| ------------ | ---------------------------- | ---------- | -------------------------- | +| `as` | `string` | `"button"` | 元素类型 | +| `asChild` | `boolean` | `false` | 合并到默认插槽的单个子元素 | +| `isDisabled` | `boolean` | `false` | 禁用触发 | +| `class` | `string \| Array \| Object` | - | 合并到触发器 | +| 默认插槽 | `{ isExpanded, isDisabled }` | - | 触发器内容 | + +事件:`click`(可在处理函数中 `preventDefault` 取消切换)。 + +### DisclosureContent + +| 属性 | 类型 | 默认值 | 描述 | +| -------- | ---------------------------- | ------- | ---------- | +| `as` | `string` | `"div"` | 面板元素 | +| `class` | `string \| Array \| Object` | - | 合并到面板 | +| 默认插槽 | `{ isExpanded, isDisabled }` | - | 面板内容 | + +### DisclosureBody / DisclosureIndicator + +Body 提供基线内边距与内层包装。Indicator 默认为基线 Chevron 图标,可传入自定义图标作为默认插槽;展开时附加 `data-expanded="true"` 并旋转。 + +## 相关组件 + +- [DisclosureGroup 折叠面板组](./disclosure-group) +- [Accordion 手风琴](./accordion) diff --git a/apps/docs/demos/accordion-basic.vue b/apps/docs/demos/accordion-basic.vue new file mode 100644 index 0000000..d35783d --- /dev/null +++ b/apps/docs/demos/accordion-basic.vue @@ -0,0 +1,94 @@ + + + diff --git a/apps/docs/demos/accordion-controlled.vue b/apps/docs/demos/accordion-controlled.vue new file mode 100644 index 0000000..f5bc4ba --- /dev/null +++ b/apps/docs/demos/accordion-controlled.vue @@ -0,0 +1,94 @@ + + + diff --git a/apps/docs/demos/accordion-custom-indicator.vue b/apps/docs/demos/accordion-custom-indicator.vue new file mode 100644 index 0000000..264ba92 --- /dev/null +++ b/apps/docs/demos/accordion-custom-indicator.vue @@ -0,0 +1,77 @@ + + + diff --git a/apps/docs/demos/accordion-custom-styles.vue b/apps/docs/demos/accordion-custom-styles.vue new file mode 100644 index 0000000..4f2131c --- /dev/null +++ b/apps/docs/demos/accordion-custom-styles.vue @@ -0,0 +1,42 @@ + + + diff --git a/apps/docs/demos/accordion-disabled.vue b/apps/docs/demos/accordion-disabled.vue new file mode 100644 index 0000000..495c025 --- /dev/null +++ b/apps/docs/demos/accordion-disabled.vue @@ -0,0 +1,85 @@ + + + diff --git a/apps/docs/demos/accordion-faq.vue b/apps/docs/demos/accordion-faq.vue new file mode 100644 index 0000000..4d67641 --- /dev/null +++ b/apps/docs/demos/accordion-faq.vue @@ -0,0 +1,83 @@ + + + diff --git a/apps/docs/demos/accordion-multiple.vue b/apps/docs/demos/accordion-multiple.vue new file mode 100644 index 0000000..8d676c9 --- /dev/null +++ b/apps/docs/demos/accordion-multiple.vue @@ -0,0 +1,50 @@ + + + diff --git a/apps/docs/demos/accordion-render-function.vue b/apps/docs/demos/accordion-render-function.vue new file mode 100644 index 0000000..84c9bb4 --- /dev/null +++ b/apps/docs/demos/accordion-render-function.vue @@ -0,0 +1,83 @@ + + + diff --git a/apps/docs/demos/accordion-surface.vue b/apps/docs/demos/accordion-surface.vue new file mode 100644 index 0000000..784b138 --- /dev/null +++ b/apps/docs/demos/accordion-surface.vue @@ -0,0 +1,94 @@ + + + diff --git a/apps/docs/demos/accordion-without-separator.vue b/apps/docs/demos/accordion-without-separator.vue new file mode 100644 index 0000000..b3f220c --- /dev/null +++ b/apps/docs/demos/accordion-without-separator.vue @@ -0,0 +1,58 @@ + + + diff --git a/apps/docs/demos/disclosure-basic.vue b/apps/docs/demos/disclosure-basic.vue new file mode 100644 index 0000000..11f8e8e --- /dev/null +++ b/apps/docs/demos/disclosure-basic.vue @@ -0,0 +1,50 @@ + + + diff --git a/apps/docs/demos/disclosure-custom-styles.vue b/apps/docs/demos/disclosure-custom-styles.vue new file mode 100644 index 0000000..1a7ac09 --- /dev/null +++ b/apps/docs/demos/disclosure-custom-styles.vue @@ -0,0 +1,43 @@ + + + diff --git a/apps/docs/demos/disclosure-group-basic.vue b/apps/docs/demos/disclosure-group-basic.vue new file mode 100644 index 0000000..dc11ce0 --- /dev/null +++ b/apps/docs/demos/disclosure-group-basic.vue @@ -0,0 +1,109 @@ + + + diff --git a/apps/docs/demos/disclosure-group-controlled.vue b/apps/docs/demos/disclosure-group-controlled.vue new file mode 100644 index 0000000..e8557ac --- /dev/null +++ b/apps/docs/demos/disclosure-group-controlled.vue @@ -0,0 +1,145 @@ + + + diff --git a/apps/docs/demos/disclosure-group-custom-styles.vue b/apps/docs/demos/disclosure-group-custom-styles.vue new file mode 100644 index 0000000..c968af8 --- /dev/null +++ b/apps/docs/demos/disclosure-group-custom-styles.vue @@ -0,0 +1,49 @@ + + + diff --git a/apps/docs/demos/disclosure-render-function.vue b/apps/docs/demos/disclosure-render-function.vue new file mode 100644 index 0000000..7519d68 --- /dev/null +++ b/apps/docs/demos/disclosure-render-function.vue @@ -0,0 +1,50 @@ + + + diff --git a/docs/compatibility.md b/docs/compatibility.md index b3c6e0e..2149a36 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -4,7 +4,7 @@ | 组件 | 状态 | 当前能力 / 差异 | | -------------------- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | -| accordion | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | +| accordion | 验证中(M23) | Accordion/Item/Heading/Trigger/Panel/Body/Indicator;10/10 基线例;surface/hideSeparator;复用组键协议 | | alert-dialog | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | autocomplete | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | avatar | 验证中(最小实现) | Reka Avatar 加载/回退;size/color/variant;Image asChild;AvatarGroup 继承仅限直接子级 | @@ -32,8 +32,8 @@ | progress-bar | 验证中(M18) | ProgressBar/Output/Track/Fill;7/7 基线例;确定/未知进度、min/max/formatOptions/valueLabel;custom-value 的 NumberField/Select 为原生临时控件 | | progress-circle | 验证中(M19) | ProgressCircle/Track/TrackCircle/FillCircle;7/7 基线例;圆环几何可覆盖;与 ProgressBar 共用取值语义 | | time-field | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | -| disclosure | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | -| disclosure-group | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | +| 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 | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | kbd | 验证中(最小实现) | variant;KbdAbbr keyValue 映射与 title;KbdContent;上下文类名;导出 kbdKeysMap/LabelMap | | link | 验证中(最小实现) | 原生 a + LinkIcon;isDisabled/asChild/焦点与 data 状态;默认图标为基线 ExternalLinkIcon;onPress 由 click 适配 | diff --git a/docs/migration-handoff.md b/docs/migration-handoff.md index 7a2e510..6de2fb2 100644 --- a/docs/migration-handoff.md +++ b/docs/migration-handoff.md @@ -222,3 +222,9 @@ M12 InputGroup 已经独立复核并由集成人修正共享 SSR ID 预规划, - 集成人:复核和提交;共享字段协议、Fieldset、SearchField、Checkbox/Radio 分组协议的扩展。尚未实施的能力不能写成完成。 - 后续其他 AI 候选:Typography → EmptyState → Breadcrumbs,前一批复核后再开。EmptyState 基线有实现但没有独立中文组件页,来源与自建文档必须区分。 - 同一 checkout 只能有一人编辑导出、导航、样式/变体入口、清单和公共协议;启动并行工作前声明这些文件归属。组件私有文件与文档内容可独立推进;遇到协议缺口先交失败用例。 + +## M13–M20 近期返工与下一批入口(2026-10-22) + +后续实施和复核先读 [近期迁移问题与执行清单](./migrations/M13-M20-lessons.md)。该清单把文档契约、Boolean 默认值、禁用作用域、动态 Primitive 结构、ARIA/ID、标签所有权、文档隔离与导航缺口对应到实际回归;原始复核报告保留为证据。 + +下一批安排为 [M21 Disclosure → M22 DisclosureGroup → M23 Accordion](./migrations/M21-M23-disclosure-accordion-prompt.md),含公共导航辅助函数与 16 个基线文档预览。只是一份待派发任务说明,不代表组件已实现。集成人继续维护共享协议和弹层基础设施;ScrollShadow→Tabs 后续单独派发。 diff --git a/docs/migrations/M13-M20-lessons.md b/docs/migrations/M13-M20-lessons.md new file mode 100644 index 0000000..b91828f --- /dev/null +++ b/docs/migrations/M13-M20-lessons.md @@ -0,0 +1,45 @@ +# 近期迁移返工总结与执行清单(M13–M20 / FORM-03) + +日期:2026-10-22。记录已经复现的问题及对应防线,适用于后续实施者与集成人。这里不是新增组件的完成声明,也不把某个组件的底层方案推广为全库方案。 + +截至 `73bd7da`,最近两批 M15–M17、M18–M20 已合入;最终全量测试 316 项(含 node SSR 7),unit 309 项。数字仅对应该提交,不作为后续验收目标。 + +## 实际问题、原因与必要回归 + +| 问题与来源 | 根因 | 后续执行规则与回归 | +| ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| FieldError 原文示例缺错误源、未定义变量;TextField API 漏属性/事件(M13–M14) | 文档、实现和演示分别维护,仅验证预览可运行 | 对照 Root 与每个部件的真实 API;完整正文 SFC 从 Markdown 提取后经 vue-tsc 和实际挂载。保留 fixture 时检查其与原文完全相同;正则/字符串断言不冒充编译或行为验证。 | +| defaultSelected 被 defaultChecked 的隐式 false 覆盖(FORM-03) | Vue Boolean 默认值把“未传”变成 false,别名优先级失真 | 区分未传、false、显式 undefined;验证别名、默认值、受控拒绝,以及控制属性动态增删后真实 DOM 是否恢复。不是只检查更新事件。 | +| Breadcrumbs 在禁用 Fieldset 内仍可点击(M15–M17) | 内层 provide(false) 遮蔽祖先 true | 先 useInheritedDisabled 合并,再 provide;验证祖先禁用/动态恢复、内层 false、嵌套、首个直接 Legend 例外。检查真实元素、ARIA、Tab 与点击/键盘拦截。 | +| 末项变成中间项后链接只剩裸文本(M15–M17) | 安装版本的 Reka Primitive 在 setup 选定 asChild 分支,复用实例切换模式不生效 | 先核对安装源码;结构模式切换必须专项验证,必要时按结构提供稳定的不同 key。保留外层成员 key,不能每次随机重建。回归 a/span、href、role、aria-current、tabindex 与事件,不能只检查 li.data-current。 | +| 显式 aria-labelledby 被三个指标 Root 删除(M18–M20) | v-bind 后再绑定 undefined 覆盖调用方属性 | 定义显式 ARIA 与自动关联的优先级;内部 ID 仅作缺省。测单/多个外部 ID、aria-label 与 aria-labelledby 同时存在、空→增→改→删→再增。 | +| 显式 Label ID 被忽略,多个标签产生重复 ID(M18–M20) | 给每个子标签分配同一个 Root ID;布尔 hasLabel 代替注册管理 | 显式 ID 优先,自动 ID 按实例唯一;注册/注销、动态 ID 和重排必须清理旧引用。SSR 首屏引用须能解析,实际水合不得靠换 ID“修正”。 | +| Label 动态增加 for 后仍是 span(M18–M20) | 把渲染时判断改成 setup 常量 | attrs 派生的元素类型/属性在渲染时读取;验证 for 的完整增删周期及原生关联激活。改共享组件必须回归已有 TextField/Choice/Switch 场景。 | +| 嵌套 TextField 标签进入外层进度名称(M18–M20 集成人修正) | 只要能 inject 到上下文就注册,没有标签所有权边界 | 最近的语义所有者优先;当前 indicator 屏蔽外围字段状态,嵌套字段保留自己的标签。现有桥接通过创建时 fieldScope 的引用身份区分,其他组件不能机械复制。验证内外两种嵌套方向及 SSR/水合。 | +| 三页仅出现在总览,未进入侧栏/相邻页(M18–M20) | 误把 components.md 当成实际导航数据源 | 同步 Layout 的实际列表、总览、选中态和 prev/next;验证桌面与移动入口。构建成功不能证明页面可发现。 | +| Typography 被文档 h1/code 规则覆盖(M15–M17) | 正文样式越过预览隔离边界 | 正文规则排除 .not-prose;标题规则限定文档标题。核对实际计算字号/行高,公共规则变更回归原组件页与窄屏。 | + +## 后续提交前的最小证据 + +1. 先对照固定源码、CSS/tv、公共导出、中文文档与全部预览,列出差异。检查 hooks/composables 等公共辅助导出,不能只数主组件。 +2. 正式测试检查最终 DOM、真实值、事件、焦点、关联目标和清理;状态属性、快照与测试数量不能替代这些断言。 +3. 动态场景包含增删、真实稳定 key 重排、闭包替换和再次恢复;“重排测试”必须真的改变顺序,不能只追加末项。 +4. 模型与公共类型分别检查源码和 dist,非法值用真实 vue-tsc 反例;测试里的类型断言不能替代类型检查。不用 as never/any 掩盖公开契约错误。 +5. SSR 冒烟与浏览器外实际水合分别验证。ID 检查须验证每个引用真实存在且无重复,不只匹配“出现过 id”。任意用户组件内部不能静态展开的边界明确记录。 +6. 样式、定位、滚动、高度测量、动画生命周期、Tab 轨迹使用真实浏览器;浅深/桌面/窄屏结果分开记录。jsdom 无布局能力,不能把 mock 高度当作视觉证据。 +7. API/插槽表全文宽、长内容换行、不缩字号不截断;样式和导航规则复用现有设施。默认 5173,不切端口或结束他人服务。 +8. test、unit、SSR、typecheck、build、format、dist 探针等记录实际入口与计数;临时探针注明已删除。历史失败、实施者修复、集成人当前结论分开写,不能由实施者自行宣称复核通过。 + +## 共享文件与责任 + +- field/choice/禁用、Label、Form、Button、Link、SearchField、indicator 标签桥接及未来弹层协议由集成人维护。其他任务发现缺口先交最小失败用例与局部方案,不能顺手改共享协议。 +- 独立的新组件家族可维护自己的内部上下文,但不要把 choice 数组模型、indicator 标签所有权等当成万能协议。 +- 同一 checkout 禁止同时编辑公共导出、类型入口、CSS/tv 入口、Layout、package.json 与兼容矩阵。并行时先明确文件归属;当前未交接就保持串行集成。 + +## 详细依据 + +- [M13–M14 复核](./M13-M14-review.md) +- [选择字段协议](../decisions/selection-field-foundation.md) +- [M15–M17 复核](./M15-M17-review.md) +- [M18–M20 复核及集成人修正](./M18-M20-review.md) +- [迁移任务拆分与复核约定](../migration-handoff.md) diff --git a/docs/migrations/M21-M23-disclosure-accordion-prompt.md b/docs/migrations/M21-M23-disclosure-accordion-prompt.md new file mode 100644 index 0000000..5e0a25e --- /dev/null +++ b/docs/migrations/M21-M23-disclosure-accordion-prompt.md @@ -0,0 +1,103 @@ +# 下一批任务与提示词:M21–M23 折叠家族 + +日期:2026-10-22。当前实现基线 `73bd7da`;本文是待派发计划,不代表已经实施或创建其他 AI 任务。 + +## 分工与先后关系 + +| 顺序 | 其他 AI 的任务 | 前置与交付 | +| ---- | ----------------------------------------------------------- | ------------------------------------------------------------------------ | +| M21 | Disclosure、Heading、Trigger、Content、Body、Indicator | 先确定单项展开、触发、ID、卸载/动画协议;基线中文页 3 个预览。 | +| M22 | DisclosureGroup 与 useDisclosureGroupNavigation 的 Vue 适配 | 在 M21 上统一组展开键与外部导航;基线中文页 3 个预览。辅助导出不能漏。 | +| M23 | Accordion、Item、Heading、Trigger、Panel、Body、Indicator | 复用前两项适用的内部机制,避免另建不兼容展开状态;基线中文页 10 个预览。 | + +集成人负责复核、共享协议和必要集成;弹层基础设施→Modal→Popover/Tooltip 留给集成人。后续 ScrollShadow→Tabs 单独派发,本批不做。折叠家族不依赖弹层先完成,可以独立开始;同一 checkout 的共享入口仍须错开修改,不据此默认授权双方同时编辑。 + +## 可复制提示词 + +```text +在独立 heroui-vue 仓库依次迁移 M21 Disclosure、M22 DisclosureGroup、M23 Accordion。 + +先读取: +AGENTS.md + docs/migration-handoff.md + docs/migrations/M13-M20-lessons.md + docs/compatibility.md + docs/upstream.md + docs/migrations/M18-M20-review.md + docs/migrations/M21-M23-disclosure-accordion-prompt.md + +当前已提交实现基线 73bd7da。记录实际起始 HEAD 与工作区差异;本轮可能有规范/提示词尚未提交,保留它们,不 reset、不清理、不自行提交或推送。 +上游 ../heroui 只读;固定 HeroUI 3.2.6 / ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960。 + +一、先建清单 + +读取三个家族的 React 实现、index 公共导出、CSS/tv、中文 (navigation) 文档及全部演示。 +基线中文预览顺序: +- Disclosure:basic、render-function、custom-styles。 +- DisclosureGroup:basic、controlled、custom-styles。 +- Accordion:basic、surface、without-separator、multiple、disabled、controlled、custom-indicator、render-function、faq、custom-styles。 +共 16 个文档预览。数量一致只是第一步,逐例核对内容、文案、布局、图标、状态与交互。 + +不要漏掉 disclosure-group/index.ts 导出的 useDisclosureGroupNavigation。 +它被 controlled 示例实际使用,需提供对应 Vue composable、公开类型、文档和行为测试;不能硬编码按钮来冒充完整能力。 + +二、实现与状态协议 + +按 M21→M22→M23 顺序实施。先核验已安装 Reka Collapsible/Accordion 的真实能力与差异,选择局部组合;不运行 React,不引入另一套整库。 + +定义清楚单项展开、组展开键、受控/非受控、默认值、事件与 Vue v-model 映射,并在 M21/M22 报告中记录。组集合采用 Vue 数组表达,空集合=[],保持基线支持的字符串/数字 key;不擅自缩成字符串,也不直接泄漏 React Set 类型。 +若底座只支持字符串,内部映射保留 key 身份(数字 1 与字符串 "1" 不能碰撞)。 +不直接修改传入数组;父级拒绝更新时真实展开状态必须恢复。模式、成员、key 与 disabled 动态变化时维持一致,重复 key 有明确处理。 + +核对 allowsMultipleExpanded、isExpanded/defaultExpanded、expandedKeys/defaultExpandedKeys、disabled、heading 语义、indicator、自定义根和其他实际基线能力,框架适配逐项记录,不删除能力。 +DisclosureGroup 与 Accordion 只复用实际共有机制;它们的布局/公开部件差异仍须保留。不要为了复用扩大公共类型或增加未存在的状态机。 +useDisclosureGroupNavigation 的空列表、当前索引、前后边界、单选替换/多选增量及响应式变化按固定源码验证,不修改传入集合。 + +Trigger 必须符合真实元素语义:type=button、不误提交表单;点击/Enter/Space 不重复更新,保留调用者取消和处理器数组。 +验证基线实际键盘行为,不因使用 Reka Accordion 就无记录引入不同的 roving/方向键契约。 +aria-expanded、aria-controls、panel/heading ID、禁用/展开状态与实际可见内容一致。 +折叠内容的隐藏、保留挂载、可聚焦性、退出动画与卸载协调,不能只切 data-expanded。 +测量变量、动画生命周期与 reduced-motion 必须映射到 Vue 底座的真实状态,不伪造 ARIA 命中 CSS。 + +三、共享边界 + +可以新增三个组件家族及必要的家族私有展开内核、CSS/tv、文档、演示、测试和公共入口增量。 +不得修改 field/*、choice/*、Form、Fieldset、Label、indicator 桥接、Button、Link、SearchField、Switch 的共享协议。 +复用 useInheritedDisabled 并保留 Fieldset/Legend 语义;内层 false 不能解除祖先 true。 +不重写主题、文档布局、构建链路或锁文件。发现共享缺口先交最小失败用例和局部方案,继续不依赖该缺口的工作。 +不改 node_modules;不把已有 Vue 私有 _vts 逻辑复制到新组件。 +若与集成人并行,先确认共享文件归属,不能同时写 index.ts/types.ts、样式/tv 入口、Layout、package.json、矩阵等。 + +四、文档与高一致性 + +移植固定 CSS、变量、尺寸、间距、动效和状态标记,仅作 hv- 和 Vue 必需适配,记录来源及 Apache-2.0 许可。 +命名导出代替 React 对象子部件,class/插槽/事件均使用真实 Vue 契约。核对 Root 和所有子部件、辅助函数的 API、默认值和属性落点。 +默认基线图形可精确移植并记录许可;文档自定义图标用 @tabler/icons-vue,不自绘 SVG。 +预览、复制、高亮共用同一 SFC;Markdown 完整示例提取后实际 vue-tsc 编译与挂载,不能只做正则断言。 +表格全文宽、长内容换行、不缩字号不截断;加入 Layout 实际侧栏/移动导航、总览、选中态与相邻页。不要只更新 components.md。 + +五、必须能复现的回归 + +- 单项展开/折叠,默认展开,受控接受与拒绝;组单选/多选、空值、模式切换。 +- 动态 attrs 空→新增→修改→删除→再次新增,包含 ARIA、class/style、事件;保留字符串/数组/对象 class 和基础类。 +- 条件/空/Fragment 插槽、父级替换插槽闭包;稳定 key 的真实成员增删和重排,不能仅追加一项就声称测过重排。 +- 自身/组/祖先禁用,动态恢复,嵌套 Fieldset 与首个直接 Legend 例外,真实点击/键盘激活和表单不误提交。 +- 真实 Trigger/Panel DOM 与 ID/ARIA 关联,所有引用可解析且无重复;显式 ID/ARIA 优先,注册/卸载/变化不留旧引用。 +- 折叠后隐藏内容不能继续 Tab 到内部交互项;动画结束、快速连续切换、内容高度变化、卸载清理。 +- 源码与 dist 类型正反消费,不用 any/as never 抹掉公开约束。 +- node SSR 不访问浏览器全局;另测实际水合,检查 ID、初始展开状态和 console 警告。 + +布局、高度测量、退出动画、焦点与 Tab 路径必须在真实浏览器验证,不能用 jsdom 假布局代替。 +文档服务固定 127.0.0.1:5173,覆盖桌面/窄屏、浅深主题、主要变体与状态和长短表格;不擅自换端口或结束别人的服务。 + +执行 pnpm test、pnpm test:unit、pnpm typecheck、pnpm build:docs、pnpm format、git diff --check。 +新测试加入 unit 的实际文件列表。分别记录文件数/项数/是否含 node SSR,临时探针、真实浏览器与未建立的自动检查分开说明。 + +六、交付与复核 + +分别写 docs/migrations/M21-disclosure.md、M22-disclosure-group.md、M23-accordion.md,记录起始 HEAD、部件/API/示例清单、来源许可、差异、测试/浏览器证据、未验证项和最短复核步骤。 +同步 compatibility/upstream/verification,区分实现、自测与集成人复核,不宣布完整兼容。 + +先将 M21/M22 的公开契约与状态/标签/生命周期测试稳定,再做 M23;中途发现核心协议阻断就提供失败场景,不一次生成三个粗略空壳。 +本批完成后交回复核,不继续做 ScrollShadow、Tabs、弹层、集合或日期,不提交、不推送,不把实施者自测改写为集成人已验收。 +``` diff --git a/docs/migrations/M21-M23-review.md b/docs/migrations/M21-M23-review.md new file mode 100644 index 0000000..158d68a --- /dev/null +++ b/docs/migrations/M21-M23-review.md @@ -0,0 +1,141 @@ +# M21–M23 集成人复核(2026-10-22) + +## 最终复核:通过本批集成检查(2026-10-22) + +第三轮事件缺陷已关闭:监听器改为有序数组,由 Vue 的 DOM 事件分发处理 stopPropagation / stopImmediatePropagation,preventDefault 取消展开;Trigger 和子根 capture 在禁用 guard 后各执行一次。此前重复回调、禁用泄漏、条件注释根、组单/多选与禁用、受控 next、数字/字符串 ID、动画过期回调及自定义根修复未发现回退。以下各轮“不提交”结论均为历史记录。 + +- 正式 `pnpm test`:19 文件 / 345 项通过(含 node SSR 8);typecheck、build:docs、format、git diff --check 通过。文档构建仅既有 chunk 大小提醒。 +- 独立补充 4 项探针:Disclosure / Accordion × 原生 button / 本库 Button,验证 `@click.stop` 后正常展开、子/Trigger click 各一次、双方 capture 各一次,全部通过;验证后移除,不计入正式数字。 +- 集成人修正 compatibility.md 中 string/number 联合类型未转义管道造成的表格错列,并移除新增事件测试中不必要的组件 `as never` 类型断言。 +- 本次修复是事件组合逻辑,未重复逐页点击文档。布局/高度的关键浏览器证据沿用前轮,未新增逐像素、完整读屏/触屏/RTL、Nuxt 或独立安装验收;兼容矩阵继续标为“验证中”。 +- 事件 helper 的 invoker.value 适配涉及 Vue 内部行为;后续 Vue 升级必须回归原生/组件根、监听数组、捕获与停止传播。本次未改共享 Button/Link 或字段协议。 +- 本批提交组件、样式、演示、测试、迁移规范及复核记录;根目录三张实施者临时 PNG 不纳入提交。 + +## 第三次复核:事件适配尚有两项 P2,暂不提交 + +本节为最新结论。第二轮的重复调用、禁用子 capture、注释根丢失三项已有修复,正式套件新增对应回归。仍未解决的是同一私有事件适配的 DOM 事件语义与 Trigger 属性透传,并非新的功能扩展要求。两个独立行为探针均已复现,验证后移除;未修改生产实现。 + +### P2:把 stopPropagation 错当成 stopImmediatePropagation / preventDefault + +位置:disclosure/triggerEvents.ts 的 runHandlers、makeTriggerClickHandler(两个 Trigger 共用)。 + +runHandlers 在任一 handler 后看到 event.cancelBubble 就直接返回,外层也据此跳过 emitClick 和 activate。stopPropagation 只阻止向祖先传播,不取消当前节点的其他监听器或按钮默认激活;它和 stopImmediatePropagation / preventDefault 必须区分。 + +独立复现:asChild 原生 button 的 onClick 为 `[(e) => e.stopPropagation(), second]`,Trigger 另有自己的 click 监听。点击后 second 实际 0 次(预期 1),Trigger click 和 toggle 也被提前跳过。常见模板 `@click.stop` 因此会使展开失效。修复需要保留同节点监听次序,只用 preventDefault 取消展开,并正确支持 stopImmediatePropagation,而不是用 cancelBubble 一并处理三种语义;回归 child/Trigger/祖先与数组处理器的不同组合。 + +### P2:asChild 时覆盖 Trigger 自己的 capture 监听器 + +位置:disclosure/triggerEvents.ts 的 cloneAsChildRoot:展开 options.shared 后无条件绑定 onClickCapture。 + +options.shared 中有 Trigger 调用者传入的 onClickCapture,但新 handler 只接收子根的 childCapture,Trigger 的监听被直接覆盖。最小复现:``,点击后 capture 为 0 次,预期 1。两个家族共用同一路径。 + +修复需要分别保存并有序合并 Trigger 与子根的捕获监听器,禁用 guard 位于业务监听之前;enabled 时各执行一次,禁用时按已约定的边界拦截。不要再通过 clone 自动合并加手动调用造成重复。补充 Trigger-only、child-only、两者都有、数组、preventDefault、停止传播与动态增删监听的测试。 + +本次正式测试为 19 文件 / 340 项通过(含 node SSR 8);typecheck、build:docs、format、git diff --check 通过,文档构建仅既有 chunk 大小提醒。临时两个失败探针不计入该数字。不重复逐页浏览器点击。 + +## 第二次复核:仍暂不提交 + +本节为返工后的最新结论,下文六项为第一轮历史记录。组成员状态已抽到 useDisclosureItem,原有无 id 单选/禁用、数字与字符串 ID、受控 next、过期动画回调与 Content `as` 的修复均已落地;现有正式测试 19 文件 / 337 项(含 node SSR 8)及 typecheck 通过。但 asChild 修复仍有三项 P2,补充四个独立行为探针均失败,因此不提交。未修改生产实现,临时探针验证后移除。 + +### P2:正常点击时子回调执行两次(两个家族) + +位置:DisclosureTrigger.vue:54–81、AccordionTrigger 同结构;triggerEvents.ts:40–51。 + +`cloneVNode(child, { onClick })` 已经自动把原有 child.props.onClick 合并到新监听器之前;makeTriggerClickHandler 又手动调用同一个 childOnClick。最小复现:``,点击一次 childClick 调用两次;AccordionTrigger 也相同。可能造成业务重复请求或状态切换两次,现有新增测试只验证 disabled 分支,未覆盖正常激活。 + +修复要求:子监听器只能由一种路径执行,正确保留调用者取消与 stopImmediatePropagation。不要同时使用 clone 自动合并与手动再次调用。回归原生子元素及本库 Button、监听数组、完整键盘激活、父子各自回调次数。 + +### P2:禁用时仍会先执行子元素 capture 回调 + +位置:DisclosureTrigger.vue:73–78、AccordionTrigger 同结构;triggerEvents.ts:59–73。 + +相同的自动合并也发生在 onClickCapture:原 capture 先执行,随后才进入新 guard。最小复现:`open`,click 仍调用 capture 一次。新增禁用 Button 普通 click 用例无法覆盖此路径,当前“六项均修复”记录对事件边界的判断过早。 + +修复要求:在实际子根上建立明确的禁用事件边界,验证 capture/bubble/祖先与数组监听顺序;不能因为阻止了 toggle 就声称业务激活已阻止。 + +### P2:首个注释节点导致唯一有效子元素整个丢失 + +位置:triggerEvents.ts:3–12,两个 Trigger 的 firstVNode / cloneVNode / return 分支。 + +firstVNode 仍直接接受任何 isVNode,包括 Comment;没有展开 Fragment 或验证唯一有效根。最小复现:`hidden`,最终 button 不存在,Trigger 只返回克隆后的注释。此场景有且只有一个有效根,属于正常条件插槽用法;不是要求支持多个有效根。 + +修复要求:按既有 asChild 约定展开 Fragment、忽略注释与空白文本、验证唯一有效根;无效多根要有明确诊断,不静默丢弃节点。回归条件切换、嵌套 Fragment、子 class/style/事件/ARIA 与动态 attrs。 + +本次以代码和行为探针复核上述差异,没有重复逐页浏览器点击。四个独立探针分别是两个家族的正常 click 计数、条件注释根、禁用 capture;这四项失败不计入正式 337 项。 + +范围:73bd7da 后未提交的 Disclosure / DisclosureGroup / Accordion。以代码规范、架构契约、固定 ce90ea3 行为差异为主,浏览器只验证关键场景,不逐例点击。未修改组件实现,未提交/推送,保留已有规范与实施者截图文件。 + +## 结论 + +暂不通过:1 项 P1、5 项 P2。独立补充的 10 项行为探针全部复现失败;现有套件未覆盖这些场景。 + +### P1:不传 id 的成员脱离组,默认单选与组禁用失效 + +位置:disclosure/Disclosure.vue 与 accordion/AccordionItem.vue 的 isExpanded、isDisabled、toggle、registerItem(例如 AccordionItem.vue:60–91)。 + +全部分支以 `group && props.id !== undefined` 为前提。未显式传 id 的成员直接使用独立 localExpanded,也不合并 group.isDisabled。id 在公开 API 是可选的,当前 accordion-basic 演示也没有传它。 + +独立测试:默认组连续点击两个无 id 成员,得到 `[true,true]` 而不是 `[false,true]`;两个家族均失败。`…` 的无 id Trigger 没有 disabled。浏览器重点验证 accordion-basic 也确认「如何下单?」与「可以修改或取消订单吗?」同时保持 aria-expanded=true。 + +修复:组成员始终有稳定的有效 key(未传时生成),展开与禁用始终遵循组协议。不要只给演示补 id 掩盖公开契约;验证无 id、稳定 key 重排、组单/多选、默认值与组/祖先禁用。自动 key 不随普通重渲染漂移,新增/动态 key 注册需有清晰策略。 + +### P2:字符串与数字 key 虽然模型区分,真实 DOM ID 仍碰撞 + +位置:两个 Item 的 domId/triggerId/contentId 生成处。 + +`String(props.id)` 把数字 1 与字符串 "1" 生成同一套 `1`、`1-trigger`、`1-content`。同一组两个合法不同 key 产生 6 个带 id 的节点,但只有 3 个唯一 ID;Trigger 的 aria-controls 无法唯一指向自己的 Panel。两种家族均已独立复现,现有“数字与字符串区分”测试仅检查展开布尔值。 + +修复:区分集合 key 身份与 DOM 关联 ID,不把序列化后的 key 当唯一 DOM ID。保留字符串/数字语义、SSR/水合稳定与显式属性契约;测试所有 ID 唯一、每个控件引用其实际 Panel,涵盖多个组、嵌套、增删重排。重复 key 应明确报错或按清晰规则处理,而非静默去重注册。 + +### P2:受控组内成员事件返回旧展开状态 + +位置:两个 Item 的 toggle(例如 AccordionItem.vue:73–77)。 + +group.toggle 发出父级更新后,立即读取 group.isExpanded;受控 props 在本轮尚未回流,读到旧值。独立测试从空组点击 a,组 update:expandedKeys 已提交 ['a'],但子项 expandedChange(false),应该是此次请求的 true。两种家族都失败。 + +修复:定义组与项的事件契约,根据本次请求计算 next,不同步读取尚未更新的受控值。验证父级接受/拒绝、打开/关闭、多选与批次更新,事件与最终 DOM 分开断言;不修改父级数组。 + +### P2:Trigger 自行 clone 的 asChild 合并绕过禁用激活边界 + +位置:disclosure/DisclosureTrigger.vue:51–84;AccordionTrigger 同结构。 + +onClick 在检查 disabled 之前 emit click;cloneVNode 又合并了插槽子元素的监听器,子监听器在禁用 guard 前已能执行。独立验证 disabled 的 asChild span:点击仍执行子 onClick 一次,只是没有展开。disabled 属性对 span 不提供原生禁用,不能依赖它兜底。 + +修复:使用项目约定的有效单根属性/事件合并方式,明确定义支持的自定义根、键盘语义、取消与捕获顺序;禁用 guard 必须位于所有业务激活监听之前。不得照抄私有 _vts,不改共享 Button 协议。回归自身/子/祖先监听、数组处理器、preventDefault/stopImmediatePropagation、完整 Enter/Space;首节点是注释/Fragment 时不能把行为合并到注释或丢掉有效子节点。 + +### P2:快速开合时,过期关闭动画回调能隐藏已重新打开的面板 + +位置:disclosure/useDisclosurePanelHeight.ts:59–79(两个家族共用)。 + +关闭阶段 Promise 完成与取消的 then/catch 都无条件设置 hidden='until-found',没有校验操作代次、当前 expanded 或实例是否已卸载。重新打开会取消旧高度过渡,旧 Promise 的 catch 随后将当前已打开 Panel 隐藏。 + +独立异步测试使用可控 Animation.finished Promise:初始打开→关闭→再次打开→拒绝旧关闭 Promise,当前 hidden 仍被设置,失败已复现。该测试证明过期回调覆盖状态,不把模拟动画当成真实布局或逐像素验证。 + +修复:过渡代次/取消与当前状态校验,卸载后旧回调失效;完成/取消仅能提交当前操作。另查 getter 参数目前用 unref 而不是 toValue 的类型/运行时一致性。真实浏览器只需重点验证快速连续开合、内容高度变化、reduced-motion 和折叠内容焦点边界。 + +### P2:DisclosureContent 文档声明的 as 没有实现 + +位置:disclosure/DisclosureContent.vue 模板与 apps/docs/components/disclosure.md 的 Content API 表。 + +文档声明 as:string、默认 div;实现固定 div 且没有 as prop。独立用例 as='section' 仍得到 DIV,只附加了一个无效 as 属性。 + +核对全部部件的自定义根与 attrs/API:支持的能力应实际实现并有源码与 dist 消费用例;若固定基线确无该能力则准确说明差异并移除错误声明,不能用说明伪装已支持。不要只补 Root 和 Trigger 而漏掉 Content/Panel/Body。 + +## 代码设计与上游差异 + +- Item 与 Trigger 在两个家族中存在大量重复行为实现,以上组事件/ID/asChild 问题同时出现。建议共享家族私有状态与事件适配,只把样式/部件差异留在包装层;不强制为统一外观重写公共 DOM。 +- 自有组状态本身不是阻断;底座差异可以局部适配,但必须实际覆盖自动成员 key、单/多选、禁用、默认值、集合变化与生命周期,不能只因为避免了 Reka 的字符串模型就认为已达到 RAC 契约。 +- CSS 有记录的 Vue 适配:Disclosure inline-block→inline-flex、Button 指示器边距、统一 panel-height 协议。对比时区分必要适配与改变设计值,不能把“已复制 CSS”写成完全一致。 +- 16 个演示已挂载不证明组行为正确;默认 basic 的单选问题正是现有静态/数量断言的盲区。 + +## 验证与证据边界 + +- 正式 test:unit:18 文件 / 323 项通过;typecheck、build:docs 通过。build:docs 仅既有 chunk 大小提醒。 +- 移除临时探针后 `pnpm test`:19 文件 / 331 项通过(含 node SSR 8 项);临时 10 项失败不计入正式套件。 +- 10 项临时探针:无 id 单选 2、无 id 组禁用 1、数字/字符串 DOM ID 2、受控组子事件 2、asChild 禁用 1、Content as 1、旧动画取消回调 1。验证后移除,保留上述复现说明。 +- 浏览器最初因自动审批额度不足未执行;后续正常工具调用恢复,只重点验 accordion-basic。当前展开面板实测 56px、scrollHeight=56、变量 auto,说明实施者后续已修复先前零高度问题,不将该历史问题继续列为待修项。默认单选异常另有上述实测证据。 +- 本轮截图保存时临时标签已因聊天中断释放,没有取得新增位图;不把已有实施者截图算成本次独立证据。未做逐像素、全量演示点击、完整读屏/RTL/触屏、Nuxt 或独立安装。 + +## 交回要求 + +优先修自动成员键/组状态与唯一 DOM ID,再收敛受控事件、asChild 和异步生命周期,补 API 契约。新增回归应检查真实状态与关联目标,减少只看 data 标记、类名和演示数量的断言。共享 Label/field/choice/Button/Link 等协议保持冻结;本次不提交任何实施改动。 diff --git a/docs/migrations/M21-disclosure.md b/docs/migrations/M21-disclosure.md new file mode 100644 index 0000000..6bbe511 --- /dev/null +++ b/docs/migrations/M21-disclosure.md @@ -0,0 +1,130 @@ +# M21 Disclosure 交接报告 + +实施日期:2026-10-22。状态:实施者自测完成,待集成人复核。**未提交、未推送、未宣布验收通过。** + +## 1. 起点与范围 + +| 项 | 值 | +| ---------- | ------------------------------------------------------------------------------------------ | +| 起始 HEAD | `73bd7da`(feat: add ProgressBar ProgressCircle and Meter) | +| 工作区起点 | 含未提交的 AGENTS.md / migration-handoff.md 规范修改与 M13–M20-lessons、本批提示词;已保留 | +| 上游基线 | HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`(`../heroui` 只读) | +| 范围 | Disclosure、Heading、Trigger、Content、Body、Indicator、默认 Chevron、样式/tv、3 个示例 | + +未修改 field/\*、choice/\*、Form、Fieldset、Label、indicator 桥接、Button、Link、SearchField、Switch 共享协议。复用 `useInheritedDisabled`。 + +## 2. 上游核对 + +- 部件:Root / Heading / Trigger / Content / Body / Indicator;对象式 `Disclosure.*` → Vue 具名导出。 +- 状态:RAC `isExpanded` / `defaultExpanded` / `onExpandedChange` / `isDisabled` → Vue `expanded`(`v-model:expanded`)/ `defaultExpanded` / `update:expanded`+`expandedChange` / `isDisabled`。 +- 默认指示图标为基线 `IconChevronDown`(Apache-2.0,精确移植 path);文档自定义图标用 Tabler。 +- CSS:`disclosure.css` 移植为 `hv-` 命名空间;高度动画映射到 Reka Collapsible 测量变量(并保留 `--disclosure-panel-height` 名)。 +- 3 个中文预览:`basic`、`render-function`、`custom-styles`。 + +## 3. Vue 实现与 API + +| 上游 | Vue | +| ---------------------- | ---------------------------------------------- | +| `Disclosure` | `Disclosure` | +| `Disclosure.Heading` | `DisclosureHeading` | +| `Disclosure.Trigger` | `DisclosureTrigger`(`asChild` 合并到 Button) | +| `Disclosure.Content` | `DisclosureContent` | +| `Disclosure.Body` | `DisclosureBody` | +| `Disclosure.Indicator` | `DisclosureIndicator` | +| `render` | `as` + 透传 `data-*` | +| `className` | `class` | + +公共属性(Root):`id`(组键+DOM id)、`expanded`、`defaultExpanded`、`isDisabled`、`as`、`class`、默认作用域插槽 `{ isExpanded, isDisabled }`。 + +行为落点: + +- 根 `div[data-slot="disclosure"]`;Trigger 为 `type="button"`,设置 `aria-expanded` / `aria-controls` / `id`。 +- Content `id` 与 Trigger `aria-controls` 对应;折叠时 `hidden` + `aria-hidden="true"`,展开时 `data-expanded="true"`。 +- Trigger `click` 可 `preventDefault` 取消;禁用时点击无效。原生 button 键盘激活不重复 toggle。 +- 指示器 `data-expanded` 控制旋转;自定义图标通过默认插槽 clone 注入 class/状态。 + +## 4. 示例对照 + +| 基线 | Vue 演示 | 状态 | +| --------------- | -------------------------------- | ----------------------------------- | +| basic | `disclosure-basic.vue` | 已迁移;Button asChild + 默认指示器 | +| render-function | `disclosure-render-function.vue` | 已迁移;`as` + `data-custom` | +| custom-styles | `disclosure-custom-styles.vue` | 已迁移 | + +图标:上游 Gravity UI / Iconify → Tabler(QrCode/BrandAppleFilled/ShoppingBag);Expo 品牌图标 Tabler 无对应,用 `IconDeviceMobile` 替代并记录。 + +## 5. 变更文件 + +新增:`packages/vue/src/components/disclosure/*`、`packages/styles/components/disclosure.css`、`apps/docs/components/disclosure.md`、`apps/docs/demos/disclosure-*.vue`(3)。共享增量:styles 入口、vue index/types、Layout、components.md、`tests/disclosure-accordion.test.ts`、`tests/ssr.test.ts`。 + +## 6. 验证结果 + +| 入口 | 文件数 | 通过数 | 含 SSR | +| ---------------- | ------ | ------ | ----------- | +| `pnpm test` | 19 | 331 | 是(SSR 8) | +| `pnpm test:unit` | 18 | 323 | 否 | + +typecheck / build:docs / format / git diff --check 通过。浏览器 5173:Trigger `type=button`、`aria-controls` 可解析、点击后 `aria-expanded`/`data-expanded`/hidden 正确;侧栏含三页。 + +## 7. 已知差异与未验证项 + +- `expanded` 为 Vue 布尔模型,不是 RAC 的 `isExpanded` 命名;事件为 `update:expanded` / `expandedChange`。 +- `asChild` 用 cloneVNode 合并,不复刻 RAC slot 查找;要求单个默认子元素。 +- 内容高度动画依赖测量(jsdom 高度为 0);真实浏览器展开动画未逐帧录制。 +- 未验证:逐像素、读屏、RTL、触屏、Nuxt 水合、独立安装、`test:browser`/`test:visual`/`test:package`。 + +## 8. 最短复核路径 + +1. 打开 `/components/disclosure`,点击「预览 HeroUI Native」应展开/折叠,指示器旋转。 +2. 检查 Trigger `aria-controls` 指向 Content `id`。 +3. 运行 `npx --yes pnpm@11.25.0 test` 与 `test:unit` 核对 331 / 323。 + +## 视觉/动画返工(2026-10-22,实施者) + +独立浏览器复核发现布局与动画未达标,已修复(未提交): + +1. **展开高度为 0**:原在 `height:0` 面板上测量,变量恒为 0。改为 RAC `useDisclosure` 协议:CSS 始终 `height: var(--disclosure-panel-height)`,JS 在展开时写 `scrollHeight px`(过渡到目标)→ 动画结束后 `auto`;收起时先写当前 `px` 再写 `0px`,动画结束后设 `hidden="until-found"`。`data-expanded` 只驱动 opacity。 +2. **箭头错位**:`.hv-disclosure__trigger { inline-block }` 覆盖 Button 的 `inline-flex`;Button 通用 `svg` 负边距覆盖 `ms-auto`。改为 trigger `inline-flex`,并以更高优先级恢复指示器 `margin-inline-start: auto` 与 16px 尺寸。basic/render-function 触发按钮使用 `full-width`。 +3. **浏览器实测**:开合高度 0→56→0 与 opacity 同步 200ms;指示器 `rotate: -180deg`(250ms);关闭动画期间不设 `hidden`。 + +未改共享 Button 协议,仅在 disclosure.css 覆盖指示器 SVG 边距。`pnpm test` 331 仍通过。 + +## 复核返工(2026-10-22,对照 M21-M23-review.md) + +六项缺陷已修复,未提交/推送: + +1. **P1 无 id 成员**:组内成员始终参与组协议;未传 `id` 时用实例稳定 auto key(useId)注册。单展开与组禁用对无 id 项生效(accordion-basic 实测互斥)。 +2. **DOM ID 碰撞**:集合 key 保留类型身份(1 ≠ "1");DOM id 不再直接序列化 key——显式字符串 id 保留,数字/auto 用实例 useId。重复 key 会 `console.warn`。 +3. **受控事件旧值**:`expandedChange` / `update:expanded` 发出本次请求的 `next`,不回读未回流的受控 props。 +4. **asChild 禁用点击**:禁用 guard 置于子监听与 emit 之前(含 capture 拦截),禁用时不再执行自定义 onClick。 +5. **过期动画回调**:`useDisclosurePanelHeight` 用操作代次 + disposed + 当前 expanded 校验;旧 close Promise 不能隐藏已重开的面板。参数读取改为 `toValue`。 +6. **Content/Panel/Body 的 `as`**:已实现(文档原本有声明);`as="section"` 等可换根元素。 + +新增 `useDisclosureItem` 共享内核,减少 Disclosure/AccordionItem 重复。回归 20 项含上述场景。 + +计数:`pnpm test` 19 文件 / **337**(SSR 8);`pnpm test:unit` 18 文件 / **329**。typecheck / format 通过。 + +## asChild Trigger 返工(2026-10-22,第二轮复核) + +三项 P2 已修复: + +1. **子回调执行两次**:`cloneVNode` 自动合并 + 手动调用重复。现剥离子 `onClick`/`onClickCapture` 后只经合成 handler 执行一次(guard → child → emit → toggle)。 +2. **禁用时子 capture 仍执行**:capture 同样剥离后由 `makeTriggerCaptureHandler` 统一处理,禁用时在任何子监听之前 `preventDefault` + `stopImmediatePropagation`。 +3. **`v-if="false"` 注释开头丢按钮**:`resolveAsChildTarget` 展开 Fragment、忽略注释/空白文本;唯一有效根才 asChild 合并,多根 warn 并原样渲染。 + +新增 3 组回归(Disclosure/Accordion 双家族 click 计数、disabled capture、注释前缀)。 + +计数:`pnpm test` 19 文件 / **340**(SSR 8);`pnpm test:unit` 18 文件 / **332**。typecheck / format 通过。 + +## 事件适配第三轮返工(2026-10-22) + +两项 P2 已修复: + +1. **`@click.stop` 误阻止展开**:原先把 `cancelBubble` 当成 `stopImmediatePropagation`,并跳过 emit/toggle。现将 child/Trigger/capture 监听排成 Vue 数组交给 invoker,由原生语义处理:`stopPropagation` 不断同节点后续监听,`stopImmediatePropagation` 才断,`preventDefault` 只取消展开。 +2. **asChild 丢失 Trigger 的 `@click.capture`**:`shared` 里的 capture 曾被覆盖。现与子根 capture 一起按序合并进数组(禁用 guard 最前)。 + +另修 Vue invoker `_vts` 同刻防重入导致手动调用被跳过的问题:解包 `invoker.value` 后重组数组,不再二次调用 invoker。 + +回归 5 组:stopPropagation 后续监听+展开、stopImmediate 断链、preventDefault 取消展开、Trigger+child capture 各一次、禁用阻断 capture。 + +计数:`pnpm test` 19 文件 / **345**(SSR 8);`pnpm test:unit` 18 文件 / **337**。typecheck / format 通过。 diff --git a/docs/migrations/M22-disclosure-group.md b/docs/migrations/M22-disclosure-group.md new file mode 100644 index 0000000..f7e90b0 --- /dev/null +++ b/docs/migrations/M22-disclosure-group.md @@ -0,0 +1,112 @@ +# M22 DisclosureGroup 交接报告 + +实施日期:2026-10-22。状态:实施者自测完成,待集成人复核。**未提交、未推送、未宣布验收通过。** + +## 1. 起点与范围 + +起始 HEAD `73bd7da`。范围:DisclosureGroup、组展开键协议、`useDisclosureGroupNavigation`、3 个示例。基于 M21 的 Disclosure。 + +## 2. 上游核对 + +- `DisclosureGroup` 为 RAC DisclosureGroup 包装;`index.ts` 额外导出 `useDisclosureGroupNavigation`。 +- 组 API:`expandedKeys`(Set)、`defaultExpandedKeys`、`onExpandedChange`、`allowsMultipleExpanded`、`isDisabled`。 +- **Vue 数组模型**:`expandedKeys: Array`,空集合 `[]`;不泄漏 React Set。key 身份用 SameValueZero(`1` ≠ `"1"`)。 +- `useDisclosureGroupNavigation`:空列表 `currentIndex=-1`;单选替换集合;多选增量添加;不修改传入集合。`itemIds` 源码为 `string[]`,Vue 参数放宽为 `(string|number)[]` 以匹配键类型。 +- 3 个中文预览:`basic`、`controlled`、`custom-styles`。 + +## 3. Vue 实现与 API + +| 上游 | Vue | +| ------------------------------ | ---------------------------------------------------------------- | +| `DisclosureGroup` | `DisclosureGroup` | +| `expandedKeys: Set` | `expandedKeys: Array`(v-model:expanded-keys) | +| `onExpandedChange(Set)` | `update:expandedKeys` / `expandedChange`(数组) | +| `useDisclosureGroupNavigation` | 同名 composable,数组入参,返回 getter + 回调 | +| render prop children | 默认作用域插槽 `{ expandedKeys, isDisabled }` | + +公共属性:`expandedKeys`、`defaultExpandedKeys`、`allowsMultipleExpanded`、`isDisabled`、`as`、`class`。 + +行为落点: + +- 根 `div[data-slot="disclosure-group"]`;禁用时 `aria-disabled` / `data-disabled`。 +- 子 Disclosure 以 `id` 作为组键注册/注销;展开状态由组统一决定。 +- 单选:点击已展开项可收起到 `[]`;多选:增删键,不改调用方数组。 + +## 4. 示例对照 + +| 基线 | Vue 演示 | 状态 | +| ------------- | ------------------------------------ | ---------------------------------------------------- | +| basic | `disclosure-group-basic.vue` | 已迁移;两组 Disclosure + Separator | +| controlled | `disclosure-group-controlled.vue` | 已迁移;useDisclosureGroupNavigation 外部上一/下一项 | +| custom-styles | `disclosure-group-custom-styles.vue` | 已迁移 | + +## 5. 变更文件 + +新增:`disclosure-group/{DisclosureGroup.vue,context.ts,useDisclosureGroupNavigation.ts}`、`disclosure-group.css`、文档与 3 个演示。公开导出:`DisclosureGroup`、`useDisclosureGroupNavigation` 及类型、`DisclosureKey`。 + +## 6. 验证结果 + +同批计数:`pnpm test` 19 文件 / **331**(SSR 8);`pnpm test:unit` 18 文件 / **323**。含组单选/多选/空值、数字与字符串 key 区分、组禁用、导航边界与增减提交的单元测试。 + +浏览器:controlled 示例上一/下一项按钮在边界禁用并可切换展开键。 + +## 7. 已知差异与未验证项 + +- 不使用 Reka Accordion 作为组底座(其 `value: string` 与 single/multiple 模型无法无损表达字符串/数字 key 与 RAC DisclosureGroup API);组状态为家族私有内核。 +- `useDisclosureGroupNavigation.itemIds` 类型比上游 `string[]` 更宽。 +- 未验证:复杂嵌套组、虚拟列表成员、读屏等。 + +## 8. 最短复核路径 + +1. `/components/disclosure-group`:点击两项应单选切换;controlled 示例点「下一项」应移动展开键。 +2. 运行同批测试命令核对 331 / 323。 + +## 视觉/动画返工(2026-10-22,实施者) + +独立浏览器复核发现布局与动画未达标,已修复(未提交): + +1. **展开高度为 0**:原在 `height:0` 面板上测量,变量恒为 0。改为 RAC `useDisclosure` 协议:CSS 始终 `height: var(--disclosure-panel-height)`,JS 在展开时写 `scrollHeight px`(过渡到目标)→ 动画结束后 `auto`;收起时先写当前 `px` 再写 `0px`,动画结束后设 `hidden="until-found"`。`data-expanded` 只驱动 opacity。 +2. **箭头错位**:`.hv-disclosure__trigger { inline-block }` 覆盖 Button 的 `inline-flex`;Button 通用 `svg` 负边距覆盖 `ms-auto`。改为 trigger `inline-flex`,并以更高优先级恢复指示器 `margin-inline-start: auto` 与 16px 尺寸。basic/render-function 触发按钮使用 `full-width`。 +3. **浏览器实测**:开合高度 0→56→0 与 opacity 同步 200ms;指示器 `rotate: -180deg`(250ms);关闭动画期间不设 `hidden`。 + +未改共享 Button 协议,仅在 disclosure.css 覆盖指示器 SVG 边距。`pnpm test` 331 仍通过。 + +## 复核返工(2026-10-22,对照 M21-M23-review.md) + +六项缺陷已修复,未提交/推送: + +1. **P1 无 id 成员**:组内成员始终参与组协议;未传 `id` 时用实例稳定 auto key(useId)注册。单展开与组禁用对无 id 项生效(accordion-basic 实测互斥)。 +2. **DOM ID 碰撞**:集合 key 保留类型身份(1 ≠ "1");DOM id 不再直接序列化 key——显式字符串 id 保留,数字/auto 用实例 useId。重复 key 会 `console.warn`。 +3. **受控事件旧值**:`expandedChange` / `update:expanded` 发出本次请求的 `next`,不回读未回流的受控 props。 +4. **asChild 禁用点击**:禁用 guard 置于子监听与 emit 之前(含 capture 拦截),禁用时不再执行自定义 onClick。 +5. **过期动画回调**:`useDisclosurePanelHeight` 用操作代次 + disposed + 当前 expanded 校验;旧 close Promise 不能隐藏已重开的面板。参数读取改为 `toValue`。 +6. **Content/Panel/Body 的 `as`**:已实现(文档原本有声明);`as="section"` 等可换根元素。 + +新增 `useDisclosureItem` 共享内核,减少 Disclosure/AccordionItem 重复。回归 20 项含上述场景。 + +计数:`pnpm test` 19 文件 / **337**(SSR 8);`pnpm test:unit` 18 文件 / **329**。typecheck / format 通过。 + +## asChild Trigger 返工(2026-10-22,第二轮复核) + +三项 P2 已修复: + +1. **子回调执行两次**:`cloneVNode` 自动合并 + 手动调用重复。现剥离子 `onClick`/`onClickCapture` 后只经合成 handler 执行一次(guard → child → emit → toggle)。 +2. **禁用时子 capture 仍执行**:capture 同样剥离后由 `makeTriggerCaptureHandler` 统一处理,禁用时在任何子监听之前 `preventDefault` + `stopImmediatePropagation`。 +3. **`v-if="false"` 注释开头丢按钮**:`resolveAsChildTarget` 展开 Fragment、忽略注释/空白文本;唯一有效根才 asChild 合并,多根 warn 并原样渲染。 + +新增 3 组回归(Disclosure/Accordion 双家族 click 计数、disabled capture、注释前缀)。 + +计数:`pnpm test` 19 文件 / **340**(SSR 8);`pnpm test:unit` 18 文件 / **332**。typecheck / format 通过。 + +## 事件适配第三轮返工(2026-10-22) + +两项 P2 已修复: + +1. **`@click.stop` 误阻止展开**:原先把 `cancelBubble` 当成 `stopImmediatePropagation`,并跳过 emit/toggle。现将 child/Trigger/capture 监听排成 Vue 数组交给 invoker,由原生语义处理:`stopPropagation` 不断同节点后续监听,`stopImmediatePropagation` 才断,`preventDefault` 只取消展开。 +2. **asChild 丢失 Trigger 的 `@click.capture`**:`shared` 里的 capture 曾被覆盖。现与子根 capture 一起按序合并进数组(禁用 guard 最前)。 + +另修 Vue invoker `_vts` 同刻防重入导致手动调用被跳过的问题:解包 `invoker.value` 后重组数组,不再二次调用 invoker。 + +回归 5 组:stopPropagation 后续监听+展开、stopImmediate 断链、preventDefault 取消展开、Trigger+child capture 各一次、禁用阻断 capture。 + +计数:`pnpm test` 19 文件 / **345**(SSR 8);`pnpm test:unit` 18 文件 / **337**。typecheck / format 通过。 diff --git a/docs/migrations/M23-accordion.md b/docs/migrations/M23-accordion.md new file mode 100644 index 0000000..190a304 --- /dev/null +++ b/docs/migrations/M23-accordion.md @@ -0,0 +1,125 @@ +# M23 Accordion 交接报告 + +实施日期:2026-10-22。状态:实施者自测完成,待集成人复核。**未提交、未推送、未宣布验收通过。** + +## 1. 起点与范围 + +起始 HEAD `73bd7da`。范围:Accordion、Item、Heading、Trigger、Panel、Body、Indicator、表面变体与 hideSeparator、10 个示例。复用 M21/M22 的展开内核与组键协议。 + +## 2. 上游核对 + +- AccordionRoot 包装 DisclosureGroup;AccordionItem 包装 Disclosure;Panel/Body/Trigger/Indicator/Heading 独立 slot 类。 +- `variant="default" | "surface"`(CSS 为 `accordion--surface`;文档正文另写 `--outline`,以固定源码 CSS 为准)。 +- `hideSeparator` → `data-hide-separator="true"`。 +- 表面变体提供 SurfaceContext `{variant:"default"}`,便于内层对比色。 +- 10 个中文预览:basic、surface、without-separator、multiple、disabled、controlled、custom-indicator、render-function、faq、custom-styles。 + +## 3. Vue 实现与 API + +| 上游 | Vue | +| --------------------- | ------------------------------ | +| `Accordion` | `Accordion` | +| `Accordion.Item` | `AccordionItem`(`id` 为组键) | +| `Accordion.Heading` | `AccordionHeading` | +| `Accordion.Trigger` | `AccordionTrigger` | +| `Accordion.Panel` | `AccordionPanel` | +| `Accordion.Body` | `AccordionBody` | +| `Accordion.Indicator` | `AccordionIndicator` | +| `render` | `as` + 透传属性 | + +Root:`expandedKeys` / `defaultExpandedKeys` / `allowsMultipleExpanded` / `isDisabled` / `variant` / `hideSeparator` / `as` / `class`。Item:`id` / `expanded` / `defaultExpanded` / `isDisabled` / `as`。 + +行为落点: + +- 根 `div[data-slot="accordion"]`;项 `div[data-slot="accordion-item"]`。 +- Trigger `type="button"`、`aria-expanded`、`aria-controls` → Panel `id`。 +- 分隔线由 `::after` 与 `data-hide-separator` 控制;surface 变体首尾圆角与分隔线 inset 对齐基线。 +- 指示器默认基线 Chevron,可插槽替换(custom-indicator 的加减号/圆形/双箭头)。 + +## 4. 示例对照(10/10) + +| 基线 | Vue 演示 | 状态 | +| ----------------- | --------------------------------- | ---------------------------------- | +| basic | `accordion-basic.vue` | 已迁移;6 项 + 图标 + 自定义指示器 | +| surface | `accordion-surface.vue` | 已迁移 | +| without-separator | `accordion-without-separator.vue` | 已迁移 | +| multiple | `accordion-multiple.vue` | 已迁移;allows-multiple-expanded | +| disabled | `accordion-disabled.vue` | 已迁移;整组禁用 + 单项禁用 | +| controlled | `accordion-controlled.vue` | 已迁移;导航 composable | +| custom-indicator | `accordion-custom-indicator.vue` | 已迁移;三种自定义图标 | +| render-function | `accordion-render-function.vue` | 已迁移;as + data-custom | +| faq | `accordion-faq.vue` | 已迁移;分类 FAQ | +| custom-styles | `accordion-custom-styles.vue` | 已迁移 | + +## 5. 变更文件 + +新增:`packages/vue/src/components/accordion/*`、`accordion.css`、`apps/docs/components/accordion.md`、`apps/docs/demos/accordion-*.vue`(10)。共享增量同 M21/M22。 + +## 6. 验证结果 + +同批计数:`pnpm test` 19 文件 / **331**(SSR 8);`pnpm test:unit` 18 文件 / **323**。覆盖多项展开、受控键、整组/单项禁用、hideSeparator、surface 变体类。 + +浏览器(127.0.0.1:5173/components/accordion):42 个 Trigger 均为 `type=button`;`aria-controls` 与 Panel `id` 一致;点击后 `aria-expanded=true`、`data-expanded=true`、`hidden` 移除;surface 变体类存在;侧栏含 Accordion/Disclosure/DisclosureGroup。 + +## 7. 已知差异与未验证项 + +- 文档正文的 `.accordion--outline` 与固定 CSS 的 `--surface` 变体不一致,实现以源码 CSS 为准。 +- Gravity UI 图标改为 Tabler;无 Expo 品牌图标时用 `IconDeviceMobile`。 +- 高度动画在 jsdom 中测量为 0,真实浏览器展开过渡未做逐帧对比。 +- 未验证:读屏、RTL、触屏、Nuxt、独立安装、自动视觉。 + +## 8. 最短复核路径 + +1. `/components/accordion`:展开「如何下单?」查看正文与指示器旋转;`without-separator` 无分隔线。 +2. `custom-indicator` 展开 id=1 应显示减号。 +3. 运行同批测试命令核对 331 / 323。 + +## 视觉/动画返工(2026-10-22,实施者) + +独立浏览器复核发现布局与动画未达标,已修复(未提交): + +1. **展开高度为 0**:原在 `height:0` 面板上测量,变量恒为 0。改为 RAC `useDisclosure` 协议:CSS 始终 `height: var(--disclosure-panel-height)`,JS 在展开时写 `scrollHeight px`(过渡到目标)→ 动画结束后 `auto`;收起时先写当前 `px` 再写 `0px`,动画结束后设 `hidden="until-found"`。`data-expanded` 只驱动 opacity。 +2. **箭头错位**:`.hv-disclosure__trigger { inline-block }` 覆盖 Button 的 `inline-flex`;Button 通用 `svg` 负边距覆盖 `ms-auto`。改为 trigger `inline-flex`,并以更高优先级恢复指示器 `margin-inline-start: auto` 与 16px 尺寸。basic/render-function 触发按钮使用 `full-width`。 +3. **浏览器实测**:开合高度 0→56→0 与 opacity 同步 200ms;指示器 `rotate: -180deg`(250ms);关闭动画期间不设 `hidden`。 + +未改共享 Button 协议,仅在 disclosure.css 覆盖指示器 SVG 边距。`pnpm test` 331 仍通过。 + +## 复核返工(2026-10-22,对照 M21-M23-review.md) + +六项缺陷已修复,未提交/推送: + +1. **P1 无 id 成员**:组内成员始终参与组协议;未传 `id` 时用实例稳定 auto key(useId)注册。单展开与组禁用对无 id 项生效(accordion-basic 实测互斥)。 +2. **DOM ID 碰撞**:集合 key 保留类型身份(1 ≠ "1");DOM id 不再直接序列化 key——显式字符串 id 保留,数字/auto 用实例 useId。重复 key 会 `console.warn`。 +3. **受控事件旧值**:`expandedChange` / `update:expanded` 发出本次请求的 `next`,不回读未回流的受控 props。 +4. **asChild 禁用点击**:禁用 guard 置于子监听与 emit 之前(含 capture 拦截),禁用时不再执行自定义 onClick。 +5. **过期动画回调**:`useDisclosurePanelHeight` 用操作代次 + disposed + 当前 expanded 校验;旧 close Promise 不能隐藏已重开的面板。参数读取改为 `toValue`。 +6. **Content/Panel/Body 的 `as`**:已实现(文档原本有声明);`as="section"` 等可换根元素。 + +新增 `useDisclosureItem` 共享内核,减少 Disclosure/AccordionItem 重复。回归 20 项含上述场景。 + +计数:`pnpm test` 19 文件 / **337**(SSR 8);`pnpm test:unit` 18 文件 / **329**。typecheck / format 通过。 + +## asChild Trigger 返工(2026-10-22,第二轮复核) + +三项 P2 已修复: + +1. **子回调执行两次**:`cloneVNode` 自动合并 + 手动调用重复。现剥离子 `onClick`/`onClickCapture` 后只经合成 handler 执行一次(guard → child → emit → toggle)。 +2. **禁用时子 capture 仍执行**:capture 同样剥离后由 `makeTriggerCaptureHandler` 统一处理,禁用时在任何子监听之前 `preventDefault` + `stopImmediatePropagation`。 +3. **`v-if="false"` 注释开头丢按钮**:`resolveAsChildTarget` 展开 Fragment、忽略注释/空白文本;唯一有效根才 asChild 合并,多根 warn 并原样渲染。 + +新增 3 组回归(Disclosure/Accordion 双家族 click 计数、disabled capture、注释前缀)。 + +计数:`pnpm test` 19 文件 / **340**(SSR 8);`pnpm test:unit` 18 文件 / **332**。typecheck / format 通过。 + +## 事件适配第三轮返工(2026-10-22) + +两项 P2 已修复: + +1. **`@click.stop` 误阻止展开**:原先把 `cancelBubble` 当成 `stopImmediatePropagation`,并跳过 emit/toggle。现将 child/Trigger/capture 监听排成 Vue 数组交给 invoker,由原生语义处理:`stopPropagation` 不断同节点后续监听,`stopImmediatePropagation` 才断,`preventDefault` 只取消展开。 +2. **asChild 丢失 Trigger 的 `@click.capture`**:`shared` 里的 capture 曾被覆盖。现与子根 capture 一起按序合并进数组(禁用 guard 最前)。 + +另修 Vue invoker `_vts` 同刻防重入导致手动调用被跳过的问题:解包 `invoker.value` 后重组数组,不再二次调用 invoker。 + +回归 5 组:stopPropagation 后续监听+展开、stopImmediate 断链、preventDefault 取消展开、Trigger+child capture 各一次、禁用阻断 capture。 + +计数:`pnpm test` 19 文件 / **345**(SSR 8);`pnpm test:unit` 18 文件 / **337**。typecheck / format 通过。 diff --git a/docs/upstream.md b/docs/upstream.md index 9e7ae78..7e7519d 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -91,3 +91,13 @@ CSS 仅 hv- 命名空间及 reduced-motion 的等价原生 media 适配(避免 - progress-bar 的 custom-value 示例上游使用 NumberField/Select;Vue 侧以原生 number/select + hv-input 临时替代并在文档标注,不冒充已迁移组件。 M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生/Fragment 标签预规划实现。显式 ID 优先,每个自动 ID 唯一,Root 引用真实标签;fieldScope 区分外围字段、当前 indicator 与嵌套字段的标签所有者。任意自定义 Vue 包装内部的标签仍需在 SSR 显式提供 ID/aria-labelledby;未声称所有包装都可静态展开。 + +## M21–M23 来源(2026-10-22) + +固定 ce90ea3 / HeroUI 3.2.6: + +- `packages/react/src/components/{disclosure,disclosure-group,accordion}` 与 `use-disclosure-group-navigation.ts`:部件结构、展开 API、导航 hook。 +- `packages/styles/components/{disclosure,disclosure-group,accordion}.css` 与同名 tv:移植为 hv- 命名空间;高度动画绑定 Reka Collapsible 测量变量。Apache-2.0 来源头与 third-party/HEROUI-LICENSE 保留。 +- 默认 Chevron 来自基线 `icons.tsx` IconChevronDown;文档图标为 Tabler;Expo 品牌图标无 Tabler 对应,演示用 IconDeviceMobile。 +- CN `(navigation)/{disclosure,disclosure-group,accordion}.mdx` 与 demos/cn 对应目录:共 16 个文档预览。 +- 组展开键由 React Set 改为 Vue `Array`,保持 key 身份;`useDisclosureGroupNavigation` 为公开 composable。 diff --git a/docs/verification.md b/docs/verification.md index bc3a28b..7140226 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -380,3 +380,60 @@ CheckboxGroup 底座行为临时探针单独验证了禁用值仍提交与 reset [完整报告](./migrations/M18-M20-review.md#返工后独立复核与集成修正2026-10-22)。四项 P2 已关闭;集成人另外修复共享 Label 的内外层字段作用域隔离,并新增标签 ID 动态变化/重排/卸载、嵌套字段标签所有权、实际 SSR 水合三项正式测试。 最终 test 18 文件 / 316 项(node SSR 7),unit 17 文件 / 309 项(不含 node SSR,含 jsdom 实际水合)。typecheck/build:docs/format/diff-check 通过。dist Props 正反消费探针通过后移除;20 个演示和 6 份原文 SFC 编译挂载回归通过。未新增逐页浏览器、逐像素、完整读屏/触屏/RTL、Nuxt 或独立安装验收。 + +## M21–M23 Disclosure / DisclosureGroup / Accordion(2026-10-22,实施者自测) + +起始 HEAD `73bd7da`。保留工作区未提交的 AGENTS.md / migration-handoff.md / lessons / 提示词。未提交、未推送、未宣布集成验收通过。 + +### 命令 + +| 命令 | 文件数 | 通过数 | 含 SSR | +| ---------------- | ------ | ------ | ------- | +| `pnpm test` | 19 | 331 | 是(8) | +| `pnpm test:unit` | 18 | 323 | 否 | + +typecheck / build:docs / format / git diff --check 通过。新增 `tests/disclosure-accordion.test.ts` 14 项;`ssr.test.ts` +1(披露组与手风琴 SSR + aria-controls 可解析)。 + +### 浏览器(127.0.0.1:5173) + +- Accordion 页:Trigger `type=button`,`aria-controls` 指向 Panel `id`;点击后 `aria-expanded=true`、`data-expanded=true`、`hidden` 移除;surface 变体类存在。 +- 侧栏包含 Accordion / Disclosure / DisclosureGroup;相邻页导航随 Layout 列表生效。 +- 16 个演示均在 jsdom 实际挂载且无 console 警告。 + +### 未验证 + +- 高度展开动画的逐帧视觉、读屏、RTL、触屏、Nuxt 水合、独立安装 dist。 +- `test:browser` / `test:visual` / `test:package` 尚未建立。 + +## M21–M23 布局与动画返工(2026-10-22) + +- 展开动画改按 React Aria `useDisclosure` 协议驱动 `--disclosure-panel-height`(px → auto / px → 0),高度与 opacity 200ms 过渡,与基线 CSS 一致。 +- 修复 trigger/indicator 错位(inline-flex + 指示器 ms-auto 恢复),浏览器实测箭头贴右、高度动画中间帧 0→17→32→47→56。 +- 指示器展开 `rotate: -180deg`(250ms)。关闭动画结束后才设 `hidden="until-found"`。 +- `pnpm test` 19 文件 / 331 仍通过;typecheck/format 通过。 + +## M21–M23 示例对齐修正(2026-10-22) + +- `Disclosure.Body` / `Accordion.Body` 的调用方 `class` 改为落在内层 `body-inner`(与基线 `composeSlotClassName(bodyInner, className)` 一致),外层仅保留 `body` 槽位类。 +- 去掉 basic/render-function 误加的 `full-width`:基线 Button 为 fit-content,配合外层 `text-center`;箭头随按钮内容,不再拉满后贴右。 +- custom-styles / group-custom-styles 改回 `Button` + `w-full justify-between`。 +- FAQ 示例按基线补齐标题/说明、第三组「支持」、`variant="surface"` 与自定义 Chevron。 +- 浏览器实测:basic 按钮宽 200px 紧凑排布;Body 内层承载卡片样式;手风琴箭头贴右、标题左对齐。 + +## M21–M23 复核六项返工(2026-10-22) + +- 无 id 组成员单选/组禁用、1 与 "1" 的 DOM id 唯一、受控 next 事件、asChild 禁用 guard、过期关闭动画回调、Content/Panel/Body `as` 均已修复并补回归。 +- 浏览器:accordion-basic 连点两项仅第二项 aria-expanded=true;aria-controls 可解析到 panel。 +- `pnpm test` 19 文件 / **337**(SSR 8);`pnpm test:unit` 18 文件 / **329**。typecheck/format 通过。未新增逐像素/读屏/Nuxt/独立安装验收。 + +## M21–M23 asChild Trigger 第二轮返工(2026-10-22) + +- 修复子 click 双执行、禁用 capture 泄漏、注释前缀丢有效根;`pnpm test` **340** / unit **332**。 + +## M21–M23 事件适配第三轮(2026-10-22) + +- 区分 stopPropagation / stopImmediatePropagation / preventDefault;Trigger `@click.capture` 与子 capture 合并;`pnpm test` **345** / unit **337**。 + +## M21–M23 最终独立复核(2026-10-22) + +此前三轮缺陷已关闭,详见 [最终复核](./migrations/M21-M23-review.md)。正式 test 为 19 文件 / 345 项通过(含 node SSR 8);typecheck、build:docs、format、diff-check 通过,文档构建仅既有 chunk 大小提醒。独立 4 项补充探针覆盖两个家族与原生/库内按钮的 stopPropagation、双方点击/捕获次数,全部通过后移除,未计入正式数字。修正兼容矩阵的管道分隔符与测试冗余类型断言。本次没有重复逐页浏览器点击,也没有新增逐像素、读屏、Nuxt 或独立安装验收。 diff --git a/package.json b/package.json index 68cac8d..90152b1 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", + "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", "test:ssr": "vitest run tests/ssr.test.ts", "format": "prettier --check .", "format:fix": "prettier --write .", diff --git a/packages/styles/components/accordion.css b/packages/styles/components/accordion.css new file mode 100644 index 0000000..c1b566f --- /dev/null +++ b/packages/styles/components/accordion.css @@ -0,0 +1,163 @@ +/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc. + * See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */ + +/* Base accordion styles */ +.hv-accordion { + @apply w-full; + + /* Performance optimization - contain layout changes */ + contain: layout style; +} + +/* Accordion elements */ +.hv-accordion__body { + @apply text-sm; +} + +.hv-accordion__body-inner { + @apply px-4 pt-0 pb-4 text-muted; +} + +.hv-accordion__heading { + @apply flex; +} + +.hv-accordion__indicator { + @apply ms-auto size-4 shrink-0 text-muted; + + /** + * Transitions + */ + @apply transition duration-250 motion-reduce:transition-none; + + /* Expanded state for indicator rotation */ + &[data-expanded="true"] { + @apply -rotate-180; + } +} + +/* Accordion Item - Separator styles */ +.hv-accordion__item { + @apply relative border-none; +} + +.hv-accordion__item::after { + content: ""; + @apply absolute start-0 bottom-0 h-px w-full rounded-xs bg-separator; +} + +.hv-accordion__item:last-child::after { + content: none; +} + +/* Hide separator when hideSeparator prop is set */ +.hv-accordion__item[data-hide-separator="true"]::after { + display: none; +} +/* ------------------------------------ */ + +.hv-accordion__trigger { + cursor: var(--cursor-interactive); + + /* Base Styles */ + @apply flex flex-1 items-center justify-between px-4 py-4 text-start text-sm font-medium no-highlight; + + /** + * Transitions + * CRITICAL: motion-reduce must be AFTER transition for correct override specificity + */ + transition: + opacity 150ms var(--ease-out), + box-shadow 150ms var(--ease-out); + @apply motion-reduce:transition-none; + + /** + * Hover state + * CRITICAL: inside `@media (hover: hover)` this keys off `:hover` alone. React Aria writes + * `data-hovered` on a render tick, so on pointer leave the attribute outlives the native + * `:hover` by at least a frame; including it here keeps this background painted for that frame, + * after a custom `hover:bg-*` override has already stopped matching, and the default color + * flashes on top. `:hover` is the same signal Tailwind's `hover:` variant compiles to, so the + * default and any override switch in lockstep. `data-hovered` is still on the element for + * consumers who want to key their own styles off it. + */ + @media (hover: hover) { + &:hover:not([aria-expanded="true"]) { + background-color: color-mix( + in oklab, + var(--foreground) 3%, + transparent 90% + ); + } + } + + /* Focus state */ + &:focus-visible:not([data-focused]), + &[data-focus-visible="true"] { + @apply status-focused; + } + + /* Disabled State */ + &:disabled, + &[aria-disabled="true"] { + @apply status-disabled; + } +} + +.hv-accordion__panel { + opacity: 0; + height: var(--disclosure-panel-height); + overflow: clip; + + /** + * Transitions + * CRITICAL: motion-reduce must be AFTER transition for correct override specificity + */ + transition: + height 200ms var(--ease-out-quad), + opacity 200ms var(--ease-out); + @apply motion-reduce:transition-none; + + &[data-expanded="true"] { + will-change: height, opacity; + opacity: 1; + } +} + +/* Surface variant */ +.hv-accordion--surface { + @apply bg-surface; + border-radius: min(32px, var(--radius-3xl)); + + .hv-accordion__trigger { + /* See the base trigger hover state for why `data-hovered` is left out here. */ + @media (hover: hover) { + &:hover:not([aria-expanded="true"]) { + @apply bg-default; + } + } + } + + .hv-accordion__item::after { + @apply bg-surface-foreground/6; + } +} + +.hv-accordion--surface .hv-accordion__item { + /* Surface variant separator styling */ + &::after { + @apply start-[3%] w-[94%]; + } + + /* Special rounding for first and last items in surface variant */ + &:first-child [data-slot="accordion-trigger"] { + border-start-start-radius: min(32px, var(--radius-3xl)); + border-start-end-radius: min(32px, var(--radius-3xl)); + } + + &:last-child:not(:has([data-slot="accordion-trigger"][aria-expanded="true"])) + [data-slot="accordion-trigger"] { + border-end-start-radius: min(32px, var(--radius-3xl)); + border-end-end-radius: min(32px, var(--radius-3xl)); + } +} diff --git a/packages/styles/components/disclosure-group.css b/packages/styles/components/disclosure-group.css new file mode 100644 index 0000000..86d9515 --- /dev/null +++ b/packages/styles/components/disclosure-group.css @@ -0,0 +1,10 @@ +/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc. + * See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */ + +/* Base disclosure-group styles */ +.hv-disclosure-group { + @apply w-full; + + /* Performance optimization - contain layout changes */ + contain: layout style; +} diff --git a/packages/styles/components/disclosure.css b/packages/styles/components/disclosure.css new file mode 100644 index 0000000..8e522e5 --- /dev/null +++ b/packages/styles/components/disclosure.css @@ -0,0 +1,93 @@ +/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc. + * See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */ + +/* Base disclosure styles */ +.hv-disclosure { + @apply relative; +} + +.hv-disclosure__heading { + @apply flex; +} + +.hv-disclosure__trigger { + cursor: var(--cursor-interactive); + /* + * Baseline uses inline-block. Button is inline-flex; a later inline-block + * would override it and break icon/text/indicator row layout when asChild + * merges trigger styles onto Button. inline-flex keeps both cases aligned. + */ + @apply inline-flex items-center no-highlight; + + /* Focus state */ + &:focus-visible:not([data-focused]), + &[data-focus-visible="true"] { + @apply status-focused; + } + + /* Disabled state */ + &:disabled, + &[aria-disabled="true"] { + @apply status-disabled; + } +} + +.hv-disclosure__indicator { + @apply ms-auto size-4 shrink-0 text-inherit; + + /** + * Transitions + */ + @apply transition duration-250 motion-reduce:transition-none; + + /* Expanded state for indicator rotation */ + &[data-expanded="true"] { + @apply -rotate-180; + } +} + +/* + * Button's generic svg rule (specificity 0,2,2) sets margin-inline/-size on + * every svg except spinner/link-icon. Beat it and restore end-alignment when + * asChild merges the trigger onto Button. + */ +.hv-button svg.hv-disclosure__indicator[data-slot="disclosure-indicator"] { + margin-block: 0; + margin-inline: 0; + margin-inline-start: auto; + width: 1rem; + height: 1rem; +} + +/* + * Height is always var(--disclosure-panel-height). The variable is driven + * by useDisclosurePanelHeight (0px ↔ scrollHeight px → auto) so the CSS + * transition matches React Aria / HeroUI. data-expanded only changes opacity. + */ +.hv-disclosure__content { + opacity: 0; + height: var(--disclosure-panel-height); + overflow: clip; + + /** + * Transitions + * CRITICAL: motion-reduce must be AFTER transition for correct override specificity + */ + transition: + height 200ms var(--ease-out-quad), + opacity 200ms var(--ease-out); + @apply motion-reduce:transition-none; + + &[data-expanded="true"] { + will-change: height, opacity; + opacity: 1; + } +} + +.hv-disclosure__body { + @apply p-2; +} + +.hv-disclosure__body-inner { + /* Inner wrapper keeps caller class on the scrolling/inner box. */ +} diff --git a/packages/styles/index.css b/packages/styles/index.css index f7ffe81..c896d71 100644 --- a/packages/styles/index.css +++ b/packages/styles/index.css @@ -114,3 +114,9 @@ @import "./components/progress-circle.css" layer(components); @import "./components/meter.css" layer(components); + +@import "./components/disclosure.css" layer(components); + +@import "./components/disclosure-group.css" layer(components); + +@import "./components/accordion.css" layer(components); diff --git a/packages/styles/src/index.ts b/packages/styles/src/index.ts index 80a6438..1ea1e77 100644 --- a/packages/styles/src/index.ts +++ b/packages/styles/src/index.ts @@ -840,3 +840,54 @@ export const meterVariants = tv({ }); export type MeterVariants = VariantProps; + +export const disclosureVariants = tv({ + defaultVariants: {}, + slots: { + base: "hv-disclosure", + body: "hv-disclosure__body", + bodyInner: "hv-disclosure__body-inner", + content: "hv-disclosure__content", + heading: "hv-disclosure__heading", + indicator: "hv-disclosure__indicator", + trigger: "hv-disclosure__trigger", + }, + variants: {}, +}); + +export type DisclosureVariants = VariantProps; + +export const disclosureGroupVariants = tv({ + defaultVariants: {}, + slots: { + base: "hv-disclosure-group", + }, + variants: {}, +}); + +export type DisclosureGroupVariants = VariantProps< + typeof disclosureGroupVariants +>; + +export const accordionVariants = tv({ + slots: { + base: "hv-accordion", + body: "hv-accordion__body", + bodyInner: "hv-accordion__body-inner", + heading: "hv-accordion__heading", + indicator: "hv-accordion__indicator", + item: "hv-accordion__item", + panel: "hv-accordion__panel", + trigger: "hv-accordion__trigger", + }, + variants: { + variant: { + default: {}, + surface: { + base: "hv-accordion--surface", + }, + }, + }, +}); + +export type AccordionVariants = VariantProps; diff --git a/packages/vue/src/components/accordion/Accordion.vue b/packages/vue/src/components/accordion/Accordion.vue new file mode 100644 index 0000000..9963f00 --- /dev/null +++ b/packages/vue/src/components/accordion/Accordion.vue @@ -0,0 +1,108 @@ + diff --git a/packages/vue/src/components/accordion/AccordionBody.vue b/packages/vue/src/components/accordion/AccordionBody.vue new file mode 100644 index 0000000..7b5486c --- /dev/null +++ b/packages/vue/src/components/accordion/AccordionBody.vue @@ -0,0 +1,30 @@ + + + diff --git a/packages/vue/src/components/accordion/AccordionHeading.vue b/packages/vue/src/components/accordion/AccordionHeading.vue new file mode 100644 index 0000000..878baa4 --- /dev/null +++ b/packages/vue/src/components/accordion/AccordionHeading.vue @@ -0,0 +1,33 @@ + + + diff --git a/packages/vue/src/components/accordion/AccordionIndicator.vue b/packages/vue/src/components/accordion/AccordionIndicator.vue new file mode 100644 index 0000000..44e67b0 --- /dev/null +++ b/packages/vue/src/components/accordion/AccordionIndicator.vue @@ -0,0 +1,59 @@ + diff --git a/packages/vue/src/components/accordion/AccordionItem.vue b/packages/vue/src/components/accordion/AccordionItem.vue new file mode 100644 index 0000000..ba29c64 --- /dev/null +++ b/packages/vue/src/components/accordion/AccordionItem.vue @@ -0,0 +1,74 @@ + diff --git a/packages/vue/src/components/accordion/AccordionPanel.vue b/packages/vue/src/components/accordion/AccordionPanel.vue new file mode 100644 index 0000000..29b51eb --- /dev/null +++ b/packages/vue/src/components/accordion/AccordionPanel.vue @@ -0,0 +1,45 @@ + + + diff --git a/packages/vue/src/components/accordion/AccordionTrigger.vue b/packages/vue/src/components/accordion/AccordionTrigger.vue new file mode 100644 index 0000000..dd9473c --- /dev/null +++ b/packages/vue/src/components/accordion/AccordionTrigger.vue @@ -0,0 +1,94 @@ + diff --git a/packages/vue/src/components/accordion/context.ts b/packages/vue/src/components/accordion/context.ts new file mode 100644 index 0000000..35ca0d2 --- /dev/null +++ b/packages/vue/src/components/accordion/context.ts @@ -0,0 +1,24 @@ +import { + computed, + inject, + provide, + type ComputedRef, + type InjectionKey, +} from "vue"; +import type { AccordionVariants } from "@heroui-vue/styles"; + +export interface AccordionContext { + hideSeparator: ComputedRef; + variant: ComputedRef>; +} + +export const accordionContextKey: InjectionKey = + Symbol("hv-accordion"); + +export function provideAccordion(ctx: AccordionContext): void { + provide(accordionContextKey, ctx); +} + +export function injectAccordion(): AccordionContext | undefined { + return inject(accordionContextKey, undefined); +} diff --git a/packages/vue/src/components/disclosure-group/DisclosureGroup.vue b/packages/vue/src/components/disclosure-group/DisclosureGroup.vue new file mode 100644 index 0000000..c4b8380 --- /dev/null +++ b/packages/vue/src/components/disclosure-group/DisclosureGroup.vue @@ -0,0 +1,88 @@ + diff --git a/packages/vue/src/components/disclosure-group/context.ts b/packages/vue/src/components/disclosure-group/context.ts new file mode 100644 index 0000000..1e4ed4c --- /dev/null +++ b/packages/vue/src/components/disclosure-group/context.ts @@ -0,0 +1,164 @@ +import { + computed, + inject, + provide, + ref, + watch, + type ComputedRef, + type InjectionKey, + type Ref, +} from "vue"; + +export type DisclosureKey = string | number; + +export interface DisclosureSlots { + [slot: string]: string; +} + +export interface DisclosureItemContext { + /** Effective expanded state (group-aware). */ + isExpanded: ComputedRef; + isDisabled: ComputedRef; + toggle: () => void; + /** Stable id used for trigger/panel ARIA association. */ + contentId: ComputedRef; + triggerId: ComputedRef; +} + +export const disclosureItemContextKey: InjectionKey = + Symbol("hv-disclosure-item"); + +export interface DisclosureGroupContext { + expandedKeys: ComputedRef; + allowsMultipleExpanded: ComputedRef; + isDisabled: ComputedRef; + isExpanded: (key: DisclosureKey) => boolean; + toggle: (key: DisclosureKey) => void; + /** Register a member key for navigation helpers; returns unregister. */ + registerItem: (key: DisclosureKey) => () => void; + itemKeys: ComputedRef; +} + +export const disclosureGroupContextKey: InjectionKey = + Symbol("hv-disclosure-group"); + +/** + * Key identity uses SameValueZero via Array.includes / index search, + * so numeric 1 and string "1" never collide. + */ +export function keyIndexOf(keys: DisclosureKey[], key: DisclosureKey): number { + for (let i = 0; i < keys.length; i += 1) { + if (Object.is(keys[i], key) || keys[i] === key) return i; + } + return -1; +} + +export function keysEqual(a: DisclosureKey[], b: DisclosureKey[]): boolean { + if (a.length !== b.length) return false; + for (let i = 0; i < a.length; i += 1) { + if (keyIndexOf(b, a[i]!) === -1) return false; + } + return true; +} + +export interface UseDisclosureGroupStateOptions { + expandedKeys?: DisclosureKey[] | undefined; + defaultExpandedKeys?: DisclosureKey[] | undefined; + allowsMultipleExpanded?: boolean; + isDisabled?: boolean; + onExpandedChange?: (keys: DisclosureKey[]) => void; +} + +export function useDisclosureGroupState( + options: UseDisclosureGroupStateOptions, + emitUpdate?: (keys: DisclosureKey[]) => void, +) { + const internal = ref([ + ...(options.defaultExpandedKeys ?? []), + ]); + const itemKeys = ref([]); + + const isControlled = computed(() => options.expandedKeys !== undefined); + + const expandedKeys = computed(() => + isControlled.value ? [...(options.expandedKeys ?? [])] : internal.value, + ); + + const allowsMultipleExpanded = computed( + () => options.allowsMultipleExpanded === true, + ); + const isDisabled = computed(() => options.isDisabled === true); + + function commit(next: DisclosureKey[]) { + // Never mutate the caller array. + const copy = [...next]; + if (!isControlled.value) { + internal.value = copy; + } + options.onExpandedChange?.(copy); + emitUpdate?.(copy); + } + + function isExpanded(key: DisclosureKey): boolean { + return keyIndexOf(expandedKeys.value, key) !== -1; + } + + function toggle(key: DisclosureKey) { + if (isDisabled.value) return; + const current = expandedKeys.value; + const open = keyIndexOf(current, key) !== -1; + if (allowsMultipleExpanded.value) { + const next = open + ? current.filter((k) => keyIndexOf([key], k) === -1) + : [...current, key]; + commit(next); + return; + } + // Single: replace; clicking open item closes it (allowsEmptySelection-style). + commit(open ? [] : [key]); + } + + function registerItem(key: DisclosureKey): () => void { + if (keyIndexOf(itemKeys.value, key) !== -1) { + // Keep both instances mounted, but make the collision visible. + console.warn( + `[heroui-vue] duplicate disclosure key ${JSON.stringify(key)}; group expand state will be shared.`, + ); + } + itemKeys.value = [...itemKeys.value, key]; + return () => { + itemKeys.value = itemKeys.value.filter( + (k) => keyIndexOf([key], k) === -1, + ); + }; + } + + // Keep internal state in sync when controlled prop is removed. + watch( + () => options.expandedKeys, + (value, prev) => { + if (value === undefined && prev !== undefined) { + internal.value = [...(prev ?? [])]; + } + }, + ); + + return { + expandedKeys, + allowsMultipleExpanded, + isDisabled, + isExpanded, + toggle, + registerItem, + itemKeys: computed(() => itemKeys.value), + commit, + }; +} + +export function injectDisclosureGroup(): DisclosureGroupContext | undefined { + return inject(disclosureGroupContextKey, undefined); +} + +export function provideDisclosureGroup(ctx: DisclosureGroupContext): void { + provide(disclosureGroupContextKey, ctx); +} diff --git a/packages/vue/src/components/disclosure-group/useDisclosureGroupNavigation.ts b/packages/vue/src/components/disclosure-group/useDisclosureGroupNavigation.ts new file mode 100644 index 0000000..cff8eea --- /dev/null +++ b/packages/vue/src/components/disclosure-group/useDisclosureGroupNavigation.ts @@ -0,0 +1,100 @@ +import { computed, toValue, type MaybeRefOrGetter } from "vue"; +import { keyIndexOf, type DisclosureKey } from "../disclosure-group/context"; + +export interface UseDisclosureGroupNavigationProps { + expandedKeys: MaybeRefOrGetter; + itemIds: MaybeRefOrGetter; + onExpandedChange: (keys: DisclosureKey[]) => void; + allowsMultipleExpanded?: boolean; +} + +export interface UseDisclosureGroupNavigationReturn { + currentIndex: number; + isPrevDisabled: boolean; + isNextDisabled: boolean; + onPrevious: () => void; + onNext: () => void; +} + +const EMPTY_ITEM_IDS: DisclosureKey[] = []; + +/** + * Vue port of HeroUI useDisclosureGroupNavigation. + * `expandedKeys` / `onExpandedChange` use arrays instead of Set; + * the source collection is never mutated. + */ +export function useDisclosureGroupNavigation({ + allowsMultipleExpanded = false, + expandedKeys, + itemIds = EMPTY_ITEM_IDS, + onExpandedChange, +}: UseDisclosureGroupNavigationProps): UseDisclosureGroupNavigationReturn { + const currentIndex = computed(() => { + const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; + const keys = toValue(expandedKeys) ?? []; + const expandedItems = ids.filter((id) => keyIndexOf(keys, id) !== -1); + const currentItem = expandedItems.length > 0 ? expandedItems[0] : ids[0]; + + if (currentItem === undefined) return -1; + + return keyIndexOf(ids, currentItem); + }); + + function handlePrevious() { + const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; + const keys = toValue(expandedKeys) ?? []; + const index = currentIndex.value; + if (index <= 0) return; + + const prevItem = ids[index - 1]; + + if (prevItem === undefined) return; + + if (allowsMultipleExpanded) { + if (keyIndexOf(keys, prevItem) === -1) { + onExpandedChange([...keys, prevItem]); + } + } else { + onExpandedChange([prevItem]); + } + } + + function handleNext() { + const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; + const keys = toValue(expandedKeys) ?? []; + const index = currentIndex.value; + if (index >= ids.length - 1) return; + + const nextItem = ids[index + 1]; + + if (nextItem === undefined) return; + + if (allowsMultipleExpanded) { + if (keyIndexOf(keys, nextItem) === -1) { + onExpandedChange([...keys, nextItem]); + } + } else { + onExpandedChange([nextItem]); + } + } + + const isPrevDisabled = computed(() => currentIndex.value <= 0); + const isNextDisabled = computed(() => { + const ids = toValue(itemIds) ?? EMPTY_ITEM_IDS; + return currentIndex.value >= ids.length - 1; + }); + + return { + get currentIndex() { + return currentIndex.value; + }, + get isPrevDisabled() { + return isPrevDisabled.value; + }, + get isNextDisabled() { + return isNextDisabled.value; + }, + onPrevious: handlePrevious, + onNext: handleNext, + }; +} diff --git a/packages/vue/src/components/disclosure/Disclosure.vue b/packages/vue/src/components/disclosure/Disclosure.vue new file mode 100644 index 0000000..af1c11a --- /dev/null +++ b/packages/vue/src/components/disclosure/Disclosure.vue @@ -0,0 +1,68 @@ + diff --git a/packages/vue/src/components/disclosure/DisclosureBody.vue b/packages/vue/src/components/disclosure/DisclosureBody.vue new file mode 100644 index 0000000..558258b --- /dev/null +++ b/packages/vue/src/components/disclosure/DisclosureBody.vue @@ -0,0 +1,26 @@ + + + diff --git a/packages/vue/src/components/disclosure/DisclosureChevronIcon.vue b/packages/vue/src/components/disclosure/DisclosureChevronIcon.vue new file mode 100644 index 0000000..621414b --- /dev/null +++ b/packages/vue/src/components/disclosure/DisclosureChevronIcon.vue @@ -0,0 +1,30 @@ + + + + + diff --git a/packages/vue/src/components/disclosure/DisclosureContent.vue b/packages/vue/src/components/disclosure/DisclosureContent.vue new file mode 100644 index 0000000..a398468 --- /dev/null +++ b/packages/vue/src/components/disclosure/DisclosureContent.vue @@ -0,0 +1,42 @@ + + + diff --git a/packages/vue/src/components/disclosure/DisclosureHeading.vue b/packages/vue/src/components/disclosure/DisclosureHeading.vue new file mode 100644 index 0000000..bfbb41f --- /dev/null +++ b/packages/vue/src/components/disclosure/DisclosureHeading.vue @@ -0,0 +1,34 @@ + + + diff --git a/packages/vue/src/components/disclosure/DisclosureIndicator.vue b/packages/vue/src/components/disclosure/DisclosureIndicator.vue new file mode 100644 index 0000000..08c3d63 --- /dev/null +++ b/packages/vue/src/components/disclosure/DisclosureIndicator.vue @@ -0,0 +1,55 @@ + diff --git a/packages/vue/src/components/disclosure/DisclosureTrigger.vue b/packages/vue/src/components/disclosure/DisclosureTrigger.vue new file mode 100644 index 0000000..cfdaf2e --- /dev/null +++ b/packages/vue/src/components/disclosure/DisclosureTrigger.vue @@ -0,0 +1,87 @@ + diff --git a/packages/vue/src/components/disclosure/triggerEvents.ts b/packages/vue/src/components/disclosure/triggerEvents.ts new file mode 100644 index 0000000..a76d80d --- /dev/null +++ b/packages/vue/src/components/disclosure/triggerEvents.ts @@ -0,0 +1,180 @@ +import { Comment, Fragment, Text, cloneVNode, isVNode, type VNode } from "vue"; + +type Handler = (event: MouseEvent) => void; + +function isIgnorableVNode(node: VNode): boolean { + if (node.type === Comment) return true; + if (node.type === Text) { + return String(node.children ?? "").trim() === ""; + } + return false; +} + +/** Flatten arrays/Fragments and drop comments/blank text. */ +export function meaningfulVNodes(list: unknown[]): VNode[] { + const out: VNode[] = []; + const walk = (nodes: unknown[]) => { + for (const node of nodes) { + if (node == null || node === false || node === true) continue; + if (Array.isArray(node)) { + walk(node); + continue; + } + if (!isVNode(node)) continue; + if (node.type === Fragment) { + walk((node.children ?? []) as unknown[]); + continue; + } + if (isIgnorableVNode(node)) continue; + out.push(node); + } + }; + walk(list); + return out; +} + +export interface AsChildTarget { + root?: VNode; + nodes: VNode[]; + fallback: unknown; +} + +export function resolveAsChildTarget(children: unknown): AsChildTarget { + const list = Array.isArray(children) ? children : [children]; + const nodes = meaningfulVNodes(list); + return { + root: nodes.length === 1 ? nodes[0] : undefined, + nodes, + fallback: children, + }; +} + +/** + * Vue wraps listeners in createInvoker (fn with .value = original handler(s)). + * Unwrap so composed arrays contain the real functions; Vue's array invoker + * then applies native stop / stopImmediatePropagation semantics. + */ +function unwrapInvoker(value: unknown): unknown { + if (typeof value === "function" && value && "value" in value) { + return (value as { value: unknown }).value; + } + return value; +} + +function flattenHandlers(value: unknown, out: Handler[] = []): Handler[] { + const raw = unwrapInvoker(value); + if (!raw) return out; + if (Array.isArray(raw)) { + for (const item of raw) flattenHandlers(item, out); + return out; + } + if (typeof raw === "function") out.push(raw as Handler); + return out; +} + +export interface TriggerClickOptions { + isDisabled: () => boolean; + /** Child onClick payload (function or array), stripped before clone. */ + childOnClick?: unknown; + emitClick: (event: MouseEvent) => void; + activate: () => void; +} + +/** + * Ordered asChild click listeners for Vue's array invoker: + * 1. disabled guard (stopImmediatePropagation) + * 2. child listeners (stopPropagation keeps later ones; stopImmediate stops them) + * 3. emit + activate (skipped on stopImmediate; activate skipped on preventDefault) + */ +export function makeTriggerClickHandlers( + options: TriggerClickOptions, +): Handler[] { + return [ + function disabledGuard(event: MouseEvent) { + if (options.isDisabled()) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + }, + ...flattenHandlers(options.childOnClick), + function emitAndActivate(event: MouseEvent) { + options.emitClick(event); + if (event.defaultPrevented) return; + options.activate(); + }, + ]; +} + +/** + * Capture-phase listeners: disabled guard first, then Trigger and child captures. + */ +export function makeTriggerCaptureHandlers( + isDisabled: () => boolean, + captureGroups: unknown[], +): Handler[] { + const handlers: Handler[] = [ + function disabledGuard(event: MouseEvent) { + if (isDisabled()) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + }, + ]; + for (const group of captureGroups) { + handlers.push(...flattenHandlers(group)); + } + return handlers; +} + +export interface AsChildCloneOptions { + isDisabled: () => boolean; + emitClick: (event: MouseEvent) => void; + activate: () => void; + class: unknown; + /** Trigger fallthrough attrs; onClick / onClickCapture are consumed here. */ + shared: Record; +} + +/** + * Clone the unique asChild root. Child and Trigger click/capture listeners are + * stripped then re-attached as ordered arrays (one execution path, correct + * stop semantics via Vue's invoker). + */ +export function cloneAsChildRoot( + root: VNode, + options: AsChildCloneOptions, +): VNode { + const childProps = (root.props ?? {}) as Record; + const childOnClick = childProps.onClick; + const childCapture = + childProps.onClickCapture ?? + childProps["onClick-capture"] ?? + childProps.onCapture; + + const cloned = cloneVNode(root); + const cleanedProps: Record = { ...(cloned.props ?? {}) }; + delete cleanedProps.onClick; + delete cleanedProps.onClickCapture; + delete cleanedProps["onClick-capture"]; + cloned.props = cleanedProps; + + const triggerCapture = options.shared.onClickCapture; + const sharedRest: Record = { ...options.shared }; + delete sharedRest.onClickCapture; + delete sharedRest.onClick; + + return cloneVNode(cloned, { + ...sharedRest, + class: options.class, + onClickCapture: makeTriggerCaptureHandlers(options.isDisabled, [ + triggerCapture, + childCapture, + ]), + onClick: makeTriggerClickHandlers({ + isDisabled: options.isDisabled, + childOnClick, + emitClick: options.emitClick, + activate: options.activate, + }), + }); +} diff --git a/packages/vue/src/components/disclosure/useDisclosureItem.ts b/packages/vue/src/components/disclosure/useDisclosureItem.ts new file mode 100644 index 0000000..f74b4d9 --- /dev/null +++ b/packages/vue/src/components/disclosure/useDisclosureItem.ts @@ -0,0 +1,129 @@ +import { + computed, + onUnmounted, + provide, + ref, + useId, + watch, + type ComputedRef, +} from "vue"; +import { useInheritedDisabled } from "../field/disabled"; +import { + disclosureItemContextKey, + injectDisclosureGroup, + type DisclosureKey, + type DisclosureItemContext, +} from "../disclosure-group/context"; + +/** + * DOM id encoding: collection keys keep type identity (1 ≠ "1"), + * but DOM ids must stay unique. Explicit string ids are kept as-is + * for DX; numbers and auto keys use the instance's SSR-stable useId. + */ +export function encodeDomId( + key: DisclosureKey | undefined, + fallback: string, +): string { + if (key === undefined) return fallback; + if (typeof key === "number") return fallback; + return String(key); +} + +export interface UseDisclosureItemOptions { + id?: DisclosureKey | undefined; + expanded?: boolean | undefined; + defaultExpanded?: boolean; + isDisabled?: boolean; + onExpanded: (next: boolean) => void; +} + +export interface DisclosureItemModel { + itemKey: ComputedRef; + domId: ComputedRef; + triggerId: ComputedRef; + contentId: ComputedRef; + isExpanded: ComputedRef; + isDisabled: ComputedRef; + toggle: () => void; +} + +/** + * Shared item state for Disclosure and AccordionItem. + * Group members always participate in the group (auto key when `id` is omitted). + * `onExpanded` receives the requested next flag — not a read-back of controlled props. + */ +export function useDisclosureItem( + options: UseDisclosureItemOptions, +): DisclosureItemModel { + const group = injectDisclosureGroup(); + const autoKeyId = useId(); + + /** Collection key: explicit id (type-preserving) or stable per-instance key. */ + const itemKey = computed(() => + options.id !== undefined ? options.id : autoKeyId, + ); + + const domId = computed(() => encodeDomId(options.id, autoKeyId)); + const triggerId = computed(() => `${domId.value}-trigger`); + const contentId = computed(() => `${domId.value}-content`); + + const localExpanded = ref( + options.expanded ?? options.defaultExpanded ?? false, + ); + watch( + () => options.expanded, + (value) => { + if (value !== undefined) localExpanded.value = value; + }, + ); + + const isControlled = computed(() => options.expanded !== undefined); + + const isExpanded = computed(() => { + if (group) return group.isExpanded(itemKey.value); + return isControlled.value ? options.expanded === true : localExpanded.value; + }); + + const isDisabled = useInheritedDisabled( + () => options.isDisabled === true || (group?.isDisabled.value ?? false), + ); + + function toggle() { + if (isDisabled.value) return; + // Compute next from the request; controlled props may not have reflowed yet. + const next = !isExpanded.value; + if (group) { + group.toggle(itemKey.value); + } else if (!isControlled.value) { + localExpanded.value = next; + } + options.onExpanded(next); + } + + let unregister: (() => void) | undefined; + if (group) { + unregister = group.registerItem(itemKey.value); + onUnmounted(() => { + unregister?.(); + unregister = undefined; + }); + } + + provide(disclosureItemContextKey, { + isExpanded, + isDisabled, + toggle, + contentId, + triggerId, + }); + + return { + itemKey, + domId, + triggerId, + contentId, + isExpanded, + isDisabled, + toggle, + }; +} diff --git a/packages/vue/src/components/disclosure/useDisclosurePanelHeight.ts b/packages/vue/src/components/disclosure/useDisclosurePanelHeight.ts new file mode 100644 index 0000000..723de32 --- /dev/null +++ b/packages/vue/src/components/disclosure/useDisclosurePanelHeight.ts @@ -0,0 +1,118 @@ +import { + onMounted, + onUnmounted, + ref, + toValue, + watch, + type MaybeRefOrGetter, + type Ref, +} from "vue"; + +export interface DisclosurePanelHeightApi { + /** Bound to the panel `hidden` attribute (until-found after close animation). */ + hidden: Ref<"until-found" | undefined>; +} + +/** + * Port of React Aria useDisclosure panel height protocol. + * CSS always uses `height: var(--disclosure-panel-height)`; this module + * animates that variable (0px ↔ scrollHeight px → auto) so open/close + * matches the fixed HeroUI baseline transition. + * + * Each apply() bumps a generation; stale animation callbacks from a prior + * close/open cycle must not hide a panel that has since been opened. + */ +export function useDisclosurePanelHeight( + panelEl: Ref, + isExpanded: MaybeRefOrGetter, +): DisclosurePanelHeightApi { + const hidden = ref<"until-found" | undefined>( + toValue(isExpanded) ? undefined : "until-found", + ); + let generation = 0; + let disposed = false; + let isExpandedRef: boolean | null = null; + + function apply(expanded: boolean, isInitial: boolean) { + const gen = ++generation; + if (typeof window === "undefined") return; + const panel = panelEl.value; + if (!panel) return; + + const canAnimate = typeof panel.getAnimations === "function"; + const commitHidden = (value: "until-found" | undefined) => { + if (disposed || gen !== generation) return; + if (value === undefined) { + panel.removeAttribute("hidden"); + hidden.value = undefined; + } else { + panel.setAttribute("hidden", value); + hidden.value = value; + } + }; + const commitHeight = (value: string) => { + if (disposed || gen !== generation) return; + panel.style.setProperty("--disclosure-panel-height", value); + }; + + if (isInitial || !canAnimate) { + if (expanded) { + commitHidden(undefined); + commitHeight("auto"); + } else { + commitHidden("until-found"); + commitHeight("0px"); + } + return; + } + + if (expanded) { + commitHidden(undefined); + commitHeight(`${panel.scrollHeight}px`); + void Promise.all(panel.getAnimations().map((a) => a.finished)) + .then(() => { + if (disposed || gen !== generation) return; + if (toValue(isExpanded) !== true) return; + commitHeight("auto"); + }) + .catch(() => { + /* cancelled transition — newer generation owns the panel */ + }); + } else { + commitHeight(`${panel.scrollHeight}px`); + void getComputedStyle(panel).height; + commitHeight("0px"); + void Promise.all(panel.getAnimations().map((a) => a.finished)) + .then(() => { + if (disposed || gen !== generation) return; + if (toValue(isExpanded) !== false) return; + commitHidden("until-found"); + }) + .catch(() => { + if (disposed || gen !== generation) return; + if (toValue(isExpanded) !== false) return; + commitHidden("until-found"); + }); + } + } + + function onExpandedChange() { + const expanded = Boolean(toValue(isExpanded)); + apply(expanded, isExpandedRef == null); + isExpandedRef = expanded; + } + + onMounted(() => { + const expanded = Boolean(toValue(isExpanded)); + apply(expanded, true); + isExpandedRef = expanded; + watch(() => Boolean(toValue(isExpanded)), onExpandedChange); + }); + + onUnmounted(() => { + disposed = true; + generation += 1; + }); + + return { hidden }; +} diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index a77d7a4..6c1d110 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -333,3 +333,53 @@ export { type ProgressCircleVariants, type MeterVariants, } from "@heroui-vue/styles"; + +export { default as Disclosure } from "./components/disclosure/Disclosure.vue"; +export { default as DisclosureHeading } from "./components/disclosure/DisclosureHeading.vue"; +export { default as DisclosureTrigger } from "./components/disclosure/DisclosureTrigger.vue"; +export { default as DisclosureContent } from "./components/disclosure/DisclosureContent.vue"; +export { default as DisclosureBody } from "./components/disclosure/DisclosureBody.vue"; +export { default as DisclosureIndicator } from "./components/disclosure/DisclosureIndicator.vue"; +export type { + DisclosureProps, + DisclosureHeadingProps, + DisclosureTriggerProps, + DisclosureContentProps, + DisclosureBodyProps, + DisclosureIndicatorProps, +} from "./types"; + +export { default as DisclosureGroup } from "./components/disclosure-group/DisclosureGroup.vue"; +export type { DisclosureGroupProps } from "./types"; +export { useDisclosureGroupNavigation } from "./components/disclosure-group/useDisclosureGroupNavigation"; +export type { + UseDisclosureGroupNavigationProps, + UseDisclosureGroupNavigationReturn, +} from "./components/disclosure-group/useDisclosureGroupNavigation"; +export type { DisclosureKey } from "./components/disclosure-group/context"; + +export { default as Accordion } from "./components/accordion/Accordion.vue"; +export { default as AccordionItem } from "./components/accordion/AccordionItem.vue"; +export { default as AccordionHeading } from "./components/accordion/AccordionHeading.vue"; +export { default as AccordionTrigger } from "./components/accordion/AccordionTrigger.vue"; +export { default as AccordionPanel } from "./components/accordion/AccordionPanel.vue"; +export { default as AccordionBody } from "./components/accordion/AccordionBody.vue"; +export { default as AccordionIndicator } from "./components/accordion/AccordionIndicator.vue"; +export type { + AccordionProps, + AccordionItemProps, + AccordionHeadingProps, + AccordionTriggerProps, + AccordionPanelProps, + AccordionBodyProps, + AccordionIndicatorProps, +} from "./types"; + +export { + disclosureVariants, + disclosureGroupVariants, + accordionVariants, + type DisclosureVariants, + type DisclosureGroupVariants, + type AccordionVariants, +} from "@heroui-vue/styles"; diff --git a/packages/vue/src/types.ts b/packages/vue/src/types.ts index f342824..a27b2b2 100644 --- a/packages/vue/src/types.ts +++ b/packages/vue/src/types.ts @@ -230,3 +230,50 @@ export type MeterProps = InstanceType["$props"]; export type MeterOutputProps = InstanceType["$props"]; export type MeterTrackProps = InstanceType["$props"]; export type MeterFillProps = InstanceType["$props"]; + +import type Disclosure from "./components/disclosure/Disclosure.vue"; +import type DisclosureHeading from "./components/disclosure/DisclosureHeading.vue"; +import type DisclosureTrigger from "./components/disclosure/DisclosureTrigger.vue"; +import type DisclosureContent from "./components/disclosure/DisclosureContent.vue"; +import type DisclosureBody from "./components/disclosure/DisclosureBody.vue"; +import type DisclosureIndicator from "./components/disclosure/DisclosureIndicator.vue"; +export type DisclosureProps = InstanceType["$props"]; +export type DisclosureHeadingProps = InstanceType< + typeof DisclosureHeading +>["$props"]; +export type DisclosureTriggerProps = InstanceType< + typeof DisclosureTrigger +>["$props"]; +export type DisclosureContentProps = InstanceType< + typeof DisclosureContent +>["$props"]; +export type DisclosureBodyProps = InstanceType["$props"]; +export type DisclosureIndicatorProps = InstanceType< + typeof DisclosureIndicator +>["$props"]; + +import type DisclosureGroup from "./components/disclosure-group/DisclosureGroup.vue"; +export type DisclosureGroupProps = InstanceType< + typeof DisclosureGroup +>["$props"]; + +import type Accordion from "./components/accordion/Accordion.vue"; +import type AccordionItem from "./components/accordion/AccordionItem.vue"; +import type AccordionHeading from "./components/accordion/AccordionHeading.vue"; +import type AccordionTrigger from "./components/accordion/AccordionTrigger.vue"; +import type AccordionPanel from "./components/accordion/AccordionPanel.vue"; +import type AccordionBody from "./components/accordion/AccordionBody.vue"; +import type AccordionIndicator from "./components/accordion/AccordionIndicator.vue"; +export type AccordionProps = InstanceType["$props"]; +export type AccordionItemProps = InstanceType["$props"]; +export type AccordionHeadingProps = InstanceType< + typeof AccordionHeading +>["$props"]; +export type AccordionTriggerProps = InstanceType< + typeof AccordionTrigger +>["$props"]; +export type AccordionPanelProps = InstanceType["$props"]; +export type AccordionBodyProps = InstanceType["$props"]; +export type AccordionIndicatorProps = InstanceType< + typeof AccordionIndicator +>["$props"]; diff --git a/tests/disclosure-accordion.test.ts b/tests/disclosure-accordion.test.ts new file mode 100644 index 0000000..64b68cf --- /dev/null +++ b/tests/disclosure-accordion.test.ts @@ -0,0 +1,1121 @@ +import { describe, it, expect, afterEach, vi } from "vitest"; +import { mount } from "@vue/test-utils"; +import { defineComponent, h, nextTick, ref } from "vue"; +import { + Button, + Accordion, + AccordionBody, + AccordionHeading, + AccordionIndicator, + AccordionItem, + AccordionPanel, + AccordionTrigger, + Disclosure, + DisclosureBody, + DisclosureContent, + DisclosureGroup, + DisclosureHeading, + DisclosureIndicator, + DisclosureTrigger, + useDisclosureGroupNavigation, +} from "../packages/vue/src"; + +afterEach(() => { + document.body.innerHTML = ""; +}); + +describe("Disclosure", () => { + it("toggles expanded state with real ARIA and content visibility", async () => { + const w = mount( + defineComponent({ + components: { + Disclosure, + DisclosureHeading, + DisclosureTrigger, + DisclosureContent, + DisclosureBody, + DisclosureIndicator, + }, + template: ` + + + + 标题 + + + + + 内容 + + + `, + }), + ); + const trigger = w.get("[data-slot=disclosure-trigger]"); + const content = w.get("[data-slot=disclosure-content]"); + expect(trigger.attributes("type")).toBe("button"); + expect(trigger.attributes("aria-expanded")).toBe("false"); + expect(content.attributes("aria-hidden")).toBe("true"); + + await trigger.trigger("click"); + expect(trigger.attributes("aria-expanded")).toBe("true"); + expect(content.attributes("aria-hidden")).toBe("false"); + expect(content.attributes("data-expanded")).toBe("true"); + expect( + w.get("[data-slot=disclosure-indicator]").attributes("data-expanded"), + ).toBe("true"); + + await trigger.trigger("click"); + expect(trigger.attributes("aria-expanded")).toBe("false"); + expect(content.attributes("aria-hidden")).toBe("true"); + }); + + it("supports v-model:expanded and defaultExpanded", async () => { + const expanded = ref(false); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ expanded }), + template: ` + + x + body + + `, + }), + ); + expect(expanded.value).toBe(false); + await w.get("[data-testid=t]").trigger("click"); + expect(expanded.value).toBe(true); + expect( + w.get("[data-slot=disclosure-trigger]").attributes("aria-expanded"), + ).toBe("true"); + + const uncontrolled = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + template: ` + + x + body + + `, + }), + ); + expect( + uncontrolled + .get("[data-slot=disclosure-trigger]") + .attributes("aria-expanded"), + ).toBe("true"); + }); + + it("blocks toggle when disabled and allows preventDefault cancel", async () => { + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + template: ` + + x + body + + `, + }), + ); + await w.get("[data-testid=t]").trigger("click"); + expect( + w.get("[data-slot=disclosure-trigger]").attributes("aria-expanded"), + ).toBe("false"); + + const click = vi.fn((e: MouseEvent) => e.preventDefault()); + const cancelable = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + template: ` + + x + body + + `, + methods: { onClick: click }, + }), + ); + await cancelable.get("[data-testid=t]").trigger("click"); + expect(click).toHaveBeenCalled(); + expect( + cancelable + .get("[data-slot=disclosure-trigger]") + .attributes("aria-expanded"), + ).toBe("false"); + }); + + it("associates trigger and panel ids uniquely and resolves ARIA", () => { + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + template: ` +
+ + x + c1 + + + y + c2 + +
+ `, + }), + ); + const t1 = w.get("[data-testid=t1]"); + const t2 = w.get("[data-testid=t2]"); + const c1 = w.get("#a-content"); + const c2 = w.get("#b-content"); + expect(t1.attributes("aria-controls")).toBe("a-content"); + expect(t2.attributes("aria-controls")).toBe("b-content"); + expect(w.find("#a-content").exists()).toBe(true); + expect(w.find("#b-content").exists()).toBe(true); + expect(t1.attributes("id")).not.toBe(t2.attributes("id")); + }); + + it("keeps explicit ARIA and dynamic attrs without dropping keys", async () => { + const label = ref(undefined); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger }, + setup: () => ({ label }), + template: ` + + x + + `, + }), + ); + const root = w.get("[data-slot=disclosure]"); + expect(root.attributes("data-custom")).toBe("keep"); + expect(root.attributes("aria-label")).toBeUndefined(); + label.value = "外部名称"; + await nextTick(); + expect(root.attributes("aria-label")).toBe("外部名称"); + label.value = undefined; + await nextTick(); + expect(root.attributes("aria-label")).toBeUndefined(); + }); +}); + +describe("DisclosureGroup", () => { + it("single mode replaces keys and supports empty selection", async () => { + const keys = ref>(["a"]); + const w = mount( + defineComponent({ + components: { + DisclosureGroup, + Disclosure, + DisclosureTrigger, + DisclosureContent, + }, + setup: () => ({ keys }), + template: ` + + Aca + Bcb + + `, + }), + ); + expect(w.get("[data-testid=ta]").attributes("aria-expanded")).toBe("true"); + await w.get("[data-testid=tb]").trigger("click"); + expect(keys.value).toEqual(["b"]); + await w.get("[data-testid=tb]").trigger("click"); + expect(keys.value).toEqual([]); + }); + + it("multiple mode adds and removes without mutating caller array", async () => { + const initial = ["a"]; + const keys = ref>([...initial]); + const w = mount( + defineComponent({ + components: { + DisclosureGroup, + Disclosure, + DisclosureTrigger, + DisclosureContent, + }, + setup: () => ({ keys }), + template: ` + + Aca + Bcb + + `, + }), + ); + await w.get("[data-testid=tb]").trigger("click"); + expect(keys.value).toEqual(["a", "b"]); + await w.get("[data-testid=ta]").trigger("click"); + expect(keys.value).toEqual(["b"]); + expect(initial).toEqual(["a"]); + }); + + it("keeps numeric and string keys distinct", async () => { + const keys = ref>([1]); + const w = mount( + defineComponent({ + components: { + DisclosureGroup, + Disclosure, + DisclosureTrigger, + DisclosureContent, + }, + setup: () => ({ keys }), + template: ` + + n1 + ss + + `, + }), + ); + expect(w.get("[data-testid=n1]").attributes("aria-expanded")).toBe("true"); + expect(w.get("[data-testid=s1]").attributes("aria-expanded")).toBe("false"); + }); + + it("group disable blocks items and can be inherited from Fieldset-like scope", async () => { + const disabled = ref(true); + const w = mount( + defineComponent({ + components: { + DisclosureGroup, + Disclosure, + DisclosureTrigger, + DisclosureContent, + }, + setup: () => ({ disabled }), + template: ` + + Aca + + `, + }), + ); + await w.get("[data-testid=ta]").trigger("click"); + expect(w.get("[data-testid=ta]").attributes("aria-expanded")).toBe("false"); + disabled.value = false; + await nextTick(); + await w.get("[data-testid=ta]").trigger("click"); + expect(w.get("[data-testid=ta]").attributes("aria-expanded")).toBe("true"); + }); +}); + +describe("useDisclosureGroupNavigation", () => { + it("handles empty list, boundaries, single replace and multiple add", () => { + const empty = useDisclosureGroupNavigation({ + expandedKeys: [], + itemIds: [], + onExpandedChange: () => {}, + }); + expect(empty.currentIndex).toBe(-1); + expect(empty.isPrevDisabled).toBe(true); + expect(empty.isNextDisabled).toBe(true); + empty.onPrevious(); + empty.onNext(); + + const keys = ref>(["a"]); + const commits: Array[] = []; + const nav = useDisclosureGroupNavigation({ + expandedKeys: keys, + itemIds: ["a", "b", "c"], + onExpandedChange: (next) => { + commits.push(next); + keys.value = next; + }, + }); + expect(nav.currentIndex).toBe(0); + expect(nav.isPrevDisabled).toBe(true); + expect(nav.isNextDisabled).toBe(false); + nav.onPrevious(); + expect(commits).toHaveLength(0); + nav.onNext(); + expect(commits.at(-1)).toEqual(["b"]); + expect(nav.currentIndex).toBe(1); + nav.onNext(); + expect(commits.at(-1)).toEqual(["c"]); + expect(nav.isNextDisabled).toBe(true); + + const multiKeys = ref>(["a"]); + const multiCommits: Array[] = []; + const multi = useDisclosureGroupNavigation({ + expandedKeys: multiKeys, + itemIds: ["a", "b", "c"], + allowsMultipleExpanded: true, + onExpandedChange: (next) => { + multiCommits.push(next); + multiKeys.value = next; + }, + }); + multi.onNext(); + expect(multiCommits.at(-1)).toEqual(["a", "b"]); + multi.onPrevious(); + // previous from index 1 goes to index 0 which is already expanded — adds only if missing + expect(multiCommits.at(-1)).toEqual(["a", "b"]); + }); +}); + +describe("Accordion", () => { + it("renders items with separators, hideSeparator and surface variant", async () => { + const w = mount( + defineComponent({ + components: { + Accordion, + AccordionItem, + AccordionHeading, + AccordionTrigger, + AccordionIndicator, + AccordionPanel, + AccordionBody, + }, + template: ` + + + + 一 + + 内容一 + + + `, + }), + ); + const root = w.get("[data-slot=accordion]"); + expect(root.classes()).toContain("hv-accordion--surface"); + const item = w.get("[data-slot=accordion-item]"); + expect(item.attributes("data-hide-separator")).toBe("true"); + expect(w.get("[data-slot=accordion-trigger]").attributes("type")).toBe( + "button", + ); + expect(w.find("[data-slot=accordion-panel]").exists()).toBe(true); + }); + + it("supports multiple expansion and controlled keys", async () => { + const keys = ref>([]); + const w = mount( + defineComponent({ + components: { + Accordion, + AccordionItem, + AccordionHeading, + AccordionTrigger, + AccordionIndicator, + AccordionPanel, + AccordionBody, + }, + setup: () => ({ keys }), + template: ` + + + A + ca + + + B + cb + + + `, + }), + ); + await w.get("[data-testid=ta]").trigger("click"); + await w.get("[data-testid=tb]").trigger("click"); + expect(keys.value).toEqual(["a", "b"]); + expect(w.get("[data-testid=ta]").attributes("aria-expanded")).toBe("true"); + expect(w.get("[data-testid=tb]").attributes("aria-expanded")).toBe("true"); + }); + + it("disables whole accordion and individual items", async () => { + const w = mount( + defineComponent({ + components: { + Accordion, + AccordionItem, + AccordionHeading, + AccordionTrigger, + AccordionIndicator, + AccordionPanel, + AccordionBody, + }, + template: ` +
+ + + A + x + + + + + B + y + + +
+ `, + }), + ); + await w.get("[data-testid=ga]").trigger("click"); + await w.get("[data-testid=ib]").trigger("click"); + expect(w.get("[data-testid=ga]").attributes("aria-expanded")).toBe("false"); + expect(w.get("[data-testid=ib]").attributes("aria-expanded")).toBe("false"); + expect(w.get("[data-testid=ib]").attributes("disabled")).toBeDefined(); + }); +}); + +describe("M21–M23 demos", () => { + const demoModules = import.meta.glob<{ default: unknown }>( + "../apps/docs/demos/{disclosure,disclosure-group,accordion}-*.vue", + { eager: true }, + ); + + it("mounts all 16 baseline demos without console errors", () => { + const names = Object.keys(demoModules) + .map((n) => n.split("/").pop()) + .sort(); + expect(names).toHaveLength(16); + expect(names).toEqual([ + "accordion-basic.vue", + "accordion-controlled.vue", + "accordion-custom-indicator.vue", + "accordion-custom-styles.vue", + "accordion-disabled.vue", + "accordion-faq.vue", + "accordion-multiple.vue", + "accordion-render-function.vue", + "accordion-surface.vue", + "accordion-without-separator.vue", + "disclosure-basic.vue", + "disclosure-custom-styles.vue", + "disclosure-group-basic.vue", + "disclosure-group-controlled.vue", + "disclosure-group-custom-styles.vue", + "disclosure-render-function.vue", + ]); + + const errors: unknown[] = []; + const warn = console.warn; + const error = console.error; + console.warn = (...args: unknown[]) => { + errors.push(args); + warn(...args); + }; + console.error = (...args: unknown[]) => { + errors.push(args); + error(...args); + }; + try { + for (const mod of Object.values(demoModules)) { + const w = mount(mod.default as never, { attachTo: document.body }); + expect(w.html().length).toBeGreaterThan(20); + w.unmount(); + document.body.innerHTML = ""; + } + } finally { + console.warn = warn; + console.error = error; + } + expect(errors).toEqual([]); + }); +}); + +describe("M21–M23 review regressions", () => { + it("enforces single-expand and group disable for members without id", async () => { + const keys = ref>([]); + const w = mount( + defineComponent({ + components: { + Accordion, + AccordionItem, + AccordionHeading, + AccordionTrigger, + AccordionPanel, + AccordionBody, + AccordionIndicator, + }, + setup: () => ({ keys }), + template: ` + + + 一 + a + + + 二 + b + + + `, + }), + ); + await w.get("[data-testid=t1]").trigger("click"); + await w.get("[data-testid=t2]").trigger("click"); + const a = w.get("[data-testid=t1]").attributes("aria-expanded"); + const b = w.get("[data-testid=t2]").attributes("aria-expanded"); + expect(a).toBe("false"); + expect(b).toBe("true"); + + const disabled = mount( + defineComponent({ + components: { + Accordion, + AccordionItem, + AccordionHeading, + AccordionTrigger, + AccordionPanel, + AccordionBody, + AccordionIndicator, + }, + template: ` + + + x + x + + + `, + }), + ); + await disabled.get("[data-testid=d1]").trigger("click"); + expect(disabled.get("[data-testid=d1]").attributes("aria-expanded")).toBe( + "false", + ); + expect( + disabled.get("[data-testid=d1]").attributes("disabled"), + ).toBeDefined(); + }); + + it("keeps DOM ids unique for number 1 and string '1'", async () => { + const w = mount( + defineComponent({ + components: { + DisclosureGroup, + Disclosure, + DisclosureTrigger, + DisclosureContent, + }, + template: ` + + nc1 + sc2 + + `, + }), + ); + const n = w.get("[data-testid=n]"); + const s = w.get("[data-testid=s]"); + expect(n.attributes("id")).toBeTruthy(); + expect(s.attributes("id")).toBeTruthy(); + expect(n.attributes("id")).not.toBe(s.attributes("id")); + expect(n.attributes("aria-controls")).not.toBe( + s.attributes("aria-controls"), + ); + const nPanel = n.attributes("aria-controls")!; + const sPanel = s.attributes("aria-controls")!; + expect(w.find(`[id="${nPanel}"]`).exists()).toBe(true); + expect(w.find(`[id="${sPanel}"]`).exists()).toBe(true); + expect(nPanel).not.toBe(sPanel); + }); + + it("emits requested next expanded state in controlled groups", async () => { + const events: boolean[] = []; + const keys = ref>([]); + const w = mount( + defineComponent({ + components: { + DisclosureGroup, + Disclosure, + DisclosureTrigger, + DisclosureContent, + }, + setup: () => ({ keys, events }), + template: ` + + + A + ca + + + `, + }), + ); + await w.get("[data-testid=ta]").trigger("click"); + expect(events.at(-1)).toBe(true); + expect(keys.value).toEqual(["a"]); + await w.get("[data-testid=ta]").trigger("click"); + expect(events.at(-1)).toBe(false); + expect(keys.value).toEqual([]); + }); + + it("does not run asChild child click when disabled", async () => { + const childClick = vi.fn(); + const emitClick = vi.fn(); + const w = mount( + defineComponent({ + components: { + Disclosure, + DisclosureTrigger, + DisclosureContent, + Button, + }, + setup: () => ({ childClick, emitClick }), + template: ` + + + + + body + + `, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(childClick).not.toHaveBeenCalled(); + expect(emitClick).not.toHaveBeenCalled(); + }); + + it("ignores stale close-animation callbacks after reopen", async () => { + let resolveClose!: () => void; + const closeFinished = new Promise((resolve) => { + resolveClose = resolve; + }); + // Stub getAnimations so close waits on our promise. + const proto = HTMLElement.prototype as HTMLElement & { + getAnimations?: () => Animation[]; + }; + const original = proto.getAnimations; + let mode: "close" | "open" = "close"; + proto.getAnimations = function getAnimations() { + const finished = + mode === "close" + ? (closeFinished as Promise) + : Promise.resolve(); + return [{ finished } as unknown as Animation]; + }; + + try { + const expanded = ref(true); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ expanded }), + template: ` + + x + body + + `, + }), + { attachTo: document.body }, + ); + await nextTick(); + // close + mode = "close"; + await w.get("[data-testid=t]").trigger("click"); + await nextTick(); + // reopen before close animation settles + mode = "open"; + await w.get("[data-testid=t]").trigger("click"); + await nextTick(); + // stale close promise rejects/settles + resolveClose(); + await Promise.resolve(); + await Promise.resolve(); + await nextTick(); + const panel = w.get("[data-testid=panel]"); + expect(panel.attributes("aria-hidden")).toBe("false"); + expect(panel.attributes("hidden")).toBeUndefined(); + } finally { + if (original) proto.getAnimations = original; + else { + (proto as { getAnimations?: unknown }).getAnimations = undefined; + } + } + }); + + it("renders DisclosureContent and AccordionPanel/Body with as", () => { + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureContent }, + template: ` + + body + + `, + }), + ); + const panel = w.get("[data-slot=disclosure-content]"); + expect(panel.element.tagName).toBe("SECTION"); + expect(panel.attributes("data-custom")).toBe("panel"); + + const acc = mount( + defineComponent({ + components: { + Accordion, + AccordionItem, + AccordionPanel, + AccordionBody, + }, + template: ` + + + + text + + + + `, + }), + ); + expect(acc.get("[data-slot=accordion-panel]").element.tagName).toBe( + "SECTION", + ); + expect(acc.get("[data-slot=accordion-body]").element.tagName).toBe( + "ARTICLE", + ); + }); +}); + +describe("M21–M23 asChild trigger regressions", () => { + it("runs child click exactly once per activation (Disclosure + Accordion)", async () => { + for (const family of ["disclosure", "accordion"] as const) { + const childClick = vi.fn(); + const rootClick = vi.fn(); + const w = mount( + defineComponent({ + components: { + Disclosure, + DisclosureTrigger, + DisclosureContent, + Accordion, + AccordionItem, + AccordionTrigger, + AccordionPanel, + AccordionBody, + Button, + }, + setup: () => ({ childClick, rootClick }), + template: + family === "disclosure" + ? ` + + + + + body + + ` + : ` + + + + + + body + + + `, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(childClick, family).toHaveBeenCalledTimes(1); + expect(rootClick, family).toHaveBeenCalledTimes(1); + w.unmount(); + } + }); + + it("does not run child click.capture when disabled", async () => { + const capture = vi.fn(); + const click = vi.fn(); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ capture, click }), + template: ` + + + open + + body + + `, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(capture).not.toHaveBeenCalled(); + expect(click).not.toHaveBeenCalled(); + expect( + w + .get("[data-slot=disclosure-trigger], [data-testid=btn]") + .attributes("aria-expanded"), + ).toBe("false"); + }); + + it("keeps the effective button when the slot starts with v-if comments", async () => { + const click = vi.fn(); + const w = mount( + defineComponent({ + components: { + Disclosure, + DisclosureTrigger, + DisclosureContent, + Button, + }, + setup: () => ({ click }), + template: ` + + + hidden + + + body + + `, + }), + ); + const btn = w.find("[data-testid=btn]"); + expect(btn.exists()).toBe(true); + expect(btn.element.tagName).toBe("BUTTON"); + expect(btn.attributes("aria-expanded")).toBe("false"); + await btn.trigger("click"); + expect(click).toHaveBeenCalledTimes(1); + expect(btn.attributes("aria-expanded")).toBe("true"); + }); +}); + +describe("M21–M23 event adaptation regressions", () => { + it("keeps same-node listeners and expand after child stopPropagation", async () => { + const second = vi.fn(); + const triggerClick = vi.fn(); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ second, triggerClick }), + render() { + return h("div", [ + h( + Disclosure, + {}, + { + default: () => [ + h( + DisclosureTrigger, + { + asChild: true, + onClick: triggerClick, + }, + { + default: () => + h( + "button", + { + "data-testid": "btn", + type: "button", + onClick: [ + (e: MouseEvent) => e.stopPropagation(), + second, + ], + }, + "open", + ), + }, + ), + h(DisclosureContent, {}, { default: () => "body" }), + ], + }, + ), + ]); + }, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(second).toHaveBeenCalledTimes(1); + expect(triggerClick).toHaveBeenCalledTimes(1); + expect(w.get("[data-testid=btn]").attributes("aria-expanded")).toBe("true"); + }); + + it("stopImmediatePropagation skips later listeners and expand", async () => { + const second = vi.fn(); + const triggerClick = vi.fn(); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ second, triggerClick }), + render() { + return h( + Disclosure, + {}, + { + default: () => [ + h( + DisclosureTrigger, + { asChild: true, onClick: triggerClick }, + { + default: () => + h( + "button", + { + "data-testid": "btn", + type: "button", + onClick: [ + (e: MouseEvent) => e.stopImmediatePropagation(), + second, + ], + }, + "open", + ), + }, + ), + h(DisclosureContent, {}, { default: () => "body" }), + ], + }, + ); + }, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(second).not.toHaveBeenCalled(); + expect(triggerClick).not.toHaveBeenCalled(); + expect(w.get("[data-testid=btn]").attributes("aria-expanded")).toBe( + "false", + ); + }); + + it("preventDefault cancels expand but still runs same-node listeners", async () => { + const second = vi.fn(); + const triggerClick = vi.fn(); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ second, triggerClick }), + render() { + return h( + Disclosure, + {}, + { + default: () => [ + h( + DisclosureTrigger, + { asChild: true, onClick: triggerClick }, + { + default: () => + h( + "button", + { + "data-testid": "btn", + type: "button", + onClick: [ + (e: MouseEvent) => e.preventDefault(), + second, + ], + }, + "open", + ), + }, + ), + h(DisclosureContent, {}, { default: () => "body" }), + ], + }, + ); + }, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(second).toHaveBeenCalledTimes(1); + expect(triggerClick).toHaveBeenCalledTimes(1); + expect(w.get("[data-testid=btn]").attributes("aria-expanded")).toBe( + "false", + ); + }); + + it("runs Trigger @click.capture with asChild alongside child capture", async () => { + const triggerCapture = vi.fn(); + const childCapture = vi.fn(); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ triggerCapture, childCapture }), + render() { + return h( + Disclosure, + {}, + { + default: () => [ + h( + DisclosureTrigger, + { + asChild: true, + onClickCapture: triggerCapture, + }, + { + default: () => + h( + "button", + { + "data-testid": "btn", + type: "button", + onClickCapture: childCapture, + }, + "open", + ), + }, + ), + h(DisclosureContent, {}, { default: () => "body" }), + ], + }, + ); + }, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(triggerCapture).toHaveBeenCalledTimes(1); + expect(childCapture).toHaveBeenCalledTimes(1); + expect(w.get("[data-testid=btn]").attributes("aria-expanded")).toBe("true"); + }); + + it("disabled asChild blocks Trigger and child capture listeners", async () => { + const triggerCapture = vi.fn(); + const childCapture = vi.fn(); + const w = mount( + defineComponent({ + components: { Disclosure, DisclosureTrigger, DisclosureContent }, + setup: () => ({ triggerCapture, childCapture }), + render() { + return h( + Disclosure, + { isDisabled: true }, + { + default: () => [ + h( + DisclosureTrigger, + { asChild: true, onClickCapture: triggerCapture }, + { + default: () => + h( + "button", + { + "data-testid": "btn", + type: "button", + onClickCapture: childCapture, + }, + "open", + ), + }, + ), + h(DisclosureContent, {}, { default: () => "body" }), + ], + }, + ); + }, + }), + ); + await w.get("[data-testid=btn]").trigger("click"); + expect(triggerCapture).not.toHaveBeenCalled(); + expect(childCapture).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/ssr.test.ts b/tests/ssr.test.ts index da7f2f9..e5809f3 100644 --- a/tests/ssr.test.ts +++ b/tests/ssr.test.ts @@ -295,3 +295,54 @@ it("renders progress and meter indicators without browser globals", async () => expect(html).toMatch(new RegExp(`id="${id}"[^>]*data-slot="label"`)); } }); + +it("renders disclosure group and accordion without browser globals", async () => { + const { + Accordion, + AccordionBody, + AccordionHeading, + AccordionIndicator, + AccordionItem, + AccordionPanel, + AccordionTrigger, + Disclosure, + DisclosureContent, + DisclosureGroup, + DisclosureHeading, + DisclosureTrigger, + } = await import("../packages/vue/src"); + const html = await renderToString( + createSSRApp({ + render: () => + h("div", {}, [ + h(DisclosureGroup, { defaultExpandedKeys: ["a"] }, () => [ + h(Disclosure, { id: "a" }, () => [ + h(DisclosureHeading, {}, () => + h(DisclosureTrigger, {}, () => "标题A"), + ), + h(DisclosureContent, {}, () => "内容A"), + ]), + ]), + h(Accordion, { defaultExpandedKeys: ["x"] }, () => [ + h(AccordionItem, { id: "x" }, () => [ + h(AccordionHeading, {}, () => + h(AccordionTrigger, {}, () => "手风琴"), + ), + h(AccordionPanel, {}, () => h(AccordionBody, {}, () => "正文")), + ]), + ]), + ]), + }), + ); + expect(html).toContain('data-slot="disclosure-group"'); + expect(html).toContain('aria-expanded="true"'); + expect(html).toContain('data-slot="accordion-item"'); + expect(html).toContain("正文"); + const controls = [...html.matchAll(/aria-controls="([^"]+)"/g)].map( + (m) => m[1], + ); + expect(controls.length).toBeGreaterThan(0); + for (const id of controls) { + expect(html).toContain(`id="${id}"`); + } +});