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
722 lines (622 loc) · 18.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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
import _ from 'lodash';
import angular from 'angular';
import $ from 'jquery';
import { metadata } from 'ui/metadata';
import { formatMsg } from 'ui/notify/lib/_format_msg';
import fatalSplashScreen from 'ui/notify/partials/fatal_splash_screen.html';
import 'ui/render_directive';
import chrome from 'ui/chrome';
/* eslint no-console: 0 */
const notifs = [];
// kibi: use kibi version
const version = metadata.kibiVersion;
const buildNum = metadata.buildNum;
// siren: put log only in debug level
const consoleGroups = false;
const log = _.bindKey(console, 'debug');
// siren: end
// used to identify the first call to fatal, set to false there
let firstFatal = true;
const fatalToastTemplate = (function lazyTemplate(tmpl) {
let 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
const 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) {
const interval = 1000;
if (notif.lifetime === Infinity || notif.lifetime === 0) {
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);
}
// kibi: button classes is changed
const typeToButtonClassMap = {
danger: 'btn-danger', // NOTE: `error` type is internally named as `danger`
warning: 'btn-warning',
info: 'btn-info',
banner: 'btn-banner'
};
// kibi: end
const buttonHierarchyClass = (index) => {
if (index === 0) {
// first action: primary className
return 'kuiButton--primary';
}
// subsequent actions: secondary/default className
return 'kuiButton--basic';
};
const typeToAlertClassMap = {
danger: `alert-danger`,
warning: `alert-warning`,
info: `alert-info`,
banner: `alert-banner`,
};
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);
});
} else if (notif.customActions) {
// wrap all of the custom functions in a close
notif.customActions = notif.customActions.map((action, index) => {
return {
key: action.text,
dataTestSubj: action.dataTestSubj,
callback: closeNotif(notif, action.callback, action.text),
getButtonClass() {
const buttonTypeClass = typeToButtonClassMap[notif.type];
return `${buttonHierarchyClass(index)} ${buttonTypeClass}`;
}
};
});
}
notif.count = (notif.count || 0) + 1;
notif.isTimed = function isTimed() {
return notif.timerId ? true : false;
};
// decorate the notification with helper functions for the template
notif.getButtonClass = () => typeToButtonClassMap[notif.type];
notif.getAlertClassStack = () => `toast-stack alert ${typeToAlertClassMap[notif.type]}`;
notif.getIconClass = () => (notif.type === 'banner') ? '' : `fa fa-${notif.icon}`;
notif.getToastMessageClass = () => (notif.type === 'banner') ? 'toast-message-banner' : 'toast-message';
notif.getAlertClass = () => (notif.type === 'banner') ?
`alert ${typeToAlertClassMap[notif.type]}` : // not including `.toast` class leaves out the flex properties for banner
`toast alert ${typeToAlertClassMap[notif.type]}`;
notif.getButtonGroupClass = () => (notif.type === 'banner') ?
'toast-controls-banner' :
'toast-controls';
let dup = null;
if (notif.content) {
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 set(opts, cb) {
if (!opts.content) {
return null;
}
if (this._sovereignNotif) {
this._sovereignNotif.clear();
}
this._sovereignNotif = add(opts, cb);
return this._sovereignNotif;
}
Notifier.prototype.add = add;
Notifier.prototype.set = set;
function formatInfo() {
const 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) {
let 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;
} else if (err.data) {
stackMsg = JSON.stringify(err.data);
}
// kibi: end
return stackMsg;
}
/**
* Functionality to check that
*/
export function Notifier(opts) {
const 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);
});
}
Notifier.config = {
shieldAuthorizationWarning: true, // kibi: show/hide shield warnings
bannerLifetime: 3000000,
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 = [];
// "Constants"
Notifier.QS_PARAM_MESSAGE = 'notif_msg';
Notifier.QS_PARAM_LEVEL = 'notif_lvl';
Notifier.QS_PARAM_LOCATION = 'notif_loc';
Notifier.pullMessageFromUrl = ($location) => {
const queryString = $location.search();
if (!queryString.notif_msg) {
return;
}
const message = queryString[Notifier.QS_PARAM_MESSAGE];
const config = queryString[Notifier.QS_PARAM_LOCATION] ? { location: queryString[Notifier.QS_PARAM_LOCATION] } : {};
const level = queryString[Notifier.QS_PARAM_LEVEL] || 'info';
$location.search(Notifier.QS_PARAM_MESSAGE, null);
$location.search(Notifier.QS_PARAM_LOCATION, null);
$location.search(Notifier.QS_PARAM_LEVEL, null);
const notifier = new Notifier(config);
notifier[level](message);
};
// 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
});
/**
* 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
});
/**
* 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) {
const self = this;
if (typeof name === 'function') {
fn = name;
name = fn.name;
}
return function WrappedNotifierFunction() {
const cntx = this;
const 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();
});
}
const html = fatalToastTemplate({
info: formatInfo(),
msg: formatMsg(err, this.from),
stack: formatStack(err)
});
let $container = $('#fatal-splash-screen');
if (!$container.length) {
$(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);
};
// kibi: added "stack" to allow the stack to be set
const overrideableOptions = ['stack', 'lifetime', 'icon'];
/**
* Alert the user of an error that occured
* @param {Error|String} err
* @param {Function} cb
*/
Notifier.prototype.error = function (err, opts, cb) {
if (_.isFunction(opts)) {
cb = opts;
opts = {};
}
// we have to use a replacer to properly stringify javascript error object
// without it it would just give you an empty object
function replaceErrors(key, value) {
if (value instanceof Error) {
const error = {};
Object.getOwnPropertyNames(value).forEach(function (key) {
error[key] = value[key];
});
return error;
}
// kibi: if value is greater than 1KB ellipse it
if (value && value.length > 1000) {
value = value.substring(0, 997) + '...';
}
return value;
}
const jsonErr = JSON.stringify(err, replaceErrors);
// kibi: This is added to redirect to the root when one or more XHR calls
// fail because the cookie is invalid or expired; an auth plugin
// will then redirect to the login page.
if (jsonErr && jsonErr.match(/Invalid cookie/)) {
window.location.href = chrome.getBasePath();
}
if (jsonErr && jsonErr.match(/.*(unauthorized|security_exception|no permissions|ElasticsearchSecurityException|Forbidden).*/i)) {
if (Notifier.config.shieldAuthorizationWarning !== false) {
return this.warning(err, opts, cb);
} else {
console.warn('Shield Authorization Warning: ' + formatMsg(err, this.from));
}
} else {
const config = _.assign({
type: 'danger',
content: formatMsg(err, this.from),
icon: 'warning',
title: 'Error',
lifetime: Notifier.config.errorLifetime,
actions: ['report', 'accept'],
stack: formatStack(err)
}, _.pick(opts, overrideableOptions));
return add(config, cb);
}
};
/**
* Warn the user abort something
* @param {String} msg
* @param {Function} cb
*/
Notifier.prototype.warning = function (msg, opts, cb) {
if (_.isFunction(opts)) {
cb = opts;
opts = {};
}
const config = _.assign({
type: 'warning',
content: formatMsg(msg, this.from),
icon: 'warning',
title: 'Warning',
lifetime: Notifier.config.warningLifetime,
actions: ['accept']
}, _.pick(opts, overrideableOptions));
return add(config, cb);
};
/**
* Display a debug message
* @param {String} msg
* @param {Function} cb
*/
Notifier.prototype.info = function (msg, opts, cb) {
if (_.isFunction(opts)) {
cb = opts;
opts = {};
}
const config = _.assign({
type: 'info',
content: formatMsg(msg, this.from),
icon: 'info-circle',
title: 'Debug',
lifetime: Notifier.config.infoLifetime,
actions: ['accept']
}, _.pick(opts, overrideableOptions));
return add(config, cb);
};
/**
* Display a banner message
* @param {String} msg
* @param {Function} cb
*/
Notifier.prototype.banner = function (msg, cb) {
return this.set({
type: 'banner',
title: 'Attention',
content: formatMsg(msg, this.from),
lifetime: Notifier.config.bannerLifetime,
actions: ['accept']
}, cb);
};
/**
* Helper for common behavior in custom and directive types
*/
function getDecoratedCustomConfig(config) {
// There is no helper condition that will allow for 2 parameters, as the
// other methods have. So check that config is an object
if (!_.isPlainObject(config)) {
throw new Error('Config param is required, and must be an object');
}
// workaround to allow callers to send `config.type` as `error` instead of
// reveal internal implementation that error notifications use a `danger`
// style
if (config.type === 'error') {
config.type = 'danger';
}
const getLifetime = (type) => {
switch (type) {
case 'banner':
return Notifier.config.bannerLifetime;
case 'warning':
return Notifier.config.warningLifetime;
case 'danger':
return Notifier.config.errorLifetime;
default: // info
return Notifier.config.infoLifetime;
}
};
const customConfig = _.assign({
type: 'info',
title: 'Notification',
lifetime: getLifetime(config.type)
}, config);
const hasActions = _.get(customConfig, 'actions.length');
if (hasActions) {
customConfig.customActions = customConfig.actions;
delete customConfig.actions;
} else {
customConfig.actions = ['accept'];
}
return customConfig;
}
/**
* Display a custom message
* @param {String} msg - required
* @param {Object} config - required
* @param {Function} cb - optional
*
* config = {
* title: 'Some Title here',
* type: 'info',
* actions: [{
* text: 'next',
* callback: function() { next(); }
* }, {
* text: 'prev',
* callback: function() { prev(); }
* }]
* }
*/
Notifier.prototype.custom = function (msg, config, cb) {
const customConfig = getDecoratedCustomConfig(config);
customConfig.content = formatMsg(msg, this.from);
return add(customConfig, cb);
};
/**
* Display a scope-bound directive using template rendering in the message area
* @param {Object} directive - required
* @param {Object} config - required
* @param {Function} cb - optional
*
* directive = {
* template: `<p>Hello World! <a ng-click="example.clickHandler()">Click me</a>.`,
* controllerAs: 'example',
* controller() {
* this.clickHandler = () {
* // do something
* };
* }
* }
*
* config = {
* title: 'Some Title here',
* type: 'info',
* actions: [{
* text: 'next',
* callback: function() { next(); }
* }, {
* text: 'prev',
* callback: function() { prev(); }
* }]
* }
*/
Notifier.prototype.directive = function (directive, config, cb) {
if (!_.isPlainObject(directive)) {
throw new Error('Directive param is required, and must be an object');
}
if (!Notifier.$compile) {
throw new Error('Unable to use the directive notification until Angular has initialized.');
}
if (directive.scope) {
throw new Error('Directive should not have a scope definition. Notifier has an internal implementation.');
}
if (directive.link) {
throw new Error('Directive should not have a link function. Notifier has an internal link function helper.');
}
// make a local copy of the directive param (helps unit tests)
const localDirective = _.clone(directive, true);
localDirective.scope = { notif: '=' };
localDirective.link = function link($scope, $el) {
const $template = angular.element($scope.notif.directive.template);
const postLinkFunction = Notifier.$compile($template);
$el.html($template);
postLinkFunction($scope);
};
const customConfig = getDecoratedCustomConfig(config);
customConfig.directive = localDirective;
return add(customConfig, cb);
};
Notifier.prototype.describeError = formatMsg.describeError;
if (log === _.noop) {
Notifier.prototype.log = _.noop;
} else {
Notifier.prototype.log = function () {
const 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
const groups = window[type + 'Groups'] = {};
return function logger(name, success) {
let status; // status of the timer
let exec; // function to execute and wrap
let ret; // return value
const complete = function (val) { logger(name, true); return val; };
const 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);
const 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;
};
}