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

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

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 _token = _interopRequireWildcard(require("./token"));

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

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

var _clone = _interopRequireDefault(require("lodash/clone"));

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

var _styleUtils = require("../../style-utils");

var _server = require("react-dom/server");

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

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:text-select:token-select');

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

  var _super = _createSuper(TokenSelect);

  function TokenSelect() {
    var _this;

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

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

    _this = _super.call.apply(_super, [this].concat(args));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "selectedCount", function () {
      return _this.props.tokens.filter(function (t) {
        return t.selected;
      }).length;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "canSelectMore", function (selectedCount) {
      var maxNoOfSelections = _this.props.maxNoOfSelections;

      if (maxNoOfSelections === 1) {
        return true;
      }

      log('[canSelectMore] maxNoOfSelections: ', maxNoOfSelections, 'selectedCount: ', selectedCount);
      return maxNoOfSelections <= 0 || isFinite(maxNoOfSelections) && selectedCount < maxNoOfSelections;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "toggleToken", function (event) {
      var target = event.target;
      var _this$props = _this.props,
          tokens = _this$props.tokens,
          animationsDisabled = _this$props.animationsDisabled;
      var tokensCloned = (0, _clone["default"])(tokens);
      var targetSpanWrapper = target.closest(".".concat(_token["default"].rootClassName));
      var targetedTokenIndex = targetSpanWrapper && targetSpanWrapper.dataset && targetSpanWrapper.dataset.indexkey;
      var t = targetedTokenIndex && tokensCloned[targetedTokenIndex]; // don't toggle if we are in print mode, token correctness is defined or if it's missing
      // (missing means that it was evaluated as correct and not selected)

      if (t && t.correct === undefined && !animationsDisabled && !t.isMissing) {
        var _this$props2 = _this.props,
            onChange = _this$props2.onChange,
            maxNoOfSelections = _this$props2.maxNoOfSelections;
        var selected = !t.selected;

        if (maxNoOfSelections === 1 && _this.selectedCount() === 1) {
          var selectedToken = (tokens || []).filter(function (t) {
            return t.selected;
          });
          var updatedTokens = tokensCloned.map(function (token) {
            if ((0, _isEqual["default"])(token, selectedToken[0])) {
              return _objectSpread(_objectSpread({}, token), {}, {
                selected: false
              });
            }

            return _objectSpread(_objectSpread({}, token), {}, {
              selectable: true
            });
          });

          var update = _objectSpread(_objectSpread({}, t), {}, {
            selected: !t.selected
          });

          updatedTokens.splice(targetedTokenIndex, 1, update);
          onChange(updatedTokens);
        } else {
          if (selected && maxNoOfSelections > 0 && _this.selectedCount() >= maxNoOfSelections) {
            log('skip toggle max reached');
            return;
          }

          var _update = _objectSpread(_objectSpread({}, t), {}, {
            selected: !t.selected
          });

          tokensCloned.splice(targetedTokenIndex, 1, _update);
          onChange(tokensCloned);
        }
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "generateTokensInHtml", function () {
      var _this$props3 = _this.props,
          tokens = _this$props3.tokens,
          disabled = _this$props3.disabled,
          highlightChoices = _this$props3.highlightChoices,
          animationsDisabled = _this$props3.animationsDisabled;

      var selectedCount = _this.selectedCount();

      var isLineBreak = function isLineBreak(text) {
        return text === '\n';
      };

      var isNewParagraph = function isNewParagraph(text) {
        return text === '\n\n';
      };

      var reducer = function reducer(accumulator, t, index) {
        var selectable = t.selected || t.selectable && _this.canSelectMore(selectedCount);

        var showCorrectAnswer = t.correct !== undefined && (t.selectable || t.selected);
        var finalAcc = accumulator;

        if (isNewParagraph(t.text)) {
          return finalAcc + '</p><p>';
        }

        if (isLineBreak(t.text)) {
          return finalAcc + '<br>';
        }

        if (selectable && !disabled || showCorrectAnswer || t.selected || t.isMissing || animationsDisabled && t.predefined // if we are in print mode
        ) {
          return finalAcc + (0, _server.renderToString)( /*#__PURE__*/_react["default"].createElement(_token["default"], (0, _extends2["default"])({
            key: index,
            disabled: disabled,
            index: index
          }, t, {
            selectable: selectable,
            highlight: highlightChoices,
            animationsDisabled: animationsDisabled
          })));
        } else {
          return accumulator + t.text;
        }
      };

      var reduceResult = (tokens || []).reduce(reducer, '<p>');
      return reduceResult + '</p>';
    });
    return _this;
  }

  (0, _createClass2["default"])(TokenSelect, [{
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          classes = _this$props4.classes,
          classNameProp = _this$props4.className;
      var className = (0, _classnames["default"])(classes.tokenSelect, classNameProp);
      var html = this.generateTokensInHtml();
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: className,
        dangerouslySetInnerHTML: {
          __html: html
        },
        onClick: this.toggleToken
      });
    }
  }]);
  return TokenSelect;
}(_react["default"].Component);

exports.TokenSelect = TokenSelect;
(0, _defineProperty2["default"])(TokenSelect, "propTypes", {
  tokens: _propTypes["default"].arrayOf(_propTypes["default"].shape(_token.TokenTypes)).isRequired,
  className: _propTypes["default"].string,
  classes: _propTypes["default"].object.isRequired,
  onChange: _propTypes["default"].func.isRequired,
  disabled: _propTypes["default"].bool,
  highlightChoices: _propTypes["default"].bool,
  animationsDisabled: _propTypes["default"].bool,
  maxNoOfSelections: _propTypes["default"].number
});
(0, _defineProperty2["default"])(TokenSelect, "defaultProps", {
  highlightChoices: false,
  maxNoOfSelections: 0,
  tokens: []
});

var _default = (0, _styles.withStyles)(function () {
  return {
    tokenSelect: _objectSpread(_objectSpread({
      backgroundColor: 'none',
      whiteSpace: 'pre'
    }, (0, _styleUtils.noSelect)()), {}, {
      '& p': {
        whiteSpace: 'break-spaces'
      }
    })
  };
})(TokenSelect);

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