-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
useFieldState.ts
205 lines (174 loc) · 5.3 KB
/
useFieldState.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { computed, reactive, ref, Ref, unref, watch } from 'vue';
import { FormContextKey } from './symbols';
import { FieldMeta, FieldState, MaybeRef } from './types';
import { getFromPath, injectWithSelf, isEqual } from './utils';
export interface StateSetterInit<TValue = unknown> extends FieldState<TValue> {
initialValue: TValue;
}
export interface FieldStateComposable<TValue = unknown> {
id: number;
path: MaybeRef<string>;
meta: FieldMeta<TValue>;
value: Ref<TValue>;
initialValue: Ref<TValue>;
errorMessage: Ref<string | undefined>;
errors: Ref<string[]>;
setState(state: Partial<StateSetterInit<TValue>>): void;
}
export interface StateInit<TValue = unknown> {
modelValue: MaybeRef<TValue>;
standalone: boolean;
}
let ID_COUNTER = 0;
export function useFieldState<TValue = unknown>(
path: MaybeRef<string>,
init: Partial<StateInit<TValue>>
): FieldStateComposable<TValue> {
const { value, initialValue, setInitialValue } = _useFieldValue<TValue>(path, init.modelValue, !init.standalone);
const { errorMessage, errors, setErrors } = _useFieldErrors(path, !init.standalone);
const meta = _useFieldMeta(value, initialValue, errors);
const id = ID_COUNTER >= Number.MAX_SAFE_INTEGER ? 0 : ++ID_COUNTER;
function setState(state: Partial<StateSetterInit<TValue>>) {
if ('value' in state) {
value.value = state.value as TValue;
}
if ('errors' in state) {
setErrors(state.errors);
}
if ('touched' in state) {
meta.touched = state.touched ?? meta.touched;
}
if ('initialValue' in state) {
setInitialValue(state.initialValue as TValue);
}
}
return {
id,
path,
value,
initialValue,
meta,
errors,
errorMessage,
setState,
};
}
interface FieldValueComposable<TValue = unknown> {
value: Ref<TValue>;
initialValue: Ref<TValue>;
setInitialValue(value: TValue): void;
}
/**
* Creates the field value and resolves the initial value
*/
export function _useFieldValue<TValue = unknown>(
path: MaybeRef<string>,
modelValue?: MaybeRef<TValue>,
shouldInjectForm = true
): FieldValueComposable<TValue> {
const form = shouldInjectForm === true ? injectWithSelf(FormContextKey, undefined) : undefined;
const modelRef = ref(unref(modelValue)) as Ref<TValue>;
function resolveInitialValue() {
if (!form) {
return unref(modelRef) as TValue;
}
return getFromPath<TValue>(form.meta.value.initialValues, unref(path), unref(modelRef)) as TValue;
}
function setInitialValue(value: TValue) {
if (!form) {
modelRef.value = value;
return;
}
form.stageInitialValue(unref(path), value, true);
}
const initialValue = computed(resolveInitialValue);
// if no form is associated, use a regular ref.
if (!form) {
const value = ref(resolveInitialValue()) as Ref<TValue>;
return {
value,
initialValue,
setInitialValue,
};
}
// to set the initial value, first check if there is a current value, if there is then use it.
// otherwise use the configured initial value if it exists.
// prioritize model value over form values
// #3429
const currentValue = modelValue ? unref(modelValue) : getFromPath(form.values, unref(path), unref(initialValue));
form.stageInitialValue(unref(path), currentValue, true);
// otherwise use a computed setter that triggers the `setFieldValue`
const value = computed<TValue>({
get() {
return getFromPath<TValue>(form.values, unref(path)) as TValue;
},
set(newVal) {
form.setFieldValue(unref(path), newVal);
},
}) as Ref<TValue>;
return {
value,
initialValue,
setInitialValue,
};
}
/**
* Creates meta flags state and some associated effects with them
*/
function _useFieldMeta<TValue>(
currentValue: Ref<TValue>,
initialValue: MaybeRef<TValue> | undefined,
errors: Ref<string[]>
) {
const meta = reactive({
touched: false,
pending: false,
valid: true,
validated: !!unref(errors).length,
initialValue: computed(() => unref(initialValue) as TValue | undefined),
dirty: computed(() => {
return !isEqual(unref(currentValue), unref(initialValue));
}),
}) as FieldMeta<TValue>;
watch(
errors,
value => {
meta.valid = !value.length;
},
{
immediate: true,
flush: 'sync',
}
);
return meta;
}
/**
* Creates the error message state for the field state
*/
export function _useFieldErrors(path: MaybeRef<string>, shouldInjectForm: boolean) {
const form = shouldInjectForm ? injectWithSelf(FormContextKey, undefined) : undefined;
function normalizeErrors(messages: string | string[] | null | undefined) {
if (!messages) {
return [];
}
return Array.isArray(messages) ? messages : [messages];
}
if (!form) {
const errors = ref<string[]>([]);
return {
errors,
errorMessage: computed<string | undefined>(() => errors.value[0]),
setErrors: (messages: string | string[] | null | undefined) => {
errors.value = normalizeErrors(messages);
},
};
}
const errors = computed(() => form.errorBag.value[unref(path)] || []);
return {
errors,
errorMessage: computed<string | undefined>(() => errors.value[0]),
setErrors: (messages: string | string[] | null | undefined) => {
form.setFieldErrorBag(unref(path), normalizeErrors(messages));
},
};
}