Liferay.Loader.define("layout-content-page-editor-web@2.0.166/page_editor/app/utils/dragAndDrop/useDragAndDrop", ['module', 'exports', 'require', 'frontend-js-web', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dnd', 'frontend-js-react-web$react-dnd-html5-backend', '../../components/CollectionItemContext', '../../components/Controls', '../../config/constants/layoutDataItemTypes', '../../store/index', './constants/dragDropTargetType', './constants/targetPosition', './defaultComputeHover', './toControlsId'], 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.useDragItem = useDragItem;
    exports.useDragSymbol = useDragSymbol;
    exports.useDropClear = useDropClear;
    exports.useDropTarget = useDropTarget;
    exports.DragAndDropContextProvider = exports.initialDragDrop = void 0;

    var _frontendJsWeb = require("frontend-js-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 _CollectionItemContext = require("../../components/CollectionItemContext");

    var _Controls = require("../../components/Controls");

    var _layoutDataItemTypes = require("../../config/constants/layoutDataItemTypes");

    var _index = require("../../store/index");

    var _dragDropTargetType = require("./constants/dragDropTargetType");

    var _targetPosition = require("./constants/targetPosition");

    var _defaultComputeHover = _interopRequireDefault(require("./defaultComputeHover"));

    var _toControlsId = _interopRequireDefault(require("./toControlsId"));

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

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

    var initialDragDrop = {
      dispatch: null,
      layoutDataRef: {
        current: {
          items: []
        }
      },
      state: {
        /**
         * Item that is being dragged
         */
        dropItem: null,

        /**
         * Target item where the item is being dragged true.
         * If elevate is true, dropTargetItem is the sibling
         * of drop item, otherwise is it's parent.
         */
        dropTargetItem: null,

        /**
         * When false, an "invalid drop" advise should be shown
         * to users.
         */
        droppable: true,

        /**
         * If true, dropTargetItem is the sibling of dropItem
         * and targetPosition determines the item index.
         */
        elevate: false,

        /**
         * Vertical position relative to dropTargetItem
         * (bottom, middle, top)
         */
        targetPositionWithMiddle: null,

        /**
         * Vertical position relative to dropTargetItem
         * (bottom, top)
         */
        targetPositionWithoutMiddle: null,

        /**
         * Source of the Drag and Drop status
         * (where the drag and drop status have been generated)
         */
        type: _dragDropTargetType.DRAG_DROP_TARGET_TYPE.INITIAL
      },
      targetRefs: new Map()
    };
    exports.initialDragDrop = initialDragDrop;

    var DragAndDropContext = /*#__PURE__*/_react.default.createContext(initialDragDrop);

    function useDragItem(sourceItem, onDragEnd) {
      var onBegin = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
      var getSourceItem = (0, _react.useCallback)(function () {
        return sourceItem;
      }, [sourceItem]);

      var _useContext = (0, _react.useContext)(DragAndDropContext),
          dispatch = _useContext.dispatch,
          layoutDataRef = _useContext.layoutDataRef,
          state = _useContext.state;

      var sourceRef = (0, _react.useRef)(null);

      var _useDrag = (0, _reactDnd.useDrag)({
        begin: function begin() {
          onBegin();
        },
        collect: function collect(monitor) {
          return {
            isDraggingSource: monitor.isDragging()
          };
        },
        end: function end() {
          computeDrop({
            dispatch: dispatch,
            layoutDataRef: layoutDataRef,
            onDragEnd: onDragEnd,
            state: state
          });
        },
        item: _objectSpread({
          getSourceItem: getSourceItem,
          icon: sourceItem.icon,
          id: sourceItem.itemId,
          name: sourceItem.name,
          type: sourceItem.type
        }, sourceItem.origin && {
          origin: sourceItem.origin
        })
      }),
          _useDrag2 = _slicedToArray(_useDrag, 3),
          isDraggingSource = _useDrag2[0].isDraggingSource,
          handlerRef = _useDrag2[1],
          previewRef = _useDrag2[2];

      (0, _react.useEffect)(function () {
        previewRef((0, _reactDndHtml5Backend.getEmptyImage)(), {
          captureDraggingState: true
        });
      }, [previewRef]);
      return {
        handlerRef: handlerRef,
        isDraggingSource: isDraggingSource,
        sourceRef: sourceRef
      };
    }

    function useDragSymbol(_ref, onDragEnd) {
      var icon = _ref.icon,
          label = _ref.label,
          type = _ref.type;
      var selectItem = (0, _Controls.useSelectItem)();
      var sourceItem = (0, _react.useMemo)(function () {
        return {
          icon: icon,
          isSymbol: true,
          itemId: label,
          name: label,
          type: type
        };
      }, [icon, label, type]);

      var _useDragItem = useDragItem(sourceItem, onDragEnd, function () {
        return selectItem(null);
      }),
          handlerRef = _useDragItem.handlerRef,
          isDraggingSource = _useDragItem.isDraggingSource,
          sourceRef = _useDragItem.sourceRef;

      return {
        isDraggingSource: isDraggingSource,
        sourceRef: function symbolRef(element) {
          sourceRef.current = element;
          handlerRef(element);
        }
      };
    }

    function useDropClear() {
      var _useContext2 = (0, _react.useContext)(DragAndDropContext),
          dispatch = _useContext2.dispatch;

      var _useDrop = (0, _reactDnd.useDrop)({
        accept: Object.values(_layoutDataItemTypes.LAYOUT_DATA_ITEM_TYPES),
        hover: function hover() {
          dispatch(initialDragDrop.state);
        }
      }),
          _useDrop2 = _slicedToArray(_useDrop, 2),
          dropClearRef = _useDrop2[1];

      return dropClearRef;
    }

    function useDropTarget(_targetItem) {
      var computeHover = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _defaultComputeHover.default;
      var collectionItemIndex = (0, _CollectionItemContext.useCollectionItemIndex)();

      var _useContext3 = (0, _react.useContext)(DragAndDropContext),
          dispatch = _useContext3.dispatch,
          layoutDataRef = _useContext3.layoutDataRef,
          state = _useContext3.state,
          targetRefs = _useContext3.targetRefs;

      var targetRef = (0, _react.useRef)(null);
      var targetItem = (0, _react.useMemo)(function () {
        return _objectSpread(_objectSpread({}, _targetItem), {}, {
          collectionItemIndex: collectionItemIndex
        });
      }, [_targetItem, collectionItemIndex]);
      var isOverTarget = state.dropTargetItem && targetItem && (0, _toControlsId.default)(layoutDataRef, state.dropTargetItem) === (0, _toControlsId.default)(layoutDataRef, targetItem);

      var _useDrop3 = (0, _reactDnd.useDrop)({
        accept: Object.values(_layoutDataItemTypes.LAYOUT_DATA_ITEM_TYPES),
        hover: function hover(_ref2, monitor) {
          var getSourceItem = _ref2.getSourceItem;

          if (getSourceItem().origin !== targetItem.origin) {
            return;
          }

          computeHover({
            dispatch: dispatch,
            layoutDataRef: layoutDataRef,
            monitor: monitor,
            sourceItem: getSourceItem(),
            targetItem: targetItem,
            targetRefs: targetRefs
          });
        }
      }),
          _useDrop4 = _slicedToArray(_useDrop3, 2),
          setDropTargetRef = _useDrop4[1];

      (0, _react.useEffect)(function () {
        var itemId = (0, _toControlsId.default)(layoutDataRef, targetItem);
        targetRefs.set(itemId, targetRef);
        return function () {
          targetRefs.delete(itemId);
        };
      }, [layoutDataRef, targetItem, targetRef, targetRefs]);
      var setTargetRef = (0, _react.useCallback)(function (element) {
        setDropTargetRef(element);
        targetRef.current = element;
      }, [setDropTargetRef]);
      return {
        canDropOverTarget: state.droppable,
        isOverTarget: isOverTarget,
        sourceItem: state.dropItem,
        targetPosition: state.targetPositionWithMiddle,
        targetRef: setTargetRef
      };
    }

    var DragAndDropContextProvider = function DragAndDropContextProvider(_ref3) {
      var children = _ref3.children;
      var layoutDataRef = (0, _react.useRef)({
        items: []
      });

      var _useReducer = (0, _react.useReducer)(function (state, nextState) {
        return Object.keys(state).some(function (key) {
          return state[key] !== nextState[key];
        }) ? nextState : state;
      }, initialDragDrop.state),
          _useReducer2 = _slicedToArray(_useReducer, 2),
          state = _useReducer2[0],
          reducerDispatch = _useReducer2[1];

      var targetRefs = (0, _react.useMemo)(function () {
        return new Map();
      }, []);
      var dispatch = (0, _react.useMemo)(function () {
        return (0, _frontendJsWeb.throttle)(reducerDispatch, 100);
      }, [reducerDispatch]);
      (0, _index.useSelector)(function (state) {
        layoutDataRef.current = state.layoutData;
        return null;
      });
      var dragAndDropContext = (0, _react.useMemo)(function () {
        return {
          dispatch: dispatch,
          layoutDataRef: layoutDataRef,
          state: state,
          targetRefs: targetRefs
        };
      }, [dispatch, layoutDataRef, state, targetRefs]);
      return (/*#__PURE__*/_react.default.createElement(DragAndDropContext.Provider, {
          value: dragAndDropContext
        }, children)
      );
    };

    exports.DragAndDropContextProvider = DragAndDropContextProvider;

    function computeDrop(_ref4) {
      var dispatch = _ref4.dispatch,
          layoutDataRef = _ref4.layoutDataRef,
          onDragEnd = _ref4.onDragEnd,
          state = _ref4.state;

      if (state.droppable && state.dropItem && state.dropTargetItem) {
        if (state.elevate) {
          var parentItem = layoutDataRef.current.items[state.dropTargetItem.parentId];
          var position = Math.min(parentItem.children.includes(state.dropItem.itemId) ? parentItem.children.length - 1 : parentItem.children.length, getSiblingPosition(state, parentItem));
          onDragEnd(parentItem.itemId, position);
        } else {
          var _position = state.dropTargetItem.children.includes(state.dropItem.itemId) ? state.dropTargetItem.children.length - 1 : state.dropTargetItem.children.length;

          onDragEnd(state.dropTargetItem.itemId, _position);
        }
      }

      dispatch(initialDragDrop.state);
    }

    function getSiblingPosition(state, parentItem) {
      var dropItemPosition = parentItem.children.indexOf(state.dropItem.itemId);
      var siblingPosition = parentItem.children.indexOf(state.dropTargetItem.itemId);

      if (state.targetPositionWithoutMiddle === _targetPosition.TARGET_POSITION.BOTTOM) {
        return siblingPosition + 1;
      } else if (dropItemPosition != -1 && dropItemPosition < siblingPosition && siblingPosition > 0) {
        return siblingPosition - 1;
      }

      return siblingPosition;
    }
    //# sourceMappingURL=useDragAndDrop.js.map
  }
});
//# sourceMappingURL=useDragAndDrop.js.map