简单实现增量markdown渲染器

189 阅读1分钟

看效果:observablehq.com/d/74108b2bc… 只实现了基础markdown,未实现扩展语法功能。 当编辑内容时,只渲染更改的行,未更改内容不会重新渲染。

npm i belling
npm i belling-dom

用了我自己写的小框架,加起来未压缩只有15kb左右。

  const text = state("");
  function md(line) {
    let type = "p";
    let t = 0;
    if (line == "---") return hr();
    else if (line.startsWith("# ")) (type = "h1"), (t = 2);
    else if (line.startsWith("## ")) (type = "h2"), (t = 3);
    else if (line.startsWith("### ")) (type = "h3"), (t = 4);
    else if (line.startsWith("> ")) (type = "blockquote"), (t = 2);
    else if (line.startsWith("- ")) (type = "li"), (t = 2);
    return h(type).ref((dom) => {
      let md = line.slice(t);
      md = md.replace(/\*\*(.*?)\*\*/g, "<strong>$1</strong>");
      md = md.replace(/\*(.*?)\*/g, "<em>$1</em>");
      md = md.replace(/`(.*?)`/g, "<code>$1</code>");
      dom.innerHTML = md;
    });
  }
  new root(
    outer,
    textarea().on({
      input(e) {
        text.v = e.target.value;
      }
    })
  );
  new root(
    document.body, // 组件渲染的位置。可以自行更改。
    ForEach(
      "div",
      compute(() => text.v.split("\n")),
      (line) => {
        return md(line);
      }
    )
  );