-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclassNameCache.ts
More file actions
291 lines (264 loc) · 8.86 KB
/
classNameCache.ts
File metadata and controls
291 lines (264 loc) · 8.86 KB
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
import * as fs from "fs";
import * as vscode from "vscode";
import safeParser from "postcss-safe-parser";
import selectorParser from "postcss-selector-parser";
import { DEBOUNCE_TIMER, SUPPORTED_MODULES } from "../config";
import Cache from "./cache";
import {
getWorkspaceRelativeUriPath,
resolveWorkspaceRelativePath,
} from "../utils/getPath";
import { sanitizeCssInput } from "../utils/sanitizeCssInput";
import { isPositionInComment } from "../utils/isPositionInScope";
import CssModuleDependencyCache from "./cssModuleDependencyCache";
import CheckDocument from "./checkDocument";
import { type ClassNameRange, ClassNameRangeMap } from "../types/cache";
/**
* A utility class to extract and cache class names from CSS Module files.
*/
export default class ClassNameCache {
/**
* A map to track debounce timers for each CSS module path.
* Used to avoid frequent cache updates on rapid file edits.
*/
protected static ClassNameCacheDebounceIdMap: Record<string, NodeJS.Timeout> =
{};
/**
* Triggers a debounced update of class name cache for the given document.
* Also triggers a refresh on dependent documents.
*
* @param e The text document to update the class name cache for.
*/
static async updateClassNameCache(e: vscode.TextDocument) {
const importPath = getWorkspaceRelativeUriPath(e.uri);
clearTimeout(this.ClassNameCacheDebounceIdMap[importPath]);
this.ClassNameCacheDebounceIdMap[importPath] = setTimeout(() => {
(async () => {
await ClassNameCache.extractFromUri(e.uri);
if (SUPPORTED_MODULES.includes(e.languageId)) {
const dependents =
CssModuleDependencyCache.getDependentsForDocument(e);
for (const workspacePath of dependents) {
const resolvedPath = resolveWorkspaceRelativePath(workspacePath);
if (!resolvedPath) {
continue;
}
const document =
await vscode.workspace.openTextDocument(resolvedPath);
CheckDocument.push(document);
}
}
})()
.catch(console.error)
.finally(() => {
delete ClassNameCache.ClassNameCacheDebounceIdMap[importPath];
});
}, DEBOUNCE_TIMER.UPDATE_CLASS_NAME);
}
/**
* Checks if the given class name exists in the CSS module associated with a document or URI.
*
* @param className The class name to check.
* @param document Text document to resolve the URI.
* @param uri URI of the CSS module.
* @returns A promise resolving to true if the class exists, false if not, or undefined if no valid URI is provided.
*/
static async hasClassName({
className,
document,
uri,
}: {
className: string;
document?: vscode.TextDocument;
uri?: vscode.Uri;
}) {
if (!uri && document) {
uri = document.uri;
}
if (!uri) {
return;
}
const importPath = getWorkspaceRelativeUriPath(uri);
return await this.hasClassNameFromImportPath(className, importPath);
}
/**
* Checks if the given class name exists in the cached CSS module identified by import path.
*
* @param className The class name to check.
* @param importPath The workspace-relative path to the CSS module file.
* @returns A promise resolving to true if the class exists, or false if not.
*/
static async hasClassNameFromImportPath(
className: string,
importPath: string
): Promise<boolean | undefined> {
if (Cache.classNameCache.hasByKey(importPath)) {
return Cache.classNameCache.getByKey(importPath)?.has(className);
} else {
return (await this.extractAndCacheClassNames(importPath))?.has(className);
}
}
/**
* Retrieves metadata (such as range) for a class name from a document or URI.
*
* @param className The class name to retrieve data for.
* @param document Text document.
* @param uri URI to locate the module file.
* @returns An array of `ClassNameData` for the class, or undefined if not found.
*/
static async getClassNameData({
className,
document,
uri,
}: {
className: string;
document?: vscode.TextDocument;
uri?: vscode.Uri;
}) {
if (!uri && document) {
uri = document.uri;
}
if (!uri) {
return;
}
const importPath = getWorkspaceRelativeUriPath(uri);
return await this.getClassNameDataFromImportPath(className, importPath);
}
/**
* Retrieves metadata (such as range) for a class name from a specific import path.
*
* @param className The class name to retrieve data for.
* @param importPath The workspace-relative path to the CSS module file.
* @returns An array of `ClassNameData`, or undefined if not found or unsupported.
*/
static async getClassNameDataFromImportPath(
className: string,
importPath: string
): Promise<ClassNameRange[] | undefined> {
if (Cache.classNameCache.hasByKey(importPath)) {
return Cache.classNameCache.getByKey(importPath)?.get(className);
} else {
return (await this.extractAndCacheClassNames(importPath))?.get(className);
}
}
/**
* Retrieves all class names from a document or URI.
*
* @param document Text document.
* @param uri URI of the CSS module file.
* @returns An array of class names, or undefined if not supported.
*/
static async getClassNames({
document,
uri,
}: {
document?: vscode.TextDocument;
uri?: vscode.Uri;
}) {
if (!uri && document) {
uri = document.uri;
}
if (!uri) {
return;
}
const importPath = getWorkspaceRelativeUriPath(uri);
return await this.getClassNamesFromImportPath(importPath);
}
/**
* Retrieves all class names from a given import path.
*
* @param importPath The workspace-relative path to the CSS module.
* @returns An array of class names, or undefined if the file is not supported.
*/
static async getClassNamesFromImportPath(
importPath: string
): Promise<string[] | undefined> {
if (Cache.classNameCache.hasByKey(importPath)) {
return Array.from(
Cache.classNameCache.getByKey(importPath)?.keys() ?? []
);
} else {
return Array.from(
(await this.extractAndCacheClassNames(importPath))?.keys() ?? []
);
}
}
/**
* Extracts and caches class names from a URI.
*
* @param uri The URI of the CSS Module file.
*/
static async extractFromUri(uri: vscode.Uri): Promise<undefined> {
const importPath = getWorkspaceRelativeUriPath(uri);
await this.extractAndCacheClassNames(importPath);
}
/**
* Parses and extracts class names from a CSS/LESS/SCSS module file,
* then caches the result internally.
*
* @param importPath The workspace-relative import path of the module file.
* @returns A map of class names to metadata, or undefined if the file is invalid or not supported.
*/
static async extractAndCacheClassNames(
importPath: string
): Promise<ClassNameRangeMap | undefined> {
const filePath = resolveWorkspaceRelativePath(importPath);
if (!fs.existsSync(filePath)) {
Cache.classNameCache.deleteByKey(importPath); // Clean up stale entries
return;
}
const document = await vscode.workspace.openTextDocument(filePath);
if (!document || !SUPPORTED_MODULES.includes(document.languageId)) {
return;
}
const content = document.getText();
const sanitizedContent = sanitizeCssInput(content);
const root = safeParser(sanitizedContent);
const classNames = new ClassNameRangeMap();
const rules: Parameters<Parameters<(typeof root)["walkRules"]>[0]>[0][] =
[];
const handleRule = async (
rule: Parameters<Parameters<(typeof root)["walkRules"]>[0]>[0]
) => {
const selector = rule.selector;
const ruleStart = rule.source?.start;
if (!selector || !ruleStart) {
return;
}
if (
await isPositionInComment(
document,
new vscode.Position(ruleStart.line - 1, ruleStart.column - 1)
)
) {
return;
}
selectorParser((selectors) => {
selectors.walkClasses((classNode) => {
const { value, sourceIndex } = classNode;
// Compute position in the document
const selectorOffsetInDoc =
document.offsetAt(
new vscode.Position(ruleStart.line - 1, ruleStart.column - 1)
) + sourceIndex;
const data: ClassNameRange = {
range: new vscode.Range(
document.positionAt(selectorOffsetInDoc),
document.positionAt(selectorOffsetInDoc + value.length + 1) // +1 for "."
),
};
classNames.add(value, data);
});
}).processSync(selector);
};
root.walkRules((rule) => {
rules.push(rule);
});
for (const rule of rules) {
await handleRule(rule);
}
Cache.classNameCache.setByKey(importPath, classNames);
Cache.saveCache().catch(console.error);
return classNames;
}
}