"use strict";

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

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

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

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

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

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

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

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

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 _mathjax = require("mathjax-full/js/mathjax");

var _assistiveMml = require("mathjax-full/js/a11y/assistive-mml");

var _semanticEnrich = require("mathjax-full/js/a11y/semantic-enrich");

var _MenuHandler = require("mathjax-full/js/ui/menu/MenuHandler");

var _FindMathML2 = require("mathjax-full/js/input/mathml/FindMathML");

var _mathml = require("mathjax-full/js/input/mathml");

var _tex = require("mathjax-full/js/input/tex");

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

var _html = require("mathjax-full/js/handlers/html");

var _browserAdaptor = require("mathjax-full/js/adaptors/browserAdaptor");

var _AllPackages = require("mathjax-full/js/input/tex/AllPackages");

var _system = require("speech-rule-engine/js/common/system");

var _mstack = require("./mstack");

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

var _normalization = require("./normalization");

var _MmlFactory = require("mathjax-full/js/core/MmlTree/MmlFactory");

var _SerializedMmlVisitor = require("mathjax-full/js/core/MmlTree/SerializedMmlVisitor");

var _WrapperFactory = require("mathjax-full/js/output/chtml/WrapperFactory");

var _mspace = require("mathjax-full/js/output/chtml/Wrappers/mspace");

var _HTMLDomStrings = require("mathjax-full/js/handlers/html/HTMLDomStrings");

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; } }

if (typeof window !== 'undefined') {
  (0, _html.RegisterHTMLHandler)((0, _browserAdaptor.browserAdaptor)());

  if (window.MathJax && window.MathJax.Menu) {
    console.log('Prevent MathJax v2 from interfering with v3 MenuHandler');
    delete window.MathJax.Menu;
  }
}

var sreReady = false;
(0, _system.engineReady)().then(function () {
  sreReady = true;
}); // import pkg from '../../package.json';

var visitor = new _SerializedMmlVisitor.SerializedMmlVisitor();

var toMMl = function toMMl(node) {
  return visitor.visitTree(node);
};

var log = (0, _debug["default"])('pie-lib:math-rendering');
var NEWLINE_BLOCK_REGEX = /\\embed\{newLine\}\[\]/g;
var NEWLINE_LATEX = '\\newline ';

var getGlobal = function getGlobal() {
  // TODO does it make sense to use version?
  // const key = `${pkg.name}@${pkg.version.split('.')[0]}`;
  // It looks like Ed made this change when he switched from mathjax3 to mathjax-full
  // I think it was supposed to make sure version 1 (using mathjax3) is not used
  // in combination with version 2 (using mathjax-full)
  // TODO higher level wrappers use this instance of math-rendering, and if 2 different instances are used, math rendering is not working
  //  so I will hardcode this for now until a better solution is found
  var key = '@pie-lib/math-rendering@2';

  if (typeof window !== 'undefined') {
    if (!window[key]) {
      window[key] = {};
    }

    return window[key];
  } else {
    return {};
  }
};
/** Add temporary support for a global singleDollar override
 *  <code>
 *   // This will enable single dollar rendering
 *   window.pie = window.pie || {};
 *   window.pie.mathRendering =  {useSingleDollar: true };
 *  </code>
 */


var defaultOpts = function defaultOpts() {
  return getGlobal().opts || {};
};

var fixMathElement = function fixMathElement(element) {
  if (element.dataset.mathHandled) {
    return;
  }

  var property = 'innerText';

  if (element.textContent) {
    property = 'textContent';
  }

  if (element[property]) {
    element[property] = (0, _normalization.wrapMath)((0, _normalization.unWrapMath)(element[property]).unwrapped); // because mathquill doesn't understand line breaks, sometimes we end up with custom elements on prompts/rationale/etc.
    // we need to replace the custom embedded elements with valid latex that Mathjax can understand

    element[property] = element[property].replace(NEWLINE_BLOCK_REGEX, NEWLINE_LATEX);
    element.dataset.mathHandled = true;
  }
};

exports.fixMathElement = fixMathElement;

var fixMathElements = function fixMathElements() {
  var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
  var mathElements = el.querySelectorAll('[data-latex]');
  mathElements.forEach(function (item) {
    return fixMathElement(item);
  });
};

exports.fixMathElements = fixMathElements;

var adjustMathMLStyle = function adjustMathMLStyle() {
  var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;
  var nodes = el.querySelectorAll('math');
  nodes.forEach(function (node) {
    return node.setAttribute('displaystyle', 'true');
  });
};

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

  var _super = _createSuper(myFindMathML);

  function myFindMathML() {
    (0, _classCallCheck2["default"])(this, myFindMathML);
    return _super.apply(this, arguments);
  }

  (0, _createClass2["default"])(myFindMathML, [{
    key: "processMath",
    value: function processMath(set) {
      var adaptor = this.adaptor;

      for (var _i = 0, _Array$from = Array.from(set); _i < _Array$from.length; _i++) {
        var mml = _Array$from[_i];

        if (adaptor.kind(adaptor.parent(mml)) === 'mjx-assistive-mml') {
          set["delete"](mml);
        }
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(myFindMathML.prototype), "processMath", this).call(this, set);
    }
  }]);
  return myFindMathML;
}(_FindMathML2.FindMathML);

var createMathMLInstance = function createMathMLInstance(opts) {
  var docProvided = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
  opts = opts || defaultOpts();

  if (opts.useSingleDollar) {
    // eslint-disable-next-line
    console.warn('[math-rendering] using $ is not advisable, please use $$..$$ or \\(...\\)');
  }

  var packages = _AllPackages.AllPackages.filter(function (name) {
    return name !== 'bussproofs';
  }); // Bussproofs needs an output jax
  // The autoload extension predefines all the macros from the extensions that haven't been loaded already
  // so that they automatically load the needed extension when they are first used


  packages.push('autoload');
  var macros = {
    parallelogram: "\\lower.2em{\\Huge\\unicode{x25B1}}",
    overarc: '\\overparen',
    napprox: '\\not\\approx',
    longdiv: '\\enclose{longdiv}'
  };
  var texConfig = opts.useSingleDollar ? {
    packages: packages,
    macros: macros,
    inlineMath: [['$', '$'], ['\\(', '\\)']],
    processEscapes: true
  } : {
    packages: packages,
    macros: macros
  };
  var mmlConfig = {
    parseError: function parseError(node) {
      // function to process parsing errors
      // eslint-disable-next-line no-console
      console.log('error:', node);
      this.error(this.adaptor.textContent(node).replace(/\n.*/g, ''));
    },
    FindMathML: new myFindMathML()
  };
  var fontURL = "https://unpkg.com/mathjax-full@".concat(_mathjax.mathjax.version, "/ts/output/chtml/fonts/tex-woff-v2");
  var htmlConfig = {
    fontURL: fontURL,
    wrapperFactory: new _WrapperFactory.CHTMLWrapperFactory(_objectSpread(_objectSpread({}, _WrapperFactory.CHTMLWrapperFactory.defaultNodes), _mstack.chtmlNodes))
  };
  var mml = new _mathml.MathML(mmlConfig);
  var customMmlFactory = new _MmlFactory.MmlFactory(_objectSpread(_objectSpread({}, _MmlFactory.MmlFactory.defaultNodes), _mstack.mmlNodes));
  var classFactory = (0, _semanticEnrich.EnrichHandler)((0, _MenuHandler.MenuHandler)((0, _assistiveMml.AssistiveMmlHandler)(_mathjax.mathjax.handlers.handlesDocument(docProvided))), mml);
  var html = classFactory.create(docProvided, {
    compileError: function compileError(mj, math, err) {
      // eslint-disable-next-line no-console
      console.log('bad math?:', math); // eslint-disable-next-line no-console

      console.error(err);
    },
    typesetError: function typesetError(doc, math, err) {
      // eslint-disable-next-line no-console
      console.log('typeset error'); // eslint-disable-next-line no-console

      console.error(err);
      doc.typesetError(math, err);
    },
    menuOptions: {
      settings: {
        assistiveMml: true,
        collapsible: false,
        explorer: false
      }
    },
    sre: {
      speech: 'deep'
    },
    enrichSpeech: 'deep',
    InputJax: [new _tex.TeX(texConfig), mml],
    OutputJax: new _chtml.CHTML(htmlConfig),
    DomStrings: new _HTMLDomStrings.HTMLDomStrings({
      skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code', 'annotation', 'annotation-xml', 'mjx-assistive-mml', 'mjx-container']
    })
  }); // Note: we must set this *after* mathjax.document (no idea why)

  mml.setMmlFactory(customMmlFactory);
  return html;
};

var enrichSpeechInitialized = false;

var bootstrap = function bootstrap(opts) {
  if (typeof window === 'undefined') {
    return {
      Typeset: function Typeset() {
        return {};
      }
    };
  }

  var html = createMathMLInstance(opts);
  return {
    version: _mathjax.mathjax.version,
    html: html,
    Typeset: function Typeset() {
      var _this = this;

      for (var _len = arguments.length, elements = new Array(_len), _key = 0; _key < _len; _key++) {
        elements[_key] = arguments[_key];
      }

      var attemptRender = function attemptRender() {
        var _updatedDocument$math, _updatedDocument$math2;

        var temporary = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

        var updatedDocument = _this.html.findMath(elements.length ? {
          elements: elements
        } : {}).compile();

        if (!temporary && sreReady) {
          updatedDocument = updatedDocument.enrich();
        }

        updatedDocument = updatedDocument.getMetrics().typeset().assistiveMml().attachSpeech().addMenu().updateDocument();

        if (!enrichSpeechInitialized && (0, _typeof2["default"])((_updatedDocument$math = updatedDocument.math.list) === null || _updatedDocument$math === void 0 ? void 0 : (_updatedDocument$math2 = _updatedDocument$math.next) === null || _updatedDocument$math2 === void 0 ? void 0 : _updatedDocument$math2.data) === 'object') {
          enrichSpeechInitialized = true;
        }

        try {
          var list = updatedDocument.math.list;

          if (list) {
            for (var item = list.next; (0, _typeof2["default"])(item.data) !== 'symbol'; item = item.next) {
              var mathMl = toMMl(item.data.root);
              var parsedMathMl = mathMl.replaceAll('\n', '');
              item.data.typesetRoot.setAttribute('data-mathml', parsedMathMl);
              item.data.typesetRoot.setAttribute('tabindex', '-1');
            }
          }
        } catch (e) {
          // eslint-disable-next-line no-console
          console.error(e.toString());
        }

        updatedDocument.clear();
      };

      if (!enrichSpeechInitialized) {
        attemptRender(true);
      }

      _mathjax.mathjax.handleRetriesFor(function () {
        attemptRender();
      });
    }
  };
};

var renderMath = function renderMath(el, renderOpts) {
  var _getGlobal$instance, _getGlobal$instance2;

  if (window && window.MathJax && window.MathJax.customKey && window.MathJax.customKey == '@pie-lib/math-rendering-accessible@1') {
    return;
  }

  var isString = typeof el === 'string';
  var executeOn = document.body;

  if (isString) {
    var div = document.createElement('div');
    div.innerHTML = el;
    executeOn = div;
  }

  fixMathElements(executeOn);
  adjustMathMLStyle(executeOn);

  if (isString) {
    var html = createMathMLInstance(undefined, executeOn);
    var updatedDocument = html.findMath().compile().getMetrics().typeset().updateDocument();
    var list = updatedDocument.math.list;
    var item = list.next;

    if (!item) {
      return '';
    }

    var mathMl = toMMl(item.data.root);
    var parsedMathMl = mathMl.replaceAll('\n', '');
    return parsedMathMl;
  }

  if (!getGlobal().instance) {
    getGlobal().instance = bootstrap(renderOpts);
  }

  if (!el) {
    log('el is undefined');
    return;
  }

  if (el instanceof Element && (_getGlobal$instance = getGlobal().instance) !== null && _getGlobal$instance !== void 0 && _getGlobal$instance.Typeset) {
    getGlobal().instance.Typeset(el);
  } else if (el.length && (_getGlobal$instance2 = getGlobal().instance) !== null && _getGlobal$instance2 !== void 0 && _getGlobal$instance2.Typeset) {
    var _getGlobal$instance3;

    var arr = Array.from(el);

    (_getGlobal$instance3 = getGlobal().instance).Typeset.apply(_getGlobal$instance3, (0, _toConsumableArray2["default"])(arr));
  }
};
/**
 * This style is added to overried default styling of mjx-mspace Mathjax tag
 * In mathjax src code \newline latex gets parsed to <mjx-mspace></mjx-mspace>,
 * but has the default style
 * 'mjx-mspace': {
  "display": 'in-line',
  "text-align": 'left'
} which prevents it from showing as a newline value
 */


_mspace.CHTMLmspace.styles = {
  'mjx-mspace': {
    display: 'block',
    'text-align': 'center',
    height: '5px'
  }
};
var _default = renderMath;
exports["default"] = _default;
//# sourceMappingURL=render-math.js.map