index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * @typedef {import('mdast').Root} Root
  3. */
  4. import {definitions} from 'mdast-util-definitions'
  5. import {SKIP, visit} from 'unist-util-visit'
  6. /**
  7. * Turn references and definitions into normal links and images.
  8. *
  9. * @returns
  10. * Transform.
  11. */
  12. export default function remarkInlineLinks() {
  13. /**
  14. * Transform.
  15. *
  16. * @param {Root} tree
  17. * Tree.
  18. * @returns {undefined}
  19. * Nothing.
  20. */
  21. return function (tree) {
  22. const definition = definitions(tree)
  23. visit(tree, function (node, index, parent) {
  24. if (
  25. node.type === 'definition' &&
  26. parent !== undefined &&
  27. typeof index === 'number'
  28. ) {
  29. parent.children.splice(index, 1)
  30. return [SKIP, index]
  31. }
  32. if (node.type === 'imageReference' || node.type === 'linkReference') {
  33. const def = definition(node.identifier)
  34. if (def && parent && typeof index === 'number') {
  35. parent.children[index] =
  36. node.type === 'imageReference'
  37. ? {type: 'image', url: def.url, title: def.title, alt: node.alt}
  38. : {
  39. type: 'link',
  40. url: def.url,
  41. title: def.title,
  42. children: node.children
  43. }
  44. return [SKIP, index]
  45. }
  46. }
  47. })
  48. }
  49. }