-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
54 lines (45 loc) · 1.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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, '/'))
}