-
-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
hash.js
80 lines (67 loc) 路 1.98 KB
/
hash.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import { merge, cached } from '../util/core'
import { parseQuery, stringifyQuery, cleanPath } from './util'
export * from './util'
function replaceHash (path) {
const i = window.location.href.indexOf('#')
window.location.replace(
window.location.href.slice(0, i >= 0 ? i : 0) + '#' + path
)
}
const replaceSlug = cached(path => {
return path
.replace('#', '?id=')
// .replace(/\?(\w+)=/g, (_, slug) => slug === 'id' ? '?id=' : `&${slug}=`)
})
/**
* Normalize the current url
*
* @example
* domain.com/docs/ => domain.com/docs/#/
* domain.com/docs/#/#slug => domain.com/docs/#/?id=slug
*/
export function normalize () {
let path = getHash()
path = replaceSlug(path)
if (path.charAt(0) === '/') return replaceHash(path)
replaceHash('/' + path)
}
export function getHash () {
// We can't use window.location.hash here because it's not
// consistent across browsers - Firefox will pre-decode it!
const href = window.location.href
const index = href.indexOf('#')
return index === -1 ? '' : href.slice(index + 1)
}
/**
* Parse the url
* @param {string} [path=window.location.herf]
* @return {object} { path, query }
*/
export function parse (path = window.location.href) {
let query = ''
const queryIndex = path.indexOf('?')
if (queryIndex >= 0) {
query = path.slice(queryIndex + 1)
path = path.slice(0, queryIndex)
}
const hashIndex = path.indexOf('#')
if (hashIndex) {
path = path.slice(hashIndex + 1)
}
return { path, query: parseQuery(query) }
}
/**
* to URL
* @param {string} path
* @param {object} qs query params
* @param {string} currentRoute optional current route
*/
export function toURL (path, params, currentRoute) {
const local = currentRoute && path[0] === '#'
const route = parse(replaceSlug(path))
route.query = merge({}, route.query, params)
path = route.path + stringifyQuery(route.query)
path = path.replace(/\.md(\?)|\.md$/, '$1')
if (local) path = currentRoute + path
return cleanPath('#/' + path)
}