Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create usePaginatedReportActions hook #44412

Merged
merged 11 commits into from
Jun 27, 2024
33 changes: 33 additions & 0 deletions src/hooks/usePaginatedReportActions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import {useMemo} from 'react';
import {useOnyx} from 'react-native-onyx';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import ONYXKEYS from '@src/ONYXKEYS';

/**
* Get the longest continuous chunk of reportActions including the linked reportAction. If not linking to a specific action, returns the continuous chunk of newest reportActions.
*/
function usePaginatedReportActions(reportID?: string, reportActionID?: string) {
// Use `||` instead of `??` to handle empty string.
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we even have this rule? This is like the 3rd time I've seen it dismissed today.

const reportIDWithDefault = reportID || '-1';
const [sortedAllReportActions = []] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportIDWithDefault}`, {
canEvict: false,
selector: (allReportActions) => ReportActionsUtils.getSortedReportActionsForDisplay(allReportActions, true),
});

const reportActions = useMemo(() => {
if (!sortedAllReportActions.length) {
return [];
}
return ReportActionsUtils.getContinuousReportActionChain(sortedAllReportActions, reportActionID);
}, [reportActionID, sortedAllReportActions]);

const linkedAction = useMemo(() => sortedAllReportActions.find((obj) => String(obj.reportActionID) === String(reportActionID)), [reportActionID, sortedAllReportActions]);

return {
reportActions,
linkedAction,
};
}

export default usePaginatedReportActions;
13 changes: 2 additions & 11 deletions src/pages/ReportDetailsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import usePaginatedReportActions from '@hooks/usePaginatedReportActions';
import useThemeStyles from '@hooks/useThemeStyles';
import Navigation from '@libs/Navigation/Navigation';
import type {ReportDetailsNavigatorParamList} from '@libs/Navigation/types';
Expand Down Expand Up @@ -80,17 +81,7 @@ function ReportDetailsPage({policies, report, session, personalDetails}: ReportD
const {isOffline} = useNetwork();
const styles = useThemeStyles();
const [parentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${report.parentReportID ?? '-1'}`);
const [sortedAllReportActions = []] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.reportID ?? '-1'}`, {
canEvict: false,
selector: (allReportActions: OnyxEntry<OnyxTypes.ReportActions>) => ReportActionsUtils.getSortedReportActionsForDisplay(allReportActions, true),
});

const reportActions = useMemo(() => {
if (!sortedAllReportActions.length) {
return [];
}
return ReportActionsUtils.getContinuousReportActionChain(sortedAllReportActions);
}, [sortedAllReportActions]);
const {reportActions} = usePaginatedReportActions(report.reportID);

const transactionThreadReportID = useMemo(
() => ReportActionsUtils.getOneTransactionThreadReportID(report.reportID, reportActions ?? [], isOffline),
Expand Down
49 changes: 13 additions & 36 deletions src/pages/home/ReportScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ import useDeepCompareRef from '@hooks/useDeepCompareRef';
import useIsReportOpenInRHP from '@hooks/useIsReportOpenInRHP';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import usePaginatedReportActions from '@hooks/usePaginatedReportActions';
import usePrevious from '@hooks/usePrevious';
import useThemeStyles from '@hooks/useThemeStyles';
import useViewportOffsetTop from '@hooks/useViewportOffsetTop';
import useWindowDimensions from '@hooks/useWindowDimensions';
import {getCurrentUserAccountID} from '@libs/actions/Report';
import Timing from '@libs/actions/Timing';
import Navigation from '@libs/Navigation/Navigation';
import clearReportNotifications from '@libs/Notification/clearReportNotifications';
Expand Down Expand Up @@ -65,9 +65,6 @@ type ReportScreenOnyxProps = {
/** The policies which the user has access to */
policies: OnyxCollection<OnyxTypes.Policy>;

/** An array containing all report actions related to this report, sorted based on a date criterion */
sortedAllReportActions: OnyxTypes.ReportAction[];

/** Additional report details */
reportNameValuePairs: OnyxEntry<OnyxTypes.ReportNameValuePairs>;

Expand Down Expand Up @@ -116,7 +113,6 @@ function ReportScreen({
betas = [],
route,
reportNameValuePairs,
sortedAllReportActions,
reportMetadata = {
isLoadingInitialReportActions: true,
isLoadingOlderReportActions: false,
Expand Down Expand Up @@ -257,12 +253,15 @@ function ReportScreen({
const prevReport = usePrevious(report);
const prevUserLeavingStatus = usePrevious(userLeavingStatus);
const [isLinkingToMessage, setIsLinkingToMessage] = useState(!!reportActionIDFromRoute);
const reportActions = useMemo(() => {
if (!sortedAllReportActions.length) {
return [];
}
return ReportActionsUtils.getContinuousReportActionChain(sortedAllReportActions, reportActionIDFromRoute);
}, [reportActionIDFromRoute, sortedAllReportActions]);

const [currentUserAccountID = -1] = useOnyx(ONYXKEYS.SESSION, {selector: (value) => value?.accountID});
const {reportActions, linkedAction} = usePaginatedReportActions(report.reportID, reportActionIDFromRoute);
const isLinkedMessageAvailable = !!linkedAction;
const isLinkedActionDeleted = useMemo(() => !!linkedAction && !ReportActionsUtils.shouldReportActionBeVisible(linkedAction, linkedAction.reportActionID), [linkedAction]);
roryabraham marked this conversation as resolved.
Show resolved Hide resolved
const isLinkedActionInaccessibleWhisper = useMemo(
() => !!linkedAction && ReportActionsUtils.isWhisperAction(linkedAction) && !(linkedAction?.whisperedToAccountIDs ?? []).includes(currentUserAccountID),
roryabraham marked this conversation as resolved.
Show resolved Hide resolved
[currentUserAccountID, linkedAction],
);

// Define here because reportActions are recalculated before mount, allowing data to display faster than useEffect can trigger.
// If we have cached reportActions, they will be shown immediately.
Expand All @@ -287,10 +286,6 @@ function ReportScreen({
const screenWrapperStyle: ViewStyle[] = [styles.appContent, styles.flex1, {marginTop: viewportOffsetTop}];
const isEmptyChat = useMemo(() => ReportUtils.isEmptyReport(report), [report]);
const isOptimisticDelete = report.statusNum === CONST.REPORT.STATUS_NUM.CLOSED;
const isLinkedMessageAvailable = useMemo(
(): boolean => sortedAllReportActions.findIndex((obj) => String(obj.reportActionID) === String(reportActionIDFromRoute)) > -1,
[sortedAllReportActions, reportActionIDFromRoute],
);

// If there's a non-404 error for the report we should show it instead of blocking the screen
const hasHelpfulErrors = Object.keys(report?.errorFields ?? {}).some((key) => key !== 'notFound');
Expand Down Expand Up @@ -662,28 +657,16 @@ function ReportScreen({
fetchReport();
}, [fetchReport]);

const {isLinkedReportActionDeleted, isInaccessibleWhisper} = useMemo(() => {
const currentUserAccountID = getCurrentUserAccountID();
if (!reportActionIDFromRoute || !sortedAllReportActions) {
return {isLinkedReportActionDeleted: false, isInaccessibleWhisper: false};
}
const action = sortedAllReportActions.find((item) => item.reportActionID === reportActionIDFromRoute);
return {
isLinkedReportActionDeleted: action && !ReportActionsUtils.shouldReportActionBeVisible(action, action.reportActionID),
isInaccessibleWhisper: action && ReportActionsUtils.isWhisperAction(action) && !(action?.whisperedToAccountIDs ?? []).includes(currentUserAccountID),
};
}, [reportActionIDFromRoute, sortedAllReportActions]);

// If user redirects to an inaccessible whisper via a deeplink, on a report they have access to,
// then we set reportActionID as empty string, so we display them the report and not the "Not found page".
useEffect(() => {
if (!isInaccessibleWhisper) {
if (!isLinkedActionInaccessibleWhisper) {
return;
}
Navigation.isNavigationReady().then(() => {
Navigation.setParams({reportActionID: ''});
});
}, [isInaccessibleWhisper]);
}, [isLinkedActionInaccessibleWhisper]);

useEffect(() => {
if (!!report.lastReadTime || !ReportUtils.isTaskReport(report)) {
Expand All @@ -693,7 +676,7 @@ function ReportScreen({
Report.readNewestAction(report.reportID);
}, [report]);

if ((!isInaccessibleWhisper && isLinkedReportActionDeleted) ?? (!shouldShowSkeleton && reportActionIDFromRoute && reportActions?.length === 0 && !isLinkingToMessage)) {
if ((!isLinkedActionInaccessibleWhisper && isLinkedActionDeleted) ?? (!shouldShowSkeleton && reportActionIDFromRoute && reportActions?.length === 0 && !isLinkingToMessage)) {
return (
<BlockingView
icon={Illustrations.ToddBehindCloud}
Expand Down Expand Up @@ -807,11 +790,6 @@ export default withCurrentReportID(
isSidebarLoaded: {
key: ONYXKEYS.IS_SIDEBAR_LOADED,
},
sortedAllReportActions: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${getReportID(route)}`,
canEvict: false,
selector: (allReportActions: OnyxEntry<OnyxTypes.ReportActions>) => ReportActionsUtils.getSortedReportActionsForDisplay(allReportActions, true),
},
reportNameValuePairs: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${getReportID(route)}`,
allowStaleData: true,
Expand Down Expand Up @@ -840,7 +818,6 @@ export default withCurrentReportID(
ReportScreen,
(prevProps, nextProps) =>
prevProps.isSidebarLoaded === nextProps.isSidebarLoaded &&
lodashIsEqual(prevProps.sortedAllReportActions, nextProps.sortedAllReportActions) &&
lodashIsEqual(prevProps.reportMetadata, nextProps.reportMetadata) &&
lodashIsEqual(prevProps.betas, nextProps.betas) &&
lodashIsEqual(prevProps.policies, nextProps.policies) &&
Expand Down
Loading
Loading