DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on • Updated on

How to prevent flickering in Live Markdown Editor

Especially, for items that shouldn't load too often, like <iframe>.

In short, incremental-dom

You can replace the entire HTML output with incremental DOM tree. (Much of the code comes from here.)

import { Parser } from 'htmlparser2'
import { elementOpen, elementClose, text } from 'incremental-dom'
import { Serialize } from 'any-serialize'

const ser = new Serialize()

export function makeIncremental (s: string): () => void {
  const open = (name: string, attr: Record<string, string> = {}) => {
    elementOpen(name, name + '-' + ser.hash(attr), Object.values(attr).flat())
  }

  const close = (name: string) => {
    elementClose(name)
  }

  const iDOMParser = new Parser(
    {
      onopentag: open,
      ontext: text,
      onclosetag: close
    },
    {
      decodeEntities: true,
      lowerCaseAttributeNames: false,
      lowerCaseTags: false,
      recognizeSelfClosing: true
    }
  )

  return () => {
    iDOMParser.write(s)
  }
}
Enter fullscreen mode Exit fullscreen mode

About htmlparser2, it does work in web browser, but I need to install @types/node (in devDependencies)...

The real project is here -- https://github.com/patarapolw/blogdown-cms/tree/heroku and it is

  • Markdown editor that supports
    • <style> tags that do not leak outside the scope (thanks to stylis)
    • Embedded PDF
    • Embedded Presentation (via reveal-md)
  • Presentation (reveal-md) editor
    • Via same-origin iframe.contentWindow

Well, reveal.js sometimes create problem for me as well. Might create my own someday.

Top comments (0)