forked from OKEAMAH/prettier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembed.js
More file actions
68 lines (59 loc) · 2.04 KB
/
embed.js
File metadata and controls
68 lines (59 loc) · 2.04 KB
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
import { hardline, markAsRoot } from "../document/builders.js";
import { replaceEndOfLine } from "../document/utils.js";
import printFrontMatter from "../utils/front-matter/print.js";
import getMaxContinuousCount from "../utils/get-max-continuous-count.js";
import inferParser from "../utils/infer-parser.js";
import { getFencedCodeBlockValue } from "./utils.js";
function embed(path, options) {
const { node } = path;
if (node.type === "code" && node.lang !== null) {
const parser = inferParser(options, { language: node.lang });
if (parser) {
return async (textToDoc) => {
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(
Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1),
);
const newOptions = { parser };
// Override the filepath option.
// This is because whether the trailing comma of type parameters
// should be printed depends on whether it is `*.ts` or `*.tsx`.
// https://github.com/prettier/prettier/issues/15282
if (node.lang === "ts" || node.lang === "typescript") {
newOptions.filepath = "dummy.ts";
} else if (node.lang === "tsx") {
newOptions.filepath = "dummy.tsx";
}
const doc = await textToDoc(
getFencedCodeBlockValue(node, options.originalText),
newOptions,
);
return markAsRoot([
style,
node.lang,
node.meta ? " " + node.meta : "",
hardline,
replaceEndOfLine(doc),
hardline,
style,
]);
};
}
}
switch (node.type) {
case "front-matter":
return (textToDoc) => printFrontMatter(node, textToDoc);
// MDX
case "import":
case "export":
return (textToDoc) => textToDoc(node.value, { parser: "babel" });
case "jsx":
return (textToDoc) =>
textToDoc(`<$>${node.value}</$>`, {
parser: "__js_expression",
rootMarker: "mdx",
});
}
return null;
}
export default embed;