Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

3293 linhas
77 KiB

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