Skip to content

Instantly share code, notes, and snippets.

@7shi
Last active October 15, 2019 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7shi/396eb8b7e1bb547667b03d996cb24ee0 to your computer and use it in GitHub Desktop.
Save 7shi/396eb8b7e1bb547667b03d996cb24ee0 to your computer and use it in GitHub Desktop.
[F#] Fable + MathJax
open System
open Fable.Core
open Fable.Core.JsInterop
open Browser.Types
open Browser
// ref. https://medium.com/@zaid.naom/f-interop-with-javascript-in-fable-the-complete-guide-ccc5b896a59f
[<Emit("convert($0, $1)")>]
let render output (input:string): unit = jsNative
let matrix m = seq {
yield @"\left(\begin{matrix}"
for ms in m do
yield String.concat " & " ms + @" \\"
yield @"\end{matrix}\right)" }
seq {
let v = [["a"]; ["b"]; ["c"]]
let w = [["d" ; "e" ; "f"]]
yield! matrix v
yield! matrix w
yield "="
yield! v |> Seq.mapi (fun i r ->
w.[0] |> Seq.mapi (fun j c ->
if i = j then "inner" else "exterior"
|> sprintf @"\underbrace{%s%s}_{%s}" r.[0] c))
|> matrix }
|> String.concat System.Environment.NewLine
|> render (document.getElementById "math")
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<!-- ref. https://github.com/mathjax/MathJax-demos-web/blob/master/input-tex2chtml.md -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
</script>
</head>
<body>
<div id="math"></div>
<script>
function convert(output, input) {
output.innerHTML = '';
MathJax.texReset();
var options = MathJax.getMetricsFor(output);
options.display = true;
MathJax.tex2chtmlPromise(input, options).then(function (node) {
//
// The promise returns the typeset node, which we add to the output
// Then update the document to include the adjusted CSS for the
// content of the new equation.
//
output.appendChild(node);
MathJax.startup.document.clear();
MathJax.startup.document.updateDocument();
}).catch(function (err) {
//
// If there was an error, put the message into the output instead
//
var pre = output.appendChild(document.createElement('pre'));
pre.appendChild(document.createTextNode(err.message));
pre.appendChild(document.createTextNode(input));
});
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment