diff --git a/AGENTS.md b/AGENTS.md index 9168a24..757a903 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -431,3 +431,18 @@ Vaul Vue 官方已说明停止维护并推荐 Reka Drawer;新项目不采用 V - 必须阅读[M33–M34迁移经验](docs/migrations/M33-M34-lessons.md):真实动画所有者、Presence与transition差异、完成/取消手势、捕获与旧节点清理、退出中重开、reduced-motion级联、同页演示、完整文档与独立产物类型。 - M33/M34最终范围见[验收记录](docs/migrations/M33-M34-acceptance.md),不能用历史返修报告或绿色测试数量推断全视觉/读屏已验收。 - 其他AI下一批为[M35 Toast → M36 Table](docs/migrations/M35-M36-toast-table-prompt.md),先同步最新main再开feat/m35-m36-toast-table。集成人继续ListBox/Select、日期与颜色基建;不要改写共享collection/field/overlay内核。 + +## SELECT-01 迁移经验(2026-10-23) + +- Select 六部件与十九例已实现,自动化验证和浏览器待验范围见 [SELECT-01](docs/migrations/SELECT-01-select.md)。不能把此前“Select 未实现”的历史描述当作当前状态,也不能把代码已落地等同完整验收。 +- 复用 Popover 时核对真正节点的 role、data-slot、aria-haspopup 与 controls:通用 dialog 默认值会覆盖字段 listbox 语义。显式部件透传放到实际 asChild 原生节点,通用默认行为保留回归。 +- 非模态不代表 Tab 不循环;Reka Popover FocusScope 默认 loop。字段复合组件要明确原生 Tab 起点与 Portal 顺序,复用现有栈,不能新增全局导航监听队列。 +- 表单可见值、原生提交、自动填充和 reset 同时验;受控值未变化时 Vue 不一定重写被浏览器 reset 的 option。原生层显式恢复接受值,数字/字符串 key 通过 option 索引恢复,内部编码不得进入提交。 +- SSR 的关闭态元数据必须先于 Value/原生选项渲染;未知包装要求显式完整 items。动态移除不得保留成功提交,布尔属性的空字符串按 true 处理,不执行用户任意 setup/render 来取文字。 +- 清空控件使用非 button、计数注册、实际 Trigger 禁用及原生取消协议;十九例同页检查 ID,异步例不能以静态假数据替代,分页失败重试和卸载 AbortSignal 都要测。 +- 本轮浏览器工具 URL 安全策略阻断,不绕过、不写成已验证;代码/SSR/水合/独立产物与真实几何/动效的结论分开,补验前留在任务分支。 + +## SELECT-01 浏览器补验接续(2026-10-23) + +- 正常 HTTP 页面恢复访问后,Select 已完成重点浏览器补验,可以按本轮验证结果集成 main;上一节“留在任务分支”的要求是此前阻断阶段,不再适用。 +- 不能只断言焦点正确:Floating 首次定位前 scrollIntoView 可能无效。定位后的动画开始及无动画路径重新检查当前焦点可见性;尊重取消、不抢焦点、忽略子动画、清理帧回调。长列表同时核对 activeElement、滚动区边界和 scrollTop。 diff --git a/apps/docs/.vitepress/theme/Layout.vue b/apps/docs/.vitepress/theme/Layout.vue index b2f09be..889bbcc 100644 --- a/apps/docs/.vitepress/theme/Layout.vue +++ b/apps/docs/.vitepress/theme/Layout.vue @@ -103,6 +103,7 @@ const groups = [ { title: "NumberField 数字输入框", url: "/components/number-field" }, { title: "Slider 滑块", url: "/components/slider" }, { title: "ListBox 列表框", url: "/components/list-box" }, + { title: "Select 选择器", url: "/components/select" }, { title: "Tooltip 工具提示", url: "/components/tooltip" }, { title: "ToggleButton 切换按钮", diff --git a/apps/docs/components/select.md b/apps/docs/components/select.md new file mode 100644 index 0000000..fd5486d --- /dev/null +++ b/apps/docs/components/select.md @@ -0,0 +1,348 @@ +--- +title: Select 选择器 +description: Select 展示可折叠的选项列表,并允许用户从中选择一项。 +component: select +group: 组件 +--- + +## 用法 + +```vue + +``` + + + +## 组件结构 + +```vue + + + + 选项 + + + + + + 请选择一项 + + + + + 第一项 + 选项说明 + + + + + 分组 + + 第二项 + + + + + + +``` + +## 示例 + +### 变体 + +Select 组件支持两种视觉变体: + +- **`primary`**(默认)— 带阴影的标准样式,适用于大多数场景 +- **`secondary`** — 低强调、无阴影,适合在 Surface 等表面背景上使用 + + + +### 宽度充满 + + + +### 带描述 + + + +### 必填 + + + +### 禁用 + + + +### 含禁用选项 + + + +### 多选 + + + +### 分组选项 + + + +### 受控组件 + + + +### 受控多选 + + + +### 受控展开状态 + + + +### 异步加载 + +Vue 使用响应式数组、Fetch 与 VueUse 可见性观察加载 PokeAPI 分页;保留取消、加载中、错误重试和手动加载入口,不导出 React Collection / ListBoxLoadMoreItem。 + + + +### 自定义指示器 + + + +### 带清除按钮 + +`SelectTrigger` 本身是 button,因此不能再嵌套 `` 来实现清除。请在触发器内组合 `SelectClearButton` — 它渲染为非 button 控件,且不会打开菜单。 + + + +由于 ARIA 将 button 的子节点视为纯展示内容,清除控件无法获得焦点,因此它带有 `aria-hidden`,仅作为指针操作的可视入口。当组合了 `SelectClearButton` 时,触发器同时支持按 `Backspace` 或 `Delete` 清除,这是键盘与屏幕阅读器用户的清除方式。两种方式都会调用 `clear`。 + +### 自定义展示值 + + + +### 渲染函数 + +通过 `as`、原生 attrs 和作用域插槽表达 Vue 渲染能力。 + + + +### 表面样式 + +在 [Surface](/components/surface) 内使用时,请使用 `variant="secondary"`,以应用适合表面背景的低强调变体。 + + + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 CSS + +若要自定义组件类,可使用 `@layer components` 指令。[了解更多](https://tailwindcss.com/docs/adding-custom-styles#adding-component-classes)。 + +```css +@layer components { + .hv-select { + @apply flex flex-col gap-1; + } + + .hv-select__trigger { + @apply rounded-lg border border-border bg-surface p-2; + } + + .hv-select__value { + @apply text-current; + } + + .hv-select__indicator { + @apply text-muted; + } + + .hv-select__popover { + @apply rounded-lg border border-border bg-surface p-2; + } +} +``` + +## 样式参考 + +HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。 + +### CSS 类 + +Select 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/select.css)): + +#### 基础类 + +- `.hv-select` - Select 根容器 +- `.hv-select__trigger` - 打开下拉的触发按钮 +- `.hv-select__value` - 当前显示的值或占位符 +- `.hv-select__clear-button` - 触发器内的可选清除控件 +- `.hv-select__indicator` - 下拉指示图标 +- `.hv-select__popover` - 弹出层容器 + +#### 变体类 + +- `.hv-select--primary` - Primary 变体,带阴影(默认) +- `.hv-select--secondary` - Secondary 变体,无阴影,适合在 Surface 上使用 + +#### 状态类 + +- `.hv-select[data-invalid="true"]` - 无效状态 +- `.hv-select__trigger[data-focus-visible="true"]` - 触发器聚焦状态 +- `.hv-select__trigger[data-disabled="true"]` - 触发器禁用状态 +- `.hv-select__value[data-placeholder="true"]` - 占位符状态 +- `.hv-select__clear-button[data-empty="true"]` - 无选中项时隐藏清除控件 +- `.hv-select__indicator[data-open="true"]` - 展开时的指示器状态 + +### 交互状态 + +该组件同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制: + +- **悬停**:触发器上的 `:hover` 或 `[data-hovered="true"]` +- **聚焦**:触发器上的 `:focus-visible` 或 `[data-focus-visible="true"]` +- **禁用**:Select 上的 `:disabled` 或 `[data-disabled="true"]` +- **展开**:指示器上的 `[data-open="true"]` + +## API 参考 + +### Select + +`SelectRoot` 是 `Select` 的别名。Key 为字符串或有限数值,数字 `0` 和字符串 `"0"` 不相同,空字符串有效。单选清空为 `null`,多选为 `[]`。显式 `modelValue` 优先于 `value`,显式 `open` 优先于 `isOpen`,包括显式传入 `undefined`。 + +| Prop | 类型 | 默认值 | 描述 | +| ------------------------------ | --------------------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `placeholder` | `string` | `"Select an item"` | 空选择的占位符。 | +| `selectionMode` | `"single" \| "multiple"` | `"single"` | 单选或多选。ListBox 的选择模式由 Select 统一管理。 | +| `modelValue` / `value` | `Key \| Key[] \| null` | — | 受控值,推荐 `v-model`。多选必须是数组。 | +| `defaultValue` | `Key \| Key[] \| null` | `null` / `[]` | 非受控初值,也是 reset 的目标值。 | +| `open` / `isOpen` | `boolean` | — | 受控展开状态,推荐 `v-model:open`。 | +| `defaultOpen` | `boolean` | `false` | 非受控展开初值。 | +| `disabledKeys` | `readonly Key[]` | — | 禁用选项 key;Vue 使用数组替代 Iterable。 | +| `items` | `readonly SelectItem[]` | — | `{ id, textValue, isDisabled? }` 完整元数据。用于不透明包装和异步数据,保证关闭态/SSR 的文字与提交正确;不负责渲染选项。 | +| `isDisabled` / `disabled` | `boolean` | `false` | 禁用交互与原生提交;继承 Fieldset 禁用。 | +| `isReadOnly` | `boolean` | `false` | 保留提交值,阻止用户改选与展开。 | +| `isRequired` | `boolean` | `false` | 必填,校验有效且未禁用的已选项。 | +| `isInvalid` | `boolean` | `false` | 外部无效状态。 | +| `validationBehavior` | `"native" \| "aria"` | 继承 Form,默认 `"native"` | 原生约束或仅 ARIA 校验。 | +| `validate` | `(value: SelectModelValue) => ValidateResult` | — | 本地自定义校验;同时消费 Form 服务端错误。 | +| `name` / `form` | `string` | — | 原生表单名称和外部 form ID。多选同名重复提交;空/不存在/禁用选项不提交。 | +| `autoComplete` | `string` | — | 传给唯一的原生 select 自动填充层;空选择时用稳定 ID 标识,首次自动填充是否出现由浏览器决定。 | +| `fullWidth` | `boolean` | `false` | 占满容器宽度。 | +| `variant` | `"primary" \| "secondary"` | `"primary"` | 主要/次要变体。 | +| `id` | `string` | 自动生成 | 触发器 DOM ID,关联 Label、选项列表与校验。 | +| `as` | `string` | `"div"` | 根 HTML 标签。 | +| `class` / `style` / 原生 attrs | 原生属性 | — | 传给根容器。根 `aria-label` 同时用于触发器;触发器可单独覆盖。 | + +### 事件 + +| 事件 | 参数 | 描述 | +| ------------------------------ | ------------------ | -------------------------------------------------------------------------- | +| `update:modelValue` / `change` | `SelectModelValue` | 用户选择提案;父组件未接受时可见状态和 FormData 保持父值,相同提案可重试。 | +| `update:open` / `openChange` | `boolean` | 展开状态提案;父更新和 reset 不伪造值变化事件。 | +| `clear` | 无 | 指针或关闭态 Backspace/Delete 请求清空;同时触发值事件。 | + +### SelectTrigger + +| Prop / 事件 | 类型 | 默认值 | 描述 | +| ------------------------ | --------- | ---------- | ---------------------------------------------------------- | +| `as` | `string` | `"button"` | 触发器标签;保留正确键盘激活行为。 | +| `isDisabled` | `boolean` | `false` | 单独禁用触发器及其内部清空控件。 | +| `class` / `style` / ARIA | 原生属性 | — | 传到真正的交互节点;显式名称优先。 | +| 原生键盘/指针事件 | DOM Event | — | 用户处理器先运行,可通过 `preventDefault()` 取消内部行为。 | + +### SelectValue + +| Prop / 插槽 | 类型 | 默认值 | 描述 | +| ----------------- | ---------- | -------- | ------------------------ | +| `as` | `string` | `"span"` | 展示值标签。 | +| `class` / `style` | 原生属性 | — | 值区域样式。 | +| `default` | 作用域插槽 | 已选文字 | 自定义展示值,参数如下。 | + +### SelectIndicator + +| Prop / 插槽 | 类型 | 描述 | +| ----------------- | ------------- | -------------------------------------------------------------- | +| `class` / `style` | 原生属性 | 指示器样式。 | +| `default` | 单一 Vue 节点 | 自定义图标;状态与样式合并到该节点。默认使用移植自基线的图标。 | + +### SelectClearButton + +| Prop / 事件 / 插槽 | 类型 | 默认值 | 描述 | +| ------------------ | ------------ | ------------ | -------------------------------------- | +| `as` | `string` | `"span"` | 保持非 button 标签,避免嵌套交互按钮。 | +| `class` / `style` | 原生属性 | — | 清除控件样式。 | +| `click` | `MouseEvent` | — | 可取消清除;不会打开弹层。 | +| `default` | Vue 插槽 | 基线关闭图标 | 自定义内容。 | + +### SelectPopover + +| Prop / 事件 | 类型 | 默认值 | 描述 | +| ----------------------------------- | ----------------------- | ---------- | -------------------------------------------------------------------------------------------------------- | +| `placement` | `OverlayPlacement` | `"bottom"` | bottom/top/left/right/start/end 及对应 left/right/top/bottom/start/end 对齐组合,沿用 Popover 定位协议。 | +| `offset` | `number` | `8` | 与触发器的距离。 | +| `shouldFlip` | `boolean` | `true` | 空间不足时翻转。 | +| `containerPadding` | `number` | `12` | 视口碰撞边距。 | +| `to` | `string \| HTMLElement` | `body` | Teleport 目标;SSR 默认关闭态不会渲染弹层。 | +| `class` / `style` / attrs | 原生属性 | — | 弹层节点属性;选择器只承载一个 ListBox。 | +| `openAutoFocus` / `closeAutoFocus` | `Event` | — | 可取消默认焦点。默认进入已选/首项,关闭恢复触发器;外部交互保留外部焦点。 | +| `escapeKeyDown` / `interactOutside` | DOM / CustomEvent | — | 复用 Popover 的事件与取消协议。 | + +### 作用域插槽状态 + +| 插槽 | 参数 | 描述 | +| --------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------- | +| Select `default` | `{ value, isOpen, selectedItems }` | 当前接受状态;初次 SSR 需要直接使用 selectedItems 时请提供 items 元数据。 | +| SelectValue `default` | `{ defaultChildren, isPlaceholder, selectedItems, state }` | 默认文字、占位状态与选中项。 | +| `selectedItems` | `{ key: Key; textValue: string }[]` | 已选元数据;自定义头像等通过业务数据查找。 | +| `state` | `{ selectedItems, isOpen }` | Vue 响应式状态快照,不暴露 React SelectState。 | + +非受控 `selectionMode` 切换会适配标量/数组外观,切回单选取首项,不发编辑事件;受控切换应由父组件同时提供匹配模式的值。 + +通过组件 ref 调用 `focus()`、`open()`、`close()`,`element` 指向触发器。 + +## 无障碍与兼容差异 + +- 原生按钮承担触发、取消与禁用。触发器使用选择型 `combobox`,关联实际 `listbox`,选项名称与字段标签隔离。 +- 方向键进入已选项(空选择时 ArrowDown 首项、ArrowUp 末项),列表复用 ListBox 导航、首字母搜索和禁用跳过。单选激活关闭,多选保持展开;Escape 关闭,Tab 离开弹层。 +- 复用现有 Popover 非模态焦点与定位体系;与上游 RAC 的移动端原生选择菜单、模态隐藏外部内容不同。当前不提供移动端原生菜单切换。 +- 关闭态从已知 ListBox/Section/Item 插槽预规划元数据;不执行任意包装组件的 setup/render。不透明包装请提供 Select 的 `items`,否则首次打开前未知选项只能显示 key,且无法提交未知选项。 +- 唯一原生 select 提交层保留字符串边界,多选使用重复 name;类型区分只用于组件值与事件。浏览器自动填充通过选中 option 的索引恢复原始 key,不把内部编码放进 FormData。 +- 支持原生必填、重置、Fieldset 与 Form 错误关联;跨浏览器自动填充与实际屏幕阅读器播报仍需专项验收,不声明等同 React Aria 全部能力。 +- 样式及 19 个中文示例来自固定 HeroUI 基线;React 渲染函数改为 Vue 插槽,文档的表单成功反馈使用内联状态,图标扩展示例使用 Tabler。 + +## 相关组件 + +[ListBox](/components/list-box)、[Popover](/components/popover)、[Fieldset](/components/fieldset)、[Label](/components/label)、[FieldError](/components/field-error) diff --git a/apps/docs/demos/select-asynchronous-loading.vue b/apps/docs/demos/select-asynchronous-loading.vue new file mode 100644 index 0000000..20843ff --- /dev/null +++ b/apps/docs/demos/select-asynchronous-loading.vue @@ -0,0 +1,91 @@ + + + + 选择宝可梦 + + + + + + + + + {{ item.textValue }} + + + + + + {{ error ? "加载失败,请重试" : "正在加载…" }} + + + + + + + 加载更多… + + + {{ error ? "重试" : "加载更多…" }} + + + + + diff --git a/apps/docs/demos/select-controlled-multiple.vue b/apps/docs/demos/select-controlled-multiple.vue new file mode 100644 index 0000000..2aada85 --- /dev/null +++ b/apps/docs/demos/select-controlled-multiple.vue @@ -0,0 +1,80 @@ + + + + + 州(受控多选) + + + + + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 佛罗里达 + + + + 纽约 + + + + 伊利诺伊 + + + + 宾夕法尼亚 + + + + + + 已选:{{ selected }} + + diff --git a/apps/docs/demos/select-controlled-open-state.vue b/apps/docs/demos/select-controlled-open-state.vue new file mode 100644 index 0000000..20eb7a9 --- /dev/null +++ b/apps/docs/demos/select-controlled-open-state.vue @@ -0,0 +1,57 @@ + + + + + 州 + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + + {{ open ? "关闭" : "打开" }}选择框 + 选择框{{ open ? "已打开" : "已关闭" }} + + diff --git a/apps/docs/demos/select-controlled.vue b/apps/docs/demos/select-controlled.vue new file mode 100644 index 0000000..69adbb5 --- /dev/null +++ b/apps/docs/demos/select-controlled.vue @@ -0,0 +1,75 @@ + + + + + 州(受控) + + + + + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 佛罗里达 + + + + 纽约 + + + + 伊利诺伊 + + + + 宾夕法尼亚 + + + + + + 已选:{{ selected }} + + diff --git a/apps/docs/demos/select-custom-indicator.vue b/apps/docs/demos/select-custom-indicator.vue new file mode 100644 index 0000000..11fca81 --- /dev/null +++ b/apps/docs/demos/select-custom-indicator.vue @@ -0,0 +1,53 @@ + + + + 州 + + + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + + diff --git a/apps/docs/demos/select-custom-styles.vue b/apps/docs/demos/select-custom-styles.vue new file mode 100644 index 0000000..e833e2f --- /dev/null +++ b/apps/docs/demos/select-custom-styles.vue @@ -0,0 +1,38 @@ + + + + 套餐 + + + + + + + + 免费 + + + + 专业版 + + + + + + diff --git a/apps/docs/demos/select-custom-value.vue b/apps/docs/demos/select-custom-value.vue new file mode 100644 index 0000000..710a6a5 --- /dev/null +++ b/apps/docs/demos/select-custom-value.vue @@ -0,0 +1,107 @@ + + + + 用户 + + + + {{ defaultChildren }} + + + {{ selectedItems.length }} 位用户已选 + + + + + + {{ users.find((u) => u.id === selectedItems[0]?.key)?.fallback }} + + + {{ defaultChildren }} + + + + + + + + + + {{ user.fallback }} + + + {{ user.name }} + {{ user.email }} + + + + + + + diff --git a/apps/docs/demos/select-default.vue b/apps/docs/demos/select-default.vue new file mode 100644 index 0000000..2a7ad0a --- /dev/null +++ b/apps/docs/demos/select-default.vue @@ -0,0 +1,50 @@ + + + + 州 + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + + diff --git a/apps/docs/demos/select-disabled.vue b/apps/docs/demos/select-disabled.vue new file mode 100644 index 0000000..8b46b18 --- /dev/null +++ b/apps/docs/demos/select-disabled.vue @@ -0,0 +1,98 @@ + + + + + 州 + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + + + 拟访问国家 + + + + + + + + 阿根廷 + + + + 委内瑞拉 + + + + 日本 + + + + 法国 + + + + 意大利 + + + + 西班牙 + + + + + + + diff --git a/apps/docs/demos/select-full-width.vue b/apps/docs/demos/select-full-width.vue new file mode 100644 index 0000000..915732d --- /dev/null +++ b/apps/docs/demos/select-full-width.vue @@ -0,0 +1,40 @@ + + + + + 喜爱的动物 + + + + + + + + 猫 + + + + 狗 + + + + 鸟 + + + + + + + diff --git a/apps/docs/demos/select-multiple-select.vue b/apps/docs/demos/select-multiple-select.vue new file mode 100644 index 0000000..fd663d3 --- /dev/null +++ b/apps/docs/demos/select-multiple-select.vue @@ -0,0 +1,62 @@ + + + + 拟访问国家 + + + + + + + + 阿根廷 + + + + 委内瑞拉 + + + + 日本 + + + + 法国 + + + + 意大利 + + + + 西班牙 + + + + 泰国 + + + + 新西兰 + + + + 冰岛 + + + + + + diff --git a/apps/docs/demos/select-on-surface.vue b/apps/docs/demos/select-on-surface.vue new file mode 100644 index 0000000..8bcaf68 --- /dev/null +++ b/apps/docs/demos/select-on-surface.vue @@ -0,0 +1,113 @@ + + + + + + 州 + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + + + + 国家 + + + + + + + + 美国 + + + + 加拿大 + + + + 墨西哥 + + + + 英国 + + + + 法国 + + + + 德国 + + + + + + + 提交 + + 表单提交成功! + + + + diff --git a/apps/docs/demos/select-render-function.vue b/apps/docs/demos/select-render-function.vue new file mode 100644 index 0000000..20bae03 --- /dev/null +++ b/apps/docs/demos/select-render-function.vue @@ -0,0 +1,50 @@ + + + + 州 + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + + diff --git a/apps/docs/demos/select-required.vue b/apps/docs/demos/select-required.vue new file mode 100644 index 0000000..91601a2 --- /dev/null +++ b/apps/docs/demos/select-required.vue @@ -0,0 +1,101 @@ + + + + + 州 + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + + + + 国家 + + + + + + + + 美国 + + + + 加拿大 + + + + 墨西哥 + + + + 英国 + + + + 法国 + + + + 德国 + + + + + + + 提交 + + 表单提交成功! + + + diff --git a/apps/docs/demos/select-variants.vue b/apps/docs/demos/select-variants.vue new file mode 100644 index 0000000..a67c668 --- /dev/null +++ b/apps/docs/demos/select-variants.vue @@ -0,0 +1,55 @@ + + + + + 主要变体 + + + + + + + + Option 1 + + + + Option 2 + + + + + + + 次要变体 + + + + + + + + Option 1 + + + + Option 2 + + + + + + + diff --git a/apps/docs/demos/select-with-clear-button.vue b/apps/docs/demos/select-with-clear-button.vue new file mode 100644 index 0000000..608b939 --- /dev/null +++ b/apps/docs/demos/select-with-clear-button.vue @@ -0,0 +1,52 @@ + + + + State + + + + + + + + + Florida + + + + Delaware + + + + California + + + + Texas + + + + New York + + + + Washington + + + + + + diff --git a/apps/docs/demos/select-with-description.vue b/apps/docs/demos/select-with-description.vue new file mode 100644 index 0000000..0ed5737 --- /dev/null +++ b/apps/docs/demos/select-with-description.vue @@ -0,0 +1,52 @@ + + + + 州 + + + + + + + + 佛罗里达 + + + + 特拉华 + + + + 加利福尼亚 + + + + 德克萨斯 + + + + 纽约 + + + + 华盛顿 + + + + + 请选择居住州 + + diff --git a/apps/docs/demos/select-with-disabled-options.vue b/apps/docs/demos/select-with-disabled-options.vue new file mode 100644 index 0000000..4a0ec7b --- /dev/null +++ b/apps/docs/demos/select-with-disabled-options.vue @@ -0,0 +1,54 @@ + + + + 动物 + + + + + + + + 狗 + + + + 猫 + + + + 鸟 + + + + 袋鼠 + + + + 大象 + + + + 老虎 + + + + + + diff --git a/apps/docs/demos/select-with-sections.vue b/apps/docs/demos/select-with-sections.vue new file mode 100644 index 0000000..ceaac01 --- /dev/null +++ b/apps/docs/demos/select-with-sections.vue @@ -0,0 +1,88 @@ + + + + 国家 + + + + + + + + 北美洲 + + 美国 + + + + 加拿大 + + + + 墨西哥 + + + + + + 欧洲 + + 英国 + + + + 法国 + + + + 德国 + + + + 西班牙 + + + + 意大利 + + + + + + 亚洲 + + 日本 + + + + 中国 + + + + 印度 + + + + 韩国 + + + + + + + diff --git a/apps/docs/package.json b/apps/docs/package.json index a7582bd..477f3d0 100644 --- a/apps/docs/package.json +++ b/apps/docs/package.json @@ -15,6 +15,7 @@ "@heroui-vue/components": "workspace:*", "@heroui-vue/styles": "workspace:*", "@tabler/icons-vue": "^3.49.0", + "@vueuse/core": "14.4.0", "reka-ui": "^2.11.0", "vue": "^3.5.44" } diff --git a/apps/playground/src/App.vue b/apps/playground/src/App.vue index 6e22f99..21f158e 100644 --- a/apps/playground/src/App.vue +++ b/apps/playground/src/App.vue @@ -1,5 +1,9 @@ - + + diff --git a/docs/compatibility.md b/docs/compatibility.md index 462c75b..252b3f2 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -80,7 +80,7 @@ | modal | 验证中(OVERLAY-02) | Root/Trigger/Backdrop/Container/Dialog/Heading/Header/Body/Footer/Icon/Close/CloseTrigger;14/14 基线例;焦点/锁/滚动/退出动画;Vue close 部件替代 React slot | | pagination | 验证中(M30) | 组合式 nav 容器(无 total/page 状态机);11 具名部件;9/9 基线例;onPress→@click;显式 aria-current 可覆盖 | | number-field | 验证中(NUMBER-01) | 五部件与 17/17 基线例;Reka 数值内核;受控/只读/表单 reset、SSR/水合;差异见 NUMBER-01 报告 | -| select | 基建中(未公开) | 集合状态与公开 ListBox 已落地;Select 六部件、字段/弹层/SSR 接入及 19 个基线预览仍待迁移,见 COLLECTION-01 | +| select | 验证中(SELECT-01) | 六部件、19/19 例、单/多选、清空、字段/原生提交/SSR/异步;复用 ListBox + Popover,重点浏览器已验,限制见 SELECT-01 | | meter | 验证中(M20) | Meter/Output/Track/Fill;6/6 基线例;role=meter progressbar;无 isIndeterminate;测量语义独立于 Progress | | slider | 验证中(SLIDER-01) | 六部件、9/9 基线例;原生 range/局部指针适配,单值/范围、受控/reset/SSR/水合;差异见 SLIDER-01 | | table | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | diff --git a/docs/decisions/collection-foundation.md b/docs/decisions/collection-foundation.md index 9291230..651c53a 100644 --- a/docs/decisions/collection-foundation.md +++ b/docs/decisions/collection-foundation.md @@ -71,3 +71,9 @@ 新增原始 Reka 探针确认:Content 的用户 keydown preventDefault 后,End 仍移动焦点。结合 none 语义、完整数据虚拟化与 textValue / 元数据需求,公共 ListBox 使用局部原生 role 节点与既有集合内核,VueUse 维护虚拟滚动测量;不修改依赖、不调用私有上下文,也不引入另一套组件底座。普通列表与虚拟列表共用唯一逻辑集合、选择和焦点状态。 泛型 SFC 不通过 Parameters 提取公共 Props:实测会让模型/模式反例失效。Root 和导出的 Props 复用 ListBoxOptions 明确 schema,保留消费端正反例;不能以 skipLibCheck 或删除反例规避。 + +## SELECT-01 公共实现接续 + +前文 Select 未实现是此前阶段状态。六部件、十九例、唯一原生 select 提交/自动填充边界、字段/reset 与 SSR 元数据已落地,见 [SELECT-01](../migrations/SELECT-01-select.md)。私有 CollectionOwner 将接受值、模式、禁用、Tab 离开与激活关闭连接到现有 ListBox,不另建全局集合或焦点内核。真实浏览器验收受工具 URL 策略阻断,待补后再决定合入 main。 + +Select 后续重点浏览器补验已完成并修复定位后已选项不在可视区的问题;此前 URL 阻断解除,当前可以集成 main,见 SELECT-01 补验节。 diff --git a/docs/migration-handoff.md b/docs/migration-handoff.md index 7dfcc73..94c5166 100644 --- a/docs/migration-handoff.md +++ b/docs/migration-handoff.md @@ -278,3 +278,7 @@ ListBox 已完成公共首轮实现,见 [报告](migrations/LISTBOX-01-list-bo ## M33–M34 最终收口与下一批 原7项失败已修复,集成人补旧节点清理/退出中重开回归、真实outside、23例同页与独立tarball消费;实际边界见[验收记录](migrations/M33-M34-acceptance.md)。后续必须先读[本轮经验](migrations/M33-M34-lessons.md)。下一批安排为[M35 Toast → M36 Table](migrations/M35-M36-toast-table-prompt.md),从最新main新开分支;历史返修说明不再要求继续旧任务。 + +## SELECT-01 接续与复核要点 + +Select 已接入六部件和十九例,见 [报告](migrations/SELECT-01-select.md)。后续集合/日期选择字段复用 CollectionOwner / ListBox、choice/Form 与 overlay,不复制状态或焦点栈。通用弹层 role/ARIA 默认覆盖、非模态 Tab 仍循环、受控 reset 后原生 DOM 不回写、SSR 关闭态缺少元数据、空字符串布尔属性及动态删除留下幽灵提交是本轮重点回归。其他 AI 不自行修改这些共享协议。真实浏览器受 URL 策略阻断,仍待补验,不能把已通过的自动化检查当作最终视觉或交互验收。 diff --git a/docs/migrations/SELECT-01-select.md b/docs/migrations/SELECT-01-select.md new file mode 100644 index 0000000..10324da --- /dev/null +++ b/docs/migrations/SELECT-01-select.md @@ -0,0 +1,45 @@ +# SELECT-01:Select 公共迁移 + +2026-10-23,独立目录 `heroui-vue-core`,分支 `feat/select`,起点 main `65db60a`。固定 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`。其他 AI 的 checkout 未修改。 + +## 交付与结构 + +- 六部件 Select / SelectRoot、SelectTrigger、SelectValue、SelectIndicator、SelectClearButton、SelectPopover;公开 Props、SelectModelValue / SelectItem / SelectSelectedItem、tv 与主题 CSS。 +- 完整移植 select.css / select.styles.ts:primary / secondary、fullWidth、字段尺寸/阴影/圆角、clear target、指示器旋转、150ms fade/zoom95 进入、100ms 退出、方向位移、字段状态与 reduced-motion。使用 hv- 命名空间;placement 改为 Reka 实际 data-side,宽度/原点/可用空间映射到测量变量。默认 SVG 来自基线 icons.tsx,原 Apache-2.0 见 third-party/HEROUI-LICENSE;自定义图标使用 Tabler Vue。 +- 中文十九个正文预览全部迁移并保持顺序:default、variants、full-width、with-description、required、disabled、with-disabled-options、multiple-select、with-sections、controlled、controlled-multiple、controlled-open-state、asynchronous-loading、custom-indicator、with-clear-button、custom-value、render-function、on-surface、custom-styles。 +- 原文标题/介绍、示例布局、选项数据、头像、清空说明、Tailwind 自定义示例和 API 部件已接入;预览、代码高亮与复制仍共用同一 SFC。React render 改 Vue as/插槽,表单 alert 改内联成功反馈。 + +复用现有 ListBox、choice/field/Form、Popover 与 Reka 弹层设施。私有 CollectionOwner 把字段接受值、模式/禁用、激活关闭与焦点目标连接给 ListBox;ListBox 仍使用同一个集合状态内核,没有新增全局选择状态、焦点栈、outside/Escape 监听或滚动锁。 + +直接包装 Reka Select 的 SSR 展示、多选表单和空字符串缺口已在 COLLECTION-01 探针确认,因此选择已有 ListBox + Popover 组合,而非复制 Reka 内部实现或引入第二套组件库。PopoverContent 仅补充原生 role 与 data-slot 的显式透传,默认 dialog 行为保留。 + +## 值、字段与表单 + +- 单选 Key/null、多选 Key[],推荐 v-model;value / isOpen 兼容别名保留,推荐 v-model:open。显式 modelValue/open 优先,包括显式 undefined。父拒绝后真实选择/展示/提交仍为父值,相同提案可重试。 +- 数字 0、字符串 "0"、空字符串分别保留身份。唯一原生 select 负责提交及 autocomplete,option 索引还原原始 key;提交值是 String(key),内部身份编码不进入 FormData。空值、未知或禁用项不提交,多选同名重复提交。 +- 空选择时原生 select 不设置 name,以免产生虚假的空提交;浏览器可通过稳定 ID 与 autocomplete 识别。不同浏览器首次自动填充表现尚未实测,不声明与 RAC 原生隐藏选择层完全一致。 +- nameless checkbox 仅负责约束和 form/reset 归属,不重复提交。native/aria、required、validate、Form 服务端错误消退/刷新、只读/Fieldset 禁用消费现有字段协议。原生 reset 后显式恢复原生选项,避免受控值未变化时 DOM 留在浏览器默认选项。 +- 非受控切换 selectionMode 时适配公开值形状,单选取首项,不发编辑事件;受控父级须同步提供匹配形状。reset 仍使用捕获的初值。 +- Item 的 Label/Description 保持自身作用域;外层标签/描述/错误只关联字段触发器。根 aria-label 传给触发器及 listbox,显式触发器名称可独立覆盖;字段 Label 点击仅聚焦触发器。 + +## SSR、异步与键盘 + +- 关闭态预规划已知 Popover/ListBox/Section/Item、Fragment 与原生结构,SSR 首屏即可显示已选文字和原生 option。布尔 props 的空字符串按 Vue 布尔属性规则解释。 +- 不执行任意用户组件的 setup/render 来探测内容;显式 items 是完整元数据,适合不透明包装与异步标签。未提供元数据的未知项在首次打开前只显示 key,无法提交。挂载 registry 不冒充逻辑全集;动态移除不能留下已删除项的成功提交。 +- Enter/Space 使用既有原生触发器与 ListBox 协议;方向键进入已选/首末项,单选激活关闭,多选保持展开,关闭态首字母搜索跳过禁用项并尊重 IME/取消。清空控件为 aria-hidden span,计数注册决定是否启用关闭态 Delete/Backspace,独立 Trigger 禁用同样阻止清空。 +- Select 使用 Popover 非模态组合。Tab 从 ListBox 退出时先把原生遍历起点返回 Trigger,再允许浏览器默认 Tab,避免底座 FocusScope 循环及 Teleport 文档顺序;不新建全局 Tab 队列。Escape 和外部交互仍由弹层底座处理。 +- 异步例使用真实 PokeAPI、AbortSignal、VueUse IntersectionObserver、分页、加载提示、失败重试与手动加载。React Collection / ListBoxLoadMoreItem 不作为 Vue 公共导出。 + +## 验证与尚未验收 + +最终命令与数量见 [verification.md](../verification.md)。Select 新增 34 项 jsdom 行为/水合/十九例共存/异步分页失败重试与取消,以及 3 项真正 node SSR;既有 ListBox/Popover/Modal、字段与其他组件完整回归保留。测试核对实际焦点、ARIA、FormData 和事件载荷;嵌套 Modal 中的 Escape 单独覆盖。 + +两个新 tarball 安装到 `/private/tmp/heroui-slider-consumer`,执行 ESM/SSR/CSS 及 NodeNext、bundler 严格正反例;旧 ListBox、NumberField/Slider、M30–M32 消费用例同时保留。 + +**本轮真实浏览器未验收。** 5174 文档服务已启动,但浏览器工具在获取既有标签页时被 URL 协议安全策略拦截,未绕过。没有把 jsdom 的 Tab/焦点或已移植动画 CSS 描述为真实浏览器结果。实际焦点遍历、碰撞/滚动、进出动效、重开、深浅色/移动布局及表格宽度仍需重点浏览器核验;暂不据此合入 main。 + +也未完成逐像素视觉、实际读屏/触屏、跨浏览器自动填充、移动端原生选择菜单切换和 Nuxt 验收。当前为“公共实现与自动化验证已落地,浏览器验收待补”,不声明完整兼容 HeroUI。 + +## 浏览器补验接续(2026-10-23) + +本轮正常 HTTP 页面已恢复访问,替代上节“浏览器待验、暂不合 main”的阶段结论。已核验默认/受控多选/清空/深浅色、真实 Tab、嵌套 Modal Escape、表格宽度,以及真实 150ms / scale .95 进入和 100ms 退出事件。长列表定位前聚焦未滚入可视区的问题已修复,保留 SelectLifecycle 夹具与回归;详情见 verification.md。当前可集成 main,完整视觉/移动/读屏等限制继续保留。 diff --git a/docs/upstream.md b/docs/upstream.md index 48c9872..6b81741 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -176,3 +176,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生 - 固定ce90ea3的react/components/{alert-dialog,drawer}、styles对应CSS/tv、中文components/(overlays)正文与demos/cn:AlertDialog14例,Drawer9例。 - hv-命名空间保留源视觉数值,AlertDialog默认图标路径来自固定icons.tsx(Apache-2.0,原声明见third-party/HEROUI-LICENSE);演示自定义图标为Tabler Vue。 - Vue复用既有Reka Dialog/Presence/FocusScope/Portal,Drawer源transition改为同方向/时长/缓动的局部keyframes以适配Presence;拖动逻辑由源阈值适配Vue生命周期与受控状态。未修改上游或安装依赖实现。 + +## SELECT-01(2026-10-23) + +固定 ce90ea3 的 `packages/react/src/components/select/select.tsx`、`packages/styles/components/select.css`、`packages/styles/src/components/select/select.styles.ts`、`icons.tsx` 的 ChevronDown/Close,以及中文 `(pickers)/select.mdx` 和十九个 `demos/cn/select` 预览。CSS/tv/默认图形沿用 Apache-2.0 声明并加 hv- 前缀,方向/宽度/原点适配 Reka 实际状态。Vue 使用现有 ListBox + Popover + 字段协议;异步 React Stately/Collection 改 Fetch + VueUse(文档包显式声明既有 14.4.0),保留数据接口、分页与错误/取消体验。差异与待验收范围见 [SELECT-01](migrations/SELECT-01-select.md)。 diff --git a/docs/verification.md b/docs/verification.md index 7511dca..dfff0ac 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -718,3 +718,24 @@ typecheck、build:docs、build:playground、format、diff-check 与 dist 正反 - 重点浏览器验证Drawer进入关键帧、阶段结束、关闭卸载/焦点/锁释放;AlertDialog标题、默认Escape策略、关闭焦点恢复,两页API表无内部横向溢出。 - 独立tarball在/private/tmp/heroui-m33-consumer通过ESM/node SSR/CSS与NodeNext、bundler正反类型;来源与未验收范围见[M33–M34最终记录](migrations/M33-M34-acceptance.md)。 - 最新main的ListBox与M33/M34共同保留;下一批Toast→Table,须先同步main并新开任务分支。 + +## SELECT-01 公共实现自动化验证(2026-10-23) + +- `pnpm test`:46 文件 / 686 项通过;Select 新增 34 项 jsdom 行为、实际水合、十九例同页挂载及异步分页/重试/取消,另 3 项真正 node SSR。预期的重复 key 拒绝用例会输出 Vue render 警告;普通示例合并挂载无 Vue 警告或重复 ID。 +- `pnpm typecheck`、`pnpm build:docs` 通过;构建只保留既存文档 chunk 超过 500kB 提示。Select CSS 为基线 150ms zoom95 进入 / 100ms 退出,data-side、宽度/原点与可用空间已适配;这些是代码/构建核对,不是实测动效结论。 +- 新 tarball 安装到 `/private/tmp/heroui-slider-consumer`:Select ESM/SSR/CSS、NodeNext / bundler 严格正反例通过;ListBox、NumberField/Slider、M30–M32 消费回归同时通过。模型、变体、模式、metadata、事件、部件位置及作用域插槽 key 类型反例保留;没有源码 alias。 +- 已验证接受值/拒绝重试、单多选空值及 0/"0"/空字符串、单项/Fieldset 禁用/只读、唯一原生提交、autocomplete 提案与回退、native/aria required/Form 错误、原生 reset/取消/受控/动态外部 form、动态移除/异步标签、清空注册/独立 Trigger 禁用、名称/描述/错误隔离、取消与处理器数组停止传播、焦点进入/Tab 起点、嵌套 Modal 的 Escape。jsdom 不模拟真正的浏览器 Tab 默认遍历,也不证明读屏或自动填充弹窗体验。 +- **真实浏览器验收未完成**:5174 文档服务已启动;浏览器工具在读取既有标签页时被 URL 协议安全策略阻止,未绕过或切换其他控制方式。因此碰撞/滚动、Tab 真实落点、进出动效/重开、深浅色/移动布局与表格几何仍待重点补验。本批留在 feat/select,不据此合入 main。 +- 公开差异与当前边界见 [SELECT-01](migrations/SELECT-01-select.md)。未做逐像素、完整读屏/触屏、跨浏览器自动填充、移动原生菜单及 Nuxt 验收;此前 Select“未实现”描述为历史阶段状态。 + +## SELECT-01 浏览器补验与定位后焦点修复(2026-10-23) + +- 本次正常 HTTP 验收页可访问,前节的 URL 策略阻断属于此前阶段。重点验证 5174,不逐一点击全部示例。 +- 单选选择关闭/恢复焦点、重新打开聚焦已选项、真实 Tab 到代码展开按钮、受控多选保持展开、Escape、清空与深浅色已验。八张 API 表在 1280×720 下均为 736px,scrollWidth=clientWidth。 +- 40 项夹具发现定位前 scrollIntoView 无效:第 12 项得到焦点但在 387px 滚动区外。SelectPopover 在进入动画开始和下一帧复核当前焦点的可见性(取消自动焦点时不运行、忽略子动画、卸载清理),修复后 scrollTop=99.5,第 12 项范围 668–704px 位于弹层 321.5–708px 内;End 聚焦第 40 项,scrollTop=1219.5。 +- 原生 animationstart/end 记录进入 enter / elapsed=0.15s / scale=.95,退出 exit / elapsed=0.1s;退出后节点卸载并恢复 Trigger。Modal 内 Select 的 Escape 只关闭当前选择层,父 dialog 保留。未将截图当作动画时长证据。 +- 保留 `SelectLifecycle.vue` 夹具,可在 playground `?select-lifecycle` 运行;临时文档验收路由已移除。截图 `/private/tmp/heroui-select-review.png`。修复后完整检查结果见本轮提交;不宣称逐像素、读屏/触屏、移动端或跨浏览器自动填充验收完成。 + +本次定位后焦点修复最终 `pnpm test`:46 文件 / 687 项通过,typecheck 和 build:docs 通过;Prettier/diff 与独立消费回归继续验证。 + +与远程 main 的 M33–M34 集成后,完整测试 51 文件 / 720 项通过,typecheck、build:docs 通过。导出/样式/脚本/报告均保留双方增量;Select 文档移除 MDX 专用 [!toc] 标记。 diff --git a/package.json b/package.json index d7697cc..111e4b5 100644 --- a/package.json +++ b/package.json @@ -15,8 +15,8 @@ "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", - "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", + "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", + "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", "format": "prettier --check .", "format:fix": "prettier --write .", "dev:playground": "pnpm build && pnpm --filter @heroui-vue/playground dev" diff --git a/packages/styles/components/select.css b/packages/styles/components/select.css new file mode 100644 index 0000000..aa8c04e --- /dev/null +++ b/packages/styles/components/select.css @@ -0,0 +1,281 @@ +/* Adapted from HeroUI ce90ea3, Apache-2.0. See third-party/HEROUI-LICENSE. + * Modified: hv- namespace, Reka placement state. */ +/* Select styles */ +.hv-select { + @apply flex flex-col gap-1; + + &[data-invalid="true"], + &[aria-invalid="true"] { + [data-slot="description"] { + @apply hidden; + } + } + + [data-slot="label"] { + @apply w-fit; + } +} + +.hv-select__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-select__indicator) { + @apply pe-7; + } + + /* Hover state - exclude when clear button is hovered to prevent double hover effect */ + @media (hover: hover) { + &:hover:not(:has(.hv-select__clear-button:hover)), + &[data-hovered="true"]:not(:has(.hv-select__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-select[data-invalid="true"] &, + .hv-select[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-select--primary { + /* Default styles */ +} + +.hv-select--secondary .hv-select__trigger { + @apply shadow-none; + background-color: var(--select-trigger-bg); + + --select-trigger-bg: var(--default); + --select-trigger-bg-hover: var(--default-hover); + --select-trigger-bg-focus: var(--default); + + /* Exclude when clear button is hovered to prevent double hover effect */ + @media (hover: hover) { + &:hover:not(:has(.hv-select__clear-button:hover)), + &[data-hovered="true"]:not(:has(.hv-select__clear-button:hover)) { + background-color: var(--select-trigger-bg-hover); + } + } + + &:focus-visible:not([data-focused]), + &[data-focus-visible="true"] { + background-color: var(--select-trigger-bg-focus); + } + + &:focus, + &[data-focus="true"] { + } + + .hv-select[data-invalid="true"] &, + .hv-select[aria-invalid="true"] & { + background-color: var(--select-trigger-bg-focus); + } +} + +.hv-select__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 select value*/ + [data-slot="list-box-item-indicator"] { + @apply hidden; + } +} + +/* Clear Button styles */ +.hv-select__clear-button { + @apply relative isolate inline-flex size-5 shrink-0 origin-center transform-gpu items-center justify-center self-center rounded-xl bg-transparent p-1 text-muted select-none no-highlight; + + /* Cursor */ + cursor: var(--cursor-interactive); + + /** + * The visible box stays at 20px so it fits inside the trigger's 36px min-height + * without growing it. Expand the pointer target to the 24px floor in WCAG 2.5.8. + */ + &::after { + @apply absolute -inset-0.5; + content: ""; + } + + /* 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="select-clear-button-icon"] { + @apply size-3.5; + } + + @media (hover: hover) { + &:hover, + &[data-hovered="true"] { + @apply bg-default-hover; + } + } + + &:active, + &[data-pressed="true"] { + transform: scale(0.93); + } +} + +.hv-select__indicator { + @apply absolute inset-y-0 end-2 my-auto flex shrink-0 items-center justify-center text-field-placeholder transition duration-150; + + @media (prefers-reduced-motion: reduce) { + transition: none; + } + + &[data-open="true"] { + @apply rotate-180; + } + + &[data-slot="select-default-indicator"] { + @apply size-4; + } +} + +/* Similar to popover content styles */ +.hv-select__popover { + /* RAC constrains overlays to available space; use Reka measurement variables. */ + max-height: var(--reka-popover-content-available-height); + max-width: var(--reka-popover-content-available-width); + @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-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; + /* 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-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; + } + + /* Listbox styles */ + [data-slot="list-box"] { + @apply p-1.5 outline-none; + } + + [data-slot="list-box-item"] { + @apply px-2.5; + } + + /* 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; + } +} + +/* Full width modifier */ +.hv-select--full-width { + @apply w-full; +} + +.hv-select__trigger--full-width { + @apply w-full; +} diff --git a/packages/styles/index.css b/packages/styles/index.css index 0c7b6eb..8600db6 100644 --- a/packages/styles/index.css +++ b/packages/styles/index.css @@ -147,3 +147,5 @@ @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/select.css" layer(components); diff --git a/packages/styles/src/index.ts b/packages/styles/src/index.ts index 5a793eb..7ee3392 100644 --- a/packages/styles/src/index.ts +++ b/packages/styles/src/index.ts @@ -1419,3 +1419,37 @@ export const drawerVariants = tv({ }); export type DrawerVariants = VariantProps; + +export const selectVariants = tv({ + defaultVariants: { + fullWidth: false, + variant: "primary", + }, + slots: { + base: "hv-select", + clearButton: "hv-select__clear-button", + indicator: "hv-select__indicator", + popover: "hv-select__popover", + trigger: "hv-select__trigger", + value: "hv-select__value", + }, + variants: { + fullWidth: { + false: {}, + true: { + base: "hv-select--full-width", + trigger: "hv-select__trigger--full-width", + }, + }, + variant: { + primary: { + base: "hv-select--primary", + }, + secondary: { + base: "hv-select--secondary", + }, + }, + }, +}); + +export type SelectVariants = VariantProps; diff --git a/packages/vue/src/components/collection/owner.ts b/packages/vue/src/components/collection/owner.ts new file mode 100644 index 0000000..8feda08 --- /dev/null +++ b/packages/vue/src/components/collection/owner.ts @@ -0,0 +1,28 @@ +import type { ComputedRef, InjectionKey } from "vue"; +import type { CollectionKey } from "./keys"; +export interface CollectionRecord { + key: CollectionKey; + text: string; + disabled: boolean; +} +export interface OwnedCollection { + items: () => CollectionRecord[]; + focus: (edge: "first" | "last" | "selected") => Promise; +} +/** A field composite may own a ListBox, without adding another value store. */ +export interface CollectionOwner { + keys: ComputedRef; + mode: ComputedRef<"single" | "multiple">; + disabled: ComputedRef; + readOnly: ComputedRef; + disabledKeys: ComputedRef; + id: string; + labelledBy: () => string | undefined; + ariaLabel: () => string | undefined; + request: (keys: CollectionKey[]) => void; + action: (key: CollectionKey) => void; + leave: () => void; + connect: (collection: OwnedCollection) => () => void; +} +export const collectionOwnerKey: InjectionKey = + Symbol("hv-collection-owner"); diff --git a/packages/vue/src/components/list-box/ListBox.vue b/packages/vue/src/components/list-box/ListBox.vue index b2f0814..60450a6 100644 --- a/packages/vue/src/components/list-box/ListBox.vue +++ b/packages/vue/src/components/list-box/ListBox.vue @@ -1,6 +1,7 @@ diff --git a/packages/vue/src/components/select/SelectClearButton.vue b/packages/vue/src/components/select/SelectClearButton.vue new file mode 100644 index 0000000..4bd9d06 --- /dev/null +++ b/packages/vue/src/components/select/SelectClearButton.vue @@ -0,0 +1,51 @@ + + + + + + + + + + diff --git a/packages/vue/src/components/select/SelectIndicator.vue b/packages/vue/src/components/select/SelectIndicator.vue new file mode 100644 index 0000000..a1a4752 --- /dev/null +++ b/packages/vue/src/components/select/SelectIndicator.vue @@ -0,0 +1,46 @@ + diff --git a/packages/vue/src/components/select/SelectPopover.vue b/packages/vue/src/components/select/SelectPopover.vue new file mode 100644 index 0000000..ac04c99 --- /dev/null +++ b/packages/vue/src/components/select/SelectPopover.vue @@ -0,0 +1,91 @@ + + + + + + diff --git a/packages/vue/src/components/select/SelectTrigger.vue b/packages/vue/src/components/select/SelectTrigger.vue new file mode 100644 index 0000000..2417448 --- /dev/null +++ b/packages/vue/src/components/select/SelectTrigger.vue @@ -0,0 +1,158 @@ + diff --git a/packages/vue/src/components/select/SelectValue.vue b/packages/vue/src/components/select/SelectValue.vue new file mode 100644 index 0000000..e47025b --- /dev/null +++ b/packages/vue/src/components/select/SelectValue.vue @@ -0,0 +1,40 @@ + + + + + {{ valueText() }} + + + diff --git a/packages/vue/src/components/select/context.ts b/packages/vue/src/components/select/context.ts new file mode 100644 index 0000000..0151fd8 --- /dev/null +++ b/packages/vue/src/components/select/context.ts @@ -0,0 +1,44 @@ +import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue"; +import type { CollectionKey } from "../collection/keys"; +import type { CollectionRecord, OwnedCollection } from "../collection/owner"; +import type { useChoiceField } from "../choice/shared"; +import type { selectVariants } from "@heroui-vue/styles"; +export type SelectValue = CollectionKey | CollectionKey[] | null; +export interface SelectItem { + id: CollectionKey; + textValue: string; + isDisabled?: boolean; +} +export interface SelectSelectedItem { + key: CollectionKey; + textValue: string; +} +export interface SelectContext { + field: ReturnType>; + slots: ComputedRef>; + keys: ComputedRef; + selectedItems: ComputedRef; + records: ComputedRef; + open: ComputedRef; + setOpen: (open: boolean) => void; + trigger: Ref; + valueId: string; + listId: string; + placeholder: () => string; + ariaLabel: () => string | undefined; + clearCount: Ref; + registerClear: () => () => void; + clear: () => void; + search: (key: string) => void; + collection: Ref; + intent: Ref<"first" | "last" | "selected">; + focusCollection: () => Promise; +} +export const selectKey: InjectionKey = Symbol("hv-select"); +export const selectTriggerDisabledKey: InjectionKey> = + Symbol("hv-select-trigger-disabled"); +export function useSelect() { + const context = inject(selectKey); + if (!context) throw new Error("Select parts require Select."); + return context; +} diff --git a/packages/vue/src/components/select/metadata.ts b/packages/vue/src/components/select/metadata.ts new file mode 100644 index 0000000..102417a --- /dev/null +++ b/packages/vue/src/components/select/metadata.ts @@ -0,0 +1,121 @@ +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 }; + 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); + // Descriptions/icons and arbitrary components are not option name sources. + if ( + node.type === Fragment || + typeof node.type === "string" || + name(node) === "Label" + ) + return text(children(node)); + return ""; + }) + .join("") + .trim(); +} +/** Inspect known collection slots only; never execute arbitrary setup/render. */ +export function planSelectItems(nodes: VNodeChild[]) { + const records: CollectionRecord[] = []; + let found = false, + 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" || + ["SelectPopover", "ListBoxSection"].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/index.ts b/packages/vue/src/index.ts index c760d32..5bffe13 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -724,3 +724,28 @@ export type { DrawerCloseTriggerProps, DrawerCloseProps, } from "./types"; + +export { + default as Select, + default as SelectRoot, +} from "./components/select/Select.vue"; +export { default as SelectTrigger } from "./components/select/SelectTrigger.vue"; +export { default as SelectValue } from "./components/select/SelectValue.vue"; +export { default as SelectIndicator } from "./components/select/SelectIndicator.vue"; +export { default as SelectClearButton } from "./components/select/SelectClearButton.vue"; +export { default as SelectPopover } from "./components/select/SelectPopover.vue"; +export type { + SelectValue as SelectModelValue, + SelectItem, + SelectSelectedItem, +} from "./components/select/context"; +export { selectVariants, type SelectVariants } from "@heroui-vue/styles"; +export type { + SelectProps, + SelectRootProps, + SelectTriggerProps, + SelectValueProps, + SelectIndicatorProps, + SelectClearButtonProps, + SelectPopoverProps, +} from "./types"; diff --git a/packages/vue/src/types.ts b/packages/vue/src/types.ts index cda0484..c399fee 100644 --- a/packages/vue/src/types.ts +++ b/packages/vue/src/types.ts @@ -591,3 +591,28 @@ export type DrawerCloseTriggerProps = InstanceType< typeof DrawerCloseTrigger >["$props"]; export type DrawerCloseProps = InstanceType["$props"]; + +export type SelectProps = InstanceType< + (typeof import("./components/select/Select.vue"))["default"] +>["$props"]; + +export type SelectTriggerProps = InstanceType< + (typeof import("./components/select/SelectTrigger.vue"))["default"] +>["$props"]; + +export type SelectValueProps = InstanceType< + (typeof import("./components/select/SelectValue.vue"))["default"] +>["$props"]; + +export type SelectIndicatorProps = InstanceType< + (typeof import("./components/select/SelectIndicator.vue"))["default"] +>["$props"]; + +export type SelectClearButtonProps = InstanceType< + (typeof import("./components/select/SelectClearButton.vue"))["default"] +>["$props"]; + +export type SelectPopoverProps = InstanceType< + (typeof import("./components/select/SelectPopover.vue"))["default"] +>["$props"]; +export type SelectRootProps = SelectProps; diff --git a/packages/vue/tests/fixtures/SelectLifecycle.vue b/packages/vue/tests/fixtures/SelectLifecycle.vue new file mode 100644 index 0000000..31351d5 --- /dev/null +++ b/packages/vue/tests/fixtures/SelectLifecycle.vue @@ -0,0 +1,86 @@ + + + + Before select + + Lifecycle select + + + + + + + + Option {{ index }} + + + + + + After select + + Open parent + + + + Parent + + Nested select + + + + + + One + + + + + + + {{ log.join("\n") }} + + diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fa299a5..fad2329 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -56,6 +56,9 @@ importers: '@tabler/icons-vue': specifier: ^3.49.0 version: 3.49.0(vue@3.5.44(typescript@5.9.3)) + '@vueuse/core': + specifier: 14.4.0 + version: 14.4.0(vue@3.5.44(typescript@5.9.3)) reka-ui: specifier: ^2.11.0 version: 2.11.0(vue@3.5.44(typescript@5.9.3)) diff --git a/tests/package/README.md b/tests/package/README.md index 4f90381..89ff065 100644 --- a/tests/package/README.md +++ b/tests/package/README.md @@ -19,3 +19,5 @@ M30–M32 增加 consume-m30-m32.mjs 和 m30-m32-contract.ts。将它们复制 LISTBOX-01 增加 `consume-list-box.mjs` / `list-box-contract.ts`。同样复制到独立消费者,用两份新 tarball 安装后运行脚本,并在 NodeNext / bundler 两种模式执行契约文件。Root 的泛型 Props 曾在 Parameters 提取后退化,非法模型/模式反例与事件参数推断必须保留。 M33–M34 使用 consume-m33-m34.mjs / m33-m34-contract.ts;同样复制到独立 tarball 消费工程,分别运行 node 与两种解析模式的 tsc。包括所有公开部件、真正 node SSR、CSS 关键帧与策略/尺寸/方向的正反类型检查。集成验证目录为 /private/tmp/heroui-m33-consumer,不复用其他并行任务的临时产物。 + +SELECT-01 增加 `consume-select.mjs` / `select-contract.ts`。新 tarball 安装后运行 ESM/SSR/CSS 脚本,两种模块解析模式都纳入类型正反例;数字/字符串/空 key、六部件、validate 与事件载荷推断不应退化。保留旧组件消费回归。 diff --git a/tests/package/consume-select.mjs b/tests/package/consume-select.mjs new file mode 100644 index 0000000..4214c75 --- /dev/null +++ b/tests/package/consume-select.mjs @@ -0,0 +1,70 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { createSSRApp, h } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import { + Select, + SelectTrigger, + SelectValue, + SelectIndicator, + SelectClearButton, + SelectPopover, + ListBox, + ListBoxItem, + Label, + selectVariants, +} from "@heroui-vue/components"; +const html = await renderToString( + createSSRApp({ + render: () => + h( + Select, + { + defaultValue: [0, "0", ""], + selectionMode: "multiple", + name: "choices", + }, + () => [ + h(Label, {}, () => "Choice"), + h(SelectTrigger, {}, () => [ + h(SelectValue), + h(SelectClearButton), + h(SelectIndicator), + ]), + h(SelectPopover, {}, () => + h(ListBox, {}, () => [ + h(ListBoxItem, { id: 0, textValue: "Numeric" }, () => "Numeric"), + h(ListBoxItem, { id: "0", textValue: "String" }, () => "String"), + h(ListBoxItem, { id: "", textValue: "Empty" }, () => "Empty"), + ]), + ), + ], + ), + }), +); +assert(html.includes("Numeric, String, Empty")); +assert(html.includes('name="choices"')); +assert.equal((html.match(/data-index="\d" selected/g) ?? []).length, 3); +assert(!html.includes('role="listbox"')); +assert(html.includes('aria-haspopup="listbox"')); +assert( + selectVariants({ variant: "secondary" }) + .base() + .includes("hv-select--secondary"), +); +const css = readFileSync( + new URL(import.meta.resolve("@heroui-vue/styles/css")), + "utf8", +); +for (const part of [ + ".hv-select", + ".hv-select__trigger", + ".hv-select__value", + ".hv-select__clear-button", + ".hv-select__indicator", + ".hv-select__popover", +]) + assert(css.includes(part)); +console.log( + "Select independent tarball: ESM, SSR labels, raw native values, variants and CSS passed.", +); diff --git a/tests/package/select-contract.ts b/tests/package/select-contract.ts new file mode 100644 index 0000000..ba93337 --- /dev/null +++ b/tests/package/select-contract.ts @@ -0,0 +1,77 @@ +import { + Select, + SelectRoot, + SelectTrigger, + SelectValue, + SelectIndicator, + SelectClearButton, + SelectPopover, + selectVariants, + type SelectProps, + type SelectValueProps, + type SelectPopoverProps, + type SelectModelValue, +} from "@heroui-vue/components"; +const value: SelectModelValue = [0, "0", ""]; +const props: SelectProps = { + modelValue: value, + selectionMode: "multiple", + variant: "secondary", + autoComplete: "country", + items: [{ id: 0, textValue: "Zero" }], + onChange: (next) => { + if (Array.isArray(next)) next.forEach((key) => String(key)); + }, + validate: (next) => (next === null ? "Required" : undefined), + onOpenChange: (open) => Boolean(open), +}; +const part: SelectValueProps = { as: "span" }; +const popup: SelectPopoverProps = { placement: "bottom start", offset: 8 }; +// @ts-expect-error Keys are strings or numbers, never objects +const badValue: SelectProps = { modelValue: { id: 0 } }; +// @ts-expect-error Selection mode is constrained +const badMode: SelectProps = { selectionMode: "checkbox" }; +// @ts-expect-error Variants are constrained +const badVariant: SelectProps = { variant: "solid" }; +// @ts-expect-error Metadata text is required +const badItems: SelectProps = { items: [{ id: 0 }] }; +// @ts-expect-error Model listener receives SelectModelValue, not boolean +const badEvent: SelectProps = { onChange: (value: boolean) => value }; +// @ts-expect-error Popover placement is constrained +const badPlacement: SelectPopoverProps = { placement: "diagonal" }; +const badComponent: InstanceType["$props"] = { + // @ts-expect-error Generated component props are also constrained + modelValue: [false], +}; +void [ + Select, + SelectRoot, + SelectTrigger, + SelectValue, + SelectIndicator, + SelectClearButton, + SelectPopover, + selectVariants, + props, + part, + popup, + badValue, + badMode, + badVariant, + badItems, + badEvent, + badPlacement, + badComponent, +]; +type RootSlot = Parameters< + NonNullable["$slots"]["default"]> +>[0]; +const slotState: RootSlot = { + value: 0, + isOpen: false, + selectedItems: [{ key: 0, textValue: "Zero" }], +}; +const selectedKey: string | number = slotState.selectedItems[0].key; +// @ts-expect-error Root scoped slot keys must retain their actual type +const booleanKey: boolean = slotState.selectedItems[0].key; +void [selectedKey, booleanKey]; diff --git a/tests/select-ssr.test.ts b/tests/select-ssr.test.ts new file mode 100644 index 0000000..8afd756 --- /dev/null +++ b/tests/select-ssr.test.ts @@ -0,0 +1,86 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { createSSRApp, h } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import { + Select, + SelectTrigger, + SelectValue, + SelectPopover, + ListBox, + ListBoxItem, + ListBoxItemIndicator, + Label, + Description, +} from "../packages/vue/src"; +function select() { + return h( + Select, + { defaultValue: [0, "0", ""], selectionMode: "multiple", name: "choices" }, + () => [ + h(Label, {}, () => "选择"), + h(SelectTrigger, {}, () => h(SelectValue)), + h(Description, {}, () => "帮助"), + h(SelectPopover, {}, () => + h(ListBox, {}, () => [ + h(ListBoxItem, { id: 0 }, () => [ + h(Label, {}, () => "Number"), + h(Description, {}, () => "Excluded"), + h(ListBoxItemIndicator), + ]), + h(ListBoxItem, { id: "0" }, () => "String"), + h(ListBoxItem, { id: "" }, () => "Empty"), + ]), + ), + ], + ); +} +describe("Select server rendering", () => { + it("renders closed metadata and repeated native selected values without browser globals", async () => { + expect(typeof window).toBe("undefined"); + const html = await renderToString( + createSSRApp({ render: () => h("form", [select(), select()]) }), + ); + expect(html.match(/Number, String, Empty/g)).toHaveLength(2); + expect(html.match(/data-index="\d" selected/g)).toHaveLength(6); + expect(html).not.toContain('role="listbox"'); + expect(html).not.toContain("Excluded"); + const ids = [...html.matchAll(/ id="([^"]+)"/g)].map((m) => m[1]); + expect(new Set(ids).size).toBe(ids.length); + for (const match of html.matchAll( + /aria-(?:labelledby|describedby)="([^"]+)"/g, + )) + for (const id of match[1].split(" ")) expect(ids).toContain(id); + }); + it("uses explicit metadata for opaque options and isolates SSR request IDs", async () => { + const app = () => + createSSRApp({ + render: () => + h( + Select, + { defaultValue: 0, items: [{ id: 0, textValue: "Known" }] }, + () => h(SelectTrigger, {}, () => h(SelectValue)), + ), + }); + const first = await renderToString(app()); + expect(first).toContain("Known"); + expect(first).toBe(await renderToString(app())); + }); + it("rejects duplicate or malformed keys before mounting", async () => { + const app = (items: { id: string | number; textValue: string }[]) => + createSSRApp({ + render: () => + h(Select, { items }, () => + h(SelectTrigger, {}, () => h(SelectValue)), + ), + }); + await expect( + renderToString( + app([ + { id: "a", textValue: "A" }, + { id: "a", textValue: "B" }, + ]), + ), + ).rejects.toThrow("Duplicate collection key"); + }); +}); diff --git a/tests/select.test.ts b/tests/select.test.ts new file mode 100644 index 0000000..a4e3284 --- /dev/null +++ b/tests/select.test.ts @@ -0,0 +1,715 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { mount, flushPromises } from "@vue/test-utils"; +import { createSSRApp, defineComponent, h, ref } from "vue"; +import { renderToString } from "@vue/server-renderer"; +import { + Modal, + ModalBackdrop, + ModalContainer, + ModalDialog, + ModalHeading, + ModalBody, + ModalTrigger, + Button, + Select, + SelectTrigger, + SelectValue, + SelectClearButton, + SelectIndicator, + SelectPopover, + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + Label, + Description, + Header, + FieldError, + Fieldset, + Form, +} from "../packages/vue/src"; +const components = { + Modal, + ModalBackdrop, + ModalContainer, + ModalDialog, + ModalHeading, + ModalBody, + ModalTrigger, + Button, + Select, + SelectTrigger, + SelectValue, + SelectClearButton, + SelectIndicator, + SelectPopover, + ListBox, + ListBoxItem, + ListBoxItemIndicator, + ListBoxSection, + Label, + Description, + Header, + FieldError, + Fieldset, + Form, +}; +const wrappers: ReturnType[] = []; +afterEach(() => { + wrappers.splice(0).forEach((w) => w.unmount()); + document.body.innerHTML = ""; +}); +const options = + 'Zero numberDetailsZero stringDisabledLast'; +const content = `ChoiceHelp${options}`; +function fixture(template: string, setup = () => ({})) { + const wrapper = mount(defineComponent({ components, setup, template }), { + attachTo: document.body, + }); + wrappers.push(wrapper); + return wrapper; +} +const trigger = (w: ReturnType) => + w.get('[data-slot="select-trigger"]'); +const option = (index: number) => + document.querySelectorAll('[role="option"]')[index]; +async function clickOption(index: number) { + option(index).click(); + await flushPromises(); +} +const data = () => [...new FormData(document.querySelector("form")!).entries()]; +describe("Select public contracts", () => { + it("plans closed labels and submits raw numeric/string keys once", async () => { + const w = fixture( + `${content}`, + ); + expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number"); + expect(data()).toEqual([["choice", "0"]]); + expect(document.querySelector('[role="listbox"]')).toBeNull(); + await trigger(w).trigger("click"); + await flushPromises(); + expect(document.querySelector('[role="listbox"]')).not.toBeNull(); + expect(option(0).getAttribute("aria-selected")).toBe("true"); + await clickOption(1); + expect( + w.getComponent(components.Select).emitted("update:modelValue"), + ).toEqual([["0"]]); + expect(data()).toEqual([["choice", "0"]]); + expect(w.get('[data-slot="select-value"]').text()).toBe("Zero string"); + }); + it("uses parent accepted multiple values, retries rejected proposals, and keeps the popup open", async () => { + const value = ref<(string | number)[]>([0]); + const w = fixture( + `${content}`, + () => ({ value }), + ); + await trigger(w).trigger("click"); + await flushPromises(); + await clickOption(1); + await clickOption(1); + expect( + w.getComponent(components.Select).emitted("update:modelValue"), + ).toEqual([[[0, "0"]], [[0, "0"]]]); + expect(option(1).getAttribute("aria-selected")).toBe("false"); + value.value = [0, "0"]; + await flushPromises(); + expect(data()).toEqual([ + ["choice", "0"], + ["choice", "0"], + ]); + expect(trigger(w).attributes("aria-expanded")).toBe("true"); + }); + it("clears without toggling, supports closed Delete only with a clear affordance", async () => { + const w = fixture(`${content}`); + await w + .get('[data-slot="select-clear-button"]') + .trigger("click", { button: 0 }); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + expect(w.getComponent(components.Select).emitted("clear")).toHaveLength(1); + expect( + w.getComponent(components.Select).emitted("update:modelValue"), + ).toEqual([[null]]); + const plain = fixture( + `${content.replace("", "")}`, + ); + await trigger(plain).trigger("keydown", { key: "Delete" }); + expect( + plain.getComponent(components.Select).emitted("change"), + ).toBeUndefined(); + }); + it("honors disabled/readonly state and native reset", async () => { + const w = fixture( + `${content}`, + ); + await trigger(w).trigger("keydown", { key: "Delete" }); + expect(data()).toEqual([]); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(data()).toEqual([["choice", "last"]]); + w.unmount(); + wrappers.pop(); + document.body.innerHTML = ""; + const readonly = fixture( + `${content}`, + ); + await trigger(readonly).trigger("click"); + expect(trigger(readonly).attributes("aria-expanded")).toBe("false"); + await trigger(readonly).trigger("keydown", { key: "Delete" }); + expect(data()).toEqual([["choice", "last"]]); + }); + it("links field labels, descriptions and errors without option leakage", async () => { + const w = fixture(`${content}`); + const t = trigger(w); + const ids = t.attributes("aria-labelledby")!.split(" "); + expect( + ids.map((id) => document.getElementById(id)?.textContent).join(" "), + ).toContain("Choice"); + expect(t.attributes("aria-describedby")).toBeTruthy(); + expect( + w.get('input[type="checkbox"]').element.checkValidity(), + ).toBe(false); + await flushPromises(); + expect(t.attributes("aria-invalid")).toBe("true"); + await t.trigger("click"); + await flushPromises(); + await clickOption(0); + expect( + w.get('input[type="checkbox"]').element.checkValidity(), + ).toBe(true); + expect(t.attributes("aria-labelledby")).toBe(ids.join(" ")); + }); + it("allows trigger event cancellation and honors explicit root accessible names", async () => { + const w = fixture( + `${content.replace("", "")}`, + ); + await trigger(w).trigger("click"); + await flushPromises(); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + expect(trigger(w).attributes("aria-label")).toBe("Named"); + }); + it("renders selected labels and native submission on SSR without mounting popup", async () => { + const app = createSSRApp( + defineComponent({ + components, + template: `${content}`, + }), + ); + const html = await renderToString(app); + expect(html).toContain("Zero number"); + expect(html).not.toContain('role="listbox"'); + expect(html).toContain('name="choice"'); + expect(html).toContain('value="0" data-index="0" selected'); + }); +}); + +describe("Select form and collection changes", () => { + it("uses native autocomplete proposals and restores rejected parent values", async () => { + const w = fixture( + `${content}`, + ); + const native = w.get("select"); + expect(native.attributes("autocomplete")).toBe("country"); + native.element.selectedIndex = 2; + await native.trigger("change"); + await flushPromises(); + expect(w.getComponent(Select).emitted("change")).toEqual([["0"]]); + expect(native.element.selectedIndex).toBe(1); + expect(data()).toEqual([["choice", "0"]]); + }); + it("omits removed or disabled selected options from FormData and constraints", async () => { + const show = ref(true), + disabled = ref(false); + const w = fixture( + `DynamicAlpha`, + () => ({ show, disabled }), + ); + expect(data()).toEqual([["choice", "a"]]); + disabled.value = true; + await flushPromises(); + expect(data()).toEqual([]); + disabled.value = false; + await flushPromises(); + expect(data()).toEqual([["choice", "a"]]); + show.value = false; + await flushPromises(); + expect(data()).toEqual([]); + }); + it("omits Fieldset-disabled values and preserves readonly values", async () => { + const w = fixture( + `${content}`, + ); + expect(trigger(w).attributes("disabled")).toBeDefined(); + expect(data()).toEqual([]); + }); + it("keeps controlled reset and cancelled reset without synthetic changes", async () => { + const w = fixture( + `${content}`, + ); + await trigger(w).trigger("keydown", { key: "Backspace" }); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(data()).toEqual([]); + expect(w.getComponent(Select).emitted("change")).toEqual([[null]]); + }); + it("counts conditional clear affordances and honors actual trigger disabled state", async () => { + const clear = ref(true), + disabled = ref(true); + const w = fixture( + `${content.replace("", '').replace("", '')}`, + () => ({ clear, disabled }), + ); + await w + .get('[data-slot="select-clear-button"]') + .trigger("click", { button: 0 }); + expect(w.getComponent(Select).emitted("change")).toBeUndefined(); + disabled.value = false; + clear.value = false; + await flushPromises(); + await trigger(w).trigger("keydown", { key: "Delete" }); + expect(w.getComponent(Select).emitted("change")).toBeUndefined(); + clear.value = true; + await flushPromises(); + await trigger(w).trigger("keydown", { key: "Delete" }); + expect(w.getComponent(Select).emitted("change")).toEqual([[null]]); + }); + it("keeps open controlled, retries rejected openings and respects explicit undefined precedence", async () => { + const w = fixture( + `${content}`, + ); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + await trigger(w).trigger("click"); + await trigger(w).trigger("click"); + expect(w.getComponent(Select).emitted("update:open")).toEqual([ + [true], + [true], + ]); + }); + it("focuses the selected option on open and skips disabled items", async () => { + const w = fixture(`${content}`); + await trigger(w).trigger("keydown", { key: "ArrowDown" }); + await flushPromises(); + expect(document.activeElement).toBe(option(3)); + option(3).dispatchEvent( + new KeyboardEvent("keydown", { key: "Home", bubbles: true }), + ); + await flushPromises(); + expect(document.activeElement).toBe(option(0)); + }); +}); + +describe("Select popup boundary", () => { + it("uses a presentation popup and a named listbox with correct ARIA ownership", async () => { + const w = fixture(`${content}`); + await trigger(w).trigger("click"); + await flushPromises(); + const popup = document.querySelector('[data-slot="select-popover"]')!; + expect(popup).not.toBeNull(); + expect(popup.getAttribute("role")).toBe("presentation"); + const list = document.querySelector('[role="listbox"]')!; + expect(trigger(w).attributes("aria-controls")).toBe(list.id); + expect(trigger(w).attributes("aria-haspopup")).toBe("listbox"); + expect(list.getAttribute("aria-labelledby")).toBe( + w.get('[data-slot="label"]').attributes("id"), + ); + }); + it("leaves Tab default traversal at the trigger without looping in the portal", async () => { + const w = fixture( + `${content}After`, + ); + await trigger(w).trigger("click"); + await flushPromises(); + const event = new KeyboardEvent("keydown", { + key: "Tab", + bubbles: true, + cancelable: true, + }); + option(0).dispatchEvent(event); + await flushPromises(); + expect(event.defaultPrevented).toBe(false); + expect(document.activeElement).toBe(trigger(w).element); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + }); + it("keeps controlled native selected options on reset even when Vue props did not change", async () => { + const value = ref("last"); + const w = fixture( + `${content}`, + () => ({ value }), + ); + value.value = 0; + await flushPromises(); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(w.get('[data-slot="select-value"]').text()).toBe("Zero number"); + expect(data()).toEqual([["choice", "0"]]); + }); +}); + +describe("Select hydration and baseline demos", () => { + it("hydrates default closed metadata, IDs and native selection without mismatches", async () => { + const Component = defineComponent({ + components, + template: `${content}`, + }); + const host = document.createElement("div"); + host.innerHTML = await renderToString(createSSRApp(Component)); + document.body.append(host); + const before = host.querySelector('[data-slot="select-trigger"]'); + const warnings: string[] = []; + const app = createSSRApp(Component); + app.config.warnHandler = (message) => warnings.push(message); + app.mount(host); + await flushPromises(); + try { + expect(warnings).toEqual([]); + expect(host.querySelector('[data-slot="select-trigger"]')).toBe(before); + expect( + host.querySelector("select")?.selectedOptions[0].dataset.index, + ).toBe("0"); + } finally { + app.unmount(); + } + }); + it("mounts all nineteen source demos with unique IDs and real async data", async () => { + const original = globalThis.fetch; + globalThis.fetch = async () => + new Response( + JSON.stringify({ next: null, results: [{ name: "bulbasaur" }] }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + try { + const demos = import.meta.glob("../apps/docs/demos/select-*.vue", { + eager: true, + import: "default", + }); + expect(Object.keys(demos)).toHaveLength(19); + const warnings: string[] = []; + const w = mount( + defineComponent({ + render: () => + h( + "main", + Object.values(demos).map((component) => + h(component as ReturnType), + ), + ), + }), + { + attachTo: document.body, + global: { + config: { warnHandler: (message) => warnings.push(message) }, + }, + }, + ); + wrappers.push(w); + await flushPromises(); + expect(warnings).toEqual([]); + const ids = w.findAll("[id]").map((node) => node.attributes("id")); + expect(new Set(ids).size).toBe(ids.length); + expect(w.findAll('[data-slot="select-trigger"]')).toHaveLength(23); + const asyncDemo = w + .findAllComponents(Select) + .find( + (component) => component.props("placeholder") === "请选择宝可梦", + )!; + expect(asyncDemo.get("select").text()).toContain("bulbasaur"); + } finally { + globalThis.fetch = original; + } + }); +}); + +describe("Select names, cancellation and closed keyboard", () => { + it("moves focus on field Label click without opening the menu", async () => { + const w = fixture(`${content}`); + await w.get('[data-slot="label"]').trigger("click"); + expect(document.activeElement).toBe(trigger(w).element); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + }); + it("supports closed typeahead and skips disabled options without editing during IME", async () => { + const w = fixture( + `PeopleLiam SmithLiam JonesMartha`, + ); + for (const key of ["l", "i", "a", "m"]) + await trigger(w).trigger("keydown", { key }); + expect(w.get('[data-slot="select-value"]').text()).toBe("Liam Smith"); + expect(w.getComponent(Select).emitted("change")).toEqual([["a"]]); + await trigger(w).trigger("keydown", { key: "m", isComposing: true }); + expect(w.getComponent(Select).emitted("change")).toHaveLength(1); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + }); + it("respects ListBox activation cancellation before selection or closing", async () => { + const w = fixture( + `${content.replace("", "")}`, + ); + await trigger(w).trigger("click"); + await flushPromises(); + option(0).dispatchEvent( + new KeyboardEvent("keydown", { + key: "Enter", + bubbles: true, + cancelable: true, + }), + ); + await flushPromises(); + expect(w.getComponent(Select).emitted("change")).toBeUndefined(); + expect(trigger(w).attributes("aria-expanded")).toBe("true"); + }); + it("keeps aria validation nonblocking and refreshes Form server errors", async () => { + const errors = ref>({ choice: "Server error" }); + const w = fixture( + `${content}`, + () => ({ errors }), + ); + expect(trigger(w).attributes("aria-invalid")).toBe("true"); + expect(w.text()).toContain("Server error"); + expect( + w.get('input[type="checkbox"]').element.checkValidity(), + ).toBe(true); + await trigger(w).trigger("click"); + await flushPromises(); + await clickOption(0); + expect(w.text()).not.toContain("Server error"); + errors.value = { choice: "Refreshed" }; + await flushPromises(); + expect(w.text()).toContain("Refreshed"); + }); +}); + +describe("Select metadata and identity", () => { + it("retains empty-string identities through native form submission", async () => { + const w = fixture( + `EmptyEmpty keyAlpha`, + ); + expect(data()).toEqual([["choice", ""]]); + expect(w.get('[data-slot="select-value"]').text()).toBe("Empty key"); + await trigger(w).trigger("click"); + await flushPromises(); + expect(option(0).getAttribute("aria-selected")).toBe("true"); + }); + it("associates an external form dynamically and restores reset values", async () => { + const owner = ref("one"); + const w = fixture( + `${content}`, + () => ({ owner }), + ); + owner.value = "two"; + await flushPromises(); + await trigger(w).trigger("keydown", { key: "Delete" }); + (w.get("#one").element as HTMLFormElement).reset(); + await flushPromises(); + expect( + w.get('[data-slot="select-value"]').attributes("data-placeholder"), + ).toBe("true"); + (w.get("#two").element as HTMLFormElement).reset(); + await flushPromises(); + expect( + new FormData(w.get("#two").element as HTMLFormElement).get("choice"), + ).toBe("last"); + }); + it("refreshes explicit asynchronous selected metadata before opening", async () => { + const items = ref<{ id: number; textValue: string }[]>([]); + const w = fixture( + `Async`, + () => ({ items }), + ); + expect(data()).toEqual([]); + items.value = [{ id: 0, textValue: "Loaded label" }]; + await flushPromises(); + expect(w.get('[data-slot="select-value"]').text()).toBe("Loaded label"); + expect(data()).toEqual([["choice", "0"]]); + items.value = []; + await flushPromises(); + expect(data()).toEqual([]); + }); + it("gives root accessible names to the popup list and keeps cancellation intact", async () => { + const w = fixture(`${content}`); + await trigger(w).trigger("click"); + await flushPromises(); + expect( + document.querySelector('[role="listbox"]')?.getAttribute("aria-label"), + ).toBe("Root name"); + }); +}); + +describe("Select integration boundaries", () => { + it("keeps a nested Modal open when its Select handles Escape", async () => { + const w = fixture( + `Open modalParent dialog${content}`, + ); + await w.get('[data-slot="modal-trigger"]').trigger("click"); + await flushPromises(); + const selectTrigger = document.querySelector( + '[data-slot="select-trigger"]', + )!; + selectTrigger.click(); + await flushPromises(); + expect(option(0)).toBeTruthy(); + option(0).dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + bubbles: true, + cancelable: true, + }), + ); + await flushPromises(); + expect(document.querySelector('[role="dialog"]')).not.toBeNull(); + expect(selectTrigger.getAttribute("aria-expanded")).toBe("false"); + }); + it("honors open autofocus cancellation and native handler array stop semantics", async () => { + const calls: string[] = []; + const stop = (event: Event) => { + calls.push("first"); + event.stopImmediatePropagation(); + }; + const second = () => calls.push("second"); + const w = fixture( + `${content.replace("", '').replace("", "")}`, + () => ({ stop, second }), + ); + await trigger(w).trigger("keydown", { key: "ArrowDown" }); + expect(calls).toEqual(["first"]); + expect(trigger(w).attributes("aria-expanded")).toBe("false"); + (trigger(w).element as HTMLElement).focus(); + await trigger(w).trigger("click"); + await flushPromises(); + expect(document.activeElement).toBe(trigger(w).element); + }); + it("honors per-item cancellation before changing or closing", async () => { + const w = fixture( + `${content.replace('', '')}`, + ); + await trigger(w).trigger("click"); + await flushPromises(); + await clickOption(0); + expect(w.getComponent(Select).emitted("change")).toBeUndefined(); + expect(trigger(w).attributes("aria-expanded")).toBe("true"); + }); +}); + +describe("Select async demo lifecycle", () => { + it("loads a second page, retains existing options on failure, and retries", async () => { + const original = globalThis.fetch; + const cursors: string[] = []; + let call = 0; + globalThis.fetch = async (input) => { + cursors.push(String(input)); + call++; + if (call === 2) return new Response("", { status: 503 }); + return new Response( + JSON.stringify( + call === 1 + ? { + next: "https://pokeapi.co/api/v2/pokemon?offset=20", + results: [{ name: "bulbasaur" }], + } + : { next: null, results: [{ name: "ivysaur" }] }, + ), + { status: 200 }, + ); + }; + try { + const { default: Demo } = + await import("../apps/docs/demos/select-asynchronous-loading.vue"); + const w = mount(Demo, { attachTo: document.body }); + wrappers.push(w); + await flushPromises(); + await trigger(w).trigger("click"); + await flushPromises(); + const more = [ + ...document.querySelectorAll( + '[data-slot="select-popover"] button', + ), + ].find((button) => button.textContent?.includes("加载更多"))!; + more.click(); + await flushPromises(); + expect(w.get("select").text()).toContain("bulbasaur"); + const retry = [ + ...document.querySelectorAll( + '[data-slot="select-popover"] button', + ), + ].find((button) => button.textContent?.includes("重试"))!; + expect(retry).toBeTruthy(); + retry.click(); + await flushPromises(); + await vi.waitFor(() => + expect(w.get("select").text()).toContain("ivysaur"), + ); + expect(cursors).toEqual([ + "https://pokeapi.co/api/v2/pokemon", + "https://pokeapi.co/api/v2/pokemon?offset=20", + "https://pokeapi.co/api/v2/pokemon?offset=20", + ]); + } finally { + globalThis.fetch = original; + } + }); + it("aborts the pending request on unmount", async () => { + const original = globalThis.fetch; + let signal: AbortSignal | undefined; + globalThis.fetch = async (_input, init) => { + signal = init?.signal ?? undefined; + return new Promise(() => {}); + }; + try { + const { default: Demo } = + await import("../apps/docs/demos/select-asynchronous-loading.vue"); + const w = mount(Demo, { attachTo: document.body }); + expect(signal?.aborted).toBe(false); + w.unmount(); + expect(signal?.aborted).toBe(true); + } finally { + globalThis.fetch = original; + } + }); +}); + +describe("Select dynamic mode", () => { + it("adapts uncontrolled single/multiple shapes and reset without synthetic edits", async () => { + const mode = ref<"single" | "multiple">("single"); + const w = fixture( + `${content}`, + () => ({ mode }), + ); + mode.value = "multiple"; + await flushPromises(); + expect(data()).toEqual([["choice", "last"]]); + await trigger(w).trigger("click"); + await flushPromises(); + await clickOption(0); + expect(w.getComponent(Select).emitted("change")).toEqual([[["last", 0]]]); + mode.value = "single"; + await flushPromises(); + expect(data()).toEqual([["choice", "last"]]); + (w.get("form").element as HTMLFormElement).reset(); + await flushPromises(); + expect(data()).toEqual([["choice", "last"]]); + expect(w.getComponent(Select).emitted("change")).toHaveLength(1); + }); +}); + +it("keeps locally disabled options out of the native submission even with explicit text metadata", () => { + const w = fixture( + `MetadataAlpha`, + ); + expect(data()).toEqual([]); + expect(w.get('[data-slot="select-value"]').text()).toBe("Alpha"); +}); + +it("reveals only the currently focused owned option after popup positioning starts", async () => { + const w = fixture(`${content}`); + await trigger(w).trigger("click"); + await flushPromises(); + const active = option(3); + const reveal = vi.fn(); + active.scrollIntoView = reveal; + const popup = document.querySelector( + '[data-slot="select-popover"]', + )!; + popup.dispatchEvent(new Event("animationstart", { bubbles: true })); + expect(reveal).toHaveBeenCalledOnce(); + active.dispatchEvent(new Event("animationstart", { bubbles: true })); + expect(reveal).toHaveBeenCalledOnce(); + (trigger(w).element as HTMLElement).focus(); + popup.dispatchEvent(new Event("animationstart", { bubbles: true })); + expect(reveal).toHaveBeenCalledOnce(); +});
+ {{ error ? "加载失败,请重试" : "正在加载…" }} +
已选:{{ selected }}
选择框{{ open ? "已打开" : "已关闭" }}
+ 表单提交成功! +
{{ log.join("\n") }}