Liferay.Loader.define("layout-admin-web@4.0.87/js/miller_columns/MillerColumns", ['module', 'exports', 'require', 'frontend-js-react-web', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dnd', 'frontend-js-react-web$react-dnd-html5-backend', './DragPreview', './MillerColumnsColumn'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = void 0;

    var _frontendJsReactWeb = require("frontend-js-react-web");

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _reactDnd = require("frontend-js-react-web$react-dnd");

    var _reactDndHtml5Backend = require("frontend-js-react-web$react-dnd-html5-backend");

    var _DragPreview = _interopRequireDefault(require("./DragPreview"));

    var _MillerColumnsColumn = _interopRequireDefault(require("./MillerColumnsColumn"));

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    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;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    var getItemsMap = function getItemsMap(columns) {
      var oldItems = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Map();
      var map = new Map();
      var parentId, parentKey;
      columns.forEach(function (column, columnIndex) {
        var childrenCount = 0;
        var newParentId, newParentKey;
        column.forEach(function (item) {
          childrenCount++;
          var oldItem = Array.from(oldItems.values()).find(function (oldItem) {
            return oldItem.id === item.id;
          });
          map.set(item.key, _objectSpread(_objectSpread({}, item), {}, {
            checked: oldItem ? oldItem.checked : false,
            columnIndex: columnIndex,
            parentId: parentId,
            parentKey: parentKey
          }));

          if (item.active && item.hasChild) {
            newParentId = item.id;
            newParentKey = item.key;
          }
        });

        if (parentKey) {
          map.set(parentKey, _objectSpread(_objectSpread({}, map.get(parentKey)), {}, {
            childrenCount: childrenCount
          }));
        }

        parentId = newParentId;
        parentKey = newParentKey;
      });
      return map;
    };

    var noop = function noop() {};

    var MillerColumns = function MillerColumns(_ref) {
      var actionHandlers = _ref.actionHandlers,
          _ref$initialColumns = _ref.initialColumns,
          initialColumns = _ref$initialColumns === void 0 ? [] : _ref$initialColumns,
          namespace = _ref.namespace,
          _ref$onColumnsChange = _ref.onColumnsChange,
          onColumnsChange = _ref$onColumnsChange === void 0 ? noop : _ref$onColumnsChange,
          _ref$onItemMove = _ref.onItemMove,
          onItemMove = _ref$onItemMove === void 0 ? noop : _ref$onItemMove,
          onItemStayHover = _ref.onItemStayHover,
          rtl = _ref.rtl,
          searchContainer = _ref.searchContainer;
      var ref = (0, _react.useRef)();

      var _useState = (0, _react.useState)(function () {
        return getItemsMap(initialColumns);
      }),
          _useState2 = _slicedToArray(_useState, 2),
          items = _useState2[0],
          setItems = _useState2[1]; // Transform items map into a columns-like array.


      var columns = (0, _react.useMemo)(function () {
        var columns = []; // eslint-disable-next-line no-for-of-loops/no-for-of-loops

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          var _loop = function _loop() {
            var item = _step.value;

            if (!columns[item.columnIndex]) {
              columns[item.columnIndex] = {
                items: [],
                parent: Array.from(items.values()).find(function (_item) {
                  return _item.id === item.parentId;
                })
              };
            }

            var column = columns[item.columnIndex];
            column.items.push(item);
          };

          for (var _iterator = items.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            _loop();
          } // Add empty column in the end if last column has an active item
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        var lastColumnActiveItem = columns[columns.length - 1].items.find(function (item) {
          return item.active;
        });

        if (lastColumnActiveItem && !lastColumnActiveItem.hasChild) {
          columns.push({
            items: [],
            parent: lastColumnActiveItem
          });
        }

        return columns;
      }, [items]);
      var previousColumnsValue = (0, _frontendJsReactWeb.usePrevious)(columns);
      var previousInitialColumnsValue = (0, _frontendJsReactWeb.usePrevious)(initialColumns);
      (0, _react.useEffect)(function () {
        if (previousInitialColumnsValue !== initialColumns) {
          setItems(getItemsMap(initialColumns, items));
        }
      }, [initialColumns, items, previousInitialColumnsValue]);
      (0, _react.useEffect)(function () {
        if (previousColumnsValue !== columns) {
          onColumnsChange(columns);
        }
      }, [columns, onColumnsChange, previousColumnsValue]);
      (0, _react.useEffect)(function () {
        if (ref.current) {
          ref.current.scrollLeft = ref.current.scrollWidth;
        }
      }, []);
      (0, _react.useEffect)(function () {
        if (searchContainer) {
          searchContainer.on('rowToggled', function (event) {
            setItems(function (oldItems) {
              var newItems = new Map(oldItems);
              newItems.forEach(function (item) {
                var itemNode = event.elements.allElements._nodes.find(function (node) {
                  return node.value === item.id;
                });

                if (itemNode) {
                  newItems.set(item.id, _objectSpread(_objectSpread({}, newItems.get(item.id)), {}, {
                    checked: itemNode.checked
                  }));
                }
              });
              return newItems;
            });
          });
        }
      }, [searchContainer]);

      var getMovedItems = function getMovedItems(sources, newParentId, targetIndex) {
        var targetColumnItems = Array.from(items.values()).filter(function (item) {
          return item.parentId === newParentId;
        }); // Return sources if target column has no items

        if (!targetColumnItems.length) {
          return sources.map(function (source, index) {
            return {
              plid: source.id,
              position: targetIndex + index
            };
          });
        } // Calculate all items of the target column that are changing position


        var movedItems = new Map();
        var previousSources = 0;
        targetColumnItems.forEach(function (item, index) {
          // Iterating on target position. Insert sources into movedItems
          if (index === targetIndex) {
            sources.forEach(function (source, sourceIndex) {
              movedItems.set(source.id, {
                plid: source.id,
                position: index - previousSources + sourceIndex
              });
            });
            previousSources = sources.length - previousSources;
          } // Iterating on a source. Don't insert it into movedItems but we
          // update previous sources counter


          if (sources.some(function (source) {
            return source.id === item.id;
          })) {
            previousSources = index < targetIndex ? previousSources + 1 : previousSources - 1;
          } // Insert item that is not a source into movedItems if it has a new
          // position
          else if (previousSources) {
              movedItems.set(item.id, {
                plid: item.id,
                position: index < targetIndex ? index - previousSources : index + previousSources
              });
            }
        }); // Insert sources into movedItems in the case we are targeting last
        // position of column so the loop does not reach it

        sources.forEach(function (source, index) {
          if (!movedItems.has(source.id)) {
            movedItems.set(source.id, {
              plid: source.id,
              position: targetIndex + index
            });
          }
        });
        return Array.from(movedItems.values());
      };

      var onItemDrop = function onItemDrop(sources, newParentId, targetIndex) {
        // Update checked items to keep them selected after updating items
        // with server response
        var newItems = new Map(items);
        sources.forEach(function (source) {
          if (source.checked) {
            newItems.set(source.id, source);
          }
        });
        setItems(newItems);
        onItemMove(getMovedItems(sources, newParentId, targetIndex), newParentId);
      };

      return (/*#__PURE__*/_react.default.createElement(_reactDnd.DndProvider, {
          backend: _reactDndHtml5Backend.HTML5Backend
        }, /*#__PURE__*/_react.default.createElement(_DragPreview.default, {
          rtl: rtl
        }), /*#__PURE__*/_react.default.createElement("div", {
          className: "bg-white miller-columns-row",
          ref: ref
        }, columns.map(function (column, index) {
          return (/*#__PURE__*/_react.default.createElement(_MillerColumnsColumn.default, {
              actionHandlers: actionHandlers,
              columnItems: column.items,
              columnsContainer: ref,
              items: items,
              key: index,
              namespace: namespace,
              onItemDrop: onItemDrop,
              onItemStayHover: onItemStayHover,
              parent: column.parent,
              rtl: rtl
            })
          );
        })))
      );
    };

    var _default = MillerColumns;
    exports.default = _default;
    //# sourceMappingURL=MillerColumns.js.map
  }
});
//# sourceMappingURL=MillerColumns.js.map