"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.TickComponent = exports.RawChartAxes = 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 _propTypes = _interopRequireDefault(require("prop-types"));

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

var _plot = require("../plot");

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

var _configUi = require("../config-ui");

var _axis = require("@vx/axis");

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

var _markLabel = _interopRequireDefault(require("./mark-label"));

var _Checkbox = _interopRequireDefault(require("@material-ui/core/Checkbox"));

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 TickComponent = /*#__PURE__*/function (_React$Component) {
  (0, _inherits2["default"])(TickComponent, _React$Component);

  var _super = _createSuper(TickComponent);

  function TickComponent(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, TickComponent);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleAlertDialog", function (open, callback) {
      return _this.setState({
        dialog: {
          open: open
        }
      }, callback);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeCategory", function (index, newLabel) {
      var _this$props = _this.props,
          categories = _this$props.categories,
          onChangeCategory = _this$props.onChangeCategory;
      var category = categories[index];
      onChangeCategory(index, _objectSpread(_objectSpread({}, category), {}, {
        label: newLabel
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "deleteCategory", function (index) {
      var _this$props2 = _this.props,
          categories = _this$props2.categories,
          onChange = _this$props2.onChange;

      if (index >= 0 && categories[index]) {
        onChange([].concat((0, _toConsumableArray2["default"])(categories.slice(0, index)), (0, _toConsumableArray2["default"])(categories.slice(index + 1))));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeInteractive", function (index, value) {
      var _this$props3 = _this.props,
          categories = _this$props3.categories,
          onChangeCategory = _this$props3.onChangeCategory;
      var category = categories[index];

      if (!value) {
        _this.setState({
          dialog: {
            open: true,
            title: 'Warning',
            text: 'This will remove the correct answer value that has been defined for this category.',
            onConfirm: function onConfirm() {
              return _this.handleAlertDialog(false, onChangeCategory(index, _objectSpread(_objectSpread({}, category), {}, {
                interactive: !category.interactive
              })));
            },
            onClose: function onClose() {
              return _this.handleAlertDialog(false);
            }
          }
        });
      } else {
        onChangeCategory(index, _objectSpread(_objectSpread({}, category), {}, {
          interactive: !category.interactive
        }));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeEditable", function (index, value) {
      var _this$props4 = _this.props,
          categories = _this$props4.categories,
          onChangeCategory = _this$props4.onChangeCategory;
      var category = categories[index];

      if (!value) {
        _this.setState({
          dialog: {
            open: true,
            title: 'Warning',
            text: 'This will remove the correct answer category name that has been defined for this category.',
            onConfirm: function onConfirm() {
              return _this.handleAlertDialog(false, onChangeCategory(index, _objectSpread(_objectSpread({}, category), {}, {
                editable: !category.editable || false
              })));
            },
            onClose: function onClose() {
              return _this.handleAlertDialog(false);
            }
          }
        });
      } else {
        onChangeCategory(index, _objectSpread(_objectSpread({}, category), {}, {
          editable: !category.editable || false
        }));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "splitText", function (text, maxChar) {
      var chunks = [];

      while ((text || '').length > 0) {
        var indexToSplit = void 0;

        if (text.length > maxChar) {
          indexToSplit = text.lastIndexOf(' ', maxChar);

          if (indexToSplit === -1) {
            indexToSplit = maxChar;
          }
        } else {
          indexToSplit = text.length;
        }

        chunks.push(text.substring(0, indexToSplit));
        text = text.substring(indexToSplit).trim();
      }

      return chunks;
    });
    _this.state = {
      dialog: {
        open: false
      }
    };
    return _this;
  }

  (0, _createClass2["default"])(TickComponent, [{
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props5 = this.props,
          classes = _this$props5.classes,
          categories = _this$props5.categories,
          xBand = _this$props5.xBand,
          bandWidth = _this$props5.bandWidth,
          barWidth = _this$props5.barWidth,
          rotate = _this$props5.rotate,
          top = _this$props5.top,
          graphProps = _this$props5.graphProps,
          defineChart = _this$props5.defineChart,
          chartingOptions = _this$props5.chartingOptions,
          x = _this$props5.x,
          y = _this$props5.y,
          formattedValue = _this$props5.formattedValue,
          changeInteractiveEnabled = _this$props5.changeInteractiveEnabled,
          changeEditableEnabled = _this$props5.changeEditableEnabled,
          error = _this$props5.error;

      if (!formattedValue) {
        return null;
      }

      var dialog = this.state.dialog;

      var _ref = chartingOptions || {},
          changeEditable = _ref.changeEditable,
          changeInteractive = _ref.changeInteractive;

      var index = parseInt(formattedValue.split('-')[0], 10);
      var category = categories[index];

      var _ref2 = category || {},
          deletable = _ref2.deletable,
          editable = _ref2.editable,
          interactive = _ref2.interactive,
          label = _ref2.label,
          correctness = _ref2.correctness,
          autoFocus = _ref2.autoFocus,
          inDefineChart = _ref2.inDefineChart;

      var barX = xBand((0, _utils.bandKey)({
        label: label
      }, index));
      var longestCategory = (categories || []).reduce(function (a, b) {
        var lengthA = a && a.label ? a.label.length : 0;
        var lengthB = b && b.label ? b.label.length : 0;
        return lengthA > lengthB ? a : b;
      });
      var longestLabel = longestCategory && longestCategory.label || '';
      var distinctMessages = error ? (0, _toConsumableArray2["default"])(new Set(Object.values(error))).join(' ') : '';
      return /*#__PURE__*/_react["default"].createElement("g", null, /*#__PURE__*/_react["default"].createElement("foreignObject", {
        x: bandWidth ? barX : x - barWidth / 2,
        y: 6,
        width: barWidth,
        height: 4,
        style: {
          pointerEvents: 'none',
          overflow: 'visible'
        }
      }, index === 0 && /*#__PURE__*/_react["default"].createElement("div", {
        id: "hiddenLabel",
        style: {
          position: 'absolute',
          visibility: 'hidden',
          wordBreak: 'break-word',
          overflow: 'visible',
          maxWidth: barWidth,
          display: 'block'
        }
      }, longestLabel), /*#__PURE__*/_react["default"].createElement(_markLabel["default"], {
        autoFocus: inDefineChart ? defineChart && autoFocus : autoFocus,
        inputRef: function inputRef(r) {
          return _this2.input = r;
        },
        disabled: !defineChart && !editable,
        mark: category,
        graphProps: graphProps,
        onChange: function onChange(newLabel) {
          return _this2.changeCategory(index, newLabel);
        },
        barWidth: barWidth,
        rotate: rotate,
        correctness: correctness,
        error: error && error[index]
      })), error && index === 0 && /*#__PURE__*/_react["default"].createElement("text", {
        className: classes.error,
        y: y + 23,
        height: 6,
        textAnchor: "start"
      }, distinctMessages), deletable && !correctness && /*#__PURE__*/_react["default"].createElement("line", {
        x1: x,
        y1: 0,
        x2: x,
        y2: y + 4 + top,
        className: classes.dottedLine,
        strokeDasharray: "4 2"
      }), deletable && !correctness && /*#__PURE__*/_react["default"].createElement("svg", {
        xmlns: "http://www.w3.org/2000/svg",
        x: x - 8,
        y: y + 60 + top,
        width: 16,
        height: 16,
        viewBox: "0 0 512 512",
        onClick: function onClick() {
          return _this2.deleteCategory(index);
        }
      }, /*#__PURE__*/_react["default"].createElement("path", {
        d: "M128 405.429C128 428.846 147.198 448 170.667 448h170.667C364.802 448 384 428.846 384 405.429V160H128v245.429zM416 96h-80l-26.785-32H202.786L176 96H96v32h320V96z"
      })), defineChart && index === 0 && /*#__PURE__*/_react["default"].createElement("svg", {
        x: -55,
        style: {
          overflow: 'visible'
        }
      }, changeInteractiveEnabled && /*#__PURE__*/_react["default"].createElement("text", {
        y: y + 90 + top,
        width: barWidth,
        height: 4,
        style: {
          position: 'absolute',
          pointerEvents: 'none',
          wordBreak: 'break-word',
          maxWidth: barWidth,
          display: 'inline-block'
        }
      }, this.splitText(changeInteractive === null || changeInteractive === void 0 ? void 0 : changeInteractive.authoringLabel, 20).map(function (word, index) {
        return /*#__PURE__*/_react["default"].createElement("tspan", {
          key: index,
          x: "0",
          dy: "".concat(index > 0 ? '1.2em' : '.6em')
        }, word);
      })), changeEditableEnabled && /*#__PURE__*/_react["default"].createElement("text", {
        y: y + 145 + top,
        width: barWidth,
        height: 4,
        style: {
          position: 'absolute',
          pointerEvents: 'none',
          wordBreak: 'break-word',
          maxWidth: barWidth,
          display: 'inline-block'
        }
      }, this.splitText(changeEditable === null || changeEditable === void 0 ? void 0 : changeEditable.authoringLabel, 20).map(function (word, index) {
        return /*#__PURE__*/_react["default"].createElement("tspan", {
          key: index,
          x: "0",
          dy: "".concat(index > 0 ? '1.2em' : '.6em')
        }, word);
      }))), defineChart && changeInteractiveEnabled && /*#__PURE__*/_react["default"].createElement("foreignObject", {
        x: x - 24,
        y: y + 80 + top,
        width: barWidth,
        height: 4,
        style: {
          pointerEvents: 'visible',
          overflow: 'visible'
        }
      }, /*#__PURE__*/_react["default"].createElement(_Checkbox["default"], {
        style: {
          position: 'fixed'
        },
        checked: interactive,
        onChange: function onChange(e) {
          return _this2.changeInteractive(index, e.target.checked);
        }
      })), defineChart && changeEditableEnabled && /*#__PURE__*/_react["default"].createElement("foreignObject", {
        x: x - 24,
        y: y + 130 + top,
        width: barWidth,
        height: 4,
        style: {
          pointerEvents: 'visible',
          overflow: 'visible'
        }
      }, /*#__PURE__*/_react["default"].createElement(_Checkbox["default"], {
        style: {
          position: 'fixed'
        },
        checked: editable,
        onChange: function onChange(e) {
          return _this2.changeEditable(index, e.target.checked);
        }
      })), /*#__PURE__*/_react["default"].createElement("foreignObject", {
        x: x - 24,
        y: y + 100 + top,
        width: barWidth,
        height: 4,
        style: {
          pointerEvents: 'visible',
          overflow: 'visible'
        }
      }, /*#__PURE__*/_react["default"].createElement(_configUi.AlertDialog, {
        open: dialog.open,
        title: dialog.title,
        text: dialog.text,
        onClose: dialog.onClose,
        onConfirm: dialog.onConfirm
      })));
    }
  }]);
  return TickComponent;
}(_react["default"].Component);

exports.TickComponent = TickComponent;
(0, _defineProperty2["default"])(TickComponent, "propTypes", {
  defineChart: _propTypes["default"].bool,
  error: _propTypes["default"].any
});
TickComponent.propTypes = {
  categories: _propTypes["default"].array,
  xBand: _propTypes["default"].func,
  bandWidth: _propTypes["default"].number,
  barWidth: _propTypes["default"].number,
  rotate: _propTypes["default"].number,
  top: _propTypes["default"].number,
  x: _propTypes["default"].number,
  y: _propTypes["default"].number,
  graphProps: _propTypes["default"].object,
  formattedValue: _propTypes["default"].string,
  onChangeCategory: _propTypes["default"].func,
  onChange: _propTypes["default"].func,
  classes: _propTypes["default"].object,
  error: _propTypes["default"].object,
  defineChart: _propTypes["default"].bool,
  chartingOptions: _propTypes["default"].object,
  changeInteractiveEnabled: _propTypes["default"].bool,
  changeEditableEnabled: _propTypes["default"].bool
};

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

  var _super2 = _createSuper(RawChartAxes);

  function RawChartAxes() {
    var _this3;

    (0, _classCallCheck2["default"])(this, RawChartAxes);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this3 = _super2.call.apply(_super2, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this3), "state", {
      height: 0
    });
    return _this3;
  }

  (0, _createClass2["default"])(RawChartAxes, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var height = document.getElementById('hiddenLabel') ? document.getElementById('hiddenLabel').offsetHeight : 0;
      this.setState({
        height: height
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props6 = this.props,
          classes = _this$props6.classes,
          graphProps = _this$props6.graphProps,
          xBand = _this$props6.xBand,
          leftAxis = _this$props6.leftAxis,
          onChange = _this$props6.onChange,
          onChangeCategory = _this$props6.onChangeCategory,
          _this$props6$categori = _this$props6.categories,
          categories = _this$props6$categori === void 0 ? [] : _this$props6$categori,
          top = _this$props6.top,
          defineChart = _this$props6.defineChart,
          chartingOptions = _this$props6.chartingOptions,
          changeInteractiveEnabled = _this$props6.changeInteractiveEnabled,
          changeEditableEnabled = _this$props6.changeEditableEnabled,
          theme = _this$props6.theme,
          error = _this$props6.error;
      var axis = classes.axis,
          axisLine = classes.axisLine,
          tick = classes.tick;

      var _ref3 = graphProps || {},
          _ref3$scale = _ref3.scale,
          scale = _ref3$scale === void 0 ? {} : _ref3$scale,
          _ref3$range = _ref3.range,
          range = _ref3$range === void 0 ? {} : _ref3$range,
          _ref3$domain = _ref3.domain,
          domain = _ref3$domain === void 0 ? {} : _ref3$domain,
          _ref3$size = _ref3.size,
          size = _ref3$size === void 0 ? {} : _ref3$size;

      var height = this.state.height;
      var bottomScale = xBand && typeof xBand.rangeRound === 'function' && xBand.rangeRound([0, size.width]);
      var bandWidth = xBand && typeof xBand.bandwidth === 'function' && xBand.bandwidth(); // for chartType "line", bandWidth will be 0, so we have to calculate it

      var barWidth = bandWidth || scale.x && scale.x(domain.max) / categories.length;
      var rowTickValues = (0, _utils.getTickValues)(_objectSpread(_objectSpread({}, range), {}, {
        step: range.labelStep
      }));
      var fontSize = theme && theme.typography ? theme.typography.fontSize : 14;
      var rotate = (0, _utils.getRotateAngle)(fontSize, height);

      var getTickLabelProps = function getTickLabelProps(value) {
        return {
          dy: 4,
          dx: -10 - (value.toLocaleString().length || 1) * 5
        };
      };

      var getTickComponent = function getTickComponent(props) {
        var properties = {
          classes: classes,
          categories: categories,
          xBand: xBand,
          bandWidth: bandWidth,
          barWidth: barWidth,
          rotate: rotate,
          top: top,
          defineChart: defineChart,
          chartingOptions: chartingOptions,
          error: error,
          onChangeCategory: onChangeCategory,
          changeInteractiveEnabled: changeInteractiveEnabled,
          changeEditableEnabled: changeEditableEnabled,
          onChange: onChange,
          graphProps: graphProps,
          x: props.x,
          y: props.y,
          formattedValue: props.formattedValue
        };
        return /*#__PURE__*/_react["default"].createElement(TickComponent, properties);
      };

      return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, leftAxis && /*#__PURE__*/_react["default"].createElement(_axis.AxisLeft, {
        scale: scale.y,
        className: axis,
        axisLineClassName: axisLine,
        tickLength: 10,
        tickClassName: tick,
        tickFormat: function tickFormat(value) {
          return value;
        },
        tickValues: rowTickValues,
        tickLabelProps: getTickLabelProps
      }), /*#__PURE__*/_react["default"].createElement(_axis.AxisBottom, {
        axisLineClassName: axisLine,
        tickClassName: tick,
        scale: bottomScale,
        labelProps: {
          y: 60 + top
        },
        top: scale.y && scale.y(range.min),
        textLabelProps: function textLabelProps() {
          return {
            textAnchor: 'middle'
          };
        },
        tickFormat: function tickFormat(count) {
          return count;
        },
        tickComponent: getTickComponent
      }));
    }
  }]);
  return RawChartAxes;
}(_react["default"].Component);

exports.RawChartAxes = RawChartAxes;
(0, _defineProperty2["default"])(RawChartAxes, "propTypes", {
  bottomScale: _propTypes["default"].func,
  classes: _propTypes["default"].object.isRequired,
  categories: _propTypes["default"].array,
  defineChart: _propTypes["default"].bool,
  error: _propTypes["default"].any,
  graphProps: _plot.types.GraphPropsType.isRequired,
  xBand: _propTypes["default"].func,
  leftAxis: _propTypes["default"].bool,
  onChange: _propTypes["default"].func,
  onChangeCategory: _propTypes["default"].func,
  top: _propTypes["default"].number,
  theme: _propTypes["default"].object,
  chartingOptions: _propTypes["default"].object,
  changeInteractiveEnabled: _propTypes["default"].bool,
  changeEditableEnabled: _propTypes["default"].bool
});
var ChartAxes = (0, _styles.withStyles)(function (theme) {
  return {
    axis: {
      stroke: _renderUi.color.primaryDark(),
      strokeWidth: 2
    },
    axisLine: {
      stroke: _renderUi.color.primaryDark(),
      strokeWidth: 2
    },
    tick: {
      '& > line': {
        stroke: _renderUi.color.primaryDark(),
        strokeWidth: 2
      },
      fill: _renderUi.color.primaryDark(),
      fontFamily: theme.typography.body1.fontFamily,
      fontSize: theme.typography.fontSize,
      textAnchor: 'middle'
    },
    dottedLine: {
      stroke: _renderUi.color.primaryLight(),
      opacity: 0.2
    },
    error: {
      fontSize: theme.typography.fontSize - 2,
      fill: theme.palette.error.main
    }
  };
}, {
  withTheme: true
})(RawChartAxes);
var _default = ChartAxes;
exports["default"] = _default;
//# sourceMappingURL=axes.js.map