"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.KeyPad = void 0;

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

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 _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _IconButton = _interopRequireDefault(require("@material-ui/core/IconButton"));

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

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

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

var _green = _interopRequireDefault(require("@material-ui/core/colors/green"));

var _debug = _interopRequireDefault(require("debug"));

var _lodash = _interopRequireDefault(require("lodash"));

var _mathquill = _interopRequireDefault(require("@pie-framework/mathquill"));

var mq = _interopRequireWildcard(require("../mq"));

var _keys = require("../keys");

var _constants = _interopRequireDefault(require("./../shared/constants"));

var _commonMqStyles = require("../mq/common-mq-styles");

var _keysLayout = require("./keys-layout");

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

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 log = (0, _debug["default"])('pie-lib:math-inline:keypad');
var LatexButton = (0, _styles.withStyles)(function (theme) {
  return {
    root: {
      textTransform: 'none',
      padding: 0,
      margin: 0,
      fontSize: '110% !important'
    },
    latexButton: {
      pointerEvents: 'none',
      textTransform: 'none !important',
      '& .mq-scaled.mq-sqrt-prefix': {
        transform: 'scale(1, 0.9) !important'
      },
      '& .mq-sup-only .mq-sup': {
        marginBottom: '0.9px !important'
      },
      '& .mq-empty': {
        backgroundColor: "".concat((0, _colorManipulator.fade)(theme.palette.secondary.main, 0.4), " !important")
      },
      '& .mq-overline .mq-overline-inner': {
        borderTop: '2px solid black'
      },
      '& .mq-non-leaf.mq-overline': {
        borderTop: 'none !important' // fixing PD-4873 - in OT, it has border-top 1px and adds extra line

      },
      '& .mq-overarrow': {
        width: '30px',
        marginTop: '0 !important',
        borderTop: '2px solid black',
        fontFamily: 'Roboto, Helvetica, Arial, sans-serif !important',
        '&.mq-arrow-both': {
          top: '0px !important',
          '& *': {
            lineHeight: '1 !important',
            borderTop: 'none !important' // fixing PD-4873 - in OT, it has border-top 1px and adds extra line,

          },
          '&:before': {
            fontSize: '80%',
            left: 'calc(-13%) !important',
            top: '-0.31em !important'
          },
          '&:after': {
            fontSize: '80% !important',
            right: 'calc(-13%) !important',
            top: '-1.5em'
          },
          '&.mq-empty:before': {
            fontSize: '80%',
            left: 'calc(-13%)',
            top: '-0.26em'
          },
          '&.mq-empty:after': {
            fontSize: '80%',
            right: 'calc(-13%)',
            top: '-0.26em'
          },
          '&.mq-empty': {
            minHeight: '1.4em'
          }
        },
        '&.mq-arrow-right:before': {
          fontSize: '80%',
          right: 'calc(-13%) !important',
          top: '-0.26em !important'
        },
        '& .mq-overarrow-inner': {
          border: 'none !important'
        },
        '& .mq-overarrow-inner .mq-overarrow-inner-right': {
          display: 'none !important'
        }
      },
      '& .mq-root-block': {
        padding: '5px !important'
      },
      '& .mq-overarrow.mq-arrow-both.mq-empty:after': {
        right: '-6px',
        fontSize: '80% !important',
        top: '-3px'
      },
      '& .mq-overarrow.mq-arrow-right.mq-empty:before': {
        right: '-5px',
        fontSize: '80% !important',
        top: '-3px'
      },
      '& .mq-overarrow.mq-arrow-both.mq-empty:before': {
        left: '-6px',
        fontSize: '80% !important',
        top: '-3px'
      },
      '& .mq-longdiv-inner': {
        borderTop: '1px solid !important',
        paddingTop: '1.5px !important'
      },
      '& .mq-parallelogram': {
        lineHeight: 0.85
      },
      '& .mq-overarc': {
        borderTop: '2px solid black !important',
        '& .mq-overline': {
          borderTop: 'none !important' // fixing PD-4873 - in OT, it has border-top 1px and adds extra line

        },
        '& .mq-overline-inner': {
          borderTop: 'none !important',
          paddingTop: '0 !important'
        }
      }
    },
    parallelButton: {
      fontStyle: 'italic !important'
    },
    leftRightArrowButton: {
      '& .mq-overarrow.mq-arrow-both': {
        '& .mq-overline-inner': {
          borderTop: 'none !important',
          paddingTop: '0 !important'
        },
        '&:after': {
          position: 'absolute !important',
          top: '0px !important'
        }
      }
    }
  };
})(function (props) {
  var buttonClass;

  if (props.latex === '\\parallel') {
    buttonClass = (0, _classnames["default"])(props.classes.latexButton, props.mqClassName, props.classes.parallelButton);
  } else if (props.latex === '\\overleftrightarrow{\\overline{}}') {
    buttonClass = (0, _classnames["default"])(props.classes.latexButton, props.mqClassName, props.classes.leftRightArrowButton);
  } else {
    buttonClass = (0, _classnames["default"])(props.classes.latexButton, props.mqClassName);
  }

  try {
    var MQ = _mathquill["default"].getInterface(2);

    var span = document.createElement('span');
    span.innerHTML = '';
    var mathField = MQ.StaticMath(span);
    mathField.parseLatex(props.latex);
    mathField.latex(props.latex);
  } catch (e) {
    // received latex has errors - do not create button
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null);
  }

  return /*#__PURE__*/_react["default"].createElement(_Button["default"], {
    className: (0, _classnames["default"])(props.classes.root, props.className),
    onClick: props.onClick,
    "aria-label": props.ariaLabel
  }, /*#__PURE__*/_react["default"].createElement(mq.Static, {
    className: buttonClass,
    latex: props.latex
  }));
});

var createCustomLayout = function createCustomLayout(layoutObj) {
  if (layoutObj) {
    return {
      gridTemplateColumns: "repeat(".concat(layoutObj.columns, ", minmax(min-content, 150px))"),
      gridTemplateRows: "repeat(".concat(layoutObj.rows, ", minmax(40px, 60px))"),
      gridAutoFlow: 'initial'
    };
  }

  return {};
};

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

  var _super = _createSuper(KeyPad);

  function KeyPad(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, KeyPad);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleKeypadInteraction", function () {
      // Check if the setKeypadInteraction prop is available, which is used for both
      // the language keypad and the special characters keypad
      if (_this.props.setKeypadInteraction) {
        _this.props.setKeypadInteraction(true);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "buttonClick", function (key) {
      log('[buttonClick]', key);
      var onPress = _this.props.onPress;
      onPress(key);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "flowKeys", function (base, extras) {
      var transposed = [].concat((0, _toConsumableArray2["default"])((0, _keysLayout.sortKeys)(base)), (0, _toConsumableArray2["default"])((0, _keysLayout.sortKeys)(extras)));
      return _lodash["default"].flatten(transposed);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "keyIsNotAllowed", function (key) {
      var noDecimal = _this.props.noDecimal;

      if ((key.write === '.' && key.label === '.' || key.write === ',' && key.label === ',') && noDecimal) {
        return true;
      }

      return false;
    });
    _this.keypadRef = /*#__PURE__*/_react["default"].createRef();
    return _this;
  }

  (0, _createClass2["default"])(KeyPad, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$keypadRef;

      var keyPadElement = (_this$keypadRef = this.keypadRef) === null || _this$keypadRef === void 0 ? void 0 : _this$keypadRef.current;
      var mainContainer = keyPadElement === null || keyPadElement === void 0 ? void 0 : keyPadElement.closest(".".concat(_constants["default"].MAIN_CONTAINER_CLASS));
      var currentToolbar = keyPadElement === null || keyPadElement === void 0 ? void 0 : keyPadElement.closest('.pie-toolbar'); // need only for math keyboard so we need also controlledKeypadMode

      if (this.props.controlledKeypadMode && mainContainer && currentToolbar) {
        var mainContainerPosition = mainContainer.getBoundingClientRect();
        var currentToolbarPosition = currentToolbar.getBoundingClientRect();
        var difference = mainContainerPosition.top + mainContainerPosition.height - (currentToolbarPosition.top + currentToolbarPosition.height);

        if (difference < 0) {
          var totalHeight = mainContainerPosition.height + mainContainerPosition.top - difference; // increase the height of the main container if keyboard needs it

          if (mainContainer) {
            mainContainer.style.height = "".concat(totalHeight, "px");
          }
        }
      }

      if (keyPadElement) {
        keyPadElement.addEventListener('touchstart', this.handleKeypadInteraction, true);
        keyPadElement.addEventListener('mousedown', this.handleKeypadInteraction, true);
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var _this$keypadRef2;

      var keyPadElement = (_this$keypadRef2 = this.keypadRef) === null || _this$keypadRef2 === void 0 ? void 0 : _this$keypadRef2.current; // need only for math keyboard

      if (this.props.controlledKeypadMode && keyPadElement) {
        var mainContainer = keyPadElement.closest(".".concat(_constants["default"].MAIN_CONTAINER_CLASS));

        if (mainContainer) {
          mainContainer.style.height = 'unset';
        }
      }

      if (keyPadElement) {
        keyPadElement.removeEventListener('touchstart', this.handleKeypadInteraction, true);
        keyPadElement.removeEventListener('mousedown', this.handleKeypadInteraction, true);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props = this.props,
          classes = _this$props.classes,
          className = _this$props.className,
          baseSet = _this$props.baseSet,
          additionalKeys = _this$props.additionalKeys,
          layoutForKeyPad = _this$props.layoutForKeyPad,
          onFocus = _this$props.onFocus,
          mode = _this$props.mode;
      var noBaseSet = ['non-negative-integers', 'integers', 'decimals', 'fractions', 'item-authoring', 'language'];
      var keysWithoutBaseSet = noBaseSet.includes(mode);
      var allKeys = keysWithoutBaseSet ? this.flowKeys([], additionalKeys || []) : this.flowKeys(baseSet, additionalKeys || []); //, ...sortKeys(additionalKeys)];

      var shift = allKeys.length % 5 ? 1 : 0;

      var style = _objectSpread({
        gridTemplateColumns: "repeat(".concat(Math.floor(allKeys.length / 5) + shift, ", minmax(min-content, 150px))")
      }, createCustomLayout(layoutForKeyPad));

      return /*#__PURE__*/_react["default"].createElement("div", {
        ref: this.keypadRef,
        className: (0, _classnames["default"])(classes.keys, className, classes[mode]),
        style: style,
        onFocus: onFocus
      }, allKeys.map(function (k, index) {
        var onClick = _this2.buttonClick.bind(_this2, k);

        if (!k) {
          return /*#__PURE__*/_react["default"].createElement("span", {
            key: "empty-".concat(index)
          });
        }

        var common = _objectSpread(_objectSpread({
          onClick: onClick,
          className: (0, _classnames["default"])(classes.labelButton, !keysWithoutBaseSet && classes[k.category], classes[k.extraClass], k.label === ',' && classes.comma, k.label === '.' && classes.dot),
          disabled: _this2.keyIsNotAllowed(k),
          key: "".concat(k.label || k.latex || k.command, "-").concat(index)
        }, k.actions || {}), k.extraProps || {});

        if (k.latex) {
          return /*#__PURE__*/_react["default"].createElement(LatexButton, (0, _extends2["default"])({
            latex: k.latex,
            key: index
          }, common, {
            className: classes.latexButton,
            ariaLabel: k.ariaLabel ? k.ariaLabel : k.name || k.label
          }));
        }

        if (k.label) {
          return /*#__PURE__*/_react["default"].createElement(_Button["default"], (0, _extends2["default"])({
            key: index
          }, common, {
            className: (0, _classnames["default"])(common.className, (0, _defineProperty2["default"])({}, classes.deleteButton, k.label === '⌫')),
            "aria-label": k.ariaLabel ? k.ariaLabel : k.name || k.label
          }), k.label);
        } else {
          var Icon = k.icon ? k.icon : 'div';
          return /*#__PURE__*/_react["default"].createElement(_IconButton["default"], (0, _extends2["default"])({
            tabIndex: '-1'
          }, common, {
            key: index
          }), /*#__PURE__*/_react["default"].createElement(Icon, {
            className: classes.icon
          }));
        }
      }));
    }
  }]);
  return KeyPad;
}(_react["default"].Component);

exports.KeyPad = KeyPad;
(0, _defineProperty2["default"])(KeyPad, "propTypes", {
  classes: _propTypes["default"].object.isRequired,
  className: _propTypes["default"].string,
  controlledKeypadMode: _propTypes["default"].bool,
  baseSet: _propTypes["default"].array,
  additionalKeys: _propTypes["default"].array,
  layoutForKeyPad: _propTypes["default"].object,
  onPress: _propTypes["default"].func.isRequired,
  onFocus: _propTypes["default"].func,
  noDecimal: _propTypes["default"].bool,
  setKeypadInteraction: _propTypes["default"].func,
  mode: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].number])
});
(0, _defineProperty2["default"])(KeyPad, "defaultProps", {
  baseSet: _keys.baseSet,
  noDecimal: false
});

var styles = function styles(theme) {
  return {
    keys: _objectSpread(_objectSpread({}, _commonMqStyles.commonMqKeyboardStyles), {}, {
      width: '100%',
      display: 'grid',
      gridTemplateRows: 'repeat(5, minmax(40px, 60px))',
      gridRowGap: '0px',
      gridColumnGap: '0px',
      gridAutoFlow: 'column'
    }),
    character: {
      textTransform: 'initial !important',
      gridTemplateRows: 'repeat(5, minmax(40px, 50px)) !important'
    },
    language: {
      gridTemplateRows: 'repeat(4, minmax(40px, 50px)) !important',
      '& *': {
        fontFamily: 'Roboto, Helvetica, Arial, sans-serif !important'
      }
    },
    holder: {
      position: 'relative',
      width: '100%',
      height: '100%',
      backgroundColor: '#cef',
      borderRadius: 0,
      padding: "".concat(theme.spacing.unit, "px 0 ").concat(theme.spacing.unit, "px 0")
    },
    labelButton: {
      minWidth: 'auto',
      fontSize: '140% !important',
      backgroundColor: (0, _colorManipulator.lighten)(theme.palette.primary.light, 0.5),
      '&:hover': {
        backgroundColor: (0, _colorManipulator.lighten)(theme.palette.primary.light, 0.7)
      },
      borderRadius: 0
    },
    latexButton: {
      minWidth: 'auto',
      borderRadius: 0,
      backgroundColor: (0, _colorManipulator.lighten)(theme.palette.primary.light, 0.5),
      '&:hover': {
        backgroundColor: (0, _colorManipulator.lighten)(theme.palette.primary.light, 0.7)
      }
    },
    deleteButton: {
      '& > span': {
        fontFamily: 'Roboto, Helvetica, Arial, sans-serif !important'
      }
    },
    base: {},
    operators: {
      backgroundColor: (0, _colorManipulator.lighten)(theme.palette.secondary.light, 0.5),
      '&:hover': {
        backgroundColor: (0, _colorManipulator.lighten)(theme.palette.secondary.light, 0.7)
      }
    },
    comparison: {
      backgroundColor: (0, _colorManipulator.lighten)(_green["default"][500], 0.5),
      '&:hover': {
        backgroundColor: (0, _colorManipulator.lighten)(_green["default"][500], 0.7)
      }
    },
    comma: {
      fontSize: '200% !important',
      lineHeight: '100%'
    },
    dot: {
      fontSize: '200% !important',
      lineHeight: '100%'
    },
    icon: {
      height: '30px'
    }
  };
};

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

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