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
4 changes: 3 additions & 1 deletion contributingGuides/NAVIGATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1736,9 +1736,11 @@ The purpose of the `adaptStateIfNecessary` function is to ensure that a given `S

When is this function used:

- This function is called when the application starts. If we open the application on the central screen, this function will push the sidebar screen.
- This function is called when the application starts. If we open the application on the central screen, this function will push the sidebar screen unless the navigation explicitly opts out on a narrow layout. Wide layouts always keep the sidebar.
- When we are on the sidebar on a small screen and we expand it to a wide layout, we have to push the central screen to fill the space on the screen.

The initial-route condition can also apply during in-app navigation while `TAB_NAVIGATOR` is the only route in the root stack. A caller can use `shouldSkipInitialSplitNavigatorSidebar` to prevent a directly opened split destination from adding the sidebar as an intermediate Back destination on a narrow layout.

> [!NOTE]
> `adaptStateIfNecessary` is called in the `getInitialState` and `getRehydratedState` methods in `src/libs/Navigation/AppNavigator/createSplitNavigator/SplitRouter.ts`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import Log from '@libs/Log';
import getParamsFromRoute from '@libs/Navigation/helpers/getParamsFromRoute';
import navigationRef from '@libs/Navigation/navigationRef';
import type {NavigationPartialRoute} from '@libs/Navigation/types';

import CONST from '@src/CONST';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
Expand All @@ -18,13 +17,42 @@ import {getPreservedNavigatorState} from './usePreserveNavigatorState';

type StackState = StackNavigationState<ParamListBase> | PartialState<StackNavigationState<ParamListBase>>;

const isAtLeastOneInState = (state: StackState, screenName: string): boolean => state.routes.some((route) => route.name === screenName);

type AdaptStateIfNecessaryArgs = {
state: StackState;
options: SplitNavigatorRouterOptions;
};

function hasSkipInitialSidebarParam(state: StackState): boolean {
const params = state.routes.at(-1)?.params;
return !!params && typeof params === 'object' && 'shouldSkipInitialSidebar' in params && params.shouldSkipInitialSidebar === true;
}

function stripSkipInitialSidebarParam(state: StackState): StackState {
const lastRoute = state.routes.at(-1);
if (!lastRoute || !hasSkipInitialSidebarParam(state)) {
return state;
}

const params = Object.fromEntries(Object.entries(lastRoute.params ?? {}).filter(([key]) => key !== 'shouldSkipInitialSidebar'));
if (state.stale === false) {
const routes = [...state.routes];
const lastStateRoute = routes.at(-1);
if (!lastStateRoute) {
return state;
}
routes[routes.length - 1] = {...lastStateRoute, params: isEmptyObject(params) ? undefined : params};
return {...state, routes};
}

const routes = [...state.routes];
const lastStateRoute = routes.at(-1);
if (!lastStateRoute) {
return state;
}
routes[routes.length - 1] = {...lastStateRoute, params: isEmptyObject(params) ? undefined : params};
return {...state, routes};
}

/**
* Adapts the navigation state of a SplitNavigator to ensure proper screen layout and navigation flow.
* This function handles both narrow and wide layouts, ensuring that:
Expand All @@ -45,21 +73,22 @@ function adaptStateIfNecessary({state, options: {sidebarScreen, defaultCentralSc

const isNarrowLayout = getIsNarrowLayout();
const rootState = navigationRef.isReady() ? navigationRef.getRootState() : undefined;
const lastRoute = state.routes.at(-1) as NavigationPartialRoute;

const routes = [...state.routes];
let modified = false;
const shouldSkipInitialSidebar = hasSkipInitialSidebarParam(state);
const stateWithoutMarker = stripSkipInitialSidebarParam(state);
const routes = [...stateWithoutMarker.routes];
let modified = stateWithoutMarker !== state;

// When initializing the app on a small screen with the center screen as the initial screen, the sidebar must also be split to allow users to swipe back.
// Despite the name, this is true for any navigation while TAB_NAVIGATOR is the only root route, not only during app startup.
// `shouldSkipInitialSidebar` lets a direct narrow-layout navigation opt out while wide layouts continue to keep the sidebar.
const isInitialRoute = !rootState || rootState.routes.length === 1;
const shouldSplitHaveSidebar = isInitialRoute || !isNarrowLayout;
const shouldSplitHaveSidebar = (isInitialRoute && !shouldSkipInitialSidebar) || !isNarrowLayout;
Comment thread
nabi-ebrahimi marked this conversation as resolved.
Resolved

// If the screen is wide, there should be at least two screens inside:
// - sidebarScreen to cover left pane.
// - defaultCentralScreen to cover central pane.
if (!isAtLeastOneInState(state, sidebarScreen) && shouldSplitHaveSidebar) {
if (!routes.some((route) => route.name === sidebarScreen) && shouldSplitHaveSidebar) {
const paramsFromRoute = getParamsFromRoute(sidebarScreen, !isNarrowLayout);
const copiedParams = pick(lastRoute?.params, paramsFromRoute);
const copiedParams = pick(routes.at(-1)?.params, paramsFromRoute);

// We don't want to get an empty object as params because it breaks some navigation logic when comparing if routes are the same.
const params = isEmptyObject(copiedParams) ? undefined : copiedParams;
Expand All @@ -86,7 +115,7 @@ function adaptStateIfNecessary({state, options: {sidebarScreen, defaultCentralSc

routes.push({
name: previousSelectedCentralScreen ?? defaultCentralScreen,
params: state.routes.at(0)?.params,
params: routes.at(0)?.params,
});
modified = true;
}
Expand Down Expand Up @@ -147,7 +176,8 @@ function SplitRouter(options: SplitNavigatorRouterOptions) {
const stateAfterPop = stackRouter.getStateForAction(state, StackActions.pop(), configOptions) as StackNavigationState<ParamListBase>;
return stackRouter.getStateForAction(stateAfterPop, StackActions.pop(), configOptions);
}
return stackRouter.getStateForAction(state, action, configOptions);
const result = stackRouter.getStateForAction(state, action, configOptions);
return result ? stripSkipInitialSidebarParam(result) : result;
},

getInitialState({routeNames, routeParamList, routeGetIdList}: RouterConfigOptions) {
Expand Down
1 change: 1 addition & 0 deletions src/libs/Navigation/Navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ function startOpenReportSpan(route: Route) {
* @param route - The route to navigate to.
* @param options - Optional navigation options.
* @param options.forceReplace - If true, the navigation action will replace the current route instead of pushing a new one.
* @param options.shouldSkipInitialSplitNavigatorSidebar - If true, a direct split destination will not add its sidebar as an intermediate Back destination.
*/
function navigate(route: Route, options?: LinkToOptions) {
clearSelectedText();
Expand Down
38 changes: 31 additions & 7 deletions src/libs/Navigation/helpers/linkTo/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import NAVIGATORS from '@src/NAVIGATORS';
import type {Route} from '@src/ROUTES';
import SCREENS from '@src/SCREENS';

import type {NavigationContainerRef, NavigationState, PartialState} from '@react-navigation/native';
import type {NavigationAction, NavigationContainerRef, NavigationState, PartialState} from '@react-navigation/native';

import {getActionFromState} from '@react-navigation/core';
import {CommonActions, findFocusedRoute} from '@react-navigation/native';
Expand All @@ -23,10 +23,35 @@ import type {ActionPayloadParams, LinkToOptions} from './types';

import getMinimalAction from './getMinimalAction';

const defaultLinkToOptions: LinkToOptions = {
const defaultLinkToOptions = {
forceReplace: false,
shouldSkipInitialSplitNavigatorSidebar: false,
skipMatchingFullScreenRoute: false,
};
} satisfies Pick<LinkToOptions, 'forceReplace' | 'shouldSkipInitialSplitNavigatorSidebar' | 'skipMatchingFullScreenRoute'>;

/**
* The split router reads `shouldSkipInitialSidebar` from the innermost screen params. Walk through nested
* navigator payloads so destinations with and without their own params receive the transient marker.
*/
function addSkipInitialSidebarParam(params: ActionPayloadParams | undefined): ActionPayloadParams {
const navigationParams = params ?? {};
if (typeof navigationParams.screen === 'string') {
return {...navigationParams, params: addSkipInitialSidebarParam(navigationParams.params)};
}
return {...navigationParams, shouldSkipInitialSidebar: true};
}

function hasParamsPayload(action: NavigationAction): action is NavigationAction & {payload: {params?: ActionPayloadParams}} {
return !!action.payload && 'params' in action.payload;
}

function addSkipInitialSidebarParamToAction(action: NavigationAction): NavigationAction {
if (!hasParamsPayload(action)) {
return action;
}

return {...action, payload: {...action.payload, params: addSkipInitialSidebarParam(action.payload.params)}};
}

/**
* Leaf screen names that represent the root/landing view of each tab.
Expand Down Expand Up @@ -160,8 +185,7 @@ export default function linkTo(navigation: NavigationContainerRef<RootNavigatorP
throw new Error("Couldn't find a navigation object. Is your component inside a screen in a navigator?");
}

// We know that the options are always defined because we have default options.
const {forceReplace, skipMatchingFullScreenRoute} = {...defaultLinkToOptions, ...options} as Required<LinkToOptions>;
const {forceReplace, shouldSkipInitialSplitNavigatorSidebar, skipMatchingFullScreenRoute} = {...defaultLinkToOptions, ...options};

const normalizedPath = normalizePath(path) as Route;
const normalizedPathAfterRedirection = (getMatchingNewRoute(normalizedPath) ?? normalizedPath) as Route;
Expand Down Expand Up @@ -234,7 +258,7 @@ export default function linkTo(navigation: NavigationContainerRef<RootNavigatorP
const isTargetAtTabRoot = ROOT_TAB_SCREENS.has(focusedRouteFromPath?.name ?? '');
if (currentActiveScreen && targetActiveScreen && currentActiveScreen !== targetActiveScreen && !isTargetAtTabRoot) {
(action as {type: string}).type = CONST.NAVIGATION.ACTION_TYPE.PUSH;
navigation.dispatch(action);
navigation.dispatch(shouldSkipInitialSplitNavigatorSidebar ? addSkipInitialSidebarParamToAction(action) : action);
return;
}

Expand Down Expand Up @@ -291,5 +315,5 @@ export default function linkTo(navigation: NavigationContainerRef<RootNavigatorP
) {
minimalAction.type = CONST.NAVIGATION.ACTION_TYPE.PUSH;
}
navigation.dispatch(minimalAction);
navigation.dispatch(shouldSkipInitialSplitNavigatorSidebar ? addSkipInitialSidebarParamToAction(minimalAction) : minimalAction);
}
8 changes: 7 additions & 1 deletion src/libs/Navigation/helpers/linkTo/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
type ActionPayloadParams = {
[key: string]: unknown;
screen?: string;
params?: unknown;
params?: ActionPayloadParams;
path?: string;
};

Expand All @@ -11,6 +12,11 @@ type ActionPayload = {
type LinkToOptions = {
// To explicitly set the action type to replace.
forceReplace?: boolean;
/**
* Prevents a directly opened split destination from adding its sidebar as an intermediate Back destination on narrow layouts.
* SplitRouter always keeps the sidebar when `getIsNarrowLayout()` is false, which can differ from a caller's responsive-layout predicate.
*/
shouldSkipInitialSplitNavigatorSidebar?: boolean;
// Callback to execute after the navigation transition animation completes.
afterTransition?: () => void;
// If true, waits for ongoing transitions to finish before navigating. Defaults to false (navigates immediately).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function getActiveWorkspaceSidebarRoute(): {sidebarRouteKey: string; splitStateK

function navigateToWorkspaceSettingsRoute(targetRoute: Route, policyID: string, shouldUseNarrowLayout: boolean, targetScreenName: string) {
if (shouldUseNarrowLayout) {
Navigation.navigate(targetRoute);
Navigation.navigate(targetRoute, {shouldSkipInitialSplitNavigatorSidebar: true});
return;
}

Expand Down
Loading
Loading