25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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