Completed
Push — master ( bbd6f2...66200a )
by Dongxin
26s
created

mjsonviewer.js (16 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
var bgColor, intColor, strColor, keyColor, defaultColor;
24
25
function onError(error) {
26
    console.log(`Error: ${error}`);
0 ignored issues
show
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
27
}
28
29
function onGot(result) {
30
    if (result[0]) {
31
        bgColor      = result[0].bgColor      || "#FDF6E3";
32
        intColor     = result[0].intColor     || "#657A81";
33
        strColor     = result[0].strColor     || "#2AA198";
34
        keyColor     = result[0].keyColor     || "#B58900";
35
        defaultColor = result[0].defaultColor || "#586E75";
36
    } else {
37
        bgColor      = result.bgColor      || "#FDF6E3";
38
        intColor     = result.intColor     || "#657A81";
39
        strColor     = result.strColor     || "#2AA198";
40
        keyColor     = result.keyColor     || "#B58900";
41
        defaultColor = result.defaultColor || "#586E75";
42
    }
43
44
    var str, jsonpMatch, hovered, tag,
45
        chrome = this.chrome || this.browser,
46
        jsonRe = /^\s*(?:\[\s*(?=-?\d|true|false|null|["[{])[^]*\]|\{\s*"[^]+\})\s*$/,
47
        div    = document.createElement("div"),
48
        body   = document.body,
49
        first  = body && body.firstChild,
50
        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...
51
        rand   = Math.random().toString(36).slice(2),
52
        HOV    = "H" + rand,
53
        DIV    = "D" + rand,
54
        KEY    = "K" + rand,
55
        STR    = "S" + rand,
56
        BOOL   = "B" + rand,
57
        ERR    = "E" + rand,
58
        COLL   = "C" + rand;
59
60
    function reconvert(str){
61
        str = str.replace(/(\\u)(\w{1,4})/gi, function($0) {
62
            return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{1,4})/g, "$2")), 16)));
63
        });
64
        str = str.replace(/(&#x)(\w{1,4});/gi, function($0) {
65
            return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{1,4})(%3B)/g, "$2"),16));
66
        });
67
        str = str.replace(/(&#)(\d{1,6});/gi, function($0) {
68
            return String.fromCharCode(parseInt(escape($0).replace(/(%26%23)(\d{1,6})(%3B)/g, "$2")));
69
        });
70
71
        return str;
72
    }
73
74
    function units(size) {
75
        return size > 1048576 ? (0|(size / 1048576)) + "MB" :
76
            size > 1024 ? (0|(size / 1024)) + "KB" :
77
            size + "B";
78
    }
79
80
    function fragment(a, b) {
81
        var frag = document.createDocumentFragment();
82
        frag.appendChild(document.createTextNode(a));
83
        if (b) {
84
            frag.appendChild(div.cloneNode());
85
            frag.appendChild(document.createTextNode(b));
86
        } else {
87
            frag.appendChild(document.createElement("br"));
88
        }
89
        return frag;
90
    }
91
92
    function change(node, query, name, set) {
93
        var list = node.querySelectorAll(query), i = list.length;
94
        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...
95
    }
96
97
    function changeSiblings(node, name, set) {
98
        var tmp, i = 0, query = [];
99
100
        for (; node && node.tagName === "I"; ) {
101
            tmp = node.previousElementSibling;
102
            if (tmp && tmp.className == KEY) {
103
                query.unshift(".D" + rand + ">i.I" + rand + "[data-key='" + node.dataset.key + "']");
104
            } else if (query[0]) {
105
                query.unshift(".D" + rand + ">i.I" + rand);
106
            } else {
107
                for (; tmp; tmp = tmp.previousElementSibling) 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...
108
                query.unshift(".D" + rand + ">" + (i ? "br:nth-of-type(" + i + ")+i.I" + rand : "i.I" + rand + ":first-child"));
109
            }
110
            node = node.parentNode && node.parentNode.previousElementSibling;
111
        }
112
        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...
113
        query[0] = ".R" + rand + ">i.I" + rand;
114
        change(document, query.join("+"), name, set);
115
    }
116
117
    function keydown(e) {
118
        if (hovered) {
119
            e.preventDefault();
120
            if (e.altKey) {
121
                changeSiblings(hovered, HOV, 1);
122
            } else if (e[mod]) {
123
                change(hovered.nextSibling, "i.I" + rand, HOV, 1);
124
            }
125
        }
126
    }
127
128
    function init() {
129
        tag = document.createElement("style");
130
        tag.textContent = [
131
            '.R', ',.D', '{font:16px consolas, Menlo, monospace}' +
132
            '.D', '{margin-left:6px; padding-left:1em; margin-top: 1px; border-left:1px dashed; border-color: #93A1A1;}' +
133
            '.X', '{border:1px solid #ccc; padding:1em}' +
134
            'a.L', '{text-decoration:none}' +
135
            'a.L', ':hover,a.L', ':focus{text-decoration:underline}' +
136
            'i.I', '{cursor:pointer;color:#ccc}' +
137
            'i.H', ',i.I', ':hover{text-shadow: 1px 1px 3px #999; color:#333}'+
138
            'i.I', ':before{content:" ▼ "}' +
139
            'i.C', ':before{content:" ▶ "}' +
140
            'i.I', ':after{content:attr(data-content)}' +
141
            'i.C', '+.D', '{width:1px; height:1px; margin:0; padding:0; border:0; display:inline-block; overflow:hidden}' +
142
            '.S', '{color:' + strColor + '}' + // string
143
            '.K', '{color:' + keyColor + '}' + // key
144
            '.E', '{color:#BCADAD}' + // error
145
            '.B', '{color:' + intColor + '}' + // number and bool
146
            '.E', ',.B', '{font-style: italic}' + // number bold
147
            'h3.E', '{margin:0 0 1em}'
148
        ].join(rand);
149
150
        tag.textContent = tag.textContent + 'body {background: ' + bgColor + '; color:' + defaultColor + ';}';
151
152
        div.classList.add(DIV);
153
        document.head.appendChild(tag);
154
        document.addEventListener("keydown", keydown);
155
        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...
156
            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...
157
        })
158
        document.addEventListener("mouseover", function(e) {
159
            if (e.target.tagName === "I") {
160
                hovered = e.target;
161
                keydown(e);
162
            }
163
        })
164
        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...
165
            if (hovered) {
166
                change(document, "." + HOV, HOV);
167
                hovered = null;
168
            }
169
        })
170
    }
171
172
    function draw(str, to, first, box) {
173
        tag || init();
174
175
        var re = /("(?:((?:https?|file):\/\/(?:\\?\S)+?)|(?:\\?.)*?)")\s*(:?)|-?\d+\.?\d*(?:e[+-]?\d+)?|true|false|null|[[\]{},]|(\S[^-[\]{},"\d]*)/gi
176
            , node = div.cloneNode()
177
            , link = document.createElement("a")
178
            , span = document.createElement("span")
179
            , info = document.createElement("i")
180
            , colon = document.createTextNode(": ")
181
            , comma = fragment(",")
182
            , path = []
183
            , cache = {
184
                "{": fragment("{", "}"),
185
                "[": fragment("[", "]")
186
            };
187
188
        node.className = "R" + rand + (box ? " " + box : "");
189
190
        link.classList.add("L" + rand);
191
        info.classList.add("I" + rand);
192
193
        to.addEventListener("click", function(e) {
194
            var target = e.target, open = target.classList.contains(COLL);
195
            if (target.tagName == "I") {
196
                if (e.altKey) {
197
                    changeSiblings(target, COLL, !open);
198
                } else if (e[mod]) {
199
                    open = target.nextSibling.querySelector("i");
200
                    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...
201
                } else {
202
                    target.classList[open ? "remove" : "add"](COLL);
203
                }
204
            }
205
        }, true);
206
207
        to.replaceChild(box = node, first);
208
        loop(str, re);
209
210
        function loop(str, re) {
211
            str = reconvert(str);
212
            var match, val, tmp, i = 0, len = str.length;
213
            try {
214
                for (; match = re.exec(str); ) {
215
                    val = match[0];
216
                    if (val == "{" || val == "[") {
217
                        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 219. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
218
                        node.appendChild(cache[val].cloneNode(true));
219
                        node = node.lastChild.previousSibling;
220
                        node.len = 1;
221
                        node.start = re.lastIndex;
222
                    } else if ((val == "}" || val == "]") && node.len) {
223
                        if (node.childNodes.length) {
224
                            tmp = info.cloneNode();
225
                            tmp.dataset.content = node.len + (
226
                                node.len == 1 ?
227
                                (val == "]" ? " item, " : " property, ") :
228
                                (val == "]" ? " items, " : " properties, ")
229
                            ) + units(re.lastIndex - node.start + 1);
230
231
                            if ((val = node.previousElementSibling) && val.className == KEY) {
232
                                tmp.dataset.key = reconvert(val.textContent.slice(1, -1).replace(/'/, "\\'"));
233
                            }
234
                            node.parentNode.insertBefore(tmp, node);
235
                        } else {
236
                            node.parentNode.removeChild(node);
237
                        }
238
                        node = path.pop();
239
                    } else if (val == ",") {
240
                        node.len += 1;
241
                        node.appendChild(comma.cloneNode(true));
242
                    } else {
243
                        if (match[2]) {
244
                            tmp = link.cloneNode();
245
                            tmp.href = match[2].replace(/\\"/g, '"');
246
                        } else {
247
                            tmp = span.cloneNode();
248
                        }
249
                        tmp.textContent = match[1] || val;
250
                        tmp.classList.add(match[3] ? KEY : match[1] ? STR : match[4] ? ERR : BOOL);
251
                        node.appendChild(tmp);
252
                        if (match[3]) {
253
                            node.appendChild(colon.cloneNode());
254
                        }
255
                    }
256
                    if (++i > 1000) {
257
                        document.title = (0|(100*re.lastIndex/len)) + "% of " + units(len);
258
                        return setTimeout(function() { loop(str, re) });
259
                    }
260
                }
261
                document.title = ""
262
                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...
263
            } catch(e) {
264
                tmp = document.createElement("h3");
265
                tmp.className = ERR;
266
                tmp.textContent = e;
267
                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...
268
            }
269
        }
270
    }
271
272
    // check whether the content is json or like json
273
    if (first
274
        && (first.tagName == "PRE"
275
            && first == body.lastElementChild
276
            || first == body.lastChild
277
            && first.nodeType == 3)
278
        && (str = first.textContent)
279
        && (/[+\/]json$/i.test(document.contentType)
280
            || (jsonpMatch = /^\s*((?:\/\*\*\/\s*)?([$a-z_][$\w]*)\s*(?:&&\s*\2\s*)?\()([^]+)(\)[\s;]*)$/i.exec(str))
281
            && jsonRe.test(jsonpMatch[3]) || jsonRe.test(str)))
282
    {
283
        if (jsonpMatch) {
284
            str = jsonpMatch[3]
285
            body.replaceChild(fragment(jsonpMatch[1], jsonpMatch[4]), first)
286
            first = body.lastChild.previousSibling
287
        }
288
        draw(str, body, first)
289
    }
290
291
    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...
292
        var node,
293
            sel   = window.getSelection(),
294
            range = sel.rangeCount && sel.getRangeAt(0),
295
            str   = range && range.toString()
296
297
        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...
298
299
        if (req.op === "formatSelection") {
300
            node = document.createElement("div")
301
            range.deleteContents()
302
            range.insertNode(node)
303
            sel.removeAllRanges()
304
            draw(str, node.parentNode, node, "X" + rand)
305
        }
306
    })
307
}
308
309
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...
310
getting.then(onGot, onError);
311
312