Skip to content

Commit

Permalink
feat(typescript): refactor JSDoc comment insertion logic to handle nu…
Browse files Browse the repository at this point in the history
…ll values and exceptions more gracefully #2
  • Loading branch information
phodal committed Apr 10, 2024
1 parent 30f301e commit 5231b70
Showing 1 changed file with 21 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,18 +52,16 @@ class JavaScriptLivingDocumentation : LivingDocumentation {
?: findDocFallback(target)

try {
val createJSDocComment: PsiElement = JSPsiElementFactory.createJSDocComment(newDoc, target)

if (existingComment != null) {
existingComment.replace(createJSDocComment)
} else {
val parent = target.parent
parent.addBefore(createJSDocComment, target)
JSChangeUtil.addWs(parent.node, target.node, "\n")
}
didInsertComment(newDoc, target, existingComment)
} catch (e: Exception) {
editor.document.insertString(startOffset, newDoc)
codeStyleManager.reformatText(target.containingFile, startOffset, newEndOffset)
// second attempt
val fromSuggestion = LivingDocumentation.buildDocFromSuggestion(newDoc, "/**", "*/")
try {
didInsertComment(fromSuggestion, target, existingComment)
} catch (e: Exception) {
editor.document.insertString(startOffset, newDoc)
codeStyleManager.reformatText(target.containingFile, startOffset, newEndOffset)
}
}
}

Expand All @@ -80,6 +78,18 @@ class JavaScriptLivingDocumentation : LivingDocumentation {
})
}

private fun didInsertComment(newDoc: String, target: PsiElement, existingComment: JSDocComment?) {
val createJSDocComment: PsiElement = JSPsiElementFactory.createJSDocComment(newDoc, target)

if (existingComment != null) {
existingComment.replace(createJSDocComment)
} else {
val parent = target.parent
parent.addBefore(createJSDocComment, target)
JSChangeUtil.addWs(parent.node, target.node, "\n")
}
}

private fun findDocFallback(documentationTarget: PsiElement): JSDocComment? {
val parentOfDestructuring: PsiElement? by lazy {
var context = documentationTarget.context
Expand Down

0 comments on commit 5231b70

Please sign in to comment.