feat: complete public Form migration and validation focus contract

This commit is contained in:
maoyingjie
2026-10-27 18:28:13 +08:00
parent f424fa5597
commit 2c221e0995
22 changed files with 843 additions and 35 deletions
+313
View File
@@ -0,0 +1,313 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mount } from "@vue/test-utils";
import { defineComponent, h, nextTick, ref } from "vue";
import {
Form,
TextField,
Input,
FieldError,
CheckboxGroup,
Switch,
} from "../packages/vue/src";
import FormBasic from "../apps/docs/demos/form-basic.vue";
import FormRenderFunction from "../apps/docs/demos/form-render-function.vue";
import FormCustomStyles from "../apps/docs/demos/form-custom-styles.vue";
const wrappers: ReturnType<typeof mount>[] = [];
// Submit occurs after mounting, as with real user input. Keep Vue's listener
// timestamp guard deterministic without changing private event properties.
beforeEach(() => vi.useFakeTimers({ toFake: ["Date"] }));
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
vi.useRealTimers();
});
function render(content: () => unknown, attrs: Record<string, unknown> = {}) {
const w = mount(Form, {
attrs,
slots: { default: content as () => ReturnType<typeof h> },
attachTo: document.body,
});
wrappers.push(w);
return w;
}
function submit(form: HTMLFormElement, submitter?: HTMLButtonElement) {
vi.setSystemTime(Date.now() + 1);
const event = new SubmitEvent("submit", {
bubbles: true,
cancelable: true,
submitter,
});
form.dispatchEvent(event);
return event;
}
const settle = async () => {
await nextTick();
await nextTick();
};
describe("Form public validation", () => {
it.each(["", "true", "false", true, false])(
"uses native boolean-attribute semantics for novalidate=%s",
(value) => {
const submitted = vi.fn((event: Event) => event.preventDefault());
const w = render(() => h("input", { required: true }), {
novalidate: value,
onSubmit: submitted,
});
submit(w.element as HTMLFormElement);
expect(submitted).toHaveBeenCalledTimes(value === false ? 0 : 1);
},
);
it.each([
() => h(CheckboxGroup, { isRequired: true }),
() => h(Switch, { isRequired: true }),
])(
"cancels composite focus and preserves the first invalid field across mixed controls",
async (Control) => {
const w = render(() => [h("input", { required: true }), Control()]);
submit(w.element as HTMLFormElement);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
w.unmount();
wrappers.splice(wrappers.indexOf(w), 1);
const canceled = render(() => [Control(), h("button", "anchor")], {
onInvalid: (e: Event) => e.preventDefault(),
});
const button = canceled.get("button").element as HTMLButtonElement;
button.focus();
submit(canceled.element as HTMLFormElement);
await settle();
expect(document.activeElement).toBe(button);
canceled.vm.checkValidity();
await settle();
expect(document.activeElement).toBe(button);
},
);
it("notifies once per invalid control and allows canceling default focus", async () => {
const invalid = vi.fn((e: Event) => e.preventDefault());
const submitted = vi.fn();
const w = render(
() => [
h("input", { required: true, name: "one" }),
h("input", { required: true, name: "two" }),
h("button", { type: "submit" }, "submit"),
],
{ onInvalid: invalid, onSubmit: submitted },
);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
const event = submit(w.element as HTMLFormElement, button);
await settle();
expect(event.defaultPrevented).toBe(true);
expect(submitted).not.toHaveBeenCalled();
expect(invalid).toHaveBeenCalledTimes(2);
expect(invalid.mock.calls[0][0].target).toBe(w.get("input").element);
expect(document.activeElement).toBe(button);
});
it("focuses the first invalid control and updates associated field errors", async () => {
const invalid = vi.fn();
const w = render(
() => [
h(TextField, { name: "email", isRequired: true }, () => [
h(Input),
h(FieldError),
]),
h("input", { required: true, name: "second" }),
],
{ onInvalid: invalid },
);
await settle();
expect(submit(w.element as HTMLFormElement).defaultPrevented).toBe(true);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
expect(invalid).toHaveBeenCalledTimes(2);
expect(w.get("input").attributes("aria-describedby")).toContain(
w.get("[data-slot=field-error]").attributes("id"),
);
});
it("honors invalid cancellation on the field itself", async () => {
const w = render(() => [
h("input", {
required: true,
onInvalid: (e: Event) => e.preventDefault(),
}),
h("button", "anchor"),
]);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
expect(submit(w.element as HTMLFormElement).defaultPrevented).toBe(true);
expect(document.activeElement).toBe(button);
});
it("validates externally associated controls and can cancel their default focus", async () => {
const invalid = vi.fn((e: Event) => e.preventDefault());
const w = mount(
defineComponent({
render: () =>
h("div", [
h(Form, { id: "external-form", onInvalid: invalid }),
h("input", { form: "external-form", required: true }),
h("button", "anchor"),
]),
}),
{ attachTo: document.body },
);
wrappers.push(w);
const button = w.get("button").element as HTMLButtonElement;
button.focus();
expect(
submit(w.get("form").element as HTMLFormElement).defaultPrevented,
).toBe(true);
expect(invalid).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(button);
});
it("skips validation for formnovalidate and respects canceled submission/reset", async () => {
const invalid = vi.fn();
const submitted = vi.fn((event: Event) => event.preventDefault());
const reset = vi.fn((event: Event) => event.preventDefault());
const w = render(
() => [
h(Input, { name: "value", defaultValue: "initial", required: true }),
h("button", { formnovalidate: true, type: "submit" }, "skip"),
],
{ onInvalid: invalid, onSubmit: submitted, onReset: reset },
);
await w.get("input").setValue("");
const event = submit(
w.element as HTMLFormElement,
w.get("button").element as HTMLButtonElement,
);
expect(event.defaultPrevented).toBe(true);
expect(submitted).toHaveBeenCalledTimes(1);
expect(invalid).not.toHaveBeenCalled();
(w.element as HTMLFormElement).reset();
await settle();
expect(reset).toHaveBeenCalledTimes(1);
expect((w.get("input").element as HTMLInputElement).value).toBe("");
});
it("exposes native form access and policy-aware validation without duplicate invalid events", async () => {
const invalid = vi.fn();
const w = render(() => h("input", { name: "value", required: true }), {
onInvalid: invalid,
});
expect(w.vm.element).toBe(w.element);
expect(w.vm.checkValidity()).toBe(false);
expect(invalid).toHaveBeenCalledTimes(1);
invalid.mockClear();
expect(w.vm.reportValidity()).toBe(false);
expect(invalid).toHaveBeenCalledTimes(1);
expect(document.activeElement).toBe(w.get("input").element);
await w.get("input").setValue("valid");
expect(w.vm.checkValidity()).toBe(true);
w.vm.reset();
await settle();
expect((w.get("input").element as HTMLInputElement).value).toBe("");
});
it("keeps dynamic native attrs and policy overrides on the real form", async () => {
const method = ref("post");
const submitted = vi.fn();
const w = mount(
defineComponent({
setup: () => () =>
h(
Form,
{
action: "/submit",
method: method.value,
validationBehavior: "aria",
onSubmit: submitted,
"data-custom": "foo",
},
() => h("input", { required: true }),
),
}),
{ attachTo: document.body },
);
wrappers.push(w);
expect(w.get("form").attributes("action")).toBe("/submit");
expect(w.get("form").attributes("data-custom")).toBe("foo");
method.value = "get";
await settle();
expect(w.get("form").attributes("method")).toBe("get");
submit(w.get("form").element as HTMLFormElement);
expect(submitted).toHaveBeenCalledTimes(1);
});
});
describe("Form fixed-source demos", () => {
it.each([FormBasic, FormRenderFunction])(
"validates both fields, submits exact data, and resets values/errors/results",
async (Demo) => {
const w = mount(Demo, { attachTo: document.body });
wrappers.push(w);
const form = w.get("form").element as HTMLFormElement;
await settle();
expect(submit(form).defaultPrevented).toBe(true);
await settle();
expect(w.findAll("[data-slot=field-error]")).toHaveLength(2);
const email = w.get('input[name="email"]');
const password = w.get('input[name="password"]');
expect(document.activeElement).toBe(email.element);
expect(w.get("[data-slot=field-error]").text()).toBe(
"请输入有效的邮箱地址",
);
await email.setValue("john@example.com");
for (const [value, error] of [
["short", "密码至少需要 8 个字符"],
["lowercase1", "密码至少需要包含一个大写字母"],
["Password", "密码至少需要包含一个数字"],
]) {
await password.setValue(value);
await settle();
submit(form);
await settle();
expect(w.get("[data-slot=field-error]").text()).toBe(error);
expect(w.find('[role="status"]').exists()).toBe(false);
}
await password.setValue("Password1");
await settle();
submit(form);
await settle();
expect(w.get('[role="status"]').text()).toContain("表单提交数据:");
expect(w.get('[role="status"]').text()).toContain(
'"email": "john@example.com"',
);
expect(w.get('[role="status"]').text()).toContain(
'"password": "Password1"',
);
expect([...new FormData(form)]).toEqual([
["email", "john@example.com"],
["password", "Password1"],
]);
form.reset();
await settle();
expect((email.element as HTMLInputElement).value).toBe("");
expect((password.element as HTMLInputElement).value).toBe("");
expect(w.find("[data-slot=field-error]").exists()).toBe(false);
expect(w.find('[role="status"]').exists()).toBe(false);
if (Demo === FormRenderFunction) expect(form.dataset.custom).toBe("foo");
},
);
it("keeps the custom-styles example as a native validated form", async () => {
const w = mount(FormCustomStyles, { attachTo: document.body });
wrappers.push(w);
const form = w.get("form").element as HTMLFormElement;
expect(w.get("label").text()).toBe("工作邮箱");
expect(w.get("button").text()).toBe("继续");
expect(submit(form).defaultPrevented).toBe(true);
await settle();
expect(document.activeElement).toBe(w.get("input").element);
await w.get("input").setValue("you@company.com");
await settle();
expect(form.checkValidity()).toBe(true);
expect(submit(form).defaultPrevented).toBe(true);
expect([...new FormData(form)]).toEqual([["email", "you@company.com"]]);
});
});
+4
View File
@@ -549,5 +549,9 @@
".hv-avatar--lg",
".hv-avatar--soft"
]
},
"form": {
"exports": ["Form", "FormRoot", "TextField", "Input", "Label", "FieldError", "Button"],
"css": [".hv-textfield", ".hv-input", ".hv-field-error", ".hv-button"]
}
}
+48
View File
@@ -0,0 +1,48 @@
import { h } from "vue";
import {
Form,
FormRoot,
type FormProps,
type FormRootProps,
type FormSlots,
type FormExpose,
} from "@heroui-vue/components";
const props: FormProps = {
validationBehavior: "native",
validationErrors: { email: ["Invalid"] },
action: "/submit",
method: "post",
enctype: "multipart/form-data",
target: "_self",
noValidate: true,
"aria-label": "Account",
class: ["flex", { compact: true }],
onSubmit: (event: SubmitEvent) => event.preventDefault(),
onReset: (event: Event) => event.preventDefault(),
onInvalid: (event: Event) => event.preventDefault(),
};
const rootProps: FormRootProps = props;
const slots: FormSlots = { default: () => h("input", { name: "email" }) };
h(Form, rootProps, { default: slots.default });
h(FormRoot, { validationBehavior: "aria" });
declare const form: FormExpose;
const valid: boolean = form.checkValidity();
const reported: boolean = form.reportValidity();
form.reset();
form.element?.requestSubmit();
// @ts-expect-error validation mode is constrained
const invalidMode: FormProps = { validationBehavior: "automatic" };
// @ts-expect-error field errors accept strings or string arrays
const invalidErrors: FormProps = { validationErrors: { email: 42 } };
// @ts-expect-error no React render function API
const invalidRender: FormProps = { render: () => h("form") };
// @ts-expect-error submit receives native SubmitEvent, not a field value
const invalidSubmit: FormProps = { onSubmit: (value: string) => value };
void [
valid,
reported,
invalidMode,
invalidErrors,
invalidRender,
invalidSubmit,
];