This repository has been archived by the owner on Oct 21, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmob-log.js
466 lines (436 loc) · 16.7 KB
/
mob-log.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
(function(){
// --- HELPERS ---
// Branches-JS element builder
String.prototype.$ = function(attr){
var ele = document.createElement(this);
if(attr) for(key in attr) ele.setAttribute(key, attr[key]);
return new Branches(ele);
};
var Branches = function(ele){this.ele = ele}
Branches.prototype = {
txt : function(content){
var txtNode = document.createTextNode(content);
this.ele.appendChild(txtNode);
return this;
},
html : function(customHtml){
this.ele.innerHTML = customHtml;
return this;
},
add : function(content){
var self = this;
content.forEach(function(val, ind){
if(val == '[object NodeList]' || val == '[object HTMLCollection]'){
for (var i = val.length - 1; i >= 0; i--) { self.ele.appendChild(val[i]) };
}
else self.ele.appendChild(val.ele);
})
return this;
},
raw : function(){
return this.ele.outerHTML;
},
get : function(){
return this.ele;
},
frag : function(){
var frag = document.createDocumentFragment();
frag.appendChild(this.ele);
return frag;
}
}
// id selector
function _id(query){return document.getElementById(query);}
// classList replacements
function addClass(node,className){
className = className.split(",");
for(var i=0; i < className.length; i++){
if((" "+node.className+" ").indexOf(" "+className[i]+" ") == -1)node.className+=" "+className[i];
}
}
function removeClass(node, className){
var nodeClasses = node.className;
className = className.split(",");
for(var i=0; i < className.length; i++){
nodeClasses = nodeClasses.replace(className[i], '');
}
node.className = nodeClasses;
}
// ./ --- HELPERS ---
// --- MobLog Code ---
var css = {
// Note that the css is being prepended with "MobLog-" after the selector
'#MobLog' : {
background: 'white',
width: '300px',
position: 'fixed',
top: '5px',
right: '-295px',
boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)',
fontFamily: "'Arial', 'Helvetica', 'sans-serif' !important",
transition: 'right 0.5s ease-out',
fontSize: '12px !important'
},
'.showLog' : {
right: '5px !important'
},
'#output' : {
maxHeight: '200px',
overflowY: 'auto'
},
'#input' : {
width: '100%',
padding: '2px 2px 5px 4px',
margin: '0',
border: '0',
boxSizing: 'border-box'
},
'#input:focus' : {
outline: '0',
borderBottom: '1.5px solid #95a5a6'
},
'#triggerShow' : {
background: '#3498db',
boxShadow: '0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)',
color: '#ecf0f1',
fontSize : '26px',
fontWeight: 'bold',
width: '40px',
height: '35px',
marginLeft: '-40px',
marginBottom: '-35px',
padding: '7px',
textAlign: 'center',
boxSizing: 'border-box',
borderTopLeftRadius: '20px',
borderBottomLeftRadius: '20px',
cursor: 'pointer'
},
'#triggerShow-text' : {
marginTop: '-6.5px'
},
'.rotate' : {
transform: 'rotate(180deg)',
'-webkit-transform': 'rotate(180deg)',
marginTop: '-3.5px !important'
},
'.line' : {
padding: '3px',
color: '#34495e'
},
'.systemError' : {
backgroundColor : '#e74c3c !important',
color : 'white !important'
},
'.errorLineLink' : {
fontWeight : 'bold',
color : 'white'
},
'.codeBlock' : {
background: '#34495e !important',
color: 'white'
},
'.fileName' : {
background : 'rgba(44, 62, 80,1.0)',
margin : '-2px -2px 0px -2px',
padding: '4px 4px 2px 4px',
fontWeight : 'bold'
},
'.tab' : {
background : '#34495e',
padding : '2px 12px 2px 15px',
marginLeft : '20px',
borderTopLeftRadius : '7px',
borderTopRightRadius : '7px'
},
'.tab-exit' : {
background : '#e74c3c',
borderRadius: '50%',
width: '7px',
height: '7px',
margin: '1px 0px 0px 4px',
display: 'inline-block',
cursor : 'pointer'
},
'.line-error-highlight' : {
background : 'rgba(231, 76, 60, 0.4)'
},
'.line:nth-child(even)': {
backgroundColor: '#ecf0f1'
},
'.line:nth-child(odd)': {
backgroundColor: '#DCE3E5'
},
'.type' : {
fontSize: '16px',
fontWeight: 'bold',
padding: '1px 9px 1px 9px',
},
'.type-info' : {
color: '#3498db',
},
'.type-error' : {
color : '#e74c3c'
},
'.type-regular' : {
color : '#34495e'
},
'.type-systemError' : {
fontSize : '0.82em',
marginLeft : '-3.5px',
color : '#fff !important'
}
}
var app = {
settings : { // Settings which aren't major enough to let the user adjust in the init call
codeViewerScope : 2 // The amount of lines surrounding the error line when opening the code inspector
},
state : {
isInitialized : false,
isHidden : true
},
cache : {
outputElement : undefined, // [DOM Node]
logsBeforeDOMLoad : [], // Whenever a console call happens before the MobLog element has been inserted, cache it
_console : {}, // Save the original console fn
commands : [], // Store commands exectuted by the user
cmdHistoryIndex : 0 // Index of command hostory navigation
}
}
function init(options){
if(app.state.isInitialized) throw "UNAUTHORIZED: MobLog has already been initialized, due to security reasons you may not initialize it again.";
app.state.isInitialized = true;
options.intercept = options.intercept || false;
options.allowInput = options.allowInput || false;
options.catchErrors = options.catchErrors || false;
options.api = options.api || false;
// Generate the CSS
document.head.appendChild(generateCSS());
// Generate the HTML and DOM apply events
var MobLogHTML = buildConsole(options.allowInput);
document.addEventListener('DOMContentLoaded', function(){
document.body.appendChild(MobLogHTML);
app.cache.outputElement = document.getElementById('MobLog-output');
writeCachedConsoleCalls();
applyEvents(options.allowInput);
}, false);
// Catch errors caused by malfunctioning code
if(options.catchErrors){
window.onerror = function(message, source, lineno) {
handleWindowError(message, source, lineno);
}
}
// Extend console calls
if(options.intercept){
options.intercept.forEach(function(type){
app.cache._console[type] = console[type];
console[type] = extendConsole(type);
});
}
}
function generateCSS(){
var styleString = '';
String.prototype.toDashedCase = function(){return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();}
Object.keys(css).forEach(function(selector){
if(selector !== '#MobLog') styleString += selector.replace(selector[0], selector[0]+'MobLog-')+'{';
else styleString += selector+'{';
for(style in css[selector]){
styleString += style.toDashedCase()+':'+css[selector][style]+';';
}
styleString += '}';
});
return 'style'.$().txt(styleString).frag();
}
function buildConsole(hasInput){
var consoleFragment =
'div'.$({'id' : 'MobLog'}).add([
'div'.$({'id' : 'MobLog-triggerShow'}).add([
'div'.$({'id' : 'MobLog-triggerShow-text'}).txt('«')
]),
'div'.$({'id' : 'MobLog-output'}),
(function(){ return hasInput ? 'input'.$({'type' : 'text', 'id' : 'MobLog-input'}) : 'span'.$() })()
]).frag();
return consoleFragment;
}
function applyEvents(hasInput){
// Input events
if(hasInput){
var input = _id('MobLog-input');
input.addEventListener('keyup', function(e){
if(e.keyCode == 13 || e.which == 13){
app.cache.commands.push(this.value);
eval(this.value);
this.value = '';
}
else if(e.keyCode == 38 || e.which == 38){
if(app.cache.cmdHistoryIndex !== (app.cache.commands.length)){
var commandList = app.cache.commands;
var commandIndex = (commandList.length-1)-app.cache.cmdHistoryIndex;
app.cache.cmdHistoryIndex += 1;
this.value = commandList[commandIndex];
}
}
else if(e.keyCode == 40 || e.which == 40){
if(app.cache.cmdHistoryIndex == 1){
this.value = '';
app.cache.cmdHistoryIndex = 0;
}
else if(app.cache.cmdHistoryIndex !== 0){
app.cache.cmdHistoryIndex -= 1;
var commandList = app.cache.commands;
var commandIndex = (commandList.length)-app.cache.cmdHistoryIndex;
this.value = commandList[commandIndex];
}
else this.value = '';
}
else app.cache.cmdHistoryIndex = 0;
}, false);
}
// Display events
var triggerShow = _id('MobLog-triggerShow');
triggerShow.addEventListener('mouseup', function(){
if(app.state.isHidden){
addClass(_id('MobLog'), 'MobLog-showLog');
addClass(_id('MobLog-triggerShow-text'), 'MobLog-rotate');
app.state.isHidden = false;
}
else{
removeClass(_id('MobLog'), 'MobLog-showLog');
removeClass(_id('MobLog-triggerShow-text'), 'MobLog-rotate');
app.state.isHidden = true;
}
}, false);
}
function extendConsole(type){
var newLog = function(){
if(app.cache.outputElement) write(arguments, type);
else app.cache.logsBeforeDOMLoad.push({args : arguments, type : type});
}
return function(){
newLog.apply(this, arguments);
if (typeof app.cache._console[type] === 'function') {
app.cache._console[type].apply(console, arguments);
}
};
}
function write(args, type){
var typeTransform = {
info : 'span'.$({'class' : 'MobLog-type MobLog-type-info'}).txt('i'),
log : 'span'.$({'class' : 'MobLog-type MobLog-type-regular'}).txt('-'),
error : 'span'.$({'class' : 'MobLog-type MobLog-type-error'}).txt('!'),
systemError : 'span'.$({'class' : 'MobLog-type MobLog-type-systemError'}).html('❌')
}
var newLineClassName = 'MobLog-line';
if(type == 'systemError'){
var output = args.join(' ');
newLineClassName += ' MobLog-systemError';
}
else{
var output = '';
for (var i = 0; i < args.length; i++) {
if(typeof args[i] == 'object') output += handleObjectType(args[i]);
else output += colorByType(args[i]);
output += ' ';
}
}
var newLine = 'div'.$({'class' : newLineClassName}).html(typeTransform[type].raw()+' '+output).frag();
app.cache.outputElement.appendChild(newLine);
app.cache.outputElement.scrollTop += app.cache.outputElement.lastChild.offsetHeight;
applyNewLineEvents(app.cache.outputElement.lastChild);
}
function writeCachedConsoleCalls(){
app.cache.logsBeforeDOMLoad.forEach(function(data){
write(data.args, data.type);
});
}
function applyNewLineEvents(newLineNode){
var errorLineLink = newLineNode.querySelector('.MobLog-errorLineLink');
if(errorLineLink){
errorLineLink.addEventListener('mouseup', function(e){
e.preventDefault();
var url = this.getAttribute('data-url');
var file = this.getAttribute('data-file');
var line = parseInt(this.getAttribute('data-line'));
displayErrorLine(url, file, line);
}, false);
}
}
function handleWindowError(message, source, lineno){
sourceArr = source.split('/');
var file = sourceArr[sourceArr.length-1];
source = 'a'.$({
'href' : '#',
'class' : 'MobLog-errorLineLink',
'data-url' : source,
'data-file' : file,
'data-line' : lineno
}).txt('['+file+':'+lineno+']').raw();
var errorLine = [message, source];
if(app.cache.outputElement) write(errorLine, 'systemError');
else app.cache.logsBeforeDOMLoad.push({args : errorLine, type : 'systemError'});
}
function displayErrorLine(url, file, line){
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) buildCodeBlock(request.responseText);
else console.error('MobLog: Error loading file data for file '+file);
};
request.onerror = function() {
console.error('MobLog: Error loading file data for file '+file);
};
request.send();
function buildCodeBlock(serverData){
var scope = app.settings.codeViewerScope;
var fileContent = serverData.replace(/</g, '<').replace(/>/g, '>').replace(/\t/g, ' ').split('\n');
var output = {
before : [],
after : []
}
for (var i = 0; i < scope; i++) {
output.before.push((line-(i+1))+' : '+fileContent[line-(i+2)]);
output.after.push((line+(i+1))+' : '+fileContent[line+i]);
};
var fileOutput =
output.before.reverse().join('<br>')+
'div'.$({'class' : 'MobLog-line-error-highlight'}).html((line)+' : '+fileContent[line-1]).raw()+
output.after.join('<br>');
var outputFragment = 'div'.$({'class' : 'MobLog-line MobLog-codeBlock'}).html('<div class="MobLog-fileName"><span class="MobLog-tab">'+file+' <div class="MobLog-tab-exit"></div></span></div>'+fileOutput).frag();
app.cache.outputElement.appendChild(outputFragment);
app.cache.outputElement.scrollTop += app.cache.outputElement.lastChild.offsetHeight;
}
}
function colorByType(inp){
switch(typeof inp){
case 'number' :
var coloredType = 'span'.$({'style' : 'color: #3694D3'}).txt(inp);
break;
case 'boolean':
var coloredType = 'span'.$({'style' : 'color: #9b59b6'}).txt(inp);
break;
case 'string' :
var coloredType = 'span'.$({'style' : 'color: #e74c3c'}).txt('"'+inp+'"');
break;
default:
return inp;
}
return coloredType.raw();
}
function handleObjectType(obj){
var output = '';
if(Array.isArray(obj)){
output += '[';
obj.forEach(function(t, ind){
output += colorByType(t)+(obj.length !== ind+1 ? ', ' : '');
});
output += ']';
}
// ADD CODE HIGHTLIGHTING
else output += JSON.stringify(obj);
return output;
}
// Assign safe functions to global scope (learned this from screenlog.js, fantastic solution!)
window.MobLog = {
init : init
}
})();