vuestic-ui
Version:
Vue 3 UI Framework
117 lines (116 loc) • 3.29 kB
JavaScript
import { provide, computed, unref, toRef } from "vue";
import { F as FormServiceKey } from "./consts.mjs";
import { u as useFormChild } from "./useFormChild.mjs";
import { c as createFormContext } from "./formContext.mjs";
const useFormParent = (options) => {
const formContext = createFormContext(options);
provide(FormServiceKey, formContext);
const { fields, forceDirty } = formContext;
const fieldNames = computed(() => fields.value.map((field) => unref(field.name)).filter(Boolean));
const fieldsNamed = computed(() => fields.value.reduce((acc, field) => {
if (unref(field.name)) {
acc[unref(field.name)] = field;
}
return acc;
}, {}));
const formData = computed(() => fields.value.reduce((acc, field) => {
if (unref(field.name)) {
acc[unref(field.name)] = unref(field.value);
}
return acc;
}, {}));
const isValid = computed(() => fields.value.every((field) => unref(field.isValid)));
const isLoading = computed(() => fields.value.some((field) => unref(field.isLoading)));
const errorMessages = computed(() => fields.value.map((field) => unref(field.errorMessages)).flat());
const errorMessagesNamed = computed(() => fields.value.reduce((acc, field) => {
if (unref(field.name)) {
acc[unref(field.name)] = unref(field.errorMessages);
}
return acc;
}, {}));
const isDirty = computed({
get() {
return fields.value.some((field) => unref(field.isDirty)) || forceDirty.value;
},
set(v) {
forceDirty.value = v;
fields.value.forEach((field) => {
field.isDirty = v;
});
}
});
const isTouched = computed({
get() {
return fields.value.some((field) => field.isTouched);
},
set(v) {
fields.value.forEach((field) => {
field.isTouched = v;
});
}
});
const validate = () => {
isDirty.value = true;
return fields.value.reduce((acc, field) => {
return field.validate() && acc;
}, true);
};
const validateAsync = () => {
isDirty.value = true;
return Promise.all(fields.value.map((field) => field.validateAsync())).then((results) => {
return results.every(Boolean);
});
};
const reset = () => {
isDirty.value = false;
fields.value.forEach((field) => field.reset());
};
const resetValidation = () => {
isDirty.value = false;
fields.value.forEach((field) => field.resetValidation());
};
const focus = () => {
var _a;
(_a = fields.value[0]) == null ? void 0 : _a.focus();
};
const focusInvalidField = () => {
const invalidField = fields.value.find((field) => !field.isValid);
invalidField == null ? void 0 : invalidField.focus();
};
useFormChild({
name: toRef(options, "name"),
isValid,
isLoading,
isDirty,
isTouched,
validate,
validateAsync,
reset,
resetValidation,
focus,
errorMessages
});
return {
immediate: computed(() => options.immediate),
isDirty,
isTouched,
formData,
fields,
fieldsNamed,
fieldNames,
isValid,
isLoading,
errorMessages,
errorMessagesNamed,
validate,
validateAsync,
reset,
resetValidation,
focus,
focusInvalidField
};
};
export {
useFormParent as u
};
//# sourceMappingURL=useFormParent.mjs.map