-
Notifications
You must be signed in to change notification settings - Fork 22
/
highlighter.ts
158 lines (140 loc) · 4.97 KB
/
highlighter.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import { getHighlighter, type ThemeInput, type Highlighter, type BuiltinLanguage, type BuiltinTheme } from 'shikiji'
import type { HighlightResult, HighlighterOptions, Theme } from './types'
import type { Element } from '../types/hast'
export const useShikiHighlighter = createSingleton((opts?: any) => {
// Grab highlighter config from publicRuntimeConfig
const { theme, preload, wrapperStyle } = opts || {}
let promise: Promise<Highlighter> | undefined
const getShikiHighlighter = () => {
if (!promise) {
// Initialize highlighter with defaults
promise = getHighlighter({
themes: [
((theme as any)?.default || theme || 'dark-plus') as BuiltinTheme,
],
langs: [
...(preload || []),
'diff',
'json',
'js',
'ts',
'css',
'shell',
'html',
'md',
'yaml',
'vue',
'mdc'
] as any[]
}).then((highlighter) => {
// Load all themes on-demand
const themes = Object.values(typeof theme === 'string' ? { default: theme } : (theme || {})) as ThemeInput[]
if (themes.length) {
return Promise
.all(themes.map(theme => highlighter.loadTheme(theme)))
.then(() => highlighter)
}
return highlighter
})
}
return promise
}
const getHighlightedAST = async (code: string, lang: BuiltinLanguage, theme: Theme, opts?: Partial<HighlighterOptions>): Promise<HighlightResult> => {
try {
const highlighter = await getShikiHighlighter()
const { highlights = [] } = opts || {}
const themesObject = typeof theme === 'string' ? { default: theme } : (theme || {})
const themeNames = Object.values(themesObject) as BuiltinTheme[]
if (themeNames.length) {
await Promise.all(themeNames.map(theme => highlighter.loadTheme(theme)))
}
if (lang && !highlighter.getLoadedLanguages().includes(lang)) {
await highlighter.loadLanguage(lang)
}
const root = highlighter.codeToHast(code.trimEnd(), {
lang,
themes: themesObject,
defaultColor: false,
transforms: {
line(node, line) {
node.properties ||= {}
if (highlights.includes(line)) {
node.properties.class = (node.properties.class || '') + ' highlight'
}
node.properties.line = line
// Add newline to end of lines
if (node.children.length === 0) {
node.children.push({
type: 'element',
tagName: 'span',
properties: {
emptyLinePlaceholder: true
},
children: [{ type: 'text', value: '' }]
})
}
const last = node.children.at(-1)
if (last?.type === 'element' && last.tagName === 'span') {
const text = last.children.at(-1)
if (text?.type === 'text')
text.value += '\n'
}
},
}
})
const preEl = root.children[0] as Element
const codeEl = preEl.children[0] as Element
preEl.properties.style = wrapperStyle ? (typeof wrapperStyle === 'string' ? wrapperStyle : preEl.properties.style) : ''
const styles: string[] = []
Object.keys(themesObject)
.forEach(color => {
const colorScheme = color !== 'default' ? `.${color}` : ''
styles.push(
wrapperStyle ? `${colorScheme} .shiki,` : '',
`html .${color} .shiki span {`,
`color: var(--shiki-${color});`,
`background: var(--shiki-${color}-bg);`,
`font-style: var(--shiki-${color}-font-style);`,
`font-weight: var(--shiki-${color}-font-weight);`,
`text-decoration: var(--shiki-${color}-text-decoration);`,
'}'
)
styles.unshift(
`html${colorScheme} .shiki span {`,
`color: var(--shiki-${color});`,
`background: var(--shiki-${color}-bg);`,
`font-style: var(--shiki-${color}-font-style);`,
`font-weight: var(--shiki-${color}-font-weight);`,
`text-decoration: var(--shiki-${color}-text-decoration);`,
'}'
)
})
return {
tree: codeEl.children as Element[],
className: preEl.properties.class as string,
inlineStyle: preEl.properties.style as string,
style: styles.join(''),
}
} catch (error: any) {
console.warn('[@nuxtjs/mdc] Failed to highlight code block', error.message)
return {
tree: [{ type: 'text', value: code }],
className: '',
inlineStyle: '',
style: ''
}
}
}
return {
getHighlightedAST,
}
})
function createSingleton<T, Params extends Array<any>>(fn: (...arg: Params) => T) {
let instance: T | undefined
return (...args: Params) => {
if (!instance) {
instance = fn(...args)
}
return instance
}
}