"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ControlGroup = void 0;
require("../control_group.scss");
var _sortable = require("@dnd-kit/sortable");
var _core = require("@dnd-kit/core");
var _classnames = _interopRequireDefault(require("classnames"));
var _react = _interopRequireWildcard(require("react"));
var _reactRedux = require("react-redux");
var _eui = require("@elastic/eui");
var _public = require("@kbn/embeddable-plugin/public");
var _control_group_strings = require("../control_group_strings");
var _control_group_sortable_item = require("./control_group_sortable_item");
var _control_group_container = require("../embeddable/control_group_container");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const contextSelect = _reactRedux.useSelector;
const ControlGroup = () => {
  const controlGroup = (0, _control_group_container.useControlGroupContainer)();

  // current state
  const panels = contextSelect(state => state.explicitInput.panels);
  const viewMode = contextSelect(state => state.explicitInput.viewMode);
  const controlStyle = contextSelect(state => state.explicitInput.controlStyle);
  const showAddButton = contextSelect(state => state.componentState.showAddButton);
  const isEditable = viewMode === _public.ViewMode.EDIT;
  const idsInOrder = (0, _react.useMemo)(() => Object.values(panels).sort((a, b) => a.order > b.order ? 1 : -1).reduce((acc, panel) => {
    acc.push(panel.explicitInput.id);
    return acc;
  }, []), [panels]);
  const [draggingId, setDraggingId] = (0, _react.useState)(null);
  const draggingIndex = (0, _react.useMemo)(() => draggingId ? idsInOrder.indexOf(draggingId) : -1, [idsInOrder, draggingId]);
  const sensors = (0, _core.useSensors)((0, _core.useSensor)(_core.PointerSensor), (0, _core.useSensor)(_core.KeyboardSensor, {
    coordinateGetter: _sortable.sortableKeyboardCoordinates
  }));
  const onDragEnd = ({
    over
  }) => {
    var _document$activeEleme;
    if (over) {
      const overIndex = idsInOrder.indexOf(over.id);
      if (draggingIndex !== overIndex) {
        const newIndex = overIndex;
        controlGroup.dispatch.setControlOrders({
          ids: (0, _sortable.arrayMove)([...idsInOrder], draggingIndex, newIndex)
        });
      }
    }
    (_document$activeEleme = document.activeElement) === null || _document$activeEleme === void 0 ? void 0 : _document$activeEleme.blur();
    setDraggingId(null);
  };
  const emptyState = !(idsInOrder && idsInOrder.length > 0);
  // Empty, non-editable view is null
  if (!isEditable && emptyState) {
    return null;
  }
  let panelBg = 'transparent';
  if (emptyState) panelBg = 'plain';
  if (draggingId) panelBg = 'success';
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, idsInOrder.length > 0 || showAddButton ? /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    borderRadius: "m",
    color: panelBg,
    paddingSize: emptyState ? 's' : 'none',
    "data-test-subj": "controls-group-wrapper",
    className: (0, _classnames.default)('controlsWrapper', {
      'controlsWrapper--empty': emptyState,
      'controlsWrapper--twoLine': controlStyle === 'twoLine'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    wrap: false,
    gutterSize: "m",
    direction: "row",
    responsive: false,
    alignItems: "center",
    "data-test-subj": "controls-group"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_core.DndContext, {
    onDragStart: ({
      active
    }) => setDraggingId(active.id),
    onDragEnd: onDragEnd,
    onDragCancel: () => setDraggingId(null),
    sensors: sensors,
    collisionDetection: _core.closestCenter,
    layoutMeasuring: {
      strategy: _core.LayoutMeasuringStrategy.Always
    }
  }, /*#__PURE__*/_react.default.createElement(_sortable.SortableContext, {
    items: idsInOrder,
    strategy: _sortable.rectSortingStrategy
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    className: (0, _classnames.default)('controlGroup', {
      'controlGroup-isDragging': draggingId
    }),
    alignItems: "center",
    gutterSize: "s",
    wrap: true
  }, idsInOrder.map((controlId, index) => panels[controlId] && /*#__PURE__*/_react.default.createElement(_control_group_sortable_item.SortableControl, {
    isEditable: isEditable,
    dragInfo: {
      index,
      draggingIndex
    },
    embeddableId: controlId,
    embeddableType: panels[controlId].type,
    key: controlId
  })))), /*#__PURE__*/_react.default.createElement(_core.DragOverlay, null, draggingId ? /*#__PURE__*/_react.default.createElement(_control_group_sortable_item.ControlClone, {
    draggingId: draggingId
  }) : null))), showAddButton && /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
    size: "s",
    iconSize: "m",
    display: "base",
    iconType: 'plusInCircle',
    "aria-label": _control_group_strings.ControlGroupStrings.management.getAddControlTitle(),
    onClick: () => controlGroup.openAddDataControlFlyout()
  })))) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null));
};
exports.ControlGroup = ControlGroup;