loading-bar.js 9.7 KB

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