-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.js
232 lines (209 loc) · 9.24 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import React, {useRef, useCallback, useState, useEffect} from 'react';
import {View, FlatList, PixelRatio, Keyboard} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import styles from '../../../styles/styles';
import AttachmentCarouselCellRenderer from './AttachmentCarouselCellRenderer';
import CarouselActions from './CarouselActions';
import withWindowDimensions from '../../withWindowDimensions';
import CarouselButtons from './CarouselButtons';
import extractAttachmentsFromReport from './extractAttachmentsFromReport';
import {propTypes, defaultProps} from './attachmentCarouselPropTypes';
import ONYXKEYS from '../../../ONYXKEYS';
import withLocalize from '../../withLocalize';
import compose from '../../../libs/compose';
import useCarouselArrows from './useCarouselArrows';
import CarouselItem from './CarouselItem';
import Navigation from '../../../libs/Navigation/Navigation';
import BlockingView from '../../BlockingViews/BlockingView';
import * as Illustrations from '../../Icon/Illustrations';
import variables from '../../../styles/variables';
import * as DeviceCapabilities from '../../../libs/DeviceCapabilities';
import * as ReportActionsUtils from '../../../libs/ReportActionsUtils';
const viewabilityConfig = {
// To facilitate paging through the attachments, we want to consider an item "viewable" when it is
// more than 95% visible. When that happens we update the page index in the state.
itemVisiblePercentThreshold: 95,
};
function AttachmentCarousel({report, reportActions, source, onNavigate, setDownloadButtonVisibility, translate}) {
const scrollRef = useRef(null);
const canUseTouchScreen = DeviceCapabilities.canUseTouchScreen();
const [containerWidth, setContainerWidth] = useState(0);
const [page, setPage] = useState(0);
const [attachments, setAttachments] = useState([]);
const [activeSource, setActiveSource] = useState(source);
const [shouldShowArrows, setShouldShowArrows, autoHideArrows, cancelAutoHideArrows] = useCarouselArrows();
const compareImage = useCallback(
(attachment) => {
if (attachment.isReceipt) {
const action = ReportActionsUtils.getParentReportAction(report);
const transactionID = _.get(action, ['originalMessage', 'IOUTransactionID']);
return attachment.transactionID === transactionID;
}
return attachment.source === source;
},
[source, report],
);
useEffect(() => {
const attachmentsFromReport = extractAttachmentsFromReport(report, reportActions);
const initialPage = _.findIndex(attachmentsFromReport, compareImage);
// Dismiss the modal when deleting an attachment during its display in preview.
if (initialPage === -1 && _.find(attachments, compareImage)) {
Navigation.dismissModal();
} else {
setPage(initialPage);
setAttachments(attachmentsFromReport);
// Update the download button visibility in the parent modal
setDownloadButtonVisibility(initialPage !== -1);
// Update the parent modal's state with the source and name from the mapped attachments
if (!_.isUndefined(attachmentsFromReport[initialPage])) {
onNavigate(attachmentsFromReport[initialPage]);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reportActions, compareImage]);
/**
* Updates the page state when the user navigates between attachments
* @param {Object} item
* @param {number} index
*/
const updatePage = useCallback(
({viewableItems}) => {
Keyboard.dismiss();
// Since we can have only one item in view at a time, we can use the first item in the array
// to get the index of the current page
const entry = _.first(viewableItems);
if (!entry) {
setActiveSource(null);
return;
}
setPage(entry.index);
setActiveSource(entry.item.source);
onNavigate(entry.item);
},
[onNavigate],
);
/**
* Increments or decrements the index to get another selected item
* @param {Number} deltaSlide
*/
const cycleThroughAttachments = useCallback(
(deltaSlide) => {
const nextIndex = page + deltaSlide;
const nextItem = attachments[nextIndex];
if (!nextItem || !scrollRef.current) {
return;
}
scrollRef.current.scrollToIndex({index: nextIndex, animated: canUseTouchScreen});
},
[attachments, canUseTouchScreen, page],
);
/**
* Calculate items layout information to optimize scrolling performance
* @param {*} data
* @param {Number} index
* @returns {{offset: Number, length: Number, index: Number}}
*/
const getItemLayout = useCallback(
(_data, index) => ({
length: containerWidth,
offset: containerWidth * index,
index,
}),
[containerWidth],
);
/**
* Defines how a single attachment should be rendered
* @param {Object} item
* @param {String} item.reportActionID
* @param {Boolean} item.isAuthTokenRequired
* @param {String} item.source
* @param {Object} item.file
* @param {String} item.file.name
* @param {Boolean} item.hasBeenFlagged
* @returns {JSX.Element}
*/
const renderItem = useCallback(
({item}) => (
<CarouselItem
item={item}
isFocused={activeSource === item.source}
onPress={canUseTouchScreen ? () => setShouldShowArrows(!shouldShowArrows) : undefined}
/>
),
[activeSource, canUseTouchScreen, setShouldShowArrows, shouldShowArrows],
);
return (
<View
style={[styles.flex1, styles.attachmentCarouselContainer]}
onLayout={({nativeEvent}) => setContainerWidth(PixelRatio.roundToNearestPixel(nativeEvent.layout.width))}
onMouseEnter={() => !canUseTouchScreen && setShouldShowArrows(true)}
onMouseLeave={() => !canUseTouchScreen && setShouldShowArrows(false)}
>
{page === -1 ? (
<BlockingView
icon={Illustrations.ToddBehindCloud}
iconWidth={variables.modalTopIconWidth}
iconHeight={variables.modalTopIconHeight}
title={translate('notFound.notHere')}
/>
) : (
<>
<CarouselButtons
shouldShowArrows={shouldShowArrows}
page={page}
attachments={attachments}
onBack={() => cycleThroughAttachments(-1)}
onForward={() => cycleThroughAttachments(1)}
autoHideArrow={autoHideArrows}
cancelAutoHideArrow={cancelAutoHideArrows}
/>
{containerWidth > 0 && (
<FlatList
keyboardShouldPersistTaps="handled"
listKey="AttachmentCarousel"
horizontal
decelerationRate="fast"
showsHorizontalScrollIndicator={false}
bounces={false}
// Scroll only one image at a time no matter how fast the user swipes
disableIntervalMomentum
pagingEnabled
snapToAlignment="start"
snapToInterval={containerWidth}
// Enable scrolling by swiping on mobile (touch) devices only
// disable scroll for desktop/browsers because they add their scrollbars
// Enable scrolling FlatList only when PDF is not in a zoomed state
scrollEnabled={canUseTouchScreen}
ref={scrollRef}
initialScrollIndex={page}
initialNumToRender={3}
windowSize={5}
maxToRenderPerBatch={3}
data={attachments}
CellRendererComponent={AttachmentCarouselCellRenderer}
renderItem={renderItem}
getItemLayout={getItemLayout}
keyExtractor={(item) => item.source}
viewabilityConfig={viewabilityConfig}
onViewableItemsChanged={updatePage}
/>
)}
<CarouselActions onCycleThroughAttachments={cycleThroughAttachments} />
</>
)}
</View>
);
}
AttachmentCarousel.propTypes = propTypes;
AttachmentCarousel.defaultProps = defaultProps;
export default compose(
withOnyx({
reportActions: {
key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.reportID}`,
canEvict: false,
},
}),
withLocalize,
withWindowDimensions,
)(AttachmentCarousel);