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
43 changes: 43 additions & 0 deletions src/hooks/useIsTabVisible.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Tells whether a tab's root screen can be seen, so data fetched for it is not wasted. An RHP hides the screen on a
* narrow layout but opens beside it on a wide one.
*/
import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import getActiveTabName from '@libs/Navigation/helpers/getActiveTabName';
import isSideModalNavigator from '@libs/Navigation/helpers/isSideModalNavigator';

import NAVIGATORS from '@src/NAVIGATORS';

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

import useRootNavigationState from './useRootNavigationState';

function subscribeToDimensions(onChange: () => void) {
const subscription = Dimensions.addEventListener('change', onChange);
return () => subscription.remove();
}

/**
* Returns true when the root screen of `tabName` is on screen. It stays true under an RHP on a wide layout, where
* `useIsFocused()` turns false although the screen is still visible beside the pane. Any other root screen above the
* tab, such as a fullscreen, hides it.
*/
function useIsTabVisible(tabName: string): boolean {
const isScreenFocused = useIsFocused();
const isTabActiveWithOnlyRHPAbove = useRootNavigationState((state) => {
const routes = state?.routes ?? [];
const tabNavigatorIndex = routes.findLastIndex((route) => route.name === NAVIGATORS.TAB_NAVIGATOR);
if (tabNavigatorIndex === -1 || getActiveTabName(routes.at(tabNavigatorIndex)) !== tabName) {
return false;
}
return routes.slice(tabNavigatorIndex + 1).every((route) => isSideModalNavigator(route.name));
});
// A boolean snapshot instead of `useResponsiveLayout`, so the screen re-renders only when the layout crosses the breakpoint and not on every resize event.
const isNarrowLayout = useSyncExternalStore(subscribeToDimensions, getIsNarrowLayout);

return isScreenFocused || (!isNarrowLayout && isTabActiveWithOnlyRHPAbove);
}

export default useIsTabVisible;
9 changes: 5 additions & 4 deletions src/hooks/useTabFocusedRefresh.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
import {useIsFocused} from '@react-navigation/native';
import {useEffect, useEffectEvent, useRef, useState} from 'react';

import useAppReturnCount from './useAppReturnCount';
import useIsTabFocused from './useIsTabFocused';
import useIsTabVisible from './useIsTabVisible';

/** A return to the app this soon after the last refresh is skipped, so flicking between browser tabs costs nothing. */
const APP_RETURN_REFRESH_INTERVAL_MS = 60 * 1000;

/**
* Calls `refresh` when the tab becomes active, when `refreshKey` changes, and when the app becomes
* visible again. A change landing behind an RHP waits until the screen is visible, so closing an RHP
* refreshes nothing on its own.
* visible again. A change landing behind an RHP that covers the screen on a narrow layout waits until the screen is
* visible, so closing an RHP refreshes nothing on its own. On a wide layout the screen stays visible beside the RHP and
* refreshes right away.
*/
function useTabFocusedRefresh(tabName: string, refreshKey: string, refresh: () => void): void {
const isTabFocused = useIsTabFocused(tabName);
const isScreenVisible = useIsFocused();
const isScreenVisible = useIsTabVisible(tabName);
const onRefresh = useEffectEvent(refresh);

// Currency conversion and the like have nothing local to watch, so a return to the app re-reads them.
Expand Down
13 changes: 10 additions & 3 deletions src/pages/Insights/InsightsDashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import ScrollView from '@components/ScrollView';

import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useIsMobileWebLandscape from '@hooks/useIsMobileWebLandscape';
import useIsTabVisible from '@hooks/useIsTabVisible';
import useLayoutSpacing from '@hooks/useLayoutSpacing';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
Expand All @@ -30,13 +31,14 @@ import variables from '@styles/variables';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import SCREENS from '@src/SCREENS';
import type {AIInsight, InsightsDashboard as InsightsDashboardRecord, InsightsDashboardID, InsightsScope} from '@src/types/onyx';
import viewRef from '@src/types/utils/viewRef';

import type {OnyxCollection} from 'react-native-onyx';

import {useIsFocused} from '@react-navigation/native';
import React, {useEffect, useEffectEvent} from 'react';
import React, {useEffect, useEffectEvent, useRef} from 'react';
import {StyleSheet, View} from 'react-native';
import Animated, {FadeIn, FadeOut} from 'react-native-reanimated';

Expand Down Expand Up @@ -307,6 +309,8 @@ function InsightsDashboard({dashboardID, accessibleDashboards}: {dashboardID: In
const shouldScrollMainHeader = useIsMobileWebLandscape();
const {isOffline} = useNetwork();
const isFocused = useIsFocused();
const isDashboardVisible = useIsTabVisible(SCREENS.INSIGHTS);
const wasFocusedRef = useRef(isFocused);
const {login} = useCurrentUserPersonalDetails();
const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const arePoliciesLoaded = policies !== undefined;
Expand Down Expand Up @@ -346,12 +350,15 @@ function InsightsDashboard({dashboardID, accessibleDashboards}: {dashboardID: In
});

useEffect(() => {
if (!isFocused) {
const wasFocused = wasFocusedRef.current;
wasFocusedRef.current = isFocused;
// An RHP opened beside a wide dashboard leaves it visible, so only closing the RHP fetches again, because the RHP may have changed the expenses behind the charts.
if (!isDashboardVisible || (wasFocused && !isFocused)) {
return;
}
onRequestConditionsChanged();
// Leaves out jsonQuery so toggling Compare mode doesn't refetch, since every response covers it. The effective bucket and the eligible charts are listed because the hash leaves them out, so changing them triggers a refetch while a pure Running total toggle does not.
}, [dashboardID, hash, queryGroupBy, eligibleGraphKeys, isFocused, isOffline]);
}, [dashboardID, hash, queryGroupBy, eligibleGraphKeys, isDashboardVisible, isFocused, isOffline]);

const [dashboard] = useOnyx(`${ONYXKEYS.COLLECTION.INSIGHTS}${dashboardID}_${hash}`);
const [hasLoadedBefore = false] = useOnyx(ONYXKEYS.COLLECTION.INSIGHTS, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ jest.mock('@hooks/useIsTabFocused', () => ({
default: jest.fn(() => true),
}));

// The real hook needs a ready navigation ref. Jest treats every layout as narrow, where tab visibility ignores the root state.
jest.mock('@hooks/useRootNavigationState', () => ({
__esModule: true,
default: jest.fn(() => false),
}));

jest.mock('@libs/actions/Search', () => ({
search: jest.fn(),
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ jest.mock('@hooks/useIsTabFocused', () => ({
default: jest.fn(() => true),
}));

// The real hook needs a ready navigation ref. Jest treats every layout as narrow, where tab visibility ignores the root state.
jest.mock('@hooks/useRootNavigationState', () => ({
__esModule: true,
default: jest.fn(() => false),
}));

jest.mock('@libs/actions/Search', () => ({
search: jest.fn(),
}));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ jest.mock('@hooks/useIsTabFocused', () => ({
default: jest.fn(() => true),
}));

// The real hook needs a ready navigation ref. Jest treats every layout as narrow, where tab visibility ignores the root state.
jest.mock('@hooks/useRootNavigationState', () => ({
__esModule: true,
default: jest.fn(() => false),
}));

jest.mock('@libs/actions/Search', () => ({
search: jest.fn(),
}));
Expand Down
196 changes: 196 additions & 0 deletions tests/unit/hooks/useIsTabVisible.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
import {act, renderHook} from '@testing-library/react-native';

import useIsTabVisible from '@hooks/useIsTabVisible';

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

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

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

import createMock from '../../utils/createMock';

const mockTabNavigatorName = NAVIGATORS.TAB_NAVIGATOR;
let mockRootRouteNames: string[] = [];
let mockActiveTab: string = SCREENS.HOME;

/** Builds a root state with the active tab inside the tab navigator and the other root routes stacked above it. */
function mockBuildRootState(): NavigationState {
return createMock<NavigationState>({
routes: mockRootRouteNames.map((name) => ({
key: name,
name,
state: name === mockTabNavigatorName ? {index: 0, routes: [{key: mockActiveTab, name: mockActiveTab}]} : undefined,
})),
});
}

jest.mock('@hooks/useRootNavigationState', () => ({
__esModule: true,
default: (selector: (state: NavigationState | undefined) => unknown) => selector(mockBuildRootState()),
}));

// Jest resolves the native helper, which treats every layout as narrow, so the web one is used to exercise both layouts.
jest.mock('@libs/getIsNarrowLayout', () => jest.requireActual<{default: () => boolean}>('@libs/getIsNarrowLayout/index.ts'));

// Landscape is covered by its own helper, so these cases are driven by width alone.
jest.mock('@libs/isInLandscapeMode', () => ({
__esModule: true,
default: jest.fn(() => false),
}));

jest.mock('@react-navigation/native', () => ({
useIsFocused: jest.fn(() => true),
}));

const mockedUseIsFocused = jest.mocked(useIsFocused);

const NARROW_WINDOW = {width: 400, height: 800, scale: 1, fontScale: 1};
const WIDE_WINDOW = {width: 1400, height: 900, scale: 1, fontScale: 1};

type DimensionsChangeHandler = Parameters<typeof Dimensions.addEventListener>[1];

// The preset already mocks `addEventListener`, so one of its subscriptions is kept for the spy to hand back.
const dimensionsSubscription = Dimensions.addEventListener('change', () => {});
let currentWindow: ScaledSize = WIDE_WINDOW;
const dimensionsChangeHandlers = new Set<DimensionsChangeHandler>();

/** Resizes the window and fires the change event the hook listens to. */
function resizeWindow(window: ScaledSize) {
currentWindow = window;
act(() => {
for (const handler of dimensionsChangeHandlers) {
handler({window, screen: window});
}
});
}

/** Renders the hook for the Home tab and counts how often it renders. */
function renderVisibility() {
let renderCount = 0;
const hook = renderHook(() => {
renderCount++;
return useIsTabVisible(SCREENS.HOME);
});
return {...hook, getRenderCount: () => renderCount};
}

describe('useIsTabVisible', () => {
beforeEach(() => {
jest.clearAllMocks();
mockedUseIsFocused.mockReturnValue(true);
mockRootRouteNames = [NAVIGATORS.TAB_NAVIGATOR];
mockActiveTab = SCREENS.HOME;
currentWindow = WIDE_WINDOW;
dimensionsChangeHandlers.clear();
jest.spyOn(Dimensions, 'get').mockImplementation(() => currentWindow);
jest.spyOn(Dimensions, 'addEventListener').mockImplementation((_type, handler) => {
dimensionsChangeHandlers.add(handler);
return dimensionsSubscription;
});
});

afterEach(() => {
jest.restoreAllMocks();
});

it('is true when the screen is focused', () => {
// Given the tab root screen is focused with nothing on top of it

// When the hook runs
const {result} = renderVisibility();

// Then the screen is visible
expect(result.current).toBe(true);
});

it('stays true under an RHP on a wide layout', () => {
// Given a wide window and an RHP opened over the active tab, which blurs the screen but leaves it beside the pane
mockRootRouteNames = [NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR];
mockedUseIsFocused.mockReturnValue(false);

// When the hook runs
const {result} = renderVisibility();

// Then the screen still counts as visible, so its data can load while the RHP is open
expect(result.current).toBe(true);
});

it('is false under an RHP on a narrow layout', () => {
// Given a narrow window, where an RHP covers the whole screen
currentWindow = NARROW_WINDOW;
mockRootRouteNames = [NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR];
mockedUseIsFocused.mockReturnValue(false);

// When the hook runs
const {result} = renderVisibility();

// Then the screen is hidden, so nothing is fetched for it until the RHP closes
expect(result.current).toBe(false);
});

it('is false on a wide layout when another tab is active', () => {
// Given a wide window with another tab selected
mockedUseIsFocused.mockReturnValue(false);
mockActiveTab = SCREENS.INSIGHTS;

// When the hook runs
const {result} = renderVisibility();

// Then the screen is hidden behind the other tab
expect(result.current).toBe(false);
});

it('is false on a wide layout when a fullscreen covers the active tab', () => {
// Given a wide window with a fullscreen screen pushed above the active tab, which hides it completely
mockRootRouteNames = [NAVIGATORS.TAB_NAVIGATOR, SCREENS.VALIDATE_LOGIN];
mockedUseIsFocused.mockReturnValue(false);

// When the hook runs
const {result} = renderVisibility();

// Then the screen is hidden, so nothing is fetched for it behind the fullscreen
expect(result.current).toBe(false);
});

it('is false on a wide layout when an RHP opens over a fullscreen that covers the active tab', () => {
// Given a wide window with an RHP opened over a fullscreen that sits above the active tab
mockRootRouteNames = [NAVIGATORS.TAB_NAVIGATOR, SCREENS.CONCIERGE, NAVIGATORS.RIGHT_MODAL_NAVIGATOR];
mockedUseIsFocused.mockReturnValue(false);

// When the hook runs
const {result} = renderVisibility();

// Then the screen beside the RHP is the fullscreen, so the tab is still hidden
expect(result.current).toBe(false);
});

it('follows the window across the breakpoint', () => {
// Given an RHP open on a wide window
mockRootRouteNames = [NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR];
mockedUseIsFocused.mockReturnValue(false);
const {result} = renderVisibility();

// When the window shrinks to a narrow layout
resizeWindow(NARROW_WINDOW);

// Then the RHP now covers the screen, so it is hidden
expect(result.current).toBe(false);
});

it('does not re-render on a resize that stays on the same side of the breakpoint', () => {
// Given the hook rendered on a wide window
const {getRenderCount} = renderVisibility();
const initialRenderCount = getRenderCount();

// When the window is resized but stays wide, as happens on every step of a drag
resizeWindow({...WIDE_WINDOW, width: 1200});
resizeWindow({...WIDE_WINDOW, width: 1000});

// Then the screen does not re-render, because only the narrow flag is read
expect(getRenderCount()).toBe(initialRenderCount);
});
});
6 changes: 6 additions & 0 deletions tests/unit/hooks/useTabFocusedRefresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ jest.mock('@hooks/useIsTabFocused', () => ({
default: jest.fn(() => true),
}));

// Jest treats every layout as narrow, where visibility follows `useIsFocused()` alone, so the root state is not needed.
jest.mock('@hooks/useRootNavigationState', () => ({
__esModule: true,
default: jest.fn(() => false),
}));

jest.mock('@react-navigation/native', () => ({
useIsFocused: jest.fn(() => true),
}));
Expand Down
Loading