This repository has been archived by the owner on Jun 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 111
/
notifier.js
426 lines (354 loc) · 10.8 KB
/
notifier.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
define(function (require) {
var _ = require('lodash');
var $ = require('jquery');
var metadata = require('ui/metadata');
var formatMsg = require('kibie/notify/lib/_format_msg');
var notifs = [];
var version = metadata.version;
var buildNum = metadata.buildNum;
var consoleGroups = ('group' in window.console) && ('groupCollapsed' in window.console) && ('groupEnd' in window.console);
var fatalSplashScreen = require('ui/notify/partials/fatal_splash_screen.html');
var log = _.bindKey(console, 'log');
// used to identify the first call to fatal, set to false there
var firstFatal = true;
var fatalToastTemplate = (function lazyTemplate(tmpl) {
var compiled;
return function (vars) {
return (compiled || (compiled = _.template(tmpl)))(vars);
};
}(require('ui/notify/partials/fatal.html')));
function now() {
if (window.performance && window.performance.now) {
return window.performance.now();
}
return Date.now();
}
function closeNotif(notif, cb = _.noop, key) {
return function () {
// this === notif
var i = notifs.indexOf(notif);
if (i !== -1) notifs.splice(i, 1);
cancelTimer(notif);
cb(key);
};
}
function cancelTimer(notif) {
if (notif.timerId) {
Notifier.config.clearInterval(notif.timerId);
notif.timerId = undefined;
}
}
function timerCanceler(notif, cb = _.noop, key) {
return function cancelNotifTimer() {
cancelTimer(notif);
cb(key);
};
}
/**
* Initiates a timer to update _timeRemaining_ on the notif at second
* intervals and clears the notif once the notif _lifetime_ has been reached.
*/
function startNotifTimer(notif, cb) {
var interval = 1000;
// kibi: added awesomeDemoMode
if (notif.lifetime === Infinity || Notifier.config.awesomeDemoMode) return;
notif.timeRemaining = Math.floor(notif.lifetime / interval);
notif.timerId = Notifier.config.setInterval(function () {
notif.timeRemaining -= 1;
if (notif.timeRemaining === 0) {
closeNotif(notif, cb, 'ignore')();
}
}, interval, notif.timeRemaining);
notif.cancelTimer = timerCanceler(notif, cb);
}
function restartNotifTimer(notif, cb) {
cancelTimer(notif);
startNotifTimer(notif, cb);
}
function add(notif, cb) {
_.set(notif, 'info.version', version);
_.set(notif, 'info.buildNum', buildNum);
notif.clear = closeNotif(notif);
if (notif.actions) {
notif.actions.forEach(function (action) {
notif[action] = closeNotif(notif, cb, action);
});
}
notif.count = (notif.count || 0) + 1;
notif.isTimed = function isTimed() {
return notif.timerId ? true : false;
};
var dup = _.find(notifs, function (item) {
return item.content === notif.content && item.lifetime === notif.lifetime;
});
if (dup) {
dup.count += 1;
dup.stacks = _.union(dup.stacks, [notif.stack]);
restartNotifTimer(dup, cb);
return dup;
}
startNotifTimer(notif, cb);
notif.stacks = [notif.stack];
notifs.push(notif);
return notif;
}
function formatInfo() {
var info = [];
if (!_.isUndefined(version)) {
info.push(`Version: ${version}`);
}
if (!_.isUndefined(buildNum)) {
info.push(`Build: ${buildNum}`);
}
return info.join('\n');
}
// browsers format Error.stack differently; always include message
function formatStack(err) {
var stackMsg;
if (err.stack && !~err.stack.indexOf(err.message)) {
stackMsg = 'Error: ' + err.message + '\n' + err.stack;
} else {
stackMsg = err.stack;
}
// kibi: display more information when error has body object
if (err.body && err.body.err) {
stackMsg = err.body.err + '\n\n' + stackMsg;
} else if (err.error && err.error.stack) {
stackMsg = err.error.stack;
}
// kibi: end
return stackMsg;
}
/**
* Functionality to check that
*/
function Notifier(opts) {
var self = this;
opts = opts || {};
// label type thing to say where notifications came from
self.from = opts.location;
'event lifecycle timed fatal error warning info'.split(' ').forEach(function (m) {
self[m] = _.bind(self[m], self);
});
}
/**
* Log a major, important, event in the lifecycle of the application
* @param {string} name - The name of the lifecycle event
* @param {boolean} success - Simple flag stating whether the lifecycle event succeeded
*/
Notifier.prototype.lifecycle = createGroupLogger('lifecycle', {
open: true
});
Notifier.config = {
awesomeDemoMode: false, // kibi: hide error messages
errorLifetime: 300000,
warningLifetime: 10000,
infoLifetime: 5000,
setInterval: window.setInterval,
clearInterval: window.clearInterval
};
Notifier.applyConfig = function (config) {
_.merge(Notifier.config, config);
};
// to be notified when the first fatal error occurs, push a function into this array.
Notifier.fatalCallbacks = [];
// simply a pointer to the global notif list
Notifier.prototype._notifs = notifs;
/**
* Log a sometimes redundant event
* @param {string} name - The name of the group
* @param {boolean} success - Simple flag stating whether the event succeeded
*/
Notifier.prototype.event = createGroupLogger('event', {
open: true
});
/**
* Wrap a function so that it's execution time gets logged.
*
* @param {function} fn - the function to wrap, it's .name property is
* read so make sure to set it
* @return {function} - the wrapped function
*/
Notifier.prototype.timed = function (name, fn) {
var self = this;
if (typeof name === 'function') {
fn = name;
name = fn.name;
}
return function WrappedNotifierFunction() {
var cntx = this;
var args = arguments;
return self.event(name, function () {
return fn.apply(cntx, args);
});
};
};
/**
* Kill the page, display an error, then throw the error.
* Used as a last-resort error back in many promise chains
* so it rethrows the error that's displayed on the page.
*
* @param {Error} err - The error that occured
*/
Notifier.prototype.fatal = function (err) {
this._showFatal(err);
throw err;
};
/**
* Display an error that destroys the entire app. Broken out so that
* global error handlers can display fatal errors without throwing another
* error like in #fatal()
*
* @param {Error} err - The fatal error that occured
*/
Notifier.prototype._showFatal = function (err) {
if (firstFatal) {
_.callEach(Notifier.fatalCallbacks);
firstFatal = false;
window.addEventListener('hashchange', function () {
window.location.reload();
});
}
var html = fatalToastTemplate({
info: formatInfo(),
msg: formatMsg(err, this.from),
stack: formatStack(err)
});
var $container = $('#fatal-splash-screen');
if (!$container.size()) {
$(document.body)
// in case the app has not completed boot
.removeAttr('ng-cloak')
.html(fatalSplashScreen);
$container = $('#fatal-splash-screen');
}
$container.append(html);
console.error(err.stack);
};
/**
* Alert the user of an error that occured
* @param {Error|String} err
*/
Notifier.prototype.error = function (err, cb) {
return add({
type: 'danger',
content: formatMsg(err, this.from),
icon: 'warning',
title: 'Error',
lifetime: Notifier.config.errorLifetime,
actions: ['report', 'accept'],
stack: formatStack(err)
}, cb);
};
/**
* Warn the user abort something
* @param {[type]} msg [description]
* @return {[type]} [description]
*/
Notifier.prototype.warning = function (msg, cb) {
return add({
type: 'warning',
content: formatMsg(msg, this.from),
icon: 'warning',
title: 'Warning',
lifetime: Notifier.config.warningLifetime,
actions: ['accept']
}, cb);
};
/**
* Display a debug message
* @param {String} msg [description]
* @return {[type]} [description]
*/
Notifier.prototype.info = function (msg, cb) {
return add({
type: 'info',
content: formatMsg(msg, this.from),
icon: 'info-circle',
title: 'Debug',
lifetime: Notifier.config.infoLifetime,
actions: ['accept']
}, cb);
};
Notifier.prototype.describeError = formatMsg.describeError;
if (log === _.noop) {
Notifier.prototype.log = _.noop;
} else {
Notifier.prototype.log = function () {
var args = [].slice.apply(arguments);
if (this.from) args.unshift(this.from + ':');
log.apply(null, args);
};
}
// general functionality used by .event() and .lifecycle()
function createGroupLogger(type, opts) {
// Track the groups managed by this logger
var groups = window[type + 'Groups'] = {};
return function logger(name, success) {
var status; // status of the timer
var exec; // function to execute and wrap
var ret; // return value
var complete = function (val) { logger(name, true); return val; };
var failure = function (err) { logger(name, false); throw err; };
if (typeof success === 'function' || success === void 0) {
// start
groups[name] = now();
if (success) {
// success === the function to time
exec = success;
} else {
// function that can report on the success or failure of an op, and pass their value along
ret = complete;
ret.failure = failure;
}
}
else {
groups[name] = now() - (groups[name] || 0);
var time = ' in ' + groups[name].toFixed(2) + 'ms';
// end
if (success) {
status = 'complete' + time;
} else {
groups[name] = false;
status = 'failure' + time;
}
}
if (consoleGroups) {
if (status) {
console.log(status);
console.groupEnd();
} else {
if (opts.open) {
console.group(name);
} else {
console.groupCollapsed(name);
}
}
} else {
log('KBN: ' + name + (status ? ' - ' + status : ''));
}
if (exec) {
try {
ret = exec();
} catch (e) {
return failure(e);
}
if (ret && typeof ret.then === 'function') {
// return a new promise that proxies the value
// and logs about the promise outcome
return ret.then(function (val) {
complete();
return val;
}, function (err) {
failure(err);
throw err;
});
}
// the function executed fine, and didn't return a promise, move along
complete();
}
return ret;
};
}
return Notifier;
});