"use strict";

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

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

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

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 _types = require("./types");

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

var _d3Selection = require("d3-selection");

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

var _renderUi = require("../render-ui");

var _editableHtml = _interopRequireDefault(require("../editable-html"));

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

var _label = _interopRequireDefault(require("./label"));

var _utils = require("./utils");

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

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

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

  var _super = _createSuper(Root);

  function Root(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Root);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "mouseMove", function (g) {
      var _this$props = _this.props,
          graphProps = _this$props.graphProps,
          onMouseMove = _this$props.onMouseMove;

      if (!onMouseMove) {
        return;
      }

      var scale = graphProps.scale,
          snap = graphProps.snap;
      var coords = (0, _d3Selection.mouse)(g._groups[0][0]);
      var x = scale.x.invert(coords[0]);
      var y = scale.y.invert(coords[1]);
      var snapped = {
        x: snap.x(x),
        y: snap.y(y)
      };
      onMouseMove(snapped);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onChangeLabel", function (newValue, side) {
      var _this$props2 = _this.props,
          labels = _this$props2.labels,
          onChangeLabels = _this$props2.onChangeLabels,
          isChart = _this$props2.isChart;

      if (!onChangeLabels) {
        return;
      }

      if (isChart) {
        if (side === 'left') {
          onChangeLabels('range', newValue);
        } else {
          onChangeLabels('domain', newValue);
        }

        return;
      }

      onChangeLabels(_objectSpread(_objectSpread({}, labels), {}, (0, _defineProperty2["default"])({}, side, newValue)));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "measureTitleHeight", function () {
      var titleElement = document.getElementById('editable-title');

      if (titleElement) {
        var titleHeight = titleElement.clientHeight;

        _this.setState({
          titleHeight: titleHeight,
          prevTitle: _this.props.title
        });
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleKeyDown", function () {
      setTimeout(_this.measureTitleHeight, 0);
    });
    _this.state = {
      titleHeight: 0
    };
    return _this;
  }

  (0, _createClass2["default"])(Root, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var g = (0, _d3Selection.select)(this.g);
      g.on('mousemove', this.mouseMove.bind(this, g));
      this.measureTitleHeight();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var g = (0, _d3Selection.select)(this.g);
      g.on('mousemove', null);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (prevProps.title !== this.props.title) {
        this.measureTitleHeight();
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props3 = this.props,
          disabledTitle = _this$props3.disabledTitle,
          disabledLabels = _this$props3.disabledLabels,
          labels = _this$props3.labels,
          labelsPlaceholders = _this$props3.labelsPlaceholders,
          titlePlaceholder = _this$props3.titlePlaceholder,
          graphProps = _this$props3.graphProps,
          children = _this$props3.children,
          classes = _this$props3.classes,
          defineChart = _this$props3.defineChart,
          onChangeTitle = _this$props3.onChangeTitle,
          isChart = _this$props3.isChart,
          showLabels = _this$props3.showLabels,
          showPixelGuides = _this$props3.showPixelGuides,
          showTitle = _this$props3.showTitle,
          title = _this$props3.title,
          rootRef = _this$props3.rootRef,
          _this$props3$mathMlOp = _this$props3.mathMlOptions,
          mathMlOptions = _this$props3$mathMlOp === void 0 ? {} : _this$props3$mathMlOp,
          labelsCharactersLimit = _this$props3.labelsCharactersLimit;
      var _graphProps$size = graphProps.size,
          _graphProps$size$widt = _graphProps$size.width,
          width = _graphProps$size$widt === void 0 ? 500 : _graphProps$size$widt,
          _graphProps$size$heig = _graphProps$size.height,
          height = _graphProps$size$heig === void 0 ? 500 : _graphProps$size$heig,
          domain = graphProps.domain,
          range = graphProps.range;
      var topPadding = 40;
      var leftPadding = (0, _utils.isEmptyString)((0, _utils.extractTextFromHTML)(labels === null || labels === void 0 ? void 0 : labels.left)) && (0, _utils.isEmptyObject)(labelsPlaceholders) ? 48 : 70;
      var rightPadding = (0, _utils.isEmptyString)((0, _utils.extractTextFromHTML)(labels === null || labels === void 0 ? void 0 : labels.right)) && (0, _utils.isEmptyObject)(labelsPlaceholders) ? 48 : 70;
      var finalWidth = width + leftPadding + rightPadding + (domain.padding || 0) * 2;
      var finalHeight = height + topPadding * 2 + (range.padding || 0) * 2;
      var activeTitlePlugins = ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'math' // 'languageCharacters'
      ];
      var actualHeight = defineChart && showPixelGuides ? height - 160 : height;
      var nbOfVerticalLines = parseInt(width / 100);
      var nbOfHorizontalLines = parseInt(actualHeight / 100);
      var sideGridlinesPadding = parseInt(actualHeight % 100);
      var titleHeight = this.state.titleHeight;
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.root
      }, showPixelGuides && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.topPixelGuides,
        style: {
          marginLeft: isChart ? 80 : showLabels ? 30 : 10
        }
      }, (0, _toConsumableArray2["default"])(Array(nbOfVerticalLines + 1).keys()).map(function (value) {
        return /*#__PURE__*/_react["default"].createElement(_renderUi.Readable, {
          "false": true,
          key: "top-guide-".concat(value)
        }, /*#__PURE__*/_react["default"].createElement("div", {
          className: classes.topPixelIndicator
        }, /*#__PURE__*/_react["default"].createElement("div", null, value * 100, "px"), /*#__PURE__*/_react["default"].createElement("div", null, "|")));
      })), showTitle && (disabledTitle ? /*#__PURE__*/_react["default"].createElement("div", {
        id: "editable-title",
        style: _objectSpread(_objectSpread({}, isChart && {
          width: finalWidth
        }), (0, _utils.isEmptyString)((0, _utils.extractTextFromHTML)(title)) && {
          display: 'none'
        }),
        className: (0, _classnames["default"])(isChart ? classes.chartTitle : classes.graphTitle, classes.disabledTitle),
        dangerouslySetInnerHTML: {
          __html: title || ''
        }
      }) : /*#__PURE__*/_react["default"].createElement("div", {
        id: "editable-title"
      }, /*#__PURE__*/_react["default"].createElement(_editableHtml["default"], {
        style: isChart && {
          width: finalWidth
        },
        className: (0, _classnames["default"])((0, _defineProperty2["default"])({}, classes.rightMargin, showPixelGuides), isChart ? classes.chartTitle : classes.graphTitle),
        markup: title || '',
        onChange: onChangeTitle,
        placeholder: defineChart && titlePlaceholder || !disabledTitle && 'Click here to add a title for this graph',
        toolbarOpts: {
          noPadding: true,
          noBorder: true
        },
        activePlugins: activeTitlePlugins,
        disableScrollbar: true,
        onKeyDown: this.handleKeyDown
      }))), showLabels && !isChart && /*#__PURE__*/_react["default"].createElement(_label["default"], {
        side: "top",
        text: labels.top,
        disabledLabel: disabledLabels,
        placeholder: labelsPlaceholders === null || labelsPlaceholders === void 0 ? void 0 : labelsPlaceholders.top,
        graphHeight: finalHeight,
        graphWidth: finalWidth,
        onChange: function onChange(value) {
          return _this2.onChangeLabel(value, 'top');
        },
        mathMlOptions: mathMlOptions,
        charactersLimit: labelsCharactersLimit
      }), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.wrapper
      }, showLabels && /*#__PURE__*/_react["default"].createElement(_label["default"], {
        side: "left",
        text: labels.left,
        disabledLabel: disabledLabels,
        placeholder: labelsPlaceholders === null || labelsPlaceholders === void 0 ? void 0 : labelsPlaceholders.left,
        graphHeight: finalHeight,
        graphWidth: finalWidth,
        isChartLeftLabel: isChart && !defineChart,
        isDefineChartLeftLabel: isChart && defineChart,
        onChange: function onChange(value) {
          return _this2.onChangeLabel(value, 'left');
        },
        mathMlOptions: mathMlOptions,
        charactersLimit: labelsCharactersLimit
      }), /*#__PURE__*/_react["default"].createElement("svg", {
        width: finalWidth,
        height: finalHeight,
        className: defineChart ? classes.defineChart : classes.chart
      }, /*#__PURE__*/_react["default"].createElement("g", {
        ref: function ref(r) {
          _this2.g = r;

          if (rootRef) {
            rootRef(r);
          }
        },
        className: classes.graphBox,
        transform: "translate(".concat(leftPadding + (domain.padding || 0), ", ").concat(topPadding + (range.padding || 0), ")")
      }, children)), showLabels && !isChart && /*#__PURE__*/_react["default"].createElement(_label["default"], {
        side: "right",
        text: labels.right,
        disabledLabel: disabledLabels,
        placeholder: labelsPlaceholders === null || labelsPlaceholders === void 0 ? void 0 : labelsPlaceholders.right,
        graphHeight: finalHeight,
        graphWidth: finalWidth,
        onChange: function onChange(value) {
          return _this2.onChangeLabel(value, 'right');
        },
        mathMlOptions: mathMlOptions,
        charactersLimit: labelsCharactersLimit
      }), showPixelGuides && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.sidePixelGuides,
        style: {
          paddingTop: sideGridlinesPadding,
          marginTop: 31
        }
      }, (0, _toConsumableArray2["default"])(Array(nbOfHorizontalLines + 1).keys()).reverse().map(function (value) {
        return /*#__PURE__*/_react["default"].createElement(_renderUi.Readable, {
          "false": true,
          key: "top-guide-".concat(value)
        }, /*#__PURE__*/_react["default"].createElement("div", {
          className: classes.sidePixelIndicator
        }, "\u2501 ", value * 100, "px"));
      }))), showLabels && /*#__PURE__*/_react["default"].createElement(_label["default"], {
        side: "bottom",
        text: labels.bottom,
        disabledLabel: disabledLabels,
        placeholder: labelsPlaceholders === null || labelsPlaceholders === void 0 ? void 0 : labelsPlaceholders.bottom,
        graphHeight: finalHeight,
        graphWidth: finalWidth,
        titleHeight: titleHeight,
        isChartBottomLabel: isChart && !defineChart,
        isDefineChartBottomLabel: isChart && defineChart,
        onChange: function onChange(value) {
          return _this2.onChangeLabel(value, 'bottom');
        },
        mathMlOptions: mathMlOptions,
        charactersLimit: labelsCharactersLimit
      }));
    }
  }]);
  return Root;
}(_react["default"].Component); // use default color theme style to avoid color contrast issues


exports.Root = Root;
(0, _defineProperty2["default"])(Root, "propTypes", {
  title: _propTypes["default"].string,
  children: _types.ChildrenType,
  defineChart: _propTypes["default"].bool,
  disabledLabels: _propTypes["default"].bool,
  disabledTitle: _propTypes["default"].bool,
  graphProps: _types.GraphPropsType.isRequired,
  isChart: _propTypes["default"].bool,
  labels: _propTypes["default"].object,
  labelsPlaceholders: _propTypes["default"].object,
  onChangeTitle: _propTypes["default"].func,
  onMouseMove: _propTypes["default"].func,
  classes: _propTypes["default"].object.isRequired,
  showLabels: _propTypes["default"].bool,
  showTitle: _propTypes["default"].bool,
  showPixelGuides: _propTypes["default"].bool,
  rootRef: _propTypes["default"].func,
  onChangeLabels: _propTypes["default"].func,
  titlePlaceholder: _propTypes["default"].string,
  mathMlOptions: _propTypes["default"].object,
  labelsCharactersLimit: _propTypes["default"].number
});

var styles = function styles(theme) {
  return {
    root: {
      border: "solid 1px ".concat(_renderUi.color.primaryLight()),
      color: _renderUi.color.defaults.TEXT,
      backgroundColor: theme.palette.common.white,
      touchAction: 'none',
      position: 'relative'
    },
    wrapper: {
      display: 'flex',
      position: 'relative'
    },
    svg: {},
    defineChart: {
      paddingLeft: '50px',
      overflow: 'visible'
    },
    chart: {
      overflow: 'visible'
    },
    graphBox: {
      cursor: 'pointer',
      userSelect: 'none'
    },
    graphTitle: {
      color: _renderUi.color.defaults.TEXT,
      fontSize: theme.typography.fontSize + 2,
      padding: "".concat(theme.spacing.unit * 1.5, "px ").concat(theme.spacing.unit / 2, "px 0"),
      textAlign: 'center'
    },
    chartTitle: {
      color: _renderUi.color.defaults.TEXT,
      fontSize: theme.typography.fontSize + 4,
      padding: "".concat(theme.spacing.unit * 1.5, "px ").concat(theme.spacing.unit / 2, "px 0"),
      textAlign: 'center'
    },
    disabledTitle: {
      pointerEvents: 'none'
    },
    rightMargin: {
      marginRight: '74px'
    },
    topPixelGuides: {
      display: 'flex',
      paddingTop: '6px'
    },
    topPixelIndicator: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      width: '100px',
      pointerEvents: 'none',
      userSelect: 'none'
    },
    sidePixelGuides: {
      width: '70px',
      display: 'flex',
      flexDirection: 'column',
      marginRight: '6px',
      marginLeft: '12px'
    },
    sidePixelIndicator: {
      textAlign: 'right',
      height: '20px',
      pointerEvents: 'none',
      userSelect: 'none',
      '&:not(:last-child)': {
        marginBottom: '80px'
      }
    }
  };
};

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

exports["default"] = _default;
//# sourceMappingURL=root.js.map