-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
54 lines (47 loc) · 1.39 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
/**
* Originally based on:
* https://github.com/reactjs/react-router/issues/394#issuecomment-220221604
*/
var CSSescape = require('css.escape')
exports.hash = function hash (h, options) {
options = options || {}
var cb = options.callback || function () {}
// There's no hash to scroll to, so "success", we did it.
if (!h) return void cb()
var scroller = options.scroller || exports.scroller
// Push onto callback queue so it runs after the DOM is updated,
// this is required when navigating from a different page so that
// the element is rendered on the page before trying to getElementById.
setTimeout(function () {
var els = exports.elements(h)
if (!els) return void cb(true)
if (scroller(els.id) || scroller(els.name)) return void cb()
cb(true)
}, 0)
}
exports.scroller = function scroller (el) {
if (!el) return false
el.scrollIntoView()
return true
}
exports.elements = function elements (h) {
var sels = exports.selectors(h)
if (!sels) return
return {
id: document.getElementById(sels.id),
name: document.querySelector(sels.name)
}
}
exports.selectors = function selectors (h) {
if (!h) return
h = h.replace(/^#/, '')
if (!h) return
return {
id: h,
name: '[name="' + CSSescape(h) + '"]'
}
}
exports.anchorate = function anchorate (options) {
exports.hash(window.location.hash, options)
}
exports.default = exports.anchorate