Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/react/src/reactrouter-compat-utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export {
export {
resolveRouteNameAndSource,
getNormalizedName,
getRootRoutes,
locationIsInsideDescendantRoute,
prefixWithSlash,
rebuildRoutePathFromAllRoutes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { checkRouteForAsyncHandler } from './lazy-routes';
import {
clearNavigationContext,
getActiveRootSpan,
getRootRoutes,
resolveRouteNameAndSource,
setNavigationContext,
transactionNameHasWildcard,
Expand Down Expand Up @@ -389,7 +390,7 @@ export function updateNavigationSpan(
const shouldUpdate = !hasBeenNamed || forceUpdate || currentNameHasWildcard;

if (shouldUpdate && !end_timestamp) {
const currentBranches = config.matchRoutes(allRoutes, location);
const currentBranches = config.matchRoutes(getRootRoutes(allRoutes), location);
const [name, source] = resolveRouteNameAndSource(
location,
allRoutes,
Expand Down Expand Up @@ -993,7 +994,7 @@ export function handleNavigation(opts: {
const { location, routes, navigationType, version, config, matches, allRoutes } = opts;
const branches = Array.isArray(matches)
? matches
: config.matchRoutes(allRoutes || routes, location, config.basename);
: config.matchRoutes(getRootRoutes(allRoutes || routes), location, config.basename);
Comment thread
JoshuaKGoldberg marked this conversation as resolved.

const client = getClient();
if (!client || !config.instrumentNavigation) {
Expand Down Expand Up @@ -1167,7 +1168,7 @@ function updatePageloadTransaction({
}): void {
const branches = Array.isArray(matches)
? matches
: (config.matchRoutes(allRoutes || routes, location, config.basename) as unknown as RouteMatch[]);
: (config.matchRoutes(getRootRoutes(allRoutes || routes), location, config.basename) as unknown as RouteMatch[]);

if (branches) {
const [name, source] = resolveRouteNameAndSource(
Expand Down Expand Up @@ -1263,7 +1264,11 @@ function tryUpdateSpanNameBeforeEnd(

const currentAllRoutes = Array.from(allRoutes);
const routesToUse = currentAllRoutes.length > 0 ? currentAllRoutes : routes;
const branches = config.matchRoutes(routesToUse, location, config.basename) as unknown as RouteMatch[];
const branches = config.matchRoutes(
getRootRoutes(routesToUse),
location,
config.basename,
) as unknown as RouteMatch[];

if (!branches) {
return;
Expand Down
28 changes: 17 additions & 11 deletions packages/react/src/reactrouter-compat-utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,15 @@ function reconstructNameFromDescendantParent(
return remainingName ? prefixWithSlash(`${parentTemplate}${prefixWithSlash(remainingName)}`) : undefined;
}

/**
* Returns the routes that aren't a child of another route in the list.
* `matchRoutes` already walks each route's children, so also passing those children multiplies its work.
*/
export function getRootRoutes(routes: RouteObject[]): RouteObject[] {
const nestedRoutes = new Set(routes.flatMap(route => route.children ?? []));
return routes.filter(route => !nestedRoutes.has(route));
}

/**
* Checks if the current location is inside a descendant route (route with splat parameter).
*/
Expand All @@ -239,17 +248,11 @@ export function locationIsInsideDescendantRoute(
routes: RouteObject[],
matchRoutes: MatchRoutes,
): boolean {
const matchedRoutes = matchRoutes(routes, location) as RouteMatch[];

if (matchedRoutes) {
for (const match of matchedRoutes) {
if (routeIsDescendant(match.route) && pickSplat(match)) {
return true;
}
}
}
return matchesAreInsideDescendantRoute(matchRoutes(getRootRoutes(routes), location) as RouteMatch[] | null);
}

return false;
function matchesAreInsideDescendantRoute(matches: RouteMatch[] | null): boolean {
return !!matches?.some(match => routeIsDescendant(match.route) && pickSplat(match));
}

/**
Expand Down Expand Up @@ -348,7 +351,10 @@ export function resolveRouteNameAndSource(
let name: string | undefined;
let source: TransactionSource = 'url';

const isInDescendantRoute = locationIsInsideDescendantRoute(location, allRoutes, matchRoutes);
// `branches` were matched with the basename, which the descendant route lookups don't strip.
const isInDescendantRoute = basename
? locationIsInsideDescendantRoute(location, allRoutes, matchRoutes)
: matchesAreInsideDescendantRoute(branches);

if (isInDescendantRoute) {
name = prefixWithSlash(rebuildRoutePathFromAllRoutes(allRoutes, location, matchRoutes));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ vi.mock('../../src/reactrouter-compat-utils/utils', () => ({
return name.includes('/*') || name === '*' || name.endsWith('*');
}),
getActiveRootSpan: vi.fn(() => undefined),
getRootRoutes: vi.fn((routes: unknown[]) => routes),
}));

vi.mock('../../src/reactrouter-compat-utils/lazy-routes', () => ({
Expand Down
26 changes: 13 additions & 13 deletions packages/react/test/reactrouter-compat-utils/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
getNavigationContext,
getNormalizedName,
getNumberOfUrlSegments,
getRootRoutes,
locationIsInsideDescendantRoute,
pathEndsWithWildcard,
pathIsWildcardAndHasChildren,
Expand Down Expand Up @@ -247,6 +248,17 @@ describe('reactrouter-compat-utils/utils', () => {
});
});

describe('getRootRoutes', () => {
it('should drop routes whose parent is also in the list', () => {
const leaf: RouteObject = { path: 'account' };
const settings: RouteObject = { path: 'settings', children: [leaf] };
const root: RouteObject = { path: '/', children: [settings] };
const descendant: RouteObject = { path: '/users/*', element: 'div' };

expect(getRootRoutes([root, settings, leaf, descendant])).toEqual([root, descendant]);
});
});

describe('locationIsInsideDescendantRoute', () => {
it('should return true when location is inside descendant route', () => {
const routes: RouteObject[] = [
Expand Down Expand Up @@ -541,16 +553,6 @@ describe('reactrouter-compat-utils/utils', () => {
{ path: '/users', element: null },
];
const branches: RouteMatch[] = [
{
route: { path: '/users', element: null },
params: {},
pathname: '/users',
pathnameBase: '',
},
];

// Mock for descendant route check
const descendantMatches: RouteMatch[] = [
{
route: { path: '/users/*', element: 'div' },
params: { '*': '123/profile' },
Expand All @@ -569,9 +571,7 @@ describe('reactrouter-compat-utils/utils', () => {
},
];

mockMatchRoutes
.mockReturnValueOnce(descendantMatches) // First call for descendant check
.mockReturnValueOnce(rebuildMatches); // Second call for path rebuild
mockMatchRoutes.mockReturnValueOnce(rebuildMatches);

const result = resolveRouteNameAndSource(location, routes, allRoutes, branches, makeConfig());
// Since locationIsInsideDescendantRoute returns true, it uses route source
Expand Down
54 changes: 54 additions & 0 deletions packages/react/test/reactrouter-cross-usage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
matchRoutes,
MemoryRouter,
Navigate,
Outlet,
Route,
RouterProvider,
Routes,
Expand Down Expand Up @@ -911,4 +912,57 @@ describe('React Router cross usage of wrappers', () => {
});
});
});

describe('nested route matching', () => {
it('should name navigations after the route the router renders, not a nested route matched on its own', async () => {
const client = createMockBrowserClient();
setCurrentClient(client);

client.addIntegration(
reactRouterV6BrowserTracingIntegration({
useEffect: React.useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
}),
);

const createSentryMemoryRouter = wrapCreateMemoryRouterV6(createMemoryRouter);

const router = createSentryMemoryRouter([
{
path: '/',
element: <Outlet />,
children: [
{ path: ':orgId', element: <div>Org</div> },
{
path: 'settings',
element: <Outlet />,
children: [{ path: 'account', element: <div>Account settings</div> }],
},
],
},
]);

render(<RouterProvider router={router} />);

await act(async () => {
router.navigate('/account');
});

await waitFor(() => expect(mockStartBrowserTracingNavigationSpan).toHaveBeenCalledTimes(1));

expect(router.state.matches.map(match => match.route.path)).toEqual(['/', ':orgId']);
expect(mockStartBrowserTracingNavigationSpan).toHaveBeenLastCalledWith(expect.any(BrowserClient), {
name: '/:orgId',
attributes: {
[SENTRY_SEGMENT_NAME_SOURCE]: 'route',
[URL_TEMPLATE]: '/:orgId',
[SENTRY_OP]: 'navigation',
[SENTRY_ORIGIN]: 'auto.navigation.react.reactrouter_v6',
},
});
});
});
});
Loading