-
-
Notifications
You must be signed in to change notification settings - Fork 374
/
notation-map.ts
40 lines (36 loc) · 1.21 KB
/
notation-map.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
import type { ShikiTransformer } from 'shiki'
import { createCommentNotationTransformer } from '../utils'
export interface TransformerNotationMapOptions {
classMap?: Record<string, string | string[]>
/**
* Class added to the <pre> element when the current code has diff
*/
classActivePre?: string
}
function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
export function transformerNotationMap(
options: TransformerNotationMapOptions = {},
name = '@shikijs/transformers:notation-map',
): ShikiTransformer {
const {
classMap = {},
classActivePre = undefined,
} = options
return createCommentNotationTransformer(
name,
new RegExp(`\\s*(?://|/\\*|<!--|#|--|%{1,2}|;{1,2}|"|')\\s+\\[!code (${Object.keys(classMap).map(escapeRegExp).join('|')})(:\\d+)?\\]\\s*(?:\\*/|-->)?\\s*$`),
function ([_, match, range = ':1'], _line, _comment, lines, index) {
const lineNum = Number.parseInt(range.slice(1), 10)
lines
.slice(index, index + lineNum)
.forEach((line) => {
this.addClassToHast(line, classMap[match])
})
if (classActivePre)
this.addClassToHast(this.pre, classActivePre)
return true
},
)
}