Skip to content

Commit

Permalink
Merge pull request #264 from nathaniel-daniel/restore-scroll
Browse files Browse the repository at this point in the history
Expose function to manually restore scroll state
  • Loading branch information
ItalyPaleAle authored Aug 7, 2022
2 parents e076e76 + 28cb64b commit 4f78f92
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions Router.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,22 @@ export function link(node, opts) {
}
}
/**
* Tries to restore the scroll state from the given history state.
*
* @param {object} state - The history state to restore from.
*/
export function restoreScroll(state) {
// If this exists, then this is a back navigation: restore the scroll position
if (state) {
window.scrollTo(state.__svelte_spa_router_scrollX, state.__svelte_spa_router_scrollY)
}
else {
// Otherwise this is a forward navigation: scroll to top
window.scrollTo(0, 0)
}
}
// Internal function used by the link function
function updateLink(node, opts) {
let href = opts.href || node.getAttribute('href')
Expand Down Expand Up @@ -470,14 +486,7 @@ if (restoreScrollState) {
window.addEventListener('popstate', popStateChanged)
afterUpdate(() => {
// If this exists, then this is a back navigation: restore the scroll position
if (previousScrollState) {
window.scrollTo(previousScrollState.__svelte_spa_router_scrollX, previousScrollState.__svelte_spa_router_scrollY)
}
else {
// Otherwise this is a forward navigation: scroll to top
window.scrollTo(0, 0)
}
restoreScroll(previousScrollState);
})
}
Expand Down

0 comments on commit 4f78f92

Please sign in to comment.