diff --git a/__mocks__/react-native-onyx.ts b/__mocks__/react-native-onyx.ts index 6db22ac1b627..f5b09f2949da 100644 --- a/__mocks__/react-native-onyx.ts +++ b/__mocks__/react-native-onyx.ts @@ -5,7 +5,7 @@ import type {ConnectOptions, OnyxKey} from 'react-native-onyx'; // eslint-disable-next-line no-restricted-imports -import Onyx, {useOnyx} from 'react-native-onyx'; +import Onyx, {useOnyx, useOnyxState} from 'react-native-onyx'; let connectCallbackDelay = 0; function addDelayToConnectCallback(delay: number) { @@ -41,4 +41,4 @@ const reactNativeOnyxMock: ReactNativeOnyxMock = { export default reactNativeOnyxMock; -export {useOnyx}; +export {useOnyx, useOnyxState}; diff --git a/src/components/ReportActionAvatars/index.tsx b/src/components/ReportActionAvatars/index.tsx index 4b7f928aeca5..3723fc1b3df0 100644 --- a/src/components/ReportActionAvatars/index.tsx +++ b/src/components/ReportActionAvatars/index.tsx @@ -84,6 +84,29 @@ type ReportActionAvatarsProps = { shouldUseRealActor?: boolean; }; +type ReportActionAvatarsViewProps = Pick< + ReportActionAvatarsProps, + | 'horizontalStacking' + | 'sort' + | 'size' + | 'singleAvatarContainerStyle' + | 'backdropColor' + | 'subscriptAvatarContainerStyle' + | 'subscriptCardFeed' + | 'subscriptCardFeedIconSize' + | 'isInReportAction' + | 'fallbackDisplayName' +> & { + avatarType: ValueOf; + avatars: IconType[]; + /** The copilot who acted for the actor, or undefined when the actor acted themselves */ + delegateAccountID: number | undefined; + shouldUseConciergeAvatar: boolean; + + /** The action resolved by useReportActionAvatars (its source.action), used to read the copilot delegate */ + action: OnyxEntry; +}; + /** * The component that renders proper user avatars based on either: * @@ -100,24 +123,15 @@ function ReportActionAvatars({ accountIDs: passedAccountIDs = [], policyID, policy: policyProp, - size = CONST.AVATAR_SIZE.DEFAULT, horizontalStacking, - sort: sortAvatars, - singleAvatarContainerStyle, - backdropColor, - subscriptAvatarContainerStyle, subscriptCardFeed, - subscriptCardFeedIconSize, - isInReportAction = false, fallbackDisplayName, invitedEmailsToAccountIDs, chatReportID, shouldUseRealActor = false, + ...viewProps }: ReportActionAvatarsProps) { const accountIDs = passedAccountIDs.filter((accountID) => accountID !== CONST.DEFAULT_NUMBER_ID); - const allPersonalDetails = usePersonalDetails(); - const {localeCompare} = useLocalize(); - const StyleUtils = useStyleUtils(); const reportID = potentialReportID ?? @@ -129,19 +143,10 @@ function ReportActionAvatars({ // Therefore, we will fall back to reportProp while the data is being fetched. const report = reportFromOnyx ?? reportProp; - const shouldStackHorizontally = !!horizontalStacking; - const isHorizontalStackingAnObject = shouldStackHorizontally && typeof horizontalStacking !== 'boolean'; - const {isHovered = false, ...horizontalStackingRest} = isHorizontalStackingAnObject ? horizontalStacking : ({} as HorizontalStackingOptions); - - const { - avatarType: notPreciseAvatarType, - avatars: unsortedIcons, - details: {delegateAccountID, shouldUseConciergeAvatar}, - source, - } = useReportActionAvatars({ + const {avatarType, avatars, details, source} = useReportActionAvatars({ report, action, - shouldStackHorizontally, + shouldStackHorizontally: !!horizontalStacking, shouldUseCardFeed: !!subscriptCardFeed, accountIDs, policyID, @@ -152,6 +157,47 @@ function ReportActionAvatars({ shouldUseRealActor, }); + return ( + + ); +} + +/** Renders avatars that `useReportActionAvatars` already computed, for callers that run the hook themselves. */ +function ReportActionAvatarsView({ + avatarType: notPreciseAvatarType, + avatars: unsortedIcons, + delegateAccountID, + shouldUseConciergeAvatar, + action, + size = CONST.AVATAR_SIZE.DEFAULT, + horizontalStacking, + sort: sortAvatars, + singleAvatarContainerStyle, + backdropColor, + subscriptAvatarContainerStyle, + subscriptCardFeed, + subscriptCardFeedIconSize, + isInReportAction = false, + fallbackDisplayName, +}: ReportActionAvatarsViewProps) { + const allPersonalDetails = usePersonalDetails(); + const {localeCompare} = useLocalize(); + const StyleUtils = useStyleUtils(); + + const shouldStackHorizontally = !!horizontalStacking; + const isHorizontalStackingAnObject = shouldStackHorizontally && typeof horizontalStacking !== 'boolean'; + const {isHovered = false, ...horizontalStackingRest} = isHorizontalStackingAnObject ? horizontalStacking : ({} as HorizontalStackingOptions); + if (!unsortedIcons.length) { return null; } @@ -190,7 +236,7 @@ function ReportActionAvatars({ // Read the copilot through `getDelegateAccountIDFromReportAction` rather than off the action: the server stamps // `delegateAccountID` on every action a copilot's request creates, including Concierge-authored ones, and the // accessor suppresses it there so Concierge never renders as " (as copilot for Concierge)". - const delegateAccountIDFromAction = shouldUseConciergeAvatar ? undefined : getDelegateAccountIDFromReportAction(source.action); + const delegateAccountIDFromAction = shouldUseConciergeAvatar ? undefined : getDelegateAccountIDFromReportAction(action); const singleAvatar: AvatarIcon = delegateAccountID && delegateAccountIDFromAction ? { @@ -266,3 +312,4 @@ function ReportActionAvatars({ } export default ReportActionAvatars; +export {ReportActionAvatarsView}; diff --git a/src/components/ReportActionAvatars/useReportPreviewSenderID.ts b/src/components/ReportActionAvatars/useReportPreviewSenderID.ts index ccfadb35274a..e06040124750 100644 --- a/src/components/ReportActionAvatars/useReportPreviewSenderID.ts +++ b/src/components/ReportActionAvatars/useReportPreviewSenderID.ts @@ -3,7 +3,6 @@ import type {PersonalDetailsByLogin} from '@components/PersonalDetailsByLoginPro import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useOnyx from '@hooks/useOnyx'; import {usePersonalDetailsByLogins} from '@hooks/usePersonalDetailByLogin'; -import useTransactionsAndViolationsForReport from '@hooks/useTransactionsAndViolationsForReport'; import {convertAttendeesToArray} from '@libs/AttendeeUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; @@ -19,6 +18,8 @@ import type {OriginalMessageIOU, Policy, Report, ReportAction, ReportActions, Tr import type {OnyxEntry} from 'react-native-onyx'; +import {useOnyxState} from 'react-native-onyx'; + function getSplitAuthor(transaction: Transaction, splits?: Array>) { const {originalTransactionID, source} = transaction.comment ?? {}; @@ -306,7 +307,14 @@ function useReportPreviewSenderID({iouReport, action, chatReport}: {action: Onyx }); const hasFinishedInitialReportActionsLoad = hasOnceLoadedReportActions === true || isLoadingInitialReportActions === false; - const {transactions: reportTransactions} = useTransactionsAndViolationsForReport(shouldFetchData ? action?.childReportID : undefined); + // Reads only this report's entry, so writes to other reports' transactions don't re-render every avatar in the list + const transactionsReportID = shouldFetchData ? action?.childReportID : undefined; + const reportTransactions = useOnyxState( + (state) => (transactionsReportID ? state[ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS]?.[transactionsReportID]?.transactions : undefined), + { + dependencies: transactionsReportID ? [ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS] : [], + }, + ); let transactions; if (!shouldFetchData) { transactions = undefined; diff --git a/src/hooks/useOnyxStateSnapshotKey.ts b/src/hooks/useOnyxStateSnapshotKey.ts new file mode 100644 index 000000000000..808a4e40513e --- /dev/null +++ b/src/hooks/useOnyxStateSnapshotKey.ts @@ -0,0 +1,39 @@ +// Lets useOnyxState selectors read from the same Search snapshot that @hooks/useOnyx redirects to. +import {SearchQueryContext, SearchResultsContext} from '@components/Search/SearchContext'; +import {useIsOnSearch} from '@components/Search/SearchScopeProvider'; + +import ONYXKEYS from '@src/ONYXKEYS'; + +import type {OnyxKey, OnyxValue} from 'react-native-onyx'; + +import {use} from 'react'; + +type SnapshotKey = `${typeof ONYXKEYS.COLLECTION.SNAPSHOT}${number}`; + +/** + * Returns the Search snapshot key that `@hooks/useOnyx` would read snapshot-compatible keys from, or undefined when + * live data is used. `useOnyxState` selectors pass it to `getSnapshotAwareValue` to keep the same data source. + */ +function useOnyxStateSnapshotKey(): SnapshotKey | undefined { + const isOnSearch = useIsOnSearch(); + const {currentSearchHash} = use(SearchQueryContext); + const {shouldUseLiveData} = use(SearchResultsContext); + if (!isOnSearch || !currentSearchHash || shouldUseLiveData) { + return undefined; + } + return `${ONYXKEYS.COLLECTION.SNAPSHOT}${currentSearchHash}`; +} + +/** Only for snapshot-compatible member keys (report, report actions, policy, transaction...). */ +function getSnapshotAwareValue(state: {readonly [K in TKey | SnapshotKey]: OnyxValue}, snapshotKey: SnapshotKey | undefined, key: TKey): OnyxValue { + if (!snapshotKey) { + return state[key]; + } + // The snapshot's data holds the same keys and value types as live Onyx, but TypeScript can't link them through the generic key + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion + return state[snapshotKey]?.data?.[key as keyof NonNullable>['data']] as OnyxValue; +} + +export default useOnyxStateSnapshotKey; +export {getSnapshotAwareValue}; +export type {SnapshotKey}; diff --git a/src/hooks/useOriginalReportID.ts b/src/hooks/useOriginalReportID.ts index b02eca20ac44..aec3b991973e 100644 --- a/src/hooks/useOriginalReportID.ts +++ b/src/hooks/useOriginalReportID.ts @@ -3,14 +3,14 @@ import {getOneTransactionThreadReportID, withDEWRoutedActionsObject} from '@libs import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {OnyxInputOrEntry, ReportAction, ReportActions} from '@src/types/onyx'; - -import type {OnyxEntry} from 'react-native-onyx'; +import type {OnyxInputOrEntry, ReportAction} from '@src/types/onyx'; import {reportTypeAndParentIDsSelector} from '@selectors/Report'; +import {useOnyxState} from 'react-native-onyx'; import useNetwork from './useNetwork'; import useOnyx from './useOnyx'; +import useOnyxStateSnapshotKey, {getSnapshotAwareValue} from './useOnyxStateSnapshotKey'; import useReportTransactionsCollection from './useReportTransactionsCollection'; /** @@ -30,17 +30,20 @@ function useOriginalReportID(reportID: string | undefined, reportAction: OnyxInp const reportActionID = reportAction?.reportActionID; const isThreadReportParentAction = reportAction?.childReportID?.toString() === reportID; - const reportActionBelongsCurrentReportSelector = (actions: OnyxEntry) => { - if (!reportActionID) { - return false; - } - if (Object.keys(actions?.[reportActionID] ?? {}).length > 0) { - return true; - } - return Object.keys(withDEWRoutedActionsObject(actions)?.[reportActionID] ?? {}).length > 0; - }; - const [reportActionBelongsCurrentReport = false] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, {selector: reportActionBelongsCurrentReportSelector}); - const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {selector: reportTypeAndParentIDsSelector}); + const snapshotKey = useOnyxStateSnapshotKey(); + const reportKey = `${ONYXKEYS.COLLECTION.REPORT}${reportID}` as const; + const reportActionsKey = `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}` as const; + const {reportActionBelongsCurrentReport, report} = useOnyxState( + (state) => { + const actions = getSnapshotAwareValue(state, snapshotKey, reportActionsKey); + let belongs = false; + if (reportActionID) { + belongs = Object.keys(actions?.[reportActionID] ?? {}).length > 0 || Object.keys(withDEWRoutedActionsObject(actions)?.[reportActionID] ?? {}).length > 0; + } + return {reportActionBelongsCurrentReport: belongs, report: reportTypeAndParentIDsSelector(getSnapshotAwareValue(state, snapshotKey, reportKey))}; + }, + {dependencies: snapshotKey ? [snapshotKey] : [reportKey, reportActionsKey]}, + ); // The full actions, chat report and transactions are only needed to find a merged transaction thread, so rows whose action is in the current report don't subscribe to them const lookupReportID = reportID && !reportActionBelongsCurrentReport && !isThreadReportParentAction && reportActionID ? reportID : undefined; diff --git a/src/hooks/useReportActionsPagination.ts b/src/hooks/useReportActionsPagination.ts index 3a272630103c..1f41cb0b657a 100644 --- a/src/hooks/useReportActionsPagination.ts +++ b/src/hooks/useReportActionsPagination.ts @@ -6,6 +6,7 @@ import {isConciergeChatReport, isInvoiceReport, isMoneyRequestReport, isReportTr import getReportActionsToDisplay from '@pages/inbox/report/getReportActionsToDisplay'; import ONYXKEYS from '@src/ONYXKEYS'; +import {reportWithoutLastActivitySelector} from '@src/selectors/Report'; import type {Report, ReportAction} from '@src/types/onyx'; import type {OnyxEntry} from 'react-native-onyx'; @@ -38,7 +39,8 @@ type UseReportActionsPaginationResult = { }; function useReportActionsPagination(reportID: string | undefined, reportActionIDFromRoute: string | undefined): UseReportActionsPaginationResult { - const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); + // Last-activity fields don't change which actions are shown, so writes to them shouldn't rebuild the list data + const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {selector: reportWithoutLastActivitySelector}); const {isOffline} = useNetwork(); const {getCurrencyDecimals} = useCurrencyListActions(); const delegateAccountID = useDelegateAccountID(); diff --git a/src/hooks/useReportActionsVisibility.ts b/src/hooks/useReportActionsVisibility.ts index 0ec24550afc0..c3248cd436e5 100644 --- a/src/hooks/useReportActionsVisibility.ts +++ b/src/hooks/useReportActionsVisibility.ts @@ -7,6 +7,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type {ReportAction} from '@src/types/onyx'; import {reportVisibleActionsSelector} from '@selectors/ReportAction'; +import {useOnyxState} from 'react-native-onyx'; import useConciergeSidePanelReportActions from './useConciergeSidePanelReportActions'; import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; @@ -15,7 +16,6 @@ import useLocalize from './useLocalize'; import useNetwork from './useNetwork'; import useOnyx from './useOnyx'; import useSidePanelState from './useSidePanelState'; -import useTransactionsAndViolationsForReport from './useTransactionsAndViolationsForReport'; type UseReportActionsVisibilityParams = { reportID: string | undefined; @@ -74,7 +74,17 @@ function useReportActionsVisibility({ ) : false; - const {transactions: reportTransactions, isLoaded: areTransactionsLoaded} = useTransactionsAndViolationsForReport(reportID); + // Reads only this report's transactions, so writes to other reports' transactions don't re-render the list + const {reportTransactions, areTransactionsLoaded} = useOnyxState( + (state) => { + const allReportsTransactionsAndViolations = state[ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS]; + return { + reportTransactions: reportID ? allReportsTransactionsAndViolations?.[reportID]?.transactions : undefined, + areTransactionsLoaded: allReportsTransactionsAndViolations !== undefined, + }; + }, + {dependencies: [ONYXKEYS.DERIVED.REPORT_TRANSACTIONS_AND_VIOLATIONS]}, + ); // When transactions haven't loaded yet, pass undefined to skip IOU filtering entirely // (undefined = "don't filter" in isIOUActionMatchingTransactionList). // Once loaded, filter normally — even if transactions is empty (genuinely no transactions). diff --git a/src/pages/inbox/report/ReportActionItemSingle.tsx b/src/pages/inbox/report/ReportActionItemSingle.tsx index 04044bd5f5bd..5f46918dedd0 100644 --- a/src/pages/inbox/report/ReportActionItemSingle.tsx +++ b/src/pages/inbox/report/ReportActionItemSingle.tsx @@ -1,6 +1,6 @@ import OfflineWithFeedback from '@components/OfflineWithFeedback'; import PressableWithoutFeedback from '@components/Pressable/PressableWithoutFeedback'; -import ReportActionAvatars from '@components/ReportActionAvatars'; +import {ReportActionAvatarsView} from '@components/ReportActionAvatars'; import useReportActionAvatars from '@components/ReportActionAvatars/useReportActionAvatars'; import {useIsOnSearch} from '@components/Search/SearchScopeProvider'; import Text from '@components/Text'; @@ -159,15 +159,16 @@ function ReportActionItemSingle({ sentryLabel={CONST.SENTRY_LABEL.REPORT.REPORT_ACTION_ITEM_SINGLE_AVATAR_BUTTON} > - diff --git a/src/selectors/Report.ts b/src/selectors/Report.ts index 6b2738ce39f0..4ad963adbe76 100644 --- a/src/selectors/Report.ts +++ b/src/selectors/Report.ts @@ -428,6 +428,29 @@ function reportParentChainSelector(reportID: string | undefined) { }; } +/** + * Returns the report without the fields that change on every read or new message (last read time, last message + * preview), so consumers that only need the report's identity and structure keep the same value across those writes. + */ +function reportWithoutLastActivitySelector(report: OnyxEntry): OnyxEntry { + if (!report) { + return undefined; + } + const { + lastReadTime, + lastReadSequenceNumber, + lastMentionedTime, + lastVisibleActionCreated, + lastVisibleActionLastModified, + lastMessageText, + lastMessageHtml, + lastActorAccountID, + lastActionType, + ...reportWithoutLastActivity + } = report; + return reportWithoutLastActivity; +} + /** * Creates a selector returning only the reports for the given IDs, so a consumer that knows the exact * reports it needs doesn't re-render when any other report in the account changes. @@ -444,6 +467,7 @@ const reportsByIDsSelector = }; export { + reportWithoutLastActivitySelector, getArchiveReason, getReportChatType, getReportType,