-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.js
214 lines (193 loc) · 8.22 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
import React, {useRef, useCallback, useState, useEffect, useMemo} from 'react';
import {View, FlatList, PixelRatio, Keyboard} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import * as DeviceCapabilities from '../../../libs/DeviceCapabilities';
import styles from '../../../styles/styles';
import CarouselActions from './CarouselActions';
import AttachmentView from '../AttachmentView';
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 useWindowDimensions from '../../../hooks/useWindowDimensions';
const canUseTouchScreen = DeviceCapabilities.canUseTouchScreen();
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}) {
const scrollRef = useRef(null);
const {windowWidth, isSmallScreenWidth} = useWindowDimensions();
const {attachments, initialPage, initialActiveSource, initialItem} = useMemo(() => extractAttachmentsFromReport(report, reportActions, source), [report, reportActions, source]);
useEffect(() => {
// Update the parent modal's state with the source and name from the mapped attachments
if (!initialItem) return;
onNavigate(initialItem);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [initialItem]);
const [containerWidth, setContainerWidth] = useState(0);
const [page, setPage] = useState(initialPage);
const [activeSource, setActiveSource] = useState(initialActiveSource);
const [shouldShowArrows, setShouldShowArrows, autoHideArrows, cancelAutoHideArrows] = useCarouselArrows();
/**
* Updates the page state when the user navigates between attachments
* @param {Object} item
* @param {number} index
*/
const updatePage = useRef(
({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, 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 container for a single attachment should be rendered
* @param {Object} cellRendererProps
* @returns {JSX.Element}
*/
const renderCell = useCallback(
(cellProps) => {
// Use window width instead of layout width to address the issue in https://github.com/Expensify/App/issues/17760
// considering horizontal margin and border width in centered modal
const modalStyles = styles.centeredModalStyles(isSmallScreenWidth, true);
const style = [cellProps.style, styles.h100, {width: PixelRatio.roundToNearestPixel(windowWidth - (modalStyles.marginHorizontal + modalStyles.borderWidth) * 2)}];
return (
<View
// eslint-disable-next-line react/jsx-props-no-spreading
{...cellProps}
style={style}
/>
);
},
[isSmallScreenWidth, windowWidth],
);
/**
* Defines how a single attachment should be rendered
* @param {Object} item
* @param {Boolean} item.isAuthTokenRequired
* @param {String} item.source
* @param {Object} item.file
* @param {String} item.file.name
* @returns {JSX.Element}
*/
const renderItem = useCallback(
({item}) => (
<AttachmentView
source={item.source}
file={item.file}
isAuthTokenRequired={item.isAuthTokenRequired}
isFocused={activeSource === item.source}
onPress={() => canUseTouchScreen && setShouldShowArrows(!shouldShowArrows)}
isUsedInCarousel
/>
),
[activeSource, 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)}
>
<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={renderCell}
renderItem={renderItem}
getItemLayout={getItemLayout}
keyExtractor={(item) => item.source}
viewabilityConfig={viewabilityConfig}
onViewableItemsChanged={updatePage.current}
/>
)}
<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);