fix(pickers): rework B02 against the public review

Restore native clearing, unify the form/field protocol with the other choice
families (per-key entries, disabled and removed keys omitted, shared form
owner), synchronise ComboBox text by key identity, keep filtering out of open
composition sessions, and stop stealing focus when a controlled close is
rejected. Also merge caller refs/ARIA/disabled, implement asChild, autoFocus
and ComboBox variant, use a locale-aware base matcher, and put the indicator
class and slot on the icon element the ported CSS selects.
This commit is contained in:
maoyingjie
2026-10-25 20:40:24 +08:00
parent 3e9be13b19
commit e34b9debdf
24 changed files with 1808 additions and 236 deletions
+10 -6
View File
@@ -205,7 +205,7 @@ Autocomplete 组件支持两种视觉变体:
### 表面样式 ### 表面样式
在 [Surface](/components/surface) 组件内使用时,请使用 `variant="secondary"` 以应用适合 Surface 背景的低强调变体。 在 [Surface](/components/surface) 组件内使用时,请使用 `variant="secondary"` 以应用适合 Surface 背景的低强调变体(根类名为 `.hv-autocomplete--secondary`;弹层内的 `SearchField` 需要时再单独声明自己的变体)。
<ComponentPreview name="autocomplete-on-surface" /> <ComponentPreview name="autocomplete-on-surface" />
@@ -320,10 +320,12 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
### Autocomplete ### Autocomplete
| Prop | 类型 | 默认值 | 描述 | | Prop | 类型 | 默认值 | 描述 |
| ------------------------- | ------------------------------------------------------------ | ------------------ | ----------------------------------------------------------------------------------- | | ------------------------- | ------------------------------------------------------------ | ------------------ | --------------------------------------------------------------------------------------------------- |
| `placeholder` | `string` | `'Select an item'` | 为空时显示的占位文本 | | `placeholder` | `string` | `'Select an item'` | 为空时显示的占位文本 |
| `selection-mode` | `'single' \| 'multiple'` | `'single'` | 单选或多选 | | `selection-mode` | `'single' \| 'multiple'` | `'single'` | 单选或多选 |
| `allows-empty-collection` | `boolean` | `false` | 是否允许空集合 | | `allows-empty-collection` | `boolean` | `false` | 是否允许空集合 |
| `items` | `Array<{ id, textValue, isDisabled? }>` | - | 对应上游 `items: Iterable<T>`:关闭态的已选文本与提交校验都取自它,不传时以 `ListBox` 子项为集合 |
| `disabled` | `boolean` | `false` | `is-disabled` 的等价别名 |
| `is-open` | `boolean` | - | 弹层打开状态(受控,`v-model:open` 亦可) | | `is-open` | `boolean` | - | 弹层打开状态(受控,`v-model:open` 亦可) |
| `default-open` | `boolean` | `false` | 弹层默认打开状态(非受控) | | `default-open` | `boolean` | `false` | 弹层默认打开状态(非受控) |
| `disabled-keys` | `Array<string \| number>` | - | 禁用项的 key | | `disabled-keys` | `Array<string \| number>` | - | 禁用项的 key |
@@ -338,7 +340,7 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
| `full-width` | `boolean` | `false` | 是否占满容器宽度 | | `full-width` | `boolean` | `false` | 是否占满容器宽度 |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 视觉变体:`primary` 为默认带阴影样式;`secondary` 为低强调无阴影,适用于 Surface 内 | | `variant` | `'primary' \| 'secondary'` | `'primary'` | 视觉变体:`primary` 为默认带阴影样式;`secondary` 为低强调无阴影,适用于 Surface 内 |
| `as` | `string` | `'div'` | 自定义根元素标签 | | `as` | `string` | `'div'` | 自定义根元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 | | `as-child` | `boolean` | `false` | 把首个插槽元素当作根节点:保留其属性、事件、ref 与子节点,并合并根类名与 `data-slot="autocomplete"` |
| `validate` | `(value) => string \| string[] \| true \| null \| undefined` | - | 校验函数;`native` 时提交会展示错误(上游无此 prop) | | `validate` | `(value) => string \| string[] \| true \| null \| undefined` | - | 校验函数;`native` 时提交会展示错误(上游无此 prop) |
| `validation-behavior` | `'native' \| 'aria'` | `'native'` | 原生校验阻止提交,或只用 ARIA 标记(上游无此 prop) | | `validation-behavior` | `'native' \| 'aria'` | `'native'` | 原生校验阻止提交,或只用 ARIA 标记(上游无此 prop) |
| 默认插槽 | `{ isOpen, selectedKeys }` | - | 组件内容;作用域提供当前状态 | | 默认插槽 | `{ isOpen, selectedKeys }` | - | 组件内容;作用域提供当前状态 |
@@ -354,6 +356,8 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
| `openChange` | `boolean` | 弹层开关变化 | | `openChange` | `boolean` | 弹层开关变化 |
| `clear` | - | 清除已选值 | | `clear` | - | 清除已选值 |
提交层:单选输出一个同名条目,多选按每个 key 输出一个同名条目(`getAll(name)` 为数组);禁用项、被 `disabled-keys` 禁用以及已从集合删除的 key 不提交;集合从未提供过该 key(受控的关闭态值)时按调用方给出的值提交。`form` 同时作用于原生提交层与 reset 校验层。
### AutocompleteTrigger ### AutocompleteTrigger
| Prop | 类型 | 默认值 | 描述 | | Prop | 类型 | 默认值 | 描述 |
@@ -387,7 +391,7 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
| 默认插槽 | `Component` | - | 自定义清除图标 | | 默认插槽 | `Component` | - | 自定义清除图标 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | | `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
`aria-label` 默认 `Clear selection`,`tabindex="-1"`,无选择时 `data-empty="true"` 并隐藏。 `aria-label` 默认 `Clear selection`,`tabindex="-1"`,无选择时 `data-empty="true"` 并隐藏。调用方 `click` 处理器先执行:它调用 `preventDefault()` 时内部清除被取消;原生 `disabled` 与根上的禁用状态任一成立都会禁用按钮并跳过清除。
`@click` 与内部清除处理会合并执行(Vue 事件数组);模板 ref 通过 `defineExpose` 暴露组件实例,需要 DOM 时取 `$el`。 `@click` 与内部清除处理会合并执行(Vue 事件数组);模板 ref 通过 `defineExpose` 暴露组件实例,需要 DOM 时取 `$el`。
@@ -415,7 +419,7 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
| 默认插槽 | `Component` | - | 必须包含 `SearchField`(内含 `SearchFieldInput`)与 `ListBox` | | 默认插槽 | `Component` | - | 必须包含 `SearchField`(内含 `SearchFieldInput`)与 `ListBox` |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | | `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
过滤文本由 `AutocompleteFilter` 拥有,并通过集合的过滤协议影响列表的显示与键盘导航;它不会清除已接受的选择。 过滤文本由 `AutocompleteFilter` 拥有,并通过集合的过滤协议影响列表的显示与键盘导航;它不会清除已接受的选择。组合输入期间列表保持原样,`compositionend` 后再提交一次过滤;会话内的 `Enter` 不确认选择。
受控文本用 `:input-value` + `@input-change`(或 `v-model:input-value`): 受控文本用 `:input-value` + `@input-change`(或 `v-model:input-value`):
@@ -441,7 +445,7 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
上游页面导出的 `useFilter` hook(`contains` / `startsWith` / `endsWith` 与 `sensitivity`)在本库没有对应导出。替代方式: 上游页面导出的 `useFilter` hook(`contains` / `startsWith` / `endsWith` 与 `sensitivity`)在本库没有对应导出。替代方式:
- `AutocompleteFilter` 的默认谓词等价于 `useFilter({ sensitivity: "base" }).contains`(不区分大小写的包含匹配) - `AutocompleteFilter` 的默认谓词等价于 `useFilter({ sensitivity: "base" }).contains`:按 `ConfigProvider` 的 locale 折叠大小写与变音符号,`cafe` 能命中 `Café`
- 需要 `startsWith` / `endsWith` 等语义时,直接给 `:filter="(text, input) => …"` 传函数 - 需要 `startsWith` / `endsWith` 等语义时,直接给 `:filter="(text, input) => …"` 传函数
- 数据源或调用方已过滤时(异步、虚拟化示例),传 `:filter="() => true"` 避免二次过滤 - 数据源或调用方已过滤时(异步、虚拟化示例),传 `:filter="() => true"` 避免二次过滤
+10 -5
View File
@@ -157,7 +157,7 @@ import {
<ComponentPreview name="combo-box-render-function" /> <ComponentPreview name="combo-box-render-function" />
上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(自定义组件作为唯一根),示例通过根元素属性演示同一能力。 上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(把首个插槽元素当作根节点)。`as-child` 时该元素保留自己的属性、事件、ref 与子节点,并额外获得根类名与 `data-slot="combo-box"`,其余部件渲染在它内部;`a` 之外的可聚焦性由调用方负责。
### 菜单触发方式 ### 菜单触发方式
@@ -171,7 +171,9 @@ import {
### 表单值 ### 表单值
使用 `form-value` 控制提交表单时提交选中项的 key 还是文本。默认值为 `key`;`allows-custom-value` 为真时始终提交文本。多选时多个值以英文逗号连接。 使用 `form-value` 控制提交表单时提交选中项的 key 还是文本。默认值为 `key`;`allows-custom-value` 为真时始终提交当前输入文本。
提交层遵循本库选择类字段的统一约定:单选输出一个同名条目,多选按每个 key 输出一个同名条目(`FormData.getAll(name)` 得到数组,不再拼成逗号串);禁用或被 `disabled-keys` 禁用的项、以及从集合中删除的项都不提交;没有任何可提交值时整个字段不出现在 `FormData` 中。`form` 同时作用于可见输入与提交层,因此外部表单的校验与 reset 归属一致。
<ComponentPreview name="combo-box-form-value" /> <ComponentPreview name="combo-box-form-value" />
@@ -277,7 +279,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
### ComboBox ### ComboBox
| Prop | 类型 | 默认值 | 描述 | | Prop | 类型 | 默认值 | 描述 |
| ------------------------- | ------------------------------------------------------------ | ------------------ | --------------------------------------------------------------------------------------------- | | ------------------------- | ------------------------------------------------------------ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `input-value` | `string` | - | 当前输入值(受控,可用 `v-model:input-value`) | | `input-value` | `string` | - | 当前输入值(受控,可用 `v-model:input-value`) |
| `default-input-value` | `string` | `''` | 默认输入值(非受控) | | `default-input-value` | `string` | `''` | 默认输入值(非受控) |
| `selection-mode` | `'single' \| 'multiple'` | `'single'` | 单选或多选 | | `selection-mode` | `'single' \| 'multiple'` | `'single'` | 单选或多选 |
@@ -290,8 +292,9 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
| `disabled-keys` | `Array<string \| number>` | - | 禁用项的 key | | `disabled-keys` | `Array<string \| number>` | - | 禁用项的 key |
| `open` / `is-open` | `boolean` | - | 弹层打开状态(受控,可用 `v-model:open`) | | `open` / `is-open` | `boolean` | - | 弹层打开状态(受控,可用 `v-model:open`) |
| `default-open` | `boolean` | `false` | 弹层默认打开状态(非受控) | | `default-open` | `boolean` | `false` | 弹层默认打开状态(非受控) |
| `default-filter` | `(text: string, inputValue: string) => boolean` | 包含匹配 | 自定义过滤函数 | | `default-filter` | `(text: string, inputValue: string) => boolean` | 不区分大小写与重音的包含匹配 | 自定义过滤函数;默认谓词按 `ConfigProvider` 的 locale 折叠大小写与变音符号(`Café` 可由 `cafe` 命中) |
| `is-disabled` | `boolean` | `false` | 是否禁用 | | `is-disabled` | `boolean` | `false` | 是否禁用 |
| `disabled` | `boolean` | `false` | `is-disabled` 的等价别名 |
| `is-read-only` | `boolean` | `false` | 只读:值可聚焦但不可修改 | | `is-read-only` | `boolean` | `false` | 只读:值可聚焦但不可修改 |
| `is-required` | `boolean` | `false` | 是否必填 | | `is-required` | `boolean` | `false` | 是否必填 |
| `is-invalid` | `boolean` | `false` | 值是否无效 | | `is-invalid` | `boolean` | `false` | 值是否无效 |
@@ -307,7 +310,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
| `menu-trigger` | `'focus' \| 'input' \| 'manual'` | `'focus'` | 打开弹层的交互方式 | | `menu-trigger` | `'focus' \| 'input' \| 'manual'` | `'focus'` | 打开弹层的交互方式 |
| `should-focus-wrap` | `boolean` | `false` | 方向键是否在首尾循环 | | `should-focus-wrap` | `boolean` | `false` | 方向键是否在首尾循环 |
| `full-width` | `boolean` | `false` | 是否占满容器宽度 | | `full-width` | `boolean` | `false` | 是否占满容器宽度 |
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 视觉变体:`primary` 为默认带阴影样式;`secondary` 为低强调无阴影,适用于 Surface 内 | | `variant` | `'primary' \| 'secondary'` | `'primary'` | 视觉变体:`primary` 为默认带阴影样式;`secondary` 为低强调无阴影,适用于 Surface 内。根上的取值由内部 `Input` 继承,`Input` 自己显式设置时以子控件为准 |
| `placeholder` | `string` | `'Select an item'` | `ComboBoxValue` 的缺省占位文本(上游根上没有该 prop,由 `ComboBoxValue` 的 placeholder 表达) | | `placeholder` | `string` | `'Select an item'` | `ComboBoxValue` 的缺省占位文本(上游根上没有该 prop,由 `ComboBoxValue` 的 placeholder 表达) |
| `as` | `string` | `'div'` | 自定义根元素标签 | | `as` | `string` | `'div'` | 自定义根元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 | | `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 |
@@ -381,6 +384,8 @@ ComboBox 实现 ARIA combobox 模式:
- 中文输入法组合期间不确认选择(`isComposing` / `keyCode 229` 时忽略键盘提交) - 中文输入法组合期间不确认选择(`isComposing` / `keyCode 229` 时忽略键盘提交)
- 过滤不会清除已接受的选择;被过滤掉的已选项仍保留标签 - 过滤不会清除已接受的选择;被过滤掉的已选项仍保留标签
- 弹层内不出现第二个 Tab 入口,关闭后移除 `aria-activedescendant` - 弹层内不出现第二个 Tab 入口,关闭后移除 `aria-activedescendant`
- 组合输入期间保留已经渲染的行,直到 `compositionend` 才提交一次过滤;会话内的 `Enter` 不会确认选择(同时检查会话状态、`isComposing` 与 `keyCode 229`)
- 必填只由校验阻止无效提交,不阻止用户把值编辑为空;`native` 与 `aria` 两种校验都按同一份约束判断
- 支持禁用状态(`is-disabled` / `disabled-keys`)、输入过滤式搜索、与原生表单集成(`name` / `form` / `form-value`)与自定义值(`allows-custom-value`) - 支持禁用状态(`is-disabled` / `disabled-keys`)、输入过滤式搜索、与原生表单集成(`name` / `form` / `form-value`)与自定义值(`allows-custom-value`)
- 未实测读屏软件的变更播报与逐项读屏行为,因此不声称已通过该层验收 - 未实测读屏软件的变更播报与逐项读屏行为,因此不声称已通过该层验收
@@ -460,3 +460,94 @@ export interface CollectionOwner extends CollectionView {
- `pnpm typecheck` 通过;`pnpm test` **81 文件 / 1078 项**通过(新增 5 项:ComboBox 自定义值回车两例、两族 `data-slot` 契约、Autocomplete 示例搜索框壳层契约);`pnpm build:docs`、`pnpm build:playground`、`pnpm format`、`git diff --check` 通过。 - `pnpm typecheck` 通过;`pnpm test` **81 文件 / 1078 项**通过(新增 5 项:ComboBox 自定义值回车两例、两族 `data-slot` 契约、Autocomplete 示例搜索框壳层契约);`pnpm build:docs`、`pnpm build:playground`、`pnpm format`、`git diff --check` 通过。
- 编译 CSS 证据见 13.5,取自 `pnpm build:docs` 产物。 - 编译 CSS 证据见 13.5,取自 `pnpm build:docs` 产物。
- 浏览器复验本轮**未完成**:IAB 在 `Page.enable`(20s)与 `Runtime.evaluate`(10s)上连续超时,`browser.tabs.new()` 返回 `renderer timed out handling IAB create`;`agent.browsers.list()` 只有 IAB 一个后端,没有扩展 Chrome 可切换。因此本轮不声称已完成浏览器视觉复验;§12.3 记录的上一轮结果仍有效,但那一轮早于本轮 CSS 与自定义值修复。待 IAB 恢复后需补验三项:触发器图标打开后 180° 旋转、弹层搜索框 `secondary` 变体无阴影、自定义值回车后的展示与关闭。 - 浏览器复验本轮**未完成**:IAB 在 `Page.enable`(20s)与 `Runtime.evaluate`(10s)上连续超时,`browser.tabs.new()` 返回 `renderer timed out handling IAB create`;`agent.browsers.list()` 只有 IAB 一个后端,没有扩展 Chrome 可切换。因此本轮不声称已完成浏览器视觉复验;§12.3 记录的上一轮结果仍有效,但那一轮早于本轮 CSS 与自定义值修复。待 IAB 恢复后需补验三项:触发器图标打开后 180° 旋转、弹层搜索框 `secondary` 变体无阴影、自定义值回车后的展示与关闭。
## 14. 整批退回返修(评审 R1–R10)
评审以 `/private/tmp/B02-public-review.md` 与 30 项探针退回 B02b/B02c,指出 5 个 P1、4 个 P2 与 B02d 未完成。探针原文已固化为 `tests/b02-review.probe.test.ts`(已加入 `test:unit`),修复前 29 项失败、1 项通过,修复后 30 项全部通过。以下逐项记录"问题 → 实现位置 → 回归"。
### 14.1 R1 原生清除按钮永远提前返回(P1)
`AutocompleteClearButton` 先 `preventDefault()` 再判断 `event.defaultPrevented`,原生可取消 click 因此从不调用 `ctx.clear()`;旧测试用不可取消的 `MouseEvent` 掩盖了它。
修复:先尊重调用方取消,再 `preventDefault` + `stopPropagation`,最后执行唯一清除路径;调用方 `disable` 与根禁用任一成立时跳过。回归:探针用真实 `.click()`;`tests/autocomplete.test.ts` 新增"调用方 `preventDefault` 时不清除"。浏览器 5182:真实点击某示例("州(受控)")的清除按钮后值回到占位符「选择一个州」,按钮转为 `data-empty`。
### 14.2 R2 表单与字段协议(P1)
原实现只输出一个 `value=逗号串` 的隐藏 `input`,`isDisabled`、`disabled-keys`、删除项、`form` 归属都不成立。现在两族改为复用本库选择类字段的统一提交层(`choice/shared.ts` 的 `selectionInputs`):
- 每个可提交 key 一个同名隐藏条目,`getAll(name)` 得到数组,含逗号的 key 不再被破坏;
- 禁用字段不渲染提交层;被 `disabled-keys` 禁用的 key 不提交;
- 曾经出现在集合里、随后被删除的 key 不提交(按"seen"集合判断);从未列出的 key(受控关闭态值)按调用方给出的值提交;`Autocomplete.items` 同理;
- `ComboBox` 的 `form` 同时落到可见 `Input`(`input().form === 外部表单`)与提交层,`useChoiceForm` 与原生层共用同一归属;
- `allowsCustomValue` 的 `form-value` 恒为当前输入文本(选中 Alpha 后再输入 Custom animal,提交 `Custom animal`);
- `request([])` 不再因 `isRequired` 被拦,必填只由校验阻止无效提交。
回归:探针 6 项;`tests/combo-box.test.ts` 新增必填可清空 + `checkValidity() === false`、外部表单 `form` 关联与 reset/取消 reset、禁用字段无提交层;`tests/autocomplete.test.ts` 新增多值同名条目 + 禁用无提交;两个 demo 契约测试改为先选择再断言 `FormData`(空状态不再输出空条目)。
### 14.3 R3 ComboBox 输入同步(P1)
旧 `watch` 用 `keys.map(String).join()` + `records.length` 作依赖,且无选中项时直接 return,`displayInputValue` 又把空文本回退成旧标签。现在:选择身份按 `typeof key` 编码(`0` 与 `"0"` 不再混同),依赖同时包含选中项的 `textValue`(同长度替换也同步),受控 `inputValue` 优先(显式 `""` 显示为空),非受控文本由"接受的选择"驱动,输入清空选择时用一次性 `keepDraft` 保住草稿,`allowsCustomValue` 的草稿在无记录时不被覆盖。表单 reset 后重新取回选中项标签。
回归:探针 5 项(外部清空、数字/字符串 key、同长度标签更新、受控空文本、必填清空)+ 既有 SSR 首屏标签用例。
### 14.4 R4 组合输入(P1)
两族此前一边保存 `composing` 一边照常过滤;ComboBox 的 `keydown` 也没检查会话状态。现在:过滤文本 `filterText` 与会话分离,组合期间保留已渲染行,`compositionend` 后统一提交一次过滤与"文本不再匹配已选值"的判断;`keydown` 同时检查会话、`event.isComposing` 与 `keyCode 229`。
回归:探针 3 项(未标记 `isComposing` 的 Enter、两族组合期间不过滤)+ 两族 `compositionstart → input → compositionend` 的完整序列。
### 14.5 R5 受控关闭被拒后抢焦点(P1)
`request()` 在选择后无条件 `nextTick` 聚焦触发器,`setOpen(false)` 也立刻清理活动项。现在焦点恢复与活动项清理都移入"关闭被接受"的分支(`nextTick` 后检查 `open.value`),拒绝关闭时保留焦点、`aria-expanded` 与活动行。
回归:探针(父级拒绝关闭后 `aria-expanded` 仍为 `true`、焦点仍在搜索框)。浏览器 5182 补验:搜索框按 `Tab` 后弹层关闭且焦点落在弹层外的按钮(不回跳触发器);点击页面标题后弹层关闭、焦点留在被点击的标题上。
### 14.6 R6 组合输入覆盖 ref / ARIA / 原生禁用(P2)
- `cloneVNode` 会替换 `ref`,且 Vue 3.5 把组件 ref 存进 `{ i, r }` 持有者。新增 `mergedRef`(`combo-box/dom.ts`)同时保留调用方模板 ref 与内部节点,`Input`/`SearchFieldInput` 都改用合并 ref。
- `AutocompleteFilter` 不再无条件写根的 `aria-label`/`aria-labelledby`/`aria-describedby`:搜索输入自己声明时以它为准。
- `AutocompleteClearButton` 与 `ComboBoxTrigger` 合并调用方 `disabled` 属性,点击守卫同样读取合并后的禁用。
回归:探针 5 项(两个 ref、搜索框名称、两处 `disabled`)+ 清除按钮取消用例;`combo-box.test.ts` 覆盖 `asChild` 宿主上的事件与 ref。
### 14.7 R7 声明了但未生效的公开参数(P2)
- `asChild`:根节点改为"根元素拥有 Popover",两族都支持把首个插槽元素当根:保留其属性、事件、ref、子节点,并合并根类名与 `data-slot`;其余部件渲染在它内部。替换 `children` 时同步修正 `shapeFlag`(否则文本子节点会渲染成 `[object Object]`)。
- `autoFocus`:挂载后聚焦组合输入,禁用字段跳过。
- `ComboBox.variant`:由根继承到内部 `Input`(`hv-input--secondary`),`Input` 自己显式声明时以子控件为准。上游该 prop 只进入 context 未被消费,这里按文档语义落地并记录。
浏览器 5182:`on-surface` 示例的输入为 `hv-input--secondary`、`box-shadow` 全零;`asChild`/`autoFocus` 由 jsdom 用例覆盖。
### 14.8 R8 过滤国际化(P2)
新增 `collection/match.ts` 的 `createBaseContains(locale)`:NFKD 分解 + 去组合记号 + `toLocaleLowerCase`,按 `ConfigProvider` 的 locale 折叠大小写与变音符号。两族默认谓词改用它,`default-filter` / `filter` 仍完全接管。
回归:`Café` ← `cafe` / `CAFÉ` / 分解形式 `cafe\u0301`;自定义谓词优先级(自定义 `defaultFilter` 被调用且结果生效)。
### 14.9 R9 Autocomplete 指示器选择器不可达(P2)
上游把指示器类名、`data-slot="autocomplete-default-indicator"` 与 `data-open` 放在**同一个元素**(默认图标 svg)上,本库把它们拆在外层 span 与内层 svg。现在默认图标与自定义图标都由图标元素本身承载类名、`data-slot`(自定义时用 `autocomplete-indicator`)与 `data-open`,外层 span 退化为 `autocomplete-indicator-wrapper`。
浏览器 5182 实测:`.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]` 命中 1 个元素,计算尺寸 `16px × 16px`,展开时 `rotate: 180deg`。
### 14.10 R10 与 B02d 收尾
- `Autocomplete.items`(对应上游 `items: Iterable<T>`)已实现:驱动关闭态已选文本、`selectedItems` 与提交校验。
- 新增公开插槽状态类型 `ComboBoxState` / `ComboBoxValueState` / `AutocompleteState` / `AutocompleteValueState`、`AutocompleteItem` 与 `CollectionKey`,配合 `tests/package/b02-pickers-contract.ts` 的正反例。
- 修掉一个真实导出缺陷:`ComboBoxValue as ComboBoxValueType` 与组件 `ComboBoxValue` 同名,消费端同时导入两者时 TypeScript 会把类型别名解析成值;模型类型改为独立导出的 `ComboBoxModelValue`。
### 14.11 本轮命令与结果
- `pnpm typecheck` 通过。
- `pnpm test`:**82 文件 / 1123 项**通过(`b02-review` 探针 30 项全部通过;两族新增 21 项补充回归)。
- `pnpm test:unit`:72 文件 / 1087 项通过(探针已加入清单)。
- `pnpm build:docs`、`pnpm build:playground`、`pnpm format`、`git diff --check` 通过。
- 独立产物消费(`/private/tmp/heroui-b02-consumer`,两份 `pnpm pack` tarball + `pnpm-workspace.yaml` override):`node consume-b02-pickers.mjs` 通过(导出、SSR HTML 契约、CSS 选择器、变体函数);`tsc --strict --skipLibCheck` 在 `--module nodenext --moduleResolution nodenext` 与 `--module esnext --moduleResolution bundler` 两种模式下对 `b02-pickers-contract.ts` 均通过,`@ts-expect-error` 反例全部生效。
- 浏览器 5182(Chromium/IAB)复核:真实点击清除按钮生效;指示器与触发器图标同为 16px、展开旋转 180°;`on-surface` 输入为 `secondary` 无阴影;自定义值回车后文本保留并关闭(值写入由 jsdom 用例断言);`Tab` 与外部点击都不会回跳触发器。
### 14.12 仍未验证
- 真实系统输入法、读屏软件、逐像素视觉对比:仍只验证组合事件与状态协议。
- 独立消费工程里的**浏览器** ESM/CSS 运行(本轮只做了 node ESM + SSR + CSS 文本断言,浏览器仍不可用时不声称)。
- 弹层内浮层选项的真实鼠标点击(IAB 对 floating option 报 `not actionable`)、嵌套 Modal 内逐层 `Escape`、快速重开。
- `ComboBox.variant` 上游只进入 context 未消费,本库按文档语义实现,属记录在案的适配差异。
+10
View File
@@ -1043,3 +1043,13 @@ Tag/TagGroup/ErrorMessage 的最新验收见 [B03 复核记录](migrations/B03-r
- `pnpm typecheck` 通过;`pnpm test` **81 文件 / 1078 项**通过(比 B02c 多 5 项:ComboBox 自定义值回车两例、两族 `data-slot` 契约、Autocomplete 示例搜索框壳层契约);`pnpm build:docs`、`pnpm build:playground`、`pnpm format`、`git diff --check` 通过。 - `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)。 - 编译产物证据(`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 变体与自定义值展示。 - 浏览器复验本轮未完成: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、快速重开。
+1 -1
View File
@@ -15,7 +15,7 @@
"build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build", "build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build",
"typecheck": "vue-tsc --noEmit", "typecheck": "vue-tsc --noEmit",
"test": "vitest run", "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/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/combo-box.test.ts tests/combo-box-demos.test.ts tests/autocomplete.test.ts tests/autocomplete-demos.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/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",
"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", "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",
"format": "prettier --check .", "format": "prettier --check .",
"format:fix": "prettier --write .", "format:fix": "prettier --write .",
@@ -1,9 +1,11 @@
<script lang="ts"> <script lang="ts">
import { import {
cloneVNode,
computed, computed,
defineComponent, defineComponent,
getCurrentInstance, getCurrentInstance,
h, h,
isVNode,
mergeProps, mergeProps,
nextTick, nextTick,
provide, provide,
@@ -19,6 +21,7 @@ import {
import { autocompleteVariants } from "@heroui-vue/styles"; import { autocompleteVariants } from "@heroui-vue/styles";
import Popover from "../popover/Popover"; import Popover from "../popover/Popover";
import { import {
selectionInputs,
useChoiceField, useChoiceField,
useChoiceForm, useChoiceForm,
useChoiceValue, useChoiceValue,
@@ -37,16 +40,16 @@ import {
type OwnedCollection, type OwnedCollection,
} from "../collection/owner"; } from "../collection/owner";
import { planCollectionItems } from "../combo-box/metadata"; import { planCollectionItems } from "../combo-box/metadata";
import { createBaseContains } from "../collection/match";
import { SHAPE_ARRAY_CHILDREN, SHAPE_TEXT_CHILDREN } from "../combo-box/dom";
import { useConfig } from "../../providers/context";
import { import {
autocompleteKey, autocompleteKey,
type AutocompleteItem,
type AutocompleteValue as AutocompleteValueType, type AutocompleteValue as AutocompleteValueType,
} from "./context"; } from "./context";
const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"]; const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"];
const contains = (text: string, inputValue: string) =>
!inputValue ||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
export default defineComponent({ export default defineComponent({
name: "Autocomplete", name: "Autocomplete",
inheritAttrs: false, inheritAttrs: false,
@@ -73,6 +76,7 @@ export default defineComponent({
type: String as PropType<"single" | "multiple">, type: String as PropType<"single" | "multiple">,
default: "single", default: "single",
}, },
items: Array as PropType<readonly AutocompleteItem[]>,
disabledKeys: Array as PropType<readonly CollectionKey[]>, disabledKeys: Array as PropType<readonly CollectionKey[]>,
open: { type: Boolean, default: undefined }, open: { type: Boolean, default: undefined },
isOpen: { type: Boolean, default: undefined }, isOpen: { type: Boolean, default: undefined },
@@ -106,6 +110,7 @@ export default defineComponent({
}, },
setup(props, { attrs, slots, emit, expose }) { setup(props, { attrs, slots, emit, expose }) {
const instance = getCurrentInstance()!; const instance = getCurrentInstance()!;
const contains = createBaseContains(useConfig()?.locale.value);
const present = (keys: string[]) => const present = (keys: string[]) =>
keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key)); keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key));
const model = useChoiceValue<AutocompleteValueType | undefined>( const model = useChoiceValue<AutocompleteValueType | undefined>(
@@ -160,11 +165,22 @@ export default defineComponent({
discovered.value = next; discovered.value = next;
}); });
const records = computed<CollectionRecord[]>(() => { const records = computed<CollectionRecord[]>(() => {
const base = complete.value const explicit = props.items?.map((item) => {
if (item.id === undefined || item.id === null)
throw new TypeError("Autocomplete items need an id.");
return {
key: item.id,
text: item.textValue,
disabled: !!item.isDisabled,
} satisfies CollectionRecord;
});
const base =
explicit ??
(complete.value
? planned.value ? planned.value
: discovered.value.length : discovered.value.length
? discovered.value ? discovered.value
: planned.value; : planned.value);
const disabledKeys = props.disabledKeys ?? []; const disabledKeys = props.disabledKeys ?? [];
return base.map((record) => ({ return base.map((record) => ({
...record, ...record,
@@ -178,6 +194,8 @@ export default defineComponent({
const valueId = `hv-autocomplete-${uid}-value`; const valueId = `hv-autocomplete-${uid}-value`;
const filterText = ref(""); const filterText = ref("");
/** Open composition session in the popover search box. */
const composing = ref(false);
const filterPredicate = ref<(text: string, input: string) => boolean>(); const filterPredicate = ref<(text: string, input: string) => boolean>();
const filter = (record: CollectionRecord) => const filter = (record: CollectionRecord) =>
(filterPredicate.value ?? contains)(record.text, filterText.value); (filterPredicate.value ?? contains)(record.text, filterText.value);
@@ -222,12 +240,8 @@ export default defineComponent({
model.request( model.request(
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null), props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
); );
if (props.selectionMode === "single") { // Focus restoration belongs to the close that the parent actually accepts.
setOpen(false); if (props.selectionMode === "single") setOpen(false);
void nextTick(() =>
triggerElement.value?.focus({ preventScroll: true }),
);
}
} }
function setOpen(next: boolean) { function setOpen(next: boolean) {
@@ -254,8 +268,10 @@ export default defineComponent({
filterInput.value?.focus({ preventScroll: true }); filterInput.value?.focus({ preventScroll: true });
}); });
} else { } else {
activeKey.value = undefined;
void nextTick(() => { void nextTick(() => {
// A rejected close keeps the row, the focus and the ARIA state intact.
if (open.value) return;
activeKey.value = undefined;
if ( if (
filterInput.value?.ownerDocument.activeElement === filterInput.value?.ownerDocument.activeElement ===
filterInput.value || filterInput.value ||
@@ -319,10 +335,22 @@ export default defineComponent({
}), }),
); );
const invalid = computed(() => field.field.invalid.value); const invalid = computed(() => field.field.invalid.value);
const formValueText = computed<string | undefined>(() => { /** Keys still backed by an enabled record: a removed item is not submitted. */
if (!props.name) return undefined; // Keys the collection has ever offered. A key that disappeared from the
return keys.value.length ? keys.value.map(String).join(",") : undefined; // collection was removed and must not submit; a key that was never listed
// (closed-state or caller-owned value) is trusted.
const seenKeys = ref(new Set<string>());
watchEffect(() => {
for (const record of records.value)
seenKeys.value.add(`${typeof record.key}\u0001${String(record.key)}`);
}); });
const successfulKeys = computed(() =>
keys.value.filter((key) => {
const record = records.value.find((item) => item.key === key);
if (record) return !record.disabled;
return !seenKeys.value.has(`${typeof key}\u0001${String(key)}`);
}),
);
provide(collectionOwnerKey, { provide(collectionOwnerKey, {
keys, keys,
@@ -376,6 +404,7 @@ export default defineComponent({
onKeydown: (event: KeyboardEvent) => { onKeydown: (event: KeyboardEvent) => {
if ( if (
event.defaultPrevented || event.defaultPrevented ||
composing.value ||
event.isComposing || event.isComposing ||
event.keyCode === 229 event.keyCode === 229
) )
@@ -451,7 +480,7 @@ export default defineComponent({
setActive, setActive,
confirmActive, confirmActive,
clear, clear,
formValueText, composing,
}); });
useChoiceForm( useChoiceForm(
@@ -522,47 +551,60 @@ export default defineComponent({
continue; continue;
restAttrs[key] = value; restAttrs[key] = value;
} }
return h( const rootProps = mergeProps(restAttrs, {
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{
default: () =>
h(
props.as,
mergeProps(restAttrs, {
class: [slotsBase.value.base(), attrs.class], class: [slotsBase.value.base(), attrs.class],
style: attrs.style, style: attrs.style,
"data-slot": "autocomplete", "data-slot": "autocomplete",
"data-invalid": invalid.value || undefined, "data-invalid": invalid.value || undefined,
"data-disabled": field.field.disabled.value || undefined, "data-disabled": field.field.disabled.value || undefined,
}), });
[ const formLayer = [
...nodes, selectionInputs({
props.name
? h("input", {
type: "hidden",
name: props.name, name: props.name,
form: props.form, form: props.form,
value: formValueText.value ?? "", multiple: props.selectionMode === "multiple",
"data-slot": "autocomplete-form-value", disabled: field.field.disabled.value,
}) keys: successfulKeys.value,
: null, slot: "autocomplete-form-value",
}),
validationInput( validationInput(
proxy, proxy,
props, props,
field.field.disabled.value, field.field.disabled.value,
field.behavior.value, field.behavior.value,
(event) => (event) =>
field.invalidEvent(event, () => field.invalidEvent(event, () => triggerElement.value?.focus()),
triggerElement.value?.focus(),
),
props.isRequired && field.behavior.value === "native", props.isRequired && field.behavior.value === "native",
keys.value.length > 0, keys.value.length > 0,
), ),
], ];
), const popover = (inner: VNodeChild[]) =>
}, h(
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{ default: () => [...inner, ...formLayer] },
); );
if (!props.asChild) return h(props.as, rootProps, [popover(nodes)]);
const [host, ...rest] = nodes;
if (!isVNode(host) || typeof host.type !== "string")
return h(props.as, rootProps, [popover(nodes)]);
// `as-child`: the caller's element is the picker root and keeps its own
// attributes, events, children and ref.
const inner = host.children;
const hostChildren = Array.isArray(inner)
? (inner as VNodeChild[])
: inner == null
? []
: [inner as VNodeChild];
const clone = cloneVNode(host, mergeProps(host.props ?? {}, rootProps));
// `children` is replaced, so the shape flag must stop claiming text.
clone.children = [
popover([...hostChildren, ...rest]),
] as typeof clone.children;
clone.shapeFlag =
(clone.shapeFlag & ~SHAPE_TEXT_CHILDREN) | SHAPE_ARRAY_CHILDREN;
return clone;
}; };
}, },
}); });
@@ -10,10 +10,17 @@ export default defineComponent({
setup(_props, { attrs, slots }) { setup(_props, { attrs, slots }) {
const ctx = useAutocomplete(); const ctx = useAutocomplete();
const empty = () => ctx.keys.value.length === 0; const empty = () => ctx.keys.value.length === 0;
const callerDisabled = () =>
attrs.disabled !== undefined && attrs.disabled !== false
? true
: undefined;
function click(event: MouseEvent) { function click(event: MouseEvent) {
// Caller cancellation is checked before we cancel the default ourselves,
// otherwise a native click would always look pre-cancelled.
if (event.defaultPrevented) return;
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (event.defaultPrevented) return; if (callerDisabled() || ctx.disabled.value) return;
ctx.clear(); ctx.clear();
} }
return () => { return () => {
@@ -54,7 +61,7 @@ export default defineComponent({
"data-slot": "autocomplete-clear-button", "data-slot": "autocomplete-clear-button",
"data-empty": empty() || undefined, "data-empty": empty() || undefined,
"aria-hidden": empty() || undefined, "aria-hidden": empty() || undefined,
disabled: ctx.disabled.value || undefined, disabled: ctx.disabled.value || callerDisabled() || undefined,
onClick: click, onClick: click,
}; };
return h("button", mergeProps(attrs, injected), [icon]); return h("button", mergeProps(attrs, injected), [icon]);
@@ -19,7 +19,7 @@ import {
} from "vue"; } from "vue";
import { useChoiceValue } from "../choice/shared"; import { useChoiceValue } from "../choice/shared";
import { useAutocomplete } from "./context"; import { useAutocomplete } from "./context";
import { elementFromRef } from "../combo-box/dom"; import { elementFromRef, mergedRef } from "../combo-box/dom";
function componentName(node: VNode): string | undefined { function componentName(node: VNode): string | undefined {
const type = node.type as Record<string, unknown> | undefined; const type = node.type as Record<string, unknown> | undefined;
@@ -52,27 +52,54 @@ export default defineComponent({
); );
const text = () => model.value.value ?? ""; const text = () => model.value.value ?? "";
const root = ref<HTMLElement>(); const root = ref<HTMLElement>();
/** While a composition session is open the collection keeps its rows. */
const composing = ref(false);
watchEffect(() => { watchEffect(() => {
ctx.filterText.value = text();
ctx.filterPredicate.value = props.filter; ctx.filterPredicate.value = props.filter;
ctx.composing.value = composing.value;
// Mid-composition text stays visible without filtering the collection.
if (!composing.value) ctx.filterText.value = text();
}); });
function commitComposition() {
composing.value = false;
ctx.composing.value = false;
ctx.filterText.value = text();
}
function compose(nodes: VNodeChild[]): VNodeChild[] { function compose(nodes: VNodeChild[]): VNodeChild[] {
return nodes.map((child) => { return nodes.map((child) => {
if (!isVNode(child)) return child; if (!isVNode(child)) return child;
const name = componentName(child); const name = componentName(child);
if (name === "ListBox") return child; if (name === "ListBox") return child;
if (name === "SearchFieldInput") if (name === "SearchFieldInput") {
return cloneVNode(child, { const own = (child.props ?? {}) as Record<string, unknown>;
const injected: Record<string, unknown> = {
...ctx.core(), ...ctx.core(),
modelValue: text(), modelValue: text(),
"onUpdate:modelValue": (next: string) => model.request(next), "onUpdate:modelValue": (next: string) => model.request(next),
ref: (instance: unknown) => { onCompositionstart: () => {
composing.value = true;
},
onCompositionend: () => commitComposition(),
// cloneVNode only honours a ref passed through its extra props.
ref: mergedRef(child.ref, (instance: unknown) => {
ctx.filterInput.value = elementFromRef(instance) as ctx.filterInput.value = elementFromRef(instance) as
HTMLInputElement | undefined; HTMLInputElement | undefined;
}, }),
}); };
// The search input's own accessible name and description win over the
// picker root's: the trigger name is not a name for this control.
for (const key of [
"aria-label",
"aria-labelledby",
"aria-describedby",
]) {
if (own[key] !== undefined) delete injected[key];
}
return cloneVNode(child, injected);
}
const children = child.children; const children = child.children;
if (Array.isArray(children)) { if (Array.isArray(children)) {
const clone = cloneVNode(child); const clone = cloneVNode(child);
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
/** Decorative chevron: the trigger itself owns activation. */ /** Decorative chevron: the trigger itself owns activation. */
import { defineComponent, h, mergeProps } from "vue"; import { cloneVNode, defineComponent, h, isVNode, mergeProps } from "vue";
import { useAutocomplete } from "./context"; import { useAutocomplete } from "./context";
const CHEVRON_PATH = const CHEVRON_PATH =
"M2.97 5.47a.75.75 0 0 1 1.06 0L8 9.44l3.97-3.97a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 0 1 0-1.06"; "M2.97 5.47a.75.75 0 0 1 1.06 0L8 9.44l3.97-3.97a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 0 1 0-1.06";
@@ -12,14 +12,28 @@ export default defineComponent({
const ctx = useAutocomplete(); const ctx = useAutocomplete();
return () => { return () => {
const custom = slots.default?.() ?? []; const custom = slots.default?.() ?? [];
const indicatorClass = ctx.slots.value.indicator();
const openAttr = ctx.open.value || undefined;
// The baseline puts the indicator class, `data-slot` and `data-open` on the
// same element (the icon), which is what the ported CSS selects.
const icon = const icon =
custom.length > 0 custom.length > 0
? custom ? custom.map((node) =>
isVNode(node)
? cloneVNode(node, {
class: [indicatorClass, node.props?.class],
"data-slot": "autocomplete-indicator",
"data-open": openAttr,
})
: node,
)
: [ : [
h( h(
"svg", "svg",
{ {
"aria-hidden": "true", "aria-hidden": "true",
class: indicatorClass,
"data-open": openAttr,
"data-slot": "autocomplete-default-indicator", "data-slot": "autocomplete-default-indicator",
fill: "none", fill: "none",
height: 16, height: 16,
@@ -41,9 +55,7 @@ export default defineComponent({
"span", "span",
mergeProps(attrs, { mergeProps(attrs, {
"aria-hidden": "true", "aria-hidden": "true",
class: ctx.slots.value.indicator(), "data-slot": "autocomplete-indicator-wrapper",
"data-slot": "autocomplete-indicator",
"data-open": ctx.open.value || undefined,
}), }),
icon, icon,
); );
@@ -33,6 +33,26 @@ export interface AutocompleteOptions {
as?: string; as?: string;
asChild?: boolean; 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 { export interface AutocompleteContext {
field: ReturnType<typeof useChoiceField<AutocompleteValue>>; field: ReturnType<typeof useChoiceField<AutocompleteValue>>;
slots: ComputedRef<ReturnType<typeof autocompleteVariants>>; slots: ComputedRef<ReturnType<typeof autocompleteVariants>>;
@@ -64,7 +84,7 @@ export interface AutocompleteContext {
setActive: (key: CollectionKey | undefined) => Promise<void>; setActive: (key: CollectionKey | undefined) => Promise<void>;
confirmActive: () => void; confirmActive: () => void;
clear: () => void; clear: () => void;
formValueText: ComputedRef<string | undefined>; composing: Ref<boolean>;
} }
export const autocompleteKey: InjectionKey<AutocompleteContext> = export const autocompleteKey: InjectionKey<AutocompleteContext> =
Symbol("hv-autocomplete"); Symbol("hv-autocomplete");
@@ -32,6 +32,7 @@ import {
type ValidateResult, type ValidateResult,
type ValidationBehavior, type ValidationBehavior,
} from "../field/context"; } from "../field/context";
import type { CollectionKey } from "../collection/keys";
import { useInheritedDisabled } from "../field/disabled"; import { useInheritedDisabled } from "../field/disabled";
export interface ChoiceFieldProps { export interface ChoiceFieldProps {
@@ -301,6 +302,51 @@ export function useChoiceForm(
onBeforeUnmount(() => owner?.removeEventListener("reset", onReset)); 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( export function validationInput(
input: Ref<HTMLInputElement | undefined>, input: Ref<HTMLInputElement | undefined>,
props: ChoiceFieldProps, props: ChoiceFieldProps,
@@ -0,0 +1,15 @@
/**
* Case- and accent-insensitive substring match, the equivalent of ICU
* "base" sensitivity for search: `Café` matches `cafe`, `STRASSE` matches
* `strasse` after compatibility normalisation.
*/
const fold = (value: string) => value.normalize("NFKD").replace(/\p{Mn}/gu, "");
export function createBaseContains(locale?: string) {
return (text: string, query: string) => {
if (!query) return true;
return fold(text)
.toLocaleLowerCase(locale)
.includes(fold(query).toLocaleLowerCase(locale));
};
}
@@ -1,11 +1,15 @@
<script lang="ts"> <script lang="ts">
import { import {
cloneVNode,
computed, computed,
defineComponent, defineComponent,
getCurrentInstance, getCurrentInstance,
h, h,
isVNode,
mergeProps, mergeProps,
nextTick, nextTick,
onBeforeUpdate,
onMounted,
provide, provide,
ref, ref,
shallowRef, shallowRef,
@@ -14,15 +18,19 @@ import {
watchEffect, watchEffect,
type PropType, type PropType,
type SlotsType, type SlotsType,
type VNode,
type VNodeChild, type VNodeChild,
} from "vue"; } from "vue";
import { comboBoxVariants } from "@heroui-vue/styles"; import { comboBoxVariants } from "@heroui-vue/styles";
import Popover from "../popover/Popover"; import Popover from "../popover/Popover";
import { import {
selectionInputs,
useChoiceField, useChoiceField,
useChoiceForm, useChoiceForm,
useChoiceValue, useChoiceValue,
} from "../choice/shared"; } from "../choice/shared";
import { useConfig } from "../../providers/context";
import { createBaseContains } from "../collection/match";
import { disabledContextKey } from "../field/disabled"; import { disabledContextKey } from "../field/disabled";
import { fieldContextKey, type FieldContext } from "../field/context"; import { fieldContextKey, type FieldContext } from "../field/context";
import type { ValidateResult, ValidationBehavior } from "../field/context"; import type { ValidateResult, ValidationBehavior } from "../field/context";
@@ -33,6 +41,7 @@ import {
type OwnedCollection, type OwnedCollection,
} from "../collection/owner"; } from "../collection/owner";
import { planCollectionItems } from "./metadata"; import { planCollectionItems } from "./metadata";
import { SHAPE_ARRAY_CHILDREN, SHAPE_TEXT_CHILDREN } from "./dom";
import { import {
comboBoxKey, comboBoxKey,
type ComboBoxItem, type ComboBoxItem,
@@ -40,10 +49,6 @@ import {
type ComboBoxValue, type ComboBoxValue,
} from "./context"; } from "./context";
const contains = (text: string, inputValue: string) =>
!inputValue ||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
export default defineComponent({ export default defineComponent({
name: "ComboBox", name: "ComboBox",
inheritAttrs: false, inheritAttrs: false,
@@ -133,6 +138,7 @@ export default defineComponent({
}, },
setup(props, { attrs, slots, emit, expose }) { setup(props, { attrs, slots, emit, expose }) {
const instance = getCurrentInstance()!; const instance = getCurrentInstance()!;
const contains = createBaseContains(useConfig()?.locale.value);
const present = (keys: string[]) => const present = (keys: string[]) =>
keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key)); keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key));
const readValue = (): ComboBoxValue | undefined => { const readValue = (): ComboBoxValue | undefined => {
@@ -240,8 +246,8 @@ export default defineComponent({
const filter = (record: CollectionRecord) => const filter = (record: CollectionRecord) =>
props.defaultFilter props.defaultFilter
? props.defaultFilter(record.text, inputValue.value) ? props.defaultFilter(record.text, filterText.value)
: contains(record.text, inputValue.value); : contains(record.text, filterText.value);
const instanceId = useId(); const instanceId = useId();
const inputId = `hv-combo-box-${instanceId}-input`; const inputId = `hv-combo-box-${instanceId}-input`;
@@ -269,6 +275,10 @@ export default defineComponent({
const keyboardIntent = ref(true); const keyboardIntent = ref(true);
const activeKey = ref<CollectionKey>(); const activeKey = ref<CollectionKey>();
/** Open composition session: filtering waits for `compositionend`. */
const composing = ref(false);
/** Text the collection is actually filtered by. */
const filterText = ref("");
const cursor = ref<CollectionKey>(); const cursor = ref<CollectionKey>();
const inputElement = ref<HTMLInputElement>(); const inputElement = ref<HTMLInputElement>();
const triggerElement = ref<HTMLElement>(); const triggerElement = ref<HTMLElement>();
@@ -298,13 +308,8 @@ export default defineComponent({
) )
return; return;
if (!next.length && !keys.value.length) return; if (!next.length && !keys.value.length) return;
if ( // Validation blocks an invalid submit; it must not stop the user from
!next.length && // editing a required field back to empty.
!props.allowsCustomValue &&
!props.allowsEmptyCollection &&
(props.isRequired || field.field.required.value)
)
return;
field.edit(); field.edit();
model.request( model.request(
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null), props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
@@ -401,40 +406,52 @@ export default defineComponent({
request([key]); request([key]);
} }
const composing = ref(false); const selectedRecord = computed(() =>
props.selectionMode === "single"
? records.value.find((record) => keys.value.includes(record.key))
: undefined,
);
const selectionIdentity = computed(() =>
keys.value
.map((key) => `${typeof key}\u0001${String(key)}`)
.join("\u0000"),
);
const inputControlled = ref(present(["inputValue", "input-value"]));
onBeforeUpdate(() => {
inputControlled.value = present(["inputValue", "input-value"]);
});
/** Set while a typed draft is allowed to outlive the cleared selection. */
let keepDraft = false;
watch( watch(
// A selection change (initial, external or accepted) owns the single-select // A selection change (initial, external or accepted) owns the single-select
// text; typing inside an allows-custom-value combo must not be overwritten. // text. The identity keeps `0` and `"0"` apart, and the label is watched
() => `${keys.value.map(String).join("\u0000")}|${records.value.length}`, // directly so an edited textValue re-syncs without a count change.
[selectionIdentity, () => selectedRecord.value?.text],
() => { () => {
if (props.selectionMode !== "single") return; if (props.selectionMode !== "single" || inputControlled.value) return;
const selected = records.value.find((record) => if (keepDraft) {
keys.value.includes(record.key), keepDraft = false;
); return;
if (!selected) return; }
if (inputValue.value !== selected.text) syncAcceptedText();
inputModel.request(selected.text);
}, },
{ immediate: true }, { immediate: true },
); );
/** /**
* The visible text falls back to the accepted item's label so an initial or * Visible text. A controlled `inputValue` wins even when empty; otherwise an
* external selection is readable on the very first render (including SSR), * explicit draft wins, and with no draft the accepted item's label is read at
* before the selection-sync watcher has run. * render time so the first SSR paint already shows the selection.
*/ */
const displayInputValue = computed(() => { const displayInputValue = computed(() => {
if (inputControlled.value) return inputValue.value;
if (inputValue.value) return inputValue.value; if (inputValue.value) return inputValue.value;
if (props.selectionMode !== "single") return ""; return selectedRecord.value?.text ?? "";
const selected = records.value.find((record) =>
keys.value.includes(record.key),
);
return selected?.text ?? "";
}); });
function setInputValue(next: string) { function applyInput(next: string) {
inputModel.request(next); filterText.value = next;
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
// Keep the active row on the first match of the new filter. // Keep the active row on the first match of the new filter.
if (next) { if (next) {
const first = records.value.find( const first = records.value.find(
@@ -450,12 +467,32 @@ export default defineComponent({
const selected = records.value.find((record) => const selected = records.value.find((record) =>
keys.value.includes(record.key), keys.value.includes(record.key),
); );
if (selected && next !== selected.text) request([]); if (selected && next !== selected.text) {
// Dropping the no-longer-matching selection must not erase the draft.
keepDraft = true;
request([]);
void nextTick(() => {
keepDraft = false;
});
}
} }
} }
function setInputValue(next: string) {
inputModel.request(next);
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
// Mid-composition text must stay visible without filtering the collection.
if (composing.value) return;
applyInput(next);
}
function keydown(event: KeyboardEvent) { function keydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.isComposing || event.keyCode === 229) if (
event.defaultPrevented ||
composing.value ||
event.isComposing ||
event.keyCode === 229
)
return; return;
if (field.field.disabled.value || field.field.readOnly.value) return; if (field.field.disabled.value || field.field.readOnly.value) return;
keyboardIntent.value = true; keyboardIntent.value = true;
@@ -501,6 +538,11 @@ export default defineComponent({
if (props.menuTrigger === "focus") setOpen(true); if (props.menuTrigger === "focus") setOpen(true);
} }
onMounted(() => {
if (!props.autoFocus || field.field.disabled.value) return;
inputElement.value?.focus({ preventScroll: true });
});
function describedBy() { function describedBy() {
return field.describedBy(); return field.describedBy();
} }
@@ -576,6 +618,7 @@ export default defineComponent({
required: required:
(field.behavior.value === "native" && field.field.required.value) || (field.behavior.value === "native" && field.field.required.value) ||
undefined, undefined,
form: props.form,
onKeydown: keydown, onKeydown: keydown,
onFocus: focusInput, onFocus: focusInput,
onCompositionstart: () => { onCompositionstart: () => {
@@ -583,6 +626,7 @@ export default defineComponent({
}, },
onCompositionend: () => { onCompositionend: () => {
composing.value = false; composing.value = false;
applyInput(inputValue.value);
}, },
}); });
@@ -621,8 +665,17 @@ export default defineComponent({
formValueText, formValueText,
invalid, invalid,
disabled: field.field.disabled, disabled: field.field.disabled,
variant: () => props.variant,
}); });
function syncAcceptedText() {
if (props.selectionMode !== "single" || inputControlled.value) return;
const next =
selectedRecord.value?.text ??
(props.allowsCustomValue ? (inputModel.value.value ?? "") : "");
if (inputModel.value.value !== next) inputModel.request(next);
}
useChoiceForm( useChoiceForm(
inputElement, inputElement,
() => { () => {
@@ -630,6 +683,8 @@ export default defineComponent({
inputModel.reset(); inputModel.reset();
field.reset(); field.reset();
setOpen(false); setOpen(false);
// Restore the accepted item's label, not the empty raw input default.
void nextTick(syncAcceptedText);
}, },
() => { () => {
field.validity(inputElement.value); field.validity(inputElement.value);
@@ -653,6 +708,74 @@ export default defineComponent({
if (!eligibleRecords.length) setOpen(false); if (!eligibleRecords.length) setOpen(false);
}); });
/** Keys still backed by an enabled record: removed items are not submitted. */
// Keys the collection has ever offered. A key that disappeared from the
// collection was removed and must not submit; a key that was never listed
// (closed-state or caller-owned value) is trusted.
const seenKeys = ref(new Set<string>());
watchEffect(() => {
for (const record of records.value)
seenKeys.value.add(`${typeof record.key}\u0001${String(record.key)}`);
});
const successfulKeys = computed(() =>
keys.value.filter((key) => {
const record = records.value.find((item) => item.key === key);
if (record) return !record.disabled;
return !seenKeys.value.has(`${typeof key}\u0001${String(key)}`);
}),
);
const submitText = computed<string | undefined>(() => {
if (!props.name) return undefined;
if (props.allowsCustomValue) return inputValue.value;
if (props.formValue !== "text") return undefined;
return successfulKeys.value
.map((key) => records.value.find((item) => item.key === key)?.text)
.filter((text): text is string => Boolean(text))
.join(",");
});
/**
* The picker root element owns the popover, so the component has a single
* root node and `as-child` can hand it to the caller's element.
*/
function renderRoot(nodes: VNodeChild[], formLayer: VNode | null) {
const rootProps = mergeProps(attrs, {
class: slotsBase.value.base(),
style: attrs.style,
"data-slot": "combo-box",
"data-invalid": invalid.value || undefined,
"data-disabled": field.field.disabled.value || undefined,
});
const popover = (inner: VNodeChild[]) =>
h(
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{ default: () => [...inner, formLayer] },
);
if (!props.asChild) return h(props.as, rootProps, [popover(nodes)]);
const [host, ...rest] = nodes;
if (!isVNode(host) || typeof host.type !== "string")
return h(props.as, rootProps, [popover(nodes)]);
// `as-child`: the caller's single root element becomes the picker root and
// keeps its own attributes, events, children and ref.
const inner = host.children;
const hostChildren = Array.isArray(inner)
? (inner as VNodeChild[])
: inner == null
? []
: [inner as VNodeChild];
const clone = cloneVNode(host, mergeProps(host.props ?? {}, rootProps));
// `children` is replaced, so the shape flag must stop claiming text.
clone.children = [
popover([...hostChildren, ...rest]),
] as typeof clone.children;
clone.shapeFlag =
(clone.shapeFlag & ~SHAPE_TEXT_CHILDREN) | SHAPE_ARRAY_CHILDREN;
return clone;
}
expose({ expose({
element: () => anchor?.(), element: () => anchor?.(),
input: inputElement, input: inputElement,
@@ -680,35 +803,16 @@ export default defineComponent({
planned.value = plan.records; planned.value = plan.records;
complete.value = plan.complete; complete.value = plan.complete;
const nodes = field.prepare(children, true); const nodes = field.prepare(children, true);
return h( const formLayer = selectionInputs({
Popover,
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
{
default: () =>
h(
props.as,
mergeProps(attrs, {
class: slotsBase.value.base(),
style: attrs.style,
"data-slot": "combo-box",
"data-invalid": invalid.value || undefined,
"data-disabled": field.field.disabled.value || undefined,
}),
[
...nodes,
props.name
? h("input", {
type: "hidden",
name: props.name, name: props.name,
form: props.form, form: props.form,
value: formValueText.value ?? "", multiple: props.selectionMode === "multiple",
"data-slot": "combo-box-form-value", disabled: field.field.disabled.value,
}) keys: successfulKeys.value,
: null, text: submitText.value,
], slot: "combo-box-form-value",
), });
}, return renderRoot(nodes, formLayer);
);
}; };
}, },
}); });
@@ -20,7 +20,7 @@ import {
} from "vue"; } from "vue";
import { injectPopoverRootContext } from "reka-ui"; import { injectPopoverRootContext } from "reka-ui";
import { useComboBox } from "./context"; import { useComboBox } from "./context";
import { elementFromRef } from "./dom"; import { elementFromRef, mergedRef } from "./dom";
function componentName(node: VNode): string | undefined { function componentName(node: VNode): string | undefined {
const type = node.type as Record<string, unknown> | undefined; const type = node.type as Record<string, unknown> | undefined;
@@ -60,15 +60,23 @@ export default defineComponent({
function compose(node: VNodeChild): VNodeChild { function compose(node: VNodeChild): VNodeChild {
if (!isVNode(node) || componentName(node) !== "Input") return node; if (!isVNode(node) || componentName(node) !== "Input") return node;
return cloneVNode(node, { const own = (node.props ?? {}) as Record<string, unknown>;
const injected: Record<string, unknown> = {
...ctx.inputProps(), ...ctx.inputProps(),
modelValue: ctx.displayInputValue.value, modelValue: ctx.displayInputValue.value,
"onUpdate:modelValue": (next: string) => ctx.setInputValue(next), "onUpdate:modelValue": (next: string) => ctx.setInputValue(next),
ref: (instance: unknown) => { // The root variant is inherited; an explicit Input variant still wins.
variant: own.variant ?? ctx.variant(),
// cloneVNode only honours a ref passed through its extra props, so the
// caller's template ref and ours are merged here.
ref: mergedRef(node.ref, (instance: unknown) => {
ctx.inputElement.value = elementFromRef(instance) as ctx.inputElement.value = elementFromRef(instance) as
HTMLInputElement | undefined; HTMLInputElement | undefined;
}, }),
}); };
for (const key of Object.keys(injected))
if (injected[key] === undefined) delete injected[key];
return cloneVNode(node, injected);
} }
return () => { return () => {
@@ -11,7 +11,13 @@ export default defineComponent({
props: { isDisabled: { type: Boolean, default: false } }, props: { isDisabled: { type: Boolean, default: false } },
setup(props, { attrs, slots }) { setup(props, { attrs, slots }) {
const ctx = useComboBox(); const ctx = useComboBox();
const disabled = () => props.isDisabled || ctx.disabled.value; // `disabled` may arrive as an attribute (`<ComboBoxTrigger disabled />`).
const callerDisabled = () =>
attrs.disabled !== undefined && attrs.disabled !== false
? true
: undefined;
const disabled = () =>
props.isDisabled || ctx.disabled.value || callerDisabled() === true;
function toggle(event: MouseEvent) { function toggle(event: MouseEvent) {
if (event.defaultPrevented || disabled()) return; if (event.defaultPrevented || disabled()) return;
ctx.setOpen(!ctx.open.value); ctx.setOpen(!ctx.open.value);
@@ -51,6 +57,7 @@ export default defineComponent({
"data-slot": "combo-box-trigger", "data-slot": "combo-box-trigger",
tabindex: -1, tabindex: -1,
disabled: disabled() || undefined, disabled: disabled() || undefined,
"aria-disabled": undefined,
"aria-label": "aria-label":
typeof attrs["aria-label"] === "string" typeof attrs["aria-label"] === "string"
? attrs["aria-label"] ? attrs["aria-label"]
@@ -11,6 +11,18 @@ export interface ComboBoxItem {
textValue: string; textValue: string;
isDisabled?: boolean; 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 { export interface ComboBoxSelectedItem {
key: CollectionKey; key: CollectionKey;
textValue: string; textValue: string;
@@ -78,6 +90,7 @@ export interface ComboBoxContext {
/** ARIA plus input handlers injected onto the composed `Input`. */ /** ARIA plus input handlers injected onto the composed `Input`. */
inputProps: () => Record<string, unknown>; inputProps: () => Record<string, unknown>;
formValueText: ComputedRef<string | undefined>; formValueText: ComputedRef<string | undefined>;
variant: () => "primary" | "secondary";
invalid: ComputedRef<boolean>; invalid: ComputedRef<boolean>;
disabled: ComputedRef<boolean>; disabled: ComputedRef<boolean>;
} }
@@ -5,3 +5,35 @@ export function elementFromRef(value: unknown): HTMLElement | undefined {
const element = (value as { $el?: unknown } | null)?.$el; const element = (value as { $el?: unknown } | null)?.$el;
return element instanceof Element ? (element as HTMLElement) : undefined; return element instanceof Element ? (element as HTMLElement) : undefined;
} }
/**
* Keep both the caller's template ref and our internal one. Vue replaces a
* cloned vnode's ref, so the merge has to happen here; Vue 3.5 also stores
* component refs inside a `{ i, r }` holder that must be unwrapped.
*/
export function mergedRef(...refs: unknown[]) {
const assign = (ref: unknown, instance: unknown) => {
if (!ref) return;
if (typeof ref === "function") {
ref(instance);
return;
}
if (typeof ref !== "object") return;
if ("value" in (ref as object)) {
(ref as { value: unknown }).value = instance;
return;
}
const inner = (ref as { r?: unknown }).r;
if (inner !== undefined) assign(inner, instance);
};
return (instance: unknown) => {
for (const ref of refs) assign(ref, instance);
};
}
/**
* 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;
+12 -1
View File
@@ -971,12 +971,18 @@ export type {
ComboBoxValueProps, ComboBoxValueProps,
ComboBoxPopoverProps, ComboBoxPopoverProps,
} from "./types"; } from "./types";
export type { CollectionKey } from "./components/collection/keys";
export type { export type {
ComboBoxItem, ComboBoxItem,
ComboBoxValue as ComboBoxValueType,
ComboBoxMenuTrigger, ComboBoxMenuTrigger,
ComboBoxOptions, ComboBoxOptions,
ComboBoxState,
ComboBoxValueState,
} from "./components/combo-box/context"; } 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 { comboBoxVariants, type ComboBoxVariants } from "@heroui-vue/styles";
@@ -996,6 +1002,11 @@ export type {
AutocompletePopoverProps, AutocompletePopoverProps,
AutocompleteFilterProps, AutocompleteFilterProps,
} from "./types"; } from "./types";
export type {
AutocompleteItem,
AutocompleteState,
AutocompleteValueState,
} from "./components/autocomplete/context";
export type { export type {
AutocompleteSelectedItem, AutocompleteSelectedItem,
AutocompleteOptions, AutocompleteOptions,
+12 -11
View File
@@ -179,19 +179,20 @@ describe("Autocomplete docs and demos", () => {
mounted.push(wrapper); mounted.push(wrapper);
await nextTick(); await nextTick();
await settle(); await settle();
const hidden = [ const root = wrapper.element as HTMLElement;
...(wrapper.element as HTMLElement).querySelectorAll<HTMLInputElement>( const pickerForm = (
'input[type="hidden"][name]', root.matches("form") ? root : root.querySelector("form")
), )!;
]; // Empty required pickers submit no entry; the Form guard blocks the submit.
expect(hidden.map((input) => input.name).sort()).toEqual([ expect(new FormData(pickerForm as HTMLFormElement).has("state")).toBe(
"country", false,
"state", );
]); expect(new FormData(pickerForm as HTMLFormElement).has("country")).toBe(
false,
);
// `Form` renders novalidate and guards submit itself: an empty required // `Form` renders novalidate and guards submit itself: an empty required
// field must keep the demo's status line empty. // field must keep the demo's status line empty.
const root = wrapper.element as HTMLElement; const form = pickerForm;
const form = (root.matches("form") ? root : root.querySelector("form"))!;
const submit = ( const submit = (
wrapper.element as HTMLElement wrapper.element as HTMLElement
).querySelector<HTMLButtonElement>('button[type="submit"]')!; ).querySelector<HTMLButtonElement>('button[type="submit"]')!;
+206 -1
View File
@@ -683,9 +683,11 @@ describe("Autocomplete ported style hooks", () => {
await nextTick(); await nextTick();
await settle(); await settle();
// The class, the `data-slot` and `data-open` must share one element, or the
// ported `.hv-autocomplete__indicator[...]` rules never match.
expect( expect(
document.querySelector( document.querySelector(
'[data-slot="autocomplete-indicator"] [data-slot="autocomplete-default-indicator"]', '.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
), ),
).not.toBeNull(); ).not.toBeNull();
expect( expect(
@@ -693,3 +695,206 @@ describe("Autocomplete ported style hooks", () => {
).not.toBeNull(); ).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<HTMLButtonElement>(
'[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);
});
});
+448
View File
@@ -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<string, unknown> = () => ({}),
opts: {
items?: Ref<Item[]>;
inputProps?: Record<string, unknown>;
filterProps?: Record<string, unknown>;
} = {},
) {
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<HTMLInputElement>('[data-slot="input"]')!;
const searchInput = () =>
document.querySelector<HTMLInputElement>('[data-slot="search-field-input"]')!;
async function open(kind: "combo" | "auto") {
if (kind === "combo") comboInput().focus();
else
document
.querySelector<HTMLElement>('[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<HTMLButtonElement>(
'[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<string | null>("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<string | number>(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<Item[]>([{ 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<HTMLButtonElement>(
'[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<HTMLButtonElement>(
'[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<Item[]>([...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<HTMLButtonElement>(
'[data-slot="combo-box-trigger"]',
)!.disabled,
).toBe(true);
});
+38 -8
View File
@@ -175,15 +175,45 @@ describe("ComboBox docs and demos", () => {
mounted.push(wrapper); mounted.push(wrapper);
await nextTick(); await nextTick();
await settle(); await settle();
const hidden = [ const form = (wrapper.element as HTMLElement).matches("form")
...(wrapper.element as HTMLElement).querySelectorAll<HTMLInputElement>( ? (wrapper.element as HTMLFormElement)
'input[type="hidden"][name]', : (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<HTMLInputElement>('[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<HTMLInputElement>('[data-slot="input"]'),
]; ];
expect(hidden.map((input) => input.name).sort()).toEqual([ // Both pickers confirmed the same row: key mode submits the id, text mode
"animal", // the label — never a comma-joined string.
"animal-text", 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(); wrapper.unmount();
mounted.pop(); mounted.pop();
}); });
+183
View File
@@ -713,3 +713,186 @@ describe("ComboBox ported style hooks", () => {
).not.toBeNull(); ).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<HTMLElement>();
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());
});
});
+251
View File
@@ -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,
};