-
Notifications
You must be signed in to change notification settings - Fork 18
/
create-location.js
49 lines (44 loc) · 1.4 KB
/
create-location.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
var document = require('global/document')
var assert = require('assert')
var xtend = require('xtend')
var qs = require('./qs')
module.exports = createLocation
// takes an initial representation of the location state
// and then synchronize a mutation across all fields
//
// scenarios:
// - create a state object from document.location; we got no state yet
// - create a new state object from a string we pass in; full override mode
// - patch a state object with some value we pass in - lil patchy stuff
//
// (obj?, str?) -> obj
function createLocation (state, patch) {
if (!state) {
return {
pathname: document.location.pathname,
search: (document.location.search) ? qs(document.location.search) : {},
hash: document.location.hash,
href: document.location.href
}
} else {
assert.equal(typeof state, 'object', 'sheet-router/create-location: state should be an object')
if (typeof patch === 'string') {
return parseUrl(patch)
} else {
assert.equal(typeof patch, 'object', 'sheet-router/create-location: patch should be an object')
return xtend(state, patch)
}
}
// parse a URL into a kv object inside the browser
// str -> obj
function parseUrl (url) {
var a = document.createElement('a')
a.href = url
return {
href: a.href,
pathname: a.pathname,
search: (a.search) ? qs(a.search) : {},
hash: a.hash
}
}
}