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ů.
 
 
 

3286 řá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. getDifferentChart(type) {
  1163. return getDifferentChart(type, this.type, this.parent, this.rawChartArgs);
  1164. }
  1165. }
  1166. class AggregationChart extends BaseChart {
  1167. constructor(parent, args) {
  1168. super(parent, args);
  1169. }
  1170. configure(args) {
  1171. super.configure(args);
  1172. this.config.maxSlices = args.maxSlices || 20;
  1173. this.config.maxLegendPoints = args.maxLegendPoints || 20;
  1174. }
  1175. calc() {
  1176. let s = this.state;
  1177. let maxSlices = this.config.maxSlices;
  1178. s.sliceTotals = [];
  1179. let allTotals = this.data.labels.map((label, i) => {
  1180. let total = 0;
  1181. this.data.datasets.map(e => {
  1182. total += e.values[i];
  1183. });
  1184. return [total, label];
  1185. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1186. let totals = allTotals;
  1187. if(allTotals.length > maxSlices) {
  1188. // Prune and keep a grey area for rest as per maxSlices
  1189. allTotals.sort((a, b) => { return b[0] - a[0]; });
  1190. totals = allTotals.slice(0, maxSlices-1);
  1191. let remaining = allTotals.slice(maxSlices-1);
  1192. let sumOfRemaining = 0;
  1193. remaining.map(d => {sumOfRemaining += d[0];});
  1194. totals.push([sumOfRemaining, 'Rest']);
  1195. this.colors[maxSlices-1] = 'grey';
  1196. }
  1197. s.labels = [];
  1198. totals.map(d => {
  1199. s.sliceTotals.push(d[0]);
  1200. s.labels.push(d[1]);
  1201. });
  1202. }
  1203. renderLegend() {
  1204. let s = this.state;
  1205. this.statsWrapper.textContent = '';
  1206. this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
  1207. let xValues = s.labels;
  1208. this.legendTotals.map((d, i) => {
  1209. if(d) {
  1210. let stats = $.create('div', {
  1211. className: 'stats',
  1212. inside: this.statsWrapper
  1213. });
  1214. stats.innerHTML = `<span class="indicator">
  1215. <i style="background: ${this.colors[i]}"></i>
  1216. <span class="text-muted">${xValues[i]}:</span>
  1217. ${d}
  1218. </span>`;
  1219. }
  1220. });
  1221. }
  1222. }
  1223. class PercentageChart extends AggregationChart {
  1224. constructor(parent, args) {
  1225. super(parent, args);
  1226. this.type = 'percentage';
  1227. this.setup();
  1228. }
  1229. makeChartArea() {
  1230. this.chartWrapper.className += ' ' + 'graph-focus-margin';
  1231. this.chartWrapper.style.marginTop = '45px';
  1232. this.statsWrapper.className += ' ' + 'graph-focus-margin';
  1233. this.statsWrapper.style.marginBottom = '30px';
  1234. this.statsWrapper.style.paddingTop = '0px';
  1235. this.svg = $.create('div', {
  1236. className: 'div',
  1237. inside: this.chartWrapper
  1238. });
  1239. this.chart = $.create('div', {
  1240. className: 'progress-chart',
  1241. inside: this.svg
  1242. });
  1243. this.percentageBar = $.create('div', {
  1244. className: 'progress',
  1245. inside: this.chart
  1246. });
  1247. }
  1248. render() {
  1249. let s = this.state;
  1250. this.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
  1251. s.slices = [];
  1252. s.sliceTotals.map((total, i) => {
  1253. let slice = $.create('div', {
  1254. className: `progress-bar`,
  1255. 'data-index': i,
  1256. inside: this.percentageBar,
  1257. styles: {
  1258. background: this.colors[i],
  1259. width: total*100/this.grandTotal + "%"
  1260. }
  1261. });
  1262. s.slices.push(slice);
  1263. });
  1264. }
  1265. bindTooltip() {
  1266. let s = this.state;
  1267. this.chartWrapper.addEventListener('mousemove', (e) => {
  1268. let slice = e.target;
  1269. if(slice.classList.contains('progress-bar')) {
  1270. let i = slice.getAttribute('data-index');
  1271. let gOff = getOffset(this.chartWrapper), pOff = getOffset(slice);
  1272. let x = pOff.left - gOff.left + slice.offsetWidth/2;
  1273. let y = pOff.top - gOff.top - 6;
  1274. let title = (this.formattedLabels && this.formattedLabels.length>0
  1275. ? this.formattedLabels[i] : this.state.labels[i]) + ': ';
  1276. let percent = (s.sliceTotals[i]*100/this.grandTotal).toFixed(1);
  1277. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  1278. this.tip.showTip();
  1279. }
  1280. });
  1281. }
  1282. }
  1283. class ChartComponent {
  1284. constructor({
  1285. layerClass = '',
  1286. layerTransform = '',
  1287. constants,
  1288. getData,
  1289. makeElements,
  1290. animateElements
  1291. }) {
  1292. this.layerTransform = layerTransform;
  1293. this.constants = constants;
  1294. this.makeElements = makeElements;
  1295. this.getData = getData;
  1296. this.animateElements = animateElements;
  1297. this.store = [];
  1298. this.layerClass = layerClass;
  1299. this.layerClass = typeof(this.layerClass) === 'function'
  1300. ? this.layerClass() : this.layerClass;
  1301. this.refresh();
  1302. }
  1303. refresh(data) {
  1304. this.data = data || this.getData();
  1305. }
  1306. setup(parent) {
  1307. this.layer = makeSVGGroup(parent, this.layerClass, this.layerTransform);
  1308. }
  1309. make() {
  1310. this.render(this.data);
  1311. this.oldData = this.data;
  1312. }
  1313. render(data) {
  1314. this.store = this.makeElements(data);
  1315. this.layer.textContent = '';
  1316. this.store.forEach(element => {
  1317. this.layer.appendChild(element);
  1318. });
  1319. }
  1320. update(animate = true) {
  1321. this.refresh();
  1322. let animateElements = [];
  1323. if(animate) {
  1324. animateElements = this.animateElements(this.data);
  1325. }
  1326. return animateElements;
  1327. }
  1328. }
  1329. let componentConfigs = {
  1330. pieSlices: {
  1331. layerClass: 'pie-slices',
  1332. makeElements(data) {
  1333. return data.sliceStrings.map((s, i) =>{
  1334. let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
  1335. slice.style.transition = 'transform .3s;';
  1336. return slice;
  1337. });
  1338. },
  1339. animateElements(newData) {
  1340. return this.store.map((slice, i) =>
  1341. animatePathStr(slice, newData.sliceStrings[i])
  1342. );
  1343. }
  1344. },
  1345. yAxis: {
  1346. layerClass: 'y axis',
  1347. makeElements(data) {
  1348. return data.positions.map((position, i) =>
  1349. yLine(position, data.labels[i], this.constants.width,
  1350. {mode: this.constants.mode, pos: this.constants.pos})
  1351. );
  1352. },
  1353. animateElements(newData) {
  1354. let newPos = newData.positions;
  1355. let newLabels = newData.labels;
  1356. let oldPos = this.oldData.positions;
  1357. let oldLabels = this.oldData.labels;
  1358. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1359. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1360. this.render({
  1361. positions: oldPos,
  1362. labels: newLabels
  1363. });
  1364. return this.store.map((line, i) => {
  1365. return translateHoriLine(
  1366. line, newPos[i], oldPos[i]
  1367. );
  1368. });
  1369. }
  1370. },
  1371. xAxis: {
  1372. layerClass: 'x axis',
  1373. makeElements(data) {
  1374. return data.positions.map((position, i) =>
  1375. xLine(position, data.calcLabels[i], this.constants.height,
  1376. {mode: this.constants.mode, pos: this.constants.pos})
  1377. );
  1378. },
  1379. animateElements(newData) {
  1380. let newPos = newData.positions;
  1381. let newLabels = newData.calcLabels;
  1382. let oldPos = this.oldData.positions;
  1383. let oldLabels = this.oldData.calcLabels;
  1384. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1385. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1386. this.render({
  1387. positions: oldPos,
  1388. calcLabels: newLabels
  1389. });
  1390. return this.store.map((line, i) => {
  1391. return translateVertLine(
  1392. line, newPos[i], oldPos[i]
  1393. );
  1394. });
  1395. }
  1396. },
  1397. yMarkers: {
  1398. layerClass: 'y-markers',
  1399. makeElements(data) {
  1400. return data.map(marker =>
  1401. yMarker(marker.position, marker.label, this.constants.width,
  1402. {pos:'right', mode: 'span', lineType: 'dashed'})
  1403. );
  1404. },
  1405. animateElements(newData) {
  1406. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1407. let newPos = newData.map(d => d.position);
  1408. let newLabels = newData.map(d => d.label);
  1409. let oldPos = this.oldData.map(d => d.position);
  1410. this.render(oldPos.map((pos, i) => {
  1411. return {
  1412. position: oldPos[i],
  1413. label: newLabels[i]
  1414. };
  1415. }));
  1416. return this.store.map((line, i) => {
  1417. return translateHoriLine(
  1418. line, newPos[i], oldPos[i]
  1419. );
  1420. });
  1421. }
  1422. },
  1423. yRegions: {
  1424. layerClass: 'y-regions',
  1425. makeElements(data) {
  1426. return data.map(region =>
  1427. yRegion(region.startPos, region.endPos, this.constants.width,
  1428. region.label)
  1429. );
  1430. },
  1431. animateElements(newData) {
  1432. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1433. let newPos = newData.map(d => d.endPos);
  1434. let newLabels = newData.map(d => d.label);
  1435. let newStarts = newData.map(d => d.startPos);
  1436. let oldPos = this.oldData.map(d => d.endPos);
  1437. let oldStarts = this.oldData.map(d => d.startPos);
  1438. this.render(oldPos.map((pos, i) => {
  1439. return {
  1440. startPos: oldStarts[i],
  1441. endPos: oldPos[i],
  1442. label: newLabels[i]
  1443. };
  1444. }));
  1445. let animateElements = [];
  1446. this.store.map((rectGroup, i) => {
  1447. animateElements = animateElements.concat(animateRegion(
  1448. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1449. ));
  1450. });
  1451. return animateElements;
  1452. }
  1453. },
  1454. barGraph: {
  1455. layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
  1456. makeElements(data) {
  1457. let c = this.constants;
  1458. this.unitType = 'bar';
  1459. this.units = data.yPositions.map((y, j) => {
  1460. return datasetBar(
  1461. data.xPositions[j],
  1462. y,
  1463. data.barWidth,
  1464. c.color,
  1465. data.labels[j],
  1466. j,
  1467. data.offsets[j],
  1468. {
  1469. zeroLine: data.zeroLine,
  1470. barsWidth: data.barsWidth,
  1471. minHeight: c.minHeight
  1472. }
  1473. );
  1474. });
  1475. return this.units;
  1476. },
  1477. animateElements(newData) {
  1478. let newXPos = newData.xPositions;
  1479. let newYPos = newData.yPositions;
  1480. let newOffsets = newData.offsets;
  1481. let newLabels = newData.labels;
  1482. let oldXPos = this.oldData.xPositions;
  1483. let oldYPos = this.oldData.yPositions;
  1484. let oldOffsets = this.oldData.offsets;
  1485. let oldLabels = this.oldData.labels;
  1486. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1487. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1488. [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
  1489. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1490. this.render({
  1491. xPositions: oldXPos,
  1492. yPositions: oldYPos,
  1493. offsets: oldOffsets,
  1494. labels: newLabels,
  1495. zeroLine: this.oldData.zeroLine,
  1496. barsWidth: this.oldData.barsWidth,
  1497. barWidth: this.oldData.barWidth,
  1498. });
  1499. let animateElements = [];
  1500. this.store.map((bar, i) => {
  1501. animateElements = animateElements.concat(animateBar(
  1502. bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
  1503. {zeroLine: newData.zeroLine}
  1504. ));
  1505. });
  1506. return animateElements;
  1507. }
  1508. },
  1509. lineGraph: {
  1510. layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
  1511. makeElements(data) {
  1512. let c = this.constants;
  1513. this.unitType = 'dot';
  1514. this.paths = {};
  1515. if(!c.hideLine) {
  1516. this.paths = getPaths(
  1517. data.xPositions,
  1518. data.yPositions,
  1519. c.color,
  1520. {
  1521. heatline: c.heatline,
  1522. regionFill: c.regionFill
  1523. },
  1524. {
  1525. svgDefs: c.svgDefs,
  1526. zeroLine: data.zeroLine
  1527. }
  1528. );
  1529. }
  1530. this.units = [];
  1531. if(!c.hideDots) {
  1532. this.units = data.yPositions.map((y, j) => {
  1533. return datasetDot(
  1534. data.xPositions[j],
  1535. y,
  1536. data.radius,
  1537. c.color,
  1538. (c.valuesOverPoints ? data.values[j] : ''),
  1539. j
  1540. );
  1541. });
  1542. }
  1543. return Object.values(this.paths).concat(this.units);
  1544. },
  1545. animateElements(newData) {
  1546. let newXPos = newData.xPositions;
  1547. let newYPos = newData.yPositions;
  1548. let newValues = newData.values;
  1549. let oldXPos = this.oldData.xPositions;
  1550. let oldYPos = this.oldData.yPositions;
  1551. let oldValues = this.oldData.values;
  1552. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1553. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1554. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  1555. this.render({
  1556. xPositions: oldXPos,
  1557. yPositions: oldYPos,
  1558. values: newValues,
  1559. zeroLine: this.oldData.zeroLine,
  1560. radius: this.oldData.radius,
  1561. });
  1562. let animateElements = [];
  1563. if(Object.keys(this.paths).length) {
  1564. animateElements = animateElements.concat(animatePath(
  1565. this.paths, newXPos, newYPos, newData.zeroLine));
  1566. }
  1567. if(this.units.length) {
  1568. this.units.map((dot, i) => {
  1569. animateElements = animateElements.concat(animateDot(
  1570. dot, newXPos[i], newYPos[i]));
  1571. });
  1572. }
  1573. return animateElements;
  1574. }
  1575. }
  1576. };
  1577. function getComponent(name, constants, getData) {
  1578. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  1579. let config = componentConfigs[keys[0]];
  1580. Object.assign(config, {
  1581. constants: constants,
  1582. getData: getData
  1583. });
  1584. return new ChartComponent(config);
  1585. }
  1586. class PieChart extends AggregationChart {
  1587. constructor(parent, args) {
  1588. super(parent, args);
  1589. this.type = 'pie';
  1590. this.initTimeout = 0;
  1591. this.setup();
  1592. }
  1593. configure(args) {
  1594. super.configure(args);
  1595. this.mouseMove = this.mouseMove.bind(this);
  1596. this.mouseLeave = this.mouseLeave.bind(this);
  1597. this.hoverRadio = args.hoverRadio || 0.1;
  1598. this.config.startAngle = args.startAngle || 0;
  1599. this.clockWise = args.clockWise || false;
  1600. }
  1601. prepareFirstData(data=this.data) {
  1602. this.init = 1;
  1603. return data;
  1604. }
  1605. calc() {
  1606. super.calc();
  1607. let s = this.state;
  1608. this.center = {
  1609. x: this.width / 2,
  1610. y: this.height / 2
  1611. };
  1612. this.radius = (this.height > this.width ? this.center.x : this.center.y);
  1613. s.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
  1614. this.calcSlices();
  1615. }
  1616. calcSlices() {
  1617. let s = this.state;
  1618. const { radius, clockWise } = this;
  1619. const prevSlicesProperties = s.slicesProperties || [];
  1620. s.sliceStrings = [];
  1621. s.slicesProperties = [];
  1622. let curAngle = 180 - this.config.startAngle;
  1623. s.sliceTotals.map((total, i) => {
  1624. const startAngle = curAngle;
  1625. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  1626. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1627. const endAngle = curAngle = curAngle + diffAngle;
  1628. const startPosition = getPositionByAngle(startAngle, radius);
  1629. const endPosition = getPositionByAngle(endAngle, radius);
  1630. const prevProperty = this.init && prevSlicesProperties[i];
  1631. let curStart,curEnd;
  1632. if(this.init) {
  1633. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  1634. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  1635. } else {
  1636. curStart = startPosition;
  1637. curEnd = endPosition;
  1638. }
  1639. const curPath = makeArcPathStr(curStart, curEnd, this.center, this.radius, this.clockWise);
  1640. s.sliceStrings.push(curPath);
  1641. s.slicesProperties.push({
  1642. startPosition,
  1643. endPosition,
  1644. value: total,
  1645. total: s.grandTotal,
  1646. startAngle,
  1647. endAngle,
  1648. angle: diffAngle
  1649. });
  1650. });
  1651. this.init = 0;
  1652. }
  1653. setupComponents() {
  1654. let s = this.state;
  1655. let componentConfigs = [
  1656. [
  1657. 'pieSlices',
  1658. { },
  1659. function() {
  1660. return {
  1661. sliceStrings: s.sliceStrings,
  1662. colors: this.colors
  1663. };
  1664. }.bind(this)
  1665. ]
  1666. ];
  1667. this.components = new Map(componentConfigs
  1668. .map(args => {
  1669. let component = getComponent(...args);
  1670. return [args[0], component];
  1671. }));
  1672. }
  1673. calTranslateByAngle(property){
  1674. const{radius,hoverRadio} = this;
  1675. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  1676. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  1677. }
  1678. hoverSlice(path,i,flag,e){
  1679. if(!path) return;
  1680. const color = this.colors[i];
  1681. if(flag) {
  1682. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  1683. path.style.fill = lightenDarkenColor(color, 50);
  1684. let g_off = getOffset(this.svg);
  1685. let x = e.pageX - g_off.left + 10;
  1686. let y = e.pageY - g_off.top - 10;
  1687. let title = (this.formatted_labels && this.formatted_labels.length > 0
  1688. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  1689. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  1690. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  1691. this.tip.showTip();
  1692. } else {
  1693. transform(path,'translate3d(0,0,0)');
  1694. this.tip.hideTip();
  1695. path.style.fill = color;
  1696. }
  1697. }
  1698. bindTooltip() {
  1699. this.chartWrapper.addEventListener('mousemove', this.mouseMove);
  1700. this.chartWrapper.addEventListener('mouseleave', this.mouseLeave);
  1701. }
  1702. mouseMove(e){
  1703. const target = e.target;
  1704. let slices = this.components.get('pieSlices').store;
  1705. let prevIndex = this.curActiveSliceIndex;
  1706. let prevAcitve = this.curActiveSlice;
  1707. if(slices.includes(target)) {
  1708. let i = slices.indexOf(target);
  1709. this.hoverSlice(prevAcitve, prevIndex,false);
  1710. this.curActiveSlice = target;
  1711. this.curActiveSliceIndex = i;
  1712. this.hoverSlice(target, i, true, e);
  1713. } else {
  1714. this.mouseLeave();
  1715. }
  1716. }
  1717. mouseLeave(){
  1718. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  1719. }
  1720. }
  1721. // Playing around with dates
  1722. // https://stackoverflow.com/a/11252167/6495043
  1723. function treatAsUtc(dateStr) {
  1724. let result = new Date(dateStr);
  1725. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1726. return result;
  1727. }
  1728. function getDdMmYyyy(date) {
  1729. let dd = date.getDate();
  1730. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1731. return [
  1732. (dd>9 ? '' : '0') + dd,
  1733. (mm>9 ? '' : '0') + mm,
  1734. date.getFullYear()
  1735. ].join('-');
  1736. }
  1737. function getWeeksBetween(startDateStr, endDateStr) {
  1738. return Math.ceil(getDaysBetween(startDateStr, endDateStr) / 7);
  1739. }
  1740. function getDaysBetween(startDateStr, endDateStr) {
  1741. let millisecondsPerDay = 24 * 60 * 60 * 1000;
  1742. return (treatAsUtc(endDateStr) - treatAsUtc(startDateStr)) / millisecondsPerDay;
  1743. }
  1744. // mutates
  1745. function addDays(date, numberOfDays) {
  1746. date.setDate(date.getDate() + numberOfDays);
  1747. }
  1748. function normalize(x) {
  1749. // Calculates mantissa and exponent of a number
  1750. // Returns normalized number and exponent
  1751. // https://stackoverflow.com/q/9383593/6495043
  1752. if(x===0) {
  1753. return [0, 0];
  1754. }
  1755. if(isNaN(x)) {
  1756. return {mantissa: -6755399441055744, exponent: 972};
  1757. }
  1758. var sig = x > 0 ? 1 : -1;
  1759. if(!isFinite(x)) {
  1760. return {mantissa: sig * 4503599627370496, exponent: 972};
  1761. }
  1762. x = Math.abs(x);
  1763. var exp = Math.floor(Math.log10(x));
  1764. var man = x/Math.pow(10, exp);
  1765. return [sig * man, exp];
  1766. }
  1767. function getChartRangeIntervals(max, min=0) {
  1768. let upperBound = Math.ceil(max);
  1769. let lowerBound = Math.floor(min);
  1770. let range = upperBound - lowerBound;
  1771. let noOfParts = range;
  1772. let partSize = 1;
  1773. // To avoid too many partitions
  1774. if(range > 5) {
  1775. if(range % 2 !== 0) {
  1776. upperBound++;
  1777. // Recalc range
  1778. range = upperBound - lowerBound;
  1779. }
  1780. noOfParts = range/2;
  1781. partSize = 2;
  1782. }
  1783. // Special case: 1 and 2
  1784. if(range <= 2) {
  1785. noOfParts = 4;
  1786. partSize = range/noOfParts;
  1787. }
  1788. // Special case: 0
  1789. if(range === 0) {
  1790. noOfParts = 5;
  1791. partSize = 1;
  1792. }
  1793. let intervals = [];
  1794. for(var i = 0; i <= noOfParts; i++){
  1795. intervals.push(lowerBound + partSize * i);
  1796. }
  1797. return intervals;
  1798. }
  1799. function getChartIntervals(maxValue, minValue=0) {
  1800. let [normalMaxValue, exponent] = normalize(maxValue);
  1801. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  1802. // Allow only 7 significant digits
  1803. normalMaxValue = normalMaxValue.toFixed(6);
  1804. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  1805. intervals = intervals.map(value => value * Math.pow(10, exponent));
  1806. return intervals;
  1807. }
  1808. function calcChartIntervals(values, withMinimum=false) {
  1809. //*** Where the magic happens ***
  1810. // Calculates best-fit y intervals from given values
  1811. // and returns the interval array
  1812. let maxValue = Math.max(...values);
  1813. let minValue = Math.min(...values);
  1814. // Exponent to be used for pretty print
  1815. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  1816. function getPositiveFirstIntervals(maxValue, absMinValue) {
  1817. let intervals = getChartIntervals(maxValue);
  1818. let intervalSize = intervals[1] - intervals[0];
  1819. // Then unshift the negative values
  1820. let value = 0;
  1821. for(var i = 1; value < absMinValue; i++) {
  1822. value += intervalSize;
  1823. intervals.unshift((-1) * value);
  1824. }
  1825. return intervals;
  1826. }
  1827. // CASE I: Both non-negative
  1828. if(maxValue >= 0 && minValue >= 0) {
  1829. exponent = normalize(maxValue)[1];
  1830. if(!withMinimum) {
  1831. intervals = getChartIntervals(maxValue);
  1832. } else {
  1833. intervals = getChartIntervals(maxValue, minValue);
  1834. }
  1835. }
  1836. // CASE II: Only minValue negative
  1837. else if(maxValue > 0 && minValue < 0) {
  1838. // `withMinimum` irrelevant in this case,
  1839. // We'll be handling both sides of zero separately
  1840. // (both starting from zero)
  1841. // Because ceil() and floor() behave differently
  1842. // in those two regions
  1843. let absMinValue = Math.abs(minValue);
  1844. if(maxValue >= absMinValue) {
  1845. exponent = normalize(maxValue)[1];
  1846. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  1847. } else {
  1848. // Mirror: maxValue => absMinValue, then change sign
  1849. exponent = normalize(absMinValue)[1];
  1850. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  1851. intervals = posIntervals.map(d => d * (-1));
  1852. }
  1853. }
  1854. // CASE III: Both non-positive
  1855. else if(maxValue <= 0 && minValue <= 0) {
  1856. // Mirrored Case I:
  1857. // Work with positives, then reverse the sign and array
  1858. let pseudoMaxValue = Math.abs(minValue);
  1859. let pseudoMinValue = Math.abs(maxValue);
  1860. exponent = normalize(pseudoMaxValue)[1];
  1861. if(!withMinimum) {
  1862. intervals = getChartIntervals(pseudoMaxValue);
  1863. } else {
  1864. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  1865. }
  1866. intervals = intervals.reverse().map(d => d * (-1));
  1867. }
  1868. return intervals;
  1869. }
  1870. function getZeroIndex(yPts) {
  1871. let zeroIndex;
  1872. let interval = getIntervalSize(yPts);
  1873. if(yPts.indexOf(0) >= 0) {
  1874. // the range has a given zero
  1875. // zero-line on the chart
  1876. zeroIndex = yPts.indexOf(0);
  1877. } else if(yPts[0] > 0) {
  1878. // Minimum value is positive
  1879. // zero-line is off the chart: below
  1880. let min = yPts[0];
  1881. zeroIndex = (-1) * min / interval;
  1882. } else {
  1883. // Maximum value is negative
  1884. // zero-line is off the chart: above
  1885. let max = yPts[yPts.length - 1];
  1886. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  1887. }
  1888. return zeroIndex;
  1889. }
  1890. function getIntervalSize(orderedArray) {
  1891. return orderedArray[1] - orderedArray[0];
  1892. }
  1893. function getValueRange(orderedArray) {
  1894. return orderedArray[orderedArray.length-1] - orderedArray[0];
  1895. }
  1896. function scale(val, yAxis) {
  1897. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier);
  1898. }
  1899. function calcDistribution(values, distributionSize) {
  1900. // Assume non-negative values,
  1901. // implying distribution minimum at zero
  1902. let dataMaxValue = Math.max(...values);
  1903. let distributionStep = 1 / (distributionSize - 1);
  1904. let distribution = [];
  1905. for(var i = 0; i < distributionSize; i++) {
  1906. let checkpoint = dataMaxValue * (distributionStep * i);
  1907. distribution.push(checkpoint);
  1908. }
  1909. return distribution;
  1910. }
  1911. function getMaxCheckpoint(value, distribution) {
  1912. return distribution.filter(d => d < value).length;
  1913. }
  1914. class Heatmap extends BaseChart {
  1915. constructor(parent, options) {
  1916. super(parent, options);
  1917. this.type = 'heatmap';
  1918. this.domain = options.domain || '';
  1919. this.subdomain = options.subdomain || '';
  1920. this.data = options.data || {};
  1921. this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
  1922. this.countLabel = options.countLabel || '';
  1923. let today = new Date();
  1924. this.start = options.start || addDays(today, 365);
  1925. let legendColors = (options.legendColors || []).slice(0, 5);
  1926. this.legendColors = this.validate_colors(legendColors)
  1927. ? legendColors
  1928. : ['#ebedf0', '#c6e48b', '#7bc96f', '#239a3b', '#196127'];
  1929. // Fixed 5-color theme,
  1930. // More colors are difficult to parse visually
  1931. this.distribution_size = 5;
  1932. this.translateX = 0;
  1933. this.setup();
  1934. }
  1935. setMargins() {
  1936. super.setMargins();
  1937. this.leftMargin = 10;
  1938. this.translateY = 10;
  1939. }
  1940. validate_colors(colors) {
  1941. if(colors.length < 5) return 0;
  1942. let valid = 1;
  1943. colors.forEach(function(string) {
  1944. if(!isValidColor(string)) {
  1945. valid = 0;
  1946. console.warn('"' + string + '" is not a valid color.');
  1947. }
  1948. }, this);
  1949. return valid;
  1950. }
  1951. configure() {
  1952. super.configure();
  1953. this.today = new Date();
  1954. if(!this.start) {
  1955. this.start = new Date();
  1956. this.start.setFullYear( this.start.getFullYear() - 1 );
  1957. }
  1958. this.firstWeekStart = new Date(this.start.toDateString());
  1959. this.lastWeekStart = new Date(this.today.toDateString());
  1960. if(this.firstWeekStart.getDay() !== 7) {
  1961. addDays(this.firstWeekStart, (-1) * this.firstWeekStart.getDay());
  1962. }
  1963. if(this.lastWeekStart.getDay() !== 7) {
  1964. addDays(this.lastWeekStart, (-1) * this.lastWeekStart.getDay());
  1965. }
  1966. this.no_of_cols = getWeeksBetween(this.firstWeekStart + '', this.lastWeekStart + '') + 1;
  1967. }
  1968. calcWidth() {
  1969. this.baseWidth = (this.no_of_cols + 3) * 12 ;
  1970. if(this.discreteDomains) {
  1971. this.baseWidth += (12 * 12);
  1972. }
  1973. }
  1974. makeChartArea() {
  1975. super.makeChartArea();
  1976. this.domainLabelGroup = makeSVGGroup(this.drawArea,
  1977. 'domain-label-group chart-label');
  1978. this.dataGroups = makeSVGGroup(this.drawArea,
  1979. 'data-groups',
  1980. `translate(0, 20)`
  1981. );
  1982. this.container.querySelector('.title').style.display = 'None';
  1983. this.container.querySelector('.sub-title').style.display = 'None';
  1984. this.container.querySelector('.graph-stats-container').style.display = 'None';
  1985. this.chartWrapper.style.marginTop = '0px';
  1986. this.chartWrapper.style.paddingTop = '0px';
  1987. }
  1988. calc() {
  1989. let dataValues = Object.keys(this.data).map(key => this.data[key]);
  1990. this.distribution = calcDistribution(dataValues, this.distribution_size);
  1991. this.monthNames = ["January", "February", "March", "April", "May", "June",
  1992. "July", "August", "September", "October", "November", "December"
  1993. ];
  1994. }
  1995. render() {
  1996. this.renderAllWeeksAndStoreXValues(this.no_of_cols);
  1997. }
  1998. renderAllWeeksAndStoreXValues(no_of_weeks) {
  1999. // renderAllWeeksAndStoreXValues
  2000. this.domainLabelGroup.textContent = '';
  2001. this.dataGroups.textContent = '';
  2002. let currentWeekSunday = new Date(this.firstWeekStart);
  2003. this.weekCol = 0;
  2004. this.currentMonth = currentWeekSunday.getMonth();
  2005. this.months = [this.currentMonth + ''];
  2006. this.monthWeeks = {}, this.monthStartPoints = [];
  2007. this.monthWeeks[this.currentMonth] = 0;
  2008. this.monthStartPoints.push(13);
  2009. for(var i = 0; i < no_of_weeks; i++) {
  2010. let dataGroup, monthChange = 0;
  2011. let day = new Date(currentWeekSunday);
  2012. [dataGroup, monthChange] = this.get_week_squares_group(day, this.weekCol);
  2013. this.dataGroups.appendChild(dataGroup);
  2014. this.weekCol += 1 + parseInt(this.discreteDomains && monthChange);
  2015. this.monthWeeks[this.currentMonth]++;
  2016. if(monthChange) {
  2017. this.currentMonth = (this.currentMonth + 1) % 12;
  2018. this.months.push(this.currentMonth + '');
  2019. this.monthWeeks[this.currentMonth] = 1;
  2020. }
  2021. addDays(currentWeekSunday, 7);
  2022. }
  2023. this.render_month_labels();
  2024. }
  2025. get_week_squares_group(currentDate, index) {
  2026. const noOfWeekdays = 7;
  2027. const squareSide = 10;
  2028. const cellPadding = 2;
  2029. const step = 1;
  2030. const todayTime = this.today.getTime();
  2031. let monthChange = 0;
  2032. let weekColChange = 0;
  2033. let dataGroup = makeSVGGroup(this.dataGroups, 'data-group');
  2034. for(var y = 0, i = 0; i < noOfWeekdays; i += step, y += (squareSide + cellPadding)) {
  2035. let dataValue = 0;
  2036. let colorIndex = 0;
  2037. let currentTimestamp = currentDate.getTime()/1000;
  2038. let timestamp = Math.floor(currentTimestamp - (currentTimestamp % 86400)).toFixed(1);
  2039. if(this.data[timestamp]) {
  2040. dataValue = this.data[timestamp];
  2041. }
  2042. if(this.data[Math.round(timestamp)]) {
  2043. dataValue = this.data[Math.round(timestamp)];
  2044. }
  2045. if(dataValue) {
  2046. colorIndex = getMaxCheckpoint(dataValue, this.distribution);
  2047. }
  2048. let x = 13 + (index + weekColChange) * 12;
  2049. let dataAttr = {
  2050. 'data-date': getDdMmYyyy(currentDate),
  2051. 'data-value': dataValue,
  2052. 'data-day': currentDate.getDay()
  2053. };
  2054. let heatSquare = makeHeatSquare('day', x, y, squareSide,
  2055. this.legendColors[colorIndex], dataAttr);
  2056. dataGroup.appendChild(heatSquare);
  2057. let nextDate = new Date(currentDate);
  2058. addDays(nextDate, 1);
  2059. if(nextDate.getTime() > todayTime) break;
  2060. if(nextDate.getMonth() - currentDate.getMonth()) {
  2061. monthChange = 1;
  2062. if(this.discreteDomains) {
  2063. weekColChange = 1;
  2064. }
  2065. this.monthStartPoints.push(13 + (index + weekColChange) * 12);
  2066. }
  2067. currentDate = nextDate;
  2068. }
  2069. return [dataGroup, monthChange];
  2070. }
  2071. render_month_labels() {
  2072. // this.first_month_label = 1;
  2073. // if (this.firstWeekStart.getDate() > 8) {
  2074. // this.first_month_label = 0;
  2075. // }
  2076. // this.last_month_label = 1;
  2077. // let first_month = this.months.shift();
  2078. // let first_month_start = this.monthStartPoints.shift();
  2079. // render first month if
  2080. // let last_month = this.months.pop();
  2081. // let last_month_start = this.monthStartPoints.pop();
  2082. // render last month if
  2083. this.months.shift();
  2084. this.monthStartPoints.shift();
  2085. this.months.pop();
  2086. this.monthStartPoints.pop();
  2087. this.monthStartPoints.map((start, i) => {
  2088. let month_name = this.monthNames[this.months[i]].substring(0, 3);
  2089. let text = makeText('y-value-text', start+12, 10, month_name);
  2090. this.domainLabelGroup.appendChild(text);
  2091. });
  2092. }
  2093. bindTooltip() {
  2094. Array.prototype.slice.call(
  2095. document.querySelectorAll(".data-group .day")
  2096. ).map(el => {
  2097. el.addEventListener('mouseenter', (e) => {
  2098. let count = e.target.getAttribute('data-value');
  2099. let dateParts = e.target.getAttribute('data-date').split('-');
  2100. let month = this.monthNames[parseInt(dateParts[1])-1].substring(0, 3);
  2101. let gOff = this.chartWrapper.getBoundingClientRect(), pOff = e.target.getBoundingClientRect();
  2102. let width = parseInt(e.target.getAttribute('width'));
  2103. let x = pOff.left - gOff.left + (width+2)/2;
  2104. let y = pOff.top - gOff.top - (width+2)/2;
  2105. let value = count + ' ' + this.countLabel;
  2106. let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
  2107. this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
  2108. this.tip.showTip();
  2109. });
  2110. });
  2111. }
  2112. update(data) {
  2113. super.update(data);
  2114. this.bindTooltip();
  2115. }
  2116. }
  2117. function dataPrep(data, type) {
  2118. data.labels = data.labels || [];
  2119. let datasetLength = data.labels.length;
  2120. // Datasets
  2121. let datasets = data.datasets;
  2122. let zeroArray = new Array(datasetLength).fill(0);
  2123. if(!datasets) {
  2124. // default
  2125. datasets = [{
  2126. values: zeroArray
  2127. }];
  2128. }
  2129. datasets.map(d=> {
  2130. // Set values
  2131. if(!d.values) {
  2132. d.values = zeroArray;
  2133. } else {
  2134. // Check for non values
  2135. let vals = d.values;
  2136. vals = vals.map(val => (!isNaN(val) ? val : 0));
  2137. // Trim or extend
  2138. if(vals.length > datasetLength) {
  2139. vals = vals.slice(0, datasetLength);
  2140. } else {
  2141. vals = fillArray(vals, datasetLength - vals.length, 0);
  2142. }
  2143. }
  2144. // Set labels
  2145. //
  2146. // Set type
  2147. if(!d.chartType ) {
  2148. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  2149. d.chartType = type;
  2150. }
  2151. });
  2152. // Markers
  2153. // Regions
  2154. // data.yRegions = data.yRegions || [];
  2155. if(data.yRegions) {
  2156. data.yRegions.map(d => {
  2157. if(d.end < d.start) {
  2158. [d.start, d.end] = [d.end, d.start];
  2159. }
  2160. });
  2161. }
  2162. return data;
  2163. }
  2164. function zeroDataPrep(realData) {
  2165. let datasetLength = realData.labels.length;
  2166. let zeroArray = new Array(datasetLength).fill(0);
  2167. let zeroData = {
  2168. labels: realData.labels.slice(0, -1),
  2169. datasets: realData.datasets.map(d => {
  2170. return {
  2171. name: '',
  2172. values: zeroArray.slice(0, -1),
  2173. chartType: d.chartType
  2174. };
  2175. }),
  2176. };
  2177. if(realData.yMarkers) {
  2178. zeroData.yMarkers = [
  2179. {
  2180. value: 0,
  2181. label: ''
  2182. }
  2183. ];
  2184. }
  2185. if(realData.yRegions) {
  2186. zeroData.yRegions = [
  2187. {
  2188. start: 0,
  2189. end: 0,
  2190. label: ''
  2191. }
  2192. ];
  2193. }
  2194. return zeroData;
  2195. }
  2196. function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
  2197. let allowedSpace = chartWidth / labels.length;
  2198. let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
  2199. let calcLabels = labels.map((label, i) => {
  2200. label += "";
  2201. if(label.length > allowedLetters) {
  2202. if(!isSeries) {
  2203. if(allowedLetters-3 > 0) {
  2204. label = label.slice(0, allowedLetters-3) + " ...";
  2205. } else {
  2206. label = label.slice(0, allowedLetters) + '..';
  2207. }
  2208. } else {
  2209. let multiple = Math.ceil(label.length/allowedLetters);
  2210. if(i % multiple !== 0) {
  2211. label = "";
  2212. }
  2213. }
  2214. }
  2215. return label;
  2216. });
  2217. return calcLabels;
  2218. }
  2219. class AxisChart extends BaseChart {
  2220. constructor(parent, args) {
  2221. super(parent, args);
  2222. this.barOptions = args.barOptions || {};
  2223. this.lineOptions = args.lineOptions || {};
  2224. this.type = args.type || 'line';
  2225. this.init = 1;
  2226. this.setup();
  2227. }
  2228. configure(args) {
  2229. super.configure();
  2230. args.axisOptions = args.axisOptions || {};
  2231. args.tooltipOptions = args.tooltipOptions || {};
  2232. this.config.xAxisMode = args.axisOptions.xAxisMode || 'span';
  2233. this.config.yAxisMode = args.axisOptions.yAxisMode || 'span';
  2234. this.config.xIsSeries = args.axisOptions.xIsSeries || 0;
  2235. this.config.formatTooltipX = args.tooltipOptions.formatTooltipX;
  2236. this.config.formatTooltipY = args.tooltipOptions.formatTooltipY;
  2237. this.config.valuesOverPoints = args.valuesOverPoints;
  2238. }
  2239. setMargins() {
  2240. super.setMargins();
  2241. this.leftMargin = Y_AXIS_MARGIN;
  2242. this.rightMargin = Y_AXIS_MARGIN;
  2243. }
  2244. prepareData(data=this.data) {
  2245. return dataPrep(data, this.type);
  2246. }
  2247. prepareFirstData(data=this.data) {
  2248. return zeroDataPrep(data);
  2249. }
  2250. calc(onlyWidthChange = false) {
  2251. this.calcXPositions();
  2252. if(onlyWidthChange) return;
  2253. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  2254. }
  2255. calcXPositions() {
  2256. let s = this.state;
  2257. let labels = this.data.labels;
  2258. s.datasetLength = labels.length;
  2259. s.unitWidth = this.width/(s.datasetLength);
  2260. // Default, as per bar, and mixed. Only line will be a special case
  2261. s.xOffset = s.unitWidth/2;
  2262. // // For a pure Line Chart
  2263. // s.unitWidth = this.width/(s.datasetLength - 1);
  2264. // s.xOffset = 0;
  2265. s.xAxis = {
  2266. labels: labels,
  2267. positions: labels.map((d, i) =>
  2268. floatTwo(s.xOffset + i * s.unitWidth)
  2269. )
  2270. };
  2271. }
  2272. calcYAxisParameters(dataValues, withMinimum = 'false') {
  2273. const yPts = calcChartIntervals(dataValues, withMinimum);
  2274. const scaleMultiplier = this.height / getValueRange(yPts);
  2275. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  2276. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  2277. this.state.yAxis = {
  2278. labels: yPts,
  2279. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  2280. scaleMultiplier: scaleMultiplier,
  2281. zeroLine: zeroLine,
  2282. };
  2283. // Dependent if above changes
  2284. this.calcDatasetPoints();
  2285. this.calcYExtremes();
  2286. this.calcYRegions();
  2287. }
  2288. calcDatasetPoints() {
  2289. let s = this.state;
  2290. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  2291. s.datasets = this.data.datasets.map((d, i) => {
  2292. let values = d.values;
  2293. let cumulativeYs = d.cumulativeYs || [];
  2294. return {
  2295. name: d.name,
  2296. index: i,
  2297. chartType: d.chartType,
  2298. values: values,
  2299. yPositions: scaleAll(values),
  2300. cumulativeYs: cumulativeYs,
  2301. cumulativeYPos: scaleAll(cumulativeYs),
  2302. };
  2303. });
  2304. }
  2305. calcYExtremes() {
  2306. let s = this.state;
  2307. if(this.barOptions.stacked) {
  2308. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  2309. return;
  2310. }
  2311. s.yExtremes = new Array(s.datasetLength).fill(9999);
  2312. s.datasets.map(d => {
  2313. d.yPositions.map((pos, j) => {
  2314. if(pos < s.yExtremes[j]) {
  2315. s.yExtremes[j] = pos;
  2316. }
  2317. });
  2318. });
  2319. }
  2320. calcYRegions() {
  2321. let s = this.state;
  2322. if(this.data.yMarkers) {
  2323. this.state.yMarkers = this.data.yMarkers.map(d => {
  2324. d.position = scale(d.value, s.yAxis);
  2325. // if(!d.label.includes(':')) {
  2326. // d.label += ': ' + d.value;
  2327. // }
  2328. return d;
  2329. });
  2330. }
  2331. if(this.data.yRegions) {
  2332. this.state.yRegions = this.data.yRegions.map(d => {
  2333. d.startPos = scale(d.start, s.yAxis);
  2334. d.endPos = scale(d.end, s.yAxis);
  2335. return d;
  2336. });
  2337. }
  2338. }
  2339. getAllYValues() {
  2340. // TODO: yMarkers, regions, sums, every Y value ever
  2341. let key = 'values';
  2342. if(this.barOptions.stacked) {
  2343. key = 'cumulativeYs';
  2344. let cumulative = new Array(this.state.datasetLength).fill(0);
  2345. this.data.datasets.map((d, i) => {
  2346. let values = this.data.datasets[i].values;
  2347. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  2348. });
  2349. }
  2350. let allValueLists = this.data.datasets.map(d => d[key]);
  2351. if(this.data.yMarkers) {
  2352. allValueLists.push(this.data.yMarkers.map(d => d.value));
  2353. }
  2354. if(this.data.yRegions) {
  2355. this.data.yRegions.map(d => {
  2356. allValueLists.push([d.end, d.start]);
  2357. });
  2358. }
  2359. return [].concat(...allValueLists);
  2360. }
  2361. setupComponents() {
  2362. let componentConfigs = [
  2363. [
  2364. 'yAxis',
  2365. {
  2366. mode: this.config.yAxisMode,
  2367. width: this.width,
  2368. // pos: 'right'
  2369. },
  2370. function() {
  2371. return this.state.yAxis;
  2372. }.bind(this)
  2373. ],
  2374. [
  2375. 'xAxis',
  2376. {
  2377. mode: this.config.xAxisMode,
  2378. height: this.height,
  2379. // pos: 'right'
  2380. },
  2381. function() {
  2382. let s = this.state;
  2383. s.xAxis.calcLabels = getShortenedLabels(this.width,
  2384. s.xAxis.labels, this.config.xIsSeries);
  2385. return s.xAxis;
  2386. }.bind(this)
  2387. ],
  2388. [
  2389. 'yRegions',
  2390. {
  2391. width: this.width,
  2392. pos: 'right'
  2393. },
  2394. function() {
  2395. return this.state.yRegions;
  2396. }.bind(this)
  2397. ],
  2398. ];
  2399. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  2400. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  2401. let barsConfigs = barDatasets.map(d => {
  2402. let index = d.index;
  2403. return [
  2404. 'barGraph' + '-' + d.index,
  2405. {
  2406. index: index,
  2407. color: this.colors[index],
  2408. stacked: this.barOptions.stacked,
  2409. // same for all datasets
  2410. valuesOverPoints: this.config.valuesOverPoints,
  2411. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  2412. },
  2413. function() {
  2414. let s = this.state;
  2415. let d = s.datasets[index];
  2416. let stacked = this.barOptions.stacked;
  2417. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  2418. let barsWidth = s.unitWidth * (1 - spaceRatio);
  2419. let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
  2420. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
  2421. if(!stacked) {
  2422. xPositions = xPositions.map(p => p + barWidth * index);
  2423. }
  2424. let labels = new Array(s.datasetLength).fill('');
  2425. if(this.config.valuesOverPoints) {
  2426. if(stacked && d.index === s.datasets.length - 1) {
  2427. labels = d.cumulativeYs;
  2428. } else {
  2429. labels = d.values;
  2430. }
  2431. }
  2432. let offsets = new Array(s.datasetLength).fill(0);
  2433. if(stacked) {
  2434. offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
  2435. }
  2436. return {
  2437. xPositions: xPositions,
  2438. yPositions: d.yPositions,
  2439. offsets: offsets,
  2440. // values: d.values,
  2441. labels: labels,
  2442. zeroLine: s.yAxis.zeroLine,
  2443. barsWidth: barsWidth,
  2444. barWidth: barWidth,
  2445. };
  2446. }.bind(this)
  2447. ];
  2448. });
  2449. let lineConfigs = lineDatasets.map(d => {
  2450. let index = d.index;
  2451. return [
  2452. 'lineGraph' + '-' + d.index,
  2453. {
  2454. index: index,
  2455. color: this.colors[index],
  2456. svgDefs: this.svgDefs,
  2457. heatline: this.lineOptions.heatline,
  2458. regionFill: this.lineOptions.regionFill,
  2459. hideDots: this.lineOptions.hideDots,
  2460. hideLine: this.lineOptions.hideLine,
  2461. // same for all datasets
  2462. valuesOverPoints: this.config.valuesOverPoints,
  2463. },
  2464. function() {
  2465. let s = this.state;
  2466. let d = s.datasets[index];
  2467. return {
  2468. xPositions: s.xAxis.positions,
  2469. yPositions: d.yPositions,
  2470. values: d.values,
  2471. zeroLine: s.yAxis.zeroLine,
  2472. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
  2473. };
  2474. }.bind(this)
  2475. ];
  2476. });
  2477. let markerConfigs = [
  2478. [
  2479. 'yMarkers',
  2480. {
  2481. width: this.width,
  2482. pos: 'right'
  2483. },
  2484. function() {
  2485. return this.state.yMarkers;
  2486. }.bind(this)
  2487. ]
  2488. ];
  2489. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  2490. let optionals = ['yMarkers', 'yRegions'];
  2491. this.dataUnitComponents = [];
  2492. this.components = new Map(componentConfigs
  2493. .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
  2494. .map(args => {
  2495. let component = getComponent(...args);
  2496. if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  2497. this.dataUnitComponents.push(component);
  2498. }
  2499. return [args[0], component];
  2500. }));
  2501. }
  2502. bindTooltip() {
  2503. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  2504. this.chartWrapper.addEventListener('mousemove', (e) => {
  2505. let o = getOffset(this.chartWrapper);
  2506. let relX = e.pageX - o.left - this.leftMargin;
  2507. let relY = e.pageY - o.top - this.translateY;
  2508. if(relY < this.height + this.translateY * 2) {
  2509. this.mapTooltipXPosition(relX);
  2510. } else {
  2511. this.tip.hideTip();
  2512. }
  2513. });
  2514. }
  2515. mapTooltipXPosition(relX) {
  2516. let s = this.state;
  2517. if(!s.yExtremes) return;
  2518. let formatY = this.config.formatTooltipY;
  2519. let formatX = this.config.formatTooltipX;
  2520. let titles = s.xAxis.labels;
  2521. if(formatX && formatX(titles[0])) {
  2522. titles = titles.map(d=>formatX(d));
  2523. }
  2524. formatY = formatY && formatY(s.yAxis.labels[0]) ? formatY : 0;
  2525. for(var i=s.datasetLength - 1; i >= 0 ; i--) {
  2526. let xVal = s.xAxis.positions[i];
  2527. // let delta = i === 0 ? s.unitWidth : xVal - s.xAxis.positions[i-1];
  2528. if(relX > xVal - s.unitWidth/2) {
  2529. let x = xVal + this.leftMargin;
  2530. let y = s.yExtremes[i] + this.translateY;
  2531. let values = this.data.datasets.map((set, j) => {
  2532. return {
  2533. title: set.name,
  2534. value: formatY ? formatY(set.values[i]) : set.values[i],
  2535. color: this.colors[j],
  2536. };
  2537. });
  2538. this.tip.setValues(x, y, {name: titles[i], value: ''}, values, i);
  2539. this.tip.showTip();
  2540. break;
  2541. }
  2542. }
  2543. }
  2544. renderLegend() {
  2545. let s = this.data;
  2546. this.statsWrapper.textContent = '';
  2547. if(s.datasets.length > 1) {
  2548. s.datasets.map((d, i) => {
  2549. let stats = $.create('div', {
  2550. className: 'stats',
  2551. inside: this.statsWrapper
  2552. });
  2553. stats.innerHTML = `<span class="indicator">
  2554. <i style="background: ${this.colors[i]}"></i>
  2555. ${d.name}
  2556. </span>`;
  2557. });
  2558. }
  2559. }
  2560. makeOverlay() {
  2561. if(this.init) {
  2562. this.init = 0;
  2563. return;
  2564. }
  2565. if(this.overlayGuides) {
  2566. this.overlayGuides.forEach(g => {
  2567. let o = g.overlay;
  2568. o.parentNode.removeChild(o);
  2569. });
  2570. }
  2571. this.overlayGuides = this.dataUnitComponents.map(c => {
  2572. return {
  2573. type: c.unitType,
  2574. overlay: undefined,
  2575. units: c.units,
  2576. };
  2577. });
  2578. if(this.state.currentIndex === undefined) {
  2579. this.state.currentIndex = this.state.datasetLength - 1;
  2580. }
  2581. // Render overlays
  2582. this.overlayGuides.map(d => {
  2583. let currentUnit = d.units[this.state.currentIndex];
  2584. d.overlay = makeOverlay[d.type](currentUnit);
  2585. this.drawArea.appendChild(d.overlay);
  2586. });
  2587. }
  2588. updateOverlayGuides() {
  2589. if(this.overlayGuides) {
  2590. this.overlayGuides.forEach(g => {
  2591. let o = g.overlay;
  2592. o.parentNode.removeChild(o);
  2593. });
  2594. }
  2595. }
  2596. bindOverlay() {
  2597. this.parent.addEventListener('data-select', () => {
  2598. this.updateOverlay();
  2599. });
  2600. }
  2601. bindUnits() {
  2602. this.dataUnitComponents.map(c => {
  2603. c.units.map(unit => {
  2604. unit.addEventListener('click', () => {
  2605. let index = unit.getAttribute('data-point-index');
  2606. this.setCurrentDataPoint(index);
  2607. });
  2608. });
  2609. });
  2610. // Note: Doesn't work as tooltip is absolutely positioned
  2611. this.tip.container.addEventListener('click', () => {
  2612. let index = this.tip.container.getAttribute('data-point-index');
  2613. this.setCurrentDataPoint(index);
  2614. });
  2615. }
  2616. updateOverlay() {
  2617. this.overlayGuides.map(d => {
  2618. let currentUnit = d.units[this.state.currentIndex];
  2619. updateOverlay[d.type](currentUnit, d.overlay);
  2620. });
  2621. }
  2622. onLeftArrow() {
  2623. this.setCurrentDataPoint(this.state.currentIndex - 1);
  2624. }
  2625. onRightArrow() {
  2626. this.setCurrentDataPoint(this.state.currentIndex + 1);
  2627. }
  2628. getDataPoint(index=this.state.currentIndex) {
  2629. let s = this.state;
  2630. let data_point = {
  2631. index: index,
  2632. label: s.xAxis.labels[index],
  2633. values: s.datasets.map(d => d.values[index])
  2634. };
  2635. return data_point;
  2636. }
  2637. setCurrentDataPoint(index) {
  2638. let s = this.state;
  2639. index = parseInt(index);
  2640. if(index < 0) index = 0;
  2641. if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  2642. if(index === s.currentIndex) return;
  2643. s.currentIndex = index;
  2644. fire(this.parent, "data-select", this.getDataPoint());
  2645. }
  2646. // API
  2647. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  2648. super.addDataPoint(label, datasetValues, index);
  2649. this.data.labels.splice(index, 0, label);
  2650. this.data.datasets.map((d, i) => {
  2651. d.values.splice(index, 0, datasetValues[i]);
  2652. });
  2653. this.update(this.data);
  2654. }
  2655. removeDataPoint(index = this.state.datasetLength-1) {
  2656. if (this.data.labels.length <= 1) {
  2657. return;
  2658. }
  2659. super.removeDataPoint(index);
  2660. this.data.labels.splice(index, 1);
  2661. this.data.datasets.map(d => {
  2662. d.values.splice(index, 1);
  2663. });
  2664. this.update(this.data);
  2665. }
  2666. updateDataset(datasetValues, index=0) {
  2667. this.data.datasets[index].values = datasetValues;
  2668. this.update(this.data);
  2669. }
  2670. // addDataset(dataset, index) {}
  2671. // removeDataset(index = 0) {}
  2672. updateDatasets(datasets) {
  2673. this.data.datasets.map((d, i) => {
  2674. if(datasets[i]) {
  2675. d.values = datasets[i];
  2676. }
  2677. });
  2678. this.update(this.data);
  2679. }
  2680. // updateDataPoint(dataPoint, index = 0) {}
  2681. // addDataPoint(dataPoint, index = 0) {}
  2682. // removeDataPoint(index = 0) {}
  2683. }
  2684. // import MultiAxisChart from './charts/MultiAxisChart';
  2685. const chartTypes = {
  2686. // multiaxis: MultiAxisChart,
  2687. percentage: PercentageChart,
  2688. heatmap: Heatmap,
  2689. pie: PieChart
  2690. };
  2691. function getChartByType(chartType = 'line', parent, options) {
  2692. if(chartType === 'line') {
  2693. options.type = 'line';
  2694. return new AxisChart(parent, options);
  2695. } else if (chartType === 'bar') {
  2696. options.type = 'bar';
  2697. return new AxisChart(parent, options);
  2698. } else if (chartType === 'axis-mixed') {
  2699. options.type = 'line';
  2700. return new AxisChart(parent, options);
  2701. }
  2702. if (!chartTypes[chartType]) {
  2703. console.error("Undefined chart type: " + chartType);
  2704. return;
  2705. }
  2706. return new chartTypes[chartType](parent, options);
  2707. }
  2708. class Chart {
  2709. constructor(parent, options) {
  2710. return getChartByType(options.type, parent, options);
  2711. }
  2712. }
  2713. export default Chart;