├── .gitignore
├── link.js
├── examples
├── basics
│ ├── .gitignore
│ ├── server.js
│ ├── app.js
│ ├── package.json
│ ├── README.md
│ ├── config.js
│ └── index.html
└── react
│ ├── .gitignore
│ ├── components
│ ├── Home.js
│ ├── NotFound.js
│ ├── Nav.js
│ ├── Friends.js
│ ├── FriendInfo.js
│ └── App.js
│ ├── db
│ └── friends.js
│ ├── server.js
│ ├── app.js
│ ├── README.md
│ ├── package.json
│ ├── index.html
│ └── config.js
├── .flowconfig
├── .babelrc
├── src
├── link.js
└── router.js
├── package.json
├── lib
└── flowtypes.js
├── dist
├── link.js
└── router.js
├── README.md
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | *.log
2 | node_modules
3 | .c9
--------------------------------------------------------------------------------
/link.js:
--------------------------------------------------------------------------------
1 | module.exports = require('./dist/link.js');
2 |
--------------------------------------------------------------------------------
/examples/basics/.gitignore:
--------------------------------------------------------------------------------
1 | jspm_packages/
2 | node_modules
3 |
--------------------------------------------------------------------------------
/examples/react/.gitignore:
--------------------------------------------------------------------------------
1 | jspm_packages/
2 | node_modules
3 |
--------------------------------------------------------------------------------
/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 | .*/lucid-router/dist/.*
3 |
4 | [include]
5 |
6 | [libs]
7 | ./lib/
8 |
9 | [options]
10 |
--------------------------------------------------------------------------------
/examples/react/components/Home.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const Home = () =>
Home!
4 |
5 | export default Home
6 |
--------------------------------------------------------------------------------
/examples/react/components/NotFound.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 |
3 | const NotFound = () => 404
4 |
5 | export default NotFound
6 |
--------------------------------------------------------------------------------
/examples/react/db/friends.js:
--------------------------------------------------------------------------------
1 | export default [
2 | {
3 | "id": "alice",
4 | "name": "Alice",
5 | "favoriteFood": "Sushi"
6 | },
7 | {
8 | "id": "bob",
9 | "name": "Bob",
10 | "favoriteFood": "Mac 'n Cheese"
11 | }
12 | ]
13 |
--------------------------------------------------------------------------------
/examples/react/components/Nav.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Link from 'lucid-router/link'
3 |
4 | const Nav = () =>
5 |
10 |
11 | export default Nav
12 |
--------------------------------------------------------------------------------
/examples/basics/server.js:
--------------------------------------------------------------------------------
1 | var express = require('express')
2 |
3 | var app = express()
4 |
5 | app.use(express.static(__dirname))
6 | app.get('/*', function(req, res) {
7 | res.sendFile('./index.html', {root: __dirname})
8 | })
9 |
10 | var ips = '0.0.0.0'
11 | var port = process.env.PORT || 3000
12 | app.listen(port, ips)
13 | console.log(''.concat('Server listening on http://'+ips+':'+port))
14 |
--------------------------------------------------------------------------------
/examples/react/server.js:
--------------------------------------------------------------------------------
1 | var express = require('express')
2 |
3 | var app = express()
4 |
5 | app.use(express.static(__dirname))
6 | app.get('/*', function(req, res) {
7 | res.sendFile('./index.html', {root: __dirname})
8 | })
9 |
10 | var ips = '0.0.0.0'
11 | var port = process.env.PORT || 3000
12 | app.listen(port, ips)
13 | console.log(''.concat('Server listening on http://'+ips+':'+port))
14 |
--------------------------------------------------------------------------------
/examples/react/components/Friends.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Link from 'lucid-router/link'
3 | import friends from '../db/friends'
4 |
5 | const Friends = () =>
6 |
7 |
All the friends!
8 |
9 | {friends.map(friend =>
10 | -
11 | {friend.name}
12 |
)}
13 |
14 |
15 |
16 | export default Friends
17 |
--------------------------------------------------------------------------------
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": ["es2015", "stage-2", "react"],
3 | "plugins": [
4 | "transform-export-extensions",
5 | "transform-react-display-name",
6 | "transform-flow-strip-types",
7 | "transform-class-properties"
8 | ],
9 | "env": {
10 | "development": {
11 | "presets": []
12 | },
13 | "production": {
14 | "plugins": [
15 | "transform-react-constant-elements",
16 | "transform-react-inline-elements"
17 | ]
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/examples/react/components/FriendInfo.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import friends from '../db/friends'
3 |
4 | const FriendInfo = ({location}) => {
5 | const friendId = location.state.name
6 | const friend = friends.find(f => f.id === friendId)
7 | return (
8 |
9 |
Friend info!
10 |
11 | - Name: {friend.name}
12 | - Favorite food: {friend.favoriteFood}
13 |
14 |
15 | )
16 | }
17 |
18 | export default FriendInfo
19 |
--------------------------------------------------------------------------------
/examples/react/app.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 | import * as router from 'lucid-router'
4 | import App from './components/App'
5 |
6 | router.addRoutes([
7 | {name: 'home', path: '/'},
8 | {name: 'friends', path: '/friends'},
9 | {name: 'friends.info', path: '/friends/:name'}
10 | ])
11 |
12 | router.register(location => render(location))
13 |
14 | render(router.getLocation())
15 |
16 | function render(location) {
17 | ReactDOM.render(, document.body)
18 | }
19 |
--------------------------------------------------------------------------------
/examples/basics/app.js:
--------------------------------------------------------------------------------
1 | import * as router from 'lucid-router'
2 |
3 | //-- let the links in nav call `navigate` --//
4 | window.navigate = router.navigate
5 |
6 | router.addRoutes([
7 | {name: 'home', path: '/'},
8 | {name: 'friends', path: '/friends'},
9 | {name: 'friends.info', path: '/friends/:name'}
10 | ])
11 |
12 | router.register(location => render(location))
13 |
14 | render(router.getLocation())
15 |
16 | function render(location) {
17 | const pre = document.querySelector('pre')
18 | pre.innerHTML = JSON.stringify(location, null, 2)
19 | }
20 |
--------------------------------------------------------------------------------
/examples/basics/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "lucid-router-basics",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "server.js",
6 | "scripts": {
7 | "postinstall": "jspm install",
8 | "start": "node server.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "devDependencies": {
13 | "jspm": "^0.16.5"
14 | },
15 | "jspm": {
16 | "dependencies": {
17 | "lucid-router": "npm:lucid-router@1.3.5"
18 | },
19 | "devDependencies": {
20 | "babel": "npm:babel-core@^5.8.24",
21 | "babel-runtime": "npm:babel-runtime@^5.8.24",
22 | "core-js": "npm:core-js@^1.1.4"
23 | }
24 | },
25 | "dependencies": {
26 | "express": "^4.13.3"
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/examples/react/components/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import Nav from './Nav'
3 | import Home from './Home'
4 | import Friends from './Friends'
5 | import FriendInfo from './FriendInfo'
6 | import NotFound from './NotFound'
7 |
8 | const viewFor = location => {
9 | switch (location.name) {
10 | case 'home': return
11 | case 'friends': return
12 | case 'friends.info': return
13 | }
14 | return
15 | }
16 |
17 | const App = ({location}) =>
18 |
19 |
22 |
23 | {viewFor(location)}
24 |
25 |
26 |
27 | export default App
28 |
--------------------------------------------------------------------------------
/examples/react/README.md:
--------------------------------------------------------------------------------
1 | # lucid-router react example
2 | This example uses `jspm` and `express`, which `npm` will grab for you:
3 | ```sh
4 | npm install
5 | ```
6 | Then run express with:
7 | ```sh
8 | npm start
9 | ```
10 | Then head to `localhost:3000`.
11 | You could also just use `serve` or something instead of `express`, but then you'd get a 404 if you navigated to `/friends` and then refreshed.
12 | : ]
13 |
14 | All the configuration bits are in the [app.js](https://github.com/spicydonuts/lucid-router/blob/master/examples/react/app.js) file.
15 | The React components are in [/components](https://github.com/spicydonuts/lucid-router/tree/master/examples/react/components).
16 |
17 | React makes it easy to render any route when a route is just state, because rendering changing state over time is what React is great at!
18 |
--------------------------------------------------------------------------------
/examples/react/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "lucid-router-react-example",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "server.js",
6 | "scripts": {
7 | "postinstall": "jspm install",
8 | "start": "node server.js"
9 | },
10 | "author": "",
11 | "license": "ISC",
12 | "devDependencies": {
13 | "jspm": "^0.16.5"
14 | },
15 | "jspm": {
16 | "dependencies": {
17 | "json-loader": "npm:json-loader@^0.5.3",
18 | "lucid-router": "npm:lucid-router@1.3.5",
19 | "react": "npm:react@^0.14.0",
20 | "react-dom": "npm:react-dom@^0.14.0"
21 | },
22 | "devDependencies": {
23 | "babel": "npm:babel-core@^5.8.24",
24 | "babel-runtime": "npm:babel-runtime@^5.8.24",
25 | "core-js": "npm:core-js@^1.1.4"
26 | }
27 | },
28 | "dependencies": {
29 | "express": "^4.13.3"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/examples/react/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | lucid-router react
6 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/examples/basics/README.md:
--------------------------------------------------------------------------------
1 | # lucid-router basic example
2 | This example uses `jspm` and `express`, which `npm` will grab for you:
3 | ```sh
4 | npm install
5 | ```
6 | Then run express with:
7 | ```sh
8 | npm start
9 | ```
10 | Then head to `localhost:3000`.
11 | You could also just use `serve` or something instead of `express`, but then you'd get a 404 if you navigated to `/friends` and then refreshed.
12 | : ]
13 |
14 | All the configuration bits are in the [app.js](https://github.com/spicydonuts/lucid-router/blob/master/examples/basics/app.js) file.
15 | All navigation is in [index.html](https://github.com/spicydonuts/lucid-router/blob/master/examples/basics/index.html).
16 |
17 | Notice the link to Github is not in the routing table, so a normal redirect is performed.
18 | Also notice when you're on one of the specific friend routes (like /friends/alice) that the `:name` key in the route overrides the `name` query param.
19 |
20 | Congratulations, you've taken your first step into abstracting the concept of routing into a simple stream of data!
21 |
--------------------------------------------------------------------------------
/src/link.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {pathFor,navigate,navigateToRoute} from 'lucid-router';
3 |
4 | function isLeftClickEvent(e) {
5 | return e.button === 0;
6 | }
7 |
8 | function isModifiedEvent(e) {
9 | return Boolean(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
10 | }
11 |
12 | export default class Link extends React.Component {
13 | onClick = (e) => {
14 | const {onClick, target} = this.props;
15 | let allowTransition = true;
16 |
17 | if (onClick instanceof Function)
18 | onClick(e);
19 |
20 | if (isModifiedEvent(e) || !isLeftClickEvent(e))
21 | return;
22 |
23 | if (e.defaultPrevented === true)
24 | allowTransition = false;
25 |
26 | if (target) {
27 | if (!allowTransition)
28 | e.preventDefault();
29 |
30 | return;
31 | }
32 |
33 | if (allowTransition) {
34 | const {to, params, href} = this.props;
35 | if (to)
36 | navigateToRoute(to, params, e);
37 | else if (href != null)
38 | navigate(href, e);
39 | }
40 | }
41 |
42 | render () {
43 | const {to, params, href, children, ...props} = this.props;
44 | const linkTo = to ? pathFor(to, params) : href;
45 | return {children};
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "lucid-router",
3 | "version": "1.5.0",
4 | "description": "a simple html5-history aware router",
5 | "main": "dist/router.js",
6 | "scripts": {
7 | "build": "npm run build-router && npm run build-link",
8 | "build-router": "babel src/router.js --out-file dist/router.js",
9 | "build-link": "babel src/link.js --out-file dist/link.js"
10 | },
11 | "repository": {
12 | "type": "git",
13 | "url": "https://github.com/spicydonuts/lucid-router.git"
14 | },
15 | "keywords": [
16 | "lucid",
17 | "router",
18 | "routing",
19 | "history",
20 | "html5",
21 | "isomorphic",
22 | "universal",
23 | "react"
24 | ],
25 | "author": "Michael Trotter",
26 | "license": "MIT",
27 | "bugs": {
28 | "url": "https://github.com/spicydonuts/lucid-router/issues"
29 | },
30 | "homepage": "https://github.com/spicydonuts/lucid-router",
31 | "dependencies": {
32 | "url-pattern": "1.0.1"
33 | },
34 | "devDependencies": {
35 | "babel-cli": "^6.6.5",
36 | "babel-plugin-transform-class-properties": "^6.6.0",
37 | "babel-plugin-transform-export-extensions": "^6.5.0",
38 | "babel-plugin-transform-flow-strip-types": "^6.7.0",
39 | "babel-plugin-transform-react-constant-elements": "^6.5.0",
40 | "babel-plugin-transform-react-display-name": "^6.5.0",
41 | "babel-plugin-transform-react-inline-elements": "^6.6.5",
42 | "babel-preset-es2015": "^6.6.0",
43 | "babel-preset-react": "^6.5.0",
44 | "babel-preset-stage-2": "^6.5.0"
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/lib/flowtypes.js:
--------------------------------------------------------------------------------
1 | type UrlPatternOptions = {
2 | escapeChar?: string;
3 | segmentNameStartChar?: string;
4 | segmentNameCharset?: string;
5 | segmentValueCharset?: string;
6 | optionalSegmentStartChar?: string;
7 | optionalSegmentEndChar?: string;
8 | wildcardChar?: string;
9 | }
10 |
11 | declare class UrlPattern {
12 | constructor(routePattern: string, options?: UrlPatternOptions): void;
13 | match(pathname: string): ?Object;
14 | stringify(params?: ?Object): string;
15 | }
16 |
17 | declare module 'url-pattern' {
18 | declare var exports: typeof UrlPattern;
19 | }
20 |
21 | // declare class RegexToArrayUrlPattern {
22 | // constructor(routePattern: RegExp): void;
23 | // match(pathname: string): ?Array;
24 | // stringify(params: Object): string;
25 | // }
26 | //
27 | // declare class RegexToObjectUrlPattern {
28 | // constructor(routePattern: RegExp, keys?: Array): void;
29 | // match(pathname: string): ?Object;
30 | // stringify(params: Object): string;
31 | // }
32 |
33 | declare function NavigationCallback(e: Event): void;
34 | declare function RouteMatchCallback(match: RouterMatch): boolean;
35 | declare function UnregisterLocationChangeCallback(): void;
36 |
37 | type RouteSpec = {
38 | name: string,
39 | path: string,
40 | external?: boolean | RouteMatchCallback
41 | };
42 | type Route = {
43 | name: string,
44 | path: string,
45 | external?: boolean | RouteMatchCallback,
46 | pattern: UrlPattern
47 | };
48 | type RouterMatch = {
49 | route: Route,
50 | pathname: string,
51 | search: string,
52 | hash: string,
53 | hashSearch: string,
54 | state: Object
55 | };
56 | type RouterLocation = {
57 | path: string,
58 | name: string,
59 | pathname: string,
60 | search: string,
61 | hash: string,
62 | hashSearch: string,
63 | state: Object
64 | };
65 |
66 | declare function LocationChangeCallback(location?: RouterLocation): void;
67 |
--------------------------------------------------------------------------------
/examples/basics/config.js:
--------------------------------------------------------------------------------
1 | System.config({
2 | baseURL: "/",
3 | defaultJSExtensions: true,
4 | transpiler: "babel",
5 | babelOptions: {
6 | "optional": [
7 | "runtime",
8 | "optimisation.modules.system"
9 | ]
10 | },
11 | paths: {
12 | "github:*": "jspm_packages/github/*",
13 | "npm:*": "jspm_packages/npm/*"
14 | },
15 |
16 | map: {
17 | "babel": "npm:babel-core@5.8.38",
18 | "babel-runtime": "npm:babel-runtime@5.8.38",
19 | "core-js": "npm:core-js@1.2.6",
20 | "lucid-router": "npm:lucid-router@1.3.5",
21 | "github:jspm/nodelibs-assert@0.1.0": {
22 | "assert": "npm:assert@1.3.0"
23 | },
24 | "github:jspm/nodelibs-path@0.1.0": {
25 | "path-browserify": "npm:path-browserify@0.0.0"
26 | },
27 | "github:jspm/nodelibs-process@0.1.2": {
28 | "process": "npm:process@0.11.2"
29 | },
30 | "github:jspm/nodelibs-util@0.1.0": {
31 | "util": "npm:util@0.10.3"
32 | },
33 | "npm:assert@1.3.0": {
34 | "util": "npm:util@0.10.3"
35 | },
36 | "npm:babel-runtime@5.8.38": {
37 | "process": "github:jspm/nodelibs-process@0.1.2"
38 | },
39 | "npm:core-js@1.2.6": {
40 | "fs": "github:jspm/nodelibs-fs@0.1.2",
41 | "path": "github:jspm/nodelibs-path@0.1.0",
42 | "process": "github:jspm/nodelibs-process@0.1.2",
43 | "systemjs-json": "github:systemjs/plugin-json@0.1.1"
44 | },
45 | "npm:inherits@2.0.1": {
46 | "util": "github:jspm/nodelibs-util@0.1.0"
47 | },
48 | "npm:lucid-router@1.3.5": {
49 | "process": "github:jspm/nodelibs-process@0.1.2",
50 | "url-pattern": "npm:url-pattern@1.0.1"
51 | },
52 | "npm:path-browserify@0.0.0": {
53 | "process": "github:jspm/nodelibs-process@0.1.2"
54 | },
55 | "npm:process@0.11.2": {
56 | "assert": "github:jspm/nodelibs-assert@0.1.0"
57 | },
58 | "npm:util@0.10.3": {
59 | "inherits": "npm:inherits@2.0.1",
60 | "process": "github:jspm/nodelibs-process@0.1.2"
61 | }
62 | }
63 | });
64 |
--------------------------------------------------------------------------------
/examples/basics/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | lucid-router basics
6 |
18 |
19 |
20 |
21 |
22 |
31 |
32 | You are here:
33 |
34 |
35 |
36 | More fun links to try:
37 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/examples/react/config.js:
--------------------------------------------------------------------------------
1 | System.config({
2 | baseURL: "/",
3 | defaultJSExtensions: true,
4 | transpiler: "babel",
5 | babelOptions: {
6 | "optional": [
7 | "runtime",
8 | "optimisation.modules.system"
9 | ]
10 | },
11 | paths: {
12 | "github:*": "jspm_packages/github/*",
13 | "npm:*": "jspm_packages/npm/*"
14 | },
15 |
16 | map: {
17 | "babel": "npm:babel-core@5.8.38",
18 | "babel-runtime": "npm:babel-runtime@5.8.38",
19 | "core-js": "npm:core-js@1.2.6",
20 | "json-loader": "npm:json-loader@0.5.4",
21 | "lucid-router": "npm:lucid-router@1.3.5",
22 | "react": "npm:react@0.14.8",
23 | "react-dom": "npm:react-dom@0.14.8",
24 | "github:jspm/nodelibs-assert@0.1.0": {
25 | "assert": "npm:assert@1.3.0"
26 | },
27 | "github:jspm/nodelibs-path@0.1.0": {
28 | "path-browserify": "npm:path-browserify@0.0.0"
29 | },
30 | "github:jspm/nodelibs-process@0.1.2": {
31 | "process": "npm:process@0.11.2"
32 | },
33 | "github:jspm/nodelibs-util@0.1.0": {
34 | "util": "npm:util@0.10.3"
35 | },
36 | "npm:assert@1.3.0": {
37 | "util": "npm:util@0.10.3"
38 | },
39 | "npm:babel-runtime@5.8.38": {
40 | "process": "github:jspm/nodelibs-process@0.1.2"
41 | },
42 | "npm:core-js@1.2.6": {
43 | "fs": "github:jspm/nodelibs-fs@0.1.2",
44 | "path": "github:jspm/nodelibs-path@0.1.0",
45 | "process": "github:jspm/nodelibs-process@0.1.2",
46 | "systemjs-json": "github:systemjs/plugin-json@0.1.1"
47 | },
48 | "npm:fbjs@0.6.1": {
49 | "process": "github:jspm/nodelibs-process@0.1.2"
50 | },
51 | "npm:inherits@2.0.1": {
52 | "util": "github:jspm/nodelibs-util@0.1.0"
53 | },
54 | "npm:lucid-router@1.3.5": {
55 | "process": "github:jspm/nodelibs-process@0.1.2",
56 | "url-pattern": "npm:url-pattern@1.0.1"
57 | },
58 | "npm:path-browserify@0.0.0": {
59 | "process": "github:jspm/nodelibs-process@0.1.2"
60 | },
61 | "npm:process@0.11.2": {
62 | "assert": "github:jspm/nodelibs-assert@0.1.0"
63 | },
64 | "npm:react-dom@0.14.8": {
65 | "react": "npm:react@0.14.8"
66 | },
67 | "npm:react@0.14.8": {
68 | "fbjs": "npm:fbjs@0.6.1",
69 | "process": "github:jspm/nodelibs-process@0.1.2"
70 | },
71 | "npm:util@0.10.3": {
72 | "inherits": "npm:inherits@2.0.1",
73 | "process": "github:jspm/nodelibs-process@0.1.2"
74 | }
75 | }
76 | });
77 |
--------------------------------------------------------------------------------
/dist/link.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
8 |
9 | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
10 |
11 | var _react = require('react');
12 |
13 | var _react2 = _interopRequireDefault(_react);
14 |
15 | var _lucidRouter = require('lucid-router');
16 |
17 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
18 |
19 | function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
20 |
21 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
22 |
23 | function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
24 |
25 | function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
26 |
27 | function isLeftClickEvent(e) {
28 | return e.button === 0;
29 | }
30 |
31 | function isModifiedEvent(e) {
32 | return Boolean(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
33 | }
34 |
35 | var Link = function (_React$Component) {
36 | _inherits(Link, _React$Component);
37 |
38 | function Link() {
39 | var _Object$getPrototypeO;
40 |
41 | var _temp, _this, _ret;
42 |
43 | _classCallCheck(this, Link);
44 |
45 | for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
46 | args[_key] = arguments[_key];
47 | }
48 |
49 | return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(Link)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.onClick = function (e) {
50 | var _this$props = _this.props;
51 | var onClick = _this$props.onClick;
52 | var target = _this$props.target;
53 |
54 | var allowTransition = true;
55 |
56 | if (onClick instanceof Function) onClick(e);
57 |
58 | if (isModifiedEvent(e) || !isLeftClickEvent(e)) return;
59 |
60 | if (e.defaultPrevented === true) allowTransition = false;
61 |
62 | if (target) {
63 | if (!allowTransition) e.preventDefault();
64 |
65 | return;
66 | }
67 |
68 | if (allowTransition) {
69 | var _this$props2 = _this.props;
70 | var to = _this$props2.to;
71 | var params = _this$props2.params;
72 | var href = _this$props2.href;
73 |
74 | if (to) (0, _lucidRouter.navigateToRoute)(to, params, e);else if (href != null) (0, _lucidRouter.navigate)(href, e);
75 | }
76 | }, _temp), _possibleConstructorReturn(_this, _ret);
77 | }
78 |
79 | _createClass(Link, [{
80 | key: 'render',
81 | value: function render() {
82 | var _props = this.props;
83 | var to = _props.to;
84 | var params = _props.params;
85 | var href = _props.href;
86 | var children = _props.children;
87 |
88 | var props = _objectWithoutProperties(_props, ['to', 'params', 'href', 'children']);
89 |
90 | var linkTo = to ? (0, _lucidRouter.pathFor)(to, params) : href;
91 | return _react2.default.createElement(
92 | 'a',
93 | _extends({}, props, { href: linkTo, onClick: this.onClick }),
94 | children
95 | );
96 | }
97 | }]);
98 |
99 | return Link;
100 | }(_react2.default.Component);
101 |
102 | exports.default = Link;
103 |
--------------------------------------------------------------------------------
/src/router.js:
--------------------------------------------------------------------------------
1 | /* @flow */
2 |
3 | import UrlPattern from 'url-pattern';
4 |
5 | var window: any = global.window;
6 | var history: History = global.history;
7 |
8 | var hasHistoryApi: boolean = (
9 | window !== undefined &&
10 | history !== undefined &&
11 | typeof history.pushState === 'function'
12 | );
13 |
14 | var locationChangeCallbacks: Array = [];
15 |
16 | var routes: Array = [];
17 |
18 | export function addRoutes(newRoutes: ?Array): void {
19 | if (!(newRoutes instanceof Array)) throw typeError(routes, 'lucid-router expects to be passed a routing array as its first parameter');
20 | for (var route of newRoutes) {
21 | if (route === null || !(route instanceof Object)) throw typeError(routes, 'lucid-router expects each route definition to be an object');
22 | route.path = route.path || null;
23 | route.name = route.name || null;
24 | route.external = typeof route.external === 'function'
25 | ? route.external
26 | : !!route.external;
27 | try {
28 | route.pattern = new UrlPattern(route.path);
29 | } catch (err) {
30 | throw typeError(route.path, 'lucid-router expects route paths to be a string or regex expression');
31 | }
32 | routes.push(route);
33 | }
34 | }
35 |
36 | export function removeRoute(name: string): void {
37 | var idx = -1;
38 | for (var i = 0, l = routes.length; i < l; i++) {
39 | if (routes[i].name === name) {
40 | idx = i;
41 | break;
42 | }
43 | }
44 | ~idx && routes.splice(idx, 1);
45 | }
46 |
47 | function parseQuery(query) {
48 | var queryArgs = {};
49 | if (query) {
50 | query.split('&')
51 | .filter(keyValStr => !!keyValStr)
52 | .map(keyValStr => keyValStr.split('=')
53 | .map(encoded => decodeURIComponent(encoded)))
54 | .forEach(([key,val]) => key && (queryArgs[key] = val));
55 | }
56 | return queryArgs;
57 | }
58 |
59 | export function match(path: string): ?RouterMatch {
60 | var [pathnameAndQuery,hashAndHashQuery] = path.split('#');
61 | var [pathname,search] = pathnameAndQuery.split('?');
62 | var [hash,hashSearch] = hashAndHashQuery
63 | ? hashAndHashQuery.split('?')
64 | : [];
65 | var queryState = parseQuery([search,hashSearch].join('&'));
66 | for (var route of routes) {
67 | var matchState = route.pattern.match(pathname);
68 | if (!matchState) continue;
69 | return {
70 | route,
71 | pathname,
72 | search: search ? '?'.concat(search) : '',
73 | hash: hash ? '#'.concat(hash) : '',
74 | hashSearch: hashSearch ? '?'.concat(hashSearch) : '',
75 | state: {...queryState, ...matchState}
76 | };
77 | }
78 | return null;
79 | }
80 |
81 | export function navigate(path: ?string, e?: Event, replace?: boolean): void {
82 | path = getFullPath(path || '');
83 | if (hasHistoryApi) {
84 | if (typeof path !== 'string' || !path) throw typeError(path, 'lucid-router.navigate expected a non empty string as its first parameter');
85 | var m = match(path);
86 | if (m && notExternal(m)) {
87 | var location: ?RouterLocation = matchAndPathToLocation(m, path);
88 | if (replace) {
89 | history.replaceState(null, '', path);
90 | } else {
91 | history.pushState(null, '', path);
92 | }
93 |
94 | if (e && e.preventDefault) {
95 | e.preventDefault();
96 | }
97 |
98 | onLocationChange(location);
99 | return;
100 | }
101 | }
102 |
103 | if (window) {
104 | if (!e) window.location = path;
105 | else {
106 | const target = ((e.target : any) : ?Element);
107 | if (!target || target.tagName !== 'A') {
108 | window.location = path;
109 | }
110 | }
111 | }
112 | }
113 |
114 | export function navigatorFor(path: string, replace?: bool): NavigationCallback {
115 | return e => navigate(path, e, replace);
116 | }
117 |
118 | export function pathFor(routeName: string, params?: Object): string {
119 | for (var route of routes) {
120 | if (route.name === routeName) {
121 | return route.pattern.stringify(params);
122 | }
123 | }
124 | throw new Error(`lucid-router.pathFor failed to find a route with the name '${routeName}'`);
125 | }
126 |
127 | export function navigateToRoute(routeName: string, params?: Object, e?: Event): void {
128 | navigate(pathFor(routeName, params), e);
129 | }
130 |
131 | export function navigatorForRoute(routeName: string, params?: Object): NavigationCallback {
132 | return e => navigateToRoute(routeName, params, e);
133 | }
134 |
135 | export function register(callback: RouteMatchCallback): UnregisterLocationChangeCallback {
136 | if (typeof callback !== 'function') throw typeError(callback, 'lucid-router.register expects to be passed a callback function');
137 | locationChangeCallbacks.push(callback);
138 | return function unregister() {
139 | var idx = locationChangeCallbacks.indexOf(callback);
140 | ~idx && locationChangeCallbacks.splice(idx, 1);
141 | };
142 | }
143 |
144 | function onLocationChange(location: ?RouterLocation): void {
145 | locationChangeCallbacks.forEach(cb => cb(location));
146 | }
147 |
148 | function getFullPath(path: string): string {
149 | if (window) {
150 | var a: HTMLAnchorElement = window.document.createElement('a');
151 | a.href = path;
152 | if (!a.host) a.href = a.href; /* IE hack */
153 | if (a.hostname === window.location.hostname) {
154 | path = a.pathname + a.search + a.hash;
155 | if (path[0] !== '/') { /* more IE hacks */
156 | path = '/' + path;
157 | }
158 | } else {
159 | path = a.href;
160 | }
161 | }
162 | return path;
163 | }
164 |
165 | function getWindowPathAndQuery(): ?string {
166 | var {location} = window;
167 | if (!location) return null;
168 | return location.pathname + location.search + location.hash;
169 | }
170 |
171 | export function getLocation(path: ?string): ?RouterLocation {
172 | path = path || getWindowPathAndQuery() || '';
173 | var m: ?RouterMatch = match(path);
174 | return matchAndPathToLocation(m, path);
175 | }
176 |
177 | function matchAndPathToLocation(m: ?RouterMatch, p: string): ?RouterLocation {
178 | return !m
179 | ? null
180 | : {
181 | path: p,
182 | name: m.route.name,
183 | pathname: m.pathname,
184 | search: m.search,
185 | hash: m.hash,
186 | hashSearch: m.hashSearch,
187 | state: m.state,
188 | route: m.route
189 | };
190 | }
191 |
192 | function notExternal(m: RouterMatch): boolean {
193 | var {external} = m.route;
194 | if (typeof external === 'function') {
195 | return !external(m);
196 | } else return !external;
197 | }
198 |
199 | if (hasHistoryApi && window) {
200 | window.addEventListener('popstate', function(e: Event) {
201 | var path = getWindowPathAndQuery() || '';
202 | var m: ?RouterMatch = match(path);
203 | if (m && notExternal(m)) {
204 | var location = matchAndPathToLocation(m, path);
205 | onLocationChange(location);
206 | }
207 | }, false);
208 | }
209 |
210 | function typeError(type: any, msg: string): TypeError {
211 | return new TypeError(msg + ' but got type `' + typeof type + '`!');
212 | }
213 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # lucid-router
2 | A simple (lucid) html5 history-aware router.
3 |
4 | - ideal for universal/isomorphic apps
5 | - tiny (adds less than 5kb to your gzipped bundle)
6 | - progressive enhancement
7 | - fall back on normal redirect behavior when the history API isn't supported, not hash routing
8 | - routes can be added and removed at any time, so load the heavier sections of your app later when the user is idle -- if they navigate to it before the bundle loads it'll just redirect like normal
9 |
10 | More interested in the philosophy than the configuration? [It's at the bottom.](https://github.com/spicydonuts/lucid-router#philosophy)
11 |
12 | Want to dive straight into some examples?
13 | - [Here's a super basic one](https://github.com/spicydonuts/lucid-router/tree/master/examples/basics)
14 | - [And here's one using React](https://github.com/spicydonuts/lucid-router/tree/master/examples/react)
15 |
16 |
17 | ## Configuration
18 | Require the router anywhere it will be used and add routes. Routes are stored inside the `lucid-router` module, so it is safe to destructure or pass the router's functions around without any binding (see below).
19 | ```js
20 | import * as router from 'lucid-router'
21 |
22 | router.addRoutes([
23 | {name: 'profile', path: '/profiles/:profileId'}, // required param
24 | {name: 'home', path: '(/:category)'} // optional param
25 | ])
26 | ```
27 | (Note: `* as router` is required because `lucid-router` does not have a default export. Most of the time you will only import the parts your module actually needs -- see the [ES2015 section](https://github.com/spicydonuts/lucid-router/blob/master/README.md#es2015-module-imports) below)
28 |
29 | You can also set an `external` property on the route definition. This flag can be a boolean or a function which takes an object containing the route matching info and returns a boolean. `false` will allow the normal route transition to occur, while `true` will cancel the location change event and instead navigate the browser directly to the url for a full page load. This setting is mainly for hybrid classic/SPA apps.
30 | ```js
31 | router.addRoutes([
32 | {
33 | name: 'elsewhere',
34 | path: '/non-spa-route',
35 | external: true | false | (matchInfo => true | false)
36 | }
37 | ])
38 | ```
39 |
40 | Also note that routes can be added or removed (see `router.removeRoute(name)`) at any time, allowing different parts of a larger application to asynchronously inject SPA features into an app as it loads. If a navigation occurs before the necessary route exists, a normal browser redirect will occur.
41 |
42 | `getLocation` returns a `RouterLocation` object, or `null` if no routes match. See the [Flow types](https://github.com/spicydonuts/lucid-router/blob/master/lib/lucid-router.t.js) for more info.
43 | Calling `getLocation` with no parameters will look for a `window` object to pull location info from. If `window` isn't available (Node.js server) or you need location data for a route you are not currently on, pass the path to match on into `getLocation`.
44 | ```js
45 | router.getLocation()
46 | router.getLocation(path)
47 | ```
48 |
49 |
50 | ## Subscribing to location changes
51 | This is where the magic happens. Use this function to call `React.render` or wrap it with a Flux store so your components can subscribe to changes. Better yet, reserve a spot for it in your global app state and make your whole app a function from `state -> UI`!
52 | ```js
53 | router.register(location => console.log(location))
54 | ```
55 |
56 | Callbacks can be registered and un-registered at any time, during an app's lifecycle (think dynamically loaded sections of a large app). Unregister by calling the callback returned from `router.register`.
57 |
58 |
59 | ## Navigating
60 | Use `navigate` to perform an immediate transition to a given url (a string). Use `navigatorFor` to build a callback bound to a particular path (equivalent to `e => navigate(path, e)`):
61 | ```js
62 | router.navigate('/path', e) // => pass the event if you want it cancelled for you
63 | router.navigatorFor('/path')(e) // => same as above, curried style (useful for event binding)
64 | ```
65 |
66 | Use `navigateToRoute` to navigate using a route name and params object:
67 | ```js
68 | router.navigateToRoute('profile', {profileId: 5}, e)
69 | router.navigatorForRoute('profile', {profileId: 5})(e)
70 | ```
71 |
72 | This functionality is also available without performing a navigation:
73 | ```js
74 | router.pathFor('profile', {profileId: 5}) // => returns '/profiles/5'
75 | ```
76 |
77 |
78 | ## ES2015 module imports
79 | This is safe and convenient:
80 | ```js
81 | import {pathFor, navigatorFor} from 'lucid-router'
82 |
83 | const link = pathFor('route-name')
84 | const navigator = navigatorFor(link)
85 | ```
86 |
87 |
88 | ## React
89 | Nothing about `lucid-router` is specific to React, but they make a great pair! I've included a helper component for building anchor tags which you can import and use like so:
90 | ```js
91 | import Link from 'lucid-router/link'
92 |
93 | class Nav extends React.Component {
94 | render() {
95 | return (
96 |
100 | )
101 | }
102 | }
103 | ```
104 | The first becomes an `` with an `href` and `onClick` which defer to `pathFor` and `navigatorForRoute`. The second just sets the `href` with the value provided and calls `navigate` when clicked. `Link` is just a shortcut for the most common use cases, so you can use it, ignore it, or make your own!
105 |
106 |
107 | ## Philosophy
108 | Another router?? Yup. I see two problems with the status quo.
109 | Routers are too specialized and they're treated as some separate, almost magical part of getting a 'real' application built.
110 |
111 | Too specialized? What's that mean?
112 | - Angular Router
113 | - Angular UI Router
114 | - Ember Router
115 | - React Router
116 | - Express Router
117 | - Koa Router
118 | - etc...
119 |
120 | Every framework has at least one router dedicated to _just_ that library, plus a few more from the community.
121 | I wanted a tool for abstracting the details from routing away from my app, not a tool that depends on the specific library I've chosen to build my app.
122 |
123 | The second problem is a little harder to quantify, and it comes from the Rails/Django/MVC patterns of views and layouts.
124 | This system tends to create a separation of _technology_ rather than a separation of _concerns_.
125 | A folder for every controller? A folder for every view?
126 | No wonder those folders got too big and we needed to abstract common layouts files...
127 |
128 | What if we organized it by concern: a folder for accounts, a folder for orders, etc.
129 | Then we have a central "app" that decides which of these to sub-apps to hand off to at any given time.
130 | What if that central hub of your app didn't have to care about routing logic?
131 | At first glance, this may not appear to give you much benefit.
132 | You'll still have code _somewhere_ in your app to decide what to render given the current location information.
133 |
134 | The difference is that your application now controls this logic, not a router.
135 | You can render each screen or state of your app without a router.
136 | You can tramsform urls into snapshots of state without an app.
137 | You can render the same way on the server _and_ the client.
138 | This is the power of abstraction -- simplicity and composability.
139 | The "single tool for everything" solutions above sure look powerful at first glance, but in the long run they lock you in to their rules and quirks.
140 |
141 | Think of it this way: if you design your app on my router and then decide it sucks, you can replace it with another one or write your own, provided you can convert the replacement's output to simple data.
142 |
143 | : ]
144 |
145 |
146 | ## Thanks
147 | Thanks to [url-pattern](https://github.com/snd/url-pattern) for all of the route/pattern work!
148 |
149 |
150 | ## Misc
151 | What about `router5`?
152 |
153 | It looks great! There are three reasons I wrote this router anyway:
154 |
155 | 1. I didn't know `router5` existed when I initially wrote this for a work app, but even if I had...
156 | 2. `router5` is more complicated. I love keeping things simple.
157 | 3. I needed really smooth fallback on regular redirects when html5 history isn't supported, not hash routing fallbacks. `lucid-router` can also be used on non-SPA apps just fine without losing the routing info.. just mark all your routes as `external`!
158 |
--------------------------------------------------------------------------------
/dist/router.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | Object.defineProperty(exports, "__esModule", {
4 | value: true
5 | });
6 |
7 | var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
8 |
9 | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
10 |
11 | var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
12 |
13 | exports.addRoutes = addRoutes;
14 | exports.removeRoute = removeRoute;
15 | exports.match = match;
16 | exports.navigate = navigate;
17 | exports.navigatorFor = navigatorFor;
18 | exports.pathFor = pathFor;
19 | exports.navigateToRoute = navigateToRoute;
20 | exports.navigatorForRoute = navigatorForRoute;
21 | exports.register = register;
22 | exports.getLocation = getLocation;
23 |
24 | var _urlPattern = require('url-pattern');
25 |
26 | var _urlPattern2 = _interopRequireDefault(_urlPattern);
27 |
28 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
29 |
30 | var window = global.window;
31 | var history = global.history;
32 |
33 | var hasHistoryApi = window !== undefined && history !== undefined && typeof history.pushState === 'function';
34 |
35 | var locationChangeCallbacks = [];
36 |
37 | var routes = [];
38 |
39 | function addRoutes(newRoutes) {
40 | if (!(newRoutes instanceof Array)) throw typeError(routes, 'lucid-router expects to be passed a routing array as its first parameter');
41 | var _iteratorNormalCompletion = true;
42 | var _didIteratorError = false;
43 | var _iteratorError = undefined;
44 |
45 | try {
46 | for (var _iterator = newRoutes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
47 | var route = _step.value;
48 |
49 | if (route === null || !(route instanceof Object)) throw typeError(routes, 'lucid-router expects each route definition to be an object');
50 | route.path = route.path || null;
51 | route.name = route.name || null;
52 | route.external = typeof route.external === 'function' ? route.external : !!route.external;
53 | try {
54 | route.pattern = new _urlPattern2.default(route.path);
55 | } catch (err) {
56 | throw typeError(route.path, 'lucid-router expects route paths to be a string or regex expression');
57 | }
58 | routes.push(route);
59 | }
60 | } catch (err) {
61 | _didIteratorError = true;
62 | _iteratorError = err;
63 | } finally {
64 | try {
65 | if (!_iteratorNormalCompletion && _iterator.return) {
66 | _iterator.return();
67 | }
68 | } finally {
69 | if (_didIteratorError) {
70 | throw _iteratorError;
71 | }
72 | }
73 | }
74 | }
75 |
76 | function removeRoute(name) {
77 | var idx = -1;
78 | for (var i = 0, l = routes.length; i < l; i++) {
79 | if (routes[i].name === name) {
80 | idx = i;
81 | break;
82 | }
83 | }
84 | ~idx && routes.splice(idx, 1);
85 | }
86 |
87 | function parseQuery(query) {
88 | var queryArgs = {};
89 | if (query) {
90 | query.split('&').filter(function (keyValStr) {
91 | return !!keyValStr;
92 | }).map(function (keyValStr) {
93 | return keyValStr.split('=').map(function (encoded) {
94 | return decodeURIComponent(encoded);
95 | });
96 | }).forEach(function (_ref) {
97 | var _ref2 = _slicedToArray(_ref, 2);
98 |
99 | var key = _ref2[0];
100 | var val = _ref2[1];
101 | return key && (queryArgs[key] = val);
102 | });
103 | }
104 | return queryArgs;
105 | }
106 |
107 | function match(path) {
108 | var _path$split = path.split('#');
109 |
110 | var _path$split2 = _slicedToArray(_path$split, 2);
111 |
112 | var pathnameAndQuery = _path$split2[0];
113 | var hashAndHashQuery = _path$split2[1];
114 |
115 | var _pathnameAndQuery$spl = pathnameAndQuery.split('?');
116 |
117 | var _pathnameAndQuery$spl2 = _slicedToArray(_pathnameAndQuery$spl, 2);
118 |
119 | var pathname = _pathnameAndQuery$spl2[0];
120 | var search = _pathnameAndQuery$spl2[1];
121 |
122 | var _ref3 = hashAndHashQuery ? hashAndHashQuery.split('?') : [];
123 |
124 | var _ref4 = _slicedToArray(_ref3, 2);
125 |
126 | var hash = _ref4[0];
127 | var hashSearch = _ref4[1];
128 |
129 | var queryState = parseQuery([search, hashSearch].join('&'));
130 | var _iteratorNormalCompletion2 = true;
131 | var _didIteratorError2 = false;
132 | var _iteratorError2 = undefined;
133 |
134 | try {
135 | for (var _iterator2 = routes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
136 | var route = _step2.value;
137 |
138 | var matchState = route.pattern.match(pathname);
139 | if (!matchState) continue;
140 | return {
141 | route: route,
142 | pathname: pathname,
143 | search: search ? '?'.concat(search) : '',
144 | hash: hash ? '#'.concat(hash) : '',
145 | hashSearch: hashSearch ? '?'.concat(hashSearch) : '',
146 | state: _extends({}, queryState, matchState)
147 | };
148 | }
149 | } catch (err) {
150 | _didIteratorError2 = true;
151 | _iteratorError2 = err;
152 | } finally {
153 | try {
154 | if (!_iteratorNormalCompletion2 && _iterator2.return) {
155 | _iterator2.return();
156 | }
157 | } finally {
158 | if (_didIteratorError2) {
159 | throw _iteratorError2;
160 | }
161 | }
162 | }
163 |
164 | return null;
165 | }
166 |
167 | function navigate(path, e, replace) {
168 | path = getFullPath(path || '');
169 | if (hasHistoryApi) {
170 | if (typeof path !== 'string' || !path) throw typeError(path, 'lucid-router.navigate expected a non empty string as its first parameter');
171 | var m = match(path);
172 | if (m && notExternal(m)) {
173 | var location = matchAndPathToLocation(m, path);
174 | if (replace) {
175 | history.replaceState(null, '', path);
176 | } else {
177 | history.pushState(null, '', path);
178 | }
179 |
180 | if (e && e.preventDefault) {
181 | e.preventDefault();
182 | }
183 |
184 | onLocationChange(location);
185 | return;
186 | }
187 | }
188 |
189 | if (window) {
190 | if (!e) window.location = path;else {
191 | var target = e.target;
192 | if (!target || target.tagName !== 'A') {
193 | window.location = path;
194 | }
195 | }
196 | }
197 | }
198 |
199 | function navigatorFor(path, replace) {
200 | return function (e) {
201 | return navigate(path, e, replace);
202 | };
203 | }
204 |
205 | function pathFor(routeName, params) {
206 | var _iteratorNormalCompletion3 = true;
207 | var _didIteratorError3 = false;
208 | var _iteratorError3 = undefined;
209 |
210 | try {
211 | for (var _iterator3 = routes[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
212 | var route = _step3.value;
213 |
214 | if (route.name === routeName) {
215 | return route.pattern.stringify(params);
216 | }
217 | }
218 | } catch (err) {
219 | _didIteratorError3 = true;
220 | _iteratorError3 = err;
221 | } finally {
222 | try {
223 | if (!_iteratorNormalCompletion3 && _iterator3.return) {
224 | _iterator3.return();
225 | }
226 | } finally {
227 | if (_didIteratorError3) {
228 | throw _iteratorError3;
229 | }
230 | }
231 | }
232 |
233 | throw new Error('lucid-router.pathFor failed to find a route with the name \'' + routeName + '\'');
234 | }
235 |
236 | function navigateToRoute(routeName, params, e) {
237 | navigate(pathFor(routeName, params), e);
238 | }
239 |
240 | function navigatorForRoute(routeName, params) {
241 | return function (e) {
242 | return navigateToRoute(routeName, params, e);
243 | };
244 | }
245 |
246 | function register(callback) {
247 | if (typeof callback !== 'function') throw typeError(callback, 'lucid-router.register expects to be passed a callback function');
248 | locationChangeCallbacks.push(callback);
249 | return function unregister() {
250 | var idx = locationChangeCallbacks.indexOf(callback);
251 | ~idx && locationChangeCallbacks.splice(idx, 1);
252 | };
253 | }
254 |
255 | function onLocationChange(location) {
256 | locationChangeCallbacks.forEach(function (cb) {
257 | return cb(location);
258 | });
259 | }
260 |
261 | function getFullPath(path) {
262 | if (window) {
263 | var a = window.document.createElement('a');
264 | a.href = path;
265 | if (!a.host) a.href = a.href; /* IE hack */
266 | if (a.hostname === window.location.hostname) {
267 | path = a.pathname + a.search + a.hash;
268 | if (path[0] !== '/') {
269 | /* more IE hacks */
270 | path = '/' + path;
271 | }
272 | } else {
273 | path = a.href;
274 | }
275 | }
276 | return path;
277 | }
278 |
279 | function getWindowPathAndQuery() {
280 | var location = window.location;
281 |
282 | if (!location) return null;
283 | return location.pathname + location.search + location.hash;
284 | }
285 |
286 | function getLocation(path) {
287 | path = path || getWindowPathAndQuery() || '';
288 | var m = match(path);
289 | return matchAndPathToLocation(m, path);
290 | }
291 |
292 | function matchAndPathToLocation(m, p) {
293 | return !m ? null : {
294 | path: p,
295 | name: m.route.name,
296 | pathname: m.pathname,
297 | search: m.search,
298 | hash: m.hash,
299 | hashSearch: m.hashSearch,
300 | state: m.state,
301 | route: m.route
302 | };
303 | }
304 |
305 | function notExternal(m) {
306 | var external = m.route.external;
307 |
308 | if (typeof external === 'function') {
309 | return !external(m);
310 | } else return !external;
311 | }
312 |
313 | if (hasHistoryApi && window) {
314 | window.addEventListener('popstate', function (e) {
315 | var path = getWindowPathAndQuery() || '';
316 | var m = match(path);
317 | if (m && notExternal(m)) {
318 | var location = matchAndPathToLocation(m, path);
319 | onLocationChange(location);
320 | }
321 | }, false);
322 | }
323 |
324 | function typeError(type, msg) {
325 | return new TypeError(msg + ' but got type `' + (typeof type === 'undefined' ? 'undefined' : _typeof(type)) + '`!');
326 | }
327 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
341 |
--------------------------------------------------------------------------------