Skip to content

Commit

Permalink
Merge pull request #197 from orange4glace/fix-no-history-override
Browse files Browse the repository at this point in the history
fix: #192 no override history state
  • Loading branch information
ItalyPaleAle authored Mar 2, 2021
2 parents 403cd07 + 2f485d6 commit ab03300
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions Router.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export async function push(location) {
await tick()
// Note: this will include scroll state in history even when restoreScrollState is false
history.replaceState({scrollX: window.scrollX, scrollY: window.scrollY}, undefined, undefined)
history.replaceState({...history.state, __svelte_spa_router_scrollX: window.scrollX, __svelte_spa_router_scrollY: window.scrollY}, undefined, undefined)
window.location.hash = (location.charAt(0) == '#' ? '' : '#') + location
}
Expand Down Expand Up @@ -132,7 +132,12 @@ export async function replace(location) {
const dest = (location.charAt(0) == '#' ? '' : '#') + location
try {
window.history.replaceState(undefined, undefined, dest)
const newState = {
...history.state
}
delete newState['__svelte_spa_router_scrollX']
delete newState['__svelte_spa_router_scrollY']
window.history.replaceState(newState, undefined, dest)
}
catch (e) {
// eslint-disable-next-line no-console
Expand Down Expand Up @@ -193,7 +198,7 @@ function scrollstateHistoryHandler(event) {
event.preventDefault()
const href = event.currentTarget.getAttribute('href')
// Setting the url (3rd arg) to href will break clicking for reasons, so don't try to do that
history.replaceState({scrollX: window.scrollX, scrollY: window.scrollY}, undefined, undefined)
history.replaceState({...history.state, __svelte_spa_router_scrollX: window.scrollX, __svelte_spa_router_scrollY: window.scrollY}, undefined, undefined)
// This will force an update as desired, but this time our scroll state will be attached
window.location.hash = href
}
Expand Down Expand Up @@ -417,7 +422,7 @@ if (restoreScrollState) {
// If this event was from our history.replaceState, event.state will contain
// our scroll history. Otherwise, event.state will be null (like on forward
// navigation)
if (event.state && event.state.scrollY) {
if (event.state && event.state.__svelte_spa_router_scrollY) {
previousScrollState = event.state
}
else {
Expand All @@ -428,7 +433,7 @@ if (restoreScrollState) {
afterUpdate(() => {
// If this exists, then this is a back navigation: restore the scroll position
if (previousScrollState) {
window.scrollTo(previousScrollState.scrollX, previousScrollState.scrollY)
window.scrollTo(previousScrollState.__svelte_spa_router_scrollX, previousScrollState.__svelte_spa_router_scrollY)
}
else {
// Otherwise this is a forward navigation: scroll to top
Expand Down

0 comments on commit ab03300

Please sign in to comment.