🐉 Dragon Router
Kyle West's JavaScript Master Project
Why make a router?
Don't those already exist?
Neither app-route or PageJS could do this:
History API
The backbone of SPA
window.history
pop
Browser Back/Fwd
push
Navigation Evt
window.history
Navigation Evt
Browser Back/Fwd
// "push" a new entry onto the history stack
history.pushState({ data }, "Page Title", "/page")
// edits "top" entry in history stack
history.replaceState({ data }, "Page 2", "/page")
// "pops" to an entry in the history stack
history.back()
hisory.forward()
history.go(-1)
push
pop
window.addEventListener('pop', (e) => {
if (e.state) { // truthy only thru History API
handleRoute(e.state)
}
// else - default behavior
})
window.addEventListener('pop', (e) => {
// only handle route if we were the ones who owned it
if (e.state && e.state.routerId === this.routerId) {
handleRoute(e.state)
}
})
Is that it?
// Missing PID & Orientation
page('/pedigree', () => {
/* redirect to /pedigree/:defaultOrientation */
});
// Missing Orientation
page(`/pedigree/:pid(<PID-RegExp>)`, () => {
/* redirect to /pedigree/:defaultOrientation/:pid */
});
// Missing PID
page(`/pedigree/:orientation(<Orientation-RegExp>)`, () => {
/* redirect to /pedigree/:orientation/:startingPid */
});
// handle the fully qualified /:view/:orientation/:pid route
page(`/pedigree/:orientation(<Orientation-RegExp>)/:pid(<PID-RegExp>)`,
() => { /* ... */})
// fetch our default values in a callback
router.use(new DerivedSubpath('orientation', () => 'landscape'));
router.use(new DerivedSubpath('pid', async () => 'STRT-PID'));
// handle the fully qualified /:view/:orientation/:pid route
router.use(`/pedigree/$:orientation(<Orientation-RegExp>)/$:pid(<PID-RegExp>)`,
() => { /* ... */})
What else?
Niceties
- Built in debug mode
- DerivedSubpaths
- Composable exports
- 40% size of PageJS
Compatibility
- ?, *, [], and regex routes
- global/local middleware
- Works with WebComps
- Works with React
- ES6+ Importable
- ES2015 & Global Scope
🖥 DEMO
Dragon Router
By Kyle West
Dragon Router
This is the presentation for my Skill Building JavaScript Master Badge Project.
- 140