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

spa-router-vir

v4.0.4

Published

The heroic, type safe, frontend router for any modern Single Page Application (SPA).

Downloads

1,404

Readme

spa-router-vir

The heroic, type safe, frontend router for any modern Single Page Application (SPA).

It works by hooking into window.history.pushState and window.history.replaceState.

Install

Install via npm:

npm i spa-router-vir

Examples

Usage

Creating a Router

Create a router by constructing SpaRouter. Ensure that you only ever have a single active router at a time. You must provide a sanitizeRoute callback for ensuring that run-time routes actually match your required route types.

Here is an example usage of SpaRouter with full run-time route type safety:

import {FullRoute, SpaRouter} from 'spa-router-vir';

export const myRouter = new SpaRouter<
    /** The allowed router paths. */
    ValidRouterPaths,
    /** This router does not allow _any_ search params. */
    undefined,
    /** This router does not allow _any_ hash string. */
    undefined
>({
    /**
     * `sanitizeRoute` is required and is the only way to ensure route type safety at run-time. This
     * ensures that all URLs navigated to from within your SPA are valid and handled by your
     * application.
     */
    sanitizeRoute(rawRoute) {
        return {
            paths: sanitizePaths(rawRoute),
            search: undefined,
            hash: undefined,
        };
    },
});

/**
 * Example valid paths that allow the following website URL paths:
 *
 * - `/home`
 * - `/gallery/<any-string>`
 * - `/about`
 * - `/about/team`
 * - `/about/website`
 */
export type ValidRouterPaths =
    | ['home']
    | ['gallery', /** Specific gallery id. */ string]
    | ['about']
    | ['about', 'team' | 'website'];

/** A helper function that specifically sanitizes the `paths` part of the route. */
export function sanitizePaths(rawRoute: Readonly<Pick<FullRoute, 'paths'>>): ValidRouterPaths {
    const topLevelPath = rawRoute.paths[0];

    if (topLevelPath === 'about') {
        if (rawRoute.paths[1] !== 'team' && rawRoute.paths[1] !== 'website') {
            return ['about'];
        } else {
            return [
                'about',
                rawRoute.paths[1],
            ];
        }
    } else if (topLevelPath === 'gallery' && rawRoute.paths[1]) {
        return [
            'gallery',
            rawRoute.paths[1],
        ];
    } else {
        /** Default to this route. */
        return ['home'];
    }
}

Supporting SPAs on GitHub Pages (or other similar services)

To use SpaRouter on GitHub Pages, you must set a basePath property when constructing SpaRouter. This ensures that your GitHub Pages repo path is maintained:

import {SpaRouter} from 'spa-router-vir';
import {ValidRouterPaths, sanitizePaths} from './router-creation.example';

export const myRouter = new SpaRouter<
    /** Use the same route type parameters as the earlier example for simplicity. */
    ValidRouterPaths,
    undefined,
    undefined
>({
    /** Sue the same route sanitizer as the earlier example for simplicity. */
    sanitizeRoute(rawRoute) {
        return {
            paths: sanitizePaths(rawRoute),
            search: undefined,
            hash: undefined,
        };
    },
    basePath: 'my-repo',
});

You can see this in action on the threejs-experiments example demo. Notice that threejs-experiments is always the first path and it does not mess up the router.

In addition to setting the router up, to get a SPA to work on GitHub Pages you need to copy paste your index.html and rename the copy to 404.html in the top-level of your GitHub Pages deployed directory. That is done in threejs-experiments as part of the deploy pipeline script.

Listening to route changes

Use listen to listen to route changes. When true, the first parameter (which is called fireImmediately) will force your router to immediately call the given listener callback. This prevents the need to manually call your own callback to update route-specific content on first page load.

import {myRouter} from './router-creation.example';

myRouter.listen(true, (routes) => {
    console.info(routes);
});

Listeners can be removed with the removeListener() method, or by calling the return value of .listen():

import {FullRoute} from 'spa-router-vir';
import {myRouter, ValidRouterPaths} from './router-creation.example';

/** Remove a listener with the removal callback. */
{
    const removeListener = myRouter.listen(true, (route) => {
        console.info(route);
    });

    removeListener();
}

/** Remove a listener by keeping track of it and passing it in to `removeListener`. */
{
    function listenToRoute(route: FullRoute<ValidRouterPaths, undefined, undefined>) {
        console.info(route);
    }

    myRouter.listen(true, listenToRoute);

    myRouter.removeListener(listenToRoute);
}

Creating a URL for links

To create a single URL string for any given route, use the createRouteUrl() method. This will create a URL that takes the SpaRouter's basePath into account, if it's provided, so you don't have to manually handle that yourself.

import {myRouter} from './router-creation.example';

document.getElementsByTagName('a')[0]!.href = myRouter.createRouteUrl({
    paths: [
        'gallery',
        'gallery-id-here',
    ],
});

Navigating Routes

To navigate to a new route, use the .setRoute() method. This will first sanitize your route, ensure that it properly includes basePath, and set it to the window URL:

import {myRouter} from './router-creation.example';

myRouter.setRoute({
    paths: [
        'gallery',
        'another-gallery-id',
    ],
});

Note that you can also use the method .setRouteOnDirectNavigation() to navigate to routes only if a given MouseEvent allows direct navigation. (Meaning, only if the user didn't try to open a link in a new tab or right click on the link.)