feat: establish shared field and form foundation
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { useAttrs } from "vue";
|
||||
import { useFieldPart } from "./useFieldPart";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const attrs = useAttrs();
|
||||
const { field, id } = useFieldPart("error", attrs);
|
||||
</script>
|
||||
<template>
|
||||
<p
|
||||
v-if="!field || field.invalid.value"
|
||||
v-bind="attrs"
|
||||
:id="id"
|
||||
data-slot="field-error"
|
||||
data-visible
|
||||
class="hv-field-error"
|
||||
role="alert"
|
||||
>
|
||||
<slot
|
||||
:validation-errors="field?.errors.value ?? []"
|
||||
:is-invalid="field?.invalid.value ?? false"
|
||||
>
|
||||
{{ field?.errors.value.join(" ") }}
|
||||
</slot>
|
||||
</p>
|
||||
</template>
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ComputedRef, InjectionKey, Ref } from "vue";
|
||||
|
||||
export type ValidationBehavior = "native" | "aria";
|
||||
export type ValidationErrors = Record<string, string | string[]>;
|
||||
export type ValidateResult = string | string[] | true | null | undefined;
|
||||
export type FieldPart = "description" | "error";
|
||||
export interface FieldContext {
|
||||
controlId: ComputedRef<string>;
|
||||
kind: "text" | "toggle";
|
||||
disabled: ComputedRef<boolean>;
|
||||
readOnly: ComputedRef<boolean>;
|
||||
required: ComputedRef<boolean>;
|
||||
invalid: ComputedRef<boolean>;
|
||||
errors: ComputedRef<string[]>;
|
||||
descriptionIds: Ref<string[]>;
|
||||
errorIds: Ref<string[]>;
|
||||
}
|
||||
export const fieldContextKey: InjectionKey<FieldContext> =
|
||||
Symbol("HeroUIVue.Field");
|
||||
export interface FormContext {
|
||||
validationBehavior: ComputedRef<ValidationBehavior>;
|
||||
validationErrors: ComputedRef<ValidationErrors>;
|
||||
}
|
||||
export const formContextKey: InjectionKey<FormContext> =
|
||||
Symbol("HeroUIVue.Form");
|
||||
|
||||
export function mergeIds(...values: (string | string[] | undefined)[]) {
|
||||
const ids = values
|
||||
.flatMap((value) =>
|
||||
typeof value === "string" ? value.split(/\s+/) : (value ?? []),
|
||||
)
|
||||
.filter(Boolean);
|
||||
return [...new Set(ids)].join(" ") || undefined;
|
||||
}
|
||||
export function errorMessages(result: ValidateResult | false): string[] {
|
||||
return (
|
||||
typeof result === "string" ? [result] : Array.isArray(result) ? result : []
|
||||
).filter(Boolean);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { computed, inject, onBeforeUnmount, useId, watch } from "vue";
|
||||
import { fieldContextKey, type FieldPart } from "./context";
|
||||
|
||||
/** IDs stay reactive when a caller replaces an explicit id; registration is instance-owned. */
|
||||
export function useFieldPart(part: FieldPart, attrs: Record<string, unknown>) {
|
||||
const field = inject(fieldContextKey, undefined);
|
||||
const generated = useId();
|
||||
const id = computed(() =>
|
||||
typeof attrs.id === "string" ? attrs.id : generated,
|
||||
);
|
||||
const ids = part === "description" ? field?.descriptionIds : field?.errorIds;
|
||||
const stop = watch(
|
||||
id,
|
||||
(current, _, cleanup) => {
|
||||
if (!ids) return;
|
||||
if (!ids.value.includes(current)) ids.value = [...ids.value, current];
|
||||
cleanup(() => {
|
||||
ids.value = ids.value.filter((value) => value !== current);
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
onBeforeUnmount(stop);
|
||||
return { field, id };
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
computed,
|
||||
inject,
|
||||
nextTick,
|
||||
onBeforeUnmount,
|
||||
onMounted,
|
||||
onUpdated,
|
||||
ref,
|
||||
watch,
|
||||
} from "vue";
|
||||
import { mergeIds, formContextKey } from "./context";
|
||||
import { textFieldContextKey } from "../textfield/context";
|
||||
|
||||
interface TextControlProps {
|
||||
modelValue?: string;
|
||||
defaultValue?: string;
|
||||
invalid?: boolean;
|
||||
variant?: "primary" | "secondary";
|
||||
fullWidth?: boolean;
|
||||
type?: string;
|
||||
}
|
||||
export function useTextControl(
|
||||
props: TextControlProps,
|
||||
attrs: Record<string, unknown>,
|
||||
emit: (event: "update:modelValue", value: string) => void,
|
||||
) {
|
||||
const field = inject(textFieldContextKey, undefined);
|
||||
const formContext = inject(formContextKey, undefined);
|
||||
const behavior = () =>
|
||||
field?.validationBehavior.value ?? formContext?.validationBehavior.value;
|
||||
const element = ref<HTMLInputElement | HTMLTextAreaElement>();
|
||||
const initial = props.defaultValue ?? "";
|
||||
const internal = ref(initial);
|
||||
field?.initialize(props.modelValue ?? initial);
|
||||
watch(
|
||||
() => (typeof attrs.id === "string" ? attrs.id : undefined),
|
||||
(id) => field?.setControlId(id),
|
||||
{ immediate: true },
|
||||
);
|
||||
const value = computed(
|
||||
() => props.modelValue ?? field?.value.value ?? internal.value,
|
||||
);
|
||||
const attrBoolean = (value: unknown) => value != null && value !== false;
|
||||
const disabled = () =>
|
||||
attrBoolean(attrs.disabled) || Boolean(field?.disabled.value);
|
||||
const readOnly = () =>
|
||||
attrBoolean(attrs.readonly ?? attrs.readOnly) ||
|
||||
Boolean(field?.readOnly.value);
|
||||
const required = () =>
|
||||
behavior() !== "aria" &&
|
||||
!readOnly() &&
|
||||
(attrBoolean(attrs.required) || Boolean(field?.required.value));
|
||||
const invalid = () =>
|
||||
Boolean(
|
||||
props.invalid ||
|
||||
field?.invalid.value ||
|
||||
attrs["aria-invalid"] === true ||
|
||||
attrs["aria-invalid"] === "true",
|
||||
);
|
||||
const variant = computed(() => props.variant ?? field?.variant.value);
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(next) => {
|
||||
if (next !== undefined) field?.syncValue(next);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
watch(element, (next) => field?.setControl(next), { flush: "post" });
|
||||
function update(event: Event) {
|
||||
const next = (event.target as HTMLInputElement).value;
|
||||
if (!disabled() && !readOnly()) {
|
||||
internal.value = next;
|
||||
field?.setValue(next);
|
||||
emit("update:modelValue", next);
|
||||
}
|
||||
void nextTick(() => {
|
||||
if (element.value) {
|
||||
element.value.value = value.value;
|
||||
if (props.modelValue !== undefined) field?.syncValue(value.value);
|
||||
}
|
||||
});
|
||||
}
|
||||
function reset(event: Event) {
|
||||
void nextTick(() => {
|
||||
if (event.defaultPrevented) return;
|
||||
internal.value = initial;
|
||||
field?.onReset();
|
||||
if (props.modelValue !== undefined) field?.syncValue(props.modelValue);
|
||||
if (element.value) element.value.value = value.value;
|
||||
});
|
||||
}
|
||||
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);
|
||||
field?.setControl(undefined);
|
||||
});
|
||||
return {
|
||||
inheritedAttrs: () => field?.controlAttrs() ?? {},
|
||||
element,
|
||||
value,
|
||||
update,
|
||||
variant,
|
||||
invalid,
|
||||
disabled,
|
||||
readOnly,
|
||||
required,
|
||||
id: () =>
|
||||
typeof attrs.id === "string" ? attrs.id : field?.controlId.value,
|
||||
name: () =>
|
||||
typeof attrs.name === "string" ? attrs.name : field?.name.value,
|
||||
type: () => props.type ?? field?.type.value ?? "text",
|
||||
describedBy: () =>
|
||||
mergeIds(
|
||||
attrs["aria-describedby"] as string | undefined,
|
||||
field?.describedBy(),
|
||||
),
|
||||
onInvalid: (event: Event) => field?.onInvalid(event),
|
||||
validationBehavior: behavior,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user