"use strict";

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

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

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

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

var _isUndefined = _interopRequireDefault(require("lodash/isUndefined"));

var _inlineDropdown = _interopRequireDefault(require("./inline-dropdown"));

var _dragInTheBlank = _interopRequireDefault(require("./drag-in-the-blank"));

var _explicitConstructedResponse = _interopRequireDefault(require("./explicit-constructed-response"));

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

var _icons = require("./icons");

var log = (0, _debug["default"])('@pie-lib:editable-html:plugins:respArea');
var lastIndexMap = {};
var elTypesMap = {
  'inline-dropdown': 'inline_dropdown',
  'explicit-constructed-response': 'explicit_constructed_response',
  'drag-in-the-blank': 'drag_in_the_blank'
};
var elTypesArray = Object.values(elTypesMap);

function ResponseAreaPlugin(opts) {
  var isOfCurrentType = function isOfCurrentType(d) {
    return d.type === opts.type || d.type === elTypesMap[opts.type];
  };

  var toolbar = {
    icon: /*#__PURE__*/_react["default"].createElement(_icons.ToolbarIcon, null),
    buttonStyles: {
      margin: '0 20px 0 auto'
    },
    onClick: function onClick(value, onChange) {
      log('[toolbar] onClick');
      var change = value.change();
      var currentRespAreaList = change.value.document.filterDescendants(isOfCurrentType);

      if (currentRespAreaList.size >= opts.maxResponseAreas) {
        return;
      }

      var type = opts.type.replace(/-/g, '_');
      var prevIndex = lastIndexMap[type];
      var newIndex = prevIndex === 0 ? prevIndex : prevIndex + 1;
      var newInline = (0, _utils.getDefaultElement)(opts, newIndex);
      lastIndexMap[type] += 1;

      if (newInline) {
        if (change.value.selection.startKey || change.value.selection.endKey) {
          change.insertInline(newInline);
        } else {
          // If the markup is empty and there's no focus
          var lastText = value.document.getLastText();

          if (!lastText) {
            return;
          }

          var parentNode = value.document.getParent(lastText.key);

          if (parentNode) {
            var index = parentNode.nodes.indexOf(lastText.key);
            if (parentNode.isVoid) return;
            change.insertNodeByKey(parentNode.key, index + 1, newInline);
          }
        }

        if (newInline.type === 'drag_in_the_blank') {
          var nextText = change.value.document.getNextText(newInline.key);

          if (nextText) {
            change.moveFocusTo(nextText.key, 0).moveAnchorTo(nextText.key, 0);
          }
        }

        onChange(change);
      }
    },
    customToolbar: opts.respAreaToolbar,
    supports: function supports(node) {
      return node.object === 'inline' && elTypesArray.indexOf(node.type) >= 0;
    },
    showDone: false
  };
  return {
    name: 'response_area',
    toolbar: toolbar,
    filterPlugins: function filterPlugins(node, plugins) {
      if (node.type === 'explicit_constructed_response' || node.type === 'drag_in_the_blank') {
        return [];
      }

      return plugins.filter(function (p) {
        return p.name !== 'response_area';
      });
    },
    deleteNode: function deleteNode(e, node, value, onChange) {
      e.preventDefault();
      var change = value.change().removeNodeByKey(node.key);
      onChange(change);
    },
    renderNode: function renderNode(props) {
      var attributes = props.attributes,
          n = props.node;

      if (n.type === 'explicit_constructed_response') {
        var data = n.data.toJSON();
        var error;

        if (opts.error) {
          error = opts.error();
        }

        return /*#__PURE__*/_react["default"].createElement(_explicitConstructedResponse["default"], {
          attributes: attributes,
          value: data.value,
          error: error && error[data.index] && error[data.index][0]
        });
      }

      if (n.type === 'drag_in_the_blank') {
        var _data = n.data.toJSON();

        return /*#__PURE__*/_react["default"].createElement(_dragInTheBlank["default"], {
          attributes: attributes,
          data: _data,
          n: n,
          nodeProps: props,
          opts: opts
        });
      }

      if (n.type === 'inline_dropdown') {
        var _data2 = n.data.toJSON();

        return /*#__PURE__*/_react["default"].createElement(_inlineDropdown["default"], {
          attributes: attributes,
          selectedItem: _data2.value
        });
      }
    },
    onChange: function onChange(change, editor) {
      var type = opts.type.replace(/-/g, '_');

      if ((0, _isUndefined["default"])(lastIndexMap[type])) {
        lastIndexMap[type] = 0;
        change.value.document.forEachDescendant(function (d) {
          if (d.type === type) {
            var newIndex = parseInt(d.data.get('index'), 10);

            if (newIndex > lastIndexMap[type]) {
              lastIndexMap[type] = newIndex;
            }
          }
        });
      }

      if (!editor.value) {
        return;
      }

      var currentRespAreaList = change.value.document.filterDescendants(isOfCurrentType);
      var oldRespAreaList = editor.value.document.filterDescendants(isOfCurrentType);

      if (currentRespAreaList.size >= opts.maxResponseAreas) {
        toolbar.disabled = true;
      } else {
        toolbar.disabled = false;
      }

      var arrayToFilter = oldRespAreaList.size > currentRespAreaList.size ? oldRespAreaList : currentRespAreaList;
      var arrayToUseForFilter = arrayToFilter === oldRespAreaList ? currentRespAreaList : oldRespAreaList;
      var elementsWithChangedStatus = arrayToFilter.filter(function (d) {
        return !arrayToUseForFilter.find(function (e) {
          return e.data.get('index') === d.data.get('index');
        });
      });

      if (elementsWithChangedStatus.size && oldRespAreaList.size > currentRespAreaList.size) {
        opts.onHandleAreaChange(elementsWithChangedStatus);
      }
    },
    onDrop: function onDrop(event, change, editor) {
      var closestEl = event.target.closest('[data-key]');
      var inline = editor.value.document.findDescendant(function (d) {
        return d.key === closestEl.dataset.key;
      });

      if (inline.type === 'drag_in_the_blank') {
        return false;
      }
    }
  };
}

var serialization = {
  deserialize: function deserialize(el) {
    var type = el.dataset && el.dataset.type;

    switch (type) {
      case 'inline_dropdown':
        return {
          object: 'inline',
          type: 'inline_dropdown',
          isVoid: true,
          data: {
            index: el.dataset.index,
            value: el.dataset.value
          }
        };

      case 'explicit_constructed_response':
        return {
          object: 'inline',
          type: 'explicit_constructed_response',
          isVoid: true,
          data: {
            index: el.dataset.index,
            value: el.dataset.value
          }
        };

      case 'drag_in_the_blank':
        return {
          object: 'inline',
          type: 'drag_in_the_blank',
          isVoid: true,
          data: {
            index: el.dataset.index,
            id: el.dataset.id,
            value: el.dataset.value,
            inTable: el.dataset.inTable
          }
        };
    }
  },
  serialize: function serialize(object) {
    if (object.object !== 'inline') {
      return;
    }

    switch (object.type) {
      case 'inline_dropdown':
        {
          var data = object.data.toJSON();
          return /*#__PURE__*/_react["default"].createElement("span", {
            "data-type": "inline_dropdown",
            "data-index": data.index,
            "data-value": data.value
          });
        }

      case 'explicit_constructed_response':
        {
          var _data3 = object.data.toJSON();

          return /*#__PURE__*/_react["default"].createElement("span", {
            "data-type": "explicit_constructed_response",
            "data-index": _data3.index,
            "data-value": _data3.value
          });
        }

      case 'drag_in_the_blank':
        {
          var _data4 = object.data.toJSON();

          return /*#__PURE__*/_react["default"].createElement("span", {
            "data-type": "drag_in_the_blank",
            "data-index": _data4.index,
            "data-id": _data4.id,
            "data-value": _data4.value,
            "data-in-table": _data4.inTable
          });
        }
    }
  }
};
exports.serialization = serialization;
//# sourceMappingURL=index.js.map