Repository: ota-meshi/eslint-plugin-astro (ts)

Issue:
Sort Attributes rule
### Motivation

Hello!

ESLint Plugin Perfectionist plans to deprecate from rules that use third-party parsers (https://github.com/azat-io/eslint-plugin-perfectionist/issues/175).

We'd like to move a rule to you for sorting Astro element attributes.

### Description

This rule is needed to sort attributes and create a consistent codebase style.

The rule should be able to sort attributes alphabetically and by line length. Sorting by descending and ascending should also be supported.

The rule should take into account spreads within Astro elements.

### Examples

```astro
---
---

{/* ✓ GOOD */}
<Foo a="aaa" b="bb" c="c" />

{/* ✗ BAD */}
<Foo b="bb" c="c" a="aaa" />
```


### Additional comments

_No response_

Pull request:
feat: add sort-attributes rule
Close #417.

The source code for the rule was partially ported from the ESLint Plugin Perfectionist. This is done as part of this task:
https://github.com/azat-io/eslint-plugin-perfectionist/issues/175

Patch:
diff --git a/.changeset/honest-jobs-grow.md b/.changeset/honest-jobs-grow.md
new file mode 100644
index 0000000..7a60b4d
--- /dev/null
+++ b/.changeset/honest-jobs-grow.md
@@ -0,0 +1,5 @@
+---
+"eslint-plugin-astro": minor
+---
+
+feat: add sort-attributes rule
diff --git a/docs/rules/sort-attributes.md b/docs/rules/sort-attributes.md
new file mode 100644
index 0000000..e35ea14
--- /dev/null
+++ b/docs/rules/sort-attributes.md
@@ -0,0 +1,59 @@
+---
+title: "astro/sort-attributes"
+description: "Enforce sorted Astro attributes"
+since: "v1.3.0"
+---
+
+# astro/sort-attributes
+
+> Enforce sorted Astro attributes
+
+- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule.
+
+## :book: Rule Details
+
+Maintaining a consistent order of attributes in Astro elements is crucial for readability and maintainability. This rule ensures that attributes are sorted, making the structure of your elements more predictable and easier to manage.
+
+Adopting this rule helps standardize code formatting across your project, facilitating better collaboration and reducing cognitive load for developers.
+
+It’s safe. The rule considers spread elements in an attributes list and does not break component functionality.
+
+Default:
+
+<ESLintCodeBlock fix>
+
+<!--eslint-skip-->
+
+```astro
+---
+---
+
+{/* ✓ GOOD */}
+<Element a="a" b="b" c="c" />
+
+{/* ✓ BAD */}
+<Element c="c" b="b" a="a" />
+```
+
+</ESLintCodeBlock>
+
+## :wrench: Options
+
+```json
+{
+  "astro/sort-attributes": [
+    "error", 
+    { "type": "alphabetical", "order": "asc", "ignoreCase": true }
+  ]
+}
+```
+
+## :rocket: Version
+
+This rule was introduced in eslint-plugin-astro v1.3.0
+
+## :mag: Implementation
+
+- [Rule source](https://github.com/ota-meshi/eslint-plugin-astro/blob/main/src/rules/sort-attributes.ts)
+- [Test source](https://github.com/ota-meshi/eslint-plugin-astro/blob/main/tests/src/rules/sort-attributes.ts)
+- [Test fixture sources](https://github.com/ota-meshi/eslint-plugin-astro/tree/main/tests/fixtures/rules/sort-attributes)
diff --git a/src/rules/sort-attributes.ts b/src/rules/sort-attributes.ts
new file mode 100644
index 0000000..b19fdc3
--- /dev/null
+++ b/src/rules/sort-attributes.ts
@@ -0,0 +1,137 @@
+import type { AST } from "astro-eslint-parser"
+
+import { createRule } from "../utils"
+
+export default createRule("sort-attributes", {
+  meta: {
+    docs: {
+      description: "enforce sorting of attributes",
+      category: "Stylistic Issues",
+      recommended: false,
+    },
+    schema: [
+      {
+        type: "object",
+        properties: {
+          type: { type: "string", enum: ["alphabetical", "line-length"] },
+          ignoreCase: { type: "boolean" },
+          order: { type: "string", enum: ["asc", "desc"] },
+        },
+        additionalProperties: false,
+      },
+    ],
+    messages: {
+      unexpectedAstroAttributesOrder:
+        'Expected "{{right}}" to come before "{{left}}".',
+    },
+    fixable: "code",
+    type: "suggestion",
+  },
+  create(context) {
+    if (!context.parserServices.isAstro) {
+      return {}
+    }
+
+    return {
+      JSXElement(node) {
+        const { openingElement } = node
+        const { attributes } = openingElement
+
+        if (attributes.length <= 1) {
+          return
+        }
+
+        const sourceCode = context.getSourceCode()
+
+        const pairwise = <T>(
+          nodes: T[],
+          callback: (left: T, right: T, iteration: number) => void,
+        ) => {
+          if (nodes.length > 1) {
+            for (let i = 1; i < nodes.length; i++) {
+              let left = nodes.at(i - 1)
+              let right = nodes.at(i)
+
+              if (left && right) {
+                callback(left, right, i - 1)
+              }
+            }
+          }
+        }
+
+        type Node =
+          | AST.AstroShorthandAttribute
+          | AST.AstroTemplateLiteralAttribute
+          | AST.JSXAttribute
+
+        type SortingNode = {
+          name: string
+          node: Node
+          size: number
+        }
+
+        const compare = (left: SortingNode, right: SortingNode) => {
+          const compareFunc = (a: SortingNode, b: SortingNode) => {
+            if (context.options[0]?.type === "line-length") {
+              return a.size - b.size
+            }
+            const formatName = (name: string) =>
+              context.options[0]?.ignoreCase === false
+                ? name
+                : name.toLowerCase()
+            return formatName(a.name).localeCompare(formatName(b.name))
+          }
+
+          const orderCoefficient = context.options[0]?.order === "desc" ? -1 : 1
+
+          return compareFunc(left, right) * orderCoefficient
+        }
+
+        const parts = attributes.reduce(
+          (accumulator: SortingNode[][], attribute) => {
+            if (attribute.type === "JSXSpreadAttribute") {
+              accumulator.push([])
+              return accumulator
+            }
+
+            const name =
+              typeof attribute.name.name === "string"
+                ? attribute.name.name
+                : sourceCode.text.slice(...attribute.name.range)
+
+            accumulator[accumulator.length - 1].push({
+              name,
+              node: attribute,
+              size: attribute.range[1] - attribute.range[0],
+            })
+
+            return accumulator
+          },
+          [[]],
+        )
+
+        for (let nodes of parts) {
+          pairwise(nodes, (left, right) => {
+            if (compare(left, right) > 0) {
+              context.report({
+                node: left.node,
+                messageId: "unexpectedAstroAttributesOrder",
+                data: {
+                  left: left.name,
+                  right: right.name,
+                },
+                fix(fixer) {
+                  return fixer.replaceTextRange(
+                    [left.node.range[0], right.node.range[1]],
+                    sourceCode.text.slice(...right.node.range) +
+                      sourceCode.text.slice(...left.node.range),
+                  )
+                },
+              })
+            }
+          })
+        }
+      },
+    }
+  },
+})
diff --git a/src/utils/rules.ts b/src/utils/rules.ts
index 1cda35a..f780fdd 100644
--- a/src/utils/rules.ts
+++ b/src/utils/rules.ts
@@ -17,6 +17,7 @@ import preferClassListDirective from "../rules/prefer-class-list-directive"
 import preferObjectClassList from "../rules/prefer-object-class-list"
 import preferSplitClassList from "../rules/prefer-split-class-list"
 import semi from "../rules/semi"
+import sortAttributes from "../rules/sort-attributes"
 import validCompile from "../rules/valid-compile"
 import { buildA11yRules } from "../a11y"
 
@@ -36,6 +37,7 @@ export const rules = [
   preferObjectClassList,
   preferSplitClassList,
   semi,
+  sortAttributes,
   validCompile,
   ...buildA11yRules(),
 ] as RuleModule[]


Test patch:
diff --git a/tests/fixtures/rules/sort-attributes/invalid/alphabetical/_config.json b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/_config.json
new file mode 100644
index 0000000..9c47765
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/_config.json
@@ -0,0 +1,3 @@
+{
+  "options": [{ "type": "alphabetical", "order": "asc" }]
+}
diff --git a/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-errors.json b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-errors.json
new file mode 100644
index 0000000..ebe798e
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-errors.json
@@ -0,0 +1,12 @@
+[
+  {
+    "message": "Expected \"b\" to come before \"c\".",
+    "line": 5,
+    "column": 6
+  },
+  {
+    "message": "Expected \"a\" to come before \"b\".",
+    "line": 5,
+    "column": 12
+  }
+]
diff --git a/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-input.astro b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-input.astro
new file mode 100644
index 0000000..b608c74
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-input.astro
@@ -0,0 +1,5 @@
+---
+
+---
+
+<div c="c" b="b" a="a"></div>
diff --git a/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-output.astro b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-output.astro
new file mode 100644
index 0000000..3e2c256
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/alphabetical/test01-output.astro
@@ -0,0 +1,5 @@
+---
+
+---
+
+<div b="b"c="c" a="a"></div>
diff --git a/tests/fixtures/rules/sort-attributes/invalid/line-length/_config.json b/tests/fixtures/rules/sort-attributes/invalid/line-length/_config.json
new file mode 100644
index 0000000..d9e6655
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/line-length/_config.json
@@ -0,0 +1,3 @@
+{
+  "options": [{ "type": "line-length", "order": "desc" }]
+}
diff --git a/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-errors.json b/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-errors.json
new file mode 100644
index 0000000..a295628
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-errors.json
@@ -0,0 +1,12 @@
+[
+  {
+    "message": "Expected \"bb\" to come before \"c\".",
+    "line": 5,
+    "column": 6
+  },
+  {
+    "message": "Expected \"aaa\" to come before \"bb\".",
+    "line": 5,
+    "column": 12
+  }
+]
diff --git a/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-input.astro b/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-input.astro
new file mode 100644
index 0000000..045c0a3
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-input.astro
@@ -0,0 +1,5 @@
+---
+
+---
+
+<div c="c" bb="b" aaa="a"></div>
diff --git a/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-output.astro b/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-output.astro
new file mode 100644
index 0000000..0ce47b6
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/invalid/line-length/test01-output.astro
@@ -0,0 +1,5 @@
+---
+
+---
+
+<div bb="b"c="c" aaa="a"></div>
diff --git a/tests/fixtures/rules/sort-attributes/valid/alphabetical/_config.json b/tests/fixtures/rules/sort-attributes/valid/alphabetical/_config.json
new file mode 100644
index 0000000..9c47765
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/valid/alphabetical/_config.json
@@ -0,0 +1,3 @@
+{
+  "options": [{ "type": "alphabetical", "order": "asc" }]
+}
diff --git a/tests/fixtures/rules/sort-attributes/valid/alphabetical/test01-input.astro b/tests/fixtures/rules/sort-attributes/valid/alphabetical/test01-input.astro
new file mode 100644
index 0000000..c282513
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/valid/alphabetical/test01-input.astro
@@ -0,0 +1,5 @@
+---
+
+---
+
+<div a="a" b="b" c="c"></div>
diff --git a/tests/fixtures/rules/sort-attributes/valid/alphabetical/test02-input.astro b/tests/fixtures/rules/sort-attributes/valid/alphabetical/test02-input.astro
new file mode 100644
index 0000000..6ca9e24
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/valid/alphabetical/test02-input.astro
@@ -0,0 +1,5 @@
+---
+const d = []
+---
+
+<div b="b" c="c" {...d} a="a"></div>
diff --git a/tests/fixtures/rules/sort-attributes/valid/line-length/_config.json b/tests/fixtures/rules/sort-attributes/valid/line-length/_config.json
new file mode 100644
index 0000000..d9e6655
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/valid/line-length/_config.json
@@ -0,0 +1,3 @@
+{
+  "options": [{ "type": "line-length", "order": "desc" }]
+}
diff --git a/tests/fixtures/rules/sort-attributes/valid/line-length/test01-input.astro b/tests/fixtures/rules/sort-attributes/valid/line-length/test01-input.astro
new file mode 100644
index 0000000..78f1a90
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/valid/line-length/test01-input.astro
@@ -0,0 +1,5 @@
+---
+
+---
+
+<div aaa="a" bb="b" c="c"></div>
diff --git a/tests/fixtures/rules/sort-attributes/valid/line-length/test02-input.astro b/tests/fixtures/rules/sort-attributes/valid/line-length/test02-input.astro
new file mode 100644
index 0000000..5feb2bf
--- /dev/null
+++ b/tests/fixtures/rules/sort-attributes/valid/line-length/test02-input.astro
@@ -0,0 +1,5 @@
+---
+const d = []
+---
+
+<div bb="b" c="c" {...d} aaa="a"></div>
diff --git a/tests/src/rules/sort-attributes.ts b/tests/src/rules/sort-attributes.ts
new file mode 100644
index 0000000..25032a8
--- /dev/null
+++ b/tests/src/rules/sort-attributes.ts
@@ -0,0 +1,15 @@
+import { RuleTester } from "eslint"
+import rule from "../../../src/rules/sort-attributes"
+import { loadTestCases } from "../../utils/utils"
+
+const tester = new RuleTester({
+  parserOptions: {
+    ecmaVersion: 2020,
+    sourceType: "module",
+  },
+  globals: {
+    Astro: false,
+  },
+})
+
+tester.run("sort-attributes", rule as any, loadTestCases("sort-attributes"))