-
-
Save mfrancois3k/474adfaf3b6185ff22a3e824f63f252c to your computer and use it in GitHub Desktop.
barba.js history direction url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import History from './history'; | |
import Barba from 'barba.js'; | |
const history = new History(); | |
Barba.Pjax.goTo = function(url) { | |
history.goTo(url); | |
this.onStateChange(); | |
}; | |
Barba.Pjax.getTransition = function() { | |
// store scroll position to previous state | |
// to make it accessible in the transition | |
// and react to it if necessary | |
history.setPrev('scrollY', window.scrollY); | |
console.log(history.direction()); | |
if(history.direction() === 'forward') { | |
// return forward transition | |
} else { | |
// return back transition | |
} | |
}; | |
export default Barba; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import set from 'lodash/set'; | |
import get from 'lodash/get'; | |
export default class History { | |
constructor() { | |
this.forward = 'forward'; | |
this.back = 'back'; | |
if(window.history.state === null) { | |
const state = sessionStorage.getItem('history') || 0; | |
window.history.replaceState(parseInt(state), null, window.location); | |
} | |
this.prevState = 0; | |
this.state = window.history.state; | |
window.addEventListener('popstate', event => { | |
sessionStorage.setItem('history', event.state); | |
this.prevState = this.state; | |
this.state = event.state; | |
}); | |
} | |
goTo(url) { | |
this.prevState = this.state; | |
this.state = window.history.state + 1; | |
window.history.pushState(this.state, null, url); | |
} | |
direction() { | |
return this.state <= this.prevState ? this.back : this.forward; | |
} | |
setSessionData(data = {}) { | |
sessionStorage.setItem('historyData', JSON.stringify(data)); | |
} | |
getSessionData() { | |
const data = sessionStorage.getItem('historyData') || null; | |
if(data === null) return {}; | |
return JSON.parse(data); | |
} | |
set(key, value) { | |
this.setSessionData(set(this.getSessionData(), this.state + '.' + key, value)); | |
} | |
setPrev(key, value) { | |
this.setSessionData(set(this.getSessionData(), this.prevState + '.' + key, value)); | |
} | |
get(key, defaultValue = null) { | |
return get(this.getSessionData(), this.state + '.' + key, defaultValue); | |
} | |
getPrev(key, defaultValue = null) { | |
return get(this.getSessionData(), this.prevState + '.' + key, defaultValue); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment