Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hail2u
Last active October 29, 2020 09:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hail2u/6cbbc39744cf8d57a0b33010fdf052ef to your computer and use it in GitHub Desktop.
Save hail2u/6cbbc39744cf8d57a0b33010fdf052ef to your computer and use it in GitHub Desktop.

figure要素を書けるようにする

画像に必ずリンクを張ることを条件に、リンクと画像のみの段落をfigure要素になるようフックしてやる。figcaption要素はリンクに指定可能なtitle属性を流用する。

キャプションあり

[![alt](src.png)](href "caption")
<figure>
<a href="href"><img alt="alt" src="src.png"></a>
<figcaption>caption</figcaption>
</figure>

キャプションなし

[![alt](src.png)](href)
<figure>
<a href="href"><img alt="alt" src="src.png"></a>
</figure>

実装

const marked = require("marked");

const markupLink = (href, titleText, text) => {
  if (!titleText) {
    return `<a href="${href}">${text}</a>`;
  }

  return `<a href="${href}">${text}</a>
<figcaption>${titleText}</figcaption>`;
};

const markupParagaraph = content => {
  if (
    /^(<a\s[^>]*>)<img\s[^>]*>(<\/a>)(\n<figcaption>[^<]*<\/figcaption>)?$/.exec(
      content
    )
  ) {
    return `<figure>
${content}
</figure>
`;
  }

  return `<p>${content}</p>
`;
};

const renderer = new marked.Renderer();
renderer.link = markupLink;
renderer.paragraph = markupParagaraph;

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