summaryrefslogtreecommitdiff
path: root/packages/integrations/markdoc/src/runtime.ts
blob: 44c232b79d63a99a51345b5fee12fb35653f5e28 (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import type { MarkdownHeading } from '@astrojs/markdown-remark';
import Markdoc, {
	type ConfigType,
	type Node,
	type NodeType,
	type RenderableTreeNode,
} from '@markdoc/markdoc';
import type { AstroInstance } from 'astro';
import { createComponent, renderComponent } from 'astro/runtime/server/index.js';
import type { AstroMarkdocConfig } from './config.js';
import { setupHeadingConfig } from './heading-ids.js';
import { htmlTag } from './html/tagdefs/html.tag.js';
import type { MarkdocIntegrationOptions } from './options.js';
/**
 * Merge user config with default config and set up context (ex. heading ID slugger)
 * Called on each file's individual transform.
 * TODO: virtual module to merge configs per-build instead of per-file?
 */
export async function setupConfig(
	userConfig: AstroMarkdocConfig = {},
	options: MarkdocIntegrationOptions | undefined,
	experimentalHeadingIdCompat: boolean,
): Promise<MergedConfig> {
	let defaultConfig: AstroMarkdocConfig = setupHeadingConfig(experimentalHeadingIdCompat);

	if (userConfig.extends) {
		for (let extension of userConfig.extends) {
			if (extension instanceof Promise) {
				extension = await extension;
			}

			defaultConfig = mergeConfig(defaultConfig, extension);
		}
	}

	let merged = mergeConfig(defaultConfig, userConfig);

	if (options?.allowHTML) {
		merged = mergeConfig(merged, HTML_CONFIG);
	}

	return merged;
}

/** Used for synchronous `getHeadings()` function */
export function setupConfigSync(
	userConfig: AstroMarkdocConfig = {},
	options: MarkdocIntegrationOptions | undefined,
	experimentalHeadingIdCompat: boolean,
): MergedConfig {
	const defaultConfig: AstroMarkdocConfig = setupHeadingConfig(experimentalHeadingIdCompat);

	let merged = mergeConfig(defaultConfig, userConfig);

	if (options?.allowHTML) {
		merged = mergeConfig(merged, HTML_CONFIG);
	}

	return merged;
}

type MergedConfig = Required<Omit<AstroMarkdocConfig, 'extends'>>;

/** Merge function from `@markdoc/markdoc` internals */
export function mergeConfig(
	configA: AstroMarkdocConfig,
	configB: AstroMarkdocConfig,
): MergedConfig {
	return {
		...configA,
		...configB,
		ctx: {
			...configA.ctx,
			...configB.ctx,
		},
		tags: {
			...configA.tags,
			...configB.tags,
		},
		nodes: {
			...configA.nodes,
			...configB.nodes,
		},
		functions: {
			...configA.functions,
			...configB.functions,
		},
		variables: {
			...configA.variables,
			...configB.variables,
		},
		partials: {
			...configA.partials,
			...configB.partials,
		},
		validation: {
			...configA.validation,
			...configB.validation,
		},
	};
}

export function resolveComponentImports(
	markdocConfig: Required<Pick<AstroMarkdocConfig, 'tags' | 'nodes'>>,
	tagComponentMap: Record<string, AstroInstance['default']>,
	nodeComponentMap: Record<NodeType, AstroInstance['default']>,
) {
	for (const [tag, render] of Object.entries(tagComponentMap)) {
		const config = markdocConfig.tags[tag];
		if (config) config.render = render;
	}
	for (const [node, render] of Object.entries(nodeComponentMap)) {
		const config = markdocConfig.nodes[node as NodeType];
		if (config) config.render = render;
	}
	return markdocConfig;
}

/**
 * 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[],
	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),
				});
			}
		}
		collectHeadings(node.children, collectedHeadings);
	}
}

export function createGetHeadings(
	stringifiedAst: string,
	userConfig: AstroMarkdocConfig,
	options: MarkdocIntegrationOptions | undefined,
	experimentalHeadingIdCompat: boolean,
) {
	return function getHeadings() {
		/* Yes, we are transforming twice (once from `getHeadings()` and again from <Content /> in case of variables).
			TODO: propose new `render()` API to allow Markdoc variable passing to `render()` itself,
			instead of the Content component. Would remove double-transform and unlock variable resolution in heading slugs. */
		const config = setupConfigSync(userConfig, options, experimentalHeadingIdCompat);
		const ast = Markdoc.Ast.fromJSON(stringifiedAst);
		const content = Markdoc.transform(ast as Node, config as ConfigType);
		let collectedHeadings: MarkdownHeading[] = [];
		collectHeadings(Array.isArray(content) ? content : [content], collectedHeadings);
		return collectedHeadings;
	};
}

export function createContentComponent(
	Renderer: AstroInstance['default'],
	stringifiedAst: string,
	userConfig: AstroMarkdocConfig,
	options: MarkdocIntegrationOptions | undefined,
	tagComponentMap: Record<string, AstroInstance['default']>,
	nodeComponentMap: Record<NodeType, AstroInstance['default']>,
	experimentalHeadingIdCompat: boolean,
) {
	return createComponent({
		async factory(result: any, props: Record<string, any>) {
			const withVariables = mergeConfig(userConfig, { variables: props });
			const config = resolveComponentImports(
				await setupConfig(withVariables, options, experimentalHeadingIdCompat),
				tagComponentMap,
				nodeComponentMap,
			);

			return renderComponent(result, Renderer.name, Renderer, { stringifiedAst, config }, {});
		},
		propagation: 'self',
	} as any);
}

// statically define a partial MarkdocConfig which registers the required "html-tag" Markdoc tag when the "allowHTML" feature is enabled
const HTML_CONFIG: AstroMarkdocConfig = {
	tags: {
		'html-tag': htmlTag,
	},
};