• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace 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 changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, info, context.preferences));
12            return [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_default_import, fixId, Diagnostics.Convert_all_to_default_imports)];
13        },
14        fixIds: [fixId],
15        getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, diag) => {
16            const info = getInfo(diag.file, diag.start);
17            if (info) doChange(changes, diag.file, info, context.preferences);
18        }),
19    });
20
21    interface Info {
22        readonly importNode: AnyImportSyntax;
23        readonly name: Identifier;
24        readonly moduleSpecifier: Expression;
25    }
26    function getInfo(sourceFile: SourceFile, pos: number): Info | undefined {
27        const name = getTokenAtPosition(sourceFile, pos);
28        if (!isIdentifier(name)) return undefined; // bad input
29        const { parent } = name;
30        if (isImportEqualsDeclaration(parent) && isExternalModuleReference(parent.moduleReference)) {
31            return { importNode: parent, name, moduleSpecifier: parent.moduleReference.expression };
32        }
33        else if (isNamespaceImport(parent)) {
34            const importNode = parent.parent.parent;
35            return { importNode, name, moduleSpecifier: importNode.moduleSpecifier };
36        }
37    }
38
39    function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, info: Info, preferences: UserPreferences): void {
40        changes.replaceNode(sourceFile, info.importNode, makeImport(info.name, /*namedImports*/ undefined, info.moduleSpecifier, getQuotePreference(sourceFile, preferences)));
41    }
42}
43