Skip to content
Draft
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
4 changes: 2 additions & 2 deletions __mocks__/react-native-onyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -41,4 +41,4 @@ const reactNativeOnyxMock: ReactNativeOnyxMock = {

export default reactNativeOnyxMock;

export {useOnyx};
export {useOnyx, useOnyxState};
91 changes: 69 additions & 22 deletions src/components/ReportActionAvatars/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,29 @@ type ReportActionAvatarsProps = {
shouldUseRealActor?: boolean;
};

type ReportActionAvatarsViewProps = Pick<
ReportActionAvatarsProps,
| 'horizontalStacking'
| 'sort'
| 'size'
| 'singleAvatarContainerStyle'
| 'backdropColor'
| 'subscriptAvatarContainerStyle'
| 'subscriptCardFeed'
| 'subscriptCardFeedIconSize'
| 'isInReportAction'
| 'fallbackDisplayName'
> & {
avatarType: ValueOf<typeof CONST.REPORT_ACTION_AVATARS.TYPE>;
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<ReportAction>;
};

/**
* The component that renders proper user avatars based on either:
*
Expand All @@ -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 ??
Expand All @@ -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,
Expand All @@ -152,6 +157,47 @@ function ReportActionAvatars({
shouldUseRealActor,
});

return (
<ReportActionAvatarsView
{...viewProps}
horizontalStacking={horizontalStacking}
subscriptCardFeed={subscriptCardFeed}
fallbackDisplayName={fallbackDisplayName}
avatarType={avatarType}
avatars={avatars}
delegateAccountID={details.delegateAccountID}
shouldUseConciergeAvatar={details.shouldUseConciergeAvatar}
action={source.action}
/>
);
}

/** 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;
}
Expand Down Expand Up @@ -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 "<copilot> (as copilot for Concierge)".
const delegateAccountIDFromAction = shouldUseConciergeAvatar ? undefined : getDelegateAccountIDFromReportAction(source.action);
const delegateAccountIDFromAction = shouldUseConciergeAvatar ? undefined : getDelegateAccountIDFromReportAction(action);
const singleAvatar: AvatarIcon =
delegateAccountID && delegateAccountIDFromAction
? {
Expand Down Expand Up @@ -266,3 +312,4 @@ function ReportActionAvatars({
}

export default ReportActionAvatars;
export {ReportActionAvatarsView};
12 changes: 10 additions & 2 deletions src/components/ReportActionAvatars/useReportPreviewSenderID.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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<ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.IOU>>) {
const {originalTransactionID, source} = transaction.comment ?? {};

Expand Down Expand Up @@ -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;
Expand Down
39 changes: 39 additions & 0 deletions src/hooks/useOnyxStateSnapshotKey.ts
Original file line number Diff line number Diff line change
@@ -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<TKey extends OnyxKey>(state: {readonly [K in TKey | SnapshotKey]: OnyxValue<K>}, snapshotKey: SnapshotKey | undefined, key: TKey): OnyxValue<TKey> {
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<OnyxValue<SnapshotKey>>['data']] as OnyxValue<TKey>;
}

export default useOnyxStateSnapshotKey;
export {getSnapshotAwareValue};
export type {SnapshotKey};
31 changes: 17 additions & 14 deletions src/hooks/useOriginalReportID.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand All @@ -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<ReportActions>) => {
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;
Expand Down
4 changes: 3 additions & 1 deletion src/hooks/useReportActionsPagination.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();
Expand Down
14 changes: 12 additions & 2 deletions src/hooks/useReportActionsVisibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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;
Expand Down Expand Up @@ -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).
Expand Down
13 changes: 7 additions & 6 deletions src/pages/inbox/report/ReportActionItemSingle.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -159,15 +159,16 @@ function ReportActionItemSingle({
sentryLabel={CONST.SENTRY_LABEL.REPORT.REPORT_ACTION_ITEM_SINGLE_AVATAR_BUTTON}
>
<OfflineWithFeedback pendingAction={details.pendingFields?.avatar ?? undefined}>
<ReportActionAvatars
<ReportActionAvatarsView
singleAvatarContainerStyle={styles.actionAvatar}
subscriptAvatarContainerStyle={styles.mr0}
backdropColor={getBackgroundColor()}
isInReportAction
reportID={iouReportID}
chatReportID={source.iouReport?.chatReportID ?? reportID}
action={action}
shouldUseRealActor={isOnSearch}
avatarType={avatarType}
avatars={avatars}
delegateAccountID={details.delegateAccountID}
shouldUseConciergeAvatar={details.shouldUseConciergeAvatar}
action={source.action}
/>
</OfflineWithFeedback>
</PressableWithoutFeedback>
Expand Down
24 changes: 24 additions & 0 deletions src/selectors/Report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Report>): OnyxEntry<Report> {
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.
Expand All @@ -444,6 +467,7 @@ const reportsByIDsSelector =
};

export {
reportWithoutLastActivitySelector,
getArchiveReason,
getReportChatType,
getReportType,
Expand Down
Loading