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.
 
 
 

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