You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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