Mathieu Acthernoene 7 лет назад
Родитель
Сommit
2895fa2ade
9 измененных файлов: 223 добавлений и 190 удалений
  1. 3
    1
      .prettierrc
  2. 47
    40
      Example/Example.js
  3. 6
    8
      Example/__tests__/index.android.js
  4. 6
    8
      Example/__tests__/index.ios.js
  5. 3
    5
      Example/index.android.js
  6. 3
    5
      Example/index.ios.js
  7. 82
    73
      index.android.js
  8. 63
    50
      index.ios.js
  9. 10
    0
      package.json

+ 3
- 1
.prettierrc Просмотреть файл

@@ -1,3 +1,5 @@
1 1
 {
2
-  "singleQuote": true
2
+  "singleQuote": true,
3
+  "trailingComma": "all",
4
+  "semi": false
3 5
 }

+ 47
- 40
Example/Example.js Просмотреть файл

@@ -4,7 +4,7 @@
4 4
  * @flow
5 5
  */
6 6
 
7
-import React, { Component } from 'react';
7
+import React, { Component } from 'react'
8 8
 import {
9 9
   StyleSheet,
10 10
   TouchableHighlight,
@@ -13,7 +13,7 @@ import {
13 13
   Alert,
14 14
   AppState,
15 15
   Platform,
16
-} from 'react-native';
16
+} from 'react-native'
17 17
 
18 18
 import Permissions from 'react-native-permissions'
19 19
 
@@ -29,11 +29,14 @@ export default class Example extends Component {
29 29
 
30 30
     this.setState({ types, canOpenSettings })
31 31
     this._updatePermissions(types)
32
-    AppState.addEventListener('change', this._handleAppStateChange.bind(this));
32
+    AppState.addEventListener('change', this._handleAppStateChange.bind(this))
33 33
   }
34 34
 
35 35
   componentWillUnmount() {
36
-    AppState.removeEventListener('change', this._handleAppStateChange.bind(this));
36
+    AppState.removeEventListener(
37
+      'change',
38
+      this._handleAppStateChange.bind(this),
39
+    )
37 40
   }
38 41
 
39 42
   //update permissions when app comes back from settings
@@ -44,16 +47,17 @@ export default class Example extends Component {
44 47
   }
45 48
 
46 49
   _openSettings() {
47
-    return Permissions.openSettings()
48
-      .then(() => alert('back to app!!'))
50
+    return Permissions.openSettings().then(() => alert('back to app!!'))
49 51
   }
50 52
 
51 53
   _updatePermissions(types) {
52 54
     Permissions.checkMultiple(types)
53 55
       .then(status => {
54 56
         if (this.state.isAlways) {
55
-          return Permissions.check('location', 'always')
56
-            .then(location => ({...status, location}))
57
+          return Permissions.check('location', 'always').then(location => ({
58
+            ...status,
59
+            location,
60
+          }))
57 61
         }
58 62
         return status
59 63
       })
@@ -70,19 +74,24 @@ export default class Example extends Component {
70 74
     Permissions.request(permission, options)
71 75
       .then(res => {
72 76
         this.setState({
73
-          status: {...this.state.status, [permission]: res}
77
+          status: { ...this.state.status, [permission]: res },
74 78
         })
75 79
         if (res != 'authorized') {
76 80
           var buttons = [{ text: 'Cancel', style: 'cancel' }]
77
-          if (this.state.canOpenSettings) buttons.push({ text: 'Open Settings', onPress: this._openSettings.bind(this) })
78
-          
81
+          if (this.state.canOpenSettings)
82
+            buttons.push({
83
+              text: 'Open Settings',
84
+              onPress: this._openSettings.bind(this),
85
+            })
86
+
79 87
           Alert.alert(
80 88
             'Whoops!',
81
-            "There was a problem getting your permission. Please enable it from settings.",
82
-            buttons
89
+            'There was a problem getting your permission. Please enable it from settings.',
90
+            buttons,
83 91
           )
84 92
         }
85
-      }).catch(e => console.warn(e))
93
+      })
94
+      .catch(e => console.warn(e))
86 95
   }
87 96
 
88 97
   _onLocationSwitchChange() {
@@ -93,46 +102,44 @@ export default class Example extends Component {
93 102
   render() {
94 103
     return (
95 104
       <View style={styles.container}>
96
-
97 105
         {this.state.types.map(p => (
98
-          <TouchableHighlight 
106
+          <TouchableHighlight
99 107
             style={[styles.button, styles[this.state.status[p]]]}
100 108
             key={p}
101
-            onPress={this._requestPermission.bind(this, p)}>
109
+            onPress={this._requestPermission.bind(this, p)}
110
+          >
102 111
             <View>
103 112
               <Text style={styles.text}>
104
-                {Platform.OS == 'ios' && p == 'location' ? `location ${this.state.isAlways ? 'always' : 'whenInUse'}` : p}
105
-              </Text>
106
-              <Text style={styles.subtext}>
107
-                {this.state.status[p]}
113
+                {Platform.OS == 'ios' && p == 'location'
114
+                  ? `location ${this.state.isAlways ? 'always' : 'whenInUse'}`
115
+                  : p}
108 116
               </Text>
117
+              <Text style={styles.subtext}>{this.state.status[p]}</Text>
109 118
             </View>
110 119
           </TouchableHighlight>
111
-          )
112
-        )}
120
+        ))}
113 121
         <View style={styles.footer}>
114
-          <TouchableHighlight 
115
-            style={styles['footer_'+Platform.OS]}
116
-            onPress={this._onLocationSwitchChange.bind(this)}>
122
+          <TouchableHighlight
123
+            style={styles['footer_' + Platform.OS]}
124
+            onPress={this._onLocationSwitchChange.bind(this)}
125
+          >
117 126
             <Text style={styles.text}>Toggle location type</Text>
118 127
           </TouchableHighlight>
119
-   
120
-          {
121
-            this.state.canOpenSettings &&
122
-            <TouchableHighlight 
123
-              onPress={this._openSettings.bind(this)}>
128
+
129
+          {this.state.canOpenSettings && (
130
+            <TouchableHighlight onPress={this._openSettings.bind(this)}>
124 131
               <Text style={styles.text}>Open settings</Text>
125 132
             </TouchableHighlight>
126
-          }
127
-
133
+          )}
128 134
         </View>
129 135
 
130
-
131
-        <Text style={styles['footer_'+Platform.OS]}>
132
-          Note: microphone permissions may not work on iOS simulator. Also, toggling permissions from the settings menu may cause the app to crash. This is normal on iOS. Google "ios crash permission change"
136
+        <Text style={styles['footer_' + Platform.OS]}>
137
+          Note: microphone permissions may not work on iOS simulator. Also,
138
+          toggling permissions from the settings menu may cause the app to
139
+          crash. This is normal on iOS. Google "ios crash permission change"
133 140
         </Text>
134 141
       </View>
135
-    );
142
+    )
136 143
   }
137 144
 }
138 145
 
@@ -169,7 +176,7 @@ const styles = StyleSheet.create({
169 176
     backgroundColor: '#ef9a9a',
170 177
   },
171 178
   restricted: {
172
-    backgroundColor: '#ef9a9a'
179
+    backgroundColor: '#ef9a9a',
173 180
   },
174 181
   footer: {
175 182
     padding: 10,
@@ -179,5 +186,5 @@ const styles = StyleSheet.create({
179 186
   footer_android: {
180 187
     height: 0,
181 188
     width: 0,
182
-  }
183
-})
189
+  },
190
+})

+ 6
- 8
Example/__tests__/index.android.js Просмотреть файл

@@ -1,12 +1,10 @@
1
-import 'react-native';
2
-import React from 'react';
3
-import Index from '../index.android.js';
1
+import 'react-native'
2
+import React from 'react'
3
+import Index from '../index.android.js'
4 4
 
5 5
 // Note: test renderer must be required after react-native.
6
-import renderer from 'react-test-renderer';
6
+import renderer from 'react-test-renderer'
7 7
 
8 8
 it('renders correctly', () => {
9
-  const tree = renderer.create(
10
-    <Index />
11
-  );
12
-});
9
+  const tree = renderer.create(<Index />)
10
+})

+ 6
- 8
Example/__tests__/index.ios.js Просмотреть файл

@@ -1,12 +1,10 @@
1
-import 'react-native';
2
-import React from 'react';
3
-import Index from '../index.ios.js';
1
+import 'react-native'
2
+import React from 'react'
3
+import Index from '../index.ios.js'
4 4
 
5 5
 // Note: test renderer must be required after react-native.
6
-import renderer from 'react-test-renderer';
6
+import renderer from 'react-test-renderer'
7 7
 
8 8
 it('renders correctly', () => {
9
-  const tree = renderer.create(
10
-    <Index />
11
-  );
12
-});
9
+  const tree = renderer.create(<Index />)
10
+})

+ 3
- 5
Example/index.android.js Просмотреть файл

@@ -4,11 +4,9 @@
4 4
  * @flow
5 5
  */
6 6
 
7
-import React, { Component } from 'react';
8
-import {
9
-  AppRegistry,
10
-} from 'react-native';
7
+import React, { Component } from 'react'
8
+import { AppRegistry } from 'react-native'
11 9
 
12 10
 import Example from './Example'
13 11
 
14
-AppRegistry.registerComponent('Example', () => Example);
12
+AppRegistry.registerComponent('Example', () => Example)

+ 3
- 5
Example/index.ios.js Просмотреть файл

@@ -4,11 +4,9 @@
4 4
  * @flow
5 5
  */
6 6
 
7
-import React, { Component } from 'react';
8
-import {
9
-  AppRegistry,
10
-} from 'react-native';
7
+import React, { Component } from 'react'
8
+import { AppRegistry } from 'react-native'
11 9
 
12 10
 import Example from './Example'
13 11
 
14
-AppRegistry.registerComponent('Example', () => Example);
12
+AppRegistry.registerComponent('Example', () => Example)

+ 82
- 73
index.android.js Просмотреть файл

@@ -1,91 +1,100 @@
1
-'use strict';
1
+'use strict'
2 2
 
3 3
 const ReactNative = require('react-native')
4
-const RNPermissions = ReactNative.PermissionsAndroid;
4
+const RNPermissions = ReactNative.PermissionsAndroid
5 5
 const AsyncStorage = ReactNative.AsyncStorage
6 6
 
7 7
 const RNPTypes = {
8
-	location: RNPermissions.PERMISSIONS.ACCESS_FINE_LOCATION,
9
-	camera: RNPermissions.PERMISSIONS.CAMERA,
10
-	microphone: RNPermissions.PERMISSIONS.RECORD_AUDIO,
11
-	contacts: RNPermissions.PERMISSIONS.READ_CONTACTS,
12
-	event: RNPermissions.PERMISSIONS.READ_CALENDAR,
13
-	storage: RNPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,
14
-	photo: RNPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,
15
-	callPhone: RNPermissions.PERMISSIONS.CALL_PHONE,
16
-	readSms: RNPermissions.PERMISSIONS.READ_SMS,
17
-	receiveSms: RNPermissions.PERMISSIONS.RECEIVE_SMS,
8
+  location: RNPermissions.PERMISSIONS.ACCESS_FINE_LOCATION,
9
+  camera: RNPermissions.PERMISSIONS.CAMERA,
10
+  microphone: RNPermissions.PERMISSIONS.RECORD_AUDIO,
11
+  contacts: RNPermissions.PERMISSIONS.READ_CONTACTS,
12
+  event: RNPermissions.PERMISSIONS.READ_CALENDAR,
13
+  storage: RNPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,
14
+  photo: RNPermissions.PERMISSIONS.READ_EXTERNAL_STORAGE,
15
+  callPhone: RNPermissions.PERMISSIONS.CALL_PHONE,
16
+  readSms: RNPermissions.PERMISSIONS.READ_SMS,
17
+  receiveSms: RNPermissions.PERMISSIONS.RECEIVE_SMS,
18 18
 }
19 19
 
20 20
 const RESULTS = {
21
-	[ RNPermissions.RESULTS.GRANTED ]: 'authorized',
22
-	[ RNPermissions.RESULTS.DENIED ]: 'denied',
23
-	[ RNPermissions.RESULTS.NEVER_ASK_AGAIN ]: 'restricted',
21
+  [RNPermissions.RESULTS.GRANTED]: 'authorized',
22
+  [RNPermissions.RESULTS.DENIED]: 'denied',
23
+  [RNPermissions.RESULTS.NEVER_ASK_AGAIN]: 'restricted',
24 24
 }
25 25
 
26 26
 const STORAGE_KEY = '@RNPermissions:didAskPermission:'
27 27
 
28 28
 const setDidAskOnce = p => AsyncStorage.setItem(STORAGE_KEY + p, 'true')
29
-const getDidAskOnce = p =>  AsyncStorage.getItem(STORAGE_KEY + p).then(res => !!res)
29
+const getDidAskOnce = p =>
30
+  AsyncStorage.getItem(STORAGE_KEY + p).then(res => !!res)
30 31
 
31 32
 class ReactNativePermissions {
32
-	canOpenSettings() {
33
-		return false
34
-	}
35
-
36
-	openSettings() {
37
-		return Promise.reject('\'openSettings\' is Depricated on android')
38
-	}
39
-
40
-	getTypes() {
41
-		return Object.keys(RNPTypes);
42
-	}
43
-
44
-	check(permission) {
45
-		const androidPermission = RNPTypes[permission]
46
-  	if (!androidPermission) return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on Android`);
47
-		
48
-		const shouldShowRationale = ReactNative.NativeModules.PermissionsAndroid.shouldShowRequestPermissionRationale;
49
-
50
-		return RNPermissions.check(androidPermission)
51
-			.then(isAuthorized => {
52
-				if (isAuthorized) return 'authorized'
53
-
54
-				return getDidAskOnce(permission)
55
-					.then(didAsk => {
56
-						if (didAsk) {
57
-							return shouldShowRationale(androidPermission)
58
-								.then(shouldShow => shouldShow ? 'denied' : 'restricted')
59
-						}
60
-						return 'undetermined'
61
-					})
62
-			})
63
-	}
64
-
65
-
66
-	request(permission) {
67
-		const androidPermission = RNPTypes[permission]
68
-  	if (!androidPermission) return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on Android`);
69
-
70
-
71
-		return RNPermissions.request(androidPermission)
72
-			.then(res => {
73
-				// RNPermissions.request() to native module resolves to boolean
74
-				// rather than string if running on OS version prior to Android M 
75
-				if (typeof res === 'boolean') return res ? 'authorized' : 'denied';
76
-				return setDidAskOnce(permission)
77
-					.then(() => RESULTS[res])
78
-			});
79
-	}
80
-
81
-	checkMultiple(permissions) {
82
-		return Promise.all(permissions.map(this.check.bind(this)))
83
-			.then(res => res.reduce((pre, cur, i) => {
84
-				var name = permissions[i]
85
-				pre[name] = cur
86
-				return pre
87
-			}, {}))
88
-	}
33
+  canOpenSettings() {
34
+    return false
35
+  }
36
+
37
+  openSettings() {
38
+    return Promise.reject("'openSettings' is Depricated on android")
39
+  }
40
+
41
+  getTypes() {
42
+    return Object.keys(RNPTypes)
43
+  }
44
+
45
+  check(permission) {
46
+    const androidPermission = RNPTypes[permission]
47
+    if (!androidPermission)
48
+      return Promise.reject(
49
+        `ReactNativePermissions: ${
50
+          permission
51
+        } is not a valid permission type on Android`,
52
+      )
53
+
54
+    const shouldShowRationale =
55
+      ReactNative.NativeModules.PermissionsAndroid
56
+        .shouldShowRequestPermissionRationale
57
+
58
+    return RNPermissions.check(androidPermission).then(isAuthorized => {
59
+      if (isAuthorized) return 'authorized'
60
+
61
+      return getDidAskOnce(permission).then(didAsk => {
62
+        if (didAsk) {
63
+          return shouldShowRationale(androidPermission).then(
64
+            shouldShow => (shouldShow ? 'denied' : 'restricted'),
65
+          )
66
+        }
67
+        return 'undetermined'
68
+      })
69
+    })
70
+  }
71
+
72
+  request(permission) {
73
+    const androidPermission = RNPTypes[permission]
74
+    if (!androidPermission)
75
+      return Promise.reject(
76
+        `ReactNativePermissions: ${
77
+          permission
78
+        } is not a valid permission type on Android`,
79
+      )
80
+
81
+    return RNPermissions.request(androidPermission).then(res => {
82
+      // RNPermissions.request() to native module resolves to boolean
83
+      // rather than string if running on OS version prior to Android M
84
+      if (typeof res === 'boolean') return res ? 'authorized' : 'denied'
85
+      return setDidAskOnce(permission).then(() => RESULTS[res])
86
+    })
87
+  }
88
+
89
+  checkMultiple(permissions) {
90
+    return Promise.all(permissions.map(this.check.bind(this))).then(res =>
91
+      res.reduce((pre, cur, i) => {
92
+        var name = permissions[i]
93
+        pre[name] = cur
94
+        return pre
95
+      }, {}),
96
+    )
97
+  }
89 98
 }
90 99
 
91 100
 module.exports = new ReactNativePermissions()

+ 63
- 50
index.ios.js Просмотреть файл

@@ -1,70 +1,83 @@
1
-'use strict';
1
+'use strict'
2 2
 
3
-const ReactNative = require('react-native');
4
-const RNPermissions = ReactNative.NativeModules.ReactNativePermissions;
3
+const ReactNative = require('react-native')
4
+const RNPermissions = ReactNative.NativeModules.ReactNativePermissions
5 5
 
6 6
 const RNPTypes = [
7
-	'location',
8
-	'camera',
9
-	'microphone',
10
-	'photo',
11
-	'contacts',
12
-	'event',
13
-	'reminder',
14
-	'bluetooth',
15
-	'notification',
16
-	'backgroundRefresh',
17
-	'speechRecognition',
7
+  'location',
8
+  'camera',
9
+  'microphone',
10
+  'photo',
11
+  'contacts',
12
+  'event',
13
+  'reminder',
14
+  'bluetooth',
15
+  'notification',
16
+  'backgroundRefresh',
17
+  'speechRecognition',
18 18
 ]
19 19
 
20 20
 const DEFAULTS = {
21
-	'location' : 'whenInUse',
22
-	'notification': ['alert', 'badge', 'sound'],
21
+  location: 'whenInUse',
22
+  notification: ['alert', 'badge', 'sound'],
23 23
 }
24 24
 
25 25
 class ReactNativePermissions {
26
-	canOpenSettings() {
27
-		return RNPermissions.canOpenSettings()
28
-	}
26
+  canOpenSettings() {
27
+    return RNPermissions.canOpenSettings()
28
+  }
29 29
 
30
-	openSettings() {
31
-		return RNPermissions.openSettings()
32
-	}
30
+  openSettings() {
31
+    return RNPermissions.openSettings()
32
+  }
33 33
 
34
-	getTypes() {
35
-		return RNPTypes;
36
-	}
34
+  getTypes() {
35
+    return RNPTypes
36
+  }
37 37
 
38
-	check(permission, type) {
39
-  	if (!RNPTypes.includes(permission)) {
40
-			return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on iOS`);
41
-		}
42
-		
43
-		return RNPermissions.getPermissionStatus(permission, type);
44
-	}
38
+  check(permission, type) {
39
+    if (!RNPTypes.includes(permission)) {
40
+      return Promise.reject(
41
+        `ReactNativePermissions: ${
42
+          permission
43
+        } is not a valid permission type on iOS`,
44
+      )
45
+    }
45 46
 
46
-	request(permission, type) {
47
-		if (!RNPTypes.includes(permission)) {
48
-			return Promise.reject(`ReactNativePermissions: ${permission} is not a valid permission type on iOS`);
49
-		}
47
+    return RNPermissions.getPermissionStatus(permission, type)
48
+  }
50 49
 
51
-		if (permission == 'backgroundRefresh') {
52
-			return Promise.reject('ReactNativePermissions: You cannot request backgroundRefresh')
53
-		}
50
+  request(permission, type) {
51
+    if (!RNPTypes.includes(permission)) {
52
+      return Promise.reject(
53
+        `ReactNativePermissions: ${
54
+          permission
55
+        } is not a valid permission type on iOS`,
56
+      )
57
+    }
54 58
 
55
-		type = type || DEFAULTS[permission]
59
+    if (permission == 'backgroundRefresh') {
60
+      return Promise.reject(
61
+        'ReactNativePermissions: You cannot request backgroundRefresh',
62
+      )
63
+    }
56 64
 
57
-		return RNPermissions.requestPermission(permission, type)
58
-	}
65
+    type = type || DEFAULTS[permission]
59 66
 
60
-	checkMultiple(permissions) {
61
-		return Promise.all(permissions.map(permission => this.check(permission)))
62
-			.then(res => res.reduce((pre, cur, i) => {
63
-				var name = permissions[i]
64
-				pre[name] = cur
65
-				return pre
66
-			}, {}))
67
-	}
67
+    return RNPermissions.requestPermission(permission, type)
68
+  }
69
+
70
+  checkMultiple(permissions) {
71
+    return Promise.all(
72
+      permissions.map(permission => this.check(permission)),
73
+    ).then(res =>
74
+      res.reduce((pre, cur, i) => {
75
+        var name = permissions[i]
76
+        pre[name] = cur
77
+        return pre
78
+      }, {}),
79
+    )
80
+  }
68 81
 }
69 82
 
70 83
 module.exports = new ReactNativePermissions()

+ 10
- 0
package.json Просмотреть файл

@@ -15,6 +15,16 @@
15 15
     "type": "git",
16 16
     "url": "https://github.com/yonahforst/react-native-permissions.git"
17 17
   },
18
+  "scripts": {
19
+    "precommit": "lint-staged",
20
+    "prettier": "prettier --write '**/*.js'"
21
+  },
22
+  "lint-staged": {
23
+    "**/*.js": [
24
+      "prettier --write",
25
+      "git add"
26
+    ]
27
+  },
18 28
   "devDependencies": {
19 29
     "husky": "^0.14.3",
20 30
     "lint-staged": "^5.0.0",