countUp.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. var __assign = (this && this.__assign) || function () {
  2. __assign = Object.assign || function(t) {
  3. for (var s, i = 1, n = arguments.length; i < n; i++) {
  4. s = arguments[i];
  5. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  6. t[p] = s[p];
  7. }
  8. return t;
  9. };
  10. return __assign.apply(this, arguments);
  11. };
  12. // playground: stackblitz.com/edit/countup-typescript
  13. var CountUp = /** @class */ (function () {
  14. function CountUp(target, endVal, options) {
  15. var _this = this;
  16. this.endVal = endVal;
  17. this.options = options;
  18. this.version = '2.6.2';
  19. this.defaults = {
  20. startVal: 0,
  21. decimalPlaces: 0,
  22. duration: 2,
  23. useEasing: true,
  24. useGrouping: true,
  25. useIndianSeparators: false,
  26. smartEasingThreshold: 999,
  27. smartEasingAmount: 333,
  28. separator: ',',
  29. decimal: '.',
  30. prefix: '',
  31. suffix: '',
  32. enableScrollSpy: false,
  33. scrollSpyDelay: 200,
  34. scrollSpyOnce: false,
  35. };
  36. this.finalEndVal = null; // for smart easing
  37. this.useEasing = true;
  38. this.countDown = false;
  39. this.error = '';
  40. this.startVal = 0;
  41. this.paused = true;
  42. this.once = false;
  43. this.count = function (timestamp) {
  44. if (!_this.startTime) {
  45. _this.startTime = timestamp;
  46. }
  47. var progress = timestamp - _this.startTime;
  48. _this.remaining = _this.duration - progress;
  49. // to ease or not to ease
  50. if (_this.useEasing) {
  51. if (_this.countDown) {
  52. _this.frameVal = _this.startVal - _this.easingFn(progress, 0, _this.startVal - _this.endVal, _this.duration);
  53. }
  54. else {
  55. _this.frameVal = _this.easingFn(progress, _this.startVal, _this.endVal - _this.startVal, _this.duration);
  56. }
  57. }
  58. else {
  59. _this.frameVal = _this.startVal + (_this.endVal - _this.startVal) * (progress / _this.duration);
  60. }
  61. // don't go past endVal since progress can exceed duration in the last frame
  62. var wentPast = _this.countDown ? _this.frameVal < _this.endVal : _this.frameVal > _this.endVal;
  63. _this.frameVal = wentPast ? _this.endVal : _this.frameVal;
  64. // decimal
  65. _this.frameVal = Number(_this.frameVal.toFixed(_this.options.decimalPlaces));
  66. // format and print value
  67. _this.printValue(_this.frameVal);
  68. // whether to continue
  69. if (progress < _this.duration) {
  70. _this.rAF = requestAnimationFrame(_this.count);
  71. }
  72. else if (_this.finalEndVal !== null) {
  73. // smart easing
  74. _this.update(_this.finalEndVal);
  75. }
  76. else {
  77. if (_this.options.onCompleteCallback) {
  78. _this.options.onCompleteCallback();
  79. }
  80. }
  81. };
  82. // default format and easing functions
  83. this.formatNumber = function (num) {
  84. var neg = (num < 0) ? '-' : '';
  85. var result, x1, x2, x3;
  86. result = Math.abs(num).toFixed(_this.options.decimalPlaces);
  87. result += '';
  88. var x = result.split('.');
  89. x1 = x[0];
  90. x2 = x.length > 1 ? _this.options.decimal + x[1] : '';
  91. if (_this.options.useGrouping) {
  92. x3 = '';
  93. var factor = 3, j = 0;
  94. for (var i = 0, len = x1.length; i < len; ++i) {
  95. if (_this.options.useIndianSeparators && i === 4) {
  96. factor = 2;
  97. j = 1;
  98. }
  99. if (i !== 0 && (j % factor) === 0) {
  100. x3 = _this.options.separator + x3;
  101. }
  102. j++;
  103. x3 = x1[len - i - 1] + x3;
  104. }
  105. x1 = x3;
  106. }
  107. // optional numeral substitution
  108. if (_this.options.numerals && _this.options.numerals.length) {
  109. x1 = x1.replace(/[0-9]/g, function (w) { return _this.options.numerals[+w]; });
  110. x2 = x2.replace(/[0-9]/g, function (w) { return _this.options.numerals[+w]; });
  111. }
  112. return neg + _this.options.prefix + x1 + x2 + _this.options.suffix;
  113. };
  114. // t: current time, b: beginning value, c: change in value, d: duration
  115. this.easeOutExpo = function (t, b, c, d) {
  116. return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
  117. };
  118. this.options = __assign(__assign({}, this.defaults), options);
  119. this.formattingFn = (this.options.formattingFn) ?
  120. this.options.formattingFn : this.formatNumber;
  121. this.easingFn = (this.options.easingFn) ?
  122. this.options.easingFn : this.easeOutExpo;
  123. this.startVal = this.validateValue(this.options.startVal);
  124. this.frameVal = this.startVal;
  125. this.endVal = this.validateValue(endVal);
  126. this.options.decimalPlaces = Math.max(0 || this.options.decimalPlaces);
  127. this.resetDuration();
  128. this.options.separator = String(this.options.separator);
  129. this.useEasing = this.options.useEasing;
  130. if (this.options.separator === '') {
  131. this.options.useGrouping = false;
  132. }
  133. this.el = (typeof target === 'string') ? document.getElementById(target) : target;
  134. if (this.el) {
  135. this.printValue(this.startVal);
  136. }
  137. else {
  138. this.error = '[CountUp] target is null or undefined';
  139. }
  140. // scroll spy
  141. if (typeof window !== 'undefined' && this.options.enableScrollSpy) {
  142. if (!this.error) {
  143. // set up global array of onscroll functions to handle multiple instances
  144. window['onScrollFns'] = window['onScrollFns'] || [];
  145. window['onScrollFns'].push(function () { return _this.handleScroll(_this); });
  146. window.onscroll = function () {
  147. window['onScrollFns'].forEach(function (fn) { return fn(); });
  148. };
  149. this.handleScroll(this);
  150. }
  151. else {
  152. console.error(this.error, target);
  153. }
  154. }
  155. }
  156. CountUp.prototype.handleScroll = function (self) {
  157. if (!self || !window || self.once)
  158. return;
  159. var bottomOfScroll = window.innerHeight + window.scrollY;
  160. var rect = self.el.getBoundingClientRect();
  161. var topOfEl = rect.top + window.pageYOffset;
  162. var bottomOfEl = rect.top + rect.height + window.pageYOffset;
  163. if (bottomOfEl < bottomOfScroll && bottomOfEl > window.scrollY && self.paused) {
  164. // in view
  165. self.paused = false;
  166. setTimeout(function () { return self.start(); }, self.options.scrollSpyDelay);
  167. if (self.options.scrollSpyOnce)
  168. self.once = true;
  169. }
  170. else if ((window.scrollY > bottomOfEl || topOfEl > bottomOfScroll) &&
  171. !self.paused) {
  172. // out of view
  173. self.reset();
  174. }
  175. };
  176. /**
  177. * Smart easing works by breaking the animation into 2 parts, the second part being the
  178. * smartEasingAmount and first part being the total amount minus the smartEasingAmount. It works
  179. * by disabling easing for the first part and enabling it on the second part. It is used if
  180. * useEasing is true and the total animation amount exceeds the smartEasingThreshold.
  181. */
  182. CountUp.prototype.determineDirectionAndSmartEasing = function () {
  183. var end = (this.finalEndVal) ? this.finalEndVal : this.endVal;
  184. this.countDown = (this.startVal > end);
  185. var animateAmount = end - this.startVal;
  186. if (Math.abs(animateAmount) > this.options.smartEasingThreshold && this.options.useEasing) {
  187. this.finalEndVal = end;
  188. var up = (this.countDown) ? 1 : -1;
  189. this.endVal = end + (up * this.options.smartEasingAmount);
  190. this.duration = this.duration / 2;
  191. }
  192. else {
  193. this.endVal = end;
  194. this.finalEndVal = null;
  195. }
  196. if (this.finalEndVal !== null) {
  197. // setting finalEndVal indicates smart easing
  198. this.useEasing = false;
  199. }
  200. else {
  201. this.useEasing = this.options.useEasing;
  202. }
  203. };
  204. // start animation
  205. CountUp.prototype.start = function (callback) {
  206. if (this.error) {
  207. return;
  208. }
  209. if (callback) {
  210. this.options.onCompleteCallback = callback;
  211. }
  212. if (this.duration > 0) {
  213. this.determineDirectionAndSmartEasing();
  214. this.paused = false;
  215. this.rAF = requestAnimationFrame(this.count);
  216. }
  217. else {
  218. this.printValue(this.endVal);
  219. }
  220. };
  221. // pause/resume animation
  222. CountUp.prototype.pauseResume = function () {
  223. if (!this.paused) {
  224. cancelAnimationFrame(this.rAF);
  225. }
  226. else {
  227. this.startTime = null;
  228. this.duration = this.remaining;
  229. this.startVal = this.frameVal;
  230. this.determineDirectionAndSmartEasing();
  231. this.rAF = requestAnimationFrame(this.count);
  232. }
  233. this.paused = !this.paused;
  234. };
  235. // reset to startVal so animation can be run again
  236. CountUp.prototype.reset = function () {
  237. cancelAnimationFrame(this.rAF);
  238. this.paused = true;
  239. this.resetDuration();
  240. this.startVal = this.validateValue(this.options.startVal);
  241. this.frameVal = this.startVal;
  242. this.printValue(this.startVal);
  243. };
  244. // pass a new endVal and start animation
  245. CountUp.prototype.update = function (newEndVal) {
  246. cancelAnimationFrame(this.rAF);
  247. this.startTime = null;
  248. this.endVal = this.validateValue(newEndVal);
  249. if (this.endVal === this.frameVal) {
  250. return;
  251. }
  252. this.startVal = this.frameVal;
  253. if (this.finalEndVal == null) {
  254. this.resetDuration();
  255. }
  256. this.finalEndVal = null;
  257. this.determineDirectionAndSmartEasing();
  258. this.rAF = requestAnimationFrame(this.count);
  259. };
  260. CountUp.prototype.printValue = function (val) {
  261. var _a;
  262. if (!this.el)
  263. return;
  264. var result = this.formattingFn(val);
  265. if ((_a = this.options.plugin) === null || _a === void 0 ? void 0 : _a.render) {
  266. this.options.plugin.render(this.el, result);
  267. return;
  268. }
  269. if (this.el.tagName === 'INPUT') {
  270. var input = this.el;
  271. input.value = result;
  272. }
  273. else if (this.el.tagName === 'text' || this.el.tagName === 'tspan') {
  274. this.el.textContent = result;
  275. }
  276. else {
  277. this.el.innerHTML = result;
  278. }
  279. };
  280. CountUp.prototype.ensureNumber = function (n) {
  281. return (typeof n === 'number' && !isNaN(n));
  282. };
  283. CountUp.prototype.validateValue = function (value) {
  284. var newValue = Number(value);
  285. if (!this.ensureNumber(newValue)) {
  286. this.error = "[CountUp] invalid start or end value: ".concat(value);
  287. return null;
  288. }
  289. else {
  290. return newValue;
  291. }
  292. };
  293. CountUp.prototype.resetDuration = function () {
  294. this.startTime = null;
  295. this.duration = Number(this.options.duration) * 1000;
  296. this.remaining = this.duration;
  297. };
  298. return CountUp;
  299. }());
  300. export { CountUp };