Unverified Commit a71227a4 authored by Jimmy Lai's avatar Jimmy Lai Committed by GitHub

parallel routes: fix layout not re-rendering (#48066)

### What?

This PR makes the parent layout of parallel routes re-render when the
parallel route segments are different or when either of them has a
refetch marker.

Example:
```
.
└── app/
    ├── page.ts
    ├── layout.ts
    ├── foo/
    │   └── page.ts
    └── @modal/
        ├── default.js
        └── foo/
            └── page.ts
```

Here if you navigated to `/foo` from `/`, `@modal/foo/page` would never
get re-rendered because the tree would only re-render from
`foo/page.ts`.

This PR adds a check that checks the router state on navigation to see
if the parallel route segments diverge on navigation. Here we would be
checking that `@modal/default` is different from `@modal/page` so we
would re-render.

Also added some logic to make sure that refetch routes are processed
first when handling parallel routes.

### Why?

See example

Closes NEXT-966
Fixes #


<!-- 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 #

-->
parent 883933b6
...@@ -32,6 +32,7 @@ export function applyFlightData( ...@@ -32,6 +32,7 @@ export function applyFlightData(
// Copy subTreeData for the root node of the cache. // Copy subTreeData for the root node of the cache.
cache.status = CacheStates.READY cache.status = CacheStates.READY
cache.subTreeData = state.cache.subTreeData cache.subTreeData = state.cache.subTreeData
cache.parallelRoutes = new Map(state.cache.parallelRoutes)
// Create a copy of the existing cache with the subTreeData applied. // Create a copy of the existing cache with the subTreeData applied.
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath) fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
} }
......
...@@ -84,9 +84,6 @@ export function computeChangedPath( ...@@ -84,9 +84,6 @@ export function computeChangedPath(
parallelRoutesB[parallelRouterKey] parallelRoutesB[parallelRouterKey]
) )
if (changedPath !== null) { if (changedPath !== null) {
if (changedPath === '') {
return segmentToPathname(segmentB)
}
return `${segmentToPathname(segmentB)}/${changedPath}` return `${segmentToPathname(segmentB)}/${changedPath}`
} }
} }
......
...@@ -21,9 +21,6 @@ export function fillLazyItemsTillLeafWithHead( ...@@ -21,9 +21,6 @@ export function fillLazyItemsTillLeafWithHead(
const cacheKey = createRouterCacheKey(segmentForParallelRoute) const cacheKey = createRouterCacheKey(segmentForParallelRoute)
if (existingCache) { if (existingCache) {
if (cacheKey === '__DEFAULT__') {
continue
}
const existingParallelRoutesCacheNode = const existingParallelRoutesCacheNode =
existingCache.parallelRoutes.get(key) existingCache.parallelRoutes.get(key)
if (existingParallelRoutesCacheNode) { if (existingParallelRoutesCacheNode) {
......
...@@ -981,7 +981,22 @@ export async function renderToHTMLOrFlight( ...@@ -981,7 +981,22 @@ export async function renderToHTMLOrFlight(
}): Promise<FlightDataPath> => { }): Promise<FlightDataPath> => {
const [segment, parallelRoutes, components] = loaderTreeToFilter const [segment, parallelRoutes, components] = loaderTreeToFilter
const parallelRoutesKeys = Object.keys(parallelRoutes) // if there's a refetch key, it'll probably take precedence when rendering
// so we sort the parallel routes so that the refetch key is first
// Sort the routes so that a route marked for refetching is at the beginning of the array
const parallelRoutesKeys = Object.keys(parallelRoutes).sort(
(parallelRouteKeyA, parallelRouteKeyB) => {
if (flightRouterState?.[1][parallelRouteKeyA][3] === 'refetch') {
return -1
}
if (flightRouterState?.[1][parallelRouteKeyB][3] === 'refetch') {
return 1
}
return 0
}
)
const { layout } = components const { layout } = components
const isLayout = typeof layout !== 'undefined' const isLayout = typeof layout !== 'undefined'
...@@ -1021,7 +1036,19 @@ export async function renderToHTMLOrFlight( ...@@ -1021,7 +1036,19 @@ export async function renderToHTMLOrFlight(
// Last item in the tree // Last item in the tree
parallelRoutesKeys.length === 0 || parallelRoutesKeys.length === 0 ||
// Explicit refresh // Explicit refresh
flightRouterState[3] === 'refetch' flightRouterState[3] === 'refetch' ||
// if any of the parallel routes segments differ or have a refresh marker
Object.entries(parallelRoutes).some(
([parallelRouteKey, [parallelRouteSegment]]) => {
const [incomingParallelRouteSegment] =
flightRouterState[1][parallelRouteKey] ?? []
return (
incomingParallelRouteSegment === '__DEFAULT__' &&
parallelRouteSegment !== '__DEFAULT__'
)
}
)
if (!parentRendered && renderComponentsOnThisLevel) { if (!parentRendered && renderComponentsOnThisLevel) {
const overriddenSegment = const overriddenSegment =
......
import React from 'react'
export default function Page() {
return <p id="interception-slot">interception from @slot/nested</p>
}
import React from 'react'
export default function Default() {
return <p id="default-slot">default from @slot</p>
}
export default function Root({ children }: { children: React.ReactNode }) { import React from 'react'
export default function Root({
children,
slot,
}: {
children: React.ReactNode
slot: React.ReactNode
}) {
return ( return (
<html> <html>
<body>{children}</body> <body>
{children}
{slot}
</body>
</html> </html>
) )
} }
import React from 'react'
export default function Page() {
return <p id="nested">hello world from /nested</p>
}
import Link from 'next/link'
import React from 'react'
export default function Page() { export default function Page() {
return <p>hello world</p> return (
<>
<p>hello world</p>
<Link href="/nested">to nested</Link>
</>
)
} }
import React from 'react'
export default function Page() {
return <div id="default-parallel">default view for parallel</div>
}
import React from 'react'
export default function Page() {
return <div id="parallel-foo">parallel for foo</div>
}
import React from 'react'
export default function Page() {
return <div id="children-foo">foo</div>
}
import React from 'react'
export default function Layout({ children, parallel }) {
return (
<>
{children}
{parallel}
</>
)
}
import Link from 'next/link'
import React from 'react'
export default function Layout() {
return (
<div>
<Link href="/parallel-non-intercepting/foo">link</Link>
</div>
)
}
...@@ -246,6 +246,30 @@ createNextDescribe( ...@@ -246,6 +246,30 @@ createNextDescribe(
) )
}) })
it('should render an intercepted route from a slot', async () => {
const browser = await next.browser('/')
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')
...@@ -283,6 +307,30 @@ createNextDescribe( ...@@ -283,6 +307,30 @@ createNextDescribe(
) )
}) })
it('should re-render the layout on the server when it had a default child route', async () => {
const browser = await next.browser('/parallel-non-intercepting')
// check if the default view loads
await check(
() => browser.waitForElementByCss('#default-parallel').text(),
'default view for parallel'
)
// check that navigating to /foo re-renders the layout to display @parallel/foo
await check(
() =>
browser
.elementByCss('[href="/parallel-non-intercepting/foo"]')
.click()
.waitForElementByCss('#parallel-foo')
.text(),
'parallel for foo'
)
// check that navigating to /foo also re-renders the base children
await check(() => browser.elementByCss('#children-foo').text(), 'foo')
})
it('should render modal when paired with parallel routes', async () => { it('should render modal when paired with parallel routes', async () => {
const browser = await next.browser( const browser = await next.browser(
'/intercepting-parallel-modal/vercel' '/intercepting-parallel-modal/vercel'
......
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