You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

4085 line
100 KiB

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