import {eFormValidateMode, eFormValidateTrigger, getValidateResultMessage, iFormValidatePropsType, iValidateState} from "./validate.utils"; import {provide, reactive} from "@peryl/react-compose"; import {$message} from "../../$message"; import {Validation} from "./createValidation"; import {AutoLoadingObserver} from "../../AutoLoadingObserver"; /** * Form以及FormItem的上下文状态注入关键字 * @author 韦胜健 * @date 2022/8/22 23:41 */ export const FORM_VALIDATION_PROVIDER = '@@FORM_VALIDATION_PROVIDER'; /** * 抽离Form中的校验逻辑 * @author 韦胜健 * @date 2022.11.5 23:41 */ export function useFormValidation({ props }: { props: iFormValidatePropsType }) { /** * 收集校验 * @author 韦胜健 * @date 2022.11.5 23:50 */ const parentValidation = Validation.useValidationParent(props); /** * 校验状态 * @author 韦胜健 * @date 2022.11.5 23:50 */ const state: iValidateState = reactive({ validateResultData: null, }); /** * 校验加载状态显示 * @author 韦胜健 * @date 2022.11.5 23:34 */ const loading = (() => { let time: null | number; const state = reactive({ loading: false }); return { state, show: () => { time = setTimeout(() => { state.loading = true; time = null; }, 500) as any as number; }, hide: () => { if (!!time) { clearTimeout(time); } else { state.loading = false; } }, }; })(); /** * 处理校验动作 * @author 韦胜健 * @date 2022.11.5 23:43 */ const handler = { onFieldChange: ({ label, field }: { label: string | null | undefined, field: string | undefined }) => { return parentValidation.methods.validateItem({ label, field, trigger: eFormValidateTrigger.change, state, formData: props.modelValue }); }, onEditChange: ({ label, field }: { label: string | null | undefined, field: string | undefined }) => { // if (props.validateMode !== eFormValidateMode.table) {return; } return handler.onFieldChange({ label, field }); }, onBlurChange: ({ label, field }: { label: string | null | undefined, field: string | undefined }) => { return parentValidation.methods.validateItem({ label, field, trigger: eFormValidateTrigger.blur, state, formData: props.modelValue }); }, }; /** * 校验方法 * @author 韦胜健 * @date 2022.11.5 23:43 */ const methods = { /** * 清空校验 * @author 韦胜健 * @date 2022.11.5 23:28 */ clearValidate: () => { state.validateResultData = null; }, /** * 触发校验 * @author 韦胜健 * @date 2022.11.5 23:28 */ validate: async (config?: { autoLoading?: boolean, autoAlert?: boolean, }) => { let promise = (async () => { config = config || {}; if (config.autoLoading != false) { loading.show(); } try { const validateResultData = await parentValidation.methods.validate({ state, formData: props.modelValue, }); if (!!validateResultData && validateResultData.length > 0) { if (config.autoAlert !== false) { $message(getValidateResultMessage(validateResultData[0], props.modelValue)); } return Promise.reject(validateResultData); } } finally { loading.hide(); } })(); AutoLoadingObserver.subject(promise); return promise; }, }; const refer = { props, state, loading, methods, handler, }; provide(FORM_VALIDATION_PROVIDER, refer); return refer; }