-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathextension.ts
executable file
·691 lines (570 loc) · 20.1 KB
/
extension.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
import * as path from 'path'
import type {
ExtensionContext,
TextDocument,
WorkspaceFolder,
ConfigurationScope,
WorkspaceConfiguration,
Selection,
} from 'vscode'
import {
workspace as Workspace,
window as Window,
Uri,
commands,
SymbolInformation,
Position,
Range,
RelativePattern,
DecorationRangeBehavior,
} from 'vscode'
import type {
DocumentFilter,
LanguageClientOptions,
ServerOptions,
} from 'vscode-languageclient/node'
import {
LanguageClient,
TransportKind,
State as LanguageClientState,
RevealOutputChannelOn,
} from 'vscode-languageclient/node'
import { languages as defaultLanguages } from '@tailwindcss/language-service/src/util/languages'
import * as semver from '@tailwindcss/language-service/src/util/semver'
import isObject from '@tailwindcss/language-service/src/util/isObject'
import namedColors from 'color-name'
import picomatch from 'picomatch'
import { CONFIG_GLOB, CSS_GLOB } from '@tailwindcss/language-server/src/lib/constants'
import braces from 'braces'
import normalizePath from 'normalize-path'
import * as servers from './servers/index'
const colorNames = Object.keys(namedColors)
const CLIENT_ID = 'tailwindcss-intellisense'
const CLIENT_NAME = 'Tailwind CSS IntelliSense'
let currentClient: Promise<LanguageClient> | null = null
function getUserLanguages(folder?: WorkspaceFolder): Record<string, string> {
const langs = Workspace.getConfiguration('tailwindCSS', folder).includeLanguages
return isObject(langs) ? langs : {}
}
function getGlobalExcludePatterns(scope: ConfigurationScope | null): string[] {
return Object.entries(Workspace.getConfiguration('files', scope)?.get('exclude') ?? [])
.filter(([, value]) => value === true)
.map(([key]) => key)
.filter(Boolean)
}
function getExcludePatterns(scope: ConfigurationScope | null): string[] {
return [
...getGlobalExcludePatterns(scope),
...(<string[]>Workspace.getConfiguration('tailwindCSS', scope).get('files.exclude')).filter(
Boolean,
),
]
}
function isExcluded(file: string, folder: WorkspaceFolder): boolean {
for (let pattern of getExcludePatterns(folder)) {
let matcher = picomatch(path.join(folder.uri.fsPath, pattern))
if (matcher(file)) {
return true
}
}
return false
}
function mergeExcludes(settings: WorkspaceConfiguration, scope: ConfigurationScope | null): any {
return {
...settings,
files: {
...settings.files,
exclude: getExcludePatterns(scope),
},
}
}
async function fileMayBeTailwindRelated(uri: Uri) {
let contents = (await Workspace.fs.readFile(uri)).toString()
let HAS_CONFIG = /@config\s*['"]/
let HAS_IMPORT = /@import\s*['"]/
let HAS_TAILWIND = /@tailwind\s*[^;]+;/
let HAS_THEME = /@theme\s*\{/
return (
HAS_CONFIG.test(contents) ||
HAS_IMPORT.test(contents) ||
HAS_TAILWIND.test(contents) ||
HAS_THEME.test(contents)
)
}
function selectionsAreEqual(
aSelections: readonly Selection[],
bSelections: readonly Selection[],
): boolean {
if (aSelections.length !== bSelections.length) {
return false
}
for (let i = 0; i < aSelections.length; i++) {
if (!aSelections[i].isEqual(bSelections[i])) {
return false
}
}
return true
}
async function getActiveTextEditorProject(): Promise<{ version: string } | null> {
// No editor, no project
let editor = Window.activeTextEditor
if (!editor) return null
// No server yet, no project
if (!currentClient) return null
// No workspace folder, no project
let uri = editor.document.uri
let folder = Workspace.getWorkspaceFolder(uri)
if (!folder) return null
// Excluded file, no project
if (isExcluded(uri.fsPath, folder)) return null
interface ProjectData {
version: string
}
// Ask the server for the project
try {
let client = await currentClient
let project = await client.sendRequest<ProjectData>('@/tailwindCSS/getProject', {
uri: uri.toString(),
})
return project
} catch {
return null
}
}
async function activeTextEditorSupportsClassSorting(): Promise<boolean> {
let project = await getActiveTextEditorProject()
if (!project) {
return false
}
// TODO: Use feature detection instead of version checking
return semver.gte(project.version, '3.0.0')
}
async function updateActiveTextEditorContext(): Promise<void> {
commands.executeCommand(
'setContext',
'tailwindCSS.activeTextEditorSupportsClassSorting',
await activeTextEditorSupportsClassSorting(),
)
}
function resetActiveTextEditorContext(): void {
commands.executeCommand('setContext', 'tailwindCSS.activeTextEditorSupportsClassSorting', false)
}
export async function activate(context: ExtensionContext) {
let outputChannel = Window.createOutputChannel(CLIENT_NAME)
context.subscriptions.push(outputChannel)
context.subscriptions.push(
commands.registerCommand('tailwindCSS.showOutput', () => {
if (outputChannel) {
outputChannel.show()
}
}),
)
await commands.executeCommand('setContext', 'tailwindCSS.hasOutputChannel', true)
outputChannel.appendLine(`Locating server…`)
let module = context.asAbsolutePath(path.join('dist', 'server.js'))
let prod = path.join('dist', 'tailwindServer.js')
try {
await Workspace.fs.stat(Uri.joinPath(context.extensionUri, prod))
module = context.asAbsolutePath(prod)
} catch (_) {}
async function sortSelection(): Promise<void> {
if (!Window.activeTextEditor) return
let { document, selections } = Window.activeTextEditor
if (selections.length === 0) {
return
}
let initialSelections = selections
let folder = Workspace.getWorkspaceFolder(document.uri)
if (!currentClient || !folder || isExcluded(document.uri.fsPath, folder)) {
throw Error(`No active Tailwind project found for file ${document.uri.fsPath}`)
}
let client = await currentClient
let result = await client.sendRequest<{ error: string } | { classLists: string[] }>(
'@/tailwindCSS/sortSelection',
{
uri: document.uri.toString(),
classLists: selections.map((selection) => document.getText(selection)),
},
)
if (
Window.activeTextEditor.document !== document ||
!selectionsAreEqual(initialSelections, Window.activeTextEditor.selections)
) {
return
}
if ('error' in result) {
throw Error(
{
'no-project': `No active Tailwind project found for file ${document.uri.fsPath}`,
}[result.error] ?? 'An unknown error occurred.',
)
}
let sortedClassLists = result.classLists
Window.activeTextEditor.edit((builder) => {
for (let i = 0; i < selections.length; i++) {
builder.replace(selections[i], sortedClassLists[i])
}
})
}
context.subscriptions.push(
commands.registerCommand('tailwindCSS.sortSelection', async () => {
try {
await sortSelection()
} catch (error) {
Window.showWarningMessage(`Couldn’t sort Tailwind classes: ${(error as any)?.message}`)
}
}),
)
context.subscriptions.push(
Window.onDidChangeActiveTextEditor(async () => {
await updateActiveTextEditorContext()
}),
)
let configWatcher = Workspace.createFileSystemWatcher(`**/${CONFIG_GLOB}`, false, true, true)
configWatcher.onDidCreate(async (uri) => {
let folder = Workspace.getWorkspaceFolder(uri)
if (!folder || isExcluded(uri.fsPath, folder)) {
return
}
await bootWorkspaceClient()
})
context.subscriptions.push(configWatcher)
let cssWatcher = Workspace.createFileSystemWatcher(`**/${CSS_GLOB}`, false, false, true)
async function bootClientIfCssFileMayBeTailwindRelated(uri: Uri) {
let folder = Workspace.getWorkspaceFolder(uri)
if (!folder || isExcluded(uri.fsPath, folder)) {
return
}
if (await fileMayBeTailwindRelated(uri)) {
await bootWorkspaceClient()
}
}
cssWatcher.onDidCreate(bootClientIfCssFileMayBeTailwindRelated)
cssWatcher.onDidChange(bootClientIfCssFileMayBeTailwindRelated)
context.subscriptions.push(cssWatcher)
// TODO: check if the actual language MAPPING changed
// not just the language IDs
// e.g. "plaintext" already exists but you change it from "html" to "css"
context.subscriptions.push(
Workspace.onDidChangeConfiguration(async (event) => {
let folders = Workspace.workspaceFolders ?? []
let needsReboot = folders.some((folder) => {
return (
event.affectsConfiguration('tailwindCSS.experimental.configFile', folder) ||
// TODO: Only reboot if the MAPPING changed instead of just the languages
// e.g. "plaintext" already exists but you change it from "html" to "css"
// TODO: This should not cause a reboot of the server but should instead
// have the server update its internal state
event.affectsConfiguration('tailwindCSS.includeLanguages', folder)
)
})
if (!needsReboot) {
return
}
// Stop the current server (if any)
if (currentClient) {
let client = await currentClient
await client.stop()
}
currentClient = null
// Start the server again with the new configuration
await bootWorkspaceClient()
}),
)
function bootWorkspaceClient() {
currentClient ??= bootIfNeeded()
return currentClient
}
async function bootIfNeeded() {
outputChannel.appendLine(`Booting server...`)
let colorDecorationType = Window.createTextEditorDecorationType({
before: {
width: '0.8em',
height: '0.8em',
contentText: ' ',
border: '0.1em solid',
margin: '0.1em 0.2em 0',
},
dark: {
before: {
borderColor: '#eeeeee',
},
},
light: {
before: {
borderColor: '#000000',
},
},
})
context.subscriptions.push(colorDecorationType)
let underlineDecorationType = Window.createTextEditorDecorationType({
textDecoration: 'none; border-bottom: 1px dashed currentColor',
rangeBehavior: DecorationRangeBehavior.ClosedClosed,
})
context.subscriptions.push(underlineDecorationType)
/**
* Clear all decorated colors from all visible text editors
*/
function clearColors(): void {
for (let editor of Window.visibleTextEditors) {
editor.setDecorations(colorDecorationType!, [])
}
}
let documentFilters: DocumentFilter[] = []
for (let folder of Workspace.workspaceFolders ?? []) {
let langs = new Set([...defaultLanguages, ...Object.keys(getUserLanguages(folder))])
for (let language of langs) {
documentFilters.push({
scheme: 'file',
language,
pattern: normalizePath(`${folder.uri.fsPath.replace(/[\[\]\{\}]/g, '?')}/**/*`),
})
}
}
let module = context.asAbsolutePath(path.join('dist', 'server.js'))
let prod = path.join('dist', 'tailwindServer.js')
try {
await Workspace.fs.stat(Uri.joinPath(context.extensionUri, prod))
module = context.asAbsolutePath(prod)
} catch (_) {}
let workspaceFile =
Workspace.workspaceFile?.scheme === 'file' ? Workspace.workspaceFile : undefined
let inspectPort =
Workspace.getConfiguration('tailwindCSS', workspaceFile).get<number | null>('inspectPort') ??
null
let serverOptions: ServerOptions = {
run: {
module,
transport: TransportKind.ipc,
options: {
execArgv: inspectPort === null ? [] : [`--inspect=${inspectPort}`],
},
},
debug: {
module,
transport: TransportKind.ipc,
options: {
execArgv: ['--nolazy', `--inspect=6011`],
},
},
}
let clientOptions: LanguageClientOptions = {
documentSelector: documentFilters,
diagnosticCollectionName: CLIENT_ID,
outputChannel: outputChannel,
revealOutputChannelOn: RevealOutputChannelOn.Never,
middleware: {
async resolveCompletionItem(item, token, next) {
let editor = Window.activeTextEditor
if (!editor) return null
let result = await next(item, token)
if (!result) return result
let selections = editor.selections
let edits = result.additionalTextEdits || []
if (selections.length <= 1 || edits.length === 0 || result['data'] !== 'variant') {
return result
}
let length = selections[0].start.character - edits[0].range.start.character
let prefixLength = edits[0].range.end.character - edits[0].range.start.character
let ranges = selections.map((selection) => {
return new Range(
new Position(selection.start.line, selection.start.character - length),
new Position(selection.start.line, selection.start.character - length + prefixLength),
)
})
if (
ranges
.map((range) => editor!.document.getText(range))
.every((text, _index, arr) => arr.indexOf(text) === 0)
) {
// all the same
result.additionalTextEdits = ranges.map((range) => {
return { range, newText: edits[0].newText }
})
} else {
result.insertText = typeof result.label === 'string' ? result.label : result.label.label
result.additionalTextEdits = []
}
return result
},
async provideDocumentColors(document, token, next) {
let colors = await next(document, token)
if (!colors) return colors
let editableColors = colors.filter((color) => {
let text =
Workspace.textDocuments.find((doc) => doc === document)?.getText(color.range) ?? ''
return new RegExp(
`-\\[(${colorNames.join('|')}|((?:#|rgba?\\(|hsla?\\())[^\\]]+)\\]$`,
).test(text)
})
let nonEditableColors = colors.filter((color) => !editableColors.includes(color))
let editors = Window.visibleTextEditors.filter((editor) => editor.document === document)
// Make sure we show document colors for all visible editors
// Not just the first one for a given document
for (let editor of editors) {
editor.setDecorations(
colorDecorationType,
nonEditableColors.map(({ range, color }) => ({
range,
renderOptions: {
before: {
backgroundColor: `rgba(${color.red * 255}, ${color.green * 255}, ${color.blue * 255}, ${color.alpha})`,
},
},
})),
)
}
return editableColors
},
workspace: {
configuration: (params) => {
return params.items.map(({ section, scopeUri }) => {
let scope: ConfigurationScope | null = null
if (scopeUri) {
let uri = Uri.parse(scopeUri)
let doc = Workspace.textDocuments.find((doc) => doc.uri.toString() === scopeUri)
// Make sure we ask VSCode for language specific settings for
// the document as it does not do this automatically
if (doc) {
scope = {
uri,
languageId: doc.languageId,
}
} else {
scope = uri
}
}
let settings = Workspace.getConfiguration(section, scope)
if (section === 'tailwindCSS') {
return mergeExcludes(settings, scope)
}
return settings
})
},
},
},
initializationOptions: {
workspaceFile: workspaceFile?.fsPath ?? undefined,
},
}
let client = new LanguageClient(CLIENT_ID, CLIENT_NAME, serverOptions, clientOptions)
client.onNotification('@/tailwindCSS/error', showError)
client.onNotification('@/tailwindCSS/warn', showWarning)
client.onNotification('@/tailwindCSS/clearColors', clearColors)
client.onNotification('@/tailwindCSS/projectInitialized', updateActiveTextEditorContext)
client.onNotification('@/tailwindCSS/projectReset', updateActiveTextEditorContext)
client.onNotification('@/tailwindCSS/projectsDestroyed', resetActiveTextEditorContext)
client.onRequest('@/tailwindCSS/annotations', ({ uri, annotations }) => {
Window.visibleTextEditors
.find((editor) => editor.document.uri.toString() === uri)
?.setDecorations(underlineDecorationType, annotations)
})
client.onRequest('@/tailwindCSS/getDocumentSymbols', showSymbols)
interface ErrorNotification {
message: string
}
async function showError({ message }: ErrorNotification) {
let action = await Window.showErrorMessage(message, 'Go to output')
if (action !== 'Go to output') return
commands.executeCommand('tailwindCSS.showOutput')
}
async function showWarning({ message }: ErrorNotification) {
let action = await Window.showWarningMessage(message, 'Go to output')
if (action !== 'Go to output') return
commands.executeCommand('tailwindCSS.showOutput')
}
interface DocumentSymbolsRequest {
uri: string
}
function showSymbols({ uri }: DocumentSymbolsRequest) {
return commands.executeCommand<SymbolInformation[]>(
'vscode.executeDocumentSymbolProvider',
Uri.parse(uri),
)
}
client.onDidChangeState(({ newState }) => {
if (newState !== LanguageClientState.Stopped) return
clearColors()
})
await client.start()
return client
}
async function bootClientIfNeeded(): Promise<void> {
if (currentClient) {
return
}
if (!(await anyFolderNeedsLanguageServer(Workspace.workspaceFolders ?? []))) {
return
}
await bootWorkspaceClient()
}
async function anyFolderNeedsLanguageServer(
folders: readonly WorkspaceFolder[],
): Promise<boolean> {
for (let folder of folders) {
if (await folderNeedsLanguageServer(folder)) {
return true
}
}
return false
}
async function folderNeedsLanguageServer(folder: WorkspaceFolder): Promise<boolean> {
let settings = Workspace.getConfiguration('tailwindCSS', folder)
if (settings.get('experimental.configFile') !== null) {
return true
}
let exclude = `{${getExcludePatterns(folder)
.flatMap((pattern) => braces.expand(pattern))
.join(',')
.replace(/{/g, '%7B')
.replace(/}/g, '%7D')}}`
let configFiles = await Workspace.findFiles(
new RelativePattern(folder, `**/${CONFIG_GLOB}`),
exclude,
1,
)
for (let file of configFiles) {
return true
}
let cssFiles = await Workspace.findFiles(new RelativePattern(folder, `**/${CSS_GLOB}`), exclude)
for (let file of cssFiles) {
outputChannel.appendLine(`Checking if ${file.fsPath} may be Tailwind-related…`)
if (await fileMayBeTailwindRelated(file)) {
return true
}
}
return false
}
async function didOpenTextDocument(document: TextDocument): Promise<void> {
if (document.languageId === 'tailwindcss') {
servers.css.boot(context, outputChannel)
}
// We are only interested in language mode text
if (document.uri.scheme !== 'file') {
return
}
let uri = document.uri
let folder = Workspace.getWorkspaceFolder(uri)
// Files outside a folder can't be handled. This might depend on the language.
// Single file languages like JSON might handle files outside the workspace folders.
if (!folder) return
await bootClientIfNeeded()
}
context.subscriptions.push(Workspace.onDidOpenTextDocument(didOpenTextDocument))
Workspace.textDocuments.forEach(didOpenTextDocument)
context.subscriptions.push(
Workspace.onDidChangeWorkspaceFolders(async () => {
let folderCount = Workspace.workspaceFolders?.length ?? 0
if (folderCount > 0) return
if (!currentClient) return
let client = await currentClient
client.stop()
currentClient = null
}),
)
}
export async function deactivate(): Promise<void> {
if (!currentClient) return
let client = await currentClient
await client.stop()
}