feat: add form field autofocus configuration (#4550)

* feat: add form field autofocus configuration
pull/48/MERGE
Squall2017 2024-10-03 13:10:21 +08:00 committed by GitHub
parent aed31a5a4e
commit 64428b9b11
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 24 additions and 1 deletions

View File

@ -3,7 +3,7 @@ import type { ZodType } from 'zod';
import type { FormSchema, MaybeComponentProps } from '../types';
import { computed } from 'vue';
import { computed, nextTick, ref, watch } from 'vue';
import {
FormControl,
@ -52,6 +52,16 @@ const errors = useFieldError(fieldName);
const formApi = formRenderProps.form;
const isInValid = computed(() => errors.value?.length > 0);
const fieldComponentRef = ref<HTMLInputElement | null>(null);
const focus = () => {
if (
fieldComponentRef.value &&
typeof fieldComponentRef.value.focus === 'function' &&
document.activeElement !== fieldComponentRef.value //
) {
fieldComponentRef.value.focus();
}
};
const fieldComponent = computed(() => {
const finalComponent = isString(component)
@ -156,6 +166,18 @@ const computedProps = computed(() => {
};
});
watch(
() => computedProps.value?.autofocus,
(value) => {
if (value === true) {
nextTick(() => {
focus();
});
}
},
{ immediate: true },
);
const shouldDisabled = computed(() => {
return isDisabled.value || disabled || computedProps.value?.disabled;
});
@ -275,6 +297,7 @@ function createComponentProps(slotProps: Record<string, any>) {
>
<component
:is="fieldComponent"
ref="fieldComponentRef"
:class="{
'border-destructive focus:border-destructive hover:border-destructive/80 focus:shadow-[0_0_0_2px_rgba(255,38,5,0.06)]':
isInValid,