feat: migrate NumberField with form integration and docs
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
cloneVNode,
|
||||
computed,
|
||||
defineComponent,
|
||||
Fragment,
|
||||
h,
|
||||
inject,
|
||||
isVNode,
|
||||
mergeProps,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
onUpdated,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
useId,
|
||||
watchEffect,
|
||||
getCurrentInstance,
|
||||
onBeforeUpdate,
|
||||
type PropType,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import { NumberFieldRoot } from "reka-ui";
|
||||
import { numberFieldVariants } from "@heroui-vue/styles";
|
||||
import { useInheritedDisabled } from "../field/disabled";
|
||||
import {
|
||||
errorMessages,
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
mergeIds,
|
||||
type ValidationBehavior,
|
||||
type ValidateResult,
|
||||
} from "../field/context";
|
||||
import { useConfig } from "../../providers/context";
|
||||
import { numberFieldKey, type NumberFieldContext } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "NumberField",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
modelValue: {
|
||||
type: [Number, null] as PropType<number | null>,
|
||||
default: undefined,
|
||||
},
|
||||
defaultValue: Number,
|
||||
minValue: Number,
|
||||
maxValue: Number,
|
||||
step: { type: Number, default: 1 },
|
||||
locale: String,
|
||||
formatOptions: Object as PropType<Intl.NumberFormatOptions>,
|
||||
isDisabled: Boolean,
|
||||
isReadOnly: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
disabled: Boolean,
|
||||
readonly: Boolean,
|
||||
required: Boolean,
|
||||
fullWidth: Boolean,
|
||||
variant: {
|
||||
type: String as PropType<"primary" | "secondary">,
|
||||
default: "primary",
|
||||
},
|
||||
id: String,
|
||||
name: String,
|
||||
form: String,
|
||||
autoFocus: Boolean,
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validationErrors: Array as PropType<string[]>,
|
||||
validate: Function as PropType<(value: number | null) => ValidateResult>,
|
||||
isWheelDisabled: { type: Boolean, default: true },
|
||||
as: { type: String, default: "div" },
|
||||
},
|
||||
emits: {
|
||||
"update:modelValue": (_value: number | null) => true,
|
||||
change: (_value: number | null) => true,
|
||||
},
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const config = useConfig();
|
||||
const formContext = inject(formContextKey, undefined);
|
||||
const instance = getCurrentInstance();
|
||||
const hasModel = () =>
|
||||
["modelValue", "model-value"].some((key) =>
|
||||
Object.hasOwn(instance?.vnode.props ?? {}, key),
|
||||
);
|
||||
const controlled = ref(hasModel());
|
||||
onBeforeUpdate(() => {
|
||||
controlled.value = hasModel();
|
||||
});
|
||||
const initial = props.defaultValue ?? null;
|
||||
const local = ref<number | null>(initial);
|
||||
const normalize = (value: number | null | undefined) =>
|
||||
value == null || !Number.isFinite(value) ? null : value;
|
||||
const value = computed(() =>
|
||||
normalize(controlled.value ? props.modelValue : local.value),
|
||||
);
|
||||
const styles = computed(() =>
|
||||
numberFieldVariants({
|
||||
variant: props.variant,
|
||||
fullWidth: props.fullWidth,
|
||||
}),
|
||||
);
|
||||
const disabled = useInheritedDisabled(
|
||||
() => props.isDisabled || props.disabled,
|
||||
);
|
||||
const readOnly = computed(() => props.isReadOnly || props.readonly);
|
||||
const required = computed(() => props.isRequired || props.required);
|
||||
const behavior = computed(
|
||||
() =>
|
||||
props.validationBehavior ??
|
||||
formContext?.validationBehavior.value ??
|
||||
"native",
|
||||
);
|
||||
const generated = useId();
|
||||
const leafId = ref<string>();
|
||||
const controlId = computed(() => leafId.value ?? props.id ?? generated);
|
||||
const element = shallowRef<HTMLInputElement>();
|
||||
const descriptionIds = ref<string[]>([]),
|
||||
errorIds = ref<string[]>([]);
|
||||
const plannedDescriptions = ref<string[]>([]),
|
||||
plannedErrors = ref<string[]>([]);
|
||||
const focused = ref(false),
|
||||
focusVisible = ref(false),
|
||||
touched = ref(false);
|
||||
const nativeError = ref("");
|
||||
const dismissed = shallowRef<object>();
|
||||
const serverErrors = computed(() =>
|
||||
props.name && formContext?.validationErrors.value !== dismissed.value
|
||||
? errorMessages(formContext?.validationErrors.value[props.name])
|
||||
: [],
|
||||
);
|
||||
const customErrors = computed(() =>
|
||||
errorMessages(props.validate?.(value.value)),
|
||||
);
|
||||
const constraintError = computed(() => {
|
||||
if (disabled.value || readOnly.value) return "";
|
||||
if (required.value && value.value === null) return "请填写此字段。";
|
||||
if (
|
||||
value.value !== null &&
|
||||
props.minValue !== undefined &&
|
||||
value.value < props.minValue
|
||||
)
|
||||
return `值必须大于或等于 ${props.minValue}。`;
|
||||
if (
|
||||
value.value !== null &&
|
||||
props.maxValue !== undefined &&
|
||||
value.value > props.maxValue
|
||||
)
|
||||
return `值必须小于或等于 ${props.maxValue}。`;
|
||||
return "";
|
||||
});
|
||||
const errors = computed(() => [
|
||||
...(props.validationErrors ?? []),
|
||||
...serverErrors.value,
|
||||
...(touched.value || behavior.value === "aria"
|
||||
? [
|
||||
...customErrors.value,
|
||||
...(constraintError.value ? [constraintError.value] : []),
|
||||
...(nativeError.value ? [nativeError.value] : []),
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
const invalid = computed(
|
||||
() =>
|
||||
props.isInvalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true" ||
|
||||
errors.value.length > 0,
|
||||
);
|
||||
const describedBy = () =>
|
||||
mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
descriptionIds.value,
|
||||
plannedDescriptions.value,
|
||||
invalid.value ? [...errorIds.value, ...plannedErrors.value] : [],
|
||||
);
|
||||
provide(fieldContextKey, {
|
||||
kind: "text",
|
||||
controlId,
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
invalid,
|
||||
errors,
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
});
|
||||
function update(next: number | undefined) {
|
||||
if (disabled.value || readOnly.value) return;
|
||||
const normalized = normalize(next);
|
||||
if (Object.is(normalized, value.value)) return;
|
||||
if (!hasModel()) local.value = normalized;
|
||||
dismissed.value = formContext?.validationErrors.value;
|
||||
nativeError.value = "";
|
||||
emit("update:modelValue", normalized);
|
||||
emit("change", normalized);
|
||||
}
|
||||
const field: NumberFieldContext = {
|
||||
styles,
|
||||
value,
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
invalid,
|
||||
behavior,
|
||||
controlId,
|
||||
element,
|
||||
focused,
|
||||
focusVisible,
|
||||
describedBy,
|
||||
inputAttrs: () => ({
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => key.startsWith("aria-")),
|
||||
),
|
||||
form: props.form,
|
||||
autofocus: props.autoFocus || undefined,
|
||||
}),
|
||||
commit: () => {
|
||||
touched.value = true;
|
||||
},
|
||||
invalidEvent: () => {
|
||||
if (behavior.value === "native") touched.value = true;
|
||||
},
|
||||
};
|
||||
provide(numberFieldKey, field);
|
||||
watchEffect(
|
||||
() => {
|
||||
element.value?.setCustomValidity(
|
||||
behavior.value === "native" && !disabled.value && !readOnly.value
|
||||
? [
|
||||
...(props.validationErrors ?? []),
|
||||
...serverErrors.value,
|
||||
...customErrors.value,
|
||||
constraintError.value,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")
|
||||
: "",
|
||||
);
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
if (!hasModel()) local.value = initial;
|
||||
touched.value = false;
|
||||
nativeError.value = "";
|
||||
dismissed.value = formContext?.validationErrors.value;
|
||||
// Native reset changes DOM input.defaultValue independently of controlled props.
|
||||
element.value?.dispatchEvent(new Event("hv-number-field-reset"));
|
||||
});
|
||||
}
|
||||
let form: HTMLFormElement | null = null;
|
||||
function bindForm() {
|
||||
const next = element.value?.form ?? null;
|
||||
if (next === form) return;
|
||||
form?.removeEventListener("reset", reset);
|
||||
form = next;
|
||||
form?.addEventListener("reset", reset);
|
||||
}
|
||||
onMounted(bindForm);
|
||||
onUpdated(bindForm);
|
||||
onBeforeUnmount(() => form?.removeEventListener("reset", reset));
|
||||
expose({ element, focus: () => element.value?.focus() });
|
||||
function prepare(
|
||||
nodes: VNodeChild[],
|
||||
descriptions: string[],
|
||||
errors: string[],
|
||||
found: { id?: string },
|
||||
path = "",
|
||||
): VNodeChild[] {
|
||||
return (Array.isArray(nodes) ? nodes : [nodes]).map((node, index) => {
|
||||
if (!isVNode(node)) return node;
|
||||
const name =
|
||||
(node.type as { name?: string; __name?: string }).name ??
|
||||
(node.type as { __name?: string }).__name;
|
||||
const position = `${path}-${index}`;
|
||||
if (name === "NumberFieldInput") found.id = node.props?.id;
|
||||
if (name === "Description" || name === "FieldError") {
|
||||
const id = node.props?.id ?? `${generated}-${name}${position}`;
|
||||
(name === "Description" ? descriptions : errors).push(String(id));
|
||||
return cloneVNode(node, { id });
|
||||
}
|
||||
if (
|
||||
name === "NumberFieldGroup" &&
|
||||
node.children &&
|
||||
typeof node.children === "object"
|
||||
) {
|
||||
const children = node.children as { default?: () => VNodeChild[] };
|
||||
if (children.default) {
|
||||
const prepared = prepare(
|
||||
children.default(),
|
||||
descriptions,
|
||||
errors,
|
||||
found,
|
||||
position,
|
||||
);
|
||||
const clone = cloneVNode(node);
|
||||
clone.children = { ...children, default: () => prepared };
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
if (
|
||||
(typeof node.type === "string" || node.type === Fragment) &&
|
||||
Array.isArray(node.children)
|
||||
) {
|
||||
const clone = cloneVNode(node);
|
||||
clone.children = prepare(
|
||||
node.children as VNodeChild[],
|
||||
descriptions,
|
||||
errors,
|
||||
found,
|
||||
position,
|
||||
) as VNode[];
|
||||
return clone;
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
const state = {
|
||||
isDisabled: disabled.value,
|
||||
isReadOnly: readOnly.value,
|
||||
isRequired: required.value,
|
||||
isInvalid: invalid.value,
|
||||
isFocused: focused.value,
|
||||
isFocusWithin: focused.value,
|
||||
isFocusVisible: focusVisible.value,
|
||||
value: value.value,
|
||||
minValue: props.minValue,
|
||||
maxValue: props.maxValue,
|
||||
step: props.step,
|
||||
validationErrors: errors.value,
|
||||
};
|
||||
const descriptions: string[] = [],
|
||||
errorsPlan: string[] = [],
|
||||
found: { id?: string } = {};
|
||||
const children = prepare(
|
||||
slots.default?.(state) ?? [],
|
||||
descriptions,
|
||||
errorsPlan,
|
||||
found,
|
||||
);
|
||||
if (leafId.value !== found.id) leafId.value = found.id;
|
||||
if (
|
||||
JSON.stringify(plannedDescriptions.value) !==
|
||||
JSON.stringify(descriptions)
|
||||
)
|
||||
plannedDescriptions.value = descriptions;
|
||||
if (JSON.stringify(plannedErrors.value) !== JSON.stringify(errorsPlan))
|
||||
plannedErrors.value = errorsPlan;
|
||||
return h(
|
||||
NumberFieldRoot,
|
||||
mergeProps(
|
||||
Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
|
||||
),
|
||||
{
|
||||
as: props.as,
|
||||
modelValue: value.value,
|
||||
min: props.minValue,
|
||||
max: props.maxValue,
|
||||
step: props.step,
|
||||
locale: props.locale ?? config?.locale.value ?? "en-US",
|
||||
formatOptions: props.formatOptions,
|
||||
disabled: disabled.value,
|
||||
readonly: readOnly.value,
|
||||
id: controlId.value,
|
||||
disableWheelChange: props.isWheelDisabled,
|
||||
"onUpdate:modelValue": update,
|
||||
class: styles.value.base(),
|
||||
"data-slot": "number-field",
|
||||
"data-invalid": invalid.value || undefined,
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-required": required.value || undefined,
|
||||
"data-readonly": readOnly.value || undefined,
|
||||
"data-focus-within": focused.value || undefined,
|
||||
"data-focus-visible": focusVisible.value || undefined,
|
||||
},
|
||||
),
|
||||
{
|
||||
default: () => [
|
||||
...children,
|
||||
props.name
|
||||
? h("input", {
|
||||
type: "hidden",
|
||||
name: props.name,
|
||||
form: props.form,
|
||||
disabled: disabled.value,
|
||||
value: value.value ?? "",
|
||||
"data-slot": "number-field-value",
|
||||
})
|
||||
: null,
|
||||
],
|
||||
},
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
Reference in New Issue
Block a user