Skip to content

Instantly share code, notes, and snippets.

@hail2u
Last active July 29, 2018 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hail2u/fd9da7714cbe4d54bfe91cdec3afa102 to your computer and use it in GitHub Desktop.
Save hail2u/fd9da7714cbe4d54bfe91cdec3afa102 to your computer and use it in GitHub Desktop.

blockquote要素で引用元の表記がある場合、figure要素で括られるようにする

最後の行が(EMダッシュ)で始まっていた場合はfigure要素で括り、かつその最後の行を引用元の表記としてfigcaption要素に変換する。

引用元あり

> This is a quote.
>
> — <cite>[txt](href)</cite>
<figure>
<blockquote>
<p>This is a quote.</p>
<figcaption><cite><a href="href">txt</a></cite></figcaption>
</blockquote>

引用元なし

> This is a quote.
<blockquote>
<p>This is a quote.</p>
</blockquote>

実装

const marked = require("marked");

const markupBlockquote = content => {
  const lines = content
    .trim()
    .split("\n")
    .map((line, idx, arr) => {
      if (idx !== arr.length -1 || !line.startsWith("<p>—")) {
        return line;
      }

      return `${line.replace(/\bp(?=>)/g, "figcaption")}`;
    });

  if (!lines[lines.length - 1].endsWith("</figcaption>")) {
    return `<blockquote>
${lines.join("\n")}
</blockquote>
`
  }

  return `<figure>
<blockquote>
${lines.join("\n")}
</blockquote>
</figure>
`
};

const renderer = new marked.Renderer();
renderer.blockquote = markupBlockquote;

module.exports = t => marked(t, {
  renderer: renderer
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment