Simple Vanilla JS router based on the π Navigation API and π URLPattern API.
π¦ Scoped @xan105
packages are for my own personal use but feel free to use them.
import { Router } from "./path/to/router.js"
const router = new Router();
router
.on("/", function(event, url){
//do something
})
.on("/about", async(event, url) => {
//do something
})
//Parameterized routes
.on("/user/:id", (event, url, param) => {
const { id } = param;
//do something
})
//Optional "not found" hook
.on(404, (event, url) => {
console.error("not found !")
})
.listen();
npm i @xan105/vanilla-router
Create an importmap:
{
"imports": {
"@xan105/vanilla-router": "./path/to/node_modules/@xan105/vanilla-router/dist/router.min.js"
}
}
index.html:
<script src="./importmap.json" type="importmap"></script>
<script src="./index.js" type="module"></script>
</body>
</html>
index.js:
import { Router } from "@xan105/vanilla-router"
const router = new Router();
router
.on("/path/to/route", (event, url)=>{
//Do a flip()
})
.listen();
extends π EventTarget
Events
error({ detail: { error: string } })
This event is dispatched when an error has occured.
will-navigate({ detail: { url: URL } })
This event is dispatched when the router is about to navigate to one of its route.
did-navigate({ detail: { url: URL } })
This event is dispatched when navigation is done.
Options
autoFocus:? boolean
(true)
Defines the navigation's focus behavior (automatic or manual).
When enabled the browser will focus the first element with the autofocus attribute, or the element if no element has autofocus set.
autoScroll:? boolean
(true)
Defines the navigation's scrolling behavior (automatic or manual).
When enabled the browser will handle the scrolling for example restoring the scroll position to the same place as last time if the page is reloaded or a page in the history is revisited.
deferredCommit:? boolean
(false)
The default behavior of immediately "committing" (i.e., updating location.href and navigation.currentEntry) works well for most situations, but some may find they do not want to immediately update the URL.
When deferred commit is used, the navigation will commit when e.commit()
is called or when a route's handler fulfills / terminates and e.commit()
hasn't yet been called (fallback).
autoFire:? boolean
(true)
Triggers a navigate event for the default route /
on a page's first load.
sensitive:? boolean
(true)
Enables case-insensitive route matching when set to false
.
Methods
Add a route to the router.
A route is unique and has one handler.
Please see the π URLPattern API for possible pattern syntax.
π‘ The on()
method is chainable.
Example:
.on("/foo/bar", (event, url, param)=>{
//render logic
})
.on("/articles/:id", async(event, url, param)=>{
//render logic
})
Handler function is bind to the following arguments:
handler(event: NavigateEvent, url: URL, param: object)
event: NavigateEvent
The corresponding π NavigateEvent.
This exposes the NavigateEvent object instance and all its goodies.
For example if it makes sense to scroll earlier, you can call event.scroll()
π NavigateEvent.scroll()
url: URL
The corresponding π URL object instance.
So you have easy access to things like href, pathname, searchParams, ...
param: object
The parameterized routes have paths that contain dynamic parts ("/articles/:id").
When using parameterized route param
will expose said parameter(s) in a key/value pair.
.on("/user/:id/:action", (event, url, param)=>{
console.log(param); //{ id: "...", action: "..." }
})
Handling no route found
π‘ There is a special route 404
that you can optionally add a handler to when you need to handle cases where no match is found.
.on(404, (event, url)=>{
//no match found
})
If you do not add a handler to this special route navigation won't be intercepted.
Remove a route from the router.
π‘ The off()
method is chainable.
Navigate to the given route if it exists.
path
equals the default route /
when omitted.
If the target of the navigation is the current route it will replace the current NavigationHistoryEntry.
Returns the object of π Navigation.navigate() if a navigation occurs.
Navigates backwards by one entry in the navigation history, if possible.
Returns the object of π Navigation.navigate() if a navigation occurs.
Navigates forwards by one entry in the navigation history, if possible.
Returns the object of π Navigation.navigate() if a navigation occurs.
Start the router logic by listening to the π navigate event and intercept when needed.
π‘ The listen()
method is chainable.
Properties
The routers' routes.
Short hand to π Navigation.currentEntry.
Short hand to π Navigation.entries().