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:
@@ -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) => {
|
||||
|
||||
+42
-12
@@ -64,12 +64,16 @@ const listId = `${uid}-list`;
|
||||
const input = ref<HTMLInputElement>();
|
||||
const inputValue = ref("");
|
||||
const accepted = ref<CollectionKey | null>(null);
|
||||
const acceptedLabel = ref<string | null>(null);
|
||||
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);
|
||||
/** Real constrained scroll owner for the virtualized instance. */
|
||||
const rowHeight = 36;
|
||||
const viewportStyle = `max-height: ${rowHeight * 4}px; overflow-y: auto;`;
|
||||
const collection = shallowRef<OwnedCollection>();
|
||||
|
||||
const records = computed<CollectionRecord[]>(() =>
|
||||
@@ -91,23 +95,48 @@ 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,
|
||||
/**
|
||||
* ListBox `items` schema. Every record carries its own textValue so the full
|
||||
* data set can filter rows that were never mounted in a virtual window.
|
||||
*/
|
||||
const listItems = computed(() =>
|
||||
props.options.map((option) => ({
|
||||
id: option.id,
|
||||
textValue: option.text,
|
||||
isDisabled: !!option.disabled,
|
||||
})),
|
||||
);
|
||||
|
||||
/** Read from the full data set: a filtered-out selection keeps its label. */
|
||||
const acceptedText = computed(() => {
|
||||
if (accepted.value === null) return null;
|
||||
// An accepted value survives its row being removed or filtered out; it is
|
||||
// history, not the active candidate.
|
||||
const record = records.value.find((item) => item.key === accepted.value);
|
||||
return record?.text ?? acceptedLabel.value ?? String(accepted.value);
|
||||
});
|
||||
|
||||
const hiddenCount = computed(
|
||||
() => records.value.filter((record) => !filterRecord(record)).length,
|
||||
);
|
||||
|
||||
function request(keys: CollectionKey[]) {
|
||||
function request(keys: CollectionKey[]): boolean {
|
||||
const next = keys[0] ?? null;
|
||||
// Confirm only what is still a real candidate: a row removed, disabled or
|
||||
// filtered out since it became active cannot be submitted.
|
||||
if (next !== null) {
|
||||
const candidate = eligible.value.find((record) => record.key === next);
|
||||
if (!open.value || !candidate) return false;
|
||||
}
|
||||
emit("proposal", next);
|
||||
if (!props.acceptSelection) return;
|
||||
if (!props.acceptSelection) return false;
|
||||
accepted.value = next;
|
||||
const record = records.value.find((item) => item.key === next);
|
||||
// Remember the label: history outlives the row leaving the collection.
|
||||
acceptedLabel.value = record?.text ?? null;
|
||||
if (record) inputValue.value = record.text;
|
||||
emit("update:modelValue", next);
|
||||
return true;
|
||||
}
|
||||
|
||||
const owner: CollectionOwner = {
|
||||
@@ -140,6 +169,7 @@ const owner: CollectionOwner = {
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
keyboardIntent,
|
||||
isOpen: () => open.value,
|
||||
};
|
||||
provide(collectionOwnerKey, owner);
|
||||
|
||||
@@ -210,8 +240,8 @@ function keydown(event: KeyboardEvent) {
|
||||
}
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (activeKey.value !== undefined) request([activeKey.value]);
|
||||
open.value = false;
|
||||
if (activeKey.value !== undefined && request([activeKey.value]))
|
||||
open.value = false;
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape" || event.key === "Tab") open.value = false;
|
||||
@@ -272,18 +302,18 @@ defineExpose({
|
||||
<ListBox
|
||||
v-if="virtualized"
|
||||
:id="listId"
|
||||
:items="options"
|
||||
:row-height="32"
|
||||
:items="listItems"
|
||||
:row-height="rowHeight"
|
||||
:virtualized="true"
|
||||
class="max-h-[128px] overflow-y-auto"
|
||||
:style="viewportStyle"
|
||||
>
|
||||
<template #default="{ item }">
|
||||
<ListBoxItem
|
||||
:id="item.id"
|
||||
:key="item.id"
|
||||
:is-disabled="item.disabled"
|
||||
:is-disabled="item.isDisabled"
|
||||
>
|
||||
{{ item.text }}
|
||||
{{ item.textValue }}
|
||||
</ListBoxItem>
|
||||
</template>
|
||||
<template #empty>
|
||||
|
||||
Reference in New Issue
Block a user