summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Engines/Markdown.js
blob: ec1e1f6fb790e4ab26c57aea56242c7b1166eb09 (plain)
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
import markdownIt from "markdown-it";

import TemplateEngine from "./TemplateEngine.js";

export default class Markdown extends TemplateEngine {
	constructor(name, eleventyConfig) {
		super(name, eleventyConfig);

		this.markdownOptions = {};

		this.setLibrary(this.config.libraryOverrides.md);
	}

	get cacheable() {
		return true;
	}

	setLibrary(mdLib) {
		this.mdLib = mdLib || markdownIt(this.getMarkdownOptions());

		// Overrides a highlighter set in `markdownOptions`
		// This is separate so devs can pass in a new mdLib and still use the official eleventy plugin for markdown highlighting
		if (this.config.markdownHighlighter && typeof this.mdLib.set === "function") {
			this.mdLib.set({
				highlight: this.config.markdownHighlighter,
			});
		}

		if (typeof this.mdLib.disable === "function") {
			// Disable indented code blocks by default (Issue #2438)
			this.mdLib.disable("code");
		}

		this.setEngineLib(this.mdLib, Boolean(this.config.libraryOverrides.md));
	}

	setMarkdownOptions(options) {
		this.markdownOptions = options;
	}

	getMarkdownOptions() {
		// work with "mode" presets https://github.com/markdown-it/markdown-it#init-with-presets-and-options
		if (typeof this.markdownOptions === "string") {
			return this.markdownOptions;
		}

		return Object.assign(
			{
				html: true,
			},
			this.markdownOptions || {},
		);
	}

	// TODO use preTemplateEngine to help inform this
	// needsCompilation() {
	// 	return super.needsCompilation();
	// }

	async #getPreEngine(preTemplateEngine) {
		if (typeof preTemplateEngine === "string") {
			return this.engineManager.getEngine(preTemplateEngine, this.extensionMap);
		}

		return preTemplateEngine;
	}

	async compile(str, inputPath, preTemplateEngine, bypassMarkdown) {
		let mdlib = this.mdLib;

		if (preTemplateEngine) {
			let engine = await this.#getPreEngine(preTemplateEngine);
			let fnReady = engine.compile(str, inputPath);

			if (bypassMarkdown) {
				return async function (data) {
					let fn = await fnReady;
					return fn(data);
				};
			} else {
				return async function (data) {
					let fn = await fnReady;
					let preTemplateEngineRender = await fn(data);
					let finishedRender = mdlib.render(preTemplateEngineRender, data);
					return finishedRender;
				};
			}
		} else {
			if (bypassMarkdown) {
				return function () {
					return str;
				};
			} else {
				return function (data) {
					return mdlib.render(str, data);
				};
			}
		}
	}
}