-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathhtml5.js
65 lines (53 loc) · 1.55 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 { isExternal, noop } from '../../util/core.js';
import { on } from '../../util/dom.js';
import { parseQuery, getPath } from '../util.js';
import { History } from './base.js';
export class HTML5History extends History {
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 && el.tagName === 'A' && !isExternal(el.href)) {
e.preventDefault();
const url = el.href;
window.history.pushState({ key: url }, '', url);
cb({ event: e, source: 'navigate' });
}
});
on('popstate', e => {
cb({ event: e, source: 'history' });
});
}
/**
* Parse the url
* @param {string} [path=location.href] URL to be parsed
* @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),
response: {},
};
}
}