Unverified Commit d9850940 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Fix scrolling when invisible element is targeted (#48874)

### What?

Mux reported they're experiencing a specific case where scroll wasn't
applied. I've found a bug when the first element in a layout or page,
the one that React will return from `findDOMNode`, is display: hidden.
At that point the rect is is `0` `0` `0` `0` and the current logic
assumes that means it's in the viewport as it's top `0`.

In order to fix this I've looked at a few ways:

- Scrolling to top when the element is not visible
- Scrolling to the parent element that is visible
- **Scrolling to the closest sibling (nextSibling) of the element that
is visible**

Eventually I landed on the third option after looking at the Mux case,
my reproduction, and the way vercel.com's pages leveraging App Router
are structured.

### How?

Used a while loop to check if the domNode is visible, if not we continue
to the next sibling until one that is visible is found. If none are
found we bail on resolving further.

While looking into this it highlighted that we should add a global
scroll handler in app-router too for the case where none of the
layout-routers apply scroll. With this fix that is less urgent though so
I've added a todo.


Fixes NEXT-1056

<!-- 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 0b59b170
...@@ -105,6 +105,26 @@ function findDOMNode( ...@@ -105,6 +105,26 @@ function findDOMNode(
return ReactDOM.findDOMNode(instance) return ReactDOM.findDOMNode(instance)
} }
const rectProperties = [
'bottom',
'height',
'left',
'right',
'top',
'width',
'x',
'y',
] as const
/**
* Check if a HTMLElement is hidden.
*/
function elementCanScroll(element: HTMLElement) {
// Uses `getBoundingClientRect` to check if the element is hidden instead of `offsetParent`
// because `offsetParent` doesn't consider document/body
const rect = element.getBoundingClientRect()
return rectProperties.every((item) => rect[item] === 0)
}
/** /**
* Check if the top corner of the HTMLElement is in the viewport. * Check if the top corner of the HTMLElement is in the viewport.
*/ */
...@@ -172,11 +192,23 @@ class ScrollAndFocusHandler extends React.Component<ScrollAndFocusHandlerProps> ...@@ -172,11 +192,23 @@ class ScrollAndFocusHandler extends React.Component<ScrollAndFocusHandlerProps>
domNode = findDOMNode(this) domNode = findDOMNode(this)
} }
// If there is no DOMNode this layout-router level is skipped. It'll be handled higher-up in the tree. // TODO-APP: Handle the case where we couldn't select any DOM node, even higher up in the layout-router above the current segmentPath.
if (!(domNode instanceof HTMLElement)) { // If there is no DOM node this layout-router level is skipped. It'll be handled higher-up in the tree.
if (!(domNode instanceof Element)) {
return return
} }
// Verify if the element is a HTMLElement and if it's visible on screen (e.g. not display: none).
// If the element is not a HTMLElement or not visible we try to select the next sibling and try again.
while (!(domNode instanceof HTMLElement) || elementCanScroll(domNode)) {
// TODO-APP: Handle the case where we couldn't select any DOM node, even higher up in the layout-router above the current segmentPath.
// No siblings found that are visible so we handle scroll higher up in the tree instead.
if (domNode.nextElementSibling === null) {
return
}
domNode = domNode.nextElementSibling
}
// State is mutated to ensure that the focus and scroll is applied only once. // State is mutated to ensure that the focus and scroll is applied only once.
focusAndScrollRef.apply = false focusAndScrollRef.apply = false
......
export default function InvisibleFirstElementPage() {
return (
<>
<div style={{ display: 'none' }}>Content that is hidden.</div>
<div id="content-that-is-visible">Content which is not hidden.</div>
{
// Repeat 500 elements
Array.from({ length: 500 }, (_, i) => (
<div key={i}>{i}</div>
))
}
</>
)
}
import Link from 'next/link'
export default function Page() {
return (
<>
{
// Repeat 500 elements
Array.from({ length: 500 }, (_, i) => (
<div key={i}>{i}</div>
))
}
<Link href="/invisible-first-element" id="to-invisible-first-element">
To invisible first element
</Link>
</>
)
}
...@@ -159,5 +159,17 @@ createNextDescribe( ...@@ -159,5 +159,17 @@ createNextDescribe(
} }
) )
}) })
describe('bugs', () => {
it('Should scroll to the top of the layout when the first child is display none', async () => {
const browser = await webdriver(next.url, '/')
await browser.eval('window.scrollTo(0, 500)')
await browser
.elementByCss('#to-invisible-first-element')
.click()
.waitForElementByCss('#content-that-is-visible')
await check(() => browser.eval('window.scrollY'), 0)
})
})
} }
) )
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