Skip to content

Commit

Permalink
feat(scroll): handle scroll on popstate
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Apr 15, 2020
1 parent 539c742 commit 181efe9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import {
ScrollToPosition,
ScrollPosition,
scrollToPosition,
saveScrollOnLeave,
getScrollKey,
getSavedScroll,
} from './utils/scroll'
import { createRouterMatcher } from './matcher'
import { createRouterError, ErrorTypes, NavigationError } from './errors'
Expand Down Expand Up @@ -420,9 +423,12 @@ export function createRouter({
// TODO: this doesn't work on first load. Moving it to RouterView could allow automatically handling transitions too maybe
// TODO: refactor with a state getter
const state = isPush || !isClient ? {} : window.history.state
handleScroll(toLocation, from, state && state.scroll).catch(err =>
triggerError(err, false)
)
const savedScroll = getSavedScroll(getScrollKey(toLocation.fullPath, 0))
handleScroll(
toLocation,
from,
savedScroll || (state && state.scroll)
).catch(err => triggerError(err, false))

// navigation is confirmed, call afterGuards
for (const guard of afterGuards.list()) guard(toLocation, from)
Expand All @@ -439,6 +445,8 @@ export function createRouter({
pendingLocation = toLocation
const from = currentRoute.value

saveScrollOnLeave(getScrollKey(from.fullPath, info.distance))

try {
await navigate(toLocation, from)
finalizeNavigation(
Expand Down
21 changes: 21 additions & 0 deletions src/utils/scroll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,24 @@ export function scrollToPosition(position: ScrollPosition): void {
window.scrollTo(normalizedPosition.x, normalizedPosition.y)
}
}

/**
* TODO: refactor the scroll behavior so it can be tree shaken
*/

export const scrollPositions = new Map<string, ScrollToPosition>()

export function getScrollKey(path: string, distance: number): string {
const position: number = history.state
? history.state.position - distance
: -1
return position + path
}

export function saveScrollOnLeave(key: string) {
scrollPositions.set(key, computeScrollPosition())
}

export function getSavedScroll(key: string) {
return scrollPositions.get(key)
}

0 comments on commit 181efe9

Please sign in to comment.