feat(autocomplete): migrate Autocomplete with popover-owned filtering
Port the fixed-baseline Autocomplete onto the B02a collection protocol. The trigger is the single Tab entry; opening moves focus to the search box inside the popover, which owns filtering, aria-activedescendant and keyboard navigation while the list only tracks an active row. - Seven parts: root (field, value/open models, form value, owner wiring), trigger (anchor + activation), value (scoped slot with selectedItems and selectedText instead of copied item subtrees), indicator, clear button, popover (measured trigger width), filter (owns the search text and composes the inner SearchFieldInput into the combobox control). - Filter exposes input-value/update:inputValue/inputChange, matching ComboBox. - Confirming the active row in multiple mode now toggles it instead of replacing the accepted set (ComboBox shared the same bug). - ComboBox shows the accepted label on the first render via a display value that falls back to the selected record, so preselected fields are readable before the selection watcher runs (including SSR). - Popovers measure the anchor with a ResizeObserver because Reka does not publish the anchor size; the caller's root class is merged again so the trigger fills the field width. - 24 baseline previews, Chinese doc page, navigation, 17 behaviour tests, 5 demo/document contracts and an independent tarball consumption script for both pickers. Not included: the full bundler/NodeNext type matrix (B02d).
This commit is contained in:
@@ -25,6 +25,11 @@ export const componentItems: DocsItem[] = [
|
||||
url: "/components/alert-dialog",
|
||||
category: "overlays",
|
||||
},
|
||||
{
|
||||
title: "Autocomplete 自动完成",
|
||||
url: "/components/autocomplete",
|
||||
category: "pickers",
|
||||
},
|
||||
{
|
||||
title: "Avatar 头像",
|
||||
url: "/components/avatar",
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
---
|
||||
title: Autocomplete 自动完成
|
||||
description: 结合选择与过滤,让用户从选项列表中搜索并选择
|
||||
component: autocomplete
|
||||
group: 组件
|
||||
---
|
||||
|
||||
## 用法
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete class="w-[256px]" placeholder="选择州/省">
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem id="california" text-value="California">
|
||||
California
|
||||
</ListBoxItem>
|
||||
<ListBoxItem id="texas" text-value="Texas">Texas</ListBoxItem>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
```
|
||||
|
||||
<ComponentPreview name="autocomplete-default" />
|
||||
|
||||
触发器是唯一 Tab 入口;打开后焦点进入弹层内的搜索框,由它负责过滤、`aria-activedescendant` 与方向键导航,列表只维护活动行。
|
||||
|
||||
## 组件结构
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Description,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete placeholder="选择一项">
|
||||
<Label>分类</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<Description>说明</Description>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索分类">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem id="news" text-value="资讯">
|
||||
资讯
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
```
|
||||
|
||||
上游的对象式子部件 `Autocomplete.Trigger` / `.Value` / `.Indicator` / `.Popover` / `.Filter` / `.ClearButton` 在本库中是具名导出 `AutocompleteTrigger` / `AutocompleteValue` / `AutocompleteIndicator` / `AutocompletePopover` / `AutocompleteFilter` / `AutocompleteClearButton`。
|
||||
|
||||
## 示例
|
||||
|
||||
### 变体
|
||||
|
||||
Autocomplete 支持两种视觉变体:`primary`(默认,带阴影)与 `secondary`(低强调、无阴影,适用于 Surface 内)。
|
||||
|
||||
<ComponentPreview name="autocomplete-variants" />
|
||||
|
||||
### 宽度充满
|
||||
|
||||
<ComponentPreview name="autocomplete-full-width" />
|
||||
|
||||
### 带描述
|
||||
|
||||
<ComponentPreview name="autocomplete-with-description" />
|
||||
|
||||
### 必填
|
||||
|
||||
<ComponentPreview name="autocomplete-required" />
|
||||
|
||||
### 禁用
|
||||
|
||||
<ComponentPreview name="autocomplete-disabled" />
|
||||
|
||||
### 含禁用选项
|
||||
|
||||
<ComponentPreview name="autocomplete-with-disabled-options" />
|
||||
|
||||
### 允许空选项
|
||||
|
||||
`allows-empty-collection` 允许集合为空时仍可打开并交互。
|
||||
|
||||
<ComponentPreview name="autocomplete-allows-empty-collection" />
|
||||
|
||||
### 分组选项
|
||||
|
||||
<ComponentPreview name="autocomplete-with-sections" />
|
||||
|
||||
### 多选
|
||||
|
||||
<ComponentPreview name="autocomplete-multiple-select" />
|
||||
|
||||
上游提醒:多选时 `Autocomplete.Value` 默认会把每个选中项在 `ListBox.Item` 中的子树复制到触发器里。本库不复制子树,而是给 `AutocompleteValue` 的作用域插槽提供 `selectedItems`(`{ key, textValue }[]`)与 `selectedText`(纯文本),由调用方决定渲染纯文本还是标签:
|
||||
|
||||
```vue
|
||||
<AutocompleteValue>
|
||||
<template #default="{ isPlaceholder, defaultChildren, selectedText }">
|
||||
{{ isPlaceholder ? defaultChildren : selectedText }}
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
```
|
||||
|
||||
需要可移除标签时用 `selectedItems` 自行渲染,示例见「多选」。
|
||||
|
||||
### 受控组件
|
||||
|
||||
<ComponentPreview name="autocomplete-controlled" />
|
||||
|
||||
### 受控多选
|
||||
|
||||
<ComponentPreview name="autocomplete-controlled-multiple" />
|
||||
|
||||
### 受控展开状态
|
||||
|
||||
<ComponentPreview name="autocomplete-controlled-open-state" />
|
||||
|
||||
### 异步搜索
|
||||
|
||||
<ComponentPreview name="autocomplete-asynchronous-filtering" />
|
||||
|
||||
### 自定义指示器
|
||||
|
||||
<ComponentPreview name="autocomplete-custom-indicator" />
|
||||
|
||||
### 自定义展示值
|
||||
|
||||
用 `AutocompleteValue` 的作用域插槽自定义展示值。
|
||||
|
||||
<ComponentPreview name="autocomplete-custom-value" />
|
||||
|
||||
### 表面样式
|
||||
|
||||
在 Surface 内使用时请用 `variant="secondary"`。
|
||||
|
||||
<ComponentPreview name="autocomplete-on-surface" />
|
||||
|
||||
### 虚拟滚动
|
||||
|
||||
集合使用 `ListBox` 的 `items` + `virtualized` + `row-height` 渲染可见窗口,仅挂载视口内的行。
|
||||
|
||||
<ComponentPreview name="autocomplete-virtualization" />
|
||||
|
||||
## 高级示例
|
||||
|
||||
### 用户选择
|
||||
|
||||
<ComponentPreview name="autocomplete-user-selection" />
|
||||
|
||||
### 用户多选
|
||||
|
||||
<ComponentPreview name="autocomplete-user-selection-multiple" />
|
||||
|
||||
### 地点搜索
|
||||
|
||||
<ComponentPreview name="autocomplete-location-search" />
|
||||
|
||||
### 标签组选择
|
||||
|
||||
<ComponentPreview name="autocomplete-tag-group-selection" />
|
||||
|
||||
### 邮件收件人
|
||||
|
||||
<ComponentPreview name="autocomplete-email-recipients" />
|
||||
|
||||
## 自定义样式
|
||||
|
||||
### Tailwind CSS
|
||||
|
||||
<ComponentPreview name="autocomplete-custom-styles" />
|
||||
|
||||
### 全局 CSS
|
||||
|
||||
可使用 `@layer components` 指令自定义 Autocomplete 组件类。
|
||||
|
||||
```css
|
||||
@layer components {
|
||||
.hv-autocomplete {
|
||||
@apply flex flex-col gap-1;
|
||||
}
|
||||
|
||||
.hv-autocomplete__trigger {
|
||||
@apply rounded-lg border border-border bg-surface p-2;
|
||||
}
|
||||
|
||||
.hv-autocomplete__value {
|
||||
@apply text-current;
|
||||
}
|
||||
|
||||
.hv-autocomplete__clear-button {
|
||||
@apply text-muted hover:text-foreground;
|
||||
}
|
||||
|
||||
.hv-autocomplete__indicator {
|
||||
@apply text-muted;
|
||||
}
|
||||
|
||||
.hv-autocomplete__popover {
|
||||
@apply rounded-lg border border-border bg-surface p-2;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 样式参考
|
||||
|
||||
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。类名前缀为 `hv-`。
|
||||
|
||||
### CSS 类
|
||||
|
||||
Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/autocomplete.css)):
|
||||
|
||||
#### 基础类
|
||||
|
||||
- `.hv-autocomplete` - 根容器
|
||||
- `.hv-autocomplete__trigger` - 展示值并打开弹层的容器
|
||||
- `.hv-autocomplete__value` - 值或占位符
|
||||
- `.hv-autocomplete__clear-button` - 清除已选值的按钮
|
||||
- `.hv-autocomplete__indicator` - 下拉指示图标
|
||||
- `.hv-autocomplete__popover` - 弹层容器
|
||||
- `.hv-autocomplete__filter` - 过滤包装器
|
||||
|
||||
#### 变体类
|
||||
|
||||
- `.hv-autocomplete--primary` - 带阴影的主变体(默认)
|
||||
- `.hv-autocomplete--secondary` - 无阴影的次变体
|
||||
|
||||
#### 状态类
|
||||
|
||||
- `.hv-autocomplete[data-invalid="true"]` - 无效状态
|
||||
- `.hv-autocomplete[data-disabled="true"]` - 禁用状态
|
||||
- `.hv-autocomplete__trigger[data-focus-visible="true"]` - 触发器聚焦
|
||||
- `.hv-autocomplete__trigger[data-disabled="true"]` - 触发器禁用
|
||||
- `.hv-autocomplete__trigger[data-open="true"]` - 展开状态
|
||||
- `.hv-autocomplete__value[data-placeholder="true"]` - 占位符状态
|
||||
- `.hv-autocomplete__clear-button[data-empty="true"]` - 无选择时隐藏清除按钮
|
||||
- `.hv-autocomplete__indicator[data-open="true"]` - 打开时图标旋转 180°
|
||||
|
||||
### 交互状态
|
||||
|
||||
- **Hover**:触发器上 `:hover` 或 `[data-hovered="true"]`
|
||||
- **Focus**:触发器与搜索框上 `:focus-visible`
|
||||
- **Disabled**:根与触发器上 `[data-disabled="true"]`
|
||||
- **Open**:触发器上 `[data-open="true"]`、指示器上 `[data-open="true"]`
|
||||
|
||||
## API 参考
|
||||
|
||||
### Autocomplete
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| ------------------------- | ----------------------------------- | ------------------ | ---------------------------------------------- |
|
||||
| `placeholder` | `string` | `'Select an item'` | 为空时显示的占位文本 |
|
||||
| `selection-mode` | `'single' \| 'multiple'` | `'single'` | 单选或多选 |
|
||||
| `allows-empty-collection` | `boolean` | `false` | 是否允许空集合 |
|
||||
| `is-open` | `boolean` | - | 弹层打开状态(受控,`v-model:open` 亦可) |
|
||||
| `default-open` | `boolean` | `false` | 弹层默认打开状态(非受控) |
|
||||
| `disabled-keys` | `Array<string \| number>` | - | 禁用项的 key |
|
||||
| `is-disabled` | `boolean` | `false` | 是否禁用 |
|
||||
| `model-value` | `string \| number \| Array \| null` | - | 当前值(受控,`v-model`) |
|
||||
| `value` | `string \| number \| Array \| null` | - | 同 `model-value`(受控别名) |
|
||||
| `default-value` | `string \| number \| Array \| null` | - | 初始值(非受控) |
|
||||
| `is-required` | `boolean` | `false` | 是否必填 |
|
||||
| `is-invalid` | `boolean` | `false` | 值是否无效 |
|
||||
| `name` | `string` | - | 表单提交字段名(输出隐藏输入,多选以逗号连接) |
|
||||
| `form` | `string` | - | 关联的表单 id |
|
||||
| `full-width` | `boolean` | `false` | 是否占满容器宽度 |
|
||||
| `variant` | `'primary' \| 'secondary'` | `'primary'` | 视觉变体 |
|
||||
| `as` | `string` | `'div'` | 自定义根元素标签 |
|
||||
| `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 |
|
||||
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
|
||||
|
||||
事件:
|
||||
|
||||
| 事件 | 载荷 | 描述 |
|
||||
| ------------------- | ----------------------------------- | ------------ |
|
||||
| `update:modelValue` | `string \| number \| Array \| null` | 值变化 |
|
||||
| `change` | 同上 | 值变化 |
|
||||
| `update:open` | `boolean` | 弹层开关变化 |
|
||||
| `openChange` | `boolean` | 弹层开关变化 |
|
||||
| `clear` | - | 清除已选值 |
|
||||
|
||||
### AutocompleteTrigger
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| ------------- | --------------------------- | ------- | -------------------------------------------------------- |
|
||||
| `is-disabled` | `boolean` | `false` | 是否禁用触发器 |
|
||||
| 默认插槽 | `Component` | - | 通常为 `AutocompleteValue` + `ClearButton` + `Indicator` |
|
||||
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
|
||||
|
||||
触发器渲染为 `role="button"` 的可点击容器,是组件唯一的 Tab 入口(`tabindex="0"`;禁用时 `-1`),`Enter` / `Space` / `ArrowDown` 打开,`Escape` 关闭,`Delete` / `Backspace` 清除。
|
||||
|
||||
### AutocompleteValue
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| -------- | ----------------------------------------------------------------- | ------ | ----------------------------- |
|
||||
| 默认插槽 | `{ isPlaceholder, defaultChildren, selectedText, selectedItems }` | - | 自定义展示值 |
|
||||
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
|
||||
|
||||
### AutocompleteIndicator
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| -------- | --------------------------- | ------ | -------------------------------- |
|
||||
| 默认插槽 | `Component` | - | 自定义指示器图形(默认为下箭头) |
|
||||
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
|
||||
|
||||
指示器是装饰元素(`aria-hidden`),激活由触发器负责。
|
||||
|
||||
### AutocompleteClearButton
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| -------- | --------------------------- | ------ | ----------------------------- |
|
||||
| 默认插槽 | `Component` | - | 自定义清除图标 |
|
||||
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
|
||||
|
||||
`aria-label` 默认 `Clear selection`,`tabindex="-1"`,无选择时 `data-empty="true"` 并隐藏。
|
||||
|
||||
### AutocompletePopover
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| ------------------- | --------------------------- | ---------- | ----------------------------- |
|
||||
| `placement` | 位置联合类型 | `'bottom'` | 相对触发器的位置 |
|
||||
| `offset` | `number` | `8` | 偏移量 |
|
||||
| `should-flip` | `boolean` | `true` | 空间不足时是否翻转 |
|
||||
| `container-padding` | `number` | `12` | 距离视口边缘的最小间距 |
|
||||
| `to` | `string \| HTMLElement` | - | 自定义 Portal 容器 |
|
||||
| 默认插槽 | `Component` | - | 通常为 `AutocompleteFilter` |
|
||||
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
|
||||
|
||||
宽度跟随触发器(`--trigger-width`)。
|
||||
|
||||
### AutocompleteFilter
|
||||
|
||||
| Prop | 类型 | 默认值 | 描述 |
|
||||
| --------------------- | ------------------------------- | ---------------------- | ------------------------------------------------------------- |
|
||||
| `filter` | `(text, inputValue) => boolean` | 不区分大小写的包含匹配 | 自定义过滤函数 |
|
||||
| `input-value` | `string` | - | 受控搜索文本 |
|
||||
| `default-input-value` | `string` | `''` | 非受控初始搜索文本 |
|
||||
| 默认插槽 | `Component` | - | 必须包含 `SearchField`(内含 `SearchFieldInput`)与 `ListBox` |
|
||||
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
|
||||
|
||||
过滤文本由 `AutocompleteFilter` 拥有,并通过集合的过滤协议影响列表的显示与键盘导航;它不会清除已接受的选择。
|
||||
|
||||
受控文本用 `:input-value` + `@input-change`(或 `v-model:input-value`):
|
||||
|
||||
| 事件 | 载荷 | 描述 |
|
||||
| ------------------- | -------- | ------------ |
|
||||
| `update:inputValue` | `string` | 搜索文本变化 |
|
||||
| `inputChange` | `string` | 搜索文本变化 |
|
||||
|
||||
### 作用域插槽与渲染信息
|
||||
|
||||
`AutocompleteValue` 的默认插槽提供:
|
||||
|
||||
| 字段 | 类型 | 描述 |
|
||||
| ----------------- | --------------------------- | -------------------------------------------- |
|
||||
| `isPlaceholder` | `boolean` | 是否没有选中项 |
|
||||
| `defaultChildren` | `string` | 缺省文本(选中项文本以逗号连接,否则占位符) |
|
||||
| `selectedText` | `string` | 选中项 `textValue` 的连接文本 |
|
||||
| `selectedItems` | `Array<{ key, textValue }>` | 选中项 |
|
||||
|
||||
上游 `state.selectedItems`(节点)在本库中是上表的 `selectedItems`(数据);不复制 item 子树,见「多选」说明。
|
||||
|
||||
## 无障碍
|
||||
|
||||
Autocomplete 实现带过滤的 ARIA select 模式:
|
||||
|
||||
- 触发器是唯一 Tab 入口,并带 `aria-haspopup="listbox"` / `aria-expanded` / `aria-controls`
|
||||
- 打开后焦点进入弹层内搜索框(`role="combobox"`),`aria-activedescendant` 指向已挂载且可见的活动选项
|
||||
- `ArrowDown` / `ArrowUp` / `Home` / `End` 在过滤后的可见集合中移动,`Enter` 确认,`Escape` 关闭,`Tab` 离开
|
||||
- 中文输入法组合期间不确认选择(`isComposing` / `keyCode 229` 时忽略键盘提交)
|
||||
- 过滤不会清除已接受的选择;关闭后焦点回到触发器,弹层内不出现第二个 Tab 入口
|
||||
|
||||
## 相关组件
|
||||
|
||||
[ComboBox 组合框](./combo-box) · [Select 选择器](./select) · [ListBox 列表框](./list-box) · [SearchField 搜索框](./search-field)
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
allows-empty-collection
|
||||
class="w-[256px]"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,153 @@
|
||||
<!-- 适配:源示例请求 SWAPI,这里用本地异步源演示相同状态(取消旧请求、加载中、空状态)。 -->
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Spinner,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
type Character = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
const SEARCH_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 query = ref("");
|
||||
const results = ref<Character[]>([]);
|
||||
const loading = ref(false);
|
||||
let controller: AbortController | undefined;
|
||||
|
||||
function match(text: string) {
|
||||
const search = text.trim().toLocaleLowerCase();
|
||||
|
||||
return characters.filter(
|
||||
(character) =>
|
||||
!search || character.name.toLocaleLowerCase().includes(search),
|
||||
);
|
||||
}
|
||||
|
||||
function runSearch(text: string) {
|
||||
// 每次查询一个 AbortController:新输入会取消上一个请求,迟到的结果不再写回。
|
||||
controller?.abort();
|
||||
const current = new AbortController();
|
||||
|
||||
controller = current;
|
||||
loading.value = true;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
if (current.signal.aborted) return;
|
||||
|
||||
results.value = match(text);
|
||||
if (controller === current) loading.value = false;
|
||||
}, SEARCH_DELAY);
|
||||
|
||||
current.signal.addEventListener("abort", () => clearTimeout(timer), {
|
||||
once: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 受控文本:AutocompleteFilter 通过 input-value / input-change 暴露搜索文本。
|
||||
function setQuery(value: string) {
|
||||
query.value = value;
|
||||
runSearch(value);
|
||||
}
|
||||
|
||||
onMounted(() => runSearch(""));
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
controller?.abort();
|
||||
controller = undefined;
|
||||
});
|
||||
|
||||
// 结果集已由异步源过滤,集合不再按输入文本二次过滤。
|
||||
const keepResults = () => true;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
allows-empty-collection
|
||||
class="w-[256px]"
|
||||
placeholder="搜索…"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>搜索《星球大战》角色</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter
|
||||
:filter="keepResults"
|
||||
:input-value="query"
|
||||
@input-change="setQuery"
|
||||
>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索角色"
|
||||
class="sticky top-0 z-10"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索角色…" />
|
||||
<Spinner
|
||||
size="sm"
|
||||
:class="[
|
||||
'absolute end-2 top-1/2 -translate-y-1/2',
|
||||
{ 'pointer-events-none opacity-0': !loading },
|
||||
]"
|
||||
/>
|
||||
<SearchFieldClearButton
|
||||
:class="{ 'pointer-events-none opacity-0': loading }"
|
||||
/>
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox :items="results" class="max-h-[420px] overflow-y-auto">
|
||||
<template #default="{ item }">
|
||||
<ListBoxItem :id="item.id" :text-value="item.name">
|
||||
{{ item.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</template>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,78 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
type TagKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const items = [
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "illinois", name: "Illinois" },
|
||||
{ id: "pennsylvania", name: "Pennsylvania" },
|
||||
];
|
||||
|
||||
const selected = ref<TagKey[]>(["california", "texas"]);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<Autocomplete
|
||||
v-model="selected"
|
||||
class="w-[256px]"
|
||||
placeholder="选择州"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
<p class="text-sm text-muted">
|
||||
已选:{{ selected.length > 0 ? selected.join(", ") : "无" }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,82 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Button,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const items = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const isOpen = ref(false);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<Autocomplete
|
||||
:is-open="isOpen"
|
||||
class="w-[256px]"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
@open-change="isOpen = $event"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
<Button @click="isOpen = !isOpen">
|
||||
{{ isOpen ? "关闭" : "打开" }} 自动完成
|
||||
</Button>
|
||||
<p class="text-sm text-muted">
|
||||
自动完成处于{{ isOpen ? "打开" : "关闭" }}状态
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,79 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const states = [
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "illinois", name: "Illinois" },
|
||||
{ id: "pennsylvania", name: "Pennsylvania" },
|
||||
];
|
||||
|
||||
const state = ref<string | null>("california");
|
||||
|
||||
const selectedState = computed(() =>
|
||||
states.find((item) => item.id === state.value),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<Autocomplete
|
||||
v-model="state"
|
||||
class="w-[256px]"
|
||||
placeholder="选择一个州"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>州(受控)</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="item in states"
|
||||
:id="item.id"
|
||||
:key="item.id"
|
||||
:text-value="item.name"
|
||||
>
|
||||
{{ item.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
<p class="text-sm text-muted">已选:{{ selectedState?.name || "无" }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,75 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
import { IconSelector } from "@tabler/icons-vue";
|
||||
|
||||
const items = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
class="w-[256px]"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator>
|
||||
<IconSelector class="size-3" aria-hidden="true" />
|
||||
</AutocompleteIndicator>
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,126 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
type TagKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const teammates = [
|
||||
{ id: "sarah", name: "Sarah Chen", role: "产品设计" },
|
||||
{ id: "marcus", name: "Marcus Lee", role: "工程" },
|
||||
{ id: "priya", name: "Priya Patel", role: "数据科学" },
|
||||
{ id: "jordan", name: "Jordan Kim", role: "客户成功" },
|
||||
{ id: "alex", name: "Alex Rivera", role: "市场营销" },
|
||||
];
|
||||
|
||||
const selectedKeys = ref<TagKey[]>([]);
|
||||
|
||||
const teammateOf = (key: unknown) =>
|
||||
teammates.find((teammate) => teammate.id === key);
|
||||
|
||||
function onRemoveTags(keys: TagKey[]) {
|
||||
selectedKeys.value = selectedKeys.value.filter((key) => !keys.includes(key));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-full max-w-sm pt-6">
|
||||
<Autocomplete
|
||||
v-model="selectedKeys"
|
||||
class="w-full gap-1.5"
|
||||
placeholder="搜索团队成员..."
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label class="font-medium text-foreground">负责人</Label>
|
||||
<Description>任务更新时将通知以下人员。</Description>
|
||||
<AutocompleteTrigger
|
||||
class="rounded-xl border border-border/80 bg-surface shadow-sm ring-1 ring-accent/5 transition-[box-shadow,border-color] focus-within:border-accent/25 focus-within:ring-2 focus-within:ring-accent/15 dark:border-border/90 dark:bg-surface dark:ring-accent/10 dark:focus-within:border-accent/35"
|
||||
>
|
||||
<AutocompleteValue>
|
||||
<template
|
||||
#default="{ defaultChildren, isPlaceholder, selectedItems }"
|
||||
>
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup v-else size="sm" @remove="onRemoveTags">
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="teammateOf(item.key)?.name"
|
||||
class="border border-accent/15 bg-accent/8 text-foreground dark:border-accent/25 dark:bg-accent/12"
|
||||
>
|
||||
{{ teammateOf(item.key)?.name }}
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover
|
||||
class="overflow-hidden rounded-xl border border-border/80 bg-surface shadow-xl ring-1 ring-black/3 dark:border-border/90 dark:bg-surface dark:ring-white/5"
|
||||
>
|
||||
<AutocompleteFilter>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="按姓名或角色搜索"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup
|
||||
class="border-b border-separator bg-surface-secondary/50"
|
||||
>
|
||||
<SearchFieldSearchIcon class="text-muted" />
|
||||
<SearchFieldInput placeholder="按姓名或角色搜索..." />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox class="p-1.5">
|
||||
<ListBoxItem
|
||||
v-for="teammate in teammates"
|
||||
:id="teammate.id"
|
||||
:key="teammate.id"
|
||||
:text-value="`${teammate.name} ${teammate.role}`"
|
||||
class="rounded-lg data-[focused=true]:bg-accent/10 data-[selected=true]:bg-accent/5 dark:data-[focused=true]:bg-accent/15 dark:data-[selected=true]:bg-accent/8"
|
||||
>
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-sm font-medium text-foreground">
|
||||
{{ teammate.name }}
|
||||
</span>
|
||||
<span class="text-xs text-muted">{{ teammate.role }}</span>
|
||||
</div>
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到团队成员</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const currencies = [
|
||||
{ code: "USD", id: "usd", name: "美元", symbol: "$" },
|
||||
{ code: "EUR", id: "eur", name: "欧元", symbol: "€" },
|
||||
{ code: "GBP", id: "gbp", name: "英镑", symbol: "£" },
|
||||
{ code: "JPY", id: "jpy", name: "日元", symbol: "¥" },
|
||||
{ code: "CHF", id: "chf", name: "瑞士法郎", symbol: "₣" },
|
||||
];
|
||||
|
||||
const currencyOf = (key: unknown) =>
|
||||
currencies.find((currency) => currency.id === key);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
class="w-[256px]"
|
||||
default-value="usd"
|
||||
placeholder="选择货币"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>货币</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template #default="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<span
|
||||
v-if="isPlaceholder || !currencyOf(selectedItems[0]?.key)"
|
||||
class="flex min-w-0 items-center gap-1.5"
|
||||
>
|
||||
{{ defaultChildren }}
|
||||
</span>
|
||||
<span v-else class="flex min-w-0 items-center gap-1.5">
|
||||
<span class="font-medium">
|
||||
{{ currencyOf(selectedItems[0]?.key)?.symbol }}
|
||||
</span>
|
||||
<span>{{ currencyOf(selectedItems[0]?.key)?.code }}</span>
|
||||
<span class="truncate text-muted">
|
||||
{{ currencyOf(selectedItems[0]?.key)?.name }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索货币"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索货币…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="currency in currencies"
|
||||
:id="currency.id"
|
||||
:key="currency.id"
|
||||
:text-value="`${currency.code} ${currency.name}`"
|
||||
>
|
||||
<div class="flex flex-col">
|
||||
<Label>{{ currency.code }}</Label>
|
||||
<Description>{{ currency.name }}</Description>
|
||||
</div>
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,97 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
type TagKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const states = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const selectedKeys = ref<TagKey[]>([]);
|
||||
|
||||
function onRemoveTags(keys: TagKey[]) {
|
||||
selectedKeys.value = selectedKeys.value.filter((key) => !keys.includes(key));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKeys"
|
||||
class="w-[256px]"
|
||||
placeholder="选择州/省"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>计划前往的州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template #default="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup v-else size="sm" @remove="onRemoveTags">
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="item.textValue"
|
||||
>
|
||||
{{ item.textValue }}
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索选项">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="state in states"
|
||||
:id="state.id"
|
||||
:key="state.id"
|
||||
:text-value="state.name"
|
||||
>
|
||||
{{ state.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,119 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const items = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const countries = [
|
||||
{ id: "argentina", name: "Argentina" },
|
||||
{ id: "venezuela", name: "Venezuela" },
|
||||
{ id: "japan", name: "Japan" },
|
||||
{ id: "france", name: "France" },
|
||||
{ id: "italy", name: "Italy" },
|
||||
{ id: "spain", name: "Spain" },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Autocomplete
|
||||
is-disabled
|
||||
class="w-[256px]"
|
||||
default-value="california"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
<Autocomplete
|
||||
is-disabled
|
||||
class="w-[256px]"
|
||||
:default-value="['argentina', 'japan', 'france']"
|
||||
placeholder="选择国家"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>计划前往的国家</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索国家">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索国家…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="country in countries"
|
||||
:id="country.id"
|
||||
:key="country.id"
|
||||
:text-value="country.name"
|
||||
>
|
||||
{{ country.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,116 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
type TagKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const emails = [
|
||||
{
|
||||
email: "alice@example.com",
|
||||
id: "alice@example.com",
|
||||
name: "Alice Johnson",
|
||||
},
|
||||
{ email: "bob@example.com", id: "bob@example.com", name: "Bob Smith" },
|
||||
{
|
||||
email: "charlie@example.com",
|
||||
id: "charlie@example.com",
|
||||
name: "Charlie Brown",
|
||||
},
|
||||
{ email: "diana@example.com", id: "diana@example.com", name: "Diana Prince" },
|
||||
{ email: "eve@example.com", id: "eve@example.com", name: "Eve Wilson" },
|
||||
];
|
||||
|
||||
const selectedKeys = ref<TagKey[]>([]);
|
||||
|
||||
function onRemoveTags(keys: TagKey[]) {
|
||||
selectedKeys.value = selectedKeys.value.filter((key) => !keys.includes(key));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKeys"
|
||||
class="w-[256px]"
|
||||
placeholder="添加收件人"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>收件人</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template #default="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup v-else size="sm" @remove="onRemoveTags">
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="item.textValue"
|
||||
>
|
||||
{{ item.textValue }}
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索邮箱"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索邮箱…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="entry in emails"
|
||||
:id="entry.id"
|
||||
:key="entry.id"
|
||||
:text-value="entry.email"
|
||||
>
|
||||
<div class="flex flex-col">
|
||||
<Label>{{ entry.name }}</Label>
|
||||
<Description>{{ entry.email }}</Description>
|
||||
</div>
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到收件人</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,76 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Surface,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const items = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Surface class="w-[380px] space-y-4 rounded-3xl p-6">
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
full-width
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
variant="secondary"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</Surface>
|
||||
</template>
|
||||
@@ -0,0 +1,114 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
type City = {
|
||||
name: string;
|
||||
country: string;
|
||||
};
|
||||
|
||||
const allCities: City[] = [
|
||||
{ country: "美国", name: "纽约" },
|
||||
{ country: "美国", name: "洛杉矶" },
|
||||
{ country: "美国", name: "芝加哥" },
|
||||
{ country: "英国", name: "伦敦" },
|
||||
{ country: "法国", name: "巴黎" },
|
||||
{ country: "日本", name: "东京" },
|
||||
{ country: "澳大利亚", name: "悉尼" },
|
||||
{ country: "加拿大", name: "多伦多" },
|
||||
{ country: "德国", name: "柏林" },
|
||||
{ country: "西班牙", name: "马德里" },
|
||||
];
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
const loading = ref(false);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const contains = (text: string, input: string) =>
|
||||
text.toLocaleLowerCase().includes(input.toLocaleLowerCase());
|
||||
|
||||
// 源示例在过滤回调里模拟异步搜索:先标记加载中,300ms 后结束。
|
||||
function customFilter(text: string, input: string) {
|
||||
if (!input) return true;
|
||||
|
||||
loading.value = true;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
loading.value = false;
|
||||
}, 300);
|
||||
|
||||
return contains(text, input);
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => clearTimeout(timer));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
class="w-[256px]"
|
||||
placeholder="搜索城市"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>城市</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter :filter="customFilter">
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索城市"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索城市…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="city in allCities"
|
||||
:id="city.name"
|
||||
:key="city.name"
|
||||
:text-value="`${city.name} ${city.country}`"
|
||||
>
|
||||
<div class="flex flex-col">
|
||||
<Label>{{ city.name }}</Label>
|
||||
<Description>{{ city.country }}</Description>
|
||||
</div>
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">
|
||||
{{ loading ? "搜索中…" : "未找到城市" }}
|
||||
</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
type TagKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const states = [
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "illinois", name: "Illinois" },
|
||||
{ id: "pennsylvania", name: "Pennsylvania" },
|
||||
];
|
||||
|
||||
const selectedKeys = ref<TagKey[]>([]);
|
||||
|
||||
function onRemoveTags(keys: TagKey[]) {
|
||||
selectedKeys.value = selectedKeys.value.filter((key) => !keys.includes(key));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKeys"
|
||||
class="w-[256px]"
|
||||
placeholder="选择州/省"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template #default="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup v-else size="sm" @remove="onRemoveTags">
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="item.textValue"
|
||||
>
|
||||
{{ item.textValue }}
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索选项">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="state in states"
|
||||
:id="state.id"
|
||||
:key="state.id"
|
||||
:text-value="state.name"
|
||||
>
|
||||
{{ state.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,83 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Surface,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const items = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Surface class="w-[320px] rounded-3xl p-6">
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
class="w-full"
|
||||
placeholder="选择一个"
|
||||
selection-mode="single"
|
||||
variant="secondary"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索州名"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</Surface>
|
||||
</template>
|
||||
@@ -0,0 +1,137 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Button,
|
||||
EmptyState,
|
||||
FieldError,
|
||||
Form,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const states = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const countries = [
|
||||
{ id: "usa", name: "United States" },
|
||||
{ id: "canada", name: "Canada" },
|
||||
{ id: "mexico", name: "Mexico" },
|
||||
{ id: "uk", name: "United Kingdom" },
|
||||
{ id: "france", name: "France" },
|
||||
{ id: "germany", name: "Germany" },
|
||||
];
|
||||
|
||||
const message = ref<string | null>(null);
|
||||
|
||||
function onSubmit(event: Event) {
|
||||
event.preventDefault();
|
||||
const formData = new FormData(event.currentTarget as HTMLFormElement);
|
||||
message.value = `表单提交成功!州:${formData.get("state")},国家:${formData.get("country")}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Form class="flex w-[256px] flex-col gap-4" @submit="onSubmit">
|
||||
<Autocomplete
|
||||
is-required
|
||||
class="w-full"
|
||||
name="state"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="state in states"
|
||||
:id="state.id"
|
||||
:key="state.id"
|
||||
:text-value="state.name"
|
||||
>
|
||||
{{ state.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
<FieldError />
|
||||
</Autocomplete>
|
||||
<Autocomplete
|
||||
is-required
|
||||
class="w-full"
|
||||
name="country"
|
||||
placeholder="选择一个国家"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>国家</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索国家">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索国家…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="country in countries"
|
||||
:id="country.id"
|
||||
:key="country.id"
|
||||
:text-value="country.name"
|
||||
>
|
||||
{{ country.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
<FieldError />
|
||||
</Autocomplete>
|
||||
<Button type="submit">提交</Button>
|
||||
<p v-if="message" role="status" class="text-sm text-success">
|
||||
{{ message }}
|
||||
</p>
|
||||
</Form>
|
||||
</template>
|
||||
@@ -0,0 +1,107 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
type TagKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const tags = [
|
||||
{ id: "react", name: "React" },
|
||||
{ id: "typescript", name: "TypeScript" },
|
||||
{ id: "javascript", name: "JavaScript" },
|
||||
{ id: "nodejs", name: "Node.js" },
|
||||
{ id: "python", name: "Python" },
|
||||
{ id: "vue", name: "Vue" },
|
||||
{ id: "angular", name: "Angular" },
|
||||
{ id: "nextjs", name: "Next.js" },
|
||||
];
|
||||
|
||||
const selectedKeys = ref<TagKey[]>([]);
|
||||
|
||||
function onRemoveTags(keys: TagKey[]) {
|
||||
selectedKeys.value = selectedKeys.value.filter((key) => !keys.includes(key));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKeys"
|
||||
class="w-[256px]"
|
||||
placeholder="选择标签"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>标签</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template #default="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup v-else size="sm" @remove="onRemoveTags">
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="item.textValue"
|
||||
>
|
||||
{{ item.textValue }}
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索标签"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索标签…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="tag in tags"
|
||||
:id="tag.id"
|
||||
:key="tag.id"
|
||||
:text-value="tag.name"
|
||||
>
|
||||
{{ tag.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到标签</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,158 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
AvatarImage,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
type TagKey,
|
||||
} 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",
|
||||
},
|
||||
];
|
||||
|
||||
const selectedKeys = ref<TagKey[]>(["1", "2"]);
|
||||
|
||||
const userOf = (key: unknown) => users.find((user) => user.id === key);
|
||||
|
||||
function onRemoveTags(keys: TagKey[]) {
|
||||
selectedKeys.value = selectedKeys.value.filter((key) => !keys.includes(key));
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKeys"
|
||||
class="w-[256px]"
|
||||
placeholder="选择队友"
|
||||
selection-mode="multiple"
|
||||
>
|
||||
<Label>用户</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template #default="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup v-else size="sm" @remove="onRemoveTags">
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="item.textValue"
|
||||
>
|
||||
<Avatar class="size-4" size="sm">
|
||||
<AvatarImage :src="userOf(item.key)?.avatarUrl ?? ''" />
|
||||
<AvatarFallback>
|
||||
{{ userOf(item.key)?.fallback }}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{{ item.textValue }}</span>
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索用户"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索用户…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<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>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,146 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Avatar,
|
||||
AvatarFallback,
|
||||
AvatarImage,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} 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",
|
||||
},
|
||||
];
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
|
||||
const userOf = (key: unknown) => users.find((user) => user.id === key);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
class="w-[256px]"
|
||||
placeholder="选择用户"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>用户</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template #default="{ defaultChildren, isPlaceholder, selectedItems }">
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<template v-else-if="selectedItems.length > 1">
|
||||
已选择 {{ selectedItems.length }} 位用户
|
||||
</template>
|
||||
<div v-else class="flex items-center gap-2">
|
||||
<Avatar class="size-4" size="sm">
|
||||
<AvatarImage
|
||||
:src="userOf(selectedItems[0]?.key)?.avatarUrl ?? ''"
|
||||
/>
|
||||
<AvatarFallback>
|
||||
{{ userOf(selectedItems[0]?.key)?.fallback }}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<span>{{ userOf(selectedItems[0]?.key)?.name }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索用户"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索用户…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<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>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,261 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Tag,
|
||||
TagGroup,
|
||||
TagGroupList,
|
||||
type TagKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const items = [
|
||||
{ id: "option1", name: "选项 1" },
|
||||
{ id: "option2", name: "选项 2" },
|
||||
{ id: "option3", name: "选项 3" },
|
||||
{ id: "option4", name: "选项 4" },
|
||||
];
|
||||
|
||||
const selectedKey1 = ref<string | null>(null);
|
||||
const selectedKey2 = ref<string | null>(null);
|
||||
const selectedKeys1 = ref<TagKey[]>([]);
|
||||
const selectedKeys2 = ref<TagKey[]>([]);
|
||||
|
||||
function onRemoveTags1(keys: TagKey[]) {
|
||||
selectedKeys1.value = selectedKeys1.value.filter(
|
||||
(key) => !keys.includes(key),
|
||||
);
|
||||
}
|
||||
|
||||
function onRemoveTags2(keys: TagKey[]) {
|
||||
selectedKeys2.value = selectedKeys2.value.filter(
|
||||
(key) => !keys.includes(key),
|
||||
);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-8">
|
||||
<div class="flex flex-col gap-4">
|
||||
<h3 class="text-lg font-semibold">单选变体</h3>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Autocomplete
|
||||
v-model="selectedKey1"
|
||||
class="w-[256px]"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
variant="primary"
|
||||
>
|
||||
<Label>主色(primary)变体</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索选项">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
<Autocomplete
|
||||
v-model="selectedKey2"
|
||||
class="w-[256px]"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
variant="secondary"
|
||||
>
|
||||
<Label>次色(secondary)变体</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索选项">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-4">
|
||||
<h3 class="text-lg font-semibold">多选变体</h3>
|
||||
<div class="flex flex-col gap-4">
|
||||
<Autocomplete
|
||||
v-model="selectedKeys1"
|
||||
class="w-[256px]"
|
||||
placeholder="选择多项"
|
||||
selection-mode="multiple"
|
||||
variant="primary"
|
||||
>
|
||||
<Label>主色(primary)变体</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template
|
||||
#default="{ defaultChildren, isPlaceholder, selectedItems }"
|
||||
>
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup v-else size="sm" @remove="onRemoveTags1">
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="item.textValue"
|
||||
>
|
||||
{{ item.textValue }}
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索选项">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
<Autocomplete
|
||||
v-model="selectedKeys2"
|
||||
class="w-[256px]"
|
||||
placeholder="选择多项"
|
||||
selection-mode="multiple"
|
||||
variant="secondary"
|
||||
>
|
||||
<Label>次色(secondary)变体</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue>
|
||||
<template
|
||||
#default="{ defaultChildren, isPlaceholder, selectedItems }"
|
||||
>
|
||||
<template v-if="isPlaceholder || selectedItems.length === 0">
|
||||
{{ defaultChildren }}
|
||||
</template>
|
||||
<TagGroup
|
||||
v-else
|
||||
size="sm"
|
||||
variant="surface"
|
||||
@remove="onRemoveTags2"
|
||||
>
|
||||
<TagGroupList>
|
||||
<Tag
|
||||
v-for="item in selectedItems"
|
||||
:id="item.key"
|
||||
:key="item.key"
|
||||
:text-value="item.textValue"
|
||||
>
|
||||
{{ item.textValue }}
|
||||
</Tag>
|
||||
</TagGroupList>
|
||||
</TagGroup>
|
||||
</template>
|
||||
</AutocompleteValue>
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索选项">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,175 @@
|
||||
<!-- 适配:源示例用 Virtualizer + ListLayout 包裹 ListBox,本库 ListBox 直接提供 items + virtualized + row-height 虚拟滚动。 -->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldClearButton,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
type ListBoxKey,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
type User = {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
};
|
||||
|
||||
const firstNames = [
|
||||
"Emma",
|
||||
"Liam",
|
||||
"Olivia",
|
||||
"Noah",
|
||||
"Ava",
|
||||
"James",
|
||||
"Sophia",
|
||||
"Oliver",
|
||||
"Isabella",
|
||||
"Lucas",
|
||||
"Mia",
|
||||
"Ethan",
|
||||
"Charlotte",
|
||||
"Mason",
|
||||
"Amelia",
|
||||
"Logan",
|
||||
"Harper",
|
||||
"Alexander",
|
||||
"Ella",
|
||||
"Benjamin",
|
||||
];
|
||||
|
||||
const lastNames = [
|
||||
"Smith",
|
||||
"Johnson",
|
||||
"Williams",
|
||||
"Brown",
|
||||
"Jones",
|
||||
"Garcia",
|
||||
"Miller",
|
||||
"Davis",
|
||||
"Rodriguez",
|
||||
"Martinez",
|
||||
"Anderson",
|
||||
"Taylor",
|
||||
"Thomas",
|
||||
"Jackson",
|
||||
"White",
|
||||
"Harris",
|
||||
"Clark",
|
||||
"Lewis",
|
||||
"Robinson",
|
||||
"Walker",
|
||||
];
|
||||
|
||||
function generateUsers(count: number): User[] {
|
||||
const users: User[] = [];
|
||||
|
||||
for (let index = 0; index < count; index++) {
|
||||
const first = firstNames[index % firstNames.length]!;
|
||||
const last =
|
||||
lastNames[Math.floor(index / firstNames.length) % lastNames.length]!;
|
||||
|
||||
users.push({
|
||||
id: index + 1,
|
||||
name: `${first} ${last}`,
|
||||
email: `${first.toLowerCase()}.${last.toLowerCase()}@acme.com`,
|
||||
});
|
||||
}
|
||||
|
||||
return users;
|
||||
}
|
||||
|
||||
const allUsers = generateUsers(1000);
|
||||
const selectedKey = ref<ListBoxKey | null>(null);
|
||||
const searchQuery = ref("");
|
||||
|
||||
const filteredUsers = computed(() => {
|
||||
const query = searchQuery.value.trim().toLocaleLowerCase();
|
||||
|
||||
if (!query) return allUsers;
|
||||
|
||||
return allUsers.filter(
|
||||
(user) =>
|
||||
user.name.toLocaleLowerCase().includes(query) ||
|
||||
user.email.toLocaleLowerCase().includes(query),
|
||||
);
|
||||
});
|
||||
|
||||
function setSearchQuery(value: string) {
|
||||
searchQuery.value = value;
|
||||
}
|
||||
|
||||
// 过滤已在上面的 computed 中完成(姓名或邮箱),集合不再叠加文本过滤。
|
||||
const keepResults = () => true;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
allows-empty-collection
|
||||
class="w-[300px]"
|
||||
placeholder="选择用户"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>用户</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter
|
||||
:filter="keepResults"
|
||||
:input-value="searchQuery"
|
||||
@input-change="setSearchQuery"
|
||||
>
|
||||
<SearchField
|
||||
auto-focus
|
||||
aria-label="搜索用户"
|
||||
class="sticky top-0 z-10"
|
||||
name="search"
|
||||
variant="secondary"
|
||||
>
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索用户…" />
|
||||
<SearchFieldClearButton />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox
|
||||
:items="filteredUsers"
|
||||
class="max-h-[320px] overflow-y-auto"
|
||||
:row-height="50"
|
||||
virtualized
|
||||
>
|
||||
<template #default="{ item }">
|
||||
<ListBoxItem :id="item.id" :text-value="item.name" class="h-full">
|
||||
<div class="flex flex-col">
|
||||
<Label>{{ item.name }}</Label>
|
||||
<Description>{{ item.email }}</Description>
|
||||
</div>
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
</template>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,74 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Description,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const items = [
|
||||
{ id: "florida", name: "Florida" },
|
||||
{ id: "delaware", name: "Delaware" },
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "new-york", name: "New York" },
|
||||
{ id: "washington", name: "Washington" },
|
||||
];
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
class="w-[256px]"
|
||||
placeholder="请选择一项"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>州</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索州名">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索州名…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<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">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
<Description>请选择你的居住州</Description>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const animals = [
|
||||
{ id: "dog", name: "狗" },
|
||||
{ id: "cat", name: "猫" },
|
||||
{ id: "bird", name: "鸟" },
|
||||
{ id: "kangaroo", name: "袋鼠" },
|
||||
{ id: "elephant", name: "象" },
|
||||
{ id: "tiger", name: "老虎" },
|
||||
];
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
class="w-[256px]"
|
||||
:disabled-keys="['cat', 'kangaroo']"
|
||||
placeholder="选择一种动物"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>动物</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索动物">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索动物…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<ListBox>
|
||||
<ListBoxItem
|
||||
v-for="animal in animals"
|
||||
:id="animal.id"
|
||||
:key="animal.id"
|
||||
:text-value="animal.name"
|
||||
>
|
||||
{{ animal.name }}
|
||||
<ListBoxItemIndicator />
|
||||
</ListBoxItem>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -0,0 +1,116 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
EmptyState,
|
||||
Header,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
ListBoxItemIndicator,
|
||||
ListBoxSection,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
Separator,
|
||||
} from "@heroui-vue/components";
|
||||
|
||||
const selectedKey = ref<string | null>(null);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Autocomplete
|
||||
v-model="selectedKey"
|
||||
class="w-[256px]"
|
||||
placeholder="选择一个国家"
|
||||
selection-mode="single"
|
||||
>
|
||||
<Label>国家</Label>
|
||||
<AutocompleteTrigger>
|
||||
<AutocompleteValue />
|
||||
<AutocompleteClearButton />
|
||||
<AutocompleteIndicator />
|
||||
</AutocompleteTrigger>
|
||||
<AutocompletePopover>
|
||||
<AutocompleteFilter>
|
||||
<SearchField aria-label="搜索国家">
|
||||
<SearchFieldGroup>
|
||||
<SearchFieldSearchIcon />
|
||||
<SearchFieldInput placeholder="搜索国家…" />
|
||||
</SearchFieldGroup>
|
||||
</SearchField>
|
||||
<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>
|
||||
<template #empty>
|
||||
<EmptyState class="p-1">未找到结果</EmptyState>
|
||||
</template>
|
||||
</ListBox>
|
||||
</AutocompleteFilter>
|
||||
</AutocompletePopover>
|
||||
</Autocomplete>
|
||||
</template>
|
||||
@@ -6,7 +6,7 @@
|
||||
| -------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| accordion | 验证中(M23) | Accordion/Item/Heading/Trigger/Panel/Body/Indicator;10/10 基线例;surface/hideSeparator;复用组键协议 |
|
||||
| alert-dialog | 验证中(M33) | 11 部件;role=alertdialog;默认不误关;14/14 基线例;Reka Dialog 底座 |
|
||||
| autocomplete | 计划 | 待实施时核验子部件、属性、事件、键盘行为与替代底座 |
|
||||
| autocomplete | 已迁移(有已知差异) | Autocomplete 七部件;24/24 基线例;触发器单一 Tab 入口 + 弹层内搜索框虚拟焦点、受控开关/文本、多选 Value 用作用域插槽;见 B02 报告 |
|
||||
| avatar | 验证中(最小实现) | Reka Avatar 加载/回退;size/color/variant;Image asChild;AvatarGroup 继承仅限直接子级 |
|
||||
| avatar-group | 验证中(最小实现) | max 截断与自动计数、显式 Count 不受截断、isGrid、overlap clip/ring;默认无 role=group |
|
||||
| badge | 验证中(最小实现) | Badge/BadgeAnchor/BadgeLabel;四角定位、圆点、文本/数字自动包装;Anchor 非链接 |
|
||||
|
||||
@@ -298,3 +298,55 @@ export interface CollectionOwner extends CollectionView {
|
||||
- 弹层内浮层选项的真实鼠标点击:本 IAB 会话对 floating 定位的 option 报 `not actionable`,改用键盘在页面验证,指针保焦点行为由 B02a 的 harness 与单测覆盖(记录为环境限制,未写成已通过)。
|
||||
- 真实系统 IME、读屏软件、逐像素视觉对比。
|
||||
- 独立 tarball 产物消费(B02d)。
|
||||
|
||||
## 12. B02c:Autocomplete 全部部件、文档与示例(已实现)
|
||||
|
||||
### 12.1 部件与映射
|
||||
|
||||
| 部件 | 实现要点 |
|
||||
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `Autocomplete` | 字段上下文(`kind: "group"`,`Label` 关联到触发器)、值/开关模型、集合 owner(`filter`/`virtualFocus`/`activeKey`/`keyboardIntent`/`isOpen`)、隐藏表单输入 + 原生校验代理、关闭后焦点回到触发器 |
|
||||
| `AutocompleteTrigger` | `role="button"` 的可点击容器,是唯一 Tab 入口;`aria-haspopup`/`-expanded`/`-controls`、`Enter`/`Space`/`ArrowDown` 打开、`Escape` 关闭、`Delete`/`Backspace` 清除;同时注册为弹层 anchor |
|
||||
| `AutocompleteValue` | 值/占位符文本,作用域插槽 `{ isPlaceholder, defaultChildren, selectedText, selectedItems }`(不复制 item 子树) |
|
||||
| `AutocompleteIndicator` | 装饰性 chevron(`aria-hidden`),`data-open` 时由 CSS 旋转 180° |
|
||||
| `AutocompleteClearButton` | 原生按钮,`aria-label="Clear selection"`、`tabindex="-1"`、`data-empty`,无选择时隐藏;点击不触发触发器切换 |
|
||||
| `AutocompletePopover` | 复用 `PopoverContent`(非模态);宽度按 anchor 实测(`ResizeObserver` → `--trigger-width`);`onOpenAutoFocus` 把焦点交给搜索框 |
|
||||
| `AutocompleteFilter` | 拥有搜索文本(`:input-value` / `@input-change`)、`filter` 谓词,并把弹层内 `SearchFieldInput` 组合成 `role="combobox"` 控件(值绑定、ARIA、方向键/Enter/Escape/Tab、IME 守卫) |
|
||||
|
||||
焦点所有权:触发器 → 打开时搜索框(`role="combobox"`,`aria-activedescendant` 指向已挂载可见的 option)→ 选择/关闭后回到触发器;列表在虚拟焦点下不处理键盘、不移动 DOM 焦点。
|
||||
|
||||
### 12.2 示例与文档
|
||||
|
||||
24 个示例(`apps/docs/demos/autocomplete-*.vue`)顺序与固定正文一致:default、variants、full-width、with-description、required、disabled、with-disabled-options、allows-empty-collection、with-sections、multiple-select、controlled、controlled-multiple、controlled-open-state、asynchronous-filtering、custom-indicator、custom-value、on-surface、virtualization、user-selection、user-selection-multiple、location-search、tag-group-selection、email-recipients、custom-styles。文档页 `apps/docs/components/autocomplete.md` 含用法/结构/24 预览/样式参考/7 个部件 API 与事件/作用域插槽说明/无障碍;导航加入 `pickers`。
|
||||
|
||||
示例与框架适配(逐项记录):
|
||||
|
||||
1. 本库无 `useFilter` hook:`AutocompleteFilter` 的默认谓词即不区分大小写的包含匹配;异步与虚拟化示例传 `:filter="() => true"`,因为集合已由数据源/调用方过滤(源示例同样不对集合二次过滤)。
|
||||
2. 无 `Virtualizer` / `ListLayout`:虚拟滚动用 `ListBox` 的 `items` + `virtualized` + `row-height`,行加 `class="h-full"` 填满固定行高。
|
||||
3. 上游多选 `Autocomplete.Value` 会复制 item 子树;本库改为提供 `selectedItems` / `selectedText`,示例用 `TagGroup` 自行渲染标签。
|
||||
4. `asynchronous-filtering`:源请求 SWAPI,改为本地异步源(300ms、每查询一个 `AbortController`、加载中不显示清除按钮、空状态)。
|
||||
5. `user-selection-multiple`:源同时传 `defaultValue` 与受控 `value`,Vue 侧用 `v-model` 初值表达同一行为。
|
||||
6. `location-search`:源的每次 filter 调用都重置定时器,这里合并为一个定时器并在卸载时清理(无行为差异)。
|
||||
|
||||
### 12.3 自验证(本轮)
|
||||
|
||||
- `pnpm typecheck` 通过;`pnpm test` **81 文件 / 1073 项**通过(新增 `tests/autocomplete.test.ts` 17 项、`tests/autocomplete-demos.test.ts` 5 项,均已加入 `test:unit`);`pnpm build:docs`、`pnpm build:playground`、Prettier、`git diff --check` 通过。
|
||||
- 行为测试覆盖:触发器单一 Tab 入口与 ARIA、打开后焦点进入搜索框、输入过滤与活动项、`Enter` 选择后关闭并回焦、`Escape`/`Tab` 关闭不选择、IME 不确认、清除按钮、禁用不可开、禁用项跳过、空结果空状态、`allows-empty-collection`、受控开关(接受与拒绝)、父级拒绝保持值、多选累加与 `aria-selected`、隐藏输入提交 key、`required` 经 `Form` 守卫阻止提交、调用方 `aria-label` 落到触发器与搜索框。
|
||||
- 演示契约:24 个预览与文件一一对应、无 `className`/`@gravity-ui/icons`/自绘 `<path>`、每个示例渲染可命名的触发器、代表示例(default/multiple-select/with-sections/custom-styles/virtualization)能打开并给出有效 `aria-activedescendant`、required 示例输出两个隐藏输入并被 `Form` 拦下。
|
||||
- 浏览器(5182):29 个触发器;首个示例打开后焦点在搜索框(`role=combobox`)、`aria-activedescendant` 指向 `role=option`、6 个 option;输入 “Te” 后仅 Texas 可见且活动项为 Texas、焦点仍在搜索框;多选示例 `Enter` 后保持打开并显示标签;空集合示例打开即显示“未找到结果”;分组示例 12 行 3 组(北美洲/欧洲/亚洲,`scrollHeight` 540);虚拟化示例 1000 行只挂载 12 行、`scrollHeight` 50012/`clientHeight` 320,`End` 后 `scrollTop` 49692 且活动项在视口内并已挂载;2 个禁用触发器 `tabindex=-1`、`aria-disabled`;清除按钮 `aria-label="Clear selection"`/`tabindex=-1`/`data-empty`;弹层宽度 256 = 触发器宽度;浅/深色下触发器背景分别为 `oklch(1 0 0)` / `oklch(0.2103 0.0059 285.89)`;控制台无 error/warning。
|
||||
- 独立 tarball 消费(`/private/tmp/b02-consumer`):`consume-b02-pickers.mjs` 通过——13 个导出、两族 SSR HTML 契约(角色、触发器、表单名、预选标签)、12 条 `hv-autocomplete*` 与 `hv-combo-box*` CSS 选择器、两族变体函数。
|
||||
|
||||
### 12.4 本轮修复的真实缺陷
|
||||
|
||||
1. `Autocomplete` 根的调用方 `class` 被丢弃(`restAttrs` 过滤后未合并)→ 触发器退化为内容宽度(110px)。已改为合并 `attrs.class`,实测 256px。
|
||||
2. 弹层宽度取不到 anchor 尺寸(Reka 未启用 size 中间件,`--reka-popper-anchor-width` 为空)→ 新增 `useTriggerWidth`(`ResizeObserver` 实测)供 ComboBox 与 Autocomplete 共用,实测弹层宽度 = 触发器宽度。
|
||||
3. `AutocompleteTrigger` 未注册为弹层 anchor → 弹层定位与宽度都错误;已注册。
|
||||
4. `AutocompleteFilter` 缺 `input-change` / `update:inputValue` 事件(与 ComboBox 不一致)→ 已补齐,两个受控示例改用该事件,不再依赖原生 `@input`。
|
||||
5. 多选下 `Enter` 确认会替换而不是累加选择(ComboBox 同样存在)→ 两个组件的 `confirmActive` 在 multiple 时改为切换该 key。
|
||||
6. ComboBox 预选值在首帧/SSR 为空 → 输入框显示值新增 `displayInputValue`(无输入文本时回落到已选标签),首帧即可读。
|
||||
|
||||
### 12.5 仍未验证
|
||||
|
||||
- 真实系统 IME、读屏软件、逐像素视觉对比。
|
||||
- 弹层内浮层选项的真实鼠标点击(本 IAB 对 floating option 报 `not actionable`;键盘与 DOM 断言覆盖,指针保焦点由 B02a harness 覆盖)。
|
||||
- 完整独立产物类型正反例矩阵(bundler / NodeNext 的公开类型契约)留在 B02d。
|
||||
|
||||
@@ -212,3 +212,7 @@ CSS/tv 仅加 `hv-` 前缀与 Vue 状态适配,保留 Apache-2.0 来源。TagR
|
||||
## 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 仓库。
|
||||
|
||||
## B02c Autocomplete(2026-10-25)
|
||||
|
||||
固定 ce90ea3 的 `packages/react/src/components/autocomplete/autocomplete.tsx`、`packages/styles/components/autocomplete.css`、`packages/styles/src/components/autocomplete/autocomplete.styles.ts`、中文 `(pickers)/autocomplete.mdx` 与 `demos/cn/autocomplete` 24 例。CSS/tv 仅加 `hv-` 前缀;默认 chevron 与清除图标沿用基线 `icons.tsx` 路径。Vue 侧把 `SearchFieldInput` 组合成弹层内的 combobox 控件;弹层宽度用本批 `useTriggerWidth`(ResizeObserver)实测,不依赖 Reka 未启用的 size 中间件;未移植 RAC 的 `useFilter`(默认谓词等价)与 `Virtualizer`(用 ListBox 的 items/virtualized)。示例的本地异步源、Value 作用域插槽与虚拟化适配已在报告 12.2 逐项记录,不运行时依赖相邻仓库。
|
||||
|
||||
@@ -1026,3 +1026,12 @@ Tag/TagGroup/ErrorMessage 的最新验收见 [B03 复核记录](migrations/B03-r
|
||||
- 新增 `tests/combo-box.test.ts`(19 项行为)与 `tests/combo-box-demos.test.ts`(6 项文档/演示契约),均已加入 `test:unit`。
|
||||
- 浏览器 5182(Chromium/IAB):输入过滤后焦点仍在输入框、`aria-activedescendant` 指向真实 option、列表只有一个 Tab 入口;`ArrowDown`+`Enter` 回写文本并关闭;`Escape` 移除 `aria-activedescendant`;三个预选示例输入框显示“猫”;禁用示例输入框原生禁用;`ComboBoxValue` 占位文本;form-value 输出 `animal` / `animal-text` 隐藏输入。
|
||||
- 未验证:浮层选项的真实鼠标点击(本 IAB 对 floating option 报 `not actionable`,指针保焦点由 B02a harness 覆盖)、真实 IME、读屏软件、逐像素对比、独立 tarball 消费(B02d)。
|
||||
|
||||
## 2026-10-25 B02c Autocomplete
|
||||
|
||||
范围与适配见 [B02 报告](migrations/B02-combobox-autocomplete.md) 第 12 节;本段只记录本轮命令与证据。
|
||||
|
||||
- `pnpm typecheck`、`pnpm build:docs`、`pnpm build:playground`、Prettier、`git diff --check` 通过;`pnpm test` **81 文件 / 1073 项**通过(新增 Autocomplete 17 项行为 + 5 项文档/演示契约,已加入 `test:unit`)。
|
||||
- 独立 tarball 消费(`/private/tmp/b02-consumer`,两族共用脚本 `tests/package/consume-b02-pickers.mjs`):导出、SSR HTML 契约、CSS 选择器与变体函数均通过;完整类型正反例矩阵留给 B02d。
|
||||
- 浏览器 5182(Chromium/IAB):29 个触发器;打开后焦点进入弹层内 `role="combobox"` 搜索框且 `aria-activedescendant` 指向真实 option;输入 “Te” 只留 Texas 且活动项随之更新;多选 `Enter` 后保持打开并显示标签;空集合示例直接显示“未找到结果”;分组示例 12 行 3 组;虚拟化示例 1000 行仅挂载 12 行,`End` 后 `scrollTop` 49692、活动项在视口内;禁用触发器 `tabindex=-1`;弹层宽度 256 = 触发器宽度;浅/深色触发器背景正确;控制台无 error/warning。
|
||||
- 未验证:真实系统 IME、读屏软件、逐像素对比、浮层选项的真实鼠标点击(本 IAB 报 `not actionable`)、完整产物类型正反例(B02d)。
|
||||
|
||||
+1
-1
@@ -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 tests/combo-box.test.ts tests/combo-box-demos.test.ts",
|
||||
"test:unit": "vitest run tests/choice-demos.test.ts tests/choice-fields.test.ts tests/fieldset-search-field.test.ts tests/components.test.ts tests/composition.test.ts tests/docs-search.test.ts tests/button-demos.test.ts tests/aligned-components.test.ts tests/surface-link-spinner.test.ts tests/close-button-avatar-skeleton.test.ts tests/separator-kbd-chip.test.ts tests/badge-alert.test.ts tests/input-group.test.ts tests/field-docs-textarea.test.ts tests/field-foundation.test.ts tests/typography-empty-breadcrumbs.test.ts tests/progress-meter.test.ts tests/disclosure-accordion.test.ts tests/overlay-foundation.test.ts tests/modal.test.ts tests/popover-tooltip.test.ts tests/overlay-demos.test.ts tests/scroll-tabs.test.ts tests/button-toggle.test.ts tests/m26-review.probe.test.ts tests/toolbar.test.ts tests/m29-review.probe.test.ts tests/m30-m32-review.probe.test.ts tests/pagination.test.ts tests/header.test.ts tests/input-otp.test.ts tests/number-field-foundation.test.ts tests/number-field.test.ts tests/slider-foundation.test.ts tests/slider.test.ts tests/collection-state.test.ts tests/collection-foundation.test.ts tests/list-box.test.ts tests/alert-dialog.test.ts tests/drawer.test.ts tests/m33-m34-review.probe.test.ts tests/m33-m34-lifecycle-review.probe.test.ts tests/m33-m34-coexist.test.ts tests/select.test.ts tests/date-value.test.ts tests/date-model.test.ts tests/date-foundation.test.ts tests/date-field.test.ts tests/date-field-demos.test.ts tests/toast.test.ts tests/table.test.ts tests/m35-m36-takeover.test.ts tests/m35-m36-review.probe.test.ts tests/m35-m36-review-2.probe.test.ts tests/m35-m36-review-3.probe.test.ts tests/m35-m36-review-4.probe.test.ts tests/m35-m36-review-5.probe.test.ts tests/m35-m36-hydration.test.ts tests/docs-shell.test.ts tests/b01-menu-dropdown.test.ts tests/b01-review.probe.test.ts tests/b01-complete-review.probe.test.ts tests/cssom.test.ts tests/tag-error-message.test.ts tests/collection-filter-virtual.test.ts tests/b02a-review.probe.test.ts tests/b02a-round2-review.probe.test.ts tests/combo-box.test.ts tests/combo-box-demos.test.ts tests/autocomplete.test.ts tests/autocomplete-demos.test.ts",
|
||||
"test:ssr": "vitest run tests/ssr.test.ts tests/input-otp-ssr.test.ts tests/slider-foundation-ssr.test.ts tests/slider-ssr.test.ts tests/collection-foundation-ssr.test.ts tests/list-box-ssr.test.ts tests/select-ssr.test.ts tests/date-foundation-ssr.test.ts tests/date-field-ssr.test.ts tests/m35-m36-ssr.test.ts",
|
||||
"format": "prettier --check .",
|
||||
"format:fix": "prettier --write .",
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
|
||||
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix. */
|
||||
/* Autocomplete styles */
|
||||
.hv-autocomplete {
|
||||
@apply flex flex-col gap-1;
|
||||
}
|
||||
|
||||
.hv-autocomplete__trigger {
|
||||
@apply relative isolate inline-flex min-h-9 rounded-field border bg-field px-3 py-2 text-sm text-field-foreground shadow-field outline-none select-none no-highlight;
|
||||
|
||||
/**
|
||||
* Transitions
|
||||
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
|
||||
*/
|
||||
transition:
|
||||
background-color 150ms var(--ease-smooth),
|
||||
border-color 150ms var(--ease-smooth),
|
||||
box-shadow 150ms var(--ease-out);
|
||||
@apply motion-reduce:transition-none;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
border-width: var(--border-width-field);
|
||||
border-color: var(--field-border);
|
||||
|
||||
/* Add inline-end padding when indicator is present */
|
||||
&:has(.hv-autocomplete__indicator) {
|
||||
@apply pe-7;
|
||||
}
|
||||
|
||||
/* Hover state - exclude when clear button is hovered to prevent double hover effect */
|
||||
@media (hover: hover) {
|
||||
&:hover:not(:has(.hv-autocomplete__clear-button:hover)),
|
||||
&[data-hovered="true"]:not(:has(.hv-autocomplete__clear-button:hover)) {
|
||||
@apply bg-field-hover;
|
||||
border-color: var(--field-border-hover);
|
||||
}
|
||||
}
|
||||
|
||||
/* Focus visible state */
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
@apply status-focused;
|
||||
border-color: var(--field-border-focus);
|
||||
background-color: var(--field-focus);
|
||||
}
|
||||
|
||||
/* Focus state */
|
||||
&:focus,
|
||||
&[data-focus="true"] {
|
||||
}
|
||||
|
||||
/* Invalid state */
|
||||
.hv-autocomplete[data-invalid="true"] &,
|
||||
.hv-autocomplete[aria-invalid="true"] & {
|
||||
@apply status-invalid-field;
|
||||
background-color: var(--field-focus);
|
||||
}
|
||||
|
||||
/* Disabled state */
|
||||
&:disabled,
|
||||
&[data-disabled="true"],
|
||||
&[aria-disabled="true"] {
|
||||
@apply status-disabled;
|
||||
}
|
||||
}
|
||||
|
||||
/* Variant property definitions */
|
||||
.hv-autocomplete--primary {
|
||||
/* Default styles */
|
||||
}
|
||||
|
||||
.hv-autocomplete--secondary .hv-autocomplete__trigger {
|
||||
@apply shadow-none;
|
||||
background-color: var(--hv-autocomplete-trigger-bg);
|
||||
|
||||
--hv-autocomplete-trigger-bg: var(--default);
|
||||
--hv-autocomplete-trigger-bg-hover: var(--default-hover);
|
||||
--hv-autocomplete-trigger-bg-focus: var(--default);
|
||||
|
||||
/* Exclude when clear button is hovered to prevent double hover effect */
|
||||
@media (hover: hover) {
|
||||
&:hover:not(:has(.hv-autocomplete__clear-button:hover)),
|
||||
&[data-hovered="true"]:not(:has(.hv-autocomplete__clear-button:hover)) {
|
||||
background-color: var(--hv-autocomplete-trigger-bg-hover);
|
||||
}
|
||||
}
|
||||
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
background-color: var(--hv-autocomplete-trigger-bg-focus);
|
||||
}
|
||||
|
||||
&:focus,
|
||||
&[data-focus="true"] {
|
||||
}
|
||||
|
||||
.hv-autocomplete[data-invalid="true"] &,
|
||||
.hv-autocomplete[aria-invalid="true"] & {
|
||||
background-color: var(--hv-autocomplete-trigger-bg-focus);
|
||||
}
|
||||
}
|
||||
|
||||
.hv-autocomplete__value {
|
||||
@apply flex-1 text-start text-base wrap-break-word text-current sm:text-sm;
|
||||
|
||||
&[data-placeholder="true"] {
|
||||
@apply text-field-placeholder;
|
||||
}
|
||||
|
||||
/* Removes the list-box-item indicator element from the hv-autocomplete value*/
|
||||
[data-slot="list-box-item-indicator"] {
|
||||
@apply hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.hv-autocomplete__indicator {
|
||||
@apply absolute inset-y-0 end-2 my-auto flex shrink-0 items-center justify-center text-field-placeholder transition duration-150;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
&[data-open="true"] {
|
||||
@apply rotate-180;
|
||||
}
|
||||
|
||||
&[data-slot="hv-autocomplete-default-indicator"] {
|
||||
@apply size-4;
|
||||
}
|
||||
}
|
||||
|
||||
/* Similar to popover content styles */
|
||||
.hv-autocomplete__popover {
|
||||
@apply flex w-(--trigger-width) max-w-(--trigger-width) origin-(--trigger-anchor-point) scroll-py-1 flex-col overflow-hidden overscroll-contain bg-overlay p-0 pt-2 text-sm outline-none;
|
||||
border-radius: min(32px, var(--radius-3xl));
|
||||
box-shadow: var(--overlay-shadow);
|
||||
|
||||
&:focus,
|
||||
&:focus-visible:not([data-focused]),
|
||||
&[data-focus-visible="true"] {
|
||||
@apply outline-none;
|
||||
}
|
||||
|
||||
/* Entering animations */
|
||||
&[data-entering="true"] {
|
||||
@apply animate-in duration-250 ease-out-fluid fade-in-0 zoom-in-95;
|
||||
|
||||
/* Placement-specific translations */
|
||||
&[data-placement="top"] {
|
||||
@apply slide-in-from-bottom-1;
|
||||
}
|
||||
|
||||
&[data-placement="bottom"] {
|
||||
@apply slide-in-from-top-1;
|
||||
}
|
||||
|
||||
&[data-placement="left"] {
|
||||
@apply slide-in-from-right-1;
|
||||
}
|
||||
|
||||
&[data-placement="right"] {
|
||||
@apply slide-in-from-left-1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Exiting animations */
|
||||
&[data-exiting="true"] {
|
||||
@apply animate-out duration-100 ease-out-quad zoom-out-95 fade-out;
|
||||
/* Stays non-interactive while closing, even if the exit animation is interrupted. */
|
||||
@apply pointer-events-none;
|
||||
}
|
||||
|
||||
&[data-exiting="true"],
|
||||
&[data-entering="true"] {
|
||||
@apply transition-[opacity,transform] will-change-[opacity,transform];
|
||||
}
|
||||
|
||||
/* Arrow styling */
|
||||
& [data-slot="popover-overlay-arrow"] {
|
||||
fill: var(--overlay);
|
||||
}
|
||||
|
||||
/* Arrow rotation based on placement */
|
||||
&[data-placement="bottom"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: 180deg;
|
||||
}
|
||||
|
||||
&[data-placement="left"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: -90deg;
|
||||
}
|
||||
|
||||
&[data-placement="right"] [data-slot="popover-overlay-arrow"] {
|
||||
rotate: 90deg;
|
||||
}
|
||||
|
||||
/* Listbox styles.
|
||||
* `min-h-0` + the popover's flex column let the list shrink below 320px when the
|
||||
* popover itself is constrained (e.g. inside a Modal, or a short viewport). Without
|
||||
* it the list keeps its full 320px and its overflow is clipped by the popover, making
|
||||
* the last options unreachable. */
|
||||
[data-slot="list-box"] {
|
||||
@apply max-h-[320px] min-h-0 scrollbar overflow-y-auto p-1.5 outline-none;
|
||||
}
|
||||
|
||||
[data-slot="list-box-item"] {
|
||||
@apply px-2.5;
|
||||
}
|
||||
|
||||
/* Virtualized rows: react-aria's Virtualizer wraps each row in an absolutely-positioned
|
||||
* [role="presentation"] element whose width equals the scroll container's clientWidth
|
||||
* (which includes the list-box horizontal padding) while sitting inside the padded content
|
||||
* box. Without this, rows overflow the right padding and the hover background reaches the
|
||||
* popover edge. Subtract the horizontal padding (2 × p-1.5 = 12px) to keep rows aligned. */
|
||||
[role="presentation"] > [data-slot="list-box-item"] {
|
||||
width: calc(100% - var(--spacing) * 3);
|
||||
}
|
||||
|
||||
/* As the popover closes fast in single-select mode, the default item indicator transition is not even visible - so we disable it only for single-select */
|
||||
[data-slot="list-box"]:not([aria-multiselectable="true"])
|
||||
[data-slot="list-box-item-indicator"],
|
||||
[data-slot="list-box"]:not([aria-multiselectable="true"])
|
||||
[data-slot="list-box-item-indicator"]
|
||||
[data-slot="list-box-item-indicator--checkmark"] {
|
||||
@apply transition-none;
|
||||
}
|
||||
|
||||
/* Search Field styles */
|
||||
[data-slot="search-field"] {
|
||||
@apply shrink-0 px-3 py-1 outline-none;
|
||||
}
|
||||
|
||||
/* Empty State */
|
||||
[data-slot="empty-state"] {
|
||||
@apply text-center text-sm text-overlay-foreground/60;
|
||||
}
|
||||
}
|
||||
|
||||
/* Full width modifier */
|
||||
.hv-autocomplete--full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
.hv-autocomplete__trigger--full-width {
|
||||
@apply w-full;
|
||||
}
|
||||
|
||||
/* Clear Button styles */
|
||||
.hv-autocomplete__clear-button {
|
||||
@apply relative isolate inline-flex h-6 w-6 shrink-0 origin-center items-center justify-center rounded-xl p-1 text-muted select-none no-highlight;
|
||||
@apply me-0 size-5 shrink-0 self-center bg-transparent;
|
||||
|
||||
/* Cursor */
|
||||
cursor: var(--cursor-interactive);
|
||||
|
||||
@apply transform-gpu;
|
||||
|
||||
/* Transition only when visible - disappears immediately when cleared */
|
||||
&:not([data-empty="true"]) {
|
||||
transition: opacity 150ms var(--ease-smooth);
|
||||
@apply motion-reduce:transition-none;
|
||||
}
|
||||
|
||||
&[data-empty="true"] {
|
||||
@apply pointer-events-none opacity-0;
|
||||
}
|
||||
|
||||
[data-slot="hv-autocomplete-clear-button-icon"] {
|
||||
@apply size-3.5;
|
||||
}
|
||||
|
||||
&:active,
|
||||
&[data-pressed="true"] {
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
&:hover,
|
||||
&[data-hovered="true"] {
|
||||
@apply bg-default-hover;
|
||||
}
|
||||
}
|
||||
|
||||
&:active,
|
||||
&[data-pressed="true"] {
|
||||
transform: scale(0.93);
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,7 @@
|
||||
@import "./components/dropdown.css" layer(components);
|
||||
@import "./components/tag-group.css" layer(components);
|
||||
@import "./components/combo-box.css" layer(components);
|
||||
@import "./components/autocomplete.css" layer(components);
|
||||
@import "./components/tag.css" layer(components);
|
||||
|
||||
@import "./components/select.css" layer(components);
|
||||
|
||||
@@ -1700,3 +1700,38 @@ export const comboBoxVariants = tv({
|
||||
});
|
||||
|
||||
export type ComboBoxVariants = VariantProps<typeof comboBoxVariants>;
|
||||
|
||||
export const autocompleteVariants = tv({
|
||||
defaultVariants: {
|
||||
fullWidth: false,
|
||||
variant: "primary",
|
||||
},
|
||||
slots: {
|
||||
base: "hv-autocomplete",
|
||||
clearButton: "hv-autocomplete__clear-button",
|
||||
filter: "hv-autocomplete__filter",
|
||||
indicator: "hv-autocomplete__indicator",
|
||||
popover: "hv-autocomplete__popover",
|
||||
trigger: "hv-autocomplete__trigger",
|
||||
value: "hv-autocomplete__value",
|
||||
},
|
||||
variants: {
|
||||
fullWidth: {
|
||||
false: {},
|
||||
true: {
|
||||
base: "hv-autocomplete--full-width",
|
||||
trigger: "hv-autocomplete__trigger--full-width",
|
||||
},
|
||||
},
|
||||
variant: {
|
||||
primary: {
|
||||
base: "hv-autocomplete--primary",
|
||||
},
|
||||
secondary: {
|
||||
base: "hv-autocomplete--secondary",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export type AutocompleteVariants = VariantProps<typeof autocompleteVariants>;
|
||||
|
||||
@@ -0,0 +1,569 @@
|
||||
<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 { autocompleteVariants } from "@heroui-vue/styles";
|
||||
import Popover from "../popover/Popover";
|
||||
import {
|
||||
useChoiceField,
|
||||
useChoiceForm,
|
||||
useChoiceValue,
|
||||
validationInput,
|
||||
} from "../choice/shared";
|
||||
import { disabledContextKey } from "../field/disabled";
|
||||
import {
|
||||
fieldContextKey,
|
||||
type ValidateResult,
|
||||
type ValidationBehavior,
|
||||
} from "../field/context";
|
||||
import { copyKeys, type CollectionKey } from "../collection/keys";
|
||||
import {
|
||||
collectionOwnerKey,
|
||||
type CollectionRecord,
|
||||
type OwnedCollection,
|
||||
} from "../collection/owner";
|
||||
import { planCollectionItems } from "../combo-box/metadata";
|
||||
import {
|
||||
autocompleteKey,
|
||||
type AutocompleteValue as AutocompleteValueType,
|
||||
} from "./context";
|
||||
|
||||
const NAMING_ATTRS = ["aria-label", "aria-labelledby", "aria-describedby"];
|
||||
const contains = (text: string, inputValue: string) =>
|
||||
!inputValue ||
|
||||
text.toLocaleLowerCase().includes(inputValue.toLocaleLowerCase());
|
||||
|
||||
export default defineComponent({
|
||||
name: "Autocomplete",
|
||||
inheritAttrs: false,
|
||||
slots: Object as SlotsType<{
|
||||
default?: (state: {
|
||||
isOpen: boolean;
|
||||
selectedKeys: CollectionKey[];
|
||||
}) => VNodeChild;
|
||||
}>,
|
||||
props: {
|
||||
modelValue: {
|
||||
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
||||
default: undefined,
|
||||
},
|
||||
value: {
|
||||
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
||||
default: undefined,
|
||||
},
|
||||
defaultValue: {
|
||||
type: [String, Number, Array, null] as PropType<AutocompleteValueType>,
|
||||
default: undefined,
|
||||
},
|
||||
selectionMode: {
|
||||
type: String as PropType<"single" | "multiple">,
|
||||
default: "single",
|
||||
},
|
||||
disabledKeys: Array as PropType<readonly CollectionKey[]>,
|
||||
open: { type: Boolean, default: undefined },
|
||||
isOpen: { type: Boolean, default: undefined },
|
||||
defaultOpen: Boolean,
|
||||
isDisabled: Boolean,
|
||||
disabled: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
allowsEmptyCollection: Boolean,
|
||||
placeholder: { type: String, default: "Select an item" },
|
||||
name: String,
|
||||
form: String,
|
||||
fullWidth: Boolean,
|
||||
variant: {
|
||||
type: String as PropType<"primary" | "secondary">,
|
||||
default: "primary",
|
||||
},
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validate: Function as PropType<
|
||||
(value: AutocompleteValueType) => ValidateResult
|
||||
>,
|
||||
as: { type: String, default: "div" },
|
||||
asChild: { type: Boolean, default: false },
|
||||
},
|
||||
emits: {
|
||||
"update:modelValue": (_value: AutocompleteValueType) => true,
|
||||
change: (_value: AutocompleteValueType) => true,
|
||||
"update:open": (_value: boolean) => true,
|
||||
openChange: (_value: boolean) => true,
|
||||
clear: () => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const instance = getCurrentInstance()!;
|
||||
const present = (keys: string[]) =>
|
||||
keys.some((key) => Object.hasOwn(instance.vnode.props ?? {}, key));
|
||||
const model = useChoiceValue<AutocompleteValueType | undefined>(
|
||||
() =>
|
||||
present(["modelValue", "model-value"])
|
||||
? (props.modelValue ?? null)
|
||||
: present(["value"])
|
||||
? (props.value ?? null)
|
||||
: undefined,
|
||||
() => props.defaultValue ?? null,
|
||||
["modelValue", "model-value", "value"],
|
||||
(value) => {
|
||||
const next = value ?? null;
|
||||
emit("update:modelValue", next);
|
||||
emit("change", next);
|
||||
},
|
||||
);
|
||||
const value = computed<AutocompleteValueType>(() => {
|
||||
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;
|
||||
const next = copyKeys(
|
||||
raw === null ? [] : Array.isArray(raw) ? raw : [raw],
|
||||
);
|
||||
if (props.selectionMode === "single" && next.length > 1)
|
||||
throw new TypeError("Single Autocomplete expects one key or null.");
|
||||
return Object.freeze(next);
|
||||
});
|
||||
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[]>([]);
|
||||
const planned = shallowRef<CollectionRecord[]>([]);
|
||||
const complete = ref(false);
|
||||
watchEffect(() => {
|
||||
if (!collection.value) return;
|
||||
const next = collection.value.items();
|
||||
if (JSON.stringify(next) !== JSON.stringify(discovered.value))
|
||||
discovered.value = next;
|
||||
});
|
||||
const records = computed<CollectionRecord[]>(() => {
|
||||
const base = complete.value
|
||||
? planned.value
|
||||
: discovered.value.length
|
||||
? discovered.value
|
||||
: planned.value;
|
||||
const disabledKeys = props.disabledKeys ?? [];
|
||||
return base.map((record) => ({
|
||||
...record,
|
||||
disabled: record.disabled || disabledKeys.includes(record.key),
|
||||
}));
|
||||
});
|
||||
|
||||
const uid = useId();
|
||||
const triggerId = `hv-autocomplete-${uid}-trigger`;
|
||||
const listId = `hv-autocomplete-${uid}-listbox`;
|
||||
const valueId = `hv-autocomplete-${uid}-value`;
|
||||
|
||||
const filterText = ref("");
|
||||
const filterPredicate = ref<(text: string, input: string) => boolean>();
|
||||
const filter = (record: CollectionRecord) =>
|
||||
(filterPredicate.value ?? contains)(record.text, filterText.value);
|
||||
|
||||
const field = useChoiceField<AutocompleteValueType>(props, attrs, {
|
||||
kind: "group",
|
||||
value,
|
||||
validate: (current) => props.validate?.(current),
|
||||
satisfied: () => keys.value.length > 0,
|
||||
requiredMessage: "请选择一个选项。",
|
||||
});
|
||||
provide(fieldContextKey, field.field);
|
||||
provide(disabledContextKey, field.field.disabled);
|
||||
|
||||
const keyboardIntent = ref(true);
|
||||
const activeKey = ref<CollectionKey>();
|
||||
const filterInput = ref<HTMLInputElement>();
|
||||
const triggerElement = ref<HTMLElement>();
|
||||
const proxy = ref<HTMLInputElement>();
|
||||
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) return;
|
||||
if (
|
||||
next.some(
|
||||
(key) =>
|
||||
records.value.find((record) => record.key === 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;
|
||||
field.edit();
|
||||
model.request(
|
||||
props.selectionMode === "multiple" ? [...next] : (next[0] ?? null),
|
||||
);
|
||||
if (props.selectionMode === "single") {
|
||||
setOpen(false);
|
||||
void nextTick(() =>
|
||||
triggerElement.value?.focus({ preventScroll: true }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function setOpen(next: boolean) {
|
||||
if (next === open.value) return;
|
||||
if (next && field.field.disabled.value) return;
|
||||
if (next && props.disabled) return;
|
||||
if (
|
||||
next &&
|
||||
!props.allowsEmptyCollection &&
|
||||
complete.value &&
|
||||
!records.value.some((record) => !record.disabled)
|
||||
)
|
||||
return;
|
||||
openModel.request(next);
|
||||
if (next) {
|
||||
filterText.value = "";
|
||||
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);
|
||||
filterInput.value?.focus({ preventScroll: true });
|
||||
});
|
||||
} else {
|
||||
activeKey.value = undefined;
|
||||
void nextTick(() => {
|
||||
if (
|
||||
filterInput.value?.ownerDocument.activeElement ===
|
||||
filterInput.value ||
|
||||
!filterInput.value
|
||||
)
|
||||
triggerElement.value?.focus({ preventScroll: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function setActive(key: CollectionKey | undefined) {
|
||||
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[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;
|
||||
if (props.selectionMode === "multiple") {
|
||||
// Confirming the active row toggles it inside the accepted set.
|
||||
const next = keys.value.includes(key)
|
||||
? keys.value.filter((item) => item !== key)
|
||||
: [...keys.value, key];
|
||||
request(next);
|
||||
return;
|
||||
}
|
||||
request([key]);
|
||||
}
|
||||
function clear() {
|
||||
if (field.field.disabled.value) return;
|
||||
if (!keys.value.length) return;
|
||||
request([]);
|
||||
emit("clear");
|
||||
}
|
||||
function focusTrigger() {
|
||||
triggerElement.value?.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
const slotsBase = computed(() =>
|
||||
autocompleteVariants({
|
||||
fullWidth: props.fullWidth,
|
||||
variant: props.variant,
|
||||
}),
|
||||
);
|
||||
const invalid = computed(() => field.field.invalid.value);
|
||||
const formValueText = computed<string | undefined>(() => {
|
||||
if (!props.name) return undefined;
|
||||
return keys.value.length ? keys.value.map(String).join(",") : undefined;
|
||||
});
|
||||
|
||||
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 : triggerId),
|
||||
ariaLabel: () =>
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: undefined,
|
||||
request,
|
||||
action: (key) => {
|
||||
void key;
|
||||
if (props.selectionMode === "single") setOpen(false);
|
||||
},
|
||||
leave: () => setOpen(false),
|
||||
connect: (next) => {
|
||||
if (collection.value && collection.value !== next)
|
||||
throw new Error("Autocomplete supports one ListBox.");
|
||||
collection.value = next;
|
||||
return () => {
|
||||
if (collection.value === next) collection.value = undefined;
|
||||
};
|
||||
},
|
||||
filter,
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
keyboardIntent,
|
||||
isOpen: () => open.value,
|
||||
});
|
||||
|
||||
const core = (): Record<string, unknown> => ({
|
||||
role: "combobox",
|
||||
"aria-expanded": true,
|
||||
"aria-controls": listId,
|
||||
"aria-activedescendant": activeId.value,
|
||||
"aria-autocomplete": "list" as const,
|
||||
"aria-haspopup": "listbox" as const,
|
||||
"aria-label":
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: undefined,
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
(attrs["aria-label"] ? undefined : field.labelledBy()),
|
||||
"aria-describedby": field.describedBy(),
|
||||
onKeydown: (event: KeyboardEvent) => {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.keyCode === 229
|
||||
)
|
||||
return;
|
||||
if (field.field.disabled.value) return;
|
||||
keyboardIntent.value = true;
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
moveActive(event.key === "ArrowDown" ? 1 : -1);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Home" || event.key === "End") {
|
||||
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) confirmActive();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Tab") setOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
provide(autocompleteKey, {
|
||||
field,
|
||||
slots: slotsBase,
|
||||
open,
|
||||
setOpen,
|
||||
keys,
|
||||
records,
|
||||
selectedItems: computed(() =>
|
||||
keys.value.map((key) => ({
|
||||
key,
|
||||
textValue:
|
||||
records.value.find((record) => record.key === key)?.text ??
|
||||
String(key),
|
||||
})),
|
||||
),
|
||||
selectionMode: computed(() => props.selectionMode),
|
||||
disabled: field.field.disabled,
|
||||
invalid,
|
||||
listId,
|
||||
triggerId,
|
||||
valueId,
|
||||
placeholder: () => props.placeholder,
|
||||
activeKey,
|
||||
activeId,
|
||||
collection,
|
||||
filterText,
|
||||
filterPredicate,
|
||||
filterInput,
|
||||
triggerElement,
|
||||
ariaLabel: () =>
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: undefined,
|
||||
core,
|
||||
focusTrigger,
|
||||
request,
|
||||
moveActive,
|
||||
setActive,
|
||||
confirmActive,
|
||||
clear,
|
||||
formValueText,
|
||||
});
|
||||
|
||||
useChoiceForm(
|
||||
proxy,
|
||||
() => {
|
||||
model.reset();
|
||||
field.reset();
|
||||
setOpen(false);
|
||||
},
|
||||
() => field.validity(proxy.value),
|
||||
);
|
||||
watchEffect(() => field.validity(proxy.value));
|
||||
watch(
|
||||
// Filtering changes the visible set: re-anchor the active row so Enter
|
||||
// always confirms something the user can actually see.
|
||||
() => `${filterText.value}|${records.value.length}|${open.value}`,
|
||||
() => {
|
||||
if (!open.value) return;
|
||||
const visible = records.value.filter(
|
||||
(record) => filter(record) && !record.disabled,
|
||||
);
|
||||
if (!visible.some((record) => record.key === activeKey.value))
|
||||
void setActive(visible[0]?.key);
|
||||
},
|
||||
);
|
||||
watch(
|
||||
() => `${keys.value.map(String).join("\u0000")}|${records.value.length}`,
|
||||
() => {
|
||||
if (
|
||||
!props.allowsEmptyCollection &&
|
||||
open.value &&
|
||||
records.value.length
|
||||
) {
|
||||
const visible = records.value.filter(
|
||||
(record) => filter(record) && !record.disabled,
|
||||
);
|
||||
if (!visible.length) setOpen(false);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
expose({
|
||||
element: triggerElement,
|
||||
open: () => setOpen(true),
|
||||
close: () => setOpen(false),
|
||||
focus: focusTrigger,
|
||||
clear,
|
||||
});
|
||||
|
||||
return () => {
|
||||
const rendered = slots.default?.({
|
||||
isOpen: open.value,
|
||||
selectedKeys: [...keys.value],
|
||||
});
|
||||
const children = Array.isArray(rendered)
|
||||
? rendered
|
||||
: rendered == null
|
||||
? []
|
||||
: [rendered];
|
||||
const plan = planCollectionItems(children);
|
||||
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
|
||||
planned.value = plan.records;
|
||||
complete.value = plan.complete;
|
||||
const nodes = field.prepare(children, true);
|
||||
const restAttrs: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
if (NAMING_ATTRS.includes(key) || key === "class" || key === "style")
|
||||
continue;
|
||||
restAttrs[key] = value;
|
||||
}
|
||||
return h(
|
||||
Popover,
|
||||
{ open: open.value, isNonModal: true, "onUpdate:open": setOpen },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
props.as,
|
||||
mergeProps(restAttrs, {
|
||||
class: [slotsBase.value.base(), attrs.class],
|
||||
style: attrs.style,
|
||||
"data-slot": "autocomplete",
|
||||
"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": "autocomplete-form-value",
|
||||
})
|
||||
: null,
|
||||
validationInput(
|
||||
proxy,
|
||||
props,
|
||||
field.field.disabled.value,
|
||||
field.behavior.value,
|
||||
(event) =>
|
||||
field.invalidEvent(event, () =>
|
||||
triggerElement.value?.focus(),
|
||||
),
|
||||
props.isRequired && field.behavior.value === "native",
|
||||
keys.value.length > 0,
|
||||
),
|
||||
],
|
||||
),
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,64 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import { useAutocomplete } from "./context";
|
||||
const CLOSE_PATH =
|
||||
"M3.47 3.47a.75.75 0 0 1 1.06 0L8 6.94l3.47-3.47a.75.75 0 1 1 1.06 1.06L9.06 8l3.47 3.47a.75.75 0 1 1-1.06 1.06L8 9.06l-3.47 3.47a.75.75 0 0 1-1.06-1.06L6.94 8 3.47 4.53a.75.75 0 0 1 0-1.06Z";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompleteClearButton",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
const empty = () => ctx.keys.value.length === 0;
|
||||
function click(event: MouseEvent) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
if (event.defaultPrevented) return;
|
||||
ctx.clear();
|
||||
}
|
||||
return () => {
|
||||
const custom = slots.default?.() ?? [];
|
||||
const icon =
|
||||
custom.length > 0
|
||||
? custom
|
||||
: [
|
||||
h(
|
||||
"svg",
|
||||
{
|
||||
"aria-hidden": "true",
|
||||
"data-slot": "autocomplete-clear-button-icon",
|
||||
fill: "none",
|
||||
height: 16,
|
||||
role: "presentation",
|
||||
viewBox: "0 0 16 16",
|
||||
width: 16,
|
||||
},
|
||||
[
|
||||
h("path", {
|
||||
d: CLOSE_PATH,
|
||||
fill: "currentColor",
|
||||
"fill-rule": "evenodd",
|
||||
"clip-rule": "evenodd",
|
||||
}),
|
||||
],
|
||||
),
|
||||
];
|
||||
const injected: Record<string, unknown> = {
|
||||
type: "button",
|
||||
tabindex: -1,
|
||||
"aria-label":
|
||||
typeof attrs["aria-label"] === "string"
|
||||
? attrs["aria-label"]
|
||||
: "Clear selection",
|
||||
class: ctx.slots.value.clearButton(),
|
||||
"data-slot": "autocomplete-clear-button",
|
||||
"data-empty": empty() || undefined,
|
||||
"aria-hidden": empty() || undefined,
|
||||
disabled: ctx.disabled.value || undefined,
|
||||
onClick: click,
|
||||
};
|
||||
return h("button", mergeProps(attrs, injected), [icon]);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,118 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* Owns the search text used to filter the collection and composes the inner
|
||||
* `SearchField.Input` into the combobox control: value binding, ARIA and the
|
||||
* keyboard contract are injected there, so navigation never moves DOM focus
|
||||
* out of the search box.
|
||||
*/
|
||||
import {
|
||||
cloneVNode,
|
||||
defineComponent,
|
||||
h,
|
||||
isVNode,
|
||||
mergeProps,
|
||||
ref,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { useChoiceValue } from "../choice/shared";
|
||||
import { useAutocomplete } from "./context";
|
||||
import { elementFromRef } from "../combo-box/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: "AutocompleteFilter",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
filter: Function as PropType<(text: string, input: string) => boolean>,
|
||||
inputValue: { type: String, default: undefined },
|
||||
defaultInputValue: { type: String, default: "" },
|
||||
},
|
||||
emits: {
|
||||
"update:inputValue": (_value: string) => true,
|
||||
inputChange: (_value: string) => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit }) {
|
||||
const ctx = useAutocomplete();
|
||||
const model = useChoiceValue<string | undefined>(
|
||||
() => props.inputValue,
|
||||
() => props.defaultInputValue,
|
||||
["inputValue", "input-value"],
|
||||
(next) => {
|
||||
emit("update:inputValue", next ?? "");
|
||||
emit("inputChange", next ?? "");
|
||||
},
|
||||
);
|
||||
const text = () => model.value.value ?? "";
|
||||
const root = ref<HTMLElement>();
|
||||
|
||||
watchEffect(() => {
|
||||
ctx.filterText.value = text();
|
||||
ctx.filterPredicate.value = props.filter;
|
||||
});
|
||||
|
||||
function compose(nodes: VNodeChild[]): VNodeChild[] {
|
||||
return nodes.map((child) => {
|
||||
if (!isVNode(child)) return child;
|
||||
const name = componentName(child);
|
||||
if (name === "ListBox") return child;
|
||||
if (name === "SearchFieldInput")
|
||||
return cloneVNode(child, {
|
||||
...ctx.core(),
|
||||
modelValue: text(),
|
||||
"onUpdate:modelValue": (next: string) => model.request(next),
|
||||
ref: (instance: unknown) => {
|
||||
ctx.filterInput.value = elementFromRef(instance) as
|
||||
HTMLInputElement | undefined;
|
||||
},
|
||||
});
|
||||
const children = child.children;
|
||||
if (Array.isArray(children)) {
|
||||
const clone = cloneVNode(child);
|
||||
clone.children = compose(children as VNodeChild[]) as never;
|
||||
return clone;
|
||||
}
|
||||
if (children && typeof children === "object") {
|
||||
const withDefault = children as {
|
||||
default?: () => VNodeChild;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
if (typeof withDefault.default === "function") {
|
||||
const clone = cloneVNode(child);
|
||||
clone.children = {
|
||||
...withDefault,
|
||||
default: () =>
|
||||
compose(([withDefault.default!()] as VNodeChild[]).flat()),
|
||||
} as never;
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
return child;
|
||||
});
|
||||
}
|
||||
|
||||
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.filter(),
|
||||
"data-slot": "autocomplete-filter",
|
||||
}),
|
||||
compose(children),
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,53 @@
|
||||
<script lang="ts">
|
||||
/** Decorative chevron: the trigger itself owns activation. */
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import { useAutocomplete } from "./context";
|
||||
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: "AutocompleteIndicator",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
return () => {
|
||||
const custom = slots.default?.() ?? [];
|
||||
const icon =
|
||||
custom.length > 0
|
||||
? custom
|
||||
: [
|
||||
h(
|
||||
"svg",
|
||||
{
|
||||
"aria-hidden": "true",
|
||||
"data-slot": "autocomplete-default-indicator",
|
||||
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",
|
||||
}),
|
||||
],
|
||||
),
|
||||
];
|
||||
return h(
|
||||
"span",
|
||||
mergeProps(attrs, {
|
||||
"aria-hidden": "true",
|
||||
class: ctx.slots.value.indicator(),
|
||||
"data-slot": "autocomplete-indicator",
|
||||
"data-open": ctx.open.value || undefined,
|
||||
}),
|
||||
icon,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,50 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useAutocomplete } from "./context";
|
||||
import { useTriggerWidth } from "../combo-box/useTriggerWidth";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompletePopover",
|
||||
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 = useAutocomplete();
|
||||
const width = useTriggerWidth(() => ctx.triggerElement.value);
|
||||
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": "autocomplete-popover",
|
||||
style: {
|
||||
"--trigger-width": width.value
|
||||
? `${width.value}px`
|
||||
: "var(--reka-popover-trigger-width)",
|
||||
"--trigger-anchor-point": "var(--reka-popper-transform-origin)",
|
||||
},
|
||||
// The filter input owns focus; the content itself never takes it.
|
||||
onOpenAutoFocus: (event: Event) => {
|
||||
event.preventDefault();
|
||||
ctx.filterInput.value?.focus({ preventScroll: true });
|
||||
},
|
||||
}),
|
||||
{ default: () => slots.default?.() },
|
||||
);
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,86 @@
|
||||
<script lang="ts">
|
||||
/** Clickable value surface: opens the popover and is the single Tab entry. */
|
||||
import { defineComponent, h, mergeProps, ref, watch } from "vue";
|
||||
import { injectPopoverRootContext } from "reka-ui";
|
||||
import { useAutocomplete } from "./context";
|
||||
import { elementFromRef } from "../combo-box/dom";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompleteTrigger",
|
||||
inheritAttrs: false,
|
||||
props: { isDisabled: { type: Boolean, default: false } },
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
const element = ref<HTMLElement>();
|
||||
const popover = injectPopoverRootContext();
|
||||
const disabled = () => props.isDisabled || ctx.disabled.value;
|
||||
|
||||
watch(
|
||||
element,
|
||||
() => {
|
||||
const node = elementFromRef(element.value);
|
||||
ctx.triggerElement.value = node;
|
||||
if (popover)
|
||||
(
|
||||
popover.triggerElement as unknown as { value: HTMLElement | null }
|
||||
).value = node ?? null;
|
||||
},
|
||||
{ immediate: true, flush: "post" },
|
||||
);
|
||||
|
||||
function toggle(event: MouseEvent) {
|
||||
if (event.defaultPrevented || disabled()) return;
|
||||
const target = event.target as Element | null;
|
||||
if (target?.closest?.('[data-slot="autocomplete-clear-button"]')) return;
|
||||
ctx.setOpen(!ctx.open.value);
|
||||
}
|
||||
function keydown(event: KeyboardEvent) {
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.isComposing ||
|
||||
event.keyCode === 229 ||
|
||||
disabled()
|
||||
)
|
||||
return;
|
||||
if (
|
||||
event.key === "Enter" ||
|
||||
event.key === " " ||
|
||||
event.key === "ArrowDown"
|
||||
) {
|
||||
event.preventDefault();
|
||||
if (!ctx.open.value) ctx.setOpen(true);
|
||||
}
|
||||
if (event.key === "Escape" && ctx.open.value) ctx.setOpen(false);
|
||||
if (event.key === "Delete" || event.key === "Backspace") ctx.clear();
|
||||
}
|
||||
|
||||
return () => {
|
||||
const injected: Record<string, unknown> = {
|
||||
ref: element,
|
||||
id: ctx.triggerId,
|
||||
role: "button",
|
||||
tabindex: disabled() ? -1 : 0,
|
||||
class: ctx.slots.value.trigger(),
|
||||
"data-slot": "autocomplete-trigger",
|
||||
"aria-haspopup": "listbox",
|
||||
"aria-expanded": ctx.open.value,
|
||||
"aria-label": attrs["aria-label"] ?? ctx.ariaLabel(),
|
||||
"aria-labelledby":
|
||||
attrs["aria-labelledby"] ??
|
||||
((attrs["aria-label"] ?? ctx.ariaLabel())
|
||||
? undefined
|
||||
: ctx.field.labelledBy()),
|
||||
onClick: toggle,
|
||||
onKeydown: keydown,
|
||||
};
|
||||
if (ctx.open.value) injected["aria-controls"] = ctx.listId;
|
||||
if (ctx.open.value) injected["data-open"] = true;
|
||||
if (disabled()) {
|
||||
injected["data-disabled"] = true;
|
||||
injected["aria-disabled"] = true;
|
||||
}
|
||||
return h("div", mergeProps(attrs, injected), slots.default?.());
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,37 @@
|
||||
<script lang="ts">
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import { useAutocomplete } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "AutocompleteValue",
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
const ctx = useAutocomplete();
|
||||
return () => {
|
||||
const selectedItems = ctx.selectedItems.value;
|
||||
const isPlaceholder = selectedItems.length === 0;
|
||||
const selectedText = selectedItems
|
||||
.map((item) => item.textValue)
|
||||
.join(", ");
|
||||
const defaultChildren = isPlaceholder ? ctx.placeholder() : selectedText;
|
||||
const content =
|
||||
slots.default?.({
|
||||
isPlaceholder,
|
||||
defaultChildren,
|
||||
selectedText,
|
||||
selectedItems,
|
||||
}) ?? defaultChildren;
|
||||
return h(
|
||||
"span",
|
||||
mergeProps(attrs, {
|
||||
id: ctx.valueId,
|
||||
class: ctx.slots.value.value(),
|
||||
"data-slot": "autocomplete-value",
|
||||
"data-placeholder": isPlaceholder || undefined,
|
||||
}),
|
||||
content,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,76 @@
|
||||
import { inject, type ComputedRef, type InjectionKey, type Ref } from "vue";
|
||||
import type { autocompleteVariants } from "@heroui-vue/styles";
|
||||
import type { CollectionKey } from "../collection/keys";
|
||||
import type { CollectionRecord, OwnedCollection } from "../collection/owner";
|
||||
import type { useChoiceField } from "../choice/shared";
|
||||
|
||||
export type AutocompleteValue = CollectionKey | CollectionKey[] | null;
|
||||
export interface AutocompleteSelectedItem {
|
||||
key: CollectionKey;
|
||||
textValue: string;
|
||||
}
|
||||
export interface AutocompleteOptions {
|
||||
modelValue?: AutocompleteValue;
|
||||
value?: AutocompleteValue;
|
||||
defaultValue?: AutocompleteValue;
|
||||
selectionMode?: "single" | "multiple";
|
||||
disabledKeys?: readonly CollectionKey[];
|
||||
open?: boolean;
|
||||
isOpen?: boolean;
|
||||
defaultOpen?: boolean;
|
||||
isDisabled?: boolean;
|
||||
disabled?: boolean;
|
||||
isRequired?: boolean;
|
||||
isInvalid?: boolean;
|
||||
allowsEmptyCollection?: boolean;
|
||||
placeholder?: string;
|
||||
name?: string;
|
||||
form?: string;
|
||||
fullWidth?: boolean;
|
||||
variant?: "primary" | "secondary";
|
||||
validationBehavior?: "native" | "aria";
|
||||
validate?: (value: AutocompleteValue) => unknown;
|
||||
as?: string;
|
||||
asChild?: boolean;
|
||||
}
|
||||
export interface AutocompleteContext {
|
||||
field: ReturnType<typeof useChoiceField<AutocompleteValue>>;
|
||||
slots: ComputedRef<ReturnType<typeof autocompleteVariants>>;
|
||||
open: ComputedRef<boolean>;
|
||||
setOpen: (open: boolean) => void;
|
||||
keys: ComputedRef<readonly CollectionKey[]>;
|
||||
records: ComputedRef<CollectionRecord[]>;
|
||||
selectedItems: ComputedRef<AutocompleteSelectedItem[]>;
|
||||
selectionMode: ComputedRef<"single" | "multiple">;
|
||||
disabled: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
listId: string;
|
||||
triggerId: string;
|
||||
valueId: string;
|
||||
placeholder: () => string;
|
||||
activeKey: Ref<CollectionKey | undefined>;
|
||||
activeId: ComputedRef<string | undefined>;
|
||||
collection: Ref<OwnedCollection | undefined>;
|
||||
/** Filter text owned by AutocompleteFilter and read by the collection filter. */
|
||||
filterText: Ref<string>;
|
||||
filterPredicate: Ref<((text: string, input: string) => boolean) | undefined>;
|
||||
filterInput: Ref<HTMLInputElement | undefined>;
|
||||
triggerElement: Ref<HTMLElement | undefined>;
|
||||
ariaLabel: () => string | undefined;
|
||||
core: () => Record<string, unknown>;
|
||||
focusTrigger: () => void;
|
||||
request: (keys: CollectionKey[]) => void;
|
||||
moveActive: (delta: 1 | -1) => void;
|
||||
setActive: (key: CollectionKey | undefined) => Promise<void>;
|
||||
confirmActive: () => void;
|
||||
clear: () => void;
|
||||
formValueText: ComputedRef<string | undefined>;
|
||||
}
|
||||
export const autocompleteKey: InjectionKey<AutocompleteContext> =
|
||||
Symbol("hv-autocomplete");
|
||||
|
||||
export function useAutocomplete(): AutocompleteContext {
|
||||
const context = inject(autocompleteKey, undefined);
|
||||
if (!context) throw new Error("Autocomplete parts require Autocomplete.");
|
||||
return context;
|
||||
}
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
type CollectionRecord,
|
||||
type OwnedCollection,
|
||||
} from "../collection/owner";
|
||||
import { planComboBoxItems } from "./metadata";
|
||||
import { planCollectionItems } from "./metadata";
|
||||
import {
|
||||
comboBoxKey,
|
||||
type ComboBoxItem,
|
||||
@@ -271,6 +271,7 @@ export default defineComponent({
|
||||
const activeKey = ref<CollectionKey>();
|
||||
const cursor = ref<CollectionKey>();
|
||||
const inputElement = ref<HTMLInputElement>();
|
||||
const triggerElement = ref<HTMLElement>();
|
||||
let anchor: (() => HTMLElement | undefined) | undefined;
|
||||
const registerAnchor = (element: () => HTMLElement | undefined) => {
|
||||
anchor = element;
|
||||
@@ -377,6 +378,14 @@ export default defineComponent({
|
||||
(item) => item.key === key && filter(item) && !item.disabled,
|
||||
);
|
||||
if (!record) return;
|
||||
if (props.selectionMode === "multiple") {
|
||||
// Confirming the active row toggles it inside the accepted set.
|
||||
const next = keys.value.includes(key)
|
||||
? keys.value.filter((item) => item !== key)
|
||||
: [...keys.value, key];
|
||||
request(next);
|
||||
return;
|
||||
}
|
||||
request([key]);
|
||||
}
|
||||
|
||||
@@ -397,6 +406,20 @@ export default defineComponent({
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* The visible text falls back to the accepted item's label so an initial or
|
||||
* external selection is readable on the very first render (including SSR),
|
||||
* before the selection-sync watcher has run.
|
||||
*/
|
||||
const displayInputValue = computed(() => {
|
||||
if (inputValue.value) return inputValue.value;
|
||||
if (props.selectionMode !== "single") return "";
|
||||
const selected = records.value.find((record) =>
|
||||
keys.value.includes(record.key),
|
||||
);
|
||||
return selected?.text ?? "";
|
||||
});
|
||||
|
||||
function setInputValue(next: string) {
|
||||
inputModel.request(next);
|
||||
if (props.menuTrigger === "input" && !open.value && next) setOpen(true);
|
||||
@@ -557,6 +580,7 @@ export default defineComponent({
|
||||
open,
|
||||
setOpen,
|
||||
inputValue,
|
||||
displayInputValue,
|
||||
setInputValue,
|
||||
inputId,
|
||||
listId,
|
||||
@@ -580,6 +604,7 @@ export default defineComponent({
|
||||
menuTrigger: () => props.menuTrigger,
|
||||
inputElement,
|
||||
registerAnchor,
|
||||
triggerElement,
|
||||
inputProps,
|
||||
formValueText,
|
||||
invalid,
|
||||
@@ -638,7 +663,7 @@ export default defineComponent({
|
||||
: rendered == null
|
||||
? []
|
||||
: [rendered];
|
||||
const plan = planComboBoxItems(children);
|
||||
const plan = planCollectionItems(children);
|
||||
if (JSON.stringify(plan.records) !== JSON.stringify(planned.value))
|
||||
planned.value = plan.records;
|
||||
complete.value = plan.complete;
|
||||
|
||||
@@ -37,6 +37,13 @@ export default defineComponent({
|
||||
const root = ref<HTMLElement>();
|
||||
|
||||
ctx.registerAnchor(() => elementFromRef(root.value));
|
||||
watch(
|
||||
root,
|
||||
() => {
|
||||
ctx.triggerElement.value = elementFromRef(root.value);
|
||||
},
|
||||
{ immediate: true, flush: "post" },
|
||||
);
|
||||
watch(
|
||||
root,
|
||||
() => {
|
||||
@@ -55,7 +62,7 @@ export default defineComponent({
|
||||
if (!isVNode(node) || componentName(node) !== "Input") return node;
|
||||
return cloneVNode(node, {
|
||||
...ctx.inputProps(),
|
||||
modelValue: ctx.inputValue.value,
|
||||
modelValue: ctx.displayInputValue.value,
|
||||
"onUpdate:modelValue": (next: string) => ctx.setInputValue(next),
|
||||
ref: (instance: unknown) => {
|
||||
ctx.inputElement.value = elementFromRef(instance) as
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { defineComponent, h, mergeProps } from "vue";
|
||||
import PopoverContent from "../popover/PopoverContent.vue";
|
||||
import { useComboBox } from "./context";
|
||||
import { useTriggerWidth } from "./useTriggerWidth";
|
||||
import type { OverlayPlacement } from "../overlay/placement";
|
||||
|
||||
export default defineComponent({
|
||||
@@ -16,6 +17,7 @@ export default defineComponent({
|
||||
},
|
||||
setup(props, { attrs, slots }) {
|
||||
const ctx = useComboBox();
|
||||
const width = useTriggerWidth(() => ctx.triggerElement.value);
|
||||
return () =>
|
||||
h(
|
||||
PopoverContent,
|
||||
@@ -30,7 +32,9 @@ export default defineComponent({
|
||||
role: "presentation",
|
||||
"data-slot": "combo-box-popover",
|
||||
style: {
|
||||
"--trigger-width": "var(--reka-popover-trigger-width)",
|
||||
"--trigger-width": width.value
|
||||
? `${width.value}px`
|
||||
: "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.
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface ComboBoxContext {
|
||||
open: ComputedRef<boolean>;
|
||||
setOpen: (open: boolean) => void;
|
||||
inputValue: ComputedRef<string>;
|
||||
/** Text shown in the input: the accepted item's label before any typing. */
|
||||
displayInputValue: ComputedRef<string>;
|
||||
setInputValue: (value: string) => void;
|
||||
inputId: string;
|
||||
listId: string;
|
||||
@@ -72,6 +74,7 @@ export interface ComboBoxContext {
|
||||
menuTrigger: () => ComboBoxMenuTrigger;
|
||||
inputElement: Ref<HTMLInputElement | undefined>;
|
||||
registerAnchor: (element: () => HTMLElement | undefined) => void;
|
||||
triggerElement: Ref<HTMLElement | undefined>;
|
||||
/** ARIA plus input handlers injected onto the composed `Input`. */
|
||||
inputProps: () => Record<string, unknown>;
|
||||
formValueText: ComputedRef<string | undefined>;
|
||||
|
||||
@@ -36,14 +36,20 @@ function text(nodes: VNodeChild[]): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
const CONTAINERS = ["ComboBoxPopover", "SelectPopover", "ListBoxSection"];
|
||||
const CONTAINERS = [
|
||||
"ComboBoxPopover",
|
||||
"AutocompletePopover",
|
||||
"AutocompleteFilter",
|
||||
"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.
|
||||
* Collect collection metadata from a picker's slot tree. Filtering, the initial
|
||||
* value label and form text need the full data set before the popover (and
|
||||
* therefore the ListBox) has ever mounted.
|
||||
*/
|
||||
export function planComboBoxItems(nodes: VNodeChild[]) {
|
||||
export function planCollectionItems(nodes: VNodeChild[]) {
|
||||
const records: CollectionRecord[] = [];
|
||||
let found = false;
|
||||
let opaque = false;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { onBeforeUnmount, ref, watchEffect } from "vue";
|
||||
|
||||
/**
|
||||
* Track the anchor's border-box width so a popover can match it. Reka does not
|
||||
* expose the anchor size without its own trigger component, so the width is
|
||||
* measured here (the baseline component measures its trigger the same way).
|
||||
*/
|
||||
export function useTriggerWidth(get: () => HTMLElement | undefined) {
|
||||
const width = ref<number>();
|
||||
let observer: ResizeObserver | undefined;
|
||||
watchEffect(() => {
|
||||
const element = get();
|
||||
observer?.disconnect();
|
||||
observer = undefined;
|
||||
if (!element) return;
|
||||
const measure = () => {
|
||||
width.value = element.offsetWidth || undefined;
|
||||
};
|
||||
measure();
|
||||
if (typeof ResizeObserver === "function") {
|
||||
observer = new ResizeObserver(measure);
|
||||
observer.observe(element);
|
||||
}
|
||||
});
|
||||
onBeforeUnmount(() => observer?.disconnect());
|
||||
return width;
|
||||
}
|
||||
@@ -979,3 +979,30 @@ export type {
|
||||
} from "./components/combo-box/context";
|
||||
|
||||
export { comboBoxVariants, type ComboBoxVariants } from "@heroui-vue/styles";
|
||||
|
||||
export { default as Autocomplete } from "./components/autocomplete/Autocomplete.vue";
|
||||
export { default as AutocompleteTrigger } from "./components/autocomplete/AutocompleteTrigger.vue";
|
||||
export { default as AutocompleteValue } from "./components/autocomplete/AutocompleteValue.vue";
|
||||
export { default as AutocompleteIndicator } from "./components/autocomplete/AutocompleteIndicator.vue";
|
||||
export { default as AutocompleteClearButton } from "./components/autocomplete/AutocompleteClearButton.vue";
|
||||
export { default as AutocompletePopover } from "./components/autocomplete/AutocompletePopover.vue";
|
||||
export { default as AutocompleteFilter } from "./components/autocomplete/AutocompleteFilter.vue";
|
||||
export type {
|
||||
AutocompleteProps,
|
||||
AutocompleteTriggerProps,
|
||||
AutocompleteValueProps,
|
||||
AutocompleteIndicatorProps,
|
||||
AutocompleteClearButtonProps,
|
||||
AutocompletePopoverProps,
|
||||
AutocompleteFilterProps,
|
||||
} from "./types";
|
||||
export type {
|
||||
AutocompleteSelectedItem,
|
||||
AutocompleteOptions,
|
||||
} from "./components/autocomplete/context";
|
||||
export type { AutocompleteValue as AutocompleteValueModel } from "./components/autocomplete/context";
|
||||
|
||||
export {
|
||||
autocompleteVariants,
|
||||
type AutocompleteVariants,
|
||||
} from "@heroui-vue/styles";
|
||||
|
||||
@@ -765,3 +765,36 @@ import type ComboBoxPopover from "./components/combo-box/ComboBoxPopover.vue";
|
||||
export type ComboBoxPopoverProps = InstanceType<
|
||||
typeof ComboBoxPopover
|
||||
>["$props"];
|
||||
|
||||
import type Autocomplete from "./components/autocomplete/Autocomplete.vue";
|
||||
export type AutocompleteProps = InstanceType<typeof Autocomplete>["$props"];
|
||||
|
||||
import type AutocompleteTrigger from "./components/autocomplete/AutocompleteTrigger.vue";
|
||||
export type AutocompleteTriggerProps = InstanceType<
|
||||
typeof AutocompleteTrigger
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteValue from "./components/autocomplete/AutocompleteValue.vue";
|
||||
export type AutocompleteValueProps = InstanceType<
|
||||
typeof AutocompleteValue
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteIndicator from "./components/autocomplete/AutocompleteIndicator.vue";
|
||||
export type AutocompleteIndicatorProps = InstanceType<
|
||||
typeof AutocompleteIndicator
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteClearButton from "./components/autocomplete/AutocompleteClearButton.vue";
|
||||
export type AutocompleteClearButtonProps = InstanceType<
|
||||
typeof AutocompleteClearButton
|
||||
>["$props"];
|
||||
|
||||
import type AutocompletePopover from "./components/autocomplete/AutocompletePopover.vue";
|
||||
export type AutocompletePopoverProps = InstanceType<
|
||||
typeof AutocompletePopover
|
||||
>["$props"];
|
||||
|
||||
import type AutocompleteFilter from "./components/autocomplete/AutocompleteFilter.vue";
|
||||
export type AutocompleteFilterProps = InstanceType<
|
||||
typeof AutocompleteFilter
|
||||
>["$props"];
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { nextTick, type Component } from "vue";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 6));
|
||||
const mounted: { unmount: () => void }[] = [];
|
||||
|
||||
const previews = [
|
||||
"default",
|
||||
"variants",
|
||||
"full-width",
|
||||
"with-description",
|
||||
"required",
|
||||
"disabled",
|
||||
"with-disabled-options",
|
||||
"allows-empty-collection",
|
||||
"with-sections",
|
||||
"multiple-select",
|
||||
"controlled",
|
||||
"controlled-multiple",
|
||||
"controlled-open-state",
|
||||
"asynchronous-filtering",
|
||||
"custom-indicator",
|
||||
"custom-value",
|
||||
"on-surface",
|
||||
"virtualization",
|
||||
"user-selection",
|
||||
"user-selection-multiple",
|
||||
"location-search",
|
||||
"tag-group-selection",
|
||||
"email-recipients",
|
||||
"custom-styles",
|
||||
];
|
||||
|
||||
afterEach(async () => {
|
||||
while (mounted.length) mounted.pop()?.unmount();
|
||||
await nextTick();
|
||||
await settle();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("Autocomplete docs and demos", () => {
|
||||
it("keeps the pinned preview order and one demo per preview", () => {
|
||||
const document = readFileSync(
|
||||
"apps/docs/components/autocomplete.md",
|
||||
"utf8",
|
||||
);
|
||||
const names = [
|
||||
...document.matchAll(/<ComponentPreview name="autocomplete-([^"]+)"/g),
|
||||
].map((match) => match[1]);
|
||||
|
||||
expect(names).toEqual(previews);
|
||||
for (const name of previews) {
|
||||
const source = readFileSync(
|
||||
`apps/docs/demos/autocomplete-${name}.vue`,
|
||||
"utf8",
|
||||
);
|
||||
expect(source, name).toContain("<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 instead of React ones", () => {
|
||||
const document = readFileSync(
|
||||
"apps/docs/components/autocomplete.md",
|
||||
"utf8",
|
||||
);
|
||||
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
|
||||
expect(document).toContain("`class`");
|
||||
expect(document).toContain("Vue class 绑定");
|
||||
for (const part of [
|
||||
"AutocompleteTrigger",
|
||||
"AutocompleteValue",
|
||||
"AutocompleteIndicator",
|
||||
"AutocompleteClearButton",
|
||||
"AutocompletePopover",
|
||||
"AutocompleteFilter",
|
||||
])
|
||||
expect(document, part).toContain(`### ${part}`);
|
||||
expect(document).not.toContain("[!toc]");
|
||||
// React object-style part names must not appear as API table entries.
|
||||
expect(document).not.toMatch(/\|\s*`Autocomplete\.[A-Z]\w*`\s*\|/);
|
||||
});
|
||||
|
||||
it("mounts every demo with a named trigger", async () => {
|
||||
const modules = import.meta.glob("../apps/docs/demos/autocomplete-*.vue");
|
||||
expect(Object.keys(modules)).toHaveLength(previews.length);
|
||||
|
||||
for (const [path, load] of Object.entries(modules)) {
|
||||
const demo = (await load()) as { default: Component };
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
const triggers = (wrapper.element as HTMLElement).querySelectorAll(
|
||||
'[data-slot="autocomplete-trigger"]',
|
||||
);
|
||||
expect(triggers.length, path).toBeGreaterThan(0);
|
||||
for (const element of triggers) {
|
||||
expect(element.getAttribute("role"), path).toBe("button");
|
||||
expect(element.getAttribute("aria-expanded"), path).toBe("false");
|
||||
}
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
await settle();
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
});
|
||||
|
||||
it("opens and filters inside representative demos", async () => {
|
||||
for (const name of [
|
||||
"default",
|
||||
"multiple-select",
|
||||
"with-sections",
|
||||
"custom-styles",
|
||||
"virtualization",
|
||||
]) {
|
||||
const demo = (await import(
|
||||
`../apps/docs/demos/autocomplete-${name}.vue`
|
||||
)) as { default: Component };
|
||||
const wrapper = mount(demo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const trigger = (
|
||||
wrapper.element as HTMLElement
|
||||
).querySelector<HTMLElement>('[data-slot="autocomplete-trigger"]')!;
|
||||
trigger.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
const search = document.querySelector<HTMLInputElement>(
|
||||
'[data-slot="search-field-input"]',
|
||||
);
|
||||
expect(search, name).not.toBeNull();
|
||||
expect(trigger.getAttribute("aria-expanded"), name).toBe("true");
|
||||
const id = search!.getAttribute("aria-activedescendant");
|
||||
expect(id, name).toBeTruthy();
|
||||
expect(document.getElementById(id!)?.getAttribute("role"), name).toBe(
|
||||
"option",
|
||||
);
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
await settle();
|
||||
document.body.innerHTML = "";
|
||||
}
|
||||
});
|
||||
|
||||
it("submits the required and name demos", async () => {
|
||||
const formDemo =
|
||||
(await import("../apps/docs/demos/autocomplete-required.vue")) as {
|
||||
default: Component;
|
||||
};
|
||||
const wrapper = mount(formDemo.default, { attachTo: document.body });
|
||||
mounted.push(wrapper);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const hidden = [
|
||||
...(wrapper.element as HTMLElement).querySelectorAll<HTMLInputElement>(
|
||||
'input[type="hidden"][name]',
|
||||
),
|
||||
];
|
||||
expect(hidden.map((input) => input.name).sort()).toEqual([
|
||||
"country",
|
||||
"state",
|
||||
]);
|
||||
// `Form` renders novalidate and guards submit itself: an empty required
|
||||
// field must keep the demo's status line empty.
|
||||
const root = wrapper.element as HTMLElement;
|
||||
const form = (root.matches("form") ? root : root.querySelector("form"))!;
|
||||
const submit = (
|
||||
wrapper.element as HTMLElement
|
||||
).querySelector<HTMLButtonElement>('button[type="submit"]')!;
|
||||
submit.click();
|
||||
await nextTick();
|
||||
expect(form.getAttribute("novalidate")).not.toBeNull();
|
||||
expect(
|
||||
(wrapper.element as HTMLElement)
|
||||
.querySelector('[role="status"]')
|
||||
?.textContent?.trim() ?? "",
|
||||
).toBe("");
|
||||
wrapper.unmount();
|
||||
mounted.pop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,666 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref, type Component } from "vue";
|
||||
import {
|
||||
Autocomplete,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteFilter,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
Form,
|
||||
Label,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldSearchIcon,
|
||||
} from "../packages/vue/src";
|
||||
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 4));
|
||||
const mounted: { unmount: () => void }[] = [];
|
||||
|
||||
type State = { id: string | number; name: string; disabled?: boolean };
|
||||
const states: State[] = [
|
||||
{ id: "california", name: "California" },
|
||||
{ id: "texas", name: "Texas" },
|
||||
{ id: "florida", name: "Florida" },
|
||||
];
|
||||
|
||||
function shell(
|
||||
props: Record<string, unknown>,
|
||||
options: { states?: State[]; empty?: boolean; description?: boolean } = {},
|
||||
emits: Record<string, unknown> = {},
|
||||
) {
|
||||
const items = options.states ?? states;
|
||||
return mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
Autocomplete,
|
||||
{
|
||||
"aria-label": "州",
|
||||
placeholder: "选择州/省",
|
||||
...emits,
|
||||
...props,
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(Label, () => "州"),
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(AutocompleteValue),
|
||||
h(AutocompleteClearButton),
|
||||
h(AutocompleteIndicator),
|
||||
],
|
||||
}),
|
||||
h(AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(AutocompleteFilter, null, {
|
||||
default: () => [
|
||||
h(
|
||||
SearchField,
|
||||
{ "aria-label": "搜索州名" },
|
||||
{
|
||||
default: () =>
|
||||
h(SearchFieldGroup, null, {
|
||||
default: () => [
|
||||
h(SearchFieldSearchIcon),
|
||||
h(SearchFieldInput, {
|
||||
placeholder: "搜索州名…",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
),
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
items.map((state) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: state.id,
|
||||
key: state.id,
|
||||
textValue: state.name,
|
||||
isDisabled: state.disabled,
|
||||
},
|
||||
() => state.name,
|
||||
),
|
||||
),
|
||||
empty: () =>
|
||||
h("p", { "data-test": "empty" }, "未找到结果"),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
}
|
||||
|
||||
function track(wrapper: { unmount: () => void }) {
|
||||
mounted.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
const trigger = () =>
|
||||
document.querySelector<HTMLElement>('[data-slot="autocomplete-trigger"]')!;
|
||||
const search = () =>
|
||||
document.querySelector<HTMLInputElement>('[data-slot="search-field-input"]')!;
|
||||
const valueText = () =>
|
||||
document
|
||||
.querySelector('[data-slot="autocomplete-value"]')
|
||||
?.textContent?.trim();
|
||||
const rowTexts = () =>
|
||||
[...document.querySelectorAll('[role="option"]')]
|
||||
.filter((row) => !row.hasAttribute("data-filtered"))
|
||||
.map((row) => row.textContent?.trim());
|
||||
|
||||
async function open(wrapper?: { unmount: () => void }) {
|
||||
void wrapper;
|
||||
trigger().dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
}
|
||||
async function press(key: string, init: KeyboardEventInit = {}) {
|
||||
search().dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
...init,
|
||||
}),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
}
|
||||
async function type(text: string) {
|
||||
const element = search();
|
||||
element.value = text;
|
||||
element.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (mounted.length) mounted.pop()?.unmount();
|
||||
await nextTick();
|
||||
await settle();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("Autocomplete trigger", () => {
|
||||
it("is the single tab entry with placeholder and value semantics", async () => {
|
||||
track(shell({}));
|
||||
await nextTick();
|
||||
await settle();
|
||||
const element = trigger();
|
||||
|
||||
expect(element.getAttribute("role")).toBe("button");
|
||||
expect(element.getAttribute("tabindex")).toBe("0");
|
||||
expect(element.getAttribute("aria-haspopup")).toBe("listbox");
|
||||
expect(element.getAttribute("aria-expanded")).toBe("false");
|
||||
expect(valueText()).toBe("选择州/省");
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="autocomplete-clear-button"]')!
|
||||
.getAttribute("tabindex"),
|
||||
).toBe("-1");
|
||||
});
|
||||
|
||||
it("opens on click, focuses the search box and filters from there", async () => {
|
||||
track(shell({}));
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("true");
|
||||
expect(document.activeElement).toBe(search());
|
||||
expect(search().getAttribute("role")).toBe("combobox");
|
||||
const id = search().getAttribute("aria-activedescendant");
|
||||
expect(document.getElementById(id!)?.getAttribute("role")).toBe("option");
|
||||
|
||||
await type("Te");
|
||||
expect(rowTexts()).toEqual(["Texas"]);
|
||||
expect(document.activeElement).toBe(search());
|
||||
const active = search().getAttribute("aria-activedescendant");
|
||||
expect(document.getElementById(active!)?.textContent?.trim()).toBe("Texas");
|
||||
});
|
||||
|
||||
it("selects with Enter, closes and restores focus to the trigger", async () => {
|
||||
const onChange = vi.fn();
|
||||
track(shell({}, {}, { onChange }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
await type("Te");
|
||||
await press("Enter");
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith("texas");
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(valueText()).toBe("Texas");
|
||||
expect(document.activeElement).toBe(trigger());
|
||||
});
|
||||
|
||||
it("closes on Escape and on Tab without selecting", async () => {
|
||||
const onChange = vi.fn();
|
||||
track(shell({}, {}, { onChange }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
await press("Escape");
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(document.activeElement).toBe(trigger());
|
||||
|
||||
await open();
|
||||
await press("Tab");
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not confirm while an IME composition is active", async () => {
|
||||
const onChange = vi.fn();
|
||||
track(shell({}, {}, { onChange }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
await press("Enter", { isComposing: true });
|
||||
await press("Enter", { keyCode: 229 });
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears the selection from the clear button", async () => {
|
||||
const onChange = vi.fn();
|
||||
const clear = vi.fn();
|
||||
track(shell({ defaultValue: "texas" }, {}, { onChange, onClear: clear }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(valueText()).toBe("Texas");
|
||||
|
||||
document
|
||||
.querySelector<HTMLElement>('[data-slot="autocomplete-clear-button"]')!
|
||||
.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
|
||||
expect(onChange).toHaveBeenLastCalledWith(null);
|
||||
expect(clear).toHaveBeenCalledTimes(1);
|
||||
expect(valueText()).toBe("选择州/省");
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("stays closed and non-tabbable while disabled", async () => {
|
||||
track(shell({ isDisabled: true }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(trigger().getAttribute("tabindex")).toBe("-1");
|
||||
expect(trigger().getAttribute("aria-disabled")).toBe("true");
|
||||
await open();
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("skips disabled keys while navigating", async () => {
|
||||
const onChange = vi.fn();
|
||||
track(
|
||||
shell(
|
||||
{},
|
||||
{
|
||||
states: [
|
||||
{ id: "california", name: "California", disabled: true },
|
||||
{ id: "texas", name: "Texas" },
|
||||
],
|
||||
},
|
||||
{ onChange },
|
||||
),
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
await press("Enter");
|
||||
expect(onChange).toHaveBeenLastCalledWith("texas");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Autocomplete state", () => {
|
||||
it("shows the empty channel when nothing matches", async () => {
|
||||
track(shell({}));
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
await type("zzz");
|
||||
expect(rowTexts()).toEqual([]);
|
||||
expect(document.querySelector('[data-test="empty"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("opens an empty collection only when allowed", async () => {
|
||||
track(shell({ allowsEmptyCollection: true }, { states: [] }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("true");
|
||||
expect(document.querySelector('[data-test="empty"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("follows a controlled open state", async () => {
|
||||
const openState = ref(false);
|
||||
const onOpenChange = vi.fn((value: boolean) => (openState.value = value));
|
||||
track(
|
||||
mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
Autocomplete,
|
||||
{
|
||||
"aria-label": "州",
|
||||
isOpen: openState.value,
|
||||
onOpenChange,
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [h(AutocompleteValue)],
|
||||
}),
|
||||
h(AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(AutocompleteFilter, null, {
|
||||
default: () => [
|
||||
h(
|
||||
SearchField,
|
||||
{ "aria-label": "搜索" },
|
||||
{
|
||||
default: () =>
|
||||
h(SearchFieldGroup, null, {
|
||||
default: () => [h(SearchFieldInput)],
|
||||
}),
|
||||
},
|
||||
),
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
states.map((state) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: state.id,
|
||||
key: state.id,
|
||||
textValue: state.name,
|
||||
},
|
||||
() => state.name,
|
||||
),
|
||||
),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
) as never,
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
expect(onOpenChange).toHaveBeenCalledWith(true);
|
||||
// The parent accepted the proposal, so the controlled state is open.
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("true");
|
||||
|
||||
openState.value = false;
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("keeps the value when the parent rejects the proposal", async () => {
|
||||
const onChange = vi.fn();
|
||||
track(shell({ value: null }, {}, { onChange }));
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
await press("Enter");
|
||||
expect(onChange).toHaveBeenCalledWith("california");
|
||||
expect(valueText()).toBe("选择州/省");
|
||||
});
|
||||
|
||||
it("accumulates multiple selections and renders tags", async () => {
|
||||
const selected = ref<(string | number)[]>([]);
|
||||
track(
|
||||
mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
Autocomplete,
|
||||
{
|
||||
"aria-label": "州",
|
||||
selectionMode: "multiple",
|
||||
modelValue: selected.value,
|
||||
"onUpdate:modelValue": (value: unknown) => {
|
||||
selected.value = (value ?? []) as (string | number)[];
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [h(AutocompleteValue)],
|
||||
}),
|
||||
h(AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(AutocompleteFilter, null, {
|
||||
default: () => [
|
||||
h(
|
||||
SearchField,
|
||||
{ "aria-label": "搜索" },
|
||||
{
|
||||
default: () =>
|
||||
h(SearchFieldGroup, null, {
|
||||
default: () => [h(SearchFieldInput)],
|
||||
}),
|
||||
},
|
||||
),
|
||||
h(
|
||||
ListBox,
|
||||
{ selectionMode: "multiple" },
|
||||
{
|
||||
default: () =>
|
||||
states.map((state) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: state.id,
|
||||
key: state.id,
|
||||
textValue: state.name,
|
||||
},
|
||||
() => state.name,
|
||||
),
|
||||
),
|
||||
},
|
||||
),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
) as never,
|
||||
);
|
||||
await nextTick();
|
||||
await settle();
|
||||
await open();
|
||||
await press("Enter");
|
||||
await press("ArrowDown");
|
||||
await press("Enter");
|
||||
expect(selected.value).toEqual(["california", "texas"]);
|
||||
// Multi-select keeps the popover open for further picks.
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("true");
|
||||
expect(
|
||||
[
|
||||
...document.querySelectorAll('[role="option"][aria-selected="true"]'),
|
||||
].map((row) => row.textContent?.trim()),
|
||||
).toEqual(["California", "Texas"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Autocomplete form and validation", () => {
|
||||
it("submits the selected key through a hidden input", async () => {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
const submitted = ref("");
|
||||
return () =>
|
||||
h(
|
||||
Form,
|
||||
{
|
||||
onSubmit: (event: Event) => {
|
||||
event.preventDefault();
|
||||
const data = new FormData(
|
||||
event.currentTarget as HTMLFormElement,
|
||||
);
|
||||
submitted.value = String(data.get("state"));
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(
|
||||
Autocomplete,
|
||||
{
|
||||
"aria-label": "州",
|
||||
name: "state",
|
||||
defaultValue: "texas",
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [h(AutocompleteValue)],
|
||||
}),
|
||||
h(AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(AutocompleteFilter, null, {
|
||||
default: () => [
|
||||
h(
|
||||
SearchField,
|
||||
{ "aria-label": "搜索" },
|
||||
{
|
||||
default: () =>
|
||||
h(SearchFieldGroup, null, {
|
||||
default: () => [h(SearchFieldInput)],
|
||||
}),
|
||||
},
|
||||
),
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
states.map((state) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: state.id,
|
||||
key: state.id,
|
||||
textValue: state.name,
|
||||
},
|
||||
() => state.name,
|
||||
),
|
||||
),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
h(
|
||||
"button",
|
||||
{ type: "submit", "data-test": "submit" },
|
||||
"提交",
|
||||
),
|
||||
h("p", { "data-test": "result" }, submitted.value),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper as never);
|
||||
await nextTick();
|
||||
await settle();
|
||||
(
|
||||
document.querySelector('[data-test="submit"]') as HTMLButtonElement
|
||||
).click();
|
||||
await nextTick();
|
||||
expect(document.querySelector('[data-test="result"]')!.textContent).toBe(
|
||||
"texas",
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks native submit when required and empty", async () => {
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(
|
||||
Form,
|
||||
{ onSubmit: (event: Event) => event.preventDefault() },
|
||||
{
|
||||
default: () => [
|
||||
h(
|
||||
Autocomplete,
|
||||
{
|
||||
"aria-label": "州",
|
||||
name: "state",
|
||||
isRequired: true,
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(Label, () => "州"),
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [h(AutocompleteValue)],
|
||||
}),
|
||||
h(AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(AutocompleteFilter, null, {
|
||||
default: () => [
|
||||
h(
|
||||
SearchField,
|
||||
{ "aria-label": "搜索" },
|
||||
{
|
||||
default: () =>
|
||||
h(SearchFieldGroup, null, {
|
||||
default: () => [h(SearchFieldInput)],
|
||||
}),
|
||||
},
|
||||
),
|
||||
h(ListBox, null, {
|
||||
default: () =>
|
||||
states.map((state) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: state.id,
|
||||
key: state.id,
|
||||
textValue: state.name,
|
||||
},
|
||||
() => state.name,
|
||||
),
|
||||
),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
h(
|
||||
"button",
|
||||
{ type: "submit", "data-test": "submit" },
|
||||
"提交",
|
||||
),
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper as never);
|
||||
await nextTick();
|
||||
await settle();
|
||||
const form = document.querySelector("form")!;
|
||||
expect(form.checkValidity()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Autocomplete composition", () => {
|
||||
it("keeps a caller-provided aria-label on the trigger and search box", async () => {
|
||||
track(shell({}));
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(trigger().getAttribute("aria-label")).toBe("州");
|
||||
await open();
|
||||
expect(search().getAttribute("aria-label")).toBe("州");
|
||||
});
|
||||
|
||||
it("mounts as a reusable component surface", async () => {
|
||||
const surface: Component = (
|
||||
await import("../apps/docs/demos/autocomplete-multiple-select.vue")
|
||||
).default;
|
||||
const wrapper = mount(surface, { attachTo: document.body });
|
||||
track(wrapper as never);
|
||||
await nextTick();
|
||||
await settle();
|
||||
expect(trigger().getAttribute("aria-expanded")).toBe("false");
|
||||
expect(valueText()).toBe("选择州/省");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createSSRApp, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import * as lib from "@heroui-vue/components";
|
||||
|
||||
for (const name of [
|
||||
"ComboBox",
|
||||
"ComboBoxInputGroup",
|
||||
"ComboBoxTrigger",
|
||||
"ComboBoxValue",
|
||||
"ComboBoxPopover",
|
||||
"Autocomplete",
|
||||
"AutocompleteTrigger",
|
||||
"AutocompleteValue",
|
||||
"AutocompleteIndicator",
|
||||
"AutocompleteClearButton",
|
||||
"AutocompletePopover",
|
||||
"AutocompleteFilter",
|
||||
"comboBoxVariants",
|
||||
"autocompleteVariants",
|
||||
])
|
||||
assert(lib[name], name);
|
||||
|
||||
const items = [
|
||||
{ id: "cat", textValue: "猫" },
|
||||
{ id: "dog", textValue: "狗" },
|
||||
];
|
||||
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h("main", [
|
||||
h(
|
||||
lib.ComboBox,
|
||||
{ "aria-label": "动物", defaultSelectedKey: "cat", name: "animal" },
|
||||
{
|
||||
default: () => [
|
||||
h(lib.Label, null, () => "动物"),
|
||||
h(lib.ComboBoxInputGroup, null, {
|
||||
default: () => [h(lib.Input, {}), h(lib.ComboBoxTrigger)],
|
||||
}),
|
||||
h(lib.ComboBoxPopover, null, {
|
||||
default: () =>
|
||||
h(lib.ListBox, null, {
|
||||
default: () =>
|
||||
items.map((item) =>
|
||||
h(
|
||||
lib.ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.textValue,
|
||||
},
|
||||
() => item.textValue,
|
||||
),
|
||||
),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
h(
|
||||
lib.Autocomplete,
|
||||
{ "aria-label": "州", name: "state", defaultValue: "dog" },
|
||||
{
|
||||
default: () => [
|
||||
h(lib.AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(lib.AutocompleteValue),
|
||||
h(lib.AutocompleteClearButton),
|
||||
h(lib.AutocompleteIndicator),
|
||||
],
|
||||
}),
|
||||
h(lib.AutocompletePopover, null, {
|
||||
default: () =>
|
||||
h(lib.AutocompleteFilter, null, {
|
||||
default: () => [
|
||||
h(
|
||||
lib.SearchField,
|
||||
{ "aria-label": "搜索" },
|
||||
{
|
||||
default: () =>
|
||||
h(lib.SearchFieldGroup, null, {
|
||||
default: () => [h(lib.SearchFieldInput)],
|
||||
}),
|
||||
},
|
||||
),
|
||||
h(lib.ListBox, null, {
|
||||
default: () =>
|
||||
items.map((item) =>
|
||||
h(
|
||||
lib.ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.textValue,
|
||||
},
|
||||
() => item.textValue,
|
||||
),
|
||||
),
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
],
|
||||
},
|
||||
),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
|
||||
assert(html.includes('data-slot="combo-box"'), "combo-box root");
|
||||
assert(html.includes('role="combobox"'), "combobox input role");
|
||||
assert(html.includes('data-slot="combo-box-trigger"'), "combo box trigger");
|
||||
assert(html.includes('name="animal"'), "combo box form name");
|
||||
assert(html.includes('data-slot="autocomplete"'), "autocomplete root");
|
||||
assert(
|
||||
html.includes('data-slot="autocomplete-trigger"'),
|
||||
"autocomplete trigger",
|
||||
);
|
||||
assert(html.includes('role="button"'), "autocomplete trigger is a button");
|
||||
assert(html.includes('name="state"'), "autocomplete form name");
|
||||
assert(html.includes("猫"), "combo box preselected label");
|
||||
|
||||
const css = readFileSync(
|
||||
"node_modules/@heroui-vue/styles/dist/styles.css",
|
||||
"utf8",
|
||||
);
|
||||
for (const rule of [
|
||||
".hv-combo-box",
|
||||
".hv-combo-box__input-group",
|
||||
".hv-combo-box__trigger",
|
||||
".hv-combo-box__popover",
|
||||
".hv-combo-box__value",
|
||||
".hv-autocomplete",
|
||||
".hv-autocomplete__trigger",
|
||||
".hv-autocomplete__value",
|
||||
".hv-autocomplete__indicator",
|
||||
".hv-autocomplete__clear-button",
|
||||
".hv-autocomplete__popover",
|
||||
".hv-autocomplete--secondary",
|
||||
])
|
||||
assert(css.includes(rule), `missing CSS ${rule}`);
|
||||
|
||||
assert(
|
||||
lib
|
||||
.comboBoxVariants({ fullWidth: true })
|
||||
.base()
|
||||
.includes("hv-combo-box--full-width"),
|
||||
);
|
||||
assert(
|
||||
lib
|
||||
.autocompleteVariants({ variant: "secondary" })
|
||||
.base()
|
||||
.includes("hv-autocomplete--secondary"),
|
||||
);
|
||||
|
||||
console.log("B02 pickers consumption OK");
|
||||
Reference in New Issue
Block a user