"use strict";

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

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

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

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

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var _debounce = _interopRequireDefault(require("lodash/debounce"));

var _textSelect = require("@pie-lib/pie-toolbox/text-select");

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

var _Chip = _interopRequireDefault(require("@material-ui/core/Chip"));

var _Info = _interopRequireDefault(require("@material-ui/icons/Info"));

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

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

var _Tooltip = _interopRequireDefault(require("@material-ui/core/Tooltip"));

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

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 Panel = _configUi.settings.Panel,
    toggle = _configUi.settings.toggle,
    radio = _configUi.settings.radio,
    dropdown = _configUi.settings.dropdown;
var log = (0, _debug["default"])('@pie-element:select-text:configure');

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

  var _super = _createSuper(Design);

  function Design(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Design);
    _this = _super.call(this, props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "updateText", (0, _debounce["default"])(function (val) {
      _this.apply(function (u) {
        u.text = val;
        u.tokens = [];
      });
    }, 200));
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeText", function (event) {
      return _this.updateText(event.target.value);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeTokens", function (tokens, mode) {
      _this.apply(function (u) {
        u.tokens = tokens;
        u.mode = mode;
        var correctTokenCount = tokens.filter(function (t) {
          return t.correct;
        }).length;
        var max = isFinite(u.maxSelections) ? u.maxSelections : 0;
        u.maxSelections = Math.max(max, correctTokenCount);
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeMaxSelections", function (event, max) {
      _this.apply(function (u) {
        return u.maxSelections = max;
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "apply", function (fn) {
      var _this$props = _this.props,
          onModelChanged = _this$props.onModelChanged,
          model = _this$props.model;
      var update = (0, _cloneDeep["default"])(model);
      fn(update);
      onModelChanged(update);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changeFeedback", function (feedback) {
      _this.apply(function (u) {
        return u.feedback = feedback;
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "changePartialScoring", function (partialScoring) {
      var _this$props2 = _this.props,
          onModelChanged = _this$props2.onModelChanged,
          model = _this$props2.model;
      var update = (0, _cloneDeep["default"])(model);
      update.partialScoring = partialScoring;
      onModelChanged(update);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onPromptChanged", function (prompt) {
      var _this$props3 = _this.props,
          onModelChanged = _this$props3.onModelChanged,
          model = _this$props3.model;
      var update = (0, _cloneDeep["default"])(model);
      update.prompt = prompt;
      onModelChanged(update);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTeacherInstructionsChanged", function (teacherInstructions) {
      var _this$props4 = _this.props,
          onModelChanged = _this$props4.onModelChanged,
          model = _this$props4.model;
      var update = (0, _cloneDeep["default"])(model);
      update.teacherInstructions = teacherInstructions;
      onModelChanged(update);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onRationaleChanged", function (rationale) {
      var _this$props5 = _this.props,
          onModelChanged = _this$props5.onModelChanged,
          model = _this$props5.model;
      onModelChanged(_objectSpread(_objectSpread({}, model), {}, {
        rationale: rationale
      }));
    });
    var _model = _this.props.model;
    _this.state = {
      text: _model && _model.text || ''
    };
    return _this;
  }

  (0, _createClass2["default"])(Design, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nProps) {
      var model = nProps.model;

      if (model && model.text) {
        this.setState({
          text: model.text
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _configuration$teache, _configuration$prompt, _configuration$ration;

      var textValue = this.state.text;
      var _this$props6 = this.props,
          classes = _this$props6.classes,
          configuration = _this$props6.configuration,
          imageSupport = _this$props6.imageSupport,
          model = _this$props6.model,
          onConfigurationChanged = _this$props6.onConfigurationChanged,
          onModelChanged = _this$props6.onModelChanged,
          uploadSoundSupport = _this$props6.uploadSoundSupport;

      var _ref = configuration || {},
          _ref$baseInputConfigu = _ref.baseInputConfiguration,
          baseInputConfiguration = _ref$baseInputConfigu === void 0 ? {} : _ref$baseInputConfigu,
          _ref$correctAnswer = _ref.correctAnswer,
          correctAnswer = _ref$correctAnswer === void 0 ? {} : _ref$correctAnswer,
          _ref$contentDimension = _ref.contentDimensions,
          contentDimensions = _ref$contentDimension === void 0 ? {} : _ref$contentDimension,
          _ref$feedback = _ref.feedback,
          feedback = _ref$feedback === void 0 ? {} : _ref$feedback,
          _ref$highlightChoices = _ref.highlightChoices,
          highlightChoices = _ref$highlightChoices === void 0 ? {} : _ref$highlightChoices,
          _ref$mode = _ref.mode,
          mode = _ref$mode === void 0 ? {} : _ref$mode,
          _ref$partialScoring = _ref.partialScoring,
          partialScoring = _ref$partialScoring === void 0 ? {} : _ref$partialScoring,
          _ref$prompt = _ref.prompt,
          prompt = _ref$prompt === void 0 ? {} : _ref$prompt,
          _ref$rationale = _ref.rationale,
          rationale = _ref$rationale === void 0 ? {} : _ref$rationale,
          _ref$selectionCount = _ref.selectionCount,
          selectionCount = _ref$selectionCount === void 0 ? {} : _ref$selectionCount,
          _ref$selections = _ref.selections,
          selections = _ref$selections === void 0 ? {} : _ref$selections,
          settingsPanelDisabled = _ref.settingsPanelDisabled,
          _ref$scoringType = _ref.scoringType,
          scoringType = _ref$scoringType === void 0 ? {} : _ref$scoringType,
          _ref$spellCheck = _ref.spellCheck,
          spellCheck = _ref$spellCheck === void 0 ? {} : _ref$spellCheck,
          _ref$studentInstructi = _ref.studentInstructions,
          studentInstructions = _ref$studentInstructi === void 0 ? {} : _ref$studentInstructi,
          _ref$teacherInstructi = _ref.teacherInstructions,
          teacherInstructions = _ref$teacherInstructi === void 0 ? {} : _ref$teacherInstructi,
          _ref$text = _ref.text,
          text = _ref$text === void 0 ? {} : _ref$text,
          _ref$tokens = _ref.tokens,
          tokens = _ref$tokens === void 0 ? {} : _ref$tokens,
          _ref$maxImageWidth = _ref.maxImageWidth,
          maxImageWidth = _ref$maxImageWidth === void 0 ? {} : _ref$maxImageWidth,
          _ref$maxImageHeight = _ref.maxImageHeight,
          maxImageHeight = _ref$maxImageHeight === void 0 ? {} : _ref$maxImageHeight,
          _ref$withRubric = _ref.withRubric,
          withRubric = _ref$withRubric === void 0 ? {} : _ref$withRubric,
          _ref$mathMlOptions = _ref.mathMlOptions,
          mathMlOptions = _ref$mathMlOptions === void 0 ? {} : _ref$mathMlOptions,
          _ref$language = _ref.language,
          language = _ref$language === void 0 ? {} : _ref$language,
          _ref$languageChoices = _ref.languageChoices,
          languageChoices = _ref$languageChoices === void 0 ? {} : _ref$languageChoices;

      var _ref2 = model || {},
          errors = _ref2.errors,
          extraCSSRules = _ref2.extraCSSRules,
          feedbackEnabled = _ref2.feedbackEnabled,
          promptEnabled = _ref2.promptEnabled,
          rationaleEnabled = _ref2.rationaleEnabled,
          spellCheckEnabled = _ref2.spellCheckEnabled,
          teacherInstructionsEnabled = _ref2.teacherInstructionsEnabled,
          toolbarEditorPosition = _ref2.toolbarEditorPosition;

      var _ref3 = errors || {},
          promptError = _ref3.prompt,
          rationaleError = _ref3.rationale,
          selectionsError = _ref3.selectionsError,
          teacherInstructionsError = _ref3.teacherInstructions,
          tokensError = _ref3.tokensError;

      var validationMessage = (0, _utils.generateValidationMessage)(configuration);
      var defaultImageMaxWidth = maxImageWidth && maxImageWidth.prompt;
      var defaultImageMaxHeight = maxImageHeight && maxImageHeight.prompt;
      var tokensModel = model.tokens;
      tokensModel = tokensModel || [];
      var toolbarOpts = {
        position: toolbarEditorPosition === 'top' ? 'top' : 'bottom'
      };
      log('[render] maxSelections:', model.maxSelections);
      var panelSettings = {
        partialScoring: partialScoring.settings && toggle(partialScoring.label),
        highlightChoices: highlightChoices.settings && toggle(highlightChoices.label),
        feedbackEnabled: feedback.settings && toggle(feedback.label),
        'language.enabled': language.settings && toggle(language.label, true),
        language: language.settings && language.enabled && dropdown(languageChoices.label, languageChoices.options)
      };
      var panelProperties = {
        teacherInstructionsEnabled: teacherInstructions.settings && toggle(teacherInstructions.label),
        studentInstructionsEnabled: studentInstructions.settings && toggle(studentInstructions.label),
        promptEnabled: prompt.settings && toggle(prompt.label),
        rationaleEnabled: rationale.settings && toggle(rationale.label),
        spellCheckEnabled: spellCheck.settings && toggle(spellCheck.label),
        scoringType: scoringType.settings && radio(scoringType.label, ['auto', 'rubric']),
        rubricEnabled: (withRubric === null || withRubric === void 0 ? void 0 : withRubric.settings) && toggle(withRubric === null || withRubric === void 0 ? void 0 : withRubric.label)
      };

      var getPluginProps = function getPluginProps() {
        var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return _objectSpread(_objectSpread({}, baseInputConfiguration), props);
      };

      return /*#__PURE__*/_react["default"].createElement(_configUi.layout.ConfigLayout, {
        extraCSSRules: extraCSSRules,
        dimensions: contentDimensions,
        hideSettings: settingsPanelDisabled,
        settings: /*#__PURE__*/_react["default"].createElement(Panel, {
          model: model,
          configuration: configuration,
          onChangeModel: function onChangeModel(model) {
            return onModelChanged(model);
          },
          onChangeConfiguration: onConfigurationChanged,
          groups: {
            Settings: panelSettings,
            Properties: panelProperties
          }
        })
      }, teacherInstructionsEnabled && /*#__PURE__*/_react["default"].createElement(_configUi.InputContainer, {
        label: teacherInstructions.label,
        className: classes.promptHolder
      }, /*#__PURE__*/_react["default"].createElement(_editableHtml.EditableHtml, {
        className: classes.prompt,
        markup: model.teacherInstructions || '',
        onChange: this.onTeacherInstructionsChanged,
        imageSupport: imageSupport,
        nonEmpty: false,
        error: teacherInstructionsError,
        toolbarOpts: toolbarOpts,
        pluginProps: getPluginProps(configuration === null || configuration === void 0 ? void 0 : (_configuration$teache = configuration.teacherInstructions) === null || _configuration$teache === void 0 ? void 0 : _configuration$teache.inputConfiguration),
        spellCheck: spellCheckEnabled,
        maxImageWidth: maxImageWidth && maxImageWidth.teacherInstructions || defaultImageMaxWidth,
        maxImageHeight: maxImageHeight && maxImageHeight.teacherInstructions || defaultImageMaxHeight,
        uploadSoundSupport: uploadSoundSupport,
        languageCharactersProps: [{
          language: 'spanish'
        }, {
          language: 'special'
        }],
        mathMlOptions: mathMlOptions
      }), teacherInstructionsError && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, teacherInstructionsError)), promptEnabled && /*#__PURE__*/_react["default"].createElement(_configUi.InputContainer, {
        label: prompt.label || '',
        className: classes.promptHolder
      }, /*#__PURE__*/_react["default"].createElement(_editableHtml.EditableHtml, {
        className: classes.prompt,
        markup: model.prompt,
        onChange: this.onPromptChanged,
        imageSupport: imageSupport,
        error: promptError,
        toolbarOpts: toolbarOpts,
        pluginProps: getPluginProps(configuration === null || configuration === void 0 ? void 0 : (_configuration$prompt = configuration.prompt) === null || _configuration$prompt === void 0 ? void 0 : _configuration$prompt.inputConfiguration),
        spellCheck: spellCheckEnabled,
        maxImageWidth: defaultImageMaxWidth,
        maxImageHeight: defaultImageMaxHeight,
        uploadSoundSupport: uploadSoundSupport,
        languageCharactersProps: [{
          language: 'spanish'
        }, {
          language: 'special'
        }],
        mathMlOptions: mathMlOptions
      }), promptError && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, promptError)), text.settings && /*#__PURE__*/_react["default"].createElement(_configUi.InputContainer, {
        label: text.label || '',
        className: classes.promptHolder
      }, /*#__PURE__*/_react["default"].createElement(_TextField["default"], {
        className: classes.input,
        multiline: true,
        defaultValue: textValue,
        onChange: this.changeText,
        spellCheck: spellCheckEnabled
      })), tokens.settings && /*#__PURE__*/_react["default"].createElement(_configUi.InputContainer, {
        label: tokens.label || '',
        className: classes.tokenizerContainer
      }, /*#__PURE__*/_react["default"].createElement(_Tooltip["default"], {
        classes: {
          tooltip: classes.tooltip
        },
        disableFocusListener: true,
        disableTouchListener: true,
        placement: 'right',
        title: validationMessage
      }, /*#__PURE__*/_react["default"].createElement(_Info["default"], {
        fontSize: 'small',
        color: 'primary',
        style: {
          position: 'absolute',
          left: '48px',
          top: '-3px'
        }
      })), /*#__PURE__*/_react["default"].createElement(_textSelect.Tokenizer, {
        className: classes.tokenizer,
        text: model.text,
        tokens: tokensModel,
        onChange: this.changeTokens
      })), tokensError && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, tokensError), selectionsError && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, selectionsError), /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.tokensDetails
      }, mode.settings && /*#__PURE__*/_react["default"].createElement(_Chip["default"], {
        label: "".concat(mode.label, ": ").concat(model.mode ? model.mode : 'None'),
        className: classes.chip
      }), selections.settings && /*#__PURE__*/_react["default"].createElement(_Chip["default"], {
        label: "".concat(selections.label, ": ").concat(tokensModel.length),
        className: classes.chip
      }), correctAnswer.settings && /*#__PURE__*/_react["default"].createElement(_Chip["default"], {
        label: "".concat(correctAnswer.label, ": ").concat(tokensModel.filter(function (t) {
          return t.correct;
        }).length),
        className: classes.chip
      }), selectionCount.settings && /*#__PURE__*/_react["default"].createElement(_configUi.NumberTextField, {
        min: tokensModel.filter(function (t) {
          return t.correct;
        }).length || 0,
        label: "".concat(selectionCount.label, " (0:any)"),
        max: tokensModel.length,
        value: model.maxSelections,
        onChange: this.changeMaxSelections,
        className: classes.numberField
      })), rationaleEnabled && /*#__PURE__*/_react["default"].createElement(_configUi.InputContainer, {
        label: rationale.label || '',
        className: classes.promptHolder
      }, /*#__PURE__*/_react["default"].createElement(_editableHtml.EditableHtml, {
        className: classes.prompt,
        markup: model.rationale || '',
        onChange: this.onRationaleChanged,
        imageSupport: imageSupport,
        error: rationaleError,
        toolbarOpts: toolbarOpts,
        pluginProps: getPluginProps(configuration === null || configuration === void 0 ? void 0 : (_configuration$ration = configuration.rationale) === null || _configuration$ration === void 0 ? void 0 : _configuration$ration.inputConfiguration),
        spellCheck: spellCheckEnabled,
        maxImageWidth: maxImageWidth && maxImageWidth.rationale || defaultImageMaxWidth,
        maxImageHeight: maxImageHeight && maxImageHeight.rationale || defaultImageMaxHeight,
        uploadSoundSupport: uploadSoundSupport,
        languageCharactersProps: [{
          language: 'spanish'
        }, {
          language: 'special'
        }],
        mathMlOptions: mathMlOptions
      }), rationaleError && /*#__PURE__*/_react["default"].createElement("div", {
        className: classes.errorText
      }, rationaleError)), feedbackEnabled && /*#__PURE__*/_react["default"].createElement(_configUi.FeedbackConfig, {
        feedback: model.feedback,
        onChange: this.changeFeedback,
        toolbarOpts: toolbarOpts
      }));
    }
  }]);
  return Design;
}(_react["default"].Component);

exports.Design = Design;
(0, _defineProperty2["default"])(Design, "propTypes", {
  model: _propTypes["default"].object.isRequired,
  configuration: _propTypes["default"].object.isRequired,
  classes: _propTypes["default"].object.isRequired,
  onModelChanged: _propTypes["default"].func.isRequired,
  onConfigurationChanged: _propTypes["default"].func.isRequired,
  imageSupport: _propTypes["default"].shape({
    add: _propTypes["default"].func.isRequired,
    "delete": _propTypes["default"].func.isRequired
  }),
  uploadSoundSupport: _propTypes["default"].object
});
(0, _defineProperty2["default"])(Design, "defaultProps", {});

var _default = (0, _styles.withStyles)(function (theme) {
  return {
    tokenizerContainer: {
      paddingRight: 0,
      marginRight: 0,
      '&:after': {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        height: '1px',
        content: '""',
        backgroundColor: theme.palette.primary.main
      },
      marginBottom: theme.spacing.unit
    },
    chip: {
      marginTop: theme.spacing.unit / 2,
      marginRight: theme.spacing.unit * 2
    },
    input: {
      width: '100%'
    },
    tokenizer: {
      marginTop: theme.spacing.unit * 2
    },
    mainOpts: {
      width: '100%',
      justifyContent: 'space-between',
      display: 'flex',
      alignItems: 'baseline'
    },
    promptHolder: {
      width: '100%',
      paddingTop: theme.spacing.unit * 2,
      marginBottom: theme.spacing.unit * 2
    },
    tokensDetails: {
      display: 'flex',
      alignItems: 'center',
      flexWrap: 'wrap',
      marginBottom: theme.spacing.unit * 2.5
    },
    numberField: {
      width: '180px',
      margin: "".concat(theme.spacing.unit / 2, "px auto 0")
    },
    tooltip: {
      fontSize: theme.typography.fontSize - 2,
      whiteSpace: 'pre',
      maxWidth: '500px'
    },
    errorText: {
      fontSize: theme.typography.fontSize - 2,
      color: theme.palette.error.main,
      paddingTop: theme.spacing.unit
    }
  };
})(Design);

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