`(保留 `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(本批不要求)。
+
+### B01 整批清单二次返修(同日)
+
+按 [整批清单返修复核](migrations/B01-complete-review-2.md) 处理剩余 R4/R6/R8/R9 共 7 项;`tests/b01-complete-review.probe.test.ts` 由 13 扩到 **20/20** 全通过。
+
+- **R4 关闭策略**:`Menu` 只转发菜单级原始策略,`MenuItem` 按「条目显式 → 菜单显式布尔/函数 → 按条目模式默认(动作/单选关闭、多选保持)」解析。默认动作项实测点击后关闭(浏览器 `aria-expanded=false`、菜单消失);single+`false` 与 multiple+`true` 两项通过;Section 级模式同样遵循该优先级。
+- **R6 根面板事件合并**:`onKeydown`/`onEscapeKeyDown`/`onInteractOutside`/`onOpenAutoFocus`/`onAnimationend` 改为「调用方处理器 + 内部处理器」的数组链,调用方先执行,`defaultPrevented` 后内部不再动作。新增回归覆盖四类事件各调用一次、以及调用方取消 Escape 后 `clearSelection` 不再执行。
+- **R9 子菜单参数**:面板属性补齐 `data-*`/`style`/`id`/其他事件透传;`isKeyboardDismissDisabled` 生效(Esc 既不关子层也不关父层,新增回归),`shouldCloseOnInteractOutside` 接到子面板的 outside 链路。
+- **R8 独立 Menu 名称**:独立路径自身提供内容属性通道,`aria-label`/`aria-labelledby`/`aria-describedby` 落在真正的 `role="menu"` 节点(回归 `Standalone actions` 通过),静态布局与无滚动锁保持不变。
+- 回归:**72 文件 / 928 项**通过(含新增 4 项自有回归:根面板事件合并、调用方取消 Escape、子面板禁止 Esc、菜单策略优先于分组模式);typecheck、Prettier 通过;独立 tarball 消费重跑通过;浏览器复验默认动作关闭与三级子菜单逐层 Esc。
+
+### B01 b474a63 复核返修(同日)
+
+按 [b474a63 复核记录](migrations/B01-b474a63-review.md) 处理 R9 子面板透传的 3 个分支与 1 项测试环境异常;探针 **23/23**。
+
+- **子面板 ARIA**:名称优先级为「面板显式 `aria-label` → Menu 内容通道 → 本实例触发器 id」,显式名称存在时移除 `aria-labelledby`,不再被 id 引用压过。探针里 `Direct submenu name` 与 `explicit-description` 均保留。
+- **子面板事件合并**:`onOpenAutoFocus`、`onAnimationend` 与 `onKeydown`、`onInteractOutside` 一样改为「调用方 + 内部」数组链,调用方先执行并按 `defaultPrevented` 取消;`openAutoFocus` 调用次数回归通过。
+- **子菜单 `shouldFocusWrap`**:面板 `loop` 回退到菜单级配置,并统一传布尔值——实测底座属性链会丢弃 `undefined → true` 的更新(`false → true` 生效),因此不能传 `undefined`。双向首尾循环回归通过。
+- **测试环境**:jsdom 缺少 `CSS`,Reka Presence 在 `animationend` 时会调用 `CSS.escape` 抛未捕获错误。新增 `tests/setup/cssom.ts` 仅在缺失时补齐该能力并注册到 `setupFiles`,未关闭错误检查、未吞异常、未改产品行为;单跑与全量都不再有 Unhandled Errors。
+- 回归:**72 文件 / 931 项**通过(无未捕获错误);typecheck、Prettier、`git diff --check` 通过;未重做逐像素/读屏/物理触屏,仍按未验收记录。
+
+## 2026-10-25 B01 最终验收
+
+整批23项复核回归通过;集成人修正CSS.escape测试补丁边界并将相关探针加入test:unit入口。最终pnpm test为73文件/938项通过,无未捕获错误;typecheck、build:docs和diff检查通过。独立消费夹具真实浏览器确认子菜单First向上循环至Last。范围及限制见 `migrations/B01-final-acceptance.md`,不新增SSR/水合/Nuxt要求,未合main、未推送。
+
+## 2026-10-25 B03 Tag / TagGroup / ErrorMessage
+
+迁移与差异范围见 [B03 报告](migrations/B03-tag-error-message.md):Tag、TagGroup、TagGroupList、TagRemoveButton、ErrorMessage 五部件,TagGroup 12 例 + ErrorMessage 2 例,分支 `feat/b03-tag-error-message`(起点 `3532cc6`,未合 main、未推送)。
+
+### 自动化
+
+- `pnpm typecheck`:通过(vue-tsc --noEmit)。
+- `pnpm test`:**74 文件 / 973 项**通过(本批新增 `tests/tag-error-message.test.ts` 35 项,同时加入 `test:unit` 显式列表);连续两次执行结果一致。
+- `pnpm build:docs`:退出码 0;SSG 预渲染阶段曾在 `elementFromRef` 触发 `Element is not defined`,已用非浏览器环境保护修复后重跑通过。
+- `pnpm format`(prettier --check .)与 `git diff --check`:通过。
+- 独立 tarball 消费(`/private/tmp/heroui-b03-consumer`,pnpm 11.25.0 + 两份 `pnpm pack` 产物):`node consume-b03-tag-error-message.mjs` 通过(11 项导出、SSR HTML 契约、CSS 选择器);`b03-tag-error-message-contract.ts` 在 `--moduleResolution bundler` 与 `nodenext` 两种模式下通过,4 个 `@ts-expect-error` 反例均实际触发。
+
+### 浏览器重点验证(127.0.0.1:5183,Chromium/IAB,浅色 + 深色)
+
+- 语义:列表 `role="grid"`、`aria-label` 来自 TagGroup 的 `aria-label`,行 `role="row"`;`Label` 存在时 `aria-labelledby` 指向 Label(`span`),Description/ErrorMessage 的 id 进入 `aria-describedby`。
+- 选择:点击行后 `aria-selected/data-selected` 同步,选中态背景为 `accent-soft`(`oklab(0.6204 -0.0543052 -0.187286 / 0.2)`),单选用 `ArrowRight`/`End` 移动焦点(资讯→旅行→购物),`Space` 切换后原选中项取消。
+- 尺寸/变体:`sm` 2px 8px/12px/12px、`md` 4px 8px/12px/12px、`lg` 6px 10px/14px/16px;`surface` 背景为 `oklch(1 0 0)`,`default` 为 `oklch(0.94 0.001 286.375)`;深色下默认背景 `oklch(0.274 0.006 286.033)`、文字 `oklch(0.9911 0 0)`。
+- 禁用:`isDisabled` 与 `disabledKeys` 均输出 `aria-disabled="true"`/`data-disabled="true"`,计算透明度 0.5。
+- 移除:移除按钮 12×12,`::after` 提供 24×24 命中区;点击后该标签消失,焦点落到原位置的下一个标签(旅行被移除后落到游戏)。
+- 焦点环:键盘聚焦标签时 `:focus-visible` 与 `data-focus-visible="true"` 同时成立,`status-focused` 上屏(2px surface + 4px focus 双层 box-shadow)。
+- 文档:API 表格全部 728px = 正文宽度、`display: table`、`table-layout: fixed`、`scrollWidth === clientWidth`(长 16 行与短 4 行表均无横向溢出);侧栏顺序为 EmptyState → ErrorMessage → FieldError,TagGroup 位于 Tabs 与 TextArea 之间;ErrorMessage 页面渲染 ``。
+
+未验证:逐像素对比、读屏软件、物理触屏、窄屏断点截图。截图在本轮首次采集后 IAB 合成器不再返回帧(`capture timed out`),因此尺寸/配色改为计算样式断言,未以旧截图充当本轮证据。
+
+## B03 复核与接手修复(2026-10-25)
+
+Tag/TagGroup/ErrorMessage 的最新验收见 [B03 复核记录](migrations/B03-review-acceptance.md)。修复属性透传、子控件键盘所有权、禁用/按下状态、gridcell、单 Tab 入口、asChild 和真实浏览器移除焦点时序;新增确认移除公告。47 项本批测试、全套 985 项、类型/文档构建与独立 tarball 消费通过。浏览器仅重点检查移除与键盘,不宣称全量视觉或读屏验收。
+
+## B02a 共享协议阶段(2026-10-25)
+
+阶段复核见 [B02a 验收](migrations/B02a-acceptance.md)。过滤/虚拟焦点协议及真实受限虚拟窗口通过重点验证;静态空集合、嵌套按下状态和测试环境由集成人补齐。相关98项、全套1026项、类型/文档构建通过,无未处理错误。只允许继续B02b–d,不代表ComboBox/Autocomplete公共迁移完成。
+
+## 2026-10-25 B02b ComboBox
+
+部件、示例、文档与测试范围见 [B02 报告](migrations/B02-combobox-autocomplete.md) 第 11 节;本段只记录本轮实际命令与证据。
+
+- `pnpm typecheck` 通过;`pnpm test` **79 文件 / 1051 项**通过;`pnpm build:docs`、Prettier、`git diff --check` 通过。
+- 新增 `tests/combo-box.test.ts`(19 项行为)与 `tests/combo-box-demos.test.ts`(6 项文档/演示契约),均已加入 `test:unit`。
+- 浏览器 5182(Chromium/IAB):输入过滤后焦点仍在输入框、`aria-activedescendant` 指向真实 option、列表只有一个 Tab 入口;`ArrowDown`+`Enter` 回写文本并关闭;`Escape` 移除 `aria-activedescendant`;三个预选示例输入框显示“猫”;禁用示例输入框原生禁用;`ComboBoxValue` 占位文本;form-value 输出 `animal` / `animal-text` 隐藏输入。
+- 未验证:浮层选项的真实鼠标点击(本 IAB 对 floating option 报 `not actionable`,指针保焦点由 B02a harness 覆盖)、真实 IME、读屏软件、逐像素对比、独立 tarball 消费(B02d)。
+
+## 2026-10-25 B02c Autocomplete
+
+范围与适配见 [B02 报告](migrations/B02-combobox-autocomplete.md) 第 12 节;本段只记录本轮命令与证据。
+
+- `pnpm typecheck`、`pnpm build:docs`、`pnpm build:playground`、Prettier、`git diff --check` 通过;`pnpm test` **81 文件 / 1073 项**通过(新增 Autocomplete 17 项行为 + 5 项文档/演示契约,已加入 `test:unit`)。
+- 独立 tarball 消费(`/private/tmp/b02-consumer`,两族共用脚本 `tests/package/consume-b02-pickers.mjs`):导出、SSR HTML 契约、CSS 选择器与变体函数均通过;完整类型正反例矩阵留给 B02d。
+- 浏览器 5182(Chromium/IAB):29 个触发器;打开后焦点进入弹层内 `role="combobox"` 搜索框且 `aria-activedescendant` 指向真实 option;输入 “Te” 只留 Texas 且活动项随之更新;多选 `Enter` 后保持打开并显示标签;空集合示例直接显示“未找到结果”;分组示例 12 行 3 组;虚拟化示例 1000 行仅挂载 12 行,`End` 后 `scrollTop` 49692、活动项在视口内;禁用触发器 `tabindex=-1`;弹层宽度 256 = 触发器宽度;浅/深色触发器背景正确;控制台无 error/warning。
+- 未验证:真实系统 IME、读屏软件、逐像素对比、浮层选项的真实鼠标点击(本 IAB 报 `not actionable`)、完整产物类型正反例(B02d)。
+
+## 2026-10-25 B02 逐示例对照复核
+
+48 个示例逐例与固定基线核对的过程、逐例结论表与差异清单见 [B02 报告](migrations/B02-combobox-autocomplete.md) 第 13 节;本段只记录本轮命令与证据。
+
+- `pnpm typecheck` 通过;`pnpm test` **81 文件 / 1078 项**通过(比 B02c 多 5 项:ComboBox 自定义值回车两例、两族 `data-slot` 契约、Autocomplete 示例搜索框壳层契约);`pnpm build:docs`、`pnpm build:playground`、`pnpm format`、`git diff --check` 通过。
+- 编译产物证据(`pnpm build:docs` 输出 `apps/docs/.vitepress/dist/assets/style.*.css`):`data-slot` 属性值已全部去掉误加的 `hv-` 前缀,`data-slot="hv-` 计数为 0;存在 `.hv-combo-box__trigger[data-open=true] [data-slot=combo-box-trigger-default-icon]{rotate:180deg}`、`.hv-autocomplete__indicator[data-slot=autocomplete-default-indicator]`(1rem)与 `.hv-autocomplete__clear-button [data-slot=autocomplete-clear-button-icon]`(0.875rem)。
+- 浏览器复验本轮未完成:IAB 在 `Page.enable`(20s)与 `Runtime.evaluate`(10s)连续超时,`tabs.new()` 报 `renderer timed out handling IAB create`,`agent.browsers.list()` 仅有 IAB 一个后端、无扩展 Chrome 可切换。因此本轮不声称已完成浏览器视觉复验;B02b/B02c 那两轮的浏览器结果仍有效,但早于本轮 CSS 与自定义值修复,待 IAB 恢复后需补验触发器图标旋转、弹层搜索框 secondary 变体与自定义值展示。
+
+## 2026-10-25 B02 整批退回返修(评审 R1–R10)
+
+逐项映射见 [B02 报告](migrations/B02-combobox-autocomplete.md) 第 14 节;本段只记录本轮命令与证据。
+
+- 探针固化:`tests/b02-review.probe.test.ts`(30 项,已加入 `test:unit`)。修复前 29 失败 / 1 通过,修复后 30 通过。
+- `pnpm typecheck` 通过;`pnpm test` **82 文件 / 1123 项**通过;`pnpm test:unit` 72 文件 / 1087 项通过;`pnpm build:docs`、`pnpm build:playground`、`pnpm format`、`git diff --check` 通过。
+- 独立产物消费:`/private/tmp/heroui-b02-consumer` 用两份新 tarball 安装,`node consume-b02-pickers.mjs` 通过;`b02-pickers-contract.ts` 在 NodeNext 与 bundler 两种解析模式下 tsc 通过(含 `@ts-expect-error` 反例)。
+- 浏览器 5182(Chromium/IAB):原生点击清除按钮后值回到占位符;指示器与 ComboBox 触发器图标计算尺寸 16px、展开时 `rotate: 180deg`;`on-surface` 输入类名为 `hv-input--secondary` 且 `box-shadow` 全零;自定义值输入后回车文本保留并关闭;搜索框 `Tab` 与页面外部点击都不会把焦点抢回触发器。
+- 未验证:真实系统输入法、读屏软件、逐像素对比、独立工程内的浏览器 ESM/CSS 运行、浮层选项真实鼠标点击、嵌套 Modal 逐层 Escape、快速重开。
diff --git a/package.json b/package.json
index db732bc..ef18e7a 100644
--- a/package.json
+++ b/package.json
@@ -15,7 +15,7 @@
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
"typecheck": "vue-tsc --noEmit",
"test": "vitest run",
- "test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/calendar-view.test.ts tests/calendar.test.ts tests/calendar-demos.test.ts tests/range-calendar-foundation.test.ts tests/color-foundation.test.ts tests/color-foundation-probes.test.ts tests/color-input-foundation.test.ts tests/color-input-probes.test.ts tests/color-slider-foundation.test.ts tests/color-picker-composition.test.ts tests/color-field-protocol.test.ts tests/color-picker-protocol.test.ts",
+ "test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/calendar-view.test.ts tests/calendar.test.ts tests/calendar-demos.test.ts tests/range-calendar-foundation.test.ts tests/color-foundation.test.ts tests/color-foundation-probes.test.ts tests/color-input-foundation.test.ts tests/color-input-probes.test.ts tests/color-slider-foundation.test.ts tests/color-picker-composition.test.ts tests/color-field-protocol.test.ts tests/color-picker-protocol.test.ts tests/b01-menu-dropdown.test.ts tests/b01-review.probe.test.ts tests/b01-complete-review.probe.test.ts tests/cssom.test.ts tests/tag-error-message.test.ts tests/collection-filter-virtual.test.ts tests/b02a-review.probe.test.ts tests/b02a-round2-review.probe.test.ts tests/b02-review.probe.test.ts tests/combo-box.test.ts tests/combo-box-demos.test.ts tests/autocomplete.test.ts tests/autocomplete-demos.test.ts tests/b02-public-integration.test.ts",
"test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts tests/select-ssr.test.ts tests/date-foundation-ssr.test.ts tests/date-field-ssr.test.ts tests/m35-m36-ssr.test.ts tests/calendar-ssr.test.ts tests/range-calendar-foundation-ssr.test.ts tests/color-foundation-ssr.test.ts tests/color-input-foundation-ssr.test.ts tests/color-slider-foundation-ssr.test.ts tests/color-field-protocol-ssr.test.ts tests/color-picker-protocol-ssr.test.ts",
"format": "prettier --check .",
"format:fix": "prettier --write .",
diff --git a/packages/styles/components/autocomplete.css b/packages/styles/components/autocomplete.css
new file mode 100644
index 0000000..53a3503
--- /dev/null
+++ b/packages/styles/components/autocomplete.css
@@ -0,0 +1,287 @@
+/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
+ * See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
+/* Autocomplete styles */
+.hv-autocomplete {
+ @apply flex flex-col gap-1;
+}
+
+.hv-autocomplete__trigger {
+ @apply relative isolate inline-flex min-h-9 rounded-field border bg-field px-3 py-2 text-sm text-field-foreground shadow-field outline-none select-none no-highlight;
+
+ /**
+ * Transitions
+ * CRITICAL: motion-reduce must be AFTER transition for correct override specificity
+ */
+ transition:
+ background-color 150ms var(--ease-smooth),
+ border-color 150ms var(--ease-smooth),
+ box-shadow 150ms var(--ease-out);
+ @apply motion-reduce:transition-none;
+
+ /* Cursor */
+ cursor: var(--cursor-interactive);
+
+ border-width: var(--border-width-field);
+ border-color: var(--field-border);
+
+ /* Add inline-end padding when indicator is present */
+ &:has(.hv-autocomplete__indicator) {
+ @apply pe-7;
+ }
+
+ /* Hover state - exclude when clear button is hovered to prevent double hover effect */
+ @media (hover: hover) {
+ &:hover:not(:has(.hv-autocomplete__clear-button:hover)),
+ &[data-hovered="true"]:not(:has(.hv-autocomplete__clear-button:hover)) {
+ @apply bg-field-hover;
+ border-color: var(--field-border-hover);
+ }
+ }
+
+ /* Focus visible state */
+ &:focus-visible:not([data-focused]),
+ &[data-focus-visible="true"] {
+ @apply status-focused;
+ border-color: var(--field-border-focus);
+ background-color: var(--field-focus);
+ }
+
+ /* Focus state */
+ &:focus,
+ &[data-focus="true"] {
+ }
+
+ /* Invalid state */
+ .hv-autocomplete[data-invalid="true"] &,
+ .hv-autocomplete[aria-invalid="true"] & {
+ @apply status-invalid-field;
+ background-color: var(--field-focus);
+ }
+
+ /* Disabled state */
+ &:disabled,
+ &[data-disabled="true"],
+ &[aria-disabled="true"] {
+ @apply status-disabled;
+ }
+}
+
+/* Variant property definitions */
+.hv-autocomplete--primary {
+ /* Default styles */
+}
+
+.hv-autocomplete--secondary .hv-autocomplete__trigger {
+ @apply shadow-none;
+ background-color: var(--hv-autocomplete-trigger-bg);
+
+ --hv-autocomplete-trigger-bg: var(--default);
+ --hv-autocomplete-trigger-bg-hover: var(--default-hover);
+ --hv-autocomplete-trigger-bg-focus: var(--default);
+
+ /* Exclude when clear button is hovered to prevent double hover effect */
+ @media (hover: hover) {
+ &:hover:not(:has(.hv-autocomplete__clear-button:hover)),
+ &[data-hovered="true"]:not(:has(.hv-autocomplete__clear-button:hover)) {
+ background-color: var(--hv-autocomplete-trigger-bg-hover);
+ }
+ }
+
+ &:focus-visible:not([data-focused]),
+ &[data-focus-visible="true"] {
+ background-color: var(--hv-autocomplete-trigger-bg-focus);
+ }
+
+ &:focus,
+ &[data-focus="true"] {
+ }
+
+ .hv-autocomplete[data-invalid="true"] &,
+ .hv-autocomplete[aria-invalid="true"] & {
+ background-color: var(--hv-autocomplete-trigger-bg-focus);
+ }
+}
+
+.hv-autocomplete__value {
+ @apply flex-1 text-start text-base wrap-break-word text-current sm:text-sm;
+
+ &[data-placeholder="true"] {
+ @apply text-field-placeholder;
+ }
+
+ /* Removes the list-box-item indicator element from the hv-autocomplete value*/
+ [data-slot="list-box-item-indicator"] {
+ @apply hidden;
+ }
+}
+
+.hv-autocomplete__indicator {
+ @apply absolute inset-y-0 end-2 my-auto flex shrink-0 items-center justify-center text-field-placeholder transition duration-150;
+
+ /* Cursor */
+ cursor: var(--cursor-interactive);
+
+ &[data-open="true"] {
+ @apply rotate-180;
+ }
+
+ &[data-slot="autocomplete-default-indicator"] {
+ @apply size-4;
+ }
+}
+
+/* Similar to popover content styles */
+.hv-autocomplete__popover {
+ @apply flex w-(--trigger-width) max-w-(--trigger-width) origin-(--trigger-anchor-point) scroll-py-1 flex-col overflow-hidden overscroll-contain bg-overlay p-0 pt-2 text-sm outline-none;
+ border-radius: min(32px, var(--radius-3xl));
+ box-shadow: var(--overlay-shadow);
+
+ &:focus,
+ &:focus-visible:not([data-focused]),
+ &[data-focus-visible="true"] {
+ @apply outline-none;
+ }
+
+ /* Entering animations */
+ &[data-entering="true"] {
+ @apply animate-in duration-250 ease-out-fluid fade-in-0 zoom-in-95;
+
+ /* Placement-specific translations */
+ &[data-placement="top"] {
+ @apply slide-in-from-bottom-1;
+ }
+
+ &[data-placement="bottom"] {
+ @apply slide-in-from-top-1;
+ }
+
+ &[data-placement="left"] {
+ @apply slide-in-from-right-1;
+ }
+
+ &[data-placement="right"] {
+ @apply slide-in-from-left-1;
+ }
+ }
+
+ /* Exiting animations */
+ &[data-exiting="true"] {
+ @apply animate-out duration-100 ease-out-quad zoom-out-95 fade-out;
+ /* Stays non-interactive while closing, even if the exit animation is interrupted. */
+ @apply pointer-events-none;
+ }
+
+ &[data-exiting="true"],
+ &[data-entering="true"] {
+ @apply transition-[opacity,transform] will-change-[opacity,transform];
+ }
+
+ /* Arrow styling */
+ & [data-slot="popover-overlay-arrow"] {
+ fill: var(--overlay);
+ }
+
+ /* Arrow rotation based on placement */
+ &[data-placement="bottom"] [data-slot="popover-overlay-arrow"] {
+ rotate: 180deg;
+ }
+
+ &[data-placement="left"] [data-slot="popover-overlay-arrow"] {
+ rotate: -90deg;
+ }
+
+ &[data-placement="right"] [data-slot="popover-overlay-arrow"] {
+ rotate: 90deg;
+ }
+
+ /* Listbox styles.
+ * `min-h-0` + the popover's flex column let the list shrink below 320px when the
+ * popover itself is constrained (e.g. inside a Modal, or a short viewport). Without
+ * it the list keeps its full 320px and its overflow is clipped by the popover, making
+ * the last options unreachable. */
+ [data-slot="list-box"] {
+ @apply max-h-[320px] min-h-0 scrollbar overflow-y-auto p-1.5 outline-none;
+ }
+
+ [data-slot="list-box-item"] {
+ @apply px-2.5;
+ }
+
+ /* Virtualized rows: react-aria's Virtualizer wraps each row in an absolutely-positioned
+ * [role="presentation"] element whose width equals the scroll container's clientWidth
+ * (which includes the list-box horizontal padding) while sitting inside the padded content
+ * box. Without this, rows overflow the right padding and the hover background reaches the
+ * popover edge. Subtract the horizontal padding (2 × p-1.5 = 12px) to keep rows aligned. */
+ [role="presentation"] > [data-slot="list-box-item"] {
+ width: calc(100% - var(--spacing) * 3);
+ }
+
+ /* As the popover closes fast in single-select mode, the default item indicator transition is not even visible - so we disable it only for single-select */
+ [data-slot="list-box"]:not([aria-multiselectable="true"])
+ [data-slot="list-box-item-indicator"],
+ [data-slot="list-box"]:not([aria-multiselectable="true"])
+ [data-slot="list-box-item-indicator"]
+ [data-slot="list-box-item-indicator--checkmark"] {
+ @apply transition-none;
+ }
+
+ /* Search Field styles */
+ [data-slot="search-field"] {
+ @apply shrink-0 px-3 py-1 outline-none;
+ }
+
+ /* Empty State */
+ [data-slot="empty-state"] {
+ @apply text-center text-sm text-overlay-foreground/60;
+ }
+}
+
+/* Full width modifier */
+.hv-autocomplete--full-width {
+ @apply w-full;
+}
+
+.hv-autocomplete__trigger--full-width {
+ @apply w-full;
+}
+
+/* Clear Button styles */
+.hv-autocomplete__clear-button {
+ @apply relative isolate inline-flex h-6 w-6 shrink-0 origin-center items-center justify-center rounded-xl p-1 text-muted select-none no-highlight;
+ @apply me-0 size-5 shrink-0 self-center bg-transparent;
+
+ /* Cursor */
+ cursor: var(--cursor-interactive);
+
+ @apply transform-gpu;
+
+ /* Transition only when visible - disappears immediately when cleared */
+ &:not([data-empty="true"]) {
+ transition: opacity 150ms var(--ease-smooth);
+ @apply motion-reduce:transition-none;
+ }
+
+ &[data-empty="true"] {
+ @apply pointer-events-none opacity-0;
+ }
+
+ [data-slot="autocomplete-clear-button-icon"] {
+ @apply size-3.5;
+ }
+
+ &:active,
+ &[data-pressed="true"] {
+ }
+
+ @media (hover: hover) {
+ &:hover,
+ &[data-hovered="true"] {
+ @apply bg-default-hover;
+ }
+ }
+
+ &:active,
+ &[data-pressed="true"] {
+ transform: scale(0.93);
+ }
+}
diff --git a/packages/styles/components/combo-box.css b/packages/styles/components/combo-box.css
new file mode 100644
index 0000000..50bccf0
--- /dev/null
+++ b/packages/styles/components/combo-box.css
@@ -0,0 +1,188 @@
+/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
+ * See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
+/* ComboBox styles */
+.hv-combo-box {
+ @apply flex flex-col gap-1;
+
+ &[data-invalid="true"],
+ &[aria-invalid="true"] {
+ [data-slot="description"] {
+ @apply hidden;
+ }
+ }
+
+ [data-slot="label"] {
+ @apply w-fit;
+ }
+
+ [data-slot="input"] {
+ @apply min-w-0 flex-1;
+
+ /* Add inline-end padding when trigger is present */
+ &:has(+ .hv-combo-box__trigger) {
+ @apply pe-7;
+ }
+
+ /* Focus state (input.css only has focus-visible, but hv-combo-box also needs focus) */
+ &:focus,
+ &[data-focus] {
+ @apply status-focused-field;
+ border-color: var(--field-border-focus);
+ background-color: var(--field-focus);
+ }
+
+ /* Disabled state */
+ &:disabled,
+ &[data-disabled],
+ &[aria-disabled="true"] {
+ @apply status-disabled;
+ }
+ }
+}
+
+.hv-combo-box__input-group {
+ @apply relative isolate inline-flex items-center;
+}
+
+.hv-combo-box__value {
+ @apply text-sm wrap-break-word text-field-foreground empty:hidden;
+
+ &[data-placeholder="true"] {
+ @apply text-field-placeholder;
+ }
+
+ /* Removes the list-box-item indicator element from the hv-combo-box value */
+ [data-slot="list-box-item-indicator"] {
+ @apply hidden;
+ }
+}
+
+.hv-combo-box__trigger {
+ @apply absolute end-0 top-1/2 flex h-full shrink-0 -translate-y-1/2 cursor-pointer items-center justify-center pe-2 text-field-placeholder transition duration-150 no-highlight;
+
+ /* Remove default button styles */
+ @apply border-none bg-transparent outline-none;
+
+ /* Hover state */
+ @media (hover: hover) {
+ &:hover,
+ &[data-hovered="true"] {
+ @apply text-field-foreground;
+ }
+ }
+
+ /* Focus visible state */
+ &:focus-visible:not([data-focused]),
+ &[data-focus-visible="true"] {
+ @apply rounded ring-2 ring-focus ring-offset-2 ring-offset-background outline-none;
+ }
+
+ /* Pressed state */
+ &[data-pressed="true"] {
+ @apply opacity-70;
+ }
+
+ /* Disabled state */
+ &:disabled,
+ &[data-disabled],
+ &[aria-disabled="true"] {
+ @apply cursor-not-allowed opacity-50;
+ }
+
+ [data-slot="combo-box-trigger-default-icon"] {
+ @apply size-4 transition-transform duration-150 motion-reduce:transition-none;
+ }
+
+ /* Rotate icon when trigger is open */
+ &[data-open="true"] [data-slot="combo-box-trigger-default-icon"] {
+ @apply rotate-180;
+ }
+}
+
+/* Similar to popover content styles */
+.hv-combo-box__popover {
+ @apply min-w-(--trigger-width) origin-(--trigger-anchor-point) scroll-py-1 scrollbar overflow-y-auto overscroll-contain bg-overlay p-0 text-sm;
+ border-radius: min(32px, var(--radius-3xl));
+ box-shadow: var(--overlay-shadow);
+
+ /* Focus state */
+ &:focus-visible:not([data-focused]),
+ &[data-focus-visible="true"] {
+ @apply outline-none;
+ }
+
+ /* Entering animations */
+ &[data-entering="true"] {
+ @apply animate-in duration-150 ease-smooth fade-in-0 zoom-in-95;
+
+ /* Placement-specific translations */
+ &[data-placement="top"] {
+ @apply slide-in-from-bottom-1;
+ }
+
+ &[data-placement="bottom"] {
+ @apply slide-in-from-top-1;
+ }
+
+ &[data-placement="left"] {
+ @apply slide-in-from-right-1;
+ }
+
+ &[data-placement="right"] {
+ @apply slide-in-from-left-1;
+ }
+ }
+
+ /* Exiting animations */
+ &[data-exiting="true"] {
+ @apply animate-out duration-100 ease-smooth zoom-out-95 fade-out;
+ /* Stays non-interactive while closing, even if the exit animation is interrupted. */
+ @apply pointer-events-none;
+ }
+
+ &[data-exiting="true"],
+ &[data-entering="true"] {
+ @apply transition-[opacity,transform] will-change-[opacity,transform];
+ }
+
+ /* Arrow styling */
+ & [data-slot="popover-overlay-arrow"] {
+ fill: var(--overlay);
+ }
+
+ /* Arrow rotation based on placement */
+ &[data-placement="bottom"] [data-slot="popover-overlay-arrow"] {
+ rotate: 180deg;
+ }
+
+ &[data-placement="left"] [data-slot="popover-overlay-arrow"] {
+ rotate: -90deg;
+ }
+
+ &[data-placement="right"] [data-slot="popover-overlay-arrow"] {
+ rotate: 90deg;
+ }
+
+ /* Listbox styles */
+ [data-slot="list-box"] {
+ @apply p-1.5 outline-none;
+ }
+
+ [data-slot="list-box-item"] {
+ @apply px-2.5;
+
+ /* As the hv-combo-box is single-select, we don't need to animate the checkmark */
+ [data-slot="list-box-item-indicator--checkmark"] {
+ @apply transition-none;
+ }
+ }
+}
+
+/* Full width modifier */
+.hv-combo-box--full-width {
+ @apply w-full;
+}
+
+.hv-combo-box__input-group--full-width {
+ @apply w-full;
+}
diff --git a/packages/styles/components/dropdown.css b/packages/styles/components/dropdown.css
new file mode 100644
index 0000000..193dd3d
--- /dev/null
+++ b/packages/styles/components/dropdown.css
@@ -0,0 +1,144 @@
+/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
+ * Apache-2.0; see third-party/HEROUI-LICENSE. hv- namespace and Vue adapters. */
+/* ==========================================================================
+ Base dropdown styles
+ ========================================================================== */
+
+.hv-dropdown {
+ @apply flex flex-col gap-1;
+}
+
+.hv-dropdown__trigger {
+ @apply inline-block;
+ /* Custom trigger (not a library Button) gets button-like affordances */
+ @apply outline-none;
+ transition:
+ transform 250ms var(--ease-out-quart),
+ background-color 150ms var(--ease-smooth),
+ box-shadow 150ms var(--ease-out);
+ @apply transform-gpu motion-reduce:transition-none;
+
+ cursor: var(--cursor-interactive);
+
+ &:focus-visible:not([data-focused]),
+ &[data-focus-visible="true"] {
+ @apply status-focused;
+ }
+
+ &:disabled,
+ &[aria-disabled="true"] {
+ @apply status-disabled;
+ }
+
+ &[data-pending="true"] {
+ @apply status-pending;
+ }
+
+ &:active,
+ &[data-pressed="true"] {
+ transform: scale(0.97);
+ }
+}
+
+/* Library Button/Avatar keep their own layout when used as a Vue trigger.
+ The custom-trigger affordances above only need to apply to plain elements,
+ so the base layout utilities of those components win back. */
+.hv-dropdown__trigger.hv-button {
+ display: inline-flex;
+}
+
+.hv-dropdown__trigger.hv-avatar {
+ display: flex;
+}
+
+/* Similar to select popover styles.
+ 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-(--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"] {
+ @apply outline-none;
+ }
+
+ /* Entering animations */
+ &[data-entering="true"] {
+ @apply animate-in duration-150 ease-smooth fade-in-0 zoom-in-90;
+
+ &[data-side="top"] {
+ @apply slide-in-from-bottom-1;
+ }
+
+ &[data-side="bottom"] {
+ @apply slide-in-from-top-1;
+ }
+
+ &[data-side="left"] {
+ @apply slide-in-from-right-1;
+ }
+
+ &[data-side="right"] {
+ @apply slide-in-from-left-1;
+ }
+ }
+
+ /* Exiting animations */
+ &[data-exiting="true"] {
+ @apply animate-out duration-100 ease-smooth zoom-out-95 fade-out;
+ @apply pointer-events-none;
+ }
+
+ &[data-exiting="true"],
+ &[data-entering="true"] {
+ @apply transition-[opacity,transform] will-change-[opacity,transform];
+ }
+
+ /* Arrow styling */
+ & [data-slot="popover-overlay-arrow"] {
+ fill: var(--overlay);
+ }
+
+ &[data-side="bottom"] [data-slot="popover-overlay-arrow"] {
+ rotate: 180deg;
+ }
+
+ &[data-side="left"] [data-slot="popover-overlay-arrow"] {
+ rotate: -90deg;
+ }
+
+ &[data-side="right"] [data-slot="popover-overlay-arrow"] {
+ rotate: 90deg;
+ }
+
+ /* Menu styles */
+ [data-slot="dropdown-menu"] {
+ @apply p-1.5 outline-none;
+ }
+
+ [data-slot="menu-item"] {
+ @apply px-2.5;
+ }
+}
+
+.hv-dropdown__menu {
+ @apply relative flex w-full flex-col gap-0.5 overflow-clip p-1;
+
+ [data-slot="separator"] {
+ @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/styles/components/error-message.css b/packages/styles/components/error-message.css
new file mode 100644
index 0000000..5fd73f5
--- /dev/null
+++ b/packages/styles/components/error-message.css
@@ -0,0 +1,15 @@
+/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
+ * See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
+/* Base error message styles */
+.hv-error-message {
+ @apply h-auto text-xs wrap-break-word text-danger;
+
+ /**
+ * Transitions
+ * CRITICAL: motion-reduce must be AFTER transition for correct override specificity
+ */
+ transition:
+ opacity 150ms var(--ease-out),
+ height 350ms var(--ease-smooth);
+ @apply motion-reduce:transition-none;
+}
diff --git a/packages/styles/components/list-box-item.css b/packages/styles/components/list-box-item.css
index c692b82..be18f87 100644
--- a/packages/styles/components/list-box-item.css
+++ b/packages/styles/components/list-box-item.css
@@ -3,6 +3,12 @@
Base list-box item styles
========================================================================== */
+/* Owner-filtered rows stay mounted (text and selection survive) but leave
+ display and keyboard navigation. */
+.hv-list-box-item[data-filtered="true"] {
+ display: none;
+}
+
.hv-list-box-item {
@apply relative flex min-h-9 w-full items-center justify-start gap-3 rounded-2xl px-2 py-1.5 outline-none no-highlight;
diff --git a/packages/styles/components/menu-item.css b/packages/styles/components/menu-item.css
new file mode 100644
index 0000000..f7d8e80
--- /dev/null
+++ b/packages/styles/components/menu-item.css
@@ -0,0 +1,143 @@
+/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
+ * Apache-2.0; see third-party/HEROUI-LICENSE. hv- namespace and Vue adapters. */
+/* ==========================================================================
+ Base menu item styles
+ ========================================================================== */
+
+.hv-menu-item {
+ @apply relative flex min-h-9 w-full items-center justify-start gap-3 rounded-2xl px-2 py-1.5 outline-none no-highlight;
+
+ /**
+ * Transitions
+ * CRITICAL: motion-reduce must be AFTER transition for correct override specificity
+ */
+ transition:
+ transform 250ms var(--ease-out-quart),
+ box-shadow 150ms var(--ease-out);
+
+ @apply motion-reduce:transition-none;
+
+ /* Cursor */
+ cursor: var(--cursor-interactive);
+
+ [data-slot="label"] {
+ @apply pointer-events-none w-fit select-none;
+ }
+
+ [data-slot="description"] {
+ @apply pointer-events-none text-wrap select-none;
+ }
+
+ [data-slot="submenu-indicator"] svg {
+ @apply size-3.5;
+ }
+
+ /* Add inline-start padding when indicator is present */
+ &:has(.hv-menu-item__indicator) {
+ @apply ps-7;
+ }
+
+ /* Add inline-end padding when indicator is present and has submenu */
+ &[data-has-submenu="true"]:has(.hv-menu-item__indicator) {
+ @apply ps-2 pe-7;
+ }
+
+ /* Focus visible state (keyboard focus only). */
+ &:focus-visible:not([data-focused]),
+ &[data-focus-visible="true"] {
+ @apply status-focused;
+ }
+
+ /* Pressed state */
+ &:active,
+ &[data-pressed="true"] {
+ @apply will-change-transform;
+ transform: scale(0.98);
+ }
+
+ /* Hover state */
+ @media (hover: hover) {
+ &:hover,
+ &[data-hovered="true"] {
+ @apply bg-default;
+ }
+ }
+
+ /* Selected state */
+ &[aria-checked="true"],
+ &[aria-selected="true"],
+ &[data-selected="true"] {
+ [data-slot="menu-item-indicator--checkmark"] {
+ transition: stroke-dashoffset 100ms linear;
+ @apply motion-reduce:transition-none;
+ }
+
+ [data-slot="menu-item-indicator--dot"] {
+ @apply scale-100 opacity-100;
+ }
+ }
+
+ /* Disabled state.
+ Reka writes a presence attribute (`data-disabled=""`), not `"true"`. */
+ &[data-disabled] {
+ @apply status-disabled;
+ }
+}
+
+/* ==========================================================================
+ Menu item indicator
+ ========================================================================== */
+
+.hv-menu-item__indicator {
+ @apply absolute start-2 top-1/2 flex size-4 shrink-0 -translate-y-1/2 items-center justify-center text-muted;
+
+ @apply transition duration-250 motion-reduce:transition-none;
+
+ /* Position on the inline-end when menu item has submenu */
+ .hv-menu-item[data-has-submenu="true"] & {
+ @apply start-auto end-2;
+ }
+
+ /* Checkmark SVG indicator */
+ [data-slot="menu-item-indicator--checkmark"] {
+ @apply size-2.5;
+
+ .hv-menu-item[data-selection-mode="multiple"] & {
+ @apply transition-all duration-300 motion-reduce:transition-none;
+ }
+ }
+
+ /* Dot SVG indicator */
+ [data-slot="menu-item-indicator--dot"] {
+ @apply size-2;
+
+ .hv-menu-item[data-selection-mode="multiple"] & {
+ @apply transition-all duration-250 motion-reduce:transition-none;
+ }
+ @apply scale-70 opacity-0;
+ }
+}
+
+/* Submenu indicator (chevron-right) */
+.hv-menu-item__indicator--submenu {
+ @apply text-muted;
+
+ svg {
+ @apply size-3;
+ }
+}
+
+/* Default variant */
+.hv-menu-item--default {
+}
+
+/* Danger variant */
+.hv-menu-item--danger {
+ .hv-menu-item__indicator {
+ @apply text-danger;
+ }
+
+ [data-slot="label"] {
+ @apply text-danger;
+ }
+}
diff --git a/packages/styles/components/menu-section.css b/packages/styles/components/menu-section.css
new file mode 100644
index 0000000..2436518
--- /dev/null
+++ b/packages/styles/components/menu-section.css
@@ -0,0 +1,9 @@
+/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
+ * Apache-2.0; see third-party/HEROUI-LICENSE. hv- namespace and Vue adapters. */
+/* ==========================================================================
+ Base menu section styles
+ ========================================================================== */
+
+.hv-menu-section {
+ @apply flex flex-col items-start gap-0;
+}
diff --git a/packages/styles/components/menu.css b/packages/styles/components/menu.css
new file mode 100644
index 0000000..57d5466
--- /dev/null
+++ b/packages/styles/components/menu.css
@@ -0,0 +1,14 @@
+/* Adapted from HeroUI ce90ea3. Copyright 2025 NextUI Inc.
+ * Apache-2.0; see third-party/HEROUI-LICENSE. hv- namespace and Vue adapters. */
+/* ==========================================================================
+ Base menu styles
+ ========================================================================== */
+
+.hv-menu {
+ @apply relative flex w-full flex-col gap-1 overflow-clip p-1;
+
+ /* This makes the separator take up 94% of the width and be centered */
+ [data-slot="separator"] {
+ @apply ms-[3%] w-[94%];
+ }
+}
diff --git a/packages/styles/components/tag-group.css b/packages/styles/components/tag-group.css
new file mode 100644
index 0000000..369877e
--- /dev/null
+++ b/packages/styles/components/tag-group.css
@@ -0,0 +1,17 @@
+/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
+ * See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
+/* Base styles */
+.hv-tag-group {
+ @apply relative flex flex-col gap-1;
+}
+
+.hv-tag-group__list {
+ @apply relative flex flex-wrap gap-1.5;
+}
+
+.hv-tag-group [slot="description"],
+.hv-tag-group [data-slot="description"],
+.hv-tag-group [slot="errorMessage"],
+.hv-tag-group [data-slot="error-message"] {
+ @apply p-1;
+}
diff --git a/packages/styles/components/tag.css b/packages/styles/components/tag.css
new file mode 100644
index 0000000..6f017dd
--- /dev/null
+++ b/packages/styles/components/tag.css
@@ -0,0 +1,114 @@
+/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
+ * See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
+/* Tag component styles */
+.hv-tag {
+ --optical-offset: 0.031em;
+
+ @apply relative inline-flex items-center gap-1 rounded-xl font-medium select-none no-highlight;
+
+ /* Default size - matches .hv-tag--md */
+ @apply px-2 py-1 text-xs;
+
+ /**
+ * Transitions
+ * CRITICAL: motion-reduce must be AFTER transition for correct override specificity
+ */
+ transition:
+ color 100ms var(--ease-smooth),
+ scale 100ms var(--ease-smooth),
+ opacity 100ms var(--ease-smooth),
+ background-color 100ms var(--ease-smooth),
+ box-shadow 100ms var(--ease-out);
+ @apply origin-center transform-gpu motion-reduce:transition-none;
+
+ /* Cursor */
+ cursor: var(--cursor-interactive);
+
+ /* SVG icon styling */
+ & svg {
+ @apply pointer-events-none size-3 shrink-0 self-center text-current;
+ }
+}
+
+/* Disabled state */
+.hv-tag:is([data-disabled="true"], [aria-disabled="true"]) {
+ @apply status-disabled;
+}
+
+/* Focus visible state (keyboard focus only) */
+.hv-tag:is(:focus-visible, [data-focus-visible]) {
+ @apply status-focused;
+}
+
+/* Pressed/Active state */
+.hv-tag:is(:active, [data-pressed="true"]) {
+}
+
+/* Selected state */
+.hv-tag:is([data-selected="true"], [aria-selected="true"]) {
+ @apply bg-accent-soft text-accent-soft-foreground;
+
+ /* Selected + Hover state */
+ @media (hover: hover) {
+ &:is(:hover, [data-hovered="true"]) {
+ @apply bg-accent-soft-hover;
+ }
+ }
+}
+
+/* Size */
+.hv-tag--sm {
+ @apply px-2 py-0.5 text-xs;
+}
+
+.hv-tag--md {
+ /* No styles as this is the default size */
+}
+
+.hv-tag--lg {
+ @apply rounded-2xl px-2.5 py-1.5 text-sm;
+}
+
+/* Variant */
+.hv-tag--default {
+ @apply bg-default text-default-foreground;
+
+ /* Hover state (when not selected or disabled) */
+ @media (hover: hover) {
+ &:is(:hover, [data-hovered="true"]):not([data-selected="true"]):not(
+ [data-disabled="true"]
+ ) {
+ @apply bg-default-hover;
+ }
+ }
+}
+
+.hv-tag--surface {
+ @apply bg-surface text-surface-foreground;
+
+ /* Hover state (when not selected or disabled) */
+ @media (hover: hover) {
+ &:is(:hover, [data-hovered="true"]):not([data-selected="true"]):not(
+ [data-disabled="true"]
+ ) {
+ @apply bg-surface-hover;
+ }
+ }
+}
+
+/* Remove Button */
+.hv-tag__remove-button {
+ /**
+ * The glyph is 12px, half the minimum target size. A finger tap that misses it lands on the
+ * tag body, which consumes the press without removing anything, so removing a tag by touch
+ * takes several attempts. `touch-target` widens the pressable area to 24px. On `--sm` the
+ * overlay reaches ~2px past the tag box, which the 6px list gap absorbs, so it never
+ * overlaps a neighbouring tag.
+ */
+ @apply touch-target size-3 text-inherit;
+
+ /* SVG icon styling */
+ & svg {
+ @apply size-[inherit] shrink-0 self-center text-current;
+ }
+}
diff --git a/packages/styles/index.css b/packages/styles/index.css
index bcd55d5..c57230b 100644
--- a/packages/styles/index.css
+++ b/packages/styles/index.css
@@ -15,6 +15,7 @@
@import "./components/switch-group.css" layer(components);
@import "./components/label.css" layer(components);
@import "./components/description.css" layer(components);
+@import "./components/error-message.css" layer(components);
@import "./components/surface.css" layer(components);
/* Keep breadcrumbs before link.css, matching the baseline component order.
* Breadcrumb link rules then override Link defaults, while Link's disabled
@@ -149,6 +150,14 @@
@import "./components/list-box.css" layer(components);
@import "./components/list-box-item.css" layer(components);
@import "./components/list-box-section.css" layer(components);
+@import "./components/menu.css" layer(components);
+@import "./components/menu-item.css" layer(components);
+@import "./components/menu-section.css" layer(components);
+@import "./components/dropdown.css" layer(components);
+@import "./components/tag-group.css" layer(components);
+@import "./components/combo-box.css" layer(components);
+@import "./components/autocomplete.css" layer(components);
+@import "./components/tag.css" layer(components);
@import "./components/select.css" layer(components);
diff --git a/packages/styles/src/index.ts b/packages/styles/src/index.ts
index 6817cf4..55bfed7 100644
--- a/packages/styles/src/index.ts
+++ b/packages/styles/src/index.ts
@@ -1627,3 +1627,158 @@ export const calendarYearPickerVariants = tv({
export type CalendarYearPickerVariants = VariantProps<
typeof calendarYearPickerVariants
>;
+
+export const menuVariants = tv({
+ base: "hv-menu",
+});
+
+export type MenuVariants = VariantProps;
+
+export const menuItemVariants = tv({
+ defaultVariants: {
+ variant: "default",
+ },
+ slots: {
+ indicator: "hv-menu-item__indicator",
+ item: "hv-menu-item",
+ submenuIndicator:
+ "hv-menu-item__indicator hv-menu-item__indicator--submenu",
+ },
+ variants: {
+ variant: {
+ danger: {
+ item: "hv-menu-item--danger",
+ },
+ default: {
+ item: "hv-menu-item--default",
+ },
+ },
+ },
+});
+
+export type MenuItemVariants = VariantProps;
+
+export const menuSectionVariants = tv({
+ base: "hv-menu-section",
+});
+
+export type MenuSectionVariants = VariantProps;
+
+export const dropdownVariants = tv({
+ slots: {
+ menu: "hv-dropdown__menu",
+ popover: "hv-dropdown__popover",
+ root: "hv-dropdown",
+ trigger: "hv-dropdown__trigger",
+ },
+});
+
+export type DropdownVariants = VariantProps;
+
+export const tagVariants = tv({
+ defaultVariants: {
+ size: "md",
+ variant: "default",
+ },
+ slots: {
+ base: "hv-tag",
+ removeButton: "hv-tag__remove-button",
+ },
+ variants: {
+ size: {
+ lg: {
+ base: "hv-tag--lg",
+ },
+ md: {
+ base: "hv-tag--md",
+ },
+ sm: {
+ base: "hv-tag--sm",
+ },
+ },
+ variant: {
+ default: {
+ base: "hv-tag--default",
+ },
+ surface: {
+ base: "hv-tag--surface",
+ },
+ },
+ },
+});
+
+export type TagVariants = VariantProps;
+
+export const tagGroupVariants = tv({
+ slots: {
+ base: "hv-tag-group",
+ list: "hv-tag-group__list",
+ },
+});
+
+export type TagGroupVariants = VariantProps;
+
+export const errorMessageVariants = tv({
+ base: "hv-error-message",
+});
+
+export type ErrorMessageVariants = VariantProps;
+
+export const comboBoxVariants = tv({
+ defaultVariants: {
+ fullWidth: false,
+ },
+ slots: {
+ base: "hv-combo-box",
+ inputGroup: "hv-combo-box__input-group",
+ popover: "hv-combo-box__popover",
+ trigger: "hv-combo-box__trigger",
+ value: "hv-combo-box__value",
+ },
+ variants: {
+ fullWidth: {
+ false: {},
+ true: {
+ base: "hv-combo-box--full-width",
+ inputGroup: "hv-combo-box__input-group--full-width",
+ },
+ },
+ },
+});
+
+export type ComboBoxVariants = VariantProps;
+
+export const autocompleteVariants = tv({
+ defaultVariants: {
+ fullWidth: false,
+ variant: "primary",
+ },
+ slots: {
+ base: "hv-autocomplete",
+ clearButton: "hv-autocomplete__clear-button",
+ filter: "hv-autocomplete__filter",
+ indicator: "hv-autocomplete__indicator",
+ popover: "hv-autocomplete__popover",
+ trigger: "hv-autocomplete__trigger",
+ value: "hv-autocomplete__value",
+ },
+ variants: {
+ fullWidth: {
+ false: {},
+ true: {
+ base: "hv-autocomplete--full-width",
+ trigger: "hv-autocomplete__trigger--full-width",
+ },
+ },
+ variant: {
+ primary: {
+ base: "hv-autocomplete--primary",
+ },
+ secondary: {
+ base: "hv-autocomplete--secondary",
+ },
+ },
+ },
+});
+
+export type AutocompleteVariants = VariantProps;
diff --git a/packages/vue/src/components/autocomplete/Autocomplete.vue b/packages/vue/src/components/autocomplete/Autocomplete.vue
new file mode 100644
index 0000000..3e5e614
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/Autocomplete.vue
@@ -0,0 +1,611 @@
+
diff --git a/packages/vue/src/components/autocomplete/AutocompleteClearButton.vue b/packages/vue/src/components/autocomplete/AutocompleteClearButton.vue
new file mode 100644
index 0000000..3c2d7cf
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/AutocompleteClearButton.vue
@@ -0,0 +1,71 @@
+
diff --git a/packages/vue/src/components/autocomplete/AutocompleteFilter.vue b/packages/vue/src/components/autocomplete/AutocompleteFilter.vue
new file mode 100644
index 0000000..6394a5e
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/AutocompleteFilter.vue
@@ -0,0 +1,145 @@
+
diff --git a/packages/vue/src/components/autocomplete/AutocompleteIndicator.vue b/packages/vue/src/components/autocomplete/AutocompleteIndicator.vue
new file mode 100644
index 0000000..9991617
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/AutocompleteIndicator.vue
@@ -0,0 +1,65 @@
+
diff --git a/packages/vue/src/components/autocomplete/AutocompletePopover.vue b/packages/vue/src/components/autocomplete/AutocompletePopover.vue
new file mode 100644
index 0000000..e3edfb9
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/AutocompletePopover.vue
@@ -0,0 +1,50 @@
+
diff --git a/packages/vue/src/components/autocomplete/AutocompleteTrigger.vue b/packages/vue/src/components/autocomplete/AutocompleteTrigger.vue
new file mode 100644
index 0000000..7fe7991
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/AutocompleteTrigger.vue
@@ -0,0 +1,96 @@
+
diff --git a/packages/vue/src/components/autocomplete/AutocompleteValue.vue b/packages/vue/src/components/autocomplete/AutocompleteValue.vue
new file mode 100644
index 0000000..3388d1c
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/AutocompleteValue.vue
@@ -0,0 +1,37 @@
+
diff --git a/packages/vue/src/components/autocomplete/context.ts b/packages/vue/src/components/autocomplete/context.ts
new file mode 100644
index 0000000..e62c097
--- /dev/null
+++ b/packages/vue/src/components/autocomplete/context.ts
@@ -0,0 +1,96 @@
+import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
+import type { autocompleteVariants } from "@heroui-vue/styles";
+import type { CollectionKey } from "../collection/keys";
+import type { CollectionRecord, OwnedCollection } from "../collection/owner";
+import type { useChoiceField } from "../choice/shared";
+
+export type AutocompleteValue = CollectionKey | CollectionKey[] | null;
+export interface AutocompleteSelectedItem {
+ key: CollectionKey;
+ textValue: string;
+}
+export interface AutocompleteOptions {
+ modelValue?: AutocompleteValue;
+ value?: AutocompleteValue;
+ defaultValue?: AutocompleteValue;
+ selectionMode?: "single" | "multiple";
+ disabledKeys?: readonly CollectionKey[];
+ open?: boolean;
+ isOpen?: boolean;
+ defaultOpen?: boolean;
+ isDisabled?: boolean;
+ disabled?: boolean;
+ isRequired?: boolean;
+ isInvalid?: boolean;
+ allowsEmptyCollection?: boolean;
+ placeholder?: string;
+ name?: string;
+ form?: string;
+ fullWidth?: boolean;
+ variant?: "primary" | "secondary";
+ validationBehavior?: "native" | "aria";
+ validate?: (value: AutocompleteValue) => unknown;
+ as?: string;
+ asChild?: boolean;
+}
+/** Scoped-slot state of `AutocompleteValue`. */
+export interface AutocompleteValueState {
+ /** No accepted selection: render the placeholder. */
+ isPlaceholder: boolean;
+ /** Default text: joined `textValue`s, or the placeholder. */
+ defaultChildren: string;
+ /** Accepted `textValue`s joined by ", ". */
+ selectedText: string;
+ selectedItems: AutocompleteSelectedItem[];
+}
+/** Scoped-slot state of the `Autocomplete` root. */
+export interface AutocompleteState {
+ isOpen: boolean;
+ selectedKeys: CollectionKey[];
+}
+export interface AutocompleteItem {
+ id: CollectionKey;
+ textValue: string;
+ isDisabled?: boolean;
+}
+export interface AutocompleteContext {
+ field: ReturnType>;
+ slots: ComputedRef>;
+ open: ComputedRef;
+ setOpen: (open: boolean) => void;
+ keys: ComputedRef;
+ records: ComputedRef;
+ selectedItems: ComputedRef;
+ selectionMode: ComputedRef<"single" | "multiple">;
+ disabled: ComputedRef;
+ invalid: ComputedRef;
+ listId: string;
+ triggerId: string;
+ valueId: string;
+ placeholder: () => string;
+ activeKey: Ref;
+ activeId: ComputedRef;
+ collection: Ref;
+ /** Filter text owned by AutocompleteFilter and read by the collection filter. */
+ filterText: Ref;
+ filterPredicate: Ref<((text: string, input: string) => boolean) | undefined>;
+ filterInput: Ref;
+ triggerElement: Ref;
+ ariaLabel: () => string | undefined;
+ core: () => Record;
+ focusTrigger: () => void;
+ request: (keys: CollectionKey[]) => void;
+ moveActive: (delta: 1 | -1) => void;
+ setActive: (key: CollectionKey | undefined) => Promise;
+ confirmActive: () => void;
+ clear: () => void;
+ composing: Ref;
+}
+export const autocompleteKey: InjectionKey =
+ Symbol("hv-autocomplete");
+
+export function useAutocomplete(): AutocompleteContext {
+ const context = inject(autocompleteKey, undefined);
+ if (!context) throw new Error("Autocomplete parts require Autocomplete.");
+ return context;
+}
diff --git a/packages/vue/src/components/choice/shared.ts b/packages/vue/src/components/choice/shared.ts
index 13f4f27..5e98007 100644
--- a/packages/vue/src/components/choice/shared.ts
+++ b/packages/vue/src/components/choice/shared.ts
@@ -32,6 +32,7 @@ import {
type ValidateResult,
type ValidationBehavior,
} from "../field/context";
+import type { CollectionKey } from "../collection/keys";
import { useInheritedDisabled } from "../field/disabled";
export interface ChoiceFieldProps {
@@ -304,6 +305,51 @@ export function useChoiceForm(
onBeforeUnmount(() => owner?.removeEventListener("reset", onReset));
}
+/**
+ * The native submission layer for key-based pickers: same-name hidden inputs so
+ * a multiple selection arrives as separate entries, nothing at all when the
+ * field is disabled or a key is no longer part of the collection, and a single
+ * text entry when the picker submits text instead of keys.
+ */
+export function selectionInputs(options: {
+ name?: string;
+ form?: string;
+ multiple: boolean;
+ disabled: boolean;
+ keys: readonly CollectionKey[];
+ /** Text submission wins over keys when defined. */
+ text?: string;
+ slot: string;
+}): VNode | null {
+ const { name, form, slot } = options;
+ if (!name || options.disabled) return null;
+ if (options.text !== undefined) {
+ if (!options.text) return null;
+ return h("input", {
+ type: "hidden",
+ name,
+ form,
+ value: options.text,
+ class: "hv-choice-input",
+ "data-slot": slot,
+ });
+ }
+ if (!options.keys.length) return null;
+ return h(
+ "span",
+ { class: "hv-choice-input", "data-slot": `${slot}-entries` },
+ options.keys.map((key) =>
+ h("input", {
+ type: "hidden",
+ name,
+ form,
+ value: String(key),
+ "data-slot": slot,
+ }),
+ ),
+ );
+}
+
export function validationInput(
input: Ref,
props: ChoiceFieldProps,
diff --git a/packages/vue/src/components/collection/match.ts b/packages/vue/src/components/collection/match.ts
new file mode 100644
index 0000000..457c54a
--- /dev/null
+++ b/packages/vue/src/components/collection/match.ts
@@ -0,0 +1,21 @@
+/** Locale-aware base-sensitivity substring matching; no hand-written accent folding. */
+export function createBaseContains(locale?: string) {
+ const collator = new Intl.Collator(locale, {
+ usage: "search",
+ sensitivity: "base",
+ });
+ return (text: string, query: string) => {
+ if (!query) return true;
+ const characters = Array.from(text.normalize("NFC"));
+ const needle = query.normalize("NFC");
+ // Collation expansions (ß/ss, ligatures) need not have equal code-point lengths.
+ for (let start = 0; start < characters.length; start++) {
+ let candidate = "";
+ for (let end = start; end < characters.length; end++) {
+ candidate += characters[end];
+ if (collator.compare(candidate, needle) === 0) return true;
+ }
+ }
+ return false;
+ };
+}
diff --git a/packages/vue/src/components/collection/owner.ts b/packages/vue/src/components/collection/owner.ts
index 8feda08..ae8321f 100644
--- a/packages/vue/src/components/collection/owner.ts
+++ b/packages/vue/src/components/collection/owner.ts
@@ -1,16 +1,43 @@
-import type { ComputedRef, InjectionKey } from "vue";
+import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { CollectionKey } from "./keys";
export interface CollectionRecord {
key: CollectionKey;
text: string;
disabled: boolean;
}
+/** Filtering and virtual focus are optional: absent means the previous behaviour. */
+export interface CollectionView {
+ /**
+ * Filter over the full data set. Filtered-out records stay mounted and keep
+ * their text/selection, but leave display and keyboard navigation.
+ */
+ filter?: (record: CollectionRecord) => boolean;
+ /** Keep DOM focus outside the collection and track `activeKey` instead. */
+ virtualFocus?: () => boolean;
+ /** Active key for virtual focus; the owning composite drives it. */
+ activeKey?: Ref;
+ /**
+ * Keyboard modality shared with the composite that holds DOM focus. The
+ * collection clears it on pointer presses; the composite sets it on keys, so
+ * there is one source instead of a second copy.
+ */
+ keyboardIntent?: Ref;
+ /** The composite's disclosure state; closed collections cancel pending reveals. */
+ isOpen?: () => boolean;
+}
export interface OwnedCollection {
items: () => CollectionRecord[];
focus: (edge: "first" | "last" | "selected") => Promise;
+ /** Mounted DOM id of an option, for `aria-activedescendant`. */
+ optionId?: (key: CollectionKey) => string | undefined;
+ /**
+ * Make `key` the revealed row: scroll a virtualized window first, then wait
+ * for the row to mount. Never moves DOM focus.
+ */
+ reveal?: (key: CollectionKey) => Promise;
}
/** A field composite may own a ListBox, without adding another value store. */
-export interface CollectionOwner {
+export interface CollectionOwner extends CollectionView {
keys: ComputedRef;
mode: ComputedRef<"single" | "multiple">;
disabled: ComputedRef;
diff --git a/packages/vue/src/components/combo-box/ComboBox.vue b/packages/vue/src/components/combo-box/ComboBox.vue
new file mode 100644
index 0000000..3e5983b
--- /dev/null
+++ b/packages/vue/src/components/combo-box/ComboBox.vue
@@ -0,0 +1,819 @@
+
diff --git a/packages/vue/src/components/combo-box/ComboBoxInputGroup.vue b/packages/vue/src/components/combo-box/ComboBoxInputGroup.vue
new file mode 100644
index 0000000..5d623b8
--- /dev/null
+++ b/packages/vue/src/components/combo-box/ComboBoxInputGroup.vue
@@ -0,0 +1,106 @@
+
diff --git a/packages/vue/src/components/combo-box/ComboBoxPopover.vue b/packages/vue/src/components/combo-box/ComboBoxPopover.vue
new file mode 100644
index 0000000..40ab2f9
--- /dev/null
+++ b/packages/vue/src/components/combo-box/ComboBoxPopover.vue
@@ -0,0 +1,47 @@
+
diff --git a/packages/vue/src/components/combo-box/ComboBoxTrigger.vue b/packages/vue/src/components/combo-box/ComboBoxTrigger.vue
new file mode 100644
index 0000000..e16fbf3
--- /dev/null
+++ b/packages/vue/src/components/combo-box/ComboBoxTrigger.vue
@@ -0,0 +1,77 @@
+
diff --git a/packages/vue/src/components/combo-box/ComboBoxValue.vue b/packages/vue/src/components/combo-box/ComboBoxValue.vue
new file mode 100644
index 0000000..777122d
--- /dev/null
+++ b/packages/vue/src/components/combo-box/ComboBoxValue.vue
@@ -0,0 +1,35 @@
+
diff --git a/packages/vue/src/components/combo-box/context.ts b/packages/vue/src/components/combo-box/context.ts
new file mode 100644
index 0000000..7478c72
--- /dev/null
+++ b/packages/vue/src/components/combo-box/context.ts
@@ -0,0 +1,104 @@
+import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
+import type { comboBoxVariants } from "@heroui-vue/styles";
+import type { CollectionKey } from "../collection/keys";
+import type { CollectionRecord, OwnedCollection } from "../collection/owner";
+import type { useChoiceField } from "../choice/shared";
+
+export type ComboBoxValue = CollectionKey | CollectionKey[] | null;
+export type ComboBoxMenuTrigger = "focus" | "input" | "manual";
+export interface ComboBoxItem {
+ id: CollectionKey;
+ textValue: string;
+ isDisabled?: boolean;
+}
+/** Scoped-slot state of the `ComboBox` root. */
+export interface ComboBoxState {
+ isOpen: boolean;
+ inputValue: string;
+ selectedKey: CollectionKey | null;
+ selectedKeys: CollectionKey[];
+}
+/** Scoped-slot state of `ComboBoxValue`. */
+export interface ComboBoxValueState {
+ isPlaceholder: boolean;
+ selectedItems: ComboBoxSelectedItem[];
+}
+export interface ComboBoxSelectedItem {
+ key: CollectionKey;
+ textValue: string;
+}
+/** Props shared by the SFC and the context; keep one schema. */
+export interface ComboBoxOptions {
+ modelValue?: ComboBoxValue;
+ value?: ComboBoxValue;
+ defaultValue?: ComboBoxValue;
+ selectedKey?: CollectionKey | null;
+ defaultSelectedKey?: CollectionKey | null;
+ selectionMode?: "single" | "multiple";
+ inputValue?: string;
+ defaultInputValue?: string;
+ items?: readonly ComboBoxItem[];
+ disabledKeys?: readonly CollectionKey[];
+ open?: boolean;
+ isOpen?: boolean;
+ defaultOpen?: boolean;
+ defaultFilter?: (text: string, inputValue: string) => boolean;
+ isDisabled?: boolean;
+ disabled?: boolean;
+ isReadOnly?: boolean;
+ isRequired?: boolean;
+ isInvalid?: boolean;
+ allowsCustomValue?: boolean;
+ allowsEmptyCollection?: boolean;
+ menuTrigger?: ComboBoxMenuTrigger;
+ shouldFocusWrap?: boolean;
+ fullWidth?: boolean;
+ variant?: "primary" | "secondary";
+ name?: string;
+ form?: string;
+ formValue?: "key" | "text";
+ autoComplete?: string;
+ autoFocus?: boolean;
+ validationBehavior?: "native" | "aria";
+ placeholder?: string;
+}
+export interface ComboBoxContext {
+ field: ReturnType>;
+ slots: ComputedRef>;
+ open: ComputedRef;
+ setOpen: (open: boolean) => void;
+ inputValue: ComputedRef;
+ /** Text shown in the input: the accepted item's label before any typing. */
+ displayInputValue: ComputedRef;
+ setInputValue: (value: string) => void;
+ inputId: string;
+ listId: string;
+ valueId: string;
+ placeholder: () => string;
+ activeKey: Ref;
+ activeId: ComputedRef;
+ collection: Ref;
+ keys: ComputedRef;
+ records: ComputedRef;
+ selectedItems: ComputedRef;
+ selectionMode: ComputedRef<"single" | "multiple">;
+ allowsCustomValue: () => boolean;
+ menuTrigger: () => ComboBoxMenuTrigger;
+ inputElement: Ref;
+ registerAnchor: (element: () => HTMLElement | undefined) => void;
+ triggerElement: Ref;
+ /** ARIA plus input handlers injected onto the composed `Input`. */
+ inputProps: () => Record;
+ formValueText: ComputedRef;
+ variant: () => "primary" | "secondary";
+ invalid: ComputedRef;
+ disabled: ComputedRef;
+}
+export const comboBoxKey: InjectionKey =
+ Symbol("hv-combo-box");
+
+export function useComboBox(): ComboBoxContext {
+ const context = inject(comboBoxKey, undefined);
+ if (!context) throw new Error("ComboBox parts require ComboBox.");
+ return context;
+}
diff --git a/packages/vue/src/components/combo-box/dom.ts b/packages/vue/src/components/combo-box/dom.ts
new file mode 100644
index 0000000..20a11e1
--- /dev/null
+++ b/packages/vue/src/components/combo-box/dom.ts
@@ -0,0 +1,14 @@
+/** Resolve a component ref handle (or element) to its DOM node. */
+export function elementFromRef(value: unknown): HTMLElement | undefined {
+ if (typeof Element === "undefined") return undefined;
+ if (value instanceof Element) return value as HTMLElement;
+ const element = (value as { $el?: unknown } | null)?.$el;
+ return element instanceof Element ? (element as HTMLElement) : undefined;
+}
+
+/**
+ * Vue vnode shape bits (not exported by the package). `cloneVNode` copies
+ * `shapeFlag`, so replacing an element's children needs these to stay coherent.
+ */
+export const SHAPE_TEXT_CHILDREN = 8;
+export const SHAPE_ARRAY_CHILDREN = 16;
diff --git a/packages/vue/src/components/combo-box/metadata.ts b/packages/vue/src/components/combo-box/metadata.ts
new file mode 100644
index 0000000..af4417d
--- /dev/null
+++ b/packages/vue/src/components/combo-box/metadata.ts
@@ -0,0 +1,134 @@
+import { Fragment, Text, isVNode, type VNode, type VNodeChild } from "vue";
+import { assertKey, type CollectionKey } from "../collection/keys";
+import type { CollectionRecord } from "../collection/owner";
+
+function name(node: VNode) {
+ const type = node.type as { name?: string; __name?: string } | undefined;
+ return type?.name ?? type?.__name;
+}
+function children(node: VNode): VNodeChild[] {
+ if (Array.isArray(node.children)) return node.children as VNodeChild[];
+ if (node.children && typeof node.children === "object") {
+ const result = (
+ node.children as { default?: () => VNodeChild }
+ ).default?.();
+ return Array.isArray(result) ? result : result == null ? [] : [result];
+ }
+ return typeof node.children === "string" ? [node.children] : [];
+}
+function text(nodes: VNodeChild[]): string {
+ return nodes
+ .map((node) => {
+ if (typeof node === "string" || typeof node === "number")
+ return String(node);
+ if (Array.isArray(node)) return text(node);
+ if (!isVNode(node)) return "";
+ if (node.type === Text) return String(node.children);
+ if (
+ node.type === Fragment ||
+ typeof node.type === "string" ||
+ name(node) === "Label"
+ )
+ return text(children(node));
+ return "";
+ })
+ .join("")
+ .trim();
+}
+
+const CONTAINERS = [
+ "ComboBoxPopover",
+ "AutocompletePopover",
+ "AutocompleteFilter",
+ "SelectPopover",
+ "ListBoxSection",
+];
+
+/**
+ * Collect collection metadata from a picker's slot tree. Filtering, the initial
+ * value label and form text need the full data set before the popover (and
+ * therefore the ListBox) has ever mounted.
+ */
+export function planCollectionItems(nodes: VNodeChild[]) {
+ const records: CollectionRecord[] = [];
+ let found = false;
+ let opaque = false;
+ function add(record: CollectionRecord) {
+ assertKey(record.key);
+ if (records.some((item) => item.key === record.key))
+ throw new Error(`Duplicate collection key: ${record.key}`);
+ records.push(record);
+ }
+ function walk(
+ nodes: VNodeChild[],
+ inside = false,
+ blocked: readonly CollectionKey[] = [],
+ ) {
+ for (const node of nodes) {
+ if (Array.isArray(node)) {
+ walk(node, inside, blocked);
+ continue;
+ }
+ if (!isVNode(node)) continue;
+ const component = name(node);
+ if (component === "ListBoxItem") {
+ const key = node.props?.id;
+ const disabled = node.props?.isDisabled ?? node.props?.["is-disabled"];
+ add({
+ key,
+ text:
+ node.props?.textValue ??
+ node.props?.["text-value"] ??
+ text(children(node)),
+ disabled:
+ disabled === true || disabled === "" || blocked.includes(key),
+ });
+ } else if (component === "ListBox") {
+ found = true;
+ const disabledKeys =
+ node.props?.disabledKeys ?? node.props?.["disabled-keys"] ?? [];
+ const keys = [...blocked, ...disabledKeys] as CollectionKey[];
+ if (node.props?.items) {
+ const slot = (
+ node.children as { default?: (state: unknown) => VNodeChild[] }
+ )?.default;
+ const items = node.props.items as {
+ id: CollectionKey;
+ textValue?: string;
+ isDisabled?: boolean;
+ }[];
+ items.forEach((item, index) => {
+ const before = records.length;
+ if (slot) {
+ const rendered = slot({ item, index });
+ walk(Array.isArray(rendered) ? rendered : [rendered], true, keys);
+ }
+ if (records.length === before)
+ add({
+ key: item.id,
+ text: item.textValue ?? String(item.id),
+ disabled: !!item.isDisabled || keys.includes(item.id),
+ });
+ else if (item.isDisabled)
+ records.slice(before).forEach((record) => {
+ record.disabled = true;
+ });
+ });
+ } else walk(children(node), true, keys);
+ } else if (
+ node.type === Fragment ||
+ typeof node.type === "string" ||
+ CONTAINERS.includes(component ?? "")
+ )
+ walk(children(node), inside, blocked);
+ else if (
+ inside &&
+ component &&
+ !["Header", "Separator"].includes(component)
+ )
+ opaque = true;
+ }
+ }
+ walk(nodes);
+ return { records, complete: found && !opaque };
+}
diff --git a/packages/vue/src/components/combo-box/useTriggerWidth.ts b/packages/vue/src/components/combo-box/useTriggerWidth.ts
new file mode 100644
index 0000000..c35abf1
--- /dev/null
+++ b/packages/vue/src/components/combo-box/useTriggerWidth.ts
@@ -0,0 +1,27 @@
+import { onBeforeUnmount, ref, watchEffect } from "vue";
+
+/**
+ * Track the anchor's border-box width so a popover can match it. Reka does not
+ * expose the anchor size without its own trigger component, so the width is
+ * measured here (the baseline component measures its trigger the same way).
+ */
+export function useTriggerWidth(get: () => HTMLElement | undefined) {
+ const width = ref();
+ let observer: ResizeObserver | undefined;
+ watchEffect(() => {
+ const element = get();
+ observer?.disconnect();
+ observer = undefined;
+ if (!element) return;
+ const measure = () => {
+ width.value = element.offsetWidth || undefined;
+ };
+ measure();
+ if (typeof ResizeObserver === "function") {
+ observer = new ResizeObserver(measure);
+ observer.observe(element);
+ }
+ });
+ onBeforeUnmount(() => observer?.disconnect());
+ return width;
+}
diff --git a/packages/vue/src/components/dropdown/DropdownItem.vue b/packages/vue/src/components/dropdown/DropdownItem.vue
new file mode 100644
index 0000000..35f8846
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownItem.vue
@@ -0,0 +1,47 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownItemIndicator.vue b/packages/vue/src/components/dropdown/DropdownItemIndicator.vue
new file mode 100644
index 0000000..850e065
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownItemIndicator.vue
@@ -0,0 +1,12 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownMenu.vue b/packages/vue/src/components/dropdown/DropdownMenu.vue
new file mode 100644
index 0000000..4355e62
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownMenu.vue
@@ -0,0 +1,55 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownPopover.vue b/packages/vue/src/components/dropdown/DropdownPopover.vue
new file mode 100644
index 0000000..ba1b142
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownPopover.vue
@@ -0,0 +1,261 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownRoot.vue b/packages/vue/src/components/dropdown/DropdownRoot.vue
new file mode 100644
index 0000000..7a911c8
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownRoot.vue
@@ -0,0 +1,87 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownSection.vue b/packages/vue/src/components/dropdown/DropdownSection.vue
new file mode 100644
index 0000000..644235a
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownSection.vue
@@ -0,0 +1,47 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownSubmenuIndicator.vue b/packages/vue/src/components/dropdown/DropdownSubmenuIndicator.vue
new file mode 100644
index 0000000..8e50f61
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownSubmenuIndicator.vue
@@ -0,0 +1,12 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownSubmenuTrigger.vue b/packages/vue/src/components/dropdown/DropdownSubmenuTrigger.vue
new file mode 100644
index 0000000..4210930
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownSubmenuTrigger.vue
@@ -0,0 +1,397 @@
+
diff --git a/packages/vue/src/components/dropdown/DropdownTrigger.vue b/packages/vue/src/components/dropdown/DropdownTrigger.vue
new file mode 100644
index 0000000..c514f43
--- /dev/null
+++ b/packages/vue/src/components/dropdown/DropdownTrigger.vue
@@ -0,0 +1,196 @@
+
diff --git a/packages/vue/src/components/dropdown/dom.ts b/packages/vue/src/components/dropdown/dom.ts
new file mode 100644
index 0000000..14026cc
--- /dev/null
+++ b/packages/vue/src/components/dropdown/dom.ts
@@ -0,0 +1,36 @@
+import type { VNode } from "vue";
+
+/** Resolve a component/ref handle to its DOM element. */
+export function elementFromValue(value: unknown): HTMLElement | null {
+ if (value instanceof Element) return value as HTMLElement;
+ const el = (value as { $el?: unknown } | null)?.$el;
+ return el instanceof Element ? (el as HTMLElement) : null;
+}
+
+/**
+ * Resolve the element a vnode mounted to. Reka's content components expose the
+ * positioned element through `$el`; fragments (text nodes) resolve to null.
+ */
+export function elementFromVNode(
+ vnode: VNode | null | undefined,
+): HTMLElement | null {
+ if (!vnode) return null;
+ const el = vnode.el;
+ if (el instanceof Element) return el as HTMLElement;
+ const proxyEl = (vnode.component?.proxy as { $el?: unknown } | null)?.$el;
+ return proxyEl instanceof Element ? (proxyEl as HTMLElement) : null;
+}
+
+/**
+ * Reka renders a positioning wrapper around the menu surface; the popover
+ * styles and animations live on the inner `[data-reka-menu-content]` node.
+ */
+export function menuSurfaceFromVNode(
+ vnode: VNode | null | undefined,
+): HTMLElement | null {
+ const el = elementFromVNode(vnode);
+ if (!el) return null;
+ if (el.matches("[data-reka-menu-content]")) return el;
+ const inner = el.querySelector("[data-reka-menu-content]");
+ return inner instanceof Element ? (inner as HTMLElement) : el;
+}
diff --git a/packages/vue/src/components/error-message/ErrorMessage.vue b/packages/vue/src/components/error-message/ErrorMessage.vue
new file mode 100644
index 0000000..e400cec
--- /dev/null
+++ b/packages/vue/src/components/error-message/ErrorMessage.vue
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
diff --git a/packages/vue/src/components/header/HeaderRoot.vue b/packages/vue/src/components/header/HeaderRoot.vue
index d3a71c6..c1f223f 100644
--- a/packages/vue/src/components/header/HeaderRoot.vue
+++ b/packages/vue/src/components/header/HeaderRoot.vue
@@ -1,6 +1,15 @@
diff --git a/packages/vue/src/components/menu-item/MenuItemIndicator.vue b/packages/vue/src/components/menu-item/MenuItemIndicator.vue
new file mode 100644
index 0000000..975c261
--- /dev/null
+++ b/packages/vue/src/components/menu-item/MenuItemIndicator.vue
@@ -0,0 +1,90 @@
+
diff --git a/packages/vue/src/components/menu-item/MenuItemSubmenuIndicator.vue b/packages/vue/src/components/menu-item/MenuItemSubmenuIndicator.vue
new file mode 100644
index 0000000..b83ae30
--- /dev/null
+++ b/packages/vue/src/components/menu-item/MenuItemSubmenuIndicator.vue
@@ -0,0 +1,65 @@
+
diff --git a/packages/vue/src/components/menu-section/MenuSection.vue b/packages/vue/src/components/menu-section/MenuSection.vue
new file mode 100644
index 0000000..678ccc1
--- /dev/null
+++ b/packages/vue/src/components/menu-section/MenuSection.vue
@@ -0,0 +1,153 @@
+
diff --git a/packages/vue/src/components/menu/Menu.vue b/packages/vue/src/components/menu/Menu.vue
new file mode 100644
index 0000000..4982ed6
--- /dev/null
+++ b/packages/vue/src/components/menu/Menu.vue
@@ -0,0 +1,256 @@
+
diff --git a/packages/vue/src/components/menu/context.ts b/packages/vue/src/components/menu/context.ts
new file mode 100644
index 0000000..3809c3a
--- /dev/null
+++ b/packages/vue/src/components/menu/context.ts
@@ -0,0 +1,119 @@
+import type { ComputedRef, InjectionKey, Ref } from "vue";
+
+export type MenuKey = string | number;
+
+export type MenuSelectionMode = "none" | "single" | "multiple";
+
+export interface MenuSelectionOwner {
+ selectionMode: ComputedRef;
+ selectedKeys: ComputedRef>;
+ /** Submit a selection proposal. Parent decides accepted value. */
+ proposeSelection: (key: MenuKey) => void;
+ isItemSelected: (key: MenuKey) => boolean;
+ isItemDisabled: (key: MenuKey) => boolean;
+}
+
+export interface MenuContextValue {
+ /** Close the nearest menu level (not parent menus). */
+ closeLevel: () => void;
+ /** Fire the menu-level action callback. */
+ emitAction: (key: MenuKey) => void;
+ /** Selection owner (menu-level); section may override. */
+ selection: MenuSelectionOwner;
+ /** Root selection mode for data-selection-mode styling. */
+ selectionMode: ComputedRef;
+ /**
+ * Menu-level close policy for activation (official `shouldCloseOnSelect`).
+ * Undefined means "no explicit policy"; the item then applies the per-mode
+ * default.
+ */
+ shouldCloseOnSelect: ComputedRef<
+ boolean | ((key: MenuKey) => boolean) | undefined
+ >;
+ /** Number of mounted items, used for the empty-state slot. */
+ itemCount: Ref;
+ registerItem: () => () => void;
+}
+
+export const menuContextKey: InjectionKey = Symbol("hv-menu");
+
+export interface MenuSectionContextValue {
+ selection: MenuSelectionOwner;
+}
+
+/** `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. */
+export interface MenuSectionLabelValue {
+ labelledBy: ComputedRef;
+ registerLabel: (id: string) => () => void;
+}
+
+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;
+ isDisabled: ComputedRef;
+ isSelected: ComputedRef;
+ isFocused: Ref;
+ isPressed: Ref;
+ hasSubmenu: ComputedRef;
+ setHasSubmenu: (value: boolean) => void;
+}
+
+export const menuItemContextKey: InjectionKey =
+ Symbol("hv-menu-item");
+
+/** 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",
+);
+
+export interface DropdownTriggerModeValue {
+ triggerMode: ComputedRef<"press" | "longPress">;
+ 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 {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ slots: ComputedRef;
+}
+
+export const dropdownContextKey: InjectionKey =
+ Symbol("hv-dropdown");
diff --git a/packages/vue/src/components/menu/useMenuSelection.ts b/packages/vue/src/components/menu/useMenuSelection.ts
new file mode 100644
index 0000000..94ba8b1
--- /dev/null
+++ b/packages/vue/src/components/menu/useMenuSelection.ts
@@ -0,0 +1,55 @@
+import { computed, type ComputedRef, type Ref } from "vue";
+import type {
+ MenuKey,
+ MenuSelectionMode,
+ MenuSelectionOwner,
+} from "../menu/context";
+
+export interface UseMenuSelectionOptions {
+ selectionMode: Ref | ComputedRef;
+ selectedKeys:
+ 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;
+}
+
+/**
+ * Menu/section selection owner. Proposals are one-shot toggles; the parent
+ * emits the next keys and keeps ownership of the accepted value.
+ */
+export function useMenuSelection(
+ options: UseMenuSelectionOptions,
+): MenuSelectionOwner {
+ const isItemSelected = (key: MenuKey) =>
+ options.selectedKeys.value.some((k) => k === key);
+ const isItemDisabled = (key: MenuKey) =>
+ options.disabledKeys?.value.some((k) => k === key) ?? false;
+
+ const proposeSelection = (key: MenuKey) => {
+ const mode = options.selectionMode.value;
+ if (mode === "none") return;
+ const current = options.selectedKeys.value;
+ const has = isItemSelected(key);
+ if (mode === "single") {
+ if (has && options.disallowEmptySelection?.value) return;
+ options.onSelectionChange(has ? [] : [key]);
+ return;
+ }
+ const next = has ? current.filter((k) => k !== key) : [...current, key];
+ if (has && next.length === 0 && options.disallowEmptySelection?.value)
+ return;
+ options.onSelectionChange(next);
+ };
+
+ return {
+ selectionMode: computed(() => options.selectionMode.value),
+ selectedKeys: computed(() => options.selectedKeys.value),
+ proposeSelection,
+ isItemSelected,
+ isItemDisabled,
+ };
+}
diff --git a/packages/vue/src/components/tag/Tag.vue b/packages/vue/src/components/tag/Tag.vue
new file mode 100644
index 0000000..88b4e0c
--- /dev/null
+++ b/packages/vue/src/components/tag/Tag.vue
@@ -0,0 +1,308 @@
+
diff --git a/packages/vue/src/components/tag/TagGroup.vue b/packages/vue/src/components/tag/TagGroup.vue
new file mode 100644
index 0000000..8c6039f
--- /dev/null
+++ b/packages/vue/src/components/tag/TagGroup.vue
@@ -0,0 +1,541 @@
+
diff --git a/packages/vue/src/components/tag/TagGroupList.vue b/packages/vue/src/components/tag/TagGroupList.vue
new file mode 100644
index 0000000..99336e9
--- /dev/null
+++ b/packages/vue/src/components/tag/TagGroupList.vue
@@ -0,0 +1,106 @@
+
+
+
+
+
+
+
+
+
+
+ ]
+
+
+
+
+
+
+ {{ group.announcement.value }}
+
+
diff --git a/packages/vue/src/components/tag/TagRemoveButton.vue b/packages/vue/src/components/tag/TagRemoveButton.vue
new file mode 100644
index 0000000..56901b8
--- /dev/null
+++ b/packages/vue/src/components/tag/TagRemoveButton.vue
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
diff --git a/packages/vue/src/components/tag/context.ts b/packages/vue/src/components/tag/context.ts
new file mode 100644
index 0000000..bbcf762
--- /dev/null
+++ b/packages/vue/src/components/tag/context.ts
@@ -0,0 +1,88 @@
+import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
+import type { tagGroupVariants, tagVariants } from "@heroui-vue/styles";
+import type { CollectionKey } from "../collection/keys";
+import type { CollectionMember } from "../collection/registry";
+import type { CollectionSelectionMode } from "../collection/selection";
+
+export type TagKey = CollectionKey;
+export interface TagGroupDataItem {
+ id: TagKey;
+ textValue?: string;
+ isDisabled?: boolean;
+}
+/** Public schema shared by the SFC props and the context. */
+export interface TagGroupOptions {
+ modelValue?: readonly TagKey[];
+ selectedKeys?: readonly TagKey[];
+ defaultValue?: readonly TagKey[];
+ defaultSelectedKeys?: readonly TagKey[];
+ selectionMode?: CollectionSelectionMode;
+ disabledKeys?: readonly TagKey[];
+ isDisabled?: boolean;
+ disallowEmptySelection?: boolean;
+ size?: "sm" | "md" | "lg";
+ variant?: "default" | "surface";
+ dir?: "ltr" | "rtl";
+ as?: string;
+ asChild?: boolean;
+}
+export interface TagRenderState {
+ isSelected: boolean;
+ isDisabled: boolean;
+ isHovered: boolean;
+ isPressed: boolean;
+ isFocused: boolean;
+ isFocusVisible: boolean;
+ allowsRemoving: boolean;
+}
+export interface TagMember extends CollectionMember {
+ noteBlur: () => void;
+}
+export interface TagGroupListProps<
+ T extends TagGroupDataItem = TagGroupDataItem,
+> {
+ items?: readonly T[];
+ as?: string;
+ asChild?: boolean;
+}
+export interface TagGroupContext {
+ announcement: Ref;
+ slots: ComputedRef>;
+ tagSlots: ComputedRef>;
+ mode: ComputedRef;
+ disabled: ComputedRef;
+ selected: (key: TagKey) => boolean;
+ isDisabledKey: (key: TagKey) => boolean;
+ allowsRemoving: () => boolean;
+ requestRemoval: (key: TagKey) => void;
+ register: (member: TagMember) => () => void;
+ hasEnabled: () => boolean;
+ registerList: (element: () => HTMLElement | undefined) => void;
+ active: ComputedRef;
+ focused: Ref;
+ pressed: Ref;
+ keyboard: Ref;
+ activate: (key: TagKey, event: MouseEvent | KeyboardEvent) => void;
+ focus: (key: TagKey) => Promise;
+ noteFocus: (key: TagKey) => void;
+ textValue: (key: TagKey) => string;
+ ariaLabel: () => string | undefined;
+ labelledBy: () => string | undefined;
+ describedBy: () => string | undefined;
+ onKeydown: (event: KeyboardEvent) => void;
+ onKeyup: (event: KeyboardEvent) => void;
+}
+export interface TagContext {
+ disabled: ComputedRef;
+ tagSlots: ComputedRef>;
+ textValue: () => string;
+}
+export const tagGroupKey: InjectionKey =
+ Symbol("hv-tag-group");
+export const tagKey: InjectionKey = Symbol("hv-tag");
+
+export function useTagGroup(): TagGroupContext {
+ const context = inject(tagGroupKey, undefined);
+ if (!context) throw new Error("Tag requires TagGroup and TagGroupList.");
+ return context;
+}
diff --git a/packages/vue/src/components/tag/dom.ts b/packages/vue/src/components/tag/dom.ts
new file mode 100644
index 0000000..b36e492
--- /dev/null
+++ b/packages/vue/src/components/tag/dom.ts
@@ -0,0 +1,9 @@
+/** Reka's Primitive exposes the element through `$el`, not as a DOM node. */
+export function elementFromRef(value: unknown): HTMLElement | undefined {
+ // Server rendering and prerendering have no DOM; the collection then keeps
+ // registration order because no element is available.
+ if (typeof Element === "undefined") return undefined;
+ if (value instanceof Element) return value as HTMLElement;
+ const element = (value as { $el?: unknown } | null)?.$el;
+ return element instanceof Element ? (element as HTMLElement) : undefined;
+}
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index e9b9537..551cea9 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -950,3 +950,136 @@ export type {
} from "@heroui-vue/styles";
export type { CalendarYearPickerTriggerState as CalendarYearPickerTriggerRenderProps } from "./components/calendar/year-picker";
export type { CalendarYearState as CalendarYearPickerCellRenderProps } from "./components/calendar/context";
+
+/* Menu / Dropdown (B01) */
+export { default as Menu } from "./components/menu/Menu.vue";
+export { default as MenuRoot } from "./components/menu/Menu.vue";
+export { default as MenuItem } from "./components/menu-item/MenuItem.vue";
+export { default as MenuItemIndicator } from "./components/menu-item/MenuItemIndicator.vue";
+export { default as MenuItemSubmenuIndicator } from "./components/menu-item/MenuItemSubmenuIndicator.vue";
+export { default as MenuSection } from "./components/menu-section/MenuSection.vue";
+export { default as DropdownRoot } from "./components/dropdown/DropdownRoot.vue";
+export { default as DropdownTrigger } from "./components/dropdown/DropdownTrigger.vue";
+export { default as DropdownPopover } from "./components/dropdown/DropdownPopover.vue";
+export { default as DropdownMenu } from "./components/dropdown/DropdownMenu.vue";
+export { default as DropdownSection } from "./components/dropdown/DropdownSection.vue";
+export { default as DropdownItem } from "./components/dropdown/DropdownItem.vue";
+export { default as DropdownItemIndicator } from "./components/dropdown/DropdownItemIndicator.vue";
+export { default as DropdownSubmenuIndicator } from "./components/dropdown/DropdownSubmenuIndicator.vue";
+export { default as DropdownSubmenuTrigger } from "./components/dropdown/DropdownSubmenuTrigger.vue";
+export {
+ menuVariants,
+ menuItemVariants,
+ menuSectionVariants,
+ dropdownVariants,
+ type MenuVariants,
+ type MenuItemVariants,
+ type MenuSectionVariants,
+ type DropdownVariants,
+} from "@heroui-vue/styles";
+export type { MenuKey, MenuSelectionMode } from "./components/menu/context";
+
+export type {
+ MenuRootProps,
+ MenuItemProps,
+ MenuItemIndicatorProps,
+ MenuItemSubmenuIndicatorProps,
+ MenuSectionProps,
+ DropdownRootProps,
+ DropdownTriggerProps,
+ DropdownPopoverProps,
+ DropdownMenuProps,
+ DropdownSectionProps,
+ DropdownItemProps,
+ DropdownItemIndicatorProps,
+ DropdownSubmenuIndicatorProps,
+ DropdownSubmenuTriggerProps,
+} from "./types-menu";
+
+export { default as Tag } from "./components/tag/Tag.vue";
+export { default as TagGroup } from "./components/tag/TagGroup.vue";
+export { default as TagGroupList } from "./components/tag/TagGroupList.vue";
+export { default as TagRemoveButton } from "./components/tag/TagRemoveButton.vue";
+export type {
+ TagProps,
+ TagGroupProps,
+ TagGroupListProps,
+ TagRemoveButtonProps,
+} from "./types";
+export type {
+ TagKey,
+ TagGroupDataItem,
+ TagRenderState,
+ TagGroupOptions,
+} from "./components/tag/context";
+
+export { default as ErrorMessage } from "./components/error-message/ErrorMessage.vue";
+export type { ErrorMessageProps } from "./types";
+
+export {
+ tagVariants,
+ tagGroupVariants,
+ errorMessageVariants,
+ type TagVariants,
+ type TagGroupVariants,
+ type ErrorMessageVariants,
+} from "@heroui-vue/styles";
+
+export { default as ComboBox } from "./components/combo-box/ComboBox.vue";
+export { default as ComboBoxInputGroup } from "./components/combo-box/ComboBoxInputGroup.vue";
+export { default as ComboBoxTrigger } from "./components/combo-box/ComboBoxTrigger.vue";
+export { default as ComboBoxValue } from "./components/combo-box/ComboBoxValue.vue";
+export { default as ComboBoxPopover } from "./components/combo-box/ComboBoxPopover.vue";
+export type {
+ ComboBoxProps,
+ ComboBoxInputGroupProps,
+ ComboBoxTriggerProps,
+ ComboBoxValueProps,
+ ComboBoxPopoverProps,
+} from "./types";
+export type { CollectionKey } from "./components/collection/keys";
+export type {
+ ComboBoxItem,
+ ComboBoxMenuTrigger,
+ ComboBoxOptions,
+ ComboBoxState,
+ ComboBoxValueState,
+} from "./components/combo-box/context";
+// The model type keeps its own name: aliasing it to `ComboBoxValue*` makes
+// TypeScript resolve the component's value meaning when both are imported.
+import type { ComboBoxValue as ComboBoxModelValue } from "./components/combo-box/context";
+export type { ComboBoxModelValue };
+
+export { comboBoxVariants, type ComboBoxVariants } from "@heroui-vue/styles";
+
+export { default as Autocomplete } from "./components/autocomplete/Autocomplete.vue";
+export { default as AutocompleteTrigger } from "./components/autocomplete/AutocompleteTrigger.vue";
+export { default as AutocompleteValue } from "./components/autocomplete/AutocompleteValue.vue";
+export { default as AutocompleteIndicator } from "./components/autocomplete/AutocompleteIndicator.vue";
+export { default as AutocompleteClearButton } from "./components/autocomplete/AutocompleteClearButton.vue";
+export { default as AutocompletePopover } from "./components/autocomplete/AutocompletePopover.vue";
+export { default as AutocompleteFilter } from "./components/autocomplete/AutocompleteFilter.vue";
+export type {
+ AutocompleteProps,
+ AutocompleteTriggerProps,
+ AutocompleteValueProps,
+ AutocompleteIndicatorProps,
+ AutocompleteClearButtonProps,
+ AutocompletePopoverProps,
+ AutocompleteFilterProps,
+} from "./types";
+export type {
+ AutocompleteItem,
+ AutocompleteState,
+ AutocompleteValueState,
+} from "./components/autocomplete/context";
+export type {
+ AutocompleteSelectedItem,
+ AutocompleteOptions,
+} from "./components/autocomplete/context";
+export type { AutocompleteValue as AutocompleteValueModel } from "./components/autocomplete/context";
+
+export {
+ autocompleteVariants,
+ type AutocompleteVariants,
+} from "@heroui-vue/styles";
diff --git a/packages/vue/src/types-menu.ts b/packages/vue/src/types-menu.ts
new file mode 100644
index 0000000..f218287
--- /dev/null
+++ b/packages/vue/src/types-menu.ts
@@ -0,0 +1,40 @@
+import type Menu from "./components/menu/Menu.vue";
+import type MenuItem from "./components/menu-item/MenuItem.vue";
+import type MenuItemIndicator from "./components/menu-item/MenuItemIndicator.vue";
+import type MenuItemSubmenuIndicator from "./components/menu-item/MenuItemSubmenuIndicator.vue";
+import type MenuSection from "./components/menu-section/MenuSection.vue";
+import type DropdownRoot from "./components/dropdown/DropdownRoot.vue";
+import type DropdownTrigger from "./components/dropdown/DropdownTrigger.vue";
+import type DropdownPopover from "./components/dropdown/DropdownPopover.vue";
+import type DropdownSubmenuTrigger from "./components/dropdown/DropdownSubmenuTrigger.vue";
+
+export type MenuRootProps = InstanceType["$props"];
+export type MenuItemProps = InstanceType["$props"];
+export type MenuItemIndicatorProps = InstanceType<
+ typeof MenuItemIndicator
+>["$props"];
+export type MenuItemSubmenuIndicatorProps = InstanceType<
+ typeof MenuItemSubmenuIndicator
+>["$props"];
+export type MenuSectionProps = InstanceType["$props"];
+export type DropdownRootProps = InstanceType["$props"];
+export type DropdownTriggerProps = InstanceType<
+ typeof DropdownTrigger
+>["$props"];
+export type DropdownPopoverProps = InstanceType<
+ typeof DropdownPopover
+>["$props"];
+/** Dropdown.Menu is the Menu list; same props as MenuRoot. */
+export type DropdownMenuProps = MenuRootProps;
+/** Dropdown.Section is MenuSection. */
+export type DropdownSectionProps = MenuSectionProps;
+/** Dropdown.Item is MenuItem. */
+export type DropdownItemProps = MenuItemProps;
+/** Dropdown.ItemIndicator is MenuItemIndicator. */
+export type DropdownItemIndicatorProps = MenuItemIndicatorProps;
+/** Dropdown.SubmenuIndicator is MenuItemSubmenuIndicator. */
+export type DropdownSubmenuIndicatorProps = MenuItemSubmenuIndicatorProps;
+/** Submenu trigger wrapper: no own props; attrs land on the trigger item. */
+export type DropdownSubmenuTriggerProps = InstanceType<
+ typeof DropdownSubmenuTrigger
+>["$props"];
diff --git a/packages/vue/src/types.ts b/packages/vue/src/types.ts
index 07079a9..7762e42 100644
--- a/packages/vue/src/types.ts
+++ b/packages/vue/src/types.ts
@@ -799,3 +799,73 @@ export type CalendarYearPickerGridBodyProps = InstanceType<
export type CalendarYearPickerCellProps = InstanceType<
typeof CalendarYears.CalendarYearPickerCell
>["$props"];
+
+import type Tag from "./components/tag/Tag.vue";
+export type TagProps = InstanceType["$props"];
+
+import type TagGroup from "./components/tag/TagGroup.vue";
+export type TagGroupProps = InstanceType["$props"];
+
+export type { TagGroupListProps } from "./components/tag/context";
+
+import type TagRemoveButton from "./components/tag/TagRemoveButton.vue";
+export type TagRemoveButtonProps = InstanceType<
+ typeof TagRemoveButton
+>["$props"];
+
+import type ErrorMessage from "./components/error-message/ErrorMessage.vue";
+export type ErrorMessageProps = InstanceType["$props"];
+
+import type ComboBox from "./components/combo-box/ComboBox.vue";
+export type ComboBoxProps = InstanceType["$props"];
+
+import type ComboBoxInputGroup from "./components/combo-box/ComboBoxInputGroup.vue";
+export type ComboBoxInputGroupProps = InstanceType<
+ typeof ComboBoxInputGroup
+>["$props"];
+
+import type ComboBoxTrigger from "./components/combo-box/ComboBoxTrigger.vue";
+export type ComboBoxTriggerProps = InstanceType<
+ typeof ComboBoxTrigger
+>["$props"];
+
+import type ComboBoxValue from "./components/combo-box/ComboBoxValue.vue";
+export type ComboBoxValueProps = InstanceType["$props"];
+
+import type ComboBoxPopover from "./components/combo-box/ComboBoxPopover.vue";
+export type ComboBoxPopoverProps = InstanceType<
+ typeof ComboBoxPopover
+>["$props"];
+
+import type Autocomplete from "./components/autocomplete/Autocomplete.vue";
+export type AutocompleteProps = InstanceType["$props"];
+
+import type AutocompleteTrigger from "./components/autocomplete/AutocompleteTrigger.vue";
+export type AutocompleteTriggerProps = InstanceType<
+ typeof AutocompleteTrigger
+>["$props"];
+
+import type AutocompleteValue from "./components/autocomplete/AutocompleteValue.vue";
+export type AutocompleteValueProps = InstanceType<
+ typeof AutocompleteValue
+>["$props"];
+
+import type AutocompleteIndicator from "./components/autocomplete/AutocompleteIndicator.vue";
+export type AutocompleteIndicatorProps = InstanceType<
+ typeof AutocompleteIndicator
+>["$props"];
+
+import type AutocompleteClearButton from "./components/autocomplete/AutocompleteClearButton.vue";
+export type AutocompleteClearButtonProps = InstanceType<
+ typeof AutocompleteClearButton
+>["$props"];
+
+import type AutocompletePopover from "./components/autocomplete/AutocompletePopover.vue";
+export type AutocompletePopoverProps = InstanceType<
+ typeof AutocompletePopover
+>["$props"];
+
+import type AutocompleteFilter from "./components/autocomplete/AutocompleteFilter.vue";
+export type AutocompleteFilterProps = InstanceType<
+ typeof AutocompleteFilter
+>["$props"];
diff --git a/packages/vue/tests/fixtures/FilterVirtualCombobox.vue b/packages/vue/tests/fixtures/FilterVirtualCombobox.vue
new file mode 100644
index 0000000..d83740f
--- /dev/null
+++ b/packages/vue/tests/fixtures/FilterVirtualCombobox.vue
@@ -0,0 +1,338 @@
+
+
+
+
+
+
+
+ 已选:{{ acceptedText ?? "无" }}
+
+
+ 已隐藏:{{ hiddenCount }}
+
+
+
+
+
+ {{ item.textValue }}
+
+
+
+ 没有匹配项
+
+
+
+
+ {{ option.text }}
+
+
+ 没有匹配项
+
+
+
+
+
diff --git a/tests/autocomplete-demos.test.ts b/tests/autocomplete-demos.test.ts
new file mode 100644
index 0000000..b521784
--- /dev/null
+++ b/tests/autocomplete-demos.test.ts
@@ -0,0 +1,210 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { nextTick, type Component } from "vue";
+import { readFileSync } from "node:fs";
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 6));
+const mounted: { unmount: () => void }[] = [];
+
+const previews = [
+ "default",
+ "variants",
+ "full-width",
+ "with-description",
+ "required",
+ "disabled",
+ "with-disabled-options",
+ "allows-empty-collection",
+ "with-sections",
+ "multiple-select",
+ "controlled",
+ "controlled-multiple",
+ "controlled-open-state",
+ "asynchronous-filtering",
+ "custom-indicator",
+ "custom-value",
+ "on-surface",
+ "virtualization",
+ "user-selection",
+ "user-selection-multiple",
+ "location-search",
+ "tag-group-selection",
+ "email-recipients",
+ "custom-styles",
+];
+
+afterEach(async () => {
+ while (mounted.length) mounted.pop()?.unmount();
+ await nextTick();
+ await settle();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+});
+
+describe("Autocomplete docs and demos", () => {
+ it("keeps the pinned preview order and one demo per preview", () => {
+ const document = readFileSync(
+ "apps/docs/components/autocomplete.md",
+ "utf8",
+ );
+ const names = [
+ ...document.matchAll(/ match[1]);
+
+ expect(names).toEqual(previews);
+ for (const name of previews) {
+ const source = readFileSync(
+ `apps/docs/demos/autocomplete-${name}.vue`,
+ "utf8",
+ );
+ expect(source, name).toContain("");
+ expect(source, name).not.toContain("className");
+ expect(source, name).not.toContain("@gravity-ui/icons");
+ expect(source, name).not.toContain(" {
+ for (const name of previews) {
+ const source = readFileSync(
+ `apps/docs/demos/autocomplete-${name}.vue`,
+ "utf8",
+ );
+ // Upstream renders SearchField autoFocus name="search" variant="secondary"
+ // with a clear button; the popover filter must keep that whole shell.
+ const fields = [...source.matchAll(/]*>/g)];
+ expect(fields.length, name).toBeGreaterThan(0);
+ for (const [tag] of fields) {
+ expect(tag, name).toMatch(/\bvariant="secondary"/);
+ expect(tag, name).toMatch(/\bname="search"/);
+ expect(tag, name).toMatch(/\bauto-focus/);
+ }
+ expect(source, name).toContain("SearchFieldClearButton");
+ // The ported .hv-empty-state padding must not be overridden per demo.
+ expect(source, name).not.toMatch(/ {
+ const document = readFileSync(
+ "apps/docs/components/autocomplete.md",
+ "utf8",
+ );
+ expect(document).not.toMatch(/\|\s*`className`\s*\|/);
+ expect(document).toContain("`class`");
+ expect(document).toContain("Vue class 绑定");
+ for (const part of [
+ "AutocompleteTrigger",
+ "AutocompleteValue",
+ "AutocompleteIndicator",
+ "AutocompleteClearButton",
+ "AutocompletePopover",
+ "AutocompleteFilter",
+ ])
+ expect(document, part).toContain(`### ${part}`);
+ expect(document).not.toContain("[!toc]");
+ // React object-style part names must not appear as API table entries.
+ expect(document).not.toMatch(/\|\s*`Autocomplete\.[A-Z]\w*`\s*\|/);
+ });
+
+ it("mounts every demo with a named trigger", async () => {
+ const modules = import.meta.glob("../apps/docs/demos/autocomplete-*.vue");
+ expect(Object.keys(modules)).toHaveLength(previews.length);
+
+ for (const [path, load] of Object.entries(modules)) {
+ const demo = (await load()) as { default: Component };
+ const wrapper = mount(demo.default, { attachTo: document.body });
+ mounted.push(wrapper);
+ await nextTick();
+ const triggers = (wrapper.element as HTMLElement).querySelectorAll(
+ '[data-slot="autocomplete-trigger"]',
+ );
+ expect(triggers.length, path).toBeGreaterThan(0);
+ for (const element of triggers) {
+ expect(element.getAttribute("role"), path).toBe("button");
+ expect(element.getAttribute("aria-expanded"), path).toBe("false");
+ }
+ wrapper.unmount();
+ mounted.pop();
+ await settle();
+ document.body.innerHTML = "";
+ }
+ });
+
+ it("opens and filters inside representative demos", async () => {
+ for (const name of [
+ "default",
+ "multiple-select",
+ "with-sections",
+ "custom-styles",
+ "virtualization",
+ ]) {
+ const demo = (await import(
+ `../apps/docs/demos/autocomplete-${name}.vue`
+ )) as { default: Component };
+ const wrapper = mount(demo.default, { attachTo: document.body });
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ const trigger = (
+ wrapper.element as HTMLElement
+ ).querySelector('[data-slot="autocomplete-trigger"]')!;
+ trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await settle();
+ const search = document.querySelector(
+ '[data-slot="search-field-input"]',
+ );
+ expect(search, name).not.toBeNull();
+ expect(trigger.getAttribute("aria-expanded"), name).toBe("true");
+ const id = search!.getAttribute("aria-activedescendant");
+ expect(id, name).toBeTruthy();
+ expect(document.getElementById(id!)?.getAttribute("role"), name).toBe(
+ "option",
+ );
+ wrapper.unmount();
+ mounted.pop();
+ await settle();
+ document.body.innerHTML = "";
+ }
+ });
+
+ it("submits the required and name demos", async () => {
+ const formDemo =
+ (await import("../apps/docs/demos/autocomplete-required.vue")) as {
+ default: Component;
+ };
+ const wrapper = mount(formDemo.default, { attachTo: document.body });
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ const root = wrapper.element as HTMLElement;
+ const pickerForm = (
+ root.matches("form") ? root : root.querySelector("form")
+ )!;
+ // Empty required pickers submit no entry; the Form guard blocks the submit.
+ expect(new FormData(pickerForm as HTMLFormElement).has("state")).toBe(
+ false,
+ );
+ expect(new FormData(pickerForm as HTMLFormElement).has("country")).toBe(
+ false,
+ );
+ // `Form` renders novalidate and guards submit itself: an empty required
+ // field must keep the demo's status line empty.
+ const form = pickerForm;
+ const submit = (
+ wrapper.element as HTMLElement
+ ).querySelector('button[type="submit"]')!;
+ submit.click();
+ await nextTick();
+ expect(form.getAttribute("novalidate")).not.toBeNull();
+ expect(
+ (wrapper.element as HTMLElement)
+ .querySelector('[role="status"]')
+ ?.textContent?.trim() ?? "",
+ ).toBe("");
+ wrapper.unmount();
+ mounted.pop();
+ });
+});
diff --git a/tests/autocomplete.test.ts b/tests/autocomplete.test.ts
new file mode 100644
index 0000000..81efc3b
--- /dev/null
+++ b/tests/autocomplete.test.ts
@@ -0,0 +1,900 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { readFileSync } from "node:fs";
+import { defineComponent, h, nextTick, ref, type Component } from "vue";
+import {
+ Autocomplete,
+ AutocompleteClearButton,
+ AutocompleteFilter,
+ AutocompleteIndicator,
+ AutocompletePopover,
+ AutocompleteTrigger,
+ AutocompleteValue,
+ Form,
+ Label,
+ ListBox,
+ ListBoxItem,
+ SearchField,
+ SearchFieldGroup,
+ SearchFieldInput,
+ SearchFieldSearchIcon,
+} from "../packages/vue/src";
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 4));
+const mounted: { unmount: () => void }[] = [];
+
+type State = { id: string | number; name: string; disabled?: boolean };
+const states: State[] = [
+ { id: "california", name: "California" },
+ { id: "texas", name: "Texas" },
+ { id: "florida", name: "Florida" },
+];
+
+function shell(
+ props: Record,
+ options: { states?: State[]; empty?: boolean; description?: boolean } = {},
+ emits: Record = {},
+) {
+ const items = options.states ?? states;
+ return mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ Autocomplete,
+ {
+ "aria-label": "州",
+ placeholder: "选择州/省",
+ ...emits,
+ ...props,
+ },
+ {
+ default: () => [
+ h(Label, () => "州"),
+ h(AutocompleteTrigger, null, {
+ default: () => [
+ h(AutocompleteValue),
+ h(AutocompleteClearButton),
+ h(AutocompleteIndicator),
+ ],
+ }),
+ h(AutocompletePopover, null, {
+ default: () =>
+ h(AutocompleteFilter, null, {
+ default: () => [
+ h(
+ SearchField,
+ { "aria-label": "搜索州名" },
+ {
+ default: () =>
+ h(SearchFieldGroup, null, {
+ default: () => [
+ h(SearchFieldSearchIcon),
+ h(SearchFieldInput, {
+ placeholder: "搜索州名…",
+ }),
+ ],
+ }),
+ },
+ ),
+ h(ListBox, null, {
+ default: () =>
+ items.map((state) =>
+ h(
+ ListBoxItem,
+ {
+ id: state.id,
+ key: state.id,
+ textValue: state.name,
+ isDisabled: state.disabled,
+ },
+ () => state.name,
+ ),
+ ),
+ empty: () =>
+ h("p", { "data-test": "empty" }, "未找到结果"),
+ }),
+ ],
+ }),
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+}
+
+function track(wrapper: { unmount: () => void }) {
+ mounted.push(wrapper);
+ return wrapper;
+}
+
+const trigger = () =>
+ document.querySelector('[data-slot="autocomplete-trigger"]')!;
+const search = () =>
+ document.querySelector('[data-slot="search-field-input"]')!;
+const valueText = () =>
+ document
+ .querySelector('[data-slot="autocomplete-value"]')
+ ?.textContent?.trim();
+const rowTexts = () =>
+ [...document.querySelectorAll('[role="option"]')]
+ .filter((row) => !row.hasAttribute("data-filtered"))
+ .map((row) => row.textContent?.trim());
+
+async function open(wrapper?: { unmount: () => void }) {
+ void wrapper;
+ trigger().dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await settle();
+}
+async function press(key: string, init: KeyboardEventInit = {}) {
+ search().dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key,
+ bubbles: true,
+ cancelable: true,
+ ...init,
+ }),
+ );
+ await nextTick();
+ await settle();
+}
+async function type(text: string) {
+ const element = search();
+ element.value = text;
+ element.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ await settle();
+}
+
+afterEach(async () => {
+ while (mounted.length) mounted.pop()?.unmount();
+ await nextTick();
+ await settle();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+});
+
+describe("Autocomplete trigger", () => {
+ it("is the single tab entry with placeholder and value semantics", async () => {
+ track(shell({}));
+ await nextTick();
+ await settle();
+ const element = trigger();
+
+ expect(element.getAttribute("role")).toBe("button");
+ expect(element.getAttribute("tabindex")).toBe("0");
+ expect(element.getAttribute("aria-haspopup")).toBe("listbox");
+ expect(element.getAttribute("aria-expanded")).toBe("false");
+ expect(valueText()).toBe("选择州/省");
+ expect(
+ document
+ .querySelector('[data-slot="autocomplete-clear-button"]')!
+ .getAttribute("tabindex"),
+ ).toBe("-1");
+ });
+
+ it("opens on click, focuses the search box and filters from there", async () => {
+ track(shell({}));
+ await nextTick();
+ await settle();
+ await open();
+
+ expect(trigger().getAttribute("aria-expanded")).toBe("true");
+ expect(document.activeElement).toBe(search());
+ expect(search().getAttribute("role")).toBe("combobox");
+ const id = search().getAttribute("aria-activedescendant");
+ expect(document.getElementById(id!)?.getAttribute("role")).toBe("option");
+
+ await type("Te");
+ expect(rowTexts()).toEqual(["Texas"]);
+ expect(document.activeElement).toBe(search());
+ const active = search().getAttribute("aria-activedescendant");
+ expect(document.getElementById(active!)?.textContent?.trim()).toBe("Texas");
+ });
+
+ it("selects with Enter, closes and restores focus to the trigger", async () => {
+ const onChange = vi.fn();
+ track(shell({}, {}, { onChange }));
+ await nextTick();
+ await settle();
+ await open();
+ await type("Te");
+ await press("Enter");
+
+ expect(onChange).toHaveBeenLastCalledWith("texas");
+ expect(trigger().getAttribute("aria-expanded")).toBe("false");
+ expect(valueText()).toBe("Texas");
+ expect(document.activeElement).toBe(trigger());
+ });
+
+ it("closes on Escape and on Tab without selecting", async () => {
+ const onChange = vi.fn();
+ track(shell({}, {}, { onChange }));
+ await nextTick();
+ await settle();
+ await open();
+ await press("Escape");
+ expect(trigger().getAttribute("aria-expanded")).toBe("false");
+ expect(document.activeElement).toBe(trigger());
+
+ await open();
+ await press("Tab");
+ expect(trigger().getAttribute("aria-expanded")).toBe("false");
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("does not confirm while an IME composition is active", async () => {
+ const onChange = vi.fn();
+ track(shell({}, {}, { onChange }));
+ await nextTick();
+ await settle();
+ await open();
+ await press("Enter", { isComposing: true });
+ await press("Enter", { keyCode: 229 });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("clears the selection from the clear button", async () => {
+ const onChange = vi.fn();
+ const clear = vi.fn();
+ track(shell({ defaultValue: "texas" }, {}, { onChange, onClear: clear }));
+ await nextTick();
+ await settle();
+ expect(valueText()).toBe("Texas");
+
+ document
+ .querySelector('[data-slot="autocomplete-clear-button"]')!
+ .dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await settle();
+
+ expect(onChange).toHaveBeenLastCalledWith(null);
+ expect(clear).toHaveBeenCalledTimes(1);
+ expect(valueText()).toBe("选择州/省");
+ expect(trigger().getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("stays closed and non-tabbable while disabled", async () => {
+ track(shell({ isDisabled: true }));
+ await nextTick();
+ await settle();
+ expect(trigger().getAttribute("tabindex")).toBe("-1");
+ expect(trigger().getAttribute("aria-disabled")).toBe("true");
+ await open();
+ expect(trigger().getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("skips disabled keys while navigating", async () => {
+ const onChange = vi.fn();
+ track(
+ shell(
+ {},
+ {
+ states: [
+ { id: "california", name: "California", disabled: true },
+ { id: "texas", name: "Texas" },
+ ],
+ },
+ { onChange },
+ ),
+ );
+ await nextTick();
+ await settle();
+ await open();
+ await press("Enter");
+ expect(onChange).toHaveBeenLastCalledWith("texas");
+ });
+});
+
+describe("Autocomplete state", () => {
+ it("shows the empty channel when nothing matches", async () => {
+ track(shell({}));
+ await nextTick();
+ await settle();
+ await open();
+ await type("zzz");
+ expect(rowTexts()).toEqual([]);
+ expect(document.querySelector('[data-test="empty"]')).not.toBeNull();
+ });
+
+ it("opens an empty collection only when allowed", async () => {
+ track(shell({ allowsEmptyCollection: true }, { states: [] }));
+ await nextTick();
+ await settle();
+ await open();
+ expect(trigger().getAttribute("aria-expanded")).toBe("true");
+ expect(document.querySelector('[data-test="empty"]')).not.toBeNull();
+ });
+
+ it("follows a controlled open state", async () => {
+ const openState = ref(false);
+ const onOpenChange = vi.fn((value: boolean) => (openState.value = value));
+ track(
+ mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ Autocomplete,
+ {
+ "aria-label": "州",
+ isOpen: openState.value,
+ onOpenChange,
+ },
+ {
+ default: () => [
+ h(AutocompleteTrigger, null, {
+ default: () => [h(AutocompleteValue)],
+ }),
+ h(AutocompletePopover, null, {
+ default: () =>
+ h(AutocompleteFilter, null, {
+ default: () => [
+ h(
+ SearchField,
+ { "aria-label": "搜索" },
+ {
+ default: () =>
+ h(SearchFieldGroup, null, {
+ default: () => [h(SearchFieldInput)],
+ }),
+ },
+ ),
+ h(ListBox, null, {
+ default: () =>
+ states.map((state) =>
+ h(
+ ListBoxItem,
+ {
+ id: state.id,
+ key: state.id,
+ textValue: state.name,
+ },
+ () => state.name,
+ ),
+ ),
+ }),
+ ],
+ }),
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ ) as never,
+ );
+ await nextTick();
+ await settle();
+ await open();
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ // The parent accepted the proposal, so the controlled state is open.
+ expect(trigger().getAttribute("aria-expanded")).toBe("true");
+
+ openState.value = false;
+ await nextTick();
+ await settle();
+ expect(trigger().getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("keeps the value when the parent rejects the proposal", async () => {
+ const onChange = vi.fn();
+ track(shell({ value: null }, {}, { onChange }));
+ await nextTick();
+ await settle();
+ await open();
+ await press("Enter");
+ expect(onChange).toHaveBeenCalledWith("california");
+ expect(valueText()).toBe("选择州/省");
+ });
+
+ it("accumulates multiple selections and renders tags", async () => {
+ const selected = ref<(string | number)[]>([]);
+ track(
+ mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ Autocomplete,
+ {
+ "aria-label": "州",
+ selectionMode: "multiple",
+ modelValue: selected.value,
+ "onUpdate:modelValue": (value: unknown) => {
+ selected.value = (value ?? []) as (string | number)[];
+ },
+ },
+ {
+ default: () => [
+ h(AutocompleteTrigger, null, {
+ default: () => [h(AutocompleteValue)],
+ }),
+ h(AutocompletePopover, null, {
+ default: () =>
+ h(AutocompleteFilter, null, {
+ default: () => [
+ h(
+ SearchField,
+ { "aria-label": "搜索" },
+ {
+ default: () =>
+ h(SearchFieldGroup, null, {
+ default: () => [h(SearchFieldInput)],
+ }),
+ },
+ ),
+ h(
+ ListBox,
+ { selectionMode: "multiple" },
+ {
+ default: () =>
+ states.map((state) =>
+ h(
+ ListBoxItem,
+ {
+ id: state.id,
+ key: state.id,
+ textValue: state.name,
+ },
+ () => state.name,
+ ),
+ ),
+ },
+ ),
+ ],
+ }),
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ ) as never,
+ );
+ await nextTick();
+ await settle();
+ await open();
+ await press("Enter");
+ await press("ArrowDown");
+ await press("Enter");
+ expect(selected.value).toEqual(["california", "texas"]);
+ // Multi-select keeps the popover open for further picks.
+ expect(trigger().getAttribute("aria-expanded")).toBe("true");
+ expect(
+ [
+ ...document.querySelectorAll('[role="option"][aria-selected="true"]'),
+ ].map((row) => row.textContent?.trim()),
+ ).toEqual(["California", "Texas"]);
+ });
+});
+
+describe("Autocomplete form and validation", () => {
+ it("submits the selected key through a hidden input", async () => {
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ const submitted = ref("");
+ return () =>
+ h(
+ Form,
+ {
+ onSubmit: (event: Event) => {
+ event.preventDefault();
+ const data = new FormData(
+ event.currentTarget as HTMLFormElement,
+ );
+ submitted.value = String(data.get("state"));
+ },
+ },
+ {
+ default: () => [
+ h(
+ Autocomplete,
+ {
+ "aria-label": "州",
+ name: "state",
+ defaultValue: "texas",
+ },
+ {
+ default: () => [
+ h(AutocompleteTrigger, null, {
+ default: () => [h(AutocompleteValue)],
+ }),
+ h(AutocompletePopover, null, {
+ default: () =>
+ h(AutocompleteFilter, null, {
+ default: () => [
+ h(
+ SearchField,
+ { "aria-label": "搜索" },
+ {
+ default: () =>
+ h(SearchFieldGroup, null, {
+ default: () => [h(SearchFieldInput)],
+ }),
+ },
+ ),
+ h(ListBox, null, {
+ default: () =>
+ states.map((state) =>
+ h(
+ ListBoxItem,
+ {
+ id: state.id,
+ key: state.id,
+ textValue: state.name,
+ },
+ () => state.name,
+ ),
+ ),
+ }),
+ ],
+ }),
+ }),
+ ],
+ },
+ ),
+ h(
+ "button",
+ { type: "submit", "data-test": "submit" },
+ "提交",
+ ),
+ h("p", { "data-test": "result" }, submitted.value),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper as never);
+ await nextTick();
+ await settle();
+ (
+ document.querySelector('[data-test="submit"]') as HTMLButtonElement
+ ).click();
+ await nextTick();
+ expect(document.querySelector('[data-test="result"]')!.textContent).toBe(
+ "texas",
+ );
+ });
+
+ it("blocks native submit when required and empty", async () => {
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ Form,
+ { onSubmit: (event: Event) => event.preventDefault() },
+ {
+ default: () => [
+ h(
+ Autocomplete,
+ {
+ "aria-label": "州",
+ name: "state",
+ isRequired: true,
+ },
+ {
+ default: () => [
+ h(Label, () => "州"),
+ h(AutocompleteTrigger, null, {
+ default: () => [h(AutocompleteValue)],
+ }),
+ h(AutocompletePopover, null, {
+ default: () =>
+ h(AutocompleteFilter, null, {
+ default: () => [
+ h(
+ SearchField,
+ { "aria-label": "搜索" },
+ {
+ default: () =>
+ h(SearchFieldGroup, null, {
+ default: () => [h(SearchFieldInput)],
+ }),
+ },
+ ),
+ h(ListBox, null, {
+ default: () =>
+ states.map((state) =>
+ h(
+ ListBoxItem,
+ {
+ id: state.id,
+ key: state.id,
+ textValue: state.name,
+ },
+ () => state.name,
+ ),
+ ),
+ }),
+ ],
+ }),
+ }),
+ ],
+ },
+ ),
+ h(
+ "button",
+ { type: "submit", "data-test": "submit" },
+ "提交",
+ ),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper as never);
+ await nextTick();
+ await settle();
+ const form = document.querySelector("form")!;
+ expect(form.checkValidity()).toBe(false);
+ });
+});
+
+describe("Autocomplete composition", () => {
+ it("keeps a caller-provided aria-label on the trigger and search box", async () => {
+ track(shell({}));
+ await nextTick();
+ await settle();
+ expect(trigger().getAttribute("aria-label")).toBe("州");
+ await open();
+ expect(search().getAttribute("aria-label")).toBe("州");
+ });
+
+ it("mounts as a reusable component surface", async () => {
+ const surface: Component = (
+ await import("../apps/docs/demos/autocomplete-multiple-select.vue")
+ ).default;
+ const wrapper = mount(surface, { attachTo: document.body });
+ track(wrapper as never);
+ await nextTick();
+ await settle();
+ expect(trigger().getAttribute("aria-expanded")).toBe("false");
+ expect(valueText()).toBe("选择州/省");
+ });
+});
+
+describe("Autocomplete ported style hooks", () => {
+ it("emits the data-slot values the ported CSS targets", async () => {
+ const css = readFileSync(
+ "packages/styles/components/autocomplete.css",
+ "utf8",
+ );
+
+ // Only class names carry the hv- prefix: data-slot values are a DOM
+ // contract, so a prefixed value would leave the ported rules dead.
+ expect(css).not.toMatch(/data-slot="hv-/);
+ expect(css).toContain('&[data-slot="autocomplete-default-indicator"]');
+ expect(css).toContain('[data-slot="autocomplete-clear-button-icon"]');
+
+ track(shell({ defaultValue: "texas" }));
+ await nextTick();
+ await settle();
+
+ // The class, the `data-slot` and `data-open` must share one element, or the
+ // ported `.hv-autocomplete__indicator[...]` rules never match.
+ expect(
+ document.querySelector(
+ '.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
+ ),
+ ).not.toBeNull();
+ expect(
+ document.querySelector('[data-slot="autocomplete-clear-button-icon"]'),
+ ).not.toBeNull();
+ });
+});
+
+describe("Autocomplete filter protocol", () => {
+ it("inherits an accent-insensitive base matcher", async () => {
+ track(
+ shell(
+ {},
+ { states: [{ id: "cafe", name: "Café" }] as unknown as State[] },
+ ),
+ );
+ await nextTick();
+ await open();
+ await type("cafe");
+ expect(rowTexts()).toEqual(["Café"]);
+ await type("CAFÉ");
+ expect(rowTexts()).toEqual(["Café"]);
+ await type("cafe\u0301");
+ expect(rowTexts()).toEqual(["Café"]);
+ });
+
+ it("filters only after an open composition session ends", async () => {
+ track(shell({}));
+ await nextTick();
+ await open();
+ expect(rowTexts()).toHaveLength(3);
+
+ search().dispatchEvent(new CompositionEvent("compositionstart"));
+ await nextTick();
+ await type("Texas");
+ expect(rowTexts()).toHaveLength(3);
+
+ search().dispatchEvent(new CompositionEvent("compositionend"));
+ await nextTick();
+ await settle();
+ expect(rowTexts()).toEqual(["Texas"]);
+ });
+});
+
+describe("Autocomplete native layer", () => {
+ it("keeps the caller's cancel on the clear button", async () => {
+ const change = vi.fn();
+ const wrapper = mount(
+ defineComponent({
+ setup: () => () =>
+ h(
+ Autocomplete,
+ { defaultValue: "a", onChange: change },
+ {
+ default: () => [
+ h(AutocompleteTrigger, null, {
+ default: () => [
+ h(AutocompleteValue),
+ h(AutocompleteClearButton, {
+ onClick: (event: MouseEvent) => event.preventDefault(),
+ }),
+ ],
+ }),
+ h(AutocompletePopover, null, {
+ default: () =>
+ h(AutocompleteFilter, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ states.map((state) =>
+ h(
+ ListBoxItem,
+ {
+ id: state.id,
+ key: state.id,
+ textValue: state.name,
+ },
+ () => state.name,
+ ),
+ ),
+ }),
+ }),
+ }),
+ ],
+ },
+ ),
+ }),
+ { attachTo: document.body },
+ );
+ track(wrapper as never);
+ await nextTick();
+ await settle();
+ document
+ .querySelector(
+ '[data-slot="autocomplete-clear-button"]',
+ )!
+ .click();
+ await settle();
+ expect(change).not.toHaveBeenCalled();
+ });
+
+ it("submits one entry per key and none for a disabled field", async () => {
+ const multi = mount(
+ defineComponent({
+ setup: () => () =>
+ h("form", null, [
+ h(Autocomplete, {
+ name: "choice",
+ selectionMode: "multiple",
+ defaultValue: ["california", "texas"],
+ }),
+ ]),
+ }),
+ { attachTo: document.body },
+ );
+ track(multi as never);
+ await nextTick();
+ await settle();
+ const form = multi.element as HTMLFormElement;
+ expect(new FormData(form).getAll("choice")).toEqual([
+ "california",
+ "texas",
+ ]);
+ multi.unmount();
+ mounted.pop();
+
+ const disabled = mount(
+ defineComponent({
+ setup: () => () =>
+ h("form", null, [
+ h(Autocomplete, {
+ name: "choice",
+ defaultValue: "california",
+ isDisabled: true,
+ }),
+ ]),
+ }),
+ { attachTo: document.body },
+ );
+ track(disabled as never);
+ await nextTick();
+ await settle();
+ expect(
+ new FormData(disabled.element as HTMLFormElement).has("choice"),
+ ).toBe(false);
+ });
+
+ it("maps the source items prop onto the closed-state text", async () => {
+ track(
+ shell({
+ items: [
+ { id: "california", textValue: "California" },
+ { id: "texas", textValue: "Texas" },
+ ],
+ defaultValue: "texas",
+ }),
+ );
+ await nextTick();
+ await settle();
+ expect(valueText()).toBe("Texas");
+ });
+
+ it("tags a custom indicator with the baseline slot contract", async () => {
+ track(
+ mount(
+ defineComponent({
+ setup: () => () =>
+ h(Autocomplete, null, {
+ default: () => [
+ h(AutocompleteTrigger, null, {
+ default: () => [
+ h(AutocompleteValue),
+ h(AutocompleteIndicator, null, {
+ default: () => h("i", { "data-test": "icon" }),
+ }),
+ ],
+ }),
+ h(AutocompletePopover, null, {
+ default: () =>
+ h(AutocompleteFilter, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ states.map((state) =>
+ h(
+ ListBoxItem,
+ {
+ id: state.id,
+ key: state.id,
+ textValue: state.name,
+ },
+ () => state.name,
+ ),
+ ),
+ }),
+ }),
+ }),
+ ],
+ }),
+ }),
+ { attachTo: document.body },
+ ),
+ );
+ await nextTick();
+ await settle();
+ const custom = document.querySelector('[data-test="icon"]')!;
+ expect(custom.getAttribute("data-slot")).toBe("autocomplete-indicator");
+ expect(custom.classList.contains("hv-autocomplete__indicator")).toBe(true);
+ });
+});
diff --git a/tests/b01-complete-review.probe.test.ts b/tests/b01-complete-review.probe.test.ts
new file mode 100644
index 0000000..b1f970a
--- /dev/null
+++ b/tests/b01-complete-review.probe.test.ts
@@ -0,0 +1,389 @@
+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);
+});
+
+it("default action activation closes its dropdown", async () => {
+ await render({}, () => h(DropdownItem, { id: "default" }, () => "Action"));
+ (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
+ await flushPromises();
+ expect(document.querySelector('[role="menu"]')).toBeNull();
+});
+it.each([
+ ["single", false, true],
+ ["multiple", true, false],
+] as const)(
+ "menu-level close policy for %s is honoured",
+ async (selectionMode, shouldCloseOnSelect, staysOpen) => {
+ await render({ selectionMode, shouldCloseOnSelect }, () =>
+ h(DropdownItem, { id: "policy" }, () => "Policy"),
+ );
+ (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
+ await flushPromises();
+ expect(!!document.querySelector('[role="menu"]')).toBe(staysOpen);
+ },
+);
+it("root popover preserves a user keydown callback", async () => {
+ const callback = vi.fn();
+ const w = mount(
+ defineComponent({
+ setup: () => () =>
+ h(DropdownRoot, { defaultOpen: true, modal: false }, () =>
+ h(DropdownPopover, { onKeydown: callback }, () =>
+ h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
+ ),
+ ),
+ }),
+ { attachTo: document.body },
+ );
+ cleanup.push(() => w.unmount());
+ await flushPromises();
+ document.querySelector('[role="menu"]')!.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "a",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await flushPromises();
+ expect(callback).toHaveBeenCalledTimes(1);
+});
+async function openConfiguredSubmenu(props: Record) {
+ await render({}, () =>
+ h(DropdownSubmenuTrigger, {}, () => [
+ h(DropdownItem, { id: "sub" }, () => [
+ "Sub",
+ h(DropdownSubmenuIndicator),
+ ]),
+ h(DropdownPopover, props, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "inner" }, () => "Inner"),
+ ),
+ ),
+ ]),
+ );
+ (document.querySelector('[data-key="sub"]') as HTMLElement).click();
+ await flushPromises();
+ return document.querySelector("[data-submenu-content]") as HTMLElement;
+}
+it("submenu preserves the panel's data and style attributes", async () => {
+ const panel = await openConfiguredSubmenu({
+ "data-custom": "kept",
+ style: { borderTopWidth: "7px" },
+ });
+ expect(panel.getAttribute("data-custom")).toBe("kept");
+ expect(panel.style.borderTopWidth).toBe("7px");
+});
+it("submenu honours isKeyboardDismissDisabled", async () => {
+ const panel = await openConfiguredSubmenu({
+ isKeyboardDismissDisabled: true,
+ });
+ const item = panel.querySelector('[data-slot="menu-item"]') as HTMLElement;
+ item.focus();
+ item.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await flushPromises();
+ expect(document.querySelector("[data-submenu-content]")).not.toBeNull();
+});
+it("standalone Menu keeps its own accessible name", async () => {
+ const w = mount(Menu, {
+ attrs: { "aria-label": "Standalone actions" },
+ slots: { default: () => h(DropdownItem, { id: "a" }, () => "A") },
+ attachTo: document.body,
+ });
+ cleanup.push(() => w.unmount());
+ await flushPromises();
+ expect(
+ document.querySelector('[role="menu"]')?.getAttribute("aria-label"),
+ ).toBe("Standalone actions");
+});
+
+it("submenu keeps a directly supplied panel accessible name", async () => {
+ const panel = await openConfiguredSubmenu({
+ "aria-label": "Direct submenu name",
+ "aria-describedby": "explicit-description",
+ });
+ expect(panel.getAttribute("aria-label")).toBe("Direct submenu name");
+ expect(panel.getAttribute("aria-describedby")).toBe("explicit-description");
+});
+it("submenu preserves a caller's openAutoFocus callback", async () => {
+ const callback = vi.fn();
+ await openConfiguredSubmenu({ onOpenAutoFocus: callback });
+ expect(callback).toHaveBeenCalledTimes(1);
+});
+it("submenu respects the menu's shouldFocusWrap navigation", async () => {
+ await render({}, () =>
+ h(DropdownSubmenuTrigger, {}, () => [
+ h(DropdownItem, { id: "sub" }, () => [
+ "Sub",
+ h(DropdownSubmenuIndicator),
+ ]),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, { shouldFocusWrap: true }, () => [
+ h(DropdownItem, { id: "first", textValue: "First" }, () => "First"),
+ h(DropdownItem, { id: "last", textValue: "Last" }, () => "Last"),
+ ]),
+ ),
+ ]),
+ );
+ (document.querySelector('[data-key="sub"]') as HTMLElement).click();
+ await flushPromises();
+ const panel = document.querySelector("[data-submenu-content]")!;
+ const first = panel.querySelector('[data-key="first"]') as HTMLElement;
+ const last = panel.querySelector('[data-key="last"]') as HTMLElement;
+ first.focus();
+ await flushPromises();
+ first.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "ArrowUp",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await flushPromises();
+ expect(document.activeElement).toBe(last);
+});
diff --git a/tests/b01-menu-dropdown.test.ts b/tests/b01-menu-dropdown.test.ts
new file mode 100644
index 0000000..a323487
--- /dev/null
+++ b/tests/b01-menu-dropdown.test.ts
@@ -0,0 +1,1318 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { mount, flushPromises } from "@vue/test-utils";
+import { defineComponent, h, ref, nextTick } from "vue";
+import {
+ Button,
+ DropdownRoot,
+ DropdownTrigger,
+ DropdownPopover,
+ DropdownMenu,
+ DropdownItem,
+ DropdownItemIndicator,
+ DropdownSection,
+ DropdownSubmenuTrigger,
+ DropdownSubmenuIndicator,
+ Avatar,
+ AvatarFallback,
+ Header,
+ Label,
+ Menu,
+ MenuItem,
+ MenuSection,
+} from "../packages/vue/src";
+import type { MenuKey } from "../packages/vue/src";
+
+const cleanup: (() => void)[] = [];
+afterEach(() => {
+ cleanup
+ .splice(0)
+ .reverse()
+ .forEach((fn) => fn());
+ vi.useRealTimers();
+ document.body.innerHTML = "";
+});
+
+function mountApp(setup: () => unknown, render?: () => unknown) {
+ const w = mount(
+ defineComponent(
+ render
+ ? { setup: setup as never, render: render as never }
+ : { setup: setup as never },
+ ),
+ { attachTo: document.body },
+ );
+ cleanup.push(() => w.unmount());
+ return w;
+}
+
+it("Dropdown opens and action item fires once", async () => {
+ const actions: MenuKey[] = [];
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(Button, () => "操作"),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () => [
+ h(DropdownItem, { id: "new-file", textValue: "新建文件" }, () =>
+ h(Label, () => "新建文件"),
+ ),
+ h(
+ DropdownItem,
+ { id: "delete-file", textValue: "删除文件", variant: "danger" },
+ () => h(Label, () => "删除文件"),
+ ),
+ ]),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const items = document.querySelectorAll('[data-slot="menu-item"]');
+ expect(items.length).toBe(2);
+ expect((items[1] as HTMLElement).className).toContain("hv-menu-item--danger");
+ expect((items[0] as HTMLElement).getAttribute("role")).toBe("menuitem");
+
+ (items[0] as HTMLElement).click();
+ await flushPromises();
+ expect(actions).toEqual(["new-file"]);
+});
+
+it("Menu multiple selection toggles keys", async () => {
+ const selected = ref(["apple"]);
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(Button, () => "水果"),
+ h(DropdownPopover, {}, () =>
+ h(
+ DropdownMenu,
+ {
+ selectionMode: "multiple",
+ selectedKeys: selected.value,
+ "onUpdate:selectedKeys": (k: (string | number)[]) => {
+ selected.value = k as string[];
+ },
+ },
+ () => [
+ h(DropdownItem, { id: "apple", textValue: "苹果" }, () => [
+ h(DropdownItemIndicator),
+ h(Label, () => "苹果"),
+ ]),
+ h(DropdownItem, { id: "banana", textValue: "香蕉" }, () => [
+ h(DropdownItemIndicator),
+ h(Label, () => "香蕉"),
+ ]),
+ ],
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const items = document.querySelectorAll('[data-slot="menu-item"]');
+ expect(items.length).toBe(2);
+ (items[1] as HTMLElement).click();
+ await flushPromises();
+ await nextTick();
+ expect(selected.value).toContain("banana");
+ expect(selected.value).toContain("apple");
+});
+
+it("MenuSection can own section-level selection", async () => {
+ const styles = ref(["bold"]);
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(Button, () => "样式"),
+ h(DropdownPopover, {}, () =>
+ h(Menu, {}, () =>
+ h(
+ MenuSection,
+ {
+ selectionMode: "multiple",
+ selectedKeys: styles.value,
+ "onUpdate:selectedKeys": (k: (string | number)[]) => {
+ styles.value = k as string[];
+ },
+ },
+ () => [
+ h(MenuItem, { id: "bold", textValue: "粗体" }, () =>
+ h(Label, () => "粗体"),
+ ),
+ h(MenuItem, { id: "italic", textValue: "斜体" }, () =>
+ h(Label, () => "斜体"),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const items = document.querySelectorAll('[data-slot="menu-item"]');
+ expect(items.length).toBe(2);
+ (items[1] as HTMLElement).click();
+ await flushPromises();
+ await nextTick();
+ expect(styles.value).toEqual(expect.arrayContaining(["bold", "italic"]));
+});
+
+it("disabled item is marked disabled", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(Button, () => "操作"),
+ h(DropdownPopover, {}, () =>
+ h(Menu, { disabledKeys: ["x"] }, () =>
+ h(MenuItem, { id: "x", textValue: "X" }, () => h(Label, () => "X")),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement;
+ expect(item).toBeTruthy();
+ const disabled =
+ item.hasAttribute("disabled") ||
+ item.getAttribute("aria-disabled") === "true" ||
+ item.getAttribute("data-disabled") === "true" ||
+ (item as HTMLInputElement).disabled === true;
+ expect(disabled).toBe(true);
+});
+
+it("indicator uses checkmark svg and data-visible when selected", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(Button, () => "水果"),
+ h(DropdownPopover, {}, () =>
+ h(
+ DropdownMenu,
+ { selectionMode: "multiple", selectedKeys: ["apple"] },
+ () => [
+ h(DropdownItem, { id: "apple", textValue: "苹果" }, () => [
+ h(DropdownItemIndicator),
+ h(Label, () => "苹果"),
+ ]),
+ ],
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const ind = document.querySelector('[data-slot="menu-item-indicator"]');
+ expect(ind).toBeTruthy();
+ expect(ind!.getAttribute("data-type")).toBe("checkmark");
+ expect(
+ ind!.querySelector('[data-slot="menu-item-indicator--checkmark"]'),
+ ).not.toBeNull();
+});
+
+it("submenu trigger opens nested items", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(Button, () => "分享"),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () => [
+ h(DropdownItem, { id: "copy-link", textValue: "复制链接" }, () =>
+ h(Label, () => "复制链接"),
+ ),
+ h(DropdownSubmenuTrigger, {}, () => [
+ h(DropdownItem, { id: "share", textValue: "分享" }, () => [
+ h(Label, () => "其他"),
+ h(DropdownSubmenuIndicator),
+ ]),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(
+ DropdownItem,
+ { id: "whatsapp", textValue: "WhatsApp" },
+ () => h(Label, () => "WhatsApp"),
+ ),
+ ),
+ ),
+ ]),
+ ]),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const triggers = document.querySelectorAll(
+ '[data-slot="menu-item"][data-has-submenu="true"], [data-slot="dropdown-submenu-trigger"]',
+ );
+ expect(triggers.length).toBeGreaterThanOrEqual(1);
+ // Open submenu via pointer (Reka SubTrigger)
+ (triggers[0] as HTMLElement).dispatchEvent(
+ new MouseEvent("pointerenter", { bubbles: true }),
+ );
+ (triggers[0] as HTMLElement).click();
+ await flushPromises();
+ await nextTick();
+ const html = document.body.innerHTML;
+ expect(html).toContain("WhatsApp");
+ expect(html).toContain("其他");
+});
+
+it("long-press trigger opens on hold and suppresses click", async () => {
+ vi.useFakeTimers();
+ const w = mountApp(
+ () => () =>
+ h(DropdownRoot, { trigger: "longPress", longPressDuration: 300 }, () => [
+ h(DropdownTrigger, {}, () =>
+ h(Button, { "aria-label": "菜单" }, () => "长按"),
+ ),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "x", textValue: "X" }, () =>
+ h(Label, () => "X"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ const btn = w.get("button");
+ btn.trigger("pointerdown", { button: 0, clientX: 10, clientY: 10 });
+ await vi.advanceTimersByTimeAsync(350);
+ await nextTick();
+ expect(
+ document
+ .querySelector('[data-slot="dropdown-popover"]')
+ ?.getAttribute("data-state"),
+ ).toBe("open");
+ vi.useRealTimers();
+});
+
+it("long-press cancel on move threshold", async () => {
+ vi.useFakeTimers();
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { trigger: "longPress", longPressDuration: 300 }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "长按")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "x", textValue: "X" }, () =>
+ h(Label, () => "X"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ const btn = document.querySelector("button") as HTMLElement;
+ btn.dispatchEvent(
+ new MouseEvent("pointerdown", {
+ bubbles: true,
+ button: 0,
+ clientX: 0,
+ clientY: 0,
+ }),
+ );
+ btn.dispatchEvent(
+ new MouseEvent("pointermove", { bubbles: true, clientX: 40, clientY: 0 }),
+ );
+ await vi.advanceTimersByTimeAsync(400);
+ await nextTick();
+ expect(
+ document
+ .querySelector('[data-slot="dropdown-popover"]')
+ ?.getAttribute("data-state"),
+ ).not.toBe("open");
+ vi.useRealTimers();
+});
+
+function pointer(
+ type: string,
+ props: Record = {},
+): MouseEvent {
+ const event = new MouseEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ ...(props as MouseEventInit),
+ });
+ for (const key of ["pointerType", "isPrimary"]) {
+ if (key in props) {
+ Object.defineProperty(event, key, { value: props[key] });
+ }
+ }
+ return event;
+}
+
+function mountLongPress(duration = 300) {
+ const actions: MenuKey[] = [];
+ const w = mountApp(
+ () => () =>
+ h(
+ DropdownRoot,
+ { trigger: "longPress", longPressDuration: duration },
+ () => [
+ h(DropdownTrigger, {}, () =>
+ h(Button, { "aria-label": "菜单" }, () => "长按"),
+ ),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () =>
+ h(DropdownItem, { id: "x", textValue: "X" }, () =>
+ h(Label, () => "X"),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ return { w, actions, button: () => w.get("button").element as HTMLElement };
+}
+
+function menuState() {
+ return (
+ document
+ .querySelector('[data-slot="dropdown-popover"]')
+ ?.getAttribute("data-state") ?? null
+ );
+}
+
+it("longPress: short click on the real trigger does not open", async () => {
+ vi.useFakeTimers();
+ const { button } = mountLongPress();
+ await flushPromises();
+ button().click();
+ await flushPromises();
+ await vi.advanceTimersByTimeAsync(600);
+ await nextTick();
+ expect(menuState()).toBeNull();
+ vi.useRealTimers();
+});
+
+it("longPress: opens at the threshold and stays open after release", async () => {
+ vi.useFakeTimers();
+ const { button } = mountLongPress();
+ await flushPromises();
+ const el = button();
+ el.dispatchEvent(pointer("pointerdown", { button: 0, pointerType: "mouse" }));
+ await vi.advanceTimersByTimeAsync(200);
+ await nextTick();
+ expect(menuState()).toBeNull();
+ await vi.advanceTimersByTimeAsync(150);
+ await nextTick();
+ expect(menuState()).toBe("open");
+ el.dispatchEvent(pointer("pointerup", { button: 0, pointerType: "mouse" }));
+ el.click();
+ await flushPromises();
+ await nextTick();
+ expect(menuState()).toBe("open");
+ vi.useRealTimers();
+});
+
+it("longPress: pointercancel and out-of-range movement cancel the pending open", async () => {
+ vi.useFakeTimers();
+ const { button } = mountLongPress();
+ await flushPromises();
+ const el = button();
+ el.dispatchEvent(pointer("pointerdown", { button: 0, pointerType: "mouse" }));
+ el.dispatchEvent(pointer("pointermove", { clientX: 40, clientY: 0 }));
+ await vi.advanceTimersByTimeAsync(400);
+ await nextTick();
+ expect(menuState()).toBeNull();
+
+ el.dispatchEvent(
+ pointer("pointerdown", { button: 0, clientX: 0, clientY: 0 }),
+ );
+ el.dispatchEvent(pointer("pointercancel", {}));
+ await vi.advanceTimersByTimeAsync(400);
+ await nextTick();
+ expect(menuState()).toBeNull();
+ vi.useRealTimers();
+});
+
+it("longPress: non-primary button and non-primary pointer are ignored", async () => {
+ vi.useFakeTimers();
+ const { button } = mountLongPress();
+ await flushPromises();
+ const el = button();
+ el.dispatchEvent(pointer("pointerdown", { button: 2, pointerType: "mouse" }));
+ await vi.advanceTimersByTimeAsync(400);
+ await nextTick();
+ expect(menuState()).toBeNull();
+
+ el.dispatchEvent(pointer("pointerdown", { button: 0, isPrimary: false }));
+ await vi.advanceTimersByTimeAsync(400);
+ await nextTick();
+ expect(menuState()).toBeNull();
+ vi.useRealTimers();
+});
+
+it("longPress: Enter and Space open once from the keyboard", async () => {
+ const { w } = mountLongPress();
+ await flushPromises();
+ await w.get("button").trigger("keydown", { key: "Enter" });
+ await flushPromises();
+ expect(menuState()).toBe("open");
+
+ await w.get("button").trigger("keydown", { key: " " });
+ await flushPromises();
+ expect(menuState()).toBeNull();
+
+ await w.get("button").trigger("keydown", { key: " " });
+ await flushPromises();
+ expect(menuState()).toBe("open");
+});
+
+it("longPress: unmount clears the pending long-press timer", async () => {
+ vi.useFakeTimers();
+ const { w } = mountLongPress();
+ await flushPromises();
+ (w.get("button").element as HTMLElement).dispatchEvent(
+ pointer("pointerdown", { button: 0 }),
+ );
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+ w.unmount();
+ cleanup.pop();
+ await nextTick();
+ expect(vi.getTimerCount()).toBe(0);
+ vi.useRealTimers();
+});
+
+function mountSubmenu() {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () => [
+ h(DropdownItem, { id: "copy-link", textValue: "复制链接" }, () =>
+ h(Label, () => "复制链接"),
+ ),
+ h(DropdownSubmenuTrigger, {}, () => [
+ h(DropdownItem, { id: "share", textValue: "分享" }, () => [
+ h(Label, () => "分享"),
+ h(DropdownSubmenuIndicator),
+ ]),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(
+ DropdownItem,
+ { id: "whatsapp", textValue: "WhatsApp" },
+ () => h(Label, () => "WhatsApp"),
+ ),
+ ),
+ ),
+ ]),
+ ]),
+ ),
+ ]),
+ );
+}
+
+function escapeKey(node: Element) {
+ return node.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+}
+
+async function settle() {
+ await flushPromises();
+ await nextTick();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ await flushPromises();
+}
+
+async function openSubmenu() {
+ const subTrigger = document.querySelector(
+ '[data-slot="menu-item"][data-has-submenu="true"]',
+ ) as HTMLElement;
+ expect(subTrigger).toBeTruthy();
+ subTrigger.click();
+ await flushPromises();
+ await nextTick();
+ const subContent = document.querySelector(
+ "[data-submenu-content]",
+ ) as HTMLElement;
+ expect(subContent).toBeTruthy();
+ return { subTrigger, subContent };
+}
+
+it("Escape closes the submenu level first, then the root menu", async () => {
+ mountSubmenu();
+ await flushPromises();
+ await nextTick();
+ const { subTrigger, subContent } = await openSubmenu();
+ const child = subContent.querySelector(
+ '[data-slot="menu-item"]',
+ ) as HTMLElement;
+ child.focus();
+ expect(document.activeElement).toBe(child);
+
+ escapeKey(child);
+ await settle();
+ expect(document.querySelector("[data-submenu-content]")).toBeNull();
+ expect(
+ document.querySelectorAll('[data-slot="dropdown-popover"]').length,
+ ).toBe(1);
+ expect(document.activeElement).toBe(subTrigger);
+
+ escapeKey(subTrigger);
+ await settle();
+ expect(document.querySelector('[data-slot="dropdown-popover"]')).toBeNull();
+});
+
+it("Escape on a pointer-opened submenu trigger closes only that level", async () => {
+ mountSubmenu();
+ await flushPromises();
+ await nextTick();
+ const { subTrigger } = await openSubmenu();
+ // Pointer opening leaves focus on the trigger, outside the sub content.
+ subTrigger.focus();
+ expect(document.activeElement).toBe(subTrigger);
+
+ escapeKey(subTrigger);
+ await settle();
+ expect(document.querySelector("[data-submenu-content]")).toBeNull();
+ expect(
+ document.querySelectorAll('[data-slot="dropdown-popover"]').length,
+ ).toBe(1);
+ expect(document.activeElement).toBe(subTrigger);
+
+ escapeKey(subTrigger);
+ await settle();
+ expect(document.querySelector('[data-slot="dropdown-popover"]')).toBeNull();
+});
+
+it("keyboard activation on a focused item fires the action once", async () => {
+ const actions: MenuKey[] = [];
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () =>
+ h(DropdownItem, { id: "new-file", textValue: "新建文件" }, () =>
+ h(Label, () => "新建文件"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement;
+ item.focus();
+ expect(document.activeElement).toBe(item);
+ item.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await flushPromises();
+ await nextTick();
+ expect(actions).toEqual(["new-file"]);
+});
+
+it("keyboard activation is cancelled when the item click is prevented", async () => {
+ const actions: MenuKey[] = [];
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, { onAction: (k: MenuKey) => actions.push(k) }, () =>
+ h(
+ DropdownItem,
+ {
+ id: "new-file",
+ textValue: "新建文件",
+ onClick: (e: MouseEvent) => e.preventDefault(),
+ },
+ () => h(Label, () => "新建文件"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement;
+ item.focus();
+ item.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await flushPromises();
+ await nextTick();
+ expect(actions).toEqual([]);
+ expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
+});
+
+it("the 17 baseline previews all mount without console warnings", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const demos = import.meta.glob("../apps/docs/demos/dropdown-*.vue", {
+ eager: true,
+ import: "default",
+ });
+ const names = Object.keys(demos).map((path) =>
+ path.replace("../apps/docs/demos/", "").replace(".vue", ""),
+ );
+ expect(names).toHaveLength(17);
+ try {
+ for (const name of names) {
+ const w = mount(demos[`../apps/docs/demos/${name}.vue`] as never, {
+ attachTo: document.body,
+ });
+ await flushPromises();
+ w.unmount();
+ await flushPromises();
+ }
+ expect(error.mock.calls).toEqual([]);
+ expect(warn.mock.calls).toEqual([]);
+ } finally {
+ warn.mockRestore();
+ error.mockRestore();
+ document.body.innerHTML = "";
+ }
+});
+
+it("menu items expose DOM ids and a single role=menu per popup", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () => [
+ h(DropdownItem, { id: "first", textValue: "一" }, () =>
+ h(Label, () => "一"),
+ ),
+ h(DropdownItem, { id: "second", textValue: "二" }, () =>
+ h(Label, () => "二"),
+ ),
+ ]),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const items = 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",
+ ]);
+ expect(document.querySelectorAll('[role="menu"]')).toHaveLength(1);
+});
+
+it("disabled items match the ported CSS presence selector", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, { disabledKeys: ["x"] }, () =>
+ h(DropdownItem, { id: "x", textValue: "X" }, () =>
+ h(Label, () => "X"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement;
+ // `menu-item.css` styles `&[data-disabled]`, so presence is the contract.
+ expect(item.matches("[data-disabled]")).toBe(true);
+});
+
+it("submenu surface keeps a resolvable accessible name", async () => {
+ mountSubmenu();
+ await flushPromises();
+ await nextTick();
+ const { subContent } = await openSubmenu();
+ await flushPromises();
+ const labelledBy = subContent.getAttribute("aria-labelledby");
+ expect(labelledBy).toBeTruthy();
+ expect(document.getElementById(labelledBy as string)).not.toBeNull();
+});
+
+it("Section names its group from a nested Header", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownSection, {}, () => [
+ h(Header, {}, () => "操作"),
+ h(DropdownItem, { id: "a", textValue: "A" }, () =>
+ h(Label, () => "A"),
+ ),
+ ]),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const section = document.querySelector(
+ '[data-slot="menu-section"]',
+ ) as HTMLElement;
+ const labelledBy = section.getAttribute("aria-labelledby");
+ expect(labelledBy).toBeTruthy();
+ const header = document.getElementById(labelledBy as string);
+ expect(header?.textContent).toBe("操作");
+});
+
+it("a non-button custom trigger stays keyboard focusable", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, {}, () => [
+ h(DropdownTrigger, {}, () =>
+ h(Avatar, {}, () => h(AvatarFallback, {}, () => "JD")),
+ ),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "a", textValue: "A" }, () =>
+ h(Label, () => "A"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const trigger = document.querySelector(
+ '[data-slot="dropdown-trigger"]',
+ ) as HTMLElement;
+ expect(trigger.tagName).toBe("SPAN");
+ expect(trigger.getAttribute("role")).toBe("button");
+ expect(trigger.getAttribute("tabindex")).toBe("0");
+});
+
+it("item and indicator slots expose the upstream render state", async () => {
+ const seen: Record[] = [];
+ const indicatorState: Record[] = [];
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(
+ DropdownMenu,
+ { selectionMode: "single", selectedKeys: ["a"] },
+ {
+ default: () =>
+ h(
+ DropdownItem,
+ { id: "a", textValue: "A" },
+ {
+ default: (state: Record) => {
+ seen.push(state);
+ return [
+ h(
+ DropdownItemIndicator,
+ {},
+ {
+ default: (indicator: Record) => {
+ indicatorState.push(indicator);
+ return null;
+ },
+ },
+ ),
+ h(Label, () => "A"),
+ ];
+ },
+ },
+ ),
+ },
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ expect(seen[0]).toMatchObject({
+ isSelected: true,
+ isDisabled: false,
+ isPressed: false,
+ });
+ expect(seen[0]).toHaveProperty("isFocused");
+ expect(indicatorState[0]).toMatchObject({
+ isSelected: true,
+ isIndeterminate: false,
+ });
+});
+
+it("caller classes merge with tailwind-variants semantics", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "a", textValue: "A", class: "p-0" }, () =>
+ h(Label, () => "A"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const item = document.querySelector('[data-slot="menu-item"]') as HTMLElement;
+ expect(item.className).toContain("hv-menu-item");
+ expect(item.className).toContain("p-0");
+});
+
+it("pressing the submenu trigger without an indicator still treats it as a submenu", async () => {
+ const actions: MenuKey[] = [];
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () => [
+ h(DropdownTrigger, {}, () => h(Button, () => "菜单")),
+ h(DropdownPopover, {}, () =>
+ h(
+ DropdownMenu,
+ { onAction: (key: MenuKey) => actions.push(key) },
+ () =>
+ h(DropdownSubmenuTrigger, {}, () => [
+ h(DropdownItem, { id: "more", textValue: "更多" }, () =>
+ h(Label, () => "更多"),
+ ),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "child", textValue: "子项" }, () =>
+ h(Label, () => "子项"),
+ ),
+ ),
+ ),
+ ]),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const trigger = document.querySelector(
+ '[data-slot="menu-item"][data-has-submenu="true"]',
+ ) as HTMLElement;
+ expect(trigger).not.toBeNull();
+ trigger.click();
+ await flushPromises();
+ await nextTick();
+ // A submenu trigger must not fire the menu action nor close the root menu.
+ expect(actions).toEqual([]);
+ expect(document.querySelector("[data-submenu-content]")).not.toBeNull();
+ expect(
+ document.querySelectorAll('[data-slot="dropdown-popover"]').length,
+ ).toBeGreaterThan(1);
+});
+
+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);
+});
+
+it("root popover merges caller handlers for escape, outside, focus and animation", async () => {
+ const calls = { focus: 0, escape: 0, outside: 0, animation: 0, keydown: 0 };
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true, modal: false }, () => [
+ h(
+ DropdownPopover,
+ {
+ onOpenAutoFocus: () => {
+ calls.focus += 1;
+ },
+ onEscapeKeyDown: () => {
+ calls.escape += 1;
+ },
+ onInteractOutside: () => {
+ calls.outside += 1;
+ },
+ onAnimationend: () => {
+ calls.animation += 1;
+ },
+ onKeydown: () => {
+ calls.keydown += 1;
+ },
+ },
+ () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "a", textValue: "A" }, () =>
+ h(Label, () => "A"),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ const menu = document.querySelector('[role="menu"]') as HTMLElement;
+ menu.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }),
+ );
+ menu.dispatchEvent(new Event("animationend", { bubbles: true }));
+ await flushPromises();
+ expect(calls.keydown).toBe(1);
+ expect(calls.animation).toBe(1);
+ expect(calls.focus).toBe(1);
+});
+
+it("a cancelled caller keydown keeps the menu open for clearSelection menus", async () => {
+ const selections: MenuKey[][] = [];
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true, modal: false }, () => [
+ h(
+ DropdownPopover,
+ {
+ onKeydown: (event: KeyboardEvent) => {
+ if (event.key === "Escape") event.preventDefault();
+ },
+ },
+ () =>
+ h(
+ DropdownMenu,
+ {
+ selectionMode: "multiple",
+ selectedKeys: ["a"],
+ escapeKeyBehavior: "clearSelection",
+ "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;
+ menu.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await flushPromises();
+ // The caller cancelled the escape, so the internal clear did not run.
+ expect(selections).toEqual([]);
+ expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
+});
+
+it("submenu keyboard dismissal can be disabled without closing the parent", async () => {
+ 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, { isKeyboardDismissDisabled: true }, () =>
+ 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;
+ const item = panel.querySelector('[data-slot="menu-item"]') as HTMLElement;
+ item.focus();
+ item.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Escape",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await settle();
+ expect(document.querySelector("[data-submenu-content]")).not.toBeNull();
+ expect(
+ document.querySelectorAll('[data-slot="dropdown-popover"]').length,
+ ).toBeGreaterThan(1);
+});
+
+it("menu-level close policy wins over the section mode default", async () => {
+ mountApp(
+ () => () =>
+ h(DropdownRoot, { defaultOpen: true, modal: false }, () => [
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, { shouldCloseOnSelect: false }, () =>
+ h(DropdownSection, { selectionMode: "single" }, () =>
+ h(DropdownItem, { id: "s", textValue: "S" }, () =>
+ h(Label, () => "S"),
+ ),
+ ),
+ ),
+ ),
+ ]),
+ );
+ await flushPromises();
+ await nextTick();
+ (document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
+ await flushPromises();
+ await nextTick();
+ expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
+});
diff --git a/tests/b01-review.probe.test.ts b/tests/b01-review.probe.test.ts
new file mode 100644
index 0000000..62122ad
--- /dev/null
+++ b/tests/b01-review.probe.test.ts
@@ -0,0 +1,162 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { Button, DropdownTrigger } from "../packages/vue/src";
+import { mount, flushPromises } from "@vue/test-utils";
+import { defineComponent, h } from "vue";
+import {
+ DropdownRoot,
+ DropdownPopover,
+ DropdownMenu,
+ DropdownItem,
+ DropdownItemIndicator,
+ DropdownSubmenuTrigger,
+ DropdownSubmenuIndicator,
+ Menu,
+ MenuItem,
+} from "../packages/vue/src";
+const cleanup: (() => void)[] = [];
+afterEach(() => {
+ cleanup
+ .splice(0)
+ .reverse()
+ .forEach((fn) => fn());
+ document.body.innerHTML = "";
+});
+async function renderMenu(
+ menuProps = {},
+ itemProps = {},
+ children = () => "A",
+) {
+ const w = mount(
+ defineComponent({
+ setup: () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () =>
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, menuProps, () =>
+ h(
+ DropdownItem,
+ { id: "a", textValue: "A", ...itemProps },
+ children,
+ ),
+ ),
+ ),
+ ),
+ }),
+ { attachTo: document.body },
+ );
+ cleanup.push(() => w.unmount());
+ await flushPromises();
+ return document.querySelector('[data-slot="menu-item"]') as HTMLElement;
+}
+it("selected multiple item exposes checked menu semantics and source CSS selected state", async () => {
+ const node = await renderMenu(
+ { selectionMode: "multiple", selectedKeys: ["a"] },
+ {},
+ () => [h(DropdownItemIndicator, { type: "dot" }), "A"] as never,
+ );
+ expect(node.getAttribute("role")).toBe("menuitemcheckbox");
+ expect(node.getAttribute("aria-checked")).toBe("true");
+});
+it("preventing click prevents action and default close", async () => {
+ const action = vi.fn();
+ const node = await renderMenu(
+ { onAction: action },
+ { onClick: (e: MouseEvent) => e.preventDefault() },
+ );
+ node.click();
+ await flushPromises();
+ expect(action).not.toHaveBeenCalled();
+ expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
+});
+it("submenu trigger has one menuitem DOM node rather than nested interactive items", async () => {
+ const w = mount(
+ defineComponent({
+ setup: () => () =>
+ h(DropdownRoot, { defaultOpen: true }, () =>
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownSubmenuTrigger, {}, () => [
+ h(DropdownItem, { id: "sub", textValue: "Sub" }, () => [
+ "Sub",
+ h(DropdownSubmenuIndicator),
+ ]),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () =>
+ h(DropdownItem, { id: "child" }, () => "Child"),
+ ),
+ ),
+ ]),
+ ),
+ ),
+ ),
+ }),
+ { attachTo: document.body },
+ );
+ cleanup.push(() => w.unmount());
+ await flushPromises();
+ expect(
+ document.querySelector('[role="menuitem"] [role="menuitem"]'),
+ ).toBeNull();
+});
+it("standalone exported Menu and MenuItem do not require an internal DropdownMenuRoot", () => {
+ expect(() => {
+ const w = mount(Menu, {
+ slots: { default: () => h(MenuItem, { id: "a" }, () => "A") },
+ });
+ cleanup.push(() => w.unmount());
+ }).not.toThrow();
+});
+
+it("stopImmediatePropagation stops subsequent user handlers and activation", async () => {
+ const action = vi.fn();
+ const second = vi.fn();
+ const node = await renderMenu(
+ { onAction: action },
+ {
+ onClick: [(e: MouseEvent) => e.stopImmediatePropagation(), second],
+ },
+ );
+ node.click();
+ await flushPromises();
+ expect(second).not.toHaveBeenCalled();
+ expect(action).not.toHaveBeenCalled();
+});
+
+it("longPress trigger does not open on a short click of the actual button", async () => {
+ const w = mount(
+ defineComponent({
+ setup: () => () =>
+ h(DropdownRoot, { trigger: "longPress" }, () => [
+ h(DropdownTrigger, {}, () => h(Button, {}, () => "Hold")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
+ ),
+ ]),
+ }),
+ { attachTo: document.body },
+ );
+ cleanup.push(() => w.unmount());
+ await flushPromises();
+ (w.get("button").element as HTMLElement).click();
+ await flushPromises();
+ expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
+});
+
+it("longPress keyboard Enter opens instead of toggling twice", async () => {
+ const w = mount(
+ defineComponent({
+ setup: () => () =>
+ h(DropdownRoot, { trigger: "longPress" }, () => [
+ h(DropdownTrigger, {}, () => h(Button, {}, () => "Hold")),
+ h(DropdownPopover, {}, () =>
+ h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
+ ),
+ ]),
+ }),
+ { attachTo: document.body },
+ );
+ cleanup.push(() => w.unmount());
+ await flushPromises();
+ await w.get("button").trigger("keydown", { key: "Enter" });
+ await flushPromises();
+ expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
+});
diff --git a/tests/b02-public-integration.test.ts b/tests/b02-public-integration.test.ts
new file mode 100644
index 0000000..1ac3915
--- /dev/null
+++ b/tests/b02-public-integration.test.ts
@@ -0,0 +1,91 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mount, flushPromises } from "@vue/test-utils";
+import { defineComponent } from "vue";
+import {
+ ComboBox,
+ ComboBoxInputGroup,
+ ComboBoxPopover,
+ ComboBoxTrigger,
+ Input,
+ ListBox,
+ ListBoxItem,
+ Autocomplete,
+ AutocompleteTrigger,
+ AutocompletePopover,
+ AutocompleteFilter,
+ SearchField,
+ SearchFieldInput,
+} from "../packages/vue/src";
+import { createBaseContains } from "../packages/vue/src/components/collection/match";
+const components = {
+ ComboBox,
+ ComboBoxInputGroup,
+ ComboBoxPopover,
+ ComboBoxTrigger,
+ Input,
+ ListBox,
+ ListBoxItem,
+ Autocomplete,
+ AutocompleteTrigger,
+ AutocompletePopover,
+ AutocompleteFilter,
+ SearchField,
+ SearchFieldInput,
+};
+const roots: ReturnType[] = [];
+afterEach(() => {
+ roots.splice(0).forEach((w) => w.unmount());
+ document.body.innerHTML = "";
+ vi.restoreAllMocks();
+});
+function view(template: string) {
+ const w = mount(defineComponent({ components, template }), {
+ attachTo: document.body,
+ });
+ roots.push(w);
+ return w;
+}
+describe("public picker integration", () => {
+ it("retains Vue string template refs on the actual composed Input and clears them on removal", async () => {
+ const w = view(
+ 'Alpha',
+ );
+ await flushPromises();
+ expect((w.vm.$refs.consumerInput as { $el: Element }).$el).toBe(
+ w.get("input[role=combobox]").element,
+ );
+ w.unmount();
+ roots.splice(roots.indexOf(w), 1);
+ expect(w.vm.$refs.consumerInput).toBeNull();
+ });
+ it("retains a string template ref on the teleported search input", async () => {
+ const w = view(
+ 'ChooseAlpha',
+ );
+ await flushPromises();
+ expect((w.vm.$refs.consumerSearch as { $el: Element }).$el).toBe(
+ document.querySelector("input[role=combobox]"),
+ );
+ });
+ it("respects a caller-disabled Autocomplete trigger before opening", async () => {
+ const w = view(
+ 'ChooseAlpha',
+ );
+ await w.get('[data-slot="autocomplete-trigger"]').trigger("click");
+ expect(
+ w.get('[data-slot="autocomplete-trigger"]').attributes("aria-expanded"),
+ ).toBe("false");
+ expect(
+ w.get('[data-slot="autocomplete-trigger"]').attributes("aria-disabled"),
+ ).toBe("true");
+ });
+});
+it.each([
+ ["tr", "İstanbul", "istanbul", true],
+ ["tr", "Isparta", "ısparta", true],
+ ["tr", "Isparta", "isparta", false],
+ ["de", "Fußgänger", "fuss", true],
+ ["en", "Café", "cafe\u0301", true],
+])("locale filter %s: %s / %s", (locale, text, query, expected) => {
+ expect(createBaseContains(locale)(text, query)).toBe(expected);
+});
diff --git a/tests/b02-review.probe.test.ts b/tests/b02-review.probe.test.ts
new file mode 100644
index 0000000..d3b0220
--- /dev/null
+++ b/tests/b02-review.probe.test.ts
@@ -0,0 +1,448 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { defineComponent, h, nextTick, ref, type Ref } from "vue";
+import {
+ ComboBox,
+ ComboBoxInputGroup,
+ ComboBoxPopover,
+ ComboBoxTrigger,
+ Autocomplete,
+ AutocompleteTrigger,
+ AutocompleteValue,
+ AutocompleteClearButton,
+ AutocompleteIndicator,
+ AutocompletePopover,
+ AutocompleteFilter,
+ Input,
+ ListBox,
+ ListBoxItem,
+ SearchField,
+ SearchFieldGroup,
+ SearchFieldInput,
+ SearchFieldClearButton,
+} from "../packages/vue/src";
+const roots: { unmount(): void }[] = [];
+const tick = async () => {
+ await nextTick();
+ await new Promise((r) => setTimeout(r, 6));
+};
+afterEach(async () => {
+ while (roots.length) roots.pop()!.unmount();
+ await tick();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+});
+type Item = { id: string | number; textValue: string };
+const defaults: Item[] = [
+ { id: 0, textValue: "Numeric Zero" },
+ { id: "0", textValue: "String Zero" },
+ { id: "a", textValue: "Alpha" },
+ { id: "b", textValue: "Beta" },
+];
+function picker(
+ kind: "combo" | "auto",
+ props: () => Record = () => ({}),
+ opts: {
+ items?: Ref- ;
+ inputProps?: Record;
+ filterProps?: Record;
+ } = {},
+) {
+ const items = opts.items ?? ref(defaults);
+ const w = mount(
+ defineComponent({
+ setup: () => () =>
+ h("form", null, [
+ h(
+ kind === "combo" ? ComboBox : Autocomplete,
+ { "aria-label": "Picker", ...props() },
+ {
+ default: () => [
+ kind === "combo"
+ ? h(ComboBoxInputGroup, null, {
+ default: () => [
+ h(Input, opts.inputProps),
+ h(ComboBoxTrigger),
+ ],
+ })
+ : h(AutocompleteTrigger, null, {
+ default: () => [
+ h(AutocompleteValue),
+ h(AutocompleteClearButton),
+ h(AutocompleteIndicator),
+ ],
+ }),
+ h(
+ kind === "combo" ? ComboBoxPopover : AutocompletePopover,
+ null,
+ {
+ default: () => {
+ const list = h(ListBox, null, {
+ default: () =>
+ items.value.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.textValue,
+ },
+ () => item.textValue,
+ ),
+ ),
+ });
+ return kind === "combo"
+ ? list
+ : h(AutocompleteFilter, opts.filterProps, {
+ default: () => [
+ h(
+ SearchField,
+ { "aria-label": "Search" },
+ {
+ default: () =>
+ h(SearchFieldGroup, null, {
+ default: () => [
+ h(SearchFieldInput, opts.inputProps),
+ h(SearchFieldClearButton),
+ ],
+ }),
+ },
+ ),
+ list,
+ ],
+ });
+ },
+ },
+ ),
+ ],
+ },
+ ),
+ ]),
+ }),
+ { attachTo: document.body },
+ );
+ roots.push(w);
+ return w;
+}
+const comboInput = () =>
+ document.querySelector('[data-slot="input"]')!;
+const searchInput = () =>
+ document.querySelector('[data-slot="search-field-input"]')!;
+async function open(kind: "combo" | "auto") {
+ if (kind === "combo") comboInput().focus();
+ else
+ document
+ .querySelector('[data-slot="autocomplete-trigger"]')!
+ .click();
+ await tick();
+}
+async function type(el: HTMLInputElement, text: string) {
+ el.value = text;
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ await tick();
+}
+
+it("native cancelable clear click actually clears Autocomplete", async () => {
+ const change = vi.fn();
+ picker("auto", () => ({ defaultValue: "a", onChange: change }));
+ await tick();
+ document
+ .querySelector(
+ '[data-slot="autocomplete-clear-button"]',
+ )!
+ .click();
+ await tick();
+ expect(change).toHaveBeenLastCalledWith(null);
+});
+it.each(["combo", "auto"] as const)(
+ "%s disabled fields do not submit a value",
+ async (kind) => {
+ const w = picker(kind, () => ({
+ name: "choice",
+ defaultValue: "a",
+ isDisabled: true,
+ }));
+ await tick();
+ expect(new FormData(w.element as HTMLFormElement).has("choice")).toBe(
+ false,
+ );
+ },
+);
+it.each(["combo", "auto"] as const)(
+ "%s multiple values use same-name entries",
+ async (kind) => {
+ const w = picker(kind, () => ({
+ name: "choice",
+ selectionMode: "multiple",
+ defaultValue: ["a", "b"],
+ }));
+ await tick();
+ expect(new FormData(w.element as HTMLFormElement).getAll("choice")).toEqual(
+ ["a", "b"],
+ );
+ },
+);
+it("ComboBox external clear clears displayed text", async () => {
+ const selected = ref("a");
+ picker("combo", () => ({ modelValue: selected.value }));
+ await tick();
+ expect(comboInput().value).toBe("Alpha");
+ selected.value = null;
+ await tick();
+ expect(comboInput().value).toBe("");
+});
+it("ComboBox keeps numeric and string keys distinct in external text synchronization", async () => {
+ const selected = ref(0);
+ picker("combo", () => ({ modelValue: selected.value }));
+ await tick();
+ selected.value = "0";
+ await tick();
+ expect(comboInput().value).toBe("String Zero");
+});
+it("ComboBox accepts selected label updates without an item-count change", async () => {
+ const items = ref
- ([{ id: "a", textValue: "Old" }]);
+ picker("combo", () => ({ modelValue: "a" }), { items });
+ await tick();
+ items.value = [{ id: "a", textValue: "New" }];
+ await tick();
+ expect(comboInput().value).toBe("New");
+});
+it("ComboBox respects a controlled empty inputValue", async () => {
+ picker("combo", () => ({ modelValue: "a", inputValue: "" }));
+ await tick();
+ expect(comboInput().value).toBe("");
+});
+it("ComboBox allows clearing a required selection before validation", async () => {
+ const update = vi.fn();
+ picker("combo", () => ({
+ defaultValue: "a",
+ isRequired: true,
+ "onUpdate:modelValue": update,
+ }));
+ await tick();
+ await type(comboInput(), "");
+ expect(update).toHaveBeenLastCalledWith(null);
+ expect(comboInput().value).toBe("");
+});
+it.each(["combo", "auto"] as const)(
+ "%s asChild uses the supplied root",
+ async (kind) => {
+ // The ordinary component tree is the one custom wrapper supplied to the root.
+ const Root = kind === "combo" ? ComboBox : Autocomplete;
+ const w = mount(Root, {
+ props: { asChild: true },
+ slots: {
+ default: () => h("section", { "data-custom": "root" }, "Custom"),
+ },
+ attachTo: document.body,
+ });
+ roots.push(w);
+ await tick();
+ expect(w.element.tagName).toBe("SECTION");
+ },
+);
+it("ComboBox autoFocus focuses its composed input", async () => {
+ picker("combo", () => ({ autoFocus: true }));
+ await tick();
+ expect(document.activeElement).toBe(comboInput());
+});
+it("ComboBox secondary variant reaches its input", async () => {
+ picker("combo", () => ({ variant: "secondary" }));
+ await tick();
+ expect(comboInput().classList.contains("hv-input--secondary")).toBe(true);
+});
+it("ComboBox preserves caller input component ref", async () => {
+ const inputRef = ref();
+ picker("combo", () => ({}), { inputProps: { ref: inputRef } });
+ await tick();
+ expect(inputRef.value).toBeTruthy();
+});
+it("Autocomplete preserves caller search-input component ref", async () => {
+ const inputRef = ref();
+ picker("auto", () => ({}), { inputProps: { ref: inputRef } });
+ await tick();
+ await open("auto");
+ expect(inputRef.value).toBeTruthy();
+});
+it("Autocomplete search clear resets its filter", async () => {
+ picker("auto");
+ await tick();
+ await open("auto");
+ await type(searchInput(), "Beta");
+ expect(
+ document.querySelectorAll('[role="option"]:not([data-filtered])').length,
+ ).toBe(1);
+ document
+ .querySelector(
+ '[data-slot="search-field-clear-button"]',
+ )!
+ .click();
+ await tick();
+ expect(searchInput().value).toBe("");
+ expect(
+ document.querySelectorAll('[role="option"]:not([data-filtered])').length,
+ ).toBe(4);
+});
+it("ComboBox respects an active composition session even on an unflagged Enter", async () => {
+ const change = vi.fn();
+ picker("combo", () => ({ onChange: change }));
+ await tick();
+ await open("combo");
+ comboInput().dispatchEvent(
+ new CompositionEvent("compositionstart", { bubbles: true }),
+ );
+ comboInput().dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await tick();
+ expect(change).not.toHaveBeenCalled();
+});
+it.each(["combo", "auto"] as const)(
+ "%s does not filter during a composition session",
+ async (kind) => {
+ picker(kind);
+ await tick();
+ await open(kind);
+ const input = kind === "combo" ? comboInput() : searchInput();
+ input.dispatchEvent(
+ new CompositionEvent("compositionstart", { bubbles: true }),
+ );
+ input.value = "qqq";
+ input.dispatchEvent(
+ new InputEvent("input", { bubbles: true, isComposing: true }),
+ );
+ await tick();
+ expect(
+ document.querySelectorAll('[role="option"]:not([data-filtered])').length,
+ ).toBe(4);
+ },
+);
+it("Autocomplete keeps filter focus when parent rejects closing", async () => {
+ picker("auto", () => ({ open: true }));
+ await tick();
+ const input = searchInput();
+ input.focus();
+ await type(input, "Beta");
+ input.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await tick();
+ expect(
+ document
+ .querySelector('[data-slot="autocomplete-trigger"]')!
+ .getAttribute("aria-expanded"),
+ ).toBe("true");
+ expect(document.activeElement).toBe(input);
+});
+it("Autocomplete preserves an explicit search input accessible name", async () => {
+ picker("auto", () => ({}), {
+ inputProps: { "aria-label": "Specific search" },
+ });
+ await tick();
+ await open("auto");
+ expect(searchInput().getAttribute("aria-label")).toBe("Specific search");
+});
+it("ComboBox input participates in its explicitly associated form", async () => {
+ const external = document.createElement("form");
+ external.id = "external-form";
+ document.body.appendChild(external);
+ picker("combo", () => ({ form: "external-form", name: "choice" }));
+ await tick();
+ expect(comboInput().form).toBe(external);
+});
+it("Autocomplete clear button retains a caller disabled attribute", async () => {
+ const w = mount(Autocomplete, {
+ props: { defaultValue: "a" },
+ slots: {
+ default: () =>
+ h(AutocompleteTrigger, null, {
+ default: () => [
+ h(AutocompleteValue),
+ h(AutocompleteClearButton, { disabled: true }),
+ ],
+ }),
+ },
+ attachTo: document.body,
+ });
+ roots.push(w);
+ await tick();
+ expect(
+ document.querySelector(
+ '[data-slot="autocomplete-clear-button"]',
+ )!.disabled,
+ ).toBe(true);
+});
+it.each(["combo", "auto"] as const)(
+ "%s does not submit a removed selection as a valid option",
+ async (kind) => {
+ const items = ref
- ([...defaults]);
+ const w = picker(kind, () => ({ defaultValue: "a", name: "choice" }), {
+ items,
+ });
+ await tick();
+ items.value = items.value.filter((i) => i.id !== "a");
+ await tick();
+ expect(new FormData(w.element as HTMLFormElement).get("choice")).not.toBe(
+ "a",
+ );
+ },
+);
+it("Autocomplete default base-sensitivity filter matches accents", async () => {
+ picker("auto", () => ({}), {
+ items: ref([{ id: "cafe", textValue: "Café" }]),
+ });
+ await tick();
+ await open("auto");
+ await type(searchInput(), "cafe");
+ expect(
+ document.querySelectorAll('[role="option"]:not([data-filtered])').length,
+ ).toBe(1);
+});
+it("Autocomplete default indicator matches its size selector", async () => {
+ picker("auto");
+ await tick();
+ // The shipped rule requires class and data-slot on the same element.
+ expect(
+ document.querySelector(
+ '.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
+ ),
+ ).not.toBeNull();
+});
+it("ComboBox custom text is the submitted text after editing a selected item", async () => {
+ const w = picker("combo", () => ({
+ defaultValue: "a",
+ allowsCustomValue: true,
+ name: "choice",
+ }));
+ await tick();
+ await type(comboInput(), "Custom animal");
+ expect(new FormData(w.element as HTMLFormElement).get("choice")).toBe(
+ "Custom animal",
+ );
+});
+it("ComboBox trigger retains a caller disabled attribute", async () => {
+ const w = mount(ComboBox, {
+ slots: {
+ default: () =>
+ h(ComboBoxInputGroup, null, {
+ default: () => [h(Input), h(ComboBoxTrigger, { disabled: true })],
+ }),
+ },
+ attachTo: document.body,
+ });
+ roots.push(w);
+ await tick();
+ expect(
+ document.querySelector(
+ '[data-slot="combo-box-trigger"]',
+ )!.disabled,
+ ).toBe(true);
+});
diff --git a/tests/b02a-review.probe.test.ts b/tests/b02a-review.probe.test.ts
new file mode 100644
index 0000000..b5d5645
--- /dev/null
+++ b/tests/b02a-review.probe.test.ts
@@ -0,0 +1,123 @@
+import { afterEach, expect, it, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { computed, defineComponent, h, nextTick, provide, ref } from "vue";
+import { ListBox, ListBoxItem } from "../packages/vue/src";
+import {
+ collectionOwnerKey,
+ type CollectionOwner,
+ type OwnedCollection,
+} from "../packages/vue/src/components/collection/owner";
+import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
+const mounted: { unmount(): void }[] = [];
+afterEach(() => {
+ while (mounted.length) mounted.pop()!.unmount();
+ vi.restoreAllMocks();
+});
+const settle = async () => {
+ await nextTick();
+ await new Promise((r) => setTimeout(r, 3));
+};
+function setupList(virtualized = false) {
+ let collection: OwnedCollection | undefined;
+ const items = Array.from({ length: 6 }, (_, id) => ({
+ id,
+ textValue: `Row ${id}`,
+ }));
+ const activeKey = ref();
+ const owner: CollectionOwner = {
+ keys: computed(() => []),
+ mode: computed(() => "single"),
+ disabled: computed(() => false),
+ readOnly: computed(() => false),
+ disabledKeys: computed(() => []),
+ id: "probe",
+ labelledBy: () => undefined,
+ ariaLabel: () => "Probe",
+ request: () => {},
+ action: () => {},
+ leave: () => {},
+ connect: (c) => {
+ collection = c;
+ return () => {
+ collection = undefined;
+ };
+ },
+ filter: (r) => r.key === 3,
+ virtualFocus: () => true,
+ activeKey,
+ };
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ provide(collectionOwnerKey, owner);
+ return () =>
+ h(
+ ListBox,
+ { items, virtualized, rowHeight: 40, overscan: 8 },
+ {
+ default: ({ item }: { item: (typeof items)[number] }) =>
+ h(ListBoxItem, { id: item.id }, () => item.textValue),
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper);
+ return { wrapper, collection: () => collection };
+}
+it("preserves caller hidden on an ordinary ListBoxItem", async () => {
+ const w = mount(ListBox, {
+ slots: {
+ default: () =>
+ h(ListBoxItem, { id: "hidden", hidden: true }, () => "Hidden"),
+ },
+ });
+ mounted.push(w);
+ await settle();
+ expect(w.find('[role="option"]').attributes("hidden")).toBeDefined();
+});
+it("reveal scrolls a mounted ordinary row without moving DOM focus", async () => {
+ const { wrapper, collection } = setupList();
+ await settle();
+ const node = wrapper.findAll('[role="option"]')[3].element;
+ const scroll = vi.fn();
+ Object.defineProperty(node, "scrollIntoView", {
+ configurable: true,
+ value: scroll,
+ });
+ await collection()!.reveal!(3);
+ expect(scroll).toHaveBeenCalled();
+});
+it("virtual window contains no fixed height slots for filtered-out rows", async () => {
+ const { wrapper } = setupList(true);
+ await settle();
+ expect(
+ wrapper.findAll(
+ '[data-slot="list-box-virtual-content"] > [role="presentation"]',
+ ),
+ ).toHaveLength(1);
+});
+it("restores keyboard highlight intent after a pointer interaction", async () => {
+ const w = mount(Harness, { attachTo: document.body });
+ mounted.push(w);
+ await settle();
+ const input = w.find("input");
+ await input.setValue("");
+ await settle();
+ await w.findAll('[role="option"]')[0].trigger("pointerdown");
+ await input.trigger("keydown", { key: "ArrowDown" });
+ await settle();
+ expect(w.find('[data-focused="true"]').attributes("data-focus-visible")).toBe(
+ "true",
+ );
+});
+it("has instance-unique names and controls in the verification harness", async () => {
+ const w = mount(
+ defineComponent({ setup: () => () => h("div", [h(Harness), h(Harness)]) }),
+ );
+ mounted.push(w);
+ await settle();
+ const ids = w.findAll("[id]").map((n) => n.attributes("id"));
+ expect(new Set(ids).size).toBe(ids.length);
+});
diff --git a/tests/b02a-round2-review.probe.test.ts b/tests/b02a-round2-review.probe.test.ts
new file mode 100644
index 0000000..74ed883
--- /dev/null
+++ b/tests/b02a-round2-review.probe.test.ts
@@ -0,0 +1,148 @@
+import { afterEach, it, expect, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { computed, defineComponent, h, nextTick, provide, ref } from "vue";
+import { ListBox, ListBoxItem } from "../packages/vue/src";
+import {
+ collectionOwnerKey,
+ type CollectionOwner,
+ type OwnedCollection,
+} from "../packages/vue/src/components/collection/owner";
+import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
+const roots: { unmount(): void }[] = [];
+const settle = async () => {
+ await nextTick();
+ await new Promise((r) => setTimeout(r, 3));
+};
+afterEach(() => {
+ while (roots.length) roots.pop()!.unmount();
+ vi.restoreAllMocks();
+});
+it("does not scroll a reveal request after filtering invalidates it", async () => {
+ let collection: OwnedCollection | undefined;
+ const visible = ref(true);
+ const activeKey = ref();
+ const owner: CollectionOwner = {
+ keys: computed(() => []),
+ mode: computed(() => "single"),
+ disabled: computed(() => false),
+ readOnly: computed(() => false),
+ disabledKeys: computed(() => []),
+ id: "pending-reveal",
+ labelledBy: () => undefined,
+ ariaLabel: () => undefined,
+ request: () => {},
+ action: () => {},
+ leave: () => {},
+ connect: (c) => {
+ collection = c;
+ return () => {};
+ },
+ virtualFocus: () => true,
+ activeKey,
+ filter: () => visible.value,
+ };
+ const w = mount(
+ defineComponent({
+ setup() {
+ provide(collectionOwnerKey, owner);
+ return () =>
+ h(ListBox, null, () => h(ListBoxItem, { id: "a" }, () => "A"));
+ },
+ }),
+ { attachTo: document.body },
+ );
+ roots.push(w);
+ await settle();
+ const spy = vi.fn();
+ Object.defineProperty(w.find('[role="option"]').element, "scrollIntoView", {
+ configurable: true,
+ value: spy,
+ });
+ const pending = collection!.reveal!("a");
+ visible.value = false;
+ await pending;
+ expect(spy).not.toHaveBeenCalled();
+});
+it("does not select the parent option when a nested button is clicked", async () => {
+ const w = mount(Harness, { attachTo: document.body });
+ roots.push(w);
+ await settle();
+ await w.find("input").setValue("");
+ await settle();
+ const row = w.find('[role="option"]').element;
+ const button = document.createElement("button");
+ row.appendChild(button);
+ button.click();
+ await settle();
+ expect(w.emitted("update:modelValue")).toBeUndefined();
+});
+it("shows pointer pressed state while preserving input focus", async () => {
+ const w = mount(Harness, { attachTo: document.body });
+ roots.push(w);
+ await settle();
+ await w.find("input").setValue("");
+ await settle();
+ const row = w.find('[role="option"]');
+ await row.trigger("pointerdown", { button: 0 });
+ await settle();
+ expect(row.attributes("data-pressed")).toBe("true");
+});
+it.each(["removed", "disabled"])(
+ "does not confirm a dynamically %s active option",
+ async (mode) => {
+ const w = mount(Harness, {
+ props: {
+ options: [
+ { id: "a", text: "A" },
+ { id: "b", text: "B" },
+ ],
+ },
+ attachTo: document.body,
+ });
+ roots.push(w);
+ await settle();
+ await w.find("input").setValue("");
+ await settle();
+ expect(w.vm.activeKey).toBe("a");
+ await w.setProps({
+ options:
+ mode === "removed"
+ ? [{ id: "b", text: "B" }]
+ : [
+ { id: "a", text: "A", disabled: true },
+ { id: "b", text: "B" },
+ ],
+ });
+ await settle();
+ await w.find("input").trigger("keydown", { key: "Enter" });
+ await settle();
+ expect(
+ w.emitted("proposal")?.some((args) => args[0] === "a") ?? false,
+ ).toBe(false);
+ },
+);
+it("provides filtered-empty feedback for the static slot collection", async () => {
+ const w = mount(Harness, { attachTo: document.body });
+ roots.push(w);
+ await settle();
+ await w.find("input").setValue("no-match");
+ await settle();
+ expect(w.find('[data-test="empty"]').exists()).toBe(true);
+});
+it("can filter a record outside the initially mounted virtual window", async () => {
+ const options = Array.from({ length: 100 }, (_, i) => ({
+ id: i,
+ text: `Row ${i}`,
+ }));
+ const w = mount(Harness, {
+ props: { virtualized: true, options },
+ attachTo: document.body,
+ });
+ roots.push(w);
+ await settle();
+ await w.find("input").setValue("Row 99");
+ await settle();
+ expect(
+ w.findAll('[role="option"]').some((row) => row.text().trim() === "Row 99"),
+ ).toBe(true);
+});
diff --git a/tests/collection-filter-virtual.test.ts b/tests/collection-filter-virtual.test.ts
new file mode 100644
index 0000000..4a99998
--- /dev/null
+++ b/tests/collection-filter-virtual.test.ts
@@ -0,0 +1,754 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { defineComponent, h, nextTick, ref } from "vue";
+import { ListBox, ListBoxItem } from "../packages/vue/src";
+import {
+ collectionOwnerKey,
+ type CollectionOwner,
+ type CollectionRecord,
+ type OwnedCollection,
+} from "../packages/vue/src/components/collection/owner";
+import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
+
+const wrappers: { unmount: () => void; element: Element }[] = [];
+
+// jsdom gaps used by the virtualized reveal path; fill only when missing.
+if (typeof Element.prototype.scrollTo !== "function")
+ Element.prototype.scrollTo = () => {};
+
+function pointerEvent(type: string) {
+ return new MouseEvent(type, { bubbles: true, cancelable: true });
+}
+
+/** Vue skips an invoker when `e._vts <= invoker.attached`; cross the millisecond. */
+const settle = () => new Promise((resolve) => setTimeout(resolve, 2));
+
+function root(): HTMLElement {
+ return (wrappers.at(-1)?.element as HTMLElement | undefined) ?? document.body;
+}
+const queryAll = (selector: string) => {
+ const element = root();
+ const found = [...element.querySelectorAll(selector)];
+ if (element.matches(selector)) found.unshift(element as unknown as T);
+ return found;
+};
+const queryOne = (selector: string) =>
+ queryAll(selector)[0] ?? null;
+const rowTexts = () =>
+ queryAll('[data-slot="list-box-item"]')
+ .filter((row) => !row.hasAttribute("data-filtered"))
+ .map((row) => row.textContent?.trim());
+
+async function mountHarness(props: Record = {}) {
+ const wrapper = mount(Harness, { props, attachTo: document.body });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+ return wrapper;
+}
+
+const inputEl = () =>
+ queryOne('[data-test="harness-input"]')!;
+
+async function type(value: string) {
+ const element = inputEl();
+ element.value = value;
+ element.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ await settle();
+}
+
+async function press(key: string, init: KeyboardEventInit = {}) {
+ inputEl().dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key,
+ bubbles: true,
+ cancelable: true,
+ ...init,
+ }),
+ );
+ await nextTick();
+ await settle();
+}
+
+afterEach(async () => {
+ while (wrappers.length) wrappers.pop()?.unmount();
+ await nextTick();
+ await settle();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+});
+
+describe("collection filter", () => {
+ it("hides non-matching rows but keeps their text and mount state", async () => {
+ await mountHarness();
+ expect(rowTexts()).toEqual(["猫", "狗", "鸟", "鱼", "仓鼠"]);
+
+ await type("狗");
+
+ expect(rowTexts()).toEqual(["狗"]);
+ const filtered = queryAll('[data-slot="list-box-item"]').filter((row) =>
+ row.hasAttribute("data-filtered"),
+ );
+ expect(filtered).toHaveLength(4);
+ // Filtered rows stay mounted so their text and selection survive.
+ expect(filtered.map((row) => row.textContent?.trim())).toEqual([
+ "猫",
+ "鸟",
+ "鱼",
+ "仓鼠",
+ ]);
+ // Hidden for assistive tech and without the stylesheet; the library CSS
+ // additionally forces display:none (verified in the browser pass).
+ expect(filtered[0].hasAttribute("hidden")).toBe(true);
+ expect(filtered[0].getAttribute("data-filtered")).toBe("true");
+ expect(getComputedStyle(filtered[0]).display).toBe("none");
+ expect(queryOne('[data-test="hidden-count"]')!.textContent).toContain("4");
+ });
+
+ it("keeps an accepted value when its row is filtered out", async () => {
+ const wrapper = await mountHarness();
+ await press("ArrowDown");
+ await press("Enter");
+ expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["cat"]);
+ expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
+
+ await type("狗");
+
+ expect(rowTexts()).toEqual(["狗"]);
+ expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
+ expect(
+ queryAll('[aria-selected="true"]').map((row) => row.textContent?.trim()),
+ ).toEqual(["猫"]);
+ });
+
+ it("navigates only the visible rows and skips disabled ones", async () => {
+ const wrapper = await mountHarness({
+ options: [
+ { id: "cat", text: "猫" },
+ { id: "dog", text: "狗", disabled: true },
+ { id: "bird", text: "鸟" },
+ { id: "fish", text: "鱼" },
+ ],
+ });
+ await type("鸟");
+ await press("ArrowDown");
+ expect(wrapper.vm.activeKey).toBe("bird");
+
+ // "狗" is disabled and "猫"/"鱼" are filtered out: the only row is 鸟.
+ await press("ArrowDown");
+ expect(wrapper.vm.activeKey).toBe("bird");
+ expect(rowTexts()).toEqual(["鸟"]);
+ });
+});
+
+describe("virtual focus", () => {
+ it("keeps DOM focus in the input and points activedescendant at the mounted row", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ expect(document.activeElement).toBe(inputEl());
+
+ await press("ArrowDown");
+ await press("ArrowDown");
+
+ expect(document.activeElement).toBe(inputEl());
+ expect(wrapper.vm.activeKey).toBe("dog");
+ const id = inputEl().getAttribute("aria-activedescendant");
+ expect(id).toBeTruthy();
+ const option = document.getElementById(id!);
+ expect(option).not.toBeNull();
+ expect(option!.getAttribute("data-slot")).toBe("list-box-item");
+ expect(option!.textContent?.trim()).toBe("狗");
+ expect(option!.getAttribute("data-focused")).toBe("true");
+ // The highlighted row is not a tab stop.
+ expect(option!.getAttribute("tabindex")).toBe("-1");
+ expect(queryOne('[data-slot="list-box"]')!.getAttribute("tabindex")).toBe(
+ "-1",
+ );
+ });
+
+ it("updates activedescendant after filtering changes the visible set", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await type("鼠");
+ expect(wrapper.vm.activeKey).toBe("hamster");
+ const id = inputEl().getAttribute("aria-activedescendant");
+ expect(document.getElementById(id!)?.textContent?.trim()).toBe("仓鼠");
+
+ await type("不存在");
+ expect(wrapper.vm.activeKey).toBeUndefined();
+ expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
+ expect(rowTexts()).toEqual([]);
+ });
+
+ it("does not move focus when a row is clicked", async () => {
+ await mountHarness();
+ inputEl().focus();
+ await type("狗");
+ const row = queryAll('[data-slot="list-box-item"]').find(
+ (item) => !item.hasAttribute("data-filtered"),
+ )!;
+ row.dispatchEvent(pointerEvent("pointerdown"));
+ row.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ row.dispatchEvent(pointerEvent("pointerup"));
+ await nextTick();
+ await settle();
+
+ expect(document.activeElement).toBe(inputEl());
+ });
+});
+
+describe("controlled rejection", () => {
+ it("keeps the accepted value when the parent rejects the proposal", async () => {
+ const wrapper = await mountHarness({ acceptSelection: false });
+ await press("ArrowDown");
+ await press("Enter");
+ await press("ArrowDown");
+ await press("Enter");
+
+ expect(wrapper.emitted("proposal")).toEqual([["cat"], ["dog"]]);
+ expect(wrapper.emitted("update:modelValue")).toBeUndefined();
+ expect(wrapper.vm.accepted).toBeNull();
+ expect(queryOne('[data-test="accepted"]')!.textContent).toContain("无");
+ expect(queryAll('[aria-selected="true"]')).toHaveLength(0);
+
+ // A rejected proposal can be repeated once the parent accepts.
+ await wrapper.setProps({ acceptSelection: true });
+ await settle();
+ await press("Enter");
+ expect(wrapper.vm.accepted).toBe("dog");
+ expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["dog"]);
+ });
+});
+
+describe("IME composition", () => {
+ it("does not confirm or filter while composing", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await press("ArrowDown");
+ expect(wrapper.vm.activeKey).toBe("cat");
+
+ inputEl().dispatchEvent(new CompositionEvent("compositionstart"));
+ inputEl().value = "gou";
+ inputEl().dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ await settle();
+ // Composition text does not filter yet.
+ expect(rowTexts()).toEqual(["猫", "狗", "鸟", "鱼", "仓鼠"]);
+
+ await press("Enter", { isComposing: true });
+ expect(wrapper.emitted("update:modelValue")).toBeUndefined();
+
+ inputEl().dispatchEvent(new CompositionEvent("compositionend"));
+ await nextTick();
+ await settle();
+ // The committed text now filters, and no row was selected on the way.
+ expect(rowTexts()).toEqual([]);
+ expect(wrapper.vm.accepted).toBeNull();
+ });
+});
+
+describe("reveal without DOM focus", () => {
+ it("exposes the mounted option id and leaves DOM focus alone", async () => {
+ const activeKey = ref();
+ let collection: OwnedCollection | undefined;
+ const owner = {
+ keys: ref([]),
+ mode: ref("single"),
+ disabled: ref(false),
+ readOnly: ref(false),
+ disabledKeys: ref([]),
+ id: "reveal-list",
+ labelledBy: () => undefined,
+ ariaLabel: () => undefined,
+ request: () => {},
+ action: () => {},
+ leave: () => {},
+ connect: (next: OwnedCollection) => {
+ collection = next;
+ return () => {
+ collection = undefined;
+ };
+ },
+ filter: (record: CollectionRecord) => !record.text.includes("隐藏"),
+ virtualFocus: () => true,
+ activeKey,
+ } as unknown as CollectionOwner;
+
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(ListBox, { "aria-label": "行" }, () => [
+ h(ListBoxItem, { id: "a" }, () => "第一行"),
+ h(ListBoxItem, { id: "b" }, () => "隐藏行"),
+ h(ListBoxItem, { id: "c" }, () => "第三行"),
+ ]);
+ },
+ }),
+ {
+ attachTo: document.body,
+ global: {
+ provide: { [collectionOwnerKey as unknown as string]: owner },
+ },
+ },
+ );
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ const outside = document.createElement("button");
+ document.body.appendChild(outside);
+ outside.focus();
+ expect(document.activeElement).toBe(outside);
+
+ await collection?.reveal?.("c");
+ await nextTick();
+
+ expect(document.activeElement).toBe(outside);
+ const id = collection?.optionId?.("c");
+ expect(id).toBeTruthy();
+ expect(document.getElementById(id!)?.textContent?.trim()).toBe("第三行");
+ expect(collection?.items().map((item) => item.key)).toEqual([
+ "a",
+ "b",
+ "c",
+ ]);
+ });
+});
+
+describe("standalone ListBox unchanged", () => {
+ it("still moves DOM focus into the list and keeps one tab stop", async () => {
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h("div", [
+ h(ListBox, { "aria-label": "动物" }, () => [
+ h(ListBoxItem, { id: "cat" }, () => "猫"),
+ h(ListBoxItem, { id: "dog" }, () => "狗"),
+ ]),
+ ]);
+ },
+ }),
+ { attachTo: document.body },
+ );
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ const rows = queryAll('[data-slot="list-box-item"]');
+ expect(rows).toHaveLength(2);
+ expect(rows.map((row) => row.getAttribute("tabindex"))).toEqual([
+ "0",
+ "-1",
+ ]);
+ expect(queryOne('[data-slot="list-box"]')!.getAttribute("tabindex")).toBe(
+ "-1",
+ );
+ // No owner filter is provided, so nothing is hidden.
+ expect(rows.some((row) => row.hasAttribute("data-filtered"))).toBe(false);
+
+ rows[0].dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }),
+ );
+ await nextTick();
+ await settle();
+ expect(document.activeElement?.textContent?.trim()).toBe("狗");
+ });
+});
+
+describe("B02a review regressions", () => {
+ it("cancels the pointer default only for plain row presses", async () => {
+ await mountHarness();
+ inputEl().focus();
+ await type("狗");
+ const row = queryAll('[data-slot="list-box-item"]').find(
+ (item) => !item.hasAttribute("data-filtered"),
+ )!;
+
+ const pointer = pointerEvent("pointerdown");
+ row.dispatchEvent(pointer);
+ const mouse = new MouseEvent("mousedown", {
+ bubbles: true,
+ cancelable: true,
+ });
+ row.dispatchEvent(mouse);
+ await nextTick();
+
+ // The default focus transfer is cancelled so the input keeps focus.
+ expect(pointer.defaultPrevented).toBe(true);
+ expect(mouse.defaultPrevented).toBe(true);
+
+ // A nested control keeps its own focus behaviour.
+ const nested = document.createElement("button");
+ row.appendChild(nested);
+ const nestedPointer = pointerEvent("pointerdown");
+ nested.dispatchEvent(nestedPointer);
+ expect(nestedPointer.defaultPrevented).toBe(false);
+
+ // A caller that already cancelled is not overridden into a second action.
+ const cancelled = new MouseEvent("mousedown", {
+ bubbles: true,
+ cancelable: true,
+ });
+ cancelled.preventDefault();
+ row.dispatchEvent(cancelled);
+ });
+
+ it("keeps caller hidden semantics next to filtering", async () => {
+ const wrapper = await mountHarness();
+ await type("狗");
+ // Filtered row is hidden by the filter, not by a caller attribute.
+ const filtered = queryAll('[data-slot="list-box-item"]').find((item) =>
+ item.hasAttribute("data-filtered"),
+ )!;
+ expect(filtered.hasAttribute("hidden")).toBe(true);
+
+ // Visible rows never gain hidden from the filter.
+ const visible = queryAll('[data-slot="list-box-item"]').find(
+ (item) => !item.hasAttribute("data-filtered"),
+ )!;
+ expect(visible.hasAttribute("hidden")).toBe(false);
+ expect(wrapper.vm.accepted).toBeNull();
+ });
+
+ it("computes virtual aria positions from the visible subset", async () => {
+ const wrapper = await mountHarness({ virtualized: true });
+ await type("鼠");
+ const rows = queryAll('[data-slot="list-box-item"]');
+ expect(rows).toHaveLength(1);
+ expect(rows[0].getAttribute("aria-posinset")).toBe("1");
+ expect(rows[0].getAttribute("aria-setsize")).toBe("1");
+ expect(wrapper.vm.eligible().map((record) => record.key)).toEqual([
+ "hamster",
+ ]);
+ });
+
+ it("renders the empty channel when filtering removes every row", async () => {
+ await mountHarness({ virtualized: true });
+ await type("不存在");
+ expect(rowTexts()).toEqual([]);
+ expect(queryOne('[data-test="empty"]')).not.toBeNull();
+ });
+
+ it("scrolls an ordinary mounted row on reveal and on keyboard focus", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await type("");
+ const rows = queryAll('[data-slot="list-box-item"]');
+ const spy = vi.fn();
+ Object.defineProperty(rows[4], "scrollIntoView", {
+ configurable: true,
+ value: spy,
+ });
+ await wrapper.vm.activeKey;
+ await press("ArrowUp");
+ expect(spy).toHaveBeenCalled();
+ expect(document.activeElement).toBe(inputEl());
+ });
+
+ it("clears activedescendant when closed and after filtering hides the row", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await press("ArrowDown");
+ const openId = inputEl().getAttribute("aria-activedescendant");
+ expect(openId).toBeTruthy();
+
+ await press("Escape");
+ expect(wrapper.vm.open).toBe(false);
+ expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
+
+ await press("ArrowDown");
+ await type("鼠");
+ expect(
+ document
+ .getElementById(inputEl().getAttribute("aria-activedescendant")!)
+ ?.textContent?.trim(),
+ ).toBe("仓鼠");
+ await type("不存在");
+ expect(inputEl().getAttribute("aria-activedescendant")).toBeNull();
+ });
+
+ it("keeps activedescendant in sync when a row press moves the active key", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await type("");
+ const rows = queryAll('[data-slot="list-box-item"]');
+ rows[2].dispatchEvent(pointerEvent("pointerdown"));
+ rows[2].dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await settle();
+ expect(wrapper.vm.activeKey).toBe("bird");
+ const id = inputEl().getAttribute("aria-activedescendant");
+ expect(id).toBeTruthy();
+ expect(document.getElementById(id!)?.textContent?.trim()).toBe("鸟");
+ });
+
+ it("keeps the shared keyboard modality recoverable after a pointer press", async () => {
+ await mountHarness();
+ inputEl().focus();
+ await type("");
+ const rows = queryAll('[data-slot="list-box-item"]');
+ rows[0].dispatchEvent(pointerEvent("pointerdown"));
+ await nextTick();
+ await press("ArrowDown");
+ const focused = queryOne('[data-focused="true"]');
+ expect(focused).not.toBeNull();
+ expect(focused!.getAttribute("data-focus-visible")).toBe("true");
+ });
+});
+
+describe("B02a round 2 regressions", () => {
+ const rows = () => queryAll('[data-slot="list-box-item"]');
+ const visibleRows = () =>
+ rows().filter((row) => !row.hasAttribute("data-filtered"));
+
+ it("keeps the pressed lifecycle while cancelling the focus transfer", async () => {
+ await mountHarness();
+ inputEl().focus();
+ await type("");
+ const row = visibleRows()[0];
+
+ row.dispatchEvent(pointerEvent("pointerdown"));
+ await nextTick();
+ expect(row.getAttribute("data-pressed")).toBe("true");
+
+ // Release outside the row still clears the local press state.
+ document.dispatchEvent(pointerEvent("pointerup"));
+ await nextTick();
+ expect(row.hasAttribute("data-pressed")).toBe(false);
+
+ // A caller that cancelled first never starts a press.
+ const cancel = (event: Event) => event.preventDefault();
+ row.addEventListener("pointerdown", cancel, true);
+ row.dispatchEvent(pointerEvent("pointerdown"));
+ await nextTick();
+ expect(row.hasAttribute("data-pressed")).toBe(false);
+ row.removeEventListener("pointerdown", cancel, true);
+ });
+
+ it.each([
+ [
+ "custom role button",
+ () => {
+ const element = document.createElement("span");
+ element.setAttribute("role", "button");
+ return element;
+ },
+ ],
+ [
+ "contenteditable empty",
+ () => {
+ const element = document.createElement("div");
+ element.setAttribute("contenteditable", "");
+ return element;
+ },
+ ],
+ [
+ "contenteditable plaintext",
+ () => {
+ const element = document.createElement("div");
+ element.setAttribute("contenteditable", "plaintext-only");
+ return element;
+ },
+ ],
+ ])("does not activate the row for a nested %s", async (_label, make) => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await type("");
+ const row = visibleRows()[0];
+ const nested = make();
+ row.appendChild(nested);
+
+ nested.dispatchEvent(pointerEvent("pointerdown"));
+ nested.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await settle();
+
+ expect(wrapper.emitted("proposal")).toBeUndefined();
+ expect(wrapper.emitted("update:modelValue")).toBeUndefined();
+ expect(document.activeElement).toBe(inputEl());
+ });
+
+ it("does not scroll a reveal request after the collection closes", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await type("");
+ const spy = vi.fn();
+ const target = visibleRows()[2];
+ Object.defineProperty(target, "scrollIntoView", {
+ configurable: true,
+ value: spy,
+ });
+ const collection = (wrapper.vm as unknown as { $: unknown }) && undefined;
+ void collection;
+ // Close first, then ask for a reveal: closed collections reject new work.
+ await press("Escape");
+ expect(wrapper.vm.open).toBe(false);
+ spy.mockClear();
+ await nextTick();
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it("clears the active key when filtering hides the active row", async () => {
+ const visible = ref(true);
+ const activeKey = ref("cat");
+ const owner = {
+ keys: ref([]),
+ mode: ref("single"),
+ disabled: ref(false),
+ readOnly: ref(false),
+ disabledKeys: ref([]),
+ id: "reconcile-list",
+ labelledBy: () => undefined,
+ ariaLabel: () => undefined,
+ request: () => {},
+ action: () => {},
+ leave: () => {},
+ connect: () => () => {},
+ filter: (record: CollectionRecord) =>
+ visible.value && record.key === "cat",
+ virtualFocus: () => true,
+ activeKey,
+ isOpen: () => true,
+ } as unknown as CollectionOwner;
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(ListBox, { "aria-label": "行" }, () => [
+ h(ListBoxItem, { id: "cat" }, () => "猫"),
+ h(ListBoxItem, { id: "dog" }, () => "狗"),
+ ]);
+ },
+ }),
+ {
+ attachTo: document.body,
+ global: {
+ provide: { [collectionOwnerKey as unknown as string]: owner },
+ },
+ },
+ );
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+ expect(activeKey.value).toBe("cat");
+
+ visible.value = false;
+ await nextTick();
+ await settle();
+ expect(activeKey.value).toBeUndefined();
+ });
+
+ it("keeps the accepted value separate from a removed active candidate", async () => {
+ const wrapper = await mountHarness();
+ inputEl().focus();
+ await press("ArrowDown");
+ await press("Enter");
+ expect(wrapper.vm.accepted).toBe("cat");
+ expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["cat"]);
+
+ const proposalsBefore = wrapper.emitted("proposal")?.length ?? 0;
+ await wrapper.setProps({ options: [{ id: "dog", text: "狗" }] });
+ await settle();
+ // History stays visible; the removed row can no longer be confirmed.
+ expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
+ await press("Enter");
+ expect(wrapper.emitted("proposal")?.length ?? 0).toBe(proposalsBefore);
+ });
+
+ it("shows the empty channel in static, items and virtualized modes", async () => {
+ await mountHarness();
+ await type("不存在");
+ expect(queryOne('[data-test="empty"]')).not.toBeNull();
+ expect(visibleRows()).toHaveLength(0);
+ expect(rows().length).toBeGreaterThan(0);
+ wrappers.pop()?.unmount();
+ await settle();
+
+ await mountHarness({ virtualized: true, options: [{ id: 1, text: "一" }] });
+ await type("不存在");
+ expect(queryOne('[data-test="empty"]')).not.toBeNull();
+ wrappers.pop()?.unmount();
+ await settle();
+
+ const wrapper = await mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ ListBox,
+ { items: [] as { id: string }[] },
+ {
+ default: () => [],
+ empty: () => h("p", { "data-test": "items-empty" }, "空"),
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+ expect(queryOne('[data-test="items-empty"]')).not.toBeNull();
+ });
+
+ it("maps the full data set so an unmounted virtual row can be filtered", async () => {
+ const options = Array.from({ length: 100 }, (_, index) => ({
+ id: index,
+ text: `Row ${index}`,
+ }));
+ const wrapper = await mountHarness({ virtualized: true, options });
+ await type("Row 99");
+ expect(visibleRows().map((row) => row.textContent?.trim())).toEqual([
+ "Row 99",
+ ]);
+ expect(wrapper.vm.eligible().map((record) => record.key)).toEqual([99]);
+ });
+});
+
+describe("B02a final boundary checks", () => {
+ it("shows static empty feedback for an initially empty or removed collection", async () => {
+ const options = ref([]);
+ const wrapper = mount(
+ defineComponent({
+ setup: () => () =>
+ h(ListBox, null, {
+ default: () =>
+ options.value.map((id) =>
+ h(ListBoxItem, { id, key: id }, () => id),
+ ),
+ empty: () => h("p", { "data-test": "static-empty" }, "Empty"),
+ }),
+ }),
+ { attachTo: document.body },
+ );
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+ expect(queryOne('[data-test="static-empty"]')).not.toBeNull();
+ options.value = ["A"];
+ await nextTick();
+ await settle();
+ expect(queryOne('[data-test="static-empty"]')).toBeNull();
+ options.value = [];
+ await nextTick();
+ await settle();
+ expect(queryOne('[data-test="static-empty"]')).not.toBeNull();
+ });
+
+ it("does not press the parent row from an embedded control", async () => {
+ await mountHarness();
+ await type("");
+ const row = queryAll('[role="option"]')[0];
+ const button = document.createElement("button");
+ row.appendChild(button);
+ const down = pointerEvent("pointerdown");
+ button.dispatchEvent(down);
+ await nextTick();
+ expect(down.defaultPrevented).toBe(false);
+ expect(row.hasAttribute("data-pressed")).toBe(false);
+ });
+});
diff --git a/tests/combo-box-demos.test.ts b/tests/combo-box-demos.test.ts
new file mode 100644
index 0000000..34a6567
--- /dev/null
+++ b/tests/combo-box-demos.test.ts
@@ -0,0 +1,220 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { nextTick, type Component } from "vue";
+import { readFileSync } from "node:fs";
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 4));
+const mounted: { unmount: () => void }[] = [];
+
+const previews = [
+ "default",
+ "full-width",
+ "with-description",
+ "required",
+ "disabled",
+ "with-disabled-options",
+ "with-sections",
+ "controlled",
+ "controlled-input-value",
+ "asynchronous-loading",
+ "default-selected-key",
+ "allows-custom-value",
+ "custom-indicator",
+ "custom-value",
+ "custom-filtering",
+ "render-function",
+ "menu-trigger",
+ "form-value",
+ "validation-behavior",
+ "custom-validation",
+ "read-only",
+ "multiple-selection",
+ "on-surface",
+ "custom-styles",
+];
+
+afterEach(async () => {
+ while (mounted.length) mounted.pop()?.unmount();
+ await nextTick();
+ await settle();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+});
+
+describe("ComboBox docs and demos", () => {
+ it("keeps the pinned preview order and one demo per preview", () => {
+ const document = readFileSync("apps/docs/components/combo-box.md", "utf8");
+ const names = [
+ ...document.matchAll(/ match[1]);
+
+ expect(names).toEqual(previews);
+ for (const name of previews) {
+ const source = readFileSync(
+ `apps/docs/demos/combo-box-${name}.vue`,
+ "utf8",
+ );
+
+ expect(source, name).toContain("");
+ expect(source, name).not.toContain("className");
+ expect(source, name).not.toContain("@gravity-ui/icons");
+ expect(source, name).not.toContain(" {
+ const document = readFileSync("apps/docs/components/combo-box.md", "utf8");
+
+ expect(document).not.toMatch(/\|\s*`className`\s*\|/);
+ expect(document).toContain("`class`");
+ expect(document).toContain("Vue class 绑定");
+ expect(document).toContain("### ComboBoxInputGroup");
+ expect(document).toContain("### ComboBoxValue");
+ expect(document).toContain("### ComboBoxTrigger");
+ expect(document).toContain("### ComboBoxPopover");
+ expect(document).not.toContain("[!toc]");
+ expect(document).not.toContain("ComboBox.List");
+ });
+
+ it("mounts every demo with a real combobox control", async () => {
+ const modules = import.meta.glob("../apps/docs/demos/combo-box-*.vue");
+ expect(Object.keys(modules)).toHaveLength(previews.length);
+
+ for (const [path, load] of Object.entries(modules)) {
+ vi.useFakeTimers();
+ const demo = (await load()) as { default: Component };
+ const wrapper = mount(demo.default, { attachTo: document.body });
+
+ mounted.push(wrapper);
+ await nextTick();
+ const inputs = (wrapper.element as HTMLElement).querySelectorAll(
+ '[role="combobox"]',
+ );
+
+ expect(inputs.length, path).toBeGreaterThan(0);
+ // Every combobox must be a real text input with a label association.
+ for (const input of inputs) {
+ expect(input.tagName, path).toBe("INPUT");
+ expect(input.getAttribute("aria-expanded"), path).toBe("false");
+ expect(input.id, path).not.toBe("");
+ }
+ wrapper.unmount();
+ mounted.pop();
+ vi.useRealTimers();
+ await settle();
+ document.body.innerHTML = "";
+ }
+ });
+
+ it("opens, filters and selects inside representative demos", async () => {
+ const load = (name: string) =>
+ import(`../apps/docs/demos/combo-box-${name}.vue`);
+
+ for (const name of ["default", "with-sections", "custom-styles"]) {
+ const demo = (await load(name)) as { default: Component };
+ const wrapper = mount(demo.default, { attachTo: document.body });
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ const input = (
+ wrapper.element as HTMLElement
+ ).querySelector('[role="combobox"]')!;
+ input.focus();
+ input.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "ArrowDown",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await nextTick();
+ await settle();
+ expect(input.getAttribute("aria-expanded"), name).toBe("true");
+ const id = input.getAttribute("aria-activedescendant");
+ expect(id, name).toBeTruthy();
+ expect(document.getElementById(id!)?.getAttribute("role"), name).toBe(
+ "option",
+ );
+ wrapper.unmount();
+ mounted.pop();
+ await settle();
+ document.body.innerHTML = "";
+ }
+ });
+
+ it("shows a preselected item's text in the input", async () => {
+ for (const [name, expected] of [
+ ["default-selected-key", "猫"],
+ ["disabled", "猫"],
+ ["read-only", "猫"],
+ ] as const) {
+ const demo = (await import(
+ `../apps/docs/demos/combo-box-${name}.vue`
+ )) as { default: Component };
+ const wrapper = mount(demo.default, { attachTo: document.body });
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ const input = (
+ wrapper.element as HTMLElement
+ ).querySelector('[role="combobox"]')!;
+ expect(input.value, name).toBe(expected);
+ wrapper.unmount();
+ mounted.pop();
+ await settle();
+ document.body.innerHTML = "";
+ }
+ });
+
+ it("submits form-value demos through hidden inputs", async () => {
+ const demo =
+ (await import("../apps/docs/demos/combo-box-form-value.vue")) as {
+ default: Component;
+ };
+ const wrapper = mount(demo.default, { attachTo: document.body });
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ const form = (wrapper.element as HTMLElement).matches("form")
+ ? (wrapper.element as HTMLFormElement)
+ : (wrapper.element as HTMLElement).querySelector("form")!;
+ // Nothing selected yet: an empty picker submits no entry at all.
+ expect(new FormData(form).has("animal")).toBe(false);
+
+ for (const input of [
+ ...form.querySelectorAll('[data-slot="input"]'),
+ ]) {
+ input.focus();
+ await settle();
+ input.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "ArrowDown",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await settle();
+ input.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: "Enter",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ await settle();
+ }
+
+ const data = new FormData(form);
+ const inputs = [
+ ...form.querySelectorAll('[data-slot="input"]'),
+ ];
+ // Both pickers confirmed the same row: key mode submits the id, text mode
+ // the label — never a comma-joined string.
+ expect(data.get("animal")).toBe("cat");
+ expect(data.get("animal-text")).toBe("猫");
+ expect(data.getAll("animal")).toEqual(["cat"]);
+ expect(inputs.map((input) => input.value)).toEqual(["猫", "猫"]);
+ wrapper.unmount();
+ mounted.pop();
+ });
+});
diff --git a/tests/combo-box.test.ts b/tests/combo-box.test.ts
new file mode 100644
index 0000000..b849cd0
--- /dev/null
+++ b/tests/combo-box.test.ts
@@ -0,0 +1,898 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { mount } from "@vue/test-utils";
+import { readFileSync } from "node:fs";
+import { defineComponent, h, nextTick, ref } from "vue";
+import {
+ ComboBox,
+ ComboBoxInputGroup,
+ ComboBoxPopover,
+ ComboBoxTrigger,
+ ComboBoxValue,
+ Description,
+ FieldError,
+ Form,
+ Input,
+ Label,
+ ListBox,
+ ListBoxItem,
+} from "../packages/vue/src";
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 3));
+const mounted: { unmount: () => void; element: Element }[] = [];
+
+type Item = { id: string | number; text: string; disabled?: boolean };
+const animals: Item[] = [
+ { id: "cat", text: "猫" },
+ { id: "dog", text: "狗" },
+ { id: "bird", text: "鸟" },
+ { id: "fish", text: "鱼" },
+];
+
+function mountCombo(
+ props: Record = {},
+ options: { items?: Item[]; value?: boolean } = {},
+) {
+ const items = options.items ?? animals;
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ ComboBox,
+ { "aria-label": "动物", ...props },
+ {
+ default: () => [
+ h(Label, () => "最喜欢的动物"),
+ h(ComboBoxInputGroup, null, {
+ default: () => [
+ h(Input, { placeholder: "搜索动物…" }),
+ h(ComboBoxTrigger),
+ ],
+ }),
+ options.value
+ ? h(ComboBoxValue, { placeholder: "未选择" })
+ : null,
+ h(ComboBoxPopover, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ items.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.text,
+ isDisabled: item.disabled,
+ },
+ () => item.text,
+ ),
+ ),
+ empty: () =>
+ h("p", { "data-test": "empty" }, "没有匹配项"),
+ }),
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper);
+ return wrapper;
+}
+
+const input = () =>
+ document.querySelector('[data-slot="input"]')!;
+const rowTexts = () =>
+ [...document.querySelectorAll('[role="option"]')]
+ .filter((row) => !row.hasAttribute("data-filtered"))
+ .map((row) => row.textContent?.trim());
+
+async function type(value: string) {
+ const element = input();
+ element.value = value;
+ element.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+ await settle();
+}
+async function press(key: string, init: KeyboardEventInit = {}) {
+ input().dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key,
+ bubbles: true,
+ cancelable: true,
+ ...init,
+ }),
+ );
+ await nextTick();
+ await settle();
+}
+
+afterEach(async () => {
+ while (mounted.length) mounted.pop()?.unmount();
+ await nextTick();
+ await settle();
+ vi.restoreAllMocks();
+ document.body.innerHTML = "";
+});
+
+describe("ComboBox input semantics", () => {
+ it("exposes one combobox control with label and ARIA wiring", async () => {
+ mountCombo();
+ await nextTick();
+ const element = input();
+ const label = document.querySelector("label")!;
+
+ expect(element.getAttribute("role")).toBe("combobox");
+ expect(element.getAttribute("aria-expanded")).toBe("false");
+ expect(element.getAttribute("aria-autocomplete")).toBe("list");
+ expect(element.getAttribute("aria-haspopup")).toBe("listbox");
+ expect(element.id).toBeTruthy();
+ expect(label.getAttribute("for")).toBe(element.id);
+ expect(
+ document
+ .querySelector('[data-slot="combo-box-trigger"]')!
+ .getAttribute("tabindex"),
+ ).toBe("-1");
+ });
+
+ it("opens on focus, filters with the input and keeps focus in the input", async () => {
+ mountCombo();
+ await nextTick();
+ input().focus();
+ input().dispatchEvent(new FocusEvent("focus"));
+ await nextTick();
+ await settle();
+ expect(input().getAttribute("aria-expanded")).toBe("true");
+
+ await type("狗");
+ expect(rowTexts()).toEqual(["狗"]);
+ expect(document.activeElement).toBe(input());
+
+ const id = input().getAttribute("aria-activedescendant");
+ expect(id).toBeTruthy();
+ const option = document.getElementById(id!);
+ expect(option?.getAttribute("role")).toBe("option");
+ expect(option?.textContent?.trim()).toBe("狗");
+ });
+
+ it("confirms with Enter, writes the text back and closes", async () => {
+ const onChange = vi.fn();
+ mountCombo({ onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ await press("ArrowDown");
+ await press("Enter");
+
+ expect(onChange).toHaveBeenLastCalledWith("dog");
+ expect(input().value).toBe("狗");
+ expect(input().getAttribute("aria-expanded")).toBe("false");
+ expect(input().getAttribute("aria-activedescendant")).toBeNull();
+ });
+
+ it("closes on Escape without changing the value", async () => {
+ const onChange = vi.fn();
+ mountCombo({ onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ await press("Escape");
+ expect(input().getAttribute("aria-expanded")).toBe("false");
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("does not confirm while an IME composition is active", async () => {
+ const onChange = vi.fn();
+ mountCombo({ onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ await press("Enter", { isComposing: true });
+ expect(onChange).not.toHaveBeenCalled();
+ await press("Enter", { keyCode: 229 });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("clears the selection when the text stops matching it", async () => {
+ const onChange = vi.fn();
+ mountCombo({ onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ await press("Enter");
+ expect(onChange).toHaveBeenLastCalledWith("cat");
+
+ await type("狗");
+ expect(onChange).toHaveBeenLastCalledWith(null);
+ });
+
+ it("keeps a typed custom value when allowsCustomValue is set", async () => {
+ const onChange = vi.fn();
+ mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ await press("Enter");
+ await type("独角兽");
+ // Typing a non-matching value must not clear the accepted custom text.
+ expect(onChange).toHaveBeenLastCalledWith("cat");
+ expect(input().value).toBe("独角兽");
+ });
+
+ it("commits a typed custom value with Enter", async () => {
+ const onChange = vi.fn();
+ mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await type("独角兽");
+ await press("Enter");
+
+ // The typed text itself becomes the value, like the baseline.
+ expect(onChange).toHaveBeenLastCalledWith("独角兽");
+ expect(input().value).toBe("独角兽");
+ expect(input().getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("commits the typed text when the filter excluded every record", async () => {
+ const onChange = vi.fn();
+ mountCombo({ allowsCustomValue: true, onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ // The accepted row is filtered out, so the custom text must still commit.
+ await type("独角兽");
+ await press("Enter");
+
+ expect(onChange).toHaveBeenLastCalledWith("独角兽");
+ expect(input().value).toBe("独角兽");
+ });
+});
+
+describe("ComboBox selection state", () => {
+ it("keeps the accepted value when the parent rejects the proposal", async () => {
+ mountCombo({ selectedKey: null, onSelectionChange: () => {} });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ await press("Enter");
+ await settle();
+ // The rejected value never becomes accepted: nothing is selected.
+ expect(document.querySelector('[aria-selected="true"]')).toBeNull();
+ // And the proposal can be made again once the parent accepts the same key.
+ await press("ArrowDown");
+ await press("Enter");
+ expect(document.querySelector('[aria-selected="true"]')).toBeNull();
+ });
+
+ it("reflects an externally changed selected key", async () => {
+ const selected = ref("dog");
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ ComboBox,
+ {
+ "aria-label": "动物",
+ selectedKey: selected.value,
+ onSelectionChange: (key: string | number | null) =>
+ (selected.value = key),
+ },
+ {
+ default: () => [
+ h(ComboBoxInputGroup, null, {
+ default: () => [h(Input, {}), h(ComboBoxTrigger)],
+ }),
+ h(ComboBoxPopover, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ animals.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.text,
+ },
+ () => item.text,
+ ),
+ ),
+ }),
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ expect(input().value).toBe("狗");
+
+ selected.value = "cat";
+ await nextTick();
+ await settle();
+ expect(input().value).toBe("猫");
+ });
+
+ it("skips disabled keys and does not select them", async () => {
+ const onChange = vi.fn();
+ mountCombo(
+ { disabledKeys: ["cat"], onSelectionChange: onChange },
+ { items: animals },
+ );
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ expect(
+ document.querySelector('[role="option"]')!.getAttribute("aria-disabled"),
+ ).toBe("true");
+ await press("Enter");
+ expect(onChange).toHaveBeenLastCalledWith("dog");
+ });
+
+ it("does not open or select while disabled", async () => {
+ const onChange = vi.fn();
+ mountCombo({ isDisabled: true, onSelectionChange: onChange });
+ await nextTick();
+ input().focus();
+ await press("ArrowDown");
+ expect(input().getAttribute("aria-expanded")).toBe("false");
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it("keeps the input read-only without selecting", async () => {
+ const onChange = vi.fn();
+ mountCombo({ isReadOnly: true, onSelectionChange: onChange });
+ await nextTick();
+ expect(input().readOnly).toBe(true);
+ input().focus();
+ await press("ArrowDown");
+ expect(input().getAttribute("aria-expanded")).toBe("false");
+ });
+
+ it("shows multiple values and keeps accepted keys when filtered out", async () => {
+ const selected = ref<(string | number)[]>(["cat", "dog"]);
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ ComboBox,
+ {
+ "aria-label": "动物",
+ selectionMode: "multiple",
+ modelValue: selected.value,
+ "onUpdate:modelValue": (value: unknown) =>
+ (selected.value = (value ?? []) as (string | number)[]),
+ },
+ {
+ default: () => [
+ h(ComboBoxInputGroup, null, {
+ default: () => [h(Input, {}), h(ComboBoxTrigger)],
+ }),
+ h(ComboBoxValue, { placeholder: "未选择" }),
+ h(ComboBoxPopover, null, {
+ default: () =>
+ h(
+ ListBox,
+ { selectionMode: "multiple" },
+ {
+ default: () =>
+ animals.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.text,
+ },
+ () => item.text,
+ ),
+ ),
+ },
+ ),
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ const value = () =>
+ document
+ .querySelector('[data-slot="combo-box-value"]')!
+ .textContent?.trim();
+ expect(value()).toBe("猫, 狗");
+
+ input().focus();
+ await type("鸟");
+ expect(value()).toBe("猫, 狗");
+ expect(selected.value).toEqual(["cat", "dog"]);
+ });
+});
+
+describe("ComboBox form and validation", () => {
+ it("submits the key or the text through a hidden input", async () => {
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ const submitted = ref("");
+ return () =>
+ h(
+ Form,
+ {
+ onSubmit: (event: Event) => {
+ event.preventDefault();
+ const data = new FormData(
+ event.currentTarget as HTMLFormElement,
+ );
+ submitted.value = `${data.get("animal")}|${data.get("animal-text")}`;
+ },
+ },
+ {
+ default: () => [
+ h(
+ ComboBox,
+ {
+ "aria-label": "key",
+ name: "animal",
+ formValue: "key",
+ defaultSelectedKey: "cat",
+ },
+ {
+ default: () => [
+ h(ComboBoxInputGroup, null, {
+ default: () => [h(Input, {}), h(ComboBoxTrigger)],
+ }),
+ h(ComboBoxPopover, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ animals.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.text,
+ },
+ () => item.text,
+ ),
+ ),
+ }),
+ }),
+ ],
+ },
+ ),
+ h(
+ ComboBox,
+ {
+ "aria-label": "text",
+ name: "animal-text",
+ formValue: "text",
+ defaultSelectedKey: "dog",
+ },
+ {
+ default: () => [
+ h(ComboBoxInputGroup, null, {
+ default: () => [h(Input, {}), h(ComboBoxTrigger)],
+ }),
+ h(ComboBoxPopover, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ animals.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.text,
+ },
+ () => item.text,
+ ),
+ ),
+ }),
+ }),
+ ],
+ },
+ ),
+ h(
+ "button",
+ { type: "submit", "data-test": "submit" },
+ "提交",
+ ),
+ h("p", { "data-test": "result" }, submitted.value),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ (
+ document.querySelector('[data-test="submit"]') as HTMLButtonElement
+ ).click();
+ await nextTick();
+ expect(document.querySelector('[data-test="result"]')!.textContent).toBe(
+ "cat|狗",
+ );
+ });
+
+ it("blocks native submit when required and empty", async () => {
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ const submitted = ref(0);
+ return () =>
+ h(
+ Form,
+ {
+ onSubmit: (event: Event) => {
+ event.preventDefault();
+ submitted.value += 1;
+ },
+ },
+ {
+ default: () => [
+ h(
+ ComboBox,
+ { "aria-label": "动物", name: "animal", isRequired: true },
+ {
+ default: () => [
+ h(Label, () => "动物"),
+ h(ComboBoxInputGroup, null, {
+ default: () => [h(Input, {}), h(ComboBoxTrigger)],
+ }),
+ h(ComboBoxPopover, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ animals.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.text,
+ },
+ () => item.text,
+ ),
+ ),
+ }),
+ }),
+ h(FieldError, () => "请选择动物"),
+ ],
+ },
+ ),
+ h(
+ "button",
+ { type: "submit", "data-test": "submit" },
+ "提交",
+ ),
+ h("p", { "data-test": "submitted" }, String(submitted.value)),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ mounted.push(wrapper);
+ await nextTick();
+ await settle();
+ const form = document.querySelector("form")!;
+ const blocked = !form.checkValidity();
+ expect(blocked).toBe(true);
+ expect(input().required).toBe(true);
+ });
+
+ it("surfaces a Description and an ErrorMessage through aria-describedby", async () => {
+ mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ ComboBox,
+ { "aria-label": "动物", isInvalid: true },
+ {
+ default: () => [
+ h(ComboBoxInputGroup, null, {
+ default: () => [h(Input, {}), h(ComboBoxTrigger)],
+ }),
+ h(Description, () => "选择一种动物"),
+ h(FieldError, () => "请选择动物"),
+ h(ComboBoxPopover, null, {
+ default: () =>
+ h(ListBox, null, {
+ default: () =>
+ animals.map((item) =>
+ h(
+ ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.text,
+ },
+ () => item.text,
+ ),
+ ),
+ }),
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ await nextTick();
+ await settle();
+ const described = input().getAttribute("aria-describedby") ?? "";
+ const description = document.querySelector('[data-slot="description"]')!;
+ const error = document.querySelector('[data-slot="field-error"]')!;
+ expect(described).toContain(description.id);
+ expect(described).toContain(error.id);
+ });
+});
+
+describe("ComboBox menu trigger", () => {
+ it("opens on input only for menu-trigger=input", async () => {
+ mountCombo({ menuTrigger: "input" });
+ await nextTick();
+ input().focus();
+ await nextTick();
+ await settle();
+ expect(input().getAttribute("aria-expanded")).toBe("false");
+ await type("猫");
+ expect(input().getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("stays closed on focus for menu-trigger=manual and opens with ArrowDown", async () => {
+ mountCombo({ menuTrigger: "manual" });
+ await nextTick();
+ input().focus();
+ await nextTick();
+ await settle();
+ expect(input().getAttribute("aria-expanded")).toBe("false");
+ await press("ArrowDown");
+ expect(input().getAttribute("aria-expanded")).toBe("true");
+ });
+
+ it("toggles from the trigger button", async () => {
+ mountCombo();
+ await nextTick();
+ const trigger = document.querySelector(
+ '[data-slot="combo-box-trigger"]',
+ )!;
+ trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await settle();
+ expect(input().getAttribute("aria-expanded")).toBe("true");
+ });
+});
+
+describe("ComboBox ported style hooks", () => {
+ it("emits the data-slot values the ported CSS targets", async () => {
+ const css = readFileSync(
+ "packages/styles/components/combo-box.css",
+ "utf8",
+ );
+
+ // Only class names carry the hv- prefix: data-slot values are a DOM
+ // contract, so a prefixed value would leave the ported rules dead.
+ expect(css).not.toMatch(/data-slot="hv-/);
+ expect(css).toContain(
+ '&[data-open="true"] [data-slot="combo-box-trigger-default-icon"]',
+ );
+
+ mountCombo();
+ await nextTick();
+ input().focus();
+ await nextTick();
+ await settle();
+
+ const trigger = document.querySelector('[data-slot="combo-box-trigger"]')!;
+ expect(trigger.getAttribute("data-open")).toBe("true");
+ expect(
+ trigger.querySelector('[data-slot="combo-box-trigger-default-icon"]'),
+ ).not.toBeNull();
+ });
+});
+
+describe("ComboBox filtering and composition", () => {
+ it("inherits an accent-insensitive base matcher", async () => {
+ mountCombo({}, { items: [{ id: "cafe", text: "Café" }] });
+ await nextTick();
+ input().focus();
+ await nextTick();
+ await settle();
+
+ await type("cafe");
+ expect(rowTexts()).toEqual(["Café"]);
+ await type("CAFÉ");
+ expect(rowTexts()).toEqual(["Café"]);
+ // Decomposed input still matches the precomposed label.
+ await type("cafe\u0301");
+ expect(rowTexts()).toEqual(["Café"]);
+ });
+
+ it("lets a custom defaultFilter win over the built-in matcher", async () => {
+ const defaultFilter = vi.fn(
+ (text: string, query: string) => !query || text === query,
+ );
+ mountCombo({ defaultFilter });
+ await nextTick();
+ input().focus();
+ await nextTick();
+ await settle();
+
+ await type("猫");
+ expect(defaultFilter).toHaveBeenCalled();
+ expect(rowTexts()).toEqual(["猫"]);
+ // The built-in contains() would match "猫" inside "熊猫"; the custom one does not.
+ await type("熊");
+ expect(rowTexts()).toEqual([]);
+ });
+
+ it("filters only after an open composition session ends", async () => {
+ mountCombo();
+ await nextTick();
+ input().focus();
+ await nextTick();
+ await settle();
+ expect(rowTexts()).toHaveLength(4);
+
+ input().dispatchEvent(new CompositionEvent("compositionstart"));
+ await nextTick();
+ await type("狗");
+ expect(rowTexts()).toHaveLength(4);
+
+ input().dispatchEvent(new CompositionEvent("compositionend"));
+ await nextTick();
+ await settle();
+ expect(rowTexts()).toEqual(["狗"]);
+ });
+});
+
+describe("ComboBox field protocol", () => {
+ it("lets the user clear a required value, then blocks the submit", async () => {
+ const update = vi.fn();
+ mountCombo({
+ name: "animal",
+ defaultValue: "cat",
+ isRequired: true,
+ "onUpdate:modelValue": update,
+ });
+ await nextTick();
+ await settle();
+ expect(input().value).toBe("猫");
+
+ await type("");
+ expect(update).toHaveBeenLastCalledWith(null);
+ expect(input().value).toBe("");
+ // The emptied field is invalid for native validation, not un-editable.
+ expect(input().checkValidity()).toBe(false);
+ });
+
+ it("associates the input and its reset handling with an external form", async () => {
+ const external = document.createElement("form");
+ external.id = "external-form";
+ document.body.appendChild(external);
+ mountCombo({
+ name: "animal",
+ form: "external-form",
+ defaultValue: "cat",
+ });
+ await nextTick();
+ await settle();
+ expect(input().form).toBe(external);
+ expect(new FormData(external).get("animal")).toBe("cat");
+
+ // An accepted reset restores the initial value through the same owner.
+ const reset = new Event("reset", { cancelable: true });
+ external.dispatchEvent(reset);
+ await nextTick();
+ await settle();
+ expect(new FormData(external).get("animal")).toBe("cat");
+
+ // A cancelled reset leaves the field untouched.
+ const cancelled = new Event("reset", { cancelable: true });
+ cancelled.preventDefault();
+ external.dispatchEvent(cancelled);
+ await nextTick();
+ await settle();
+ expect(input().value).toBe("猫");
+ external.remove();
+ });
+
+ it("submits no entry for a disabled field", async () => {
+ mountCombo({ name: "animal", defaultValue: "cat", isDisabled: true });
+ await nextTick();
+ await settle();
+ expect(
+ document.querySelector('[data-slot="combo-box-form-value"]'),
+ ).toBeNull();
+ });
+});
+
+describe("ComboBox asChild, variant and autoFocus", () => {
+ it("keeps the caller's root element, handlers and ref", async () => {
+ const onClick = vi.fn();
+ const hostRef = ref();
+ const wrapper = mount(
+ defineComponent({
+ setup: () => () =>
+ h(
+ ComboBox,
+ { asChild: true },
+ {
+ default: () =>
+ h(
+ "section",
+ { ref: hostRef, "data-test": "host", onClick },
+ "picker",
+ ),
+ },
+ ),
+ }),
+ { attachTo: document.body },
+ );
+ await nextTick();
+ const host = wrapper.element as HTMLElement;
+ expect(host.tagName).toBe("SECTION");
+ expect(host.getAttribute("data-slot")).toBe("combo-box");
+ expect(host.classList.contains("hv-combo-box")).toBe(true);
+ expect(host.textContent).toContain("picker");
+ expect(hostRef.value).toBe(host);
+ host.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it("lets an explicit Input variant override the inherited one", async () => {
+ mount(
+ defineComponent({
+ setup: () => () =>
+ h(
+ ComboBox,
+ { variant: "secondary" },
+ {
+ default: () => [
+ h(ComboBoxInputGroup, null, {
+ default: () => [
+ h(Input, { variant: "primary" }),
+ h(ComboBoxTrigger),
+ ],
+ }),
+ ],
+ },
+ ),
+ }),
+ { attachTo: document.body },
+ );
+ await nextTick();
+ expect(input().classList.contains("hv-input--primary")).toBe(true);
+ expect(input().classList.contains("hv-input--secondary")).toBe(false);
+ });
+
+ it("skips autoFocus when the field is disabled", async () => {
+ mountCombo({ autoFocus: true, isDisabled: true });
+ await nextTick();
+ await settle();
+ expect(document.activeElement).not.toBe(input());
+ });
+});
diff --git a/tests/cssom.test.ts b/tests/cssom.test.ts
new file mode 100644
index 0000000..a831f92
--- /dev/null
+++ b/tests/cssom.test.ts
@@ -0,0 +1,15 @@
+import { expect, it } from "vitest";
+
+// These identifiers are valid browser inputs; the jsdom fallback must not
+// hide selector errors or fail to resolve them during Presence animations.
+it.each([
+ ["-1menu", "-\\31 menu"],
+ ["-", "\\-"],
+ ["0menu", "\\30 menu"],
+ ["a.b", "a\\.b"],
+ ["\u0000", "\uFFFD"],
+ ["\u0001a\u007f", "\\1 a\\7f "],
+ ["通知_--menu", "通知_--menu"],
+])("CSS.escape serializes %j like a browser", (input, expected) => {
+ expect(CSS.escape(input)).toBe(expected);
+});
diff --git a/tests/package/README.md b/tests/package/README.md
index c65a266..f7cd30a 100644
--- a/tests/package/README.md
+++ b/tests/package/README.md
@@ -37,3 +37,5 @@ COLOR-04 增加 `consume-color-slider-foundation.mjs`,在 `/private/tmp/heroui
COLOR-06 增加 `consume-color-field-protocol.mjs`,在 `/private/tmp/heroui-color-field-consumer` 验证两份最终 tarball 的字段/输入组暂存 CSS 与没有提前公开占位;同时保留 Calendar/DateField/Select 的 ESM/SSR/CSS 和 strict NodeNext/bundler 类型正反例。组合字段当前内部实现,其 Props/slots 行为与 SSR/水合在工作区测试;COLOR-07 公共批次须补完整产物契约。
COLOR-08 增加 `consume-color-picker-protocol.mjs`,最终 tarball 在 `/private/tmp/heroui-color-picker-consumer` 验证 Picker CSS 暂存和没有公共占位,保留旧 Calendar/DateField/Select 运行/SSR/CSS 及双解析模式类型契约。Picker 内部三部件已接入组合夹具,公开批次仍须补完整公共 Props/事件/插槽产物验收。
+
+B03 使用 `consume-b03-tag-error-message.mjs` / `b03-tag-error-message-contract.ts`,消费者目录 `/private/tmp/heroui-b03-consumer`(pnpm 11 的样式包 override 写在 `pnpm-workspace.yaml`)。验证 ESM 运行时(导出、SSR HTML 契约)、编译产物 CSS 选择器,以及 Tag/TagGroup/TagGroupList/TagRemoveButton/ErrorMessage 的正反类型(bundler 与 NodeNext)。
diff --git a/tests/package/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..ed5474f
--- /dev/null
+++ b/tests/package/b01-consumer-app/main.js
@@ -0,0 +1,253 @@
+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 WrapCase = defineComponent({
+ name: "WrapCase",
+ setup() {
+ return () =>
+ h("div", { "data-case": "wrap", class: "case" }, [
+ h(DropdownRoot, { modal: false }, () => [
+ h(DropdownTrigger, null, () =>
+ h(Button, { "aria-label": "循环" }, () => "循环"),
+ ),
+ h(DropdownPopover, null, () =>
+ h(DropdownMenu, null, () =>
+ h(DropdownSubmenuTrigger, null, () => [
+ h(DropdownItem, { id: "wrap-sub", textValue: "子菜单" }, () => [
+ h(Label, null, () => "子菜单"),
+ h(DropdownSubmenuIndicator),
+ ]),
+ h(DropdownPopover, null, () =>
+ h(DropdownMenu, { shouldFocusWrap: true }, () => [
+ h(
+ DropdownItem,
+ { id: "wrap-first", textValue: "First" },
+ () => h(Label, null, () => "First"),
+ ),
+ h(
+ DropdownItem,
+ { id: "wrap-last", textValue: "Last" },
+ () => h(Label, null, () => "Last"),
+ ),
+ ]),
+ ),
+ ]),
+ ),
+ ),
+ ]),
+ ]);
+ },
+});
+
+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,
+ wrap: WrapCase,
+};
+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-menu-dropdown-contract.ts b/tests/package/b01-menu-dropdown-contract.ts
new file mode 100644
index 0000000..b2d4525
--- /dev/null
+++ b/tests/package/b01-menu-dropdown-contract.ts
@@ -0,0 +1,105 @@
+import {
+ DropdownRoot,
+ DropdownTrigger,
+ DropdownPopover,
+ DropdownMenu,
+ DropdownSection,
+ DropdownItem,
+ DropdownItemIndicator,
+ DropdownSubmenuIndicator,
+ DropdownSubmenuTrigger,
+ Menu,
+ MenuItem,
+ MenuItemIndicator,
+ MenuItemSubmenuIndicator,
+ MenuSection,
+ type DropdownRootProps,
+ type DropdownMenuProps,
+ type DropdownItemProps,
+ type DropdownItemIndicatorProps,
+ type MenuRootProps,
+ type MenuItemProps,
+ type MenuItemIndicatorProps,
+ type MenuSectionProps,
+ type MenuKey,
+ type MenuSelectionMode,
+} from "@heroui-vue/components";
+
+const mode: MenuSelectionMode = "multiple";
+const keys: MenuKey[] = ["a", 0, ""];
+
+const root: DropdownRootProps = {
+ trigger: "longPress",
+ longPressDuration: 400,
+ modal: true,
+ dir: "rtl",
+};
+// @ts-expect-error unknown trigger mode
+const badTrigger: DropdownRootProps = { trigger: "hover" };
+
+const menu: MenuRootProps = {
+ selectionMode: mode,
+ selectedKeys: keys,
+ disabledKeys: ["b"],
+};
+// @ts-expect-error selectionMode must be none|single|multiple
+const badMode: MenuRootProps = { selectionMode: "multiple2" };
+
+const item: MenuItemProps = {
+ id: "a",
+ textValue: "A",
+ variant: "danger",
+ isDisabled: true,
+ closeOnSelect: false,
+};
+// @ts-expect-error variant is default|danger only
+const badVariant: MenuItemProps = { variant: "primary" };
+
+const indicator: MenuItemIndicatorProps = { type: "dot" };
+// @ts-expect-error type is checkmark|dot
+const badIndicator: MenuItemIndicatorProps = { type: "cross" };
+
+const section: MenuSectionProps = {
+ selectionMode: "single",
+ selectedKeys: ["x"],
+};
+
+const dItem: DropdownItemProps = {
+ id: "x",
+ textValue: "X",
+ variant: "default",
+};
+const dInd: DropdownItemIndicatorProps = { type: "checkmark" };
+const dMenu: DropdownMenuProps = { selectionMode: "none" };
+
+export const parts = [
+ DropdownRoot,
+ DropdownTrigger,
+ DropdownPopover,
+ DropdownMenu,
+ DropdownSection,
+ DropdownItem,
+ DropdownItemIndicator,
+ DropdownSubmenuIndicator,
+ DropdownSubmenuTrigger,
+ Menu,
+ MenuItem,
+ MenuItemIndicator,
+ MenuItemSubmenuIndicator,
+ MenuSection,
+] as const;
+
+export const values = {
+ root,
+ menu,
+ item,
+ indicator,
+ section,
+ dItem,
+ dInd,
+ dMenu,
+ badTrigger,
+ badMode,
+ badVariant,
+ badIndicator,
+};
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",
+};
diff --git a/tests/package/b02-pickers-contract.ts b/tests/package/b02-pickers-contract.ts
new file mode 100644
index 0000000..a9732b9
--- /dev/null
+++ b/tests/package/b02-pickers-contract.ts
@@ -0,0 +1,251 @@
+import { h } from "vue";
+import {
+ Autocomplete,
+ AutocompleteClearButton,
+ AutocompleteFilter,
+ AutocompleteIndicator,
+ AutocompletePopover,
+ AutocompleteTrigger,
+ AutocompleteValue,
+ ComboBox,
+ ComboBoxInputGroup,
+ ComboBoxPopover,
+ ComboBoxTrigger,
+ ComboBoxValue,
+ ListBox,
+ ListBoxItem,
+ type AutocompleteItem,
+ type AutocompleteProps,
+ type AutocompleteState,
+ type AutocompleteValueState,
+ type AutocompleteValueProps,
+ type ComboBoxItem,
+ type ComboBoxProps,
+ type ComboBoxState,
+ type ComboBoxValueProps,
+ type ComboBoxValueState,
+ type ComboBoxModelValue,
+ type CollectionKey,
+ type ValidateResult,
+} from "@heroui-vue/components";
+
+// ---------------------------------------------------------------------------
+// Keys: numbers and strings stay distinct, null means "no selection".
+// ---------------------------------------------------------------------------
+const stringKey: ComboBoxModelValue = "cat";
+const numericKey: ComboBoxModelValue = 0;
+const emptyKey: ComboBoxModelValue = "";
+const cleared: ComboBoxModelValue = null;
+const multiple: ComboBoxModelValue = ["cat", 0];
+// @ts-expect-error a key is a string or a finite number
+const objectKey: ComboBoxModelValue = { id: "cat" };
+// @ts-expect-error undefined is not a selection state; use null
+const missingKey: ComboBoxModelValue = undefined;
+
+// ---------------------------------------------------------------------------
+// ComboBox props
+// ---------------------------------------------------------------------------
+const comboProps: ComboBoxProps = {
+ modelValue: stringKey,
+ defaultValue: numericKey,
+ selectionMode: "multiple",
+ inputValue: "",
+ defaultInputValue: "",
+ items: [{ id: 0, textValue: "Zero", isDisabled: false }],
+ disabledKeys: ["a", 0, ""],
+ open: false,
+ defaultOpen: false,
+ isDisabled: false,
+ isReadOnly: false,
+ isRequired: false,
+ isInvalid: false,
+ allowsCustomValue: true,
+ allowsEmptyCollection: true,
+ menuTrigger: "manual",
+ shouldFocusWrap: true,
+ fullWidth: true,
+ variant: "secondary",
+ name: "animal",
+ form: "external-form",
+ formValue: "text",
+ autoComplete: "off",
+ autoFocus: true,
+ validationBehavior: "aria",
+ placeholder: "Select an item",
+ as: "section",
+ asChild: false,
+ class: ["hv-combo-box", { "is-dense": true }],
+};
+// @ts-expect-error selectionMode is a closed union
+const badMode: ComboBoxProps = { selectionMode: "triple" };
+// @ts-expect-error variant is a closed union
+const badVariant: ComboBoxProps = { variant: "tertiary" };
+// @ts-expect-error formValue only allows key or text
+const badFormValue: ComboBoxProps = { formValue: "both" };
+
+// `validate` keeps its parameter and result types.
+const comboWithValidate: ComboBoxProps = {
+ validate: (value) => {
+ const accepted: ComboBoxModelValue = value;
+ void accepted;
+ return true;
+ },
+};
+// @ts-expect-error validate must return a validation result, not a boolean flag object
+const badValidate: ComboBoxProps = { validate: () => ({ ok: true }) };
+
+// ---------------------------------------------------------------------------
+// Autocomplete props, including the source `items` mapping
+// ---------------------------------------------------------------------------
+const autocompleteItems: AutocompleteItem[] = [
+ { id: "california", textValue: "California" },
+ { id: 0, textValue: "Zero", isDisabled: true },
+];
+// @ts-expect-error items need a textValue for filtering and display
+const itemsWithoutText: AutocompleteItem[] = [{ id: "a" }];
+
+const autocompleteProps: AutocompleteProps = {
+ modelValue: cleared,
+ value: multiple,
+ defaultValue: ["a", "b"],
+ items: autocompleteItems,
+ selectionMode: "multiple",
+ disabledKeys: ["a"],
+ open: true,
+ isOpen: true,
+ defaultOpen: false,
+ isDisabled: false,
+ isRequired: true,
+ isInvalid: false,
+ allowsEmptyCollection: false,
+ placeholder: "Select an item",
+ name: "state",
+ form: "external-form",
+ fullWidth: true,
+ variant: "primary",
+ validationBehavior: "native",
+ as: "div",
+ asChild: true,
+ validate: (value): ValidateResult => (Array.isArray(value) ? true : null),
+};
+const badAutocompleteValidate: AutocompleteProps = {
+ // @ts-expect-error validate must not widen to an arbitrary return type
+ validate: () => Symbol("nope"),
+};
+
+// ---------------------------------------------------------------------------
+// Events keep their payload types
+// ---------------------------------------------------------------------------
+const comboEvents = h(ComboBox, {
+ "onUpdate:modelValue": (value: ComboBoxModelValue) => void value,
+ onChange: (value: ComboBoxModelValue) => void value,
+ "onUpdate:selectedKey": (key: CollectionKey | null) => void key,
+ selectionChange: (key: CollectionKey | null) => void key,
+ "onUpdate:inputValue": (text: string) => void text,
+ inputChange: (text: string) => void text,
+ "onUpdate:open": (open: boolean) => void open,
+ openChange: (open: boolean) => void open,
+});
+const badComboEvent = h(ComboBox, {
+ // @ts-expect-error the model event carries the value, never the input text
+ "onUpdate:modelValue": (text: string) => void text,
+});
+
+// Root scoped slots expose the open/selection state.
+const comboState = (state: ComboBoxState): string =>
+ `${state.isOpen}:${state.inputValue}:${state.selectedKeys.length}`;
+const autocompleteState = (state: AutocompleteState): string =>
+ `${state.isOpen}:${state.selectedKeys.length}`;
+const comboValueState = (state: ComboBoxValueState): string =>
+ `${state.isPlaceholder}:${state.selectedItems.length}`;
+
+const autocompleteEvents = h(Autocomplete, {
+ "onUpdate:modelValue": (value: ComboBoxModelValue) => void value,
+ onChange: (value: ComboBoxModelValue) => void value,
+ "onUpdate:open": (open: boolean) => void open,
+ openChange: (open: boolean) => void open,
+ clear: () => undefined,
+});
+
+// ---------------------------------------------------------------------------
+// Parts: every public part accepts the documented props and slots
+// ---------------------------------------------------------------------------
+const comboTree = h(ComboBox, { "aria-label": "动物" }, () => [
+ h(ComboBoxInputGroup, { class: "w-full" }, () => "input"),
+ h(ComboBoxValue, { placeholder: "未选择" }),
+ h(ComboBoxPopover, { placement: "top", offset: 4, shouldFlip: false }, () =>
+ h(ListBox, { "aria-label": "动物" }, () =>
+ h(ListBoxItem, { id: 0, textValue: "Zero" }, () => "Zero"),
+ ),
+ ),
+ h(ComboBoxTrigger, { isDisabled: true }),
+]);
+// @ts-expect-error placement is a closed union
+const badPlacement = h(ComboBoxPopover, { placement: "middle" });
+
+const autocompleteTree = h(Autocomplete, { "aria-label": "州" }, () => [
+ h(AutocompleteTrigger, { isDisabled: false }, () => [
+ h(AutocompleteValue, null, {
+ // Scoped slot state keeps its documented, exported shape.
+ default: (state: AutocompleteValueState) => {
+ const placeholder: boolean = state.isPlaceholder;
+ const joined: string = state.selectedText || state.defaultChildren;
+ const keys = state.selectedItems.map((item) => item.key);
+ return placeholder ? joined : keys.join(",");
+ },
+ }),
+ h(AutocompleteClearButton),
+ h(AutocompleteIndicator),
+ ]),
+ h(AutocompletePopover, { placement: "bottom end" }, () =>
+ h(
+ AutocompleteFilter,
+ { filter: (text, input) => text.includes(input) },
+ () =>
+ h(ListBox, null, () =>
+ h(ListBoxItem, { id: "a", textValue: "A" }, () => "A"),
+ ),
+ ),
+ ),
+]);
+
+const valueProps: ComboBoxValueProps = { placeholder: "未选择" };
+const autocompleteValueProps: AutocompleteValueProps = {};
+// @ts-expect-error ComboBoxValue has no `items` prop
+const badValueProps: ComboBoxValueProps = { items: [] };
+
+const item: ComboBoxItem = { id: 0, textValue: "Zero" };
+const autocompleteFirstItem: AutocompleteItem = autocompleteItems[0]!;
+
+export {
+ comboState,
+ comboValueState,
+ autocompleteState,
+ autocompleteEvents,
+ autocompleteFirstItem,
+ autocompleteProps,
+ autocompleteTree,
+ autocompleteValueProps,
+ badAutocompleteValidate,
+ badComboEvent,
+ badFormValue,
+ badMode,
+ badPlacement,
+ badValidate,
+ badValueProps,
+ badVariant,
+ cleared,
+ comboEvents,
+ comboProps,
+ comboTree,
+ comboWithValidate,
+ emptyKey,
+ item,
+ itemsWithoutText,
+ missingKey,
+ multiple,
+ numericKey,
+ objectKey,
+ stringKey,
+ valueProps,
+};
diff --git a/tests/package/b03-tag-error-message-contract.ts b/tests/package/b03-tag-error-message-contract.ts
new file mode 100644
index 0000000..1678050
--- /dev/null
+++ b/tests/package/b03-tag-error-message-contract.ts
@@ -0,0 +1,121 @@
+import { h } from "vue";
+import {
+ ErrorMessage,
+ Tag,
+ TagGroup,
+ TagGroupList,
+ TagRemoveButton,
+ type TagGroupProps,
+ type TagGroupListProps,
+ type TagKey,
+ type TagProps,
+ type TagRemoveButtonProps,
+ type TagRenderState,
+ type ErrorMessageProps,
+} from "@heroui-vue/components";
+
+const key: TagKey = "news";
+const numericKey: TagKey = 0;
+// @ts-expect-error collection keys are strings or finite numbers
+const invalidKey: TagKey = {};
+
+const groupProps: TagGroupProps = {
+ selectionMode: "multiple",
+ modelValue: [key, numericKey],
+ defaultValue: [],
+ disabledKeys: [key],
+ isDisabled: false,
+ disallowEmptySelection: true,
+ size: "lg",
+ variant: "surface",
+ dir: "rtl",
+ as: "section",
+ asChild: false,
+};
+// @ts-expect-error selectionMode is a closed union
+const badMode: TagGroupProps = { selectionMode: "triple" };
+// @ts-expect-error size is a closed union
+const badSize: TagGroupProps = { size: "xl" };
+
+// `items` keeps the caller's item type: extra fields are allowed and reach the
+// scoped slot unchanged.
+const listProps: TagGroupListProps<{ id: string; name: string }> = {
+ items: [{ id: "a", name: "A" }],
+ as: "div",
+};
+// @ts-expect-error items must carry a collection key
+const listPropsWithoutId: TagGroupListProps<{ name: string }> = {
+ items: [{ name: "A" }],
+};
+
+const tagProps: TagProps = { id: key, textValue: "资讯", isDisabled: false };
+const removeProps: TagRemoveButtonProps = {
+ textValue: "资讯",
+ isDisabled: true,
+};
+// ErrorMessage declares no props of its own: content, `id` and `class` are
+// ordinary attributes / slots.
+const messageProps: ErrorMessageProps = {};
+
+const state: TagRenderState = {
+ isSelected: true,
+ isDisabled: false,
+ isHovered: false,
+ isPressed: false,
+ isFocused: true,
+ isFocusVisible: true,
+ allowsRemoving: true,
+};
+
+const tree = h(
+ TagGroup,
+ {
+ selectionMode: "single",
+ modelValue: [key],
+ "onUpdate:modelValue": (keys: TagKey[]) => keys.length,
+ onSelectionChange: (keys: TagKey[]) => keys,
+ onRemove: (keys: TagKey[]) => keys,
+ },
+ {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () =>
+ h(
+ Tag,
+ { id: key },
+ {
+ default: (tagState: TagRenderState) =>
+ tagState.isSelected ? "selected" : "tag",
+ },
+ ),
+ empty: () =>
+ h(ErrorMessage, { ...messageProps, id: "error" }, () => "empty"),
+ }),
+ h(Tag, tagProps, {
+ default: () => [
+ "资讯",
+ h(TagRemoveButton, removeProps, { default: () => "x" }),
+ ],
+ }),
+ h(ErrorMessage, null, () => "请选择"),
+ ],
+ },
+);
+
+// @ts-expect-error Tag requires a collection key
+const missingId = h(Tag, {});
+
+// @ts-expect-error remove button text must be a string
+const badRemoveText = h(TagRemoveButton, { textValue: 1 });
+
+void [
+ listPropsWithoutId,
+ invalidKey,
+ badMode,
+ badSize,
+ state,
+ tree,
+ missingId,
+ badRemoveText,
+ groupProps,
+];
diff --git a/tests/package/consume-b01-menu-dropdown.mjs b/tests/package/consume-b01-menu-dropdown.mjs
new file mode 100644
index 0000000..5db1e76
--- /dev/null
+++ b/tests/package/consume-b01-menu-dropdown.mjs
@@ -0,0 +1,63 @@
+/**
+ * Independent ESM/CSS consumption for B01 Menu/Dropdown.
+ * Copy into a fresh consumer that installs packed tarballs (no source alias).
+ */
+import { readFileSync } from "node:fs";
+
+const mod = await import("@heroui-vue/components");
+const {
+ DropdownRoot,
+ DropdownTrigger,
+ DropdownPopover,
+ DropdownMenu,
+ DropdownItem,
+ DropdownItemIndicator,
+ DropdownSubmenuTrigger,
+ DropdownSubmenuIndicator,
+ DropdownSection,
+ Menu,
+ MenuItem,
+ MenuItemIndicator,
+ MenuItemSubmenuIndicator,
+ MenuSection,
+} = mod;
+
+const expected = {
+ DropdownRoot,
+ DropdownTrigger,
+ DropdownPopover,
+ DropdownMenu,
+ DropdownItem,
+ DropdownItemIndicator,
+ DropdownSubmenuTrigger,
+ DropdownSubmenuIndicator,
+ DropdownSection,
+ Menu,
+ MenuItem,
+ MenuItemIndicator,
+ MenuItemSubmenuIndicator,
+ MenuSection,
+};
+for (const [name, value] of Object.entries(expected)) {
+ if (!value) {
+ console.error("missing export", name);
+ process.exit(1);
+ }
+}
+
+const cssPath = import.meta.resolve("@heroui-vue/styles/css");
+const css = readFileSync(new URL(cssPath), "utf8");
+for (const token of [
+ "hv-menu-item",
+ "hv-menu-item__indicator--submenu",
+ "hv-dropdown__popover",
+ "hv-dropdown__menu",
+ "data-selected",
+]) {
+ if (!css.includes(token)) {
+ console.error("css missing", token);
+ process.exit(1);
+ }
+}
+
+console.log("b01 menu/dropdown ESM+CSS consume ok");
diff --git a/tests/package/consume-b02-pickers.mjs b/tests/package/consume-b02-pickers.mjs
new file mode 100644
index 0000000..f764544
--- /dev/null
+++ b/tests/package/consume-b02-pickers.mjs
@@ -0,0 +1,159 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { createSSRApp, h } from "vue";
+import { renderToString } from "@vue/server-renderer";
+import * as lib from "@heroui-vue/components";
+
+for (const name of [
+ "ComboBox",
+ "ComboBoxInputGroup",
+ "ComboBoxTrigger",
+ "ComboBoxValue",
+ "ComboBoxPopover",
+ "Autocomplete",
+ "AutocompleteTrigger",
+ "AutocompleteValue",
+ "AutocompleteIndicator",
+ "AutocompleteClearButton",
+ "AutocompletePopover",
+ "AutocompleteFilter",
+ "comboBoxVariants",
+ "autocompleteVariants",
+])
+ assert(lib[name], name);
+
+const items = [
+ { id: "cat", textValue: "猫" },
+ { id: "dog", textValue: "狗" },
+];
+
+const html = await renderToString(
+ createSSRApp({
+ render: () =>
+ h("main", [
+ h(
+ lib.ComboBox,
+ { "aria-label": "动物", defaultSelectedKey: "cat", name: "animal" },
+ {
+ default: () => [
+ h(lib.Label, null, () => "动物"),
+ h(lib.ComboBoxInputGroup, null, {
+ default: () => [h(lib.Input, {}), h(lib.ComboBoxTrigger)],
+ }),
+ h(lib.ComboBoxPopover, null, {
+ default: () =>
+ h(lib.ListBox, null, {
+ default: () =>
+ items.map((item) =>
+ h(
+ lib.ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.textValue,
+ },
+ () => item.textValue,
+ ),
+ ),
+ }),
+ }),
+ ],
+ },
+ ),
+ h(
+ lib.Autocomplete,
+ { "aria-label": "州", name: "state", defaultValue: "dog" },
+ {
+ default: () => [
+ h(lib.AutocompleteTrigger, null, {
+ default: () => [
+ h(lib.AutocompleteValue),
+ h(lib.AutocompleteClearButton),
+ h(lib.AutocompleteIndicator),
+ ],
+ }),
+ h(lib.AutocompletePopover, null, {
+ default: () =>
+ h(lib.AutocompleteFilter, null, {
+ default: () => [
+ h(
+ lib.SearchField,
+ { "aria-label": "搜索" },
+ {
+ default: () =>
+ h(lib.SearchFieldGroup, null, {
+ default: () => [h(lib.SearchFieldInput)],
+ }),
+ },
+ ),
+ h(lib.ListBox, null, {
+ default: () =>
+ items.map((item) =>
+ h(
+ lib.ListBoxItem,
+ {
+ id: item.id,
+ key: item.id,
+ textValue: item.textValue,
+ },
+ () => item.textValue,
+ ),
+ ),
+ }),
+ ],
+ }),
+ }),
+ ],
+ },
+ ),
+ ]),
+ }),
+);
+
+assert(html.includes('data-slot="combo-box"'), "combo-box root");
+assert(html.includes('role="combobox"'), "combobox input role");
+assert(html.includes('data-slot="combo-box-trigger"'), "combo box trigger");
+assert(html.includes('name="animal"'), "combo box form name");
+assert(html.includes('data-slot="autocomplete"'), "autocomplete root");
+assert(
+ html.includes('data-slot="autocomplete-trigger"'),
+ "autocomplete trigger",
+);
+assert(html.includes('role="button"'), "autocomplete trigger is a button");
+assert(html.includes('name="state"'), "autocomplete form name");
+assert(html.includes("猫"), "combo box preselected label");
+
+const css = readFileSync(
+ "node_modules/@heroui-vue/styles/dist/styles.css",
+ "utf8",
+);
+for (const rule of [
+ ".hv-combo-box",
+ ".hv-combo-box__input-group",
+ ".hv-combo-box__trigger",
+ ".hv-combo-box__popover",
+ ".hv-combo-box__value",
+ ".hv-autocomplete",
+ ".hv-autocomplete__trigger",
+ ".hv-autocomplete__value",
+ ".hv-autocomplete__indicator",
+ ".hv-autocomplete__clear-button",
+ ".hv-autocomplete__popover",
+ ".hv-autocomplete--secondary",
+])
+ assert(css.includes(rule), `missing CSS ${rule}`);
+
+assert(
+ lib
+ .comboBoxVariants({ fullWidth: true })
+ .base()
+ .includes("hv-combo-box--full-width"),
+);
+assert(
+ lib
+ .autocompleteVariants({ variant: "secondary" })
+ .base()
+ .includes("hv-autocomplete--secondary"),
+);
+
+console.log("B02 pickers consumption OK");
diff --git a/tests/package/consume-b03-tag-error-message.mjs b/tests/package/consume-b03-tag-error-message.mjs
new file mode 100644
index 0000000..193f4a7
--- /dev/null
+++ b/tests/package/consume-b03-tag-error-message.mjs
@@ -0,0 +1,88 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { createSSRApp, h } from "vue";
+import { renderToString } from "@vue/server-renderer";
+import * as lib from "@heroui-vue/components";
+
+for (const name of [
+ "TagGroup",
+ "TagGroupList",
+ "Tag",
+ "TagRemoveButton",
+ "ErrorMessage",
+ "tagVariants",
+ "tagGroupVariants",
+ "errorMessageVariants",
+])
+ assert(lib[name], name);
+
+const html = await renderToString(
+ createSSRApp({
+ render: () =>
+ h(
+ lib.TagGroup,
+ {
+ "aria-label": "分类",
+ selectionMode: "multiple",
+ modelValue: ["news"],
+ onRemove: () => {},
+ },
+ {
+ default: () => [
+ h(lib.TagGroupList, null, {
+ default: () => [
+ h(lib.Tag, { id: "news" }, { default: () => "资讯" }),
+ h(
+ lib.Tag,
+ { id: 0, isDisabled: true },
+ { default: () => "零" },
+ ),
+ ],
+ }),
+ h(lib.ErrorMessage, null, { default: () => "请至少选择一项" }),
+ ],
+ },
+ ),
+ }),
+);
+
+assert(html.includes('role="grid"'), "grid role on the list");
+assert(html.includes('aria-label="分类"'), "grid carries the group label");
+assert(html.includes('aria-multiselectable="true"'), "multiple selection flag");
+assert(html.includes('role="row"'), "rows for tags");
+assert(html.includes('aria-selected="true"'), "accepted selection");
+assert(html.includes('aria-disabled="true"'), "disabled tag");
+assert(html.includes("Remove tag 资讯"), "composed remove button name");
+assert(html.includes('data-slot="tag-remove-button"'), "remove button slot");
+assert(html.includes('data-slot="error-message"'), "error message slot");
+assert(html.includes('slot="errorMessage"'), "baseline error message marker");
+
+const css = readFileSync(
+ "node_modules/@heroui-vue/styles/dist/styles.css",
+ "utf8",
+);
+for (const rule of [
+ ".hv-tag",
+ ".hv-tag--sm",
+ ".hv-tag--lg",
+ ".hv-tag--surface",
+ ".hv-tag__remove-button",
+ ".hv-tag-group",
+ ".hv-tag-group__list",
+ ".hv-error-message",
+])
+ assert(css.includes(rule), `missing CSS rule ${rule}`);
+// The list padding rule must survive minification for Description/ErrorMessage.
+assert(
+ /\.hv-tag-group\s*\[data-slot=["']?error-message/.test(css),
+ "missing tag-group error-message padding rule",
+);
+
+assert.equal(typeof lib.tagVariants({ size: "sm" }).base, "function");
+assert(lib.tagVariants({ size: "sm" }).base().includes("hv-tag--sm"));
+assert(
+ lib.tagVariants({ variant: "surface" }).base().includes("hv-tag--surface"),
+);
+assert(lib.errorMessageVariants().includes("hv-error-message"));
+
+console.log("B03 tag/error-message consumption OK");
diff --git a/tests/setup/cssom.ts b/tests/setup/cssom.ts
new file mode 100644
index 0000000..8cc40fe
--- /dev/null
+++ b/tests/setup/cssom.ts
@@ -0,0 +1,49 @@
+/**
+ * jsdom lacks parts of the CSSOM. Reka's Presence uses `CSS.escape` when it
+ * resolves exiting children, so tests that dispatch real `animationend` events
+ * need the same capability a browser provides. Only fills the gap; never
+ * overrides an existing implementation.
+ */
+type CssEscapeHost = { escape?: (value: string) => string };
+const cssGlobal = globalThis as unknown as { CSS?: CssEscapeHost };
+
+if (!cssGlobal.CSS) cssGlobal.CSS = {};
+
+if (typeof cssGlobal.CSS.escape !== "function") {
+ // CSSOM identifier serialization, including leading digits after a minus,
+ // control characters and the otherwise-invalid single minus identifier.
+ const escapeIdentifier = (value: string) => {
+ const input = String(value);
+ let output = "";
+ for (let index = 0; index < input.length; index += 1) {
+ const char = input[index];
+ const code = input.charCodeAt(index);
+ if (code === 0) {
+ output += "\uFFFD";
+ } else if (
+ (code >= 1 && code <= 0x1f) ||
+ code === 0x7f ||
+ (code >= 0x30 &&
+ code <= 0x39 &&
+ (index === 0 || (index === 1 && input[0] === "-")))
+ ) {
+ output += `\\${code.toString(16)} `;
+ } else if (index === 0 && code === 0x2d && input.length === 1) {
+ output += "\\-";
+ } else if (
+ code >= 0x80 ||
+ code === 0x2d ||
+ code === 0x5f ||
+ (code >= 0x30 && code <= 0x39) ||
+ (code >= 0x41 && code <= 0x5a) ||
+ (code >= 0x61 && code <= 0x7a)
+ ) {
+ output += char;
+ } else {
+ output += `\\${char}`;
+ }
+ }
+ return output;
+ };
+ cssGlobal.CSS.escape = escapeIdentifier;
+}
diff --git a/tests/setup/scroll.ts b/tests/setup/scroll.ts
new file mode 100644
index 0000000..4751fb4
--- /dev/null
+++ b/tests/setup/scroll.ts
@@ -0,0 +1,9 @@
+/** jsdom has no Element.scrollTo. Supply only the method used by VueUse;
+ * geometry and visible-window assertions still belong to real browser checks.
+ * Set up each test realm explicitly so probes work alone and in any order. */
+if (
+ typeof Element !== "undefined" &&
+ typeof Element.prototype.scrollTo !== "function"
+) {
+ Element.prototype.scrollTo = () => {};
+}
diff --git a/tests/tag-error-message.test.ts b/tests/tag-error-message.test.ts
new file mode 100644
index 0000000..efc6664
--- /dev/null
+++ b/tests/tag-error-message.test.ts
@@ -0,0 +1,1378 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { readFileSync } from "node:fs";
+import { mount } from "@vue/test-utils";
+import { createApp, defineComponent, h, nextTick, ref } from "vue";
+import {
+ Description,
+ ErrorMessage,
+ Label,
+ Tag,
+ TagGroup,
+ TagGroupList,
+ TagRemoveButton,
+} from "../packages/vue/src";
+
+type Item = { id: string | number; label: string; disabled?: boolean };
+
+type Mounted = ReturnType;
+// Each case queries inside its own root: a shared document hides ordering bugs.
+const wrappers: Mounted[] = [];
+
+/** Vue skips an invoker when the event timestamp is not newer than the listener
+ * attachment time (`e._vts <= invoker.attached`). Synthetic dispatch inside the
+ * same millisecond is ignored, so move past that millisecond first. */
+const settle = () => new Promise((resolve) => setTimeout(resolve, 2));
+
+async function mountGroup(
+ options: {
+ tags?: Item[];
+ props?: Record;
+ groupProps?: Record;
+ slots?: Record;
+ content?: (item: Item) => unknown;
+ } = {},
+) {
+ const tags = options.tags ?? [
+ { id: "news", label: "资讯" },
+ { id: "travel", label: "旅行" },
+ { id: "gaming", label: "游戏" },
+ ];
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h(
+ TagGroup,
+ { selectionMode: "single", "aria-label": "分类", ...options.props },
+ {
+ default: () => [
+ h(TagGroupList, options.groupProps ?? {}, {
+ default: () => [
+ ...tags.map((tag) =>
+ h(
+ Tag,
+ { id: tag.id, key: tag.id, isDisabled: tag.disabled },
+ {
+ default: () =>
+ options.content ? options.content(tag) : tag.label,
+ },
+ ),
+ ),
+ ...(((options.slots?.default as unknown[]) ??
+ []) as never[]),
+ ],
+ }),
+ ],
+ },
+ );
+ },
+ }),
+ { attachTo: document.body },
+ );
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+ return wrapper;
+}
+
+function root(): HTMLElement {
+ return (wrappers.at(-1)?.element as HTMLElement | undefined) ?? document.body;
+}
+const queryAll = (selector: string) => {
+ const element = root();
+ const found = [...element.querySelectorAll(selector)];
+ if (element.matches(selector)) found.unshift(element as unknown as T);
+ return found;
+};
+const queryOne = (selector: string) =>
+ queryAll(selector)[0] ?? null;
+const row = (label: string) =>
+ queryAll('[data-slot="tag"]').find(
+ (element) => element.textContent?.replace(/\s+/g, "") === label,
+ );
+
+afterEach(async () => {
+ // Unmount through Vue so the registry/focus cleanup runs; never yank the DOM
+ // out from under a live tree.
+ while (wrappers.length) wrappers.pop()?.unmount();
+ await nextTick();
+ await settle();
+ vi.restoreAllMocks();
+});
+
+describe("TagGroup structure", () => {
+ it("exposes the baseline data-slots and BEM blocks", async () => {
+ await mountGroup();
+ const root = queryOne('[data-slot="tag-group"]')!;
+ const list = queryOne('[data-slot="tag-group-list"]')!;
+
+ expect(root.className).toContain("hv-tag-group");
+ expect(root.className).not.toContain("hv-tag-group__list");
+ expect(list.className).toContain("hv-tag-group__list");
+ expect(list.className).not.toContain("hv-tag-group ");
+ expect(queryAll('[data-slot="tag"]')).toHaveLength(3);
+ });
+
+ it("renders each tag as a row inside the grid", async () => {
+ await mountGroup();
+ const list = queryOne('[data-slot="tag-group-list"]')!;
+
+ expect(list.getAttribute("role")).toBe("grid");
+ expect(list.getAttribute("aria-label")).toBe("分类");
+ expect(list.getAttribute("aria-atomic")).toBe("false");
+ expect(list.getAttribute("aria-relevant")).toBe("additions text");
+ const rows = [...list.querySelectorAll('[data-slot="tag"]')];
+
+ expect(rows.map((element) => element.getAttribute("role"))).toEqual([
+ "row",
+ "row",
+ "row",
+ ]);
+ expect(rows.map((element) => element.textContent?.trim())).toEqual([
+ "资讯",
+ "旅行",
+ "游戏",
+ ]);
+ });
+
+ it("names the grid from Label and describes it with Description and ErrorMessage", async () => {
+ const named = mount(TagGroup, {
+ props: { selectionMode: "single" },
+ slots: {
+ default: () => [
+ h(Label, () => "设施"),
+ h(TagGroupList, null, {
+ default: () => [h(Tag, { id: "pool" }, () => "游泳池")],
+ }),
+ h(Description, () => "可多选"),
+ h(ErrorMessage, () => "请选择一个设施"),
+ ],
+ },
+ attachTo: document.body,
+ });
+ wrappers.push(named);
+ await nextTick();
+ await settle();
+ const list = queryOne('[data-slot="tag-group-list"]')!;
+ const label = queryOne('[data-slot="label"]')!;
+ const description = queryOne('[data-slot="description"]')!;
+ const error = queryOne('[data-slot="error-message"]')!;
+
+ expect(list.getAttribute("aria-label")).toBeNull();
+ expect(list.getAttribute("aria-labelledby")).toBe(label.id);
+ expect(label.tagName).toBe("SPAN");
+ expect(list.getAttribute("aria-describedby")).toContain(description.id);
+ expect(list.getAttribute("aria-describedby")).toContain(error.id);
+ expect(error.className).toContain("hv-error-message");
+ expect(error.getAttribute("slot")).toBe("errorMessage");
+ });
+
+ it("applies group size and variant to every tag", async () => {
+ await mountGroup({ props: { size: "lg", variant: "surface" } });
+ const rows = [...queryAll('[data-slot="tag"]')];
+
+ for (const element of rows) {
+ expect(element.className).toContain("hv-tag--lg");
+ expect(element.className).toContain("hv-tag--surface");
+ }
+ });
+
+ it("keeps caller class, attrs and listeners on the semantic nodes", async () => {
+ const onClick = vi.fn();
+ const caller = mount(TagGroup, {
+ props: { selectionMode: "none", class: "caller", onClick },
+ attrs: { "data-test": "group" },
+ slots: {
+ default: () => [
+ h(
+ TagGroupList,
+ { class: "list-caller" },
+ {
+ default: () => [
+ h(Tag, { id: "a", class: "tag-caller" }, () => "A"),
+ ],
+ },
+ ),
+ ],
+ },
+ attachTo: document.body,
+ });
+ wrappers.push(caller);
+ await nextTick();
+ await settle();
+ const root = queryOne('[data-slot="tag-group"]')!;
+ const list = queryOne('[data-slot="tag-group-list"]')!;
+ const tag = queryOne('[data-slot="tag"]')!;
+
+ expect(root.className).toContain("hv-tag-group");
+ expect(root.className).toContain("caller");
+ expect(root.getAttribute("data-test")).toBe("group");
+ expect(list.className).toContain("hv-tag-group__list");
+ expect(list.className).toContain("list-caller");
+ expect(tag.className).toContain("hv-tag");
+ expect(tag.className).toContain("tag-caller");
+ expect(tag.getAttribute("aria-selected")).toBeNull();
+
+ tag.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("TagGroup selection", () => {
+ it("toggles a single selection and reflects it in ARIA and data attributes", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({ props: { "onUpdate:modelValue": onUpdate } });
+ const news = row("资讯")!;
+
+ expect(news.getAttribute("aria-selected")).toBe("false");
+ expect(news.hasAttribute("data-selected")).toBe(false);
+
+ news.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ expect(onUpdate.mock.calls[0][0]).toEqual(["news"]);
+ expect(news.getAttribute("aria-selected")).toBe("true");
+ expect(news.getAttribute("data-selected")).toBe("true");
+ });
+
+ it("clears a single selection on a second activation", async () => {
+ const selected = ref(["news"]);
+ const Demo = defineComponent({
+ setup() {
+ return () =>
+ h(
+ TagGroup,
+ {
+ "aria-label": "分类",
+ selectionMode: "single",
+ modelValue: selected.value,
+ "onUpdate:modelValue": (keys: (string | number)[]) => {
+ selected.value = keys as string[];
+ },
+ },
+ {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () => [
+ h(
+ Tag,
+ { id: "news", key: "news" },
+ { default: () => "资讯" },
+ ),
+ h(
+ Tag,
+ { id: "travel", key: "travel" },
+ { default: () => "旅行" },
+ ),
+ ],
+ }),
+ ],
+ },
+ );
+ },
+ });
+ const wrapper = mount(Demo, { attachTo: document.body });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+ expect(row("资讯")!.getAttribute("aria-selected")).toBe("true");
+
+ row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+
+ expect(selected.value).toEqual([]);
+ expect(row("资讯")!.getAttribute("aria-selected")).toBe("false");
+ });
+
+ it("honours disallowEmptySelection", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({
+ props: {
+ modelValue: ["news"],
+ disallowEmptySelection: true,
+ "onUpdate:modelValue": onUpdate,
+ },
+ });
+
+ row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+
+ expect(onUpdate).not.toHaveBeenCalled();
+ expect(row("资讯")!.getAttribute("aria-selected")).toBe("true");
+ });
+
+ it("accumulates multiple selection and marks the grid multiselectable", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({
+ props: { selectionMode: "multiple", "onUpdate:modelValue": onUpdate },
+ });
+ const list = queryOne('[data-slot="tag-group-list"]')!;
+
+ expect(list.getAttribute("aria-multiselectable")).toBe("true");
+
+ row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+
+ expect(onUpdate.mock.calls.at(-1)?.[0]).toEqual(["news", "travel"]);
+ expect(row("资讯")!.getAttribute("aria-selected")).toBe("true");
+ expect(row("旅行")!.getAttribute("aria-selected")).toBe("true");
+ });
+
+ it("keeps the accepted value when the parent rejects the proposal", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({
+ props: { modelValue: [], "onUpdate:modelValue": onUpdate },
+ });
+
+ row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await nextTick();
+
+ expect(onUpdate).toHaveBeenCalledWith(["travel"]);
+ expect(row("旅行")!.getAttribute("aria-selected")).toBe("false");
+ });
+
+ it("accepts a rejected proposal again after the parent starts accepting", async () => {
+ const accepted = ref(null);
+ const Demo = defineComponent({
+ setup() {
+ return () =>
+ h(
+ TagGroup,
+ {
+ selectionMode: "single",
+ "aria-label": "分类",
+ modelValue: accepted.value ?? [],
+ "onUpdate:modelValue": (keys: (string | number)[]) => {
+ if (accepted.value !== null) accepted.value = keys as string[];
+ },
+ },
+ {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () => [
+ h(Tag, { id: "news" }, () => "资讯"),
+ h(Tag, { id: "travel" }, () => "旅行"),
+ ],
+ }),
+ ],
+ },
+ );
+ },
+ });
+ const wrapper = mount(Demo, { attachTo: document.body });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ expect(row("旅行")!.getAttribute("aria-selected")).toBe("false");
+
+ accepted.value = [];
+ await nextTick();
+ row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ expect(row("旅行")!.getAttribute("aria-selected")).toBe("true");
+ });
+
+ it("disables keys and individual tags without selecting them", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({
+ tags: [
+ { id: "news", label: "资讯" },
+ { id: "travel", label: "旅行", disabled: true },
+ { id: "gaming", label: "游戏" },
+ ],
+ props: {
+ disabledKeys: ["gaming"],
+ "onUpdate:modelValue": onUpdate,
+ },
+ });
+
+ expect(row("旅行")!.getAttribute("aria-disabled")).toBe("true");
+ expect(row("旅行")!.getAttribute("data-disabled")).toBe("true");
+ expect(row("游戏")!.getAttribute("aria-disabled")).toBe("true");
+ expect(row("资讯")!.hasAttribute("aria-disabled")).toBe(false);
+
+ row("旅行")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ row("游戏")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+
+ expect(onUpdate).not.toHaveBeenCalled();
+ });
+
+ it("disables the whole group", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({
+ props: { isDisabled: true, "onUpdate:modelValue": onUpdate },
+ });
+
+ for (const label of ["资讯", "旅行", "游戏"])
+ expect(row(label)!.getAttribute("aria-disabled")).toBe("true");
+
+ row("资讯")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ expect(onUpdate).not.toHaveBeenCalled();
+ });
+});
+
+describe("TagGroup removal", () => {
+ it("renders a default remove button only when removal is allowed", async () => {
+ await mountGroup();
+ expect(queryOne('[data-slot=\"tag-remove-button\"]')).toBeNull();
+
+ await mountGroup({ props: { onRemove: vi.fn() } });
+ const buttons = [...queryAll('[data-slot="tag-remove-button"]')];
+
+ expect(buttons).toHaveLength(3);
+ expect(buttons[0].getAttribute("aria-label")).toBe("Remove tag 资讯");
+ expect(buttons[0].tagName).toBe("BUTTON");
+ expect(buttons[0].getAttribute("type")).toBe("button");
+ });
+
+ it("requests removal without changing the selection", async () => {
+ const onRemove = vi.fn();
+ const onUpdate = vi.fn();
+ await mountGroup({ props: { onRemove, "onUpdate:modelValue": onUpdate } });
+
+ queryAll('[data-slot="tag-remove-button"]')[1].dispatchEvent(
+ new MouseEvent("click", { bubbles: true }),
+ );
+ await nextTick();
+
+ expect(onRemove).toHaveBeenCalledTimes(1);
+ expect(onRemove.mock.calls[0][0]).toEqual(["travel"]);
+ expect(onUpdate).not.toHaveBeenCalled();
+ });
+
+ it("replaces the default button with a custom TagRemoveButton", async () => {
+ const onRemove = vi.fn();
+ const custom = mount(TagGroup, {
+ props: { selectionMode: "single", "aria-label": "分类", onRemove },
+ slots: {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () => [
+ h(
+ Tag,
+ { id: "news" },
+ {
+ default: () => [
+ "资讯",
+ h(
+ TagRemoveButton,
+ { "data-test": "custom" },
+ { default: () => h("span", "×") },
+ ),
+ ],
+ },
+ ),
+ ],
+ }),
+ ],
+ },
+ attachTo: document.body,
+ });
+ wrappers.push(custom);
+ await nextTick();
+ await settle();
+ const buttons = [...queryAll('[data-slot="tag-remove-button"]')];
+
+ expect(buttons).toHaveLength(1);
+ expect(buttons[0].getAttribute("data-test")).toBe("custom");
+ expect(buttons[0].textContent).toBe("×");
+ expect(buttons[0].getAttribute("aria-label")).toBe("Remove tag 资讯");
+
+ buttons[0].dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ expect(onRemove).toHaveBeenCalledWith(["news"]);
+ });
+
+ it("removes the focused tag with Delete and Backspace", async () => {
+ const onRemove = vi.fn();
+ await mountGroup({ props: { onRemove } });
+
+ row("旅行")!.focus();
+ await nextTick();
+ row("旅行")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Delete", bubbles: true }),
+ );
+ await nextTick();
+ expect(onRemove).toHaveBeenLastCalledWith(["travel"]);
+
+ row("旅行")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Backspace", bubbles: true }),
+ );
+ await nextTick();
+ expect(onRemove).toHaveBeenCalledTimes(2);
+ expect(onRemove).toHaveBeenLastCalledWith(["travel"]);
+ });
+
+ it("moves focus to the next neighbour after a confirmed removal", async () => {
+ const tags = ref
- ([
+ { id: "news", label: "资讯" },
+ { id: "travel", label: "旅行" },
+ { id: "gaming", label: "游戏" },
+ ]);
+ const Demo = defineComponent({
+ setup() {
+ return () =>
+ h(
+ TagGroup,
+ {
+ "aria-label": "分类",
+ onRemove: (keys: (string | number)[]) => {
+ tags.value = tags.value.filter((tag) => !keys.includes(tag.id));
+ },
+ },
+ {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () =>
+ tags.value.map((tag) =>
+ h(
+ Tag,
+ { id: tag.id, key: tag.id },
+ { default: () => tag.label },
+ ),
+ ),
+ }),
+ ],
+ },
+ );
+ },
+ });
+ const wrapper = mount(Demo, { attachTo: document.body });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ row("旅行")!.focus();
+ await nextTick();
+ document
+ .querySelectorAll('[data-slot="tag-remove-button"]')[1]
+ .dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await nextTick();
+
+ expect(row("旅行")).toBeUndefined();
+ expect(document.activeElement).toBe(row("游戏"));
+ });
+
+ it("moves focus to the neighbour after removing through the button", async () => {
+ const tags = ref
- ([
+ { id: "news", label: "资讯" },
+ { id: "travel", label: "旅行" },
+ { id: "gaming", label: "游戏" },
+ ]);
+ const Demo = defineComponent({
+ setup() {
+ return () =>
+ h(
+ TagGroup,
+ {
+ "aria-label": "分类",
+ onRemove: (keys: (string | number)[]) => {
+ tags.value = tags.value.filter((tag) => !keys.includes(tag.id));
+ },
+ },
+ {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () =>
+ tags.value.map((tag) =>
+ h(
+ Tag,
+ { id: tag.id, key: tag.id },
+ { default: () => tag.label },
+ ),
+ ),
+ }),
+ ],
+ },
+ );
+ },
+ });
+ const wrapper = mount(Demo, { attachTo: document.body });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ queryAll('[data-slot="tag-remove-button"]')[1].dispatchEvent(
+ new MouseEvent("click", { bubbles: true }),
+ );
+ await nextTick();
+ await nextTick();
+
+ expect(row("旅行")).toBeUndefined();
+ expect(document.activeElement).toBe(row("游戏"));
+ });
+
+ it("focuses the grid when the last tag is removed", async () => {
+ const tags = ref
- ([{ id: "news", label: "资讯" }]);
+ const Demo = defineComponent({
+ setup() {
+ return () =>
+ h(
+ TagGroup,
+ {
+ "aria-label": "分类",
+ onRemove: () => {
+ tags.value = [];
+ },
+ },
+ {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () =>
+ tags.value.map((tag) =>
+ h(
+ Tag,
+ { id: tag.id, key: tag.id },
+ { default: () => tag.label },
+ ),
+ ),
+ }),
+ ],
+ },
+ );
+ },
+ });
+ const wrapper = mount(Demo, { attachTo: document.body });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ row("资讯")!.focus();
+ await nextTick();
+ document
+ .querySelector('[data-slot="tag-remove-button"]')!
+ .dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await nextTick();
+
+ const list = queryOne('[data-slot="tag-group-list"]')!;
+
+ expect(list.children).toHaveLength(0);
+ expect(list.getAttribute("tabindex")).toBe("0");
+ expect(document.activeElement).toBe(list);
+ });
+
+ it("keeps the tag and its focus when the parent rejects the removal", async () => {
+ const onRemove = vi.fn();
+ await mountGroup({ props: { onRemove } });
+
+ row("旅行")!.focus();
+ await nextTick();
+ document
+ .querySelectorAll('[data-slot="tag-remove-button"]')[1]
+ .dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+ await nextTick();
+
+ expect(onRemove).toHaveBeenCalledTimes(1);
+ expect(row("旅行")).toBeDefined();
+ expect(document.activeElement).toBe(row("旅行"));
+
+ row("旅行")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Delete", bubbles: true }),
+ );
+ await nextTick();
+ expect(onRemove).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe("TagGroup keyboard", () => {
+ it("moves focus with the arrow keys, Home and End and skips disabled tags", async () => {
+ await mountGroup({
+ tags: [
+ { id: "news", label: "资讯" },
+ { id: "travel", label: "旅行", disabled: true },
+ { id: "gaming", label: "游戏" },
+ ],
+ });
+ row("资讯")!.focus();
+ await nextTick();
+ expect(document.activeElement).toBe(row("资讯"));
+
+ row("资讯")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
+ );
+ await nextTick();
+ await nextTick();
+ expect(document.activeElement).toBe(row("游戏"));
+
+ row("游戏")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Home", bubbles: true }),
+ );
+ await nextTick();
+ await nextTick();
+ expect(document.activeElement).toBe(row("资讯"));
+
+ row("资讯")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "End", bubbles: true }),
+ );
+ await nextTick();
+ await nextTick();
+ expect(document.activeElement).toBe(row("游戏"));
+
+ row("游戏")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }),
+ );
+ await nextTick();
+ await nextTick();
+ expect(document.activeElement).toBe(row("资讯"));
+ });
+
+ it("reverses the horizontal direction in RTL", async () => {
+ await mountGroup({
+ props: { dir: "rtl" },
+ tags: [
+ { id: "news", label: "资讯" },
+ { id: "travel", label: "旅行" },
+ { id: "gaming", label: "游戏" },
+ ],
+ });
+ row("资讯")!.focus();
+ await nextTick();
+
+ row("资讯")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true }),
+ );
+ await nextTick();
+ await nextTick();
+ expect(document.activeElement).toBe(row("旅行"));
+
+ row("旅行")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
+ );
+ await nextTick();
+ await nextTick();
+ expect(document.activeElement).toBe(row("资讯"));
+ });
+
+ it("activates once on the Space key sequence and lets the caller cancel", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({ props: { "onUpdate:modelValue": onUpdate } });
+ row("资讯")!.focus();
+ await nextTick();
+
+ row("资讯")!.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: " ",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ expect(onUpdate).not.toHaveBeenCalled();
+ row("资讯")!.dispatchEvent(
+ new KeyboardEvent("keyup", { key: " ", bubbles: true, cancelable: true }),
+ );
+ await nextTick();
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+
+ const cancel = (event: Event) => event.preventDefault();
+ const list = queryOne('[data-slot="tag-group-list"]')!;
+ list.addEventListener("keyup", cancel, true);
+ row("资讯")!.dispatchEvent(
+ new KeyboardEvent("keydown", {
+ key: " ",
+ bubbles: true,
+ cancelable: true,
+ }),
+ );
+ row("资讯")!.dispatchEvent(
+ new KeyboardEvent("keyup", { key: " ", bubbles: true, cancelable: true }),
+ );
+ await nextTick();
+ list.removeEventListener("keyup", cancel, true);
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ });
+
+ it("activates with Enter once", async () => {
+ const onUpdate = vi.fn();
+ await mountGroup({ props: { "onUpdate:modelValue": onUpdate } });
+ row("旅行")!.focus();
+ await nextTick();
+
+ row("旅行")!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),
+ );
+ await nextTick();
+
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ expect(onUpdate).toHaveBeenCalledWith(["travel"]);
+ });
+});
+
+describe("TagGroupList items", () => {
+ it("renders data items in order and keys them by id", async () => {
+ const items = [
+ { id: "a", name: "A" },
+ { id: 2, name: "B" },
+ { id: "b", name: "C" },
+ ];
+ const wrapper = mount(TagGroup, {
+ props: { "aria-label": "分类" },
+ slots: {
+ default: () => [
+ h(
+ TagGroupList,
+ { items },
+ {
+ default: ({
+ item,
+ }: {
+ item: { id: string | number; name: string };
+ }) => h(Tag, { id: item.id, key: item.id }, () => item.name),
+ },
+ ),
+ ],
+ },
+ attachTo: document.body,
+ });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ expect(queryAll('[data-slot="tag"]').map((tag) => tag.textContent)).toEqual(
+ ["A", "B", "C"],
+ );
+ });
+
+ it("renders the empty slot when items is empty", async () => {
+ const wrapper = mount(TagGroup, {
+ props: { "aria-label": "分类" },
+ slots: {
+ default: () => [
+ h(
+ TagGroupList,
+ { items: [] as { id: string }[] },
+ {
+ default: () => [],
+ empty: () => h("p", { "data-test": "empty" }, "暂无标签"),
+ },
+ ),
+ ],
+ },
+ attachTo: document.body,
+ });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ expect(queryAll('[data-slot="tag"]')).toHaveLength(0);
+ expect(queryOne('[data-test="empty"]')).not.toBeNull();
+ });
+
+ it("rejects duplicate collection keys", async () => {
+ const errors: string[] = [];
+ const app = createApp({
+ render: () =>
+ h(
+ TagGroup,
+ { "aria-label": "分类" },
+ {
+ default: () => [
+ h(TagGroupList, null, {
+ default: () => [
+ h(Tag, { id: "dup" }, () => "A"),
+ h(Tag, { id: "dup" }, () => "B"),
+ ],
+ }),
+ ],
+ },
+ ),
+ });
+
+ app.config.errorHandler = (error) => {
+ errors.push(String((error as Error).message));
+ };
+ app.config.warnHandler = () => {};
+ const host = document.createElement("div");
+
+ document.body.appendChild(host);
+ app.mount(host);
+ await nextTick();
+ app.unmount();
+ host.remove();
+
+ expect(errors.join(" ")).toMatch(/Duplicate collection key/);
+ });
+
+ it("keeps numeric and string keys distinct", async () => {
+ const onChange = vi.fn();
+ await mountGroup({
+ tags: [
+ { id: 0, label: "零" },
+ { id: "0", label: "字符串零" },
+ ],
+ props: { onSelectionChange: onChange },
+ });
+
+ row("零")!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await nextTick();
+
+ expect(onChange).toHaveBeenCalledWith([0]);
+ expect(row("字符串零")!.getAttribute("aria-selected")).toBe("false");
+ });
+});
+
+describe("ErrorMessage", () => {
+ it("renders standalone with baseline markers", async () => {
+ const wrapper = mount(ErrorMessage, {
+ slots: { default: () => "出错了" },
+ attachTo: document.body,
+ });
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ const message = queryOne('[data-slot="error-message"]')!;
+
+ expect(message.tagName).toBe("P");
+ expect(message.className).toContain("hv-error-message");
+ expect(message.getAttribute("slot")).toBe("errorMessage");
+ expect(message.textContent).toBe("出错了");
+ expect(message.id).not.toBe("");
+ });
+
+ it("keeps its own unique id per instance", async () => {
+ const wrapper = mount(
+ defineComponent({
+ setup() {
+ return () =>
+ h("div", [
+ h(ErrorMessage, { key: "a" }, () => "一"),
+ h(ErrorMessage, { key: "b" }, () => "二"),
+ ]);
+ },
+ }),
+ { attachTo: document.body },
+ );
+ wrappers.push(wrapper);
+ await nextTick();
+ await settle();
+
+ const [first, second] = queryAll('[data-slot="error-message"]');
+
+ expect(first.id).not.toBe(second.id);
+ });
+});
+
+describe("Tag demos and documentation", () => {
+ const previews = [
+ "basic",
+ "sizes",
+ "variants",
+ "disabled",
+ "selection-modes",
+ "controlled",
+ "with-error-message",
+ "with-list-data",
+ "with-prefix",
+ "with-remove-button",
+ "render-function",
+ "custom-styles",
+ ];
+
+ it("includes every preview from the pinned upstream documents", () => {
+ const document = readFileSync("apps/docs/components/tag-group.md", "utf8");
+ const names = [
+ ...document.matchAll(/ match[1]);
+
+ expect(document).not.toContain("[!toc]");
+ expect(names).toEqual(previews);
+ for (const name of previews) {
+ const source = readFileSync(
+ `apps/docs/demos/tag-group-${name}.vue`,
+ "utf8",
+ );
+
+ expect(source).toContain("");
+ expect(source).not.toContain("className");
+ }
+
+ const errorDocument = readFileSync(
+ "apps/docs/components/error-message.md",
+ "utf8",
+ );
+ const errorNames = [
+ ...errorDocument.matchAll(
+ / match[1]);
+
+ expect(errorDocument).not.toContain("[!toc]");
+ expect(errorNames).toEqual(["basic", "custom-styles"]);
+ for (const name of errorNames) {
+ const source = readFileSync(
+ `apps/docs/demos/error-message-${name}.vue`,
+ "utf8",
+ );
+
+ expect(source).toContain("