"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.toolIsAvailable = exports.setToolbarAvailability = exports.getAvailableTool = exports.filterByVisibleToolTypes = exports.filterByValidToolTypes = exports["default"] = exports.GraphWithControls = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _styles = require("@material-ui/core/styles");

var _classnames = _interopRequireDefault(require("classnames"));

var _uniq = _interopRequireDefault(require("lodash/uniq"));

var _isString = _interopRequireDefault(require("lodash/isString"));

var _renderUi = require("@pie-lib/render-ui");

var _toolMenu = _interopRequireDefault(require("./tool-menu"));

var _graph = _interopRequireWildcard(require("./graph"));

var _undoRedo = _interopRequireDefault(require("./undo-redo"));

var _tools = require("./tools");

var _core = require("@material-ui/core");

var _ExpandMore = _interopRequireDefault(require("@material-ui/icons/ExpandMore"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(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; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["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; } }

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) { (0, _defineProperty2["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; }

var setToolbarAvailability = function setToolbarAvailability(toolbarTools) {
  return _tools.toolsArr.map(function (tA) {
    return _objectSpread(_objectSpread({}, tA), {}, {
      toolbar: !!toolbarTools.find(function (t) {
        return t === tA.type;
      })
    });
  }) || [];
};

exports.setToolbarAvailability = setToolbarAvailability;

var toolIsAvailable = function toolIsAvailable(tools, currentTool) {
  return currentTool && tools && (tools.find(function (tool) {
    return tool.type === currentTool.type;
  }) || {}).toolbar;
};

exports.toolIsAvailable = toolIsAvailable;

var getAvailableTool = function getAvailableTool(tools) {
  return tools.find(function (tool) {
    return tool.toolbar;
  });
};

exports.getAvailableTool = getAvailableTool;

var filterByValidToolTypes = function filterByValidToolTypes(backgroundMarks) {
  return backgroundMarks.filter(function (bM) {
    return !!_tools.allTools.find(function (tool) {
      return tool === bM.type;
    });
  });
};

exports.filterByValidToolTypes = filterByValidToolTypes;

var filterByVisibleToolTypes = function filterByVisibleToolTypes(toolbarTools, marks) {
  return marks.filter(function (bM) {
    return !!toolbarTools.find(function (tool) {
      return tool === bM.type;
    });
  });
};

exports.filterByVisibleToolTypes = filterByVisibleToolTypes;

var getDefaultCurrentTool = function getDefaultCurrentTool(toolType) {
  return _tools.toolsArr.find(function (tool) {
    return tool.type === toolType;
  }) || null;
};

var Collapsible = function Collapsible(_ref) {
  var classes = _ref.classes,
      children = _ref.children,
      title = _ref.title;
  return /*#__PURE__*/_react["default"].createElement(_core.ExpansionPanel, {
    elevation: 0,
    className: classes.expansionPanel,
    disabledGutters: true,
    square: true
  }, /*#__PURE__*/_react["default"].createElement(_core.ExpansionPanelSummary, {
    classes: {
      root: classes.summaryRoot,
      content: classes.summaryContent
    },
    expandIcon: /*#__PURE__*/_react["default"].createElement(_ExpandMore["default"], null)
  }, /*#__PURE__*/_react["default"].createElement(_core.Typography, {
    variant: "subheading"
  }, title)), /*#__PURE__*/_react["default"].createElement(_core.ExpansionPanelDetails, {
    className: classes.details
  }, children));
};

Collapsible.propTypes = {
  classes: _propTypes["default"].object,
  children: _propTypes["default"].array,
  title: _propTypes["default"].string
};

var GraphWithControls = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(GraphWithControls, _React$Component);

  var _super = _createSuper(GraphWithControls);

  function GraphWithControls(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, GraphWithControls);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeCurrentTool", function (tool, tools) {
      return _this.setState({
        currentTool: tools.find(function (t) {
          return t.type === tool;
        })
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toggleLabelMode", function () {
      return _this.setState(function (state) {
        return {
          labelModeEnabled: !state.labelModeEnabled
        };
      });
    });
    _this.state = {
      currentTool: getDefaultCurrentTool(props.defaultTool),
      labelModeEnabled: false
    };
    return _this;
  }

  (0, _createClass2["default"])(GraphWithControls, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var defaultTool = this.props.defaultTool;

      if (prevProps.defaultTool !== defaultTool) {
        var currentTool = getDefaultCurrentTool(defaultTool);
        this.setState({
          currentTool: currentTool
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$state = this.state,
          currentTool = _this$state.currentTool,
          labelModeEnabled = _this$state.labelModeEnabled;
      var _this$props = this.props,
          axesSettings = _this$props.axesSettings,
          classes = _this$props.classes,
          className = _this$props.className,
          coordinatesOnHover = _this$props.coordinatesOnHover,
          collapsibleToolbar = _this$props.collapsibleToolbar,
          collapsibleToolbarTitle = _this$props.collapsibleToolbarTitle,
          disabled = _this$props.disabled,
          disabledLabels = _this$props.disabledLabels,
          disabledTitle = _this$props.disabledTitle,
          domain = _this$props.domain,
          labels = _this$props.labels,
          labelsPlaceholders = _this$props.labelsPlaceholders,
          onChangeLabels = _this$props.onChangeLabels,
          onChangeMarks = _this$props.onChangeMarks,
          onChangeTitle = _this$props.onChangeTitle,
          onUndo = _this$props.onUndo,
          onRedo = _this$props.onRedo,
          range = _this$props.range,
          size = _this$props.size,
          showLabels = _this$props.showLabels,
          showPixelGuides = _this$props.showPixelGuides,
          showTitle = _this$props.showTitle,
          title = _this$props.title,
          titlePlaceholder = _this$props.titlePlaceholder,
          language = _this$props.language,
          _this$props$disableTo = _this$props.disableToolbar,
          disableToolbar = _this$props$disableTo === void 0 ? false : _this$props$disableTo,
          gssLineData = _this$props.gssLineData,
          onChangeGssLineData = _this$props.onChangeGssLineData,
          onSolutionSetSelected = _this$props.onSolutionSetSelected,
          onCustomReset = _this$props.onCustomReset;
      var _this$props2 = this.props,
          backgroundMarks = _this$props2.backgroundMarks,
          marks = _this$props2.marks,
          toolbarTools = _this$props2.toolbarTools; // make sure only valid tool types are kept (string) and without duplicates

      toolbarTools = (0, _uniq["default"])(toolbarTools || []).filter(function (tT) {
        return !!(0, _isString["default"])(tT);
      }) || []; // keep only the backgroundMarks that have valid types

      backgroundMarks = filterByValidToolTypes(backgroundMarks || []); // keep only the marks that have types which appear in toolbar

      marks = filterByVisibleToolTypes(toolbarTools, marks || []);
      if (gssLineData && gssLineData.lineA && marks[0] && marks[0].type === 'line') marks[0].fill = gssLineData.lineA.lineType;
      if (gssLineData && gssLineData.lineB && marks[1] && marks[1].type === 'line') marks[1].fill = gssLineData.lineB.lineType;
      var tools = setToolbarAvailability(toolbarTools); // set current tool if there's no current tool or if the existing one is no longer available

      if (!currentTool || !toolIsAvailable(tools, currentTool)) {
        currentTool = getAvailableTool(tools);
      }

      var gssActions = gssLineData && /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_toolMenu["default"], {
        numberOfLines: gssLineData.numberOfLines,
        gssLineData: gssLineData,
        onChange: onChangeGssLineData,
        disabled: !!disabled,
        language: language
      }), !disabled && /*#__PURE__*/_react["default"].createElement(_undoRedo["default"], {
        className: classes.undoRedoOuterDiv,
        onUndo: onUndo,
        onRedo: onRedo,
        onReset: onCustomReset,
        language: language
      }));

      return /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames["default"])(classes.graphWithControls, className)
      }, !disableToolbar && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.controls
      }, collapsibleToolbar ? /*#__PURE__*/_react["default"].createElement(Collapsible, {
        classes: classes,
        title: collapsibleToolbarTitle
      }, gssActions) : gssActions), /*#__PURE__*/_react["default"].createElement("div", {
        ref: function ref(r) {
          return _this2.labelNode = r;
        }
      }), /*#__PURE__*/_react["default"].createElement(_graph["default"], {
        axesSettings: axesSettings,
        backgroundMarks: backgroundMarks,
        coordinatesOnHover: coordinatesOnHover,
        currentTool: currentTool,
        disabledLabels: disabledLabels,
        disabledTitle: disabledTitle,
        domain: domain,
        labels: labels,
        labelModeEnabled: labelModeEnabled,
        labelsPlaceholders: labelsPlaceholders,
        marks: marks,
        onChangeMarks: !disabled ? onChangeMarks : undefined,
        onChangeLabels: onChangeLabels,
        onChangeTitle: onChangeTitle,
        range: range,
        size: size,
        showLabels: showLabels,
        showPixelGuides: showPixelGuides,
        showTitle: showTitle,
        title: title,
        titlePlaceholder: titlePlaceholder,
        tools: tools,
        gssLineData: gssLineData,
        onSolutionSetSelected: onSolutionSetSelected,
        disabled: !!disabled
      }));
    }
  }]);
  return GraphWithControls;
}(_react["default"].Component);

exports.GraphWithControls = GraphWithControls;
(0, _defineProperty2["default"])(GraphWithControls, "propTypes", _objectSpread(_objectSpread({}, _graph.graphPropTypes), {}, {
  onUndo: _propTypes["default"].func,
  onRedo: _propTypes["default"].func,
  onReset: _propTypes["default"].func,
  toolbarTools: _propTypes["default"].arrayOf(_propTypes["default"].string),
  // array of tool types that have to be displayed in the toolbar, same shape as 'allTools'
  language: _propTypes["default"].string
}));
(0, _defineProperty2["default"])(GraphWithControls, "defaultProps", {
  collapsibleToolbar: false,
  collapsibleToolbarTitle: '',
  disabledLabels: false,
  disabledTitle: false,
  showLabels: true,
  showTitle: true,
  toolbarTools: []
});

var styles = function styles(theme) {
  return {
    graphWithControls: {
      display: 'flex',
      flexDirection: 'column',
      width: 'min-content'
    },
    controls: {
      display: 'flex',
      justifyContent: 'space-between',
      padding: 'calc(1.25rem - 12px) calc(1.25rem - 12px) 1.25rem',
      color: _renderUi.color.text(),
      backgroundColor: '#9FA8DA',
      '& button': {
        fontSize: '0.875rem',
        padding: '0.25rem .3rem',
        width: '5rem'
      }
    },
    expansionPanel: {
      backgroundColor: _renderUi.color.primaryLight(),
      width: '100%'
    },
    summaryRoot: {
      padding: "0 ".concat(theme.spacing.unit, "px"),
      minHeight: '32px !important'
    },
    summaryContent: {
      margin: '4px 0 !important'
    },
    details: {
      padding: 0,
      marginTop: theme.spacing.unit,
      display: 'flex',
      justifyContent: 'space-between'
    },
    undoRedoOuterDiv: {
      display: 'flex',
      flexDirection: 'column',
      marginTop: '.5rem'
    }
  };
};

var _default = (0, _styles.withStyles)(styles)(GraphWithControls);

exports["default"] = _default;
//# sourceMappingURL=graph-with-controls.js.map