Unverified Commit dc61d29e authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Interception routes match from nested route navigation (#84898)

### What?

Refactors interception route regex generation to fix nested route
navigation and improve maintainability.

### Why?

Interception routes failed to trigger when navigating from nested
descendant routes. The previous implementation had overly complex,
fragile regex patterns spread across multiple functions that were
difficult to maintain and didn't handle all navigation scenarios
correctly.

The root cause was an overly restrictive header matching pattern
(`/[^/]+` - single segment only) that prevented matching navigation from
deeper nested routes like `/groups/123/settings` → `/groups/123/new`.

### How?

**Simplified Architecture:**
- Consolidated regex generation logic into `route-regex.ts` where it
properly belongs
- Removed ~230 lines of complex, duplicated regex building code from
`generate-interception-routes-rewrites.ts`
- Leveraged existing `getNamedRouteRegex()` with a new `reference`
parameter to handle parameter name mapping

**Parameter Naming Fix:**
- Introduced `nxtI` prefix for parameters adjacent to interception
markers (e.g., `(.)[id]` → `nxtIid`)
- Maintains `nxtP` prefix for regular parameters
- Ensures consistent parameter naming across source, destination, and
regex patterns

**Regex Pattern Fix:**
- Changed header matching from single-segment (`/[^/]+)?` to
multi-segment `(/.+)?` pattern
- Now correctly matches navigation from any descendant route depth

**Test Coverage:**
- Added comprehensive e2e tests for nested navigation scenarios
- Updated existing tests to reflect new parameter naming convention

Fixes #84813

NAR-445
parent 6bd5c47b
...@@ -19,10 +19,27 @@ export function isInterceptionRouteAppPath(path: string): boolean { ...@@ -19,10 +19,27 @@ export function isInterceptionRouteAppPath(path: string): boolean {
) )
} }
export function extractInterceptionRouteInformation(path: string) { type InterceptionRouteInformation = {
let interceptingRoute: string | undefined, /**
marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined, * The intercepting route. This is the route that is being intercepted or the
interceptedRoute: string | undefined * route that the user was coming from. This is matched by the Next-Url
* header.
*/
interceptingRoute: string
/**
* The intercepted route. This is the route that is being intercepted or the
* route that the user is going to. This is matched by the request pathname.
*/
interceptedRoute: string
}
export function extractInterceptionRouteInformation(
path: string
): InterceptionRouteInformation {
let interceptingRoute: string | undefined
let marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined
let interceptedRoute: string | undefined
for (const segment of path.split('/')) { for (const segment of path.split('/')) {
marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m)) marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))
......
...@@ -44,8 +44,13 @@ describe('getNamedRouteRegex', () => { ...@@ -44,8 +44,13 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/photos/(.):nxtIauthor/:nxtPid", "pathToRegexpPattern": "/photos/(.):nxtIauthor/:nxtPid",
"re": /\\^\\\\/photos\\\\/\\\\\\(\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/photos\\\\/\\\\\\(\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"author": "nxtIauthor", "intercepted": {
"id": "nxtPid", "author": "(.)",
},
"names": {
"author": "nxtIauthor",
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtIauthor": "nxtIauthor", "nxtIauthor": "nxtIauthor",
...@@ -86,8 +91,13 @@ describe('getNamedRouteRegex', () => { ...@@ -86,8 +91,13 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/(.):nxtIauthor/:nxtPid", "pathToRegexpPattern": "/(.):nxtIauthor/:nxtPid",
"re": /\\^\\\\/\\\\\\(\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\\\\\(\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"author": "nxtIauthor", "intercepted": {
"id": "nxtPid", "author": "(.)",
},
"names": {
"author": "nxtIauthor",
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtIauthor": "nxtIauthor", "nxtIauthor": "nxtIauthor",
...@@ -122,8 +132,13 @@ describe('getNamedRouteRegex', () => { ...@@ -122,8 +132,13 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/(..)(..):nxtIauthor/:nxtPid", "pathToRegexpPattern": "/(..)(..):nxtIauthor/:nxtPid",
"re": /\\^\\\\/\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"author": "nxtIauthor", "intercepted": {
"id": "nxtPid", "author": "(..)(..)",
},
"names": {
"author": "nxtIauthor",
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtIauthor": "nxtIauthor", "nxtIauthor": "nxtIauthor",
...@@ -160,8 +175,13 @@ describe('getNamedRouteRegex', () => { ...@@ -160,8 +175,13 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/photos/(..)(..):nxtIauthor/:nxtPid", "pathToRegexpPattern": "/photos/(..)(..):nxtIauthor/:nxtPid",
"re": /\\^\\\\/photos\\\\/\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/photos\\\\/\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\\\\\(\\\\\\.\\\\\\.\\\\\\)\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"author": "nxtIauthor", "intercepted": {
"id": "nxtPid", "author": "(..)(..)",
},
"names": {
"author": "nxtIauthor",
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtIauthor": "nxtIauthor", "nxtIauthor": "nxtIauthor",
...@@ -206,8 +226,11 @@ describe('getNamedRouteRegex', () => { ...@@ -206,8 +226,11 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/:nxtPlocale/about.segments/:nxtPsegmentPath+.segment.rsc", "pathToRegexpPattern": "/:nxtPlocale/about.segments/:nxtPsegmentPath+.segment.rsc",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/about\\\\\\.segments\\\\/\\(\\.\\+\\?\\)\\\\\\.segment\\\\\\.rsc\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/about\\\\\\.segments\\\\/\\(\\.\\+\\?\\)\\\\\\.segment\\\\\\.rsc\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"locale": "nxtPlocale", "intercepted": {},
"segmentPath": "nxtPsegmentPath", "names": {
"locale": "nxtPlocale",
"segmentPath": "nxtPsegmentPath",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPlocale": "nxtPlocale", "nxtPlocale": "nxtPlocale",
...@@ -245,8 +268,11 @@ describe('getNamedRouteRegex', () => { ...@@ -245,8 +268,11 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/:nxtPlocale/about.segments/$dname$d/:nxtPname.segment.rsc", "pathToRegexpPattern": "/:nxtPlocale/about.segments/$dname$d/:nxtPname.segment.rsc",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/about\\\\\\.segments\\\\/\\\\\\$dname\\\\\\$d\\(\\[\\^/\\]\\+\\?\\)\\\\\\.segment\\\\\\.rsc\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/about\\\\\\.segments\\\\/\\\\\\$dname\\\\\\$d\\(\\[\\^/\\]\\+\\?\\)\\\\\\.segment\\\\\\.rsc\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"locale": "nxtPlocale", "intercepted": {},
"name": "nxtPname", "names": {
"locale": "nxtPlocale",
"name": "nxtPname",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPlocale": "nxtPlocale", "nxtPlocale": "nxtPlocale",
...@@ -283,7 +309,10 @@ describe('getNamedRouteRegex', () => { ...@@ -283,7 +309,10 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/photos/(.)author/:nxtPid", "pathToRegexpPattern": "/photos/(.)author/:nxtPid",
"re": /\\^\\\\/photos\\\\/\\\\\\(\\\\\\.\\\\\\)author\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/photos\\\\/\\\\\\(\\\\\\.\\\\\\)author\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"id": "nxtPid", "intercepted": {},
"names": {
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPid": "nxtPid", "nxtPid": "nxtPid",
...@@ -317,7 +346,10 @@ describe('getNamedRouteRegex', () => { ...@@ -317,7 +346,10 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/photos/:nxtPid", "pathToRegexpPattern": "/photos/:nxtPid",
"re": /\\^\\\\/photos\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/photos\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"id": "nxtPid", "intercepted": {},
"names": {
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPid": "nxtPid", "nxtPid": "nxtPid",
...@@ -354,7 +386,10 @@ describe('getNamedRouteRegex', () => { ...@@ -354,7 +386,10 @@ describe('getNamedRouteRegex', () => {
"pathToRegexpPattern": "/photos/:nxtPid*", "pathToRegexpPattern": "/photos/:nxtPid*",
"re": /\\^\\\\/photos\\(\\?:\\\\/\\(\\.\\+\\?\\)\\)\\?\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/photos\\(\\?:\\\\/\\(\\.\\+\\?\\)\\)\\?\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"id": "nxtPid", "intercepted": {},
"names": {
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPid": "nxtPid", "nxtPid": "nxtPid",
...@@ -402,7 +437,10 @@ describe('getNamedRouteRegex - Parameter Sanitization', () => { ...@@ -402,7 +437,10 @@ describe('getNamedRouteRegex - Parameter Sanitization', () => {
"pathToRegexpPattern": "/:nxtPfoobar/page", "pathToRegexpPattern": "/:nxtPfoobar/page",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/page\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/page\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"foo-bar": "nxtPfoobar", "intercepted": {},
"names": {
"foo-bar": "nxtPfoobar",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPfoobar": "nxtPfoo-bar", "nxtPfoobar": "nxtPfoo-bar",
...@@ -430,7 +468,10 @@ describe('getNamedRouteRegex - Parameter Sanitization', () => { ...@@ -430,7 +468,10 @@ describe('getNamedRouteRegex - Parameter Sanitization', () => {
"pathToRegexpPattern": "/:nxtPfoo_id/page", "pathToRegexpPattern": "/:nxtPfoo_id/page",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/page\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/page\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"foo_id": "nxtPfoo_id", "intercepted": {},
"names": {
"foo_id": "nxtPfoo_id",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPfoo_id": "nxtPfoo_id", "nxtPfoo_id": "nxtPfoo_id",
...@@ -458,7 +499,10 @@ describe('getNamedRouteRegex - Parameter Sanitization', () => { ...@@ -458,7 +499,10 @@ describe('getNamedRouteRegex - Parameter Sanitization', () => {
"pathToRegexpPattern": "/:nxtPthisis_myroute/page", "pathToRegexpPattern": "/:nxtPthisis_myroute/page",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/page\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/page\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"this-is_my-route": "nxtPthisis_myroute", "intercepted": {},
"names": {
"this-is_my-route": "nxtPthisis_myroute",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPthisis_myroute": "nxtPthis-is_my-route", "nxtPthisis_myroute": "nxtPthis-is_my-route",
...@@ -508,11 +552,11 @@ describe('getNamedRouteRegex - Reference Mapping', () => { ...@@ -508,11 +552,11 @@ describe('getNamedRouteRegex - Reference Mapping', () => {
}) })
// Both should use the same prefixed key for 'lang' // Both should use the same prefixed key for 'lang'
expect(regex1.reference.lang).toBe(regex2.reference.lang) expect(regex1.reference.names.lang).toBe(regex2.reference.names.lang)
expect(regex2.reference.lang).toBe('nxtPlang') expect(regex2.reference.names.lang).toBe('nxtPlang')
// New parameter should be added to the reference // New parameter should be added to the reference
expect(regex2.reference.id).toBe('nxtPid') expect(regex2.reference.names.id).toBe('nxtPid')
}) })
it('should maintain reference consistency across multiple paths', () => { it('should maintain reference consistency across multiple paths', () => {
...@@ -526,8 +570,10 @@ describe('getNamedRouteRegex - Reference Mapping', () => { ...@@ -526,8 +570,10 @@ describe('getNamedRouteRegex - Reference Mapping', () => {
}) })
// Same parameter name should map to same prefixed key // Same parameter name should map to same prefixed key
expect(baseRegex.reference.locale).toBe(interceptedRegex.reference.locale) expect(baseRegex.reference.names.locale).toBe(
expect(interceptedRegex.reference.locale).toBe('nxtPlocale') interceptedRegex.reference.names.locale
)
expect(interceptedRegex.reference.names.locale).toBe('nxtPlocale')
}) })
it('should generate inverse pattern with correct parameter references', () => { it('should generate inverse pattern with correct parameter references', () => {
...@@ -566,7 +612,10 @@ describe('getNamedRouteRegex - Duplicate Keys', () => { ...@@ -566,7 +612,10 @@ describe('getNamedRouteRegex - Duplicate Keys', () => {
"pathToRegexpPattern": "/:nxtPid/posts/:nxtPid", "pathToRegexpPattern": "/:nxtPid/posts/:nxtPid",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/posts\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/posts\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"id": "nxtPid", "intercepted": {},
"names": {
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPid": "nxtPid", "nxtPid": "nxtPid",
...@@ -595,7 +644,10 @@ describe('getNamedRouteRegex - Duplicate Keys', () => { ...@@ -595,7 +644,10 @@ describe('getNamedRouteRegex - Duplicate Keys', () => {
"pathToRegexpPattern": "/:nxtPid/posts/:nxtPid", "pathToRegexpPattern": "/:nxtPid/posts/:nxtPid",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/posts\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/posts\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"id": "nxtPid", "intercepted": {},
"names": {
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPid": "nxtPid", "nxtPid": "nxtPid",
...@@ -639,10 +691,13 @@ describe('getNamedRouteRegex - Complex Paths', () => { ...@@ -639,10 +691,13 @@ describe('getNamedRouteRegex - Complex Paths', () => {
"pathToRegexpPattern": "/:nxtPorg/:nxtPrepo/:nxtPbranch/:nxtPpath+", "pathToRegexpPattern": "/:nxtPorg/:nxtPrepo/:nxtPbranch/:nxtPpath+",
"re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\.\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\[\\^/\\]\\+\\?\\)\\\\/\\(\\.\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"branch": "nxtPbranch", "intercepted": {},
"org": "nxtPorg", "names": {
"path": "nxtPpath", "branch": "nxtPbranch",
"repo": "nxtPrepo", "org": "nxtPorg",
"path": "nxtPpath",
"repo": "nxtPrepo",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPbranch": "nxtPbranch", "nxtPbranch": "nxtPbranch",
...@@ -689,7 +744,7 @@ describe('getNamedRouteRegex - Complex Paths', () => { ...@@ -689,7 +744,7 @@ describe('getNamedRouteRegex - Complex Paths', () => {
prefixRouteKeys: true, prefixRouteKeys: true,
}) })
// Should use interception prefix // Should use consistent parameter prefix (interception marker adjacent to parameter uses nxtI)
expect(regex.routeKeys).toEqual({ expect(regex.routeKeys).toEqual({
nxtIid: 'nxtIid', nxtIid: 'nxtIid',
}) })
...@@ -721,7 +776,10 @@ describe('getNamedRouteRegex - Trailing Slash Behavior', () => { ...@@ -721,7 +776,10 @@ describe('getNamedRouteRegex - Trailing Slash Behavior', () => {
"pathToRegexpPattern": "/posts/:nxtPid", "pathToRegexpPattern": "/posts/:nxtPid",
"re": /\\^\\\\/posts\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/, "re": /\\^\\\\/posts\\\\/\\(\\[\\^/\\]\\+\\?\\)\\(\\?:\\\\/\\)\\?\\$/,
"reference": { "reference": {
"id": "nxtPid", "intercepted": {},
"names": {
"id": "nxtPid",
},
}, },
"routeKeys": { "routeKeys": {
"nxtPid": "nxtPid", "nxtPid": "nxtPid",
......
...@@ -18,6 +18,11 @@ export interface RouteRegex { ...@@ -18,6 +18,11 @@ export interface RouteRegex {
re: RegExp re: RegExp
} }
export type RegexReference = {
names: Record<string, string>
intercepted: Record<string, string>
}
type GetNamedRouteRegexOptions = { type GetNamedRouteRegexOptions = {
/** /**
* Whether to prefix the route keys with the NEXT_INTERCEPTION_MARKER_PREFIX * Whether to prefix the route keys with the NEXT_INTERCEPTION_MARKER_PREFIX
...@@ -58,7 +63,7 @@ type GetNamedRouteRegexOptions = { ...@@ -58,7 +63,7 @@ type GetNamedRouteRegexOptions = {
* keys instead of generating them in context. This is currently only used for * keys instead of generating them in context. This is currently only used for
* interception routes. * interception routes.
*/ */
reference?: Record<string, string> reference?: RegexReference
} }
type GetRouteRegexOptions = { type GetRouteRegexOptions = {
...@@ -266,7 +271,7 @@ function getNamedParametrizedRoute( ...@@ -266,7 +271,7 @@ function getNamedParametrizedRoute(
includeSuffix: boolean, includeSuffix: boolean,
includePrefix: boolean, includePrefix: boolean,
backreferenceDuplicateKeys: boolean, backreferenceDuplicateKeys: boolean,
reference: Record<string, string> = {} reference: RegexReference = { names: {}, intercepted: {} }
) { ) {
const getSafeRouteKey = buildGetSafeRouteKey() const getSafeRouteKey = buildGetSafeRouteKey()
const routeKeys: { [named: string]: string } = {} const routeKeys: { [named: string]: string } = {}
...@@ -284,25 +289,37 @@ function getNamedParametrizedRoute( ...@@ -284,25 +289,37 @@ function getNamedParametrizedRoute(
const paramMatches = segment.match(PARAMETER_PATTERN) // Check for parameters const paramMatches = segment.match(PARAMETER_PATTERN) // Check for parameters
if (hasInterceptionMarker && paramMatches && paramMatches[2]) { const interceptionMarker = hasInterceptionMarker
? paramMatches?.[1]
: undefined
let keyPrefix: string | undefined
if (interceptionMarker && paramMatches?.[2]) {
keyPrefix = prefixRouteKeys ? NEXT_INTERCEPTION_MARKER_PREFIX : undefined
reference.intercepted[paramMatches[2]] = interceptionMarker
} else if (paramMatches?.[2] && reference.intercepted[paramMatches[2]]) {
keyPrefix = prefixRouteKeys ? NEXT_INTERCEPTION_MARKER_PREFIX : undefined
} else {
keyPrefix = prefixRouteKeys ? NEXT_QUERY_PARAM_PREFIX : undefined
}
if (interceptionMarker && paramMatches && paramMatches[2]) {
// If there's an interception marker, add it to the segments. // If there's an interception marker, add it to the segments.
const { key, pattern, cleanedKey, repeat, optional } = const { key, pattern, cleanedKey, repeat, optional } =
getSafeKeyFromSegment({ getSafeKeyFromSegment({
getSafeRouteKey, getSafeRouteKey,
interceptionMarker: paramMatches[1], interceptionMarker,
segment: paramMatches[2], segment: paramMatches[2],
routeKeys, routeKeys,
keyPrefix: prefixRouteKeys keyPrefix,
? NEXT_INTERCEPTION_MARKER_PREFIX
: undefined,
backreferenceDuplicateKeys, backreferenceDuplicateKeys,
}) })
segments.push(pattern) segments.push(pattern)
inverseParts.push( inverseParts.push(
`/${paramMatches[1]}:${reference[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}` `/${paramMatches[1]}:${reference.names[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}`
) )
reference[key] ??= cleanedKey reference.names[key] ??= cleanedKey
} else if (paramMatches && paramMatches[2]) { } else if (paramMatches && paramMatches[2]) {
// If there's a prefix, add it to the segments if it's enabled. // If there's a prefix, add it to the segments if it's enabled.
if (includePrefix && paramMatches[1]) { if (includePrefix && paramMatches[1]) {
...@@ -315,7 +332,7 @@ function getNamedParametrizedRoute( ...@@ -315,7 +332,7 @@ function getNamedParametrizedRoute(
getSafeRouteKey, getSafeRouteKey,
segment: paramMatches[2], segment: paramMatches[2],
routeKeys, routeKeys,
keyPrefix: prefixRouteKeys ? NEXT_QUERY_PARAM_PREFIX : undefined, keyPrefix,
backreferenceDuplicateKeys, backreferenceDuplicateKeys,
}) })
...@@ -327,9 +344,9 @@ function getNamedParametrizedRoute( ...@@ -327,9 +344,9 @@ function getNamedParametrizedRoute(
segments.push(s) segments.push(s)
inverseParts.push( inverseParts.push(
`/:${reference[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}` `/:${reference.names[key] ?? cleanedKey}${repeat ? (optional ? '*' : '+') : ''}`
) )
reference[key] ??= cleanedKey reference.names[key] ??= cleanedKey
} else { } else {
segments.push(`/${escapeStringRegexp(segment)}`) segments.push(`/${escapeStringRegexp(segment)}`)
inverseParts.push(`/${segment}`) inverseParts.push(`/${segment}`)
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { retry } from 'next-test-utils'
describe('interception-dynamic-segment-middleware', () => { describe('interception-dynamic-segment-middleware', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -10,9 +10,59 @@ describe('interception-dynamic-segment-middleware', () => { ...@@ -10,9 +10,59 @@ describe('interception-dynamic-segment-middleware', () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await browser.elementByCss('[href="/foo/p/1"]').click() await browser.elementByCss('[href="/foo/p/1"]').click()
await check(() => browser.elementById('modal').text(), /intercepted/) await retry(async () => {
expect(await browser.elementById('modal').text()).toMatch(/intercepted/)
})
await browser.refresh() await browser.refresh()
await check(() => browser.elementById('modal').text(), 'default') await retry(async () => {
await check(() => browser.elementById('children').text(), /not intercepted/) expect(await browser.elementById('modal').text()).toBe('default')
})
await retry(async () => {
expect(await browser.elementById('children').text()).toMatch(
/not intercepted/
)
})
})
it('should intercept with back/forward navigation with middleware', async () => {
// Test that interception works correctly with middleware and browser navigation
const browser = await next.browser('/')
// Navigate with interception
await browser.elementByCss('[href="/foo/p/1"]').click()
await retry(async () => {
expect(await browser.elementById('modal').text()).toMatch(/intercepted/)
})
// Go back to root
await browser.back()
await retry(async () => {
const url = await browser.url()
expect(url).toContain('/')
})
// Go forward - should show intercepted version
await browser.forward()
await retry(async () => {
expect(await browser.elementById('modal').text()).toMatch(/intercepted/)
})
})
it('should intercept multiple times with middleware active', async () => {
// Test that repeated interception works when middleware is involved
const browser = await next.browser('/')
for (let i = 0; i < 2; i++) {
await browser.elementByCss('[href="/foo/p/1"]').click()
await retry(async () => {
expect(await browser.elementById('modal').text()).toMatch(/intercepted/)
})
await browser.back()
await retry(async () => {
const url = await browser.url()
expect(url).toMatch(/\/$/)
})
}
}) })
}) })
...@@ -24,6 +24,48 @@ describe('interception-dynamic-segment', () => { ...@@ -24,6 +24,48 @@ describe('interception-dynamic-segment', () => {
}) })
}) })
it('should intercept consistently with back/forward navigation', async () => {
// Test that the fix works with browser back/forward navigation
const browser = await next.browser('/')
// Navigate with interception
await browser.elementByCss('[href="/foo/1"]').click()
await retry(async () => {
expect(await browser.elementById('modal').text()).toEqual('intercepted')
})
// Go back to root
await browser.back()
await retry(async () => {
const url = await browser.url()
expect(url).toContain('/')
})
// Go forward - should show intercepted version
await browser.forward()
await retry(async () => {
expect(await browser.elementById('modal').text()).toEqual('intercepted')
})
})
it('should intercept multiple times from root', async () => {
// Test that repeated interception from root works
const browser = await next.browser('/')
for (let i = 0; i < 2; i++) {
await browser.elementByCss('[href="/foo/1"]').click()
await retry(async () => {
expect(await browser.elementById('modal').text()).toEqual('intercepted')
})
await browser.back()
await retry(async () => {
const url = await browser.url()
expect(url).toMatch(/\/$/)
})
}
})
if (isNextStart) { if (isNextStart) {
it('should correctly prerender segments with generateStaticParams', async () => { it('should correctly prerender segments with generateStaticParams', async () => {
expect(next.cliOutput).toContain('/generate-static-params/a') expect(next.cliOutput).toContain('/generate-static-params/a')
......
export default async function ItemModal(props: {
params: Promise<{ a: string; b: string; c: string }>
}) {
const params = await props.params
return (
<div id="item-modal">
Modal: Item for path {params.a}/{params.b}/{params.c}
</div>
)
}
export default function NewUserModal() {
return <div id="new-user-modal">Modal: New User Form</div>
}
export default async function NewItemModal(props: {
params: Promise<{ id: string }>
}) {
const params = await props.params
return <div id="new-modal">Modal: New item for group {params.id}</div>
}
export default async function TeamSettingsModal(props: {
params: Promise<{ orgId: string; teamId: string }>
}) {
const params = await props.params
return (
<div id="settings-modal">
Modal: Settings for Team {params.teamId} in Org {params.orgId}
</div>
)
}
export default function ConsecutiveDynamicModalDefault() {
return null
}
export default function GroupModalDefault() {
return null
}
export default async function ItemPage(props: {
params: Promise<{ a: string; b: string; c: string }>
}) {
const params = await props.params
return (
<div id="item-page">
Item for path: {params.a}/{params.b}/{params.c}
</div>
)
}
import Link from 'next/link'
export default async function ConsecutiveDynamicPage(props: {
params: Promise<{ a: string; b: string; c: string }>
}) {
const params = await props.params
return (
<div>
<div id="consecutive-page">
Path: {params.a}/{params.b}/{params.c}
</div>
<Link href={`/${params.a}/${params.b}/${params.c}/item`} id="item-link">
View Item
</Link>
</div>
)
}
export default function NewUserPage() {
return <div id="new-user-page">New User Form</div>
}
import Link from 'next/link'
export default function UsersPage() {
return (
<div>
<div id="users-page">Admin Dashboard - Users</div>
<Link href="/admin/dashboard/users/new" id="new-user-link">
New User
</Link>
</div>
)
}
export default function Default() {
return null
}
export default async function NewItemPage(props: {
params: Promise<{ id: string }>
}) {
const params = await props.params
return <div id="new-page">New item for group {params.id}</div>
}
import Link from 'next/link'
export default async function GroupPage(props: {
params: Promise<{ id: string }>
}) {
const params = await props.params
return (
<div>
<div id="group-page">Group {params.id}</div>
<Link href={`/groups/${params.id}/new`} id="new-link">
New Item
</Link>
</div>
)
}
import { Suspense } from 'react'
export default function Layout(props: {
children: React.ReactNode
modal: React.ReactNode
}) {
return (
<Suspense>
<html>
<body>
<div id="children">{props.children}</div>
<div id="modal">{props.modal}</div>
</body>
</html>
</Suspense>
)
}
import Link from 'next/link'
export default async function TeamPage(props: {
params: Promise<{ orgId: string; teamId: string }>
}) {
const params = await props.params
return (
<div>
<div id="team-page">
Team {params.teamId} in Org {params.orgId}
</div>
<Link
href={`/org/${params.orgId}/team/${params.teamId}/settings`}
id="settings-link"
>
Settings
</Link>
</div>
)
}
export default async function TeamSettingsPage(props: {
params: Promise<{ orgId: string; teamId: string }>
}) {
const params = await props.params
return (
<div id="settings-page">
Settings for Team {params.teamId} in Org {params.orgId}
</div>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<Link href="/groups/123" id="groups-link">
Group 123
</Link>{' '}
<Link href="/org/acme/team/engineering" id="team-link">
Team
</Link>{' '}
<Link href="/x/y/z" id="consecutive-link">
Consecutive
</Link>{' '}
<Link href="/admin/dashboard/users" id="admin-link">
Admin
</Link>
</div>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { retry } from 'next-test-utils'
describe('interception-segments-two-levels-above', () => { describe('interception-segments-two-levels-above', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -10,6 +10,64 @@ describe('interception-segments-two-levels-above', () => { ...@@ -10,6 +10,64 @@ describe('interception-segments-two-levels-above', () => {
const browser = await next.browser('/foo/bar') const browser = await next.browser('/foo/bar')
await browser.elementByCss('[href="/hoge"]').click() await browser.elementByCss('[href="/hoge"]').click()
await check(() => browser.elementById('intercepted').text(), /intercepted/) await retry(async () => {
expect(await browser.elementById('intercepted').text()).toMatch(
/intercepted/
)
})
})
it('should intercept consistently with back/forward navigation', async () => {
// Test that interception works correctly with browser back/forward
const browser = await next.browser('/foo/bar')
// Navigate with interception
await browser.elementByCss('[href="/hoge"]').click()
await retry(async () => {
expect(await browser.elementById('intercepted').text()).toMatch(
/intercepted/
)
})
// Go back
await browser.back()
await retry(async () => {
const url = await browser.url()
expect(url).toContain('/foo/bar')
})
// Go forward - should show the intercepted version again
await browser.forward()
await retry(async () => {
expect(await browser.elementById('intercepted').text()).toMatch(
/intercepted/
)
})
})
it('should intercept multiple times from same route', async () => {
// Test that repeated interception works
const browser = await next.browser('/foo/bar')
for (let i = 0; i < 2; i++) {
await retry(async () => {
await browser.elementByCss('[href="/hoge"]').click()
})
await retry(async () => {
expect(await browser.elementById('intercepted').text()).toMatch(
/intercepted/
)
})
await browser.back()
await retry(async () => {
const url = await browser.url()
expect(url).toContain('/foo/bar')
await browser.elementByCss('[href="/hoge"]')
})
}
}) })
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment