"use strict";

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

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

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

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

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

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

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

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

var _reactInputAutosize = _interopRequireDefault(require("react-input-autosize"));

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

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

var _styles2 = require("./common/styles");

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

var _mathRendering = require("../math-rendering");

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 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 styles = function styles(theme) {
  return {
    input: {
      "float": 'right',
      fontFamily: theme.typography.fontFamily,
      fontSize: theme.typography.fontSize,
      border: 'none',
      '&.correct': (0, _styles2.correct)('color'),
      '&.incorrect': (0, _styles2.incorrect)('color'),
      '&.disabled': {
        backgroundColor: 'transparent !important'
      },
      '&.error': {
        border: "2px solid ".concat(theme.palette.error.main)
      }
    },
    mathInput: {
      pointerEvents: 'auto',
      textAlign: 'center',
      fontSize: theme.typography.fontSize + 2,
      fontFamily: theme.typography.fontFamily,
      color: _renderUi.color.primaryDark(),
      paddingTop: theme.typography.fontSize / 2
    },
    disabled: _objectSpread(_objectSpread({}, (0, _styles2.disabled)('color')), {}, {
      backgroundColor: 'transparent !important'
    }),
    error: {
      border: "2px solid ".concat(theme.palette.error.main)
    },
    correct: _objectSpread({}, (0, _styles2.correct)('color')),
    incorrect: _objectSpread({}, (0, _styles2.incorrect)('color')),
    flexContainer: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center'
    }
  };
};

function isFractionFormat(label) {
  var trimmedLabel = (label === null || label === void 0 ? void 0 : label.trim()) || '';
  var fracRegex = new RegExp(/^[1-9]*[0-9]*\s?[1-9][0-9]*\/[1-9][0-9]*$/);
  return fracRegex.test(trimmedLabel);
}

function getLabelMathFormat(label) {
  var trimmedLabel = (label === null || label === void 0 ? void 0 : label.trim()) || '';
  var fraction;
  var mixedNr = '';
  var improperFraction = trimmedLabel.split(' ');

  if (improperFraction[1] && improperFraction[1].includes('/')) {
    fraction = improperFraction[1].split('/') || '';
  } else {
    fraction = (trimmedLabel === null || trimmedLabel === void 0 ? void 0 : trimmedLabel.split('/')) || '';
  }

  var formattedLLabel;

  if (isFractionFormat(label)) {
    if (improperFraction[0] && improperFraction[1]) {
      mixedNr = improperFraction[0];
    }

    formattedLLabel = "\\(".concat(mixedNr, "\\frac{").concat(fraction[0], "}{").concat(fraction[1], "}\\)");
    return formattedLLabel;
  }

  return undefined;
}

var MarkLabel = function MarkLabel(props) {
  var _classNames;

  // eslint-disable-next-line no-unused-vars
  var _useState = (0, _react.useState)(null),
      _useState2 = (0, _slicedToArray2["default"])(_useState, 2),
      input = _useState2[0],
      setInput = _useState2[1];

  var _ref = (0, _react.useCallback)(function (node) {
    return setInput(node);
  }, null);

  var mark = props.mark,
      classes = props.classes,
      disabled = props.disabled,
      externalInputRef = props.inputRef,
      barWidth = props.barWidth,
      rotate = props.rotate,
      correctness = props.correctness,
      autoFocus = props.autoFocus,
      error = props.error,
      isHiddenLabel = props.isHiddenLabel,
      limitCharacters = props.limitCharacters,
      correctnessIndicator = props.correctnessIndicator;

  var _useState3 = (0, _react.useState)(mark.label),
      _useState4 = (0, _slicedToArray2["default"])(_useState3, 2),
      label = _useState4[0],
      setLabel = _useState4[1];

  var _useState5 = (0, _react.useState)(getLabelMathFormat(mark.label)),
      _useState6 = (0, _slicedToArray2["default"])(_useState5, 2),
      mathLabel = _useState6[0],
      setMathLabel = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = (0, _slicedToArray2["default"])(_useState7, 2),
      isEditing = _useState8[0],
      setIsEditing = _useState8[1];

  var root = (0, _react.useRef)(null);

  var onChange = function onChange(e) {
    if (limitCharacters && e.target.value && e.target.value.length > 20) {
      return;
    }

    setLabel(e.target.value);
  };

  var isMathRendering = function isMathRendering() {
    return isEditing === false && mathLabel !== undefined;
  };

  var onChangeProp = function onChangeProp(e) {
    setMathLabel(getLabelMathFormat(mark.label));
    setIsEditing(false);
    props.onChange(e.target.value);
  };

  var extraStyle = {};

  if (rotate) {
    extraStyle = {
      width: 'unset',
      textAlign: 'left'
    };
  } // useState only sets the value once, to synch props to state need useEffect


  (0, _react.useEffect)(function () {
    setLabel(mark.label);
  }, [mark.label]);
  (0, _react.useEffect)(function () {
    (0, _mathRendering.renderMath)(root);
  }, []);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.flexContainer
  }, correctnessIndicator, isMathRendering() ? /*#__PURE__*/_react["default"].createElement("div", {
    ref: function ref(r) {
      root = r;
      externalInputRef(r);
    },
    dangerouslySetInnerHTML: {
      __html: getLabelMathFormat(label)
    },
    className: (0, _classnames["default"])(classes.mathInput, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, classes.disabled, disabled), (0, _defineProperty2["default"])(_classNames, classes.error, error), (0, _defineProperty2["default"])(_classNames, classes.correct, mark.editable && (correctness === null || correctness === void 0 ? void 0 : correctness.label) === 'correct'), (0, _defineProperty2["default"])(_classNames, classes.incorrect, mark.editable && (correctness === null || correctness === void 0 ? void 0 : correctness.label) === 'incorrect'), _classNames)),
    onClick: function onClick() {
      return setIsEditing(true);
    },
    style: {
      minWidth: barWidth,
      position: 'fixed',
      transformOrigin: 'left',
      transform: "rotate(".concat(rotate, "deg)"),
      visibility: isHiddenLabel ? 'hidden' : 'unset',
      marginTop: correctnessIndicator ? '24px' : '0'
    }
  }) : /*#__PURE__*/_react["default"].createElement(_reactInputAutosize["default"], {
    inputRef: function inputRef(r) {
      _ref(r);

      externalInputRef(r);
    },
    autoFocus: isEditing || autoFocus,
    disabled: disabled,
    inputClassName: (0, _classnames["default"])(classes.input, correctness && mark.editable ? correctness.label : null, disabled && 'disabled', error && 'error'),
    inputStyle: _objectSpread({
      minWidth: barWidth,
      textAlign: 'center',
      background: 'transparent',
      boxSizing: 'border-box',
      paddingLeft: 0,
      paddingRight: 0
    }, extraStyle),
    value: label,
    style: {
      position: 'fixed',
      pointerEvents: 'auto',
      top: 0,
      left: 0,
      minWidth: barWidth,
      transformOrigin: 'left',
      transform: "rotate(".concat(rotate, "deg)"),
      visibility: isHiddenLabel ? 'hidden' : 'unset',
      marginTop: correctnessIndicator ? '24px' : '0'
    },
    onChange: onChange,
    onBlur: onChangeProp
  }));
};

exports.MarkLabel = MarkLabel;
MarkLabel.propTypes = {
  autoFocus: _propTypes["default"].bool,
  disabled: _propTypes["default"].bool,
  error: _propTypes["default"].any,
  onChange: _propTypes["default"].func,
  graphProps: _plot.types.GraphPropsType,
  classes: _propTypes["default"].object,
  inputRef: _propTypes["default"].func,
  mark: _propTypes["default"].object,
  barWidth: _propTypes["default"].number,
  rotate: _propTypes["default"].number,
  correctness: _propTypes["default"].shape({
    value: _propTypes["default"].string,
    label: _propTypes["default"].string
  }),
  isHiddenLabel: _propTypes["default"].bool,
  limitCharacters: _propTypes["default"].bool,
  correctnessIndicator: _propTypes["default"].node
};

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

exports["default"] = _default;
//# sourceMappingURL=mark-label.js.map