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.
 
 
 

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