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

mithril-hobbit-navigator

v0.3.2

Published

Component based routing using the HTML5 history API for Mithril

Downloads

6

Readme

Mithril Hobbit Navigator

NPM Version NPM License NPM Downloads

Hobbit navigator is part of the Hobbit framework for mithril. This package contains a component based routing system heavily inspired by React-router.

The router component is easy to use and extremely light - weighing less than 2KB - bringing the whole mithril package to just about 11 KB.

It does not support any JSX structure (Yet).

How to install

To install Hobbit navigator, either install the hobbit framework or this package individually through npm:

npm install --save mithril-hobbit-navigator

Hobbit navigator is also available as a UMD module in a minified or unminified format.

How to use

Hobbit navigator is component based and thus can be used at any point in the structure. This greatly simplifies the code and allows for varied rendering depending on the current URL.

import m from 'mithril';
import r from 'mithril-hobbit-navigator';

//Create the router, this must always be called before any render.
r.createRouter();

const index = {
    onClickIndex: function() {
        r.navigate('/index');
    },
    view: function() {
        return m('div.index', [
            m('h1', 'Header'),
            //Create a route
            r('/index', m('h3', 'Index')),
            m('div.footrer', [
                m('a', {onclick: this.onClickIndex}, 'Index'),
            ]),
        ]);
    },
};

m.mount(document.body.querySelector('#root'), index);

The r function creates a router where the component or vnode given will only render if the URL matches the route pattern. For example, the h3 would only render if the URL is exactly /index. r can accept either a vnode created by m or a component.

r also accepts an object of route/view pairs where only the first pair whose route matches the URL will render.

r({
    '/index': m('h3', 'Index'),
    '/admin': m('h3', 'Admin'),
})

The rendered view will always receive the current location in its vnode attributes. It can also be accessed directly with r.getLocation().

view: function(vnode) {
    //Location is under vnode.attrs.location
}

Parameters can be used in the route pattern and the parameter will be extracted if it matches. For example, /red would match '/:color' and the parameter object {color: 'red'} would be extracted. The parameters are also accessible in the vnode attributes under params.

Navigating

Navigating is done through the use of the r.navigate function, like so:

r.navigate('/route');

The function can also receive parameters if using routes pattern with parameters, for example /:color. Giving an object with the parameters names as keys will create the route with those parameters.

r.navigate('/:color', {color: 'red'});

//Will navigate to /red

404 Page

A view that always render if no other route could render can be created by giving an empty route pattern. This is useful for 404 error pages.

const 404 = ...;

r('', 404);
//Or
r([
    ['/index', m('h3', 'Index')],
    ['/admin', m('h3', 'Admin')],
    ['', 404] //Or null
])

Redraws

Hobbit navigator will only rerender when the hash part of the URL changes from a manual change by the user. All other redraws are to be handled manually through the existing auto redraw system from mithril. Remember that mithril can only redraw routes if they are mounted using m.mount().

Use with the base mithril router

Hobbit navigator can be used with the base router from mithril without conflicts and do not aim to be a replacement to the existing router system.

API

r(*)

r can accept one of two arrangements for its arguments, either r(route, view, options = {}) or r({route: view}, options = {}).

In both cases, the options object enables some configuration for the routes;

  • loose will return a match for routes that can be compared with regexes, but are not equal. For example, /foo and /foo/bar would return true with loose activated. False by default, routes must thus be an equal match to the URL.
  • caseSensitive will match routes with case sensitivity enabled. True by default.
  • strict will enfore route patterns to have a trailing slash ("/"). False by default.

r.createRouter(configuration)

r.createRouter creates the history router that handles the HTML5 history module. It can be configured through the use of the configuration argument which currently accepts the following options.

  • hashbanged is a boolean that allows the router to use a hashbang rather than the default routing system. False by default.
  • location will set the default location of the router when first created without changing the URL. This can be useful for initial redirects or SSR. Location can accept either a string for the route to use or a full location object. If not set, the router will set the initial location using the URL. Unset by default.
  • hashbangPrefix will chose the prefix to add before the routes when using the hashbanged option. By default, it will add the prefix "#!" before any route.

r.getLocation()

r.getLocation returns the current location in the router as an object with useful values.

  • path contains the path of the last navigation once transformed using parameters.
  • url is the true url that was navigated to, including any query string arguments or the hashbang prefix.
  • pattern is the route pattern that was used by the last navigation to create the path.
  • params is the parameters object that was given in the last navigation to create the path from the pattern.
  • sender is the sender of the last navigation given when using r.navigate.

r.navigate(route, params = {}, options = {})

r.navigate navigates the user to a new page using the HTML5 history module. The route argument is necessary to navigate and, if it contains any parameters, will use the parameters given in the param argument to resolve its true path. The options argument takes options similar to r and changes the way routes are handled and transformed.

  • sender set who caused the navigation and is set by the programmer. This option will appear in the location object and is unused by the system, it is however useful for custom animations.
  • force forces the navigation even if navigating to the exact same route, otherwise it will ignore any navigation to the exact same url.
  • options.replace will use the replace function from the history API rather than the set function which changes the way the back button works in browsers.

r.withLocation(pattern, component, options)

r.withLocation will decorate the given vnode component with the parameters of the given pattern and the location. This can be useful to ensure a component always has access to the parameters it should have access. For example :

const decorated = r.withLocation('/:test', {
    view: function(vnode) {
        // Here vnode.attrs contains location and params
        // params contains the value of /:test
    },
});

It also accepts an option arguments which may contains:

  • loose will return a match for routes that can be compared with regexes, but are not equal. For example, /foo and /foo/bar would return true with loose activated.
  • caseSensitive will match routes with case sensitivity enabled.
  • strict will enfore route patterns to have a trailing slash ("/").

Browsers support

Hobbit navigator supports all browsers in theory. However, browsers with no support for the HTML5 history API will experience a browser refresh on navigation, like mithril does with its own router.