Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

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