BlogProject

Markdown/WYSIWYG Converter!

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 done

The Technical Bits

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

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 .txt file.

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.

References

  1. Quill.jsquilljs.com
  2. Marked.jsmarked.js.org
  3. Turndownmixmark-io.github.io
  4. PDF exportparall.ax