chore: remove legacy SSR checks and consolidate migration maintenance
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, ref, nextTick } from "vue";
|
||||
import {
|
||||
Button,
|
||||
ButtonGroup,
|
||||
ToggleButton,
|
||||
ToggleButtonGroup,
|
||||
} from "../../../packages/vue/src";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(async () => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
await flushPromises();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
function fixture(template: string, setup = () => ({})) {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: { Button, ButtonGroup, ToggleButton, ToggleButtonGroup },
|
||||
template,
|
||||
setup,
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
return w;
|
||||
}
|
||||
it("caller preventDefault cancels standalone and grouped activation", async () => {
|
||||
const change = vi.fn();
|
||||
const w = fixture(
|
||||
'<div><ToggleButton @click.prevent @change="change">one</ToggleButton><ToggleButtonGroup selection-mode="multiple" @selection-change="change"><ToggleButton value="a" @click.prevent>two</ToggleButton></ToggleButtonGroup></div>',
|
||||
() => ({ change }),
|
||||
);
|
||||
for (const b of w.findAll("button")) await b.trigger("click");
|
||||
expect(change).not.toHaveBeenCalled();
|
||||
});
|
||||
it("dynamic group size updates existing members", async () => {
|
||||
const size = ref("sm");
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup :size="size"><ToggleButton value="a">A</ToggleButton></ToggleButtonGroup>',
|
||||
() => ({ size }),
|
||||
);
|
||||
expect(w.get("button").classes()).toContain("hv-toggle-button--sm");
|
||||
size.value = "lg";
|
||||
await nextTick();
|
||||
expect(w.get("button").classes()).toContain("hv-toggle-button--lg");
|
||||
});
|
||||
it("multiple to single reconciles to at most one checked radio", async () => {
|
||||
const mode = ref("multiple");
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup :selection-mode="mode" :default-selected-keys="[\'a\',\'b\']"><ToggleButton value="a">A</ToggleButton><ToggleButton value="b">B</ToggleButton></ToggleButtonGroup>',
|
||||
() => ({ mode }),
|
||||
);
|
||||
mode.value = "single";
|
||||
await nextTick();
|
||||
expect(w.findAll('[aria-checked="true"]').length).toBeLessThanOrEqual(1);
|
||||
});
|
||||
it("a disabled first member leaves an enabled keyboard entry point", async () => {
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup><ToggleButton value="a" is-disabled>A</ToggleButton><ToggleButton value="b">B</ToggleButton></ToggleButtonGroup>',
|
||||
);
|
||||
await flushPromises();
|
||||
expect(w.findAll("button")[1].attributes("tabindex")).toBe("0");
|
||||
});
|
||||
it("numeric and string group keys do not produce duplicate DOM ids", () => {
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup selection-mode="multiple"><ToggleButton :id="1">number</ToggleButton><ToggleButton id="1">string</ToggleButton></ToggleButtonGroup>',
|
||||
);
|
||||
const ids = w
|
||||
.findAll("button")
|
||||
.map((b) => b.attributes("id"))
|
||||
.filter((id) => id !== undefined);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
it("cancelled arrow key is not processed", async () => {
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup><ToggleButton value="a" @keydown.prevent>A</ToggleButton><ToggleButton value="b">B</ToggleButton></ToggleButtonGroup>',
|
||||
);
|
||||
await flushPromises();
|
||||
const buttons = w.findAll("button");
|
||||
(buttons[0].element as HTMLElement).focus();
|
||||
await buttons[0].trigger("keydown", { key: "ArrowRight" });
|
||||
expect(document.activeElement).toBe(buttons[0].element);
|
||||
});
|
||||
it("changing member keys updates keyboard registration", async () => {
|
||||
const key = ref("a");
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup><ToggleButton :value="key">first</ToggleButton><ToggleButton value="b">second</ToggleButton></ToggleButtonGroup>',
|
||||
() => ({ key }),
|
||||
);
|
||||
await flushPromises();
|
||||
key.value = "c";
|
||||
await nextTick();
|
||||
const buttons = w.findAll("button");
|
||||
(buttons[0].element as HTMLElement).focus();
|
||||
await buttons[0].trigger("keydown", { key: "ArrowRight" });
|
||||
expect(document.activeElement).toBe(buttons[1].element);
|
||||
});
|
||||
|
||||
it("Tab exits the group using either a single tab stop or focus-to-end strategy", async () => {
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup><ToggleButton value="a">A</ToggleButton><ToggleButton value="b">B</ToggleButton><ToggleButton value="c">C</ToggleButton></ToggleButtonGroup>',
|
||||
);
|
||||
await flushPromises();
|
||||
const buttons = w.findAll("button");
|
||||
(buttons[0].element as HTMLElement).focus();
|
||||
if (w.findAll('button[tabindex="0"]').length > 1) {
|
||||
await buttons[0].trigger("keydown", { key: "Tab" });
|
||||
expect(document.activeElement).toBe(buttons[2].element);
|
||||
} else {
|
||||
expect(w.findAll('button[tabindex="0"]')).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
it("vertical orientation does not consume perpendicular arrows", async () => {
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup orientation="vertical"><ToggleButton value="a">A</ToggleButton><ToggleButton value="b">B</ToggleButton></ToggleButtonGroup>',
|
||||
);
|
||||
await flushPromises();
|
||||
const first = w.findAll("button")[0];
|
||||
(first.element as HTMLElement).focus();
|
||||
await first.trigger("keydown", { key: "ArrowRight" });
|
||||
expect(document.activeElement).toBe(first.element);
|
||||
});
|
||||
|
||||
it("explicit child isDisabled=false overrides only ButtonGroup default as in pinned source", () => {
|
||||
const w = fixture(
|
||||
'<ButtonGroup is-disabled><Button :is-disabled="false">Enabled override</Button></ButtonGroup>',
|
||||
);
|
||||
expect((w.get("button").element as HTMLButtonElement).disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("arrow navigation follows keyed DOM order after a reorder", async () => {
|
||||
const keys = ref(["a", "b", "c"]);
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup><ToggleButton v-for="key in keys" :key="key" :value="key">{{ key }}</ToggleButton></ToggleButtonGroup>',
|
||||
() => ({ keys }),
|
||||
);
|
||||
await flushPromises();
|
||||
keys.value = ["c", "b", "a"];
|
||||
await nextTick();
|
||||
const buttons = w.findAll("button");
|
||||
expect(buttons.map((b) => b.text())).toEqual(["c", "b", "a"]);
|
||||
(buttons[1].element as HTMLElement).focus();
|
||||
await buttons[1].trigger("keydown", { key: "ArrowRight" });
|
||||
expect(document.activeElement).toBe(buttons[2].element);
|
||||
});
|
||||
|
||||
it("focusing a member updates the single Tab entry to that member", async () => {
|
||||
const w = fixture(
|
||||
'<ToggleButtonGroup><ToggleButton value="a">A</ToggleButton><ToggleButton value="b">B</ToggleButton><ToggleButton value="c">C</ToggleButton></ToggleButtonGroup>',
|
||||
);
|
||||
await flushPromises();
|
||||
const buttons = w.findAll("button");
|
||||
(buttons[2].element as HTMLElement).focus();
|
||||
await nextTick();
|
||||
expect(buttons[2].attributes("tabindex")).toBe("0");
|
||||
expect(buttons[0].attributes("tabindex")).toBe("-1");
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { afterEach, expect, it, 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 mounted: { unmount(): void }[] = [];
|
||||
afterEach(() => {
|
||||
while (mounted.length) mounted.pop()!.unmount();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
const settle = async () => {
|
||||
await nextTick();
|
||||
await new Promise((r) => setTimeout(r, 3));
|
||||
};
|
||||
function setupList(virtualized = false) {
|
||||
let collection: OwnedCollection | undefined;
|
||||
const items = Array.from({ length: 6 }, (_, id) => ({
|
||||
id,
|
||||
textValue: `Row ${id}`,
|
||||
}));
|
||||
const activeKey = ref<string | number>();
|
||||
const owner: CollectionOwner = {
|
||||
keys: computed(() => []),
|
||||
mode: computed(() => "single"),
|
||||
disabled: computed(() => false),
|
||||
readOnly: computed(() => false),
|
||||
disabledKeys: computed(() => []),
|
||||
id: "probe",
|
||||
labelledBy: () => undefined,
|
||||
ariaLabel: () => "Probe",
|
||||
request: () => {},
|
||||
action: () => {},
|
||||
leave: () => {},
|
||||
connect: (c) => {
|
||||
collection = c;
|
||||
return () => {
|
||||
collection = undefined;
|
||||
};
|
||||
},
|
||||
filter: (r) => r.key === 3,
|
||||
virtualFocus: () => true,
|
||||
activeKey,
|
||||
};
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
provide(collectionOwnerKey, owner);
|
||||
return () =>
|
||||
h(
|
||||
ListBox,
|
||||
{ items, virtualized, rowHeight: 40, overscan: 8 },
|
||||
{
|
||||
default: ({ item }: { item: (typeof items)[number] }) =>
|
||||
h(ListBoxItem, { id: item.id }, () => item.textValue),
|
||||
},
|
||||
);
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
mounted.push(wrapper);
|
||||
return { wrapper, collection: () => collection };
|
||||
}
|
||||
it("preserves caller hidden on an ordinary ListBoxItem", async () => {
|
||||
const w = mount(ListBox, {
|
||||
slots: {
|
||||
default: () =>
|
||||
h(ListBoxItem, { id: "hidden", hidden: true }, () => "Hidden"),
|
||||
},
|
||||
});
|
||||
mounted.push(w);
|
||||
await settle();
|
||||
expect(w.find('[role="option"]').attributes("hidden")).toBeDefined();
|
||||
});
|
||||
it("reveal scrolls a mounted ordinary row without moving DOM focus", async () => {
|
||||
const { wrapper, collection } = setupList();
|
||||
await settle();
|
||||
const node = wrapper.findAll('[role="option"]')[3].element;
|
||||
const scroll = vi.fn();
|
||||
Object.defineProperty(node, "scrollIntoView", {
|
||||
configurable: true,
|
||||
value: scroll,
|
||||
});
|
||||
await collection()!.reveal!(3);
|
||||
expect(scroll).toHaveBeenCalled();
|
||||
});
|
||||
it("virtual window contains no fixed height slots for filtered-out rows", async () => {
|
||||
const { wrapper } = setupList(true);
|
||||
await settle();
|
||||
expect(
|
||||
wrapper.findAll(
|
||||
'[data-slot="list-box-virtual-content"] > [role="presentation"]',
|
||||
),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
it("restores keyboard highlight intent after a pointer interaction", async () => {
|
||||
const w = mount(Harness, { attachTo: document.body });
|
||||
mounted.push(w);
|
||||
await settle();
|
||||
const input = w.find("input");
|
||||
await input.setValue("");
|
||||
await settle();
|
||||
await w.findAll('[role="option"]')[0].trigger("pointerdown");
|
||||
await input.trigger("keydown", { key: "ArrowDown" });
|
||||
await settle();
|
||||
expect(w.find('[data-focused="true"]').attributes("data-focus-visible")).toBe(
|
||||
"true",
|
||||
);
|
||||
});
|
||||
it("has instance-unique names and controls in the verification harness", async () => {
|
||||
const w = mount(
|
||||
defineComponent({ setup: () => () => h("div", [h(Harness), h(Harness)]) }),
|
||||
);
|
||||
mounted.push(w);
|
||||
await settle();
|
||||
const ids = w.findAll("[id]").map((n) => n.attributes("id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,448 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref, type Ref } from "vue";
|
||||
import {
|
||||
ComboBox,
|
||||
ComboBoxInputGroup,
|
||||
ComboBoxPopover,
|
||||
ComboBoxTrigger,
|
||||
Autocomplete,
|
||||
AutocompleteTrigger,
|
||||
AutocompleteValue,
|
||||
AutocompleteClearButton,
|
||||
AutocompleteIndicator,
|
||||
AutocompletePopover,
|
||||
AutocompleteFilter,
|
||||
Input,
|
||||
ListBox,
|
||||
ListBoxItem,
|
||||
SearchField,
|
||||
SearchFieldGroup,
|
||||
SearchFieldInput,
|
||||
SearchFieldClearButton,
|
||||
} from "../../../packages/vue/src";
|
||||
const roots: { unmount(): void }[] = [];
|
||||
const tick = async () => {
|
||||
await nextTick();
|
||||
await new Promise((r) => setTimeout(r, 6));
|
||||
};
|
||||
afterEach(async () => {
|
||||
while (roots.length) roots.pop()!.unmount();
|
||||
await tick();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
type Item = { id: string | number; textValue: string };
|
||||
const defaults: Item[] = [
|
||||
{ id: 0, textValue: "Numeric Zero" },
|
||||
{ id: "0", textValue: "String Zero" },
|
||||
{ id: "a", textValue: "Alpha" },
|
||||
{ id: "b", textValue: "Beta" },
|
||||
];
|
||||
function picker(
|
||||
kind: "combo" | "auto",
|
||||
props: () => Record<string, unknown> = () => ({}),
|
||||
opts: {
|
||||
items?: Ref<Item[]>;
|
||||
inputProps?: Record<string, unknown>;
|
||||
filterProps?: Record<string, unknown>;
|
||||
} = {},
|
||||
) {
|
||||
const items = opts.items ?? ref(defaults);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h("form", null, [
|
||||
h(
|
||||
kind === "combo" ? ComboBox : Autocomplete,
|
||||
{ "aria-label": "Picker", ...props() },
|
||||
{
|
||||
default: () => [
|
||||
kind === "combo"
|
||||
? h(ComboBoxInputGroup, null, {
|
||||
default: () => [
|
||||
h(Input, opts.inputProps),
|
||||
h(ComboBoxTrigger),
|
||||
],
|
||||
})
|
||||
: h(AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(AutocompleteValue),
|
||||
h(AutocompleteClearButton),
|
||||
h(AutocompleteIndicator),
|
||||
],
|
||||
}),
|
||||
h(
|
||||
kind === "combo" ? ComboBoxPopover : AutocompletePopover,
|
||||
null,
|
||||
{
|
||||
default: () => {
|
||||
const list = h(ListBox, null, {
|
||||
default: () =>
|
||||
items.value.map((item) =>
|
||||
h(
|
||||
ListBoxItem,
|
||||
{
|
||||
id: item.id,
|
||||
key: item.id,
|
||||
textValue: item.textValue,
|
||||
},
|
||||
() => item.textValue,
|
||||
),
|
||||
),
|
||||
});
|
||||
return kind === "combo"
|
||||
? list
|
||||
: h(AutocompleteFilter, opts.filterProps, {
|
||||
default: () => [
|
||||
h(
|
||||
SearchField,
|
||||
{ "aria-label": "Search" },
|
||||
{
|
||||
default: () =>
|
||||
h(SearchFieldGroup, null, {
|
||||
default: () => [
|
||||
h(SearchFieldInput, opts.inputProps),
|
||||
h(SearchFieldClearButton),
|
||||
],
|
||||
}),
|
||||
},
|
||||
),
|
||||
list,
|
||||
],
|
||||
});
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
},
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
roots.push(w);
|
||||
return w;
|
||||
}
|
||||
const comboInput = () =>
|
||||
document.querySelector<HTMLInputElement>('[data-slot="input"]')!;
|
||||
const searchInput = () =>
|
||||
document.querySelector<HTMLInputElement>('[data-slot="search-field-input"]')!;
|
||||
async function open(kind: "combo" | "auto") {
|
||||
if (kind === "combo") comboInput().focus();
|
||||
else
|
||||
document
|
||||
.querySelector<HTMLElement>('[data-slot="autocomplete-trigger"]')!
|
||||
.click();
|
||||
await tick();
|
||||
}
|
||||
async function type(el: HTMLInputElement, text: string) {
|
||||
el.value = text;
|
||||
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
await tick();
|
||||
}
|
||||
|
||||
it("native cancelable clear click actually clears Autocomplete", async () => {
|
||||
const change = vi.fn();
|
||||
picker("auto", () => ({ defaultValue: "a", onChange: change }));
|
||||
await tick();
|
||||
document
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="autocomplete-clear-button"]',
|
||||
)!
|
||||
.click();
|
||||
await tick();
|
||||
expect(change).toHaveBeenLastCalledWith(null);
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s disabled fields do not submit a value",
|
||||
async (kind) => {
|
||||
const w = picker(kind, () => ({
|
||||
name: "choice",
|
||||
defaultValue: "a",
|
||||
isDisabled: true,
|
||||
}));
|
||||
await tick();
|
||||
expect(new FormData(w.element as HTMLFormElement).has("choice")).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
);
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s multiple values use same-name entries",
|
||||
async (kind) => {
|
||||
const w = picker(kind, () => ({
|
||||
name: "choice",
|
||||
selectionMode: "multiple",
|
||||
defaultValue: ["a", "b"],
|
||||
}));
|
||||
await tick();
|
||||
expect(new FormData(w.element as HTMLFormElement).getAll("choice")).toEqual(
|
||||
["a", "b"],
|
||||
);
|
||||
},
|
||||
);
|
||||
it("ComboBox external clear clears displayed text", async () => {
|
||||
const selected = ref<string | null>("a");
|
||||
picker("combo", () => ({ modelValue: selected.value }));
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("Alpha");
|
||||
selected.value = null;
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("");
|
||||
});
|
||||
it("ComboBox keeps numeric and string keys distinct in external text synchronization", async () => {
|
||||
const selected = ref<string | number>(0);
|
||||
picker("combo", () => ({ modelValue: selected.value }));
|
||||
await tick();
|
||||
selected.value = "0";
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("String Zero");
|
||||
});
|
||||
it("ComboBox accepts selected label updates without an item-count change", async () => {
|
||||
const items = ref<Item[]>([{ id: "a", textValue: "Old" }]);
|
||||
picker("combo", () => ({ modelValue: "a" }), { items });
|
||||
await tick();
|
||||
items.value = [{ id: "a", textValue: "New" }];
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("New");
|
||||
});
|
||||
it("ComboBox respects a controlled empty inputValue", async () => {
|
||||
picker("combo", () => ({ modelValue: "a", inputValue: "" }));
|
||||
await tick();
|
||||
expect(comboInput().value).toBe("");
|
||||
});
|
||||
it("ComboBox allows clearing a required selection before validation", async () => {
|
||||
const update = vi.fn();
|
||||
picker("combo", () => ({
|
||||
defaultValue: "a",
|
||||
isRequired: true,
|
||||
"onUpdate:modelValue": update,
|
||||
}));
|
||||
await tick();
|
||||
await type(comboInput(), "");
|
||||
expect(update).toHaveBeenLastCalledWith(null);
|
||||
expect(comboInput().value).toBe("");
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s asChild uses the supplied root",
|
||||
async (kind) => {
|
||||
// The ordinary component tree is the one custom wrapper supplied to the root.
|
||||
const Root = kind === "combo" ? ComboBox : Autocomplete;
|
||||
const w = mount(Root, {
|
||||
props: { asChild: true },
|
||||
slots: {
|
||||
default: () => h("section", { "data-custom": "root" }, "Custom"),
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await tick();
|
||||
expect(w.element.tagName).toBe("SECTION");
|
||||
},
|
||||
);
|
||||
it("ComboBox autoFocus focuses its composed input", async () => {
|
||||
picker("combo", () => ({ autoFocus: true }));
|
||||
await tick();
|
||||
expect(document.activeElement).toBe(comboInput());
|
||||
});
|
||||
it("ComboBox secondary variant reaches its input", async () => {
|
||||
picker("combo", () => ({ variant: "secondary" }));
|
||||
await tick();
|
||||
expect(comboInput().classList.contains("hv-input--secondary")).toBe(true);
|
||||
});
|
||||
it("ComboBox preserves caller input component ref", async () => {
|
||||
const inputRef = ref();
|
||||
picker("combo", () => ({}), { inputProps: { ref: inputRef } });
|
||||
await tick();
|
||||
expect(inputRef.value).toBeTruthy();
|
||||
});
|
||||
it("Autocomplete preserves caller search-input component ref", async () => {
|
||||
const inputRef = ref();
|
||||
picker("auto", () => ({}), { inputProps: { ref: inputRef } });
|
||||
await tick();
|
||||
await open("auto");
|
||||
expect(inputRef.value).toBeTruthy();
|
||||
});
|
||||
it("Autocomplete search clear resets its filter", async () => {
|
||||
picker("auto");
|
||||
await tick();
|
||||
await open("auto");
|
||||
await type(searchInput(), "Beta");
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(1);
|
||||
document
|
||||
.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="search-field-clear-button"]',
|
||||
)!
|
||||
.click();
|
||||
await tick();
|
||||
expect(searchInput().value).toBe("");
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(4);
|
||||
});
|
||||
it("ComboBox respects an active composition session even on an unflagged Enter", async () => {
|
||||
const change = vi.fn();
|
||||
picker("combo", () => ({ onChange: change }));
|
||||
await tick();
|
||||
await open("combo");
|
||||
comboInput().dispatchEvent(
|
||||
new CompositionEvent("compositionstart", { bubbles: true }),
|
||||
);
|
||||
comboInput().dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Enter",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await tick();
|
||||
expect(change).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s does not filter during a composition session",
|
||||
async (kind) => {
|
||||
picker(kind);
|
||||
await tick();
|
||||
await open(kind);
|
||||
const input = kind === "combo" ? comboInput() : searchInput();
|
||||
input.dispatchEvent(
|
||||
new CompositionEvent("compositionstart", { bubbles: true }),
|
||||
);
|
||||
input.value = "qqq";
|
||||
input.dispatchEvent(
|
||||
new InputEvent("input", { bubbles: true, isComposing: true }),
|
||||
);
|
||||
await tick();
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(4);
|
||||
},
|
||||
);
|
||||
it("Autocomplete keeps filter focus when parent rejects closing", async () => {
|
||||
picker("auto", () => ({ open: true }));
|
||||
await tick();
|
||||
const input = searchInput();
|
||||
input.focus();
|
||||
await type(input, "Beta");
|
||||
input.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Enter",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await tick();
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="autocomplete-trigger"]')!
|
||||
.getAttribute("aria-expanded"),
|
||||
).toBe("true");
|
||||
expect(document.activeElement).toBe(input);
|
||||
});
|
||||
it("Autocomplete preserves an explicit search input accessible name", async () => {
|
||||
picker("auto", () => ({}), {
|
||||
inputProps: { "aria-label": "Specific search" },
|
||||
});
|
||||
await tick();
|
||||
await open("auto");
|
||||
expect(searchInput().getAttribute("aria-label")).toBe("Specific search");
|
||||
});
|
||||
it("ComboBox input participates in its explicitly associated form", async () => {
|
||||
const external = document.createElement("form");
|
||||
external.id = "external-form";
|
||||
document.body.appendChild(external);
|
||||
picker("combo", () => ({ form: "external-form", name: "choice" }));
|
||||
await tick();
|
||||
expect(comboInput().form).toBe(external);
|
||||
});
|
||||
it("Autocomplete clear button retains a caller disabled attribute", async () => {
|
||||
const w = mount(Autocomplete, {
|
||||
props: { defaultValue: "a" },
|
||||
slots: {
|
||||
default: () =>
|
||||
h(AutocompleteTrigger, null, {
|
||||
default: () => [
|
||||
h(AutocompleteValue),
|
||||
h(AutocompleteClearButton, { disabled: true }),
|
||||
],
|
||||
}),
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await tick();
|
||||
expect(
|
||||
document.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="autocomplete-clear-button"]',
|
||||
)!.disabled,
|
||||
).toBe(true);
|
||||
});
|
||||
it.each(["combo", "auto"] as const)(
|
||||
"%s does not submit a removed selection as a valid option",
|
||||
async (kind) => {
|
||||
const items = ref<Item[]>([...defaults]);
|
||||
const w = picker(kind, () => ({ defaultValue: "a", name: "choice" }), {
|
||||
items,
|
||||
});
|
||||
await tick();
|
||||
items.value = items.value.filter((i) => i.id !== "a");
|
||||
await tick();
|
||||
expect(new FormData(w.element as HTMLFormElement).get("choice")).not.toBe(
|
||||
"a",
|
||||
);
|
||||
},
|
||||
);
|
||||
it("Autocomplete default base-sensitivity filter matches accents", async () => {
|
||||
picker("auto", () => ({}), {
|
||||
items: ref([{ id: "cafe", textValue: "Café" }]),
|
||||
});
|
||||
await tick();
|
||||
await open("auto");
|
||||
await type(searchInput(), "cafe");
|
||||
expect(
|
||||
document.querySelectorAll('[role="option"]:not([data-filtered])').length,
|
||||
).toBe(1);
|
||||
});
|
||||
it("Autocomplete default indicator matches its size selector", async () => {
|
||||
picker("auto");
|
||||
await tick();
|
||||
// The shipped rule requires class and data-slot on the same element.
|
||||
expect(
|
||||
document.querySelector(
|
||||
'.hv-autocomplete__indicator[data-slot="autocomplete-default-indicator"]',
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
it("ComboBox custom text is the submitted text after editing a selected item", async () => {
|
||||
const w = picker("combo", () => ({
|
||||
defaultValue: "a",
|
||||
allowsCustomValue: true,
|
||||
name: "choice",
|
||||
}));
|
||||
await tick();
|
||||
await type(comboInput(), "Custom animal");
|
||||
expect(new FormData(w.element as HTMLFormElement).get("choice")).toBe(
|
||||
"Custom animal",
|
||||
);
|
||||
});
|
||||
it("ComboBox trigger retains a caller disabled attribute", async () => {
|
||||
const w = mount(ComboBox, {
|
||||
slots: {
|
||||
default: () =>
|
||||
h(ComboBoxInputGroup, null, {
|
||||
default: () => [h(Input), h(ComboBoxTrigger, { disabled: true })],
|
||||
}),
|
||||
},
|
||||
attachTo: document.body,
|
||||
});
|
||||
roots.push(w);
|
||||
await tick();
|
||||
expect(
|
||||
document.querySelector<HTMLButtonElement>(
|
||||
'[data-slot="combo-box-trigger"]',
|
||||
)!.disabled,
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect, afterEach, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent } from "vue";
|
||||
import {
|
||||
ColorFieldRoot,
|
||||
ColorFieldInput,
|
||||
ColorSliderRoot,
|
||||
ColorSliderTrack,
|
||||
ColorSliderThumb,
|
||||
} from "../../../packages/vue/tests/fixtures/color-probe";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
describe("installed Reka color input audit, not public component acceptance", () => {
|
||||
it("emits hex for a polar channel edit", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: { ColorFieldRoot, ColorFieldInput },
|
||||
template:
|
||||
'<ColorFieldRoot default-value="hsb(270,0%,50%,.12345)" channel="hue" color-space="hsb"><ColorFieldInput/></ColorFieldRoot>',
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get("input").setValue("271");
|
||||
await w.get("input").trigger("blur");
|
||||
expect(
|
||||
w.getComponent(ColorFieldRoot).emitted("update:modelValue")?.[0]?.[0],
|
||||
).toBe("#8080801f");
|
||||
});
|
||||
it("keeps optimistic slider state after a controlled parent rejection", async () => {
|
||||
vi.stubGlobal(
|
||||
"ResizeObserver",
|
||||
class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
},
|
||||
);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: { ColorSliderRoot, ColorSliderTrack, ColorSliderThumb },
|
||||
template:
|
||||
'<ColorSliderRoot model-value="hsb(270,0%,50%)" channel="hue" color-space="hsb"><ColorSliderTrack><ColorSliderThumb/></ColorSliderTrack></ColorSliderRoot>',
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get('[role="slider"]').trigger("keydown", { key: "ArrowRight" });
|
||||
expect(
|
||||
w.getComponent(ColorSliderRoot).emitted("update:modelValue")?.[0]?.[0],
|
||||
).toMatch(/^#/);
|
||||
expect(w.get('[role="slider"]').attributes("aria-valuenow")).not.toBe(
|
||||
"270",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, it, expect, afterEach } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent } from "vue";
|
||||
import {
|
||||
ColorAreaRoot,
|
||||
ColorAreaArea,
|
||||
ColorAreaThumb,
|
||||
parseColor,
|
||||
getChannelRange,
|
||||
getChannelValue,
|
||||
getAreaBackgroundStyle,
|
||||
} from "../../../packages/vue/tests/fixtures/color-probe";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
});
|
||||
function area() {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: { ColorAreaRoot, ColorAreaArea, ColorAreaThumb },
|
||||
template:
|
||||
'<ColorAreaRoot model-value="hsb(240, 50%, 50%)" color-space="hsb" x-channel="saturation" y-channel="brightness"><ColorAreaArea><ColorAreaThumb/></ColorAreaArea></ColorAreaRoot>',
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
return w;
|
||||
}
|
||||
describe("Reka 2.11 installed color capability audit (not public acceptance)", () => {
|
||||
it("emits hex and leaves a rejected channel at its optimistic thumb position", async () => {
|
||||
const w = area();
|
||||
await w.get('[role="slider"]').trigger("keydown", { key: "ArrowRight" });
|
||||
await flushPromises();
|
||||
expect(
|
||||
w.getComponent(ColorAreaRoot).emitted("update:modelValue")?.[0]?.[0],
|
||||
).toMatch(/^#/);
|
||||
expect(w.get('[role="slider"]').attributes("aria-valuenow")).toBe("51");
|
||||
});
|
||||
it("does not emit keyboard changeEnd after releasing an arrow", async () => {
|
||||
const w = area();
|
||||
await w.get('[role="slider"]').trigger("keydown", { key: "ArrowRight" });
|
||||
await w.get('[role="slider"]').trigger("keyup", { key: "ArrowRight" });
|
||||
expect(w.getComponent(ColorAreaRoot).emitted("changeEnd")).toBeUndefined();
|
||||
});
|
||||
it("uses percent alpha channel metadata while color storage uses a fraction", () => {
|
||||
expect(getChannelRange("alpha").max).toBe(100);
|
||||
expect(parseColor("#ff000080").alpha).toBeCloseTo(128 / 255);
|
||||
});
|
||||
it("loses achromatic HSB hue through the generic hue getter", () => {
|
||||
expect(getChannelValue(parseColor("hsb(240, 0%, 50%)"), "hue")).toBe(0);
|
||||
});
|
||||
it("accepts functional trailing junk and out-of-range values without normalization", () => {
|
||||
expect(parseColor("rgb(999, 0, 0) trailing")).toMatchObject({ r: 999 });
|
||||
});
|
||||
it("does not parse the four-digit alpha shorthand", () => {
|
||||
expect(() => parseColor("#f008")).toThrow();
|
||||
});
|
||||
it("falls back to no hue layer when hue is the y axis", () => {
|
||||
const style = getAreaBackgroundStyle(
|
||||
parseColor("hsb(240, 50%, 50%)"),
|
||||
"saturation",
|
||||
"hue",
|
||||
"hsb",
|
||||
);
|
||||
expect(style.backgroundImage).not.toContain("#ff0000, #ffff00");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,389 @@
|
||||
import Surface from "../../../packages/vue/src/components/surface/Surface.vue";
|
||||
import { surfaceContextKey } from "../../../packages/vue/src/components/surface/context";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h, ref, inject } from "vue";
|
||||
import {
|
||||
Button,
|
||||
DropdownRoot,
|
||||
DropdownTrigger,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownSection,
|
||||
DropdownSubmenuTrigger,
|
||||
DropdownSubmenuIndicator,
|
||||
DropdownItem,
|
||||
Menu,
|
||||
} from "../../../packages/vue/src";
|
||||
const cleanup: (() => void)[] = [];
|
||||
afterEach(() => {
|
||||
cleanup
|
||||
.splice(0)
|
||||
.reverse()
|
||||
.forEach((fn) => fn());
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
async function render(
|
||||
menuProps: Record<string, unknown>,
|
||||
children: () => unknown,
|
||||
) {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true, modal: false }, () =>
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, menuProps, { default: children }),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
return w;
|
||||
}
|
||||
it("section disabledKeys work when selection is inherited", async () => {
|
||||
await render({ selectionMode: "multiple" }, () =>
|
||||
h(DropdownSection, { disabledKeys: ["x"] }, () =>
|
||||
h(DropdownItem, { id: "x" }, () => "X"),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="menu-item"]')
|
||||
?.getAttribute("aria-disabled"),
|
||||
).toBe("true");
|
||||
});
|
||||
it("root disabledKeys remain effective in a section with its own selection", async () => {
|
||||
await render({ disabledKeys: ["x"] }, () =>
|
||||
h(DropdownSection, { selectionMode: "multiple" }, () =>
|
||||
h(DropdownItem, { id: "x" }, () => "X"),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
document
|
||||
.querySelector('[data-slot="menu-item"]')
|
||||
?.getAttribute("aria-disabled"),
|
||||
).toBe("true");
|
||||
});
|
||||
it("single-selection closeOnSelect=false keeps the menu open", async () => {
|
||||
await render({ selectionMode: "single" }, () =>
|
||||
h(DropdownItem, { id: "x", closeOnSelect: false }, () => "X"),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
|
||||
});
|
||||
it("multiple-selection closeOnSelect=true closes the menu", async () => {
|
||||
await render({ selectionMode: "multiple" }, () =>
|
||||
h(DropdownItem, { id: "x", closeOnSelect: true }, () => "X"),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
it("typed numeric and string keys never create duplicate DOM ids", async () => {
|
||||
await render({ selectionMode: "multiple" }, () => [
|
||||
h(DropdownItem, { id: 0 }, () => "Number"),
|
||||
h(DropdownItem, { id: "0" }, () => "String"),
|
||||
]);
|
||||
const nodes = Array.from(
|
||||
document.querySelectorAll('[data-slot="menu-item"]'),
|
||||
);
|
||||
expect(new Set(nodes.map((n) => n.id)).size).toBe(nodes.length);
|
||||
});
|
||||
it("standalone Menu does not lock body scrolling or disable outside controls", async () => {
|
||||
const outside = document.createElement("button");
|
||||
document.body.append(outside);
|
||||
const w = mount(Menu, {
|
||||
slots: { default: () => h(DropdownItem, { id: "x" }, () => "X") },
|
||||
attachTo: document.body,
|
||||
});
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(document.body.style.overflow).not.toBe("hidden");
|
||||
expect(document.body.style.pointerEvents).not.toBe("none");
|
||||
expect(outside.getAttribute("aria-hidden")).not.toBe("true");
|
||||
});
|
||||
it("native link menu items retain anchor href semantics", async () => {
|
||||
await render({}, () =>
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "link", href: "/target", target: "_blank" },
|
||||
() => "Go",
|
||||
),
|
||||
);
|
||||
const item = document.querySelector('[data-slot="menu-item"]')!;
|
||||
expect(item.tagName).toBe("A");
|
||||
expect(item.getAttribute("href")).toBe("/target");
|
||||
});
|
||||
it("longPress cannot open a disabled actual trigger", async () => {
|
||||
vi.useFakeTimers();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress", modal: false }, () => [
|
||||
h(DropdownTrigger, {}, () =>
|
||||
h(Button, { isDisabled: true }, () => "Hold"),
|
||||
),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "x" }, () => "X")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await w.get("button").trigger("pointerdown", {
|
||||
pointerType: "mouse",
|
||||
button: 0,
|
||||
isPrimary: true,
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
it("cancelled trigger keydown does not open longPress menu", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress", modal: false }, () => [
|
||||
h(
|
||||
DropdownTrigger,
|
||||
{ onKeydown: (e: KeyboardEvent) => e.preventDefault() },
|
||||
() => h(Button, {}, () => "Hold"),
|
||||
),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "x" }, () => "X")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await w.get("button").trigger("keydown", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
it("root menu's accessible name follows its labelled DropdownMenu", async () => {
|
||||
await render({ "aria-label": "File actions" }, () =>
|
||||
h(DropdownItem, { id: "x" }, () => "X"),
|
||||
);
|
||||
const menu = document.querySelector('[role="menu"]')!;
|
||||
expect(menu.getAttribute("aria-label")).toBe("File actions");
|
||||
});
|
||||
|
||||
it("submenu Menu owns its selection instead of inheriting a parent section owner", async () => {
|
||||
await render({}, () =>
|
||||
h(
|
||||
DropdownSection,
|
||||
{ selectionMode: "multiple", selectedKeys: ["outer"] },
|
||||
() =>
|
||||
h(DropdownMenu, { selectionMode: "none" }, () =>
|
||||
h(DropdownItem, { id: "inner" }, () => "Inner"),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
document.querySelector('[data-slot="menu-item"]')?.getAttribute("role"),
|
||||
).toBe("menuitem");
|
||||
});
|
||||
|
||||
it("dropdown popover resets inherited Surface context like the fixed upstream", async () => {
|
||||
const Inspector = defineComponent({
|
||||
setup() {
|
||||
const ctx = inject(surfaceContextKey, null);
|
||||
return () =>
|
||||
h("span", { "data-test": "surface" }, ctx?.variant.value ?? "none");
|
||||
},
|
||||
});
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Surface, { variant: "secondary" }, () =>
|
||||
h(DropdownRoot, { defaultOpen: true, modal: false }, () =>
|
||||
h(DropdownPopover, {}, () => h(Inspector)),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-test="surface"]')?.textContent).toBe(
|
||||
"default",
|
||||
);
|
||||
});
|
||||
|
||||
it("submenu panel preserves a caller keydown listener", async () => {
|
||||
const keydown = vi.fn();
|
||||
await render({}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, { onKeydown: keydown }, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownItem, { id: "inner" }, () => "Inner"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
const panel = document.querySelector("[data-submenu-content]")!;
|
||||
expect(panel).not.toBeNull();
|
||||
panel.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "a", bubbles: true, cancelable: true }),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(keydown).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("default action activation closes its dropdown", async () => {
|
||||
await render({}, () => h(DropdownItem, { id: "default" }, () => "Action"));
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[role="menu"]')).toBeNull();
|
||||
});
|
||||
it.each([
|
||||
["single", false, true],
|
||||
["multiple", true, false],
|
||||
] as const)(
|
||||
"menu-level close policy for %s is honoured",
|
||||
async (selectionMode, shouldCloseOnSelect, staysOpen) => {
|
||||
await render({ selectionMode, shouldCloseOnSelect }, () =>
|
||||
h(DropdownItem, { id: "policy" }, () => "Policy"),
|
||||
);
|
||||
(document.querySelector('[data-slot="menu-item"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(!!document.querySelector('[role="menu"]')).toBe(staysOpen);
|
||||
},
|
||||
);
|
||||
it("root popover preserves a user keydown callback", async () => {
|
||||
const callback = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true, modal: false }, () =>
|
||||
h(DropdownPopover, { onKeydown: callback }, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
document.querySelector('[role="menu"]')!.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "a",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
async function openConfiguredSubmenu(props: Record<string, unknown>) {
|
||||
await render({}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, props, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownItem, { id: "inner" }, () => "Inner"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
(document.querySelector('[data-key="sub"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
return document.querySelector("[data-submenu-content]") as HTMLElement;
|
||||
}
|
||||
it("submenu preserves the panel's data and style attributes", async () => {
|
||||
const panel = await openConfiguredSubmenu({
|
||||
"data-custom": "kept",
|
||||
style: { borderTopWidth: "7px" },
|
||||
});
|
||||
expect(panel.getAttribute("data-custom")).toBe("kept");
|
||||
expect(panel.style.borderTopWidth).toBe("7px");
|
||||
});
|
||||
it("submenu honours isKeyboardDismissDisabled", async () => {
|
||||
const panel = await openConfiguredSubmenu({
|
||||
isKeyboardDismissDisabled: true,
|
||||
});
|
||||
const item = panel.querySelector('[data-slot="menu-item"]') as HTMLElement;
|
||||
item.focus();
|
||||
item.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Escape",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.querySelector("[data-submenu-content]")).not.toBeNull();
|
||||
});
|
||||
it("standalone Menu keeps its own accessible name", async () => {
|
||||
const w = mount(Menu, {
|
||||
attrs: { "aria-label": "Standalone actions" },
|
||||
slots: { default: () => h(DropdownItem, { id: "a" }, () => "A") },
|
||||
attachTo: document.body,
|
||||
});
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(
|
||||
document.querySelector('[role="menu"]')?.getAttribute("aria-label"),
|
||||
).toBe("Standalone actions");
|
||||
});
|
||||
|
||||
it("submenu keeps a directly supplied panel accessible name", async () => {
|
||||
const panel = await openConfiguredSubmenu({
|
||||
"aria-label": "Direct submenu name",
|
||||
"aria-describedby": "explicit-description",
|
||||
});
|
||||
expect(panel.getAttribute("aria-label")).toBe("Direct submenu name");
|
||||
expect(panel.getAttribute("aria-describedby")).toBe("explicit-description");
|
||||
});
|
||||
it("submenu preserves a caller's openAutoFocus callback", async () => {
|
||||
const callback = vi.fn();
|
||||
await openConfiguredSubmenu({ onOpenAutoFocus: callback });
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("submenu respects the menu's shouldFocusWrap navigation", async () => {
|
||||
await render({}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, { shouldFocusWrap: true }, () => [
|
||||
h(DropdownItem, { id: "first", textValue: "First" }, () => "First"),
|
||||
h(DropdownItem, { id: "last", textValue: "Last" }, () => "Last"),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
);
|
||||
(document.querySelector('[data-key="sub"]') as HTMLElement).click();
|
||||
await flushPromises();
|
||||
const panel = document.querySelector("[data-submenu-content]")!;
|
||||
const first = panel.querySelector('[data-key="first"]') as HTMLElement;
|
||||
const last = panel.querySelector('[data-key="last"]') as HTMLElement;
|
||||
first.focus();
|
||||
await flushPromises();
|
||||
first.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "ArrowUp",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
await flushPromises();
|
||||
expect(document.activeElement).toBe(last);
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { Button, DropdownTrigger } from "../../../packages/vue/src";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import {
|
||||
DropdownRoot,
|
||||
DropdownPopover,
|
||||
DropdownMenu,
|
||||
DropdownItem,
|
||||
DropdownItemIndicator,
|
||||
DropdownSubmenuTrigger,
|
||||
DropdownSubmenuIndicator,
|
||||
Menu,
|
||||
MenuItem,
|
||||
} from "../../../packages/vue/src";
|
||||
const cleanup: (() => void)[] = [];
|
||||
afterEach(() => {
|
||||
cleanup
|
||||
.splice(0)
|
||||
.reverse()
|
||||
.forEach((fn) => fn());
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
async function renderMenu(
|
||||
menuProps = {},
|
||||
itemProps = {},
|
||||
children = () => "A",
|
||||
) {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true }, () =>
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, menuProps, () =>
|
||||
h(
|
||||
DropdownItem,
|
||||
{ id: "a", textValue: "A", ...itemProps },
|
||||
children,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
return document.querySelector('[data-slot="menu-item"]') as HTMLElement;
|
||||
}
|
||||
it("selected multiple item exposes checked menu semantics and source CSS selected state", async () => {
|
||||
const node = await renderMenu(
|
||||
{ selectionMode: "multiple", selectedKeys: ["a"] },
|
||||
{},
|
||||
() => [h(DropdownItemIndicator, { type: "dot" }), "A"] as never,
|
||||
);
|
||||
expect(node.getAttribute("role")).toBe("menuitemcheckbox");
|
||||
expect(node.getAttribute("aria-checked")).toBe("true");
|
||||
});
|
||||
it("preventing click prevents action and default close", async () => {
|
||||
const action = vi.fn();
|
||||
const node = await renderMenu(
|
||||
{ onAction: action },
|
||||
{ onClick: (e: MouseEvent) => e.preventDefault() },
|
||||
);
|
||||
node.click();
|
||||
await flushPromises();
|
||||
expect(action).not.toHaveBeenCalled();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
|
||||
});
|
||||
it("submenu trigger has one menuitem DOM node rather than nested interactive items", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { defaultOpen: true }, () =>
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownSubmenuTrigger, {}, () => [
|
||||
h(DropdownItem, { id: "sub", textValue: "Sub" }, () => [
|
||||
"Sub",
|
||||
h(DropdownSubmenuIndicator),
|
||||
]),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () =>
|
||||
h(DropdownItem, { id: "child" }, () => "Child"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(
|
||||
document.querySelector('[role="menuitem"] [role="menuitem"]'),
|
||||
).toBeNull();
|
||||
});
|
||||
it("standalone exported Menu and MenuItem do not require an internal DropdownMenuRoot", () => {
|
||||
expect(() => {
|
||||
const w = mount(Menu, {
|
||||
slots: { default: () => h(MenuItem, { id: "a" }, () => "A") },
|
||||
});
|
||||
cleanup.push(() => w.unmount());
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it("stopImmediatePropagation stops subsequent user handlers and activation", async () => {
|
||||
const action = vi.fn();
|
||||
const second = vi.fn();
|
||||
const node = await renderMenu(
|
||||
{ onAction: action },
|
||||
{
|
||||
onClick: [(e: MouseEvent) => e.stopImmediatePropagation(), second],
|
||||
},
|
||||
);
|
||||
node.click();
|
||||
await flushPromises();
|
||||
expect(second).not.toHaveBeenCalled();
|
||||
expect(action).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("longPress trigger does not open on a short click of the actual button", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress" }, () => [
|
||||
h(DropdownTrigger, {}, () => h(Button, {}, () => "Hold")),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
(w.get("button").element as HTMLElement).click();
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("longPress keyboard Enter opens instead of toggling twice", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(DropdownRoot, { trigger: "longPress" }, () => [
|
||||
h(DropdownTrigger, {}, () => h(Button, {}, () => "Hold")),
|
||||
h(DropdownPopover, {}, () =>
|
||||
h(DropdownMenu, {}, () => h(DropdownItem, { id: "a" }, () => "A")),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
await w.get("button").trigger("keydown", { key: "Enter" });
|
||||
await flushPromises();
|
||||
expect(document.querySelector('[data-slot="menu-item"]')).not.toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h, ref } from "vue";
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot,
|
||||
Label,
|
||||
Description,
|
||||
FieldError,
|
||||
Fieldset,
|
||||
Form,
|
||||
Pagination,
|
||||
PaginationLink,
|
||||
} from "../../../packages/vue/src";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(async () => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
await flushPromises();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
function fixture(template: string, setup = () => ({})) {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot,
|
||||
Label,
|
||||
Description,
|
||||
FieldError,
|
||||
Fieldset,
|
||||
Form,
|
||||
Pagination,
|
||||
PaginationLink,
|
||||
},
|
||||
template,
|
||||
setup,
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
return w;
|
||||
}
|
||||
const slots =
|
||||
'<InputOTPGroup><InputOTPSlot v-for="i in 4" :key="i" :index="i-1"/></InputOTPGroup>';
|
||||
const inputs = (w: ReturnType<typeof mount>) =>
|
||||
w.findAll('input[data-slot="input-otp-input"]');
|
||||
|
||||
it("noncontrolled OTP restores its initial visible and submitted value on native reset", async () => {
|
||||
const w = fixture(
|
||||
`<form><InputOTP :max-length="4" default-value="12" name="code">${slots}</InputOTP></form>`,
|
||||
);
|
||||
await inputs(w)[0].setValue("9");
|
||||
await flushPromises();
|
||||
expect(new FormData(w.get("form").element).get("code")).toBe("92");
|
||||
w.get("form").element.reset();
|
||||
await flushPromises();
|
||||
expect(
|
||||
inputs(w)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("12");
|
||||
expect(new FormData(w.get("form").element).get("code")).toBe("12");
|
||||
});
|
||||
it("controlled OTP middle deletion keeps visual slots aligned with real inputs", async () => {
|
||||
const value = ref("1234");
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" v-model="value">${slots}</InputOTP>`,
|
||||
() => ({ value }),
|
||||
);
|
||||
await inputs(w)[1].trigger("keydown", { key: "Delete" });
|
||||
await flushPromises();
|
||||
expect(inputs(w).map((i) => (i.element as HTMLInputElement).value)).toEqual([
|
||||
"1",
|
||||
"",
|
||||
"3",
|
||||
"4",
|
||||
]);
|
||||
expect(
|
||||
w.findAll('[data-slot="input-otp-slot-value"]').map((i) => i.text()),
|
||||
).toEqual(["1", "3", "4"]);
|
||||
expect(
|
||||
w.findAll('[data-slot="input-otp-slot"]')[1].attributes("data-filled"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it("rejecting a controlled update still allows a later identical request", async () => {
|
||||
const update = vi.fn();
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" model-value="12" @update:model-value="update">${slots}</InputOTP>`,
|
||||
() => ({ update }),
|
||||
);
|
||||
await inputs(w)[2].setValue("9");
|
||||
await flushPromises();
|
||||
expect(
|
||||
inputs(w)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("12");
|
||||
await inputs(w)[2].setValue("9");
|
||||
await flushPromises();
|
||||
expect(update).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("OTP readonly blocks editing and deletion", async () => {
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" default-value="1234" readonly>${slots}</InputOTP>`,
|
||||
);
|
||||
expect((inputs(w)[0].element as HTMLInputElement).readOnly).toBe(true);
|
||||
await inputs(w)[0].trigger("keydown", { key: "Delete" });
|
||||
await flushPromises();
|
||||
expect(
|
||||
inputs(w)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("1234");
|
||||
});
|
||||
it("OTP consumes Fieldset disabled for real input state and visual slots", async () => {
|
||||
const w = fixture(
|
||||
`<Fieldset disabled><InputOTP :max-length="4">${slots}</InputOTP></Fieldset>`,
|
||||
);
|
||||
expect((inputs(w)[0].element as HTMLInputElement).disabled).toBe(true);
|
||||
expect(
|
||||
w.get('[data-slot="input-otp-slot"]').attributes("data-disabled"),
|
||||
).toBeDefined();
|
||||
});
|
||||
it("OTP real inputs reference descriptions and errors from their field context", async () => {
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" is-invalid :validation-errors="['Invalid']"><Label>Code</Label>${slots}<Description id="otp-help">Help</Description><FieldError id="otp-error"/></InputOTP>`,
|
||||
);
|
||||
await flushPromises();
|
||||
for (const input of inputs(w)) {
|
||||
expect(input.attributes("aria-describedby")?.split(/\s+/)).toContain(
|
||||
"otp-help",
|
||||
);
|
||||
expect(input.attributes("aria-describedby")?.split(/\s+/)).toContain(
|
||||
"otp-error",
|
||||
);
|
||||
expect(input.attributes("aria-invalid")).toBe("true");
|
||||
}
|
||||
});
|
||||
it("OTP consumes named server errors from the public Form", async () => {
|
||||
const w = fixture(
|
||||
`<Form :validation-errors="{code: 'Invalid code'}"><InputOTP :max-length="4" name="code">${slots}<FieldError/></InputOTP></Form>`,
|
||||
);
|
||||
await flushPromises();
|
||||
expect(w.get('[data-slot="input-otp"]').attributes("data-invalid")).toBe(
|
||||
"true",
|
||||
);
|
||||
expect(w.text()).toContain("Invalid code");
|
||||
});
|
||||
it("OTP inputClassName augments the structural input class", () => {
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" input-class-name="custom-input">${slots}</InputOTP>`,
|
||||
);
|
||||
expect(inputs(w)[0].classes()).toContain("custom-input");
|
||||
expect(inputs(w)[0].classes()).toContain("hv-input-otp__input");
|
||||
});
|
||||
it("OTP mask does not reveal plaintext through its visual value layer", () => {
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" default-value="1234" mask>${slots}</InputOTP>`,
|
||||
);
|
||||
expect(
|
||||
inputs(w).every((input) => input.attributes("type") === "password"),
|
||||
).toBe(true);
|
||||
expect(w.get('[data-slot="input-otp-slot-value"]').text()).not.toBe("1");
|
||||
});
|
||||
it("PaginationLink preserves an explicit aria-current override when not isActive", () => {
|
||||
const w = fixture(
|
||||
'<Pagination><PaginationLink aria-current="step">Next step</PaginationLink></Pagination>',
|
||||
);
|
||||
expect(w.get("button").attributes("aria-current")).toBe("step");
|
||||
});
|
||||
|
||||
it("OTP composed Label names the actual focusable input", async () => {
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4"><Label id="otp-label">Verification code</Label>${slots}</InputOTP>`,
|
||||
);
|
||||
await flushPromises();
|
||||
const actual = inputs(w)[0];
|
||||
const hasReference = actual
|
||||
.attributes("aria-labelledby")
|
||||
?.split(/\s+/)
|
||||
.includes("otp-label");
|
||||
const hasNativeLabel =
|
||||
Boolean(actual.attributes("id")) &&
|
||||
w.get("label").attributes("for") === actual.attributes("id");
|
||||
const hasExplicitName = actual
|
||||
.attributes("aria-label")
|
||||
?.includes("Verification code");
|
||||
expect(Boolean(hasReference || hasNativeLabel || hasExplicitName)).toBe(true);
|
||||
});
|
||||
it("OTP dynamically added readonly reaches the real input", async () => {
|
||||
const extra = ref<Record<string, unknown>>({});
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" default-value="12" v-bind="extra">${slots}</InputOTP>`,
|
||||
() => ({ extra }),
|
||||
);
|
||||
expect((inputs(w)[0].element as HTMLInputElement).readOnly).toBe(false);
|
||||
extra.value = { readonly: true };
|
||||
await flushPromises();
|
||||
expect((inputs(w)[0].element as HTMLInputElement).readOnly).toBe(true);
|
||||
});
|
||||
it("OTP edit dismisses the current server error response", async () => {
|
||||
const w = fixture(
|
||||
`<Form :validation-errors="{code:'Invalid code'}"><InputOTP :max-length="4" name="code" default-value="12">${slots}<FieldError/></InputOTP></Form>`,
|
||||
);
|
||||
await inputs(w)[0].setValue("9");
|
||||
await flushPromises();
|
||||
expect(
|
||||
w.get('[data-slot="input-otp"]').attributes("data-invalid"),
|
||||
).toBeUndefined();
|
||||
expect(w.text()).not.toContain("Invalid code");
|
||||
});
|
||||
it("OTP does not lose valid characters with a global RegExp filter", async () => {
|
||||
const filter = /\d/g;
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" :pattern="filter">${slots}</InputOTP>`,
|
||||
() => ({ filter }),
|
||||
);
|
||||
for (let i = 0; i < 4; i++) await inputs(w)[i].setValue(String(i + 1));
|
||||
await flushPromises();
|
||||
expect(
|
||||
inputs(w)
|
||||
.map((input) => (input.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("1234");
|
||||
});
|
||||
it("OTP Slot keydown.prevent cancels editing before the bottom-layer handler", async () => {
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" default-value="1234"><InputOTPGroup><InputOTPSlot v-for="i in 4" :key="i" :index="i-1" @keydown.prevent/></InputOTPGroup></InputOTP>`,
|
||||
);
|
||||
await inputs(w)[1].trigger("keydown", { key: "Delete" });
|
||||
await flushPromises();
|
||||
expect(
|
||||
inputs(w)
|
||||
.map((input) => (input.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("1234");
|
||||
});
|
||||
it("OTP capture handler arrays honor stopImmediatePropagation", async () => {
|
||||
const stop = (event: Event) => event.stopImmediatePropagation();
|
||||
const after = vi.fn();
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4" default-value="1234"><InputOTPGroup><InputOTPSlot v-for="i in 4" :key="i" :index="i-1" :onKeydownCapture="[stop,after]"/></InputOTPGroup></InputOTP>`,
|
||||
() => ({ stop, after }),
|
||||
);
|
||||
await inputs(w)[1].trigger("keydown", { key: "Delete" });
|
||||
await flushPromises();
|
||||
expect(after).not.toHaveBeenCalled();
|
||||
});
|
||||
it("OTP resizing retains existing empty slot indices", async () => {
|
||||
const length = ref(4);
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="length" default-value="1234"><InputOTPGroup><InputOTPSlot v-for="i in length" :key="i" :index="i-1"/></InputOTPGroup></InputOTP>`,
|
||||
() => ({ length }),
|
||||
);
|
||||
await inputs(w)[1].trigger("keydown", { key: "Delete" });
|
||||
await flushPromises();
|
||||
length.value = 5;
|
||||
await flushPromises();
|
||||
expect(
|
||||
inputs(w).map((input) => (input.element as HTMLInputElement).value),
|
||||
).toEqual(["1", "", "3", "4", ""]);
|
||||
});
|
||||
it("OTP form and validation examples have unique field IDs on the same page", async () => {
|
||||
const formDemo =
|
||||
await import("../../../apps/docs/demos/input-otp-form-example.vue");
|
||||
const validationDemo =
|
||||
await import("../../../apps/docs/demos/input-otp-with-validation.vue");
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
render: () => h("div", [h(formDemo.default), h(validationDemo.default)]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await flushPromises();
|
||||
const ids = wrapper
|
||||
.findAll("[id]")
|
||||
.map((element) => element.attributes("id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
it("OTP primitive fallback name cannot override a composed Label or explicit name", async () => {
|
||||
const w = fixture(
|
||||
`<InputOTP :max-length="4"><Label id="otp-composed">Verification code</Label>${slots}</InputOTP>`,
|
||||
);
|
||||
await flushPromises();
|
||||
for (const input of inputs(w))
|
||||
expect(input.attributes("aria-labelledby")?.split(/\s+/)).toContain(
|
||||
"otp-composed",
|
||||
);
|
||||
const explicit = fixture(
|
||||
`<InputOTP :max-length="4" aria-label="Security code">${slots}</InputOTP>`,
|
||||
);
|
||||
await flushPromises();
|
||||
expect(inputs(explicit)[0].attributes("aria-label")).toBe("Security code");
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, nextTick, ref } from "vue";
|
||||
import {
|
||||
Drawer,
|
||||
DrawerBackdrop,
|
||||
DrawerContent,
|
||||
DrawerDialog,
|
||||
DrawerHeading,
|
||||
} from "../../../packages/vue/src";
|
||||
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(async () => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
await flushPromises();
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
async function panel(controlled = false, preventDrag = false) {
|
||||
const dismissable = ref(true);
|
||||
const placement = ref<"bottom" | "left">("bottom");
|
||||
const requests = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: {
|
||||
Drawer,
|
||||
DrawerBackdrop,
|
||||
DrawerContent,
|
||||
DrawerDialog,
|
||||
DrawerHeading,
|
||||
},
|
||||
setup: () => ({
|
||||
dismissable,
|
||||
placement,
|
||||
requests,
|
||||
controlled,
|
||||
preventDrag,
|
||||
}),
|
||||
template: `<Drawer :open="controlled ? true : undefined" :default-open="true" @update:open="requests"><DrawerBackdrop :is-dismissable="dismissable"><DrawerContent :placement="placement"><DrawerDialog @pointerdown.capture="preventDrag && $event.preventDefault()"><DrawerHeading>Review drawer</DrawerHeading></DrawerDialog></DrawerContent></DrawerBackdrop></Drawer>`,
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
await flushPromises();
|
||||
const el = document.querySelector<HTMLElement>(
|
||||
'[data-slot="drawer-dialog"]',
|
||||
)!;
|
||||
Object.defineProperty(el, "offsetHeight", { configurable: true, value: 200 });
|
||||
Object.defineProperty(el, "offsetWidth", { configurable: true, value: 200 });
|
||||
let now = 1000;
|
||||
vi.spyOn(Date, "now").mockImplementation(() => now);
|
||||
function pointer(type: string, y: number, pointerId = 1) {
|
||||
now += 100;
|
||||
const e = new MouseEvent(type, {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
button: 0,
|
||||
clientY: y,
|
||||
});
|
||||
Object.defineProperty(e, "pointerId", { value: pointerId });
|
||||
el.dispatchEvent(e);
|
||||
}
|
||||
return { el, pointer, dismissable, placement, requests };
|
||||
}
|
||||
|
||||
it("controlled rejected drag close restores the still-open panel", async () => {
|
||||
const { el, pointer, requests } = await panel(true);
|
||||
pointer("pointerdown", 100);
|
||||
pointer("pointermove", 180);
|
||||
pointer("pointerup", 180);
|
||||
await flushPromises();
|
||||
expect(requests).toHaveBeenCalledWith(false);
|
||||
expect(el.isConnected).toBe(true);
|
||||
expect(el.style.transform).toBe("");
|
||||
expect(el.style.transition).not.toBe("none");
|
||||
});
|
||||
it("turning dismissable off during a drag cancels it without a close request", async () => {
|
||||
const { el, pointer, dismissable, requests } = await panel(true);
|
||||
pointer("pointerdown", 100);
|
||||
pointer("pointermove", 180);
|
||||
dismissable.value = false;
|
||||
await nextTick();
|
||||
pointer("pointerup", 180);
|
||||
await flushPromises();
|
||||
expect(requests).not.toHaveBeenCalled();
|
||||
expect(el.style.transform).toBe("");
|
||||
});
|
||||
it("placement change cancels the old-axis drag", async () => {
|
||||
const { el, pointer, placement } = await panel(true);
|
||||
pointer("pointerdown", 100);
|
||||
pointer("pointermove", 120);
|
||||
placement.value = "left";
|
||||
await nextTick();
|
||||
expect(el.style.transform).toBe("");
|
||||
expect(el.style.transition).not.toBe("none");
|
||||
});
|
||||
it("another pointer cannot move or finish the owning pointer gesture", async () => {
|
||||
const { el, pointer, requests } = await panel(true);
|
||||
pointer("pointerdown", 100, 1);
|
||||
pointer("pointermove", 180, 2);
|
||||
pointer("pointerup", 180, 2);
|
||||
await flushPromises();
|
||||
expect(requests).not.toHaveBeenCalled();
|
||||
expect(el.style.transform).toBe("");
|
||||
});
|
||||
|
||||
it("caller cancellation prevents starting the drag", async () => {
|
||||
const { el, pointer, requests } = await panel(true, true);
|
||||
pointer("pointerdown", 100);
|
||||
pointer("pointermove", 180);
|
||||
pointer("pointerup", 180);
|
||||
await flushPromises();
|
||||
expect(requests).not.toHaveBeenCalled();
|
||||
expect(el.style.transform).toBe("");
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref } from "vue";
|
||||
import { useDrawerDrag } from "../../../packages/vue/src/components/drawer/useDrawerDrag";
|
||||
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(() => wrappers.splice(0).forEach((w) => w.unmount()));
|
||||
async function gesture() {
|
||||
const open = ref(true);
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
const { dialogRef } = useDrawerDrag(
|
||||
ref("bottom"),
|
||||
ref(true),
|
||||
open,
|
||||
() => {
|
||||
open.value = false;
|
||||
},
|
||||
);
|
||||
// Keep the node mounted to model Presence retaining it through exit.
|
||||
return () => h("div", { ref: dialogRef, "data-slot": "drawer-dialog" });
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
const el = wrapper.element as HTMLElement;
|
||||
Object.defineProperty(el, "offsetHeight", { value: 200 });
|
||||
function pointer(type: string, clientY: number) {
|
||||
const event = new MouseEvent(type, { bubbles: true, button: 0, clientY });
|
||||
Object.defineProperty(event, "pointerId", { value: 1 });
|
||||
el.dispatchEvent(event);
|
||||
}
|
||||
return { el, open, pointer };
|
||||
}
|
||||
it("normal lost capture after an accepted drag-close preserves exit offset", async () => {
|
||||
const { el, open, pointer } = await gesture();
|
||||
pointer("pointerdown", 100);
|
||||
pointer("pointermove", 180);
|
||||
pointer("pointerup", 180);
|
||||
await nextTick();
|
||||
expect(open.value).toBe(false);
|
||||
expect(el.style.transform).toBe("translateY(80px)");
|
||||
pointer("lostpointercapture", 180);
|
||||
expect(el.style.transform).toBe("translateY(80px)");
|
||||
});
|
||||
it("programmatic close prevents retained exit node from continuing to drag", async () => {
|
||||
const { el, open, pointer } = await gesture();
|
||||
pointer("pointerdown", 100);
|
||||
pointer("pointermove", 120);
|
||||
open.value = false;
|
||||
await nextTick();
|
||||
const closingTransform = el.style.transform;
|
||||
pointer("pointermove", 180);
|
||||
expect(el.style.transform).toBe(closingTransform);
|
||||
});
|
||||
|
||||
it("reopening a retained exit node clears the old drag offset", async () => {
|
||||
const { el, open, pointer } = await gesture();
|
||||
pointer("pointerdown", 100);
|
||||
pointer("pointermove", 180);
|
||||
pointer("pointerup", 180);
|
||||
await nextTick();
|
||||
expect(el.style.transform).toBe("translateY(80px)");
|
||||
open.value = true;
|
||||
await nextTick();
|
||||
expect(el.style.transform).toBe("");
|
||||
pointer("lostpointercapture", 180);
|
||||
expect(el.style.transform).toBe("");
|
||||
});
|
||||
it("replacing the dialog releases and clears the old node, leaving the new node intact", async () => {
|
||||
let replace!: (el: HTMLElement) => void;
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
const { dialogRef } = useDrawerDrag(
|
||||
ref("bottom"),
|
||||
ref(true),
|
||||
ref(true),
|
||||
() => {},
|
||||
);
|
||||
replace = (el) => {
|
||||
dialogRef.value = el;
|
||||
};
|
||||
return () => h("div", { ref: dialogRef, "data-slot": "drawer-dialog" });
|
||||
},
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
await nextTick();
|
||||
const old = wrapper.element as HTMLElement;
|
||||
const release = vi.fn();
|
||||
Object.defineProperty(old, "setPointerCapture", { value: vi.fn() });
|
||||
Object.defineProperty(old, "releasePointerCapture", { value: release });
|
||||
for (const [type, clientY] of [
|
||||
["pointerdown", 100],
|
||||
["pointermove", 120],
|
||||
] as const) {
|
||||
const e = new MouseEvent(type, { bubbles: true, button: 0, clientY });
|
||||
Object.defineProperty(e, "pointerId", { value: 7 });
|
||||
old.dispatchEvent(e);
|
||||
}
|
||||
expect(old.style.transform).toBe("translateY(20px)");
|
||||
const next = document.createElement("div");
|
||||
next.style.transform = "scale(1.1)";
|
||||
replace(next);
|
||||
await nextTick();
|
||||
expect(release).toHaveBeenCalledWith(7);
|
||||
expect(old.style.transform).toBe("");
|
||||
expect(next.style.transform).toBe("scale(1.1)");
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h, ref } from "vue";
|
||||
import {
|
||||
Table,
|
||||
TableContent,
|
||||
TableBody,
|
||||
TableCollection,
|
||||
TableRow,
|
||||
TableCell,
|
||||
ToastProvider,
|
||||
ToastQueue,
|
||||
createToastFunction,
|
||||
ToastContent,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
} from "../../../packages/vue/src";
|
||||
const cleanup: (() => void)[] = [];
|
||||
afterEach(() => {
|
||||
cleanup
|
||||
.splice(0)
|
||||
.reverse()
|
||||
.forEach((fn) => fn());
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
it("TableBody preserves a populated TableCollection when #empty is supplied", () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(
|
||||
TableBody,
|
||||
{},
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
TableCollection,
|
||||
{ items: ["A"] },
|
||||
{
|
||||
default: ({ item }: { item: string }) =>
|
||||
h(TableRow, { rowKey: item }, () =>
|
||||
h(TableCell, {}, () => item),
|
||||
),
|
||||
},
|
||||
),
|
||||
empty: () => h("span", { "data-test": "empty" }, "Empty"),
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(false);
|
||||
});
|
||||
it("Toast root follows explicit Title and Description ids", async () => {
|
||||
const q = new ToastQueue();
|
||||
cleanup.push(() => q.destroy());
|
||||
const toast = createToastFunction(q);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(
|
||||
ToastProvider,
|
||||
{ queue: q, to: "body" },
|
||||
{
|
||||
default: () =>
|
||||
h(ToastContent, {}, () => [
|
||||
h(ToastTitle, { id: "custom-title" }, () => "Title"),
|
||||
h(
|
||||
ToastDescription,
|
||||
{ id: "custom-description" },
|
||||
() => "Description",
|
||||
),
|
||||
]),
|
||||
},
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
toast("Title", { timeout: 0 });
|
||||
await flushPromises();
|
||||
const root = document.querySelector('[data-slot="toast"]')!;
|
||||
expect(root.getAttribute("aria-labelledby")).toBe("custom-title");
|
||||
expect(root.getAttribute("aria-describedby")).toBe("custom-description");
|
||||
});
|
||||
it("title-only Toast does not reference a nonexistent description", async () => {
|
||||
const q = new ToastQueue();
|
||||
cleanup.push(() => q.destroy());
|
||||
const toast = createToastFunction(q);
|
||||
const w = mount(ToastProvider, {
|
||||
props: { queue: q, to: "body" },
|
||||
attachTo: document.body,
|
||||
});
|
||||
cleanup.push(() => w.unmount());
|
||||
toast("Title only", { timeout: 0 });
|
||||
await flushPromises();
|
||||
const root = document.querySelector('[data-slot="toast"]')!;
|
||||
const refs = (root.getAttribute("aria-describedby") ?? "")
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
for (const id of refs) expect(document.getElementById(id)).not.toBeNull();
|
||||
});
|
||||
|
||||
it("Toast part ids react to later id attribute changes", async () => {
|
||||
const title = ref("title-before");
|
||||
const description = ref("description-before");
|
||||
const q = new ToastQueue();
|
||||
cleanup.push(() => q.destroy());
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(
|
||||
ToastProvider,
|
||||
{ queue: q, to: "body" },
|
||||
{
|
||||
default: () =>
|
||||
h(ToastContent, {}, () => [
|
||||
h(ToastTitle, { id: title.value }, () => "Title"),
|
||||
h(
|
||||
ToastDescription,
|
||||
{ id: description.value },
|
||||
() => "Description",
|
||||
),
|
||||
]),
|
||||
},
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
createToastFunction(q)("Title", { timeout: 0 });
|
||||
await flushPromises();
|
||||
title.value = "title-after";
|
||||
description.value = "description-after";
|
||||
await flushPromises();
|
||||
const root = document.querySelector('[data-slot="toast"]')!;
|
||||
expect(root.querySelector('[data-slot="toast-title"]')?.id).toBe(
|
||||
"title-after",
|
||||
);
|
||||
expect(root.getAttribute("aria-labelledby")).toBe("title-after");
|
||||
expect(root.querySelector('[data-slot="toast-description"]')?.id).toBe(
|
||||
"description-after",
|
||||
);
|
||||
expect(root.getAttribute("aria-describedby")).toBe("description-after");
|
||||
});
|
||||
|
||||
it("wrapped collection transitions back to empty without swallowing its future rows", async () => {
|
||||
const items = ref<string[]>(["A"]);
|
||||
const Rows = defineComponent({
|
||||
name: "Rows",
|
||||
setup: () => () =>
|
||||
h(
|
||||
TableCollection,
|
||||
{ items: items.value },
|
||||
{
|
||||
default: ({ item }: { item: string }) =>
|
||||
h(TableRow, { rowKey: item }, () => h(TableCell, {}, () => item)),
|
||||
},
|
||||
),
|
||||
});
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(
|
||||
TableBody,
|
||||
{},
|
||||
{
|
||||
default: () => h(Rows),
|
||||
empty: () => h("span", { "data-test": "empty" }, "Empty"),
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
|
||||
items.value = [];
|
||||
await flushPromises();
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(0);
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
items.value = ["B"];
|
||||
await flushPromises();
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(false);
|
||||
});
|
||||
|
||||
it("forced empty state does not expose existing data rows", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(
|
||||
TableBody,
|
||||
{ empty: true },
|
||||
{
|
||||
default: () =>
|
||||
h(TableRow, { rowKey: "A" }, () =>
|
||||
h(TableCell, {}, () => "A"),
|
||||
),
|
||||
empty: () => h("span", { "data-test": "empty" }, "Empty"),
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("observes native rows rendered by an anonymous wrapper as data changes", async () => {
|
||||
const items = ref<string[]>([]);
|
||||
const Rows = () =>
|
||||
items.value.map((item) => h("tr", { key: item }, [h("td", item)]));
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(
|
||||
TableBody,
|
||||
{},
|
||||
{
|
||||
default: () => h(Rows),
|
||||
empty: () => h("span", { "data-test": "empty" }, "Empty"),
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
items.value = ["A"];
|
||||
await flushPromises();
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(false);
|
||||
expect(w.find("tbody").text()).toBe("A");
|
||||
items.value = [];
|
||||
await flushPromises();
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("switches forced empty off and restores the data row", async () => {
|
||||
const empty = ref(false);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, { selectionMode: "multiple" }, () =>
|
||||
h(
|
||||
TableBody,
|
||||
{ empty: empty.value },
|
||||
{
|
||||
default: () =>
|
||||
h(TableRow, { rowKey: "A" }, () =>
|
||||
h(TableCell, {}, () => "A"),
|
||||
),
|
||||
empty: () => h("span", { "data-test": "empty" }, "Empty"),
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
cleanup.push(() => w.unmount());
|
||||
await flushPromises();
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
|
||||
empty.value = true;
|
||||
await flushPromises();
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(0);
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
empty.value = false;
|
||||
await flushPromises();
|
||||
expect(w.findAll('[data-slot="table-row"]')).toHaveLength(1);
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import {
|
||||
Table,
|
||||
TableContent,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableColumnResizer,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
ToastProvider,
|
||||
ToastQueue,
|
||||
} from "../../../packages/vue/src";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const queues: ToastQueue[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
queues.splice(0).forEach((q) => q.destroy());
|
||||
if (vi.isFakeTimers()) vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
it("column defaultWidth is applied to its rendered column", () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableColumn, { defaultWidth: 180 }, () => "Name"),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
expect((w.get("th").element as HTMLElement).style.width).toBe("180px");
|
||||
});
|
||||
it("a selectable table supplies a keyboard focus entry without caller tabindex", () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, { selectionMode: "multiple" }, () =>
|
||||
h(TableBody, {}, () =>
|
||||
h(TableRow, { rowKey: "one" }, () =>
|
||||
h(TableCell, {}, () => "One"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
expect(w.findAll('[tabindex="0"]').length).toBeGreaterThan(0);
|
||||
});
|
||||
it("unmount during an active column drag releases capture", () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableColumn, {}, () => h(TableColumnResizer)),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const handle = w.get('[data-slot="table-column-resizer"]')
|
||||
.element as HTMLElement;
|
||||
const release = vi.fn();
|
||||
Object.defineProperty(handle, "setPointerCapture", { value: vi.fn() });
|
||||
Object.defineProperty(handle, "releasePointerCapture", { value: release });
|
||||
const th = w.get("th").element;
|
||||
Object.defineProperty(th, "getBoundingClientRect", {
|
||||
value: () => ({ width: 100 }),
|
||||
});
|
||||
for (const [type, x] of [
|
||||
["pointerdown", 100],
|
||||
["pointermove", 120],
|
||||
] as const) {
|
||||
const e = new MouseEvent(type, { bubbles: true, button: 0, clientX: x });
|
||||
Object.defineProperty(e, "pointerId", { value: 7 });
|
||||
handle.dispatchEvent(e);
|
||||
}
|
||||
w.unmount();
|
||||
expect(release).toHaveBeenCalledWith(7);
|
||||
});
|
||||
it("default action respects the caller's disabled state", () => {
|
||||
const q = new ToastQueue();
|
||||
queues.push(q);
|
||||
q.add(
|
||||
{ title: "Action", actionProps: { label: "Blocked", isDisabled: true } },
|
||||
{ timeout: 0 },
|
||||
);
|
||||
const w = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(w);
|
||||
const button = w.findAll("button").find((b) => b.text() === "Blocked")!;
|
||||
expect((button.element as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
it("the default toast demo escapes the containing preview", async () => {
|
||||
vi.useFakeTimers();
|
||||
const mod = await import("../../../apps/docs/demos/toast-default.vue");
|
||||
const host = document.createElement("div");
|
||||
host.className = "component-preview-container";
|
||||
document.body.append(host);
|
||||
const w = mount(mod.default, { attachTo: host });
|
||||
wrappers.push(w);
|
||||
await w.get("button").trigger("click");
|
||||
await flushPromises();
|
||||
const region = document.querySelector('[data-slot="toast-region"]')!;
|
||||
expect(region).not.toBeNull();
|
||||
expect(region.closest(".component-preview-container")).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import {
|
||||
ToastQueue,
|
||||
ToastProvider,
|
||||
toast,
|
||||
toastQueue,
|
||||
createToastFunction,
|
||||
Table,
|
||||
TableContent,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableColumn,
|
||||
TableColumnResizer,
|
||||
TableSortableColumnHeader,
|
||||
} from "../../../packages/vue/src";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const queues: ToastQueue[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
queues.splice(0).forEach((q) => q.destroy());
|
||||
toastQueue.clear();
|
||||
if (vi.isFakeTimers()) vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
it("the exported toast helper is rendered by the default provider", async () => {
|
||||
vi.useFakeTimers();
|
||||
const w = mount(ToastProvider);
|
||||
wrappers.push(w);
|
||||
toast("global notification", { timeout: 0 });
|
||||
await flushPromises();
|
||||
expect(w.text()).toContain("global notification");
|
||||
});
|
||||
it("row click listener is forwarded exactly once", async () => {
|
||||
const onClick = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableBody, {}, () =>
|
||||
h(TableRow, { rowKey: "one", onClick }, () =>
|
||||
h(TableCell, {}, () => "One"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get("tr").trigger("click");
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("caller preventDefault vetoes sort before the sort proposal", async () => {
|
||||
const change = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, { onSortChange: change }, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableRow, { rowKey: "head" }, () =>
|
||||
h(
|
||||
TableSortableColumnHeader,
|
||||
{
|
||||
columnKey: "name",
|
||||
onClick: (e: MouseEvent) => e.preventDefault(),
|
||||
},
|
||||
() => "Name",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get("button").trigger("click");
|
||||
expect(change).not.toHaveBeenCalled();
|
||||
});
|
||||
it("the first column resize handle changes its containing column", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableRow, { rowKey: "head" }, () => [
|
||||
h(TableColumn, {}, () => ["First", h(TableColumnResizer)]),
|
||||
h(TableColumn, {}, () => "Second"),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
const th = w.get("th").element as HTMLElement;
|
||||
Object.defineProperty(th, "getBoundingClientRect", {
|
||||
value: () => ({ width: 100 }),
|
||||
});
|
||||
await w
|
||||
.get('[data-slot="table-column-resizer"]')
|
||||
.trigger("keydown", { key: "ArrowRight" });
|
||||
expect(th.style.width).toBe("108px");
|
||||
});
|
||||
it("changing provider queue subscribes to and renders the new queue", async () => {
|
||||
const a = new ToastQueue(),
|
||||
b = new ToastQueue();
|
||||
queues.push(a, b);
|
||||
const w = mount(ToastProvider, { props: { queue: a } });
|
||||
wrappers.push(w);
|
||||
await w.setProps({ queue: b });
|
||||
b.add({ title: "new queue" }, { timeout: 0 });
|
||||
await flushPromises();
|
||||
expect(w.text()).toContain("new queue");
|
||||
});
|
||||
it("a completed promise cannot overwrite an explicitly replaced loading entry", async () => {
|
||||
const q = new ToastQueue({ exitDuration: 0 });
|
||||
queues.push(q);
|
||||
const api = createToastFunction(q);
|
||||
let resolve!: (n: number) => void;
|
||||
const id = api.promise(
|
||||
new Promise<number>((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
{ loading: "loading", success: "old result", error: "failed" },
|
||||
);
|
||||
api.update(id, "new content", { timeout: 0 });
|
||||
resolve(1);
|
||||
await flushPromises();
|
||||
expect(q.visibleToasts.find((t) => t.key === id)?.content.title).toBe(
|
||||
"new content",
|
||||
);
|
||||
});
|
||||
it("default loading content renders the shared Spinner", () => {
|
||||
const q = new ToastQueue();
|
||||
queues.push(q);
|
||||
q.add({ title: "Loading", isLoading: true }, { timeout: 0 });
|
||||
const w = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(w);
|
||||
expect(w.find('[data-slot="spinner"]').exists()).toBe(true);
|
||||
});
|
||||
it("default action forwards its callback and visual options", async () => {
|
||||
const action = vi.fn();
|
||||
const q = new ToastQueue();
|
||||
queues.push(q);
|
||||
q.add(
|
||||
{
|
||||
title: "Action",
|
||||
actionProps: { label: "Retry", onClick: action, variant: "danger" },
|
||||
},
|
||||
{ timeout: 0 },
|
||||
);
|
||||
const w = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(w);
|
||||
const button = w.findAll("button").find((b) => b.text() === "Retry")!;
|
||||
await button.trigger("click");
|
||||
expect(action).toHaveBeenCalledTimes(1);
|
||||
expect(button.classes()).toContain("hv-button--danger");
|
||||
});
|
||||
@@ -0,0 +1,392 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, h, nextTick, ref } from "vue";
|
||||
import {
|
||||
Table,
|
||||
TableContent,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableColumnResizer,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableSortableColumnHeader,
|
||||
ToastProvider,
|
||||
ToastQueue,
|
||||
} from "../../../packages/vue/src";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const queues: ToastQueue[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
queues.splice(0).forEach((q) => q.destroy());
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
function table(
|
||||
options: Record<string, unknown> = {},
|
||||
keys: (string | number)[] = [0, "0", "", 3],
|
||||
) {
|
||||
const items = ref(keys);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, () =>
|
||||
h(TableContent, options, () => [
|
||||
h(TableHeader, () => [
|
||||
h(TableColumn, { id: "name", isRowHeader: true }, () => "Name"),
|
||||
h(TableColumn, { id: "value" }, () => "Value"),
|
||||
]),
|
||||
h(TableBody, () =>
|
||||
items.value.map((key) =>
|
||||
h(TableRow, { rowKey: key, key }, () => [
|
||||
h(TableCell, () => String(key)),
|
||||
h(TableCell, () => "Value"),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
return { w, items };
|
||||
}
|
||||
it("roves across numeric/string/empty keys, skips disabled rows and extends a range", async () => {
|
||||
const { w } = table({ selectionMode: "multiple", disabledKeys: ["0"] });
|
||||
await nextTick();
|
||||
const rows = w.findAll("tbody tr");
|
||||
expect(rows.map((r) => r.attributes("tabindex"))).toEqual([
|
||||
"0",
|
||||
"-1",
|
||||
"-1",
|
||||
"-1",
|
||||
]);
|
||||
(rows[0].element as HTMLElement).focus();
|
||||
await rows[0].trigger("keydown", { key: " " });
|
||||
await rows[0].trigger("keydown", { key: "ArrowDown", shiftKey: true });
|
||||
await nextTick();
|
||||
expect(document.activeElement).toBe(rows[2].element);
|
||||
expect(
|
||||
w.findComponent(TableContent).emitted("selectionChange")?.at(-1),
|
||||
).toEqual([[0, ""]]);
|
||||
await rows[2].trigger("keydown", { key: "a", ctrlKey: true });
|
||||
expect(
|
||||
w.findComponent(TableContent).emitted("selectionChange")?.at(-1),
|
||||
).toEqual([[0, "", 3]]);
|
||||
});
|
||||
it("uses accepted controlled selection and permits the same rejected range proposal again", async () => {
|
||||
const { w } = table({ selectionMode: "multiple", selectedKeys: [] });
|
||||
await nextTick();
|
||||
const rows = w.findAll("tbody tr");
|
||||
(rows[0].element as HTMLElement).focus();
|
||||
await rows[2].trigger("click", { shiftKey: true });
|
||||
await rows[2].trigger("click", { shiftKey: true });
|
||||
expect(w.findComponent(TableContent).emitted("selectionChange")).toEqual([
|
||||
[[0, "0", ""]],
|
||||
[[0, "0", ""]],
|
||||
]);
|
||||
expect(rows.every((row) => row.attributes("aria-selected") === "false")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
it("moves through cells and honors preventDefault without stealing child controls", async () => {
|
||||
const { w } = table();
|
||||
await nextTick();
|
||||
const rows = w.findAll("tbody tr");
|
||||
(rows[0].element as HTMLElement).focus();
|
||||
await rows[0].trigger("keydown", { key: "ArrowRight" });
|
||||
expect(document.activeElement).toBe(rows[0].findAll("th,td")[0].element);
|
||||
await w.get("tbody th").trigger("keydown", { key: "ArrowDown" });
|
||||
expect(document.activeElement).toBe(rows[1].findAll("th,td")[0].element);
|
||||
});
|
||||
it("refreshes DOM order after keyed reordering", async () => {
|
||||
const { w, items } = table();
|
||||
await nextTick();
|
||||
items.value = [3, "", 0, "0"];
|
||||
await nextTick();
|
||||
const rows = w.findAll("tbody tr");
|
||||
(rows[0].element as HTMLElement).focus();
|
||||
await rows[0].trigger("keydown", { key: "ArrowDown" });
|
||||
expect(document.activeElement).toBe(rows[1].element);
|
||||
});
|
||||
it("requests and focuses a previously unmounted logical row", async () => {
|
||||
const visible = ref([0]);
|
||||
const onFocusRow = vi.fn((key: string | number) => {
|
||||
visible.value = [Number(key)];
|
||||
});
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, () =>
|
||||
h(TableContent, { rowKeys: [0, 1, 2], onFocusRow }, () =>
|
||||
h(TableBody, () =>
|
||||
visible.value.map((key) =>
|
||||
h(TableRow, { key, rowKey: key }, () =>
|
||||
h(TableCell, () => key),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
await nextTick();
|
||||
(w.get("tbody tr").element as HTMLElement).focus();
|
||||
await w.get("tbody tr").trigger("keydown", { key: "ArrowDown" });
|
||||
await nextTick();
|
||||
expect(onFocusRow).toHaveBeenCalledWith(1, 1);
|
||||
expect(document.activeElement?.textContent).toBe("1");
|
||||
});
|
||||
it("maps row headers and tree-column slot metadata only to their actual columns", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, () =>
|
||||
h(TableContent, { treeColumn: "name" }, () => [
|
||||
h(TableHeader, () => [
|
||||
h(TableColumn, { id: "name", isRowHeader: true }, () => "Name"),
|
||||
h(TableColumn, { id: "value" }, () => "Value"),
|
||||
]),
|
||||
h(TableBody, () =>
|
||||
h(TableRow, { rowKey: "a", hasChildItems: true }, () => [
|
||||
h(
|
||||
TableCell,
|
||||
{},
|
||||
{
|
||||
default: ({ isTreeColumn }: { isTreeColumn: boolean }) =>
|
||||
String(isTreeColumn),
|
||||
},
|
||||
),
|
||||
h(
|
||||
TableCell,
|
||||
{},
|
||||
{
|
||||
default: ({ isTreeColumn }: { isTreeColumn: boolean }) =>
|
||||
String(isTreeColumn),
|
||||
},
|
||||
),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await nextTick();
|
||||
expect(w.get("tbody th").attributes("scope")).toBe("row");
|
||||
expect(w.get("tbody th").text()).toBe("true");
|
||||
expect(w.get("tbody td").text()).toBe("false");
|
||||
});
|
||||
it("sorts only the correct column and only once per click", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, () =>
|
||||
h(TableContent, () =>
|
||||
h(TableHeader, () =>
|
||||
["a", "b"].map((id) =>
|
||||
h(TableColumn, { id, allowsSorting: true }, () =>
|
||||
h(TableSortableColumnHeader, { columnKey: id }, () => id),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.findAll("button")[1].trigger("click");
|
||||
expect(w.findComponent(TableContent).emitted("sortChange")).toEqual([
|
||||
[{ column: "b", direction: "ascending" }],
|
||||
]);
|
||||
expect(
|
||||
w.findAll('[data-slot="table-sortable-column-indicator"]'),
|
||||
).toHaveLength(1);
|
||||
expect(w.findAll("th").map((th) => th.attributes("aria-sort"))).toEqual([
|
||||
"none",
|
||||
"ascending",
|
||||
]);
|
||||
});
|
||||
it("controlled column width proposals respect max, RTL and rejection/retry", async () => {
|
||||
const update = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, { dir: "rtl" }, () =>
|
||||
h(TableContent, () =>
|
||||
h(TableHeader, () =>
|
||||
h(
|
||||
TableColumn,
|
||||
{ width: 100, maxWidth: 110, "onUpdate:width": update },
|
||||
() => h(TableColumnResizer),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
const th = w.get("th").element as HTMLElement;
|
||||
vi.spyOn(th, "getBoundingClientRect").mockReturnValue({
|
||||
width: 100,
|
||||
} as DOMRect);
|
||||
const handle = w.get('[role="separator"]');
|
||||
await handle.trigger("keydown", { key: "ArrowLeft", shiftKey: true });
|
||||
await handle.trigger("keydown", { key: "ArrowLeft", shiftKey: true });
|
||||
expect(update.mock.calls).toEqual([[110], [110]]);
|
||||
expect(th.style.width).toBe("100px");
|
||||
});
|
||||
it("default toast anatomy separates indicator/text/actions; overflow is inert", async () => {
|
||||
const q = new ToastQueue();
|
||||
queues.push(q);
|
||||
for (let i = 0; i < 4; i++)
|
||||
q.add(
|
||||
{
|
||||
title: "Title",
|
||||
description: "Description",
|
||||
actionProps: { label: "Action" },
|
||||
},
|
||||
{ timeout: 0 },
|
||||
);
|
||||
const w = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(w);
|
||||
await nextTick();
|
||||
const card = w.get('[data-slot="toast"]');
|
||||
expect(
|
||||
card.get('[data-slot="toast-content"]').findAll("button"),
|
||||
).toHaveLength(0);
|
||||
expect(card.findAll(':scope > [data-slot="toast-indicator"]')).toHaveLength(
|
||||
1,
|
||||
);
|
||||
expect(w.get('[data-hidden="true"]').attributes("inert")).toBeDefined();
|
||||
});
|
||||
it("Alt+T enters the live stack, close focuses its neighbor, Escape returns to trigger", async () => {
|
||||
const trigger = document.createElement("button");
|
||||
document.body.append(trigger);
|
||||
trigger.focus();
|
||||
const q = new ToastQueue();
|
||||
queues.push(q);
|
||||
const first = q.add({ title: "First" }, { timeout: 0 });
|
||||
const second = q.add({ title: "Second" }, { timeout: 0 });
|
||||
const w = mount(ToastProvider, {
|
||||
props: { queue: q },
|
||||
attachTo: document.body,
|
||||
});
|
||||
wrappers.push(w);
|
||||
await nextTick();
|
||||
document.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { code: "KeyT", altKey: true, bubbles: true }),
|
||||
);
|
||||
await nextTick();
|
||||
expect(document.activeElement?.textContent).toBe("Second");
|
||||
q.close(second);
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(document.activeElement?.textContent).toBe("First");
|
||||
document.activeElement?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
|
||||
);
|
||||
await nextTick();
|
||||
expect(document.activeElement).toBe(trigger);
|
||||
});
|
||||
it("one provider unmount cannot release another provider hover pause on the same queue", async () => {
|
||||
vi.useFakeTimers();
|
||||
const q = new ToastQueue({ exitDuration: 0 });
|
||||
queues.push(q);
|
||||
q.add({ title: "Shared" }, { timeout: 1000 });
|
||||
const a = mount(ToastProvider, { props: { queue: q } }),
|
||||
b = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(b);
|
||||
a.element.dispatchEvent(new MouseEvent("pointerenter"));
|
||||
b.element.dispatchEvent(new MouseEvent("pointerenter"));
|
||||
a.unmount();
|
||||
vi.advanceTimersByTime(2000);
|
||||
expect(q.visibleToasts).toHaveLength(1);
|
||||
});
|
||||
it("default toast action stopImmediatePropagation vetoes automatic close", async () => {
|
||||
const queue = new ToastQueue();
|
||||
queues.push(queue);
|
||||
queue.add(
|
||||
{
|
||||
title: "Action",
|
||||
actionProps: {
|
||||
label: "Keep",
|
||||
onClick: (event) => event.stopImmediatePropagation(),
|
||||
},
|
||||
},
|
||||
{ timeout: 0 },
|
||||
);
|
||||
const w = mount(ToastProvider, { props: { queue } });
|
||||
wrappers.push(w);
|
||||
await w.get('[data-slot="toast-action-button"]').trigger("click");
|
||||
expect(queue.getExitingKeys().size).toBe(0);
|
||||
expect(queue.visibleToasts).toHaveLength(1);
|
||||
});
|
||||
it("load-more observes its scroll container and deduplicates an in-flight request", async () => {
|
||||
const observers: {
|
||||
callback: IntersectionObserverCallback;
|
||||
options?: IntersectionObserverInit;
|
||||
disconnect: ReturnType<typeof vi.fn>;
|
||||
}[] = [];
|
||||
vi.stubGlobal(
|
||||
"IntersectionObserver",
|
||||
class {
|
||||
disconnect = vi.fn();
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
constructor(
|
||||
callback: IntersectionObserverCallback,
|
||||
options?: IntersectionObserverInit,
|
||||
) {
|
||||
observers.push({ callback, options, disconnect: this.disconnect });
|
||||
}
|
||||
},
|
||||
);
|
||||
const { TableLoadMoreItem, TableLoadMoreContent, TableScrollContainer } =
|
||||
await import("../../../packages/vue/src");
|
||||
const loading = ref(false);
|
||||
const load = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, () =>
|
||||
h(TableScrollContainer, () =>
|
||||
h(TableContent, () =>
|
||||
h(TableBody, () =>
|
||||
h(
|
||||
TableLoadMoreItem,
|
||||
{ isLoading: loading.value, onLoadMore: load },
|
||||
() => h(TableLoadMoreContent, () => "Loading"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
const observer = observers.at(-1)!;
|
||||
expect(observer.options?.root).toBe(
|
||||
w.get('[data-slot="table-scroll-container"]').element,
|
||||
);
|
||||
expect(
|
||||
w.find('tbody > tr > td > [data-slot="table-load-more-content"]').exists(),
|
||||
).toBe(true);
|
||||
const entry = [{ isIntersecting: true }] as IntersectionObserverEntry[];
|
||||
observer.callback(entry, {} as IntersectionObserver);
|
||||
observer.callback(entry, {} as IntersectionObserver);
|
||||
expect(load).toHaveBeenCalledTimes(1);
|
||||
loading.value = true;
|
||||
await nextTick();
|
||||
loading.value = false;
|
||||
await nextTick();
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
w.unmount();
|
||||
wrappers.pop();
|
||||
observer.callback(entry, {} as IntersectionObserver);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import {
|
||||
ToastQueue,
|
||||
ToastProvider,
|
||||
createToastFunction,
|
||||
Table,
|
||||
TableContent,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableSortableColumnHeader,
|
||||
} from "../../../packages/vue/src";
|
||||
const queues: ToastQueue[] = [];
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
queues.splice(0).forEach((q) => q.destroy());
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
function queue() {
|
||||
const q = new ToastQueue({ exitDuration: 0 });
|
||||
queues.push(q);
|
||||
return q;
|
||||
}
|
||||
it("toasts added while paused start their countdown on resume", () => {
|
||||
vi.useFakeTimers();
|
||||
const q = queue();
|
||||
q.pauseAll();
|
||||
q.add({ title: "paused-add" }, { timeout: 100 });
|
||||
vi.advanceTimersByTime(500);
|
||||
expect(q.visibleToasts).toHaveLength(1);
|
||||
q.resumeAll();
|
||||
vi.advanceTimersByTime(101);
|
||||
expect(q.visibleToasts).toHaveLength(0);
|
||||
});
|
||||
it("a repeated resume does not leave a stale countdown after a later pause", () => {
|
||||
vi.useFakeTimers();
|
||||
const q = queue();
|
||||
q.add({ title: "x" }, { timeout: 1000 });
|
||||
vi.advanceTimersByTime(100);
|
||||
q.resumeAll();
|
||||
vi.advanceTimersByTime(100);
|
||||
q.pauseAll();
|
||||
vi.advanceTimersByTime(2000);
|
||||
expect(q.visibleToasts).toHaveLength(1);
|
||||
});
|
||||
it("promise resolving after early close does not create a replacement notification", async () => {
|
||||
const q = queue();
|
||||
const toast = createToastFunction(q);
|
||||
let resolve!: (n: number) => void;
|
||||
const id = toast.promise(
|
||||
new Promise<number>((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
{ loading: "loading", success: "done", error: "error" },
|
||||
);
|
||||
toast.close(id);
|
||||
expect(q.visibleToasts).toHaveLength(0);
|
||||
resolve(1);
|
||||
await flushPromises();
|
||||
expect(q.visibleToasts).toHaveLength(0);
|
||||
});
|
||||
it("variant demo renders actual Vue labels rather than JSX-like literals", async () => {
|
||||
const mod = await import("../../../apps/docs/demos/toast-variants.vue");
|
||||
const w = mount(mod.default);
|
||||
wrappers.push(w);
|
||||
expect(w.findAll("button").map((b) => b.text())).toEqual([
|
||||
"默认 Toast",
|
||||
"强调 Toast",
|
||||
"成功 Toast",
|
||||
"警告 Toast",
|
||||
"危险 Toast",
|
||||
]);
|
||||
});
|
||||
it("a row action does not select the enclosing row", async () => {
|
||||
const onSelection = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(
|
||||
Table,
|
||||
{ selectionMode: "multiple", onSelectionChange: onSelection },
|
||||
() =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableBody, {}, () =>
|
||||
h(TableRow, { rowKey: "a" }, () =>
|
||||
h(TableCell, {}, () =>
|
||||
h("button", { type: "button" }, "Edit"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get("button").trigger("click");
|
||||
expect(onSelection).not.toHaveBeenCalled();
|
||||
});
|
||||
it("sortable header invokes a user click listener only once", async () => {
|
||||
const onClick = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableRow, { rowKey: "head" }, () =>
|
||||
h(
|
||||
TableSortableColumnHeader,
|
||||
{ columnKey: "a", onClick },
|
||||
() => "A",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get("button").trigger("click");
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("hovering the notification region pauses its timeout", async () => {
|
||||
vi.useFakeTimers();
|
||||
const q = queue();
|
||||
q.add({ title: "hover" }, { timeout: 100 });
|
||||
const w = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(w);
|
||||
await w.get('[data-slot="toast-region"]').trigger("pointerenter");
|
||||
vi.advanceTimersByTime(101);
|
||||
expect(q.visibleToasts).toHaveLength(1);
|
||||
});
|
||||
it("default provider renders queued content without requiring a custom renderer", () => {
|
||||
const q = queue();
|
||||
q.add({ title: "default content" }, { timeout: 0 });
|
||||
const w = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(w);
|
||||
expect(w.text()).toContain("default content");
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { nextTick, defineComponent, h } from "vue";
|
||||
import {
|
||||
ToastQueue,
|
||||
ToastProvider,
|
||||
Table,
|
||||
TableContent,
|
||||
TableHeader,
|
||||
TableColumn,
|
||||
TableColumnResizer,
|
||||
TableBody,
|
||||
TableRow,
|
||||
TableCell,
|
||||
} from "../../../packages/vue/src";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const queues: ToastQueue[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
queues.splice(0).forEach((q) => q.destroy());
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
it("column minWidth constrains keyboard resizing", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableColumn, { minWidth: 160 }, () => h(TableColumnResizer)),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
const th = w.get("th").element as HTMLElement;
|
||||
Object.defineProperty(th, "getBoundingClientRect", {
|
||||
value: () => ({ width: 160 }),
|
||||
});
|
||||
await w
|
||||
.get('[data-slot="table-column-resizer"]')
|
||||
.trigger("keydown", { key: "ArrowLeft" });
|
||||
expect(parseFloat(th.style.width)).toBeGreaterThanOrEqual(160);
|
||||
});
|
||||
it("an unrelated pointer cancellation does not reset an active column drag", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableColumn, {}, () => h(TableColumnResizer)),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
const th = w.get("th").element as HTMLElement;
|
||||
Object.defineProperty(th, "getBoundingClientRect", {
|
||||
value: () => ({ width: 100 }),
|
||||
});
|
||||
const handle = w.get('[data-slot="table-column-resizer"]').element;
|
||||
const pointer = (type: string, id: number, x: number) => {
|
||||
const e = new MouseEvent(type, { bubbles: true, button: 0, clientX: x });
|
||||
Object.defineProperty(e, "pointerId", { value: id });
|
||||
handle.dispatchEvent(e);
|
||||
};
|
||||
pointer("pointerdown", 1, 100);
|
||||
pointer("pointermove", 1, 120);
|
||||
await nextTick();
|
||||
expect(th.style.width).toBe("120px");
|
||||
pointer("pointercancel", 2, 120);
|
||||
await nextTick();
|
||||
expect(th.style.width).toBe("120px");
|
||||
});
|
||||
it("Space selects the focused selectable table row", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, { selectionMode: "multiple" }, () =>
|
||||
h(TableBody, {}, () =>
|
||||
h(TableRow, { rowKey: "one", tabindex: 0 }, () =>
|
||||
h(TableCell, {}, () => "One"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
const row = w.get("tr");
|
||||
(row.element as HTMLElement).focus();
|
||||
expect(document.activeElement).toBe(row.element);
|
||||
await row.trigger("keydown", { key: " ", code: "Space" });
|
||||
expect(row.attributes("aria-selected")).toBe("true");
|
||||
});
|
||||
it("default toast groups title and description in its content layout", () => {
|
||||
const q = new ToastQueue();
|
||||
queues.push(q);
|
||||
q.add({ title: "Title", description: "Description" }, { timeout: 0 });
|
||||
const w = mount(ToastProvider, { props: { queue: q } });
|
||||
wrappers.push(w);
|
||||
expect(
|
||||
w.find('[data-slot="toast-content"] [data-slot="toast-title"]').exists(),
|
||||
).toBe(true);
|
||||
expect(
|
||||
w
|
||||
.find('[data-slot="toast-content"] [data-slot="toast-description"]')
|
||||
.exists(),
|
||||
).toBe(true);
|
||||
});
|
||||
it("the provider exposed toast factory uses the current queue after replacement", async () => {
|
||||
const a = new ToastQueue({ exitDuration: 0 }),
|
||||
b = new ToastQueue({ exitDuration: 0 });
|
||||
queues.push(a, b);
|
||||
const w = mount(ToastProvider, { props: { queue: a } });
|
||||
wrappers.push(w);
|
||||
const api = w.vm as unknown as {
|
||||
toast: () => (message: string, options: { timeout: number }) => string;
|
||||
};
|
||||
api.toast()("initial", { timeout: 0 });
|
||||
await w.setProps({ queue: b });
|
||||
api.toast()("current", { timeout: 0 });
|
||||
await flushPromises();
|
||||
expect(b.visibleToasts.map((t) => t.content.title)).toContain("current");
|
||||
});
|
||||
it("selection demo select-all checks the actual row controls", async () => {
|
||||
const mod = await import("../../../apps/docs/demos/table-selection.vue");
|
||||
const w = mount(mod.default);
|
||||
wrappers.push(w);
|
||||
const controls = w.findAll('input[type="checkbox"]');
|
||||
expect(controls.length).toBeGreaterThan(1);
|
||||
await controls[0].setValue(true);
|
||||
await flushPromises();
|
||||
expect(
|
||||
controls.slice(1).every((c) => (c.element as HTMLInputElement).checked),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h } from "vue";
|
||||
import {
|
||||
ToastQueue,
|
||||
ToastProvider,
|
||||
Table,
|
||||
TableContent,
|
||||
TableBody,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableColumn,
|
||||
} from "../../../packages/vue/src";
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const queues: ToastQueue[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
queues.splice(0).forEach((q) => q.destroy());
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
it("after queue swap the visible toast close action closes the new queue", async () => {
|
||||
const a = new ToastQueue({ exitDuration: 0 }),
|
||||
b = new ToastQueue({ exitDuration: 0 });
|
||||
queues.push(a, b);
|
||||
const w = mount(ToastProvider, { props: { queue: a } });
|
||||
wrappers.push(w);
|
||||
await w.setProps({ queue: b });
|
||||
b.add({ title: "new queue toast" }, { timeout: 0 });
|
||||
await flushPromises();
|
||||
expect(w.text()).toContain("new queue toast");
|
||||
await w.get('button[data-slot="toast-close"]').trigger("click");
|
||||
await flushPromises();
|
||||
expect(b.visibleToasts).toHaveLength(0);
|
||||
});
|
||||
it("row event arrays respect stopImmediatePropagation before other handlers and selection", async () => {
|
||||
const second = vi.fn(),
|
||||
select = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(
|
||||
TableContent,
|
||||
{ selectionMode: "multiple", onSelectionChange: select },
|
||||
() =>
|
||||
h(TableBody, {}, () =>
|
||||
h(
|
||||
TableRow,
|
||||
{
|
||||
rowKey: "one",
|
||||
onClick: [
|
||||
(e: MouseEvent) => e.stopImmediatePropagation(),
|
||||
second,
|
||||
],
|
||||
},
|
||||
() => h(TableCell, {}, () => "One"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get("tr").trigger("click");
|
||||
expect(second).not.toHaveBeenCalled();
|
||||
expect(select).not.toHaveBeenCalled();
|
||||
});
|
||||
it("a sortable column forwards user click and honors its cancellation", async () => {
|
||||
const sort = vi.fn(),
|
||||
click = vi.fn((e: MouseEvent) => e.preventDefault());
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, { onSortChange: sort }, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(
|
||||
TableColumn,
|
||||
{ id: "name", allowsSorting: true, onClick: click },
|
||||
() => "Name",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
wrappers.push(w);
|
||||
await w.get("th").trigger("click");
|
||||
expect(click).toHaveBeenCalledTimes(1);
|
||||
expect(sort).not.toHaveBeenCalled();
|
||||
});
|
||||
it("baseline table header creates a header row around its columns", async () => {
|
||||
const mod = await import("../../../apps/docs/demos/table-sorting.vue");
|
||||
const w = mount(mod.default);
|
||||
wrappers.push(w);
|
||||
expect(w.find("thead > tr > th").exists()).toBe(true);
|
||||
});
|
||||
it("baseline sorting exposes the current direction on the real column header", async () => {
|
||||
const mod = await import("../../../apps/docs/demos/table-sorting.vue");
|
||||
const w = mount(mod.default);
|
||||
wrappers.push(w);
|
||||
const column = w.findAll("th")[1];
|
||||
await column.trigger("click");
|
||||
expect(column.attributes("aria-sort")).toBe("ascending");
|
||||
});
|
||||
@@ -0,0 +1,444 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount, flushPromises } from "@vue/test-utils";
|
||||
import { defineComponent, h, ref, nextTick, computed } from "vue";
|
||||
import {
|
||||
Checkbox,
|
||||
CheckboxContent,
|
||||
CheckboxControl,
|
||||
CheckboxIndicator,
|
||||
EmptyState,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableColumn,
|
||||
TableCollection,
|
||||
TableContent,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
ToastActionButton,
|
||||
ToastCloseButton,
|
||||
ToastContent,
|
||||
ToastDescription,
|
||||
ToastIndicator,
|
||||
ToastProvider,
|
||||
ToastQueue,
|
||||
ToastTitle,
|
||||
createToastFunction,
|
||||
} from "../../../packages/vue/src";
|
||||
|
||||
const wrappers: ReturnType<typeof mount>[] = [];
|
||||
const queues: ToastQueue[] = [];
|
||||
afterEach(() => {
|
||||
wrappers.splice(0).forEach((w) => w.unmount());
|
||||
queues.splice(0).forEach((q) => q.destroy());
|
||||
if (vi.isFakeTimers()) vi.runOnlyPendingTimers();
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function mountDemo(setup: () => unknown, render?: () => unknown) {
|
||||
const w = mount(
|
||||
defineComponent(
|
||||
render
|
||||
? { setup: setup as never, render: render as never }
|
||||
: { setup: setup as never },
|
||||
),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(w);
|
||||
return w;
|
||||
}
|
||||
|
||||
it("TableBody #empty renders EmptyState without a data row", () => {
|
||||
const w = mountDemo(
|
||||
() => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, { "aria-label": "空表格" }, () => [
|
||||
h(TableHeader, {}, () => h(TableColumn, {}, () => "姓名")),
|
||||
h(
|
||||
TableBody,
|
||||
{ colspan: 1 },
|
||||
{
|
||||
empty: () =>
|
||||
h(EmptyState, {}, () =>
|
||||
h("span", { class: "msg" }, "未找到结果"),
|
||||
),
|
||||
},
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
const body = w.get("tbody");
|
||||
expect(body.attributes("data-empty")).toBeDefined();
|
||||
expect(w.findAll("tr[data-slot='table-row']").length).toBe(0);
|
||||
expect(w.find(".msg").text()).toBe("未找到结果");
|
||||
expect(w.find("td[data-slot='table-empty-cell']").attributes("colspan")).toBe(
|
||||
"1",
|
||||
);
|
||||
// Presentation row must not look like a selectable data row.
|
||||
expect(w.find("tr[data-slot='table-empty-row']").attributes("role")).toBe(
|
||||
"presentation",
|
||||
);
|
||||
expect(
|
||||
w.find("tr[data-slot='table-empty-row']").attributes("aria-selected"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("TableBody keeps data rows when present and ignores #empty", () => {
|
||||
const w = mountDemo(
|
||||
() => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () => [
|
||||
h(
|
||||
TableBody,
|
||||
{},
|
||||
{
|
||||
default: () =>
|
||||
h(TableRow, { rowKey: "1" }, () => h(TableCell, {}, () => "A")),
|
||||
empty: () => h("span", { class: "msg" }, "未找到结果"),
|
||||
},
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
expect(w.find(".msg").exists()).toBe(false);
|
||||
expect(w.findAll("tr[data-slot='table-row']").length).toBe(1);
|
||||
expect(w.get("tbody").attributes("data-empty")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("select-all checkbox supports indeterminate and shows 全部 when complete", async () => {
|
||||
const users = [
|
||||
{ id: "1", name: "Kate" },
|
||||
{ id: "2", name: "John" },
|
||||
{ id: "3", name: "Sara" },
|
||||
];
|
||||
const selectedKeys = ref<string[]>([]);
|
||||
const w = mountDemo(
|
||||
() => {
|
||||
const allChecked = computed(
|
||||
() => users.length > 0 && selectedKeys.value.length === users.length,
|
||||
);
|
||||
const someChecked = computed(
|
||||
() => selectedKeys.value.length > 0 && !allChecked.value,
|
||||
);
|
||||
return {
|
||||
selectedKeys,
|
||||
allChecked,
|
||||
someChecked,
|
||||
users,
|
||||
};
|
||||
},
|
||||
function (this: {
|
||||
selectedKeys: string[];
|
||||
allChecked: boolean;
|
||||
someChecked: boolean;
|
||||
users: typeof users;
|
||||
}) {
|
||||
return h("div", [
|
||||
h(Checkbox, {
|
||||
ariaLabel: "全选",
|
||||
isSelected: this.allChecked,
|
||||
isIndeterminate: this.someChecked,
|
||||
"onUpdate:checked": () => {
|
||||
this.selectedKeys = this.allChecked
|
||||
? []
|
||||
: this.users.map((u) => u.id);
|
||||
},
|
||||
}),
|
||||
h(
|
||||
"p",
|
||||
{ class: "summary" },
|
||||
this.allChecked
|
||||
? "全部"
|
||||
: this.selectedKeys.length
|
||||
? this.selectedKeys.join(", ")
|
||||
: "无",
|
||||
),
|
||||
]);
|
||||
},
|
||||
);
|
||||
expect(w.find(".summary").text()).toBe("无");
|
||||
const input = w.get("input");
|
||||
expect(input.element.indeterminate).toBe(false);
|
||||
|
||||
selectedKeys.value = ["1"];
|
||||
await nextTick();
|
||||
expect(w.find(".summary").text()).toBe("1");
|
||||
expect(w.get("input").element.indeterminate).toBe(true);
|
||||
|
||||
selectedKeys.value = ["1", "2", "3"];
|
||||
await nextTick();
|
||||
expect(w.find(".summary").text()).toBe("全部");
|
||||
expect(w.get("input").element.indeterminate).toBe(false);
|
||||
expect(w.get("input").element.checked).toBe(true);
|
||||
});
|
||||
|
||||
it("row checkbox click does not also toggle row selection", async () => {
|
||||
const selectionChanges: unknown[] = [];
|
||||
const w = mountDemo(
|
||||
() => ({ selectionChanges }),
|
||||
function (this: { selectionChanges: unknown[] }) {
|
||||
return h(Table, {}, () =>
|
||||
h(
|
||||
TableContent,
|
||||
{
|
||||
selectionMode: "multiple",
|
||||
onSelectionChange: (keys: unknown) =>
|
||||
this.selectionChanges.push(keys),
|
||||
},
|
||||
() =>
|
||||
h(TableBody, {}, () =>
|
||||
h(
|
||||
TableRow,
|
||||
{ rowKey: "1" },
|
||||
{
|
||||
default: () => [
|
||||
h(TableCell, {}, () =>
|
||||
h(
|
||||
Checkbox,
|
||||
{},
|
||||
{
|
||||
default: () => [
|
||||
h(
|
||||
CheckboxContent,
|
||||
{},
|
||||
{
|
||||
default: () => [
|
||||
h(CheckboxControl, {}, () =>
|
||||
h(CheckboxIndicator),
|
||||
),
|
||||
],
|
||||
},
|
||||
),
|
||||
],
|
||||
},
|
||||
),
|
||||
),
|
||||
h(TableCell, {}, () => "Kate"),
|
||||
],
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
const label = w.get("label[data-slot='checkbox-content']");
|
||||
await label.trigger("click");
|
||||
await nextTick();
|
||||
// Clicking the choice control must not bubble into row selection.
|
||||
expect(
|
||||
(w.vm as unknown as { selectionChanges: unknown[] }).selectionChanges,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("toast root is alertdialog with title/description ids and content role=alert", async () => {
|
||||
const queue = new ToastQueue();
|
||||
queues.push(queue);
|
||||
const toast = createToastFunction(queue);
|
||||
const w = mountDemo(
|
||||
() => ({ queue }),
|
||||
() =>
|
||||
h(
|
||||
ToastProvider,
|
||||
{ queue: queue as never, to: "body" },
|
||||
{
|
||||
default: ({
|
||||
toast: item,
|
||||
close,
|
||||
}: {
|
||||
toast: { title: string; description: string };
|
||||
close: () => void;
|
||||
}) =>
|
||||
h(ToastContent, {}, () => [
|
||||
h(ToastTitle, () => item.title),
|
||||
h(ToastDescription, () => item.description),
|
||||
h(ToastActionButton, { onClick: () => close() }, () => "忽略"),
|
||||
h(ToastCloseButton, { onClick: () => close() }),
|
||||
]),
|
||||
},
|
||||
),
|
||||
);
|
||||
toast("您已被邀请加入团队", {
|
||||
description: "Bob 邀请您加入 HeroUI 团队",
|
||||
timeout: 0,
|
||||
});
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
|
||||
const root = document.querySelector('[data-slot="toast"]') as HTMLElement;
|
||||
expect(root).toBeTruthy();
|
||||
expect(root.getAttribute("role")).toBe("alertdialog");
|
||||
expect(root.getAttribute("aria-modal")).toBe("false");
|
||||
const title = root.querySelector('[data-slot="toast-title"]') as HTMLElement;
|
||||
const desc = root.querySelector(
|
||||
'[data-slot="toast-description"]',
|
||||
) as HTMLElement;
|
||||
expect(title.id).toBeTruthy();
|
||||
expect(desc.id).toBeTruthy();
|
||||
expect(root.getAttribute("aria-labelledby")).toBe(title.id);
|
||||
expect(root.getAttribute("aria-describedby")).toBe(desc.id);
|
||||
|
||||
const content = root.querySelector(
|
||||
'[data-slot="toast-content"]',
|
||||
) as HTMLElement;
|
||||
expect(content.getAttribute("role")).toBe("alert");
|
||||
expect(content.getAttribute("aria-atomic")).toBe("true");
|
||||
// After mount the alert payload is visible so it can be announced.
|
||||
await nextTick();
|
||||
expect(content.getAttribute("aria-hidden")).not.toBe("true");
|
||||
|
||||
// Close button keeps an accessible name.
|
||||
const close = root.querySelector("[data-slot='toast-close']");
|
||||
expect(close?.getAttribute("aria-label")).toBeTruthy();
|
||||
void w;
|
||||
});
|
||||
|
||||
it("toast indicator sets data-swapped only after the first paint", async () => {
|
||||
const queue = new ToastQueue();
|
||||
queues.push(queue);
|
||||
const toast = createToastFunction(queue);
|
||||
mountDemo(
|
||||
() => ({ queue }),
|
||||
() =>
|
||||
h(
|
||||
ToastProvider,
|
||||
{ queue: queue as never, to: "body" },
|
||||
{
|
||||
default: ({
|
||||
toast: item,
|
||||
}: {
|
||||
toast: { title: string; isLoading?: boolean; variant?: string };
|
||||
}) =>
|
||||
h(ToastContent, {}, () => [
|
||||
h(ToastTitle, () => item.title),
|
||||
h(
|
||||
ToastIndicator,
|
||||
{ variant: (item.variant ?? "default") as never },
|
||||
item.isLoading
|
||||
? () => h("span", { "data-slot": "spinner" })
|
||||
: undefined,
|
||||
),
|
||||
]),
|
||||
},
|
||||
),
|
||||
);
|
||||
const loadingId = toast("正在上传文件…", { isLoading: true, timeout: 0 });
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
|
||||
const indicator = () =>
|
||||
document.querySelector('[data-slot="toast-indicator"]') as HTMLElement;
|
||||
expect(indicator().getAttribute("data-swapped")).toBeNull();
|
||||
|
||||
toast.update(loadingId, "文件已上传", {
|
||||
isLoading: false,
|
||||
variant: "success",
|
||||
timeout: 0,
|
||||
});
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
expect(indicator().getAttribute("data-swapped")).toBe("true");
|
||||
});
|
||||
|
||||
it("column defaultWidth 1fr does not write an invalid CSS width", () => {
|
||||
const w = mountDemo(
|
||||
() => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableColumn, { id: "name", defaultWidth: "1fr" }, () => "姓名"),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const th = w.get("th");
|
||||
expect((th.element as HTMLElement).style.width).toBe("");
|
||||
expect(th.attributes("data-default-width")).toBe("1fr");
|
||||
});
|
||||
|
||||
it("tree column cell gets data-tree-column and row level variable", () => {
|
||||
const w = mountDemo(
|
||||
() => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, { treeColumn: "name" }, () => [
|
||||
h(TableHeader, {}, () =>
|
||||
h(TableColumn, { id: "name" }, () => "姓名"),
|
||||
),
|
||||
h(TableBody, {}, () =>
|
||||
h(TableRow, { rowKey: "1", level: 2, hasChildItems: true }, () =>
|
||||
h(TableCell, {}, () => "文档"),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
);
|
||||
const tr = w.get("tr[data-slot='table-row']");
|
||||
expect(tr.attributes("data-level")).toBe("2");
|
||||
expect(
|
||||
(tr.element as HTMLElement).style.getPropertyValue("--table-row-level"),
|
||||
).toBe("2");
|
||||
const td = w.get("td[data-slot='table-cell']");
|
||||
expect(td.attributes("data-tree-column")).toBeDefined();
|
||||
});
|
||||
|
||||
it("TableCollection empty ↔ non-empty toggles the empty slot", async () => {
|
||||
const items = ref<string[]>([]);
|
||||
const w = mountDemo(
|
||||
() => () =>
|
||||
h(Table, {}, () =>
|
||||
h(TableContent, {}, () =>
|
||||
h(
|
||||
TableBody,
|
||||
{ colspan: 1 },
|
||||
{
|
||||
default: () =>
|
||||
h(
|
||||
TableCollection,
|
||||
{ items: items.value },
|
||||
{
|
||||
default: ({ item }: { item: string }) =>
|
||||
h(TableRow, { rowKey: item }, () =>
|
||||
h(TableCell, {}, () => item),
|
||||
),
|
||||
},
|
||||
),
|
||||
empty: () => h("span", { "data-test": "empty" }, "Empty"),
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
expect(w.findAll('[data-slot="table-row"]').length).toBe(0);
|
||||
|
||||
items.value = ["A", "B"];
|
||||
await nextTick();
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(false);
|
||||
expect(w.findAll('[data-slot="table-row"]').length).toBe(2);
|
||||
|
||||
items.value = [];
|
||||
await nextTick();
|
||||
expect(w.find('[data-test="empty"]').exists()).toBe(true);
|
||||
expect(w.findAll('[data-slot="table-row"]').length).toBe(0);
|
||||
});
|
||||
|
||||
it("title-only toast omits aria-describedby when no description part exists", async () => {
|
||||
const queue = new ToastQueue();
|
||||
queues.push(queue);
|
||||
const toast = createToastFunction(queue);
|
||||
mountDemo(
|
||||
() => ({ queue }),
|
||||
() => h(ToastProvider, { queue: queue as never, to: "body" }),
|
||||
);
|
||||
toast("标题独占", { timeout: 0 });
|
||||
await flushPromises();
|
||||
await nextTick();
|
||||
const root = document.querySelector('[data-slot="toast"]') as HTMLElement;
|
||||
const refs = (root.getAttribute("aria-describedby") ?? "")
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
expect(refs.length).toBe(0);
|
||||
const labelled = root.getAttribute("aria-labelledby");
|
||||
expect(labelled && document.getElementById(labelled)).toBeTruthy();
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { defineComponent, nextTick, ref } from "vue";
|
||||
import {
|
||||
Button,
|
||||
Toolbar,
|
||||
ToggleButton,
|
||||
ToggleButtonGroup,
|
||||
} 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: { Button, Toolbar, ToggleButton, ToggleButtonGroup },
|
||||
template,
|
||||
setup,
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
wrappers.push(wrapper);
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
it("standalone Button preserves the caller tabindex after Toolbar integration", async () => {
|
||||
const wrapper = fixture('<Button :tabindex="-1">Excluded</Button>');
|
||||
await nextTick();
|
||||
expect(wrapper.get("button").attributes("tabindex")).toBe("-1");
|
||||
});
|
||||
|
||||
it("standalone asChild buttons preserve tabindex supplied by their native child", async () => {
|
||||
const wrapper = fixture(
|
||||
'<div><Button as-child><button tabindex="-1">Button child</button></Button><ToggleButton as-child><button tabindex="-1">Toggle child</button></ToggleButton></div>',
|
||||
);
|
||||
await nextTick();
|
||||
expect(
|
||||
wrapper.findAll("button").map((button) => button.attributes("tabindex")),
|
||||
).toEqual(["-1", "-1"]);
|
||||
});
|
||||
|
||||
it("moving an existing Button through Teleport restores its own tabindex", async () => {
|
||||
const inline = ref(true);
|
||||
const wrapper = fixture(
|
||||
'<Toolbar><Button>A</Button><Teleport to="body" :disabled="inline"><Button data-outside tabindex="3">Moving</Button></Teleport></Toolbar>',
|
||||
() => ({ inline }),
|
||||
);
|
||||
await nextTick();
|
||||
const moving = document.querySelector("[data-outside]") as HTMLButtonElement;
|
||||
expect(moving.getAttribute("tabindex")).toBe("-1");
|
||||
inline.value = false;
|
||||
await nextTick();
|
||||
expect(wrapper.element.contains(moving)).toBe(false);
|
||||
expect(moving.getAttribute("tabindex")).toBe("3");
|
||||
});
|
||||
|
||||
it("moving an existing group outside Toolbar restores its arrow navigation", async () => {
|
||||
const inline = ref(true);
|
||||
fixture(
|
||||
'<Toolbar><Button>A</Button><Teleport to="body" :disabled="inline"><ToggleButtonGroup data-moving><ToggleButton value="x">X</ToggleButton><ToggleButton value="y">Y</ToggleButton></ToggleButtonGroup></Teleport></Toolbar>',
|
||||
() => ({ inline }),
|
||||
);
|
||||
await nextTick();
|
||||
inline.value = false;
|
||||
await nextTick();
|
||||
const buttons = document.querySelectorAll<HTMLButtonElement>(
|
||||
"[data-moving] button",
|
||||
);
|
||||
buttons[0].focus();
|
||||
buttons[0].dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }),
|
||||
);
|
||||
await nextTick();
|
||||
expect(document.activeElement).toBe(buttons[1]);
|
||||
});
|
||||
|
||||
it("Toolbar root keydown handler is preserved and can cancel navigation", async () => {
|
||||
const handler = vi.fn((event: KeyboardEvent) => event.preventDefault());
|
||||
const wrapper = fixture(
|
||||
'<Toolbar @keydown="handler"><Button>A</Button><Button>B</Button></Toolbar>',
|
||||
() => ({ handler }),
|
||||
);
|
||||
await nextTick();
|
||||
const buttons = wrapper.findAll("button");
|
||||
(buttons[0].element as HTMLElement).focus();
|
||||
await buttons[0].trigger("keydown", { key: "ArrowRight" });
|
||||
expect(handler).toHaveBeenCalledTimes(1);
|
||||
expect(document.activeElement).toBe(buttons[0].element);
|
||||
});
|
||||
|
||||
it("Toolbar navigation excludes controls teleported outside its DOM", async () => {
|
||||
const wrapper = fixture(
|
||||
'<Toolbar><Button>A</Button><Button>B</Button><Teleport to="body"><Button>Outside</Button></Teleport></Toolbar>',
|
||||
);
|
||||
await nextTick();
|
||||
const buttons = wrapper.findAll("button");
|
||||
expect(buttons).toHaveLength(2);
|
||||
(buttons[1].element as HTMLElement).focus();
|
||||
await buttons[1].trigger("keydown", { key: "ArrowRight" });
|
||||
expect(document.activeElement).toBe(buttons[0].element);
|
||||
const outside = [...document.querySelectorAll("button")].find(
|
||||
(button) => button.textContent === "Outside",
|
||||
);
|
||||
expect(outside?.hasAttribute("tabindex")).toBe(false);
|
||||
});
|
||||
Reference in New Issue
Block a user