toaster.js 26 KB

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