fix(collection): make virtual window, reveal and confirmation honest

- Give the verification instance a real constrained scroll owner and a row
  height that matches the rendered row, and feed ListBox the full data schema so
  a row that was never mounted can still be filtered.
- Move reveal validity in front of every side effect and re-check after each
  await: latest token, mounted component, enabled row, still visible and open.
  Waiting for a virtualized row now requires connected DOM, not just a
  registration, and closing the collection cancels pending work.
- Reconcile the shared active key reactively: a removed, disabled, filtered-out
  or closed active row is cleared, while the accepted value stays as history.
  The composite re-validates before confirming, so a stale candidate cannot be
  submitted.
- Read the caller's cancellation before the focus guard so a plain virtual-focus
  press keeps its pressed state, and use one nested-interactive boundary for
  both pointer and click, covering contenteditable variants and custom roles.
- Render the empty channel for static slot collections too, keeping hidden
  members mounted.

Adds the seven-case round-two probe and twelve regressions; browser checks cover
the real virtual window, remote filtering, viewport-contained navigation and
filter restoration.
This commit is contained in:
maoyingjie
2026-10-25 16:40:00 +08:00
parent 50ad3ca180
commit c8b0aa26c3
8 changed files with 522 additions and 44 deletions
@@ -22,6 +22,8 @@ export interface CollectionView {
* there is one source instead of a second copy.
*/
keyboardIntent?: Ref<boolean>;
/** The composite's disclosure state; closed collections cancel pending reveals. */
isOpen?: () => boolean;
}
export interface OwnedCollection {
items: () => CollectionRecord[];
@@ -11,6 +11,7 @@ import {
provide,
ref,
useAttrs,
watchEffect,
} from "vue";
import { useVirtualList } from "@vueuse/core";
import { listboxVariants } from "@heroui-vue/styles";
@@ -160,6 +161,26 @@ const visibleKeys = computed(
() => new Set(visibleKnown().map((item) => item.key)),
);
const eligible = () => visibleKnown().filter((item) => !item.disabled);
/** Empty channel needs a settled collection: static children register on mount. */
const visibleIsEmpty = computed(
() => visibleKeys.value.size === 0 && (!!props.items || known().length > 0),
);
// A removed, disabled or filtered-out row cannot stay active. The collection
// clears the shared active key (it never invents a value) and leaves the next
// candidate to the composite; a closed collection has no active row at all.
watchEffect(() => {
if (!virtualFocus.value || !mounted.value) return;
const activeRef = owner?.activeKey;
if (!activeRef || activeRef.value === undefined) return;
const key = activeRef.value;
void visibleKeys.value;
if (
owner?.isOpen?.() === false ||
!eligible().some((item) => item.key === key)
)
activeRef.value = undefined;
});
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
@@ -247,10 +268,15 @@ const nextFrame = (): Promise<void> =>
typeof requestAnimationFrame === "function"
? new Promise((resolve) => requestAnimationFrame(() => resolve()))
: nextTick();
/** A virtualized row mounts after the window moves; wait for it, bounded. */
async function waitForMountedRow(key: ListBoxKey) {
/** A virtualized row mounts after the window moves; wait for real DOM, bounded. */
async function waitForMountedRow(key: ListBoxKey, valid: () => boolean) {
for (let attempt = 0; attempt < 3; attempt++) {
if (registry.ordered().some((member) => member.key() === key)) return;
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
if (element?.isConnected) return;
await nextFrame();
}
}
@@ -259,38 +285,55 @@ async function waitForMountedRow(key: ListBoxKey) {
* window by index; ordinary lists scroll the mounted row (the row itself may
* sit inside any scroll container supplied by the caller).
*/
async function revealRow(key: ListBoxKey) {
async function revealRow(key: ListBoxKey, valid: () => boolean) {
// Every side effect is guarded: filtering, closing, unmounting or a newer
// request invalidates the work that is still awaiting.
if (!valid()) return;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
if (index < 0) return;
if (index < 0 || !valid()) return;
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
) {
if (!valid()) return;
scrollTo(index);
await waitForMountedRow(key);
}
await waitForMountedRow(key, valid);
return;
}
await nextTick();
if (!valid()) return;
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
element?.scrollIntoView?.({ block: "nearest" });
if (!valid() || !element?.isConnected) return;
element.scrollIntoView?.({ block: "nearest" });
}
let revealRequest = 0;
/**
* A request stays valid only while it is the newest one, the row is still
* visible/enabled, the collection is open and the component is alive.
*/
function revealToken(key: ListBoxKey) {
const request = ++revealRequest;
return () =>
!disposing &&
request === revealRequest &&
!disabled.value &&
owner?.isOpen?.() !== false &&
eligible().some((item) => item.key === key);
}
/** Reveal a row without taking DOM focus (virtual focus / activedescendant). */
async function reveal(key: ListBoxKey) {
if (disposing || disabled.value) return;
if (!eligible().some((item) => item.key === key)) return;
const request = ++revealRequest;
const valid = revealToken(key);
if (!valid()) return;
lastFocused.value = key;
await revealRow(key);
// A newer request, filtering, close or unmount makes this one obsolete.
if (disposing || request !== revealRequest) return;
await revealRow(key, valid);
}
async function focus(key: ListBoxKey) {
if (
@@ -302,14 +345,17 @@ async function focus(key: ListBoxKey) {
const request = ++focusRequest;
lastFocused.value = key;
if (virtualFocus.value) {
const valid = revealToken(key);
if (!valid()) return;
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
const revealToken = ++revealRequest;
await revealRow(key);
if (disposing || revealToken !== revealRequest) return;
await revealRow(key, valid);
return;
}
await revealRow(key);
await revealRow(
key,
() => !disposing && !disabled.value && request === focusRequest,
);
if (disposing || request !== focusRequest || disabled.value) return;
const element = registry
.available()
@@ -612,10 +658,13 @@ defineExpose({
<template>
<component :is="as" ref="root" v-bind="rootAttrs()">
<slot v-if="!items" :item="undefined!" :index="-1" />
<template v-if="!items">
<!-- Static slots keep every member mounted (so text and selection
survive filtering); the empty channel is additive. -->
<slot v-if="visibleIsEmpty" name="empty" />
<slot :item="undefined!" :index="-1" />
</template>
<template v-else>
<!-- Filtered-empty still needs a visible channel; non-virtualized rows
keep their DOM and are only hidden by data-filtered. -->
<slot v-if="!visibleItems.length" name="empty" />
<div
v-if="virtualized"
@@ -139,6 +139,20 @@ export default defineComponent({
else context.restoreFocus();
}
});
/**
* Nested controls own their own press, focus and click. `[contenteditable]`
* matches the attribute alone so "", "true" and "plaintext-only" all count;
* explicit "false" opts out.
*/
const NESTED_INTERACTIVE =
'button, a[href], input, select, textarea, summary, [role="button"], ' +
'[role="link"], [role="menuitem"], [role="checkbox"], [role="radio"], ' +
'[role="switch"], [role="tab"], [role="option"], ' +
'[contenteditable]:not([contenteditable="false"])';
function nestedInteractive(target: EventTarget | null) {
const hit = (target as Element | null)?.closest?.(NESTED_INTERACTIVE);
return hit && hit !== element.value ? hit : undefined;
}
/**
* Native presses move focus to the pressed element (or body for a
* non-focusable row). Under virtual focus the composite's input must keep
@@ -149,16 +163,14 @@ export default defineComponent({
function keepInputFocus(event: MouseEvent | PointerEvent) {
if (!context.virtual() || event.defaultPrevented) return;
if (event instanceof MouseEvent && event.button !== 0) return;
const target = event.target as Element | null;
const nested = target?.closest?.(
'button, a, input, select, textarea, [contenteditable="true"]',
);
if (nested && nested !== element.value) return;
if (nestedInteractive(event.target)) return;
event.preventDefault();
}
function click(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value || context.readOnly.value)
return;
// A click that bubbled out of a nested control belongs to that control.
if (nestedInteractive(event.target)) return;
const select = new CustomEvent("select", {
cancelable: true,
detail: { key: props.id, originalEvent: event },
@@ -233,12 +245,11 @@ export default defineComponent({
hovered.value = false;
},
onPointerdown: (event: PointerEvent) => {
// The caller's cancellation must be read before our focus guard
// calls preventDefault, otherwise every row would look cancelled.
const cancelled = event.defaultPrevented;
keepInputFocus(event);
if (
!event.defaultPrevented &&
!disabled.value &&
event.button === 0
)
if (!cancelled && !disabled.value && event.button === 0)
pressed.value = true;
},
onMousedown: (event: MouseEvent) => {