diff wdown.go @ 8:4a25b534c81c javascript-experiment

Add v8 engine and include katex
author Jonatan Werpers <jonatan@werpers.com>
date Wed, 17 Jun 2020 21:43:52 +0200
parents a5aa39557726
children
line wrap: on
line diff
--- a/wdown.go	Wed Jun 17 12:23:56 2020 +0200
+++ b/wdown.go	Wed Jun 17 21:43:52 2020 +0200
@@ -14,6 +14,7 @@
 	meta "github.com/yuin/goldmark-meta"
 	"github.com/yuin/goldmark/extension"
 	"github.com/yuin/goldmark/parser"
+	"rogchap.com/v8go"
 )
 
 func main() {
@@ -73,4 +74,26 @@
 	} else {
 		fmt.Print(htmlContent)
 	}
+
+	katexFormula := "c = \\pm\\sqrt{a^2 + b^2} = \\pm x^2"
+	katexRenderOptions := `{
+        throwOnError: false,
+        displayMode: true,
+    }
+    `
+	ctx, _ := v8go.NewContext(nil) // creates a new V8 context with a new Isolate aka VM
+	ctx.RunScript(katexSrc(), "katex/katex.js")
+	ctx.RunScript("const katexFormula = String.raw`"+katexFormula+"`", "main.js")                          // executes a script on the global context
+	ctx.RunScript("const mathHtml = katex.renderToString(katexFormula,"+katexRenderOptions+")", "main.js") // any functions previously added to the context can be called
+	mathHtml, _ := ctx.RunScript("mathHtml", "value.js")                                                   // return a value in JavaScript back to Go
+	fmt.Println(mathHtml)
 }
+
+func katexSrc() string {
+	katexBytes, err := ioutil.ReadFile("katex/katex.js")
+	if err != nil {
+		log.Fatal(err)
+	}
+
+	return string(katexBytes)
+}