summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/remark-unwrap.ts
blob: e43a57a0ce7bb318a45387425234bc21ca1027c4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import {visit, SKIP} from 'unist-util-visit'

// Remove the wrapping paragraph for <astro-root> islands
export default function remarkUnwrap() {
  const astroRootNodes = new Set();
  let insideAstroRoot = false;

  return (tree: any) => {
    // reset state
    insideAstroRoot = false;
    astroRootNodes.clear();

    visit(tree, 'html', (node) => {
      if (node.value.indexOf('<astro-root') > -1 && !insideAstroRoot) {
        insideAstroRoot = true;
      }
      if (node.value.indexOf('</astro-root') > -1 && insideAstroRoot) {
        insideAstroRoot = false;
      }
      astroRootNodes.add(node);
    })

    visit(tree, 'paragraph', (node, index, parent) => {
      if (
        parent &&
        typeof index === 'number' &&
        containsAstroRootNode(node)
      ) {
        parent.children.splice(index, 1, ...node.children)
        return [SKIP, index]
      }
    })
  }

  function containsAstroRootNode(node: any) {
    return node.children.map((child: any) => astroRootNodes.has(child)).reduce((all: boolean, v: boolean) => all ? all : v, false)
  }
}