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
@@ -19,6 +19,7 @@ const { field, id } = useFieldPart("error", attrs);
<slot
:validation-errors="field?.errors.value ?? []"
:is-invalid="field?.invalid.value ?? false"
:validation-details="field?.validationDetails?.value"
>
{{ field?.errors.value.join(" ") }}
</slot>
@@ -12,6 +12,7 @@ export interface FieldContext {
required: ComputedRef<boolean>;
invalid: ComputedRef<boolean>;
errors: ComputedRef<string[]>;
validationDetails?: ComputedRef<ValidityState | undefined>;
labelIds?: Ref<string[]>;
descriptionIds: Ref<string[]>;
errorIds: Ref<string[]>;
@@ -12,12 +12,15 @@ import {
shallowRef,
useId,
watchEffect,
onMounted,
nextTick,
type PropType,
type ExtractPropTypes,
type Slots,
type VNode,
type VNodeChild,
} from "vue";
import { validitySnapshot } from "./validation";
import { textFieldVariants } from "@heroui-vue/styles";
import {
fieldContextKey,
@@ -34,6 +37,18 @@ import {
import { useInheritedDisabled } from "./disabled";
export interface TextFieldRenderProps {
value: string;
isDisabled: boolean;
isReadOnly: boolean;
isRequired: boolean;
isInvalid: boolean;
isFocusWithin: boolean;
isFocusVisible: boolean;
validationErrors: string[];
validationDetails: ValidityState;
}
export const textFieldProps = {
modelValue: String,
defaultValue: String,
@@ -50,6 +65,8 @@ export const textFieldProps = {
isReadOnly: Boolean,
isRequired: Boolean,
isInvalid: Boolean,
autoFocus: Boolean,
validationErrors: [String, Array] as PropType<string | string[]>,
fullWidth: Boolean,
variant: String as PropType<"primary" | "secondary">,
validationBehavior: String as PropType<ValidationBehavior>,
@@ -89,6 +106,10 @@ export function useTextField(
const touched = ref(false),
nativeError = ref("");
const dismissed = shallowRef<object>();
const dismissedLocal = shallowRef<string | string[]>();
const focused = ref(false),
focusVisible = ref(false);
const details = shallowRef<ValidityState>(validitySnapshot());
const descriptionIds = ref<string[]>([]),
errorIds = ref<string[]>([]);
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
@@ -109,11 +130,19 @@ export function useTextField(
? errorMessages(source[props.name])
: [];
});
const localErrors = computed(() =>
props.validationErrors !== dismissedLocal.value
? errorMessages(props.validationErrors)
: [],
);
const externalErrors = computed(() => [
...new Set([...localErrors.value, ...serverErrors.value]),
]);
const customErrors = computed(() =>
errorMessages(props.validate?.(value.value)),
);
const errors = computed(() => [
...serverErrors.value,
...externalErrors.value,
...(touched.value || behavior.value === "aria" ? customErrors.value : []),
...((touched.value || behavior.value === "aria") && nativeError.value
? [nativeError.value]
@@ -128,8 +157,11 @@ export function useTextField(
);
function setValue(next: string) {
if (disabled.value || readOnly.value) return;
if (next !== value.value) {
dismissed.value = form?.validationErrors.value;
dismissedLocal.value = props.validationErrors;
}
internal.value = next;
dismissed.value = form?.validationErrors.value;
nativeError.value = "";
emit("update:modelValue", next);
}
@@ -148,6 +180,7 @@ export function useTextField(
required,
invalid,
errors,
validationDetails: computed(() => details.value),
descriptionIds,
errorIds,
value,
@@ -189,7 +222,7 @@ export function useTextField(
touched.value = true;
const element = event.target as HTMLInputElement | HTMLTextAreaElement;
nativeError.value =
customErrors.value.length || serverErrors.value.length
customErrors.value.length || externalErrors.value.length
? ""
: element.validationMessage;
},
@@ -198,6 +231,7 @@ export function useTextField(
touched.value = false;
nativeError.value = "";
dismissed.value = form?.validationErrors.value;
dismissedLocal.value = props.validationErrors;
},
};
provide(fieldContextKey, field);
@@ -205,16 +239,28 @@ export function useTextField(
watchEffect(
() => {
const currentValue = value.value;
// Native constraints are patched by the leaf before this post effect.
// Track root props even when the value itself has not changed.
void [
props.type,
props.minLength,
props.maxLength,
props.pattern,
required.value,
];
control.value?.setCustomValidity(
behavior.value === "native" && !disabled.value && !readOnly.value
? [...serverErrors.value, ...customErrors.value].join(" ")
? [...externalErrors.value, ...customErrors.value].join(" ")
: "",
);
if (behavior.value === "native" && touched.value)
nativeError.value =
customErrors.value.length || serverErrors.value.length
customErrors.value.length || externalErrors.value.length
? ""
: (control.value?.validationMessage ?? "");
const snapshot = validitySnapshot(control.value?.validity);
if (JSON.stringify(snapshot) !== JSON.stringify(details.value))
details.value = snapshot;
if (behavior.value === "aria")
nativeError.value =
disabled.value || readOnly.value
@@ -225,9 +271,30 @@ export function useTextField(
},
{ flush: "post" },
);
onMounted(() => {
void nextTick(() => {
if (props.autoFocus && !disabled.value) control.value?.focus();
});
});
function focusIn(event: FocusEvent) {
focused.value = true;
focusVisible.value = (event.target as HTMLElement).matches(
":focus-visible",
);
}
function focusOut(event: FocusEvent) {
if (
!(event.currentTarget as HTMLElement).contains(
event.relatedTarget as Node | null,
)
) {
focused.value = false;
focusVisible.value = false;
}
}
expose({ focus: () => control.value?.focus(), element: control });
function prepare(
nodes: VNodeChild[],
nodes: VNodeChild,
found: {
description: string[];
error: string[];
@@ -237,7 +304,7 @@ export function useTextField(
},
path = "",
): VNodeChild[] {
return nodes.map((node, index) => {
return (Array.isArray(nodes) ? nodes : [nodes]).map((node, index) => {
if (!isVNode(node) || node.type === Comment) return node;
const position = `${path}-${index}`;
const type = node.type as { name?: string; __name?: string };
@@ -267,7 +334,7 @@ export function useTextField(
node.children &&
typeof node.children === "object"
) {
const groupSlots = node.children as { default?: () => VNodeChild[] };
const groupSlots = node.children as { default?: () => VNodeChild };
if (typeof groupSlots.default === "function") {
const prepared = prepare(groupSlots.default(), found, position);
const clone = cloneVNode(node);
@@ -305,6 +372,10 @@ export function useTextField(
isRequired: required.value,
isInvalid: invalid.value,
validationErrors: errors.value,
validationDetails: details.value,
value: value.value,
isFocusWithin: focused.value,
isFocusVisible: focusVisible.value,
...options.slotState?.(),
}) ?? [],
found,
@@ -330,6 +401,10 @@ export function useTextField(
textFieldVariants({ fullWidth: props.fullWidth }),
attrs.class,
],
onFocusin: focusIn,
onFocusout: focusOut,
"data-focus-within": focused.value || undefined,
"data-focus-visible": focusVisible.value || undefined,
"data-slot": options.rootSlot ?? "textfield",
"data-invalid": invalid.value || undefined,
"data-disabled": disabled.value || undefined,
@@ -341,5 +416,5 @@ export function useTextField(
children,
);
};
return { field, element: control, render };
return { field, element: control, render, focused, focusVisible };
}
@@ -0,0 +1,16 @@
/** Snapshot native readonly validity flags without retaining a live DOM object. */
export function validitySnapshot(value?: ValidityState): ValidityState {
return {
badInput: value?.badInput ?? false,
customError: value?.customError ?? false,
patternMismatch: value?.patternMismatch ?? false,
rangeOverflow: value?.rangeOverflow ?? false,
rangeUnderflow: value?.rangeUnderflow ?? false,
stepMismatch: value?.stepMismatch ?? false,
tooLong: value?.tooLong ?? false,
tooShort: value?.tooShort ?? false,
typeMismatch: value?.typeMismatch ?? false,
valid: value?.valid ?? true,
valueMissing: value?.valueMissing ?? false,
};
}
@@ -17,10 +17,12 @@ import {
useAttrs,
useId,
watch,
watchEffect,
type PropType,
type VNode,
type VNodeChild,
} from "vue";
import { validitySnapshot } from "../field/validation";
import { PinInputRoot } from "reka-ui";
import { inputOTPVariants, type InputOTPVariants } from "@heroui-vue/styles";
import { useInheritedDisabled } from "../field/disabled";
@@ -43,11 +45,11 @@ function attrBoolean(value: unknown): boolean {
return value != null && value !== false;
}
/** Match one character without leaking lastIndex on global/sticky regexes. */
function charAllowed(re: RegExp, char: string): boolean {
if (!char) return true;
/** Test the whole candidate without leaking lastIndex on global/sticky regexes. */
function valueAllowed(re: RegExp, value: string): boolean {
if (!value) return true;
const flags = re.flags.replace(/[gy]/g, "");
return new RegExp(re.source, flags).test(char);
return new RegExp(re.source, flags).test(value);
}
export default defineComponent({
@@ -83,6 +85,13 @@ export default defineComponent({
type: Boolean,
default: false,
},
autoFocus: Boolean,
pasteTransformer: Function as PropType<(pastedText: string) => string>,
textAlign: {
type: String as PropType<"left" | "center" | "right">,
default: "left",
},
validationDetails: Object as PropType<ValidityState>,
validationErrors: {
type: Array as PropType<string[]>,
default: undefined,
@@ -113,7 +122,7 @@ export default defineComponent({
type: String,
default: "",
},
/** Character filter, e.g. REGEXP_ONLY_DIGITS. */
/** Whole-value predicate, e.g. REGEXP_ONLY_DIGITS. */
pattern: {
type: [String, RegExp] as PropType<string | RegExp>,
default: undefined,
@@ -179,19 +188,23 @@ export default defineComponent({
: EMPTY_ERRORS;
});
const nativeError = ref("");
const invalid = computed(
() =>
props.isInvalid ||
(props.validationErrors?.length ?? 0) > 0 ||
serverErrors.value.length > 0 ||
Boolean(nativeError.value) ||
attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true",
);
const errors = computed(() => [
...(props.validationErrors ?? EMPTY_ERRORS),
...serverErrors.value,
...(nativeError.value ? [nativeError.value] : []),
]);
const nativeDetails = shallowRef<ValidityState>(validitySnapshot());
const resolvedId = computed(() => props.id ?? autoId);
/** Stable id per real focusable input; Label `for` uses index 0. */
function inputId(index: number): string {
@@ -206,6 +219,9 @@ export default defineComponent({
required: computed(() => props.required),
invalid,
errors,
validationDetails: computed(
() => props.validationDetails ?? nativeDetails.value,
),
labelIds,
descriptionIds,
errorIds,
@@ -261,18 +277,25 @@ export default defineComponent({
const raw = next[i];
return raw == null ? "" : String(raw);
});
const proposed = stringFromChars(clamped);
const re = pattern.value;
if (re) {
for (let i = 0; i < clamped.length; i++) {
const char = clamped[i];
if (char && !charAllowed(re, char)) clamped[i] = "";
}
if (re && !valueAllowed(re, proposed)) {
// Force the primitive and native inputs back to the accepted slots.
const accepted = [...slotChars.value];
void nextTick(() => {
slotChars.value = accepted;
rootEl.value
?.querySelectorAll<HTMLInputElement>(
'input[data-slot="input-otp-input"]',
)
.forEach((input, index) => {
input.value = accepted[index] ?? "";
});
});
return false;
}
const previous = stringFromChars(slotChars.value);
const prevFilled = slotChars.value.filter(Boolean).length;
const nextFilled = clamped.filter(Boolean).length;
slotChars.value = clamped;
const proposed = stringFromChars(clamped);
const currentPublic = isControlled.value
? (props.modelValue ?? "")
: previous;
@@ -282,6 +305,7 @@ export default defineComponent({
lastEmitted = proposed;
// Effective edit dismisses the current server-error response.
dismissed.value = form?.validationErrors.value;
nativeError.value = "";
emit("update:modelValue", proposed);
emit("change", proposed);
void nextTick(() => {
@@ -294,15 +318,27 @@ export default defineComponent({
}
});
}
if (
prevFilled < length.value &&
nextFilled === length.value &&
length.value > 0
) {
emit("complete", proposed);
}
return true;
}
// Completion follows the accepted public value, never a rejected proposal.
watch(
() =>
isControlled.value
? (props.modelValue ?? "")
: stringFromChars(slotChars.value),
(next, previous) => {
if (
next !== previous &&
previous.length < length.value &&
next.length === length.value &&
length.value > 0
)
emit("complete", next);
},
{ flush: "post" },
);
function handlePinUpdate(value: unknown) {
applyChars(Array.isArray(value) ? value : []);
}
@@ -327,6 +363,7 @@ export default defineComponent({
slotChars.value = charsFromString(incoming, length.value);
}
dismissed.value = form?.validationErrors.value;
nativeError.value = "";
});
}
@@ -349,7 +386,46 @@ export default defineComponent({
formEl = next;
formEl?.addEventListener("reset", reset);
}
onMounted(bindForm);
onMounted(() => {
bindForm();
void nextTick(() => {
if (props.autoFocus && !disabled.value)
rootEl.value
?.querySelector<HTMLInputElement>(
'input[data-slot="input-otp-input"]:not(:disabled)',
)
?.focus();
});
});
watchEffect(
() => {
// Shared FieldContext exposes the real validation proxy, with optional
// caller-supplied ValidityState taking precedence for FieldError slots.
const proxy = rootEl.value?.querySelector<HTMLInputElement>(
'input[aria-hidden="true"]',
);
if (!proxy) return;
const source = pattern.value?.source;
if (source) proxy.setAttribute("pattern", source);
else proxy.removeAttribute("pattern");
proxy.readOnly = readOnly.value;
if (disabled.value || readOnly.value) nativeError.value = "";
proxy.setCustomValidity(
disabled.value || readOnly.value
? ""
: [...(props.validationErrors ?? []), ...serverErrors.value].join(
" ",
),
);
// Track primitive value updates so native validity is read after DOM patch.
chars.value;
props.required;
const snapshot = validitySnapshot(proxy.validity);
if (JSON.stringify(snapshot) !== JSON.stringify(nativeDetails.value))
nativeDetails.value = snapshot;
},
{ flush: "post" },
);
onUpdated(bindForm);
onBeforeUnmount(() => {
formEl?.removeEventListener("reset", reset);
@@ -369,12 +445,78 @@ export default defineComponent({
chars,
mask: computed(() => props.mask),
inputClassName: computed(() => props.inputClassName),
textAlign: computed(() => props.textAlign),
handlePaste,
guardInput,
describedBy,
inputId,
labelledBy,
accessibleLabel,
});
function guardInput(event: InputEvent, index: number) {
if (event.isComposing) return;
if (!(event.target instanceof HTMLInputElement)) return;
const target = event.target;
const next = [...slotChars.value];
const multi = (event.data?.length ?? 0) > 1;
if (multi) {
const text = target.value;
const start = text.length >= length.value ? 0 : index;
for (
let i = start;
i < Math.min(start + text.length, length.value);
i++
)
next[i] = text[i - start]!;
} else next[index] = event.data || target.value.slice(-1);
if (
disabled.value ||
readOnly.value ||
event.defaultPrevented ||
(pattern.value && !valueAllowed(pattern.value, stringFromChars(next)))
) {
event.preventDefault();
event.stopImmediatePropagation();
target.value = slotChars.value[index] ?? "";
target.select();
}
}
function handlePaste(event: ClipboardEvent, index: number) {
if (
event.defaultPrevented ||
disabled.value ||
readOnly.value ||
!event.clipboardData
)
return;
const raw =
event.clipboardData.getData("text/plain") ||
event.clipboardData.getData("text");
const text = props.pasteTransformer ? props.pasteTransformer(raw) : raw;
event.preventDefault();
event.stopImmediatePropagation();
if (!text) return;
// Preserve PinInput's slot editing convention: a full code replaces
// all slots; a shorter paste starts at the focused slot.
const start = text.length >= length.value ? 0 : index;
const next = [...slotChars.value];
for (let i = start; i < Math.min(start + text.length, length.value); i++)
next[i] = text[i - start]!;
if (!applyChars(next)) return;
void nextTick(() => {
if (isControlled.value && props.modelValue !== stringFromChars(next))
return;
const inputs = rootEl.value?.querySelectorAll<HTMLInputElement>(
'input[data-slot="input-otp-input"]',
);
const input = inputs?.[Math.min(start + text.length, length.value - 1)];
input?.focus();
input?.select();
});
}
function prepareLabels(
nodes: VNodeChild[],
ids: string[],
@@ -405,6 +547,19 @@ export default defineComponent({
return node;
});
}
function invalidCapture(event: Event) {
const target = event.target;
if (
target instanceof HTMLInputElement &&
target.getAttribute("aria-hidden") === "true"
) {
nativeDetails.value = validitySnapshot(target.validity);
nativeError.value =
props.validationErrors?.length || serverErrors.value.length
? ""
: target.validationMessage;
}
}
function render() {
const labels: string[] = [];
const children = prepareLabels(slots.default?.() ?? [], labels);
@@ -413,6 +568,7 @@ export default defineComponent({
return h(
PinInputRoot,
{
...attrs,
ref: setRoot,
modelValue: chars.value,
disabled: disabled.value,
@@ -423,7 +579,14 @@ export default defineComponent({
required: props.required,
id: resolvedId.value,
"onUpdate:modelValue": handlePinUpdate,
...attrs,
onInvalidCapture: [
...(Array.isArray(attrs.onInvalidCapture)
? attrs.onInvalidCapture
: attrs.onInvalidCapture
? [attrs.onInvalidCapture]
: []),
invalidCapture,
],
class: [variantSlots.value.base(), attrs.class],
"data-disabled": disabled.value || undefined,
"data-invalid": invalid.value ? "true" : undefined,
@@ -93,6 +93,7 @@ export default defineComponent({
onKeydownCapture: userKeydownCapture,
onPaste: userPaste,
onPasteCapture: userPasteCapture,
onInputCapture: userInputCapture,
...rest
} = attrs as Record<string, unknown>;
@@ -110,6 +111,7 @@ export default defineComponent({
...toHandlerArray(userPasteCapture),
...toHandlerArray(userPaste),
stopIfPrevented,
(event) => context?.handlePaste(event as ClipboardEvent, props.index),
];
return h(
@@ -117,6 +119,10 @@ export default defineComponent({
{
...rest,
class: [slotClass, cls],
onInputCapture: [
...toHandlerArray(userInputCapture),
(event: InputEvent) => context?.guardInput(event, props.index),
],
onKeydownCapture: keydownCapture,
onPasteCapture: pasteCapture,
"data-active": isActive.value || undefined,
@@ -151,6 +157,7 @@ export default defineComponent({
disabled: isDisabled.value,
readonly: isReadOnly.value || undefined,
class: inputClass,
style: { textAlign: context?.textAlign.value },
id: context?.inputId(props.index),
"data-slot": "input-otp-input",
autocomplete: "one-time-code",
@@ -14,6 +14,9 @@ export interface InputOTPContextValue {
chars: ComputedRef<string[]>;
mask: ComputedRef<boolean>;
inputClassName: ComputedRef<string | undefined>;
textAlign: ComputedRef<"left" | "center" | "right">;
guardInput: (event: InputEvent, index: number) => void;
handlePaste: (event: ClipboardEvent, index: number) => void;
describedBy: ComputedRef<string | undefined>;
labelledBy: ComputedRef<string | undefined>;
accessibleLabel: ComputedRef<string | undefined>;
@@ -4,21 +4,24 @@ import {
defineComponent,
getCurrentInstance,
nextTick,
onMounted,
provide,
ref,
type SlotsType,
type VNode,
} from "vue";
import { searchFieldVariants } from "@heroui-vue/styles";
import { textFieldProps, useTextField } from "../field/useTextField";
import { searchFieldContextKey } from "./context";
import { searchFieldContextKey, type SearchFieldRenderProps } from "./context";
export default defineComponent({
name: "SearchField",
inheritAttrs: false,
slots: Object as SlotsType<{
default: (state: SearchFieldRenderProps) => VNode[];
}>,
props: {
...textFieldProps,
type: { type: String, default: "search" },
autoFocus: Boolean,
},
emits: {
"update:modelValue": (_value: string) => true,
@@ -27,32 +30,34 @@ export default defineComponent({
},
setup(props, context) {
const instance = getCurrentInstance();
const hovered = ref(false),
focused = ref(false),
focusVisible = ref(false);
const hovered = ref(false);
const slots = computed(() =>
searchFieldVariants({
variant: props.variant,
fullWidth: props.fullWidth,
}),
);
const { field, element, render } = useTextField(props, context, {
rootSlot: "search-field",
rootClass: () => slots.value.base(),
rootAttrs: () => ({
onKeydown: keydown,
"data-empty": !field.value.value || undefined,
"data-focus-within": focused.value || undefined,
"data-focus-visible": focusVisible.value || undefined,
"data-hovered": (!field.disabled.value && hovered.value) || undefined,
}),
slotState: () => ({
isEmpty: !field.value.value,
isHovered: !field.disabled.value && hovered.value,
isFocusWithin: focused.value,
isFocusVisible: focusVisible.value,
}),
});
const { field, element, render, focused, focusVisible } = useTextField(
props,
context,
{
rootSlot: "search-field",
rootClass: () => slots.value.base(),
rootAttrs: () => ({
onKeydown: keydown,
"data-empty": !field.value.value || undefined,
"data-focus-within": focused.value || undefined,
"data-focus-visible": focusVisible.value || undefined,
"data-hovered": (!field.disabled.value && hovered.value) || undefined,
}),
slotState: () => ({
isEmpty: !field.value.value,
isHovered: !field.disabled.value && hovered.value,
isFocusWithin: focused.value,
isFocusVisible: focusVisible.value,
}),
},
);
function clear(event?: Event) {
const input = element.value;
if (
@@ -112,9 +117,7 @@ export default defineComponent({
clear,
keydown,
});
onMounted(() => {
if (props.autoFocus && !field.disabled.value) element.value?.focus();
});
return render;
},
});
@@ -1,6 +1,11 @@
import type { ComputedRef, InjectionKey, Ref } from "vue";
import type { searchFieldVariants } from "@heroui-vue/styles";
import type { TextFieldContext } from "../textfield/context";
import type { TextFieldRenderProps } from "../field/useTextField";
export interface SearchFieldRenderProps extends TextFieldRenderProps {
isEmpty: boolean;
isHovered: boolean;
}
export interface SearchFieldContext {
field: TextFieldContext;
slots: ComputedRef<ReturnType<typeof searchFieldVariants>>;
@@ -1,10 +1,17 @@
<script lang="ts">
import { defineComponent } from "vue";
import { textFieldProps, useTextField } from "../field/useTextField";
import { defineComponent, type SlotsType, type VNode } from "vue";
import {
textFieldProps,
useTextField,
type TextFieldRenderProps,
} from "../field/useTextField";
export default defineComponent({
name: "TextField",
inheritAttrs: false,
props: textFieldProps,
slots: Object as SlotsType<{
default: (state: TextFieldRenderProps) => VNode[];
}>,
emits: { "update:modelValue": (_value: string) => true },
setup(props, context) {
return useTextField(props, context).render;
+3
View File
@@ -1510,3 +1510,6 @@ export type {
TooltipRootProps,
TypographyRootProps,
} from "./types";
export type { TextFieldRenderProps } from "./components/field/useTextField";
export type { SearchFieldRenderProps } from "./components/search-field/context";