返回 slidev
annotations.ts
根目录 / packages / vscode / src / views / annotations.ts
1 import type { SourceSlideInfo } from '@slidev/types'
2 import type { DecorationOptions } from 'vscode'
3 import { clamp, ensurePrefix } from '@antfu/utils'
4 import { computed, defineService, useActiveTextEditor, watch } from 'reactive-vscode'
5 import { Position, Range, ThemeColor, window } from 'vscode'
6 import { useProjectFromDoc } from '../composables/useProjectFromDoc'
7 import { config } from '../configs'
8 import { activeProject } from '../projects'
9 import { toRelativePath } from '../utils/toRelativePath'
10
11 const RE_NEWLINE = /\r?\n/
12 const RE_LEADING_BACKTICKS = /^\s*`+/
13 const RE_FRONTMATTER_BLOCK = /^---[\s\S]*?\n---/
14
15 const frontmatterBgOptions = {
16 isWholeLine: true,
17 backgroundColor: '#8881',
18 }
19
20 const firstLineDecoration = window.createTextEditorDecorationType({})
21 const dividerDecoration = window.createTextEditorDecorationType({
22 ...frontmatterBgOptions,
23 color: new ThemeColor('panelTitle.inactiveForeground'),
24 borderStyle: 'solid',
25 borderWidth: '1px 0 0 0',
26 borderColor: new ThemeColor('panelTitle.activeBorder'),
27 })
28 const frontmatterContentDecoration = window.createTextEditorDecorationType(frontmatterBgOptions)
29 const frontmatterEndDecoration = window.createTextEditorDecorationType({
30 ...frontmatterBgOptions,
31 color: new ThemeColor('panelTitle.inactiveForeground'),
32 })
33 const errorDecoration = window.createTextEditorDecorationType({
34 isWholeLine: true,
35 })
36 const codeBlockLineNumberDecoration = window.createTextEditorDecorationType({
37 isWholeLine: false,
38 rangeBehavior: 1,
39 })
40
41 function mergeSlideNumbers(slides: { index: number }[]): string {
42 const indexes = slides.map(s => s.index + 1)
43 const merged = [
44 [indexes[0], indexes[0]],
45 ]
46 for (let i = 1; i < indexes.length; i++) {
47 if (merged[merged.length - 1][1] + 1 === indexes[i])
48 merged[merged.length - 1][1] = indexes[i]
49 else
50 merged.push([indexes[i], indexes[i]])
51 }
52 return merged.map(([start, end]) => start === end
53 ? `#${start}`
54 : `#${start}-${end}`).join(', ')
55 }
56
57 interface CodeBlockInfo {
58 startLine: number
59 endLine: number
60 indent: number
61 }
62
63 function findCodeBlocks(docText: string): CodeBlockInfo[] {
64 const lines = docText.split(RE_NEWLINE)
65 const codeBlocks: CodeBlockInfo[] = []
66
67 for (let i = 0; i < lines.length; i++) {
68 const line = lines[i]
69 const trimmedLine = line.trimStart()
70
71 if (trimmedLine.startsWith('```')) {
72 const indent = line.length - trimmedLine.length
73 const codeBlockLevel = line.match(RE_LEADING_BACKTICKS)![0]
74 const backtickCount = codeBlockLevel.trim().length
75 const startLine = i
76
77 if (backtickCount !== 3) {
78 continue
79 }
80
81 let endLine = i
82 for (let j = i + 1; j < lines.length; j++) {
83 if (lines[j].startsWith(codeBlockLevel)) {
84 endLine = j
85 break
86 }
87 }
88
89 if (endLine > startLine) {
90 codeBlocks.push({
91 startLine: startLine + 1,
92 endLine,
93 indent,
94 })
95 }
96
97 i = endLine
98 }
99 }
100
101 return codeBlocks
102 }
103
104 function updateCodeBlockLineNumbers(editor: ReturnType<typeof useActiveTextEditor>['value'], docText: string) {
105 if (!editor || !config['annotations-line-numbers'])
106 return
107
108 const codeBlockLineNumbers: DecorationOptions[] = []
109 const codeBlocks = findCodeBlocks(docText)
110
111 for (const block of codeBlocks) {
112 const lineCount = block.endLine - block.startLine
113 const maxLineNumber = lineCount
114 const numberWidth = String(maxLineNumber).length
115
116 for (let i = 0; i < lineCount; i++) {
117 const lineNumber = i + 1
118 const currentLine = block.startLine + i
119
120 if (currentLine >= editor.document.lineCount)
121 continue
122
123 // \u2800 renders as a space but won't be trimmed
124 const paddedNumber = String(lineNumber).padStart(numberWidth, '\u2800')
125
126 const position = new Position(currentLine, block.indent)
127 codeBlockLineNumbers.push({
128 range: new Range(position, position),
129 renderOptions: {
130 before: {
131 contentText: `${paddedNumber}│`,
132 color: new ThemeColor('editorLineNumber.foreground'),
133 fontWeight: 'normal',
134 fontStyle: 'normal',
135 margin: '0 0.5em 0 0',
136 },
137 },
138 })
139 }
140 }
141
142 editor.setDecorations(codeBlockLineNumberDecoration, codeBlockLineNumbers)
143 }
144
145 export const useAnnotations = defineService(() => {
146 const editor = useActiveTextEditor()
147 const doc = computed(() => editor.value?.document)
148 const projectInfo = useProjectFromDoc(doc)
149
150 watch(
151 [
152 editor,
153 doc,
154 projectInfo,
155 activeProject,
156 () => config.annotations,
157 () => config['annotations-line-numbers'],
158 ],
159 ([editor, doc, projectInfo, activeProject, enabled, lineNumbersEnabled]) => {
160 if (!editor || !doc)
161 return
162
163 if (!projectInfo || !enabled) {
164 editor.setDecorations(firstLineDecoration, [])
165 editor.setDecorations(dividerDecoration, [])
166 editor.setDecorations(frontmatterContentDecoration, [])
167 editor.setDecorations(frontmatterEndDecoration, [])
168 editor.setDecorations(errorDecoration, [])
169 editor.setDecorations(codeBlockLineNumberDecoration, [])
170 return
171 }
172
173 const { project, md } = projectInfo
174 const isActive = project === activeProject
175 const docText = doc.getText()
176
177 function getTextContent(source: SourceSlideInfo) {
178 const slides = project.data.slides.filter(
179 s => s.source === source || s.importChain?.includes(source),
180 )
181 const posInfo = slides?.length
182 ? mergeSlideNumbers(slides)
183 : isActive ? '(hidden)' : ''
184 const entryInfo = source.index === 0 && project.data.entry !== md
185 ? ` (entry: ${toRelativePath(project.entry)})`
186 : ''
187 const activeInfo = source.index === 0 && !isActive
188 ? ' (inactive)'
189 : ''
190 return ` ${posInfo}${entryInfo}${activeInfo}`
191 }
192
193 const firstLineRanges: DecorationOptions[] = []
194 const dividerRanges: DecorationOptions[] = []
195 const frontmatterContentRanges: DecorationOptions[] = []
196 const frontmatterEndRanges: DecorationOptions[] = []
197 for (const slide of md.slides) {
198 const lineNo = slide.frontmatterStyle === 'frontmatter'
199 ? slide.start
200 : slide.start - 1
201 const line = doc.lineAt(clamp(lineNo, 0, doc.lineCount))
202
203 const start = new Position(line.lineNumber, 0)
204 const startDividerRange = new Range(start, new Position(line.lineNumber, line.text.length))
205
206 // If a markdown has no headmatter, we should set `isWholeLine` to `false` for the first line
207 const isSpecialCase = slide.index === 0 && !slide.frontmatterStyle
208 const ranges = isSpecialCase ? firstLineRanges : dividerRanges
209 ranges.push({
210 range: startDividerRange,
211 renderOptions: {
212 after: {
213 contentText: getTextContent(slide),
214 fontWeight: 'bold',
215 color: new ThemeColor('panelTitle.activeBorder'),
216 },
217 },
218 })
219
220 if (slide.frontmatterRaw != null) {
221 const range = docText.slice(doc.offsetAt(start))
222 const match = range.match(RE_FRONTMATTER_BLOCK)
223 if (match && match.index != null) {
224 const endLine = doc.positionAt(doc.offsetAt(start) + match.index + match[0].length).line
225 frontmatterContentRanges.push({
226 range: new Range(new Position(line.lineNumber + 1, 0), new Position(endLine - 1, 0)),
227 })
228 if (endLine !== start.line) {
229 frontmatterEndRanges.push({
230 range: new Range(new Position(endLine, 0), new Position(endLine, 0)),
231 })
232 }
233 }
234 }
235 }
236
237 editor.setDecorations(firstLineDecoration, firstLineRanges)
238 editor.setDecorations(dividerDecoration, dividerRanges)
239 editor.setDecorations(frontmatterContentDecoration, frontmatterContentRanges)
240 editor.setDecorations(frontmatterEndDecoration, frontmatterEndRanges)
241
242 const errors: DecorationOptions[] = []
243 for (const error of md.errors ?? []) {
244 errors.push({
245 range: new Range(error.row, 0, error.row, 0),
246 renderOptions: {
247 after: {
248 contentText: ensurePrefix(error.message, ' '),
249 color: new ThemeColor('editorError.foreground'),
250 backgroundColor: new ThemeColor('editorError.background'),
251 },
252 },
253 })
254 }
255 editor.setDecorations(errorDecoration, errors)
256
257 if (lineNumbersEnabled) {
258 updateCodeBlockLineNumbers(editor, docText)
259 }
260 else {
261 editor.setDecorations(codeBlockLineNumberDecoration, [])
262 }
263 },
264 { immediate: true },
265 )
266 })
267
267 lines TYPESCRIPT