summaryrefslogtreecommitdiff
path: root/packages/integrations/markdoc/src/runtime.ts
blob: dadb73cd6601a0dcef2bf6e8f39522eddcc76ed4 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import type { MarkdownHeading } from '@astrojs/markdown-remark';
import Markdoc, {
	type RenderableTreeNode,
	type ConfigType as MarkdocConfig,
} from '@markdoc/markdoc';
import type { ContentEntryModule } from 'astro';
import { nodes as astroNodes } from './nodes/index.js';

/** Used to reset Slugger cache on each build at runtime */
export { headingSlugger } from './nodes/index.js';
export { default as Markdoc } from '@markdoc/markdoc';

export function applyDefaultConfig(
	config: MarkdocConfig,
	entry: ContentEntryModule
): MarkdocConfig {
	return {
		...config,
		variables: {
			entry,
			...config.variables,
		},
		nodes: {
			...astroNodes,
			...config.nodes,
		},
		// TODO: Syntax highlighting
	};
}

/**
 * Get text content as a string from a Markdoc transform AST
 */
export function getTextContent(childNodes: RenderableTreeNode[]): string {
	let text = '';
	for (const node of childNodes) {
		if (typeof node === 'string' || typeof node === 'number') {
			text += node;
		} else if (typeof node === 'object' && Markdoc.Tag.isTag(node)) {
			text += getTextContent(node.children);
		}
	}
	return text;
}

const headingLevels = [1, 2, 3, 4, 5, 6] as const;

/**
 * Collect headings from Markdoc transform AST
 * for `headings` result on `render()` return value
 */
export function collectHeadings(children: RenderableTreeNode[]): MarkdownHeading[] {
	let collectedHeadings: MarkdownHeading[] = [];
	for (const node of children) {
		if (typeof node !== 'object' || !Markdoc.Tag.isTag(node)) continue;

		if (node.attributes.__collectHeading === true && typeof node.attributes.level === 'number') {
			collectedHeadings.push({
				slug: node.attributes.id,
				depth: node.attributes.level,
				text: getTextContent(node.children),
			});
			continue;
		}

		for (const level of headingLevels) {
			if (node.name === 'h' + level) {
				collectedHeadings.push({
					slug: node.attributes.id,
					depth: level,
					text: getTextContent(node.children),
				});
			}
		}
		collectedHeadings.concat(collectHeadings(node.children));
	}
	return collectedHeadings;
}