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.
 
 
 

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