Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions packages/core/src/theme/components/DocContent/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
import { MDXProvider } from '@mdx-js/react';
import { Content, usePage, useSite } from '@rspress/core/runtime';
import {
Callout,
FallbackHeading,
getCustomMDXComponent,
useScrollAfterNav,
} from '@theme';
import { Callout, FallbackHeading, getCustomMDXComponent } from '@theme';
import './doc.scss';

function FallbackTitle() {
Expand Down Expand Up @@ -38,8 +33,6 @@ export function DocContent({
*/
afterDocContent?: React.ReactNode;
}) {
useScrollAfterNav();

const mdxComponents = {
...getCustomMDXComponent(),
...components,
Expand Down
3 changes: 1 addition & 2 deletions packages/core/src/theme/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,10 @@ export { Layout, type LayoutProps } from './layout/Layout/index';
export { NotFoundLayout } from './layout/NotFountLayout/index';
// logic
export { mergeRefs } from './logic/mergeRefs';
export { ScrollRestoration } from './logic/ScrollRestoration';
export { useFullTextSearch } from './logic/useFullTextSearch';
export { usePrevNextPage } from './logic/usePrevNextPage';
export { useRedirect4FirstVisit } from './logic/useRedirect4FirstVisit';
export { useScrollAfterNav } from './logic/useScrollAfterNav';
export { useScrollReset } from './logic/useScrollReset';
export { useSetup } from './logic/useSetup';
export { useStorageValue } from './logic/useStorageValue';
export { useThemeState } from './logic/useThemeState';
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/theme/layout/Layout/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import {
type DocLayoutProps,
Nav,
type NavProps,
ScrollRestoration,
useRedirect4FirstVisit,
useScrollReset,
useSetup,
} from '@theme';
import { Head, useHead } from '@unhead/react';
Expand Down Expand Up @@ -203,7 +203,6 @@ export function Layout(props: LayoutProps) {
}

useSetup();
useScrollReset();
useRedirect4FirstVisit();

const {
Expand Down Expand Up @@ -236,6 +235,7 @@ export function Layout(props: LayoutProps) {

{getContentLayout()}
{bottom}
<ScrollRestoration />
</>
);
}
196 changes: 196 additions & 0 deletions packages/core/src/theme/logic/ScrollRestoration.tsx
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 }, "");
}
Comment on lines +87 to +90
Copy link

Copilot AI Feb 26, 2026

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 existing history.state object. 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 existing history.state when injecting a key (and keep the current URL) instead of replacing it with a minimal object.

Copilot uses AI. Check for mistakes.

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 }}
/>
);
}
64 changes: 0 additions & 64 deletions packages/core/src/theme/logic/useScrollAfterNav.ts

This file was deleted.

18 changes: 0 additions & 18 deletions packages/core/src/theme/logic/useScrollReset.ts

This file was deleted.

Loading