import getAllInputs from './getAllInputs.js';
import findInput from './findInput.js';
const noop = () => { };
/**
 * The decorator is created based on final-form-focus https://github.com/final-form/final-form-focus
 */
const createDecorator = () => (form) => {
    const scrollToFirstError = (errors) => {
        const allInputs = getAllInputs();
        const firstInput = findInput(allInputs, errors);
        const inputToScrollTo = firstInput === null || firstInput === void 0 ? void 0 : firstInput.parentElement;
        if (inputToScrollTo) {
            inputToScrollTo.scrollIntoView({ behavior: 'smooth' });
        }
    };
    // Save original submit function
    const originalSubmit = form.submit;
    let state = {};
    const unsubscribe = form.subscribe((nextState) => {
        state = nextState;
    }, { errors: true, submitErrors: true });
    // What to do after submit
    const afterSubmit = () => {
        const { errors, submitErrors } = state;
        if (errors && Object.keys(errors).length) {
            scrollToFirstError(errors);
        }
        else if (submitErrors && Object.keys(submitErrors).length) {
            scrollToFirstError(submitErrors);
        }
    };
    // Rewrite submit function
    form.submit = () => {
        const result = originalSubmit.call(form);
        if (result && typeof result.then === 'function') {
            // async
            result.then(afterSubmit, noop);
        }
        else {
            // sync
            afterSubmit();
        }
        return result;
    };
    return () => {
        unsubscribe();
        form.submit = originalSubmit;
    };
};
export default createDecorator;
//# sourceMappingURL=createDecorator.js.map