-
Notifications
You must be signed in to change notification settings - Fork 1.4k
docs: fix scroll position restoration when navigating back/forward #9242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
reidbarber
wants to merge
1
commit into
main
Choose a base branch
from
s2-docs-fix-scroll-restoration
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -30,14 +30,52 @@ let updateRoot = hydrate({ | |
| let currentNavigationId = 0; | ||
| let currentAbortController: AbortController | null = null; | ||
|
|
||
| // Store scroll positions by pathname | ||
| const scrollPositions = new Map<string, {scrollTop: number, windowScrollTop: number}>(); | ||
|
|
||
| // Track the current pathname so we can save scroll position on popstate | ||
| // (when popstate fires, location.pathname has already changed to the destination) | ||
| let currentPathname = location.pathname; | ||
|
|
||
| function getScrollContainer(): HTMLElement | null { | ||
| return document.querySelector('main'); | ||
| } | ||
|
|
||
| // Save scroll position for a given pathname | ||
| function saveScrollPosition(pathname: string) { | ||
| let scrollContainer = getScrollContainer(); | ||
| let scrollTop = scrollContainer?.scrollTop ?? 0; | ||
| let windowScrollTop = window.scrollY; | ||
| scrollPositions.set(pathname, {scrollTop, windowScrollTop}); | ||
| } | ||
|
|
||
| function restoreScrollPosition(pathname: string) { | ||
| let position = scrollPositions.get(pathname); | ||
| if (position) { | ||
| requestAnimationFrame(() => { | ||
| let scrollContainer = getScrollContainer(); | ||
| if (scrollContainer) { | ||
| scrollContainer.scrollTop = position.scrollTop; | ||
| } | ||
| window.scrollTo(0, position.windowScrollTop); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wouldn't it need to be the inner div that we scroll not the window? |
||
| }); | ||
| } | ||
| } | ||
|
|
||
| // A very simple router. When we navigate, we'll fetch a new RSC payload from the server, | ||
| // and in a React transition, stream in the new page. Once complete, we'll pushState to | ||
| // update the URL in the browser. | ||
| async function navigate(pathname: string, push = false) { | ||
| // restoreScroll: when true (e.g., popstate), restore scroll position from saved positions | ||
| async function navigate(pathname: string, push = false, restoreScroll = false) { | ||
| let [basePath, pathAnchor] = pathname.split('#'); | ||
| let currentPath = location.pathname; | ||
| let isSamePageAnchor = (!basePath || basePath === currentPath) && pathAnchor; | ||
|
|
||
| // Save scroll position before navigating away | ||
| // For push: use location.pathname (still the current page) | ||
| // For popstate: use currentPathname (because location.pathname already changed) | ||
| saveScrollPosition(push ? location.pathname : currentPathname); | ||
|
|
||
| if (isSamePageAnchor) { | ||
| if (push) { | ||
| history.pushState(null, '', pathname); | ||
|
|
@@ -95,16 +133,28 @@ async function navigate(pathname: string, push = false) { | |
| push = false; | ||
| } | ||
|
|
||
| // Reset scroll if navigating to a different page without an anchor | ||
| if (currentPath !== newBasePath && !newPathAnchor) { | ||
| // Handle scroll position | ||
| if (restoreScroll) { | ||
| // Restore scroll position from saved positions (back/forward navigation) | ||
| restoreScrollPosition(newBasePath); | ||
| } else if (currentPath !== newBasePath && !newPathAnchor) { | ||
| // Reset scroll for forward navigation to a different page without an anchor | ||
| let scrollContainer = getScrollContainer(); | ||
| if (scrollContainer) { | ||
| scrollContainer.scrollTop = 0; | ||
| } | ||
| window.scrollTo(0, 0); | ||
| } else if (newPathAnchor) { | ||
| // Scroll to anchor | ||
| let element = document.getElementById(newPathAnchor); | ||
| if (element) { | ||
| element.scrollIntoView(); | ||
| } | ||
| } | ||
|
|
||
| // Update tracked pathname after navigation completes | ||
| currentPathname = newBasePath; | ||
|
|
||
| queueMicrotask(() => { | ||
| window.dispatchEvent(new CustomEvent('rsc-navigation')); | ||
| resolve(); | ||
|
|
@@ -235,9 +285,10 @@ document.addEventListener('click', e => { | |
| } | ||
| }); | ||
|
|
||
| // When the user clicks the back button, navigate with RSC. | ||
| // When the user clicks the back/forward button, navigate with RSC. | ||
| // Pass restoreScroll=true to restore scroll position from saved positions. | ||
| window.addEventListener('popstate', () => { | ||
| navigate(location.pathname + location.search + location.hash); | ||
| navigate(location.pathname + location.search + location.hash, false, true); | ||
| }); | ||
|
|
||
| function scrollToCurrentHash() { | ||
|
|
@@ -267,7 +318,5 @@ function scrollToCurrentHash() { | |
| if (document.readyState === 'complete' || document.readyState === 'interactive') { | ||
| scrollToCurrentHash(); | ||
| } else { | ||
| window.addEventListener('DOMContentLoaded', () => { | ||
| scrollToCurrentHash(); | ||
| }, {once: true}); | ||
| window.addEventListener('DOMContentLoaded', scrollToCurrentHash, {once: true}); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we can save these in the history entry itself? https://stackoverflow.com/a/16732655
Might also have to turn off the browser's defaults? https://developer.chrome.com/blog/history-api-scroll-restoration
I did wonder if the defaults would work if we moved the
keyfrom the<main>element further down (e.g. article) so that it doesn't get replaced on each navigation. Did you try that?