-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathfind.ts
544 lines (478 loc) · 16.5 KB
/
find.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
import type { Range, Position } from 'vscode-languageserver'
import type { TextDocument } from 'vscode-languageserver-textdocument'
import type { DocumentClassName, DocumentClassList, State, DocumentHelperFunction } from './state'
import lineColumn from 'line-column'
import { isCssContext, isCssDoc } from './css'
import { isHtmlContext, isVueDoc } from './html'
import { isWithinRange } from './isWithinRange'
import { isJsxContext } from './js'
import { dedupeByRange, flatten } from './array'
import { getClassAttributeLexer, getComputedClassAttributeLexer } from './lexers'
import { getLanguageBoundaries } from './getLanguageBoundaries'
import { absoluteRange } from './absoluteRange'
import { getTextWithoutComments } from './doc'
import { isSemicolonlessCssLanguage } from './languages'
import { customClassesIn } from './classes'
import { SEARCH_RANGE } from './constants'
export function findAll(re: RegExp, str: string): RegExpMatchArray[] {
let match: RegExpMatchArray
let matches: RegExpMatchArray[] = []
while ((match = re.exec(str)) !== null) {
matches.push({ ...match })
}
return matches
}
export function findLast(re: RegExp, str: string): RegExpMatchArray {
const matches = findAll(re, str)
if (matches.length === 0) {
return null
}
return matches[matches.length - 1]
}
export function getClassNamesInClassList(
{ classList, range, important }: DocumentClassList,
blocklist: State['blocklist'],
): DocumentClassName[] {
const parts = classList.split(/(\s+)/)
const names: DocumentClassName[] = []
let index = 0
for (let i = 0; i < parts.length; i++) {
if (i % 2 === 0 && !blocklist.includes(parts[i])) {
const start = indexToPosition(classList, index)
const end = indexToPosition(classList, index + parts[i].length)
names.push({
className: parts[i],
classList: {
classList,
range,
important,
},
relativeRange: {
start,
end,
},
range: {
start: {
line: range.start.line + start.line,
character: (end.line === 0 ? range.start.character : 0) + start.character,
},
end: {
line: range.start.line + end.line,
character: (end.line === 0 ? range.start.character : 0) + end.character,
},
},
})
}
index += parts[i].length
}
return names
}
export async function findClassNamesInRange(
state: State,
doc: TextDocument,
range?: Range,
mode?: 'html' | 'css' | 'jsx',
includeCustom: boolean = true,
): Promise<DocumentClassName[]> {
const classLists = await findClassListsInRange(state, doc, range, mode, includeCustom)
return flatten(
classLists.map((classList) => getClassNamesInClassList(classList, state.blocklist)),
)
}
export async function findClassNamesInDocument(
state: State,
doc: TextDocument,
): Promise<DocumentClassName[]> {
const classLists = await findClassListsInDocument(state, doc)
return flatten(
classLists.map((classList) => getClassNamesInClassList(classList, state.blocklist)),
)
}
export function findClassListsInCssRange(
state: State,
doc: TextDocument,
range?: Range,
lang?: string,
): DocumentClassList[] {
const text = getTextWithoutComments(doc, 'css', range)
let regex = isSemicolonlessCssLanguage(lang ?? doc.languageId, state.editor?.userLanguages)
? /(@apply\s+)(?<classList>[^}\r\n]+?)(?<important>\s*!important)?(?:\r|\n|}|$)/g
: /(@apply\s+)(?<classList>[^;}]+?)(?<important>\s*!important)?\s*[;}]/g
const matches = findAll(regex, text)
const globalStart: Position = range ? range.start : { line: 0, character: 0 }
return matches.map((match) => {
const start = indexToPosition(text, match.index + match[1].length)
const end = indexToPosition(text, match.index + match[1].length + match.groups.classList.length)
return {
classList: match.groups.classList,
important: Boolean(match.groups.important),
range: {
start: {
line: globalStart.line + start.line,
character: (end.line === 0 ? globalStart.character : 0) + start.character,
},
end: {
line: globalStart.line + end.line,
character: (end.line === 0 ? globalStart.character : 0) + end.character,
},
},
}
})
}
async function findCustomClassLists(
state: State,
doc: TextDocument,
range?: Range,
): Promise<DocumentClassList[]> {
const settings = await state.editor.getConfiguration(doc.uri)
const regexes = settings.tailwindCSS.experimental.classRegex
if (!Array.isArray(regexes) || regexes.length === 0) return []
const text = doc.getText(range ? { ...range, start: doc.positionAt(0) } : undefined)
const result: DocumentClassList[] = []
try {
for (let match of customClassesIn({ text, filters: regexes })) {
result.push({
classList: match.classList,
range: {
start: doc.positionAt(match.range[0]),
end: doc.positionAt(match.range[1]),
},
})
}
} catch (err) {
console.error(err)
console.log({ text, filters: regexes })
throw new Error('Failed to parse custom class regex')
}
return result
}
export function matchClassAttributes(text: string, attributes: string[]): RegExpMatchArray[] {
const attrs = attributes.filter((x) => typeof x === 'string').flatMap((a) => [a, `\\[${a}\\]`])
const re = /(?:\s|:|\()(ATTRS)\s*=\s*['"`{]/
return findAll(new RegExp(re.source.replace('ATTRS', attrs.join('|')), 'gi'), text)
}
export function matchClassFunctions(text: string, fnNames: string[]): RegExpMatchArray[] {
// 1. Validate the list of function name patterns provided by the user
let names = fnNames.filter((x) => typeof x === 'string')
if (names.length === 0) return []
// 2. Extract function names in the document
// This is intentionally scoped to JS syntax for now but should be extended to
// other languages in the future
//
// This regex the JS pattern for an identifier + function call with some
// additional constraints:
//
// - It needs to be in an expression position — so it must be preceded by
// whitespace, parens, curlies, commas, whitespace, etc…
// - It must look like a fn call or a tagged template literal
let FN_NAMES = /(?<=^|[:=,;\s{()])([\p{ID_Start}$_][\p{ID_Continue}$_.]*)[(`]/dgiu
let foundFns = findAll(FN_NAMES, text)
// 3. Match against the function names in the document
let re = /^(NAMES)$/
let isClassFn = new RegExp(re.source.replace('NAMES', names.join('|')), 'i')
let matches = foundFns.filter((fn) => isClassFn.test(fn[1]))
return matches
}
export async function findClassListsInHtmlRange(
state: State,
doc: TextDocument,
type: 'html' | 'js' | 'jsx',
range?: Range,
): Promise<DocumentClassList[]> {
if (!state.editor) return []
const text = getTextWithoutComments(doc, type, range)
const settings = (await state.editor.getConfiguration(doc.uri)).tailwindCSS
const matches = matchClassAttributes(text, settings.classAttributes)
let boundaries = getLanguageBoundaries(state, doc)
for (let boundary of boundaries ?? []) {
let isJsContext = boundary.type === 'js' || boundary.type === 'jsx'
if (!isJsContext) continue
if (!settings.classFunctions?.length) continue
let str = doc.getText(boundary.range)
let offset = doc.offsetAt(boundary.range.start)
let fnMatches = matchClassFunctions(str, settings.classFunctions)
fnMatches.forEach((match) => {
if (match.index) match.index += offset
})
matches.push(...fnMatches)
}
const existingResultSet = new Set<string>()
const results: DocumentClassList[] = []
matches.forEach((match) => {
const subtext = text.substr(match.index + match[0].length - 1)
let lexer =
match[0][0] === ':' || (match[1].startsWith('[') && match[1].endsWith(']'))
? getComputedClassAttributeLexer()
: getClassAttributeLexer()
lexer.reset(subtext)
let classLists: { value: string; offset: number }[] = []
let token: moo.Token
let currentClassList: { value: string; offset: number }
try {
for (let token of lexer) {
if (token.type === 'classlist' || token.type.startsWith('arb')) {
if (currentClassList) {
currentClassList.value += token.value
} else {
currentClassList = {
value: token.value,
offset: token.offset,
}
}
} else {
if (currentClassList) {
classLists.push({
value: currentClassList.value,
offset: currentClassList.offset,
})
}
currentClassList = undefined
}
}
} catch (_) {}
if (currentClassList) {
classLists.push({
value: currentClassList.value,
offset: currentClassList.offset,
})
}
classLists.forEach(({ value, offset }) => {
if (value.trim() === '') {
return null
}
const before = value.match(/^\s*/)
const beforeOffset = before === null ? 0 : before[0].length
const after = value.match(/\s*$/)
const afterOffset = after === null ? 0 : -after[0].length
const start = indexToPosition(text, match.index + match[0].length - 1 + offset + beforeOffset)
const end = indexToPosition(
text,
match.index + match[0].length - 1 + offset + value.length + afterOffset,
)
const result: DocumentClassList = {
classList: value.substr(beforeOffset, value.length + afterOffset),
range: {
start: {
line: (range?.start.line || 0) + start.line,
character: (end.line === 0 ? range?.start.character || 0 : 0) + start.character,
},
end: {
line: (range?.start.line || 0) + end.line,
character: (end.line === 0 ? range?.start.character || 0 : 0) + end.character,
},
},
}
const resultKey = [
result.classList,
result.range.start.line,
result.range.start.character,
result.range.end.line,
result.range.end.character,
].join(':')
// No need to add the result if it was already matched
if (!existingResultSet.has(resultKey)) {
existingResultSet.add(resultKey)
results.push(result)
}
})
})
return results
}
export async function findClassListsInRange(
state: State,
doc: TextDocument,
range?: Range,
mode?: 'html' | 'css' | 'jsx',
includeCustom: boolean = true,
lang?: string,
): Promise<DocumentClassList[]> {
let classLists: DocumentClassList[] = []
if (mode === 'css') {
classLists = findClassListsInCssRange(state, doc, range, lang)
} else if (mode === 'html' || mode === 'jsx') {
classLists = await findClassListsInHtmlRange(state, doc, mode, range)
}
return dedupeByRange([
...classLists,
...(includeCustom ? await findCustomClassLists(state, doc, range) : []),
])
}
export async function findClassListsInDocument(
state: State,
doc: TextDocument,
): Promise<DocumentClassList[]> {
if (isCssDoc(state, doc)) {
return findClassListsInCssRange(state, doc)
}
let boundaries = getLanguageBoundaries(state, doc)
if (!boundaries) return []
return dedupeByRange(
flatten([
...(await Promise.all(
boundaries
.filter((b) => b.type === 'html' || b.type === 'jsx')
.map(({ type, range }) =>
findClassListsInHtmlRange(state, doc, type === 'html' ? 'html' : 'jsx', range),
),
)),
...boundaries
.filter((b) => b.type === 'css')
.map(({ range, lang }) => findClassListsInCssRange(state, doc, range, lang)),
await findCustomClassLists(state, doc),
]),
)
}
export function findHelperFunctionsInDocument(
state: State,
doc: TextDocument,
): DocumentHelperFunction[] {
if (isCssDoc(state, doc)) {
return findHelperFunctionsInRange(doc)
}
let boundaries = getLanguageBoundaries(state, doc)
if (!boundaries) return []
return flatten(
boundaries
.filter((b) => b.type === 'css')
.map(({ range }) => findHelperFunctionsInRange(doc, range)),
)
}
function getFirstCommaIndex(str: string): number | null {
let quoteChar: string | undefined
for (let i = 0; i < str.length; i++) {
let char = str[i]
if (char === ',' && !quoteChar) {
return i
}
if (!quoteChar && (char === '"' || char === "'")) {
quoteChar = char
} else if (char === quoteChar) {
quoteChar = undefined
}
}
return null
}
export function findHelperFunctionsInRange(
doc: TextDocument,
range?: Range,
): DocumentHelperFunction[] {
const text = getTextWithoutComments(doc, 'css', range)
let matches = findAll(
/(?<prefix>[\W])(?<helper>config|theme|--theme|var)(?<innerPrefix>\(\s*)(?<path>[^)]*?)\s*\)/g,
text,
)
// Eliminate matches that are on an `@import`
matches = matches.filter((match) => {
// Scan backwards to see if we're in an `@import` statement
for (let i = match.index - 1; i >= 0; i--) {
let char = text[i]
if (char === '\n') break
if (char === ';') break
// Detecting theme(…) inside the media query list of `@import` is okay
if (char === '(') break
if (char === ')') break
if (text.startsWith('@import', i)) {
return false
}
}
return true
})
return matches.map((match) => {
let quotesBefore = ''
let path = match.groups.path
let commaIndex = getFirstCommaIndex(path)
if (commaIndex !== null) {
path = path.slice(0, commaIndex).trimEnd()
}
path = path.replace(/['"]+$/, '').replace(/^['"]+/, (m) => {
quotesBefore = m
return ''
})
let matches = path.match(/^([^\s]+)(?![^\[]*\])(?:\s*\/\s*([^\/\s]+))$/)
if (matches) {
path = matches[1]
}
path = path.replace(/['"]*\s*$/, '')
let startIndex =
match.index +
match.groups.prefix.length +
match.groups.helper.length +
match.groups.innerPrefix.length
let helper: 'config' | 'theme' | 'var' = 'config'
if (match.groups.helper === 'theme' || match.groups.helper === '--theme') {
helper = 'theme'
} else if (match.groups.helper === 'var') {
helper = 'var'
}
return {
helper,
path,
ranges: {
full: absoluteRange(
{
start: indexToPosition(text, startIndex),
end: indexToPosition(text, startIndex + match.groups.path.length),
},
range,
),
path: absoluteRange(
{
start: indexToPosition(text, startIndex + quotesBefore.length),
end: indexToPosition(text, startIndex + quotesBefore.length + path.length),
},
range,
),
},
}
})
}
export function indexToPosition(str: string, index: number): Position {
const { line, col } = lineColumn(str + '\n').fromIndex(index) ?? { line: 1, col: 1 }
return { line: line - 1, character: col - 1 }
}
export async function findClassNameAtPosition(
state: State,
doc: TextDocument,
position: Position,
): Promise<DocumentClassName> {
let classNames: DocumentClassName[] = []
const positionOffset = doc.offsetAt(position)
const searchRange: Range = {
start: doc.positionAt(0),
end: doc.positionAt(positionOffset + SEARCH_RANGE),
}
if (isVueDoc(doc)) {
let boundaries = getLanguageBoundaries(state, doc)
let groups = await Promise.all(
boundaries.map(async ({ type, range, lang }) => {
if (type === 'css') {
return await findClassListsInRange(state, doc, range, 'css', true, lang)
}
if (type === 'html') {
return await findClassListsInRange(state, doc, range, 'html')
}
if (type === 'js' || type === 'jsx') {
return await findClassListsInRange(state, doc, range, 'jsx')
}
return []
}),
)
classNames = dedupeByRange(flatten(groups)).flatMap((classList) =>
getClassNamesInClassList(classList, state.blocklist),
)
} else if (isCssContext(state, doc, position)) {
classNames = await findClassNamesInRange(state, doc, searchRange, 'css')
} else if (isHtmlContext(state, doc, position)) {
classNames = await findClassNamesInRange(state, doc, searchRange, 'html')
} else if (isJsxContext(state, doc, position)) {
classNames = await findClassNamesInRange(state, doc, searchRange, 'jsx')
} else {
classNames = await findClassNamesInRange(state, doc, searchRange)
}
if (classNames.length === 0) {
return null
}
const className = classNames.find(({ range }) => isWithinRange(position, range))
if (!className) return null
return className
}