Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP-PoC] [added] useScrollToTopBehavior #2471

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions modules/useScrollToTopBehavior.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { setWindowScrollPosition } from './DOMUtils'

export default function useScrollToTopBehavior(createHistory) {
return function (options) {
const history = createHistory(options)

history.listen(() => {
// Need to defer this to after other listeners fire in case some of them
// update the page.
setTimeout(() => setWindowScrollPosition(0, 0))
})

return history
}
}
62 changes: 62 additions & 0 deletions modules/useStandardScrollBehavior.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { readState, saveState } from 'history/lib/DOMStateStorage'
import { addEventListener, getWindowScrollPosition, setWindowScrollPosition }
from './DOMUtils'

export default function useStandardScrollBehavior(createHistory) {
return function (options) {
const history = createHistory(options)

let currentLocation
let savePositionHandle = null

addEventListener(window, 'scroll', () => {
if (savePositionHandle !== null) {
clearTimeout(savePositionHandle)
}

savePositionHandle = setTimeout(() => {
savePositionHandle = null

if (!currentLocation) {
return
}
const { key } = currentLocation

const state = readState(key)
saveState(key, {
...state, scrollPosition: getWindowScrollPosition()
})
})
})

history.listenBefore(() => {
if (savePositionHandle !== null) {
clearTimeout(savePositionHandle)
savePositionHandle = null
}
})

function getScrollPosition() {
const state = readState(currentLocation.key)
if (!state) {
return null
}

return state.scrollPosition
}

history.listen(location => {
currentLocation = location

const scrollPosition = getScrollPosition() || {}
const { x = 0, y = 0 } = scrollPosition

// Need to defer the scroll operation because this listener fires before
// e.g. the router updates its state, and this might need to scroll past
// the end of the page pre-transition if the popped page was longer.
setTimeout(() => setWindowScrollPosition(x, y))
})

return history
}
}