-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathuseInternalContext.ts
58 lines (49 loc) · 1.39 KB
/
useInternalContext.ts
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import {
ComputedRef,
getCurrentInstance,
inject,
InjectionKey,
WritableComputedRef,
} from 'vue';
import {
FieldArrayValidator,
FieldAttrs,
FormErrors,
FormTouched,
FormValues,
MaybeRef,
SetFieldArrayValue,
UseFormRegister,
UseFormSetFieldValue,
} from '../types';
function injectMaybeSelf<T>(
key: InjectionKey<T>,
defaultValue: T | undefined = undefined,
): T | undefined {
const vm = getCurrentInstance() as any;
return vm?.provides[key as any] || inject(key, defaultValue);
}
export interface InternalContextValues {
registerFieldArray: (
name: MaybeRef<string>,
options: {
validate?: FieldArrayValidator<any>;
reset: () => void;
},
) => void;
getFieldValue: <Value>(name: MaybeRef<string>) => WritableComputedRef<Value>;
setFieldValue: UseFormSetFieldValue<FormValues>;
getFieldError: (name: string) => FormErrors<any>;
getFieldTouched: (name: string) => FormTouched<boolean>;
getFieldDirty: (name: string) => boolean;
getFieldAttrs: (name: MaybeRef<string>) => ComputedRef<FieldAttrs>;
setFieldArrayValue: SetFieldArrayValue;
register: UseFormRegister<FormValues>;
}
export const InternalContextKey: InjectionKey<InternalContextValues> = Symbol(
__DEV__ ? 'vorms internal context' : '',
);
export function useInternalContext() {
const context = injectMaybeSelf(InternalContextKey) as InternalContextValues;
return context;
}