-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathtw.ts
1064 lines (903 loc) · 31.7 KB
/
tw.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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
CompletionItem,
CompletionList,
CompletionParams,
Connection,
DocumentColorParams,
ColorInformation,
ColorPresentation,
Hover,
InitializeParams,
TextDocumentPositionParams,
ColorPresentationParams,
CodeActionParams,
CodeAction,
BulkUnregistration,
Disposable,
TextDocumentIdentifier,
DocumentLinkParams,
DocumentLink,
InitializeResult,
WorkspaceFolder,
} from 'vscode-languageserver/node'
import {
CompletionRequest,
DocumentColorRequest,
BulkRegistration,
CodeActionRequest,
HoverRequest,
DidChangeWatchedFilesNotification,
FileChangeType,
DocumentLinkRequest,
TextDocumentSyncKind,
} from 'vscode-languageserver/node'
import { URI } from 'vscode-uri'
import normalizePath from 'normalize-path'
import * as path from 'node:path'
import type * as chokidar from 'chokidar'
import picomatch from 'picomatch'
import * as parcel from './watcher/index.js'
import { equal } from '@tailwindcss/language-service/src/util/array'
import { CONFIG_GLOB, CSS_GLOB, PACKAGE_LOCK_GLOB, TSCONFIG_GLOB } from './lib/constants'
import { clearRequireCache, isObject, changeAffectsFile, normalizeDriveLetter } from './utils'
import { DocumentService } from './documents'
import { createProjectService, type ProjectService } from './projects'
import { type SettingsCache, createSettingsCache } from './config'
import { readCssFile } from './util/css'
import { ProjectLocator, type ProjectConfig } from './project-locator'
import type { TailwindCssSettings } from '@tailwindcss/language-service/src/util/state'
import { createResolver, Resolver } from './resolver'
import { retry } from './util/retry'
const TRIGGER_CHARACTERS = [
// class attributes
'"',
"'",
'`',
// between class names
' ',
// @apply and emmet-style
'.',
// config/theme helper
'(',
'[',
// End of an arbitrary value
']',
// JIT "important" prefix
'!',
// JIT opacity modifiers
'/',
// Between parts of a variant or class
'-',
] as const
async function getConfigFileFromCssFile(cssFile: string): Promise<string | null> {
let css = await readCssFile(cssFile)
if (!css) return null
let match = css.match(/@config\s*(?<config>'[^']+'|"[^"]+")/)
if (!match) {
return null
}
return normalizeDriveLetter(
normalizePath(path.resolve(path.dirname(cssFile), match.groups.config.slice(1, -1))),
)
}
export class TW {
private initPromise: Promise<void>
private lspHandlersAdded = false
private projects: Map<string, ProjectService>
private projectCounter: number
private documentService: DocumentService
public initializeParams: InitializeParams
private registrations: Promise<BulkUnregistration>
private disposables: Disposable[] = []
private watchPatterns: (patterns: string[]) => void = () => {}
private watched: string[] = []
private settingsCache: SettingsCache
constructor(private connection: Connection) {
this.documentService = new DocumentService(this.connection)
this.projects = new Map()
this.projectCounter = 0
this.settingsCache = createSettingsCache(connection)
}
async init(): Promise<void> {
if (!this.initPromise) {
this.initPromise = this._init()
}
await this.initPromise
}
private getWorkspaceFolders(): WorkspaceFolder[] {
if (this.initializeParams.workspaceFolders?.length) {
return this.initializeParams.workspaceFolders.map((folder) => ({
uri: URI.parse(folder.uri).fsPath,
name: folder.name,
}))
}
if (this.initializeParams.rootUri) {
return [
{
uri: URI.parse(this.initializeParams.rootUri).fsPath,
name: 'Root',
},
]
}
if (this.initializeParams.rootPath) {
return [
{
uri: URI.file(this.initializeParams.rootPath).fsPath,
name: 'Root',
},
]
}
return []
}
private async _init(): Promise<void> {
clearRequireCache()
let folders = this.getWorkspaceFolders().map((folder) => normalizePath(folder.uri))
if (folders.length === 0) {
console.error('No workspace folders found, not initializing.')
return
}
// Initialize each workspace separately
// We use `allSettled` here because failures in one folder should not prevent initialization of others
//
// NOTE: We should eventually be smart about avoiding duplicate work. We do
// not necessarily need to set up file watchers, search for projects, read
// configs, etc… per folder. Some of this work should be sharable.
let results = await Promise.allSettled(
folders.map((basePath) => this._initFolder(URI.file(basePath))),
)
for (let [idx, result] of results.entries()) {
if (result.status === 'rejected') {
console.error('Failed to initialize workspace folder', folders[idx], result.reason)
}
}
await this.listenForEvents()
}
private async _initFolder(baseUri: URI): Promise<void> {
let initUserLanguages = this.initializeParams.initializationOptions?.userLanguages ?? {}
if (Object.keys(initUserLanguages).length > 0) {
console.warn(
'Language mappings are currently set via initialization options (`userLanguages`). This is deprecated and will be removed in a future release. Please use the `tailwindCSS.includeLanguages` setting instead.',
)
}
let base = baseUri.fsPath
let workspaceFolders: Array<ProjectConfig> = []
let globalSettings = await this.settingsCache.get()
let ignore = globalSettings.tailwindCSS.files.exclude
// Get user languages for the given workspace folder
let folderSettings = await this.settingsCache.get(baseUri.toString())
// Merge the languages from the global settings with the languages from the workspace folder
let userLanguages = {
...initUserLanguages,
...(folderSettings.tailwindCSS.includeLanguages ?? {}),
}
let cssFileConfigMap: Map<string, string> = new Map()
let configTailwindVersionMap: Map<string, string> = new Map()
// base directory to resolve relative `experimental.configFile` paths against
let userDefinedConfigBase = this.initializeParams.initializationOptions?.workspaceFile
? path.dirname(this.initializeParams.initializationOptions.workspaceFile)
: base
function getExplicitConfigFiles(settings: TailwindCssSettings) {
function resolvePathForConfig(filepath: string) {
return normalizeDriveLetter(normalizePath(path.resolve(userDefinedConfigBase, filepath)))
}
let configFileOrFiles = settings.experimental.configFile
let configs: Record<string, string[]> = {}
if (typeof configFileOrFiles === 'string') {
let configFile = resolvePathForConfig(configFileOrFiles)
let docSelectors = [resolvePathForConfig(path.resolve(base, '**'))]
configs[configFile] = docSelectors
} else if (isObject(configFileOrFiles)) {
for (let [configFile, selectors] of Object.entries(configFileOrFiles)) {
if (typeof configFile !== 'string') return null
configFile = resolvePathForConfig(configFile)
let docSelectors: string[]
if (typeof selectors === 'string') {
docSelectors = [resolvePathForConfig(selectors)]
} else if (Array.isArray(selectors)) {
docSelectors = selectors.map(resolvePathForConfig)
} else {
return null
}
configs[configFile] = docSelectors
}
} else if (configFileOrFiles) {
return null
}
return Object.entries(configs)
}
let configs = getExplicitConfigFiles(globalSettings.tailwindCSS)
if (configs === null) {
console.error('Invalid `experimental.configFile` configuration, not initializing.')
return
}
let resolver = await createResolver({
root: base,
pnp: true,
tsconfig: true,
})
let locator = new ProjectLocator(base, globalSettings, resolver)
if (configs.length > 0) {
console.log('Loading Tailwind CSS projects from the workspace settings.')
workspaceFolders = await locator.loadAllFromWorkspace(configs)
} else {
console.log("Searching for Tailwind CSS projects in the workspace's folders.")
workspaceFolders = await locator.search()
}
for (let project of workspaceFolders) {
// Track the Tailwind version for a given config
configTailwindVersionMap.set(project.config.path, project.tailwind.version)
if (project.config.source !== 'css') continue
// Track the config file for a given CSS file
for (let file of project.config.entries) {
if (file.type !== 'css') continue
cssFileConfigMap.set(file.path, project.config.path)
}
}
let workspaceDescription = workspaceFolders.map((workspace) => {
return {
folder: workspace.folder,
config: workspace.config.path,
selectors: workspace.documentSelector,
user: workspace.isUserConfigured,
tailwind: workspace.tailwind,
}
})
console.log(`[Global] Creating projects: ${JSON.stringify(workspaceDescription)}`)
const onDidChangeWatchedFiles = async (
changes: Array<{ file: string; type: FileChangeType }>,
): Promise<void> => {
let needsRestart = false
let needsSoftRestart = false
let isPackageMatcher = picomatch(`**/${PACKAGE_LOCK_GLOB}`, { dot: true })
let isCssMatcher = picomatch(`**/${CSS_GLOB}`, { dot: true })
let isConfigMatcher = picomatch(`**/${CONFIG_GLOB}`, { dot: true })
let isTSConfigMatcher = picomatch(`**/${TSCONFIG_GLOB}`, { dot: true })
changeLoop: for (let change of changes) {
let normalizedFilename = normalizePath(change.file)
// This filename comes from VSCode rather than from the filesystem
// which means the drive letter *might* be lowercased and we need
// to normalize it so that we can compare it properly.
normalizedFilename = normalizeDriveLetter(normalizedFilename)
for (let ignorePattern of ignore) {
let isIgnored = picomatch(ignorePattern, { dot: true })
if (isIgnored(normalizedFilename)) {
continue changeLoop
}
}
let isPackageFile = isPackageMatcher(normalizedFilename)
if (isPackageFile) {
for (let [, project] of this.projects) {
let twVersion = require('tailwindcss/package.json').version
try {
let v = require(
await resolver.resolveCjsId(
'tailwindcss/package.json',
path.dirname(project.projectConfig.configPath),
),
).version
if (typeof v === 'string') {
twVersion = v
}
} catch {}
if (configTailwindVersionMap.get(project.projectConfig.configPath) !== twVersion) {
needsRestart = true
break changeLoop
}
}
}
let isTsconfig = isTSConfigMatcher(normalizedFilename)
if (isTsconfig) {
// TODO: Use a refresh() instead of a full server restart
// let refreshPromise = retry({
// tries: 4,
// delay: 250,
// callback: () => resolver.refresh(),
// })
// try {
// await refreshPromise
// } catch (err) {
// console.error('Unable to reload resolver', err)
// }
needsRestart = true
break changeLoop
}
for (let [, project] of this.projects) {
if (!project.state.v4) continue
if (!changeAffectsFile(normalizedFilename, project.dependencies())) continue
needsSoftRestart = true
break changeLoop
}
let isCssFile = isCssMatcher(`**/${CSS_GLOB}`)
if (isCssFile && change.type !== FileChangeType.Deleted) {
// TODO: Determine if we can only use `normalizedFilename`
let configPath =
(await getConfigFileFromCssFile(normalizedFilename)) ||
(await getConfigFileFromCssFile(change.file))
if (
cssFileConfigMap.has(normalizedFilename) &&
cssFileConfigMap.get(normalizedFilename) !== configPath
) {
needsRestart = true
break
} else if (!cssFileConfigMap.has(normalizedFilename) && configPath) {
needsRestart = true
break
}
}
let isConfigFile = isConfigMatcher(normalizedFilename)
if (isConfigFile && change.type === FileChangeType.Created) {
needsRestart = true
break
}
for (let [, project] of this.projects) {
if (
change.type === FileChangeType.Deleted &&
changeAffectsFile(normalizedFilename, [project.projectConfig.configPath])
) {
needsRestart = true
break changeLoop
}
}
}
if (needsRestart) {
this.restart()
return
}
if (needsSoftRestart) {
try {
await this.softRestart()
} catch {
this.restart()
}
return
}
for (let [, project] of this.projects) {
project.onFileEvents(changes)
}
}
if (this.initializeParams.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration) {
this.disposables.push(
this.connection.onDidChangeWatchedFiles(async ({ changes }) => {
let normalizedChanges = changes
.map(({ uri, type }) => ({
file: URI.parse(uri).fsPath,
type,
}))
.filter(
(change, changeIndex, changes) =>
changes.findIndex((c) => c.file === change.file && c.type === change.type) ===
changeIndex,
)
await onDidChangeWatchedFiles(normalizedChanges)
}),
)
let disposable = await this.connection.client.register(
DidChangeWatchedFilesNotification.type,
{
watchers: [
{ globPattern: `**/${CONFIG_GLOB}` },
{ globPattern: `**/${PACKAGE_LOCK_GLOB}` },
{ globPattern: `**/${CSS_GLOB}` },
{ globPattern: `**/${TSCONFIG_GLOB}` },
],
},
)
this.disposables.push(disposable)
this.watchPatterns = (patterns) => {
let newPatterns = this.filterNewWatchPatterns(patterns)
if (newPatterns.length) {
console.log(`[Global] Adding watch patterns: ${newPatterns.join(', ')}`)
this.connection.client
.register(DidChangeWatchedFilesNotification.type, {
watchers: newPatterns.map((pattern) => ({ globPattern: pattern })),
})
.then((disposable) => {
this.disposables.push(disposable)
})
}
}
} else if (parcel.getBinding()) {
let typeMap = {
create: FileChangeType.Created,
update: FileChangeType.Changed,
delete: FileChangeType.Deleted,
}
let subscription = await parcel.subscribe(
base,
(err, events) => {
onDidChangeWatchedFiles(
events.map((event) => ({ file: event.path, type: typeMap[event.type] })),
)
},
{
ignore: ignore.map((ignorePattern) =>
path.resolve(base, ignorePattern.replace(/^[*/]+/, '').replace(/[*/]+$/, '')),
),
},
)
this.disposables.push({
dispose() {
subscription.unsubscribe()
},
})
} else {
let watch: typeof chokidar.watch = require('chokidar').watch
let chokidarWatcher = watch(
[`**/${CONFIG_GLOB}`, `**/${PACKAGE_LOCK_GLOB}`, `**/${CSS_GLOB}`, `**/${TSCONFIG_GLOB}`],
{
cwd: base,
ignorePermissionErrors: true,
ignoreInitial: true,
ignored: ignore,
awaitWriteFinish: {
stabilityThreshold: 100,
pollInterval: 20,
},
},
)
await new Promise<void>((resolve) => {
chokidarWatcher.on('ready', () => resolve())
})
chokidarWatcher
.on('add', (file) =>
onDidChangeWatchedFiles([
{ file: path.resolve(base, file), type: FileChangeType.Created },
]),
)
.on('change', (file) =>
onDidChangeWatchedFiles([
{ file: path.resolve(base, file), type: FileChangeType.Changed },
]),
)
.on('unlink', (file) =>
onDidChangeWatchedFiles([
{ file: path.resolve(base, file), type: FileChangeType.Deleted },
]),
)
this.disposables.push({
dispose() {
chokidarWatcher.close()
},
})
this.watchPatterns = (patterns) => {
let newPatterns = this.filterNewWatchPatterns(patterns)
if (newPatterns.length) {
console.log(`[Global] Adding watch patterns: ${newPatterns.join(', ')}`)
chokidarWatcher.add(newPatterns)
}
}
}
console.log(`[Global] Preparing projects...`)
await Promise.all(
workspaceFolders.map((projectConfig) =>
this.addProject(
projectConfig,
this.initializeParams,
this.watchPatterns,
configTailwindVersionMap.get(projectConfig.configPath),
userLanguages,
resolver,
baseUri,
),
),
)
console.log(`[Global] Initializing projects...`)
// init projects for documents that are _already_ open
let readyDocuments: string[] = []
let enabledProjectCount = 0
for (let document of this.documentService.getAllDocuments()) {
let project = this.getProject(document)
if (project && !project.enabled()) {
project.enable()
await project.tryInit()
enabledProjectCount++
}
readyDocuments.push(document.uri)
}
console.log(`[Global] Initialized ${enabledProjectCount} projects`)
this.setupLSPHandlers()
this.disposables.push(
this.connection.onDidChangeConfiguration(async ({ settings }) => {
let previousExclude = globalSettings.tailwindCSS.files.exclude
this.settingsCache.clear()
globalSettings = await this.settingsCache.get()
if (!equal(previousExclude, globalSettings.tailwindCSS.files.exclude)) {
this.restart()
return
}
for (let [, project] of this.projects) {
project.onUpdateSettings(settings)
}
}),
)
const isTestMode = this.initializeParams.initializationOptions?.testMode ?? false
if (!isTestMode) return
console.log(`[Global][Test] Sending document notifications...`)
await Promise.all(
readyDocuments.map((uri) =>
this.connection.sendNotification('@/tailwindCSS/documentReady', {
uri,
}),
),
)
}
private async listenForEvents() {
const isTestMode = this.initializeParams.initializationOptions?.testMode ?? false
this.disposables.push(
this.connection.onShutdown(() => {
this.dispose()
}),
)
this.disposables.push(
this.documentService.onDidChangeContent((change) => {
this.getProject(change.document)?.provideDiagnostics(change.document)
const { document } = change
this.getProject(document)
?.provideAnnotations(document)
.then((annotations) => {
this.connection.sendRequest('@/tailwindCSS/annotations', {
uri: document.uri,
annotations,
})
})
}),
)
this.disposables.push(
this.documentService.onDidOpen(async (event) => {
let project = this.getProject(event.document)
if (!project) return
if (!project.enabled()) {
project.enable()
await project.tryInit()
}
if (!isTestMode) return
// TODO: This is a hack and shouldn't be necessary
// await new Promise((resolve) => setTimeout(resolve, 100))
await this.connection.sendNotification('@/tailwindCSS/documentReady', {
uri: event.document.uri,
})
const { document } = event
this.getProject(document)
?.provideAnnotations(document)
.then((annotations) => {
this.connection.sendRequest('@/tailwindCSS/annotations', {
uri: document.uri,
annotations,
})
})
}),
)
this.documentService.getAllDocuments().forEach((document) => {
this.getProject(document)
?.provideAnnotations(document)
.then((annotations) => {
this.connection.sendRequest('@/tailwindCSS/annotations', {
uri: document.uri,
annotations,
})
})
})
if (this.initializeParams.capabilities.workspace.workspaceFolders) {
this.disposables.push(
this.connection.workspace.onDidChangeWorkspaceFolders(async (evt) => {
// Initialize any new folders that have appeared
let added = evt.added
.map((folder) => ({
uri: URI.parse(folder.uri).fsPath,
name: folder.name,
}))
.map((folder) => normalizePath(folder.uri))
await Promise.allSettled(added.map((basePath) => this._initFolder(URI.file(basePath))))
// TODO: If folders get removed we should cleanup any associated state and resources
}),
)
}
// TODO: This is a hack and shouldn't be necessary
if (isTestMode) {
await this.connection.sendNotification('@/tailwindCSS/serverReady')
}
}
private filterNewWatchPatterns(patterns: string[]) {
// Make sure the list of patterns is unique
patterns = Array.from(new Set(patterns))
// Filter out any patterns that are already being watched
patterns = patterns.filter((pattern) => !this.watched.includes(pattern))
this.watched.push(...patterns)
return patterns
}
private async addProject(
projectConfig: ProjectConfig,
params: InitializeParams,
watchPatterns: (patterns: string[]) => void,
tailwindVersion: string,
userLanguages: Record<string, string>,
resolver: Resolver,
baseUri: URI,
): Promise<void> {
let key = String(this.projectCounter++)
const project = await createProjectService(
key,
projectConfig,
this.connection,
params,
this.documentService,
() => this.updateCapabilities(),
() => {
for (let document of this.documentService.getAllDocuments()) {
let project = this.getProject(document)
if (project && !project.enabled()) {
project.enable()
project.tryInit()
break
}
}
},
() => this.refreshDiagnostics(),
(patterns: string[]) => watchPatterns(patterns),
tailwindVersion,
this.settingsCache.get,
userLanguages,
resolver,
)
this.projects.set(key, project)
if (!this.supportsTailwindProjectDetails) {
return
}
this.connection.sendNotification('@/tailwindCSS/projectDetails', {
uri: baseUri.toString(),
config: projectConfig.configPath,
tailwind: projectConfig.tailwind,
})
}
private get supportsTailwindProjectDetails() {
return this.initializeParams.capabilities.experimental?.['tailwind']?.projectDetails ?? false
}
private refreshDiagnostics() {
for (let doc of this.documentService.getAllDocuments()) {
let project = this.getProject(doc)
if (project) {
project.provideDiagnosticsForce(doc)
} else {
this.connection.sendDiagnostics({ uri: doc.uri, diagnostics: [] })
}
}
}
setupLSPHandlers() {
if (this.lspHandlersAdded) {
return
}
this.lspHandlersAdded = true
this.connection.onHover(this.onHover.bind(this))
this.connection.onCompletion(this.onCompletion.bind(this))
this.connection.onCompletionResolve(this.onCompletionResolve.bind(this))
this.connection.onDocumentColor(this.onDocumentColor.bind(this))
this.connection.onColorPresentation(this.onColorPresentation.bind(this))
this.connection.onCodeAction(this.onCodeAction.bind(this))
this.connection.onDocumentLinks(this.onDocumentLinks.bind(this))
this.connection.onRequest(this.onRequest.bind(this))
}
private onRequest(
method: '@/tailwindCSS/sortSelection',
params: { uri: string; classLists: string[] },
): { error: string } | { classLists: string[] }
private onRequest(
method: '@/tailwindCSS/getProject',
params: { uri: string },
): { version: string } | null
private onRequest(method: string, params: any): any {
if (method === '@/tailwindCSS/sortSelection') {
let project = this.getProject({ uri: params.uri })
if (!project) {
return { error: 'no-project' }
}
try {
return { classLists: project.sortClassLists(params.classLists) }
} catch {
return { error: 'unknown' }
}
}
if (method === '@/tailwindCSS/getProject') {
let project = this.getProject({ uri: params.uri })
if (!project || !project.enabled() || !project.state?.enabled) {
return null
}
return {
version: project.state.version,
}
}
}
private updateCapabilities() {
if (!supportsDynamicRegistration(this.initializeParams)) {
return
}
if (this.registrations) {
this.registrations.then((r) => r.dispose())
}
let projects = Array.from(this.projects.values())
let capabilities = BulkRegistration.create()
capabilities.add(HoverRequest.type, { documentSelector: null })
capabilities.add(DocumentColorRequest.type, { documentSelector: null })
capabilities.add(CodeActionRequest.type, { documentSelector: null })
capabilities.add(DocumentLinkRequest.type, { documentSelector: null })
capabilities.add(CompletionRequest.type, {
documentSelector: null,
resolveProvider: true,
triggerCharacters: [
...TRIGGER_CHARACTERS,
...projects
.map((project) => project.state.separator)
.filter((sep) => typeof sep === 'string')
.map((sep) => sep.slice(-1)),
].filter(Boolean),
})
this.registrations = this.connection.client.register(capabilities)
}
private getProject(document: TextDocumentIdentifier): ProjectService {
let fallbackProject: ProjectService
let matchedProject: ProjectService
let matchedPriority: number = Infinity
let uri = URI.parse(document.uri)
let fsPath = uri.fsPath
let normalPath = uri.path
// This filename comes from VSCode rather than from the filesystem
// which means the drive letter *might* be lowercased and we need
// to normalize it so that we can compare it properly.
fsPath = normalizeDriveLetter(fsPath)
for (let project of this.projects.values()) {
if (!project.projectConfig.configPath) {
fallbackProject = fallbackProject ?? project
continue
}
let documentSelector = project
.documentSelector()
.concat()
// move all the negated patterns to the front
.sort((a, z) => {
if (a.pattern.startsWith('!') && !z.pattern.startsWith('!')) {
return -1
}
if (!a.pattern.startsWith('!') && z.pattern.startsWith('!')) {
return 1
}
return 0
})
for (let selector of documentSelector) {
let pattern = selector.pattern.replace(/[\[\]{}()]/g, (m) => `\\${m}`)
if (pattern.startsWith('!')) {
if (picomatch(pattern.slice(1), { dot: true })(fsPath)) {
break
}
if (picomatch(pattern.slice(1), { dot: true })(normalPath)) {
break
}
}
if (picomatch(pattern, { dot: true })(fsPath) && selector.priority < matchedPriority) {
matchedProject = project
matchedPriority = selector.priority
continue
}
if (picomatch(pattern, { dot: true })(normalPath) && selector.priority < matchedPriority) {
matchedProject = project
matchedPriority = selector.priority
continue
}
}
}
let project = matchedProject ?? fallbackProject
if (!project) {
console.debug('[GLOBAL] No matching project for document', {
fsPath,
normalPath,
})
}
return project
}
async onDocumentColor(params: DocumentColorParams): Promise<ColorInformation[]> {
await this.init()
return this.getProject(params.textDocument)?.onDocumentColor(params) ?? []
}
async onColorPresentation(params: ColorPresentationParams): Promise<ColorPresentation[]> {
await this.init()
return this.getProject(params.textDocument)?.onColorPresentation(params) ?? []
}
async onHover(params: TextDocumentPositionParams): Promise<Hover> {
await this.init()
return this.getProject(params.textDocument)?.onHover(params) ?? null
}
async onCompletion(params: CompletionParams): Promise<CompletionList> {
await this.init()
return this.getProject(params.textDocument)?.onCompletion(params) ?? null
}
async onCompletionResolve(item: CompletionItem): Promise<CompletionItem> {
await this.init()
return this.projects.get(item.data?._projectKey)?.onCompletionResolve(item) ?? null
}
async onCodeAction(params: CodeActionParams): Promise<CodeAction[]> {
await this.init()
return this.getProject(params.textDocument)?.onCodeAction(params) ?? null
}
async onDocumentLinks(params: DocumentLinkParams): Promise<DocumentLink[]> {
await this.init()
return this.getProject(params.textDocument)?.onDocumentLinks(params) ?? null
}
setup() {
this.connection.onInitialize(async (params: InitializeParams): Promise<InitializeResult> => {
this.initializeParams = params
if (supportsDynamicRegistration(params)) {
return {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
workspace: {
workspaceFolders: {
changeNotifications: true,
},
},
},
}
}
this.setupLSPHandlers()
return {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
hoverProvider: true,
colorProvider: true,
codeActionProvider: true,
documentLinkProvider: {},
completionProvider: {
resolveProvider: true,
triggerCharacters: [...TRIGGER_CHARACTERS, ':'],
},
workspace: {