Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

3171 righe
75 KiB

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