feat: establish shared field and form foundation
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, provide, ref, useAttrs } from "vue";
|
||||
import {
|
||||
formContextKey,
|
||||
type ValidationBehavior,
|
||||
type ValidationErrors,
|
||||
} from "../field/context";
|
||||
defineOptions({ inheritAttrs: false });
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
validationBehavior?: ValidationBehavior;
|
||||
validationErrors?: ValidationErrors;
|
||||
}>(),
|
||||
{ validationBehavior: "native", validationErrors: () => ({}) },
|
||||
);
|
||||
const attrs = useAttrs();
|
||||
provide(formContextKey, {
|
||||
validationBehavior: computed(() => props.validationBehavior),
|
||||
validationErrors: computed(() => props.validationErrors),
|
||||
});
|
||||
const element = ref<HTMLFormElement>();
|
||||
function checkValidity(report = false) {
|
||||
let first:
|
||||
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement | undefined;
|
||||
for (const control of Array.from(element.value?.elements ?? [])) {
|
||||
if (
|
||||
!("checkValidity" in control) ||
|
||||
(control.getAttribute("data-validation-behavior") ??
|
||||
props.validationBehavior) === "aria"
|
||||
)
|
||||
continue;
|
||||
const field = control as
|
||||
HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
||||
if (!field.checkValidity() && !first) first = field;
|
||||
}
|
||||
if (report && first) {
|
||||
first.focus();
|
||||
first.reportValidity();
|
||||
}
|
||||
return !first;
|
||||
}
|
||||
function submit(event: Event) {
|
||||
const submitter = (event as SubmitEvent).submitter as
|
||||
HTMLButtonElement | HTMLInputElement | null;
|
||||
const skip =
|
||||
attrs.novalidate === "" ||
|
||||
attrs.novalidate === true ||
|
||||
attrs.noValidate === true;
|
||||
if (!skip && !submitter?.formNoValidate && !checkValidity(true)) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
}
|
||||
}
|
||||
// Native auto-validation is disabled so per-field aria/native modes can coexist.
|
||||
// The submit guard still uses each native control's Constraint Validation API.
|
||||
defineExpose({
|
||||
element,
|
||||
checkValidity: () => checkValidity(),
|
||||
reportValidity: () => checkValidity(true),
|
||||
reset: () => element.value?.reset(),
|
||||
});
|
||||
</script>
|
||||
<template>
|
||||
<form ref="element" @submit.capture="submit" v-bind="attrs" novalidate>
|
||||
<slot />
|
||||
</form>
|
||||
</template>
|
||||
Reference in New Issue
Block a user