-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathhtml5.js
65 lines (53 loc) · 1.43 KB
/
html5.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
55
56
57
58
59
60
61
62
63
64
65
import {History} from './base'
import {noop} from '../../util/core'
import {on} from '../../util/dom'
import {parseQuery, getPath} from '../util'
export class HTML5History extends History {
constructor(config) {
super(config)
this.mode = 'history'
}
getCurrentPath() {
const base = this.getBasePath()
let path = window.location.pathname
if (base && path.indexOf(base) === 0) {
path = path.slice(base.length)
}
return (path || '/') + window.location.search + window.location.hash
}
onchange(cb = noop) {
on('click', e => {
const el = e.target.tagName === 'A' ? e.target : e.target.parentNode
if (el.tagName === 'A' && !/_blank/.test(el.target)) {
e.preventDefault()
const url = el.href
window.history.pushState({key: url}, '', url)
cb()
}
})
on('popstate', cb)
}
/**
* Parse the url
* @param {string} [path=location.href]
* @return {object} { path, query }
*/
parse(path = location.href) {
let query = ''
const queryIndex = path.indexOf('?')
if (queryIndex >= 0) {
query = path.slice(queryIndex + 1)
path = path.slice(0, queryIndex)
}
const base = getPath(location.origin)
const baseIndex = path.indexOf(base)
if (baseIndex > -1) {
path = path.slice(baseIndex + base.length)
}
return {
path,
file: this.getFile(path),
query: parseQuery(query)
}
}
}