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.
 
 
 

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