• Stars
    star
    108
  • Rank 321,201 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

A flexible nested router.

Cherrytree is a flexible hierarchical router that translates every URL change into a transition descriptor object and calls your middleware functions that put the application into a desired state.

Installation

The size excluding all deps is ~4.83kB gzipped and the standalone build with all deps is ~7.24kB gzipped.

$ npm install --save cherrytree

In a CJS environment

require('cherrytree')

In an AMD environment, require the standalone UMD build - this version has all of the dependencies bundled

require('cherrytree/standalone')

Docs

Demo

See it in action in this demo.

Plugins

To use cherrytree with React, check out cherrytree-for-react.

Usage

var cherrytree = require('cherrytree')

// create the router
var router = cherrytree()
var handlers = require('./handlers')

// provide your route map
router.map(function (route) {
  route('application', {path: '/', abstract: true}, function () {
    route('feed', {path: ''})
    route('messages')
    route('status', {path: ':user/status/:id'})
    route('profile', {path: ':user'}, function () {
      route('profile.lists')
      route('profile.edit')
    })
  })
})

router.use(function render (transition) {
  transition.routes.forEach(function (route, i) {
    route.view = handlers[route.name]({
      params: transition.params,
      query: transition.query
    })
    var parent = transition.routes[i-1]
    var containerEl = parent ? parent.view.el.querySelector('.outlet') : document.body
    containerEl.appendChild(view.render().el)
  })
})

router.use(function errorHandler (transition) {
  transition.catch(function (err) {
    if (err.type !== 'TransitionCancelled' && err.type !== 'TransitionRedirected') {
      console.error(err.stack)
    }
  })
})

// start listening to URL changes
router.listen()

Examples

You can clone this repo if you want to run the examples locally:

A more complex example in it's own repo:

Features

  • can be used with any view and data framework
  • nested routes are great for nested UIs
  • generate links in a systematic way, e.g. router.generate('commit', {sha: '1e2760'})
  • use pushState with automatic hashchange fallback
  • all urls are generated with or without # as appropriate
  • link clicks on the page are intercepted automatically when using pushState
  • dynamically load parts of your app during transitions
  • dynamic segments, optional params and query params
  • support for custom query string parser
  • transition is a first class citizen - abort, pause, resume, retry. E.g. pause the transition to display "There are unsaved changes" message if the user clicked some link on the page or used browser's back/forward buttons
  • navigate around the app programatically, e.g. router.transitionTo('commits')
  • easily rename URL segments in a single place (e.g. /account -> /profile)

How does it compare to other routers?

  • Backbone router is nice and simple and can often be enough. In fact cherrytree uses some bits from Backbone router under the hood. Cherrytree adds nested routing, support for asynchronous transitions, more flexible dynamic params, url generation, automatic click handling for pushState.
  • Ember router / router.js is the inspiration for cherrytree. It's where cherrytree inherits the idea of declaring hierarchical nested route maps. The scope of cherrytree is slightly different than that of router.js, for example cherrytree doesn't have the concept of handler objects or model hooks. On the other hand, unlike router.js - cherrytree handles browser url changes and intercepts link clicks with pushState out of the box. The handler concept and model hooks can be implemented based on the specific application needs using the middleware mechanism. Overall, cherrytree is less prescriptive, more flexible and easier to use out of the box.
  • react-router is also inspired by router.js. React-router is trying to solve a lot of routing related aspects out of the box in the most React idiomatic way whereas with cherrytree you'll have to write the glue code for integrating into React yourself (see cherrytree-for-react plugin). However, what you get instead is a smaller, simpler and hopefully more flexible library which should be more adaptable to your specific needs. This also means that you can use a react-router like approach with other React inspired libraries such as mercury, riot, om, cycle, deku and so on.

CI

Build Status build status

Browser Support

Sauce Test Status

Cherrytree works in all modern browsers. It requires es5 environment and es6 promises. Use polyfills for those if you have to support older browsers, e.g.:

Acknowledgement

Thanks to Marko Stupić for giving Cherrytree a logo from his http://icon-a-day.com/ project!

FAQ

  • Why is cherrytree written as one word? You got me, I'd say that represents the wabisabi nature of the library.

Want to work on this for your day job?

This project was created by the Engineering team at Qubit. As we use open source libraries, we make our projects public where possible.

We’re currently looking to grow our team, so if you’re a JavaScript engineer and keen on ES2016 React+Redux applications and Node micro services, why not get in touch? Work with like minded engineers in an environment that has fantastic perks, including an annual ski trip, yoga, a competitive foosball league, and copious amounts of yogurt.

Find more details on our Engineering site. Don’t have an up to date CV? Just link us your Github profile! Better yet, send us a pull request that improves this project.

More Repositories

1

bamboo

HAProxy auto configuration and auto service discovery for Mesos Marathon
Go
793
star
2

exporter_exporter

A reverse proxy designed for Prometheus exporters
Go
341
star
3

gcs-browser-upload

Resumable chunked uploads to Google Cloud Storage from the browser
JavaScript
84
star
4

d3-react-sparkline

A simple component to render a sparkline with D3
JavaScript
73
star
5

aws_audit_exporter

Prometheus exporter for aws billing information
Go
24
star
6

queue-that

A queue managed in localStorage for async tasks that may run immediately before page unload
JavaScript
21
star
7

json-bourne

Drop in replacement for JSON that standardizes Array.toJSON and Date.toJSON
JavaScript
15
star
8

dataflow_launcher

A unified way of launching Dataflow jobs
Python
14
star
9

metrics-flow

Metrics collection library for Google Dataflow
Java
13
star
10

kafka_lag_exporter

A kafka lag exporter for prometheus
Go
11
star
11

cookieman

simple cookie lib
JavaScript
11
star
12

shopify-qubit-asset

Template snippets for implementing Qubit events in Shopify
Liquid
11
star
13

jsonlogic

Go
10
star
14

bapistrano

Deploy JS apps to s3 multiverse.
JavaScript
9
star
15

iris

Envoy xDS for Kubernetes service discovery
Go
8
star
16

qubit-cli

Develop experiences from your desktop
JavaScript
8
star
17

secret-door

An RPC implementation on top of window.postMessage for cross context communication in the browser ㊙️ 🚪
JavaScript
7
star
18

sync-p

Tiny battle tested sync promise lib
JavaScript
7
star
19

kube-ci

Go
6
star
20

driftwood

A namespaced stylish logger
JavaScript
6
star
21

utils

Utilities for clientside code injection
JavaScript
5
star
22

gogoproto-java

Java packaging for Gogoproto
5
star
23

akka-cloudpubsub

Akka Streams Source and Sink for Cloud Pub/Sub
Scala
5
star
24

mflowd

A go daemon that collects monitoring metrics from Google Dataflow workers and exposes them to Prometheus
Go
5
star
25

event-kitten

An event emitter inspired by event-kit, written in JavaScript
JavaScript
5
star
26

recommendations

@qubit/recommendations
JavaScript
4
star
27

topNET

Lightweight Java NIO HTTP Server
Java
4
star
28

uv-api

Universal Variable API
JavaScript
3
star
29

express-sourcemap-filter

Simple express middleware to restrict sourcemap access to certain IP addresses
JavaScript
3
star
30

qubit-react

A wrapper component for use with Qubit Experiences
JavaScript
3
star
31

slapdash

A lightweight JavaScript utility belt with native method override protection
JavaScript
3
star
32

matchete

Super simple string value matching
JavaScript
2
star
33

placement-examples

2
star
34

url-canon

Normalizes URL's to prevent duplicates that point to the same server resource
JavaScript
2
star
35

base64int

Pure JS integer to/from base64 converter
JavaScript
2
star
36

dubber

Advanced DNS zone provisioning from orchestration services.
Go
2
star
37

tlsproxy

A simple tls to unix/tcp proxy, in go.
Go
2
star
38

log-requests

A service that simply logs all requests sent to it
JavaScript
2
star
39

looker-source-block

Looker Block for Qubit Live Tap - Retail
LookML
2
star
40

s3-cnpm

S3 storage wrapper for cnpm
JavaScript
1
star
41

really-unique-id

Produces random ID's on browsers using plugins and cookies for more randomness
JavaScript
1
star
42

prom-config-controller

A kubernetes controller that exposes Prometheus Scrapes and Rule Groups as CRDs
Go
1
star
43

battlesauce

battle test your rest apis with saucelabs
JavaScript
1
star