-
Notifications
You must be signed in to change notification settings - Fork 18
/
href.js
41 lines (32 loc) · 1.18 KB
/
href.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
var window = require('global/window')
var assert = require('assert')
var qs = require('./qs')
module.exports = href
var noRoutingAttrName = 'data-no-routing'
// handle a click if is anchor tag with an href
// and url lives on the same domain. Replaces
// trailing '#' so empty links work as expected.
// (fn(str), obj?) -> undefined
function href (cb, root) {
assert.equal(typeof cb, 'function', 'sheet-router/href: cb must be a function')
window.onclick = function (e) {
if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return
var node = (function traverse (node) {
if (!node || node === root) return
if (node.localName !== 'a') return traverse(node.parentNode)
if (node.href === undefined) return traverse(node.parentNode)
if (window.location.host !== node.host) return traverse(node.parentNode)
return node
})(e.target)
if (!node) return
var isRoutingDisabled = node.hasAttribute(noRoutingAttrName)
if (isRoutingDisabled) return
e.preventDefault()
cb({
pathname: node.pathname,
search: (node.search) ? qs(node.search) : {},
href: node.href,
hash: node.hash
})
}
}