feat: migrate Pagination Header and InputOTP with field and event regressions

This commit is contained in:
maoyingjie
2026-10-23 13:49:44 +08:00
parent b2525bb04d
commit 1fa2929a24
72 changed files with 5784 additions and 16 deletions
@@ -0,0 +1,33 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { inputOTPContextKey } from "./context";
export default defineComponent({
name: "InputOTPGroup",
inheritAttrs: false,
props: {
as: {
type: String,
default: "div",
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const context = inject(inputOTPContextKey, null);
function render() {
return h(
props.as,
{
...attrs,
class: [context?.slots.value.group(), attrs.class],
"data-slot": "input-otp-group",
},
slots.default?.(),
);
}
return render;
},
});
</script>
@@ -0,0 +1,439 @@
<script lang="ts">
import {
cloneVNode,
Fragment,
isVNode,
computed,
defineComponent,
h,
inject,
nextTick,
onBeforeUnmount,
onMounted,
onUpdated,
provide,
ref,
shallowRef,
useAttrs,
useId,
watch,
type PropType,
type VNode,
type VNodeChild,
} from "vue";
import { PinInputRoot } from "reka-ui";
import { inputOTPVariants, type InputOTPVariants } from "@heroui-vue/styles";
import { useInheritedDisabled } from "../field/disabled";
import {
errorMessages,
fieldContextKey,
formContextKey,
mergeIds,
type FieldContext,
} from "../field/context";
import {
charsFromString,
inputOTPContextKey,
stringFromChars,
} from "./context";
const EMPTY_ERRORS: string[] = [];
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;
const flags = re.flags.replace(/[gy]/g, "");
return new RegExp(re.source, flags).test(char);
}
export default defineComponent({
name: "InputOTPRoot",
inheritAttrs: false,
props: {
/** Public string value; character at index i occupies slot i. */
modelValue: {
type: String,
default: undefined,
},
defaultValue: {
type: String,
default: "",
},
maxLength: {
type: Number,
required: true,
},
variant: {
type: String as PropType<InputOTPVariants["variant"]>,
default: "primary",
},
isDisabled: {
type: Boolean,
default: false,
},
isReadOnly: {
type: Boolean,
default: false,
},
isInvalid: {
type: Boolean,
default: false,
},
validationErrors: {
type: Array as PropType<string[]>,
default: undefined,
},
/** Class applied to the real PinInput inputs (merged with structure class). */
inputClassName: {
type: String,
default: undefined,
},
name: {
type: String,
default: undefined,
},
required: {
type: Boolean,
default: false,
},
mask: {
type: Boolean,
default: false,
},
/** Enables one-time-code autofill attributes on the real inputs. */
otp: {
type: Boolean,
default: false,
},
placeholder: {
type: String,
default: "",
},
/** Character filter, e.g. REGEXP_ONLY_DIGITS. */
pattern: {
type: [String, RegExp] as PropType<string | RegExp>,
default: undefined,
},
id: {
type: String,
default: undefined,
},
},
emits: ["update:modelValue", "change", "complete"],
setup(props, { emit, slots }) {
const attrs = useAttrs();
const autoId = useId();
const form = inject(formContextKey, undefined);
const length = computed(() => Math.max(0, props.maxLength | 0));
const pattern = computed<RegExp | null>(() => {
if (!props.pattern) return null;
return typeof props.pattern === "string"
? new RegExp(props.pattern)
: props.pattern;
});
const isControlled = computed(() => props.modelValue !== undefined);
const initial = props.defaultValue ?? "";
const startPublic = isControlled.value ? (props.modelValue ?? "") : initial;
/** Index-preserving slot characters; "" keeps a middle empty slot. */
const slotChars = ref<string[]>(charsFromString(startPublic, length.value));
/** Last string we emitted; parent echo keeps holes in slotChars. */
let lastEmitted = startPublic;
const disabled = useInheritedDisabled(
() => props.isDisabled || attrBoolean(attrs.disabled),
);
const readOnly = computed(
() =>
props.isReadOnly ||
attrBoolean(attrs.readonly) ||
attrBoolean(attrs.readOnly),
);
const descriptionIds = ref<string[]>([]);
const errorIds = ref<string[]>([]);
const labelIds = ref<string[]>([]);
const plannedLabels = ref<string[]>([]);
const labelledBy = computed(
() =>
(attrs["aria-labelledby"] as string | undefined) ??
(attrs["aria-label"]
? undefined
: mergeIds(plannedLabels.value, labelIds.value)),
);
const accessibleLabel = computed(
() => attrs["aria-label"] as string | undefined,
);
// shallowRef keeps object identity for response comparison (see useTextField).
const dismissed = shallowRef<object | undefined>();
const serverErrors = computed(() => {
const source = form?.validationErrors.value;
return source && source !== dismissed.value && props.name
? errorMessages(source[props.name])
: EMPTY_ERRORS;
});
const invalid = computed(
() =>
props.isInvalid ||
(props.validationErrors?.length ?? 0) > 0 ||
serverErrors.value.length > 0 ||
attrs["aria-invalid"] === true ||
attrs["aria-invalid"] === "true",
);
const errors = computed(() => [
...(props.validationErrors ?? EMPTY_ERRORS),
...serverErrors.value,
]);
const resolvedId = computed(() => props.id ?? autoId);
/** Stable id per real focusable input; Label `for` uses index 0. */
function inputId(index: number): string {
return `${resolvedId.value}-slot-${index}`;
}
provide(fieldContextKey, {
controlId: computed(() => inputId(0)),
kind: "text",
disabled,
readOnly,
required: computed(() => props.required),
invalid,
errors,
labelIds,
descriptionIds,
errorIds,
} satisfies FieldContext);
/**
* Display/input characters. When the parent echoes our emission the
* hole-preserving array is kept so middle deletes do not left-shift.
*/
const chars = computed(() => [...slotChars.value]);
watch(
() => props.modelValue,
(next, prev) => {
if (!isControlled.value) return;
if (next === prev) return;
const incoming = next ?? "";
// Echo of our own proposal — keep the index-preserving array.
if (incoming === lastEmitted) return;
lastEmitted = incoming;
slotChars.value = charsFromString(incoming, length.value);
},
);
watch(
() => length.value,
(nextLen) => {
// Pad/crop by index — do not serialize, or empty slots left-shift.
const prev = slotChars.value;
if (nextLen > prev.length) {
slotChars.value = [
...prev,
...Array.from({ length: nextLen - prev.length }, () => ""),
];
} else if (nextLen < prev.length) {
slotChars.value = prev.slice(0, nextLen);
}
const proposed = stringFromChars(slotChars.value);
const currentPublic = isControlled.value
? (props.modelValue ?? "")
: lastEmitted;
if (proposed !== currentPublic) {
lastEmitted = proposed;
emit("update:modelValue", proposed);
emit("change", proposed);
}
},
);
function applyChars(next: unknown[]) {
if (disabled.value || readOnly.value) return;
const clamped = Array.from({ length: length.value }, (_, i) => {
const raw = next[i];
return raw == null ? "" : String(raw);
});
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] = "";
}
}
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;
// Always request a change when the proposal differs from the public
// value so a rejected update can be retried with the same characters.
if (proposed !== currentPublic) {
lastEmitted = proposed;
// Effective edit dismisses the current server-error response.
dismissed.value = form?.validationErrors.value;
emit("update:modelValue", proposed);
emit("change", proposed);
void nextTick(() => {
if (!isControlled.value) return;
const publicValue = props.modelValue ?? "";
if (publicValue !== lastEmitted) {
// Parent rejected the proposal — restore from the public value.
slotChars.value = charsFromString(publicValue, length.value);
lastEmitted = publicValue;
}
});
}
if (
prevFilled < length.value &&
nextFilled === length.value &&
length.value > 0
) {
emit("complete", proposed);
}
}
function handlePinUpdate(value: unknown) {
applyChars(Array.isArray(value) ? value : []);
}
const describedBy = computed(() =>
mergeIds(
attrs["aria-describedby"] as string | undefined,
descriptionIds.value,
invalid.value ? errorIds.value : [],
),
);
function reset(event: Event) {
void nextTick(() => {
if (event.defaultPrevented) return;
if (!isControlled.value) {
slotChars.value = charsFromString(initial, length.value);
lastEmitted = initial;
} else {
const incoming = props.modelValue ?? "";
lastEmitted = incoming;
slotChars.value = charsFromString(incoming, length.value);
}
dismissed.value = form?.validationErrors.value;
});
}
const rootEl = ref<HTMLElement | null>(null);
function setRoot(el: unknown) {
const node = (el as { $el?: HTMLElement } | HTMLElement | null) ?? null;
const next = !node
? null
: node instanceof HTMLElement
? node
: ((node.$el as HTMLElement) ?? null);
rootEl.value = next;
}
let formEl: HTMLFormElement | null = null;
function bindForm() {
const next = rootEl.value?.closest("form") ?? null;
if (next === formEl) return;
formEl?.removeEventListener("reset", reset);
formEl = next;
formEl?.addEventListener("reset", reset);
}
onMounted(bindForm);
onUpdated(bindForm);
onBeforeUnmount(() => {
formEl?.removeEventListener("reset", reset);
formEl = null;
});
const variantSlots = computed(() =>
inputOTPVariants({ variant: props.variant }),
);
provide(inputOTPContextKey, {
slots: variantSlots,
isDisabled: disabled,
isInvalid: invalid,
isReadOnly: readOnly,
maxLength: length,
pattern,
chars,
mask: computed(() => props.mask),
inputClassName: computed(() => props.inputClassName),
describedBy,
inputId,
labelledBy,
accessibleLabel,
});
function prepareLabels(
nodes: VNodeChild[],
ids: string[],
path = "",
): VNodeChild[] {
return nodes.map((node, index) => {
if (!isVNode(node)) return node;
const type = node.type as { name?: string; __name?: string };
if ((type.name ?? type.__name) === "Label") {
const id = String(
node.props?.id ?? `${autoId}-label${path}-${index}`,
);
ids.push(id);
return cloneVNode(node, { id });
}
if (
(typeof node.type === "string" || node.type === Fragment) &&
Array.isArray(node.children)
) {
const copy = cloneVNode(node);
copy.children = prepareLabels(
node.children as VNodeChild[],
ids,
`${path}-${index}`,
) as VNode[];
return copy;
}
return node;
});
}
function render() {
const labels: string[] = [];
const children = prepareLabels(slots.default?.() ?? [], labels);
if (JSON.stringify(labels) !== JSON.stringify(plannedLabels.value))
plannedLabels.value = labels;
return h(
PinInputRoot,
{
ref: setRoot,
modelValue: chars.value,
disabled: disabled.value,
mask: props.mask,
otp: props.otp,
placeholder: props.placeholder,
name: props.name,
required: props.required,
id: resolvedId.value,
"onUpdate:modelValue": handlePinUpdate,
...attrs,
class: [variantSlots.value.base(), attrs.class],
"data-disabled": disabled.value || undefined,
"data-invalid": invalid.value ? "true" : undefined,
"data-slot": "input-otp",
},
{ default: () => children },
);
}
return render;
},
});
</script>
@@ -0,0 +1,33 @@
<script lang="ts">
import { defineComponent, h, inject, useAttrs } from "vue";
import { inputOTPContextKey } from "./context";
export default defineComponent({
name: "InputOTPSeparator",
inheritAttrs: false,
props: {
as: {
type: String,
default: "div",
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const context = inject(inputOTPContextKey, null);
function render() {
return h(
props.as,
{
...attrs,
class: [context?.slots.value.separator(), attrs.class],
"data-slot": "input-otp-separator",
},
slots.default?.(),
);
}
return render;
},
});
</script>
@@ -0,0 +1,189 @@
<script lang="ts">
import { computed, defineComponent, h, inject, ref, useAttrs } from "vue";
import { PinInputInput } from "reka-ui";
import { inputOTPContextKey } from "./context";
type Handler = (event: Event) => void;
function toHandlerArray(value: unknown): Handler[] {
if (!value) return [];
if (Array.isArray(value)) {
return value.filter((item): item is Handler => typeof item === "function");
}
return typeof value === "function" ? [value as Handler] : [];
}
export default defineComponent({
name: "InputOTPSlot",
inheritAttrs: false,
props: {
index: {
type: Number,
required: true,
},
as: {
type: String,
default: "div",
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const context = inject(inputOTPContextKey, null);
const focused = ref(false);
const char = computed(() => context?.chars.value[props.index] ?? "");
const isDisabled = computed(() => Boolean(context?.isDisabled.value));
const isInvalid = computed(() => Boolean(context?.isInvalid.value));
const isReadOnly = computed(() => Boolean(context?.isReadOnly.value));
const isFilled = computed(() => char.value.length > 0);
const isActive = computed(() => focused.value && !isDisabled.value);
const mask = computed(() => Boolean(context?.mask.value));
const displayChar = computed(() => (mask.value ? "•" : char.value));
function onInputFocus() {
focused.value = true;
}
function onInputBlur() {
focused.value = false;
}
/** Block edit keys before Reka handlers when readonly/disabled. */
function guardEdit(event: Event) {
if (!isReadOnly.value && !isDisabled.value) return;
const key = (event as KeyboardEvent).key;
if (
key === "Tab" ||
key === "Escape" ||
key === "ArrowLeft" ||
key === "ArrowRight" ||
key === "ArrowUp" ||
key === "ArrowDown" ||
key === "Home" ||
key === "End"
) {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
}
function guardPaste(event: Event) {
if (!isReadOnly.value && !isDisabled.value) return;
event.preventDefault();
event.stopImmediatePropagation();
}
/** After user handlers: preventDefault means cancel the edit. */
function stopIfPrevented(event: Event) {
if (event.defaultPrevented) event.stopImmediatePropagation();
}
function render() {
const slotClass = context?.slots.value.slot();
const valueClass = context?.slots.value.slotValue();
const caretClass = context?.slots.value.caret();
const inputClass = [
context?.slots.value.input(),
context?.inputClassName.value,
];
const {
class: cls,
onKeydown: userKeydown,
onKeydownCapture: userKeydownCapture,
onPaste: userPaste,
onPasteCapture: userPasteCapture,
...rest
} = attrs as Record<string, unknown>;
// Vue native handler arrays honor stopImmediatePropagation between
// items. Bubble-phase keydown/paste are promoted into the capture
// list so user preventDefault can cancel Reka's edit handlers.
const keydownCapture: Handler[] = [
guardEdit,
...toHandlerArray(userKeydownCapture),
...toHandlerArray(userKeydown),
stopIfPrevented,
];
const pasteCapture: Handler[] = [
guardPaste,
...toHandlerArray(userPasteCapture),
...toHandlerArray(userPaste),
stopIfPrevented,
];
return h(
props.as,
{
...rest,
class: [slotClass, cls],
onKeydownCapture: keydownCapture,
onPasteCapture: pasteCapture,
"data-active": isActive.value || undefined,
"data-disabled": isDisabled.value || undefined,
"data-filled": isFilled.value || undefined,
"data-invalid": isInvalid.value || undefined,
"data-readonly": isReadOnly.value || undefined,
"data-slot": "input-otp-slot",
},
[
isFilled.value
? h(
"div",
{
class: valueClass,
"data-slot": "input-otp-slot-value",
},
displayChar.value,
)
: null,
isActive.value
? h("div", {
class: caretClass,
"data-slot": "input-otp-caret",
})
: null,
h(
PinInputInput,
{
asChild: true,
index: props.index,
disabled: isDisabled.value,
readonly: isReadOnly.value || undefined,
class: inputClass,
id: context?.inputId(props.index),
"data-slot": "input-otp-input",
autocomplete: "one-time-code",
"aria-describedby": context?.describedBy.value,
"aria-invalid": isInvalid.value ? "true" : undefined,
onFocus: onInputFocus,
onBlur: onInputBlur,
},
{
// Own the native ARIA so the primitive's default label cannot
// override the composed field name. Retain its input handlers.
default: () =>
h("input", {
"aria-labelledby":
attrs["aria-labelledby"] ??
(attrs["aria-label"]
? undefined
: context?.labelledBy.value),
"aria-label":
attrs["aria-label"] ??
context?.accessibleLabel.value ??
(context?.labelledBy.value
? undefined
: `pin input ${props.index + 1} of ${context?.maxLength.value ?? 0}`),
}),
},
),
slots.default?.(),
],
);
}
return render;
},
});
</script>
@@ -0,0 +1,40 @@
import type { ComputedRef, InjectionKey } from "vue";
import type { inputOTPVariants } from "@heroui-vue/styles";
export type InputOTPSlots = ReturnType<typeof inputOTPVariants>;
export interface InputOTPContextValue {
slots: ComputedRef<InputOTPSlots>;
isDisabled: ComputedRef<boolean>;
isInvalid: ComputedRef<boolean>;
isReadOnly: ComputedRef<boolean>;
maxLength: ComputedRef<number>;
pattern: ComputedRef<RegExp | null>;
/** Index-preserving character array; empty string means an empty slot. */
chars: ComputedRef<string[]>;
mask: ComputedRef<boolean>;
inputClassName: ComputedRef<string | undefined>;
describedBy: ComputedRef<string | undefined>;
labelledBy: ComputedRef<string | undefined>;
accessibleLabel: ComputedRef<string | undefined>;
/** Stable DOM id for the real focusable input at `index`. */
inputId: (index: number) => string;
}
export const inputOTPContextKey: InjectionKey<InputOTPContextValue> = Symbol(
"heroui-vue.input-otp",
);
/**
* Public model is a string. Slot `i` maps to `value[i]`.
* Empty slots stay at their indices in the internal array so the UI
* never left-shifts later characters. Serialization joins characters
* in index order (`arr.join("")`) — slot display always reads the array.
*/
export function charsFromString(value: string, length: number): string[] {
return Array.from({ length }, (_, i) => value[i] ?? "");
}
export function stringFromChars(chars: string[]): string {
return chars.join("");
}