From 1a7d4b34ba0959629ffa44a5198b424074fb37b6 Mon Sep 17 00:00:00 2001 From: Vyacheslav Pukhanov Date: Sun, 27 May 2018 23:36:25 +0300 Subject: [PATCH] addMethodDeclaration: add after quickfix location if possible (#22674) --- src/services/codefixes/fixAddMissingMember.ts | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index 2eafb5cdd6f..ccf5829f363 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -199,6 +199,34 @@ namespace ts.codefix { preferences: UserPreferences, ): void { const methodDeclaration = createMethodFromCallExpression(callExpression, token.text, inJs, makeStatic, preferences); - changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + const currentMethod = getNodeToInsertMethodAfter(classDeclaration, callExpression); + + if (currentMethod) { + changeTracker.insertNodeAfter(classDeclarationSourceFile, currentMethod, methodDeclaration); + } + else { + changeTracker.insertNodeAtClassStart(classDeclarationSourceFile, classDeclaration, methodDeclaration); + } + } + + // Gets the MethodDeclaration of a method of the cls class that contains the node, or undefined if the node is not in a method or that method is not in the cls class. + function getNodeToInsertMethodAfter(cls: ClassLikeDeclaration, node: Node): MethodDeclaration | undefined { + const nodeMethod = getParentMethodDeclaration(node); + if (nodeMethod) { + const isClsMethod = contains(cls.members, nodeMethod); + if (isClsMethod) { + return nodeMethod; + } + } + return undefined; + } + + // Gets the MethodDeclaration of the method that contains the node, or undefined if the node is not in a method. + function getParentMethodDeclaration(node: Node): MethodDeclaration | undefined { + while (node) { + if (isMethodDeclaration(node)) break; + node = node.parent; + } + return node; } }