feat: migrate NumberField with form integration and docs

This commit is contained in:
maoyingjie
2026-10-23 11:48:06 +08:00
parent 7fc8315037
commit 23527d4e4c
43 changed files with 2788 additions and 9 deletions
+361
View File
@@ -0,0 +1,361 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { mount, flushPromises } from "@vue/test-utils";
import { defineComponent, ref, nextTick, createSSRApp, h } from "vue";
import { renderToString } from "@vue/server-renderer";
import {
NumberField,
NumberFieldGroup,
NumberFieldInput,
NumberFieldIncrementButton,
NumberFieldDecrementButton,
Label,
Description,
FieldError,
Fieldset,
Form,
} from "../packages/vue/src";
const wrappers: ReturnType<typeof mount>[] = [];
afterEach(() => {
wrappers.splice(0).forEach((w) => w.unmount());
document.body.innerHTML = "";
});
function fixture(template: string, setup = () => ({})) {
const w = mount(
defineComponent({
components: {
NumberField,
NumberFieldGroup,
NumberFieldInput,
NumberFieldIncrementButton,
NumberFieldDecrementButton,
Label,
Description,
FieldError,
Fieldset,
Form,
},
template,
setup,
}),
{ attachTo: document.body },
);
wrappers.push(w);
return w;
}
const parts =
"<Label>Quantity</Label><NumberFieldGroup><NumberFieldDecrementButton/><NumberFieldInput/><NumberFieldIncrementButton/></NumberFieldGroup><Description>Choose quantity</Description><FieldError/>";
describe("NumberField public contracts", () => {
it("repeats a held step and clears timers on cancellation and unmount", async () => {
vi.useFakeTimers();
try {
const w = fixture(
`<NumberField :default-value="0">${parts}</NumberField>`,
);
const button = w.get('[data-slot="number-field-increment-button"]');
await button.trigger("pointerdown", { button: 0, pointerId: 1 });
await vi.advanceTimersByTimeAsync(460);
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"2",
);
await button.trigger("pointercancel");
await vi.advanceTimersByTimeAsync(1000);
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"2",
);
expect(vi.getTimerCount()).toBe(0);
await button.trigger("pointerdown", { button: 0, pointerId: 2 });
w.unmount();
wrappers.splice(wrappers.indexOf(w), 1);
expect(vi.getTimerCount()).toBe(0);
} finally {
vi.useRealTimers();
}
});
it("hydrates control IDs and description associations without mismatches", async () => {
const app = defineComponent({
render: () =>
h(NumberField, { defaultValue: 2 }, () => [
h(Label, {}, () => "Amount"),
h(NumberFieldGroup, {}, () => [h(NumberFieldInput)]),
h(Description, {}, () => "Help"),
]),
});
const html = await renderToString(createSSRApp(app));
const container = document.createElement("div");
container.innerHTML = html;
document.body.append(container);
const warnings: unknown[][] = [];
const warn = vi.spyOn(console, "warn").mockImplementation((...args) => {
warnings.push(args);
});
const client = createSSRApp(app);
try {
client.mount(container);
await nextTick();
const input = container.querySelector('input[role="spinbutton"]')!;
expect(container.querySelector("label")?.htmlFor).toBe(input.id);
expect(
container.querySelector(
`[id="${input.getAttribute("aria-describedby")}"]`,
),
).toBeTruthy();
expect(warnings).toEqual([]);
} finally {
client.unmount();
warn.mockRestore();
}
});
it("updates ARIA/class attributes and controlled ownership as props are added and removed", async () => {
const attributes = ref<Record<string, unknown>>({});
const w = fixture(
`<NumberField :default-value="2" v-bind="attributes">${parts}</NumberField>`,
() => ({ attributes }),
);
for (const [index, label] of ["First", "Second"].entries()) {
attributes.value = {
"aria-label": label,
class: "custom-root",
modelValue: 7,
};
await nextTick();
expect(w.get('[role="spinbutton"]').attributes("aria-label")).toBe(label);
expect(w.get('[data-slot="number-field"]').classes()).toContain(
"custom-root",
);
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"7",
);
attributes.value = {};
await nextTick();
expect(
w.get('[role="spinbutton"]').attributes("aria-label"),
).toBeUndefined();
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
String(3 + index),
);
}
});
it("compiles and mounts all 17 baseline examples without Vue warnings", async () => {
const warnings: unknown[][] = [];
const warn = vi.spyOn(console, "warn").mockImplementation((...args) => {
warnings.push(args);
});
try {
const names = [
"basic",
"variants",
"on-surface",
"with-description",
"required",
"disabled",
"full-width",
"validation",
"controlled",
"with-step",
"with-format-options",
"form-example",
"with-validation",
"custom-icons",
"with-chevrons",
"render-function",
"custom-styles",
];
for (const name of names) {
const module = await import(
`../apps/docs/demos/number-field-${name}.vue`
);
const wrapper = mount(module.default, { attachTo: document.body });
try {
await nextTick();
expect(wrapper.findAll('[role="spinbutton"]').length).toBeGreaterThan(
0,
);
} finally {
wrapper.unmount();
}
}
} finally {
warn.mockRestore();
}
expect(warnings).toEqual([]);
});
it("steps decimals once and honors bounds and canonical FormData", async () => {
const w = fixture(
`<form><NumberField :default-value="0.2" :step="0.1" :min-value="0" :max-value="0.3" name="quantity">${parts}</NumberField></form>`,
);
await w.get('[data-slot="number-field-increment-button"]').trigger("click");
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe(
"0.3",
);
expect(
(
w.get('[data-slot="number-field-increment-button"]')
.element as HTMLButtonElement
).disabled,
).toBe(true);
expect(new FormData(w.get("form").element).getAll("quantity")).toEqual([
"0.3",
]);
});
it("keeps empty controlled state when a parent rejects a step", async () => {
const update = vi.fn();
const w = fixture(
`<NumberField :model-value="null" @update:model-value="update">${parts}</NumberField>`,
() => ({ update }),
);
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
expect(update).toHaveBeenCalledWith(0);
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).value,
).toBe("");
expect(
w.get('[role="spinbutton"]').attributes("aria-valuenow"),
).toBeUndefined();
});
it("restores controlled text after rejected typing and clearing", async () => {
const w = fixture(`<NumberField :model-value="4">${parts}</NumberField>`);
const input = w.get('input[role="spinbutton"]');
for (const text of ["9", ""]) {
await input.setValue(text);
await input.trigger("blur");
await flushPromises();
expect((input.element as HTMLInputElement).value).toBe("4");
}
});
it("blocks readonly Home End wheel click and typing", async () => {
const update = vi.fn();
const w = fixture(
`<NumberField :default-value="2" :min-value="0" :max-value="5" is-read-only @change="update">${parts}</NumberField>`,
() => ({ update }),
);
const input = w.get('[role="spinbutton"]');
for (const key of [
"Home",
"End",
"ArrowUp",
"ArrowDown",
"PageUp",
"PageDown",
])
await input.trigger("keydown", { key });
await input.setValue("9");
await input.trigger("blur");
await flushPromises();
await w.get('[data-slot="number-field-increment-button"]').trigger("click");
expect(update).not.toHaveBeenCalled();
expect((input.element as HTMLInputElement).value).toBe("2");
});
it("respects cancelled keyboard and button activation events", async () => {
const w = fixture(
`<NumberField :default-value="2"><NumberFieldInput @keydown.prevent/><NumberFieldIncrementButton @click.prevent/></NumberField>`,
);
await w.get('[role="spinbutton"]').trigger("keydown", { key: "ArrowUp" });
await w.get("button").trigger("click");
expect(w.get('[role="spinbutton"]').attributes("aria-valuenow")).toBe("2");
});
it("resets noncontrolled values and preserves cancelled reset", async () => {
const w = fixture(
`<form><NumberField :default-value="2" name="quantity">${parts}</NumberField></form>`,
);
const input = w.get('[role="spinbutton"]');
await input.trigger("keydown", { key: "ArrowUp" });
w.get("form").element.reset();
await flushPromises();
expect(input.attributes("aria-valuenow")).toBe("2");
expect((input.element as HTMLInputElement).value).toBe("2");
expect(new FormData(w.get("form").element).get("quantity")).toBe("2");
w.get("form").element.addEventListener("reset", (e) => e.preventDefault());
await input.trigger("keydown", { key: "ArrowUp" });
w.get("form").element.reset();
await flushPromises();
expect(input.attributes("aria-valuenow")).toBe("3");
});
it("controlled reset preserves both visible and submitted parent value", async () => {
const w = fixture(
`<form><NumberField :model-value="8" :default-value="2" name="quantity">${parts}</NumberField></form>`,
);
w.get("form").element.reset();
await flushPromises();
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).value,
).toBe("8");
expect(new FormData(w.get("form").element).get("quantity")).toBe("8");
});
it("uses locale display and a single invariant submission value", async () => {
const w = fixture(
`<form><NumberField :default-value="1234.5" locale="de-DE" name="amount">${parts}</NumberField></form>`,
);
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).value,
).toBe("1.234,5");
expect(new FormData(w.get("form").element).getAll("amount")).toEqual([
"1234.5",
]);
});
it("inherits Fieldset disabled and omits values", async () => {
const w = fixture(
`<form><Fieldset disabled><NumberField :default-value="2" name="quantity">${parts}</NumberField></Fieldset></form>`,
);
expect(
(w.get('[role="spinbutton"]').element as HTMLInputElement).disabled,
).toBe(true);
expect(new FormData(w.get("form").element).has("quantity")).toBe(false);
});
it("associates Label and multiple descriptions and removes stale references", async () => {
const show = ref(true);
const w = fixture(
`<NumberField><Label>Amount</Label><NumberFieldGroup><NumberFieldInput id="amount" aria-describedby="external"/></NumberFieldGroup><Description v-if="show" id="help">Help</Description></NumberField>`,
() => ({ show }),
);
expect(w.get("label").attributes("for")).toBe("amount");
expect(w.get("input").attributes("aria-describedby")).toContain("help");
show.value = false;
await nextTick();
expect(w.get("input").attributes("aria-describedby")).toBe("external");
});
it("blocks native invalid submit and surfaces FieldError", async () => {
const submit = vi.fn();
const w = fixture(
`<Form @submit="submit"><NumberField is-required>${parts}</NumberField><button type="submit">Submit</button></Form>`,
() => ({ submit }),
);
await w.get("form").trigger("submit");
expect(submit).not.toHaveBeenCalled();
expect(w.get('[data-slot="field-error"]').text()).toContain("请填写");
expect(document.activeElement).toBe(w.get('[role="spinbutton"]').element);
});
it("aria validation exposes errors without blocking submission", async () => {
const submit = vi.fn();
const w = fixture(
`<Form @submit.prevent="submit"><NumberField validation-behavior="aria" is-required>${parts}</NumberField></Form>`,
() => ({ submit }),
);
await w.get("form").trigger("submit");
expect(submit).toHaveBeenCalledTimes(1);
expect(w.get('[role="spinbutton"]').attributes("aria-invalid")).toBe(
"true",
);
});
it("renders SSR associations before descriptions and explicit leaf IDs", async () => {
const html = await renderToString(
createSSRApp({
render: () =>
h(NumberField, {}, () => [
h(Label, {}, () => "SSR"),
h(NumberFieldGroup, {}, () =>
h(NumberFieldInput, { id: "ssr-number" }),
),
h(Description, {}, () => "Help"),
]),
}),
);
expect(html).toContain('for="ssr-number"');
const described = html.match(/aria-describedby="([^"]+)"/)?.[1];
expect(described).toBeTruthy();
expect(html).toContain(`id="${described}"`);
});
});
+32
View File
@@ -567,3 +567,35 @@ it("renders Toolbar with nested groups without browser globals", async () => {
expect(html).toContain("hv-separator--horizontal");
expect(html).toContain('data-slot="button-group"');
});
it("renders NumberField in node with initial control associations and numeric submission", async () => {
const {
NumberField,
NumberFieldGroup,
NumberFieldInput,
Label,
Description,
} = await import("../packages/vue/src");
const html = await renderToString(
createSSRApp({
render: () =>
h(
NumberField,
{ defaultValue: 12.5, name: "amount", locale: "de-DE" },
() => [
h(Label, {}, () => "Amount"),
h(NumberFieldGroup, {}, () => [h(NumberFieldInput)]),
h(Description, {}, () => "Help"),
],
),
}),
);
expect(html).toContain('value="12,5"');
expect(html).toContain('name="amount"');
const inputId = html.match(/for="([^"]+)"/)?.[1];
expect(inputId).toBeTruthy();
expect(html).toContain(`id="${inputId}"`);
const descriptionId = html.match(/aria-describedby="([^"]+)"/)?.[1];
expect(descriptionId).toBeTruthy();
expect(html).toContain(`id="${descriptionId}"`);
});
+30
View File
@@ -0,0 +1,30 @@
import {
NumberField,
type NumberFieldProps,
numberFieldVariants,
} from "../../packages/vue/src";
const valid: NumberFieldProps = {
modelValue: null,
defaultValue: 2,
minValue: 0,
maxValue: 10,
step: 0.1,
locale: "de-DE",
variant: "secondary",
validationBehavior: "aria",
validate: (value) => (value === null ? "Required" : true),
};
// @ts-expect-error public value is numeric, not a localized display string
const invalidValue: NumberFieldProps = { modelValue: "1.234,5" };
// @ts-expect-error unsupported variant
const invalidVariant: NumberFieldProps = { variant: "ghost" };
// @ts-expect-error no async validation protocol
const invalidValidator: NumberFieldProps = { validate: async () => true };
void [
NumberField,
valid,
invalidValue,
invalidVariant,
invalidValidator,
numberFieldVariants,
];