diff --git a/src/comments.js b/src/comments.js index d2b25707..d0c0d0cd 100644 --- a/src/comments.js +++ b/src/comments.js @@ -279,6 +279,7 @@ function attach(comments, ast, text) { ) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment) || + handleMethodNameComments(enclosingNode, precedingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) ) { // We're good @@ -548,6 +549,24 @@ function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) { return false; } +function handleMethodNameComments(enclosingNode, precedingNode, comment) { + // This is only needed for estree parsers (flow, typescript) to attach + // after a method name: + // obj = { fn /*comment*/() {} }; + if ( + enclosingNode && + precedingNode && + (enclosingNode.type === "Property" || + enclosingNode.type === "MethodDefinition") && + precedingNode.type === "Identifier" && + enclosingNode.key === precedingNode + ) { + addTrailingComment(precedingNode, comment); + return true; + } + return false; +} + function handleCommentInEmptyParens(text, enclosingNode, comment) { if (getNextNonSpaceNonCommentCharacter(text, comment) !== ")") { return false; diff --git a/tests/classes/__snapshots__/jsfmt.spec.js.snap b/tests/classes/__snapshots__/jsfmt.spec.js.snap index 3ae8f8b2..6c76fff6 100644 --- a/tests/classes/__snapshots__/jsfmt.spec.js.snap +++ b/tests/classes/__snapshots__/jsfmt.spec.js.snap @@ -138,6 +138,29 @@ exports[`member.js 1`] = ` `; +exports[`method.js 1`] = ` + +class C { + name/*comment*/() { + } +}; + + +({ + name/*comment*/() { + } +}); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +class C { + name /*comment*/() {} +} + +({ + name /*comment*/() {} +}); + +`; + exports[`ternary.js 1`] = ` if (1) (class {}) ? 1 : 2; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/tests/classes/jsfmt.spec.js b/tests/classes/jsfmt.spec.js index 7580dfab..c426c19c 100644 --- a/tests/classes/jsfmt.spec.js +++ b/tests/classes/jsfmt.spec.js @@ -1 +1 @@ -run_spec(__dirname, null, ["typescript"]); +run_spec(__dirname, null, ["babylon", "typescript"]); diff --git a/tests/classes/method.js b/tests/classes/method.js new file mode 100644 index 00000000..49d7c46d --- /dev/null +++ b/tests/classes/method.js @@ -0,0 +1,11 @@ + +class C { + name/*comment*/() { + } +}; + + +({ + name/*comment*/() { + } +});