feat(collections): auto incremental async loading, shared filtering and submenu delay

HD-10 scope, against heroui ce90ea3 collection sources and their
react-aria/react-stately dependencies:

- the ComboBox async demo now auto-loads on scroll-to-bottom
  (IntersectionObserver sentinel + fill chain mirroring the pinned
  ListBoxLoadMoreItem re-observe semantics), never duplicates requests
  (loading guards + monotonic sequence token), drops stale responses on
  query switches, keeps a retry path for failures (injectable mock
  failure) and documents its differences from the pinned SWAPI source;
  the Select demo's observer stays untouched (real-network scroll
  triggering verified in browser)
- the Autocomplete virtualization demo and the default filter share one
  locale-sensitive matcher: createBaseContains (Intl.Collator base
  sensitivity, cafe matches Cafe with accent folding) is now exported
  from the package root
- Autocomplete trigger semantics verified complete (single tab stop,
  Enter/Space/Escape/Delete/IME, single and multiple selection) and the
  scoped slots gained composition data instead of child copying:
  AutocompleteValue exposes selectedItem and per-entry source item,
  the ComboBox root exposes selectedItem
- DropdownSubmenuTrigger exposes the pinned delay contract (default
  200ms): the controlled open gate retimes Reka's fixed 100ms hover,
  keyboard opens stay immediate and cancel the pending hover, pointer
  leave cancels; the dead side/align forwarding is gone (Reka fixes the
  submenu side per direction); Button/Avatar trigger layout
  compensation kept after browser proof it is what wins the cascade
- tests/fixtures/collections-rtl.vue drives the real-browser delay and
  RTL geometry checks; b02-pickers contract pins the new export and
  slot typing

Full suite 111 files / 1666 tests, typecheck, build:docs and the
b02-pickers + api-root-aliases tarball contracts pass.
This commit is contained in:
maoyingjie
2026-10-29 13:46:13 +08:00
parent c34faccd70
commit c8d54abefb
21 changed files with 1020 additions and 173 deletions
+5 -3
View File
@@ -162,7 +162,7 @@ Autocomplete 组件支持两种视觉变体:
::: warning
多选模式下,上游 `Autocomplete.Value` 会把每个选中项在 `ListBox.Item` 中的 children 复制到触发器中,并以符合当前语言环境的分隔符连接:仅包含文本的选项显示为纯文本,但复选框、头像等可见内容会随每个选中项各出现一次;函数形式的 children 也始终以 `isSelected: false` 调用。
本库不复制子树,而是给 `AutocompleteValue` 的作用域插槽提供 `selectedItems`(`{ key, textValue }[]`)与 `selectedText`(纯文本),因此不存在上述重复渲染问题,但函数形式的插槽同样不携带 `isSelected`。
本库不复制子树,而是给 `AutocompleteValue` 的作用域插槽提供 `selectedItems`(`{ key, textValue, item? }[]`,`item` 为根 `items` 中的源数据项)、`selectedItem`(首个选中项)与 `selectedText`(纯文本),调用方可直接用源数据组合头像、可移除标签等丰富展示,因此不存在上述重复渲染问题,但函数形式的插槽同样不携带 `isSelected`。
:::
如需以纯文本显示选中值,请使用 `selectedText`:
@@ -437,15 +437,17 @@ Autocomplete 组件使用以下 CSS 类([查看源码样式](https://github.co
| `isPlaceholder` | `boolean` | 是否没有选中项 |
| `defaultChildren` | `string`(上游为 `ReactNode`) | 缺省文本(选中项文本以逗号连接,否则占位符) |
| `selectedText` | `string` | 选中项 `textValue` 的连接文本 |
| `selectedItems` | `Array<{ key, textValue }>` | 选中项 |
| `selectedItems` | `Array<{ key, textValue, item? }>` | 选中项;`item` 为根 `items` 中的源数据项(集合自发现的项没有) |
| `selectedItem` | `{ key, textValue, item? } \| null` | 首个选中项(单选即所选项),便于单选组合 |
上游 `state.selectedItems`(节点)在本库中是上表的 `selectedItems`(数据);不复制 item 子树,见「多选」说明。
上游 `state.selectedItems`(节点)在本库中是上表的 `selectedItems`(数据,条目携带源数据 `item`);不复制 item 子树,见「多选」说明。
### 过滤函数(`useFilter` 替代)
上游页面导出的 `useFilter` hook(`contains` / `startsWith` / `endsWith` 与 `sensitivity`)在本库没有对应导出。替代方式:
- `AutocompleteFilter` 的默认谓词等价于 `useFilter({ sensitivity: "base" }).contains`:按 `ConfigProvider` 的 locale 折叠大小写与变音符号,`cafe` 能命中 `Café`
- 调用方自行过滤数据时(虚拟化、异步数据源),可从包根导入 `createBaseContains`(与默认谓词同一实现)保持语义一致:`const { locale } = useLocale(); const contains = createBaseContains(locale.value)`
- 需要 `startsWith` / `endsWith` 等语义时,直接给 `:filter="(text, input) => …"` 传函数
- 数据源或调用方已过滤时(异步、虚拟化示例),传 `:filter="() => true"` 避免二次过滤
+5 -3
View File
@@ -133,6 +133,8 @@ import {
<ComponentPreview name="combo-box-asynchronous-loading" />
示例的本地数据源模拟固定源的 SWAPI 请求状态机(搜索过滤、游标分页、加载中、滚动到底自动增量加载、取消旧请求与过期响应保护、失败重试);与 SWAPI 的差异是数据为固定 12 条本地角色、延迟为模拟值,失败由「模拟加载失败」开关注入。加载行位于 ListBox 之外(固定源为 `ListBoxLoadMoreItem` 行内哨兵),自动触发语义一致。
### 默认选中项
<ComponentPreview name="combo-box-default-selected-key" />
@@ -314,7 +316,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
| `placeholder` | `string` | `'Select an item'` | `ComboBoxValue` 的缺省占位文本(上游根上没有该 prop,由 `ComboBoxValue` 的 placeholder 表达) |
| `as` | `string` | `'div'` | 自定义根元素标签 |
| `as-child` | `boolean` | `false` | 使用唯一子元素作为根节点并合并属性 |
| 默认插槽 | `{ isOpen, inputValue, selectedKey, selectedKeys }` | - | 组件内容;作用域提供当前状态 |
| 默认插槽 | `{ isOpen, inputValue, selectedKey, selectedKeys, selectedItem }` | - | 组件内容;作用域提供当前状态 |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
事件:
@@ -334,7 +336,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
### 作用域插槽与渲染状态
默认插槽提供 `{ isOpen, inputValue, selectedKey, selectedKeys }`。上游的 `Render Props` 表格里还有 `state` 与 `selectedItem`:本库不暴露 React Aria 的 state 对象,选中项数据可从 `records`/`selectedKeys` 派生(示例见 `@update:model-value` 与 `ComboBoxValue` 的作用域插槽),该差异不另设等价 prop。
默认插槽提供 `{ isOpen, inputValue, selectedKey, selectedKeys, selectedItem }`。上游的 `Render Props` 表格里还有 `state` 与 `selectedItem`:`selectedItem` 以作用域数据补齐(根 `items` 中与单选 key 匹配的源数据项;多选或自定义值时为 `null`,`ComboBoxValue` 的 `selectedItems` 条目也携带同源 `item`),调用方可直接用自己的数据对象组合展示,无需按键反查;本库不暴露 React Aria 的 state 对象,该差异不另设等价 prop。
### ComboBoxInputGroup
@@ -350,7 +352,7 @@ ComboBox 组件使用以下 CSS 类([查看源码样式](https://github.com/he
| Prop | 类型 | 默认值 | 描述 |
| ------------- | ---------------------------------- | -------------------- | ----------------------------- |
| `placeholder` | `string`(上游为 `ReactNode`) | 根上的 `placeholder` | 未选中任何项时的占位文本 |
| 默认插槽 | `{ isPlaceholder, selectedItems }` | - | 自定义已选值展示 |
| 默认插槽 | `{ isPlaceholder, selectedItems }` | - | 自定义已选值展示;`selectedItems` 条目为 `{ key, textValue, item? }`(`item` 为根 `items` 中的源数据项) |
| `class` | `string \| Array \| Object` | - | 附加 CSS 类(Vue class 绑定) |
### ComboBoxTrigger
+2 -1
View File
@@ -370,6 +370,7 @@ Dropdown 使用 Menu、MenuItem 与 MenuSection 作为底层组件。以下类
| Slots / Props | 说明 |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 默认插槽 | 第一个子节点是触发条目,其余子节点渲染进子菜单内容 |
| `delay` | 悬停展开延迟(毫秒),默认 `200`(与固定源 `useSubmenuTrigger` 一致);键盘展开立即生效并取消挂起的悬停展开,指针离开取消 |
| `class`/ARIA | 合并到触发条目元素上 |
| 面板参数 | 嵌套 `DropdownPopover` 的 `offset`/`crossOffset`/`shouldFlip`/`containerPadding`/`loop`/`to`、`class`/`style`/`id`/`data-*`/ARIA 与事件都会传给子菜单面板;`isKeyboardDismissDisabled` 为真时 Esc 既不关子层也不关父层,`shouldCloseOnInteractOutside` 返回 `false` 时外部交互不关闭 |
@@ -408,7 +409,7 @@ Dropdown 组件实现 ARIA 菜单模式,并提供:
- 部件导出为具名组件(`DropdownRoot` / `DropdownTrigger` / …),触发器需要显式包裹,官方是把 `Button` 直接放在 `Dropdown` 下。
- `Selection`/`Set` 改为 `MenuKey[]`;`onAction`/`onSelectionChange`/`onClose` 改为 Vue 事件;`isOpen`/`onOpenChange` 改为 `open` + `v-model:open`。
- 官方 `items` + 渲染函数的数据驱动集合用 `v-for` 表达;`renderEmptyState` 对应 `empty` 插槽。不提供 React Collection 对象模型。
- 子菜单悬停展开延迟由底层固定为 100ms,未暴露官方 `delay`(默认 200ms);子菜单面板的 `side`/`align` 由底层固定,只有偏移与碰撞参数可调。
- 子菜单悬停展开延迟由 `DropdownSubmenuTrigger` 的 `delay` 配置(默认 200ms,与固定源 `useSubmenuTrigger` 一致):底层 Reka 的固定 100ms 悬停计时被重定为该延迟,键盘展开立即生效并取消挂起的悬停展开,指针离开取消;子菜单面板的 `side`/`align` 由底层固定(贴父项向右、RTL 反向),只有偏移与碰撞参数可调。
- `DropdownTrigger` 的作用域插槽只提供 `{ isOpen }`,`DropdownPopover` 只提供 `{ isEntering, isExiting, placement }`;官方 Button/Popover 的完整 render props 未全部覆盖。
- `DropdownRoot` 额外渲染一层 `.hv-dropdown` 包裹元素(官方该类没有 DOM 宿主),承载根级 class、style、id、ARIA、data 属性与原生事件。作为 `ButtonGroup` 直接子级时仍保留该容器,接缝样式按容器在组内的位置适配内部触发按钮;根级属性与捕获事件的行为不变。
- 条目 `id` 是业务 key,DOM id 为实例级;官方把 key 直接作为 DOM id(Vue 端避免数字 `0` 与字符串 `"0"` 冲突)。
@@ -9,6 +9,7 @@ import {
AutocompletePopover,
AutocompleteTrigger,
AutocompleteValue,
createBaseContains,
Description,
EmptyState,
Label,
@@ -20,6 +21,7 @@ import {
SearchFieldGroup,
SearchFieldInput,
SearchFieldSearchIcon,
useLocale,
type ListBoxKey,
} from "@heroui-vue/components";
@@ -97,15 +99,19 @@ const allUsers = generateUsers(1000);
const selectedKey = ref<ListBoxKey | null>(null);
const searchQuery = ref("");
// 与 AutocompleteFilter 默认谓词共用同一实现(locale 敏感、大小写与变音折叠,
// 例如 cafe 能匹配 Café);本示例自行过滤以驱动虚拟滚动,故关闭集合二次过滤。
const { locale } = useLocale();
const contains = computed(() => createBaseContains(locale.value));
const filteredUsers = computed(() => {
const query = searchQuery.value.trim().toLocaleLowerCase();
const query = searchQuery.value.trim();
if (!query) return allUsers;
return allUsers.filter(
(user) =>
user.name.toLocaleLowerCase().includes(query) ||
user.email.toLocaleLowerCase().includes(query),
contains.value(user.name, query) || contains.value(user.email, query),
);
});
@@ -1,6 +1,11 @@
<!-- 适配:源示例请求 SWAPI,这里用本地异步源演示相同状态(取消旧请求、加载中、增量加载)。 -->
<!-- 适配说明:固定源此例请求 SWAPI(swapi.py4e.com/api/people,useAsyncList 游标分页 + 行内 ListBoxLoadMoreItem 哨兵)。
本示例改用本地异步源模拟同一状态机:搜索过滤、游标分页、加载中、滚动到底自动增量加载、
取消旧请求与过期响应保护、失败重试。与 SWAPI 的差异:数据为固定 12 条本地角色(非 82 条远端人员),
网络延迟为固定 300ms 模拟(不可观测 DNS/网络错误),失败由「模拟加载失败」开关注入。
加载行位于 ListBox 之外(基线为 ListBoxLoadMoreItem 的行内加载行),自动触发语义一致。 -->
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from "vue";
import { useIntersectionObserver } from "@vueuse/core";
import {
Button,
ComboBox,
@@ -39,12 +44,18 @@ const characters: Character[] = [
{ id: "Boba Fett", name: "Boba Fett" },
];
const simulateFailure = ref(false);
const inputValue = ref("");
const items = ref<Character[]>([]);
const loading = ref(false);
const loadingMore = ref(false);
const error = ref(false);
const hasMore = ref(false);
const sentinel = ref<HTMLElement>();
const sentinelVisible = ref(false);
let controller: AbortController | undefined;
/** Monotonic request token: stale responses are dropped even without abort. */
let sequence = 0;
function matches(query: string) {
const text = query.trim().toLocaleLowerCase();
@@ -54,39 +65,53 @@ function matches(query: string) {
);
}
function mockPage(query: string, offset: number, signal: AbortSignal) {
return new Promise<Character[]>((resolve, reject) => {
const timer = setTimeout(() => {
if (simulateFailure.value) {
reject(new Error("模拟加载失败"));
return;
}
resolve(matches(query).slice(offset, offset + PAGE_SIZE));
}, PAGE_DELAY);
signal.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
},
{ once: true },
);
});
}
async function load(query: string, offset: number, append: boolean) {
controller?.abort();
const current = new AbortController();
const token = ++sequence;
controller = current;
error.value = false;
if (append) loadingMore.value = true;
else loading.value = true;
try {
const page = await new Promise<Character[]>((resolve, reject) => {
const timer = setTimeout(() => {
resolve(matches(query).slice(offset, offset + PAGE_SIZE));
}, PAGE_DELAY);
const page = await mockPage(query, offset, current.signal);
current.signal.addEventListener(
"abort",
() => {
clearTimeout(timer);
reject(new DOMException("Aborted", "AbortError"));
},
{ once: true },
);
});
if (current.signal.aborted) return;
// A newer request superseded this one: drop the stale response.
if (current.signal.aborted || token !== sequence) return;
items.value = append ? [...items.value, ...page] : page;
hasMore.value = offset + page.length < matches(query).length;
} catch {
if (current.signal.aborted) return;
if (current.signal.aborted || token !== sequence) return;
items.value = [];
hasMore.value = false;
error.value = true;
if (!append) {
items.value = [];
hasMore.value = false;
}
} finally {
// A newer request owns the flags once it has taken over the controller.
if (controller === current) {
@@ -94,6 +119,11 @@ async function load(query: string, offset: number, append: boolean) {
loadingMore.value = false;
}
}
// Chain-fill: the fresh page may leave the sentinel inside the viewport, in
// which case scrolling is not needed to request the next one.
if (sentinelVisible.value && hasMore.value && !error.value)
queueMicrotask(() => maybeLoadMore());
}
function handleInputChange(next: string) {
@@ -101,11 +131,25 @@ function handleInputChange(next: string) {
void load(next, 0, false);
}
function loadMore() {
if (loading.value || loadingMore.value || !hasMore.value) return;
function maybeLoadMore() {
if (loading.value || loadingMore.value || error.value || !hasMore.value) return;
void load(inputValue.value, items.value.length, true);
}
function retry() {
if (loading.value || loadingMore.value) return;
void load(inputValue.value, items.value.length, items.value.length > 0);
}
// Scroll-to-bottom auto incremental loading: the sentinel drives the loads and
// in-flight requests are never duplicated. When a fresh page does not push the
// sentinel out of view, the load chain keeps filling (the pinned
// ListBoxLoadMoreItem re-observes per collection change for the same effect).
useIntersectionObserver(sentinel, ([entry]) => {
sentinelVisible.value = !!entry?.isIntersecting;
if (entry?.isIntersecting) maybeLoadMore();
});
onMounted(() => {
void load(inputValue.value, 0, false);
});
@@ -116,41 +160,50 @@ onBeforeUnmount(() => {
</script>
<template>
<ComboBox
allows-empty-collection
class="w-[256px]"
:input-value="inputValue"
@input-change="handleInputChange"
>
<Label>选择角色</Label>
<ComboBoxInputGroup>
<Input placeholder="星球大战角色…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover>
<ListBox :aria-busy="loading || undefined">
<ListBoxItem
v-for="item in items"
:id="item.id"
:key="item.id"
:text-value="item.name"
<div class="flex flex-col gap-2">
<ComboBox
allows-empty-collection
class="w-[256px]"
:input-value="inputValue"
@input-change="handleInputChange"
>
<Label>选择角色</Label>
<ComboBoxInputGroup>
<Input placeholder="星球大战角色…" />
<ComboBoxTrigger />
</ComboBoxInputGroup>
<ComboBoxPopover class="max-h-80">
<ListBox :aria-busy="loading || undefined">
<ListBoxItem
v-for="item in items"
:id="item.id"
:key="item.id"
:text-value="item.name"
>
{{ item.name }}
<ListBoxItemIndicator />
</ListBoxItem>
<template #empty>
<EmptyState />
</template>
</ListBox>
<div ref="sentinel" aria-hidden="true" class="h-px" />
<div
v-if="loadingMore || error"
class="flex items-center justify-center gap-2 py-2"
role="status"
>
{{ item.name }}
<ListBoxItemIndicator />
</ListBoxItem>
<template #empty>
<EmptyState />
</template>
</ListBox>
<div v-if="hasMore" class="flex items-center justify-center gap-2 py-2">
<template v-if="loadingMore">
<Spinner size="sm" />
<span class="text-sm text-muted" role="status">加载更多…</span>
</template>
<Button v-else variant="ghost" size="sm" @click="loadMore">
加载更多…
</Button>
</div>
</ComboBoxPopover>
</ComboBox>
<template v-if="loadingMore">
<Spinner size="sm" />
<span class="text-sm text-muted">加载更多…</span>
</template>
<Button v-else variant="ghost" size="sm" @click="retry">重试</Button>
</div>
</ComboBoxPopover>
</ComboBox>
<label class="flex items-center gap-2 text-sm text-muted">
<input v-model="simulateFailure" type="checkbox" />
模拟加载失败(本地数据源注入;SWAPI 场景为真实网络错误)
</label>
</div>
</template>
+7
View File
@@ -24,6 +24,13 @@ const labs = [
() => import("../../../tests/fixtures/table-layout.vue"),
),
},
{
key: "collections-rtl",
title: "子菜单延迟与 RTL 定位",
component: defineAsyncComponent(
() => import("../../../tests/fixtures/collections-rtl.vue"),
),
},
{
key: "button-group-dropdown",
title: "按钮组与下拉根属性",