You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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