Unverified Commit 5977121e authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

interception routes: add new sibling matcher marker + validation (#48276)

This PR adds a new marker for intercepting siblings routes + adds some
validation to intercepting routes ( you shouldn't use (..) at the top
level!)

also fixes a bug with any interception from `/` when navigating from a
child route

the new marker, `(.)`, makes it easier to model cases like 
```
/profile/[id]
/profile/[id]/photos/[id]/
```

With the current syntax available, you’d need to do:
```with (..):
/profile/[id]/(..)[id]/photos/[id]

with (...):
/profile/[id]/(...)profile/[id]/photos/[id]

with (..)(..):
/profile/[id]/(..)(..)profile/[id]/photos/[id]
```

now, with (.)
```
/profile/[id]/(.)photos/[id]
```

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation or adding/fixing Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

link NEXT-935
also fixes NEXT-970
fixes NEXT-973
parent 17e44d29
...@@ -21,9 +21,9 @@ export function generateInterceptionRoutesRewrites( ...@@ -21,9 +21,9 @@ export function generateInterceptionRoutesRewrites(
const { interceptingRoute, interceptedRoute } = const { interceptingRoute, interceptedRoute } =
extractInterceptionRouteInformation(appPath) extractInterceptionRouteInformation(appPath)
const normalizedInterceptingRoute = `${toPathToRegexpPath( const normalizedInterceptingRoute = `${
interceptingRoute interceptingRoute !== '/' ? toPathToRegexpPath(interceptingRoute) : ''
)}/(.*)?` }/(.*)?`
const normalizedInterceptedRoute = toPathToRegexpPath(interceptedRoute) const normalizedInterceptedRoute = toPathToRegexpPath(interceptedRoute)
const normalizedAppPath = toPathToRegexpPath(appPath) const normalizedAppPath = toPathToRegexpPath(appPath)
......
...@@ -9,6 +9,7 @@ describe('Interception Route helper', () => { ...@@ -9,6 +9,7 @@ describe('Interception Route helper', () => {
expect(isInterceptionRouteAppPath('/foo/(..)/bar')).toBe(true) expect(isInterceptionRouteAppPath('/foo/(..)/bar')).toBe(true)
expect(isInterceptionRouteAppPath('/foo/(...)/bar')).toBe(true) expect(isInterceptionRouteAppPath('/foo/(...)/bar')).toBe(true)
expect(isInterceptionRouteAppPath('/foo/(..)(..)/bar')).toBe(true) expect(isInterceptionRouteAppPath('/foo/(..)(..)/bar')).toBe(true)
expect(isInterceptionRouteAppPath('/foo/(.)bar')).toBe(true)
}) })
it('should not validate incorrect paths', () => { it('should not validate incorrect paths', () => {
expect(isInterceptionRouteAppPath('/foo/(..')).toBe(false) expect(isInterceptionRouteAppPath('/foo/(..')).toBe(false)
...@@ -39,6 +40,11 @@ describe('Interception Route helper', () => { ...@@ -39,6 +40,11 @@ describe('Interception Route helper', () => {
expect( expect(
extractInterceptionRouteInformation('/foo/bar/@modal/(..)(..)baz') extractInterceptionRouteInformation('/foo/bar/@modal/(..)(..)baz')
).toEqual({ interceptingRoute: '/foo/bar', interceptedRoute: '/baz' }) ).toEqual({ interceptingRoute: '/foo/bar', interceptedRoute: '/baz' })
expect(extractInterceptionRouteInformation('/foo/bar/(.)baz')).toEqual({
interceptingRoute: '/foo/bar',
interceptedRoute: '/foo/bar/baz',
})
}) })
it('should not extract incorrect information', () => { it('should not extract incorrect information', () => {
expect(() => expect(() =>
...@@ -57,5 +63,17 @@ describe('Interception Route helper', () => { ...@@ -57,5 +63,17 @@ describe('Interception Route helper', () => {
`"Invalid interception route: /foo. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>"` `"Invalid interception route: /foo. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>"`
) )
}) })
it('should check the segment length', () => {
expect(() =>
extractInterceptionRouteInformation('/(..)bar')
).toThrowErrorMatchingInlineSnapshot(
`"Invalid interception route: /(..)bar. Cannot use (..) marker at the root level, use (.) instead."`
)
expect(() =>
extractInterceptionRouteInformation('/(..)(..)bar')
).toThrowErrorMatchingInlineSnapshot(
`"Invalid interception route: /(..)(..)bar. Cannot use (..)(..) marker at the root level or one level up."`
)
})
}) })
}) })
import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths' import { normalizeAppPath } from '../../../shared/lib/router/utils/app-paths'
// order matters here, the first match will be used // order matters here, the first match will be used
export const INTERCEPTION_ROUTE_MARKERS = ['(..)(..)', '(..)', '(...)'] as const export const INTERCEPTION_ROUTE_MARKERS = [
'(..)(..)',
'(.)',
'(..)',
'(...)',
] as const
export function isInterceptionRouteAppPath(path: string): boolean { export function isInterceptionRouteAppPath(path: string): boolean {
// TODO-APP: add more serious validation // TODO-APP: add more serious validation
...@@ -33,31 +38,52 @@ export function extractInterceptionRouteInformation(path: string) { ...@@ -33,31 +38,52 @@ export function extractInterceptionRouteInformation(path: string) {
) )
} }
interceptingRoute = interceptingRoute.slice(0, -1) // remove the trailing slash
interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed
if (marker === '(..)') { switch (marker) {
// (..) indicates that we should remove the last segment of the intercepting case '(.)':
// route to prepend the intercepted route. // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route
interceptedRoute = if (interceptingRoute === '/') {
interceptingRoute.split('/').slice(0, -1).join('/') + interceptedRoute = `/${interceptedRoute}`
'/' + } else {
interceptedRoute interceptedRoute = interceptingRoute + '/' + interceptedRoute
} }
break
case '(..)':
// (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route
if (interceptingRoute === '/') {
throw new Error(
`Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`
)
}
interceptedRoute = interceptingRoute
.split('/')
.slice(0, -1)
.concat(interceptedRoute)
.join('/')
break
case '(...)':
// (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route
interceptedRoute = '/' + interceptedRoute
break
case '(..)(..)':
// (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route
if (marker === '(...)') { const splitInterceptingRoute = interceptingRoute.split('/')
// (...) will match the route segment in the root directory, so we need to if (splitInterceptingRoute.length <= 2) {
// use the root directory to prepend the intercepted route. throw new Error(
interceptedRoute = '/' + interceptedRoute `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`
} )
}
if (marker === '(..)(..)') { interceptedRoute = splitInterceptingRoute
// (..)(..) indicates that we should remove the last two segments of the .slice(0, -2)
// intercepting route to prepend the intercepted route. .concat(interceptedRoute)
interceptedRoute = .join('/')
interceptingRoute.split('/').slice(0, -2).join('/') + break
'/' + default:
interceptedRoute throw new Error('Invariant: unexpected marker')
} }
return { interceptingRoute, interceptedRoute } return { interceptingRoute, interceptedRoute }
} }
...@@ -7,7 +7,7 @@ export default function Page() { ...@@ -7,7 +7,7 @@ export default function Page() {
<ul> <ul>
{Array.from({ length: 10 }).map((_, i) => ( {Array.from({ length: 10 }).map((_, i) => (
<li key={i}> <li key={i}>
<Link href={`/intercepting-routes/photos/${i}`}>Link {i}</Link> <Link href={`/intercepting-routes/feed/photos/${i}`}>Link {i}</Link>
</li> </li>
))} ))}
</ul> </ul>
......
...@@ -7,7 +7,7 @@ export default function Page() { ...@@ -7,7 +7,7 @@ export default function Page() {
<ul> <ul>
{Array.from({ length: 10 }).map((_, i) => ( {Array.from({ length: 10 }).map((_, i) => (
<li key={i}> <li key={i}>
<Link href={`/intercepting-routes/photos/${i}`}>Link {i}</Link> <Link href={`/intercepting-routes/feed/photos/${i}`}>Link {i}</Link>
</li> </li>
))} ))}
</ul> </ul>
......
import Link from 'next/link'
import React from 'react'
export default function Page() {
return (
<>
<Link href="/nested">to nested</Link>
</>
)
}
...@@ -253,7 +253,7 @@ createNextDescribe( ...@@ -253,7 +253,7 @@ createNextDescribe(
await check( await check(
() => () =>
browser browser
.elementByCss('[href="/intercepting-routes/photos/1"]') .elementByCss('[href="/intercepting-routes/feed/photos/1"]')
.click() .click()
.waitForElementByCss('#photo-intercepted-1') .waitForElementByCss('#photo-intercepted-1')
.text(), .text(),
...@@ -267,7 +267,7 @@ createNextDescribe( ...@@ -267,7 +267,7 @@ createNextDescribe(
// Check if url matches even though it was intercepted. // Check if url matches even though it was intercepted.
await check( await check(
() => browser.url(), () => browser.url(),
next.url + '/intercepting-routes/photos/1' next.url + '/intercepting-routes/feed/photos/1'
) )
// Trigger a refresh, this should load the normal page, not the modal. // Trigger a refresh, this should load the normal page, not the modal.
...@@ -279,7 +279,7 @@ createNextDescribe( ...@@ -279,7 +279,7 @@ createNextDescribe(
// Check if the url matches still. // Check if the url matches still.
await check( await check(
() => browser.url(), () => browser.url(),
next.url + '/intercepting-routes/photos/1' next.url + '/intercepting-routes/feed/photos/1'
) )
}) })
...@@ -307,6 +307,30 @@ createNextDescribe( ...@@ -307,6 +307,30 @@ createNextDescribe(
) )
}) })
it('should render an intercepted route at the top level from a nested path', async () => {
const browser = await next.browser('/nested-link')
await check(
() => browser.waitForElementByCss('#default-slot').text(),
'default from @slot'
)
await check(
() =>
browser
.elementByCss('[href="/nested"]')
.click()
.waitForElementByCss('#interception-slot')
.text(),
'interception from @slot/nested'
)
await check(
() => browser.refresh().waitForElementByCss('#nested').text(),
'hello world from /nested'
)
})
it('should render intercepted route from a nested route', async () => { it('should render intercepted route from a nested route', async () => {
const browser = await next.browser('/intercepting-routes/feed/nested') const browser = await next.browser('/intercepting-routes/feed/nested')
...@@ -314,7 +338,7 @@ createNextDescribe( ...@@ -314,7 +338,7 @@ createNextDescribe(
await check( await check(
() => () =>
browser browser
.elementByCss('[href="/intercepting-routes/photos/1"]') .elementByCss('[href="/intercepting-routes/feed/photos/1"]')
.click() .click()
.waitForElementByCss('#photo-intercepted-1') .waitForElementByCss('#photo-intercepted-1')
.text(), .text(),
...@@ -328,7 +352,7 @@ createNextDescribe( ...@@ -328,7 +352,7 @@ createNextDescribe(
// Check if url matches even though it was intercepted. // Check if url matches even though it was intercepted.
await check( await check(
() => browser.url(), () => browser.url(),
next.url + '/intercepting-routes/photos/1' next.url + '/intercepting-routes/feed/photos/1'
) )
// Trigger a refresh, this should load the normal page, not the modal. // Trigger a refresh, this should load the normal page, not the modal.
...@@ -340,7 +364,7 @@ createNextDescribe( ...@@ -340,7 +364,7 @@ createNextDescribe(
// Check if the url matches still. // Check if the url matches still.
await check( await check(
() => browser.url(), () => browser.url(),
next.url + '/intercepting-routes/photos/1' next.url + '/intercepting-routes/feed/photos/1'
) )
}) })
......
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