-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathremark-format-code.js
59 lines (55 loc) · 1.73 KB
/
remark-format-code.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
import {format} from 'prettier';
import {visit} from 'unist-util-visit';
export default function remarkFormatCodeBlocks() {
return async tree => {
const codeNodes = [];
visit(tree, 'code', node => {
codeNodes.push(node);
});
const formattingWork = codeNodes
// skip code blocks with diff meta as they might have
// broken syntax due to + and - characters
// or with `onboardingOptions` as they need to have predictable line numbers
// or `@inject` statements as they often lead to unnecessary line breaks
.filter(
node =>
!(
node.meta?.includes('diff') ||
node.meta?.includes('onboardingOptions') ||
node.value?.includes('@inject packages')
)
)
.map(node => formatCode(node));
await Promise.all(formattingWork);
};
}
async function formatCode(node) {
const lang = node.lang;
const parsersConfigs = {
javascript: {parser: 'babel'},
jsx: {parser: 'babel'},
typescript: {parser: 'babel-ts'},
tsx: {parser: 'babel-ts'},
html: {parser: 'html'},
css: {parser: 'css'},
json: {parser: 'json'},
markdown: {parser: 'markdown'},
yaml: {parser: 'yaml'},
yml: {parser: 'yaml'},
xml: {parser: 'xml', plugins: ['@prettier/plugin-xml']},
};
const parserConfig = parsersConfigs[lang];
if (!parserConfig) {
return;
}
try {
const formattedCode = await format(node.value, {
printWidth: 75, // The code blocks in the docs have around 77 characters available on desktop
...parserConfig,
});
// get rid of the trailing newline
node.value = formattedCode.trimEnd();
} catch (e) {
// noop - logging here would spam the build logs to a degree of unusability
}
}