Skip to content

t8js/router

Repository files navigation

npm Lightweight TypeScript ✓

@t8/router

Vanilla JS/TS browser history router

Installation: npm i @t8/router

Initialization

import { Route } from "@t8/router";

let route = new Route();

🔹 The new Route(location) constructor accepts an optional URL location. If omitted, it's the browser's current URL.

Navigation

- window.location.assign("/intro");
+ route.assign("/intro");

- window.location.replace("/intro");
+ route.replace("/intro");

- console.log(window.location.href);
+ console.log(route.href);

Events & Middleware

route.on("navigationstart", href => {
  if (hasUnsavedChanges)
    return false; // prevents navigation

  if (href === "/") {
    route.assign("/intro"); // redirection
    return false; // prevents navigation
  }
});
route.on("navigationcomplete", href => {
  if (href === "/intro")
    document.title = "Intro";
});

🔹 Both event handlers, acting like routing middleware, are immediately called when they are added if the route is already in the navigation-complete state.

Route matching

console.log(route.href === "/intro");
console.log(route.href.startsWith("/sections/"));
console.log(/\/sections\/\d+\/?/.test(route.href));
let { ok, params } = route.match(/^\/sections\/(?<id>\d+)\/?/);

console.log(ok, params.id);

🔹 Type-safe params can be obtained by providing a type-safe URL pattern, such as produced by url-shape, to the route.match(pattern) method.

Converting HTML links to SPA route links

route.observe(document);

The above line turns all <a> and <area> elements in the document to SPA route links enabling navigation without page reloads via the History API.

🔹 route.observe(container, elements) accepts a container element (it can be document, as in the example above) and optionally elements (which can be a selector or HTML elements).