Skip to content
Merged
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
19 changes: 17 additions & 2 deletions src/hooks/useIsTabFocused.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {getPreInsertedOriginalTabRoute} from '@libs/Navigation/AppNavigator/createRootStackNavigator/GetStateForActionHandlers';
import getActiveTabName from '@libs/Navigation/helpers/getActiveTabName';
import isSideModalNavigator from '@libs/Navigation/helpers/isSideModalNavigator';
import type {NavigationRoute} from '@libs/Navigation/types';

import NAVIGATORS from '@src/NAVIGATORS';
Expand All @@ -14,8 +16,21 @@ function useIsTabFocused(tabName: string): boolean {
if (!state) {
return false;
}
const topTabNavigator = state.routes.findLast((route) => route.name === NAVIGATORS.TAB_NAVIGATOR) as NavigationRoute | undefined;
return getActiveTabName(topTabNavigator) === tabName;
const tabNavigatorIndex = state.routes.findLastIndex((route) => route.name === NAVIGATORS.TAB_NAVIGATOR);
if (tabNavigatorIndex < 0) {
return false;
}
const topTabNavigator = state.routes.at(tabNavigatorIndex) as NavigationRoute | undefined;
const preInsertedOriginalTabRoute = getPreInsertedOriginalTabRoute();

// Pre-inserting a destination under an RHP is not a tab departure. Keep the original tab focused until the
// destination is committed or the RHP disappears, so cancelling does not look like returning to the tab.
const isDestinationPreInsertedUnderRHP =
!!preInsertedOriginalTabRoute &&
preInsertedOriginalTabRoute.key === topTabNavigator?.key &&
state.routes.slice(tabNavigatorIndex + 1).some((route) => isSideModalNavigator(route.name));

return getActiveTabName(isDestinationPreInsertedUnderRHP ? preInsertedOriginalTabRoute : topTabNavigator) === tabName;
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import useOnyx from '@hooks/useOnyx';

import KeyboardShortcut from '@libs/KeyboardShortcut';
import getActiveTabName from '@libs/Navigation/helpers/getActiveTabName';
import isSideModalNavigator from '@libs/Navigation/helpers/isSideModalNavigator';
import Navigation, {navigationRef} from '@libs/Navigation/Navigation';
import type {NavigationRoute} from '@libs/Navigation/types';

Expand Down Expand Up @@ -85,6 +86,11 @@ function EscapeHandler() {
return;
}

// Restore the original tab before dismissing, just like the flow's back button. Waiting for unmount
// cleanup would briefly focus the speculative destination and make cancellation look like a tab return.
if (topmostRootRoute && isSideModalNavigator(topmostRootRoute.name)) {
Navigation.removePreInsertedFullscreenIfNeeded();
}
Navigation.dismissModal();
},
shortcutConfig.descriptionKey,
Expand Down
124 changes: 122 additions & 2 deletions tests/unit/HomePage/InsightsSection/useInsightDataRefreshTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,26 @@
* - returning to Home, changing charts, and reconnecting still refetch it
* - joining a workspace fetches it again
*/
import {renderHook} from '@testing-library/react-native';
import {act, renderHook} from '@testing-library/react-native';

import type {SearchQueryJSON} from '@components/Search/types';

import useIsTabFocused from '@hooks/useIsTabFocused';
import useNetwork from '@hooks/useNetwork';
import useRootNavigationState from '@hooks/useRootNavigationState';

import {search} from '@libs/actions/Search';
import {getPreInsertedOriginalTabRoute} from '@libs/Navigation/AppNavigator/createRootStackNavigator/GetStateForActionHandlers';
import type {SearchTypeMenuItem} from '@libs/SearchUIUtils';

import useInsightData from '@pages/home/InsightsSection/useInsightData';

import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import ONYXKEYS from '@src/ONYXKEYS';
import SCREENS from '@src/SCREENS';

import type {NavigationState} from '@react-navigation/native';

import {useIsFocused} from '@react-navigation/native';

Expand Down Expand Up @@ -53,6 +59,24 @@ const config: SearchTypeMenuItem = {

// Module mocks

let mockRootState: NavigationState | undefined;
const mockStateListeners = new Set<() => void>();
jest.mock('@libs/Navigation/navigationRef', () => ({
__esModule: true,
default: {
isReady: () => true,
getRootState: () => mockRootState,
addListener: (_event: string, listener: () => void) => {
mockStateListeners.add(listener);
return () => mockStateListeners.delete(listener);
},
},
}));

jest.mock('@libs/Navigation/AppNavigator/createRootStackNavigator/GetStateForActionHandlers', () => ({
getPreInsertedOriginalTabRoute: jest.fn(),
}));

jest.mock('@react-navigation/native', () => ({
useIsFocused: jest.fn(() => true),
createNavigationContainerRef: () => ({}),
Expand Down Expand Up @@ -105,14 +129,62 @@ const mockedSearch = jest.mocked(search);
const mockedUseIsFocused = jest.mocked(useIsFocused);
const mockedUseIsTabFocused = jest.mocked(useIsTabFocused);
const mockedUseNetwork = jest.mocked(useNetwork);
const mockedUseRootNavigationState = jest.mocked(useRootNavigationState);
const mockedGetPreInsertedOriginalTabRoute = jest.mocked(getPreInsertedOriginalTabRoute);

function buildHomeNavigationState(isSearchSelected = false, hasRHP = false): NavigationState {
return {
key: 'root',
type: 'stack',
stale: false,
index: hasRHP ? 1 : 0,
routeNames: [NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR],
routes: [
{
key: 'tabs',
name: NAVIGATORS.TAB_NAVIGATOR,
state: {
key: 'tab-state',
type: 'tab',
stale: false,
index: isSearchSelected ? 1 : 0,
routeNames: [SCREENS.HOME, NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR],
routes: [
{key: 'home', name: SCREENS.HOME},
{key: 'search', name: NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR},
],
},
},
...(hasRHP ? [{key: 'rhp', name: NAVIGATORS.RIGHT_MODAL_NAVIGATOR}] : []),
],
};
}

function publishNavigationState(state: NavigationState) {
act(() => {
mockRootState = state;
for (const listener of mockStateListeners) {
listener();
}
});
}

function enableRealTabFocus() {
mockedUseIsTabFocused.mockImplementation(jest.requireActual<{default: typeof useIsTabFocused}>('@hooks/useIsTabFocused').default);
mockedUseRootNavigationState.mockImplementation(jest.requireActual<{default: typeof useRootNavigationState}>('@hooks/useRootNavigationState').default);
mockRootState = buildHomeNavigationState();
}

beforeEach(() => {
for (const key of Object.keys(onyxData)) {
delete onyxData[key];
}
mockedSearch.mockClear();
mockedUseIsFocused.mockReturnValue(true);
mockedUseIsTabFocused.mockReturnValue(true);
mockedUseIsTabFocused.mockReset().mockReturnValue(true);
mockedUseRootNavigationState.mockReset().mockReturnValue(false);
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(undefined);
mockStateListeners.clear();
mockedUseNetwork.mockReturnValue({isOffline: false});
});

Expand Down Expand Up @@ -142,6 +214,54 @@ describe('useInsightData — refresh gating', () => {
expect(mockedSearch).toHaveBeenCalledTimes(1);
});

it.each([false, true])('does not refetch after cancelling a speculative tab switch (expense update: %s)', (hasExpenseUpdate) => {
// Given a loaded chart using the real focus hook and navigation-state subscription
enableRealTabFocus();
const originalTabRoute = mockRootState?.routes.at(0);
const {rerender} = renderHook(() => useInsightData(config));
mockedUseIsFocused.mockReturnValue(false);
rerender(undefined);
publishNavigationState(buildHomeNavigationState(false, true));
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(originalTabRoute);
publishNavigationState(buildHomeNavigationState(true, true));

// When an optional expense update arrives, then cancellation restores Home before closing the RHP
if (hasExpenseUpdate) {
onyxData[ONYXKEYS.DERIVED.SPEND_DATA_SIGNATURE] = {expenses: 1, cardExpenses: 0};
rerender(undefined);
}
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(undefined);
publishNavigationState(buildHomeNavigationState(false, true));
mockedUseIsFocused.mockReturnValue(true);
publishNavigationState(buildHomeNavigationState());
rerender(undefined);

// Then neither the pre-insertion nor cancellation is treated as a tab arrival
expect(mockedSearch).toHaveBeenCalledTimes(1);
});

it('refreshes on returning Home after a speculative destination is committed', () => {
// Given Search is pre-inserted under an RHP while Home remains logically focused
enableRealTabFocus();
const originalTabRoute = mockRootState?.routes.at(0);
const {rerender} = renderHook(() => useInsightData(config));
mockedUseIsFocused.mockReturnValue(false);
rerender(undefined);
publishNavigationState(buildHomeNavigationState(false, true));
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(originalTabRoute);
publishNavigationState(buildHomeNavigationState(true, true));

// When submission commits Search and the user later switches back to Home
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(undefined);
publishNavigationState(buildHomeNavigationState(true));
expect(mockedSearch).toHaveBeenCalledTimes(1);
mockedUseIsFocused.mockReturnValue(true);
publishNavigationState(buildHomeNavigationState());

// Then the genuine tab return still fetches fresh chart data
expect(mockedSearch).toHaveBeenCalledTimes(2);
});

it('does not refetch when expenses are added, edited, or deleted', () => {
// Given the chart has already fetched
const {rerender} = renderHook(() => useInsightData(config));
Expand Down
81 changes: 81 additions & 0 deletions tests/unit/Navigation/EscapeHandlerTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/** Verifies that Escape cancels a destination pre-mount before dismissing its RHP. */
import {act, render} from '@testing-library/react-native';

import useOnyx from '@hooks/useOnyx';

import EscapeHandler from '@libs/Navigation/AppNavigator/KeyboardShortcutsHandler/EscapeHandler';
import Navigation from '@libs/Navigation/Navigation';

import NAVIGATORS from '@src/NAVIGATORS';
import SCREENS from '@src/SCREENS';

let mockTopRouteName: string = NAVIGATORS.RIGHT_MODAL_NAVIGATOR;
let mockEscapeCallback: (() => void) | undefined;

jest.mock('@components/WideRHPContextProvider', () => ({
useWideRHPState: () => ({}),
}));

jest.mock('@hooks/useOnyx', () => ({
__esModule: true,
default: jest.fn(() => [undefined]),
}));

jest.mock('@libs/KeyboardShortcut', () => ({
__esModule: true,
default: {
subscribe: (_shortcut: string, callback: () => void) => {
mockEscapeCallback = callback;
return () => {
mockEscapeCallback = undefined;
};
},
},
}));

jest.mock('@libs/Navigation/Navigation', () => ({
__esModule: true,
default: {
removePreInsertedFullscreenIfNeeded: jest.fn(),
dismissModal: jest.fn(),
},
navigationRef: {
getRootState: () => ({routes: [{key: 'top', name: mockTopRouteName}]}),
},
}));

describe('EscapeHandler', () => {
beforeEach(() => {
jest.clearAllMocks();
mockTopRouteName = NAVIGATORS.RIGHT_MODAL_NAVIGATOR;
jest.mocked(useOnyx).mockReturnValue([undefined, {status: 'loaded'}]);
});

it('restores the original tab before dismissing the RHP', () => {
// Given an open RHP whose pre-mounted destination must not become the visible tab on cancellation
const calls: string[] = [];
jest.mocked(Navigation.removePreInsertedFullscreenIfNeeded).mockImplementation(() => calls.push('restore'));
jest.mocked(Navigation.dismissModal).mockImplementation(() => {
calls.push('dismiss');
});
render(<EscapeHandler />);

// When Escape cancels the flow without submitting
act(() => mockEscapeCallback?.());

// Then restoration happens while the RHP still covers the destination, not during later unmount cleanup
expect(calls).toEqual(['restore', 'dismiss']);
});

it('does not start pre-mount cleanup when Escape is pressed outside an RHP', () => {
// Given a root screen with no side modal to cancel
mockTopRouteName = SCREENS.HOME;
render(<EscapeHandler />);

// When Escape is pressed
act(() => mockEscapeCallback?.());

// Then it does not restore a saved tab belonging to some other flow
expect(Navigation.removePreInsertedFullscreenIfNeeded).not.toHaveBeenCalled();
});
});
56 changes: 56 additions & 0 deletions tests/unit/hooks/useIsTabFocused.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import {renderHook} from '@testing-library/react-native';
import useIsTabFocused from '@hooks/useIsTabFocused';
import useRootNavigationState from '@hooks/useRootNavigationState';

import {getPreInsertedOriginalTabRoute} from '@libs/Navigation/AppNavigator/createRootStackNavigator/GetStateForActionHandlers';

import NAVIGATORS from '@src/NAVIGATORS';
import SCREENS from '@src/SCREENS';

Expand All @@ -13,7 +15,12 @@ jest.mock('@hooks/useRootNavigationState', () => ({
default: jest.fn(),
}));

jest.mock('@libs/Navigation/AppNavigator/createRootStackNavigator/GetStateForActionHandlers', () => ({
getPreInsertedOriginalTabRoute: jest.fn(),
}));

const mockedUseRootNavigationState = jest.mocked(useRootNavigationState);
const mockedGetPreInsertedOriginalTabRoute = jest.mocked(getPreInsertedOriginalTabRoute);

type RootRoute = NavigationState['routes'][number];

Expand Down Expand Up @@ -57,6 +64,7 @@ function renderWithState(state: NavigationState | undefined, tabName: string = S
describe('useIsTabFocused', () => {
beforeEach(() => {
jest.clearAllMocks();
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(undefined);
});

it('is true when the tab is the selected one', () => {
Expand Down Expand Up @@ -110,4 +118,52 @@ describe('useIsTabFocused', () => {
// Then it reports not focused rather than refreshing against an unknown state
expect(isFocused).toBe(false);
});

it('is false when the stack has no tab navigator', () => {
// Given a root route that must not be mistaken for a tab navigator
const state = buildRootState([{key: 'home', name: SCREENS.HOME}]);

// When the hook is asked about Home
const isFocused = renderWithState(state);

// Then a matching screen name alone is not tab focus
expect(isFocused).toBe(false);
});

it('keeps the original tab focused while a destination is pre-inserted under an RHP', () => {
// Given Home was selected before Search was pre-inserted beneath an RHP and its buffer
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(buildTabNavigatorRoute('tabs', SCREENS.HOME));
const state = buildRootState([
buildTabNavigatorRoute('tabs', SCREENS.SEARCH.ROOT),
{key: 'buffer', name: SCREENS.PRE_MOUNT_BUFFER},
{key: 'rhp', name: NAVIGATORS.RIGHT_MODAL_NAVIGATOR},
]);

// When querying both the original tab and the speculative destination
const isHomeFocused = renderWithState(state);
const isSearchFocused = renderWithState(state, SCREENS.SEARCH.ROOT);

// Then pre-mounting does not count as leaving Home or arriving at Search
expect(isHomeFocused).toBe(true);
expect(isSearchFocused).toBe(false);
});

it.each(['different navigator', 'no RHP', 'RHP below the navigator'] as const)('ignores the saved tab with %s', (scenario) => {
// Given a saved Home route that no longer represents a destination hidden under its RHP
mockedGetPreInsertedOriginalTabRoute.mockReturnValue(buildTabNavigatorRoute('tabs', SCREENS.HOME));
const searchRoute = buildTabNavigatorRoute(scenario === 'different navigator' ? 'new-tabs' : 'tabs', SCREENS.SEARCH.ROOT);
const rhpRoute = {key: 'rhp', name: NAVIGATORS.RIGHT_MODAL_NAVIGATOR};
let routes = [searchRoute];
if (scenario === 'different navigator') {
routes = [searchRoute, rhpRoute];
} else if (scenario === 'RHP below the navigator') {
routes = [rhpRoute, searchRoute];
}

// When the hook resolves the active tab
const isHomeFocused = renderWithState(buildRootState(routes));

// Then stale saved state cannot keep Home focused
expect(isHomeFocused).toBe(false);
});
});
Loading