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

@nxcode-npm/navjs

v1.0.6

Published

Simple, lightweight, framework agnostic navigation library built on top of *Web Component and HistoryAPI standards* for Single Page Web App development. #### Features *routing*, *navigation*, *browser history management*, *parameter passing between page

Downloads

307

Readme

navjs

Simple, lightweight, framework agnostic navigation library built on top of Web Component and HistoryAPI standards for Single Page Web App development.

Features

routing, navigation, browser history management, parameter passing between pages (simulation of a query string), state object (at application and page level), load body fragments.

💡 The library is under development and testing. It is published to collect any comments, suggestions or bug reports.

Install

npm i @nxcode-npm/navjs

Router

The router is a JavaScript object literal composed of pages and paths; pages can reference one or concatenate multiple paths to assign a URL in the navigation history.
In ./src folder create the app router.

The todos page declares a path /user/agenda. On loading, the URL /user/agenda/todos will be displayed in the browser bar.

'index' must be the key of the root page

./src/appRouter.ts

enum paths  {USER="user",AGENDA="agenda"}

export const appRouter:router = {
    pages:{
        'index':{
            el:'index-page',
            params:{},
            state:{}
        },
        'home':{
            el:'home-page',
            path:paths.USER.concat('/'), // user/home
            params:{},
            state:{}
        },
        'todos':{
            el:'todos-page',
            path:paths.USER.concat('/',paths.AGENDA,'/'), // user/agenda/todos
            params:{},
            state:{}
        }
    }
}

Page components

Create Web Components to use as pages. Use standard Web ComponentAPIs or any library built on top of HTMLElement e.g. Lit.

As an example, a simple basic web component.

In the standard onclick event that I use to navigate, app refers to the global application object created by WebPack. This may be different if you use another bundler or development server.

./src/pages/index.page.ts

export class IndexPage extends HTMLElement {

    static rootEl:string = 'index'

    constructor(){
        super()
    }

    connectedCallback(){
        this.innerHTML = this.template()
    }

    template(){
    return `<header>
                <h1>Index page</h1>
            </header>
            <main>
                <p>This is the Main page. <a href="#" onclick="app.Nav({'name':'home','params':{}}); return false;">Click here</a> to go Home page.</p>
            </main>`
    }
}

App startup

./src/index.html

Create an empty HTML file as the root of the app.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
        <meta name="Description" content="">
        <base href="/">
        <title>Demo nav-js</title>
    </head>
    <body></body>
</html>

./index.js

In the app startup file you must declare the definition of the page components and then call the createApp() method passing appRouter and a root object.

import { createApp } from "@nxcode-npm/nav-js"
import { IndexPage } from "./src/pages/index.page"
import { HomePage } from "./src/pages/home.page"
import { ToDosPage } from "./src/pages/todos.page"
import { appRouter } from "./src/router"
import { Nav } from "@nxcode-npm/nav-js"
import { App } from "@nxcode-npm/nav-js/src/lib/App"

customElements.define("index-page", IndexPage)
customElements.define("home-page", HomePage)
customElements.define("todos-page", ToDosPage)

createApp({ name:'test-navjs', router: appRouter, state:{} },{ name:'index', params:{} })

export { Nav, App }

The web server loads the <index-page> template at startup. By inspecting the DOM in the browser console, can check that the page component has been added to the body.

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
        <meta name="Description" content="">
        <base href="/">
        <title>Demo nav-js</title>
    </head>
    <body>
        <test-navjs>
            <index-page>
                <!-- MainPage template -->
                <header>
                    <h1>Main page</h1>
                </header>
                <main>
                    <p>This is the Main page. <a href="#" onclick="app.Nav({'name':'home','params':{}}); return false;">Click here</a> to go Home page.</p>
                </main>
            </index-page>
        </test-navjs>    
    </body>
</html>

Navigation

To load a page call Nav passing a root. The root must implement the {name,params} interface; the name is the component key of appRouter.ts and params is a Javascript object literal.

 // Load <home-page> passing userdID as params
 import { Nav } from "@nxcode-npm/nav-js"

 Nav({name:'home',params:{userID:'ABC123'}})
<!-- standard HTML -->
<script>
    function goTo(rootName, params_){
        app.Nav({name:rootName, params: params_})
    }
</script>

Read parameters from root

import { Router } from "@nxcode-npm/nav-js"
import { route } from "@nxcode-npm/nav-js/src/lib/Router"

const route_:route = Router('home')
const userID:string = route_.params['userID']

State

In some cases there is a need to save the state of the page (for example when the user is filling out a form and browsing back and forward). For example, the code below saves in the page state the user name chosen by the user.

Page state

import { Router } from "@nxcode-npm/nav-js"
import { route } from "@nxcode-npm/nav-js/src/lib/Router"

const route_:route = Router('home')
// Save the name chosen by the user in the page state
route_.state['name'] = (<HTMLInputElement>document.querySelector('#input-name')).value as string

If the page is reloaded from a forward or backward with the browser (or in any case until the route parameters are changed or cleaned up) can read the name from the state to initialize the #input-name value.

import { Router } from "@nxcode-npm/nav-js"
import { route } from "@nxcode-npm/nav-js/src/lib/Router"

export class FormPage1 extends HTMLElement {

    static rootName:string = 'form-page1'
    name:string

    constructor(){
        super()
        this.name = Router('form-page1').state['name']

    //...
}

App state

The app state is a Javascript object literal {[key:string]:any} where properties ( from simple to static objects to be used as global services ) are persistently stored and can be read or written anywhere in the app.

./src/services/user.service.ts

//UserService
export class UserService {
    static userName
}

./index.js

import { UserService } from "..."

//Inject UserService into app state.
const appState = { 'user': UserService }

createApp({ name:'test-navjs', router: appRouter, state:appState },{ name:'main', params:{} })
// Set user name
App.app.state['user'].userName = 'NavJS'
// Get user name
const userName:string = App.app.state['user'].userName

Render fragment

Sometimes you don't need to load the entire page but only a part (for example keep the <header> navigation bar and load only in the <main>). In this case I can avoid reloading the header navigation bar.

Navigation

To load a page in a portion of the document instead of reloading the entire body, pass 2 additional parameters to the Nav; the first always true; the second the HTMLElement container.

// From agenda.page.ts
// Load <todos-page> in <main>. This will not reload <nav>.
Nav({name:'todos',params:{}}, true, document.querySelector('main'));

root container

In the router, define an agenda page and 2 subpages that share a path and set the container prop. In this way, even back or forward actions made with the browser load the page in the indicated CSS selector without reloading, for example, the navigation bar.

import { router } from "../../dev/src/lib/Router"

enum paths {USER="user", AGENDA="agenda"}

export const appRouter:router = { 
    pages:{
        'agenda':{
            el:'agenda-page',
            path:paths.USER.concat('/'),
            params:{},
            state:{}
        },
        'todos':{
            el:'todos-page',
            path:paths.USER.concat('/', paths.AGENDA, '/'),
            container:'main',
            params:{},
            state:{}
        },
        'calendar':{
            el:'calendar-page',
            path:paths.USER.concat('/', paths.AGENDA, '/'),
            container:'main',
            params:{},
            state:{}
        }       
    }
}

Templates

agenda.page.ts

<!-- user/agenda/ -->
<header>
    <nav>
        <a href="#" onclick="nav.Nav({'name':'index','params':{}});return false;">Logout</a> | 
        <a href="#" onclick="nav.Nav({'name':'home','params':{}});return false;" >Home</a> | 
        <a href="#" onclick="nav.Nav({'name':'todos','params':{}}, true, document.querySelector('main'));return false;" >Todos</a> | 
        <a href="#" onclick="nav.Nav({'name':'calendar','params':{}}, true, document.querySelector('main'));return false;" >Calendar</a>
    </nav>
</header>
<main>
    <h2>Agenda page</h2>
        <p><i>&lt;todos-main&gt;</i> and </i>&lt;calendar-main&gt;</i> share the same nav within <i>&lt;agenda-page&gt;</i>. See docs on npm for more details and examples.</p>
</main>

todos.page.ts

<!-- /user/agenda/todos/ -->
<section>
    <h2>Todos page</h2>
</section>

calendar.page.ts

<!-- /user/agenda/calendar/ -->
<section>
    <h2>Calendar page</h2>
</section>

Custom root name

By default the name assigned to the page in the URL is the route key; to replace it with a different name set the name parameter in the route.


enum paths {USER="user", AGENDA="agenda"}

export const appRouter:router = { 
    
    pages:{
        'agenda':{
            el:'agenda-page',
            path:paths.USER.concat('/'),
            params:{},
            state:{},
            name:'thatsAgenda'// Nav({name:'agenda',params:{}}) => ./user/thasAgenda
        },
    }
}