loading-bar.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /*!
  2. * angular-loading-bar v0.7.1
  3. * https://chieffancypants.github.io/angular-loading-bar
  4. * Copyright (c) 2015 Wes Cruver
  5. * License: MIT
  6. */
  7. /*
  8. * angular-loading-bar
  9. *
  10. * intercepts XHR requests and creates a loading bar.
  11. * Based on the excellent nprogress work by rstacruz (more info in readme)
  12. *
  13. * (c) 2013 Wes Cruver
  14. * License: MIT
  15. */
  16. (function() {
  17. 'use strict';
  18. // Alias the loading bar for various backwards compatibilities since the project has matured:
  19. angular.module('angular-loading-bar', ['cfp.loadingBarInterceptor']);
  20. angular.module('chieffancypants.loadingBar', ['cfp.loadingBarInterceptor']);
  21. /**
  22. * loadingBarInterceptor service
  23. *
  24. * Registers itself as an Angular interceptor and listens for XHR requests.
  25. */
  26. angular.module('cfp.loadingBarInterceptor', ['cfp.loadingBar'])
  27. .config(['$httpProvider', function ($httpProvider) {
  28. var interceptor = ['$q', '$cacheFactory', '$timeout', '$rootScope', '$log', 'cfpLoadingBar', function ($q, $cacheFactory, $timeout, $rootScope, $log, cfpLoadingBar) {
  29. /**
  30. * The total number of requests made
  31. */
  32. var reqsTotal = 0;
  33. /**
  34. * The number of requests completed (either successfully or not)
  35. */
  36. var reqsCompleted = 0;
  37. /**
  38. * The amount of time spent fetching before showing the loading bar
  39. */
  40. var latencyThreshold = cfpLoadingBar.latencyThreshold;
  41. /**
  42. * $timeout handle for latencyThreshold
  43. */
  44. var startTimeout;
  45. /**
  46. * calls cfpLoadingBar.complete() which removes the
  47. * loading bar from the DOM.
  48. */
  49. function setComplete() {
  50. $timeout.cancel(startTimeout);
  51. cfpLoadingBar.complete();
  52. reqsCompleted = 0;
  53. reqsTotal = 0;
  54. }
  55. /**
  56. * Determine if the response has already been cached
  57. * @param {Object} config the config option from the request
  58. * @return {Boolean} retrns true if cached, otherwise false
  59. */
  60. function isCached(config) {
  61. var cache;
  62. var defaultCache = $cacheFactory.get('$http');
  63. var defaults = $httpProvider.defaults;
  64. // Choose the proper cache source. Borrowed from angular: $http service
  65. if ((config.cache || defaults.cache) && config.cache !== false &&
  66. (config.method === 'GET' || config.method === 'JSONP')) {
  67. cache = angular.isObject(config.cache) ? config.cache
  68. : angular.isObject(defaults.cache) ? defaults.cache
  69. : defaultCache;
  70. }
  71. var cached = cache !== undefined ?
  72. cache.get(config.url) !== undefined : false;
  73. if (config.cached !== undefined && cached !== config.cached) {
  74. return config.cached;
  75. }
  76. config.cached = cached;
  77. return cached;
  78. }
  79. return {
  80. 'request': function(config) {
  81. // Check to make sure this request hasn't already been cached and that
  82. // the requester didn't explicitly ask us to ignore this request:
  83. if (!config.ignoreLoadingBar && !isCached(config)) {
  84. $rootScope.$broadcast('cfpLoadingBar:loading', {url: config.url});
  85. if (reqsTotal === 0) {
  86. startTimeout = $timeout(function() {
  87. cfpLoadingBar.start();
  88. }, latencyThreshold);
  89. }
  90. reqsTotal++;
  91. cfpLoadingBar.set(reqsCompleted / reqsTotal);
  92. }
  93. return config;
  94. },
  95. 'response': function(response) {
  96. if (!response || !response.config) {
  97. $log.error('Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50');
  98. return response;
  99. }
  100. if (!response.config.ignoreLoadingBar && !isCached(response.config)) {
  101. reqsCompleted++;
  102. $rootScope.$broadcast('cfpLoadingBar:loaded', {url: response.config.url, result: response});
  103. if (reqsCompleted >= reqsTotal) {
  104. setComplete();
  105. } else {
  106. cfpLoadingBar.set(reqsCompleted / reqsTotal);
  107. }
  108. }
  109. return response;
  110. },
  111. 'responseError': function(rejection) {
  112. if (!rejection || !rejection.config) {
  113. $log.error('Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50');
  114. return $q.reject(rejection);
  115. }
  116. if (!rejection.config.ignoreLoadingBar && !isCached(rejection.config)) {
  117. reqsCompleted++;
  118. $rootScope.$broadcast('cfpLoadingBar:loaded', {url: rejection.config.url, result: rejection});
  119. if (reqsCompleted >= reqsTotal) {
  120. setComplete();
  121. } else {
  122. cfpLoadingBar.set(reqsCompleted / reqsTotal);
  123. }
  124. }
  125. return $q.reject(rejection);
  126. }
  127. };
  128. }];
  129. $httpProvider.interceptors.push(interceptor);
  130. }]);
  131. /**
  132. * Loading Bar
  133. *
  134. * This service handles adding and removing the actual element in the DOM.
  135. * Generally, best practices for DOM manipulation is to take place in a
  136. * directive, but because the element itself is injected in the DOM only upon
  137. * XHR requests, and it's likely needed on every view, the best option is to
  138. * use a service.
  139. */
  140. angular.module('cfp.loadingBar', [])
  141. .provider('cfpLoadingBar', function() {
  142. this.includeSpinner = true;
  143. this.includeBar = true;
  144. this.latencyThreshold = 100;
  145. this.startSize = 0.02;
  146. this.parentSelector = 'body';
  147. this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>';
  148. this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>';
  149. this.$get = ['$injector', '$document', '$timeout', '$rootScope', function ($injector, $document, $timeout, $rootScope) {
  150. var $animate;
  151. var $parentSelector = this.parentSelector,
  152. loadingBarContainer = angular.element(this.loadingBarTemplate),
  153. loadingBar = loadingBarContainer.find('div').eq(0),
  154. spinner = angular.element(this.spinnerTemplate);
  155. var incTimeout,
  156. completeTimeout,
  157. started = false,
  158. status = 0;
  159. var includeSpinner = this.includeSpinner;
  160. var includeBar = this.includeBar;
  161. var startSize = this.startSize;
  162. /**
  163. * Inserts the loading bar element into the dom, and sets it to 2%
  164. */
  165. function _start() {
  166. if (!$animate) {
  167. $animate = $injector.get('$animate');
  168. }
  169. var $parent = $document.find($parentSelector).eq(0);
  170. $timeout.cancel(completeTimeout);
  171. // do not continually broadcast the started event:
  172. if (started) {
  173. return;
  174. }
  175. $rootScope.$broadcast('cfpLoadingBar:started');
  176. started = true;
  177. if (includeBar) {
  178. $animate.enter(loadingBarContainer, $parent, angular.element($parent[0].lastChild));
  179. }
  180. if (includeSpinner) {
  181. $animate.enter(spinner, $parent, angular.element($parent[0].lastChild));
  182. }
  183. _set(startSize);
  184. }
  185. /**
  186. * Set the loading bar's width to a certain percent.
  187. *
  188. * @param n any value between 0 and 1
  189. */
  190. function _set(n) {
  191. if (!started) {
  192. return;
  193. }
  194. var pct = (n * 100) + '%';
  195. loadingBar.css('width', pct);
  196. status = n;
  197. // increment loadingbar to give the illusion that there is always
  198. // progress but make sure to cancel the previous timeouts so we don't
  199. // have multiple incs running at the same time.
  200. $timeout.cancel(incTimeout);
  201. incTimeout = $timeout(function() {
  202. _inc();
  203. }, 250);
  204. }
  205. /**
  206. * Increments the loading bar by a random amount
  207. * but slows down as it progresses
  208. */
  209. function _inc() {
  210. if (_status() >= 1) {
  211. return;
  212. }
  213. var rnd = 0;
  214. // TODO: do this mathmatically instead of through conditions
  215. var stat = _status();
  216. if (stat >= 0 && stat < 0.25) {
  217. // Start out between 3 - 6% increments
  218. rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
  219. } else if (stat >= 0.25 && stat < 0.65) {
  220. // increment between 0 - 3%
  221. rnd = (Math.random() * 3) / 100;
  222. } else if (stat >= 0.65 && stat < 0.9) {
  223. // increment between 0 - 2%
  224. rnd = (Math.random() * 2) / 100;
  225. } else if (stat >= 0.9 && stat < 0.99) {
  226. // finally, increment it .5 %
  227. rnd = 0.005;
  228. } else {
  229. // after 99%, don't increment:
  230. rnd = 0;
  231. }
  232. var pct = _status() + rnd;
  233. _set(pct);
  234. }
  235. function _status() {
  236. return status;
  237. }
  238. function _completeAnimation() {
  239. status = 0;
  240. started = false;
  241. }
  242. function _complete() {
  243. if (!$animate) {
  244. $animate = $injector.get('$animate');
  245. }
  246. $rootScope.$broadcast('cfpLoadingBar:completed');
  247. _set(1);
  248. $timeout.cancel(completeTimeout);
  249. // Attempt to aggregate any start/complete calls within 500ms:
  250. completeTimeout = $timeout(function() {
  251. var promise = $animate.leave(loadingBarContainer, _completeAnimation);
  252. if (promise && promise.then) {
  253. promise.then(_completeAnimation);
  254. }
  255. $animate.leave(spinner);
  256. }, 500);
  257. }
  258. return {
  259. start : _start,
  260. set : _set,
  261. status : _status,
  262. inc : _inc,
  263. complete : _complete,
  264. includeSpinner : this.includeSpinner,
  265. latencyThreshold : this.latencyThreshold,
  266. parentSelector : this.parentSelector,
  267. startSize : this.startSize
  268. };
  269. }]; //
  270. }); // wtf javascript. srsly
  271. })(); //