fix: complete field and OTP public contracts (HD-07)

This commit is contained in:
maoyingjie
2026-10-29 09:30:58 +08:00
parent 27cc62e36f
commit 2d7e3d4e1e
26 changed files with 1067 additions and 100 deletions
+138
View File
@@ -463,3 +463,141 @@ it("native Switch overrides an aria Form and blocks invalid submission", async (
expect(w.get("[role=switch]").attributes("aria-invalid")).toBe("true");
w.unmount();
});
it("TextField autoFocus and focus-within cover moves between child controls", async () => {
const w = mount(
defineComponent({
render: () =>
h(
TextField,
{ autoFocus: true },
{
default: (state: Record<string, unknown>) => [
h(Input),
h("button", { type: "button" }, "inside"),
h("output", String(state.isFocusWithin)),
],
},
),
}),
{ attachTo: document.body },
);
try {
await settle();
expect(document.activeElement).toBe(w.get("input").element);
expect(
w.get('[data-slot="textfield"]').attributes("data-focus-within"),
).toBe("true");
(w.get("button").element as HTMLButtonElement).focus();
await settle();
expect(w.get("output").text()).toBe("true");
(w.get("button").element as HTMLButtonElement).blur();
await settle();
expect(w.get("output").text()).toBe("false");
} finally {
w.unmount();
}
});
it("field and Form errors merge in order, dismiss on edit/reset, and a new response reappears", async () => {
const local = ref(["local"]),
server = ref({ name: "server" });
const w = mount(
defineComponent({
render: () =>
h(Form, { validationErrors: server.value }, () =>
h(TextField, { name: "name", validationErrors: local.value }, () => [
h(Input),
h(
FieldError,
{},
{
default: (s: {
validationErrors: string[];
validationDetails?: ValidityState;
}) =>
`${s.validationErrors.join("|")}:${s.validationDetails?.customError}`,
},
),
]),
),
}),
{ attachTo: document.body },
);
try {
await settle();
expect(w.get('[role="alert"]').text()).toBe("local|server:true");
expect((w.get("input").element as HTMLInputElement).checkValidity()).toBe(
false,
);
await w.get("input").setValue("edit");
await settle();
expect(w.find('[role="alert"]').exists()).toBe(false);
local.value = ["new local"];
server.value = { name: "new server" };
await settle();
expect(w.get('[role="alert"]').text()).toBe("new local|new server:true");
(w.get("form").element as HTMLFormElement).reset();
await settle();
expect(w.find('[role="alert"]').exists()).toBe(false);
} finally {
w.unmount();
}
});
it("TextField FieldError exposes native validity flags for required input", async () => {
const w = mount(
defineComponent({
render: () =>
h(TextField, { isRequired: true }, () => [
h(Input),
h(
FieldError,
{},
{
default: (s: { validationDetails?: ValidityState }) =>
String(s.validationDetails?.valueMissing),
},
),
]),
}),
{ attachTo: document.body },
);
try {
await settle();
(w.get("input").element as HTMLInputElement).checkValidity();
await settle();
expect(w.get('[role="alert"]').text()).toBe("true");
} finally {
w.unmount();
}
});
it("TextField validity details update when native constraints change without an edit", async () => {
const pattern = ref("[0-9]+");
const w = mount(
defineComponent({
render: () =>
h(
TextField,
{ defaultValue: "123", pattern: pattern.value },
{
default: (state: { validationDetails: ValidityState }) => [
h(Input),
h("output", String(state.validationDetails.patternMismatch)),
],
},
),
}),
);
try {
await settle();
expect(w.get("output").text()).toBe("false");
pattern.value = "[a-z]+";
await settle();
expect(w.get("output").text()).toBe("true");
pattern.value = "[0-9]+";
await settle();
expect(w.get("output").text()).toBe("false");
} finally {
w.unmount();
}
});
+37
View File
@@ -509,3 +509,40 @@ it.each(["changed-query", "x"])(
}
},
);
it("SearchField exposes value and shares field-level validation errors with Form", async () => {
const local = ref(["local search"]),
formErrors = ref({ q: "form search" });
const w = mount(
defineComponent({
render: () =>
h(Form, { validationErrors: formErrors.value }, () =>
h(
SearchField,
{ name: "q", validationErrors: local.value },
{
default: (s: { value: string }) => [
h(SearchFieldGroup, {}, () => h(SearchFieldInput)),
h(FieldError),
h("output", s.value),
],
},
),
),
}),
{ attachTo: document.body },
);
try {
await settle();
expect(w.get('[role="alert"]').text()).toBe("local search form search");
await w.get("input").setValue("query");
await settle();
expect(w.get("output").text()).toBe("query");
expect(w.find('[role="alert"]').exists()).toBe(false);
local.value = ["new search"];
await settle();
expect(w.get('[role="alert"]').text()).toBe("new search");
} finally {
w.unmount();
}
});
+134
View File
@@ -0,0 +1,134 @@
<script setup lang="ts">
import { ref } from "vue";
import {
TextField,
SearchField,
SearchFieldGroup,
SearchFieldInput,
SearchFieldClearButton,
Form,
Label,
Input,
FieldError,
InputOTP,
InputOTPGroup,
InputOTPSlot,
} from "@heroui-vue/components";
const local = ref(["字段错误"]),
server = ref({ name: "Form错误" });
const mounted = ref(false),
accepted = ref(true),
disabled = ref(false),
readonly = ref(false);
const otp = ref(""),
completes = ref<string[]>([]),
proposals = ref<string[]>([]);
const align = ref<"left" | "center" | "right">("left");
const strip = (text: string) => text.replaceAll("-", "");
</script>
<template>
<main style="padding: 24px; display: grid; gap: 20px">
<Form :validation-errors="server">
<TextField
v-slot="state"
auto-focus
name="name"
:validation-errors="local"
>
<Label>姓名</Label>
<Input />
<button type="button">字段内按钮</button>
<output id="field-state">
{{
JSON.stringify({
value: state.value,
within: state.isFocusWithin,
visible: state.isFocusVisible,
})
}}
</output>
<FieldError v-slot="errors">
{{ errors.validationErrors.join("|") }} /
{{ errors.validationDetails?.customError }}
</FieldError>
</TextField>
<SearchField v-slot="state" name="query">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldInput />
<SearchFieldClearButton />
</SearchFieldGroup>
<output id="search-value">{{ state.value }}</output>
</SearchField>
<button type="reset">重置字段</button>
<button
type="button"
@click="
local = ['新字段错误'];
server = { name: '新Form错误' };
"
>
新错误响应
</button>
</Form>
<div>
<button @click="mounted = true">挂载验证码</button>
<label>
<input v-model="accepted" type="checkbox" />
接受验证码
</label>
<label>
<input v-model="disabled" type="checkbox" />
禁用验证码
</label>
<label>
<input v-model="readonly" type="checkbox" />
只读验证码
</label>
<label>
输入对齐
<select v-model="align">
<option>left</option>
<option>center</option>
<option>right</option>
</select>
</label>
</div>
<Form @submit.prevent>
<InputOTP
v-if="mounted"
:model-value="otp"
:max-length="4"
auto-focus
required
aria-label="验证码"
name="code"
:is-disabled="disabled"
:is-read-only="readonly"
:text-align="align"
:paste-transformer="strip"
pattern="^\d+$"
@update:model-value="
proposals.push($event);
accepted && (otp = $event);
"
@complete="completes.push($event)"
>
<InputOTPGroup>
<InputOTPSlot v-for="index in 4" :key="index" :index="index - 1" />
</InputOTPGroup>
<FieldError v-slot="state">
{{ state.validationErrors.join("|") }} / missing={{
state.validationDetails?.valueMissing
}}
</FieldError>
</InputOTP>
<button type="submit">校验验证码</button>
<button type="reset">重置验证码</button>
<button type="button" @click="otp = ''">清空验证码</button>
</Form>
<output id="otp-state">
{{ JSON.stringify({ value: otp, completes, proposals }) }}
</output>
</main>
</template>
+250 -1
View File
@@ -219,7 +219,7 @@ describe("InputOTP value model", () => {
});
describe("InputOTP pattern and states", () => {
it("filters characters with REGEXP_ONLY_CHARS and digits constants", async () => {
it("checks candidates 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]+$");
@@ -540,3 +540,252 @@ describe("InputOTP types", () => {
expect((bad as { variant?: string }).variant).toBe("ghost");
});
});
function pasteInto(input: Element, text: string) {
const event = new Event("paste", { bubbles: true, cancelable: true });
Object.defineProperty(event, "clipboardData", {
value: { getData: () => text },
});
input.dispatchEvent(event);
}
const settleOtp = async () => {
await nextTick();
await nextTick();
await nextTick();
};
function enhancedOtp(
props: Record<string, unknown> = {},
slots: Record<string, unknown> = {},
) {
return mount(InputOTP, {
props: { maxLength: 4, ...props },
slots: {
default: () =>
h(InputOTPGroup, {}, () =>
[0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })),
),
...slots,
},
attachTo: document.body,
});
}
it("OTP autoFocus and textAlign reach actual inputs without leaking root props", async () => {
const w = enhancedOtp({ autoFocus: true, textAlign: "right" });
try {
await settleOtp();
expect(document.activeElement).toBe(slotInputs(w)[0].element);
expect((slotInputs(w)[0].element as HTMLInputElement).style.textAlign).toBe(
"right",
);
expect(w.attributes("textalign")).toBeUndefined();
await w.setProps({ textAlign: "center" });
expect((slotInputs(w)[3].element as HTMLInputElement).style.textAlign).toBe(
"center",
);
} finally {
w.unmount();
}
});
it.each(["isDisabled", "isReadOnly"])(
"OTP %s prevents paste transformation and edits",
async (flag) => {
const transform = vi.fn((text: string) => text.replaceAll("-", ""));
const w = enhancedOtp({
[flag]: true,
defaultValue: "12",
pasteTransformer: transform,
autoFocus: true,
});
try {
await settleOtp();
pasteInto(slotInputs(w)[0].element, "34-56");
await settleOtp();
expect(transform).not.toHaveBeenCalled();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("12");
if (flag === "isDisabled")
expect(w.element.contains(document.activeElement)).toBe(false);
} finally {
w.unmount();
}
},
);
it("OTP transforms paste before whole-value pattern checking and restores rejected DOM values", async () => {
const w = enhancedOtp({
pattern: "^12[0-9]*$",
defaultValue: "12",
pasteTransformer: (t: string) => t.replaceAll("-", ""),
});
try {
pasteInto(slotInputs(w)[0].element, "12-34");
await settleOtp();
expect(
slotInputs(w).map((i) => (i.element as HTMLInputElement).value),
).toEqual(["1", "2", "3", "4"]);
expect(document.activeElement).toBe(slotInputs(w)[3].element);
expect((slotInputs(w)[3].element as HTMLInputElement).selectionStart).toBe(
0,
);
await slotInputs(w)[2].setValue("8");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("1284");
await slotInputs(w)[0].setValue("9");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("1284");
pasteInto(slotInputs(w)[0].element, "90-12");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("1284");
} finally {
w.unmount();
}
});
it("OTP rejects an invalid paste as one edit and honors consumer cancellation", async () => {
const w = enhancedOtp({ pattern: REGEXP_ONLY_DIGITS, defaultValue: "12" });
try {
pasteInto(slotInputs(w)[0].element, "3a45");
await settleOtp();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("12");
const transform = vi.fn((t: string) => t);
await w.setProps({ pasteTransformer: transform });
const slot = w.element;
slot.addEventListener("paste", (e: Event) => e.preventDefault(), {
capture: true,
});
pasteInto(slotInputs(w)[0].element, "5678");
await settleOtp();
expect(transform).not.toHaveBeenCalled();
} finally {
w.unmount();
}
});
it("OTP complete follows accepted threshold crossings, including external updates, rather than rejected drafts", async () => {
const w = enhancedOtp({ modelValue: "12" });
try {
pasteInto(slotInputs(w)[0].element, "1234");
await settleOtp();
pasteInto(slotInputs(w)[0].element, "1234");
await settleOtp();
expect(w.emitted("update:modelValue")).toHaveLength(2);
expect(w.emitted("complete")).toBeUndefined();
expect(
slotInputs(w)
.map((i) => (i.element as HTMLInputElement).value)
.join(""),
).toBe("12");
await w.setProps({ modelValue: "1234" });
await settleOtp();
expect(w.emitted("complete")).toEqual([["1234"]]);
await w.setProps({ modelValue: "9876" });
await settleOtp();
pasteInto(slotInputs(w)[0].element, "9876");
await settleOtp();
expect(w.emitted("complete")).toHaveLength(1);
await w.setProps({ modelValue: "" });
await settleOtp();
await w.setProps({ modelValue: "4567" });
await settleOtp();
expect(w.emitted("complete")).toEqual([["1234"], ["4567"]]);
} finally {
w.unmount();
}
});
it("OTP passes caller ValidityState through shared FieldError without emitting it on the DOM", async () => {
const { FieldError } = await import("../packages/vue/src");
const details = {
badInput: false,
customError: true,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valid: false,
valueMissing: false,
};
const w = enhancedOtp(
{
isInvalid: true,
validationDetails: details,
validationErrors: ["server"],
},
{
default: () => [
h(InputOTPGroup, {}, () =>
[0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })),
),
h(
FieldError,
{},
{
default: (s: { validationDetails?: ValidityState }) =>
String(s.validationDetails?.customError),
},
),
],
},
);
try {
await settleOtp();
expect(w.get('[data-slot="field-error"]').text()).toBe("true");
expect(w.attributes("validationdetails")).toBeUndefined();
} finally {
w.unmount();
}
});
it("OTP native required validation shares FieldError details and clears on an effective edit", async () => {
const { FieldError } = await import("../packages/vue/src");
const w = enhancedOtp(
{ required: true },
{
default: () => [
h(InputOTPGroup, {}, () =>
[0, 1, 2, 3].map((index) => h(InputOTPSlot, { index })),
),
h(
FieldError,
{},
{
default: (s: { validationDetails?: ValidityState }) =>
String(s.validationDetails?.valueMissing),
},
),
],
},
);
try {
await settleOtp();
const proxy = w.get('input[aria-hidden="true"]')
.element as HTMLInputElement;
expect(proxy.checkValidity()).toBe(false);
await settleOtp();
expect(w.get('[role="alert"]').text()).toBe("true");
await slotInputs(w)[0].setValue("1");
await settleOtp();
expect(w.find('[role="alert"]').exists()).toBe(false);
expect(proxy.checkValidity()).toBe(true);
} finally {
w.unmount();
}
});
+15
View File
@@ -871,5 +871,20 @@
".hv-date-picker__trigger",
".hv-date-range-picker__trigger"
]
},
"field-otp": {
"exports": [
"TextField",
"SearchField",
"FieldError",
"InputOTP",
"InputOTPSlot"
],
"css": [
".hv-textfield",
".hv-search-field",
".hv-field-error",
".hv-input-otp__input"
]
}
}
+51
View File
@@ -0,0 +1,51 @@
import { h } from "vue";
import {
TextField,
SearchField,
type TextFieldProps,
type SearchFieldProps,
type TextFieldRenderProps,
type SearchFieldRenderProps,
type InputOTPProps,
} from "@heroui-vue/components";
const text: TextFieldProps = { autoFocus: true, validationErrors: ["server"] };
const search: SearchFieldProps = { validationErrors: "local", autoFocus: true };
const otp: InputOTPProps = {
maxLength: 4,
autoFocus: true,
textAlign: "right",
pasteTransformer: (text) => text.replaceAll("-", ""),
};
const textSlot: NonNullable<
InstanceType<typeof TextField>["$slots"]["default"]
> = (state: TextFieldRenderProps) => [
h(
"span",
`${state.value}/${state.isFocusWithin}/${state.validationDetails.valid}`,
),
];
const searchSlot: NonNullable<
InstanceType<typeof SearchField>["$slots"]["default"]
> = (state: SearchFieldRenderProps) => [
h("span", `${state.value}/${state.isEmpty}/${state.isFocusVisible}`),
];
// @ts-expect-error errors are local text/arrays, not Form name maps
const badField: TextFieldProps = { validationErrors: { email: "wrong" } };
// @ts-expect-error text alignment is a closed union
const badAlignment: InputOTPProps = { maxLength: 4, textAlign: "bottom" };
// @ts-expect-error the paste transformer returns a string
const badPaste: InputOTPProps = { maxLength: 4, pasteTransformer: () => 42 };
const badDetails: InputOTPProps = {
maxLength: 4,
// @ts-expect-error all native validity flags are required
validationDetails: { valid: false },
};
void text;
void search;
void otp;
void textSlot;
void searchSlot;
void badField;
void badAlignment;
void badPaste;
void badDetails;