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.
 
 
 

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