add-inline-code-property.ts 919 B

123456789101112131415161718192021222324252627282930313233343536
  1. import type { Element, Root } from 'hast';
  2. import type { Plugin } from 'unified';
  3. import { is } from 'unist-util-is';
  4. import { visitParents } from 'unist-util-visit-parents';
  5. const isInlineCodeTag = (
  6. node: Element,
  7. parent: Element | Root | null,
  8. ): boolean => {
  9. if (node.tagName !== 'code') {
  10. return false;
  11. }
  12. if (parent && is(parent, { type: 'element', tagName: 'pre' })) {
  13. return false;
  14. }
  15. return true;
  16. };
  17. export const rehypePlugin: Plugin = () => {
  18. return (tree) => {
  19. visitParents(tree, 'element', (node: Element, ancestors) => {
  20. // The immediate parent is the last item in the ancestors array
  21. const parent = ancestors[ancestors.length - 1] || null;
  22. // Check if the current element is an inline <code> tag
  23. if (isInlineCodeTag(node, parent)) {
  24. node.properties = {
  25. ...node.properties,
  26. inline: true,
  27. };
  28. }
  29. });
  30. };
  31. };