add-inline-code-property.ts 912 B

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