UNPKG

choo-shortcache

Version:

choo nanocomponent cache shortcut

55 lines (45 loc) 1.64 kB
var assert = require('assert') var wayfarer = require('wayfarer') // electron support var isLocalFile = (/file:\/\//.test( typeof window === 'object' && window.location && window.location.origin )) /* eslint-disable no-useless-escape */ var electron = '^(file:\/\/|\/)(.*\.html?\/?)?' var protocol = '^(http(s)?(:\/\/))?(www\.)?' var domain = '[a-zA-Z0-9-_\.]+(:[0-9]{1,5})?(\/{1})?' var qs = '[\?].*$' /* eslint-enable no-useless-escape */ var stripElectron = new RegExp(electron) var prefix = new RegExp(protocol + domain) var normalize = new RegExp('#') var suffix = new RegExp(qs) module.exports = Nanorouter function Nanorouter (opts) { if (!(this instanceof Nanorouter)) return new Nanorouter(opts) opts = opts || {} this.router = wayfarer(opts.default || '/404') } Nanorouter.prototype.on = function (routename, listener) { assert.equal(typeof routename, 'string') routename = routename.replace(/^[#/]/, '') this.router.on(routename, listener) } Nanorouter.prototype.emit = function (routename) { assert.equal(typeof routename, 'string') routename = pathname(routename, isLocalFile) return this.router.emit(routename) } Nanorouter.prototype.match = function (routename) { assert.equal(typeof routename, 'string') routename = pathname(routename, isLocalFile) return this.router.match(routename) } // replace everything in a route but the pathname and hash function pathname (routename, isElectron) { if (isElectron) routename = routename.replace(stripElectron, '') else routename = routename.replace(prefix, '') return decodeURI(routename.replace(suffix, '').replace(normalize, '/')) }