1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
1
2
import { Rule } from 'eslint'
2
3
4
+ function detectConditionalExpression (
5
+ expression : any ,
6
+ context : Rule . RuleContext ,
7
+ node : any ,
8
+ ) {
9
+ if ( expression ) {
10
+ if (
11
+ expression . type === 'ConditionalExpression' ||
12
+ ( expression . type === 'LogicalExpression' &&
13
+ ( expression . operator === '&&' || expression . operator === '||' ) )
14
+ ) {
15
+ context . report ( {
16
+ message :
17
+ 'Avoid using conditionals within the css prop, move them to style.' ,
18
+ node : node ,
19
+ } )
20
+ }
21
+ }
22
+ }
23
+
3
24
export default {
4
25
create ( context ) {
5
26
return {
6
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
27
JSXAttribute ( node : any ) {
8
- if (
9
- node . name . name === 'css' &&
10
- node . value &&
11
- node . value . type === 'JSXExpressionContainer' &&
12
- ( node . value . expression . type === 'ConditionalExpression' ||
13
- ( node . value . expression . type === 'LogicalExpression' &&
14
- ( node . value . expression . operator === '&&' ||
15
- node . value . expression . operator === '||' ) ) )
16
- ) {
17
- context . report ( {
18
- message :
19
- 'Avoid using conditionals within the css prop, move them to style.' ,
20
- node ,
21
- } )
28
+ if ( node . name . name === 'css' ) {
29
+ if ( node . value && node . value . type === 'JSXExpressionContainer' ) {
30
+ const expression = node . value . expression
31
+
32
+ // Check if it's an array
33
+ if ( expression . type === 'ArrayExpression' ) {
34
+ expression . elements . forEach ( ( element : any ) => {
35
+ detectConditionalExpression ( element , context , node )
36
+ } )
37
+ } else {
38
+ // Check single expressions
39
+ detectConditionalExpression ( expression , context , node )
40
+ }
41
+ }
22
42
}
23
43
} ,
24
44
}
@@ -27,6 +47,13 @@ export default {
27
47
docs : {
28
48
category : 'Best Practices' ,
29
49
description : 'Disallow conditionals within the css prop in components' ,
50
+ example : `
51
+ // Before
52
+ <div css={[randomDivStyle, isRed ? {color: "red"} : null]} />
53
+
54
+ // After
55
+ <div css={randomDivStyle} style={isRed ? {color: "red"}} />
56
+ ` ,
30
57
recommended : false ,
31
58
} ,
32
59
schema : [ ] ,
0 commit comments