From a2b2b521e0e7ecefdaddca3cb8a74d96e22cf6b0 Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Fri, 19 Jun 2026 17:44:54 +0200 Subject: [PATCH 01/11] add logic to handle dynamic routes-tab-navigators --- src/hooks/useDynamicBackPath.ts | 2 +- .../helpers/collectScreensWithTabNavigator.ts | 45 ++++-- .../findAllMatchingDynamicSuffixes.ts | 55 ++++++- .../getDynamicRouteAdaptedState.ts | 2 +- .../findFocusedRouteWithOnyxTabGuard.ts | 8 +- .../helpers/getAdaptedStateFromPath.ts | 4 +- .../Navigation/helpers/getPathFromState.ts | 53 +++++-- .../Navigation/helpers/getStateFromPath.ts | 4 +- src/libs/Navigation/linkingConfig/config.ts | 13 +- .../findAllMatchingDynamicSuffixesTests.ts | 115 +++++++++++--- tests/navigation/getPathFromStateTests.ts | 141 ++++++++++++++++-- 11 files changed, 357 insertions(+), 85 deletions(-) diff --git a/src/hooks/useDynamicBackPath.ts b/src/hooks/useDynamicBackPath.ts index f21a493821db..fcf8f347c849 100644 --- a/src/hooks/useDynamicBackPath.ts +++ b/src/hooks/useDynamicBackPath.ts @@ -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; diff --git a/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts b/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts index f87374743ef3..90b366c07abe 100644 --- a/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts +++ b/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts @@ -1,25 +1,52 @@ import NAVIGATORS from '@src/NAVIGATORS'; +import isDynamicRouteSuffix from './dynamicRoutesUtils/isDynamicRouteSuffix'; type ScreenConfigEntry = string | {path?: string; screens?: Record}; const navigatorNames = new Set(Object.values(NAVIGATORS) as string[]); +type CollectResult = { + screensWithTabNavigator: Set; + + /** Maps dynamic-route pattern - tab-child paths of that screen's tab navigator. + * Used by findAllMatchingDynamicSuffixes to safely strip trailing tab segments. */ + dynamicTabPatternToTabPaths: Map>; +}; + /** - * 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, result: Set = new Set()): Set { +function collectScreensWithTabNavigator( + screens: Record, + result: CollectResult = {screensWithTabNavigator: new Set(), dynamicTabPatternToTabPaths: 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. + if (isDynamicRouteSuffix(screenConfig.path)) { + const tabPaths = new Set(); + for (const tabConfig of Object.values(screenConfig.screens)) { + const tabPath = typeof tabConfig === 'string' ? tabConfig : tabConfig?.path; + if (tabPath) { + tabPaths.add(tabPath); + } + } + if (tabPaths.size > 0) { + result.dynamicTabPatternToTabPaths.set(screenConfig.path, tabPaths); + } + } } if (screenConfig.screens) { collectScreensWithTabNavigator(screenConfig.screens, result); @@ -29,5 +56,5 @@ function collectScreensWithTabNavigator(screens: Record; + /** The path to pass to getPathWithoutDynamicSuffix. Equal to the original path unless a trailing tab segment was stripped. */ + pathUsedForMatching: string; }; /** @@ -18,7 +21,7 @@ type DynamicSuffixMatch = { * * @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[]): Omit | undefined { const normalized = candidate.endsWith('/') ? candidate : `${candidate}/`; for (const {compiled} of patterns) { @@ -48,8 +51,35 @@ 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: + * Strips the trailing tab segment from a path and retries matching against Phases 1–3. + * Returns an empty array if stripping is not applicable. + * Calls `findAllMatchingDynamicSuffixes` recursively with an empty map to prevent double-stripping. + * + * @private - Internal helper. Do not export or use outside this file. + */ +function tryStripTabSuffix(normalizedPath: string, query: string, tabPatternMap: Map>): DynamicSuffixMatch[] { + if (tabPatternMap.size === 0) { + return []; + } + const lastSlash = normalizedPath.lastIndexOf('/'); + if (lastSlash <= 0) { + return []; + } + const lastSegment = normalizedPath.slice(lastSlash + 1); + const pathWithoutTab = normalizedPath.slice(0, lastSlash); + const fullPathWithoutTab = query ? `${pathWithoutTab}?${query}` : pathWithoutTab; + const retriedResults = findAllMatchingDynamicSuffixes(pathWithoutTab, new Map()); + + // Keep only matches whose pattern owns the stripped segment as a registered tab-child path. + const validResults = retriedResults.filter((match) => tabPatternMap.get(match.pattern)?.has(lastSegment)); + return validResults.map((match) => ({...match, pathUsedForMatching: fullPathWithoutTab})); +} + +/** + * 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. @@ -63,14 +93,23 @@ function tryMatchParametric(candidate: string, candidateSegmentCount: number, pa * to what `findMatchingDynamicSuffix` would return for the same path. * * @param path - The path to find all matching dynamic suffixes for + * @param tabPatternMap - Override for the tab-pattern map (defaults to the app-wide + * `dynamicTabPatternToTabPaths`). * @returns Array of all matching dynamic suffixes in priority order (may be empty) */ -function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] { - const [normalizedPath] = splitPathAndQuery(path); +function findAllMatchingDynamicSuffixes(path = '', tabPatternMap: Map> = dynamicTabPatternToTabPaths): DynamicSuffixMatch[] { + const [normalizedPath, query] = splitPathAndQuery(path); if (!normalizedPath) { return []; } + // Handles dynamic routes that host a tab navigator: if the URL ends with a tab segment, + // strip it and return the match immediately. + const tabResults = tryStripTabSuffix(normalizedPath, query ?? '', tabPatternMap); + if (tabResults.length > 0) { + return tabResults; + } + const segments = normalizedPath.split('/').filter(Boolean); const results: DynamicSuffixMatch[] = []; const seenPatterns = new Set(); @@ -79,7 +118,7 @@ function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] { for (let i = 0; i < segments.length; i++) { const candidate = segments.slice(i).join('/'); if (dynamicRoutePaths.has(candidate)) { - results.push({pattern: candidate, actualSuffix: candidate, pathParams: {}}); + results.push({pattern: candidate, actualSuffix: candidate, pathParams: {}, pathUsedForMatching: path}); seenPatterns.add(candidate); } } @@ -88,7 +127,7 @@ function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] { for (let i = 0; i < segments.length; i++) { const match = tryMatchParametric(segments.slice(i).join('/'), segments.length - i, compiledStrictParametricDynamicRoutes); if (match && !seenPatterns.has(match.pattern)) { - results.push(match); + results.push({...match, pathUsedForMatching: path}); seenPatterns.add(match.pattern); } } @@ -97,7 +136,7 @@ function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] { for (let i = 0; i < segments.length; i++) { const match = tryMatchParametric(segments.slice(i).join('/'), segments.length - i, compiledOptionalParametricDynamicRoutes); if (match && !seenPatterns.has(match.pattern)) { - results.push(match); + results.push({...match, pathUsedForMatching: path}); seenPatterns.add(match.pattern); } } diff --git a/src/libs/Navigation/helpers/dynamicRoutesUtils/getDynamicRouteAdaptedState.ts b/src/libs/Navigation/helpers/dynamicRoutesUtils/getDynamicRouteAdaptedState.ts index df66973ba157..536db3dd044c 100644 --- a/src/libs/Navigation/helpers/dynamicRoutesUtils/getDynamicRouteAdaptedState.ts +++ b/src/libs/Navigation/helpers/dynamicRoutesUtils/getDynamicRouteAdaptedState.ts @@ -85,7 +85,7 @@ function getDynamicRouteAdaptedState(state: PartialState, 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; } diff --git a/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts b/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts index 345d22d31520..ded28cb797fb 100644 --- a/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts +++ b/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts @@ -1,4 +1,4 @@ -import type {findFocusedRoute, NavigationState, PartialState} from '@react-navigation/native'; +import type {NavigationRoute, NavigationState, ParamListBase, PartialState} from '@react-navigation/native'; import {screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config'; /** @@ -7,18 +7,18 @@ import {screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config * 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): ReturnType { +function findFocusedRouteWithOnyxTabGuard(state: NavigationState | PartialState): NavigationRoute | 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; + return route as NavigationRoute; } if (route.state) { return findFocusedRouteWithOnyxTabGuard(route.state); } - return route as ReturnType; + return route as NavigationRoute; } export default findFocusedRouteWithOnyxTabGuard; diff --git a/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts b/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts index 8d41e85f40ca..0115d2cb6c2e 100644 --- a/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts +++ b/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts @@ -235,9 +235,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; diff --git a/src/libs/Navigation/helpers/getPathFromState.ts b/src/libs/Navigation/helpers/getPathFromState.ts index 2d884a0136de..e90afdd8d8e3 100644 --- a/src/libs/Navigation/helpers/getPathFromState.ts +++ b/src/libs/Navigation/helpers/getPathFromState.ts @@ -1,13 +1,18 @@ -import {findFocusedRoute, getPathFromState as RNGetPathFromState} from '@react-navigation/native'; +import {getPathFromState as RNGetPathFromState} from '@react-navigation/native'; import type {NavigationState, PartialState} from '@react-navigation/routers'; -import {config, normalizedConfigs} from '@libs/Navigation/linkingConfig/config'; +import {config, normalizedConfigs, screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config'; import type {Screen} from '@src/SCREENS'; import getDynamicRouteQueryParams from './dynamicRoutesUtils/getDynamicRouteQueryParams'; import isDynamicRouteScreen from './dynamicRoutesUtils/isDynamicRouteScreen'; import splitPathAndQuery from './dynamicRoutesUtils/splitPathAndQuery'; +import findFocusedRouteWithOnyxTabGuard from './findFocusedRouteWithOnyxTabGuard'; type State = NavigationState | Omit, 'stale'>; +function isScreen(name: string): name is Screen { + return name in normalizedConfigs; +} + /** * Resolves a single path segment: if it's a `:param` placeholder, replaces it * with the URL-encoded value from `params`; otherwise returns the segment as-is. @@ -68,12 +73,19 @@ function buildSuffixFromPattern(pattern: string, params: Record * Pops the deepest focused route from a navigation state tree. * Returns the reduced state, or undefined if the tree becomes empty. * + * Screens listed in `isLeaf` are treated as atomic leaves - the function will + * not recurse into their nested state (e.g. tab navigators), so the entire + * screen is removed as a unit rather than popping an individual tab. + * * @param state - The navigation state tree to pop from + * @param isLeaf - Optional guard: return true for screen names that should be + * treated as leaves (not recursed into). Used to prevent drilling + * into tab navigators hosted by dynamic screens. * @returns The reduced state, or undefined if the tree becomes empty * * @private - Internal helper. Do not export or use outside this file. */ -function popFocusedRoute(state: State): State | undefined { +function popFocusedRoute(state: State, isLeaf?: (name: string) => boolean): State | undefined { const index = state.index ?? state.routes.length - 1; const focusedRoute = state.routes[index]; @@ -82,9 +94,10 @@ function popFocusedRoute(state: State): State | undefined { return undefined; } - // the focused route has nested state — try to pop from deeper levels first. - if (focusedRoute.state) { - const nestedResult = popFocusedRoute(focusedRoute.state as State); + // the focused route has nested state - try to pop from deeper levels first, + // unless it is a leaf screen (e.g. a tab-hosting dynamic screen). + if (focusedRoute.state && !isLeaf?.(focusedRoute.name ?? '')) { + const nestedResult = popFocusedRoute(focusedRoute.state as State, isLeaf); // A deeper route was successfully popped - rebuild the current level with the updated nested state. if (nestedResult) { @@ -106,16 +119,20 @@ function popFocusedRoute(state: State): State | undefined { } /** - * Builds a URL path for a dynamic route screen that has no `path` in state. + * Builds a URL path for a dynamic route screen. * Recursively peels off dynamic suffixes and resolves the base path underneath. * + * When the focused dynamic screen hosts a tab navigator (i.e. it is in + * `screensWithOnyxTabNavigator`), the focused tab's path segment is appended + * to the dynamic suffix before the base path is resolved. + * * @param state - The navigation state tree to build the path from * @returns The resolved path for the focused dynamic route screen * * @private - Internal helper. Do not export or use outside this file. */ function getPathFromStateWithDynamicRoute(state: State): string { - const focusedRoute = findFocusedRoute(state); + const focusedRoute = findFocusedRouteWithOnyxTabGuard(state); const screenName = focusedRoute?.name ?? ''; const suffixPattern = normalizedConfigs[screenName as Screen]?.path; @@ -123,8 +140,22 @@ function getPathFromStateWithDynamicRoute(state: State): string { return RNGetPathFromState(state, config); } - const actualSuffix = buildSuffixFromPattern(suffixPattern, focusedRoute?.params as Record | undefined); - const reducedState = popFocusedRoute(state); + let actualSuffix = buildSuffixFromPattern(suffixPattern, focusedRoute?.params as Record | undefined); + + // If this dynamic screen hosts a tab navigator, append the focused tab's path segment. + if (screensWithOnyxTabNavigator.has(screenName)) { + const tabState = focusedRoute?.state; + if (tabState) { + const tabIndex = tabState.index ?? tabState.routes.length - 1; + const focusedTab = tabState.routes[tabIndex]; + const tabPath = focusedTab && isScreen(focusedTab.name) ? normalizedConfigs[focusedTab.name]?.path : undefined; + if (tabPath) { + actualSuffix = `${actualSuffix}/${tabPath}`; + } + } + } + + const reducedState = popFocusedRoute(state, (name) => screensWithOnyxTabNavigator.has(name)); if (!reducedState) { return `/${actualSuffix}`; @@ -145,7 +176,7 @@ function getPathFromStateWithDynamicRoute(state: State): string { } function getPathFromState(state: State): string { - const focusedRoute = findFocusedRoute(state); + const focusedRoute = findFocusedRouteWithOnyxTabGuard(state); const screenName = focusedRoute?.name ?? ''; if (isDynamicRouteScreen(screenName as Screen)) { diff --git a/src/libs/Navigation/helpers/getStateFromPath.ts b/src/libs/Navigation/helpers/getStateFromPath.ts index 1d44bf54fb84..f16276960244 100644 --- a/src/libs/Navigation/helpers/getStateFromPath.ts +++ b/src/libs/Navigation/helpers/getStateFromPath.ts @@ -29,8 +29,8 @@ function getStateFromPath(path: Route): PartialState { const dynamicRouteKeys = Object.keys(DYNAMIC_ROUTES) as DynamicRouteKey[]; for (const suffixMatch of allSuffixMatches) { - const {pattern, actualSuffix, pathParams} = suffixMatch; - const pathWithoutDynamicSuffix = getPathWithoutDynamicSuffix(normalizedPathAfterRedirection, actualSuffix, pattern); + const {pattern, actualSuffix, pathParams, pathUsedForMatching} = suffixMatch; + const pathWithoutDynamicSuffix = getPathWithoutDynamicSuffix(pathUsedForMatching, actualSuffix, pattern); // Find the DYNAMIC_ROUTES config key whose path matches the extracted pattern. const dynamicRoute = dynamicRouteKeys.find((key) => DYNAMIC_ROUTES[key].path === pattern) ?? ''; diff --git a/src/libs/Navigation/linkingConfig/config.ts b/src/libs/Navigation/linkingConfig/config.ts index 4af188881270..9390be8ec5e6 100644 --- a/src/libs/Navigation/linkingConfig/config.ts +++ b/src/libs/Navigation/linkingConfig/config.ts @@ -980,16 +980,13 @@ const config: LinkingOptions['config'] = { path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT.route, screens: { [CONST.TAB.RECEIPT_PARTNERS.ALL]: { - path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT_ALL, - exact: true, + path: CONST.TAB.RECEIPT_PARTNERS.ALL, }, [CONST.TAB.RECEIPT_PARTNERS.LINKED]: { - path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT_LINKED, - exact: true, + path: CONST.TAB.RECEIPT_PARTNERS.LINKED, }, [CONST.TAB.RECEIPT_PARTNERS.OUTSTANDING]: { - path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT_OUTSTANDING, - exact: true, + path: CONST.TAB.RECEIPT_PARTNERS.OUTSTANDING, }, }, }, @@ -2374,6 +2371,6 @@ const normalizedConfigs = Object.keys(config.screens) {} as Record, ); -const screensWithOnyxTabNavigator = collectScreensWithTabNavigator(config.screens as Record); +const {screensWithTabNavigator: screensWithOnyxTabNavigator, dynamicTabPatternToTabPaths} = collectScreensWithTabNavigator(config.screens as Record); -export {normalizedConfigs, config, screensWithOnyxTabNavigator}; +export {normalizedConfigs, config, screensWithOnyxTabNavigator, dynamicTabPatternToTabPaths}; diff --git a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts index 9bf3760939cd..781d1eab6edf 100644 --- a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts +++ b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts @@ -1,5 +1,9 @@ import findAllMatchingDynamicSuffixes, {findMatchingDynamicSuffix} from '@libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes'; +jest.mock('@libs/Navigation/linkingConfig/config', () => ({ + dynamicTabPatternToTabPaths: new Map(), +})); + jest.mock('@src/ROUTES', () => ({ DYNAMIC_ROUTES: { VERIFY_ACCOUNT: {path: 'verify-account'}, @@ -18,7 +22,7 @@ jest.mock('@src/ROUTES', () => ({ describe('findMatchingDynamicSuffix', () => { it('should match a single-segment dynamic suffix', () => { - expect(findMatchingDynamicSuffix('settings/wallet/verify-account')).toEqual({ + expect(findMatchingDynamicSuffix('settings/wallet/verify-account')).toMatchObject({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, @@ -26,7 +30,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match when the path has a leading slash', () => { - expect(findMatchingDynamicSuffix('/settings/wallet/verify-account')).toEqual({ + expect(findMatchingDynamicSuffix('/settings/wallet/verify-account')).toMatchObject({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, @@ -46,7 +50,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should ignore query parameters when matching', () => { - expect(findMatchingDynamicSuffix('settings/wallet/verify-account?sortBy=date')).toEqual({ + expect(findMatchingDynamicSuffix('settings/wallet/verify-account?sortBy=date')).toMatchObject({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, @@ -54,7 +58,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should handle trailing slashes', () => { - expect(findMatchingDynamicSuffix('settings/wallet/verify-account/')).toEqual({ + expect(findMatchingDynamicSuffix('settings/wallet/verify-account/')).toMatchObject({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, @@ -66,7 +70,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match a suffix when path has suffix-specific query params', () => { - expect(findMatchingDynamicSuffix('settings/profile/address/country?country=US')).toEqual({ + expect(findMatchingDynamicSuffix('settings/profile/address/country?country=US')).toMatchObject({ pattern: 'country', actualSuffix: 'country', pathParams: {}, @@ -74,7 +78,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should prefer longer multi-segment static match over shorter', () => { - expect(findMatchingDynamicSuffix('/settings/wallet/add-bank-account/verify-account')).toEqual({ + expect(findMatchingDynamicSuffix('/settings/wallet/add-bank-account/verify-account')).toMatchObject({ pattern: 'add-bank-account/verify-account', actualSuffix: 'add-bank-account/verify-account', pathParams: {}, @@ -82,7 +86,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match parametric suffix and extract params', () => { - expect(findMatchingDynamicSuffix('/r/123/flag/456/abc')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/flag/456/abc')).toMatchObject({ pattern: 'flag/:reportID/:reportActionID', actualSuffix: 'flag/456/abc', pathParams: {reportID: '456', reportActionID: 'abc'}, @@ -90,7 +94,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match single-param suffix', () => { - expect(findMatchingDynamicSuffix('/r/123/members/member-details/456')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/members/member-details/456')).toMatchObject({ pattern: 'member-details/:accountID', actualSuffix: 'member-details/456', pathParams: {accountID: '456'}, @@ -106,7 +110,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should handle query params alongside parametric suffix', () => { - expect(findMatchingDynamicSuffix('/r/123/flag/456/abc?tab=details')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/flag/456/abc?tab=details')).toMatchObject({ pattern: 'flag/:reportID/:reportActionID', actualSuffix: 'flag/456/abc', pathParams: {reportID: '456', reportActionID: 'abc'}, @@ -114,7 +118,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match keyboard-shortcuts dynamic suffix', () => { - expect(findMatchingDynamicSuffix('settings/about/keyboard-shortcuts')).toEqual({ + expect(findMatchingDynamicSuffix('settings/about/keyboard-shortcuts')).toMatchObject({ pattern: 'keyboard-shortcuts', actualSuffix: 'keyboard-shortcuts', pathParams: {}, @@ -123,7 +127,7 @@ describe('findMatchingDynamicSuffix', () => { describe('optional path params', () => { it('should match trailing-optional pattern when optional is absent', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/opt-page')).toMatchObject({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page', pathParams: {}, @@ -131,7 +135,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match trailing-optional pattern when optional is present', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page/789')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/opt-page/789')).toMatchObject({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page/789', pathParams: {id: '789'}, @@ -139,7 +143,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match middle-optional pattern when optional is absent', () => { - expect(findMatchingDynamicSuffix('/r/123/wrap/end')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/wrap/end')).toMatchObject({ pattern: 'wrap/:p?/end', actualSuffix: 'wrap/end', pathParams: {}, @@ -147,7 +151,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match middle-optional pattern when optional is present', () => { - expect(findMatchingDynamicSuffix('/r/123/wrap/x/end')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/wrap/x/end')).toMatchObject({ pattern: 'wrap/:p?/end', actualSuffix: 'wrap/x/end', pathParams: {p: 'x'}, @@ -155,7 +159,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should ignore query params when matching trailing-optional present-form', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page/789?tab=details')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/opt-page/789?tab=details')).toMatchObject({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page/789', pathParams: {id: '789'}, @@ -163,7 +167,7 @@ describe('findMatchingDynamicSuffix', () => { }); it('should ignore query params when matching trailing-optional absent-form', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page?tab=details')).toEqual({ + expect(findMatchingDynamicSuffix('/r/123/opt-page?tab=details')).toMatchObject({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page', pathParams: {}, @@ -186,11 +190,11 @@ describe('findAllMatchingDynamicSuffixes', () => { }); it('should return a single-element array for an unambiguous static path', () => { - expect(findAllMatchingDynamicSuffixes('settings/wallet/verify-account')).toEqual([{pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}]); + expect(findAllMatchingDynamicSuffixes('settings/wallet/verify-account')).toMatchObject([{pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}]); }); it('should return both a static and a parametric candidate when a tag name matches a static suffix (gl-code collision)', () => { - expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/gl-code')).toEqual([ + expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/gl-code')).toMatchObject([ {pattern: 'gl-code', actualSuffix: 'gl-code', pathParams: {}}, { pattern: 'tag-settings/:orderWeight/:tagName', @@ -203,8 +207,8 @@ describe('findAllMatchingDynamicSuffixes', () => { it('should place static candidates before strict parametric candidates (priority order)', () => { const results = findAllMatchingDynamicSuffixes('/base/flag/123/verify-account'); expect(results).toHaveLength(2); - expect(results.at(0)).toEqual({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}); - expect(results.at(1)).toEqual({ + expect(results.at(0)).toMatchObject({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}); + expect(results.at(1)).toMatchObject({ pattern: 'flag/:reportID/:reportActionID', actualSuffix: 'flag/123/verify-account', pathParams: {reportID: '123', reportActionID: 'verify-account'}, @@ -214,8 +218,8 @@ describe('findAllMatchingDynamicSuffixes', () => { it('should place static candidates before optional parametric candidates (priority order)', () => { const results = findAllMatchingDynamicSuffixes('/base/opt-page/verify-account'); expect(results).toHaveLength(2); - expect(results.at(0)).toEqual({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}); - expect(results.at(1)).toEqual({ + expect(results.at(0)).toMatchObject({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}); + expect(results.at(1)).toMatchObject({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page/verify-account', pathParams: {id: 'verify-account'}, @@ -223,6 +227,71 @@ describe('findAllMatchingDynamicSuffixes', () => { }); it('should return a single-element array when only one candidate exists (tag-approver at the end)', () => { - expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/tagname/tag-approver')).toEqual([{pattern: 'tag-approver', actualSuffix: 'tag-approver', pathParams: {}}]); + expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/tagname/tag-approver')).toMatchObject([{pattern: 'tag-approver', actualSuffix: 'tag-approver', pathParams: {}}]); + }); +}); + +describe('findAllMatchingDynamicSuffixes – Phase 4 (tab-suffix stripping)', () => { + // 'flag/:reportID/:reportActionID' → tabs: 'AllTab', 'LinkedTab' + // URLs ending with .../flag/456/abc/AllTab should be recognised as the flag route with tab stripped. + // 'keyboard-shortcuts' is registered as a dynamic route but NOT in the tabMap, so Phase 4 + // must not fire even when the URL ends with a seemingly tab-like segment. + const tabMap = new Map>([['flag/:reportID/:reportActionID', new Set(['AllTab', 'LinkedTab'])]]); + + it('strips the trailing tab segment and returns match with pathUsedForMatching', () => { + const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab', tabMap); + expect(results).toHaveLength(1); + expect(results.at(0)).toEqual({ + pattern: 'flag/:reportID/:reportActionID', + actualSuffix: 'flag/456/abc', + pathParams: {reportID: '456', reportActionID: 'abc'}, + pathUsedForMatching: '/base/flag/456/abc', + }); + }); + + it('strips the non-default tab segment and sets pathUsedForMatching', () => { + const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/LinkedTab', tabMap); + expect(results).toHaveLength(1); + expect(results.at(0)).toMatchObject({ + pattern: 'flag/:reportID/:reportActionID', + pathUsedForMatching: '/base/flag/456/abc', + }); + }); + + it('preserves query string in pathUsedForMatching when stripping tab segment', () => { + const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab?foo=bar', tabMap); + expect(results).toHaveLength(1); + expect(results.at(0)).toMatchObject({ + pathUsedForMatching: '/base/flag/456/abc?foo=bar', + }); + }); + + it('does NOT strip when the last segment is a tab of a different (non-matched) pattern', () => { + // After stripping 'AllTab', the retry on '/base/about/keyboard-shortcuts' finds the + // static 'keyboard-shortcuts' pattern. But tabMap.get('keyboard-shortcuts') is undefined, + // so the scoped check fails and the result is empty. + const results = findAllMatchingDynamicSuffixes('/base/about/keyboard-shortcuts/AllTab', tabMap); + expect(results).toEqual([]); + }); + + it('does NOT strip when tabMap is not provided', () => { + expect(findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab')).toEqual([]); + }); + + it('does NOT strip when tabMap is empty', () => { + expect(findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab', new Map())).toEqual([]); + }); + + it('recursive retry does not receive tabMap so stripping stops after one level', () => { + // '/base/flag/456/AllTab/LinkedTab' → Phase 4 strips 'LinkedTab' → + // retry '/base/flag/456/AllTab' → 'flag/456/AllTab' matches flag pattern + // (reportID='456', reportActionID='AllTab') → tabMap.get(pattern)?.has('LinkedTab') → true. + const results = findAllMatchingDynamicSuffixes('/base/flag/456/AllTab/LinkedTab', tabMap); + expect(results).toHaveLength(1); + expect(results.at(0)).toMatchObject({ + pattern: 'flag/:reportID/:reportActionID', + pathParams: {reportID: '456', reportActionID: 'AllTab'}, + pathUsedForMatching: '/base/flag/456/AllTab', + }); }); }); diff --git a/tests/navigation/getPathFromStateTests.ts b/tests/navigation/getPathFromStateTests.ts index cf5d476837cd..d41d7d9d5516 100644 --- a/tests/navigation/getPathFromStateTests.ts +++ b/tests/navigation/getPathFromStateTests.ts @@ -1,9 +1,8 @@ -import {findFocusedRoute, getPathFromState as RNGetPathFromState} from '@react-navigation/native'; +import {getPathFromState as RNGetPathFromState} from '@react-navigation/native'; import type {NavigationState, PartialState} from '@react-navigation/routers'; import getPathFromState from '@libs/Navigation/helpers/getPathFromState'; jest.mock('@react-navigation/native', () => ({ - findFocusedRoute: jest.fn(), getPathFromState: jest.fn(), })); @@ -34,7 +33,21 @@ jest.mock('@libs/Navigation/linkingConfig/config', () => ({ ReportScreen: { path: 'r/:reportID', }, + // Tab-hosting dynamic screen and its tab children + TabHostDynamicScreen: { + path: ':integration/edit', + }, + TabAll: { + path: 'all', + }, + TabLinked: { + path: 'linked', + }, }, + // Screens that host an OnyxTabNavigator — findFocusedRouteWithOnyxTabGuard stops here + screensWithOnyxTabNavigator: new Set(['TabHostDynamicScreen']), + // Pattern-to-tabs map used by findAllMatchingDynamicSuffixes Phase 4 (not used in getPathFromState tests) + dynamicTabPatternToTabPaths: new Map(), })); jest.mock('@libs/Navigation/linkingConfig', () => ({ @@ -62,6 +75,9 @@ jest.mock('@src/ROUTES', () => ({ path: 'constant-picker', queryParams: ['formType', 'fieldName', 'fieldValue'], }, + TAB_HOST_DYNAMIC: { + path: ':integration/edit', + }, }, })); @@ -98,7 +114,6 @@ const staticBasePaths: Record) => stri }; describe('getPathFromState', () => { - const mockFindFocusedRoute = findFocusedRoute as jest.Mock; const mockRNGetPathFromState = RNGetPathFromState as jest.Mock; beforeEach(() => { @@ -106,7 +121,6 @@ describe('getPathFromState', () => { }); it('should resolve dynamic screen from pattern and params', () => { - mockFindFocusedRoute.mockImplementation(realFindFocusedRoute); mockRNGetPathFromState.mockImplementation(staticBasePaths.WalletScreen); const state = buildState([{name: 'WalletScreen'}, {name: 'TestDynamicScreen'}]); @@ -117,26 +131,21 @@ describe('getPathFromState', () => { }); it('should use RN getPathFromState for standard screens', () => { - const state = {} as PartialState; const expectedPath = '/standard/path'; - - mockFindFocusedRoute.mockReturnValue({ - name: 'StandardScreen', - }); mockRNGetPathFromState.mockReturnValue(expectedPath); - const result = getPathFromState(state); + const state = buildState([{name: 'StandardScreen'}]); + const result = getPathFromState(state as PartialState); expect(result).toBe(expectedPath); expect(mockRNGetPathFromState).toHaveBeenCalledWith(state, expect.anything()); }); it('should handle state where no route is focused', () => { - const state = {} as PartialState; - mockFindFocusedRoute.mockReturnValue(undefined); mockRNGetPathFromState.mockReturnValue('/fallback'); - const result = getPathFromState(state); + const state = buildState([{name: 'StandardScreen'}]); + const result = getPathFromState(state as PartialState); expect(result).toBe('/fallback'); expect(mockRNGetPathFromState).toHaveBeenCalled(); @@ -144,8 +153,6 @@ describe('getPathFromState', () => { describe('dynamic route resolution from pattern and params', () => { beforeEach(() => { - mockFindFocusedRoute.mockImplementation(realFindFocusedRoute); - mockRNGetPathFromState.mockImplementation((s: TestState) => { const route = realFindFocusedRoute(s); const builder = staticBasePaths[route?.name ?? '']; @@ -302,4 +309,108 @@ describe('getPathFromState', () => { expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/country'); }); }); + + describe('dynamic screen with tab navigator inside', () => { + beforeEach(() => { + mockRNGetPathFromState.mockImplementation((s: TestState) => { + const route = realFindFocusedRoute(s); + const builder = staticBasePaths[route?.name ?? '']; + return builder ? builder(route?.params) : '/unknown'; + }); + }); + + it('resolves default tab (index 0) when tab-host dynamic screen is focused', () => { + const state = buildState([ + {name: 'WalletScreen'}, + { + name: 'TabHostDynamicScreen', + params: {integration: 'brex'}, + state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), + }, + ]); + + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/all'); + }); + + it('resolves non-default tab (index 1) when tab-host dynamic screen is focused', () => { + const state = buildState([ + {name: 'WalletScreen'}, + { + name: 'TabHostDynamicScreen', + params: {integration: 'brex'}, + state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 1), + }, + ]); + + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/linked'); + }); + + it('resolves tab path when tab-host dynamic screen is the only screen (no base)', () => { + const state = buildState([ + { + name: 'TabHostDynamicScreen', + params: {integration: 'brex'}, + state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), + }, + ]); + + expect(getPathFromState(state as PartialState)).toBe('/brex/edit/all'); + }); + + it('resolves tab path inside a nested navigator', () => { + const state = buildState([ + { + name: 'RHPNavigator', + state: buildState([ + {name: 'WalletScreen'}, + { + name: 'TabHostDynamicScreen', + params: {integration: 'lyft'}, + state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), + }, + ]), + }, + ]); + + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/lyft/edit/all'); + }); + + it('resolves tab-host dynamic screen in backstack under another focused dynamic screen', () => { + // Stack: WalletScreen → TabHostDynamicScreen[TabAll] → VerifyAccountScreen (focused) + // Expected: basePath(WalletScreen) / tabHostSuffix / tabPath / verifyAccountSuffix + const state = buildState([ + {name: 'WalletScreen'}, + { + name: 'TabHostDynamicScreen', + params: {integration: 'brex'}, + state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), + }, + {name: 'VerifyAccountScreen'}, + ]); + + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/all/verify-account'); + }); + + it('tab-host in backstack uses the currently focused tab, not always default', () => { + // Non-default tab (linked) is focused inside the tab-host that sits under another dynamic screen + const state = buildState([ + {name: 'WalletScreen'}, + { + name: 'TabHostDynamicScreen', + params: {integration: 'brex'}, + state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 1), + }, + {name: 'VerifyAccountScreen'}, + ]); + + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/linked/verify-account'); + }); + + it('does not append tab path when tab-host dynamic screen has no nested tab state', () => { + // Edge case: tab state is absent (e.g. partially initialised navigation state) + const state = buildState([{name: 'WalletScreen'}, {name: 'TabHostDynamicScreen', params: {integration: 'brex'}}]); + + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit'); + }); + }); }); From 8ee33581619dd66047a0f0d6e78bd2b2c44aa089 Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Mon, 22 Jun 2026 13:35:54 +0200 Subject: [PATCH 02/11] cleanup --- .../findFocusedRouteWithOnyxTabGuard.ts | 12 +- .../Navigation/helpers/getPathFromState.ts | 25 +-- .../findAllMatchingDynamicSuffixesTests.ts | 83 +++++---- tests/navigation/getPathFromStateTests.ts | 163 ++++++------------ 4 files changed, 111 insertions(+), 172 deletions(-) diff --git a/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts b/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts index ded28cb797fb..899b73efe3ad 100644 --- a/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts +++ b/src/libs/Navigation/helpers/findFocusedRouteWithOnyxTabGuard.ts @@ -1,5 +1,7 @@ -import type {NavigationRoute, NavigationState, ParamListBase, 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 @@ -7,18 +9,18 @@ import {screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config * 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: NavigationState | PartialState): NavigationRoute | undefined { +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 NavigationRoute; + return route; } if (route.state) { - return findFocusedRouteWithOnyxTabGuard(route.state); + return findFocusedRouteWithOnyxTabGuard(route.state as State); } - return route as NavigationRoute; + return route; } export default findFocusedRouteWithOnyxTabGuard; diff --git a/src/libs/Navigation/helpers/getPathFromState.ts b/src/libs/Navigation/helpers/getPathFromState.ts index e90afdd8d8e3..db765cc84831 100644 --- a/src/libs/Navigation/helpers/getPathFromState.ts +++ b/src/libs/Navigation/helpers/getPathFromState.ts @@ -1,14 +1,12 @@ import {getPathFromState as RNGetPathFromState} from '@react-navigation/native'; -import type {NavigationState, PartialState} from '@react-navigation/routers'; import {config, normalizedConfigs, screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config'; +import type {State} from '@libs/Navigation/types'; import type {Screen} from '@src/SCREENS'; import getDynamicRouteQueryParams from './dynamicRoutesUtils/getDynamicRouteQueryParams'; import isDynamicRouteScreen from './dynamicRoutesUtils/isDynamicRouteScreen'; import splitPathAndQuery from './dynamicRoutesUtils/splitPathAndQuery'; import findFocusedRouteWithOnyxTabGuard from './findFocusedRouteWithOnyxTabGuard'; -type State = NavigationState | Omit, 'stale'>; - function isScreen(name: string): name is Screen { return name in normalizedConfigs; } @@ -73,19 +71,12 @@ function buildSuffixFromPattern(pattern: string, params: Record * Pops the deepest focused route from a navigation state tree. * Returns the reduced state, or undefined if the tree becomes empty. * - * Screens listed in `isLeaf` are treated as atomic leaves - the function will - * not recurse into their nested state (e.g. tab navigators), so the entire - * screen is removed as a unit rather than popping an individual tab. - * * @param state - The navigation state tree to pop from - * @param isLeaf - Optional guard: return true for screen names that should be - * treated as leaves (not recursed into). Used to prevent drilling - * into tab navigators hosted by dynamic screens. * @returns The reduced state, or undefined if the tree becomes empty * * @private - Internal helper. Do not export or use outside this file. */ -function popFocusedRoute(state: State, isLeaf?: (name: string) => boolean): State | undefined { +function popFocusedRoute(state: State): State | undefined { const index = state.index ?? state.routes.length - 1; const focusedRoute = state.routes[index]; @@ -95,9 +86,9 @@ function popFocusedRoute(state: State, isLeaf?: (name: string) => boolean): Stat } // the focused route has nested state - try to pop from deeper levels first, - // unless it is a leaf screen (e.g. a tab-hosting dynamic screen). - if (focusedRoute.state && !isLeaf?.(focusedRoute.name ?? '')) { - const nestedResult = popFocusedRoute(focusedRoute.state as State, isLeaf); + // unless it hosts an OnyxTabNavigator (treat it as a leaf). + if (focusedRoute.state && !screensWithOnyxTabNavigator.has(focusedRoute.name ?? '')) { + const nestedResult = popFocusedRoute(focusedRoute.state as State); // A deeper route was successfully popped - rebuild the current level with the updated nested state. if (nestedResult) { @@ -122,10 +113,6 @@ function popFocusedRoute(state: State, isLeaf?: (name: string) => boolean): Stat * Builds a URL path for a dynamic route screen. * Recursively peels off dynamic suffixes and resolves the base path underneath. * - * When the focused dynamic screen hosts a tab navigator (i.e. it is in - * `screensWithOnyxTabNavigator`), the focused tab's path segment is appended - * to the dynamic suffix before the base path is resolved. - * * @param state - The navigation state tree to build the path from * @returns The resolved path for the focused dynamic route screen * @@ -155,7 +142,7 @@ function getPathFromStateWithDynamicRoute(state: State): string { } } - const reducedState = popFocusedRoute(state, (name) => screensWithOnyxTabNavigator.has(name)); + const reducedState = popFocusedRoute(state); if (!reducedState) { return `/${actualSuffix}`; diff --git a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts index 781d1eab6edf..37df441c8c7a 100644 --- a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts +++ b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts @@ -22,18 +22,20 @@ jest.mock('@src/ROUTES', () => ({ describe('findMatchingDynamicSuffix', () => { it('should match a single-segment dynamic suffix', () => { - expect(findMatchingDynamicSuffix('settings/wallet/verify-account')).toMatchObject({ + expect(findMatchingDynamicSuffix('settings/wallet/verify-account')).toEqual({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, + pathUsedForMatching: 'settings/wallet/verify-account', }); }); it('should match when the path has a leading slash', () => { - expect(findMatchingDynamicSuffix('/settings/wallet/verify-account')).toMatchObject({ + expect(findMatchingDynamicSuffix('/settings/wallet/verify-account')).toEqual({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, + pathUsedForMatching: '/settings/wallet/verify-account', }); }); @@ -50,18 +52,20 @@ describe('findMatchingDynamicSuffix', () => { }); it('should ignore query parameters when matching', () => { - expect(findMatchingDynamicSuffix('settings/wallet/verify-account?sortBy=date')).toMatchObject({ + expect(findMatchingDynamicSuffix('settings/wallet/verify-account?sortBy=date')).toEqual({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, + pathUsedForMatching: 'settings/wallet/verify-account?sortBy=date', }); }); it('should handle trailing slashes', () => { - expect(findMatchingDynamicSuffix('settings/wallet/verify-account/')).toMatchObject({ + expect(findMatchingDynamicSuffix('settings/wallet/verify-account/')).toEqual({ pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, + pathUsedForMatching: 'settings/wallet/verify-account/', }); }); @@ -70,34 +74,38 @@ describe('findMatchingDynamicSuffix', () => { }); it('should match a suffix when path has suffix-specific query params', () => { - expect(findMatchingDynamicSuffix('settings/profile/address/country?country=US')).toMatchObject({ + expect(findMatchingDynamicSuffix('settings/profile/address/country?country=US')).toEqual({ pattern: 'country', actualSuffix: 'country', pathParams: {}, + pathUsedForMatching: 'settings/profile/address/country?country=US', }); }); it('should prefer longer multi-segment static match over shorter', () => { - expect(findMatchingDynamicSuffix('/settings/wallet/add-bank-account/verify-account')).toMatchObject({ + expect(findMatchingDynamicSuffix('/settings/wallet/add-bank-account/verify-account')).toEqual({ pattern: 'add-bank-account/verify-account', actualSuffix: 'add-bank-account/verify-account', pathParams: {}, + pathUsedForMatching: '/settings/wallet/add-bank-account/verify-account', }); }); it('should match parametric suffix and extract params', () => { - expect(findMatchingDynamicSuffix('/r/123/flag/456/abc')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/flag/456/abc')).toEqual({ pattern: 'flag/:reportID/:reportActionID', actualSuffix: 'flag/456/abc', pathParams: {reportID: '456', reportActionID: 'abc'}, + pathUsedForMatching: '/r/123/flag/456/abc', }); }); it('should match single-param suffix', () => { - expect(findMatchingDynamicSuffix('/r/123/members/member-details/456')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/members/member-details/456')).toEqual({ pattern: 'member-details/:accountID', actualSuffix: 'member-details/456', pathParams: {accountID: '456'}, + pathUsedForMatching: '/r/123/members/member-details/456', }); }); @@ -110,67 +118,75 @@ describe('findMatchingDynamicSuffix', () => { }); it('should handle query params alongside parametric suffix', () => { - expect(findMatchingDynamicSuffix('/r/123/flag/456/abc?tab=details')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/flag/456/abc?tab=details')).toEqual({ pattern: 'flag/:reportID/:reportActionID', actualSuffix: 'flag/456/abc', pathParams: {reportID: '456', reportActionID: 'abc'}, + pathUsedForMatching: '/r/123/flag/456/abc?tab=details', }); }); it('should match keyboard-shortcuts dynamic suffix', () => { - expect(findMatchingDynamicSuffix('settings/about/keyboard-shortcuts')).toMatchObject({ + expect(findMatchingDynamicSuffix('settings/about/keyboard-shortcuts')).toEqual({ pattern: 'keyboard-shortcuts', actualSuffix: 'keyboard-shortcuts', pathParams: {}, + pathUsedForMatching: 'settings/about/keyboard-shortcuts', }); }); describe('optional path params', () => { it('should match trailing-optional pattern when optional is absent', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/opt-page')).toEqual({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page', pathParams: {}, + pathUsedForMatching: '/r/123/opt-page', }); }); it('should match trailing-optional pattern when optional is present', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page/789')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/opt-page/789')).toEqual({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page/789', pathParams: {id: '789'}, + pathUsedForMatching: '/r/123/opt-page/789', }); }); it('should match middle-optional pattern when optional is absent', () => { - expect(findMatchingDynamicSuffix('/r/123/wrap/end')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/wrap/end')).toEqual({ pattern: 'wrap/:p?/end', actualSuffix: 'wrap/end', pathParams: {}, + pathUsedForMatching: '/r/123/wrap/end', }); }); it('should match middle-optional pattern when optional is present', () => { - expect(findMatchingDynamicSuffix('/r/123/wrap/x/end')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/wrap/x/end')).toEqual({ pattern: 'wrap/:p?/end', actualSuffix: 'wrap/x/end', pathParams: {p: 'x'}, + pathUsedForMatching: '/r/123/wrap/x/end', }); }); it('should ignore query params when matching trailing-optional present-form', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page/789?tab=details')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/opt-page/789?tab=details')).toEqual({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page/789', pathParams: {id: '789'}, + pathUsedForMatching: '/r/123/opt-page/789?tab=details', }); }); it('should ignore query params when matching trailing-optional absent-form', () => { - expect(findMatchingDynamicSuffix('/r/123/opt-page?tab=details')).toMatchObject({ + expect(findMatchingDynamicSuffix('/r/123/opt-page?tab=details')).toEqual({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page', pathParams: {}, + pathUsedForMatching: '/r/123/opt-page?tab=details', }); }); }); @@ -190,16 +206,19 @@ describe('findAllMatchingDynamicSuffixes', () => { }); it('should return a single-element array for an unambiguous static path', () => { - expect(findAllMatchingDynamicSuffixes('settings/wallet/verify-account')).toMatchObject([{pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}]); + expect(findAllMatchingDynamicSuffixes('settings/wallet/verify-account')).toEqual([ + {pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, pathUsedForMatching: 'settings/wallet/verify-account'}, + ]); }); it('should return both a static and a parametric candidate when a tag name matches a static suffix (gl-code collision)', () => { - expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/gl-code')).toMatchObject([ - {pattern: 'gl-code', actualSuffix: 'gl-code', pathParams: {}}, + expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/gl-code')).toEqual([ + {pattern: 'gl-code', actualSuffix: 'gl-code', pathParams: {}, pathUsedForMatching: '/settings/tags/tag-settings/0/gl-code'}, { pattern: 'tag-settings/:orderWeight/:tagName', actualSuffix: 'tag-settings/0/gl-code', pathParams: {orderWeight: '0', tagName: 'gl-code'}, + pathUsedForMatching: '/settings/tags/tag-settings/0/gl-code', }, ]); }); @@ -207,35 +226,35 @@ describe('findAllMatchingDynamicSuffixes', () => { it('should place static candidates before strict parametric candidates (priority order)', () => { const results = findAllMatchingDynamicSuffixes('/base/flag/123/verify-account'); expect(results).toHaveLength(2); - expect(results.at(0)).toMatchObject({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}); - expect(results.at(1)).toMatchObject({ + expect(results.at(0)).toEqual({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, pathUsedForMatching: '/base/flag/123/verify-account'}); + expect(results.at(1)).toEqual({ pattern: 'flag/:reportID/:reportActionID', actualSuffix: 'flag/123/verify-account', pathParams: {reportID: '123', reportActionID: 'verify-account'}, + pathUsedForMatching: '/base/flag/123/verify-account', }); }); it('should place static candidates before optional parametric candidates (priority order)', () => { const results = findAllMatchingDynamicSuffixes('/base/opt-page/verify-account'); expect(results).toHaveLength(2); - expect(results.at(0)).toMatchObject({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}}); - expect(results.at(1)).toMatchObject({ + expect(results.at(0)).toEqual({pattern: 'verify-account', actualSuffix: 'verify-account', pathParams: {}, pathUsedForMatching: '/base/opt-page/verify-account'}); + expect(results.at(1)).toEqual({ pattern: 'opt-page/:id?', actualSuffix: 'opt-page/verify-account', pathParams: {id: 'verify-account'}, + pathUsedForMatching: '/base/opt-page/verify-account', }); }); it('should return a single-element array when only one candidate exists (tag-approver at the end)', () => { - expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/tagname/tag-approver')).toMatchObject([{pattern: 'tag-approver', actualSuffix: 'tag-approver', pathParams: {}}]); + expect(findAllMatchingDynamicSuffixes('/settings/tags/tag-settings/0/tagname/tag-approver')).toEqual([ + {pattern: 'tag-approver', actualSuffix: 'tag-approver', pathParams: {}, pathUsedForMatching: '/settings/tags/tag-settings/0/tagname/tag-approver'}, + ]); }); }); -describe('findAllMatchingDynamicSuffixes – Phase 4 (tab-suffix stripping)', () => { - // 'flag/:reportID/:reportActionID' → tabs: 'AllTab', 'LinkedTab' - // URLs ending with .../flag/456/abc/AllTab should be recognised as the flag route with tab stripped. - // 'keyboard-shortcuts' is registered as a dynamic route but NOT in the tabMap, so Phase 4 - // must not fire even when the URL ends with a seemingly tab-like segment. +describe('findAllMatchingDynamicSuffixes - tab-suffix stripping', () => { const tabMap = new Map>([['flag/:reportID/:reportActionID', new Set(['AllTab', 'LinkedTab'])]]); it('strips the trailing tab segment and returns match with pathUsedForMatching', () => { @@ -267,9 +286,6 @@ describe('findAllMatchingDynamicSuffixes – Phase 4 (tab-suffix stripping)', () }); it('does NOT strip when the last segment is a tab of a different (non-matched) pattern', () => { - // After stripping 'AllTab', the retry on '/base/about/keyboard-shortcuts' finds the - // static 'keyboard-shortcuts' pattern. But tabMap.get('keyboard-shortcuts') is undefined, - // so the scoped check fails and the result is empty. const results = findAllMatchingDynamicSuffixes('/base/about/keyboard-shortcuts/AllTab', tabMap); expect(results).toEqual([]); }); @@ -283,9 +299,6 @@ describe('findAllMatchingDynamicSuffixes – Phase 4 (tab-suffix stripping)', () }); it('recursive retry does not receive tabMap so stripping stops after one level', () => { - // '/base/flag/456/AllTab/LinkedTab' → Phase 4 strips 'LinkedTab' → - // retry '/base/flag/456/AllTab' → 'flag/456/AllTab' matches flag pattern - // (reportID='456', reportActionID='AllTab') → tabMap.get(pattern)?.has('LinkedTab') → true. const results = findAllMatchingDynamicSuffixes('/base/flag/456/AllTab/LinkedTab', tabMap); expect(results).toHaveLength(1); expect(results.at(0)).toMatchObject({ diff --git a/tests/navigation/getPathFromStateTests.ts b/tests/navigation/getPathFromStateTests.ts index d41d7d9d5516..8c71771425e7 100644 --- a/tests/navigation/getPathFromStateTests.ts +++ b/tests/navigation/getPathFromStateTests.ts @@ -9,75 +9,30 @@ jest.mock('@react-navigation/native', () => ({ jest.mock('@libs/Navigation/linkingConfig/config', () => ({ config: {}, normalizedConfigs: { - TestDynamicScreen: { - path: 'test-dynamic', - }, - StandardScreen: { - path: 'standard', - }, - VerifyAccountScreen: { - path: 'verify-account', - }, - CountryScreen: { - path: 'country', - }, - FlagScreen: { - path: 'flag/:reportID/:reportActionID', - }, - ConstantPickerScreen: { - path: 'constant-picker', - }, - WalletScreen: { - path: 'settings/wallet', - }, - ReportScreen: { - path: 'r/:reportID', - }, - // Tab-hosting dynamic screen and its tab children - TabHostDynamicScreen: { - path: ':integration/edit', - }, - TabAll: { - path: 'all', - }, - TabLinked: { - path: 'linked', - }, - }, - // Screens that host an OnyxTabNavigator — findFocusedRouteWithOnyxTabGuard stops here - screensWithOnyxTabNavigator: new Set(['TabHostDynamicScreen']), - // Pattern-to-tabs map used by findAllMatchingDynamicSuffixes Phase 4 (not used in getPathFromState tests) - dynamicTabPatternToTabPaths: new Map(), -})); - -jest.mock('@libs/Navigation/linkingConfig', () => ({ - linkingConfig: { - config: {}, + TestDynamicScreen: {path: 'test-dynamic'}, + StandardScreen: {path: 'standard'}, + VerifyAccountScreen: {path: 'verify-account'}, + CountryScreen: {path: 'country'}, + FlagScreen: {path: 'flag/:reportID/:reportActionID'}, + ConstantPickerScreen: {path: 'constant-picker'}, + WalletScreen: {path: 'settings/wallet'}, + ReportScreen: {path: 'r/:reportID'}, + SplitExpenseScreen: {path: 'split-expense/:reportID'}, + + AmountTab: {path: 'amount'}, + ScanTab: {path: 'scan'}, }, + screensWithOnyxTabNavigator: new Set(['SplitExpenseScreen']), })); jest.mock('@src/ROUTES', () => ({ DYNAMIC_ROUTES: { - TEST_DYNAMIC: { - path: 'test-dynamic', - }, - VERIFY_ACCOUNT: { - path: 'verify-account', - }, - ADDRESS_COUNTRY: { - path: 'country', - queryParams: ['country'], - }, - FLAG: { - path: 'flag/:reportID/:reportActionID', - }, - CONSTANT_PICKER: { - path: 'constant-picker', - queryParams: ['formType', 'fieldName', 'fieldValue'], - }, - TAB_HOST_DYNAMIC: { - path: ':integration/edit', - }, + TEST_DYNAMIC: {path: 'test-dynamic'}, + VERIFY_ACCOUNT: {path: 'verify-account'}, + ADDRESS_COUNTRY: {path: 'country', queryParams: ['country']}, + FLAG: {path: 'flag/:reportID/:reportActionID'}, + CONSTANT_PICKER: {path: 'constant-picker', queryParams: ['formType', 'fieldName', 'fieldValue']}, + SPLIT_EXPENSE: {path: 'split-expense/:reportID'}, }, })); @@ -100,8 +55,8 @@ function buildState(routes: RouteEntry[], index?: number): TestState { } as TestState; } -function realFindFocusedRoute(state: TestState | RouteEntry['state']): RouteEntry | undefined { - let current: TestState | RouteEntry['state'] = state; +function realFindFocusedRoute(s: TestState | RouteEntry['state']): RouteEntry | undefined { + let current: TestState | RouteEntry['state'] = s; while (current?.routes?.[current.index ?? 0]?.state != null) { current = current.routes[current.index ?? 0].state; } @@ -310,7 +265,7 @@ describe('getPathFromState', () => { }); }); - describe('dynamic screen with tab navigator inside', () => { + describe('tab navigator integration (OnyxTabNavigator)', () => { beforeEach(() => { mockRNGetPathFromState.mockImplementation((s: TestState) => { const route = realFindFocusedRoute(s); @@ -319,98 +274,80 @@ describe('getPathFromState', () => { }); }); - it('resolves default tab (index 0) when tab-host dynamic screen is focused', () => { + it('appends focused tab path segment when first tab is focused', () => { const state = buildState([ {name: 'WalletScreen'}, { - name: 'TabHostDynamicScreen', - params: {integration: 'brex'}, - state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), + name: 'SplitExpenseScreen', + params: {reportID: '123'}, + state: buildState([{name: 'AmountTab'}, {name: 'ScanTab'}], 0), }, ]); - expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/all'); + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/split-expense/123/amount'); }); - it('resolves non-default tab (index 1) when tab-host dynamic screen is focused', () => { + it('appends focused tab path segment when second tab is focused', () => { const state = buildState([ {name: 'WalletScreen'}, { - name: 'TabHostDynamicScreen', - params: {integration: 'brex'}, - state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 1), + name: 'SplitExpenseScreen', + params: {reportID: '123'}, + state: buildState([{name: 'AmountTab'}, {name: 'ScanTab'}], 1), }, ]); - expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/linked'); + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/split-expense/123/scan'); }); - it('resolves tab path when tab-host dynamic screen is the only screen (no base)', () => { - const state = buildState([ - { - name: 'TabHostDynamicScreen', - params: {integration: 'brex'}, - state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), - }, - ]); + it('omits tab segment when tab-hosting screen has no nested state', () => { + const state = buildState([{name: 'WalletScreen'}, {name: 'SplitExpenseScreen', params: {reportID: '123'}}]); - expect(getPathFromState(state as PartialState)).toBe('/brex/edit/all'); + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/split-expense/123'); }); - it('resolves tab path inside a nested navigator', () => { + it('tab-hosting screen inside a nested navigator', () => { const state = buildState([ { name: 'RHPNavigator', state: buildState([ {name: 'WalletScreen'}, { - name: 'TabHostDynamicScreen', - params: {integration: 'lyft'}, - state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), + name: 'SplitExpenseScreen', + params: {reportID: '789'}, + state: buildState([{name: 'AmountTab'}, {name: 'ScanTab'}], 1), }, ]), }, ]); - expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/lyft/edit/all'); + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/split-expense/789/scan'); }); - it('resolves tab-host dynamic screen in backstack under another focused dynamic screen', () => { - // Stack: WalletScreen → TabHostDynamicScreen[TabAll] → VerifyAccountScreen (focused) - // Expected: basePath(WalletScreen) / tabHostSuffix / tabPath / verifyAccountSuffix + it('tab-hosting screen is the only route (no base)', () => { const state = buildState([ - {name: 'WalletScreen'}, { - name: 'TabHostDynamicScreen', - params: {integration: 'brex'}, - state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 0), + name: 'SplitExpenseScreen', + params: {reportID: '42'}, + state: buildState([{name: 'AmountTab'}, {name: 'ScanTab'}], 0), }, - {name: 'VerifyAccountScreen'}, ]); - expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/all/verify-account'); + expect(getPathFromState(state as PartialState)).toBe('/split-expense/42/amount'); }); - it('tab-host in backstack uses the currently focused tab, not always default', () => { - // Non-default tab (linked) is focused inside the tab-host that sits under another dynamic screen + it('popFocusedRoute treats tab-hosting screen as a leaf (removes whole screen, not individual tab)', () => { const state = buildState([ {name: 'WalletScreen'}, { - name: 'TabHostDynamicScreen', - params: {integration: 'brex'}, - state: buildState([{name: 'TabAll'}, {name: 'TabLinked'}], 1), + name: 'SplitExpenseScreen', + params: {reportID: '123'}, + state: buildState([{name: 'AmountTab'}, {name: 'ScanTab'}], 0), }, {name: 'VerifyAccountScreen'}, ]); - expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit/linked/verify-account'); - }); - - it('does not append tab path when tab-host dynamic screen has no nested tab state', () => { - // Edge case: tab state is absent (e.g. partially initialised navigation state) - const state = buildState([{name: 'WalletScreen'}, {name: 'TabHostDynamicScreen', params: {integration: 'brex'}}]); - - expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/brex/edit'); + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/split-expense/123/amount/verify-account'); }); }); }); From d6eca6084ec3fdebe325445fe693686c01f9d58d Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Mon, 22 Jun 2026 14:07:12 +0200 Subject: [PATCH 03/11] fix tests + typecheck --- .../findAllMatchingDynamicSuffixes.ts | 2 +- .../Navigation/helpers/getAdaptedStateFromPath.ts | 12 ++++++------ src/libs/Navigation/linkingConfig/config.ts | 3 +++ .../collectScreensWithTabNavigatorTests.ts | 12 ++++++------ tests/navigation/getDynamicRouteAdaptedStateTests.ts | 1 + tests/navigation/getMatchingFullScreenRouteTests.ts | 1 + tests/navigation/getStateFromPathTests.ts | 1 + tests/navigation/useDynamicBackPathTests.ts | 3 +++ 8 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts b/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts index 7b72da9c8924..428726c9a78f 100644 --- a/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts +++ b/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts @@ -51,7 +51,7 @@ function tryMatchParametric(candidate: string, candidateSegmentCount: number, pa } /** - * Strips the trailing tab segment from a path and retries matching against Phases 1–3. + * Strips the trailing tab segment from a path and retries matching. * Returns an empty array if stripping is not applicable. * Calls `findAllMatchingDynamicSuffixes` recursively with an empty map to prevent double-stripping. * diff --git a/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts b/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts index 0115d2cb6c2e..642971f8e12c 100644 --- a/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts +++ b/src/libs/Navigation/helpers/getAdaptedStateFromPath.ts @@ -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'; @@ -69,11 +69,11 @@ function getTabNavigatorState(selectedTabRoute: NavigationPartialRoute): Navigat return {name: NAVIGATORS.TAB_NAVIGATOR, state: {routes, index}}; } -function isRouteWithBackToParam(route: NavigationPartialRoute): route is Route { +function isRouteWithBackToParam(route: NavigationRoute): route is Route { return route.params !== undefined && 'backTo' in route.params && typeof route.params.backTo === 'string'; } -function isRouteWithReportID(route: NavigationPartialRoute): route is Route { +function isRouteWithReportID(route: NavigationRoute): route is Route { return route.params !== undefined && 'reportID' in route.params && typeof route.params.reportID === 'string'; } @@ -83,7 +83,7 @@ function isRouteWithReportID(route: NavigationPartialRoute): route is Route['config'] = { screens: { [CONST.TAB.RECEIPT_PARTNERS.ALL]: { path: CONST.TAB.RECEIPT_PARTNERS.ALL, + exact: true, }, [CONST.TAB.RECEIPT_PARTNERS.LINKED]: { path: CONST.TAB.RECEIPT_PARTNERS.LINKED, + exact: true, }, [CONST.TAB.RECEIPT_PARTNERS.OUTSTANDING]: { path: CONST.TAB.RECEIPT_PARTNERS.OUTSTANDING, + exact: true, }, }, }, diff --git a/tests/navigation/collectScreensWithTabNavigatorTests.ts b/tests/navigation/collectScreensWithTabNavigatorTests.ts index 8349f28704f4..4cc74a9603e1 100644 --- a/tests/navigation/collectScreensWithTabNavigatorTests.ts +++ b/tests/navigation/collectScreensWithTabNavigatorTests.ts @@ -19,7 +19,7 @@ describe('collectScreensWithTabNavigator', () => { const result = collectScreensWithTabNavigator(screens); - expect(result.size).toBe(0); + expect(result.screensWithTabNavigator.size).toBe(0); }); it('should collect a screen that has both path and screens', () => { @@ -29,7 +29,7 @@ describe('collectScreensWithTabNavigator', () => { const result = collectScreensWithTabNavigator(screens); - expect(result).toEqual(new Set(['TabScreen'])); + expect(result.screensWithTabNavigator).toEqual(new Set(['TabScreen'])); }); it('should exclude navigator names even if they have both path and screens', () => { @@ -40,7 +40,7 @@ describe('collectScreensWithTabNavigator', () => { const result = collectScreensWithTabNavigator(screens); - expect(result.size).toBe(0); + expect(result.screensWithTabNavigator.size).toBe(0); }); it('should collect a nested tab screen inside a navigator', () => { @@ -54,7 +54,7 @@ describe('collectScreensWithTabNavigator', () => { const result = collectScreensWithTabNavigator(screens); - expect(result).toEqual(new Set(['NestedTabScreen'])); + expect(result.screensWithTabNavigator).toEqual(new Set(['NestedTabScreen'])); }); it('should collect tab screens at all depth levels in a 3-level structure', () => { @@ -73,7 +73,7 @@ describe('collectScreensWithTabNavigator', () => { const result = collectScreensWithTabNavigator(screens); - expect(result).toEqual(new Set(['Level1Tab', 'Level3Tab'])); + expect(result.screensWithTabNavigator).toEqual(new Set(['Level1Tab', 'Level3Tab'])); }); it('should collect only matching screens from a mixed config', () => { @@ -88,6 +88,6 @@ describe('collectScreensWithTabNavigator', () => { const result = collectScreensWithTabNavigator(screens); - expect(result).toEqual(new Set(['ValidTab', 'AnotherTab'])); + expect(result.screensWithTabNavigator).toEqual(new Set(['ValidTab', 'AnotherTab'])); }); }); diff --git a/tests/navigation/getDynamicRouteAdaptedStateTests.ts b/tests/navigation/getDynamicRouteAdaptedStateTests.ts index 351403ec5d2e..ad013f99389f 100644 --- a/tests/navigation/getDynamicRouteAdaptedStateTests.ts +++ b/tests/navigation/getDynamicRouteAdaptedStateTests.ts @@ -21,6 +21,7 @@ jest.mock('@libs/Navigation/linkingConfig/config', () => ({ DynCrossStack: {path: 'suffix-cross'}, }, screensWithOnyxTabNavigator: new Set(), + dynamicTabPatternToTabPaths: new Map(), })); jest.mock('@src/ROUTES', () => ({ diff --git a/tests/navigation/getMatchingFullScreenRouteTests.ts b/tests/navigation/getMatchingFullScreenRouteTests.ts index 4ab687e0ce30..8971919aed14 100644 --- a/tests/navigation/getMatchingFullScreenRouteTests.ts +++ b/tests/navigation/getMatchingFullScreenRouteTests.ts @@ -9,6 +9,7 @@ jest.mock('@libs/Navigation/linkingConfig/config', () => ({ DynamicScreen: {path: 'suffix-a'}, }, screensWithOnyxTabNavigator: new Set(), + dynamicTabPatternToTabPaths: new Map(), })); jest.mock('@libs/ReportUtils', () => ({ diff --git a/tests/navigation/getStateFromPathTests.ts b/tests/navigation/getStateFromPathTests.ts index e6b73892c396..c7346a47ebda 100644 --- a/tests/navigation/getStateFromPathTests.ts +++ b/tests/navigation/getStateFromPathTests.ts @@ -20,6 +20,7 @@ jest.mock('@libs/Navigation/linkingConfig', () => ({ jest.mock('@libs/Navigation/linkingConfig/config', () => ({ screensWithOnyxTabNavigator: new Set(), + dynamicTabPatternToTabPaths: new Map(), })); jest.mock('@src/ROUTES', () => ({ diff --git a/tests/navigation/useDynamicBackPathTests.ts b/tests/navigation/useDynamicBackPathTests.ts index 0eb060126549..6dbc65a1e592 100644 --- a/tests/navigation/useDynamicBackPathTests.ts +++ b/tests/navigation/useDynamicBackPathTests.ts @@ -5,6 +5,9 @@ import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; jest.mock('@hooks/useRootNavigationState', () => jest.fn()); jest.mock('@libs/Navigation/helpers/getPathFromState', () => jest.fn()); +jest.mock('@libs/Navigation/linkingConfig/config', () => ({ + dynamicTabPatternToTabPaths: new Map(), +})); jest.mock('@src/ROUTES', () => ({ default: { HOME: 'home', From 087b17e8a6b64f9cb6c73c5ae3be69f6e2de183d Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Mon, 22 Jun 2026 14:12:52 +0200 Subject: [PATCH 04/11] fix knip check --- src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts b/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts index 90b366c07abe..ab2961f3aebb 100644 --- a/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts +++ b/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts @@ -56,5 +56,5 @@ function collectScreensWithTabNavigator( return result; } -export type {ScreenConfigEntry, CollectResult}; +export type {ScreenConfigEntry}; export default collectScreensWithTabNavigator; From 378de94d899f5f8965498992d81f575bda96d449 Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Mon, 22 Jun 2026 14:38:01 +0200 Subject: [PATCH 05/11] revert config changes to main --- src/libs/Navigation/linkingConfig/config.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libs/Navigation/linkingConfig/config.ts b/src/libs/Navigation/linkingConfig/config.ts index b38461b9d478..9f9c979f132b 100644 --- a/src/libs/Navigation/linkingConfig/config.ts +++ b/src/libs/Navigation/linkingConfig/config.ts @@ -980,15 +980,15 @@ const config: LinkingOptions['config'] = { path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT.route, screens: { [CONST.TAB.RECEIPT_PARTNERS.ALL]: { - path: CONST.TAB.RECEIPT_PARTNERS.ALL, + path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT_ALL, exact: true, }, [CONST.TAB.RECEIPT_PARTNERS.LINKED]: { - path: CONST.TAB.RECEIPT_PARTNERS.LINKED, + path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT_LINKED, exact: true, }, [CONST.TAB.RECEIPT_PARTNERS.OUTSTANDING]: { - path: CONST.TAB.RECEIPT_PARTNERS.OUTSTANDING, + path: ROUTES.WORKSPACE_RECEIPT_PARTNERS_INVITE_EDIT_OUTSTANDING, exact: true, }, }, From 72669f4c18dfdc7189f3d25a84e5bb31593c0517 Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Wed, 24 Jun 2026 13:50:14 +0200 Subject: [PATCH 06/11] refactor logic of matching suffixes --- .../findAllMatchingDynamicSuffixes.ts | 110 +++++++++--------- .../Navigation/helpers/getPathFromState.ts | 2 +- .../findAllMatchingDynamicSuffixesTests.ts | 24 ++-- 3 files changed, 63 insertions(+), 73 deletions(-) diff --git a/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts b/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts index 428726c9a78f..91c87fb4e697 100644 --- a/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts +++ b/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts @@ -15,13 +15,15 @@ type DynamicSuffixMatch = { pathUsedForMatching: string; }; +type RawSuffixMatch = Omit; + /** * 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[]): Omit | undefined { +function tryMatchParametric(candidate: string, candidateSegmentCount: number, patterns: CompiledEntry[]): RawSuffixMatch | undefined { const normalized = candidate.endsWith('/') ? candidate : `${candidate}/`; for (const {compiled} of patterns) { @@ -51,28 +53,47 @@ function tryMatchParametric(candidate: string, candidateSegmentCount: number, pa } /** - * Strips the trailing tab segment from a path and retries matching. - * Returns an empty array if stripping is not applicable. - * Calls `findAllMatchingDynamicSuffixes` recursively with an empty map to prevent double-stripping. + * Collects all registered dynamic route suffixes that syntactically match the end of the given path, + * 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. * * @private - Internal helper. Do not export or use outside this file. */ -function tryStripTabSuffix(normalizedPath: string, query: string, tabPatternMap: Map>): DynamicSuffixMatch[] { - if (tabPatternMap.size === 0) { - return []; +function collectMatchesForPath(normalizedPath: string): RawSuffixMatch[] { + const segments = normalizedPath.split('/').filter(Boolean); + const results: RawSuffixMatch[] = []; + const seenPatterns = new Set(); + + // Phase 1: Static matches (longest to shortest) + for (let i = 0; i < segments.length; i++) { + const candidate = segments.slice(i).join('/'); + if (dynamicRoutePaths.has(candidate)) { + results.push({pattern: candidate, actualSuffix: candidate, pathParams: {}}); + seenPatterns.add(candidate); + } } - const lastSlash = normalizedPath.lastIndexOf('/'); - if (lastSlash <= 0) { - return []; + + // Phase 2: Strict parametric patterns - no optional params (longest to shortest) + for (let i = 0; i < segments.length; i++) { + const match = tryMatchParametric(segments.slice(i).join('/'), segments.length - i, compiledStrictParametricDynamicRoutes); + if (match && !seenPatterns.has(match.pattern)) { + results.push(match); + seenPatterns.add(match.pattern); + } } - const lastSegment = normalizedPath.slice(lastSlash + 1); - const pathWithoutTab = normalizedPath.slice(0, lastSlash); - const fullPathWithoutTab = query ? `${pathWithoutTab}?${query}` : pathWithoutTab; - const retriedResults = findAllMatchingDynamicSuffixes(pathWithoutTab, new Map()); - // Keep only matches whose pattern owns the stripped segment as a registered tab-child path. - const validResults = retriedResults.filter((match) => tabPatternMap.get(match.pattern)?.has(lastSegment)); - return validResults.map((match) => ({...match, pathUsedForMatching: fullPathWithoutTab})); + // Phase 3: Optional parametric patterns - has at least one :param? (longest to shortest) + for (let i = 0; i < segments.length; i++) { + const match = tryMatchParametric(segments.slice(i).join('/'), segments.length - i, compiledOptionalParametricDynamicRoutes); + if (match && !seenPatterns.has(match.pattern)) { + results.push(match); + seenPatterns.add(match.pattern); + } + } + + return results; } /** @@ -93,54 +114,33 @@ function tryStripTabSuffix(normalizedPath: string, query: string, tabPatternMap: * to what `findMatchingDynamicSuffix` would return for the same path. * * @param path - The path to find all matching dynamic suffixes for - * @param tabPatternMap - Override for the tab-pattern map (defaults to the app-wide - * `dynamicTabPatternToTabPaths`). * @returns Array of all matching dynamic suffixes in priority order (may be empty) */ -function findAllMatchingDynamicSuffixes(path = '', tabPatternMap: Map> = dynamicTabPatternToTabPaths): DynamicSuffixMatch[] { +function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] { const [normalizedPath, query] = splitPathAndQuery(path); if (!normalizedPath) { return []; } - // Handles dynamic routes that host a tab navigator: if the URL ends with a tab segment, - // strip it and return the match immediately. - const tabResults = tryStripTabSuffix(normalizedPath, query ?? '', tabPatternMap); - if (tabResults.length > 0) { - return tabResults; - } - - const segments = normalizedPath.split('/').filter(Boolean); - const results: DynamicSuffixMatch[] = []; - const seenPatterns = new Set(); - - // Phase 1: Static matches (longest to shortest) - for (let i = 0; i < segments.length; i++) { - const candidate = segments.slice(i).join('/'); - if (dynamicRoutePaths.has(candidate)) { - results.push({pattern: candidate, actualSuffix: candidate, pathParams: {}, pathUsedForMatching: path}); - seenPatterns.add(candidate); - } - } - - // Phase 2: Strict parametric patterns - no optional params (longest to shortest) - for (let i = 0; i < segments.length; i++) { - const match = tryMatchParametric(segments.slice(i).join('/'), segments.length - i, compiledStrictParametricDynamicRoutes); - if (match && !seenPatterns.has(match.pattern)) { - results.push({...match, pathUsedForMatching: path}); - seenPatterns.add(match.pattern); - } - } - - // Phase 3: Optional parametric patterns - has at least one :param? (longest to shortest) - for (let i = 0; i < segments.length; i++) { - const match = tryMatchParametric(segments.slice(i).join('/'), segments.length - i, compiledOptionalParametricDynamicRoutes); - if (match && !seenPatterns.has(match.pattern)) { - results.push({...match, pathUsedForMatching: path}); - seenPatterns.add(match.pattern); + // 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})); } } + const results = collectMatchesForPath(normalizedPath).map((match) => ({...match, pathUsedForMatching: path})); return results; } diff --git a/src/libs/Navigation/helpers/getPathFromState.ts b/src/libs/Navigation/helpers/getPathFromState.ts index db765cc84831..4f2655fcc0dc 100644 --- a/src/libs/Navigation/helpers/getPathFromState.ts +++ b/src/libs/Navigation/helpers/getPathFromState.ts @@ -87,7 +87,7 @@ function popFocusedRoute(state: State): State | undefined { // the focused route has nested state - try to pop from deeper levels first, // unless it hosts an OnyxTabNavigator (treat it as a leaf). - if (focusedRoute.state && !screensWithOnyxTabNavigator.has(focusedRoute.name ?? '')) { + if (focusedRoute.state && focusedRoute.name && !screensWithOnyxTabNavigator.has(focusedRoute.name)) { const nestedResult = popFocusedRoute(focusedRoute.state as State); // A deeper route was successfully popped - rebuild the current level with the updated nested state. diff --git a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts index 37df441c8c7a..66acc286a1d2 100644 --- a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts +++ b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts @@ -1,7 +1,7 @@ import findAllMatchingDynamicSuffixes, {findMatchingDynamicSuffix} from '@libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes'; jest.mock('@libs/Navigation/linkingConfig/config', () => ({ - dynamicTabPatternToTabPaths: new Map(), + dynamicTabPatternToTabPaths: new Map([['flag/:reportID/:reportActionID', new Set(['AllTab', 'LinkedTab'])]]), })); jest.mock('@src/ROUTES', () => ({ @@ -255,10 +255,8 @@ describe('findAllMatchingDynamicSuffixes', () => { }); describe('findAllMatchingDynamicSuffixes - tab-suffix stripping', () => { - const tabMap = new Map>([['flag/:reportID/:reportActionID', new Set(['AllTab', 'LinkedTab'])]]); - it('strips the trailing tab segment and returns match with pathUsedForMatching', () => { - const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab', tabMap); + const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab'); expect(results).toHaveLength(1); expect(results.at(0)).toEqual({ pattern: 'flag/:reportID/:reportActionID', @@ -269,7 +267,7 @@ describe('findAllMatchingDynamicSuffixes - tab-suffix stripping', () => { }); it('strips the non-default tab segment and sets pathUsedForMatching', () => { - const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/LinkedTab', tabMap); + const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/LinkedTab'); expect(results).toHaveLength(1); expect(results.at(0)).toMatchObject({ pattern: 'flag/:reportID/:reportActionID', @@ -278,7 +276,7 @@ describe('findAllMatchingDynamicSuffixes - tab-suffix stripping', () => { }); it('preserves query string in pathUsedForMatching when stripping tab segment', () => { - const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab?foo=bar', tabMap); + const results = findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab?foo=bar'); expect(results).toHaveLength(1); expect(results.at(0)).toMatchObject({ pathUsedForMatching: '/base/flag/456/abc?foo=bar', @@ -286,20 +284,12 @@ describe('findAllMatchingDynamicSuffixes - tab-suffix stripping', () => { }); it('does NOT strip when the last segment is a tab of a different (non-matched) pattern', () => { - const results = findAllMatchingDynamicSuffixes('/base/about/keyboard-shortcuts/AllTab', tabMap); + const results = findAllMatchingDynamicSuffixes('/base/about/keyboard-shortcuts/AllTab'); expect(results).toEqual([]); }); - it('does NOT strip when tabMap is not provided', () => { - expect(findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab')).toEqual([]); - }); - - it('does NOT strip when tabMap is empty', () => { - expect(findAllMatchingDynamicSuffixes('/base/flag/456/abc/AllTab', new Map())).toEqual([]); - }); - - it('recursive retry does not receive tabMap so stripping stops after one level', () => { - const results = findAllMatchingDynamicSuffixes('/base/flag/456/AllTab/LinkedTab', tabMap); + it('stripping stops after one level - nested tab segments do not double-strip', () => { + const results = findAllMatchingDynamicSuffixes('/base/flag/456/AllTab/LinkedTab'); expect(results).toHaveLength(1); expect(results.at(0)).toMatchObject({ pattern: 'flag/:reportID/:reportActionID', From ddb26da2525afb781629a617126494d3cb1fbe4f Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Thu, 25 Jun 2026 12:37:51 +0200 Subject: [PATCH 07/11] fix suffix and query splitting in getPathFromState --- src/libs/Navigation/helpers/getPathFromState.ts | 3 ++- tests/navigation/getPathFromStateTests.ts | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/libs/Navigation/helpers/getPathFromState.ts b/src/libs/Navigation/helpers/getPathFromState.ts index 4f2655fcc0dc..d6a6f24d493a 100644 --- a/src/libs/Navigation/helpers/getPathFromState.ts +++ b/src/libs/Navigation/helpers/getPathFromState.ts @@ -137,7 +137,8 @@ function getPathFromStateWithDynamicRoute(state: State): string { const focusedTab = tabState.routes[tabIndex]; const tabPath = focusedTab && isScreen(focusedTab.name) ? normalizedConfigs[focusedTab.name]?.path : undefined; if (tabPath) { - actualSuffix = `${actualSuffix}/${tabPath}`; + const [suffixPathOnly, suffixQueryOnly] = splitPathAndQuery(actualSuffix); + actualSuffix = `${suffixPathOnly}/${tabPath}${suffixQueryOnly ? `?${suffixQueryOnly}` : ''}`; } } } diff --git a/tests/navigation/getPathFromStateTests.ts b/tests/navigation/getPathFromStateTests.ts index 8c71771425e7..9547237fb7c3 100644 --- a/tests/navigation/getPathFromStateTests.ts +++ b/tests/navigation/getPathFromStateTests.ts @@ -18,11 +18,12 @@ jest.mock('@libs/Navigation/linkingConfig/config', () => ({ WalletScreen: {path: 'settings/wallet'}, ReportScreen: {path: 'r/:reportID'}, SplitExpenseScreen: {path: 'split-expense/:reportID'}, + SplitExpenseQueryScreen: {path: 'split-expense-q/:reportID'}, AmountTab: {path: 'amount'}, ScanTab: {path: 'scan'}, }, - screensWithOnyxTabNavigator: new Set(['SplitExpenseScreen']), + screensWithOnyxTabNavigator: new Set(['SplitExpenseScreen', 'SplitExpenseQueryScreen']), })); jest.mock('@src/ROUTES', () => ({ @@ -33,6 +34,7 @@ jest.mock('@src/ROUTES', () => ({ FLAG: {path: 'flag/:reportID/:reportActionID'}, CONSTANT_PICKER: {path: 'constant-picker', queryParams: ['formType', 'fieldName', 'fieldValue']}, SPLIT_EXPENSE: {path: 'split-expense/:reportID'}, + SPLIT_EXPENSE_QUERY: {path: 'split-expense-q/:reportID', queryParams: ['currency']}, }, })); @@ -336,6 +338,19 @@ describe('getPathFromState', () => { expect(getPathFromState(state as PartialState)).toBe('/split-expense/42/amount'); }); + it('tab segment is placed before query params when the tab-host screen has query params', () => { + const state = buildState([ + {name: 'WalletScreen'}, + { + name: 'SplitExpenseQueryScreen', + params: {reportID: '123', currency: 'USD'}, + state: buildState([{name: 'AmountTab'}, {name: 'ScanTab'}], 1), + }, + ]); + + expect(getPathFromState(state as PartialState)).toBe('/settings/wallet/split-expense-q/123/scan?currency=USD'); + }); + it('popFocusedRoute treats tab-hosting screen as a leaf (removes whole screen, not individual tab)', () => { const state = buildState([ {name: 'WalletScreen'}, From eab2158872f27a0bc3bdceadd8a6d1526b2f0804 Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Thu, 25 Jun 2026 12:14:02 +0200 Subject: [PATCH 08/11] add tab navi immediately after refresh --- .../findAllMatchingDynamicSuffixes.ts | 4 ++- .../getStateForDynamicRoute.ts | 34 +++++++++++++++++-- .../Navigation/helpers/getStateFromPath.ts | 4 +-- .../findAllMatchingDynamicSuffixesTests.ts | 1 + 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts b/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts index 91c87fb4e697..f3912cd1515d 100644 --- a/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts +++ b/src/libs/Navigation/helpers/dynamicRoutesUtils/findAllMatchingDynamicSuffixes.ts @@ -13,6 +13,8 @@ type DynamicSuffixMatch = { pathParams: Record; /** 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; @@ -136,7 +138,7 @@ function findAllMatchingDynamicSuffixes(path = ''): DynamicSuffixMatch[] { 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})); + return tabMatches.map((match) => ({...match, pathUsedForMatching: fullPathWithoutTab, strippedTabPath: lastSegment})); } } diff --git a/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts b/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts index 256c939db62b..7b5fca2e316a 100644 --- a/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts +++ b/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts @@ -1,4 +1,4 @@ -import {normalizedConfigs} from '@libs/Navigation/linkingConfig/config'; +import {normalizedConfigs, screensWithOnyxTabNavigator} from '@libs/Navigation/linkingConfig/config'; import {DYNAMIC_ROUTES} from '@src/ROUTES'; import type {DynamicRouteSuffix} from '@src/ROUTES'; import splitPathAndQuery from './splitPathAndQuery'; @@ -7,6 +7,7 @@ type LeafRoute = { name: string; path: string; params?: Record; + state?: {routes: Array<{name: string}>; index: 0}; }; type NestedRoute = { @@ -21,6 +22,22 @@ type RouteNode = LeafRoute | NestedRoute; const configEntries = Object.entries(normalizedConfigs); +/** + * Finds the screen name of a tab child by its parent host screen name and its URL path segment. + * Needed because screen name and path are conventionally identical today, but may diverge. + * + * @private - Internal helper. Do not export or use outside this file. + */ +function findTabScreenName(hostScreenName: string, activeTabPath: string): string | undefined { + for (const [screenName, config] of configEntries) { + const parentScreenName = config.routeNames.at(-2); // at(-1) is the tab child itself; at(-2) is the tab-host parent + if (parentScreenName === hostScreenName && config.path === activeTabPath) { + return screenName; + } + } + return undefined; +} + /** * Parses a query string into a key-value record. * @@ -54,7 +71,7 @@ function getRouteNamesForDynamicRoute(dynamicRouteName: DynamicRouteSuffix): str return null; } -function getStateForDynamicRoute(path: string, dynamicRouteName: keyof typeof DYNAMIC_ROUTES, parentRouteParams?: Record) { +function getStateForDynamicRoute(path: string, dynamicRouteName: keyof typeof DYNAMIC_ROUTES, parentRouteParams?: Record, activeTabPath?: string) { const routeConfig = getRouteNamesForDynamicRoute(DYNAMIC_ROUTES[dynamicRouteName].path); const [, query] = splitPathAndQuery(path); const params = getParamsFromQuery(query); @@ -75,6 +92,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 = findTabScreenName(currentRoute, activeTabPath) ?? activeTabPath; + return { + name: currentRoute, + path, + ...paramsSpread, + state: {routes: [{name: tabScreenName}], index: 0 as const}, + }; + } + return { name: currentRoute ?? '', path, diff --git a/src/libs/Navigation/helpers/getStateFromPath.ts b/src/libs/Navigation/helpers/getStateFromPath.ts index f16276960244..49f38a88c01c 100644 --- a/src/libs/Navigation/helpers/getStateFromPath.ts +++ b/src/libs/Navigation/helpers/getStateFromPath.ts @@ -29,7 +29,7 @@ function getStateFromPath(path: Route): PartialState { const dynamicRouteKeys = Object.keys(DYNAMIC_ROUTES) as DynamicRouteKey[]; for (const suffixMatch of allSuffixMatches) { - const {pattern, actualSuffix, pathParams, pathUsedForMatching} = suffixMatch; + const {pattern, actualSuffix, pathParams, pathUsedForMatching, strippedTabPath} = suffixMatch; const pathWithoutDynamicSuffix = getPathWithoutDynamicSuffix(pathUsedForMatching, actualSuffix, pattern); // Find the DYNAMIC_ROUTES config key whose path matches the extracted pattern. @@ -48,7 +48,7 @@ function getStateFromPath(path: Route): PartialState { ...(focusedRoute?.params as Record | undefined), ...pathParams, }; - return getStateForDynamicRoute(normalizedPath, dynamicRoute as DynamicRouteKey, mergedParams); + return getStateForDynamicRoute(normalizedPath, dynamicRoute as DynamicRouteKey, mergedParams, strippedTabPath); } // If the base path is empty there's no underlying screen - show Not Found immediately. diff --git a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts index 66acc286a1d2..541a5f3cdf3e 100644 --- a/tests/navigation/findAllMatchingDynamicSuffixesTests.ts +++ b/tests/navigation/findAllMatchingDynamicSuffixesTests.ts @@ -263,6 +263,7 @@ describe('findAllMatchingDynamicSuffixes - tab-suffix stripping', () => { actualSuffix: 'flag/456/abc', pathParams: {reportID: '456', reportActionID: 'abc'}, pathUsedForMatching: '/base/flag/456/abc', + strippedTabPath: 'AllTab', }); }); From 942cebea65b24d1d7cdc596a75a5b4cf3babb55e Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Thu, 25 Jun 2026 12:25:57 +0200 Subject: [PATCH 09/11] optimize config --- .../helpers/collectScreensWithTabNavigator.ts | 14 ++++++++++--- .../getStateForDynamicRoute.ts | 20 ++----------------- src/libs/Navigation/linkingConfig/config.ts | 8 ++++++-- 3 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts b/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts index ab2961f3aebb..4de783c48b08 100644 --- a/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts +++ b/src/libs/Navigation/helpers/collectScreensWithTabNavigator.ts @@ -11,6 +11,10 @@ type CollectResult = { /** Maps dynamic-route pattern - tab-child paths of that screen's tab navigator. * Used by findAllMatchingDynamicSuffixes to safely strip trailing tab segments. */ dynamicTabPatternToTabPaths: Map>; + + /** 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>; }; /** @@ -26,7 +30,7 @@ type CollectResult = { */ function collectScreensWithTabNavigator( screens: Record, - result: CollectResult = {screensWithTabNavigator: new Set(), dynamicTabPatternToTabPaths: new Map()}, + result: CollectResult = {screensWithTabNavigator: new Set(), dynamicTabPatternToTabPaths: new Map(), dynamicTabScreensByHost: new Map()}, ): CollectResult { const screenConfigEntries = Object.entries(screens); for (const [screenName, screenConfig] of screenConfigEntries) { @@ -34,17 +38,21 @@ function collectScreensWithTabNavigator( if (screenConfig.path !== undefined && screenConfig.screens && !navigatorNames.has(screenName)) { result.screensWithTabNavigator.add(screenName); - // For dynamic tab-host screens, map the route pattern - tab paths for findAllMatchingDynamicSuffixes. + // 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(); - for (const tabConfig of Object.values(screenConfig.screens)) { + const tabScreensByPath = new Map(); + 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); } } } diff --git a/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts b/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts index 7b5fca2e316a..fa380d85c701 100644 --- a/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts +++ b/src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts @@ -1,4 +1,4 @@ -import {normalizedConfigs, screensWithOnyxTabNavigator} 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'; @@ -22,22 +22,6 @@ type RouteNode = LeafRoute | NestedRoute; const configEntries = Object.entries(normalizedConfigs); -/** - * Finds the screen name of a tab child by its parent host screen name and its URL path segment. - * Needed because screen name and path are conventionally identical today, but may diverge. - * - * @private - Internal helper. Do not export or use outside this file. - */ -function findTabScreenName(hostScreenName: string, activeTabPath: string): string | undefined { - for (const [screenName, config] of configEntries) { - const parentScreenName = config.routeNames.at(-2); // at(-1) is the tab child itself; at(-2) is the tab-host parent - if (parentScreenName === hostScreenName && config.path === activeTabPath) { - return screenName; - } - } - return undefined; -} - /** * Parses a query string into a key-value record. * @@ -96,7 +80,7 @@ function getStateForDynamicRoute(path: string, dynamicRouteName: keyof typeof DY // 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 = findTabScreenName(currentRoute, activeTabPath) ?? activeTabPath; + const tabScreenName = dynamicTabScreensByHost.get(currentRoute)?.get(activeTabPath) ?? activeTabPath; return { name: currentRoute, path, diff --git a/src/libs/Navigation/linkingConfig/config.ts b/src/libs/Navigation/linkingConfig/config.ts index ea123bd06d3e..5d1756bf0f9f 100644 --- a/src/libs/Navigation/linkingConfig/config.ts +++ b/src/libs/Navigation/linkingConfig/config.ts @@ -2369,6 +2369,10 @@ const normalizedConfigs = Object.keys(config.screens) {} as Record, ); -const {screensWithTabNavigator: screensWithOnyxTabNavigator, dynamicTabPatternToTabPaths} = collectScreensWithTabNavigator(config.screens as Record); +const { + screensWithTabNavigator: screensWithOnyxTabNavigator, + dynamicTabPatternToTabPaths, + dynamicTabScreensByHost, +} = collectScreensWithTabNavigator(config.screens as Record); -export {normalizedConfigs, config, screensWithOnyxTabNavigator, dynamicTabPatternToTabPaths}; +export {normalizedConfigs, config, screensWithOnyxTabNavigator, dynamicTabPatternToTabPaths, dynamicTabScreensByHost}; From 714ecaeb5fe1e90ead2e5fc8f7bd1d5ad0b8a33c Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Thu, 25 Jun 2026 13:02:16 +0200 Subject: [PATCH 10/11] add tests --- .../collectScreensWithTabNavigatorTests.ts | 131 +++++++++++++++++- 1 file changed, 124 insertions(+), 7 deletions(-) diff --git a/tests/navigation/collectScreensWithTabNavigatorTests.ts b/tests/navigation/collectScreensWithTabNavigatorTests.ts index 4cc74a9603e1..4c49db2fcf6d 100644 --- a/tests/navigation/collectScreensWithTabNavigatorTests.ts +++ b/tests/navigation/collectScreensWithTabNavigatorTests.ts @@ -1,13 +1,16 @@ import type {ScreenConfigEntry} from '@libs/Navigation/helpers/collectScreensWithTabNavigator'; import collectScreensWithTabNavigator from '@libs/Navigation/helpers/collectScreensWithTabNavigator'; -jest.mock('@src/NAVIGATORS', () => { - const navigators = { - CENTRAL_PANE_NAVIGATOR: 'CentralPaneNavigator', - RIGHT_MODAL_NAVIGATOR: 'RightModalNavigator', - }; - return navigators; -}); +jest.mock('@src/NAVIGATORS', () => ({ + CENTRAL_PANE_NAVIGATOR: 'CentralPaneNavigator', + RIGHT_MODAL_NAVIGATOR: 'RightModalNavigator', +})); + +jest.mock('@libs/Navigation/helpers/dynamicRoutesUtils/isDynamicRouteSuffix', () => ({ + __esModule: true, + default: (suffix: string) => suffix === 'tag/:tagID' || suffix === 'report/:reportID', + dynamicRoutePaths: new Set(['tag/:tagID', 'report/:reportID']), +})); describe('collectScreensWithTabNavigator', () => { it('should skip string configs and object configs missing path or screens', () => { @@ -91,3 +94,117 @@ describe('collectScreensWithTabNavigator', () => { expect(result.screensWithTabNavigator).toEqual(new Set(['ValidTab', 'AnotherTab'])); }); }); + +describe('collectScreensWithTabNavigator — dynamicTabPatternToTabPaths', () => { + it('should not populate map for non-dynamic tab-host screens', () => { + const screens: Record = { + TabScreen: {path: '/tabs', screens: {Tab1: 'tab1', Tab2: 'tab2'}}, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabPatternToTabPaths.size).toBe(0); + }); + + it('should map dynamic pattern to tab paths', () => { + const screens: Record = { + TagScreen: {path: 'tag/:tagID', screens: {Expenses: 'expenses', Reports: 'reports'}}, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabPatternToTabPaths.get('tag/:tagID')).toEqual(new Set(['expenses', 'reports'])); + }); + + it('should exclude tab children without a path', () => { + const screens: Record = { + TagScreen: { + path: 'tag/:tagID', + screens: { + WithPath: {path: 'expenses'}, + WithoutPath: {}, + }, + }, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabPatternToTabPaths.get('tag/:tagID')).toEqual(new Set(['expenses'])); + }); + + it('should handle multiple dynamic tab-host screens independently', () => { + const screens: Record = { + TagScreen: {path: 'tag/:tagID', screens: {Tab1: 'tab1'}}, + ReportScreen: {path: 'report/:reportID', screens: {Tab2: 'tab2'}}, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabPatternToTabPaths.get('tag/:tagID')).toEqual(new Set(['tab1'])); + expect(result.dynamicTabPatternToTabPaths.get('report/:reportID')).toEqual(new Set(['tab2'])); + }); +}); + +describe('collectScreensWithTabNavigator — dynamicTabScreensByHost', () => { + it('should not populate map for non-dynamic tab-host screens', () => { + const screens: Record = { + TabScreen: {path: '/tabs', screens: {Tab1: 'tab1'}}, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabScreensByHost.size).toBe(0); + }); + + it('should map host screen name to tab path - screen name', () => { + const screens: Record = { + TagScreen: {path: 'tag/:tagID', screens: {ExpenseTab: 'expenses', ReportTab: 'reports'}}, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabScreensByHost.get('TagScreen')).toEqual( + new Map([ + ['expenses', 'ExpenseTab'], + ['reports', 'ReportTab'], + ]), + ); + }); + + it('should handle mixed string and object tab children', () => { + const screens: Record = { + TagScreen: { + path: 'tag/:tagID', + screens: { + StringChild: 'string-path', + ObjectChild: {path: 'object-path'}, + }, + }, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabScreensByHost.get('TagScreen')).toEqual( + new Map([ + ['string-path', 'StringChild'], + ['object-path', 'ObjectChild'], + ]), + ); + }); + + it('should exclude children without a path from the map', () => { + const screens: Record = { + TagScreen: { + path: 'tag/:tagID', + screens: { + WithPath: 'expenses', + WithoutPath: {}, + }, + }, + }; + + const result = collectScreensWithTabNavigator(screens); + + expect(result.dynamicTabScreensByHost.get('TagScreen')).toEqual(new Map([['expenses', 'WithPath']])); + }); +}); From 8f16673cd47dc3096ee4838fbcb1f1e98b4f7f81 Mon Sep 17 00:00:00 2001 From: Yehor Kharchenko Date: Thu, 25 Jun 2026 13:29:09 +0200 Subject: [PATCH 11/11] fix tests --- tests/navigation/getStateFromPathTests.ts | 24 +++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tests/navigation/getStateFromPathTests.ts b/tests/navigation/getStateFromPathTests.ts index c7346a47ebda..36a27e61d734 100644 --- a/tests/navigation/getStateFromPathTests.ts +++ b/tests/navigation/getStateFromPathTests.ts @@ -115,7 +115,7 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(dynamicSuffixAState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'SUFFIX_A', focusedRouteParams); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'SUFFIX_A', focusedRouteParams, undefined); }); it('should fallback to standard RN parsing if focused screen is NOT authorized for dynamic route', () => { @@ -136,8 +136,8 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(dynamicSuffixBState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/suffix-a', 'SUFFIX_A', focusedRouteParams); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'SUFFIX_B', focusedRouteParams); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/suffix-a', 'SUFFIX_A', focusedRouteParams, undefined); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'SUFFIX_B', focusedRouteParams, undefined); }); it('should fallback to RN parsing when the outer suffix entryScreens does not include the inner dynamic screen', () => { @@ -153,7 +153,7 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(standardState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/suffix-a', 'SUFFIX_A', focusedRouteParams); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/suffix-a', 'SUFFIX_A', focusedRouteParams, undefined); expect(mockLogWarn).toHaveBeenCalledWith(expect.stringContaining('None of the')); }); @@ -162,7 +162,7 @@ describe('getStateFromPath', () => { getStateFromPath(fullPath as unknown as Route); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'SUFFIX_B', focusedRouteParams); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'SUFFIX_B', focusedRouteParams, undefined); }); it('should support a multi-segment inner suffix inside the layered path', () => { @@ -171,8 +171,8 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(dynamicMultiSegLayerState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/deep/suffix-a', 'MULTI_SEG', focusedRouteParams); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'MULTI_SEG_LAYER', focusedRouteParams); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/deep/suffix-a', 'MULTI_SEG', focusedRouteParams, undefined); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'MULTI_SEG_LAYER', focusedRouteParams, undefined); }); }); @@ -183,7 +183,7 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(dynamicWildcardState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'WILDCARD_SUFFIX', focusedRouteParams); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'WILDCARD_SUFFIX', focusedRouteParams, undefined); expect(mockLogWarn).not.toHaveBeenCalled(); }); @@ -193,8 +193,8 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(dynamicWildcardState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/suffix-a', 'SUFFIX_A', focusedRouteParams); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'WILDCARD_SUFFIX', focusedRouteParams); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith('/base/suffix-a', 'SUFFIX_A', focusedRouteParams, undefined); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'WILDCARD_SUFFIX', focusedRouteParams, undefined); expect(mockLogWarn).not.toHaveBeenCalled(); }); }); @@ -245,7 +245,7 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(tagSettingsParamState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'TAG_SETTINGS_PARAM', expect.objectContaining({orderWeight: '0', tagName: 'gl-code'})); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'TAG_SETTINGS_PARAM', expect.objectContaining({orderWeight: '0', tagName: 'gl-code'}), undefined); expect(mockLogWarn).not.toHaveBeenCalled(); }); @@ -256,7 +256,7 @@ describe('getStateFromPath', () => { const result = getStateFromPath(fullPath as unknown as Route); expect(result).toBe(ambiguousStaticState); - expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'AMBIGUOUS_STATIC', expect.objectContaining(categorySettingsParams)); + expect(mockGetStateForDynamicRoute).toHaveBeenCalledWith(fullPath, 'AMBIGUOUS_STATIC', expect.objectContaining(categorySettingsParams), undefined); expect(mockLogWarn).not.toHaveBeenCalled(); }); });