forked from unocss/unocss
/
annotation.ts
171 lines (150 loc) · 5.58 KB
/
annotation.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
159
160
161
162
163
164
165
166
167
168
169
170
171
import path from 'path'
import type { DecorationOptions, ExtensionContext, StatusBarItem } from 'vscode'
import { DecorationRangeBehavior, MarkdownString, Range, window, workspace } from 'vscode'
import { INCLUDE_COMMENT_IDE, getMatchedPositions } from './integration'
import { log } from './log'
import { getColorsMap, getPrettiedMarkdown, isCssId, throttle } from './utils'
import type { ContextLoader } from './contextLoader'
export async function registerAnnotations(
cwd: string,
contextLoader: ContextLoader,
status: StatusBarItem,
ext: ExtensionContext,
) {
let underline: boolean = workspace.getConfiguration().get('unocss.underline') ?? true
let colorPreview: boolean = workspace.getConfiguration().get('unocss.colorPreview') ?? true
ext.subscriptions.push(workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration('unocss.underline')) {
underline = workspace.getConfiguration().get('unocss.underline') ?? true
updateAnnotation()
}
if (event.affectsConfiguration('unocss.colorPreview')) {
colorPreview = workspace.getConfiguration().get('unocss.colorPreview') ?? true
updateAnnotation()
}
}))
workspace.onDidSaveTextDocument(async (doc) => {
const id = doc.uri.fsPath
const dir = path.dirname(id)
if (contextLoader.contextsMap.has(dir)) {
const ctx = contextLoader.contextsMap.get(dir)!
try {
await ctx.reloadConfig()
log.appendLine(`Config reloaded by ${path.relative(cwd, doc.uri.fsPath)}`)
}
catch (e) {
log.appendLine('Error on loading config')
log.appendLine(String(e))
}
}
})
const UnderlineDecoration = window.createTextEditorDecorationType({
textDecoration: 'none; border-bottom: 1px dashed currentColor',
rangeBehavior: DecorationRangeBehavior.ClosedClosed,
})
const NoneDecoration = window.createTextEditorDecorationType({
textDecoration: 'none',
rangeBehavior: DecorationRangeBehavior.ClosedClosed,
})
const colorDecoration = window.createTextEditorDecorationType({
before: {
width: '0.9em',
height: '0.9em',
contentText: ' ',
border: '1px solid',
margin: 'auto 0.2em auto 0;vertical-align: middle;border-radius:50%;',
},
dark: {
before: {
borderColor: '#eeeeee50',
},
},
light: {
before: {
borderColor: '#00000050',
},
},
})
async function updateAnnotation(editor = window.activeTextEditor) {
try {
const doc = editor?.document
if (!doc)
return reset()
const code = doc.getText()
const id = doc.uri.fsPath
if (!code)
return reset()
let ctx = await contextLoader.resolveContext(code, id)
if (!ctx)
ctx = await contextLoader.resolveClosestContext(code, id)
else if (!ctx.filter(code, id) && !code.includes(INCLUDE_COMMENT_IDE) && !isCssId(id))
return null
const result = await ctx.uno.generate(code, { id, preflights: false, minify: true })
const colorsMap = getColorsMap(ctx.uno, result)
const colorRanges: DecorationOptions[] = []
const _colorPositionsCache = new Map<string, string>() // cache for avoid duplicated color ranges
const ranges: DecorationOptions[] = (
await Promise.all(
getMatchedPositions(code, Array.from(result.matched))
.map(async (i): Promise<DecorationOptions> => {
// side-effect: update colorRanges
if (colorPreview && colorsMap.has(i[2]) && !_colorPositionsCache.has(`${i[0]}:${i[1]}`)) {
_colorPositionsCache.set(`${i[0]}:${i[1]}`, i[2])
colorRanges.push({
range: new Range(doc.positionAt(i[0]), doc.positionAt(i[1])),
renderOptions: { before: { backgroundColor: colorsMap.get(i[2]) } },
})
}
try {
const md = await getPrettiedMarkdown(ctx!.uno, i[2])
return {
range: new Range(doc.positionAt(i[0]), doc.positionAt(i[1])),
get hoverMessage() {
return new MarkdownString(md)
},
}
}
catch (e) {
log.appendLine(`Failed to parse ${i[2]}`)
log.appendLine(String(e))
return undefined!
}
}),
)
).filter(Boolean)
_colorPositionsCache.clear()
editor.setDecorations(colorDecoration, colorRanges)
if (underline) {
editor.setDecorations(NoneDecoration, [])
editor.setDecorations(UnderlineDecoration, ranges)
}
else {
editor.setDecorations(UnderlineDecoration, [])
editor.setDecorations(NoneDecoration, ranges)
}
status.text = `UnoCSS: ${result.matched.size}`
status.tooltip = new MarkdownString(`${result.matched.size} utilities used in this file`)
status.show()
function reset() {
editor?.setDecorations(UnderlineDecoration, [])
editor?.setDecorations(NoneDecoration, [])
editor?.setDecorations(colorDecoration, [])
status.hide()
}
}
catch (e) {
log.appendLine('Error on annotation')
log.appendLine(String(e))
}
}
const throttledUpdateAnnotation = throttle(updateAnnotation, 200)
window.onDidChangeActiveTextEditor(updateAnnotation)
workspace.onDidChangeTextDocument((e) => {
if (e.document === window.activeTextEditor?.document)
throttledUpdateAnnotation()
})
contextLoader.events.on('reload', async () => {
await updateAnnotation()
})
await updateAnnotation()
}