npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@xan105/vanilla-router

v0.3.0

Published

Simple Vanilla JS router based on the Navigation API

Downloads

8

Readme

About

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.

Example

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();

Install

npm i @xan105/vanilla-router

Optional

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();

API

⚠️ This module is only available as an ECMAScript module (ESM) and is intended for the browser.

Named export

Router(option?: object): Class

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.

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.

  • 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

on(path: string | number, handler: (async)function): Router

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.

off(path: string | number): Router

Remove a route from the router.

💡 The off() method is chainable.

navigate(path?: string): void | object

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.

back(): void

Navigates backwards by one entry in the navigation history, if possible.

forward(): void

Navigates forwards by one entry in the navigation history, if possible.

listen(): Router

Start the router logic by listening to the 📖 navigate event and intercept when needed.

💡 The listen() method is chainable.

Properties

routes: string[] (read only)

The routers' routes.

current: NavigationHistoryEntry (read only)

Short hand to 📖 Navigation.currentEntry.

history: NavigationHistoryEntry[] (read only)

Short hand to 📖 Navigation.entries().