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.
 
 
 

3672 regels
86 KiB

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