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.
 
 
 

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