Skip to content
This repository has been archived by the owner on Jul 28, 2018. It is now read-only.

Commit

Permalink
Scroll to top on transition cache hit
Browse files Browse the repository at this point in the history
  • Loading branch information
Thibaut committed May 10, 2015
1 parent 6cadc8d commit bc30b17
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
15 changes: 9 additions & 6 deletions lib/assets/javascripts/turbolinks.js.coffee
Expand Up @@ -30,12 +30,12 @@ fetch = (url, options = {}) ->
progressBar?.start()

if transitionCacheEnabled and cachedPage = transitionCacheFor(url.absolute)
fetchHistory cachedPage
fetchHistory cachedPage, recallScrollPosition: false
options.showProgressBar = false
fetchReplacement url, options
else
options.onLoadFunction = resetScrollPosition unless options.change
fetchReplacement url, options

fetchReplacement url, options

transitionCacheFor = (url) ->
cachedPage = pageCache[url]
Expand Down Expand Up @@ -89,11 +89,14 @@ fetchReplacement = (url, options) ->

xhr.send()

fetchHistory = (cachedPage) ->
fetchHistory = (cachedPage, options) ->
xhr?.abort()
changePage createDocument(cachedPage.body), title: cachedPage.title, runScripts: false
progressBar?.done()
recallScrollPosition cachedPage
if options.recallScrollPosition
recallScrollPosition cachedPage
else
resetScrollPosition()
triggerEvent EVENTS.RESTORE

cacheCurrentPage = ->
Expand Down Expand Up @@ -587,7 +590,7 @@ onHistoryChange = (event) ->
if event.state?.turbolinks && event.state.url != currentState.url
if cachedPage = pageCache[(new ComponentUrl(event.state.url)).absolute]
cacheCurrentPage()
fetchHistory cachedPage
fetchHistory cachedPage, recallScrollPosition: true
else
visit event.target.location.href

Expand Down
22 changes: 22 additions & 0 deletions test/javascript/turbolinks_visit_test.coffee
Expand Up @@ -259,6 +259,28 @@ suite 'Turbolinks.visit()', ->
@Turbolinks.pagesCached(0)
@Turbolinks.visit('iframe2.html')

test "scrolls to top on transition cache hit", (done) ->
load = 0
restoreCalled = false
@document.addEventListener 'page:load', =>
load += 1
if load is 1
@window.scrollTo(8, 8)
setTimeout (=> @Turbolinks.visit('iframe.html')), 0
else if load is 2
assert.ok restoreCalled
assert.equal @window.pageXOffset, 16
assert.equal @window.pageYOffset, 16
done()
@document.addEventListener 'page:restore', =>
assert.equal @window.pageXOffset, 0
assert.equal @window.pageYOffset, 0
@window.scrollTo(16, 16)
restoreCalled = true
@window.scrollTo(4, 4)
@Turbolinks.enableTransitionCache()
@Turbolinks.visit('iframe2.html')

test "doesn't scroll to top with :change", (done) ->
@window.scrollTo(42, 42)
@document.addEventListener 'page:load', =>
Expand Down

0 comments on commit bc30b17

Please sign in to comment.