|
| 1 | +import { getChangesTracker, getIndentFromPos } from '../../utils' |
| 2 | +import { CodeAction } from '../getCodeActions' |
| 3 | + |
| 4 | +export default { |
| 5 | + name: 'Split Declaration and Initialization', |
| 6 | + id: 'splitDeclarationAndInitialization', |
| 7 | + kind: 'refactor.rewrite.split-declaration-and-initialization', |
| 8 | + tryToApply(sourceFile, position, range, node, formatOptions, languageService, languageServiceHost) { |
| 9 | + if (range || !node) return |
| 10 | + if (!ts.isVariableDeclarationList(node) || node.declarations.length !== 1) return |
| 11 | + const declaration = node.declarations[0]! |
| 12 | + if (position > declaration.pos || !declaration.initializer || !ts.isIdentifier(declaration.name)) return |
| 13 | + if (!formatOptions) return true |
| 14 | + const typeChecker = languageService.getProgram()!.getTypeChecker()! |
| 15 | + let typeNode = declaration.type |
| 16 | + if (!typeNode) { |
| 17 | + let type = typeChecker.getTypeAtLocation(declaration) |
| 18 | + if (type.isLiteral()) { |
| 19 | + type = typeChecker.getBaseTypeOfLiteralType(type) |
| 20 | + } |
| 21 | + typeNode = typeChecker.typeToTypeNode(type, node.parent, ts.NodeBuilderFlags.NoTruncation) |
| 22 | + } |
| 23 | + const changesTracker = getChangesTracker(formatOptions) |
| 24 | + const { factory } = ts |
| 25 | + const nodeStart = node.pos + node.getLeadingTriviaWidth() |
| 26 | + const varName = declaration.name.text |
| 27 | + changesTracker.insertNodeAt( |
| 28 | + sourceFile, |
| 29 | + nodeStart, |
| 30 | + factory.createVariableDeclarationList( |
| 31 | + [factory.createVariableDeclaration(factory.createIdentifier(varName), undefined, typeNode)], |
| 32 | + ts.NodeFlags.Let, |
| 33 | + ), |
| 34 | + ) |
| 35 | + changesTracker.replaceNode( |
| 36 | + sourceFile, |
| 37 | + node, |
| 38 | + factory.createBinaryExpression(factory.createIdentifier(varName), factory.createToken(ts.SyntaxKind.EqualsToken), declaration.initializer), |
| 39 | + { |
| 40 | + prefix: `\n${getIndentFromPos(ts, sourceFile, position)}`, |
| 41 | + suffix: '\n', |
| 42 | + leadingTriviaOption: /*Ignore all*/ 0, |
| 43 | + }, |
| 44 | + ) |
| 45 | + return changesTracker.getChanges()[0]?.textChanges as ts.TextChange[] |
| 46 | + }, |
| 47 | +} satisfies CodeAction |
0 commit comments