"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = exports.RubricType = exports.RawAuthoring = exports.PointConfig = 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 _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

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

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

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

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

var _OutlinedInput = _interopRequireDefault(require("@material-ui/core/OutlinedInput"));

var _InputLabel = _interopRequireDefault(require("@material-ui/core/InputLabel"));

var _Select = _interopRequireDefault(require("@material-ui/core/Select"));

var _FormControl = _interopRequireDefault(require("@material-ui/core/FormControl"));

var _MenuItem = _interopRequireDefault(require("@material-ui/core/MenuItem"));

var _times = _interopRequireDefault(require("lodash/times"));

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

var _FormGroup = _interopRequireDefault(require("@material-ui/core/FormGroup"));

var _FormControlLabel = _interopRequireDefault(require("@material-ui/core/FormControlLabel"));

var _grey = _interopRequireDefault(require("@material-ui/core/colors/grey"));

var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));

var _DragIndicator = _interopRequireDefault(require("@material-ui/icons/DragIndicator"));

var _editableHtml = _interopRequireDefault(require("@pie-lib/editable-html"));

var _reactBeautifulDnd = require("react-beautiful-dnd");

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

var _pointMenu = _interopRequireDefault(require("./point-menu"));

var _range = _interopRequireDefault(require("lodash/range"));

var _configUi = require("@pie-lib/config-ui");

var _renderUi = require("@pie-lib/render-ui");

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:rubric:authoring');

var reorder = function reorder(list, startIndex, endIndex) {
  var result = Array.from(list);

  var _result$splice = result.splice(startIndex, 1),
      _result$splice2 = (0, _slicedToArray2["default"])(_result$splice, 1),
      removed = _result$splice2[0];

  result.splice(endIndex, 0, removed);
  return result;
};

var RubricType = _propTypes["default"].shape({
  excludeZero: _propTypes["default"].bool,
  points: _propTypes["default"].arrayOf(_propTypes["default"].string),
  sampleAnswers: _propTypes["default"].arrayOf(_propTypes["default"].string),
  maxPoints: _propTypes["default"].number,
  rubriclessInstruction: _propTypes["default"].string
});

exports.RubricType = RubricType;
var MaxPoints = (0, _styles.withStyles)(function (theme) {
  return {
    formControl: {
      minWidth: '120px',
      margin: theme.spacing.unit
    }
  };
})(function (props) {
  var value = props.value,
      _onChange = props.onChange,
      max = props.max,
      classes = props.classes;
  return /*#__PURE__*/_react["default"].createElement(_FormControl["default"], {
    className: classes.formControl,
    variant: "outlined"
  }, /*#__PURE__*/_react["default"].createElement(_InputLabel["default"], {
    width: 100,
    htmlFor: "..."
  }, "Max Points"), /*#__PURE__*/_react["default"].createElement(_Select["default"], {
    value: value,
    onChange: function onChange(e) {
      return _onChange(e.target.value);
    },
    input: /*#__PURE__*/_react["default"].createElement(_OutlinedInput["default"], {
      labelWidth: 80
    })
  }, (0, _range["default"])(1, max + 1).map(function (v) {
    return /*#__PURE__*/_react["default"].createElement(_MenuItem["default"], {
      key: "".concat(v),
      value: v
    }, v);
  })));
}); // if the value is null or 'null', the Sample Answer input field for that point will not be dispalyed
// if the value is '', the Sample Answer input field will be empty

var checkSampleAnswer = function checkSampleAnswer(sampleAnswer) {
  return sampleAnswer === null || sampleAnswer === 'null';
};

var PointConfig = (0, _styles.withStyles)(function (theme) {
  return {
    pointConfig: {},
    row: {
      display: 'flex',
      width: '100%',
      position: 'relative'
    },
    editor: {
      width: '100%',
      backgroundColor: "".concat(theme.palette.common.white, " !important")
    },
    dragIndicator: {
      paddingTop: theme.spacing.unit,
      color: _grey["default"][500]
    },
    pointsLabel: {
      color: _grey["default"][500],
      paddingBottom: theme.spacing.unit,
      textTransform: 'uppercase'
    },
    sampleAnswersEditor: {
      paddingLeft: theme.spacing.unit * 3
    },
    pointMenu: {
      position: 'absolute',
      right: 0
    },
    errorText: {
      fontSize: theme.typography.fontSize - 2,
      color: theme.palette.error.main,
      paddingLeft: theme.spacing.unit * 3,
      paddingTop: theme.spacing.unit
    }
  };
})(function (props) {
  var points = props.points,
      content = props.content,
      classes = props.classes,
      sampleAnswer = props.sampleAnswer,
      _props$mathMlOptions = props.mathMlOptions,
      mathMlOptions = _props$mathMlOptions === void 0 ? {} : _props$mathMlOptions,
      error = props.error,
      _props$pluginOpts = props.pluginOpts,
      pluginOpts = _props$pluginOpts === void 0 ? {} : _props$pluginOpts,
      excludeZero = props.excludeZero,
      _props$imageSupport = props.imageSupport,
      imageSupport = _props$imageSupport === void 0 ? {} : _props$imageSupport;
  var pointsCount = excludeZero ? points + 1 : points;
  var pointsLabel = "".concat(pointsCount, " ").concat(pointsCount === 1 ? 'pt' : 'pts');
  var showSampleAnswer = checkSampleAnswer(sampleAnswer);
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.pointConfig
  }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    variant: "overline",
    className: classes.pointsLabel
  }, pointsLabel), /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.row
  }, /*#__PURE__*/_react["default"].createElement(_DragIndicator["default"], {
    className: classes.dragIndicator
  }), /*#__PURE__*/_react["default"].createElement(_editableHtml["default"], {
    className: classes.editor,
    error: error,
    pluginProps: pluginOpts,
    markup: content,
    onChange: props.onChange,
    mathMlOptions: mathMlOptions,
    imageSupport: imageSupport,
    languageCharactersProps: [{
      language: 'spanish'
    }, {
      language: 'special'
    }]
  }), /*#__PURE__*/_react["default"].createElement(_pointMenu["default"], {
    classes: {
      icon: classes.pointMenu
    },
    showSampleAnswer: showSampleAnswer,
    onChange: props.onMenuChange
  })), error && /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.errorText
  }, error), !showSampleAnswer && /*#__PURE__*/_react["default"].createElement("div", {
    className: classes.sampleAnswersEditor
  }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
    variant: "overline",
    className: classes.dragIndicator
  }, "Sample Response"), /*#__PURE__*/_react["default"].createElement(_editableHtml["default"], {
    className: classes.editor,
    markup: sampleAnswer,
    pluginProps: pluginOpts,
    onChange: props.onSampleChange,
    mathMlOptions: mathMlOptions,
    imageSupport: imageSupport,
    languageCharactersProps: [{
      language: 'spanish'
    }, {
      language: 'special'
    }]
  })));
});
exports.PointConfig = PointConfig;

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

  var _super = _createSuper(RawAuthoring);

  function RawAuthoring() {
    var _this;

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

    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), "dragEnd", function (result) {
      if (!result.destination) {
        return;
      }

      var _this$props = _this.props,
          value = _this$props.value,
          onChange = _this$props.onChange;
      var points = reorder(value.points, result.source.index, result.destination.index);
      var sampleAnswers = reorder(value.sampleAnswers, result.source.index, result.destination.index);
      onChange(_objectSpread(_objectSpread({}, value), {}, {
        points: points,
        sampleAnswers: sampleAnswers
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeRubriclessInstruction", function (input) {
      var _this$props2 = _this.props,
          value = _this$props2.value,
          onChange = _this$props2.onChange;
      onChange(_objectSpread(_objectSpread({}, value), {}, {
        rubriclessInstruction: input
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeMaxPoints", function (maxPoints) {
      var _this$props3 = _this.props,
          value = _this$props3.value,
          onChange = _this$props3.onChange; // excludeZero should be false and disabled when maxPoints is 1

      var excludeZero = maxPoints === 1 ? false : value.excludeZero;
      onChange(_objectSpread(_objectSpread({}, value), {}, {
        maxPoints: maxPoints,
        excludeZero: excludeZero
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeContent", function (index, content, type) {
      // type could be 'points' or 'sampleAnswers'
      log("changeModel[".concat(type, "]:"), index, content);

      if (type !== 'points' && type !== 'sampleAnswers') {
        return;
      }

      var _this$props4 = _this.props,
          value = _this$props4.value,
          onChange = _this$props4.onChange;
      var items = value[type] && Array.from(value[type]);
      items.splice(index, 1, content);
      log("changeModel[".concat(type, "]:"), items);
      onChange(_objectSpread(_objectSpread({}, value), {}, (0, _defineProperty2["default"])({}, type, items)));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "excludeZeros", function () {
      var _this$props5 = _this.props,
          value = _this$props5.value,
          onChange = _this$props5.onChange;
      onChange(_objectSpread(_objectSpread({}, value), {}, {
        excludeZero: !value.excludeZero
      }));
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onPointMenuChange", function (index, clickedItem) {
      if (clickedItem === 'sample') {
        var value = _this.props.value;
        var sampleAnswers = Array.from(value.sampleAnswers || []);

        if (checkSampleAnswer(sampleAnswers[index])) {
          // an empty string will display an empty Sample Answer input field
          _this.changeContent(index, '', 'sampleAnswers');
        } else {
          // when the content is null or 'null', the Sample Answer input field will not be displayed
          _this.changeContent(index, null, 'sampleAnswers');
        }
      }
    });
    return _this;
  }

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

      var _this$props6 = this.props,
          classes = _this$props6.classes,
          className = _this$props6.className,
          value = _this$props6.value,
          _this$props6$mathMlOp = _this$props6.mathMlOptions,
          mathMlOptions = _this$props6$mathMlOp === void 0 ? {} : _this$props6$mathMlOp,
          _this$props6$config = _this$props6.config,
          config = _this$props6$config === void 0 ? {} : _this$props6$config,
          _this$props6$rubricle = _this$props6.rubricless,
          rubricless = _this$props6$rubricle === void 0 ? false : _this$props6$rubricle,
          _this$props6$pluginOp = _this$props6.pluginOpts,
          pluginOpts = _this$props6$pluginOp === void 0 ? {} : _this$props6$pluginOp,
          _this$props6$imageSup = _this$props6.imageSupport,
          imageSupport = _this$props6$imageSup === void 0 ? {} : _this$props6$imageSup;

      var _ref = value || {},
          _ref$excludeZeroEnabl = _ref.excludeZeroEnabled,
          excludeZeroEnabled = _ref$excludeZeroEnabl === void 0 ? true : _ref$excludeZeroEnabl,
          _ref$maxPointsEnabled = _ref.maxPointsEnabled,
          maxPointsEnabled = _ref$maxPointsEnabled === void 0 ? true : _ref$maxPointsEnabled,
          _ref$errors = _ref.errors,
          errors = _ref$errors === void 0 ? {} : _ref$errors,
          _ref$rubriclessInstru = _ref.rubriclessInstructionEnabled,
          rubriclessInstructionEnabled = _ref$rubriclessInstru === void 0 ? false : _ref$rubriclessInstru,
          _ref$maxPoints = _ref.maxPoints,
          maxPoints = _ref$maxPoints === void 0 ? 10 : _ref$maxPoints; // rubric will contain a max value for maxPoints


      var _ref2 = config || {},
          _ref2$rubriclessInstr = _ref2.rubriclessInstruction,
          rubriclessInstruction = _ref2$rubriclessInstr === void 0 ? {} : _ref2$rubriclessInstr,
          _ref2$maxMaxPoints = _ref2.maxMaxPoints,
          maxMaxPoints = _ref2$maxMaxPoints === void 0 ? 10 : _ref2$maxMaxPoints;

      var _ref3 = errors || {},
          pointsDescriptorsErrors = _ref3.pointsDescriptorsErrors;

      if (value && Number.isFinite(value.maxPoints)) {
        // eslint-disable-next-line no-console
        console.warn('maxPoints is deprecated - remove from model');
      } // for rubric value is computed based on points


      var maxPointsValue = maxPoints;
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: (0, _classnames["default"])(classes["class"], className)
      }, /*#__PURE__*/_react["default"].createElement(_Typography["default"], {
        variant: "h5",
        className: classes.rubricTitle
      }, "Rubric"), /*#__PURE__*/_react["default"].createElement(_FormGroup["default"], {
        row: true
      }, maxPointsEnabled && /*#__PURE__*/_react["default"].createElement(MaxPoints, {
        max: maxMaxPoints < 100 ? maxMaxPoints : 100,
        value: maxPointsValue,
        onChange: this.changeMaxPoints,
        pluginOpts: pluginOpts,
        imageSupport: imageSupport
      }), excludeZeroEnabled && /*#__PURE__*/_react["default"].createElement(_FormControlLabel["default"], {
        label: "Exclude zeros",
        control: /*#__PURE__*/_react["default"].createElement(_Checkbox["default"], {
          className: classes.customColor,
          checked: value.excludeZero,
          onChange: this.excludeZeros,
          disabled: maxPointsValue === 1
        })
      })), rubriclessInstructionEnabled && rubricless && /*#__PURE__*/_react["default"].createElement(_configUi.InputContainer, {
        label: rubriclessInstruction.label,
        className: classes.inputContainer
      }, /*#__PURE__*/_react["default"].createElement(_editableHtml["default"], {
        className: classes.input,
        markup: value.rubriclessInstruction || '',
        onChange: this.changeRubriclessInstruction,
        pluginProps: pluginOpts,
        nonEmpty: false,
        disableUnderline: true,
        languageCharactersProps: [{
          language: 'spanish'
        }, {
          language: 'special'
        }],
        mathMlOptions: mathMlOptions,
        imageSupport: imageSupport
      })), /*#__PURE__*/_react["default"].createElement("div", {
        className: rubricless ? classes.rubricless : classes.container
      }, /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.DragDropContext, {
        onDragEnd: this.dragEnd
      }, /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Droppable, {
        droppableId: "droppable"
      }, function (provided) {
        return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({}, provided.droppableProps, {
          ref: provided.innerRef
        }), value.points.map(function (p, index) {
          return /*#__PURE__*/_react["default"].createElement(_reactBeautifulDnd.Draggable, {
            key: "".concat(p.points, "-").concat(index),
            index: index,
            draggableId: index.toString()
          }, function (provided) {
            return /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
              className: classes.configHolder,
              ref: provided.innerRef
            }, provided.draggableProps, provided.dragHandleProps), /*#__PURE__*/_react["default"].createElement(PointConfig, {
              points: value.points.length - 1 - index,
              content: p,
              error: pointsDescriptorsErrors && pointsDescriptorsErrors[value.points.length - 1 - index],
              sampleAnswer: value.sampleAnswers && value.sampleAnswers[index],
              onChange: function onChange(content) {
                return _this2.changeContent(index, content, 'points');
              },
              onSampleChange: function onSampleChange(content) {
                return _this2.changeContent(index, content, 'sampleAnswers');
              },
              onMenuChange: function onMenuChange(clickedItem) {
                return _this2.onPointMenuChange(index, clickedItem);
              },
              mathMlOptions: mathMlOptions,
              pluginOpts: pluginOpts,
              imageSupport: imageSupport,
              excludeZero: value.excludeZero
            }));
          });
        }), provided.placeholder);
      }))));
    }
  }]);
  return RawAuthoring;
}(_react["default"].Component);

exports.RawAuthoring = RawAuthoring;
(0, _defineProperty2["default"])(RawAuthoring, "propTypes", {
  classes: _propTypes["default"].object.isRequired,
  className: _propTypes["default"].string,
  value: RubricType,
  config: _propTypes["default"].object,
  pluginOpts: _propTypes["default"].object,
  rubricless: _propTypes["default"].bool,
  onChange: _propTypes["default"].func,
  imageSupport: _propTypes["default"].shape({
    add: _propTypes["default"].func.isRequired,
    "delete": _propTypes["default"].func.isRequired
  })
});
(0, _defineProperty2["default"])(RawAuthoring, "defaultProps", {});

var styles = function styles(theme) {
  return {
    container: {
      backgroundColor: _grey["default"][200],
      borderWidth: 1,
      borderStyle: 'solid',
      borderColor: _grey["default"][300],
      padding: theme.spacing.unit * 2,
      margin: theme.spacing.unit
    },
    inputContainer: {
      width: '100%',
      paddingTop: theme.spacing.unit * 2,
      marginBottom: theme.spacing.unit * 2
    },
    rubricless: {
      display: 'none'
    },
    configHolder: {
      paddingTop: theme.spacing.unit,
      paddingBottom: theme.spacing.unit
    },
    rubricTitle: {
      paddingLeft: theme.spacing.unit,
      margin: theme.spacing.unit
    },
    customColor: {
      color: "".concat(_renderUi.color.tertiary(), " !important")
    }
  };
};

var StyledRawAuthoring = (0, _styles.withStyles)(styles)(RawAuthoring);

var Reverse = function Reverse(props) {
  var _ref4 = props || {},
      _ref4$rubricless = _ref4.rubricless,
      rubricless = _ref4$rubricless === void 0 ? false : _ref4$rubricless,
      _ref4$config = _ref4.config,
      config = _ref4$config === void 0 ? {} : _ref4$config,
      _ref4$pluginOpts = _ref4.pluginOpts,
      pluginOpts = _ref4$pluginOpts === void 0 ? {} : _ref4$pluginOpts,
      _ref4$imageSupport = _ref4.imageSupport,
      imageSupport = _ref4$imageSupport === void 0 ? {} : _ref4$imageSupport;

  var points = Array.from(props.value.points || []).reverse();
  var sampleAnswers = Array.from(props.value.sampleAnswers || []).reverse();

  if (points.length > sampleAnswers.length) {
    sampleAnswers = (0, _times["default"])(points.length - sampleAnswers.length).map(function () {
      return null;
    }).concat(sampleAnswers);
  }

  var value = _objectSpread(_objectSpread({}, props.value), {}, {
    points: points,
    sampleAnswers: sampleAnswers
  });

  var onChange = function onChange(value) {
    props.onChange(_objectSpread(_objectSpread({}, value), {}, {
      points: Array.from(value.points || []).reverse(),
      sampleAnswers: Array.from(value.sampleAnswers || []).reverse()
    }));
  };

  return /*#__PURE__*/_react["default"].createElement(StyledRawAuthoring, {
    value: value,
    config: config,
    onChange: onChange,
    rubricless: rubricless,
    pluginOpts: pluginOpts,
    imageSupport: imageSupport
  });
};

Reverse.propTypes = {
  value: RubricType,
  config: _propTypes["default"].object,
  pluginOpts: _propTypes["default"].object,
  rubricless: _propTypes["default"].bool,
  getIndex: _propTypes["default"].func,
  onChange: _propTypes["default"].func,
  imageSupport: _propTypes["default"].shape({
    add: _propTypes["default"].func.isRequired,
    "delete": _propTypes["default"].func.isRequired
  })
};
var _default = Reverse;
exports["default"] = _default;
//# sourceMappingURL=authoring.js.map