fix(collection): close the six review gaps in filtering and virtual focus

- Keep the composite input focused on real pointer presses: cancel the default
  focus transfer for plain row presses only, leaving nested controls and already
  cancelled callers alone.
- Drive the virtual window, total height, reveal index and aria positions from
  the visible subset, and render the empty channel when filtering removes every
  row. Non-virtualized rows stay mounted and are hidden, so their text and
  accepted selection survive.
- Scroll mounted rows for reveal/focus outside virtualization, wait for a
  virtualized row to mount (frame-based, bounded), and drop reveal requests that
  filtering, closing or unmounting made obsolete.
- Stop overwriting caller `hidden`: mergeProps deletes an earlier key when a
  later value is undefined, so the filter now only adds `hidden` when the caller
  did not set it.
- Share keyboard modality through an optional `keyboardIntent` ref so a pointer
  press no longer leaves the active row without data-focus-visible.
- Give the verification harness instance-unique ids and derive
  aria-activedescendant from open state, mounted id and filter visibility.

Adds the reviewer probe plus eight regressions, and a virtualized harness
instance for the browser smoke of filtering plus window/height/positions.
This commit is contained in:
maoyingjie
2026-10-25 16:28:33 +08:00
parent 1b972a78ba
commit 50ad3ca180
9 changed files with 511 additions and 55 deletions
@@ -16,6 +16,12 @@ export interface CollectionView {
virtualFocus?: () => boolean;
/** Active key for virtual focus; the owning composite drives it. */
activeKey?: Ref<CollectionKey | undefined>;
/**
* Keyboard modality shared with the composite that holds DOM focus. The
* collection clears it on pointer presses; the composite sets it on keys, so
* there is one source instead of a second copy.
*/
keyboardIntent?: Ref<boolean>;
}
export interface OwnedCollection {
items: () => CollectionRecord[];
@@ -185,7 +185,8 @@ const selection = useCollectionSelection({
const focused = ref<ListBoxKey>();
const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
const keyboard = ref(true);
// Pointer presses clear keyboard intent; the composite sets it again on keys.
const keyboard = owner?.keyboardIntent ?? ref(true);
const active = computed(() => {
if (virtualFocus.value && owner?.activeKey) return owner.activeKey.value;
if (!mounted.value) return undefined;
@@ -197,7 +198,18 @@ const active = computed(() => {
items[0]?.key
);
});
const source = computed(() => (props.items ? [...props.items] : []));
/**
* Items as the caller passed them, restricted to the visible subset. The full
* data set stays available through `known()` for text and accepted values.
*/
const visibleItems = computed(() => {
const items = props.items ? [...props.items] : [];
const filter = ownerFilter.value;
if (!items.length || !filter) return items;
const visible = visibleKeys.value;
return items.filter((item) => visible.has(item.id));
});
const source = computed(() => visibleItems.value);
// VueUse owns measurement, scroll range and cleanup; one logical collection
// remains available for select-all/typeahead even while most rows are unmounted.
const {
@@ -231,28 +243,54 @@ function optionId(key: ListBoxKey): string | undefined {
?.element();
return element?.id || undefined;
}
function scrollRowIntoView(key: ListBoxKey) {
if (!props.virtualized) return;
const index = source.value.findIndex((item) => item.id === key);
if (index < 0) return;
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
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) {
for (let attempt = 0; attempt < 3; attempt++) {
if (registry.ordered().some((member) => member.key() === key)) return;
await nextFrame();
}
}
/**
* Bring a row into view without taking DOM focus. Virtualized lists move the
* 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) {
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
if (index < 0) return;
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
await waitForMountedRow(key);
return;
}
await nextTick();
const element = registry
.ordered()
.find((member) => member.key() === key)
?.element();
element?.scrollIntoView?.({ block: "nearest" });
}
let revealRequest = 0;
/** 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;
lastFocused.value = key;
scrollRowIntoView(key);
// Wait one tick so a virtualized row is mounted before the consumer reads
// its element id for aria-activedescendant.
await nextTick();
await revealRow(key);
// A newer request, filtering, close or unmount makes this one obsolete.
if (disposing || request !== revealRequest) return;
}
async function focus(key: ListBoxKey) {
if (
@@ -263,14 +301,15 @@ async function focus(key: ListBoxKey) {
return;
const request = ++focusRequest;
lastFocused.value = key;
scrollRowIntoView(key);
if (virtualFocus.value) {
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
await nextTick();
const revealToken = ++revealRequest;
await revealRow(key);
if (disposing || revealToken !== revealRequest) return;
return;
}
await nextTick();
await revealRow(key);
if (disposing || request !== focusRequest || disabled.value) return;
const element = registry
.available()
@@ -493,9 +532,9 @@ provide(listBoxKey, {
restoreFocus,
position: (key) => {
if (!props.virtualized || !data.value) return undefined;
const items = ownerFilter.value ? visibleKnown() : data.value;
const items = visibleItems.value;
return {
index: items.findIndex((item) => item.key === key) + 1,
index: items.findIndex((item) => item.id === key) + 1,
size: items.length,
};
},
@@ -574,24 +613,28 @@ defineExpose({
<template>
<component :is="as" ref="root" v-bind="rootAttrs()">
<slot v-if="!items" :item="undefined!" :index="-1" />
<slot v-else-if="!items.length" name="empty" />
<div
v-else-if="virtualized"
v-bind="wrapperProps"
role="presentation"
data-slot="list-box-virtual-content"
>
<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-for="entry in windowItems"
:key="entry.data.id"
v-if="virtualized"
v-bind="wrapperProps"
role="presentation"
:style="{ height: `${rowHeight}px` }"
data-slot="list-box-virtual-content"
>
<slot :item="entry.data" :index="entry.index" />
<div
v-for="entry in windowItems"
:key="entry.data.id"
role="presentation"
:style="{ height: `${rowHeight}px` }"
>
<slot :item="entry.data" :index="entry.index" />
</div>
</div>
</div>
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
<template v-else v-for="(item, index) in items" :key="item.id">
<slot :item="item" :index="index" />
</template>
</template>
</component>
</template>
@@ -139,6 +139,23 @@ export default defineComponent({
else context.restoreFocus();
}
});
/**
* Native presses move focus to the pressed element (or body for a
* non-focusable row). Under virtual focus the composite's input must keep
* focus, so the default focus transfer is cancelled here — but only for a
* plain row press: nested controls keep their own focus behaviour and a
* caller that already cancelled is respected.
*/
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;
event.preventDefault();
}
function click(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || disabled.value || context.readOnly.value)
return;
@@ -156,6 +173,10 @@ export default defineComponent({
const current = state();
const position = context.position(props.id);
const visible = context.visible(props.id);
// Never emit an undefined-valued key over the caller's attribute:
// mergeProps removes the earlier key when a later value is undefined.
const hideFiltered =
!visible && (attrs as Record<string, unknown>).hidden === undefined;
const children = text.prepare(slots.default?.(current) ?? [], true);
return h(
props.as,
@@ -172,7 +193,6 @@ export default defineComponent({
context.active.value === props.id
? 0
: -1,
hidden: visible ? undefined : true,
"aria-selected":
context.mode.value === "none" ? undefined : current.isSelected,
"aria-disabled": disabled.value || undefined,
@@ -186,6 +206,10 @@ export default defineComponent({
text.describedBy(),
),
"data-slot": "list-box-item",
// Filtered rows stay mounted and are hidden, not removed, so their
// text and accepted selection survive. `hidden` is only added when the
// caller did not set it; the stylesheet also hides data-filtered.
...(hideFiltered ? { hidden: true } : {}),
"data-filtered": visible ? undefined : true,
"data-disabled": disabled.value || undefined,
"data-selected": current.isSelected || undefined,
@@ -209,6 +233,7 @@ export default defineComponent({
hovered.value = false;
},
onPointerdown: (event: PointerEvent) => {
keepInputFocus(event);
if (
!event.defaultPrevented &&
!disabled.value &&
@@ -216,6 +241,11 @@ export default defineComponent({
)
pressed.value = true;
},
onMousedown: (event: MouseEvent) => {
// Chromium transfers focus on mousedown even when pointerdown was
// cancelled, so the same rule is applied to both events.
keepInputFocus(event);
},
}),
children,
);
+81 -16
View File
@@ -4,7 +4,15 @@
* owner protocol (filter + virtual focus). It proves the protocol; it is NOT
* the public ComboBox.
*/
import { computed, nextTick, provide, ref, shallowRef } from "vue";
import {
computed,
nextTick,
provide,
ref,
shallowRef,
useId,
watchEffect,
} from "vue";
import { ListBox, ListBoxItem } from "@heroui-vue/components";
import {
collectionOwnerKey,
@@ -26,6 +34,8 @@ const props = withDefaults(
/** When false the parent rejects every selection proposal. */
acceptSelection?: boolean;
filterEnabled?: boolean;
/** Render the collection through ListBox's virtualized items mode. */
virtualized?: boolean;
}>(),
{
options: () => [
@@ -37,6 +47,7 @@ const props = withDefaults(
],
acceptSelection: true,
filterEnabled: true,
virtualized: false,
},
);
@@ -45,8 +56,11 @@ const emit = defineEmits<{
proposal: [key: CollectionKey | null];
}>();
const labelId = "b02a-label";
const listId = "b02a-list";
// Instance-unique ids: several harnesses coexist on the verification page.
const uid = useId();
const labelId = `${uid}-label`;
const inputId = `${uid}-input`;
const listId = `${uid}-list`;
const input = ref<HTMLInputElement>();
const inputValue = ref("");
const accepted = ref<CollectionKey | null>(null);
@@ -54,6 +68,8 @@ const activeKey = ref<CollectionKey>();
const activeId = ref<string>();
const open = ref(false);
const composing = ref(false);
/** Shared modality: ListBox clears it on pointer presses, keys restore it. */
const keyboardIntent = ref(true);
const collection = shallowRef<OwnedCollection>();
const records = computed<CollectionRecord[]>(() =>
@@ -108,9 +124,9 @@ const owner: CollectionOwner = {
labelledBy: () => labelId,
ariaLabel: () => undefined,
request,
action: () => {
open.value = false;
},
// The harness stays open after a pick so the active-key/id sync is observable;
// closing behaviour belongs to the real ComboBox.
action: () => {},
leave: () => {
open.value = false;
},
@@ -123,18 +139,42 @@ const owner: CollectionOwner = {
filter: filterRecord,
virtualFocus: () => true,
activeKey,
keyboardIntent,
};
provide(collectionOwnerKey, owner);
/**
* The id is only usable when the list is open and the row is mounted, visible
* and not filtered out; otherwise the attribute must disappear.
*/
function resolveActiveId(): string | undefined {
if (!open.value) return undefined;
const key = activeKey.value;
if (key === undefined) return undefined;
const id = collection.value?.optionId?.(key);
if (!id) return undefined;
const element =
typeof document === "undefined" ? null : document.getElementById(id);
if (!element || element.hasAttribute("data-filtered")) return undefined;
return id;
}
// One derivation for every path that can move the active key: keyboard,
// pointer clicks inside the list, filtering and open/close.
watchEffect(() => {
void eligible.value.length;
void collection.value;
activeId.value = resolveActiveId();
});
async function setActive(key: CollectionKey | undefined) {
activeKey.value = key;
if (key === undefined) {
activeId.value = undefined;
return;
if (key !== undefined) {
// Reveal first (mounts a virtualized row); the effect above re-reads the id
// once the row is actually mounted.
await collection.value?.reveal?.(key);
}
// Reveal first (mounts a virtualized row), then read the mounted id.
await collection.value?.reveal?.(key);
activeId.value = collection.value?.optionId?.(key);
activeId.value = resolveActiveId();
}
function moveActive(delta: 1 | -1) {
@@ -161,6 +201,7 @@ function onInput() {
function keydown(event: KeyboardEvent) {
// IME: never confirm while composing (Safari reports keyCode 229).
if (event.isComposing || composing.value || event.keyCode === 229) return;
keyboardIntent.value = true;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!open.value) open.value = true;
@@ -199,18 +240,18 @@ defineExpose({
<template>
<div class="flex w-[256px] flex-col gap-1">
<label :id="labelId" class="text-sm font-medium" for="b02a-input">
<label :id="labelId" class="text-sm font-medium" :for="inputId">
动物(B02a 协议验证)
</label>
<input
id="b02a-input"
:id="inputId"
ref="input"
:value="inputValue"
aria-autocomplete="list"
:aria-activedescendant="activeId"
:aria-controls="listId"
:aria-expanded="open"
aria-labelledby="b02a-label"
:aria-labelledby="labelId"
autocomplete="off"
class="rounded-field border border-field-border bg-field px-3 py-2 text-sm"
data-test="harness-input"
@@ -228,7 +269,28 @@ defineExpose({
已隐藏:{{ hiddenCount }}
</p>
<div v-show="open" data-test="popover">
<ListBox :id="listId">
<ListBox
v-if="virtualized"
:id="listId"
:items="options"
:row-height="32"
:virtualized="true"
class="max-h-[128px] overflow-y-auto"
>
<template #default="{ item }">
<ListBoxItem
:id="item.id"
:key="item.id"
:is-disabled="item.disabled"
>
{{ item.text }}
</ListBoxItem>
</template>
<template #empty>
<p data-test="empty">没有匹配项</p>
</template>
</ListBox>
<ListBox v-else :id="listId">
<ListBoxItem
v-for="option in options"
:id="option.id"
@@ -237,6 +299,9 @@ defineExpose({
>
{{ option.text }}
</ListBoxItem>
<template #empty>
<p data-test="empty">没有匹配项</p>
</template>
</ListBox>
</div>
</div>