Files
heroui-vue/tests/list-box.test.ts
T

474 lines
20 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { createSSRApp, defineComponent, h, ref } from "vue";
import { renderToString } from "@vue/server-renderer";
import {
ListBox,
ListBoxItem,
ListBoxItemIndicator,
ListBoxSection,
Label,
Description,
Header,
Fieldset,
} from "../packages/vue/src";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((wrapper) => wrapper.unmount());
document.body.innerHTML = "";
});
function fixture(template: string, setup = () => ({})) {
const wrapper = mount(
defineComponent({
components: {
ListBox,
ListBoxItem,
ListBoxItemIndicator,
ListBoxSection,
Label,
Description,
Header,
Fieldset,
},
setup,
template,
}),
{ attachTo: document.body },
);
wrappers.push(wrapper);
return wrapper;
}
const options =
'<ListBoxItem :id="0" text-value="Émma"><Label>Emma</Label><Description>emma@example.com</Description><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="0" text-value="Fred"><Label>Fred</Label><ListBoxItemIndicator/></ListBoxItem><ListBoxItem id="disabled" is-disabled><Label>Disabled</Label></ListBoxItem><ListBoxItem id="last" text-value="Martha"><Label>Martha</Label></ListBoxItem>';
const option = (wrapper: ReturnType<typeof mount>, index: number) =>
wrapper.findAll<HTMLElement>('[role="option"]')[index];
describe("ListBox public behavior", () => {
it("retains the last Tab entry after blur and combines native focus-visible with local modality", async () => {
const wrapper = fixture(
`<div><ListBox>${options}</ListBox><button>Outside</button></div>`,
);
await option(wrapper, 1).trigger("pointerdown", { button: 0 });
option(wrapper, 1).element.focus();
await flushPromises();
wrapper.get("button").element.focus();
await flushPromises();
expect(option(wrapper, 1).attributes("tabindex")).toBe("0");
expect(option(wrapper, 0).attributes("tabindex")).toBe("-1");
expect(option(wrapper, 1).attributes("data-focused")).toBeUndefined();
option(wrapper, 1).element.focus();
await flushPromises();
expect(option(wrapper, 1).element.matches(":focus-visible")).toBe(true);
expect(option(wrapper, 1).attributes("data-focus-visible")).toBe("true");
});
it("hides selection in none mode, keeps item variants independent and leaves modified Enter alone", async () => {
const wrapper = fixture(
`<ListBox selection-mode="none" variant="danger" :default-value="['last']">${options}</ListBox>`,
);
option(wrapper, 0).element.focus();
expect(option(wrapper, 3).attributes("data-selected")).toBeUndefined();
expect(option(wrapper, 0).classes()).toContain("hv-list-box-item--default");
await option(wrapper, 0).trigger("keydown", {
key: "Enter",
ctrlKey: true,
});
expect(wrapper.getComponent(ListBox).emitted("action")).toBeUndefined();
await option(wrapper, 0).trigger("keydown", { key: "Enter" });
expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0]]);
});
it("holds keyboard pressed state, activates Space on release once and respects keyup cancellation", async () => {
const cancelled = ref(false);
const wrapper = fixture(
`<ListBox @keyup="cancelled && $event.preventDefault()">${options}</ListBox>`,
() => ({ cancelled }),
);
option(wrapper, 0).element.focus();
await option(wrapper, 0).trigger("keydown", { key: " " });
expect(option(wrapper, 0).attributes("data-pressed")).toBe("true");
expect(wrapper.getComponent(ListBox).emitted("action")).toBeUndefined();
await option(wrapper, 0).trigger("keydown", { key: " ", repeat: true });
await option(wrapper, 0).trigger("keyup", { key: " " });
expect(option(wrapper, 0).attributes("data-pressed")).toBeUndefined();
expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0]]);
cancelled.value = true;
await flushPromises();
await option(wrapper, 0).trigger("keydown", { key: " " });
await option(wrapper, 0).trigger("keyup", { key: " " });
expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0]]);
expect(option(wrapper, 0).attributes("data-pressed")).toBeUndefined();
});
it("keeps the current prefix match while typing a word and cycles repeated initials", async () => {
const wrapper = fixture(
'<ListBox><ListBoxItem id="a" text-value="Liam Smith">Liam Smith</ListBoxItem><ListBoxItem id="b" text-value="Liam Jones">Liam Jones</ListBoxItem><ListBoxItem id="c" text-value="Emma">Emma</ListBoxItem></ListBox>',
);
option(wrapper, 2).element.focus();
for (const key of ["l", "i", "a", "m"])
await wrapper.get('[role="listbox"]').trigger("keydown", { key });
expect(document.activeElement).toBe(option(wrapper, 0).element);
// A new repeated-initial search cycles, rather than searching for "ll".
vi.spyOn(Date, "now").mockReturnValue(Date.now() + 2000);
try {
await option(wrapper, 0).trigger("keydown", { key: "l" });
expect(document.activeElement).toBe(option(wrapper, 1).element);
await option(wrapper, 1).trigger("keydown", { key: "l" });
expect(document.activeElement).toBe(option(wrapper, 0).element);
} finally {
vi.restoreAllMocks();
}
});
it("keeps typed keys, selection aliases and generated DOM ids distinct", async () => {
const wrapper = fixture(
`<ListBox :default-selected-keys="[0]" selection-mode="multiple" aria-label="People">${options}</ListBox>`,
);
await flushPromises();
expect(option(wrapper, 0).attributes("aria-selected")).toBe("true");
expect(option(wrapper, 1).attributes("aria-selected")).toBe("false");
await option(wrapper, 1).trigger("click");
expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([
[[0, "0"]],
]);
expect(wrapper.getComponent(ListBox).emitted("selectionChange")).toEqual([
[[0, "0"]],
]);
expect(option(wrapper, 0).attributes("id")).not.toBe("0");
expect(option(wrapper, 0).attributes("id")).not.toBe(
option(wrapper, 1).attributes("id"),
);
expect(option(wrapper, 0).attributes("aria-labelledby")).toBe(
option(wrapper, 0).get('[data-slot="label"]').attributes("id"),
);
expect(option(wrapper, 0).attributes("aria-describedby")).toBe(
option(wrapper, 0).get('[data-slot="description"]').attributes("id"),
);
});
it("restores controlled selection after rejection and retries identical proposals", async () => {
const wrapper = fixture(
`<ListBox :model-value="[0]" selection-mode="multiple">${options}</ListBox>`,
);
await option(wrapper, 1).trigger("click");
await option(wrapper, 1).trigger("click");
expect(option(wrapper, 1).attributes("aria-selected")).toBe("false");
expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([
[[0, "0"]],
[[0, "0"]],
]);
});
it("treats explicit undefined model as controlled and gives it priority over selectedKeys", async () => {
const wrapper = fixture(
`<ListBox :model-value="undefined" :selected-keys="[0]">${options}</ListBox>`,
);
await option(wrapper, 0).trigger("click");
expect(option(wrapper, 0).attributes("aria-selected")).toBe("false");
expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([
[[0]],
]);
});
it("implements single toggle and disallow-empty selection", async () => {
const locked = ref(true);
const wrapper = fixture(
`<ListBox :default-value="[0]" :disallow-empty-selection="locked">${options}</ListBox>`,
() => ({ locked }),
);
await option(wrapper, 0).trigger("click");
expect(option(wrapper, 0).attributes("aria-selected")).toBe("true");
locked.value = false;
await flushPromises();
await option(wrapper, 0).trigger("click");
expect(option(wrapper, 0).attributes("aria-selected")).toBe("false");
await option(wrapper, 1).trigger("click");
expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([
[[]],
[["0"]],
]);
});
it("keeps action-only collections unselected for pointer and keyboard activation", async () => {
const wrapper = fixture(
`<ListBox selection-mode="none">${options}</ListBox>`,
);
await option(wrapper, 0).trigger("click");
await flushPromises();
await option(wrapper, 0).trigger("keydown", { key: "Enter" });
expect(wrapper.getComponent(ListBox).emitted("action")).toEqual([[0], [0]]);
expect(
wrapper.getComponent(ListBox).emitted("update:modelValue"),
).toBeUndefined();
expect(option(wrapper, 0).attributes("aria-selected")).toBeUndefined();
});
it("uses one Tab stop, skips disabled keys and supports Home/End and RTL orientation", async () => {
const wrapper = fixture(
`<ListBox orientation="horizontal" dir="rtl">${options}</ListBox>`,
);
await flushPromises();
const root = wrapper.get('[role="listbox"]');
expect(root.attributes("tabindex")).toBe("-1");
expect(wrapper.findAll('[role="option"][tabindex="0"]')).toHaveLength(1);
option(wrapper, 0).element.focus();
await option(wrapper, 0).trigger("keydown", { key: "ArrowLeft" });
expect(document.activeElement).toBe(option(wrapper, 1).element);
await option(wrapper, 1).trigger("keydown", { key: "ArrowLeft" });
expect(document.activeElement).toBe(option(wrapper, 3).element);
await option(wrapper, 3).trigger("keydown", { key: "Home" });
expect(document.activeElement).toBe(option(wrapper, 0).element);
await option(wrapper, 0).trigger("keydown", { key: "End" });
expect(document.activeElement).toBe(option(wrapper, 3).element);
expect(
wrapper.getComponent(ListBox).emitted("update:modelValue"),
).toBeUndefined();
});
it("selects a range with a zero anchor, toggles all available keys and respects readonly", async () => {
const readonly = ref(false);
const wrapper = fixture(
`<ListBox selection-mode="multiple" :is-read-only="readonly">${options}</ListBox>`,
() => ({ readonly }),
);
await option(wrapper, 0).trigger("click");
await flushPromises();
await option(wrapper, 0).trigger("keydown", { key: "End", shiftKey: true });
expect(wrapper.findAll('[aria-selected="true"]')).toHaveLength(3);
expect(option(wrapper, 2).attributes("aria-selected")).toBe("false");
readonly.value = true;
await flushPromises();
await option(wrapper, 3).trigger("keydown", { key: "a", ctrlKey: true });
await option(wrapper, 1).trigger("click");
expect(wrapper.getComponent(ListBox).emitted("update:modelValue")).toEqual([
[[0]],
[[0, "0", "last"]],
]);
});
it("replace navigation selects focused options while modifier navigation only moves focus", async () => {
const wrapper = fixture(
`<ListBox selection-mode="multiple" selection-behavior="replace">${options}</ListBox>`,
);
await option(wrapper, 0).trigger("click");
await flushPromises();
await option(wrapper, 0).trigger("keydown", { key: "ArrowDown" });
expect(option(wrapper, 1).attributes("aria-selected")).toBe("true");
expect(option(wrapper, 0).attributes("aria-selected")).toBe("false");
await option(wrapper, 1).trigger("keydown", { key: "End", ctrlKey: true });
expect(document.activeElement).toBe(option(wrapper, 3).element);
expect(option(wrapper, 3).attributes("aria-selected")).toBe("false");
});
it("uses textValue for accent-insensitive typeahead and leaves IME alone", async () => {
const wrapper = fixture(`<ListBox>${options}</ListBox>`);
option(wrapper, 1).element.focus();
await option(wrapper, 1).trigger("keydown", {
key: "e",
isComposing: true,
});
expect(document.activeElement).toBe(option(wrapper, 1).element);
await option(wrapper, 1).trigger("keydown", { key: "e" });
expect(document.activeElement).toBe(option(wrapper, 0).element);
});
it("respects caller keyboard/click cancellation and DOM listener-array stop semantics", async () => {
const second = vi.fn();
const wrapper = fixture(
`<ListBox @keydown.prevent><ListBoxItem id="a" :onClick="handlers">A</ListBoxItem><ListBoxItem id="b">B</ListBoxItem></ListBox>`,
() => ({
handlers: [
(event: MouseEvent) => event.stopImmediatePropagation(),
second,
],
}),
);
option(wrapper, 0).element.focus();
await option(wrapper, 0).trigger("keydown", { key: "ArrowDown" });
expect(document.activeElement).toBe(option(wrapper, 0).element);
await option(wrapper, 0).trigger("click");
expect(second).not.toHaveBeenCalled();
expect(
wrapper.getComponent(ListBox).emitted("update:modelValue"),
).toBeUndefined();
});
it("cancels select before activation and exposes the original keyboard event", async () => {
const select = vi.fn((event: CustomEvent) => event.preventDefault());
const wrapper = fixture(
'<ListBox><ListBoxItem id="a" @select="select">A</ListBoxItem></ListBox>',
() => ({ select }),
);
option(wrapper, 0).element.focus();
await option(wrapper, 0).trigger("keydown", { key: " " });
await option(wrapper, 0).trigger("keyup", { key: " " });
expect(select).toHaveBeenCalledOnce();
expect(select.mock.calls[0][0].detail.originalEvent).toBeInstanceOf(
KeyboardEvent,
);
expect(wrapper.getComponent(ListBox).emitted("action")).toBeUndefined();
});
it("applies Fieldset disabled semantics and preserves first Legend exemption", async () => {
const wrapper = fixture(
`<Fieldset disabled><legend><ListBox>${options}</ListBox></legend><ListBox>${options}</ListBox></Fieldset>`,
);
const lists = wrapper.findAllComponents(ListBox);
await lists[0].findAll('[role="option"]')[0].trigger("click");
await lists[1].findAll('[role="option"]')[0].trigger("click");
expect(lists[0].emitted("update:modelValue")).toEqual([[[0]]]);
expect(lists[1].emitted("update:modelValue")).toBeUndefined();
expect(
lists[1].findAll('[role="option"]')[0].attributes("aria-disabled"),
).toBe("true");
expect(lists[1].findAll('[tabindex="0"]')).toHaveLength(0);
});
it("isolates option labels/descriptions, names sections and honors explicit ARIA", async () => {
const wrapper = fixture(
'<ListBox><ListBoxSection><Header>Team</Header><ListBoxItem id="a"><Label>A</Label><Description>Detail A</Description></ListBoxItem><ListBoxItem id="b" aria-label="Explicit"><Label>B</Label><Description>Detail B</Description></ListBoxItem></ListBoxSection></ListBox>',
);
expect(wrapper.get('[role="group"]').attributes("aria-labelledby")).toBe(
wrapper.get("header").attributes("id"),
);
expect(option(wrapper, 0).attributes("aria-describedby")).not.toBe(
option(wrapper, 1).attributes("aria-describedby"),
);
expect(option(wrapper, 1).attributes("aria-labelledby")).toBeUndefined();
expect(option(wrapper, 1).attributes("aria-label")).toBe("Explicit");
});
it("handles member reordering, disabled updates and removal without losing a focus entry", async () => {
const items = ref([
{ id: "a", textValue: "A" },
{ id: "b", textValue: "B" },
{ id: "c", textValue: "C" },
]);
const blocked = ref<string[]>([]);
const wrapper = fixture(
'<ListBox :disabled-keys="blocked"><ListBoxItem v-for="item in items" :key="item.id" :id="item.id" :text-value="item.textValue">{{ item.textValue }}</ListBoxItem></ListBox>',
() => ({ items, blocked }),
);
option(wrapper, 0).element.focus();
items.value.reverse();
await flushPromises();
await option(wrapper, 2).trigger("keydown", { key: "Home" });
expect(document.activeElement?.textContent).toBe("C");
blocked.value = ["c"];
await flushPromises();
expect(document.activeElement?.textContent).toBe("B");
items.value = items.value.filter((item) => item.id !== "b");
await flushPromises();
expect(document.activeElement?.textContent).toBe("A");
expect(wrapper.findAll('[role="option"][tabindex="0"]')).toHaveLength(1);
});
it("renders a bounded virtual window but selects the entire logical collection", async () => {
const items = Array.from({ length: 1000 }, (_, index) => ({
id: index,
textValue: `User ${index}`,
isDisabled: index === 999,
}));
const wrapper = fixture(
'<ListBox :items="items" virtualized selection-mode="multiple" style="height:400px" v-slot="{ item }"><ListBoxItem :id="item.id" :text-value="item.textValue">{{ item.textValue }}</ListBoxItem></ListBox>',
() => ({ items }),
);
await flushPromises();
expect(wrapper.findAll('[role="option"]').length).toBeGreaterThan(0);
expect(wrapper.findAll('[role="option"]').length).toBeLessThan(40);
await option(wrapper, 0).trigger("keydown", { key: "a", ctrlKey: true });
const changes = wrapper.getComponent(ListBox).emitted("update:modelValue")!;
expect(changes[0][0] as number[]).toHaveLength(999);
expect(changes[0][0] as number[]).not.toContain(999);
expect(option(wrapper, 0).attributes("aria-setsize")).toBe("1000");
// jsdom does not verify scrolling geometry; browser verifies End/scroll/focus.
});
it("keeps all instances isolated and supports a supplied empty state", async () => {
const wrapper = fixture(
`<div><ListBox>${options}</ListBox><ListBox>${options}</ListBox><ListBox :items="[]"><template #empty>No results</template></ListBox></div>`,
);
await option(wrapper, 0).trigger("click");
expect(wrapper.findAll('[aria-selected="true"]')).toHaveLength(1);
const ids = wrapper.findAll("[id]").map((node) => node.attributes("id"));
expect(new Set(ids).size).toBe(ids.length);
expect(wrapper.text()).toContain("No results");
});
it("hydrates selected options and label relationships without mismatches", async () => {
const Component = defineComponent({
render: () =>
h(ListBox, { defaultValue: [0] }, () =>
h(
ListBoxItem,
{ id: 0 },
{
default: () => [
h(Label, {}, () => "Bob"),
h(Description, {}, () => "Details"),
],
},
),
),
});
const host = document.createElement("div");
host.innerHTML = await renderToString(createSSRApp(Component));
document.body.append(host);
const before = host.querySelector('[role="option"]')!;
const beforeId = before.id;
const warnings: string[] = [];
const app = createSSRApp(Component);
app.config.warnHandler = (message) => warnings.push(message);
app.mount(host);
await flushPromises();
try {
expect(warnings).toEqual([]);
const after = host.querySelector('[role="option"]')!;
expect(after).toBe(before);
expect(after.id).toBe(beforeId);
expect(after.getAttribute("aria-selected")).toBe("true");
expect(after.getAttribute("aria-labelledby")).toBe(
after.querySelector('[data-slot="label"]')?.id,
);
expect(after.getAttribute("aria-describedby")).toBe(
after.querySelector('[data-slot="description"]')?.id,
);
} finally {
app.unmount();
}
});
it("compiles and mounts all nine baseline demos together without warnings or duplicate IDs", async () => {
const demos = import.meta.glob("../apps/docs/demos/list-box-*.vue", {
eager: true,
import: "default",
});
expect(Object.keys(demos)).toHaveLength(9);
const warnings: string[] = [];
const wrapper = mount(
defineComponent({
render: () =>
h(
"main",
Object.values(demos).map((component) =>
h(component as ReturnType<typeof defineComponent>),
),
),
}),
{
attachTo: document.body,
global: {
config: { warnHandler: (message) => warnings.push(message) },
},
},
);
wrappers.push(wrapper);
await flushPromises();
expect(warnings).toEqual([]);
expect(wrapper.findAll('[role="listbox"]')).toHaveLength(9);
expect(wrapper.findAll('[role="option"]').length).toBeLessThan(100);
const ids = wrapper.findAll("[id]").map((node) => node.attributes("id"));
expect(new Set(ids).size).toBe(ids.length);
const defaults = wrapper.findAll('[role="listbox"]')[0];
expect(wrapper.text()).toContain("bob@heroui.com");
expect(defaults.find('[role="option"]').exists()).toBe(true);
});
});