-
-
Notifications
You must be signed in to change notification settings - Fork 219
feat(theme): add ScrollRestoration to avoid scroll flash #3160
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
SoonIter
wants to merge
11
commits into
main
Choose a base branch
from
syt/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.
+200
−94
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
98f2c44
feat(theme): add ScrollRestoration for back/forward scroll position r…
SoonIter c3fb72a
chore: update
SoonIter 4571dc8
refactor(theme): merge useScrollAfterNav into ScrollRestoration
SoonIter 498b88e
docs: add React Router ScrollRestoration reference link
SoonIter b4ac690
chore: update
SoonIter 868fdcc
chore: fixed by antigravity
SoonIter 986f6bd
chore: fixed by glm-5
SoonIter 65453d3
chore: update
SoonIter 461234d
chore: update
SoonIter 25ac3bb
chore: update
SoonIter 5a28af2
chore: update
SoonIter 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
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
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
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 |
|---|---|---|
| @@ -0,0 +1,196 @@ | ||
| import { useLocation, useNavigationType } from '@rspress/core/runtime'; | ||
| import { useLayoutEffect, useRef } from 'react'; | ||
|
|
||
| const STORAGE_KEY = 'rspress-scroll-positions'; | ||
| const MAX_SCROLL_ENTRIES = 100; | ||
|
|
||
| // Module-level state for scroll positions | ||
| const savedScrollPositions: Record<string, number> = | ||
| typeof window === 'undefined' | ||
| ? {} | ||
| : JSON.parse(sessionStorage.getItem(STORAGE_KEY) || '{}'); | ||
|
|
||
| /** | ||
| * Parse CSS length value to number (in pixels). | ||
| * Supports: px | ||
| */ | ||
| function parseCSSLength(value: string): number { | ||
| if (!value || value === 'auto' || value === 'none') { | ||
| return 0; | ||
| } | ||
|
|
||
| const numValue = Number.parseFloat(value); | ||
| if (Number.isNaN(numValue)) { | ||
| return 0; | ||
| } | ||
|
|
||
| return numValue; | ||
| } | ||
|
|
||
| /** | ||
| * Scroll to a hash target element, respecting scroll-padding-top. | ||
| */ | ||
| function scrollToHashTarget(hash: string): boolean { | ||
| const target = document.getElementById(hash.slice(1)); | ||
| if (!target) { | ||
| return false; | ||
| } | ||
|
|
||
| const scrollPaddingTop = parseCSSLength( | ||
| window | ||
| .getComputedStyle(document.documentElement) | ||
| .getPropertyValue('scroll-padding-top'), | ||
| ); | ||
|
|
||
| const offsetTop = Math.round( | ||
| window.scrollY + target.getBoundingClientRect().top - scrollPaddingTop, | ||
| ); | ||
|
|
||
| window.scrollTo({ left: 0, top: offsetTop }); | ||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Get the scroll restoration key from location. | ||
| * Uses location.key by default, which provides unique keys for each navigation. | ||
| */ | ||
| function getScrollRestorationKey(location: { key: string }): string { | ||
| return location.key; | ||
| } | ||
|
|
||
| /** | ||
| * Persist scroll positions to sessionStorage. | ||
| * Prunes oldest entries if exceeding MAX_SCROLL_ENTRIES. | ||
| */ | ||
| function persistSavedPositions(): void { | ||
| try { | ||
| const keys = Object.keys(savedScrollPositions); | ||
| if (keys.length > MAX_SCROLL_ENTRIES) { | ||
| // Remove oldest entries (first inserted keys) | ||
| const excess = keys.length - MAX_SCROLL_ENTRIES; | ||
| for (let i = 0; i < excess; i++) { | ||
| delete savedScrollPositions[keys[i]]; | ||
| } | ||
| } | ||
| sessionStorage.setItem(STORAGE_KEY, JSON.stringify(savedScrollPositions)); | ||
| } catch { | ||
| // Ignore errors | ||
| } | ||
| } | ||
|
|
||
| // The inline script that runs before React hydration. | ||
| // It reads the saved scroll position from sessionStorage and restores it immediately, | ||
| // preventing a flash of wrong scroll position. | ||
| // Also handles hash anchor scrolling since scrollRestoration is 'manual'. | ||
| const inlineScript = `(function(){ | ||
| try { | ||
| if (!window.history.state || !window.history.state.key) { | ||
| var key = Math.random().toString(32).slice(2); | ||
| window.history.replaceState({ key: key }, ""); | ||
| } | ||
|
|
||
| var positions = JSON.parse(sessionStorage.getItem('${STORAGE_KEY}') || '{}'); | ||
| var y = positions[window.history.state.key]; | ||
|
|
||
| if (typeof y === 'number') { | ||
| window.history.scrollRestoration = 'manual'; | ||
| window.scrollTo(0, y); | ||
| } | ||
| } catch(e) {} | ||
| })()`; | ||
|
|
||
| /** | ||
| * Hook for scroll restoration logic. | ||
| * Follows React Router's implementation closely. | ||
| */ | ||
| function useScrollRestoration() { | ||
| const location = useLocation(); | ||
| const navigationType = useNavigationType(); | ||
| const prevKeyRef = useRef<string | undefined>(undefined); | ||
|
|
||
| // Save positions on pagehide for tab close / page refresh scenarios. | ||
| // Reads key from history.state directly so this effect only runs once. | ||
| useLayoutEffect(() => { | ||
| const onPageHide = () => { | ||
| const state = window.history.state; | ||
| const key = state?.key; | ||
| if (key) { | ||
| savedScrollPositions[key] = window.scrollY; | ||
| persistSavedPositions(); | ||
| } | ||
| // Let browser handle scroll restoration on page refresh | ||
| window.history.scrollRestoration = 'auto'; | ||
| }; | ||
|
|
||
| window.addEventListener('pagehide', onPageHide); | ||
| return () => { | ||
| window.removeEventListener('pagehide', onPageHide); | ||
| }; | ||
| }, []); | ||
|
|
||
| // Handle scroll on navigation | ||
| useLayoutEffect(() => { | ||
| const prevKey = prevKeyRef.current; | ||
| const currentKey = getScrollRestorationKey(location); | ||
| prevKeyRef.current = currentKey; | ||
|
|
||
| // Save the previous page's scroll position before handling the new page. | ||
| // This is essential for SPA navigation where pagehide does not fire. | ||
| if (prevKey) { | ||
| savedScrollPositions[prevKey] = window.scrollY; | ||
| persistSavedPositions(); | ||
| } | ||
|
|
||
| // For POP navigation (back/forward), restore saved position | ||
| if (navigationType === 'POP') { | ||
| // console.log(`[ScrollRestoration] POP navigation detected. Restoring scroll position for key: ${currentKey}`); | ||
| // const savedY = savedScrollPositions[currentKey]; | ||
|
|
||
| // if (typeof savedY === 'number') { | ||
| // // Use requestAnimationFrame to ensure DOM is ready | ||
| // requestAnimationFrame(() => { | ||
| // window.scrollTo(0, savedY); | ||
| // }); | ||
| // } | ||
| // If no saved position, let browser handle it naturally | ||
| return; | ||
| } | ||
|
|
||
| // For PUSH/REPLACE navigation | ||
| const hash = decodeURIComponent(window.location.hash); | ||
|
|
||
| if (hash.length > 0) { | ||
| // Try to scroll to hash target | ||
| // Use requestAnimationFrame to ensure target element is rendered | ||
| requestAnimationFrame(() => { | ||
| scrollToHashTarget(hash); | ||
| }); | ||
| } else { | ||
| // Scroll to top for new navigation | ||
| window.scrollTo(0, 0); | ||
| } | ||
| }, [location.search, location.hash, location.pathname, navigationType]); | ||
| } | ||
|
|
||
| /** | ||
| * Scroll restoration component inspired by React Router's ScrollRestoration. | ||
| * | ||
| * This component: | ||
| * 1. Renders an inline script that restores scroll position before React hydration | ||
| * 2. Sets up scroll position saving on pagehide | ||
| * 3. Handles scroll restoration on navigation | ||
| * | ||
| * @see https://reactrouter.com/api/components/ScrollRestoration | ||
| * @private | ||
| * @unstable | ||
| */ | ||
| export function ScrollRestoration() { | ||
| useScrollRestoration(); | ||
|
|
||
| return ( | ||
| <script | ||
| // biome-ignore lint/security/noDangerouslySetInnerHtml: intentional inline script for pre-hydration scroll restoration | ||
| dangerouslySetInnerHTML={{ __html: inlineScript }} | ||
| /> | ||
| ); | ||
| } | ||
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
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.
In the inline pre-hydration script,
history.replaceState({ key }, "")overwrites the existinghistory.stateobject. React Router’s BrowserRouter/history uses additional state fields (e.g.,idx,usr) to manage navigation; clobbering them can break back/forward behavior or internal routing invariants. Preserve/merge the existinghistory.statewhen injecting a key (and keep the current URL) instead of replacing it with a minimal object.