Skip to content
Merged
6 changes: 4 additions & 2 deletions src/hooks/useMarkAsRead.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import useAppFocusEvent from './useAppFocusEvent';
import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails';
import useIsAnonymousUser from './useIsAnonymousUser';
import useIsReportActionsLoaded from './useIsReportActionsLoaded';
import {useDerivedIsEmptyReport} from './useReportAttributes';
import useReportIsArchived from './useReportIsArchived';

// useRef gets reset when the reportID changes (the list reuses the same instance per report),
Expand Down Expand Up @@ -116,6 +117,7 @@ function useMarkAsRead({
const route = useRoute<PlatformStackRouteProp<ReportsSplitNavigatorParamList, typeof SCREENS.REPORT>>();
const isFocused = useIsFocused();
const isReportArchived = useReportIsArchived(reportID);
const derivedIsEmptyReport = useDerivedIsEmptyReport(reportID);
const isReportActionsLoaded = useIsReportActionsLoaded(reportID);

const [isVisible, setIsVisible] = useState(Visibility.isVisible);
Expand All @@ -137,7 +139,7 @@ function useMarkAsRead({
const didMarkReportAsReadInitially = useRef(false);

const lastAction = sortedVisibleReportActions.at(0);
const isReportUnreadValue = isUnread(report, transactionThreadReport, isReportArchived) || (!!lastAction && isCurrentActionUnread(report, lastAction));
const isReportUnreadValue = isUnread(report, transactionThreadReport, isReportArchived, derivedIsEmptyReport) || (!!lastAction && isCurrentActionUnread(report, lastAction));

const [instanceID] = useState(() => {
lastInstanceID += 1;
Expand Down Expand Up @@ -195,7 +197,7 @@ function useMarkAsRead({
}

const isLastActionUnread = !!lastAction && isCurrentActionUnread(report, lastAction, sortedVisibleReportActions);
if (!isUnread(report, transactionThreadReport, isReportArchived) && !isLastActionUnread) {
if (!isUnread(report, transactionThreadReport, isReportArchived, derivedIsEmptyReport) && !isLastActionUnread) {
return;
}
const isFromNotification = route?.params?.referrer === CONST.REFERRER.NOTIFICATION;
Expand Down
3 changes: 3 additions & 0 deletions src/hooks/useReportActionsListModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import useOnyx from './useOnyx';
import useParentReportAction from './useParentReportAction';
import useReportActionsPagination from './useReportActionsPagination';
import useReportActionsVisibility from './useReportActionsVisibility';
import {useDerivedIsEmptyReport} from './useReportAttributes';
import useReportIsArchived from './useReportIsArchived';

/**
Expand Down Expand Up @@ -65,6 +66,7 @@ function useReportActionsListModel(reportID: string, isReportLoadPending: boolea
const shouldBeAlignedToTop = shouldReportAlignToTop(report, parentReportAction);

const isReportArchived = useReportIsArchived(reportID);
const derivedIsEmptyReport = useDerivedIsEmptyReport(reportID);
const canPerformWriteAction = !!canUserPerformWriteAction(report, isReportArchived);

const isAppLoadPending = useIsAppLoadPending();
Expand Down Expand Up @@ -138,6 +140,7 @@ function useReportActionsListModel(reportID: string, isReportLoadPending: boolea
isConciergeMainDM,
hasCachedReportActions,
showConciergeSidePanelWelcome,
derivedIsEmptyReport,
};

// The render state slice on `ReportActionsListStateContext`; this is what drives list re-renders.
Expand Down
17 changes: 15 additions & 2 deletions src/hooks/useReportAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type {ReportAttributesDerivedValue} from '@src/types/onyx';

import type {OnyxEntry} from 'react-native-onyx';

import {reportNameSelector} from '@selectors/ReportAttributes';
import {reportIsEmptySelector, reportNameSelector} from '@selectors/ReportAttributes';

import useOnyx from './useOnyx';

Expand Down Expand Up @@ -68,5 +68,18 @@ function useDerivedReportNamesByReportIDs(reportIDs: Array<string | undefined>)
return reportNames;
}

/**
* Returns a single report's cached `isEmpty` flag using a selector.
*
* The selector output is a primitive boolean, so its comparison is trivial and the component re-renders only when
* that specific report's emptiness changes — not on every global report attribute change.
*/
function useDerivedIsEmptyReport(reportID: string | undefined) {
const [isEmpty] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, {
selector: (value: OnyxEntry<ReportAttributesDerivedValue>) => reportIsEmptySelector(value, reportID),
});
return isEmpty;
}

export default useReportAttributes;
export {useReportAttributesByID, useDerivedReportNameByReportID, useDerivedReportNamesByReportIDs};
export {useReportAttributesByID, useDerivedReportNameByReportID, useDerivedReportNamesByReportIDs, useDerivedIsEmptyReport};
3 changes: 3 additions & 0 deletions src/libs/DebugUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1528,6 +1528,7 @@ function getReasonForShowingRowInLHN({
currentUserAccountID,
conciergeReportID,
hasGuidesEmails,
derivedIsEmptyReport,
}: {
report: OnyxEntry<Report>;
chatReport: OnyxEntry<Report>;
Expand All @@ -1541,6 +1542,7 @@ function getReasonForShowingRowInLHN({
currentUserAccountID?: number;
hasGuidesEmails: boolean;
conciergeReportID: string | undefined;
derivedIsEmptyReport: boolean | undefined;
}): TranslationPaths | null {
if (!report) {
return null;
Expand All @@ -1561,6 +1563,7 @@ function getReasonForShowingRowInLHN({
currentUserLogin,
currentUserAccountID,
conciergeReportID,
derivedIsEmptyReport,
hasGuidesEmails,
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import useOnyx from '@hooks/useOnyx';
import useReportAttributes from '@hooks/useReportAttributes';

import markAllMessagesAsRead from '@libs/actions/Report/MarkAllMessageAsRead';
import KeyboardShortcut from '@libs/KeyboardShortcut';
Expand All @@ -11,19 +12,25 @@ import {useEffect, useRef} from 'react';

function MarkAllMessagesAsReadHandler() {
const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, {selector: reportNameValuePairsArchivedSelector});
const reportAttributesDerived = useReportAttributes();
// The keyboard-shortcut callback below is registered once on mount, so keep the latest archived state in a ref
// for it to read at fire time instead of closing over a stale value.
const reportNameValuePairsRef = useRef(reportNameValuePairs);
const reportAttributesDerivedRef = useRef(reportAttributesDerived);

useEffect(() => {
reportNameValuePairsRef.current = reportNameValuePairs;
}, [reportNameValuePairs]);

useEffect(() => {
reportAttributesDerivedRef.current = reportAttributesDerived;
}, [reportAttributesDerived]);

useEffect(() => {
const shortcutConfig = CONST.KEYBOARD_SHORTCUTS.MARK_ALL_MESSAGES_AS_READ;
const unsubscribe = KeyboardShortcut.subscribe(
shortcutConfig.shortcutKey,
() => markAllMessagesAsRead(reportNameValuePairsRef.current),
() => markAllMessagesAsRead(reportNameValuePairsRef.current, undefined, reportAttributesDerivedRef.current),
shortcutConfig.descriptionKey,
shortcutConfig.modifiers,
true,
Expand Down
5 changes: 4 additions & 1 deletion src/libs/OptionsListUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1829,6 +1829,7 @@ function isValidReport(
draftComment: string | undefined,
chatReport: OnyxEntry<Report>,
hasGuidesEmails: boolean,
derivedIsEmptyReport: boolean | undefined,
): boolean {
const {
isDefaultRoomsBetaEnabled = false,
Expand Down Expand Up @@ -1874,6 +1875,7 @@ function isValidReport(
currentUserAccountID,
conciergeReportID,
hasGuidesEmails,
derivedIsEmptyReport,
});

if (!shouldBeInOptionList) {
Expand Down Expand Up @@ -2069,7 +2071,7 @@ function prepareReportOptionsForDisplay(
: undefined;
const oneTransactionThreadReport = oneTransactionThreadReportID ? allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`] : undefined;

isOptionUnread = isUnread(report, oneTransactionThreadReport, option.private_isArchived) && !!report.lastActorAccountID;
isOptionUnread = isUnread(report, oneTransactionThreadReport, option.private_isArchived, reportAttributesDerived?.[report.reportID]?.isEmpty) && !!report.lastActorAccountID;
}

let lastIOUCreationDate;
Expand Down Expand Up @@ -2284,6 +2286,7 @@ function getValidOptions(
chatReport,
// TODO: Pass guideAccountIDs once callers are fully migrated — PR 33 (https://github.com/Expensify/App/issues/66413); hasExpensifyGuidesEmails falls back to allPersonalDetails
isDefaultRoom(report.item) ? hasExpensifyGuidesEmails(Object.keys(report.item?.participants ?? {}).map(Number), undefined) : false,
report.reportID ? reportAttributesDerived?.[report.reportID]?.isEmpty : undefined,
);
};

Expand Down
37 changes: 14 additions & 23 deletions src/libs/ReportUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1219,14 +1219,6 @@ Onyx.connect({
},
});

let reportAttributesDerivedValue: ReportAttributesDerivedValue['reports'];
Onyx.connect({
key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES,
callback: (value) => {
reportAttributesDerivedValue = value?.reports ?? {};
},
});

let cachedSelfDMReportID: OnyxEntry<string>;
Onyx.connect({
key: ONYXKEYS.SELF_DM_REPORT_ID,
Expand Down Expand Up @@ -9610,20 +9602,15 @@ function buildOptimisticMoneyRequestEntities({

/**
* Check if the report is empty, meaning it has no visible messages (i.e. only a "created" report action).
* Added caching mechanism via derived values.
*
* @param derivedIsEmptyReport Always prefer passing this cached flag for this report from ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, i.e.
* `reportAttributes?.[reportID]?.isEmpty`.
*/
function isEmptyReport(report: OnyxEntry<Report>, isReportArchived: boolean | undefined): boolean {
function isEmptyReport(report: OnyxEntry<Report>, isReportArchived: boolean | undefined, derivedIsEmptyReport: boolean | undefined): boolean {
if (!report) {
return true;
}

// Get the `isEmpty` state from cached report attributes
const attributes = reportAttributesDerivedValue?.[report.reportID];
if (attributes) {
return attributes.isEmpty;
}

return generateIsEmptyReport(report, isReportArchived);
return derivedIsEmptyReport ?? generateIsEmptyReport(report, isReportArchived);
}

/**
Expand Down Expand Up @@ -9723,12 +9710,12 @@ function generateIsEmptyReport(report: OnyxEntry<Report>, isReportArchived: bool
}

// We need oneTransactionThreadReport to get the correct last visible action created
function isUnread(report: OnyxEntry<Report>, oneTransactionThreadReport: OnyxEntry<Report>, isReportArchived: boolean | undefined): boolean {
function isUnread(report: OnyxEntry<Report>, oneTransactionThreadReport: OnyxEntry<Report>, isReportArchived: boolean | undefined, derivedIsEmptyReport: boolean | undefined): boolean {
if (!report) {
return false;
}

if (isEmptyReport(report, isReportArchived)) {
if (isEmptyReport(report, isReportArchived, derivedIsEmptyReport)) {
return false;
}

Expand Down Expand Up @@ -10270,6 +10257,8 @@ type ShouldReportBeInOptionListParams = {
conciergeReportID: string | undefined;
/** Pre-computed value from reportAttributes derived value. When provided, skips the expensive requiresAttentionFromCurrentUser recomputation. */
requiresAttention?: boolean;
/** Pre-computed isEmpty flag from reportAttributes derived value. When provided, skips the module-level reportAttributesDerivedValue read inside isEmptyReport. */
derivedIsEmptyReport: boolean | undefined;
hasGuidesEmails: boolean;
};

Expand All @@ -10290,6 +10279,7 @@ function reasonForReportToBeInOptionList({
isReportArchived,
conciergeReportID,
requiresAttention,
derivedIsEmptyReport,
hasGuidesEmails,
}: ShouldReportBeInOptionListParams): ValueOf<typeof CONST.REPORT_IN_LHN_REASONS> | null {
const isInDefaultMode = !isInFocusMode;
Expand Down Expand Up @@ -10338,7 +10328,7 @@ function reasonForReportToBeInOptionList({
// We used to use the system DM for A/B testing onboarding tasks, but now only create them in the Concierge chat. We
// still need to allow existing users who have tasks in the system DM to see them, but otherwise we don't need to
// show that chat
if (report?.participants?.[CONST.ACCOUNT_ID.NOTIFICATIONS] && isEmptyReport(report, isReportArchived)) {
if (report?.participants?.[CONST.ACCOUNT_ID.NOTIFICATIONS] && isEmptyReport(report, isReportArchived, derivedIsEmptyReport)) {
return null;
}

Expand Down Expand Up @@ -10375,7 +10365,7 @@ function reasonForReportToBeInOptionList({
return CONST.REPORT_IN_LHN_REASONS.HAS_GBR;
}

const isEmptyChat = isEmptyReport(report, isReportArchived);
const isEmptyChat = isEmptyReport(report, isReportArchived, derivedIsEmptyReport);
const canHideReport = shouldHideReport(report, currentReportId, isReportArchived);

// Drafts already return early above, so no draft check needed here
Expand Down Expand Up @@ -10416,7 +10406,7 @@ function reasonForReportToBeInOptionList({
if (isInFocusMode) {
const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, currentReportActions);
const oneTransactionThreadReport = deprecatedAllReports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`];
return isUnread(report, oneTransactionThreadReport, isReportArchived) && getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE
return isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport) && getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE
? CONST.REPORT_IN_LHN_REASONS.IS_UNREAD
: null;
}
Expand Down Expand Up @@ -14473,6 +14463,7 @@ export {
isDefaultRoom,
isDeprecatedGroupDM,
generateIsEmptyReport,
isEmptyReport,
isRootGroupChat,
isExpenseReport,
isExpenseRequest,
Expand Down
15 changes: 10 additions & 5 deletions src/libs/SidebarUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ function shouldDisplayReportInLHN({
includeSelfDM: true,
isReportArchived,
requiresAttention,
derivedIsEmptyReport: reportAttributes?.[report?.reportID]?.isEmpty,
currentUserLogin,
currentUserAccountID,
conciergeReportID,
Expand Down Expand Up @@ -305,7 +306,7 @@ function getReportsToDisplayInLHN({

if (shouldDisplay) {
const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention ?? false;
const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived);
const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived, reportAttributes?.[report?.reportID]?.isEmpty);
reportsToDisplay[reportID] =
requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport ? {...report, requiresAttention, hasErrorsOtherThanFailedReceipt, isUnreadReport} : report;
}
Expand Down Expand Up @@ -394,7 +395,7 @@ function updateReportsToDisplayInLHN({

if (shouldDisplay) {
const requiresAttention = reportAttributes?.[report?.reportID]?.requiresAttention ?? false;
const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived);
const isUnreadReport = getIsUnreadReportForInboxTab(report, isReportArchived, reportAttributes?.[report?.reportID]?.isEmpty);
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const hasFlags = requiresAttention || hasErrorsOtherThanFailedReceipt || isUnreadReport;
const existingEntry = displayedReports[reportID];
Expand Down Expand Up @@ -827,7 +828,7 @@ function getOptionData({
result.statusNum = report.statusNum;
// When the only message of a report is deleted lastVisibleActionCreated is not reset leading to wrongly
// setting it Unread so we add additional condition here to avoid empty chat LHN from being bold.
result.isUnread = isUnread(report, oneTransactionThreadReport, isReportArchived) && !!report.lastActorAccountID;
result.isUnread = isUnread(report, oneTransactionThreadReport, isReportArchived, reportAttributes?.isEmpty) && !!report.lastActorAccountID;
result.isUnreadWithMention = isUnreadWithMention(report);
result.isPinned = report.isPinned;
result.iouReportID = report.iouReportID;
Expand Down Expand Up @@ -975,10 +976,14 @@ function getOptionData({
* Whether a report should appear in the "Unread" Inbox tab: it has unread messages and is not muted.
* Computed once while building the LHN report set (which is cached/incremental) so the tab filter only reads a flag.
*/
function getIsUnreadReportForInboxTab(report: Report, isReportArchived: boolean): boolean {
function getIsUnreadReportForInboxTab(report: Report, isReportArchived: boolean, derivedIsEmptyReport: boolean | undefined): boolean {
// The `lastActorAccountID` guard matches getOptionData: it keeps chats whose only visible message was
// deleted out of the Unread tab even though isUnread() can still be true (lastVisibleActionCreated isn't reset).
return isUnread(report, undefined, isReportArchived) && !!report.lastActorAccountID && getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE;
return (
isUnread(report, undefined, isReportArchived, derivedIsEmptyReport) &&
!!report.lastActorAccountID &&
getReportNotificationPreference(report) !== CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE
);
}

/** Whether a report belongs in the "To-do" Inbox tab: it has an outstanding GBR (requiresAttention) or RBR (errors). */
Expand Down
16 changes: 14 additions & 2 deletions src/libs/UnreadIndicatorUpdater/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import Navigation, {navigationRef} from '@navigation/Navigation';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Report, ReportActions, ReportNameValuePairs, Session} from '@src/types/onyx';
import type {Report, ReportActions, ReportAttributesDerivedValue, ReportNameValuePairs, Session} from '@src/types/onyx';

import type {OnyxCollection} from 'react-native-onyx';

Expand Down Expand Up @@ -65,6 +65,15 @@ Onyx.connectWithoutView({
},
});

let reportAttributesDerived: ReportAttributesDerivedValue['reports'] | undefined;
// This subscription is used to update the unread indicators count which is not linked to UI and it does not update any UI state.
Onyx.connectWithoutView({
Comment thread
hoangzinh marked this conversation as resolved.
Resolved
Comment on lines +68 to +70

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can you please leave a clear comment why its fine to use it here? thanks

@hoangzinh hoangzinh Sep 12, 2026 •

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.

Yes, I done in a24baed and added comment explaining this subscription updates the unread indicator count, which is not linked to UI and doesn't update any UI state

key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES,
callback: (value) => {
reportAttributesDerived = value?.reports;
},
});

function getUnreadReportsForUnreadIndicator(reports: OnyxCollection<Report>, currentReportID: string | undefined, draftComment: string | undefined) {
// Read the in-memory offline state directly since this is an imperative one-shot computation (reactivity is not needed here).
const isOffline = getIsOffline();
Expand All @@ -91,7 +100,9 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection<Report>, cur
const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report?.reportID}`], isOffline);
const oneTransactionThreadReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`];

if (!ReportUtils.isUnread(report, oneTransactionThreadReport, isReportArchived)) {
const derivedIsEmptyReport = report?.reportID ? reportAttributesDerived?.[report.reportID]?.isEmpty : undefined;

if (!ReportUtils.isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport)) {
return false;
}

Expand All @@ -112,6 +123,7 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection<Report>, cur
// TODO: Pass guideAccountIDs once callers are fully migrated — PR 33 (https://github.com/Expensify/App/issues/66413); hasExpensifyGuidesEmails falls back to allPersonalDetails
hasGuidesEmails: ReportUtils.isDefaultRoom(report) ? ReportUtils.hasExpensifyGuidesEmails(Object.keys(report?.participants ?? {}).map(Number), undefined) : false,
conciergeReportID,
derivedIsEmptyReport,
});
});
}
Expand Down
Loading
Loading