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

4032 wiersze
97 KiB

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