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
@@ -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>