diff --git a/src/Expensify.tsx b/src/Expensify.tsx
index 95f2b5c9c911..bde792a3ec89 100644
--- a/src/Expensify.tsx
+++ b/src/Expensify.tsx
@@ -12,6 +12,7 @@ import type {Route} from './ROUTES';
import {useInitialURLActions} from './components/InitialURLContextProvider';
import AppleAuthWrapper from './components/SignInButtons/AppleAuthWrapper';
import SplashScreenHider from './components/SplashScreenHider';
+import UnreadIndicatorUpdater from './components/UnreadIndicatorUpdater';
import CONFIG from './CONFIG';
import CONST from './CONST';
import DeepLinkHandler from './DeepLinkHandler';
@@ -307,6 +308,7 @@ function Expensify() {
+ {splashScreenState === CONST.BOOT_SPLASH_STATE.HIDDEN && }
{/* Wait for the initial URL to resolve before mounting NavigationRoot, because its initialState
is computed once on mount. In HybridApp, getInitialURL() may never resolve (OldDot native
bridge), so we skip this guard to avoid blocking the app. */}
diff --git a/src/SplashScreenStateContext.tsx b/src/SplashScreenStateContext.tsx
index f68b09c5586f..8dbf75e9daee 100644
--- a/src/SplashScreenStateContext.tsx
+++ b/src/SplashScreenStateContext.tsx
@@ -7,7 +7,6 @@ import type ChildrenProps from './types/utils/ChildrenProps';
import CONFIG from './CONFIG';
import CONST from './CONST';
import {addBootsplashBreadcrumb} from './libs/telemetry/bootsplashTelemetry';
-import loadUnreadIndicatorUpdater from './libs/UnreadIndicatorUpdater/load';
type SplashScreenState = ValueOf;
@@ -30,7 +29,6 @@ const SplashScreenActionsContext = React.createContext report?.reportID).filter((reportID): reportID is string => !!reportID);
+
+ useEffect(() => {
+ const publish = () => updateUnread(unreadReportIDs.length, unreadReportIDs);
+ publish();
+ setUnreadUpdateCallback(publish);
+ const unsubscribe = AppStateMonitor.addBecameActiveListener(publish);
+ return unsubscribe;
+ }, [unreadReportIDs]);
+
+ return null;
+}
+
+export default UnreadIndicatorUpdater;
diff --git a/src/libs/UnreadIndicatorUpdater/index.ts b/src/libs/UnreadIndicatorUpdater/index.ts
index f4572dce6ee1..ed3f9d417e3a 100644
--- a/src/libs/UnreadIndicatorUpdater/index.ts
+++ b/src/libs/UnreadIndicatorUpdater/index.ts
@@ -1,84 +1,32 @@
-import AppStateMonitor from '@libs/AppStateMonitor';
-import memoize from '@libs/memoize';
import {getIsOffline} from '@libs/NetworkState';
import {getOneTransactionThreadReportID} from '@libs/ReportActionsUtils';
-import * as ReportUtils from '@libs/ReportUtils';
-
-import Navigation, {navigationRef} from '@navigation/Navigation';
+import {getReportNotificationPreference, hasExpensifyGuidesEmails, isArchivedReport, isDefaultRoom, isHiddenForCurrentUser, isUnread, shouldReportBeInOptionList} from '@libs/ReportUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
-import type {Report, ReportActions, ReportAttributesDerivedValue, ReportNameValuePairs, Session} from '@src/types/onyx';
+import type {Report, ReportActions, ReportAttributesDerivedValue, ReportNameValuePairs} from '@src/types/onyx';
import type {OnyxCollection} from 'react-native-onyx';
-import debounce from 'lodash/debounce';
-import Onyx from 'react-native-onyx';
-
-import updateUnread, {setUnreadUpdateCallback} from './updateUnread';
-
-let allReports: OnyxCollection = {};
-let currentUserAccountID: number = CONST.DEFAULT_NUMBER_ID;
-let currentUserLogin = '';
-let conciergeReportID: string | undefined;
-
-Onyx.connectWithoutView({
- key: ONYXKEYS.SESSION,
- callback: (value: Session | undefined) => {
- currentUserAccountID = value?.accountID ?? CONST.DEFAULT_NUMBER_ID;
- currentUserLogin = value?.email ?? '';
- },
-});
-
-// this utility updates the web tab's title (to display the unread message indicator)
-// which is not a react component, so therefore, there is no way to use useOnyx().
-Onyx.connectWithoutView({
- key: ONYXKEYS.CONCIERGE_REPORT_ID,
- callback: (value) => {
- conciergeReportID = value;
- },
-});
-
-let allReportNameValuePairs: OnyxCollection = {};
-// 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({
- key: ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS,
- callback: (value) => {
- allReportNameValuePairs = value;
- },
-});
-
-let allReportActions: OnyxCollection = {};
-// 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({
- key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
- callback: (value) => {
- allReportActions = value;
- },
-});
-
-let allDraftComments: OnyxCollection = {};
-Onyx.connectWithoutView({
- key: ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT,
- callback: (value) => {
- allDraftComments = value;
- },
-});
-
-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({
- key: ONYXKEYS.DERIVED.REPORT_ATTRIBUTES,
- callback: (value) => {
- reportAttributesDerived = value?.reports;
- },
-});
-
-function getUnreadReportsForUnreadIndicator(reports: OnyxCollection, currentReportID: string | undefined, draftComment: string | undefined) {
+type UnreadIndicatorData = {
+ reportNameValuePairs?: OnyxCollection;
+ reportActions?: OnyxCollection;
+ reportAttributes?: ReportAttributesDerivedValue['reports'];
+ currentUserLogin?: string;
+ currentUserAccountID?: number;
+ conciergeReportID?: string;
+};
+
+function getUnreadReportsForUnreadIndicator(
+ reports: OnyxCollection,
+ currentReportID: string | undefined,
+ draftComment: string | undefined,
+ {reportNameValuePairs, reportActions, reportAttributes, currentUserLogin = '', currentUserAccountID = CONST.DEFAULT_NUMBER_ID, conciergeReportID}: UnreadIndicatorData = {},
+) {
// Read the in-memory offline state directly since this is an imperative one-shot computation (reactivity is not needed here).
const isOffline = getIsOffline();
return Object.values(reports ?? {}).filter((report) => {
- const notificationPreference = ReportUtils.getReportNotificationPreference(report);
+ const notificationPreference = getReportNotificationPreference(report, currentUserAccountID);
/**
* Cheapest predicates first so we reject the large muted/hidden population before doing any expensive work.
@@ -90,25 +38,25 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection, cur
* Furthermore, muted reports may or may not appear in the LHN depending on priority mode,
* but they should not be considered in the unread indicator count.
*/
- if (ReportUtils.isHiddenForCurrentUser(notificationPreference) || notificationPreference === CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE) {
+ if (isHiddenForCurrentUser(notificationPreference) || notificationPreference === CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE) {
return false;
}
- const nameValuePairs = allReportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`];
- const isReportArchived = ReportUtils.isArchivedReport(nameValuePairs);
+ const nameValuePairs = reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`];
+ const isReportArchived = isArchivedReport(nameValuePairs);
const chatReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.chatReportID}`];
- const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, allReportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report?.reportID}`], isOffline);
- const oneTransactionThreadReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`];
+ const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, reportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report?.reportID}`], isOffline);
+ const oneTransactionThreadReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`];
- const derivedIsEmptyReport = report?.reportID ? reportAttributesDerived?.[report.reportID]?.isEmpty : undefined;
- const requiresAttention = report?.reportID ? reportAttributesDerived?.[report.reportID]?.requiresAttention : undefined;
+ const derivedIsEmptyReport = report?.reportID ? reportAttributes?.[report.reportID]?.isEmpty : undefined;
+ const requiresAttention = report?.reportID ? reportAttributes?.[report.reportID]?.requiresAttention : undefined;
- if (!ReportUtils.isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport)) {
+ if (!isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport)) {
return false;
}
// Heaviest predicate runs last, only for unread, non-muted, non-hidden reports — a small fraction of all reports.
- return ReportUtils.shouldReportBeInOptionList({
+ return shouldReportBeInOptionList({
report,
chatReport,
currentReportId: currentReportID,
@@ -122,7 +70,7 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection, cur
currentUserLogin,
currentUserAccountID,
// TODO: Pass guideAccountIDs in Phase B. hasExpensifyGuidesEmails falls back to the personal details store until then. See https://github.com/Expensify/App/issues/66413.
- hasGuidesEmails: ReportUtils.isDefaultRoom(report) ? ReportUtils.hasExpensifyGuidesEmails(Object.keys(report?.participants ?? {}).map(Number), undefined) : false,
+ hasGuidesEmails: isDefaultRoom(report) ? hasExpensifyGuidesEmails(Object.keys(report?.participants ?? {}).map(Number), undefined) : false,
conciergeReportID,
requiresAttention,
derivedIsEmptyReport,
@@ -130,43 +78,4 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection, cur
});
}
-const memoizedGetUnreadReportsForUnreadIndicator = memoize(getUnreadReportsForUnreadIndicator, {maxArgs: 3});
-
-/**
- * Debouncing is used here to limit the frequency of updates to the unread indicator.
- * This ensures that rapid changes in the underlying data (e.g., multiple Onyx updates in quick succession)
- * do not trigger excessive computations or updates, improving performance and avoiding unnecessary overhead.
- */
-const triggerUnreadUpdate = debounce(() => {
- const currentReportID = navigationRef?.isReady?.() ? Navigation.getTopmostReportId() : undefined;
- const draftComment = allDraftComments?.[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${currentReportID}`];
- // We want to keep notification count consistent with what can be accessed from the LHN list
- const unreadReports = memoizedGetUnreadReportsForUnreadIndicator(allReports, currentReportID, draftComment);
-
- updateUnread(
- unreadReports.length,
- unreadReports.map((report) => report?.reportID).filter((reportID): reportID is string => !!reportID),
- );
-}, CONST.TIMING.UNREAD_UPDATE_DEBOUNCE_TIME);
-
-setUnreadUpdateCallback(triggerUnreadUpdate);
-
-// 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({
- key: ONYXKEYS.COLLECTION.REPORT,
- callback: (value) => {
- allReports = value;
- triggerUnreadUpdate();
- },
-});
-
-navigationRef?.addListener?.('state', () => {
- triggerUnreadUpdate();
-});
-
-// Listen for app state changes to update unread count when app becomes active
-AppStateMonitor.addBecameActiveListener(() => {
- triggerUnreadUpdate();
-});
-
export default {getUnreadReportsForUnreadIndicator};
diff --git a/src/libs/UnreadIndicatorUpdater/load.android.ts b/src/libs/UnreadIndicatorUpdater/load.android.ts
deleted file mode 100644
index 742ee81aeff2..000000000000
--- a/src/libs/UnreadIndicatorUpdater/load.android.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-/**
- * `updateUnread` is a no-op on Android (there is no tab title or app icon badge to update), so we skip loading
- * the updater entirely. This keeps the module and its Onyx subscriptions out of the Android bundle, avoiding a
- * walk over every report on each update only to discard the result.
- */
-export default function loadUnreadIndicatorUpdater() {}
diff --git a/src/libs/UnreadIndicatorUpdater/load.ts b/src/libs/UnreadIndicatorUpdater/load.ts
deleted file mode 100644
index 199f443343d5..000000000000
--- a/src/libs/UnreadIndicatorUpdater/load.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-/**
- * Loads the unread indicator updater, which registers the Onyx subscriptions that keep the unread count
- * (browser tab title on web, app icon badge on iOS) in sync.
- */
-export default function loadUnreadIndicatorUpdater() {
- import('.');
-}
diff --git a/tests/ui/UnreadIndicatorUpdaterTest.tsx b/tests/ui/UnreadIndicatorUpdaterTest.tsx
new file mode 100644
index 000000000000..9967520b708d
--- /dev/null
+++ b/tests/ui/UnreadIndicatorUpdaterTest.tsx
@@ -0,0 +1,123 @@
+import {act, render} from '@testing-library/react-native';
+
+import UnreadIndicatorUpdater from '@components/UnreadIndicatorUpdater';
+
+import {useCurrentReportIDState} from '@hooks/useCurrentReportID';
+
+import AppStateMonitor from '@libs/AppStateMonitor';
+import updateUnread from '@libs/UnreadIndicatorUpdater/updateUnread';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+
+import React from 'react';
+import Onyx from 'react-native-onyx';
+
+import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct';
+
+jest.mock('@components/UnreadIndicatorUpdater', () => jest.requireActual<{default: unknown}>('../../src/components/UnreadIndicatorUpdater/index.tsx'));
+jest.mock('@libs/UnreadIndicatorUpdater/updateUnread', () => ({
+ __esModule: true,
+ default: jest.fn(),
+ setUnreadUpdateCallback: jest.fn(),
+}));
+
+jest.mock('@hooks/useCurrentReportID', () => ({
+ useCurrentReportIDState: jest.fn(() => ({currentReportID: undefined})),
+}));
+jest.mock('@libs/AppStateMonitor', () => ({
+ __esModule: true,
+ default: {addBecameActiveListener: jest.fn(() => () => {})},
+}));
+
+const mockUpdateUnread = jest.mocked(updateUnread);
+const mockUseCurrentReportIDState = jest.mocked(useCurrentReportIDState);
+const mockAddBecameActiveListener = jest.mocked(AppStateMonitor.addBecameActiveListener);
+
+const CURRENT_USER_ACCOUNT_ID = 1;
+
+const unreadReport = {
+ reportID: '1',
+ reportName: 'test',
+ type: CONST.REPORT.TYPE.CHAT,
+ participants: {[CURRENT_USER_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS}},
+ lastReadTime: '2023-07-08 07:15:44.030',
+ lastVisibleActionCreated: '2023-08-08 07:15:44.030',
+ lastActorAccountID: 2,
+ lastMessageText: 'test',
+};
+
+describe('UnreadIndicatorUpdater', () => {
+ beforeAll(() => {
+ Onyx.init({keys: ONYXKEYS});
+ });
+
+ beforeEach(async () => {
+ await Onyx.clear();
+ await Onyx.set(ONYXKEYS.SESSION, {accountID: CURRENT_USER_ACCOUNT_ID, email: 'test@test.com'});
+ mockUpdateUnread.mockClear();
+ mockAddBecameActiveListener.mockClear();
+ mockUseCurrentReportIDState.mockReturnValue({currentReportID: undefined});
+ });
+
+ it('publishes the unread count from the reports in Onyx', async () => {
+ // Given a chat the user is in whose last message, from someone else, is newer than the last time it was read
+ await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}1`, unreadReport);
+
+ // When the updater is mounted
+ render();
+ await waitForBatchedUpdatesWithAct();
+
+ // Then the tab title and badge get a count of one, with that report's ID
+ expect(mockUpdateUnread).toHaveBeenLastCalledWith(1, ['1']);
+ });
+
+ it('publishes a new count when a report is read', async () => {
+ // Given the updater is showing one unread report
+ await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}1`, unreadReport);
+ render();
+ await waitForBatchedUpdatesWithAct();
+ expect(mockUpdateUnread).toHaveBeenLastCalledWith(1, ['1']);
+
+ // When the report is read, so its last read time passes its last action
+ await act(() => Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {lastReadTime: '2023-09-08 07:15:44.030'}));
+ await waitForBatchedUpdatesWithAct();
+
+ // Then the count drops to zero without waiting for any other trigger
+ expect(mockUpdateUnread).toHaveBeenLastCalledWith(0, []);
+ });
+
+ it('publishes a new count when the user opens a report that only counts while it is open', async () => {
+ // Given an unread report with no name, which the list skips unless it is the report being viewed
+ await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}1`, {...unreadReport, reportName: undefined});
+ const {rerender} = render();
+ await waitForBatchedUpdatesWithAct();
+ expect(mockUpdateUnread).toHaveBeenLastCalledWith(0, []);
+
+ // When the user navigates to that report
+ mockUseCurrentReportIDState.mockReturnValue({currentReportID: '1'});
+ rerender();
+ await waitForBatchedUpdatesWithAct();
+
+ // Then the count is recomputed for the new current report instead of reusing the old snapshot
+ expect(mockUpdateUnread).toHaveBeenLastCalledWith(1, ['1']);
+ });
+
+ it('republishes the latest count when the app comes back to the foreground', async () => {
+ // Given the updater has published one unread report and the report was then read
+ await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}1`, unreadReport);
+ render();
+ await waitForBatchedUpdatesWithAct();
+ await act(() => Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}1`, {lastReadTime: '2023-09-08 07:15:44.030'}));
+ await waitForBatchedUpdatesWithAct();
+ mockUpdateUnread.mockClear();
+
+ // When the app becomes active, firing the most recently registered listener
+ const becameActive = mockAddBecameActiveListener.mock.calls.at(-1)?.[0];
+ becameActive?.();
+
+ // Then the badge is set again from the latest data, not the count from the first render
+ expect(mockUpdateUnread).toHaveBeenCalledTimes(1);
+ expect(mockUpdateUnread).toHaveBeenLastCalledWith(0, []);
+ });
+});