feat(combo-box): migrate ComboBox with input-owned focus and filtering

Port the fixed-baseline ComboBox onto the B02a collection protocol: the input
keeps real DOM focus, the list only tracks an active row, and filtering reuses
the owner filter instead of a second collection kernel.

- Five parts: root (field text control, value/input/open models, form value,
  owner wiring), InputGroup (composes the caller's Input into the combobox
  control and anchors the popover), Trigger, Value, Popover.
- Closed-state metadata is planned from the slot tree, so filtering, the initial
  value label and form-value="text" work before the list has mounted.
- Selection text syncs on selection changes only, so allows-custom-value typing
  is not overwritten; read-only and disabled are injected onto the composed
  input because it reads the text-field protocol, not the field context.
- 24 baseline previews, the Chinese doc page, navigation, 19 behaviour tests and
  6 demo/document contracts. Async demo uses a local async source with abort,
  loading and incremental append (documented adaptations).

Not included: independent tarball consumption (B02d).
This commit is contained in:
maoyingjie
2026-10-25 16:59:16 +08:00
parent ff486fb665
commit 46e4df7e85
46 changed files with 4322 additions and 2 deletions
+5
View File
@@ -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",
+378
View File
@@ -0,0 +1,378 @@
---
title: ComboBox 组合框
description: 将文本输入与 ListBox 结合,用户可通过输入查询把选项列表过滤为匹配项
component: combo-box
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox class="w-[256px]">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="cat" text-value="猫">猫</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">狗</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
```
<ComponentPreview name="combo-box-default" />
输入框既是过滤条件也是控件的真实焦点:`ComboBoxInputGroup` 把 `Input` 组合成 `role="combobox"` 控件,键盘与 `aria-activedescendant` 都落在它身上,弹层里的列表只维护活动行,不抢焦点。
## 组件结构
```vue
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
ComboBoxValue,
Description,
Header,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
ListBoxSection,
Separator,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox>
<Label>分类</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<!-- 展示已选中的值,主要用于多选 -->
<ComboBoxValue />
<Description>说明</Description>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="news" text-value="资讯">
资讯
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxSection>
<Header>更多</Header>
<ListBoxItem id="travel" text-value="旅行">旅行</ListBoxItem>
</ListBoxSection>
</ListBox>
<Separator />
</ComboBoxPopover>
</ComboBox>
</template>
```
上游的对象式子部件 `ComboBox.InputGroup` / `.Trigger` / `.Value` / `.Popover` 在本库中是具名导出 `ComboBoxInputGroup` / `ComboBoxTrigger` / `ComboBoxValue` / `ComboBoxPopover`。
## 示例
### 宽度充满
<ComponentPreview name="combo-box-full-width" />
### 带描述
<ComponentPreview name="combo-box-with-description" />
### 必填
<ComponentPreview name="combo-box-required" />
### 禁用
<ComponentPreview name="combo-box-disabled" />
### 含禁用选项
<ComponentPreview name="combo-box-with-disabled-options" />
### 分组选项
<ComponentPreview name="combo-box-with-sections" />
### 受控组件
<ComponentPreview name="combo-box-controlled" />
### 受控输入值
<ComponentPreview name="combo-box-controlled-input-value" />
### 异步加载
<ComponentPreview name="combo-box-asynchronous-loading" />
### 默认选中项
<ComponentPreview name="combo-box-default-selected-key" />
### 允许自定义值
<ComponentPreview name="combo-box-allows-custom-value" />
### 自定义指示器
<ComponentPreview name="combo-box-custom-indicator" />
### 自定义展示值
<ComponentPreview name="combo-box-custom-value" />
### 自定义过滤
<ComponentPreview name="combo-box-custom-filtering" />
### 渲染函数
<ComponentPreview name="combo-box-render-function" />
上游用 React `render` 函数替换根 DOM 元素;Vue 中对应 `as`(自定义根元素标签)与 `as-child`(自定义组件作为唯一根),示例通过根元素属性演示同一能力。
### 菜单触发方式
使用 `menu-trigger` 控制弹层何时打开:
- `focus`(默认):输入框获得焦点时打开
- `input`:用户编辑输入文本时打开
- `manual`:仅当按下触发按钮或使用方向键时打开
<ComponentPreview name="combo-box-menu-trigger" />
### 表单值
使用 `form-value` 控制提交表单时提交选中项的 key 还是文本。默认值为 `key`;`allows-custom-value` 为真时始终提交文本。多选时多个值以英文逗号连接。
<ComponentPreview name="combo-box-form-value" />
### 校验行为
使用 `validation-behavior` 控制校验信息的展示方式:
- `native`(默认):值为空或无效时阻止表单提交
- `aria`:实时显示错误,不阻止提交
<ComponentPreview name="combo-box-validation-behavior" />
### 自定义校验
使用 `validate` 在值无效时返回错误信息,有效时返回 `true`。
<ComponentPreview name="combo-box-custom-validation" />
### 只读
使用 `is-read-only` 将 ComboBox 设为只读。选中值可以获得焦点,但不能修改。
<ComponentPreview name="combo-box-read-only" />
### 多选
设置 `selection-mode="multiple"` 允许选择多个选项。多选时用 `ComboBoxValue` 展示已选项,并同时给内部 `ListBox` 传 `selection-mode="multiple"`。值通过 `v-model` / `default-value`(数组)以及 `@selection-change` 控制。
<ComponentPreview name="combo-box-multiple-selection" />
### 表面样式
在 Surface 内使用时,请使用 `variant="secondary"` 以应用适合 Surface 背景的低强调变体。
<ComponentPreview name="combo-box-on-surface" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="combo-box-custom-styles" />
### 全局 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<string \| number>` | - | 禁用项的 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)
@@ -0,0 +1,53 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Description,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox allows-custom-value class="w-[256px]">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索或输入动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>可输入任意动物名称,即使不在列表中</Description>
</ComboBox>
</template>
@@ -0,0 +1,158 @@
<!-- 适配:源示例请求 SWAPI,这里用本地异步源演示相同状态(取消旧请求、加载中、增量加载)。 -->
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import {
Button,
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
EmptyState,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Spinner,
} from "@heroui-vue/components";
type Character = {
id: string;
name: string;
};
const PAGE_SIZE = 4;
const PAGE_DELAY = 300;
const characters: Character[] = [
{ id: "luke-skywalker", name: "卢克·天行者" },
{ id: "princess-leia", name: "莱娅公主" },
{ id: "han-solo", name: "汉·索罗" },
{ id: "darth-vader", name: "达斯·维达" },
{ id: "yoda", name: "尤达" },
{ id: "obi-wan-kenobi", name: "欧比旺·克诺比" },
{ id: "palpatine", name: "帕尔帕廷" },
{ id: "lando-calrissian", name: "兰多·卡瑞辛" },
{ id: "chewbacca", name: "楚巴卡" },
{ id: "r2-d2", name: "R2-D2" },
{ id: "c-3po", name: "C-3PO" },
{ id: "boba-fett", name: "波巴·费特" },
];
const inputValue = ref("");
const items = ref<Character[]>([]);
const loading = ref(false);
const loadingMore = ref(false);
const hasMore = ref(false);
let controller: AbortController | undefined;
function matches(query: string) {
const text = query.trim().toLocaleLowerCase();
return characters.filter(
(character) => !text || character.name.toLocaleLowerCase().includes(text),
);
}
async function load(query: string, offset: number, append: boolean) {
controller?.abort();
const current = new AbortController();
controller = current;
if (append) loadingMore.value = true;
else loading.value = true;
try {
const page = await new Promise<Character[]>((resolve, reject) => {
const timer = setTimeout(() => {
resolve(matches(query).slice(offset, offset + PAGE_SIZE));
}, PAGE_DELAY);
current.signal.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
},
{ once: true },
);
});
if (current.signal.aborted) return;
items.value = append ? [...items.value, ...page] : page;
hasMore.value = offset + page.length < matches(query).length;
} catch {
if (current.signal.aborted) return;
items.value = [];
hasMore.value = false;
} finally {
// A newer request owns the flags once it has taken over the controller.
if (controller === current) {
loading.value = false;
loadingMore.value = false;
}
}
}
function handleInputChange(next: string) {
inputValue.value = next;
void load(next, 0, false);
}
function loadMore() {
if (loading.value || loadingMore.value || !hasMore.value) return;
void load(inputValue.value, items.value.length, true);
}
onMounted(() => {
void load(inputValue.value, 0, false);
});
onBeforeUnmount(() => {
controller?.abort();
});
</script>
<template>
<ComboBox
allows-empty-collection
class="w-[256px]"
:input-value="inputValue"
@input-change="handleInputChange"
>
<Label>选择角色</Label>
<ComboBoxInputGroup>
<Input placeholder="星球大战角色…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox :aria-busy="loading || undefined">
<ListBoxItem
v-for="item in items"
:id="item.id"
:key="item.id"
:text-value="item.name"
>
{{ item.name }}
<ListBoxItemIndicator />
</ListBoxItem>
<template #empty>
<EmptyState class="p-1">
{{ loading ? "正在加载…" : "没有找到角色" }}
</EmptyState>
</template>
</ListBox>
<div v-if="hasMore" class="flex items-center justify-center gap-2 py-2">
<template v-if="loadingMore">
<Spinner size="sm" />
<span class="text-sm text-muted" role="status">加载更多…</span>
</template>
<Button v-else variant="ghost" size="sm" @click="loadMore">
加载更多…
</Button>
</div>
</ComboBoxPopover>
</ComboBox>
</template>
@@ -0,0 +1,61 @@
<script setup lang="ts">
import { ref } from "vue";
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const inputValue = ref("");
</script>
<template>
<div class="space-y-2">
<ComboBox
class="w-[256px]"
:input-value="inputValue"
@input-change="inputValue = $event"
>
<Label>搜索(受控输入)</Label>
<ComboBoxInputGroup>
<Input placeholder="输入以搜索…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
<p class="text-sm text-muted">输入值:{{ inputValue || "(空)" }}</p>
</div>
</template>
+59
View File
@@ -0,0 +1,59 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
type ListBoxKey,
} from "@heroui-vue/components";
const animals = [
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "bird", name: "鸟" },
{ id: "fish", name: "鱼" },
{ id: "hamster", name: "仓鼠" },
];
const selectedKey = ref<ListBoxKey | null>("cat");
const selectedAnimal = computed(() =>
animals.find((animal) => animal.id === selectedKey.value),
);
</script>
<template>
<div class="space-y-2">
<ComboBox
class="w-[256px]"
:selected-key="selectedKey"
@selection-change="selectedKey = $event"
>
<Label>动物(受控)</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
<p class="text-sm text-muted">已选:{{ selectedAnimal?.name || "无" }}</p>
</div>
</template>
@@ -0,0 +1,50 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const animals = [
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "bird", name: "鸟" },
{ id: "fish", name: "鱼" },
{ id: "hamster", name: "仓鼠" },
];
</script>
<template>
<ComboBox
class="w-[256px]"
:default-filter="
(text, inputValue) =>
!inputValue || text.toLowerCase().includes(inputValue.toLowerCase())
"
>
<Label>动物(自定义筛选)</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
@@ -0,0 +1,54 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
import { IconSelector } from "@tabler/icons-vue";
</script>
<template>
<ComboBox class="w-[256px]">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger>
<IconSelector class="size-3" aria-hidden="true" />
</ComboBoxTrigger>
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
@@ -0,0 +1,48 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const itemClass =
"rounded-lg data-[focused=true]:bg-muted/70 data-[selected=true]:font-medium data-[selected=true]:text-foreground";
</script>
<template>
<ComboBox class="w-64 gap-1.5">
<Label class="font-medium text-neutral-800 dark:text-neutral-100">
框架
</Label>
<ComboBoxInputGroup
class="rounded-xl border border-border/80 bg-surface shadow-sm ring-1 ring-black/5 transition-[box-shadow,border-color] focus-within:ring-2 focus-within:ring-neutral-400/25 dark:ring-white/10 dark:focus-within:ring-neutral-500/30"
>
<Input placeholder="搜索…" />
<ComboBoxTrigger class="text-muted" />
</ComboBoxInputGroup>
<ComboBoxPopover
class="rounded-xl border border-border/80 bg-surface p-1 shadow-lg ring-1 ring-black/5 dark:ring-white/10"
>
<ListBox>
<ListBoxItem :class="itemClass" id="react" text-value="React">
React
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem :class="itemClass" id="vue" text-value="Vue">
Vue
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem :class="itemClass" id="svelte" text-value="Svelte">
Svelte
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
@@ -0,0 +1,68 @@
<script setup lang="ts">
import {
Button,
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
FieldError,
Form,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const animals = [
{ id: "aardvark", name: "土豚" },
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "kangaroo", name: "袋鼠" },
{ id: "panda", name: "熊猫" },
{ id: "snake", name: "蛇" },
];
function validate(value: string | number | (string | number)[] | null) {
if (value == null) {
return "请选择一种动物";
}
if (value === "snake") {
return "不允许选择蛇";
}
return true;
}
function onSubmit() {
alert("表单提交成功!");
}
</script>
<template>
<Form class="flex w-[256px] flex-col gap-4" @submit.prevent="onSubmit">
<ComboBox is-required class="w-full" name="animal" :validate="validate">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<FieldError />
</ComboBox>
<Button class="w-fit" type="submit">提交</Button>
</Form>
</template>
@@ -0,0 +1,90 @@
<script setup lang="ts">
import {
Avatar,
AvatarFallback,
AvatarImage,
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Description,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const users = [
{
id: "1",
name: "Bob",
email: "bob@heroui.com",
fallback: "B",
avatarUrl:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/blue.jpg",
},
{
id: "2",
name: "Fred",
email: "fred@heroui.com",
fallback: "F",
avatarUrl:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/green.jpg",
},
{
id: "3",
name: "Martha",
email: "martha@heroui.com",
fallback: "M",
avatarUrl:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/purple.jpg",
},
{
id: "4",
name: "John",
email: "john@heroui.com",
fallback: "J",
avatarUrl:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/red.jpg",
},
{
id: "5",
name: "Jane",
email: "jane@heroui.com",
fallback: "J",
avatarUrl:
"https://heroui-assets.nyc3.cdn.digitaloceanspaces.com/avatars/orange.jpg",
},
];
</script>
<template>
<ComboBox class="w-[256px]">
<Label>用户</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索用户…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="user in users"
:id="user.id"
:key="user.id"
:text-value="user.name"
>
<Avatar size="sm">
<AvatarImage :src="user.avatarUrl" />
<AvatarFallback>{{ user.fallback }}</AvatarFallback>
</Avatar>
<div class="flex flex-col">
<Label>{{ user.name }}</Label>
<Description>{{ user.email }}</Description>
</div>
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox class="w-[256px]" default-selected-key="cat">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const animals = [
{ id: "aardvark", name: "土豚" },
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "kangaroo", name: "袋鼠" },
{ id: "panda", name: "熊猫" },
{ id: "snake", name: "蛇" },
];
</script>
<template>
<ComboBox class="w-[256px]">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
+51
View File
@@ -0,0 +1,51 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox is-disabled class="w-[256px]" default-selected-key="cat">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
+86
View File
@@ -0,0 +1,86 @@
<script setup lang="ts">
import {
Button,
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Description,
FieldError,
Form,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
import { ref } from "vue";
const animals = [
{ id: "aardvark", name: "土豚" },
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "kangaroo", name: "袋鼠" },
{ id: "panda", name: "熊猫" },
{ id: "snake", name: "蛇" },
];
const message = ref<string | null>(null);
function onSubmit(event: Event) {
event.preventDefault();
const formData = new FormData(event.currentTarget as HTMLFormElement);
message.value = `key:${formData.get("animal")}。文本:${formData.get("animal-text")}。`;
}
</script>
<template>
<Form class="flex w-[256px] flex-col gap-4" @submit="onSubmit">
<ComboBox is-required class="w-full" form-value="key" name="animal">
<Label>动物</Label>
<ComboBoxInputGroup>
<Input placeholder="选择动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>提交选中项的 key</Description>
<FieldError />
</ComboBox>
<ComboBox is-required class="w-full" form-value="text" name="animal-text">
<Label>动物(文本)</Label>
<ComboBoxInputGroup>
<Input placeholder="选择动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>提交选中项的文本</Description>
<FieldError />
</ComboBox>
<Button class="w-fit" type="submit">提交</Button>
<p v-if="message" class="text-sm text-muted">{{ message }}</p>
</Form>
</template>
+41
View File
@@ -0,0 +1,41 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
</script>
<template>
<div class="w-[400px] space-y-4">
<ComboBox full-width>
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</div>
</template>
+138
View File
@@ -0,0 +1,138 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Description,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
</script>
<template>
<div class="flex flex-col gap-8">
<div class="flex flex-col gap-2">
<p class="text-sm font-medium text-muted">聚焦(默认)</p>
<ComboBox class="w-[256px]" menu-trigger="focus">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>输入框获得焦点时打开弹出层</Description>
</ComboBox>
</div>
<div class="flex flex-col gap-2">
<p class="text-sm font-medium text-muted">输入</p>
<ComboBox class="w-[256px]" menu-trigger="input">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>用户编辑输入文本时打开弹出层</Description>
</ComboBox>
</div>
<div class="flex flex-col gap-2">
<p class="text-sm font-medium text-muted">手动</p>
<ComboBox class="w-[256px]" menu-trigger="manual">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>仅在按下触发按钮或使用方向键时打开弹出层</Description>
</ComboBox>
</div>
</div>
</template>
@@ -0,0 +1,47 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
ComboBoxValue,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const animals = [
{ id: "aardvark", name: "土豚" },
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "kangaroo", name: "袋鼠" },
{ id: "panda", name: "熊猫" },
{ id: "snake", name: "蛇" },
];
</script>
<template>
<ComboBox class="w-[256px]" selection-mode="multiple">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxValue placeholder="未选择任何动物" />
<ComboBoxPopover>
<ListBox selection-mode="multiple">
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
+66
View File
@@ -0,0 +1,66 @@
<script setup lang="ts">
import {
Button,
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
FieldError,
Form,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Surface,
} from "@heroui-vue/components";
function onSubmit(event: Event) {
event.preventDefault();
alert("表单提交成功!");
}
</script>
<template>
<Surface class="w-[320px] rounded-3xl p-6">
<Form class="flex w-full flex-col gap-4" @submit="onSubmit">
<ComboBox is-required class="w-full" name="animal" variant="secondary">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<FieldError />
</ComboBox>
<Button type="submit">提交</Button>
</Form>
</Surface>
</template>
+45
View File
@@ -0,0 +1,45 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const animals = [
{ id: "aardvark", name: "土豚" },
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "kangaroo", name: "袋鼠" },
{ id: "panda", name: "熊猫" },
{ id: "snake", name: "蛇" },
];
</script>
<template>
<ComboBox is-read-only class="w-[256px]" default-selected-key="cat">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
@@ -0,0 +1,51 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox class="w-[256px]" as="div" data-custom="foo">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
+75
View File
@@ -0,0 +1,75 @@
<script setup lang="ts">
import { ref } from "vue";
import {
Button,
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
FieldError,
Form,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const submitted = ref(false);
function submit(event: Event) {
const formData = new FormData(event.currentTarget as HTMLFormElement);
const data: Record<string, string> = {};
formData.forEach((value, key) => {
data[key] = value.toString();
});
submitted.value = "animal" in data;
}
</script>
<template>
<Form class="flex w-[256px] flex-col gap-4" @submit.prevent="submit">
<ComboBox is-required class="w-full" name="animal">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<FieldError />
</ComboBox>
<Button type="submit">提交</Button>
<p v-if="submitted" role="status" class="text-sm text-success">
表单提交成功!
</p>
</Form>
</template>
@@ -0,0 +1,107 @@
<script setup lang="ts">
import {
Button,
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Description,
FieldError,
Form,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
import { ref } from "vue";
const animals = [
{ id: "aardvark", name: "土豚" },
{ id: "cat", name: "猫" },
{ id: "dog", name: "狗" },
{ id: "kangaroo", name: "袋鼠" },
{ id: "panda", name: "熊猫" },
{ id: "snake", name: "蛇" },
];
const nativeMessage = ref<string | null>(null);
const ariaMessage = ref<string | null>(null);
function submitNative(event: Event) {
event.preventDefault();
nativeMessage.value = "已通过原生校验提交。";
}
function submitAria(event: Event) {
event.preventDefault();
ariaMessage.value = "已通过 ARIA 校验提交。";
}
</script>
<template>
<div class="flex flex-col gap-8">
<Form class="flex w-[256px] flex-col gap-4" @submit="submitNative">
<ComboBox
is-required
class="w-full"
name="animal"
validation-behavior="native"
>
<Label>动物(原生校验)</Label>
<ComboBoxInputGroup>
<Input placeholder="选择动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>值为空时阻止提交</Description>
<FieldError />
</ComboBox>
<Button class="w-fit" type="submit">提交</Button>
<p v-if="nativeMessage" class="text-sm text-muted">{{ nativeMessage }}</p>
</Form>
<Form class="flex w-[256px] flex-col gap-4" @submit="submitAria">
<ComboBox
is-required
class="w-full"
name="animal-aria"
validation-behavior="aria"
>
<Label>动物(ARIA 校验)</Label>
<ComboBoxInputGroup>
<Input placeholder="选择动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem
v-for="animal in animals"
:id="animal.id"
:key="animal.id"
:text-value="animal.name"
>
{{ animal.name }}
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>实时显示错误,不阻止提交</Description>
<FieldError />
</ComboBox>
<Button class="w-fit" type="submit">提交</Button>
<p v-if="ariaMessage" class="text-sm text-muted">{{ ariaMessage }}</p>
</Form>
</div>
</template>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Description,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox class="w-[256px]">
<Label>最喜欢的动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="aardvark" text-value="土豚">
土豚
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="panda" text-value="熊猫">
熊猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="snake" text-value="蛇">
蛇
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
<Description>搜索并选择你最喜欢的动物</Description>
</ComboBox>
</template>
@@ -0,0 +1,53 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
} from "@heroui-vue/components";
const disabledKeys = ["cat", "kangaroo"];
</script>
<template>
<ComboBox class="w-[256px]" :disabled-keys="disabledKeys">
<Label>动物</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索动物…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxItem id="dog" text-value="狗">
狗
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="cat" text-value="猫">
猫
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="bird" text-value="鸟">
鸟
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="kangaroo" text-value="袋鼠">
袋鼠
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="elephant" text-value="象">
象
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="tiger" text-value="老虎">
老虎
<ListBoxItemIndicator />
</ListBoxItem>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
@@ -0,0 +1,89 @@
<script setup lang="ts">
import {
ComboBox,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
Header,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
ListBoxSection,
Separator,
} from "@heroui-vue/components";
</script>
<template>
<ComboBox class="w-[256px]">
<Label>国家</Label>
<ComboBoxInputGroup>
<Input placeholder="搜索国家…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox>
<ListBoxSection>
<Header>北美洲</Header>
<ListBoxItem id="usa" text-value="美国">
美国
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="canada" text-value="加拿大">
加拿大
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="mexico" text-value="墨西哥">
墨西哥
<ListBoxItemIndicator />
</ListBoxItem>
</ListBoxSection>
<Separator />
<ListBoxSection>
<Header>欧洲</Header>
<ListBoxItem id="uk" text-value="英国">
英国
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="france" text-value="法国">
法国
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="germany" text-value="德国">
德国
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="spain" text-value="西班牙">
西班牙
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="italy" text-value="意大利">
意大利
<ListBoxItemIndicator />
</ListBoxItem>
</ListBoxSection>
<Separator />
<ListBoxSection>
<Header>亚洲</Header>
<ListBoxItem id="japan" text-value="日本">
日本
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="china" text-value="中国">
中国
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="india" text-value="印度">
印度
<ListBoxItemIndicator />
</ListBoxItem>
<ListBoxItem id="south-korea" text-value="韩国">
韩国
<ListBoxItemIndicator />
</ListBoxItem>
</ListBoxSection>
</ListBox>
</ComboBoxPopover>
</ComboBox>
</template>
+1 -1
View File
@@ -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 | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
@@ -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` 渲染 `<label for>`)、值/输入值/开关三套受控模型、集合 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`/自绘 `<path>`、每个示例都渲染真实 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)。
+4
View File
@@ -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 仓库。
+9
View File
@@ -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)。
+1 -1
View File
@@ -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 .",
+188
View File
@@ -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;
}
+1
View File
@@ -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);
+24
View File
@@ -1676,3 +1676,27 @@ export const errorMessageVariants = tv({
});
export type ErrorMessageVariants = VariantProps<typeof errorMessageVariants>;
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<typeof comboBoxVariants>;
@@ -0,0 +1,678 @@
<script lang="ts">
import {
computed,
defineComponent,
getCurrentInstance,
h,
mergeProps,
nextTick,
provide,
ref,
shallowRef,
useId,
watch,
watchEffect,
type PropType,
type SlotsType,
type VNodeChild,
} from "vue";
import { comboBoxVariants } from "@heroui-vue/styles";
import Popover from "../popover/Popover";
import {
useChoiceField,
useChoiceForm,
useChoiceValue,
} from "../choice/shared";
import { disabledContextKey } from "../field/disabled";
import { fieldContextKey, type FieldContext } from "../field/context";
import type { ValidateResult, ValidationBehavior } from "../field/context";
import { assertKey, copyKeys, type CollectionKey } from "../collection/keys";
import {
collectionOwnerKey,
type CollectionRecord,
type OwnedCollection,
} from "../collection/owner";
import { planComboBoxItems } from "./metadata";
import {
comboBoxKey,
type ComboBoxItem,
type ComboBoxMenuTrigger,
type ComboBoxValue,
} from "./context";
const contains = (text: string, inputValue: string) =>
!inputValue ||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
export default defineComponent({
name: "ComboBox",
inheritAttrs: false,
slots: Object as SlotsType<{
default?: (state: {
isOpen: boolean;
inputValue: string;
selectedKey: CollectionKey | null;
selectedKeys: CollectionKey[];
}) => VNodeChild;
}>,
props: {
modelValue: {
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
default: undefined,
},
value: {
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
default: undefined,
},
defaultValue: {
type: [String, Number, Array, null] as PropType<ComboBoxValue>,
default: undefined,
},
selectedKey: {
type: [String, Number, null] as PropType<CollectionKey | null>,
default: undefined,
},
defaultSelectedKey: {
type: [String, Number, null] as PropType<CollectionKey | null>,
default: undefined,
},
selectionMode: {
type: String as PropType<"single" | "multiple">,
default: "single",
},
inputValue: { type: String, default: undefined },
defaultInputValue: { type: String, default: "" },
items: Array as PropType<readonly ComboBoxItem[]>,
disabledKeys: Array as PropType<readonly CollectionKey[]>,
open: { type: Boolean, default: undefined },
isOpen: { type: Boolean, default: undefined },
defaultOpen: Boolean,
defaultFilter: Function as PropType<
(text: string, inputValue: string) => boolean
>,
isDisabled: Boolean,
disabled: Boolean,
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
allowsCustomValue: Boolean,
allowsEmptyCollection: Boolean,
menuTrigger: {
type: String as PropType<ComboBoxMenuTrigger>,
default: "focus",
},
shouldFocusWrap: Boolean,
fullWidth: Boolean,
variant: {
type: String as PropType<"primary" | "secondary">,
default: "primary",
},
name: String,
form: String,
formValue: {
type: String as PropType<"key" | "text">,
default: "key",
},
autoComplete: String,
autoFocus: Boolean,
validationBehavior: String as PropType<ValidationBehavior>,
validate: Function as PropType<(value: ComboBoxValue) => ValidateResult>,
placeholder: { type: String, default: "Select an item" },
as: { type: String, default: "div" },
asChild: { type: Boolean, default: false },
},
emits: {
"update:modelValue": (_value: ComboBoxValue) => true,
change: (_value: ComboBoxValue) => true,
"update:selectedKey": (_value: CollectionKey | null) => true,
selectionChange: (_value: CollectionKey | null) => true,
"update:inputValue": (_value: string) => true,
inputChange: (_value: string) => true,
"update:open": (_value: boolean) => true,
openChange: (_value: boolean) => true,
},
setup(props, { attrs, slots, emit, expose }) {
const instance = getCurrentInstance()!;
const present = (keys: string[]) =>
keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key));
const readValue = (): ComboBoxValue | undefined => {
if (present(["modelValue", "model-value"]))
return props.modelValue ?? null;
if (present(["value"])) return props.value ?? null;
if (present(["selectedKey", "selected-key"]))
return props.selectedKey ?? null;
return undefined;
};
const model = useChoiceValue<ComboBoxValue | undefined>(
readValue,
() => props.defaultValue ?? props.defaultSelectedKey ?? null,
["modelValue", "model-value", "value", "selectedKey", "selected-key"],
(value) => {
const next = value ?? null;
emit("update:modelValue", next);
emit("change", next);
const single =
props.selectionMode === "multiple"
? ((Array.isArray(next) ? next[0] : next) ?? null)
: Array.isArray(next)
? (next[0] ?? null)
: next;
emit("update:selectedKey", single);
emit("selectionChange", single);
},
);
const value = computed<ComboBoxValue>(() => {
const raw = model.value.value ?? null;
if (props.selectionMode === "multiple")
return raw === null ? [] : Array.isArray(raw) ? raw : [raw];
return Array.isArray(raw) ? (raw[0] ?? null) : raw;
});
const keys = computed<readonly CollectionKey[]>(() => {
const raw = value.value;
if (
props.selectionMode === "multiple" &&
raw !== null &&
!Array.isArray(raw)
)
throw new TypeError("Multiple ComboBox expects a key array.");
const next = copyKeys(
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
);
if (props.selectionMode === "single" && next.length > 1)
throw new TypeError("Single ComboBox expects one key or null.");
return Object.freeze(next);
});
const inputModel = useChoiceValue<string | undefined>(
() => props.inputValue,
() => props.defaultInputValue,
["inputValue", "input-value"],
(next) => {
emit("update:inputValue", next ?? "");
emit("inputChange", next ?? "");
},
);
const inputValue = computed(() => inputModel.value.value ?? "");
const openModel = useChoiceValue<boolean | undefined>(
() => (present(["open"]) ? props.open : props.isOpen),
() => props.defaultOpen,
["open", "isOpen", "is-open"],
(next) => {
emit("update:open", !!next);
emit("openChange", !!next);
},
);
const open = computed(() => !!openModel.value.value);
const collection = shallowRef<OwnedCollection>();
const discovered = shallowRef<CollectionRecord[]>([]);
watchEffect(() => {
if (!collection.value) return;
const next = collection.value.items();
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
discovered.value = next;
});
const planned = shallowRef<CollectionRecord[]>([]);
const complete = ref(false);
const records = computed<CollectionRecord[]>(() => {
const explicit = props.items?.map((item) => {
assertKey(item.id);
return {
key: item.id,
text: item.textValue,
disabled: !!item.isDisabled,
} satisfies CollectionRecord;
});
// Caller data wins; otherwise the complete slot plan is authoritative for
// a closed ComboBox, and mounted rows fill in when the plan is opaque.
const base =
explicit ??
(complete.value
? planned.value
: discovered.value.length
? discovered.value
: planned.value);
return base.map((record) => ({
...record,
disabled: record.disabled || !!props.disabledKeys?.includes(record.key),
}));
});
const filter = (record: CollectionRecord) =>
props.defaultFilter
? props.defaultFilter(record.text, inputValue.value)
: contains(record.text, inputValue.value);
const instanceId = useId();
const inputId = `hv-combo-box-${instanceId}-input`;
const listId = `hv-combo-box-${instanceId}-listbox`;
const valueId = `hv-combo-box-${instanceId}-value`;
const field = useChoiceField<ComboBoxValue>(props, attrs, {
kind: "group",
value,
validate: (current) => props.validate?.(current),
satisfied: () =>
props.allowsCustomValue
? inputValue.value.trim().length > 0
: keys.value.length > 0,
requiredMessage: "请选择一个选项。",
});
// A combobox input is a text control: Label must render `<label for>` and
// point at the composed input, not at an unrelated generated id.
provide(fieldContextKey, {
...field.field,
kind: "text",
controlId: computed(() => inputId),
} as FieldContext);
provide(disabledContextKey, field.field.disabled);
const keyboardIntent = ref(true);
const activeKey = ref<CollectionKey>();
const cursor = ref<CollectionKey>();
const inputElement = ref<HTMLInputElement>();
let anchor: (() => HTMLElement | undefined) | undefined;
const registerAnchor = (element: () => HTMLElement | undefined) => {
anchor = element;
};
const activeId = computed<string | undefined>(() => {
if (!open.value || activeKey.value === undefined) return undefined;
return collection.value?.optionId?.(activeKey.value);
});
function request(next: CollectionKey[]) {
if (field.field.disabled.value || field.field.readOnly.value) return;
const candidate = (key: CollectionKey) =>
records.value.find((record) => record.key === key);
if (
next.some(
(key) => candidate(key)?.disabled && !keys.value.includes(key),
)
)
return;
if (
next.length === keys.value.length &&
next.every((key) => keys.value.includes(key))
)
return;
if (!next.length && !keys.value.length) return;
if (
!next.length &&
!props.allowsCustomValue &&
!props.allowsEmptyCollection &&
(props.isRequired || field.field.required.value)
)
return;
field.edit();
model.request(
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
);
if (props.selectionMode === "single") {
const record = next.length ? candidate(next[0]) : undefined;
if (record && !props.allowsCustomValue) inputModel.request(record.text);
setOpen(false);
}
}
function setOpen(next: boolean) {
if (next === open.value) return;
if (
next &&
(field.field.disabled.value || field.field.readOnly.value) === true
)
return;
if (
next &&
props.items &&
!props.items.length &&
!props.allowsEmptyCollection
)
return;
openModel.request(next);
if (next) {
void nextTick(() => {
const record =
records.value.find(
(item) =>
keys.value.includes(item.key) && filter(item) && !item.disabled,
) ?? records.value.find((item) => filter(item) && !item.disabled);
void setActive(record?.key);
});
} else {
activeKey.value = undefined;
}
}
async function setActive(key: CollectionKey | undefined) {
cursor.value = key;
activeKey.value = key;
if (key !== undefined) await collection.value?.reveal?.(key);
}
function moveActive(delta: 1 | -1) {
const items = records.value.filter(
(record) => filter(record) && !record.disabled,
);
if (!items.length) {
void setActive(undefined);
return;
}
const index = items.findIndex((item) => item.key === activeKey.value);
const next =
index < 0
? items[delta > 0 ? 0 : items.length - 1]
: items[
props.shouldFocusWrap
? (index + delta + items.length) % items.length
: Math.min(Math.max(index + delta, 0), items.length - 1)
];
if (next) void setActive(next.key);
}
function confirmActive() {
const key = activeKey.value;
if (key === undefined) return;
const record = records.value.find(
(item) => item.key === key && filter(item) && !item.disabled,
);
if (!record) return;
request([key]);
}
const composing = ref(false);
watch(
// A selection change (initial, external or accepted) owns the single-select
// text; typing inside an allows-custom-value combo must not be overwritten.
() => `${keys.value.map(String).join("\u0000")}|${records.value.length}`,
() => {
if (props.selectionMode !== "single") return;
const selected = records.value.find((record) =>
keys.value.includes(record.key),
);
if (!selected) return;
if (inputValue.value !== selected.text)
inputModel.request(selected.text);
},
{ immediate: true },
);
function setInputValue(next: string) {
inputModel.request(next);
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
// Keep the active row on the first match of the new filter.
if (next) {
const first = records.value.find(
(record) => filter(record) && !record.disabled,
);
if (first) void setActive(first.key);
}
if (
props.selectionMode === "single" &&
!props.allowsCustomValue &&
keys.value.length
) {
const selected = records.value.find((record) =>
keys.value.includes(record.key),
);
if (selected && next !== selected.text) request([]);
}
}
function keydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.isComposing || event.keyCode === 229)
return;
if (field.field.disabled.value || field.field.readOnly.value) return;
keyboardIntent.value = true;
const meta = event.metaKey || event.ctrlKey || event.altKey;
if (meta) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!open.value) {
setOpen(true);
return;
}
moveActive(event.key === "ArrowDown" ? 1 : -1);
return;
}
if (event.key === "Home" || event.key === "End") {
if (!open.value) return;
event.preventDefault();
const items = records.value.filter(
(record) => filter(record) && !record.disabled,
);
const target = event.key === "Home" ? items[0] : items.at(-1);
if (target) void setActive(target.key);
return;
}
if (event.key === "Enter") {
event.preventDefault();
if (event.repeat) return;
confirmActive();
return;
}
if (event.key === "Escape") {
if (!open.value) return;
event.preventDefault();
setOpen(false);
return;
}
if (event.key === "Tab") {
setOpen(false);
}
}
function focusInput() {
if (props.menuTrigger === "focus") setOpen(true);
}
function describedBy() {
return field.describedBy();
}
const formValueText = computed<string | undefined>(() => {
if (!props.name) return undefined;
if (props.formValue === "text" || props.allowsCustomValue) {
const texts = keys.value
.map((key) => records.value.find((item) => item.key === key)?.text)
.filter((text): text is string => !!text);
return texts.length ? texts.join(",") : inputValue.value || undefined;
}
return keys.value.length ? keys.value.map(String).join(",") : undefined;
});
const invalid = computed(() => field.field.invalid.value);
const slotsBase = computed(() =>
comboBoxVariants({ fullWidth: props.fullWidth }),
);
provide(collectionOwnerKey, {
keys,
mode: computed(() => props.selectionMode),
disabled: field.field.disabled,
readOnly: field.field.readOnly,
disabledKeys: computed(() => props.disabledKeys ?? []),
id: listId,
labelledBy: () =>
field.labelledBy() ?? (attrs["aria-label"] ? undefined : inputId),
ariaLabel: () =>
typeof attrs["aria-label"] === "string"
? attrs["aria-label"]
: undefined,
request,
action: (key) => {
if (props.selectionMode === "single") setOpen(false);
void key;
},
leave: () => setOpen(false),
connect: (next) => {
if (collection.value && collection.value !== next)
throw new Error("ComboBox supports one ListBox.");
collection.value = next;
return () => {
if (collection.value === next) collection.value = undefined;
};
},
filter,
virtualFocus: () => true,
activeKey,
keyboardIntent,
isOpen: () => open.value,
});
const inputProps = () => ({
id: inputId,
role: "combobox",
autocomplete: props.autoComplete ?? "off",
spellcheck: false,
"aria-expanded": open.value,
"aria-controls": open.value ? listId : undefined,
"aria-activedescendant": activeId.value,
"aria-autocomplete": "list" as const,
"aria-haspopup": "listbox" as const,
"aria-label": attrs["aria-label"] as string | undefined,
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"] ? undefined : field.labelledBy()),
"aria-describedby": describedBy(),
"aria-invalid": invalid.value || undefined,
readonly: field.field.readOnly.value || undefined,
disabled: field.field.disabled.value || undefined,
required:
(field.behavior.value === "native" && field.field.required.value) ||
undefined,
onKeydown: keydown,
onFocus: focusInput,
onCompositionstart: () => {
composing.value = true;
},
onCompositionend: () => {
composing.value = false;
},
});
provide(comboBoxKey, {
field,
slots: slotsBase,
open,
setOpen,
inputValue,
setInputValue,
inputId,
listId,
valueId,
placeholder: () => props.placeholder,
activeKey,
activeId,
collection,
keys,
records,
selectedItems: computed(() =>
keys.value.map((key) => ({
key,
textValue:
records.value.find((record) => record.key === key)?.text ??
String(key),
})),
),
selectionMode: computed(() => props.selectionMode),
allowsCustomValue: () => props.allowsCustomValue,
menuTrigger: () => props.menuTrigger,
inputElement,
registerAnchor,
inputProps,
formValueText,
invalid,
disabled: field.field.disabled,
});
useChoiceForm(
inputElement,
() => {
model.reset();
inputModel.reset();
field.reset();
setOpen(false);
},
() => {
field.validity(inputElement.value);
},
);
watchEffect(() => {
// `required` plus the custom message live on the visible input, which is
// the control the browser blocks on.
const element = inputElement.value;
if (!element) return;
element.required =
field.behavior.value === "native" && field.field.required.value;
field.validity(element);
});
watchEffect(() => {
if (!open.value || props.allowsEmptyCollection) return;
if (!records.value.length) return;
const eligibleRecords = records.value.filter(
(record) => filter(record) && !record.disabled,
);
if (!eligibleRecords.length) setOpen(false);
});
expose({
element: () => anchor?.(),
input: inputElement,
open: () => setOpen(true),
close: () => setOpen(false),
focus: () => inputElement.value?.focus(),
});
return () => {
const rendered = slots.default?.({
isOpen: open.value,
inputValue: inputValue.value,
selectedKey: Array.isArray(value.value)
? null
: (value.value as CollectionKey | null),
selectedKeys: [...keys.value],
});
const children = Array.isArray(rendered)
? rendered
: rendered == null
? []
: [rendered];
const plan = planComboBoxItems(children);
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
planned.value = plan.records;
complete.value = plan.complete;
const nodes = field.prepare(children, true);
return h(
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,
form: props.form,
value: formValueText.value ?? "",
"data-slot": "combo-box-form-value",
})
: null,
],
),
},
);
};
},
});
</script>
@@ -0,0 +1,85 @@
<script lang="ts">
/**
* Container for the combobox input and its trigger. It also composes the
* consumer's `Input` into the combobox control: value binding, ARIA and the
* keyboard contract are injected onto that single input, so focus never leaves
* it while the list navigates.
*/
import {
cloneVNode,
defineComponent,
h,
isVNode,
mergeProps,
onMounted,
onUpdated,
ref,
watch,
type VNode,
type VNodeChild,
} from "vue";
import { injectPopoverRootContext } from "reka-ui";
import { useComboBox } from "./context";
import { elementFromRef } from "./dom";
function componentName(node: VNode): string | undefined {
const type = node.type as Record<string, unknown> | undefined;
const name = type?.name ?? type?.__name;
return typeof name === "string" ? name : undefined;
}
export default defineComponent({
name: "ComboBoxInputGroup",
inheritAttrs: false,
setup(_props, { attrs, slots }) {
const ctx = useComboBox();
const popover = injectPopoverRootContext();
const root = ref<HTMLElement>();
ctx.registerAnchor(() => elementFromRef(root.value));
watch(
root,
() => {
if (popover) popover.triggerElement.value = elementFromRef(root.value);
},
{ immediate: true, flush: "post" },
);
onMounted(() => {
if (popover) popover.triggerElement.value = elementFromRef(root.value);
});
onUpdated(() => {
if (popover) popover.triggerElement.value = elementFromRef(root.value);
});
function compose(node: VNodeChild): VNodeChild {
if (!isVNode(node) || componentName(node) !== "Input") return node;
return cloneVNode(node, {
...ctx.inputProps(),
modelValue: ctx.inputValue.value,
"onUpdate:modelValue": (next: string) => ctx.setInputValue(next),
ref: (instance: unknown) => {
ctx.inputElement.value = elementFromRef(instance) as
HTMLInputElement | undefined;
},
});
}
return () => {
const rendered = slots.default?.() ?? [];
const children = (
Array.isArray(rendered) ? rendered : [rendered]
) as VNodeChild[];
return h(
"div",
mergeProps(attrs, {
ref: root,
class: ctx.slots.value.inputGroup(),
"data-slot": "combo-box-input-group",
"data-disabled": ctx.disabled.value || undefined,
}),
children.map(compose),
);
};
},
});
</script>
@@ -0,0 +1,43 @@
<script lang="ts">
import { defineComponent, h, mergeProps } from "vue";
import PopoverContent from "../popover/PopoverContent.vue";
import { useComboBox } from "./context";
import type { OverlayPlacement } from "../overlay/placement";
export default defineComponent({
name: "ComboBoxPopover",
inheritAttrs: false,
props: {
placement: { type: String as () => OverlayPlacement, default: "bottom" },
offset: { type: Number, default: 8 },
to: [String, Object] as unknown as () => string | HTMLElement,
shouldFlip: { type: Boolean, default: true },
containerPadding: { type: Number, default: 12 },
},
setup(props, { attrs, slots }) {
const ctx = useComboBox();
return () =>
h(
PopoverContent,
mergeProps(attrs, {
placement: props.placement,
offset: props.offset,
to: props.to,
shouldFlip: props.shouldFlip,
containerPadding: props.containerPadding,
class: ctx.slots.value.popover(),
id: `${ctx.listId}-popover`,
role: "presentation",
"data-slot": "combo-box-popover",
style: {
"--trigger-width": "var(--reka-popover-trigger-width)",
"--trigger-anchor-point": "var(--reka-popper-transform-origin)",
},
// Focus stays in the combobox input; the list only tracks an active row.
onOpenAutoFocus: (event: Event) => event.preventDefault(),
}),
{ default: () => slots.default?.() },
);
},
});
</script>
@@ -0,0 +1,70 @@
<script lang="ts">
import { defineComponent, h, mergeProps } from "vue";
import { useComboBox } from "./context";
// Baseline chevron, adapted from HeroUI ce90ea3 icons.tsx (Apache-2.0).
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";
export default defineComponent({
name: "ComboBoxTrigger",
inheritAttrs: false,
props: { isDisabled: { type: Boolean, default: false } },
setup(props, { attrs, slots }) {
const ctx = useComboBox();
const disabled = () => props.isDisabled || ctx.disabled.value;
function toggle(event: MouseEvent) {
if (event.defaultPrevented || disabled()) return;
ctx.setOpen(!ctx.open.value);
ctx.inputElement.value?.focus({ preventScroll: true });
}
return () => {
const open = ctx.open.value;
const custom = slots.default?.() ?? [];
const icon =
custom.length > 0
? custom
: [
h(
"svg",
{
"aria-hidden": "true",
"data-slot": "combo-box-trigger-default-icon",
fill: "none",
height: 16,
role: "presentation",
viewBox: "0 0 16 16",
width: 16,
},
[
h("path", {
d: CHEVRON_PATH,
fill: "currentColor",
"fill-rule": "evenodd",
"clip-rule": "evenodd",
}),
],
),
];
const injected: Record<string, unknown> = {
type: "button",
class: ctx.slots.value.trigger(),
"data-slot": "combo-box-trigger",
tabindex: -1,
disabled: disabled() || undefined,
"aria-label":
typeof attrs["aria-label"] === "string"
? attrs["aria-label"]
: "Show suggestions",
"aria-expanded": open,
onClick: toggle,
};
if (open) {
injected["data-open"] = true;
injected["aria-controls"] = ctx.listId;
}
if (disabled()) injected["data-disabled"] = true;
return h("button", mergeProps(attrs, injected), [icon]);
};
},
});
</script>
@@ -0,0 +1,35 @@
<script lang="ts">
import { defineComponent, h, mergeProps } from "vue";
import { useComboBox } from "./context";
export default defineComponent({
name: "ComboBoxValue",
inheritAttrs: false,
props: { placeholder: { type: String, default: undefined } },
setup(props, { attrs, slots }) {
const ctx = useComboBox();
return () => {
const selected = ctx.selectedItems.value;
const isPlaceholder = selected.length === 0;
const text = selected
.map((item) => item.textValue)
.join(", ")
.trim();
const placeholder = props.placeholder ?? ctx.placeholder();
const content =
slots.default?.({ isPlaceholder, selectedItems: selected }) ??
(isPlaceholder ? placeholder : text);
return h(
"div",
mergeProps(attrs, {
class: ctx.slots.value.value(),
id: ctx.valueId,
"data-slot": "combo-box-value",
"data-placeholder": isPlaceholder || undefined,
}),
content,
);
};
},
});
</script>
@@ -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<typeof useChoiceField<ComboBoxValue>>;
slots: ComputedRef<ReturnType<typeof comboBoxVariants>>;
open: ComputedRef<boolean>;
setOpen: (open: boolean) => void;
inputValue: ComputedRef<string>;
setInputValue: (value: string) => void;
inputId: string;
listId: string;
valueId: string;
placeholder: () => string;
activeKey: Ref<CollectionKey | undefined>;
activeId: ComputedRef<string | undefined>;
collection: Ref<OwnedCollection | undefined>;
keys: ComputedRef<readonly CollectionKey[]>;
records: ComputedRef<CollectionRecord[]>;
selectedItems: ComputedRef<ComboBoxSelectedItem[]>;
selectionMode: ComputedRef<"single" | "multiple">;
allowsCustomValue: () => boolean;
menuTrigger: () => ComboBoxMenuTrigger;
inputElement: Ref<HTMLInputElement | undefined>;
registerAnchor: (element: () => HTMLElement | undefined) => void;
/** ARIA plus input handlers injected onto the composed `Input`. */
inputProps: () => Record<string, unknown>;
formValueText: ComputedRef<string | undefined>;
invalid: ComputedRef<boolean>;
disabled: ComputedRef<boolean>;
}
export const comboBoxKey: InjectionKey<ComboBoxContext> =
Symbol("hv-combo-box");
export function useComboBox(): ComboBoxContext {
const context = inject(comboBoxKey, undefined);
if (!context) throw new Error("ComboBox parts require ComboBox.");
return context;
}
@@ -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;
}
@@ -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 };
}
+21
View File
@@ -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";
+21
View File
@@ -744,3 +744,24 @@ export type TagRemoveButtonProps = InstanceType<
import type ErrorMessage from "./components/error-message/ErrorMessage.vue";
export type ErrorMessageProps = InstanceType<typeof ErrorMessage>["$props"];
import type ComboBox from "./components/combo-box/ComboBox.vue";
export type ComboBoxProps = InstanceType<typeof ComboBox>["$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<typeof ComboBoxValue>["$props"];
import type ComboBoxPopover from "./components/combo-box/ComboBoxPopover.vue";
export type ComboBoxPopoverProps = InstanceType<
typeof ComboBoxPopover
>["$props"];
+190
View File
@@ -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(/<ComponentPreview name="combo-box-([^"]+)"/g),
].map((match) => 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("<template>");
expect(source, name).not.toContain("className");
expect(source, name).not.toContain("@gravity-ui/icons");
expect(source, name).not.toContain("<path");
}
});
it("documents Vue props and events instead of React ones", () => {
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<HTMLInputElement>('[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<HTMLInputElement>('[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<HTMLInputElement>(
'input[type="hidden"][name]',
),
];
expect(hidden.map((input) => input.name).sort()).toEqual([
"animal",
"animal-text",
]);
wrapper.unmount();
mounted.pop();
});
});
+657
View File
@@ -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<string, unknown> = {},
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<HTMLInputElement>('[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<string | number | null>("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<HTMLButtonElement>(
'[data-slot="combo-box-trigger"]',
)!;
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
expect(input().getAttribute("aria-expanded")).toBe("true");
});
});