Skip to content

Commit

Permalink
fix: scroll back to top on navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
quentinderoubaix committed Feb 1, 2024
1 parent 887f3d8 commit 9ca108f
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions demo/src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import './bs-customTheme.scss';
import {/*canonicalURL$,*/ pathToRoot$, routeLevel$} from '$lib/stores';
import './styles.scss';
import {beforeNavigate, onNavigate} from '$app/navigation';
import {afterNavigate, beforeNavigate, onNavigate} from '$app/navigation';
import {page, updated} from '$app/stores';
import {onMount} from 'svelte';
import MobileSubMenu from './menu/MobileSubMenu.svelte';
Expand All @@ -14,6 +14,7 @@
import SideMenu from './menu/SideMenu.svelte';
import TOC from './menu/TOC.svelte';
import agnosUILogo from '$resources/agnosui-logo.svg?raw';
import type {Snapshot} from '@sveltejs/kit';
const onServiceWorkerUpdate = () => {
void updated.check();
Expand Down Expand Up @@ -43,6 +44,24 @@
});
});
});
let container: HTMLElement;
const regexFwkSubPath = /\/docs\/(angular|react|svelte)\/([^#?]*)([#?].*)?$/;
afterNavigate((navigation) => {
if (!navigation.to?.url?.hash) {
const toFwkSubPath = navigation.to?.url?.href?.match(regexFwkSubPath)?.[2] as string | undefined;
const fromFwkSubPath = navigation.from?.url?.href?.match(regexFwkSubPath)?.[2] as string | undefined;
if (!toFwkSubPath || !fromFwkSubPath || toFwkSubPath !== fromFwkSubPath) {
container.scrollTo(0, 0);
}
}
});
export const snapshot: Snapshot<number> = {
capture: () => container.scrollTop,
restore: (y) => container.scrollTo(0, y),
};
</script>

<!-- TODO: add canonical URL when noindex is removed
Expand Down Expand Up @@ -82,7 +101,7 @@
</div>
</div>
</nav>
<div class="demo-main d-flex flex-column">
<div class="demo-main d-flex flex-column" bind:this={container}>
{#if isMainPage}
<slot />
{:else}
Expand Down Expand Up @@ -150,6 +169,9 @@
grid-area: main;
overflow: auto;
scrollbar-gutter: stable;
@media (max-width: 991px) {
scroll-padding-top: 43px;
}
}
.demo-sidebar {
Expand Down

0 comments on commit 9ca108f

Please sign in to comment.