Unverified Commit da907823 authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

Fix App Router scroll padding visibility (#96308)

## Summary

- Treat the root `scroll-padding-top` as the lower boundary of the
usable viewport during App Router navigations, so content obscured by a
sticky header is not incorrectly considered visible.
- Preserve the merged Fragment scroll-ownership state machine: empty
Fragments remain unavailable targets, while real targets are classified
against the padding-aware viewport.
- Resolve pixel and percentage values and use the same visibility rule
in both the legacy element handler and the Fragment-ref handler.
- Add regression coverage showing that Next scrolls when the destination
is hidden inside the padding boundary, while preserving the current
scroll position when the destination is genuinely visible below it.

## Performance

The root computed style is resolved lazily, only after the candidate
produces client rects. Empty Fragments and hash navigations do not
perform this lookup. For a real route-scroll target, the resolved value
is cached locally and reused by the second geometry check after
`scrollTop = 0`.

This does not add work to scroll events or every render, and keeping the
value local allows responsive CSS, root classes, and custom properties
to change between navigations. In a 50-iteration dirty-style Chromium
probe, both the existing and updated paths reported 50 style
recalculations and 50 layouts, indicating that the lookup reused the
style/layout update already required by the handler in that test.

## Related work

#96342 is now merged into `canary` and handles empty Fragment scroll
ownership. This PR composes with its `NoClientRects` / `InViewport` /
`OutOfViewport` state machine by changing only the visible-region
boundary for real targets.

## Verification

- `HEADLESS=true pnpm test-dev-turbo
test/e2e/app-dir/router-autoscroll/router-autoscroll.test.ts -t "scroll
padding"` (3/3)
- `HEADLESS=true __NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER=false pnpm
test-dev-turbo
test/e2e/app-dir/router-autoscroll/router-autoscroll.test.ts -t "scroll
padding"` (3/3)
- `HEADLESS=true pnpm test-dev-turbo
test/e2e/app-dir/parallel-routes-scroll-owner/parallel-routes-scroll-owner.test.ts`
(8/8)
- `HEADLESS=true pnpm test-dev-webpack
test/e2e/app-dir/parallel-routes-scroll-owner/parallel-routes-scroll-owner.test.ts`
(8/8)
- `HEADLESS=true pnpm test-dev-turbo
test/e2e/app-dir/navigation-focus/navigation-focus.test.ts` (5/5)
- Manually compared the same sticky-header reproduction before and after
the change.

<!-- NEXT_JS_LLM -->
parent c00449d5
......@@ -108,11 +108,45 @@ const enum ScrollTargetState {
}
/**
* Check where the top corner of the HTMLElement is relative to the viewport.
* Resolve the root scroll padding used by the viewport check.
*
* Computed lengths serialize as pixels, but percentages remain relative to
* the scrollport. Preserve the existing behavior for values that still
* contain unresolved CSS math.
*/
function getScrollPaddingTopInPixels(
htmlElement: HTMLElement,
viewportHeight: number
): number {
const scrollPaddingTop = getComputedStyle(htmlElement).scrollPaddingTop
const value = Number.parseFloat(scrollPaddingTop)
if (!Number.isFinite(value) || value < 0) {
return 0
}
if (scrollPaddingTop.endsWith('px')) {
return value
}
if (scrollPaddingTop.endsWith('%')) {
return (value / 100) * viewportHeight
}
return 0
}
/**
* Check where the top corner of the HTMLElement is relative to the usable
* viewport.
*
* Scroll padding is resolved lazily so an empty Fragment does not trigger a
* computed style read. The caller caches the value for the second check.
*/
function getScrollTargetState(
instance: HTMLElement | FragmentInstance,
viewportHeight: number
viewportHeight: number,
getScrollPaddingTop: () => number
): ScrollTargetState {
const rects = instance.getClientRects()
if (rects.length === 0) {
......@@ -125,7 +159,7 @@ function getScrollTargetState(
elementTop = rect.top
}
}
return elementTop >= 0 && elementTop <= viewportHeight
return elementTop >= getScrollPaddingTop() && elementTop <= viewportHeight
? ScrollTargetState.InViewport
: ScrollTargetState.OutOfViewport
}
......@@ -226,10 +260,21 @@ class InnerScrollAndFocusHandlerOld extends React.Component<ScrollAndMaybeFocusH
// and it won't change during this function.
const htmlElement = document.documentElement
const viewportHeight = htmlElement.clientHeight
let scrollPaddingTop: number | null = null
const getScrollPaddingTop = () => {
if (scrollPaddingTop === null) {
// Reuse the style and layout update from the geometry read above.
scrollPaddingTop = getScrollPaddingTopInPixels(
htmlElement,
viewportHeight
)
}
return scrollPaddingTop
}
// If the element's top edge is already in the viewport, exit early.
if (
getScrollTargetState(domNode, viewportHeight) ===
getScrollTargetState(domNode, viewportHeight, getScrollPaddingTop) ===
ScrollTargetState.InViewport
) {
return
......@@ -243,7 +288,7 @@ class InnerScrollAndFocusHandlerOld extends React.Component<ScrollAndMaybeFocusH
// Scroll to domNode if domNode is not in viewport when scrolled to top of document
if (
getScrollTargetState(domNode, viewportHeight) !==
getScrollTargetState(domNode, viewportHeight, getScrollPaddingTop) !==
ScrollTargetState.InViewport
) {
// Scroll into view doesn't scroll horizontally by default when not needed
......@@ -323,12 +368,27 @@ function InnerScrollHandlerNew(props: ScrollAndMaybeFocusHandlerProps) {
const htmlElement = document.documentElement
let viewportHeight: number | null = null
let initialTargetState: ScrollTargetState | null = null
let scrollPaddingTop: number | null = null
const getScrollPaddingTop = () => {
if (scrollPaddingTop === null) {
// Reuse the style and layout update from the geometry read.
scrollPaddingTop = getScrollPaddingTopInPixels(
htmlElement,
viewportHeight!
)
}
return scrollPaddingTop
}
if (!hashFragment) {
// Store the current viewport height because reading `clientHeight` causes a reflow,
// and it won't change during this function.
viewportHeight = htmlElement.clientHeight
initialTargetState = getScrollTargetState(instance, viewportHeight)
initialTargetState = getScrollTargetState(
instance,
viewportHeight,
getScrollPaddingTop
)
// An empty Fragment is not a scroll target. In particular, avoid
// React's sibling fallback and leave the scroll signal available
......@@ -366,8 +426,11 @@ function InnerScrollHandlerNew(props: ScrollAndMaybeFocusHandlerProps) {
// Scroll to domNode if domNode is not in viewport when scrolled to top of document
if (
getScrollTargetState(instance, viewportHeight!) ===
ScrollTargetState.OutOfViewport
getScrollTargetState(
instance,
viewportHeight!,
getScrollPaddingTop
) === ScrollTargetState.OutOfViewport
) {
// Scroll into view doesn't scroll horizontally by default when not needed
instance.scrollIntoView()
......
......@@ -35,6 +35,21 @@ describe('router autoscrolling on navigation', () => {
await waitForScrollToComplete(browser, options)
}
const setScrollPaddingTop = async (
browser: Playwright,
scrollPaddingTop: string
) => {
const rule = `html { scroll-padding-top: ${scrollPaddingTop}; }`
// Avoid mutating the root style attribute, which React owns and validates
// during client navigations.
await browser.eval(`
const sheet = new CSSStyleSheet()
sheet.replaceSync(${JSON.stringify(rule)})
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]
`)
}
describe('vertical scroll', () => {
it('should scroll to top of document when navigating between to pages without layout', async () => {
const browser = await next.browser('/0/0/100/10000/page1')
......@@ -81,6 +96,29 @@ describe('router autoscrolling on navigation', () => {
await waitForScrollToComplete(browser, { x: 0, y: 50 })
})
it.each(['100px', '50%'])(
'should scroll when the page top is obscured by scroll padding (%s)',
async (scrollPaddingTop) => {
const browser = await next.browser('/10/100/100/1000/page1')
await setScrollPaddingTop(browser, scrollPaddingTop)
await scrollTo(browser, { x: 0, y: 50 })
await browser.eval(`window.router.push("/10/100/100/1000/page2")`)
await waitForScrollToComplete(browser, { x: 0, y: 0 })
}
)
it('should maintain scroll when the page top is below the scroll padding boundary', async () => {
const browser = await next.browser('/10/1000/100/1000/page1')
await setScrollPaddingTop(browser, '100px')
await scrollTo(browser, { x: 0, y: 800 })
await browser.eval(`window.router.push("/10/1000/100/1000/page2")`)
await waitForScrollToComplete(browser, { x: 0, y: 800 })
})
it('should scroll to top of document if possible while giving focus to page', async () => {
const browser = await next.browser('/10/100/100/1000/page1')
......
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