summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/remark-unwrap.ts
blob: 3ce7a72c0ca249fd0ea0a3d9940b762049da6a59 (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
39
40
41
42
43
44
import { visit as _visit, SKIP } from 'unist-util-visit';

// This is a workaround.
// It fixes a compatibility issue between different, incompatible ASTs given by plugins to Unist
const visit = _visit as (
	node: any,
	type: string,
	callback?: (node: any, index: number, parent: any) => any
) => any;

// 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);
	}
}