fix: align Dropdown/Menu with the HeroUI baseline after fidelity audit

- menu-item.css keys disabled styling off the presence attribute Reka emits.
- Dropdown surfaces drive the ported enter/exit animations and use data-side
  for placement-specific motion.
- One role=menu per popup; items render their key as DOM id; submenu surfaces
  point aria-labelledby at the real trigger; MenuSection names its group from a
  nested Header.
- Custom (asChild) triggers stay keyboard focusable; library Button/Avatar keep
  their own layout instead of the custom-trigger rules.
- Items emit data-focused/data-hovered/data-pressed, expose the upstream render
  props to slots, and merge caller classes through tailwind-variants.
- Submenu triggers declare hasSubmenu explicitly and forward class/ARIA; the
  default submenu indicator uses the baseline chevron artwork.
- Demos restore Kbd slot="keyboard" (27x), IconSquarePlus, and remove the added
  comment, stray space and duplicated indicator SVGs.
- Document the page after the official structure and API tables, including
  renamed props, Vue extensions and remaining gaps.
This commit is contained in:
maoyingjie
2026-10-24 22:14:10 +08:00
parent 64aaf5e53f
commit 043a5418f3
27 changed files with 1124 additions and 254 deletions
+226 -76
View File
@@ -5,7 +5,7 @@ component: dropdown
group: 组件
---
> 基于固定 HeroUI 3.2.6(ce90ea3)迁移。命名组件、作用域插槽与 DOM attrs 为 Vue 适配;预览、复制与高亮来自同一份 SFC。
> 基于固定 HeroUI 3.2.6(`ce90ea3`)迁移:React 对象部件改为具名导出,`Selection`/`Set` 改为 `MenuKey[]`,回调改为 Vue 事件;预览、复制与高亮来自同一份 SFC。
## 用法
@@ -13,11 +13,12 @@ group: 组件
<script setup lang="ts">
import {
DropdownRoot,
DropdownTrigger,
DropdownPopover,
DropdownMenu,
DropdownItem,
Label,
Button,
Label,
} from "@heroui-vue/components";
</script>
```
@@ -27,16 +28,59 @@ import {
## 组件结构
```vue
<DropdownRoot>
<Button variant="secondary" aria-label="菜单">操作</Button>
<DropdownPopover>
<DropdownMenu>
<DropdownItem id="new-file" text-value="新建文件">
<Label>新建文件</Label>
</DropdownItem>
</DropdownMenu>
</DropdownPopover>
</DropdownRoot>
<script setup lang="ts">
import {
Button,
Description,
DropdownItem,
DropdownItemIndicator,
DropdownMenu,
DropdownPopover,
DropdownRoot,
DropdownSection,
DropdownSubmenuIndicator,
DropdownSubmenuTrigger,
DropdownTrigger,
Header,
Kbd,
Label,
Separator,
} from "@heroui-vue/components";
</script>
<template>
<DropdownRoot>
<DropdownTrigger>
<Button />
</DropdownTrigger>
<DropdownPopover>
<DropdownMenu>
<DropdownItem>
<Label />
<Description />
<Kbd slot="keyboard" />
<DropdownItemIndicator />
</DropdownItem>
<Separator />
<DropdownSection>
<Header />
<DropdownItem />
</DropdownSection>
<DropdownSubmenuTrigger>
<DropdownItem>
<Label />
<DropdownSubmenuIndicator />
</DropdownItem>
<DropdownPopover>
<DropdownMenu>
<DropdownItem />
</DropdownMenu>
</DropdownPopover>
</DropdownSubmenuTrigger>
</DropdownMenu>
</DropdownPopover>
</DropdownRoot>
</template>
```
## 示例
@@ -109,15 +153,24 @@ import {
### 全局 CSS
若要自定义组件类,可使用 `@layer components` 指令。
可使用 `@layer components` 指令自定义 Dropdown 组件类。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。
```css
@layer components {
.hv-dropdown {
@apply flex flex-col gap-1;
}
.hv-dropdown__trigger {
@apply outline-none;
}
.hv-dropdown__popover {
@apply rounded-2xl bg-overlay shadow-lg;
@apply rounded-3xl border border-border bg-overlay p-2;
}
.hv-dropdown__menu {
@apply flex flex-col gap-1;
}
}
```
@@ -128,91 +181,146 @@ HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态
### CSS 类
Dropdown 组件使用以下 CSS 类(类名统一加 `hv-` 前缀):
#### 基础类
- `.hv-dropdown` — 根容器
- `.hv-dropdown__trigger` — 触发器
- `.hv-dropdown__popover` — 浮层
- `.hv-dropdown__menu` — 菜单容器
- `.hv-dropdown` — Dropdown 根容器(Vue 端渲染的包裹元素)
- `.hv-dropdown__trigger` — 触发 Dropdown 的按钮或元素
- `.hv-dropdown__popover` — Popover 容器
- `.hv-dropdown__menu` — Popover 内的菜单容器
#### 菜单组件类
#### 状态类
- `.hv-menu` — 菜单列表
- `.hv-menu-item` — 菜单项
- `.hv-menu-item__indicator` — 选中指示器
- `.hv-menu-item__indicator--submenu` — 子菜单指示器
- `.hv-menu-item--default` / `.hv-menu-item--danger` — 变体
- `.hv-menu-section` — 分组
- `.hv-dropdown__trigger[data-focus-visible="true"]` — 触发器聚焦状态
- `.hv-dropdown__trigger[data-disabled="true"]` — 触发器禁用状态
- `.hv-dropdown__trigger[data-pressed="true"]` — 触发器按下状态
- `.hv-dropdown__popover[data-entering="true"]` — 进入动画状态
- `.hv-dropdown__popover[data-exiting="true"]` — 退出动画状态
- `.hv-dropdown__popover[data-side="top|bottom|left|right"]` — 定位方向(进入动画的位移方向)
- `.hv-dropdown__menu[data-selection-mode="single"]` — 单选模式
- `.hv-dropdown__menu[data-selection-mode="multiple"]` — 多选模式
### 菜单组件类
Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类名也可用于自定义:
#### 菜单类
- `.hv-menu` — 菜单容器
- `[data-slot="separator"]` — 菜单内的分隔线元素
#### 菜单项类
- `.hv-menu-item` — 菜单项容器
- `.hv-menu-item__indicator` — 选中指示器(对勾或圆点)
- `[data-slot="menu-item-indicator--checkmark"]` — 对勾指示器 SVG
- `[data-slot="menu-item-indicator--dot"]` — 圆点指示器 SVG
- `.hv-menu-item__indicator--submenu` — 子菜单指示器(箭头)
- `.hv-menu-item--default` — 默认样式变体
- `.hv-menu-item--danger` — 危险样式变体
#### 菜单项状态类
- `.hv-menu-item[data-focus-visible="true"]` — 聚焦状态(键盘焦点)
- `.hv-menu-item[data-focused]` — 聚焦状态
- `.hv-menu-item[data-pressed]` — 按下状态
- `.hv-menu-item[data-hovered]` — 悬停状态
- `.hv-menu-item[data-selected="true"]` — 选中状态
- `.hv-menu-item[data-disabled]` — 禁用状态(存在即禁用)
- `.hv-menu-item[data-has-submenu="true"]` — 带子菜单的项
- `.hv-menu-item[data-selection-mode="single"]` — 单选模式
- `.hv-menu-item[data-selection-mode="multiple"]` — 多选模式
- `.hv-menu-item[aria-checked="true"]` — 已勾选(ARIA)
#### 菜单分区类
- `.hv-menu-section` — 菜单分区容器
### 交互状态
- **悬停**:`:hover` 或 `[data-hovered="true"]`
- **聚焦**:`:focus-visible` 或 `[data-focus-visible="true"]`
- **按下**:`[data-pressed="true"]`
- **选中**:`[aria-checked="true"]` / `[data-selected="true"]`
- **禁用**:`[data-disabled="true"]`
- **进入/退出**:`[data-entering]` / `[data-exiting]`
- **放置**:`[data-placement="*"]`
组件同时支持 CSS 伪类与 data 属性:
- **Hover**:触发器与菜单项上 `:hover` 或 `[data-hovered]`
- **Focus**:触发器与菜单项上 `:focus-visible` 或 `[data-focus-visible="true"]`;菜单项另有 `[data-focused]`
- **Disabled**:触发器上 `:disabled`/`[aria-disabled="true"]`,菜单项上 `[data-disabled]`
- **Pressed**:菜单项与触发器上 `:active` 或 `[data-pressed]`
- **Selected**:菜单项上 `[data-selected="true"]` 或 `[aria-checked="true"]`
- **Open/Close**:`DropdownPopover` 上 `[data-state="open"]`;进入/退出期间另有 `[data-entering="true"]` / `[data-exiting="true"]`
## API 参考
所有部件接受 `class`、`style`、ARIA 与原生事件。选择集合使用 Vue 数组模型(`MenuKey[]`),不使用 React `Set`/`Selection`。
所有部件接受 `class`、`style`、ARIA 与原生事件(`DropdownSubmenuTrigger` 会把它们合并到它的条目元素上)。选择集合使用 Vue 数组模型(`MenuKey[]`),不使用 React `Set`/`Selection`。标记「Vue 扩展」的属性在官方 HeroUI 中没有对应项。
### DropdownRoot
| Prop | 类型 | 默认值 | 描述 |
| ------------------- | ------------------------ | --------- | ------------------------------- |
| `open` | `boolean` | — | 受控展开 |
| `defaultOpen` | `boolean` | — | 非受控初始展开 |
| `modal` | `boolean` | `true` | 模态焦点管理 |
| `dir` | `'ltr' \| 'rtl'` | — | 文本方向 |
| `trigger` | `'press' \| 'longPress'` | `'press'` | 长按打开并抑制随后 click |
| `longPressDuration` | `number` | `500` | 长按时长 ms;移动超过 10px 取消 |
| `update:open` | 事件 | — | 展开变更 |
| Prop | 类型 | 默认值 | 描述 |
| ------------------- | ------------------------ | --------- | --------------------------------------------- |
| `open` | `boolean` | — | 设置菜单展开状态(受控)。官方名 `isOpen` |
| `defaultOpen` | `boolean` | — | 设置菜单默认展开状态(非受控)。 |
| `trigger` | `'press' \| 'longPress'` | `'press'` | 触发菜单的交互类型。 |
| `update:open` | 事件 `(open: boolean)` | — | 展开状态变化时触发。官方名 `onOpenChange` |
| `modal` | `boolean` | `true` | **Vue 扩展**:模态焦点管理 |
| `dir` | `'ltr' \| 'rtl'` | — | **Vue 扩展**:文本方向 |
| `longPressDuration` | `number` | `500` | **Vue 扩展**:长按时长 ms;移动超过 10px 取消 |
长按模式下 Enter/Space 仍可键盘打开;`pointerup`/`pointercancel`/`pointerleave`/卸载会清理计时。
### DropdownTrigger
| Prop | 类型 | 默认值 | 描述 |
| --------- | --------- | ------ | ---------------------- |
| `asChild` | `boolean` | `true` | 将触发合并到唯一子节点 |
| Prop | 类型 | 默认值 | 描述 |
| --------- | --------- | ------ | ---------------------------------- |
| `asChild` | `boolean` | `true` | 将触发合并到唯一子节点(默认行为) |
| `as` | `string` | — | 自定义触发元素标签 |
页面里的 `Button` props 写在内部的 `Button` 上。子节点若不是原生可聚焦元素(例如 Avatar),组件会补 `role="button"` 与 `tabindex="0"`,保持官方「触发器可键盘操作」的行为。
### DropdownPopover
| Prop | 类型 | 默认值 | 描述 |
| ----------------- | --------- | ------ | ---------------- |
| `side` / `align` | `string` | — | 相对触发器的位置 |
| `sideOffset` | `number` | — | 侧边偏移 |
| `avoidCollisions` | `boolean` | — | 碰撞翻转 |
| `loop` | `boolean` | — | 焦点循环 |
| Prop | 类型 | 默认值 | 描述 |
| ------------------ | --------- | ------ | ------------------------------------- |
| `side` / `align` | `string` | — | 相对触发器的位置。官方用 `placement` |
| `sideOffset` | `number` | — | 侧边偏移。官方名 `offset` |
| `alignOffset` | `number` | — | 交叉轴偏移。官方名 `crossOffset` |
| `avoidCollisions` | `boolean` | — | 碰撞翻转。官方名 `shouldFlip` |
| `collisionPadding` | `number` | — | 边界内边距。官方名 `containerPadding` |
| `loop` | `boolean` | — | **Vue 扩展**:焦点循环 |
### DropdownMenu
| Prop | 类型 | 默认值 | 描述 |
| ----------------------------------------- | ---------------------------------- | -------- | ----------- |
| `selectionMode` | `'none' \| 'single' \| 'multiple'` | `'none'` | 选择模式 |
| `selectedKeys` / `defaultSelectedKeys` | `MenuKey[]` | — / `[]` | 受控 / 初始 |
| `disabledKeys` | `MenuKey[]` | `[]` | 禁用项 |
| `update:selectedKeys` / `selectionChange` | 事件 | — | 选择变更 |
| `action` | 事件 `(key: MenuKey)` | — | 动作项激活 |
| Prop | 类型 | 默认值 | 描述 |
| ----------------------------------------- | ---------------------------------- | -------- | ------------------------------------------ |
| `selectionMode` | `'none' \| 'single' \| 'multiple'` | `'none'` | 是否启用单选、多选或不启用选择。 |
| `selectedKeys` | `MenuKey[]` | — | 当前选中的 key(受控)。 |
| `defaultSelectedKeys` | `MenuKey[]` | `[]` | 初始选中的 key(非受控)。 |
| `disabledKeys` | `MenuKey[]` | `[]` | 禁用项的 key。 |
| `update:selectedKeys` / `selectionChange` | 事件 `(keys: MenuKey[])` | — | 选中变化时触发。官方名 `onSelectionChange` |
| `action` | 事件 `(key: MenuKey)` | — | 激活菜单项时触发。官方名 `onAction` |
### DropdownSection
与 `DropdownMenu` 相同的选择 Props,可在分组内独立拥有 `selectionMode` / `selectedKeys`。
| Prop | 类型 | 默认值 | 描述 |
| ----------------------------------------- | ------------------------ | ------ | ------------------------------------------ |
| `selectionMode` | `'single' \| 'multiple'` | — | 该分组内菜单项的选择模式;省略则继承菜单。 |
| `selectedKeys` | `MenuKey[]` | — | 当前选中的 key(受控)。 |
| `defaultSelectedKeys` | `MenuKey[]` | `[]` | 初始选中的 key(非受控)。 |
| `disabledKeys` | `MenuKey[]` | `[]` | 禁用项的 key。 |
| `update:selectedKeys` / `selectionChange` | 事件 `(keys: MenuKey[])` | — | 选中变化时触发。官方名 `onSelectionChange` |
分组内嵌套的 `Header` 会自动成为分组的可访问名称来源(`aria-labelledby`)。
### DropdownItem
| Prop | 类型 | 默认值 | 描述 |
| --------------- | ----------------------- | ----------- | ---------------------------- |
| `id` | `MenuKey` | — | 条目标识 |
| `textValue` | `string` | — | 首字母导航文本 |
| `variant` | `'default' \| 'danger'` | `'default'` | 视觉变体 |
| `isDisabled` | `boolean` | `false` | 禁用 |
| `closeOnSelect` | `boolean` | — | `false` 时动作后保持菜单打开 |
| `select` | 事件 `(key: MenuKey)` | — | 激活回调 |
| Prop | 类型 | 默认值 | 描述 |
| --------------- | ----------------------- | ----------- | ---------------------------------------------------------------- |
| `id` | `MenuKey` | — | 菜单项唯一标识,同时作为元素 `id`。 |
| `textValue` | `string` | — | 用于首字母导航的文本内容。 |
| `variant` | `'default' \| 'danger'` | `'default'` | 菜单项视觉变体。 |
| `isDisabled` | `boolean` | `false` | 禁用该项。 |
| `closeOnSelect` | `boolean` | — | `false` 时动作项激活后保持菜单打开。官方名 `shouldCloseOnSelect` |
| `select` | 事件 `(key: MenuKey)` | — | **Vue 扩展**:条目激活回调 |
**事件取消**:条目上 `@click.prevent`(或 `preventDefault`)会取消默认动作、选择变更与关闭。选择项输出 `menuitemradio`/`menuitemcheckbox` 并带 `aria-checked`;`selectionMode=none` 为 `menuitem`。
默认插槽会收到 `{ isSelected, isFocused, isDisabled, isPressed }`,对应官方的 Render Props。
### DropdownItemIndicator
@@ -220,24 +328,66 @@ HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态
| ------ | ---------------------- | ------------- | ---------- |
| `type` | `'checkmark' \| 'dot'` | `'checkmark'` | 指示器类型 |
### DropdownSubmenuIndicator / DropdownSubmenuTrigger
默认插槽会收到 `{ isSelected, isIndeterminate, isFocused, isDisabled, isPressed }`(菜单项没有不确定态,`isIndeterminate` 恒为 `false`):
子菜单指示器默认 chevron-right;`DropdownSubmenuTrigger` 包裹条目与嵌套 `DropdownPopover`,每层子菜单独立 open 状态。
```vue
<DropdownItemIndicator v-slot="{ isSelected }">
<MyCheckIcon v-if="isSelected" />
</DropdownItemIndicator>
```
### DropdownSubmenuIndicator
| 内容 | 说明 |
| ---- | ---------------------------------------- |
| 默认 | 官方内置的 chevron-right 图标 |
| 插槽 | 自定义指示器内容;只有带子菜单的项才渲染 |
### DropdownSubmenuTrigger
| Slots / Props | 说明 |
| ------------- | -------------------------------------------------- |
| 默认插槽 | 第一个子节点是触发条目,其余子节点渲染进子菜单内容 |
| `class`/ARIA | 合并到触发条目元素上 |
每层子菜单独立持有 open 状态;焦点在子菜单内按 Esc 只关闭当前层,焦点回到该层触发器。
### Render Props
在 `DropdownItem` 中使用作用域插槽时,会收到以下值:
| Prop | 类型 | 描述 |
| ------------ | --------- | ---------------------- |
| `isSelected` | `boolean` | 该项是否选中。 |
| `isFocused` | `boolean` | 该项是否聚焦。 |
| `isDisabled` | `boolean` | 该项是否禁用。 |
| `isPressed` | `boolean` | 该项是否处于按下状态。 |
## 无障碍
菜单使用 `role="menu"` / `menuitem`。上下键与首尾导航、Enter/Space 激活、Esc 关闭并恢复触发器焦点。禁用项跳过;隐藏/退出条目不进入 Tab 顺序。
Dropdown 组件实现 ARIA 菜单模式,并提供:
- 完整键盘导航(方向键、Home/End、首字母导航)
- 屏幕阅读器对操作与选中变化的播报
- 合理的焦点管理(关闭后焦点回到触发器)
- 禁用态支持
- 长按交互支持
- 子菜单导航,Esc 逐层关闭
菜单使用 `role="menu"` / `menuitem`(选择项为 `menuitemradio` / `menuitemcheckbox`);禁用项跳过,不进入 Tab 顺序。
## 上游差异
- React 对象部件改具名导出;`Selection`/`Set` 改 `MenuKey[]`;`onAction`/`onSelectionChange` 改 Vue 事件。
- 条目 `onClick` `preventDefault` 取消动作/选择/关闭(对应上游可取消事件契约)。
- 长按封装在 `DropdownRoot` `trigger="longPress"`;Menu/Item/Section 导出含 `*Props` 类型。
- `Kbd slot="keyboard"` 为上游原生 slot 透传;本库 Kbd 支持同结构。
- 部件导出为具名组件(`DropdownRoot` / `DropdownTrigger` / …),触发器需要显式包裹,官方是把 `Button` 直接放在 `Dropdown` 下。
- `Selection`/`Set` 改为 `MenuKey[]`;`onAction`/`onSelectionChange` 改为 Vue 事件;`isOpen`/`onOpenChange` 改为 `open` + `v-model:open`。
- `placement` 改为 `side`/`align`(Reka 定位模型),`offset`/`crossOffset`/`shouldFlip`/`containerPadding` 分别改为 `sideOffset`/`alignOffset`/`avoidCollisions`/`collisionPadding`。
- 官方支持的链接型菜单项(`href`/`target`)未实现:底层 Reka 菜单项没有锚点路径。
- 子菜单悬停展开延迟由底层固定为 100ms,未暴露官方 `delay`(默认 200ms)。
- `DropdownRoot` 额外渲染一层 `.hv-dropdown` 包裹元素(官方该类没有 DOM 宿主),用于承载根级 class 与方向。
- 条目 `onClick` 中 `preventDefault()` 会取消动作、选择与关闭;`stopImmediatePropagation()` 会终止后续处理器,均为原生事件语义。
## 相关组件
- [Button 按钮](./button)
- [Popover 弹出层](./popover)
- [ListBox 列表框](./list-box)
- [Separator 分隔线](./separator)
@@ -11,7 +11,6 @@ import {
</script>
<template>
<!-- trigger="longPress": press-and-hold opens; click is suppressed. -->
<DropdownRoot trigger="longPress">
<DropdownTrigger>
<Button aria-label="菜单" variant="secondary">长按</Button>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref } from "vue";
import { defineComponent, h, ref } from "vue";
import {
DropdownRoot,
DropdownTrigger,
@@ -15,6 +15,30 @@ import {
import type { MenuKey } from "@heroui-vue/components";
const selected = ref<MenuKey[]>(["apple"]);
// 官方示例用一个自定义图标常量复用给每个条目;Vue 端用同名组件保持单一来源。
const CustomCheckmarkIcon = defineComponent({
name: "CustomCheckmarkIcon",
setup: () => () =>
h(
"svg",
{
height: "16",
viewBox: "0 0 16 16",
width: "16",
xmlns: "http://www.w3.org/2000/svg",
},
[
h("path", {
class: "text-accent",
"clip-rule": "evenodd",
d: "M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m3.1-8.55a.75.75 0 1 0-1.2-.9L7.419 8.858L6.03 7.47a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.13-.08z",
fill: "currentColor",
"fill-rule": "evenodd",
}),
],
),
});
</script>
<template>
<DropdownRoot>
@@ -31,102 +55,32 @@ const selected = ref<MenuKey[]>(["apple"]);
<Header>选择水果</Header>
<DropdownItem id="apple" text-value="苹果">
<DropdownItemIndicator v-slot="{ isSelected }">
<svg
v-if="isSelected"
height="16"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
>
<path
class="text-accent"
clip-rule="evenodd"
d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m3.1-8.55a.75.75 0 1 0-1.2-.9L7.419 8.858L6.03 7.47a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.13-.08z"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
<CustomCheckmarkIcon v-if="isSelected" />
</DropdownItemIndicator>
<Label>苹果</Label>
</DropdownItem>
<DropdownItem id="banana" text-value="香蕉">
<DropdownItemIndicator v-slot="{ isSelected }">
<svg
v-if="isSelected"
height="16"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
>
<path
class="text-accent"
clip-rule="evenodd"
d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m3.1-8.55a.75.75 0 1 0-1.2-.9L7.419 8.858L6.03 7.47a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.13-.08z"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
<CustomCheckmarkIcon v-if="isSelected" />
</DropdownItemIndicator>
<Label>香蕉</Label>
</DropdownItem>
<DropdownItem id="cherry" text-value="樱桃">
<DropdownItemIndicator v-slot="{ isSelected }">
<svg
v-if="isSelected"
height="16"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
>
<path
class="text-accent"
clip-rule="evenodd"
d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m3.1-8.55a.75.75 0 1 0-1.2-.9L7.419 8.858L6.03 7.47a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.13-.08z"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
<CustomCheckmarkIcon v-if="isSelected" />
</DropdownItemIndicator>
<Label>樱桃</Label>
</DropdownItem>
</DropdownSection>
<DropdownItem id="orange" text-value="橙子">
<DropdownItemIndicator v-slot="{ isSelected }">
<svg
v-if="isSelected"
height="16"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
>
<path
class="text-accent"
clip-rule="evenodd"
d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m3.1-8.55a.75.75 0 1 0-1.2-.9L7.419 8.858L6.03 7.47a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.13-.08z"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
<CustomCheckmarkIcon v-if="isSelected" />
</DropdownItemIndicator>
<Label>橙子</Label>
</DropdownItem>
<DropdownItem id="pear" text-value="梨">
<DropdownItemIndicator v-slot="{ isSelected }">
<svg
v-if="isSelected"
height="16"
viewBox="0 0 16 16"
width="16"
xmlns="http://www.w3.org/2000/svg"
>
<path
class="text-accent"
clip-rule="evenodd"
d="M8 15A7 7 0 1 0 8 1a7 7 0 0 0 0 14m3.1-8.55a.75.75 0 1 0-1.2-.9L7.419 8.858L6.03 7.47a.75.75 0 0 0-1.06 1.06l2 2a.75.75 0 0 0 1.13-.08z"
fill="currentColor"
fill-rule="evenodd"
/>
</svg>
<CustomCheckmarkIcon v-if="isSelected" />
</DropdownItemIndicator>
<Label>梨</Label>
</DropdownItem>
@@ -2,7 +2,7 @@
import {
IconDeviceFloppy,
IconFolderOpen,
IconPlus,
IconSquarePlus,
IconTrash,
} from "@tabler/icons-vue";
import {
@@ -32,13 +32,13 @@ function onAction(key: string | number) {
<DropdownMenu @action="onAction">
<DropdownItem id="new-file" text-value="新建文件">
<div class="flex h-8 items-start justify-center pt-px">
<IconPlus class="size-4 shrink-0 text-muted" />
<IconSquarePlus class="size-4 shrink-0 text-muted" />
</div>
<div class="flex flex-col">
<Label>新建文件</Label>
<Description>创建新文件</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>N</KbdContent>
</Kbd>
@@ -51,7 +51,7 @@ function onAction(key: string | number) {
<Label>打开文件</Label>
<Description>打开已有文件</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>O</KbdContent>
</Kbd>
@@ -64,7 +64,7 @@ function onAction(key: string | number) {
<Label>保存文件</Label>
<Description>保存当前文件</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>S</KbdContent>
</Kbd>
@@ -77,7 +77,7 @@ function onAction(key: string | number) {
<Label>删除文件</Label>
<Description>移至废纸篓</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdAbbr key-value="shift" />
<KbdContent>D</KbdContent>
@@ -1,5 +1,10 @@
<script setup lang="ts">
import { IconMenu2, IconPencil, IconPlus, IconTrash } from "@tabler/icons-vue";
import {
IconMenu2,
IconPencil,
IconSquarePlus,
IconTrash,
} from "@tabler/icons-vue";
import {
DropdownRoot,
DropdownTrigger,
@@ -34,13 +39,13 @@ function onAction(key: string | number) {
<Header>操作</Header>
<DropdownItem id="new-file" text-value="新建文件">
<div class="flex h-8 items-start justify-center pt-px">
<IconPlus class="size-4 shrink-0 text-muted" />
<IconSquarePlus class="size-4 shrink-0 text-muted" />
</div>
<div class="flex flex-col">
<Label>新建文件</Label>
<Description>创建新文件</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>N</KbdContent>
</Kbd>
@@ -53,7 +58,7 @@ function onAction(key: string | number) {
<Label>编辑文件</Label>
<Description>进行修改</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>E</KbdContent>
</Kbd>
@@ -70,7 +75,7 @@ function onAction(key: string | number) {
<Label>删除文件</Label>
<Description>移至废纸篓</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdAbbr key-value="shift" />
<KbdContent>D</KbdContent>
+6 -6
View File
@@ -2,7 +2,7 @@
import {
IconDeviceFloppy,
IconFolderOpen,
IconPlus,
IconSquarePlus,
IconTrash,
} from "@tabler/icons-vue";
import {
@@ -30,9 +30,9 @@ function onAction(key: string | number) {
<DropdownPopover>
<DropdownMenu @action="onAction">
<DropdownItem id="new-file" text-value="新建文件">
<IconPlus class="size-4 shrink-0 text-muted" />
<IconSquarePlus class="size-4 shrink-0 text-muted" />
<Label>新建文件</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>N</KbdContent>
</Kbd>
@@ -40,7 +40,7 @@ function onAction(key: string | number) {
<DropdownItem id="open-file" text-value="打开文件">
<IconFolderOpen class="size-4 shrink-0 text-muted" />
<Label>打开文件</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>O</KbdContent>
</Kbd>
@@ -48,7 +48,7 @@ function onAction(key: string | number) {
<DropdownItem id="save-file" text-value="保存文件">
<IconDeviceFloppy class="size-4 shrink-0 text-muted" />
<Label>保存文件</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>S</KbdContent>
</Kbd>
@@ -56,7 +56,7 @@ function onAction(key: string | number) {
<DropdownItem id="delete-file" text-value="删除文件" variant="danger">
<IconTrash class="size-4 shrink-0 text-danger" />
<Label>删除文件</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdAbbr key-value="shift" />
<KbdContent>D</KbdContent>
@@ -25,28 +25,28 @@ function onAction(key: string | number) {
<DropdownMenu @action="onAction">
<DropdownItem id="new" text-value="新建">
<Label>新建</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>N</KbdContent>
</Kbd>
</DropdownItem>
<DropdownItem id="open" text-value="打开">
<Label>打开</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>O</KbdContent>
</Kbd>
</DropdownItem>
<DropdownItem id="save" text-value="保存">
<Label>保存</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>S</KbdContent>
</Kbd>
</DropdownItem>
<DropdownItem id="delete" text-value="删除" variant="danger">
<Label>删除</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdAbbr key-value="shift" />
<KbdContent>D</KbdContent>
@@ -32,21 +32,21 @@ const textAlignment = ref<MenuKey[]>(["left"]);
<Header>操作</Header>
<DropdownItem id="cut" text-value="剪切">
<Label>剪切</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>X</KbdContent>
</Kbd>
</DropdownItem>
<DropdownItem id="copy" text-value="复制">
<Label>复制</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>C</KbdContent>
</Kbd>
</DropdownItem>
<DropdownItem id="paste" text-value="粘贴">
<Label>粘贴</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>U</KbdContent>
</Kbd>
@@ -62,7 +62,7 @@ const textAlignment = ref<MenuKey[]>(["left"]);
<DropdownItem id="bold" text-value="粗体">
<DropdownItemIndicator />
<Label>粗体</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>B</KbdContent>
</Kbd>
@@ -70,7 +70,7 @@ const textAlignment = ref<MenuKey[]>(["left"]);
<DropdownItem id="italic" text-value="斜体">
<DropdownItemIndicator />
<Label>斜体</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>I</KbdContent>
</Kbd>
@@ -78,7 +78,7 @@ const textAlignment = ref<MenuKey[]>(["left"]);
<DropdownItem id="underline" text-value="下划线">
<DropdownItemIndicator />
<Label>下划线</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>U</KbdContent>
</Kbd>
@@ -94,7 +94,7 @@ const textAlignment = ref<MenuKey[]>(["left"]);
<DropdownItem id="left" text-value="左对齐">
<DropdownItemIndicator type="dot" />
<Label>左对齐</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="alt" />
<KbdContent>A</KbdContent>
</Kbd>
@@ -102,7 +102,7 @@ const textAlignment = ref<MenuKey[]>(["left"]);
<DropdownItem id="center" text-value="居中">
<DropdownItemIndicator type="dot" />
<Label>居中</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="alt" />
<KbdContent>H</KbdContent>
</Kbd>
@@ -110,7 +110,7 @@ const textAlignment = ref<MenuKey[]>(["left"]);
<DropdownItem id="right" text-value="右对齐">
<DropdownItemIndicator type="dot" />
<Label>右对齐</Label>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="alt" />
<KbdContent>D</KbdContent>
</Kbd>
+5 -5
View File
@@ -2,7 +2,7 @@
import {
IconDotsVertical,
IconPencil,
IconPlus,
IconSquarePlus,
IconTrash,
} from "@tabler/icons-vue";
import {
@@ -39,13 +39,13 @@ function onAction(key: string | number) {
<Header>操作</Header>
<DropdownItem id="new-file" text-value="新建文件">
<div class="flex h-8 items-start justify-center pt-px">
<IconPlus class="size-4 shrink-0 text-muted" />
<IconSquarePlus class="size-4 shrink-0 text-muted" />
</div>
<div class="flex flex-col">
<Label>新建文件</Label>
<Description>创建新文件</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>N</KbdContent>
</Kbd>
@@ -58,7 +58,7 @@ function onAction(key: string | number) {
<Label>编辑文件</Label>
<Description>进行修改</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdContent>E</KbdContent>
</Kbd>
@@ -75,7 +75,7 @@ function onAction(key: string | number) {
<Label>删除文件</Label>
<Description>移至废纸篓</Description>
</div>
<Kbd class="ms-auto" variant="light">
<Kbd class="ms-auto" slot="keyboard" variant="light">
<KbdAbbr key-value="command" />
<KbdAbbr key-value="shift" />
<KbdContent>D</KbdContent>
+110
View File
@@ -0,0 +1,110 @@
# B01 忠实度审计:Dropdown / Menu 家族
2026-10-24。基线 HeroUI 3.2.6 / `ce90ea3`(只读 `../heroui`)。对照对象:`apps/docs/components/dropdown.md`、`apps/docs/demos/dropdown-*.vue`、`packages/vue/src/components/{dropdown,menu,menu-item,menu-section}`、`packages/styles/components/{dropdown,menu,menu-item,menu-section}.css`。
对照依据:官方 `apps/docs/content/docs/cn/react/components/(collections)/dropdown.mdx`(380 行)、官方 17 个演示 `apps/docs/src/demos/cn/dropdown/*.tsx`、上游 `packages/react/src/components/{dropdown,menu,menu-item,menu-section}`、`packages/styles/components/*.css`、`components-registry.ts`。DOM 与计算样式结论来自 jsdom 实渲染与浏览器 5181 实测。
状态列:`已修` / `未修(原因)` / `保留(设计选择)`。
## A. 组件实现:不是复刻的地方
| ID | 问题 | 证据 | 状态 |
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- |
| A1 | 禁用项没有禁用样式:移植 CSS 用 `[data-disabled="true"]`,Reka 只写空串 `data-disabled=""`,选择器永不命中,`with-disabled-items` 的删除行不置灰 | `menu-item.css:81`;`reka-ui/Menu/MenuItemImpl.vue:85`;dist 为 `.hv-menu-item[data-disabled=true]`;DOM 实测 `data-disabled=""`;测试 `tests/b01-menu-dropdown.test.ts` 断言放宽故漏检 | 已修 |
| A2 | 进入/退出动画、placement 位移全部失效:CSS 依赖 `[data-entering]`/`[data-exiting]`/`[data-placement]`,Dropdown 链路从不发这些属性 | `dropdown.css:54-84`;DOM 实测只有 `data-state`/`data-side`/`data-align`;适配层只存在于 Popover/Tooltip/Drawer/Toast | 已修 |
| A3 | 每个弹出层出现两层 `role="menu"`(Reka content 本身已是 menu,`Menu` 又给内层加了 role) | `Menu.vue:112`;实测 `querySelectorAll('[role="menu"]').length === 2`;官方只有一个 menu | 已修 |
| A4 | 条目没有 DOM `id`;子菜单 content 的 `aria-labelledby` 指向不存在的节点 | `MenuItem.vue` 只把 `id` 当选择 key;实测条目 `id=null`、子菜单 `aria-labelledby=reka-menu-sub-trigger-v-2` → MISSING | 已修 |
| A5 | 链接型菜单项无法实现:`href` 落到 `div[role=menuitem]`,没有 `<a>` | Reka `MenuItem` 无链接路径;官方 RAC `MenuItem` 支持 `href/target` | 未修(能力缺失) |
| A6 | 自定义触发器变成不可聚焦 `<span>`;官方是 `<button>`,可键盘操作 | 实测 `<span role=null tabindex=null aria-haspopup=menu>`;官方 `Dropdown.Trigger` = RAC `Button` | 已修 |
| A7 | 触发器被加 `hv-dropdown__trigger`,`display:inline-block` 覆盖 Button 的 `inline-flex`,图标触发器偏移 | dist 顺序 36211(`.hv-button`) → 270480(`.hv-dropdown__trigger`);浏览器实测计算 `display:block`、图标中心偏左 12px;Modal/Popover/Tooltip 都有 `.X__trigger.hv-button` 兼容规则,Dropdown 缺 | 已修 |
| A8 | 子菜单能力依赖「是否渲染指示器组件」:不带 `<DropdownSubmenuIndicator>` 的子菜单项被当普通动作项,点击关闭整栈 | `MenuItemSubmenuIndicator.vue:37`;`MenuItem.vue:84` | 已修 |
| A9 | Section 标题与分组没有关联:`div[role=group]` 无 `aria-labelledby`,`Header` 无 id/注册 | `MenuSection.vue:119-129`;`Header.vue` | 已修 |
| A10 | 菜单项没有官方 Render Props(`isSelected/isFocused/isDisabled/isPressed`);指示器只有 `isSelected`,缺 `isIndeterminate` | 官方 `dropdown.mdx:331-363`;`MenuItem.vue` 直接透传 slot;`MenuItemIndicator.vue:62` | 已修 |
| A11 | 不发 `data-focused`/`data-hovered`/`data-pressed`/`data-focus-visible`:`custom-styles` 演示的 `data-[focused=true]` 工具类永不生效,`menu-item.css` 对应分支为死代码 | 官方演示 `custom-styles.tsx:10,17,24`;实测条目无 `data-focused`;Reka 只发 `data-highlighted`,而移植 CSS 没有该选择器 | 已修 |
| A12 | 子菜单项/子菜单 Popover 丢弃 `class`/`aria-*` | `DropdownSubmenuTrigger.vue:42-43`(`inheritAttrs:false` + `useAttrs()` 未使用);`DropdownPopover.vue:51-56` Fragment 分支;实测两者均丢 | 已修 |
| A13 | 用户 class 不经过 twMerge,冲突工具类压不掉基础类 | `Menu.vue:107`、`MenuItem.vue:125`、`MenuSection.vue:124` 用 `join(" ")`;官方走 tailwind-variants | 已修 |
| A14 | 默认子菜单指示器是自绘描边 SVG,官方是 `IconChevronRight`(16 视框实心) | `MenuItemSubmenuIndicator.vue:12-28`;官方 `menu-item.tsx:145` | 已修 |
| A15 | 独立 `Menu` 丢了 `data-slot="menu"`;`data-slot="menu-section"` 又是新增 | 官方 `menu.tsx:26` 用 `data-slot="menu"`;`Menu.vue` 恒为 `dropdown-menu` | 已修 |
| A16 | `MenuSection.as` 声明但渲染不使用(死参数) | `MenuSection.vue:27` vs `:119-129` | 已修 |
| A17 | Section 只传 `selectedKeys` 时自动推断 `multiple`,官方无此推断 | `MenuSection.vue:63-67` | 已修 |
| A18 | 子菜单悬停开启延迟:Reka 固定 100ms,官方 `delay` 默认 200ms 可配 | 官方 `dropdown.mdx:352`;Reka `MenuSubTrigger` 100ms | 未修(底座固定值) |
| A19 | 长按键盘语义自定(Enter/Space 切换),RAC longPress 文档只写 Alt+↓;另加 `longPressDuration`、10px 移动取消等无上游对应项 | `DropdownTrigger.vue:71-76`;官方 `dropdown.mdx:259` 无时长参数 | 保留(复核要求) |
| A20 | `DropdownRoot` 自带一层 `div.hv-dropdown` + `data-trigger`,官方该类在无 DOM 宿主 | `DropdownRoot.vue:58-66`;官方 `dropdown.tsx:39-48` | 保留(结构差异) |
| A21 | 缺失的官方 props:`disallowEmptySelection`、`escapeKeyBehavior`、`shouldFocusWrap`、`autoFocus`、`onClose`、`items`/`renderEmptyState`、`shouldCloseOnSelect`(菜单级)、`isKeyboardDismissDisabled`、`shouldCloseOnInteractOutside`、Popover 全部 render props | 官方 `dropdown.mdx:282-321` 及各部件表 | 未修(公开 prop 缺口) |
## B. 17 个演示与官方源码的差异
| ID | 问题 | 证据 | 状态 |
| --- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| B1 | 每个演示多包一层 `<DropdownTrigger>`(官方是 `Dropdown` 直接子级 `Button`) | 17/17 演示;官方 `dropdown.tsx:39-47` | 保留(既定 API) |
| B2 | `Kbd slot="keyboard"` 全部丢失,共 27 处 | with-icons 4、with-descriptions 4、with-disabled-items 3、with-sections 3、with-keyboard-shortcuts 4、with-section-level-selection 9;Vue 端 0 处 | 已修 |
| B3 | 图标换成了不同概念的图标:`SquarePlus`→`IconPlus`(应 `IconSquarePlus`);`ArrowRightFromSquare`→`IconLogout`;`Persons`→`IconUsers` | 官方 `with-icons.tsx:15` 等;`@tabler/icons-vue` 已导出 `IconSquarePlus` | 部分已修 |
| B4 | `controlled-open-state` 多一个空格:`下拉菜单: 打开` | `dropdown-controlled-open-state.vue:17-20`;官方无空格 | 已修 |
| B5 | `single-with-custom-indicator` 把官方复用一个常量拆成 5 段内联 SVG 复制 | `dropdown-single-with-custom-indicator.vue:33-130`(136 行 vs 官方 71 行) | 已修 |
| B6 | `long-press-trigger` 多了一条官方没有的中文注释(演示即复制源) | `dropdown-long-press-trigger.vue:14` | 已修 |
| B7 | `with-multiple-selection` 用 `MenuKey[]` 取代 `Selection`/`Set`,且无 `"all"` 支持 | 已登记为适配;`Menu.vue:42-45` | 保留(已登记) |
| B8 | `custom-styles` 的 `data-[focused=true]` 死代码(见 A11) | 演示逐字抄官方,状态不发 | 已修 |
## C. 文档页 `apps/docs/components/dropdown.md`
| ID | 问题 | 证据 | 状态 |
| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ---------------- |
| C1 | 组件结构示例不是官方骨架:缺 `DropdownTrigger`(照抄无法展开)、缺 `Separator`/`Section`+`Header`/`SubmenuTrigger`/`SubmenuIndicator`/`Description`/`Kbd slot="keyboard"`/`ItemIndicator` | `dropdown.md:29-40` vs 官方 `dropdown.mdx:23-59` | 已修 |
| C2 | 全局 CSS 示例自造:只给 2 个类、popover 用 `rounded-2xl bg-overlay shadow-lg`,与官方 4 类与实际 CSS 都不符 | `dropdown.md:114-123` vs 官方 `dropdown.mdx:164-182` | 已修 |
| C3 | 样式参考清单缩水并混入未实现状态(`data-entering`/`data-exiting`/`data-placement`/`data-hovered`/`data-pressed`/`data-disabled`),丢了官方分节与源码链接 | `dropdown.md:147-155` | 已修 |
| C4 | API 表不成体系:`DropdownSection` 只有一句话、`SubmenuIndicator`/`SubmenuTrigger` 无表、`ItemIndicator` 缺 render/slot 契约、整节 Render Props 缺失 | `dropdown.md:157-225` vs 官方 `dropdown.mdx:250-364` | 已修 |
| C5 | 改名列未对标:`isOpen`→`open`、`onOpenChange`→`update:open`、`placement`→`side`/`align`、`offset`→`sideOffset`、`crossOffset`→`alignOffset`、`containerPadding`→`collisionPadding`、`shouldFlip`→`avoidCollisions`、`onAction`→`action`、`onSelectionChange`→`selectionChange`、`shouldCloseOnSelect`→`closeOnSelect` | `dropdown.md:161-225` | 已修 |
| C6 | 自造项未标为扩展:`longPressDuration`、`closeOnSelect`、`modal`、`dir`、`loop`、Item 的 `isDisabled`、`select` 事件、`data-trigger`/`dropdown-root`/`dropdown-trigger-region`/`data-submenu-content` | `dropdown.md:163-213` | 已修 |
| C7 | 无障碍段改写,丢掉官方 5 条(键盘导航/播报/焦点/禁用/长按/子菜单),加了未验证的「隐藏/退出条目不进 Tab 顺序」 | `dropdown.md:227-229` vs 官方 `dropdown.mdx:365-376` | 已修 |
| C8 | 相关组件 4 条且顺序不同;官方 `slice(0,3)` = button/popover/separator | `dropdown.md:238-243`;`components-registry.ts:644` | 已修 |
| C9 | 顶部迁移注记与 `## 上游差异` 节为项目自加(确认是否作为统一约定保留) | `dropdown.md:8,231-236` | 保留(项目约定) |
## D. 核对一致、不需要改
- 17 个演示名称与顺序;全部 `id`/`textValue`/文案/`variant`/`aria-label`;`min-w-[256px]`、`ms-auto`、`size-3.5 text-muted`、`text-danger` 等工具类;`KbdAbbr` 键位映射与官方常量一致。
- 四个 CSS 文件是逐字移植(只差 `hv-` 前缀、注释与上游那条空的 `&:focus` 规则);`dropdownVariants`/`menuItemVariants` 与官方 1:1。
- 选择模型 `MenuKey[]`、事件名、具名导出为已登记的 Vue 适配。
## E. 无法核实
上游 checkout 未安装 `node_modules`,以下按官方文档表 + 上游 CSS 选择器反推,未做运行时验证:RAC 的 `data-focused`/每项 `data-selection-mode` 输出、`MenuSection` 的 `aria-labelledby` 实现方式、`trigger="longPress"` 的键盘语义、`MenuItemRenderProps` 是否含 `isIndeterminate`、`@gravity-ui/icons` 的默认属性。
## F. 本轮修复记录(2026-10-24)
同一分支 `feat/b01-menu-dropdown` 逐项修复,证据均为实渲染 DOM 与浏览器 5181 实测。
### 实现
- **A1**:`menu-item.css` 禁用态改为存在选择器 `&[data-disabled]`(Reka 写空串)。浏览器实测禁用行 `opacity: 0.5`、`cursor: not-allowed`,其余行 `opacity: 1`。
- **A2**:`DropdownPopover` 与子菜单内容接入共享 `useOverlayAnimation`,输出真实的 `data-entering`/`data-exiting`;`dropdown.css` 的 `[data-placement]` 改为 Reka 实际输出的 `[data-side]`。浏览器实测打开时 `data-entering="true"`、`animation: enter 0.15s`,动画结束后属性清除、`opacity: 1`;关闭时 `data-exiting="true"`、`animation: exit 0.1s`、`pointer-events: none`,随后节点卸载。
- **A3**:`Menu` 不再给内层列表加 `role="menu"`(Reka content 已是 menu)。实测每个弹层只有 1 个 `role="menu"`。
- **A4**:`MenuItem` 把 key 渲染为元素 `id`;`DropdownSubmenuTrigger` 在挂载/更新后把子菜单内容的 `aria-labelledby` 指回真实触发器(Reka 生成的 id 被用户 key 覆盖导致悬空)。实测子菜单 `aria-labelledby="share"` 可解析。
- **A6**:`DropdownTrigger` 在 `asChild` 目标不是原生可聚焦元素时补 `role="button"` 与 `tabindex="0"`。浏览器实测自定义触发器为 `<span role="button" tabindex="0" aria-haspopup="menu">`,Enter 可打开。
- **A7**:`dropdown.css` 增加 `.hv-dropdown__trigger.hv-button{display:inline-flex}` 与 `.hv-avatar{display:flex}` 兼容规则(与 Modal/Popover/Tooltip 既有做法一致)。实测纯图标触发器图标中心偏移从 `-12px` 变为 `0`。
- **A8**:`DropdownItem` 新增 `hasSubmenu` 显式下发,`DropdownSubmenuTrigger` 自动设置,不再依赖是否渲染指示器。新增回归:不带指示器的子菜单触发器点击不触发 action、不关闭根菜单。
- **A9**:`MenuSection` 提供标签注册上下文,`Header` 注册自身 id,分组输出 `aria-labelledby`。实测可解析到 `Header`。
- **A10**:`MenuItem` 默认插槽提供 `{ isSelected, isFocused, isDisabled, isPressed }`;`DropdownItemIndicator` 插槽提供 `{ isSelected, isIndeterminate, isFocused, isDisabled, isPressed }`。
- **A11**:条目输出 `data-focused`/`data-hovered`/`data-pressed`。浏览器实测 `custom-styles` 演示键盘聚焦行 `data-focused="true"` 且背景变为 `bg-default`,官方示例的 `data-[focused=true]` 不再是死代码。
- **A12**:`DropdownSubmenuTrigger` 把 `class`/ARIA 合并到触发条目;子菜单内 `DropdownPopover` 的 `class`/`data-*`/`aria-*` 继承到子菜单面板。实测 `hv-dropdown__popover nested-pop` 与 `data-x` 均落地。
- **A13**:`Menu`/`MenuItem`/`MenuItemIndicator`/`MenuItemSubmenuIndicator`/`MenuSection`/`DropdownTrigger`/`DropdownPopover` 的用户 class 改为经 tailwind-variants(含 twMerge)合并。
- **A14**:默认子菜单指示器改用官方 `IconChevronRight` 的路径(16 视框、实心),不再自绘 24 视框描边箭头。
- **A15/A16/A17**:独立 `Menu` 用 `data-slot="menu"`;删除 `MenuSection` 无效的 `as`;删除「只传 selectedKeys 就推断 multiple」的自造语义。
### 演示
- **B2**:6 个演示共 27 处 `Kbd slot="keyboard"` 全部还原(浏览器实测打开的菜单里有 4 个 `kbd[slot="keyboard"]`,类名为 `ms-auto hv-kbd hv-kbd--light`)。
- **B3**:`SquarePlus` 改用 `IconSquarePlus`(4 个演示)。
- **B4/B5/B6**:`controlled-open-state` 多余空格、`single-with-custom-indicator` 的 5 段重复 SVG(改为单一定义组件,136→82 行)、`long-press-trigger` 的自加中文注释。
### 文档
- **C1–C8**:`apps/docs/components/dropdown.md` 按官方 `dropdown.mdx` 分节重写:完整组件骨架(含 `DropdownTrigger`/`Separator`/`Section`+`Header`/`SubmenuTrigger`/`Description`/`Kbd slot="keyboard"`/`ItemIndicator`)、官方 4 个类的全局 CSS 示例、分节的样式参考(只列真实发出的状态)、每个部件一张 API 表并标注改名列与「Vue 扩展」、新增 Render Props 表、无障碍按官方条目、相关组件改为官方 3 项。
### 仍保留 / 未修
- **A5**:链接型菜单项(`href`/`target`)未实现——Reka 菜单项没有锚点路径,需自建或换底座;文档已写明不支持。
- **A18**:子菜单悬停延迟由 Reka 固定 100ms,未暴露官方 `delay`。
- **A19**:长按键盘用 Enter/Space(本批复核明确要求),与 RAC 文档的 Alt+↓ 不同。
- **A20**:`DropdownRoot` 保留 `.hv-dropdown` 包裹元素(承载根级 class/dir),官方该类没有 DOM 宿主。
- **A21**:`disallowEmptySelection`、`escapeKeyBehavior`、`shouldFocusWrap`、`autoFocus`、`onClose`、`items`/`renderEmptyState`、菜单级 `shouldCloseOnSelect`、`isKeyboardDismissDisabled`、`shouldCloseOnInteractOutside`、Popover/Trigger render props 仍未提供。
- **B1/B7**:显示用 `DropdownTrigger` 包裹触发器、`Selection`→`MenuKey[]`(含无 `"all"`)为既定 Vue API 适配,文档已登记。
+6
View File
@@ -76,3 +76,9 @@ default、with-icons、with-descriptions、with-disabled-items、with-sections
5. **浏览器(5181,真实点击/按键)**:长按示例真实短点击后不打开;真实 Enter 打开且不被二次切换关闭;Space 一次开一次关;Esc 关闭后焦点回触发器。`with-submenus` 焦点在子菜单项上按 Esc → 只关子菜单、根菜单保持、焦点回「其他」,再按 Esc → 关根菜单、焦点回「分享」,console warn/error 为 0。
**仍存限制(诚实记录)**:本运行时浏览器后端没有 press-and-hold 输入,“按住达到阈值才打开”的计时路径只有 jsdom + 假时钟证据;完整读屏、物理触屏、Nuxt、逐像素与自动视觉对比未验证。
## 忠实度审计(2026-10-24)
按官方 `dropdown.mdx` 与 17 个官方演示逐条对照,问题清单、证据与逐项状态见 [B01 忠实度审计](B01-fidelity-audit.md)。本轮修掉 25 项(禁用态、进出动画、单 `role="menu"`、条目 id 与子菜单 `aria-labelledby`、自定义触发器可聚焦、触发器 inline-flex 冲突、`hasSubmenu` 来源、Section 标题关联、Render Props、`data-focused` 等交互状态、class 合并、子菜单指示器图标、演示 27 处 `Kbd slot="keyboard"`、官方图标与文档页重写),并保留 6 项须记录的差异:链接型菜单项不支持、子菜单悬停延迟固定 100ms、无 `disallowEmptySelection` 等官方 props、长按键盘语义、`DropdownRoot` 包裹元素、`Selection`→`MenuKey[]` 适配。
回归:`tests/b01-menu-dropdown.test.ts` **27/27**、`tests/b01-review.probe.test.ts` **7/7**,完整 **71 文件 / 897 项**;typecheck、build:docs、Prettier 通过;浏览器 5181 实测禁用态、进出动画、图标居中、自定义触发器键盘打开、`data-focused` 背景、单 `role="menu"` 与 `kbd[slot="keyboard"]`。
+16
View File
@@ -925,3 +925,19 @@ Button/PopoverTrigger/Link/ToggleButtonGroup 源码及几何复核后,移除
- 独立 tarball `/tmp/heroui-b01-consumer` 重新打包安装后:ESM 命名导出 + `@heroui-vue/styles/css` 通过;`b01-menu-dropdown-contract.ts` 在 bundler 与 NodeNext 下正反例均通过(`@ts-expect-error` 仍生效)。
- 浏览器 5181 实测(真实点击/真实按键):长按示例真实短点击后 `aria-expanded=false`、无 popover;真实 Enter 打开并保持、`aria-expanded=true`;Space 一次开一次关;Esc 关闭后焦点回到「长按」触发器。`with-submenus` 中焦点在子菜单项 WhatsApp 上按 Esc:子菜单卸载、根菜单仍开(`aria-expanded=true`)、焦点回「其他」;再按 Esc 关根菜单、焦点回「分享」。指针打开子菜单、焦点留在「其他」时同样只关一层。期间 console warn/error 为 0。
- 本运行时浏览器后端不提供 press-and-hold 输入,因此“按住达到阈值才打开”的计时路径只有 jsdom + 假时钟证据;真实鼠标长按与物理触屏仍未验证。完整读屏、Nuxt、逐像素、自动视觉对比也未验证。
### B01 忠实度审计与修复(同日)
按 [忠实度审计](migrations/B01-fidelity-audit.md) 对照官方 `dropdown.mdx` 与 17 个官方演示,逐项修掉复刻偏差,并重写文档页。
- **禁用项样式**:`menu-item.css` 的 `[data-disabled="true"]` 改为存在选择器(Reka 写空串,原选择器永不命中)。浏览器实测禁用行 `opacity 0.5`、`cursor not-allowed`,其余行 `opacity 1`。
- **进入/退出动画**:Dropdown 内容接入共享 `useOverlayAnimation`,输出 `data-entering`/`data-exiting`,CSS 的 `[data-placement]` 改为 Reka 实际输出的 `[data-side]`。浏览器实测打开 `data-entering="true"` + `animation: enter .15s`,结束后属性清除、`opacity 1`;关闭 `data-exiting="true"` + `animation: exit .1s` + `pointer-events:none`,随后卸载。
- **ARIA 结构**:每个弹层只剩 1 个 `role="menu"`(原为 2 个嵌套);条目渲染 DOM `id`;子菜单面板的 `aria-labelledby` 由悬空改为指向真实触发器;`MenuSection` 的 `Header` 通过注册成为分组可访问名称。
- **触发器**:加入 `.hv-dropdown__trigger.hv-button{display:inline-flex}` 与 `.hv-avatar{display:flex}` 兼容规则,纯图标触发器图标中心偏移由 `-12px` 修正为 `0`;自定义(Avatar)触发器补 `role="button"`/`tabindex="0"`,浏览器实测为 `<span role=button tabindex=0>` 且 Enter 可打开(官方渲染的是 `<button>`,DOM 仍不同)。
- **交互状态**:条目输出 `data-focused`/`data-hovered`/`data-pressed`;`custom-styles` 演示的 `data-[focused=true]:bg-default` 实测生效(键盘聚焦行背景为 `bg-default`)。条目与指示器插槽提供官方 Render Props(`isSelected/isFocused/isDisabled/isPressed` 与 `isIndeterminate`)。
- **子菜单**:`hasSubmenu` 改由 `DropdownSubmenuTrigger` 显式下发,不再依赖是否渲染指示器;子菜单面板与触发条目补上原本被丢弃的 `class`/ARIA。
- **样式合并**:用户 class 改经 tailwind-variants(含 twMerge)合并。
- **演示**:6 个演示共 27 处 `Kbd slot="keyboard"` 还原;`SquarePlus`→`IconSquarePlus`;`controlled-open-state` 多余空格、自定义指示器 5 段重复 SVG、长按演示自加注释。
- **文档**:`apps/docs/components/dropdown.md` 按官方分节重写(完整骨架、官方 4 类全局 CSS 示例、分节样式参考、每部件 API 表含改名列与 Vue 扩展、Render Props 表、官方无障碍条目、3 项相关组件)。
- **回归**:`tests/b01-menu-dropdown.test.ts` 增至 **27/27**(新增 17 个预览整体挂载无 warn/error、DOM id 与单 `role=menu`、禁用选择器、子菜单 `aria-labelledby` 可解析、Section 标签、自定义触发器可聚焦、插槽 render state、class 合并、无指示器子菜单),`b01-review.probe.test.ts` **7/7**;完整 **71 文件 / 897 项**;typecheck、build:docs、Prettier 通过。
- **仍保留**:链接型菜单项(`href`)不支持(Reka 无锚点路径)、子菜单悬停延迟固定 100ms、`disallowEmptySelection` 等官方 props 未提供、`DropdownRoot` 保留一层包裹元素;`Kbd slot="keyboard"` 之外未做逐像素对比,完整读屏/触屏/Nuxt 仍未验证。
+18 -7
View File
@@ -40,6 +40,17 @@
}
}
/* Library Button/Avatar keep their own layout when used as a Vue trigger.
The custom-trigger affordances above only need to apply to plain elements,
so the base layout utilities of those components win back. */
.hv-dropdown__trigger.hv-button {
display: inline-flex;
}
.hv-dropdown__trigger.hv-avatar {
display: flex;
}
/* Similar to select popover styles */
.hv-dropdown__popover {
@apply max-w-[48svw] origin-(--trigger-anchor-point) scroll-py-1 scrollbar overflow-y-auto overscroll-contain bg-overlay p-0 text-sm md:min-w-55;
@@ -55,19 +66,19 @@
&[data-entering="true"] {
@apply animate-in duration-150 ease-smooth fade-in-0 zoom-in-90;
&[data-placement="top"] {
&[data-side="top"] {
@apply slide-in-from-bottom-1;
}
&[data-placement="bottom"] {
&[data-side="bottom"] {
@apply slide-in-from-top-1;
}
&[data-placement="left"] {
&[data-side="left"] {
@apply slide-in-from-right-1;
}
&[data-placement="right"] {
&[data-side="right"] {
@apply slide-in-from-left-1;
}
}
@@ -88,15 +99,15 @@
fill: var(--overlay);
}
&[data-placement="bottom"] [data-slot="popover-overlay-arrow"] {
&[data-side="bottom"] [data-slot="popover-overlay-arrow"] {
rotate: 180deg;
}
&[data-placement="left"] [data-slot="popover-overlay-arrow"] {
&[data-side="left"] [data-slot="popover-overlay-arrow"] {
rotate: -90deg;
}
&[data-placement="right"] [data-slot="popover-overlay-arrow"] {
&[data-side="right"] [data-slot="popover-overlay-arrow"] {
rotate: 90deg;
}
+3 -2
View File
@@ -77,8 +77,9 @@
}
}
/* Disabled state */
&[data-disabled="true"] {
/* Disabled state.
Reka writes a presence attribute (`data-disabled=""`), not `"true"`. */
&[data-disabled] {
@apply status-disabled;
}
}
@@ -1,22 +1,28 @@
<script lang="ts">
import {
Fragment,
computed,
defineComponent,
h,
inject,
provide,
ref,
useAttrs,
type PropType,
type Ref,
} from "vue";
import {
DropdownMenuContent as RekaDropdownMenuContent,
injectDropdownMenuRootContext,
} from "reka-ui";
import { dropdownVariants } from "@heroui-vue/styles";
import {
dropdownContextKey,
menuCloseKey,
submenuContentKey,
} from "../menu/context";
import { useOverlayAnimation } from "../overlay/animation";
import { menuSurfaceFromVNode } from "./dom";
/**
* Dropdown popover / menu content shell. Provides close for Menu items.
@@ -47,19 +53,28 @@ export default defineComponent({
rootCtx?.onOpenChange(false);
});
const contentElement = ref<HTMLElement | null>(null);
const isOpen = computed(() => rootCtx?.open.value ?? false);
const { entering, exiting, onAnimationEnd } = useOverlayAnimation(
isOpen as Ref<boolean>,
contentElement,
true,
);
return () => {
const cls = [dropdownCtx?.slots.value.popover(), attrs.class];
if (inSubmenu) {
// Reka SubContent already positions and dismisses this level;
// keep a lightweight shell so Menu styling still applies.
// the submenu trigger forwards attrs onto that element.
return h(Fragment, null, slots.default?.() as never);
}
return h(
RekaDropdownMenuContent as never,
{
...attrs,
class: cls,
class: dropdownCtx?.slots.value.popover({ class: attrs.class }),
"data-slot": "dropdown-popover",
"data-entering": entering.value || undefined,
"data-exiting": exiting.value || undefined,
side: props.side,
sideOffset: props.sideOffset,
align: props.align,
@@ -67,6 +82,17 @@ export default defineComponent({
avoidCollisions: props.avoidCollisions,
collisionPadding: props.collisionPadding,
loop: props.loop,
onAnimationend: onAnimationEnd,
onVnodeMounted: (vnode) => {
contentElement.value = menuSurfaceFromVNode(vnode);
},
onVnodeUpdated: (vnode) => {
const element = menuSurfaceFromVNode(vnode);
if (element) contentElement.value = element;
},
onVnodeUnmounted: () => {
contentElement.value = null;
},
},
slots,
);
@@ -2,12 +2,19 @@
import {
Fragment,
cloneVNode,
computed,
defineComponent,
h,
inject,
isVNode,
nextTick,
onMounted,
provide,
ref,
useAttrs,
useId,
watch,
type Ref,
type VNodeChild,
} from "vue";
import {
@@ -15,7 +22,11 @@ import {
DropdownMenuSubContent as RekaDropdownMenuSubContent,
DropdownMenuSubTrigger as RekaDropdownMenuSubTrigger,
} from "reka-ui";
import { dropdownVariants } from "@heroui-vue/styles";
import { dropdownContextKey, submenuContentKey } from "../menu/context";
import { useOverlayAnimation } from "../overlay/animation";
import { elementFromValue, menuSurfaceFromVNode } from "./dom";
import DropdownPopover from "./DropdownPopover.vue";
function flatten(nodes: VNodeChild[], out: VNodeChild[] = []): VNodeChild[] {
for (const n of nodes) {
@@ -25,10 +36,24 @@ function flatten(nodes: VNodeChild[], out: VNodeChild[] = []): VNodeChild[] {
return out;
}
function resolveElement(value: unknown): HTMLElement | null {
if (value instanceof Element) return value as HTMLElement;
const el = (value as { $el?: unknown } | null)?.$el;
return el instanceof Element ? (el as HTMLElement) : null;
/** Attributes a nested `<DropdownPopover>` may pass to the submenu surface. */
function inheritableAttrs(props: Record<string, unknown> | null) {
const out: Record<string, unknown> = {};
if (!props) return out;
for (const [key, value] of Object.entries(props)) {
if (key === "ref" || key === "key") continue;
if (
key === "class" ||
key === "style" ||
key === "id" ||
key === "role" ||
key.startsWith("data-") ||
key.startsWith("aria-") ||
/^on[A-Z]/.test(key)
)
out[key] = value;
}
return out;
}
/**
@@ -47,6 +72,41 @@ export default defineComponent({
const subOpen = ref(false);
const triggerRef = ref<unknown>(null);
const contentElement = ref<HTMLElement | null>(null);
const fallbackId = useId();
const { entering, exiting, onAnimationEnd } = useOverlayAnimation(
subOpen as Ref<boolean>,
contentElement,
true,
);
/**
* Reka labels the submenu surface with the id it generates for its own
* trigger, but our trigger item keeps the caller's `id` (the selection
* key), so that reference dangles. Point it at the real trigger element.
*/
function repairLabel() {
const content = contentElement.value;
const trigger = elementFromValue(triggerRef.value);
if (!content || !trigger) return;
const ids = (content.getAttribute("aria-labelledby") ?? "")
.split(/\s+/)
.filter(Boolean);
const resolves = ids.some(
(id) => content.ownerDocument.getElementById(id) !== null,
);
if (resolves) return;
if (!trigger.id) trigger.id = fallbackId;
content.setAttribute("aria-labelledby", trigger.id);
}
watch(
contentElement,
(element) => {
if (element) void nextTick(repairLabel);
},
{ flush: "post" },
);
onMounted(repairLabel as () => void);
function handleEscape(event: KeyboardEvent) {
if (event.key !== "Escape" || !subOpen.value) return;
@@ -59,13 +119,21 @@ export default defineComponent({
event.preventDefault();
event.stopPropagation();
subOpen.value = false;
resolveElement(triggerRef.value)?.focus();
elementFromValue(triggerRef.value)?.focus();
}
return () => {
const children = flatten(slots.default?.() ?? []);
const triggerVNode = children[0] ?? null;
const contentVNodes = children.slice(1);
const popoverVNode = contentVNodes.find(
(node) => isVNode(node) && node.type === DropdownPopover,
);
const popoverAttrs = inheritableAttrs(
isVNode(popoverVNode)
? (popoverVNode.props as Record<string, unknown> | null)
: null,
);
return h(
RekaDropdownMenuSub as never,
@@ -88,7 +156,11 @@ export default defineComponent({
default: () =>
triggerVNode
? cloneVNode(triggerVNode as never, {
...attrs,
ref: triggerRef as never,
// The item is a submenu trigger regardless of whether
// the caller renders an indicator.
hasSubmenu: true,
// Escape with focus on the trigger (pointer-opened
// submenu) must also close only this level.
onKeydown: handleEscape,
@@ -99,10 +171,29 @@ export default defineComponent({
h(
RekaDropdownMenuSubContent as never,
{
class: [dropdownCtx?.slots.value.popover()],
...popoverAttrs,
class: [dropdownCtx?.slots.value.popover(), popoverAttrs.class],
"data-slot": "dropdown-popover",
"data-submenu-content": "true",
"data-entering": entering.value || undefined,
"data-exiting": exiting.value || undefined,
onKeydown: handleEscape,
onAnimationend: onAnimationEnd,
onVnodeMounted: (vnode) => {
contentElement.value = menuSurfaceFromVNode(vnode);
void nextTick(repairLabel);
},
onVnodeUpdated: (vnode) => {
const element = menuSurfaceFromVNode(vnode);
if (!element) return;
contentElement.value = element;
// Reka re-applies its own trigger id on re-render, so the
// association is restored after every patch.
void nextTick(repairLabel);
},
onVnodeUnmounted: () => {
contentElement.value = null;
},
},
{
default: () =>
@@ -1,7 +1,17 @@
<script lang="ts">
import { defineComponent, h, inject, onBeforeUnmount, useAttrs } from "vue";
import {
defineComponent,
h,
inject,
nextTick,
onBeforeUnmount,
onMounted,
ref,
useAttrs,
} from "vue";
import { DropdownMenuTrigger as RekaDropdownMenuTrigger } from "reka-ui";
import { dropdownContextKey } from "../menu/context";
import { elementFromValue } from "./dom";
const LONG_PRESS_MOVE_PX = 10;
@@ -23,6 +33,7 @@ export default defineComponent({
setup(props, { slots }) {
const attrs = useAttrs();
const dropdownCtx = inject(dropdownContextKey, null);
const triggerRef = ref<unknown>(null);
const isLongPress = () =>
(dropdownCtx?.triggerMode.value ?? "press") === "longPress";
@@ -75,6 +86,33 @@ export default defineComponent({
dropdownCtx?.setOpen(!(dropdownCtx?.open.value ?? false));
}
/**
* Upstream's `Dropdown.Trigger` is a real `<button>`, so a custom trigger
* (e.g. an Avatar) stays keyboard operable. With `asChild` the element is
* whatever the caller supplied, so restore button semantics when it is not
* natively focusable.
*/
function ensureFocusable() {
const el = elementFromValue(triggerRef.value);
if (!el) return;
const tag = el.tagName;
const role = el.getAttribute("role");
if (
tag === "BUTTON" ||
(tag === "A" && el.hasAttribute("href")) ||
el.hasAttribute("tabindex") ||
role === "button" ||
role === "link" ||
role === "menuitem"
)
return;
if (!role) el.setAttribute("role", "button");
el.setAttribute("tabindex", "0");
}
onMounted(() => void nextTick(ensureFocusable));
onBeforeUnmount(clearPress);
const guardHandlers = {
onPointerdownCapture: onPointerdown,
onPointermoveCapture: onPointermove,
@@ -86,16 +124,17 @@ export default defineComponent({
onContextmenuCapture: clearPress,
};
onBeforeUnmount(clearPress);
return () => {
const trigger = h(
RekaDropdownMenuTrigger as never,
{
...attrs,
ref: triggerRef,
as: props.as,
asChild: props.asChild ?? true,
class: [dropdownCtx?.slots.value.trigger(), attrs.class],
class: dropdownCtx?.slots.value.trigger({
class: attrs.class as never,
}),
"data-slot": "dropdown-trigger",
},
slots,
@@ -0,0 +1,36 @@
import type { VNode } from "vue";
/** Resolve a component/ref handle to its DOM element. */
export function elementFromValue(value: unknown): HTMLElement | null {
if (value instanceof Element) return value as HTMLElement;
const el = (value as { $el?: unknown } | null)?.$el;
return el instanceof Element ? (el as HTMLElement) : null;
}
/**
* Resolve the element a vnode mounted to. Reka's content components expose the
* positioned element through `$el`; fragments (text nodes) resolve to null.
*/
export function elementFromVNode(
vnode: VNode | null | undefined,
): HTMLElement | null {
if (!vnode) return null;
const el = vnode.el;
if (el instanceof Element) return el as HTMLElement;
const proxyEl = (vnode.component?.proxy as { $el?: unknown } | null)?.$el;
return proxyEl instanceof Element ? (proxyEl as HTMLElement) : null;
}
/**
* Reka renders a positioning wrapper around the menu surface; the popover
* styles and animations live on the inner `[data-reka-menu-content]` node.
*/
export function menuSurfaceFromVNode(
vnode: VNode | null | undefined,
): HTMLElement | null {
const el = elementFromVNode(vnode);
if (!el) return null;
if (el.matches("[data-reka-menu-content]")) return el;
const inner = el.querySelector("[data-reka-menu-content]");
return inner instanceof Element ? (inner as HTMLElement) : el;
}
@@ -1,6 +1,15 @@
<script lang="ts">
import { defineComponent, h, useAttrs } from "vue";
import {
defineComponent,
h,
inject,
onUnmounted,
useAttrs,
useId,
watch,
} from "vue";
import { headerVariants } from "@heroui-vue/styles";
import { menuSectionLabelKey } from "../menu/context";
/**
* Collection / group section heading (RAC Header).
@@ -19,12 +28,33 @@ export default defineComponent({
},
setup(props, { slots }) {
const attrs = useAttrs();
// Inside a MenuSection the header names the group (upstream wires this
// through the collection); elsewhere it stays a plain heading element.
const section = inject(menuSectionLabelKey, null);
const autoId = useId();
let unregister: (() => void) | undefined;
const resolveId = () =>
(attrs.id as string | undefined) || (section ? autoId : undefined);
watch(
resolveId,
(id, prev) => {
if (!section || !id || id === prev) return;
unregister?.();
unregister = section.registerLabel(id);
},
{ immediate: true },
);
onUnmounted(() => {
unregister?.();
unregister = undefined;
});
function render() {
return h(
props.as,
{
...attrs,
id: resolveId(),
class: [headerVariants(), attrs.class],
"data-slot": "header",
},
@@ -20,6 +20,7 @@ import {
type NativeClickHandler =
((e: MouseEvent) => void) | ((e: MouseEvent) => void)[] | undefined;
type NativeHandler<Ev> = ((e: Ev) => void) | ((e: Ev) => void)[] | undefined;
export default defineComponent({
name: "MenuItem",
@@ -35,6 +36,12 @@ export default defineComponent({
},
/** Set false to keep the menu open after an action item. */
closeOnSelect: { type: Boolean, default: undefined },
/**
* Render this item as a submenu trigger. `DropdownSubmenuTrigger` sets it
* so the item no longer depends on a rendered indicator to know it has a
* submenu (upstream derives it from the collection structure).
*/
hasSubmenu: { type: Boolean, default: undefined },
},
emits: {
select: (_key: MenuKey) => true,
@@ -44,11 +51,17 @@ export default defineComponent({
const menuCtx = inject(menuContextKey, null);
const sectionCtx = inject(menuSectionContextKey, null);
const owner = sectionCtx?.selection ?? menuCtx?.selection;
const hasSubmenu = ref(false);
const indicatorSubmenu = ref(false);
const isFocused = ref(false);
const isHovered = ref(false);
const isPressed = ref(false);
const key = computed<MenuKey>(
() => props.id ?? (attrs.id as MenuKey | undefined) ?? "",
);
const hasSubmenu = computed(
() => props.hasSubmenu ?? indicatorSubmenu.value,
);
const isDisabled = computed(
() =>
props.isDisabled ||
@@ -72,9 +85,11 @@ export default defineComponent({
slots: slotsComputed,
isDisabled,
isSelected,
hasSubmenu: computed(() => hasSubmenu.value),
isFocused,
isPressed,
hasSubmenu,
setHasSubmenu(value: boolean) {
hasSubmenu.value = value;
indicatorSubmenu.value = value;
},
});
@@ -93,6 +108,16 @@ export default defineComponent({
menuCtx?.closeLevel();
}
/** Keep the caller's own handler(s) in front of the internal tracker. */
function withOwn<Ev extends Event>(
name: string,
own: (event: Ev) => void,
): NativeHandler<Ev> {
const user = (attrs as Record<string, NativeHandler<Ev>>)[name];
if (!user) return own;
return Array.isArray(user) ? [...user, own] : [user, own];
}
return () => {
// Hand the user handlers and our activation to Vue as one DOM `onClick`
// array so browser/Vue listener semantics stay intact: capture order,
@@ -105,6 +130,17 @@ export default defineComponent({
...(attrs as Record<string, unknown>),
};
delete rest.onClick;
for (const name of [
"onFocus",
"onBlur",
"onPointerDown",
"onPointerUp",
"onPointerCancel",
"onPointerEnter",
"onPointerLeave",
]) {
delete rest[name];
}
const clickChain: Array<(e: MouseEvent) => void> = (
Array.isArray(userOnClick)
@@ -118,12 +154,16 @@ export default defineComponent({
activate();
});
const roleAttr = (attrs.role as string | undefined) ?? role.value;
const domId = props.id ?? (attrs.id as MenuKey | undefined);
return h(
RekaMenuItem as never,
{
...rest,
class: [slotsComputed.value.item(), attrs.class],
role: (attrs.role as string | undefined) ?? role.value,
id: domId,
class: slotsComputed.value.item({ class: attrs.class as never }),
role: roleAttr,
"aria-checked":
selectionMode.value === "none"
? undefined
@@ -133,16 +173,52 @@ export default defineComponent({
"aria-disabled": isDisabled.value || undefined,
"data-slot": "menu-item",
"data-selected": isSelected.value || undefined,
// RAC's render-state hooks that the ported CSS and the official
// custom-styles demo rely on.
"data-focused": isFocused.value || undefined,
"data-hovered": isHovered.value || undefined,
"data-pressed": isPressed.value || undefined,
"data-has-submenu": hasSubmenu.value || undefined,
"data-selection-mode": selectionMode.value,
disabled: isDisabled.value,
textValue: props.textValue,
onClick: clickChain,
onFocus: withOwn<FocusEvent>("onFocus", () => {
isFocused.value = true;
}),
onBlur: withOwn<FocusEvent>("onBlur", () => {
isFocused.value = false;
isPressed.value = false;
}),
onPointerDown: withOwn<PointerEvent>("onPointerDown", () => {
isPressed.value = true;
}),
onPointerUp: withOwn<PointerEvent>("onPointerUp", () => {
isPressed.value = false;
}),
onPointerCancel: withOwn<PointerEvent>("onPointerCancel", () => {
isPressed.value = false;
}),
onPointerEnter: withOwn<PointerEvent>("onPointerEnter", () => {
isHovered.value = true;
}),
onPointerLeave: withOwn<PointerEvent>("onPointerLeave", () => {
isHovered.value = false;
isPressed.value = false;
}),
onSelect: (itemSelectEvent?: { preventDefault?: () => void }) => {
itemSelectEvent?.preventDefault?.();
},
},
slots,
{
default: () =>
slots.default?.({
isSelected: isSelected.value,
isFocused: isFocused.value,
isDisabled: isDisabled.value,
isPressed: isPressed.value,
}),
},
);
};
},
@@ -58,21 +58,29 @@ export default defineComponent({
const attrs = useAttrs();
const item = inject(menuItemContextKey, null);
return () => {
const isSelected = item?.isSelected.value ?? false;
const state = {
isSelected: item?.isSelected.value ?? false,
// Menu items have no indeterminate state; kept for the upstream
// render-prop contract.
isIndeterminate: false,
isFocused: item?.isFocused.value ?? false,
isDisabled: item?.isDisabled.value ?? false,
isPressed: item?.isPressed.value ?? false,
};
const content = slots.default
? slots.default({ isSelected })
? slots.default(state)
: props.type === "dot"
? DotIcon()
: CheckmarkIcon(isSelected);
: CheckmarkIcon(state.isSelected);
return h(
props.as,
{
...attrs,
"aria-hidden": "true",
class: [item?.slots.value.indicator(), attrs.class],
class: item?.slots.value.indicator({ class: attrs.class as never }),
"data-slot": "menu-item-indicator",
"data-type": props.type,
"data-visible": isSelected || undefined,
"data-visible": state.isSelected || undefined,
},
content,
);
@@ -9,6 +9,9 @@ import {
} from "vue";
import { menuItemContextKey } from "../menu/context";
/** Ported from HeroUI `IconChevronRight` (icons.tsx) so the default
* submenu affordance keeps the baseline artwork without adding an icon
* dependency to the component package. */
function ChevronIcon() {
return h(
"svg",
@@ -16,14 +19,19 @@ function ChevronIcon() {
"aria-hidden": "true",
fill: "none",
height: "16",
stroke: "currentColor",
"stroke-linecap": "round",
"stroke-linejoin": "round",
"stroke-width": "2",
viewBox: "0 0 24 24",
role: "presentation",
viewBox: "0 0 16 16",
width: "16",
xmlns: "http://www.w3.org/2000/svg",
},
[h("path", { d: "m9 18 6-6-6-6" })],
[
h("path", {
"clip-rule": "evenodd",
d: "M5.47 2.97a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1 0 1.06l-4.5 4.5a.75.75 0 1 1-1.06-1.06L9.44 8 5.47 4.03a.75.75 0 0 1 0-1.06Z",
fill: "currentColor",
"fill-rule": "evenodd",
}),
],
);
}
@@ -44,7 +52,9 @@ export default defineComponent({
{
...attrs,
"aria-hidden": "true",
class: [item.slots.value.submenuIndicator(), attrs.class],
class: item.slots.value.submenuIndicator({
class: attrs.class as never,
}),
"data-slot": "submenu-indicator",
},
slots.default ? slots.default() : ChevronIcon(),
@@ -15,6 +15,7 @@ import { menuSectionVariants } from "@heroui-vue/styles";
import {
menuContextKey,
menuSectionContextKey,
menuSectionLabelKey,
type MenuKey,
type MenuSelectionMode,
} from "../menu/context";
@@ -24,7 +25,6 @@ export default defineComponent({
name: "MenuSection",
inheritAttrs: false,
props: {
as: { type: String, default: "div" },
/** Section-level selection mode. Omit to inherit the menu's selection. */
selectionMode: {
type: String as PropType<MenuSelectionMode>,
@@ -60,11 +60,9 @@ export default defineComponent({
const acceptedKeys = computed(() =>
isControlled.value ? (props.selectedKeys ?? []) : internal.value,
);
const effectiveMode = computed<MenuSelectionMode>(() => {
if (props.selectionMode) return props.selectionMode;
if (ownsSelection.value) return "multiple";
return menuCtx?.selectionMode.value ?? "none";
});
const effectiveMode = computed<MenuSelectionMode>(
() => props.selectionMode ?? menuCtx?.selectionMode.value ?? "none",
);
const sectionSelection = useMenuSelection({
selectionMode: effectiveMode,
@@ -84,6 +82,21 @@ export default defineComponent({
},
);
// A nested Header registers here so the group keeps an accessible name.
const labelIds = ref<string[]>([]);
provide(menuSectionLabelKey, {
labelledBy: computed(() =>
labelIds.value.length ? labelIds.value.join(" ") : undefined,
),
registerLabel(id: string) {
if (!labelIds.value.includes(id))
labelIds.value = [...labelIds.value, id];
return () => {
labelIds.value = labelIds.value.filter((item) => item !== id);
};
},
});
provide(menuSectionContextKey, {
selection: {
get selectionMode() {
@@ -116,17 +129,22 @@ export default defineComponent({
},
});
return () =>
h(
return () => {
const labelledBy =
(attrs["aria-labelledby"] as string | undefined) ??
(labelIds.value.length ? labelIds.value.join(" ") : undefined);
return h(
RekaMenuGroup as never,
{
...attrs,
class: [menuSectionVariants(), attrs.class],
class: menuSectionVariants({ class: attrs.class as never }),
"aria-labelledby": labelledBy,
"data-slot": "menu-section",
role: "group",
role: (attrs.role as string | undefined) ?? "group",
},
slots,
);
};
},
});
</script>
+17 -12
View File
@@ -15,7 +15,7 @@ import {
DropdownMenuRoot as RekaDropdownMenuRoot,
injectDropdownMenuRootContext,
} from "reka-ui";
import { menuVariants } from "@heroui-vue/styles";
import { dropdownVariants, menuVariants } from "@heroui-vue/styles";
import {
dropdownContextKey,
menuCloseKey,
@@ -34,7 +34,6 @@ export default defineComponent({
name: "Menu",
inheritAttrs: false,
props: {
as: { type: String, default: "div" },
selectionMode: {
type: String as PropType<MenuSelectionMode>,
default: "none",
@@ -99,20 +98,26 @@ export default defineComponent({
selectionMode: computed(() => props.selectionMode),
});
const listNode = () =>
h(
props.as,
const listNode = () => {
// The surrounding Reka content already renders `role="menu"`; upstream
// also styles the list itself, so it stays a plain element here.
const userRole = attrs.role as string | undefined;
const rest: Record<string, unknown> = { ...attrs };
delete rest.role;
return h(
"div",
{
...attrs,
class: [dropdownCtx?.slots.value.menu(), menuVariants(), attrs.class]
.filter(Boolean)
.join(" "),
...rest,
...(userRole ? { role: userRole } : {}),
class: menuVariants({
class: [dropdownCtx?.slots.value.menu(), attrs.class],
}),
"data-selection-mode": props.selectionMode,
"data-slot": "dropdown-menu",
role: "menu",
"data-slot": dropdownCtx ? "dropdown-menu" : "menu",
},
slots,
);
};
return () => {
if (!needsOwnRoot.value) return listNode();
@@ -126,7 +131,7 @@ export default defineComponent({
h(
RekaDropdownMenuContent as never,
{
class: dropdownCtx?.slots.value.popover(),
class: dropdownVariants().popover(),
"data-slot": "dropdown-popover",
sideOffset: 0,
},
+13 -1
View File
@@ -1,4 +1,4 @@
import type { ComputedRef, InjectionKey } from "vue";
import type { ComputedRef, InjectionKey, Ref } from "vue";
export type MenuKey = string | number;
@@ -33,11 +33,23 @@ export interface MenuSectionContextValue {
export const menuSectionContextKey: InjectionKey<MenuSectionContextValue> =
Symbol("hv-menu-section");
/** MenuSection exposes this so a nested Header can name the group. */
export interface MenuSectionLabelValue {
labelledBy: ComputedRef<string | undefined>;
registerLabel: (id: string) => () => void;
}
export const menuSectionLabelKey: InjectionKey<MenuSectionLabelValue> = Symbol(
"hv-menu-section-label",
);
export interface MenuItemContextValue {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slots: ComputedRef<any>;
isDisabled: ComputedRef<boolean>;
isSelected: ComputedRef<boolean>;
isFocused: Ref<boolean>;
isPressed: Ref<boolean>;
hasSubmenu: ComputedRef<boolean>;
setHasSubmenu: (value: boolean) => void;
}
+5 -2
View File
@@ -6,6 +6,7 @@ import type MenuSection from "./components/menu-section/MenuSection.vue";
import type DropdownRoot from "./components/dropdown/DropdownRoot.vue";
import type DropdownTrigger from "./components/dropdown/DropdownTrigger.vue";
import type DropdownPopover from "./components/dropdown/DropdownPopover.vue";
import type DropdownSubmenuTrigger from "./components/dropdown/DropdownSubmenuTrigger.vue";
export type MenuRootProps = InstanceType<typeof Menu>["$props"];
export type MenuItemProps = InstanceType<typeof MenuItem>["$props"];
@@ -33,5 +34,7 @@ export type DropdownItemProps = MenuItemProps;
export type DropdownItemIndicatorProps = MenuItemIndicatorProps;
/** Dropdown.SubmenuIndicator is MenuItemSubmenuIndicator. */
export type DropdownSubmenuIndicatorProps = MenuItemSubmenuIndicatorProps;
/** Submenu trigger wrapper; accepts common layout attrs. */
export type DropdownSubmenuTriggerProps = Record<string, unknown>;
/** Submenu trigger wrapper: no own props; attrs land on the trigger item. */
export type DropdownSubmenuTriggerProps = InstanceType<
typeof DropdownSubmenuTrigger
>["$props"];
+264
View File
@@ -12,6 +12,9 @@ import {
DropdownSection,
DropdownSubmenuTrigger,
DropdownSubmenuIndicator,
Avatar,
AvatarFallback,
Header,
Label,
Menu,
MenuItem,
@@ -650,3 +653,264 @@ it("keyboard activation is cancelled when the item click is prevented", async ()
expect(actions).toEqual([]);
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
});
it("the 17 baseline previews all mount without console warnings", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const error = vi.spyOn(console, "error").mockImplementation(() => {});
const demos = import.meta.glob("../apps/docs/demos/dropdown-*.vue", {
eager: true,
import: "default",
});
const names = Object.keys(demos).map((path) =>
path.replace("../apps/docs/demos/", "").replace(".vue", ""),
);
expect(names).toHaveLength(17);
try {
for (const name of names) {
const w = mount(demos[`../apps/docs/demos/${name}.vue`] as never, {
attachTo: document.body,
});
await flushPromises();
w.unmount();
await flushPromises();
}
expect(error.mock.calls).toEqual([]);
expect(warn.mock.calls).toEqual([]);
} finally {
warn.mockRestore();
error.mockRestore();
document.body.innerHTML = "";
}
});
it("menu items expose DOM ids and a single role=menu per popup", async () => {
mountApp(
() => () =>
h(DropdownRoot, { defaultOpen: true }, () => [
h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
h(DropdownPopover, {}, () =>
h(DropdownMenu, {}, () => [
h(DropdownItem, { id: "first", textValue: "一" }, () =>
h(Label, () => "一"),
),
h(DropdownItem, { id: "second", textValue: "二" }, () =>
h(Label, () => "二"),
),
]),
),
]),
);
await flushPromises();
await nextTick();
const items = document.querySelectorAll('[data-slot="menu-item"]');
expect(Array.from(items).map((item) => item.getAttribute("id"))).toEqual([
"first",
"second",
]);
expect(document.querySelectorAll('[role="menu"]')).toHaveLength(1);
});
it("disabled items match the ported CSS presence selector", async () => {
mountApp(
() => () =>
h(DropdownRoot, { defaultOpen: true }, () => [
h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
h(DropdownPopover, {}, () =>
h(DropdownMenu, { disabledKeys: ["x"] }, () =>
h(DropdownItem, { id: "x", textValue: "X" }, () =>
h(Label, () => "X"),
),
),
),
]),
);
await flushPromises();
await nextTick();
const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement;
// `menu-item.css` styles `&[data-disabled]`, so presence is the contract.
expect(item.matches("[data-disabled]")).toBe(true);
});
it("submenu surface keeps a resolvable accessible name", async () => {
mountSubmenu();
await flushPromises();
await nextTick();
const { subContent } = await openSubmenu();
await flushPromises();
const labelledBy = subContent.getAttribute("aria-labelledby");
expect(labelledBy).toBeTruthy();
expect(document.getElementById(labelledBy as string)).not.toBeNull();
});
it("Section names its group from a nested Header", async () => {
mountApp(
() => () =>
h(DropdownRoot, { defaultOpen: true }, () => [
h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
h(DropdownPopover, {}, () =>
h(DropdownMenu, {}, () =>
h(DropdownSection, {}, () => [
h(Header, {}, () => "操作"),
h(DropdownItem, { id: "a", textValue: "A" }, () =>
h(Label, () => "A"),
),
]),
),
),
]),
);
await flushPromises();
await nextTick();
const section = document.querySelector(
'[data-slot="menu-section"]',
) as HTMLElement;
const labelledBy = section.getAttribute("aria-labelledby");
expect(labelledBy).toBeTruthy();
const header = document.getElementById(labelledBy as string);
expect(header?.textContent).toBe("操作");
});
it("a non-button custom trigger stays keyboard focusable", async () => {
mountApp(
() => () =>
h(DropdownRoot, {}, () => [
h(DropdownTrigger, {}, () =>
h(Avatar, {}, () => h(AvatarFallback, {}, () => "JD")),
),
h(DropdownPopover, {}, () =>
h(DropdownMenu, {}, () =>
h(DropdownItem, { id: "a", textValue: "A" }, () =>
h(Label, () => "A"),
),
),
),
]),
);
await flushPromises();
await nextTick();
const trigger = document.querySelector(
'[data-slot="dropdown-trigger"]',
) as HTMLElement;
expect(trigger.tagName).toBe("SPAN");
expect(trigger.getAttribute("role")).toBe("button");
expect(trigger.getAttribute("tabindex")).toBe("0");
});
it("item and indicator slots expose the upstream render state", async () => {
const seen: Record<string, unknown>[] = [];
const indicatorState: Record<string, unknown>[] = [];
mountApp(
() => () =>
h(DropdownRoot, { defaultOpen: true }, () => [
h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
h(DropdownPopover, {}, () =>
h(
DropdownMenu,
{ selectionMode: "single", selectedKeys: ["a"] },
{
default: () =>
h(
DropdownItem,
{ id: "a", textValue: "A" },
{
default: (state: Record<string, unknown>) => {
seen.push(state);
return [
h(
DropdownItemIndicator,
{},
{
default: (indicator: Record<string, unknown>) => {
indicatorState.push(indicator);
return null;
},
},
),
h(Label, () => "A"),
];
},
},
),
},
),
),
]),
);
await flushPromises();
await nextTick();
expect(seen[0]).toMatchObject({
isSelected: true,
isDisabled: false,
isPressed: false,
});
expect(seen[0]).toHaveProperty("isFocused");
expect(indicatorState[0]).toMatchObject({
isSelected: true,
isIndeterminate: false,
});
});
it("caller classes merge with tailwind-variants semantics", async () => {
mountApp(
() => () =>
h(DropdownRoot, { defaultOpen: true }, () => [
h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
h(DropdownPopover, {}, () =>
h(DropdownMenu, {}, () =>
h(DropdownItem, { id: "a", textValue: "A", class: "p-0" }, () =>
h(Label, () => "A"),
),
),
),
]),
);
await flushPromises();
await nextTick();
const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement;
expect(item.className).toContain("hv-menu-item");
expect(item.className).toContain("p-0");
});
it("pressing the submenu trigger without an indicator still treats it as a submenu", async () => {
const actions: string[] = [];
mountApp(
() => () =>
h(DropdownRoot, { defaultOpen: true }, () => [
h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
h(DropdownPopover, {}, () =>
h(
DropdownMenu,
{ onAction: (key: string) => actions.push(key) },
() =>
h(DropdownSubmenuTrigger, {}, () => [
h(DropdownItem, { id: "more", textValue: "更多" }, () =>
h(Label, () => "更多"),
),
h(DropdownPopover, {}, () =>
h(DropdownMenu, {}, () =>
h(DropdownItem, { id: "child", textValue: "子项" }, () =>
h(Label, () => "子项"),
),
),
),
]),
),
),
]),
);
await flushPromises();
await nextTick();
const trigger = document.querySelector(
'[data-slot="menu-item"][data-has-submenu="true"]',
) as HTMLElement;
expect(trigger).not.toBeNull();
trigger.click();
await flushPromises();
await nextTick();
// A submenu trigger must not fire the menu action nor close the root menu.
expect(actions).toEqual([]);
expect(document.querySelector("[data-submenu-content]")).not.toBeNull();
expect(
document.querySelectorAll('[data-slot="dropdown-popover"]').length,
).toBeGreaterThan(1);
});