Created
August 9, 2020 11:08
-
-
Save prionkor/59215ff78de7b706fbb6b97a9a61b578 to your computer and use it in GitHub Desktop.
Hash Source for reach/router
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
"use strict"; | |
const getHashPath = () => { | |
const href = window.location.href; | |
const hashIndex = href.indexOf('#'); | |
return hashIndex === -1 ? '' : href.substring(hashIndex + 1); | |
}; | |
const pushHashPath = path => window.location.hash = path; | |
const replaceHashPath = path => { | |
const hashIndex = window.location.href.indexOf('#'); | |
window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + '#' + path); | |
}; | |
const getState = path => { | |
const pathname = path ? path : getHashPath(); | |
return { pathname, search: ''} | |
} | |
const resolveInitialState = state => { | |
if (state.pathname === '') { | |
replaceHashPath('/'); | |
} | |
}; | |
const createHashSource = () => { | |
const state = getState(); | |
resolveInitialState(state); | |
return { | |
get location() { | |
return getState(); | |
}, | |
addEventListener: function (name, fn) { | |
window.addEventListener(name, fn); | |
}, | |
removeEventListener: function (name, fn) { | |
window.removeEventListener(name, fn); | |
}, | |
history: { | |
state, | |
pushState: function (stateObj, _, uri) { | |
this.state = {...(this.state || {}), ...stateObj} | |
pushHashPath(uri); | |
}, | |
replaceState: function (stateObj, _, uri) { | |
this.state = {...stateObj} | |
replaceHashPath(uri); | |
}, | |
}, | |
}; | |
}; | |
export default createHashSource; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment