import { jsx as _jsx } from "react/jsx-runtime";
import * as React from 'react';
import { cloneDeep, set, unset } from 'lodash';
import Fields from "./components/Fields/Fields.js";
import { formGeneratorCn } from "./utils/cn.js";
import { getValueByPath } from "./utils/fields.js";
import './FormGenerator.css';
const b = formGeneratorCn('generator');
const FormGenerator = ({ blockConfig, contentConfig, onUpdate, onUpdateByKey, className, }) => {
    const contentRef = React.useRef(contentConfig);
    // Sync during render (not in useEffect) so that onDataUpdate calls within the same
    // effects batch all build on top of each other. If we synced in useEffect, it would
    // run *after* child effects, resetting any accumulated changes made by onDataUpdate.
    contentRef.current = contentConfig;
    const onDataUpdate = React.useCallback((key, value, options) => {
        if (!onUpdate && !onUpdateByKey) {
            return;
        }
        const newContentConfig = cloneDeep(contentRef.current ?? {});
        const removeAt = options?.removeArrayItemAt;
        if (typeof removeAt === 'number') {
            const arr = getValueByPath(newContentConfig, key);
            if (Array.isArray(arr) && removeAt >= 0 && removeAt < arr.length) {
                arr.splice(removeAt, 1);
            }
        }
        else if (options?.unset) {
            unset(newContentConfig, key);
        }
        else {
            set(newContentConfig, key, value);
        }
        contentRef.current = newContentConfig;
        if (onUpdateByKey) {
            onUpdateByKey(key, value);
        }
        if (onUpdate) {
            onUpdate(newContentConfig);
        }
    }, [onUpdate, onUpdateByKey]);
    return (_jsx("div", { className: b(null, className), children: _jsx(Fields, { fields: blockConfig, content: contentConfig, onUpdate: onDataUpdate }) }));
};
export default FormGenerator;
//# sourceMappingURL=FormGenerator.js.map
