Using MathJax in ClojureScript

419 views Asked by At

I want to use MathJax in a ClojureScript program to typeset some math in a DOM element, not the whole page (which works), just this one particular DOM element. (It's the live preview pane of a Markdown editor that also formats math in the Latex format.)

According to this documentation page on the MathJax site, you can use something like this in JavaScript.

MathJax.Hub.Queue(["Typeset", MathJax.Hub, latex-node]);

I've been using trial and error and have not gotten it right. Something like this:

(defn typeset-latex
  [latex-node]
  (.Queue js/MathJax.Hub ["TypeSet" (.-Hub js/MathJax) latex-node]))

compiles and does not produce any errors when run, but does not yield any output either.

Using the js* macro to try to reproduce the method on the documentation page:

(js* "MathJax.Hub.Queue([\"TypeSet\", MathJax.Hub, \"mde-preview-id\"]);")

produces an error message in the browser stating that "Error: Can't make callback from given data".

ALSO: Assuming I can get the syntax right to get typesetting working in figwheel, any guidance on how to setup the externs file for use with an optimized build would be appreciated.

2

There are 2 answers

1
exupero On BEST ANSWER

You're close. I think you just need to make the Clojure vector into a JavaScript list. You can use the #js reader macro:

(defn typeset-latex
  [latex-node]
  (.Queue js/MathJax.Hub #js ["Typeset" (.-Hub js/MathJax) latex-node]))

Here is a line of code in one of my own projects that's equivalent, though it uses slightly different syntax.

Update: change TypeSet to Typeset.

0
Alan Thompson On

I don't know about MathJax, but this template CLJS project has examples of 3 different ways of performing native JS interop from ClojureScript:


Looking at the MathJax example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>MathJax example</title>
  <script type="text/javascript" async
  src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/latest.js?config=TeX-MML-AM_CHTML" async>
</script>
</head>
<body>
<p>
  When \(a \ne 0\), there are two solutions to \(ax^2 + bx + c = 0\) and they are
  $$x = {-b \pm \sqrt{b^2-4ac} \over 2a}.$$
</p>
</body>
</html>

it seems straightforward. Can you give an example of what you're trying to do?