feat: add Fieldset and SearchField infrastructure
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
import { computed, inject, type ComputedRef, type InjectionKey } from "vue";
|
||||
|
||||
/** Semantic disabled scope, including controls with no native disabled attribute. */
|
||||
export const disabledContextKey: InjectionKey<ComputedRef<boolean>> =
|
||||
Symbol("HeroUIVue.Disabled");
|
||||
export function useInheritedDisabled(local: () => unknown = () => false) {
|
||||
const parent = inject(disabledContextKey, undefined);
|
||||
return computed(() => Boolean(local() || parent?.value));
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
ref,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { useInheritedDisabled } from "./disabled";
|
||||
import { mergeIds, formContextKey } from "./context";
|
||||
import { textFieldContextKey } from "../textfield/context";
|
||||
|
||||
@@ -41,8 +42,11 @@ export function useTextControl(
|
||||
() => props.modelValue ?? field?.value.value ?? internal.value,
|
||||
);
|
||||
const attrBoolean = (value: unknown) => value != null && value !== false;
|
||||
const inheritedDisabled = useInheritedDisabled();
|
||||
const disabled = () =>
|
||||
attrBoolean(attrs.disabled) || Boolean(field?.disabled.value);
|
||||
inheritedDisabled.value ||
|
||||
attrBoolean(attrs.disabled) ||
|
||||
Boolean(field?.disabled.value);
|
||||
const readOnly = () =>
|
||||
attrBoolean(attrs.readonly ?? attrs.readOnly) ||
|
||||
Boolean(field?.readOnly.value);
|
||||
@@ -97,7 +101,10 @@ export function useTextControl(
|
||||
form = next;
|
||||
form?.addEventListener("reset", reset);
|
||||
}
|
||||
onMounted(bindForm);
|
||||
onMounted(() => {
|
||||
field?.setControl(element.value);
|
||||
bindForm();
|
||||
});
|
||||
onUpdated(bindForm);
|
||||
onBeforeUnmount(() => {
|
||||
form?.removeEventListener("reset", reset);
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
import {
|
||||
Comment,
|
||||
Fragment,
|
||||
cloneVNode,
|
||||
computed,
|
||||
h,
|
||||
mergeProps,
|
||||
inject,
|
||||
isVNode,
|
||||
provide,
|
||||
ref,
|
||||
shallowRef,
|
||||
useId,
|
||||
watchEffect,
|
||||
type PropType,
|
||||
type ExtractPropTypes,
|
||||
type Slots,
|
||||
type VNode,
|
||||
type VNodeChild,
|
||||
} from "vue";
|
||||
import {
|
||||
fieldContextKey,
|
||||
formContextKey,
|
||||
errorMessages,
|
||||
mergeIds,
|
||||
type ValidateResult,
|
||||
type ValidationBehavior,
|
||||
} from "./context";
|
||||
import {
|
||||
textFieldContextKey,
|
||||
type TextFieldContext,
|
||||
} from "../textfield/context";
|
||||
|
||||
import { useInheritedDisabled } from "./disabled";
|
||||
|
||||
export const textFieldProps = {
|
||||
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>,
|
||||
} as const;
|
||||
|
||||
export function useTextField(
|
||||
props: Readonly<ExtractPropTypes<typeof textFieldProps>>,
|
||||
{
|
||||
attrs,
|
||||
slots,
|
||||
emit,
|
||||
expose,
|
||||
}: {
|
||||
attrs: Record<string, unknown>;
|
||||
slots: Slots;
|
||||
emit: (event: "update:modelValue", value: string) => void;
|
||||
expose: (exposed: Record<string, unknown>) => void;
|
||||
},
|
||||
options: {
|
||||
rootSlot?: string;
|
||||
rootClass?: () => unknown;
|
||||
rootAttrs?: () => Record<string, unknown>;
|
||||
slotState?: () => Record<string, unknown>;
|
||||
} = {},
|
||||
) {
|
||||
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 = useInheritedDisabled(() => props.isDisabled);
|
||||
const 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;
|
||||
controlValue?: string;
|
||||
hasControl?: boolean;
|
||||
},
|
||||
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" ||
|
||||
name === "InputGroupInput" ||
|
||||
name === "InputGroupTextArea" ||
|
||||
name === "SearchFieldInput"
|
||||
) {
|
||||
found.hasControl = true;
|
||||
found.controlId = node.props?.id;
|
||||
found.controlValue = node.props?.modelValue ?? node.props?.defaultValue;
|
||||
}
|
||||
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 });
|
||||
}
|
||||
// InputGroup is a library-owned transparent field wrapper. Prepare its
|
||||
// default slot once, preserving the current render's values and keys.
|
||||
// Arbitrary consumer components remain opaque to SSR planning.
|
||||
if (
|
||||
(name === "InputGroup" || name === "SearchFieldGroup") &&
|
||||
node.children &&
|
||||
typeof node.children === "object"
|
||||
) {
|
||||
const groupSlots = node.children as { default?: () => VNodeChild[] };
|
||||
if (typeof groupSlots.default === "function") {
|
||||
const prepared = prepare(groupSlots.default(), found, position);
|
||||
const clone = cloneVNode(node);
|
||||
clone.children = { ...groupSlots, 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[],
|
||||
found,
|
||||
position,
|
||||
) as VNode[];
|
||||
return clone;
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
const render = () => {
|
||||
const found: {
|
||||
description: string[];
|
||||
error: string[];
|
||||
controlId?: string;
|
||||
controlValue?: string;
|
||||
hasControl?: boolean;
|
||||
} = { description: [], error: [] };
|
||||
const children = prepare(
|
||||
slots.default?.({
|
||||
isDisabled: disabled.value,
|
||||
isReadOnly: readOnly.value,
|
||||
isRequired: required.value,
|
||||
isInvalid: invalid.value,
|
||||
validationErrors: errors.value,
|
||||
...options.slotState?.(),
|
||||
}) ?? [],
|
||||
found,
|
||||
);
|
||||
if (found.hasControl && leafId.value !== found.controlId)
|
||||
leafId.value = found.controlId;
|
||||
if (found.controlValue !== undefined) initialize(found.controlValue);
|
||||
const nextPlan = JSON.stringify(found);
|
||||
if (lastPlan !== nextPlan) {
|
||||
lastPlan = nextPlan;
|
||||
plannedDescriptions.value = found.description;
|
||||
plannedErrors.value = found.error;
|
||||
}
|
||||
return h(
|
||||
"div",
|
||||
mergeProps(
|
||||
{
|
||||
...Object.fromEntries(
|
||||
Object.entries(attrs).filter(([key]) => !key.startsWith("aria-")),
|
||||
),
|
||||
class: [
|
||||
options.rootClass?.() ?? [
|
||||
"hv-textfield",
|
||||
props.fullWidth && "hv-textfield--full-width",
|
||||
],
|
||||
attrs.class,
|
||||
],
|
||||
"data-slot": options.rootSlot ?? "textfield",
|
||||
"data-invalid": invalid.value || undefined,
|
||||
"data-disabled": disabled.value || undefined,
|
||||
"data-required": required.value || undefined,
|
||||
"data-readonly": readOnly.value || undefined,
|
||||
},
|
||||
options.rootAttrs?.() ?? {},
|
||||
),
|
||||
children,
|
||||
);
|
||||
};
|
||||
return { field, element: control, render };
|
||||
}
|
||||
Reference in New Issue
Block a user