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.