progress.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. /*!
  2. * # Fomantic-UI - Progress
  3. * http://github.com/fomantic/Fomantic-UI/
  4. *
  5. *
  6. * Released under the MIT license
  7. * http://opensource.org/licenses/MIT
  8. *
  9. */
  10. ;(function ($, window, document, undefined) {
  11. 'use strict';
  12. $.isFunction = $.isFunction || function(obj) {
  13. return typeof obj === "function" && typeof obj.nodeType !== "number";
  14. };
  15. window = (typeof window != 'undefined' && window.Math == Math)
  16. ? window
  17. : (typeof self != 'undefined' && self.Math == Math)
  18. ? self
  19. : Function('return this')()
  20. ;
  21. $.fn.progress = function(parameters) {
  22. var
  23. $allModules = $(this),
  24. moduleSelector = $allModules.selector || '',
  25. time = new Date().getTime(),
  26. performance = [],
  27. query = arguments[0],
  28. methodInvoked = (typeof query == 'string'),
  29. queryArguments = [].slice.call(arguments, 1),
  30. returnedValue
  31. ;
  32. $allModules
  33. .each(function() {
  34. var
  35. settings = ( $.isPlainObject(parameters) )
  36. ? $.extend(true, {}, $.fn.progress.settings, parameters)
  37. : $.extend({}, $.fn.progress.settings),
  38. className = settings.className,
  39. metadata = settings.metadata,
  40. namespace = settings.namespace,
  41. selector = settings.selector,
  42. error = settings.error,
  43. eventNamespace = '.' + namespace,
  44. moduleNamespace = 'module-' + namespace,
  45. $module = $(this),
  46. $bars = $(this).find(selector.bar),
  47. $progresses = $(this).find(selector.progress),
  48. $label = $(this).find(selector.label),
  49. element = this,
  50. instance = $module.data(moduleNamespace),
  51. animating = false,
  52. transitionEnd,
  53. module
  54. ;
  55. module = {
  56. helper: {
  57. sum: function (nums) {
  58. return Array.isArray(nums) ? nums.reduce(function (left, right) {
  59. return left + Number(right);
  60. }, 0) : 0;
  61. },
  62. /**
  63. * Derive precision for multiple progress with total and values.
  64. *
  65. * This helper dervices a precision that is sufficiently large to show minimum value of multiple progress.
  66. *
  67. * Example1
  68. * - total: 1122
  69. * - values: [325, 111, 74, 612]
  70. * - min ratio: 74/1122 = 0.0659...
  71. * - required precision: 100
  72. *
  73. * Example2
  74. * - total: 10541
  75. * - values: [3235, 1111, 74, 6121]
  76. * - min ratio: 74/10541 = 0.0070...
  77. * - required precision: 1000
  78. *
  79. * @param min A minimum value within multiple values
  80. * @param total A total amount of multiple values
  81. * @returns {number} A precison. Could be 1, 10, 100, ... 1e+10.
  82. */
  83. derivePrecision: function(min, total) {
  84. var precisionPower = 0
  85. var precision = 1;
  86. var ratio = min / total;
  87. while (precisionPower < 10) {
  88. ratio = ratio * precision;
  89. if (ratio > 1) {
  90. break;
  91. }
  92. precision = Math.pow(10, precisionPower++);
  93. }
  94. return precision;
  95. },
  96. forceArray: function (element) {
  97. return Array.isArray(element)
  98. ? element
  99. : !isNaN(element)
  100. ? [element]
  101. : typeof element == 'string'
  102. ? element.split(',')
  103. : []
  104. ;
  105. }
  106. },
  107. initialize: function() {
  108. module.set.duration();
  109. module.set.transitionEvent();
  110. module.debug(element);
  111. module.read.metadata();
  112. module.read.settings();
  113. module.instantiate();
  114. },
  115. instantiate: function() {
  116. module.verbose('Storing instance of progress', module);
  117. instance = module;
  118. $module
  119. .data(moduleNamespace, module)
  120. ;
  121. },
  122. destroy: function() {
  123. module.verbose('Destroying previous progress for', $module);
  124. clearInterval(instance.interval);
  125. module.remove.state();
  126. $module.removeData(moduleNamespace);
  127. instance = undefined;
  128. },
  129. reset: function() {
  130. module.remove.nextValue();
  131. module.update.progress(0);
  132. },
  133. complete: function(keepState) {
  134. if(module.percent === undefined || module.percent < 100) {
  135. module.remove.progressPoll();
  136. if(keepState !== true){
  137. module.set.percent(100);
  138. }
  139. }
  140. },
  141. read: {
  142. metadata: function() {
  143. var
  144. data = {
  145. percent : module.helper.forceArray($module.data(metadata.percent)),
  146. total : $module.data(metadata.total),
  147. value : module.helper.forceArray($module.data(metadata.value))
  148. }
  149. ;
  150. if(data.total) {
  151. module.debug('Total value set from metadata', data.total);
  152. module.set.total(data.total);
  153. }
  154. if(data.value.length > 0) {
  155. module.debug('Current value set from metadata', data.value);
  156. module.set.value(data.value);
  157. module.set.progress(data.value);
  158. }
  159. if(data.percent.length > 0) {
  160. module.debug('Current percent value set from metadata', data.percent);
  161. module.set.percent(data.percent);
  162. }
  163. },
  164. settings: function() {
  165. if(settings.total !== false) {
  166. module.debug('Current total set in settings', settings.total);
  167. module.set.total(settings.total);
  168. }
  169. if(settings.value !== false) {
  170. module.debug('Current value set in settings', settings.value);
  171. module.set.value(settings.value);
  172. module.set.progress(module.value);
  173. }
  174. if(settings.percent !== false) {
  175. module.debug('Current percent set in settings', settings.percent);
  176. module.set.percent(settings.percent);
  177. }
  178. }
  179. },
  180. bind: {
  181. transitionEnd: function(callback) {
  182. var
  183. transitionEnd = module.get.transitionEnd()
  184. ;
  185. $bars
  186. .one(transitionEnd + eventNamespace, function(event) {
  187. clearTimeout(module.failSafeTimer);
  188. callback.call(this, event);
  189. })
  190. ;
  191. module.failSafeTimer = setTimeout(function() {
  192. $bars.triggerHandler(transitionEnd);
  193. }, settings.duration + settings.failSafeDelay);
  194. module.verbose('Adding fail safe timer', module.timer);
  195. }
  196. },
  197. increment: function(incrementValue) {
  198. var
  199. startValue,
  200. newValue
  201. ;
  202. if( module.has.total() ) {
  203. startValue = module.get.value();
  204. incrementValue = incrementValue || 1;
  205. }
  206. else {
  207. startValue = module.get.percent();
  208. incrementValue = incrementValue || module.get.randomValue();
  209. }
  210. newValue = startValue + incrementValue;
  211. module.debug('Incrementing percentage by', startValue, newValue, incrementValue);
  212. newValue = module.get.normalizedValue(newValue);
  213. module.set.progress(newValue);
  214. },
  215. decrement: function(decrementValue) {
  216. var
  217. total = module.get.total(),
  218. startValue,
  219. newValue
  220. ;
  221. if(total) {
  222. startValue = module.get.value();
  223. decrementValue = decrementValue || 1;
  224. newValue = startValue - decrementValue;
  225. module.debug('Decrementing value by', decrementValue, startValue);
  226. }
  227. else {
  228. startValue = module.get.percent();
  229. decrementValue = decrementValue || module.get.randomValue();
  230. newValue = startValue - decrementValue;
  231. module.debug('Decrementing percentage by', decrementValue, startValue);
  232. }
  233. newValue = module.get.normalizedValue(newValue);
  234. module.set.progress(newValue);
  235. },
  236. has: {
  237. progressPoll: function() {
  238. return module.progressPoll;
  239. },
  240. total: function() {
  241. return (module.get.total() !== false);
  242. }
  243. },
  244. get: {
  245. text: function(templateText, index) {
  246. var
  247. index_ = index || 0,
  248. value = module.get.value(index_),
  249. total = module.total || 0,
  250. percent = (animating)
  251. ? module.get.displayPercent(index_)
  252. : module.get.percent(index_),
  253. left = (module.total > 0)
  254. ? (total - value)
  255. : (100 - percent)
  256. ;
  257. templateText = templateText || '';
  258. templateText = templateText
  259. .replace('{value}', value)
  260. .replace('{total}', total)
  261. .replace('{left}', left)
  262. .replace('{percent}', percent)
  263. .replace('{bar}', settings.text.bars[index_] || '')
  264. ;
  265. module.verbose('Adding variables to progress bar text', templateText);
  266. return templateText;
  267. },
  268. normalizedValue: function(value) {
  269. if(value < 0) {
  270. module.debug('Value cannot decrement below 0');
  271. return 0;
  272. }
  273. if(module.has.total()) {
  274. if(value > module.total) {
  275. module.debug('Value cannot increment above total', module.total);
  276. return module.total;
  277. }
  278. }
  279. else if(value > 100 ) {
  280. module.debug('Value cannot increment above 100 percent');
  281. return 100;
  282. }
  283. return value;
  284. },
  285. updateInterval: function() {
  286. if(settings.updateInterval == 'auto') {
  287. return settings.duration;
  288. }
  289. return settings.updateInterval;
  290. },
  291. randomValue: function() {
  292. module.debug('Generating random increment percentage');
  293. return Math.floor((Math.random() * settings.random.max) + settings.random.min);
  294. },
  295. numericValue: function(value) {
  296. return (typeof value === 'string')
  297. ? (value.replace(/[^\d.]/g, '') !== '')
  298. ? +(value.replace(/[^\d.]/g, ''))
  299. : false
  300. : value
  301. ;
  302. },
  303. transitionEnd: function() {
  304. var
  305. element = document.createElement('element'),
  306. transitions = {
  307. 'transition' :'transitionend',
  308. 'OTransition' :'oTransitionEnd',
  309. 'MozTransition' :'transitionend',
  310. 'WebkitTransition' :'webkitTransitionEnd'
  311. },
  312. transition
  313. ;
  314. for(transition in transitions){
  315. if( element.style[transition] !== undefined ){
  316. return transitions[transition];
  317. }
  318. }
  319. },
  320. // gets current displayed percentage (if animating values this is the intermediary value)
  321. displayPercent: function(index) {
  322. var
  323. $bar = $($bars[index]),
  324. barWidth = $bar.width(),
  325. totalWidth = $module.width(),
  326. minDisplay = parseInt($bar.css('min-width'), 10),
  327. displayPercent = (barWidth > minDisplay)
  328. ? (barWidth / totalWidth * 100)
  329. : module.percent
  330. ;
  331. return (settings.precision > 0)
  332. ? Math.round(displayPercent * (10 * settings.precision)) / (10 * settings.precision)
  333. : Math.round(displayPercent)
  334. ;
  335. },
  336. percent: function(index) {
  337. return module.percent && module.percent[index || 0] || 0;
  338. },
  339. value: function(index) {
  340. return module.nextValue || module.value && module.value[index || 0] || 0;
  341. },
  342. total: function() {
  343. return module.total || false;
  344. }
  345. },
  346. create: {
  347. progressPoll: function() {
  348. module.progressPoll = setTimeout(function() {
  349. module.update.toNextValue();
  350. module.remove.progressPoll();
  351. }, module.get.updateInterval());
  352. },
  353. },
  354. is: {
  355. complete: function() {
  356. return module.is.success() || module.is.warning() || module.is.error();
  357. },
  358. success: function() {
  359. return $module.hasClass(className.success);
  360. },
  361. warning: function() {
  362. return $module.hasClass(className.warning);
  363. },
  364. error: function() {
  365. return $module.hasClass(className.error);
  366. },
  367. active: function() {
  368. return $module.hasClass(className.active);
  369. },
  370. visible: function() {
  371. return $module.is(':visible');
  372. }
  373. },
  374. remove: {
  375. progressPoll: function() {
  376. module.verbose('Removing progress poll timer');
  377. if(module.progressPoll) {
  378. clearTimeout(module.progressPoll);
  379. delete module.progressPoll;
  380. }
  381. },
  382. nextValue: function() {
  383. module.verbose('Removing progress value stored for next update');
  384. delete module.nextValue;
  385. },
  386. state: function() {
  387. module.verbose('Removing stored state');
  388. delete module.total;
  389. delete module.percent;
  390. delete module.value;
  391. },
  392. active: function() {
  393. module.verbose('Removing active state');
  394. $module.removeClass(className.active);
  395. },
  396. success: function() {
  397. module.verbose('Removing success state');
  398. $module.removeClass(className.success);
  399. },
  400. warning: function() {
  401. module.verbose('Removing warning state');
  402. $module.removeClass(className.warning);
  403. },
  404. error: function() {
  405. module.verbose('Removing error state');
  406. $module.removeClass(className.error);
  407. }
  408. },
  409. set: {
  410. barWidth: function(values) {
  411. module.debug("set bar width with ", values);
  412. values = module.helper.forceArray(values);
  413. var firstNonZeroIndex = -1;
  414. var lastNonZeroIndex = -1;
  415. var valuesSum = module.helper.sum(values);
  416. var barCounts = $bars.length;
  417. var isMultiple = barCounts > 1;
  418. var percents = values.map(function(value, index) {
  419. var allZero = (index === barCounts - 1 && valuesSum === 0);
  420. var $bar = $($bars[index]);
  421. if (value === 0 && isMultiple && !allZero) {
  422. $bar.css('display', 'none');
  423. } else {
  424. if (isMultiple && allZero) {
  425. $bar.css('background', 'transparent');
  426. }
  427. if (firstNonZeroIndex == -1) {
  428. firstNonZeroIndex = index;
  429. }
  430. lastNonZeroIndex = index;
  431. $bar.css({
  432. display: 'block',
  433. width: value + '%'
  434. });
  435. }
  436. return parseFloat(value);
  437. });
  438. values.forEach(function(_, index) {
  439. var $bar = $($bars[index]);
  440. $bar.css({
  441. borderTopLeftRadius: index == firstNonZeroIndex ? '' : 0,
  442. borderBottomLeftRadius: index == firstNonZeroIndex ? '' : 0,
  443. borderTopRightRadius: index == lastNonZeroIndex ? '' : 0,
  444. borderBottomRightRadius: index == lastNonZeroIndex ? '' : 0
  445. });
  446. });
  447. $module
  448. .attr('data-percent', percents)
  449. ;
  450. },
  451. duration: function(duration) {
  452. duration = duration || settings.duration;
  453. duration = (typeof duration == 'number')
  454. ? duration + 'ms'
  455. : duration
  456. ;
  457. module.verbose('Setting progress bar transition duration', duration);
  458. $bars
  459. .css({
  460. 'transition-duration': duration
  461. })
  462. ;
  463. },
  464. percent: function(percents) {
  465. percents = module.helper.forceArray(percents).map(function(percent) {
  466. return (typeof percent == 'string')
  467. ? +(percent.replace('%', ''))
  468. : percent
  469. ;
  470. });
  471. var hasTotal = module.has.total();
  472. var totalPecent = module.helper.sum(percents);
  473. var isMultpleValues = percents.length > 1 && hasTotal;
  474. var sumTotal = module.helper.sum(module.helper.forceArray(module.value));
  475. if (isMultpleValues && sumTotal > module.total) {
  476. // Sum values instead of pecents to avoid precision issues when summing floats
  477. module.error(error.sumExceedsTotal, sumTotal, module.total);
  478. } else if (!isMultpleValues && totalPecent > 100) {
  479. // Sum before rouding since sum of rounded may have error though sum of actual is fine
  480. module.error(error.tooHigh, totalPecent);
  481. } else if (totalPecent < 0) {
  482. module.error(error.tooLow, totalPecent);
  483. } else {
  484. var autoPrecision = settings.precision > 0
  485. ? settings.precision
  486. : isMultpleValues
  487. ? module.helper.derivePrecision(Math.min.apply(null, module.value), module.total)
  488. : undefined;
  489. // round display percentage
  490. var roundedPercents = percents.map(function (percent) {
  491. return (autoPrecision > 0)
  492. ? Math.round(percent * (10 * autoPrecision)) / (10 * autoPrecision)
  493. : Math.round(percent)
  494. ;
  495. });
  496. module.percent = roundedPercents;
  497. if (!hasTotal) {
  498. module.value = roundedPercents.map(function (percent) {
  499. return (autoPrecision > 0)
  500. ? Math.round((percent / 100) * module.total * (10 * autoPrecision)) / (10 * autoPrecision)
  501. : Math.round((percent / 100) * module.total * 10) / 10
  502. ;
  503. });
  504. if (settings.limitValues) {
  505. module.value = module.value.map(function (value) {
  506. return (value > 100)
  507. ? 100
  508. : (module.value < 0)
  509. ? 0
  510. : module.value;
  511. });
  512. }
  513. }
  514. module.set.barWidth(percents);
  515. module.set.labelInterval();
  516. module.set.labels();
  517. }
  518. settings.onChange.call(element, percents, module.value, module.total);
  519. },
  520. labelInterval: function() {
  521. var
  522. animationCallback = function() {
  523. module.verbose('Bar finished animating, removing continuous label updates');
  524. clearInterval(module.interval);
  525. animating = false;
  526. module.set.labels();
  527. }
  528. ;
  529. clearInterval(module.interval);
  530. module.bind.transitionEnd(animationCallback);
  531. animating = true;
  532. module.interval = setInterval(function() {
  533. var
  534. isInDOM = $.contains(document.documentElement, element)
  535. ;
  536. if(!isInDOM) {
  537. clearInterval(module.interval);
  538. animating = false;
  539. }
  540. module.set.labels();
  541. }, settings.framerate);
  542. },
  543. labels: function() {
  544. module.verbose('Setting both bar progress and outer label text');
  545. module.set.barLabel();
  546. module.set.state();
  547. },
  548. label: function(text) {
  549. text = text || '';
  550. if(text) {
  551. text = module.get.text(text);
  552. module.verbose('Setting label to text', text);
  553. $label.text(text);
  554. }
  555. },
  556. state: function(percent) {
  557. percent = (percent !== undefined)
  558. ? percent
  559. : module.helper.sum(module.percent)
  560. ;
  561. if(percent === 100) {
  562. if(settings.autoSuccess && $bars.length === 1 && !(module.is.warning() || module.is.error() || module.is.success())) {
  563. module.set.success();
  564. module.debug('Automatically triggering success at 100%');
  565. }
  566. else {
  567. module.verbose('Reached 100% removing active state');
  568. module.remove.active();
  569. module.remove.progressPoll();
  570. }
  571. }
  572. else if(percent > 0) {
  573. module.verbose('Adjusting active progress bar label', percent);
  574. module.set.active();
  575. }
  576. else {
  577. module.remove.active();
  578. module.set.label(settings.text.active);
  579. }
  580. },
  581. barLabel: function(text) {
  582. $progresses.map(function(index, element){
  583. var $progress = $(element);
  584. if (text !== undefined) {
  585. $progress.text( module.get.text(text, index) );
  586. }
  587. else if (settings.label == 'ratio' && module.total) {
  588. module.verbose('Adding ratio to bar label');
  589. $progress.text( module.get.text(settings.text.ratio, index) );
  590. }
  591. else if (settings.label == 'percent') {
  592. module.verbose('Adding percentage to bar label');
  593. $progress.text( module.get.text(settings.text.percent, index) );
  594. }
  595. });
  596. },
  597. active: function(text) {
  598. text = text || settings.text.active;
  599. module.debug('Setting active state');
  600. if(settings.showActivity && !module.is.active() ) {
  601. $module.addClass(className.active);
  602. }
  603. module.remove.warning();
  604. module.remove.error();
  605. module.remove.success();
  606. text = settings.onLabelUpdate('active', text, module.value, module.total);
  607. if(text) {
  608. module.set.label(text);
  609. }
  610. module.bind.transitionEnd(function() {
  611. settings.onActive.call(element, module.value, module.total);
  612. });
  613. },
  614. success : function(text, keepState) {
  615. text = text || settings.text.success || settings.text.active;
  616. module.debug('Setting success state');
  617. $module.addClass(className.success);
  618. module.remove.active();
  619. module.remove.warning();
  620. module.remove.error();
  621. module.complete(keepState);
  622. if(settings.text.success) {
  623. text = settings.onLabelUpdate('success', text, module.value, module.total);
  624. module.set.label(text);
  625. }
  626. else {
  627. text = settings.onLabelUpdate('active', text, module.value, module.total);
  628. module.set.label(text);
  629. }
  630. module.bind.transitionEnd(function() {
  631. settings.onSuccess.call(element, module.total);
  632. });
  633. },
  634. warning : function(text, keepState) {
  635. text = text || settings.text.warning;
  636. module.debug('Setting warning state');
  637. $module.addClass(className.warning);
  638. module.remove.active();
  639. module.remove.success();
  640. module.remove.error();
  641. module.complete(keepState);
  642. text = settings.onLabelUpdate('warning', text, module.value, module.total);
  643. if(text) {
  644. module.set.label(text);
  645. }
  646. module.bind.transitionEnd(function() {
  647. settings.onWarning.call(element, module.value, module.total);
  648. });
  649. },
  650. error : function(text, keepState) {
  651. text = text || settings.text.error;
  652. module.debug('Setting error state');
  653. $module.addClass(className.error);
  654. module.remove.active();
  655. module.remove.success();
  656. module.remove.warning();
  657. module.complete(keepState);
  658. text = settings.onLabelUpdate('error', text, module.value, module.total);
  659. if(text) {
  660. module.set.label(text);
  661. }
  662. module.bind.transitionEnd(function() {
  663. settings.onError.call(element, module.value, module.total);
  664. });
  665. },
  666. transitionEvent: function() {
  667. transitionEnd = module.get.transitionEnd();
  668. },
  669. total: function(totalValue) {
  670. module.total = totalValue;
  671. },
  672. value: function(value) {
  673. module.value = module.helper.forceArray(value);
  674. },
  675. progress: function(value) {
  676. if(!module.has.progressPoll()) {
  677. module.debug('First update in progress update interval, immediately updating', value);
  678. module.update.progress(value);
  679. module.create.progressPoll();
  680. }
  681. else {
  682. module.debug('Updated within interval, setting next update to use new value', value);
  683. module.set.nextValue(value);
  684. }
  685. },
  686. nextValue: function(value) {
  687. module.nextValue = value;
  688. }
  689. },
  690. update: {
  691. toNextValue: function() {
  692. var
  693. nextValue = module.nextValue
  694. ;
  695. if(nextValue) {
  696. module.debug('Update interval complete using last updated value', nextValue);
  697. module.update.progress(nextValue);
  698. module.remove.nextValue();
  699. }
  700. },
  701. progress: function(values) {
  702. var hasTotal = module.has.total();
  703. if (hasTotal) {
  704. module.set.value(values);
  705. }
  706. var percentCompletes = module.helper.forceArray(values).map(function(value) {
  707. var
  708. percentComplete
  709. ;
  710. value = module.get.numericValue(value);
  711. if (value === false) {
  712. module.error(error.nonNumeric, value);
  713. }
  714. value = module.get.normalizedValue(value);
  715. if (hasTotal) {
  716. percentComplete = (value / module.total) * 100;
  717. module.debug('Calculating percent complete from total', percentComplete);
  718. }
  719. else {
  720. percentComplete = value;
  721. module.debug('Setting value to exact percentage value', percentComplete);
  722. }
  723. return percentComplete;
  724. });
  725. module.set.percent( percentCompletes );
  726. }
  727. },
  728. setting: function(name, value) {
  729. module.debug('Changing setting', name, value);
  730. if( $.isPlainObject(name) ) {
  731. $.extend(true, settings, name);
  732. }
  733. else if(value !== undefined) {
  734. if($.isPlainObject(settings[name])) {
  735. $.extend(true, settings[name], value);
  736. }
  737. else {
  738. settings[name] = value;
  739. }
  740. }
  741. else {
  742. return settings[name];
  743. }
  744. },
  745. internal: function(name, value) {
  746. if( $.isPlainObject(name) ) {
  747. $.extend(true, module, name);
  748. }
  749. else if(value !== undefined) {
  750. module[name] = value;
  751. }
  752. else {
  753. return module[name];
  754. }
  755. },
  756. debug: function() {
  757. if(!settings.silent && settings.debug) {
  758. if(settings.performance) {
  759. module.performance.log(arguments);
  760. }
  761. else {
  762. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  763. module.debug.apply(console, arguments);
  764. }
  765. }
  766. },
  767. verbose: function() {
  768. if(!settings.silent && settings.verbose && settings.debug) {
  769. if(settings.performance) {
  770. module.performance.log(arguments);
  771. }
  772. else {
  773. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  774. module.verbose.apply(console, arguments);
  775. }
  776. }
  777. },
  778. error: function() {
  779. if(!settings.silent) {
  780. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  781. module.error.apply(console, arguments);
  782. }
  783. },
  784. performance: {
  785. log: function(message) {
  786. var
  787. currentTime,
  788. executionTime,
  789. previousTime
  790. ;
  791. if(settings.performance) {
  792. currentTime = new Date().getTime();
  793. previousTime = time || currentTime;
  794. executionTime = currentTime - previousTime;
  795. time = currentTime;
  796. performance.push({
  797. 'Name' : message[0],
  798. 'Arguments' : [].slice.call(message, 1) || '',
  799. 'Element' : element,
  800. 'Execution Time' : executionTime
  801. });
  802. }
  803. clearTimeout(module.performance.timer);
  804. module.performance.timer = setTimeout(module.performance.display, 500);
  805. },
  806. display: function() {
  807. var
  808. title = settings.name + ':',
  809. totalTime = 0
  810. ;
  811. time = false;
  812. clearTimeout(module.performance.timer);
  813. $.each(performance, function(index, data) {
  814. totalTime += data['Execution Time'];
  815. });
  816. title += ' ' + totalTime + 'ms';
  817. if(moduleSelector) {
  818. title += ' \'' + moduleSelector + '\'';
  819. }
  820. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  821. console.groupCollapsed(title);
  822. if(console.table) {
  823. console.table(performance);
  824. }
  825. else {
  826. $.each(performance, function(index, data) {
  827. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  828. });
  829. }
  830. console.groupEnd();
  831. }
  832. performance = [];
  833. }
  834. },
  835. invoke: function(query, passedArguments, context) {
  836. var
  837. object = instance,
  838. maxDepth,
  839. found,
  840. response
  841. ;
  842. passedArguments = passedArguments || queryArguments;
  843. context = element || context;
  844. if(typeof query == 'string' && object !== undefined) {
  845. query = query.split(/[\. ]/);
  846. maxDepth = query.length - 1;
  847. $.each(query, function(depth, value) {
  848. var camelCaseValue = (depth != maxDepth)
  849. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  850. : query
  851. ;
  852. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  853. object = object[camelCaseValue];
  854. }
  855. else if( object[camelCaseValue] !== undefined ) {
  856. found = object[camelCaseValue];
  857. return false;
  858. }
  859. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  860. object = object[value];
  861. }
  862. else if( object[value] !== undefined ) {
  863. found = object[value];
  864. return false;
  865. }
  866. else {
  867. module.error(error.method, query);
  868. return false;
  869. }
  870. });
  871. }
  872. if ( $.isFunction( found ) ) {
  873. response = found.apply(context, passedArguments);
  874. }
  875. else if(found !== undefined) {
  876. response = found;
  877. }
  878. if(Array.isArray(returnedValue)) {
  879. returnedValue.push(response);
  880. }
  881. else if(returnedValue !== undefined) {
  882. returnedValue = [returnedValue, response];
  883. }
  884. else if(response !== undefined) {
  885. returnedValue = response;
  886. }
  887. return found;
  888. }
  889. };
  890. if(methodInvoked) {
  891. if(instance === undefined) {
  892. module.initialize();
  893. }
  894. module.invoke(query);
  895. }
  896. else {
  897. if(instance !== undefined) {
  898. instance.invoke('destroy');
  899. }
  900. module.initialize();
  901. }
  902. })
  903. ;
  904. return (returnedValue !== undefined)
  905. ? returnedValue
  906. : this
  907. ;
  908. };
  909. $.fn.progress.settings = {
  910. name : 'Progress',
  911. namespace : 'progress',
  912. silent : false,
  913. debug : false,
  914. verbose : false,
  915. performance : true,
  916. random : {
  917. min : 2,
  918. max : 5
  919. },
  920. duration : 300,
  921. updateInterval : 'auto',
  922. autoSuccess : true,
  923. showActivity : true,
  924. limitValues : true,
  925. label : 'percent',
  926. precision : 0,
  927. framerate : (1000 / 30), /// 30 fps
  928. percent : false,
  929. total : false,
  930. value : false,
  931. // delay in ms for fail safe animation callback
  932. failSafeDelay : 100,
  933. onLabelUpdate : function(state, text, value, total){
  934. return text;
  935. },
  936. onChange : function(percent, value, total){},
  937. onSuccess : function(total){},
  938. onActive : function(value, total){},
  939. onError : function(value, total){},
  940. onWarning : function(value, total){},
  941. error : {
  942. method : 'The method you called is not defined.',
  943. nonNumeric : 'Progress value is non numeric',
  944. tooHigh : 'Value specified is above 100%',
  945. tooLow : 'Value specified is below 0%',
  946. sumExceedsTotal : 'Sum of multple values exceed total',
  947. },
  948. regExp: {
  949. variable: /\{\$*[A-z0-9]+\}/g
  950. },
  951. metadata: {
  952. percent : 'percent',
  953. total : 'total',
  954. value : 'value'
  955. },
  956. selector : {
  957. bar : '> .bar',
  958. label : '> .label',
  959. progress : '.bar > .progress'
  960. },
  961. text : {
  962. active : false,
  963. error : false,
  964. success : false,
  965. warning : false,
  966. percent : '{percent}%',
  967. ratio : '{value} of {total}',
  968. bars : ['']
  969. },
  970. className : {
  971. active : 'active',
  972. error : 'error',
  973. success : 'success',
  974. warning : 'warning'
  975. }
  976. };
  977. })( jQuery, window, document );