25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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