Files
heroui-vue/apps/docs/demos/combo-box-asynchronous-loading.vue
T
maoyingjie c8d54abefb 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.
2026-10-29 13:46:34 +08:00

210 lines
6.5 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!-- 适配说明:固定源此例请求 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,
ComboBoxInputGroup,
ComboBoxPopover,
ComboBoxTrigger,
EmptyState,
Input,
Label,
ListBox,
ListBoxItem,
ListBoxItemIndicator,
Spinner,
} from "@heroui-vue/components";
type Character = {
id: string;
name: string;
};
const PAGE_SIZE = 4;
const PAGE_DELAY = 300;
const characters: Character[] = [
{ id: "Luke Skywalker", name: "Luke Skywalker" },
{ id: "Princess Leia", name: "Princess Leia" },
{ id: "Han Solo", name: "Han Solo" },
{ id: "Darth Vader", name: "Darth Vader" },
{ id: "Yoda", name: "Yoda" },
{ id: "Obi-Wan Kenobi", name: "Obi-Wan Kenobi" },
{ id: "Palpatine", name: "Palpatine" },
{ id: "Lando Calrissian", name: "Lando Calrissian" },
{ id: "Chewbacca", name: "Chewbacca" },
{ id: "R2-D2", name: "R2-D2" },
{ id: "C-3PO", name: "C-3PO" },
{ 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();
return characters.filter(
(character) => !text || character.name.toLocaleLowerCase().includes(text),
);
}
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 mockPage(query, offset, current.signal);
// 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 || token !== sequence) return;
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) {
loading.value = false;
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) {
inputValue.value = next;
void load(next, 0, false);
}
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);
});
onBeforeUnmount(() => {
controller?.abort();
});
</script>
<template>
<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"
>
<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>