-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathUriUtils.js
104 lines (86 loc) · 2.1 KB
/
UriUtils.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// @flow
import LZString from "lz-string";
import type { PersistedState } from "./types";
const URL_KEYS = [
"babili",
"browsers",
"build",
"builtIns",
"code",
"debug",
"circleciRepo",
"evaluate",
"lineWrap",
"presets",
"targets",
"version",
];
const compress = (string: string) =>
LZString.compressToBase64(string)
.replace(/\+/g, "-") // Convert '+' to '-'
.replace(/\//g, "_") // Convert '/' to '_'
.replace(/=+$/, ""); // Remove ending '='
const decompress = (string: string) =>
LZString.decompressFromBase64(
string
.replace(/-/g, "+") // Convert '-' to '+'
.replace(/_/g, "/") // Convert '_' to '/'
);
const encode = (value: any) => window.encodeURIComponent(value);
const decode = (value: any) => {
try {
return window.decodeURIComponent("" + value);
} catch (err) {
return value;
}
};
const mergeDefinedKeys = (raw: Object, keys: Array<string>, target: Object) => {
keys.forEach(key => {
if (raw[key] != null) {
target[key] = raw[key];
}
});
};
const parseQuery = () => {
const raw = document.location.hash
.replace(/^#\?/, "")
.split("&")
.reduce((reduced: Object, pair: string) => {
const pieces = pair.split("=");
const name = decodeURIComponent("" + pieces[0]);
let value = decodeURIComponent("" + pieces[1]);
if (value === "true" || value === "false") {
value = value === "true";
}
reduced[name] = value;
return reduced;
}, {});
const state = {};
mergeDefinedKeys(raw, URL_KEYS, state);
if (raw.code_lz != null) {
state.code = decompress(raw.code_lz || "");
}
return state;
};
const updateQuery = (state: PersistedState) => {
const query = URL_KEYS.map(key => {
if (state[key] == null) {
return null;
} else if (key === "code") {
return `${key}_lz=` + compress(state.code);
} else {
return key + "=" + encode(state[key]);
}
})
.filter(value => value)
.join("&");
window.location.hash = "?" + query;
};
export default {
compress,
decode,
decompress,
encode,
parseQuery,
updateQuery,
};