Markdown/WYSIWYG Converter!

Markdown/WYSIWYG Converter!

codepen

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, or WYSIWYG (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 done 

The Technical Bits

This is built in a class called MD2WYSIWYG, that coordinates 3 libraries:

  • Quill.js: The WYSIWYG editor with the nice toolbar.
  • Marked.js: Converts Markdown to HTML.
  • Turndown: Converts HTML back to Markdown.

The class also exports in 2 ways:

  • PDF export: Uses jsPDF to generate a document in the PDF format.
  • Text export: Downloads your Markdown as a .txt file.