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.
 
 
 

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