feat: establish shared field and form foundation
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
Comment,
|
||||
Fragment,
|
||||
cloneVNode,
|
||||
computed,
|
||||
defineComponent,
|
||||
h,
|
||||
inject,
|
||||
isVNode,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
useId,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import {
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
errorMessages,
|
||||
mergeIds,
|
||||
type ValidateResult,
|
||||
type ValidationBehavior,
|
||||
} from "../field/context";
|
||||
import { textFieldContextKey, type TextFieldContext } from "./context";
|
||||
|
||||
export default defineComponent({
|
||||
name: "TextField",
|
||||
inheritAttrs: false,
|
||||
props: {
|
||||
modelValue: String,
|
||||
defaultValue: String,
|
||||
name: String,
|
||||
id: String,
|
||||
type: String,
|
||||
minLength: Number,
|
||||
maxLength: Number,
|
||||
pattern: String,
|
||||
autoComplete: String,
|
||||
inputMode: String,
|
||||
form: String,
|
||||
isDisabled: Boolean,
|
||||
isReadOnly: Boolean,
|
||||
isRequired: Boolean,
|
||||
isInvalid: Boolean,
|
||||
fullWidth: Boolean,
|
||||
variant: String as PropType<"primary" | "secondary">,
|
||||
validationBehavior: String as PropType<ValidationBehavior>,
|
||||
validate: Function as PropType<(value: string) => ValidateResult>,
|
||||
},
|
||||
emits: { "update:modelValue": (_value: string) => true },
|
||||
setup(props, { attrs, slots, emit, expose }) {
|
||||
const form = inject(formContextKey, undefined);
|
||||
const generated = useId();
|
||||
const leafId = ref<string>();
|
||||
const controlId = computed(() => leafId.value ?? props.id ?? generated);
|
||||
const internal = ref(props.defaultValue ?? "");
|
||||
let initialized =
|
||||
props.modelValue !== undefined || props.defaultValue !== undefined;
|
||||
let initialValue = props.defaultValue ?? "";
|
||||
const value = computed(() => props.modelValue ?? internal.value);
|
||||
const control = shallowRef<HTMLInputElement | HTMLTextAreaElement>();
|
||||
const touched = ref(false),
|
||||
nativeError = ref("");
|
||||
const dismissed = shallowRef<object>();
|
||||
const descriptionIds = ref<string[]>([]),
|
||||
errorIds = ref<string[]>([]);
|
||||
// Pre-plan direct/native-wrapped parts before rendering controls, so SSR has
|
||||
// complete ID associations even when Description follows Input.
|
||||
const plannedDescriptions = ref<string[]>([]),
|
||||
plannedErrors = ref<string[]>([]);
|
||||
let lastPlan = "";
|
||||
const behavior = computed(
|
||||
() =>
|
||||
props.validationBehavior ?? form?.validationBehavior.value ?? "native",
|
||||
);
|
||||
const disabled = computed(() => props.isDisabled),
|
||||
readOnly = computed(() => props.isReadOnly);
|
||||
const required = computed(() => props.isRequired);
|
||||
const serverErrors = computed(() => {
|
||||
const source = form?.validationErrors.value;
|
||||
return source && source !== dismissed.value && props.name
|
||||
? errorMessages(source[props.name])
|
||||
: [];
|
||||
});
|
||||
const customErrors = computed(() =>
|
||||
errorMessages(props.validate?.(value.value)),
|
||||
);
|
||||
const errors = computed(() => [
|
||||
...serverErrors.value,
|
||||
...(touched.value || behavior.value === "aria" ? customErrors.value : []),
|
||||
...((touched.value || behavior.value === "aria") && nativeError.value
|
||||
? [nativeError.value]
|
||||
: []),
|
||||
]);
|
||||
const invalid = computed(
|
||||
() =>
|
||||
props.isInvalid ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true" ||
|
||||
errors.value.length > 0,
|
||||
);
|
||||
function setValue(next: string) {
|
||||
if (disabled.value || readOnly.value) return;
|
||||
internal.value = next;
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
nativeError.value = "";
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
function initialize(next: string) {
|
||||
if (!initialized) {
|
||||
internal.value = next;
|
||||
initialValue = next;
|
||||
initialized = true;
|
||||
}
|
||||
}
|
||||
const field: TextFieldContext = {
|
||||
controlId,
|
||||
kind: "text",
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
invalid,
|
||||
errors,
|
||||
descriptionIds,
|
||||
errorIds,
|
||||
value,
|
||||
name: computed(() => props.name),
|
||||
type: computed(() => props.type),
|
||||
variant: computed(() => props.variant),
|
||||
validationBehavior: behavior,
|
||||
controlAttrs: () => ({
|
||||
minlength: props.minLength,
|
||||
maxlength: props.maxLength,
|
||||
pattern: props.pattern,
|
||||
autocomplete: props.autoComplete,
|
||||
inputmode: props.inputMode,
|
||||
form: props.form,
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => key.startsWith("aria-")),
|
||||
),
|
||||
}),
|
||||
describedBy: () =>
|
||||
mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
descriptionIds.value,
|
||||
plannedDescriptions.value,
|
||||
invalid.value ? [...errorIds.value, ...plannedErrors.value] : [],
|
||||
),
|
||||
setControlId: (id) => {
|
||||
leafId.value = id;
|
||||
},
|
||||
initialize,
|
||||
setValue,
|
||||
syncValue: (next) => {
|
||||
internal.value = next;
|
||||
},
|
||||
setControl: (next) => {
|
||||
control.value = next;
|
||||
},
|
||||
onInvalid(event) {
|
||||
if (behavior.value === "aria") return;
|
||||
touched.value = true;
|
||||
const element = event.target as HTMLInputElement | HTMLTextAreaElement;
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
? ""
|
||||
: element.validationMessage;
|
||||
},
|
||||
onReset() {
|
||||
internal.value = initialValue;
|
||||
touched.value = false;
|
||||
nativeError.value = "";
|
||||
dismissed.value = form?.validationErrors.value;
|
||||
},
|
||||
};
|
||||
provide(fieldContextKey, field);
|
||||
provide(textFieldContextKey, field);
|
||||
watchEffect(
|
||||
() => {
|
||||
const currentValue = value.value;
|
||||
control.value?.setCustomValidity(
|
||||
behavior.value === "native" && !disabled.value && !readOnly.value
|
||||
? [...serverErrors.value, ...customErrors.value].join(" ")
|
||||
: "",
|
||||
);
|
||||
if (behavior.value === "native" && touched.value)
|
||||
nativeError.value =
|
||||
customErrors.value.length || serverErrors.value.length
|
||||
? ""
|
||||
: (control.value?.validationMessage ?? "");
|
||||
if (behavior.value === "aria")
|
||||
nativeError.value =
|
||||
disabled.value || readOnly.value
|
||||
? ""
|
||||
: required.value && !currentValue
|
||||
? "请填写此字段。"
|
||||
: (control.value?.validationMessage ?? "");
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
expose({ focus: () => control.value?.focus(), element: control });
|
||||
function prepare(
|
||||
nodes: VNodeChild[],
|
||||
found: { description: string[]; error: string[]; controlId?: string },
|
||||
path = "",
|
||||
): VNodeChild[] {
|
||||
return 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 };
|
||||
const name = type?.name ?? type?.__name;
|
||||
if (name === "Input" || name === "TextArea")
|
||||
found.controlId = node.props?.id;
|
||||
if (name === "Description" || name === "FieldError") {
|
||||
const kind = name === "Description" ? "description" : "error";
|
||||
const id = node.props?.id ?? `${generated}-${kind}${position}`;
|
||||
found[kind].push(String(id));
|
||||
return cloneVNode(node, { id });
|
||||
}
|
||||
if (
|
||||
(typeof node.type === "string" || node.type === Fragment) &&
|
||||
Array.isArray(node.children)
|
||||
) {
|
||||
const clone = cloneVNode(node);
|
||||
clone.children = prepare(
|
||||
node.children as VNodeChild[],
|
||||
found,
|
||||
position,
|
||||
) as VNode[];
|
||||
return clone;
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
const found: {
|
||||
description: string[];
|
||||
error: string[];
|
||||
controlId?: string;
|
||||
} = { description: [], error: [] };
|
||||
const children = prepare(
|
||||
slots.default?.({
|
||||
isDisabled: disabled.value,
|
||||
isReadOnly: readOnly.value,
|
||||
isRequired: required.value,
|
||||
isInvalid: invalid.value,
|
||||
validationErrors: errors.value,
|
||||
}) ?? [],
|
||||
found,
|
||||
);
|
||||
if (found.controlId !== undefined && leafId.value !== found.controlId)
|
||||
leafId.value = found.controlId;
|
||||
const nextPlan = JSON.stringify(found);
|
||||
if (lastPlan !== nextPlan) {
|
||||
lastPlan = nextPlan;
|
||||
plannedDescriptions.value = found.description;
|
||||
plannedErrors.value = found.error;
|
||||
}
|
||||
return h(
|
||||
"div",
|
||||
{
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
|
||||
),
|
||||
class: [
|
||||
"hv-textfield",
|
||||
props.fullWidth && "hv-textfield--full-width",
|
||||
attrs.class,
|
||||
],
|
||||
"data-slot": "textfield",
|
||||
"data-invalid": invalid.value || undefined,
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-required": required.value || undefined,
|
||||
"data-readonly": readOnly.value || undefined,
|
||||
},
|
||||
children,
|
||||
);
|
||||
};
|
||||
},
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ComputedRef, InjectionKey } from "vue";
|
||||
import type { FieldContext, ValidationBehavior } from "../field/context";
|
||||
export interface TextFieldContext extends FieldContext {
|
||||
value: ComputedRef<string>;
|
||||
name: ComputedRef<string | undefined>;
|
||||
type: ComputedRef<string | undefined>;
|
||||
variant: ComputedRef<"primary" | "secondary" | undefined>;
|
||||
validationBehavior: ComputedRef<ValidationBehavior>;
|
||||
controlAttrs: () => Record<string, unknown>;
|
||||
describedBy: () => string | undefined;
|
||||
setControlId: (id: string | undefined) => void;
|
||||
initialize: (value: string) => void;
|
||||
setValue: (value: string) => void;
|
||||
syncValue: (value: string) => void;
|
||||
setControl: (
|
||||
control: HTMLInputElement | HTMLTextAreaElement | undefined,
|
||||
) => void;
|
||||
onInvalid: (event: Event) => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
export const textFieldContextKey: InjectionKey<TextFieldContext> = Symbol(
|
||||
"HeroUIVue.TextField",
|
||||
);
|
||||
Reference in New Issue
Block a user