/
autocomplete.ts
207 lines (170 loc) · 5.78 KB
/
autocomplete.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import type { UnocssAutocomplete } from '@unocss/autocomplete'
import { createAutocomplete } from '@unocss/autocomplete'
import type { CompletionItemProvider, Disposable, ExtensionContext } from 'vscode'
import { CompletionItem, CompletionItemKind, CompletionList, MarkdownString, Range, languages, window, workspace } from 'vscode'
import type { UnoGenerator, UnocssPluginContext } from '@unocss/core'
import { getCSS, getColorString, getPrettiedCSS, getPrettiedMarkdown } from './utils'
import { log } from './log'
import type { ContextLoader } from './contextLoader'
import { isCssId } from './integration'
import { useConfigurations } from './configuration'
const defaultLanguageIds = [
'erb',
'haml',
'hbs',
'html',
'css',
'postcss',
'javascript',
'javascriptreact',
'markdown',
'ejs',
'php',
'svelte',
'typescript',
'typescriptreact',
'vue-html',
'vue',
'sass',
'scss',
'less',
'stylus',
'astro',
'rust',
]
const delimiters = ['-', ':', ' ', '"', '\'']
class UnoCompletionItem extends CompletionItem {
uno: UnoGenerator
value: string
constructor(label: string, kind: CompletionItemKind, value: string, uno: UnoGenerator) {
super(label, kind)
this.uno = uno
this.value = value
}
}
export async function registerAutoComplete(
contextLoader: ContextLoader,
ext: ExtensionContext,
) {
const allLanguages = await languages.getLanguages()
const autoCompletes = new Map<UnocssPluginContext, UnocssAutocomplete>()
const { configuration, watchChanged, disposable } = useConfigurations(ext)
contextLoader.events.on('contextReload', (ctx) => {
autoCompletes.delete(ctx)
})
contextLoader.events.on('contextUnload', (ctx) => {
autoCompletes.delete(ctx)
})
contextLoader.events.on('unload', (ctx) => {
autoCompletes.delete(ctx)
disposable.dispose()
})
function getAutocomplete(ctx: UnocssPluginContext) {
const cached = autoCompletes.get(ctx)
if (cached)
return cached
const autocomplete = createAutocomplete(ctx.uno, {
matchType: configuration.matchType,
})
autoCompletes.set(ctx, autocomplete)
return autocomplete
}
async function getMarkdown(uno: UnoGenerator, util: string, remToPxRatio: number) {
return new MarkdownString(await getPrettiedMarkdown(uno, util, remToPxRatio))
}
function validateLanguages(targets: string[]) {
const unValidLanguages: string[] = []
const validLanguages = targets.filter((language) => {
if (!allLanguages.includes(language)) {
unValidLanguages.push(language)
return false
}
return true
})
if (unValidLanguages.length)
window.showWarningMessage(`These language configurations are illegal: ${unValidLanguages.join(',')}`)
return validLanguages
}
const provider: CompletionItemProvider<UnoCompletionItem> = {
async provideCompletionItems(doc, position) {
const id = doc.uri.fsPath
if (!contextLoader.isTarget(id))
return null
const code = doc.getText()
if (!code)
return null
const ctx = await contextLoader.resolveClosestContext(code, id)
if (!ctx)
return null
if (!ctx.filter(code, id) && !isCssId(id))
return null
try {
const autoComplete = getAutocomplete(ctx)
const result = await autoComplete.suggestInFile(code, doc.offsetAt(position))
if (!result)
return
// log.appendLine(`🤖 ${id} | ${result.suggestions.slice(0, 10).map(v => `[${v[0]}, ${v[1]}]`).join(', ')}`)
if (!result.suggestions.length)
return
const completionItems: UnoCompletionItem[] = []
const suggestions = result.suggestions.slice(0, configuration.maxItems)
for (const [value, label] of suggestions) {
const css = await getCSS(ctx!.uno, value)
const colorString = getColorString(css)
const itemKind = colorString ? CompletionItemKind.Color : CompletionItemKind.EnumMember
const item = new UnoCompletionItem(label, itemKind, value, ctx!.uno)
const resolved = result.resolveReplacement(value)
item.insertText = resolved.replacement
item.range = new Range(doc.positionAt(resolved.start), doc.positionAt(resolved.end))
if (colorString) {
item.documentation = colorString
item.sortText = /-\d$/.test(label) ? '1' : '2' // reorder color completions
}
completionItems.push(item)
}
return new CompletionList(completionItems, true)
}
catch (e: any) {
log.appendLine('⚠️ Error on getting autocompletion items')
log.appendLine(String(e.stack ?? e))
return null
}
},
async resolveCompletionItem(item) {
const remToPxRatio = configuration.remToPxRatio ? configuration.remToPxRatio : -1
if (item.kind === CompletionItemKind.Color)
item.detail = await (await getPrettiedCSS(item.uno, item.value, remToPxRatio)).prettified
else
item.documentation = await getMarkdown(item.uno, item.value, remToPxRatio)
return item
},
}
let completeUnregister: Disposable
const registerProvider = () => {
completeUnregister?.dispose?.()
const languagesIds: string[] = workspace.getConfiguration().get('unocss.languageIds') || []
const validLanguages = validateLanguages(languagesIds)
completeUnregister = languages.registerCompletionItemProvider(
defaultLanguageIds.concat(validLanguages),
provider,
...delimiters,
)
return completeUnregister
}
watchChanged(['languagesIds'], () => {
ext.subscriptions.push(
registerProvider(),
)
})
watchChanged([
'matchType',
'maxItems',
'remToPxRatio',
'remToPxPreview',
], () => {
autoCompletes.clear()
})
ext.subscriptions.push(
registerProvider(),
)
}