-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
ReportScreen.js
575 lines (511 loc) · 23.7 KB
/
ReportScreen.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
import {useIsFocused} from '@react-navigation/native';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import Banner from '@components/Banner';
import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView';
import DragAndDropProvider from '@components/DragAndDrop/Provider';
import MoneyReportHeader from '@components/MoneyReportHeader';
import MoneyRequestHeader from '@components/MoneyRequestHeader';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView';
import ScreenWrapper from '@components/ScreenWrapper';
import TaskHeaderActionButton from '@components/TaskHeaderActionButton';
import withCurrentReportID, {withCurrentReportIDDefaultProps, withCurrentReportIDPropTypes} from '@components/withCurrentReportID';
import withViewportOffsetTop from '@components/withViewportOffsetTop';
import useAppFocusEvent from '@hooks/useAppFocusEvent';
import useLocalize from '@hooks/useLocalize';
import usePrevious from '@hooks/usePrevious';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import Timing from '@libs/actions/Timing';
import compose from '@libs/compose';
import Navigation from '@libs/Navigation/Navigation';
import clearReportNotifications from '@libs/Notification/clearReportNotifications';
import reportWithoutHasDraftSelector from '@libs/OnyxSelectors/reportWithoutHasDraftSelector';
import Performance from '@libs/Performance';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import personalDetailsPropType from '@pages/personalDetailsPropType';
import reportMetadataPropTypes from '@pages/reportMetadataPropTypes';
import reportPropTypes from '@pages/reportPropTypes';
import * as ComposerActions from '@userActions/Composer';
import * as Report from '@userActions/Report';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import HeaderView from './HeaderView';
import reportActionPropTypes from './report/reportActionPropTypes';
import ReportActionsView from './report/ReportActionsView';
import ReportFooter from './report/ReportFooter';
import {ActionListContext, ReactionListContext} from './ReportScreenContext';
const propTypes = {
/** Navigation route context info provided by react navigation */
route: PropTypes.shape({
/** Route specific parameters used on this screen */
params: PropTypes.shape({
/** The ID of the report this screen should display */
reportID: PropTypes.string,
/** The reportActionID to scroll to */
reportActionID: PropTypes.string,
}).isRequired,
}).isRequired,
/** Tells us if the sidebar has rendered */
isSidebarLoaded: PropTypes.bool,
/** The report currently being looked at */
report: reportPropTypes,
/** The report metadata loading states */
reportMetadata: reportMetadataPropTypes,
/** Array of report actions for this report */
reportActions: PropTypes.arrayOf(PropTypes.shape(reportActionPropTypes)),
/** Whether the composer is full size */
isComposerFullSize: PropTypes.bool,
/** Beta features list */
betas: PropTypes.arrayOf(PropTypes.string),
/** The policies which the user has access to */
policies: PropTypes.objectOf(
PropTypes.shape({
/** The policy name */
name: PropTypes.string,
/** The type of the policy */
type: PropTypes.string,
}),
),
/** The account manager report ID */
accountManagerReportID: PropTypes.string,
/** All of the personal details for everyone */
personalDetails: PropTypes.objectOf(personalDetailsPropType),
/** Onyx function that marks the component ready for hydration */
markReadyForHydration: PropTypes.func,
/** Whether user is leaving the current report */
userLeavingStatus: PropTypes.bool,
viewportOffsetTop: PropTypes.number.isRequired,
...withCurrentReportIDPropTypes,
};
const defaultProps = {
isSidebarLoaded: false,
reportActions: [],
report: {},
reportMetadata: {
isLoadingInitialReportActions: true,
isLoadingOlderReportActions: false,
isLoadingNewerReportActions: false,
},
isComposerFullSize: false,
betas: [],
policies: {},
accountManagerReportID: null,
userLeavingStatus: false,
personalDetails: {},
markReadyForHydration: null,
...withCurrentReportIDDefaultProps,
};
/**
* Get the currently viewed report ID as number
*
* @param {Object} route
* @param {Object} route.params
* @param {String} route.params.reportID
* @returns {String}
*/
function getReportID(route) {
// The report ID is used in an onyx key. If it's an empty string, onyx will return
// a collection instead of an individual report.
// We can't use the default value functionality of `lodash.get()` because it only
// provides a default value on `undefined`, and will return an empty string.
// Placing the default value outside of `lodash.get()` is intentional.
return String(lodashGet(route, 'params.reportID') || 0);
}
function ReportScreen({
betas,
route,
report,
reportMetadata,
reportActions,
accountManagerReportID,
personalDetails,
markReadyForHydration,
policies,
isSidebarLoaded,
viewportOffsetTop,
isComposerFullSize,
errors,
userLeavingStatus,
currentReportID,
navigation,
}) {
const styles = useThemeStyles();
const {translate} = useLocalize();
const {isSmallScreenWidth} = useWindowDimensions();
const firstRenderRef = useRef(true);
const flatListRef = useRef();
const reactionListRef = useRef();
const prevReport = usePrevious(report);
const prevUserLeavingStatus = usePrevious(userLeavingStatus);
const [isBannerVisible, setIsBannerVisible] = useState(true);
const [listHeight, setListHeight] = useState(0);
const [scrollPosition, setScrollPosition] = useState({});
const wasReportAccessibleRef = useRef(false);
if (firstRenderRef.current) {
Timing.start(CONST.TIMING.CHAT_RENDER);
Performance.markStart(CONST.TIMING.CHAT_RENDER);
}
const reportID = getReportID(route);
const {addWorkspaceRoomOrChatPendingAction, addWorkspaceRoomOrChatErrors} = ReportUtils.getReportOfflinePendingActionAndErrors(report);
const screenWrapperStyle = [styles.appContent, styles.flex1, {marginTop: viewportOffsetTop}];
// There are no reportActions at all to display and we are still in the process of loading the next set of actions.
const isLoadingInitialReportActions = _.isEmpty(reportActions) && reportMetadata.isLoadingInitialReportActions;
const isOptimisticDelete = lodashGet(report, 'statusNum') === CONST.REPORT.STATUS.CLOSED;
const shouldHideReport = !ReportUtils.canAccessReport(report, policies, betas);
const isLoading = !reportID || !isSidebarLoaded || _.isEmpty(personalDetails);
const parentReportAction = ReportActionsUtils.getParentReportAction(report);
const isSingleTransactionView = ReportUtils.isMoneyRequest(report);
const policy = policies[`${ONYXKEYS.COLLECTION.POLICY}${report.policyID}`] || {};
const isTopMostReportId = currentReportID === getReportID(route);
const didSubscribeToReportLeavingEvents = useRef(false);
useEffect(() => {
if (!report || !report.reportID || shouldHideReport) {
return;
}
wasReportAccessibleRef.current = true;
}, [shouldHideReport, report]);
const goBack = useCallback(() => {
Navigation.goBack(ROUTES.HOME, false, true);
}, []);
let headerView = (
<HeaderView
reportID={reportID}
onNavigationMenuButtonClicked={goBack}
personalDetails={personalDetails}
report={report}
/>
);
if (isSingleTransactionView) {
headerView = (
<MoneyRequestHeader
report={report}
policy={policy}
personalDetails={personalDetails}
isSingleTransactionView={isSingleTransactionView}
parentReportAction={parentReportAction}
/>
);
}
if (ReportUtils.isMoneyRequestReport(report)) {
headerView = (
<MoneyReportHeader
report={report}
policy={policy}
personalDetails={personalDetails}
isSingleTransactionView={isSingleTransactionView}
parentReportAction={parentReportAction}
/>
);
}
/**
* When false the ReportActionsView will completely unmount and we will show a loader until it returns true.
*
* @returns {Boolean}
*/
const isReportReadyForDisplay = useMemo(() => {
const reportIDFromPath = getReportID(route);
// This is necessary so that when we are retrieving the next report data from Onyx the ReportActionsView will remount completely
const isTransitioning = report && report.reportID !== reportIDFromPath;
return reportIDFromPath !== '' && report.reportID && !isTransitioning;
}, [route, report]);
const isFocused = useIsFocused();
useEffect(() => {
if (!report.reportID || !isFocused) {
return;
}
Report.updateLastVisitTime(report.reportID);
}, [report.reportID, isFocused]);
const fetchReportIfNeeded = useCallback(() => {
const reportIDFromPath = getReportID(route);
// Report ID will be empty when the reports collection is empty.
// This could happen when we are loading the collection for the first time after logging in.
if (!ReportUtils.isValidReportIDFromPath(reportIDFromPath)) {
return;
}
// It possible that we may not have the report object yet in Onyx yet e.g. we navigated to a URL for an accessible report that
// is not stored locally yet. If report.reportID exists, then the report has been stored locally and nothing more needs to be done.
// If it doesn't exist, then we fetch the report from the API.
if (report.reportID && report.reportID === getReportID(route) && !isLoadingInitialReportActions) {
return;
}
Report.openReport(reportIDFromPath);
}, [report.reportID, route, isLoadingInitialReportActions]);
const dismissBanner = useCallback(() => {
setIsBannerVisible(false);
}, []);
const chatWithAccountManager = useCallback(() => {
Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(accountManagerReportID));
}, [accountManagerReportID]);
/**
* @param {String} text
*/
const onSubmitComment = useCallback(
(text) => {
Report.addComment(getReportID(route), text);
},
[route],
);
// Clear notifications for the current report when it's opened and re-focused
const clearNotifications = useCallback(() => {
// Check if this is the top-most ReportScreen since the Navigator preserves multiple at a time
if (!isTopMostReportId) {
return;
}
clearReportNotifications(report.reportID);
}, [report.reportID, isTopMostReportId]);
useEffect(clearNotifications, [clearNotifications]);
useAppFocusEvent(clearNotifications);
useEffect(() => {
Timing.end(CONST.TIMING.CHAT_RENDER);
Performance.markEnd(CONST.TIMING.CHAT_RENDER);
fetchReportIfNeeded();
ComposerActions.setShouldShowComposeInput(true);
return () => {
if (!didSubscribeToReportLeavingEvents) {
return;
}
Report.unsubscribeFromLeavingRoomReportChannel(report.reportID);
};
// I'm disabling the warning, as it expects to use exhaustive deps, even though we want this useEffect to run only on the first render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
// We don't want this effect to run on the first render.
if (firstRenderRef.current) {
firstRenderRef.current = false;
return;
}
const onyxReportID = report.reportID;
const prevOnyxReportID = prevReport.reportID;
const routeReportID = getReportID(route);
// Navigate to the Concierge chat if the room was removed from another device (e.g. user leaving a room or removed from a room)
if (
// non-optimistic case
(!prevUserLeavingStatus && userLeavingStatus) ||
// optimistic case
(prevOnyxReportID &&
prevOnyxReportID === routeReportID &&
!onyxReportID &&
prevReport.statusNum === CONST.REPORT.STATUS.OPEN &&
(report.statusNum === CONST.REPORT.STATUS.CLOSED || (!report.statusNum && !prevReport.parentReportID && prevReport.chatType === CONST.REPORT.CHAT_TYPE.POLICY_ROOM))) ||
((ReportUtils.isMoneyRequest(prevReport) || ReportUtils.isMoneyRequestReport(prevReport)) && _.isEmpty(report))
) {
Navigation.dismissModal();
if (Navigation.getTopmostReportId() === prevOnyxReportID) {
Navigation.setShouldPopAllStateOnUP();
Navigation.goBack(ROUTES.HOME, false, true);
}
if (prevReport.parentReportID) {
Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(prevReport.parentReportID));
return;
}
Report.navigateToConciergeChat();
return;
}
// If you already have a report open and are deeplinking to a new report on native,
// the ReportScreen never actually unmounts and the reportID in the route also doesn't change.
// Therefore, we need to compare if the existing reportID is the same as the one in the route
// before deciding that we shouldn't call OpenReport.
if (onyxReportID === prevReport.reportID && (!onyxReportID || onyxReportID === routeReportID)) {
return;
}
fetchReportIfNeeded();
ComposerActions.setShouldShowComposeInput(true);
}, [
route,
report,
errors,
fetchReportIfNeeded,
prevReport.reportID,
prevUserLeavingStatus,
userLeavingStatus,
prevReport.statusNum,
prevReport.parentReportID,
prevReport.chatType,
prevReport,
]);
useEffect(() => {
if (!ReportUtils.isValidReportIDFromPath(reportID)) {
return;
}
// Ensures subscription event succeeds when the report/workspace room is created optimistically.
// Check if the optimistic `OpenReport` or `AddWorkspaceRoom` has succeeded by confirming
// any `pendingFields.createChat` or `pendingFields.addWorkspaceRoom` fields are set to null.
// Existing reports created will have empty fields for `pendingFields`.
const didCreateReportSuccessfully = !report.pendingFields || (!report.pendingFields.addWorkspaceRoom && !report.pendingFields.createChat);
if (!didSubscribeToReportLeavingEvents.current && didCreateReportSuccessfully) {
Report.subscribeToReportLeavingEvents(reportID);
didSubscribeToReportLeavingEvents.current = true;
}
}, [report, didSubscribeToReportLeavingEvents, reportID]);
const onListLayout = useCallback((e) => {
setListHeight((prev) => lodashGet(e, 'nativeEvent.layout.height', prev));
if (!markReadyForHydration) {
return;
}
markReadyForHydration();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// eslint-disable-next-line rulesdir/no-negated-variables
const shouldShowNotFoundPage = useMemo(
() =>
(!wasReportAccessibleRef.current &&
!firstRenderRef.current &&
!report.reportID &&
!isOptimisticDelete &&
!reportMetadata.isLoadingInitialReportActions &&
!isLoading &&
!userLeavingStatus) ||
shouldHideReport,
[report, reportMetadata, isLoading, shouldHideReport, isOptimisticDelete, userLeavingStatus],
);
const actionListValue = useMemo(() => ({flatListRef, scrollPosition, setScrollPosition}), [flatListRef, scrollPosition, setScrollPosition]);
return (
<ActionListContext.Provider value={actionListValue}>
<ReactionListContext.Provider value={reactionListRef}>
<ScreenWrapper
navigation={navigation}
style={screenWrapperStyle}
shouldEnableKeyboardAvoidingView={isTopMostReportId}
testID={ReportScreen.displayName}
>
<FullPageNotFoundView
shouldShow={shouldShowNotFoundPage}
subtitleKey="notFound.noAccess"
shouldShowCloseButton={false}
shouldShowBackButton={isSmallScreenWidth}
onBackButtonPress={Navigation.goBack}
shouldShowLink={false}
>
<OfflineWithFeedback
pendingAction={addWorkspaceRoomOrChatPendingAction}
errors={addWorkspaceRoomOrChatErrors}
shouldShowErrorMessages={false}
needsOffscreenAlphaCompositing
>
{headerView}
{ReportUtils.isTaskReport(report) && isSmallScreenWidth && ReportUtils.isOpenTaskReport(report, parentReportAction) && (
<View style={[styles.borderBottom]}>
<View style={[styles.appBG, styles.pl0]}>
<View style={[styles.ph5, styles.pb3]}>
<TaskHeaderActionButton report={report} />
</View>
</View>
</View>
)}
</OfflineWithFeedback>
{!!accountManagerReportID && ReportUtils.isConciergeChatReport(report) && isBannerVisible && (
<Banner
containerStyles={[styles.mh4, styles.mt4, styles.p4, styles.bgDark]}
textStyles={[styles.colorReversed]}
text={translate('reportActionsView.chatWithAccountManager')}
onClose={dismissBanner}
onPress={chatWithAccountManager}
shouldShowCloseButton
/>
)}
<DragAndDropProvider isDisabled={!isReportReadyForDisplay || !ReportUtils.canUserPerformWriteAction(report)}>
<View
style={[styles.flex1, styles.justifyContentEnd, styles.overflowHidden]}
onLayout={onListLayout}
>
{isReportReadyForDisplay && !isLoadingInitialReportActions && !isLoading && (
<ReportActionsView
reportActions={reportActions}
report={report}
isLoadingInitialReportActions={reportMetadata.isLoadingInitialReportActions}
isLoadingNewerReportActions={reportMetadata.isLoadingNewerReportActions}
isLoadingOlderReportActions={reportMetadata.isLoadingOlderReportActions}
isComposerFullSize={isComposerFullSize}
policy={policy}
/>
)}
{/* Note: The ReportActionsSkeletonView should be allowed to mount even if the initial report actions are not loaded.
If we prevent rendering the report while they are loading then
we'll unnecessarily unmount the ReportActionsView which will clear the new marker lines initial state. */}
{(!isReportReadyForDisplay || isLoadingInitialReportActions || isLoading) && <ReportActionsSkeletonView />}
{isReportReadyForDisplay ? (
<ReportFooter
pendingAction={addWorkspaceRoomOrChatPendingAction}
reportActions={reportActions}
report={report}
isComposerFullSize={isComposerFullSize}
onSubmitComment={onSubmitComment}
policies={policies}
listHeight={listHeight}
personalDetails={personalDetails}
/>
) : (
<ReportFooter isReportReadyForDisplay={false} />
)}
</View>
</DragAndDropProvider>
</FullPageNotFoundView>
</ScreenWrapper>
</ReactionListContext.Provider>
</ActionListContext.Provider>
);
}
ReportScreen.propTypes = propTypes;
ReportScreen.defaultProps = defaultProps;
ReportScreen.displayName = 'ReportScreen';
export default compose(
withViewportOffsetTop,
withCurrentReportID,
withOnyx(
{
isSidebarLoaded: {
key: ONYXKEYS.IS_SIDEBAR_LOADED,
},
reportActions: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getReportID(route)}`,
canEvict: false,
selector: (reportActions) => ReportActionsUtils.getSortedReportActionsForDisplay(reportActions, true),
},
report: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT}${getReportID(route)}`,
allowStaleData: true,
selector: reportWithoutHasDraftSelector,
},
reportMetadata: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_METADATA}${getReportID(route)}`,
initialValue: {
isLoadingInitialReportActions: true,
isLoadingOlderReportActions: false,
isLoadingNewerReportActions: false,
},
},
isComposerFullSize: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_IS_COMPOSER_FULL_SIZE}${getReportID(route)}`,
initialValue: false,
},
betas: {
key: ONYXKEYS.BETAS,
},
policies: {
key: ONYXKEYS.COLLECTION.POLICY,
allowStaleData: true,
},
accountManagerReportID: {
key: ONYXKEYS.ACCOUNT_MANAGER_REPORT_ID,
initialValue: null,
},
personalDetails: {
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
},
userLeavingStatus: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_USER_IS_LEAVING_ROOM}${getReportID(route)}`,
initialValue: false,
},
},
true,
),
)(ReportScreen);