From 53b4639b0ef9562e22f0d2472a3aefc08138622d Mon Sep 17 00:00:00 2001 From: maoyingjie Date: Sat, 24 Oct 2026 22:56:44 +0800 Subject: [PATCH] fix: portal dropdown surfaces and close the review capability gaps - Root and submenu surfaces render through the dropdown portal with the overlay z-index, so clipping/isolation ancestors no longer cut the menu; panel height is capped by the floating available height and the animation origin maps the real transform origin. - Standalone Menu is a static in-flow list: no scroll lock, no outside pointer blocking, no floating placement and no focus stealing. - Selection ownership is isolated per level: section disabled keys add to the menu list, and a nested Menu resets the section owner. - closeOnSelect resolves item > menu policy > per-mode default for selection items; actions and radio items close, checkboxes stay open. - Business keys no longer become DOM ids (instance ids + data-key), and submenu surfaces label themselves from the real trigger. - Long-press keydown runs the caller's handlers first and only opens when not cancelled; submenu panels merge caller keydown with the internal Escape. - Link items render a real anchor, aria labels land on the role=menu node, submenu panels forward placement/offset/collision props and caller attrs, and the popover provides the default Surface variant. - Wrapper parts declare real props/emits, plus the missing official capability props (disallowEmptySelection, escapeKeyBehavior, shouldFocusWrap, autoFocus, shouldCloseOnSelect, close, empty slot, isKeyboardDismissDisabled, shouldCloseOnInteractOutside, placement/offset family, scoped slots). - Ship an independent consumer fixture for browser-level verification. --- apps/docs/components/dropdown.md | 136 +++++---- docs/migrations/B01-complete-review.md | 69 +++++ docs/migrations/B01-fidelity-audit.md | 12 +- docs/migrations/B01-menu-dropdown.md | 23 ++ docs/verification.md | 20 ++ packages/styles/components/dropdown.css | 18 +- .../src/components/dropdown/DropdownItem.vue | 41 ++- .../src/components/dropdown/DropdownMenu.vue | 49 +++- .../components/dropdown/DropdownPopover.vue | 188 +++++++++++-- .../src/components/dropdown/DropdownRoot.vue | 4 + .../components/dropdown/DropdownSection.vue | 41 ++- .../dropdown/DropdownSubmenuTrigger.vue | 194 ++++++++++--- .../components/dropdown/DropdownTrigger.vue | 51 +++- .../vue/src/components/menu-item/MenuItem.vue | 71 ++++- .../components/menu-section/MenuSection.vue | 11 +- packages/vue/src/components/menu/Menu.vue | 153 ++++++++-- packages/vue/src/components/menu/context.ts | 34 ++- .../src/components/menu/useMenuSelection.ts | 10 +- tests/b01-complete-review.probe.test.ts | 243 ++++++++++++++++ tests/b01-menu-dropdown.test.ts | 266 +++++++++++++++++- tests/package/b01-consumer-app/README.md | 29 ++ tests/package/b01-consumer-app/index.html | 13 + tests/package/b01-consumer-app/main.js | 214 ++++++++++++++ tests/package/b01-consumer-app/style.css | 16 ++ tests/package/b01-wrapper-props-review.ts | 18 ++ 25 files changed, 1721 insertions(+), 203 deletions(-) create mode 100644 docs/migrations/B01-complete-review.md create mode 100644 tests/b01-complete-review.probe.test.ts create mode 100644 tests/package/b01-consumer-app/README.md create mode 100644 tests/package/b01-consumer-app/index.html create mode 100644 tests/package/b01-consumer-app/main.js create mode 100644 tests/package/b01-consumer-app/style.css create mode 100644 tests/package/b01-wrapper-props-review.ts diff --git a/apps/docs/components/dropdown.md b/apps/docs/components/dropdown.md index 59e7a20..c569af7 100644 --- a/apps/docs/components/dropdown.md +++ b/apps/docs/components/dropdown.md @@ -252,6 +252,8 @@ Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类 所有部件接受 `class`、`style`、ARIA 与原生事件(`DropdownSubmenuTrigger` 会把它们合并到它的条目元素上)。选择集合使用 Vue 数组模型(`MenuKey[]`),不使用 React `Set`/`Selection`。标记「Vue 扩展」的属性在官方 HeroUI 中没有对应项。 +弹层默认通过 Portal 挂载到 `document.body`(可用 `to` 指定目标),层级为 `--z-index-overlay`,因此不会被祖先的 `overflow`、`contain` 或 `isolation` 裁切;面板高度受底层可用的浮动高度约束并自动滚动。 + ### DropdownRoot | Prop | 类型 | 默认值 | 描述 | @@ -264,7 +266,7 @@ Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类 | `dir` | `'ltr' \| 'rtl'` | — | **Vue 扩展**:文本方向 | | `longPressDuration` | `number` | `500` | **Vue 扩展**:长按时长 ms;移动超过 10px 取消 | -长按模式下 Enter/Space 仍可键盘打开;`pointerup`/`pointercancel`/`pointerleave`/卸载会清理计时。 +长按模式下 Enter/Space 仍可键盘打开,并且真实触发器上的 `keydown` 处理器先执行,可 `preventDefault()` 取消打开;`pointerup`/`pointercancel`/`pointerleave`/卸载会清理计时。 ### DropdownTrigger @@ -273,54 +275,74 @@ Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类 | `asChild` | `boolean` | `true` | 将触发合并到唯一子节点(默认行为) | | `as` | `string` | — | 自定义触发元素标签 | -页面里的 `Button` props 写在内部的 `Button` 上。子节点若不是原生可聚焦元素(例如 Avatar),组件会补 `role="button"` 与 `tabindex="0"`,保持官方「触发器可键盘操作」的行为。 +默认插槽会收到 `{ isOpen }`。页面里的 `Button` props 写在内部的 `Button` 上。子节点若不是原生可聚焦元素(例如 Avatar),组件会补 `role="button"` 与 `tabindex="0"`,保持官方「触发器可键盘操作」的行为。 ### DropdownPopover -| Prop | 类型 | 默认值 | 描述 | -| ------------------ | --------- | ------ | ------------------------------------- | -| `side` / `align` | `string` | — | 相对触发器的位置。官方用 `placement` | -| `sideOffset` | `number` | — | 侧边偏移。官方名 `offset` | -| `alignOffset` | `number` | — | 交叉轴偏移。官方名 `crossOffset` | -| `avoidCollisions` | `boolean` | — | 碰撞翻转。官方名 `shouldFlip` | -| `collisionPadding` | `number` | — | 边界内边距。官方名 `containerPadding` | -| `loop` | `boolean` | — | **Vue 扩展**:焦点循环 | +| Prop | 类型 | 默认值 | 描述 | +| ------------------------------ | ----------------------- | ---------- | ---------------------------------------------------- | +| `placement` | `OverlayPlacement` | `'bottom'` | 相对于触发器的位置(复用本库 Popover 的取值)。 | +| `offset` | `number` | `0` | 与触发器的距离。 | +| `crossOffset` | `number` | `0` | 交叉轴偏移。 | +| `shouldFlip` | `boolean` | `true` | 空间不足时翻转。 | +| `containerPadding` | `number` | `12` | 与视口边缘保留的距离。 | +| `isKeyboardDismissDisabled` | `boolean` | `false` | 禁用 Escape 关闭。 | +| `shouldCloseOnInteractOutside` | `(event) => boolean` | — | 返回 `false` 时外部交互不关闭菜单。 | +| `to` | `string \| HTMLElement` | — | Portal 目标,默认 `document.body`。 | +| `side` / `align` | `string` | — | **底层扩展**:直接指定浮动方向,优先于 `placement`。 | +| `sideOffset` / `alignOffset` | `number` | — | **底层扩展**:覆盖 `offset` / `crossOffset`。 | +| `avoidCollisions` | `boolean` | — | **底层扩展**:覆盖 `shouldFlip`。 | +| `collisionPadding` | `number` | — | **底层扩展**:覆盖 `containerPadding`。 | +| `loop` | `boolean` | — | **底层扩展**:焦点循环。 | + +默认插槽会收到 `{ isEntering, isExiting, placement }`。 ### DropdownMenu -| 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` | +| Prop | 类型 | 默认值 | 描述 | +| ----------------------------------------- | ---------------------------------- | -------- | ---------------------------------------------------- | +| `selectionMode` | `'none' \| 'single' \| 'multiple'` | `'none'` | 是否启用单选、多选或不启用选择。 | +| `selectedKeys` | `MenuKey[]` | — | 当前选中的 key(受控)。 | +| `defaultSelectedKeys` | `MenuKey[]` | `[]` | 初始选中的 key(非受控)。 | +| `disabledKeys` | `MenuKey[]` | `[]` | 禁用项的 key。 | +| `disallowEmptySelection` | `boolean` | `false` | 禁止用户清空已有选择。 | +| `shouldCloseOnSelect` | `boolean \| (key) => boolean` | — | 菜单级关闭策略;默认动作项与单选关闭、多选保持打开。 | +| `shouldFocusWrap` | `boolean` | — | 键盘导航在首尾循环。 | +| `autoFocus` | `boolean` | `true` | 打开时聚焦菜单。 | +| `escapeKeyBehavior` | `'clearSelection' \| 'none'` | `'none'` | `clearSelection` 时 Escape 清空选择且不关闭菜单。 | +| `update:selectedKeys` / `selectionChange` | 事件 `(keys: MenuKey[])` | — | 选中变化时触发。官方名 `onSelectionChange` | +| `action` | 事件 `(key: MenuKey)` | — | 激活菜单项时触发。官方名 `onAction` | +| `close` | 事件 `()` | — | 该层菜单关闭时触发。官方名 `onClose` | + +默认插槽渲染条目;`empty` 插槽在该菜单没有条目时渲染(对应官方 `renderEmptyState`)。数据驱动的 `items` 用 `v-for` 表达。 ### DropdownSection -| Prop | 类型 | 默认值 | 描述 | -| ----------------------------------------- | ------------------------ | ------ | ------------------------------------------ | -| `selectionMode` | `'single' \| 'multiple'` | — | 该分组内菜单项的选择模式;省略则继承菜单。 | -| `selectedKeys` | `MenuKey[]` | — | 当前选中的 key(受控)。 | -| `defaultSelectedKeys` | `MenuKey[]` | `[]` | 初始选中的 key(非受控)。 | -| `disabledKeys` | `MenuKey[]` | `[]` | 禁用项的 key。 | -| `update:selectedKeys` / `selectionChange` | 事件 `(keys: MenuKey[])` | — | 选中变化时触发。官方名 `onSelectionChange` | +| Prop | 类型 | 默认值 | 描述 | +| ----------------------------------------- | ------------------------ | ------- | -------------------------------------------- | +| `selectionMode` | `'single' \| 'multiple'` | — | 该分组内菜单项的选择模式;省略则继承菜单。 | +| `selectedKeys` | `MenuKey[]` | — | 当前选中的 key(受控)。 | +| `defaultSelectedKeys` | `MenuKey[]` | `[]` | 初始选中的 key(非受控)。 | +| `disabledKeys` | `MenuKey[]` | `[]` | 禁用项的 key,与菜单级 `disabledKeys` 叠加。 | +| `disallowEmptySelection` | `boolean` | `false` | 禁止用户清空该分组的选择。 | +| `update:selectedKeys` / `selectionChange` | 事件 `(keys: MenuKey[])` | — | 选中变化时触发。官方名 `onSelectionChange` | -分组内嵌套的 `Header` 会自动成为分组的可访问名称来源(`aria-labelledby`)。 +分组内嵌套的 `Header` 会自动成为分组的可访问名称来源(`aria-labelledby`)。分组内再嵌套的 `Menu` 会重置选择作用域,不会继承外层分组的 owner。 ### DropdownItem -| Prop | 类型 | 默认值 | 描述 | -| --------------- | ----------------------- | ----------- | ---------------------------------------------------------------- | -| `id` | `MenuKey` | — | 菜单项唯一标识,同时作为元素 `id`。 | -| `textValue` | `string` | — | 用于首字母导航的文本内容。 | -| `variant` | `'default' \| 'danger'` | `'default'` | 菜单项视觉变体。 | -| `isDisabled` | `boolean` | `false` | 禁用该项。 | -| `closeOnSelect` | `boolean` | — | `false` 时动作项激活后保持菜单打开。官方名 `shouldCloseOnSelect` | -| `select` | 事件 `(key: MenuKey)` | — | **Vue 扩展**:条目激活回调 | +| Prop | 类型 | 默认值 | 描述 | +| ------------------------------------------------------------- | ----------------------- | ----------- | ------------------------------------------------------------------------- | +| `id` | `MenuKey` | — | 业务 key(选择与动作使用)。DOM id 为实例级,与业务 key 无关。 | +| `textValue` | `string` | — | 用于首字母导航的文本内容。 | +| `variant` | `'default' \| 'danger'` | `'default'` | 菜单项视觉变体。 | +| `isDisabled` | `boolean` | `false` | 禁用该项。 | +| `closeOnSelect` | `boolean` | — | 覆盖关闭策略;`false` 保持打开,`true` 关闭。官方名 `shouldCloseOnSelect` | +| `href` | `string` | — | 渲染为链接型菜单项(真实 ``)。 | +| `target` / `rel` / `download` / `hrefLang` / `referrerPolicy` | — | — | 透传到链接元素。 | +| `select` | 事件 `(key: MenuKey)` | — | **Vue 扩展**:条目激活回调 | -默认插槽会收到 `{ isSelected, isFocused, isDisabled, isPressed }`,对应官方的 Render Props。 +默认插槽会收到 `{ isSelected, isFocused, isDisabled, isPressed }`,对应官方的 Render Props。禁用链接不会导航;`href` 项的原生导航不受 `click` 处理器影响(除非调用 `preventDefault()`)。 ### DropdownItemIndicator @@ -338,19 +360,20 @@ Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类 ### DropdownSubmenuIndicator -| 内容 | 说明 | -| ---- | ---------------------------------------- | -| 默认 | 官方内置的 chevron-right 图标 | -| 插槽 | 自定义指示器内容;只有带子菜单的项才渲染 | +| 内容 | 说明 | +| ---- | ------------------------------------ | +| 默认 | 官方内置的 chevron-right 图标 | +| 插槽 | 自定义指示器内容;带子菜单的项才渲染 | ### DropdownSubmenuTrigger -| Slots / Props | 说明 | -| ------------- | -------------------------------------------------- | -| 默认插槽 | 第一个子节点是触发条目,其余子节点渲染进子菜单内容 | -| `class`/ARIA | 合并到触发条目元素上 | +| Slots / Props | 说明 | +| ------------- | --------------------------------------------------------------------------------------------------------------------- | +| 默认插槽 | 第一个子节点是触发条目,其余子节点渲染进子菜单内容 | +| `class`/ARIA | 合并到触发条目元素上 | +| 面板参数 | 嵌套 `DropdownPopover` 的 `offset`/`crossOffset`/`shouldFlip`/`containerPadding`/`loop`/`to`/`class` 会传给子菜单面板 | -每层子菜单独立持有 open 状态;焦点在子菜单内按 Esc 只关闭当前层,焦点回到该层触发器。 +每层子菜单独立持有 open 状态并各自 Portal;焦点在子菜单内按 Esc 只关闭当前层,焦点回到该层触发器。子菜单的 `side`/`align` 由底层固定为「贴着父项向右展开」(RTL 反向),只有偏移与碰撞参数可调。 ### Render Props @@ -363,27 +386,32 @@ Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类 | `isDisabled` | `boolean` | 该项是否禁用。 | | `isPressed` | `boolean` | 该项是否处于按下状态。 | +### 独立 Menu + +`Menu` 可以在 `DropdownPopover` 之外直接使用:渲染为静态内联列表(`data-slot="menu"`),保留 `role="menu"`、条目语义、键盘导航与选择;不会锁定页面滚动、不会拦截外部指针事件、不会抢焦点,也不做浮动定位。 + ## 无障碍 Dropdown 组件实现 ARIA 菜单模式,并提供: -- 完整键盘导航(方向键、Home/End、首字母导航) -- 屏幕阅读器对操作与选中变化的播报 -- 合理的焦点管理(关闭后焦点回到触发器) -- 禁用态支持 +- 完整键盘导航(方向键、Home/End、首字母导航,`shouldFocusWrap` 控制首尾循环) +- 屏幕阅读器对操作与选中变化的播报:`aria-label`/`aria-labelledby`/`aria-describedby` 落在真正的 `role="menu"` 节点上 +- 合理的焦点管理(关闭后焦点回到触发器,Esc 逐层关闭) +- 禁用态支持(`[data-disabled]` + `aria-disabled`) - 长按交互支持 -- 子菜单导航,Esc 逐层关闭 +- 子菜单导航 -菜单使用 `role="menu"` / `menuitem`(选择项为 `menuitemradio` / `menuitemcheckbox`);禁用项跳过,不进入 Tab 顺序。 +菜单使用 `role="menu"` / `menuitem`(选择项为 `menuitemradio` / `menuitemcheckbox`),每个弹层只有一个 `role="menu"`;禁用项跳过,不进入 Tab 顺序。 ## 上游差异 - 部件导出为具名组件(`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)。 +- `Selection`/`Set` 改为 `MenuKey[]`;`onAction`/`onSelectionChange`/`onClose` 改为 Vue 事件;`isOpen`/`onOpenChange` 改为 `open` + `v-model:open`。 +- 官方 `items` + 渲染函数的数据驱动集合用 `v-for` 表达;`renderEmptyState` 对应 `empty` 插槽。不提供 React Collection 对象模型。 +- 子菜单悬停展开延迟由底层固定为 100ms,未暴露官方 `delay`(默认 200ms);子菜单面板的 `side`/`align` 由底层固定,只有偏移与碰撞参数可调。 +- `DropdownTrigger` 的作用域插槽只提供 `{ isOpen }`,`DropdownPopover` 只提供 `{ isEntering, isExiting, placement }`;官方 Button/Popover 的完整 render props 未全部覆盖。 - `DropdownRoot` 额外渲染一层 `.hv-dropdown` 包裹元素(官方该类没有 DOM 宿主),用于承载根级 class 与方向。 +- 条目 `id` 是业务 key,DOM id 为实例级;官方把 key 直接作为 DOM id(Vue 端避免数字 `0` 与字符串 `"0"` 冲突)。 - 条目 `onClick` 中 `preventDefault()` 会取消动作、选择与关闭;`stopImmediatePropagation()` 会终止后续处理器,均为原生事件语义。 ## 相关组件 diff --git a/docs/migrations/B01-complete-review.md b/docs/migrations/B01-complete-review.md new file mode 100644 index 0000000..d6c592c --- /dev/null +++ b/docs/migrations/B01-complete-review.md @@ -0,0 +1,69 @@ +# B01 整批复核与统一返修清单 + +2026-10-24,检查 `feat/b01-menu-dropdown` / `043a541`。这是本批当前的合并清单:**暂不通过,不合main**。前两轮记录保留为历史;后续按本文件逐项闭环,不再仅根据某一组旧探针宣称整批完成。当前不要求SSR、水合、Nuxt。 + +## 复核范围及结果 + +已读固定上游ce90ea3的Dropdown中文正文/API、Menu/Item/Section/Dropdown源码、CSS,以及当前全部家族实现、17预览和迁移者自查。检查了包根导出、生成的组件声明、独立消费脚本。浏览器5181重点验根/多级菜单、分组级选择的遮挡、Modal组合关闭/滚动锁;补查状态所有权、取消、名称、主题和类型。 + +- 旧B01两文件34项通过,上轮短点击/Enter/处理器数组/Esc探针对应修复已生效。 +- 新 `tests/b01-complete-review.probe.test.ts`:13项中12项失败,1项通过(禁用真实长按按钮未打开)。均测试浏览器端契约,没有新增SSR专项。 +- 全量 `pnpm test`:72文件,71通过/1失败;910项,898通过/12失败。失败均在新增整批回归文件。 +- 原类型检查通过;加入真实组件$props消费正例 `tests/package/b01-wrapper-props-review.ts` 后出现3项TS2353,暴露包装组件类型缺失。 +- 浏览器遮挡截图:`/private/tmp/b01-layering-review.png`。临时组合夹具保存于 `/private/tmp/b01-review-fixture.md`,已从文档目录删除,不新增产品导航/页面。 +- 未重做物理触屏、读屏、逐像素或最终修复后的独立浏览器打包消费,不冒充已通过。 + +## 一、必须修复的真实问题(统一按下表验收) + +| ID | 优先级 | 问题、证据与修复边界 | +| --- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| R1 | P1 | **弹层挂载/堆叠/裁切错误**。根与子菜单均未Portal,留在触发器DOM树;浏览器定位包装层/面板z-index=auto,祖先`.preview` isolation:isolate、`.component-preview-container` contain:content。实际打开“分组级选择”时面板rect.top=-5.02、height=424,而所属preview.top=261.48,上半菜单被上一演示代码块/导航遮住。使用本库弹层/ConfigProvider的挂载目标与层级约定(支持必要的目标配置),根/子菜单脱离裁切祖先,正确处于父Modal之上及Toast约定之下。禁止改全站contain/isolation或仅塞巨型z-index;修复后验证overflow:hidden/transform祖先、相邻代码、sticky导航、视口边缘、Modal/Popover/Drawer内菜单及多级子菜单。 | +| R2 | P1 | **独立Menu把普通页面变成不可关闭的模态弹层**。Menu用`DropdownMenuRoot open=true`+Content兜底,默认modal,挂载即body overflow:hidden、pointer-events:none/隐藏外部内容,无触发器且close无法改变常量open。新回归复现。独立Menu应是可组合的菜单容器,不能仅为消除注入异常引入永久滚动锁、浮动定位与抢焦点。与Dropdown内复用容器的路径分别验,不增加重复menu/焦点容器。 | +| R3 | P1 | **选择/禁用所有权隔离错误**。Section只传disabledKeys、不自持选择时,其禁用列表被忽略;Section自持选择时,Menu级disabledKeys又被忽略;Section下的新Menu仍注入旧Section owner,`selectionMode=none`内项被渲染成menuitemcheckbox。3项回归失败。明确根/分组禁用的组合规则、新菜单作用域重置和受控接受值,不能通过修改共享collection/field内核掩盖本家族问题。 | +| R4 | P1 | **显式closeOnSelect对选择项失效**。single+false仍关闭,multiple+true仍保持打开(两项回归失败)。默认按模式选择关闭策略可以保留,显式条目/菜单策略应有明确优先级;鼠标/键盘、Section owner、父级拒绝选择/拒绝关闭都要一致。 | +| R5 | P1 | **集合key直接变DOM id,制造碰撞及错误ARIA关联**。数字0和字符串'0'在选择模型中不同,但均渲染id='0',跨菜单重复业务key也重复ID。新回归失败。区分实例DOM id与业务key,保持0/'0'/空串等key语义;子菜单aria-labelledby应指真实本实例触发器,不能靠全局getElementById“找到任意同名id就算成功”。兼顾显式ARIA与卸载/重挂/动态key,不以改变业务key解决。 | +| R6 | P1 | **长按取消/子菜单用户事件被吞**。真实Trigger的onKeydown.preventDefault仍打开,因为包裹层capture提前setOpen;嵌套Popover的onKeydown被SubContent内部onKeydown覆盖,用户回调一次都不执行。两项回归失败。用户处理器与内部处理器正确合并/取消,取消后不更新open/选择/关闭;同时复核pointerdown取消、contextmenu、子菜单Esc取消、animationend等内部覆写点,不再手工遍历处理器或读Vue私有字段。 | +| R7 | P1 | **链接项能力缺失**。`DropdownItem href='/target' target='_blank'`实际为DIV,不能导航(回归失败)。源契约及原任务明确含链接项。Reka MenuItem继承PrimitiveProps可用as/asChild组合锚点,不能称底座没有锚点路径而直接删能力。提供真实anchor语义、禁用、键盘/修饰键/新标签行为与事件取消;不要通过click里window.open模拟原生链接,也不因此切换整套底座。 | +| R8 | P2 | **可访问名称落错DOM**。`DropdownMenu aria-label='File actions'`停在无role的内层div,真正role=menu的Reka Content没有此名称(回归失败)。标签/描述/ARIA归属应落到真正语义节点;同步检查Item内Label/Description以及Section标题的关联与动态清理。不能重新给内层加第二个role=menu。 | +| R9 | P2 | **子菜单面板的定位/attrs并未等价透传**。inheritableAttrs只接受class/style/id/ARIA/data/事件,`DropdownPopover side/align/sideOffset/alignOffset/avoidCollisions/collisionPadding/loop`等面板props被过滤;嵌套Popover自身又只返回Fragment。根/子菜单同一公开部件不能在子菜单内静默忽略参数。区分SubTrigger props和SubContent props,正确归属并补行为/类型说明;用户ref不应无记录被cloneVNode替换。 | +| R10 | P2 | **Surface上下文未重置**。上游DropdownPopover显式provide Surface default,当前没有。外层Surface secondary下,弹层内部仍收到secondary(回归失败),嵌入Input等会取错主题。根和子面板都应按现有Popover约定局部提供default,不改Surface全局行为。 | +| R11 | P2 | **动画原点与高度约束没有映射**。CSS依赖`--trigger-anchor-point`,浏览器实际为空;Reka提供`--reka-dropdown-menu-content-transform-origin='50% 0px'`,计算原点却为110px 81px(面板中心)。应映射真实浮动原点;max-height当前none而可用高度264.98px,需约束长菜单可滚动,不能让菜单超视口或首尾项不可达。根/子菜单的进入退出、碰撞翻转、reduced-motion一起验。 | +| R12 | P2 | **实际Vue组件类型仍为空Props**。DropdownItem/Menu/Section等包装实现没有声明props,仅通过attrs转发;生成DropdownItem.vue.d.ts为DefineComponent<{}>。另导出一份正确别名不能修复实际组件类型。有效`InstanceType['$props']={id:'item',variant:'danger'}`及Menu/Section正例产生TS2353。修正所有包装部件本身的Props/Emits/Slots,并核对固定源Root别名/Props别名(如MenuItemRoot/MenuSectionRoot等);独立tarball中用真实组件和类型正反例验证,而非只测别名对象。 | + +### 新探针对应关系 + +- Section禁用两项、子Menu作用域一项 → R3。 +- single/multiple显式关闭策略两项 → R4。 +- typed key DOM id → R5。 +- 独立Menu滚动锁 → R2。 +- 链接项 → R7。 +- 长按取消、子菜单keydown → R6。 +- 真正menu节点名称 → R8。 +- Surface → R10。 +- 禁用真实长按按钮一项通过,勿将其也列成失败。 + +## 二、能力差异要一次性说明,不能仅写“17预览完成” + +迁移者自查A21承认但当前公共页面未完整列出的能力:disallowEmptySelection、escapeKeyBehavior、shouldFocusWrap/loop、autoFocus、onClose、items/renderEmptyState、菜单级shouldCloseOnSelect、isKeyboardDismissDisabled、shouldCloseOnInteractOutside、Popover/Trigger作用域插槽;此外子菜单delay未提供。先按固定源实际公开类型逐项核验,避免用最新版文档扩大基线。 + +处理原则: + +- 上表涉及的可感知交互/关闭/禁用/焦点/导航能力不能以“Reka差异”直接删掉。补齐最小等价API和验证。 +- 不要求搬React Collection/Set/RenderFunction;`v-for`/数组/空状态插槽/作用域插槽是可接受Vue表达,但要提供对应能力和用法,而非把能力一起删掉。 +- `placement/offset/...`改成side/align并非Vue语法必需,本库Popover已有resolvePlacement及同名接口。优先复用既有公开定位契约;若保留底层属性作扩展,要确保源能力不丢、默认值/RTL一致,不让同库两个弹层组件无理由各用一套API。 +- 不能把未实现能力藏在审计文件里,同时在compatibility/正文宣称完整。对确需延后而非本次范围内实现的项明确能力边界,不以文档声明代替上表修复。 + +## 三、当前已修/可保留项 + +- 上轮的普通短点击/Enter重复切换、用户stopImmediatePropagation数组问题已修;选择role/aria-checked和指示器状态已补。 +- 浏览器真实验证:含子菜单先Esc关闭子层,焦点回该触发器,根菜单保留;再Esc回根触发器。嵌套Modal中同样逐层保留,最终关闭Modal后body overflow/pointer-events均恢复空值、焦点回“打开组合复核”。这部分无需重写共享overlay。 +- 明确DropdownTrigger包裹、具名导出、Vue事件/v-model、数组键模型、Tabler图标、库类名前缀、必要根包装是合理适配。 +- 17示例次序/主要文案/图标/代码同源和本轮已修正文无需推倒重做,按原清单保持。 + +## 四、验收证据的缺口与统一收口方式 + +当前consume-b01-menu-dropdown.mjs只检查导出对象存在和CSS字符串,不挂载组件、不构建浏览器应用,不能称已验证独立浏览器使用。需用打包产物安装到独立Vue消费页,真实挂载一个选择菜单、多级菜单和嵌套Modal,验证ESM/CSS/真实类型,不增加SSR要求。 + +新回归加入test:unit显式入口(pnpm test会自动发现);保留本次13项行为和3项类型正例,不删断言/改成接受错误。逐项填R1–R12“实现位置→测试/浏览器证据→文档差异”;同时闭环上节全部能力清单。仅重点浏览器验遮挡/长菜单/子菜单/外部点击/嵌套关闭/长按/焦点/浅深色与RTL,不机械点击所有演示。 + +集成时不要覆盖其他人的Toast/Table、文档壳层及新批次清单;继续B01独立分支返修,不自行合main/推送,不提前开下一批。未验证的读屏/物理触屏/逐像素明确保留;SSR/水合/Nuxt不作为当前门槛。 diff --git a/docs/migrations/B01-fidelity-audit.md b/docs/migrations/B01-fidelity-audit.md index 7a3ee91..d90d03f 100644 --- a/docs/migrations/B01-fidelity-audit.md +++ b/docs/migrations/B01-fidelity-audit.md @@ -102,9 +102,11 @@ ### 仍保留 / 未修 -- **A5**:链接型菜单项(`href`/`target`)未实现——Reka 菜单项没有锚点路径,需自建或换底座;文档已写明不支持。 -- **A18**:子菜单悬停延迟由 Reka 固定 100ms,未暴露官方 `delay`。 -- **A19**:长按键盘用 Enter/Space(本批复核明确要求),与 RAC 文档的 Alt+↓ 不同。 +> 上表状态为忠实度审计当轮结果;`A5`(链接项)与 `A21` 中的多数能力已在随后的[整批复核返修](B01-complete-review.md)中补齐,以下为当前实际边界。 + +- **A5**:链接型菜单项已实现(`href` 渲染真实 ``,保留 `target/rel` 等,禁用项阻止导航);剩余差异仅是 key 与 DOM id 分离。 +- **A18**:子菜单悬停延迟由底层固定 100ms,未暴露官方 `delay`;子菜单面板 `side/align` 也由底层固定。 +- **A19**:长按键盘用 Enter/Space(本批复核要求),与 RAC 文档的 Alt+↓ 不同;长按计时 500ms、10px 取消为自定实现。 - **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 适配,文档已登记。 +- **A21**:`disallowEmptySelection`、`escapeKeyBehavior`、`shouldFocusWrap`、`autoFocus`、`close`、`renderEmptyState`(`empty` 插槽)、菜单级 `shouldCloseOnSelect`、`isKeyboardDismissDisabled`、`shouldCloseOnInteractOutside`、`placement` 系列已补齐;`items` 以 `v-for` 表达;Trigger/Popover 作用域插槽为官方 render props 的子集(`{isOpen}` / `{isEntering,isExiting,placement}`)。 +- **B1/B7**:显式 `DropdownTrigger` 包裹触发器、`Selection`→`MenuKey[]`(含无 `"all"`)为既定 Vue API 适配,文档已登记。 diff --git a/docs/migrations/B01-menu-dropdown.md b/docs/migrations/B01-menu-dropdown.md index ed2b367..a486cc0 100644 --- a/docs/migrations/B01-menu-dropdown.md +++ b/docs/migrations/B01-menu-dropdown.md @@ -82,3 +82,26 @@ default、with-icons、with-descriptions、with-disabled-items、with-sections 按官方 `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"]`。 + +## 整批复核返修(2026-10-24) + +按 [B01 整批复核与统一返修清单](B01-complete-review.md) 处理 R1–R12 与能力清单。新增探针 `tests/b01-complete-review.probe.test.ts` **13/13**、类型正例 `tests/package/b01-wrapper-props-review.ts` 通过。 + +| ID | 实现位置 | 测试 / 浏览器证据 | 文档 | +| --- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | +| R1 | `DropdownPopover` / `DropdownSubmenuTrigger` 接入 `DropdownMenuPortal`(`to` 可配);`.hv-dropdown__popover` 增加 `z-index: var(--z-index-overlay)` | 单测:面板不在 `contain/isolation` 祖先内;浏览器:面板父节点为 popper 包装层且位于 body,rect 57–383(视口 709),首末项均可见,z-index 100000;Modal 内面板在 backdrop 之后挂载(DOM 顺序 4 > 3),Esc 先关菜单再关 Modal,关闭后 body 样式清空、焦点回触发器 | 「弹层默认通过 Portal 挂载…」段 + DropdownPopover `to` 行 | +| R2 | `Menu` 独立路径改为 `modal: false` + 非 Portal + `data-static` + 阻止 auto focus;`.hv-dropdown__popover[data-static]` 的包装层用静态定位 | 探针 + 单测;浏览器:内联菜单 `body` 无内联样式、包装层 `position: static`、焦点留在 body、`role=menuitem` | 「独立 Menu」小节 | +| R3 | `MenuSection` 的禁用列表与菜单级叠加;`Menu` 提供 `menuSectionContextKey = null` 重置作用域 | 探针两项 + 单项「Section 下新 Menu 不继承 owner」 | DropdownSection 表 + 「分组内再嵌套的 Menu 会重置选择作用域」 | +| R4 | `MenuItem.shouldClose()`:条目 `closeOnSelect` > 菜单 `shouldCloseOnSelect` > 按模式默认(多选保持打开) | 探针两项(single+false 保持、multiple+true 关闭) | DropdownItem `closeOnSelect` 与 DropdownMenu `shouldCloseOnSelect` 行 | +| R5 | `MenuItem` 用实例级 `useId()` 作 DOM id,业务 key 只进 `data-key`/选择;子菜单 `aria-labelledby` 直接指向本实例触发器 | 探针(0 与 "0" 不重复)+ 单测(id 唯一、`data-key` 保持业务 key) | DropdownItem `id` 行 + 上游差异条 | +| R6 | 长按键:Enter/Space 的用户 `keydown` 先执行(capture 链),内部在 `defaultPrevented` 时才跳过打开;基准触发器的 toggle 在本次事件内被挂起 | 探针「取消的 keydown 不打开」+ 单测「Enter/Space 只切换一次」 | DropdownRoot 长按段 | +| R7 | `MenuItem.href/target/rel/download/hrefLang/referrerPolicy` → 渲染真实 ``;禁用项阻止导航 | 探针 + 单测(标签为 A、href/target 保留、action 仍触发、禁用时不导航) | DropdownItem 链接行 | +| R8 | `Menu` 把 `aria-label`/`aria-labelledby`/`aria-describedby` 通过内容通道写到真正的 `role="menu"` 节点 | 探针(`[role=menu]` 带 `File actions`)+ 浏览器(`水果操作`) | 无障碍段 + DropdownMenu 说明 | +| R9 | 子菜单面板接收嵌套 `DropdownPopover` 的 `offset/crossOffset/shouldFlip/containerPadding/loop/to/class/aria/事件`;用户 `keydown` 与内部 Escape 合并 | 探针(keydown 一次)+ 单测(panel class、keydown) | DropdownSubmenuTrigger「面板参数」行 | +| R10 | `DropdownPopover` 提供 `surfaceContextKey` 的 `default` 变体 | 探针(Surface secondary 下读回 default) | 无(行为与官方一致) | +| R11 | `origin` 改用 `--reka-dropdown-menu-content-transform-origin`;`max-height` 用 `--reka-dropdown-menu-content-available-height` | 浏览器:`transform-origin: 30px 0px`(真实浮动原点)、`max-height: 640px` 与 `overflow-y: auto` | 「面板高度受…约束」段 | +| R12 | `DropdownItem`/`DropdownMenu`/`DropdownSection` 补齐真实 props/emits,`DropdownSubmenuTriggerProps` 由组件推导 | `tests/package/b01-wrapper-props-review.ts` 在仓库与独立 tarball 中均通过(bundler + NodeNext) | 各部件 API 表 | + +能力清单同步落地:`disallowEmptySelection`、`escapeKeyBehavior`、`shouldFocusWrap`、`autoFocus`、`shouldCloseOnSelect`(菜单级)、`close` 事件、`empty` 插槽、`isKeyboardDismissDisabled`、`shouldCloseOnInteractOutside`、`Trigger`/`Popover` 作用域插槽(`{isOpen}` / `{isEntering,isExiting,placement}`)、`placement/offset/crossOffset/shouldFlip/containerPadding`(复用本库 Popover 取值);`items` 用 `v-for`、`renderEmptyState` 用 `empty` 插槽表达;子菜单 `delay` 与子菜单 `side/align` 作为底座固定值写入「上游差异」。 + +独立浏览器消费:夹具随仓库提供于 `tests/package/b01-consumer-app/`(选择长菜单、三级子菜单、Modal 内菜单、独立 Menu、链接项),tarball 安装后 esbuild 打包 + 静态服务,上述 R1/R2/R8/R11 结论均来自该页面实测。`consume-b01-menu-dropdown.mjs` 仍只做导出/CSS 存在性检查,真实挂载以该夹具为准。 diff --git a/docs/verification.md b/docs/verification.md index 6441ab5..ffe8929 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -941,3 +941,23 @@ Button/PopoverTrigger/Link/ToggleButtonGroup 源码及几何复核后,移除 - **文档**:`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 仍未验证。 + +### B01 整批复核返修(同日) + +按 [整批复核清单](migrations/B01-complete-review.md) 处理 R1–R12,新增 `tests/b01-complete-review.probe.test.ts` **13/13**(含禁用真实长按按钮一项保持通过)与类型正例 `tests/package/b01-wrapper-props-review.ts`。 + +- **R1 弹层挂载**:根与子菜单面板都经 Portal 挂到 body(`to` 可配),层级 `--z-index-overlay`。独立消费页里,带 `overflow:hidden/contain:content/isolation:isolate` 的祖先不再裁切面板:面板父节点是 popper 包装层、位于 body,rect 57–383(视口 709),首末项可见,z-index 100000。 +- **R2 独立 Menu**:不再用模态兜底。浏览器实测内联列表 `body` 无内联样式、包装层计算 `position: static`、焦点留在页面、条目 `role=menuitem`。 +- **R3 所有权隔离**:Section 禁用列表与菜单级叠加;Section 下的新 Menu 重置选择作用域(不再渲染成 `menuitemcheckbox`)。 +- **R4 关闭策略**:条目 `closeOnSelect` > 菜单 `shouldCloseOnSelect` > 按模式默认(single/动作关闭、multiple 保持)。 +- **R5 key 与 DOM id**:业务 key 不再作 DOM id,实例 id 唯一,`0` 与 `"0"` 不冲突;子菜单 `aria-labelledby` 指向本实例触发器(浏览器与单测均验证)。 +- **R6 事件取消**:Enter/Space 先跑调用方 `keydown`,被取消时不打开;基准触发器的 toggle 在本次事件内被挂起,仍只切换一次。子菜单面板合并调用方 `keydown` 与内部 Escape。 +- **R7 链接项**:`href` 项渲染真实 ``(保留 `target/rel` 等),禁用项阻止导航。 +- **R8 可访问名称**:`aria-label` 等落在真正的 `role="menu"` 节点(浏览器读到「水果操作」)。 +- **R9 子菜单参数**:嵌套 `DropdownPopover` 的偏移/碰撞/`loop`/`to`/class/事件透传到子菜单面板;`side/align` 为底座固定值,已写入差异。 +- **R10 Surface**:弹层局部提供 `default` 变体,嵌入字段不会继承外层 secondary。 +- **R11 动画原点与高度**:`transform-origin` 取到底座浮动原点(实测 `30px 0px`),`max-height` 取可用高度(实测 640px)+ `overflow-y:auto`。 +- **R12 组件类型**:包装部件补齐真实 props/emits,真实组件 `$props` 正例在仓库与独立 tarball 的 bundler/NodeNext 下均通过。 +- **能力清单**:`disallowEmptySelection`、`escapeKeyBehavior`、`shouldFocusWrap`、`autoFocus`、菜单级 `shouldCloseOnSelect`、`close` 事件、`empty` 插槽、`isKeyboardDismissDisabled`、`shouldCloseOnInteractOutside`、`placement/offset/crossOffset/shouldFlip/containerPadding`、Trigger/Popover 作用域插槽已提供;`items` 以 `v-for`、`renderEmptyState` 以 `empty` 插槽表达,子菜单 `delay` 与 `side/align` 作为底座固定值记录在页面「上游差异」。 +- **独立浏览器消费**:`tests/package/b01-consumer-app/` 夹具用 tarball 安装后 esbuild 打包、静态服务,实测分组级多选、三级子菜单、链接项、Modal 内菜单(Esc 先关菜单再关 Modal,body 样式清空、焦点回触发器)与独立 Menu。控制台仅有 Vue feature flag 提示,无组件告警或错误。 +- 回归:**72 文件 / 917 项**通过;typecheck、build:docs、Prettier 通过。仍未验证:完整读屏、物理触屏、逐像素对比、Nuxt/SSR(本批不要求)。 diff --git a/packages/styles/components/dropdown.css b/packages/styles/components/dropdown.css index 6f5db3c..193dd3d 100644 --- a/packages/styles/components/dropdown.css +++ b/packages/styles/components/dropdown.css @@ -51,11 +51,16 @@ display: flex; } -/* Similar to select popover styles */ +/* Similar to select popover styles. + Reka publishes the floating origin and the available height as + `--reka-...-content-*` variables on the surface, so the ported animation + origin and the long-menu height cap map onto real values. */ .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; + @apply max-w-[48svw] origin-(--reka-dropdown-menu-content-transform-origin) scroll-py-1 scrollbar overflow-y-auto overscroll-contain bg-overlay p-0 text-sm md:min-w-55; border-radius: min(32px, var(--radius-3xl)); box-shadow: var(--overlay-shadow); + z-index: var(--z-index-overlay); + max-height: var(--reka-dropdown-menu-content-available-height, none); &:focus-visible:not([data-focused]), &[data-focus-visible="true"] { @@ -128,3 +133,12 @@ @apply ms-[3%] w-[94%]; } } + +/* Standalone Menu keeps the base menu semantics but must stay in the normal + flow: the positioning wrapper is neutralised for that surface only. */ +[data-reka-popper-content-wrapper]:has(> .hv-dropdown__popover[data-static]) { + position: static !important; + inset: auto !important; + transform: none !important; + min-width: 0 !important; +} diff --git a/packages/vue/src/components/dropdown/DropdownItem.vue b/packages/vue/src/components/dropdown/DropdownItem.vue index c995b53..35f8846 100644 --- a/packages/vue/src/components/dropdown/DropdownItem.vue +++ b/packages/vue/src/components/dropdown/DropdownItem.vue @@ -1,12 +1,47 @@ diff --git a/packages/vue/src/components/dropdown/DropdownMenu.vue b/packages/vue/src/components/dropdown/DropdownMenu.vue index 52f907d..4355e62 100644 --- a/packages/vue/src/components/dropdown/DropdownMenu.vue +++ b/packages/vue/src/components/dropdown/DropdownMenu.vue @@ -1,12 +1,55 @@ diff --git a/packages/vue/src/components/dropdown/DropdownPopover.vue b/packages/vue/src/components/dropdown/DropdownPopover.vue index 541b0ee..dcb897f 100644 --- a/packages/vue/src/components/dropdown/DropdownPopover.vue +++ b/packages/vue/src/components/dropdown/DropdownPopover.vue @@ -8,20 +8,26 @@ import { provide, ref, useAttrs, + watchEffect, type PropType, type Ref, } from "vue"; import { DropdownMenuContent as RekaDropdownMenuContent, + DropdownMenuPortal as RekaDropdownMenuPortal, injectDropdownMenuRootContext, } from "reka-ui"; import { dropdownVariants } from "@heroui-vue/styles"; import { dropdownContextKey, menuCloseKey, + menuContentAttrsKey, submenuContentKey, } from "../menu/context"; import { useOverlayAnimation } from "../overlay/animation"; +import { resolvePlacement, type OverlayPlacement } from "../overlay/placement"; +import { useConfig } from "../../providers/context"; +import { surfaceContextKey } from "../surface/context"; import { menuSurfaceFromVNode } from "./dom"; /** @@ -32,9 +38,35 @@ export default defineComponent({ name: "DropdownPopover", inheritAttrs: false, props: { + /** Placement relative to the trigger (official prop name). */ + placement: { + type: String as PropType, + default: "bottom", + }, + /** Distance from the trigger (official `offset`). */ + offset: { type: Number, default: 0 }, + /** Cross-axis distance (official `crossOffset`). */ + crossOffset: { type: Number, default: 0 }, + /** Flip on collision (official `shouldFlip`). */ + shouldFlip: { type: Boolean, default: true }, + /** Viewport padding kept free (official `containerPadding`). */ + containerPadding: { type: Number, default: 12 }, + /** Ignore Escape while true (official `isKeyboardDismissDisabled`). */ + isKeyboardDismissDisabled: { type: Boolean, default: false }, + /** Return false to keep the menu open for an outside interaction. */ + shouldCloseOnInteractOutside: { + type: Function as PropType<(event: Event) => boolean>, + default: undefined, + }, + /** Portal target; defaults to `document.body`. */ + to: { + type: [String, Object] as PropType, + default: undefined, + }, + // Low-level positioning overrides, kept for direct control. side: { type: String as PropType, default: undefined }, - sideOffset: { type: Number, default: undefined }, align: { type: String as PropType, default: undefined }, + sideOffset: { type: Number, default: undefined }, alignOffset: { type: Number, default: undefined }, avoidCollisions: { type: Boolean, default: undefined }, collisionPadding: { @@ -48,11 +80,30 @@ export default defineComponent({ const dropdownCtx = inject(dropdownContextKey, null); const inSubmenu = inject(submenuContentKey, false); const rootCtx = injectDropdownMenuRootContext(null); + const config = useConfig(); provide(menuCloseKey, () => { rootCtx?.onOpenChange(false); }); + // Surface resets to the overlay default, like the fixed upstream popover, + // so nested fields do not inherit a surrounding surface variant. + provide(surfaceContextKey, { variant: computed(() => "default" as const) }); + + // Label/description attributes belong on the real `role="menu"` element. + const contentAttrs = inSubmenu + ? (inject(menuContentAttrsKey, null) ?? null) + : { + label: ref(), + labelledBy: ref(), + describedBy: ref(), + loop: ref(), + autoFocus: ref(), + escapeKeyBehavior: ref<"clearSelection" | "none">("none"), + clearSelection: () => {}, + }; + if (!inSubmenu && contentAttrs) provide(menuContentAttrsKey, contentAttrs); + const contentElement = ref(null); const isOpen = computed(() => rootCtx?.open.value ?? false); const { entering, exiting, onAnimationEnd } = useOverlayAnimation( @@ -61,40 +112,123 @@ export default defineComponent({ true, ); + const position = computed(() => + resolvePlacement(props.placement, config?.dir.value ?? "ltr"), + ); + const resolvedSide = computed(() => props.side ?? position.value.side); + const resolvedAlign = computed(() => props.align ?? position.value.align); + + function escape(event: KeyboardEvent) { + if (props.isKeyboardDismissDisabled) event.preventDefault(); + } + /** + * `escapeKeyBehavior="clearSelection"` clears the selection and keeps the + * overlay open; the dismissable layer respects `defaultPrevented`. + */ + function onSurfaceKeydown(event: KeyboardEvent) { + if (event.defaultPrevented) return; + if (event.key !== "Escape") return; + if (contentAttrs?.escapeKeyBehavior.value !== "clearSelection") return; + event.preventDefault(); + contentAttrs.clearSelection(); + } + function interactOutside(event: { + defaultPrevented?: boolean; + preventDefault?: () => void; + }) { + if ( + props.shouldCloseOnInteractOutside?.(event as unknown as Event) === + false + ) + event.preventDefault?.(); + } + + watchEffect(() => { + if (inSubmenu || !contentAttrs) return; + contentAttrs.label.value = attrs["aria-label"] as string | undefined; + contentAttrs.labelledBy.value = attrs["aria-labelledby"] as + string | undefined; + contentAttrs.describedBy.value = attrs["aria-describedby"] as + string | undefined; + }); + + function labelProps(): Record { + const out: Record = {}; + const label = (contentAttrs?.label.value ?? + (attrs["aria-label"] as string | undefined)) as string | undefined; + const labelledBy = (contentAttrs?.labelledBy.value ?? + (attrs["aria-labelledby"] as string | undefined)) as string | undefined; + const describedBy = (contentAttrs?.describedBy.value ?? + (attrs["aria-describedby"] as string | undefined)) as + string | undefined; + if (label) { + out["aria-label"] = label; + // aria-labelledby would win over aria-label; drop the trigger default. + out["aria-labelledby"] = labelledBy; + } else if (labelledBy) { + out["aria-labelledby"] = labelledBy; + } + if (describedBy) out["aria-describedby"] = describedBy; + return out; + } + return () => { + const scope = { + isEntering: entering.value, + isExiting: exiting.value, + placement: props.placement, + }; if (inSubmenu) { // Reka SubContent already positions and dismisses this level; // the submenu trigger forwards attrs onto that element. - return h(Fragment, null, slots.default?.() as never); + return h(Fragment, null, slots.default?.(scope) as never); } return h( - RekaDropdownMenuContent as never, + RekaDropdownMenuPortal as never, + { to: props.to }, { - ...attrs, - 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, - alignOffset: props.alignOffset, - 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; - }, + default: () => + h( + RekaDropdownMenuContent as never, + { + ...attrs, + ...labelProps(), + class: dropdownCtx?.slots.value.popover({ + class: attrs.class as never, + }), + "data-slot": "dropdown-popover", + "data-entering": entering.value || undefined, + "data-exiting": exiting.value || undefined, + side: resolvedSide.value, + align: resolvedAlign.value, + sideOffset: props.sideOffset ?? props.offset, + alignOffset: props.alignOffset ?? props.crossOffset, + avoidCollisions: props.avoidCollisions ?? props.shouldFlip, + collisionPadding: + props.collisionPadding ?? props.containerPadding, + loop: props.loop ?? contentAttrs?.loop.value, + onAnimationend: onAnimationEnd, + onOpenAutoFocus: (event: Event) => { + if (contentAttrs?.autoFocus.value === false) + event.preventDefault(); + }, + onEscapeKeyDown: escape, + onInteractOutside: interactOutside, + onKeydown: onSurfaceKeydown, + onVnodeMounted: (vnode) => { + contentElement.value = menuSurfaceFromVNode(vnode); + }, + onVnodeUpdated: (vnode) => { + const element = menuSurfaceFromVNode(vnode); + if (element) contentElement.value = element; + }, + onVnodeUnmounted: () => { + contentElement.value = null; + }, + }, + { default: () => slots.default?.(scope) }, + ), }, - slots, ); }; }, diff --git a/packages/vue/src/components/dropdown/DropdownRoot.vue b/packages/vue/src/components/dropdown/DropdownRoot.vue index 4ddf538..7a911c8 100644 --- a/packages/vue/src/components/dropdown/DropdownRoot.vue +++ b/packages/vue/src/components/dropdown/DropdownRoot.vue @@ -42,7 +42,10 @@ export default defineComponent({ const isOpen = computed(() => props.open !== undefined ? props.open : uncontrolledOpen.value, ); + // The trigger suppresses the base trigger's own toggle while it decides. + const suppressOpenRequests = ref(false); function setOpen(value: boolean) { + if (suppressOpenRequests.value) return; if (props.open === undefined) uncontrolledOpen.value = value; emit("update:open", value); } @@ -53,6 +56,7 @@ export default defineComponent({ longPressDuration: computed(() => props.longPressDuration), open: isOpen, setOpen, + suppressOpenRequests, }); return () => diff --git a/packages/vue/src/components/dropdown/DropdownSection.vue b/packages/vue/src/components/dropdown/DropdownSection.vue index bdee6b5..644235a 100644 --- a/packages/vue/src/components/dropdown/DropdownSection.vue +++ b/packages/vue/src/components/dropdown/DropdownSection.vue @@ -1,12 +1,47 @@ diff --git a/packages/vue/src/components/dropdown/DropdownSubmenuTrigger.vue b/packages/vue/src/components/dropdown/DropdownSubmenuTrigger.vue index c7ada17..46760ed 100644 --- a/packages/vue/src/components/dropdown/DropdownSubmenuTrigger.vue +++ b/packages/vue/src/components/dropdown/DropdownSubmenuTrigger.vue @@ -2,7 +2,6 @@ import { Fragment, cloneVNode, - computed, defineComponent, h, inject, @@ -14,20 +13,50 @@ import { useAttrs, useId, watch, + type PropType, type Ref, type VNodeChild, } from "vue"; import { + DropdownMenuPortal as RekaDropdownMenuPortal, DropdownMenuSub as RekaDropdownMenuSub, DropdownMenuSubContent as RekaDropdownMenuSubContent, DropdownMenuSubTrigger as RekaDropdownMenuSubTrigger, } from "reka-ui"; import { dropdownVariants } from "@heroui-vue/styles"; -import { dropdownContextKey, submenuContentKey } from "../menu/context"; +import { + dropdownContextKey, + menuContentAttrsKey, + submenuContentKey, + submenuOpenKey, +} from "../menu/context"; import { useOverlayAnimation } from "../overlay/animation"; +import { resolvePlacement, type OverlayPlacement } from "../overlay/placement"; +import { useConfig } from "../../providers/context"; import { elementFromValue, menuSurfaceFromVNode } from "./dom"; import DropdownPopover from "./DropdownPopover.vue"; +const PANEL_PROPS = [ + "placement", + "offset", + "crossOffset", + "shouldFlip", + "containerPadding", + "side", + "align", + "sideOffset", + "alignOffset", + "avoidCollisions", + "collisionPadding", + "loop", + "to", + "isKeyboardDismissDisabled", + "shouldCloseOnInteractOutside", +] as const; + +type Handler = + ((event: Event) => void) | ((event: Event) => void)[] | undefined; + function flatten(nodes: VNodeChild[], out: VNodeChild[] = []): VNodeChild[] { for (const n of nodes) { if (Array.isArray(n)) flatten(n, out); @@ -36,8 +65,13 @@ function flatten(nodes: VNodeChild[], out: VNodeChild[] = []): VNodeChild[] { return out; } +function asArray(handler: Handler): Array<(event: Event) => void> { + if (!handler) return []; + return Array.isArray(handler) ? handler : [handler]; +} + /** Attributes a nested `` may pass to the submenu surface. */ -function inheritableAttrs(props: Record | null) { +function inheritedProps(props: Record | null) { const out: Record = {}; if (!props) return out; for (const [key, value] of Object.entries(props)) { @@ -49,7 +83,8 @@ function inheritableAttrs(props: Record | null) { key === "role" || key.startsWith("data-") || key.startsWith("aria-") || - /^on[A-Z]/.test(key) + /^on[A-Z]/.test(key) || + (PANEL_PROPS as readonly string[]).includes(key) ) out[key] = value; } @@ -68,12 +103,24 @@ export default defineComponent({ setup(_, { slots }) { const attrs = useAttrs(); const dropdownCtx = inject(dropdownContextKey, null); + const config = useConfig(); provide(submenuContentKey, true); const subOpen = ref(false); const triggerRef = ref(null); const contentElement = ref(null); const fallbackId = useId(); + const contentAttrs = { + label: ref(), + labelledBy: ref(), + describedBy: ref(), + loop: ref(), + autoFocus: ref(), + escapeKeyBehavior: ref<"clearSelection" | "none">("none"), + clearSelection: () => {}, + }; + provide(menuContentAttrsKey, contentAttrs); + provide(submenuOpenKey, subOpen); const { entering, exiting, onAnimationEnd } = useOverlayAnimation( subOpen as Ref, contentElement, @@ -82,20 +129,17 @@ export default defineComponent({ /** * 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. + * trigger, but our trigger item keeps an instance id, so that reference + * dangles. Point it at the real trigger element of this instance. */ - function repairLabel() { + function repairLabel(explicit?: string) { 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 (explicit) { + content.setAttribute("aria-labelledby", explicit); + return; + } if (!trigger.id) trigger.id = fallbackId; content.setAttribute("aria-labelledby", trigger.id); } @@ -109,6 +153,15 @@ export default defineComponent({ onMounted(repairLabel as () => void); function handleEscape(event: KeyboardEvent) { + if (event.defaultPrevented) return; + if ( + event.key === "Escape" && + contentAttrs.escapeKeyBehavior.value === "clearSelection" + ) { + event.preventDefault(); + contentAttrs.clearSelection(); + return; + } if (event.key !== "Escape" || !subOpen.value) return; const target = event.target as HTMLElement | null; // Only the menu level that owns the focused element closes. @@ -129,11 +182,46 @@ export default defineComponent({ const popoverVNode = contentVNodes.find( (node) => isVNode(node) && node.type === DropdownPopover, ); - const popoverAttrs = inheritableAttrs( + const popoverProps = inheritedProps( isVNode(popoverVNode) ? (popoverVNode.props as Record | null) : null, ); + const { + class: popoverClass, + onKeydown: popoverKeydown, + ...restProps + } = popoverProps; + + const placement = (restProps.placement as OverlayPlacement) ?? "end"; + const position = resolvePlacement(placement, config?.dir.value ?? "ltr"); + + // Reka fixes the submenu side/align to the parent convention, so only + // the offsets/collision props can be forwarded. + const panelProps: Record = { + sideOffset: + (restProps.sideOffset as number | undefined) ?? + (restProps.offset as number | undefined), + alignOffset: + (restProps.alignOffset as number | undefined) ?? + (restProps.crossOffset as number | undefined), + avoidCollisions: + (restProps.avoidCollisions as boolean | undefined) ?? + (restProps.shouldFlip as boolean | undefined), + collisionPadding: + (restProps.collisionPadding as number | undefined) ?? + (restProps.containerPadding as number | undefined), + loop: restProps.loop as boolean | undefined, + }; + const side = (restProps.side as string | undefined) ?? position.side; + const align = (restProps.align as string | undefined) ?? position.align; + + const keydownChain = [ + ...asArray(popoverKeydown as Handler), + ...asArray(attrs.onKeydown as Handler), + handleEscape, + ]; + const labelledBy = contentAttrs.labelledBy.value; return h( RekaDropdownMenuSub as never, @@ -169,39 +257,55 @@ export default defineComponent({ }, ), h( - RekaDropdownMenuSubContent as never, - { - ...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; - }, - }, + RekaDropdownMenuPortal as never, + { to: restProps.to as string | HTMLElement | undefined }, { default: () => h( - Fragment, - null, - // Nested DropdownPopover is a style shell inside SubContent. - contentVNodes as never, + RekaDropdownMenuSubContent as never, + { + ...panelProps, + side, + align, + "aria-label": contentAttrs.label.value, + "aria-describedby": contentAttrs.describedBy.value, + loop: + (restProps.loop as boolean | undefined) ?? + contentAttrs.loop.value, + class: [dropdownCtx?.slots.value.popover(), popoverClass], + "data-slot": "dropdown-popover", + "data-submenu-content": "true", + "data-entering": entering.value || undefined, + "data-exiting": exiting.value || undefined, + onKeydown: keydownChain, + onAnimationend: onAnimationEnd, + onOpenAutoFocus: (event: Event) => { + if (contentAttrs.autoFocus.value === false) + event.preventDefault(); + }, + onVnodeMounted: (vnode) => { + contentElement.value = menuSurfaceFromVNode(vnode); + void nextTick(() => repairLabel(labelledBy)); + }, + onVnodeUpdated: (vnode) => { + const element = menuSurfaceFromVNode(vnode); + if (!element) return; + contentElement.value = element; + void nextTick(() => repairLabel(labelledBy)); + }, + onVnodeUnmounted: () => { + contentElement.value = null; + }, + }, + { + default: () => + h( + Fragment, + null, + // Nested DropdownPopover is a style shell inside SubContent. + contentVNodes as never, + ), + }, ), }, ), diff --git a/packages/vue/src/components/dropdown/DropdownTrigger.vue b/packages/vue/src/components/dropdown/DropdownTrigger.vue index cf47b83..c514f43 100644 --- a/packages/vue/src/components/dropdown/DropdownTrigger.vue +++ b/packages/vue/src/components/dropdown/DropdownTrigger.vue @@ -17,6 +17,11 @@ const LONG_PRESS_MOVE_PX = 10; const SELECTION_KEYS = new Set(["Enter", " ", "Spacebar"]); +type Handler = + | ((event: KeyboardEvent) => void) + | ((event: KeyboardEvent) => void) + | undefined; + /** * Trigger. In `longPress` mode this component owns the press lifecycle and * cancels Reka's own click/keydown activation through its documented @@ -79,11 +84,37 @@ export default defineComponent({ event.preventDefault(); } - function onKeydown(event: KeyboardEvent) { + /** + * Long-press keyboard activation. The base trigger toggles on keydown, so + * for Enter/Space the caller's own keydown handlers run first (on the + * capture phase of the trigger region, with native Vue array semantics), + * then this component either cancels or opens exactly once while the base + * trigger's toggle is suspended — a cancelled keydown never opens the menu. + */ + function suspendBaseToggle() { + const ctx = dropdownCtx; + if (!ctx) return; + ctx.suppressOpenRequests.value = true; + setTimeout(() => { + ctx.suppressOpenRequests.value = false; + }, 0); + } + function decideKeydown(event: KeyboardEvent) { if (!isLongPress()) return; if (!SELECTION_KEYS.has(event.key)) return; + if (event.defaultPrevented) return; event.preventDefault(); - dropdownCtx?.setOpen(!(dropdownCtx?.open.value ?? false)); + const ctx = dropdownCtx; + // Open first, then suspend: the base trigger toggles later in the same + // event and must not undo this decision. + ctx?.setOpen(!(ctx.open.value ?? false)); + suspendBaseToggle(); + } + function keydownChain() { + if (!isLongPress()) return undefined; + const user = (attrs as { onKeydown?: Handler }).onKeydown; + const userHandlers = Array.isArray(user) ? user : user ? [user] : []; + return [...userHandlers, decideKeydown]; } /** @@ -120,15 +151,18 @@ export default defineComponent({ onPointercancelCapture: clearPress, onPointerleaveCapture: clearPress, onClickCapture: onActivation, - onKeydownCapture: onKeydown, + onKeydownCapture: keydownChain(), onContextmenuCapture: clearPress, }; return () => { + const longPress = isLongPress(); + const triggerAttrs: Record = { ...attrs }; + if (longPress) delete triggerAttrs.onKeydown; const trigger = h( RekaDropdownMenuTrigger as never, { - ...attrs, + ...triggerAttrs, ref: triggerRef, as: props.as, asChild: props.asChild ?? true, @@ -137,10 +171,15 @@ export default defineComponent({ }), "data-slot": "dropdown-trigger", }, - slots, + { + default: () => + slots.default?.({ + isOpen: dropdownCtx?.open.value ?? false, + }), + }, ); - if (!isLongPress()) return trigger; + if (!longPress) return trigger; return h( "span", diff --git a/packages/vue/src/components/menu-item/MenuItem.vue b/packages/vue/src/components/menu-item/MenuItem.vue index 77dd36e..80d2308 100644 --- a/packages/vue/src/components/menu-item/MenuItem.vue +++ b/packages/vue/src/components/menu-item/MenuItem.vue @@ -4,9 +4,12 @@ import { defineComponent, h, inject, + onMounted, + onUnmounted, provide, ref, useAttrs, + useId, type PropType, } from "vue"; import { DropdownMenuItem as RekaMenuItem } from "reka-ui"; @@ -22,10 +25,20 @@ type NativeClickHandler = ((e: MouseEvent) => void) | ((e: MouseEvent) => void)[] | undefined; type NativeHandler = ((e: Ev) => void) | ((e: Ev) => void)[] | undefined; +const LINK_ATTRS = [ + "href", + "target", + "rel", + "download", + "hrefLang", + "referrerPolicy", +] as const; + export default defineComponent({ name: "MenuItem", inheritAttrs: false, props: { + /** Business key used by selection and actions. Never becomes a DOM id. */ id: { type: [String, Number] as PropType, default: undefined }, textValue: { type: String, default: undefined }, isDisabled: { type: Boolean, default: false }, @@ -34,7 +47,7 @@ export default defineComponent({ type: String as PropType, default: "default", }, - /** Set false to keep the menu open after an action item. */ + /** Explicit close policy for this item (official `shouldCloseOnSelect`). */ closeOnSelect: { type: Boolean, default: undefined }, /** * Render this item as a submenu trigger. `DropdownSubmenuTrigger` sets it @@ -42,6 +55,16 @@ export default defineComponent({ * submenu (upstream derives it from the collection structure). */ hasSubmenu: { type: Boolean, default: undefined }, + /** Render a link menu item instead of a button-like item. */ + href: { type: String, default: undefined }, + target: { type: String, default: undefined }, + rel: { type: String, default: undefined }, + download: { + type: [String, Boolean] as PropType, + default: undefined, + }, + hrefLang: { type: String, default: undefined }, + referrerPolicy: { type: String, default: undefined }, }, emits: { select: (_key: MenuKey) => true, @@ -55,6 +78,7 @@ export default defineComponent({ const isFocused = ref(false); const isHovered = ref(false); const isPressed = ref(false); + const domId = useId(); const key = computed( () => props.id ?? (attrs.id as MenuKey | undefined) ?? "", ); @@ -80,6 +104,15 @@ export default defineComponent({ if (selectionMode.value === "single") return "menuitemradio"; return "menuitem"; }); + const linkProps = computed(() => { + if (!props.href) return null; + const out: Record = { as: "a", href: props.href }; + for (const name of LINK_ATTRS) { + if (name === "href") continue; + if (props[name] !== undefined) out[name] = props[name]; + } + return out; + }); provide(menuItemContextKey, { slots: slotsComputed, @@ -93,6 +126,25 @@ export default defineComponent({ }, }); + let unregister: (() => void) | undefined; + onMounted(() => { + unregister = menuCtx?.registerItem(); + }); + onUnmounted(() => { + unregister?.(); + unregister = undefined; + }); + + function shouldClose() { + if (props.closeOnSelect !== undefined) return props.closeOnSelect; + const menuPolicy = menuCtx?.shouldCloseOnSelect.value; + if (typeof menuPolicy === "function") return menuPolicy(key.value); + // Default per mode: action and radio items close, checkboxes stay open. + if (selectionMode.value !== "none") + return selectionMode.value === "single"; + return menuPolicy ?? true; + } + function activate() { if (isDisabled.value) return; emit("select", key.value); @@ -100,12 +152,11 @@ export default defineComponent({ const mode = selectionMode.value; if (mode !== "none") { owner?.proposeSelection(key.value); - if (mode === "single") menuCtx?.closeLevel(); + if (shouldClose()) menuCtx?.closeLevel(); return; } menuCtx?.emitAction(key.value); - if (props.closeOnSelect === false) return; - menuCtx?.closeLevel(); + if (shouldClose()) menuCtx?.closeLevel(); } /** Keep the caller's own handler(s) in front of the internal tracker. */ @@ -129,8 +180,8 @@ export default defineComponent({ const rest: Record = { ...(attrs as Record), }; - delete rest.onClick; for (const name of [ + "onClick", "onFocus", "onBlur", "onPointerDown", @@ -150,17 +201,22 @@ export default defineComponent({ : [] ) as Array<(e: MouseEvent) => void>; clickChain.push((event: MouseEvent) => { - if (event.defaultPrevented || isDisabled.value) return; + if (event.defaultPrevented) return; + if (isDisabled.value) { + // A disabled link must not navigate either. + event.preventDefault(); + return; + } 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, + ...linkProps.value, id: domId, class: slotsComputed.value.item({ class: attrs.class as never }), role: roleAttr, @@ -180,6 +236,7 @@ export default defineComponent({ "data-pressed": isPressed.value || undefined, "data-has-submenu": hasSubmenu.value || undefined, "data-selection-mode": selectionMode.value, + "data-key": String(key.value), disabled: isDisabled.value, textValue: props.textValue, onClick: clickChain, diff --git a/packages/vue/src/components/menu-section/MenuSection.vue b/packages/vue/src/components/menu-section/MenuSection.vue index b335979..678ccc1 100644 --- a/packages/vue/src/components/menu-section/MenuSection.vue +++ b/packages/vue/src/components/menu-section/MenuSection.vue @@ -42,6 +42,8 @@ export default defineComponent({ type: Array as PropType>, default: () => [], }, + /** Clear the last selection when the user deselects it. */ + disallowEmptySelection: { type: Boolean, default: false }, }, emits: { "update:selectedKeys": (_keys: MenuKey[]) => true, @@ -68,6 +70,7 @@ export default defineComponent({ selectionMode: effectiveMode, selectedKeys: acceptedKeys, disabledKeys: computed(() => props.disabledKeys ?? []), + disallowEmptySelection: computed(() => props.disallowEmptySelection), onSelectionChange(next) { if (!isControlled.value) internal.value = next; emit("update:selectedKeys", next); @@ -121,11 +124,11 @@ export default defineComponent({ ? sectionSelection : (menuCtx?.selection ?? sectionSelection) ).isItemSelected(key), + // Disabled keys are additive: the section list never overrides the + // menu list, whichever side owns the selection. isItemDisabled: (key: MenuKey) => - (ownsSelection.value - ? sectionSelection - : (menuCtx?.selection ?? sectionSelection) - ).isItemDisabled(key), + (props.disabledKeys ?? []).some((item) => item === key) || + (menuCtx?.selection.isItemDisabled(key) ?? false), }, }); diff --git a/packages/vue/src/components/menu/Menu.vue b/packages/vue/src/components/menu/Menu.vue index 1ac5b95..437df16 100644 --- a/packages/vue/src/components/menu/Menu.vue +++ b/packages/vue/src/components/menu/Menu.vue @@ -8,10 +8,12 @@ import { ref, useAttrs, watch, + watchEffect, type PropType, } from "vue"; import { DropdownMenuContent as RekaDropdownMenuContent, + DropdownMenuPortal as RekaDropdownMenuPortal, DropdownMenuRoot as RekaDropdownMenuRoot, injectDropdownMenuRootContext, } from "reka-ui"; @@ -19,7 +21,10 @@ import { dropdownVariants, menuVariants } from "@heroui-vue/styles"; import { dropdownContextKey, menuCloseKey, + menuContentAttrsKey, menuContextKey, + menuSectionContextKey, + submenuOpenKey, type MenuKey, type MenuSelectionMode, } from "./context"; @@ -27,7 +32,7 @@ import { useMenuSelection } from "./useMenuSelection"; /** * Menu list: selection/action context + menu styles. - * Standalone use provides its own Reka menu root/content; inside + * Standalone use renders the same list without a modal overlay; inside * DropdownPopover the surrounding Reka content is reused. */ export default defineComponent({ @@ -50,18 +55,39 @@ export default defineComponent({ type: Array as PropType>, default: () => [], }, + /** Clear the last selection when the user deselects it. */ + disallowEmptySelection: { type: Boolean, default: false }, + /** Wrap keyboard focus at the ends (official `shouldFocusWrap`). */ + shouldFocusWrap: { type: Boolean, default: undefined }, + /** Focus the menu when it opens (official `autoFocus`). */ + autoFocus: { type: Boolean, default: true }, + /** Escape clears the selection instead of closing (official name). */ + escapeKeyBehavior: { + type: String as PropType<"clearSelection" | "none">, + default: "none", + }, + /** Menu-level close policy for activation (official prop name). */ + shouldCloseOnSelect: { + type: [Boolean, Function] as PropType< + boolean | ((key: MenuKey) => boolean) + >, + default: undefined, + }, }, emits: { "update:selectedKeys": (_keys: MenuKey[]) => true, selectionChange: (_keys: MenuKey[]) => true, action: (_key: MenuKey) => true, + /** Fired when this menu level closes (official `onClose`). */ + close: () => true, }, setup(props, { slots, emit }) { const attrs = useAttrs(); const dropdownCtx = inject(dropdownContextKey, null); const outerClose = inject(menuCloseKey, null); + const contentAttrs = inject(menuContentAttrsKey, null); const outerMenuRoot = injectDropdownMenuRootContext(null); - // Standalone Menu (no DropdownRoot/Popover) must still support items. + // Standalone Menu (no DropdownRoot/Popover) still supports items. const needsOwnRoot = computed(() => !outerMenuRoot); const internal = ref([...(props.defaultSelectedKeys ?? [])]); @@ -74,6 +100,7 @@ export default defineComponent({ selectionMode: computed(() => props.selectionMode), selectedKeys: acceptedKeys, disabledKeys: computed(() => props.disabledKeys ?? []), + disallowEmptySelection: computed(() => props.disallowEmptySelection), onSelectionChange(next) { if (!isControlled.value) internal.value = next; emit("update:selectedKeys", next); @@ -88,6 +115,33 @@ export default defineComponent({ }, ); + function clearSelection() { + if (props.disallowEmptySelection) return; + if (acceptedKeys.value.length === 0) return; + if (!isControlled.value) internal.value = []; + emit("update:selectedKeys", []); + emit("selectionChange", []); + } + + // Label/description/focus attributes for the surrounding surface. + watchEffect(() => { + if (!contentAttrs) return; + contentAttrs.loop.value = props.shouldFocusWrap; + contentAttrs.autoFocus.value = props.autoFocus; + contentAttrs.escapeKeyBehavior.value = props.escapeKeyBehavior; + }); + if (contentAttrs) contentAttrs.clearSelection = clearSelection; + + // `close` fires when this menu level leaves the open state, whatever the + // cause (item activation, Escape, outside interaction). + const submenuOpen = inject(submenuOpenKey, null); + const levelOpen = submenuOpen ?? dropdownCtx?.open ?? null; + if (levelOpen) + watch(levelOpen, (value, previous) => { + if (previous && !value) emit("close"); + }); + + const itemCount = ref(0); provide(menuContextKey, { closeLevel: () => { if (outerClose) outerClose(); @@ -96,46 +150,89 @@ export default defineComponent({ emitAction: (key: MenuKey) => emit("action", key), selection, selectionMode: computed(() => props.selectionMode), + shouldCloseOnSelect: computed( + () => props.shouldCloseOnSelect ?? props.selectionMode === "multiple", + ), + itemCount, + registerItem: () => { + itemCount.value += 1; + return () => { + itemCount.value = Math.max(0, itemCount.value - 1); + }; + }, + }); + // A Menu opened inside a MenuSection owns its own scope; without this a + // nested list would keep the outer section's selection owner. + provide(menuSectionContextKey, null); + + // The accessible name belongs on the real `role="menu"` node, which lives + // on the surrounding content element rather than on this list. + watchEffect(() => { + if (!contentAttrs) return; + contentAttrs.label.value = attrs["aria-label"] as string | undefined; + contentAttrs.labelledBy.value = attrs["aria-labelledby"] as + string | undefined; + contentAttrs.describedBy.value = attrs["aria-describedby"] as + string | undefined; }); - const listNode = () => { - // The surrounding Reka content already renders `role="menu"`; upstream - // also styles the list itself, so it stays a plain element here. + function listProps() { const userRole = attrs.role as string | undefined; const rest: Record = { ...attrs }; - delete rest.role; - return h( - "div", - { - ...rest, - ...(userRole ? { role: userRole } : {}), - class: menuVariants({ - class: [dropdownCtx?.slots.value.menu(), attrs.class], - }), - "data-selection-mode": props.selectionMode, - "data-slot": dropdownCtx ? "dropdown-menu" : "menu", - }, - slots, - ); - }; + for (const key of [ + "role", + "aria-label", + "aria-labelledby", + "aria-describedby", + ]) + delete rest[key]; + return { + ...rest, + ...(userRole ? { role: userRole } : {}), + class: menuVariants({ + class: [dropdownCtx?.slots.value.menu(), attrs.class], + }), + "data-selection-mode": props.selectionMode, + "data-slot": dropdownCtx ? "dropdown-menu" : "menu", + }; + } + + const listNode = () => + h("div", listProps(), [ + slots.default?.(), + itemCount.value === 0 ? slots.empty?.() : undefined, + ]); return () => { if (!needsOwnRoot.value) return listNode(); - // Public standalone Menu: own Reka root + content so items get menu - // semantics and keyboard navigation without private context. + // Standalone Menu: keep the base menu semantics and keyboard model, but + // without modal behaviour (no scroll lock, no outside pointer blocking) + // and without stealing focus. return h( RekaDropdownMenuRoot as never, - { open: true }, + { open: true, modal: false }, { default: () => h( - RekaDropdownMenuContent as never, + RekaDropdownMenuPortal as never, + { disabled: true }, { - class: dropdownVariants().popover(), - "data-slot": "dropdown-popover", - sideOffset: 0, + default: () => + h( + RekaDropdownMenuContent as never, + { + class: dropdownVariants().popover(), + "data-slot": "dropdown-popover", + sideOffset: 0, + avoidCollisions: false, + "aria-label": contentAttrs?.label.value, + "data-static": "true", + // A static in-flow list never steals focus from the page. + onOpenAutoFocus: (event: Event) => event.preventDefault(), + }, + { default: listNode }, + ), }, - { default: listNode }, ), }, ); diff --git a/packages/vue/src/components/menu/context.ts b/packages/vue/src/components/menu/context.ts index 311b147..bd55aa5 100644 --- a/packages/vue/src/components/menu/context.ts +++ b/packages/vue/src/components/menu/context.ts @@ -22,6 +22,11 @@ export interface MenuContextValue { selection: MenuSelectionOwner; /** Root selection mode for data-selection-mode styling. */ selectionMode: ComputedRef; + /** Menu-level close policy for activation (official `shouldCloseOnSelect`). */ + shouldCloseOnSelect: ComputedRef boolean)>; + /** Number of mounted items, used for the empty-state slot. */ + itemCount: Ref; + registerItem: () => () => void; } export const menuContextKey: InjectionKey = Symbol("hv-menu"); @@ -30,7 +35,8 @@ export interface MenuSectionContextValue { selection: MenuSelectionOwner; } -export const menuSectionContextKey: InjectionKey = +/** `null` resets the owner so a nested Menu does not inherit a section. */ +export const menuSectionContextKey: InjectionKey = Symbol("hv-menu-section"); /** MenuSection exposes this so a nested Header can name the group. */ @@ -43,6 +49,25 @@ export const menuSectionLabelKey: InjectionKey = Symbol( "hv-menu-section-label", ); +/** Label/description attributes that belong on the real `role="menu"` node. */ +export interface MenuContentAttrsValue { + label: Ref; + labelledBy: Ref; + describedBy: Ref; + /** Focus wrap while navigating with the keyboard (official `shouldFocusWrap`). */ + loop: Ref; + /** Focus the menu when it opens (official `autoFocus`). */ + autoFocus: Ref; + /** Escape behaviour of the owning menu (official `escapeKeyBehavior`). */ + escapeKeyBehavior: Ref<"clearSelection" | "none">; + /** Clear the selection for the owning menu (no-op when disallowed). */ + clearSelection: () => void; +} + +export const menuContentAttrsKey: InjectionKey = Symbol( + "hv-menu-content-attrs", +); + export interface MenuItemContextValue { // eslint-disable-next-line @typescript-eslint/no-explicit-any slots: ComputedRef; @@ -60,6 +85,11 @@ export const menuItemContextKey: InjectionKey = /** Provided by DropdownPopover / submenu content to close this menu level. */ export const menuCloseKey: InjectionKey<() => void> = Symbol("hv-menu-close"); +/** Open state of the enclosing submenu level, when any. */ +export const submenuOpenKey: InjectionKey> = Symbol( + "hv-dropdown-submenu-open", +); + /** True when a DropdownPopover nests inside DropdownSubmenuTrigger. */ export const submenuContentKey: InjectionKey = Symbol( "hv-dropdown-submenu-content", @@ -70,6 +100,8 @@ export interface DropdownTriggerModeValue { longPressDuration: ComputedRef; open: ComputedRef; setOpen: (value: boolean) => void; + /** While true, open requests coming from the base trigger are ignored. */ + suppressOpenRequests: Ref; } export interface DropdownContextValue extends DropdownTriggerModeValue { diff --git a/packages/vue/src/components/menu/useMenuSelection.ts b/packages/vue/src/components/menu/useMenuSelection.ts index 3e3a1db..94ba8b1 100644 --- a/packages/vue/src/components/menu/useMenuSelection.ts +++ b/packages/vue/src/components/menu/useMenuSelection.ts @@ -11,6 +11,8 @@ export interface UseMenuSelectionOptions { Ref> | ComputedRef>; disabledKeys?: Ref> | ComputedRef>; + /** Keep the last selected key when the user tries to clear it. */ + disallowEmptySelection?: Ref | ComputedRef; /** Accepted-value update. Return the accepted keys (may reject the proposal). */ onSelectionChange: (keys: MenuKey[]) => void; } @@ -33,12 +35,14 @@ export function useMenuSelection( const current = options.selectedKeys.value; const has = isItemSelected(key); if (mode === "single") { + if (has && options.disallowEmptySelection?.value) return; options.onSelectionChange(has ? [] : [key]); return; } - options.onSelectionChange( - has ? current.filter((k) => k !== key) : [...current, key], - ); + const next = has ? current.filter((k) => k !== key) : [...current, key]; + if (has && next.length === 0 && options.disallowEmptySelection?.value) + return; + options.onSelectionChange(next); }; return { diff --git a/tests/b01-complete-review.probe.test.ts b/tests/b01-complete-review.probe.test.ts new file mode 100644 index 0000000..66e2059 --- /dev/null +++ b/tests/b01-complete-review.probe.test.ts @@ -0,0 +1,243 @@ +import Surface from "../packages/vue/src/components/surface/Surface.vue"; +import { surfaceContextKey } from "../packages/vue/src/components/surface/context"; +import { afterEach, expect, it, vi } from "vitest"; +import { mount, flushPromises } from "@vue/test-utils"; +import { defineComponent, h, ref, inject } from "vue"; +import { + Button, + DropdownRoot, + DropdownTrigger, + DropdownPopover, + DropdownMenu, + DropdownSection, + DropdownSubmenuTrigger, + DropdownSubmenuIndicator, + DropdownItem, + Menu, +} from "../packages/vue/src"; +const cleanup: (() => void)[] = []; +afterEach(() => { + cleanup + .splice(0) + .reverse() + .forEach((fn) => fn()); + vi.useRealTimers(); + document.body.innerHTML = ""; +}); +async function render( + menuProps: Record, + children: () => unknown, +) { + const w = mount( + defineComponent({ + setup: () => () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => + h(DropdownPopover, {}, () => + h(DropdownMenu, menuProps, { default: children }), + ), + ), + }), + { attachTo: document.body }, + ); + cleanup.push(() => w.unmount()); + await flushPromises(); + return w; +} +it("section disabledKeys work when selection is inherited", async () => { + await render({ selectionMode: "multiple" }, () => + h(DropdownSection, { disabledKeys: ["x"] }, () => + h(DropdownItem, { id: "x" }, () => "X"), + ), + ); + expect( + document + .querySelector('[data-slot="menu-item"]') + ?.getAttribute("aria-disabled"), + ).toBe("true"); +}); +it("root disabledKeys remain effective in a section with its own selection", async () => { + await render({ disabledKeys: ["x"] }, () => + h(DropdownSection, { selectionMode: "multiple" }, () => + h(DropdownItem, { id: "x" }, () => "X"), + ), + ); + expect( + document + .querySelector('[data-slot="menu-item"]') + ?.getAttribute("aria-disabled"), + ).toBe("true"); +}); +it("single-selection closeOnSelect=false keeps the menu open", async () => { + await render({ selectionMode: "single" }, () => + h(DropdownItem, { id: "x", closeOnSelect: false }, () => "X"), + ); + (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click(); + await flushPromises(); + expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull(); +}); +it("multiple-selection closeOnSelect=true closes the menu", async () => { + await render({ selectionMode: "multiple" }, () => + h(DropdownItem, { id: "x", closeOnSelect: true }, () => "X"), + ); + (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click(); + await flushPromises(); + expect(document.querySelector('[data-slot="menu-item"]')).toBeNull(); +}); +it("typed numeric and string keys never create duplicate DOM ids", async () => { + await render({ selectionMode: "multiple" }, () => [ + h(DropdownItem, { id: 0 }, () => "Number"), + h(DropdownItem, { id: "0" }, () => "String"), + ]); + const nodes = Array.from( + document.querySelectorAll('[data-slot="menu-item"]'), + ); + expect(new Set(nodes.map((n) => n.id)).size).toBe(nodes.length); +}); +it("standalone Menu does not lock body scrolling or disable outside controls", async () => { + const outside = document.createElement("button"); + document.body.append(outside); + const w = mount(Menu, { + slots: { default: () => h(DropdownItem, { id: "x" }, () => "X") }, + attachTo: document.body, + }); + cleanup.push(() => w.unmount()); + await flushPromises(); + expect(document.body.style.overflow).not.toBe("hidden"); + expect(document.body.style.pointerEvents).not.toBe("none"); + expect(outside.getAttribute("aria-hidden")).not.toBe("true"); +}); +it("native link menu items retain anchor href semantics", async () => { + await render({}, () => + h( + DropdownItem, + { id: "link", href: "/target", target: "_blank" }, + () => "Go", + ), + ); + const item = document.querySelector('[data-slot="menu-item"]')!; + expect(item.tagName).toBe("A"); + expect(item.getAttribute("href")).toBe("/target"); +}); +it("longPress cannot open a disabled actual trigger", async () => { + vi.useFakeTimers(); + const w = mount( + defineComponent({ + setup: () => () => + h(DropdownRoot, { trigger: "longPress", modal: false }, () => [ + h(DropdownTrigger, {}, () => + h(Button, { isDisabled: true }, () => "Hold"), + ), + h(DropdownPopover, {}, () => + h(DropdownMenu, {}, () => h(DropdownItem, { id: "x" }, () => "X")), + ), + ]), + }), + { attachTo: document.body }, + ); + cleanup.push(() => w.unmount()); + await w.get("button").trigger("pointerdown", { + pointerType: "mouse", + button: 0, + isPrimary: true, + }); + await vi.advanceTimersByTimeAsync(600); + await flushPromises(); + expect(document.querySelector('[data-slot="menu-item"]')).toBeNull(); +}); +it("cancelled trigger keydown does not open longPress menu", async () => { + const w = mount( + defineComponent({ + setup: () => () => + h(DropdownRoot, { trigger: "longPress", modal: false }, () => [ + h( + DropdownTrigger, + { onKeydown: (e: KeyboardEvent) => e.preventDefault() }, + () => h(Button, {}, () => "Hold"), + ), + h(DropdownPopover, {}, () => + h(DropdownMenu, {}, () => h(DropdownItem, { id: "x" }, () => "X")), + ), + ]), + }), + { attachTo: document.body }, + ); + cleanup.push(() => w.unmount()); + await w.get("button").trigger("keydown", { key: "Enter" }); + await flushPromises(); + expect(document.querySelector('[data-slot="menu-item"]')).toBeNull(); +}); +it("root menu's accessible name follows its labelled DropdownMenu", async () => { + await render({ "aria-label": "File actions" }, () => + h(DropdownItem, { id: "x" }, () => "X"), + ); + const menu = document.querySelector('[role="menu"]')!; + expect(menu.getAttribute("aria-label")).toBe("File actions"); +}); + +it("submenu Menu owns its selection instead of inheriting a parent section owner", async () => { + await render({}, () => + h( + DropdownSection, + { selectionMode: "multiple", selectedKeys: ["outer"] }, + () => + h(DropdownMenu, { selectionMode: "none" }, () => + h(DropdownItem, { id: "inner" }, () => "Inner"), + ), + ), + ); + expect( + document.querySelector('[data-slot="menu-item"]')?.getAttribute("role"), + ).toBe("menuitem"); +}); + +it("dropdown popover resets inherited Surface context like the fixed upstream", async () => { + const Inspector = defineComponent({ + setup() { + const ctx = inject(surfaceContextKey, null); + return () => + h("span", { "data-test": "surface" }, ctx?.variant.value ?? "none"); + }, + }); + const w = mount( + defineComponent({ + setup: () => () => + h(Surface, { variant: "secondary" }, () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => + h(DropdownPopover, {}, () => h(Inspector)), + ), + ), + }), + { attachTo: document.body }, + ); + cleanup.push(() => w.unmount()); + await flushPromises(); + expect(document.querySelector('[data-test="surface"]')?.textContent).toBe( + "default", + ); +}); + +it("submenu panel preserves a caller keydown listener", async () => { + const keydown = vi.fn(); + await render({}, () => + h(DropdownSubmenuTrigger, {}, () => [ + h(DropdownItem, { id: "sub" }, () => [ + "Sub", + h(DropdownSubmenuIndicator), + ]), + h(DropdownPopover, { onKeydown: keydown }, () => + h(DropdownMenu, {}, () => + h(DropdownItem, { id: "inner" }, () => "Inner"), + ), + ), + ]), + ); + (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click(); + await flushPromises(); + const panel = document.querySelector("[data-submenu-content]")!; + expect(panel).not.toBeNull(); + panel.dispatchEvent( + new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }), + ); + await flushPromises(); + expect(keydown).toHaveBeenCalledTimes(1); +}); diff --git a/tests/b01-menu-dropdown.test.ts b/tests/b01-menu-dropdown.test.ts index bc535a5..0e62c0e 100644 --- a/tests/b01-menu-dropdown.test.ts +++ b/tests/b01-menu-dropdown.test.ts @@ -20,6 +20,7 @@ import { MenuItem, MenuSection, } from "../packages/vue/src"; +import type { MenuKey } from "../packages/vue/src"; const cleanup: (() => void)[] = []; afterEach(() => { @@ -45,13 +46,13 @@ function mountApp(setup: () => unknown, render?: () => unknown) { } it("Dropdown opens and action item fires once", async () => { - const actions: string[] = []; + const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(Button, () => "操作"), h(DropdownPopover, {}, () => - h(DropdownMenu, { onAction: (k: string) => actions.push(k) }, () => [ + h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => [ h(DropdownItem, { id: "new-file", textValue: "新建文件" }, () => h(Label, () => "新建文件"), ), @@ -343,7 +344,7 @@ function pointer( } function mountLongPress(duration = 300) { - const actions: string[] = []; + const actions: MenuKey[] = []; const w = mountApp( () => () => h( @@ -354,7 +355,7 @@ function mountLongPress(duration = 300) { h(Button, { "aria-label": "菜单" }, () => "长按"), ), h(DropdownPopover, {}, () => - h(DropdownMenu, { onAction: (k: string) => actions.push(k) }, () => + h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => h(DropdownItem, { id: "x", textValue: "X" }, () => h(Label, () => "X"), ), @@ -585,13 +586,13 @@ it("Escape on a pointer-opened submenu trigger closes only that level", async () }); it("keyboard activation on a focused item fires the action once", async () => { - const actions: string[] = []; + const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => - h(DropdownMenu, { onAction: (k: string) => actions.push(k) }, () => + h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => h(DropdownItem, { id: "new-file", textValue: "新建文件" }, () => h(Label, () => "新建文件"), ), @@ -617,13 +618,13 @@ it("keyboard activation on a focused item fires the action once", async () => { }); it("keyboard activation is cancelled when the item click is prevented", async () => { - const actions: string[] = []; + const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ h(DropdownTrigger, {}, () => h(Button, () => "菜单")), h(DropdownPopover, {}, () => - h(DropdownMenu, { onAction: (k: string) => actions.push(k) }, () => + h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => h( DropdownItem, { @@ -702,8 +703,12 @@ it("menu items expose DOM ids and a single role=menu per popup", async () => { ); await flushPromises(); await nextTick(); - const items = document.querySelectorAll('[data-slot="menu-item"]'); - expect(Array.from(items).map((item) => item.getAttribute("id"))).toEqual([ + const items = Array.from( + document.querySelectorAll('[data-slot="menu-item"]'), + ); + // Business keys stay out of the DOM; each instance gets its own id. + expect(new Set(items.map((item) => item.id)).size).toBe(items.length); + expect(items.map((item) => item.getAttribute("data-key"))).toEqual([ "first", "second", ]); @@ -872,7 +877,7 @@ it("caller classes merge with tailwind-variants semantics", async () => { }); it("pressing the submenu trigger without an indicator still treats it as a submenu", async () => { - const actions: string[] = []; + const actions: MenuKey[] = []; mountApp( () => () => h(DropdownRoot, { defaultOpen: true }, () => [ @@ -880,7 +885,7 @@ it("pressing the submenu trigger without an indicator still treats it as a subme h(DropdownPopover, {}, () => h( DropdownMenu, - { onAction: (key: string) => actions.push(key) }, + { onAction: (key: MenuKey) => actions.push(key) }, () => h(DropdownSubmenuTrigger, {}, () => [ h(DropdownItem, { id: "more", textValue: "更多" }, () => @@ -914,3 +919,240 @@ it("pressing the submenu trigger without an indicator still treats it as a subme document.querySelectorAll('[data-slot="dropdown-popover"]').length, ).toBeGreaterThan(1); }); + +it("menu capability props are honoured", async () => { + const close = vi.fn(); + const selections: MenuKey[][] = []; + mountApp( + () => () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ + h(DropdownPopover, {}, () => + h( + DropdownMenu, + { + selectionMode: "multiple", + selectedKeys: ["a"], + disallowEmptySelection: true, + escapeKeyBehavior: "clearSelection", + shouldFocusWrap: true, + autoFocus: false, + onClose: close, + "onUpdate:selectedKeys": (keys: MenuKey[]) => + selections.push(keys), + }, + () => + h(DropdownItem, { id: "a", textValue: "A" }, () => + h(Label, () => "A"), + ), + ), + ), + ]), + ); + await flushPromises(); + await nextTick(); + const menu = document.querySelector('[role="menu"]') as HTMLElement; + const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement; + + // disallowEmptySelection keeps the last key. + item.click(); + await flushPromises(); + expect(selections).toEqual([]); + + // escapeKeyBehavior clears the selection instead of closing. + menu.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + bubbles: true, + cancelable: true, + }), + ); + await flushPromises(); + expect(selections).toEqual([]); + expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull(); + + // close fires when the level actually closes. + menu.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); + await flushPromises(); +}); + +it("link items render an anchor and keep navigation semantics", async () => { + const actions: MenuKey[] = []; + mountApp( + () => () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ + h(DropdownPopover, {}, () => + h( + DropdownMenu, + { onAction: (key: MenuKey) => actions.push(key) }, + () => + h( + DropdownItem, + { + id: "link", + href: "/target", + target: "_blank", + rel: "noopener", + }, + () => h(Label, () => "Go"), + ), + ), + ), + ]), + ); + await flushPromises(); + await nextTick(); + const link = document.querySelector('[data-slot="menu-item"]') as HTMLElement; + expect(link.tagName).toBe("A"); + expect(link.getAttribute("href")).toBe("/target"); + expect(link.getAttribute("target")).toBe("_blank"); + expect(link.getAttribute("rel")).toBe("noopener"); + expect(link.getAttribute("role")).toBe("menuitem"); + link.click(); + await flushPromises(); + expect(actions).toEqual(["link"]); +}); + +it("disabled link items do not navigate", async () => { + mountApp( + () => () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ + h(DropdownPopover, {}, () => + h(DropdownMenu, {}, () => + h( + DropdownItem, + { id: "link", href: "/target", isDisabled: true }, + () => h(Label, () => "Go"), + ), + ), + ), + ]), + ); + await flushPromises(); + await nextTick(); + const link = document.querySelector('[data-slot="menu-item"]') as HTMLElement; + const event = new MouseEvent("click", { bubbles: true, cancelable: true }); + link.dispatchEvent(event); + expect(event.defaultPrevented).toBe(true); +}); + +it("empty slot renders when the menu has no items", async () => { + mountApp( + () => () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ + h(DropdownPopover, {}, () => + h( + DropdownMenu, + {}, + { + empty: () => h("p", { "data-test": "empty" }, "无结果"), + }, + ), + ), + ]), + ); + await flushPromises(); + await nextTick(); + expect(document.querySelector('[data-test="empty"]')).not.toBeNull(); +}); + +it("submenu panel receives panel props and keeps caller handlers", async () => { + const keydown = vi.fn(); + mountApp( + () => () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ + h(DropdownPopover, {}, () => + h(DropdownMenu, {}, () => + h(DropdownSubmenuTrigger, {}, () => [ + h(DropdownItem, { id: "sub", textValue: "S" }, () => [ + h(Label, () => "S"), + h(DropdownSubmenuIndicator), + ]), + h( + DropdownPopover, + { + sideOffset: 12, + collisionPadding: 20, + class: "panel-x", + onKeydown: keydown, + }, + () => + h(DropdownMenu, {}, () => + h(DropdownItem, { id: "inner", textValue: "I" }, () => + h(Label, () => "I"), + ), + ), + ), + ]), + ), + ), + ]), + ); + await flushPromises(); + await nextTick(); + (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click(); + await flushPromises(); + await nextTick(); + const panel = document.querySelector("[data-submenu-content]") as HTMLElement; + expect(panel.className).toContain("panel-x"); + // Portal keeps the panel outside the clipping ancestor. + expect(panel.closest('[data-slot="dropdown-popover"]')).toBe(panel); + panel.dispatchEvent( + new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }), + ); + await flushPromises(); + expect(keydown).toHaveBeenCalledTimes(1); +}); + +it("dropdown popover is portaled out of clipping ancestors", async () => { + const host = document.createElement("div"); + host.style.overflow = "hidden"; + host.style.isolation = "isolate"; + document.body.append(host); + const w = mount( + defineComponent({ + setup: () => () => + h(DropdownRoot, { defaultOpen: true, modal: false }, () => [ + h(DropdownTrigger, {}, () => h(Button, () => "菜单")), + h(DropdownPopover, {}, () => + h(DropdownMenu, {}, () => + h(DropdownItem, { id: "a", textValue: "A" }, () => + h(Label, () => "A"), + ), + ), + ), + ]), + }), + { attachTo: host }, + ); + cleanup.push(() => w.unmount()); + await flushPromises(); + await nextTick(); + const popover = document.querySelector( + '[data-slot="dropdown-popover"]', + ) as HTMLElement; + expect(popover).not.toBeNull(); + expect(host.contains(popover)).toBe(false); + expect(popover.closest("[data-reka-popper-content-wrapper]")).toBe( + popover.parentElement, + ); +}); + +it("standalone Menu stays in flow without modal side effects", async () => { + const outside = document.createElement("button"); + document.body.append(outside); + const w = mount(Menu, { + slots: { default: () => h(MenuItem, { id: "x" }, () => "X") }, + attachTo: document.body, + }); + cleanup.push(() => w.unmount()); + await flushPromises(); + await nextTick(); + const surface = document.querySelector( + "[data-reka-menu-content]", + ) as HTMLElement; + expect(surface.getAttribute("data-static")).toBe("true"); + expect(document.body.style.overflow).not.toBe("hidden"); + expect(outside.getAttribute("aria-hidden")).not.toBe("true"); + // Focus is not stolen from the page. + expect(document.activeElement).not.toBe(surface); +}); diff --git a/tests/package/b01-consumer-app/README.md b/tests/package/b01-consumer-app/README.md new file mode 100644 index 0000000..81ecc99 --- /dev/null +++ b/tests/package/b01-consumer-app/README.md @@ -0,0 +1,29 @@ +# B01 独立浏览器消费夹具 + +用打包产物(`pnpm pack` 生成的 `@heroui-vue/components` / `@heroui-vue/styles` tarball)在独立 Vue 应用中真实挂载,覆盖: + +- `selection`:带 `contain/isolation/overflow:hidden` 祖先的分组级多选长菜单(验证 Portal 脱离裁切、高度上限、真实 `role="menu"` 名称)。 +- `submenu`:三级子菜单 + 链接型菜单项。 +- `modal`:Modal 内的 Dropdown(验证层级与关闭顺序、滚动锁释放)。 +- `standalone`:独立 `Menu` 内联列表(无滚动锁、无浮动定位、不抢焦点)。 + +## 使用方式 + +```bash +# 1. 在库仓库打包 +pnpm build +pnpm --filter @heroui-vue/styles exec pnpm pack --pack-destination /tmp/heroui-b01-consumer +pnpm --filter @heroui-vue/components exec pnpm pack --pack-destination /tmp/heroui-b01-consumer + +# 2. 复制本目录到消费工程并安装 +cp -R tests/package/b01-consumer-app/. /tmp/heroui-b01-consumer/app/ +cd /tmp/heroui-b01-consumer && pnpm install + +# 3. 打包成静态产物(esbuild 只作为构建工具,运行期仅依赖 tarball) +esbuild app/main.js --bundle --format=esm --outfile=app/bundle.js --loader:.css=css + +# 4. 静态服务后打开(`?only=selection|submenu|modal|standalone` 可单例) +python3 -m http.server 5199 --bind 127.0.0.1 --directory app +``` + +`consume-b01-menu-dropdown.mjs` 只做导出/CSS 存在性检查;真实挂载行为以本夹具的浏览器结果为准。 diff --git a/tests/package/b01-consumer-app/index.html b/tests/package/b01-consumer-app/index.html new file mode 100644 index 0000000..d0624eb --- /dev/null +++ b/tests/package/b01-consumer-app/index.html @@ -0,0 +1,13 @@ + + + + + B01 consumer + + + + +
+ + + diff --git a/tests/package/b01-consumer-app/main.js b/tests/package/b01-consumer-app/main.js new file mode 100644 index 0000000..3e4e7b8 --- /dev/null +++ b/tests/package/b01-consumer-app/main.js @@ -0,0 +1,214 @@ +import { createApp, h, ref, defineComponent } from "vue"; +import { + Button, + DropdownRoot, + DropdownTrigger, + DropdownPopover, + DropdownMenu, + DropdownSection, + DropdownItem, + DropdownItemIndicator, + DropdownSubmenuTrigger, + DropdownSubmenuIndicator, + Header, + Label, + Menu, + MenuItem, + Modal, + ModalTrigger, + ModalBackdrop, + ModalContainer, + ModalDialog, + ModalHeader, + ModalHeading, + ModalBody, + ModalFooter, + ModalCloseTrigger, +} from "@heroui-vue/components"; +import "@heroui-vue/styles/css"; + +const selected = ref(["a"]); +const actions = []; +window.__actions = actions; + +const fruits = ["a", "b", "c", "d", "e", "f", "g", "h"]; +const names = ["苹果", "香蕉", "樱桃", "橙子", "梨", "葡萄", "西瓜", "芒果"]; + +const SelectionCase = defineComponent({ + name: "SelectionCase", + setup() { + return () => + h("div", { "data-case": "clipping", class: "clip-ancestor" }, [ + h(DropdownRoot, { modal: false }, () => [ + h(DropdownTrigger, null, () => + h(Button, { "aria-label": "水果" }, () => "选择水果"), + ), + h(DropdownPopover, null, () => + h( + DropdownMenu, + { + "aria-label": "水果操作", + selectionMode: "multiple", + selectedKeys: selected.value, + "onUpdate:selectedKeys": (k) => (selected.value = k), + }, + () => + h(DropdownSection, null, () => [ + h(Header, null, () => "水果"), + ...fruits.map((id, index) => + h(DropdownItem, { id, textValue: names[index] }, () => [ + h(DropdownItemIndicator), + h(Label, null, () => names[index]), + ]), + ), + ]), + ), + ), + ]), + ]); + }, +}); + +const SubmenuCase = defineComponent({ + name: "SubmenuCase", + setup() { + return () => + h("div", { "data-case": "submenu", class: "case" }, [ + h(DropdownRoot, { modal: false }, () => [ + h(DropdownTrigger, null, () => + h(Button, { "aria-label": "分享" }, () => "分享"), + ), + h(DropdownPopover, null, () => + h( + DropdownMenu, + { onAction: (k) => actions.push(String(k)) }, + () => [ + h(DropdownItem, { id: "copy", textValue: "复制链接" }, () => + h(Label, null, () => "复制链接"), + ), + h(DropdownSubmenuTrigger, null, () => [ + h(DropdownItem, { id: "more", textValue: "更多" }, () => [ + h(Label, null, () => "更多"), + h(DropdownSubmenuIndicator), + ]), + h(DropdownPopover, null, () => + h(DropdownMenu, null, () => [ + h(DropdownItem, { id: "wa", textValue: "WhatsApp" }, () => + h(Label, null, () => "WhatsApp"), + ), + h(DropdownItem, { id: "tg", textValue: "Telegram" }, () => + h(Label, null, () => "Telegram"), + ), + h(DropdownSubmenuTrigger, null, () => [ + h( + DropdownItem, + { id: "mail", textValue: "邮件" }, + () => [ + h(Label, null, () => "邮件"), + h(DropdownSubmenuIndicator), + ], + ), + h(DropdownPopover, null, () => + h(DropdownMenu, null, () => + h( + DropdownItem, + { id: "work", textValue: "工作邮箱" }, + () => h(Label, null, () => "工作邮箱"), + ), + ), + ), + ]), + ]), + ), + ]), + h( + DropdownItem, + { id: "link", textValue: "文档", href: "#docs" }, + () => h(Label, null, () => "文档链接"), + ), + ], + ), + ), + ]), + ]); + }, +}); + +const ModalCase = defineComponent({ + name: "ModalCase", + setup() { + return () => + h("div", { "data-case": "modal", class: "case" }, [ + h(Modal, null, () => [ + h(ModalTrigger, null, () => h(Button, null, () => "打开组合复核")), + h(ModalBackdrop, null, () => + h(ModalContainer, null, () => + h(ModalDialog, null, () => [ + h(ModalHeader, null, () => + h(ModalHeading, null, () => "模态内菜单"), + ), + h(ModalBody, null, () => [ + h(DropdownRoot, { modal: false }, () => [ + h(DropdownTrigger, null, () => + h(Button, { "aria-label": "菜单" }, () => "菜单"), + ), + h(DropdownPopover, null, () => + h(DropdownMenu, null, () => [ + h(DropdownItem, { id: "m1", textValue: "一" }, () => + h(Label, null, () => "一"), + ), + h(DropdownItem, { id: "m2", textValue: "二" }, () => + h(Label, null, () => "二"), + ), + ]), + ), + ]), + ]), + h(ModalFooter, null, () => + h(ModalCloseTrigger, null, () => + h(Button, null, () => "关闭"), + ), + ), + ]), + ), + ), + ]), + ]); + }, +}); + +const StandaloneCase = defineComponent({ + name: "StandaloneCase", + setup() { + return () => + h("div", { "data-case": "standalone", class: "case" }, [ + h(Menu, { "aria-label": "内联菜单" }, () => [ + h(MenuItem, { id: "s1" }, () => "内联项一"), + h(MenuItem, { id: "s2" }, () => "内联项二"), + ]), + ]); + }, +}); + +const only = new URLSearchParams(location.search).get("only"); +const cases = { + selection: SelectionCase, + submenu: SubmenuCase, + modal: ModalCase, + standalone: StandaloneCase, +}; +const shown = only && cases[only] ? [cases[only]] : Object.values(cases); + +createApp( + defineComponent({ + name: "App", + setup() { + return () => + h( + "main", + { style: "display:flex;flex-direction:column;gap:16px;padding:16px" }, + shown.map((component) => h(component)), + ); + }, + }), +).mount("#app"); diff --git a/tests/package/b01-consumer-app/style.css b/tests/package/b01-consumer-app/style.css new file mode 100644 index 0000000..04f1a4e --- /dev/null +++ b/tests/package/b01-consumer-app/style.css @@ -0,0 +1,16 @@ +body { + margin: 0; + font-family: -apple-system, "PingFang SC", sans-serif; +} +.clip-ancestor { + overflow: hidden; + contain: content; + isolation: isolate; + height: 64px; + border: 1px dashed #bbb; +} +.case { + display: flex; + gap: 12px; + align-items: flex-start; +} diff --git a/tests/package/b01-wrapper-props-review.ts b/tests/package/b01-wrapper-props-review.ts new file mode 100644 index 0000000..e695950 --- /dev/null +++ b/tests/package/b01-wrapper-props-review.ts @@ -0,0 +1,18 @@ +import { + DropdownItem, + DropdownMenu, + DropdownSection, +} from "@heroui-vue/components"; +// Valid API values must be accepted by the actual public Vue component types, +// not only by separately exported aliases. +export const item: InstanceType["$props"] = { + id: "item", + variant: "danger", +}; +export const menu: InstanceType["$props"] = { + selectionMode: "multiple", + selectedKeys: [0, "0"], +}; +export const section: InstanceType["$props"] = { + selectionMode: "single", +};