DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on • Edited on

3 3

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay