From 1a73d60e5eac7a0a23af5edd97c4f6532c791a8f Mon Sep 17 00:00:00 2001 From: Guo Date: Mon, 29 Apr 2019 13:10:04 +0800 Subject: [PATCH 1/3] feat: add support for MathJax --- README.md | 33 ++++++++++++++++++++++++++++++--- src/Renderer.js | 25 +++++++++++++++++++++---- static/samples.html.template | 29 +++++++++++++++++++++++++++-- 3 files changed, 78 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 71aea5f..56e3424 100644 --- a/README.md +++ b/README.md @@ -30,9 +30,36 @@ your HTML files: ``` -Pseudocode.js depends on [KaTeX](https://github.com/Khan/KaTeX) to render math -formulas and uses KaTeX's fonts to render texts. So make sure that [KaTeX is -setup](https://github.com/Khan/KaTeX#usage) properly. +Pseudocode.js can use either [KaTeX](https://github.com/Khan/KaTeX) or [MathJax](https://www.mathjax.org/) to render math +formulas and uses some KaTeX's fonts **(KaTeX's CSS)** to render styled texts. + +#### For KaTeX users +Include these 2 tags in ``: +```html + + +``` + +#### For MathJax users +Include these 3 tags in ``: +```html + + + +``` Assume the pseudocode to be rendered is in a `
` DOM element:
 ```html
diff --git a/src/Renderer.js b/src/Renderer.js
index 064d7b3..8e0ec17 100644
--- a/src/Renderer.js
+++ b/src/Renderer.js
@@ -160,12 +160,29 @@ TextEnvironment.prototype.renderToHTML = function() {
                 this._html.putText(text);
                 break;
             case 'math':
-                if (!katex) {
+                useKatex = true;
+                if (typeof katex === 'undefined') {
                     try { katex = require('katex'); }
-                    catch (e) { throw 'katex is required to render math'; }
+                    catch (e) {
+                        if (typeof MathJax === 'undefined') {
+                            throw 'KaTeX or MathJax is required to render math';
+                        }
+                        var useKatex = false;
+                    }
                 }
-                var mathHTML = katex.renderToString(text);
-                this._html.putSpan(mathHTML);
+
+                // KaTeX
+                if (useKatex) {
+                    var mathHTML = katex.renderToString(text);
+                    this._html.putSpan(mathHTML);
+                }
+
+                // MathJax
+                else {
+                    this._html.putSpan(MathJax.HTML.Element("span", null,
+                        ["$" + text + "$"]).outerHTML);
+                }
+
                 break;
             case 'cond-symbol':
                 this._html
diff --git a/static/samples.html.template b/static/samples.html.template
index db24b48..d39ba8a 100644
--- a/static/samples.html.template
+++ b/static/samples.html.template
@@ -1,19 +1,43 @@
 
 
+
 
     
     Pseudocode.js Samples
+
     
-    
+    
     
+
     
+
+    
+
     
     
     
 
+