Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

4004 рядки
96 KiB

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