toaster.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /* global angular */
  2. (function(window, document) {
  3. 'use strict';
  4. /*
  5. * AngularJS Toaster
  6. * Version: 2.1.0
  7. *
  8. * Copyright 2013-2016 Jiri Kavulak.
  9. * All Rights Reserved.
  10. * Use, reproduction, distribution, and modification of this code is subject to the terms and
  11. * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
  12. *
  13. * Author: Jiri Kavulak
  14. * Related to project of John Papa, Hans Fjällemark and Nguyễn Thiện Hùng (thienhung1989)
  15. */
  16. angular.module('toaster', []).constant(
  17. 'toasterConfig', {
  18. 'limit': 0, // limits max number of toasts
  19. 'tap-to-dismiss': true,
  20. 'close-button': false,
  21. 'close-html': '<button class="toast-close-button" type="button">&times;</button>',
  22. 'newest-on-top': true,
  23. 'time-out': 5000,
  24. 'icon-classes': {
  25. error: 'toast-error',
  26. info: 'toast-info',
  27. wait: 'toast-wait',
  28. success: 'toast-success',
  29. warning: 'toast-warning'
  30. },
  31. 'body-output-type': '', // Options: '', 'trustedHtml', 'template', 'templateWithData', 'directive'
  32. 'body-template': 'toasterBodyTmpl.html',
  33. 'icon-class': 'toast-info',
  34. 'position-class': 'toast-top-right', // Options (see CSS):
  35. // 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center',
  36. // 'toast-top-left', 'toast-top-center', 'toast-top-right',
  37. // 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-right',
  38. 'title-class': 'toast-title',
  39. 'message-class': 'toast-message',
  40. 'prevent-duplicates': false,
  41. 'mouseover-timer-stop': true // stop timeout on mouseover and restart timer on mouseout
  42. }
  43. ).run(['$templateCache', function($templateCache) {
  44. $templateCache.put('angularjs-toaster/toast.html',
  45. '<div id="toast-container" ng-class="[config.position, config.animation]">' +
  46. '<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)">' +
  47. '<div ng-if="toaster.showCloseButton" ng-click="click($event, toaster, true)" ng-bind-html="toaster.closeHtml"></div>' +
  48. '<div ng-class="config.title">{{toaster.title}}</div>' +
  49. '<div ng-class="config.message" ng-switch on="toaster.bodyOutputType">' +
  50. '<div ng-switch-when="trustedHtml" ng-bind-html="toaster.html"></div>' +
  51. '<div ng-switch-when="template"><div ng-include="toaster.bodyTemplate"></div></div>' +
  52. '<div ng-switch-when="templateWithData"><div ng-include="toaster.bodyTemplate"></div></div>' +
  53. '<div ng-switch-when="directive"><div directive-template directive-name="{{toaster.html}}" directive-data="{{toaster.directiveData}}"></div></div>' +
  54. '<div ng-switch-default >{{toaster.body}}</div>' +
  55. '</div>' +
  56. '</div>' +
  57. '</div>');
  58. }
  59. ]).service(
  60. 'toaster', [
  61. '$rootScope', 'toasterConfig', function($rootScope, toasterConfig) {
  62. // http://stackoverflow.com/questions/26501688/a-typescript-guid-class
  63. var Guid = (function() {
  64. var Guid = {};
  65. Guid.newGuid = function() {
  66. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  67. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  68. return v.toString(16);
  69. });
  70. };
  71. return Guid;
  72. }());
  73. this.pop = function(type, title, body, timeout, bodyOutputType, clickHandler, toasterId, showCloseButton, toastId, onHideCallback) {
  74. if (angular.isObject(type)) {
  75. var params = type; // Enable named parameters as pop argument
  76. this.toast = {
  77. type: params.type,
  78. title: params.title,
  79. body: params.body,
  80. timeout: params.timeout,
  81. bodyOutputType: params.bodyOutputType,
  82. clickHandler: params.clickHandler,
  83. showCloseButton: params.showCloseButton,
  84. closeHtml: params.closeHtml,
  85. toastId: params.toastId,
  86. onShowCallback: params.onShowCallback,
  87. onHideCallback: params.onHideCallback,
  88. directiveData: params.directiveData,
  89. tapToDismiss: params.tapToDismiss
  90. };
  91. toasterId = params.toasterId;
  92. } else {
  93. this.toast = {
  94. type: type,
  95. title: title,
  96. body: body,
  97. timeout: timeout,
  98. bodyOutputType: bodyOutputType,
  99. clickHandler: clickHandler,
  100. showCloseButton: showCloseButton,
  101. toastId: toastId,
  102. onHideCallback: onHideCallback
  103. };
  104. }
  105. if (!this.toast.toastId || !this.toast.toastId.length) {
  106. this.toast.toastId = Guid.newGuid();
  107. }
  108. $rootScope.$emit('toaster-newToast', toasterId, this.toast.toastId);
  109. return {
  110. toasterId: toasterId,
  111. toastId: this.toast.toastId
  112. };
  113. };
  114. this.clear = function(toasterId, toastId) {
  115. if (angular.isObject(toasterId)) {
  116. $rootScope.$emit('toaster-clearToasts', toasterId.toasterId, toasterId.toastId);
  117. } else {
  118. $rootScope.$emit('toaster-clearToasts', toasterId, toastId);
  119. }
  120. };
  121. // Create one method per icon class, to allow to call toaster.info() and similar
  122. for (var type in toasterConfig['icon-classes']) {
  123. this[type] = createTypeMethod(type);
  124. }
  125. function createTypeMethod(toasterType) {
  126. return function(title, body, timeout, bodyOutputType, clickHandler, toasterId, showCloseButton, toastId, onHideCallback) {
  127. if (angular.isString(title)) {
  128. return this.pop(
  129. toasterType,
  130. title,
  131. body,
  132. timeout,
  133. bodyOutputType,
  134. clickHandler,
  135. toasterId,
  136. showCloseButton,
  137. toastId,
  138. onHideCallback);
  139. } else { // 'title' is actually an object with options
  140. return this.pop(angular.extend(title, { type: toasterType }));
  141. }
  142. };
  143. }
  144. }]
  145. ).factory(
  146. 'toasterEventRegistry', [
  147. '$rootScope', function($rootScope) {
  148. var deregisterNewToast = null, deregisterClearToasts = null, newToastEventSubscribers = [], clearToastsEventSubscribers = [], toasterFactory;
  149. toasterFactory = {
  150. setup: function() {
  151. if (!deregisterNewToast) {
  152. deregisterNewToast = $rootScope.$on(
  153. 'toaster-newToast', function(event, toasterId, toastId) {
  154. for (var i = 0, len = newToastEventSubscribers.length; i < len; i++) {
  155. newToastEventSubscribers[i](event, toasterId, toastId);
  156. }
  157. });
  158. }
  159. if (!deregisterClearToasts) {
  160. deregisterClearToasts = $rootScope.$on(
  161. 'toaster-clearToasts', function(event, toasterId, toastId) {
  162. for (var i = 0, len = clearToastsEventSubscribers.length; i < len; i++) {
  163. clearToastsEventSubscribers[i](event, toasterId, toastId);
  164. }
  165. });
  166. }
  167. },
  168. subscribeToNewToastEvent: function(onNewToast) {
  169. newToastEventSubscribers.push(onNewToast);
  170. },
  171. subscribeToClearToastsEvent: function(onClearToasts) {
  172. clearToastsEventSubscribers.push(onClearToasts);
  173. },
  174. unsubscribeToNewToastEvent: function(onNewToast) {
  175. var index = newToastEventSubscribers.indexOf(onNewToast);
  176. if (index >= 0) {
  177. newToastEventSubscribers.splice(index, 1);
  178. }
  179. if (newToastEventSubscribers.length === 0) {
  180. deregisterNewToast();
  181. deregisterNewToast = null;
  182. }
  183. },
  184. unsubscribeToClearToastsEvent: function(onClearToasts) {
  185. var index = clearToastsEventSubscribers.indexOf(onClearToasts);
  186. if (index >= 0) {
  187. clearToastsEventSubscribers.splice(index, 1);
  188. }
  189. if (clearToastsEventSubscribers.length === 0) {
  190. deregisterClearToasts();
  191. deregisterClearToasts = null;
  192. }
  193. }
  194. };
  195. return {
  196. setup: toasterFactory.setup,
  197. subscribeToNewToastEvent: toasterFactory.subscribeToNewToastEvent,
  198. subscribeToClearToastsEvent: toasterFactory.subscribeToClearToastsEvent,
  199. unsubscribeToNewToastEvent: toasterFactory.unsubscribeToNewToastEvent,
  200. unsubscribeToClearToastsEvent: toasterFactory.unsubscribeToClearToastsEvent
  201. };
  202. }]
  203. )
  204. .directive('directiveTemplate', ['$compile', '$injector', function($compile, $injector) {
  205. return {
  206. restrict: 'A',
  207. scope: {
  208. directiveName: '@directiveName',
  209. directiveData: '@directiveData'
  210. },
  211. replace: true,
  212. link: function(scope, elm, attrs) {
  213. scope.$watch('directiveName', function(directiveName) {
  214. if (angular.isUndefined(directiveName) || directiveName.length <= 0)
  215. throw new Error('A valid directive name must be provided via the toast body argument when using bodyOutputType: directive');
  216. var directive;
  217. try {
  218. directive = $injector.get(attrs.$normalize(directiveName) + 'Directive');
  219. } catch (e) {
  220. throw new Error(directiveName + ' could not be found. ' +
  221. 'The name should appear as it exists in the markup, not camelCased as it would appear in the directive declaration,' +
  222. ' e.g. directive-name not directiveName.');
  223. }
  224. var directiveDetails = directive[0];
  225. if (directiveDetails.scope !== true && directiveDetails.scope) {
  226. throw new Error('Cannot use a directive with an isolated scope. ' +
  227. 'The scope must be either true or falsy (e.g. false/null/undefined). ' +
  228. 'Occurred for directive ' + directiveName + '.');
  229. }
  230. if (directiveDetails.restrict.indexOf('A') < 0) {
  231. throw new Error('Directives must be usable as attributes. ' +
  232. 'Add "A" to the restrict option (or remove the option entirely). Occurred for directive ' +
  233. directiveName + '.');
  234. }
  235. if (scope.directiveData)
  236. scope.directiveData = angular.fromJson(scope.directiveData);
  237. var template = $compile('<div ' + directiveName + '></div>')(scope);
  238. elm.append(template);
  239. });
  240. }
  241. };
  242. }])
  243. .directive(
  244. 'toasterContainer', [
  245. '$parse', '$rootScope', '$interval', '$sce', 'toasterConfig', 'toaster', 'toasterEventRegistry',
  246. function($parse, $rootScope, $interval, $sce, toasterConfig, toaster, toasterEventRegistry) {
  247. return {
  248. replace: true,
  249. restrict: 'EA',
  250. scope: true, // creates an internal scope for this directive (one per directive instance)
  251. link: function(scope, elm, attrs) {
  252. var mergedConfig;
  253. // Merges configuration set in directive with default one
  254. mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions));
  255. scope.config = {
  256. toasterId: mergedConfig['toaster-id'],
  257. position: mergedConfig['position-class'],
  258. title: mergedConfig['title-class'],
  259. message: mergedConfig['message-class'],
  260. tap: mergedConfig['tap-to-dismiss'],
  261. closeButton: mergedConfig['close-button'],
  262. closeHtml: mergedConfig['close-html'],
  263. animation: mergedConfig['animation-class'],
  264. mouseoverTimer: mergedConfig['mouseover-timer-stop']
  265. };
  266. scope.$on(
  267. "$destroy", function() {
  268. toasterEventRegistry.unsubscribeToNewToastEvent(scope._onNewToast);
  269. toasterEventRegistry.unsubscribeToClearToastsEvent(scope._onClearToasts);
  270. }
  271. );
  272. function setTimeout(toast, time) {
  273. toast.timeoutPromise = $interval(
  274. function() {
  275. scope.removeToast(toast.toastId);
  276. }, time, 1
  277. );
  278. }
  279. scope.configureTimer = function(toast) {
  280. var timeout = angular.isNumber(toast.timeout) ? toast.timeout : mergedConfig['time-out'];
  281. if (typeof timeout === "object") timeout = timeout[toast.type];
  282. if (timeout > 0) {
  283. setTimeout(toast, timeout);
  284. }
  285. };
  286. function addToast(toast, toastId) {
  287. toast.type = mergedConfig['icon-classes'][toast.type];
  288. if (!toast.type) {
  289. toast.type = mergedConfig['icon-class'];
  290. }
  291. if (mergedConfig['prevent-duplicates'] === true && scope.toasters.length) {
  292. if (scope.toasters[scope.toasters.length - 1].body === toast.body) {
  293. return;
  294. } else {
  295. var i, len, dupFound = false;
  296. for (i = 0, len = scope.toasters.length; i < len; i++) {
  297. if (scope.toasters[i].toastId === toastId) {
  298. dupFound = true;
  299. break;
  300. }
  301. }
  302. if (dupFound) return;
  303. }
  304. }
  305. // set the showCloseButton property on the toast so that
  306. // each template can bind directly to the property to show/hide
  307. // the close button
  308. var closeButton = mergedConfig['close-button'];
  309. // if toast.showCloseButton is a boolean value,
  310. // it was specifically overriden in the pop arguments
  311. if (typeof toast.showCloseButton === "boolean") {
  312. } else if (typeof closeButton === "boolean") {
  313. toast.showCloseButton = closeButton;
  314. } else if (typeof closeButton === "object") {
  315. var closeButtonForType = closeButton[toast.type];
  316. if (typeof closeButtonForType !== "undefined" && closeButtonForType !== null) {
  317. toast.showCloseButton = closeButtonForType;
  318. }
  319. } else {
  320. // if an option was not set, default to false.
  321. toast.showCloseButton = false;
  322. }
  323. if (toast.showCloseButton) {
  324. toast.closeHtml = $sce.trustAsHtml(toast.closeHtml || scope.config.closeHtml);
  325. }
  326. // Set the toast.bodyOutputType to the default if it isn't set
  327. toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type'];
  328. switch (toast.bodyOutputType) {
  329. case 'trustedHtml':
  330. toast.html = $sce.trustAsHtml(toast.body);
  331. break;
  332. case 'template':
  333. toast.bodyTemplate = toast.body || mergedConfig['body-template'];
  334. break;
  335. case 'templateWithData':
  336. var fcGet = $parse(toast.body || mergedConfig['body-template']);
  337. var templateWithData = fcGet(scope);
  338. toast.bodyTemplate = templateWithData.template;
  339. toast.data = templateWithData.data;
  340. break;
  341. case 'directive':
  342. toast.html = toast.body;
  343. break;
  344. }
  345. scope.configureTimer(toast);
  346. if (mergedConfig['newest-on-top'] === true) {
  347. scope.toasters.unshift(toast);
  348. if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
  349. scope.toasters.pop();
  350. }
  351. } else {
  352. scope.toasters.push(toast);
  353. if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
  354. scope.toasters.shift();
  355. }
  356. }
  357. if (angular.isFunction(toast.onShowCallback)) {
  358. toast.onShowCallback();
  359. }
  360. }
  361. scope.removeToast = function(toastId) {
  362. var i, len;
  363. for (i = 0, len = scope.toasters.length; i < len; i++) {
  364. if (scope.toasters[i].toastId === toastId) {
  365. removeToast(i);
  366. break;
  367. }
  368. }
  369. };
  370. function removeToast(toastIndex) {
  371. var toast = scope.toasters[toastIndex];
  372. // toast is always defined since the index always has a match
  373. if (toast.timeoutPromise) {
  374. $interval.cancel(toast.timeoutPromise);
  375. }
  376. scope.toasters.splice(toastIndex, 1);
  377. if (angular.isFunction(toast.onHideCallback)) {
  378. toast.onHideCallback();
  379. }
  380. }
  381. function removeAllToasts(toastId) {
  382. for (var i = scope.toasters.length - 1; i >= 0; i--) {
  383. if (isUndefinedOrNull(toastId)) {
  384. removeToast(i);
  385. } else {
  386. if (scope.toasters[i].toastId == toastId) {
  387. removeToast(i);
  388. }
  389. }
  390. }
  391. }
  392. scope.toasters = [];
  393. function isUndefinedOrNull(val) {
  394. return angular.isUndefined(val) || val === null;
  395. }
  396. scope._onNewToast = function(event, toasterId, toastId) {
  397. // Compatibility: if toaster has no toasterId defined, and if call to display
  398. // hasn't either, then the request is for us
  399. if ((isUndefinedOrNull(scope.config.toasterId) && isUndefinedOrNull(toasterId)) || (!isUndefinedOrNull(scope.config.toasterId) && !isUndefinedOrNull(toasterId) && scope.config.toasterId == toasterId)) {
  400. addToast(toaster.toast, toastId);
  401. }
  402. };
  403. scope._onClearToasts = function(event, toasterId, toastId) {
  404. // Compatibility: if toaster has no toasterId defined, and if call to display
  405. // hasn't either, then the request is for us
  406. if (toasterId == '*' || (isUndefinedOrNull(scope.config.toasterId) && isUndefinedOrNull(toasterId)) || (!isUndefinedOrNull(scope.config.toasterId) && !isUndefinedOrNull(toasterId) && scope.config.toasterId == toasterId)) {
  407. removeAllToasts(toastId);
  408. }
  409. };
  410. toasterEventRegistry.setup();
  411. toasterEventRegistry.subscribeToNewToastEvent(scope._onNewToast);
  412. toasterEventRegistry.subscribeToClearToastsEvent(scope._onClearToasts);
  413. },
  414. controller: [
  415. '$scope', '$element', '$attrs', function($scope, $element, $attrs) {
  416. // Called on mouseover
  417. $scope.stopTimer = function(toast) {
  418. if ($scope.config.mouseoverTimer === true) {
  419. if (toast.timeoutPromise) {
  420. $interval.cancel(toast.timeoutPromise);
  421. toast.timeoutPromise = null;
  422. }
  423. }
  424. };
  425. // Called on mouseout
  426. $scope.restartTimer = function(toast) {
  427. if ($scope.config.mouseoverTimer === true) {
  428. if (!toast.timeoutPromise) {
  429. $scope.configureTimer(toast);
  430. }
  431. } else if (toast.timeoutPromise === null) {
  432. $scope.removeToast(toast.toastId);
  433. }
  434. };
  435. $scope.click = function(event, toast, isCloseButton) {
  436. event.stopPropagation();
  437. var tapToDismiss = typeof toast.tapToDismiss === "boolean"
  438. ? toast.tapToDismiss
  439. : $scope.config.tap;
  440. if (tapToDismiss === true || (toast.showCloseButton === true && isCloseButton === true)) {
  441. var removeToast = true;
  442. if (toast.clickHandler) {
  443. if (angular.isFunction(toast.clickHandler)) {
  444. removeToast = toast.clickHandler(toast, isCloseButton);
  445. } else if (angular.isFunction($scope.$parent.$eval(toast.clickHandler))) {
  446. removeToast = $scope.$parent.$eval(toast.clickHandler)(toast, isCloseButton);
  447. } else {
  448. console.log("TOAST-NOTE: Your click handler is not inside a parent scope of toaster-container.");
  449. }
  450. }
  451. if (removeToast) {
  452. $scope.removeToast(toast.toastId);
  453. }
  454. }
  455. };
  456. }],
  457. templateUrl: 'angularjs-toaster/toast.html'
  458. };
  459. }]
  460. );
  461. })(window, document);