json: support "Sort properties alphabetically" intention when caret is after last symbol

GitOrigin-RevId: d51665f0e1a1cc8f20af8df39525afd48c438869
This commit is contained in:
Sergey Simonchik
2023-06-30 18:59:55 +02:00
committed by intellij-monorepo-bot
parent f3b660c2d8
commit ddc91500ef
4 changed files with 27 additions and 8 deletions

View File

@@ -1,10 +1,11 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.json.intentions
import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.json.JsonBundle
import com.intellij.json.psi.JsonFile
import com.intellij.json.psi.JsonObject
import com.intellij.json.psi.JsonProperty
import com.intellij.json.psi.impl.JsonRecursiveElementVisitor
@@ -19,7 +20,7 @@ import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.util.IncorrectOperationException
import org.jetbrains.annotations.Nls
open class JsonSortPropertiesIntention : PsiElementBaseIntentionAction(), LowPriorityAction, LightEditCompatible, DumbAware {
open class JsonSortPropertiesIntention : BaseElementAtCaretIntentionAction(), LowPriorityAction, LightEditCompatible, DumbAware {
override fun getText(): @Nls(capitalization = Nls.Capitalization.Sentence) String = JsonBundle.message("json.intention.sort.properties")
override fun getFamilyName(): @Nls(capitalization = Nls.Capitalization.Sentence) String =
@@ -81,7 +82,10 @@ open class JsonSortPropertiesIntention : PsiElementBaseIntentionAction(), LowPri
}
private fun findRootObject(): JsonObject? {
val initObj = PsiTreeUtil.getParentOfType(contextElement, JsonObject::class.java)
val initObj: JsonObject? = PsiTreeUtil.getParentOfType(contextElement, JsonObject::class.java) ?: run {
val jsonFile = contextElement.containingFile as? JsonFile ?: return@run null
return jsonFile.allTopLevelValues.filterIsInstance<JsonObject>().firstOrNull()
}
if (initObj == null || !selectionModel.hasSelection()) {
return initObj
}
@@ -101,9 +105,7 @@ open class JsonSortPropertiesIntention : PsiElementBaseIntentionAction(), LowPri
}
}
}
}
companion object {
private fun isSorted(obj: JsonObject): Boolean {
return obj.propertyList.asSequence()
.map { it.name }

View File

@@ -25,4 +25,8 @@ class JsonSortPropertiesIntentionTest : JsonTestCase() {
fun testSortRecursively() {
doTest()
}
fun testSortWhenCaretAfterLastSymbol() {
doTest()
}
}

View File

@@ -0,0 +1,7 @@
{
"version": "1.0.0",
"main": "index.js",
"name": "my-app",
"license": "MIT"
}
<caret>

View File

@@ -0,0 +1,6 @@
{
"license": "MIT",
"main": "index.js",
"name": "my-app",
"version": "1.0.0"
}