"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getStackData = exports.Row = exports.Line = exports.CHTMLmstack = void 0;

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 _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

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

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

var _Wrapper = require("mathjax-full/js/output/chtml/Wrapper");

var _lodash = _interopRequireDefault(require("lodash"));

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 reduceText = function reduceText(acc, n) {
  if (n.node && n.node.kind === 'text') {
    acc += n.node.text;
  }

  return acc;
};

var Line = /*#__PURE__*/function () {
  function Line() {
    (0, _classCallCheck2["default"])(this, Line);
    this.kind = 'line';
  }

  (0, _createClass2["default"])(Line, [{
    key: "columns",
    get: function get() {
      return [];
    }
  }]);
  return Line;
}();

exports.Line = Line;

var Row = /*#__PURE__*/function () {
  function Row(columns, operator) {
    (0, _classCallCheck2["default"])(this, Row);
    this.kind = 'row';
    this.operator = operator;
    this.columns = columns;
  }

  (0, _createClass2["default"])(Row, [{
    key: "pad",
    value: function pad(count) {
      var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'right';

      if (count < this.columns.length) {
        throw new Error('no');
      }

      var diff = count - this.columns.length;

      var padding = _lodash["default"].times(diff).map(function () {
        return '__pad__';
      });

      return direction === 'right' ? [].concat((0, _toConsumableArray2["default"])(padding), (0, _toConsumableArray2["default"])(this.columns)) : [].concat((0, _toConsumableArray2["default"])(this.columns), (0, _toConsumableArray2["default"])(padding));
    }
  }]);
  return Row;
}();

exports.Row = Row;

var mathNodeToCharArray = function mathNodeToCharArray(mn) {
  var text = mn.childNodes.reduce(reduceText, '');
  return text.split('');
};
/**
 * Convert child a column entry
 * @param {*} child
 * @return an array of column content
 */


var toColumnArray = function toColumnArray(child) {
  if (!child || !child.kind) {
    return [];
  }

  if (child.kind === 'msrow') {
    throw new Error('msrow in msrow?');
  }

  if (child.kind === 'mo') {
    // We are going to treat this operator as a text array.
    // It's probably going to be a decimal point
    // eslint-disable-next-line no-console
    console.warn('mo that is not 1st node in msrow?');
    return mathNodeToCharArray(child); // throw new Error('mo must be first child of msrow');
  }

  if (child.kind === 'mn') {
    return mathNodeToCharArray(child);
  }

  if (child.toCHTML) {
    return child;
  }
};
/**
 *  convert mstack chtml childNodes into a Row
 *  @param child chtml child node of mstack
 *  @return Row | Line
 */


var rowStack = function rowStack(child) {
  if (!child || !child.kind) {
    return;
  }

  if (child.kind === 'msrow') {
    if (!child.childNodes || child.childNodes.length === 0) {
      return new Row([]);
    }

    var f = _lodash["default"].first(child.childNodes);

    var nodes = f && f.kind === 'mo' ? _lodash["default"].tail(child.childNodes) : child.childNodes;

    var columns = _lodash["default"].flatten(nodes.map(toColumnArray));

    return new Row(columns, f.kind === 'mo' ? f : undefined);
  }

  if (child.kind === 'mn') {
    var _columns = mathNodeToCharArray(child);

    return new Row(_columns, undefined);
  }

  if (child.kind === 'mo') {
    // eslint-disable-next-line no-console
    console.warn('mo on its own row?');
    return new Row([], child);
  }

  if (child.kind === 'msline') {
    return new Line();
  }

  if (child.toCHTML) {
    return new Row([child]);
  }
};
/** convert MathJax chtml tree to Row[]
 * @param mstack the root of the mathjax chtml tree
 * @return Row[]
 */


var getStackData = function getStackData(mstack) {
  if (!mstack || !mstack.childNodes) {
    return [];
  }

  return _lodash["default"].compact(mstack.childNodes.map(rowStack));
};

exports.getStackData = getStackData;

var CHTMLmstack = /*#__PURE__*/function (_CHTMLWrapper) {
  (0, _inherits2["default"])(CHTMLmstack, _CHTMLWrapper);

  var _super = _createSuper(CHTMLmstack);

  function CHTMLmstack(factory, node) {
    var _this;

    var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
    (0, _classCallCheck2["default"])(this, CHTMLmstack);
    _this = _super.call(this, factory, node, parent);
    _this.ce = _this.adaptor.document.createElement.bind(_this.adaptor.document);
    return _this;
  }

  (0, _createClass2["default"])(CHTMLmstack, [{
    key: "toCHTML",
    value: function toCHTML(parent) {
      var _this2 = this;

      var chtml = this.standardCHTMLnode(parent);
      var stackData = getStackData(this); // console.log('stackData', stackData);

      var maxCols = stackData.reduce(function (acc, r) {
        if (r && r.columns.length > acc) {
          acc = r.columns.length;
        }

        return acc;
      }, 0);
      var table = this.ce('table');
      chtml.appendChild(table);
      stackData.forEach(function (row) {
        var tr = _this2.ce('tr');

        table.appendChild(tr);

        if (row.kind === 'row') {
          var td = _this2.ce('td');

          tr.appendChild(td);

          if (row.operator && row.operator.toCHTML) {
            td.setAttribute('class', 'inner');
            row.operator.toCHTML(td);
          } else {
            td.textContent = '';
          } // align right for now:


          var cols = row.pad(maxCols, 'right');
          cols.forEach(function (c) {
            var t = _this2.ce('td');

            tr.appendChild(t);

            if (c === '__pad__') {
              t.textContent = '';
            } else if (typeof c === 'string') {
              t.textContent = c;
            } else if (c.kind === 'none') {
              t.textContent = '';
            } else if (c.toCHTML) {
              t.setAttribute('class', 'inner');
              c.toCHTML(t);
            }
          });
        } else if (row.kind === 'line') {
          var _td = _this2.ce('td');

          tr.appendChild(_td);

          _td.setAttribute('colspan', maxCols + 1);

          _td.setAttribute('class', 'mjx-line');

          _td.textContent = '';
        }
      });
    }
  }]);
  return CHTMLmstack;
}(_Wrapper.CHTMLWrapper);

exports.CHTMLmstack = CHTMLmstack;
CHTMLmstack.styles = {
  'mjx-mstack > table': {
    'line-height': 'initial',
    border: 'solid 0px red',
    'border-spacing': '0em',
    'border-collapse': 'separate'
  },
  'mjx-mstack > table > tr': {
    'line-height': 'initial'
  },
  'mjx-mstack > table > tr > td': {
    // padding: '1.2rem',
    border: 'solid 0px blue',
    'font-family': 'sans-serif',
    'line-height': 'initial'
  },
  'mjx-mstack > table > tr > td.inner': {
    'font-family': 'inherit'
  },
  'mjx-mstack > table > tr > .mjx-line': {
    padding: 0,
    'border-top': 'solid 1px black'
  },
  '.TEX-A': {
    'font-family': 'MJXZERO, MJXTEX !important'
  }
};
//# sourceMappingURL=chtml.js.map