├── src ├── index.js ├── Redirect.js ├── Switch.js ├── Route.js ├── parseRoute.js ├── Link.js └── location.js ├── .gitignore ├── .travis.yml ├── test ├── ts │ ├── tsconfig.json │ └── index.tsx ├── link.test.js ├── switch.test.js ├── route.test.js └── index.test.js ├── LICENSE.md ├── index.d.ts ├── package.json └── README.md /src/index.js: -------------------------------------------------------------------------------- 1 | export { Link } from "./Link" 2 | export { Route } from "./Route" 3 | export { Switch } from "./Switch" 4 | export { Redirect } from "./Redirect" 5 | export { location } from "./location" 6 | -------------------------------------------------------------------------------- /src/Redirect.js: -------------------------------------------------------------------------------- 1 | export function Redirect(props) { 2 | return function(state, actions) { 3 | var location = state.location 4 | history.replaceState(props.from || location.pathname, "", props.to) 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IDE 2 | .idea/ 3 | .vscode/ 4 | 5 | # Logs 6 | *.log* 7 | yarn.lock 8 | package-lock.json 9 | 10 | # Misc 11 | example 12 | node_modules 13 | coverage 14 | *.xml 15 | 16 | # Dist 17 | *.gz 18 | dist/ 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "8" 4 | - "7" 5 | 6 | env: 7 | - NODE_ENV=development 8 | 9 | before_install: 10 | - npm i -g codecov 11 | 12 | install: 13 | - npm install 14 | 15 | script: 16 | - npm test 17 | - codecov 18 | 19 | notifications: 20 | email: false 21 | -------------------------------------------------------------------------------- /src/Switch.js: -------------------------------------------------------------------------------- 1 | export function Switch(props, children) { 2 | return function(state, actions) { 3 | var child, 4 | i = 0 5 | while ( 6 | !(child = children[i] && children[i](state, actions)) && 7 | i < children.length 8 | ) 9 | i++ 10 | return child 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /test/ts/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "strict": true, 4 | "noEmit": true, 5 | "jsx": "react", 6 | "jsxFactory": "h", 7 | "baseUrl": "../..", 8 | "paths": { 9 | "router": ["src", "index.d.ts"], 10 | "hyperapp": ["./node_modules/hyperapp/hyperapp.d.ts"] 11 | 12 | }, 13 | "target": "es6" 14 | }, 15 | "include": ["*.ts", "*.tsx", "**/*.ts", "**/*.tsx"] 16 | } 17 | -------------------------------------------------------------------------------- /src/Route.js: -------------------------------------------------------------------------------- 1 | import { parseRoute } from "./parseRoute" 2 | 3 | export function Route(props) { 4 | return function(state, actions) { 5 | var location = state.location 6 | var match = parseRoute(props.path, location.pathname, { 7 | exact: !props.parent 8 | }) 9 | 10 | return ( 11 | match && 12 | props.render({ 13 | match: match, 14 | location: location 15 | }) 16 | ) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /test/link.test.js: -------------------------------------------------------------------------------- 1 | import { Link } from "../src" 2 | 3 | test('Link passes given attributes except "to" and "location" to underlying element', () => { 4 | const vnode = Link({ to: "/path", pass: "through", location })({}, {}) 5 | expect(vnode.attributes.to).toBeUndefined() 6 | expect(vnode.attributes.location).toBeUndefined() 7 | expect(vnode.attributes.href).toEqual("/path") 8 | expect(vnode.attributes.pass).toEqual("through") 9 | }) 10 | 11 | test("Calling onclick of VNode transparently calls Link's onclick prop", () => { 12 | const onclickProp = jest.fn() 13 | const vnode = Link({ onclick: onclickProp })({}, {}) 14 | const event = new Object() 15 | expect(vnode.attributes.onclick).not.toBe(onclickProp) 16 | vnode.attributes.onclick(event) 17 | expect(onclickProp).toBeCalledWith(event) 18 | }) 19 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright © 2017-present [Jorge Bucaran](https://github.com/jorgebucaran) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /src/parseRoute.js: -------------------------------------------------------------------------------- 1 | function createMatch(isExact, path, url, params) { 2 | return { 3 | isExact: isExact, 4 | path: path, 5 | url: url, 6 | params: params 7 | } 8 | } 9 | 10 | function trimTrailingSlash(url) { 11 | for (var len = url.length; "/" === url[--len]; ); 12 | return url.slice(0, len + 1) 13 | } 14 | 15 | function decodeParam(val) { 16 | try { 17 | return decodeURIComponent(val) 18 | } catch (e) { 19 | return val 20 | } 21 | } 22 | 23 | export function parseRoute(path, url, options) { 24 | if (path === url || !path) { 25 | return createMatch(path === url, path, url) 26 | } 27 | 28 | var exact = options && options.exact 29 | var paths = trimTrailingSlash(path).split("/") 30 | var urls = trimTrailingSlash(url).split("/") 31 | 32 | if (paths.length > urls.length || (exact && paths.length < urls.length)) { 33 | return 34 | } 35 | 36 | for (var i = 0, params = {}, len = paths.length, url = ""; i < len; i++) { 37 | if (":" === paths[i][0]) { 38 | params[paths[i].slice(1)] = urls[i] = decodeParam(urls[i]) 39 | } else if (paths[i] !== urls[i]) { 40 | return 41 | } 42 | url += urls[i] + "/" 43 | } 44 | 45 | return createMatch(false, path, url.slice(0, -1), params) 46 | } 47 | -------------------------------------------------------------------------------- /src/Link.js: -------------------------------------------------------------------------------- 1 | import { h } from "hyperapp" 2 | 3 | function getOrigin(loc) { 4 | return loc.protocol + "//" + loc.hostname + (loc.port ? ":" + loc.port : "") 5 | } 6 | 7 | function isExternal(anchorElement) { 8 | // Location.origin and HTMLAnchorElement.origin are not 9 | // supported by IE and Safari. 10 | return getOrigin(location) !== getOrigin(anchorElement) 11 | } 12 | 13 | export function Link(props, children) { 14 | return function(state, actions) { 15 | var to = props.to 16 | var location = state.location 17 | var onclick = props.onclick 18 | delete props.to 19 | delete props.location 20 | 21 | props.href = to 22 | props.onclick = function(e) { 23 | if (onclick) { 24 | onclick(e) 25 | } 26 | if ( 27 | e.defaultPrevented || 28 | e.button !== 0 || 29 | e.altKey || 30 | e.metaKey || 31 | e.ctrlKey || 32 | e.shiftKey || 33 | props.target === "_blank" || 34 | isExternal(e.currentTarget) 35 | ) { 36 | } else { 37 | e.preventDefault() 38 | 39 | if (to !== location.pathname) { 40 | history.pushState(location.pathname, "", to) 41 | } 42 | } 43 | } 44 | 45 | return h("a", props, children) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/location.js: -------------------------------------------------------------------------------- 1 | function wrapHistory(keys) { 2 | return keys.reduce(function(next, key) { 3 | var fn = history[key] 4 | 5 | history[key] = function(data, title, url) { 6 | fn.call(this, data, title, url) 7 | dispatchEvent(new CustomEvent("pushstate", { detail: data })) 8 | } 9 | 10 | return function() { 11 | history[key] = fn 12 | next && next() 13 | } 14 | }, null) 15 | } 16 | 17 | export var location = { 18 | state: { 19 | pathname: window.location.pathname, 20 | previous: window.location.pathname 21 | }, 22 | actions: { 23 | go: function(pathname) { 24 | history.pushState(null, "", pathname) 25 | }, 26 | set: function(data) { 27 | return data 28 | } 29 | }, 30 | subscribe: function(actions) { 31 | function handleLocationChange(e) { 32 | actions.set({ 33 | pathname: window.location.pathname, 34 | previous: e.detail 35 | ? (window.location.previous = e.detail) 36 | : window.location.previous 37 | }) 38 | } 39 | 40 | var unwrap = wrapHistory(["pushState", "replaceState"]) 41 | 42 | addEventListener("pushstate", handleLocationChange) 43 | addEventListener("popstate", handleLocationChange) 44 | 45 | return function() { 46 | removeEventListener("pushstate", handleLocationChange) 47 | removeEventListener("popstate", handleLocationChange) 48 | unwrap() 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import { Children, VNode } from "hyperapp"; 2 | 3 | /** Link */ 4 | interface LinkProps { 5 | to: string; 6 | location?: Location; 7 | [attributeName: string]: any 8 | } 9 | export function Link(props: LinkProps, children: Children): VNode; 10 | 11 | /** Route */ 12 | interface Match

{ 13 | url: string; 14 | path: string; 15 | isExact: boolean; 16 | params: P; 17 | } 18 | interface RenderProps

{ 19 | location: Location; 20 | match: Match

; 21 | } 22 | 23 | interface RouteProps

{ 24 | parent?: boolean; 25 | path?: string; 26 | location?: Location; 27 | render: (props: RenderProps

) => VNode>; 28 | } 29 | 30 | export function Route

( 31 | props: RouteProps

32 | ): VNode> | null; 33 | 34 | /**Switch */ 35 | export function Switch

( 36 | props: object, 37 | children: Array>> 38 | ): VNode; 39 | 40 | /** Redirect */ 41 | interface RedirectProps extends LinkProps { 42 | from?: string 43 | } 44 | export function Redirect(props: RedirectProps): VNode; 45 | 46 | /** location */ 47 | interface LocationState { 48 | pathname: string; 49 | previous: string; 50 | } 51 | 52 | interface LocationActions { 53 | go: (pathname: string) => void; 54 | } 55 | interface RouterLocation { 56 | state: LocationState; 57 | actions: LocationActions; 58 | subscribe: (actions: LocationActions) => Function; 59 | } 60 | 61 | export declare const location: RouterLocation; 62 | -------------------------------------------------------------------------------- /test/switch.test.js: -------------------------------------------------------------------------------- 1 | import { Switch } from "../src/Switch" 2 | 3 | test("Switch expects children are implemented as lazy components", () => { 4 | const state = new Object() 5 | const actions = new Object() 6 | const child = jest.fn() 7 | Switch(null, [child])(state, actions) 8 | expect(child.mock.calls.length).toBe(1) 9 | expect(child).toBeCalledWith(state, actions) 10 | }) 11 | 12 | test("Switch returns only the first truthy child", () => { 13 | const state = new Object() 14 | const actions = new Object() 15 | const children = [ 16 | jest.fn(() => 0), 17 | jest.fn(() => null), 18 | jest.fn(() => "first truthy value"), 19 | jest.fn(() => "another truthy") 20 | ] 21 | expect(Switch(null, children)(state, actions)).toEqual("first truthy value") 22 | expect(children[0]).toBeCalledWith(state, actions) 23 | expect(children[1]).toBeCalledWith(state, actions) 24 | expect(children[2]).toBeCalledWith(state, actions) 25 | expect(children[3]).not.toBeCalled() 26 | }) 27 | 28 | test("Switch returns falsy when all children falsy", () => { 29 | const state = new Object() 30 | const actions = new Object() 31 | const children = [ 32 | jest.fn(() => 0), 33 | jest.fn(() => ""), 34 | jest.fn(() => false), 35 | jest.fn(() => null) 36 | ] 37 | expect(Switch(null, children)(state, actions)).toBeFalsy() 38 | children.forEach(child => expect(child).toBeCalledWith(state, actions)) 39 | }) 40 | 41 | test("Switch returns falsy when children is empty", () => { 42 | expect(Switch(null, [])({}, {})).toBeFalsy() 43 | }) 44 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@hyperapp/router", 3 | "description": "Declarative routing for Hyperapp V1 using the History API.", 4 | "version": "0.7.2", 5 | "main": "dist/router.js", 6 | "module": "src/index.js", 7 | "typings": "index.d.ts", 8 | "license": "MIT", 9 | "repository": "hyperapp/router", 10 | "files": [ 11 | "src", 12 | "dist", 13 | "index.d.ts" 14 | ], 15 | "author": "Jorge Bucaran", 16 | "keywords": [ 17 | "hyperapp", 18 | "router", 19 | "navigation", 20 | "history" 21 | ], 22 | "scripts": { 23 | "test": "jest --coverage --no-cache&& tsc -p test/ts", 24 | "build": "npm run bundle && npm run minify", 25 | "bundle": "rollup -i src/index.js -o dist/router.js -f umd -mn hyperappRouter -g hyperapp:hyperapp", 26 | "minify": "uglifyjs dist/router.js -o dist/router.js -mc pure_funcs=['Object.defineProperty'] --source-map includeSources,url=router.js.map", 27 | "prepublish": "npm run build", 28 | "format": "prettier --semi false --write '{src,test}/**/*.js'", 29 | "release": "npm run build && npm test && git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags && npm publish" 30 | }, 31 | "babel": { 32 | "presets": [ 33 | "env" 34 | ], 35 | "plugins": [ 36 | [ 37 | "transform-react-jsx", 38 | { 39 | "pragma": "h" 40 | } 41 | ] 42 | ] 43 | }, 44 | "jest": { 45 | "testURL": "http://localhost" 46 | }, 47 | "devDependencies": { 48 | "babel-jest": "^22.4.3", 49 | "babel-plugin-transform-react-jsx": "^6.24.1", 50 | "babel-preset-env": "^1.6.1", 51 | "hyperapp": "^1.2.5", 52 | "jest": "^22.4.3", 53 | "prettier": "^1.11.1", 54 | "rollup": "^0.57.1", 55 | "uglify-js": "^3.3.16", 56 | "typescript": "2.8.1" 57 | }, 58 | "peerDependencies": { 59 | "hyperapp": "1.2.5" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /test/ts/index.tsx: -------------------------------------------------------------------------------- 1 | import { h, app, View, ActionsType } from "hyperapp"; 2 | import { 3 | Link, 4 | Route, 5 | RenderProps, 6 | Switch, 7 | location, 8 | LocationActions, 9 | LocationState 10 | } from "router"; 11 | 12 | const Home = () =>

Home

; 13 | const About = () =>

About

; 14 | const Topic = ({ match }: RenderProps<{ topicId: string }>) => ( 15 |

{match.params.topicId}

16 | ); 17 | const TopicsView = ({ match }: RenderProps<{ topicId: string }>) => ( 18 |
19 |

Topics

20 |
    21 |
  • 22 | Components 23 |
  • 24 |
  • 25 | Single State Tree 26 |
  • 27 |
  • 28 | Routing 29 |
  • 30 |
31 | 32 | {match.isExact &&

Please select a topic.

} 33 | 34 | 35 |
36 | ); 37 | 38 | interface RouteState { 39 | location: LocationState; 40 | } 41 | const state: RouteState = { 42 | location: location.state 43 | }; 44 | 45 | interface RouteActions { 46 | location: LocationActions; 47 | } 48 | 49 | const routeActions: ActionsType = { 50 | location: location.actions 51 | }; 52 | const view: View = (state: RouteState) => ( 53 |
54 |
    55 |
  • 56 | Home 57 |
  • 58 |
  • 59 | About 60 |
  • 61 |
  • 62 | Topics 63 |
  • 64 |
65 | 66 |
67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 |
76 | 77 | 78 | 79 |
80 | ); 81 | 82 | const main = app(state, routeActions, view, document.body); 83 | 84 | const unsubscribe = location.subscribe(main.location); 85 | -------------------------------------------------------------------------------- /test/route.test.js: -------------------------------------------------------------------------------- 1 | import { Route } from "../src/Route" 2 | 3 | test("Route is a lazy component", () => { 4 | expect(Route(null, [])).toBeInstanceOf(Function) 5 | }) 6 | 7 | test("Route returns falsy if it doesn't match to current location", () => { 8 | const state = { location: { pathname: "/articles" } } 9 | const actions = {} 10 | const render = jest.fn() 11 | expect(Route({ path: "/users", render }, [])(state, actions)).toBeFalsy() 12 | expect(render).not.toBeCalled() 13 | }) 14 | 15 | test("Route returns result of render prop if it exactly matches to current location", () => { 16 | expect.assertions(3) 17 | const state = { location: { pathname: "/users" } } 18 | const actions = {} 19 | const render = jest.fn(({ match }) => { 20 | expect(match.isExact).toBe(true) 21 | return "result" 22 | }) 23 | expect(Route({ path: "/users", render }, [])(state, actions)).toEqual( 24 | "result" 25 | ) 26 | expect(render).toBeCalled() 27 | }) 28 | 29 | test("Route returns result of render prop if it matches to current location", () => { 30 | expect.assertions(4) 31 | const state = { location: { pathname: "/users/1" } } 32 | const actions = {} 33 | const render = jest.fn(({ match }) => { 34 | expect(match.isExact).toBe(false) 35 | expect(match.params).toEqual({ id: "1" }) 36 | return "result" 37 | }) 38 | expect(Route({ path: "/users/:id", render }, [])(state, actions)).toEqual( 39 | "result" 40 | ) 41 | expect(render).toBeCalled() 42 | }) 43 | 44 | test("Route without path prop matches to every location", () => { 45 | const render = () => true 46 | expect(Route({ render }, [])({ location: { pathname: "/" } })).toBe(true) 47 | expect(Route({ render }, [])({ location: { pathname: "/users" } })).toBe(true) 48 | }) 49 | 50 | test("Route decodes encoded URI", () => { 51 | expect.assertions(1) 52 | const state = { location: { pathname: "/foo/caf%C3%A9/bar/baz" } } 53 | const actions = {} 54 | const render = ({ match }) => { 55 | expect(match.params).toEqual({ foo: "café", bar: "baz" }) 56 | } 57 | Route({ path: "/foo/:foo/bar/:bar", render }, [])(state, actions) 58 | }) 59 | 60 | test("Route ignores url params containing invalid character sequences", () => { 61 | expect.assertions(3) 62 | const invalid = "%E0%A4%A" 63 | expect(() => decodeURI(invalid)).toThrow(URIError) 64 | const state = { location: { pathname: `/foo/${invalid}/bar/baz` } } 65 | const actions = {} 66 | const render = ({ match }) => { 67 | expect(match.params).toEqual({ foo: invalid, bar: "baz" }) 68 | } 69 | expect(() => 70 | Route({ path: "/foo/:foo/bar/:bar", render }, [])(state, actions) 71 | ).not.toThrowError() 72 | }) 73 | -------------------------------------------------------------------------------- /test/index.test.js: -------------------------------------------------------------------------------- 1 | import { h, app } from "hyperapp" 2 | import { Route, Link, Redirect, location } from "../src" 3 | 4 | const wait = async ms => new Promise(resolve => setTimeout(resolve, ms)) 5 | const click = e => e.dispatchEvent(new MouseEvent("click", { button: 0 })) 6 | 7 | let state, actions, unsubscribe 8 | 9 | beforeEach(() => { 10 | state = { location: location.state } 11 | actions = { 12 | location: location.actions, 13 | getLocation: () => state => state.location 14 | } 15 | unsubscribe = null 16 | }) 17 | 18 | afterEach(() => { 19 | unsubscribe && unsubscribe() 20 | }) 21 | 22 | test("Transition by location.go()", async done => { 23 | const spy = jest.fn() 24 | const view = () => 25 | const main = app(state, actions, view, document.body) 26 | unsubscribe = location.subscribe(main.location) 27 | await wait(0) 28 | expect(spy).not.toBeCalled() 29 | main.location.go("/test") 30 | await wait(0) 31 | expect(spy).toBeCalled() 32 | done() 33 | }) 34 | 35 | test("Transition by clicking Link", async done => { 36 | const spy = jest.fn() 37 | const view = () => ( 38 |
39 | 40 | 41 |
42 | ) 43 | const main = app(state, actions, view, document.body) 44 | unsubscribe = location.subscribe(main.location) 45 | await wait(0) 46 | expect(spy).not.toBeCalled() 47 | click(document.body.getElementsByTagName("a")[0]) 48 | await wait(0) 49 | expect(spy).toBeCalled() 50 | // Clicking the same link again doesn't cause transition. 51 | const count = spy.mock.calls.length 52 | click(document.body.getElementsByTagName("a")[0]) 53 | await wait(0) 54 | expect(spy).toHaveBeenCalledTimes(count) 55 | done() 56 | }) 57 | 58 | test('Click Link with target="_blank"', async done => { 59 | const spy = jest.fn() 60 | const view = () => ( 61 |
62 | 63 | 64 |
65 | ) 66 | const main = app(state, actions, view, document.body) 67 | unsubscribe = location.subscribe(main.location) 68 | await wait(0) 69 | click(document.body.getElementsByTagName("a")[0]) 70 | await wait(0) 71 | expect(spy).not.toBeCalled() 72 | done() 73 | }) 74 | 75 | test("Click external Link", async done => { 76 | const spy = jest.fn() 77 | const view = () => 78 | const main = app(state, actions, view, document.body) 79 | unsubscribe = location.subscribe(main.location) 80 | await wait(0) 81 | expect(main.getLocation().pathname).toEqual("/") 82 | click(document.body.getElementsByTagName("a")[0]) 83 | await wait(0) 84 | expect(main.getLocation().pathname).toEqual("/") 85 | done() 86 | }) 87 | 88 | test("Transition by clicking Link including non alphanumeric characters", async done => { 89 | const spy = jest.fn() 90 | const view = () => ( 91 |
92 | 93 | 94 |
95 | ) 96 | const main = app(state, actions, view, document.body) 97 | unsubscribe = location.subscribe(main.location) 98 | await wait(0) 99 | expect(spy).not.toBeCalled() 100 | click(document.body.getElementsByTagName("a")[0]) 101 | await wait(0) 102 | expect(spy).toBeCalled() 103 | expect(spy.mock.calls[0][0].match.params).toEqual({ id: "café" }) 104 | expect(main.getLocation().pathname).toEqual("/test/caf%C3%A9") 105 | done() 106 | }) 107 | 108 | test("Transition by rendering Redirect", async done => { 109 | const spy = jest.fn() 110 | const view = () => ( 111 |
112 | } /> 113 | 114 |
115 | ) 116 | const main = app(state, actions, view, document.body) 117 | unsubscribe = location.subscribe(main.location) 118 | await wait(0) 119 | expect(spy).not.toBeCalled() 120 | main.location.go("/test") 121 | await wait(0) 122 | expect(spy).toBeCalled() 123 | done() 124 | }) 125 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hyperapp Router 2 | 3 | [![Travis CI](https://img.shields.io/travis/hyperapp/router/master.svg)](https://travis-ci.org/hyperapp/router) [![Codecov](https://img.shields.io/codecov/c/github/hyperapp/router/master.svg)](https://codecov.io/gh/hyperapp/router) [![npm](https://img.shields.io/npm/v/@hyperapp/router.svg)](https://www.npmjs.org/package/hyperapp) [![Slack](https://hyperappjs.herokuapp.com/badge.svg)](https://hyperappjs.herokuapp.com "Join us") 4 | 5 | Hyperapp Router provides declarative routing for [Hyperapp](https://github.com/hyperapp/hyperapp) using the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History). 6 | 7 | [Try this example online](http://hyperapp-router.surge.sh). 8 | 9 | ```jsx 10 | import { h, app } from "hyperapp" 11 | import { Link, Route, location } from "@hyperapp/router" 12 | 13 | const Home = () =>

Home

14 | const About = () =>

About

15 | const Topic = ({ match }) =>

{match.params.topicId}

16 | const TopicsView = ({ match }) => ( 17 |
18 |

Topics

19 |
    20 |
  • 21 | Components 22 |
  • 23 |
  • 24 | Single State Tree 25 |
  • 26 |
  • 27 | Routing 28 |
  • 29 |
30 | 31 | {match.isExact &&

Please select a topic.

} 32 | 33 | 34 |
35 | ) 36 | 37 | const state = { 38 | location: location.state 39 | } 40 | 41 | const actions = { 42 | location: location.actions 43 | } 44 | 45 | const view = state => ( 46 |
47 |
    48 |
  • 49 | Home 50 |
  • 51 |
  • 52 | About 53 |
  • 54 |
  • 55 | Topics 56 |
  • 57 |
58 | 59 |
60 | 61 | 62 | 63 | 64 |
65 | ) 66 | 67 | const main = app(state, actions, view, document.body) 68 | 69 | const unsubscribe = location.subscribe(main.location) 70 | ``` 71 | 72 | ## Installation 73 | 74 |
 75 | npm i @hyperapp/router
 76 | 
77 | 78 | Then with a module bundler like Rollup or Webpack, use as you would anything else. 79 | 80 | ```jsx 81 | import { Link, Route, Switch, Redirect, location } from "@hyperapp/router" 82 | ``` 83 | 84 | If you don't want to set up a build environment, you can download Hyperapp Router from a CDN like [unpkg.com](https://unpkg.com/@hyperapp/router) and it will be globally available through the window.hyperappRouter object. We support all ES5-compliant browsers, including Internet Explorer 10 and above. 85 | 86 | ## Usage 87 | 88 | Add the `location` module to your state and actions and start the application. 89 | 90 | ```jsx 91 | const state = { 92 | location: location.state 93 | } 94 | 95 | const actions = { 96 | location: location.actions 97 | } 98 | 99 | const main = app( 100 | state, 101 | actions, 102 | (state, actions) =>

Hello!

} />, 103 | document.body 104 | ) 105 | ``` 106 | 107 | Then call `subscribe` to listen to location change events. 108 | 109 | ```js 110 | const unsubscribe = location.subscribe(main.location) 111 | ``` 112 | 113 | ## Components 114 | 115 | ### Route 116 | 117 | Render a component when the given path matches the current [window location](https://developer.mozilla.org/en-US/docs/Web/API/Location). A route without a path is always a match. Routes can have nested routes. 118 | 119 | ```jsx 120 | 121 | 122 | 123 | ``` 124 | 125 | #### parent 126 | 127 | The route contains child routes. 128 | 129 | #### path 130 | 131 | The path to match against the current location. 132 | 133 | #### render 134 | 135 | The component to render when there is a match. 136 | 137 | ### Render Props 138 | 139 | Rendered components are passed the following props. 140 | 141 | ```jsx 142 | const RouteInfo = ({ location, match }) => ( 143 |
144 |

Url: {match.url}

145 |

Path: {match.path}

146 |
    147 | {Object.keys(match.params).map(key => ( 148 |
  • 149 | {key}: {match.params[key]} 150 |
  • 151 | ))} 152 |
153 |

Location: {location.pathname}

154 |
155 | ) 156 | ``` 157 | 158 | #### location 159 | 160 | The [window location](https://developer.mozilla.org/en-US/docs/Web/API/Location). 161 | 162 | #### match.url 163 | 164 | The matched part of the url. Use to assemble links inside routes. See [Link](#link). 165 | 166 | #### match.path 167 | 168 | The route [path](#path). 169 | 170 | #### match.isExact 171 | 172 | Indicates whether the given path matched the url exactly or not. 173 | 174 | ### Link 175 | 176 | Use the Link component to update the current [window location](https://developer.mozilla.org/en-US/docs/Web/API/Location) and navigate between views without a page reload. The new location will be pushed to the history stack using `history.pushState`. 177 | 178 | ```jsx 179 | const Navigation = ( 180 |
    181 |
  • 182 | Home 183 |
  • 184 |
  • 185 | About 186 |
  • 187 |
  • 188 | Topics 189 |
  • 190 |
191 | ) 192 | ``` 193 | 194 | #### to 195 | 196 | The link's destination url. 197 | 198 | ### Redirect 199 | 200 | Use the Redirect component to navigate to a new location. The new location will override the current location in the history stack using `history.replaceState`. 201 | 202 | ```jsx 203 | const Login = ({ from, login, redirectToReferrer }) => props => { 204 | if (redirectToReferrer) { 205 | return 206 | } 207 | 208 | return ( 209 |
210 |

You must log in to view the page at {from}.

211 | 218 |
219 | ) 220 | } 221 | ``` 222 | 223 | #### to 224 | 225 | The redirect's destination url. 226 | 227 | #### from 228 | 229 | Overwrite the previous pathname. See [location.previous](#previous). 230 | 231 | ### Switch 232 | 233 | Use the Switch component when you want to ensure only one out of several routes is rendered. It always renders the first matching child. 234 | 235 | ```jsx 236 | const NoMatchExample = ( 237 | 238 | 239 | } 242 | /> 243 | 244 | 245 | 246 | ) 247 | ``` 248 | 249 | ## Modules 250 | 251 | ### location 252 | 253 | #### pathname 254 | 255 | Same as window.location.pathname. 256 | 257 | #### previous 258 | 259 | The previous location.pathname. Useful when redirecting back to the referrer url/pathname after leaving a protected route. 260 | 261 | #### go(url) 262 | 263 | Navigate to the given url. 264 | 265 | ## License 266 | 267 | Hyperapp Router is MIT licensed. See [LICENSE](LICENSE.md). 268 | --------------------------------------------------------------------------------