You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

3157 line
74 KiB

  1. function $$1(expr, con) {
  2. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  3. }
  4. $$1.create = (tag, o) => {
  5. var element = document.createElement(tag);
  6. for (var i in o) {
  7. var val = o[i];
  8. if (i === "inside") {
  9. $$1(val).appendChild(element);
  10. }
  11. else if (i === "around") {
  12. var ref = $$1(val);
  13. ref.parentNode.insertBefore(element, ref);
  14. element.appendChild(ref);
  15. } else if (i === "styles") {
  16. if(typeof val === "object") {
  17. Object.keys(val).map(prop => {
  18. element.style[prop] = val[prop];
  19. });
  20. }
  21. } else if (i in element ) {
  22. element[i] = val;
  23. }
  24. else {
  25. element.setAttribute(i, val);
  26. }
  27. }
  28. return element;
  29. };
  30. function getOffset(element) {
  31. let rect = element.getBoundingClientRect();
  32. return {
  33. // https://stackoverflow.com/a/7436602/6495043
  34. // rect.top varies with scroll, so we add whatever has been
  35. // scrolled to it to get absolute distance from actual page top
  36. top: rect.top + (document.documentElement.scrollTop || document.body.scrollTop),
  37. left: rect.left + (document.documentElement.scrollLeft || document.body.scrollLeft)
  38. };
  39. }
  40. function isElementInViewport(el) {
  41. // Although straightforward: https://stackoverflow.com/a/7557433/6495043
  42. var rect = el.getBoundingClientRect();
  43. return (
  44. rect.top >= 0 &&
  45. rect.left >= 0 &&
  46. rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
  47. rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
  48. );
  49. }
  50. function getElementContentWidth(element) {
  51. var styles = window.getComputedStyle(element);
  52. var padding = parseFloat(styles.paddingLeft) +
  53. parseFloat(styles.paddingRight);
  54. return element.clientWidth - padding;
  55. }
  56. class SvgTip {
  57. constructor({
  58. parent = null,
  59. colors = []
  60. }) {
  61. this.parent = parent;
  62. this.colors = colors;
  63. this.title_name = '';
  64. this.title_value = '';
  65. this.list_values = [];
  66. this.title_value_first = 0;
  67. this.x = 0;
  68. this.y = 0;
  69. this.top = 0;
  70. this.left = 0;
  71. this.setup();
  72. }
  73. setup() {
  74. this.make_tooltip();
  75. }
  76. refresh() {
  77. this.fill();
  78. this.calc_position();
  79. // this.show_tip();
  80. }
  81. make_tooltip() {
  82. this.container = $$1.create('div', {
  83. inside: this.parent,
  84. className: 'graph-svg-tip comparison',
  85. innerHTML: `<span class="title"></span>
  86. <ul class="data-point-list"></ul>
  87. <div class="svg-pointer"></div>`
  88. });
  89. this.hide_tip();
  90. this.title = this.container.querySelector('.title');
  91. this.data_point_list = this.container.querySelector('.data-point-list');
  92. this.parent.addEventListener('mouseleave', () => {
  93. this.hide_tip();
  94. });
  95. }
  96. fill() {
  97. let title;
  98. if(this.title_value_first) {
  99. title = `<strong>${this.title_value}</strong>${this.title_name}`;
  100. } else {
  101. title = `${this.title_name}<strong>${this.title_value}</strong>`;
  102. }
  103. this.title.innerHTML = title;
  104. this.data_point_list.innerHTML = '';
  105. this.list_values.map((set, i) => {
  106. const color = this.colors[i] || 'black';
  107. let li = $$1.create('li', {
  108. styles: {
  109. 'border-top': `3px solid ${color}`
  110. },
  111. innerHTML: `<strong style="display: block;">${ set.value === 0 || set.value ? set.value : '' }</strong>
  112. ${set.title ? set.title : '' }`
  113. });
  114. this.data_point_list.appendChild(li);
  115. });
  116. }
  117. calc_position() {
  118. let width = this.container.offsetWidth;
  119. this.top = this.y - this.container.offsetHeight;
  120. this.left = this.x - width/2;
  121. let max_left = this.parent.offsetWidth - width;
  122. let pointer = this.container.querySelector('.svg-pointer');
  123. if(this.left < 0) {
  124. pointer.style.left = `calc(50% - ${-1 * this.left}px)`;
  125. this.left = 0;
  126. } else if(this.left > max_left) {
  127. let delta = this.left - max_left;
  128. let pointer_offset = `calc(50% + ${delta}px)`;
  129. pointer.style.left = pointer_offset;
  130. this.left = max_left;
  131. } else {
  132. pointer.style.left = `50%`;
  133. }
  134. }
  135. set_values(x, y, title_name = '', title_value = '', list_values = [], title_value_first = 0) {
  136. this.title_name = title_name;
  137. this.title_value = title_value;
  138. this.list_values = list_values;
  139. this.x = x;
  140. this.y = y;
  141. this.title_value_first = title_value_first;
  142. this.refresh();
  143. }
  144. hide_tip() {
  145. this.container.style.top = '0px';
  146. this.container.style.left = '0px';
  147. this.container.style.opacity = '0';
  148. }
  149. show_tip() {
  150. this.container.style.top = this.top + 'px';
  151. this.container.style.left = this.left + 'px';
  152. this.container.style.opacity = '1';
  153. }
  154. }
  155. /**
  156. * Returns the value of a number upto 2 decimal places.
  157. * @param {Number} d Any number
  158. */
  159. function floatTwo(d) {
  160. return parseFloat(d.toFixed(2));
  161. }
  162. /**
  163. * Returns whether or not two given arrays are equal.
  164. * @param {Array} arr1 First array
  165. * @param {Array} arr2 Second array
  166. */
  167. /**
  168. * Shuffles array in place. ES6 version
  169. * @param {Array} array An array containing the items.
  170. */
  171. /**
  172. * Fill an array with extra points
  173. * @param {Array} array Array
  174. * @param {Number} count number of filler elements
  175. * @param {Object} element element to fill with
  176. * @param {Boolean} start fill at start?
  177. */
  178. function fillArray(array, count, element, start=false) {
  179. if(!element) {
  180. element = start ? array[0] : array[array.length - 1];
  181. }
  182. let fillerArray = new Array(Math.abs(count)).fill(element);
  183. array = start ? fillerArray.concat(array) : array.concat(fillerArray);
  184. return array;
  185. }
  186. /**
  187. * Returns pixel width of string.
  188. * @param {String} string
  189. * @param {Number} charWidth Width of single char in pixels
  190. */
  191. function getStringWidth(string, charWidth) {
  192. return (string+"").length * charWidth;
  193. }
  194. function getBarHeightAndYAttr(yTop, zeroLine) {
  195. let height, y;
  196. if (yTop <= zeroLine) {
  197. height = zeroLine - yTop;
  198. y = yTop;
  199. } else {
  200. height = yTop - zeroLine;
  201. y = zeroLine;
  202. }
  203. return [height, y];
  204. }
  205. function equilizeNoOfElements(array1, array2,
  206. extra_count=array2.length - array1.length) {
  207. // Doesn't work if either has zero elements.
  208. if(extra_count > 0) {
  209. array1 = fillArray(array1, extra_count);
  210. } else {
  211. array2 = fillArray(array2, extra_count);
  212. }
  213. return [array1, array2];
  214. }
  215. // let char_width = 8;
  216. // let allowed_space = avgUnitWidth * 1.5;
  217. // let allowed_letters = allowed_space / 8;
  218. // return values.map((value, i) => {
  219. // let space_taken = getStringWidth(value, char_width) + 2;
  220. // if(space_taken > allowed_space) {
  221. // if(isSeries) {
  222. // // Skip some axis lines if X axis is a series
  223. // let skips = 1;
  224. // while((space_taken/skips)*2 > allowed_space) {
  225. // skips++;
  226. // }
  227. // if(i % skips !== 0) {
  228. // return;
  229. // }
  230. // } else {
  231. // value = value.slice(0, allowed_letters-3) + " ...";
  232. // }
  233. // }
  234. const UNIT_ANIM_DUR = 350;
  235. const MARKER_LINE_ANIM_DUR = UNIT_ANIM_DUR;
  236. const REPLACE_ALL_NEW_DUR = 250;
  237. const STD_EASING = 'easein';
  238. function translate(unit, oldCoord, newCoord, duration) {
  239. let old = typeof oldCoord === 'string' ? oldCoord : oldCoord.join(', ');
  240. return [
  241. unit,
  242. {transform: newCoord.join(', ')},
  243. duration,
  244. STD_EASING,
  245. "translate",
  246. {transform: old}
  247. ];
  248. }
  249. function translateVertLine(xLine, newX, oldX) {
  250. return translate(xLine, [oldX, 0], [newX, 0], MARKER_LINE_ANIM_DUR);
  251. }
  252. function translateHoriLine(yLine, newY, oldY) {
  253. return translate(yLine, [0, oldY], [0, newY], MARKER_LINE_ANIM_DUR);
  254. }
  255. function animateRegion(rectGroup, newY1, newY2, oldY2) {
  256. let newHeight = newY1 - newY2;
  257. let rect = rectGroup.childNodes[0];
  258. let width = rect.getAttribute("width");
  259. let rectAnim = [
  260. rect,
  261. { height: newHeight, 'stroke-dasharray': `${width}, ${newHeight}` },
  262. MARKER_LINE_ANIM_DUR,
  263. STD_EASING
  264. ];
  265. let groupAnim = translate(rectGroup, [0, oldY2], [0, newY2], MARKER_LINE_ANIM_DUR);
  266. return [rectAnim, groupAnim];
  267. }
  268. function animateBar(bar, x, yTop, width, index=0, meta={}) {
  269. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  270. if(bar.nodeName !== 'rect') {
  271. let rect = bar.childNodes[0];
  272. let rectAnim = [
  273. rect,
  274. {width: width, height: height},
  275. UNIT_ANIM_DUR,
  276. STD_EASING
  277. ];
  278. let old = bar.getAttribute("transform").split("(")[1].slice(0, -1);
  279. let groupAnim = translate(bar, old, [x, y], MARKER_LINE_ANIM_DUR);
  280. return [rectAnim, groupAnim];
  281. } else {
  282. return [[bar, {width: width, height: height, x: x, y: y}, UNIT_ANIM_DUR, STD_EASING]];
  283. }
  284. // bar.animate({height: args.newHeight, y: yTop}, UNIT_ANIM_DUR, mina.easein);
  285. }
  286. /*
  287. <filter id="glow" x="-10%" y="-10%" width="120%" height="120%">
  288. <feGaussianBlur stdDeviation="0.5 0.5" result="glow"></feGaussianBlur>
  289. <feMerge>
  290. <feMergeNode in="glow"></feMergeNode>
  291. <feMergeNode in="glow"></feMergeNode>
  292. <feMergeNode in="glow"></feMergeNode>
  293. </feMerge>
  294. </filter>
  295. filter: url(#glow);
  296. fill: #fff;
  297. */
  298. const AXIS_TICK_LENGTH = 6;
  299. const LABEL_MARGIN = 4;
  300. const FONT_SIZE = 10;
  301. const BASE_LINE_COLOR = '#dadada';
  302. function $$2(expr, con) {
  303. return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
  304. }
  305. function createSVG(tag, o) {
  306. var element = document.createElementNS("http://www.w3.org/2000/svg", tag);
  307. for (var i in o) {
  308. var val = o[i];
  309. if (i === "inside") {
  310. $$2(val).appendChild(element);
  311. }
  312. else if (i === "around") {
  313. var ref = $$2(val);
  314. ref.parentNode.insertBefore(element, ref);
  315. element.appendChild(ref);
  316. } else if (i === "styles") {
  317. if(typeof val === "object") {
  318. Object.keys(val).map(prop => {
  319. element.style[prop] = val[prop];
  320. });
  321. }
  322. } else {
  323. if(i === "className") { i = "class"; }
  324. if(i === "innerHTML") {
  325. element['textContent'] = val;
  326. } else {
  327. element.setAttribute(i, val);
  328. }
  329. }
  330. }
  331. return element;
  332. }
  333. function makeSVGContainer(parent, className, width, height) {
  334. return createSVG('svg', {
  335. className: className,
  336. inside: parent,
  337. width: width,
  338. height: height
  339. });
  340. }
  341. function makeSVGDefs(svgContainer) {
  342. return createSVG('defs', {
  343. inside: svgContainer,
  344. });
  345. }
  346. function makeSVGGroup(parent, className, transform='') {
  347. return createSVG('g', {
  348. className: className,
  349. inside: parent,
  350. transform: transform
  351. });
  352. }
  353. function makePath(pathStr, className='', stroke='none', fill='none') {
  354. return createSVG('path', {
  355. className: className,
  356. d: pathStr,
  357. styles: {
  358. stroke: stroke,
  359. fill: fill
  360. }
  361. });
  362. }
  363. function makeHeatSquare(className, x, y, size, fill='none', data={}) {
  364. let args = {
  365. className: className,
  366. x: x,
  367. y: y,
  368. width: size,
  369. height: size,
  370. fill: 1
  371. };
  372. Object.keys(data).map(key => {
  373. args[key] = data[key];
  374. });
  375. return createSVG("rect", args);
  376. }
  377. function makeText(className, x, y, content) {
  378. return createSVG('text', {
  379. className: className,
  380. x: x,
  381. y: y,
  382. dy: (FONT_SIZE / 2) + 'px',
  383. 'font-size': FONT_SIZE + 'px',
  384. innerHTML: content
  385. });
  386. }
  387. function makeVertLine(x, label, y1, y2, options={}) {
  388. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  389. let l = createSVG('line', {
  390. className: 'line-vertical ' + options.className,
  391. x1: 0,
  392. x2: 0,
  393. y1: y1,
  394. y2: y2,
  395. styles: {
  396. stroke: options.stroke
  397. }
  398. });
  399. let text = createSVG('text', {
  400. x: 0,
  401. y: y1 > y2 ? y1 + LABEL_MARGIN : y1 - LABEL_MARGIN - FONT_SIZE,
  402. dy: FONT_SIZE + 'px',
  403. 'font-size': FONT_SIZE + 'px',
  404. 'text-anchor': 'middle',
  405. innerHTML: label
  406. });
  407. let line = createSVG('g', {
  408. transform: `translate(${ x }, 0)`
  409. });
  410. line.appendChild(l);
  411. line.appendChild(text);
  412. return line;
  413. }
  414. function makeHoriLine(y, label, x1, x2, options={}) {
  415. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  416. if(!options.lineType) options.lineType = '';
  417. let className = 'line-horizontal ' + options.className +
  418. (options.lineType === "dashed" ? "dashed": "");
  419. let l = createSVG('line', {
  420. className: className,
  421. x1: x1,
  422. x2: x2,
  423. y1: 0,
  424. y2: 0,
  425. styles: {
  426. stroke: options.stroke
  427. }
  428. });
  429. let text = createSVG('text', {
  430. x: x1 < x2 ? x1 - LABEL_MARGIN : x1 + LABEL_MARGIN,
  431. y: 0,
  432. dy: (FONT_SIZE / 2 - 2) + 'px',
  433. 'font-size': FONT_SIZE + 'px',
  434. 'text-anchor': x1 < x2 ? 'end' : 'start',
  435. innerHTML: label+""
  436. });
  437. let line = createSVG('g', {
  438. transform: `translate(0, ${y})`,
  439. 'stroke-opacity': 1
  440. });
  441. if(text === 0 || text === '0') {
  442. line.style.stroke = "rgba(27, 31, 35, 0.6)";
  443. }
  444. line.appendChild(l);
  445. line.appendChild(text);
  446. return line;
  447. }
  448. function yLine(y, label, width, options={}) {
  449. if(!options.pos) options.pos = 'left';
  450. if(!options.offset) options.offset = 0;
  451. if(!options.mode) options.mode = 'span';
  452. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  453. if(!options.className) options.className = '';
  454. let x1 = -1 * AXIS_TICK_LENGTH;
  455. let x2 = options.mode === 'span' ? width + AXIS_TICK_LENGTH : 0;
  456. if(options.mode === 'tick' && options.pos === 'right') {
  457. x1 = width + AXIS_TICK_LENGTH;
  458. x2 = width;
  459. }
  460. x1 += options.offset;
  461. x2 += options.offset;
  462. return makeHoriLine(y, label, x1, x2, {
  463. stroke: options.stroke,
  464. className: options.className,
  465. lineType: options.lineType
  466. });
  467. }
  468. function xLine(x, label, height, options={}) {
  469. if(!options.pos) options.pos = 'bottom';
  470. if(!options.offset) options.offset = 0;
  471. if(!options.mode) options.mode = 'span';
  472. if(!options.stroke) options.stroke = BASE_LINE_COLOR;
  473. if(!options.className) options.className = '';
  474. // Draw X axis line in span/tick mode with optional label
  475. // y2(span)
  476. // |
  477. // |
  478. // x line |
  479. // |
  480. // |
  481. // ---------------------+-- y2(tick)
  482. // |
  483. // y1
  484. let y1 = height + AXIS_TICK_LENGTH;
  485. let y2 = options.mode === 'span' ? -1 * AXIS_TICK_LENGTH : height;
  486. if(options.mode === 'tick' && options.pos === 'top') {
  487. // top axis ticks
  488. y1 = -1 * AXIS_TICK_LENGTH;
  489. y2 = 0;
  490. }
  491. return makeVertLine(x, label, y1, y2, {
  492. stroke: options.stroke,
  493. className: options.className,
  494. lineType: options.lineType
  495. });
  496. }
  497. function yMarker(y, label, width, options={}) {
  498. let labelSvg = createSVG('text', {
  499. className: 'chart-label',
  500. x: width - getStringWidth(label, 5) - LABEL_MARGIN,
  501. y: 0,
  502. dy: (FONT_SIZE / -2) + 'px',
  503. 'font-size': FONT_SIZE + 'px',
  504. 'text-anchor': 'start',
  505. innerHTML: label+""
  506. });
  507. let line = makeHoriLine(y, '', 0, width, {
  508. stroke: options.stroke || BASE_LINE_COLOR,
  509. className: options.className || '',
  510. lineType: options.lineType
  511. });
  512. line.appendChild(labelSvg);
  513. return line;
  514. }
  515. function yRegion(y1, y2, width, label) {
  516. // return a group
  517. let height = y1 - y2;
  518. let rect = createSVG('rect', {
  519. className: `bar mini`, // remove class
  520. styles: {
  521. fill: `rgba(228, 234, 239, 0.49)`,
  522. stroke: BASE_LINE_COLOR,
  523. 'stroke-dasharray': `${width}, ${height}`
  524. },
  525. // 'data-point-index': index,
  526. x: 0,
  527. y: 0,
  528. width: width,
  529. height: height
  530. });
  531. let labelSvg = createSVG('text', {
  532. className: 'chart-label',
  533. x: width - getStringWidth(label, 4.5) - LABEL_MARGIN,
  534. y: 0,
  535. dy: (FONT_SIZE / -2) + 'px',
  536. 'font-size': FONT_SIZE + 'px',
  537. 'text-anchor': 'start',
  538. innerHTML: label+""
  539. });
  540. let region = createSVG('g', {
  541. transform: `translate(0, ${y2})`
  542. });
  543. region.appendChild(rect);
  544. region.appendChild(labelSvg);
  545. return region;
  546. }
  547. function datasetBar(x, yTop, width, color, label='', index=0, offset=0, meta={}) {
  548. let [height, y] = getBarHeightAndYAttr(yTop, meta.zeroLine);
  549. // console.log(yTop, meta.zeroLine, y, offset);
  550. y -= offset;
  551. let rect = createSVG('rect', {
  552. className: `bar mini`,
  553. style: `fill: ${color}`,
  554. 'data-point-index': index,
  555. x: x,
  556. y: y,
  557. width: width,
  558. height: height || meta.minHeight // TODO: correct y for positive min height
  559. });
  560. if(!label && !label.length) {
  561. return rect;
  562. } else {
  563. rect.setAttribute('y', 0);
  564. rect.setAttribute('x', 0);
  565. let text = createSVG('text', {
  566. className: 'data-point-value',
  567. x: width/2,
  568. y: 0,
  569. dy: (FONT_SIZE / 2 * -1) + 'px',
  570. 'font-size': FONT_SIZE + 'px',
  571. 'text-anchor': 'middle',
  572. innerHTML: label
  573. });
  574. let group = createSVG('g', {
  575. transform: `translate(${x}, ${y})`
  576. });
  577. group.appendChild(rect);
  578. group.appendChild(text);
  579. return group;
  580. }
  581. }
  582. const PRESET_COLOR_MAP = {
  583. 'light-blue': '#7cd6fd',
  584. 'blue': '#5e64ff',
  585. 'violet': '#743ee2',
  586. 'red': '#ff5858',
  587. 'orange': '#ffa00a',
  588. 'yellow': '#feef72',
  589. 'green': '#28a745',
  590. 'light-green': '#98d85b',
  591. 'purple': '#b554ff',
  592. 'magenta': '#ffa3ef',
  593. 'black': '#36114C',
  594. 'grey': '#bdd3e6',
  595. 'light-grey': '#f0f4f7',
  596. 'dark-grey': '#b8c2cc'
  597. };
  598. const DEFAULT_COLORS = ['light-blue', 'blue', 'violet', 'red', 'orange',
  599. 'yellow', 'green', 'light-green', 'purple', 'magenta'];
  600. function limitColor(r){
  601. if (r > 255) return 255;
  602. else if (r < 0) return 0;
  603. return r;
  604. }
  605. function lightenDarkenColor(color, amt) {
  606. let col = getColor(color);
  607. let usePound = false;
  608. if (col[0] == "#") {
  609. col = col.slice(1);
  610. usePound = true;
  611. }
  612. let num = parseInt(col,16);
  613. let r = limitColor((num >> 16) + amt);
  614. let b = limitColor(((num >> 8) & 0x00FF) + amt);
  615. let g = limitColor((num & 0x0000FF) + amt);
  616. return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  617. }
  618. function isValidColor(string) {
  619. // https://stackoverflow.com/a/8027444/6495043
  620. return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(string);
  621. }
  622. const getColor = (color) => {
  623. return PRESET_COLOR_MAP[color] || color;
  624. };
  625. const ALL_CHART_TYPES = ['line', 'scatter', 'bar', 'percentage', 'heatmap', 'pie'];
  626. const COMPATIBLE_CHARTS = {
  627. bar: ['line', 'scatter', 'percentage', 'pie'],
  628. line: ['scatter', 'bar', 'percentage', 'pie'],
  629. pie: ['line', 'scatter', 'percentage', 'bar'],
  630. scatter: ['line', 'bar', 'percentage', 'pie'],
  631. percentage: ['bar', 'line', 'scatter', 'pie'],
  632. heatmap: []
  633. };
  634. // Needs structure as per only labels/datasets
  635. const COLOR_COMPATIBLE_CHARTS = {
  636. bar: ['line', 'scatter'],
  637. line: ['scatter', 'bar'],
  638. pie: ['percentage'],
  639. scatter: ['line', 'bar'],
  640. percentage: ['pie'],
  641. heatmap: []
  642. };
  643. function getDifferentChart(type, current_type, args) {
  644. if(type === current_type) return;
  645. if(!ALL_CHART_TYPES.includes(type)) {
  646. console.error(`'${type}' is not a valid chart type.`);
  647. }
  648. if(!COMPATIBLE_CHARTS[current_type].includes(type)) {
  649. console.error(`'${current_type}' chart cannot be converted to a '${type}' chart.`);
  650. }
  651. // whether the new chart can use the existing colors
  652. const useColor = COLOR_COMPATIBLE_CHARTS[current_type].includes(type);
  653. // Okay, this is anticlimactic
  654. // this function will need to actually be 'changeChartType(type)'
  655. // that will update only the required elements, but for now ...
  656. return new Chart({
  657. parent: args.parent,
  658. title: args.title,
  659. data: args.data,
  660. type: type,
  661. height: args.height,
  662. colors: useColor ? args.colors : undefined
  663. });
  664. }
  665. // Leveraging SMIL Animations
  666. const EASING = {
  667. ease: "0.25 0.1 0.25 1",
  668. linear: "0 0 1 1",
  669. // easein: "0.42 0 1 1",
  670. easein: "0.1 0.8 0.2 1",
  671. easeout: "0 0 0.58 1",
  672. easeinout: "0.42 0 0.58 1"
  673. };
  674. function animateSVGElement(element, props, dur, easingType="linear", type=undefined, oldValues={}) {
  675. let animElement = element.cloneNode(true);
  676. let newElement = element.cloneNode(true);
  677. for(var attributeName in props) {
  678. let animateElement;
  679. if(attributeName === 'transform') {
  680. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animateTransform");
  681. } else {
  682. animateElement = document.createElementNS("http://www.w3.org/2000/svg", "animate");
  683. }
  684. let currentValue = oldValues[attributeName] || element.getAttribute(attributeName);
  685. let value = props[attributeName];
  686. let animAttr = {
  687. attributeName: attributeName,
  688. from: currentValue,
  689. to: value,
  690. begin: "0s",
  691. dur: dur/1000 + "s",
  692. values: currentValue + ";" + value,
  693. keySplines: EASING[easingType],
  694. keyTimes: "0;1",
  695. calcMode: "spline",
  696. fill: 'freeze'
  697. };
  698. if(type) {
  699. animAttr["type"] = type;
  700. }
  701. for (var i in animAttr) {
  702. animateElement.setAttribute(i, animAttr[i]);
  703. }
  704. animElement.appendChild(animateElement);
  705. if(type) {
  706. newElement.setAttribute(attributeName, `translate(${value})`);
  707. } else {
  708. newElement.setAttribute(attributeName, value);
  709. }
  710. }
  711. return [animElement, newElement];
  712. }
  713. function transform(element, style) { // eslint-disable-line no-unused-vars
  714. element.style.transform = style;
  715. element.style.webkitTransform = style;
  716. element.style.msTransform = style;
  717. element.style.mozTransform = style;
  718. element.style.oTransform = style;
  719. }
  720. function animateSVG(svgContainer, elements) {
  721. let newElements = [];
  722. let animElements = [];
  723. elements.map(element => {
  724. let unit = element[0];
  725. let parent = unit.parentNode;
  726. let animElement, newElement;
  727. element[0] = unit;
  728. [animElement, newElement] = animateSVGElement(...element);
  729. newElements.push(newElement);
  730. animElements.push([animElement, parent]);
  731. parent.replaceChild(animElement, unit);
  732. });
  733. let animSvg = svgContainer.cloneNode(true);
  734. animElements.map((animElement, i) => {
  735. animElement[1].replaceChild(newElements[i], animElement[0]);
  736. elements[i][0] = newElements[i];
  737. });
  738. return animSvg;
  739. }
  740. function runSMILAnimation(parent, svgElement, elementsToAnimate) {
  741. if(elementsToAnimate.length === 0) return;
  742. let animSvgElement = animateSVG(svgElement, elementsToAnimate);
  743. if(svgElement.parentNode == parent) {
  744. parent.removeChild(svgElement);
  745. parent.appendChild(animSvgElement);
  746. }
  747. // Replace the new svgElement (data has already been replaced)
  748. setTimeout(() => {
  749. if(animSvgElement.parentNode == parent) {
  750. parent.removeChild(animSvgElement);
  751. parent.appendChild(svgElement);
  752. }
  753. }, REPLACE_ALL_NEW_DUR);
  754. }
  755. class BaseChart {
  756. constructor({
  757. height = 240,
  758. title = '',
  759. subtitle = '',
  760. colors = [],
  761. isNavigable = 0,
  762. showLegend = 1,
  763. type = '',
  764. parent,
  765. data
  766. }) {
  767. this.rawChartArgs = arguments[0];
  768. this.parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
  769. this.title = title;
  770. this.subtitle = subtitle;
  771. this.argHeight = height;
  772. this.type = type;
  773. this.isNavigable = isNavigable;
  774. if(this.isNavigable) {
  775. this.currentIndex = 0;
  776. }
  777. this.realData = this.prepareData(data);
  778. this.data = this.prepareFirstData(this.realData);
  779. this.colors = [];
  780. this.config = {};
  781. this.state = {};
  782. this.options = {};
  783. this.configure(arguments[0]);
  784. }
  785. configure(args) {
  786. this.setColors();
  787. this.config = {
  788. showTooltip: 1, // calculate
  789. showLegend: 1,
  790. isNavigable: 0,
  791. animate: 1
  792. };
  793. this.setMargins();
  794. // Bind window events
  795. window.addEventListener('resize', () => this.draw());
  796. window.addEventListener('orientationchange', () => this.draw());
  797. }
  798. setColors() {
  799. let args = this.rawChartArgs;
  800. // Needs structure as per only labels/datasets, from config
  801. const list = args.type === 'percentage' || args.type === 'pie'
  802. ? args.data.labels
  803. : args.data.datasets;
  804. if(!args.colors || (list && args.colors.length < list.length)) {
  805. this.colors = DEFAULT_COLORS;
  806. } else {
  807. this.colors = args.colors;
  808. }
  809. this.colors = this.colors.map(color => getColor(color));
  810. }
  811. setMargins() {
  812. // TODO: think for all
  813. let height = this.argHeight;
  814. this.baseHeight = height;
  815. this.height = height - 40; // change
  816. this.translateY = 20;
  817. // Horizontal margins
  818. this.translateXLeft = 60;
  819. this.translateXRight = 40;
  820. }
  821. validate(){
  822. if(!this.parent) {
  823. console.error("No parent element to render on was provided.");
  824. return false;
  825. }
  826. return true;
  827. }
  828. setup() {
  829. if(this.validate()) {
  830. this._setup();
  831. }
  832. }
  833. _setup() {
  834. this.makeContainer();
  835. this.makeTooltip(); // without binding
  836. this.draw(true);
  837. }
  838. initComponents() {}
  839. setupComponents() {
  840. this.components = new Map();
  841. }
  842. makeContainer() {
  843. this.container = $$1.create('div', {
  844. className: 'chart-container',
  845. innerHTML: `<h6 class="title">${this.title}</h6>
  846. <h6 class="sub-title uppercase">${this.subtitle}</h6>
  847. <div class="frappe-chart graphics"></div>
  848. <div class="graph-stats-container"></div>`
  849. });
  850. // Chart needs a dedicated parent element
  851. this.parent.innerHTML = '';
  852. this.parent.appendChild(this.container);
  853. this.chartWrapper = this.container.querySelector('.frappe-chart');
  854. this.statsWrapper = this.container.querySelector('.graph-stats-container');
  855. }
  856. makeTooltip() {
  857. this.tip = new SvgTip({
  858. parent: this.chartWrapper,
  859. colors: this.colors
  860. });
  861. this.bindTooltip();
  862. }
  863. bindTooltip() {}
  864. draw(init=false) {
  865. this.calcWidth();
  866. this.makeChartArea();
  867. this.calc();
  868. this.initComponents(); // Only depend on the drawArea made in makeChartArea
  869. this.setupComponents();
  870. this.components.forEach(c => c.setup(this.drawArea)); // or c.build()
  871. this.components.forEach(c => c.make()); // or c.build()
  872. this.renderLegend();
  873. this.setupNavigation(init);
  874. // TODO: remove timeout and decrease post animate time in chart component
  875. if(init) {
  876. this.data = this.realData;
  877. setTimeout(() => {this.update();}, 1000);
  878. }
  879. }
  880. calcWidth() {
  881. let outerAnnotationsWidth = 0;
  882. // let charWidth = 8;
  883. // this.specificValues.map(val => {
  884. // let strWidth = getStringWidth((val.title + ""), charWidth);
  885. // if(strWidth > outerAnnotationsWidth) {
  886. // outerAnnotationsWidth = strWidth - 40;
  887. // }
  888. // });
  889. this.baseWidth = getElementContentWidth(this.parent) - outerAnnotationsWidth;
  890. this.width = this.baseWidth - (this.translateXLeft + this.translateXRight);
  891. }
  892. update(data=this.data) {
  893. this.data = this.prepareData(data);
  894. this.calc(); // builds state
  895. this.render();
  896. }
  897. prepareData() {}
  898. calc() {} // builds state
  899. render(components=this.components, animate=true) {
  900. // Can decouple to this.refreshComponents() first to save animation timeout
  901. let elementsToAnimate = [];
  902. components.forEach(c => {
  903. elementsToAnimate = elementsToAnimate.concat(c.update(animate));
  904. });
  905. if(elementsToAnimate.length > 0) {
  906. runSMILAnimation(this.chartWrapper, this.svg, elementsToAnimate);
  907. }
  908. // TODO: rebind new units
  909. // if(this.isNavigable) {
  910. // this.bind_units(units_array);
  911. // }
  912. }
  913. makeChartArea() {
  914. if(this.svg) {
  915. this.chartWrapper.removeChild(this.svg);
  916. }
  917. this.svg = makeSVGContainer(
  918. this.chartWrapper,
  919. 'chart',
  920. this.baseWidth,
  921. this.baseHeight
  922. );
  923. this.svgDefs = makeSVGDefs(this.svg);
  924. // I WISH !!!
  925. // this.svg = makeSVGGroup(
  926. // svgContainer,
  927. // 'flipped-coord-system',
  928. // `translate(0, ${this.baseHeight}) scale(1, -1)`
  929. // );
  930. this.drawArea = makeSVGGroup(
  931. this.svg,
  932. this.type + '-chart',
  933. `translate(${this.translateXLeft}, ${this.translateY})`
  934. );
  935. }
  936. renderLegend() {}
  937. setupNavigation(init=false) {
  938. if(this.isNavigable) return;
  939. this.makeOverlay();
  940. if(init) {
  941. this.bindOverlay();
  942. document.addEventListener('keydown', (e) => {
  943. if(isElementInViewport(this.chartWrapper)) {
  944. e = e || window.event;
  945. if (e.keyCode == '37') {
  946. this.onLeftArrow();
  947. } else if (e.keyCode == '39') {
  948. this.onRightArrow();
  949. } else if (e.keyCode == '38') {
  950. this.onUpArrow();
  951. } else if (e.keyCode == '40') {
  952. this.onDownArrow();
  953. } else if (e.keyCode == '13') {
  954. this.onEnterKey();
  955. }
  956. }
  957. });
  958. }
  959. }
  960. makeOverlay() {}
  961. bindOverlay() {}
  962. bind_units() {}
  963. onLeftArrow() {}
  964. onRightArrow() {}
  965. onUpArrow() {}
  966. onDownArrow() {}
  967. onEnterKey() {}
  968. // ????????????
  969. // Update the data here, then do relevant updates
  970. // and drawing in child classes by overriding
  971. // The Child chart will only know what a particular update means
  972. // and what components are affected,
  973. // BaseChart shouldn't be doing the animating
  974. getDataPoint(index = 0) {}
  975. setCurrentDataPoint(point) {}
  976. updateDataset(dataset, index) {}
  977. addDataset(dataset, index) {}
  978. removeDataset(index = 0) {}
  979. updateDatasets(datasets) {}
  980. updateDataPoint(dataPoint, index = 0) {}
  981. addDataPoint(dataPoint, index = 0) {}
  982. removeDataPoint(index = 0) {}
  983. getDifferentChart(type) {
  984. return getDifferentChart(type, this.type, this.rawChartArgs);
  985. }
  986. }
  987. const Y_AXIS_MARGIN = 60;
  988. const MIN_BAR_PERCENT_HEIGHT = 0.01;
  989. const DEFAULT_AXIS_CHART_TYPE = 'line';
  990. const AXIS_DATASET_CHART_TYPES = ['line', 'bar'];
  991. const BAR_CHART_SPACE_RATIO = 0.5;
  992. function dataPrep(data, type) {
  993. data.labels = data.labels || [];
  994. let datasetLength = data.labels.length;
  995. // Datasets
  996. let datasets = data.datasets;
  997. let zeroArray = new Array(datasetLength).fill(0);
  998. if(!datasets) {
  999. // default
  1000. datasets = [{
  1001. values: zeroArray
  1002. }];
  1003. }
  1004. datasets.map((d, i)=> {
  1005. // Set values
  1006. if(!d.values) {
  1007. d.values = zeroArray;
  1008. } else {
  1009. // Check for non values
  1010. let vals = d.values;
  1011. vals = vals.map(val => (!isNaN(val) ? val : 0));
  1012. // Trim or extend
  1013. if(vals.length > datasetLength) {
  1014. vals = vals.slice(0, datasetLength);
  1015. } else {
  1016. vals = fillArray(vals, datasetLength - vals.length, 0);
  1017. }
  1018. }
  1019. // Set labels
  1020. //
  1021. // Set type
  1022. if(!d.chartType ) {
  1023. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  1024. d.chartType = type;
  1025. }
  1026. });
  1027. // Markers
  1028. // Regions
  1029. // data.yRegions = data.yRegions || [];
  1030. if(data.yRegions) {
  1031. data.yRegions.map(d => {
  1032. if(d.end < d.start) {
  1033. [d.start, d.end] = [d.end, start];
  1034. }
  1035. });
  1036. }
  1037. return data;
  1038. }
  1039. function zeroDataPrep(realData) {
  1040. let datasetLength = realData.labels.length;
  1041. let zeroArray = new Array(datasetLength).fill(0);
  1042. let zeroData = {
  1043. labels: realData.labels.slice(0, -1),
  1044. datasets: realData.datasets.map(d => {
  1045. return {
  1046. name: '',
  1047. values: zeroArray.slice(0, -1),
  1048. chartType: d.chartType
  1049. }
  1050. }),
  1051. yRegions: [
  1052. {
  1053. start: 0,
  1054. end: 0,
  1055. label: ''
  1056. }
  1057. ],
  1058. yMarkers: [
  1059. {
  1060. value: 0,
  1061. label: ''
  1062. }
  1063. ]
  1064. };
  1065. return zeroData;
  1066. }
  1067. class ChartComponent$1 {
  1068. constructor({
  1069. layerClass = '',
  1070. layerTransform = '',
  1071. constants,
  1072. getData,
  1073. makeElements,
  1074. animateElements
  1075. }) {
  1076. this.layerTransform = layerTransform;
  1077. this.constants = constants;
  1078. this.makeElements = makeElements;
  1079. this.getData = getData;
  1080. this.animateElements = animateElements;
  1081. this.store = [];
  1082. this.layerClass = layerClass;
  1083. this.layerClass = typeof(this.layerClass) === 'function'
  1084. ? this.layerClass() : this.layerClass;
  1085. this.refresh();
  1086. }
  1087. refresh(data) {
  1088. this.data = data || this.getData();
  1089. }
  1090. setup(parent) {
  1091. this.layer = makeSVGGroup(parent, this.layerClass, this.layerTransform);
  1092. }
  1093. make() {
  1094. this.render(this.data);
  1095. this.oldData = this.data;
  1096. }
  1097. render(data) {
  1098. this.store = this.makeElements(data);
  1099. this.layer.textContent = '';
  1100. this.store.forEach(element => {
  1101. this.layer.appendChild(element);
  1102. });
  1103. }
  1104. update(animate = true) {
  1105. this.refresh();
  1106. let animateElements = [];
  1107. if(animate) {
  1108. animateElements = this.animateElements(this.data);
  1109. }
  1110. // TODO: Can we remove this?
  1111. setTimeout(() => {
  1112. this.make();
  1113. }, 1400);
  1114. return animateElements;
  1115. }
  1116. }
  1117. let componentConfigs = {
  1118. yAxis: {
  1119. layerClass: 'y axis',
  1120. makeElements(data) {
  1121. return data.positions.map((position, i) =>
  1122. yLine(position, data.labels[i], this.constants.width,
  1123. {mode: this.constants.mode, pos: this.constants.pos})
  1124. );
  1125. },
  1126. animateElements(newData) {
  1127. let newPos = newData.positions;
  1128. let newLabels = newData.labels;
  1129. let oldPos = this.oldData.positions;
  1130. let oldLabels = this.oldData.labels;
  1131. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1132. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1133. this.render({
  1134. positions: oldPos,
  1135. labels: newLabels
  1136. });
  1137. return this.store.map((line, i) => {
  1138. return translateHoriLine(
  1139. line, newPos[i], oldPos[i]
  1140. );
  1141. });
  1142. }
  1143. },
  1144. xAxis: {
  1145. layerClass: 'x axis',
  1146. makeElements(data) {
  1147. return data.positions.map((position, i) =>
  1148. xLine(position, data.labels[i], this.constants.height,
  1149. {mode: this.constants.mode, pos: this.constants.pos})
  1150. );
  1151. },
  1152. animateElements(newData) {
  1153. let newPos = newData.positions;
  1154. let newLabels = newData.labels;
  1155. let oldPos = this.oldData.positions;
  1156. let oldLabels = this.oldData.labels;
  1157. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1158. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1159. this.render({
  1160. positions: oldPos,
  1161. labels: newLabels
  1162. });
  1163. return this.store.map((line, i) => {
  1164. return translateVertLine(
  1165. line, newPos[i], oldPos[i]
  1166. );
  1167. });
  1168. }
  1169. },
  1170. yMarkers: {
  1171. layerClass: 'y-markers',
  1172. makeElements(data) {
  1173. return data.map(marker =>
  1174. yMarker(marker.position, marker.label, this.constants.width,
  1175. {pos:'right', mode: 'span', lineType: 'dashed'})
  1176. );
  1177. },
  1178. animateElements(newData) {
  1179. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1180. let newPos = newData.map(d => d.position);
  1181. let newLabels = newData.map(d => d.label);
  1182. let oldPos = this.oldData.map(d => d.position);
  1183. let oldLabels = this.oldData.map(d => d.label);
  1184. this.render(oldPos.map((pos, i) => {
  1185. return {
  1186. position: oldPos[i],
  1187. label: newLabels[i]
  1188. }
  1189. }));
  1190. return this.store.map((line, i) => {
  1191. return translateHoriLine(
  1192. line, newPos[i], oldPos[i]
  1193. );
  1194. });
  1195. }
  1196. },
  1197. yRegions: {
  1198. layerClass: 'y-regions',
  1199. makeElements(data) {
  1200. return data.map(region =>
  1201. yRegion(region.start, region.end, this.constants.width,
  1202. region.label)
  1203. );
  1204. },
  1205. animateElements(newData) {
  1206. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1207. let newPos = newData.map(d => d.end);
  1208. let newLabels = newData.map(d => d.label);
  1209. let newStarts = newData.map(d => d.start);
  1210. let oldPos = this.oldData.map(d => d.end);
  1211. let oldLabels = this.oldData.map(d => d.label);
  1212. let oldStarts = this.oldData.map(d => d.start);
  1213. this.render(oldPos.map((pos, i) => {
  1214. return {
  1215. start: oldStarts[i],
  1216. end: oldPos[i],
  1217. label: newLabels[i]
  1218. }
  1219. }));
  1220. let animateElements = [];
  1221. this.store.map((rectGroup, i) => {
  1222. animateElements = animateElements.concat(animateRegion(
  1223. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1224. ));
  1225. });
  1226. return animateElements;
  1227. }
  1228. },
  1229. barGraph: {
  1230. layerClass: function() { return 'dataset-units dataset-' + this.constants.index; },
  1231. makeElements(data) {
  1232. let c = this.constants;
  1233. return data.yPositions.map((y, j) => {
  1234. return datasetBar(
  1235. data.xPositions[j],
  1236. y,
  1237. data.barWidth,
  1238. c.color,
  1239. (c.valuesOverPoints ? (c.stacked ? data.cumulativeYs[j] : data.values[j]) : ''),
  1240. j,
  1241. y - (c.stacked ? data.cumulativeYPos[j] : y),
  1242. {
  1243. zeroLine: data.zeroLine,
  1244. barsWidth: data.barsWidth,
  1245. minHeight: c.minHeight
  1246. }
  1247. )
  1248. });
  1249. },
  1250. animateElements(newData) {
  1251. let c = this.constants;
  1252. let newXPos = newData.xPositions;
  1253. let newYPos = newData.yPositions;
  1254. let newCYPos = newData.cumulativeYPos;
  1255. let newValues = newData.values;
  1256. let newCYs = newData.cumulativeYs;
  1257. let oldXPos = this.oldData.xPositions;
  1258. let oldYPos = this.oldData.yPositions;
  1259. let oldCYPos = this.oldData.cumulativeYPos;
  1260. let oldValues = this.oldData.values;
  1261. let oldCYs = this.oldData.cumulativeYs;
  1262. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1263. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1264. [oldCYPos, newCYPos] = equilizeNoOfElements(oldCYPos, newCYPos);
  1265. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  1266. [oldCYs, newCYs] = equilizeNoOfElements(oldCYs, newCYs);
  1267. this.render({
  1268. xPositions: oldXPos,
  1269. yPositions: oldYPos,
  1270. cumulativeYPos: oldCYPos,
  1271. values: newValues,
  1272. cumulativeYs: newCYs,
  1273. zeroLine: this.oldData.zeroLine,
  1274. barsWidth: this.oldData.barsWidth,
  1275. barWidth: this.oldData.barWidth,
  1276. });
  1277. let animateElements = [];
  1278. this.store.map((bar, i) => {
  1279. animateElements = animateElements.concat(animateBar(
  1280. bar, newXPos[i], newYPos[i], newData.barWidth, c.index,
  1281. {zeroLine: newData.zeroLine}
  1282. ));
  1283. });
  1284. return animateElements;
  1285. }
  1286. },
  1287. lineGraph: {
  1288. }
  1289. };
  1290. function getComponent(name, constants, getData) {
  1291. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  1292. let config = componentConfigs[keys[0]];
  1293. Object.assign(config, {
  1294. constants: constants,
  1295. getData: getData
  1296. });
  1297. return new ChartComponent$1(config);
  1298. }
  1299. function normalize(x) {
  1300. // Calculates mantissa and exponent of a number
  1301. // Returns normalized number and exponent
  1302. // https://stackoverflow.com/q/9383593/6495043
  1303. if(x===0) {
  1304. return [0, 0];
  1305. }
  1306. if(isNaN(x)) {
  1307. return {mantissa: -6755399441055744, exponent: 972};
  1308. }
  1309. var sig = x > 0 ? 1 : -1;
  1310. if(!isFinite(x)) {
  1311. return {mantissa: sig * 4503599627370496, exponent: 972};
  1312. }
  1313. x = Math.abs(x);
  1314. var exp = Math.floor(Math.log10(x));
  1315. var man = x/Math.pow(10, exp);
  1316. return [sig * man, exp];
  1317. }
  1318. function getChartRangeIntervals(max, min=0) {
  1319. let upperBound = Math.ceil(max);
  1320. let lowerBound = Math.floor(min);
  1321. let range = upperBound - lowerBound;
  1322. let noOfParts = range;
  1323. let partSize = 1;
  1324. // To avoid too many partitions
  1325. if(range > 5) {
  1326. if(range % 2 !== 0) {
  1327. upperBound++;
  1328. // Recalc range
  1329. range = upperBound - lowerBound;
  1330. }
  1331. noOfParts = range/2;
  1332. partSize = 2;
  1333. }
  1334. // Special case: 1 and 2
  1335. if(range <= 2) {
  1336. noOfParts = 4;
  1337. partSize = range/noOfParts;
  1338. }
  1339. // Special case: 0
  1340. if(range === 0) {
  1341. noOfParts = 5;
  1342. partSize = 1;
  1343. }
  1344. let intervals = [];
  1345. for(var i = 0; i <= noOfParts; i++){
  1346. intervals.push(lowerBound + partSize * i);
  1347. }
  1348. return intervals;
  1349. }
  1350. function getChartIntervals(maxValue, minValue=0) {
  1351. let [normalMaxValue, exponent] = normalize(maxValue);
  1352. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  1353. // Allow only 7 significant digits
  1354. normalMaxValue = normalMaxValue.toFixed(6);
  1355. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  1356. intervals = intervals.map(value => value * Math.pow(10, exponent));
  1357. return intervals;
  1358. }
  1359. function calcChartIntervals(values, withMinimum=false) {
  1360. //*** Where the magic happens ***
  1361. // Calculates best-fit y intervals from given values
  1362. // and returns the interval array
  1363. let maxValue = Math.max(...values);
  1364. let minValue = Math.min(...values);
  1365. // Exponent to be used for pretty print
  1366. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  1367. function getPositiveFirstIntervals(maxValue, absMinValue) {
  1368. let intervals = getChartIntervals(maxValue);
  1369. let intervalSize = intervals[1] - intervals[0];
  1370. // Then unshift the negative values
  1371. let value = 0;
  1372. for(var i = 1; value < absMinValue; i++) {
  1373. value += intervalSize;
  1374. intervals.unshift((-1) * value);
  1375. }
  1376. return intervals;
  1377. }
  1378. // CASE I: Both non-negative
  1379. if(maxValue >= 0 && minValue >= 0) {
  1380. exponent = normalize(maxValue)[1];
  1381. if(!withMinimum) {
  1382. intervals = getChartIntervals(maxValue);
  1383. } else {
  1384. intervals = getChartIntervals(maxValue, minValue);
  1385. }
  1386. }
  1387. // CASE II: Only minValue negative
  1388. else if(maxValue > 0 && minValue < 0) {
  1389. // `withMinimum` irrelevant in this case,
  1390. // We'll be handling both sides of zero separately
  1391. // (both starting from zero)
  1392. // Because ceil() and floor() behave differently
  1393. // in those two regions
  1394. let absMinValue = Math.abs(minValue);
  1395. if(maxValue >= absMinValue) {
  1396. exponent = normalize(maxValue)[1];
  1397. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  1398. } else {
  1399. // Mirror: maxValue => absMinValue, then change sign
  1400. exponent = normalize(absMinValue)[1];
  1401. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  1402. intervals = posIntervals.map(d => d * (-1));
  1403. }
  1404. }
  1405. // CASE III: Both non-positive
  1406. else if(maxValue <= 0 && minValue <= 0) {
  1407. // Mirrored Case I:
  1408. // Work with positives, then reverse the sign and array
  1409. let pseudoMaxValue = Math.abs(minValue);
  1410. let pseudoMinValue = Math.abs(maxValue);
  1411. exponent = normalize(pseudoMaxValue)[1];
  1412. if(!withMinimum) {
  1413. intervals = getChartIntervals(pseudoMaxValue);
  1414. } else {
  1415. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  1416. }
  1417. intervals = intervals.reverse().map(d => d * (-1));
  1418. }
  1419. return intervals;
  1420. }
  1421. function getZeroIndex(yPts) {
  1422. let zeroIndex;
  1423. let interval = getIntervalSize(yPts);
  1424. if(yPts.indexOf(0) >= 0) {
  1425. // the range has a given zero
  1426. // zero-line on the chart
  1427. zeroIndex = yPts.indexOf(0);
  1428. } else if(yPts[0] > 0) {
  1429. // Minimum value is positive
  1430. // zero-line is off the chart: below
  1431. let min = yPts[0];
  1432. zeroIndex = (-1) * min / interval;
  1433. } else {
  1434. // Maximum value is negative
  1435. // zero-line is off the chart: above
  1436. let max = yPts[yPts.length - 1];
  1437. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  1438. }
  1439. return zeroIndex;
  1440. }
  1441. function getIntervalSize(orderedArray) {
  1442. return orderedArray[1] - orderedArray[0];
  1443. }
  1444. function getValueRange(orderedArray) {
  1445. return orderedArray[orderedArray.length-1] - orderedArray[0];
  1446. }
  1447. function scale(val, yAxis) {
  1448. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier)
  1449. }
  1450. function calcDistribution(values, distributionSize) {
  1451. // Assume non-negative values,
  1452. // implying distribution minimum at zero
  1453. let dataMaxValue = Math.max(...values);
  1454. let distributionStep = 1 / (distributionSize - 1);
  1455. let distribution = [];
  1456. for(var i = 0; i < distributionSize; i++) {
  1457. let checkpoint = dataMaxValue * (distributionStep * i);
  1458. distribution.push(checkpoint);
  1459. }
  1460. return distribution;
  1461. }
  1462. function getMaxCheckpoint(value, distribution) {
  1463. return distribution.filter(d => d < value).length;
  1464. }
  1465. class AxisChart extends BaseChart {
  1466. constructor(args) {
  1467. super(args);
  1468. this.isSeries = args.isSeries;
  1469. this.valuesOverPoints = args.valuesOverPoints;
  1470. this.formatTooltipY = args.formatTooltipY;
  1471. this.formatTooltipX = args.formatTooltipX;
  1472. this.barOptions = args.barOptions || {};
  1473. this.lineOptions = args.lineOptions || {};
  1474. this.type = args.type || 'line';
  1475. this.xAxisMode = args.xAxisMode || 'span';
  1476. this.yAxisMode = args.yAxisMode || 'span';
  1477. this.zeroLine = this.height;
  1478. // this.setTrivialState();
  1479. this.setup();
  1480. }
  1481. configure(args) {3;
  1482. super.configure();
  1483. // TODO: set in options and use
  1484. this.config.xAxisMode = args.xAxisMode;
  1485. this.config.yAxisMode = args.yAxisMode;
  1486. }
  1487. setMargins() {
  1488. super.setMargins();
  1489. this.translateXLeft = Y_AXIS_MARGIN;
  1490. this.translateXRight = Y_AXIS_MARGIN;
  1491. }
  1492. prepareData(data=this.data) {
  1493. return dataPrep(data, this.type);
  1494. }
  1495. prepareFirstData(data=this.data) {
  1496. return zeroDataPrep(data);
  1497. }
  1498. calc() {
  1499. this.calcXPositions();
  1500. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  1501. }
  1502. calcXPositions(s=this.state) {
  1503. let labels = this.data.labels;
  1504. s.datasetLength = labels.length;
  1505. s.unitWidth = this.width/(s.datasetLength);
  1506. // Default, as per bar, and mixed. Only line will be a special case
  1507. s.xOffset = s.unitWidth/2;
  1508. s.xAxis = {
  1509. labels: labels,
  1510. positions: labels.map((d, i) =>
  1511. floatTwo(s.xOffset + i * s.unitWidth)
  1512. )
  1513. };
  1514. }
  1515. calcYAxisParameters(dataValues, withMinimum = 'false') {
  1516. const yPts = calcChartIntervals(dataValues, withMinimum);
  1517. const scaleMultiplier = this.height / getValueRange(yPts);
  1518. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  1519. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  1520. this.state.yAxis = {
  1521. labels: yPts,
  1522. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  1523. scaleMultiplier: scaleMultiplier,
  1524. zeroLine: zeroLine,
  1525. };
  1526. this.calcYUnits();
  1527. this.calcYExtremes();
  1528. this.calcYRegions();
  1529. }
  1530. calcYUnits() {
  1531. let s = this.state;
  1532. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  1533. s.datasets = this.data.datasets.map((d, i) => {
  1534. let values = d.values;
  1535. let cumulativeYs = d.cumulativeYs || [];
  1536. return {
  1537. name: d.name,
  1538. index: i,
  1539. chartType: d.chartType,
  1540. values: values,
  1541. yPositions: scaleAll(values),
  1542. cumulativeYs: cumulativeYs,
  1543. cumulativeYPos: scaleAll(cumulativeYs),
  1544. };
  1545. });
  1546. }
  1547. calcYExtremes() {
  1548. let s = this.state;
  1549. if(this.barOptions && this.barOptions.stacked) {
  1550. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  1551. return;
  1552. }
  1553. s.yExtremes = new Array(s.datasetLength).fill(9999);
  1554. s.datasets.map((d, i) => {
  1555. d.yPositions.map((pos, j) => {
  1556. if(pos < s.yExtremes[j]) {
  1557. s.yExtremes[j] = pos;
  1558. }
  1559. });
  1560. });
  1561. }
  1562. calcYRegions() {
  1563. let s = this.state;
  1564. if(this.data.yMarkers) {
  1565. this.state.yMarkers = this.data.yMarkers.map(d => {
  1566. d.position = scale(d.value, s.yAxis);
  1567. d.label += ': ' + d.value;
  1568. return d;
  1569. });
  1570. }
  1571. if(this.data.yRegions) {
  1572. this.state.yRegions = this.data.yRegions.map(d => {
  1573. d.start = scale(d.start, s.yAxis);
  1574. d.end = scale(d.end, s.yAxis);
  1575. return d;
  1576. });
  1577. }
  1578. }
  1579. getAllYValues() {
  1580. // TODO: yMarkers, regions, sums, every Y value ever
  1581. let key = 'values';
  1582. if(this.barOptions && this.barOptions.stacked) {
  1583. key = 'cumulativeYs';
  1584. let cumulative = new Array(this.state.datasetLength).fill(0);
  1585. this.data.datasets.map((d, i) => {
  1586. let values = this.data.datasets[i].values;
  1587. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  1588. });
  1589. }
  1590. return [].concat(...this.data.datasets.map(d => d[key]));
  1591. }
  1592. initComponents() {
  1593. this.componentConfigs = [
  1594. [
  1595. 'yAxis',
  1596. {
  1597. mode: this.yAxisMode,
  1598. width: this.width,
  1599. // pos: 'right'
  1600. }
  1601. ],
  1602. [
  1603. 'xAxis',
  1604. {
  1605. mode: this.xAxisMode,
  1606. height: this.height,
  1607. // pos: 'right'
  1608. }
  1609. ],
  1610. [
  1611. 'yRegions',
  1612. {
  1613. width: this.width,
  1614. pos: 'right'
  1615. }
  1616. ],
  1617. ];
  1618. this.componentConfigs.map(args => {
  1619. args.push(
  1620. function() {
  1621. return this.state[args[0]];
  1622. }.bind(this)
  1623. );
  1624. });
  1625. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  1626. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  1627. // console.log('barDatasets', barDatasets, this.state.datasets);
  1628. // Bars
  1629. let barsConfigs = barDatasets.map(d => {
  1630. let index = d.index;
  1631. return [
  1632. 'barGraph' + '-' + d.index,
  1633. {
  1634. index: index,
  1635. color: this.colors[index],
  1636. // same for all datasets
  1637. valuesOverPoints: this.valuesOverPoints,
  1638. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  1639. },
  1640. function() {
  1641. let s = this.state;
  1642. let d = s.datasets[index];
  1643. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  1644. let barsWidth = s.unitWidth * (1 - spaceRatio);
  1645. let barWidth = barsWidth/(this.barOptions.stacked ? 1 : barDatasets.length);
  1646. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2 + barWidth * index);
  1647. return {
  1648. xPositions: xPositions,
  1649. yPositions: d.yPositions,
  1650. cumulativeYPos: d.cumulativeYPos,
  1651. values: d.values,
  1652. cumulativeYs: d.cumulativeYs,
  1653. zeroLine: s.yAxis.zeroLine,
  1654. barsWidth: barsWidth,
  1655. barWidth: barWidth,
  1656. };
  1657. }.bind(this)
  1658. ];
  1659. });
  1660. let markerConfigs = [
  1661. [
  1662. 'yMarkers',
  1663. {
  1664. width: this.width,
  1665. pos: 'right'
  1666. }
  1667. ]
  1668. ];
  1669. markerConfigs.map(args => {
  1670. args.push(
  1671. function() {
  1672. return this.state[args[0]];
  1673. }.bind(this)
  1674. );
  1675. });
  1676. this.componentConfigs = this.componentConfigs.concat(barsConfigs, markerConfigs);
  1677. }
  1678. setupComponents() {
  1679. let optionals = ['yMarkers', 'yRegions'];
  1680. this.components = new Map(this.componentConfigs
  1681. .filter(args => !optionals.includes(args[0]) || this.state[args[0]] || args[0] === 'barGraph')
  1682. .map(args => {
  1683. return [args[0], getComponent(...args)];
  1684. }));
  1685. }
  1686. getChartComponents() {
  1687. let dataUnitsComponents = [];
  1688. // this.state is not defined at this stage
  1689. this.data.datasets.forEach((d, index) => {
  1690. if(d.chartType === 'line') {
  1691. dataUnitsComponents.push(this.getPathComponent(d, index));
  1692. }
  1693. let renderer = this.unitRenderers[d.chartType];
  1694. dataUnitsComponents.push(this.getDataUnitComponent(
  1695. index, renderer
  1696. ));
  1697. });
  1698. return dataUnitsComponents;
  1699. }
  1700. getDataUnitComponent(index, unitRenderer) {
  1701. return new ChartComponent({
  1702. layerClass: 'dataset-units dataset-' + index,
  1703. makeElements: () => {
  1704. // yPositions, xPostions, color, valuesOverPoints,
  1705. let d = this.data.datasets[index];
  1706. return d.positions.map((y, j) => {
  1707. return unitRenderer.draw(
  1708. this.state.xAxis.positions[j],
  1709. y,
  1710. this.colors[index],
  1711. (this.valuesOverPoints ? (this.barOptions &&
  1712. this.barOptions.stacked ? d.cumulativeYs[j] : d.values[j]) : ''),
  1713. j,
  1714. y - (d.cumulativePositions ? d.cumulativePositions[j] : y)
  1715. );
  1716. });
  1717. },
  1718. postMake: function() {
  1719. let translate_layer = () => {
  1720. this.layer.setAttribute('transform', `translate(${unitRenderer.consts.width * index}, 0)`);
  1721. };
  1722. // let d = this.data.datasets[index];
  1723. if(this.meta.type === 'bar' && (!this.meta.barOptions
  1724. || !this.meta.barOptions.stacked)) {
  1725. translate_layer();
  1726. }
  1727. },
  1728. animate: (svgUnits) => {
  1729. // have been updated in axis render;
  1730. let newX = this.state.xAxis.positions;
  1731. let newY = this.data.datasets[index].positions;
  1732. let lastUnit = svgUnits[svgUnits.length - 1];
  1733. let parentNode = lastUnit.parentNode;
  1734. if(this.oldState.xExtra > 0) {
  1735. for(var i = 0; i<this.oldState.xExtra; i++) {
  1736. let unit = lastUnit.cloneNode(true);
  1737. parentNode.appendChild(unit);
  1738. svgUnits.push(unit);
  1739. }
  1740. }
  1741. svgUnits.map((unit, i) => {
  1742. if(newX[i] === undefined || newY[i] === undefined) return;
  1743. this.elementsToAnimate.push(unitRenderer.animate(
  1744. unit, // unit, with info to replace where it came from in the data
  1745. newX[i],
  1746. newY[i],
  1747. index,
  1748. this.data.datasets.length
  1749. ));
  1750. });
  1751. }
  1752. });
  1753. }
  1754. getPathComponent(d, index) {
  1755. return new ChartComponent({
  1756. layerClass: 'path dataset-path',
  1757. setData: () => {},
  1758. makeElements: () => {
  1759. let d = this.data.datasets[index];
  1760. let color = this.colors[index];
  1761. return getPaths(
  1762. d.positions,
  1763. this.state.xAxis.positions,
  1764. color,
  1765. this.config.heatline,
  1766. this.config.regionFill
  1767. );
  1768. },
  1769. animate: (paths) => {
  1770. let newX = this.state.xAxis.positions;
  1771. let newY = this.data.datasets[index].positions;
  1772. let oldX = this.oldState.xAxis.positions;
  1773. let oldY = this.oldState.datasets[index].positions;
  1774. let parentNode = paths[0].parentNode;
  1775. [oldX, newX] = equilizeNoOfElements(oldX, newX);
  1776. [oldY, newY] = equilizeNoOfElements(oldY, newY);
  1777. if(this.oldState.xExtra > 0) {
  1778. paths = getPaths(
  1779. oldY, oldX, this.colors[index],
  1780. this.config.heatline,
  1781. this.config.regionFill
  1782. );
  1783. parentNode.textContent = '';
  1784. paths.map(path => parentNode.appendChild(path));
  1785. }
  1786. const newPointsList = newY.map((y, i) => (newX[i] + ',' + y));
  1787. this.elementsToAnimate = this.elementsToAnimate
  1788. .concat(this.renderer.animatepath(paths, newPointsList.join("L")));
  1789. }
  1790. });
  1791. }
  1792. bindTooltip() {
  1793. // TODO: could be in tooltip itself, as it is a given functionality for its parent
  1794. this.chartWrapper.addEventListener('mousemove', (e) => {
  1795. let o = getOffset(this.chartWrapper);
  1796. let relX = e.pageX - o.left - this.translateXLeft;
  1797. let relY = e.pageY - o.top - this.translateY;
  1798. if(relY < this.height + this.translateY * 2) {
  1799. this.mapTooltipXPosition(relX);
  1800. } else {
  1801. this.tip.hide_tip();
  1802. }
  1803. });
  1804. }
  1805. mapTooltipXPosition(relX) {
  1806. let s = this.state;
  1807. if(!s.yExtremes) return;
  1808. let titles = s.xAxis.labels;
  1809. if(this.formatTooltipX && this.formatTooltipX(titles[0])) {
  1810. titles = titles.map(d=>this.formatTooltipX(d));
  1811. }
  1812. let formatY = this.formatTooltipY && this.formatTooltipY(this.y[0].values[0]);
  1813. for(var i=s.datasetLength - 1; i >= 0 ; i--) {
  1814. let xVal = s.xAxis.positions[i];
  1815. // let delta = i === 0 ? s.unitWidth : xVal - s.xAxis.positions[i-1];
  1816. if(relX > xVal - s.unitWidth/2) {
  1817. let x = xVal + this.translateXLeft;
  1818. let y = s.yExtremes[i] + this.translateY;
  1819. let values = this.data.datasets.map((set, j) => {
  1820. return {
  1821. title: set.title,
  1822. value: formatY ? this.formatTooltipY(set.values[i]) : set.values[i],
  1823. color: this.colors[j],
  1824. };
  1825. });
  1826. this.tip.set_values(x, y, titles[i], '', values);
  1827. this.tip.show_tip();
  1828. break;
  1829. }
  1830. }
  1831. }
  1832. getDataPoint(index=this.current_index) {
  1833. // check for length
  1834. let data_point = {
  1835. index: index
  1836. };
  1837. let y = this.y[0];
  1838. ['svg_units', 'yUnitPositions', 'values'].map(key => {
  1839. let data_key = key.slice(0, key.length-1);
  1840. data_point[data_key] = y[key][index];
  1841. });
  1842. data_point.label = this.xAxis.labels[index];
  1843. return data_point;
  1844. }
  1845. setCurrentDataPoint(index) {
  1846. index = parseInt(index);
  1847. if(index < 0) index = 0;
  1848. if(index >= this.xAxis.labels.length) index = this.xAxis.labels.length - 1;
  1849. if(index === this.current_index) return;
  1850. this.current_index = index;
  1851. $.fire(this.parent, "data-select", this.getDataPoint());
  1852. }
  1853. // API
  1854. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  1855. super.addDataPoint(label, datasetValues, index);
  1856. // console.log(label, datasetValues, this.data.labels);
  1857. this.data.labels.splice(index, 0, label);
  1858. this.data.datasets.map((d, i) => {
  1859. d.values.splice(index, 0, datasetValues[i]);
  1860. });
  1861. // console.log(this.data);
  1862. this.update(this.data);
  1863. }
  1864. removeDataPoint(index = this.state.datasetLength-1) {
  1865. super.removeDataPoint(index);
  1866. this.data.labels.splice(index, 1);
  1867. this.data.datasets.map(d => {
  1868. d.values.splice(index, 1);
  1869. });
  1870. this.update(this.data);
  1871. }
  1872. // updateData() {
  1873. // // animate if same no. of datasets,
  1874. // // else return new chart
  1875. // //
  1876. // }
  1877. }
  1878. // keep a binding at the end of chart
  1879. class LineChart extends AxisChart {
  1880. constructor(args) {
  1881. super(args);
  1882. this.type = 'line';
  1883. if(Object.getPrototypeOf(this) !== LineChart.prototype) {
  1884. return;
  1885. }
  1886. this.setup();
  1887. }
  1888. configure(args) {
  1889. super.configure(args);
  1890. this.config.xAxisMode = args.xAxisMode || 'span';
  1891. this.config.yAxisMode = args.yAxisMode || 'span';
  1892. this.config.dotRadius = args.dotRadius || 4;
  1893. this.config.heatline = args.heatline || 0;
  1894. this.config.regionFill = args.regionFill || 0;
  1895. this.config.showDots = args.showDots || 1;
  1896. }
  1897. configUnits() {
  1898. this.unitArgs = {
  1899. type: 'dot',
  1900. args: { radius: this.config.dotRadius }
  1901. };
  1902. }
  1903. // temp commented
  1904. setUnitWidthAndXOffset() {
  1905. this.state.unitWidth = this.width/(this.state.datasetLength - 1);
  1906. this.state.xOffset = 0;
  1907. }
  1908. }
  1909. class ScatterChart extends LineChart {
  1910. constructor(args) {
  1911. super(args);
  1912. this.type = 'scatter';
  1913. if(!args.dotRadius) {
  1914. this.dotRadius = 8;
  1915. } else {
  1916. this.dotRadius = args.dotRadius;
  1917. }
  1918. this.setup();
  1919. }
  1920. setup_values() {
  1921. super.setup_values();
  1922. this.unit_args = {
  1923. type: 'dot',
  1924. args: { radius: this.dotRadius }
  1925. };
  1926. }
  1927. make_paths() {}
  1928. make_path() {}
  1929. }
  1930. class MultiAxisChart extends AxisChart {
  1931. constructor(args) {
  1932. super(args);
  1933. // this.unitType = args.unitType || 'line';
  1934. // this.setup();
  1935. }
  1936. preSetup() {
  1937. this.type = 'multiaxis';
  1938. }
  1939. setMargins() {
  1940. super.setMargins();
  1941. let noOfLeftAxes = this.data.datasets.filter(d => d.axisPosition === 'left').length;
  1942. this.translateXLeft = (noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
  1943. this.translateXRight = (this.data.datasets.length - noOfLeftAxes) * Y_AXIS_MARGIN || Y_AXIS_MARGIN;
  1944. }
  1945. prepareYAxis() { }
  1946. prepareData(data) {
  1947. super.prepareData(data);
  1948. let sets = this.state.datasets;
  1949. // let axesLeft = sets.filter(d => d.axisPosition === 'left');
  1950. // let axesRight = sets.filter(d => d.axisPosition === 'right');
  1951. // let axesNone = sets.filter(d => !d.axisPosition ||
  1952. // !['left', 'right'].includes(d.axisPosition));
  1953. let leftCount = 0, rightCount = 0;
  1954. sets.forEach((d, i) => {
  1955. d.yAxis = {
  1956. position: d.axisPosition,
  1957. index: d.axisPosition === 'left' ? leftCount++ : rightCount++
  1958. };
  1959. });
  1960. }
  1961. configure(args) {
  1962. super.configure(args);
  1963. this.config.xAxisMode = args.xAxisMode || 'tick';
  1964. this.config.yAxisMode = args.yAxisMode || 'span';
  1965. }
  1966. // setUnitWidthAndXOffset() {
  1967. // this.state.unitWidth = this.width/(this.state.datasetLength);
  1968. // this.state.xOffset = this.state.unitWidth/2;
  1969. // }
  1970. configUnits() {
  1971. this.unitArgs = {
  1972. type: 'bar',
  1973. args: {
  1974. spaceWidth: this.state.unitWidth/2,
  1975. }
  1976. };
  1977. }
  1978. setYAxis() {
  1979. this.state.datasets.map(d => {
  1980. this.calcYAxisParameters(d.yAxis, d.values, this.unitType === 'line');
  1981. });
  1982. }
  1983. calcYUnits() {
  1984. this.state.datasets.map(d => {
  1985. d.positions = d.values.map(val => floatTwo(d.yAxis.zeroLine - val * d.yAxis.scaleMultiplier));
  1986. });
  1987. }
  1988. // TODO: function doesn't exist, handle with components
  1989. renderConstants() {
  1990. this.state.datasets.map(d => {
  1991. let guidePos = d.yAxis.position === 'left'
  1992. ? -1 * d.yAxis.index * Y_AXIS_MARGIN
  1993. : this.width + d.yAxis.index * Y_AXIS_MARGIN;
  1994. this.renderer.xLine(guidePos, '', {
  1995. pos:'top',
  1996. mode: 'span',
  1997. stroke: this.colors[i],
  1998. className: 'y-axis-guide'
  1999. });
  2000. });
  2001. }
  2002. getYAxesComponents() {
  2003. return this.data.datasets.map((e, i) => {
  2004. return new ChartComponent({
  2005. layerClass: 'y axis y-axis-' + i,
  2006. make: () => {
  2007. let yAxis = this.state.datasets[i].yAxis;
  2008. this.renderer.setZeroline(yAxis.zeroline);
  2009. let options = {
  2010. pos: yAxis.position,
  2011. mode: 'tick',
  2012. offset: yAxis.index * Y_AXIS_MARGIN,
  2013. stroke: this.colors[i]
  2014. };
  2015. return yAxis.positions.map((position, j) =>
  2016. this.renderer.yLine(position, yAxis.labels[j], options)
  2017. );
  2018. },
  2019. animate: () => {}
  2020. });
  2021. });
  2022. }
  2023. // TODO remove renderer zeroline from above and below
  2024. getChartComponents() {
  2025. return this.data.datasets.map((d, index) => {
  2026. return new ChartComponent({
  2027. layerClass: 'dataset-units dataset-' + index,
  2028. make: () => {
  2029. let d = this.state.datasets[index];
  2030. let unitType = this.unitArgs;
  2031. // the only difference, should be tied to datasets or default
  2032. this.renderer.setZeroline(d.yAxis.zeroLine);
  2033. return d.positions.map((y, j) => {
  2034. return this.renderer[unitType.type](
  2035. this.state.xAxisPositions[j],
  2036. y,
  2037. unitType.args,
  2038. this.colors[index],
  2039. j,
  2040. index,
  2041. this.state.datasetLength
  2042. );
  2043. });
  2044. },
  2045. animate: (svgUnits) => {
  2046. let d = this.state.datasets[index];
  2047. let unitType = this.unitArgs.type;
  2048. // have been updated in axis render;
  2049. let newX = this.state.xAxisPositions;
  2050. let newY = this.state.datasets[index].positions;
  2051. let lastUnit = svgUnits[svgUnits.length - 1];
  2052. let parentNode = lastUnit.parentNode;
  2053. if(this.oldState.xExtra > 0) {
  2054. for(var i = 0; i<this.oldState.xExtra; i++) {
  2055. let unit = lastUnit.cloneNode(true);
  2056. parentNode.appendChild(unit);
  2057. svgUnits.push(unit);
  2058. }
  2059. }
  2060. this.renderer.setZeroline(d.yAxis.zeroLine);
  2061. svgUnits.map((unit, i) => {
  2062. if(newX[i] === undefined || newY[i] === undefined) return;
  2063. this.elementsToAnimate.push(this.renderer['animate' + unitType](
  2064. unit, // unit, with info to replace where it came from in the data
  2065. newX[i],
  2066. newY[i],
  2067. index,
  2068. this.state.noOfDatasets
  2069. ));
  2070. });
  2071. }
  2072. });
  2073. });
  2074. }
  2075. }
  2076. class PercentageChart extends BaseChart {
  2077. constructor(args) {
  2078. super(args);
  2079. this.type = 'percentage';
  2080. this.max_slices = 10;
  2081. this.max_legend_points = 6;
  2082. this.setup();
  2083. }
  2084. makeChartArea() {
  2085. this.chartWrapper.className += ' ' + 'graph-focus-margin';
  2086. this.chartWrapper.style.marginTop = '45px';
  2087. this.statsWrapper.className += ' ' + 'graph-focus-margin';
  2088. this.statsWrapper.style.marginBottom = '30px';
  2089. this.statsWrapper.style.paddingTop = '0px';
  2090. this.chartDiv = $$1.create('div', {
  2091. className: 'div',
  2092. inside: this.chartWrapper
  2093. });
  2094. this.chart = $$1.create('div', {
  2095. className: 'progress-chart',
  2096. inside: this.chartDiv
  2097. });
  2098. }
  2099. setupLayers() {
  2100. this.percentageBar = $$1.create('div', {
  2101. className: 'progress',
  2102. inside: this.chart
  2103. });
  2104. }
  2105. setup_values() {
  2106. this.slice_totals = [];
  2107. let all_totals = this.data.labels.map((d, i) => {
  2108. let total = 0;
  2109. this.data.datasets.map(e => {
  2110. total += e.values[i];
  2111. });
  2112. return [total, d];
  2113. }).filter(d => { return d[0] > 0; }); // keep only positive results
  2114. let totals = all_totals;
  2115. if(all_totals.length > this.max_slices) {
  2116. all_totals.sort((a, b) => { return b[0] - a[0]; });
  2117. totals = all_totals.slice(0, this.max_slices-1);
  2118. let others = all_totals.slice(this.max_slices-1);
  2119. let sum_of_others = 0;
  2120. others.map(d => {sum_of_others += d[0];});
  2121. totals.push([sum_of_others, 'Rest']);
  2122. this.colors[this.max_slices-1] = 'grey';
  2123. }
  2124. this.labels = [];
  2125. totals.map(d => {
  2126. this.slice_totals.push(d[0]);
  2127. this.labels.push(d[1]);
  2128. });
  2129. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  2130. }
  2131. renderComponents() {
  2132. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  2133. this.slices = [];
  2134. this.slice_totals.map((total, i) => {
  2135. let slice = $$1.create('div', {
  2136. className: `progress-bar`,
  2137. inside: this.percentageBar,
  2138. styles: {
  2139. background: this.colors[i],
  2140. width: total*100/this.grand_total + "%"
  2141. }
  2142. });
  2143. this.slices.push(slice);
  2144. });
  2145. }
  2146. calc() {}
  2147. bindTooltip() {
  2148. this.slices.map((slice, i) => {
  2149. slice.addEventListener('mouseenter', () => {
  2150. let g_off = getOffset(this.chartWrapper), p_off = getOffset(slice);
  2151. let x = p_off.left - g_off.left + slice.offsetWidth/2;
  2152. let y = p_off.top - g_off.top - 6;
  2153. let title = (this.formatted_labels && this.formatted_labels.length>0
  2154. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  2155. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  2156. this.tip.set_values(x, y, title, percent + "%");
  2157. this.tip.show_tip();
  2158. });
  2159. });
  2160. }
  2161. renderLegend() {
  2162. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  2163. ? this.formatted_labels : this.labels;
  2164. this.legend_totals.map((d, i) => {
  2165. if(d) {
  2166. let stats = $$1.create('div', {
  2167. className: 'stats',
  2168. inside: this.statsWrapper
  2169. });
  2170. stats.innerHTML = `<span class="indicator">
  2171. <i style="background: ${this.colors[i]}"></i>
  2172. <span class="text-muted">${x_values[i]}:</span>
  2173. ${d}
  2174. </span>`;
  2175. }
  2176. });
  2177. }
  2178. }
  2179. const ANGLE_RATIO = Math.PI / 180;
  2180. const FULL_ANGLE = 360;
  2181. class PieChart extends BaseChart {
  2182. constructor(args) {
  2183. super(args);
  2184. this.type = 'pie';
  2185. this.elements_to_animate = null;
  2186. this.hoverRadio = args.hoverRadio || 0.1;
  2187. this.max_slices = 10;
  2188. this.max_legend_points = 6;
  2189. this.isAnimate = false;
  2190. this.startAngle = args.startAngle || 0;
  2191. this.clockWise = args.clockWise || false;
  2192. this.mouseMove = this.mouseMove.bind(this);
  2193. this.mouseLeave = this.mouseLeave.bind(this);
  2194. this.setup();
  2195. }
  2196. setup_values() {
  2197. this.centerX = this.width / 2;
  2198. this.centerY = this.height / 2;
  2199. this.radius = (this.height > this.width ? this.centerX : this.centerY);
  2200. this.slice_totals = [];
  2201. let all_totals = this.data.labels.map((d, i) => {
  2202. let total = 0;
  2203. this.data.datasets.map(e => {
  2204. total += e.values[i];
  2205. });
  2206. return [total, d];
  2207. }).filter(d => { return d[0] > 0; }); // keep only positive results
  2208. let totals = all_totals;
  2209. if(all_totals.length > this.max_slices) {
  2210. all_totals.sort((a, b) => { return b[0] - a[0]; });
  2211. totals = all_totals.slice(0, this.max_slices-1);
  2212. let others = all_totals.slice(this.max_slices-1);
  2213. let sum_of_others = 0;
  2214. others.map(d => {sum_of_others += d[0];});
  2215. totals.push([sum_of_others, 'Rest']);
  2216. this.colors[this.max_slices-1] = 'grey';
  2217. }
  2218. this.labels = [];
  2219. totals.map(d => {
  2220. this.slice_totals.push(d[0]);
  2221. this.labels.push(d[1]);
  2222. });
  2223. this.legend_totals = this.slice_totals.slice(0, this.max_legend_points);
  2224. }
  2225. static getPositionByAngle(angle,radius){
  2226. return {
  2227. x:Math.sin(angle * ANGLE_RATIO) * radius,
  2228. y:Math.cos(angle * ANGLE_RATIO) * radius,
  2229. };
  2230. }
  2231. makeArcPath(startPosition,endPosition){
  2232. const{centerX,centerY,radius,clockWise} = this;
  2233. return `M${centerX} ${centerY} L${centerX+startPosition.x} ${centerY+startPosition.y} A ${radius} ${radius} 0 0 ${clockWise ? 1 : 0} ${centerX+endPosition.x} ${centerY+endPosition.y} z`;
  2234. }
  2235. renderComponents(init){
  2236. const{radius,clockWise} = this;
  2237. this.grand_total = this.slice_totals.reduce((a, b) => a + b, 0);
  2238. const prevSlicesProperties = this.slicesProperties || [];
  2239. this.slices = [];
  2240. this.elements_to_animate = [];
  2241. this.slicesProperties = [];
  2242. let curAngle = 180 - this.startAngle;
  2243. this.slice_totals.map((total, i) => {
  2244. const startAngle = curAngle;
  2245. const originDiffAngle = (total / this.grand_total) * FULL_ANGLE;
  2246. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  2247. const endAngle = curAngle = curAngle + diffAngle;
  2248. const startPosition = PieChart.getPositionByAngle(startAngle,radius);
  2249. const endPosition = PieChart.getPositionByAngle(endAngle,radius);
  2250. const prevProperty = init && prevSlicesProperties[i];
  2251. let curStart,curEnd;
  2252. if(init){
  2253. curStart = prevProperty?prevProperty.startPosition : startPosition;
  2254. curEnd = prevProperty? prevProperty.endPosition : startPosition;
  2255. }else{
  2256. curStart = startPosition;
  2257. curEnd = endPosition;
  2258. }
  2259. const curPath = this.makeArcPath(curStart,curEnd);
  2260. let slice = makePath(curPath, 'pie-path', 'none', this.colors[i]);
  2261. slice.style.transition = 'transform .3s;';
  2262. this.drawArea.appendChild(slice);
  2263. this.slices.push(slice);
  2264. this.slicesProperties.push({
  2265. startPosition,
  2266. endPosition,
  2267. value: total,
  2268. total: this.grand_total,
  2269. startAngle,
  2270. endAngle,
  2271. angle:diffAngle
  2272. });
  2273. if(init){
  2274. this.elements_to_animate.push([{unit: slice, array: this.slices, index: this.slices.length - 1},
  2275. {d:this.makeArcPath(startPosition,endPosition)},
  2276. 650, "easein",null,{
  2277. d:curPath
  2278. }]);
  2279. }
  2280. });
  2281. if(init){
  2282. runSMILAnimation(this.chartWrapper, this.svg, this.elements_to_animate);
  2283. }
  2284. }
  2285. calTranslateByAngle(property){
  2286. const{radius,hoverRadio} = this;
  2287. const position = PieChart.getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  2288. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  2289. }
  2290. hoverSlice(path,i,flag,e){
  2291. if(!path) return;
  2292. const color = this.colors[i];
  2293. if(flag){
  2294. transform(path,this.calTranslateByAngle(this.slicesProperties[i]));
  2295. path.style.fill = lightenDarkenColor(color,50);
  2296. let g_off = getOffset(this.svg);
  2297. let x = e.pageX - g_off.left + 10;
  2298. let y = e.pageY - g_off.top - 10;
  2299. let title = (this.formatted_labels && this.formatted_labels.length>0
  2300. ? this.formatted_labels[i] : this.labels[i]) + ': ';
  2301. let percent = (this.slice_totals[i]*100/this.grand_total).toFixed(1);
  2302. this.tip.set_values(x, y, title, percent + "%");
  2303. this.tip.show_tip();
  2304. }else{
  2305. transform(path,'translate3d(0,0,0)');
  2306. this.tip.hide_tip();
  2307. path.style.fill = color;
  2308. }
  2309. }
  2310. mouseMove(e){
  2311. const target = e.target;
  2312. let prevIndex = this.curActiveSliceIndex;
  2313. let prevAcitve = this.curActiveSlice;
  2314. for(let i = 0; i < this.slices.length; i++){
  2315. if(target === this.slices[i]){
  2316. this.hoverSlice(prevAcitve,prevIndex,false);
  2317. this.curActiveSlice = target;
  2318. this.curActiveSliceIndex = i;
  2319. this.hoverSlice(target,i,true,e);
  2320. break;
  2321. }
  2322. }
  2323. }
  2324. mouseLeave(){
  2325. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  2326. }
  2327. bindTooltip() {
  2328. this.drawArea.addEventListener('mousemove',this.mouseMove);
  2329. this.drawArea.addEventListener('mouseleave',this.mouseLeave);
  2330. }
  2331. renderLegend() {
  2332. let x_values = this.formatted_labels && this.formatted_labels.length > 0
  2333. ? this.formatted_labels : this.labels;
  2334. this.legend_totals.map((d, i) => {
  2335. const color = this.colors[i];
  2336. if(d) {
  2337. let stats = $$1.create('div', {
  2338. className: 'stats',
  2339. inside: this.statsWrapper
  2340. });
  2341. stats.innerHTML = `<span class="indicator">
  2342. <i style="background-color:${color};"></i>
  2343. <span class="text-muted">${x_values[i]}:</span>
  2344. ${d}
  2345. </span>`;
  2346. }
  2347. });
  2348. }
  2349. }
  2350. // Playing around with dates
  2351. // https://stackoverflow.com/a/11252167/6495043
  2352. function treatAsUtc(dateStr) {
  2353. let result = new Date(dateStr);
  2354. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  2355. return result;
  2356. }
  2357. function getDdMmYyyy(date) {
  2358. let dd = date.getDate();
  2359. let mm = date.getMonth() + 1; // getMonth() is zero-based
  2360. return [
  2361. (dd>9 ? '' : '0') + dd,
  2362. (mm>9 ? '' : '0') + mm,
  2363. date.getFullYear()
  2364. ].join('-');
  2365. }
  2366. function getWeeksBetween(startDateStr, endDateStr) {
  2367. return Math.ceil(getDaysBetween(startDateStr, endDateStr) / 7);
  2368. }
  2369. function getDaysBetween(startDateStr, endDateStr) {
  2370. let millisecondsPerDay = 24 * 60 * 60 * 1000;
  2371. return (treatAsUtc(endDateStr) - treatAsUtc(startDateStr)) / millisecondsPerDay;
  2372. }
  2373. // mutates
  2374. function addDays(date, numberOfDays) {
  2375. date.setDate(date.getDate() + numberOfDays);
  2376. }
  2377. // export function getMonthName() {}
  2378. class Heatmap extends BaseChart {
  2379. constructor({
  2380. start = '',
  2381. domain = '',
  2382. subdomain = '',
  2383. data = {},
  2384. discrete_domains = 0,
  2385. count_label = '',
  2386. legend_colors = []
  2387. }) {
  2388. super(arguments[0]);
  2389. this.type = 'heatmap';
  2390. this.domain = domain;
  2391. this.subdomain = subdomain;
  2392. this.data = data;
  2393. this.discrete_domains = discrete_domains;
  2394. this.count_label = count_label;
  2395. let today = new Date();
  2396. this.start = start || addDays(today, 365);
  2397. legend_colors = legend_colors.slice(0, 5);
  2398. this.legend_colors = this.validate_colors(legend_colors)
  2399. ? legend_colors
  2400. : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  2401. // Fixed 5-color theme,
  2402. // More colors are difficult to parse visually
  2403. this.distribution_size = 5;
  2404. this.translateX = 0;
  2405. // this.setup();
  2406. }
  2407. validate_colors(colors) {
  2408. if(colors.length < 5) return 0;
  2409. let valid = 1;
  2410. colors.forEach(function(string) {
  2411. if(!isValidColor(string)) {
  2412. valid = 0;
  2413. console.warn('"' + string + '" is not a valid color.');
  2414. }
  2415. }, this);
  2416. return valid;
  2417. }
  2418. configure() {
  2419. super.configure();
  2420. this.today = new Date();
  2421. if(!this.start) {
  2422. this.start = new Date();
  2423. this.start.setFullYear( this.start.getFullYear() - 1 );
  2424. }
  2425. this.first_week_start = new Date(this.start.toDateString());
  2426. this.last_week_start = new Date(this.today.toDateString());
  2427. if(this.first_week_start.getDay() !== 7) {
  2428. addDays(this.first_week_start, (-1) * this.first_week_start.getDay());
  2429. }
  2430. if(this.last_week_start.getDay() !== 7) {
  2431. addDays(this.last_week_start, (-1) * this.last_week_start.getDay());
  2432. }
  2433. this.no_of_cols = getWeeksBetween(this.first_week_start + '', this.last_week_start + '') + 1;
  2434. }
  2435. calcWidth() {
  2436. this.baseWidth = (this.no_of_cols + 3) * 12 ;
  2437. if(this.discrete_domains) {
  2438. this.baseWidth += (12 * 12);
  2439. }
  2440. }
  2441. setupLayers() {
  2442. this.domain_label_group = this.makeLayer(
  2443. 'domain-label-group chart-label');
  2444. this.data_groups = this.makeLayer(
  2445. 'data-groups',
  2446. `translate(0, 20)`
  2447. );
  2448. }
  2449. setup_values() {
  2450. this.domain_label_group.textContent = '';
  2451. this.data_groups.textContent = '';
  2452. let data_values = Object.keys(this.data).map(key => this.data[key]);
  2453. this.distribution = calcDistribution(data_values, this.distribution_size);
  2454. this.month_names = ["January", "February", "March", "April", "May", "June",
  2455. "July", "August", "September", "October", "November", "December"
  2456. ];
  2457. this.render_all_weeks_and_store_x_values(this.no_of_cols);
  2458. }
  2459. render_all_weeks_and_store_x_values(no_of_weeks) {
  2460. let current_week_sunday = new Date(this.first_week_start);
  2461. this.week_col = 0;
  2462. this.current_month = current_week_sunday.getMonth();
  2463. this.months = [this.current_month + ''];
  2464. this.month_weeks = {}, this.month_start_points = [];
  2465. this.month_weeks[this.current_month] = 0;
  2466. this.month_start_points.push(13);
  2467. for(var i = 0; i < no_of_weeks; i++) {
  2468. let data_group, month_change = 0;
  2469. let day = new Date(current_week_sunday);
  2470. [data_group, month_change] = this.get_week_squares_group(day, this.week_col);
  2471. this.data_groups.appendChild(data_group);
  2472. this.week_col += 1 + parseInt(this.discrete_domains && month_change);
  2473. this.month_weeks[this.current_month]++;
  2474. if(month_change) {
  2475. this.current_month = (this.current_month + 1) % 12;
  2476. this.months.push(this.current_month + '');
  2477. this.month_weeks[this.current_month] = 1;
  2478. }
  2479. addDays(current_week_sunday, 7);
  2480. }
  2481. this.render_month_labels();
  2482. }
  2483. get_week_squares_group(current_date, index) {
  2484. const no_of_weekdays = 7;
  2485. const square_side = 10;
  2486. const cell_padding = 2;
  2487. const step = 1;
  2488. const today_time = this.today.getTime();
  2489. let month_change = 0;
  2490. let week_col_change = 0;
  2491. let data_group = makeSVGGroup(this.data_groups, 'data-group');
  2492. for(var y = 0, i = 0; i < no_of_weekdays; i += step, y += (square_side + cell_padding)) {
  2493. let data_value = 0;
  2494. let color_index = 0;
  2495. let current_timestamp = current_date.getTime()/1000;
  2496. let timestamp = Math.floor(current_timestamp - (current_timestamp % 86400)).toFixed(1);
  2497. if(this.data[timestamp]) {
  2498. data_value = this.data[timestamp];
  2499. }
  2500. if(this.data[Math.round(timestamp)]) {
  2501. data_value = this.data[Math.round(timestamp)];
  2502. }
  2503. if(data_value) {
  2504. color_index = getMaxCheckpoint(data_value, this.distribution);
  2505. }
  2506. let x = 13 + (index + week_col_change) * 12;
  2507. let dataAttr = {
  2508. 'data-date': getDdMmYyyy(current_date),
  2509. 'data-value': data_value,
  2510. 'data-day': current_date.getDay()
  2511. };
  2512. let heatSquare = makeHeatSquare('day', x, y, square_side,
  2513. this.legend_colors[color_index], dataAttr);
  2514. data_group.appendChild(heatSquare);
  2515. let next_date = new Date(current_date);
  2516. addDays(next_date, 1);
  2517. if(next_date.getTime() > today_time) break;
  2518. if(next_date.getMonth() - current_date.getMonth()) {
  2519. month_change = 1;
  2520. if(this.discrete_domains) {
  2521. week_col_change = 1;
  2522. }
  2523. this.month_start_points.push(13 + (index + week_col_change) * 12);
  2524. }
  2525. current_date = next_date;
  2526. }
  2527. return [data_group, month_change];
  2528. }
  2529. render_month_labels() {
  2530. // this.first_month_label = 1;
  2531. // if (this.first_week_start.getDate() > 8) {
  2532. // this.first_month_label = 0;
  2533. // }
  2534. // this.last_month_label = 1;
  2535. // let first_month = this.months.shift();
  2536. // let first_month_start = this.month_start_points.shift();
  2537. // render first month if
  2538. // let last_month = this.months.pop();
  2539. // let last_month_start = this.month_start_points.pop();
  2540. // render last month if
  2541. this.months.shift();
  2542. this.month_start_points.shift();
  2543. this.months.pop();
  2544. this.month_start_points.pop();
  2545. this.month_start_points.map((start, i) => {
  2546. let month_name = this.month_names[this.months[i]].substring(0, 3);
  2547. let text = makeText('y-value-text', start+12, 10, month_name);
  2548. this.domain_label_group.appendChild(text);
  2549. });
  2550. }
  2551. renderComponents() {
  2552. Array.prototype.slice.call(
  2553. this.container.querySelectorAll('.graph-stats-container, .sub-title, .title')
  2554. ).map(d => {
  2555. d.style.display = 'None';
  2556. });
  2557. this.chartWrapper.style.marginTop = '0px';
  2558. this.chartWrapper.style.paddingTop = '0px';
  2559. }
  2560. bindTooltip() {
  2561. Array.prototype.slice.call(
  2562. document.querySelectorAll(".data-group .day")
  2563. ).map(el => {
  2564. el.addEventListener('mouseenter', (e) => {
  2565. let count = e.target.getAttribute('data-value');
  2566. let date_parts = e.target.getAttribute('data-date').split('-');
  2567. let month = this.month_names[parseInt(date_parts[1])-1].substring(0, 3);
  2568. let g_off = this.chartWrapper.getBoundingClientRect(), p_off = e.target.getBoundingClientRect();
  2569. let width = parseInt(e.target.getAttribute('width'));
  2570. let x = p_off.left - g_off.left + (width+2)/2;
  2571. let y = p_off.top - g_off.top - (width+2)/2;
  2572. let value = count + ' ' + this.count_label;
  2573. let name = ' on ' + month + ' ' + date_parts[0] + ', ' + date_parts[2];
  2574. this.tip.set_values(x, y, name, value, [], 1);
  2575. this.tip.show_tip();
  2576. });
  2577. });
  2578. }
  2579. update(data) {
  2580. this.data = data;
  2581. this.setup_values();
  2582. this.bindTooltip();
  2583. }
  2584. }
  2585. const chartTypes = {
  2586. mixed: AxisChart,
  2587. multiaxis: MultiAxisChart,
  2588. scatter: ScatterChart,
  2589. percentage: PercentageChart,
  2590. heatmap: Heatmap,
  2591. pie: PieChart
  2592. };
  2593. function getChartByType(chartType = 'line', options) {
  2594. debugger;
  2595. if(chartType === 'line') {
  2596. options.type = 'line';
  2597. return new AxisChart(options);
  2598. } else if (chartType === 'bar') {
  2599. options.type = 'bar';
  2600. return new AxisChart(options);
  2601. }
  2602. if (!chartTypes[chartType]) {
  2603. console.error("Undefined chart type: " + chartType);
  2604. return;
  2605. }
  2606. return new chartTypes[chartType](options);
  2607. }
  2608. class Chart {
  2609. constructor(args) {
  2610. return getChartByType(args.type, arguments[0]);
  2611. }
  2612. }
  2613. export default Chart;