"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    useGridRowContext: ()=>useGridRowContext,
    Grid: ()=>Grid,
    useGridContext: ()=>useGridContext,
    GridRowContext: ()=>GridRowContext
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const schema_namespaceObject = require("@tachybase/schema");
const tinycolor_namespaceObject = require("@ctrl/tinycolor");
const core_namespaceObject = require("@dnd-kit/core");
const external_classnames_namespaceObject = require("classnames");
var external_classnames_default = /*#__PURE__*/ __webpack_require__.n(external_classnames_namespaceObject);
const external_lodash_namespaceObject = require("lodash");
var external_lodash_default = /*#__PURE__*/ __webpack_require__.n(external_lodash_namespaceObject);
const index_js_namespaceObject = require("../__builtins__/index.js");
const external_index_js_namespaceObject = require("../../../index.js");
const external_block_provider_index_js_namespaceObject = require("../../../block-provider/index.js");
const dnd_context_index_js_namespaceObject = require("../../common/dnd-context/index.js");
const external_Grid_style_js_namespaceObject = require("./Grid.style.js");
var external_Grid_style_js_default = /*#__PURE__*/ __webpack_require__.n(external_Grid_style_js_namespaceObject);
const GridRowContext = /*#__PURE__*/ (0, external_react_namespaceObject.createContext)({});
GridRowContext.displayName = 'GridRowContext';
const GridColContext = /*#__PURE__*/ (0, external_react_namespaceObject.createContext)({});
GridColContext.displayName = 'GridColContext';
const GridContext = /*#__PURE__*/ (0, external_react_namespaceObject.createContext)({});
GridContext.displayName = 'GridContext';
const breakRemoveOnGrid = (s)=>'Grid' === s['x-component'];
const breakRemoveOnRow = (s)=>'Grid.Row' === s['x-component'];
const MemorizedRecursionField = /*#__PURE__*/ external_react_default().memo(schema_namespaceObject.RecursionField);
MemorizedRecursionField.displayName = 'MemorizedRecursionField';
const ColDivider = (props)=>{
    var _dndContext_active_data_current_schema, _dndContext_active_data_current, _dndContext_active;
    const { token } = (0, index_js_namespaceObject.useToken)();
    const dragIdRef = (0, external_react_namespaceObject.useRef)(null);
    const { isOver, setNodeRef } = (0, core_namespaceObject.useDroppable)({
        id: props.id,
        data: props.data
    });
    const { dn, designable } = (0, external_index_js_namespaceObject.useDesignable)();
    const dividerRef = (0, external_react_namespaceObject.useRef)();
    const droppableStyle = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!isOver) return {};
        return {
            backgroundColor: new tinycolor_namespaceObject.TinyColor(token.colorSettings).setAlpha(0.1).toHex8String()
        };
    }, [
        isOver
    ]);
    const dndContext = (0, core_namespaceObject.useDndContext)();
    const activeSchema = null === (_dndContext_active = dndContext.active) || void 0 === _dndContext_active ? void 0 : null === (_dndContext_active_data_current = _dndContext_active.data.current) || void 0 === _dndContext_active_data_current ? void 0 : null === (_dndContext_active_data_current_schema = _dndContext_active_data_current.schema) || void 0 === _dndContext_active_data_current_schema ? void 0 : _dndContext_active_data_current_schema.parent;
    const blocksLength = activeSchema ? Object.keys(activeSchema.properties).length : 0;
    let visible = true;
    if (1 === blocksLength) {
        if (props.first) visible = activeSchema !== props.cols[0];
        else {
            const currentSchema = props.cols[props.index];
            const downSchema = props.cols[props.index + 1];
            visible = activeSchema !== currentSchema && downSchema !== activeSchema;
        }
    }
    const prevSchema = props.cols[props.index];
    const nextSchema = props.cols[props.index + 1];
    const { attributes, listeners, setNodeRef: setDraggableNodeRef, isDragging } = (0, core_namespaceObject.useDraggable)({
        disabled: props.first || props.last || !designable,
        id: props.id,
        data: {
            dividerRef,
            prevSchema,
            nextSchema
        }
    });
    const [clientWidths, setClientWidths] = (0, external_react_namespaceObject.useState)([
        0,
        0
    ]);
    (0, core_namespaceObject.useDndMonitor)({
        onDragStart (event) {
            var _event_active_data_current_dividerRef;
            if ((null === (_event_active_data_current_dividerRef = event.active.data.current.dividerRef) || void 0 === _event_active_data_current_dividerRef ? void 0 : _event_active_data_current_dividerRef.current) !== dividerRef.current) return;
            dragIdRef.current = event.active.id;
            const el = dividerRef.current;
            const prev = el.previousElementSibling;
            const next = el.nextElementSibling;
            setClientWidths([
                prev.clientWidth,
                next.clientWidth
            ]);
        },
        onDragMove (event) {
            if (!isDragging) return;
            if (dragIdRef.current === event.active.id) dragIdRef.current = dragIdRef.current + '_move';
            const el = dividerRef.current;
            const prev = el.previousElementSibling;
            const next = el.nextElementSibling;
            prev.style.width = "".concat(clientWidths[0] + event.delta.x, "px");
            next.style.width = "".concat(clientWidths[1] - event.delta.x, "px");
        },
        onDragEnd (event) {
            var _dragIdRef_current;
            if (!dragIdRef.current) return;
            if (null === (_dragIdRef_current = dragIdRef.current) || void 0 === _dragIdRef_current ? void 0 : _dragIdRef_current.startsWith(event.active.id)) {
                if (!dragIdRef.current.endsWith('_move')) return;
            }
            if (clientWidths[0] <= 0 || clientWidths[1] <= 0) return;
            setClientWidths([
                0,
                0
            ]);
            if (!prevSchema || !nextSchema) return;
            const el = dividerRef.current;
            const prev = el.previousElementSibling;
            const next = el.nextElementSibling;
            prevSchema['x-component-props'] = prevSchema['x-component-props'] || {};
            nextSchema['x-component-props'] = nextSchema['x-component-props'] || {};
            const dividerWidth = el.clientWidth * (props.cols.length + 1) / props.cols.length;
            const preWidth = (100 * (prev.getBoundingClientRect().width + dividerWidth) / el.parentElement.clientWidth).toFixed(2);
            const nextWidth = (100 * (next.getBoundingClientRect().width + dividerWidth) / el.parentElement.clientWidth).toFixed(2);
            external_lodash_default().set(prevSchema, 'x-component-props.width', preWidth);
            external_lodash_default().set(nextSchema, 'x-component-props.width', nextWidth);
            dn.emit('batchPatch', {
                schemas: [
                    {
                        ['x-uid']: prevSchema['x-uid'],
                        'x-component-props': {
                            ...prevSchema['x-component-props']
                        }
                    },
                    {
                        ['x-uid']: nextSchema['x-uid'],
                        'x-component-props': {
                            ...nextSchema['x-component-props']
                        }
                    }
                ]
            });
        }
    });
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
        ref: (el)=>{
            if (visible) {
                setNodeRef(el);
                dividerRef.current = el;
            }
        },
        className: external_classnames_default()('tb-col-divider', 'ColDivider'),
        style: droppableStyle,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
            ref: setDraggableNodeRef,
            ...listeners,
            ...attributes,
            tabIndex: -1,
            className: props.first || props.last || !designable ? null : 'DraggableNode'
        })
    });
};
const RowDivider = (props)=>{
    var _dndContext_active_data_current_schema, _dndContext_active_data_current, _dndContext_active;
    const { token } = (0, index_js_namespaceObject.useToken)();
    const { isOver, setNodeRef } = (0, core_namespaceObject.useDroppable)({
        id: props.id,
        data: props.data
    });
    const [active, setActive] = (0, external_react_namespaceObject.useState)(false);
    const droppableStyle = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!isOver) return {
            zIndex: active ? 1000 : -1
        };
        return {
            zIndex: active ? 1000 : -1,
            backgroundColor: new tinycolor_namespaceObject.TinyColor(token.colorSettings).setAlpha(0.1).toHex8String()
        };
    }, [
        active,
        isOver
    ]);
    const dndContext = (0, core_namespaceObject.useDndContext)();
    const currentSchema = props.rows[props.index];
    const activeSchema = null === (_dndContext_active = dndContext.active) || void 0 === _dndContext_active ? void 0 : null === (_dndContext_active_data_current = _dndContext_active.data.current) || void 0 === _dndContext_active_data_current ? void 0 : null === (_dndContext_active_data_current_schema = _dndContext_active_data_current.schema) || void 0 === _dndContext_active_data_current_schema ? void 0 : _dndContext_active_data_current_schema.parent.parent;
    const colsLength = null == activeSchema ? void 0 : activeSchema.mapProperties((schema)=>'Grid.Col' === schema['x-component']).filter(Boolean).length;
    let visible = true;
    if (1 === colsLength) {
        if (props.first) visible = activeSchema !== props.rows[0];
        else {
            const downSchema = props.rows[props.index + 1];
            visible = activeSchema !== currentSchema && downSchema !== activeSchema;
        }
    }
    (0, core_namespaceObject.useDndMonitor)({
        onDragStart (event) {
            setActive(true);
        },
        onDragMove (event) {},
        onDragOver (event) {},
        onDragEnd (event) {
            setActive(false);
        },
        onDragCancel (event) {
            setActive(false);
        }
    });
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
        ref: visible ? setNodeRef : null,
        className: external_classnames_default()('tb-row-divider', 'RowDivider'),
        style: droppableStyle
    });
};
const wrapRowSchema = (schema)=>{
    const row = new schema_namespaceObject.Schema({
        type: 'void',
        name: "row_".concat((0, schema_namespaceObject.uid)()),
        'x-uid': (0, schema_namespaceObject.uid)(),
        'x-component': 'Grid.Row'
    });
    const col = row.addProperty((0, schema_namespaceObject.uid)(), {
        type: 'void',
        'x-uid': (0, schema_namespaceObject.uid)(),
        'x-component': 'Grid.Col'
    });
    if (schema_namespaceObject.Schema.isSchemaInstance(schema)) schema.parent = col;
    col.addProperty(schema.name, schema);
    return row;
};
const wrapColSchema = (schema)=>{
    const s = new schema_namespaceObject.Schema({
        type: 'void',
        name: "col_".concat((0, schema_namespaceObject.uid)()),
        'x-uid': (0, schema_namespaceObject.uid)(),
        'x-component': 'Grid.Col'
    });
    if (schema_namespaceObject.Schema.isSchemaInstance(schema)) schema.parent = s;
    s.addProperty(schema.name, schema);
    return s;
};
const useRowProperties = ()=>{
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    return (0, external_react_namespaceObject.useMemo)(()=>fieldSchema.reduceProperties((buf, s)=>{
            if ('Grid.Row' === s['x-component'] && !s['x-hidden']) buf.push(s);
            return buf;
        }, []), [
        Object.keys(fieldSchema.properties || {}).join(',')
    ]);
};
const useColProperties = ()=>{
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    return (0, external_react_namespaceObject.useMemo)(()=>fieldSchema.reduceProperties((buf, s)=>{
            if ('Grid.Col' === s['x-component'] && !s['x-hidden']) buf.push(s);
            return buf;
        }, []), [
        Object.keys(fieldSchema.properties || {}).join(',')
    ]);
};
const DndWrapper = (props)=>{
    if (false === props.dndContext) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(jsx_runtime_namespaceObject.Fragment, {
        children: props.children
    });
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(dnd_context_index_js_namespaceObject.DndContext, {
        ...props.dndContext,
        children: props.children
    });
};
const useGridContext = ()=>(0, external_react_namespaceObject.useContext)(GridContext);
const useGridRowContext = ()=>(0, external_react_namespaceObject.useContext)(GridRowContext);
const Grid = (0, schema_namespaceObject.observer)((props)=>{
    const { distributed, showDivider = true } = props;
    const gridRef = (0, external_react_namespaceObject.useRef)(null);
    const field = (0, schema_namespaceObject.useField)();
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const { render } = (0, external_index_js_namespaceObject.useSchemaInitializerRender)(fieldSchema['x-initializer'], fieldSchema['x-initializer-props']);
    const InitializerComponent = (props)=>render(props);
    const addr = field.address.toString();
    const rows = useRowProperties();
    const { setPrintContent } = (0, external_index_js_namespaceObject.useFormBlockContext)();
    const { wrapSSR, componentCls, hashId } = external_Grid_style_js_default()();
    const distributedValue = void 0 === distributed ? (null == fieldSchema ? void 0 : fieldSchema.parent['x-component']) === 'Page' || (null == fieldSchema ? void 0 : fieldSchema.parent['x-component']) === 'Tabs.TabPane' : distributed;
    (0, external_react_namespaceObject.useEffect)(()=>{
        gridRef.current && (null == setPrintContent || setPrintContent(gridRef.current));
    }, [
        gridRef.current
    ]);
    return wrapSSR(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(GridContext.Provider, {
        value: {
            ref: gridRef,
            fieldSchema,
            renderSchemaInitializer: render,
            InitializerComponent,
            showDivider
        },
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
            className: "tb-grid ".concat(componentCls, " ").concat(hashId),
            style: {
                position: 'relative'
            },
            ref: gridRef,
            children: [
                /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(DndWrapper, {
                    dndContext: props.dndContext,
                    children: [
                        showDivider ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(RowDivider, {
                            rows: rows,
                            first: true,
                            id: "".concat(addr, "_0"),
                            data: {
                                breakRemoveOn: breakRemoveOnGrid,
                                wrapSchema: wrapRowSchema,
                                insertAdjacent: 'afterBegin',
                                schema: fieldSchema
                            }
                        }) : null,
                        rows.map((schema, index)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(external_react_default().Fragment, {
                                children: [
                                    distributedValue ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_index_js_namespaceObject.SchemaComponent, {
                                        name: schema.name,
                                        schema: schema,
                                        distributed: true
                                    }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(MemorizedRecursionField, {
                                        name: schema.name,
                                        schema: schema
                                    }),
                                    showDivider ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(RowDivider, {
                                        rows: rows,
                                        index: index,
                                        id: "".concat(addr, "_").concat(index + 1),
                                        data: {
                                            breakRemoveOn: breakRemoveOnGrid,
                                            wrapSchema: wrapRowSchema,
                                            insertAdjacent: 'afterEnd',
                                            schema
                                        }
                                    }) : null
                                ]
                            }, index))
                    ]
                }),
                render()
            ]
        })
    }));
}, {
    displayName: 'Grid'
});
Grid.Row = (0, schema_namespaceObject.observer)(()=>{
    const field = (0, schema_namespaceObject.useField)();
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const addr = field.address.toString();
    const cols = useColProperties();
    const { showDivider } = useGridContext();
    const { type } = (0, external_block_provider_index_js_namespaceObject.useFormBlockType)();
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(GridRowContext.Provider, {
        value: {
            schema: fieldSchema,
            cols
        },
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
            className: external_classnames_default()('tb-grid-row', 'CardRow', {
                showDivider
            }),
            children: [
                showDivider && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ColDivider, {
                    cols: cols,
                    first: true,
                    id: "".concat(addr, "_0"),
                    data: {
                        breakRemoveOn: breakRemoveOnRow,
                        wrapSchema: wrapColSchema,
                        insertAdjacent: 'afterBegin',
                        schema: fieldSchema
                    }
                }),
                cols.map((schema, index)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(external_react_default().Fragment, {
                        children: [
                            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.RecursionField, {
                                name: schema.name,
                                schema: schema,
                                mapProperties: (schema)=>{
                                    if ('update' === type) schema.default = null;
                                    return schema;
                                }
                            }),
                            showDivider && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ColDivider, {
                                cols: cols,
                                index: index,
                                last: index === cols.length - 1,
                                id: "".concat(addr, "_").concat(index + 1),
                                data: {
                                    breakRemoveOn: breakRemoveOnRow,
                                    wrapSchema: wrapColSchema,
                                    insertAdjacent: 'afterEnd',
                                    schema
                                }
                            })
                        ]
                    }, index))
            ]
        })
    });
}, {
    displayName: 'Grid.Row'
});
Grid.Col = (0, schema_namespaceObject.observer)((props)=>{
    var _schema_xcomponentprops;
    const { cols = [] } = (0, external_react_namespaceObject.useContext)(GridRowContext);
    const { showDivider } = useGridContext();
    const schema = (0, schema_namespaceObject.useFieldSchema)();
    const field = (0, schema_namespaceObject.useField)();
    const { token } = (0, index_js_namespaceObject.useToken)();
    const style = (0, external_react_namespaceObject.useMemo)(()=>{
        let width = '';
        if (null == cols ? void 0 : cols.length) {
            var _schema_xcomponentprops;
            const w = (null == schema ? void 0 : null === (_schema_xcomponentprops = schema['x-component-props']) || void 0 === _schema_xcomponentprops ? void 0 : _schema_xcomponentprops['width']) || 100 / cols.length;
            width = "calc(".concat(w, "% - ").concat(token.marginLG, "px *  ").concat((showDivider ? cols.length + 1 : 0) / cols.length, ")");
        }
        return {
            width
        };
    }, [
        null == cols ? void 0 : cols.length,
        null == schema ? void 0 : null === (_schema_xcomponentprops = schema['x-component-props']) || void 0 === _schema_xcomponentprops ? void 0 : _schema_xcomponentprops['width']
    ]);
    const { isOver, setNodeRef } = (0, core_namespaceObject.useDroppable)({
        id: field.address.toString(),
        data: {
            insertAdjacent: 'beforeEnd',
            schema,
            wrapSchema: (s)=>s
        }
    });
    const [active, setActive] = (0, external_react_namespaceObject.useState)(false);
    const droppableStyle = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!isOver) return {
            height: '100%'
        };
        return {
            background: "linear-gradient(to top,  ".concat(new tinycolor_namespaceObject.TinyColor(token.colorSettings).setAlpha(0.1).toHex8String(), " 20%, transparent 20%)"),
            borderTopRightRadius: '10px',
            borderTopLeftRadius: '10px',
            height: '100%'
        };
    }, [
        active,
        isOver
    ]);
    (0, core_namespaceObject.useDndMonitor)({
        onDragStart (event) {
            setActive(true);
        },
        onDragMove (event) {},
        onDragOver (event) {},
        onDragEnd (event) {
            setActive(false);
        },
        onDragCancel (event) {
            setActive(false);
        }
    });
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(GridColContext.Provider, {
        value: {
            cols,
            schema
        },
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
            ref: setNodeRef,
            style: {
                ...style,
                ...droppableStyle
            },
            className: external_classnames_default()('tb-grid-col  CardCol'),
            children: props.children
        })
    });
}, {
    displayName: 'Grid.Row'
});
Grid.wrap = (schema)=>({
        type: 'void',
        'x-component': 'Grid.Row',
        properties: {
            [(0, schema_namespaceObject.uid)()]: {
                type: 'void',
                'x-component': 'Grid.Col',
                properties: {
                    [schema.name || (0, schema_namespaceObject.uid)()]: schema
                }
            }
        }
    });
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
