JavaScript HTML
Latest commit 023e64f Feb 17, 2017 @tunnckoCore committed on GitHub Update README.md

README.md

gibon NPM version NPM monthly downloads npm total downloads

Functional client-side router in ~570 bytes, built on HTML5 History API

code climate standard code style linux build status windows build status coverage status dependency status

You might also be interested in mitt - a 200 bytes event emitter, and hyperapp - build rich UI apps with 1kb.

✨ Pull requests for client-side tests or any other features/fixes are welcome! 🚀

Table of Contents

(TOC generated by verb using markdown-toc)

Install

Install with npm

$ npm install gibon --save

or install using yarn

$ yarn add gibon

Both UMD and IIFE builds are also available on unpkg CDN

<script src="https://unpkg.com/gibon/dist/gibon.umd.js"></script>
<!-- or -->
<script src="https://unpkg.com/gibon/dist/gibon.iife.js"></script>

Usage

For more use-cases see the tests

const router = gibon({
  '/': (state) => console.log('home'),
  '/about': (state) => console.log('about'),
  '/users/:user': (state, params) => console.log('user:', params.user),
  '/users/:user/edit': (state, params) => {
    console.log('edit user:', params.user)
  },
  '/groups/:group/users/:user': (state, params) => {
    console.log('user:', params.user, 'group:', params.group)
  }
})

router.start()

API

router = gibon(routes, onRoute, onClick)

routes

Object with key/value pairs, where key is the route and value should be a function that has (state, params) signature.

  • route - path like /users/:user
  • value - function that has (state, params) signature

The route path syntax is based on the same syntax found in Express.

Example

const userView = (state, params) => {
  console.log('user:', params.user)
}

const router = gibon({
  '/users/:user': userView
})

router.start()

back to top


onRoute - optional

It should be function that is triggered every time when given route is accessed. Completely optional, but useful for higher level things such as seen in hyperapp.

It is passed with (view, state, el) signature. See public/dom.js example.

  • view - always a function for the route
  • state - value that is passed as second argument to .render() method
  • el - previous dom element (if bel is used for example) or undefined

Example

const html = requre('bel')

const state = {
  title: 'Welcome!'
}

const routes = {
  '/users/:user': (state, params) => html`<div>
    <h1>${state.title}</h1>
    <h2>${params.user}</h2>
  </div>`
}

// some entry point
const main = document.querySelector('#app')

const helper = (parent, child) => {
  return parent.replaceChild(child, parent.childNodes[0])
}

const onRoute = (view, _, el) => {
  return helper(main, view(state))
}

const router = gibon(routes, onRoute)
router.start()

For complete working example see public/nanomorph.js, which uses nanomorph to do the diffing and updating only needed dom elements.

back to top


onClick - optional

It should be function that controls behaviour of clicking on links. We intercept all <a href="/path">...</a> clicks. If you want to opt out of this, add the custom attribute data-no-routing to any anchor element that should be handled differently.

It is passed with (e, render) signature.

  • e - the clicked a element
  • render - function which is the .render() method

All that just means that it is perfectly configured by default to work on pushState servers, so page won't refresh while you move through pages of the defined routes.

Try out some of the provided examples in public/.

back to top


router.start()

Starts the router. Function that starts the router to listen on routes. If you not call it, it won't attach any listeners, so it won't work.

back to top


el = router.render(view, state)

We can use .render() without .start()ing the router.

You can use that to manually render view with optional state. It returns what the view returns, so if the view returns a DOM element, then el will be that element.

  • view - string path to route, or function like userView
  • state - optional, any value that you want

Example 1

const router = gibon()

const userView = (state, params) => {
  console.log('title is', state.title)
}

router.render(userView, { title: 'hello world' })

The cool thing comes when you use some Virtual or Real DOM builder, such as bel or hyperx.

In the next example we are using bel to define some HTML without breaking the JavaScript and we "render" some specific route with some context/state, and finally we append it ot the page body.

Example 2

const html = require('bel')
const router = gibon({
  '/users/:user': (state, params) => html`<div>
    <h1>${state.title}</h1>
    <h2>user is ${params.user}</h2>
  </div>`
})

const el = router.render('/users/tunnckoCore', { title: 'hello world' })
document.body.appendChild(el)

So we'll get such that div in the document body

<div>
  <h1>hello world</h1>
  <h2>user is tunnckoCore</h2>
</div>

back to top

Examples

Run some of the examples by cloning the repo and calling them through npm scripts

npm run example:nanomorph
npm run example:simple
npm run example:dom

Related

  • always-done: Handle completion and errors with elegance! Support for streams, callbacks, promises, child processes, async/await and sync functions. A drop-in replacement… more | homepage
  • bel: A simple extension to native elements | homepage
  • hyperapp: HyperApp is a 1kb functional JavaScript library for building modern UI applications | homepage
  • hyperx: tagged template string virtual dom builder | homepage
  • minibase: Minimalist alternative for Base. Build complex APIs with small units called plugins. Works well with most of the already existing… more | homepage
  • nanomorph: Hyper fast diffing algorithm for real DOM nodes | homepage
  • redom: Tiny DOM library | homepage
  • try-catch-core: Low-level package to handle completion and errors of sync or asynchronous functions, using once and dezalgo libs. Useful for and… more | homepage

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Please read the contributing guidelines for advice on opening issues, pull requests, and coding standards.
If you need some help and can spent some cash, feel free to contact me at CodeMentor.io too.

In short: If you want to contribute to that project, please follow these things

  1. Please DO NOT edit README.md, CHANGELOG.md and .verb.md files. See "Building docs" section.
  2. Ensure anything is okey by installing the dependencies and run the tests. See "Running tests" section.
  3. Always use npm run commit to commit changes instead of git commit, because it is interactive and user-friendly. It uses commitizen behind the scenes, which follows Conventional Changelog idealogy.
  4. Do NOT bump the version in package.json. For that we use npm run release, which is standard-version and follows Conventional Changelog idealogy.

Thanks a lot! :)

Building docs

Documentation and that readme is generated using verb-generate-readme, which is a verb generator, so you need to install both of them and then run verb command like that

$ npm install verbose/verb#dev verb-generate-readme --global && verb

Please don't edit the README directly. Any changes to the readme must be made in .verb.md.

Running tests

Clone repository and run the following in that cloned directory

$ npm install && npm test

Author

Charlike Mike Reagent

License

Copyright © 2016-2017, Charlike Mike Reagent. Released under the MIT license.


This file was generated by verb-generate-readme, v0.4.1, on February 09, 2017.
Project scaffolded using charlike cli.