Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

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