Skip to content
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

fix: avoid flash of page scrolling to top on refresh #7342

Merged
merged 1 commit into from
May 5, 2022
Merged
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
20 changes: 13 additions & 7 deletions packages/docusaurus/src/client/ClientLifecyclesDispatcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ export function dispatchLifecycleAction<K extends keyof ClientModule>(
return () => callbacks.forEach((cb) => cb?.());
}

function scrollAfterNavigation(location: Location) {
const {hash} = location;
if (!hash) {
window.scrollTo(0, 0);
} else {
const id = decodeURIComponent(hash.substring(1));
const element = document.getElementById(id);
element?.scrollIntoView();
}
}

function ClientLifecyclesDispatcher({
children,
location,
Expand All @@ -38,13 +49,8 @@ function ClientLifecyclesDispatcher({
}): JSX.Element {
useLayoutEffect(() => {
if (previousLocation !== location) {
const {hash} = location;
if (!hash) {
window.scrollTo(0, 0);
} else {
const id = decodeURIComponent(hash.substring(1));
const element = document.getElementById(id);
element?.scrollIntoView();
if (previousLocation) {
scrollAfterNavigation(location);
}
dispatchLifecycleAction('onRouteDidUpdate', {previousLocation, location});
}
Expand Down