Unverified Commit f8afd611 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Ensure metadata doesn't break scroll-to-top on navigation (#74748)

parent 5bd025d4
...@@ -215,6 +215,14 @@ class InnerScrollAndFocusHandler extends React.Component<ScrollAndFocusHandlerPr ...@@ -215,6 +215,14 @@ class InnerScrollAndFocusHandler extends React.Component<ScrollAndFocusHandlerPr
// Verify if the element is a HTMLElement and if we want to consider it for scroll behavior. // Verify if the element is a HTMLElement and if we want to consider it for scroll behavior.
// If the element is skipped, try to select the next sibling and try again. // If the element is skipped, try to select the next sibling and try again.
while (!(domNode instanceof HTMLElement) || shouldSkipElement(domNode)) { while (!(domNode instanceof HTMLElement) || shouldSkipElement(domNode)) {
if (process.env.NODE_ENV !== 'production') {
if (domNode.parentElement?.localName === 'head') {
console.error(
'Tried to scroll to a head element. This is a bug in Next.js.'
)
}
}
// No siblings found that match the criteria are found, so handle scroll higher up in the tree instead. // No siblings found that match the criteria are found, so handle scroll higher up in the tree instead.
if (domNode.nextElementSibling === null) { if (domNode.nextElementSibling === null) {
return return
......
...@@ -399,25 +399,25 @@ async function createComponentTreeInternal({ ...@@ -399,25 +399,25 @@ async function createComponentTreeInternal({
const notFoundElement = NotFound ? ( const notFoundElement = NotFound ? (
<> <>
<NotFound />
{metadata} {metadata}
{notFoundStyles} {notFoundStyles}
<NotFound />
</> </>
) : undefined ) : undefined
const forbiddenElement = Forbidden ? ( const forbiddenElement = Forbidden ? (
<> <>
<Forbidden />
{metadata} {metadata}
{forbiddenStyles} {forbiddenStyles}
<Forbidden />
</> </>
) : undefined ) : undefined
const unauthorizedElement = Unauthorized ? ( const unauthorizedElement = Unauthorized ? (
<> <>
<Unauthorized />
{metadata} {metadata}
{unauthorizedStyles} {unauthorizedStyles}
<Unauthorized />
</> </>
) : undefined ) : undefined
...@@ -669,8 +669,13 @@ async function createComponentTreeInternal({ ...@@ -669,8 +669,13 @@ async function createComponentTreeInternal({
return [ return [
actualSegment, actualSegment,
<React.Fragment key={cacheNodeKey}> <React.Fragment key={cacheNodeKey}>
{metadata}
{pageElement} {pageElement}
{/*
* The order here matters since a parent might call findDOMNode().
* findDOMNode() will return the first child if multiple children are rendered.
* But React will hoist metadata into <head> which breaks scroll handling.
*/}
{metadata}
{layerAssets} {layerAssets}
<OutletBoundary> <OutletBoundary>
<MetadataOutlet ready={getViewportReady} /> <MetadataOutlet ready={getViewportReady} />
...@@ -805,12 +810,12 @@ async function createComponentTreeInternal({ ...@@ -805,12 +810,12 @@ async function createComponentTreeInternal({
notFound={ notFound={
NotFound ? ( NotFound ? (
<> <>
{metadata}
{layerAssets} {layerAssets}
<SegmentComponent params={params}> <SegmentComponent params={params}>
{notFoundStyles} {notFoundStyles}
<NotFound /> <NotFound />
</SegmentComponent> </SegmentComponent>
{metadata}
</> </>
) : undefined ) : undefined
} }
......
...@@ -374,7 +374,9 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -374,7 +374,9 @@ describe('Error overlay for hydration errors in App router', () => {
const { session, browser } = sandbox const { session, browser } = sandbox
await session.openRedbox() await session.openRedbox()
await retry(async () => {
expect(await getRedboxTotalErrorCount(browser)).toBe(2) expect(await getRedboxTotalErrorCount(browser)).toBe(2)
})
// FIXME: Should also have "text nodes cannot be a child of tr" // FIXME: Should also have "text nodes cannot be a child of tr"
expect(await session.getRedboxDescription()).toMatchInlineSnapshot( expect(await session.getRedboxDescription()).toMatchInlineSnapshot(
...@@ -439,7 +441,6 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -439,7 +441,6 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}>
<__next_metadata_boundary__>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}> <Page params={Promise} searchParams={Promise}>
> <table> > <table>
...@@ -567,7 +568,9 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -567,7 +568,9 @@ describe('Error overlay for hydration errors in App router', () => {
const { session, browser } = sandbox const { session, browser } = sandbox
await session.openRedbox() await session.openRedbox()
await retry(async () => {
expect(await getRedboxTotalErrorCount(browser)).toBe(2) expect(await getRedboxTotalErrorCount(browser)).toBe(2)
})
const description = await session.getRedboxDescription() const description = await session.getRedboxDescription()
expect(description).toContain( expect(description).toContain(
...@@ -665,7 +668,9 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -665,7 +668,9 @@ describe('Error overlay for hydration errors in App router', () => {
const { session, browser } = sandbox const { session, browser } = sandbox
await session.openRedbox() await session.openRedbox()
await retry(async () => {
expect(await getRedboxTotalErrorCount(browser)).toBe(2) expect(await getRedboxTotalErrorCount(browser)).toBe(2)
})
const description = await session.getRedboxDescription() const description = await session.getRedboxDescription()
expect(description).toEqual(outdent` expect(description).toEqual(outdent`
...@@ -718,7 +723,9 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -718,7 +723,9 @@ describe('Error overlay for hydration errors in App router', () => {
const { session, browser } = sandbox const { session, browser } = sandbox
await session.openRedbox() await session.openRedbox()
await retry(async () => {
expect(await getRedboxTotalErrorCount(browser)).toBe(2) expect(await getRedboxTotalErrorCount(browser)).toBe(2)
})
const description = await session.getRedboxDescription() const description = await session.getRedboxDescription()
expect(description).toContain( expect(description).toContain(
...@@ -895,7 +902,6 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -895,7 +902,6 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}>
<__next_metadata_boundary__>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}> <Page params={Promise} searchParams={Promise}>
<div> <div>
...@@ -916,7 +922,6 @@ describe('Error overlay for hydration errors in App router', () => { ...@@ -916,7 +922,6 @@ describe('Error overlay for hydration errors in App router', () => {
<RedirectBoundary> <RedirectBoundary>
<RedirectErrorBoundary router={{...}}> <RedirectErrorBoundary router={{...}}>
<InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}> <InnerLayoutRouter url="/" tree={[...]} cacheNode={{lazyData:null, ...}} segmentPath={[...]}>
<__next_metadata_boundary__>
<ClientPageRoot Component={function Page} searchParams={{}} params={{}}> <ClientPageRoot Component={function Page} searchParams={{}} params={{}}>
<Page params={Promise} searchParams={Promise}> <Page params={Promise} searchParams={Promise}>
<div> <div>
......
import type { Metadata } from 'next'
export const metadata: Metadata = {
keywords: ['new-metadata'],
}
export default function Page() {
return (
<>
{
// Repeat 500 elements
Array.from({ length: 500 }, (_, i) => (
<div key={i}>{i}</div>
))
}
</>
)
}
...@@ -31,6 +31,10 @@ export default function Page() { ...@@ -31,6 +31,10 @@ export default function Page() {
To sticky first element To sticky first element
</Link> </Link>
</div> </div>
<div>
<Link href="/new-metadata">To new metadata</Link>
</div>
</> </>
) )
} }
import webdriver from 'next-webdriver' import webdriver, { type BrowserInterface } from 'next-webdriver'
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils' import { check, assertNoConsoleErrors, retry } from 'next-test-utils'
describe('router autoscrolling on navigation', () => { describe('router autoscrolling on navigation', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
type BrowserInterface = Awaited<ReturnType<typeof webdriver>>
const getTopScroll = async (browser: BrowserInterface) => const getTopScroll = async (browser: BrowserInterface) =>
await browser.eval('document.documentElement.scrollTop') await browser.eval('document.documentElement.scrollTop')
const getLeftScroll = async (browser: BrowserInterface) => const getLeftScroll = async (browser: BrowserInterface) =>
await browser.eval('document.documentElement.scrollLeft') await browser.eval('document.documentElement.scrollLeft')
const waitForScrollToComplete = ( const waitForScrollToComplete = async (
browser, browser: BrowserInterface,
options: { x: number; y: number } options: { x: number; y: number }
) => ) => {
check(async () => { await retry(async () => {
const top = await getTopScroll(browser) const top = await getTopScroll(browser)
const left = await getLeftScroll(browser) const left = await getLeftScroll(browser)
return top === options.y && left === options.x expect({ top, left }).toEqual({ top: options.y, left: options.x })
? 'success' })
: JSON.stringify({ top, left }) await assertNoConsoleErrors(browser)
}, 'success') }
const scrollTo = async ( const scrollTo = async (
browser: BrowserInterface, browser: BrowserInterface,
...@@ -93,6 +91,23 @@ describe('router autoscrolling on navigation', () => { ...@@ -93,6 +91,23 @@ describe('router autoscrolling on navigation', () => {
await browser.eval(`window.router.push("/10/100/100/1000/page2")`) await browser.eval(`window.router.push("/10/100/100/1000/page2")`)
await waitForScrollToComplete(browser, { x: 0, y: 0 }) await waitForScrollToComplete(browser, { x: 0, y: 0 })
}) })
it('should scroll to top of document with new metadata', async () => {
const browser = await webdriver(next.url, '/')
// scroll to bottom
await browser.eval(
`window.scrollTo(0, ${await browser.eval('document.documentElement.scrollHeight')})`
)
// Just need to scroll by something
expect(await getTopScroll(browser)).toBeGreaterThan(0)
await browser.elementByCss('[href="/new-metadata"]').click()
expect(
await browser.eval('document.documentElement.scrollHeight')
).toBeGreaterThan(0)
await waitForScrollToComplete(browser, { x: 0, y: 0 })
})
}) })
describe('horizontal scroll', () => { describe('horizontal scroll', () => {
...@@ -153,7 +168,7 @@ describe('router autoscrolling on navigation', () => { ...@@ -153,7 +168,7 @@ describe('router autoscrolling on navigation', () => {
return ( return (
content + content +
` `
\\\\ Add this meaningless comment to force refresh // Add this meaningless comment to force refresh
` `
) )
}) })
......
...@@ -1553,8 +1553,9 @@ export async function assertNoConsoleErrors(browser: BrowserInterface) { ...@@ -1553,8 +1553,9 @@ export async function assertNoConsoleErrors(browser: BrowserInterface) {
log.source === 'warning' || log.source === 'warning' ||
(log.source === 'error' && (log.source === 'error' &&
// These are expected when we visit 404 pages. // These are expected when we visit 404 pages.
log.message !== !log.message.startsWith(
'Failed to load resource: the server responded with a status of 404 (Not Found)') 'Failed to load resource: the server responded with a status of 404'
))
) )
}) })
......
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