@supportworks/multi-imagepicker 6.0.0 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,285 +1,305 @@
1
- import * as React from 'react';
2
- import { View, TouchableOpacity, Alert, Platform, Linking } from 'react-native';
3
- import ActionSheet from '@alessiocancian/react-native-actionsheet';
4
- import ImagePicker from 'react-native-image-crop-picker';
5
- import ImageResizer from '@bam.tech/react-native-image-resizer';
6
- import { Api } from '@supportworks/api-core';
7
- import { check, request, PERMISSIONS, RESULTS, openSettings } from 'react-native-permissions';
8
-
9
- class MultiImagePicker extends React.Component {
10
- static defaultProps = {
11
- useCamera: 'Take Photo...',
12
- useLibrary: 'Choose from Library...',
13
- title: 'Add Photo(s)',
14
- parentStyle: null, //style to be applied to the parent (view) in the render function. Otherwise, a 'style' prop is applied to the TouchableOpacity, which is a child of View.
15
- customButtons: [], //array of titles of custom buttons to display, pre-pended to action sheet buttons (optional)
16
- maxCount: 25, //max number of images that can be selected
17
- callbackData: null, //data appended to payload and passed with callback function (optional)
18
- callback: null //callback function (optional)
19
- };
20
-
21
- constructor(props) {
22
- super(props);
23
- this.imgArr = []; //temp array for holding selected images to attach, before title & desc updated
24
- this.imgDescArr = []; //temp array for holding descriptions of selected images, before saved to project
25
- this.imgValidArr = []; //temp array for holding boolean value specifying whether each image title is valid or not
26
- this.pickerDone = this.pickerDone.bind(this);
27
- this.showActionSheet = this.showActionSheet.bind(this);
28
- this.takeOnePicture = this.takeOnePicture.bind(this);
29
- }
30
-
31
- async checkAndRequestSinglePermission(permission) {
32
- const result = await check(permission);
33
- switch (result) {
34
- case RESULTS.GRANTED:
35
- return true;
36
- case RESULTS.DENIED:
37
- //if request is blocked, show persmission
38
- const requestResponse = await request(permission);
39
- if (requestResponse === RESULTS.BLOCKED) {
40
- this.showPermissionAlert('Storage');
41
- return false;
42
- }
43
- return requestResponse === RESULTS.GRANTED;
44
- case RESULTS.BLOCKED:
45
- this.showPermissionAlert('Storage');
46
- return false;
47
- default:
48
- return false;
1
+ import React, { useCallback, useMemo, useRef, forwardRef, useImperativeHandle } from 'react'
2
+ import {
3
+ View,
4
+ TouchableOpacity,
5
+ Alert,
6
+ Platform,
7
+ Linking
8
+ } from 'react-native'
9
+ import ActionSheet from '@alessiocancian/react-native-actionsheet'
10
+ import ImagePicker from 'react-native-image-crop-picker'
11
+ import ImageResizer from '@bam.tech/react-native-image-resizer'
12
+ import { Api } from '@supportworks/api-core'
13
+ import { check, request, PERMISSIONS, RESULTS, openSettings } from 'react-native-permissions'
14
+
15
+ const MultiImagePicker = forwardRef((props, ref) => {
16
+ // Destructure known props and collect any remaining props to forward to the TouchableOpacity.
17
+ const {
18
+ useCamera = 'Take Photo...',
19
+ useLibrary = 'Choose from Library...',
20
+ title = 'Add Photo(s)',
21
+ parentStyle = null, // style applied to the parent View; otherwise style prop will be forwarded to TouchableOpacity
22
+ customButtons = [], // array of titles of custom buttons to display, pre-pended to action sheet buttons (optional)
23
+ maxCount = 25, // max number of images that can be selected
24
+ callbackData = null, // data appended to payload and passed with callback function (optional)
25
+ callback = null, // callback function (optional)
26
+ children,
27
+ ...touchableProps // any other props passed into MultiImagePicker will be spread onto the TouchableOpacity below
28
+ } = props
29
+
30
+ const imgArrRef = useRef([]) // temp array for holding selected images to attach, before title & desc updated
31
+ const imgDescArrRef = useRef([]) // temp array for holding descriptions of selected images, before saved to project
32
+ const imgValidArrRef = useRef([]) // temp array for holding boolean value specifying whether each image title is valid or not
33
+ const actionSheetRef = useRef(null)
34
+
35
+ const showPermissionAlert = useCallback((type) => {
36
+ const platformMessage = Platform.select({
37
+ ios:
38
+ 'Photo library access is required. Please go to Settings > Privacy > Photos and grant full access for this app.',
39
+ android:
40
+ `${type} access is required to select photos. Please go to Settings > Apps > THIS_APP > Permissions and enable access.`
41
+ })
42
+
43
+ Alert.alert(
44
+ 'Permission Required',
45
+ `${platformMessage || 'Permission is required.'} You need to enable access to continue.`,
46
+ [
47
+ { text: 'Cancel', style: 'cancel' },
48
+ {
49
+ text: 'Open Settings',
50
+ onPress: () => openSettings().catch(() => Linking.openURL('app-settings:'))
49
51
  }
50
- }
51
-
52
- async requestPermissions(permission) {
53
- if (Array.isArray(permission)) {
54
- // Handle multiple permissions
55
- const results = await Promise.all(permission.map((p) => this.checkAndRequestSinglePermission(p)));
56
- return results.every((result) => result); // All permissions must be granted
57
- } else {
58
- // Handle single permission
59
- return await this.checkAndRequestSinglePermission(permission);
52
+ ]
53
+ )
54
+ }, [])
55
+
56
+ const checkAndRequestSinglePermission = useCallback(async (permission) => {
57
+ const result = await check(permission)
58
+ switch (result) {
59
+ case RESULTS.GRANTED:
60
+ return true
61
+ case RESULTS.DENIED: {
62
+ // if request is blocked, show persmission
63
+ const requestResponse = await request(permission)
64
+ if (requestResponse === RESULTS.BLOCKED) {
65
+ showPermissionAlert('Storage')
66
+ return false
60
67
  }
68
+ return requestResponse === RESULTS.GRANTED
69
+ }
70
+ case RESULTS.BLOCKED:
71
+ showPermissionAlert('Storage')
72
+ return false
73
+ default:
74
+ return false
61
75
  }
76
+ }, [showPermissionAlert])
62
77
 
63
-
64
- async requestCameraPermission() {
65
- const permission = Platform.select({
66
- ios: PERMISSIONS.IOS.CAMERA,
67
- android: PERMISSIONS.ANDROID.CAMERA,
68
- });
69
-
70
- const result = await check(permission);
71
-
72
- switch (result) {
73
- case RESULTS.GRANTED:
74
- return true;
75
- case RESULTS.DENIED:
76
- const requestResult = await request(permission);
77
- return requestResult === RESULTS.GRANTED;
78
- case RESULTS.BLOCKED:
79
- this.showPermissionAlert('Camera');
80
- return false;
81
- default:
82
- return false;
83
- }
78
+ const requestPermissions = useCallback(async (permission) => {
79
+ if (Array.isArray(permission)) {
80
+ // Handle multiple permissions
81
+ const results = await Promise.all(permission.map((p) => checkAndRequestSinglePermission(p)))
82
+ return results.every((result) => result)
84
83
  }
85
-
86
- showPermissionAlert(type) {
87
-
88
- const platformMessage = Platform.select({
89
- ios:
90
- "Photo library access is required. Please go to Settings > Privacy > Photos and grant full access for this app.",
91
- android:
92
- `${type} access is required to select photos. Please go to Settings > Apps > THIS_APP > Permissions and enable access.`,
93
- });
94
-
95
- Alert.alert(
96
- 'Permission Required',
97
- `${platformMessage} You need to enable access to continue.`,
98
- [
99
- { text: 'Cancel', style: 'cancel' },
100
- {
101
- text: 'Open Settings',
102
- onPress: () => openSettings().catch(() => Linking.openURL('app-settings:'))
103
- },
104
- ]
105
- );
84
+ // Handle single permission
85
+ return checkAndRequestSinglePermission(permission)
86
+ }, [checkAndRequestSinglePermission])
87
+
88
+ const requestCameraPermission = useCallback(async () => {
89
+ const permission = Platform.select({
90
+ ios: PERMISSIONS.IOS.CAMERA,
91
+ android: PERMISSIONS.ANDROID.CAMERA
92
+ })
93
+
94
+ if (!permission) {
95
+ return true
106
96
  }
107
97
 
108
- async checkAndOpenPicker(options, action) {
109
-
110
- let permission;
111
-
112
- if (Platform.OS === 'android') {
113
- // Check Android version
114
- const androidVersion = parseInt(Platform.Version, 10);
115
- if (androidVersion >= 33) {
116
- // Android 13+ requires specific media permissions -
117
- // UPDATE 9/24/25: these are no longer needed and in fact Google Play Store prohibits use of them in our case
118
- /*permission = [
119
- PERMISSIONS.ANDROID.READ_MEDIA_IMAGES,
120
- PERMISSIONS.ANDROID.READ_MEDIA_VIDEO,
121
- ];*/
122
- } else {
123
- // Use legacy storage permission for Android < 33
124
- permission = PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE;
125
- }
126
- } else {
127
- // iOS permission
128
- permission = PERMISSIONS.IOS.PHOTO_LIBRARY;
129
- }
130
-
131
- //check if permission is a string or an array of strings, if its an array do a for each and check each permission
132
- const hasPermission = permission ? await this.requestPermissions(permission) : true;
133
- if (hasPermission) {
134
- action(options); // Proceed if permission granted
135
- } else {
136
- this.showPermissionAlert('Both Storage and the Photos and Videos');
137
- }
98
+ const result = await check(permission)
99
+
100
+ switch (result) {
101
+ case RESULTS.GRANTED:
102
+ return true
103
+ case RESULTS.DENIED: {
104
+ const requestResult = await request(permission)
105
+ return requestResult === RESULTS.GRANTED
106
+ }
107
+ case RESULTS.BLOCKED:
108
+ showPermissionAlert('Camera')
109
+ return false
110
+ default:
111
+ return false
138
112
  }
139
-
140
- async pickerDone(index, cancelIndex, imageSource = null) {
141
- //user is done using the picker to select images. index: index of button that was clicked.
142
- // cancelIndex: index of the cancel button, so we know which button was clicked, since we know cancel is the last index available.
143
- // imageSource: "taken" if image was taken from device now, "library" if image(s) were selected from library
144
-
145
- const { callback, callbackData } = this.props;
146
- if (callback) {
147
- for (let i = 0; i < this.imgArr.length; i++) {
148
- const resizedImage = await ImageResizer.createResizedImage(
149
- this.imgArr[i].path,
150
- 2000,
151
- 2000,
152
- 'JPEG',
153
- 80
154
- );
155
- await Api.getApi().moveLocalFile(resizedImage.path, this.imgArr[i].path, true);
156
- }
157
- callback({
158
- index,
159
- cancelIndex,
160
- imageArray: this.imgArr,
161
- imageDescArray: this.imgDescArr,
162
- imageValidArray: this.imgValidArr,
163
- imageSource,
164
- callbackData,
165
- });
166
- }
113
+ }, [showPermissionAlert])
114
+
115
+ const checkAndOpenPicker = useCallback(async (options, action) => {
116
+ let permission
117
+
118
+ if (Platform.OS === 'android') {
119
+ // Check Android version
120
+ const androidVersion = parseInt(String(Platform.Version), 10)
121
+ if (androidVersion >= 33) {
122
+ // Android 13+ requires specific media permissions -
123
+ // UPDATE 9/24/25: these are no longer needed and in fact Google Play Store prohibits use of them in our case
124
+ /* permission = [
125
+ PERMISSIONS.ANDROID.READ_MEDIA_IMAGES,
126
+ PERMISSIONS.ANDROID.READ_MEDIA_VIDEO,
127
+ ]; */
128
+ permission = undefined
129
+ } else {
130
+ // Use legacy storage permission for Android < 33
131
+ permission = PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE
132
+ }
133
+ } else {
134
+ // iOS permission
135
+ permission = PERMISSIONS.IOS.PHOTO_LIBRARY
167
136
  }
168
137
 
169
- async takeOnePicture(index, cancelIndex, options, depth, callback) {
170
- if (depth > this.props.maxCount) {
171
- callback();
172
- return;
173
- }
174
-
175
- const hasPermission = await this.requestCameraPermission();
176
- if (!hasPermission) {
177
- this.showPermissionAlert('Camera');
178
- callback();
179
- return;
180
- }
181
-
182
- try {
183
- const image = await ImagePicker.openCamera(options);
184
- console.log("SWSI take photo, image: " + JSON.stringify(image));
185
-
186
- this.imgArr.push(image);
187
- this.imgDescArr.push('');
188
- this.imgValidArr.push(true);
189
- await this.takeOnePicture(index, cancelIndex, options, depth + 1, callback);
190
- } catch (e) {
191
- callback();
192
- }
138
+ const hasPermission = permission ? await requestPermissions(permission) : true
139
+ if (hasPermission) {
140
+ action(options) // Proceed if permission granted
141
+ } else {
142
+ showPermissionAlert('Both Storage and the Photos and Videos')
193
143
  }
144
+ }, [requestPermissions, showPermissionAlert])
194
145
 
195
- usePicker(index, cancelIndex) {
196
- //index: index of ActionSheet. Depends on whether custom buttons added. Last 3 are fixed (Take Photo, Choose from Library, Cancel). Anything before that is custom button.
197
- // Custom buttons can be sent using customButtons prop.
198
- //results - sets cRef.imgArr to an array of image info that the picker library provided
199
- // sets cRef.imgDescArray to an array of the image descriptions
200
- // initializes cRef.imgValidArr to an array of booleans (all true) for all selected images, to be used/updated by calling code as needed
201
-
202
- const options = {
203
- multiple: true,
204
- maxFiles: this.props.maxCount, //ios only
205
- cropping: false,
206
- mediaType: 'photo',
207
- };
208
- this.imgArr = []; //clear selected images
209
- this.imgDescArr = []; //clear descriptions for selected images
210
- this.imgValidArr = []; //clear valid flags for selected images
211
-
146
+ const pickerDone = useCallback(async (index, cancelIndex, imageSource = null) => {
147
+ // user is done using the picker to select images. index: index of button that was clicked.
148
+ // cancelIndex: index of the cancel button, so we know which button was clicked, since we know cancel is the last index available.
149
+ // imageSource: "taken" if image was taken from device now, "library" if image(s) were selected from library
212
150
 
213
- const takePhotoIndex = cancelIndex - 2;
214
- const chooseLibIndex = cancelIndex - 1;
215
- let imageSource = null;
216
-
217
- switch (index) {
218
- case takePhotoIndex:
219
- console.log('User pressed take photo');
220
- this.checkAndOpenPicker(options, () =>
221
- this.takeOnePicture(index, cancelIndex, options, 1, () => {
222
- if (this.imgArr.length > 0) {
223
- imageSource = 'taken';
224
- this.pickerDone(index, cancelIndex, imageSource);
225
- }
226
- })
227
- );
228
- break;
229
-
230
- case chooseLibIndex:
231
- this.checkAndOpenPicker(options, () =>
232
- ImagePicker.openPicker(options)
233
- .then((images) => {
234
- if (images.length > this.props.maxCount) {
235
- alert(`You may only select a max of ${this.props.maxCount} photo(s)`);
236
- } else {
237
- this.imgArr = images;
238
- this.imgDescArr = Array(images.length).fill('');
239
- this.imgValidArr = Array(images.length).fill(true);
240
- imageSource = 'library';
241
- this.pickerDone(index, cancelIndex, imageSource);
242
- }
243
- })
244
- .catch((err) => {
245
- console.log(`----usePicker Image Picker Error: ${err.message}`);
246
- })
247
- );
248
- break;
151
+ if (!callback) {
152
+ return
153
+ }
249
154
 
250
- case cancelIndex:
251
- console.log('----usePicker User pressed cancel');
252
- break;
155
+ for (let i = 0; i < imgArrRef.current.length; i++) {
156
+ const resizedImage = await ImageResizer.createResizedImage(
157
+ imgArrRef.current[i].path,
158
+ 2000,
159
+ 2000,
160
+ 'JPEG',
161
+ 80
162
+ )
163
+ await Api.getApi().moveLocalFile(resizedImage.path, imgArrRef.current[i].path, true)
164
+ }
253
165
 
254
- default:
255
- console.log('----usePicker User pressed custom button');
256
- this.pickerDone(index, cancelIndex);
257
- }
166
+ callback({
167
+ index,
168
+ cancelIndex,
169
+ imageArray: imgArrRef.current,
170
+ imageDescArray: imgDescArrRef.current,
171
+ imageValidArray: imgValidArrRef.current,
172
+ imageSource,
173
+ callbackData
174
+ })
175
+ }, [callback, callbackData])
176
+
177
+ const takeOnePicture = useCallback(async (
178
+ index,
179
+ cancelIndex,
180
+ options,
181
+ depth,
182
+ done
183
+ ) => {
184
+ if (depth > maxCount) {
185
+ done()
186
+ return
258
187
  }
259
188
 
260
- showActionSheet = () => {
261
- this.ActionSheet.show();
262
- };
189
+ const hasPermission = await requestCameraPermission()
190
+ if (!hasPermission) {
191
+ showPermissionAlert('Camera')
192
+ done()
193
+ return
194
+ }
263
195
 
264
- render() {
265
- const buttonArr = [...this.props.customButtons, this.props.useCamera, this.props.useLibrary, 'Cancel'];
266
- const cancelIndex = buttonArr.length - 1;
196
+ try {
197
+ const image = await ImagePicker.openCamera(options)
198
+ console.log('SWSI take photo, image: ' + JSON.stringify(image))
199
+ imgArrRef.current.push(image)
200
+ imgDescArrRef.current.push('')
201
+ imgValidArrRef.current.push(true)
202
+ await takeOnePicture(index, cancelIndex, options, depth + 1, done)
203
+ } catch (e) {
204
+ done()
205
+ }
206
+ }, [maxCount, requestCameraPermission, showPermissionAlert])
207
+
208
+ const usePicker = useCallback((index, cancelIndex) => {
209
+ // index: index of ActionSheet. Depends on whether custom buttons added. Last 3 are fixed (Take Photo, Choose from Library, Cancel). Anything before that is custom button.
210
+ // Custom buttons can be sent using customButtons prop.
211
+ // results - sets cRef.imgArr to an array of image info that the picker library provided
212
+ // sets cRef.imgDescArray to an array of the image descriptions
213
+ // initializes cRef.imgValidArr to an array of booleans (all true) for all selected images, to be used/updated by calling code as needed
214
+
215
+ const options = {
216
+ multiple: true,
217
+ maxFiles: maxCount, // ios only
218
+ cropping: false,
219
+ mediaType: 'photo'
220
+ }
267
221
 
268
- return (
269
- <View style={this.props.parentStyle}>
270
- <ActionSheet
271
- ref={(o) => (this.ActionSheet = o)}
272
- title={this.props.title}
273
- options={buttonArr}
274
- cancelButtonIndex={cancelIndex}
275
- onPress={(index) => this.usePicker(index, cancelIndex)}
276
- />
277
- <TouchableOpacity {...this.props} onPress={this.showActionSheet}>
278
- {this.props.children}
279
- </TouchableOpacity>
280
- </View>
281
- );
222
+ imgArrRef.current = [] // clear selected images
223
+ imgDescArrRef.current = [] // clear descriptions for selected images
224
+ imgValidArrRef.current = [] // clear valid flags for selected images
225
+
226
+ const takePhotoIndex = cancelIndex - 2
227
+ const chooseLibIndex = cancelIndex - 1
228
+ let imageSource = null
229
+
230
+ switch (index) {
231
+ case takePhotoIndex:
232
+ console.log('User pressed take photo')
233
+ checkAndOpenPicker(options, () =>
234
+ takeOnePicture(index, cancelIndex, options, 1, () => {
235
+ if (imgArrRef.current.length > 0) {
236
+ imageSource = 'taken'
237
+ pickerDone(index, cancelIndex, imageSource)
238
+ }
239
+ })
240
+ )
241
+ break
242
+ case chooseLibIndex:
243
+ checkAndOpenPicker(options, () =>
244
+ ImagePicker.openPicker(options)
245
+ .then((imagesOrImage) => {
246
+ const images = Array.isArray(imagesOrImage) ? imagesOrImage : [imagesOrImage]
247
+ if (images.length > maxCount) {
248
+ Alert.alert('Selection Limit', `You may only select a max of ${maxCount} photo(s)`)
249
+ } else {
250
+ imgArrRef.current = images
251
+ imgDescArrRef.current = Array(images.length).fill('')
252
+ imgValidArrRef.current = Array(images.length).fill(true)
253
+ imageSource = 'library'
254
+ pickerDone(index, cancelIndex, imageSource)
255
+ }
256
+ })
257
+ .catch((err) => {
258
+ console.log(`----usePicker Image Picker Error: ${err.message}`)
259
+ })
260
+ )
261
+ break
262
+ case cancelIndex:
263
+ console.log('----usePicker User pressed cancel')
264
+ break
265
+ default:
266
+ console.log('----usePicker User pressed custom button')
267
+ pickerDone(index, cancelIndex)
282
268
  }
283
- }
269
+ }, [checkAndOpenPicker, maxCount, pickerDone, takeOnePicture])
284
270
 
285
- export default MultiImagePicker;
271
+ const showActionSheet = useCallback(() => {
272
+ if (actionSheetRef.current && typeof actionSheetRef.current.show === 'function') {
273
+ actionSheetRef.current.show()
274
+ }
275
+ }, [])
276
+
277
+ useImperativeHandle(ref, () => ({
278
+ showActionSheet
279
+ }), [showActionSheet])
280
+
281
+ const buttonArr = useMemo(
282
+ () => [...customButtons, useCamera, useLibrary, 'Cancel'],
283
+ [customButtons, useCamera, useLibrary]
284
+ )
285
+ const cancelIndex = buttonArr.length - 1
286
+
287
+ return (
288
+ <View style={parentStyle}>
289
+ <ActionSheet
290
+ ref={(node) => {
291
+ actionSheetRef.current = node
292
+ }}
293
+ title={title}
294
+ options={buttonArr}
295
+ cancelButtonIndex={cancelIndex}
296
+ onPress={(buttonIndex) => usePicker(buttonIndex, cancelIndex)}
297
+ />
298
+ <TouchableOpacity {...touchableProps} onPress={showActionSheet}>
299
+ {children}
300
+ </TouchableOpacity>
301
+ </View>
302
+ )
303
+ })
304
+
305
+ export default MultiImagePicker