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.
 
 
 

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