diff --git a/.gitignore b/.gitignore index 3e5e087..e37e306 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ node_modules/ package-lock.json examples/**/node_modules/ examples/**/build/ -examples/**/package-lock.json \ No newline at end of file +examples/**/package-lock.json +.idea/ diff --git a/dist/muuri-react.cjs.js b/dist/muuri-react.cjs.js index 037b0a3..c65d604 100644 --- a/dist/muuri-react.cjs.js +++ b/dist/muuri-react.cjs.js @@ -57,10 +57,8 @@ function isDecorated(instance) { return !!instance[key]; } -function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - +function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * Add a decoration to the instance. * @@ -69,6 +67,7 @@ function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { */ function addDecoration(instance, decoration) { if (isDecorated(instance)) { + // @ts-ignore Object.assign(instance[key], decoration); } else { instance[key] = _objectSpread$2({}, decoration); @@ -99,8 +98,7 @@ function removeDecorations(decorated) { * * @returns - The id of the instance. */ - -Muuri__default['default'].prototype.getId = function getId() { +Muuri__default["default"].prototype.getId = function getId() { return getDecoration(this).id; }; /** @@ -108,9 +106,7 @@ Muuri__default['default'].prototype.getId = function getId() { * * @returns - The group ids of the instance. */ - - -Muuri__default['default'].prototype.getGroupIds = function getGroupIds() { +Muuri__default["default"].prototype.getGroupIds = function getGroupIds() { return getDecoration(this).groupIds; }; /** @@ -118,19 +114,16 @@ Muuri__default['default'].prototype.getGroupIds = function getGroupIds() { * * @returns - The group ids of the instance. */ - - -Muuri__default['default'].prototype.getSizerElement = function getSizerElement() { +Muuri__default["default"].prototype.getSizerElement = function getSizerElement() { return getDecoration(this).sizerElement; }; + /** * Item key getter. * * @returns - The item component key. */ - - -Muuri__default['default'].Item.prototype.getKey = function getKey() { +Muuri__default["default"].Item.prototype.getKey = function getKey() { return getDecoration(this).key; }; /** @@ -138,9 +131,7 @@ Muuri__default['default'].Item.prototype.getKey = function getKey() { * * @returns - The item component props. */ - - -Muuri__default['default'].Item.prototype.getProps = function getProps() { +Muuri__default["default"].Item.prototype.getProps = function getProps() { return getDecoration(this).props; }; /** @@ -148,9 +139,7 @@ Muuri__default['default'].Item.prototype.getProps = function getProps() { * * @returns - The item component data. */ - - -Muuri__default['default'].Item.prototype.getData = function getData() { +Muuri__default["default"].Item.prototype.getData = function getData() { return getDecoration(this).data; }; /** @@ -158,32 +147,30 @@ Muuri__default['default'].Item.prototype.getData = function getData() { * * @param data - The data. */ - - -Muuri__default['default'].Item.prototype.setData = function setData(data) { +Muuri__default["default"].Item.prototype.setData = function setData(data) { getDecoration(this).data = data; }; // Grid context. -var GridContext = /*#__PURE__*/React.createContext({}); // Grid provider. - -var GridProvider = GridContext.Provider; // Grid context hook. - +var GridContext = /*#__PURE__*/React.createContext({}); +// Grid provider. +var GridProvider = GridContext.Provider; +// Grid context hook. var useGridContext = function useGridContext() { return React.useContext(GridContext); -}; // Grid provider display name. - +}; +// Grid provider display name. GridContext.displayName = 'GridProvider'; // Item context. -var ItemContext = /*#__PURE__*/React.createContext({}); // Item provider. - -var ItemProvider = ItemContext.Provider; // Item context hook. - +var ItemContext = /*#__PURE__*/React.createContext({}); +// Item provider. +var ItemProvider = ItemContext.Provider; +// Item context hook. var useItemContext = function useItemContext() { return React.useContext(ItemContext); -}; // Item provider display name. - +}; +// Item provider display name. ItemContext.displayName = 'ItemProvider'; /** @@ -195,14 +182,11 @@ ItemContext.displayName = 'ItemProvider'; */ var EventController = /*#__PURE__*/function () { function EventController() { - _classCallCheck__default['default'](this, EventController); - - _defineProperty__default['default'](this, "_eventsMap", new Map()); - - _defineProperty__default['default'](this, "_payloadsMap", new Map()); + _classCallCheck__default["default"](this, EventController); + _defineProperty__default["default"](this, "_eventsMap", new Map()); + _defineProperty__default["default"](this, "_payloadsMap", new Map()); } - - _createClass__default['default'](EventController, [{ + _createClass__default["default"](EventController, [{ key: "enableEvent", value: /** @@ -214,60 +198,57 @@ var EventController = /*#__PURE__*/function () { function enableEvent(event, emitter) { this._eventsMap.set(event, emitter); } + /** * Set an event payload and emit it the event. * * @param event - The event name. * @param payload - The payload. */ - }, { key: "emitEvent", value: function emitEvent(event, payload) { if (this.isEnabled(event)) { - this._payloadsMap.set(event, payload); // @ts-ignore - - + this._payloadsMap.set(event, payload); + // @ts-ignore this._eventsMap.get(event)(); } } + /** * Get the payload of the event. * * @param event - The event. * @returns - The payload. */ - }, { key: "getPayload", value: function getPayload(event) { return this._payloadsMap.get(event); } + /** * Returns if at least an event is enabled. * * @param event - The event. * @returns - If at least an event is enabled. */ - }, { key: "isEnabled", value: function isEnabled(event) { return this._eventsMap.has(event); } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._eventsMap.clear(); - this._payloadsMap.clear(); } }]); - return EventController; }(); @@ -281,12 +262,10 @@ var EventController = /*#__PURE__*/function () { */ var ItemAddController = /*#__PURE__*/function () { function ItemAddController() { - _classCallCheck__default['default'](this, ItemAddController); - - _defineProperty__default['default'](this, "_requests", []); + _classCallCheck__default["default"](this, ItemAddController); + _defineProperty__default["default"](this, "_requests", []); } - - _createClass__default['default'](ItemAddController, [{ + _createClass__default["default"](ItemAddController, [{ key: "useInit", value: /** @@ -295,13 +274,13 @@ var ItemAddController = /*#__PURE__*/function () { function useInit() { this._requests = []; } + /** * Emit the new items to the * components that made a request. * * @param items - The items. */ - }, { key: "emit", value: function emit(items) { @@ -309,61 +288,54 @@ var ItemAddController = /*#__PURE__*/function () { this._requests[i](items[i]); } } + /** * Request an item. * * @param cb - The callback. */ - }, { key: "requestItem", value: function requestItem(cb) { this._requests.push(cb); } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._requests = []; } }]); - return ItemAddController; }(); -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default['default'](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default['default'](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default['default'](this, result); }; } - +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - var isProduction = process.env.NODE_ENV === 'production'; -var prefix = 'Invariant failed'; // Invarianto instance +var prefix = 'Invariant failed'; +// Invarianto instance var Invariant = /*#__PURE__*/function (_Error) { - _inherits__default['default'](Invariant, _Error); - + _inherits__default["default"](Invariant, _Error); var _super = _createSuper(Invariant); - function Invariant(message) { var _this; - - _classCallCheck__default['default'](this, Invariant); - + _classCallCheck__default["default"](this, Invariant); _this = _super.call(this, message); _this.name = 'Invariant'; return _this; } + return _createClass__default["default"](Invariant); +}( /*#__PURE__*/_wrapNativeSuper__default["default"](Error)); - return Invariant; -}( /*#__PURE__*/_wrapNativeSuper__default['default'](Error)); // Throw an error if the condition fails - +// Throw an error if the condition fails function invariant(condition, message) { if (condition) { return; } - if (isProduction) { // In production we strip the message but still throw throw new Invariant(prefix); @@ -383,14 +355,11 @@ function invariant(condition, message) { */ var ItemRefController = /*#__PURE__*/function () { function ItemRefController() { - _classCallCheck__default['default'](this, ItemRefController); - - _defineProperty__default['default'](this, "_item", null); - - _defineProperty__default['default'](this, "_instance", {}); + _classCallCheck__default["default"](this, ItemRefController); + _defineProperty__default["default"](this, "_item", null); + _defineProperty__default["default"](this, "_instance", {}); } - - _createClass__default['default'](ItemRefController, [{ + _createClass__default["default"](ItemRefController, [{ key: "set", value: /** @@ -401,18 +370,18 @@ var ItemRefController = /*#__PURE__*/function () { */ function set(key, value) { if (this._item) { - addDecoration(this._item, _defineProperty__default['default']({}, key, value)); + addDecoration(this._item, _defineProperty__default["default"]({}, key, value)); } else { this._instance[key] = value; } } + /** * Get a decoration value from the item. * * @param key - The decoration key. * @returns - The decoration value. */ - }, { key: "get", value: function get(key) { @@ -422,21 +391,21 @@ var ItemRefController = /*#__PURE__*/function () { return this._instance[key]; } } + /** * Remove all the decorations from the item. */ - }, { key: "delete", value: function _delete() { if (this._item) removeDecorations(this._item); } + /** * Set the item in the controller. * * @param item - The item. */ - }, { key: "setItem", value: function setItem(item) { @@ -444,33 +413,33 @@ var ItemRefController = /*#__PURE__*/function () { addDecoration(this._item, this._instance); this._instance = {}; } + /** * Item getter. * * @returns - The item. */ - }, { key: "getItem", value: function getItem() { invariant(this._item !== null, 'The item has not been setted yet'); return this._item; } + /** * Returns if the item has been setted. * * @returns - If the item has been setted. */ - }, { key: "hasItem", value: function hasItem() { return this._item !== null; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -478,7 +447,6 @@ var ItemRefController = /*#__PURE__*/function () { this._instance = {}; } }]); - return ItemRefController; }(); @@ -490,12 +458,10 @@ var ItemRefController = /*#__PURE__*/function () { */ var ItemRemoveController = /*#__PURE__*/function () { function ItemRemoveController() { - _classCallCheck__default['default'](this, ItemRemoveController); - - _defineProperty__default['default'](this, "_itemsToRemove", []); + _classCallCheck__default["default"](this, ItemRemoveController); + _defineProperty__default["default"](this, "_itemsToRemove", []); } - - _createClass__default['default'](ItemRemoveController, [{ + _createClass__default["default"](ItemRemoveController, [{ key: "useInit", value: /** @@ -504,37 +470,36 @@ var ItemRemoveController = /*#__PURE__*/function () { function useInit() { this._itemsToRemove = []; } + /** * Request an item to be removed. * * @param item - The item to be removed. */ - }, { key: "removeItem", value: function removeItem(item) { this._itemsToRemove.push(item); } + /** * Return all the items to remove. */ - }, { key: "getItemsToRemove", value: function getItemsToRemove() { return this._itemsToRemove; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._itemsToRemove = []; } }]); - return ItemRemoveController; }(); @@ -557,49 +522,42 @@ var LayoutController = /*#__PURE__*/function () { /** Constructor. */ function LayoutController() { - _classCallCheck__default['default'](this, LayoutController); - - _defineProperty__default['default'](this, "_itemsToRefresh", void 0); - - _defineProperty__default['default'](this, "_itemsToShow", void 0); - - _defineProperty__default['default'](this, "_itemsToHide", void 0); - - _defineProperty__default['default'](this, "_isRendering", void 0); - + _classCallCheck__default["default"](this, LayoutController); + _defineProperty__default["default"](this, "_itemsToRefresh", void 0); + _defineProperty__default["default"](this, "_itemsToShow", void 0); + _defineProperty__default["default"](this, "_itemsToHide", void 0); + _defineProperty__default["default"](this, "_isRendering", void 0); this._itemsToRefresh = []; this._itemsToShow = []; this._itemsToHide = []; this._isRendering = false; } + /** * Init. */ - - - _createClass__default['default'](LayoutController, [{ + _createClass__default["default"](LayoutController, [{ key: "useInit", value: function useInit() { var _this = this; - // Items. this._itemsToRefresh = []; this._itemsToShow = []; - this._itemsToHide = []; // State. - - this._isRendering = true; // Change state. + this._itemsToHide = []; + // State. + this._isRendering = true; + // Change state. // eslint-disable-next-line - React.useEffect(function () { _this._isRendering = false; }); } + /** * Refresh an item. * * @param item - The item to refresh. */ - }, { key: "refreshItem", value: function refreshItem(item) { @@ -611,12 +569,13 @@ var LayoutController = /*#__PURE__*/function () { } else { // If the item is changing parent this // will get the right parent. - var grid = item.getGrid(); // The layout is managed here. - + var grid = item.getGrid(); + // The layout is managed here. grid.refreshItems([item]); grid.layout(); } } + /** * Set an item visibility. * @@ -624,7 +583,6 @@ var LayoutController = /*#__PURE__*/function () { * @param visible - The visibility. * @param instant - If the visibility change should happen without animations. */ - }, { key: "setItemVisibility", value: function setItemVisibility(item, visible, instant) { @@ -636,8 +594,8 @@ var LayoutController = /*#__PURE__*/function () { } else { // If the item is changing parent this // will get the right parent. - var grid = item.getGrid(); // The layout is managed here. - + var grid = item.getGrid(); + // The layout is managed here. if (visible) grid.show([item], { instant: instant });else grid.hide([item], { @@ -645,43 +603,43 @@ var LayoutController = /*#__PURE__*/function () { }); } } + /** * Get the items that have to be refreshed. * * @returns - The items. */ - }, { key: "getItemsToRefresh", value: function getItemsToRefresh() { return this._itemsToRefresh; } + /** * Get the items that have to be shown. * * @returns - The items. */ - }, { key: "getItemsToShow", value: function getItemsToShow() { return this._itemsToShow; } + /** * Get the items that have to be hidden. * * @returns - The items. */ - }, { key: "getItemsToHide", value: function getItemsToHide() { return this._itemsToHide; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -690,7 +648,6 @@ var LayoutController = /*#__PURE__*/function () { this._itemsToHide = []; } }]); - return LayoutController; }(); @@ -702,14 +659,11 @@ var LayoutController = /*#__PURE__*/function () { */ var FiberController = /*#__PURE__*/function () { function FiberController() { - _classCallCheck__default['default'](this, FiberController); - - _defineProperty__default['default'](this, "_fiber", void 0); - - _defineProperty__default['default'](this, "_flag", '0'); + _classCallCheck__default["default"](this, FiberController); + _defineProperty__default["default"](this, "_fiber", void 0); + _defineProperty__default["default"](this, "_flag", '0'); } - - _createClass__default['default'](FiberController, [{ + _createClass__default["default"](FiberController, [{ key: "useInit", value: /** @@ -719,58 +673,58 @@ var FiberController = /*#__PURE__*/function () { */ function useInit(gridElementRef) { var _this = this; - - this.updateFlag(); // eslint-disable-next-line - + this.updateFlag(); + // eslint-disable-next-line React.useEffect(function () { invariant(gridElementRef.current !== null); _this._fiber = getFiber(gridElementRef.current); }, []); // eslint-disable-line } + /** * Return the DOM elements in the chosen positions. * * @param orderedIndices - The positions. * @returns - The elements. */ - }, { key: "getStateNodes", value: function getStateNodes(orderedIndices) { - var stateNodes = []; // If there aren't indices retun an empty array. + var stateNodes = []; + // If there aren't indices retun an empty array. + if (orderedIndices.length === 0) return stateNodes; - if (orderedIndices.length === 0) return stateNodes; // The first child. + // The first child. + var child = getCurrentFiber(this._fiber, this._flag).child; - var child = getCurrentFiber(this._fiber, this._flag).child; // Fill the state nodes array. + // Fill the state nodes array. // We trust that the user input. - orderedIndices.forEach(function (index) { // @ts-ignore while (child.index !== index) { // @ts-ignore child = child.sibling; - } // @ts-ignore - + } + // @ts-ignore stateNodes.push(getStateNode(child)); }); return stateNodes; } + /** * Append an itemComponent fiber * (the same is done for the alternate if exists). * * @param child - The item. */ - }, { key: "append", value: function append(itemComponentFiber) { // Get the current fiber. - var fiber = getCurrentFiber(this._fiber, this._flag); // Append the fiber. - + var fiber = getCurrentFiber(this._fiber, this._flag); + // Append the fiber. appendFiber(fiber, itemComponentFiber); - if (fiber.alternate) { if (itemComponentFiber.alternate) { // Append the alternate. @@ -778,6 +732,7 @@ var FiberController = /*#__PURE__*/function () { } } } + /** * Remove an itemComponent fiber given the key of its Item * (The same is done for the alternate if exists). @@ -785,48 +740,45 @@ var FiberController = /*#__PURE__*/function () { * @param key - The key of the item. * @returns - The removed item. */ - }, { key: "remove", value: function remove(key) { // Get the current fiber. - var fiber = getCurrentFiber(this._fiber, this._flag); // Remove the fiber. - + var fiber = getCurrentFiber(this._fiber, this._flag); + // Remove the fiber. var removedChild = removeChild(fiber, key); - if (fiber.alternate) { if (removedChild.alternate) { // Remove the alternate. removeChild(fiber.alternate, key); } } - return removedChild; } + /** * Return the props containing the flag value to add in the grid element. * * @returns - The props. */ - }, { key: "getFlagProp", value: function getFlagProp() { - return _defineProperty__default['default']({}, FlagProp, this._flag); + return _defineProperty__default["default"]({}, FlagProp, this._flag); } + /** * Update the flag value. */ - }, { key: "updateFlag", value: function updateFlag() { if (this._flag === '0') this._flag = '1';else this._flag = '0'; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -834,29 +786,30 @@ var FiberController = /*#__PURE__*/function () { this._fiber = null; } }]); - return FiberController; }(); + /** * The flag prop name. */ - var FlagProp = 'muuri-react-flag'; + /** * Get the fiber of the given grid element. * * @param grid - The element. * @return - The fiber node. */ - function getFiber(grid) { var key = Object.keys(grid).find(function (key) { return key.startsWith('__reactInternalInstance$') || key.startsWith('__reactFiber$'); }); - invariant(typeof key === 'string', 'Cannot find the __reactInternalInstance$'); // @ts-ignore + invariant(typeof key === 'string', 'Cannot find the __reactInternalInstance$'); + // @ts-ignore return grid[key]; } + /** * Return the current fiber. * Try to use the prop flag for the search first, @@ -872,37 +825,40 @@ function getFiber(grid) { * @param flag - the flag. * @returns - The current fiber. */ - - function getCurrentFiber(fiber, currentFlag) { - if (!fiber.alternate) return fiber; // Flags. + if (!fiber.alternate) return fiber; + // Flags. var fiberFlag = fiber.memoizedProps[FlagProp]; - var alternateFlag = fiber.alternate.memoizedProps[FlagProp]; // If the two flags are the same it should mean that + var alternateFlag = fiber.alternate.memoizedProps[FlagProp]; + + // If the two flags are the same it should mean that // in at least one of the items there has been a re-render // from the last render of the GridComponent. // We can no longer trust the flag prop and we have // to look for the RootFiber and check which // fiber is in the current tree. - if (fiberFlag === alternateFlag) { - var topFiber = fiber; // Get the top fiber - // (Not the RootFiber). + var topFiber = fiber; + // Get the top fiber + // (Not the RootFiber). while (topFiber["return"]) { topFiber = topFiber["return"]; - } // Fibers. - + } + // Fibers. var rootFiber = topFiber.stateNode; - var topCurrentFiber = rootFiber.current; // The current fiber. + var topCurrentFiber = rootFiber.current; + // The current fiber. return topCurrentFiber === topFiber ? fiber : fiber.alternate; - } // If we got here we can trust the flag prop to find the current Fiber. - + } + // If we got here we can trust the flag prop to find the current Fiber. return fiberFlag === currentFlag ? fiber : fiber.alternate; } + /** * Returns the first stateNode among the descendants * of the given itemComponent Fiber. @@ -910,51 +866,44 @@ function getCurrentFiber(fiber, currentFlag) { * @param itemComponentFiber - The fiber. * @returns - The element. */ - - function getStateNode(itemComponentFiber) { // ItemComponent -> ItemProvider -> Item. - var itemFiber = itemComponentFiber.child.child; // @ts-ignore - - while (!(itemFiber.stateNode instanceof HTMLElement)) { - // @ts-ignore - itemFiber = itemFiber.child; - } - + var itemFiber = itemComponentFiber.child.child; + // @ts-ignore + while (!(itemFiber.stateNode instanceof HTMLElement)) + // @ts-ignore + itemFiber = itemFiber.child; return itemFiber.stateNode; } + /** * Append the child fiber in the last position among the children of the parent fiber. * * @param parent - The parent fiber. * @param child - The child fiber. */ - - function appendFiber(parent, child) { var _parent$return; - if (!parent.child) { // If it has no child. parent.child = child; child.index = 0; } else { var c = parent.child; - while (c.sibling) { c = c.sibling; } - - child.index = c.index + 1; // Inserted as last child. - + child.index = c.index + 1; + // Inserted as last child. c.sibling = child; - } // Update the references. - - - child["return"] = parent; // If we are in development. + } + // Update the references. + child["return"] = parent; + // If we are in development. if (child._debugOwner) child._debugOwner = (_parent$return = parent["return"]) === null || _parent$return === void 0 ? void 0 : _parent$return["return"]; } + /** * Remove a child with the given key from the fiber. * @@ -962,76 +911,71 @@ function appendFiber(parent, child) { * @param key - The key of the item. * @return - The removed fiber. */ - - function removeChild(parent, key) { var child = parent.child; - var removedChild; // @ts-ignore + var removedChild; + // @ts-ignore if (hasNot(child, key)) { // @ts-ignore while (hasNot(child.sibling, key)) { // @ts-ignore child = child.sibling; - } // @ts-ignore - - - removedChild = removeSibling(child); // @ts-ignore - + } + // @ts-ignore + removedChild = removeSibling(child); + // @ts-ignore adjustIndices(child); } else { - removedChild = removeFirstChild(parent); // @ts-ignore - + removedChild = removeFirstChild(parent); + // @ts-ignore child = child.sibling; if (child) adjustIndices(child); } - removedChild.sibling = null; return removedChild; } + /** * Remove the first itemComponent fiber of a gridELement fiber and return it. * * @param GridElementFiber - The gridELement fiber. * @return - The removed itemComponent fiber. */ - - function removeFirstChild(gridElementFiber) { - var removed = gridElementFiber.child; // @ts-ignore - - gridElementFiber.child = gridElementFiber.child.sibling; // @ts-ignore - + var removed = gridElementFiber.child; + // @ts-ignore + gridElementFiber.child = gridElementFiber.child.sibling; + // @ts-ignore return removed; } + /** * Remove the first sibling from a itemComponent fiber and return it. * * @param fiber - The fiber. * @return - The removed sibling. */ - - function removeSibling(fiber) { - var removed = fiber.sibling; // @ts-ignore - - fiber.sibling = fiber.sibling.sibling; // @ts-ignore - + var removed = fiber.sibling; + // @ts-ignore + fiber.sibling = fiber.sibling.sibling; + // @ts-ignore return removed; } + /** * Adjust the indices of the siblings of an itemComponent fiber. * * @param itemComponentFiber - The itemComponent fiber. */ - - function adjustIndices(itemComponentFiber) { while (itemComponentFiber.sibling) { itemComponentFiber.sibling.index = itemComponentFiber.index + 1; itemComponentFiber = itemComponentFiber.sibling; } } + /** * Returns if the itemComponent fiber is not the parent of the item with the given key. * @@ -1039,8 +983,6 @@ function adjustIndices(itemComponentFiber) { * @param key - The key of the item. * @return - If the itemComponent fiber is not the parent of the item with the given key. */ - - function hasNot(itemComponentFiber, key) { // ItemComponent -> ItemProvider -> Item. return itemComponentFiber.child.child.key !== key; @@ -1055,18 +997,13 @@ function hasNot(itemComponentFiber, key) { */ var ChildrenController = /*#__PURE__*/function () { function ChildrenController() { - _classCallCheck__default['default'](this, ChildrenController); - - _defineProperty__default['default'](this, "_oldChildrenArray", []); - - _defineProperty__default['default'](this, "_children", []); - - _defineProperty__default['default'](this, "_indicesToAdd", []); - - _defineProperty__default['default'](this, "_dragCounter", 0); + _classCallCheck__default["default"](this, ChildrenController); + _defineProperty__default["default"](this, "_oldChildrenArray", []); + _defineProperty__default["default"](this, "_children", []); + _defineProperty__default["default"](this, "_indicesToAdd", []); + _defineProperty__default["default"](this, "_dragCounter", 0); } - - _createClass__default['default'](ChildrenController, [{ + _createClass__default["default"](ChildrenController, [{ key: "useInit", value: /** @@ -1077,55 +1014,57 @@ var ChildrenController = /*#__PURE__*/function () { function useInit(newChildren) { // @ts-ignore // We need to ensure that the children are in an array. - var newChildrenArray = React.Children.toArray(newChildren); // The indices to add. + var newChildrenArray = React.Children.toArray(newChildren); + + // The indices to add. + this._indicesToAdd = getIndicesToAdd(newChildrenArray, this._oldChildrenArray); - this._indicesToAdd = getIndicesToAdd(newChildrenArray, this._oldChildrenArray); // The _children will be used to map all + // The _children will be used to map all // the child in the render method. // We can't use the ChildrenArray because we need the users // key provided in the components and not the escaped one (e.g. .$1). - this._children = newChildren || []; this._oldChildrenArray = newChildrenArray; } + /** * Remove a child in the given position and return it. * * @param index - The index of the child to remove. * @returns - The removed child. */ - }, { key: "remove", value: function remove(index) { return this._oldChildrenArray.splice(index, 1)[0]; } + /** * Append a child in the children array. * * @param child - The child to append. */ - }, { key: "append", value: function append(child) { this._oldChildrenArray.push(child); } + /** * Returns the ordered array of indices of the added children. */ - }, { key: "getIndicesToAdd", value: function getIndicesToAdd() { return this._indicesToAdd; } + /** * Map all the children. * * @param cb - The callback. * @returns - The mapped children. */ - }, { key: "render", value: function render(cb) { @@ -1134,10 +1073,12 @@ var ChildrenController = /*#__PURE__*/function () { // there are rare cases where the keys are not indispensable, // the user may not choose to use at his own risk. return cb(child, child.key); - }); // Flush the children. + }); + // Flush the children. this.flush(); return children; + /** // If an item is being dragged we need to ensure // that no child is inserted before it. @@ -1146,46 +1087,46 @@ var ChildrenController = /*#__PURE__*/function () { : getChildrenInSafePositions(children, this._indicesToAdd); */ } + /** * Increment the drag counter. */ - }, { key: "incrementDragCounter", value: function incrementDragCounter() { this._dragCounter += 1; } + /** * Decrement the drag counter. */ - }, { key: "decrementDragCounter", value: function decrementDragCounter() { this._dragCounter -= 1; } + /** * Remove the current children so they can be garbage collected. */ - }, { key: "flush", value: function flush() { this._children = []; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this.flush(); } }]); - return ChildrenController; }(); + /** * Return an array of positions of the added children. * The algorithm is optimized for cases where the order of @@ -1196,15 +1137,12 @@ var ChildrenController = /*#__PURE__*/function () { * @param oldChildren - The old children. * @return - The indices. */ - function getIndicesToAdd(newChildren, oldChildren) { var indicesToAdd = []; var oIndex = 0; - for (var nIndex = 0; nIndex < newChildren.length; nIndex++) { // Finde the index. var index = findIndex(oldChildren, newChildren[nIndex], oIndex); - if (index === -1) { // If it is not present is a new Child. indicesToAdd.push(nIndex); @@ -1214,9 +1152,9 @@ function getIndicesToAdd(newChildren, oldChildren) { oIndex = index; } } - return indicesToAdd; } + /** * Returns the index of the child in the children array, * if it is not present returns -1. @@ -1227,22 +1165,23 @@ function getIndicesToAdd(newChildren, oldChildren) { * @param fromIndex - The initial index. * @returns - The index of the child. */ - function findIndex(children, child, fromIndex) { - fromIndex = fromIndex > children.length ? children.length : fromIndex; // If the heuristics are respected the child will be here. + fromIndex = fromIndex > children.length ? children.length : fromIndex; + // If the heuristics are respected the child will be here. for (var index = fromIndex; index < children.length; index++) { if (is(child, children[index])) return index; - } // If the child is here the heuristics are not respected. - + } + // If the child is here the heuristics are not respected. for (var _index = 0; _index < fromIndex; _index++) { if (is(child, children[_index])) return _index; - } // The child is not present. - + } + // The child is not present. return -1; } + /** * There would be the risk that a component will be inserted before * an item that is being dragged (and that is placed in a drag @@ -1281,8 +1220,6 @@ function getChildrenInSafePositions( * @param componentB - The second component. * @returns - If they have the same key. */ - - function is(componentA, componentB) { return componentA.key === componentB.key; } @@ -1294,18 +1231,21 @@ function is(componentA, componentB) { * @param grid - The Muuri instance. */ function fillGrid(grid) { - var sizerElement = document.createElement('div'); // Keep the element hidden. + var sizerElement = document.createElement('div'); + // Keep the element hidden. sizerElement.style.visibility = 'hidden'; - sizerElement.style.position = 'absolute'; // Add the class. - - sizerElement.classList.add('grid-sizer'); // Set the element. + sizerElement.style.position = 'absolute'; + // Add the class. + sizerElement.classList.add('grid-sizer'); + // Set the element. addDecoration(grid, { sizerElement: sizerElement }); - var gridElement = grid.getElement(); // Insert as first child. + var gridElement = grid.getElement(); + // Insert as first child. if (gridElement.children.length === 0) { gridElement.appendChild(sizerElement); } else { @@ -1315,6 +1255,7 @@ function fillGrid(grid) { // Allowed position values. var positions = ['relative', 'absolute', 'fixed']; + /** * Fill a grid element: * - If it is not position the style.position is setted to "relative". @@ -1327,26 +1268,25 @@ var positions = ['relative', 'absolute', 'fixed']; * @param gridElement - The element to fill. * @param gridClass - The Css class of the grid element. */ - function fillGridElement(gridElement, gridClass) { - var position = getComputedStyle(gridElement).position; // Set the default position. + var position = getComputedStyle(gridElement).position; + // Set the default position. if (!positions.includes(position)) { gridElement.style.position = positions[0]; - } // Set the grid class. - + } - gridElement.classList.add(gridClass); // Ensure that the grid class can't be removed. + // Set the grid class. + gridElement.classList.add(gridClass); + // Ensure that the grid class can't be removed. var defaultSetAttribute = gridElement.setAttribute.bind(gridElement); - gridElement.setAttribute = function setAttribute(attribute, value) { if (attribute === 'class') { - var classNames = (gridElement.getAttribute('class') || '').split(' '); // Add the grid class. - + var classNames = (gridElement.getAttribute('class') || '').split(' '); + // Add the grid class. if (!classNames.includes(gridClass)) value = "".concat(value, " ").concat(gridClass); } - defaultSetAttribute(attribute, value); }; } @@ -1358,18 +1298,18 @@ function fillGridElement(gridElement, gridClass) { * * @param item - The item to fill. */ - function fillItem(item) { addDecoration(item, { props: {}, data: {} - }); // Change the sort data. - + }); + // Change the sort data. Object.defineProperty(item, '_sortData', { get: function get() { return this.getData(); }, - set: function set() {// nothing to do here. + set: function set() { + // nothing to do here. } }); } @@ -1386,20 +1326,20 @@ function fillItem(item) { * @param itemClasses - The Css classes of the items. */ function fillItemElement(itemElement, itemClasses) { - itemElement.style.position = 'absolute'; // Ensure that the Css item classes are not removed. + itemElement.style.position = 'absolute'; + // Ensure that the Css item classes are not removed. var defaultSetAttribute = itemElement.setAttribute.bind(itemElement); - itemElement.setAttribute = function setAttribute(attribute, value) { if (attribute === 'class') { var classNames = (itemElement.getAttribute('class') || '').split(' '); var classNamesToAdd = classNames.filter(function (className) { return itemClasses.includes(className); - }); // Add the Css items classes. + }); + // Add the Css items classes. value = "".concat(value, " ").concat(classNamesToAdd.join(' ')); } - defaultSetAttribute(attribute, value); }; } @@ -1412,7 +1352,6 @@ function fillItemElement(itemElement, itemClasses) { * @param callback - The function to memoize. * @returns - The memoized function. */ - function useFunction(callback) { return React.useRef(callback).current; } @@ -1424,17 +1363,19 @@ function useFunction(callback) { * @param dependencyList - The dependencyList. * @returns - If the dependencyList is changed from the previous render. */ - function useReference(dependencyList) { - var ref = React.useRef(dependencyList); // If it is the first call return true. - - if (ref.current === dependencyList) return true; // Compare the dependencyLists. + var ref = React.useRef(dependencyList); - var didUpdate = compare(ref.current, dependencyList); // Keep the reference of the new one. + // If it is the first call return true. + if (ref.current === dependencyList) return true; + // Compare the dependencyLists. + var didUpdate = compare(ref.current, dependencyList); + // Keep the reference of the new one. ref.current = dependencyList; return didUpdate; } + /** * Compare two dependencyLists and return if they are different. * @@ -1442,14 +1383,11 @@ function useReference(dependencyList) { * @param b - The second dependencyList to compare. * @returns - If the 2 dependencyLists are different. */ - function compare(a, b) { if (a.length !== b.length) return true; - for (var i = 0; i < a.length; i++) { if (a[i] !== b[i]) return true; } - return false; } @@ -1459,18 +1397,18 @@ function compare(a, b) { * @param didUpdate - The method to run. * @param deps - The dependecies. */ - function useInstantEffect(didUpdate, deps) { // Deps check. var needUpdate = useReference(deps); - var cleanUpRef = React.useRef(); // Run. + var cleanUpRef = React.useRef(); + // Run. if (needUpdate) { if (cleanUpRef.current) cleanUpRef.current(); cleanUpRef.current = didUpdate(); - } // Catch unmount. - + } + // Catch unmount. React.useEffect(function () { return function () { if (cleanUpRef.current) cleanUpRef.current(); @@ -1486,14 +1424,11 @@ function useInstantEffect(didUpdate, deps) { * @param factory - The factory method. * @returns - The memoized value. */ - function useMemoized(factory) { var valueRef = React.useRef(); - if (!valueRef.current) { valueRef.current = factory(); } - return valueRef.current; } @@ -1503,7 +1438,6 @@ function useMemoized(factory) { * * @returns - The re-render method. */ - function useRerender() { var setState = React.useState()[1]; return useFunction(function () { @@ -1516,92 +1450,102 @@ function useRerender() { // Item component. function ItemComponent(_ref) { var child = _ref.children, - itemClasses = _ref.itemClasses, - itemAddController = _ref.itemAddController, - itemRemoveController = _ref.itemRemoveController, - propsToData = _ref.propsToData, - itemKey = _ref.itemKey, - grid = _ref.grid; + itemClasses = _ref.itemClasses, + itemAddController = _ref.itemAddController, + itemRemoveController = _ref.itemRemoveController, + propsToData = _ref.propsToData, + itemKey = _ref.itemKey, + grid = _ref.grid; // The store provided doesn't change the reference. var store = useMemoized(function () { // Create the controllers. var eventController = new EventController(); - var itemRefController = new ItemRefController(); // Add the data that won't change. - + var itemRefController = new ItemRefController(); + // Add the data that won't change. itemRefController.set('key', itemKey); - itemRefController.set('eventController', eventController); // Return the controllers. - + itemRefController.set('eventController', eventController); + // Return the controllers. return { eventController: eventController, itemRefController: itemRefController, itemRemoveController: itemRemoveController, grid: grid }; - }); // Set the props. + }); + // Set the props. store.itemRefController.set('props', child.props); store.itemRemoveController = itemRemoveController; - store.grid = grid; // Set the data. + store.grid = grid; + // Set the data. if (propsToData) { // Get the data. - var data = propsToData(child.props); // Must be an object. + var data = propsToData(child.props); - invariant(_typeof__default['default'](data) === 'object', "The data returned by 'propsToData' must be an object, founded ".concat(_typeof__default['default'](data))); // Set the data. + // Must be an object. + invariant(_typeof__default["default"](data) === 'object', "The data returned by 'propsToData' must be an object, founded ".concat(_typeof__default["default"](data))); + // Set the data. store.itemRefController.set('data', data); - } // On mount. - + } + // On mount. React.useEffect(function () { // Request the item. itemAddController.requestItem(function (item) { - fillItem(item); // @ts-ignore - + fillItem(item); + // @ts-ignore fillItemElement(item.getElement(), itemClasses); store.itemRefController.setItem(item); }); return function () { // The item. var item = store.itemRefController.getItem(); - invariant(item !== null); // The element. + invariant(item !== null); + // The element. var element = item.getElement(); - invariant(element !== undefined); // If the item is going to be unmounted + invariant(element !== undefined); + + // If the item is going to be unmounted // and it is being dragged it have to end the event // (Because it could be child of a different DOM element). - if (item.isDragging()) { element.style.display = 'none'; - element.style.visibility = 'hidden'; // @ts-ignore + element.style.visibility = 'hidden'; + // @ts-ignore if (item._drag) item._drag.destroy(); store.grid.getElement().appendChild(element); - } // Remove the item. - + } + // Remove the item. store.itemRefController["delete"](); - store.itemRemoveController.removeItem(item); // Destroy the controllers instances. + store.itemRemoveController.removeItem(item); + // Destroy the controllers instances. store.itemRefController.destroy(); store.eventController.destroy(); }; }, []); // eslint-disable-line - // Render. - return /*#__PURE__*/React__default['default'].createElement(ItemProvider, { + // Render. + return /*#__PURE__*/React__default["default"].createElement(ItemProvider, { value: store }, child); -} // PropTypes. +} +// PropTypes. ItemComponent.propTypes = { - itemAddController: PropTypes__default['default'].object.isRequired, - itemClasses: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string.isRequired).isRequired, - propsToData: PropTypes__default['default'].func, - children: PropTypes__default['default'].element.isRequired, - grid: PropTypes__default['default'].instanceOf(Muuri__default['default']).isRequired -}; // Display name. + itemAddController: PropTypes__default["default"].object.isRequired, + itemClasses: PropTypes__default["default"].arrayOf(PropTypes__default["default"].string.isRequired).isRequired, + propsToData: PropTypes__default["default"].func, + children: PropTypes__default["default"].element.isRequired, + grid: PropTypes__default["default"].instanceOf(Muuri__default["default"]).isRequired +}; +// Display name. ItemComponent.displayName = 'ItemComponent'; /** @@ -1620,10 +1564,10 @@ function addItems(grid, addedDOMItems, indicesToAdd, addOptions, filter) { index: indicesToAdd[i], layout: false }); - } // Show the added items (usefull just if the items are - // hidden by default and the filter is not setted). - + } + // Show the added items (usefull just if the items are + // hidden by default and the filter is not setted). if (!filter && addOptions !== null && addOptions !== void 0 && addOptions.show) { grid.show(grid.getItems(indicesToAdd), { layout: false @@ -1647,13 +1591,13 @@ function filterItems(grid, predicate) { /** Class name. */ var gridClassName = 'containerClass'; + /** * Returns the Css class of the grid element. * * @param grid - The Muuri instance. * @returns - The class. */ - function getGridClass(grid) { // @ts-ignore return grid._settings[gridClassName]; @@ -1661,13 +1605,13 @@ function getGridClass(grid) { /** Class names. */ var itemClassNames = ['itemClass', 'itemVisibleClass', 'itemHiddenClass', 'itemPositioningClass', 'itemDraggingClass', 'itemReleasingClass', 'itemPlaceholderClass']; + /** * Returns the items classes. * * @param grid - The Muuri instance. * @returns - The classes. */ - function getItemClasses(grid) { // @ts-ignore return itemClassNames.map(function (className) { @@ -1712,10 +1656,8 @@ function showItems(grid, items) { }); } -function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - +function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * Sort the items. * @@ -1728,22 +1670,24 @@ function sortItems(grid, predicate, sortOptions) { // @ts-ignore sortOptions = _objectSpread$1(_objectSpread$1({}, sortOptions || {}), {}, { layout: false - }); // Handle a function. + }); + // Handle a function. if (typeof predicate === 'function') { handleFunction(grid, predicate, sortOptions); - } // Handle a string. - + } + // Handle a string. if (typeof predicate === 'string') { handleString(grid, predicate, sortOptions); - } // Hanndle an array of keys. - + } + // Hanndle an array of keys. if (Array.isArray(predicate)) { handleArray(grid, predicate, sortOptions); } } + /** * Sort the items given a predicate function. * @@ -1751,12 +1695,12 @@ function sortItems(grid, predicate, sortOptions) { * @param predicate - The predicate function. * @param sortOptions - The sort options. */ - function handleFunction(grid, predicate, sortOptions) { grid.sort(function (itemA, itemB) { return predicate(itemA.getData(), itemB.getData(), itemA, itemB); }, sortOptions); } + /** * Sort the items given a predicate string. * @@ -1764,11 +1708,10 @@ function handleFunction(grid, predicate, sortOptions) { * @param predicate - The predicate string. * @param sortOptions - The sort options. */ - - function handleString(grid, predicate, sortOptions) { grid.sort(predicate, sortOptions); } + /** * Sort the items given an array of keys. * If the key has a match, the item is inserted in that position, otherwise at the bottom. @@ -1777,29 +1720,29 @@ function handleString(grid, predicate, sortOptions) { * @param predicate - The array of keys. * @param sortOptions - The sort options. */ - - function handleArray(grid, predicate, sortOptions) { - var items = grid.getItems(); // Items that can be sorted. - - var sortedItems = []; // Items that can't be sorted. - - var otherItems = []; // Fills the arrays. + var items = grid.getItems(); + // Items that can be sorted. + var sortedItems = []; + // Items that can't be sorted. + var otherItems = []; + // Fills the arrays. items.forEach(function (item) { var itemKey = item._component.key; var index = predicate.findIndex(function (key) { return key === itemKey; }); - if (index > -1) { sortedItems[index] = item; } else { otherItems.push(item); } - }); // Sort. + }); - grid.sort(Array.prototype.concat( // Some position can be empty. + // Sort. + grid.sort(Array.prototype.concat( + // Some position can be empty. sortedItems.filter(function (item) { return !!item; }), otherItems), sortOptions); @@ -1810,30 +1753,28 @@ function handleArray(grid, predicate, sortOptions) { // Grid component. function GridComponent(_ref) { var children = _ref.children, - gridProps = _ref.gridProps, - grid = _ref.grid, - filter = _ref.filter, - sort = _ref.sort, - sortOptions = _ref.sortOptions, - addOptions = _ref.addOptions, - propsToData = _ref.propsToData, - onSend = _ref.onSend, - onDragStart = _ref.onDragStart, - onDragEnd = _ref.onDragEnd, - onFilter = _ref.onFilter, - onSort = _ref.onSort, - onMount = _ref.onMount, - onUnmount = _ref.onUnmount, - forceSync = _ref.forceSync, - dragFixed = _ref.dragFixed, - dragEnabled = _ref.dragEnabled, - instantLayout = _ref.instantLayout; - + gridProps = _ref.gridProps, + grid = _ref.grid, + filter = _ref.filter, + sort = _ref.sort, + sortOptions = _ref.sortOptions, + addOptions = _ref.addOptions, + propsToData = _ref.propsToData, + onSend = _ref.onSend, + onDragStart = _ref.onDragStart, + onDragEnd = _ref.onDragEnd, + onFilter = _ref.onFilter, + onSort = _ref.onSort, + onMount = _ref.onMount, + onUnmount = _ref.onUnmount, + forceSync = _ref.forceSync, + dragFixed = _ref.dragFixed, + dragEnabled = _ref.dragEnabled, + instantLayout = _ref.instantLayout; /* ------------------ */ - /* ----- STORES ----- */ - /* ------------------ */ + // Store references of objects // generated in previous renders. var store = useMemoized(function () { @@ -1841,31 +1782,16 @@ function GridComponent(_ref) { // Grid and items data. gridRef: /*#__PURE__*/ - /* */ React.createRef(), - gridClass: - /* */ - getGridClass(grid), - itemClasses: - /* */ - getItemClasses(grid), + gridClass: /* */getGridClass(grid), + itemClasses: /* */getItemClasses(grid), // Controllers. - childrenController: - /* */ - new ChildrenController(), - fiberController: - /* */ - new FiberController(), - itemAddController: - /* */ - new ItemAddController(), - itemRemoveController: - /* */ - new ItemRemoveController(), - layoutController: - /* */ - new LayoutController(), + childrenController: /* */new ChildrenController(), + fiberController: /* */new FiberController(), + itemAddController: /* */new ItemAddController(), + itemRemoveController: /* */new ItemRemoveController(), + layoutController: /* */new LayoutController(), // Events. onUnmount: onUnmount, onDragStart: onDragStart, @@ -1874,73 +1800,46 @@ function GridComponent(_ref) { onSort: onSort, onSend: onSend }; - }); // Store references of objects + }); + + // Store references of objects // that are used inside useEffect. // The references are flushed on each new render. - var vars = { // Items data. - indicesToAdd: - /* */ - [], - addedDOMItems: - /* */ - [], - itemsToRemove: - /* */ - [], - itemsToRefresh: - /* */ - [], - itemsToShow: - /* */ - [], - itemsToHide: - /* */ - [], + indicesToAdd: /* */[], + addedDOMItems: /* */[], + itemsToRemove: /* */[], + itemsToRefresh: /* */[], + itemsToShow: /* */[], + itemsToHide: /* */[], // Items flags. - hasAdded: - /* */ - false, - hasRemoved: - /* */ - false, - hasFiltered: - /* */ - false, - hasSorted: - /* */ - false, - hasRefreshed: - /* */ - false, - hasShown: - /* */ - false, - hasHidden: - /* */ - false + hasAdded: /* */false, + hasRemoved: /* */false, + hasFiltered: /* */false, + hasSorted: /* */false, + hasRefreshed: /* */false, + hasShown: /* */false, + hasHidden: /* */false }; - /* ----------------- */ + /* ----------------- */ /* ----- MOUNT ----- */ - /* ----------------- */ - // Initialize the grid on mount. + // Initialize the grid on mount. React.useEffect(function () { /* ------------------ */ - /* ----- EVENTS ----- */ - /* ------------------ */ + // Add all the event handlers. - grid // "Send" and "receive" events. + grid + // "Send" and "receive" events. .on('beforeSend', function (_ref2) { var item = _ref2.item, - fromGrid = _ref2.fromGrid, - fromIndex = _ref2.fromIndex; - + fromGrid = _ref2.fromGrid, + fromIndex = _ref2.fromIndex; if (!getDecoration(item).sentPayload) { // Generate the sentPayload. var sentPayload = { @@ -1948,23 +1847,25 @@ function GridComponent(_ref) { fromFiberController: store.fiberController, fromGrid: fromGrid, fromIndex: fromIndex - }; // Add the decoration. + }; + // Add the decoration. addDecoration(item, { sentPayload: sentPayload }); } }).on('receive', function (_ref3) { var item = _ref3.item, - toGrid = _ref3.toGrid, - toIndex = _ref3.toIndex; + toGrid = _ref3.toGrid, + toIndex = _ref3.toIndex; // Controllers. var toChildrenController = store.childrenController; - var toFiberController = store.fiberController; // If the method is activated by user interaction (the item is being dragged) + var toFiberController = store.fiberController; + + // If the method is activated by user interaction (the item is being dragged) // the synchronization will be performed during the "dragEnd" event. // If the method is called via Muuri's instance (the item is not being dragged) // the synchronization takes place here, but the onSend callback is not fired. - if (item.isDragging()) { // Generate the receivedPayload. var receivedPayload = { @@ -1972,82 +1873,95 @@ function GridComponent(_ref) { toFiberController: toFiberController, toGrid: toGrid, toIndex: toIndex - }; // Add the decoration. + }; + // Add the decoration. addDecoration(item, { receivedPayload: receivedPayload }); } else { // Payloads data. - var sentPayload = getDecoration(item).sentPayload; // The payload must have been created in the send method. - - invariant(sentPayload !== null && _typeof__default['default'](sentPayload) === 'object'); // Controllers. - + var sentPayload = getDecoration(item).sentPayload; + // The payload must have been created in the send method. + invariant(sentPayload !== null && _typeof__default["default"](sentPayload) === 'object'); + // Controllers. var fromChildrenController = sentPayload.fromChildrenController, - fromFiberController = sentPayload.fromFiberController; // Remove the payload. + fromFiberController = sentPayload.fromFiberController; + // Remove the payload. addDecoration(item, { sentPayload: null - }); // Remove the item instances from the old GridComponent. + }); + // Remove the item instances from the old GridComponent. var itemFiber = fromFiberController.remove(item.getKey()); - var itemComponent = fromChildrenController.remove(itemFiber.index); // Add the item instances to the new GridComponent. + var itemComponent = fromChildrenController.remove(itemFiber.index); + // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); toChildrenController.append(itemComponent); - } // Emit the "send" event. - + } + // Emit the "send" event. getDecoration(item).eventController.emitEvent('send', grid); - }) // Drag events. + }) + + // Drag events. .on('dragInit', function (item, event) { // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. - store.childrenController.incrementDragCounter(); // Emit the "drag" event. + store.childrenController.incrementDragCounter(); + // Emit the "drag" event. // This event is used instead of "dragStart" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). - - getDecoration(item).eventController.emitEvent('drag', true); // "onDragStart" Callback. - + getDecoration(item).eventController.emitEvent('drag', true); + // "onDragStart" Callback. if (store.onDragStart) store.onDragStart(item, event); }).on('dragEnd', function (item) { // Payloads. var sentPayload = getDecoration(item).sentPayload; - var receivedPayload = getDecoration(item).receivedPayload; // If an item was sent during the drag the - // GridComponents are synchronized. + var receivedPayload = getDecoration(item).receivedPayload; + // If an item was sent during the drag the + // GridComponents are synchronized. if (sentPayload && receivedPayload) { // SentPayload data. var fromChildrenController = sentPayload.fromChildrenController, - fromFiberController = sentPayload.fromFiberController, - fromGrid = sentPayload.fromGrid, - fromIndex = sentPayload.fromIndex; // ReceivedPayload data. + fromFiberController = sentPayload.fromFiberController, + fromGrid = sentPayload.fromGrid, + fromIndex = sentPayload.fromIndex; + // ReceivedPayload data. var toChildrenController = receivedPayload.toChildrenController, - toFiberController = receivedPayload.toFiberController, - toGrid = receivedPayload.toGrid, - toIndex = receivedPayload.toIndex; // Reset the payloads. + toFiberController = receivedPayload.toFiberController, + toGrid = receivedPayload.toGrid, + toIndex = receivedPayload.toIndex; + // Reset the payloads. addDecoration(item, { sentPayload: null, receivedPayload: null - }); // Check if the item has been sended. + }); + // Check if the item has been sended. if (fromGrid !== toGrid) { // "onSend" will be called with the receive event. - invariant(typeof store.onSend === 'function', 'An item cannot be sent to another MuuriComponent if the ' + "'onSend' property has not been passed to the MuuriComponent."); // Remove the item instances from the old GridComponent. + invariant(typeof store.onSend === 'function', 'An item cannot be sent to another MuuriComponent if the ' + "'onSend' property has not been passed to the MuuriComponent."); + // Remove the item instances from the old GridComponent. var itemFiber = fromFiberController.remove(item.getKey()); - var itemComponent = fromChildrenController.remove(itemFiber.index); // Add the item instances to the new GridComponent. + var itemComponent = fromChildrenController.remove(itemFiber.index); + // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); - toChildrenController.append(itemComponent); // "onSend" callback. + toChildrenController.append(itemComponent); + + // "onSend" callback. // DragEnd is called in the grid where // the drag start, so onSend. - store.onSend({ // The key the user has set. key: getDecoration(item).key, @@ -2068,25 +1982,27 @@ function GridComponent(_ref) { // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. - store.childrenController.decrementDragCounter(); // Emit the event. + store.childrenController.decrementDragCounter(); + // Emit the event. // This event is used instead of "dragEnd" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). - - getDecoration(item).eventController.emitEvent('drag', false); // Call the event. - + getDecoration(item).eventController.emitEvent('drag', false); + // Call the event. if (store.onDragEnd) store.onDragEnd(item); - }) // Show and hide events. + }) + + // Show and hide events. .on('showStart', function (items) { // The items could be shown before they are decorated. - if (!isDecorated(items[0])) return; // Emit the event. - + if (!isDecorated(items[0])) return; + // Emit the event. items.forEach(function (item) { - var eventController = getDecoration(item).eventController; // The event is triggered also for items that have not + var eventController = getDecoration(item).eventController; + // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. - if (eventController.getPayload('show') !== true) { eventController.emitEvent('show', true); } @@ -2094,43 +2010,45 @@ function GridComponent(_ref) { }).on('hideEnd', function (items) { // Emit the event. items.forEach(function (item) { - var eventController = getDecoration(item).eventController; // The event is triggered also for items that have not + var eventController = getDecoration(item).eventController; + // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. - if (eventController.getPayload('show') !== false) { eventController.emitEvent('show', false); } }); - }) // Filter and sort events. + }) + + // Filter and sort events. .on('filter', function (shownItems, hiddenItems) { if (store.onFilter) store.onFilter(shownItems, hiddenItems); }).on('sort', function (currentOrder, previousOrder) { if (store.onSort) store.onSort(currentOrder, previousOrder); - }); // Fix the dimensions of the items when they are dragged. + }); + // Fix the dimensions of the items when they are dragged. if (dragFixed) { grid.on('dragInit', function (item) { // Let's set fixed widht/height to the dragged item // so that it does not stretch unwillingly when // it's appended to the document body for the // duration of the drag. - var element = item.getElement(); // The element must exist. - - invariant(element !== undefined); // Get the computed dimensions. - + var element = item.getElement(); + // The element must exist. + invariant(element !== undefined); + // Get the computed dimensions. var _getComputedStyle = getComputedStyle(element), - width = _getComputedStyle.width, - height = _getComputedStyle.height, - paddingTop = _getComputedStyle.paddingTop; // Save the previous style in case it was setted. - - + width = _getComputedStyle.width, + height = _getComputedStyle.height, + paddingTop = _getComputedStyle.paddingTop; + // Save the previous style in case it was setted. addDecoration(item, { dragWidth: element.style.width, dragHeight: element.style.height, dragPaddingTop: element.style.paddingTop - }); // Set the new style. - + }); + // Set the new style. element.style.width = width; element.style.height = height; element.style.paddingTop = paddingTop; @@ -2139,38 +2057,38 @@ function GridComponent(_ref) { // dragged item now that it is back in a grid // column and can freely adjust to it's // surroundings. - var element = item.getElement(); // The element must exist. - - invariant(element !== undefined); // Get the old style. - + var element = item.getElement(); + // The element must exist. + invariant(element !== undefined); + // Get the old style. var _getDecoration = getDecoration(item), - dragWidth = _getDecoration.dragWidth, - dragHeight = _getDecoration.dragHeight, - dragPaddingTop = _getDecoration.dragPaddingTop; // Restore the previous style in case it was setted. - - + dragWidth = _getDecoration.dragWidth, + dragHeight = _getDecoration.dragHeight, + dragPaddingTop = _getDecoration.dragPaddingTop; + // Restore the previous style in case it was setted. element.style.width = dragWidth; element.style.height = dragHeight; element.style.paddingTop = dragPaddingTop; }); } - /* ---------------- */ + /* ---------------- */ /* ----- GRID ----- */ - /* -----------------*/ - // Check . + // Check . + invariant(store.gridRef.current !== null); - invariant(store.gridRef.current !== null); // Work with the grid. + // Work with the grid. // @ts-ignore - grid._element = store.gridRef.current; fillGridElement(store.gridRef.current, store.gridClass); - fillGrid(grid); // "onMount" Callback. + fillGrid(grid); - if (onMount) onMount(grid); // Delete the instance from the global map. + // "onMount" Callback. + if (onMount) onMount(grid); + // Delete the instance from the global map. return function () { // Destroy the controllers. store.childrenController.destroy(); @@ -2182,35 +2100,37 @@ function GridComponent(_ref) { }, []); // eslint-disable-line /* ---------------- */ - /* ----- INIT ----- */ - /* -----------------*/ - // Init the controllers. + // Init the controllers. store.childrenController.useInit(children); store.fiberController.useInit(store.gridRef); store.itemRemoveController.useInit(); store.itemAddController.useInit(); - store.layoutController.useInit(); // IsChanged flags. + store.layoutController.useInit(); + // IsChanged flags. var isFilterChanged = useReference([filter]); - var isSortChanged = useReference([sort, sortOptions]); // Get items to add/remove. + var isSortChanged = useReference([sort, sortOptions]); + // Get items to add/remove. React.useEffect(function () { // Set drag enabled option. addDecoration(grid, { dragEnabled: dragEnabled - }); // Set the items data. + }); + // Set the items data. vars.indicesToAdd = store.childrenController.getIndicesToAdd(); vars.addedDOMItems = store.fiberController.getStateNodes(vars.indicesToAdd); vars.itemsToRemove = store.itemRemoveController.getItemsToRemove(); vars.itemsToRefresh = store.layoutController.getItemsToRefresh(); vars.itemsToShow = store.layoutController.getItemsToShow(); - vars.itemsToHide = store.layoutController.getItemsToHide(); // This will remove lot of the implementation - // problems for the user. + vars.itemsToHide = store.layoutController.getItemsToHide(); + // This will remove lot of the implementation + // problems for the user. store.onUnmount = onUnmount; store.onDragStart = onDragStart; store.onDragEnd = onDragEnd; @@ -2218,122 +2138,112 @@ function GridComponent(_ref) { store.onSort = onSort; store.onSend = onSend; }); - /* ------------------- */ + /* ------------------- */ /* ----- ACTIONS ----- */ - /* ------------------- */ React.useEffect(function () { /* ---------------------- */ - /* ---- ADD & REMOVE ---- */ - /* ---------------------- */ + // Remove items. if (vars.itemsToRemove.length) { - removeItems(grid, vars.itemsToRemove); // Set the flag. - + removeItems(grid, vars.itemsToRemove); + // Set the flag. vars.hasRemoved = true; - } // Add items after the old ones are removed - // to add them in the right positions. - + } + // Add items after the old ones are removed + // to add them in the right positions. if (vars.indicesToAdd.length) { - addItems(grid, vars.addedDOMItems, vars.indicesToAdd, addOptions, filter); // New Items. - - var addedItems = grid.getItems(vars.indicesToAdd); // Emit the new items to the itemComponents. - - store.itemAddController.emit(addedItems); // Set the flag. - + addItems(grid, vars.addedDOMItems, vars.indicesToAdd, addOptions, filter); + // New Items. + var addedItems = grid.getItems(vars.indicesToAdd); + // Emit the new items to the itemComponents. + store.itemAddController.emit(addedItems); + // Set the flag. vars.hasAdded = true; } - /* ------------------------- */ + /* ------------------------- */ /* ----- SORT & FILTER ----- */ - /* ------------------------- */ - // Filter items. - + // Filter items. if (filter && (isFilterChanged || vars.hasAdded || forceSync)) { - filterItems(grid, filter); // Set the flag. - + filterItems(grid, filter); + // Set the flag. vars.hasFiltered = true; - } // Sort items. - + } + // Sort items. if (sort && (isSortChanged || vars.hasAdded || forceSync)) { - sortItems(grid, sort, sortOptions); // Set the flag. - + sortItems(grid, sort, sortOptions); + // Set the flag. vars.hasSorted = true; } - /* ----------------------- */ + /* ----------------------- */ /* ----- SHOW & HIDE ----- */ - /* ----------------------- */ - // Filter has priority on the items visibility. - + // Filter has priority on the items visibility. if (!filter && vars.itemsToShow.length) { - showItems(grid, vars.itemsToShow); // Set the flag. - + showItems(grid, vars.itemsToShow); + // Set the flag. vars.hasShown = true; - } // Filter has priority on the items visibility. - + } + // Filter has priority on the items visibility. if (!filter && vars.itemsToHide.length) { - hideItems(grid, vars.itemsToHide); // Set the flag. - + hideItems(grid, vars.itemsToHide); + // Set the flag. vars.hasHidden = true; } - /* ------------------- */ + /* ------------------- */ /* ----- REFRESH ----- */ - /* ------------------- */ - // Items with dimensions to refresh. - + // Items with dimensions to refresh. if (vars.itemsToRefresh.length) { - grid.refreshItems(vars.itemsToRefresh); // Set the flag. - + grid.refreshItems(vars.itemsToRefresh); + // Set the flag. vars.hasRefreshed = true; } - /* ------------------ */ + /* ------------------ */ /* ----- LAYOUT ----- */ - /* ------------------ */ + // Layout is calculated only in the end. // Check the previous flags. - - if (vars.hasAdded || vars.hasRemoved || vars.hasSorted || vars.hasFiltered || vars.hasRefreshed || vars.hasShown || vars.hasHidden) { grid.layout(instantLayout); } }); - /* ------------------ */ + /* ------------------ */ /* ----- RENDER ----- */ - /* ------------------ */ - // Provided value doesn't change the reference. + // Provided value doesn't change the reference. var value = useMemoized(function () { return { layoutController: store.layoutController, grid: grid }; - }); // render. + }); - return /*#__PURE__*/React__default['default'].createElement(GridProvider, { + // render. + return /*#__PURE__*/React__default["default"].createElement(GridProvider, { value: value - }, /*#__PURE__*/React__default['default'].createElement("div", _extends__default['default']({}, gridProps, { + }, /*#__PURE__*/React__default["default"].createElement("div", _extends__default["default"]({}, gridProps, { ref: store.gridRef }, store.fiberController.getFlagProp()), store.childrenController.render(function (child, key) { - return /*#__PURE__*/React__default['default'].createElement(ItemComponent, { + return /*#__PURE__*/React__default["default"].createElement(ItemComponent, { key: key, itemKey: key, grid: grid, @@ -2343,32 +2253,34 @@ function GridComponent(_ref) { itemRemoveController: store.itemRemoveController }, child); }))); -} // Proptypes. +} +// Proptypes. GridComponent.propTypes = { - grid: PropTypes__default['default'].object.isRequired, - gridProps: PropTypes__default['default'].object, - filter: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func]), - sort: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].func, PropTypes__default['default'].arrayOf(PropTypes__default['default'].string)]), - sortOptions: PropTypes__default['default'].exact({ - descending: PropTypes__default['default'].bool + grid: PropTypes__default["default"].object.isRequired, + gridProps: PropTypes__default["default"].object, + filter: PropTypes__default["default"].oneOfType([PropTypes__default["default"].string, PropTypes__default["default"].func]), + sort: PropTypes__default["default"].oneOfType([PropTypes__default["default"].string, PropTypes__default["default"].func, PropTypes__default["default"].arrayOf(PropTypes__default["default"].string)]), + sortOptions: PropTypes__default["default"].exact({ + descending: PropTypes__default["default"].bool }), - addOptions: PropTypes__default['default'].exact({ - show: PropTypes__default['default'].bool + addOptions: PropTypes__default["default"].exact({ + show: PropTypes__default["default"].bool }), - onSend: PropTypes__default['default'].func, - onDragStart: PropTypes__default['default'].func, - onDragEnd: PropTypes__default['default'].func, - onFilter: PropTypes__default['default'].func, - onSort: PropTypes__default['default'].func, - onMount: PropTypes__default['default'].func, - onUnmount: PropTypes__default['default'].func, - forceSync: PropTypes__default['default'].bool, - dragFixed: PropTypes__default['default'].bool, - dragEnabled: PropTypes__default['default'].bool, - instantLayout: PropTypes__default['default'].bool -}; // Default props. + onSend: PropTypes__default["default"].func, + onDragStart: PropTypes__default["default"].func, + onDragEnd: PropTypes__default["default"].func, + onFilter: PropTypes__default["default"].func, + onSort: PropTypes__default["default"].func, + onMount: PropTypes__default["default"].func, + onUnmount: PropTypes__default["default"].func, + forceSync: PropTypes__default["default"].bool, + dragFixed: PropTypes__default["default"].bool, + dragEnabled: PropTypes__default["default"].bool, + instantLayout: PropTypes__default["default"].bool +}; +// Default props. GridComponent.defaultProps = { gridProps: {}, addOptions: { @@ -2381,8 +2293,9 @@ GridComponent.defaultProps = { dragFixed: false, dragEnabled: false, instantLayout: false -}; // Display name. +}; +// Display name. GridComponent.displayName = 'GridComponent'; /** @@ -2391,14 +2304,11 @@ GridComponent.displayName = 'GridComponent'; */ var MuuriMap = /*#__PURE__*/function () { function MuuriMap() { - _classCallCheck__default['default'](this, MuuriMap); - - _defineProperty__default['default'](this, "_idMap", new Map()); - - _defineProperty__default['default'](this, "_groupMap", new Map()); + _classCallCheck__default["default"](this, MuuriMap); + _defineProperty__default["default"](this, "_idMap", new Map()); + _defineProperty__default["default"](this, "_groupMap", new Map()); } - - _createClass__default['default'](MuuriMap, [{ + _createClass__default["default"](MuuriMap, [{ key: "get", value: /** @@ -2410,6 +2320,7 @@ var MuuriMap = /*#__PURE__*/function () { function get(id) { return this._idMap.get(id) || null; } + /** * Get all the grid instances in the group of the given id. * The reference of the group array never changes. @@ -2417,33 +2328,30 @@ var MuuriMap = /*#__PURE__*/function () { * @param groupId - The group id. * @returns - The array of grid instances. */ - }, { key: "getGroup", value: function getGroup(groupId) { var group = this._groupMap.get(groupId); - if (!group) { var newGroup = []; - this._groupMap.set(groupId, newGroup); - return newGroup; } else { return group; } } + /** * Get all the grid instances in the map. * * @returns - The grid instances. */ - }, { key: "getAll", value: function getAll() { return Array.from(this._idMap.values()); } + /** * Set the grid instance with the given id. * @@ -2451,14 +2359,13 @@ var MuuriMap = /*#__PURE__*/function () { * @param id - The id of the instance. * @returns - The muuriMap. */ - }, { key: "set", value: function set(grid, id) { this._idMap.set(id, grid); - return this; } + /** * Set the grid instance in the group of the given id. * @@ -2466,68 +2373,59 @@ var MuuriMap = /*#__PURE__*/function () { * @param groupId - The id of the group. * @returns - The muuriMap. */ - }, { key: "setGroup", value: function setGroup(grid, groupId) { var group = this._groupMap.get(groupId); - if (group) { group.push(grid); } else { this._groupMap.set(groupId, [grid]); } - return this; } + /** * Delete the grid instance with the given id. * * @param id - The id of the instance. * @returns - The muuriMap. */ - }, { key: "delete", value: function _delete(id) { this._idMap["delete"](id); - return this; } + /** * Delete the instance from the group with the given id. * * @param grid - The grid instance. * @param groupIds - The group ids of the instance. */ - }, { key: "deleteGroup", value: function deleteGroup(grid, groupId) { var group = this._groupMap.get(groupId); - if (group) { var index = group.indexOf(grid); if (index > -1) group.splice(index, 1); } - return this; } + /** * Clear the maps. */ - }, { key: "clear", value: function clear() { this._idMap.clear(); - this._groupMap.clear(); - return this; } }]); - return MuuriMap; }(); var muuriMap = new MuuriMap(); @@ -2539,14 +2437,16 @@ var muuriMap = new MuuriMap(); * @returns - The muuri instance. */ function getInstance(options) { - var el = document.createElement('div'); // The element won't be visible. + var el = document.createElement('div'); + // The element won't be visible. + el.style.display = 'none'; + // Muuri (0.8.0) need an element in the DOM to be instanciated. + document.body.appendChild(el); - el.style.display = 'none'; // Muuri (0.8.0) need an element in the DOM to be instanciated. - - document.body.appendChild(el); // Generate the instance. - - var grid = new Muuri__default['default'](el, options); // Remove the element. + // Generate the instance. + var grid = new Muuri__default["default"](el, options); + // Remove the element. document.body.removeChild(el); return grid; } @@ -2559,7 +2459,8 @@ function getInstance(options) { */ function handleRef(ref, value) { if (!ref) return; - if (typeof ref === 'function') ref(value); // @ts-ignore + if (typeof ref === 'function') ref(value); + // @ts-ignore else if ('current' in ref) ref.current = value; } @@ -2570,20 +2471,23 @@ function handleRef(ref, value) { * @param options - The grid options. */ function setDragAutoScroll(options) { - var dragAutoScroll = options.dragAutoScroll; // Wrap the options only if it is setted. + var dragAutoScroll = options.dragAutoScroll; + // Wrap the options only if it is setted. if (!dragAutoScroll || !Array.isArray(dragAutoScroll.targets)) return; dragAutoScroll.targets.forEach(function (target) { // Check if it is an object to wrap. if (isTargetElement(target)) return; - invariant('element' in target, 'You must provide an element in each scroll target'); // Scroll target element. - - var element = target.element; // The element ref. + invariant('element' in target, 'You must provide an element in each scroll target'); + // Scroll target element. + var element = target.element; + // The element ref. var ref = { current: null - }; // Define the element property. + }; + // Define the element property. Object.defineProperty(target, 'element', { get: function get() { return ref.current; @@ -2595,21 +2499,24 @@ function setDragAutoScroll(options) { ref = element; } } - }); // Set the element. + }); + // Set the element. target.element = element; }); } + /** * Returns if the target is a valid element. * * @param element - The target. * @returns - If the target is a valid element. */ - function isTargetElement(target) { - return (// A DOM element. - target instanceof HTMLElement || // The window. + return ( + // A DOM element. + target instanceof HTMLElement || + // The window. target instanceof window.constructor ); } @@ -2621,12 +2528,13 @@ function isTargetElement(target) { * @param options - The grid options. */ function setDragContainer(options) { - var dragContainer = options.dragContainer; // The drag container ref. - + var dragContainer = options.dragContainer; + // The drag container ref. var ref = { current: null - }; // Define the property. + }; + // Define the property. Object.defineProperty(options, 'dragContainer', { get: function get() { return ref.current; @@ -2638,8 +2546,9 @@ function setDragContainer(options) { ref = value; } } - }); // Set the drag container. + }); + // Set the drag container. options.dragContainer = dragContainer; } @@ -2651,14 +2560,16 @@ function setDragContainer(options) { * @param globalMap - The globalMap. */ function setDragSort(options, globalMap) { - var dragSort = options.dragSort; // Parse this options only if it is an object. - - if (!dragSort || _typeof__default['default'](dragSort) !== 'object') return; // Check the options. - - invariant(typeof dragSort.groupId === 'string', 'You must provide a string as groupId'); // The group, its reference doesn't change. + var dragSort = options.dragSort; + // Parse this options only if it is an object. + if (!dragSort || _typeof__default["default"](dragSort) !== 'object') return; + // Check the options. + invariant(typeof dragSort.groupId === 'string', 'You must provide a string as groupId'); - var group = globalMap.getGroup(dragSort.groupId); // dragSort method. + // The group, its reference doesn't change. + var group = globalMap.getGroup(dragSort.groupId); + // dragSort method. options.dragSort = function () { return group; }; @@ -2673,120 +2584,123 @@ function setDragSort(options, globalMap) { * @param options - The grid options. */ function setDragStartPredicate(options) { - var dragStartPredicate = options.dragStartPredicate; // Default predicate. + var dragStartPredicate = options.dragStartPredicate; - var defaultStartPredicate = getDefaultStartPredicate(dragStartPredicate); // Wrap the method. + // Default predicate. + var defaultStartPredicate = getDefaultStartPredicate(dragStartPredicate); + // Wrap the method. options.dragStartPredicate = function (item, event) { if (!getDecoration(item.getGrid()).dragEnabled) return false; if (isDecorated(item) && getDecoration(item).draggable === false) return false; return defaultStartPredicate(item, event); }; } + /** * Given the dragStartPredicate option return the default method. * * @param dragStartPredicate - The dragStartPredicate option. * @returns - The defaultStartPredicate method. */ - function getDefaultStartPredicate(dragStartPredicate) { return typeof dragStartPredicate === 'function' ? dragStartPredicate : function (item, event) { - return Muuri__default['default'].ItemDrag.defaultStartPredicate(item, event, dragStartPredicate); + return Muuri__default["default"].ItemDrag.defaultStartPredicate(item, event, dragStartPredicate); }; } var _excluded = ["children", "id", "groupIds", "gridProps", "filter", "sort", "sortOptions", "addOptions", "propsToData", "onSend", "onDragStart", "onDragEnd", "onFilter", "onSort", "onMount", "onUnmount", "forceSync", "dragFixed", "dragEnabled", "instantLayout"]; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty__default['default'](target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - +// Muuri component. var MuuriComponent = /*#__PURE__*/React.forwardRef(function MuuriComponent(_ref, muuriRef) { var children = _ref.children, - id = _ref.id, - groupIds = _ref.groupIds, - gridProps = _ref.gridProps, - filter = _ref.filter, - sort = _ref.sort, - sortOptions = _ref.sortOptions, - addOptions = _ref.addOptions, - propsToData = _ref.propsToData, - onSend = _ref.onSend, - onDragStart = _ref.onDragStart, - onDragEnd = _ref.onDragEnd, - onFilter = _ref.onFilter, - onSort = _ref.onSort, - onMount = _ref.onMount, - onUnmount = _ref.onUnmount, - forceSync = _ref.forceSync, - dragFixed = _ref.dragFixed, - dragEnabled = _ref.dragEnabled, - instantLayout = _ref.instantLayout, - options = _objectWithoutProperties__default['default'](_ref, _excluded); - + id = _ref.id, + groupIds = _ref.groupIds, + gridProps = _ref.gridProps, + filter = _ref.filter, + sort = _ref.sort, + sortOptions = _ref.sortOptions, + addOptions = _ref.addOptions, + propsToData = _ref.propsToData, + onSend = _ref.onSend, + onDragStart = _ref.onDragStart, + onDragEnd = _ref.onDragEnd, + onFilter = _ref.onFilter, + onSort = _ref.onSort, + onMount = _ref.onMount, + onUnmount = _ref.onUnmount, + forceSync = _ref.forceSync, + dragFixed = _ref.dragFixed, + dragEnabled = _ref.dragEnabled, + instantLayout = _ref.instantLayout, + options = _objectWithoutProperties__default["default"](_ref, _excluded); // Generate the Muuri instance. var grid = useMemoized(function () { // Remove the standard option '*'. // @ts-ignore - options.items = []; // Muuri (0.9.0) generate the "ItemDrag" instances only if + options.items = []; + // Muuri (0.9.0) generate the "ItemDrag" instances only if // drag is enabled. These instances do not handle scrolling well on touch devices, // so we only create these instances if drag-and-drop have to be used // (assuming that a boolean is passed to the prop instead of the default value "null"). // The enabling / disabling of the drag is managed in dragStartPredicate. // @ts-ignore - - options.dragEnabled = dragEnabled !== null; // Allow the drag container to be a React.Ref. - - setDragContainer(options); // Allow the option to be an object ({ groupId }). - - setDragSort(options, muuriMap); // Allow the target elements to be React.Ref. - - setDragAutoScroll(options); // Allow enabling / disabling the drag-and-drop. - - setDragStartPredicate(options); // Generate the instance. - - var grid = getInstance(options); // Add the instance to the map. - - if (id) muuriMap.set(grid, id); // Add the decoration. - + options.dragEnabled = dragEnabled !== null; + + // Allow the drag container to be a React.Ref. + setDragContainer(options); + // Allow the option to be an object ({ groupId }). + setDragSort(options, muuriMap); + // Allow the target elements to be React.Ref. + setDragAutoScroll(options); + // Allow enabling / disabling the drag-and-drop. + setDragStartPredicate(options); + + // Generate the instance. + var grid = getInstance(options); + + // Add the instance to the map. + if (id) muuriMap.set(grid, id); + // Add the decoration. addDecoration(grid, { id: id - }); // Set the ref. - + }); + // Set the ref. handleRef(muuriRef, grid); return grid; }); // eslint-disable-line - // On unmount effect. + // On unmount effect. React.useEffect(function () { // Clean-up. return function () { // Unset the ref. - handleRef(muuriRef, null); // Remove the decorations. - - removeDecorations(grid); // Remove the instance from the map. - - if (id) muuriMap["delete"](id); // Destroy the instace - + handleRef(muuriRef, null); + // Remove the decorations. + removeDecorations(grid); + // Remove the instance from the map. + if (id) muuriMap["delete"](id); + // Destroy the instace grid.destroy(); }; }, []); // eslint-disable-line - // Allow the groupIds to be changed. + // Allow the groupIds to be changed. useInstantEffect(function () { // decorate the instance addDecoration(grid, { groupIds: groupIds - }); // Add the instance to the groups. - + }); + // Add the instance to the groups. if (groupIds) { groupIds.forEach(function (groupId) { muuriMap.setGroup(grid, groupId); }); - } // Clean-up. - + } + // Clean-up. return function () { // Remove the instance from the groups. if (groupIds) { @@ -2795,9 +2709,10 @@ var MuuriComponent = /*#__PURE__*/React.forwardRef(function MuuriComponent(_ref, }); } }; - }, groupIds || []); // Render. + }, groupIds || []); - return /*#__PURE__*/React__default['default'].createElement(GridComponent, { + // Render. + return /*#__PURE__*/React__default["default"].createElement(GridComponent, { grid: grid, gridProps: gridProps, filter: filter, @@ -2817,93 +2732,98 @@ var MuuriComponent = /*#__PURE__*/React.forwardRef(function MuuriComponent(_ref, dragEnabled: dragEnabled, instantLayout: instantLayout }, children); -}); // Proptypes. +}); +// Proptypes. MuuriComponent.propTypes = { - id: PropTypes__default['default'].string, - groupIds: PropTypes__default['default'].arrayOf(PropTypes__default['default'].string.isRequired), - showDuration: PropTypes__default['default'].number, - showEasing: PropTypes__default['default'].string, - hideDuration: PropTypes__default['default'].number, - hideEasing: PropTypes__default['default'].string, - visibleStyles: PropTypes__default['default'].shape({}), - hiddenStyles: PropTypes__default['default'].shape({}), + id: PropTypes__default["default"].string, + groupIds: PropTypes__default["default"].arrayOf(PropTypes__default["default"].string.isRequired), + showDuration: PropTypes__default["default"].number, + showEasing: PropTypes__default["default"].string, + hideDuration: PropTypes__default["default"].number, + hideEasing: PropTypes__default["default"].string, + visibleStyles: PropTypes__default["default"].shape({}), + hiddenStyles: PropTypes__default["default"].shape({}), // @ts-ignore - layout: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].exact({ - fillGaps: PropTypes__default['default'].bool, - horizontal: PropTypes__default['default'].bool, - alignRight: PropTypes__default['default'].bool, - alignBottom: PropTypes__default['default'].bool, - rounding: PropTypes__default['default'].bool + layout: PropTypes__default["default"].oneOfType([PropTypes__default["default"].func, PropTypes__default["default"].exact({ + fillGaps: PropTypes__default["default"].bool, + horizontal: PropTypes__default["default"].bool, + alignRight: PropTypes__default["default"].bool, + alignBottom: PropTypes__default["default"].bool, + rounding: PropTypes__default["default"].bool })]), - layoutOnResize: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].number]), - layoutDuration: PropTypes__default['default'].number, - layoutEasing: PropTypes__default['default'].string, - dragContainer: PropTypes__default['default'].oneOfType([PropTypes__default['default'].instanceOf(HTMLElement), PropTypes__default['default'].shape({ - current: PropTypes__default['default'].instanceOf(HTMLElement).isRequired + layoutOnResize: PropTypes__default["default"].oneOfType([PropTypes__default["default"].bool, PropTypes__default["default"].number]), + layoutDuration: PropTypes__default["default"].number, + layoutEasing: PropTypes__default["default"].string, + dragContainer: PropTypes__default["default"].oneOfType([PropTypes__default["default"].instanceOf(HTMLElement), PropTypes__default["default"].shape({ + current: PropTypes__default["default"].instanceOf(HTMLElement).isRequired })]), // @ts-ignore - dragStartPredicate: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].exact({ - distance: PropTypes__default['default'].number, - delay: PropTypes__default['default'].number, - handle: PropTypes__default['default'].oneOfType([PropTypes__default['default'].string, PropTypes__default['default'].bool]) + dragStartPredicate: PropTypes__default["default"].oneOfType([PropTypes__default["default"].func, PropTypes__default["default"].exact({ + distance: PropTypes__default["default"].number, + delay: PropTypes__default["default"].number, + handle: PropTypes__default["default"].oneOfType([PropTypes__default["default"].string, PropTypes__default["default"].bool]) })]), - dragAxis: PropTypes__default['default'].oneOf(['x', 'y', 'xy']), - dragSort: PropTypes__default['default'].oneOfType([PropTypes__default['default'].bool, PropTypes__default['default'].func, PropTypes__default['default'].exact({ - groupId: PropTypes__default['default'].string.isRequired + dragAxis: PropTypes__default["default"].oneOf(['x', 'y', 'xy']), + dragSort: PropTypes__default["default"].oneOfType([PropTypes__default["default"].bool, PropTypes__default["default"].func, PropTypes__default["default"].exact({ + groupId: PropTypes__default["default"].string.isRequired })]), // @ts-ignore - dragSortHeuristics: PropTypes__default['default'].exact({ - sortInterval: PropTypes__default['default'].number, - minDragDistance: PropTypes__default['default'].number, - minBounceBackAngle: PropTypes__default['default'].number + dragSortHeuristics: PropTypes__default["default"].exact({ + sortInterval: PropTypes__default["default"].number, + minDragDistance: PropTypes__default["default"].number, + minBounceBackAngle: PropTypes__default["default"].number }), // @ts-ignore - dragSortPredicate: PropTypes__default['default'].oneOfType([PropTypes__default['default'].func, PropTypes__default['default'].exact({ - action: PropTypes__default['default'].oneOf(['move', 'swap']), - migrateAction: PropTypes__default['default'].oneOf(['move', 'swap']), - threshold: PropTypes__default['default'].number + dragSortPredicate: PropTypes__default["default"].oneOfType([PropTypes__default["default"].func, PropTypes__default["default"].exact({ + action: PropTypes__default["default"].oneOf(['move', 'swap']), + migrateAction: PropTypes__default["default"].oneOf(['move', 'swap']), + threshold: PropTypes__default["default"].number })]), // @ts-ignore - dragRelease: PropTypes__default['default'].exact({ - duration: PropTypes__default['default'].number, - easing: PropTypes__default['default'].string, - useDragContainer: PropTypes__default['default'].bool + dragRelease: PropTypes__default["default"].exact({ + duration: PropTypes__default["default"].number, + easing: PropTypes__default["default"].string, + useDragContainer: PropTypes__default["default"].bool }), // @ts-ignore - dragCssProps: PropTypes__default['default'].exact({ - touchAction: PropTypes__default['default'].string, - userSelect: PropTypes__default['default'].string, - userDrag: PropTypes__default['default'].string, - tapHighlightColor: PropTypes__default['default'].string, - touchCallout: PropTypes__default['default'].string, - contentZooming: PropTypes__default['default'].string + dragCssProps: PropTypes__default["default"].exact({ + touchAction: PropTypes__default["default"].string, + userSelect: PropTypes__default["default"].string, + userDrag: PropTypes__default["default"].string, + tapHighlightColor: PropTypes__default["default"].string, + touchCallout: PropTypes__default["default"].string, + contentZooming: PropTypes__default["default"].string }), // @ts-ignore - dragPlaceholder: PropTypes__default['default'].exact({ - enabled: PropTypes__default['default'].bool, - createElement: PropTypes__default['default'].func, - onCreate: PropTypes__default['default'].func, - onRemove: PropTypes__default['default'].func, - easing: PropTypes__default['default'].string, - duration: PropTypes__default['default'].number + dragPlaceholder: PropTypes__default["default"].exact({ + enabled: PropTypes__default["default"].bool, + createElement: PropTypes__default["default"].func, + onCreate: PropTypes__default["default"].func, + onRemove: PropTypes__default["default"].func, + easing: PropTypes__default["default"].string, + duration: PropTypes__default["default"].number }), - containerClass: PropTypes__default['default'].string, - itemClass: PropTypes__default['default'].string, - itemVisibleClass: PropTypes__default['default'].string, - itemHiddenClass: PropTypes__default['default'].string, - itemPositioningClass: PropTypes__default['default'].string, - itemDraggingClass: PropTypes__default['default'].string, - itemReleasingClass: PropTypes__default['default'].string, - itemPlaceholderClass: PropTypes__default['default'].string -}; // Default props. - -MuuriComponent.defaultProps = _objectSpread(_objectSpread({}, Muuri__default['default'].defaultOptions), {}, { + containerClass: PropTypes__default["default"].string, + itemClass: PropTypes__default["default"].string, + itemVisibleClass: PropTypes__default["default"].string, + itemHiddenClass: PropTypes__default["default"].string, + itemPositioningClass: PropTypes__default["default"].string, + itemDraggingClass: PropTypes__default["default"].string, + itemReleasingClass: PropTypes__default["default"].string, + itemPlaceholderClass: PropTypes__default["default"].string +}; + +// Default props. +MuuriComponent.defaultProps = _objectSpread(_objectSpread({}, Muuri__default["default"].defaultOptions), {}, { dragEnabled: null -}); // Display name. +}); +// Display name. MuuriComponent.displayName = 'MuuriComponent'; +// The method return by the hook. + /** * The useData hook allow to set the data to the item in which the hook has been called. * It also returns the setter method. @@ -2914,18 +2834,20 @@ MuuriComponent.displayName = 'MuuriComponent'; */ function useData(initialData, options) { var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); - invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); // Because of memoization, The identity of the function is guaranteed + // Because of memoization, The identity of the function is guaranteed // to be stable so it will be safe to omit them as a dependency. - var setData = useFunction(function (data, options) { // Check if the data is an object. - invariant(_typeof__default['default'](data) === 'object', "The data must be an object, founded: ".concat(_typeof__default['default'](data))); // Default options. - - options = options || useData.defaultOptions; // Set the data. + invariant(_typeof__default["default"](data) === 'object', "The data must be an object, founded: ".concat(_typeof__default["default"](data))); + // Default options. + options = options || useData.defaultOptions; + // Set the data. if (options.merge) { // Merge. var currentData = itemRefController.get('data') || {}; @@ -2934,15 +2856,16 @@ function useData(initialData, options) { // Set. itemRefController.set('data', data); } - }); // Set the inital data. + }); - if (_typeof__default['default'](initialData) === 'object') { + // Set the inital data. + if (_typeof__default["default"](initialData) === 'object') { setData(initialData, options); } - return setData; -} // Default options. +} +// Default options. useData.defaultOptions = { merge: false }; @@ -2954,21 +2877,23 @@ useData.defaultOptions = { * * @returns - If the item is being dragged. */ - function useDrag() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; - - var reRender = useRerender(); // Check if the hook is called inside an item. + eventController = _useItemContext.eventController; + var reRender = useRerender(); - invariant(eventController !== undefined, 'The useDrag hook can be used only inside an Item'); // Enable the event. + // Check if the hook is called inside an item. + invariant(eventController !== undefined, 'The useDrag hook can be used only inside an Item'); + // Enable the event. React.useEffect(function () { eventController.enableEvent('drag', reRender); }, [eventController, reRender]); return eventController.getPayload('drag') || false; } +// The method returned by the hook. + /** * The useDraggable hook allow to decide if the item (in which the hook has been called) * can be dragged or not. @@ -2978,9 +2903,9 @@ function useDrag() { */ function useDraggable() { var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. - + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); var setDraggable = useFunction(function (draggable) { // Set if the item can be dragged. @@ -2997,16 +2922,18 @@ function useDraggable() { */ function useGrid() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; - + eventController = _useItemContext.eventController; var gridContext = useGridContext(); - var reRender = useRerender(); // Check if the hook is called inside an item. + var reRender = useRerender(); - invariant(eventController !== undefined && gridContext.grid !== undefined, 'The useData hook can be used only inside an Item'); // The context is not updated when the hook is trigger - // so we need to get the updated instance from the eventController. + // Check if the hook is called inside an item. + invariant(eventController !== undefined && gridContext.grid !== undefined, 'The useData hook can be used only inside an Item'); - var grid = eventController.getPayload('send') || gridContext.grid; // Enable the event. + // The context is not updated when the hook is trigger + // so we need to get the updated instance from the eventController. + var grid = eventController.getPayload('send') || gridContext.grid; + // Enable the event. React.useEffect(function () { eventController.enableEvent('send', reRender); }, [eventController, reRender]); @@ -3017,6 +2944,8 @@ function useGrid() { }; } +// The method returned by the hook. + /** * The useRefresh hook allow to notify the MuuriComponent that the * item dimensions are changed, so that it can update the layout. @@ -3026,22 +2955,21 @@ function useGrid() { */ function useRefresh() { var deps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var _useGridContext = useGridContext(), - layoutController = _useGridContext.layoutController; - + layoutController = _useGridContext.layoutController; var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined && layoutController !== undefined, 'The useRefresh hook can be used only inside an Item'); - invariant(itemRefController !== undefined && layoutController !== undefined, 'The useRefresh hook can be used only inside an Item'); // Because of memoization, The identity of the function is guaranteed + // Because of memoization, The identity of the function is guaranteed // to be stable so it will be safe to omit it as a dependency. - var refresh = React.useCallback(function () { - if (!itemRefController.hasItem()) return; // Get the item. - - var item = itemRefController.getItem(); // If the component is rendering within the MuuriComponent. - + if (!itemRefController.hasItem()) return; + // Get the item. + var item = itemRefController.getItem(); + // If the component is rendering within the MuuriComponent. layoutController.refreshItem(item); }, [layoutController, itemRefController]); React.useEffect(function () { @@ -3057,21 +2985,23 @@ function useRefresh() { * * @returns - If the item is showing. */ - function useShow() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; + eventController = _useItemContext.eventController; + var reRender = useRerender(); - var reRender = useRerender(); // Check if the hook is called inside an item. - - invariant(eventController !== undefined, 'The useShow hook can be used only inside an Item'); // Enable the event. + // Check if the hook is called inside an item. + invariant(eventController !== undefined, 'The useShow hook can be used only inside an Item'); + // Enable the event. React.useEffect(function () { eventController.enableEvent('show', reRender); }, [eventController, reRender]); return eventController.getPayload('show'); } +// The method returned by the hook. + /** * The useVisibility hook allow you to show/hide the item in which the hook has been called. * @@ -3079,26 +3009,29 @@ function useShow() { */ function useVisibility() { var _useGridContext = useGridContext(), - layoutController = _useGridContext.layoutController; - + layoutController = _useGridContext.layoutController; var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController, - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. - + eventController = _useItemContext.eventController, + itemRefController = _useItemContext.itemRefController; - invariant(itemRefController !== undefined && layoutController !== undefined && eventController !== undefined, 'The useData hook can be used only inside an Item'); // Set visibility. + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined && layoutController !== undefined && eventController !== undefined, 'The useData hook can be used only inside an Item'); + // Set visibility. var setVisibility = useFunction(function (visible, options) { if (!itemRefController.hasItem()) return; - if (!!visible === eventController.getPayload('show')) return; // Default options. + if (!!visible === eventController.getPayload('show')) return; - options = options || useVisibility.defaultOptions; // Set the visibility. + // Default options. + options = options || useVisibility.defaultOptions; + // Set the visibility. layoutController.setItemVisibility(itemRefController.getItem(), visible, options.instant === true); }); return setVisibility; -} // Default options. +} +// Default options. useVisibility.defaultOptions = { instant: false }; @@ -3124,27 +3057,30 @@ var hooks = /*#__PURE__*/Object.freeze({ */ function getResponsiveStyle(options) { // Check options. - invariant(_typeof__default['default'](options) === 'object', 'You must define options'); // Check columns. + invariant(_typeof__default["default"](options) === 'object', 'You must define options'); - invariant(typeof options.columns === 'number' && options.columns > 0 && options.columns <= 1, 'options.columns must be a number between 0 (excluded) and 1 (included)'); // Check height and ratio. + // Check columns. + invariant(typeof options.columns === 'number' && options.columns > 0 && options.columns <= 1, 'options.columns must be a number between 0 (excluded) and 1 (included)'); - invariant(typeof options.ratio === 'number' || typeof options.height === 'number' || typeof options.height === 'string', 'You must provide at least one option between height and ratio'); // Check that the height and the ratio options are not setted togheter. + // Check height and ratio. + invariant(typeof options.ratio === 'number' || typeof options.height === 'number' || typeof options.height === 'string', 'You must provide at least one option between height and ratio'); - invariant(typeof options.ratio !== 'number' || typeof options.height !== 'number' && typeof options.height !== 'string', 'You cannot provide both the height and the ratio options'); // The margin values. + // Check that the height and the ratio options are not setted togheter. + invariant(typeof options.ratio !== 'number' || typeof options.height !== 'number' && typeof options.height !== 'string', 'You cannot provide both the height and the ratio options'); + // The margin values. var _getResponsiveMargin = getResponsiveMargin(options.margin || '0px'), - margin = _getResponsiveMargin.margin, - mStatic = _getResponsiveMargin.mStatic, - mDynamic = _getResponsiveMargin.mDynamic; // The item width. - - + margin = _getResponsiveMargin.margin, + mStatic = _getResponsiveMargin.mStatic, + mDynamic = _getResponsiveMargin.mDynamic; + // The item width. var _getResponsiveWidth = getResponsiveWidth(options.columns, mStatic, mDynamic), - needCalc = _getResponsiveWidth.needCalc, - width = _getResponsiveWidth.width; // If ratio is used set The paddingTop + needCalc = _getResponsiveWidth.needCalc, + width = _getResponsiveWidth.width; + + // If ratio is used set The paddingTop // instad of the heght, the child element must // have "display: absolute". - - return options.ratio ? { width: needCalc ? "calc(".concat(width, ")") : width, paddingTop: getResponsivePaddingTop(width, options.ratio, needCalc), @@ -3160,6 +3096,7 @@ function getResponsiveStyle(options) { margin: margin }; } + /** * Get the responsive width. * @@ -3168,7 +3105,6 @@ function getResponsiveStyle(options) { * @param mDynamic - The dynamic margin. * @returns - The width. */ - function getResponsiveWidth(columns, mStatic, mDynamic) { var needCalc = mStatic !== 0; var rawWidth = columns * 100 - mDynamic; @@ -3178,6 +3114,7 @@ function getResponsiveWidth(columns, mStatic, mDynamic) { width: width }; } + /** * Get the responsive paddingTop. * @@ -3186,39 +3123,37 @@ function getResponsiveWidth(columns, mStatic, mDynamic) { * @param needCalc - If the width need to be surrounded by calc(). * @returns - The paddingTop. */ - - function getResponsivePaddingTop(width, ratio, needCalc) { return needCalc ? "calc((".concat(width, ") / ").concat(ratio, ")") : "".concat(parseFloat(width) / ratio, "%"); } + /** * Get the fixed height. * * @param height - The mixed height. * @returns - The height string. */ - - function getFixedHeight(height) { return typeof height === 'number' ? "".concat(height, "px") : height; } + /** * The responsive margin. * * @param margin - The margin. * @returns - The responsive margin. */ - - function getResponsiveMargin(margin) { if (typeof margin === 'number') margin = "".concat(margin, "px"); - var margins = margin.trim().split(' '); // Margin default values. + var margins = margin.trim().split(' '); + // Margin default values. var leftMargin = '0px'; var rightMargin = '0px'; var mDynamic = 0; - var mStatic = 0; // Get the values from the input. + var mStatic = 0; + // Get the values from the input. if (margins.length === 1) { leftMargin = rightMargin = margins[0]; } else if (margins.length === 2) { @@ -3228,9 +3163,9 @@ function getResponsiveMargin(margin) { } else if (margins.length === 4) { leftMargin = margins[3]; rightMargin = margins[1]; - } // Set dynamic/static margins. - + } + // Set dynamic/static margins. if (leftMargin.indexOf('%') === -1) mStatic += parseFloat(leftMargin);else mDynamic += parseFloat(leftMargin); if (rightMargin.indexOf('%') === -1) mStatic += parseFloat(rightMargin);else mDynamic += parseFloat(rightMargin); return { @@ -3247,20 +3182,23 @@ function getResponsiveMargin(margin) { * @returns - The style. */ function getStaticStyle(options) { - var style = getResponsiveStyle(options); // Check the options. + var style = getResponsiveStyle(options); - invariant('grid' in options, 'You mast pass the grid instance to get the static style.'); // The sizer element. + // Check the options. + invariant('grid' in options, 'You mast pass the grid instance to get the static style.'); - var sizerElement = options.grid.getSizerElement(); // Set the style in the sizer. + // The sizer element. + var sizerElement = options.grid.getSizerElement(); - Object.assign(sizerElement.style, style); // Get the style from the sizer. + // Set the style in the sizer. + Object.assign(sizerElement.style, style); + // Get the style from the sizer. var _window$getComputedSt = window.getComputedStyle(sizerElement), - width = _window$getComputedSt.width, - height = _window$getComputedSt.height, - paddingTop = _window$getComputedSt.paddingTop, - margin = _window$getComputedSt.margin; - + width = _window$getComputedSt.width, + height = _window$getComputedSt.height, + paddingTop = _window$getComputedSt.paddingTop, + margin = _window$getComputedSt.margin; return { width: width, height: height, @@ -3269,53 +3207,42 @@ function getStaticStyle(options) { }; } -var hooksNames = ['useData', 'useDrag', 'useDraggable', 'useGrid', 'useRefresh', 'useShow', 'useVisibility']; // Handler type. +// Hook names. +var hooksNames = ['useData', 'useDrag', 'useDraggable', 'useGrid', 'useRefresh', 'useShow', 'useVisibility']; + +// Handler type. // Hook handlers. -var HooksHandlers = [['useData', -/* */ -getHandler('setData')], ['useDrag', -/* */ -getHandler('isDragging')], ['useDraggable', -/* */ -getHandler('setDraggable')], ['useGrid', -/* */ -getHandler('gridData')], ['useRefresh', -/* */ -getHandler('refresh')], ['useShow', -/* */ -getHandler('isShowing')], ['useVisibility', -/* */ -getHandler('setVisibility')]]; +var HooksHandlers = [['useData', /* */getHandler('setData')], ['useDrag', /* */getHandler('isDragging')], ['useDraggable', /* */getHandler('setDraggable')], ['useGrid', /* */getHandler('gridData')], ['useRefresh', /* */getHandler('refresh')], ['useShow', /* */getHandler('isShowing')], ['useVisibility', /* */getHandler('setVisibility')]]; + /** * Return the handler with the given key. * * @param key - The key. * @returns - The method. */ - function getHandler(key) { return function handler(payload) { - return _defineProperty__default['default']({}, key, payload); + return _defineProperty__default["default"]({}, key, payload); }; } + /** * Run all the handlers and merge all the payloads. * * @param hooksHandlers - The handlers. * @returns - The merged payload. */ - function getMerged(hooksHandlers) { - return Object.assign.apply(Object, [{}].concat(_toConsumableArray__default['default'](hooksHandlers.map(function (_ref2) { - var _ref3 = _slicedToArray__default['default'](_ref2, 2), - hookName = _ref3[0], - handler = _ref3[1]; - + return Object.assign.apply(Object, [{}].concat(_toConsumableArray__default["default"](hooksHandlers.map(function (_ref2) { + var _ref3 = _slicedToArray__default["default"](_ref2, 2), + hookName = _ref3[0], + handler = _ref3[1]; var payload = hooks[hookName](); return handler(payload); })))); } + /** * Item HOC for hooks. * @@ -3323,33 +3250,35 @@ function getMerged(hooksHandlers) { * @param enabledHooks - The hooks to enable. * @returns - The wrapped component. */ - - function withHooks(Component, enabledHooks) { // There must be an array of hooks to enable. - invariant(Array.isArray(enabledHooks), 'An array of hooks name must be provided to wrap an item.'); // All the hooks must be valid. + invariant(Array.isArray(enabledHooks), 'An array of hooks name must be provided to wrap an item.'); + // All the hooks must be valid. enabledHooks.forEach(function (hookName) { invariant(hooksNames.includes(hookName), "Invalid item hook: ".concat(hookName)); - }); // There must be at least one hook to enable. + }); - invariant(enabledHooks.length !== 0, 'To wrap an item at least one hook must be provided.'); // Get the handlers array of the enabled hook. + // There must be at least one hook to enable. + invariant(enabledHooks.length !== 0, 'To wrap an item at least one hook must be provided.'); + // Get the handlers array of the enabled hook. var hooksHandlers = HooksHandlers.filter(function (_ref4) { - var _ref5 = _slicedToArray__default['default'](_ref4, 1), - hookName = _ref5[0]; - + var _ref5 = _slicedToArray__default["default"](_ref4, 1), + hookName = _ref5[0]; return enabledHooks.includes(hookName); - }); // Return the HOC. + }); + // Return the HOC. return function WrappedItem(props) { // The hooks will run in the 'getMerged' method. - return /*#__PURE__*/React__default['default'].createElement(Component, _extends__default['default']({}, props, getMerged(hooksHandlers))); + return /*#__PURE__*/React__default["default"].createElement(Component, _extends__default["default"]({}, props, getMerged(hooksHandlers))); }; } -var AutoScroller = Muuri__default['default'].AutoScroller; -var ItemDrag = Muuri__default['default'].ItemDrag; // Muuri-react exports. +// Muuri-exports. +var AutoScroller = Muuri__default["default"].AutoScroller; +var ItemDrag = Muuri__default["default"].ItemDrag; exports.AutoScroller = AutoScroller; exports.ChildrenController = ChildrenController; diff --git a/dist/muuri-react.esm.js b/dist/muuri-react.esm.js index f30a2de..b1e4b1c 100644 --- a/dist/muuri-react.esm.js +++ b/dist/muuri-react.esm.js @@ -35,10 +35,8 @@ function isDecorated(instance) { return !!instance[key]; } -function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - +function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * Add a decoration to the instance. * @@ -47,6 +45,7 @@ function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { */ function addDecoration(instance, decoration) { if (isDecorated(instance)) { + // @ts-ignore Object.assign(instance[key], decoration); } else { instance[key] = _objectSpread$2({}, decoration); @@ -77,7 +76,6 @@ function removeDecorations(decorated) { * * @returns - The id of the instance. */ - Muuri.prototype.getId = function getId() { return getDecoration(this).id; }; @@ -86,8 +84,6 @@ Muuri.prototype.getId = function getId() { * * @returns - The group ids of the instance. */ - - Muuri.prototype.getGroupIds = function getGroupIds() { return getDecoration(this).groupIds; }; @@ -96,18 +92,15 @@ Muuri.prototype.getGroupIds = function getGroupIds() { * * @returns - The group ids of the instance. */ - - Muuri.prototype.getSizerElement = function getSizerElement() { return getDecoration(this).sizerElement; }; + /** * Item key getter. * * @returns - The item component key. */ - - Muuri.Item.prototype.getKey = function getKey() { return getDecoration(this).key; }; @@ -116,8 +109,6 @@ Muuri.Item.prototype.getKey = function getKey() { * * @returns - The item component props. */ - - Muuri.Item.prototype.getProps = function getProps() { return getDecoration(this).props; }; @@ -126,8 +117,6 @@ Muuri.Item.prototype.getProps = function getProps() { * * @returns - The item component data. */ - - Muuri.Item.prototype.getData = function getData() { return getDecoration(this).data; }; @@ -136,32 +125,30 @@ Muuri.Item.prototype.getData = function getData() { * * @param data - The data. */ - - Muuri.Item.prototype.setData = function setData(data) { getDecoration(this).data = data; }; // Grid context. -var GridContext = /*#__PURE__*/createContext({}); // Grid provider. - -var GridProvider = GridContext.Provider; // Grid context hook. - +var GridContext = /*#__PURE__*/createContext({}); +// Grid provider. +var GridProvider = GridContext.Provider; +// Grid context hook. var useGridContext = function useGridContext() { return useContext(GridContext); -}; // Grid provider display name. - +}; +// Grid provider display name. GridContext.displayName = 'GridProvider'; // Item context. -var ItemContext = /*#__PURE__*/createContext({}); // Item provider. - -var ItemProvider = ItemContext.Provider; // Item context hook. - +var ItemContext = /*#__PURE__*/createContext({}); +// Item provider. +var ItemProvider = ItemContext.Provider; +// Item context hook. var useItemContext = function useItemContext() { return useContext(ItemContext); -}; // Item provider display name. - +}; +// Item provider display name. ItemContext.displayName = 'ItemProvider'; /** @@ -174,12 +161,9 @@ ItemContext.displayName = 'ItemProvider'; var EventController = /*#__PURE__*/function () { function EventController() { _classCallCheck(this, EventController); - _defineProperty(this, "_eventsMap", new Map()); - _defineProperty(this, "_payloadsMap", new Map()); } - _createClass(EventController, [{ key: "enableEvent", value: @@ -192,60 +176,57 @@ var EventController = /*#__PURE__*/function () { function enableEvent(event, emitter) { this._eventsMap.set(event, emitter); } + /** * Set an event payload and emit it the event. * * @param event - The event name. * @param payload - The payload. */ - }, { key: "emitEvent", value: function emitEvent(event, payload) { if (this.isEnabled(event)) { - this._payloadsMap.set(event, payload); // @ts-ignore - - + this._payloadsMap.set(event, payload); + // @ts-ignore this._eventsMap.get(event)(); } } + /** * Get the payload of the event. * * @param event - The event. * @returns - The payload. */ - }, { key: "getPayload", value: function getPayload(event) { return this._payloadsMap.get(event); } + /** * Returns if at least an event is enabled. * * @param event - The event. * @returns - If at least an event is enabled. */ - }, { key: "isEnabled", value: function isEnabled(event) { return this._eventsMap.has(event); } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._eventsMap.clear(); - this._payloadsMap.clear(); } }]); - return EventController; }(); @@ -260,10 +241,8 @@ var EventController = /*#__PURE__*/function () { var ItemAddController = /*#__PURE__*/function () { function ItemAddController() { _classCallCheck(this, ItemAddController); - _defineProperty(this, "_requests", []); } - _createClass(ItemAddController, [{ key: "useInit", value: @@ -273,13 +252,13 @@ var ItemAddController = /*#__PURE__*/function () { function useInit() { this._requests = []; } + /** * Emit the new items to the * components that made a request. * * @param items - The items. */ - }, { key: "emit", value: function emit(items) { @@ -287,61 +266,54 @@ var ItemAddController = /*#__PURE__*/function () { this._requests[i](items[i]); } } + /** * Request an item. * * @param cb - The callback. */ - }, { key: "requestItem", value: function requestItem(cb) { this._requests.push(cb); } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._requests = []; } }]); - return ItemAddController; }(); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - var isProduction = process.env.NODE_ENV === 'production'; -var prefix = 'Invariant failed'; // Invarianto instance +var prefix = 'Invariant failed'; +// Invarianto instance var Invariant = /*#__PURE__*/function (_Error) { _inherits(Invariant, _Error); - var _super = _createSuper(Invariant); - function Invariant(message) { var _this; - _classCallCheck(this, Invariant); - _this = _super.call(this, message); _this.name = 'Invariant'; return _this; } + return _createClass(Invariant); +}( /*#__PURE__*/_wrapNativeSuper(Error)); - return Invariant; -}( /*#__PURE__*/_wrapNativeSuper(Error)); // Throw an error if the condition fails - +// Throw an error if the condition fails function invariant(condition, message) { if (condition) { return; } - if (isProduction) { // In production we strip the message but still throw throw new Invariant(prefix); @@ -362,12 +334,9 @@ function invariant(condition, message) { var ItemRefController = /*#__PURE__*/function () { function ItemRefController() { _classCallCheck(this, ItemRefController); - _defineProperty(this, "_item", null); - _defineProperty(this, "_instance", {}); } - _createClass(ItemRefController, [{ key: "set", value: @@ -384,13 +353,13 @@ var ItemRefController = /*#__PURE__*/function () { this._instance[key] = value; } } + /** * Get a decoration value from the item. * * @param key - The decoration key. * @returns - The decoration value. */ - }, { key: "get", value: function get(key) { @@ -400,21 +369,21 @@ var ItemRefController = /*#__PURE__*/function () { return this._instance[key]; } } + /** * Remove all the decorations from the item. */ - }, { key: "delete", value: function _delete() { if (this._item) removeDecorations(this._item); } + /** * Set the item in the controller. * * @param item - The item. */ - }, { key: "setItem", value: function setItem(item) { @@ -422,33 +391,33 @@ var ItemRefController = /*#__PURE__*/function () { addDecoration(this._item, this._instance); this._instance = {}; } + /** * Item getter. * * @returns - The item. */ - }, { key: "getItem", value: function getItem() { invariant(this._item !== null, 'The item has not been setted yet'); return this._item; } + /** * Returns if the item has been setted. * * @returns - If the item has been setted. */ - }, { key: "hasItem", value: function hasItem() { return this._item !== null; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -456,7 +425,6 @@ var ItemRefController = /*#__PURE__*/function () { this._instance = {}; } }]); - return ItemRefController; }(); @@ -469,10 +437,8 @@ var ItemRefController = /*#__PURE__*/function () { var ItemRemoveController = /*#__PURE__*/function () { function ItemRemoveController() { _classCallCheck(this, ItemRemoveController); - _defineProperty(this, "_itemsToRemove", []); } - _createClass(ItemRemoveController, [{ key: "useInit", value: @@ -482,37 +448,36 @@ var ItemRemoveController = /*#__PURE__*/function () { function useInit() { this._itemsToRemove = []; } + /** * Request an item to be removed. * * @param item - The item to be removed. */ - }, { key: "removeItem", value: function removeItem(item) { this._itemsToRemove.push(item); } + /** * Return all the items to remove. */ - }, { key: "getItemsToRemove", value: function getItemsToRemove() { return this._itemsToRemove; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._itemsToRemove = []; } }]); - return ItemRemoveController; }(); @@ -536,48 +501,41 @@ var LayoutController = /*#__PURE__*/function () { /** Constructor. */ function LayoutController() { _classCallCheck(this, LayoutController); - _defineProperty(this, "_itemsToRefresh", void 0); - _defineProperty(this, "_itemsToShow", void 0); - _defineProperty(this, "_itemsToHide", void 0); - _defineProperty(this, "_isRendering", void 0); - this._itemsToRefresh = []; this._itemsToShow = []; this._itemsToHide = []; this._isRendering = false; } + /** * Init. */ - - _createClass(LayoutController, [{ key: "useInit", value: function useInit() { var _this = this; - // Items. this._itemsToRefresh = []; this._itemsToShow = []; - this._itemsToHide = []; // State. - - this._isRendering = true; // Change state. + this._itemsToHide = []; + // State. + this._isRendering = true; + // Change state. // eslint-disable-next-line - useEffect(function () { _this._isRendering = false; }); } + /** * Refresh an item. * * @param item - The item to refresh. */ - }, { key: "refreshItem", value: function refreshItem(item) { @@ -589,12 +547,13 @@ var LayoutController = /*#__PURE__*/function () { } else { // If the item is changing parent this // will get the right parent. - var grid = item.getGrid(); // The layout is managed here. - + var grid = item.getGrid(); + // The layout is managed here. grid.refreshItems([item]); grid.layout(); } } + /** * Set an item visibility. * @@ -602,7 +561,6 @@ var LayoutController = /*#__PURE__*/function () { * @param visible - The visibility. * @param instant - If the visibility change should happen without animations. */ - }, { key: "setItemVisibility", value: function setItemVisibility(item, visible, instant) { @@ -614,8 +572,8 @@ var LayoutController = /*#__PURE__*/function () { } else { // If the item is changing parent this // will get the right parent. - var grid = item.getGrid(); // The layout is managed here. - + var grid = item.getGrid(); + // The layout is managed here. if (visible) grid.show([item], { instant: instant });else grid.hide([item], { @@ -623,43 +581,43 @@ var LayoutController = /*#__PURE__*/function () { }); } } + /** * Get the items that have to be refreshed. * * @returns - The items. */ - }, { key: "getItemsToRefresh", value: function getItemsToRefresh() { return this._itemsToRefresh; } + /** * Get the items that have to be shown. * * @returns - The items. */ - }, { key: "getItemsToShow", value: function getItemsToShow() { return this._itemsToShow; } + /** * Get the items that have to be hidden. * * @returns - The items. */ - }, { key: "getItemsToHide", value: function getItemsToHide() { return this._itemsToHide; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -668,7 +626,6 @@ var LayoutController = /*#__PURE__*/function () { this._itemsToHide = []; } }]); - return LayoutController; }(); @@ -681,12 +638,9 @@ var LayoutController = /*#__PURE__*/function () { var FiberController = /*#__PURE__*/function () { function FiberController() { _classCallCheck(this, FiberController); - _defineProperty(this, "_fiber", void 0); - _defineProperty(this, "_flag", '0'); } - _createClass(FiberController, [{ key: "useInit", value: @@ -697,58 +651,58 @@ var FiberController = /*#__PURE__*/function () { */ function useInit(gridElementRef) { var _this = this; - - this.updateFlag(); // eslint-disable-next-line - + this.updateFlag(); + // eslint-disable-next-line useEffect(function () { invariant(gridElementRef.current !== null); _this._fiber = getFiber(gridElementRef.current); }, []); // eslint-disable-line } + /** * Return the DOM elements in the chosen positions. * * @param orderedIndices - The positions. * @returns - The elements. */ - }, { key: "getStateNodes", value: function getStateNodes(orderedIndices) { - var stateNodes = []; // If there aren't indices retun an empty array. + var stateNodes = []; + // If there aren't indices retun an empty array. + if (orderedIndices.length === 0) return stateNodes; - if (orderedIndices.length === 0) return stateNodes; // The first child. + // The first child. + var child = getCurrentFiber(this._fiber, this._flag).child; - var child = getCurrentFiber(this._fiber, this._flag).child; // Fill the state nodes array. + // Fill the state nodes array. // We trust that the user input. - orderedIndices.forEach(function (index) { // @ts-ignore while (child.index !== index) { // @ts-ignore child = child.sibling; - } // @ts-ignore - + } + // @ts-ignore stateNodes.push(getStateNode(child)); }); return stateNodes; } + /** * Append an itemComponent fiber * (the same is done for the alternate if exists). * * @param child - The item. */ - }, { key: "append", value: function append(itemComponentFiber) { // Get the current fiber. - var fiber = getCurrentFiber(this._fiber, this._flag); // Append the fiber. - + var fiber = getCurrentFiber(this._fiber, this._flag); + // Append the fiber. appendFiber(fiber, itemComponentFiber); - if (fiber.alternate) { if (itemComponentFiber.alternate) { // Append the alternate. @@ -756,6 +710,7 @@ var FiberController = /*#__PURE__*/function () { } } } + /** * Remove an itemComponent fiber given the key of its Item * (The same is done for the alternate if exists). @@ -763,48 +718,45 @@ var FiberController = /*#__PURE__*/function () { * @param key - The key of the item. * @returns - The removed item. */ - }, { key: "remove", value: function remove(key) { // Get the current fiber. - var fiber = getCurrentFiber(this._fiber, this._flag); // Remove the fiber. - + var fiber = getCurrentFiber(this._fiber, this._flag); + // Remove the fiber. var removedChild = removeChild(fiber, key); - if (fiber.alternate) { if (removedChild.alternate) { // Remove the alternate. removeChild(fiber.alternate, key); } } - return removedChild; } + /** * Return the props containing the flag value to add in the grid element. * * @returns - The props. */ - }, { key: "getFlagProp", value: function getFlagProp() { return _defineProperty({}, FlagProp, this._flag); } + /** * Update the flag value. */ - }, { key: "updateFlag", value: function updateFlag() { if (this._flag === '0') this._flag = '1';else this._flag = '0'; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -812,29 +764,30 @@ var FiberController = /*#__PURE__*/function () { this._fiber = null; } }]); - return FiberController; }(); + /** * The flag prop name. */ - var FlagProp = 'muuri-react-flag'; + /** * Get the fiber of the given grid element. * * @param grid - The element. * @return - The fiber node. */ - function getFiber(grid) { var key = Object.keys(grid).find(function (key) { return key.startsWith('__reactInternalInstance$') || key.startsWith('__reactFiber$'); }); - invariant(typeof key === 'string', 'Cannot find the __reactInternalInstance$'); // @ts-ignore + invariant(typeof key === 'string', 'Cannot find the __reactInternalInstance$'); + // @ts-ignore return grid[key]; } + /** * Return the current fiber. * Try to use the prop flag for the search first, @@ -850,37 +803,40 @@ function getFiber(grid) { * @param flag - the flag. * @returns - The current fiber. */ - - function getCurrentFiber(fiber, currentFlag) { - if (!fiber.alternate) return fiber; // Flags. + if (!fiber.alternate) return fiber; + // Flags. var fiberFlag = fiber.memoizedProps[FlagProp]; - var alternateFlag = fiber.alternate.memoizedProps[FlagProp]; // If the two flags are the same it should mean that + var alternateFlag = fiber.alternate.memoizedProps[FlagProp]; + + // If the two flags are the same it should mean that // in at least one of the items there has been a re-render // from the last render of the GridComponent. // We can no longer trust the flag prop and we have // to look for the RootFiber and check which // fiber is in the current tree. - if (fiberFlag === alternateFlag) { - var topFiber = fiber; // Get the top fiber - // (Not the RootFiber). + var topFiber = fiber; + // Get the top fiber + // (Not the RootFiber). while (topFiber["return"]) { topFiber = topFiber["return"]; - } // Fibers. - + } + // Fibers. var rootFiber = topFiber.stateNode; - var topCurrentFiber = rootFiber.current; // The current fiber. + var topCurrentFiber = rootFiber.current; + // The current fiber. return topCurrentFiber === topFiber ? fiber : fiber.alternate; - } // If we got here we can trust the flag prop to find the current Fiber. - + } + // If we got here we can trust the flag prop to find the current Fiber. return fiberFlag === currentFlag ? fiber : fiber.alternate; } + /** * Returns the first stateNode among the descendants * of the given itemComponent Fiber. @@ -888,51 +844,44 @@ function getCurrentFiber(fiber, currentFlag) { * @param itemComponentFiber - The fiber. * @returns - The element. */ - - function getStateNode(itemComponentFiber) { // ItemComponent -> ItemProvider -> Item. - var itemFiber = itemComponentFiber.child.child; // @ts-ignore - - while (!(itemFiber.stateNode instanceof HTMLElement)) { - // @ts-ignore - itemFiber = itemFiber.child; - } - + var itemFiber = itemComponentFiber.child.child; + // @ts-ignore + while (!(itemFiber.stateNode instanceof HTMLElement)) + // @ts-ignore + itemFiber = itemFiber.child; return itemFiber.stateNode; } + /** * Append the child fiber in the last position among the children of the parent fiber. * * @param parent - The parent fiber. * @param child - The child fiber. */ - - function appendFiber(parent, child) { var _parent$return; - if (!parent.child) { // If it has no child. parent.child = child; child.index = 0; } else { var c = parent.child; - while (c.sibling) { c = c.sibling; } - - child.index = c.index + 1; // Inserted as last child. - + child.index = c.index + 1; + // Inserted as last child. c.sibling = child; - } // Update the references. - - - child["return"] = parent; // If we are in development. + } + // Update the references. + child["return"] = parent; + // If we are in development. if (child._debugOwner) child._debugOwner = (_parent$return = parent["return"]) === null || _parent$return === void 0 ? void 0 : _parent$return["return"]; } + /** * Remove a child with the given key from the fiber. * @@ -940,76 +889,71 @@ function appendFiber(parent, child) { * @param key - The key of the item. * @return - The removed fiber. */ - - function removeChild(parent, key) { var child = parent.child; - var removedChild; // @ts-ignore + var removedChild; + // @ts-ignore if (hasNot(child, key)) { // @ts-ignore while (hasNot(child.sibling, key)) { // @ts-ignore child = child.sibling; - } // @ts-ignore - - - removedChild = removeSibling(child); // @ts-ignore - + } + // @ts-ignore + removedChild = removeSibling(child); + // @ts-ignore adjustIndices(child); } else { - removedChild = removeFirstChild(parent); // @ts-ignore - + removedChild = removeFirstChild(parent); + // @ts-ignore child = child.sibling; if (child) adjustIndices(child); } - removedChild.sibling = null; return removedChild; } + /** * Remove the first itemComponent fiber of a gridELement fiber and return it. * * @param GridElementFiber - The gridELement fiber. * @return - The removed itemComponent fiber. */ - - function removeFirstChild(gridElementFiber) { - var removed = gridElementFiber.child; // @ts-ignore - - gridElementFiber.child = gridElementFiber.child.sibling; // @ts-ignore - + var removed = gridElementFiber.child; + // @ts-ignore + gridElementFiber.child = gridElementFiber.child.sibling; + // @ts-ignore return removed; } + /** * Remove the first sibling from a itemComponent fiber and return it. * * @param fiber - The fiber. * @return - The removed sibling. */ - - function removeSibling(fiber) { - var removed = fiber.sibling; // @ts-ignore - - fiber.sibling = fiber.sibling.sibling; // @ts-ignore - + var removed = fiber.sibling; + // @ts-ignore + fiber.sibling = fiber.sibling.sibling; + // @ts-ignore return removed; } + /** * Adjust the indices of the siblings of an itemComponent fiber. * * @param itemComponentFiber - The itemComponent fiber. */ - - function adjustIndices(itemComponentFiber) { while (itemComponentFiber.sibling) { itemComponentFiber.sibling.index = itemComponentFiber.index + 1; itemComponentFiber = itemComponentFiber.sibling; } } + /** * Returns if the itemComponent fiber is not the parent of the item with the given key. * @@ -1017,8 +961,6 @@ function adjustIndices(itemComponentFiber) { * @param key - The key of the item. * @return - If the itemComponent fiber is not the parent of the item with the given key. */ - - function hasNot(itemComponentFiber, key) { // ItemComponent -> ItemProvider -> Item. return itemComponentFiber.child.child.key !== key; @@ -1034,16 +976,11 @@ function hasNot(itemComponentFiber, key) { var ChildrenController = /*#__PURE__*/function () { function ChildrenController() { _classCallCheck(this, ChildrenController); - _defineProperty(this, "_oldChildrenArray", []); - _defineProperty(this, "_children", []); - _defineProperty(this, "_indicesToAdd", []); - _defineProperty(this, "_dragCounter", 0); } - _createClass(ChildrenController, [{ key: "useInit", value: @@ -1055,55 +992,57 @@ var ChildrenController = /*#__PURE__*/function () { function useInit(newChildren) { // @ts-ignore // We need to ensure that the children are in an array. - var newChildrenArray = Children.toArray(newChildren); // The indices to add. + var newChildrenArray = Children.toArray(newChildren); - this._indicesToAdd = getIndicesToAdd(newChildrenArray, this._oldChildrenArray); // The _children will be used to map all + // The indices to add. + this._indicesToAdd = getIndicesToAdd(newChildrenArray, this._oldChildrenArray); + + // The _children will be used to map all // the child in the render method. // We can't use the ChildrenArray because we need the users // key provided in the components and not the escaped one (e.g. .$1). - this._children = newChildren || []; this._oldChildrenArray = newChildrenArray; } + /** * Remove a child in the given position and return it. * * @param index - The index of the child to remove. * @returns - The removed child. */ - }, { key: "remove", value: function remove(index) { return this._oldChildrenArray.splice(index, 1)[0]; } + /** * Append a child in the children array. * * @param child - The child to append. */ - }, { key: "append", value: function append(child) { this._oldChildrenArray.push(child); } + /** * Returns the ordered array of indices of the added children. */ - }, { key: "getIndicesToAdd", value: function getIndicesToAdd() { return this._indicesToAdd; } + /** * Map all the children. * * @param cb - The callback. * @returns - The mapped children. */ - }, { key: "render", value: function render(cb) { @@ -1112,10 +1051,12 @@ var ChildrenController = /*#__PURE__*/function () { // there are rare cases where the keys are not indispensable, // the user may not choose to use at his own risk. return cb(child, child.key); - }); // Flush the children. + }); + // Flush the children. this.flush(); return children; + /** // If an item is being dragged we need to ensure // that no child is inserted before it. @@ -1124,46 +1065,46 @@ var ChildrenController = /*#__PURE__*/function () { : getChildrenInSafePositions(children, this._indicesToAdd); */ } + /** * Increment the drag counter. */ - }, { key: "incrementDragCounter", value: function incrementDragCounter() { this._dragCounter += 1; } + /** * Decrement the drag counter. */ - }, { key: "decrementDragCounter", value: function decrementDragCounter() { this._dragCounter -= 1; } + /** * Remove the current children so they can be garbage collected. */ - }, { key: "flush", value: function flush() { this._children = []; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this.flush(); } }]); - return ChildrenController; }(); + /** * Return an array of positions of the added children. * The algorithm is optimized for cases where the order of @@ -1174,15 +1115,12 @@ var ChildrenController = /*#__PURE__*/function () { * @param oldChildren - The old children. * @return - The indices. */ - function getIndicesToAdd(newChildren, oldChildren) { var indicesToAdd = []; var oIndex = 0; - for (var nIndex = 0; nIndex < newChildren.length; nIndex++) { // Finde the index. var index = findIndex(oldChildren, newChildren[nIndex], oIndex); - if (index === -1) { // If it is not present is a new Child. indicesToAdd.push(nIndex); @@ -1192,9 +1130,9 @@ function getIndicesToAdd(newChildren, oldChildren) { oIndex = index; } } - return indicesToAdd; } + /** * Returns the index of the child in the children array, * if it is not present returns -1. @@ -1205,22 +1143,23 @@ function getIndicesToAdd(newChildren, oldChildren) { * @param fromIndex - The initial index. * @returns - The index of the child. */ - function findIndex(children, child, fromIndex) { - fromIndex = fromIndex > children.length ? children.length : fromIndex; // If the heuristics are respected the child will be here. + fromIndex = fromIndex > children.length ? children.length : fromIndex; + // If the heuristics are respected the child will be here. for (var index = fromIndex; index < children.length; index++) { if (is(child, children[index])) return index; - } // If the child is here the heuristics are not respected. - + } + // If the child is here the heuristics are not respected. for (var _index = 0; _index < fromIndex; _index++) { if (is(child, children[_index])) return _index; - } // The child is not present. - + } + // The child is not present. return -1; } + /** * There would be the risk that a component will be inserted before * an item that is being dragged (and that is placed in a drag @@ -1259,8 +1198,6 @@ function getChildrenInSafePositions( * @param componentB - The second component. * @returns - If they have the same key. */ - - function is(componentA, componentB) { return componentA.key === componentB.key; } @@ -1272,18 +1209,21 @@ function is(componentA, componentB) { * @param grid - The Muuri instance. */ function fillGrid(grid) { - var sizerElement = document.createElement('div'); // Keep the element hidden. + var sizerElement = document.createElement('div'); + // Keep the element hidden. sizerElement.style.visibility = 'hidden'; - sizerElement.style.position = 'absolute'; // Add the class. - - sizerElement.classList.add('grid-sizer'); // Set the element. + sizerElement.style.position = 'absolute'; + // Add the class. + sizerElement.classList.add('grid-sizer'); + // Set the element. addDecoration(grid, { sizerElement: sizerElement }); - var gridElement = grid.getElement(); // Insert as first child. + var gridElement = grid.getElement(); + // Insert as first child. if (gridElement.children.length === 0) { gridElement.appendChild(sizerElement); } else { @@ -1293,6 +1233,7 @@ function fillGrid(grid) { // Allowed position values. var positions = ['relative', 'absolute', 'fixed']; + /** * Fill a grid element: * - If it is not position the style.position is setted to "relative". @@ -1305,26 +1246,25 @@ var positions = ['relative', 'absolute', 'fixed']; * @param gridElement - The element to fill. * @param gridClass - The Css class of the grid element. */ - function fillGridElement(gridElement, gridClass) { - var position = getComputedStyle(gridElement).position; // Set the default position. + var position = getComputedStyle(gridElement).position; + // Set the default position. if (!positions.includes(position)) { gridElement.style.position = positions[0]; - } // Set the grid class. - + } - gridElement.classList.add(gridClass); // Ensure that the grid class can't be removed. + // Set the grid class. + gridElement.classList.add(gridClass); + // Ensure that the grid class can't be removed. var defaultSetAttribute = gridElement.setAttribute.bind(gridElement); - gridElement.setAttribute = function setAttribute(attribute, value) { if (attribute === 'class') { - var classNames = (gridElement.getAttribute('class') || '').split(' '); // Add the grid class. - + var classNames = (gridElement.getAttribute('class') || '').split(' '); + // Add the grid class. if (!classNames.includes(gridClass)) value = "".concat(value, " ").concat(gridClass); } - defaultSetAttribute(attribute, value); }; } @@ -1336,18 +1276,18 @@ function fillGridElement(gridElement, gridClass) { * * @param item - The item to fill. */ - function fillItem(item) { addDecoration(item, { props: {}, data: {} - }); // Change the sort data. - + }); + // Change the sort data. Object.defineProperty(item, '_sortData', { get: function get() { return this.getData(); }, - set: function set() {// nothing to do here. + set: function set() { + // nothing to do here. } }); } @@ -1364,20 +1304,20 @@ function fillItem(item) { * @param itemClasses - The Css classes of the items. */ function fillItemElement(itemElement, itemClasses) { - itemElement.style.position = 'absolute'; // Ensure that the Css item classes are not removed. + itemElement.style.position = 'absolute'; + // Ensure that the Css item classes are not removed. var defaultSetAttribute = itemElement.setAttribute.bind(itemElement); - itemElement.setAttribute = function setAttribute(attribute, value) { if (attribute === 'class') { var classNames = (itemElement.getAttribute('class') || '').split(' '); var classNamesToAdd = classNames.filter(function (className) { return itemClasses.includes(className); - }); // Add the Css items classes. + }); + // Add the Css items classes. value = "".concat(value, " ").concat(classNamesToAdd.join(' ')); } - defaultSetAttribute(attribute, value); }; } @@ -1390,7 +1330,6 @@ function fillItemElement(itemElement, itemClasses) { * @param callback - The function to memoize. * @returns - The memoized function. */ - function useFunction(callback) { return useRef(callback).current; } @@ -1402,17 +1341,19 @@ function useFunction(callback) { * @param dependencyList - The dependencyList. * @returns - If the dependencyList is changed from the previous render. */ - function useReference(dependencyList) { - var ref = useRef(dependencyList); // If it is the first call return true. + var ref = useRef(dependencyList); - if (ref.current === dependencyList) return true; // Compare the dependencyLists. - - var didUpdate = compare(ref.current, dependencyList); // Keep the reference of the new one. + // If it is the first call return true. + if (ref.current === dependencyList) return true; + // Compare the dependencyLists. + var didUpdate = compare(ref.current, dependencyList); + // Keep the reference of the new one. ref.current = dependencyList; return didUpdate; } + /** * Compare two dependencyLists and return if they are different. * @@ -1420,14 +1361,11 @@ function useReference(dependencyList) { * @param b - The second dependencyList to compare. * @returns - If the 2 dependencyLists are different. */ - function compare(a, b) { if (a.length !== b.length) return true; - for (var i = 0; i < a.length; i++) { if (a[i] !== b[i]) return true; } - return false; } @@ -1437,18 +1375,18 @@ function compare(a, b) { * @param didUpdate - The method to run. * @param deps - The dependecies. */ - function useInstantEffect(didUpdate, deps) { // Deps check. var needUpdate = useReference(deps); - var cleanUpRef = useRef(); // Run. + var cleanUpRef = useRef(); + // Run. if (needUpdate) { if (cleanUpRef.current) cleanUpRef.current(); cleanUpRef.current = didUpdate(); - } // Catch unmount. - + } + // Catch unmount. useEffect(function () { return function () { if (cleanUpRef.current) cleanUpRef.current(); @@ -1464,14 +1402,11 @@ function useInstantEffect(didUpdate, deps) { * @param factory - The factory method. * @returns - The memoized value. */ - function useMemoized(factory) { var valueRef = useRef(); - if (!valueRef.current) { valueRef.current = factory(); } - return valueRef.current; } @@ -1481,7 +1416,6 @@ function useMemoized(factory) { * * @returns - The re-render method. */ - function useRerender() { var setState = useState()[1]; return useFunction(function () { @@ -1494,92 +1428,102 @@ function useRerender() { // Item component. function ItemComponent(_ref) { var child = _ref.children, - itemClasses = _ref.itemClasses, - itemAddController = _ref.itemAddController, - itemRemoveController = _ref.itemRemoveController, - propsToData = _ref.propsToData, - itemKey = _ref.itemKey, - grid = _ref.grid; + itemClasses = _ref.itemClasses, + itemAddController = _ref.itemAddController, + itemRemoveController = _ref.itemRemoveController, + propsToData = _ref.propsToData, + itemKey = _ref.itemKey, + grid = _ref.grid; // The store provided doesn't change the reference. var store = useMemoized(function () { // Create the controllers. var eventController = new EventController(); - var itemRefController = new ItemRefController(); // Add the data that won't change. - + var itemRefController = new ItemRefController(); + // Add the data that won't change. itemRefController.set('key', itemKey); - itemRefController.set('eventController', eventController); // Return the controllers. - + itemRefController.set('eventController', eventController); + // Return the controllers. return { eventController: eventController, itemRefController: itemRefController, itemRemoveController: itemRemoveController, grid: grid }; - }); // Set the props. + }); + // Set the props. store.itemRefController.set('props', child.props); store.itemRemoveController = itemRemoveController; - store.grid = grid; // Set the data. + store.grid = grid; + // Set the data. if (propsToData) { // Get the data. - var data = propsToData(child.props); // Must be an object. + var data = propsToData(child.props); - invariant(_typeof(data) === 'object', "The data returned by 'propsToData' must be an object, founded ".concat(_typeof(data))); // Set the data. + // Must be an object. + invariant(_typeof(data) === 'object', "The data returned by 'propsToData' must be an object, founded ".concat(_typeof(data))); + // Set the data. store.itemRefController.set('data', data); - } // On mount. - + } + // On mount. useEffect(function () { // Request the item. itemAddController.requestItem(function (item) { - fillItem(item); // @ts-ignore - + fillItem(item); + // @ts-ignore fillItemElement(item.getElement(), itemClasses); store.itemRefController.setItem(item); }); return function () { // The item. var item = store.itemRefController.getItem(); - invariant(item !== null); // The element. + invariant(item !== null); + // The element. var element = item.getElement(); - invariant(element !== undefined); // If the item is going to be unmounted + invariant(element !== undefined); + + // If the item is going to be unmounted // and it is being dragged it have to end the event // (Because it could be child of a different DOM element). - if (item.isDragging()) { element.style.display = 'none'; - element.style.visibility = 'hidden'; // @ts-ignore + element.style.visibility = 'hidden'; + // @ts-ignore if (item._drag) item._drag.destroy(); store.grid.getElement().appendChild(element); - } // Remove the item. - + } + // Remove the item. store.itemRefController["delete"](); - store.itemRemoveController.removeItem(item); // Destroy the controllers instances. + store.itemRemoveController.removeItem(item); + // Destroy the controllers instances. store.itemRefController.destroy(); store.eventController.destroy(); }; }, []); // eslint-disable-line - // Render. + // Render. return /*#__PURE__*/React.createElement(ItemProvider, { value: store }, child); -} // PropTypes. +} +// PropTypes. ItemComponent.propTypes = { itemAddController: PropTypes.object.isRequired, itemClasses: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired, propsToData: PropTypes.func, children: PropTypes.element.isRequired, grid: PropTypes.instanceOf(Muuri).isRequired -}; // Display name. +}; +// Display name. ItemComponent.displayName = 'ItemComponent'; /** @@ -1598,10 +1542,10 @@ function addItems(grid, addedDOMItems, indicesToAdd, addOptions, filter) { index: indicesToAdd[i], layout: false }); - } // Show the added items (usefull just if the items are - // hidden by default and the filter is not setted). - + } + // Show the added items (usefull just if the items are + // hidden by default and the filter is not setted). if (!filter && addOptions !== null && addOptions !== void 0 && addOptions.show) { grid.show(grid.getItems(indicesToAdd), { layout: false @@ -1625,13 +1569,13 @@ function filterItems(grid, predicate) { /** Class name. */ var gridClassName = 'containerClass'; + /** * Returns the Css class of the grid element. * * @param grid - The Muuri instance. * @returns - The class. */ - function getGridClass(grid) { // @ts-ignore return grid._settings[gridClassName]; @@ -1639,13 +1583,13 @@ function getGridClass(grid) { /** Class names. */ var itemClassNames = ['itemClass', 'itemVisibleClass', 'itemHiddenClass', 'itemPositioningClass', 'itemDraggingClass', 'itemReleasingClass', 'itemPlaceholderClass']; + /** * Returns the items classes. * * @param grid - The Muuri instance. * @returns - The classes. */ - function getItemClasses(grid) { // @ts-ignore return itemClassNames.map(function (className) { @@ -1690,10 +1634,8 @@ function showItems(grid, items) { }); } -function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - +function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * Sort the items. * @@ -1706,22 +1648,24 @@ function sortItems(grid, predicate, sortOptions) { // @ts-ignore sortOptions = _objectSpread$1(_objectSpread$1({}, sortOptions || {}), {}, { layout: false - }); // Handle a function. + }); + // Handle a function. if (typeof predicate === 'function') { handleFunction(grid, predicate, sortOptions); - } // Handle a string. - + } + // Handle a string. if (typeof predicate === 'string') { handleString(grid, predicate, sortOptions); - } // Hanndle an array of keys. - + } + // Hanndle an array of keys. if (Array.isArray(predicate)) { handleArray(grid, predicate, sortOptions); } } + /** * Sort the items given a predicate function. * @@ -1729,12 +1673,12 @@ function sortItems(grid, predicate, sortOptions) { * @param predicate - The predicate function. * @param sortOptions - The sort options. */ - function handleFunction(grid, predicate, sortOptions) { grid.sort(function (itemA, itemB) { return predicate(itemA.getData(), itemB.getData(), itemA, itemB); }, sortOptions); } + /** * Sort the items given a predicate string. * @@ -1742,11 +1686,10 @@ function handleFunction(grid, predicate, sortOptions) { * @param predicate - The predicate string. * @param sortOptions - The sort options. */ - - function handleString(grid, predicate, sortOptions) { grid.sort(predicate, sortOptions); } + /** * Sort the items given an array of keys. * If the key has a match, the item is inserted in that position, otherwise at the bottom. @@ -1755,29 +1698,29 @@ function handleString(grid, predicate, sortOptions) { * @param predicate - The array of keys. * @param sortOptions - The sort options. */ - - function handleArray(grid, predicate, sortOptions) { - var items = grid.getItems(); // Items that can be sorted. - - var sortedItems = []; // Items that can't be sorted. - - var otherItems = []; // Fills the arrays. + var items = grid.getItems(); + // Items that can be sorted. + var sortedItems = []; + // Items that can't be sorted. + var otherItems = []; + // Fills the arrays. items.forEach(function (item) { var itemKey = item._component.key; var index = predicate.findIndex(function (key) { return key === itemKey; }); - if (index > -1) { sortedItems[index] = item; } else { otherItems.push(item); } - }); // Sort. + }); - grid.sort(Array.prototype.concat( // Some position can be empty. + // Sort. + grid.sort(Array.prototype.concat( + // Some position can be empty. sortedItems.filter(function (item) { return !!item; }), otherItems), sortOptions); @@ -1788,30 +1731,28 @@ function handleArray(grid, predicate, sortOptions) { // Grid component. function GridComponent(_ref) { var children = _ref.children, - gridProps = _ref.gridProps, - grid = _ref.grid, - filter = _ref.filter, - sort = _ref.sort, - sortOptions = _ref.sortOptions, - addOptions = _ref.addOptions, - propsToData = _ref.propsToData, - onSend = _ref.onSend, - onDragStart = _ref.onDragStart, - onDragEnd = _ref.onDragEnd, - onFilter = _ref.onFilter, - onSort = _ref.onSort, - onMount = _ref.onMount, - onUnmount = _ref.onUnmount, - forceSync = _ref.forceSync, - dragFixed = _ref.dragFixed, - dragEnabled = _ref.dragEnabled, - instantLayout = _ref.instantLayout; - + gridProps = _ref.gridProps, + grid = _ref.grid, + filter = _ref.filter, + sort = _ref.sort, + sortOptions = _ref.sortOptions, + addOptions = _ref.addOptions, + propsToData = _ref.propsToData, + onSend = _ref.onSend, + onDragStart = _ref.onDragStart, + onDragEnd = _ref.onDragEnd, + onFilter = _ref.onFilter, + onSort = _ref.onSort, + onMount = _ref.onMount, + onUnmount = _ref.onUnmount, + forceSync = _ref.forceSync, + dragFixed = _ref.dragFixed, + dragEnabled = _ref.dragEnabled, + instantLayout = _ref.instantLayout; /* ------------------ */ - /* ----- STORES ----- */ - /* ------------------ */ + // Store references of objects // generated in previous renders. var store = useMemoized(function () { @@ -1819,31 +1760,16 @@ function GridComponent(_ref) { // Grid and items data. gridRef: /*#__PURE__*/ - /* */ createRef(), - gridClass: - /* */ - getGridClass(grid), - itemClasses: - /* */ - getItemClasses(grid), + gridClass: /* */getGridClass(grid), + itemClasses: /* */getItemClasses(grid), // Controllers. - childrenController: - /* */ - new ChildrenController(), - fiberController: - /* */ - new FiberController(), - itemAddController: - /* */ - new ItemAddController(), - itemRemoveController: - /* */ - new ItemRemoveController(), - layoutController: - /* */ - new LayoutController(), + childrenController: /* */new ChildrenController(), + fiberController: /* */new FiberController(), + itemAddController: /* */new ItemAddController(), + itemRemoveController: /* */new ItemRemoveController(), + layoutController: /* */new LayoutController(), // Events. onUnmount: onUnmount, onDragStart: onDragStart, @@ -1852,73 +1778,46 @@ function GridComponent(_ref) { onSort: onSort, onSend: onSend }; - }); // Store references of objects + }); + + // Store references of objects // that are used inside useEffect. // The references are flushed on each new render. - var vars = { // Items data. - indicesToAdd: - /* */ - [], - addedDOMItems: - /* */ - [], - itemsToRemove: - /* */ - [], - itemsToRefresh: - /* */ - [], - itemsToShow: - /* */ - [], - itemsToHide: - /* */ - [], + indicesToAdd: /* */[], + addedDOMItems: /* */[], + itemsToRemove: /* */[], + itemsToRefresh: /* */[], + itemsToShow: /* */[], + itemsToHide: /* */[], // Items flags. - hasAdded: - /* */ - false, - hasRemoved: - /* */ - false, - hasFiltered: - /* */ - false, - hasSorted: - /* */ - false, - hasRefreshed: - /* */ - false, - hasShown: - /* */ - false, - hasHidden: - /* */ - false + hasAdded: /* */false, + hasRemoved: /* */false, + hasFiltered: /* */false, + hasSorted: /* */false, + hasRefreshed: /* */false, + hasShown: /* */false, + hasHidden: /* */false }; - /* ----------------- */ + /* ----------------- */ /* ----- MOUNT ----- */ - /* ----------------- */ - // Initialize the grid on mount. + // Initialize the grid on mount. useEffect(function () { /* ------------------ */ - /* ----- EVENTS ----- */ - /* ------------------ */ + // Add all the event handlers. - grid // "Send" and "receive" events. + grid + // "Send" and "receive" events. .on('beforeSend', function (_ref2) { var item = _ref2.item, - fromGrid = _ref2.fromGrid, - fromIndex = _ref2.fromIndex; - + fromGrid = _ref2.fromGrid, + fromIndex = _ref2.fromIndex; if (!getDecoration(item).sentPayload) { // Generate the sentPayload. var sentPayload = { @@ -1926,23 +1825,25 @@ function GridComponent(_ref) { fromFiberController: store.fiberController, fromGrid: fromGrid, fromIndex: fromIndex - }; // Add the decoration. + }; + // Add the decoration. addDecoration(item, { sentPayload: sentPayload }); } }).on('receive', function (_ref3) { var item = _ref3.item, - toGrid = _ref3.toGrid, - toIndex = _ref3.toIndex; + toGrid = _ref3.toGrid, + toIndex = _ref3.toIndex; // Controllers. var toChildrenController = store.childrenController; - var toFiberController = store.fiberController; // If the method is activated by user interaction (the item is being dragged) + var toFiberController = store.fiberController; + + // If the method is activated by user interaction (the item is being dragged) // the synchronization will be performed during the "dragEnd" event. // If the method is called via Muuri's instance (the item is not being dragged) // the synchronization takes place here, but the onSend callback is not fired. - if (item.isDragging()) { // Generate the receivedPayload. var receivedPayload = { @@ -1950,82 +1851,95 @@ function GridComponent(_ref) { toFiberController: toFiberController, toGrid: toGrid, toIndex: toIndex - }; // Add the decoration. + }; + // Add the decoration. addDecoration(item, { receivedPayload: receivedPayload }); } else { // Payloads data. - var sentPayload = getDecoration(item).sentPayload; // The payload must have been created in the send method. - - invariant(sentPayload !== null && _typeof(sentPayload) === 'object'); // Controllers. - + var sentPayload = getDecoration(item).sentPayload; + // The payload must have been created in the send method. + invariant(sentPayload !== null && _typeof(sentPayload) === 'object'); + // Controllers. var fromChildrenController = sentPayload.fromChildrenController, - fromFiberController = sentPayload.fromFiberController; // Remove the payload. + fromFiberController = sentPayload.fromFiberController; + // Remove the payload. addDecoration(item, { sentPayload: null - }); // Remove the item instances from the old GridComponent. + }); + // Remove the item instances from the old GridComponent. var itemFiber = fromFiberController.remove(item.getKey()); - var itemComponent = fromChildrenController.remove(itemFiber.index); // Add the item instances to the new GridComponent. + var itemComponent = fromChildrenController.remove(itemFiber.index); + // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); toChildrenController.append(itemComponent); - } // Emit the "send" event. - + } + // Emit the "send" event. getDecoration(item).eventController.emitEvent('send', grid); - }) // Drag events. + }) + + // Drag events. .on('dragInit', function (item, event) { // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. - store.childrenController.incrementDragCounter(); // Emit the "drag" event. + store.childrenController.incrementDragCounter(); + // Emit the "drag" event. // This event is used instead of "dragStart" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). - - getDecoration(item).eventController.emitEvent('drag', true); // "onDragStart" Callback. - + getDecoration(item).eventController.emitEvent('drag', true); + // "onDragStart" Callback. if (store.onDragStart) store.onDragStart(item, event); }).on('dragEnd', function (item) { // Payloads. var sentPayload = getDecoration(item).sentPayload; - var receivedPayload = getDecoration(item).receivedPayload; // If an item was sent during the drag the - // GridComponents are synchronized. + var receivedPayload = getDecoration(item).receivedPayload; + // If an item was sent during the drag the + // GridComponents are synchronized. if (sentPayload && receivedPayload) { // SentPayload data. var fromChildrenController = sentPayload.fromChildrenController, - fromFiberController = sentPayload.fromFiberController, - fromGrid = sentPayload.fromGrid, - fromIndex = sentPayload.fromIndex; // ReceivedPayload data. + fromFiberController = sentPayload.fromFiberController, + fromGrid = sentPayload.fromGrid, + fromIndex = sentPayload.fromIndex; + // ReceivedPayload data. var toChildrenController = receivedPayload.toChildrenController, - toFiberController = receivedPayload.toFiberController, - toGrid = receivedPayload.toGrid, - toIndex = receivedPayload.toIndex; // Reset the payloads. + toFiberController = receivedPayload.toFiberController, + toGrid = receivedPayload.toGrid, + toIndex = receivedPayload.toIndex; + // Reset the payloads. addDecoration(item, { sentPayload: null, receivedPayload: null - }); // Check if the item has been sended. + }); + // Check if the item has been sended. if (fromGrid !== toGrid) { // "onSend" will be called with the receive event. - invariant(typeof store.onSend === 'function', 'An item cannot be sent to another MuuriComponent if the ' + "'onSend' property has not been passed to the MuuriComponent."); // Remove the item instances from the old GridComponent. + invariant(typeof store.onSend === 'function', 'An item cannot be sent to another MuuriComponent if the ' + "'onSend' property has not been passed to the MuuriComponent."); + // Remove the item instances from the old GridComponent. var itemFiber = fromFiberController.remove(item.getKey()); - var itemComponent = fromChildrenController.remove(itemFiber.index); // Add the item instances to the new GridComponent. + var itemComponent = fromChildrenController.remove(itemFiber.index); + // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); - toChildrenController.append(itemComponent); // "onSend" callback. + toChildrenController.append(itemComponent); + + // "onSend" callback. // DragEnd is called in the grid where // the drag start, so onSend. - store.onSend({ // The key the user has set. key: getDecoration(item).key, @@ -2046,25 +1960,27 @@ function GridComponent(_ref) { // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. - store.childrenController.decrementDragCounter(); // Emit the event. + store.childrenController.decrementDragCounter(); + // Emit the event. // This event is used instead of "dragEnd" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). - - getDecoration(item).eventController.emitEvent('drag', false); // Call the event. - + getDecoration(item).eventController.emitEvent('drag', false); + // Call the event. if (store.onDragEnd) store.onDragEnd(item); - }) // Show and hide events. + }) + + // Show and hide events. .on('showStart', function (items) { // The items could be shown before they are decorated. - if (!isDecorated(items[0])) return; // Emit the event. - + if (!isDecorated(items[0])) return; + // Emit the event. items.forEach(function (item) { - var eventController = getDecoration(item).eventController; // The event is triggered also for items that have not + var eventController = getDecoration(item).eventController; + // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. - if (eventController.getPayload('show') !== true) { eventController.emitEvent('show', true); } @@ -2072,43 +1988,45 @@ function GridComponent(_ref) { }).on('hideEnd', function (items) { // Emit the event. items.forEach(function (item) { - var eventController = getDecoration(item).eventController; // The event is triggered also for items that have not + var eventController = getDecoration(item).eventController; + // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. - if (eventController.getPayload('show') !== false) { eventController.emitEvent('show', false); } }); - }) // Filter and sort events. + }) + + // Filter and sort events. .on('filter', function (shownItems, hiddenItems) { if (store.onFilter) store.onFilter(shownItems, hiddenItems); }).on('sort', function (currentOrder, previousOrder) { if (store.onSort) store.onSort(currentOrder, previousOrder); - }); // Fix the dimensions of the items when they are dragged. + }); + // Fix the dimensions of the items when they are dragged. if (dragFixed) { grid.on('dragInit', function (item) { // Let's set fixed widht/height to the dragged item // so that it does not stretch unwillingly when // it's appended to the document body for the // duration of the drag. - var element = item.getElement(); // The element must exist. - - invariant(element !== undefined); // Get the computed dimensions. - + var element = item.getElement(); + // The element must exist. + invariant(element !== undefined); + // Get the computed dimensions. var _getComputedStyle = getComputedStyle(element), - width = _getComputedStyle.width, - height = _getComputedStyle.height, - paddingTop = _getComputedStyle.paddingTop; // Save the previous style in case it was setted. - - + width = _getComputedStyle.width, + height = _getComputedStyle.height, + paddingTop = _getComputedStyle.paddingTop; + // Save the previous style in case it was setted. addDecoration(item, { dragWidth: element.style.width, dragHeight: element.style.height, dragPaddingTop: element.style.paddingTop - }); // Set the new style. - + }); + // Set the new style. element.style.width = width; element.style.height = height; element.style.paddingTop = paddingTop; @@ -2117,38 +2035,38 @@ function GridComponent(_ref) { // dragged item now that it is back in a grid // column and can freely adjust to it's // surroundings. - var element = item.getElement(); // The element must exist. - - invariant(element !== undefined); // Get the old style. - + var element = item.getElement(); + // The element must exist. + invariant(element !== undefined); + // Get the old style. var _getDecoration = getDecoration(item), - dragWidth = _getDecoration.dragWidth, - dragHeight = _getDecoration.dragHeight, - dragPaddingTop = _getDecoration.dragPaddingTop; // Restore the previous style in case it was setted. - - + dragWidth = _getDecoration.dragWidth, + dragHeight = _getDecoration.dragHeight, + dragPaddingTop = _getDecoration.dragPaddingTop; + // Restore the previous style in case it was setted. element.style.width = dragWidth; element.style.height = dragHeight; element.style.paddingTop = dragPaddingTop; }); } - /* ---------------- */ + /* ---------------- */ /* ----- GRID ----- */ - /* -----------------*/ - // Check . + // Check . + invariant(store.gridRef.current !== null); - invariant(store.gridRef.current !== null); // Work with the grid. + // Work with the grid. // @ts-ignore - grid._element = store.gridRef.current; fillGridElement(store.gridRef.current, store.gridClass); - fillGrid(grid); // "onMount" Callback. + fillGrid(grid); - if (onMount) onMount(grid); // Delete the instance from the global map. + // "onMount" Callback. + if (onMount) onMount(grid); + // Delete the instance from the global map. return function () { // Destroy the controllers. store.childrenController.destroy(); @@ -2160,35 +2078,37 @@ function GridComponent(_ref) { }, []); // eslint-disable-line /* ---------------- */ - /* ----- INIT ----- */ - /* -----------------*/ - // Init the controllers. + // Init the controllers. store.childrenController.useInit(children); store.fiberController.useInit(store.gridRef); store.itemRemoveController.useInit(); store.itemAddController.useInit(); - store.layoutController.useInit(); // IsChanged flags. + store.layoutController.useInit(); + // IsChanged flags. var isFilterChanged = useReference([filter]); - var isSortChanged = useReference([sort, sortOptions]); // Get items to add/remove. + var isSortChanged = useReference([sort, sortOptions]); + // Get items to add/remove. useEffect(function () { // Set drag enabled option. addDecoration(grid, { dragEnabled: dragEnabled - }); // Set the items data. + }); + // Set the items data. vars.indicesToAdd = store.childrenController.getIndicesToAdd(); vars.addedDOMItems = store.fiberController.getStateNodes(vars.indicesToAdd); vars.itemsToRemove = store.itemRemoveController.getItemsToRemove(); vars.itemsToRefresh = store.layoutController.getItemsToRefresh(); vars.itemsToShow = store.layoutController.getItemsToShow(); - vars.itemsToHide = store.layoutController.getItemsToHide(); // This will remove lot of the implementation - // problems for the user. + vars.itemsToHide = store.layoutController.getItemsToHide(); + // This will remove lot of the implementation + // problems for the user. store.onUnmount = onUnmount; store.onDragStart = onDragStart; store.onDragEnd = onDragEnd; @@ -2196,116 +2116,106 @@ function GridComponent(_ref) { store.onSort = onSort; store.onSend = onSend; }); - /* ------------------- */ + /* ------------------- */ /* ----- ACTIONS ----- */ - /* ------------------- */ useEffect(function () { /* ---------------------- */ - /* ---- ADD & REMOVE ---- */ - /* ---------------------- */ + // Remove items. if (vars.itemsToRemove.length) { - removeItems(grid, vars.itemsToRemove); // Set the flag. - + removeItems(grid, vars.itemsToRemove); + // Set the flag. vars.hasRemoved = true; - } // Add items after the old ones are removed - // to add them in the right positions. - + } + // Add items after the old ones are removed + // to add them in the right positions. if (vars.indicesToAdd.length) { - addItems(grid, vars.addedDOMItems, vars.indicesToAdd, addOptions, filter); // New Items. - - var addedItems = grid.getItems(vars.indicesToAdd); // Emit the new items to the itemComponents. - - store.itemAddController.emit(addedItems); // Set the flag. - + addItems(grid, vars.addedDOMItems, vars.indicesToAdd, addOptions, filter); + // New Items. + var addedItems = grid.getItems(vars.indicesToAdd); + // Emit the new items to the itemComponents. + store.itemAddController.emit(addedItems); + // Set the flag. vars.hasAdded = true; } - /* ------------------------- */ + /* ------------------------- */ /* ----- SORT & FILTER ----- */ - /* ------------------------- */ - // Filter items. - + // Filter items. if (filter && (isFilterChanged || vars.hasAdded || forceSync)) { - filterItems(grid, filter); // Set the flag. - + filterItems(grid, filter); + // Set the flag. vars.hasFiltered = true; - } // Sort items. - + } + // Sort items. if (sort && (isSortChanged || vars.hasAdded || forceSync)) { - sortItems(grid, sort, sortOptions); // Set the flag. - + sortItems(grid, sort, sortOptions); + // Set the flag. vars.hasSorted = true; } - /* ----------------------- */ + /* ----------------------- */ /* ----- SHOW & HIDE ----- */ - /* ----------------------- */ - // Filter has priority on the items visibility. - + // Filter has priority on the items visibility. if (!filter && vars.itemsToShow.length) { - showItems(grid, vars.itemsToShow); // Set the flag. - + showItems(grid, vars.itemsToShow); + // Set the flag. vars.hasShown = true; - } // Filter has priority on the items visibility. - + } + // Filter has priority on the items visibility. if (!filter && vars.itemsToHide.length) { - hideItems(grid, vars.itemsToHide); // Set the flag. - + hideItems(grid, vars.itemsToHide); + // Set the flag. vars.hasHidden = true; } - /* ------------------- */ + /* ------------------- */ /* ----- REFRESH ----- */ - /* ------------------- */ - // Items with dimensions to refresh. - + // Items with dimensions to refresh. if (vars.itemsToRefresh.length) { - grid.refreshItems(vars.itemsToRefresh); // Set the flag. - + grid.refreshItems(vars.itemsToRefresh); + // Set the flag. vars.hasRefreshed = true; } - /* ------------------ */ + /* ------------------ */ /* ----- LAYOUT ----- */ - /* ------------------ */ + // Layout is calculated only in the end. // Check the previous flags. - - if (vars.hasAdded || vars.hasRemoved || vars.hasSorted || vars.hasFiltered || vars.hasRefreshed || vars.hasShown || vars.hasHidden) { grid.layout(instantLayout); } }); - /* ------------------ */ + /* ------------------ */ /* ----- RENDER ----- */ - /* ------------------ */ - // Provided value doesn't change the reference. + // Provided value doesn't change the reference. var value = useMemoized(function () { return { layoutController: store.layoutController, grid: grid }; - }); // render. + }); + // render. return /*#__PURE__*/React.createElement(GridProvider, { value: value }, /*#__PURE__*/React.createElement("div", _extends({}, gridProps, { @@ -2321,8 +2231,9 @@ function GridComponent(_ref) { itemRemoveController: store.itemRemoveController }, child); }))); -} // Proptypes. +} +// Proptypes. GridComponent.propTypes = { grid: PropTypes.object.isRequired, gridProps: PropTypes.object, @@ -2345,8 +2256,9 @@ GridComponent.propTypes = { dragFixed: PropTypes.bool, dragEnabled: PropTypes.bool, instantLayout: PropTypes.bool -}; // Default props. +}; +// Default props. GridComponent.defaultProps = { gridProps: {}, addOptions: { @@ -2359,8 +2271,9 @@ GridComponent.defaultProps = { dragFixed: false, dragEnabled: false, instantLayout: false -}; // Display name. +}; +// Display name. GridComponent.displayName = 'GridComponent'; /** @@ -2370,12 +2283,9 @@ GridComponent.displayName = 'GridComponent'; var MuuriMap = /*#__PURE__*/function () { function MuuriMap() { _classCallCheck(this, MuuriMap); - _defineProperty(this, "_idMap", new Map()); - _defineProperty(this, "_groupMap", new Map()); } - _createClass(MuuriMap, [{ key: "get", value: @@ -2388,6 +2298,7 @@ var MuuriMap = /*#__PURE__*/function () { function get(id) { return this._idMap.get(id) || null; } + /** * Get all the grid instances in the group of the given id. * The reference of the group array never changes. @@ -2395,33 +2306,30 @@ var MuuriMap = /*#__PURE__*/function () { * @param groupId - The group id. * @returns - The array of grid instances. */ - }, { key: "getGroup", value: function getGroup(groupId) { var group = this._groupMap.get(groupId); - if (!group) { var newGroup = []; - this._groupMap.set(groupId, newGroup); - return newGroup; } else { return group; } } + /** * Get all the grid instances in the map. * * @returns - The grid instances. */ - }, { key: "getAll", value: function getAll() { return Array.from(this._idMap.values()); } + /** * Set the grid instance with the given id. * @@ -2429,14 +2337,13 @@ var MuuriMap = /*#__PURE__*/function () { * @param id - The id of the instance. * @returns - The muuriMap. */ - }, { key: "set", value: function set(grid, id) { this._idMap.set(id, grid); - return this; } + /** * Set the grid instance in the group of the given id. * @@ -2444,68 +2351,59 @@ var MuuriMap = /*#__PURE__*/function () { * @param groupId - The id of the group. * @returns - The muuriMap. */ - }, { key: "setGroup", value: function setGroup(grid, groupId) { var group = this._groupMap.get(groupId); - if (group) { group.push(grid); } else { this._groupMap.set(groupId, [grid]); } - return this; } + /** * Delete the grid instance with the given id. * * @param id - The id of the instance. * @returns - The muuriMap. */ - }, { key: "delete", value: function _delete(id) { this._idMap["delete"](id); - return this; } + /** * Delete the instance from the group with the given id. * * @param grid - The grid instance. * @param groupIds - The group ids of the instance. */ - }, { key: "deleteGroup", value: function deleteGroup(grid, groupId) { var group = this._groupMap.get(groupId); - if (group) { var index = group.indexOf(grid); if (index > -1) group.splice(index, 1); } - return this; } + /** * Clear the maps. */ - }, { key: "clear", value: function clear() { this._idMap.clear(); - this._groupMap.clear(); - return this; } }]); - return MuuriMap; }(); var muuriMap = new MuuriMap(); @@ -2517,14 +2415,16 @@ var muuriMap = new MuuriMap(); * @returns - The muuri instance. */ function getInstance(options) { - var el = document.createElement('div'); // The element won't be visible. - - el.style.display = 'none'; // Muuri (0.8.0) need an element in the DOM to be instanciated. - - document.body.appendChild(el); // Generate the instance. + var el = document.createElement('div'); + // The element won't be visible. + el.style.display = 'none'; + // Muuri (0.8.0) need an element in the DOM to be instanciated. + document.body.appendChild(el); - var grid = new Muuri(el, options); // Remove the element. + // Generate the instance. + var grid = new Muuri(el, options); + // Remove the element. document.body.removeChild(el); return grid; } @@ -2537,7 +2437,8 @@ function getInstance(options) { */ function handleRef(ref, value) { if (!ref) return; - if (typeof ref === 'function') ref(value); // @ts-ignore + if (typeof ref === 'function') ref(value); + // @ts-ignore else if ('current' in ref) ref.current = value; } @@ -2548,20 +2449,23 @@ function handleRef(ref, value) { * @param options - The grid options. */ function setDragAutoScroll(options) { - var dragAutoScroll = options.dragAutoScroll; // Wrap the options only if it is setted. + var dragAutoScroll = options.dragAutoScroll; + // Wrap the options only if it is setted. if (!dragAutoScroll || !Array.isArray(dragAutoScroll.targets)) return; dragAutoScroll.targets.forEach(function (target) { // Check if it is an object to wrap. if (isTargetElement(target)) return; - invariant('element' in target, 'You must provide an element in each scroll target'); // Scroll target element. - - var element = target.element; // The element ref. + invariant('element' in target, 'You must provide an element in each scroll target'); + // Scroll target element. + var element = target.element; + // The element ref. var ref = { current: null - }; // Define the element property. + }; + // Define the element property. Object.defineProperty(target, 'element', { get: function get() { return ref.current; @@ -2573,21 +2477,24 @@ function setDragAutoScroll(options) { ref = element; } } - }); // Set the element. + }); + // Set the element. target.element = element; }); } + /** * Returns if the target is a valid element. * * @param element - The target. * @returns - If the target is a valid element. */ - function isTargetElement(target) { - return (// A DOM element. - target instanceof HTMLElement || // The window. + return ( + // A DOM element. + target instanceof HTMLElement || + // The window. target instanceof window.constructor ); } @@ -2599,12 +2506,13 @@ function isTargetElement(target) { * @param options - The grid options. */ function setDragContainer(options) { - var dragContainer = options.dragContainer; // The drag container ref. - + var dragContainer = options.dragContainer; + // The drag container ref. var ref = { current: null - }; // Define the property. + }; + // Define the property. Object.defineProperty(options, 'dragContainer', { get: function get() { return ref.current; @@ -2616,8 +2524,9 @@ function setDragContainer(options) { ref = value; } } - }); // Set the drag container. + }); + // Set the drag container. options.dragContainer = dragContainer; } @@ -2629,14 +2538,16 @@ function setDragContainer(options) { * @param globalMap - The globalMap. */ function setDragSort(options, globalMap) { - var dragSort = options.dragSort; // Parse this options only if it is an object. - - if (!dragSort || _typeof(dragSort) !== 'object') return; // Check the options. + var dragSort = options.dragSort; + // Parse this options only if it is an object. + if (!dragSort || _typeof(dragSort) !== 'object') return; + // Check the options. + invariant(typeof dragSort.groupId === 'string', 'You must provide a string as groupId'); - invariant(typeof dragSort.groupId === 'string', 'You must provide a string as groupId'); // The group, its reference doesn't change. - - var group = globalMap.getGroup(dragSort.groupId); // dragSort method. + // The group, its reference doesn't change. + var group = globalMap.getGroup(dragSort.groupId); + // dragSort method. options.dragSort = function () { return group; }; @@ -2651,23 +2562,25 @@ function setDragSort(options, globalMap) { * @param options - The grid options. */ function setDragStartPredicate(options) { - var dragStartPredicate = options.dragStartPredicate; // Default predicate. + var dragStartPredicate = options.dragStartPredicate; - var defaultStartPredicate = getDefaultStartPredicate(dragStartPredicate); // Wrap the method. + // Default predicate. + var defaultStartPredicate = getDefaultStartPredicate(dragStartPredicate); + // Wrap the method. options.dragStartPredicate = function (item, event) { if (!getDecoration(item.getGrid()).dragEnabled) return false; if (isDecorated(item) && getDecoration(item).draggable === false) return false; return defaultStartPredicate(item, event); }; } + /** * Given the dragStartPredicate option return the default method. * * @param dragStartPredicate - The dragStartPredicate option. * @returns - The defaultStartPredicate method. */ - function getDefaultStartPredicate(dragStartPredicate) { return typeof dragStartPredicate === 'function' ? dragStartPredicate : function (item, event) { return Muuri.ItemDrag.defaultStartPredicate(item, event, dragStartPredicate); @@ -2675,96 +2588,97 @@ function getDefaultStartPredicate(dragStartPredicate) { } var _excluded = ["children", "id", "groupIds", "gridProps", "filter", "sort", "sortOptions", "addOptions", "propsToData", "onSend", "onDragStart", "onDragEnd", "onFilter", "onSort", "onMount", "onUnmount", "forceSync", "dragFixed", "dragEnabled", "instantLayout"]; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - +// Muuri component. var MuuriComponent = /*#__PURE__*/forwardRef(function MuuriComponent(_ref, muuriRef) { var children = _ref.children, - id = _ref.id, - groupIds = _ref.groupIds, - gridProps = _ref.gridProps, - filter = _ref.filter, - sort = _ref.sort, - sortOptions = _ref.sortOptions, - addOptions = _ref.addOptions, - propsToData = _ref.propsToData, - onSend = _ref.onSend, - onDragStart = _ref.onDragStart, - onDragEnd = _ref.onDragEnd, - onFilter = _ref.onFilter, - onSort = _ref.onSort, - onMount = _ref.onMount, - onUnmount = _ref.onUnmount, - forceSync = _ref.forceSync, - dragFixed = _ref.dragFixed, - dragEnabled = _ref.dragEnabled, - instantLayout = _ref.instantLayout, - options = _objectWithoutProperties(_ref, _excluded); - + id = _ref.id, + groupIds = _ref.groupIds, + gridProps = _ref.gridProps, + filter = _ref.filter, + sort = _ref.sort, + sortOptions = _ref.sortOptions, + addOptions = _ref.addOptions, + propsToData = _ref.propsToData, + onSend = _ref.onSend, + onDragStart = _ref.onDragStart, + onDragEnd = _ref.onDragEnd, + onFilter = _ref.onFilter, + onSort = _ref.onSort, + onMount = _ref.onMount, + onUnmount = _ref.onUnmount, + forceSync = _ref.forceSync, + dragFixed = _ref.dragFixed, + dragEnabled = _ref.dragEnabled, + instantLayout = _ref.instantLayout, + options = _objectWithoutProperties(_ref, _excluded); // Generate the Muuri instance. var grid = useMemoized(function () { // Remove the standard option '*'. // @ts-ignore - options.items = []; // Muuri (0.9.0) generate the "ItemDrag" instances only if + options.items = []; + // Muuri (0.9.0) generate the "ItemDrag" instances only if // drag is enabled. These instances do not handle scrolling well on touch devices, // so we only create these instances if drag-and-drop have to be used // (assuming that a boolean is passed to the prop instead of the default value "null"). // The enabling / disabling of the drag is managed in dragStartPredicate. // @ts-ignore - - options.dragEnabled = dragEnabled !== null; // Allow the drag container to be a React.Ref. - - setDragContainer(options); // Allow the option to be an object ({ groupId }). - - setDragSort(options, muuriMap); // Allow the target elements to be React.Ref. - - setDragAutoScroll(options); // Allow enabling / disabling the drag-and-drop. - - setDragStartPredicate(options); // Generate the instance. - - var grid = getInstance(options); // Add the instance to the map. - - if (id) muuriMap.set(grid, id); // Add the decoration. - + options.dragEnabled = dragEnabled !== null; + + // Allow the drag container to be a React.Ref. + setDragContainer(options); + // Allow the option to be an object ({ groupId }). + setDragSort(options, muuriMap); + // Allow the target elements to be React.Ref. + setDragAutoScroll(options); + // Allow enabling / disabling the drag-and-drop. + setDragStartPredicate(options); + + // Generate the instance. + var grid = getInstance(options); + + // Add the instance to the map. + if (id) muuriMap.set(grid, id); + // Add the decoration. addDecoration(grid, { id: id - }); // Set the ref. - + }); + // Set the ref. handleRef(muuriRef, grid); return grid; }); // eslint-disable-line - // On unmount effect. + // On unmount effect. useEffect(function () { // Clean-up. return function () { // Unset the ref. - handleRef(muuriRef, null); // Remove the decorations. - - removeDecorations(grid); // Remove the instance from the map. - - if (id) muuriMap["delete"](id); // Destroy the instace - + handleRef(muuriRef, null); + // Remove the decorations. + removeDecorations(grid); + // Remove the instance from the map. + if (id) muuriMap["delete"](id); + // Destroy the instace grid.destroy(); }; }, []); // eslint-disable-line - // Allow the groupIds to be changed. + // Allow the groupIds to be changed. useInstantEffect(function () { // decorate the instance addDecoration(grid, { groupIds: groupIds - }); // Add the instance to the groups. - + }); + // Add the instance to the groups. if (groupIds) { groupIds.forEach(function (groupId) { muuriMap.setGroup(grid, groupId); }); - } // Clean-up. - + } + // Clean-up. return function () { // Remove the instance from the groups. if (groupIds) { @@ -2773,8 +2687,9 @@ var MuuriComponent = /*#__PURE__*/forwardRef(function MuuriComponent(_ref, muuri }); } }; - }, groupIds || []); // Render. + }, groupIds || []); + // Render. return /*#__PURE__*/React.createElement(GridComponent, { grid: grid, gridProps: gridProps, @@ -2795,8 +2710,9 @@ var MuuriComponent = /*#__PURE__*/forwardRef(function MuuriComponent(_ref, muuri dragEnabled: dragEnabled, instantLayout: instantLayout }, children); -}); // Proptypes. +}); +// Proptypes. MuuriComponent.propTypes = { id: PropTypes.string, groupIds: PropTypes.arrayOf(PropTypes.string.isRequired), @@ -2874,14 +2790,18 @@ MuuriComponent.propTypes = { itemDraggingClass: PropTypes.string, itemReleasingClass: PropTypes.string, itemPlaceholderClass: PropTypes.string -}; // Default props. +}; +// Default props. MuuriComponent.defaultProps = _objectSpread(_objectSpread({}, Muuri.defaultOptions), {}, { dragEnabled: null -}); // Display name. +}); +// Display name. MuuriComponent.displayName = 'MuuriComponent'; +// The method return by the hook. + /** * The useData hook allow to set the data to the item in which the hook has been called. * It also returns the setter method. @@ -2892,18 +2812,20 @@ MuuriComponent.displayName = 'MuuriComponent'; */ function useData(initialData, options) { var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); - invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); // Because of memoization, The identity of the function is guaranteed + // Because of memoization, The identity of the function is guaranteed // to be stable so it will be safe to omit them as a dependency. - var setData = useFunction(function (data, options) { // Check if the data is an object. - invariant(_typeof(data) === 'object', "The data must be an object, founded: ".concat(_typeof(data))); // Default options. - - options = options || useData.defaultOptions; // Set the data. + invariant(_typeof(data) === 'object', "The data must be an object, founded: ".concat(_typeof(data))); + // Default options. + options = options || useData.defaultOptions; + // Set the data. if (options.merge) { // Merge. var currentData = itemRefController.get('data') || {}; @@ -2912,15 +2834,16 @@ function useData(initialData, options) { // Set. itemRefController.set('data', data); } - }); // Set the inital data. + }); + // Set the inital data. if (_typeof(initialData) === 'object') { setData(initialData, options); } - return setData; -} // Default options. +} +// Default options. useData.defaultOptions = { merge: false }; @@ -2932,21 +2855,23 @@ useData.defaultOptions = { * * @returns - If the item is being dragged. */ - function useDrag() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; + eventController = _useItemContext.eventController; + var reRender = useRerender(); - var reRender = useRerender(); // Check if the hook is called inside an item. - - invariant(eventController !== undefined, 'The useDrag hook can be used only inside an Item'); // Enable the event. + // Check if the hook is called inside an item. + invariant(eventController !== undefined, 'The useDrag hook can be used only inside an Item'); + // Enable the event. useEffect(function () { eventController.enableEvent('drag', reRender); }, [eventController, reRender]); return eventController.getPayload('drag') || false; } +// The method returned by the hook. + /** * The useDraggable hook allow to decide if the item (in which the hook has been called) * can be dragged or not. @@ -2956,9 +2881,9 @@ function useDrag() { */ function useDraggable() { var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. - + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); var setDraggable = useFunction(function (draggable) { // Set if the item can be dragged. @@ -2975,16 +2900,18 @@ function useDraggable() { */ function useGrid() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; - + eventController = _useItemContext.eventController; var gridContext = useGridContext(); - var reRender = useRerender(); // Check if the hook is called inside an item. + var reRender = useRerender(); - invariant(eventController !== undefined && gridContext.grid !== undefined, 'The useData hook can be used only inside an Item'); // The context is not updated when the hook is trigger - // so we need to get the updated instance from the eventController. + // Check if the hook is called inside an item. + invariant(eventController !== undefined && gridContext.grid !== undefined, 'The useData hook can be used only inside an Item'); - var grid = eventController.getPayload('send') || gridContext.grid; // Enable the event. + // The context is not updated when the hook is trigger + // so we need to get the updated instance from the eventController. + var grid = eventController.getPayload('send') || gridContext.grid; + // Enable the event. useEffect(function () { eventController.enableEvent('send', reRender); }, [eventController, reRender]); @@ -2995,6 +2922,8 @@ function useGrid() { }; } +// The method returned by the hook. + /** * The useRefresh hook allow to notify the MuuriComponent that the * item dimensions are changed, so that it can update the layout. @@ -3004,22 +2933,21 @@ function useGrid() { */ function useRefresh() { var deps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var _useGridContext = useGridContext(), - layoutController = _useGridContext.layoutController; - + layoutController = _useGridContext.layoutController; var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined && layoutController !== undefined, 'The useRefresh hook can be used only inside an Item'); - invariant(itemRefController !== undefined && layoutController !== undefined, 'The useRefresh hook can be used only inside an Item'); // Because of memoization, The identity of the function is guaranteed + // Because of memoization, The identity of the function is guaranteed // to be stable so it will be safe to omit it as a dependency. - var refresh = useCallback(function () { - if (!itemRefController.hasItem()) return; // Get the item. - - var item = itemRefController.getItem(); // If the component is rendering within the MuuriComponent. - + if (!itemRefController.hasItem()) return; + // Get the item. + var item = itemRefController.getItem(); + // If the component is rendering within the MuuriComponent. layoutController.refreshItem(item); }, [layoutController, itemRefController]); useEffect(function () { @@ -3035,21 +2963,23 @@ function useRefresh() { * * @returns - If the item is showing. */ - function useShow() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; + eventController = _useItemContext.eventController; + var reRender = useRerender(); - var reRender = useRerender(); // Check if the hook is called inside an item. - - invariant(eventController !== undefined, 'The useShow hook can be used only inside an Item'); // Enable the event. + // Check if the hook is called inside an item. + invariant(eventController !== undefined, 'The useShow hook can be used only inside an Item'); + // Enable the event. useEffect(function () { eventController.enableEvent('show', reRender); }, [eventController, reRender]); return eventController.getPayload('show'); } +// The method returned by the hook. + /** * The useVisibility hook allow you to show/hide the item in which the hook has been called. * @@ -3057,26 +2987,29 @@ function useShow() { */ function useVisibility() { var _useGridContext = useGridContext(), - layoutController = _useGridContext.layoutController; - + layoutController = _useGridContext.layoutController; var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController, - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. - + eventController = _useItemContext.eventController, + itemRefController = _useItemContext.itemRefController; - invariant(itemRefController !== undefined && layoutController !== undefined && eventController !== undefined, 'The useData hook can be used only inside an Item'); // Set visibility. + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined && layoutController !== undefined && eventController !== undefined, 'The useData hook can be used only inside an Item'); + // Set visibility. var setVisibility = useFunction(function (visible, options) { if (!itemRefController.hasItem()) return; - if (!!visible === eventController.getPayload('show')) return; // Default options. + if (!!visible === eventController.getPayload('show')) return; - options = options || useVisibility.defaultOptions; // Set the visibility. + // Default options. + options = options || useVisibility.defaultOptions; + // Set the visibility. layoutController.setItemVisibility(itemRefController.getItem(), visible, options.instant === true); }); return setVisibility; -} // Default options. +} +// Default options. useVisibility.defaultOptions = { instant: false }; @@ -3102,27 +3035,30 @@ var hooks = /*#__PURE__*/Object.freeze({ */ function getResponsiveStyle(options) { // Check options. - invariant(_typeof(options) === 'object', 'You must define options'); // Check columns. + invariant(_typeof(options) === 'object', 'You must define options'); - invariant(typeof options.columns === 'number' && options.columns > 0 && options.columns <= 1, 'options.columns must be a number between 0 (excluded) and 1 (included)'); // Check height and ratio. + // Check columns. + invariant(typeof options.columns === 'number' && options.columns > 0 && options.columns <= 1, 'options.columns must be a number between 0 (excluded) and 1 (included)'); - invariant(typeof options.ratio === 'number' || typeof options.height === 'number' || typeof options.height === 'string', 'You must provide at least one option between height and ratio'); // Check that the height and the ratio options are not setted togheter. + // Check height and ratio. + invariant(typeof options.ratio === 'number' || typeof options.height === 'number' || typeof options.height === 'string', 'You must provide at least one option between height and ratio'); - invariant(typeof options.ratio !== 'number' || typeof options.height !== 'number' && typeof options.height !== 'string', 'You cannot provide both the height and the ratio options'); // The margin values. + // Check that the height and the ratio options are not setted togheter. + invariant(typeof options.ratio !== 'number' || typeof options.height !== 'number' && typeof options.height !== 'string', 'You cannot provide both the height and the ratio options'); + // The margin values. var _getResponsiveMargin = getResponsiveMargin(options.margin || '0px'), - margin = _getResponsiveMargin.margin, - mStatic = _getResponsiveMargin.mStatic, - mDynamic = _getResponsiveMargin.mDynamic; // The item width. - - + margin = _getResponsiveMargin.margin, + mStatic = _getResponsiveMargin.mStatic, + mDynamic = _getResponsiveMargin.mDynamic; + // The item width. var _getResponsiveWidth = getResponsiveWidth(options.columns, mStatic, mDynamic), - needCalc = _getResponsiveWidth.needCalc, - width = _getResponsiveWidth.width; // If ratio is used set The paddingTop + needCalc = _getResponsiveWidth.needCalc, + width = _getResponsiveWidth.width; + + // If ratio is used set The paddingTop // instad of the heght, the child element must // have "display: absolute". - - return options.ratio ? { width: needCalc ? "calc(".concat(width, ")") : width, paddingTop: getResponsivePaddingTop(width, options.ratio, needCalc), @@ -3138,6 +3074,7 @@ function getResponsiveStyle(options) { margin: margin }; } + /** * Get the responsive width. * @@ -3146,7 +3083,6 @@ function getResponsiveStyle(options) { * @param mDynamic - The dynamic margin. * @returns - The width. */ - function getResponsiveWidth(columns, mStatic, mDynamic) { var needCalc = mStatic !== 0; var rawWidth = columns * 100 - mDynamic; @@ -3156,6 +3092,7 @@ function getResponsiveWidth(columns, mStatic, mDynamic) { width: width }; } + /** * Get the responsive paddingTop. * @@ -3164,39 +3101,37 @@ function getResponsiveWidth(columns, mStatic, mDynamic) { * @param needCalc - If the width need to be surrounded by calc(). * @returns - The paddingTop. */ - - function getResponsivePaddingTop(width, ratio, needCalc) { return needCalc ? "calc((".concat(width, ") / ").concat(ratio, ")") : "".concat(parseFloat(width) / ratio, "%"); } + /** * Get the fixed height. * * @param height - The mixed height. * @returns - The height string. */ - - function getFixedHeight(height) { return typeof height === 'number' ? "".concat(height, "px") : height; } + /** * The responsive margin. * * @param margin - The margin. * @returns - The responsive margin. */ - - function getResponsiveMargin(margin) { if (typeof margin === 'number') margin = "".concat(margin, "px"); - var margins = margin.trim().split(' '); // Margin default values. + var margins = margin.trim().split(' '); + // Margin default values. var leftMargin = '0px'; var rightMargin = '0px'; var mDynamic = 0; - var mStatic = 0; // Get the values from the input. + var mStatic = 0; + // Get the values from the input. if (margins.length === 1) { leftMargin = rightMargin = margins[0]; } else if (margins.length === 2) { @@ -3206,9 +3141,9 @@ function getResponsiveMargin(margin) { } else if (margins.length === 4) { leftMargin = margins[3]; rightMargin = margins[1]; - } // Set dynamic/static margins. - + } + // Set dynamic/static margins. if (leftMargin.indexOf('%') === -1) mStatic += parseFloat(leftMargin);else mDynamic += parseFloat(leftMargin); if (rightMargin.indexOf('%') === -1) mStatic += parseFloat(rightMargin);else mDynamic += parseFloat(rightMargin); return { @@ -3225,20 +3160,23 @@ function getResponsiveMargin(margin) { * @returns - The style. */ function getStaticStyle(options) { - var style = getResponsiveStyle(options); // Check the options. + var style = getResponsiveStyle(options); - invariant('grid' in options, 'You mast pass the grid instance to get the static style.'); // The sizer element. + // Check the options. + invariant('grid' in options, 'You mast pass the grid instance to get the static style.'); - var sizerElement = options.grid.getSizerElement(); // Set the style in the sizer. + // The sizer element. + var sizerElement = options.grid.getSizerElement(); - Object.assign(sizerElement.style, style); // Get the style from the sizer. + // Set the style in the sizer. + Object.assign(sizerElement.style, style); + // Get the style from the sizer. var _window$getComputedSt = window.getComputedStyle(sizerElement), - width = _window$getComputedSt.width, - height = _window$getComputedSt.height, - paddingTop = _window$getComputedSt.paddingTop, - margin = _window$getComputedSt.margin; - + width = _window$getComputedSt.width, + height = _window$getComputedSt.height, + paddingTop = _window$getComputedSt.paddingTop, + margin = _window$getComputedSt.margin; return { width: width, height: height, @@ -3247,53 +3185,42 @@ function getStaticStyle(options) { }; } -var hooksNames = ['useData', 'useDrag', 'useDraggable', 'useGrid', 'useRefresh', 'useShow', 'useVisibility']; // Handler type. +// Hook names. +var hooksNames = ['useData', 'useDrag', 'useDraggable', 'useGrid', 'useRefresh', 'useShow', 'useVisibility']; + +// Handler type. // Hook handlers. -var HooksHandlers = [['useData', -/* */ -getHandler('setData')], ['useDrag', -/* */ -getHandler('isDragging')], ['useDraggable', -/* */ -getHandler('setDraggable')], ['useGrid', -/* */ -getHandler('gridData')], ['useRefresh', -/* */ -getHandler('refresh')], ['useShow', -/* */ -getHandler('isShowing')], ['useVisibility', -/* */ -getHandler('setVisibility')]]; +var HooksHandlers = [['useData', /* */getHandler('setData')], ['useDrag', /* */getHandler('isDragging')], ['useDraggable', /* */getHandler('setDraggable')], ['useGrid', /* */getHandler('gridData')], ['useRefresh', /* */getHandler('refresh')], ['useShow', /* */getHandler('isShowing')], ['useVisibility', /* */getHandler('setVisibility')]]; + /** * Return the handler with the given key. * * @param key - The key. * @returns - The method. */ - function getHandler(key) { return function handler(payload) { return _defineProperty({}, key, payload); }; } + /** * Run all the handlers and merge all the payloads. * * @param hooksHandlers - The handlers. * @returns - The merged payload. */ - function getMerged(hooksHandlers) { return Object.assign.apply(Object, [{}].concat(_toConsumableArray(hooksHandlers.map(function (_ref2) { var _ref3 = _slicedToArray(_ref2, 2), - hookName = _ref3[0], - handler = _ref3[1]; - + hookName = _ref3[0], + handler = _ref3[1]; var payload = hooks[hookName](); return handler(payload); })))); } + /** * Item HOC for hooks. * @@ -3301,32 +3228,34 @@ function getMerged(hooksHandlers) { * @param enabledHooks - The hooks to enable. * @returns - The wrapped component. */ - - function withHooks(Component, enabledHooks) { // There must be an array of hooks to enable. - invariant(Array.isArray(enabledHooks), 'An array of hooks name must be provided to wrap an item.'); // All the hooks must be valid. + invariant(Array.isArray(enabledHooks), 'An array of hooks name must be provided to wrap an item.'); + // All the hooks must be valid. enabledHooks.forEach(function (hookName) { invariant(hooksNames.includes(hookName), "Invalid item hook: ".concat(hookName)); - }); // There must be at least one hook to enable. + }); - invariant(enabledHooks.length !== 0, 'To wrap an item at least one hook must be provided.'); // Get the handlers array of the enabled hook. + // There must be at least one hook to enable. + invariant(enabledHooks.length !== 0, 'To wrap an item at least one hook must be provided.'); + // Get the handlers array of the enabled hook. var hooksHandlers = HooksHandlers.filter(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 1), - hookName = _ref5[0]; - + hookName = _ref5[0]; return enabledHooks.includes(hookName); - }); // Return the HOC. + }); + // Return the HOC. return function WrappedItem(props) { // The hooks will run in the 'getMerged' method. return /*#__PURE__*/React.createElement(Component, _extends({}, props, getMerged(hooksHandlers))); }; } +// Muuri-exports. var AutoScroller = Muuri.AutoScroller; -var ItemDrag = Muuri.ItemDrag; // Muuri-react exports. +var ItemDrag = Muuri.ItemDrag; export { AutoScroller, ChildrenController, EventController, FiberController, FlagProp, GridComponent, GridContext, GridProvider, ItemAddController, ItemComponent, ItemContext, ItemDrag, ItemProvider, ItemRefController, ItemRemoveController, LayoutController, MuuriComponent, MuuriMap, getHandler, getIndicesToAdd, getResponsiveStyle, getStaticStyle, muuriMap, useData, useDrag, useDraggable, useGrid, useGridContext, useItemContext, useRefresh, useShow, useVisibility, withHooks }; diff --git a/dist/muuri-react.js b/dist/muuri-react.js index bd0813b..2548bda 100644 --- a/dist/muuri-react.js +++ b/dist/muuri-react.js @@ -11,14 +11,41 @@ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('muuri'), require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'muuri', 'react'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MuuriReact = {}, global.Muuri, global.React)); -}(this, (function (exports, Muuri, React) { 'use strict'; +})(this, (function (exports, Muuri, React) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var Muuri__default = /*#__PURE__*/_interopDefaultLegacy(Muuri); var React__default = /*#__PURE__*/_interopDefaultLegacy(React); + function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); + } + + function _toPrimitive(input, hint) { + if (_typeof(input) !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== undefined) { + var res = prim.call(input, hint || "default"); + if (_typeof(res) !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); + } + + function _toPropertyKey(arg) { + var key = _toPrimitive(arg, "string"); + return _typeof(key) === "symbol" ? key : String(key); + } + function _defineProperty(obj, key, value) { + key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, @@ -29,7 +56,6 @@ } else { obj[key] = value; } - return obj; } @@ -45,10 +71,8 @@ return !!instance[key]; } - function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - + function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * Add a decoration to the instance. * @@ -57,6 +81,7 @@ */ function addDecoration(instance, decoration) { if (isDecorated(instance)) { + // @ts-ignore Object.assign(instance[key], decoration); } else { instance[key] = _objectSpread$2({}, decoration); @@ -87,8 +112,7 @@ * * @returns - The id of the instance. */ - - Muuri__default['default'].prototype.getId = function getId() { + Muuri__default["default"].prototype.getId = function getId() { return getDecoration(this).id; }; /** @@ -96,9 +120,7 @@ * * @returns - The group ids of the instance. */ - - - Muuri__default['default'].prototype.getGroupIds = function getGroupIds() { + Muuri__default["default"].prototype.getGroupIds = function getGroupIds() { return getDecoration(this).groupIds; }; /** @@ -106,19 +128,16 @@ * * @returns - The group ids of the instance. */ - - - Muuri__default['default'].prototype.getSizerElement = function getSizerElement() { + Muuri__default["default"].prototype.getSizerElement = function getSizerElement() { return getDecoration(this).sizerElement; }; + /** * Item key getter. * * @returns - The item component key. */ - - - Muuri__default['default'].Item.prototype.getKey = function getKey() { + Muuri__default["default"].Item.prototype.getKey = function getKey() { return getDecoration(this).key; }; /** @@ -126,9 +145,7 @@ * * @returns - The item component props. */ - - - Muuri__default['default'].Item.prototype.getProps = function getProps() { + Muuri__default["default"].Item.prototype.getProps = function getProps() { return getDecoration(this).props; }; /** @@ -136,9 +153,7 @@ * * @returns - The item component data. */ - - - Muuri__default['default'].Item.prototype.getData = function getData() { + Muuri__default["default"].Item.prototype.getData = function getData() { return getDecoration(this).data; }; /** @@ -146,50 +161,25 @@ * * @param data - The data. */ - - - Muuri__default['default'].Item.prototype.setData = function setData(data) { + Muuri__default["default"].Item.prototype.setData = function setData(data) { getDecoration(this).data = data; }; function _extends() { - _extends = Object.assign || function (target) { + _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; - for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } - return target; }; - return _extends.apply(this, arguments); } - function _typeof$1(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof$1 = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof$1 = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof$1(obj); - } - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } @@ -498,16 +488,22 @@ * LICENSE file in the root directory of this source tree. */ - var ReactPropTypesSecret$1 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + var ReactPropTypesSecret$2 = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; + + var ReactPropTypesSecret_1 = ReactPropTypesSecret$2; + + var has$2 = Function.call.bind(Object.prototype.hasOwnProperty); - var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; + var ReactPropTypesSecret$1 = ReactPropTypesSecret_1; + + var has$1 = has$2; var printWarning$1 = function() {}; { - var ReactPropTypesSecret = ReactPropTypesSecret_1; + var ReactPropTypesSecret = ReactPropTypesSecret$1; var loggedTypeFailures = {}; - var has$1 = Function.call.bind(Object.prototype.hasOwnProperty); + var has = has$1; printWarning$1 = function(text) { var message = 'Warning: ' + text; @@ -519,7 +515,7 @@ // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); - } catch (x) {} + } catch (x) { /**/ } }; } @@ -534,10 +530,10 @@ * @param {?Function} getStack Returns the component stack. * @private */ - function checkPropTypes(typeSpecs, values, location, componentName, getStack) { + function checkPropTypes$1(typeSpecs, values, location, componentName, getStack) { { for (var typeSpecName in typeSpecs) { - if (has$1(typeSpecs, typeSpecName)) { + if (has(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. @@ -548,7 +544,8 @@ if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + - 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.' ); err.name = 'Invariant Violation'; throw err; @@ -588,15 +585,16 @@ * * @private */ - checkPropTypes.resetWarningCache = function() { + checkPropTypes$1.resetWarningCache = function() { { loggedTypeFailures = {}; } }; - var checkPropTypes_1 = checkPropTypes; + var checkPropTypes_1 = checkPropTypes$1; + + var checkPropTypes = checkPropTypes_1; - var has = Function.call.bind(Object.prototype.hasOwnProperty); var printWarning = function() {}; { @@ -697,6 +695,7 @@ // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), + bigint: createPrimitiveTypeChecker('bigint'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), @@ -742,8 +741,9 @@ * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ - function PropTypeError(message) { + function PropTypeError(message, data) { this.message = message; + this.data = data && typeof data === 'object' ? data: {}; this.stack = ''; } // Make `instanceof Error` still work for returned errors. @@ -758,7 +758,7 @@ componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; - if (secret !== ReactPropTypesSecret_1) { + if (secret !== ReactPropTypesSecret$1) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error( @@ -778,7 +778,7 @@ ) { printWarning( 'You are manually calling a React.PropTypes validation ' + - 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' @@ -817,7 +817,10 @@ // 'of type `object`'. var preciseType = getPreciseType(propValue); - return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); + return new PropTypeError( + 'Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'), + {expectedType: expectedType} + ); } return null; } @@ -839,7 +842,7 @@ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { - var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1); + var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret$1); if (error instanceof Error) { return error; } @@ -931,8 +934,8 @@ return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { - if (has(propValue, key)) { - var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); + if (has$1(propValue, key)) { + var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret$1); if (error instanceof Error) { return error; } @@ -961,14 +964,19 @@ } function validate(props, propName, componentName, location, propFullName) { + var expectedTypes = []; for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; - if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) { + var checkerResult = checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret$1); + if (checkerResult == null) { return null; } + if (checkerResult.data && has$1(checkerResult.data, 'expectedType')) { + expectedTypes.push(checkerResult.data.expectedType); + } } - - return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); + var expectedTypesMessage = (expectedTypes.length > 0) ? ', expected one of type [' + expectedTypes.join(', ') + ']': ''; + return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`' + expectedTypesMessage + '.')); } return createChainableTypeChecker(validate); } @@ -983,6 +991,13 @@ return createChainableTypeChecker(validate); } + function invalidValidatorError(componentName, location, propFullName, key, type) { + return new PropTypeError( + (componentName || 'React class') + ': ' + location + ' type `' + propFullName + '.' + key + '` is invalid; ' + + 'it must be a function, usually from the `prop-types` package, but received `' + type + '`.' + ); + } + function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; @@ -992,10 +1007,10 @@ } for (var key in shapeTypes) { var checker = shapeTypes[key]; - if (!checker) { - continue; + if (typeof checker !== 'function') { + return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); } - var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret$1); if (error) { return error; } @@ -1012,19 +1027,21 @@ if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } - // We need to check all keys in case some are required but missing from - // props. + // We need to check all keys in case some are required but missing from props. var allKeys = objectAssign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; + if (has$1(shapeTypes, key) && typeof checker !== 'function') { + return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); + } if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + - '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } - var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1); + var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret$1); if (error) { return error; } @@ -1166,13 +1183,15 @@ return propValue.constructor.name; } - ReactPropTypes.checkPropTypes = checkPropTypes_1; - ReactPropTypes.resetWarningCache = checkPropTypes_1.resetWarningCache; + ReactPropTypes.checkPropTypes = checkPropTypes; + ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; + var require$$1 = factoryWithTypeCheckers; + var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. @@ -1187,30 +1206,32 @@ // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; - module.exports = factoryWithTypeCheckers(ReactIs.isElement, throwOnDirectAccess); + module.exports = require$$1(ReactIs.isElement, throwOnDirectAccess); } }); - // Grid context. - var GridContext = /*#__PURE__*/React.createContext({}); // Grid provider. - - var GridProvider = GridContext.Provider; // Grid context hook. + var PropTypes = propTypes; + // Grid context. + var GridContext = /*#__PURE__*/React.createContext({}); + // Grid provider. + var GridProvider = GridContext.Provider; + // Grid context hook. var useGridContext = function useGridContext() { return React.useContext(GridContext); - }; // Grid provider display name. - + }; + // Grid provider display name. GridContext.displayName = 'GridProvider'; // Item context. - var ItemContext = /*#__PURE__*/React.createContext({}); // Item provider. - - var ItemProvider = ItemContext.Provider; // Item context hook. - + var ItemContext = /*#__PURE__*/React.createContext({}); + // Item provider. + var ItemProvider = ItemContext.Provider; + // Item context hook. var useItemContext = function useItemContext() { return React.useContext(ItemContext); - }; // Item provider display name. - + }; + // Item provider display name. ItemContext.displayName = 'ItemProvider'; function _classCallCheck(instance, Constructor) { @@ -1225,13 +1246,15 @@ descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); + Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } - function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); + Object.defineProperty(Constructor, "prototype", { + writable: false + }); return Constructor; } @@ -1245,12 +1268,9 @@ var EventController = /*#__PURE__*/function () { function EventController() { _classCallCheck(this, EventController); - _defineProperty(this, "_eventsMap", new Map()); - _defineProperty(this, "_payloadsMap", new Map()); } - _createClass(EventController, [{ key: "enableEvent", value: @@ -1263,60 +1283,57 @@ function enableEvent(event, emitter) { this._eventsMap.set(event, emitter); } + /** * Set an event payload and emit it the event. * * @param event - The event name. * @param payload - The payload. */ - }, { key: "emitEvent", value: function emitEvent(event, payload) { if (this.isEnabled(event)) { - this._payloadsMap.set(event, payload); // @ts-ignore - - + this._payloadsMap.set(event, payload); + // @ts-ignore this._eventsMap.get(event)(); } } + /** * Get the payload of the event. * * @param event - The event. * @returns - The payload. */ - }, { key: "getPayload", value: function getPayload(event) { return this._payloadsMap.get(event); } + /** * Returns if at least an event is enabled. * * @param event - The event. * @returns - If at least an event is enabled. */ - }, { key: "isEnabled", value: function isEnabled(event) { return this._eventsMap.has(event); } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._eventsMap.clear(); - this._payloadsMap.clear(); } }]); - return EventController; }(); @@ -1331,10 +1348,8 @@ var ItemAddController = /*#__PURE__*/function () { function ItemAddController() { _classCallCheck(this, ItemAddController); - _defineProperty(this, "_requests", []); } - _createClass(ItemAddController, [{ key: "useInit", value: @@ -1344,13 +1359,13 @@ function useInit() { this._requests = []; } + /** * Emit the new items to the * components that made a request. * * @param items - The items. */ - }, { key: "emit", value: function emit(items) { @@ -1358,37 +1373,35 @@ this._requests[i](items[i]); } } + /** * Request an item. * * @param cb - The callback. */ - }, { key: "requestItem", value: function requestItem(cb) { this._requests.push(cb); } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._requests = []; } }]); - return ItemAddController; }(); function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; - return _setPrototypeOf(o, p); } @@ -1396,7 +1409,6 @@ if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } - subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, @@ -1404,41 +1416,16 @@ configurable: true } }); + Object.defineProperty(subClass, "prototype", { + writable: false + }); if (superClass) _setPrototypeOf(subClass, superClass); } - var _typeof_1 = createCommonjsModule(function (module) { - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - module.exports = _typeof = function _typeof(obj) { - return typeof obj; - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - } else { - module.exports = _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - } - - return _typeof(obj); - } - - module.exports = _typeof; - module.exports["default"] = module.exports, module.exports.__esModule = true; - }); - - var _typeof = unwrapExports(_typeof_1); - function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } - return self; } @@ -1448,12 +1435,11 @@ } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } - return _assertThisInitialized(self); } function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); @@ -1467,7 +1453,6 @@ if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; - try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; @@ -1478,7 +1463,7 @@ function _construct(Parent, args, Class) { if (_isNativeReflectConstruct$1()) { - _construct = Reflect.construct; + _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; @@ -1489,30 +1474,23 @@ return instance; }; } - return _construct.apply(null, arguments); } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; - _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; - if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } - if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); - _cache.set(Class, Wrapper); } - function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } - Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, @@ -1523,38 +1501,32 @@ }); return _setPrototypeOf(Wrapper, Class); }; - return _wrapNativeSuper(Class); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - var prefix = 'Invariant failed'; // Invarianto instance + var prefix = 'Invariant failed'; + // Invarianto instance var Invariant = /*#__PURE__*/function (_Error) { _inherits(Invariant, _Error); - var _super = _createSuper(Invariant); - function Invariant(message) { var _this; - _classCallCheck(this, Invariant); - _this = _super.call(this, message); _this.name = 'Invariant'; return _this; } + return _createClass(Invariant); + }( /*#__PURE__*/_wrapNativeSuper(Error)); - return Invariant; - }( /*#__PURE__*/_wrapNativeSuper(Error)); // Throw an error if the condition fails - + // Throw an error if the condition fails function invariant(condition, message) { if (condition) { return; } - { // When not in production we allow the message to pass through // *This block will be removed in production builds* @@ -1572,12 +1544,9 @@ var ItemRefController = /*#__PURE__*/function () { function ItemRefController() { _classCallCheck(this, ItemRefController); - _defineProperty(this, "_item", null); - _defineProperty(this, "_instance", {}); } - _createClass(ItemRefController, [{ key: "set", value: @@ -1594,13 +1563,13 @@ this._instance[key] = value; } } + /** * Get a decoration value from the item. * * @param key - The decoration key. * @returns - The decoration value. */ - }, { key: "get", value: function get(key) { @@ -1610,21 +1579,21 @@ return this._instance[key]; } } + /** * Remove all the decorations from the item. */ - }, { key: "delete", value: function _delete() { if (this._item) removeDecorations(this._item); } + /** * Set the item in the controller. * * @param item - The item. */ - }, { key: "setItem", value: function setItem(item) { @@ -1632,33 +1601,33 @@ addDecoration(this._item, this._instance); this._instance = {}; } + /** * Item getter. * * @returns - The item. */ - }, { key: "getItem", value: function getItem() { invariant(this._item !== null, 'The item has not been setted yet'); return this._item; } + /** * Returns if the item has been setted. * * @returns - If the item has been setted. */ - }, { key: "hasItem", value: function hasItem() { return this._item !== null; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -1666,7 +1635,6 @@ this._instance = {}; } }]); - return ItemRefController; }(); @@ -1679,10 +1647,8 @@ var ItemRemoveController = /*#__PURE__*/function () { function ItemRemoveController() { _classCallCheck(this, ItemRemoveController); - _defineProperty(this, "_itemsToRemove", []); } - _createClass(ItemRemoveController, [{ key: "useInit", value: @@ -1692,37 +1658,36 @@ function useInit() { this._itemsToRemove = []; } + /** * Request an item to be removed. * * @param item - The item to be removed. */ - }, { key: "removeItem", value: function removeItem(item) { this._itemsToRemove.push(item); } + /** * Return all the items to remove. */ - }, { key: "getItemsToRemove", value: function getItemsToRemove() { return this._itemsToRemove; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this._itemsToRemove = []; } }]); - return ItemRemoveController; }(); @@ -1746,48 +1711,41 @@ /** Constructor. */ function LayoutController() { _classCallCheck(this, LayoutController); - _defineProperty(this, "_itemsToRefresh", void 0); - _defineProperty(this, "_itemsToShow", void 0); - _defineProperty(this, "_itemsToHide", void 0); - _defineProperty(this, "_isRendering", void 0); - this._itemsToRefresh = []; this._itemsToShow = []; this._itemsToHide = []; this._isRendering = false; } + /** * Init. */ - - _createClass(LayoutController, [{ key: "useInit", value: function useInit() { var _this = this; - // Items. this._itemsToRefresh = []; this._itemsToShow = []; - this._itemsToHide = []; // State. - - this._isRendering = true; // Change state. + this._itemsToHide = []; + // State. + this._isRendering = true; + // Change state. // eslint-disable-next-line - React.useEffect(function () { _this._isRendering = false; }); } + /** * Refresh an item. * * @param item - The item to refresh. */ - }, { key: "refreshItem", value: function refreshItem(item) { @@ -1799,12 +1757,13 @@ } else { // If the item is changing parent this // will get the right parent. - var grid = item.getGrid(); // The layout is managed here. - + var grid = item.getGrid(); + // The layout is managed here. grid.refreshItems([item]); grid.layout(); } } + /** * Set an item visibility. * @@ -1812,7 +1771,6 @@ * @param visible - The visibility. * @param instant - If the visibility change should happen without animations. */ - }, { key: "setItemVisibility", value: function setItemVisibility(item, visible, instant) { @@ -1824,8 +1782,8 @@ } else { // If the item is changing parent this // will get the right parent. - var grid = item.getGrid(); // The layout is managed here. - + var grid = item.getGrid(); + // The layout is managed here. if (visible) grid.show([item], { instant: instant });else grid.hide([item], { @@ -1833,43 +1791,43 @@ }); } } + /** * Get the items that have to be refreshed. * * @returns - The items. */ - }, { key: "getItemsToRefresh", value: function getItemsToRefresh() { return this._itemsToRefresh; } + /** * Get the items that have to be shown. * * @returns - The items. */ - }, { key: "getItemsToShow", value: function getItemsToShow() { return this._itemsToShow; } + /** * Get the items that have to be hidden. * * @returns - The items. */ - }, { key: "getItemsToHide", value: function getItemsToHide() { return this._itemsToHide; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -1878,7 +1836,6 @@ this._itemsToHide = []; } }]); - return LayoutController; }(); @@ -1891,12 +1848,9 @@ var FiberController = /*#__PURE__*/function () { function FiberController() { _classCallCheck(this, FiberController); - _defineProperty(this, "_fiber", void 0); - _defineProperty(this, "_flag", '0'); } - _createClass(FiberController, [{ key: "useInit", value: @@ -1907,58 +1861,58 @@ */ function useInit(gridElementRef) { var _this = this; - - this.updateFlag(); // eslint-disable-next-line - + this.updateFlag(); + // eslint-disable-next-line React.useEffect(function () { invariant(gridElementRef.current !== null); _this._fiber = getFiber(gridElementRef.current); }, []); // eslint-disable-line } + /** * Return the DOM elements in the chosen positions. * * @param orderedIndices - The positions. * @returns - The elements. */ - }, { key: "getStateNodes", value: function getStateNodes(orderedIndices) { - var stateNodes = []; // If there aren't indices retun an empty array. + var stateNodes = []; + // If there aren't indices retun an empty array. + if (orderedIndices.length === 0) return stateNodes; - if (orderedIndices.length === 0) return stateNodes; // The first child. + // The first child. + var child = getCurrentFiber(this._fiber, this._flag).child; - var child = getCurrentFiber(this._fiber, this._flag).child; // Fill the state nodes array. + // Fill the state nodes array. // We trust that the user input. - orderedIndices.forEach(function (index) { // @ts-ignore while (child.index !== index) { // @ts-ignore child = child.sibling; - } // @ts-ignore - + } + // @ts-ignore stateNodes.push(getStateNode(child)); }); return stateNodes; } + /** * Append an itemComponent fiber * (the same is done for the alternate if exists). * * @param child - The item. */ - }, { key: "append", value: function append(itemComponentFiber) { // Get the current fiber. - var fiber = getCurrentFiber(this._fiber, this._flag); // Append the fiber. - + var fiber = getCurrentFiber(this._fiber, this._flag); + // Append the fiber. appendFiber(fiber, itemComponentFiber); - if (fiber.alternate) { if (itemComponentFiber.alternate) { // Append the alternate. @@ -1966,6 +1920,7 @@ } } } + /** * Remove an itemComponent fiber given the key of its Item * (The same is done for the alternate if exists). @@ -1973,48 +1928,45 @@ * @param key - The key of the item. * @returns - The removed item. */ - }, { key: "remove", value: function remove(key) { // Get the current fiber. - var fiber = getCurrentFiber(this._fiber, this._flag); // Remove the fiber. - + var fiber = getCurrentFiber(this._fiber, this._flag); + // Remove the fiber. var removedChild = removeChild(fiber, key); - if (fiber.alternate) { if (removedChild.alternate) { // Remove the alternate. removeChild(fiber.alternate, key); } } - return removedChild; } + /** * Return the props containing the flag value to add in the grid element. * * @returns - The props. */ - }, { key: "getFlagProp", value: function getFlagProp() { return _defineProperty({}, FlagProp, this._flag); } + /** * Update the flag value. */ - }, { key: "updateFlag", value: function updateFlag() { if (this._flag === '0') this._flag = '1';else this._flag = '0'; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { @@ -2022,29 +1974,30 @@ this._fiber = null; } }]); - return FiberController; }(); + /** * The flag prop name. */ - var FlagProp = 'muuri-react-flag'; + /** * Get the fiber of the given grid element. * * @param grid - The element. * @return - The fiber node. */ - function getFiber(grid) { var key = Object.keys(grid).find(function (key) { return key.startsWith('__reactInternalInstance$') || key.startsWith('__reactFiber$'); }); - invariant(typeof key === 'string', 'Cannot find the __reactInternalInstance$'); // @ts-ignore + invariant(typeof key === 'string', 'Cannot find the __reactInternalInstance$'); + // @ts-ignore return grid[key]; } + /** * Return the current fiber. * Try to use the prop flag for the search first, @@ -2060,37 +2013,40 @@ * @param flag - the flag. * @returns - The current fiber. */ - - function getCurrentFiber(fiber, currentFlag) { - if (!fiber.alternate) return fiber; // Flags. + if (!fiber.alternate) return fiber; + // Flags. var fiberFlag = fiber.memoizedProps[FlagProp]; - var alternateFlag = fiber.alternate.memoizedProps[FlagProp]; // If the two flags are the same it should mean that + var alternateFlag = fiber.alternate.memoizedProps[FlagProp]; + + // If the two flags are the same it should mean that // in at least one of the items there has been a re-render // from the last render of the GridComponent. // We can no longer trust the flag prop and we have // to look for the RootFiber and check which // fiber is in the current tree. - if (fiberFlag === alternateFlag) { - var topFiber = fiber; // Get the top fiber - // (Not the RootFiber). + var topFiber = fiber; + // Get the top fiber + // (Not the RootFiber). while (topFiber["return"]) { topFiber = topFiber["return"]; - } // Fibers. - + } + // Fibers. var rootFiber = topFiber.stateNode; - var topCurrentFiber = rootFiber.current; // The current fiber. + var topCurrentFiber = rootFiber.current; + // The current fiber. return topCurrentFiber === topFiber ? fiber : fiber.alternate; - } // If we got here we can trust the flag prop to find the current Fiber. - + } + // If we got here we can trust the flag prop to find the current Fiber. return fiberFlag === currentFlag ? fiber : fiber.alternate; } + /** * Returns the first stateNode among the descendants * of the given itemComponent Fiber. @@ -2098,51 +2054,44 @@ * @param itemComponentFiber - The fiber. * @returns - The element. */ - - function getStateNode(itemComponentFiber) { // ItemComponent -> ItemProvider -> Item. - var itemFiber = itemComponentFiber.child.child; // @ts-ignore - - while (!(itemFiber.stateNode instanceof HTMLElement)) { - // @ts-ignore - itemFiber = itemFiber.child; - } - + var itemFiber = itemComponentFiber.child.child; + // @ts-ignore + while (!(itemFiber.stateNode instanceof HTMLElement)) + // @ts-ignore + itemFiber = itemFiber.child; return itemFiber.stateNode; } + /** * Append the child fiber in the last position among the children of the parent fiber. * * @param parent - The parent fiber. * @param child - The child fiber. */ - - function appendFiber(parent, child) { var _parent$return; - if (!parent.child) { // If it has no child. parent.child = child; child.index = 0; } else { var c = parent.child; - while (c.sibling) { c = c.sibling; } - - child.index = c.index + 1; // Inserted as last child. - + child.index = c.index + 1; + // Inserted as last child. c.sibling = child; - } // Update the references. - - - child["return"] = parent; // If we are in development. + } + // Update the references. + child["return"] = parent; + // If we are in development. if (child._debugOwner) child._debugOwner = (_parent$return = parent["return"]) === null || _parent$return === void 0 ? void 0 : _parent$return["return"]; } + /** * Remove a child with the given key from the fiber. * @@ -2150,76 +2099,71 @@ * @param key - The key of the item. * @return - The removed fiber. */ - - function removeChild(parent, key) { var child = parent.child; - var removedChild; // @ts-ignore + var removedChild; + // @ts-ignore if (hasNot(child, key)) { // @ts-ignore while (hasNot(child.sibling, key)) { // @ts-ignore child = child.sibling; - } // @ts-ignore - - - removedChild = removeSibling(child); // @ts-ignore - + } + // @ts-ignore + removedChild = removeSibling(child); + // @ts-ignore adjustIndices(child); } else { - removedChild = removeFirstChild(parent); // @ts-ignore - + removedChild = removeFirstChild(parent); + // @ts-ignore child = child.sibling; if (child) adjustIndices(child); } - removedChild.sibling = null; return removedChild; } + /** * Remove the first itemComponent fiber of a gridELement fiber and return it. * * @param GridElementFiber - The gridELement fiber. * @return - The removed itemComponent fiber. */ - - function removeFirstChild(gridElementFiber) { - var removed = gridElementFiber.child; // @ts-ignore - - gridElementFiber.child = gridElementFiber.child.sibling; // @ts-ignore - + var removed = gridElementFiber.child; + // @ts-ignore + gridElementFiber.child = gridElementFiber.child.sibling; + // @ts-ignore return removed; } + /** * Remove the first sibling from a itemComponent fiber and return it. * * @param fiber - The fiber. * @return - The removed sibling. */ - - function removeSibling(fiber) { - var removed = fiber.sibling; // @ts-ignore - - fiber.sibling = fiber.sibling.sibling; // @ts-ignore - + var removed = fiber.sibling; + // @ts-ignore + fiber.sibling = fiber.sibling.sibling; + // @ts-ignore return removed; } + /** * Adjust the indices of the siblings of an itemComponent fiber. * * @param itemComponentFiber - The itemComponent fiber. */ - - function adjustIndices(itemComponentFiber) { while (itemComponentFiber.sibling) { itemComponentFiber.sibling.index = itemComponentFiber.index + 1; itemComponentFiber = itemComponentFiber.sibling; } } + /** * Returns if the itemComponent fiber is not the parent of the item with the given key. * @@ -2227,8 +2171,6 @@ * @param key - The key of the item. * @return - If the itemComponent fiber is not the parent of the item with the given key. */ - - function hasNot(itemComponentFiber, key) { // ItemComponent -> ItemProvider -> Item. return itemComponentFiber.child.child.key !== key; @@ -2244,16 +2186,11 @@ var ChildrenController = /*#__PURE__*/function () { function ChildrenController() { _classCallCheck(this, ChildrenController); - _defineProperty(this, "_oldChildrenArray", []); - _defineProperty(this, "_children", []); - _defineProperty(this, "_indicesToAdd", []); - _defineProperty(this, "_dragCounter", 0); } - _createClass(ChildrenController, [{ key: "useInit", value: @@ -2265,55 +2202,57 @@ function useInit(newChildren) { // @ts-ignore // We need to ensure that the children are in an array. - var newChildrenArray = React.Children.toArray(newChildren); // The indices to add. + var newChildrenArray = React.Children.toArray(newChildren); + + // The indices to add. + this._indicesToAdd = getIndicesToAdd(newChildrenArray, this._oldChildrenArray); - this._indicesToAdd = getIndicesToAdd(newChildrenArray, this._oldChildrenArray); // The _children will be used to map all + // The _children will be used to map all // the child in the render method. // We can't use the ChildrenArray because we need the users // key provided in the components and not the escaped one (e.g. .$1). - this._children = newChildren || []; this._oldChildrenArray = newChildrenArray; } + /** * Remove a child in the given position and return it. * * @param index - The index of the child to remove. * @returns - The removed child. */ - }, { key: "remove", value: function remove(index) { return this._oldChildrenArray.splice(index, 1)[0]; } + /** * Append a child in the children array. * * @param child - The child to append. */ - }, { key: "append", value: function append(child) { this._oldChildrenArray.push(child); } + /** * Returns the ordered array of indices of the added children. */ - }, { key: "getIndicesToAdd", value: function getIndicesToAdd() { return this._indicesToAdd; } + /** * Map all the children. * * @param cb - The callback. * @returns - The mapped children. */ - }, { key: "render", value: function render(cb) { @@ -2322,10 +2261,12 @@ // there are rare cases where the keys are not indispensable, // the user may not choose to use at his own risk. return cb(child, child.key); - }); // Flush the children. + }); + // Flush the children. this.flush(); return children; + /** // If an item is being dragged we need to ensure // that no child is inserted before it. @@ -2334,46 +2275,46 @@ : getChildrenInSafePositions(children, this._indicesToAdd); */ } + /** * Increment the drag counter. */ - }, { key: "incrementDragCounter", value: function incrementDragCounter() { this._dragCounter += 1; } + /** * Decrement the drag counter. */ - }, { key: "decrementDragCounter", value: function decrementDragCounter() { this._dragCounter -= 1; } + /** * Remove the current children so they can be garbage collected. */ - }, { key: "flush", value: function flush() { this._children = []; } + /** * Destroy the instance. */ - }, { key: "destroy", value: function destroy() { this.flush(); } }]); - return ChildrenController; }(); + /** * Return an array of positions of the added children. * The algorithm is optimized for cases where the order of @@ -2384,15 +2325,12 @@ * @param oldChildren - The old children. * @return - The indices. */ - function getIndicesToAdd(newChildren, oldChildren) { var indicesToAdd = []; var oIndex = 0; - for (var nIndex = 0; nIndex < newChildren.length; nIndex++) { // Finde the index. var index = findIndex(oldChildren, newChildren[nIndex], oIndex); - if (index === -1) { // If it is not present is a new Child. indicesToAdd.push(nIndex); @@ -2402,9 +2340,9 @@ oIndex = index; } } - return indicesToAdd; } + /** * Returns the index of the child in the children array, * if it is not present returns -1. @@ -2415,22 +2353,23 @@ * @param fromIndex - The initial index. * @returns - The index of the child. */ - function findIndex(children, child, fromIndex) { - fromIndex = fromIndex > children.length ? children.length : fromIndex; // If the heuristics are respected the child will be here. + fromIndex = fromIndex > children.length ? children.length : fromIndex; + // If the heuristics are respected the child will be here. for (var index = fromIndex; index < children.length; index++) { if (is(child, children[index])) return index; - } // If the child is here the heuristics are not respected. - + } + // If the child is here the heuristics are not respected. for (var _index = 0; _index < fromIndex; _index++) { if (is(child, children[_index])) return _index; - } // The child is not present. - + } + // The child is not present. return -1; } + /** * There would be the risk that a component will be inserted before * an item that is being dragged (and that is placed in a drag @@ -2469,8 +2408,6 @@ * @param componentB - The second component. * @returns - If they have the same key. */ - - function is(componentA, componentB) { return componentA.key === componentB.key; } @@ -2482,18 +2419,21 @@ * @param grid - The Muuri instance. */ function fillGrid(grid) { - var sizerElement = document.createElement('div'); // Keep the element hidden. + var sizerElement = document.createElement('div'); + // Keep the element hidden. sizerElement.style.visibility = 'hidden'; - sizerElement.style.position = 'absolute'; // Add the class. - - sizerElement.classList.add('grid-sizer'); // Set the element. + sizerElement.style.position = 'absolute'; + // Add the class. + sizerElement.classList.add('grid-sizer'); + // Set the element. addDecoration(grid, { sizerElement: sizerElement }); - var gridElement = grid.getElement(); // Insert as first child. + var gridElement = grid.getElement(); + // Insert as first child. if (gridElement.children.length === 0) { gridElement.appendChild(sizerElement); } else { @@ -2503,6 +2443,7 @@ // Allowed position values. var positions = ['relative', 'absolute', 'fixed']; + /** * Fill a grid element: * - If it is not position the style.position is setted to "relative". @@ -2515,26 +2456,25 @@ * @param gridElement - The element to fill. * @param gridClass - The Css class of the grid element. */ - function fillGridElement(gridElement, gridClass) { - var position = getComputedStyle(gridElement).position; // Set the default position. + var position = getComputedStyle(gridElement).position; + // Set the default position. if (!positions.includes(position)) { gridElement.style.position = positions[0]; - } // Set the grid class. - + } - gridElement.classList.add(gridClass); // Ensure that the grid class can't be removed. + // Set the grid class. + gridElement.classList.add(gridClass); + // Ensure that the grid class can't be removed. var defaultSetAttribute = gridElement.setAttribute.bind(gridElement); - gridElement.setAttribute = function setAttribute(attribute, value) { if (attribute === 'class') { - var classNames = (gridElement.getAttribute('class') || '').split(' '); // Add the grid class. - + var classNames = (gridElement.getAttribute('class') || '').split(' '); + // Add the grid class. if (!classNames.includes(gridClass)) value = "".concat(value, " ").concat(gridClass); } - defaultSetAttribute(attribute, value); }; } @@ -2546,18 +2486,18 @@ * * @param item - The item to fill. */ - function fillItem(item) { addDecoration(item, { props: {}, data: {} - }); // Change the sort data. - + }); + // Change the sort data. Object.defineProperty(item, '_sortData', { get: function get() { return this.getData(); }, - set: function set() {// nothing to do here. + set: function set() { + // nothing to do here. } }); } @@ -2574,20 +2514,20 @@ * @param itemClasses - The Css classes of the items. */ function fillItemElement(itemElement, itemClasses) { - itemElement.style.position = 'absolute'; // Ensure that the Css item classes are not removed. + itemElement.style.position = 'absolute'; + // Ensure that the Css item classes are not removed. var defaultSetAttribute = itemElement.setAttribute.bind(itemElement); - itemElement.setAttribute = function setAttribute(attribute, value) { if (attribute === 'class') { var classNames = (itemElement.getAttribute('class') || '').split(' '); var classNamesToAdd = classNames.filter(function (className) { return itemClasses.includes(className); - }); // Add the Css items classes. + }); + // Add the Css items classes. value = "".concat(value, " ").concat(classNamesToAdd.join(' ')); } - defaultSetAttribute(attribute, value); }; } @@ -2600,7 +2540,6 @@ * @param callback - The function to memoize. * @returns - The memoized function. */ - function useFunction(callback) { return React.useRef(callback).current; } @@ -2612,17 +2551,19 @@ * @param dependencyList - The dependencyList. * @returns - If the dependencyList is changed from the previous render. */ - function useReference(dependencyList) { - var ref = React.useRef(dependencyList); // If it is the first call return true. - - if (ref.current === dependencyList) return true; // Compare the dependencyLists. + var ref = React.useRef(dependencyList); - var didUpdate = compare(ref.current, dependencyList); // Keep the reference of the new one. + // If it is the first call return true. + if (ref.current === dependencyList) return true; + // Compare the dependencyLists. + var didUpdate = compare(ref.current, dependencyList); + // Keep the reference of the new one. ref.current = dependencyList; return didUpdate; } + /** * Compare two dependencyLists and return if they are different. * @@ -2630,14 +2571,11 @@ * @param b - The second dependencyList to compare. * @returns - If the 2 dependencyLists are different. */ - function compare(a, b) { if (a.length !== b.length) return true; - for (var i = 0; i < a.length; i++) { if (a[i] !== b[i]) return true; } - return false; } @@ -2647,18 +2585,18 @@ * @param didUpdate - The method to run. * @param deps - The dependecies. */ - function useInstantEffect(didUpdate, deps) { // Deps check. var needUpdate = useReference(deps); - var cleanUpRef = React.useRef(); // Run. + var cleanUpRef = React.useRef(); + // Run. if (needUpdate) { if (cleanUpRef.current) cleanUpRef.current(); cleanUpRef.current = didUpdate(); - } // Catch unmount. - + } + // Catch unmount. React.useEffect(function () { return function () { if (cleanUpRef.current) cleanUpRef.current(); @@ -2674,14 +2612,11 @@ * @param factory - The factory method. * @returns - The memoized value. */ - function useMemoized(factory) { var valueRef = React.useRef(); - if (!valueRef.current) { valueRef.current = factory(); } - return valueRef.current; } @@ -2691,7 +2626,6 @@ * * @returns - The re-render method. */ - function useRerender() { var setState = React.useState()[1]; return useFunction(function () { @@ -2704,92 +2638,102 @@ // Item component. function ItemComponent(_ref) { var child = _ref.children, - itemClasses = _ref.itemClasses, - itemAddController = _ref.itemAddController, - itemRemoveController = _ref.itemRemoveController, - propsToData = _ref.propsToData, - itemKey = _ref.itemKey, - grid = _ref.grid; + itemClasses = _ref.itemClasses, + itemAddController = _ref.itemAddController, + itemRemoveController = _ref.itemRemoveController, + propsToData = _ref.propsToData, + itemKey = _ref.itemKey, + grid = _ref.grid; // The store provided doesn't change the reference. var store = useMemoized(function () { // Create the controllers. var eventController = new EventController(); - var itemRefController = new ItemRefController(); // Add the data that won't change. - + var itemRefController = new ItemRefController(); + // Add the data that won't change. itemRefController.set('key', itemKey); - itemRefController.set('eventController', eventController); // Return the controllers. - + itemRefController.set('eventController', eventController); + // Return the controllers. return { eventController: eventController, itemRefController: itemRefController, itemRemoveController: itemRemoveController, grid: grid }; - }); // Set the props. + }); + // Set the props. store.itemRefController.set('props', child.props); store.itemRemoveController = itemRemoveController; - store.grid = grid; // Set the data. + store.grid = grid; + // Set the data. if (propsToData) { // Get the data. - var data = propsToData(child.props); // Must be an object. + var data = propsToData(child.props); - invariant(_typeof$1(data) === 'object', "The data returned by 'propsToData' must be an object, founded ".concat(_typeof$1(data))); // Set the data. + // Must be an object. + invariant(_typeof(data) === 'object', "The data returned by 'propsToData' must be an object, founded ".concat(_typeof(data))); + // Set the data. store.itemRefController.set('data', data); - } // On mount. - + } + // On mount. React.useEffect(function () { // Request the item. itemAddController.requestItem(function (item) { - fillItem(item); // @ts-ignore - + fillItem(item); + // @ts-ignore fillItemElement(item.getElement(), itemClasses); store.itemRefController.setItem(item); }); return function () { // The item. var item = store.itemRefController.getItem(); - invariant(item !== null); // The element. + invariant(item !== null); + // The element. var element = item.getElement(); - invariant(element !== undefined); // If the item is going to be unmounted + invariant(element !== undefined); + + // If the item is going to be unmounted // and it is being dragged it have to end the event // (Because it could be child of a different DOM element). - if (item.isDragging()) { element.style.display = 'none'; - element.style.visibility = 'hidden'; // @ts-ignore + element.style.visibility = 'hidden'; + // @ts-ignore if (item._drag) item._drag.destroy(); store.grid.getElement().appendChild(element); - } // Remove the item. - + } + // Remove the item. store.itemRefController["delete"](); - store.itemRemoveController.removeItem(item); // Destroy the controllers instances. + store.itemRemoveController.removeItem(item); + // Destroy the controllers instances. store.itemRefController.destroy(); store.eventController.destroy(); }; }, []); // eslint-disable-line - // Render. - return /*#__PURE__*/React__default['default'].createElement(ItemProvider, { + // Render. + return /*#__PURE__*/React__default["default"].createElement(ItemProvider, { value: store }, child); - } // PropTypes. + } + // PropTypes. ItemComponent.propTypes = { - itemAddController: propTypes.object.isRequired, - itemClasses: propTypes.arrayOf(propTypes.string.isRequired).isRequired, - propsToData: propTypes.func, - children: propTypes.element.isRequired, - grid: propTypes.instanceOf(Muuri__default['default']).isRequired - }; // Display name. + itemAddController: PropTypes.object.isRequired, + itemClasses: PropTypes.arrayOf(PropTypes.string.isRequired).isRequired, + propsToData: PropTypes.func, + children: PropTypes.element.isRequired, + grid: PropTypes.instanceOf(Muuri__default["default"]).isRequired + }; + // Display name. ItemComponent.displayName = 'ItemComponent'; /** @@ -2808,10 +2752,10 @@ index: indicesToAdd[i], layout: false }); - } // Show the added items (usefull just if the items are - // hidden by default and the filter is not setted). - + } + // Show the added items (usefull just if the items are + // hidden by default and the filter is not setted). if (!filter && addOptions !== null && addOptions !== void 0 && addOptions.show) { grid.show(grid.getItems(indicesToAdd), { layout: false @@ -2835,13 +2779,13 @@ /** Class name. */ var gridClassName = 'containerClass'; + /** * Returns the Css class of the grid element. * * @param grid - The Muuri instance. * @returns - The class. */ - function getGridClass(grid) { // @ts-ignore return grid._settings[gridClassName]; @@ -2849,13 +2793,13 @@ /** Class names. */ var itemClassNames = ['itemClass', 'itemVisibleClass', 'itemHiddenClass', 'itemPositioningClass', 'itemDraggingClass', 'itemReleasingClass', 'itemPlaceholderClass']; + /** * Returns the items classes. * * @param grid - The Muuri instance. * @returns - The classes. */ - function getItemClasses(grid) { // @ts-ignore return itemClassNames.map(function (className) { @@ -2900,10 +2844,8 @@ }); } - function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - + function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * Sort the items. * @@ -2916,22 +2858,24 @@ // @ts-ignore sortOptions = _objectSpread$1(_objectSpread$1({}, sortOptions || {}), {}, { layout: false - }); // Handle a function. + }); + // Handle a function. if (typeof predicate === 'function') { handleFunction(grid, predicate, sortOptions); - } // Handle a string. - + } + // Handle a string. if (typeof predicate === 'string') { handleString(grid, predicate, sortOptions); - } // Hanndle an array of keys. - + } + // Hanndle an array of keys. if (Array.isArray(predicate)) { handleArray(grid, predicate, sortOptions); } } + /** * Sort the items given a predicate function. * @@ -2939,12 +2883,12 @@ * @param predicate - The predicate function. * @param sortOptions - The sort options. */ - function handleFunction(grid, predicate, sortOptions) { grid.sort(function (itemA, itemB) { return predicate(itemA.getData(), itemB.getData(), itemA, itemB); }, sortOptions); } + /** * Sort the items given a predicate string. * @@ -2952,11 +2896,10 @@ * @param predicate - The predicate string. * @param sortOptions - The sort options. */ - - function handleString(grid, predicate, sortOptions) { grid.sort(predicate, sortOptions); } + /** * Sort the items given an array of keys. * If the key has a match, the item is inserted in that position, otherwise at the bottom. @@ -2965,29 +2908,29 @@ * @param predicate - The array of keys. * @param sortOptions - The sort options. */ - - function handleArray(grid, predicate, sortOptions) { - var items = grid.getItems(); // Items that can be sorted. - - var sortedItems = []; // Items that can't be sorted. - - var otherItems = []; // Fills the arrays. + var items = grid.getItems(); + // Items that can be sorted. + var sortedItems = []; + // Items that can't be sorted. + var otherItems = []; + // Fills the arrays. items.forEach(function (item) { var itemKey = item._component.key; var index = predicate.findIndex(function (key) { return key === itemKey; }); - if (index > -1) { sortedItems[index] = item; } else { otherItems.push(item); } - }); // Sort. + }); - grid.sort(Array.prototype.concat( // Some position can be empty. + // Sort. + grid.sort(Array.prototype.concat( + // Some position can be empty. sortedItems.filter(function (item) { return !!item; }), otherItems), sortOptions); @@ -2998,30 +2941,28 @@ // Grid component. function GridComponent(_ref) { var children = _ref.children, - gridProps = _ref.gridProps, - grid = _ref.grid, - filter = _ref.filter, - sort = _ref.sort, - sortOptions = _ref.sortOptions, - addOptions = _ref.addOptions, - propsToData = _ref.propsToData, - onSend = _ref.onSend, - onDragStart = _ref.onDragStart, - onDragEnd = _ref.onDragEnd, - onFilter = _ref.onFilter, - onSort = _ref.onSort, - onMount = _ref.onMount, - onUnmount = _ref.onUnmount, - forceSync = _ref.forceSync, - dragFixed = _ref.dragFixed, - dragEnabled = _ref.dragEnabled, - instantLayout = _ref.instantLayout; - + gridProps = _ref.gridProps, + grid = _ref.grid, + filter = _ref.filter, + sort = _ref.sort, + sortOptions = _ref.sortOptions, + addOptions = _ref.addOptions, + propsToData = _ref.propsToData, + onSend = _ref.onSend, + onDragStart = _ref.onDragStart, + onDragEnd = _ref.onDragEnd, + onFilter = _ref.onFilter, + onSort = _ref.onSort, + onMount = _ref.onMount, + onUnmount = _ref.onUnmount, + forceSync = _ref.forceSync, + dragFixed = _ref.dragFixed, + dragEnabled = _ref.dragEnabled, + instantLayout = _ref.instantLayout; /* ------------------ */ - /* ----- STORES ----- */ - /* ------------------ */ + // Store references of objects // generated in previous renders. var store = useMemoized(function () { @@ -3029,31 +2970,16 @@ // Grid and items data. gridRef: /*#__PURE__*/ - /* */ React.createRef(), - gridClass: - /* */ - getGridClass(grid), - itemClasses: - /* */ - getItemClasses(grid), + gridClass: /* */getGridClass(grid), + itemClasses: /* */getItemClasses(grid), // Controllers. - childrenController: - /* */ - new ChildrenController(), - fiberController: - /* */ - new FiberController(), - itemAddController: - /* */ - new ItemAddController(), - itemRemoveController: - /* */ - new ItemRemoveController(), - layoutController: - /* */ - new LayoutController(), + childrenController: /* */new ChildrenController(), + fiberController: /* */new FiberController(), + itemAddController: /* */new ItemAddController(), + itemRemoveController: /* */new ItemRemoveController(), + layoutController: /* */new LayoutController(), // Events. onUnmount: onUnmount, onDragStart: onDragStart, @@ -3062,73 +2988,46 @@ onSort: onSort, onSend: onSend }; - }); // Store references of objects + }); + + // Store references of objects // that are used inside useEffect. // The references are flushed on each new render. - var vars = { // Items data. - indicesToAdd: - /* */ - [], - addedDOMItems: - /* */ - [], - itemsToRemove: - /* */ - [], - itemsToRefresh: - /* */ - [], - itemsToShow: - /* */ - [], - itemsToHide: - /* */ - [], + indicesToAdd: /* */[], + addedDOMItems: /* */[], + itemsToRemove: /* */[], + itemsToRefresh: /* */[], + itemsToShow: /* */[], + itemsToHide: /* */[], // Items flags. - hasAdded: - /* */ - false, - hasRemoved: - /* */ - false, - hasFiltered: - /* */ - false, - hasSorted: - /* */ - false, - hasRefreshed: - /* */ - false, - hasShown: - /* */ - false, - hasHidden: - /* */ - false + hasAdded: /* */false, + hasRemoved: /* */false, + hasFiltered: /* */false, + hasSorted: /* */false, + hasRefreshed: /* */false, + hasShown: /* */false, + hasHidden: /* */false }; - /* ----------------- */ + /* ----------------- */ /* ----- MOUNT ----- */ - /* ----------------- */ - // Initialize the grid on mount. + // Initialize the grid on mount. React.useEffect(function () { /* ------------------ */ - /* ----- EVENTS ----- */ - /* ------------------ */ + // Add all the event handlers. - grid // "Send" and "receive" events. + grid + // "Send" and "receive" events. .on('beforeSend', function (_ref2) { var item = _ref2.item, - fromGrid = _ref2.fromGrid, - fromIndex = _ref2.fromIndex; - + fromGrid = _ref2.fromGrid, + fromIndex = _ref2.fromIndex; if (!getDecoration(item).sentPayload) { // Generate the sentPayload. var sentPayload = { @@ -3136,23 +3035,25 @@ fromFiberController: store.fiberController, fromGrid: fromGrid, fromIndex: fromIndex - }; // Add the decoration. + }; + // Add the decoration. addDecoration(item, { sentPayload: sentPayload }); } }).on('receive', function (_ref3) { var item = _ref3.item, - toGrid = _ref3.toGrid, - toIndex = _ref3.toIndex; + toGrid = _ref3.toGrid, + toIndex = _ref3.toIndex; // Controllers. var toChildrenController = store.childrenController; - var toFiberController = store.fiberController; // If the method is activated by user interaction (the item is being dragged) + var toFiberController = store.fiberController; + + // If the method is activated by user interaction (the item is being dragged) // the synchronization will be performed during the "dragEnd" event. // If the method is called via Muuri's instance (the item is not being dragged) // the synchronization takes place here, but the onSend callback is not fired. - if (item.isDragging()) { // Generate the receivedPayload. var receivedPayload = { @@ -3160,82 +3061,95 @@ toFiberController: toFiberController, toGrid: toGrid, toIndex: toIndex - }; // Add the decoration. + }; + // Add the decoration. addDecoration(item, { receivedPayload: receivedPayload }); } else { // Payloads data. - var sentPayload = getDecoration(item).sentPayload; // The payload must have been created in the send method. - - invariant(sentPayload !== null && _typeof$1(sentPayload) === 'object'); // Controllers. - + var sentPayload = getDecoration(item).sentPayload; + // The payload must have been created in the send method. + invariant(sentPayload !== null && _typeof(sentPayload) === 'object'); + // Controllers. var fromChildrenController = sentPayload.fromChildrenController, - fromFiberController = sentPayload.fromFiberController; // Remove the payload. + fromFiberController = sentPayload.fromFiberController; + // Remove the payload. addDecoration(item, { sentPayload: null - }); // Remove the item instances from the old GridComponent. + }); + // Remove the item instances from the old GridComponent. var itemFiber = fromFiberController.remove(item.getKey()); - var itemComponent = fromChildrenController.remove(itemFiber.index); // Add the item instances to the new GridComponent. + var itemComponent = fromChildrenController.remove(itemFiber.index); + // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); toChildrenController.append(itemComponent); - } // Emit the "send" event. - + } + // Emit the "send" event. getDecoration(item).eventController.emitEvent('send', grid); - }) // Drag events. + }) + + // Drag events. .on('dragInit', function (item, event) { // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. - store.childrenController.incrementDragCounter(); // Emit the "drag" event. + store.childrenController.incrementDragCounter(); + // Emit the "drag" event. // This event is used instead of "dragStart" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). - - getDecoration(item).eventController.emitEvent('drag', true); // "onDragStart" Callback. - + getDecoration(item).eventController.emitEvent('drag', true); + // "onDragStart" Callback. if (store.onDragStart) store.onDragStart(item, event); }).on('dragEnd', function (item) { // Payloads. var sentPayload = getDecoration(item).sentPayload; - var receivedPayload = getDecoration(item).receivedPayload; // If an item was sent during the drag the - // GridComponents are synchronized. + var receivedPayload = getDecoration(item).receivedPayload; + // If an item was sent during the drag the + // GridComponents are synchronized. if (sentPayload && receivedPayload) { // SentPayload data. var fromChildrenController = sentPayload.fromChildrenController, - fromFiberController = sentPayload.fromFiberController, - fromGrid = sentPayload.fromGrid, - fromIndex = sentPayload.fromIndex; // ReceivedPayload data. + fromFiberController = sentPayload.fromFiberController, + fromGrid = sentPayload.fromGrid, + fromIndex = sentPayload.fromIndex; + // ReceivedPayload data. var toChildrenController = receivedPayload.toChildrenController, - toFiberController = receivedPayload.toFiberController, - toGrid = receivedPayload.toGrid, - toIndex = receivedPayload.toIndex; // Reset the payloads. + toFiberController = receivedPayload.toFiberController, + toGrid = receivedPayload.toGrid, + toIndex = receivedPayload.toIndex; + // Reset the payloads. addDecoration(item, { sentPayload: null, receivedPayload: null - }); // Check if the item has been sended. + }); + // Check if the item has been sended. if (fromGrid !== toGrid) { // "onSend" will be called with the receive event. - invariant(typeof store.onSend === 'function', 'An item cannot be sent to another MuuriComponent if the ' + "'onSend' property has not been passed to the MuuriComponent."); // Remove the item instances from the old GridComponent. + invariant(typeof store.onSend === 'function', 'An item cannot be sent to another MuuriComponent if the ' + "'onSend' property has not been passed to the MuuriComponent."); + // Remove the item instances from the old GridComponent. var itemFiber = fromFiberController.remove(item.getKey()); - var itemComponent = fromChildrenController.remove(itemFiber.index); // Add the item instances to the new GridComponent. + var itemComponent = fromChildrenController.remove(itemFiber.index); + // Add the item instances to the new GridComponent. toFiberController.append(itemFiber); - toChildrenController.append(itemComponent); // "onSend" callback. + toChildrenController.append(itemComponent); + + // "onSend" callback. // DragEnd is called in the grid where // the drag start, so onSend. - store.onSend({ // The key the user has set. key: getDecoration(item).key, @@ -3256,25 +3170,27 @@ // The childrenController must change the positions of // the newly added components if any items are being // dragged to add the safely. - store.childrenController.decrementDragCounter(); // Emit the event. + store.childrenController.decrementDragCounter(); + // Emit the event. // This event is used instead of "dragEnd" to allow the // reRender of the component when the item is not inside // the dragContainer, this makes it possible to change // the style of the element safely (e.g. using relative dimensions). - - getDecoration(item).eventController.emitEvent('drag', false); // Call the event. - + getDecoration(item).eventController.emitEvent('drag', false); + // Call the event. if (store.onDragEnd) store.onDragEnd(item); - }) // Show and hide events. + }) + + // Show and hide events. .on('showStart', function (items) { // The items could be shown before they are decorated. - if (!isDecorated(items[0])) return; // Emit the event. - + if (!isDecorated(items[0])) return; + // Emit the event. items.forEach(function (item) { - var eventController = getDecoration(item).eventController; // The event is triggered also for items that have not + var eventController = getDecoration(item).eventController; + // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. - if (eventController.getPayload('show') !== true) { eventController.emitEvent('show', true); } @@ -3282,43 +3198,45 @@ }).on('hideEnd', function (items) { // Emit the event. items.forEach(function (item) { - var eventController = getDecoration(item).eventController; // The event is triggered also for items that have not + var eventController = getDecoration(item).eventController; + // The event is triggered also for items that have not // changed their "visibility" state. // This check is done to avoid useless re-rendering. - if (eventController.getPayload('show') !== false) { eventController.emitEvent('show', false); } }); - }) // Filter and sort events. + }) + + // Filter and sort events. .on('filter', function (shownItems, hiddenItems) { if (store.onFilter) store.onFilter(shownItems, hiddenItems); }).on('sort', function (currentOrder, previousOrder) { if (store.onSort) store.onSort(currentOrder, previousOrder); - }); // Fix the dimensions of the items when they are dragged. + }); + // Fix the dimensions of the items when they are dragged. if (dragFixed) { grid.on('dragInit', function (item) { // Let's set fixed widht/height to the dragged item // so that it does not stretch unwillingly when // it's appended to the document body for the // duration of the drag. - var element = item.getElement(); // The element must exist. - - invariant(element !== undefined); // Get the computed dimensions. - + var element = item.getElement(); + // The element must exist. + invariant(element !== undefined); + // Get the computed dimensions. var _getComputedStyle = getComputedStyle(element), - width = _getComputedStyle.width, - height = _getComputedStyle.height, - paddingTop = _getComputedStyle.paddingTop; // Save the previous style in case it was setted. - - + width = _getComputedStyle.width, + height = _getComputedStyle.height, + paddingTop = _getComputedStyle.paddingTop; + // Save the previous style in case it was setted. addDecoration(item, { dragWidth: element.style.width, dragHeight: element.style.height, dragPaddingTop: element.style.paddingTop - }); // Set the new style. - + }); + // Set the new style. element.style.width = width; element.style.height = height; element.style.paddingTop = paddingTop; @@ -3327,38 +3245,38 @@ // dragged item now that it is back in a grid // column and can freely adjust to it's // surroundings. - var element = item.getElement(); // The element must exist. - - invariant(element !== undefined); // Get the old style. - + var element = item.getElement(); + // The element must exist. + invariant(element !== undefined); + // Get the old style. var _getDecoration = getDecoration(item), - dragWidth = _getDecoration.dragWidth, - dragHeight = _getDecoration.dragHeight, - dragPaddingTop = _getDecoration.dragPaddingTop; // Restore the previous style in case it was setted. - - + dragWidth = _getDecoration.dragWidth, + dragHeight = _getDecoration.dragHeight, + dragPaddingTop = _getDecoration.dragPaddingTop; + // Restore the previous style in case it was setted. element.style.width = dragWidth; element.style.height = dragHeight; element.style.paddingTop = dragPaddingTop; }); } - /* ---------------- */ + /* ---------------- */ /* ----- GRID ----- */ - /* -----------------*/ - // Check . + // Check . + invariant(store.gridRef.current !== null); - invariant(store.gridRef.current !== null); // Work with the grid. + // Work with the grid. // @ts-ignore - grid._element = store.gridRef.current; fillGridElement(store.gridRef.current, store.gridClass); - fillGrid(grid); // "onMount" Callback. + fillGrid(grid); - if (onMount) onMount(grid); // Delete the instance from the global map. + // "onMount" Callback. + if (onMount) onMount(grid); + // Delete the instance from the global map. return function () { // Destroy the controllers. store.childrenController.destroy(); @@ -3370,35 +3288,37 @@ }, []); // eslint-disable-line /* ---------------- */ - /* ----- INIT ----- */ - /* -----------------*/ - // Init the controllers. + // Init the controllers. store.childrenController.useInit(children); store.fiberController.useInit(store.gridRef); store.itemRemoveController.useInit(); store.itemAddController.useInit(); - store.layoutController.useInit(); // IsChanged flags. + store.layoutController.useInit(); + // IsChanged flags. var isFilterChanged = useReference([filter]); - var isSortChanged = useReference([sort, sortOptions]); // Get items to add/remove. + var isSortChanged = useReference([sort, sortOptions]); + // Get items to add/remove. React.useEffect(function () { // Set drag enabled option. addDecoration(grid, { dragEnabled: dragEnabled - }); // Set the items data. + }); + // Set the items data. vars.indicesToAdd = store.childrenController.getIndicesToAdd(); vars.addedDOMItems = store.fiberController.getStateNodes(vars.indicesToAdd); vars.itemsToRemove = store.itemRemoveController.getItemsToRemove(); vars.itemsToRefresh = store.layoutController.getItemsToRefresh(); vars.itemsToShow = store.layoutController.getItemsToShow(); - vars.itemsToHide = store.layoutController.getItemsToHide(); // This will remove lot of the implementation - // problems for the user. + vars.itemsToHide = store.layoutController.getItemsToHide(); + // This will remove lot of the implementation + // problems for the user. store.onUnmount = onUnmount; store.onDragStart = onDragStart; store.onDragEnd = onDragEnd; @@ -3406,122 +3326,112 @@ store.onSort = onSort; store.onSend = onSend; }); - /* ------------------- */ + /* ------------------- */ /* ----- ACTIONS ----- */ - /* ------------------- */ React.useEffect(function () { /* ---------------------- */ - /* ---- ADD & REMOVE ---- */ - /* ---------------------- */ + // Remove items. if (vars.itemsToRemove.length) { - removeItems(grid, vars.itemsToRemove); // Set the flag. - + removeItems(grid, vars.itemsToRemove); + // Set the flag. vars.hasRemoved = true; - } // Add items after the old ones are removed - // to add them in the right positions. - + } + // Add items after the old ones are removed + // to add them in the right positions. if (vars.indicesToAdd.length) { - addItems(grid, vars.addedDOMItems, vars.indicesToAdd, addOptions, filter); // New Items. - - var addedItems = grid.getItems(vars.indicesToAdd); // Emit the new items to the itemComponents. - - store.itemAddController.emit(addedItems); // Set the flag. - + addItems(grid, vars.addedDOMItems, vars.indicesToAdd, addOptions, filter); + // New Items. + var addedItems = grid.getItems(vars.indicesToAdd); + // Emit the new items to the itemComponents. + store.itemAddController.emit(addedItems); + // Set the flag. vars.hasAdded = true; } - /* ------------------------- */ + /* ------------------------- */ /* ----- SORT & FILTER ----- */ - /* ------------------------- */ - // Filter items. - + // Filter items. if (filter && (isFilterChanged || vars.hasAdded || forceSync)) { - filterItems(grid, filter); // Set the flag. - + filterItems(grid, filter); + // Set the flag. vars.hasFiltered = true; - } // Sort items. - + } + // Sort items. if (sort && (isSortChanged || vars.hasAdded || forceSync)) { - sortItems(grid, sort, sortOptions); // Set the flag. - + sortItems(grid, sort, sortOptions); + // Set the flag. vars.hasSorted = true; } - /* ----------------------- */ + /* ----------------------- */ /* ----- SHOW & HIDE ----- */ - /* ----------------------- */ - // Filter has priority on the items visibility. - + // Filter has priority on the items visibility. if (!filter && vars.itemsToShow.length) { - showItems(grid, vars.itemsToShow); // Set the flag. - + showItems(grid, vars.itemsToShow); + // Set the flag. vars.hasShown = true; - } // Filter has priority on the items visibility. - + } + // Filter has priority on the items visibility. if (!filter && vars.itemsToHide.length) { - hideItems(grid, vars.itemsToHide); // Set the flag. - + hideItems(grid, vars.itemsToHide); + // Set the flag. vars.hasHidden = true; } - /* ------------------- */ + /* ------------------- */ /* ----- REFRESH ----- */ - /* ------------------- */ - // Items with dimensions to refresh. - + // Items with dimensions to refresh. if (vars.itemsToRefresh.length) { - grid.refreshItems(vars.itemsToRefresh); // Set the flag. - + grid.refreshItems(vars.itemsToRefresh); + // Set the flag. vars.hasRefreshed = true; } - /* ------------------ */ + /* ------------------ */ /* ----- LAYOUT ----- */ - /* ------------------ */ + // Layout is calculated only in the end. // Check the previous flags. - - if (vars.hasAdded || vars.hasRemoved || vars.hasSorted || vars.hasFiltered || vars.hasRefreshed || vars.hasShown || vars.hasHidden) { grid.layout(instantLayout); } }); - /* ------------------ */ + /* ------------------ */ /* ----- RENDER ----- */ - /* ------------------ */ - // Provided value doesn't change the reference. + // Provided value doesn't change the reference. var value = useMemoized(function () { return { layoutController: store.layoutController, grid: grid }; - }); // render. + }); - return /*#__PURE__*/React__default['default'].createElement(GridProvider, { + // render. + return /*#__PURE__*/React__default["default"].createElement(GridProvider, { value: value - }, /*#__PURE__*/React__default['default'].createElement("div", _extends({}, gridProps, { + }, /*#__PURE__*/React__default["default"].createElement("div", _extends({}, gridProps, { ref: store.gridRef }, store.fiberController.getFlagProp()), store.childrenController.render(function (child, key) { - return /*#__PURE__*/React__default['default'].createElement(ItemComponent, { + return /*#__PURE__*/React__default["default"].createElement(ItemComponent, { key: key, itemKey: key, grid: grid, @@ -3531,32 +3441,34 @@ itemRemoveController: store.itemRemoveController }, child); }))); - } // Proptypes. + } + // Proptypes. GridComponent.propTypes = { - grid: propTypes.object.isRequired, - gridProps: propTypes.object, - filter: propTypes.oneOfType([propTypes.string, propTypes.func]), - sort: propTypes.oneOfType([propTypes.string, propTypes.func, propTypes.arrayOf(propTypes.string)]), - sortOptions: propTypes.exact({ - descending: propTypes.bool + grid: PropTypes.object.isRequired, + gridProps: PropTypes.object, + filter: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), + sort: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.arrayOf(PropTypes.string)]), + sortOptions: PropTypes.exact({ + descending: PropTypes.bool }), - addOptions: propTypes.exact({ - show: propTypes.bool + addOptions: PropTypes.exact({ + show: PropTypes.bool }), - onSend: propTypes.func, - onDragStart: propTypes.func, - onDragEnd: propTypes.func, - onFilter: propTypes.func, - onSort: propTypes.func, - onMount: propTypes.func, - onUnmount: propTypes.func, - forceSync: propTypes.bool, - dragFixed: propTypes.bool, - dragEnabled: propTypes.bool, - instantLayout: propTypes.bool - }; // Default props. + onSend: PropTypes.func, + onDragStart: PropTypes.func, + onDragEnd: PropTypes.func, + onFilter: PropTypes.func, + onSort: PropTypes.func, + onMount: PropTypes.func, + onUnmount: PropTypes.func, + forceSync: PropTypes.bool, + dragFixed: PropTypes.bool, + dragEnabled: PropTypes.bool, + instantLayout: PropTypes.bool + }; + // Default props. GridComponent.defaultProps = { gridProps: {}, addOptions: { @@ -3569,8 +3481,9 @@ dragFixed: false, dragEnabled: false, instantLayout: false - }; // Display name. + }; + // Display name. GridComponent.displayName = 'GridComponent'; function _objectWithoutPropertiesLoose(source, excluded) { @@ -3578,13 +3491,11 @@ var target = {}; var sourceKeys = Object.keys(source); var key, i; - for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } - return target; } @@ -3592,10 +3503,8 @@ if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; - if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; @@ -3603,7 +3512,6 @@ target[key] = source[key]; } } - return target; } @@ -3614,12 +3522,9 @@ var MuuriMap = /*#__PURE__*/function () { function MuuriMap() { _classCallCheck(this, MuuriMap); - _defineProperty(this, "_idMap", new Map()); - _defineProperty(this, "_groupMap", new Map()); } - _createClass(MuuriMap, [{ key: "get", value: @@ -3632,6 +3537,7 @@ function get(id) { return this._idMap.get(id) || null; } + /** * Get all the grid instances in the group of the given id. * The reference of the group array never changes. @@ -3639,33 +3545,30 @@ * @param groupId - The group id. * @returns - The array of grid instances. */ - }, { key: "getGroup", value: function getGroup(groupId) { var group = this._groupMap.get(groupId); - if (!group) { var newGroup = []; - this._groupMap.set(groupId, newGroup); - return newGroup; } else { return group; } } + /** * Get all the grid instances in the map. * * @returns - The grid instances. */ - }, { key: "getAll", value: function getAll() { return Array.from(this._idMap.values()); } + /** * Set the grid instance with the given id. * @@ -3673,14 +3576,13 @@ * @param id - The id of the instance. * @returns - The muuriMap. */ - }, { key: "set", value: function set(grid, id) { this._idMap.set(id, grid); - return this; } + /** * Set the grid instance in the group of the given id. * @@ -3688,68 +3590,59 @@ * @param groupId - The id of the group. * @returns - The muuriMap. */ - }, { key: "setGroup", value: function setGroup(grid, groupId) { var group = this._groupMap.get(groupId); - if (group) { group.push(grid); } else { this._groupMap.set(groupId, [grid]); } - return this; } + /** * Delete the grid instance with the given id. * * @param id - The id of the instance. * @returns - The muuriMap. */ - }, { key: "delete", value: function _delete(id) { this._idMap["delete"](id); - return this; } + /** * Delete the instance from the group with the given id. * * @param grid - The grid instance. * @param groupIds - The group ids of the instance. */ - }, { key: "deleteGroup", value: function deleteGroup(grid, groupId) { var group = this._groupMap.get(groupId); - if (group) { var index = group.indexOf(grid); if (index > -1) group.splice(index, 1); } - return this; } + /** * Clear the maps. */ - }, { key: "clear", value: function clear() { this._idMap.clear(); - this._groupMap.clear(); - return this; } }]); - return MuuriMap; }(); var muuriMap = new MuuriMap(); @@ -3761,14 +3654,16 @@ * @returns - The muuri instance. */ function getInstance(options) { - var el = document.createElement('div'); // The element won't be visible. - - el.style.display = 'none'; // Muuri (0.8.0) need an element in the DOM to be instanciated. - - document.body.appendChild(el); // Generate the instance. + var el = document.createElement('div'); + // The element won't be visible. + el.style.display = 'none'; + // Muuri (0.8.0) need an element in the DOM to be instanciated. + document.body.appendChild(el); - var grid = new Muuri__default['default'](el, options); // Remove the element. + // Generate the instance. + var grid = new Muuri__default["default"](el, options); + // Remove the element. document.body.removeChild(el); return grid; } @@ -3781,7 +3676,8 @@ */ function handleRef(ref, value) { if (!ref) return; - if (typeof ref === 'function') ref(value); // @ts-ignore + if (typeof ref === 'function') ref(value); + // @ts-ignore else if ('current' in ref) ref.current = value; } @@ -3792,20 +3688,23 @@ * @param options - The grid options. */ function setDragAutoScroll(options) { - var dragAutoScroll = options.dragAutoScroll; // Wrap the options only if it is setted. + var dragAutoScroll = options.dragAutoScroll; + // Wrap the options only if it is setted. if (!dragAutoScroll || !Array.isArray(dragAutoScroll.targets)) return; dragAutoScroll.targets.forEach(function (target) { // Check if it is an object to wrap. if (isTargetElement(target)) return; - invariant('element' in target, 'You must provide an element in each scroll target'); // Scroll target element. - - var element = target.element; // The element ref. + invariant('element' in target, 'You must provide an element in each scroll target'); + // Scroll target element. + var element = target.element; + // The element ref. var ref = { current: null - }; // Define the element property. + }; + // Define the element property. Object.defineProperty(target, 'element', { get: function get() { return ref.current; @@ -3817,21 +3716,24 @@ ref = element; } } - }); // Set the element. + }); + // Set the element. target.element = element; }); } + /** * Returns if the target is a valid element. * * @param element - The target. * @returns - If the target is a valid element. */ - function isTargetElement(target) { - return (// A DOM element. - target instanceof HTMLElement || // The window. + return ( + // A DOM element. + target instanceof HTMLElement || + // The window. target instanceof window.constructor ); } @@ -3843,12 +3745,13 @@ * @param options - The grid options. */ function setDragContainer(options) { - var dragContainer = options.dragContainer; // The drag container ref. - + var dragContainer = options.dragContainer; + // The drag container ref. var ref = { current: null - }; // Define the property. + }; + // Define the property. Object.defineProperty(options, 'dragContainer', { get: function get() { return ref.current; @@ -3860,8 +3763,9 @@ ref = value; } } - }); // Set the drag container. + }); + // Set the drag container. options.dragContainer = dragContainer; } @@ -3873,14 +3777,16 @@ * @param globalMap - The globalMap. */ function setDragSort(options, globalMap) { - var dragSort = options.dragSort; // Parse this options only if it is an object. + var dragSort = options.dragSort; + // Parse this options only if it is an object. + if (!dragSort || _typeof(dragSort) !== 'object') return; + // Check the options. + invariant(typeof dragSort.groupId === 'string', 'You must provide a string as groupId'); - if (!dragSort || _typeof$1(dragSort) !== 'object') return; // Check the options. - - invariant(typeof dragSort.groupId === 'string', 'You must provide a string as groupId'); // The group, its reference doesn't change. - - var group = globalMap.getGroup(dragSort.groupId); // dragSort method. + // The group, its reference doesn't change. + var group = globalMap.getGroup(dragSort.groupId); + // dragSort method. options.dragSort = function () { return group; }; @@ -3895,120 +3801,123 @@ * @param options - The grid options. */ function setDragStartPredicate(options) { - var dragStartPredicate = options.dragStartPredicate; // Default predicate. + var dragStartPredicate = options.dragStartPredicate; - var defaultStartPredicate = getDefaultStartPredicate(dragStartPredicate); // Wrap the method. + // Default predicate. + var defaultStartPredicate = getDefaultStartPredicate(dragStartPredicate); + // Wrap the method. options.dragStartPredicate = function (item, event) { if (!getDecoration(item.getGrid()).dragEnabled) return false; if (isDecorated(item) && getDecoration(item).draggable === false) return false; return defaultStartPredicate(item, event); }; } + /** * Given the dragStartPredicate option return the default method. * * @param dragStartPredicate - The dragStartPredicate option. * @returns - The defaultStartPredicate method. */ - function getDefaultStartPredicate(dragStartPredicate) { return typeof dragStartPredicate === 'function' ? dragStartPredicate : function (item, event) { - return Muuri__default['default'].ItemDrag.defaultStartPredicate(item, event, dragStartPredicate); + return Muuri__default["default"].ItemDrag.defaultStartPredicate(item, event, dragStartPredicate); }; } var _excluded = ["children", "id", "groupIds", "gridProps", "filter", "sort", "sortOptions", "addOptions", "propsToData", "onSend", "onDragStart", "onDragEnd", "onFilter", "onSort", "onMount", "onUnmount", "forceSync", "dragFixed", "dragEnabled", "instantLayout"]; + function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } + function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } - function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - - function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - + // Muuri component. var MuuriComponent = /*#__PURE__*/React.forwardRef(function MuuriComponent(_ref, muuriRef) { var children = _ref.children, - id = _ref.id, - groupIds = _ref.groupIds, - gridProps = _ref.gridProps, - filter = _ref.filter, - sort = _ref.sort, - sortOptions = _ref.sortOptions, - addOptions = _ref.addOptions, - propsToData = _ref.propsToData, - onSend = _ref.onSend, - onDragStart = _ref.onDragStart, - onDragEnd = _ref.onDragEnd, - onFilter = _ref.onFilter, - onSort = _ref.onSort, - onMount = _ref.onMount, - onUnmount = _ref.onUnmount, - forceSync = _ref.forceSync, - dragFixed = _ref.dragFixed, - dragEnabled = _ref.dragEnabled, - instantLayout = _ref.instantLayout, - options = _objectWithoutProperties(_ref, _excluded); - + id = _ref.id, + groupIds = _ref.groupIds, + gridProps = _ref.gridProps, + filter = _ref.filter, + sort = _ref.sort, + sortOptions = _ref.sortOptions, + addOptions = _ref.addOptions, + propsToData = _ref.propsToData, + onSend = _ref.onSend, + onDragStart = _ref.onDragStart, + onDragEnd = _ref.onDragEnd, + onFilter = _ref.onFilter, + onSort = _ref.onSort, + onMount = _ref.onMount, + onUnmount = _ref.onUnmount, + forceSync = _ref.forceSync, + dragFixed = _ref.dragFixed, + dragEnabled = _ref.dragEnabled, + instantLayout = _ref.instantLayout, + options = _objectWithoutProperties(_ref, _excluded); // Generate the Muuri instance. var grid = useMemoized(function () { // Remove the standard option '*'. // @ts-ignore - options.items = []; // Muuri (0.9.0) generate the "ItemDrag" instances only if + options.items = []; + // Muuri (0.9.0) generate the "ItemDrag" instances only if // drag is enabled. These instances do not handle scrolling well on touch devices, // so we only create these instances if drag-and-drop have to be used // (assuming that a boolean is passed to the prop instead of the default value "null"). // The enabling / disabling of the drag is managed in dragStartPredicate. // @ts-ignore - - options.dragEnabled = dragEnabled !== null; // Allow the drag container to be a React.Ref. - - setDragContainer(options); // Allow the option to be an object ({ groupId }). - - setDragSort(options, muuriMap); // Allow the target elements to be React.Ref. - - setDragAutoScroll(options); // Allow enabling / disabling the drag-and-drop. - - setDragStartPredicate(options); // Generate the instance. - - var grid = getInstance(options); // Add the instance to the map. - - if (id) muuriMap.set(grid, id); // Add the decoration. - + options.dragEnabled = dragEnabled !== null; + + // Allow the drag container to be a React.Ref. + setDragContainer(options); + // Allow the option to be an object ({ groupId }). + setDragSort(options, muuriMap); + // Allow the target elements to be React.Ref. + setDragAutoScroll(options); + // Allow enabling / disabling the drag-and-drop. + setDragStartPredicate(options); + + // Generate the instance. + var grid = getInstance(options); + + // Add the instance to the map. + if (id) muuriMap.set(grid, id); + // Add the decoration. addDecoration(grid, { id: id - }); // Set the ref. - + }); + // Set the ref. handleRef(muuriRef, grid); return grid; }); // eslint-disable-line - // On unmount effect. + // On unmount effect. React.useEffect(function () { // Clean-up. return function () { // Unset the ref. - handleRef(muuriRef, null); // Remove the decorations. - - removeDecorations(grid); // Remove the instance from the map. - - if (id) muuriMap["delete"](id); // Destroy the instace - + handleRef(muuriRef, null); + // Remove the decorations. + removeDecorations(grid); + // Remove the instance from the map. + if (id) muuriMap["delete"](id); + // Destroy the instace grid.destroy(); }; }, []); // eslint-disable-line - // Allow the groupIds to be changed. + // Allow the groupIds to be changed. useInstantEffect(function () { // decorate the instance addDecoration(grid, { groupIds: groupIds - }); // Add the instance to the groups. - + }); + // Add the instance to the groups. if (groupIds) { groupIds.forEach(function (groupId) { muuriMap.setGroup(grid, groupId); }); - } // Clean-up. - + } + // Clean-up. return function () { // Remove the instance from the groups. if (groupIds) { @@ -4017,9 +3926,10 @@ }); } }; - }, groupIds || []); // Render. + }, groupIds || []); - return /*#__PURE__*/React__default['default'].createElement(GridComponent, { + // Render. + return /*#__PURE__*/React__default["default"].createElement(GridComponent, { grid: grid, gridProps: gridProps, filter: filter, @@ -4039,93 +3949,98 @@ dragEnabled: dragEnabled, instantLayout: instantLayout }, children); - }); // Proptypes. + }); + // Proptypes. MuuriComponent.propTypes = { - id: propTypes.string, - groupIds: propTypes.arrayOf(propTypes.string.isRequired), - showDuration: propTypes.number, - showEasing: propTypes.string, - hideDuration: propTypes.number, - hideEasing: propTypes.string, - visibleStyles: propTypes.shape({}), - hiddenStyles: propTypes.shape({}), + id: PropTypes.string, + groupIds: PropTypes.arrayOf(PropTypes.string.isRequired), + showDuration: PropTypes.number, + showEasing: PropTypes.string, + hideDuration: PropTypes.number, + hideEasing: PropTypes.string, + visibleStyles: PropTypes.shape({}), + hiddenStyles: PropTypes.shape({}), // @ts-ignore - layout: propTypes.oneOfType([propTypes.func, propTypes.exact({ - fillGaps: propTypes.bool, - horizontal: propTypes.bool, - alignRight: propTypes.bool, - alignBottom: propTypes.bool, - rounding: propTypes.bool + layout: PropTypes.oneOfType([PropTypes.func, PropTypes.exact({ + fillGaps: PropTypes.bool, + horizontal: PropTypes.bool, + alignRight: PropTypes.bool, + alignBottom: PropTypes.bool, + rounding: PropTypes.bool })]), - layoutOnResize: propTypes.oneOfType([propTypes.bool, propTypes.number]), - layoutDuration: propTypes.number, - layoutEasing: propTypes.string, - dragContainer: propTypes.oneOfType([propTypes.instanceOf(HTMLElement), propTypes.shape({ - current: propTypes.instanceOf(HTMLElement).isRequired + layoutOnResize: PropTypes.oneOfType([PropTypes.bool, PropTypes.number]), + layoutDuration: PropTypes.number, + layoutEasing: PropTypes.string, + dragContainer: PropTypes.oneOfType([PropTypes.instanceOf(HTMLElement), PropTypes.shape({ + current: PropTypes.instanceOf(HTMLElement).isRequired })]), // @ts-ignore - dragStartPredicate: propTypes.oneOfType([propTypes.func, propTypes.exact({ - distance: propTypes.number, - delay: propTypes.number, - handle: propTypes.oneOfType([propTypes.string, propTypes.bool]) + dragStartPredicate: PropTypes.oneOfType([PropTypes.func, PropTypes.exact({ + distance: PropTypes.number, + delay: PropTypes.number, + handle: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]) })]), - dragAxis: propTypes.oneOf(['x', 'y', 'xy']), - dragSort: propTypes.oneOfType([propTypes.bool, propTypes.func, propTypes.exact({ - groupId: propTypes.string.isRequired + dragAxis: PropTypes.oneOf(['x', 'y', 'xy']), + dragSort: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.exact({ + groupId: PropTypes.string.isRequired })]), // @ts-ignore - dragSortHeuristics: propTypes.exact({ - sortInterval: propTypes.number, - minDragDistance: propTypes.number, - minBounceBackAngle: propTypes.number + dragSortHeuristics: PropTypes.exact({ + sortInterval: PropTypes.number, + minDragDistance: PropTypes.number, + minBounceBackAngle: PropTypes.number }), // @ts-ignore - dragSortPredicate: propTypes.oneOfType([propTypes.func, propTypes.exact({ - action: propTypes.oneOf(['move', 'swap']), - migrateAction: propTypes.oneOf(['move', 'swap']), - threshold: propTypes.number + dragSortPredicate: PropTypes.oneOfType([PropTypes.func, PropTypes.exact({ + action: PropTypes.oneOf(['move', 'swap']), + migrateAction: PropTypes.oneOf(['move', 'swap']), + threshold: PropTypes.number })]), // @ts-ignore - dragRelease: propTypes.exact({ - duration: propTypes.number, - easing: propTypes.string, - useDragContainer: propTypes.bool + dragRelease: PropTypes.exact({ + duration: PropTypes.number, + easing: PropTypes.string, + useDragContainer: PropTypes.bool }), // @ts-ignore - dragCssProps: propTypes.exact({ - touchAction: propTypes.string, - userSelect: propTypes.string, - userDrag: propTypes.string, - tapHighlightColor: propTypes.string, - touchCallout: propTypes.string, - contentZooming: propTypes.string + dragCssProps: PropTypes.exact({ + touchAction: PropTypes.string, + userSelect: PropTypes.string, + userDrag: PropTypes.string, + tapHighlightColor: PropTypes.string, + touchCallout: PropTypes.string, + contentZooming: PropTypes.string }), // @ts-ignore - dragPlaceholder: propTypes.exact({ - enabled: propTypes.bool, - createElement: propTypes.func, - onCreate: propTypes.func, - onRemove: propTypes.func, - easing: propTypes.string, - duration: propTypes.number + dragPlaceholder: PropTypes.exact({ + enabled: PropTypes.bool, + createElement: PropTypes.func, + onCreate: PropTypes.func, + onRemove: PropTypes.func, + easing: PropTypes.string, + duration: PropTypes.number }), - containerClass: propTypes.string, - itemClass: propTypes.string, - itemVisibleClass: propTypes.string, - itemHiddenClass: propTypes.string, - itemPositioningClass: propTypes.string, - itemDraggingClass: propTypes.string, - itemReleasingClass: propTypes.string, - itemPlaceholderClass: propTypes.string - }; // Default props. - - MuuriComponent.defaultProps = _objectSpread(_objectSpread({}, Muuri__default['default'].defaultOptions), {}, { + containerClass: PropTypes.string, + itemClass: PropTypes.string, + itemVisibleClass: PropTypes.string, + itemHiddenClass: PropTypes.string, + itemPositioningClass: PropTypes.string, + itemDraggingClass: PropTypes.string, + itemReleasingClass: PropTypes.string, + itemPlaceholderClass: PropTypes.string + }; + + // Default props. + MuuriComponent.defaultProps = _objectSpread(_objectSpread({}, Muuri__default["default"].defaultOptions), {}, { dragEnabled: null - }); // Display name. + }); + // Display name. MuuriComponent.displayName = 'MuuriComponent'; + // The method return by the hook. + /** * The useData hook allow to set the data to the item in which the hook has been called. * It also returns the setter method. @@ -4136,18 +4051,20 @@ */ function useData(initialData, options) { var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); - invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); // Because of memoization, The identity of the function is guaranteed + // Because of memoization, The identity of the function is guaranteed // to be stable so it will be safe to omit them as a dependency. - var setData = useFunction(function (data, options) { // Check if the data is an object. - invariant(_typeof$1(data) === 'object', "The data must be an object, founded: ".concat(_typeof$1(data))); // Default options. - - options = options || useData.defaultOptions; // Set the data. + invariant(_typeof(data) === 'object', "The data must be an object, founded: ".concat(_typeof(data))); + // Default options. + options = options || useData.defaultOptions; + // Set the data. if (options.merge) { // Merge. var currentData = itemRefController.get('data') || {}; @@ -4156,15 +4073,16 @@ // Set. itemRefController.set('data', data); } - }); // Set the inital data. + }); - if (_typeof$1(initialData) === 'object') { + // Set the inital data. + if (_typeof(initialData) === 'object') { setData(initialData, options); } - return setData; - } // Default options. + } + // Default options. useData.defaultOptions = { merge: false }; @@ -4176,21 +4094,23 @@ * * @returns - If the item is being dragged. */ - function useDrag() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; - - var reRender = useRerender(); // Check if the hook is called inside an item. + eventController = _useItemContext.eventController; + var reRender = useRerender(); - invariant(eventController !== undefined, 'The useDrag hook can be used only inside an Item'); // Enable the event. + // Check if the hook is called inside an item. + invariant(eventController !== undefined, 'The useDrag hook can be used only inside an Item'); + // Enable the event. React.useEffect(function () { eventController.enableEvent('drag', reRender); }, [eventController, reRender]); return eventController.getPayload('drag') || false; } + // The method returned by the hook. + /** * The useDraggable hook allow to decide if the item (in which the hook has been called) * can be dragged or not. @@ -4200,9 +4120,9 @@ */ function useDraggable() { var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. - + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. invariant(itemRefController !== undefined, 'The useData hook can be used only inside an Item'); var setDraggable = useFunction(function (draggable) { // Set if the item can be dragged. @@ -4219,16 +4139,18 @@ */ function useGrid() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; - + eventController = _useItemContext.eventController; var gridContext = useGridContext(); - var reRender = useRerender(); // Check if the hook is called inside an item. + var reRender = useRerender(); - invariant(eventController !== undefined && gridContext.grid !== undefined, 'The useData hook can be used only inside an Item'); // The context is not updated when the hook is trigger - // so we need to get the updated instance from the eventController. + // Check if the hook is called inside an item. + invariant(eventController !== undefined && gridContext.grid !== undefined, 'The useData hook can be used only inside an Item'); - var grid = eventController.getPayload('send') || gridContext.grid; // Enable the event. + // The context is not updated when the hook is trigger + // so we need to get the updated instance from the eventController. + var grid = eventController.getPayload('send') || gridContext.grid; + // Enable the event. React.useEffect(function () { eventController.enableEvent('send', reRender); }, [eventController, reRender]); @@ -4239,6 +4161,8 @@ }; } + // The method returned by the hook. + /** * The useRefresh hook allow to notify the MuuriComponent that the * item dimensions are changed, so that it can update the layout. @@ -4248,22 +4172,21 @@ */ function useRefresh() { var deps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var _useGridContext = useGridContext(), - layoutController = _useGridContext.layoutController; - + layoutController = _useGridContext.layoutController; var _useItemContext = useItemContext(), - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. + itemRefController = _useItemContext.itemRefController; + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined && layoutController !== undefined, 'The useRefresh hook can be used only inside an Item'); - invariant(itemRefController !== undefined && layoutController !== undefined, 'The useRefresh hook can be used only inside an Item'); // Because of memoization, The identity of the function is guaranteed + // Because of memoization, The identity of the function is guaranteed // to be stable so it will be safe to omit it as a dependency. - var refresh = React.useCallback(function () { - if (!itemRefController.hasItem()) return; // Get the item. - - var item = itemRefController.getItem(); // If the component is rendering within the MuuriComponent. - + if (!itemRefController.hasItem()) return; + // Get the item. + var item = itemRefController.getItem(); + // If the component is rendering within the MuuriComponent. layoutController.refreshItem(item); }, [layoutController, itemRefController]); React.useEffect(function () { @@ -4279,21 +4202,23 @@ * * @returns - If the item is showing. */ - function useShow() { var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController; - - var reRender = useRerender(); // Check if the hook is called inside an item. + eventController = _useItemContext.eventController; + var reRender = useRerender(); - invariant(eventController !== undefined, 'The useShow hook can be used only inside an Item'); // Enable the event. + // Check if the hook is called inside an item. + invariant(eventController !== undefined, 'The useShow hook can be used only inside an Item'); + // Enable the event. React.useEffect(function () { eventController.enableEvent('show', reRender); }, [eventController, reRender]); return eventController.getPayload('show'); } + // The method returned by the hook. + /** * The useVisibility hook allow you to show/hide the item in which the hook has been called. * @@ -4301,26 +4226,29 @@ */ function useVisibility() { var _useGridContext = useGridContext(), - layoutController = _useGridContext.layoutController; - + layoutController = _useGridContext.layoutController; var _useItemContext = useItemContext(), - eventController = _useItemContext.eventController, - itemRefController = _useItemContext.itemRefController; // Check if the hook is called inside an item. - + eventController = _useItemContext.eventController, + itemRefController = _useItemContext.itemRefController; - invariant(itemRefController !== undefined && layoutController !== undefined && eventController !== undefined, 'The useData hook can be used only inside an Item'); // Set visibility. + // Check if the hook is called inside an item. + invariant(itemRefController !== undefined && layoutController !== undefined && eventController !== undefined, 'The useData hook can be used only inside an Item'); + // Set visibility. var setVisibility = useFunction(function (visible, options) { if (!itemRefController.hasItem()) return; - if (!!visible === eventController.getPayload('show')) return; // Default options. + if (!!visible === eventController.getPayload('show')) return; - options = options || useVisibility.defaultOptions; // Set the visibility. + // Default options. + options = options || useVisibility.defaultOptions; + // Set the visibility. layoutController.setItemVisibility(itemRefController.getItem(), visible, options.instant === true); }); return setVisibility; - } // Default options. + } + // Default options. useVisibility.defaultOptions = { instant: false }; @@ -4346,27 +4274,30 @@ */ function getResponsiveStyle(options) { // Check options. - invariant(_typeof$1(options) === 'object', 'You must define options'); // Check columns. + invariant(_typeof(options) === 'object', 'You must define options'); - invariant(typeof options.columns === 'number' && options.columns > 0 && options.columns <= 1, 'options.columns must be a number between 0 (excluded) and 1 (included)'); // Check height and ratio. + // Check columns. + invariant(typeof options.columns === 'number' && options.columns > 0 && options.columns <= 1, 'options.columns must be a number between 0 (excluded) and 1 (included)'); - invariant(typeof options.ratio === 'number' || typeof options.height === 'number' || typeof options.height === 'string', 'You must provide at least one option between height and ratio'); // Check that the height and the ratio options are not setted togheter. + // Check height and ratio. + invariant(typeof options.ratio === 'number' || typeof options.height === 'number' || typeof options.height === 'string', 'You must provide at least one option between height and ratio'); - invariant(typeof options.ratio !== 'number' || typeof options.height !== 'number' && typeof options.height !== 'string', 'You cannot provide both the height and the ratio options'); // The margin values. + // Check that the height and the ratio options are not setted togheter. + invariant(typeof options.ratio !== 'number' || typeof options.height !== 'number' && typeof options.height !== 'string', 'You cannot provide both the height and the ratio options'); + // The margin values. var _getResponsiveMargin = getResponsiveMargin(options.margin || '0px'), - margin = _getResponsiveMargin.margin, - mStatic = _getResponsiveMargin.mStatic, - mDynamic = _getResponsiveMargin.mDynamic; // The item width. - - + margin = _getResponsiveMargin.margin, + mStatic = _getResponsiveMargin.mStatic, + mDynamic = _getResponsiveMargin.mDynamic; + // The item width. var _getResponsiveWidth = getResponsiveWidth(options.columns, mStatic, mDynamic), - needCalc = _getResponsiveWidth.needCalc, - width = _getResponsiveWidth.width; // If ratio is used set The paddingTop + needCalc = _getResponsiveWidth.needCalc, + width = _getResponsiveWidth.width; + + // If ratio is used set The paddingTop // instad of the heght, the child element must // have "display: absolute". - - return options.ratio ? { width: needCalc ? "calc(".concat(width, ")") : width, paddingTop: getResponsivePaddingTop(width, options.ratio, needCalc), @@ -4382,6 +4313,7 @@ margin: margin }; } + /** * Get the responsive width. * @@ -4390,7 +4322,6 @@ * @param mDynamic - The dynamic margin. * @returns - The width. */ - function getResponsiveWidth(columns, mStatic, mDynamic) { var needCalc = mStatic !== 0; var rawWidth = columns * 100 - mDynamic; @@ -4400,6 +4331,7 @@ width: width }; } + /** * Get the responsive paddingTop. * @@ -4408,39 +4340,37 @@ * @param needCalc - If the width need to be surrounded by calc(). * @returns - The paddingTop. */ - - function getResponsivePaddingTop(width, ratio, needCalc) { return needCalc ? "calc((".concat(width, ") / ").concat(ratio, ")") : "".concat(parseFloat(width) / ratio, "%"); } + /** * Get the fixed height. * * @param height - The mixed height. * @returns - The height string. */ - - function getFixedHeight(height) { return typeof height === 'number' ? "".concat(height, "px") : height; } + /** * The responsive margin. * * @param margin - The margin. * @returns - The responsive margin. */ - - function getResponsiveMargin(margin) { if (typeof margin === 'number') margin = "".concat(margin, "px"); - var margins = margin.trim().split(' '); // Margin default values. + var margins = margin.trim().split(' '); + // Margin default values. var leftMargin = '0px'; var rightMargin = '0px'; var mDynamic = 0; - var mStatic = 0; // Get the values from the input. + var mStatic = 0; + // Get the values from the input. if (margins.length === 1) { leftMargin = rightMargin = margins[0]; } else if (margins.length === 2) { @@ -4450,9 +4380,9 @@ } else if (margins.length === 4) { leftMargin = margins[3]; rightMargin = margins[1]; - } // Set dynamic/static margins. - + } + // Set dynamic/static margins. if (leftMargin.indexOf('%') === -1) mStatic += parseFloat(leftMargin);else mDynamic += parseFloat(leftMargin); if (rightMargin.indexOf('%') === -1) mStatic += parseFloat(rightMargin);else mDynamic += parseFloat(rightMargin); return { @@ -4469,20 +4399,23 @@ * @returns - The style. */ function getStaticStyle(options) { - var style = getResponsiveStyle(options); // Check the options. + var style = getResponsiveStyle(options); - invariant('grid' in options, 'You mast pass the grid instance to get the static style.'); // The sizer element. + // Check the options. + invariant('grid' in options, 'You mast pass the grid instance to get the static style.'); - var sizerElement = options.grid.getSizerElement(); // Set the style in the sizer. + // The sizer element. + var sizerElement = options.grid.getSizerElement(); - Object.assign(sizerElement.style, style); // Get the style from the sizer. + // Set the style in the sizer. + Object.assign(sizerElement.style, style); + // Get the style from the sizer. var _window$getComputedSt = window.getComputedStyle(sizerElement), - width = _window$getComputedSt.width, - height = _window$getComputedSt.height, - paddingTop = _window$getComputedSt.paddingTop, - margin = _window$getComputedSt.margin; - + width = _window$getComputedSt.width, + height = _window$getComputedSt.height, + paddingTop = _window$getComputedSt.paddingTop, + margin = _window$getComputedSt.margin; return { width: width, height: height, @@ -4496,42 +4429,36 @@ } function _iterableToArrayLimit(arr, i) { - var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; - - if (_i == null) return; - var _arr = []; - var _n = true; - var _d = false; - - var _s, _e; - - try { - for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { + var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; + if (null != _i) { + var _s, + _e, + _x, + _r, + _arr = [], + _n = !0, + _d = !1; try { - if (!_n && _i["return"] != null) _i["return"](); + if (_x = (_i = _i.call(arr)).next, 0 === i) { + if (Object(_i) !== _i) return; + _n = !1; + } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); + } catch (err) { + _d = !0, _e = err; } finally { - if (_d) throw _e; + try { + if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return; + } finally { + if (_d) throw _e; + } } + return _arr; } - - return _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]; - } - + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } @@ -4568,53 +4495,42 @@ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - var hooksNames = ['useData', 'useDrag', 'useDraggable', 'useGrid', 'useRefresh', 'useShow', 'useVisibility']; // Handler type. + // Hook names. + var hooksNames = ['useData', 'useDrag', 'useDraggable', 'useGrid', 'useRefresh', 'useShow', 'useVisibility']; + + // Handler type. // Hook handlers. - var HooksHandlers = [['useData', - /* */ - getHandler('setData')], ['useDrag', - /* */ - getHandler('isDragging')], ['useDraggable', - /* */ - getHandler('setDraggable')], ['useGrid', - /* */ - getHandler('gridData')], ['useRefresh', - /* */ - getHandler('refresh')], ['useShow', - /* */ - getHandler('isShowing')], ['useVisibility', - /* */ - getHandler('setVisibility')]]; + var HooksHandlers = [['useData', /* */getHandler('setData')], ['useDrag', /* */getHandler('isDragging')], ['useDraggable', /* */getHandler('setDraggable')], ['useGrid', /* */getHandler('gridData')], ['useRefresh', /* */getHandler('refresh')], ['useShow', /* */getHandler('isShowing')], ['useVisibility', /* */getHandler('setVisibility')]]; + /** * Return the handler with the given key. * * @param key - The key. * @returns - The method. */ - function getHandler(key) { return function handler(payload) { return _defineProperty({}, key, payload); }; } + /** * Run all the handlers and merge all the payloads. * * @param hooksHandlers - The handlers. * @returns - The merged payload. */ - function getMerged(hooksHandlers) { return Object.assign.apply(Object, [{}].concat(_toConsumableArray(hooksHandlers.map(function (_ref2) { var _ref3 = _slicedToArray(_ref2, 2), - hookName = _ref3[0], - handler = _ref3[1]; - + hookName = _ref3[0], + handler = _ref3[1]; var payload = hooks[hookName](); return handler(payload); })))); } + /** * Item HOC for hooks. * @@ -4622,33 +4538,35 @@ * @param enabledHooks - The hooks to enable. * @returns - The wrapped component. */ - - function withHooks(Component, enabledHooks) { // There must be an array of hooks to enable. - invariant(Array.isArray(enabledHooks), 'An array of hooks name must be provided to wrap an item.'); // All the hooks must be valid. + invariant(Array.isArray(enabledHooks), 'An array of hooks name must be provided to wrap an item.'); + // All the hooks must be valid. enabledHooks.forEach(function (hookName) { invariant(hooksNames.includes(hookName), "Invalid item hook: ".concat(hookName)); - }); // There must be at least one hook to enable. + }); - invariant(enabledHooks.length !== 0, 'To wrap an item at least one hook must be provided.'); // Get the handlers array of the enabled hook. + // There must be at least one hook to enable. + invariant(enabledHooks.length !== 0, 'To wrap an item at least one hook must be provided.'); + // Get the handlers array of the enabled hook. var hooksHandlers = HooksHandlers.filter(function (_ref4) { var _ref5 = _slicedToArray(_ref4, 1), - hookName = _ref5[0]; - + hookName = _ref5[0]; return enabledHooks.includes(hookName); - }); // Return the HOC. + }); + // Return the HOC. return function WrappedItem(props) { // The hooks will run in the 'getMerged' method. - return /*#__PURE__*/React__default['default'].createElement(Component, _extends({}, props, getMerged(hooksHandlers))); + return /*#__PURE__*/React__default["default"].createElement(Component, _extends({}, props, getMerged(hooksHandlers))); }; } - var AutoScroller = Muuri__default['default'].AutoScroller; - var ItemDrag = Muuri__default['default'].ItemDrag; // Muuri-react exports. + // Muuri-exports. + var AutoScroller = Muuri__default["default"].AutoScroller; + var ItemDrag = Muuri__default["default"].ItemDrag; exports.AutoScroller = AutoScroller; exports.ChildrenController = ChildrenController; @@ -4686,4 +4604,4 @@ Object.defineProperty(exports, '__esModule', { value: true }); -}))); +})); diff --git a/dist/muuri-react.min.js b/dist/muuri-react.min.js index 16f2046..9db7473 100644 --- a/dist/muuri-react.min.js +++ b/dist/muuri-react.min.js @@ -6,7 +6,7 @@ * https://github.com/Paol-imi/muuri-react/blob/master/LICENSE * @license MIT */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("muuri"),require("react")):"function"==typeof define&&define.amd?define(["exports","muuri","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).MuuriReact={},e.Muuri,e.React)}(this,(function(e,t,n){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=r(t),i=r(n);function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var u="_component";function s(e){return!!e[u]}function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e,t){s(e)?Object.assign(e[u],t):e[u]=function(e){for(var t=1;te.length?e.length:n;r-1?o[r]=e:i.push(e)})),e.sort(Array.prototype.concat(o.filter((function(e){return!!e})),i),n)}(e,t,n)}function Ae(e){var t=e.children,r=e.gridProps,o=e.grid,a=e.filter,u=e.sort,l=e.sortOptions,d=e.addOptions,g=e.propsToData,h=e.onSend,m=e.onDragStart,v=e.onDragEnd,b=e.onFilter,C=e.onSort,O=e.onMount,_=e.onUnmount,S=e.forceSync,w=e.dragFixed,T=e.dragEnabled,R=e.instantLayout,E=Re((function(){return{gridRef:n.createRef(),gridClass:Ie(o),itemClasses:xe(o),childrenController:new be,fiberController:new de,itemAddController:new Q,itemRemoveController:new ce,layoutController:new fe,onUnmount:_,onDragStart:m,onDragEnd:v,onFilter:b,onSort:C,onSend:h}})),P={indicesToAdd:[],addedDOMItems:[],itemsToRemove:[],itemsToRefresh:[],itemsToShow:[],itemsToHide:[],hasAdded:!1,hasRemoved:!1,hasFiltered:!1,hasSorted:!1,hasRefreshed:!1,hasShown:!1,hasHidden:!1};n.useEffect((function(){return o.on("beforeSend",(function(e){var t=e.item,n=e.fromGrid,r=e.fromIndex;f(t).sentPayload||c(t,{sentPayload:{fromChildrenController:E.childrenController,fromFiberController:E.fiberController,fromGrid:n,fromIndex:r}})})).on("receive",(function(e){var t=e.item,n=e.toGrid,r=e.toIndex,i=E.childrenController,a=E.fiberController;if(t.isDragging()){c(t,{receivedPayload:{toChildrenController:i,toFiberController:a,toGrid:n,toIndex:r}})}else{var u=f(t).sentPayload;se(null!==u&&"object"===y(u));var s=u.fromChildrenController,l=u.fromFiberController;c(t,{sentPayload:null});var d=l.remove(t.getKey()),p=s.remove(d.index);a.append(d),i.append(p)}f(t).eventController.emitEvent("send",o)})).on("dragInit",(function(e,t){E.childrenController.incrementDragCounter(),f(e).eventController.emitEvent("drag",!0),E.onDragStart&&E.onDragStart(e,t)})).on("dragEnd",(function(e){var t=f(e).sentPayload,n=f(e).receivedPayload;if(t&&n){var r=t.fromChildrenController,o=t.fromFiberController,i=t.fromGrid,a=t.fromIndex,u=n.toChildrenController,s=n.toFiberController,l=n.toGrid,d=n.toIndex;if(c(e,{sentPayload:null,receivedPayload:null}),i!==l){se("function"==typeof E.onSend);var p=o.remove(e.getKey()),y=r.remove(p.index);s.append(p),u.append(y),E.onSend({key:f(e).key,fromGrid:i,fromIndex:a,fromId:f(i).id,fromGroupIds:f(i).groupIds,toGrid:l,toIndex:d,toId:f(l).id,toGroupIds:f(l).groupIds})}}})).on("dragReleaseEnd",(function(e){E.childrenController.decrementDragCounter(),f(e).eventController.emitEvent("drag",!1),E.onDragEnd&&E.onDragEnd(e)})).on("showStart",(function(e){s(e[0])&&e.forEach((function(e){var t=f(e).eventController;!0!==t.getPayload("show")&&t.emitEvent("show",!0)}))})).on("hideEnd",(function(e){e.forEach((function(e){var t=f(e).eventController;!1!==t.getPayload("show")&&t.emitEvent("show",!1)}))})).on("filter",(function(e,t){E.onFilter&&E.onFilter(e,t)})).on("sort",(function(e,t){E.onSort&&E.onSort(e,t)})),w&&o.on("dragInit",(function(e){var t=e.getElement();se(void 0!==t);var n=getComputedStyle(t),r=n.width,o=n.height,i=n.paddingTop;c(e,{dragWidth:t.style.width,dragHeight:t.style.height,dragPaddingTop:t.style.paddingTop}),t.style.width=r,t.style.height=o,t.style.paddingTop=i})).on("dragReleaseEnd",(function(e){var t=e.getElement();se(void 0!==t);var n=f(e),r=n.dragWidth,o=n.dragHeight,i=n.dragPaddingTop;t.style.width=r,t.style.height=o,t.style.paddingTop=i})),se(null!==E.gridRef.current),o._element=E.gridRef.current,function(e,t){var n=getComputedStyle(e).position;Se.includes(n)||(e.style.position=Se[0]),e.classList.add(t);var r=e.setAttribute.bind(e);e.setAttribute=function(n,o){"class"===n&&((e.getAttribute("class")||"").split(" ").includes(t)||(o="".concat(o," ").concat(t)));r(n,o)}}(E.gridRef.current,E.gridClass),function(e){var t=document.createElement("div");t.style.visibility="hidden",t.style.position="absolute",t.classList.add("grid-sizer"),c(e,{sizerElement:t});var n=e.getElement();0===n.children.length?n.appendChild(t):n.insertBefore(t,n.children[0])}(o),O&&O(o),function(){E.childrenController.destroy(),E.fiberController.destroy(),E.itemRemoveController.destroy(),E.itemAddController.destroy(),E.layoutController.destroy()}}),[]),E.childrenController.useInit(t),E.fiberController.useInit(E.gridRef),E.itemRemoveController.useInit(),E.itemAddController.useInit(),E.layoutController.useInit();var I=Te([a]),j=Te([u,l]);n.useEffect((function(){c(o,{dragEnabled:T}),P.indicesToAdd=E.childrenController.getIndicesToAdd(),P.addedDOMItems=E.fiberController.getStateNodes(P.indicesToAdd),P.itemsToRemove=E.itemRemoveController.getItemsToRemove(),P.itemsToRefresh=E.layoutController.getItemsToRefresh(),P.itemsToShow=E.layoutController.getItemsToShow(),P.itemsToHide=E.layoutController.getItemsToHide(),E.onUnmount=_,E.onDragStart=m,E.onDragEnd=v,E.onFilter=b,E.onSort=C,E.onSend=h})),n.useEffect((function(){if(P.itemsToRemove.length&&(!function(e,t){e.remove(t,{layout:!1,removeElements:!1})}(o,P.itemsToRemove),P.hasRemoved=!0),P.indicesToAdd.length){!function(e,t,n,r,o){for(var i=0;i=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}Ae.propTypes={grid:L.object.isRequired,gridProps:L.object,filter:L.oneOfType([L.string,L.func]),sort:L.oneOfType([L.string,L.func,L.arrayOf(L.string)]),sortOptions:L.exact({descending:L.bool}),addOptions:L.exact({show:L.bool}),onSend:L.func,onDragStart:L.func,onDragEnd:L.func,onFilter:L.func,onSort:L.func,onMount:L.func,onUnmount:L.func,forceSync:L.bool,dragFixed:L.bool,dragEnabled:L.bool,instantLayout:L.bool},Ae.defaultProps={gridProps:{},addOptions:{show:!0},sortOptions:{descending:!1},forceSync:!1,dragFixed:!1,dragEnabled:!1,instantLayout:!1},Ae.displayName="GridComponent";var Ge=function(){function e(){K(this,e),a(this,"_idMap",new Map),a(this,"_groupMap",new Map)}return Z(e,[{key:"get",value:function(e){return this._idMap.get(e)||null}},{key:"getGroup",value:function(e){var t=this._groupMap.get(e);if(t)return t;var n=[];return this._groupMap.set(e,n),n}},{key:"getAll",value:function(){return Array.from(this._idMap.values())}},{key:"set",value:function(e,t){return this._idMap.set(t,e),this}},{key:"setGroup",value:function(e,t){var n=this._groupMap.get(t);return n?n.push(e):this._groupMap.set(t,[e]),this}},{key:"delete",value:function(e){return this._idMap.delete(e),this}},{key:"deleteGroup",value:function(e,t){var n=this._groupMap.get(t);if(n){var r=n.indexOf(e);r>-1&&n.splice(r,1)}return this}},{key:"clear",value:function(){return this._idMap.clear(),this._groupMap.clear(),this}}]),e}(),He=new Ge;function $e(e,t){e&&("function"==typeof e?e(t):"current"in e&&(e.current=t))}function qe(e){return e instanceof HTMLElement||e instanceof window.constructor}function Le(e){var t=function(e){return"function"==typeof e?e:function(t,n){return o.default.ItemDrag.defaultStartPredicate(t,n,e)}}(e.dragStartPredicate);e.dragStartPredicate=function(e,n){return!!f(e.getGrid()).dragEnabled&&((!s(e)||!1!==f(e).draggable)&&t(e,n))}}var ze=["children","id","groupIds","gridProps","filter","sort","sortOptions","addOptions","propsToData","onSend","onDragStart","onDragEnd","onFilter","onSort","onMount","onUnmount","forceSync","dragFixed","dragEnabled","instantLayout"];function Ne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ve(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:[],t=V(),r=t.layoutController,o=W(),i=o.itemRefController;se(void 0!==i&&void 0!==r);var a=n.useCallback((function(){if(i.hasItem()){var e=i.getItem();r.refreshItem(e)}}),[r,i]);return n.useEffect((function(){a()}),e.concat(a)),a}function Je(){var e=W().eventController,t=Ee();return se(void 0!==e),n.useEffect((function(){e.enableEvent("show",t)}),[e,t]),e.getPayload("show")}function Qe(){var e=V().layoutController,t=W(),n=t.eventController,r=t.itemRefController;return se(void 0!==r&&void 0!==e&&void 0!==n),we((function(t,o){r.hasItem()&&!!t!==n.getPayload("show")&&(o=o||Qe.defaultOptions,e.setItemVisibility(r.getItem(),t,!0===o.instant))}))}Ue.propTypes={id:L.string,groupIds:L.arrayOf(L.string.isRequired),showDuration:L.number,showEasing:L.string,hideDuration:L.number,hideEasing:L.string,visibleStyles:L.shape({}),hiddenStyles:L.shape({}),layout:L.oneOfType([L.func,L.exact({fillGaps:L.bool,horizontal:L.bool,alignRight:L.bool,alignBottom:L.bool,rounding:L.bool})]),layoutOnResize:L.oneOfType([L.bool,L.number]),layoutDuration:L.number,layoutEasing:L.string,dragContainer:L.oneOfType([L.instanceOf(HTMLElement),L.shape({current:L.instanceOf(HTMLElement).isRequired})]),dragStartPredicate:L.oneOfType([L.func,L.exact({distance:L.number,delay:L.number,handle:L.oneOfType([L.string,L.bool])})]),dragAxis:L.oneOf(["x","y","xy"]),dragSort:L.oneOfType([L.bool,L.func,L.exact({groupId:L.string.isRequired})]),dragSortHeuristics:L.exact({sortInterval:L.number,minDragDistance:L.number,minBounceBackAngle:L.number}),dragSortPredicate:L.oneOfType([L.func,L.exact({action:L.oneOf(["move","swap"]),migrateAction:L.oneOf(["move","swap"]),threshold:L.number})]),dragRelease:L.exact({duration:L.number,easing:L.string,useDragContainer:L.bool}),dragCssProps:L.exact({touchAction:L.string,userSelect:L.string,userDrag:L.string,tapHighlightColor:L.string,touchCallout:L.string,contentZooming:L.string}),dragPlaceholder:L.exact({enabled:L.bool,createElement:L.func,onCreate:L.func,onRemove:L.func,easing:L.string,duration:L.number}),containerClass:L.string,itemClass:L.string,itemVisibleClass:L.string,itemHiddenClass:L.string,itemPositioningClass:L.string,itemDraggingClass:L.string,itemReleasingClass:L.string,itemPlaceholderClass:L.string},Ue.defaultProps=Ve(Ve({},o.default.defaultOptions),{},{dragEnabled:null}),Ue.displayName="MuuriComponent",Be.defaultOptions={merge:!1},Qe.defaultOptions={instant:!1};var Xe=Object.freeze({__proto__:null,useData:Be,useDrag:We,useDraggable:Ke,useGrid:Ye,useRefresh:Ze,useShow:Je,useVisibility:Qe});function et(e){se("object"===y(e)),se("number"==typeof e.columns&&e.columns>0&&e.columns<=1),se("number"==typeof e.ratio||"number"==typeof e.height||"string"==typeof e.height),se("number"!=typeof e.ratio||"number"!=typeof e.height&&"string"!=typeof e.height);var t,n=function(e){"number"==typeof e&&(e="".concat(e,"px"));var t=e.trim().split(" "),n="0px",r="0px",o=0,i=0;1===t.length?n=r=t[0]:2===t.length||3===t.length?n=r=t[1]:4===t.length&&(n=t[3],r=t[1]);-1===n.indexOf("%")?i+=parseFloat(n):o+=parseFloat(n);-1===r.indexOf("%")?i+=parseFloat(r):o+=parseFloat(r);return{margin:e,mStatic:i,mDynamic:o}}(e.margin||"0px"),r=n.margin,o=n.mStatic,i=n.mDynamic,a=function(e,t,n){var r=0!==t,o=100*e-n,i=r?"".concat(o,"% - ").concat(t,"px"):"".concat(o,"%");return{needCalc:r,width:i}}(e.columns,o,i),u=a.needCalc,s=a.width;return e.ratio?{width:u?"calc(".concat(s,")"):s,paddingTop:tt(s,e.ratio,u),height:"0px",borderWidth:"0px",margin:r}:{width:u?"calc(".concat(s,")"):s,paddingTop:"0px",height:(t=e.height,"number"==typeof t?"".concat(t,"px"):t),borderWidth:"0px",margin:r}}function tt(e,t,n){return n?"calc((".concat(e,") / ").concat(t,")"):"".concat(parseFloat(e)/t,"%")}function nt(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length?e.length:n;r-1?o[r]=e:i.push(e)})),e.sort(Array.prototype.concat(o.filter((function(e){return!!e})),i),n)}(e,t,n)}function Fe(e){var t=e.children,r=e.gridProps,o=e.grid,u=e.filter,s=e.sort,l=e.sortOptions,f=e.addOptions,g=e.propsToData,m=e.onSend,y=e.onDragStart,v=e.onDragEnd,b=e.onFilter,C=e.onSort,O=e.onMount,_=e.onUnmount,S=e.forceSync,w=e.dragFixed,T=e.dragEnabled,R=e.instantLayout,E=Ee((function(){return{gridRef:n.createRef(),gridClass:je(o),itemClasses:xe(o),childrenController:new Ce,fiberController:new pe,itemAddController:new ee,itemRemoveController:new fe,layoutController:new de,onUnmount:_,onDragStart:y,onDragEnd:v,onFilter:b,onSort:C,onSend:m}})),P={indicesToAdd:[],addedDOMItems:[],itemsToRemove:[],itemsToRefresh:[],itemsToShow:[],itemsToHide:[],hasAdded:!1,hasRemoved:!1,hasFiltered:!1,hasSorted:!1,hasRefreshed:!1,hasShown:!1,hasHidden:!1};n.useEffect((function(){return o.on("beforeSend",(function(e){var t=e.item,n=e.fromGrid,r=e.fromIndex;p(t).sentPayload||d(t,{sentPayload:{fromChildrenController:E.childrenController,fromFiberController:E.fiberController,fromGrid:n,fromIndex:r}})})).on("receive",(function(e){var t=e.item,n=e.toGrid,r=e.toIndex,i=E.childrenController,u=E.fiberController;if(t.isDragging()){d(t,{receivedPayload:{toChildrenController:i,toFiberController:u,toGrid:n,toIndex:r}})}else{var s=p(t).sentPayload;le(null!==s&&"object"===a(s));var l=s.fromChildrenController,c=s.fromFiberController;d(t,{sentPayload:null});var f=c.remove(t.getKey()),g=l.remove(f.index);u.append(f),i.append(g)}p(t).eventController.emitEvent("send",o)})).on("dragInit",(function(e,t){E.childrenController.incrementDragCounter(),p(e).eventController.emitEvent("drag",!0),E.onDragStart&&E.onDragStart(e,t)})).on("dragEnd",(function(e){var t=p(e).sentPayload,n=p(e).receivedPayload;if(t&&n){var r=t.fromChildrenController,o=t.fromFiberController,i=t.fromGrid,a=t.fromIndex,u=n.toChildrenController,s=n.toFiberController,l=n.toGrid,c=n.toIndex;if(d(e,{sentPayload:null,receivedPayload:null}),i!==l){le("function"==typeof E.onSend);var f=o.remove(e.getKey()),g=r.remove(f.index);s.append(f),u.append(g),E.onSend({key:p(e).key,fromGrid:i,fromIndex:a,fromId:p(i).id,fromGroupIds:p(i).groupIds,toGrid:l,toIndex:c,toId:p(l).id,toGroupIds:p(l).groupIds})}}})).on("dragReleaseEnd",(function(e){E.childrenController.decrementDragCounter(),p(e).eventController.emitEvent("drag",!1),E.onDragEnd&&E.onDragEnd(e)})).on("showStart",(function(e){c(e[0])&&e.forEach((function(e){var t=p(e).eventController;!0!==t.getPayload("show")&&t.emitEvent("show",!0)}))})).on("hideEnd",(function(e){e.forEach((function(e){var t=p(e).eventController;!1!==t.getPayload("show")&&t.emitEvent("show",!1)}))})).on("filter",(function(e,t){E.onFilter&&E.onFilter(e,t)})).on("sort",(function(e,t){E.onSort&&E.onSort(e,t)})),w&&o.on("dragInit",(function(e){var t=e.getElement();le(void 0!==t);var n=getComputedStyle(t),r=n.width,o=n.height,i=n.paddingTop;d(e,{dragWidth:t.style.width,dragHeight:t.style.height,dragPaddingTop:t.style.paddingTop}),t.style.width=r,t.style.height=o,t.style.paddingTop=i})).on("dragReleaseEnd",(function(e){var t=e.getElement();le(void 0!==t);var n=p(e),r=n.dragWidth,o=n.dragHeight,i=n.dragPaddingTop;t.style.width=r,t.style.height=o,t.style.paddingTop=i})),le(null!==E.gridRef.current),o._element=E.gridRef.current,function(e,t){var n=getComputedStyle(e).position;we.includes(n)||(e.style.position=we[0]),e.classList.add(t);var r=e.setAttribute.bind(e);e.setAttribute=function(n,o){"class"===n&&((e.getAttribute("class")||"").split(" ").includes(t)||(o="".concat(o," ").concat(t)));r(n,o)}}(E.gridRef.current,E.gridClass),function(e){var t=document.createElement("div");t.style.visibility="hidden",t.style.position="absolute",t.classList.add("grid-sizer"),d(e,{sizerElement:t});var n=e.getElement();0===n.children.length?n.appendChild(t):n.insertBefore(t,n.children[0])}(o),O&&O(o),function(){E.childrenController.destroy(),E.fiberController.destroy(),E.itemRemoveController.destroy(),E.itemAddController.destroy(),E.layoutController.destroy()}}),[]),E.childrenController.useInit(t),E.fiberController.useInit(E.gridRef),E.itemRemoveController.useInit(),E.itemAddController.useInit(),E.layoutController.useInit();var I=Re([u]),j=Re([s,l]);n.useEffect((function(){d(o,{dragEnabled:T}),P.indicesToAdd=E.childrenController.getIndicesToAdd(),P.addedDOMItems=E.fiberController.getStateNodes(P.indicesToAdd),P.itemsToRemove=E.itemRemoveController.getItemsToRemove(),P.itemsToRefresh=E.layoutController.getItemsToRefresh(),P.itemsToShow=E.layoutController.getItemsToShow(),P.itemsToHide=E.layoutController.getItemsToHide(),E.onUnmount=_,E.onDragStart=y,E.onDragEnd=v,E.onFilter=b,E.onSort=C,E.onSend=m})),n.useEffect((function(){if(P.itemsToRemove.length&&(!function(e,t){e.remove(t,{layout:!1,removeElements:!1})}(o,P.itemsToRemove),P.hasRemoved=!0),P.indicesToAdd.length){!function(e,t,n,r,o){for(var i=0;i=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}Fe.propTypes={grid:N.object.isRequired,gridProps:N.object,filter:N.oneOfType([N.string,N.func]),sort:N.oneOfType([N.string,N.func,N.arrayOf(N.string)]),sortOptions:N.exact({descending:N.bool}),addOptions:N.exact({show:N.bool}),onSend:N.func,onDragStart:N.func,onDragEnd:N.func,onFilter:N.func,onSort:N.func,onMount:N.func,onUnmount:N.func,forceSync:N.bool,dragFixed:N.bool,dragEnabled:N.bool,instantLayout:N.bool},Fe.defaultProps={gridProps:{},addOptions:{show:!0},sortOptions:{descending:!1},forceSync:!1,dragFixed:!1,dragEnabled:!1,instantLayout:!1},Fe.displayName="GridComponent";var He=function(){function e(){Z(this,e),s(this,"_idMap",new Map),s(this,"_groupMap",new Map)}return Q(e,[{key:"get",value:function(e){return this._idMap.get(e)||null}},{key:"getGroup",value:function(e){var t=this._groupMap.get(e);if(t)return t;var n=[];return this._groupMap.set(e,n),n}},{key:"getAll",value:function(){return Array.from(this._idMap.values())}},{key:"set",value:function(e,t){return this._idMap.set(t,e),this}},{key:"setGroup",value:function(e,t){var n=this._groupMap.get(t);return n?n.push(e):this._groupMap.set(t,[e]),this}},{key:"delete",value:function(e){return this._idMap.delete(e),this}},{key:"deleteGroup",value:function(e,t){var n=this._groupMap.get(t);if(n){var r=n.indexOf(e);r>-1&&n.splice(r,1)}return this}},{key:"clear",value:function(){return this._idMap.clear(),this._groupMap.clear(),this}}]),e}(),$e=new He;function qe(e,t){e&&("function"==typeof e?e(t):"current"in e&&(e.current=t))}function Le(e){return e instanceof HTMLElement||e instanceof window.constructor}function ze(e){var t=function(e){return"function"==typeof e?e:function(t,n){return o.default.ItemDrag.defaultStartPredicate(t,n,e)}}(e.dragStartPredicate);e.dragStartPredicate=function(e,n){return!!p(e.getGrid()).dragEnabled&&((!c(e)||!1!==p(e).draggable)&&t(e,n))}}var Ne=["children","id","groupIds","gridProps","filter","sort","sortOptions","addOptions","propsToData","onSend","onDragStart","onDragEnd","onFilter","onSort","onMount","onUnmount","forceSync","dragFixed","dragEnabled","instantLayout"];function Ve(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function Ue(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:[],t=B(),r=t.layoutController,o=Y(),i=o.itemRefController;le(void 0!==i&&void 0!==r);var a=n.useCallback((function(){if(i.hasItem()){var e=i.getItem();r.refreshItem(e)}}),[r,i]);return n.useEffect((function(){a()}),e.concat(a)),a}function Qe(){var e=Y().eventController,t=Pe();return le(void 0!==e),n.useEffect((function(){e.enableEvent("show",t)}),[e,t]),e.getPayload("show")}function Xe(){var e=B().layoutController,t=Y(),n=t.eventController,r=t.itemRefController;return le(void 0!==r&&void 0!==e&&void 0!==n),Te((function(t,o){r.hasItem()&&!!t!==n.getPayload("show")&&(o=o||Xe.defaultOptions,e.setItemVisibility(r.getItem(),t,!0===o.instant))}))}Be.propTypes={id:N.string,groupIds:N.arrayOf(N.string.isRequired),showDuration:N.number,showEasing:N.string,hideDuration:N.number,hideEasing:N.string,visibleStyles:N.shape({}),hiddenStyles:N.shape({}),layout:N.oneOfType([N.func,N.exact({fillGaps:N.bool,horizontal:N.bool,alignRight:N.bool,alignBottom:N.bool,rounding:N.bool})]),layoutOnResize:N.oneOfType([N.bool,N.number]),layoutDuration:N.number,layoutEasing:N.string,dragContainer:N.oneOfType([N.instanceOf(HTMLElement),N.shape({current:N.instanceOf(HTMLElement).isRequired})]),dragStartPredicate:N.oneOfType([N.func,N.exact({distance:N.number,delay:N.number,handle:N.oneOfType([N.string,N.bool])})]),dragAxis:N.oneOf(["x","y","xy"]),dragSort:N.oneOfType([N.bool,N.func,N.exact({groupId:N.string.isRequired})]),dragSortHeuristics:N.exact({sortInterval:N.number,minDragDistance:N.number,minBounceBackAngle:N.number}),dragSortPredicate:N.oneOfType([N.func,N.exact({action:N.oneOf(["move","swap"]),migrateAction:N.oneOf(["move","swap"]),threshold:N.number})]),dragRelease:N.exact({duration:N.number,easing:N.string,useDragContainer:N.bool}),dragCssProps:N.exact({touchAction:N.string,userSelect:N.string,userDrag:N.string,tapHighlightColor:N.string,touchCallout:N.string,contentZooming:N.string}),dragPlaceholder:N.exact({enabled:N.bool,createElement:N.func,onCreate:N.func,onRemove:N.func,easing:N.string,duration:N.number}),containerClass:N.string,itemClass:N.string,itemVisibleClass:N.string,itemHiddenClass:N.string,itemPositioningClass:N.string,itemDraggingClass:N.string,itemReleasingClass:N.string,itemPlaceholderClass:N.string},Be.defaultProps=Ue(Ue({},o.default.defaultOptions),{},{dragEnabled:null}),Be.displayName="MuuriComponent",We.defaultOptions={merge:!1},Xe.defaultOptions={instant:!1};var et=Object.freeze({__proto__:null,useData:We,useDrag:Ke,useDraggable:Ye,useGrid:Ze,useRefresh:Je,useShow:Qe,useVisibility:Xe});function tt(e){le("object"===a(e)),le("number"==typeof e.columns&&e.columns>0&&e.columns<=1),le("number"==typeof e.ratio||"number"==typeof e.height||"string"==typeof e.height),le("number"!=typeof e.ratio||"number"!=typeof e.height&&"string"!=typeof e.height);var t,n=function(e){"number"==typeof e&&(e="".concat(e,"px"));var t=e.trim().split(" "),n="0px",r="0px",o=0,i=0;1===t.length?n=r=t[0]:2===t.length||3===t.length?n=r=t[1]:4===t.length&&(n=t[3],r=t[1]);-1===n.indexOf("%")?i+=parseFloat(n):o+=parseFloat(n);-1===r.indexOf("%")?i+=parseFloat(r):o+=parseFloat(r);return{margin:e,mStatic:i,mDynamic:o}}(e.margin||"0px"),r=n.margin,o=n.mStatic,i=n.mDynamic,u=function(e,t,n){var r=0!==t,o=100*e-n,i=r?"".concat(o,"% - ").concat(t,"px"):"".concat(o,"%");return{needCalc:r,width:i}}(e.columns,o,i),s=u.needCalc,l=u.width;return e.ratio?{width:s?"calc(".concat(l,")"):l,paddingTop:nt(l,e.ratio,s),height:"0px",borderWidth:"0px",margin:r}:{width:s?"calc(".concat(l,")"):l,paddingTop:"0px",height:(t=e.height,"number"==typeof t?"".concat(t,"px"):t),borderWidth:"0px",margin:r}}function nt(e,t,n){return n?"calc((".concat(e,") / ").concat(t,")"):"".concat(parseFloat(e)/t,"%")}function rt(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n; gridProps: PropTypes.Requireable; - filter: PropTypes.Requireable any)>; - sort: PropTypes.Requireable any) | (string | null | undefined)[]>; + filter: PropTypes.Requireable any) | null | undefined>>; + sort: PropTypes.Requireable any) | (string | null | undefined)[] | null | undefined>>; sortOptions: PropTypes.Requireable; }>>>; diff --git a/dist/types/components/itemComponent.d.ts b/dist/types/components/itemComponent.d.ts index 7ba15c5..2e87f79 100644 --- a/dist/types/components/itemComponent.d.ts +++ b/dist/types/components/itemComponent.d.ts @@ -9,7 +9,7 @@ export declare namespace ItemComponent { itemClasses: PropTypes.Validator; propsToData: PropTypes.Requireable<(...args: any[]) => any>; children: PropTypes.Validator; - grid: PropTypes.Validator; + grid: PropTypes.Validator<{}>; }; var displayName: string; } diff --git a/dist/types/contexts/gridContext.d.ts b/dist/types/contexts/gridContext.d.ts index a35faf1..1724ebd 100644 --- a/dist/types/contexts/gridContext.d.ts +++ b/dist/types/contexts/gridContext.d.ts @@ -1,7 +1,7 @@ /// import type { DecoratedGrid } from '../interfaces'; import type { LayoutController } from '../controllers'; -export declare type GridContextValue = { +export type GridContextValue = { grid: DecoratedGrid; layoutController: LayoutController; }; diff --git a/dist/types/contexts/itemContext.d.ts b/dist/types/contexts/itemContext.d.ts index 0d6b743..f94dc9e 100644 --- a/dist/types/contexts/itemContext.d.ts +++ b/dist/types/contexts/itemContext.d.ts @@ -1,6 +1,6 @@ /// import type { ItemRefController, EventController } from '../controllers'; -export declare type ItemContextValue = { +export type ItemContextValue = { itemRefController: ItemRefController; eventController: EventController; }; diff --git a/dist/types/hooks/useData.d.ts b/dist/types/hooks/useData.d.ts index 4e978c8..4690c64 100644 --- a/dist/types/hooks/useData.d.ts +++ b/dist/types/hooks/useData.d.ts @@ -1,5 +1,5 @@ -export declare type SetDataMethod = (data: object, options?: UseDataOptions) => void; -export declare type UseDataOptions = { +export type SetDataMethod = (data: object, options?: UseDataOptions) => void; +export type UseDataOptions = { /** If the data have to be merged with the old one. */ merge?: boolean; }; diff --git a/dist/types/hooks/useDraggable.d.ts b/dist/types/hooks/useDraggable.d.ts index 0f8c1b3..68114dc 100644 --- a/dist/types/hooks/useDraggable.d.ts +++ b/dist/types/hooks/useDraggable.d.ts @@ -1,4 +1,4 @@ -export declare type SetDraggableMethod = (draggable: boolean) => void; +export type SetDraggableMethod = (draggable: boolean) => void; /** * The useDraggable hook allow to decide if the item (in which the hook has been called) * can be dragged or not. diff --git a/dist/types/hooks/useGrid.d.ts b/dist/types/hooks/useGrid.d.ts index 1339fec..c2deb4b 100644 --- a/dist/types/hooks/useGrid.d.ts +++ b/dist/types/hooks/useGrid.d.ts @@ -1,5 +1,5 @@ import type { DecoratedGrid } from '../interfaces'; -export declare type GridData = { +export type GridData = { id?: string; groupIds?: string[]; grid: DecoratedGrid; diff --git a/dist/types/hooks/useRefresh.d.ts b/dist/types/hooks/useRefresh.d.ts index 3872f86..fe6c760 100644 --- a/dist/types/hooks/useRefresh.d.ts +++ b/dist/types/hooks/useRefresh.d.ts @@ -1,4 +1,4 @@ -export declare type RefreshMethod = () => void; +export type RefreshMethod = () => void; /** * The useRefresh hook allow to notify the MuuriComponent that the * item dimensions are changed, so that it can update the layout. diff --git a/dist/types/hooks/useVisibility.d.ts b/dist/types/hooks/useVisibility.d.ts index 8ee3eef..3b8b0ec 100644 --- a/dist/types/hooks/useVisibility.d.ts +++ b/dist/types/hooks/useVisibility.d.ts @@ -1,5 +1,5 @@ -export declare type SetVisibilityMethod = (visible: boolean, options?: UseVisibilityOptions) => void; -export declare type UseVisibilityOptions = { +export type SetVisibilityMethod = (visible: boolean, options?: UseVisibilityOptions) => void; +export type UseVisibilityOptions = { /** If the animation should be skipped. */ instant?: boolean; }; diff --git a/dist/types/interfaces/fibers.d.ts b/dist/types/interfaces/fibers.d.ts index 3e5cbf1..563b76a 100644 --- a/dist/types/interfaces/fibers.d.ts +++ b/dist/types/interfaces/fibers.d.ts @@ -1,8 +1,8 @@ import type ReactReconciler from 'react-reconciler'; /** Flag type. */ -export declare type Flag = '0' | '1'; +export type Flag = '0' | '1'; /** Use this file as the only source for fibers. */ -export declare type Fiber = ReactReconciler.Fiber; +export type Fiber = ReactReconciler.Fiber; /** The fiber of the item element. */ export interface ItemElementFiber extends Fiber { stateNode: HTMLElement; diff --git a/dist/types/interfaces/muuriComponent.d.ts b/dist/types/interfaces/muuriComponent.d.ts index 4f2b003..ac65338 100644 --- a/dist/types/interfaces/muuriComponent.d.ts +++ b/dist/types/interfaces/muuriComponent.d.ts @@ -71,23 +71,23 @@ export interface GridProps { itemPlaceholderClass?: GridOptions['itemPlaceholderClass']; } /** Maybe ref type. */ -export declare type MaybeRef = RefObject | T; +export type MaybeRef = RefObject | T; /** DragStartPredicate function type. */ -export declare type DecoratedDragStartPredicate = (item: DecoratedItem, event: DraggerStartEvent | DraggerMoveEvent | DraggerEndEvent | DraggerCancelEvent) => boolean | undefined; +export type DecoratedDragStartPredicate = (item: DecoratedItem, event: DraggerStartEvent | DraggerMoveEvent | DraggerEndEvent | DraggerCancelEvent) => boolean | undefined; /** DragSort function type. */ -export declare type DecoratedDragSortGetter = (this: DecoratedGrid, item: DecoratedItem) => DecoratedGrid[] | null | void | undefined; +export type DecoratedDragSortGetter = (this: DecoratedGrid, item: DecoratedItem) => DecoratedGrid[] | null | void | undefined; /** DragSort object type. */ -export declare type DecoratedDragSort = { +export type DecoratedDragSort = { groupId: string; }; /** DragSortPredicate function type. */ -export declare type DecoratedDragSortPredicate = (item: DecoratedItem, e: DraggerEvent) => { +export type DecoratedDragSortPredicate = (item: DecoratedItem, e: DraggerEvent) => { index: number; grid: DecoratedGrid; action?: 'move' | 'swap'; }; /** DragPlaceholder type. */ -export declare type DragPlaceholder = { +export type DragPlaceholder = { /** Enabled. */ enabled?: boolean; /** Generator. */ @@ -98,31 +98,31 @@ export declare type DragPlaceholder = { onRemove?(item: DecoratedItem, placeholderElement: HTMLElement): void; }; /** DragAutoScroll element type. */ -export declare type DragAutoScrollElement = HTMLElement | Window; +export type DragAutoScrollElement = HTMLElement | Window; /** DragAutoScroll target element type. */ -export declare type DragAutoScrollTargetElement = RefObject | DragAutoScrollElement; +export type DragAutoScrollTargetElement = RefObject | DragAutoScrollElement; /** DragAutoScroll target element type. */ -export declare type DragAutoScrollTargetObject = { +export type DragAutoScrollTargetObject = { element: DragAutoScrollTargetElement; axis?: number | null; priority?: number | null; threshold?: number | null; }; /** DragAutoScroll target type. */ -export declare type DragAutoScrollTarget = DragAutoScrollTargetObject | DragAutoScrollTargetElement; +export type DragAutoScrollTarget = DragAutoScrollTargetObject | DragAutoScrollTargetElement; /** DragAutoScrollOnStart type. */ -export declare type DragAutoScrollOnStart = (item: DecoratedItem, scrollElement: DragAutoScrollElement, scrollDirection: number) => void; +export type DragAutoScrollOnStart = (item: DecoratedItem, scrollElement: DragAutoScrollElement, scrollDirection: number) => void; /** DragAutoScrollOnStop type. */ -export declare type DragAutoScrollOnStop = (item: DecoratedItem, scrollElement: DragAutoScrollElement, scrollDirection: number) => void; +export type DragAutoScrollOnStop = (item: DecoratedItem, scrollElement: DragAutoScrollElement, scrollDirection: number) => void; /** DragAutoScrollHandle type. */ -export declare type DragAutoScrollHandle = (item: DecoratedItem, itemClientX: number, itemClientY: number, itemWidth: number, itemHeight: number, pointerClientX: number, pointerClientY: number) => { +export type DragAutoScrollHandle = (item: DecoratedItem, itemClientX: number, itemClientY: number, itemWidth: number, itemHeight: number, pointerClientX: number, pointerClientY: number) => { left: number; top: number; width: number; height: number; }; /** DragAutoScrollSpeed type. */ -export declare type DragAutoScrollSpeed = (item: DecoratedItem, scrollElement: DragAutoScrollElement, scrollData: { +export type DragAutoScrollSpeed = (item: DecoratedItem, scrollElement: DragAutoScrollElement, scrollData: { direction: number; threshold: number; distance: number; diff --git a/package.json b/package.json index 9605b7b..4622164 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "muuri-react", - "version": "3.1.6", + "version": "4.0.0", "description": "The layout engine for React.", "main": "dist/muuri-react.cjs.js", "module": "dist/muuri-react.esm.js", @@ -14,7 +14,7 @@ "type-check": "tsc --noEmit", "type-check:watch": "npm run type-check -- --watch", "eslint": "./node_modules/.bin/eslint src/**/*.{js,jsx,ts,tsx} test/**/*.{js,jsx,ts,tsx}", - "prettier": "./node_modules/.bin/prettier --write **/*.{js,jsx,ts,tsx,md,mdx,json}", + "prettier": "./node_modules/.bin/prettier --write '**/*.{js,jsx,ts,tsx,md,mdx,json}'", "prepublishOnly": "npm run type-check && npm run test && npm run prettier && npm run build" }, "homepage": "https://paol-imi.github.io/muuri-react", @@ -47,11 +47,11 @@ "@rollup/plugin-commonjs": "^11.0.2", "@rollup/plugin-node-resolve": "^7.1.1", "@rollup/plugin-replace": "^2.3.1", - "@types/react": "^16.9.31", + "@types/react": "^18.0.2", "@types/react-reconciler": "^0.18.0", "@typescript-eslint/eslint-plugin": "^2.26.0", "@typescript-eslint/parser": "^2.26.0", - "@wojtekmaj/enzyme-adapter-react-17": "^0.6.3", + "@cfaester/enzyme-adapter-react-18": "~0.6.0", "enzyme": "^3.11.0", "eslint": "^6.8.0", "eslint-config-airbnb": "^18.0.1", @@ -65,16 +65,16 @@ "jest": "^25.2.6", "muuri": "^0.8.0", "prettier": "^2.0.4", - "react": "^17.0.2", - "react-dom": "^17.0.2", + "react": "^18.0.2", + "react-dom": "^18.0.2", "rollup": "^2.3.2", "rollup-plugin-babel": "^4.4.0", "rollup-plugin-terser": "^5.3.0", - "typescript": "^3.8.3" + "typescript": "^4.7.4" }, "peerDependencies": { - "muuri": "^0.8.0", - "react": "^17.0.2" + "muuri": ">=0.8.0", + "react": "^18.0.2" }, "dependencies": { "@babel/runtime": "^7.9.2", diff --git a/src/utils/decorators/addDecoration.ts b/src/utils/decorators/addDecoration.ts index eacb67f..01ec43f 100644 --- a/src/utils/decorators/addDecoration.ts +++ b/src/utils/decorators/addDecoration.ts @@ -13,6 +13,7 @@ export function addDecoration( decoration: Partial ): void { if (isDecorated(instance)) { + // @ts-ignore Object.assign(instance[key], decoration); } else { instance[key] = {...decoration}; diff --git a/test/filtering/test.js b/test/filtering/test.js index aac3c64..8133184 100644 --- a/test/filtering/test.js +++ b/test/filtering/test.js @@ -9,6 +9,8 @@ import { VisibilityResponsiveItem, } from './components'; +const flushPromises = () => new Promise((r) => setTimeout(r, 0)); + describe('How items are filtered', () => { test('The items are sorted correctly using a function as predicate (propsToData)', () => { const data = [{id: '2'}, {id: '1'}, {id: '3'}]; @@ -86,7 +88,7 @@ describe('How interact with filtering', () => { expect(DOMItems.findById('1').style.display).toBe('none'); }); - test('The filter has priority over the visibility of the item ', () => { + test('The filter has priority over the visibility of the item ', async () => { const setVisibilityRef = React.createRef(); const {wrapper, DOMItems} = mount( @@ -103,7 +105,7 @@ describe('How interact with filtering', () => { }); describe('How interact with filtering', () => { - test('The component re-render when its visibility change', () => { + test('The component re-render when its visibility change', async () => { const onRender = jest.fn(); const {wrapper} = mount( @@ -113,9 +115,15 @@ describe('How interact with filtering', () => { ); expect(onRender.mock.calls.length).toBe(1); - wrapper.setProps({filter: () => true}); - expect(onRender.mock.calls.length).toBe(2); - wrapper.setProps({filter: () => false}); - expect(onRender.mock.calls.length).toBe(3); + + wrapper.setProps({filter: () => true}, async () => { + await flushPromises(); + expect(onRender.mock.calls.length).toBe(2); + }); + + wrapper.setProps({filter: () => false}, async () => { + await flushPromises(); + expect(onRender.mock.calls.length).toBe(3); + }); }); }); diff --git a/test/setup.js b/test/setup.js index 14a971b..dc8b469 100644 --- a/test/setup.js +++ b/test/setup.js @@ -1,5 +1,5 @@ // setup file import {configure} from 'enzyme'; -import Adapter from '@wojtekmaj/enzyme-adapter-react-17'; +import Adapter from '@cfaester/enzyme-adapter-react-18'; configure({adapter: new Adapter()});