@supportworks/multi-imagepicker 8.3.6 → 8.3.8

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,4 +1,4 @@
1
- import React, { useCallback, useMemo, useRef, forwardRef, useImperativeHandle, useState } from 'react'
1
+ import React, { useCallback, useEffect, useMemo, useRef, forwardRef, useImperativeHandle, useState } from 'react'
2
2
  import {
3
3
  AppState,
4
4
  View,
@@ -14,6 +14,7 @@ import ImageResizer from '@bam.tech/react-native-image-resizer'
14
14
  import { Api } from '@supportworks/api-core'
15
15
  import { check, request, PERMISSIONS, RESULTS, openSettings } from 'react-native-permissions'
16
16
  import CameraModal from './CameraModal'
17
+ import loaderHandler from './loaderHandler'
17
18
 
18
19
  const waitForAppToBeActive = async () => {
19
20
  if (AppState.currentState === 'active') {
@@ -39,6 +40,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
39
40
  parentStyle = null, // style applied to the parent View; otherwise style prop will be forwarded to TouchableOpacity
40
41
  customButtons = [], // array of titles of custom buttons to display, pre-pended to action sheet buttons (optional)
41
42
  maxCount = 25, // max number of images that can be selected
43
+ existingCount = 0, // number of images already attached outside of this picker session
42
44
  callbackData = null, // data appended to payload and passed with callback function (optional)
43
45
  callback = null, // callback function (optional)
44
46
  children,
@@ -48,11 +50,54 @@ const MultiImagePicker = forwardRef((props, ref) => {
48
50
  const [showCameraModal, setShowCameraModal] = useState(false)
49
51
  const [pendingPickerIndex, setPendingPickerIndex] = useState(null)
50
52
  const [pendingCancelIndex, setPendingCancelIndex] = useState(null)
53
+ const [actionSheetInstanceKey, setActionSheetInstanceKey] = useState(0)
51
54
 
52
55
  const imgArrRef = useRef([]) // temp array for holding selected images to attach, before title & desc updated
53
56
  const imgDescArrRef = useRef([]) // temp array for holding descriptions of selected images, before saved to project
54
57
  const imgValidArrRef = useRef([]) // temp array for holding boolean value specifying whether each image title is valid or not
55
58
  const actionSheetRef = useRef(null)
59
+ const pendingCameraProcessTimeoutRef = useRef(null)
60
+
61
+ const resolvedMaxCount = useMemo(() => {
62
+ const parsedMaxCount = Number(maxCount)
63
+ if (!Number.isFinite(parsedMaxCount)) {
64
+ return 25
65
+ }
66
+ return Math.max(0, Math.floor(parsedMaxCount))
67
+ }, [maxCount])
68
+
69
+ const resolvedExistingCount = useMemo(() => {
70
+ const parsedExistingCount = Number(existingCount)
71
+ if (!Number.isFinite(parsedExistingCount)) {
72
+ return 0
73
+ }
74
+ return Math.max(0, Math.floor(parsedExistingCount))
75
+ }, [existingCount])
76
+
77
+ const remainingCount = useMemo(
78
+ () => Math.max(resolvedMaxCount - resolvedExistingCount, 0),
79
+ [resolvedExistingCount, resolvedMaxCount]
80
+ )
81
+
82
+ const resetActionSheet = useCallback(() => {
83
+ actionSheetRef.current = null
84
+ setActionSheetInstanceKey((prevKey) => prevKey + 1)
85
+ }, [])
86
+
87
+ const clearPendingCameraProcessTimeout = useCallback(() => {
88
+ if (pendingCameraProcessTimeoutRef.current) {
89
+ clearTimeout(pendingCameraProcessTimeoutRef.current)
90
+ pendingCameraProcessTimeoutRef.current = null
91
+ }
92
+ }, [])
93
+
94
+ const showSelectionLimitAlert = useCallback(() => {
95
+ const message = remainingCount <= 0
96
+ ? `You already have the maximum of ${resolvedMaxCount} photo(s)`
97
+ : `You may only add ${remainingCount} more photo(s)`
98
+
99
+ Alert.alert('Selection Limit', message)
100
+ }, [remainingCount, resolvedMaxCount])
56
101
 
57
102
  const showPermissionAlert = useCallback((type) => {
58
103
  const platformMessage = Platform.select({
@@ -64,7 +109,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
64
109
 
65
110
  Alert.alert(
66
111
  'Permission Required',
67
- `${platformMessage || 'Permission is required.'} You need to enable access to continue. After doing so, please restart the app and try again.`,
112
+ `${platformMessage || 'Permission is required.'} You need to enable access to continue.`,
68
113
  [
69
114
  { text: 'Cancel', style: 'cancel' },
70
115
  {
@@ -174,64 +219,91 @@ const MultiImagePicker = forwardRef((props, ref) => {
174
219
  return
175
220
  }
176
221
 
177
- for (let i = 0; i < imgArrRef.current.length; i++) {
178
- const resizedImage = await ImageResizer.createResizedImage(
179
- imgArrRef.current[i].path,
180
- 2000,
181
- 2000,
182
- 'JPEG',
183
- 80
184
- )
185
- await Api.getApi().moveLocalFile(resizedImage.path, imgArrRef.current[i].path, true)
222
+ loaderHandler.showLoader('Processing Photos...')
223
+
224
+ try {
225
+ for (let i = 0; i < imgArrRef.current.length; i++) {
226
+ const resizedImage = await ImageResizer.createResizedImage(
227
+ imgArrRef.current[i].path,
228
+ 2000,
229
+ 2000,
230
+ 'JPEG',
231
+ 80
232
+ )
233
+ await Api.getApi().moveLocalFile(resizedImage.path, imgArrRef.current[i].path, true)
234
+ }
235
+
236
+ await Promise.resolve(callback({
237
+ index,
238
+ cancelIndex,
239
+ imageArray: imgArrRef.current,
240
+ imageDescArray: imgDescArrRef.current,
241
+ imageValidArray: imgValidArrRef.current,
242
+ imageSource,
243
+ callbackData
244
+ }))
245
+ } finally {
246
+ loaderHandler.hideLoader()
186
247
  }
248
+ }, [callback, callbackData])
249
+
250
+ const processCameraModalImages = useCallback((images, pickerIndex, cancelIndex) => {
251
+ imgArrRef.current = []
252
+ imgDescArrRef.current = []
253
+ imgValidArrRef.current = []
254
+
255
+ images.forEach((img) => {
256
+ const imageData = {
257
+ path: img.imageURI,
258
+ mime: 'image/jpeg',
259
+ width: 2000,
260
+ height: 2000
261
+ }
262
+
263
+ if (img.depthMapURI) {
264
+ imageData.depthMapUri = img.depthMapURI
265
+ }
187
266
 
188
- callback({
189
- index,
190
- cancelIndex,
191
- imageArray: imgArrRef.current,
192
- imageDescArray: imgDescArrRef.current,
193
- imageValidArray: imgValidArrRef.current,
194
- imageSource,
195
- callbackData
267
+ imgArrRef.current.push(imageData)
268
+ imgDescArrRef.current.push('')
269
+ imgValidArrRef.current.push(true)
196
270
  })
197
- }, [callback, callbackData])
271
+
272
+ pickerDone(pickerIndex, cancelIndex, 'taken')
273
+ }, [pickerDone])
198
274
 
199
275
  const handleCameraModalDone = useCallback(async (images = []) => {
200
276
  // Handle images returned from CameraModal
201
277
  console.log('SWSI Camera modal done, images:', images)
202
278
 
279
+ const pickerIndex = pendingPickerIndex
280
+ const cancelIndex = pendingCancelIndex
281
+
282
+ clearPendingCameraProcessTimeout()
203
283
  setShowCameraModal(false)
284
+ resetActionSheet()
204
285
 
205
286
  if (images && images.length > 0) {
206
- // Convert CameraModal format to ImagePicker format
207
- images.forEach((img) => {
208
- const imageData = {
209
- path: img.imageURI,
210
- mime: 'image/jpeg',
211
- width: 2000,
212
- height: 2000
213
- }
214
-
215
- // Store depth map URI if available (can be used by calling code)
216
- if (img.depthMapURI) {
217
- imageData.depthMapUri = img.depthMapURI
218
- }
219
-
220
- imgArrRef.current.push(imageData)
221
- imgDescArrRef.current.push('')
222
- imgValidArrRef.current.push(true)
223
- })
224
-
225
- if (pendingPickerIndex !== null && pendingCancelIndex !== null) {
226
- const imageSource = 'taken'
227
- pickerDone(pendingPickerIndex, pendingCancelIndex, imageSource)
287
+ if (pickerIndex !== null && cancelIndex !== null) {
288
+ pendingCameraProcessTimeoutRef.current = setTimeout(() => {
289
+ pendingCameraProcessTimeoutRef.current = null
290
+ processCameraModalImages(images, pickerIndex, cancelIndex)
291
+ }, 350)
292
+ } else {
293
+ console.log('SWSI Camera modal missing picker indices; skipping captured image handoff')
228
294
  }
229
295
  }
230
296
 
231
297
  // Reset pending indices
232
298
  setPendingPickerIndex(null)
233
299
  setPendingCancelIndex(null)
234
- }, [pendingCancelIndex, pendingPickerIndex, pickerDone])
300
+ }, [clearPendingCameraProcessTimeout, pendingCancelIndex, pendingPickerIndex, processCameraModalImages, resetActionSheet])
301
+
302
+ useEffect(() => {
303
+ return () => {
304
+ clearPendingCameraProcessTimeout()
305
+ }
306
+ }, [clearPendingCameraProcessTimeout])
235
307
 
236
308
  const takeOnePicture = useCallback(async (
237
309
  index,
@@ -240,7 +312,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
240
312
  depth,
241
313
  done
242
314
  ) => {
243
- if (depth > maxCount) {
315
+ if (depth > remainingCount) {
244
316
  done()
245
317
  return
246
318
  }
@@ -262,7 +334,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
262
334
  } catch (e) {
263
335
  done()
264
336
  }
265
- }, [maxCount, requestCameraPermission, showPermissionAlert])
337
+ }, [remainingCount, requestCameraPermission, showPermissionAlert])
266
338
 
267
339
  const usePicker = useCallback(async (index, cancelIndex) => {
268
340
  // 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.
@@ -273,7 +345,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
273
345
 
274
346
  const options = {
275
347
  multiple: true,
276
- maxFiles: maxCount, // ios only
348
+ maxFiles: remainingCount, // ios only
277
349
  cropping: false,
278
350
  mediaType: 'photo'
279
351
  }
@@ -290,6 +362,11 @@ const MultiImagePicker = forwardRef((props, ref) => {
290
362
  case takePhotoIndex:
291
363
  console.log('User pressed take photo')
292
364
 
365
+ if (remainingCount <= 0) {
366
+ showSelectionLimitAlert()
367
+ break
368
+ }
369
+
293
370
  // Use CameraModal on iOS 26+, native camera on Android
294
371
  if (Platform.OS === 'ios' && parseInt(Platform.Version,10) >= 26) {
295
372
  const hasPermission = await requestCameraPermission()
@@ -300,6 +377,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
300
377
  await waitForAppToBeActive()
301
378
  setPendingPickerIndex(index)
302
379
  setPendingCancelIndex(cancelIndex)
380
+ resetActionSheet()
303
381
  setShowCameraModal(true)
304
382
  } else {
305
383
  // Fall back to native camera (Android)
@@ -314,12 +392,17 @@ const MultiImagePicker = forwardRef((props, ref) => {
314
392
  }
315
393
  break
316
394
  case chooseLibIndex:
395
+ if (remainingCount <= 0) {
396
+ showSelectionLimitAlert()
397
+ break
398
+ }
399
+
317
400
  checkAndOpenPicker(options, () =>
318
401
  ImagePicker.openPicker(options)
319
402
  .then((imagesOrImage) => {
320
403
  const images = Array.isArray(imagesOrImage) ? imagesOrImage : [imagesOrImage]
321
- if (images.length > maxCount) {
322
- Alert.alert('Selection Limit', `You may only select a max of ${maxCount} photo(s)`)
404
+ if (images.length > remainingCount) {
405
+ showSelectionLimitAlert()
323
406
  } else {
324
407
  imgArrRef.current = images
325
408
  imgDescArrRef.current = Array(images.length).fill('')
@@ -340,7 +423,16 @@ const MultiImagePicker = forwardRef((props, ref) => {
340
423
  console.log('----usePicker User pressed custom button')
341
424
  pickerDone(index, cancelIndex)
342
425
  }
343
- }, [checkAndOpenPicker, maxCount, pickerDone, requestCameraPermission, showPermissionAlert, takeOnePicture])
426
+ }, [
427
+ checkAndOpenPicker,
428
+ pickerDone,
429
+ remainingCount,
430
+ requestCameraPermission,
431
+ resetActionSheet,
432
+ showPermissionAlert,
433
+ showSelectionLimitAlert,
434
+ takeOnePicture
435
+ ])
344
436
 
345
437
  const showActionSheet = useCallback(() => {
346
438
  if (actionSheetRef.current && typeof actionSheetRef.current.show === 'function') {
@@ -361,6 +453,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
361
453
  return (
362
454
  <View style={parentStyle}>
363
455
  <ActionSheet
456
+ key={`multi-image-picker-action-sheet-${actionSheetInstanceKey}`}
364
457
  ref={(node) => {
365
458
  actionSheetRef.current = node
366
459
  }}
@@ -382,7 +475,7 @@ const MultiImagePicker = forwardRef((props, ref) => {
382
475
  >
383
476
  <CameraModal
384
477
  onDone={handleCameraModalDone}
385
- limit={maxCount}
478
+ limit={remainingCount}
386
479
  onCancel={() => handleCameraModalDone([])}
387
480
  />
388
481
  </Modal>