Skip to content
2 changes: 1 addition & 1 deletion src/hooks/useDynamicBackPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function useDynamicBackPath(dynamicRouteSuffix: DynamicRouteSuffix): Route {
const pathWithoutLeadingSlash = path.replaceAll(/^\/+/g, '');
const match = findAllMatchingDynamicSuffixes(pathWithoutLeadingSlash).find((m) => m.pattern === dynamicRouteSuffix);
if (match) {
return getPathWithoutDynamicSuffix(pathWithoutLeadingSlash, match.actualSuffix, match.pattern);
return getPathWithoutDynamicSuffix(match.pathUsedForMatching, match.actualSuffix, match.pattern);
}

return pathWithoutLeadingSlash as Route;
Expand Down
51 changes: 43 additions & 8 deletions src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,60 @@
import NAVIGATORS from '@src/NAVIGATORS';
import isDynamicRouteSuffix from './dynamicRoutesUtils/isDynamicRouteSuffix';

type ScreenConfigEntry = string | {path?: string; screens?: Record<string, ScreenConfigEntry>};

const navigatorNames = new Set(Object.values(NAVIGATORS) as string[]);

type CollectResult = {
screensWithTabNavigator: Set<string>;

/** Maps dynamic-route pattern - tab-child paths of that screen's tab navigator.
* Used by findAllMatchingDynamicSuffixes to safely strip trailing tab segments. */
dynamicTabPatternToTabPaths: Map<string, Set<string>>;

/** Maps host screen name - (tab path - tab screen name) for dynamic tab-host screens.
* Used by getStateForDynamicRoute for O(1) tab screen name lookup. */
dynamicTabScreensByHost: Map<string, Map<string, string>>;
};

/**
* Recursively walks the linking config tree and collects screen names that host
* an OnyxTabNavigator. These screens are identified by having both a `path` and
* nested `screens` - a pattern unique to tab-hosting screens in the config.
* Navigator entries (from NAVIGATORS) are excluded to avoid false positives.
* Recursively walks the linking config tree and collects:
* 1. `screensWithTabNavigator` - screen names that host an OnyxTabNavigator
* (identified by having both a `path` and nested `screens`, navigators excluded).
* 2. `dynamicTabPatternToTabPaths` - for each tab-host screen that is also a dynamic
* route, a mapping from its route pattern to the path values of its tab children.
*
* @param screens - The linking config screens object (or a nested `screens` subtree)
* @param result - Accumulator set passed through recursive calls
* @returns Set of screen names that contain an OnyxTabNavigator
* @param result - Accumulator passed through recursive calls
* @returns Collected data
*/
function collectScreensWithTabNavigator(screens: Record<string, ScreenConfigEntry>, result: Set<string> = new Set<string>()): Set<string> {
function collectScreensWithTabNavigator(
screens: Record<string, ScreenConfigEntry>,
result: CollectResult = {screensWithTabNavigator: new Set(), dynamicTabPatternToTabPaths: new Map(), dynamicTabScreensByHost: new Map()},
): CollectResult {
const screenConfigEntries = Object.entries(screens);
for (const [screenName, screenConfig] of screenConfigEntries) {
if (typeof screenConfig === 'object' && screenConfig !== null) {
if (screenConfig.path !== undefined && screenConfig.screens && !navigatorNames.has(screenName)) {
result.add(screenName);
result.screensWithTabNavigator.add(screenName);

// For dynamic tab-host screens, map the route pattern - tab paths for findAllMatchingDynamicSuffixes,
// and map host screen name - (tab path - tab screen name) for getStateForDynamicRoute.
if (isDynamicRouteSuffix(screenConfig.path)) {
const tabPaths = new Set<string>();
const tabScreensByPath = new Map<string, string>();
for (const [tabScreenName, tabConfig] of Object.entries(screenConfig.screens)) {
const tabPath = typeof tabConfig === 'string' ? tabConfig : tabConfig?.path;
if (tabPath) {
tabPaths.add(tabPath);
tabScreensByPath.set(tabPath, tabScreenName);
}
}
if (tabPaths.size > 0) {
result.dynamicTabPatternToTabPaths.set(screenConfig.path, tabPaths);
result.dynamicTabScreensByHost.set(screenName, tabScreensByPath);
}
}
}
if (screenConfig.screens) {
collectScreensWithTabNavigator(screenConfig.screens, result);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {dynamicTabPatternToTabPaths} from '@libs/Navigation/linkingConfig/config';
import type {CompiledEntry} from './compileDynamicRoutePattern';
import {compiledOptionalParametricDynamicRoutes, compiledStrictParametricDynamicRoutes} from './compileDynamicRoutePattern';
import {dynamicRoutePaths} from './isDynamicRouteSuffix';
Expand All @@ -10,15 +11,21 @@ type DynamicSuffixMatch = {
actualSuffix: string;
/** Extracted path params, e.g. {reportID: '456', reportActionID: 'abc'} */
pathParams: Record<string, string>;
/** The path to pass to getPathWithoutDynamicSuffix. Equal to the original path unless a trailing tab segment was stripped. */
pathUsedForMatching: string;
/** The tab path segment that was stripped from the URL. Present only when tryStripTabSuffix removed a trailing tab segment. */
strippedTabPath?: string;
};

type RawSuffixMatch = Omit<DynamicSuffixMatch, 'pathUsedForMatching'>;

/**
* Tries to match a candidate suffix against a list of compiled parametric patterns.
* Returns the first match with extracted path params, or undefined.
*
* @private - Internal helper. Do not export or use outside this file.
*/
function tryMatchParametric(candidate: string, candidateSegmentCount: number, patterns: CompiledEntry[]): DynamicSuffixMatch | undefined {
function tryMatchParametric(candidate: string, candidateSegmentCount: number, patterns: CompiledEntry[]): RawSuffixMatch | undefined {
const normalized = candidate.endsWith('/') ? candidate : `${candidate}/`;

for (const {compiled} of patterns) {
Expand Down Expand Up @@ -49,30 +56,16 @@ function tryMatchParametric(candidate: string, candidateSegmentCount: number, pa

/**
* Collects all registered dynamic route suffixes that syntactically match the end of the given path,
* across all three phases and in priority order:
* across three phases in priority order:
* 1. Static matches (`dynamicRoutePaths` Set lookup), longest to shortest.
* 2. Strict parametric patterns (no optional params), longest to shortest.
* 3. Optional parametric patterns (has at least one `:param?`), longest to shortest.
*
* Use this instead of `findMatchingDynamicSuffix` when you need to validate matches against
* additional context (e.g. `entryScreens`) and fall back to the next candidate if the first
* one doesn't satisfy the constraint. This prevents false-positive greedy matches where a
* user-defined name (e.g. a tag named "gl-code") coincides with a registered static suffix.
*
* Each pattern appears at most once in the result array. The first element is always equal
* to what `findMatchingDynamicSuffix` would return for the same path.
*
* @param path - The path to find all matching dynamic suffixes for
* @returns Array of all matching dynamic suffixes in priority order (may be empty)
* @private - Internal helper. Do not export or use outside this file.
*/
function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] {
const [normalizedPath] = splitPathAndQuery(path);
if (!normalizedPath) {
return [];
}

function collectMatchesForPath(normalizedPath: string): RawSuffixMatch[] {
const segments = normalizedPath.split('/').filter(Boolean);
const results: DynamicSuffixMatch[] = [];
const results: RawSuffixMatch[] = [];
const seenPatterns = new Set<string>();

// Phase 1: Static matches (longest to shortest)
Expand Down Expand Up @@ -105,6 +98,54 @@ function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] {
return results;
}

/**
* Collects all registered dynamic route suffixes that syntactically match the end of the given path.
* First checks whether the path ends with a tab-navigator segment (i.e. the matched dynamic route
* hosts a nested tab navigator), if so, strips the tab segment and returns the match immediately.
* Otherwise collects matches across three phases in priority order:
* 1. Static matches (`dynamicRoutePaths` Set lookup), longest to shortest.
* 2. Strict parametric patterns (no optional params), longest to shortest.
* 3. Optional parametric patterns (has at least one `:param?`), longest to shortest.
*
* Use this instead of `findMatchingDynamicSuffix` when you need to validate matches against
* additional context (e.g. `entryScreens`) and fall back to the next candidate if the first
* one doesn't satisfy the constraint. This prevents false-positive greedy matches where a
* user-defined name (e.g. a tag named "gl-code") coincides with a registered static suffix.
*
* Each pattern appears at most once in the result array. The first element is always equal
* to what `findMatchingDynamicSuffix` would return for the same path.
*
* @param path - The path to find all matching dynamic suffixes for
* @returns Array of all matching dynamic suffixes in priority order (may be empty)
*/
function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] {
const [normalizedPath, query] = splitPathAndQuery(path);
if (!normalizedPath) {
return [];
}

// Some dynamic routes host a tab navigator, so their URLs end with an extra tab segment
// We detect this by stripping the last segment,
// matching the remaining path, and keeping only matches whose pattern has that segment
// registered as a tab child in `dynamicTabPatternToTabPaths`. If any such match is found
// we return early with `pathUsedForMatching` pointing at the path without the tab segment
// (preserving the query string) so that callers can correctly strip the dynamic suffix.
const lastSlash = normalizedPath.lastIndexOf('/');
if (lastSlash > 0) {
const lastSegment = normalizedPath.slice(lastSlash + 1);
const pathWithoutTab = normalizedPath.slice(0, lastSlash);
const matches = collectMatchesForPath(pathWithoutTab);
const tabMatches = matches.filter((match) => dynamicTabPatternToTabPaths.get(match.pattern)?.has(lastSegment));
if (tabMatches.length > 0) {
const fullPathWithoutTab = query ? `${pathWithoutTab}?${query}` : pathWithoutTab;
return tabMatches.map((match) => ({...match, pathUsedForMatching: fullPathWithoutTab, strippedTabPath: lastSegment}));
}
}

const results = collectMatchesForPath(normalizedPath).map((match) => ({...match, pathUsedForMatching: path}));
return results;
}

/** Mirrors previous `findMatchingDynamicSuffix` logic - returns only the first (highest-priority) match. */
function findMatchingDynamicSuffix(path = ''): DynamicSuffixMatch | undefined {
return findAllMatchingDynamicSuffixes(path).at(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ function getDynamicRouteAdaptedState(state: PartialState<NavigationState>, focus
const allSuffixMatches = findAllMatchingDynamicSuffixes(currentPath);

for (const candidate of allSuffixMatches) {
const candidateBasePath = getPathWithoutDynamicSuffix(currentPath, candidate.actualSuffix, candidate.pattern);
const candidateBasePath = getPathWithoutDynamicSuffix(candidate.pathUsedForMatching, candidate.actualSuffix, candidate.pattern);
if (!candidateBasePath || candidateBasePath === currentPath) {
continue;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {normalizedConfigs} from '@libs/Navigation/linkingConfig/config';
import {dynamicTabScreensByHost, normalizedConfigs, screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config';
import {DYNAMIC_ROUTES} from '@src/ROUTES';
import type {DynamicRouteSuffix} from '@src/ROUTES';
import splitPathAndQuery from './splitPathAndQuery';
Expand All @@ -7,6 +7,7 @@ type LeafRoute = {
name: string;
path: string;
params?: Record<string, unknown>;
state?: {routes: Array<{name: string}>; index: 0};
};

type NestedRoute = {
Expand Down Expand Up @@ -54,7 +55,7 @@ function getRouteNamesForDynamicRoute(dynamicRouteName: DynamicRouteSuffix): str
return null;
}

function getStateForDynamicRoute(path: string, dynamicRouteName: keyof typeof DYNAMIC_ROUTES, parentRouteParams?: Record<string, unknown>) {
function getStateForDynamicRoute(path: string, dynamicRouteName: keyof typeof DYNAMIC_ROUTES, parentRouteParams?: Record<string, unknown>, activeTabPath?: string) {
const routeConfig = getRouteNamesForDynamicRoute(DYNAMIC_ROUTES[dynamicRouteName].path);
const [, query] = splitPathAndQuery(path);
const params = getParamsFromQuery(query);
Expand All @@ -75,6 +76,19 @@ function getStateForDynamicRoute(path: string, dynamicRouteName: keyof typeof DY
const cleanedParams = Object.fromEntries(Object.entries(mergedParams).filter(([, v]) => v !== undefined));
const paramsSpread = cleanedParams && Object.keys(cleanedParams).length > 0 ? {params: cleanedParams} : {};

// If this leaf hosts a tab navigator and we know which tab was active from the URL,
// build a partial tab state so TabRouter.getRehydratedState selects the correct tab on
// mount — without waiting for Onyx to load the stored selection.
if (activeTabPath && currentRoute && screensWithOnyxTabNavigator.has(currentRoute)) {
const tabScreenName = dynamicTabScreensByHost.get(currentRoute)?.get(activeTabPath) ?? activeTabPath;
return {
name: currentRoute,
path,
...paramsSpread,
state: {routes: [{name: tabScreenName}], index: 0 as const},
};
}

return {
name: currentRoute ?? '',
path,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
import type {findFocusedRoute, NavigationState, PartialState} from '@react-navigation/native';
import {screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config';
import type {State} from '@libs/Navigation/types';

type RouteFromState = State['routes'][number];

/**
* Works like React Navigation's {@link findFocusedRoute} but stops recursing when it reaches
* a screen that hosts an OnyxTabNavigator. Without this guard the lookup would drill into the
* tab navigator's internal state and return the individual tab name (e.g. "amount", "scan")
* instead of the parent screen (e.g. "Money_Request_Split_Expense").
*/
function findFocusedRouteWithOnyxTabGuard(state: PartialState<NavigationState>): ReturnType<typeof findFocusedRoute> {
function findFocusedRouteWithOnyxTabGuard(state: State): RouteFromState | undefined {
const route = state.routes[state.index ?? state.routes.length - 1];
if (route === undefined) {
return undefined;
}
if (screensWithOnyxTabNavigator.has(route.name)) {
return route as ReturnType<typeof findFocusedRoute>;
return route;
}
if (route.state) {
return findFocusedRouteWithOnyxTabGuard(route.state);
return findFocusedRouteWithOnyxTabGuard(route.state as State);
}
return route as ReturnType<typeof findFocusedRoute>;
return route;
}

export default findFocusedRouteWithOnyxTabGuard;
16 changes: 7 additions & 9 deletions src/libs/Navigation/helpers/getAdaptedStateFromPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import pick from 'lodash/pick';
import getInitialSplitNavigatorState from '@libs/Navigation/AppNavigator/createSplitNavigator/getInitialSplitNavigatorState';
import TAB_SCREENS from '@libs/Navigation/AppNavigator/Navigators/TAB_SCREENS';
import {RHP_TO_DOMAIN, RHP_TO_HOME, RHP_TO_SEARCH, RHP_TO_SETTINGS, RHP_TO_SIDEBAR, RHP_TO_WORKSPACE, RHP_TO_WORKSPACES_LIST} from '@libs/Navigation/linkingConfig/RELATIONS';
import type {NavigationPartialRoute, RootNavigatorParamList} from '@libs/Navigation/types';
import type {NavigationPartialRoute, NavigationRoute, RootNavigatorParamList} from '@libs/Navigation/types';
import {getReportOrDraftReport} from '@libs/ReportUtils';
import {getSearchParamFromPath} from '@libs/Url';
import CONST from '@src/CONST';
Expand Down Expand Up @@ -57,11 +57,11 @@ function getTabNavigatorState(selectedTabRoute: NavigationPartialRoute): Navigat
return {name: NAVIGATORS.TAB_NAVIGATOR, state: buildTabNavigatorNestedState(selectedTabRoute)};
}

function isRouteWithBackToParam(route: NavigationPartialRoute): route is Route<string, {backTo: string}> {
function isRouteWithBackToParam(route: NavigationRoute): route is Route<string, {backTo: string}> {
return route.params !== undefined && 'backTo' in route.params && typeof route.params.backTo === 'string';
}

function isRouteWithReportID(route: NavigationPartialRoute): route is Route<string, {reportID: string}> {
function isRouteWithReportID(route: NavigationRoute): route is Route<string, {reportID: string}> {
return route.params !== undefined && 'reportID' in route.params && typeof route.params.reportID === 'string';
}

Expand All @@ -71,7 +71,7 @@ function isRouteWithReportID(route: NavigationPartialRoute): route is Route<stri
* When a split tab route is accessed from search context (path contains '/search'),
* we use SPLIT_EXPENSE_SEARCH for the mapping lookup instead of the tab name.
*/
function getSearchScreenNameForRoute(route: NavigationPartialRoute): string {
function getSearchScreenNameForRoute(route: NavigationRoute): string {
const splitTabNames = Object.values(CONST.TAB.SPLIT) as string[];
const isSplitTabRoute = splitTabNames.includes(route.name);

Expand All @@ -82,7 +82,7 @@ function getSearchScreenNameForRoute(route: NavigationPartialRoute): string {
return route.name;
}

function getMatchingFullScreenRoute(route: NavigationPartialRoute) {
function getMatchingFullScreenRoute(route: NavigationRoute) {
const isDynamicScreen = isDynamicRouteScreen(route.name as Screen);

// Check for backTo param. One screen with different backTo value may need different screens visible under the overlay.
Expand Down Expand Up @@ -223,9 +223,7 @@ function getMatchingFullScreenRoute(route: NavigationPartialRoute) {
if (route.path) {
const allSuffixMatches = findAllMatchingDynamicSuffixes(route.path);
for (const suffixMatch of allSuffixMatches) {
// Strip the suffix from the URL. For parametric routes we pass both the actual URL
// suffix and the registered pattern so query params can be resolved correctly.
const pathWithoutDynamicSuffix = getPathWithoutDynamicSuffix(route.path, suffixMatch.actualSuffix, suffixMatch.pattern);
const pathWithoutDynamicSuffix = getPathWithoutDynamicSuffix(suffixMatch.pathUsedForMatching, suffixMatch.actualSuffix, suffixMatch.pattern);

if (!pathWithoutDynamicSuffix) {
continue;
Expand Down Expand Up @@ -264,7 +262,7 @@ function getMatchingFullScreenRoute(route: NavigationPartialRoute) {
// It is the reports split navigator with report. If the reportID is defined in the focused route, we want to use it for the default report.
// This is separated from getMatchingFullScreenRoute because we want to use it only for the initial state.
// We don't want to make this route mandatory e.g. after deep linking or opening a specific flow.
function getDefaultFullScreenRoute(route?: NavigationPartialRoute) {
function getDefaultFullScreenRoute(route?: NavigationRoute) {
if (route && isRouteWithReportID(route)) {
const reportID = route.params.reportID;

Expand Down
Loading
Loading