"use strict";

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

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

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

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

var _get = _interopRequireDefault(require("lodash/get"));

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

var _serialization = require("./serialization");

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

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 Paragraph = (0, _styles.withStyles)(function (theme) {
  return {
    para: {
      paddingTop: 2 * theme.spacing.unit,
      paddingBottom: 2 * theme.spacing.unit
    }
  };
})(function (props) {
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: props.classes.para
  }, props.children);
});
var Spacer = (0, _styles.withStyles)(function () {
  return {
    spacer: {
      display: 'inline-block',
      width: '.75em'
    }
  };
})(function (props) {
  return /*#__PURE__*/_react["default"].createElement("span", {
    className: props.classes.spacer
  });
});
var restrictWhitespaceTypes = ['tbody', 'tr'];

var addText = function addText(parentNode, text) {
  var isWhitespace = text.trim() === '';
  var parentType = parentNode && parentNode.type;

  if (isWhitespace && restrictWhitespaceTypes.includes(parentType)) {
    return undefined;
  } else {
    return text;
  }
};

var getMark = function getMark(n) {
  var mark = n.leaves.find(function (leave) {
    return (0, _get["default"])(leave, 'marks', []).length;
  });

  if (mark) {
    return mark.marks[0];
  }

  return null;
};

var renderChildren = function renderChildren(layout, value, onChange, rootRenderChildren, parentNode, elementType) {
  if (!value) {
    return null;
  }

  var children = [];
  (layout.nodes || []).forEach(function (n, index) {
    var key = n.type ? "".concat(n.type, "-").concat(index) : "".concat(index);

    if (n.isMath) {
      children.push( /*#__PURE__*/_react["default"].createElement("span", {
        dangerouslySetInnerHTML: {
          __html: "<math displaystyle=\"true\">".concat(n.nodes[0].innerHTML, "</math>")
        }
      }));
      return children;
    }

    if (rootRenderChildren) {
      var c = rootRenderChildren(n, value, onChange);

      if (c) {
        children.push(c);

        if ((parentNode === null || parentNode === void 0 ? void 0 : parentNode.type) !== 'td' && elementType === 'drag-in-the-blank') {
          children.push( /*#__PURE__*/_react["default"].createElement(Spacer, {
            key: "spacer-".concat(index)
          }));
        }

        return;
      }
    }

    if (n.object === 'text') {
      var content = n.leaves.reduce(function (acc, l) {
        var t = l.text;
        var extraText = addText(parentNode, t);
        return extraText ? acc + extraText : acc;
      }, '');
      var mark = getMark(n);

      if (mark) {
        var markKey;

        for (markKey in _serialization.MARK_TAGS) {
          if (_serialization.MARK_TAGS[markKey] === mark.type) {
            var Tag = markKey;
            children.push( /*#__PURE__*/_react["default"].createElement(Tag, {
              key: key
            }, content));
            break;
          }
        }
      } else if (content.length > 0) {
        children.push(content);

        if ((parentNode === null || parentNode === void 0 ? void 0 : parentNode.type) !== 'td' && elementType === 'drag-in-the-blank') {
          children.push( /*#__PURE__*/_react["default"].createElement(Spacer, {
            key: "spacer-".concat(index)
          }));
        }
      }
    } else {
      var subNodes = renderChildren(n, value, onChange, rootRenderChildren, n, elementType);

      if (n.type === 'p' || n.type === 'paragraph') {
        children.push( /*#__PURE__*/_react["default"].createElement(Paragraph, {
          key: key
        }, subNodes));
      } else {
        var _Tag = n.type;

        if (n.nodes && n.nodes.length > 0) {
          children.push( /*#__PURE__*/_react["default"].createElement(_Tag, (0, _extends2["default"])({
            key: key
          }, n.data.attributes), subNodes));
        } else {
          children.push( /*#__PURE__*/_react["default"].createElement(_Tag, (0, _extends2["default"])({
            key: key
          }, n.data.attributes)));
        }
      }
    }
  });
  return children;
};

exports.renderChildren = renderChildren;
var MaskContainer = (0, _styles.withStyles)(function () {
  return {
    main: {
      display: 'initial'
    },
    tableStyle: {
      '&:not(.MathJax) table': {
        borderCollapse: 'collapse'
      },
      // align table content to left as per STAR requirement PD-3687
      '&:not(.MathJax) table td, &:not(.MathJax) table th': {
        padding: '8px 12px',
        textAlign: 'left'
      }
    }
  };
})(function (props) {
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])(props.classes.main, props.classes.tableStyle)
  }, props.children);
});
/**
 * Renders a layout that uses the slate.js Value model structure.
 */

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

  var _super = _createSuper(Mask);

  function Mask() {
    var _this;

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

    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), "handleChange", function (id, value) {
      var data = _objectSpread(_objectSpread({}, _this.props.value), {}, (0, _defineProperty2["default"])({}, id, value));

      _this.props.onChange(data);
    });
    return _this;
  }

  (0, _createClass2["default"])(Mask, [{
    key: "render",
    value: function render() {
      var _this$props = this.props,
          value = _this$props.value,
          layout = _this$props.layout,
          elementType = _this$props.elementType;
      var children = renderChildren(layout, value, this.handleChange, this.props.renderChildren, null, elementType);
      return /*#__PURE__*/_react["default"].createElement(MaskContainer, null, children);
    }
  }]);
  return Mask;
}(_react["default"].Component);

exports["default"] = Mask;
(0, _defineProperty2["default"])(Mask, "propTypes", {
  renderChildren: _propTypes["default"].func,
  layout: _propTypes["default"].object,
  value: _propTypes["default"].object,
  onChange: _propTypes["default"].func,
  elementType: _propTypes["default"].string
});
//# sourceMappingURL=mask.js.map