535 lines
17 KiB
TypeScript
535 lines
17 KiB
TypeScript
import { describe, it, expect, afterEach, vi } from "vitest";
|
||
import { mount } from "@vue/test-utils";
|
||
import { defineComponent, h, nextTick, ref } from "vue";
|
||
import { readFileSync } from "node:fs";
|
||
import {
|
||
Description,
|
||
FieldError,
|
||
Form,
|
||
Input,
|
||
InputGroup,
|
||
InputGroupInput,
|
||
Label,
|
||
TextArea,
|
||
TextField,
|
||
} from "../packages/vue/src";
|
||
|
||
afterEach(() => {
|
||
document.body.innerHTML = "";
|
||
});
|
||
|
||
const settle = async () => {
|
||
await nextTick();
|
||
await nextTick();
|
||
};
|
||
|
||
describe("TextArea", () => {
|
||
it("renders native textarea with default rows and variant classes", () => {
|
||
const w = mount(TextArea, {
|
||
props: { rows: 5, variant: "secondary", fullWidth: true },
|
||
});
|
||
const el = w.get("[data-slot=textarea]");
|
||
expect(el.element.tagName).toBe("TEXTAREA");
|
||
expect((el.element as HTMLTextAreaElement).rows).toBe(5);
|
||
expect(el.classes()).toContain("hv-textarea");
|
||
expect(el.classes()).toContain("hv-textarea--secondary");
|
||
expect(el.classes()).toContain("hv-textarea--full-width");
|
||
});
|
||
|
||
it("defaults rows to 3", () => {
|
||
const w = mount(TextArea);
|
||
expect((w.get("textarea").element as HTMLTextAreaElement).rows).toBe(3);
|
||
});
|
||
|
||
it("submits FormData, respects disabled/readonly and resets uncontrolled values", async () => {
|
||
const w = mount(
|
||
defineComponent({
|
||
render: () =>
|
||
h(Form, {}, () => [
|
||
h(TextField, { name: "bio", defaultValue: "start" }, () => [
|
||
h(TextArea),
|
||
]),
|
||
h(
|
||
TextField,
|
||
{ name: "off", defaultValue: "no", isDisabled: true },
|
||
() => [h(TextArea)],
|
||
),
|
||
h(
|
||
TextField,
|
||
{ name: "ro", defaultValue: "yes", isReadOnly: true },
|
||
() => [h(TextArea)],
|
||
),
|
||
]),
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
const areas = w.findAll("textarea");
|
||
await areas[0].setValue("changed");
|
||
expect(
|
||
Object.fromEntries(
|
||
new FormData(w.get("form").element as HTMLFormElement),
|
||
),
|
||
).toEqual({ bio: "changed", ro: "yes" });
|
||
(w.get("form").element as HTMLFormElement).reset();
|
||
await settle();
|
||
expect((areas[0].element as HTMLTextAreaElement).value).toBe("start");
|
||
w.unmount();
|
||
});
|
||
|
||
it("restores DOM value when the parent rejects updates", async () => {
|
||
const value = ref("fixed");
|
||
const w = mount(
|
||
defineComponent({
|
||
components: { TextField, TextArea },
|
||
setup: () => ({ value }),
|
||
template: `<TextField :model-value="value"><TextArea /></TextField>`,
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
const area = w.get("textarea");
|
||
await area.setValue("typing");
|
||
await settle();
|
||
expect((area.element as HTMLTextAreaElement).value).toBe("fixed");
|
||
w.unmount();
|
||
});
|
||
|
||
it("respects canceled form reset", async () => {
|
||
const w = mount(
|
||
defineComponent({
|
||
render: () =>
|
||
h(Form, {}, () => [
|
||
h(TextField, { name: "t", defaultValue: "init" }, () => [
|
||
h(TextArea),
|
||
]),
|
||
]),
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
const area = w.get("textarea");
|
||
await area.setValue("edited");
|
||
const form = w.get("form").element as HTMLFormElement;
|
||
form.addEventListener("reset", (e) => e.preventDefault());
|
||
form.reset();
|
||
await settle();
|
||
expect((area.element as HTMLTextAreaElement).value).toBe("edited");
|
||
w.unmount();
|
||
});
|
||
|
||
it("associates Label, Description and FieldError through TextField", async () => {
|
||
const w = mount(
|
||
defineComponent({
|
||
render: () =>
|
||
h(TextField, { isInvalid: true, name: "x" }, () => [
|
||
h(Label, {}, () => "Bio"),
|
||
h(TextArea, { rows: 2 }),
|
||
h(Description, {}, () => "hint"),
|
||
h(FieldError),
|
||
]),
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
await settle();
|
||
const area = w.get("textarea");
|
||
const label = w.get("label");
|
||
expect(label.attributes("for")).toBe(area.attributes("id"));
|
||
const described = area.attributes("aria-describedby")!.split(" ");
|
||
expect(described.length).toBeGreaterThanOrEqual(2);
|
||
for (const id of described) {
|
||
expect(w.find(`[id="${id}"]`).exists()).toBe(true);
|
||
}
|
||
expect(w.find("[data-slot=field-error]").exists()).toBe(true);
|
||
w.unmount();
|
||
});
|
||
|
||
it("keeps InputGroup integration working next to TextArea", async () => {
|
||
const w = mount(
|
||
defineComponent({
|
||
render: () =>
|
||
h(Form, {}, () => [
|
||
h(TextField, { name: "email", defaultValue: "a@b.c" }, () => [
|
||
h(InputGroup, {}, () => [h(InputGroupInput)]),
|
||
]),
|
||
h(TextField, { name: "note", defaultValue: "hi" }, () => [
|
||
h(TextArea, { rows: 2 }),
|
||
]),
|
||
]),
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
expect(
|
||
Object.fromEntries(
|
||
new FormData(w.get("form").element as HTMLFormElement),
|
||
),
|
||
).toEqual({ email: "a@b.c", note: "hi" });
|
||
w.unmount();
|
||
});
|
||
|
||
it("keeps public prop types constrained", async () => {
|
||
const { TextArea: Area } = await import("../packages/vue/src");
|
||
// @ts-expect-error rows must be a number
|
||
const badRows: InstanceType<typeof Area>["$props"]["rows"] = "3";
|
||
// @ts-expect-error variant must be primary | secondary
|
||
const badVariant: InstanceType<typeof Area>["$props"]["variant"] = "ghost";
|
||
void badRows;
|
||
void badVariant;
|
||
const ok: InstanceType<typeof Area>["$props"] = {
|
||
rows: 6,
|
||
variant: "secondary",
|
||
fullWidth: true,
|
||
modelValue: "x",
|
||
};
|
||
expect(ok.rows).toBe(6);
|
||
});
|
||
});
|
||
|
||
describe("M13 field docs demos", () => {
|
||
const expected: Record<string, string[]> = {
|
||
textfield: [
|
||
"basic",
|
||
"on-surface",
|
||
"with-description",
|
||
"required",
|
||
"disabled",
|
||
"full-width",
|
||
"validation",
|
||
"controlled",
|
||
"with-error",
|
||
"textarea",
|
||
"input-types",
|
||
"render-function",
|
||
"text-field-custom-styles",
|
||
],
|
||
label: ["basic", "custom-styles"],
|
||
description: ["basic", "custom-styles"],
|
||
"field-error": ["basic", "custom-styles"],
|
||
textarea: [
|
||
"basic",
|
||
"variants",
|
||
"on-surface",
|
||
"full-width",
|
||
"controlled",
|
||
"rows",
|
||
"custom-styles",
|
||
],
|
||
};
|
||
|
||
const docFiles: Record<string, string> = {
|
||
textfield: "text-field",
|
||
label: "label",
|
||
description: "description",
|
||
"field-error": "field-error",
|
||
textarea: "textarea",
|
||
};
|
||
|
||
it("includes every preview from the pinned upstream documents", () => {
|
||
for (const [key, names] of Object.entries(expected)) {
|
||
const docName = docFiles[key];
|
||
const document = readFileSync(
|
||
`apps/docs/components/${docName}.md`,
|
||
"utf8",
|
||
);
|
||
const previewNames = [
|
||
...document.matchAll(/<ComponentPreview name="([^"]+)"/g),
|
||
].map((m) => m[1]);
|
||
const ids =
|
||
key === "textfield"
|
||
? names.map((n) =>
|
||
n === "text-field-custom-styles" ? n : `textfield-${n}`,
|
||
)
|
||
: names.map((n) => `${key}-${n}`);
|
||
expect(previewNames).toEqual(ids);
|
||
for (const id of ids) {
|
||
const source = readFileSync(`apps/docs/demos/${id}.vue`, "utf8");
|
||
expect(source).toContain("<template>");
|
||
}
|
||
}
|
||
});
|
||
|
||
it("documents Vue class binding and slots instead of React APIs", () => {
|
||
for (const docName of [
|
||
"text-field",
|
||
"label",
|
||
"description",
|
||
"field-error",
|
||
"textarea",
|
||
]) {
|
||
const document = readFileSync(
|
||
`apps/docs/components/${docName}.md`,
|
||
"utf8",
|
||
);
|
||
expect(document).not.toMatch(/\|\s*`className`\s*\|/);
|
||
expect(document).not.toMatch(/\|\s*`children`\s*\|/);
|
||
expect(document).toContain("`class`");
|
||
}
|
||
const fieldError = readFileSync(
|
||
"apps/docs/components/field-error.md",
|
||
"utf8",
|
||
);
|
||
expect(fieldError).toContain("validationErrors");
|
||
expect(fieldError).toContain("不提供完整 React Aria `validationDetails`");
|
||
expect(fieldError).toContain("作用域插槽");
|
||
});
|
||
|
||
it("keeps the three shared textfield demos and new pages aligned", () => {
|
||
for (const name of [
|
||
"textfield-basic",
|
||
"textfield-with-description",
|
||
"textfield-validation",
|
||
]) {
|
||
const source = readFileSync(`apps/docs/demos/${name}.vue`, "utf8");
|
||
expect(source).toContain("TextField");
|
||
}
|
||
const fieldsGuide = readFileSync("apps/docs/fields.md", "utf8");
|
||
expect(fieldsGuide).toContain("textfield-basic");
|
||
// Independent pages exist alongside the infrastructure guide
|
||
for (const page of [
|
||
"text-field",
|
||
"label",
|
||
"description",
|
||
"field-error",
|
||
"textarea",
|
||
]) {
|
||
expect(readFileSync(`apps/docs/components/${page}.md`, "utf8")).toContain(
|
||
"ComponentPreview",
|
||
);
|
||
}
|
||
});
|
||
|
||
it("uses Tabler-free demos with library parts for field docs", () => {
|
||
for (const name of [
|
||
"label-basic",
|
||
"description-basic",
|
||
"field-error-basic",
|
||
"textarea-basic",
|
||
]) {
|
||
const source = readFileSync(`apps/docs/demos/${name}.vue`, "utf8");
|
||
expect(source).not.toContain("className");
|
||
expect(source).not.toContain("@gravity-ui/icons");
|
||
expect(source).toContain("@heroui-vue/components");
|
||
}
|
||
});
|
||
});
|
||
|
||
function extractVueBlocks(markdown: string): string[] {
|
||
return [...markdown.matchAll(/```vue\n([\s\S]*?)```/g)].map((m) => m[1]);
|
||
}
|
||
|
||
function scriptBindings(block: string): Set<string> {
|
||
const script =
|
||
block.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)?.[1] ?? "";
|
||
const names = new Set<string>();
|
||
for (const m of script.matchAll(
|
||
/(?:const|let|function)\s+([A-Za-z_$][\w$]*)/g,
|
||
)) {
|
||
names.add(m[1]);
|
||
}
|
||
return names;
|
||
}
|
||
|
||
function templateIdentifiers(block: string): string[] {
|
||
const template = block.match(/<template>([\s\S]*)<\/template>/)?.[1] ?? block;
|
||
const ids: string[] = [];
|
||
// Only bindings that must come from <script setup>, not slot/v-for locals.
|
||
for (const m of template.matchAll(
|
||
/(?:v-model|:is-invalid|:validate|:model-value)="([^"]+)"/g,
|
||
)) {
|
||
const expr = m[1];
|
||
// Inline arrows/closures define their own params.
|
||
if (expr.includes("=>")) continue;
|
||
for (const id of expr.matchAll(/[A-Za-z_$][\w$]*/g)) {
|
||
const name = id[0];
|
||
if (name === "true" || name === "false" || name === "null") continue;
|
||
// Skip property access tails like value.length
|
||
const before = expr.slice(Math.max(0, id.index! - 1), id.index!);
|
||
if (before === ".") continue;
|
||
ids.push(name);
|
||
}
|
||
}
|
||
return ids;
|
||
}
|
||
|
||
describe("M13 field-error body examples", () => {
|
||
const markdown = readFileSync("apps/docs/components/field-error.md", "utf8");
|
||
const blocks = extractVueBlocks(markdown);
|
||
|
||
it("checks common script bindings in full SFC blocks", () => {
|
||
const fullSfcs = blocks.filter((b) => b.includes("<template>"));
|
||
expect(fullSfcs.length).toBeGreaterThanOrEqual(4);
|
||
for (const block of fullSfcs) {
|
||
const bindings = scriptBindings(block);
|
||
for (const id of templateIdentifiers(block)) {
|
||
if (id === "true" || id === "false") continue;
|
||
expect(
|
||
bindings.has(id),
|
||
`template identifier "${id}" is not defined in script`,
|
||
).toBe(true);
|
||
}
|
||
expect(block).not.toContain("hasErrors");
|
||
}
|
||
});
|
||
|
||
it("dynamic error example uses FieldError slot and a real error source", () => {
|
||
const dynamic = blocks.find((b) => b.includes("validatePassword"));
|
||
expect(dynamic).toBeTruthy();
|
||
expect(dynamic!.includes("validationErrors")).toBe(true);
|
||
expect(dynamic!.includes("FieldError")).toBe(true);
|
||
expect(dynamic!.includes("validate")).toBe(true);
|
||
expect(dynamic!.includes('validation-behavior="aria"')).toBe(true);
|
||
});
|
||
|
||
it("renders dynamic and multi-error messages from validate", async () => {
|
||
const DynamicDemo = defineComponent({
|
||
components: { TextField, Label, Input, FieldError },
|
||
setup() {
|
||
const password = ref("");
|
||
function validatePassword(value: string) {
|
||
if (value.length === 0) return true;
|
||
return value.length < 8 ? "密码至少需要 8 个字符" : true;
|
||
}
|
||
return { password, validatePassword };
|
||
},
|
||
template: `
|
||
<TextField
|
||
v-model="password"
|
||
name="password"
|
||
validation-behavior="aria"
|
||
:validate="validatePassword"
|
||
>
|
||
<Label>密码</Label>
|
||
<Input type="password" />
|
||
<FieldError>
|
||
<template #default="{ validationErrors }">
|
||
{{ validationErrors.join(",") }}
|
||
</template>
|
||
</FieldError>
|
||
</TextField>
|
||
`,
|
||
});
|
||
const w = mount(DynamicDemo, { attachTo: document.body });
|
||
await w.get("input").setValue("abc");
|
||
await settle();
|
||
expect(w.get("[data-slot=field-error]").text()).toContain(
|
||
"密码至少需要 8 个字符",
|
||
);
|
||
await w.get("input").setValue("long-enough-Password");
|
||
await settle();
|
||
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
|
||
w.unmount();
|
||
|
||
const MultiDemo = defineComponent({
|
||
components: { TextField, Label, Input, FieldError },
|
||
setup() {
|
||
const password = ref("");
|
||
function validatePassword(value: string) {
|
||
if (value.length === 0) return true;
|
||
const errors: string[] = [];
|
||
if (value.length < 8) errors.push("密码至少需要 8 个字符");
|
||
if (!/[A-Z]/.test(value)) errors.push("需要包含一个大写字母");
|
||
return errors.length ? errors : true;
|
||
}
|
||
return { password, validatePassword };
|
||
},
|
||
template: `
|
||
<TextField
|
||
v-model="password"
|
||
name="password"
|
||
validation-behavior="aria"
|
||
:validate="validatePassword"
|
||
>
|
||
<Label>密码</Label>
|
||
<Input type="password" />
|
||
<FieldError>
|
||
<template #default="{ validationErrors }">
|
||
<div v-for="(error, i) in validationErrors" :key="i">{{ error }}</div>
|
||
</template>
|
||
</FieldError>
|
||
</TextField>
|
||
`,
|
||
});
|
||
const m = mount(MultiDemo, { attachTo: document.body });
|
||
await m.get("input").setValue("abc");
|
||
await settle();
|
||
const text = m.get("[data-slot=field-error]").text();
|
||
expect(text).toContain("密码至少需要 8 个字符");
|
||
expect(text).toContain("需要包含一个大写字母");
|
||
expect(m.findAll("[data-slot=field-error] div")).toHaveLength(2);
|
||
m.unmount();
|
||
});
|
||
});
|
||
|
||
describe("M13 TextField and TextArea public API docs", () => {
|
||
it("documents autoComplete, inputMode, form, events and expose on TextField", () => {
|
||
const doc = readFileSync("apps/docs/components/text-field.md", "utf8");
|
||
expect(doc).toContain("`autoComplete`");
|
||
expect(doc).toContain("`inputMode`");
|
||
expect(doc).toContain("`form`");
|
||
expect(doc).toContain("update:modelValue");
|
||
expect(doc).toContain("focus");
|
||
expect(doc).toContain("element");
|
||
});
|
||
|
||
it("documents focus/element and value updates on TextArea", () => {
|
||
const doc = readFileSync("apps/docs/components/textarea.md", "utf8");
|
||
expect(doc).toContain("update:modelValue");
|
||
expect(doc).toContain("focus");
|
||
expect(doc).toContain("element");
|
||
expect(doc).toContain("`rows`");
|
||
});
|
||
|
||
it("keeps TextField autoComplete/inputMode/form wired to the real control", async () => {
|
||
const w = mount(
|
||
defineComponent({
|
||
components: { TextField, TextArea },
|
||
template: `
|
||
<TextField
|
||
model-value="x"
|
||
name="email"
|
||
type="email"
|
||
auto-complete="email"
|
||
input-mode="email"
|
||
form="outer"
|
||
>
|
||
<TextArea />
|
||
</TextField>
|
||
`,
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
const area = w.get("textarea");
|
||
expect(area.attributes("autocomplete")).toBe("email");
|
||
expect(area.attributes("inputmode")).toBe("email");
|
||
expect(area.attributes("form")).toBe("outer");
|
||
w.unmount();
|
||
});
|
||
|
||
it("exposes focus and element on TextField and TextArea", async () => {
|
||
const areaRef = ref();
|
||
const fieldRef = ref();
|
||
const wrap = mount(
|
||
defineComponent({
|
||
components: { TextField, TextArea },
|
||
setup: () => ({ areaRef, fieldRef }),
|
||
template: `
|
||
<TextField ref="fieldRef" model-value="a">
|
||
<TextArea ref="areaRef" />
|
||
</TextField>
|
||
`,
|
||
}),
|
||
{ attachTo: document.body },
|
||
);
|
||
await settle();
|
||
const areaInstance = areaRef.value;
|
||
expect(typeof areaInstance?.focus).toBe("function");
|
||
const native = wrap.get("textarea").element;
|
||
// Vue unwraps exposed refs on the public component instance.
|
||
expect(areaInstance.element).toBe(native);
|
||
expect(fieldRef.value.element).toBe(native);
|
||
areaInstance.focus();
|
||
expect(document.activeElement).toBe(native);
|
||
(native as HTMLTextAreaElement).blur();
|
||
fieldRef.value.focus();
|
||
expect(document.activeElement).toBe(native);
|
||
wrap.unmount();
|
||
});
|
||
});
|