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.
 
 
 

3333 line
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.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=this.data) {
  1073. this.data = this.prepareData(data);
  1074. this.calc(); // builds state
  1075. this.render();
  1076. }
  1077. prepareData(data=this.data) {
  1078. return data;
  1079. }
  1080. prepareFirstData(data=this.data) {
  1081. return data;
  1082. }
  1083. calc() {} // builds state
  1084. render(components=this.components, animate=true) {
  1085. if(this.config.isNavigable) {
  1086. // Remove all existing overlays
  1087. this.overlays.map(o => o.parentNode.removeChild(o));
  1088. // ref.parentNode.insertBefore(element, ref);
  1089. }
  1090. let elementsToAnimate = [];
  1091. // Can decouple to this.refreshComponents() first to save animation timeout
  1092. components.forEach(c => {
  1093. elementsToAnimate = elementsToAnimate.concat(c.update(animate));
  1094. });
  1095. if(elementsToAnimate.length > 0) {
  1096. runSMILAnimation(this.container, this.svg, elementsToAnimate);
  1097. setTimeout(() => {
  1098. components.forEach(c => c.make());
  1099. this.updateNav();
  1100. }, CHART_POST_ANIMATE_TIMEOUT);
  1101. } else {
  1102. components.forEach(c => c.make());
  1103. this.updateNav();
  1104. }
  1105. }
  1106. updateNav() {
  1107. if(this.config.isNavigable) {
  1108. this.makeOverlay();
  1109. this.bindUnits();
  1110. }
  1111. }
  1112. makeChartArea() {
  1113. if(this.svg) {
  1114. this.container.removeChild(this.svg);
  1115. }
  1116. let titleAreaHeight = 0;
  1117. let legendAreaHeight = 0;
  1118. if(this.title.length) {
  1119. titleAreaHeight = 30;
  1120. }
  1121. if(this.showLegend) {
  1122. legendAreaHeight = 30;
  1123. }
  1124. this.svg = makeSVGContainer(
  1125. this.container,
  1126. 'frappe-chart chart',
  1127. this.baseWidth,
  1128. this.baseHeight + titleAreaHeight + legendAreaHeight
  1129. );
  1130. this.svgDefs = makeSVGDefs(this.svg);
  1131. if(this.title.length) {
  1132. this.titleEL = makeText(
  1133. 'title',
  1134. this.leftMargin - AXIS_TICK_LENGTH,
  1135. this.topMargin,
  1136. this.title,
  1137. 11
  1138. );
  1139. this.svg.appendChild(this.titleEL);
  1140. }
  1141. let top = this.topMargin + titleAreaHeight;
  1142. this.drawArea = makeSVGGroup(
  1143. this.svg,
  1144. this.type + '-chart',
  1145. `translate(${this.leftMargin}, ${top})`
  1146. );
  1147. top = this.baseHeight + titleAreaHeight;
  1148. this.legendArea = makeSVGGroup(
  1149. this.svg,
  1150. 'chart-legend',
  1151. `translate(${this.leftMargin}, ${top})`
  1152. );
  1153. }
  1154. renderLegend() {}
  1155. setupNavigation(init=false) {
  1156. if(!this.config.isNavigable) return;
  1157. if(init) {
  1158. this.bindOverlay();
  1159. this.keyActions = {
  1160. '13': this.onEnterKey.bind(this),
  1161. '37': this.onLeftArrow.bind(this),
  1162. '38': this.onUpArrow.bind(this),
  1163. '39': this.onRightArrow.bind(this),
  1164. '40': this.onDownArrow.bind(this),
  1165. };
  1166. document.addEventListener('keydown', (e) => {
  1167. if(isElementInViewport(this.container)) {
  1168. e = e || window.event;
  1169. if(this.keyActions[e.keyCode]) {
  1170. this.keyActions[e.keyCode]();
  1171. }
  1172. }
  1173. });
  1174. }
  1175. }
  1176. makeOverlay() {}
  1177. updateOverlay() {}
  1178. bindOverlay() {}
  1179. bindUnits() {}
  1180. onLeftArrow() {}
  1181. onRightArrow() {}
  1182. onUpArrow() {}
  1183. onDownArrow() {}
  1184. onEnterKey() {}
  1185. addDataPoint() {}
  1186. removeDataPoint() {}
  1187. getDataPoint() {}
  1188. setCurrentDataPoint() {}
  1189. updateDataset() {}
  1190. getDifferentChart(type) {
  1191. const currentType = this.type;
  1192. let args = this.rawChartArgs;
  1193. if(type === currentType) return;
  1194. if(!ALL_CHART_TYPES.includes(type)) {
  1195. console.error(`'${type}' is not a valid chart type.`);
  1196. }
  1197. if(!COMPATIBLE_CHARTS[currentType].includes(type)) {
  1198. console.error(`'${currentType}' chart cannot be converted to a '${type}' chart.`);
  1199. }
  1200. // whether the new chart can use the existing colors
  1201. const useColor = DATA_COLOR_DIVISIONS[currentType] === DATA_COLOR_DIVISIONS[type];
  1202. // Okay, this is anticlimactic
  1203. // this function will need to actually be 'changeChartType(type)'
  1204. // that will update only the required elements, but for now ...
  1205. args.type = type;
  1206. args.colors = useColor ? args.colors : undefined;
  1207. return new Chart(this.parent, args);
  1208. }
  1209. unbindWindowEvents(){
  1210. window.removeEventListener('resize', () => this.draw(true));
  1211. window.removeEventListener('orientationchange', () => this.draw(true));
  1212. }
  1213. }
  1214. class AggregationChart extends BaseChart {
  1215. constructor(parent, args) {
  1216. super(parent, args);
  1217. }
  1218. configure(args) {
  1219. super.configure(args);
  1220. this.config.maxSlices = args.maxSlices || 20;
  1221. this.config.maxLegendPoints = args.maxLegendPoints || 20;
  1222. }
  1223. calc() {
  1224. let s = this.state;
  1225. let maxSlices = this.config.maxSlices;
  1226. s.sliceTotals = [];
  1227. let allTotals = this.data.labels.map((label, i) => {
  1228. let total = 0;
  1229. this.data.datasets.map(e => {
  1230. total += e.values[i];
  1231. });
  1232. return [total, label];
  1233. }).filter(d => { return d[0] > 0; }); // keep only positive results
  1234. let totals = allTotals;
  1235. if(allTotals.length > maxSlices) {
  1236. // Prune and keep a grey area for rest as per maxSlices
  1237. allTotals.sort((a, b) => { return b[0] - a[0]; });
  1238. totals = allTotals.slice(0, maxSlices-1);
  1239. let remaining = allTotals.slice(maxSlices-1);
  1240. let sumOfRemaining = 0;
  1241. remaining.map(d => {sumOfRemaining += d[0];});
  1242. totals.push([sumOfRemaining, 'Rest']);
  1243. this.colors[maxSlices-1] = 'grey';
  1244. }
  1245. s.labels = [];
  1246. totals.map(d => {
  1247. s.sliceTotals.push(d[0]);
  1248. s.labels.push(d[1]);
  1249. });
  1250. }
  1251. renderLegend() {
  1252. // let s = this.state;
  1253. // this.statsWrapper.textContent = '';
  1254. // this.legendTotals = s.sliceTotals.slice(0, this.config.maxLegendPoints);
  1255. // let xValues = s.labels;
  1256. // this.legendTotals.map((d, i) => {
  1257. // if(d) {
  1258. // let stats = $.create('div', {
  1259. // className: 'stats',
  1260. // inside: this.statsWrapper
  1261. // });
  1262. // stats.innerHTML = `<span class="indicator">
  1263. // <i style="background: ${this.colors[i]}"></i>
  1264. // <span class="text-muted">${xValues[i]}:</span>
  1265. // ${d}
  1266. // </span>`;
  1267. // }
  1268. // });
  1269. }
  1270. }
  1271. class PercentageChart extends AggregationChart {
  1272. constructor(parent, args) {
  1273. super(parent, args);
  1274. this.type = 'percentage';
  1275. this.setup();
  1276. }
  1277. makeChartArea() {
  1278. this.container.className += ' ' + 'graph-focus-margin';
  1279. this.container.style.marginTop = '45px';
  1280. // this.statsWrapper.className += ' ' + 'graph-focus-margin';
  1281. // this.statsWrapper.style.marginBottom = '30px';
  1282. // this.statsWrapper.style.paddingTop = '0px';
  1283. this.svg = $.create('div', {
  1284. className: 'div',
  1285. inside: this.container
  1286. });
  1287. this.chart = $.create('div', {
  1288. className: 'progress-chart',
  1289. inside: this.svg
  1290. });
  1291. this.percentageBar = $.create('div', {
  1292. className: 'progress',
  1293. inside: this.chart
  1294. });
  1295. }
  1296. render() {
  1297. let s = this.state;
  1298. this.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
  1299. s.slices = [];
  1300. s.sliceTotals.map((total, i) => {
  1301. let slice = $.create('div', {
  1302. className: `progress-bar`,
  1303. 'data-index': i,
  1304. inside: this.percentageBar,
  1305. styles: {
  1306. background: this.colors[i],
  1307. width: total*100/this.grandTotal + "%"
  1308. }
  1309. });
  1310. s.slices.push(slice);
  1311. });
  1312. }
  1313. bindTooltip() {
  1314. let s = this.state;
  1315. this.container.addEventListener('mousemove', (e) => {
  1316. let slice = e.target;
  1317. if(slice.classList.contains('progress-bar')) {
  1318. let i = slice.getAttribute('data-index');
  1319. let gOff = getOffset(this.container), pOff = getOffset(slice);
  1320. let x = pOff.left - gOff.left + slice.offsetWidth/2;
  1321. let y = pOff.top - gOff.top - 6;
  1322. let title = (this.formattedLabels && this.formattedLabels.length>0
  1323. ? this.formattedLabels[i] : this.state.labels[i]) + ': ';
  1324. let percent = (s.sliceTotals[i]*100/this.grandTotal).toFixed(1);
  1325. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  1326. this.tip.showTip();
  1327. }
  1328. });
  1329. }
  1330. }
  1331. class ChartComponent {
  1332. constructor({
  1333. layerClass = '',
  1334. layerTransform = '',
  1335. constants,
  1336. getData,
  1337. makeElements,
  1338. animateElements
  1339. }) {
  1340. this.layerTransform = layerTransform;
  1341. this.constants = constants;
  1342. this.makeElements = makeElements;
  1343. this.getData = getData;
  1344. this.animateElements = animateElements;
  1345. this.store = [];
  1346. this.layerClass = layerClass;
  1347. this.layerClass = typeof(this.layerClass) === 'function'
  1348. ? this.layerClass() : this.layerClass;
  1349. this.refresh();
  1350. }
  1351. refresh(data) {
  1352. this.data = data || this.getData();
  1353. }
  1354. setup(parent) {
  1355. this.layer = makeSVGGroup(parent, this.layerClass, this.layerTransform);
  1356. }
  1357. make() {
  1358. this.render(this.data);
  1359. this.oldData = this.data;
  1360. }
  1361. render(data) {
  1362. this.store = this.makeElements(data);
  1363. this.layer.textContent = '';
  1364. this.store.forEach(element => {
  1365. this.layer.appendChild(element);
  1366. });
  1367. }
  1368. update(animate = true) {
  1369. this.refresh();
  1370. let animateElements = [];
  1371. if(animate) {
  1372. animateElements = this.animateElements(this.data);
  1373. }
  1374. return animateElements;
  1375. }
  1376. }
  1377. let componentConfigs = {
  1378. pieSlices: {
  1379. layerClass: 'pie-slices',
  1380. makeElements(data) {
  1381. return data.sliceStrings.map((s, i) =>{
  1382. let slice = makePath(s, 'pie-path', 'none', data.colors[i]);
  1383. slice.style.transition = 'transform .3s;';
  1384. return slice;
  1385. });
  1386. },
  1387. animateElements(newData) {
  1388. return this.store.map((slice, i) =>
  1389. animatePathStr(slice, newData.sliceStrings[i])
  1390. );
  1391. }
  1392. },
  1393. yAxis: {
  1394. layerClass: 'y axis',
  1395. makeElements(data) {
  1396. return data.positions.map((position, i) =>
  1397. yLine(position, data.labels[i], this.constants.width,
  1398. {mode: this.constants.mode, pos: this.constants.pos})
  1399. );
  1400. },
  1401. animateElements(newData) {
  1402. let newPos = newData.positions;
  1403. let newLabels = newData.labels;
  1404. let oldPos = this.oldData.positions;
  1405. let oldLabels = this.oldData.labels;
  1406. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1407. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1408. this.render({
  1409. positions: oldPos,
  1410. labels: newLabels
  1411. });
  1412. return this.store.map((line, i) => {
  1413. return translateHoriLine(
  1414. line, newPos[i], oldPos[i]
  1415. );
  1416. });
  1417. }
  1418. },
  1419. xAxis: {
  1420. layerClass: 'x axis',
  1421. makeElements(data) {
  1422. return data.positions.map((position, i) =>
  1423. xLine(position, data.calcLabels[i], this.constants.height,
  1424. {mode: this.constants.mode, pos: this.constants.pos})
  1425. );
  1426. },
  1427. animateElements(newData) {
  1428. let newPos = newData.positions;
  1429. let newLabels = newData.calcLabels;
  1430. let oldPos = this.oldData.positions;
  1431. let oldLabels = this.oldData.calcLabels;
  1432. [oldPos, newPos] = equilizeNoOfElements(oldPos, newPos);
  1433. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1434. this.render({
  1435. positions: oldPos,
  1436. calcLabels: newLabels
  1437. });
  1438. return this.store.map((line, i) => {
  1439. return translateVertLine(
  1440. line, newPos[i], oldPos[i]
  1441. );
  1442. });
  1443. }
  1444. },
  1445. yMarkers: {
  1446. layerClass: 'y-markers',
  1447. makeElements(data) {
  1448. return data.map(marker =>
  1449. yMarker(marker.position, marker.label, this.constants.width,
  1450. {pos:'right', mode: 'span', lineType: 'dashed'})
  1451. );
  1452. },
  1453. animateElements(newData) {
  1454. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1455. let newPos = newData.map(d => d.position);
  1456. let newLabels = newData.map(d => d.label);
  1457. let oldPos = this.oldData.map(d => d.position);
  1458. this.render(oldPos.map((pos, i) => {
  1459. return {
  1460. position: oldPos[i],
  1461. label: newLabels[i]
  1462. };
  1463. }));
  1464. return this.store.map((line, i) => {
  1465. return translateHoriLine(
  1466. line, newPos[i], oldPos[i]
  1467. );
  1468. });
  1469. }
  1470. },
  1471. yRegions: {
  1472. layerClass: 'y-regions',
  1473. makeElements(data) {
  1474. return data.map(region =>
  1475. yRegion(region.startPos, region.endPos, this.constants.width,
  1476. region.label)
  1477. );
  1478. },
  1479. animateElements(newData) {
  1480. [this.oldData, newData] = equilizeNoOfElements(this.oldData, newData);
  1481. let newPos = newData.map(d => d.endPos);
  1482. let newLabels = newData.map(d => d.label);
  1483. let newStarts = newData.map(d => d.startPos);
  1484. let oldPos = this.oldData.map(d => d.endPos);
  1485. let oldStarts = this.oldData.map(d => d.startPos);
  1486. this.render(oldPos.map((pos, i) => {
  1487. return {
  1488. startPos: oldStarts[i],
  1489. endPos: oldPos[i],
  1490. label: newLabels[i]
  1491. };
  1492. }));
  1493. let animateElements = [];
  1494. this.store.map((rectGroup, i) => {
  1495. animateElements = animateElements.concat(animateRegion(
  1496. rectGroup, newStarts[i], newPos[i], oldPos[i]
  1497. ));
  1498. });
  1499. return animateElements;
  1500. }
  1501. },
  1502. barGraph: {
  1503. layerClass: function() { return 'dataset-units dataset-bars dataset-' + this.constants.index; },
  1504. makeElements(data) {
  1505. let c = this.constants;
  1506. this.unitType = 'bar';
  1507. this.units = data.yPositions.map((y, j) => {
  1508. return datasetBar(
  1509. data.xPositions[j],
  1510. y,
  1511. data.barWidth,
  1512. c.color,
  1513. data.labels[j],
  1514. j,
  1515. data.offsets[j],
  1516. {
  1517. zeroLine: data.zeroLine,
  1518. barsWidth: data.barsWidth,
  1519. minHeight: c.minHeight
  1520. }
  1521. );
  1522. });
  1523. return this.units;
  1524. },
  1525. animateElements(newData) {
  1526. let newXPos = newData.xPositions;
  1527. let newYPos = newData.yPositions;
  1528. let newOffsets = newData.offsets;
  1529. let newLabels = newData.labels;
  1530. let oldXPos = this.oldData.xPositions;
  1531. let oldYPos = this.oldData.yPositions;
  1532. let oldOffsets = this.oldData.offsets;
  1533. let oldLabels = this.oldData.labels;
  1534. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1535. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1536. [oldOffsets, newOffsets] = equilizeNoOfElements(oldOffsets, newOffsets);
  1537. [oldLabels, newLabels] = equilizeNoOfElements(oldLabels, newLabels);
  1538. this.render({
  1539. xPositions: oldXPos,
  1540. yPositions: oldYPos,
  1541. offsets: oldOffsets,
  1542. labels: newLabels,
  1543. zeroLine: this.oldData.zeroLine,
  1544. barsWidth: this.oldData.barsWidth,
  1545. barWidth: this.oldData.barWidth,
  1546. });
  1547. let animateElements = [];
  1548. this.store.map((bar, i) => {
  1549. animateElements = animateElements.concat(animateBar(
  1550. bar, newXPos[i], newYPos[i], newData.barWidth, newOffsets[i],
  1551. {zeroLine: newData.zeroLine}
  1552. ));
  1553. });
  1554. return animateElements;
  1555. }
  1556. },
  1557. lineGraph: {
  1558. layerClass: function() { return 'dataset-units dataset-line dataset-' + this.constants.index; },
  1559. makeElements(data) {
  1560. let c = this.constants;
  1561. this.unitType = 'dot';
  1562. this.paths = {};
  1563. if(!c.hideLine) {
  1564. this.paths = getPaths(
  1565. data.xPositions,
  1566. data.yPositions,
  1567. c.color,
  1568. {
  1569. heatline: c.heatline,
  1570. regionFill: c.regionFill
  1571. },
  1572. {
  1573. svgDefs: c.svgDefs,
  1574. zeroLine: data.zeroLine
  1575. }
  1576. );
  1577. }
  1578. this.units = [];
  1579. if(!c.hideDots) {
  1580. this.units = data.yPositions.map((y, j) => {
  1581. return datasetDot(
  1582. data.xPositions[j],
  1583. y,
  1584. data.radius,
  1585. c.color,
  1586. (c.valuesOverPoints ? data.values[j] : ''),
  1587. j
  1588. );
  1589. });
  1590. }
  1591. return Object.values(this.paths).concat(this.units);
  1592. },
  1593. animateElements(newData) {
  1594. let newXPos = newData.xPositions;
  1595. let newYPos = newData.yPositions;
  1596. let newValues = newData.values;
  1597. let oldXPos = this.oldData.xPositions;
  1598. let oldYPos = this.oldData.yPositions;
  1599. let oldValues = this.oldData.values;
  1600. [oldXPos, newXPos] = equilizeNoOfElements(oldXPos, newXPos);
  1601. [oldYPos, newYPos] = equilizeNoOfElements(oldYPos, newYPos);
  1602. [oldValues, newValues] = equilizeNoOfElements(oldValues, newValues);
  1603. this.render({
  1604. xPositions: oldXPos,
  1605. yPositions: oldYPos,
  1606. values: newValues,
  1607. zeroLine: this.oldData.zeroLine,
  1608. radius: this.oldData.radius,
  1609. });
  1610. let animateElements = [];
  1611. if(Object.keys(this.paths).length) {
  1612. animateElements = animateElements.concat(animatePath(
  1613. this.paths, newXPos, newYPos, newData.zeroLine));
  1614. }
  1615. if(this.units.length) {
  1616. this.units.map((dot, i) => {
  1617. animateElements = animateElements.concat(animateDot(
  1618. dot, newXPos[i], newYPos[i]));
  1619. });
  1620. }
  1621. return animateElements;
  1622. }
  1623. }
  1624. };
  1625. function getComponent(name, constants, getData) {
  1626. let keys = Object.keys(componentConfigs).filter(k => name.includes(k));
  1627. let config = componentConfigs[keys[0]];
  1628. Object.assign(config, {
  1629. constants: constants,
  1630. getData: getData
  1631. });
  1632. return new ChartComponent(config);
  1633. }
  1634. class PieChart extends AggregationChart {
  1635. constructor(parent, args) {
  1636. super(parent, args);
  1637. this.type = 'pie';
  1638. this.initTimeout = 0;
  1639. this.setup();
  1640. }
  1641. configure(args) {
  1642. super.configure(args);
  1643. this.mouseMove = this.mouseMove.bind(this);
  1644. this.mouseLeave = this.mouseLeave.bind(this);
  1645. this.hoverRadio = args.hoverRadio || 0.1;
  1646. this.config.startAngle = args.startAngle || 0;
  1647. this.clockWise = args.clockWise || false;
  1648. }
  1649. prepareFirstData(data=this.data) {
  1650. this.init = 1;
  1651. return data;
  1652. }
  1653. calc() {
  1654. super.calc();
  1655. let s = this.state;
  1656. this.center = {
  1657. x: this.width / 2,
  1658. y: this.height / 2
  1659. };
  1660. this.radius = (this.height > this.width ? this.center.x : this.center.y);
  1661. s.grandTotal = s.sliceTotals.reduce((a, b) => a + b, 0);
  1662. this.calcSlices();
  1663. }
  1664. calcSlices() {
  1665. let s = this.state;
  1666. const { radius, clockWise } = this;
  1667. const prevSlicesProperties = s.slicesProperties || [];
  1668. s.sliceStrings = [];
  1669. s.slicesProperties = [];
  1670. let curAngle = 180 - this.config.startAngle;
  1671. s.sliceTotals.map((total, i) => {
  1672. const startAngle = curAngle;
  1673. const originDiffAngle = (total / s.grandTotal) * FULL_ANGLE;
  1674. const diffAngle = clockWise ? -originDiffAngle : originDiffAngle;
  1675. const endAngle = curAngle = curAngle + diffAngle;
  1676. const startPosition = getPositionByAngle(startAngle, radius);
  1677. const endPosition = getPositionByAngle(endAngle, radius);
  1678. const prevProperty = this.init && prevSlicesProperties[i];
  1679. let curStart,curEnd;
  1680. if(this.init) {
  1681. curStart = prevProperty ? prevProperty.startPosition : startPosition;
  1682. curEnd = prevProperty ? prevProperty.endPosition : startPosition;
  1683. } else {
  1684. curStart = startPosition;
  1685. curEnd = endPosition;
  1686. }
  1687. const curPath = makeArcPathStr(curStart, curEnd, this.center, this.radius, this.clockWise);
  1688. s.sliceStrings.push(curPath);
  1689. s.slicesProperties.push({
  1690. startPosition,
  1691. endPosition,
  1692. value: total,
  1693. total: s.grandTotal,
  1694. startAngle,
  1695. endAngle,
  1696. angle: diffAngle
  1697. });
  1698. });
  1699. this.init = 0;
  1700. }
  1701. setupComponents() {
  1702. let s = this.state;
  1703. let componentConfigs = [
  1704. [
  1705. 'pieSlices',
  1706. { },
  1707. function() {
  1708. return {
  1709. sliceStrings: s.sliceStrings,
  1710. colors: this.colors
  1711. };
  1712. }.bind(this)
  1713. ]
  1714. ];
  1715. this.components = new Map(componentConfigs
  1716. .map(args => {
  1717. let component = getComponent(...args);
  1718. return [args[0], component];
  1719. }));
  1720. }
  1721. calTranslateByAngle(property){
  1722. const{radius,hoverRadio} = this;
  1723. const position = getPositionByAngle(property.startAngle+(property.angle / 2),radius);
  1724. return `translate3d(${(position.x) * hoverRadio}px,${(position.y) * hoverRadio}px,0)`;
  1725. }
  1726. hoverSlice(path,i,flag,e){
  1727. if(!path) return;
  1728. const color = this.colors[i];
  1729. if(flag) {
  1730. transform(path, this.calTranslateByAngle(this.state.slicesProperties[i]));
  1731. path.style.fill = lightenDarkenColor(color, 50);
  1732. let g_off = getOffset(this.svg);
  1733. let x = e.pageX - g_off.left + 10;
  1734. let y = e.pageY - g_off.top - 10;
  1735. let title = (this.formatted_labels && this.formatted_labels.length > 0
  1736. ? this.formatted_labels[i] : this.state.labels[i]) + ': ';
  1737. let percent = (this.state.sliceTotals[i] * 100 / this.state.grandTotal).toFixed(1);
  1738. this.tip.setValues(x, y, {name: title, value: percent + "%"});
  1739. this.tip.showTip();
  1740. } else {
  1741. transform(path,'translate3d(0,0,0)');
  1742. this.tip.hideTip();
  1743. path.style.fill = color;
  1744. }
  1745. }
  1746. bindTooltip() {
  1747. this.container.addEventListener('mousemove', this.mouseMove);
  1748. this.container.addEventListener('mouseleave', this.mouseLeave);
  1749. }
  1750. mouseMove(e){
  1751. const target = e.target;
  1752. let slices = this.components.get('pieSlices').store;
  1753. let prevIndex = this.curActiveSliceIndex;
  1754. let prevAcitve = this.curActiveSlice;
  1755. if(slices.includes(target)) {
  1756. let i = slices.indexOf(target);
  1757. this.hoverSlice(prevAcitve, prevIndex,false);
  1758. this.curActiveSlice = target;
  1759. this.curActiveSliceIndex = i;
  1760. this.hoverSlice(target, i, true, e);
  1761. } else {
  1762. this.mouseLeave();
  1763. }
  1764. }
  1765. mouseLeave(){
  1766. this.hoverSlice(this.curActiveSlice,this.curActiveSliceIndex,false);
  1767. }
  1768. }
  1769. // Playing around with dates
  1770. const NO_OF_YEAR_MONTHS = 12;
  1771. const NO_OF_DAYS_IN_WEEK = 7;
  1772. const NO_OF_MILLIS = 1000;
  1773. const SEC_IN_DAY = 86400;
  1774. const MONTH_NAMES = ["January", "February", "March", "April", "May", "June",
  1775. "July", "August", "September", "October", "November", "December"];
  1776. // https://stackoverflow.com/a/11252167/6495043
  1777. function treatAsUtc(date) {
  1778. let result = new Date(date);
  1779. result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
  1780. return result;
  1781. }
  1782. function getDdMmYyyy(date) {
  1783. let dd = date.getDate();
  1784. let mm = date.getMonth() + 1; // getMonth() is zero-based
  1785. return [
  1786. (dd>9 ? '' : '0') + dd,
  1787. (mm>9 ? '' : '0') + mm,
  1788. date.getFullYear()
  1789. ].join('-');
  1790. }
  1791. function clone(date) {
  1792. return new Date(date.getTime());
  1793. }
  1794. function getWeeksBetween(startDate, endDate) {
  1795. return Math.ceil(getDaysBetween(startDate, endDate) / NO_OF_DAYS_IN_WEEK);
  1796. }
  1797. function getDaysBetween(startDate, endDate) {
  1798. let millisecondsPerDay = SEC_IN_DAY * NO_OF_MILLIS;
  1799. return (treatAsUtc(endDate) - treatAsUtc(startDate)) / millisecondsPerDay;
  1800. }
  1801. function getMonthName(i, short=false) {
  1802. let monthName = MONTH_NAMES[i];
  1803. return short ? monthName.slice(0, 3) : monthName;
  1804. }
  1805. // mutates
  1806. function setDayToSunday(date) {
  1807. const day = date.getDay();
  1808. if(day !== NO_OF_DAYS_IN_WEEK) {
  1809. addDays(date, (-1) * day);
  1810. }
  1811. return date;
  1812. }
  1813. // mutates
  1814. function addDays(date, numberOfDays) {
  1815. date.setDate(date.getDate() + numberOfDays);
  1816. }
  1817. function normalize(x) {
  1818. // Calculates mantissa and exponent of a number
  1819. // Returns normalized number and exponent
  1820. // https://stackoverflow.com/q/9383593/6495043
  1821. if(x===0) {
  1822. return [0, 0];
  1823. }
  1824. if(isNaN(x)) {
  1825. return {mantissa: -6755399441055744, exponent: 972};
  1826. }
  1827. var sig = x > 0 ? 1 : -1;
  1828. if(!isFinite(x)) {
  1829. return {mantissa: sig * 4503599627370496, exponent: 972};
  1830. }
  1831. x = Math.abs(x);
  1832. var exp = Math.floor(Math.log10(x));
  1833. var man = x/Math.pow(10, exp);
  1834. return [sig * man, exp];
  1835. }
  1836. function getChartRangeIntervals(max, min=0) {
  1837. let upperBound = Math.ceil(max);
  1838. let lowerBound = Math.floor(min);
  1839. let range = upperBound - lowerBound;
  1840. let noOfParts = range;
  1841. let partSize = 1;
  1842. // To avoid too many partitions
  1843. if(range > 5) {
  1844. if(range % 2 !== 0) {
  1845. upperBound++;
  1846. // Recalc range
  1847. range = upperBound - lowerBound;
  1848. }
  1849. noOfParts = range/2;
  1850. partSize = 2;
  1851. }
  1852. // Special case: 1 and 2
  1853. if(range <= 2) {
  1854. noOfParts = 4;
  1855. partSize = range/noOfParts;
  1856. }
  1857. // Special case: 0
  1858. if(range === 0) {
  1859. noOfParts = 5;
  1860. partSize = 1;
  1861. }
  1862. let intervals = [];
  1863. for(var i = 0; i <= noOfParts; i++){
  1864. intervals.push(lowerBound + partSize * i);
  1865. }
  1866. return intervals;
  1867. }
  1868. function getChartIntervals(maxValue, minValue=0) {
  1869. let [normalMaxValue, exponent] = normalize(maxValue);
  1870. let normalMinValue = minValue ? minValue/Math.pow(10, exponent): 0;
  1871. // Allow only 7 significant digits
  1872. normalMaxValue = normalMaxValue.toFixed(6);
  1873. let intervals = getChartRangeIntervals(normalMaxValue, normalMinValue);
  1874. intervals = intervals.map(value => value * Math.pow(10, exponent));
  1875. return intervals;
  1876. }
  1877. function calcChartIntervals(values, withMinimum=false) {
  1878. //*** Where the magic happens ***
  1879. // Calculates best-fit y intervals from given values
  1880. // and returns the interval array
  1881. let maxValue = Math.max(...values);
  1882. let minValue = Math.min(...values);
  1883. // Exponent to be used for pretty print
  1884. let exponent = 0, intervals = []; // eslint-disable-line no-unused-vars
  1885. function getPositiveFirstIntervals(maxValue, absMinValue) {
  1886. let intervals = getChartIntervals(maxValue);
  1887. let intervalSize = intervals[1] - intervals[0];
  1888. // Then unshift the negative values
  1889. let value = 0;
  1890. for(var i = 1; value < absMinValue; i++) {
  1891. value += intervalSize;
  1892. intervals.unshift((-1) * value);
  1893. }
  1894. return intervals;
  1895. }
  1896. // CASE I: Both non-negative
  1897. if(maxValue >= 0 && minValue >= 0) {
  1898. exponent = normalize(maxValue)[1];
  1899. if(!withMinimum) {
  1900. intervals = getChartIntervals(maxValue);
  1901. } else {
  1902. intervals = getChartIntervals(maxValue, minValue);
  1903. }
  1904. }
  1905. // CASE II: Only minValue negative
  1906. else if(maxValue > 0 && minValue < 0) {
  1907. // `withMinimum` irrelevant in this case,
  1908. // We'll be handling both sides of zero separately
  1909. // (both starting from zero)
  1910. // Because ceil() and floor() behave differently
  1911. // in those two regions
  1912. let absMinValue = Math.abs(minValue);
  1913. if(maxValue >= absMinValue) {
  1914. exponent = normalize(maxValue)[1];
  1915. intervals = getPositiveFirstIntervals(maxValue, absMinValue);
  1916. } else {
  1917. // Mirror: maxValue => absMinValue, then change sign
  1918. exponent = normalize(absMinValue)[1];
  1919. let posIntervals = getPositiveFirstIntervals(absMinValue, maxValue);
  1920. intervals = posIntervals.map(d => d * (-1));
  1921. }
  1922. }
  1923. // CASE III: Both non-positive
  1924. else if(maxValue <= 0 && minValue <= 0) {
  1925. // Mirrored Case I:
  1926. // Work with positives, then reverse the sign and array
  1927. let pseudoMaxValue = Math.abs(minValue);
  1928. let pseudoMinValue = Math.abs(maxValue);
  1929. exponent = normalize(pseudoMaxValue)[1];
  1930. if(!withMinimum) {
  1931. intervals = getChartIntervals(pseudoMaxValue);
  1932. } else {
  1933. intervals = getChartIntervals(pseudoMaxValue, pseudoMinValue);
  1934. }
  1935. intervals = intervals.reverse().map(d => d * (-1));
  1936. }
  1937. return intervals;
  1938. }
  1939. function getZeroIndex(yPts) {
  1940. let zeroIndex;
  1941. let interval = getIntervalSize(yPts);
  1942. if(yPts.indexOf(0) >= 0) {
  1943. // the range has a given zero
  1944. // zero-line on the chart
  1945. zeroIndex = yPts.indexOf(0);
  1946. } else if(yPts[0] > 0) {
  1947. // Minimum value is positive
  1948. // zero-line is off the chart: below
  1949. let min = yPts[0];
  1950. zeroIndex = (-1) * min / interval;
  1951. } else {
  1952. // Maximum value is negative
  1953. // zero-line is off the chart: above
  1954. let max = yPts[yPts.length - 1];
  1955. zeroIndex = (-1) * max / interval + (yPts.length - 1);
  1956. }
  1957. return zeroIndex;
  1958. }
  1959. function getIntervalSize(orderedArray) {
  1960. return orderedArray[1] - orderedArray[0];
  1961. }
  1962. function getValueRange(orderedArray) {
  1963. return orderedArray[orderedArray.length-1] - orderedArray[0];
  1964. }
  1965. function scale(val, yAxis) {
  1966. return floatTwo(yAxis.zeroLine - val * yAxis.scaleMultiplier);
  1967. }
  1968. function calcDistribution(values, distributionSize) {
  1969. // Assume non-negative values,
  1970. // implying distribution minimum at zero
  1971. let dataMaxValue = Math.max(...values);
  1972. let distributionStep = 1 / (distributionSize - 1);
  1973. let distribution = [];
  1974. for(var i = 0; i < distributionSize; i++) {
  1975. let checkpoint = dataMaxValue * (distributionStep * i);
  1976. distribution.push(checkpoint);
  1977. }
  1978. return distribution;
  1979. }
  1980. function getMaxCheckpoint(value, distribution) {
  1981. return distribution.filter(d => d < value).length;
  1982. }
  1983. const COL_SIZE = HEATMAP_SQUARE_SIZE + HEATMAP_GUTTER_SIZE;
  1984. class Heatmap extends BaseChart {
  1985. constructor(parent, options) {
  1986. super(parent, options);
  1987. this.type = 'heatmap';
  1988. this.dataPoints = options.data.dataPoints || {};
  1989. this.discreteDomains = options.discreteDomains === 0 ? 0 : 1;
  1990. this.countLabel = options.countLabel || '';
  1991. this.setup();
  1992. }
  1993. updateWidth() {
  1994. this.baseWidth = (this.state.noOfWeeks + 99) * COL_SIZE;
  1995. if(this.discreteDomains) {
  1996. this.baseWidth += (COL_SIZE * NO_OF_YEAR_MONTHS);
  1997. }
  1998. }
  1999. makeChartArea() {
  2000. super.makeChartArea();
  2001. this.domainLabelGroup = makeSVGGroup(this.drawArea,
  2002. 'domain-label-group chart-label');
  2003. this.colGroups = makeSVGGroup(this.drawArea,
  2004. 'data-groups',
  2005. `translate(0, 20)`
  2006. );
  2007. }
  2008. prepareData(data=this.data) {
  2009. if(data.start && data.end && data.start > data.end) {
  2010. throw new Error('Start date cannot be greater than end date.');
  2011. }
  2012. if(!data.start) {
  2013. data.start = new Date();
  2014. data.start.setFullYear( data.start.getFullYear() - 1 );
  2015. }
  2016. if(!data.end) { data.end = new Date(); }
  2017. return data;
  2018. }
  2019. calc() {
  2020. let s = this.state;
  2021. s.start = this.data.start;
  2022. s.end = this.data.end;
  2023. s.firstWeekStart = setDayToSunday(clone(s.start));
  2024. s.noOfWeeks = getWeeksBetween(s.firstWeekStart, s.end);
  2025. s.distribution = calcDistribution(
  2026. Object.values(this.dataPoints), HEATMAP_DISTRIBUTION_SIZE);
  2027. }
  2028. update(data=this.data) {
  2029. this.data = this.prepareData(data);
  2030. this.draw();
  2031. this.bindTooltip();
  2032. }
  2033. render() {
  2034. this.renderAllWeeksAndStoreXValues(this.state.noOfWeeks);
  2035. }
  2036. renderAllWeeksAndStoreXValues(no_of_weeks) {
  2037. // renderAllWeeksAndStoreXValues
  2038. this.domainLabelGroup.textContent = '';
  2039. this.colGroups.textContent = '';
  2040. let currentWeekSunday = new Date(this.state.firstWeekStart);
  2041. this.weekCol = 0;
  2042. this.currentMonth = currentWeekSunday.getMonth();
  2043. this.months = [this.currentMonth + ''];
  2044. this.monthWeeks = {}, this.monthStartPoints = [];
  2045. this.monthWeeks[this.currentMonth] = 0;
  2046. for(var i = 0; i < no_of_weeks; i++) {
  2047. let colGroup, monthChange = 0;
  2048. let day = new Date(currentWeekSunday);
  2049. [colGroup, monthChange] = this.getWeekSquaresGroup(day, this.weekCol);
  2050. this.colGroups.appendChild(colGroup);
  2051. this.weekCol += 1 + parseInt(this.discreteDomains && monthChange);
  2052. this.monthWeeks[this.currentMonth]++;
  2053. if(monthChange) {
  2054. this.currentMonth = (this.currentMonth + 1) % NO_OF_YEAR_MONTHS;
  2055. this.months.push(this.currentMonth + '');
  2056. this.monthWeeks[this.currentMonth] = 1;
  2057. }
  2058. addDays(currentWeekSunday, NO_OF_DAYS_IN_WEEK);
  2059. }
  2060. this.renderMonthLabels();
  2061. }
  2062. getWeekSquaresGroup(currentDate, index) {
  2063. const step = 1;
  2064. let today = new Date();
  2065. const todayTime = today.getTime();
  2066. let monthChange = 0;
  2067. let weekColChange = 0;
  2068. let colGroup = makeSVGGroup(this.colGroups, 'data-group');
  2069. for(var y = 0, i = 0; i < NO_OF_DAYS_IN_WEEK; i += step, y += COL_SIZE) {
  2070. let dataValue = 0;
  2071. let colorIndex = 0;
  2072. let currentTimestamp = currentDate.getTime()/NO_OF_MILLIS;
  2073. let timestamp = Math.floor(currentTimestamp - (currentTimestamp % 86400)).toFixed(1);
  2074. if(this.dataPoints[timestamp]) {
  2075. dataValue = this.dataPoints[timestamp];
  2076. }
  2077. if(this.dataPoints[Math.round(timestamp)]) {
  2078. dataValue = this.dataPoints[Math.round(timestamp)];
  2079. }
  2080. if(dataValue) {
  2081. colorIndex = getMaxCheckpoint(dataValue, this.state.distribution);
  2082. }
  2083. let x = (index + weekColChange) * COL_SIZE;
  2084. let dataAttr = {
  2085. 'data-date': getDdMmYyyy(currentDate),
  2086. 'data-value': dataValue,
  2087. 'data-day': currentDate.getDay()
  2088. };
  2089. let heatSquare = makeHeatSquare('day', x, y, HEATMAP_SQUARE_SIZE,
  2090. this.colors[colorIndex], dataAttr);
  2091. colGroup.appendChild(heatSquare);
  2092. let nextDate = new Date(currentDate);
  2093. addDays(nextDate, 1);
  2094. if(nextDate.getTime() > todayTime) break;
  2095. if(nextDate.getMonth() - currentDate.getMonth()) {
  2096. monthChange = 1;
  2097. if(this.discreteDomains) {
  2098. weekColChange = 1;
  2099. }
  2100. this.monthStartPoints.push((index + weekColChange) * COL_SIZE);
  2101. }
  2102. currentDate = nextDate;
  2103. }
  2104. return [colGroup, monthChange];
  2105. }
  2106. renderMonthLabels() {
  2107. // this.first_month_label = 1;
  2108. // if (this.state.firstWeekStart.getDate() > 8) {
  2109. // this.first_month_label = 0;
  2110. // }
  2111. // this.last_month_label = 1;
  2112. // let first_month = this.months.shift();
  2113. // let first_month_start = this.monthStartPoints.shift();
  2114. // render first month if
  2115. // let last_month = this.months.pop();
  2116. // let last_month_start = this.monthStartPoints.pop();
  2117. // render last month if
  2118. this.months.shift();
  2119. this.monthStartPoints.shift();
  2120. this.months.pop();
  2121. this.monthStartPoints.pop();
  2122. this.monthStartPoints.map((start, i) => {
  2123. let month_name = getMonthName(this.months[i], true);
  2124. let text = makeText('y-value-text', start + COL_SIZE, HEATMAP_SQUARE_SIZE, month_name);
  2125. this.domainLabelGroup.appendChild(text);
  2126. });
  2127. }
  2128. bindTooltip() {
  2129. Array.prototype.slice.call(
  2130. document.querySelectorAll(".data-group .day")
  2131. ).map(el => {
  2132. el.addEventListener('mouseenter', (e) => {
  2133. let count = e.target.getAttribute('data-value');
  2134. let dateParts = e.target.getAttribute('data-date').split('-');
  2135. let month = getMonthName(parseInt(dateParts[1])-1, true);
  2136. let gOff = this.container.getBoundingClientRect(), pOff = e.target.getBoundingClientRect();
  2137. let width = parseInt(e.target.getAttribute('width'));
  2138. let x = pOff.left - gOff.left + (width+2)/2;
  2139. let y = pOff.top - gOff.top - (width+2)/2;
  2140. let value = count + ' ' + this.countLabel;
  2141. let name = ' on ' + month + ' ' + dateParts[0] + ', ' + dateParts[2];
  2142. this.tip.setValues(x, y, {name: name, value: value, valueFirst: 1}, []);
  2143. this.tip.showTip();
  2144. });
  2145. });
  2146. }
  2147. }
  2148. function dataPrep(data, type) {
  2149. data.labels = data.labels || [];
  2150. let datasetLength = data.labels.length;
  2151. // Datasets
  2152. let datasets = data.datasets;
  2153. let zeroArray = new Array(datasetLength).fill(0);
  2154. if(!datasets) {
  2155. // default
  2156. datasets = [{
  2157. values: zeroArray
  2158. }];
  2159. }
  2160. datasets.map(d=> {
  2161. // Set values
  2162. if(!d.values) {
  2163. d.values = zeroArray;
  2164. } else {
  2165. // Check for non values
  2166. let vals = d.values;
  2167. vals = vals.map(val => (!isNaN(val) ? val : 0));
  2168. // Trim or extend
  2169. if(vals.length > datasetLength) {
  2170. vals = vals.slice(0, datasetLength);
  2171. } else {
  2172. vals = fillArray(vals, datasetLength - vals.length, 0);
  2173. }
  2174. }
  2175. // Set labels
  2176. //
  2177. // Set type
  2178. if(!d.chartType ) {
  2179. if(!AXIS_DATASET_CHART_TYPES.includes(type)) type === DEFAULT_AXIS_CHART_TYPE;
  2180. d.chartType = type;
  2181. }
  2182. });
  2183. // Markers
  2184. // Regions
  2185. // data.yRegions = data.yRegions || [];
  2186. if(data.yRegions) {
  2187. data.yRegions.map(d => {
  2188. if(d.end < d.start) {
  2189. [d.start, d.end] = [d.end, d.start];
  2190. }
  2191. });
  2192. }
  2193. return data;
  2194. }
  2195. function zeroDataPrep(realData) {
  2196. let datasetLength = realData.labels.length;
  2197. let zeroArray = new Array(datasetLength).fill(0);
  2198. let zeroData = {
  2199. labels: realData.labels.slice(0, -1),
  2200. datasets: realData.datasets.map(d => {
  2201. return {
  2202. name: '',
  2203. values: zeroArray.slice(0, -1),
  2204. chartType: d.chartType
  2205. };
  2206. }),
  2207. };
  2208. if(realData.yMarkers) {
  2209. zeroData.yMarkers = [
  2210. {
  2211. value: 0,
  2212. label: ''
  2213. }
  2214. ];
  2215. }
  2216. if(realData.yRegions) {
  2217. zeroData.yRegions = [
  2218. {
  2219. start: 0,
  2220. end: 0,
  2221. label: ''
  2222. }
  2223. ];
  2224. }
  2225. return zeroData;
  2226. }
  2227. function getShortenedLabels(chartWidth, labels=[], isSeries=true) {
  2228. let allowedSpace = chartWidth / labels.length;
  2229. let allowedLetters = allowedSpace / DEFAULT_CHAR_WIDTH;
  2230. let calcLabels = labels.map((label, i) => {
  2231. label += "";
  2232. if(label.length > allowedLetters) {
  2233. if(!isSeries) {
  2234. if(allowedLetters-3 > 0) {
  2235. label = label.slice(0, allowedLetters-3) + " ...";
  2236. } else {
  2237. label = label.slice(0, allowedLetters) + '..';
  2238. }
  2239. } else {
  2240. let multiple = Math.ceil(label.length/allowedLetters);
  2241. if(i % multiple !== 0) {
  2242. label = "";
  2243. }
  2244. }
  2245. }
  2246. return label;
  2247. });
  2248. return calcLabels;
  2249. }
  2250. class AxisChart extends BaseChart {
  2251. constructor(parent, args) {
  2252. super(parent, args);
  2253. this.barOptions = args.barOptions || {};
  2254. this.lineOptions = args.lineOptions || {};
  2255. this.type = args.type || 'line';
  2256. this.init = 1;
  2257. this.setup();
  2258. }
  2259. configure(args) {
  2260. super.configure(args);
  2261. args.axisOptions = args.axisOptions || {};
  2262. args.tooltipOptions = args.tooltipOptions || {};
  2263. this.config.xAxisMode = args.axisOptions.xAxisMode || 'span';
  2264. this.config.yAxisMode = args.axisOptions.yAxisMode || 'span';
  2265. this.config.xIsSeries = args.axisOptions.xIsSeries || 0;
  2266. this.config.formatTooltipX = args.tooltipOptions.formatTooltipX;
  2267. this.config.formatTooltipY = args.tooltipOptions.formatTooltipY;
  2268. this.config.valuesOverPoints = args.valuesOverPoints;
  2269. }
  2270. setMargins() {
  2271. super.setMargins();
  2272. this.leftMargin = Y_AXIS_LEFT_MARGIN;
  2273. this.rightMargin = Y_AXIS_RIGHT_MARGIN;
  2274. }
  2275. prepareData(data=this.data) {
  2276. return dataPrep(data, this.type);
  2277. }
  2278. prepareFirstData(data=this.data) {
  2279. return zeroDataPrep(data);
  2280. }
  2281. calc(onlyWidthChange = false) {
  2282. this.calcXPositions();
  2283. if(onlyWidthChange) return;
  2284. this.calcYAxisParameters(this.getAllYValues(), this.type === 'line');
  2285. }
  2286. calcXPositions() {
  2287. let s = this.state;
  2288. let labels = this.data.labels;
  2289. s.datasetLength = labels.length;
  2290. s.unitWidth = this.width/(s.datasetLength);
  2291. // Default, as per bar, and mixed. Only line will be a special case
  2292. s.xOffset = s.unitWidth/2;
  2293. // // For a pure Line Chart
  2294. // s.unitWidth = this.width/(s.datasetLength - 1);
  2295. // s.xOffset = 0;
  2296. s.xAxis = {
  2297. labels: labels,
  2298. positions: labels.map((d, i) =>
  2299. floatTwo(s.xOffset + i * s.unitWidth)
  2300. )
  2301. };
  2302. }
  2303. calcYAxisParameters(dataValues, withMinimum = 'false') {
  2304. const yPts = calcChartIntervals(dataValues, withMinimum);
  2305. const scaleMultiplier = this.height / getValueRange(yPts);
  2306. const intervalHeight = getIntervalSize(yPts) * scaleMultiplier;
  2307. const zeroLine = this.height - (getZeroIndex(yPts) * intervalHeight);
  2308. this.state.yAxis = {
  2309. labels: yPts,
  2310. positions: yPts.map(d => zeroLine - d * scaleMultiplier),
  2311. scaleMultiplier: scaleMultiplier,
  2312. zeroLine: zeroLine,
  2313. };
  2314. // Dependent if above changes
  2315. this.calcDatasetPoints();
  2316. this.calcYExtremes();
  2317. this.calcYRegions();
  2318. }
  2319. calcDatasetPoints() {
  2320. let s = this.state;
  2321. let scaleAll = values => values.map(val => scale(val, s.yAxis));
  2322. s.datasets = this.data.datasets.map((d, i) => {
  2323. let values = d.values;
  2324. let cumulativeYs = d.cumulativeYs || [];
  2325. return {
  2326. name: d.name,
  2327. index: i,
  2328. chartType: d.chartType,
  2329. values: values,
  2330. yPositions: scaleAll(values),
  2331. cumulativeYs: cumulativeYs,
  2332. cumulativeYPos: scaleAll(cumulativeYs),
  2333. };
  2334. });
  2335. }
  2336. calcYExtremes() {
  2337. let s = this.state;
  2338. if(this.barOptions.stacked) {
  2339. s.yExtremes = s.datasets[s.datasets.length - 1].cumulativeYPos;
  2340. return;
  2341. }
  2342. s.yExtremes = new Array(s.datasetLength).fill(9999);
  2343. s.datasets.map(d => {
  2344. d.yPositions.map((pos, j) => {
  2345. if(pos < s.yExtremes[j]) {
  2346. s.yExtremes[j] = pos;
  2347. }
  2348. });
  2349. });
  2350. }
  2351. calcYRegions() {
  2352. let s = this.state;
  2353. if(this.data.yMarkers) {
  2354. this.state.yMarkers = this.data.yMarkers.map(d => {
  2355. d.position = scale(d.value, s.yAxis);
  2356. // if(!d.label.includes(':')) {
  2357. // d.label += ': ' + d.value;
  2358. // }
  2359. return d;
  2360. });
  2361. }
  2362. if(this.data.yRegions) {
  2363. this.state.yRegions = this.data.yRegions.map(d => {
  2364. d.startPos = scale(d.start, s.yAxis);
  2365. d.endPos = scale(d.end, s.yAxis);
  2366. return d;
  2367. });
  2368. }
  2369. }
  2370. getAllYValues() {
  2371. // TODO: yMarkers, regions, sums, every Y value ever
  2372. let key = 'values';
  2373. if(this.barOptions.stacked) {
  2374. key = 'cumulativeYs';
  2375. let cumulative = new Array(this.state.datasetLength).fill(0);
  2376. this.data.datasets.map((d, i) => {
  2377. let values = this.data.datasets[i].values;
  2378. d[key] = cumulative = cumulative.map((c, i) => c + values[i]);
  2379. });
  2380. }
  2381. let allValueLists = this.data.datasets.map(d => d[key]);
  2382. if(this.data.yMarkers) {
  2383. allValueLists.push(this.data.yMarkers.map(d => d.value));
  2384. }
  2385. if(this.data.yRegions) {
  2386. this.data.yRegions.map(d => {
  2387. allValueLists.push([d.end, d.start]);
  2388. });
  2389. }
  2390. return [].concat(...allValueLists);
  2391. }
  2392. setupComponents() {
  2393. let componentConfigs = [
  2394. [
  2395. 'yAxis',
  2396. {
  2397. mode: this.config.yAxisMode,
  2398. width: this.width,
  2399. // pos: 'right'
  2400. },
  2401. function() {
  2402. return this.state.yAxis;
  2403. }.bind(this)
  2404. ],
  2405. [
  2406. 'xAxis',
  2407. {
  2408. mode: this.config.xAxisMode,
  2409. height: this.height,
  2410. // pos: 'right'
  2411. },
  2412. function() {
  2413. let s = this.state;
  2414. s.xAxis.calcLabels = getShortenedLabels(this.width,
  2415. s.xAxis.labels, this.config.xIsSeries);
  2416. return s.xAxis;
  2417. }.bind(this)
  2418. ],
  2419. [
  2420. 'yRegions',
  2421. {
  2422. width: this.width,
  2423. pos: 'right'
  2424. },
  2425. function() {
  2426. return this.state.yRegions;
  2427. }.bind(this)
  2428. ],
  2429. ];
  2430. let barDatasets = this.state.datasets.filter(d => d.chartType === 'bar');
  2431. let lineDatasets = this.state.datasets.filter(d => d.chartType === 'line');
  2432. let barsConfigs = barDatasets.map(d => {
  2433. let index = d.index;
  2434. return [
  2435. 'barGraph' + '-' + d.index,
  2436. {
  2437. index: index,
  2438. color: this.colors[index],
  2439. stacked: this.barOptions.stacked,
  2440. // same for all datasets
  2441. valuesOverPoints: this.config.valuesOverPoints,
  2442. minHeight: this.height * MIN_BAR_PERCENT_HEIGHT,
  2443. },
  2444. function() {
  2445. let s = this.state;
  2446. let d = s.datasets[index];
  2447. let stacked = this.barOptions.stacked;
  2448. let spaceRatio = this.barOptions.spaceRatio || BAR_CHART_SPACE_RATIO;
  2449. let barsWidth = s.unitWidth * (1 - spaceRatio);
  2450. let barWidth = barsWidth/(stacked ? 1 : barDatasets.length);
  2451. let xPositions = s.xAxis.positions.map(x => x - barsWidth/2);
  2452. if(!stacked) {
  2453. xPositions = xPositions.map(p => p + barWidth * index);
  2454. }
  2455. let labels = new Array(s.datasetLength).fill('');
  2456. if(this.config.valuesOverPoints) {
  2457. if(stacked && d.index === s.datasets.length - 1) {
  2458. labels = d.cumulativeYs;
  2459. } else {
  2460. labels = d.values;
  2461. }
  2462. }
  2463. let offsets = new Array(s.datasetLength).fill(0);
  2464. if(stacked) {
  2465. offsets = d.yPositions.map((y, j) => y - d.cumulativeYPos[j]);
  2466. }
  2467. return {
  2468. xPositions: xPositions,
  2469. yPositions: d.yPositions,
  2470. offsets: offsets,
  2471. // values: d.values,
  2472. labels: labels,
  2473. zeroLine: s.yAxis.zeroLine,
  2474. barsWidth: barsWidth,
  2475. barWidth: barWidth,
  2476. };
  2477. }.bind(this)
  2478. ];
  2479. });
  2480. let lineConfigs = lineDatasets.map(d => {
  2481. let index = d.index;
  2482. return [
  2483. 'lineGraph' + '-' + d.index,
  2484. {
  2485. index: index,
  2486. color: this.colors[index],
  2487. svgDefs: this.svgDefs,
  2488. heatline: this.lineOptions.heatline,
  2489. regionFill: this.lineOptions.regionFill,
  2490. hideDots: this.lineOptions.hideDots,
  2491. hideLine: this.lineOptions.hideLine,
  2492. // same for all datasets
  2493. valuesOverPoints: this.config.valuesOverPoints,
  2494. },
  2495. function() {
  2496. let s = this.state;
  2497. let d = s.datasets[index];
  2498. return {
  2499. xPositions: s.xAxis.positions,
  2500. yPositions: d.yPositions,
  2501. values: d.values,
  2502. zeroLine: s.yAxis.zeroLine,
  2503. radius: this.lineOptions.dotSize || LINE_CHART_DOT_SIZE,
  2504. };
  2505. }.bind(this)
  2506. ];
  2507. });
  2508. let markerConfigs = [
  2509. [
  2510. 'yMarkers',
  2511. {
  2512. width: this.width,
  2513. pos: 'right'
  2514. },
  2515. function() {
  2516. return this.state.yMarkers;
  2517. }.bind(this)
  2518. ]
  2519. ];
  2520. componentConfigs = componentConfigs.concat(barsConfigs, lineConfigs, markerConfigs);
  2521. let optionals = ['yMarkers', 'yRegions'];
  2522. this.dataUnitComponents = [];
  2523. this.components = new Map(componentConfigs
  2524. .filter(args => !optionals.includes(args[0]) || this.state[args[0]])
  2525. .map(args => {
  2526. let component = getComponent(...args);
  2527. if(args[0].includes('lineGraph') || args[0].includes('barGraph')) {
  2528. this.dataUnitComponents.push(component);
  2529. }
  2530. return [args[0], component];
  2531. }));
  2532. }
  2533. bindTooltip() {
  2534. // NOTE: could be in tooltip itself, as it is a given functionality for its parent
  2535. this.container.addEventListener('mousemove', (e) => {
  2536. let o = getOffset(this.container);
  2537. let relX = e.pageX - o.left - this.leftMargin;
  2538. let relY = e.pageY - o.top - this.topMargin;
  2539. if(relY < this.height + this.topMargin * 2) {
  2540. this.mapTooltipXPosition(relX);
  2541. } else {
  2542. this.tip.hideTip();
  2543. }
  2544. });
  2545. }
  2546. mapTooltipXPosition(relX) {
  2547. let s = this.state;
  2548. if(!s.yExtremes) return;
  2549. let formatY = this.config.formatTooltipY;
  2550. let formatX = this.config.formatTooltipX;
  2551. let titles = s.xAxis.labels;
  2552. if(formatX && formatX(titles[0])) {
  2553. titles = titles.map(d=>formatX(d));
  2554. }
  2555. formatY = formatY && formatY(s.yAxis.labels[0]) ? formatY : 0;
  2556. for(var i=s.datasetLength - 1; i >= 0 ; i--) {
  2557. let xVal = s.xAxis.positions[i];
  2558. // let delta = i === 0 ? s.unitWidth : xVal - s.xAxis.positions[i-1];
  2559. if(relX > xVal - s.unitWidth/2) {
  2560. let x = xVal + this.leftMargin;
  2561. let y = s.yExtremes[i] + this.topMargin;
  2562. let values = this.data.datasets.map((set, j) => {
  2563. return {
  2564. title: set.name,
  2565. value: formatY ? formatY(set.values[i]) : set.values[i],
  2566. color: this.colors[j],
  2567. };
  2568. });
  2569. this.tip.setValues(x, y, {name: titles[i], value: ''}, values, i);
  2570. this.tip.showTip();
  2571. break;
  2572. }
  2573. }
  2574. }
  2575. renderLegend() {
  2576. // let s = this.data;
  2577. // this.statsWrapper.textContent = '';
  2578. // if(s.datasets.length > 1) {
  2579. // s.datasets.map((d, i) => {
  2580. // let stats = $.create('div', {
  2581. // className: 'stats',
  2582. // inside: this.statsWrapper
  2583. // });
  2584. // stats.innerHTML = `<span class="indicator">
  2585. // <i style="background: ${this.colors[i]}"></i>
  2586. // ${d.name}
  2587. // </span>`;
  2588. // });
  2589. // }
  2590. }
  2591. makeOverlay() {
  2592. if(this.init) {
  2593. this.init = 0;
  2594. return;
  2595. }
  2596. if(this.overlayGuides) {
  2597. this.overlayGuides.forEach(g => {
  2598. let o = g.overlay;
  2599. o.parentNode.removeChild(o);
  2600. });
  2601. }
  2602. this.overlayGuides = this.dataUnitComponents.map(c => {
  2603. return {
  2604. type: c.unitType,
  2605. overlay: undefined,
  2606. units: c.units,
  2607. };
  2608. });
  2609. if(this.state.currentIndex === undefined) {
  2610. this.state.currentIndex = this.state.datasetLength - 1;
  2611. }
  2612. // Render overlays
  2613. this.overlayGuides.map(d => {
  2614. let currentUnit = d.units[this.state.currentIndex];
  2615. d.overlay = makeOverlay[d.type](currentUnit);
  2616. this.drawArea.appendChild(d.overlay);
  2617. });
  2618. }
  2619. updateOverlayGuides() {
  2620. if(this.overlayGuides) {
  2621. this.overlayGuides.forEach(g => {
  2622. let o = g.overlay;
  2623. o.parentNode.removeChild(o);
  2624. });
  2625. }
  2626. }
  2627. bindOverlay() {
  2628. this.parent.addEventListener('data-select', () => {
  2629. this.updateOverlay();
  2630. });
  2631. }
  2632. bindUnits() {
  2633. this.dataUnitComponents.map(c => {
  2634. c.units.map(unit => {
  2635. unit.addEventListener('click', () => {
  2636. let index = unit.getAttribute('data-point-index');
  2637. this.setCurrentDataPoint(index);
  2638. });
  2639. });
  2640. });
  2641. // Note: Doesn't work as tooltip is absolutely positioned
  2642. this.tip.container.addEventListener('click', () => {
  2643. let index = this.tip.container.getAttribute('data-point-index');
  2644. this.setCurrentDataPoint(index);
  2645. });
  2646. }
  2647. updateOverlay() {
  2648. this.overlayGuides.map(d => {
  2649. let currentUnit = d.units[this.state.currentIndex];
  2650. updateOverlay[d.type](currentUnit, d.overlay);
  2651. });
  2652. }
  2653. onLeftArrow() {
  2654. this.setCurrentDataPoint(this.state.currentIndex - 1);
  2655. }
  2656. onRightArrow() {
  2657. this.setCurrentDataPoint(this.state.currentIndex + 1);
  2658. }
  2659. getDataPoint(index=this.state.currentIndex) {
  2660. let s = this.state;
  2661. let data_point = {
  2662. index: index,
  2663. label: s.xAxis.labels[index],
  2664. values: s.datasets.map(d => d.values[index])
  2665. };
  2666. return data_point;
  2667. }
  2668. setCurrentDataPoint(index) {
  2669. let s = this.state;
  2670. index = parseInt(index);
  2671. if(index < 0) index = 0;
  2672. if(index >= s.xAxis.labels.length) index = s.xAxis.labels.length - 1;
  2673. if(index === s.currentIndex) return;
  2674. s.currentIndex = index;
  2675. fire(this.parent, "data-select", this.getDataPoint());
  2676. }
  2677. // API
  2678. addDataPoint(label, datasetValues, index=this.state.datasetLength) {
  2679. super.addDataPoint(label, datasetValues, index);
  2680. this.data.labels.splice(index, 0, label);
  2681. this.data.datasets.map((d, i) => {
  2682. d.values.splice(index, 0, datasetValues[i]);
  2683. });
  2684. this.update(this.data);
  2685. }
  2686. removeDataPoint(index = this.state.datasetLength-1) {
  2687. if (this.data.labels.length <= 1) {
  2688. return;
  2689. }
  2690. super.removeDataPoint(index);
  2691. this.data.labels.splice(index, 1);
  2692. this.data.datasets.map(d => {
  2693. d.values.splice(index, 1);
  2694. });
  2695. this.update(this.data);
  2696. }
  2697. updateDataset(datasetValues, index=0) {
  2698. this.data.datasets[index].values = datasetValues;
  2699. this.update(this.data);
  2700. }
  2701. // addDataset(dataset, index) {}
  2702. // removeDataset(index = 0) {}
  2703. updateDatasets(datasets) {
  2704. this.data.datasets.map((d, i) => {
  2705. if(datasets[i]) {
  2706. d.values = datasets[i];
  2707. }
  2708. });
  2709. this.update(this.data);
  2710. }
  2711. // updateDataPoint(dataPoint, index = 0) {}
  2712. // addDataPoint(dataPoint, index = 0) {}
  2713. // removeDataPoint(index = 0) {}
  2714. }
  2715. const chartTypes = {
  2716. // multiaxis: MultiAxisChart,
  2717. percentage: PercentageChart,
  2718. heatmap: Heatmap,
  2719. pie: PieChart
  2720. };
  2721. function getChartByType(chartType = 'line', parent, options) {
  2722. if(chartType === 'line') {
  2723. options.type = 'line';
  2724. return new AxisChart(parent, options);
  2725. } else if (chartType === 'bar') {
  2726. options.type = 'bar';
  2727. return new AxisChart(parent, options);
  2728. } else if (chartType === 'axis-mixed') {
  2729. options.type = 'line';
  2730. return new AxisChart(parent, options);
  2731. }
  2732. if (!chartTypes[chartType]) {
  2733. console.error("Undefined chart type: " + chartType);
  2734. return;
  2735. }
  2736. return new chartTypes[chartType](parent, options);
  2737. }
  2738. class Chart {
  2739. constructor(parent, options) {
  2740. return getChartByType(options.type, parent, options);
  2741. }
  2742. }
  2743. export { Chart, PercentageChart, PieChart, Heatmap, AxisChart };