Skip to content
Merged
2 changes: 2 additions & 0 deletions src/Expensify.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -307,6 +308,7 @@ function Expensify() {
<FullstoryUserContextHandler />
<DeepLinkHandler onInitialUrl={setInitialUrl} />
<AppleAuthWrapper />
{splashScreenState === CONST.BOOT_SPLASH_STATE.HIDDEN && <UnreadIndicatorUpdater />}
{/* 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. */}
Expand Down
2 changes: 0 additions & 2 deletions src/SplashScreenStateContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof CONST.BOOT_SPLASH_STATE>;

Expand All @@ -30,7 +29,6 @@ const SplashScreenActionsContext = React.createContext<SplashScreenActionsContex
function loadPostSplashScreenModules() {
import('./libs/actions/replaceOptimisticReportWithActualReport');
import('./libs/actions/replaceOptimisticAgentWithActualAgent');
loadUnreadIndicatorUpdater();
}

function SplashScreenStateContextProvider({children}: ChildrenProps) {
Expand Down
6 changes: 6 additions & 0 deletions src/components/UnreadIndicatorUpdater/index.android.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Android has no tab title or app badge to update, so skip the work entirely
function UnreadIndicatorUpdater() {
return null;
}

export default UnreadIndicatorUpdater;
46 changes: 46 additions & 0 deletions src/components/UnreadIndicatorUpdater/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {useCurrentReportIDState} from '@hooks/useCurrentReportID';
import useOnyx from '@hooks/useOnyx';
import useReportAttributes from '@hooks/useReportAttributes';

import AppStateMonitor from '@libs/AppStateMonitor';
import UnreadIndicatorUtils from '@libs/UnreadIndicatorUpdater';
import updateUnread, {setUnreadUpdateCallback} from '@libs/UnreadIndicatorUpdater/updateUnread';

import ONYXKEYS from '@src/ONYXKEYS';

import {useEffect} from 'react';

/** Keeps the tab title and app badge unread count in sync. Renders nothing. */
function UnreadIndicatorUpdater() {
const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);
const [reportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
const reportAttributes = useReportAttributes();
const [session] = useOnyx(ONYXKEYS.SESSION);
const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID);
const {currentReportID} = useCurrentReportIDState();
const [draftComment] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${currentReportID}`);

// React Compiler caches this on its inputs, so it only reruns when one of them changes
const unreadReports = UnreadIndicatorUtils.getUnreadReportsForUnreadIndicator(reports, currentReportID, draftComment, {
reportNameValuePairs,
reportActions,
reportAttributes,
currentUserLogin: session?.email,
currentUserAccountID: session?.accountID,
conciergeReportID,
});
const unreadReportIDs = unreadReports.map((report) => 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;
147 changes: 28 additions & 119 deletions src/libs/UnreadIndicatorUpdater/index.ts
Original file line number Diff line number Diff line change
@@ -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<Report> = {};
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<ReportNameValuePairs> = {};
// 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<ReportActions> = {};
// 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<string> = {};
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<Report>, currentReportID: string | undefined, draftComment: string | undefined) {
type UnreadIndicatorData = {
reportNameValuePairs?: OnyxCollection<ReportNameValuePairs>;
reportActions?: OnyxCollection<ReportActions>;
reportAttributes?: ReportAttributesDerivedValue['reports'];
currentUserLogin?: string;
currentUserAccountID?: number;
conciergeReportID?: string;
};

function getUnreadReportsForUnreadIndicator(
reports: OnyxCollection<Report>,
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.
Expand All @@ -90,25 +38,25 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection<Report>, 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,
Expand All @@ -122,51 +70,12 @@ function getUnreadReportsForUnreadIndicator(reports: OnyxCollection<Report>, 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,
});
});
}

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};
6 changes: 0 additions & 6 deletions src/libs/UnreadIndicatorUpdater/load.android.ts

This file was deleted.

7 changes: 0 additions & 7 deletions src/libs/UnreadIndicatorUpdater/load.ts

This file was deleted.

Loading
Loading