Skip to content

Instantly share code, notes, and snippets.

@dontwork
Created May 8, 2020 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dontwork/515fc3d7db599db7dc1dbe53465c0fc8 to your computer and use it in GitHub Desktop.
Save dontwork/515fc3d7db599db7dc1dbe53465c0fc8 to your computer and use it in GitHub Desktop.
router
import createRouteMatcher from 'feather-route-matcher'
const createRouter = routeConfig => {
const prefix = window.location.protocol + '//' + window.location.host
const getPath = () => {
return decodeURI(window.location.href).substring(prefix.length) || '/'
}
const routeMatcher = createRouteMatcher(routeConfig)
const initialRoute = routeMatcher(getPath())
const pathLookup = Object.entries(routeConfig).reduce(
(result, [path, route]) => {
return Object.assign(result, { [route.value]: path })
},
{}
)
const toPath = (id, params = {}) => {
const path = pathLookup[id]
return [...path.matchAll(/(:[^/]*)/g)]
.map(a => a[1])
.reduce(
(result, pathParam) => {
return result.replace(new RegExp(pathParam), encodeURI(params[pathParam.substring(1)]))
},
path
)
}
const getRoute = (id, params) => {
return routeMatcher(toPath(id, params))
}
const getHref = (id, params) => {
const url = toPath(id, params)
return {
href: url,
onclick: evt => {
evt.preventDefault()
window.history.pushState({}, '', url)
window.onpopstate()
}
}
}
const start = ({ navigateTo }) => {
window.onpopstate = () => {
navigateTo(routeMatcher(getPath()))
}
}
const locationBarSync = route => {
const path = route.url
if (getPath() !== path) {
window.history.pushState({}, '', prefix + path)
}
}
return { initialRoute, routeMatcher, getHref, start, toPath, locationBarSync, getRoute }
}
export const Route = {
Home: 'Home',
Login: 'Login',
Register: 'Register',
Dashboard: 'Dashboard',
NotFound: 'NotFound'
}
const routeConfig = {
'/': Route.Home,
'/login': Route.Login,
'/register': Route.Register,
'/dashboard': Route.Dashboard,
'/:404': Route.NotFound
}
export const router = createRouter(routeConfig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment