Introducing Discourse Chat (BETA)

It seems that discourse-math is broken in chat, at least for KaTeX, and this script fixes it:

script
;(function () {
    
var loadScript = require("discourse/lib/load-script").default;

function ensureKaTeX() {
  return loadScript("/plugins/discourse-math/katex/katex.min.js").then(function () {
    return loadScript("/plugins/discourse-math/katex/katex.min.css", {
      css: true,
    }).then(function () {
      return loadScript("/plugins/discourse-math/katex/mhchem.min.js");
    });
  });
}

function decorate(elem) {
  var $elem = $(elem);
  var displayMode = elem.tagName === "DIV";

  if ($elem.data("applied-katex")) {
    return;
  }
  $elem.data("applied-katex", true);

  if ($elem.hasClass("math")) {
    var tag = elem.tagName === "DIV" ? "div" : "span";
    var displayClass = tag === "div" ? "block-math" : "inline-math";
    var text = $elem.text();
    $elem.addClass(`math-container ${displayClass} katex-math`).text("");
    window.katex.render(text, elem, { displayMode });
  }
}

function katex($elem) {
  if (!$elem || !$elem.find) {
    return;
  }

  const mathElems = $elem.find(".math");

  if (mathElems.length > 0) {
    ensureKaTeX().then(function () {
      mathElems.each(function (idx, elem) { decorate(elem) });
    });
  }
}

setInterval(function () {
    Array.from(document.querySelectorAll('.tc-message-container')).forEach(function (el) { katex(Discourse.$(el)) })
}, 1000)

})()
3 Likes