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.
 
 
 

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