Sometimes you need to write in Markdown, and sometimes you just want to click buttons and see your text get bold or italic right away (WYSIWYG, or What You See Is What You Get).
The problem? These two methods don’t play nice together.
What if you could have both at the same time? Type in Markdown, see it formatted instantly. And vice-versa.
The Infinite Loop Problem
The challenge: if changing Markdown updates the WYSIWYG side, and the other way around… wouldn’t they just keep triggering each other forever?
Yep! Normally this would cause an infinite loop, and with enough time it could crash the browser. The solution is to check if the code is updating on one side or the other, and only convert that side.
if (this.isUpdating) return; // Don't do anything if it's still updating
this.isUpdating = true;
// Do the conversion work
this.isUpdating = false; // All doneThe Technical Bits
This is built in a class called MD2WYSIWYG, that coordinates 3 libraries:
- Quill.js1: The WYSIWYG editor with the nice toolbar.
- Marked.js2: Converts Markdown to HTML.
- Turndown3: Converts HTML back to Markdown.
The class also exports in 2 ways:
- PDF export4: Uses jsPDF to generate a document in the PDF format.
- Text export: Downloads your Markdown as a
.txtfile.
The standalone version
I later rebuilt this as a proper Markdown editor. Same two-way sync, plus a live preview and a cleaner writing space than a CodePen. Write in Markdown or in rich text, and the other side keeps up.