refactor(core): add router

This commit is contained in:
qingwei.li 2017-02-18 11:41:33 +08:00 • committed by cinwell.li
commit 30da0d5d46
17 changed files with 316 additions and 88 deletions

View file

@ -1,7 +1,27 @@
// import { cleanPath, getLocation } from './util'
export function ensureSlash () {
const path = getHash()
if (path.charAt(0) === '/') return
import { parseQuery } from './util'
function replaceHash (path) {
const i = window.location.href.indexOf('#')
window.location.replace(
window.location.href.slice(0, i >= 0 ? i : 0) + '#' + path
)
}
/**
* 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 = path
.replace('#', '?id=')
.replace(/\?(\w+)=/g, (_, slug) => slug === 'id' ? '?id=' : `&${slug}=`)
if (path.charAt(0) === '/') return replaceHash(path)
replaceHash('/' + path)
}
@ -13,11 +33,33 @@ export function getHash () {
return index === -1 ? '' : href.slice(index + 1)
}
function replaceHash (path) {
const i = window.location.href.indexOf('#')
window.location.replace(
window.location.href.slice(0, i >= 0 ? i : 0) + '#' + path
)
/**
* Parse the current url
* @return {object} { path, query }
*/
export function parse () {
let 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) }
}
// TODO 把第二个 hash 转成 ?id=
/**
* to URL
* @param {String} path
* @param {String} qs query string
*/
export function toURL (path, qs) {
}