refactor(core): and markdown compiler

This commit is contained in:
qingwei.li 2017-02-18 14:09:17 +08:00 committed by cinwell.li
commit fe88c154b0
12 changed files with 194 additions and 232 deletions

View file

@ -1,4 +1,5 @@
import { parseQuery } from './util'
import { merge } from '../util/core'
import { parseQuery, stringifyQuery, cleanPath } from './util'
function replaceHash (path) {
const i = window.location.href.indexOf('#')
@ -34,11 +35,11 @@ export function getHash () {
}
/**
* Parse the current url
* Parse the url
* @param {string} [path=window.location.herf]
* @return {object} { path, query }
*/
export function parse () {
let path = window.location.href
export function parse (path = window.location.href) {
let query = ''
const queryIndex = path.indexOf('?')
@ -57,9 +58,14 @@ export function parse () {
/**
* to URL
* @param {String} path
* @param {String} qs query string
* @param {string} path
* @param {object} qs query params
*/
export function toURL (path, qs) {
export function toURL (path, params) {
const route = parse(path)
route.query = merge({}, route.query, params)
path = route.path + stringifyQuery(route.query)
return '#' + path
}

View file

@ -30,13 +30,19 @@ export function routeMixin (Docsify) {
}
}
let lastRoute = {}
export function initRoute (vm) {
normalize()
vm.route = parse()
lastRoute = vm.route = parse()
on('hashchange', _ => {
normalize()
vm.route = parse()
lastRoute = vm.route = parse()
if (lastRoute.path === vm.route.path) {
// TODO: goto xxx
return
}
vm._fetch()
})
}

View file

@ -1,6 +1,7 @@
import { cached } from '../util/core'
const decode = decodeURIComponent
const encode = encodeURIComponent
export const parseQuery = cached(query => {
const res = {}
@ -11,35 +12,35 @@ export const parseQuery = cached(query => {
return res
}
// Simple parse
query.split('&').forEach(function (param) {
const parts = param.replace(/\+/g, ' ').split('=')
const key = decode(parts.shift())
const val = parts.length > 0
? decode(parts.join('='))
: null
if (res[key] === undefined) {
res[key] = val
} else if (Array.isArray(res[key])) {
res[key].push(val)
} else {
res[key] = [res[key], val]
}
res[parts[0]] = decode(parts[1])
})
return res
})
export function stringifyQuery (obj) {
const qs = []
for (const key in obj) {
qs.push(`${encode(key)}=${encode(obj[key])}`)
}
return qs.length ? `?${qs.join('&')}` : ''
}
export const getBasePath = cached(base => {
return /^(\/|https?:)/g.test(base)
? base
: cleanPath(window.location.pathname + '/' + base)
})
export const getRoot = cached(path => {
return /\/$/g.test(path) ? path : path.match(/(\S*\/)[^\/]+$/)[1]
})
export function cleanPath (path) {
return path.replace(/\/+/g, '/')
}
export function getBasePath (base) {
return /^(\/|https?:)/g.test(base)
? base
: cleanPath(window.location.pathname + '/' + base)
}
export function getCurrentRoot (path) {
return /\/$/g.test(path) ? path : path.match(/(\S*\/)[^\/]+$/)[1]
}