-
Notifications
You must be signed in to change notification settings - Fork 281
/
toaster.js
516 lines (463 loc) · 26.7 KB
/
toaster.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
/* global angular */
/*
* @license
* AngularJS Toaster
* Version: 3.0.0
*
* Copyright 2013-2019 Jiri Kavulak, Stabzs.
* All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
*
* Authors: Jiri Kavulak, Stabzs
* Related to project of John Papa, Hans Fjällemark and Nguyễn Thiện Hùng (thienhung1989)
*/
(function(window, document) {
'use strict';
angular.module('toaster', []).constant(
'toasterConfig', {
'limit': 0, // limits max number of toasts
'tap-to-dismiss': true,
'close-button': false,
'close-html': '<button class="toast-close-button" type="button">×</button>',
'newest-on-top': true,
'time-out': 5000,
'icon-classes': {
error: 'toast-error',
info: 'toast-info',
wait: 'toast-wait',
success: 'toast-success',
warning: 'toast-warning'
},
'body-output-type': '', // Options: '', 'html', 'trustedHtml', 'template', 'templateWithData', 'directive'
'body-template': 'toasterBodyTmpl.html',
'icon-class': 'toast-info',
'position-class': 'toast-top-right', // Options (see CSS):
// 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center',
// 'toast-top-left', 'toast-top-center', 'toast-top-right',
// 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-right',
'title-class': 'toast-title',
'message-class': 'toast-message',
'prevent-duplicates': false,
'mouseover-timer-stop': true // stop timeout on mouseover and restart timer on mouseout
}
).run(['$templateCache', function($templateCache) {
$templateCache.put('angularjs-toaster/toast.html',
'<div id="toast-container" ng-class="[config.position, config.animation]">' +
'<div ng-repeat="toaster in toasters" class="toast" ng-class="toaster.type" ng-click="click($event, toaster)" ng-mouseover="stopTimer(toaster)" ng-mouseout="restartTimer(toaster)">' +
'<div ng-if="toaster.showCloseButton" ng-click="click($event, toaster, true)" ng-bind-html="toaster.closeHtml"></div>' +
'<div ng-class="config.title">{{toaster.title}}</div>' +
'<div ng-class="config.message" ng-switch on="toaster.bodyOutputType">' +
'<div ng-switch-when="html" ng-bind-html="toaster.body"></div>' +
'<div ng-switch-when="trustedHtml" ng-bind-html="toaster.html"></div>' +
'<div ng-switch-when="template"><div ng-include="toaster.bodyTemplate"></div></div>' +
'<div ng-switch-when="templateWithData"><div ng-include="toaster.bodyTemplate"></div></div>' +
'<div ng-switch-when="directive"><div directive-template directive-name="{{toaster.html}}" directive-data="toaster.directiveData"></div></div>' +
'<div ng-switch-default >{{toaster.body}}</div>' +
'</div>' +
'</div>' +
'</div>');
}
]).service(
'toaster', [
'$rootScope', 'toasterConfig', function($rootScope, toasterConfig) {
// http://stackoverflow.com/questions/26501688/a-typescript-guid-class
var Guid = (function() {
var Guid = {};
Guid.newGuid = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
return Guid;
}());
this.pop = function(type, title, body, timeout, bodyOutputType, clickHandler, toasterId, showCloseButton, toastId, onHideCallback) {
if (angular.isObject(type)) {
var params = type; // Enable named parameters as pop argument
this.toast = {
type: params.type,
title: params.title,
body: params.body,
timeout: params.timeout,
bodyOutputType: params.bodyOutputType,
clickHandler: params.clickHandler,
showCloseButton: params.showCloseButton,
closeHtml: params.closeHtml,
toastId: params.toastId,
onShowCallback: params.onShowCallback,
onHideCallback: params.onHideCallback,
directiveData: params.directiveData,
tapToDismiss: params.tapToDismiss
};
toasterId = params.toasterId;
} else {
this.toast = {
type: type,
title: title,
body: body,
timeout: timeout,
bodyOutputType: bodyOutputType,
clickHandler: clickHandler,
showCloseButton: showCloseButton,
toastId: toastId,
onHideCallback: onHideCallback
};
}
if (!this.toast.toastId || !this.toast.toastId.length) {
this.toast.toastId = Guid.newGuid();
}
$rootScope.$emit('toaster-newToast', toasterId, this.toast.toastId);
return {
toasterId: toasterId,
toastId: this.toast.toastId
};
};
this.clear = function(toasterId, toastId) {
if (angular.isObject(toasterId)) {
$rootScope.$emit('toaster-clearToasts', toasterId.toasterId, toasterId.toastId);
} else {
$rootScope.$emit('toaster-clearToasts', toasterId, toastId);
}
};
// Create one method per icon class, to allow to call toaster.info() and similar
for (var type in toasterConfig['icon-classes']) {
this[type] = createTypeMethod(type);
}
function createTypeMethod(toasterType) {
return function(title, body, timeout, bodyOutputType, clickHandler, toasterId, showCloseButton, toastId, onHideCallback) {
if (angular.isString(title)) {
return this.pop(
toasterType,
title,
body,
timeout,
bodyOutputType,
clickHandler,
toasterId,
showCloseButton,
toastId,
onHideCallback);
} else { // 'title' is actually an object with options
return this.pop(angular.extend(title, { type: toasterType }));
}
};
}
}]
).factory(
'toasterEventRegistry', [
'$rootScope', function($rootScope) {
var deregisterNewToast = null, deregisterClearToasts = null, newToastEventSubscribers = [], clearToastsEventSubscribers = [], toasterFactory;
toasterFactory = {
setup: function() {
if (!deregisterNewToast) {
deregisterNewToast = $rootScope.$on(
'toaster-newToast', function(event, toasterId, toastId) {
for (var i = 0, len = newToastEventSubscribers.length; i < len; i++) {
newToastEventSubscribers[i](event, toasterId, toastId);
}
});
}
if (!deregisterClearToasts) {
deregisterClearToasts = $rootScope.$on(
'toaster-clearToasts', function(event, toasterId, toastId) {
for (var i = 0, len = clearToastsEventSubscribers.length; i < len; i++) {
clearToastsEventSubscribers[i](event, toasterId, toastId);
}
});
}
},
subscribeToNewToastEvent: function(onNewToast) {
newToastEventSubscribers.push(onNewToast);
},
subscribeToClearToastsEvent: function(onClearToasts) {
clearToastsEventSubscribers.push(onClearToasts);
},
unsubscribeToNewToastEvent: function(onNewToast) {
var index = newToastEventSubscribers.indexOf(onNewToast);
if (index >= 0) {
newToastEventSubscribers.splice(index, 1);
}
if (newToastEventSubscribers.length === 0) {
deregisterNewToast();
deregisterNewToast = null;
}
},
unsubscribeToClearToastsEvent: function(onClearToasts) {
var index = clearToastsEventSubscribers.indexOf(onClearToasts);
if (index >= 0) {
clearToastsEventSubscribers.splice(index, 1);
}
if (clearToastsEventSubscribers.length === 0) {
deregisterClearToasts();
deregisterClearToasts = null;
}
}
};
return {
setup: toasterFactory.setup,
subscribeToNewToastEvent: toasterFactory.subscribeToNewToastEvent,
subscribeToClearToastsEvent: toasterFactory.subscribeToClearToastsEvent,
unsubscribeToNewToastEvent: toasterFactory.unsubscribeToNewToastEvent,
unsubscribeToClearToastsEvent: toasterFactory.unsubscribeToClearToastsEvent
};
}]
)
.directive('directiveTemplate', ['$compile', '$injector', function($compile, $injector) {
return {
restrict: 'A',
scope: {
directiveName: '@directiveName',
directiveData: '=directiveData'
},
replace: true,
link: function(scope, elm, attrs) {
scope.$watch('directiveName', function(directiveName) {
if (angular.isUndefined(directiveName) || directiveName.length <= 0)
throw new Error('A valid directive name must be provided via the toast body argument when using bodyOutputType: directive');
var directive;
try {
directive = $injector.get(attrs.$normalize(directiveName) + 'Directive');
} catch (e) {
throw new Error(directiveName + ' could not be found. ' +
'The name should appear as it exists in the markup, not camelCased as it would appear in the directive declaration,' +
' e.g. directive-name not directiveName.');
}
var directiveDetails = directive[0];
if (directiveDetails.scope !== true && directiveDetails.scope) {
throw new Error('Cannot use a directive with an isolated scope. ' +
'The scope must be either true or falsy (e.g. false/null/undefined). ' +
'Occurred for directive ' + directiveName + '.');
}
if (directiveDetails.restrict.indexOf('A') < 0) {
throw new Error('Directives must be usable as attributes. ' +
'Add "A" to the restrict option (or remove the option entirely). Occurred for directive ' +
directiveName + '.');
}
if (scope.directiveData)
scope.directiveData = angular.fromJson(scope.directiveData);
var template = $compile('<div ' + directiveName + '></div>')(scope);
elm.append(template);
});
}
};
}])
.directive(
'toasterContainer', [
'$parse', '$rootScope', '$interval', '$sce', 'toasterConfig', 'toaster', 'toasterEventRegistry',
function($parse, $rootScope, $interval, $sce, toasterConfig, toaster, toasterEventRegistry) {
return {
replace: true,
restrict: 'EA',
scope: true, // creates an internal scope for this directive (one per directive instance)
link: function(scope, elm, attrs) {
var mergedConfig;
// Merges configuration set in directive with default one
mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions));
scope.config = {
toasterId: mergedConfig['toaster-id'],
position: mergedConfig['position-class'],
title: mergedConfig['title-class'],
message: mergedConfig['message-class'],
tap: mergedConfig['tap-to-dismiss'],
closeButton: mergedConfig['close-button'],
closeHtml: mergedConfig['close-html'],
animation: mergedConfig['animation-class'],
mouseoverTimer: mergedConfig['mouseover-timer-stop']
};
scope.$on(
"$destroy", function() {
toasterEventRegistry.unsubscribeToNewToastEvent(scope._onNewToast);
toasterEventRegistry.unsubscribeToClearToastsEvent(scope._onClearToasts);
}
);
function setTimeout(toast, time) {
toast.timeoutPromise = $interval(
function() {
scope.removeToast(toast.toastId);
}, time, 1
);
}
scope.configureTimer = function(toast) {
var timeout = angular.isNumber(toast.timeout) ? toast.timeout : mergedConfig['time-out'];
if (typeof timeout === "object") timeout = timeout[toast.type];
if (timeout > 0) {
setTimeout(toast, timeout);
}
};
function addToast(toast, toastId) {
toast.type = mergedConfig['icon-classes'][toast.type];
if (!toast.type) {
toast.type = mergedConfig['icon-class'];
}
if (mergedConfig['prevent-duplicates'] === true && scope.toasters.length) {
if (scope.toasters[scope.toasters.length - 1].body === toast.body) {
return;
} else {
var i, len, dupFound = false;
for (i = 0, len = scope.toasters.length; i < len; i++) {
if (scope.toasters[i].toastId === toastId) {
dupFound = true;
break;
}
}
if (dupFound) return;
}
}
// set the showCloseButton property on the toast so that
// each template can bind directly to the property to show/hide
// the close button
var closeButton = mergedConfig['close-button'];
// if toast.showCloseButton is a boolean value,
// it was specifically overriden in the pop arguments
if (typeof toast.showCloseButton === "boolean") {
} else if (typeof closeButton === "boolean") {
toast.showCloseButton = closeButton;
} else if (typeof closeButton === "object") {
var closeButtonForType = closeButton[toast.type];
if (typeof closeButtonForType !== "undefined" && closeButtonForType !== null) {
toast.showCloseButton = closeButtonForType;
}
} else {
// if an option was not set, default to false.
toast.showCloseButton = false;
}
if (toast.showCloseButton) {
toast.closeHtml = $sce.trustAsHtml(toast.closeHtml || scope.config.closeHtml);
}
// Set the toast.bodyOutputType to the default if it isn't set
toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type'];
switch (toast.bodyOutputType) {
case 'trustedHtml':
toast.html = $sce.trustAsHtml(toast.body);
break;
case 'template':
toast.bodyTemplate = toast.body || mergedConfig['body-template'];
break;
case 'templateWithData':
var fcGet = $parse(toast.body || mergedConfig['body-template']);
var templateWithData = fcGet(scope);
toast.bodyTemplate = templateWithData.template;
toast.data = templateWithData.data;
break;
case 'directive':
toast.html = toast.body;
break;
}
scope.configureTimer(toast);
if (mergedConfig['newest-on-top'] === true) {
scope.toasters.unshift(toast);
if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
removeToast(scope.toasters.length - 1);
}
} else {
scope.toasters.push(toast);
if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
removeToast(0);
}
}
if (angular.isFunction(toast.onShowCallback)) {
toast.onShowCallback(toast);
}
}
scope.removeToast = function(toastId) {
var i, len;
for (i = 0, len = scope.toasters.length; i < len; i++) {
if (scope.toasters[i].toastId === toastId) {
removeToast(i);
break;
}
}
};
function removeToast(toastIndex) {
var toast = scope.toasters[toastIndex];
// toast is always defined since the index always has a match
if (toast.timeoutPromise) {
$interval.cancel(toast.timeoutPromise);
}
scope.toasters.splice(toastIndex, 1);
if (angular.isFunction(toast.onHideCallback)) {
toast.onHideCallback(toast);
}
}
function removeAllToasts(toastId) {
for (var i = scope.toasters.length - 1; i >= 0; i--) {
if (isUndefinedOrNull(toastId)) {
removeToast(i);
} else {
if (scope.toasters[i].toastId == toastId) {
removeToast(i);
}
}
}
}
scope.toasters = [];
function isUndefinedOrNull(val) {
return angular.isUndefined(val) || val === null;
}
scope._onNewToast = function(event, toasterId, toastId) {
// Compatibility: if toaster has no toasterId defined, and if call to display
// hasn't either, then the request is for us
if ((isUndefinedOrNull(scope.config.toasterId) && isUndefinedOrNull(toasterId)) || (!isUndefinedOrNull(scope.config.toasterId) && !isUndefinedOrNull(toasterId) && scope.config.toasterId == toasterId)) {
addToast(toaster.toast, toastId);
}
};
scope._onClearToasts = function(event, toasterId, toastId) {
// Compatibility: if toaster has no toasterId defined, and if call to display
// hasn't either, then the request is for us
if (toasterId == '*' || (isUndefinedOrNull(scope.config.toasterId) && isUndefinedOrNull(toasterId)) || (!isUndefinedOrNull(scope.config.toasterId) && !isUndefinedOrNull(toasterId) && scope.config.toasterId == toasterId)) {
removeAllToasts(toastId);
}
};
toasterEventRegistry.setup();
toasterEventRegistry.subscribeToNewToastEvent(scope._onNewToast);
toasterEventRegistry.subscribeToClearToastsEvent(scope._onClearToasts);
},
controller: [
'$scope', '$element', '$attrs', function($scope, $element, $attrs) {
// Called on mouseover
$scope.stopTimer = function(toast) {
if ($scope.config.mouseoverTimer === true) {
if (toast.timeoutPromise) {
$interval.cancel(toast.timeoutPromise);
toast.timeoutPromise = null;
}
}
};
// Called on mouseout
$scope.restartTimer = function(toast) {
if ($scope.config.mouseoverTimer === true) {
if (!toast.timeoutPromise) {
$scope.configureTimer(toast);
}
} else if (toast.timeoutPromise === null) {
$scope.removeToast(toast.toastId);
}
};
$scope.click = function(event, toast, isCloseButton) {
event.stopPropagation();
var tapToDismiss = typeof toast.tapToDismiss === "boolean"
? toast.tapToDismiss
: $scope.config.tap;
if (tapToDismiss === true || (toast.showCloseButton === true && isCloseButton === true)) {
var removeToast = true;
if (toast.clickHandler) {
if (angular.isFunction(toast.clickHandler)) {
removeToast = toast.clickHandler(toast, isCloseButton);
} else if (angular.isFunction($scope.$parent.$eval(toast.clickHandler))) {
removeToast = $scope.$parent.$eval(toast.clickHandler)(toast, isCloseButton);
} else {
console.log("TOAST-NOTE: Your click handler is not inside a parent scope of toaster-container.");
}
}
if (removeToast) {
$scope.removeToast(toast.toastId);
}
}
};
}],
templateUrl: 'angularjs-toaster/toast.html'
};
}]
);
})(window, document);