Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

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