• Stars
    star
    762
  • Rank 59,405 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A navigation aid (aka, router) for the browser in 850 bytes~!
navaid
A navigation aid (aka, router) for the browser in 865 bytes~!

Install

$ npm install --save navaid

Usage

const navaid = require('navaid');

// Setup router
let router = navaid();
// or: new Navaid();

// Attach routes
router
  .on('/', () => {
    console.log('~> /');
  })
  .on('/users/:username', params => {
    console.log('~> /users/:username', params);
  })
  .on('/books/*', params => {
    console.log('~> /books/*', params);
  });

// Run as single instance
router.run('/');
//=> "~> /"
router.run('/users/lukeed');
//=> "~> /users/:username { username: 'lukeed' }"
router.run('/books/kids/narnia');
//=> "~> /books/* { wild: 'kids/narnia' }"

// Run as long-lived router w/ history & "<a>" bindings
// Also immediately calls `run()` handler for current location
router.listen();

API

navaid(base, on404)

Returns: Navaid

base

Type: String
Default: '/'

The base pathname for your application. By default, Navaid assumes it's operating on the root.

All routes will be processed relative to this path (see on()). Similarly, while listening, Navaid will not intercept any links that don't lead with this base pathname.

Note: Navaid will accept a base with or without a leading and/or trailing slash, as all cases are handled identically.

on404

Type: Function
Default: undefined

The function to run if the incoming pathname did not match any of your defined defined patterns.
When defined, this function will receive the formatted uri as its only parameter; see format().

Important: Navaid only processes routes that match your base path!
Put differently, on404 will never run for URLs that do not begin with base.
This allows you to mount multiple Navaid instances on the same page, each with different base paths. 😉

format(uri)

Returns: String or false

Formats and returns a pathname relative to the base path.

If the uri does not begin with the base, then false will be returned instead.
Otherwise, the return value will always lead with a slash (/).

Note: This is called automatically within the listen() and run() methods.

uri

Type: String

The path to format.

Note: Much like base, paths with or without leading and trailing slashes are handled identically.

route(uri, replace)

Returns: undefined

Programmatically route to a path whilst modifying & using the history events.

uri

Type: String

The desired path to navigate.

Important: Navaid will prefix your uri with the base, if/when defined.

replace

Type: Boolean
Default: false

If true, then history.replaceState will be used. Otherwise history.pushState will be used.

This is generally used for redirects; for example, redirecting a user away from a login page if they're already logged in.

on(pattern, handler)

Returns: Navaid

Define a function handler to run when a route matches the given pattern string.

pattern

Type: String

The supported pattern types are:

  • static (/users)
  • named parameters (/users/:id)
  • nested parameters (/users/:id/books/:title)
  • optional parameters (/users/:id?/books/:title?)
  • any match / wildcards (/users/*)

Note: It does not matter if your pattern begins with a / — it will be added if missing.

handler

Type: Function

The function to run when its pattern is matched.

Note: This can also be a Promise or async function, but it's up to you to handle its result/error.

For patterns with named parameters and/or wildcards, the handler will receive an "params" object containing the parsed values.

When wildcards are used, the "params" object will fill a wild key with the URL segment(s) that match from that point & onward.

let r = new Navaid();

r.on('/users/:id', console.log).run('/users/lukeed');
//=> { id: 'lukeed' }

r.on('/users/:id/books/:title?', console.log).run('/users/lukeed/books/narnia');
//=> { id: 'lukeed', title: 'narnia' }

r.on('/users/:id/jobs/*').run('/users/lukeed/jobs/foo/bar/baz/bat');
//=> { id: 'lukeed', wild: 'foo/bar/baz/bat' }

run(uri)

Returns: Navaid

Executes the matching handler for the specified path.

Unlike route(), this does not pass through the history state nor emit any events.

Note: You'll generally want to use listen() instead, but run() may be useful in Node.js/SSR contexts.

uri

Type: String
Default: location.pathname

The pathname to process. Its matching handler (as defined by on()) will be executed.

listen(uri?)

Returns: Navaid

Attaches global listeners to synchronize your router with URL changes, which allows Navaid to respond consistently to your browser's BACK and FORWARD buttons.

These are the (global) events that Navaid creates and/or responds to:

  • popstate
  • replacestate
  • pushstate

Navaid will also bind to any click event(s) on anchor tags (<a href="" />) so long as the link has a valid href that matches the base path. Navaid will not intercept links that have any target attribute or if the link was clicked with a special modifier (eg; ALT, SHIFT, CMD, or CTRL).

uri

Type: String
Default: undefined

(Optional) Any value passed to listen() will be forwarded to the underlying run() call.
When not defined, run() will read the current location.pathname value.

unlisten()

Returns: undefined

Detach all listeners initialized by listen().

Note: This method is only available after listen() has been invoked.

License

MIT © Luke Edwards

More Repositories

1

clsx

A tiny (239B) utility for constructing `className` strings conditionally.
JavaScript
7,819
star
2

polka

A micro web server so fast, it'll make you dance! 👯
JavaScript
5,266
star
3

pwa

(WIP) Universal PWA Builder
JavaScript
3,124
star
4

uvu

uvu is an extremely fast and lightweight test runner for Node.js and the browser
JavaScript
2,958
star
5

taskr

A fast, concurrency-focused task automation tool.
JavaScript
2,528
star
6

sockette

The cutest little WebSocket wrapper! 🧦
JavaScript
2,398
star
7

worktop

The next generation web framework for Cloudflare Workers
TypeScript
1,644
star
8

kleur

The fastest Node.js library for formatting terminal text with ANSI colors~!
JavaScript
1,599
star
9

klona

A tiny (240B to 501B) and fast utility to "deep clone" Objects, Arrays, Dates, RegExps, and more!
JavaScript
1,563
star
10

dequal

A tiny (304B to 489B) utility to check for deep equality
JavaScript
1,335
star
11

tsm

TypeScript Module Loader
TypeScript
1,168
star
12

tinydate

A tiny (349B) reusable date formatter. Extremely fast!
JavaScript
1,060
star
13

sirv

An optimized middleware & CLI application for serving static files~!
JavaScript
1,042
star
14

sade

Smooth (CLI) Operator 🎶
JavaScript
1,009
star
15

rosetta

A general purpose internationalization library in 292 bytes
JavaScript
772
star
16

dset

A tiny (194B) utility for safely writing deep Object values~!
JavaScript
754
star
17

uid

A tiny (130B to 205B) and fast utility to generate random IDs of fixed length
JavaScript
645
star
18

httpie

A Node.js HTTP client as easy as pie! 🥧
JavaScript
575
star
19

ganalytics

A tiny (312B) client-side module for tracking with Google Analytics
JavaScript
575
star
20

trouter

🐟 A fast, small-but-mighty, familiar fish...errr, router*
JavaScript
563
star
21

regexparam

A tiny (394B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇‍♂️
JavaScript
559
star
22

dimport

Run ES Module syntax (`import`, `import()`, and `export`) in any browser – even IE!
JavaScript
547
star
23

mri

Quickly scan for CLI flags and arguments
JavaScript
533
star
24

tempura

A light, crispy, and delicious template engine 🍤
JavaScript
517
star
25

calendarize

A tiny (202B) utility to generate calendar views.
JavaScript
472
star
26

formee

A tiny (532B) library for handling <form> elements.
JavaScript
443
star
27

qss

A tiny (294b) browser utility for encoding & decoding a querystring.
JavaScript
408
star
28

uuid

A tiny (~230B)and fast UUID (V4) generator for Node and the browser
JavaScript
391
star
29

preact-starter

Webpack3 boilerplate for building SPA / PWA / offline front-end apps with Preact
JavaScript
387
star
30

vegemite

A Pub/Sub state manager you'll love... or hate
JavaScript
373
star
31

resolve.exports

A tiny (952b), correct, general-purpose, and configurable `"exports"` and `"imports"` resolver without file-system reliance
TypeScript
357
star
32

fetch-event-stream

A tiny (736b) utility for Server Sent Event (SSE) streaming via `fetch` and Web Streams API
TypeScript
344
star
33

polkadot

The tiny HTTP server that gets out of your way! ・
JavaScript
323
star
34

matchit

Quickly parse & match URLs
JavaScript
321
star
35

flru

A tiny (215B) and fast Least Recently Used (LRU) cache
JavaScript
312
star
36

mrmime

A tiny (2.8kB) and fast utility for getting a MIME type from an extension or filename
TypeScript
306
star
37

watchlist

Recursively watch a list of directories & run a command on any file system changes
JavaScript
260
star
38

ley

(WIP) Driver-agnostic database migrations
JavaScript
259
star
39

arr

A collection of tiny, highly performant Array.prototype alternatives
JavaScript
255
star
40

flattie

A tiny (203B) and fast utility to flatten an object with customizable glue
JavaScript
254
star
41

webpack-messages

Beautifully format Webpack messages throughout your bundle lifecycle(s)!
JavaScript
246
star
42

obj-str

A tiny (96B) library for serializing Object values to Strings.
JavaScript
225
star
43

templite

Lightweight templating in 150 bytes
JavaScript
223
star
44

ms

A tiny (414B) and fast utility to convert milliseconds to and from strings.
JavaScript
206
star
45

nestie

A tiny (215B) and fast utility to expand a flattened object
JavaScript
199
star
46

throttles

A tiny (139B to 204B) utility to regulate the execution rate of your functions
JavaScript
198
star
47

hexoid

A tiny (190B) and extremely fast utility to generate random IDs of fixed length
JavaScript
186
star
48

astray

Walk an AST without being led astray
JavaScript
178
star
49

fromnow

A tiny (339B) utility for human-readable time differences between now and past or future dates.
JavaScript
178
star
50

tmp-cache

A least-recently-used cache in 35 lines of code~!
JavaScript
175
star
51

bundt

A simple bundler for your delicious modules
JavaScript
168
star
52

wrr

A tiny (148B) weighted round robin utility
JavaScript
164
star
53

freshie

(WIP) A fresh take on building universal applications with support for pluggable frontends and backends.
TypeScript
154
star
54

svelte-ssr-worker

A quick demo for rendering Svelte server-side (SSR), but within a Cloudflare Worker!
JavaScript
153
star
55

totalist

A tiny (195B to 224B) utility to recursively list all (total) files in a directory
JavaScript
149
star
56

escalade

A tiny (183B to 210B) and fast utility to ascend parent directories
JavaScript
144
star
57

typescript-module

Template repository for authoring npm modules via TypeScript
TypeScript
143
star
58

sublet

Reactive leases for data subscriptions
JavaScript
139
star
59

webpack-route-manifest

Generate an asset manifest file, keyed by route patterns!
JavaScript
127
star
60

url-shim

A 1.5kB browser polyfill for the Node.js `URL` and `URLSearchParams` classes.
JavaScript
123
star
61

semiver

A tiny (153B) utility to compare semver strings.
JavaScript
120
star
62

svelte-demo

Multi-page demo built Svelte 3.x and Rollup with code-splitting
Svelte
113
star
63

saturated

A tiny (203B) utility to enqueue items for batch processing and/or satisfying rate limits.
JavaScript
112
star
64

webpack-format-messages

Beautiful formatting for Webpack messages; ported from Create React App!
JavaScript
111
star
65

gittar

🎸 Download and/or Extract git repositories (GitHub, GitLab, BitBucket). Cross-platform and Offline-first!
JavaScript
111
star
66

cfw

(WIP) A build and deploy utility for Cloudflare Workers.
TypeScript
110
star
67

webpack-critical

Extracts & inlines Critical CSS with Wepack
JavaScript
109
star
68

pages-fullstack

Demo SvelteKit application running on Cloudflare Pages
Svelte
101
star
69

sort-isostring

A tiny (110B) and fast utility to sort ISO 8601 Date strings
JavaScript
98
star
70

colors-app

🎨 A PWA for copying values from popular color palettes. Supports HEX, RGB, and HSL formats.
JavaScript
95
star
71

salteen

A snappy and lightweight (259B) utility to encrypt and decrypt values with salt.
JavaScript
95
star
72

is-offline

A tiny (174B) library to detect `offline` status & respond to changes in the browser.
JavaScript
91
star
73

seolint

(WIP) A robust and configurable SEO linter
TypeScript
86
star
74

rafps

A tiny (178B) helper for playing, pausing, and setting `requestAnimationFrame` frame rates
JavaScript
82
star
75

preact-cli-ssr

A quick demo for adding SSR to a Preact CLI app
JavaScript
79
star
76

webpack-modules

Handle `.mjs` files correctly within webpack
JavaScript
71
star
77

csprng

A tiny (~90B) isomorphic wrapper for `crypto.randomBytes` in Node.js and browsers.
JavaScript
66
star
78

premove

A tiny (201B to 247B) utility to remove items recursively
JavaScript
63
star
79

classico

A tiny (255B) shim when Element.classList cannot be used~!
JavaScript
62
star
80

mk-dirs

A tiny (381B to 419B) utility to make a directory and its parents, recursively
JavaScript
54
star
81

primeval

A tiny (128B) utility to check if a value is a prime number
JavaScript
51
star
82

loadr

Quickly attach multiple ESM Loaders and/or Require Hooks together but without the repetitive `--experimental-loader` and/or `--require` Node flags
JavaScript
49
star
83

preact-progress

Simple and lightweight (~590 bytes gzip) progress bar component for Preact
JavaScript
49
star
84

route-manifest

A tiny (412B) runtime to retrieve the correct entry from a Route Manifest file.
JavaScript
46
star
85

svelte-preprocess-esbuild

A Svelte Preprocessor to compile TypeScript via esbuild!
TypeScript
45
star
86

rollup-route-manifest

A Rollup plugin to generate an asset manifest, keyed by route patterns ("route manifest")
JavaScript
41
star
87

preact-scroll-header

A (800b gzip) header that will show/hide while scrolling for Preact
JavaScript
41
star
88

inferno-starter

Webpack2 boilerplate for building SPA / PWA / offline front-end apps with Inferno.js
JavaScript
41
star
89

onloaded

A tiny (350B) library to detect when images have loaded.
JavaScript
38
star
90

route-sort

A tiny (200B) utility to sort route patterns by specificity
JavaScript
36
star
91

webpack-plugin-replace

Replace content while bundling.
JavaScript
36
star
92

scorta

A tiny (330B to 357B) and fast utility to find a package's hidden supply / cache directory.
JavaScript
33
star
93

local-hostname

A tiny (171B) utility to check if a hostname is local
JavaScript
32
star
94

taskr-outdated

A generator & coroutine-based task runner. Fasten your seatbelt. 🚀
JavaScript
32
star
95

rewrite-imports

Rewrite `import` statements as `require()`s; via RegExp
JavaScript
31
star
96

preact-offline

A (300b gzip) component to render alerts/messages when offline.
JavaScript
29
star
97

fly-kit-preact

A starter kit for building offline / SPA / PWA apps with Preact
JavaScript
28
star
98

fannypack

The tool belt for front-end developers
JavaScript
28
star
99

is-ready

A tiny (309B) library to detect when `window` globals are defined and ready to use~!
JavaScript
28
star
100

ava-http

Async HTTP request wrapper 🚀
JavaScript
25
star