Unverified Commit a5d53155 authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Check root layout change on client (#41475)

Moves the logic that checks if there's a new root layout to the client.
Adds test for static and dynamic catchall.

Related: #41457

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 765791a6
...@@ -406,7 +406,7 @@ function applyRouterStatePatchToTree( ...@@ -406,7 +406,7 @@ function applyRouterStatePatchToTree(
flightRouterState: FlightRouterState, flightRouterState: FlightRouterState,
treePatch: FlightRouterState treePatch: FlightRouterState
): FlightRouterState | null { ): FlightRouterState | null {
const [segment, parallelRoutes /* , url */] = flightRouterState const [segment, parallelRoutes, , , isRootLayout] = flightRouterState
// Root refresh // Root refresh
if (flightSegmentPath.length === 1) { if (flightSegmentPath.length === 1) {
...@@ -451,6 +451,11 @@ function applyRouterStatePatchToTree( ...@@ -451,6 +451,11 @@ function applyRouterStatePatchToTree(
}, },
] ]
// Current segment is the root layout
if (isRootLayout) {
tree[4] = true
}
// TODO-APP: Revisit // TODO-APP: Revisit
// if (url) { // if (url) {
// tree[2] = url // tree[2] = url
...@@ -494,6 +499,47 @@ function shouldHardNavigate( ...@@ -494,6 +499,47 @@ function shouldHardNavigate(
) )
} }
function isNavigatingToNewRootLayout(
currentTree: FlightRouterState,
nextTree: FlightRouterState
): boolean {
// Compare segments
const currentTreeSegment = currentTree[0]
const nextTreeSegment = nextTree[0]
// If any segment is different before we find the root layout, the root layout has changed.
// E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js
// First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.
if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {
// Compare dynamic param name and type but ignore the value, different values would not affect the current root layout
// /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js
if (
currentTreeSegment[0] !== nextTreeSegment[0] ||
currentTreeSegment[2] !== nextTreeSegment[2]
) {
return true
}
} else if (currentTreeSegment !== nextTreeSegment) {
return true
}
// Current tree root layout found
if (currentTree[4]) {
// If the next tree doesn't have the root layout flag, it must have changed.
return !nextTree[4]
}
// Current tree didn't have its root layout here, must have changed.
if (nextTree[4]) {
return true
}
// We can't assume it's `parallelRoutes.children` here in case the root layout is `app/@something/layout.js`
// But it's not possible to be more than one parallelRoutes before the root layout is found
// TODO-APP: change to traverse all parallel routes
const currentTreeChild = Object.values(currentTree[1])[0]
const nextTreeChild = Object.values(nextTree[1])[0]
if (!currentTreeChild || !nextTreeChild) return true
return isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild)
}
export type FocusAndScrollRef = { export type FocusAndScrollRef = {
/** /**
* If focus and scroll should be set in the layout-router's useEffect() * If focus and scroll should be set in the layout-router's useEffect()
...@@ -518,6 +564,7 @@ interface RefreshAction { ...@@ -518,6 +564,7 @@ interface RefreshAction {
mutable: { mutable: {
previousTree?: FlightRouterState previousTree?: FlightRouterState
patchedTree?: FlightRouterState patchedTree?: FlightRouterState
mpaNavigation?: boolean
canonicalUrlOverride?: string canonicalUrlOverride?: string
} }
} }
...@@ -553,6 +600,7 @@ interface NavigateAction { ...@@ -553,6 +600,7 @@ interface NavigateAction {
forceOptimisticNavigation: boolean forceOptimisticNavigation: boolean
cache: CacheNode cache: CacheNode
mutable: { mutable: {
mpaNavigation?: boolean
previousTree?: FlightRouterState previousTree?: FlightRouterState
patchedTree?: FlightRouterState patchedTree?: FlightRouterState
canonicalUrlOverride?: string canonicalUrlOverride?: string
...@@ -587,6 +635,7 @@ interface ServerPatchAction { ...@@ -587,6 +635,7 @@ interface ServerPatchAction {
cache: CacheNode cache: CacheNode
mutable: { mutable: {
patchedTree?: FlightRouterState patchedTree?: FlightRouterState
mpaNavigation?: boolean
canonicalUrlOverride?: string canonicalUrlOverride?: string
} }
} }
...@@ -671,18 +720,42 @@ function clientReducer( ...@@ -671,18 +720,42 @@ function clientReducer(
const href = createHrefFromUrl(url) const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push' const pendingPush = navigateType === 'push'
// Handle concurrent rendering / strict mode case where the cache and tree were already populated. const isForCurrentTree =
if (
mutable.patchedTree &&
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree) JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
) {
if (mutable.mpaNavigation && isForCurrentTree) {
return {
// Set href.
canonicalUrl: mutable.canonicalUrlOverride
? mutable.canonicalUrlOverride
: href,
// TODO-APP: verify mpaNavigation not being set is correct here.
pushRef: {
pendingPush,
mpaNavigation: mutable.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { apply: false },
// Apply cache.
cache: state.cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree: state.tree,
}
}
// Handle concurrent rendering / strict mode case where the cache and tree were already populated.
if (mutable.patchedTree && isForCurrentTree) {
return { return {
// Set href. // Set href.
canonicalUrl: mutable.canonicalUrlOverride canonicalUrl: mutable.canonicalUrlOverride
? mutable.canonicalUrlOverride ? mutable.canonicalUrlOverride
: href, : href,
// TODO-APP: verify mpaNavigation not being set is correct here. // TODO-APP: verify mpaNavigation not being set is correct here.
pushRef: { pendingPush, mpaNavigation: false }, pushRef: {
pendingPush,
mpaNavigation: false,
},
// All navigation requires scroll and focus management to trigger. // All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { apply: true }, focusAndScrollRef: { apply: true },
// Apply cache. // Apply cache.
...@@ -705,6 +778,10 @@ function clientReducer( ...@@ -705,6 +778,10 @@ function clientReducer(
if (newTree !== null) { if (newTree !== null) {
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(
state.tree,
newTree
)
const hardNavigate = const hardNavigate =
// TODO-APP: Revisit if this is correct. // TODO-APP: Revisit if this is correct.
...@@ -793,6 +870,10 @@ function clientReducer( ...@@ -793,6 +870,10 @@ function clientReducer(
if (!res?.bailOptimistic) { if (!res?.bailOptimistic) {
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = optimisticTree mutable.patchedTree = optimisticTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(
state.tree,
optimisticTree
)
return { return {
// Set href. // Set href.
canonicalUrl: href, canonicalUrl: href,
...@@ -867,6 +948,7 @@ function clientReducer( ...@@ -867,6 +948,7 @@ function clientReducer(
} }
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
if (flightDataPath.length === 2) { if (flightDataPath.length === 2) {
cache.subTreeData = subTreeData cache.subTreeData = subTreeData
...@@ -906,6 +988,27 @@ function clientReducer( ...@@ -906,6 +988,27 @@ function clientReducer(
return state return state
} }
if (mutable.mpaNavigation) {
return {
// Set href.
canonicalUrl: mutable.canonicalUrlOverride
? mutable.canonicalUrlOverride
: state.canonicalUrl,
// TODO-APP: verify mpaNavigation not being set is correct here.
pushRef: {
pendingPush: true,
mpaNavigation: mutable.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { apply: false },
// Apply cache.
cache: state.cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree: state.tree,
}
}
// Handle concurrent rendering / strict mode case where the cache and tree were already populated. // Handle concurrent rendering / strict mode case where the cache and tree were already populated.
if (mutable.patchedTree) { if (mutable.patchedTree) {
return { return {
...@@ -968,6 +1071,7 @@ function clientReducer( ...@@ -968,6 +1071,7 @@ function clientReducer(
} }
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
// Root refresh // Root refresh
if (flightDataPath.length === 2) { if (flightDataPath.length === 2) {
...@@ -1013,11 +1117,32 @@ function clientReducer( ...@@ -1013,11 +1117,32 @@ function clientReducer(
const { cache, mutable } = action const { cache, mutable } = action
const href = state.canonicalUrl const href = state.canonicalUrl
// Handle concurrent rendering / strict mode case where the cache and tree were already populated. const isForCurrentTree =
if (
mutable.patchedTree &&
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree) JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
) {
if (mutable.mpaNavigation && isForCurrentTree) {
return {
// Set href.
canonicalUrl: mutable.canonicalUrlOverride
? mutable.canonicalUrlOverride
: state.canonicalUrl,
// TODO-APP: verify mpaNavigation not being set is correct here.
pushRef: {
pendingPush: true,
mpaNavigation: mutable.mpaNavigation,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: { apply: false },
// Apply cache.
cache: state.cache,
prefetchCache: state.prefetchCache,
// Apply patched router state.
tree: state.tree,
}
}
// Handle concurrent rendering / strict mode case where the cache and tree were already populated.
if (mutable.patchedTree && isForCurrentTree) {
return { return {
// Set href. // Set href.
canonicalUrl: mutable.canonicalUrlOverride canonicalUrl: mutable.canonicalUrlOverride
...@@ -1095,6 +1220,7 @@ function clientReducer( ...@@ -1095,6 +1220,7 @@ function clientReducer(
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.mpaNavigation = isNavigatingToNewRootLayout(state.tree, newTree)
// Set subTreeData for the root node of the cache. // Set subTreeData for the root node of the cache.
cache.subTreeData = subTreeData cache.subTreeData = subTreeData
......
...@@ -443,7 +443,8 @@ export type FlightRouterState = [ ...@@ -443,7 +443,8 @@ export type FlightRouterState = [
segment: Segment, segment: Segment,
parallelRoutes: { [parallelRouterKey: string]: FlightRouterState }, parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },
url?: string, url?: string,
refresh?: 'refetch' refresh?: 'refetch',
isRootLayout?: boolean
] ]
/** /**
...@@ -849,10 +850,10 @@ export async function renderToHTMLOrFlight( ...@@ -849,10 +850,10 @@ export async function renderToHTMLOrFlight(
} }
} }
const createFlightRouterStateFromLoaderTree = ([ const createFlightRouterStateFromLoaderTree = (
segment, [segment, parallelRoutes, { layout }]: LoaderTree,
parallelRoutes, rootLayoutIncluded = false
]: LoaderTree): FlightRouterState => { ): FlightRouterState => {
const dynamicParam = getDynamicParamFromSegment(segment) const dynamicParam = getDynamicParamFromSegment(segment)
const segmentTree: FlightRouterState = [ const segmentTree: FlightRouterState = [
...@@ -860,18 +861,22 @@ export async function renderToHTMLOrFlight( ...@@ -860,18 +861,22 @@ export async function renderToHTMLOrFlight(
{}, {},
] ]
if (parallelRoutes) { if (!rootLayoutIncluded && typeof layout !== 'undefined') {
segmentTree[1] = Object.keys(parallelRoutes).reduce( rootLayoutIncluded = true
(existingValue, currentValue) => { segmentTree[4] = true
existingValue[currentValue] = createFlightRouterStateFromLoaderTree(
parallelRoutes[currentValue]
)
return existingValue
},
{} as FlightRouterState[1]
)
} }
segmentTree[1] = Object.keys(parallelRoutes).reduce(
(existingValue, currentValue) => {
existingValue[currentValue] = createFlightRouterStateFromLoaderTree(
parallelRoutes[currentValue],
rootLayoutIncluded
)
return existingValue
},
{} as FlightRouterState[1]
)
return segmentTree return segmentTree
} }
......
...@@ -4,7 +4,7 @@ import { NextInstance } from 'test/lib/next-modes/base' ...@@ -4,7 +4,7 @@ import { NextInstance } from 'test/lib/next-modes/base'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { getRedboxSource, hasRedbox } from 'next-test-utils' import { getRedboxSource, hasRedbox } from 'next-test-utils'
describe.skip('app-dir root layout', () => { describe('app-dir root layout', () => {
const isDev = (global as any).isNextDev const isDev = (global as any).isNextDev
if ((global as any).isNextDeploy) { if ((global as any).isNextDeploy) {
...@@ -151,18 +151,18 @@ describe.skip('app-dir root layout', () => { ...@@ -151,18 +151,18 @@ describe.skip('app-dir root layout', () => {
}) })
it('should work with dynamic routes', async () => { it('should work with dynamic routes', async () => {
const browser = await webdriver(next.url, '/dynamic/first/route') const browser = await webdriver(next.url, '/dynamic/first')
expect(await browser.elementById('dynamic-route').text()).toBe( expect(await browser.elementById('dynamic-first').text()).toBe(
'dynamic route' 'dynamic first'
) )
await browser.eval('window.__TEST_NO_RELOAD = true') await browser.eval('window.__TEST_NO_RELOAD = true')
// Navigate to page with same root layout // Navigate to page with same root layout
await browser.elementByCss('a').click() await browser.elementByCss('a').click()
expect( expect(
await browser.waitForElementByCss('#dynamic-second-hello').text() await browser.waitForElementByCss('#dynamic-first-second').text()
).toBe('dynamic hello') ).toBe('dynamic first second')
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeTrue() expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeTrue()
// Navigate to page with different root layout // Navigate to page with different root layout
...@@ -172,5 +172,51 @@ describe.skip('app-dir root layout', () => { ...@@ -172,5 +172,51 @@ describe.skip('app-dir root layout', () => {
).toBe('Inner basic route') ).toBe('Inner basic route')
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeUndefined() expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeUndefined()
}) })
it('should work with dynamic catchall routes', async () => {
const browser = await webdriver(next.url, '/dynamic-catchall/slug')
expect(await browser.elementById('catchall-slug').text()).toBe(
'catchall slug'
)
await browser.eval('window.__TEST_NO_RELOAD = true')
// Navigate to page with same root layout
await browser.elementById('to-next-url').click()
expect(
await browser.waitForElementByCss('#catchall-slug-slug').text()
).toBe('catchall slug slug')
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeTrue()
// Navigate to page with different root layout
await browser.elementById('to-dynamic-first').click()
expect(await browser.elementById('dynamic-first').text()).toBe(
'dynamic first'
)
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeUndefined()
})
it('should work with static routes', async () => {
const browser = await webdriver(next.url, '/static-mpa-navigation/slug1')
expect(await browser.elementById('static-slug1').text()).toBe(
'static slug1'
)
await browser.eval('window.__TEST_NO_RELOAD = true')
// Navigate to page with same root layout
await browser.elementByCss('a').click()
expect(await browser.waitForElementByCss('#static-slug2').text()).toBe(
'static slug2'
)
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeTrue()
// Navigate to page with different root layout
await browser.elementByCss('a').click()
expect(await browser.elementById('basic-route').text()).toBe(
'Basic route'
)
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeUndefined()
})
}) })
}) })
export default function Root({ children }) {
return (
<html>
<head>
<title>Hello</title>
</head>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Page({ params }) {
const nextUrl = [...params.slug, 'slug']
return (
<>
<Link href={`/dynamic-catchall/${nextUrl.join('/')}`}>
<a id="to-next-url">To next url</a>
</Link>
<Link href="/dynamic/first">
<a id="to-dynamic-first">To next url</a>
</Link>
<p id={`catchall-${params.slug.join('-')}`}>
catchall {params.slug.join(' ')}
</p>
</>
)
}
...@@ -4,7 +4,9 @@ export default function Page({ params }) { ...@@ -4,7 +4,9 @@ export default function Page({ params }) {
return ( return (
<> <>
<Link href="/basic-route/inner">To basic inner</Link> <Link href="/basic-route/inner">To basic inner</Link>
<p id={`dynamic-second-${params.param}`}>dynamic {params.param}</p> <p id={`dynamic-${params.first}-${params.second}`}>
dynamic {params.first} {params.second}
</p>
</> </>
) )
} }
...@@ -3,8 +3,8 @@ import Link from 'next/link' ...@@ -3,8 +3,8 @@ import Link from 'next/link'
export default function Page({ params }) { export default function Page({ params }) {
return ( return (
<> <>
<Link href="/dynamic/second/hello">To second dynamic</Link> <Link href="/dynamic/first/second">To inner dynamic</Link>
<p id={`dynamic-${params.param}`}>dynamic {params.param}</p> <p id={`dynamic-${params.first}`}>dynamic {params.first}</p>
</> </>
) )
} }
export default function Layout({ children }) {
return (
<html>
<head>
<title>Hello</title>
</head>
<body>{children}</body>
</html>
)
}
export function generateStaticParams() {
return [{ slug: 'slug1' }, { slug: 'slug2' }]
}
import Link from 'next/link'
export const config = {
dynamicParams: false,
}
export default function Page({ params }) {
return (
<>
<Link
href={
params.slug === 'slug1'
? '/static-mpa-navigation/slug2'
: '/basic-route'
}
>
To next
</Link>
<p id={`static-${params.slug}`}>static {params.slug}</p>
</>
)
}
...@@ -3,7 +3,7 @@ import Link from 'next/link' ...@@ -3,7 +3,7 @@ import Link from 'next/link'
export default function Page() { export default function Page() {
return ( return (
<> <>
<Link href="/dynamic/first/hello">To dynamic route</Link> <Link href="/dynamic/hello">To dynamic route</Link>
<p id="parallel-one-inner">One inner</p> <p id="parallel-one-inner">One inner</p>
</> </>
) )
......
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