Quill + Mathjax custom
by Imabot
HTML
<link rel="stylesheet" href="//cdn.quilljs.com/1.3.6/quill.snow.css">
<script src="//cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6""></script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-svg.js"></script>
<button id="delta">Show delta in console</button>
<button id="mathjax">Add MathJax</button>
<div id="editor-container"></div>
<small>More details on <a href="https://lucidar.me/en/rich-content-editor/mathjax-and-quill-editor" target="_blank">this page</a>.</small>
JavaScript
// Initialize Quill editor
var quill = new Quill('#editor-container', {
placeholder: 'Click the MathJax button to insert a formula.',
theme: 'snow',
modules: {
toolbar: [
['bold', 'italic', 'underline', 'strike'],
['link'],
['blockquote'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
[{ 'script': 'sub'}, { 'script': 'super' }],
['align', { 'align': 'center' }, { 'align': 'right' }, { 'align': 'justify' }]
]
},
});
// Display the current delta content of the editor in the console
document.getElementById('delta').onclick = () => {
console.log ( quill.getContents() );
}
// When the MathJax button is clicked, add a mathjax equation at the current selection
document.getElementById('mathjax').onclick = () => {
var latex = prompt("Enter a LaTeX formula:", "e=mc^2");
var range = quill.getSelection(true);
quill.deleteText(range.index, range.length);
quill.insertEmbed(range.index, 'mathjax', latex);
quill.insertText(range.index + range.length + 1 , ' ');
quill.setSelection(range.index + range.length + 1);
}
// Import parchment and delta for creating custom module
const Parchment = Quill.imports.parchment;
const Delta = Quill.imports.delta;
// Extend the embed
class Mathjax extends Parchment.Embed {
// Create node
static create(value)
{
const node = super.create(value);
if (typeof value === 'string') {
node.innerHTML = "" + this.tex2svg(value) + "";
node.contentEditable = 'false';
node.setAttribute('data-value', value);
}
return node;
}
// Return the attribute value (probably for Delta)
static value(domNode)
{
return domNode.getAttribute('data-value');
}
// Manually render a MathJax equation until version 3.0.2 is not released
static tex2svg(latex)
{
// Create a hidden node and render the formula inside
let MathJaxNode = document.createElement("DIV");
MathJaxNode.style.visibility = "hidden";
MathJaxNode.innerHTML = '\\(' + latex...