Skip to content

Commit 8c35a7d

Browse files
committed
fix: don't sort class members if right value depends on left
1 parent eff6523 commit 8c35a7d

File tree

2 files changed

+1590
-576
lines changed

2 files changed

+1590
-576
lines changed

rules/sort-classes.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { TSESTree } from '@typescript-eslint/types'
12
import type { TSESLint } from '@typescript-eslint/utils'
23

34
import type { SortingNode } from '../typings'
@@ -186,6 +187,55 @@ export default createEslintRule<Options, MESSAGE_ID>({
186187

187188
let sourceCode = getSourceCode(context)
188189

190+
let extractDependencies = (
191+
expression: TSESTree.Expression,
192+
): string[] => {
193+
let dependencies: string[] = []
194+
195+
let checkNode = (nodeValue: TSESTree.Node) => {
196+
if (
197+
nodeValue.type === 'MemberExpression' &&
198+
nodeValue.object.type === 'ThisExpression' &&
199+
nodeValue.property.type === 'Identifier'
200+
) {
201+
dependencies.push(nodeValue.property.name)
202+
}
203+
204+
if ('body' in nodeValue && nodeValue.body) {
205+
traverseNode(nodeValue.body)
206+
}
207+
208+
if ('left' in nodeValue) {
209+
traverseNode(nodeValue.left)
210+
}
211+
212+
if ('right' in nodeValue) {
213+
traverseNode(nodeValue.right)
214+
}
215+
216+
if ('elements' in nodeValue) {
217+
nodeValue.elements
218+
.filter(currentNode => currentNode !== null)
219+
.forEach(traverseNode)
220+
}
221+
222+
if ('arguments' in nodeValue) {
223+
nodeValue.arguments.forEach(traverseNode)
224+
}
225+
}
226+
227+
let traverseNode = (nodeValue: TSESTree.Node[] | TSESTree.Node) => {
228+
if (Array.isArray(nodeValue)) {
229+
nodeValue.forEach(traverseNode)
230+
} else {
231+
checkNode(nodeValue)
232+
}
233+
}
234+
235+
traverseNode(expression)
236+
return dependencies
237+
}
238+
189239
let formattedNodes: SortingNode[][] = node.body.reduce(
190240
(accumulator: SortingNode[][], member) => {
191241
let comment = getCommentBefore(member, sourceCode)
@@ -199,6 +249,7 @@ export default createEslintRule<Options, MESSAGE_ID>({
199249
}
200250

201251
let name: string
252+
let dependencies: string[] = []
202253
let { getGroup, defineGroup, setCustomGroups } = useGroups(
203254
options.groups,
204255
)
@@ -299,9 +350,14 @@ export default createEslintRule<Options, MESSAGE_ID>({
299350
override: true,
300351
})
301352

353+
if (member.type === 'PropertyDefinition' && member.value) {
354+
dependencies = extractDependencies(member.value)
355+
}
356+
302357
let value = {
303358
size: rangeToDiff(member.range),
304359
group: getGroup(),
360+
dependencies,
305361
node: member,
306362
name,
307363
}

0 commit comments

Comments
 (0)