• Stars
    star
    291
  • Rank 142,563 (Top 3 %)
  • Language
    JavaScript
  • Created about 10 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

Like ui-router, but without all the Angular. The best way to structure a single-page webapp.

Changelog β€’ Join the chat on Discord β€’ API documentation

Brief explanation

abstract-state-router lets you build single-page webapps using nested routes/states. Your code doesn't reference routes directly, like /app/users/josh, but by name and properties, like app.user + { name: 'josh' }.

To find out why you should be using this kind of router, read Why Your Webapp Needs a State-Based Router.

abstract-state-router is heavily inspired by the original ui-router. The biggest difference is: you can use abstract-state-router with whatever templating/component library you like.

It is similar in that way to the new ui-router, except that abstract-state-router is smaller, its documentation is more readable, and it is easier to create new renderers for arbitrary view libraries.

To see an example app implemented with a couple of different browser rendering libraries, click here to visit the state-router-example on Github Pages.

Project status

This project is stable and has been used in production for years.

The last major version bump change was in July of 2021 when the project started shipping modern JS instead of ES5. There have been no breaking changes to the library's function APIs since 2015.

abstract-state-router is extensible without much work, so very few feature additions have been necessary.

I occasionally have dreams of a rewrite, but it's hard to justify when the current version works so well for my main target use case (business software).

Browser compatibility

This project is currently published as CommonJS with modern JS syntax. If you're targeting browsers more than 2-3 years old, I assume you're already compiling your code for your target environments.

If you're supporting really old browsers pre-ES2015 browsers, you'll need polyfills for Promise and Object.assign. Check out polyfill.io for automatic polyfills, it makes life super-easy.

Current renderer implementations

If you want to use the state router with any other templating/dom manipulation library, read these docs! It's not too bad to get started.

Install

npm i abstract-state-router

Your CommonJS-supporting bundler should be able to import make_state_router from 'abstract-state-router' without issue.

API

Instantiate

var createStateRouter = require('abstract-state-router')

var stateRouter = createStateRouter(makeRenderer, rootElement, options)

The makeRenderer should be a function that returns an object with these properties: render, destroy, and getChildElement. Documentation is here - see test/support/renderer-mock.js for an example implementation.

The rootElement is the element where the first-generation states will be created.

options

Possible properties of the options object are:

  • pathPrefix defaults to '#'. If you're using HTML5 routing/pushState, you'll most likely want to set this to an empty string.
  • router defaults to an instance of a hash brown [email protected]. The abstract-state-router unit tests use the hash brown router stub. To use pushState, pass in a hash brown router created with sausage-router.
  • throwOnError defaults to true, because you get way better stack traces in Chrome when you throw than if you console.log(err) or emit 'error' events. The unit tests disable this.

stateRouter.addState({name, route, defaultChild, data, template, resolve, activate, querystringParameters, defaultParameters, canLeaveState})

The addState function takes a single object of options. All of them are optional, unless stated otherwise.

name is parsed in the same way as ui-router's dot notation, so 'contacts.list' is a child state of 'contacts'. Required.

route is an express-style url string that is parsed with a fork of path-to-regexp. If the state is a child state, this route string will be concatenated to the route string of its parent (e.g. if 'contacts' state has route ':user/contacts' and 'contacts.list' has a route of '/list', you could visit the child state by browsing to '/tehshrike/contacts/list').

defaultChild is a string (or a function that returns a string) of the default child's name. Use the short name (list), not the fully qualified name with all its parents (contacts.list).

If the viewer navigates to a state that has a default child, the router will redirect to the default child. (For example, if 'list' is the default child of 'contacts', state.go('contacts') will actually be equivalent to state.go('contacts.list'). Likewise, browsing to '/tehshrike/contacts' would take the viewer to '/tehshrike/contacts/list'.)

data is an object that can hold whatever you want - it will be passed in to the resolve and activate functions.

template is a template string/object/whatever to be interpreted by the render function. Required.

resolve is a function called when the selected state begins to be transitioned to, allowing you to accomplish the same objective as you would with ui-router's resolve.

activate is a function called when the state is made active - the equivalent of the AngularJS controller to the ui-router.

querystringParameters is an array of query string parameters that will be watched by this state.

defaultParameters is an object whose properties should correspond to parameters defined in the querystringParameters option or the route parameters. Whatever values you supply here will be used as the defaults in case the url does not contain any value for that parameter. If you pass a function for a default parameter, the return of that function will be used as the default value.

For backwards compatibility reasons, defaultQuerystringParameters will work as well (though it does not function any differently).

canLeaveState is an optional function with the state's domApi as its sole argument. If it returns false, navigation from the state will be prevented. If it is returns true or is left undefined, state changes will not be prevented.

resolve(data, parameters, callback(err, content).redirect(stateName, [stateParameters]))

data is the data object you passed to the addState call. parameters is an object containing the parameters that were parsed out of the route and the query string.

Returning values

Your resolve function can either return a promise, or call the callback.

Properties on the returned object will be set as attributes on the state's component.

async function resolve(data, parameters) {
	const [ user, invoice ] = await Promise.all([
		fetchUser(parameters.userId),
		fetchInvoice(parameters.invoiceId),
	])

	return {
		user,
		invoice,
	}
}

Errors/redirecting

If you return a rejected promise or call callback(err, content) with a truthy err value, the state change will be cancelled and the previous state will remain active.

If you call callback.redirect(stateName, [stateParameters]), the state router will begin transitioning to that state instead. The current destination will never become active, and will not show up in the browser history.

To cause a redirect with promises, return a rejected promise with an object containing a redirectTo property with name and params values for the state to redirect to:

function resolve(data, parameters) {
	return Promise.reject({
		redirectTo: {
			name: 'otherCoolState',
			params: {
				extraCool: true
			}
		}
	})
}

activate(context)

The activate function is called when the state becomes active. It is passed an event emitter named context with four properties:

  • domApi: the DOM API returned by the renderer
  • data: the data object given to the addState call
  • parameters: the route/querystring parameters
  • content: the object passed into the resolveFunction's callback

The context object is also an event emitter that emits a 'destroy' event when the state is being transitioned away from. You should listen to this event to clean up any workers that may be ongoing.

addState examples

stateRouter.addState({
	name: 'app',
	data: {},
	route: '/app',
	template: '',
	defaultChild: 'tab1',
	async resolve(data, parameters) {
		return isLoggedIn()
	},
	activate(context) {
		// Normally, you would set data in your favorite view library
		var isLoggedIn = context.content
		var ele = document.getElementById('status')
		ele.innerText = isLoggedIn ? 'Logged In!' : 'Logged Out!'
	}
})

stateRouter.addState({
	name: 'app.tab1',
	data: {},
	route: '/tab_1',
	template: '',
	async resolve(data, parameters) {
		return getTab1Data()
	},
	activate(context) {
		document.getElementById('tab').innerText = context.content

		var intervalId = setInterval(function() {
			document.getElementById('tab').innerText = 'MORE CONTENT!'
		}, 1000)

		context.on('destroy', function() {
			clearInterval(intervalId)
		})
	}
})

stateRouter.addState({
	name: 'app.tab2',
	data: {},
	route: '/tab_2',
	template: '',
	async resolve(data, parameters) {
		return getTab2Data()
	},
	activate(context) {
		document.getElementById('tab').innerText = context.content
	}
})

stateRouter.go(stateName, [stateParameters, [options]])

Browses to the given state, with the current parameters. Changes the url to match.

The options object currently supports two options:

  • replace - if it is truthy, the current state is replaced in the url history.
  • inherit - if true, querystring parameters are inherited from the current state. Defaults to false.

If a state change is triggered during a state transition, and the DOM hasn't been manipulated yet, then the current state change is discarded, and the new one replaces it. Otherwise, it is queued and applied once the current state change is done.

If stateName is null, the current state is used as the destination.

stateRouter.go('app')
// This actually redirects to app.tab1, because the app state has the default child: 'tab1'

stateRouter.evaluateCurrentRoute(fallbackStateName, [fallbackStateParameters])

You'll want to call this once you've added all your initial states. It causes the current path to be evaluated, and will activate the current state. If no route is set, abstract-state-router will change the url to to the fallback state.

stateRouter.evaluateCurrentRoute('app.home')

stateRouter.stateIsActive([stateName, [stateParameters]])

Returns true if stateName is the current active state, or an ancestor of the current active state...

...And all of the properties of stateParameters match the current state parameter values.

You can pass in null as the state name to see if the current state is active with a given set of parameters.

// Current state name: app.tab1
// Current parameters: { fancy: 'yes', thing: 'hello' }
stateRouter.stateIsActive('app.tab1', { fancy: 'yes' }) // => true
stateRouter.stateIsActive('app.tab1', { fancy: 'no' }) // => false
stateRouter.stateIsActive('app') // => true
stateRouter.stateIsActive(null, { fancy: 'yes' }) // => true

stateRouter.makePath(stateName, [stateParameters, [options]])

Returns a path to the state, starting with an optional octothorpe #, suitable for inserting straight into the href attribute of a link.

The options object supports one property: inherit - if true, querystring parameters are inherited from the current state. Defaults to false.

If stateName is null, the current state is used.

stateRouter.makePath('app.tab2', { pants: 'no' })

stateRouter.getActiveState()

Returns the last completely loaded state

// Current state name: app.tab1
// Current state params: pants: 'no'
stateRouter.getActiveState() // => { name: 'app.tab1', parameters: { pants: 'no' }}

Events

These are all emitted on the state router object.

State change

  • stateChangeAttempt(functionThatBeginsTheStateChange) - used by the state transition manager, probably not useful to anyone else at the moment
  • stateChangeStart(state, parameters, states) - emitted after the state name and parameters have been validated
  • stateChangeCancelled(err) - emitted if a redirect is issued in a resolve function
  • stateChangeEnd(state, parameters, states) - after all activate functions are called
  • stateChangeError(err) - emitted if an error occurs while trying to navigate to a new state - including if you try to navigate to a state that doesn't exist
  • stateError(err) - emitted if an error occurs in an activation function, or somewhere else that doesn't directly interfere with changing states. Should probably be combined with stateChangeError at some point since they're not that different?
  • routeNotFound(route, parameters) - emitted if the user or some errant code changes the location hash to a route that does not have any states associated with it. If you have a generic "not found" page you want to redirect people to, you can do so like this:
stateRouter.on('routeNotFound', function(route, parameters) {
	stateRouter.go('not-found', {
		route: route,
		parameters: parameters
	})
})

DOM API interactions

  • beforeCreateState({state, content, parameters})
  • afterCreateState({state, domApi, content, parameters})
  • beforeDestroyState({state, domApi})
  • afterDestroyState({state})

Testing/development

To run the unit tests:

  • clone this repository
  • run npm install
  • run npm test

State change flow

  • emit stateChangeStart
  • call all resolve functions
  • resolve functions return
  • NO LONGER AT PREVIOUS STATE
  • destroy the contexts of all "destroy" states
  • destroy appropriate dom elements
  • call render functions for "create"ed states
  • call all activate functions
  • emit stateChangeEnd

Every state change does this to states

  • destroy: states that are no longer active at all. The contexts are destroyed, and the DOM elements are destroyed.
  • create: states that weren't active at all before. The DOM elements are rendered, and resolve/activate are called.

HTML5/pushState routing

pushState routing is technically supported. To use it, pass in an options object with a router hash-brown-router constructed with a sausage-router, and then set the pathPrefix option to an empty string.

var makeStateRouter = require('abstract-state-router')
var sausage = require('sausage-router')
var makeRouter = require('hash-brown-router')

var stateRouter = makeStateRouter(makeRenderer, rootElement, {
	pathPrefix: '',
	router: makeRouter(sausage())
})

However to use it in the real world, there are two things you probably want to do:

Intercept link clicks

To get all the benefits of navigating around nested states, you'll need to intercept every click on a link and block the link navigation, calling go(path) on the sausage-router instead.

You would need to add these click handlers whenever a state change happened.

Server-side rendering

You would also need to be able to render the correct HTML on the server-side.

For this to even be possible, your chosen rendering library needs to be able to work on the server-side to generate static HTML. I know at least Ractive.js and Riot support this.

The abstract-state-router would need to be changed to supply the list of nested DOM API objects for your chosen renderer.

Then to generate the static HTML for the current route, you would create an abstract-state-router, tell it to navigate to that route, collect all the nested DOM API objects, render them as HTML strings, embedding the children inside of the parents.

You would probably also want to send the client the data that was returned by the resolve functions, so that when the JavaScript app code started running the abstract-state-router on the client-side, it wouldn't hit the server to fetch all the data that had already been fetched on the server to generate the original HTML.

Who's adding this?

Track development progress in #48.

It could be added by me, but probably not in the near future, since I will mostly be using this for form-heavy business apps where generating static HTML isn't any benefit.

If I use the abstract-state-router on an app where I want to support clients without JS, then I'll start working through those tasks in the issue above.

If anyone else has need of this functionality and wants to get keep making progress on it, I'd be happy to help. Stop by the chat room to ask any questions.

Maintainers

License

WTFPL

More Repositories

1

deepmerge

A library for deep (recursive) merging of Javascript objects
JavaScript
2,755
star
2

idle-until-urgent

Defer JS work until the browser has a chance to breathe
JavaScript
133
star
3

noddity

It's a blog, it's a wiki, it's a fast CMS!
HTML
56
star
4

backup-bear-notes

Back up your Bear Notes as markdown files.
JavaScript
51
star
5

sheetsy

Use Google Sheets as a data source in the browser without OAuth
JavaScript
46
star
6

svelte-state-renderer

abstract-state-router renderer for Svelte
JavaScript
35
star
7

svelte-preprocess-postcss

Use PostCSS to preprocess your styles in Svelte components
JavaScript
25
star
8

wtfpl2.com

My favorite license, now easier to link to!
HTML
24
star
9

financial-number

Do math with money! Without risking loss of data to floating point representations!
TypeScript
23
star
10

sql-concat

A MySQL query builder
JavaScript
22
star
11

regex-fun

Write maintainable regular expressions
JavaScript
21
star
12

joi-sql

Create Joi validation code for MySQL databases
JavaScript
21
star
13

sync-diigo-to-folder

Sync all your Diigo bookmarks to a directory as Markdown files. Intended for use with Obsidian
JavaScript
21
star
14

world-english-bible

The World English Bible translation in JSON
HTML
18
star
15

state-router-example

Examples of abstract-state-router usage with various templating/rendering libraries
JavaScript
15
star
16

is-mergeable-object

JavaScript
12
star
17

sql-tagged-template-literal

ES6 SQL-escaping tagged template literal that spits out a sanitized SQL string
JavaScript
12
star
18

shiz

Lazily calculated values
JavaScript
12
star
19

riot-state-renderer

a RiotJS-based renderer for the abstract-state-router
JavaScript
11
star
20

ractive-state-router

A state router implimentation with a RactiveJS renderer
JavaScript
10
star
21

small-indexeddb

Simple IndexedDB transactions with Promises
JavaScript
10
star
22

shell-tag

Run shell commands inline in JavaScript with ES6 template strings
JavaScript
10
star
23

warg

A reactive stream thing
TypeScript
9
star
24

books-of-the-bible

An ordered list of the names of the canonical books of the bible, with common abbreviations
JavaScript
9
star
25

better-emitter

A very simple event emitter with a better API than all the others
JavaScript
9
star
26

canon-reader

A simple Bible reader.
JavaScript
8
star
27

k

Command-line Kanbanize interface
JavaScript
8
star
28

gzip-all

Create .gz files for all files in a folder
JavaScript
8
star
29

svelte-querystring-router

A router that only serializes a small amount of state to the querystring
JavaScript
7
star
30

mannish

Mannish, the Manly Mediator
JavaScript
7
star
31

verse-reference-regex

A regular expression that matches Bible verse references and ranges
JavaScript
7
star
32

koa-bestest-router

Router middleware for Koa. Mutation-free, less than 100 lines
JavaScript
6
star
33

hash-brown-router

A client-side router for single-page apps
JavaScript
6
star
34

check-if-folder-contents-changed-in-git-commit-range

Check if folder contents changed in a git commit range
JavaScript
6
star
35

state-router-redux-ractive

If you use abstract-state-router and want to use Redux, this package is for you
JavaScript
6
star
36

Sublime-AlphanumericMarkdownFootnote

A Sublime Text plugin that inserts footnotes into your markdown for you
Python
5
star
37

now-alias

Assign an alias to a recent "now" deployment
JavaScript
5
star
38

basic-xhr

The barest-bones wrapper for XHR in the cases where I want to use XHR
JavaScript
5
star
39

glob-module-file

Generate a file of code that imports/requires a bunch of files, and exports them as an array
JavaScript
5
star
40

ezpr

Open a Github pull request based on your local branch
JavaScript
4
star
41

text-metadata-parser

Store your metadata in plain text, if you want to!
JavaScript
4
star
42

inventory-pos

Makes the world go round
JavaScript
4
star
43

financial-arithmetic-functions

A set of functions for doing math on numbers without floating point numbers
TypeScript
4
star
44

memorize-text-app

Memorize stuff. Add new decks by creating Google spreadsheets
HTML
4
star
45

ractive-drag-and-drop-files

A Ractive event proxy wrapper for https://github.com/mikolalysenko/drag-and-drop-files
JavaScript
4
star
46

obsidian-tag-pages

Creates a page for each tag, containing a list of the pages that have that tag
JavaScript
4
star
47

browserstack-tape-reporter

Run your tape tests on BrowserStack
JavaScript
4
star
48

polkadot-router

A nice simple router for polkadot
JavaScript
3
star
49

communal-checklist

Because all those other sites my wife is trying are a pain
JavaScript
3
star
50

text-fit-component

Fits text to match the width of its parent
HTML
3
star
51

polkadot-middleware

A middleware pattern for polkadot
JavaScript
3
star
52

classy-graph

An exercise in creating classy graphs
HTML
3
star
53

key-master

A map that takes a "default value" function
JavaScript
3
star
54

spyfallx

Spyfall
JavaScript
3
star
55

susd-search-site

Quickly search the Shut Up And Sit Down archives
JavaScript
3
star
56

private-github-website

A node.js server that hosts private content from a Github repo, protected by email address authentication
JavaScript
3
star
57

dynamic-import-iife

"Dynamic import"/lazyload IIFE bundles in the browser
JavaScript
3
star
58

combine-arrays

Iterate over multiple arrays at once, functionally
JavaScript
2
star
59

sync-github-to-fs

Keep a local folder up to date with the contents of a Github repository
JavaScript
2
star
60

add-affiliate-querystring

Given a user-entered URL, add your own affiliate code to the querystring.
JavaScript
2
star
61

memorization-app

Memorize stuff you want to learn, word for word
JavaScript
2
star
62

cyoa-app

Shrike's choose-your-own-adventure framework
Svelte
2
star
63

weak-type-wizard

He's a caster, get it?
JavaScript
2
star
64

noddity-butler

Hustles and bustles around, bringing you blog posts at your whim
JavaScript
2
star
65

symlink-cli

Like ln -s except less tricksy
JavaScript
2
star
66

stripe-donation

A donation page for non-profit sites, backed by Stripe
JavaScript
2
star
67

noddity-generator-cli

Generate static HTML files from Noddity posts
JavaScript
2
star
68

just-uuid4

Just UUID v4
JavaScript
2
star
69

click-should-be-intercepted-for-navigation

Given a click event, returns true if it's a left-click that you should intercept to trigger navigation
JavaScript
2
star
70

pickering-majority-text-revelation

A programmatic version of Pickering's Majority Text translation of Revelation
JavaScript
2
star
71

asr-active-state-watcher

Waches an abstract-state-router and calls your function with all active DOM APIs
JavaScript
2
star
72

ordered-entries

Like Object.entries, but using getOwnPropertyNames, so that key order is respected
JavaScript
2
star
73

revelation-timeline

A timeline of historical events as they align with the prophesies in the book of Revelation
JavaScript
2
star
74

tap-strings

Generate valid TAP output as strings
JavaScript
2
star
75

tak-game

An implementation of the rules of the board game Tak
JavaScript
2
star
76

try-catch

Mistakes I've made, and things I wish I could tell my younger self
1
star
77

svelte-1-25-0-array-binding-repro

A weird bug
HTML
1
star
78

duffventures.com

duffventures.com
HTML
1
star
79

make-tree

Turn an array of keys into a hierarchy of objects
JavaScript
1
star
80

react-app-example

JavaScript
1
star
81

bitstorm

Automatically exported from code.google.com/p/bitstorm
PHP
1
star
82

list-input

Because every other spreadsheet-like form on the web sucks
Svelte
1
star
83

private-static-website

Easily host a private web site authenticated by email address only
JavaScript
1
star
84

read-write-lock

Reads are exclusive with writes, writes are exclusive with everything
JavaScript
1
star
85

get-text-fit-size

Find out what font size will make a text block fit inside of another element without wrapping
JavaScript
1
star
86

fix-bandcamp-directory-structure

JavaScript
1
star
87

schedulator-sorter

Sorts out who the next people in line are for this app I'm throwing together
JavaScript
1
star
88

bookindex2

Where did I put that book in my library
JavaScript
1
star
89

create-redux-reducer-from-map

My personal preference for building reducer functions
JavaScript
1
star
90

joshduff.com

My home page
HTML
1
star
91

tsx_issue_86_repro

Reproduction of issue 86
JavaScript
1
star
92

take-live-notes-like-for-meeting-minutes

Edit markdown in one window, have a rendered version show up in a different browser window, updating live
CSS
1
star
93

dining-room-terminal

The clock in my dining room
HTML
1
star
94

noddity-retrieval

A way to retrieve blog posts that are being served in this stupid-simple format
JavaScript
1
star
95

lispyscriptify

Lispyscript transform for Browserify
JavaScript
1
star
96

c25k

Running is good for you or whatever
JavaScript
1
star
97

noddity-template-parser

Turns Noddity posts into things browsers can display
JavaScript
1
star
98

invoice-app

Svelte
1
star
99

noddity-render-static

Generate static HTML from Noddity posts
JavaScript
1
star
100

majority-text-family-35-revelation

Machine-readable greek of the book of Revelation, from the family 35 majority text
HTML
1
star