-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (62 loc) · 1.79 KB
/
index.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
72
73
/// <reference types="./index.d.ts" />
// @ts-check
import { parsers } from 'prettier/plugins/markdown';
import { titleCase } from 'title-case';
/**
* Call the given parser to get the AST, then convert the text values of all heading tokens to title-case.
*
* @param {string} code
* @param {import('prettier').ParserOptions} options
* @param {import('prettier').Parser} parser
*/
async function parseWithHeadingsToTitleCase(code, options, parser) {
const titleCaseOptions = options.titleCase
? JSON.parse(options.titleCase)
: undefined;
const ast = await parser.parse(code, options);
// assuming all heading tokens are children of root
const headings = ast.children.filter((token) => token.type === 'heading');
for (const heading of headings) {
const textTokens = heading.children.filter(
(token) => token.type === 'text',
);
const text = textTokens.map((token) => token.value).join('');
let converted = titleCase(text, titleCaseOptions);
textTokens.forEach((token) => {
token.value = converted.slice(0, token.value.length);
converted = converted.slice(token.value.length);
});
}
return ast;
}
/**
* Patch the `parse` method of the given parser to use `parseWithHeadingsToTitleCase` instead which wraps the given parser.
*
* @param {import('prettier').Parser} parser
*
* @returns {import('prettier').Parser}
*/
function withPatchedParse(parser) {
return {
...parser,
parse: (code, options) =>
parseWithHeadingsToTitleCase(code, options, parser),
};
}
/**
* @type {import('prettier').Plugin}
*/
export default {
options: {
titleCase: {
type: 'string',
default: undefined,
category: 'TitleCase',
description:
'JSON-stringified object with options for the `title-case` package.',
},
},
parsers: {
markdown: withPatchedParse(parsers.markdown),
},
};