/
embed.js
71 lines (64 loc) · 1.91 KB
/
embed.js
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
"use strict";
const { getParserName, getMaxContinuousCount } = require("../common/util");
const {
builders: { hardline, concat, markAsRoot },
utils: { replaceNewlinesWithLiterallines },
} = require("../document");
const { print: printFrontMatter } = require("../utils/front-matter");
const { getFencedCodeBlockValue } = require("./utils");
function embed(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type === "code" && node.lang !== null) {
// only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
const langMatch = node.lang.match(/^[\w-]+/);
const lang = langMatch ? langMatch[0] : "";
const parser = getParserName(lang, options);
if (parser) {
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(
Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1)
);
const doc = textToDoc(
getFencedCodeBlockValue(node, options.originalText),
{ parser },
{ stripTrailingHardline: true }
);
return markAsRoot(
concat([
style,
node.lang,
node.meta ? " " + node.meta : "",
hardline,
replaceNewlinesWithLiterallines(doc),
hardline,
style,
])
);
}
}
switch (node.type) {
case "front-matter":
return printFrontMatter(node, textToDoc);
// MDX
case "importExport":
return concat([
textToDoc(
node.value,
{ parser: "babel" },
{ stripTrailingHardline: true }
),
hardline,
]);
case "jsx":
return textToDoc(
`<$>${node.value}</$>`,
{
parser: "__js_expression",
rootMarker: "mdx",
},
{ stripTrailingHardline: true }
);
}
return null;
}
module.exports = embed;