Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 52 additions & 5 deletions src/hooks/useMarkAsRead.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import DateUtils from '@libs/DateUtils';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types';
Expand All @@ -12,7 +13,9 @@ import type {ReportsSplitNavigatorParamList} from '@navigation/types';
import {readNewestAction} from '@userActions/Report';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type SCREENS from '@src/SCREENS';
import {isLoadingInitialReportActionsSelector} from '@src/selectors/ReportMetaData';
import type * as OnyxTypes from '@src/types/onyx';

import type {OnyxEntry} from 'react-native-onyx';
Expand All @@ -28,6 +31,9 @@ import useIsHiddenWideTabPreMount from './useIsHiddenWideTabPreMount';
import useIsReportActionsLoaded from './useIsReportActionsLoaded';
import useIsReportOutOfSight from './useIsReportOutOfSight';
import useMarkReadAfterReveal from './useMarkReadAfterReveal';
import useNetwork from './useNetwork';
import useOnyx from './useOnyx';
import usePrevious from './usePrevious';
import {useDerivedIsEmptyReport} from './useReportAttributes';
import useReportIsArchived from './useReportIsArchived';

Expand Down Expand Up @@ -91,6 +97,9 @@ type UseMarkAsReadParams = {
isScrolledToEnd: boolean;
hasNewerActions: boolean;

/** The oldest unread action the list opened at. */
oldestUnreadReportActionID?: string;

/** Identifies the list surface consuming the hook, so unrelated surfaces don't share previous-report tracking. */
scopeKey?: string;

Expand All @@ -114,6 +123,7 @@ function useMarkAsRead({
sortedReportActions,
isScrolledToEnd,
hasNewerActions,
oldestUnreadReportActionID,
scopeKey = 'default',
shouldRequireScreenFocus = false,
}: UseMarkAsReadParams): UseMarkAsReadResult {
Expand All @@ -129,6 +139,24 @@ function useMarkAsRead({
const isHiddenFromUser = useIsReportOutOfSight();
const isHiddenPreMount = useIsHiddenWideTabPreMount();
const {markRead, cancelPendingRead} = useMarkReadAfterReveal(reportID, report?.lastReadTime);
const {isOffline} = useNetwork();
// When a saved page reaches the newest end but no saved page holds the oldest unread action, that page was cached
// before those messages came in, so the read waits for OpenReport to bring the up-to-date page.
const [isOldestUnreadActionOutsidePages = false] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS_PAGES}${getNonEmptyStringOnyxID(reportID)}`, {
selector: (pages) =>
!!oldestUnreadReportActionID && !!pages?.some((page) => page.at(0) === CONST.PAGINATION_START_ID) && !pages.some((page) => page.includes(oldestUnreadReportActionID)),
Comment thread
zeryns marked this conversation as resolved.
Resolved
});
const [isLoadingInitialReportActions] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${getNonEmptyStringOnyxID(reportID)}`, {
selector: isLoadingInitialReportActionsSelector,
});
const wasLoadingInitialReportActions = usePrevious(isLoadingInitialReportActions);
// OpenReport can fail and leave the pages as they are, so the wait also ends once it finishes
const hasOpenReportFinished = wasLoadingInitialReportActions === true && isLoadingInitialReportActions === false;
const [isWaitingForUnreadPage, setIsWaitingForUnreadPage] = useState(() => !isOffline && isOldestUnreadActionOutsidePages);
if (isWaitingForUnreadPage && (!isOldestUnreadActionOutsidePages || hasOpenReportFinished)) {
setIsWaitingForUnreadPage(false);
}
const hasUnloadedNewerActions = hasNewerActions || isWaitingForUnreadPage;

const [isVisible, setIsVisible] = useState(Visibility.isVisible);
useEffect(() => {
Expand Down Expand Up @@ -234,7 +262,7 @@ function useMarkAsRead({

didMarkReportAsReadInitially.current = true;

if (hasNewerActions || !isScrolledToEnd) {
if (hasUnloadedNewerActions || !isScrolledToEnd) {
return;
}

Expand Down Expand Up @@ -271,9 +299,10 @@ function useMarkAsRead({
return;
}
const isFromNotification = route?.params?.referrer === CONST.REFERRER.NOTIFICATION;
const shouldReadOnReportChange = ((isVisible && Visibility.hasFocus()) || isFromNotification) && !hasNewerActions && isScrolledToEnd;
const shouldReadOnReportChange = ((isVisible && Visibility.hasFocus()) || isFromNotification) && !hasUnloadedNewerActions && isScrolledToEnd;

if (shouldReadOnReportChange) {
readActionSkippedRef.current = false;
markRead(isReportActionsLoaded);
if (isFromNotification) {
Navigation.setParams({referrer: undefined});
Expand All @@ -291,7 +320,7 @@ function useMarkAsRead({
// skipped read.
useEffect(() => {
handleReportChangeMarkAsRead();
}, [report?.lastVisibleActionCreated, transactionThreadReport?.lastVisibleActionCreated, reportID, isVisible, isReportActionsLoaded, isHiddenFromUser]);
}, [report?.lastVisibleActionCreated, transactionThreadReport?.lastVisibleActionCreated, reportID, isVisible, isReportActionsLoaded, isHiddenFromUser, isWaitingForUnreadPage]);

// isFocused is passed as an arg because the Effect Event closure can be stale (stuck true) on frozen screens,
// re-marking a just-unread report as read on report switch
Expand All @@ -313,7 +342,7 @@ function useMarkAsRead({

// readNewestAction marks everything up to now as read, so newer actions outside the loaded slice would be
// consumed without ever being seen. Mirrors the !hasNewerActions guard on the report-change path.
if (hasNewerActions) {
if (hasUnloadedNewerActions) {
return;
}

Expand Down Expand Up @@ -350,12 +379,30 @@ function useMarkAsRead({
};

const completeSkippedMarkAsRead = () => {
if (!readActionSkippedRef.current || !Visibility.hasFocus()) {
// markNewestActionAsRead marks everything up to now as read, so complete the skipped read only once the
// newer pages are loaded; otherwise unloaded newer actions would be marked read without being seen.
if (!readActionSkippedRef.current || hasUnloadedNewerActions || !Visibility.hasFocus()) {
return;
}
markNewestActionAsRead();
};

// The last newer page can land without changing anything on screen, for example when it only has messages that are already
// shown, and then nothing else would finish a read skipped while newer pages were loading.
const completeSkippedReadOnceNewestLoaded = useEffectEvent(() => {
if (!isScrolledToEnd || !isVisible || !isFocused || isHiddenFromUser) {
return;
}
completeSkippedMarkAsRead();
});

useEffect(() => {
if (hasUnloadedNewerActions) {
return;
}
completeSkippedReadOnceNewestLoaded();
}, [hasUnloadedNewerActions]);

return {markNewestActionAsRead, completeSkippedMarkAsRead};
}

Expand Down
3 changes: 2 additions & 1 deletion src/hooks/useReportActionsScroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,8 @@ function useReportActionsScroll({
}

const shouldFocusToTopOnMount = shouldBeAlignedToTop && !initialScrollKey && !shouldScrollToLatestOnOpen;
const shouldMaintainVisibleContentPosition = hasScrolledOverThreshold || shouldFocusToTopOnMount;
// While newer messages are still on the server, the bottom isn't the live tail, so keep the view in place and let each newer page load below it.
const shouldMaintainVisibleContentPosition = hasScrolledOverThreshold || shouldFocusToTopOnMount || hasNewerActions;
Comment thread
zeryns marked this conversation as resolved.
Resolved
const [shouldAutoscrollToBottom, setShouldAutoscrollToBottom] = useState(shouldFocusToTopOnMount);
const [shouldDisablePillTracking, setShouldDisablePillTracking] = useState(!!initialScrollKey);

Expand Down
2 changes: 2 additions & 0 deletions src/pages/inbox/ActionListTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ type ActionListRef = {
getScrollableNode?: () => unknown;
getLayout?: (index: number) => unknown;
computeVisibleIndices?: () => {startIndex: number; endIndex: number} | undefined;
/** FlashList's last scroll offset, which already includes its own position corrections. Other list implementations can omit this. */
getAbsoluteLastScrollOffset?: () => number;
/** Measured item positions supplied by LegendList. Other list implementations can omit this. */
getState?: () => {positionByKey: (key: string) => number | undefined; scroll?: number; contentLength?: number; scrollLength?: number} | undefined;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps)
sortedVisibleReportActions,
isScrolledToEnd: !hasScrolledOverThreshold,
hasNewerActions,
oldestUnreadReportActionID: oldestUnreadReportAction?.reportActionID,
});

const reportActionsListData = useReportActionsListData({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {ViewableItemsChangedHandler} from '@components/FlashList/types';

import useOnyx from '@hooks/useOnyx';
import useReportActionsScroll from '@hooks/useReportActionsScroll';
import useReportScrollManager from '@hooks/useReportScrollManager';
import useWindowDimensions from '@hooks/useWindowDimensions';
Expand All @@ -13,14 +14,21 @@ import useFollowActionBadgeTarget from '@pages/inbox/report/useFollowActionBadge
import useScrollToEditingReportAction from '@pages/inbox/report/useScrollToEditingReportAction';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {canLoadNewerReportActionsSelector} from '@src/selectors/ReportMetaData';
import type * as OnyxTypes from '@src/types/onyx';

import type {LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';

import {useEffect, useRef} from 'react';
import {useEffect, useEffectEvent, useRef} from 'react';

import type {UseReportActionsListScrollParams} from './types';

const START_REACHED_THRESHOLD = 0.75;

const newestFetchedReportActionIDSelector = (paginationState: OnyxEntry<OnyxTypes.ReportPaginationState>) => paginationState?.newestFetchedReportActionID;

/**
* Create a unique key for each action in the FlatList.
* We use the reportActionID that is a string representation of a random 64-bit int, which should be
Expand Down Expand Up @@ -163,7 +171,16 @@ function useReportActionsListScroll({
loadOlderChats(false);
};

const [newestFetchedReportActionID] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_PAGINATION_STATE}${reportID}`, {selector: newestFetchedReportActionIDSelector});
const [canLoadNewerReportActions = false] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}`, {selector: canLoadNewerReportActionsSelector});
const requestedNewerCursorRef = useRef(newestFetchedReportActionID);
const listHeightRef = useRef(0);

const loadNewerChatsAfterTransitions = () => {
if (!canLoadNewerReportActions) {
return;
}
requestedNewerCursorRef.current = newestFetchedReportActionID;
if (!isSearchTopmostFullScreenRoute()) {
loadNewerChats(false);
return;
Expand All @@ -176,6 +193,22 @@ function useReportActionsListScroll({
});
};

// FlashList won't call onStartReached again while the user stays at the bottom, so ask for the next page when the cursor moves.
const loadNewerChatsIfAtBottom = useEffectEvent(() => {
if (!hasNewerActions || !newestFetchedReportActionID || requestedNewerCursorRef.current === newestFetchedReportActionID || listHeightRef.current <= 0) {
return;
Comment on lines +198 to +199

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Replay start requests skipped during the initial report load

When a partially cached chat already has a cursor and the user reaches its loaded bottom while OpenReport is pending, onStartReached now returns at the loading guard. If OpenReport returns the same page/cursor, clearing the loading flag cannot resume pagination: this comparison matches the cursor used to initialize requestedNewerCursorRef, despite no newer request having been made. Since FlashList has consumed its start-zone callback, newer messages remain unloaded until the user scrolls away and back. Track the deferred start request or initialize the ref as unrequested so finishing the initial load retries it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not sure about this one. I've tested this on native app, desktop and mobile web, but couldn't reproduce it, even when forcing the conditions (failing the first GetNewerActions and delaying OpenReport)

On the first visit in a session, the list remounts after OpenReport finishes, so onStartReached runs again. On later visits, onStartReached fires before OpenReport sets the loading flag, so it isn't skipped and the request just waits for OpenReport to finish

}
const scrollOffset = listRef.current?.getAbsoluteLastScrollOffset?.();
if (scrollOffset === undefined || scrollOffset > listHeightRef.current * START_REACHED_THRESHOLD) {
return;
}
loadNewerChatsAfterTransitions();
});

useEffect(() => {
loadNewerChatsIfAtBottom();
}, [hasNewerActions, newestFetchedReportActionID, canLoadNewerReportActions]);

useFollowActionBadgeTarget({
reportID,
actionTargetReportActionID: actionBadgeTargetID,
Expand All @@ -199,9 +232,11 @@ function useReportActionsListScroll({
getItemType: (item: OnyxTypes.ReportAction) => item.actionName,
onEndReached: loadOlderChatsOnEndReached,
onEndReachedThreshold: 0.75,
onStartReached: loadNewerChatsAfterTransitions,
onStartReachedThreshold: 0.75,
// FlashList calls this once per entry into the start zone, so don't use that call up before there are newer messages.
onStartReached: hasNewerActions ? loadNewerChatsAfterTransitions : undefined,
onStartReachedThreshold: START_REACHED_THRESHOLD,
onLayout: (event: LayoutChangeEvent) => {
listHeightRef.current = event.nativeEvent.layout.height;
onLayout?.(event);
flushPendingScrollToBottom();
},
Expand Down
3 changes: 3 additions & 0 deletions src/selectors/ReportMetaData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ const reportActionsListLoadingStateSelector = (
}
: undefined;

const canLoadNewerReportActionsSelector = (loadingState: OnyxEntry<ReportLoadingState>) => loadingState?.isLoadingInitialReportActions === false && !loadingState.isLoadingNewerReportActions;

const isLoadingInitialReportActionsSelector = (loadingState: OnyxEntry<ReportLoadingState>) => loadingState?.isLoadingInitialReportActions;

const isLoadingReportStatusSelector = (loadingState: OnyxEntry<ReportLoadingState>) => loadingState?.isLoadingReportStatus;
Expand Down Expand Up @@ -149,6 +151,7 @@ export {
hasOnceLoadedReportActionsSelector,
reportActionsLoadingStateSelector,
reportActionsListLoadingStateSelector,
canLoadNewerReportActionsSelector,
isLoadingInitialReportActionsSelector,
isLoadingReportStatusSelector,
isOptimisticReportSelector,
Expand Down
10 changes: 10 additions & 0 deletions tests/ui/PaginationTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ const LIST_CONTENT_SIZE = {
};
const TEN_MINUTES_AGO = subMinutes(new Date(), 10);

const LIST_POSITION_CORRECTION_SETTLE_MS = 150;

const REPORT_ID = '1';
const COMMENT_LINKING_REPORT_ID = '2';
const USER_A_ACCOUNT_ID = 1;
Expand Down Expand Up @@ -392,6 +394,14 @@ describe('Pagination', () => {
TestHelper.expectAPICommandToHaveBeenCalled('GetOlderActions', 0);
TestHelper.expectAPICommandToHaveBeenCalledWith('GetNewerActions', 0, {reportID: REPORT_ID, reportActionID: '5'});

// FlashList ignores scroll events for 100 ms after it keeps the visible messages in place for the newer page.
await act(
() =>
new Promise<void>((resolve) => {
setTimeout(resolve, LIST_POSITION_CORRECTION_SETTLE_MS);
}),
);

// Simulate the maintainVisibleContentPosition scroll adjustment, so it is now possible to scroll down more.
scrollToOffset(500);
await waitForBatchedUpdatesWithAct();
Expand Down
Loading
Loading