|
| 1 | +/* @internal */ |
| 2 | +namespace ts.codefix { |
| 3 | + const fixId = "useDefaultImport"; |
| 4 | + const errorCodes = [Diagnostics.Import_may_be_converted_to_a_default_import.code]; |
| 5 | + registerCodeFix({ |
| 6 | + errorCodes, |
| 7 | + getCodeActions(context) { |
| 8 | + const { sourceFile, span: { start } } = context; |
| 9 | + const info = getInfo(sourceFile, start); |
| 10 | + if (!info) return undefined; |
| 11 | + const description = getLocaleSpecificMessage(Diagnostics.Convert_to_default_import); |
| 12 | + const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, info)); |
| 13 | + return [{ description, changes, fixId }]; |
| 14 | + }, |
| 15 | + fixIds: [fixId], |
| 16 | + getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => { |
| 17 | + const info = getInfo(diag.file!, diag.start!); |
| 18 | + if (info) doChange(changes, diag.file!, info); |
| 19 | + }), |
| 20 | + }); |
| 21 | + |
| 22 | + interface Info { |
| 23 | + readonly importNode: AnyImportSyntax; |
| 24 | + readonly name: Identifier; |
| 25 | + readonly moduleSpecifier: Expression; |
| 26 | + } |
| 27 | + function getInfo(sourceFile: SourceFile, pos: number): Info | undefined { |
| 28 | + const name = getTokenAtPosition(sourceFile, pos, /*includeJsDocComment*/ false); |
| 29 | + if (!isIdentifier(name)) return undefined; // bad input |
| 30 | + const { parent } = name; |
| 31 | + if (isImportEqualsDeclaration(parent) && isExternalModuleReference(parent.moduleReference)) { |
| 32 | + return { importNode: parent, name, moduleSpecifier: parent.moduleReference.expression }; |
| 33 | + } |
| 34 | + else if (isNamespaceImport(parent)) { |
| 35 | + const importNode = parent.parent.parent; |
| 36 | + return { importNode, name, moduleSpecifier: importNode.moduleSpecifier }; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, info: Info): void { |
| 41 | + changes.replaceNode(sourceFile, info.importNode, makeImportDeclaration(info.name, /*namedImports*/ undefined, info.moduleSpecifier)); |
| 42 | + } |
| 43 | +} |
0 commit comments