-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript-console.js
315 lines (300 loc) · 10.5 KB
/
javascript-console.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
var StackTrace = require('stacktrace-js');
var Path = require('path');
class JavaScriptConsole {
/**
* @constructor
* @param {Element} view - A DOM node where the console is to be created.
* @param {Object} options - Configuration options:
* - beforeAppend(clientId, type, stack, args...): optional. A callback
* to be called before a line is appended to the console.
* - afterAppend(line): optional. A callback to be called after a line
* has been appended to the console.
* - afterClear(): optional. A callback to be called when the console is
* cleared.
* - onCodeInput(code): optional. A callback to be called when the user
* enters some text in the bottom text field and presses Enter.
* - onFilerefClick(fileref): optional. A callback to be called when a
* stack frame on the right of a line is clicked.
* @return {JavaScriptConsole} The created JavaScriptConsole object.
*/
constructor(view, options = {}) {
this.view = view;
this.beforeAppend = options.beforeAppend;
this.afterAppend = options.afterAppend;
this.afterClear = options.afterClear;
this.onCodeInput = options.onCodeInput;
this.onFilerefClick = options.onFilerefClick;
this.useCallbacks = true;
this.history = [];
this.historyIndex = 0;
this.colors = {};
this.localColor = 'black';
this.disabledColor = '#999';
this.objects = {};
this.nextObjectId = 1;
view.classList.add('javascript-console');
view.innerHTML = `
<div class="toolbar">
<span class="fa fa-trash-o"></span>
<input type="text" class="filter" placeholder="Search" />
</div>
<div class="history"></div>
<input type="text" class="code-input" placeholder="Enter JavaScript code ..." />
`;
var clearButton = view.getElementsByClassName('fa-trash-o')[0];
clearButton.addEventListener('click', (event) => { this.clear(); });
var filterInput = view.getElementsByClassName('filter')[0];
filterInput.addEventListener('keyup', (event) => {
this.filterTerm = event.target.value.toLowerCase();
this.filterByName(this.filterTerm, this.historyView.childNodes);
});
this.filterTerm = '';
this.historyView = view.getElementsByClassName('history')[0];
var codeInput = view.getElementsByClassName('code-input')[0];
codeInput.addEventListener('keydown', (event) => {
this.onCodeKeydown(event);
});
view.addEventListener('click', (event) => {
var target = event.target;
if (!target.classList) {
return;
}
if (target.classList.contains('expandable')) {
this.toggleObject(event);
} else if (target.classList.contains('fileref')) {
if (this.onFilerefClick) {
var fileref = this.objects[target.dataset.filerefId];
this.onFilerefClick(fileref);
}
}
});
}
/**
* Intercept all console logs and errors generated by the given window.
* @param {Window} window - A window whose console logs and errors are to be
* added to the console.
*/
attachToWindow(window) {
if (window._javaScriptConsole_) {
throw 'Already bound to this window.';
}
var console = window.console;
var oldConsole = {log: console.log, debug: console.debug,
info: console.info, warn: console.warn, error: console.error,
count: console.count, assert: console.assert};
window._javaScriptConsole_ = {oldConsole};
var consoleApply = (type, args, jsonArgs, stack) => {
if (oldConsole[type] && args) {
oldConsole[type].apply(console, args);
}
jsonArgs = jsonArgs || args;
if (!stack) {
stack = StackTrace.getSync();
stack.splice(0, 2);
}
var clientId = window._javaScriptConsole_.clientId;
this.append(clientId, type, stack, ...jsonArgs);
}
console.log = (...args) => {
consoleApply('log', args);
};
console.debug = (...args) => {
consoleApply('debug', args);
};
console.info = (...args) => {
consoleApply('info', args);
};
console.warn = (...args) => {
consoleApply('warn', args);
};
console.error = (...args) => {
consoleApply('error', args);
};
var consoleCount = {};
console.count = (...args) => {
var label = args[0];
var count = (consoleCount[label] = (consoleCount[label] || 0) + 1);
consoleApply('count', args, [`${label}:`, count]);
};
console.assert = (...args) => {
var assertion = args[0];
if (!assertion) {
args.splice(0, 1);
consoleApply('assert', args);
}
};
window.addEventListener('error', (event) => {
StackTrace.fromError(event.error).then((stack) => {
consoleApply('exception', [event.message], null, stack);
});
});
}
/**
* Set a clientId to be associated with the given window.
* Each line appended by that window will have the clientId as a data attribute.
* @param {String} clientId - The new clientId.
* @param {Window} window - The window to be associated with the clientId.
*/
setClientId(window, clientId) {
window._javaScriptConsole_.clientId = clientId;
}
onCodeKeydown(event) {
var input = event.target;
var historyElement;
if (event.which === 13) {
var code = input.value;
if (code === 'console.clear()') {
this.clear();
} else if (this.useCallbacks && this.onCodeInput) {
this.onCodeInput(code);
} else {
return;
}
this.history.push(code);
input.value = '';
} else if (event.which === 38) {
this.historyIndex = Math.max(0, this.historyIndex - 1);
historyElement = (this.historyIndex < this.history.length ? this.history[this.historyIndex] : '');
input.value = historyElement;
} else if (event.which === 40) {
this.historyIndex = Math.min(this.history.length, this.historyIndex + 1);
historyElement = (this.historyIndex < this.history.length ? this.history[this.historyIndex] : '');
$input.value = historyElement;
}
}
scrollToBottom() {
this.historyView.scrollTop = this.historyView.scrollHeight;
}
filterByName(name, elements) {
for (var element of elements) {
element.classList.toggle('filtered-out', name !== '' && element.textContent.toLowerCase().indexOf(name) === -1);
}
}
applyFilter(elements) {
elements = elements || this.historyView.childNodes;
this.filterByName(this.filterTerm, elements);
this.scrollToBottom();
}
/**
* Change the text color for lines associated with a certain clientId.
* @param {String} clientId - The clientId whose color is to be changed.
* @param {String} color - The color to be associated with the given clientId.
*/
setColor(clientId, color) {
if (color) {
this.colors[clientId] = color;
} else {
delete this.colors[clientId];
color = this.disabledColor;
}
for (var line of this.historyView.querySelectorAll(`[data-client-id="${clientId}"]`)) {
line.getElementsByClassName('content')[0].style.color = color;
}
}
parseArg(arg) {
if (arg === undefined) {
return '<span class="keyword">undefined</span>';
} else if (arg === null) {
return '<span class="keyword">null</span>';
} else if (Array.isArray(arg)) {
var elements = arg.map((element) => this.parseArg(element)).join('');
return `<span>Array [${elements}]</span>`;
} else if (typeof(arg) === 'object') {
var span = `<span data-object-id="${this.nextObjectId}" class="expandable">Object</span>`;
this.objects[this.nextObjectId] = arg;
this.nextObjectId += 1;
return span;
} else if (typeof(arg) === 'function') {
arg = arg.toString();
arg = arg.substr(0, arg.indexOf('{'));
return `<span>${arg}</span>`;
} else {
var temp = document.createElement('div');
temp.textContent = arg;
arg = temp.innerHTML;
return `<span>${arg}</span>`;
}
}
/**
* Append a line to the console with a variable number of arguments.
* @param {String} clientId - The clientId to be associated with this line.
* @param {String} type - One of `log`, `info`, `warn`, `error`, `assert`,
* `exception`, `code`. The type affects the icon and the background color
* of the line.
* @param {[StackFrame]} stack - The call stack. The first StackFrame object
* will be visible on the right of the line. This parameter can be null.
* @param args - The objects to be printed.
*/
append(clientId, type, stack, ...args) {
if (this.useCallbacks && this.beforeAppend) {
this.beforeAppend(clientId, type, stack, ...args);
}
var content = '';
if (stack && stack[0].fileName) {
var file = stack[0];
var label = `${Path.basename(file.fileName)}:${file.lineNumber}:${file.columnNumber}`;
var fileref = `<a href="#" data-fileref-id="${this.nextObjectId}" class="fileref">${label}</a>`;
this.objects[this.nextObjectId] = file;
this.nextObjectId += 1;
content += fileref;
}
content += args.map((arg) => this.parseArg(arg)).join('');
var color = (clientId ? this.colors[clientId] || this.disabledColor : this.localColor);
content = `<span class="content" style="color:${color}">${content}</span>`;
var icons = {log: 'angle-left', info: 'info-circle', warn: 'warning',
error: 'times', count: 'angle-left', assert: 'exclamation',
exception: 'times-circle', code: 'angle-right'};
var icon = icons[type];
type = {assert: 'error', exception: 'error', count: 'log'}[type] || type;
var line = document.createElement('div');
line.className = `line ${type}`;
if (clientId) {
line.dataset.clientId = clientId;
}
line.innerHTML = `<span class="fa fa-${icon}"></span>${content}</div>`;
this.historyView.appendChild(line);
this.applyFilter([line]);
if (this.useCallbacks && this.afterAppend) {
this.afterAppend(line);
}
}
toggleObject(event) {
var element = event.target;
var next = element.nextSibling;
if (next && next.classList && next.classList.contains('expansion')) {
next.classList.toggle('expanded');
} else {
var object = this.objects[element.dataset.objectId];
var content = '';
var isProto = element.parentNode.classList.contains('proto');
for (var property in object) {
if (isProto || object.hasOwnProperty(property)) {
try {
content += `<div><span>${property}:</span>${this.parseArg(object[property])}</div>`;
} catch (e) {}
}
}
var proto = `<div class="proto"><span>__proto__:</span>${this.parseArg(object.__proto__)}</div>`;
content += proto;
var expansion = document.createElement('span');
expansion.classList = `expansion expanded`;
expansion.innerHTML = `{<div class="indent">${content}</div>}`;
if (next) {
element.parentNode.insertBefore(expansion, next);
} else {
element.parentNode.appendChild(expansion);
}
}
}
/**
* Clear the console.
*/
clear() {
this.historyView.innerHTML = '';
this.objects = {};
if (this.useCallbacks && this.afterClear) {
this.afterClear();
}
}
}
module.exports = JavaScriptConsole;