feat(collection): add optional filtering and virtual focus for composite pickers

ComboBox and Autocomplete need two capabilities the collection protocol did not
express: filtering a collection by an external input value, and keeping DOM focus
in the composite's input while an active option is tracked for
aria-activedescendant.

Both are opt-in members on CollectionOwner plus optionId/reveal on the owned
collection. Standalone ListBox and Select provide none of them and keep their
previous behaviour: DOM focus still moves into the list, one roving tab stop, no
row filtering.

Filtered rows stay mounted with data-filtered (display:none) so their text and
accepted selection survive; only display, aria positions and keyboard navigation
see the visible subset. Under virtual focus the list never takes DOM focus,
never exposes a roving tab stop, and leaves keyboard handling to the composite;
reveal() scrolls a virtualized window and waits for the row to mount before the
composite reads its id.

Includes the playground verification page, a ten-case suite and the B02a section
of the migration report.
This commit is contained in:
maoyingjie
2026-10-25 14:53:49 +08:00
parent fa73cafd20
commit 1b972a78ba
11 changed files with 849 additions and 30 deletions
@@ -3,6 +3,12 @@
Base list-box item styles
========================================================================== */
/* Owner-filtered rows stay mounted (text and selection survive) but leave
display and keyboard navigation. */
.hv-list-box-item[data-filtered="true"] {
display: none;
}
.hv-list-box-item {
@apply relative flex min-h-9 w-full items-center justify-start gap-3 rounded-2xl px-2 py-1.5 outline-none no-highlight;
@@ -1,16 +1,35 @@
import type { ComputedRef, InjectionKey } from "vue";
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { CollectionKey } from "./keys";
export interface CollectionRecord {
key: CollectionKey;
text: string;
disabled: boolean;
}
/** Filtering and virtual focus are optional: absent means the previous behaviour. */
export interface CollectionView {
/**
* Filter over the full data set. Filtered-out records stay mounted and keep
* their text/selection, but leave display and keyboard navigation.
*/
filter?: (record: CollectionRecord) => boolean;
/** Keep DOM focus outside the collection and track `activeKey` instead. */
virtualFocus?: () => boolean;
/** Active key for virtual focus; the owning composite drives it. */
activeKey?: Ref<CollectionKey | undefined>;
}
export interface OwnedCollection {
items: () => CollectionRecord[];
focus: (edge: "first" | "last" | "selected") => Promise<void>;
/** Mounted DOM id of an option, for `aria-activedescendant`. */
optionId?: (key: CollectionKey) => string | undefined;
/**
* Make `key` the revealed row: scroll a virtualized window first, then wait
* for the row to mount. Never moves DOM focus.
*/
reveal?: (key: CollectionKey) => Promise<void>;
}
/** A field composite may own a ListBox, without adding another value store. */
export interface CollectionOwner {
export interface CollectionOwner extends CollectionView {
keys: ComputedRef<readonly CollectionKey[]>;
mode: ComputedRef<"single" | "multiple">;
disabled: ComputedRef<boolean>;
@@ -84,6 +84,10 @@ const disabled = useInheritedDisabled(
);
provide(disabledContextKey, disabled);
const dir = computed(() => props.dir ?? config?.dir.value ?? "ltr");
// Optional owner-driven view: filtering and virtual focus stay off unless the
// composite asks for them, so standalone ListBox and Select are unchanged.
const virtualFocus = computed(() => !!owner?.virtualFocus?.());
const ownerFilter = computed(() => owner?.filter);
const registry = useCollectionRegistry<ListBoxMember>();
const mounted = ref(false);
let disconnectOwner: (() => void) | undefined;
@@ -92,6 +96,8 @@ onMounted(() => {
if (owner)
disconnectOwner = owner.connect({
items: known,
optionId,
reveal,
focus: async (edge) => {
const available = eligible();
const key =
@@ -144,7 +150,16 @@ const known = () => {
}))
);
};
const eligible = () => known().filter((item) => !item.disabled);
/** Full data set with the owner filter applied: display and navigation only. */
const visibleKnown = () => {
const filter = ownerFilter.value;
const items = known();
return filter ? items.filter((item) => filter(item)) : items;
};
const visibleKeys = computed(
() => new Set(visibleKnown().map((item) => item.key)),
);
const eligible = () => visibleKnown().filter((item) => !item.disabled);
const blockedKeys = computed(() =>
known()
.filter((item) => item.disabled)
@@ -172,6 +187,7 @@ const lastFocused = ref<ListBoxKey>();
const pressed = ref<ListBoxKey>();
const keyboard = ref(true);
const active = computed(() => {
if (virtualFocus.value && owner?.activeKey) return owner.activeKey.value;
if (!mounted.value) return undefined;
const items = eligible();
return (
@@ -207,6 +223,37 @@ onBeforeUnmount(() => {
disposing = true;
focusRequest++;
});
/** Mounted DOM id of an option; undefined while a virtualized row is unmounted. */
function optionId(key: ListBoxKey): string | undefined {
const element = registry
.ordered()
.find((member) => member.key() === key)
?.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);
}
/** 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;
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();
}
async function focus(key: ListBoxKey) {
if (
disposing ||
@@ -216,16 +263,12 @@ async function focus(key: ListBoxKey) {
return;
const request = ++focusRequest;
lastFocused.value = key;
if (props.virtualized) {
const index = source.value.findIndex((item) => item.id === key);
const rowTop = index * props.rowHeight;
const element = root.value;
if (
element &&
(rowTop < element.scrollTop ||
rowTop + props.rowHeight > element.scrollTop + element.clientHeight)
)
scrollTo(index);
scrollRowIntoView(key);
if (virtualFocus.value) {
if (owner?.activeKey && owner.activeKey.value !== key)
owner.activeKey.value = key;
await nextTick();
return;
}
await nextTick();
if (disposing || request !== focusRequest || disabled.value) return;
@@ -274,6 +317,7 @@ let search = "",
let pendingSpace: ListBoxKey | undefined;
function keydown(event: KeyboardEvent) {
if (
virtualFocus.value ||
event.defaultPrevented ||
event.isComposing ||
event.keyCode === 229 ||
@@ -406,6 +450,7 @@ function keydown(event: KeyboardEvent) {
}
}
function keyup(event: KeyboardEvent) {
if (virtualFocus.value) return;
if (event.key !== " ") return;
const key = pendingSpace;
pendingSpace = undefined;
@@ -442,14 +487,18 @@ provide(listBoxKey, {
activate,
focus,
virtualized: () => props.virtualized,
virtual: () => virtualFocus.value,
visible: (key) => visibleKeys.value.has(key),
optionId,
restoreFocus,
position: (key) =>
props.virtualized && data.value
? {
index: data.value.findIndex((item) => item.key === key) + 1,
size: data.value.length,
}
: undefined,
position: (key) => {
if (!props.virtualized || !data.value) return undefined;
const items = ownerFilter.value ? visibleKnown() : data.value;
return {
index: items.findIndex((item) => item.key === key) + 1,
size: items.length,
};
},
});
function rootAttrs() {
if (mode.value === "single" && selection.keys.value.length > 1)
@@ -483,6 +532,7 @@ function rootAttrs() {
"aria-multiselectable":
mode.value === "none" ? undefined : mode.value === "multiple",
tabindex:
virtualFocus.value ||
disabled.value ||
(mounted.value &&
registry.available().some((member) => member.key() === active.value))
@@ -73,10 +73,16 @@ export default defineComponent({
const state = () => ({
isSelected: context.selected(props.id),
isDisabled: disabled.value,
isFocused: context.focused.value === props.id,
isFocusVisible:
context.focused.value === props.id &&
(context.keyboard.value || !!element.value?.matches(":focus-visible")),
// Under virtual focus the DOM focus stays in the composite's input, so the
// active key is what marks the row as focused.
isFocused: context.virtual()
? context.active.value === props.id
: context.focused.value === props.id,
isFocusVisible: context.virtual()
? context.keyboard.value && context.active.value === props.id
: context.focused.value === props.id &&
(context.keyboard.value ||
!!element.value?.matches(":focus-visible")),
isPressed:
(pressed.value || context.pressed.value === props.id) &&
!disabled.value,
@@ -149,6 +155,7 @@ export default defineComponent({
return () => {
const current = state();
const position = context.position(props.id);
const visible = context.visible(props.id);
const children = text.prepare(slots.default?.(current) ?? [], true);
return h(
props.as,
@@ -160,7 +167,12 @@ export default defineComponent({
variant: props.variant,
}).item(),
tabindex:
!disabled.value && context.active.value === props.id ? 0 : -1,
!disabled.value &&
!context.virtual() &&
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,
@@ -174,6 +186,7 @@ export default defineComponent({
text.describedBy(),
),
"data-slot": "list-box-item",
"data-filtered": visible ? undefined : true,
"data-disabled": disabled.value || undefined,
"data-selected": current.isSelected || undefined,
"data-focused": current.isFocused || undefined,
@@ -56,6 +56,11 @@ export interface ListBoxContext {
activate: (key: ListBoxKey, event: MouseEvent | KeyboardEvent) => void;
focus: (key: ListBoxKey) => Promise<void>;
virtualized: () => boolean;
/** Keep DOM focus outside the collection; only the active key moves. */
virtual: () => boolean;
/** Whether the owner filter currently shows this record. */
visible: (key: ListBoxKey) => boolean;
optionId: (key: ListBoxKey) => string | undefined;
restoreFocus: () => void;
position: (key: ListBoxKey) => { index: number; size: number } | undefined;
}
+243
View File
@@ -0,0 +1,243 @@
<script setup lang="ts">
/**
* B02a verification harness: a minimal combobox that consumes the optional
* owner protocol (filter + virtual focus). It proves the protocol; it is NOT
* the public ComboBox.
*/
import { computed, nextTick, provide, ref, shallowRef } from "vue";
import { ListBox, ListBoxItem } from "@heroui-vue/components";
import {
collectionOwnerKey,
type CollectionOwner,
type CollectionRecord,
type OwnedCollection,
} from "../../src/components/collection/owner";
import type { CollectionKey } from "../../src/components/collection/keys";
interface Option {
id: CollectionKey;
text: string;
disabled?: boolean;
}
const props = withDefaults(
defineProps<{
options?: readonly Option[];
/** When false the parent rejects every selection proposal. */
acceptSelection?: boolean;
filterEnabled?: boolean;
}>(),
{
options: () => [
{ id: "cat", text: "猫" },
{ id: "dog", text: "狗" },
{ id: "bird", text: "鸟" },
{ id: "fish", text: "鱼" },
{ id: "hamster", text: "仓鼠" },
],
acceptSelection: true,
filterEnabled: true,
},
);
const emit = defineEmits<{
"update:modelValue": [key: CollectionKey | null];
proposal: [key: CollectionKey | null];
}>();
const labelId = "b02a-label";
const listId = "b02a-list";
const input = ref<HTMLInputElement>();
const inputValue = ref("");
const accepted = ref<CollectionKey | null>(null);
const activeKey = ref<CollectionKey>();
const activeId = ref<string>();
const open = ref(false);
const composing = ref(false);
const collection = shallowRef<OwnedCollection>();
const records = computed<CollectionRecord[]>(() =>
props.options.map((option) => ({
key: option.id,
text: option.text,
disabled: !!option.disabled,
})),
);
/** Filtering affects display and navigation only; accepted values stay. */
function filterRecord(record: CollectionRecord) {
if (!props.filterEnabled) return true;
const needle = inputValue.value.trim();
return !needle || record.text.includes(needle);
}
const eligible = computed(() =>
records.value.filter((record) => !record.disabled && filterRecord(record)),
);
/** Read from the full data set: a filtered-out selection keeps its label. */
const acceptedText = computed(
() => records.value.find((item) => item.key === accepted.value)?.text ?? null,
);
const hiddenCount = computed(
() => records.value.filter((record) => !filterRecord(record)).length,
);
function request(keys: CollectionKey[]) {
const next = keys[0] ?? null;
emit("proposal", next);
if (!props.acceptSelection) return;
accepted.value = next;
const record = records.value.find((item) => item.key === next);
if (record) inputValue.value = record.text;
emit("update:modelValue", next);
}
const owner: CollectionOwner = {
keys: computed(() => (accepted.value === null ? [] : [accepted.value])),
mode: computed(() => "single" as const),
disabled: computed(() => false),
readOnly: computed(() => false),
disabledKeys: computed(() =>
records.value
.filter((record) => record.disabled)
.map((record) => record.key),
),
id: listId,
labelledBy: () => labelId,
ariaLabel: () => undefined,
request,
action: () => {
open.value = false;
},
leave: () => {
open.value = false;
},
connect: (next: OwnedCollection) => {
collection.value = next;
return () => {
if (collection.value === next) collection.value = undefined;
};
},
filter: filterRecord,
virtualFocus: () => true,
activeKey,
};
provide(collectionOwnerKey, owner);
async function setActive(key: CollectionKey | undefined) {
activeKey.value = key;
if (key === undefined) {
activeId.value = undefined;
return;
}
// Reveal first (mounts a virtualized row), then read the mounted id.
await collection.value?.reveal?.(key);
activeId.value = collection.value?.optionId?.(key);
}
function moveActive(delta: 1 | -1) {
const items = eligible.value;
if (!items.length) {
void setActive(undefined);
return;
}
const index = items.findIndex((item) => item.key === activeKey.value);
const next =
index < 0
? items[delta > 0 ? 0 : items.length - 1]
: items[(index + delta + items.length) % items.length];
void setActive(next.key);
}
function onInput() {
if (composing.value) return;
inputValue.value = input.value?.value ?? "";
open.value = true;
void setActive(eligible.value[0]?.key);
}
function keydown(event: KeyboardEvent) {
// IME: never confirm while composing (Safari reports keyCode 229).
if (event.isComposing || composing.value || event.keyCode === 229) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!open.value) open.value = true;
moveActive(event.key === "ArrowDown" ? 1 : -1);
return;
}
if (event.key === "Enter") {
event.preventDefault();
if (activeKey.value !== undefined) request([activeKey.value]);
open.value = false;
return;
}
if (event.key === "Escape" || event.key === "Tab") open.value = false;
}
function compositionStart() {
composing.value = true;
}
function compositionEnd() {
composing.value = false;
onInput();
void nextTick();
}
defineExpose({
inputValue,
accepted,
activeKey,
activeId,
open,
eligible: () => eligible.value,
hiddenCount: () => hiddenCount.value,
});
</script>
<template>
<div class="flex w-[256px] flex-col gap-1">
<label :id="labelId" class="text-sm font-medium" for="b02a-input">
动物(B02a 协议验证)
</label>
<input
id="b02a-input"
ref="input"
:value="inputValue"
aria-autocomplete="list"
:aria-activedescendant="activeId"
:aria-controls="listId"
:aria-expanded="open"
aria-labelledby="b02a-label"
autocomplete="off"
class="rounded-field border border-field-border bg-field px-3 py-2 text-sm"
data-test="harness-input"
role="combobox"
type="text"
@compositionend="compositionEnd"
@compositionstart="compositionStart"
@input="onInput"
@keydown="keydown"
/>
<p class="text-xs text-muted" data-test="accepted">
已选:{{ acceptedText ?? "无" }}
</p>
<p class="text-xs text-muted" data-test="hidden-count">
已隐藏:{{ hiddenCount }}
</p>
<div v-show="open" data-test="popover">
<ListBox :id="listId">
<ListBoxItem
v-for="option in options"
:id="option.id"
:key="option.id"
:is-disabled="option.disabled"
>
{{ option.text }}
</ListBoxItem>
</ListBox>
</div>
</div>
</template>