Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

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