Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

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