-
Notifications
You must be signed in to change notification settings - Fork 0
/
rehype-highlight.ts
49 lines (39 loc) · 1.15 KB
/
rehype-highlight.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
import { visit } from 'unist-util-visit';
import type { Todo } from '@/types/common';
function rehypeHighlight() {
return (tree: Todo) => {
visit(tree, 'text', (node, index, parent) => {
const value = node.value;
const regex = /==(.+)==/g;
const matches = [...value.matchAll(regex)];
if (matches.length > 0) {
const children = [];
let lastIndex = 0;
matches.forEach((match) => {
const [fullMatch, text] = match;
const index = match.index;
if (index > lastIndex) {
children.push({
type: 'text',
value: value.slice(lastIndex, index),
});
}
children.push({
type: 'element',
tagName: 'mark',
children: [{ type: 'text', value: text }],
});
lastIndex = index + fullMatch.length;
});
if (lastIndex < value.length) {
children.push({
type: 'text',
value: value.slice(lastIndex),
});
}
parent.children.splice(index, 1, ...children);
}
});
};
}
export default rehypeHighlight;