Liferay.Loader.define("layout-content-page-editor-web@2.0.102/page_editor/plugins/page-structure/components/StructureTreeNode", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/icon', 'frontend-js-react-web$classnames', 'frontend-js-react-web$prop-types', 'frontend-js-react-web$react', '../../../app/components/CollectionItemContext', '../../../app/components/Controls', '../../../app/components/layout-data-items/Collection', '../../../app/config/constants/itemActivationOrigins', '../../../app/config/constants/itemTypes', '../../../app/config/constants/layoutDataItemTypes', '../../../app/selectors/selectCanUpdatePageStructure', '../../../app/selectors/selectSegmentsExperienceId', '../../../app/store/index', '../../../app/thunks/deleteItem', '../../../app/thunks/moveItem', '../../../app/utils/checkDeepEqual', '../../../app/utils/dragAndDrop/checkAllowedChild', '../../../app/utils/dragAndDrop/constants/dragDropTargetType', '../../../app/utils/dragAndDrop/constants/targetPosition', '../../../app/utils/dragAndDrop/getTargetPosition', '../../../app/utils/dragAndDrop/itemIsAncestor', '../../../app/utils/dragAndDrop/toControlsId', '../../../app/utils/dragAndDrop/useDragAndDrop'], 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 = StructureTreeNode;

    var _button = _interopRequireDefault(require("@frontend-taglib-clay$clayui/button"));

    var _icon = _interopRequireDefault(require("@frontend-taglib-clay$clayui/icon"));

    var _classnames = _interopRequireDefault(require("frontend-js-react-web$classnames"));

    var _propTypes = _interopRequireDefault(require("frontend-js-react-web$prop-types"));

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

    var _CollectionItemContext = require("../../../app/components/CollectionItemContext");

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

    var _Collection = require("../../../app/components/layout-data-items/Collection");

    var _itemActivationOrigins = require("../../../app/config/constants/itemActivationOrigins");

    var _itemTypes = require("../../../app/config/constants/itemTypes");

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

    var _selectCanUpdatePageStructure = _interopRequireDefault(require("../../../app/selectors/selectCanUpdatePageStructure"));

    var _selectSegmentsExperienceId = _interopRequireDefault(require("../../../app/selectors/selectSegmentsExperienceId"));

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

    var _deleteItem = _interopRequireDefault(require("../../../app/thunks/deleteItem"));

    var _moveItem = _interopRequireDefault(require("../../../app/thunks/moveItem"));

    var _checkDeepEqual = require("../../../app/utils/checkDeepEqual");

    var _checkAllowedChild = _interopRequireDefault(require("../../../app/utils/dragAndDrop/checkAllowedChild"));

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

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

    var _getTargetPosition3 = _interopRequireDefault(require("../../../app/utils/dragAndDrop/getTargetPosition"));

    var _itemIsAncestor = _interopRequireDefault(require("../../../app/utils/dragAndDrop/itemIsAncestor"));

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

    var _useDragAndDrop = require("../../../app/utils/dragAndDrop/useDragAndDrop");

    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 _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: 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;
    }

    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 HOVER_EXPAND_DELAY = 1000;

    function StructureTreeNode(_ref) {
      var node = _ref.node;
      var activationOrigin = (0, _Controls.useActivationOrigin)();
      var activeItemId = (0, _Controls.useActiveItemId)();
      var hoveredItemId = (0, _Controls.useHoveredItemId)();
      var isSelected = node.id === (0, _Collection.fromControlsId)(activeItemId);
      return (/*#__PURE__*/_react.default.createElement(MemoizedStructureTreeNodeContent, {
          activationOrigin: isSelected ? activationOrigin : null,
          isActive: node.activable && isSelected,
          isHovered: node.id === (0, _Collection.fromControlsId)(hoveredItemId),
          isSelected: isSelected,
          node: node
        })
      );
    }

    var MemoizedStructureTreeNodeContent = /*#__PURE__*/_react.default.memo(StructureTreeNodeContent, function (prevProps, nextProps) {
      return (0, _checkDeepEqual.deepEqual)(_objectSpread(_objectSpread({}, prevProps), {}, {
        node: _objectSpread(_objectSpread({}, prevProps.node), {}, {
          children: []
        })
      }), _objectSpread(_objectSpread({}, nextProps), {}, {
        node: _objectSpread(_objectSpread({}, nextProps.node), {}, {
          children: []
        })
      }));
    });

    function StructureTreeNodeContent(_ref2) {
      var activationOrigin = _ref2.activationOrigin,
          isActive = _ref2.isActive,
          isHovered = _ref2.isHovered,
          isSelected = _ref2.isSelected,
          node = _ref2.node;
      var canUpdatePageStructure = (0, _index.useSelector)(_selectCanUpdatePageStructure.default);
      var dispatch = (0, _index.useDispatch)();
      var hoverItem = (0, _Controls.useHoverItem)();
      var isDisabled = !node.activable || node.disabled;
      var nodeRef = (0, _react.useRef)();
      var segmentsExperienceId = (0, _index.useSelector)(_selectSegmentsExperienceId.default);
      var selectItem = (0, _Controls.useSelectItem)();
      var toControlsId = (0, _CollectionItemContext.useToControlsId)();
      var item = {
        children: node.children,
        icon: node.icon,
        itemId: node.id,
        name: node.name,
        origin: _itemActivationOrigins.ITEM_ACTIVATION_ORIGINS.structureTree,
        parentId: node.parentItemId,
        type: node.type || node.itemType
      };

      var _useDropTarget = (0, _useDragAndDrop.useDropTarget)(item, computeHover),
          isOverTarget = _useDropTarget.isOverTarget,
          targetPosition = _useDropTarget.targetPosition,
          targetRef = _useDropTarget.targetRef;

      var _useDragItem = (0, _useDragAndDrop.useDragItem)(item, function (parentItemId, position) {
        return dispatch((0, _moveItem.default)({
          itemId: node.id,
          parentItemId: parentItemId,
          position: position,
          segmentsExperienceId: segmentsExperienceId
        }));
      }),
          handlerRef = _useDragItem.handlerRef,
          isDraggingSource = _useDragItem.isDraggingSource;

      (0, _react.useEffect)(function () {
        if (isActive && activationOrigin === _itemActivationOrigins.ITEM_ACTIVATION_ORIGINS.pageEditor && nodeRef.current) {
          nodeRef.current.scrollIntoView({
            behavior: 'smooth',
            block: 'center',
            inline: 'nearest'
          });
        }
      }, [activationOrigin, isActive]);
      (0, _react.useEffect)(function () {
        var timeoutId = null;

        if (isOverTarget) {
          timeoutId = setTimeout(function () {
            node.onHoverNode(node.id);
          }, HOVER_EXPAND_DELAY);
        }

        return function () {
          clearTimeout(timeoutId);
        };
      }, [isOverTarget, node]);
      return (/*#__PURE__*/_react.default.createElement("div", {
          "aria-disabled": isDisabled,
          "aria-selected": isActive,
          className: (0, _classnames.default)('page-editor__page-structure__tree-node', {
            'drag-over-bottom': isOverTarget && targetPosition === _targetPosition.TARGET_POSITION.BOTTOM,
            'drag-over-middle': isOverTarget && targetPosition === _targetPosition.TARGET_POSITION.MIDDLE,
            'drag-over-top': isOverTarget && targetPosition === _targetPosition.TARGET_POSITION.TOP,
            dragged: isDraggingSource,
            'page-editor__page-structure__tree-node--activable': node.activable && node.itemType !== _itemTypes.ITEM_TYPES.editable,
            'page-editor__page-structure__tree-node--active': isActive,
            'page-editor__page-structure__tree-node--hovered': isHovered
          }),
          onMouseLeave: function onMouseLeave(event) {
            if (!isDraggingSource && isHovered) {
              event.stopPropagation();
              hoverItem(null);
            }
          },
          onMouseOver: function onMouseOver(event) {
            if (!isDraggingSource) {
              event.stopPropagation();
              hoverItem(node.id);
            }
          },
          ref: targetRef
        }, /*#__PURE__*/_react.default.createElement("div", {
          "aria-label": Liferay.Util.sub(Liferay.Language.get('select-x'), [node.name]),
          className: "page-editor__page-structure__tree-node__mask",
          onClick: function onClick(event) {
            event.stopPropagation();
            event.target.focus();

            if (node.activable) {
              selectItem(toControlsId(node.id), {
                itemType: node.itemType,
                origin: _itemActivationOrigins.ITEM_ACTIVATION_ORIGINS.structureTree
              });
            }
          },
          onDoubleClick: function onDoubleClick(event) {
            return event.stopPropagation();
          },
          ref: handlerRef,
          role: "button"
        }), /*#__PURE__*/_react.default.createElement(NameLabel, {
          disabled: node.disabled,
          icon: node.icon,
          isActive: isActive,
          name: node.name,
          ref: nodeRef
        }), node.removable && canUpdatePageStructure && /*#__PURE__*/_react.default.createElement(RemoveButton, {
          node: node,
          visible: isHovered || isSelected
        }))
      );
    }

    var NameLabel = /*#__PURE__*/_react.default.forwardRef(function (_ref3, ref) {
      var disabled = _ref3.disabled,
          icon = _ref3.icon,
          isActive = _ref3.isActive,
          name = _ref3.name;
      return (/*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('page-editor__page-structure__tree-node__name', {
            'page-editor__page-structure__tree-node__name--active': isActive,
            'page-editor__page-structure__tree-node__name--disabled': disabled
          }),
          ref: ref
        }, icon && /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: icon || ''
        }), name || Liferay.Language.get('element'))
      );
    });

    var RemoveButton = function RemoveButton(_ref4) {
      var node = _ref4.node,
          visible = _ref4.visible;
      var dispatch = (0, _index.useDispatch)();
      var selectItem = (0, _Controls.useSelectItem)();
      var store = (0, _index.useSelector)(function (state) {
        return state;
      });
      return (/*#__PURE__*/_react.default.createElement(_button.default, {
          "aria-label": Liferay.Util.sub(Liferay.Language.get('remove-x'), [node.name]),
          className: (0, _classnames.default)('page-editor__page-structure__tree-node__remove-button', {
            'page-editor__page-structure__tree-node__remove-button--visible': visible
          }),
          displayType: "unstyled",
          onClick: function onClick(event) {
            event.stopPropagation();
            dispatch((0, _deleteItem.default)({
              itemId: node.id,
              selectItem: selectItem,
              store: store
            }));
          }
        }, /*#__PURE__*/_react.default.createElement(_icon.default, {
          symbol: "times-circle"
        }))
      );
    };

    function computeHover(_ref5) {
      var dispatch = _ref5.dispatch,
          layoutDataRef = _ref5.layoutDataRef,
          monitor = _ref5.monitor,
          _ref5$siblingItem = _ref5.siblingItem,
          siblingItem = _ref5$siblingItem === void 0 ? null : _ref5$siblingItem,
          sourceItem = _ref5.sourceItem,
          targetItem = _ref5.targetItem,
          targetRefs = _ref5.targetRefs;

      // Not dragging over direct child
      // We do not want to alter state here,
      // as dnd generate extra hover events when
      // items are being dragged over nested children
      if (!monitor.isOver({
        shallow: true
      })) {
        return;
      } // Dragging over itself or a descendant


      if ((0, _itemIsAncestor.default)(sourceItem, targetItem, layoutDataRef)) {
        return dispatch(_objectSpread(_objectSpread({}, _useDragAndDrop.initialDragDrop.state), {}, {
          type: _dragDropTargetType.DRAG_DROP_TARGET_TYPE.DRAGGING_TO_ITSELF
        }));
      } // Apparently valid drag, calculate vertical position and
      // nesting validation


      var _getItemPosition = getItemPosition(siblingItem || targetItem, monitor, layoutDataRef, targetRefs),
          _getItemPosition2 = _slicedToArray(_getItemPosition, 3),
          targetPositionWithMiddle = _getItemPosition2[0],
          targetPositionWithoutMiddle = _getItemPosition2[1],
          elevation = _getItemPosition2[2]; // Drop inside target


      var validDropInsideTarget = function () {
        var _layoutDataRef$curren;

        var targetIsColumn = targetItem.type === _layoutDataItemTypes.LAYOUT_DATA_ITEM_TYPES.column;
        var targetIsFragment = targetItem.type === _layoutDataItemTypes.LAYOUT_DATA_ITEM_TYPES.fragment;
        var targetIsContainer = targetItem.type === _layoutDataItemTypes.LAYOUT_DATA_ITEM_TYPES.container;
        var targetIsEmpty = ((_layoutDataRef$curren = layoutDataRef.current.items[targetItem.itemId]) === null || _layoutDataRef$curren === void 0 ? void 0 : _layoutDataRef$curren.children.length) === 0;
        var targetIsParent = sourceItem.parentId === targetItem.itemId;
        return targetPositionWithMiddle === _targetPosition.TARGET_POSITION.MIDDLE && (targetIsEmpty || targetIsColumn || targetIsContainer) && !targetIsFragment && !targetIsParent;
      }();

      if (!siblingItem && validDropInsideTarget) {
        return dispatch({
          dropItem: sourceItem,
          dropTargetItem: targetItem,
          droppable: (0, _checkAllowedChild.default)(sourceItem, targetItem, layoutDataRef),
          elevate: null,
          targetPositionWithMiddle: targetPositionWithMiddle,
          targetPositionWithoutMiddle: targetPositionWithoutMiddle,
          type: _dragDropTargetType.DRAG_DROP_TARGET_TYPE.INSIDE
        });
      } // Valid elevation:
      // - dropItem should be child of dropTargetItem
      // - dropItem should be sibling of siblingItem


      if (siblingItem && (0, _checkAllowedChild.default)(sourceItem, targetItem, layoutDataRef)) {
        return dispatch({
          dropItem: sourceItem,
          dropTargetItem: siblingItem,
          droppable: true,
          elevate: true,
          targetPositionWithMiddle: targetPositionWithMiddle,
          targetPositionWithoutMiddle: targetPositionWithoutMiddle,
          type: _dragDropTargetType.DRAG_DROP_TARGET_TYPE.ELEVATE
        });
      } // Try to elevate to a valid ancestor


      if (elevation) {
        var getElevatedTargetItem = function getElevatedTargetItem(target) {
          var parent = layoutDataRef.current.items[target.parentId] ? _objectSpread(_objectSpread({}, layoutDataRef.current.items[target.parentId]), {}, {
            collectionItemIndex: target.collectionItemIndex
          }) : null;

          if (parent) {
            var _getItemPosition3 = getItemPosition(target, monitor, layoutDataRef, targetRefs),
                _getItemPosition4 = _slicedToArray(_getItemPosition3, 1),
                targetPosition = _getItemPosition4[0];

            var _getItemPosition5 = getItemPosition(parent, monitor, layoutDataRef, targetRefs),
                _getItemPosition6 = _slicedToArray(_getItemPosition5, 1),
                parentPosition = _getItemPosition6[0];

            if ((targetPosition === targetPositionWithMiddle || parentPosition === targetPositionWithMiddle) && (0, _checkAllowedChild.default)(sourceItem, parent, layoutDataRef)) {
              return [parent, target];
            }
          }

          return [null, null];
        };

        var _getElevatedTargetIte = getElevatedTargetItem(targetItem),
            _getElevatedTargetIte2 = _slicedToArray(_getElevatedTargetIte, 2),
            elevatedTargetItem = _getElevatedTargetIte2[0],
            _siblingItem = _getElevatedTargetIte2[1];

        if (elevatedTargetItem && elevatedTargetItem !== targetItem) {
          return computeHover({
            dispatch: dispatch,
            layoutDataRef: layoutDataRef,
            monitor: monitor,
            siblingItem: _siblingItem,
            sourceItem: sourceItem,
            targetItem: elevatedTargetItem,
            targetRefs: targetRefs
          });
        }
      }
    }

    var ELEVATION_BORDER_SIZE = 5;

    function getItemPosition(item, monitor, layoutDataRef, targetRefs) {
      var targetRef = targetRefs.get((0, _toControlsId.default)(layoutDataRef, item));

      if (!targetRef || !targetRef.current) {
        return [null, null];
      }

      var clientOffsetY = monitor.getClientOffset().y;
      var hoverBoundingRect = targetRef.current.getBoundingClientRect();

      var _getTargetPosition = (0, _getTargetPosition3.default)(clientOffsetY, hoverBoundingRect, ELEVATION_BORDER_SIZE),
          _getTargetPosition2 = _slicedToArray(_getTargetPosition, 2),
          targetPositionWithMiddle = _getTargetPosition2[0],
          targetPositionWithoutMiddle = _getTargetPosition2[1];

      var elevation = targetPositionWithMiddle !== _targetPosition.TARGET_POSITION.MIDDLE;
      return [targetPositionWithMiddle, targetPositionWithoutMiddle, elevation];
    }
    //# sourceMappingURL=StructureTreeNode.js.map
  }
});
//# sourceMappingURL=StructureTreeNode.js.map