feat: initialize Vue component library and aligned documentation

This commit is contained in:
maoyingjie
2026-10-21 09:06:28 +08:00
commit 9d40dc0ecb
149 changed files with 13208 additions and 0 deletions
+170
View File
@@ -0,0 +1,170 @@
import { describe, it, expect } from "vitest";
import { mount } from "@vue/test-utils";
import { h, nextTick, ref } from "vue";
import { readFileSync } from "node:fs";
import {
Input,
Label,
Switch,
SwitchContent,
SwitchControl,
SwitchThumb,
Description,
FieldError,
} from "../packages/vue/src";
import SwitchForm from "../apps/docs/demos/switch-form.vue";
import InputTypes from "../apps/docs/demos/input-types.vue";
import CardForm from "../apps/docs/demos/card-with-form.vue";
const inventory = {
card: [
"default",
"variants",
"horizontal",
"with-avatar",
"with-images",
"with-form",
"custom-styles",
],
input: [
"basic",
"variants",
"on-surface",
"full-width",
"types",
"controlled",
"custom-styles",
],
switch: [
"basic",
"sizes",
"with-icons",
"disabled",
"without-label",
"with-description",
"default-selected",
"controlled",
"label-position",
"group",
"group-horizontal",
"form",
"render-props",
"render-function",
"custom-styles",
],
};
describe("aligned examples", () => {
for (const [component, names] of Object.entries(inventory)) {
it(`${component} preserves the pinned preview inventory and order`, () => {
const text = readFileSync(`apps/docs/components/${component}.md`, "utf8");
expect(
[...text.matchAll(/<ComponentPreview name="([^"]+)"/g)].map(
(m) => m[1],
),
).toEqual(names.map((n) => `${component}-${n}`));
});
}
it("associates each input with its visible label and generates unique IDs per instance", () => {
const w = mount({ render: () => [h(InputTypes), h(InputTypes)] });
const ids = w.findAll("input").map((e) => e.attributes("id"));
expect(new Set(ids).size).toBe(6);
for (const label of w.findAll("label"))
expect(ids).toContain(label.attributes("for"));
w.unmount();
});
it("restores controlled Input DOM when the parent declines an update", async () => {
const w = mount(Input, { props: { modelValue: "固定" } });
await w.get("input").setValue("编辑");
await nextTick();
expect(w.element.value).toBe("固定");
w.unmount();
});
it("submits actual selected values and restores Switch defaults on form reset", async () => {
const w = mount(SwitchForm, { attachTo: document.body });
const form = w.get("form").element as HTMLFormElement;
const switches = w.findAll("[role=switch]");
expect(new FormData(form).get("newsletter")).toBe("on");
await switches[0].trigger("click");
await switches[1].trigger("click");
expect(new FormData(form).get("notifications")).toBe("on");
expect(new FormData(form).has("newsletter")).toBe(false);
await w.get("form").trigger("submit");
expect(w.get("output").text()).toContain("notifications: on");
form.reset();
await nextTick();
await nextTick();
expect(switches[0].attributes("aria-checked")).toBe("false");
expect(switches[1].attributes("aria-checked")).toBe("true");
w.unmount();
});
it("passes root ARIA attributes into composed SwitchContent and preserves container styles", async () => {
const name = ref("静音");
const w = mount({
render: () =>
h(
Switch,
{ "aria-label": name.value, class: "custom", style: "gap:20px" },
() => h(SwitchContent, () => h(SwitchControl, () => h(SwitchThumb))),
),
});
expect(w.get("[role=switch]").attributes("aria-label")).toBe("静音");
expect(w.get("[data-slot=switch]").classes()).toContain("custom");
name.value = "音量";
await nextTick();
expect(w.get("[role=switch]").attributes("aria-label")).toBe("音量");
w.unmount();
});
it("blocks readonly keyboard activation and supports native and ARIA validation", async () => {
const w = mount(Switch, {
attachTo: document.body,
props: {
isReadOnly: true,
isRequired: true,
validate: (v) => (v ? true : "请启用"),
},
slots: {
default: () => [
h(SwitchContent, () => [
h(SwitchControl, () => h(SwitchThumb)),
h(Label, () => "通知"),
]),
h(Description, () => "描述一"),
h(Description, () => "描述二"),
h(FieldError),
],
},
});
const control = w.get("[role=switch]");
await control.trigger("keydown", { key: "Enter" });
expect(w.emitted("change")).toBeUndefined();
const ids = w
.findAll("[data-slot=description]")
.map((e) => e.attributes("id"));
expect(new Set(ids).size).toBe(2);
for (const id of ids)
expect(control.attributes("aria-describedby")).toContain(id);
await w.setProps({ isReadOnly: false });
expect((w.get("input").element as HTMLInputElement).checkValidity()).toBe(
false,
);
await nextTick();
expect(w.get("[role=alert]").text()).toBe("请启用");
expect(document.activeElement).toBe(control.element);
await control.trigger("click");
expect(w.find("[role=alert]").exists()).toBe(false);
await w.setProps({ checked: false, validationBehavior: "aria" });
expect(control.attributes("aria-invalid")).toBe("true");
expect((w.get("input").element as HTMLInputElement).checkValidity()).toBe(
true,
);
w.unmount();
});
it("renders a working Card form using labelled native fields", async () => {
const w = mount(CardForm);
expect(w.findAll("label")).toHaveLength(2);
await w.get("input[type=email]").setValue("test@example.com");
await w.get("input[type=password]").setValue("test-pass");
await w.get("form").trigger("submit");
expect(w.get("[role=status]").text()).toContain("表单提交成功");
w.unmount();
});
});
+115
View File
@@ -0,0 +1,115 @@
import { afterEach, describe, it, expect, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { h } from "vue";
import { readFileSync } from "node:fs";
import { Button } from "../packages/vue/src";
import LoadingState from "../apps/docs/demos/button-loading-state.vue";
import Ripple from "../apps/docs/demos/button-ripple-effect.vue";
const expected = [
"basic",
"variants",
"sizes",
"with-icons",
"icon-only",
"loading",
"loading-state",
"full-width",
"disabled",
"social",
"render-function",
"custom-variants",
"ripple-effect",
"custom-styles",
];
afterEach(() => vi.useRealTimers());
describe("Button examples", () => {
it("includes every preview in the pinned upstream Button document", () => {
const document = readFileSync("apps/docs/components/button.md", "utf8");
const names = [
...document.matchAll(/<ComponentPreview name="button-([^"]+)"/g),
].map((match) => match[1]);
expect(names).toEqual(expected);
for (const name of names)
expect(
readFileSync(`apps/docs/demos/button-${name}.vue`, "utf8"),
).toContain("<template>");
});
it("allows upload, suppresses duplicate activation, restores the button and allows another upload", async () => {
vi.useFakeTimers();
const w = mount(LoadingState, { attachTo: document.body });
const button = w.get("button");
expect(button.text()).toBe("上传文件");
expect(button.attributes("disabled")).toBeUndefined();
(button.element as HTMLButtonElement).focus();
await button.trigger("click");
expect(button.text()).toBe("上传中…");
expect(button.attributes("aria-disabled")).toBe("true");
expect(document.activeElement).toBe(button.element);
expect(button.attributes("disabled")).toBeUndefined();
await vi.advanceTimersByTimeAsync(1000);
await button.trigger("click");
await vi.advanceTimersByTimeAsync(1000);
expect(button.text()).toBe("上传文件");
expect(button.attributes("aria-disabled")).toBeUndefined();
expect(w.get("[role=status]").text()).toContain("上传完成");
await button.trigger("click");
expect(button.text()).toBe("上传中…");
w.unmount();
expect(vi.getTimerCount()).toBe(0);
});
it("treats loading as pending, not native disabled, while preventing repeat clicks", async () => {
const click = vi.fn();
const w = mount(Button, {
props: { loading: true },
attrs: { onClick: click },
});
await w.trigger("click");
expect(click).not.toHaveBeenCalled();
expect(w.attributes("disabled")).toBeUndefined();
await w.setProps({ loading: false });
await w.trigger("click");
expect(click).toHaveBeenCalledOnce();
});
it("clears hover and pressed states when loading starts and does not restore stale states", async () => {
const w = mount(Button);
await w.trigger("pointerenter");
await w.trigger("pointerdown");
expect(w.attributes("data-hovered")).toBe("true");
expect(w.attributes("data-pressed")).toBe("true");
await w.setProps({ isPending: true });
expect(w.attributes("data-hovered")).toBeUndefined();
expect(w.attributes("data-pressed")).toBeUndefined();
await w.trigger("keydown", { key: "Enter" });
expect(w.attributes("data-pressed")).toBeUndefined();
await w.setProps({ isPending: false });
expect(w.attributes("data-hovered")).toBeUndefined();
expect(w.attributes("data-pressed")).toBeUndefined();
w.unmount();
});
it("merges interaction and classes onto a custom native button and exposes pressed slot state", async () => {
const w = mount(Button, {
props: { asChild: true },
slots: {
default: (state) =>
h(
"button",
{ "data-custom": state.isPressed ? "pressed" : "bar" },
"点按",
),
},
});
expect(w.findAll("button")).toHaveLength(1);
expect(w.get("button").classes()).toContain("hv-button");
await w.get("button").trigger("pointerdown");
expect(w.get("button").attributes("data-custom")).toBe("pressed");
await w.get("button").trigger("pointerup");
expect(w.get("button").attributes("data-custom")).toBe("bar");
});
it("creates a keyboard ripple and removes the finished animation", async () => {
const w = mount(Ripple);
await w.get("button").trigger("keydown", { key: "Enter" });
expect(w.findAll(".ripple-wave")).toHaveLength(1);
await w.get(".ripple-wave").trigger("animationend");
expect(w.findAll(".ripple-wave")).toHaveLength(0);
});
});
+110
View File
@@ -0,0 +1,110 @@
import { describe, it, expect } from "vitest";
import { mount } from "@vue/test-utils";
import { Button, Input, Switch } from "../packages/vue/src";
describe("Button", () => {
it("defaults to a non-submit button and blocks loading interactions", async () => {
const w = mount(Button, {
props: { loading: true },
slots: { default: "保存" },
});
expect(w.attributes("type")).toBe("button");
expect(w.attributes("disabled")).toBeUndefined();
expect(w.attributes("data-pending")).toBe("true");
expect(w.attributes("aria-busy")).toBe("true");
});
});
describe("Input", () => {
it("emits values without mutating a controlled value", async () => {
const w = mount(Input, {
props: { modelValue: "原值" },
attrs: { "aria-label": "名称", name: "name" },
});
await w.get("input").setValue("新值");
expect(w.emitted("update:modelValue")).toEqual([["新值"]]);
await w.setProps({ modelValue: "父级值" });
expect(w.element.value).toBe("父级值");
expect(w.attributes("name")).toBe("name");
});
it("supports uncontrolled initial values and native form reset", async () => {
const form = document.createElement("form");
document.body.append(form);
const w = mount(Input, { props: { defaultValue: "初始" }, attachTo: form });
await w.get("input").setValue("编辑");
expect(w.element.value).toBe("编辑");
form.reset();
await w.vm.$nextTick();
expect(w.element.value).toBe("初始");
w.unmount();
form.remove();
});
});
describe("Switch", () => {
it("emits the checked model and exposes accessible state", async () => {
const w = mount(Switch, {
props: { checked: false },
attrs: { "aria-label": "通知" },
});
expect(w.get("[role=switch]").attributes("role")).toBe("switch");
await w.get("[role=switch]").trigger("click");
expect(w.emitted("update:checked")).toEqual([[true]]);
await w.setProps({ checked: true });
expect(w.get("[role=switch]").attributes("aria-checked")).toBe("true");
});
it("supports uncontrolled defaultChecked", async () => {
const w = mount(Switch, { props: { defaultChecked: true } });
expect(w.get("[role=switch]").attributes("aria-checked")).toBe("true");
await w.get("[role=switch]").trigger("click");
expect(w.get("[role=switch]").attributes("aria-checked")).toBe("false");
});
it("prevents toggling when disabled", async () => {
const w = mount(Switch, { props: { disabled: true, checked: false } });
await w.get("[role=switch]").trigger("click");
expect(w.emitted("update:checked")).toBeUndefined();
});
});
describe("upstream component contracts", () => {
it("keeps pending buttons focusable and suppresses repeated activation", async () => {
let clicks = 0;
const w = mount(Button, {
props: { isPending: true },
attrs: { onClick: () => clicks++ },
});
expect(w.attributes("disabled")).toBeUndefined();
expect(w.attributes("data-pending")).toBe("true");
await w.trigger("click");
expect(clicks).toBe(0);
await w.setProps({ isPending: false });
await w.trigger("click");
expect(clicks).toBe(1);
});
it("applies icon-only and soft danger variants without leaking props to the DOM", () => {
const w = mount(Button, {
props: { variant: "danger-soft", isIconOnly: true, isDisabled: true },
attrs: { "aria-label": "删除" },
});
expect(w.classes()).toContain("hv-button--danger-soft");
expect(w.classes()).toContain("hv-button--icon-only");
expect(w.attributes("disabled")).toBeDefined();
expect(w.attributes("isicononly")).toBeUndefined();
});
it("maps Input secondary and invalid states to the documented CSS hooks", () => {
const w = mount(Input, {
props: { variant: "secondary", fullWidth: true, invalid: true },
});
expect(w.classes()).toContain("hv-input--secondary");
expect(w.classes()).toContain("hv-input--full-width");
expect(w.attributes("data-invalid")).toBe("true");
expect(w.attributes("aria-invalid")).toBe("true");
});
it("preserves readonly switch values and gives isSelected precedence", async () => {
const w = mount(Switch, {
props: { isSelected: true, checked: false, isReadOnly: true },
});
const control = w.get("[role=switch]");
expect(control.attributes("aria-checked")).toBe("true");
expect(control.attributes("aria-readonly")).toBe("true");
await control.trigger("click");
expect(w.emitted("change")).toBeUndefined();
});
});
+73
View File
@@ -0,0 +1,73 @@
import { describe, it, expect } from "vitest";
import { h } from "vue";
import { mount } from "@vue/test-utils";
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
Switch,
SwitchContent,
SwitchControl,
SwitchThumb,
Description,
} from "../packages/vue/src";
describe("compound components", () => {
it("preserves Card parts, heading semantics and custom elements", () => {
const w = mount(Card, {
props: { variant: "tertiary", as: "article" },
slots: {
default: () => [
h(CardHeader, () => [
h(CardTitle, () => "成为 Acme 创作者!"),
h(CardDescription, () => "描述"),
]),
h(CardContent, () => "内容"),
h(CardFooter, () => "操作"),
],
},
});
expect(w.element.tagName).toBe("ARTICLE");
expect(w.get("h3").text()).toBe("成为 Acme 创作者!");
for (const part of ["header", "title", "description", "content", "footer"])
expect(w.find(`[data-slot=card-${part}]`).exists()).toBe(true);
});
it("names a composed Switch and associates its Description", async () => {
const w = mount(Switch, {
props: { defaultSelected: true },
slots: {
default: () => [
h(SwitchContent, () => [
h(SwitchControl, () => h(SwitchThumb)),
"公开资料",
]),
h(Description, () => "允许他人查看你的资料信息"),
],
},
});
await w.vm.$nextTick();
const control = w.get("[role=switch]");
expect(control.text()).toBe("公开资料");
expect(control.attributes("aria-describedby")).toBe(
w.get("[data-slot=description]").attributes("id"),
);
await control.trigger("click");
expect(w.emitted("change")).toEqual([[false]]);
});
it("submits the selected Switch form value through the underlying native field", async () => {
const form = document.createElement("form");
document.body.append(form);
const w = mount(Switch, {
attachTo: form,
props: { name: "notifications", value: "enabled", defaultSelected: true },
});
await w.vm.$nextTick();
expect(new FormData(form).get("notifications")).toBe("enabled");
await w.get("[role=switch]").trigger("click");
expect(new FormData(form).get("notifications")).toBeNull();
w.unmount();
form.remove();
});
});
+66
View File
@@ -0,0 +1,66 @@
import { describe, it, expect } from "vitest";
import {
searchDocs,
searchExcerpt,
type SearchEntry,
} from "../apps/docs/.vitepress/theme/search";
const entries: SearchEntry[] = [
{
title: "Button 按钮",
section: "API 参考",
url: "/components/button#api-参考",
text: "isPending boolean 加载期间保留焦点",
},
{
title: "Switch 开关",
section: "API 参考",
url: "/components/switch#api-参考",
text: "isReadOnly 只读 checked",
},
{
title: "主题",
section: "默认主题",
url: "/themes#默认主题",
text: "Button 采用相同颜色变量",
},
{
title: "Input 输入框",
section: "受控组件",
url: "/components/input#受控组件",
text: "使用 v-model 更新输入值",
},
];
describe("documentation search", () => {
it("finds parameters inside API content rather than only page titles", () => {
expect(searchDocs(entries, "ispending").map((e) => e.url)).toEqual([
"/components/button#api-参考",
]);
});
it("ranks component-title matches before incidental content mentions", () => {
expect(searchDocs(entries, "button")[0].title).toBe("Button 按钮");
});
it("requires all search terms and ignores surrounding whitespace and casing", () => {
expect(searchDocs(entries, " SWITCH 只读 ").map((e) => e.title)).toEqual(
["Switch 开关"],
);
});
it("returns no results for blank or unmatched queries", () => {
expect(searchDocs(entries, " ")).toEqual([]);
expect(searchDocs(entries, "unknown-component")).toEqual([]);
});
});
it("shows the matched parameter in excerpts instead of table separator noise", () => {
const entry = {
title: "Button",
section: "API",
url: "/button",
text:
"Prop 类型 -------- " +
"前文 ".repeat(60) +
"isPending boolean 是否处于加载状态",
};
const excerpt = searchExcerpt(entry, "isPending");
expect(excerpt).toContain("isPending");
expect(excerpt).not.toContain("--------");
});
+24
View File
@@ -0,0 +1,24 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>文档窄屏验证</title>
</head>
<body
style="
margin: 0;
background: #e5e5e5;
font: 14px system-ui;
text-align: center;
"
>
<p>390px 文档视口</p>
<iframe
title="390px 文档"
src="/components/button"
width="390"
height="760"
style="border: 1px solid #aaa; border-radius: 12px; background: white"
></iframe>
</body>
</html>
+20
View File
@@ -0,0 +1,20 @@
// @vitest-environment node
import { it, expect } from "vitest";
import { createSSRApp, h } from "vue";
import { renderToString } from "@vue/server-renderer";
import { Button, Card, Input, Switch } from "../packages/vue/src";
it("renders the initial components without browser globals", async () => {
const html = await renderToString(
createSSRApp({
render: () =>
h(Card, () => [
h(Button, () => "保存"),
h(Input, { modelValue: "名称" }),
h(Switch, { checked: true, "aria-label": "通知" }),
]),
}),
);
expect(html).toContain("保存");
expect(html).toContain('value="名称"');
expect(html).toContain('role="switch"');
});