Files

352 lines
12 KiB
TypeScript

import { afterEach, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, nextTick, ref } from "vue";
import { readFileSync } from "node:fs";
import {
Button,
Drawer,
DrawerBackdrop,
DrawerBody,
DrawerClose,
DrawerCloseTrigger,
DrawerContent,
DrawerDialog,
DrawerFooter,
DrawerHandle,
DrawerHeader,
DrawerHeading,
} from "../packages/vue/src";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(async () => {
for (const w of wrappers.splice(0)) w.unmount();
await flushPromises();
document.body.innerHTML = "";
});
const components = {
Drawer,
DrawerBackdrop,
DrawerContent,
DrawerDialog,
DrawerCloseTrigger,
DrawerHandle,
DrawerHeader,
DrawerHeading,
DrawerBody,
DrawerFooter,
DrawerClose,
Button,
};
const panel =
'<DrawerBackdrop><DrawerContent placement="bottom"><DrawerDialog><DrawerHandle/><DrawerCloseTrigger/><DrawerHeader><DrawerHeading>抽屉标题</DrawerHeading></DrawerHeader><DrawerBody>内容</DrawerBody><DrawerFooter><DrawerClose as-child><Button>关闭</Button></DrawerClose></DrawerFooter></DrawerDialog></DrawerContent></DrawerBackdrop>';
function view(template: string, setup = () => ({})) {
const w = mount(defineComponent({ components, template, setup }), {
attachTo: document.body,
});
wrappers.push(w);
return w;
}
it("opens drawer with dialog role and heading association", async () => {
const w = view(`<Drawer><Button>打开</Button>${panel}</Drawer>`);
await w.get("button").trigger("click");
await flushPromises();
const dialog = document.querySelector('[data-slot="drawer-dialog"]')!;
expect(dialog).not.toBeNull();
const labelled = dialog.getAttribute("aria-labelledby")!;
expect(document.getElementById(labelled)?.textContent).toContain("抽屉标题");
expect(
document
.querySelector('[data-slot="drawer-handle"]')
?.getAttribute("aria-hidden"),
).toBe("true");
});
it("places panel by placement class", async () => {
const w = view(
`<Drawer><Button>打开</Button><DrawerBackdrop><DrawerContent placement="left"><DrawerDialog><DrawerHeading>左</DrawerHeading></DrawerDialog></DrawerContent></DrawerBackdrop></Drawer>`,
);
await w.get("button").trigger("click");
await flushPromises();
const content = document.querySelector('[data-slot="drawer-content"]')!;
expect(content.className).toContain("hv-drawer__content--left");
expect(content.getAttribute("data-placement")).toBe("left");
const dialog = document.querySelector('[data-slot="drawer-dialog"]')!;
expect(dialog.getAttribute("data-placement")).toBe("left");
});
it("isDismissable=false blocks drag handlers on the dialog", async () => {
const w = view(
`<Drawer><Button>打开</Button><DrawerBackdrop :is-dismissable="false"><DrawerContent><DrawerDialog><DrawerHeading>不可拖</DrawerHeading></DrawerDialog></DrawerContent></DrawerBackdrop></Drawer>`,
);
await w.get("button").trigger("click");
await flushPromises();
const dialog = document.querySelector('[data-slot="drawer-dialog"]')!;
expect(dialog.getAttribute("style") ?? "").not.toContain("none");
});
it("drag past 30% dimension closes the drawer", async () => {
const w = view(`<Drawer><Button>打开</Button>${panel}</Drawer>`);
await w.get("button").trigger("click");
await flushPromises();
const dialog = document.querySelector('[data-slot="drawer-dialog"]')!;
// Give the dialog a measurable height (jsdom defaults to 0).
Object.defineProperty(dialog, "offsetHeight", {
value: 200,
configurable: true,
});
function pointer(type: string, clientY: number) {
const event = new MouseEvent(type, {
bubbles: true,
cancelable: true,
button: 0,
clientY,
});
Object.defineProperty(event, "pointerId", { value: 1 });
dialog.dispatchEvent(event);
}
pointer("pointerdown", 100);
pointer("pointermove", 120);
pointer("pointermove", 180);
// 80px of 200 = 40% > 30% → dismiss
pointer("pointerup", 180);
await flushPromises();
await nextTick();
expect(document.querySelector('[data-slot="drawer-dialog"]')).toBeNull();
});
it("small slow drag snaps back and does not dismiss", async () => {
const w = view(`<Drawer><Button>打开</Button>${panel}</Drawer>`);
await w.get("button").trigger("click");
await flushPromises();
const dialog = document.querySelector<HTMLElement>(
'[data-slot="drawer-dialog"]',
)!;
Object.defineProperty(dialog, "offsetHeight", {
value: 200,
configurable: true,
});
// Controlled clock: 10px over 200ms → 0.05px/ms, well under the 0.5 threshold.
let now = 1_000_000;
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
function pointer(type: string, clientY: number) {
now += 100;
const event = new MouseEvent(type, {
bubbles: true,
cancelable: true,
button: 0,
clientY,
});
Object.defineProperty(event, "pointerId", { value: 1 });
dialog.dispatchEvent(event);
}
pointer("pointerdown", 100);
pointer("pointermove", 105);
pointer("pointermove", 110);
pointer("pointerup", 110);
nowSpy.mockRestore();
await flushPromises();
await nextTick();
expect(document.querySelector('[data-slot="drawer-dialog"]')).not.toBeNull();
});
it("fast flick closes even under the distance threshold", async () => {
const w = view(`<Drawer><Button>打开</Button>${panel}</Drawer>`);
await w.get("button").trigger("click");
await flushPromises();
const dialog = document.querySelector<HTMLElement>(
'[data-slot="drawer-dialog"]',
)!;
Object.defineProperty(dialog, "offsetHeight", {
value: 200,
configurable: true,
});
// 15px in 10ms → 1.5px/ms > 0.5, dismiss on velocity alone.
let now = 1_000_000;
const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => now);
function pointer(type: string, clientY: number) {
now += 5;
const event = new MouseEvent(type, {
bubbles: true,
cancelable: true,
button: 0,
clientY,
});
Object.defineProperty(event, "pointerId", { value: 1 });
dialog.dispatchEvent(event);
}
pointer("pointerdown", 100);
pointer("pointermove", 110);
pointer("pointerup", 115);
nowSpy.mockRestore();
await flushPromises();
await nextTick();
expect(document.querySelector('[data-slot="drawer-dialog"]')).toBeNull();
});
it("controlled parent rejects open and allows retry", async () => {
const opens = vi.fn();
const w = view(
`<Drawer :is-open="false" @update:is-open="opens"><Button>打开</Button>${panel}</Drawer>`,
() => ({ opens }),
);
await w.get("button").trigger("click");
await flushPromises();
expect(opens).toHaveBeenCalled();
expect(document.querySelector('[data-slot="drawer-dialog"]')).toBeNull();
const before = opens.mock.calls.length;
await w.get("button").trigger("click");
await flushPromises();
expect(opens.mock.calls.length).toBeGreaterThan(before);
});
it("closes via DrawerClose and close trigger", async () => {
const w = view(`<Drawer><Button>打开</Button>${panel}</Drawer>`);
await w.get("button").trigger("click");
await flushPromises();
(
document.querySelector("[data-slot=drawer-close-trigger]") as HTMLElement
).click();
await flushPromises();
await nextTick();
expect(document.querySelector('[data-slot="drawer-dialog"]')).toBeNull();
await w.get("button").trigger("click");
await flushPromises();
[...document.querySelectorAll("button")]
.find((b) => b.textContent?.trim() === "关闭")!
.click();
await flushPromises();
await nextTick();
expect(document.querySelector('[data-slot="drawer-dialog"]')).toBeNull();
});
it("all 9 demos mount without Vue warnings", async () => {
const names = [
"basic",
"placements",
"non-dismissable",
"scrollable-content",
"controlled",
"with-form",
"navigation",
"backdrop-variants",
"custom-styles",
];
expect(names).toHaveLength(9);
const warnings: string[] = [];
const spy = vi.spyOn(console, "warn").mockImplementation((...args) => {
warnings.push(args.map(String).join(" "));
});
for (const name of names) {
const mod = await import(`../apps/docs/demos/drawer-${name}.vue`);
const w = mount(mod.default, { attachTo: document.body });
await nextTick();
expect(w.html().length).toBeGreaterThan(0);
w.unmount();
}
spy.mockRestore();
expect(warnings).toEqual([]);
});
it("uses CSS animations so Presence can defer exit unmount", async () => {
// Source contract: enter/exit must be CSS animations (not only transitions)
// because Reka Presence keys off animationName. jsdom has no animation
// engine so runtime deferral is verified in the browser instead.
const css = readFileSync("packages/styles/components/drawer.css", "utf8");
for (const name of [
"hv-drawer-backdrop-in",
"hv-drawer-backdrop-out",
"hv-drawer-in-from-bottom",
"hv-drawer-out-to-bottom",
"hv-drawer-out-to-right",
"hv-drawer-out-to-left",
"hv-drawer-out-to-top",
]) {
expect(css).toContain(`@keyframes ${name}`);
}
expect(css).toMatch(/\.hv-drawer__dialog\[data-exiting="true"\]/);
expect(css).not.toMatch(
/\.hv-drawer__dialog\s*\{[^}]*transition:\s*translate/,
);
});
it("multiple drawers can coexist with unique heading ids", async () => {
const w = mount(
defineComponent({
components,
template: `
<div>
<Drawer>
<Button class="open-a">打开 A</Button>
<DrawerBackdrop>
<DrawerContent placement="bottom">
<DrawerDialog>
<DrawerHeading>抽屉 A</DrawerHeading>
</DrawerDialog>
</DrawerContent>
</DrawerBackdrop>
</Drawer>
<Drawer>
<Button class="open-b">打开 B</Button>
<DrawerBackdrop>
<DrawerContent placement="right">
<DrawerDialog>
<DrawerHeading>抽屉 B</DrawerHeading>
</DrawerDialog>
</DrawerContent>
</DrawerBackdrop>
</Drawer>
</div>
`,
}),
{ attachTo: document.body },
);
wrappers.push(w);
await w.get("button.open-a").trigger("click");
await flushPromises();
await w.get("button.open-b").trigger("click");
await flushPromises();
const dialogs = document.querySelectorAll('[data-slot="drawer-dialog"]');
expect(dialogs.length).toBe(2);
const ids = [...dialogs].map((d) => d.getAttribute("aria-labelledby"));
expect(new Set(ids).size).toBe(2);
for (const id of ids) {
expect(id && document.getElementById(id)).toBeTruthy();
}
});
it("outside click closes when isDismissable and not when disabled", async () => {
const w = view(`<Drawer><Button>打开</Button>${panel}</Drawer>`);
await w.get("button").trigger("click");
await flushPromises();
expect(document.querySelector('[data-slot="drawer-dialog"]')).not.toBeNull();
// Click the backdrop (outside the dialog panel).
const backdrop = document.querySelector("[data-slot=drawer-backdrop]");
backdrop!.dispatchEvent(
new MouseEvent("pointerdown", { bubbles: true, cancelable: true }),
);
backdrop!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await flushPromises();
await nextTick();
expect(document.querySelector('[data-slot="drawer-dialog"]')).toBeNull();
// Non-dismissable: outside click keeps the panel.
const w2 = view(
`<Drawer><Button>打开</Button><DrawerBackdrop :is-dismissable="false"><DrawerContent><DrawerDialog><DrawerHeading>不可关</DrawerHeading></DrawerDialog></DrawerContent></DrawerBackdrop></Drawer>`,
);
await w2.get("button").trigger("click");
await flushPromises();
const backdrop2 = document.querySelector("[data-slot=drawer-backdrop]")!;
backdrop2.dispatchEvent(
new MouseEvent("pointerdown", { bubbles: true, cancelable: true }),
);
backdrop2.dispatchEvent(new MouseEvent("click", { bubbles: true }));
await flushPromises();
await nextTick();
expect(document.querySelector('[data-slot="drawer-dialog"]')).not.toBeNull();
});