forked from
quillmatiq.com/augment
Fork of Chiri for Astro for my blog
1import { visit } from 'unist-util-visit'
2
3/**
4 * Rehype plugin to cleanup and extract raw figure elements from paragraph nodes
5 */
6export default function rehypeCleanup() {
7 return (tree) => {
8 visit(tree, 'element', (node, index, parent) => {
9 if (node.tagName !== 'p') {
10 return
11 }
12 if (!node.children?.length) {
13 return
14 }
15 if (!parent) {
16 return
17 }
18
19 const rawFigureNodes = []
20
21 for (const child of node.children) {
22 if (child.type === 'raw' && child.value && child.value.trim().startsWith('<figure')) {
23 rawFigureNodes.push(child)
24 } else if (child.type !== 'text' || child.value.trim() !== '') {
25 return
26 }
27 }
28
29 if (rawFigureNodes.length > 0) {
30 parent.children.splice(index, 1, ...rawFigureNodes)
31 return index
32 }
33 })
34 }
35}