"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useFormikAutoSave = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const react_redux_1 = require("react-redux");
const debounce_js_1 = tslib_1.__importDefault(require("lodash-es/debounce.js"));
const formik_1 = require("formik");
const useFormikAutoSave = (debounce = 1000) => {
    const [autoSaveIDs, setAutoSaveIDs] = react_1.default.useState([]);
    const { values, isSubmitting, submitForm } = (0, formik_1.useFormikContext)();
    const prevValuesRef = react_1.default.useRef(values);
    const commitRef = react_1.default.useRef((0, debounce_js_1.default)((autoSaveID) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        yield submitForm();
        setAutoSaveIDs((ids) => ids.filter((id) => id > autoSaveID));
    }), debounce));
    react_1.default.useEffect(() => {
        if (!(0, react_redux_1.shallowEqual)(prevValuesRef.current, values) && !isSubmitting) {
            const autoSaveID = Date.now();
            setAutoSaveIDs((ids) => {
                ids.push(autoSaveID);
                return ids;
            });
            void commitRef.current(autoSaveID);
        }
        if (!isSubmitting) {
            prevValuesRef.current = values;
        }
    }, [values, isSubmitting, setAutoSaveIDs]);
    react_1.default.useEffect(() => {
        const commit = commitRef.current;
        return () => commit.cancel();
    }, []);
    return !!autoSaveIDs.length;
};
exports.useFormikAutoSave = useFormikAutoSave;
const FormikAutoSave = ({ debounce = 1000 }) => {
    const { values, dirty, isSubmitting, submitForm } = (0, formik_1.useFormikContext)();
    const prevValuesRef = react_1.default.useRef(values);
    const commitRef = react_1.default.useRef((0, debounce_js_1.default)(submitForm, debounce));
    react_1.default.useEffect(() => {
        if (!(0, react_redux_1.shallowEqual)(prevValuesRef.current, values) && dirty && !isSubmitting) {
            void commitRef.current();
        }
        if (!isSubmitting) {
            prevValuesRef.current = values;
        }
    }, [values, dirty, isSubmitting]);
    react_1.default.useEffect(() => {
        const commit = commitRef.current;
        return () => commit.cancel();
    }, []);
    return null;
};
exports.default = FormikAutoSave;
//# sourceMappingURL=FormikAutoSave.js.map