Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

4021 wiersze
97 KiB

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