UNPKG

@offensichtbar-codestock/es6-flex-masonry-grid

Version:
311 lines (244 loc) 10.9 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var Utils = _interopRequireWildcard(require("./utils")); var _card = _interopRequireDefault(require("./card")); var _observer = require("./observer"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var DEFAULTCONFIG = { animation: true, animationType: 'fade', animationDelay: 200, observeDOM: false }; var OSB_MasonryGrid = /*#__PURE__*/function () { /** * Represents the grid * @constructor * @param {object} config - animation config * @param {node} el - HTMLElement */ function OSB_MasonryGrid(el, config) { _classCallCheck(this, OSB_MasonryGrid); /* Error if element not exists */ if (!el) { throw new ReferenceError("The specified HTML selector for the grid is not valid. Please make sure that the referenced HTML object exists. For more information, visit the documentation at https://github.com/offensichtbar-codestock/es6-flex-masonry-grid."); } this._config = this.setConfig(config); this._domelement = el; if (this._config.animation) this._domelement.classList.add("obs_grid-animation-".concat(this._config.animationType.toLowerCase())); this._initCards(); this._animateCards(); this._initGrid(); this._addEventListener(); this._observeGrid(); } /** * Merges default config and custom config * @param {object} config - custom config * @return {object} _config */ _createClass(OSB_MasonryGrid, [{ key: "setConfig", value: function setConfig(config) { this._config = config || DEFAULTCONFIG; return Object.assign(DEFAULTCONFIG, this._config); } /** * Initializes the grid elements * Creates instances of grid cards * and pushes them to this._cards array */ }, { key: "_initCards", value: function _initCards() { var _this = this; this._cards = []; Array.from(this._domelement.children).forEach(function (child, index) { var card = new _card["default"](child, index, _this._config.animation); _this._cards.push(card); }); } /** * Animates the grid elements. */ }, { key: "_animateCards", value: function _animateCards() { var speed = this._config.animationDelay; if (!this._config.animation) speed = 0; Array.from(this._cards).forEach(function (card, index) { setTimeout(function () { card.animate(); }, index * speed); }); } /** * Initializes the grid * Gets amount of cols * Gets heights of rows * Sets card translation for masonry layout * Sets container height */ }, { key: "_initGrid", value: function _initGrid() { /* Calculates amount of cols */ var cardWidth = this._cards[0] !== undefined ? this._cards[0].width : this._domelement.offsetWidth; this._cols = Math.round(this._domelement.offsetWidth / cardWidth); /* Calculates row heights */ this._calcRowHeights(); /* Set card translation for masonry layout */ this._translateCard(); /* Set container height */ this._setContainerHeight(); } /** * Accumulates the offset values per column * @param {number} index - index of current card * @return {number} offset - card translateY */ }, { key: "_getPrevOffset", value: function _getPrevOffset(index) { var prevElIndex = index - this._cols; var offset = 0; while (prevElIndex >= 0) { var currentRowHeight = this._rowHeights[Math.floor(prevElIndex / this._cols)]; var currentOffset = currentRowHeight - this._cards[prevElIndex].height; offset += currentOffset; prevElIndex = prevElIndex - this._cols; } return offset; } /** * Gets row height * by comparing heights of cards per row * Assigns the largest element height value per row to this._rowHeights array item */ }, { key: "_calcRowHeights", value: function _calcRowHeights() { this._rowHeights = []; var rows = Math.ceil(this._cards.length / this._cols); for (var row = 0; row < rows; row++) { this._rowHeights.push(0); var cardsPerRow = this._cards.slice(row * this._cols, row * this._cols + this._cols); this._rowHeights[row] = Math.max.apply(Math, _toConsumableArray(cardsPerRow.map(function (card) { return card.height; }))); } } /** * Sets transform: translateY style to each card */ }, { key: "_translateCard", value: function _translateCard() { var _this2 = this; Array.from(this._cards).forEach(function (card, index) { card.translate(_this2._getPrevOffset(index)); }); } /** * Sets total height for container */ }, { key: "_setContainerHeight", value: function _setContainerHeight() { var _containerHeight = []; for (var col = 0; col < this._cols; col++) { _containerHeight.push([0]); var i = 0; while (col + this._cols * i < this._cards.length) { var currVal = _containerHeight[col % this._cols]; var newVal = this._cards[col + i * this._cols].height; _containerHeight[col % this._cols] = parseInt(currVal) + newVal; i++; } } this._domelement.style.height = "".concat(Math.max.apply(Math, _containerHeight), "px"); } /** * Observes addition and removal of cards */ }, { key: "_observeGrid", value: function _observeGrid() { new _observer.ObserveDOM(this._domelement); } /** * Creates card instance * Adds class to new card * Adds card instance to array * Reinits grid * @param{event} event - addcard */ }, { key: "_addCard", value: function _addCard(event) { var newCard = this._domelement.children[event.data]; var card = new _card["default"](newCard, this._cards.length, this._config.animation); this._cards.splice(event.data, 0, card); this._cards.forEach(function (card, index) { return card.cardindex = index; }); setTimeout(function () { card.animate(); }, 100); this._initGrid(); } /** * Removes card instance from array * Resets card indexes * Reinits grid * @param{event} event - removecard */ }, { key: "_removeCard", value: function _removeCard(event) { var removedElIndex = event.data; this._cards.splice(removedElIndex, 1); this._cards.forEach(function (card, index) { return card.cardindex = index; }); this._initGrid(); } /** * Adds event listener for resize * Recalculates card specs on resize * Recalculates translation values for cards on resize * Reinits grid when card is added or removed * Reinits grid when card height changes * @callback{function} */ }, { key: "_addEventListener", value: function _addEventListener() { var _this3 = this; var initgrid = Utils.debounce(function () { _this3._initGrid(); }, 200); window.addEventListener('resize', initgrid); Utils.ModuleEventManager.on('addcard', this._addCard.bind(this)); Utils.ModuleEventManager.on('removecard', this._removeCard.bind(this)); Utils.ModuleEventManager.on('mutationevent', this._initGrid.bind(this)); } }]); return OSB_MasonryGrid; }(); exports["default"] = OSB_MasonryGrid;