Ben Lin
2024-10-22 78999ce1626d2a786f3a705281eeba79c2f1d6dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import type { ComputedRef, Ref } from 'vue';
import {
  type FormSchemaInner as FormSchema,
  type FormActionType,
  type FormProps,
} from '../types/form';
 
import { unref, nextTick, watchEffect } from 'vue';
 
interface UseAutoFocusContext {
  getSchema: ComputedRef<FormSchema[]>;
  getProps: ComputedRef<FormProps>;
  isInitedDefault: Ref<boolean>;
  formElRef: Ref<FormActionType>;
}
export async function useAutoFocus({
  getSchema,
  getProps,
  formElRef,
  isInitedDefault,
}: UseAutoFocusContext) {
  watchEffect(async () => {
    if (unref(isInitedDefault) || !unref(getProps).autoFocusFirstItem) {
      return;
    }
    await nextTick();
    const schemas = unref(getSchema);
    const formEl = unref(formElRef);
    const el = (formEl as any)?.$el as HTMLElement;
    if (!formEl || !el || !schemas || schemas.length === 0) {
      return;
    }
 
    const firstItem = schemas[0];
    // Only open when the first form item is input type
    if (!firstItem.component || !firstItem.component.includes('Input')) {
      return;
    }
 
    const inputEl = el.querySelector('.ant-row:first-child input') as Nullable<HTMLInputElement>;
    if (!inputEl) return;
    inputEl?.focus();
  });
}