@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,337 +1,506 @@
1
- import * as React from 'react';
1
+ import React, { useCallback, useEffect, useState, useRef, forwardRef, useImperativeHandle } from 'react'
2
2
  import {
3
- Text,
4
- View,
5
- Modal,
6
- SafeAreaView,
7
- TouchableOpacity,
8
- StyleSheet, ScrollView, KeyboardAvoidingView, Platform, PermissionsAndroid
9
- } from 'react-native';
10
- import {Icons} from "@supportworks/icon-library";
11
- import loaderHandler from './loaderHandler';
12
- import MultiImagePicker from "./MultiImagePicker";
13
- import SelectedImages from "./SelectedImages";
14
- import AppStyler, {colors, stdStyles} from "@supportworks/app-styler";
15
- import {LoadingOverlay} from '@supportworks/navbars';
16
- import {CheckBox} from "@supportworks/core-controls";
17
- import {CameraRoll} from "@react-native-camera-roll/camera-roll";
18
- import {Api} from '@supportworks/api-core';
19
- import {Analytics} from '@supportworks/analytics';
20
-
21
- class AddImages extends React.Component
22
- {
23
- static defaultProps = {
24
- parentStyle: null, //style passed to MultiImagePicker
25
- prospectInst: null, //optional prospect class instance for desired prospect (project/appt) that is passed back to props.addPicture
26
- addPicture: null, //optional function that adds one picture to the prospect (uses default if none specified)
27
- //maxCount: null, //max number of images that can be selected. Passed to MultiImagePicker. If not commented out, causes crash, so leave it this way.
28
- callback: null, //function to call after images added
29
- hitSlop: null, //hitSlop passed to MultiImagePicker
30
- allowEdit: true, //whether or not to allow user to edit file names and add commehts
31
- annotationAllowed: false
32
- };
33
-
34
- constructor (props)
35
- {
36
- super(props);
37
- this.state = {
38
- showAttaching: false,
39
- showAdd: false,
40
- allImageDataValid: true,
41
- showDescription: false,
42
- saveToDevice: true //default to true in case props.allowEdit is false, so it saves to camera roll even if the checkbox not displayed to give them the option to disable saving to camera roll
43
- };
44
-
45
- this._mounted = false;
46
- this.onImageSelect = this.onImageSelect.bind(this);
47
- this.setAllImageDataValid = this.setAllImageDataValid.bind(this);
48
- this.onAttach = this.onAttach.bind(this);
49
- this.triggerAction = this.triggerAction.bind(this);
50
- this.imgArr = []; //temp array for holding selected images to attach, before title & desc updated
51
- this.imgDescArr = []; //temp array for holding descriptions of selected images, before saved to project
52
- this.imgValidArr = []; //temp array for holding boolean value specifying whether each image title is valid or not
53
- this.imgSource = null; //temp value designating picker type used, if image was "taken" from device now, or image(s) chosen from "library"
54
- }
3
+ View,
4
+ Modal,
5
+ SafeAreaView,
6
+ StyleSheet, ScrollView, KeyboardAvoidingView, Platform, PermissionsAndroid, Alert
7
+ } from 'react-native'
8
+ import Moment from 'moment'
9
+ import { Icons } from '@supportworks/icon-library'
10
+ import loaderHandler from './loaderHandler'
11
+ import MultiImagePicker from './MultiImagePicker'
12
+ import SelectedImages from './SelectedImages'
13
+ import { colors } from '@supportworks/app-styler'
14
+ import { LoadingOverlay } from '@supportworks/navbars'
15
+ import { CheckBox, AppBarH8, CommonButton, ListItem } from '@supportworks/core-controls'
16
+ import { CameraRoll } from '@react-native-camera-roll/camera-roll'
17
+ import { Api } from '@supportworks/api-core'
18
+ import { Analytics } from '@supportworks/analytics'
19
+ import AsyncStorage from '@react-native-async-storage/async-storage'
20
+ import UploadWarningModal from './UploadWarningModal'
55
21
 
56
- componentDidMount() {
57
- this._mounted = true;
58
- }
59
- componentWillUnmount() {
60
- this._mounted = false;
61
- }
22
+ const AddImages = forwardRef((
23
+ {
24
+ parentStyle = null, // style passed to MultiImagePicker
25
+ prospectInst = null, // optional prospect class instance for desired prospect (project/appt) that is passed back to addPicture
26
+ addPicture = null, // optional function that adds one picture to the prospect (uses default if none specified)
27
+ callback = null, // function to call after images added
28
+ hitSlop = null, // hitSlop passed to MultiImagePicker
29
+ allowEdit = true, // whether to allow user to edit file names and descriptions
30
+ annotationAllowed = false, // whether to allow annotations on images
31
+ showToCustomerAllowed = false, // whether to allow "show to customer" option
32
+ maxCount, // = null, //max number of images that can be selected. Passed to MultiImagePicker. If null default not commented out, causes crash, so leave it this way.
33
+ children
34
+ }, ref) => {
35
+ const [showAttaching, setShowAttaching] = useState(false)
36
+ const [showAdd, setShowAdd] = useState(false)
37
+ const [showInfoDialog, setShowInfoDialog] = useState(false)
38
+ const [allImageDataValid, setAllImageDataValid] = useState(true)
39
+ const [showToCust, setShowToCust] = useState(false)
40
+ const [saveToDevice, setSaveToDevice] = useState(true) // default to true in case props.allowEdit is false, so it saves to camera roll even if the checkbox not displayed to give them the option to disable saving to camera roll
41
+ const [allowSaveToDevice, setAllowSaveToDevice] = useState(false)
42
+ // Single source of truth for selected images
43
+ const [items, setItems] = useState([])
62
44
 
63
- triggerAction() {
64
- this.Picker.showActionSheet();
65
- }
45
+ // Mirror ref for imperative/async access without triggering renders
46
+ const itemsRef = useRef([]) // temp array for holding selected images to attach
47
+ const imgSourceRef = useRef(null) // temp value designating picker type used, if image was "taken" from device now, or image(s) chosen from "library"
48
+ const pickerRef = useRef(null)
49
+ const isMountedRef = useRef(true)
50
+ const STORAGE_KEY_SKIP_DIALOG = '@MIP_UploadWarningsModal_Skip'
51
+ const allowSaveToDevicePlatform = Platform.OS !== 'android' // TODO: set to true when Android support is added
66
52
 
67
- async hasAndroidWritePermission() {
68
- try {
69
- const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE;
53
+ useEffect(() => {
54
+ return () => {
55
+ isMountedRef.current = false
56
+ }
57
+ }, [])
70
58
 
71
- const hasPermission = await PermissionsAndroid.check(permission);
72
- if (hasPermission) {
73
- console.log("Has permission: " + permission);
74
- return true;
75
- }
59
+ const setPickerRef = useCallback((node) => {
60
+ pickerRef.current = node
61
+ }, [])
76
62
 
77
- console.log("Permission request: " + permission);
78
- const status = await PermissionsAndroid.request(permission);
79
- console.log("Permission request status: " + status);
80
- return status === 'granted';
81
- } catch (err) {
82
- console.log(err);
83
- }
63
+ const triggerAction = useCallback(() => {
64
+ if (pickerRef.current && typeof pickerRef.current.showActionSheet === 'function') {
65
+ pickerRef.current.showActionSheet()
84
66
  }
67
+ }, [])
85
68
 
86
- async addPicturesToProject() {
87
- //go through all images selected and add to project
69
+ useImperativeHandle(ref, () => ({
70
+ triggerAction
71
+ }), [triggerAction])
88
72
 
89
- try {
73
+ const hasAndroidWritePermission = useCallback(async () => {
74
+ try {
75
+ const permission = PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
90
76
 
91
- loaderHandler.showLoader("Saving Pictures...");
92
- let cRef = this;
93
-
94
- //save image to device library if it was just taken, if they selected to save to device, or didn't have the option to select that (allowEdit=false)
95
- // NOTE: only saving photos to camera roll for iOS currently since the cameraroll lib doesn't
96
- // support it for android (with targetSDKVersion=30) yet, as of v4.1.2
97
- if (Platform.OS !== "android") { //TODO: WILL REMOVE this line once it's working for android
98
- if (cRef.imgSource === "taken" && cRef.state.saveToDevice) {
99
- if (Platform.OS === "android" && !(await cRef.hasAndroidWritePermission())) {
100
- console.log("Skip saving picture to android camera roll");
101
- } else {
102
- CameraRoll.save(cRef.imgArr[0].path)
103
- .then(url => {
104
- console.log("CameraRoll.save success")
105
- })
106
- .catch(err => {
107
- console.log("CameraRoll.save failed, Error: " + err)
108
- });
109
- }
110
- }
111
- }
77
+ const hasPermission = await PermissionsAndroid.check(permission)
78
+ if (hasPermission) {
79
+ console.log('Has permission: ' + permission)
80
+ return true
81
+ }
82
+
83
+ console.log('Permission request: ' + permission)
84
+ const status = await PermissionsAndroid.request(permission)
85
+ console.log('Permission request status: ' + status)
86
+ return status === 'granted'
87
+ } catch (err) {
88
+ console.log(err)
89
+ return false
90
+ }
91
+ }, [])
92
+
93
+ const addPicturesToProject = useCallback(async () => {
94
+ // go through all images selected and add to project
95
+ try {
96
+ loaderHandler.showLoader('Saving Pictures...')
112
97
 
113
- //console.log("----addPicturesToProject: Before For Loop; imgArr.length=" + cRef.imgArr.length);
114
- for (let i = 0; i < cRef.imgArr.length; i++) {
115
- //console.log("----addPicturesToProject: In For Loop; Before addOnePictureToProject(); i=" + i);
116
- if (cRef.props.addPicture) { //if they supplied a function to call
117
- await cRef.props.addPicture(cRef.imgArr[i], cRef.imgDescArr[i], cRef.props.prospectInst);
118
- } else { //otherwise use the default one in API
119
- await Api.getApi().addOnePictureToProject(cRef.imgArr[i], cRef.imgDescArr[i], cRef.props.prospectInst);
98
+ // Save selected images to device camera roll (per-item), only for camera-taken images
99
+ // save image to device library if it was just taken, if they selected to save to device, or didn't have the option to select that (allowEdit=false)
100
+ // NOTE: only saving photos to camera roll for iOS currently since the cameraroll lib doesn't
101
+ // support it for android (with targetSDKVersion=30) yet, as of v4.1.2
102
+ try {
103
+ if (allowSaveToDevice) {
104
+ const toSave = (itemsRef.current || []).filter(it => !!it.saveToDevice && !!it.path)
105
+ if (toSave.length > 0) {
106
+ {
107
+ for (const it of toSave) {
108
+ try {
109
+ await CameraRoll.save(it.path)
110
+ } catch (err) {
111
+ console.log('CameraRoll.save failed for ' + it.path + '; Error: ' + err)
120
112
  }
121
- //console.log("----addPicturesToProject: In For Loop; After addOnePictureToProject(); i=" + i);
113
+ }
122
114
  }
115
+ }
116
+ }
117
+ } catch (e) {
118
+ console.log('Error during save-to-device batch: ' + e)
119
+ }
123
120
 
124
- //console.log("----addPicturesToProject: returning true");
125
- loaderHandler.hideLoader();
126
- return true;
121
+ // Upload/add images to project
122
+ for (let i = 0; i < itemsRef.current.length; i++) {
123
+ if (addPicture) {
124
+ await addPicture(itemsRef.current[i], itemsRef.current[i]?.desc || '', prospectInst)
125
+ } else {
126
+ await Api.getApi().addOnePictureToProject(itemsRef.current[i], itemsRef.current[i]?.desc || '', prospectInst)
127
+ }
128
+ }
127
129
 
128
- } catch(err2) {
130
+ loaderHandler.hideLoader()
131
+ return true
132
+ } catch (err) {
133
+ console.log('----addPicturesToProject: returning false; ERROR: ' + err.toString())
134
+ loaderHandler.hideLoader()
135
+ return false
136
+ }
137
+ }, [addPicture, prospectInst, hasAndroidWritePermission, showToCust, saveToDevice, allowSaveToDevice])
129
138
 
130
- console.log("----addPicturesToProject: returning false; ERROR: " + err2.toString());
131
- loaderHandler.hideLoader();
132
- return false;
133
- }
139
+ const onAttach = useCallback(async () => {
140
+ if (!isMountedRef.current) {
141
+ return
134
142
  }
135
143
 
136
- async onImageSelect(payload) {
137
- //handle return of selected images from MultiImagePicker
138
- //payload expected (json): {index: integer, imageArray: [image info], imageDescArray: [image descriptions], imageValidArray: [array of true booleans], imageSource: ["taken" or "library"]}
144
+ setShowAttaching(false)
145
+ setShowAdd(false)
139
146
 
140
- let cRef = this;
147
+ await addPicturesToProject()
148
+ if (allowEdit && allowSaveToDevice) {
149
+ await Api.getApi().setDefaultSavePhotosToDevice(saveToDevice)
150
+ }
151
+ if (allowEdit && showToCustomerAllowed) {
152
+ await Api.getApi().setDefaultShowToCustomer(showToCust)
153
+ }
154
+ Analytics.logEvent('mip_addImages_onAttach', { source_page: 'MultiImagePicker' })
155
+ if (callback) {
156
+ callback()
157
+ }
158
+ }, [addPicturesToProject, allowEdit, callback, saveToDevice, allowSaveToDevice, showToCust, showToCustomerAllowed])
141
159
 
142
- cRef.imgArr = payload.imageArray;
143
- cRef.imgDescArr = payload.imageDescArray;
144
- cRef.imgValidArr = payload.imageValidArray;
145
- cRef.imgSource = payload.imageSource;
146
- if (cRef.props.allowEdit) {
147
- let std = await Api.getApi().getDefaultSavePhotosToDevice();
148
- if(cRef._mounted) cRef.setState({showAdd: true, saveToDevice: std});
149
- } else {
150
- //skip editing, just process attachments
151
- cRef.onAttach();
152
- }
160
+ const onClose = useCallback(() => {
161
+ if (!isMountedRef.current) {
162
+ return
153
163
  }
164
+ setShowAttaching(false)
165
+ setShowAdd(false)
166
+ }, [])
154
167
 
155
- setAllImageDataValid(allValid) {
156
- //handle return of selected images from MultiImagePicker <SelectedImages>
157
- //payload expected: (boolean) true if all selected images are valid, false otherwise
158
- let cRef = this;
159
- let initAllValid = cRef.state.allImageDataValid;
160
- if (allValid !== initAllValid) {
161
- //need to set state since overall validity flipped
162
- if(cRef._mounted) cRef.setState({allImageDataValid: allValid});
163
- }
168
+ const onCloseInfoDialog = useCallback(async (storageVal) => {
169
+ try {
170
+ setShowInfoDialog(false)
171
+ await AsyncStorage.setItem(STORAGE_KEY_SKIP_DIALOG, storageVal ? 'true' : 'false')
172
+ } catch (e) {
173
+ console.log('AddImages: error setting skip dialog pref: ' + e)
164
174
  }
175
+ }, [])
165
176
 
166
- onPressCheckbox() {
167
- Analytics.logEvent('mip_addImages_saveToDevice', { source_page: 'MultiImagePicker', saveToDeviceSetTo: !this.state.saveToDevice })
168
- this.setState({saveToDevice: !this.state.saveToDevice});
177
+ const onPressCheckbox_ShowToCust = useCallback(() => {
178
+ const total = itemsRef.current.length
179
+ const allTrue = total > 0 && itemsRef.current.every(it => !!it.showToCust)
180
+ const newValue = !allTrue
181
+ Analytics.logEvent('mip_addImages_showToCustomer', { source_page: 'MultiImagePicker', showToCustomerSetTo: newValue })
182
+ // Update each image's per-item flag and trigger re-render
183
+ if (itemsRef.current && itemsRef.current.length > 0) {
184
+ for (let i = 0; i < itemsRef.current.length; i++) {
185
+ itemsRef.current[i].showToCust = newValue
186
+ }
187
+ setItems([...itemsRef.current])
169
188
  }
189
+ setShowToCust(newValue)
190
+ }, [])
170
191
 
171
- onClose() {
172
- //clicked Close icon to close attach selected pictures modal
173
- let cRef = this;
174
- if(cRef._mounted) cRef.setState({showAttaching: false, showAdd: false});
192
+ const onPressCheckbox_SaveToDevice = useCallback(() => {
193
+ const total = itemsRef.current.length
194
+ const allTrue = total > 0 && itemsRef.current.every(it => !!it.saveToDevice)
195
+ const newValue = !allTrue
196
+ Analytics.logEvent('mip_addImages_saveToDevice', { source_page: 'MultiImagePicker', saveToDeviceSetTo: newValue })
197
+ // Update each image's metadata flag and trigger re-render
198
+ if (itemsRef.current && itemsRef.current.length > 0) {
199
+ for (let i = 0; i < itemsRef.current.length; i++) {
200
+ itemsRef.current[i].saveToDevice = newValue
201
+ }
202
+ // trigger rerender with shallow copy
203
+ setItems([...itemsRef.current])
175
204
  }
176
- onAttach() {
177
- //clicked Attach button to attach selected pictures
178
- let cRef = this;
179
- if (cRef._mounted) {
180
- cRef.setState({showAttaching: false, showAdd: false}, async function () {
181
- await cRef.addPicturesToProject();
182
- if (cRef.props.allowEdit && (cRef.imgSource === "taken")) {
183
- //only save user selection if they had a chance to enable/disable sabving to camera roll
184
- await Api.getApi().setDefaultSavePhotosToDevice(cRef.state.saveToDevice);
185
- }
186
- Analytics.logEvent('mip_addImages_onAttach', { source_page: 'MultiImagePicker' })
187
- if (cRef.props.callback) {
188
- cRef.props.callback();
189
- }
190
- });
205
+ setSaveToDevice(newValue)
206
+ }, [])
207
+
208
+ // Stable handler for item-level changes coming from SelectedImages
209
+ const onItemChange = useCallback((idx, patch) => {
210
+ setItems(prev => {
211
+ const next = prev.map((it, i) => (i === idx ? { ...it, ...patch } : it))
212
+ itemsRef.current = next
213
+ // recompute derived globals
214
+ const allSave = next.length > 0 && next.every(it => !!it.saveToDevice)
215
+ const allShow = next.length > 0 && next.every(it => !!it.showToCust)
216
+ if (saveToDevice !== allSave) setSaveToDevice(allSave)
217
+ if (showToCust !== allShow) setShowToCust(allShow)
218
+ // validity aggregate for Attach button
219
+ const allValid = next.every(it => it?.isValid !== false)
220
+ setAllImageDataValid(prevValid => (prevValid === allValid ? prevValid : allValid))
221
+ return next
222
+ })
223
+ }, [saveToDevice, showToCust])
224
+
225
+ const handleDeleteItem = useCallback((idx) => {
226
+ try {
227
+ if (!itemsRef.current || idx < 0 || idx >= itemsRef.current.length || itemsRef.current.length <= 1) return
228
+
229
+ const performDelete = () => {
230
+ try {
231
+ // Remove from all parallel arrays
232
+ itemsRef.current.splice(idx, 1)
233
+
234
+ // Update state from refs (single source of truth)
235
+ setItems([...itemsRef.current])
236
+
237
+ // Recompute global toggles based on remaining items
238
+ const allSave = itemsRef.current.length > 0 && itemsRef.current.every(it => !!it.saveToDevice)
239
+ const allShow = itemsRef.current.length > 0 && itemsRef.current.every(it => !!it.showToCust)
240
+ setSaveToDevice(allSave)
241
+ setShowToCust(allShow)
242
+
243
+ // Recompute validity aggregate
244
+ const allValid = itemsRef.current.every(it => it?.isValid !== false)
245
+ setAllImageDataValid(prev => (prev === allValid ? prev : allValid))
246
+ } catch (e) {
247
+ console.log('AddImages.handleDeleteItem performDelete error: ' + e)
191
248
  }
249
+ }
250
+
251
+ Alert.alert(
252
+ 'Remove photo?',
253
+ 'This will remove the photo from your selection.',
254
+ [
255
+ { text: 'Cancel', style: 'cancel' },
256
+ { text: 'Delete', style: 'destructive', onPress: performDelete }
257
+ ]
258
+ )
259
+ } catch (e) {
260
+ console.log('AddImages.handleDeleteItem error: ' + e)
261
+ }
262
+ }, [])
263
+
264
+ const handleSetAllImageDataValid = useCallback((allValid) => {
265
+ setAllImageDataValid(prev => (prev === allValid ? prev : allValid))
266
+ }, [])
267
+
268
+ const buildDefaultFilename = useCallback((img, idx, seedMs) => {
269
+ try {
270
+ const { filename: providedFilename, defaultName, path = '' } = img || {}
271
+ // Use existing defaultName when provided, otherwise fall back to a timestamp-based name
272
+ const baseName = defaultName || Moment(new Date(seedMs)).format('YYYY-MM-DD_hmmssa') + '_' + (idx + 1)
273
+ const normalizedPath = String(path).split('?')[0]
274
+ const lastDot = normalizedPath.lastIndexOf('.')
275
+ const extension = lastDot !== -1 ? normalizedPath.substring(lastDot) : ''
276
+ return extension ? `${baseName}${extension}` : baseName
277
+ } catch (e) {
278
+ console.log('AddImages.buildDefaultFilename error: ' + e)
279
+ return Moment().format('YYYY-MM-DD_hmmssa')
192
280
  }
281
+ }, [])
282
+
283
+ const onImageSelect = useCallback(async (payload) => {
284
+ // Build unified items list from payload
285
+ // handle return of selected images from MultiImagePicker
286
+
287
+ const { imageArray = [], imageDescArray = [], imageValidArray = [] } = payload || {}
288
+ const timestampSeed = Date.now()
289
+ itemsRef.current = imageArray.map((img, i) => ({
290
+ ...img,
291
+ filename: buildDefaultFilename(img, i, timestampSeed),
292
+ desc: imageDescArray[i] || '',
293
+ isValid: imageValidArray[i] !== false,
294
+ saveToDevice: false,
295
+ showToCust: false
296
+ }))
297
+ imgSourceRef.current = payload.imageSource
298
+
299
+ // init for saving selected images to device camera roll, only for camera-taken images
300
+ const canSaveToDevice = allowSaveToDevicePlatform && (payload.imageSource === 'taken')
301
+ setAllowSaveToDevice(canSaveToDevice)
193
302
 
194
- render ()
195
- {
196
- let cRef = this;
197
- if (cRef.state.showAttaching) {
198
- return (
199
- <LoadingOverlay/>
200
- );
303
+ if (allowEdit) {
304
+ const [defaultSaveToDevice, defaultShowToCustomer] = await Promise.all([
305
+ Api.getApi().getDefaultSavePhotosToDevice(),
306
+ showToCustomerAllowed ? Api.getApi().getDefaultShowToCustomer() : Promise.resolve(false)
307
+ ])
308
+
309
+ // initialize per-image flags
310
+ const initialSaveFlag = canSaveToDevice ? defaultSaveToDevice : false
311
+ const initialShowFlag = showToCustomerAllowed ? !!defaultShowToCustomer : false
312
+
313
+ if (itemsRef.current && itemsRef.current.length > 0) {
314
+ for (let i = 0; i < itemsRef.current.length; i++) {
315
+ itemsRef.current[i].saveToDevice = initialSaveFlag
316
+ itemsRef.current[i].showToCust = initialShowFlag
201
317
  }
202
- if (cRef.state.showAdd) {
203
- //If clicked Add button and selected images, show modal of selected images so user can edit title/descriptions before saving to project
204
-
205
- return (
206
- <Modal presentationStyle={"fullScreen"} animationType={"slide"}>
207
- <SafeAreaView style={styles.Page}>
208
- <View style={styles.NavProjectMain}>
209
- <TouchableOpacity hitSlop={{top: 20, bottom: 20, left: 20, right: 20}}
210
- onPress={() => {cRef.onClose()}}>
211
- <View style={styles.NavProjectButton}>
212
- <Icons.IconClose width="16" height="16" viewBox="0 0 16 16" />
213
- </View>
214
- </TouchableOpacity>
215
- <View style={styles.NavProjectTextContainer}>
216
- <View style={styles.NavProjectTextWrap}>
217
- <Text style={styles.NavProjectText}>Photos to Add</Text>
218
- </View>
219
- </View>
220
- <TouchableOpacity hitSlop={{top: 20, bottom: 20, left: 20, right: 20}}
221
- onPress={() => {cRef.onAttach()}} disabled={!this.state.allImageDataValid}>
222
- <Text style={this.state.allImageDataValid ? styles.ButtonTextRightActive : styles.ButtonTextRightDisabled}>Attach</Text>
223
- </TouchableOpacity>
224
- </View>
225
- {(Platform.OS !== "android") && (cRef.imgSource === "taken") && <TouchableOpacity style={styles.SaveToDeviceWrapper}
226
- onPress={() => cRef.onPressCheckbox()}>
227
- <View style={styles.SaveToDeviceCheckBox}>
228
- <CheckBox containerStyle={styles.CheckboxContainer}
229
- checkboxStyle={styles.CheckBox}
230
- checked={cRef.state.saveToDevice}
231
- onChange={(checked) => cRef.onPressCheckbox()}/>
232
- </View>
233
- <Text style={stdStyles.S2}>Save Photo to Device</Text>
234
- </TouchableOpacity>}
235
- {/*<KeyboardAwareScrollView contentContainerStyle={styles.ScrollViewContainer} keyboardShouldPersistTaps='always'>*/}
236
- <KeyboardAvoidingView behavior="padding" enabled>
237
- <ScrollView contentContainerStyle={styles.ScrollViewContainer} keyboardShouldPersistTaps='handled'>
238
-
239
- <SelectedImages imgArr={cRef.imgArr} imgDescArr={cRef.imgDescArr} imgValidArr={cRef.imgValidArr} callback={cRef.setAllImageDataValid} annotationAllowed={cRef.props.annotationAllowed}/>
240
-
241
- </ScrollView>
242
- </KeyboardAvoidingView>
243
- {/*</KeyboardAwareScrollView>*/}
244
- </SafeAreaView>
245
- </Modal>
246
- );
247
- } else {
248
- return (
249
- <MultiImagePicker ref={o => cRef.Picker = o} hitSlop={cRef.props.hitSlop} maxCount={cRef.props.maxCount} parentStyle={cRef.props.parentStyle} callback={cRef.onImageSelect}>
250
- {cRef.props.children}
251
- </MultiImagePicker>
252
- )
318
+ }
319
+ if (isMountedRef.current) {
320
+ setShowAdd(true)
321
+ setSaveToDevice(initialSaveFlag)
322
+ setShowToCust(initialShowFlag)
323
+ // also update local state arrays to reflect modified objects
324
+ setItems([...itemsRef.current])
325
+ // Show info dialog unless the user opted out previously
326
+ try {
327
+ const skipped = await AsyncStorage.getItem(STORAGE_KEY_SKIP_DIALOG)
328
+ if (skipped !== 'true') {
329
+ setShowInfoDialog(true)
330
+ }
331
+ } catch (e) {
332
+ console.log('AddImages: error reading skip dialog pref: ' + e)
333
+ setShowInfoDialog(true)
253
334
  }
335
+ }
336
+ } else {
337
+ // skip editing, just process attachments
338
+ if (isMountedRef.current) {
339
+ setItems([...itemsRef.current])
340
+ }
341
+ await onAttach()
254
342
  }
255
- }
256
-
257
- let styles = StyleSheet.create({
258
- Page: {
259
- backgroundColor: colors.white,
260
- flex: 1,
261
- },
262
- ScrollViewContainer: {
263
- paddingBottom: 100,
264
- },
265
- NavProjectMain: {
266
- flexDirection: 'row',
267
- //flex: 1,
268
- minHeight: 66,
269
- alignItems: 'center',
270
- paddingLeft: 16,
271
- //borderColor: 'black', borderWidth: 1
272
- },
273
- NavProjectButton: {
274
- paddingRight: 25
275
- },
276
- NavProjectTextContainer: {
277
- flex: 1,
278
- alignItems: 'flex-start',
279
- justifyContent: 'center'
280
- },
281
- NavProjectTextWrap: {
282
- flexDirection: 'row',
283
- alignItems: 'center',
284
- //paddingTop: 2
285
- },
286
- NavProjectText: {
287
- fontFamily: AppStyler.helper('fontFamily')("bold"),
288
- fontSize: 20,
289
- paddingRight: 10
290
- },
291
- NavProjectTextSub: {
292
- fontSize: 12,
293
- color: colors.black60
294
- },
295
- ButtonTextRightActive: {
296
- fontFamily: AppStyler.helper('fontFamily')('medium'),
297
- fontSize: 18,
298
- paddingRight: 25,
299
- textAlign: 'right',
300
- color: colors.blue,
301
- opacity: 1
302
- },
303
- ButtonTextRightDisabled: {
304
- fontFamily: AppStyler.helper('fontFamily')('medium'),
305
- fontSize: 18,
306
- paddingRight: 25,
307
- textAlign: 'right',
308
- color: colors.blue,
309
- opacity: 0.38
310
- },
311
- SaveToDeviceWrapper: {
312
- //backgroundColor: colors.white,
313
- borderTopWidth: 1,
314
- borderBottomWidth: 1,
315
- borderColor: colors.black05,
316
- paddingVertical: 5,
317
- flexDirection: "row",
318
- alignItems: "center",
319
- justifyContent: 'flex-start',
320
- },
321
- CheckboxContainer: {
322
- },
323
- SaveToDeviceCheckBox: {
324
- flex: 0,
325
- flexDirection: "row",
326
- justifyContent: "center",
327
- alignItems: "center",
328
- paddingTop: 5,
329
- marginHorizontal: 20,
330
- },
331
- CheckBox: {
332
- width: 18,
333
- height: 18,
334
- },
335
- });
336
-
337
- export default AddImages;
343
+ }, [allowEdit, buildDefaultFilename, onAttach, showToCustomerAllowed])
344
+
345
+ const SaveOptions = () => {
346
+ if (!showToCustomerAllowed && !allowSaveToDevice) {
347
+ return null
348
+ }
349
+ const total = items.length
350
+ const saveCount = items.filter(i => !!i.saveToDevice).length
351
+ const showCount = items.filter(i => !!i.showToCust).length
352
+ const allSave = total > 0 && saveCount === total
353
+ const someSave = total > 0 && saveCount > 0 && saveCount < total
354
+ const allShow = total > 0 && showCount === total
355
+ const someShow = total > 0 && showCount > 0 && showCount < total
356
+ // console.log(`SaveOptions: total=${total}, saveCount=${saveCount}, showCount=${showCount}, allSave=${allSave}, someSave=${someSave}, allShow=${allShow}, someShow=${someShow}`)
357
+
358
+ return (
359
+ <View style={styles.SaveOptionsContainer}>
360
+ {showToCustomerAllowed
361
+ ? <ListItem
362
+ key='showToCust'
363
+ leftContent={
364
+ <View style={styles.IconCircle}>
365
+ <Icons.IconEye_WithPad fill={colors.buttonPrimary} fillOpacity={1} />
366
+ </View>
367
+ }
368
+ mainAction={onPressCheckbox_ShowToCust}
369
+ rightAction={onPressCheckbox_ShowToCust}
370
+ title='Show all to customer'
371
+ subtitle='Select to share all w/ customer.'
372
+ rightContent={<CheckBox
373
+ checked={allShow}
374
+ indeterminate={someShow}
375
+ onChange={onPressCheckbox_ShowToCust}
376
+ />}
377
+ height={55}
378
+ paddingLeft={20}
379
+ rightContentWidth={40}
380
+ paddingRight={16}
381
+ topSeparator={false}
382
+ />
383
+ : null}
384
+ {allowSaveToDevice
385
+ ? <ListItem
386
+ key='saveToDevice'
387
+ leftContent={
388
+ <View style={styles.IconCircle}>
389
+ <Icons.IconSave_WithPad fill={colors.buttonPrimary} fillOpacity={1} />
390
+ </View>
391
+ }
392
+ mainAction={onPressCheckbox_SaveToDevice}
393
+ rightAction={onPressCheckbox_SaveToDevice}
394
+ title='Download all to device'
395
+ rightContent={<CheckBox
396
+ checked={allSave}
397
+ indeterminate={someSave}
398
+ onChange={onPressCheckbox_SaveToDevice}
399
+ />}
400
+ height={56}
401
+ paddingLeft={20}
402
+ rightContentWidth={40}
403
+ paddingRight={16}
404
+ topSeparator={showToCustomerAllowed}
405
+ />
406
+ : null}
407
+ </View>
408
+ )
409
+ }
410
+
411
+ if (showAttaching) {
412
+ return (
413
+ <LoadingOverlay />
414
+ )
415
+ }
416
+
417
+ if (showAdd) {
418
+ return (
419
+ <Modal presentationStyle='fullScreen' animationType='slide'>
420
+ <SafeAreaView style={styles.Page}>
421
+ <AppBarH8
422
+ variant='regular'
423
+ title='Photos to Add'
424
+ subtitle={items.length + ' Photo' + (items.length > 1 ? 's' : '')}
425
+ leftContentType='closeButton'
426
+ callback={onClose}
427
+ bgColor={colors.backgroundMedium}
428
+ bottomShadow
429
+ />
430
+ <SaveOptions />
431
+ <KeyboardAvoidingView behavior='padding' enabled style={styles.Content}>
432
+ <ScrollView contentContainerStyle={styles.ScrollViewContainer} keyboardShouldPersistTaps='handled'>
433
+ <SelectedImages
434
+ items={items}
435
+ callback={handleSetAllImageDataValid}
436
+ annotationAllowed={annotationAllowed}
437
+ onDeleteItem={handleDeleteItem}
438
+ onItemChange={onItemChange}
439
+ allowSaveToDevice={allowSaveToDevice}
440
+ allowShowToCustomer={showToCustomerAllowed}
441
+ />
442
+ </ScrollView>
443
+ </KeyboardAvoidingView>
444
+ <View style={styles.ButtonContainer}>
445
+ <CommonButton
446
+ variant='filled'
447
+ size='medium'
448
+ fullWidth
449
+ label='Attach'
450
+ endIcon={<Icons.IconUploadAll />}
451
+ onPress={onAttach}
452
+ disabled={!allImageDataValid}
453
+ />
454
+ </View>
455
+ </SafeAreaView>
456
+
457
+ <UploadWarningModal
458
+ visible={showInfoDialog}
459
+ onClose={onCloseInfoDialog}
460
+ />
461
+ </Modal>
462
+ )
463
+ }
464
+
465
+ return (
466
+ <MultiImagePicker ref={setPickerRef} hitSlop={hitSlop} maxCount={maxCount} parentStyle={parentStyle} callback={onImageSelect}>
467
+ {children}
468
+ </MultiImagePicker>
469
+ )
470
+ })
471
+
472
+ const styles = StyleSheet.create({
473
+ Page: {
474
+ backgroundColor: colors.backgroundMedium,
475
+ flex: 1
476
+ },
477
+ Content: {
478
+ flex: 1
479
+ },
480
+ ScrollViewContainer: {
481
+ paddingBottom: 100,
482
+ marginTop: 8
483
+ },
484
+ SaveOptionsContainer: {
485
+ backgroundColor: colors.white,
486
+ margin: 16,
487
+ borderRadius: 16
488
+ },
489
+ IconCircle: {
490
+ width: 32,
491
+ height: 32,
492
+ borderRadius: 16,
493
+ backgroundColor: colors.buttonPrimaryLight,
494
+ justifyContent: 'center',
495
+ alignItems: 'center'
496
+ },
497
+ ButtonContainer: {
498
+ height: 56,
499
+ paddingHorizontal: 16,
500
+ paddingVertical: 8,
501
+ borderTopWidth: 1,
502
+ borderTopColor: colors.black05
503
+ }
504
+ })
505
+
506
+ export default AddImages