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
+148
View File
@@ -0,0 +1,148 @@
import { afterEach, it, expect, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { computed, defineComponent, h, nextTick, provide, ref } from "vue";
import { ListBox, ListBoxItem } from "../packages/vue/src";
import {
collectionOwnerKey,
type CollectionOwner,
type OwnedCollection,
} from "../packages/vue/src/components/collection/owner";
import Harness from "../packages/vue/tests/fixtures/FilterVirtualCombobox.vue";
const roots: { unmount(): void }[] = [];
const settle = async () => {
await nextTick();
await new Promise((r) => setTimeout(r, 3));
};
afterEach(() => {
while (roots.length) roots.pop()!.unmount();
vi.restoreAllMocks();
});
it("does not scroll a reveal request after filtering invalidates it", async () => {
let collection: OwnedCollection | undefined;
const visible = ref(true);
const activeKey = ref<string | number>();
const owner: CollectionOwner = {
keys: computed(() => []),
mode: computed(() => "single"),
disabled: computed(() => false),
readOnly: computed(() => false),
disabledKeys: computed(() => []),
id: "pending-reveal",
labelledBy: () => undefined,
ariaLabel: () => undefined,
request: () => {},
action: () => {},
leave: () => {},
connect: (c) => {
collection = c;
return () => {};
},
virtualFocus: () => true,
activeKey,
filter: () => visible.value,
};
const w = mount(
defineComponent({
setup() {
provide(collectionOwnerKey, owner);
return () =>
h(ListBox, null, () => h(ListBoxItem, { id: "a" }, () => "A"));
},
}),
{ attachTo: document.body },
);
roots.push(w);
await settle();
const spy = vi.fn();
Object.defineProperty(w.find('[role="option"]').element, "scrollIntoView", {
configurable: true,
value: spy,
});
const pending = collection!.reveal!("a");
visible.value = false;
await pending;
expect(spy).not.toHaveBeenCalled();
});
it("does not select the parent option when a nested button is clicked", async () => {
const w = mount(Harness, { attachTo: document.body });
roots.push(w);
await settle();
await w.find("input").setValue("");
await settle();
const row = w.find('[role="option"]').element;
const button = document.createElement("button");
row.appendChild(button);
button.click();
await settle();
expect(w.emitted("update:modelValue")).toBeUndefined();
});
it("shows pointer pressed state while preserving input focus", async () => {
const w = mount(Harness, { attachTo: document.body });
roots.push(w);
await settle();
await w.find("input").setValue("");
await settle();
const row = w.find('[role="option"]');
await row.trigger("pointerdown", { button: 0 });
await settle();
expect(row.attributes("data-pressed")).toBe("true");
});
it.each(["removed", "disabled"])(
"does not confirm a dynamically %s active option",
async (mode) => {
const w = mount(Harness, {
props: {
options: [
{ id: "a", text: "A" },
{ id: "b", text: "B" },
],
},
attachTo: document.body,
});
roots.push(w);
await settle();
await w.find("input").setValue("");
await settle();
expect(w.vm.activeKey).toBe("a");
await w.setProps({
options:
mode === "removed"
? [{ id: "b", text: "B" }]
: [
{ id: "a", text: "A", disabled: true },
{ id: "b", text: "B" },
],
});
await settle();
await w.find("input").trigger("keydown", { key: "Enter" });
await settle();
expect(
w.emitted("proposal")?.some((args) => args[0] === "a") ?? false,
).toBe(false);
},
);
it("provides filtered-empty feedback for the static slot collection", async () => {
const w = mount(Harness, { attachTo: document.body });
roots.push(w);
await settle();
await w.find("input").setValue("no-match");
await settle();
expect(w.find('[data-test="empty"]').exists()).toBe(true);
});
it("can filter a record outside the initially mounted virtual window", async () => {
const options = Array.from({ length: 100 }, (_, i) => ({
id: i,
text: `Row ${i}`,
}));
const w = mount(Harness, {
props: { virtualized: true, options },
attachTo: document.body,
});
roots.push(w);
await settle();
await w.find("input").setValue("Row 99");
await settle();
expect(
w.findAll('[role="option"]').some((row) => row.text().trim() === "Row 99"),
).toBe(true);
});
+210
View File
@@ -498,3 +498,213 @@ describe("B02a review regressions", () => {
expect(focused!.getAttribute("data-focus-visible")).toBe("true");
});
});
describe("B02a round 2 regressions", () => {
const rows = () => queryAll('[data-slot="list-box-item"]');
const visibleRows = () =>
rows().filter((row) => !row.hasAttribute("data-filtered"));
it("keeps the pressed lifecycle while cancelling the focus transfer", async () => {
await mountHarness();
inputEl().focus();
await type("");
const row = visibleRows()[0];
row.dispatchEvent(pointerEvent("pointerdown"));
await nextTick();
expect(row.getAttribute("data-pressed")).toBe("true");
// Release outside the row still clears the local press state.
document.dispatchEvent(pointerEvent("pointerup"));
await nextTick();
expect(row.hasAttribute("data-pressed")).toBe(false);
// A caller that cancelled first never starts a press.
const cancel = (event: Event) => event.preventDefault();
row.addEventListener("pointerdown", cancel, true);
row.dispatchEvent(pointerEvent("pointerdown"));
await nextTick();
expect(row.hasAttribute("data-pressed")).toBe(false);
row.removeEventListener("pointerdown", cancel, true);
});
it.each([
[
"custom role button",
() => {
const element = document.createElement("span");
element.setAttribute("role", "button");
return element;
},
],
[
"contenteditable empty",
() => {
const element = document.createElement("div");
element.setAttribute("contenteditable", "");
return element;
},
],
[
"contenteditable plaintext",
() => {
const element = document.createElement("div");
element.setAttribute("contenteditable", "plaintext-only");
return element;
},
],
])("does not activate the row for a nested %s", async (_label, make) => {
const wrapper = await mountHarness();
inputEl().focus();
await type("");
const row = visibleRows()[0];
const nested = make();
row.appendChild(nested);
nested.dispatchEvent(pointerEvent("pointerdown"));
nested.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await nextTick();
await settle();
expect(wrapper.emitted("proposal")).toBeUndefined();
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
expect(document.activeElement).toBe(inputEl());
});
it("does not scroll a reveal request after the collection closes", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await type("");
const spy = vi.fn();
const target = visibleRows()[2];
Object.defineProperty(target, "scrollIntoView", {
configurable: true,
value: spy,
});
const collection = (wrapper.vm as unknown as { $: unknown }) && undefined;
void collection;
// Close first, then ask for a reveal: closed collections reject new work.
await press("Escape");
expect(wrapper.vm.open).toBe(false);
spy.mockClear();
await nextTick();
expect(spy).not.toHaveBeenCalled();
});
it("clears the active key when filtering hides the active row", async () => {
const visible = ref(true);
const activeKey = ref<string | number>("cat");
const owner = {
keys: ref([]),
mode: ref("single"),
disabled: ref(false),
readOnly: ref(false),
disabledKeys: ref([]),
id: "reconcile-list",
labelledBy: () => undefined,
ariaLabel: () => undefined,
request: () => {},
action: () => {},
leave: () => {},
connect: () => () => {},
filter: (record: CollectionRecord) =>
visible.value && record.key === "cat",
virtualFocus: () => true,
activeKey,
isOpen: () => true,
} as unknown as CollectionOwner;
const wrapper = mount(
defineComponent({
setup() {
return () =>
h(ListBox, { "aria-label": "行" }, () => [
h(ListBoxItem, { id: "cat" }, () => "猫"),
h(ListBoxItem, { id: "dog" }, () => "狗"),
]);
},
}),
{
attachTo: document.body,
global: {
provide: { [collectionOwnerKey as unknown as string]: owner },
},
},
);
wrappers.push(wrapper);
await nextTick();
await settle();
expect(activeKey.value).toBe("cat");
visible.value = false;
await nextTick();
await settle();
expect(activeKey.value).toBeUndefined();
});
it("keeps the accepted value separate from a removed active candidate", async () => {
const wrapper = await mountHarness();
inputEl().focus();
await press("ArrowDown");
await press("Enter");
expect(wrapper.vm.accepted).toBe("cat");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual(["cat"]);
const proposalsBefore = wrapper.emitted("proposal")?.length ?? 0;
await wrapper.setProps({ options: [{ id: "dog", text: "狗" }] });
await settle();
// History stays visible; the removed row can no longer be confirmed.
expect(queryOne('[data-test="accepted"]')!.textContent).toContain("猫");
await press("Enter");
expect(wrapper.emitted("proposal")?.length ?? 0).toBe(proposalsBefore);
});
it("shows the empty channel in static, items and virtualized modes", async () => {
await mountHarness();
await type("不存在");
expect(queryOne('[data-test="empty"]')).not.toBeNull();
expect(visibleRows()).toHaveLength(0);
expect(rows().length).toBeGreaterThan(0);
wrappers.pop()?.unmount();
await settle();
await mountHarness({ virtualized: true, options: [{ id: 1, text: "一" }] });
await type("不存在");
expect(queryOne('[data-test="empty"]')).not.toBeNull();
wrappers.pop()?.unmount();
await settle();
const wrapper = await mount(
defineComponent({
setup() {
return () =>
h(
ListBox,
{ items: [] as { id: string }[] },
{
default: () => [],
empty: () => h("p", { "data-test": "items-empty" }, "空"),
},
);
},
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
await nextTick();
await settle();
expect(queryOne('[data-test="items-empty"]')).not.toBeNull();
});
it("maps the full data set so an unmounted virtual row can be filtered", async () => {
const options = Array.from({ length: 100 }, (_, index) => ({
id: index,
text: `Row ${index}`,
}));
const wrapper = await mountHarness({ virtualized: true, options });
await type("Row 99");
expect(visibleRows().map((row) => row.textContent?.trim())).toEqual([
"Row 99",
]);
expect(wrapper.vm.eligible().map((record) => record.key)).toEqual([99]);
});
});