feat: migrate Pagination Header and InputOTP with field and event regressions
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createSSRApp, defineComponent, h, nextTick, ref } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import { Header, HeaderRoot } from "../packages/vue/src";
|
||||
|
||||
import HeaderBasicDemo from "../apps/docs/demos/header-basic.vue";
|
||||
import HeaderCustomClassDemo from "../apps/docs/demos/header-custom-class.vue";
|
||||
import HeaderSemanticDemo from "../apps/docs/demos/header-semantic.vue";
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
describe("Header basics", () => {
|
||||
it("renders a native header with baseline class and data-slot", () => {
|
||||
const w = mount(Header, {
|
||||
props: {},
|
||||
slots: { default: "操作" },
|
||||
attachTo: document.body,
|
||||
});
|
||||
const root = w.get('[data-slot="header"]');
|
||||
expect(root.element.tagName).toBe("HEADER");
|
||||
expect(root.classes().join(" ")).toContain("hv-header");
|
||||
expect(root.text()).toBe("操作");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("exports Header as HeaderRoot alias", () => {
|
||||
expect(Header).toBe(HeaderRoot);
|
||||
});
|
||||
|
||||
it("supports as override without inventing heading levels", () => {
|
||||
const w = mount(Header, {
|
||||
props: { as: "div" },
|
||||
slots: { default: "分组" },
|
||||
attachTo: document.body,
|
||||
});
|
||||
const root = w.get('[data-slot="header"]');
|
||||
expect(root.element.tagName).toBe("DIV");
|
||||
expect(root.attributes("role")).toBeUndefined();
|
||||
expect(root.attributes("aria-level")).toBeUndefined();
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("merges class and attrs, including dynamic add/update/delete/re-add", async () => {
|
||||
const extra = ref<Record<string, unknown>>({});
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: { Header },
|
||||
setup: () => ({ extra }),
|
||||
template: `<Header v-bind="extra" class="base-header">分组</Header>`,
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
let root = w.get('[data-slot="header"]');
|
||||
expect(root.classes()).toContain("hv-header");
|
||||
expect(root.classes()).toContain("base-header");
|
||||
|
||||
extra.value = {
|
||||
"data-testid": "h1",
|
||||
"aria-label": "分组标题",
|
||||
id: "group-title",
|
||||
};
|
||||
await nextTick();
|
||||
root = w.get('[data-slot="header"]');
|
||||
expect(root.attributes("data-testid")).toBe("h1");
|
||||
expect(root.attributes("aria-label")).toBe("分组标题");
|
||||
expect(root.attributes("id")).toBe("group-title");
|
||||
|
||||
extra.value = { "data-testid": "h2", title: "updated" };
|
||||
await nextTick();
|
||||
root = w.get('[data-slot="header"]');
|
||||
expect(root.attributes("data-testid")).toBe("h2");
|
||||
expect(root.attributes("title")).toBe("updated");
|
||||
expect(root.attributes("aria-label")).toBeUndefined();
|
||||
expect(root.attributes("id")).toBeUndefined();
|
||||
|
||||
extra.value = {};
|
||||
await nextTick();
|
||||
root = w.get("[data-slot=header]");
|
||||
expect(root.attributes("data-testid")).toBeUndefined();
|
||||
expect(root.attributes("title")).toBeUndefined();
|
||||
|
||||
extra.value = { style: { color: "red" } };
|
||||
await nextTick();
|
||||
root = w.get("[data-slot=header]");
|
||||
expect(root.attributes("style")).toContain("color: red");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("updates default slot content and keeps multiple instances independent", async () => {
|
||||
const label = ref("A 组");
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: { Header },
|
||||
setup: () => ({ label }),
|
||||
template: `
|
||||
<div>
|
||||
<Header data-testid="one">{{ label }}</Header>
|
||||
<Header data-testid="two">B 组</Header>
|
||||
</div>
|
||||
`,
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
expect(w.get('[data-testid="one"]').text()).toBe("A 组");
|
||||
expect(w.get('[data-testid="two"]').text()).toBe("B 组");
|
||||
|
||||
label.value = "A 组已更新";
|
||||
await nextTick();
|
||||
expect(w.get('[data-testid="one"]').text()).toBe("A 组已更新");
|
||||
expect(w.get('[data-testid="two"]').text()).toBe("B 组");
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Header demos", () => {
|
||||
it("mounts all self-authored demos without Vue warnings", async () => {
|
||||
const warnings: string[] = [];
|
||||
const spy = vi.spyOn(console, "warn").mockImplementation((...args) => {
|
||||
warnings.push(args.map(String).join(" "));
|
||||
});
|
||||
for (const demo of [
|
||||
HeaderBasicDemo,
|
||||
HeaderCustomClassDemo,
|
||||
HeaderSemanticDemo,
|
||||
]) {
|
||||
const w = mount(demo, { attachTo: document.body });
|
||||
await nextTick();
|
||||
expect(w.html().length).toBeGreaterThan(0);
|
||||
expect(w.find('[data-slot="header"]').exists()).toBe(true);
|
||||
w.unmount();
|
||||
}
|
||||
spy.mockRestore();
|
||||
expect(warnings).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Header types", () => {
|
||||
it("exposes HeaderProps alias", () => {
|
||||
const ok: InstanceType<typeof HeaderRoot>["$props"] = { as: "header" };
|
||||
expect(ok.as).toBe("header");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Header SSR", () => {
|
||||
it("renders without touching browser globals", async () => {
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () => h(Header, () => "操作"),
|
||||
}),
|
||||
);
|
||||
expect(html).toContain("<header");
|
||||
expect(html).toContain('data-slot="header"');
|
||||
expect(html).toContain("hv-header");
|
||||
expect(html).toContain("操作");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// @vitest-environment node
|
||||
import { expect, it } from "vitest";
|
||||
import { createSSRApp, h } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPSlot,
|
||||
Label,
|
||||
} from "../packages/vue/src";
|
||||
it("renders composed OTP names on the real native inputs without browser globals", async () => {
|
||||
expect(typeof window).toBe("undefined");
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(InputOTP, { maxLength: 2, defaultValue: "12" }, () => [
|
||||
h(Label, { id: "otp-server-label" }, () => "Security code"),
|
||||
h(InputOTPGroup, {}, () => [
|
||||
h(InputOTPSlot, { index: 0 }),
|
||||
h(InputOTPSlot, { index: 1 }),
|
||||
]),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(html.match(/aria-labelledby="otp-server-label"/g)).toHaveLength(2);
|
||||
expect(html).toContain('value="1"');
|
||||
expect(html).toContain('value="2"');
|
||||
expect(html).not.toMatch(/aria-label="pin input/);
|
||||
});
|
||||
@@ -0,0 +1,563 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createSSRApp, defineComponent, h, nextTick, ref } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import {
|
||||
InputOTP,
|
||||
InputOTPGroup,
|
||||
InputOTPRoot,
|
||||
InputOTPSeparator,
|
||||
InputOTPSlot,
|
||||
REGEXP_ONLY_CHARS,
|
||||
REGEXP_ONLY_DIGITS,
|
||||
REGEXP_ONLY_DIGITS_AND_CHARS,
|
||||
} from "../packages/vue/src";
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function mountOtp(
|
||||
opts: {
|
||||
maxLength?: number;
|
||||
modelValue?: string;
|
||||
defaultValue?: string;
|
||||
pattern?: string | RegExp;
|
||||
isDisabled?: boolean;
|
||||
isInvalid?: boolean;
|
||||
validationErrors?: string[];
|
||||
name?: string;
|
||||
required?: boolean;
|
||||
variant?: "primary" | "secondary";
|
||||
inputClassName?: string;
|
||||
otp?: boolean;
|
||||
onComplete?: (v: string) => void;
|
||||
} = {},
|
||||
) {
|
||||
const value = ref(opts.modelValue ?? opts.defaultValue ?? "");
|
||||
const controlled = opts.modelValue !== undefined;
|
||||
const updates: string[] = [];
|
||||
const completes: string[] = [];
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ value }),
|
||||
render: () =>
|
||||
h(
|
||||
InputOTP,
|
||||
{
|
||||
maxLength: opts.maxLength ?? 6,
|
||||
modelValue: controlled ? value.value : undefined,
|
||||
defaultValue: opts.defaultValue,
|
||||
pattern: opts.pattern,
|
||||
isDisabled: opts.isDisabled,
|
||||
isInvalid: opts.isInvalid,
|
||||
validationErrors: opts.validationErrors,
|
||||
name: opts.name,
|
||||
required: opts.required,
|
||||
variant: opts.variant,
|
||||
inputClassName: opts.inputClassName,
|
||||
otp: opts.otp,
|
||||
"onUpdate:modelValue": (v: string) => {
|
||||
value.value = v;
|
||||
updates.push(v);
|
||||
},
|
||||
onComplete: (v: string) => {
|
||||
completes.push(v);
|
||||
opts.onComplete?.(v);
|
||||
},
|
||||
},
|
||||
() => [
|
||||
h(InputOTPGroup, () =>
|
||||
Array.from({ length: opts.maxLength ?? 6 }, (_, i) =>
|
||||
h(InputOTPSlot, { index: i }),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
return { w, value, updates, completes, controlled };
|
||||
}
|
||||
|
||||
function slotInputs(w: ReturnType<typeof mount>) {
|
||||
return w.findAll("input[data-slot=input-otp-input]");
|
||||
}
|
||||
|
||||
describe("InputOTP structure", () => {
|
||||
it("exports InputOTP as Root alias and renders slots/groups", () => {
|
||||
expect(InputOTP).toBe(InputOTPRoot);
|
||||
const { w } = mountOtp({ maxLength: 4, variant: "secondary" });
|
||||
const root = w.get('[data-slot="input-otp"]');
|
||||
expect(root.classes().join(" ")).toContain("hv-input-otp");
|
||||
expect(root.classes().join(" ")).toContain("hv-input-otp--secondary");
|
||||
expect(w.findAll('[data-slot="input-otp-slot"]')).toHaveLength(4);
|
||||
expect(slotInputs(w)).toHaveLength(4);
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("renders separator and applies inputClassName to real inputs only", () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(InputOTP, { maxLength: 2, inputClassName: "custom-input" }, () => [
|
||||
h(InputOTPGroup, () => h(InputOTPSlot, { index: 0 })),
|
||||
h(InputOTPSeparator, { class: "custom-sep" }),
|
||||
h(InputOTPGroup, () => h(InputOTPSlot, { index: 1 })),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
expect(w.get('[data-slot="input-otp-separator"]').classes()).toContain(
|
||||
"custom-sep",
|
||||
);
|
||||
for (const input of slotInputs(w)) {
|
||||
expect(input.classes()).toContain("custom-input");
|
||||
}
|
||||
expect(w.get('[data-slot="input-otp"]').classes()).not.toContain(
|
||||
"custom-input",
|
||||
);
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("InputOTP value model", () => {
|
||||
it("supports uncontrolled defaultValue and typed updates as strings", async () => {
|
||||
const { w, value, updates } = mountOtp({ defaultValue: "12" });
|
||||
await nextTick();
|
||||
const slots = w.findAll('[data-slot="input-otp-slot"]');
|
||||
expect(slots[0].text()).toContain("1");
|
||||
expect(slots[1].text()).toContain("2");
|
||||
expect(slots[2].text()).not.toContain("3");
|
||||
|
||||
await slotInputs(w)[2].setValue("3");
|
||||
await nextTick();
|
||||
expect(value.value).toBe("123");
|
||||
expect(updates.at(-1)).toBe("123");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("controlled parent rejects update and restores actual input", async () => {
|
||||
const value = ref("12");
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ value }),
|
||||
render: () =>
|
||||
h(
|
||||
InputOTP,
|
||||
{
|
||||
maxLength: 4,
|
||||
modelValue: value.value,
|
||||
// Parent always keeps "12"
|
||||
"onUpdate:modelValue": () => {},
|
||||
},
|
||||
() =>
|
||||
h(InputOTPGroup, () =>
|
||||
[0, 1, 2, 3].map((i) => h(InputOTPSlot, { index: i })),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await nextTick();
|
||||
const list = slotInputs(w);
|
||||
await list[2].setValue("9");
|
||||
await nextTick();
|
||||
// Parent rejected; display should still be 12
|
||||
expect(value.value).toBe("12");
|
||||
const slots = w.findAll('[data-slot="input-otp-slot"]');
|
||||
expect(slots[0].text()).toContain("1");
|
||||
expect(slots[2].text()).not.toContain("9");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("keeps middle empty slot without left-shifting later characters", async () => {
|
||||
const { w } = mountOtp({ defaultValue: "123456" });
|
||||
await nextTick();
|
||||
await slotInputs(w)[1].setValue("");
|
||||
await nextTick();
|
||||
const slots = w.findAll('[data-slot="input-otp-slot"]');
|
||||
expect(slots[1].text()).not.toContain("2");
|
||||
expect(slots[2].text()).toContain("3");
|
||||
expect(slots[3].text()).toContain("4");
|
||||
expect(slots[5].text()).toContain("6");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("clears value and restores on retype", async () => {
|
||||
const { w, value } = mountOtp({ defaultValue: "12" });
|
||||
await nextTick();
|
||||
await slotInputs(w)[0].setValue("");
|
||||
await slotInputs(w)[1].setValue("");
|
||||
await nextTick();
|
||||
expect(value.value).toBe("");
|
||||
await slotInputs(w)[0].setValue("9");
|
||||
await nextTick();
|
||||
expect(value.value).toBe("9");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("emits complete on first fill and not on same-value rewrite", async () => {
|
||||
const completes: string[] = [];
|
||||
const { w, value } = mountOtp({
|
||||
maxLength: 3,
|
||||
onComplete: (v: string) => completes.push(v),
|
||||
});
|
||||
const list = slotInputs(w);
|
||||
await list[0].setValue("1");
|
||||
await list[1].setValue("2");
|
||||
await list[2].setValue("3");
|
||||
await nextTick();
|
||||
expect(completes.at(-1)).toBe("123");
|
||||
const count = completes.length;
|
||||
// Re-set same value should not grow complete
|
||||
await list[2].setValue("3");
|
||||
await nextTick();
|
||||
expect(completes.length).toBe(count);
|
||||
expect(value.value).toBe("123");
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("InputOTP pattern and states", () => {
|
||||
it("filters characters with REGEXP_ONLY_CHARS and digits constants", async () => {
|
||||
expect(REGEXP_ONLY_DIGITS).toBe("^\\d+$");
|
||||
expect(REGEXP_ONLY_CHARS).toBe("^[a-zA-Z]+$");
|
||||
expect(REGEXP_ONLY_DIGITS_AND_CHARS).toBe("^[a-zA-Z0-9]+$");
|
||||
|
||||
const { w, value } = mountOtp({
|
||||
maxLength: 4,
|
||||
pattern: REGEXP_ONLY_DIGITS,
|
||||
});
|
||||
await slotInputs(w)[0].setValue("a");
|
||||
await nextTick();
|
||||
expect(value.value).toBe("");
|
||||
await slotInputs(w)[0].setValue("7");
|
||||
await nextTick();
|
||||
expect(value.value).toBe("7");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("marks disabled, invalid and filled data attributes", async () => {
|
||||
const { w } = mountOtp({
|
||||
defaultValue: "1",
|
||||
isDisabled: true,
|
||||
isInvalid: true,
|
||||
});
|
||||
await nextTick();
|
||||
expect(
|
||||
w.get('[data-slot="input-otp"]').attributes("data-disabled"),
|
||||
).toBeDefined();
|
||||
expect(
|
||||
w.get('[data-slot="input-otp"]').attributes("data-invalid"),
|
||||
).toBeDefined();
|
||||
const slots = w.findAll('[data-slot="input-otp-slot"]');
|
||||
expect(slots[0].attributes("data-filled")).toBeDefined();
|
||||
expect(slots[0].attributes("data-disabled")).toBeDefined();
|
||||
expect(slots[0].attributes("data-invalid")).toBeDefined();
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("shows validation errors via field context", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h("div", () => [
|
||||
h(
|
||||
InputOTP,
|
||||
{
|
||||
maxLength: 4,
|
||||
isInvalid: true,
|
||||
validationErrors: ["验证码无效"],
|
||||
name: "code",
|
||||
},
|
||||
() =>
|
||||
h(InputOTPGroup, () =>
|
||||
[0, 1, 2, 3].map((i) => h(InputOTPSlot, { index: i })),
|
||||
),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
// FieldError is optional; invalid state on root is enough for this check
|
||||
expect(
|
||||
w.get('[data-slot="input-otp"]').attributes("data-invalid"),
|
||||
).toBeDefined();
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("InputOTP form and label", () => {
|
||||
it("submits a single form value and omits when disabled", async () => {
|
||||
const { w } = mountOtp({
|
||||
name: "code",
|
||||
defaultValue: "123456",
|
||||
});
|
||||
await nextTick();
|
||||
const form = document.createElement("form");
|
||||
form.appendChild(w.element);
|
||||
document.body.appendChild(form);
|
||||
const data = new FormData(form);
|
||||
expect(data.get("code")).toBe("123456");
|
||||
form.remove();
|
||||
|
||||
const d = mountOtp({
|
||||
name: "code",
|
||||
defaultValue: "12",
|
||||
isDisabled: true,
|
||||
});
|
||||
await nextTick();
|
||||
const form2 = document.createElement("form");
|
||||
form2.appendChild(d.w.element);
|
||||
document.body.appendChild(form2);
|
||||
const data2 = new FormData(form2);
|
||||
expect(data2.get("code")).toBeNull();
|
||||
form2.remove();
|
||||
d.w.unmount();
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("resets uncontrolled value to defaultValue and keeps controlled parent value", async () => {
|
||||
const uncontrolled = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h("form", null, [
|
||||
h(
|
||||
InputOTP,
|
||||
{ maxLength: 4, defaultValue: "12", name: "code" },
|
||||
() =>
|
||||
h(InputOTPGroup, () =>
|
||||
[0, 1, 2, 3].map((i) => h(InputOTPSlot, { index: i })),
|
||||
),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const uInputs = slotInputs(uncontrolled);
|
||||
await uInputs[0].setValue("9");
|
||||
await nextTick();
|
||||
expect(new FormData(uncontrolled.get("form").element).get("code")).toBe(
|
||||
"92",
|
||||
);
|
||||
uncontrolled.get("form").element.reset();
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(
|
||||
slotInputs(uncontrolled)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("12");
|
||||
expect(new FormData(uncontrolled.get("form").element).get("code")).toBe(
|
||||
"12",
|
||||
);
|
||||
|
||||
// Cancelable reset keeps the edited value.
|
||||
await slotInputs(uncontrolled)[0].setValue("9");
|
||||
await nextTick();
|
||||
const form = uncontrolled.get("form").element as HTMLFormElement;
|
||||
form.addEventListener(
|
||||
"reset",
|
||||
(event) => {
|
||||
event.preventDefault();
|
||||
},
|
||||
true,
|
||||
);
|
||||
form.reset();
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(
|
||||
slotInputs(uncontrolled)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("92");
|
||||
uncontrolled.unmount();
|
||||
|
||||
const value = ref("34");
|
||||
const controlled = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ value }),
|
||||
render: () =>
|
||||
h("form", null, [
|
||||
h(
|
||||
InputOTP,
|
||||
{
|
||||
maxLength: 4,
|
||||
modelValue: value.value,
|
||||
"onUpdate:modelValue": () => {
|
||||
/* parent rejects */
|
||||
},
|
||||
},
|
||||
() =>
|
||||
h(InputOTPGroup, () =>
|
||||
[0, 1, 2, 3].map((i) => h(InputOTPSlot, { index: i })),
|
||||
),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await nextTick();
|
||||
await slotInputs(controlled)[0].setValue("9");
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(
|
||||
slotInputs(controlled)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("34");
|
||||
controlled.get("form").element.reset();
|
||||
await nextTick();
|
||||
expect(
|
||||
slotInputs(controlled)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("34");
|
||||
controlled.unmount();
|
||||
});
|
||||
|
||||
it("restores real inputs after a rejected controlled update and allows retry", async () => {
|
||||
const updates: string[] = [];
|
||||
const value = ref("12");
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ value }),
|
||||
render: () =>
|
||||
h(
|
||||
InputOTP,
|
||||
{
|
||||
maxLength: 4,
|
||||
modelValue: value.value,
|
||||
"onUpdate:modelValue": (v: string) => {
|
||||
updates.push(v);
|
||||
},
|
||||
},
|
||||
() =>
|
||||
h(InputOTPGroup, () =>
|
||||
[0, 1, 2, 3].map((i) => h(InputOTPSlot, { index: i })),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await nextTick();
|
||||
await slotInputs(w)[2].setValue("9");
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(
|
||||
slotInputs(w)
|
||||
.map((i) => (i.element as HTMLInputElement).value)
|
||||
.join(""),
|
||||
).toBe("12");
|
||||
await slotInputs(w)[2].setValue("9");
|
||||
await nextTick();
|
||||
expect(updates.filter((u) => u === "129").length).toBe(2);
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("middle deletion keeps slot values aligned without left-shift", async () => {
|
||||
const value = ref("1234");
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ value }),
|
||||
render: () =>
|
||||
h(
|
||||
InputOTP,
|
||||
{
|
||||
maxLength: 4,
|
||||
modelValue: value.value,
|
||||
"onUpdate:modelValue": (v: string) => {
|
||||
value.value = v;
|
||||
},
|
||||
},
|
||||
() =>
|
||||
h(InputOTPGroup, () =>
|
||||
[0, 1, 2, 3].map((i) => h(InputOTPSlot, { index: i })),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await nextTick();
|
||||
await slotInputs(w)[1].trigger("keydown", { key: "Delete" });
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
expect(
|
||||
slotInputs(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"]);
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("InputOTP demos", () => {
|
||||
it("mounts all 11 demos without Vue warnings", async () => {
|
||||
const names = [
|
||||
"basic",
|
||||
"variants",
|
||||
"on-surface",
|
||||
"disabled",
|
||||
"four-digits",
|
||||
"controlled",
|
||||
"on-complete",
|
||||
"form-example",
|
||||
"with-pattern",
|
||||
"with-validation",
|
||||
"custom-styles",
|
||||
];
|
||||
expect(names).toHaveLength(11);
|
||||
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/input-otp-${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([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("InputOTP types", () => {
|
||||
it("accepts legal string model and rejects illegal variant", () => {
|
||||
const ok: InstanceType<typeof InputOTPRoot>["$props"] = {
|
||||
modelValue: "123",
|
||||
maxLength: 6,
|
||||
variant: "secondary",
|
||||
};
|
||||
expect(ok.modelValue).toBe("123");
|
||||
const bad: InstanceType<typeof InputOTPRoot>["$props"] = {
|
||||
maxLength: 4,
|
||||
// @ts-expect-error variant must be primary | secondary
|
||||
variant: "ghost",
|
||||
};
|
||||
expect((bad as { variant?: string }).variant).toBe("ghost");
|
||||
});
|
||||
});
|
||||
|
||||
describe("InputOTP SSR", () => {
|
||||
it("renders without touching browser globals", async () => {
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(InputOTP, { maxLength: 4, name: "code", defaultValue: "12" }, () =>
|
||||
h(InputOTPGroup, () =>
|
||||
[0, 1, 2, 3].map((i) => h(InputOTPSlot, { index: i })),
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
expect(html).toContain('data-slot="input-otp"');
|
||||
expect(html).toContain("hv-input-otp");
|
||||
expect(html).toContain('data-slot="input-otp-slot"');
|
||||
expect(html).toContain("1");
|
||||
expect(html).toContain('name="code"');
|
||||
});
|
||||
});
|
||||
@@ -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,623 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { createSSRApp, defineComponent, h, nextTick, ref } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationEllipsis,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
PaginationNext,
|
||||
PaginationNextIcon,
|
||||
PaginationPrevious,
|
||||
PaginationPreviousIcon,
|
||||
PaginationRoot,
|
||||
PaginationSummary,
|
||||
} from "../packages/vue/src";
|
||||
|
||||
import PaginationBasicDemo from "../apps/docs/demos/pagination-basic.vue";
|
||||
import PaginationSizesDemo from "../apps/docs/demos/pagination-sizes.vue";
|
||||
import PaginationDisabledDemo from "../apps/docs/demos/pagination-disabled.vue";
|
||||
import PaginationSimplePrevNextDemo from "../apps/docs/demos/pagination-simple-prev-next.vue";
|
||||
import PaginationControlledDemo from "../apps/docs/demos/pagination-controlled.vue";
|
||||
import PaginationWithEllipsisDemo from "../apps/docs/demos/pagination-with-ellipsis.vue";
|
||||
import PaginationWithSummaryDemo from "../apps/docs/demos/pagination-with-summary.vue";
|
||||
import PaginationCustomIconsDemo from "../apps/docs/demos/pagination-custom-icons.vue";
|
||||
import PaginationCustomStylesDemo from "../apps/docs/demos/pagination-custom-styles.vue";
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
function mountFull(props: Record<string, unknown> = {}, rootProps = {}) {
|
||||
return mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Pagination, { ...rootProps }, () =>
|
||||
h(PaginationContent, () => [
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationPrevious, props.previous ?? {}, () => [
|
||||
h(PaginationPreviousIcon),
|
||||
h("span", "上一页"),
|
||||
]),
|
||||
),
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationLink, props.link ?? {}, () => "1"),
|
||||
),
|
||||
h(PaginationItem, () => h(PaginationEllipsis)),
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationNext, props.next ?? {}, () => [
|
||||
h("span", "下一页"),
|
||||
h(PaginationNextIcon),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
}
|
||||
|
||||
describe("Pagination structure and ARIA", () => {
|
||||
it("renders nav/list/listitem with baseline slots and classes", () => {
|
||||
const w = mountFull({}, { size: "md" });
|
||||
const root = w.get('[data-slot="pagination"]');
|
||||
expect(root.element.tagName).toBe("NAV");
|
||||
expect(root.attributes("role")).toBe("navigation");
|
||||
expect(root.attributes("aria-label")).toBe("pagination");
|
||||
expect(root.classes().join(" ")).toContain("hv-pagination");
|
||||
expect(root.classes().join(" ")).toContain("hv-pagination--md");
|
||||
|
||||
const content = w.get('[data-slot="pagination-content"]');
|
||||
expect(content.element.tagName).toBe("UL");
|
||||
expect(content.classes().join(" ")).toContain("hv-pagination__content");
|
||||
|
||||
const items = w.findAll('[data-slot="pagination-item"]');
|
||||
expect(items).toHaveLength(4);
|
||||
for (const item of items) {
|
||||
expect(item.element.tagName).toBe("LI");
|
||||
expect(item.classes().join(" ")).toContain("hv-pagination__item");
|
||||
}
|
||||
|
||||
const link = w.get('[data-slot="pagination-link"]');
|
||||
expect(link.element.tagName).toBe("BUTTON");
|
||||
expect(link.attributes("type")).toBe("button");
|
||||
expect(link.classes().join(" ")).toContain("hv-pagination__link");
|
||||
expect(link.classes().join(" ")).not.toContain("hv-button");
|
||||
|
||||
const previous = w.get('[data-slot="pagination-previous"]');
|
||||
expect(previous.element.tagName).toBe("BUTTON");
|
||||
expect(previous.attributes("type")).toBe("button");
|
||||
expect(previous.classes().join(" ")).toContain("hv-pagination__link");
|
||||
expect(previous.classes().join(" ")).toContain("hv-pagination__link--nav");
|
||||
expect(previous.classes().join(" ")).not.toContain("hv-button");
|
||||
|
||||
const next = w.get('[data-slot="pagination-next"]');
|
||||
expect(next.classes().join(" ")).toContain("hv-pagination__link--nav");
|
||||
|
||||
const ellipsis = w.get('[data-slot="pagination-ellipsis"]');
|
||||
expect(ellipsis.element.tagName).toBe("SPAN");
|
||||
expect(ellipsis.attributes("aria-hidden")).toBe("true");
|
||||
expect(ellipsis.text()).toBe("…");
|
||||
|
||||
const prevIcon = w.get('[data-slot="pagination-previous-icon"]');
|
||||
expect(prevIcon.attributes("aria-hidden")).toBe("true");
|
||||
expect(prevIcon.find("svg").exists()).toBe(true);
|
||||
|
||||
const nextIcon = w.get('[data-slot="pagination-next-icon"]');
|
||||
expect(nextIcon.attributes("aria-hidden")).toBe("true");
|
||||
expect(nextIcon.find("svg").exists()).toBe(true);
|
||||
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("exposes Pagination as Root alias and isolated instances", () => {
|
||||
expect(Pagination).toBe(PaginationRoot);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h("div", () => [
|
||||
h(Pagination, { "data-testid": "a" }, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationLink, { isActive: true }, () => "1"),
|
||||
),
|
||||
),
|
||||
),
|
||||
h(Pagination, { "data-testid": "b", size: "lg" }, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationLink, { isActive: true }, () => "1"),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const roots = w.findAll('[data-slot="pagination"]');
|
||||
expect(roots).toHaveLength(2);
|
||||
expect(roots[0].classes().join(" ")).toContain("hv-pagination--md");
|
||||
expect(roots[1].classes().join(" ")).toContain("hv-pagination--lg");
|
||||
expect(roots[0].attributes("aria-label")).toBe("pagination");
|
||||
expect(roots[0].attributes("data-testid")).toBe("a");
|
||||
expect(roots[1].attributes("data-testid")).toBe("b");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("updates size context dynamically and keeps custom classes", async () => {
|
||||
const size = ref<"sm" | "md" | "lg">("sm");
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ size }),
|
||||
render: () =>
|
||||
h(Pagination, { size: size.value, class: "custom-root" }, () =>
|
||||
h(PaginationContent, { class: "custom-content" }, () =>
|
||||
h(PaginationItem, { class: "custom-item" }, () =>
|
||||
h(PaginationLink, { class: "custom-link" }, () => "1"),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
let root = w.get('[data-slot="pagination"]');
|
||||
expect(root.classes().join(" ")).toContain("hv-pagination--sm");
|
||||
expect(root.classes().join(" ")).toContain("custom-root");
|
||||
expect(w.get('[data-slot="pagination-content"]').classes()).toContain(
|
||||
"custom-content",
|
||||
);
|
||||
expect(w.get('[data-slot="pagination-item"]').classes()).toContain(
|
||||
"custom-item",
|
||||
);
|
||||
expect(w.get('[data-slot="pagination-link"]').classes()).toContain(
|
||||
"custom-link",
|
||||
);
|
||||
|
||||
size.value = "lg";
|
||||
await nextTick();
|
||||
root = w.get('[data-slot="pagination"]');
|
||||
expect(root.classes().join(" ")).toContain("hv-pagination--lg");
|
||||
expect(root.classes().join(" ")).not.toContain("hv-pagination--sm");
|
||||
expect(root.classes().join(" ")).toContain("custom-root");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("keeps nested pagination size contexts independent", () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Pagination, { size: "sm", "data-testid": "outer" }, () =>
|
||||
h(PaginationContent, () => [
|
||||
h(PaginationItem, () => h(PaginationLink, () => "1")),
|
||||
h(PaginationItem, () =>
|
||||
h(Pagination, { size: "lg", "data-testid": "inner" }, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () => h(PaginationLink, () => "2")),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const outer = w.get('[data-testid="outer"]');
|
||||
const inner = w.get('[data-testid="inner"]');
|
||||
expect(outer.classes().join(" ")).toContain("hv-pagination--sm");
|
||||
expect(inner.classes().join(" ")).toContain("hv-pagination--lg");
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pagination active and summary states", () => {
|
||||
it("toggles aria-current and data-active with isActive", async () => {
|
||||
const isActive = ref(true);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ isActive }),
|
||||
render: () =>
|
||||
h(Pagination, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationLink, { isActive: isActive.value }, () => "3"),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
let link = w.get('[data-slot="pagination-link"]');
|
||||
expect(link.attributes("aria-current")).toBe("page");
|
||||
expect(link.attributes("data-active")).toBe("true");
|
||||
|
||||
isActive.value = false;
|
||||
await nextTick();
|
||||
link = w.get('[data-slot="pagination-link"]');
|
||||
expect(link.attributes("aria-current")).toBeUndefined();
|
||||
expect(link.attributes("data-active")).toBeUndefined();
|
||||
|
||||
isActive.value = true;
|
||||
await nextTick();
|
||||
link = w.get('[data-slot="pagination-link"]');
|
||||
expect(link.attributes("aria-current")).toBe("page");
|
||||
expect(link.attributes("data-active")).toBe("true");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("summary defaults to dir=auto and allows explicit dir override", async () => {
|
||||
const dir = ref<string | undefined>(undefined);
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
setup: () => ({ dir }),
|
||||
render: () =>
|
||||
h(Pagination, () =>
|
||||
h(PaginationSummary, { dir: dir.value }, () => "1–5 of 10"),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
let summary = w.get('[data-slot="pagination-summary"]');
|
||||
expect(summary.element.tagName).toBe("DIV");
|
||||
expect(summary.attributes("dir")).toBe("auto");
|
||||
expect(summary.classes().join(" ")).toContain("hv-pagination__summary");
|
||||
|
||||
dir.value = "rtl";
|
||||
await nextTick();
|
||||
summary = w.get('[data-slot="pagination-summary"]');
|
||||
expect(summary.attributes("dir")).toBe("rtl");
|
||||
|
||||
dir.value = undefined;
|
||||
await nextTick();
|
||||
summary = w.get('[data-slot="pagination-summary"]');
|
||||
expect(summary.attributes("dir")).toBe("auto");
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pagination button behavior", () => {
|
||||
it("activates once on click and does not when disabled", async () => {
|
||||
const clicks = vi.fn();
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Pagination, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () =>
|
||||
h(
|
||||
PaginationLink,
|
||||
{ isDisabled: false, onClick: clicks },
|
||||
() => "1",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await w.get('[data-slot="pagination-link"]').trigger("click");
|
||||
expect(clicks).toHaveBeenCalledTimes(1);
|
||||
|
||||
await w.unmount();
|
||||
|
||||
const disabledClicks = vi.fn();
|
||||
const w2 = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Pagination, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () =>
|
||||
h(
|
||||
PaginationLink,
|
||||
{ isDisabled: true, onClick: disabledClicks },
|
||||
() => "1",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const disabledLink = w2.get('[data-slot="pagination-link"]');
|
||||
expect(disabledLink.attributes("disabled")).toBeDefined();
|
||||
expect((disabledLink.element as HTMLButtonElement).disabled).toBe(true);
|
||||
await disabledLink.trigger("click");
|
||||
expect(disabledClicks).not.toHaveBeenCalled();
|
||||
w2.unmount();
|
||||
});
|
||||
|
||||
it("supports handler arrays, capture and stopImmediatePropagation", async () => {
|
||||
const order: string[] = [];
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Pagination, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () =>
|
||||
h(
|
||||
PaginationLink,
|
||||
{
|
||||
onClick: [
|
||||
() => order.push("a"),
|
||||
(e: Event) => {
|
||||
order.push("b");
|
||||
e.stopImmediatePropagation();
|
||||
},
|
||||
],
|
||||
},
|
||||
() => "1",
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
await w.get('[data-slot="pagination-link"]').trigger("click");
|
||||
expect(order).toEqual(["a", "b"]);
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("keeps Previous/Next disabled state on native buttons", async () => {
|
||||
const w = mountFull({
|
||||
previous: { isDisabled: true },
|
||||
next: { disabled: true },
|
||||
});
|
||||
const previous = w.get('[data-slot="pagination-previous"]');
|
||||
const next = w.get('[data-slot="pagination-next"]');
|
||||
expect((previous.element as HTMLButtonElement).disabled).toBe(true);
|
||||
expect((next.element as HTMLButtonElement).disabled).toBe(true);
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pagination attrs merge", () => {
|
||||
it("adds, updates, deletes and re-adds root and leaf attrs", async () => {
|
||||
const extra = ref<Record<string, unknown>>({});
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
components: {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
},
|
||||
setup: () => ({ extra }),
|
||||
template: `
|
||||
<Pagination v-bind="extra" class="base-root">
|
||||
<PaginationContent v-bind="extra">
|
||||
<PaginationItem v-bind="extra">
|
||||
<PaginationLink v-bind="extra">1</PaginationLink>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
`,
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
|
||||
let root = w.get('[data-slot="pagination"]');
|
||||
expect(root.classes()).toContain("base-root");
|
||||
expect(root.attributes("data-testid")).toBeUndefined();
|
||||
|
||||
extra.value = {
|
||||
"data-testid": "p1",
|
||||
"aria-label": "页码",
|
||||
tabindex: 0,
|
||||
onClick: () => {},
|
||||
};
|
||||
await nextTick();
|
||||
root = w.get('[data-slot="pagination"]');
|
||||
expect(root.attributes("data-testid")).toBe("p1");
|
||||
expect(root.attributes("aria-label")).toBe("页码");
|
||||
expect(root.attributes("tabindex")).toBe("0");
|
||||
const link = w.get('[data-slot="pagination-link"]');
|
||||
expect(link.attributes("data-testid")).toBe("p1");
|
||||
expect(link.attributes("aria-label")).toBe("页码");
|
||||
expect(link.attributes("tabindex")).toBe("0");
|
||||
|
||||
extra.value = { "data-testid": "p2", title: "updated" };
|
||||
await nextTick();
|
||||
root = w.get('[data-slot="pagination"]');
|
||||
expect(root.attributes("data-testid")).toBe("p2");
|
||||
expect(root.attributes("title")).toBe("updated");
|
||||
expect(root.attributes("aria-label")).toBe("pagination");
|
||||
expect(root.attributes("tabindex")).toBeUndefined();
|
||||
|
||||
extra.value = {};
|
||||
await nextTick();
|
||||
root = w.get('[data-slot="pagination"]');
|
||||
expect(root.attributes("data-testid")).toBeUndefined();
|
||||
expect(root.attributes("title")).toBeUndefined();
|
||||
|
||||
extra.value = { style: { color: "red" }, "aria-current": "true" };
|
||||
await nextTick();
|
||||
root = w.get("[data-slot=pagination]");
|
||||
expect(root.attributes("style")).toContain("color: red");
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("preserves asChild native child attributes", async () => {
|
||||
const w = mount(
|
||||
defineComponent({
|
||||
render: () =>
|
||||
h(Pagination, () =>
|
||||
h(PaginationContent, () =>
|
||||
h(PaginationItem, () =>
|
||||
h(
|
||||
PaginationLink,
|
||||
{
|
||||
asChild: true,
|
||||
isActive: true,
|
||||
"data-custom": "keep",
|
||||
tabindex: 0,
|
||||
},
|
||||
{
|
||||
default: () =>
|
||||
h("a", { href: "#page-1", id: "native-link" }, "1"),
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
}),
|
||||
{ attachTo: document.body },
|
||||
);
|
||||
const link = w.get("#native-link");
|
||||
expect(link.element.tagName).toBe("A");
|
||||
expect(link.attributes("href")).toBe("#page-1");
|
||||
expect(link.attributes("data-custom")).toBe("keep");
|
||||
expect(link.attributes("tabindex")).toBe("0");
|
||||
expect(link.attributes("aria-current")).toBe("page");
|
||||
expect(link.attributes("data-active")).toBe("true");
|
||||
expect(link.attributes("data-slot")).toBe("pagination-link");
|
||||
w.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pagination demos", () => {
|
||||
it("controlled demo pages, disables at bounds and keeps summary in sync", async () => {
|
||||
const w = mount(PaginationControlledDemo, { attachTo: document.body });
|
||||
const previous = w.get('[data-slot="pagination-previous"]');
|
||||
const next = w.get('[data-slot="pagination-next"]');
|
||||
expect((previous.element as HTMLButtonElement).disabled).toBe(true);
|
||||
expect((next.element as HTMLButtonElement).disabled).toBe(false);
|
||||
expect(w.get('[data-slot="pagination-summary"]').text()).toContain(
|
||||
"第 1–10 条",
|
||||
);
|
||||
expect(
|
||||
w.get('[data-slot="pagination-link"][data-active="true"]').text(),
|
||||
).toBe("1");
|
||||
|
||||
await next.trigger("click");
|
||||
await nextTick();
|
||||
expect(w.get('[data-slot="pagination-summary"]').text()).toContain(
|
||||
"第 11–20 条",
|
||||
);
|
||||
expect(
|
||||
w.get('[data-slot="pagination-link"][data-active="true"]').text(),
|
||||
).toBe("2");
|
||||
expect(
|
||||
(w.get('[data-slot="pagination-previous"]').element as HTMLButtonElement)
|
||||
.disabled,
|
||||
).toBe(false);
|
||||
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const nextBtn = w.get('[data-slot="pagination-next"]');
|
||||
if ((nextBtn.element as HTMLButtonElement).disabled) break;
|
||||
await nextBtn.trigger("click");
|
||||
}
|
||||
await nextTick();
|
||||
expect(
|
||||
(w.get('[data-slot="pagination-next"]').element as HTMLButtonElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
expect(w.get('[data-slot="pagination-summary"]').text()).toContain(
|
||||
"第 111–120 条",
|
||||
);
|
||||
expect(
|
||||
w.get('[data-slot="pagination-link"][data-active="true"]').text(),
|
||||
).toBe("12");
|
||||
expect(
|
||||
w.findAll('[data-slot="pagination-ellipsis"]').length,
|
||||
).toBeGreaterThan(0);
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("basic demo updates the active page", async () => {
|
||||
const w = mount(PaginationBasicDemo, { attachTo: document.body });
|
||||
const links = w.findAll('[data-slot="pagination-link"]');
|
||||
expect(links[0].attributes("data-active")).toBe("true");
|
||||
await links[2].trigger("click");
|
||||
await nextTick();
|
||||
expect(links[2].attributes("data-active")).toBe("true");
|
||||
expect(links[0].attributes("data-active")).toBeUndefined();
|
||||
w.unmount();
|
||||
});
|
||||
|
||||
it("mounts all 9 pagination demos without Vue warnings", async () => {
|
||||
const warnings: string[] = [];
|
||||
const spy = vi.spyOn(console, "warn").mockImplementation((...args) => {
|
||||
warnings.push(args.map(String).join(" "));
|
||||
});
|
||||
const demos = [
|
||||
PaginationBasicDemo,
|
||||
PaginationSizesDemo,
|
||||
PaginationDisabledDemo,
|
||||
PaginationSimplePrevNextDemo,
|
||||
PaginationControlledDemo,
|
||||
PaginationWithEllipsisDemo,
|
||||
PaginationWithSummaryDemo,
|
||||
PaginationCustomIconsDemo,
|
||||
PaginationCustomStylesDemo,
|
||||
];
|
||||
expect(demos).toHaveLength(9);
|
||||
for (const demo of demos) {
|
||||
const w = mount(demo, { attachTo: document.body });
|
||||
await nextTick();
|
||||
expect(w.html().length).toBeGreaterThan(0);
|
||||
w.unmount();
|
||||
}
|
||||
spy.mockRestore();
|
||||
expect(warnings).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pagination types", () => {
|
||||
it("accepts legal props and rejects illegal size values", () => {
|
||||
const bad: InstanceType<typeof PaginationRoot>["$props"] = {
|
||||
// @ts-expect-error size must be sm | md | lg
|
||||
size: "xl",
|
||||
};
|
||||
expect((bad as { size?: string }).size).toBe("xl");
|
||||
const ok: InstanceType<typeof PaginationRoot>["$props"] = {
|
||||
size: "lg",
|
||||
};
|
||||
expect(ok.size).toBe("lg");
|
||||
|
||||
const okLink: InstanceType<typeof PaginationLink>["$props"] = {
|
||||
isActive: true,
|
||||
isDisabled: false,
|
||||
};
|
||||
expect(okLink.isActive).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Pagination SSR", () => {
|
||||
it("renders without touching browser globals", async () => {
|
||||
const html = await renderToString(
|
||||
createSSRApp({
|
||||
render: () =>
|
||||
h(Pagination, { size: "sm" }, () => [
|
||||
h(PaginationSummary, () => "显示第 1–10 条,共 120 条结果"),
|
||||
h(PaginationContent, () => [
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationPrevious, { isDisabled: true }, () => [
|
||||
h(PaginationPreviousIcon),
|
||||
h("span", "上一页"),
|
||||
]),
|
||||
),
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationLink, { isActive: true }, () => "1"),
|
||||
),
|
||||
h(PaginationItem, () => h(PaginationEllipsis)),
|
||||
h(PaginationItem, () =>
|
||||
h(PaginationNext, () => [
|
||||
h("span", "下一页"),
|
||||
h(PaginationNextIcon),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(html).toContain('data-slot="pagination"');
|
||||
expect(html).toContain("hv-pagination--sm");
|
||||
expect(html).toContain('dir="auto"');
|
||||
expect(html).toContain('aria-current="page"');
|
||||
expect(html).toContain('data-active="true"');
|
||||
expect(html).toContain("…");
|
||||
expect(html).toContain("disabled");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user