UNPKG

@maksiks/markdown-it-image-caption

Version:

Cleanly add a <figcaption> to your markdown-it images.

24 lines (23 loc) 1.21 kB
const markdownItImageCaption = (md, { imgClass, figureClass, figcaptionClass } = {}) => { const old = md.renderer.rules.image; md.renderer.rules.image = (tokens, idx, options, env, self) => { if (tokens[idx]?.attrs?.[2]) { let attrs = tokens[idx].attrs; let title = attrs[2][1]; let src = attrs[0][1]; let alt = tokens[idx].content; const imgTag = `<img src="${src}" ${imgClass ? ` class="${imgClass}"` : ''} alt="${alt}" ${title !== ':::nocaption' ? ` title="${title}"` : ''} />`; return title !== ':::nocaption' ? `<figure ${figureClass ? ` class="${figureClass}"` : ''}>${imgTag}<figcaption ${figcaptionClass ? ` class="${figcaptionClass}"` : ''}>${title}</figcaption></figure>` : `<figure ${figureClass ? ` class="${figureClass}"` : ''}>${imgTag}</figure>`; } if (old) { return old(tokens, idx, options, env, self); } else { console.warn('@maksiks/markdown-it-image-caption: original renderer doesn\'t exist, something went horribly wrong.'); return ''; } }; }; export default markdownItImageCaption;