Skip to content

Instantly share code, notes, and snippets.

@prionkor
Created August 9, 2020 11:08
Show Gist options
  • Save prionkor/59215ff78de7b706fbb6b97a9a61b578 to your computer and use it in GitHub Desktop.
Save prionkor/59215ff78de7b706fbb6b97a9a61b578 to your computer and use it in GitHub Desktop.
Hash Source for reach/router
"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