|
| 1 | +import { isNumber } from 'lodash' |
| 2 | +import { |
| 3 | + findChildContainingExactPosition, |
| 4 | + getChangesTracker, |
| 5 | + getPositionHighlights, |
| 6 | + isValidInitializerForDestructure, |
| 7 | + isNameUniqueAtNodeClosestScope, |
| 8 | +} from '../../utils' |
| 9 | +import { CodeAction } from '../getCodeActions' |
| 10 | + |
| 11 | +export const getPropertyIdentifier = (bindingElement: ts.BindingElement): ts.Identifier | undefined => { |
| 12 | + const name = bindingElement.propertyName ?? bindingElement.name |
| 13 | + return ts.isIdentifier(name) ? name : undefined |
| 14 | +} |
| 15 | +const createFlattenedExpressionFromDestructuring = (bindingElement: ts.BindingElement, baseExpression: ts.Expression) => { |
| 16 | + // number: array index; identifier: property name |
| 17 | + const propertyAccessors: Array<ts.Identifier | number> = [] |
| 18 | + let current: ts.Node = bindingElement |
| 19 | + while (ts.isBindingElement(current)) { |
| 20 | + propertyAccessors.push(ts.isObjectBindingPattern(current.parent) ? getPropertyIdentifier(current)! : current.parent.elements.indexOf(current)) |
| 21 | + current = current.parent.parent |
| 22 | + } |
| 23 | + |
| 24 | + let flattenedExpression = baseExpression |
| 25 | + for (const [i, _] of propertyAccessors.reverse().entries()) { |
| 26 | + const accessor = propertyAccessors[i] |
| 27 | + |
| 28 | + flattenedExpression = isNumber(accessor) |
| 29 | + ? ts.factory.createElementAccessExpression(flattenedExpression, ts.factory.createNumericLiteral(accessor)) |
| 30 | + : ts.factory.createPropertyAccessExpression(flattenedExpression, accessor!.text) |
| 31 | + } |
| 32 | + return flattenedExpression |
| 33 | +} |
| 34 | + |
| 35 | +const collectBindings = (node: ts.BindingPattern): ts.BindingElement[] => { |
| 36 | + const bindings: ts.BindingElement[] = [] |
| 37 | + |
| 38 | + const doCollectBindings = (node: ts.BindingPattern) => { |
| 39 | + for (const element of node.elements) { |
| 40 | + if (ts.isOmittedExpression(element)) { |
| 41 | + continue |
| 42 | + } |
| 43 | + |
| 44 | + const elementName = element.name |
| 45 | + |
| 46 | + if (ts.isIdentifier(elementName)) { |
| 47 | + bindings.push(element) |
| 48 | + } else if (ts.isArrayBindingPattern(elementName) || ts.isObjectBindingPattern(elementName)) { |
| 49 | + doCollectBindings(elementName) |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + doCollectBindings(node) |
| 55 | + |
| 56 | + return bindings |
| 57 | +} |
| 58 | + |
| 59 | +const convertFromDestructureWithVariableNameReplacement = ( |
| 60 | + declarationName: ts.BindingPattern, |
| 61 | + sourceFile: ts.SourceFile, |
| 62 | + languageService: ts.LanguageService, |
| 63 | +) => { |
| 64 | + const bindings = collectBindings(declarationName) |
| 65 | + const tracker = getChangesTracker({}) |
| 66 | + |
| 67 | + const BASE_VARIABLE_NAME = 'newVariable' |
| 68 | + |
| 69 | + const variableName = isNameUniqueAtNodeClosestScope(BASE_VARIABLE_NAME, declarationName, languageService.getProgram()!.getTypeChecker()) |
| 70 | + ? BASE_VARIABLE_NAME |
| 71 | + : tsFull.getUniqueName(BASE_VARIABLE_NAME, sourceFile as unknown as FullSourceFile) |
| 72 | + |
| 73 | + for (const binding of bindings) { |
| 74 | + const declaration = createFlattenedExpressionFromDestructuring(binding, ts.factory.createIdentifier(variableName)) |
| 75 | + |
| 76 | + /** Important to use `getEnd()` here to get correct highlights for destructured and renamed binding, e.g. `{ bar: bar_1 }` */ |
| 77 | + const bindingNameEndPos = binding.getEnd() |
| 78 | + const highlightPositions = getPositionHighlights(bindingNameEndPos, sourceFile, languageService) |
| 79 | + |
| 80 | + if (!highlightPositions) return |
| 81 | + |
| 82 | + for (const pos of highlightPositions) { |
| 83 | + if (pos >= declarationName.getStart() && pos <= declarationName.getEnd()) { |
| 84 | + continue |
| 85 | + } |
| 86 | + const node = findChildContainingExactPosition(sourceFile, pos) |
| 87 | + |
| 88 | + if (!node) continue |
| 89 | + const printer = ts.createPrinter() |
| 90 | + |
| 91 | + tracker.replaceRangeWithText(sourceFile, { pos, end: node.end }, printer.printNode(ts.EmitHint.Unspecified, declaration, sourceFile)) |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + const declarationNameLeadingTrivia = declarationName.getLeadingTriviaWidth(sourceFile) |
| 96 | + |
| 97 | + tracker.replaceRange( |
| 98 | + sourceFile, |
| 99 | + { pos: declarationName.pos + declarationNameLeadingTrivia, end: declarationName.end }, |
| 100 | + ts.factory.createIdentifier(variableName), |
| 101 | + ) |
| 102 | + const changes = tracker.getChanges() |
| 103 | + return { |
| 104 | + edits: [ |
| 105 | + { |
| 106 | + fileName: sourceFile.fileName, |
| 107 | + textChanges: changes[0]!.textChanges, |
| 108 | + }, |
| 109 | + ], |
| 110 | + } |
| 111 | +} |
| 112 | +export default { |
| 113 | + id: 'fromDestruct', |
| 114 | + name: 'From Destruct', |
| 115 | + kind: 'refactor.rewrite.from-destruct', |
| 116 | + tryToApply(sourceFile, position, _range, node, formatOptions, languageService) { |
| 117 | + if (!node || !position) return |
| 118 | + const declaration = ts.findAncestor(node, n => ts.isVariableDeclaration(n) || ts.isParameter(n)) as |
| 119 | + | ts.VariableDeclaration |
| 120 | + | ts.ParameterDeclaration |
| 121 | + | undefined |
| 122 | + |
| 123 | + if (!declaration || !(ts.isObjectBindingPattern(declaration.name) || ts.isArrayBindingPattern(declaration.name))) return |
| 124 | + |
| 125 | + if (ts.isParameter(declaration)) { |
| 126 | + return convertFromDestructureWithVariableNameReplacement(declaration.name, sourceFile, languageService) |
| 127 | + } |
| 128 | + |
| 129 | + if (!ts.isVariableDeclarationList(declaration.parent)) return |
| 130 | + |
| 131 | + const { initializer } = declaration |
| 132 | + if (!initializer || !isValidInitializerForDestructure(initializer)) return |
| 133 | + |
| 134 | + const bindings = collectBindings(declaration.name) |
| 135 | + if (bindings.length > 1) { |
| 136 | + return convertFromDestructureWithVariableNameReplacement(declaration.name, sourceFile, languageService) |
| 137 | + } |
| 138 | + |
| 139 | + const { factory } = ts |
| 140 | + |
| 141 | + const declarations = bindings.map(bindingElement => |
| 142 | + factory.createVariableDeclaration( |
| 143 | + bindingElement.name, |
| 144 | + undefined, |
| 145 | + undefined, |
| 146 | + createFlattenedExpressionFromDestructuring(bindingElement, initializer), |
| 147 | + ), |
| 148 | + ) |
| 149 | + |
| 150 | + const variableDeclarationList = declaration.parent |
| 151 | + |
| 152 | + const updatedVariableDeclarationList = factory.createVariableDeclarationList(declarations, variableDeclarationList.flags) |
| 153 | + |
| 154 | + const tracker = getChangesTracker(formatOptions ?? {}) |
| 155 | + |
| 156 | + const leadingTrivia = variableDeclarationList.getLeadingTriviaWidth(sourceFile) |
| 157 | + |
| 158 | + tracker.replaceRange(sourceFile, { pos: variableDeclarationList.pos + leadingTrivia, end: variableDeclarationList.end }, updatedVariableDeclarationList) |
| 159 | + |
| 160 | + const changes = tracker.getChanges() |
| 161 | + |
| 162 | + if (!changes) return undefined |
| 163 | + return { |
| 164 | + edits: [ |
| 165 | + { |
| 166 | + fileName: sourceFile.fileName, |
| 167 | + textChanges: changes[0]!.textChanges, |
| 168 | + }, |
| 169 | + ], |
| 170 | + } |
| 171 | + }, |
| 172 | +} satisfies CodeAction |
0 commit comments