"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("@builder.io/react");
var react_2 = require("react");
var react_masonry_component_1 = require("react-masonry-component");
var isArray_1 = require("lodash-es/isArray");
var last_1 = require("lodash-es/last");
var defaultTile = {
    '@type': '@builder.io/sdk:Element',
    responsiveStyles: {
        large: {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'stretch',
            position: 'relative',
            flexShrink: '0',
            boxSizing: 'border-box',
            marginTop: '20px',
            minHeight: '20px',
            minWidth: '20px',
            overflow: 'hidden',
            marginLeft: '20px'
        }
    },
    component: {
        name: 'Image',
        options: {
            image: 'https://builder.io/api/v1/image/assets%2Fpwgjf0RoYWbdnJSbpBAjXNRMe9F2%2Ffb27a7c790324294af8be1c35fe30f4d?width=2000&height=1200',
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            aspectRatio: 0.7041
        }
    }
};
var getRandomAspectTile = function () { return (__assign(__assign({}, defaultTile), { component: __assign(__assign({}, defaultTile.component), { options: __assign(__assign({}, defaultTile.component.options), { 
            // range from 0.5 to 2, rounded to 2 decimal points
            aspectRatio: Math.round((Math.random() * 1.5 + 0.5) * 100) / 100 }) }) })); };
// TODO: column with, gutter, etc options
var BuilderMasonryComponent = /** @class */ (function (_super) {
    __extends(BuilderMasonryComponent, _super);
    function BuilderMasonryComponent() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.divRef = null;
        _this.masonryRef = null;
        _this.state = {
            layoutComplete: false
        };
        return _this;
    }
    BuilderMasonryComponent.prototype.componentDidMount = function () {
        var _this = this;
        setTimeout(function () {
            if (_this.divRef) {
                _this.divRef.dispatchEvent(new CustomEvent('builder:masonry:load', {
                    bubbles: true,
                    cancelable: false,
                    detail: {
                        block: _this.props.builderBlock,
                        ref: _this.divRef,
                        masonry: _this.masonryRef
                    }
                }));
            }
            if (react_1.Builder.isEditing) {
                // mutation observer?
            }
        });
    };
    BuilderMasonryComponent.prototype.render = function () {
        var _this = this;
        var slides = this.props.tiles;
        // if (slides && !Builder.isBrowser) {
        //   slides = slides.slice(0, 1)
        // }
        var itemStyle = {
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'stretch',
            width: this.props.columnWidth
        };
        return (react_2.default.createElement("div", { style: {
                opacity: react_1.Builder.isBrowser && this.state.layoutComplete ? 1 : 0,
                transition: 'opacity 0.2s'
            } },
            react_2.default.createElement(react_1.BuilderAsyncRequestsContext.Consumer, null, function (value) {
                _this._errors = value && value.errors;
                _this._logs = value && value.logs;
                return (react_2.default.createElement(react_1.BuilderStoreContext.Consumer, null, function (state) { return (react_2.default.createElement("div", { ref: function (ref) { return (_this.divRef = ref); }, className: "builder-masonry" },
                    react_2.default.createElement(react_masonry_component_1.default, { onLayoutComplete: function () {
                            if (!_this.state.layoutComplete) {
                                _this.setState(__assign(__assign({}, _this.state), { layoutComplete: true }));
                            }
                        }, options: {
                            gutter: _this.props.gutterSize,
                            // Maybe us this
                            fitWidth: _this.props.columnWidth && _this.props.columnWidth.endsWith('%')
                                ? false
                                : true,
                            percentPosition: 
                            // TODO: option to override this too
                            (_this.props.columnWidth &&
                                (_this.props.columnWidth.endsWith('%') ||
                                    _this.props.columnWidth.startsWith('.'))) ||
                                false
                        }, ref: function (ref) { return (_this.masonryRef = ref); } }, _this.props.useChildrenForTiles
                        ? _this.props.builderBlock &&
                            _this.props.builderBlock.children &&
                            _this.props.builderBlock.children.map(function (block, index) {
                                if (block.repeat && block.repeat.collection) {
                                    var collectionPath = block.repeat.collection;
                                    var collectionName = last_1.default((collectionPath || '')
                                        .split(/\.\w+\(/)[0]
                                        .trim()
                                        .split('.'));
                                    var itemName_1 = block.repeat.itemName ||
                                        (collectionName ? collectionName + 'Item' : 'item');
                                    var array = react_1.stringToFunction(collectionPath, true, _this._errors, _this._logs)(state.state);
                                    if (isArray_1.default(array)) {
                                        if (!react_1.Builder.isBrowser) {
                                            array = array.slice(0, 1);
                                        }
                                        return array.map(function (data, index) {
                                            var _a;
                                            // TODO: Builder state produce the data
                                            var childState = __assign(__assign({}, state.state), (_a = { $index: index, $item: data }, _a[itemName_1] = data, _a));
                                            return (react_2.default.createElement("div", { className: "masonry-item", style: itemStyle },
                                                react_2.default.createElement(react_1.BuilderStoreContext.Provider, { key: block.id, value: __assign(__assign({}, state), { state: childState }) },
                                                    react_2.default.createElement(react_1.BuilderBlockComponent, { block: __assign(__assign({}, block), { repeat: null }), index: index, child: true }))));
                                        });
                                    }
                                }
                                return (react_2.default.createElement("div", { style: itemStyle, className: "masonry-item" },
                                    react_2.default.createElement(react_1.BuilderBlockComponent, { key: block.id, block: block, index: index, child: true })));
                            })
                        : _this.props.tiles &&
                            _this.props.tiles.map(function (tile, index) { return (
                            // TODO: how make react compatible with plain react components
                            // tiles: <Foo><Bar> <- builder blocks if passed react nodes as blocks just forward them
                            react_2.default.createElement("div", { style: itemStyle, className: "masonry-item" },
                                react_2.default.createElement(react_1.BuilderBlocks, { key: index, parentElementId: _this.props.builderBlock && _this.props.builderBlock.id, dataPath: "component.options.tiles." + index + ".content", child: true, blocks: tile.content || tile }))); })))); }));
            })));
    };
    return BuilderMasonryComponent;
}(react_2.default.Component));
exports.BuilderMasonryComponent = BuilderMasonryComponent;
exports.BuilderMasonry = react_1.withBuilder(BuilderMasonryComponent, {
    name: 'Builder:Masonry',
    // TODO: default children
    image: 'https://cdn.builder.io/api/v1/image/assets%2FBvYIl5jKN9QpChUB3PVzsTe2ZSI2%2F7ed6bd8129d148608ecec09300786d71?width=2000&height=1200',
    canHaveChildren: true,
    defaultStyles: {
        paddingLeft: '20px',
        paddingRight: '20px',
        paddingBottom: '20px'
    },
    defaultChildren: [
        getRandomAspectTile(),
        getRandomAspectTile(),
        getRandomAspectTile(),
        getRandomAspectTile(),
        getRandomAspectTile(),
        getRandomAspectTile(),
        getRandomAspectTile(),
        getRandomAspectTile(),
        getRandomAspectTile()
    ],
    inputs: [
        {
            name: 'columnWidth',
            // TODO: type: 'styleNumber'
            type: 'string',
            helperText: 'Width of each tile, as a CSS value. E.g. "200px" or "50%"',
            defaultValue: '200px'
        },
        {
            name: 'gutterSize',
            type: 'number',
            helperText: 'Horizontal space between tiles in pixels, e.g. "20" for 20 pixels wide',
            defaultValue: 0,
            advanced: true
        },
        {
            name: 'tiles',
            type: 'list',
            subFields: [
                {
                    name: 'content',
                    type: 'uiBlocks',
                    hideFromUI: true,
                    defaultValue: [defaultTile]
                }
            ],
            defaultValue: [],
            showIf: function (options) { return !options.get('useChildrenForTiles'); }
        },
        {
            name: 'useChildrenForTiles',
            type: 'boolean',
            helperText: 'Use child elements for each slide, instead of the array. Useful for dynamically repeating tiles',
            advanced: true,
            defaultValue: true,
            onChange: function (options) {
                if (options.get('useChildrenForTiles') === true) {
                    options.set('tiles', []);
                }
            }
        }
    ]
});
//# sourceMappingURL=Masonry.js.map