diff --git a/src/components/SidePanel/useSyncSidePanelWithHistory/index.ts b/src/components/SidePanel/useSyncSidePanelWithHistory/index.ts index da7107e2bf87..153d6ef11ec2 100644 --- a/src/components/SidePanel/useSyncSidePanelWithHistory/index.ts +++ b/src/components/SidePanel/useSyncSidePanelWithHistory/index.ts @@ -3,7 +3,7 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useSidePanelActions from '@hooks/useSidePanelActions'; import useSidePanelState from '@hooks/useSidePanelState'; -import {asCustomHistory, isModalHistorySentinel} from '@libs/Navigation/AppNavigator/routerExtensions/addRootHistoryRouterExtensionUtils'; +import {isModalHistorySentinel} from '@libs/Navigation/AppNavigator/routerExtensions/addRootHistoryRouterExtensionUtils'; import Navigation from '@libs/Navigation/Navigation'; import navigationRef from '@libs/Navigation/navigationRef'; @@ -27,7 +27,7 @@ export default function useSyncSidePanelWithHistory() { const {isExtraLargeScreenWidth} = useResponsiveLayout(); // Modals with `shouldHandleNavigationBack` push their own back-guard entry after the Side Panel's, so skip those: // a modal opened from the panel must not read as the panel having been closed. - const lastHistoryEntry = useNavigationState((state) => asCustomHistory(state?.history)?.findLast((entry) => !isModalHistorySentinel(entry))); + const lastHistoryEntry = useNavigationState((state) => state?.history?.findLast((entry) => !isModalHistorySentinel(entry))); const previousLastHistoryEntry = usePrevious(lastHistoryEntry); useEffect(() => { diff --git a/src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts b/src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts index ebe8acbf39a3..8f0166adec06 100644 --- a/src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts +++ b/src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts @@ -2,20 +2,22 @@ import compoundParamsKey from '@libs/compoundParamsKey'; import type {PlatformStackNavigationState, PlatformStackRouterFactory, PlatformStackRouterOptions} from '@libs/Navigation/PlatformStackNavigation/types'; import type {GoBackAction, SetParamsAction} from '@libs/Navigation/types'; import {cancelPendingFocusRestore, notifyPushParamsBackward, notifyPushParamsForward} from '@libs/NavigationFocusReturn'; +import {isRecord} from '@libs/ObjectUtils'; import CONST from '@src/CONST'; -import type {NavigationRoute, ParamListBase, PartialState, Router, RouterConfigOptions, StackActionType} from '@react-navigation/native'; +import type {ParamListBase, PartialState, Router, RouterConfigOptions, StackActionType} from '@react-navigation/native'; import {CommonActions} from '@react-navigation/native'; -import type {CustomHistoryEntry, PushParamsActionType, PushParamsRouterAction} from './types'; +import type {PushParamsActionType, PushParamsRouterAction} from './types'; import {enhanceStateWithHistory} from './utils'; -function preserveHistoryForRoutes(oldHistory: CustomHistoryEntry[], routes: Array<{key?: string}>): CustomHistoryEntry[] { +function preserveHistoryForRoutes(oldHistory: unknown[], routes: Array<{key?: string}>): unknown[] { const remainingKeys = new Set(routes.map((r) => r.key)); - return oldHistory.filter((entry) => typeof entry === 'string' || remainingKeys.has(entry.key)); + // Keep string history markers and anything else that is not a route snapshot; drop only route snapshots whose route is gone. + return oldHistory.filter((entry) => !isRecord(entry) || typeof entry.key !== 'string' || remainingKeys.has(entry.key)); } // noop=match at cursor; backward/forward=move cursor to match; ambiguous=same compound at cursor±1 (see ambiguous branch); unknown=target not in history. @@ -25,7 +27,7 @@ type ResetOutcome = {type: 'noop'; cursor: number} | {type: 'backward'; cursor: * Classifies a RESET's target against our PUSH_PARAMS history + cursor so the caller fires the right focus-return notification and updates the cursor. * Without the 'noop' branch, `useNavigationResetOnLayoutChange`'s reflexive `reset(getState())` on window resize would be treated as a real navigation — cancelling any pending Esc-triggered focus restore so focus never returns to the trigger. */ -function resolveCursorForReset(history: CustomHistoryEntry[], currentCursor: number, newFocused: {key: string; params: unknown}): ResetOutcome { +function resolveCursorForReset(history: unknown[], currentCursor: number, newFocused: {key: string; params: unknown}): ResetOutcome { const inRange = currentCursor >= 0 && currentCursor < history.length; // Snapped cursor drives direction inference only; adjacent probes are gated on inRange. const cursor = inRange ? currentCursor : history.length - 1; @@ -36,7 +38,7 @@ function resolveCursorForReset(history: CustomHistoryEntry[], currentCursor: num return false; } const entry = history.at(index); - if (typeof entry === 'string' || !entry || entry.key !== newFocused.key) { + if (!isRecord(entry) || entry.key !== newFocused.key) { return false; } return compoundParamsKey(entry.key, entry.params) === newCompound; @@ -134,7 +136,10 @@ function addPushParamsRouterExtension>, configOptions: RouterConfigOptions) => { + const getRehydratedState = ( + partialState: PartialState> | PlatformStackNavigationState, + configOptions: RouterConfigOptions, + ) => { const state = router.getRehydratedState(partialState, configOptions); return seedCursor(enhanceStateWithHistory(state)); }; @@ -178,29 +183,30 @@ function addPushParamsRouterExtension => typeof entry !== 'string'); + const routeHistoryEntries = state.history.filter((entry) => typeof entry !== 'string'); if (routeHistoryEntries.length > state.routes.length) { // Index-based, not at(-1) — must match the key PUSH_PARAMS captured under. const focusedRoute = state.routes.at(state.index) ?? state.routes.at(-1); if (focusedRoute) { // Cursor-relative, not last-two: last-two drifts out of sync after a mid-cursor browser-back RESET. - const history = state.history as CustomHistoryEntry[]; + const history = state.history; const currentIdx = pushParamsHistoryPosition >= 0 && pushParamsHistoryPosition < history.length ? pushParamsHistoryPosition : history.length - 1; const currentEntry = history.at(currentIdx); - if (currentEntry && typeof currentEntry !== 'string' && currentEntry.key === focusedRoute.key) { + if (isRecord(currentEntry) && currentEntry.key === focusedRoute.key) { let prevIdx = -1; for (let i = currentIdx - 1; i >= 0; i -= 1) { const e = history.at(i); - if (e && typeof e !== 'string' && e.key === focusedRoute.key) { + if (isRecord(e) && e.key === focusedRoute.key) { prevIdx = i; break; } } - if (prevIdx >= 0) { - const prevEntry = history.at(prevIdx) as NavigationRoute; + const prevEntry = history.at(prevIdx); + // React Navigation types history entries as unknown, so check that the snapshot's params are valid route params before restoring them. + if (prevIdx >= 0 && isRecord(prevEntry) && (prevEntry.params === undefined || isRecord(prevEntry.params))) { const targetParams = prevEntry.params; const routes = [...state.routes]; routes[state.index] = { @@ -232,7 +238,7 @@ function addPushParamsRouterExtension 0 ? preservedHistory.length - 1 : -1; return { @@ -254,14 +260,13 @@ function addPushParamsRouterExtension>, configOptions: RouterConfigOptions) => { + const getRehydratedState = (partialState: PartialState | RootHistoryState, configOptions: RouterConfigOptions) => { const state = router.getRehydratedState(partialState, configOptions); const stateWithInitialHistory = enhanceStateWithHistory(state); @@ -49,17 +48,12 @@ function addRootHistoryRouterExtension 0) { - stateWithInitialHistory.history = [...(asCustomHistory(stateWithInitialHistory.history) ?? []), ...trailingSentinels]; + stateWithInitialHistory.history = [...(stateWithInitialHistory.history ?? []), ...trailingSentinels]; } return stateWithInitialHistory; }; - // Centralizes the `PartialState | FullState` cast to `getRehydratedState`'s input shape. - function rehydrate(newState: PartialState | RootHistoryState, configOptions: RouterConfigOptions) { - return getRehydratedState(newState as PartialState, configOptions); - } - const getStateForAction = (state: RootHistoryState, action: RootStackNavigatorAction, configOptions: RouterConfigOptions) => { // Snapshot is stale if its RHP key vanished via a non-DISMISS path. if (pendingReveal && !state.routes.some((r) => r.key === pendingReveal?.rhpKey)) { @@ -75,14 +69,14 @@ function addRootHistoryRouterExtension; type PendingReveal = {rhpKey: string; routesLengthAtCapture: number; historyLengthAtCapture: number}; type RehydrateRootHistoryState = (newState: PartialState | RootHistoryState, configOptions: RouterConfigOptions) => RootHistoryState; @@ -31,7 +29,7 @@ function isDismissModalAction(action: RootStackNavigatorAction): action is Dismi } /** Returns true if the entry is a per-instance Modal back-guard (`CUSTOM_HISTORY_ENTRY_MODAL:`). */ -function isModalHistorySentinel(entry: CustomHistoryEntry | undefined): boolean { +function isModalHistorySentinel(entry: unknown): boolean { return typeof entry === 'string' && entry.startsWith(`${CONST.NAVIGATION.CUSTOM_HISTORY_ENTRY_MODAL}:`); } @@ -41,19 +39,18 @@ function isModalHistorySentinel(entry: CustomHistoryEntry | undefined): boolean * overlays' browser entries alive through benign history rebuilds (e.g. RESET / resize). */ function getTrailingStringSentinels(history: unknown[] | undefined): string[] { - const typed = asCustomHistory(history); - if (!typed?.length) { + if (!history?.length) { return []; } - let cutoff = typed.length; - while (cutoff > 0 && typeof typed.at(cutoff - 1) === 'string') { + let cutoff = history.length; + while (cutoff > 0 && typeof history.at(cutoff - 1) === 'string') { cutoff -= 1; } - return typed.slice(cutoff).filter((entry): entry is string => typeof entry === 'string'); + return history.slice(cutoff).filter((entry): entry is string => typeof entry === 'string'); } /** Removes only the topmost modal back-guard entry (used to consume one guard on forward navigation). */ -function stripTrailingModalSentinels(history: CustomHistoryEntry[]): CustomHistoryEntry[] { +function stripTrailingModalSentinels(history: unknown[]): unknown[] { if (isModalHistorySentinel(history.at(-1))) { return history.slice(0, -1); } @@ -64,13 +61,8 @@ function isRightModalNavigatorRouteName(name: string | undefined): boolean { return name === NAVIGATORS.RIGHT_MODAL_NAVIGATOR; } -/** Centralizes the cast from PlatformStackNavigationState's `unknown[]` history slot to our typed array. */ -function asCustomHistory(history: unknown[] | undefined): CustomHistoryEntry[] | undefined { - return history as CustomHistoryEntry[] | undefined; -} - /** Counts the leading `CUSTOM_HISTORY_ENTRY_REVEAL_PADDING` padding entries in a history array. */ -function countLeadingRevealPadding(history: CustomHistoryEntry[] | undefined): number { +function countLeadingRevealPadding(history: unknown[] | undefined): number { if (!history?.length) { return 0; } @@ -87,11 +79,11 @@ function countLeadingRevealPadding(history: CustomHistoryEntry[] | undefined): n } /** Returns a fresh history array with `offset` reveal-padding entries prepended. */ -function buildPaddedHistory(baseHistory: CustomHistoryEntry[], offset: number): CustomHistoryEntry[] { +function buildPaddedHistory(baseHistory: unknown[], offset: number): unknown[] { if (offset <= 0) { return [...baseHistory]; } - const padding = new Array(offset).fill(CONST.NAVIGATION.CUSTOM_HISTORY_ENTRY_REVEAL_PADDING); + const padding = new Array(offset).fill(CONST.NAVIGATION.CUSTOM_HISTORY_ENTRY_REVEAL_PADDING); return [...padding, ...baseHistory]; } @@ -154,7 +146,7 @@ function getRevealDismissState( // Apply the reveal fix only when this DISMISS closes the same RHP we snapshotted. if (dismissingTopKey === pendingReveal.rhpKey && depthMatches && historyDepthMatches) { const rehydrated = rehydrate(newState, configOptions); - const rehydratedHistory = asCustomHistory(rehydrated.history) ?? []; + const rehydratedHistory = rehydrated.history ?? []; // rehydratedHistory already includes any trailing SIDE_PANEL entry, // so it does not inflate the computed offset. const lengthDelta = (state.history?.length ?? 0) - rehydratedHistory.length; @@ -183,9 +175,9 @@ function getRevealDismissState( function applyRevealPaddingOffset(state: RootHistoryState, rehydrated: RootHistoryState): RootHistoryState { // Regular navigation rebuilds history from routes; put back any fake slots already in use. - const offset = countLeadingRevealPadding(asCustomHistory(state.history)); + const offset = countLeadingRevealPadding(state.history); if (offset > 0) { - return {...rehydrated, history: buildPaddedHistory(asCustomHistory(rehydrated.history) ?? [], offset)}; + return {...rehydrated, history: buildPaddedHistory(rehydrated.history ?? [], offset)}; } return rehydrated; } @@ -193,7 +185,6 @@ function applyRevealPaddingOffset(state: RootHistoryState, rehydrated: RootHisto export type {PendingReveal, RootHistoryState}; export { applyRevealPaddingOffset, - asCustomHistory, getFrozenHistoryStateForRemoveFullscreenUnderRHP, getFrozenHistoryStateForReplaceFullscreenUnderRHP, getRevealDismissState, diff --git a/src/libs/TransactionUtils/amountUtils.ts b/src/libs/TransactionUtils/amountUtils.ts index e0101c29b742..8a18a41bdeb3 100644 --- a/src/libs/TransactionUtils/amountUtils.ts +++ b/src/libs/TransactionUtils/amountUtils.ts @@ -1,9 +1,9 @@ import CONST from '@src/CONST'; -import type {Transaction} from '@src/types/onyx'; +import type {OnyxInputOrEntry, Transaction} from '@src/types/onyx'; import type {OnyxEntry} from 'react-native-onyx'; -function hasValidModifiedAmount(transaction: OnyxEntry | null): boolean { +function hasValidModifiedAmount(transaction: OnyxInputOrEntry>>): boolean { if (!transaction) { return false; } diff --git a/src/libs/TransactionUtils/duplicates.ts b/src/libs/TransactionUtils/duplicates.ts index d1f7e5b7d432..78b483236fa4 100644 --- a/src/libs/TransactionUtils/duplicates.ts +++ b/src/libs/TransactionUtils/duplicates.ts @@ -216,8 +216,8 @@ function isReportMergeableForDuplicates(report: OnyxEntry, reportID: str */ function removeSettledAndApprovedTransactions(transactions: Array>): Transaction[] { return transactions.filter( - (transaction) => !!transaction && isReportMergeableForDuplicates(getReportOrDraftReport({reportID: transaction.reportID}), transaction.reportID), - ) as Transaction[]; + (transaction): transaction is Transaction => !!transaction && isReportMergeableForDuplicates(getReportOrDraftReport({reportID: transaction.reportID}), transaction.reportID), + ); } /** @@ -288,7 +288,7 @@ function compareDuplicateTransactionFields( items .map((item) => { // Prioritize modifiedMerchant over merchant - if (keys.includes('modifiedMerchant' as keyof Transaction) && keys.includes('merchant' as keyof Transaction)) { + if (keys.includes('modifiedMerchant') && keys.includes('merchant')) { return getMerchant(item); } return keys.map((key) => item?.[key]); @@ -460,11 +460,11 @@ function buildMergeDuplicatesParams( keptTransaction: OnyxEntry, ): MergeDuplicatesTransactionParams { return { - amount: -getAmount(originalTransaction as OnyxEntry, true), + amount: -getAmount(originalTransaction, true), reportID: originalTransaction?.reportID, receiptID: originalTransaction?.receipt?.receiptID ?? CONST.DEFAULT_NUMBER_ID, - currency: getCurrency(originalTransaction as OnyxEntry), - created: getFormattedCreated(originalTransaction as OnyxEntry), + currency: getCurrency(originalTransaction), + created: getFormattedCreated(originalTransaction), transaction: keptTransaction, transactionList: removeSettledAndApprovedTransactions(duplicatedTransactions ?? []), billable: reviewDuplicates?.billable ?? false, diff --git a/src/libs/TransactionUtils/fields.ts b/src/libs/TransactionUtils/fields.ts index 936d2ad21df1..2dd31e42e8cc 100644 --- a/src/libs/TransactionUtils/fields.ts +++ b/src/libs/TransactionUtils/fields.ts @@ -18,7 +18,7 @@ import getTagArrayFromName from './getTagArrayFromName'; /** * Return the currency field from the transaction, return the modifiedCurrency if present. */ -function getCurrency(transaction: OnyxInputOrEntry>): string { +function getCurrency(transaction: OnyxInputOrEntry>>): string { const currency = transaction?.modifiedCurrency ?? ''; if (currency) { return currency; @@ -26,7 +26,7 @@ function getCurrency(transaction: OnyxInputOrEntry): string { +function getCreated(transaction: OnyxInputOrEntry>>): string { return transaction?.modifiedCreated ? transaction.modifiedCreated : transaction?.created || ''; } @@ -34,7 +34,7 @@ function getCreated(transaction: OnyxInputOrEntry): string { * Return the created field from the transaction as yyyy-MM-dd, using the modifiedCreated if present. It is the same in * every language, so a date shown to the user is formatted from it with the user's locale. */ -function getFormattedCreated(transaction: OnyxInputOrEntry): string { +function getFormattedCreated(transaction: OnyxInputOrEntry>>): string { return DateUtils.formatMachineDateWithUTCTimeZone(getCreated(transaction)); } @@ -93,7 +93,13 @@ function isTimeRequest(transaction: OnyxEntry): boolean { /** * Return the amount field from the transaction, return the modifiedAmount if present. */ -function getAmount(transaction: OnyxInputOrEntry, isFromExpenseReport = false, isFromTrackedExpense = false, allowNegative = false, disableOppositeConversion = false): number { +function getAmount( + transaction: OnyxInputOrEntry>, + isFromExpenseReport = false, + isFromTrackedExpense = false, + allowNegative = false, + disableOppositeConversion = false, +): number { // IOU requests cannot have negative values, but they can be stored as negative values, let's return absolute value if (!isFromExpenseReport && !isFromTrackedExpense && !allowNegative) { const amount = Number(transaction?.modifiedAmount) ?? 0; diff --git a/src/libs/actions/getCompanyCardBankConnection/index.tsx b/src/libs/actions/getCompanyCardBankConnection/index.tsx index 877fc03ed653..ac171738a9d9 100644 --- a/src/libs/actions/getCompanyCardBankConnection/index.tsx +++ b/src/libs/actions/getCompanyCardBankConnection/index.tsx @@ -1,6 +1,7 @@ import {getApiRoot} from '@libs/ApiUtils'; import {splitCardFeedWithDomainID} from '@libs/CardUtils'; import * as NetworkStore from '@libs/Network/NetworkStore'; +import {getObjectKeys, hasKey} from '@libs/ObjectUtils'; import * as PolicyUtils from '@libs/PolicyUtils'; import CONST from '@src/CONST'; @@ -21,7 +22,7 @@ type PersonalCardBankConnection = { }; function getCompanyCardBankConnection(policyID?: string, bankName?: string | null, feed?: CompanyCardFeedWithDomainID) { - const bankConnection = Object.keys(CONST.COMPANY_CARDS.BANKS).find((key) => CONST.COMPANY_CARDS.BANKS[key as keyof typeof CONST.COMPANY_CARDS.BANKS] === bankName); + const bankConnection = getObjectKeys(CONST.COMPANY_CARDS.BANKS).find((key) => CONST.COMPANY_CARDS.BANKS[key] === bankName); if (!bankName || !bankConnection || !policyID) { return null; @@ -46,7 +47,7 @@ function getCompanyCardBankConnection(policyID?: string, bankName?: string | nul queryParams.feed = selectedFeed.feedName; } - const bank = CONST.COMPANY_CARDS.BANK_CONNECTIONS[bankConnection as keyof typeof CONST.COMPANY_CARDS.BANK_CONNECTIONS]; + const bank = hasKey(CONST.COMPANY_CARDS.BANK_CONNECTIONS, bankConnection) ? CONST.COMPANY_CARDS.BANK_CONNECTIONS[bankConnection] : undefined; // The Amex connection whitelists only our production servers, so we need to always use the production API for American Express const forceProductionAPI = bank === CONST.COMPANY_CARDS.BANK_CONNECTIONS.AMEX; @@ -60,7 +61,7 @@ function getCompanyCardBankConnection(policyID?: string, bankName?: string | nul } function getPersonalCardBankConnection(bankName?: string | null) { - const bankConnection = Object.keys(CONST.PERSONAL_CARDS.BANKS).find((key) => CONST.PERSONAL_CARDS.BANKS[key as keyof typeof CONST.PERSONAL_CARDS.BANKS] === bankName); + const bankConnection = getObjectKeys(CONST.PERSONAL_CARDS.BANKS).find((key) => CONST.PERSONAL_CARDS.BANKS[key] === bankName); if (!bankName || !bankConnection) { return null; @@ -71,7 +72,7 @@ function getPersonalCardBankConnection(bankName?: string | null) { isNewDot: 'true', scrapeMinDate: '', }; - const bank = CONST.PERSONAL_CARDS.BANK_CONNECTIONS[bankConnection as keyof typeof CONST.PERSONAL_CARDS.BANK_CONNECTIONS]; + const bank = hasKey(CONST.PERSONAL_CARDS.BANK_CONNECTIONS, bankConnection) ? CONST.PERSONAL_CARDS.BANK_CONNECTIONS[bankConnection] : undefined; // The Amex connection whitelists only our production servers, so we need to always use the production API for American Express const forceProductionAPI = bank === CONST.PERSONAL_CARDS.BANK_CONNECTIONS.AMEX;