-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remarkPlugin.ts
74 lines (65 loc) · 2.19 KB
/
remarkPlugin.ts
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
/* Based on https://github.com/kevinzunigacuellar/remark-code-title */
import { visit } from 'unist-util-visit';
import type * as hast from 'hast';
import type * as unified from 'unified';
const LANGUAGE_EXCLUSIONS: string[] = ['diff', 'treeview'];
export const labelCodeBlock: unified.Plugin<[], hast.Root> = () => {
return (tree, file) => {
visit(tree, 'element', (node, index, parent) => {
if (node.tagName !== 'pre') return;
if (parent == null) return;
let offset: number = 1;
index = index ?? 0;
// process the code language
const className = node.properties?.className ?? [];
if (className != null && Array.isArray(className)) {
const language: string =
className
.map((x) => x.toString())
.find((x) => x.match(/language-/))
?.replace('language-', '') ?? '';
if (!LANGUAGE_EXCLUSIONS.some((x) => language.includes(x))) {
const languageNode: hast.Element = {
type: 'element',
tagName: 'header',
properties: {},
children: [
{
type: 'element',
tagName: 'button',
properties: {
className: 'copy-code-button',
onclick: 'copyCodeBlock(this)',
},
children: [
{
type: 'element',
tagName: 'i',
properties: {
className: 'fa fa-copy',
},
children: [],
},
],
},
],
};
parent.children.splice(index, 0, languageNode);
offset++;
}
}
// const title = `${node.properties["data-title"] ?? ""}`.trim();
// if (title) {
// const titleNode: hast.Element = {
// type: "element",
// tagName: "h4",
// children: [{ type: "text", value: title }],
// };
// node.children.splice(index + 1, 0, titleNode);
// offset++;
// }
/* Skips this node (title) and the next node (code) */
return index + offset;
});
};
};