import getAllInputs from "./getAllInputs.mjs";
import findInput from "./findInput.mjs";
//#region src/utilities/form/final-form-scroll/createDecorator.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 inputToScrollTo = findInput(getAllInputs(), errors)?.parentElement;
		if (inputToScrollTo) inputToScrollTo.scrollIntoView({ behavior: "smooth" });
	};
	const originalSubmit = form.submit;
	let state = {};
	const unsubscribe = form.subscribe((nextState) => {
		state = nextState;
	}, {
		errors: true,
		submitErrors: true
	});
	const afterSubmit = () => {
		const { errors, submitErrors } = state;
		if (errors && Object.keys(errors).length) scrollToFirstError(errors);
		else if (submitErrors && Object.keys(submitErrors).length) scrollToFirstError(submitErrors);
	};
	form.submit = () => {
		const result = originalSubmit.call(form);
		if (result && typeof result.then === "function") result.then(afterSubmit, noop);
		else afterSubmit();
		return result;
	};
	return () => {
		unsubscribe();
		form.submit = originalSubmit;
	};
};
//#endregion
export { createDecorator as default };

//# sourceMappingURL=createDecorator.mjs.map