/
LocationUtils.js
76 lines (66 loc) · 1.92 KB
/
LocationUtils.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
import resolvePathname from "resolve-pathname"
import valueEqual from "value-equal"
import { parsePath } from "./PathUtils"
export const createLocation = (path, state, key, currentLocation) => {
let location
if (typeof path === "string") {
// Two-arg form: push(path, state)
location = parsePath(path)
location.state = state
} else {
// One-arg form: push(location)
location = { ...path }
if (location.pathname === undefined) location.pathname = ""
if (location.search) {
if (location.search.charAt(0) !== "?")
location.search = "?" + location.search
} else {
location.search = ""
}
if (location.hash) {
if (location.hash.charAt(0) !== "#") location.hash = "#" + location.hash
} else {
location.hash = ""
}
if (state !== undefined && location.state === undefined)
location.state = state
}
try {
location.pathname = decodeURI(location.pathname)
} catch (e) {
if (e instanceof URIError) {
throw new URIError(
'Pathname "' +
location.pathname +
'" could not be decoded. ' +
"This is likely caused by an invalid percent-encoding."
)
} else {
throw e
}
}
if (key) location.key = key
if (currentLocation) {
// Resolve incomplete/relative pathname relative to current location.
if (!location.pathname) {
location.pathname = currentLocation.pathname
} else if (location.pathname.charAt(0) !== "/") {
location.pathname = resolvePathname(
location.pathname,
currentLocation.pathname
)
}
} else {
// When there is no prior location and pathname is empty, set it to /
if (!location.pathname) {
location.pathname = "/"
}
}
return location
}
export const locationsAreEqual = (a, b) =>
a.pathname === b.pathname &&
a.search === b.search &&
a.hash === b.hash &&
a.key === b.key &&
valueEqual(a.state, b.state)