• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* @internal */
2namespace ts.codefix {
3    const errorCodes = [Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both.code];
4    const fixId = "splitTypeOnlyImport";
5    registerCodeFix({
6        errorCodes,
7        fixIds: [fixId],
8        getCodeActions: context => {
9            const changes = textChanges.ChangeTracker.with(context, t => {
10                return splitTypeOnlyImport(t, getImportDeclaration(context.sourceFile, context.span), context);
11            });
12            if (changes.length) {
13                return [createCodeFixAction(fixId, changes, Diagnostics.Split_into_two_separate_import_declarations, fixId, Diagnostics.Split_all_invalid_type_only_imports)];
14            }
15        },
16        getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, error) => {
17            splitTypeOnlyImport(changes, getImportDeclaration(context.sourceFile, error), context);
18        }),
19    });
20
21    function getImportDeclaration(sourceFile: SourceFile, span: TextSpan) {
22        return findAncestor(getTokenAtPosition(sourceFile, span.start), isImportDeclaration);
23    }
24
25    function splitTypeOnlyImport(changes: textChanges.ChangeTracker, importDeclaration: ImportDeclaration | undefined, context: CodeFixContextBase) {
26        if (!importDeclaration) {
27            return;
28        }
29        const importClause = Debug.checkDefined(importDeclaration.importClause);
30        changes.replaceNode(context.sourceFile, importDeclaration, factory.updateImportDeclaration(
31            importDeclaration,
32            importDeclaration.decorators,
33            importDeclaration.modifiers,
34            factory.updateImportClause(importClause, importClause.isTypeOnly, importClause.name, /*namedBindings*/ undefined),
35            importDeclaration.moduleSpecifier));
36
37        changes.insertNodeAfter(context.sourceFile, importDeclaration, factory.createImportDeclaration(
38            /*decorators*/ undefined,
39            /*modifiers*/ undefined,
40            factory.updateImportClause(importClause, importClause.isTypeOnly, /*name*/ undefined, importClause.namedBindings),
41            importDeclaration.moduleSpecifier));
42    }
43}
44