index.js 1018 B

12345678910111213141516171819202122232425262728293031
  1. const visit = require('unist-util-visit');
  2. const remove = require('unist-util-remove');
  3. module.exports = ({ markdownAST }) => {
  4. visit(markdownAST, 'paragraph', (node, index, parent) => {
  5. let imageClass = 'default';
  6. const hasOnlyImagesNodes = node.children.every(child => {
  7. if (child.type === 'text' && /\{(.*)\}/.test(child.value.trim())) {
  8. let matches = child.value.trim().match(/\{(.*)\}/);
  9. imageClass = matches[1].trim();
  10. }
  11. return (
  12. (child.type === 'html' && child.value.indexOf('gatsby-resp-image-wrapper') >= 0) ||
  13. (child.type === 'text' && /\{(.*)\}/.test(child.value.trim()))
  14. );
  15. });
  16. if (!hasOnlyImagesNodes) {
  17. return;
  18. }
  19. node.children[0].value = `<div class="image-${imageClass}">${node.children[0].value}</div>`;
  20. remove(node, 'text');
  21. parent.children.splice(index, 1, ...node.children);
  22. return index;
  23. });
  24. };