diff --git a/apps/docs/.vitepress/theme/navigation.ts b/apps/docs/.vitepress/theme/navigation.ts index 8d68d3c..0aae4ef 100644 --- a/apps/docs/.vitepress/theme/navigation.ts +++ b/apps/docs/.vitepress/theme/navigation.ts @@ -80,6 +80,11 @@ export const componentItems: DocsItem[] = [ url: "/components/close-button", category: "buttons", }, + { + title: "ComboBox 组合框", + url: "/components/combo-box", + category: "pickers", + }, { title: "DateField 日期字段", url: "/components/date-field", diff --git a/apps/docs/components/combo-box.md b/apps/docs/components/combo-box.md new file mode 100644 index 0000000..ca3fd47 --- /dev/null +++ b/apps/docs/components/combo-box.md @@ -0,0 +1,378 @@ +--- +title: ComboBox 组合框 +description: 将文本输入与 ListBox 结合,用户可通过输入查询把选项列表过滤为匹配项 +component: combo-box +group: 组件 +--- + +## 用法 + +```vue + + + + + 最喜欢的动物 + + + + + + + 猫 + 狗 + + + + +``` + + + +输入框既是过滤条件也是控件的真实焦点:`ComboBoxInputGroup` 把 `Input` 组合成 `role="combobox"` 控件,键盘与 `aria-activedescendant` 都落在它身上,弹层里的列表只维护活动行,不抢焦点。 + +## 组件结构 + +```vue + + + + + 分类 + + + + + + + 说明 + + + + 资讯 + + + + 更多 + 旅行 + + + + + + +``` + +上游的对象式子部件 `ComboBox.InputGroup` / `.Trigger` / `.Value` / `.Popover` 在本库中是具名导出 `ComboBoxInputGroup` / `ComboBoxTrigger` / `ComboBoxValue` / `ComboBoxPopover`。 + +## 示例 + +### 宽度充满 + + + +### 带描述 + + + +### 必填 + + + +### 禁用 + + + +### 含禁用选项 + + + +### 分组选项 + + + +### 受控组件 + + + +### 受控输入值 + + + +### 异步加载 + + + +### 默认选中项 + + + +### 允许自定义值 + + + +### 自定义指示器 + + + +### 自定义展示值 + + + +### 自定义过滤 + + + +### 渲染函数 + + + +上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(自定义组件作为唯一根),示例通过根元素属性演示同一能力。 + +### 菜单触发方式 + +使用 `menu-trigger` 控制弹层何时打开: + +- `focus`(默认):输入框获得焦点时打开 +- `input`:用户编辑输入文本时打开 +- `manual`:仅当按下触发按钮或使用方向键时打开 + + + +### 表单值 + +使用 `form-value` 控制提交表单时提交选中项的 key 还是文本。默认值为 `key`;`allows-custom-value` 为真时始终提交文本。多选时多个值以英文逗号连接。 + + + +### 校验行为 + +使用 `validation-behavior` 控制校验信息的展示方式: + +- `native`(默认):值为空或无效时阻止表单提交 +- `aria`:实时显示错误,不阻止提交 + + + +### 自定义校验 + +使用 `validate` 在值无效时返回错误信息,有效时返回 `true`。 + + + +### 只读 + +使用 `is-read-only` 将 ComboBox 设为只读。选中值可以获得焦点,但不能修改。 + + + +### 多选 + +设置 `selection-mode="multiple"` 允许选择多个选项。多选时用 `ComboBoxValue` 展示已选项,并同时给内部 `ListBox` 传 `selection-mode="multiple"`。值通过 `v-model` / `default-value`(数组)以及 `@selection-change` 控制。 + + + +### 表面样式 + +在 Surface 内使用时,请使用 `variant="secondary"` 以应用适合 Surface 背景的低强调变体。 + + + +## 自定义样式 + +### Tailwind CSS + + + +### 全局 CSS + +可使用 `@layer components` 指令自定义 ComboBox 组件类。 + +```css +@layer components { + .hv-combo-box { + @apply flex flex-col gap-1; + } + + .hv-combo-box__input-group { + @apply relative inline-flex items-center; + } + + .hv-combo-box__trigger { + @apply absolute end-0 text-muted; + } + + .hv-combo-box__popover { + @apply rounded-lg border border-border bg-surface p-2; + } +} +``` + +## 样式参考 + +HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。类名前缀为 `hv-`。 + +### CSS 类 + +ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/combo-box.css)): + +#### 基础类 + +- `.hv-combo-box` - ComboBox 根容器 +- `.hv-combo-box__input-group` - 输入框与触发按钮的容器 +- `.hv-combo-box__value` - 已选值的展示区域(用于多选) +- `.hv-combo-box__trigger` - 打开 Popover 的按钮 +- `.hv-combo-box__popover` - Popover 容器 + +#### 状态类 + +- `.hv-combo-box[data-invalid="true"]` - 无效状态(隐藏 Description) +- `.hv-combo-box[data-disabled="true"]` - 禁用状态 +- `.hv-combo-box__trigger[data-focus-visible="true"]` - 触发器聚焦 +- `.hv-combo-box__trigger[data-disabled="true"]` - 触发器禁用 +- `.hv-combo-box__trigger[data-open="true"]` - 展开状态(图标旋转 180°) +- `.hv-combo-box__value[data-placeholder="true"]` - 占位符状态 +- `.hv-combo-box [data-slot="input"]:focus` - 输入框聚焦(组合框里额外提供非 `focus-visible` 的聚焦态) + +### 交互状态 + +- **Hover**:触发器上 `:hover` 或 `[data-hovered="true"]` +- **Focus**:触发器上 `:focus-visible` 或 `[data-focus-visible="true"]` +- **Disabled**:ComboBox 上 `[data-disabled="true"]`,触发器上 `[data-disabled="true"]` +- **Open**:触发器上 `[data-open="true"]` + +## API 参考 + +### ComboBox + +| Prop | 类型 | 默认值 | 描述 | +| ------------------------- | ------------------------------------------------------------ | ----------- | ------------------------------------------------------- | +| `input-value` | `string` | - | 当前输入值(受控,可用 `v-model:input-value`) | +| `default-input-value` | `string` | `''` | 默认输入值(非受控) | +| `selection-mode` | `'single' \| 'multiple'` | `'single'` | 单选或多选 | +| `model-value` | `string \| number \| Array \| null` | - | 当前值(受控,`v-model`) | +| `value` | `string \| number \| Array \| null` | - | 同 `model-value`(受控别名) | +| `default-value` | `string \| number \| Array \| null` | - | 初始值(非受控) | +| `selected-key` | `string \| number \| null` | - | 单选当前 key(受控别名) | +| `default-selected-key` | `string \| number \| null` | - | 单选初始 key(非受控别名) | +| `items` | `Array<{ id, textValue, isDisabled? }>` | - | 数据驱动渲染;不传时以 `ListBox` 的静态子项作为集合 | +| `disabled-keys` | `Array` | - | 禁用项的 key | +| `default-filter` | `(text: string, inputValue: string) => boolean` | 包含匹配 | 自定义过滤函数 | +| `is-disabled` | `boolean` | `false` | 是否禁用 | +| `is-read-only` | `boolean` | `false` | 只读:值可聚焦但不可修改 | +| `is-required` | `boolean` | `false` | 是否必填 | +| `is-invalid` | `boolean` | `false` | 值是否无效 | +| `validate` | `(value) => string \| string[] \| true \| null \| undefined` | - | 校验函数,返回字符串表示无效 | +| `validation-behavior` | `'native' \| 'aria'` | `'native'` | 原生校验阻止提交,或只用 ARIA 标记 | +| `name` | `string` | - | 表单提交时的字段名(输出隐藏输入) | +| `form` | `string` | - | 关联的表单 id | +| `form-value` | `'key' \| 'text'` | `'key'` | 提交 key 还是文本;`allows-custom-value` 时始终提交文本 | +| `auto-complete` | `string` | `'off'` | 输入框 `autocomplete` | +| `auto-focus` | `boolean` | `false` | 挂载时聚焦 | +| `allows-custom-value` | `boolean` | `false` | 允许输入不在列表中的值 | +| `allows-empty-collection` | `boolean` | `false` | 无匹配项时仍可打开弹层 | +| `menu-trigger` | `'focus' \| 'input' \| 'manual'` | `'focus'` | 打开弹层的交互方式 | +| `should-focus-wrap` | `boolean` | `false` | 方向键是否在首尾循环 | +| `full-width` | `boolean` | `false` | 是否占满容器宽度 | +| `variant` | `'primary' \| 'secondary'` | `'primary'` | 视觉变体 | +| `placeholder` | `string` | - | `ComboBoxValue` 的缺省占位文本 | +| `as` | `string` | `'div'` | 自定义根元素标签 | +| `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 | +| 默认插槽 | `{ isOpen, inputValue, selectedKey, selectedKeys }` | - | 组件内容;作用域提供当前状态 | +| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | + +事件: + +| 事件 | 载荷 | 描述 | +| -------------------- | ----------------------------------- | ------------- | +| `update:modelValue` | `string \| number \| Array \| null` | 值变化 | +| `change` | 同上 | 值变化 | +| `update:selectedKey` | `string \| number \| null` | 单选 key 变化 | +| `selectionChange` | `string \| number \| null` | 单选 key 变化 | +| `update:inputValue` | `string` | 输入值变化 | +| `inputChange` | `string` | 输入值变化 | +| `update:open` | `boolean` | 弹层开关变化 | +| `openChange` | `boolean` | 弹层开关变化 | + +`aria-label`、`aria-labelledby`、`aria-describedby` 落在真正的 `role="combobox"` 输入框上,而不是根容器。 + +### ComboBoxInputGroup + +| Prop | 类型 | 默认值 | 描述 | +| -------- | --------------------------- | ------ | ---------------------------------------------- | +| 默认插槽 | `Component` | - | 必须包含本库 `Input`;可再放 `ComboBoxTrigger` | +| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | + +### ComboBoxValue + +渲染已选中的值;没有选中项时渲染占位符。多选时以逗号连接各选中项文本。 + +| Prop | 类型 | 默认值 | 描述 | +| ------------- | ---------------------------------- | -------------------- | ----------------------------- | +| `placeholder` | `string` | 根上的 `placeholder` | 未选中任何项时的占位文本 | +| 默认插槽 | `{ isPlaceholder, selectedItems }` | - | 自定义已选值展示 | +| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | + +### ComboBoxTrigger + +| Prop | 类型 | 默认值 | 描述 | +| ------------- | --------------------------- | ------- | ------------------------------ | +| `is-disabled` | `boolean` | `false` | 是否禁用触发器 | +| 默认插槽 | `Component` | - | 自定义触发器内容(默认下箭头) | +| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | + +触发器默认 `tabindex="-1"`:整个组合框保留输入框一个 Tab 入口。 + +### ComboBoxPopover + +| Prop | 类型 | 默认值 | 描述 | +| ------------------- | --------------------------- | ---------- | ----------------------------- | +| `placement` | 位置联合类型 | `'bottom'` | 相对触发容器的位置 | +| `offset` | `number` | `8` | 偏移量 | +| `should-flip` | `boolean` | `true` | 空间不足时是否翻转 | +| `container-padding` | `number` | `12` | 距离视口边缘的最小间距 | +| `to` | `string \| HTMLElement` | - | 自定义 Portal 容器 | +| 默认插槽 | `Component` | - | 弹层内容(通常为 `ListBox`) | +| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) | + +## 无障碍 + +ComboBox 实现 ARIA combobox 模式: + +- 真实焦点始终留在输入框,`aria-activedescendant` 指向已挂载且可见的活动选项 +- `ArrowDown` / `ArrowUp` / `Home` / `End` 在过滤后的可见集合中移动活动项,`Enter` 确认,`Escape` 关闭,`Tab` 离开 +- 中文输入法组合期间不确认选择(`isComposing` / `keyCode 229` 时忽略键盘提交) +- 过滤不会清除已接受的选择;被过滤掉的已选项仍保留标签 +- 弹层内不出现第二个 Tab 入口,关闭后移除 `aria-activedescendant` + +## 相关组件 + +[ListBox 列表框](./list-box) · [Select 选择器](./select) · [FieldError 字段错误](./field-error) · [Label 标签](./label) diff --git a/apps/docs/demos/combo-box-allows-custom-value.vue b/apps/docs/demos/combo-box-allows-custom-value.vue new file mode 100644 index 0000000..bbc09cb --- /dev/null +++ b/apps/docs/demos/combo-box-allows-custom-value.vue @@ -0,0 +1,53 @@ + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + 可输入任意动物名称,即使不在列表中 + + diff --git a/apps/docs/demos/combo-box-asynchronous-loading.vue b/apps/docs/demos/combo-box-asynchronous-loading.vue new file mode 100644 index 0000000..6d27ec3 --- /dev/null +++ b/apps/docs/demos/combo-box-asynchronous-loading.vue @@ -0,0 +1,158 @@ + + + + + + 选择角色 + + + + + + + + {{ item.name }} + + + + + {{ loading ? "正在加载…" : "没有找到角色" }} + + + + + + + 加载更多… + + + 加载更多… + + + + + diff --git a/apps/docs/demos/combo-box-controlled-input-value.vue b/apps/docs/demos/combo-box-controlled-input-value.vue new file mode 100644 index 0000000..e15e0b1 --- /dev/null +++ b/apps/docs/demos/combo-box-controlled-input-value.vue @@ -0,0 +1,61 @@ + + + + + + 搜索(受控输入) + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + + 输入值:{{ inputValue || "(空)" }} + + diff --git a/apps/docs/demos/combo-box-controlled.vue b/apps/docs/demos/combo-box-controlled.vue new file mode 100644 index 0000000..ed0851b --- /dev/null +++ b/apps/docs/demos/combo-box-controlled.vue @@ -0,0 +1,59 @@ + + + + + + 动物(受控) + + + + + + + + {{ animal.name }} + + + + + + 已选:{{ selectedAnimal?.name || "无" }} + + diff --git a/apps/docs/demos/combo-box-custom-filtering.vue b/apps/docs/demos/combo-box-custom-filtering.vue new file mode 100644 index 0000000..e0d2fcc --- /dev/null +++ b/apps/docs/demos/combo-box-custom-filtering.vue @@ -0,0 +1,50 @@ + + + + + 动物(自定义筛选) + + + + + + + + {{ animal.name }} + + + + + + diff --git a/apps/docs/demos/combo-box-custom-indicator.vue b/apps/docs/demos/combo-box-custom-indicator.vue new file mode 100644 index 0000000..c7477fc --- /dev/null +++ b/apps/docs/demos/combo-box-custom-indicator.vue @@ -0,0 +1,54 @@ + + + + + 最喜欢的动物 + + + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + + diff --git a/apps/docs/demos/combo-box-custom-styles.vue b/apps/docs/demos/combo-box-custom-styles.vue new file mode 100644 index 0000000..0ba4120 --- /dev/null +++ b/apps/docs/demos/combo-box-custom-styles.vue @@ -0,0 +1,48 @@ + + + + + + 框架 + + + + + + + + + React + + + + Vue + + + + Svelte + + + + + + diff --git a/apps/docs/demos/combo-box-custom-validation.vue b/apps/docs/demos/combo-box-custom-validation.vue new file mode 100644 index 0000000..e1c0a69 --- /dev/null +++ b/apps/docs/demos/combo-box-custom-validation.vue @@ -0,0 +1,68 @@ + + + + + + 最喜欢的动物 + + + + + + + + {{ animal.name }} + + + + + + + 提交 + + diff --git a/apps/docs/demos/combo-box-custom-value.vue b/apps/docs/demos/combo-box-custom-value.vue new file mode 100644 index 0000000..2165824 --- /dev/null +++ b/apps/docs/demos/combo-box-custom-value.vue @@ -0,0 +1,90 @@ + + + + + 用户 + + + + + + + + + + {{ user.fallback }} + + + {{ user.name }} + {{ user.email }} + + + + + + + diff --git a/apps/docs/demos/combo-box-default-selected-key.vue b/apps/docs/demos/combo-box-default-selected-key.vue new file mode 100644 index 0000000..8a92ae3 --- /dev/null +++ b/apps/docs/demos/combo-box-default-selected-key.vue @@ -0,0 +1,51 @@ + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + + diff --git a/apps/docs/demos/combo-box-default.vue b/apps/docs/demos/combo-box-default.vue new file mode 100644 index 0000000..06d39a6 --- /dev/null +++ b/apps/docs/demos/combo-box-default.vue @@ -0,0 +1,45 @@ + + + + + 最喜欢的动物 + + + + + + + + {{ animal.name }} + + + + + + diff --git a/apps/docs/demos/combo-box-disabled.vue b/apps/docs/demos/combo-box-disabled.vue new file mode 100644 index 0000000..ce56367 --- /dev/null +++ b/apps/docs/demos/combo-box-disabled.vue @@ -0,0 +1,51 @@ + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + + diff --git a/apps/docs/demos/combo-box-form-value.vue b/apps/docs/demos/combo-box-form-value.vue new file mode 100644 index 0000000..12a24b8 --- /dev/null +++ b/apps/docs/demos/combo-box-form-value.vue @@ -0,0 +1,86 @@ + + + + + + 动物 + + + + + + + + {{ animal.name }} + + + + + 提交选中项的 key + + + + 动物(文本) + + + + + + + + {{ animal.name }} + + + + + 提交选中项的文本 + + + 提交 + {{ message }} + + diff --git a/apps/docs/demos/combo-box-full-width.vue b/apps/docs/demos/combo-box-full-width.vue new file mode 100644 index 0000000..5cb78a2 --- /dev/null +++ b/apps/docs/demos/combo-box-full-width.vue @@ -0,0 +1,41 @@ + + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + + + + diff --git a/apps/docs/demos/combo-box-menu-trigger.vue b/apps/docs/demos/combo-box-menu-trigger.vue new file mode 100644 index 0000000..e839636 --- /dev/null +++ b/apps/docs/demos/combo-box-menu-trigger.vue @@ -0,0 +1,138 @@ + + + + + + 聚焦(默认) + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + 输入框获得焦点时打开弹出层 + + + + + 输入 + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + 用户编辑输入文本时打开弹出层 + + + + + 手动 + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + 仅在按下触发按钮或使用方向键时打开弹出层 + + + + diff --git a/apps/docs/demos/combo-box-multiple-selection.vue b/apps/docs/demos/combo-box-multiple-selection.vue new file mode 100644 index 0000000..05a8cb9 --- /dev/null +++ b/apps/docs/demos/combo-box-multiple-selection.vue @@ -0,0 +1,47 @@ + + + + + 最喜欢的动物 + + + + + + + + + {{ animal.name }} + + + + + + diff --git a/apps/docs/demos/combo-box-on-surface.vue b/apps/docs/demos/combo-box-on-surface.vue new file mode 100644 index 0000000..dabb6a1 --- /dev/null +++ b/apps/docs/demos/combo-box-on-surface.vue @@ -0,0 +1,66 @@ + + + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + + + 提交 + + + diff --git a/apps/docs/demos/combo-box-read-only.vue b/apps/docs/demos/combo-box-read-only.vue new file mode 100644 index 0000000..8b4a82c --- /dev/null +++ b/apps/docs/demos/combo-box-read-only.vue @@ -0,0 +1,45 @@ + + + + + 最喜欢的动物 + + + + + + + + {{ animal.name }} + + + + + + diff --git a/apps/docs/demos/combo-box-render-function.vue b/apps/docs/demos/combo-box-render-function.vue new file mode 100644 index 0000000..af70d53 --- /dev/null +++ b/apps/docs/demos/combo-box-render-function.vue @@ -0,0 +1,51 @@ + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + + diff --git a/apps/docs/demos/combo-box-required.vue b/apps/docs/demos/combo-box-required.vue new file mode 100644 index 0000000..f640301 --- /dev/null +++ b/apps/docs/demos/combo-box-required.vue @@ -0,0 +1,75 @@ + + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + + + 提交 + + 表单提交成功! + + + diff --git a/apps/docs/demos/combo-box-validation-behavior.vue b/apps/docs/demos/combo-box-validation-behavior.vue new file mode 100644 index 0000000..654b7a1 --- /dev/null +++ b/apps/docs/demos/combo-box-validation-behavior.vue @@ -0,0 +1,107 @@ + + + + + + + 动物(原生校验) + + + + + + + + {{ animal.name }} + + + + + 值为空时阻止提交 + + + 提交 + {{ nativeMessage }} + + + + 动物(ARIA 校验) + + + + + + + + {{ animal.name }} + + + + + 实时显示错误,不阻止提交 + + + 提交 + {{ ariaMessage }} + + + diff --git a/apps/docs/demos/combo-box-with-description.vue b/apps/docs/demos/combo-box-with-description.vue new file mode 100644 index 0000000..91b6926 --- /dev/null +++ b/apps/docs/demos/combo-box-with-description.vue @@ -0,0 +1,53 @@ + + + + + 最喜欢的动物 + + + + + + + + 土豚 + + + + 猫 + + + + 狗 + + + + 袋鼠 + + + + 熊猫 + + + + 蛇 + + + + + 搜索并选择你最喜欢的动物 + + diff --git a/apps/docs/demos/combo-box-with-disabled-options.vue b/apps/docs/demos/combo-box-with-disabled-options.vue new file mode 100644 index 0000000..d32cace --- /dev/null +++ b/apps/docs/demos/combo-box-with-disabled-options.vue @@ -0,0 +1,53 @@ + + + + + 动物 + + + + + + + + 狗 + + + + 猫 + + + + 鸟 + + + + 袋鼠 + + + + 象 + + + + 老虎 + + + + + + diff --git a/apps/docs/demos/combo-box-with-sections.vue b/apps/docs/demos/combo-box-with-sections.vue new file mode 100644 index 0000000..0cd4856 --- /dev/null +++ b/apps/docs/demos/combo-box-with-sections.vue @@ -0,0 +1,89 @@ + + + + + 国家 + + + + + + + + 北美洲 + + 美国 + + + + 加拿大 + + + + 墨西哥 + + + + + + 欧洲 + + 英国 + + + + 法国 + + + + 德国 + + + + 西班牙 + + + + 意大利 + + + + + + 亚洲 + + 日本 + + + + 中国 + + + + 印度 + + + + 韩国 + + + + + + + diff --git a/docs/compatibility.md b/docs/compatibility.md index 9b1e83f..61ff417 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -24,7 +24,7 @@ | color-swatch | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | color-swatch-picker | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | close-button | 验证中(最小实现) | 专用 CSS/变体、默认基线 CloseIcon、插槽替换图标、isDisabled、aria-label 默认 Close;onPress 由 click 适配 | -| combo-box | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | +| combo-box | 已迁移(有已知差异) | ComboBox 五部件;24/24 基线例;可编辑输入 + 过滤 + 虚拟焦点、form-value key/text、menu-trigger 三态、多选 Value;见 B02 报告 | | date-field | 已迁移(有已知差异) | DateField 七部件与 DateInputGroup 六部件、17 预览;完整 ISO、字段校验、reset、SSR/水合与浏览器重点检查,见 DATE-02 报告;本地化整日期粘贴、13 月/era 编辑等仍待专项。 | | date-picker | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | | date-range-picker | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 | diff --git a/docs/migrations/B02-combobox-autocomplete.md b/docs/migrations/B02-combobox-autocomplete.md index 3ac4fd1..57058f9 100644 --- a/docs/migrations/B02-combobox-autocomplete.md +++ b/docs/migrations/B02-combobox-autocomplete.md @@ -249,3 +249,52 @@ export interface CollectionOwner extends CollectionView { ## 11. B02a 阶段复核通过 以 [B02a 阶段验收](B02a-acceptance.md) 为当前结论。集成人补齐静态空集合、嵌套控件按下状态及探针独立运行的 scrollTo 环境初始化;最新全套为 77 文件 / 1026 项,无未处理错误。仅放行 B02a,在当前任务分支连续完成 B02b、B02c、B02d,公共组件和完整示例尚未验收。 + +## 11. B02b:ComboBox 全部部件、文档与示例(已实现) + +起点 `ff486fb`(含 B02a 验收 `B02a-acceptance.md`)。5 个部件、24 个基线示例、1 页中文文档、导航、19 项行为测试与 6 项演示/文档测试全部落地。**未做**独立产物消费(按四段安排在 B02d 统一完成)。 + +### 11.1 部件与映射 + +| 部件 | 实现要点 | +| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ComboBox` | 字段上下文(`kind: "text"`,`Label` 渲染 ``)、值/输入值/开关三套受控模型、集合 owner(`filter` / `virtualFocus` / `activeKey` / `keyboardIntent` / `isOpen`)、隐藏表单输入、`form-value` key/text | +| `ComboBoxInputGroup` | 组合调用方的 `Input`:注入 `role="combobox"`、`aria-expanded` / `-controls` / `-activedescendant` / `-autocomplete` / `-haspopup` / `-describedby`、`required`、`readonly`、`disabled`、值绑定与键盘处理;同时把它注册为弹层的 anchor | +| `ComboBoxTrigger` | 原生按钮、`data-open`、`tabindex=-1`(整个组合框只保留输入框一个 Tab 入口)、默认基线 chevron(展开时 CSS 旋转) | +| `ComboBoxValue` | 已选值文本(逗号连接)与 `data-placeholder`,支持作用域插槽 `{ isPlaceholder, selectedItems }` | +| `ComboBoxPopover` | 复用现有 `PopoverContent`(非模态、Teleport、外部点击、退出动画),`--trigger-width` / anchor point 变量,`onOpenAutoFocus` 阻止焦点进入弹层 | + +**键盘与焦点所有权**:真实焦点始终在输入框;`ArrowDown/Up`、`Home/End`、`Enter`、`Escape`、`Tab` 与 IME(`isComposing` / `keyCode 229`)一律由组合体处理,集合在 `virtualFocus` 下不处理键盘、不移动 DOM 焦点、不提供 roving Tab;`aria-activedescendant` 指向真实挂载且可见的 option。 + +**关闭态元数据**:`metadata.ts` 的 `planComboBoxItems` 从插槽树收集 `ListBox` / `ListBoxItem`(含 `items` 驱动的渲染函数、`ListBoxSection`、`disabledKeys`),使关闭时也能过滤、显示初始值标签、解析 `form-value="text"`;`items` 属性优先,插槽计划不完整时回退到已挂载 registry。 + +### 11.2 示例与文档 + +24 个示例全部来自 `apps/docs/demos/combo-box-*.vue`,顺序与固定正文一致(default → full-width → with-description → required → disabled → with-disabled-options → with-sections → controlled → controlled-input-value → asynchronous-loading → default-selected-key → allows-custom-value → custom-indicator → custom-value → custom-filtering → render-function → menu-trigger → form-value → validation-behavior → custom-validation → read-only → multiple-selection → on-surface → custom-styles)。文档页 `apps/docs/components/combo-box.md` 含用法、组件结构、24 个预览、样式参考、5 个部件的 API 表与事件表、无障碍;导航加入 `pickers` 分类。 + +示例适配(逐项记录,未以占位替代): + +1. `asynchronous-loading`:源示例请求 SWAPI;改为本地异步源(300ms、每查询一个 `AbortController`、加载中状态、`加载更多` 增量追加、空状态),状态机与源一致。 +2. `ListBoxLoadMoreItem` 在本库不存在:用显式「加载更多」按钮 + `Spinner` 状态行替代(与既有 `select-asynchronous-loading` 同做法)。 +3. `required` / `custom-validation`:源的 `alert` 改为页内 `role="status"` 文案(沿用 `select-required` 约定),仍读取真实 `FormData`。 +4. `custom-value`:源示例本身没有 `ComboBox.Value`,保持同样的结构(选中项文本回写输入框)。 +5. `render-function`:React `render` → 根元素 `as="div" data-custom="foo"`。 + +### 11.3 验证 + +- `pnpm typecheck` 通过;`pnpm test` **79 文件 / 1051 项**通过(新增 `tests/combo-box.test.ts` 19 项、`tests/combo-box-demos.test.ts` 6 项,均已加入 `test:unit`);`pnpm build:docs`、Prettier、`git diff --check` 通过。 +- 行为测试覆盖:单一 combobox 节点与 `label for`、`aria-*` 连线、聚焦打开、输入过滤、Enter 确认并回写文本、Escape 关闭、IME 不确认、文本与选中不匹配时清除、`allows-custom-value` 保留输入、父级拒绝后仍未选中且可再次提案、外部改值同步、禁用 key 跳过、禁用不打开、只读不可改、多选值与过滤后保留已接受键、隐藏输入提交 key/text、`required` 原生阻止提交、Description/FieldError 进入 `aria-describedby`、`menu-trigger` 三态、触发器切换。 +- 演示测试:预览清单与 24 个文件一一对应、无 `className`/`@gravity-ui/icons`/自绘 ``、每个示例都渲染真实 combobox(含唯一 id 与 `aria-expanded`)、代表示例能打开并给出有效 `aria-activedescendant`、初始选中项的文本进入输入框、form-value 示例输出两个隐藏输入。 +- 浏览器(5182,Chromium/IAB):24 个示例共 28 个 combobox;首个示例输入“猫”后 `expanded=true`、焦点仍在输入框、`aria-activedescendant` 指向 `role="option"` 的“猫”、列表 6 个 option 中 2 个可见(“猫”“熊猫”为包含匹配)、列表 `tabindex=-1`;`ArrowDown`+`Enter` 后输入框回写“猫”、列表关闭、焦点仍在输入;`Escape` 关闭并移除 `aria-activedescendant`;三个预选示例的输入框显示“猫”;禁用示例的输入框原生 `disabled`;`ComboBoxValue` 显示占位文本“未选择任何动物”;触发器 `tabindex=-1`;form-value 示例输出 `animal` / `animal-text` 隐藏输入。 + +### 11.4 本轮新增经验 + +- 关闭态的集合元数据必须由插槽计划提供:`ListBox` 未挂载时 registry 为空,过滤、初始标签与 `form-value="text"` 都会失效。 +- 选中值的文本同步只能跟「选择变化」走,不能跟「输入值变化」走,否则 `allows-custom-value` 下用户输入会被立刻覆盖。 +- 只读/禁用必须显式注入到组合出来的 `Input`(它读的是 `TextField` 上下文,不认 `fieldContextKey`)。 + +### 11.5 仍未验证 + +- 弹层内浮层选项的真实鼠标点击:本 IAB 会话对 floating 定位的 option 报 `not actionable`,改用键盘在页面验证,指针保焦点行为由 B02a 的 harness 与单测覆盖(记录为环境限制,未写成已通过)。 +- 真实系统 IME、读屏软件、逐像素视觉对比。 +- 独立 tarball 产物消费(B02d)。 diff --git a/docs/upstream.md b/docs/upstream.md index b375f93..ccf4ec1 100644 --- a/docs/upstream.md +++ b/docs/upstream.md @@ -208,3 +208,7 @@ M18–M20 的标签桥接在 Vue 使用 indicator 注册表与 SSR 直接/原生 固定 HeroUI 3.2.6 / `ce90ea3ab49d58f6c428f71bfd6fe8ae2a87b960`:`packages/react/src/components/{tag,tag-group,error-message}`、`packages/styles/components/{tag,tag-group,error-message}.css`、`packages/styles/src/components/{tag,tag-group,error-message}/*.styles.ts`,中文 `(collections)/tag-group.mdx`、`(forms)/error-message.mdx` 与 `demos/cn/tag-group` 12 例、`demos/cn/error-message` 2 例。Tag 无独立文档页,按固定 tag-group 正文与示例迁移。 CSS/tv 仅加 `hv-` 前缀与 Vue 状态适配,保留 Apache-2.0 来源。TagRemoveButton 复用本库 CloseButton 与基线 CloseIcon,可访问名称为 `Remove tag {标签文本}`(固定基线测试的同一字符串)。上游 `TagGroup.List` / `Tag.RemoveButton` 在本库为具名导出 `TagGroupList` / `TagRemoveButton`;React `render` 函数对应 `as` / `as-child`;`useListData` 演示改为 Vue 响应式数组。RAC 的 `FieldSlotsGate`/`TextContext` 只在集合渲染时需要,Vue 端改用字段上下文与渲染期 id 规划,不移植该 gate。无新增依赖,未运行时依赖相邻 React 仓库。 + +## B02b ComboBox(2026-10-25) + +固定 ce90ea3 的 `packages/react/src/components/combo-box/combo-box.tsx`、`packages/styles/components/combo-box.css`、`packages/styles/src/components/combo-box/combo-box.styles.ts`、中文 `(pickers)/combo-box.mdx` 与 `demos/cn/combo-box` 24 例。CSS/tv 仅加 `hv-` 前缀;默认 chevron 沿用基线 `icons.tsx` 路径。Vue 侧用选择/字段/弹层既有设施组合,未移植 RAC 的 `createCollectionSlot`(`InputGroup` 直接渲染容器并组合调用方的 `Input`),关闭态元数据由本批 `combo-box/metadata.ts` 从插槽树规划。示例的异步源、加载更多控件与 `alert` 适配已在报告 11.2 逐项记录,未运行时依赖相邻 React 仓库。 diff --git a/docs/verification.md b/docs/verification.md index 33778f9..56453f8 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -1017,3 +1017,12 @@ Tag/TagGroup/ErrorMessage 的最新验收见 [B03 复核记录](migrations/B03-r ## B02a 共享协议阶段(2026-10-25) 阶段复核见 [B02a 验收](migrations/B02a-acceptance.md)。过滤/虚拟焦点协议及真实受限虚拟窗口通过重点验证;静态空集合、嵌套按下状态和测试环境由集成人补齐。相关98项、全套1026项、类型/文档构建通过,无未处理错误。只允许继续B02b–d,不代表ComboBox/Autocomplete公共迁移完成。 + +## 2026-10-25 B02b ComboBox + +部件、示例、文档与测试范围见 [B02 报告](migrations/B02-combobox-autocomplete.md) 第 11 节;本段只记录本轮实际命令与证据。 + +- `pnpm typecheck` 通过;`pnpm test` **79 文件 / 1051 项**通过;`pnpm build:docs`、Prettier、`git diff --check` 通过。 +- 新增 `tests/combo-box.test.ts`(19 项行为)与 `tests/combo-box-demos.test.ts`(6 项文档/演示契约),均已加入 `test:unit`。 +- 浏览器 5182(Chromium/IAB):输入过滤后焦点仍在输入框、`aria-activedescendant` 指向真实 option、列表只有一个 Tab 入口;`ArrowDown`+`Enter` 回写文本并关闭;`Escape` 移除 `aria-activedescendant`;三个预选示例输入框显示“猫”;禁用示例输入框原生禁用;`ComboBoxValue` 占位文本;form-value 输出 `animal` / `animal-text` 隐藏输入。 +- 未验证:浮层选项的真实鼠标点击(本 IAB 对 floating option 报 `not actionable`,指针保焦点由 B02a harness 覆盖)、真实 IME、读屏软件、逐像素对比、独立 tarball 消费(B02d)。 diff --git a/package.json b/package.json index 0d429c4..74049af 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "build:docs": "pnpm build && pnpm --filter @heroui-vue/docs build", "typecheck": "vue-tsc --noEmit", "test": "vitest run", - "test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/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", + "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", "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:fix": "prettier --write .", diff --git a/packages/styles/components/combo-box.css b/packages/styles/components/combo-box.css new file mode 100644 index 0000000..4812f17 --- /dev/null +++ b/packages/styles/components/combo-box.css @@ -0,0 +1,188 @@ +/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc. + * See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */ +/* ComboBox styles */ +.hv-combo-box { + @apply flex flex-col gap-1; + + &[data-invalid="true"], + &[aria-invalid="true"] { + [data-slot="description"] { + @apply hidden; + } + } + + [data-slot="label"] { + @apply w-fit; + } + + [data-slot="input"] { + @apply min-w-0 flex-1; + + /* Add inline-end padding when trigger is present */ + &:has(+ .hv-combo-box__trigger) { + @apply pe-7; + } + + /* Focus state (input.css only has focus-visible, but hv-combo-box also needs focus) */ + &:focus, + &[data-focus] { + @apply status-focused-field; + border-color: var(--field-border-focus); + background-color: var(--field-focus); + } + + /* Disabled state */ + &:disabled, + &[data-disabled], + &[aria-disabled="true"] { + @apply status-disabled; + } + } +} + +.hv-combo-box__input-group { + @apply relative isolate inline-flex items-center; +} + +.hv-combo-box__value { + @apply text-sm wrap-break-word text-field-foreground empty:hidden; + + &[data-placeholder="true"] { + @apply text-field-placeholder; + } + + /* Removes the list-box-item indicator element from the hv-combo-box value */ + [data-slot="list-box-item-indicator"] { + @apply hidden; + } +} + +.hv-combo-box__trigger { + @apply absolute end-0 top-1/2 flex h-full shrink-0 -translate-y-1/2 cursor-pointer items-center justify-center pe-2 text-field-placeholder transition duration-150 no-highlight; + + /* Remove default button styles */ + @apply border-none bg-transparent outline-none; + + /* Hover state */ + @media (hover: hover) { + &:hover, + &[data-hovered="true"] { + @apply text-field-foreground; + } + } + + /* Focus visible state */ + &:focus-visible:not([data-focused]), + &[data-focus-visible="true"] { + @apply rounded ring-2 ring-focus ring-offset-2 ring-offset-background outline-none; + } + + /* Pressed state */ + &[data-pressed="true"] { + @apply opacity-70; + } + + /* Disabled state */ + &:disabled, + &[data-disabled], + &[aria-disabled="true"] { + @apply cursor-not-allowed opacity-50; + } + + [data-slot="hv-combo-box-trigger-default-icon"] { + @apply size-4 transition-transform duration-150 motion-reduce:transition-none; + } + + /* Rotate icon when trigger is open */ + &[data-open="true"] [data-slot="hv-combo-box-trigger-default-icon"] { + @apply rotate-180; + } +} + +/* Similar to popover content styles */ +.hv-combo-box__popover { + @apply min-w-(--trigger-width) origin-(--trigger-anchor-point) scroll-py-1 scrollbar overflow-y-auto overscroll-contain bg-overlay p-0 text-sm; + border-radius: min(32px, var(--radius-3xl)); + box-shadow: var(--overlay-shadow); + + /* Focus state */ + &:focus-visible:not([data-focused]), + &[data-focus-visible="true"] { + @apply outline-none; + } + + /* Entering animations */ + &[data-entering="true"] { + @apply animate-in duration-150 ease-smooth fade-in-0 zoom-in-95; + + /* Placement-specific translations */ + &[data-placement="top"] { + @apply slide-in-from-bottom-1; + } + + &[data-placement="bottom"] { + @apply slide-in-from-top-1; + } + + &[data-placement="left"] { + @apply slide-in-from-right-1; + } + + &[data-placement="right"] { + @apply slide-in-from-left-1; + } + } + + /* Exiting animations */ + &[data-exiting="true"] { + @apply animate-out duration-100 ease-smooth zoom-out-95 fade-out; + /* Stays non-interactive while closing, even if the exit animation is interrupted. */ + @apply pointer-events-none; + } + + &[data-exiting="true"], + &[data-entering="true"] { + @apply transition-[opacity,transform] will-change-[opacity,transform]; + } + + /* Arrow styling */ + & [data-slot="popover-overlay-arrow"] { + fill: var(--overlay); + } + + /* Arrow rotation based on placement */ + &[data-placement="bottom"] [data-slot="popover-overlay-arrow"] { + rotate: 180deg; + } + + &[data-placement="left"] [data-slot="popover-overlay-arrow"] { + rotate: -90deg; + } + + &[data-placement="right"] [data-slot="popover-overlay-arrow"] { + rotate: 90deg; + } + + /* Listbox styles */ + [data-slot="list-box"] { + @apply p-1.5 outline-none; + } + + [data-slot="list-box-item"] { + @apply px-2.5; + + /* As the hv-combo-box is single-select, we don't need to animate the checkmark */ + [data-slot="list-box-item-indicator--checkmark"] { + @apply transition-none; + } + } +} + +/* Full width modifier */ +.hv-combo-box--full-width { + @apply w-full; +} + +.hv-combo-box__input-group--full-width { + @apply w-full; +} diff --git a/packages/styles/index.css b/packages/styles/index.css index 994b424..9223b5b 100644 --- a/packages/styles/index.css +++ b/packages/styles/index.css @@ -155,6 +155,7 @@ @import "./components/menu-section.css" layer(components); @import "./components/dropdown.css" layer(components); @import "./components/tag-group.css" layer(components); +@import "./components/combo-box.css" layer(components); @import "./components/tag.css" layer(components); @import "./components/select.css" layer(components); diff --git a/packages/styles/src/index.ts b/packages/styles/src/index.ts index 1edac8b..7bb9091 100644 --- a/packages/styles/src/index.ts +++ b/packages/styles/src/index.ts @@ -1676,3 +1676,27 @@ export const errorMessageVariants = tv({ }); export type ErrorMessageVariants = VariantProps; + +export const comboBoxVariants = tv({ + defaultVariants: { + fullWidth: false, + }, + slots: { + base: "hv-combo-box", + inputGroup: "hv-combo-box__input-group", + popover: "hv-combo-box__popover", + trigger: "hv-combo-box__trigger", + value: "hv-combo-box__value", + }, + variants: { + fullWidth: { + false: {}, + true: { + base: "hv-combo-box--full-width", + inputGroup: "hv-combo-box__input-group--full-width", + }, + }, + }, +}); + +export type ComboBoxVariants = VariantProps; diff --git a/packages/vue/src/components/combo-box/ComboBox.vue b/packages/vue/src/components/combo-box/ComboBox.vue new file mode 100644 index 0000000..5dde0b7 --- /dev/null +++ b/packages/vue/src/components/combo-box/ComboBox.vue @@ -0,0 +1,678 @@ + diff --git a/packages/vue/src/components/combo-box/ComboBoxInputGroup.vue b/packages/vue/src/components/combo-box/ComboBoxInputGroup.vue new file mode 100644 index 0000000..252ef6b --- /dev/null +++ b/packages/vue/src/components/combo-box/ComboBoxInputGroup.vue @@ -0,0 +1,85 @@ + diff --git a/packages/vue/src/components/combo-box/ComboBoxPopover.vue b/packages/vue/src/components/combo-box/ComboBoxPopover.vue new file mode 100644 index 0000000..372ebfc --- /dev/null +++ b/packages/vue/src/components/combo-box/ComboBoxPopover.vue @@ -0,0 +1,43 @@ + diff --git a/packages/vue/src/components/combo-box/ComboBoxTrigger.vue b/packages/vue/src/components/combo-box/ComboBoxTrigger.vue new file mode 100644 index 0000000..a54f12b --- /dev/null +++ b/packages/vue/src/components/combo-box/ComboBoxTrigger.vue @@ -0,0 +1,70 @@ + diff --git a/packages/vue/src/components/combo-box/ComboBoxValue.vue b/packages/vue/src/components/combo-box/ComboBoxValue.vue new file mode 100644 index 0000000..777122d --- /dev/null +++ b/packages/vue/src/components/combo-box/ComboBoxValue.vue @@ -0,0 +1,35 @@ + diff --git a/packages/vue/src/components/combo-box/context.ts b/packages/vue/src/components/combo-box/context.ts new file mode 100644 index 0000000..3d414af --- /dev/null +++ b/packages/vue/src/components/combo-box/context.ts @@ -0,0 +1,88 @@ +import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue"; +import type { comboBoxVariants } from "@heroui-vue/styles"; +import type { CollectionKey } from "../collection/keys"; +import type { CollectionRecord, OwnedCollection } from "../collection/owner"; +import type { useChoiceField } from "../choice/shared"; + +export type ComboBoxValue = CollectionKey | CollectionKey[] | null; +export type ComboBoxMenuTrigger = "focus" | "input" | "manual"; +export interface ComboBoxItem { + id: CollectionKey; + textValue: string; + isDisabled?: boolean; +} +export interface ComboBoxSelectedItem { + key: CollectionKey; + textValue: string; +} +/** Props shared by the SFC and the context; keep one schema. */ +export interface ComboBoxOptions { + modelValue?: ComboBoxValue; + value?: ComboBoxValue; + defaultValue?: ComboBoxValue; + selectedKey?: CollectionKey | null; + defaultSelectedKey?: CollectionKey | null; + selectionMode?: "single" | "multiple"; + inputValue?: string; + defaultInputValue?: string; + items?: readonly ComboBoxItem[]; + disabledKeys?: readonly CollectionKey[]; + open?: boolean; + isOpen?: boolean; + defaultOpen?: boolean; + defaultFilter?: (text: string, inputValue: string) => boolean; + isDisabled?: boolean; + disabled?: boolean; + isReadOnly?: boolean; + isRequired?: boolean; + isInvalid?: boolean; + allowsCustomValue?: boolean; + allowsEmptyCollection?: boolean; + menuTrigger?: ComboBoxMenuTrigger; + shouldFocusWrap?: boolean; + fullWidth?: boolean; + variant?: "primary" | "secondary"; + name?: string; + form?: string; + formValue?: "key" | "text"; + autoComplete?: string; + autoFocus?: boolean; + validationBehavior?: "native" | "aria"; + placeholder?: string; +} +export interface ComboBoxContext { + field: ReturnType>; + slots: ComputedRef>; + open: ComputedRef; + setOpen: (open: boolean) => void; + inputValue: ComputedRef; + setInputValue: (value: string) => void; + inputId: string; + listId: string; + valueId: string; + placeholder: () => string; + activeKey: Ref; + activeId: ComputedRef; + collection: Ref; + keys: ComputedRef; + records: ComputedRef; + selectedItems: ComputedRef; + selectionMode: ComputedRef<"single" | "multiple">; + allowsCustomValue: () => boolean; + menuTrigger: () => ComboBoxMenuTrigger; + inputElement: Ref; + registerAnchor: (element: () => HTMLElement | undefined) => void; + /** ARIA plus input handlers injected onto the composed `Input`. */ + inputProps: () => Record; + formValueText: ComputedRef; + invalid: ComputedRef; + disabled: ComputedRef; +} +export const comboBoxKey: InjectionKey = + Symbol("hv-combo-box"); + +export function useComboBox(): ComboBoxContext { + const context = inject(comboBoxKey, undefined); + if (!context) throw new Error("ComboBox parts require ComboBox."); + return context; +} diff --git a/packages/vue/src/components/combo-box/dom.ts b/packages/vue/src/components/combo-box/dom.ts new file mode 100644 index 0000000..cda9ebd --- /dev/null +++ b/packages/vue/src/components/combo-box/dom.ts @@ -0,0 +1,7 @@ +/** Resolve a component ref handle (or element) to its DOM node. */ +export function elementFromRef(value: unknown): HTMLElement | undefined { + if (typeof Element === "undefined") return undefined; + if (value instanceof Element) return value as HTMLElement; + const element = (value as { $el?: unknown } | null)?.$el; + return element instanceof Element ? (element as HTMLElement) : undefined; +} diff --git a/packages/vue/src/components/combo-box/metadata.ts b/packages/vue/src/components/combo-box/metadata.ts new file mode 100644 index 0000000..7cd2a07 --- /dev/null +++ b/packages/vue/src/components/combo-box/metadata.ts @@ -0,0 +1,128 @@ +import { Fragment, Text, isVNode, type VNode, type VNodeChild } from "vue"; +import { assertKey, type CollectionKey } from "../collection/keys"; +import type { CollectionRecord } from "../collection/owner"; + +function name(node: VNode) { + const type = node.type as { name?: string; __name?: string } | undefined; + return type?.name ?? type?.__name; +} +function children(node: VNode): VNodeChild[] { + if (Array.isArray(node.children)) return node.children as VNodeChild[]; + if (node.children && typeof node.children === "object") { + const result = ( + node.children as { default?: () => VNodeChild } + ).default?.(); + return Array.isArray(result) ? result : result == null ? [] : [result]; + } + return typeof node.children === "string" ? [node.children] : []; +} +function text(nodes: VNodeChild[]): string { + return nodes + .map((node) => { + if (typeof node === "string" || typeof node === "number") + return String(node); + if (Array.isArray(node)) return text(node); + if (!isVNode(node)) return ""; + if (node.type === Text) return String(node.children); + if ( + node.type === Fragment || + typeof node.type === "string" || + name(node) === "Label" + ) + return text(children(node)); + return ""; + }) + .join("") + .trim(); +} + +const CONTAINERS = ["ComboBoxPopover", "SelectPopover", "ListBoxSection"]; + +/** + * Collect the collection metadata of a closed ComboBox from its slot tree. + * Filtering, the initial value label and `form-value="text"` need the full data + * set before the popover (and therefore the ListBox) has ever mounted. + */ +export function planComboBoxItems(nodes: VNodeChild[]) { + const records: CollectionRecord[] = []; + let found = false; + let opaque = false; + function add(record: CollectionRecord) { + assertKey(record.key); + if (records.some((item) => item.key === record.key)) + throw new Error(`Duplicate collection key: ${record.key}`); + records.push(record); + } + function walk( + nodes: VNodeChild[], + inside = false, + blocked: readonly CollectionKey[] = [], + ) { + for (const node of nodes) { + if (Array.isArray(node)) { + walk(node, inside, blocked); + continue; + } + if (!isVNode(node)) continue; + const component = name(node); + if (component === "ListBoxItem") { + const key = node.props?.id; + const disabled = node.props?.isDisabled ?? node.props?.["is-disabled"]; + add({ + key, + text: + node.props?.textValue ?? + node.props?.["text-value"] ?? + text(children(node)), + disabled: + disabled === true || disabled === "" || blocked.includes(key), + }); + } else if (component === "ListBox") { + found = true; + const disabledKeys = + node.props?.disabledKeys ?? node.props?.["disabled-keys"] ?? []; + const keys = [...blocked, ...disabledKeys] as CollectionKey[]; + if (node.props?.items) { + const slot = ( + node.children as { default?: (state: unknown) => VNodeChild[] } + )?.default; + const items = node.props.items as { + id: CollectionKey; + textValue?: string; + isDisabled?: boolean; + }[]; + items.forEach((item, index) => { + const before = records.length; + if (slot) { + const rendered = slot({ item, index }); + walk(Array.isArray(rendered) ? rendered : [rendered], true, keys); + } + if (records.length === before) + add({ + key: item.id, + text: item.textValue ?? String(item.id), + disabled: !!item.isDisabled || keys.includes(item.id), + }); + else if (item.isDisabled) + records.slice(before).forEach((record) => { + record.disabled = true; + }); + }); + } else walk(children(node), true, keys); + } else if ( + node.type === Fragment || + typeof node.type === "string" || + CONTAINERS.includes(component ?? "") + ) + walk(children(node), inside, blocked); + else if ( + inside && + component && + !["Header", "Separator"].includes(component) + ) + opaque = true; + } + } + walk(nodes); + return { records, complete: found && !opaque }; +} diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index a7c07b8..1db842e 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -958,3 +958,24 @@ export { type TagGroupVariants, type ErrorMessageVariants, } from "@heroui-vue/styles"; + +export { default as ComboBox } from "./components/combo-box/ComboBox.vue"; +export { default as ComboBoxInputGroup } from "./components/combo-box/ComboBoxInputGroup.vue"; +export { default as ComboBoxTrigger } from "./components/combo-box/ComboBoxTrigger.vue"; +export { default as ComboBoxValue } from "./components/combo-box/ComboBoxValue.vue"; +export { default as ComboBoxPopover } from "./components/combo-box/ComboBoxPopover.vue"; +export type { + ComboBoxProps, + ComboBoxInputGroupProps, + ComboBoxTriggerProps, + ComboBoxValueProps, + ComboBoxPopoverProps, +} from "./types"; +export type { + ComboBoxItem, + ComboBoxValue as ComboBoxValueType, + ComboBoxMenuTrigger, + ComboBoxOptions, +} from "./components/combo-box/context"; + +export { comboBoxVariants, type ComboBoxVariants } from "@heroui-vue/styles"; diff --git a/packages/vue/src/types.ts b/packages/vue/src/types.ts index 468c48d..dfb64b1 100644 --- a/packages/vue/src/types.ts +++ b/packages/vue/src/types.ts @@ -744,3 +744,24 @@ export type TagRemoveButtonProps = InstanceType< import type ErrorMessage from "./components/error-message/ErrorMessage.vue"; export type ErrorMessageProps = InstanceType["$props"]; + +import type ComboBox from "./components/combo-box/ComboBox.vue"; +export type ComboBoxProps = InstanceType["$props"]; + +import type ComboBoxInputGroup from "./components/combo-box/ComboBoxInputGroup.vue"; +export type ComboBoxInputGroupProps = InstanceType< + typeof ComboBoxInputGroup +>["$props"]; + +import type ComboBoxTrigger from "./components/combo-box/ComboBoxTrigger.vue"; +export type ComboBoxTriggerProps = InstanceType< + typeof ComboBoxTrigger +>["$props"]; + +import type ComboBoxValue from "./components/combo-box/ComboBoxValue.vue"; +export type ComboBoxValueProps = InstanceType["$props"]; + +import type ComboBoxPopover from "./components/combo-box/ComboBoxPopover.vue"; +export type ComboBoxPopoverProps = InstanceType< + typeof ComboBoxPopover +>["$props"]; diff --git a/tests/combo-box-demos.test.ts b/tests/combo-box-demos.test.ts new file mode 100644 index 0000000..3721041 --- /dev/null +++ b/tests/combo-box-demos.test.ts @@ -0,0 +1,190 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { mount } from "@vue/test-utils"; +import { nextTick, type Component } from "vue"; +import { readFileSync } from "node:fs"; + +const settle = () => new Promise((resolve) => setTimeout(resolve, 4)); +const mounted: { unmount: () => void }[] = []; + +const previews = [ + "default", + "full-width", + "with-description", + "required", + "disabled", + "with-disabled-options", + "with-sections", + "controlled", + "controlled-input-value", + "asynchronous-loading", + "default-selected-key", + "allows-custom-value", + "custom-indicator", + "custom-value", + "custom-filtering", + "render-function", + "menu-trigger", + "form-value", + "validation-behavior", + "custom-validation", + "read-only", + "multiple-selection", + "on-surface", + "custom-styles", +]; + +afterEach(async () => { + while (mounted.length) mounted.pop()?.unmount(); + await nextTick(); + await settle(); + vi.restoreAllMocks(); + document.body.innerHTML = ""; +}); + +describe("ComboBox docs and demos", () => { + it("keeps the pinned preview order and one demo per preview", () => { + const document = readFileSync("apps/docs/components/combo-box.md", "utf8"); + const names = [ + ...document.matchAll(/ match[1]); + + expect(names).toEqual(previews); + for (const name of previews) { + const source = readFileSync( + `apps/docs/demos/combo-box-${name}.vue`, + "utf8", + ); + + expect(source, name).toContain(""); + expect(source, name).not.toContain("className"); + expect(source, name).not.toContain("@gravity-ui/icons"); + expect(source, name).not.toContain(" { + const document = readFileSync("apps/docs/components/combo-box.md", "utf8"); + + expect(document).not.toMatch(/\|\s*`className`\s*\|/); + expect(document).toContain("`class`"); + expect(document).toContain("Vue class 绑定"); + expect(document).toContain("### ComboBoxInputGroup"); + expect(document).toContain("### ComboBoxValue"); + expect(document).toContain("### ComboBoxTrigger"); + expect(document).toContain("### ComboBoxPopover"); + expect(document).not.toContain("[!toc]"); + expect(document).not.toContain("ComboBox.List"); + }); + + it("mounts every demo with a real combobox control", async () => { + const modules = import.meta.glob("../apps/docs/demos/combo-box-*.vue"); + expect(Object.keys(modules)).toHaveLength(previews.length); + + for (const [path, load] of Object.entries(modules)) { + vi.useFakeTimers(); + const demo = (await load()) as { default: Component }; + const wrapper = mount(demo.default, { attachTo: document.body }); + + mounted.push(wrapper); + await nextTick(); + const inputs = (wrapper.element as HTMLElement).querySelectorAll( + '[role="combobox"]', + ); + + expect(inputs.length, path).toBeGreaterThan(0); + // Every combobox must be a real text input with a label association. + for (const input of inputs) { + expect(input.tagName, path).toBe("INPUT"); + expect(input.getAttribute("aria-expanded"), path).toBe("false"); + expect(input.id, path).not.toBe(""); + } + wrapper.unmount(); + mounted.pop(); + vi.useRealTimers(); + await settle(); + document.body.innerHTML = ""; + } + }); + + it("opens, filters and selects inside representative demos", async () => { + const load = (name: string) => + import(`../apps/docs/demos/combo-box-${name}.vue`); + + for (const name of ["default", "with-sections", "custom-styles"]) { + const demo = (await load(name)) as { default: Component }; + const wrapper = mount(demo.default, { attachTo: document.body }); + mounted.push(wrapper); + await nextTick(); + await settle(); + const input = ( + wrapper.element as HTMLElement + ).querySelector('[role="combobox"]')!; + input.focus(); + input.dispatchEvent( + new KeyboardEvent("keydown", { + key: "ArrowDown", + bubbles: true, + cancelable: true, + }), + ); + await nextTick(); + await settle(); + expect(input.getAttribute("aria-expanded"), name).toBe("true"); + const id = input.getAttribute("aria-activedescendant"); + expect(id, name).toBeTruthy(); + expect(document.getElementById(id!)?.getAttribute("role"), name).toBe( + "option", + ); + wrapper.unmount(); + mounted.pop(); + await settle(); + document.body.innerHTML = ""; + } + }); + + it("shows a preselected item's text in the input", async () => { + for (const [name, expected] of [ + ["default-selected-key", "猫"], + ["disabled", "猫"], + ["read-only", "猫"], + ] as const) { + const demo = (await import( + `../apps/docs/demos/combo-box-${name}.vue` + )) as { default: Component }; + const wrapper = mount(demo.default, { attachTo: document.body }); + mounted.push(wrapper); + await nextTick(); + await settle(); + const input = ( + wrapper.element as HTMLElement + ).querySelector('[role="combobox"]')!; + expect(input.value, name).toBe(expected); + wrapper.unmount(); + mounted.pop(); + await settle(); + document.body.innerHTML = ""; + } + }); + + it("submits form-value demos through hidden inputs", async () => { + const demo = + (await import("../apps/docs/demos/combo-box-form-value.vue")) as { + default: Component; + }; + const wrapper = mount(demo.default, { attachTo: document.body }); + mounted.push(wrapper); + await nextTick(); + await settle(); + const hidden = [ + ...(wrapper.element as HTMLElement).querySelectorAll( + 'input[type="hidden"][name]', + ), + ]; + expect(hidden.map((input) => input.name).sort()).toEqual([ + "animal", + "animal-text", + ]); + wrapper.unmount(); + mounted.pop(); + }); +}); diff --git a/tests/combo-box.test.ts b/tests/combo-box.test.ts new file mode 100644 index 0000000..92560c5 --- /dev/null +++ b/tests/combo-box.test.ts @@ -0,0 +1,657 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { mount } from "@vue/test-utils"; +import { defineComponent, h, nextTick, ref } from "vue"; +import { + ComboBox, + ComboBoxInputGroup, + ComboBoxPopover, + ComboBoxTrigger, + ComboBoxValue, + Description, + FieldError, + Form, + Input, + Label, + ListBox, + ListBoxItem, +} from "../packages/vue/src"; + +const settle = () => new Promise((resolve) => setTimeout(resolve, 3)); +const mounted: { unmount: () => void; element: Element }[] = []; + +type Item = { id: string | number; text: string; disabled?: boolean }; +const animals: Item[] = [ + { id: "cat", text: "猫" }, + { id: "dog", text: "狗" }, + { id: "bird", text: "鸟" }, + { id: "fish", text: "鱼" }, +]; + +function mountCombo( + props: Record = {}, + options: { items?: Item[]; value?: boolean } = {}, +) { + const items = options.items ?? animals; + const wrapper = mount( + defineComponent({ + setup() { + return () => + h( + ComboBox, + { "aria-label": "动物", ...props }, + { + default: () => [ + h(Label, () => "最喜欢的动物"), + h(ComboBoxInputGroup, null, { + default: () => [ + h(Input, { placeholder: "搜索动物…" }), + h(ComboBoxTrigger), + ], + }), + options.value + ? h(ComboBoxValue, { placeholder: "未选择" }) + : null, + h(ComboBoxPopover, null, { + default: () => + h(ListBox, null, { + default: () => + items.map((item) => + h( + ListBoxItem, + { + id: item.id, + key: item.id, + textValue: item.text, + isDisabled: item.disabled, + }, + () => item.text, + ), + ), + empty: () => + h("p", { "data-test": "empty" }, "没有匹配项"), + }), + }), + ], + }, + ); + }, + }), + { attachTo: document.body }, + ); + mounted.push(wrapper); + return wrapper; +} + +const input = () => + document.querySelector('[data-slot="input"]')!; +const rowTexts = () => + [...document.querySelectorAll('[role="option"]')] + .filter((row) => !row.hasAttribute("data-filtered")) + .map((row) => row.textContent?.trim()); + +async function type(value: string) { + const element = input(); + element.value = value; + element.dispatchEvent(new Event("input", { bubbles: true })); + await nextTick(); + await settle(); +} +async function press(key: string, init: KeyboardEventInit = {}) { + input().dispatchEvent( + new KeyboardEvent("keydown", { + key, + bubbles: true, + cancelable: true, + ...init, + }), + ); + await nextTick(); + await settle(); +} + +afterEach(async () => { + while (mounted.length) mounted.pop()?.unmount(); + await nextTick(); + await settle(); + vi.restoreAllMocks(); + document.body.innerHTML = ""; +}); + +describe("ComboBox input semantics", () => { + it("exposes one combobox control with label and ARIA wiring", async () => { + mountCombo(); + await nextTick(); + const element = input(); + const label = document.querySelector("label")!; + + expect(element.getAttribute("role")).toBe("combobox"); + expect(element.getAttribute("aria-expanded")).toBe("false"); + expect(element.getAttribute("aria-autocomplete")).toBe("list"); + expect(element.getAttribute("aria-haspopup")).toBe("listbox"); + expect(element.id).toBeTruthy(); + expect(label.getAttribute("for")).toBe(element.id); + expect( + document + .querySelector('[data-slot="combo-box-trigger"]')! + .getAttribute("tabindex"), + ).toBe("-1"); + }); + + it("opens on focus, filters with the input and keeps focus in the input", async () => { + mountCombo(); + await nextTick(); + input().focus(); + input().dispatchEvent(new FocusEvent("focus")); + await nextTick(); + await settle(); + expect(input().getAttribute("aria-expanded")).toBe("true"); + + await type("狗"); + expect(rowTexts()).toEqual(["狗"]); + expect(document.activeElement).toBe(input()); + + const id = input().getAttribute("aria-activedescendant"); + expect(id).toBeTruthy(); + const option = document.getElementById(id!); + expect(option?.getAttribute("role")).toBe("option"); + expect(option?.textContent?.trim()).toBe("狗"); + }); + + it("confirms with Enter, writes the text back and closes", async () => { + const onChange = vi.fn(); + mountCombo({ onSelectionChange: onChange }); + await nextTick(); + input().focus(); + await press("ArrowDown"); + await press("ArrowDown"); + await press("Enter"); + + expect(onChange).toHaveBeenLastCalledWith("dog"); + expect(input().value).toBe("狗"); + expect(input().getAttribute("aria-expanded")).toBe("false"); + expect(input().getAttribute("aria-activedescendant")).toBeNull(); + }); + + it("closes on Escape without changing the value", async () => { + const onChange = vi.fn(); + mountCombo({ onSelectionChange: onChange }); + await nextTick(); + input().focus(); + await press("ArrowDown"); + await press("Escape"); + expect(input().getAttribute("aria-expanded")).toBe("false"); + expect(onChange).not.toHaveBeenCalled(); + }); + + it("does not confirm while an IME composition is active", async () => { + const onChange = vi.fn(); + mountCombo({ onSelectionChange: onChange }); + await nextTick(); + input().focus(); + await press("ArrowDown"); + await press("Enter", { isComposing: true }); + expect(onChange).not.toHaveBeenCalled(); + await press("Enter", { keyCode: 229 }); + expect(onChange).not.toHaveBeenCalled(); + }); + + it("clears the selection when the text stops matching it", async () => { + const onChange = vi.fn(); + mountCombo({ onSelectionChange: onChange }); + await nextTick(); + input().focus(); + await press("ArrowDown"); + await press("Enter"); + expect(onChange).toHaveBeenLastCalledWith("cat"); + + await type("狗"); + expect(onChange).toHaveBeenLastCalledWith(null); + }); + + it("keeps a typed custom value when allowsCustomValue is set", async () => { + const onChange = vi.fn(); + mountCombo({ allowsCustomValue: true, onSelectionChange: onChange }); + await nextTick(); + input().focus(); + await press("ArrowDown"); + await press("Enter"); + await type("独角兽"); + expect(onChange).not.toHaveBeenLastCalledWith(null); + expect(input().value).toBe("独角兽"); + }); +}); + +describe("ComboBox selection state", () => { + it("keeps the accepted value when the parent rejects the proposal", async () => { + mountCombo({ selectedKey: null, onSelectionChange: () => {} }); + await nextTick(); + input().focus(); + await press("ArrowDown"); + await press("Enter"); + await settle(); + // The rejected value never becomes accepted: nothing is selected. + expect(document.querySelector('[aria-selected="true"]')).toBeNull(); + // And the proposal can be made again once the parent accepts the same key. + await press("ArrowDown"); + await press("Enter"); + expect(document.querySelector('[aria-selected="true"]')).toBeNull(); + }); + + it("reflects an externally changed selected key", async () => { + const selected = ref("dog"); + const wrapper = mount( + defineComponent({ + setup() { + return () => + h( + ComboBox, + { + "aria-label": "动物", + selectedKey: selected.value, + onSelectionChange: (key: string | number | null) => + (selected.value = key), + }, + { + default: () => [ + h(ComboBoxInputGroup, null, { + default: () => [h(Input, {}), h(ComboBoxTrigger)], + }), + h(ComboBoxPopover, null, { + default: () => + h(ListBox, null, { + default: () => + animals.map((item) => + h( + ListBoxItem, + { + id: item.id, + key: item.id, + textValue: item.text, + }, + () => item.text, + ), + ), + }), + }), + ], + }, + ); + }, + }), + { attachTo: document.body }, + ); + mounted.push(wrapper); + await nextTick(); + await settle(); + expect(input().value).toBe("狗"); + + selected.value = "cat"; + await nextTick(); + await settle(); + expect(input().value).toBe("猫"); + }); + + it("skips disabled keys and does not select them", async () => { + const onChange = vi.fn(); + mountCombo( + { disabledKeys: ["cat"], onSelectionChange: onChange }, + { items: animals }, + ); + await nextTick(); + input().focus(); + await press("ArrowDown"); + expect( + document.querySelector('[role="option"]')!.getAttribute("aria-disabled"), + ).toBe("true"); + await press("Enter"); + expect(onChange).toHaveBeenLastCalledWith("dog"); + }); + + it("does not open or select while disabled", async () => { + const onChange = vi.fn(); + mountCombo({ isDisabled: true, onSelectionChange: onChange }); + await nextTick(); + input().focus(); + await press("ArrowDown"); + expect(input().getAttribute("aria-expanded")).toBe("false"); + expect(onChange).not.toHaveBeenCalled(); + }); + + it("keeps the input read-only without selecting", async () => { + const onChange = vi.fn(); + mountCombo({ isReadOnly: true, onSelectionChange: onChange }); + await nextTick(); + expect(input().readOnly).toBe(true); + input().focus(); + await press("ArrowDown"); + expect(input().getAttribute("aria-expanded")).toBe("false"); + }); + + it("shows multiple values and keeps accepted keys when filtered out", async () => { + const selected = ref<(string | number)[]>(["cat", "dog"]); + const wrapper = mount( + defineComponent({ + setup() { + return () => + h( + ComboBox, + { + "aria-label": "动物", + selectionMode: "multiple", + modelValue: selected.value, + "onUpdate:modelValue": (value: unknown) => + (selected.value = (value ?? []) as (string | number)[]), + }, + { + default: () => [ + h(ComboBoxInputGroup, null, { + default: () => [h(Input, {}), h(ComboBoxTrigger)], + }), + h(ComboBoxValue, { placeholder: "未选择" }), + h(ComboBoxPopover, null, { + default: () => + h( + ListBox, + { selectionMode: "multiple" }, + { + default: () => + animals.map((item) => + h( + ListBoxItem, + { + id: item.id, + key: item.id, + textValue: item.text, + }, + () => item.text, + ), + ), + }, + ), + }), + ], + }, + ); + }, + }), + { attachTo: document.body }, + ); + mounted.push(wrapper); + await nextTick(); + await settle(); + const value = () => + document + .querySelector('[data-slot="combo-box-value"]')! + .textContent?.trim(); + expect(value()).toBe("猫, 狗"); + + input().focus(); + await type("鸟"); + expect(value()).toBe("猫, 狗"); + expect(selected.value).toEqual(["cat", "dog"]); + }); +}); + +describe("ComboBox form and validation", () => { + it("submits the key or the text through a hidden input", async () => { + const wrapper = mount( + defineComponent({ + setup() { + const submitted = ref(""); + return () => + h( + Form, + { + onSubmit: (event: Event) => { + event.preventDefault(); + const data = new FormData( + event.currentTarget as HTMLFormElement, + ); + submitted.value = `${data.get("animal")}|${data.get("animal-text")}`; + }, + }, + { + default: () => [ + h( + ComboBox, + { + "aria-label": "key", + name: "animal", + formValue: "key", + defaultSelectedKey: "cat", + }, + { + default: () => [ + h(ComboBoxInputGroup, null, { + default: () => [h(Input, {}), h(ComboBoxTrigger)], + }), + h(ComboBoxPopover, null, { + default: () => + h(ListBox, null, { + default: () => + animals.map((item) => + h( + ListBoxItem, + { + id: item.id, + key: item.id, + textValue: item.text, + }, + () => item.text, + ), + ), + }), + }), + ], + }, + ), + h( + ComboBox, + { + "aria-label": "text", + name: "animal-text", + formValue: "text", + defaultSelectedKey: "dog", + }, + { + default: () => [ + h(ComboBoxInputGroup, null, { + default: () => [h(Input, {}), h(ComboBoxTrigger)], + }), + h(ComboBoxPopover, null, { + default: () => + h(ListBox, null, { + default: () => + animals.map((item) => + h( + ListBoxItem, + { + id: item.id, + key: item.id, + textValue: item.text, + }, + () => item.text, + ), + ), + }), + }), + ], + }, + ), + h( + "button", + { type: "submit", "data-test": "submit" }, + "提交", + ), + h("p", { "data-test": "result" }, submitted.value), + ], + }, + ); + }, + }), + { attachTo: document.body }, + ); + mounted.push(wrapper); + await nextTick(); + await settle(); + ( + document.querySelector('[data-test="submit"]') as HTMLButtonElement + ).click(); + await nextTick(); + expect(document.querySelector('[data-test="result"]')!.textContent).toBe( + "cat|狗", + ); + }); + + it("blocks native submit when required and empty", async () => { + const wrapper = mount( + defineComponent({ + setup() { + const submitted = ref(0); + return () => + h( + Form, + { + onSubmit: (event: Event) => { + event.preventDefault(); + submitted.value += 1; + }, + }, + { + default: () => [ + h( + ComboBox, + { "aria-label": "动物", name: "animal", isRequired: true }, + { + default: () => [ + h(Label, () => "动物"), + h(ComboBoxInputGroup, null, { + default: () => [h(Input, {}), h(ComboBoxTrigger)], + }), + h(ComboBoxPopover, null, { + default: () => + h(ListBox, null, { + default: () => + animals.map((item) => + h( + ListBoxItem, + { + id: item.id, + key: item.id, + textValue: item.text, + }, + () => item.text, + ), + ), + }), + }), + h(FieldError, () => "请选择动物"), + ], + }, + ), + h( + "button", + { type: "submit", "data-test": "submit" }, + "提交", + ), + h("p", { "data-test": "submitted" }, String(submitted.value)), + ], + }, + ); + }, + }), + { attachTo: document.body }, + ); + mounted.push(wrapper); + await nextTick(); + await settle(); + const form = document.querySelector("form")!; + const blocked = !form.checkValidity(); + expect(blocked).toBe(true); + expect(input().required).toBe(true); + }); + + it("surfaces a Description and an ErrorMessage through aria-describedby", async () => { + mount( + defineComponent({ + setup() { + return () => + h( + ComboBox, + { "aria-label": "动物", isInvalid: true }, + { + default: () => [ + h(ComboBoxInputGroup, null, { + default: () => [h(Input, {}), h(ComboBoxTrigger)], + }), + h(Description, () => "选择一种动物"), + h(FieldError, () => "请选择动物"), + h(ComboBoxPopover, null, { + default: () => + h(ListBox, null, { + default: () => + animals.map((item) => + h( + ListBoxItem, + { + id: item.id, + key: item.id, + textValue: item.text, + }, + () => item.text, + ), + ), + }), + }), + ], + }, + ); + }, + }), + { attachTo: document.body }, + ); + await nextTick(); + await settle(); + const described = input().getAttribute("aria-describedby") ?? ""; + const description = document.querySelector('[data-slot="description"]')!; + const error = document.querySelector('[data-slot="field-error"]')!; + expect(described).toContain(description.id); + expect(described).toContain(error.id); + }); +}); + +describe("ComboBox menu trigger", () => { + it("opens on input only for menu-trigger=input", async () => { + mountCombo({ menuTrigger: "input" }); + await nextTick(); + input().focus(); + await nextTick(); + await settle(); + expect(input().getAttribute("aria-expanded")).toBe("false"); + await type("猫"); + expect(input().getAttribute("aria-expanded")).toBe("true"); + }); + + it("stays closed on focus for menu-trigger=manual and opens with ArrowDown", async () => { + mountCombo({ menuTrigger: "manual" }); + await nextTick(); + input().focus(); + await nextTick(); + await settle(); + expect(input().getAttribute("aria-expanded")).toBe("false"); + await press("ArrowDown"); + expect(input().getAttribute("aria-expanded")).toBe("true"); + }); + + it("toggles from the trigger button", async () => { + mountCombo(); + await nextTick(); + const trigger = document.querySelector( + '[data-slot="combo-box-trigger"]', + )!; + trigger.dispatchEvent(new MouseEvent("click", { bubbles: true })); + await nextTick(); + await settle(); + expect(input().getAttribute("aria-expanded")).toBe("true"); + }); +});
输入值:{{ inputValue || "(空)" }}
已选:{{ selectedAnimal?.name || "无" }}
{{ message }}
聚焦(默认)
输入
手动
+ 表单提交成功! +
{{ nativeMessage }}
{{ ariaMessage }}