Completed
Push — master ( 586be1...cacae6 )
by Dongxin
24s
created

mjsonviewer.js (17 issues)

1
//////////////////////////////////////////////////////////////////////////////////////
2
// Copyright © 2017 TangDongxin
3
//
4
// Permission is hereby granted, free of charge, to any person obtaining
5
// a copy of this software and associated documentation files (the "Software"),
6
// to deal in the Software without restriction, including without limitation
7
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
8
// and/or sell copies of the Software, and to permit persons to whom the
9
// Software is furnished to do so, subject to the following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
16
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
20
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
//////////////////////////////////////////////////////////////////////////////////////
22
23
// ===========================================
24
// JSON PARSER
25
// ===========================================
26
27
var bgColor, intColor, strColor, keyColor, defaultColor;
28
var fontStyle;
29
var strictOnly, hideDetails;
30
31
function onError(error) {
32
    console.log(error);
0 ignored issues
show
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
33
}
34
35
function onGot(result) {
36
    if (result[0]) {
37
        fontStyle    = result[0].fontStyle    || "Consolas";
38
        bgColor      = result[0].bgColor      || "#FDF6E3";
39
        intColor     = result[0].intColor     || "#657A81";
40
        strColor     = result[0].strColor     || "#2AA198";
41
        keyColor     = result[0].keyColor     || "#B58900";
42
        defaultColor = result[0].defaultColor || "#586E75";
43
44
        strictOnly   = result[0].strictOnly   || false;
45
        hideDetails  = result[0].hideDetails  || false;
46
    } else {
47
        fontStyle    = result.fontStyle       || "Consolas";
48
        bgColor      = result.bgColor         || "#FDF6E3";
49
        intColor     = result.intColor        || "#657A81";
50
        strColor     = result.strColor        || "#2AA198";
51
        keyColor     = result.keyColor        || "#B58900";
52
        defaultColor = result.defaultColor    || "#586E75";
53
54
        strictOnly   = result.strictOnly      || false;
55
        hideDetails  = result.hideDetails  || false;
56
    }
57
58
    var str, jsonpMatch, hovered, tag,
59
        chrome = this.chrome || this.browser,
60
        jsonRe = /^\s*(?:\[\s*(?=-?\d|true|false|null|["[{])[^]*\]|\{\s*"[^]+\})\s*$/,
61
        div = document.createElement("div"),
62
        body = document.body,
63
        first = body && body.firstChild,
64
        mod = /Mac|iPod|iPhone|iPad|Pike/.test(navigator.platform) ? "metaKey" : "ctrlKey",
0 ignored issues
show
The variable navigator seems to be never declared. If this is a global, consider adding a /** global: navigator */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
65
        rand = Math.random().toString(36).slice(2),
66
        HOV = "H" + rand,
67
        DIV = "D" + rand,
68
        KEY = "K" + rand,
69
        STR = "S" + rand,
70
        BOOL = "B" + rand,
71
        ERR = "E" + rand,
72
        COLL = "C" + rand;
73
74
    function reconvert(str) {
75
        str = str.replace(/(\\u)(\w{1,4})/gi, function($0) {
76
            return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
77
        });
78
        str = str.replace(/(&#x)(\w{1,4});/gi, function($0) {
79
            return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"), 16));
80
        });
81
        str = str.replace(/(&#)(\d{1,6});/gi, function($0) {
82
            return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
83
        });
84
85
        return str;
86
    }
87
88
    function units(size) {
89
        return size > 1048576 ? (0 | (size / 1048576)) + "MB" :
90
            size > 1024 ? (0 | (size / 1024)) + "KB" :
91
            size + "B";
92
    }
93
94
    function fragment(a, b) {
95
        var frag = document.createDocumentFragment();
96
        frag.appendChild(document.createTextNode(a));
97
        if (b) {
98
            frag.appendChild(div.cloneNode());
99
            frag.appendChild(document.createTextNode(b));
100
        } else {
101
            frag.appendChild(document.createElement("br"));
102
        }
103
        return frag;
104
    }
105
106
    function change(node, query, name, set) {
107
        var list = node.querySelectorAll(query),
108
            i = list.length;
109
        for (; i--;) list[i].classList[set ? "add" : "remove"](name);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
110
    }
111
112
    function changeSiblings(node, name, set) {
113
        var tmp, i = 0,
114
            query = [];
115
116
        for (; node && node.tagName === "I";) {
117
            tmp = node.previousElementSibling;
118
            if (tmp && tmp.className == KEY) {
119
                query.unshift(".D" + rand + ">i.I" + rand + "[data-key='" + node.dataset.key + "']");
120
            } else if (query[0]) {
121
                query.unshift(".D" + rand + ">i.I" + rand);
122
            } else {
123
                for (; tmp; tmp = tmp.previousElementSibling)
124
                    if (tmp.tagName === "BR") i++;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
125
                query.unshift(".D" + rand + ">" + (i ? "br:nth-of-type(" + i + ")+i.I" + rand : "i.I" + rand + ":first-child"));
126
            }
127
            node = node.parentNode && node.parentNode.previousElementSibling;
128
        }
129
        if (!query[1]) return;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
130
        query[0] = ".R" + rand + ">i.I" + rand;
131
        change(document, query.join("+"), name, set);
132
    }
133
134
    function keydown(e) {
135
        if (hovered) {
136
            e.preventDefault();
137
            if (e.altKey) {
138
                changeSiblings(hovered, HOV, 1);
139
            } else if (e[mod]) {
140
                change(hovered.nextSibling, "i.I" + rand, HOV, 1);
141
            }
142
        }
143
    }
144
145
    function init() {
146
        tag = document.createElement("style");
147
        tag.textContent = [
148
            '.R', ',.D', '{font:16px ' + fontStyle + '}' +
149
            '.D', '{margin-left:6px; padding-left:1em; margin-top: 1px; border-left:1px dashed; border-color: #93A1A1;}' +
150
            '.X', '{border:1px solid #ccc; padding:1em}' +
151
            'a.L', '{text-decoration:none}' +
152
            'a.L', ':hover,a.L', ':focus{text-decoration:underline}' +
153
            'i.I', '{cursor:pointer;color:#ccc}' +
154
            'i.H', ',i.I', ':hover{text-shadow: 1px 1px 3px #999; color:#333}' +
155
            'i.I', ':before{content:" ▼ "}' +
156
            'i.C', ':before{content:" ▶ "}' +
157
            'i.I', ':after{content:attr(data-content)}' +
158
            'i.C', '+.D', '{width:1px; height:1px; margin:0; padding:0; border:0; display:inline-block; overflow:hidden}' +
159
            '.S', '{color:' + strColor + '}' + // string
160
            '.K', '{color:' + keyColor + '}' + // key
161
            '.E', '{color:#BCADAD}' + // error
162
            '.B', '{color:' + intColor + '}' + // number and bool
163
            '.E', ',.B', '{font-style: italic}' + // number bold
164
            'h3.E', '{margin:0 0 1em}'
165
        ].join(rand);
166
167
        tag.textContent = tag.textContent + 'body {background: ' + bgColor + '; color:' + defaultColor + ';}';
168
169
        div.classList.add(DIV);
170
        document.head.appendChild(tag);
171
        document.addEventListener("keydown", keydown);
172
        document.addEventListener("keyup", function(e) {
0 ignored issues
show
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
173
            if (hovered) change(document, "." + HOV, HOV);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
174
        })
175
        document.addEventListener("mouseover", function(e) {
176
            if (e.target.tagName === "I") {
177
                hovered = e.target;
178
                keydown(e);
179
            }
180
        })
181
        document.addEventListener("mouseout", function(e) {
0 ignored issues
show
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
182
            if (hovered) {
183
                change(document, "." + HOV, HOV);
184
                hovered = null;
185
            }
186
        })
187
    }
188
189
    function draw(str, to, first, box) {
190
        tag || init();
191
192
        var re = /("(?:((?:https?|file):\/\/(?:\\?\S)+?)|(?:\\?.)*?)")\s*(:?)|-?\d+\.?\d*(?:e[+-]?\d+)?|true|false|null|[[\]{},]|(\S[^-[\]{},"\d]*)/gi,
193
            node = div.cloneNode(),
194
            link = document.createElement("a"),
195
            span = document.createElement("span"),
196
            info = document.createElement("i"),
197
            colon = document.createTextNode(": "),
198
            comma = fragment(","),
199
            path = [],
200
            cache = {
201
                "{": fragment("{", "}"),
202
                "[": fragment("[", "]")
203
            };
204
205
        node.className = "R" + rand + (box ? " " + box : "");
206
207
        link.classList.add("L" + rand);
208
        info.classList.add("I" + rand);
209
210
        to.addEventListener("click", function(e) {
211
            var target = e.target,
212
                open = target.classList.contains(COLL);
213
            if (target.tagName == "I") {
214
                if (e.altKey) {
215
                    changeSiblings(target, COLL, !open);
216
                } else if (e[mod]) {
217
                    open = target.nextSibling.querySelector("i");
218
                    if (open) change(target.nextSibling, "i", COLL, !open.classList.contains(COLL));
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
219
                } else {
220
                    target.classList[open ? "remove" : "add"](COLL);
221
                }
222
            }
223
        }, true);
224
225
        to.replaceChild(box = node, first);
226
        loop(str, re);
227
228
        function loop(str, re) {
229
            str = reconvert(str);
230
            var match, val, tmp, i = 0,
231
                len = str.length;
232
            try {
233
                for (; match = re.exec(str);) {
234
                    val = match[0];
235
                    if (val == "{" || val == "[") {
236
                        path.push(node);
0 ignored issues
show
The variable node is changed as part of the for loop for example by node.lastChild.previousSibling on line 238. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
237
                        node.appendChild(cache[val].cloneNode(true));
238
                        node = node.lastChild.previousSibling;
239
                        node.len = 1;
240
                        node.start = re.lastIndex;
241
                    } else if ((val == "}" || val == "]") && node.len) {
242
                        if (node.childNodes.length) {
243
                            tmp = info.cloneNode();
244
                            if (!hideDetails) {
245
                                tmp.dataset.content = node.len + (
246
                                    node.len == 1 ?
247
                                    (val == "]" ? " item, " : " property, ") :
248
                                    (val == "]" ? " items, " : " properties, ")
249
                                ) + units(re.lastIndex - node.start + 1);
250
                            }
251
252
                            if ((val = node.previousElementSibling) && val.className == KEY) {
253
                                tmp.dataset.key = reconvert(val.textContent.slice(1, -1).replace(/'/, "\\'"));
254
                            }
255
                            node.parentNode.insertBefore(tmp, node);
256
                        } else {
257
                            node.parentNode.removeChild(node);
258
                        }
259
                        node = path.pop();
260
                    } else if (val == ",") {
261
                        node.len += 1;
262
                        node.appendChild(comma.cloneNode(true));
263
                    } else {
264
                        if (match[2]) {
265
                            tmp = link.cloneNode();
266
                            tmp.href = match[2].replace(/\\"/g, '"');
267
                        } else {
268
                            tmp = span.cloneNode();
269
                        }
270
                        tmp.textContent = match[1] || val;
271
                        tmp.classList.add(match[3] ? KEY : match[1] ? STR : match[4] ? ERR : BOOL);
272
                        node.appendChild(tmp);
273
                        if (match[3]) {
274
                            node.appendChild(colon.cloneNode());
275
                        }
276
                    }
277
                    if (++i > 1000) {
278
                        document.title = (0 | (100 * re.lastIndex / len)) + "% of " + units(len);
279
                        return setTimeout(function() {
280
                            loop(str, re)
281
                        });
282
                    }
283
                }
284
                document.title = ""
285
                JSON.parse(str)
0 ignored issues
show
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
286
            } catch (e) {
287
                tmp = document.createElement("h3");
288
                tmp.className = ERR;
289
                tmp.textContent = e;
290
                box.insertBefore(tmp, box.firstChild);
0 ignored issues
show
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
291
            }
292
        }
293
    }
294
295
    if (strictOnly) {
296
        // only render when the contentType is json
297
        if (/[+\/]json$/i.test(document.contentType)) {
298
            draw(str, body, first)
0 ignored issues
show
The variable str seems to be never initialized.
Loading history...
299
        }
300
    } else {
301
        // check whether the content is json or like json
302
        if (first &&
303
            (first.tagName == "PRE" &&
304
                first == body.lastElementChild ||
305
                first == body.lastChild &&
306
                first.nodeType == 3) &&
307
            (str = first.textContent) &&
308
            (/[+\/]json$/i.test(document.contentType) ||
309
                (jsonpMatch = /^\s*((?:\/\*\*\/\s*)?([$a-z_][$\w]*)\s*(?:&&\s*\2\s*)?\()([^]+)(\)[\s;]*)$/i.exec(str)) &&
310
                jsonRe.test(jsonpMatch[3]) || jsonRe.test(str))) {
311
            if (jsonpMatch) {
312
                str = jsonpMatch[3]
313
                body.replaceChild(fragment(jsonpMatch[1], jsonpMatch[4]), first)
314
                first = body.lastChild.previousSibling
315
            }
316
            draw(str, body, first)
317
        }
318
    }
319
320
    chrome.runtime.onMessage.addListener(function(req, sender, sendResponse) {
0 ignored issues
show
The parameter sender is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
The parameter sendResponse is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
321
        var node,
322
            sel = window.getSelection(),
323
            range = sel.rangeCount && sel.getRangeAt(0),
324
            str = range && range.toString()
325
326
        if (!str) return
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
327
328
        if (req.op === "formatSelection") {
329
            node = document.createElement("div")
330
            range.deleteContents()
331
            range.insertNode(node)
332
            sel.removeAllRanges()
333
            draw(str, node.parentNode, node, "X" + rand)
334
        }
335
    })
336
}
337
338
var getting = browser.storage.local.get();
0 ignored issues
show
The variable browser seems to be never declared. If this is a global, consider adding a /** global: browser */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
339
getting.then(onGot, onError);
340