-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcode-fix.ts
More file actions
151 lines (136 loc) · 5.99 KB
/
code-fix.ts
File metadata and controls
151 lines (136 loc) · 5.99 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
import type { CMKConfig, Resolver } from '@css-modules-kit/core';
import { isCSSModuleFile } from '@css-modules-kit/core';
import type { Language } from '@volar/language-core';
import ts from 'typescript';
import { convertDefaultImportsToNamespaceImports, createPreferencesForCompletion } from '../../util.js';
// ref: https://github.com/microsoft/TypeScript/blob/220706eb0320ff46fad8bf80a5e99db624ee7dfb/src/compiler/diagnosticMessages.json
export const CANNOT_FIND_NAME_ERROR_CODE = 2304;
export const PROPERTY_DOES_NOT_EXIST_ERROR_CODES: [number, number] = [2339, 2551];
export function getCodeFixesAtPosition(
language: Language<string>,
languageService: ts.LanguageService,
project: ts.server.Project,
resolver: Resolver,
config: CMKConfig,
): ts.LanguageService['getCodeFixesAtPosition'] {
return (...args) => {
const [fileName, start, end, errorCodes, formatOptions, preferences, ...rest] = args;
const prior = Array.from(
languageService.getCodeFixesAtPosition(
fileName,
start,
end,
errorCodes,
formatOptions,
createPreferencesForCompletion(preferences, config),
...rest,
),
);
if (config.namedExports && !config.prioritizeNamedImports) {
convertDefaultImportsToNamespaceImports(prior, fileName, resolver);
excludeNamedImports(prior, fileName, resolver);
}
// If a user is trying to use a non-existent token (e.g. `styles.nonExistToken`), provide a code fix to add the token.
if (errorCodes.some((errorCode) => PROPERTY_DOES_NOT_EXIST_ERROR_CODES.includes(errorCode))) {
const tokenConsumer = getTokenConsumerAtPosition(fileName, start, languageService, project, config);
if (tokenConsumer) {
prior.push({
fixName: 'fixMissingCSSRule',
description: `Add missing CSS rule '.${tokenConsumer.tokenName}'`,
changes: [createInsertRuleFileChange(tokenConsumer.from, tokenConsumer.tokenName, language)],
});
}
}
return prior.filter((codeFix) => codeFix.changes.length > 0);
};
}
/**
* Exclude code fixes that add named imports (e.g. `import { foo } from './a.module.css'`)
*/
function excludeNamedImports(codeFixes: ts.CodeFixAction[], fileName: string, resolver: Resolver): void {
for (const codeFix of codeFixes) {
if (codeFix.fixName !== 'import') continue;
const match = codeFix.description.match(/^Add import from "(.*)"$/u);
if (!match) continue;
const specifier = match[1]!;
const resolved = resolver(specifier, { request: fileName });
if (!resolved || !isCSSModuleFile(resolved)) continue;
for (const change of codeFix.changes) {
change.textChanges = change.textChanges.filter((textChange) => !textChange.newText.startsWith(`import {`));
}
codeFix.changes = codeFix.changes.filter((change) => change.textChanges.length > 0);
}
}
interface TokenConsumer {
/** The token name (e.g. `foo` in `styles.foo`) */
tokenName: string;
/** The file path of the CSS module that defines the token */
from: string;
}
/**
* Get the token consumer at the specified position.
* If the position is at `styles.foo`, it returns `{ tokenName: 'foo', from: '/path/to/a.module.css' }`.
*/
function getTokenConsumerAtPosition(
fileName: string,
position: number,
languageService: ts.LanguageService,
project: ts.server.Project,
config: CMKConfig,
): TokenConsumer | undefined {
const sourceFile = project.getSourceFile(project.projectService.toPath(fileName));
if (!sourceFile) return undefined;
const propertyAccessExpression = getPropertyAccessExpressionAtPosition(sourceFile, position);
if (!propertyAccessExpression) return undefined;
// Check if the expression of property access expression (e.g. `styles` in `styles.foo`) is imported from a CSS module.
// `expression` is the expression of the property access expression (e.g. `styles` in `styles.foo`).
const expression = propertyAccessExpression.expression;
let [definition] = languageService.getDefinitionAtPosition(fileName, expression.getStart()) ?? [];
if (!definition) return undefined;
// `definition` is may be `styles` definition in CSS Modules file.
if (isCSSModuleFile(definition.fileName)) {
return { tokenName: propertyAccessExpression.name.text, from: definition.fileName };
} else if (config.namedExports) {
// If namespaced import is used, it may be a definition in a component file
// (e.g. the `styles` of `import * as styles from './a.module.css'`).
// In that case, we need to call `getDefinitionAtPosition` again to get the definition in CSS module file.
[definition] = languageService.getDefinitionAtPosition(definition.fileName, definition.textSpan.start) ?? [];
if (definition && isCSSModuleFile(definition.fileName)) {
return { tokenName: propertyAccessExpression.name.text, from: definition.fileName };
}
}
return undefined;
}
/** Get the property access expression at the specified position. (e.g. `obj.foo`, `styles.foo`) */
function getPropertyAccessExpressionAtPosition(
sourceFile: ts.SourceFile,
position: number,
): ts.PropertyAccessExpression | undefined {
function getPropertyAccessExpressionImpl(node: ts.Node): ts.PropertyAccessExpression | undefined {
if (node.pos <= position && position <= node.end && ts.isPropertyAccessExpression(node)) {
return node;
}
return ts.forEachChild(node, getPropertyAccessExpressionImpl);
}
return getPropertyAccessExpressionImpl(sourceFile);
}
function createInsertRuleFileChange(
cssModuleFileName: string,
className: string,
language: Language<string>,
): ts.FileTextChanges {
const script = language.scripts.get(cssModuleFileName);
if (script) {
return {
fileName: cssModuleFileName,
textChanges: [{ span: { start: script.snapshot.getLength(), length: 0 }, newText: `\n.${className} {\n \n}` }],
isNewFile: false,
};
} else {
return {
fileName: cssModuleFileName,
textChanges: [{ span: { start: 0, length: 0 }, newText: `.${className} {\n \n}\n\n` }],
isNewFile: true,
};
}
}