Intellicode / eslint-plugin-react-native

React Native plugin for ESLint
MIT License
722 stars 130 forks source link

Support looking for unused styles when using react-native-themed-styles (in a stylized way) #283

Open gjbadros opened 3 years ago

gjbadros commented 3 years ago

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch eslint-plugin-react-native@3.10.0 for the project I'm working on.

I made this work with https://github.com/wvteijlingen/react-native-themed-styles, using "SSF" in the eslint config:

    "react-native/style-sheet-object-names": ["SSF", "StyleSheet"],

and then

class SSF {
  static create = registerThemes({ light, dark }, () => {
    const colorScheme = useColorScheme()
    return colorScheme == 'dark' ? DARK_SCHEME : 'light' # or whatever
  })
}

The pattern then has to be:

const themedStyles = SSF.create((themeColors) => ({ # name 'themedStyles' matters for this patch but is easy to generalize
....
}))

and then inside the component:

  const [styles, themeColors] = useTheme(themedStyles) # name 'styles' matters for this patch but is easy to generalize with a setting

Here is the diff that solved my problem:

diff --git a/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js b/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js
index ff8da41..9157a2a 100644
--- a/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js
+++ b/node_modules/eslint-plugin-react-native/lib/util/stylesheet.js
@@ -126,7 +126,11 @@ const astHelpers = {

   getStyleSheetName: function (node) {
     if (node && node.parent && node.parent.id) {
-      return node.parent.id.name;
+      let answer = node.parent.id.name;
+      if (answer == 'themedStyles') {
+        answer = 'styles'
+      }
+      return answer
     }
   },

@@ -140,6 +144,19 @@ const astHelpers = {
     ) {
       return node.arguments[0].properties.filter((property) => property.type === 'Property');
     }
+    if (
+      node &&
+      node.type === 'CallExpression' &&
+      node.arguments &&
+      node.arguments[0] &&
+      node.arguments[0].body &&
+      node.arguments[0].body.properties
+    ) {
+      // console.log('gsd = []', 'v= ', node.arguments[0].body.properties)
+      return node.arguments[0].body.properties.filter(
+        (property) => property.type === 'Property'
+      )
+    }

     return [];
   },

This issue body was partially generated by patch-package.