Skip to content

Commit

Permalink
Expose function to manually restore scroll state
Browse files Browse the repository at this point in the history
  • Loading branch information
nathaniel-daniel committed May 13, 2022
1 parent 916347d commit 28cb64b
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 28cb64b

Please sign in to comment.