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.
 
 
 

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