Skip to content

Commit 3061c67

Browse files
crisbetothePunderWoman
authored andcommitted
refactor(language-service): update code fix for unused imports (#58468)
Since the unused imports diagnostic setup has changed, we need to update the code fix to account for it. PR Close #58468
1 parent c0738c9 commit 3061c67

1 file changed

Lines changed: 24 additions & 8 deletions

File tree

packages/language-service/src/codefixes/fix_unused_standalone_imports.ts

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,20 @@ export const fixUnusedStandaloneImportsMeta: CodeActionMeta = {
2929
}
3030

3131
const node = findFirstMatchingNode(file, {
32-
filter: (current): current is tss.ArrayLiteralExpression =>
33-
current.getStart() === start &&
34-
current.getWidth() === length &&
35-
tss.isArrayLiteralExpression(current),
32+
filter: (
33+
current,
34+
): current is tss.PropertyAssignment & {initializer: tss.ArrayLiteralExpression} =>
35+
tss.isPropertyAssignment(current) &&
36+
tss.isArrayLiteralExpression(current.initializer) &&
37+
current.name.getStart() === start &&
38+
current.name.getWidth() === length,
3639
});
3740

3841
if (node === null) {
3942
continue;
4043
}
4144

45+
const importsArray = node.initializer;
4246
let newText: string;
4347

4448
// If `relatedInformation` is empty, it means that all the imports are unused.
@@ -50,11 +54,23 @@ export const fixUnusedStandaloneImportsMeta: CodeActionMeta = {
5054
// filtered out. We make a set of ranges corresponding to nodes which will be deleted and
5155
// remove all nodes that belong to the set.
5256
const excludeRanges = new Set(
53-
relatedInformation.map((info) => `${info.start}-${info.length}`),
57+
relatedInformation.reduce((ranges, info) => {
58+
// If the compiler can't resolve the unused import to an identifier within the array,
59+
// it falls back to reporting the identifier of the class declaration instead. In theory
60+
// that class could have the same offsets as the diagnostic location. It's a slim chance
61+
// that would happen, but we filter out reports from other files just in case.
62+
if (info.file === file) {
63+
ranges.push(`${info.start}-${info.length}`);
64+
}
65+
return ranges;
66+
}, [] as string[]),
5467
);
68+
5569
const newArray = tss.factory.updateArrayLiteralExpression(
56-
node,
57-
node.elements.filter((el) => !excludeRanges.has(`${el.getStart()}-${el.getWidth()}`)),
70+
importsArray,
71+
importsArray.elements.filter(
72+
(el) => !excludeRanges.has(`${el.getStart()}-${el.getWidth()}`),
73+
),
5874
);
5975

6076
newText = tss.createPrinter().printNode(tss.EmitHint.Unspecified, newArray, file);
@@ -64,7 +80,7 @@ export const fixUnusedStandaloneImportsMeta: CodeActionMeta = {
6480
fileName: file.fileName,
6581
textChanges: [
6682
{
67-
span: {start, length},
83+
span: {start: importsArray.getStart(), length: importsArray.getWidth()},
6884
newText,
6985
},
7086
],

0 commit comments

Comments
 (0)