countUp.ts 11 KB

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