Last active
May 23, 2023 08:54
-
-
Save lukaskleinschmidt/f1c6a6bebb7bb131604f1884d4b2a6e0 to your computer and use it in GitHub Desktop.
Determine history direction in barba.js
This file contains hidden or 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 hidden or 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