Giter VIP home page Giter VIP logo

rlite's Introduction

rlite

Tiny, fast, light-weight JavaScript routing with zero dependencies.

  • Order of route declaration doesn't matter: the most specific route wins
  • Zero dependencies
  • No performance drop as you add routes
  • Less than 700 bytes minified and gzipped
  • Parses query strings
  • Wildcard support

Build Status

Usage

Rlite does not come with any explicit tie into HTML5 push state or hash-change events, but these are easy enough to tie in based on your needs. Here's an example:

const route = rlite(notFound, {
  // Default route
  '': function () {
    return 'Home';
  },

  // #inbox
  'inbox': function () {
    return 'Inbox';
  },

  // #sent?to=john -> r.params.to will equal 'john'
  'sent': function ({to}) {
    return 'Sent to ' + to;
  },

  // #users/chris -> r.params.name will equal 'chris'
  'users/:name': function ({name}) {
    return 'User ' + name;
  },

  // #users/foo/bar/baz -> r.params.path will equal 'foo/bar/baz'
  'users/*path': function ({path}) {
    return 'Path = ' + path;
  },

  // #logout
  'logout': function () {
    return 'Logout';
  }
});

function notFound() {
  return '<h1>404 Not found :/</h1>';
}

// Hash-based routing
function processHash() {
  const hash = location.hash || '#';

  // Do something useful with the result of the route
  document.body.textContent = route(hash.slice(1));
}

window.addEventListener('hashchange', processHash);
processHash();

The previous examples should be relatively self-explantatory. Simple, parameterized routes are supported. Only relative URLs are supported. (So, instead of passing: 'http://example.com/users/1', pass '/users/1').

Routes are not case sensitive, so 'Users/:name' will resolve to 'users/:name'

Possible surprises

If there is a query parameter with the same name as a route parameter, it will override the route parameter. So given the following route definition:

/users/:name

If you pass the following URL:

/users/chris?name=joe

The value of params.name will be 'joe', not 'chris'.

Keywords/patterns need to immediately follow a slash. So, routes like the following will not be matched:

/users/user-:id

In this case, you'll need to either use a wildcard route /users/*prefixedId or else, you'd want to modify the URL to be in a format like this: /users/user/:id.

Route handlers

Route handlers ara functions that take three arguments and return a result and/or produce a side-effect.

Here's an example handler:

const route = rlite(notFound, {
  'users/:id': function (params, state, url) {
    // Do interesting stuff here...
  }
});

The first argument is params. It is an object representing the route parameters. So, if you were to run route('users/33'), params would be {id: '33'}.

The second argument is state. It is an optional value that was passed into the route function. So, if you were to run route('users/22', 'Hello'), params would be {id: '22'} and state would be 'Hello'.

The third argument is url. It is the URL which was matched to the route. So, if you were to run route('users/25'), params would be {id: '25'}, state would be undefined and url would be 'users/25'.

Modules

If you're using ES6, import rlite like so:

import rlite from 'rlite-router';

const routes = rlite(notFound, {
  '': function () { }
});

// etc

Or using CommonJS like so:

var Rlite = require('rlite-router');
var routes = rlite(notFound, {
  '': function () { }
});

// etc

Handling 404s

The first parameter to rlite is the 404 handler. This function will be invoked when rlite is called with a URL that has no matching routes.

In the following example, the body will end up with <h1>404 NOT FOUND</h1>.

const route = rlite(() => '<h1>404 NOT FOUND</h1>', {
  'hello': => '<h1>WORLD</h1>'
});

document.body.innerHTML = route('/not/a/valid/url');

Changes from 1.x

  • The parameters to route handlers have changed
  • The plugins have been dropped since 2.x is more functional in nature, it's easy to extend
  • rlite returns a function, rather than an object
  • You can pass optional state into your route handlers
  • The result of your route handler is returned by the router

Installation

Just download rlite.min.js, or use bower:

bower install rlite

Or use npm: https://www.npmjs.com/package/rlite-router

npm install --save rlite-router

Contributing

Make your changes (and add tests), then run the tests:

npm test

If all is well, build your changes:

npm run min

This minifies rlite, and tells you the size. It's currently just under 700 bytes, and I'd like to keep it that way!

Status

Rlite is being actively maintained, but is pretty much feature complete. Generally, I avoid repos that look stale (no recent activity), but in this case, the reason for inactivity is that library is stable and complete.

Usage with React

I've been using Rlite along with React and Redux. Here's a write up on how that works.

License MIT

Copyright (c) 2016 Chris Davies

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

rlite's People

Contributors

adalinesimonian avatar barryosull avatar chrisdavies avatar erwanjegouzo avatar jesusprubio avatar nemzes avatar paulocoghi avatar rpearce avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rlite's Issues

Can't load / use rlite

Maybe related to #26 because I'm new with modules and just try to use it as "script"...

Loaded by

<script src="https://cdn.rawgit.com/chrisdavies/rlite/d025c663/rlite.min.js"></script>

I get following error

Uncaught ReferenceError: rlite is not defined

And also tested as module

<script type="module" src="https://cdn.rawgit.com/chrisdavies/rlite/d025c663/rlite.min.js"></script>

with error:

Uncaught ReferenceError: rlite is not defined
rlite.js:15 Uncaught TypeError: Cannot set property 'Rlite' of undefined

How to load rlite the right way in a html file as js?

Implement Hash routing but leaving the root location alone.

Apologies if this is not the place to put this, but I have spent some time trying to work around this issue and I'd like to share the solution so others don't waste their time.

There is no 'real' issue here (the rlite code is fine). It is more my lack of understanding of how it works, and in particular, of a part of the documentation.

The documentation proposes this to enable hash routing

// Hash-based routing
function processHash() {
  const hash = location.hash || '#';

  // Do something useful with the result of the route
  document.body.textContent = route(hash.slice(1));
}

window.addEventListener('hashchange', processHash);
processHash();

And the issue is that the function gets called on the root location immediately after you call processHash(), so if you had something displayed in the page, it all goes away and gets replaced by "" (nothing).

// on the root location, hash.slice(1) == ""
// so "" gets injected on the page and whatever you had on it goes away
document.body.textContent = route(hash.slice(1));

I found out that you only need to modify that a little to 'leave alone the root location'.

// Hash-based routing
function processHash() {
  const hash = location.hash || '#';


  var afterHash=hash.slice(1);
  console.log(`processHash has been called by "${afterHash}"`);
  
  // Do something useful with the result of the route
  // v1: The --output-- of the function gets injected on the page
  //document.body.textContent = route(hash.slice(1));

  // Do something useful with the result of the route unless is the Root location
  // v2: Just run the function assigned to the route
  if (afterHash!=""){
    route(afterHash);
  }
}

window.addEventListener('hashchange', processHash);
processHash();

Percent signs in request results in "URI malformed" error

Example:

(require('rlite-router')(() => console.log('404'), {
  '/foo': () => console.log('foo'),
}))('/a%b');

Results in

URIError: URI malformed
    at decodeURIComponent (<anonymous>)
    at recurseUrl (node_modules/rlite-router/rlite.js:65:19)
    at recurseUrl (node_modules/rlite-router/rlite.js:67:14)
    at lookup (node_modules/rlite-router/rlite.js:99:42)
    at run (node_modules/rlite-router/rlite.js:119:20)

Do I need to pass URL-encoded values, or is it a possible bug?

Dumb question

Dumb question: what is routing? I read the README and I'm still mystified.

Typo in the readme.md

Hey man, you forgot to enclose the code in the code segment (it's the key point, but hard to find).

window.addEventListener('hashchange', processHash); processHash();

Middleware support

Is there any way to easily use middleware with rlite, i do i have do add the method call in each of the callbacks?

Routes with multiple parameters

Routes such as "hey/:hello/:world" don't seem to be supported anymore in the newer versions. Looking at the source, it seems that the "rules" object in the "add" function only includes the first parameter ("hello" in the example).

Would be great if the latest version on bower includes this functionality again!

Example without hash based routing

First of all -- fantastic package!

I was just wondering -- do you have any example documentation on how to use rlite without hash-based routing? For example, I'd like to be able to go to https://myApp/MyRoute rather than https://myApp/#myRoute

I got it working doing this:

history.pushState = ( f => function pushState(){
    var ret = f.apply(this, arguments);
    window.dispatchEvent(new Event('pushstate'));
    window.dispatchEvent(new Event('locationchange'));
    return ret;
})(history.pushState);

history.replaceState = ( f => function replaceState(){
    var ret = f.apply(this, arguments);
    window.dispatchEvent(new Event('replacestate'));
    window.dispatchEvent(new Event('locationchange'));
    return ret;
})(history.replaceState);

window.addEventListener('popstate',()=>{
    window.dispatchEvent(new Event('locationchange'))
});

(location change example taken from here )
Then defining my routes

Then using this to hook into the custom event.

  function processNoHash() {
    // Do something useful with the result of the route
    console.log(window.location.pathname);
    document.body.textContent = route(window.location.pathname);
  }

window.addEventListener('locationchange', processNoHash);
processNoHash();

It seems to work well, but I was wondering if there was a different recommended approach, and if perhaps an example could be added to the readme.

support history api?

I sounds like rlite doesn't support history api (browser address bar changes)?
Is there a example / extension how to do browser address bar / history handling?

Uppercase routes

Routes with uppercase letters are not handled correctly since you're lowercasing all the pieces in the run function:

var piece = decode(pieces[i]),
    rule = rules[piece.toLowerCase()];

I know it's not considered good practice, but it would be great to support that!

Greedy parameter matching

When using a route like /users/:name and name contains a /, like for example a/b, the route will no longer match. I wonder if a token could be introduced that matches greedly across slashes.

Express for example allows these route via a regex route like /(.+), thought for rlite, I could see something simpler work, like /users/::name.

Publish to npm?

Hi @chrisdavies, have you published the package to npm already? Unfortunately rlite seems to be taken. It will make it much easier to handle it as a dependency... Thanks :) Darío

Possible wildcard match bug

Not sure if this counts as a bug, but

(require('.')(() => console.log('404'), {
  '/foo/*bar': () => console.log('1'),
  '/foo/:baz/qux': () => console.log('2'),
}))('/foo/something');

logs 404. When I comment the second route, it goes to the first as expected.

Cannot read property 'define' of undefined

When I try to use the lib I get this error:

Uncaught TypeError: Cannot read property 'define' of undefined
    at routes (index.js:723)
    at Object.<anonymous> (index.js:732)
    at __webpack_require__ (index.js:20)
    at Object.<anonymous> (index.js:623)
    at __webpack_require__ (index.js:20)
    at Object.<anonymous> (index.js:53)
    at __webpack_require__ (index.js:20)
    at index.js:40
    at index.js:43

Basically it's on this line:
var define = root.define;

It's trying to get define of root but root is undefined

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.